hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
4f54cc8afed7facc39718b265c2bd927276ffddd
8,516
hpp
C++
thirdparty/libgenerator/inc/gml/quaternion.hpp
ppiecuch/godot
ff2098b324b814a0d1bd9d5722aa871fc5214fab
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
thirdparty/libgenerator/inc/gml/quaternion.hpp
ppiecuch/godot
ff2098b324b814a0d1bd9d5722aa871fc5214fab
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
thirdparty/libgenerator/inc/gml/quaternion.hpp
ppiecuch/godot
ff2098b324b814a0d1bd9d5722aa871fc5214fab
[ "MIT", "Apache-2.0", "CC-BY-4.0", "Unlicense" ]
null
null
null
// Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef UUID_B15DF4F752A94088BD3A77BC2D628831 #define UUID_B15DF4F752A94088BD3A77BC2D628831 #include <assert.h> #include <cmath> #include <iostream> #include <sstream> #include <string> #include "vec.hpp" namespace gml { /** * Complex number with scalar as real part and 3-vector as imaginary part. * Used for rotations and for storing orientation in 3d space. */ template <typename T> class quaternion { public: /// Type of the real part and a single component of the imaginary part. using value_type = T; /// Quaternion with zero real an imaginary parts. quaternion() : real{ 0 }, imag{ T{ 0 } } {} /// A quaternion with given real part and zero imaginary part explicit quaternion(const T &real) : real{ real }, imag{ T{ 0 } } {} /// A quaternion with zero real part and given imaginary part explicit quaternion(const vec<T, 3> &imag) : real{ 0 }, imag{ imag } {} /// A quaternion with given real and imaginary parts. quaternion(T real, const vec<T, 3> &imag) : real{ real }, imag{ imag } {} quaternion(const quaternion &) = default; quaternion(quaternion &&) = default; quaternion &operator=(const quaternion &) = default; quaternion &operator=(quaternion &&) = default; /// Component-wise addition quaternion<T> operator+(const quaternion<T> &q) const { return quaternion<T>{ real + q.real, imag + q.imag }; } /// Component-wise addition by interpreting v as imaginary part of a quaternion. quaternion<T> operator+(const vec<T, 3> &v) const { return quaternion<T>{ real, imag + v }; } /// Component-wise addition. quaternion<T> operator+(const T &a) const { return quaternion<T>{ real + a, imag }; } /// Components wise subtraction quaternion<T> operator-(const quaternion<T> &q) const { return quaternion<T>{ real - q.real, imag - q.imag }; } /// Components wise subtraction quaternion<T> operator-(const vec<T, 3> &v) const { return quaternion<T>{ real, imag - v }; } /// Components wise subtraction quaternion<T> operator-(const T &a) const { return quaternion<T>{ real - a, imag }; } /// Quaternion multiplication. /// Not done component wise. quaternion<T> operator*(const quaternion<T> &q) const { return quaternion<T>{ real * q.real - dot(imag, q.imag), real * q.imag + q.real * imag + cross(imag, q.imag) }; } /// Multiply quaternion and 3-vector (aka quaternion with zero real part). /// Note that vector v is not rotated by quaternion q by q*v but q*v*conj(q) /// (or use qtransform). quaternion<T> operator*(const vec<T, 3> &v) const { return quaternion<T>{ -dot(imag, v), real * v + cross(imag, v) }; } /// Multiply with scalar as it were the real part of a quaternion. quaternion<T> operator*(const T &a) const { return quaternion<T>{ real * a, imag * a }; } quaternion<T> operator/(const T &a) const { return quaternion<T>{ real / a, imag / a }; } quaternion<T> &operator+=(const quaternion<T> &q) { real += q.real; imag += q.imag; return *this; } quaternion<T> &operator-=(const quaternion<T> &q) { real -= q.real; imag -= q.imag; return *this; } quaternion<T> &operator*=(const quaternion<T> &q) { *this = *this * q; return *this; } /// Quaternions are equal if both parts are equal. bool operator==(const quaternion<T> &q) const { if (real != q.real) return false; if (imag != q.imag) return false; return true; } bool operator==(const T &a) const { if (real != a) return false; if (imag != vec<T, 3>{ 0 }) return false; return true; } bool operator==(const vec<T, 3> &v) const { if (real != T{ 0 }) return false; if (imag != v) return false; return true; } /// Quaternions are not equal if either of the parts are not equal. bool operator!=(const quaternion<T> &q) const { if (real != q.real) return true; if (imag != q.imag) return true; return false; } /// The real part of the quaternion T real; /// The imaginary part of the quaternion vec<T, 3> imag; }; /// Multiplies scalar (aka quaternion with zero imaginary part) and quaternion template <typename T> quaternion<T> operator*(const T &a, const quaternion<T> &q) { return quaternion<T>{ a * q.real, a * q.imag }; } /// Multiply quaternion and vector as it were the imaginary part of a quaternion. template <typename T> quaternion<T> operator*(const vec<T, 3> &v, const quaternion<T> &q) { return quaternion<T>{ -dot(v, q.imag), q.real * v + cross(v, q.imag) }; } /// Add quaternion and vector as it were the imaginary part of a quaternion. template <typename T> quaternion<T> operator+(vec<T, 3> v, const quaternion<T> &q) { return quaternion<T>{ q.real, v + q.imag }; } template <typename T> quaternion<T> operator+(const T &a, const quaternion<T> &q) { return quaternion<T>{ a + q.real, q.imag }; } template <typename T> quaternion<T> operator-(const quaternion<T> &q) { return quaternion<T>{ -q.real, -q.imag }; } template <typename T> quaternion<T> operator-(const T &a, const quaternion<T> &q) { return quaternion<T>{ a - q.real, -q.imag }; } template <typename T> quaternion<T> operator-(const vec<T, 3> &v, const quaternion<T> &q) { return quaternion<T>{ -q.real, v - q.imag }; } /// Write a quaternion to a stream inside brackets parts separated by a comma. template <typename T> std::ostream &operator<<(std::ostream &os, const quaternion<T> &q) { os << '(' << q.real << ',' << q.imag << ')'; return os; } /// Reads a quaternion from a stream. /// The parts must be inside brackets separated be a comma. template <typename T> std::istream &operator>>(std::istream &is, quaternion<T> &q) { char ch = 0; is >> ch >> q.real >> ch >> q.imag >> ch; return is; } /// Converts a quaternion to std::string. template <typename T> std::string to_string(const quaternion<T> &q) { std::stringstream ss{}; ss << q; return ss.str(); } /// Absolute value. template <typename T> T abs(const quaternion<T> &q) { using std::sqrt; return sqrt(q.real * q.real + dot(q.imag, q.imag)); } /// Makes the quaternion a unit quaternion. template <typename T> quaternion<T> normalize(const quaternion<T> &q) { return q / abs(q); } /// Quaternion conjugate (negates imaginary part) template <typename T> quaternion<T> conj(const quaternion<T> &q) { return quaternion<T>{ q.real, -q.imag }; } /// Generates rotation quaternion from axis and angle /// @param angle Rotation angle in radians /// @param axis Unit length rotation axis. template <typename T> quaternion<T> qrotate(const T &angle, const vec<T, 3> &axis) { using std::cos; using std::sin; const T a = angle / T{ 2 }; return quaternion<T>{ cos(a), sin(a) * axis }; } /// Generates rotation quaternion from Euler angles /// @param angle Euler angles in radians. template <typename T> quaternion<T> qrotate(const vec<T, 3> &angle) { using std::cos; using std::sin; const T a1 = angle[0] / T{ 2 }; const T a2 = angle[1] / T{ 2 }; const T a3 = angle[2] / T{ 2 }; const T sx = sin(a1); const T cx = cos(a1); const T sy = sin(a2); const T cy = cos(a2); const T sz = sin(a3); const T cz = cos(a3); return quaternion<T>{ cx * cy * cz + sx * sy * sz, vec<T, 3>{ cy * cz * sx - cx * sy * sz, cx * cz * sy + cy * sx * sz, -cz * sx * sy + cx * cy * sz } }; } /// Linear interpolation between quaternions. /// the resulting quaternion is NOT normalized template <typename T> quaternion<T> mix(const quaternion<T> &q1, const quaternion<T> &q2, const T &a) { return (T{ 1 } - a) * q1 + a * q2; } /// Rotates 3-vector v with quaternion q (computes q*v*conj(q)) /// Note q has to be a unit quaternion. template <typename T> vec<T, 3> transform(const quaternion<T> &q, const vec<T, 3> &v) { const vec<T, 3> temp = T{ 2 } * cross(q.imag, v); return v + q.real * temp + cross(q.imag, temp); } /// Inverse of quaternion. template <typename T> quaternion<T> inverse(const quaternion<T> &q) { return conj(q) / (q.real * q.real + dot(q.imag, q.imag)); } /// Static cast each component from T2 to T1. template <typename T1, typename T2> quaternion<T1> static_quaternion_cast(const quaternion<T2> &q) { return quaternion<T1>{ static_cast<T1>(q.real), static_vec_cast<T1>(q.imag) }; } typedef quaternion<float> quat; typedef quaternion<double> dquat; typedef quaternion<int> iquat; typedef quaternion<unsigned int> uquat; typedef quaternion<bool> bquat; } // namespace gml #endif
26.122699
81
0.660991
[ "vector", "transform", "3d" ]
4f554e06be55756b71c224f0dc445a543db26c33
2,794
hpp
C++
Runtime/Character/CAnimSource.hpp
Jcw87/urde
fb9ea9092ad00facfe957ece282a86c194e9cbda
[ "MIT" ]
267
2016-03-10T21:59:16.000Z
2021-03-28T18:21:03.000Z
Runtime/Character/CAnimSource.hpp
cobalt2727/metaforce
3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a
[ "MIT" ]
129
2016-03-12T10:17:32.000Z
2021-04-05T20:45:19.000Z
Runtime/Character/CAnimSource.hpp
cobalt2727/metaforce
3bb05c0ee5dd9b1b8eaa861fc49713aef62c844a
[ "MIT" ]
31
2016-03-20T00:20:11.000Z
2021-03-10T21:14:11.000Z
#pragma once #include <memory> #include <vector> #include "Runtime/CToken.hpp" #include "Runtime/RetroTypes.hpp" #include "Runtime/Character/CCharAnimTime.hpp" #include "Runtime/Character/CSegId.hpp" #include <zeus/CQuaternion.hpp> #include <zeus/CVector3f.hpp> namespace metaforce { class CAnimPOIData; class CBoolPOINode; class CInt32POINode; class CParticlePOINode; class CSegId; class CSegIdList; class CSegStatementSet; class CSoundPOINode; class IObjectStore; class RotationAndOffsetStorage { friend class CAnimSource; std::unique_ptr<float[]> x0_storage; u32 x8_frameCount; u32 xc_rotPerFrame; u32 x10_transPerFrame; std::unique_ptr<float[]> GetRotationsAndOffsets(const std::vector<zeus::CQuaternion>& rots, const std::vector<zeus::CVector3f>& offs, u32 frameCount); static void CopyRotationsAndOffsets(const std::vector<zeus::CQuaternion>& rots, const std::vector<zeus::CVector3f>& offs, u32 frameCount, float*); static u32 DataSizeInBytes(u32 rotPerFrame, u32 transPerFrame, u32 frameCount); public: struct CRotationAndOffsetVectors { std::vector<zeus::CQuaternion> x0_rotations; std::vector<zeus::CVector3f> x10_offsets; explicit CRotationAndOffsetVectors(CInputStream& in); }; u32 GetFrameSizeInBytes() const; RotationAndOffsetStorage(const CRotationAndOffsetVectors& vectors, u32 frameCount); }; class CAnimSource { friend class CAnimSourceInfo; CCharAnimTime x0_duration; CCharAnimTime x8_interval; u32 x10_frameCount; CSegId x1c_rootBone; std::vector<u8> x20_rotationChannels; std::vector<u8> x30_translationChannels; RotationAndOffsetStorage x40_data; CAssetId x54_evntId; TCachedToken<CAnimPOIData> x58_evntData; float x60_averageVelocity; void CalcAverageVelocity(); public: explicit CAnimSource(CInputStream& in, IObjectStore& store); void GetSegStatementSet(const CSegIdList& list, CSegStatementSet& set, const CCharAnimTime& time) const; const std::vector<CSoundPOINode>& GetSoundPOIStream() const; const std::vector<CParticlePOINode>& GetParticlePOIStream() const; const std::vector<CInt32POINode>& GetInt32POIStream() const; const std::vector<CBoolPOINode>& GetBoolPOIStream() const; const TCachedToken<CAnimPOIData>& GetPOIData() const { return x58_evntData; } float GetAverageVelocity() const { return x60_averageVelocity; } zeus::CQuaternion GetRotation(const CSegId& seg, const CCharAnimTime& time) const; zeus::CVector3f GetOffset(const CSegId& seg, const CCharAnimTime& time) const; bool HasOffset(const CSegId& seg) const; const CCharAnimTime& GetDuration() const { return x0_duration; } const CSegId& GetRootBoneId() const { return x1c_rootBone; } }; } // namespace metaforce
34.073171
108
0.759485
[ "vector" ]
4f5d7bf754e6912897489607b9cff3fedad33f0d
3,745
cpp
C++
2004/samples/database/ARXDBG/App/ArxDbgUiTdcOptions.cpp
kevinzhwl/ObjectARXMod
ef4c87db803a451c16213a7197470a3e9b40b1c6
[ "MIT" ]
1
2021-06-25T02:58:47.000Z
2021-06-25T02:58:47.000Z
2004/samples/database/ARXDBG/App/ArxDbgUiTdcOptions.cpp
kevinzhwl/ObjectARXMod
ef4c87db803a451c16213a7197470a3e9b40b1c6
[ "MIT" ]
null
null
null
2004/samples/database/ARXDBG/App/ArxDbgUiTdcOptions.cpp
kevinzhwl/ObjectARXMod
ef4c87db803a451c16213a7197470a3e9b40b1c6
[ "MIT" ]
3
2020-05-23T02:47:44.000Z
2020-10-27T01:26:53.000Z
// // (C) Copyright 1998-1999 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // // #include "stdafx.h" #include "ArxDbgUiTdcOptions.h" #include "ArxDbgOptions.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif /**************************************************************************** ** ** ArxDbgUiTdcOptions::ArxDbgUiTdcOptions ** ** **jma ** *************************************/ ArxDbgUiTdcOptions::ArxDbgUiTdcOptions(CWnd* pParent) : CAcUiTabChildDialog(pParent) { //{{AFX_DATA_INIT(ArxDbgUiTdcOptions) //}}AFX_DATA_INIT // get the initial values from our global object m_showDwgFilerMsgs = ArxDbgOptions::m_instance.m_showDwgFilerMessages; m_showWblockCloneDetails = ArxDbgOptions::m_instance.m_showWblockCloneDetails; m_showDeepCloneDetails = ArxDbgOptions::m_instance.m_showDeepCloneDetails; m_doDictInsertByHand = ArxDbgOptions::m_instance.m_doDictRecordInsertByHand; } /**************************************************************************** ** ** ArxDbgUiTdcOptions::DoDataExchange ** ** **jma ** *************************************/ void ArxDbgUiTdcOptions::DoDataExchange(CDataExchange* pDX) { CAcUiTabChildDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(ArxDbgUiTdcOptions) DDX_Check(pDX, ARXDBG_CB_DWG_FILER_MESSAGES, m_showDwgFilerMsgs); DDX_Check(pDX, ARXDBG_CB_DEEP_CLONE_DETAILS, m_showDeepCloneDetails); DDX_Check(pDX, ARXDBG_CB_WBLOCK_CLONE_DETAILS, m_showWblockCloneDetails); DDX_Check(pDX, ARXDBG_CB_USE_DICT_MERGESTYLE, m_doDictInsertByHand); //}}AFX_DATA_MAP } ///////////////////////////////////////////////////////////////////////////// // ArxDbgUiTdcOptions message map BEGIN_MESSAGE_MAP(ArxDbgUiTdcOptions, CAcUiTabChildDialog) //{{AFX_MSG_MAP(ArxDbgUiTdcOptions) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // ArxDbgUiTdcOptions message handlers /**************************************************************************** ** ** ArxDbgUiTdcOptions::OnMainDialogOK ** ** **jma ** *************************************/ void ArxDbgUiTdcOptions::OnMainDialogOK() { CAcUiTabChildDialog::OnMainDialogOK(); // set the final values on our global object. NOTE: can't just // put these directly in the DDX map since MFC doesn't map anything // to type "bool", only to type "BOOL" ArxDbgOptions::m_instance.m_showDwgFilerMessages = intToBool(m_showDwgFilerMsgs); ArxDbgOptions::m_instance.m_showWblockCloneDetails = intToBool(m_showWblockCloneDetails); ArxDbgOptions::m_instance.m_showDeepCloneDetails = intToBool(m_showDeepCloneDetails); ArxDbgOptions::m_instance.m_doDictRecordInsertByHand = intToBool(m_doDictInsertByHand); }
34.675926
93
0.651802
[ "object" ]
4f60e7b98129eb2d2857a29ff3ca88e56dab4533
22,291
cc
C++
server/s3_put_object_action_base.cc
mengwanguc/cortx-s3server
7628919ea6d663ab65298bccf3e1f792bd117da4
[ "Apache-2.0" ]
null
null
null
server/s3_put_object_action_base.cc
mengwanguc/cortx-s3server
7628919ea6d663ab65298bccf3e1f792bd117da4
[ "Apache-2.0" ]
5
2021-01-27T06:42:35.000Z
2021-02-01T07:56:57.000Z
server/s3_put_object_action_base.cc
mengwanguc/cortx-s3server
7628919ea6d663ab65298bccf3e1f792bd117da4
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2020 Seagate Technology LLC and/or its Affiliates * * 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 questions about this software or licensing, * please email opensource@seagate.com or cortx-questions@seagate.com. * */ #include <utility> #include "s3_factory.h" #include "s3_iem.h" #include "s3_log.h" #include "s3_m0_uint128_helper.h" #include "s3_motr_kvs_writer.h" #include "s3_motr_writer.h" #include "s3_option.h" #include "s3_probable_delete_record.h" #include "s3_put_object_action_base.h" #include "s3_uri_to_motr_oid.h" extern struct m0_uint128 global_probable_dead_object_list_index_oid; S3PutObjectActionBase::S3PutObjectActionBase( std::shared_ptr<S3RequestObject> s3_request_object, std::shared_ptr<S3BucketMetadataFactory> bucket_meta_factory, std::shared_ptr<S3ObjectMetadataFactory> object_meta_factory, std::shared_ptr<MotrAPI> motr_api, std::shared_ptr<S3MotrWriterFactory> motr_s3_factory, std::shared_ptr<S3MotrKVSWriterFactory> kv_writer_factory) : S3ObjectAction(std::move(s3_request_object), std::move(bucket_meta_factory), std::move(object_meta_factory)) { s3_log(S3_LOG_DEBUG, request_id, "Constructor\n"); if (motr_api) { s3_motr_api = std::move(motr_api); } else { s3_motr_api = std::make_shared<ConcreteMotrAPI>(); } if (motr_s3_factory) { motr_writer_factory = std::move(motr_s3_factory); } else { motr_writer_factory = std::make_shared<S3MotrWriterFactory>(); } if (kv_writer_factory) { mote_kv_writer_factory = std::move(kv_writer_factory); } else { mote_kv_writer_factory = std::make_shared<S3MotrKVSWriterFactory>(); } } void S3PutObjectActionBase::_set_layout_id(int layout_id) { assert(layout_id > 0 && layout_id < 15); this->layout_id = layout_id; motr_write_payload_size = S3Option::get_instance()->get_motr_write_payload_size(layout_id); assert(motr_write_payload_size > 0); motr_unit_size = S3MotrLayoutMap::get_instance()->get_unit_size_for_layout(layout_id); assert(motr_unit_size > 0); } void S3PutObjectActionBase::fetch_bucket_info_failed() { s3_log(S3_LOG_INFO, request_id, "Entering\n"); s3_put_action_state = S3PutObjectActionState::validationFailed; switch (bucket_metadata->get_state()) { case S3BucketMetadataState::missing: s3_log(S3_LOG_DEBUG, request_id, "Bucket not found"); set_s3_error("NoSuchBucket"); break; case S3BucketMetadataState::failed_to_launch: s3_log(S3_LOG_ERROR, request_id, "Bucket metadata load operation failed due to pre launch failure"); set_s3_error("ServiceUnavailable"); break; default: s3_log(S3_LOG_DEBUG, request_id, "Bucket metadata fetch failed"); set_s3_error("InternalError"); } send_response_to_s3_client(); s3_log(S3_LOG_DEBUG, "", "Exiting\n"); } void S3PutObjectActionBase::fetch_additional_bucket_info_failed() { s3_log(S3_LOG_INFO, stripped_request_id, "%s Entry\n", __func__); s3_put_action_state = S3PutObjectActionState::validationFailed; switch (additional_bucket_metadata->get_state()) { case S3BucketMetadataState::missing: s3_log(S3_LOG_ERROR, request_id, "Bucket: [%s] not found", additional_bucket_name.c_str()); set_s3_error("NoSuchBucket"); break; case S3BucketMetadataState::failed_to_launch: s3_log(S3_LOG_ERROR, request_id, "Bucket metadata load operation failed due to pre launch failure"); set_s3_error("ServiceUnavailable"); break; default: s3_log(S3_LOG_DEBUG, request_id, "Bucket metadata fetch failed"); set_s3_error("InternalError"); } send_response_to_s3_client(); s3_log(S3_LOG_DEBUG, "", "%s Exit", __func__); } void S3PutObjectActionBase::fetch_additional_object_info_failed() { s3_log(S3_LOG_INFO, stripped_request_id, "%s Entry\n", __func__); s3_put_action_state = S3PutObjectActionState::validationFailed; m0_uint128 additional_object_list_oid = additional_bucket_metadata->get_object_list_index_oid(); if (additional_object_list_oid.u_hi == 0ULL && additional_object_list_oid.u_lo == 0ULL) { s3_log(S3_LOG_ERROR, request_id, "Object not found\n"); set_s3_error("NoSuchKey"); } else { switch (additional_object_metadata->get_state()) { case S3ObjectMetadataState::missing: set_s3_error("NoSuchKey"); break; case S3ObjectMetadataState::failed_to_launch: s3_log(S3_LOG_ERROR, request_id, "Additional object metadata load operation failed due to pre " "launch " "failure\n"); set_s3_error("ServiceUnavailable"); break; default: s3_log(S3_LOG_DEBUG, request_id, "Additional object metadata fetch failed\n"); set_s3_error("InternalError"); } } send_response_to_s3_client(); s3_log(S3_LOG_DEBUG, "", "%s Exit", __func__); } void S3PutObjectActionBase::fetch_object_info_success() { s3_log(S3_LOG_INFO, request_id, "Entering\n"); const auto metadata_state = object_metadata->get_state(); if (metadata_state == S3ObjectMetadataState::missing) { s3_log(S3_LOG_DEBUG, request_id, "Destination object is absent"); } else if (metadata_state == S3ObjectMetadataState::present) { s3_log(S3_LOG_DEBUG, request_id, "Destination object already exists"); old_object_oid = object_metadata->get_oid(); old_oid_str = S3M0Uint128Helper::to_string(old_object_oid); old_layout_id = object_metadata->get_layout_id(); create_new_oid(old_object_oid); } else { s3_put_action_state = S3PutObjectActionState::validationFailed; if (metadata_state == S3ObjectMetadataState::failed_to_launch) { s3_log(S3_LOG_ERROR, request_id, "Object metadata load operation failed due to pre launch failure"); set_s3_error("ServiceUnavailable"); } else { s3_log(S3_LOG_ERROR, request_id, "Failed to look up metadata."); set_s3_error("InternalError"); } send_response_to_s3_client(); return; } // Check if additioanl metadata needs to be loaded, // case1: CopyObject API std::string source = request->get_headers_copysource(); if (!source.empty()) { // this is CopyObject API request get_source_bucket_and_object(source); fetch_additional_bucket_info(); } else { // No additional metadata load required. next(); } s3_log(S3_LOG_DEBUG, "", "Exiting\n"); } void S3PutObjectActionBase::fetch_object_info_failed() { // Proceed to to next task, object metadata doesnt exist, will create now struct m0_uint128 object_list_oid = bucket_metadata->get_object_list_index_oid(); if (!(object_list_oid.u_hi | object_list_oid.u_lo) || !(objects_version_list_oid.u_hi | objects_version_list_oid.u_lo)) { // Rare/unlikely: Motr KVS data corruption: // object_list_oid/objects_version_list_oid is null only when bucket // metadata is corrupted. // user has to delete and recreate the bucket again to make it work. s3_log(S3_LOG_ERROR, request_id, "Bucket(%s) metadata is corrupted.\n", request->get_bucket_name().c_str()); s3_iem(LOG_ERR, S3_IEM_METADATA_CORRUPTED, S3_IEM_METADATA_CORRUPTED_STR, S3_IEM_METADATA_CORRUPTED_JSON); s3_put_action_state = S3PutObjectActionState::validationFailed; set_s3_error("MetaDataCorruption"); send_response_to_s3_client(); return; } // Check if additioanl metadata needs to be loaded, // case1: CopyObject API std::string source = request->get_headers_copysource(); if (!source.empty()) { // this is CopyObject API request get_source_bucket_and_object(source); fetch_additional_bucket_info(); } else { // No additional metadata load required. next(); } } void S3PutObjectActionBase::create_object() { s3_log(S3_LOG_INFO, request_id, "Entering\n"); if (!tried_count) { motr_writer = motr_writer_factory->create_motr_writer(request); } _set_layout_id(S3MotrLayoutMap::get_instance()->get_layout_for_object_size( total_data_to_stream)); motr_writer->create_object( std::bind(&S3PutObjectActionBase::create_object_successful, this), std::bind(&S3PutObjectActionBase::create_object_failed, this), new_object_oid, layout_id); // for shutdown testcases, check FI and set shutdown signal S3_CHECK_FI_AND_SET_SHUTDOWN_SIGNAL( "put_object_action_create_object_shutdown_fail"); s3_log(S3_LOG_DEBUG, "", "Exiting\n"); } void S3PutObjectActionBase::create_object_successful() { s3_log(S3_LOG_INFO, request_id, "Entering\n"); s3_put_action_state = S3PutObjectActionState::newObjOidCreated; // New Object or overwrite, create new metadata and release old. new_object_metadata = object_metadata_factory->create_object_metadata_obj( request, bucket_metadata->get_object_list_index_oid()); new_object_metadata->set_objects_version_list_index_oid( bucket_metadata->get_objects_version_list_index_oid()); new_oid_str = S3M0Uint128Helper::to_string(new_object_oid); // Generate a version id for the new object. new_object_metadata->regenerate_version_id(); new_object_metadata->set_oid(motr_writer->get_oid()); new_object_metadata->set_layout_id(layout_id); add_object_oid_to_probable_dead_oid_list(); s3_log(S3_LOG_DEBUG, "", "Exiting\n"); } void S3PutObjectActionBase::create_object_failed() { s3_log(S3_LOG_INFO, request_id, "Entering\n"); if (check_shutdown_and_rollback()) { s3_log(S3_LOG_DEBUG, "", "Exiting\n"); return; } if (motr_writer->get_state() == S3MotrWiterOpState::exists) { collision_detected(); } else { s3_put_action_state = S3PutObjectActionState::newObjOidCreationFailed; if (motr_writer->get_state() == S3MotrWiterOpState::failed_to_launch) { s3_log(S3_LOG_ERROR, request_id, "Create object failed.\n"); set_s3_error("ServiceUnavailable"); } else { s3_log(S3_LOG_WARN, request_id, "Create object failed.\n"); // Any other error report failure. set_s3_error("InternalError"); } send_response_to_s3_client(); } s3_log(S3_LOG_DEBUG, "", "Exiting\n"); } void S3PutObjectActionBase::collision_detected() { if (check_shutdown_and_rollback()) { s3_log(S3_LOG_DEBUG, NULL, "Shutdown or rollback"); } else if (tried_count < MAX_COLLISION_RETRY_COUNT) { s3_log(S3_LOG_INFO, request_id, "Object ID collision happened for uri %s\n", request->get_object_uri().c_str()); // Handle Collision create_new_oid(new_object_oid); ++tried_count; if (tried_count > 5) { s3_log(S3_LOG_INFO, request_id, "Object ID collision happened %d times for uri %s\n", tried_count, request->get_object_uri().c_str()); } create_object(); } else { s3_log(S3_LOG_ERROR, request_id, "Exceeded maximum collision retry attempts." "Collision occurred %d times for uri %s\n", tried_count, request->get_object_uri().c_str()); s3_iem(LOG_ERR, S3_IEM_COLLISION_RES_FAIL, S3_IEM_COLLISION_RES_FAIL_STR, S3_IEM_COLLISION_RES_FAIL_JSON); s3_put_action_state = S3PutObjectActionState::newObjOidCreationFailed; set_s3_error("InternalError"); send_response_to_s3_client(); } s3_log(S3_LOG_DEBUG, NULL, "Exiting"); } void S3PutObjectActionBase::create_new_oid(struct m0_uint128 current_oid) { unsigned salt_counter = 0; std::string salted_uri; do { salted_uri = request->get_object_uri() + "uri_salt_" + std::to_string(salt_counter) + std::to_string(tried_count); S3UriToMotrOID(s3_motr_api, salted_uri.c_str(), request_id, &new_object_oid); ++salt_counter; } while ((new_object_oid.u_hi == current_oid.u_hi) && (new_object_oid.u_lo == current_oid.u_lo)); } void S3PutObjectActionBase::add_object_oid_to_probable_dead_oid_list() { s3_log(S3_LOG_INFO, request_id, "Entering\n"); std::map<std::string, std::string> probable_oid_list; assert(!new_oid_str.empty()); // store old object oid if (old_object_oid.u_hi | old_object_oid.u_lo) { assert(!old_oid_str.empty()); // key = oldoid + "-" + newoid std::string old_oid_rec_key = old_oid_str + '-' + new_oid_str; s3_log(S3_LOG_DEBUG, request_id, "Adding old_probable_del_rec with key [%s]\n", old_oid_rec_key.c_str()); old_probable_del_rec.reset(new S3ProbableDeleteRecord( old_oid_rec_key, {0, 0}, object_metadata->get_object_name(), old_object_oid, old_layout_id, bucket_metadata->get_object_list_index_oid(), bucket_metadata->get_objects_version_list_index_oid(), object_metadata->get_version_key_in_index(), false /* force_delete */)); probable_oid_list[old_oid_rec_key] = old_probable_del_rec->to_json(); } s3_log(S3_LOG_DEBUG, request_id, "Adding new_probable_del_rec with key [%s]\n", new_oid_str.c_str()); new_probable_del_rec.reset(new S3ProbableDeleteRecord( new_oid_str, old_object_oid, new_object_metadata->get_object_name(), new_object_oid, layout_id, bucket_metadata->get_object_list_index_oid(), bucket_metadata->get_objects_version_list_index_oid(), new_object_metadata->get_version_key_in_index(), false /* force_delete */)); // store new oid, key = newoid probable_oid_list[new_oid_str] = new_probable_del_rec->to_json(); if (!motr_kv_writer) { motr_kv_writer = mote_kv_writer_factory->create_motr_kvs_writer(request, s3_motr_api); } motr_kv_writer->put_keyval( global_probable_dead_object_list_index_oid, probable_oid_list, std::bind(&S3PutObjectActionBase::next, this), std::bind(&S3PutObjectActionBase:: add_object_oid_to_probable_dead_oid_list_failed, this)); s3_log(S3_LOG_DEBUG, "", "Exiting\n"); } void S3PutObjectActionBase::add_object_oid_to_probable_dead_oid_list_failed() { s3_log(S3_LOG_INFO, request_id, "Entering\n"); s3_put_action_state = S3PutObjectActionState::probableEntryRecordFailed; if (motr_kv_writer->get_state() == S3MotrKVSWriterOpState::failed_to_launch) { set_s3_error("ServiceUnavailable"); } else { set_s3_error("InternalError"); } // Clean up will be done after response. send_response_to_s3_client(); s3_log(S3_LOG_DEBUG, "", "Exiting\n"); } void S3PutObjectActionBase::startcleanup() { s3_log(S3_LOG_INFO, request_id, "Entering\n"); // TODO: Perf - all/some of below tasks can be done in parallel // Any of the following steps fail, backgrounddelete will be able to perform // cleanups. // Clear task list and setup cleanup task list clear_tasks(); cleanup_started = true; // Success conditions if (s3_put_action_state == S3PutObjectActionState::completed) { s3_log(S3_LOG_DEBUG, request_id, "Cleanup old Object\n"); if (old_object_oid.u_hi || old_object_oid.u_lo) { // mark old OID for deletion in overwrite case, this optimizes // backgrounddelete decisions. ACTION_TASK_ADD(S3PutObjectActionBase::mark_old_oid_for_deletion, this); } // remove new oid from probable delete list. ACTION_TASK_ADD(S3PutObjectActionBase::remove_new_oid_probable_record, this); if (old_object_oid.u_hi || old_object_oid.u_lo) { // Object overwrite case, old object exists, delete it. ACTION_TASK_ADD(S3PutObjectActionBase::delete_old_object, this); // If delete object is successful, attempt to delete old probable record } } else if (s3_put_action_state == S3PutObjectActionState::newObjOidCreated || s3_put_action_state == S3PutObjectActionState::writeFailed || s3_put_action_state == S3PutObjectActionState::md5ValidationFailed || s3_put_action_state == S3PutObjectActionState::metadataSaveFailed) { // PUT is assumed to be failed with a need to rollback s3_log(S3_LOG_DEBUG, request_id, "Cleanup new Object: s3_put_action_state[%d]\n", s3_put_action_state); // Mark new OID for deletion, this optimizes backgrounddelete decisionss. ACTION_TASK_ADD(S3PutObjectActionBase::mark_new_oid_for_deletion, this); if (old_object_oid.u_hi || old_object_oid.u_lo) { // remove old oid from probable delete list. ACTION_TASK_ADD(S3PutObjectActionBase::remove_old_oid_probable_record, this); } ACTION_TASK_ADD(S3PutObjectActionBase::delete_new_object, this); // If delete object is successful, attempt to delete new probable record } else { s3_log(S3_LOG_DEBUG, request_id, "No Cleanup required: s3_put_action_state[%d]\n", s3_put_action_state); assert(s3_put_action_state == S3PutObjectActionState::empty || s3_put_action_state == S3PutObjectActionState::validationFailed || s3_put_action_state == S3PutObjectActionState::probableEntryRecordFailed || s3_put_action_state == S3PutObjectActionState::newObjOidCreationFailed); // Nothing to undo } // Start running the cleanup task list start(); } void S3PutObjectActionBase::mark_new_oid_for_deletion() { s3_log(S3_LOG_INFO, request_id, "Entering\n"); assert(!new_oid_str.empty()); // update new oid, key = newoid, force_del = true new_probable_del_rec->set_force_delete(true); if (!motr_kv_writer) { motr_kv_writer = mote_kv_writer_factory->create_motr_kvs_writer(request, s3_motr_api); } motr_kv_writer->put_keyval(global_probable_dead_object_list_index_oid, new_oid_str, new_probable_del_rec->to_json(), std::bind(&S3PutObjectActionBase::next, this), std::bind(&S3PutObjectActionBase::next, this)); s3_log(S3_LOG_DEBUG, "", "Exiting\n"); } void S3PutObjectActionBase::mark_old_oid_for_deletion() { s3_log(S3_LOG_INFO, request_id, "Entering\n"); assert(!old_oid_str.empty()); assert(!new_oid_str.empty()); // key = oldoid + "-" + newoid std::string old_oid_rec_key = old_oid_str + '-' + new_oid_str; // update old oid, force_del = true old_probable_del_rec->set_force_delete(true); if (!motr_kv_writer) { motr_kv_writer = mote_kv_writer_factory->create_motr_kvs_writer(request, s3_motr_api); } motr_kv_writer->put_keyval(global_probable_dead_object_list_index_oid, old_oid_rec_key, old_probable_del_rec->to_json(), std::bind(&S3PutObjectActionBase::next, this), std::bind(&S3PutObjectActionBase::next, this)); s3_log(S3_LOG_DEBUG, "", "Exiting\n"); } void S3PutObjectActionBase::remove_old_oid_probable_record() { s3_log(S3_LOG_INFO, request_id, "Entering\n"); assert(!old_oid_str.empty()); assert(!new_oid_str.empty()); // key = oldoid + "-" + newoid std::string old_oid_rec_key = old_oid_str + '-' + new_oid_str; if (!motr_kv_writer) { motr_kv_writer = mote_kv_writer_factory->create_motr_kvs_writer(request, s3_motr_api); } motr_kv_writer->delete_keyval(global_probable_dead_object_list_index_oid, old_oid_rec_key, std::bind(&S3PutObjectActionBase::next, this), std::bind(&S3PutObjectActionBase::next, this)); s3_log(S3_LOG_DEBUG, "", "Exiting\n"); } void S3PutObjectActionBase::remove_new_oid_probable_record() { s3_log(S3_LOG_INFO, request_id, "Entering\n"); assert(!new_oid_str.empty()); if (!motr_kv_writer) { motr_kv_writer = mote_kv_writer_factory->create_motr_kvs_writer(request, s3_motr_api); } motr_kv_writer->delete_keyval(global_probable_dead_object_list_index_oid, new_oid_str, std::bind(&S3PutObjectActionBase::next, this), std::bind(&S3PutObjectActionBase::next, this)); s3_log(S3_LOG_DEBUG, "", "Exiting\n"); } void S3PutObjectActionBase::delete_old_object() { s3_log(S3_LOG_INFO, request_id, "Entering\n"); // If PUT is success, we delete old object if present assert(old_object_oid.u_hi != 0ULL || old_object_oid.u_lo != 0ULL); motr_writer->delete_object( std::bind(&S3PutObjectActionBase::remove_old_object_version_metadata, this), std::bind(&S3PutObjectActionBase::next, this), old_object_oid, old_layout_id, object_metadata->get_pvid()); s3_log(S3_LOG_DEBUG, "", "Exiting\n"); } void S3PutObjectActionBase::remove_old_object_version_metadata() { s3_log(S3_LOG_INFO, request_id, "Entering\n"); object_metadata->remove_version_metadata( std::bind(&S3PutObjectActionBase::remove_old_oid_probable_record, this), std::bind(&S3PutObjectActionBase::next, this)); s3_log(S3_LOG_DEBUG, "", "Exiting\n"); } void S3PutObjectActionBase::delete_new_object() { s3_log(S3_LOG_INFO, request_id, "Entering\n"); // If PUT failed, then clean new object. assert(s3_put_action_state != S3PutObjectActionState::completed); assert(new_object_oid.u_hi != 0ULL || new_object_oid.u_lo != 0ULL); motr_writer->delete_object( std::bind(&S3PutObjectActionBase::remove_new_oid_probable_record, this), std::bind(&S3PutObjectActionBase::next, this), new_object_oid, layout_id); s3_log(S3_LOG_DEBUG, "", "Exiting\n"); } void S3PutObjectActionBase::set_authorization_meta() { s3_log(S3_LOG_DEBUG, request_id, "Entering\n"); auth_client->set_acl_and_policy(bucket_metadata->get_encoded_bucket_acl(), bucket_metadata->get_policy_as_json()); next(); s3_log(S3_LOG_DEBUG, "", "Exiting\n"); }
38.366609
80
0.712844
[ "object" ]
4f6415f1933c1dec41e7e511a1695c5d6db91eee
57,467
cc
C++
crawl-ref/source/acquire.cc
b-crawl/bcrawl
a84e4a50629b5242d76e0166700d20ce8a6d1488
[ "CC0-1.0" ]
58
2018-12-10T05:09:50.000Z
2022-01-17T02:22:49.000Z
crawl-ref/source/acquire.cc
b-crawl/bcrawl
a84e4a50629b5242d76e0166700d20ce8a6d1488
[ "CC0-1.0" ]
4
2019-01-06T09:43:10.000Z
2021-09-02T13:37:15.000Z
crawl-ref/source/acquire.cc
b-crawl/bcrawl
a84e4a50629b5242d76e0166700d20ce8a6d1488
[ "CC0-1.0" ]
11
2019-01-05T20:14:48.000Z
2022-01-06T21:25:53.000Z
/** * @file * @brief Acquirement and Trog/Oka/Sif gifts. **/ #include "AppHdr.h" #include "acquire.h" #include <algorithm> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <queue> #include <set> #include "artefact.h" #include "art-enum.h" #include "defines.h" #include "describe.h" #include "dungeon.h" #include "food.h" #include "god-item.h" #include "god-passive.h" #include "invent.h" #include "item-name.h" #include "item-prop.h" #include "item-status-flag-type.h" #include "item-type-id-state-type.h" #include "items.h" #include "item-use.h" #include "libutil.h" #include "macro.h" #include "message.h" #include "output.h" #include "player.h" #include "prompt.h" #include "randbook.h" #include "random.h" #include "religion.h" #include "shopping.h" #include "skills.h" #include "spl-book.h" #include "spl-util.h" #include "state.h" #include "stringutil.h" #include "terrain.h" #include "unwind.h" #include "ui.h" static bool _acquiring_now = false; static equipment_type _acquirement_armour_slot(bool); static armour_type _acquirement_armour_for_slot(equipment_type, bool); static armour_type _acquirement_shield_type(); static armour_type _acquirement_body_armour(bool); static armour_type _useless_armour_type(); /** * Get a randomly rounded value for the player's specified skill, unmodified * by crosstraining, draining, etc. * * @param skill The skill in question; e.g. SK_ARMOUR. * @param mult A multiplier to the skill, for higher precision. * @return A rounded value of that skill; e.g. _skill_rdiv(SK_ARMOUR) * for a value of 10.1 will return 11 90% of the time & * 10 the remainder. */ static int _skill_rdiv(skill_type skill, int mult = 1) { const int scale = 256; return div_rand_round(you.skill(skill, mult * scale, true), scale); } /** * Choose a random subtype of armour to generate through acquirement/divine * gifts. * * Guaranteed to be wearable, in principle. * * @param divine Lowers the odds of high-tier body armours being chosen. * @return The armour_type of the armour to be generated. */ static int _acquirement_armour_subtype(bool divine, int & /*quantity*/) { const equipment_type slot_type = _acquirement_armour_slot(divine); return _acquirement_armour_for_slot(slot_type, divine); } /** * Take a set of weighted elements and a filter, and return a random element * from those elements that fulfills the filter condition. * * @param weights The elements to choose from. * @param filter An optional filter; if present, only elements for which * the filter returns true may be chosen. * @return A random element from the given list. */ template<class M> M filtered_vector_select(vector<pair<M, int>> weights, function<bool(M)> filter) { for (auto &weight : weights) { if (filter && !filter(weight.first)) weight.second = 0; else weight.second = max(weight.second, 0); // cleanup } M *chosen_elem = random_choose_weighted(weights); ASSERT(chosen_elem); return *chosen_elem; } /** * Choose a random slot to acquire armour for. * * For most races, even odds for all armour slots when acquiring, or 50-50 * split between body armour/aux armour when getting god gifts. * * Centaurs & nagas get a high extra chance for bardings, especially if they * haven't seen any yet. * * Guaranteed to be wearable, in principle. * * @param divine Whether the item is a god gift. * @return A random equipment slot; e.g. EQ_SHIELD, EQ_BODY_ARMOUR... */ static equipment_type _acquirement_armour_slot(bool divine) { if (you.species == SP_NAGA || you.species == SP_CENTAUR) { if (one_chance_in(you.seen_armour[ARM_BARDING] ? 4 : 2)) return EQ_BOOTS; } vector<pair<equipment_type, int>> weights = { { EQ_BODY_ARMOUR, divine ? 5 : 1 }, { EQ_SHIELD, 1 }, { EQ_CLOAK, 1 }, { EQ_HELMET, 1 }, { EQ_GLOVES, 1 }, { EQ_BOOTS, 1 }, }; return filtered_vector_select<equipment_type>(weights, [] (equipment_type etyp) { return you_can_wear(etyp); // evading template nonsense }); } /** * Choose a random subtype of armour that will fit in the given equipment slot, * to generate through acquirement/divine gifts. * * Guaranteed to be usable by the player & weighted weakly by their skills; * heavy investment in armour skill, relative to dodging & spellcasting, makes * heavier armours more likely to be generated. * * @param divine Whether the armour is a god gift. * @return The armour_type of the armour to be generated. */ static armour_type _acquirement_armour_for_slot(equipment_type slot_type, bool divine) { switch (slot_type) { case EQ_CLOAK: if (you_can_wear(EQ_CLOAK) == MB_TRUE) return random_choose(ARM_CLOAK, ARM_SCARF); return ARM_SCARF; case EQ_GLOVES: return ARM_GLOVES; case EQ_BOOTS: switch (you.species) { case SP_NAGA: case SP_CENTAUR: return ARM_BARDING; default: return ARM_BOOTS; } case EQ_HELMET: if (you_can_wear(EQ_HELMET) == MB_TRUE) return random_choose(ARM_HELMET, ARM_HAT); return ARM_HAT; case EQ_SHIELD: return _acquirement_shield_type(); case EQ_BODY_ARMOUR: return _acquirement_body_armour(divine); default: die("Unknown armour slot %d!", slot_type); } } /** * Choose a random type of shield to be generated via acquirement or god gifts. * * Weighted by Shields skill & the secret racial shield bonus. * * Ratios by shields skill & player size (B = buckler, S = shield, L = lg. sh.) * * Shields 0 5 10 15 20 * Large: {6B}/5S/4L ~{1B}/1S/1L ~{1B}/5S/7L ~2S/3L 1S/2L * Med.: 2B/1S 6B/4S/1L 2B/2S/1L 4B/8S/3L 1S/1L * Small: ~3B/1S ~5B/2S ~2B/1S ~3B/2S ~1B/1S * * XXX: possibly shield skill should count for more for non-med races? * * @return A potentially wearable type of shield. */ static armour_type _acquirement_shield_type() { const int scale = 256; vector<pair<armour_type, int>> weights = { { ARM_BUCKLER, player_shield_racial_factor() * 4 * scale - _skill_rdiv(SK_SHIELDS, scale) }, { ARM_SHIELD, 10 * scale }, { ARM_LARGE_SHIELD, 20 * scale - player_shield_racial_factor() * 4 * scale + _skill_rdiv(SK_SHIELDS, scale / 2) }, }; return filtered_vector_select<armour_type>(weights, [] (armour_type shtyp) { return check_armour_size(shtyp, you.body_size(PSIZE_TORSO, true)); }); } /** * Determine the weight (likelihood) to acquire a specific type of body armour. * * If divine is set, returns the base weight for the armour type. * Otherwise, if warrior is set, multiplies the base weight by the base ac^2. * Otherwise, uses the player's Armour skill to crudely guess how likely they * are to want the armour, based on its EVP. * * @param armour The type of armour in question. (E.g. ARM_ROBE.) * @param divine Whether the 'acquirement' is actually a god gift. * @param warrior Whether we think the player only cares about AC. * @return A weight for the armour. */ static int _body_acquirement_weight(armour_type armour, bool divine, bool warrior) { const int base_weight = armour_acq_weight(armour); if (divine) return base_weight; // gods don't care about your skills, apparently if (warrior) { const int ac = armour_prop(armour, PARM_AC); return base_weight * ac * ac; } // highest chance when armour skill = (displayed) evp - 3 const int evp = armour_prop(armour, PARM_EVASION); const int skill = min(27, _skill_rdiv(SK_ARMOUR) + 3); const int sk_diff = skill + evp / 10; const int inv_diff = max(1, 27 - sk_diff); // armour closest to ideal evp is 27^3 times as likely as the furthest away return base_weight * inv_diff * inv_diff * inv_diff; } /** * Choose a random type of body armour to be generated via acquirement or * god gifts. * * @param divine Whether the armour is a god gift. * @return A potentially wearable type of body armour.. */ static armour_type _acquirement_body_armour(bool divine) { // Using an arbitrary legacy formula, do we think the player doesn't care // about armour EVP? int light_pref = _skill_rdiv(SK_SPELLCASTING, 3); light_pref += _skill_rdiv(SK_DODGING); light_pref = random2(light_pref); const bool warrior = light_pref < random2(_skill_rdiv(SK_ARMOUR, 2)); vector<pair<armour_type, int>> weights; for (int i = ARM_FIRST_MUNDANE_BODY; i < NUM_ARMOURS; ++i) { const armour_type armour = (armour_type)i; if (get_armour_slot(armour) != EQ_BODY_ARMOUR) continue; if (!check_armour_size(armour, you.body_size(PSIZE_TORSO, true))) continue; const int weight = _body_acquirement_weight(armour, divine, warrior); if (weight) { const pair<armour_type, int> weight_pair = { armour, weight }; weights.push_back(weight_pair); } } const armour_type* armour_ptr = random_choose_weighted(weights); ASSERT(armour_ptr); return *armour_ptr; } /** * Choose a random type of armour that the player cannot wear, for Xom to spite * the player with. * * @return A random useless armour_type. */ static armour_type _useless_armour_type() { vector<pair<equipment_type, int>> weights = { { EQ_BODY_ARMOUR, 1 }, { EQ_SHIELD, 1 }, { EQ_CLOAK, 1 }, { EQ_HELMET, 1 }, { EQ_GLOVES, 1 }, { EQ_BOOTS, 1 }, }; // everyone has some kind of boot-slot item they can't wear, regardless // of what you_can_wear() claims for (auto &weight : weights) if (you_can_wear(weight.first) == MB_TRUE && weight.first != EQ_BOOTS) weight.second = 0; const equipment_type* slot_ptr = random_choose_weighted(weights); const equipment_type slot = slot_ptr ? *slot_ptr : EQ_BOOTS; switch (slot) { case EQ_BOOTS: // Boots-wearers get bardings; everyone else gets boots. if (you_can_wear(EQ_BOOTS) == MB_TRUE) return ARM_BARDING; return ARM_BOOTS; case EQ_GLOVES: return ARM_GLOVES; case EQ_HELMET: if (you_can_wear(EQ_HELMET)) return ARM_HELMET; return random_choose(ARM_HELMET, ARM_HAT); case EQ_CLOAK: return ARM_CLOAK; case EQ_SHIELD: { vector<pair<armour_type, int>> shield_weights = { { ARM_BUCKLER, 1 }, { ARM_SHIELD, 1 }, { ARM_LARGE_SHIELD, 1 }, }; return filtered_vector_select<armour_type>(shield_weights, [] (armour_type shtyp) { return !check_armour_size(shtyp, you.body_size(PSIZE_TORSO, true)); }); } case EQ_BODY_ARMOUR: // only the rarest & most precious of unwearable armours for Xom if (you_can_wear(EQ_BODY_ARMOUR)) return ARM_CRYSTAL_PLATE_ARMOUR; // arbitrary selection of [unwearable] dragon armours return random_choose(ARM_FIRE_DRAGON_ARMOUR, ARM_ICE_DRAGON_ARMOUR, ARM_PEARL_DRAGON_ARMOUR, ARM_GOLD_DRAGON_ARMOUR, ARM_SHADOW_DRAGON_ARMOUR, ARM_STORM_DRAGON_ARMOUR); default: die("Unknown slot type selected for Xom bad-armour-acq!"); } } static armour_type _pick_unseen_armour() { // Consider shields uninteresting always, since unlike with other slots // players might well prefer an empty slot to wearing one. We don't // want to try to guess at this by looking at their weapon's handedness // because this would encourage switching weapons or putting on a // shield right before reading acquirement in some cases. --elliptic // This affects only the "unfilled slot" special-case, not regular // acquirement which can always produce (wearable) shields. static const equipment_type armour_slots[] = { EQ_CLOAK, EQ_HELMET, EQ_GLOVES, EQ_BOOTS }; armour_type picked = NUM_ARMOURS; int count = 0; for (auto &slot : armour_slots) { if (!you_can_wear(slot)) continue; const armour_type sub_type = _acquirement_armour_for_slot(slot, false); ASSERT(sub_type != NUM_ARMOURS); if (!you.seen_armour[sub_type] && one_chance_in(++count)) picked = sub_type; } return picked; } static int _acquirement_food_subtype(bool /*divine*/, int& quantity) { int type_wanted; // Food is a little less predictable now. - bwr if (you.species == SP_GHOUL) type_wanted = FOOD_CHUNK; else if (you.species == SP_VAMPIRE) { // Vampires really don't want any OBJ_FOOD but OBJ_CORPSES // but it's easier to just give them a potion of blood // class type is set elsewhere type_wanted = POT_BLOOD; } else type_wanted = FOOD_RATION; quantity = 6 + random2(7); // giving more of the lower food value items if (type_wanted == FOOD_CHUNK) quantity += 2 + random2avg(10, 2); else if (type_wanted == POT_BLOOD) quantity = 8 + random2(5); return type_wanted; } /** * Randomly choose a class of weapons (those using a specific weapon skill) * for acquirement to give the player. Weight toward the player's skills. * * @param divine Whether this is a god gift, which are less strongly * tailored to the player's skills. * @return An appropriate weapon skill; e.g. SK_LONG_BLADES. */ static skill_type _acquirement_weapon_skill(bool divine) { // reservoir sample. int count = 0; skill_type skill = SK_FIGHTING; for (skill_type sk = SK_FIRST_WEAPON; sk <= SK_LAST_WEAPON; ++sk) { // Adding a small constant allows for the occasional // weapon in an untrained skill. int weight = _skill_rdiv(sk) + 1; // Exaggerate the weighting if it's a scroll acquirement. if (!divine) weight = (weight + 1) * (weight + 2); count += weight; if (x_chance_in_y(weight, count)) skill = sk; } return skill; } static int _acquirement_weapon_subtype(bool divine, int & /*quantity*/) { const skill_type skill = _acquirement_weapon_skill(divine); int best_sk = 0; for (int i = SK_FIRST_WEAPON; i <= SK_LAST_WEAPON; i++) best_sk = max(best_sk, _skill_rdiv((skill_type)i)); best_sk = max(best_sk, _skill_rdiv(SK_UNARMED_COMBAT)); // Now choose a subtype which uses that skill. int result = OBJ_RANDOM; int count = 0; item_def item_considered; item_considered.base_type = OBJ_WEAPONS; // Let's guess the percentage of shield use the player did, this is // based on empirical data where pure-shield MDs get skills like 17 sh // 25 m&f and pure-shield Spriggans 7 sh 18 m&f. Pretend formicid // shield skill is 0 so they always weight towards 2H. const int shield_sk = you.species == SP_FORMICID ? 0 : _skill_rdiv(SK_SHIELDS) * species_apt_factor(SK_SHIELDS); const int want_shield = min(2 * shield_sk, best_sk) + 10; const int dont_shield = max(best_sk - shield_sk, 0) + 10; // At XL 10, weapons of the handedness you want get weight *2, those of // opposite handedness 1/2, assuming your shields usage is respectively // 0% or 100% in the above formula. At skill 25 that's *3.5 . for (int i = 0; i < NUM_WEAPONS; ++i) { const int wskill = item_attack_skill(OBJ_WEAPONS, i); if (wskill != skill) continue; item_considered.sub_type = i; int acqweight = property(item_considered, PWPN_ACQ_WEIGHT) * 100; if (!acqweight) continue; const bool two_handed = you.hands_reqd(item_considered) == HANDS_TWO; if (two_handed && you.get_mutation_level(MUT_MISSING_HAND)) continue; // For non-Trog/Okawaru acquirements, give a boost to high-end items. if (!divine && !is_range_weapon(item_considered)) { if (acqweight < 500) acqweight = 500; // Quick blades get unproportionately hit by damage weighting. if (i == WPN_QUICK_BLADE) acqweight = acqweight * 25 / 9; int damage = property(item_considered, PWPN_DAMAGE); if (!two_handed) damage = damage * 3 / 2; damage *= damage * damage; acqweight *= damage / property(item_considered, PWPN_SPEED); } if (two_handed) acqweight = acqweight * dont_shield / want_shield; else acqweight = acqweight * want_shield / dont_shield; if (!you.seen_weapon[i]) acqweight *= 5; // strong emphasis on type variety, brands go only second // reservoir sampling if (x_chance_in_y(acqweight, count += acqweight)) result = i; } return result; } static int _acquirement_missile_subtype(bool /*divine*/, int & /*quantity*/) { int count = 0; int skill = SK_THROWING; for (int i = SK_SLINGS; i <= SK_THROWING; i++) { const int sk = _skill_rdiv((skill_type)i); count += sk; if (x_chance_in_y(sk, count)) skill = i; } missile_type result = MI_TOMAHAWK; switch (skill) { case SK_SLINGS: result = MI_SLING_BULLET; break; case SK_BOWS: result = MI_ARROW; break; case SK_CROSSBOWS: result = MI_BOLT; break; case SK_THROWING: { // Choose from among all usable missile types. vector<pair<missile_type, int> > missile_weights; missile_weights.emplace_back(MI_TOMAHAWK, 50); if (you.body_size() >= SIZE_MEDIUM) missile_weights.emplace_back(MI_JAVELIN, 100); if (you.can_throw_large_rocks()) missile_weights.emplace_back(MI_LARGE_ROCK, 100); result = *random_choose_weighted(missile_weights); } break; default: break; } return result; } static int _acquirement_jewellery_subtype(bool /*divine*/, int & /*quantity*/) { int result = 0; // Rings are (number of usable rings) times as common as amulets. // XXX: unify this with the actual check for ring slots const int ring_num = (you.species == SP_OCTOPODE ? 8 : 2) - (you.get_mutation_level(MUT_MISSING_HAND) ? 1 : 0); // Try ten times to give something the player hasn't seen. for (int i = 0; i < 10; i++) { result = one_chance_in(ring_num + 1) ? get_random_amulet_type() : get_random_ring_type(); // If we haven't seen this yet, we're done. if (!get_ident_type(OBJ_JEWELLERY, result)) break; } return result; } static int _acquirement_staff_subtype(bool /*divine*/, int & /*quantity*/) { // Try to pick an enhancer staff matching the player's best skill. skill_type best_spell_skill = best_skill(SK_FIRST_MAGIC_SCHOOL, SK_LAST_MAGIC); bool found_enhancer = false; int result = 0; do { result = random2(NUM_STAVES); } while (item_type_removed(OBJ_STAVES, result)); switch (best_spell_skill) { #define TRY_GIVE(x) { if (!you.type_ids[OBJ_STAVES][x]) \ {result = x; found_enhancer = true;} } case SK_FIRE_MAGIC: TRY_GIVE(STAFF_FIRE); break; case SK_ICE_MAGIC: TRY_GIVE(STAFF_COLD); break; case SK_AIR_MAGIC: TRY_GIVE(STAFF_AIR); break; case SK_EARTH_MAGIC: TRY_GIVE(STAFF_EARTH); break; case SK_POISON_MAGIC: TRY_GIVE(STAFF_POISON); break; case SK_NECROMANCY: TRY_GIVE(STAFF_DEATH); break; case SK_CONJURATIONS: TRY_GIVE(STAFF_CONJURATION); break; case SK_SUMMONINGS: TRY_GIVE(STAFF_SUMMONING); break; #undef TRY_GIVE default: break; } if (one_chance_in(found_enhancer ? 2 : 3)) return result; // Otherwise pick a non-enhancer staff. switch (random2(2)) { case 0: result = STAFF_WIZARDRY; break; case 1: result = STAFF_POWER; break; } return result; } /** * Return a miscellaneous evokable item for acquirement. * @return The item type chosen. */ static int _acquirement_misc_subtype(bool /*divine*/, int & /*quantity*/) { const bool NO_LOVE = you.get_mutation_level(MUT_NO_LOVE); const vector<pair<int, int> > choices = { // These have charges, so give them a constant weight. {MISC_BOX_OF_BEASTS, (NO_LOVE ? 0 : 8)}, {MISC_PHANTOM_MIRROR, (NO_LOVE ? 0 : 6)}, // The player never needs more than one. {MISC_SACK_OF_SPIDERS, ((NO_LOVE || you.seen_misc[MISC_SACK_OF_SPIDERS]) ? 0 : 9)}, {MISC_PHIAL_OF_FLOODS, ((NO_LOVE || you.seen_misc[MISC_PHIAL_OF_FLOODS]) ? 0 : 17)}, {MISC_LIGHTNING_ROD, (you.seen_misc[MISC_LIGHTNING_ROD] ? 0 : 17)}, {MISC_LAMP_OF_FIRE, (you.seen_misc[MISC_LAMP_OF_FIRE] ? 0 : 17)}, {MISC_FAN_OF_GALES, (you.seen_misc[MISC_FAN_OF_GALES] ? 0 : 9)}, }; const int * const choice = random_choose_weighted(choices); // Could be nullptr if all the weights were 0. return choice ? *choice : MISC_LIGHTNING_ROD; } /** * Choose a random type of wand to be generated via acquirement or god gifts. * * Heavily weighted toward more useful wands and wands the player hasn't yet * seen. * * @return A random wand type. */ static int _acquirement_wand_subtype(bool /*divine*/, int & /*quantity*/) { // basic total: 120 vector<pair<wand_type, int>> weights = { { WAND_SCATTERSHOT, 25 }, { WAND_CLOUDS, 25 }, { WAND_ACID, 25 }, { WAND_ICEBLAST, 20 }, { WAND_ENSLAVEMENT, you.get_mutation_level(MUT_NO_LOVE) ? 0 : 10 }, { WAND_PARALYSIS, 10 }, { WAND_DIGGING, 10 }, { WAND_DISINTEGRATION, 5 }, { WAND_POLYMORPH, 5 }, { WAND_RANDOM_EFFECTS, 2 }, { WAND_FLAME, 1 }, }; // Unknown wands get a huge weight bonus. for (auto &weight : weights) if (!get_ident_type(OBJ_WANDS, weight.first)) weight.second *= 2; const wand_type* wand = random_choose_weighted(weights); ASSERT(wand); return *wand; } static int _acquirement_book_subtype(bool /*divine*/, int & /*quantity*/) { return BOOK_MINOR_MAGIC; //this gets overwritten later, but needs to be a sane value //or asserts will get set off } typedef int (*acquirement_subtype_finder)(bool divine, int &quantity); static const acquirement_subtype_finder _subtype_finders[] = { _acquirement_weapon_subtype, _acquirement_missile_subtype, _acquirement_armour_subtype, _acquirement_wand_subtype, _acquirement_food_subtype, 0, // no scrolls _acquirement_jewellery_subtype, _acquirement_food_subtype, // potion acquirement = food for vampires _acquirement_book_subtype, _acquirement_staff_subtype, 0, // no, you can't acquire the orb _acquirement_misc_subtype, 0, // no corpses 0, // gold handled elsewhere, and doesn't have subtypes anyway #if TAG_MAJOR_VERSION == 34 0, // no rods #endif 0, // no runes either }; static int _find_acquirement_subtype(object_class_type &class_wanted, int &quantity, bool divine, int agent) { COMPILE_CHECK(ARRAYSZ(_subtype_finders) == NUM_OBJECT_CLASSES); ASSERT(class_wanted != OBJ_RANDOM); int type_wanted = OBJ_RANDOM; int useless_count = 0; do { // Wands and misc have a common acquirement class. if (class_wanted == OBJ_MISCELLANY) class_wanted = random_choose(OBJ_WANDS, OBJ_MISCELLANY); // Vampires acquire blood, not food. if (class_wanted == OBJ_FOOD && you.species == SP_VAMPIRE) class_wanted = OBJ_POTIONS; if (_subtype_finders[class_wanted]) type_wanted = (*_subtype_finders[class_wanted])(divine, quantity); item_def dummy; dummy.base_type = class_wanted; dummy.sub_type = type_wanted; dummy.plus = 1; // empty wands would be useless dummy.flags |= ISFLAG_IDENT_MASK; if (!is_useless_item(dummy, false) && !god_hates_item(dummy) && (agent >= NUM_GODS || god_likes_item_type(dummy, (god_type)agent))) { break; } } while (useless_count++ < 200); return type_wanted; } // The weight of a spell takes into account its disciplines' skill levels // and the spell difficulty. static int _spell_weight(spell_type spell) { ASSERT(spell != SPELL_NO_SPELL); int weight = 0; spschools_type disciplines = get_spell_disciplines(spell); int count = 0; for (const auto disc : spschools_type::range()) { if (disciplines & disc) { weight += _skill_rdiv(spell_type2skill(disc)); count++; } } ASSERT(count > 0); // Particularly difficult spells _reduce_ the overall weight. int leveldiff = 5 - spell_difficulty(spell); return max(0, 2 * weight/count + leveldiff); } // When randomly picking a book for acquirement, use the sum of the // weights of all unknown spells in the book. static int _book_weight(book_type book) { ASSERT_RANGE(book, 0, MAX_FIXED_BOOK + 1); int total_weight = 0; for (spell_type stype : spellbook_template(book)) { // Skip over spells already in library. if (you.spell_library[stype]) continue; if (god_hates_spell(stype, you.religion)) continue; total_weight += _spell_weight(stype); } return total_weight; } static bool _is_magic_skill(int skill) { return skill >= SK_SPELLCASTING && skill < SK_INVOCATIONS; } static bool _skill_useless_with_god(int skill) { switch (you.religion) { case GOD_TROG: return _is_magic_skill(skill) || skill == SK_INVOCATIONS; case GOD_ZIN: case GOD_SHINING_ONE: case GOD_ELYVILON: return skill == SK_NECROMANCY; case GOD_XOM: case GOD_RU: case GOD_KIKUBAAQUDGHA: case GOD_VEHUMET: case GOD_ASHENZARI: case GOD_JIYVA: case GOD_GOZAG: case GOD_NO_GOD: return skill == SK_INVOCATIONS; default: return false; } } /** * Randomly decide whether the player should get a manual from a given instance * of book acquirement. * * @param agent The source of the acquirement (e.g. a god) * @return Whether the player should get a manual from this book * acquirement. */ static bool _should_acquire_manual(int agent) { // Manuals are too useful for Xom, and useless when gifted from Sif Muna. if (agent == GOD_XOM || agent == GOD_SIF_MUNA) return false; int magic_weights = 0; int other_weights = 0; for (skill_type sk = SK_FIRST_SKILL; sk < NUM_SKILLS; ++sk) { const int weight = _skill_rdiv(sk); if (_is_magic_skill(sk)) magic_weights += weight; else other_weights += weight; } if (you_worship(GOD_TROG)) magic_weights = 0; // If someone has 25% or more magic skills, never give manuals. // Otherwise, count magic skills double to bias against manuals // for magic users. return magic_weights * 3 < other_weights && x_chance_in_y(other_weights, 2*magic_weights + other_weights); } /** * Turn a given book into an acquirement-quality manual. * * @param book[out] The book to be turned into a manual. * @return Whether a manual was successfully created. */ static bool _acquire_manual(item_def &book) { int weights[NUM_SKILLS] = { 0 }; int total_weights = 0; for (skill_type sk = SK_FIRST_SKILL; sk < NUM_SKILLS; ++sk) { const int skl = _skill_rdiv(sk); if (skl == 27 || is_useless_skill(sk)) continue; int w = (skl < 12) ? skl + 3 : max(0, 25 - skl); // Greatly reduce the chances of getting a manual for a skill // you couldn't use unless you switched your religion. if (_skill_useless_with_god(sk)) w /= 2; weights[sk] = w; total_weights += w; } // Are we too skilled to get any manuals? if (total_weights == 0) return false; book.sub_type = BOOK_MANUAL; book.skill = static_cast<skill_type>( choose_random_weighted(weights, end(weights))); // Set number of bonus skill points. book.skill_points = random_range(2000, 3000); // Identify. set_ident_type(book, true); set_ident_flags(book, ISFLAG_IDENT_MASK); return true; } static bool _do_book_acquirement(item_def &book, int agent) { // items() shouldn't make book a randart for acquirement items. ASSERT(!is_random_artefact(book)); if (_should_acquire_manual(agent)) return _acquire_manual(book); const int choice = random_choose_weighted( 30, BOOK_RANDART_THEME, agent == GOD_SIF_MUNA ? 10 : 40, NUM_BOOKS, // normal books 1, BOOK_RANDART_LEVEL); switch (choice) { default: case NUM_BOOKS: { int total_weights = 0; // Pick a random spellbook according to unknown spells contained. int weights[MAX_FIXED_BOOK + 1] = { 0 }; for (int bk = 0; bk <= MAX_FIXED_BOOK; bk++) { const auto bkt = static_cast<book_type>(bk); if (is_rare_book(bkt) && agent == GOD_SIF_MUNA || item_type_removed(OBJ_BOOKS, bk)) { continue; } weights[bk] = _book_weight(bkt); total_weights += weights[bk]; } if (total_weights > 0) { book.sub_type = choose_random_weighted(weights, end(weights)); break; } // else intentional fall-through } case BOOK_RANDART_THEME: acquire_themed_randbook(book, agent); break; case BOOK_RANDART_LEVEL: { const int level = agent == GOD_XOM ? random_range(1, 9) : max(1, (_skill_rdiv(SK_SPELLCASTING) + 2) / 3); book.sub_type = BOOK_RANDART_LEVEL; if (!make_book_level_randart(book, level)) return false; break; } } // switch book choice // If we couldn't make a useful book, try to make a manual instead. // We have to temporarily identify the book for this. if (agent != GOD_XOM && agent != GOD_SIF_MUNA) { bool useless = false; { unwind_var<iflags_t> oldflags{book.flags}; book.flags |= ISFLAG_KNOW_TYPE; useless = is_useless_item(book); } if (useless) { destroy_item(book); book.base_type = OBJ_BOOKS; book.quantity = 1; return _acquire_manual(book); } } return true; } static int _failed_acquirement(bool quiet) { if (!quiet) mpr("The demon of the infinite void smiles upon you."); return NON_ITEM; } static int _weapon_brand_quality(int brand, bool range) { switch (brand) { case SPWPN_SPEED: return range ? 3 : 5; case SPWPN_PENETRATION: return 4; case SPWPN_ELECTROCUTION: case SPWPN_DISTORTION: case SPWPN_HOLY_WRATH: case SPWPN_REAPING: return 3; case SPWPN_CHAOS: return 2; default: return 1; case SPWPN_NORMAL: return 0; case SPWPN_PAIN: return _skill_rdiv(SK_NECROMANCY) / 2; case SPWPN_VORPAL: return range ? 5 : 1; } } static bool _armour_slot_seen(armour_type arm) { item_def item; item.base_type = OBJ_ARMOUR; item.quantity = 1; for (int i = 0; i < NUM_ARMOURS; i++) { if (get_armour_slot(arm) != get_armour_slot((armour_type)i)) continue; item.sub_type = i; // having seen a helmet means nothing about your decision to go // bare-headed if you have horns if (!can_wear_armour(item, false, true)) continue; if (you.seen_armour[i]) return true; } return false; } static bool _is_armour_plain(const item_def &item) { ASSERT(item.base_type == OBJ_ARMOUR); if (is_artefact(item)) return false; if (armour_is_special(item)) { // These are always interesting, even with no brand. // May still be redundant, but that has another check. return false; } return get_armour_ego_type(item) == SPARM_NORMAL; } /** * Has the player already encountered an item with this brand? * * Only supports weapons & armour. * * @param item The item in question. * @param Whether the player has encountered another weapon or * piece of armour with the same ego. */ static bool _brand_already_seen(const item_def &item) { switch (item.base_type) { case OBJ_WEAPONS: return you.seen_weapon[item.sub_type] & (1<<get_weapon_brand(item)); case OBJ_ARMOUR: return you.seen_armour[item.sub_type] & (1<<get_armour_ego_type(item)); default: die("Unsupported item type!"); } } // ugh #define ITEM_LEVEL (divine ? ISPEC_GIFT : ISPEC_GOOD_ITEM) /** * Take a newly-generated acquirement item, and adjust its brand if we don't * like it. * * Specifically, if we think the brand is too weak (for non-divine gifts), or * sometimes if we've seen the brand before. * * @param item The item which may have its brand adjusted. Not necessarily * a weapon or piece of armour. * @param divine Whether the item is a god gift, rather than from * acquirement proper. */ static void _adjust_brand(item_def &item, bool divine) { if (item.base_type != OBJ_WEAPONS && item.base_type != OBJ_ARMOUR) return; // don't reroll missile brands, I guess if (is_artefact(item)) return; // their own kettle of fish // Not from a god, so we should prefer better brands. if (!divine && item.base_type == OBJ_WEAPONS) { while (_weapon_brand_quality(get_weapon_brand(item), is_range_weapon(item)) < random2(6)) { reroll_brand(item, ITEM_LEVEL); } } // Try to not generate brands that were already seen, although unlike // jewellery and books, this is not absolute. while (_brand_already_seen(item) && !one_chance_in(5)) reroll_brand(item, ITEM_LEVEL); } /** * Should the given item be rejected as an acquirement/god gift result & * rerolled? If so, why? * * @param item The item in question. * @param agent The entity creating the item; possibly a god. * @return A reason why the item should be rejected, if it should be; * otherwise, the empty string. */ static string _why_reject(const item_def &item, int agent) { if (agent != GOD_XOM && (item.base_type == OBJ_WEAPONS && !can_wield(&item, false, true) || item.base_type == OBJ_ARMOUR && !can_wear_armour(item, false, true))) { return "Destroying unusable weapon or armour!"; } // Trog does not gift the Wrath of Trog, nor weapons of pain // (which work together with Necromantic magic). // nor fancy magic staffs (wucad mu, majin-bo) if (agent == GOD_TROG && (get_weapon_brand(item) == SPWPN_PAIN || is_unrandom_artefact(item, UNRAND_TROG) || is_unrandom_artefact(item, UNRAND_WUCAD_MU) || is_unrandom_artefact(item, UNRAND_MAJIN))) { return "Destroying a weapon Trog hates!"; } // Pain brand is useless if you've sacrificed Necromacy. if (you.get_mutation_level(MUT_NO_NECROMANCY_MAGIC) && get_weapon_brand(item) == SPWPN_PAIN) { return "Destroying pain weapon after Necro sac!"; } // Sif Muna shouldn't gift special books. // (The spells therein are still fair game for randart books.) if (agent == GOD_SIF_MUNA && is_rare_book(static_cast<book_type>(item.sub_type))) { ASSERT(item.base_type == OBJ_BOOKS); return "Destroying sif-gifted rarebook!"; } return ""; // all OK } int acquirement_create_item_general(object_class_type class_wanted, int agent, bool quiet, const coord_def &pos, bool debug, bool move) { ASSERT(class_wanted != OBJ_RANDOM); const bool divine = (agent == GOD_OKAWARU || agent == GOD_XOM || agent == GOD_TROG); int thing_created = NON_ITEM; int quant = 1; #define MAX_ACQ_TRIES 40 for (int item_tries = 0; item_tries < MAX_ACQ_TRIES; item_tries++) { int type_wanted = -1; if (agent == GOD_XOM && class_wanted == OBJ_ARMOUR && one_chance_in(20)) type_wanted = _useless_armour_type(); else { // This may clobber class_wanted (e.g. staves or vampire food) type_wanted = _find_acquirement_subtype(class_wanted, quant, divine, agent); } ASSERT(type_wanted != -1); // Don't generate randart books in items(), we do that // ourselves. bool want_arts = (class_wanted != OBJ_BOOKS); if (agent == GOD_TROG && !one_chance_in(3)) want_arts = false; thing_created = items(want_arts, class_wanted, type_wanted, ITEM_LEVEL, 0, agent); if (thing_created == NON_ITEM) { if (!quiet) dprf("Failed to make thing!"); continue; } item_def &acq_item(mitm[thing_created]); _adjust_brand(acq_item, divine); // For plain armour, try to change the subtype to something // matching a currently unfilled equipment slot. if (acq_item.base_type == OBJ_ARMOUR && !is_artefact(acq_item)) { const special_armour_type sparm = get_armour_ego_type(acq_item); if (agent != GOD_XOM && you.seen_armour[acq_item.sub_type] & (1 << sparm) && x_chance_in_y(MAX_ACQ_TRIES - item_tries, MAX_ACQ_TRIES + 5) || !divine && you.seen_armour[acq_item.sub_type] && !one_chance_in(3) && item_tries < 20) { // We have seen the exact item already, it's very unlikely // extras will do any good. // For scroll acquirement, prefer base items not seen before // as well, even if you didn't see the exact brand yet. destroy_item(thing_created, true); thing_created = NON_ITEM; if (!quiet) dprf("Destroying already-seen item!"); continue; } // Try to fill empty slots. if ((_is_armour_plain(acq_item) || get_armour_slot(acq_item) == EQ_BODY_ARMOUR && coinflip()) && _armour_slot_seen((armour_type)acq_item.sub_type)) { armour_type at = _pick_unseen_armour(); if (at != NUM_ARMOURS) { destroy_item(thing_created, true); thing_created = items(true, OBJ_ARMOUR, at, ITEM_LEVEL, 0, agent); } else if (agent != GOD_XOM && one_chance_in(3)) { // If the item is plain and there aren't any // unfilled slots, we might want to roll again. destroy_item(thing_created, true); thing_created = NON_ITEM; if (!quiet) dprf("Destroying plain item!"); continue; } } } if (agent == GOD_TROG && coinflip() && acq_item.base_type == OBJ_WEAPONS && !is_range_weapon(acq_item) && !is_unrandom_artefact(acq_item)) { // ... but Trog loves the antimagic brand specially. set_item_ego_type(acq_item, OBJ_WEAPONS, SPWPN_ANTIMAGIC); } const string rejection_reason = _why_reject(acq_item, agent); if (!rejection_reason.empty()) { if (!quiet) dprf("%s", rejection_reason.c_str()); destroy_item(acq_item); thing_created = NON_ITEM; continue; } ASSERT(acq_item.is_valid()); switch (class_wanted) { case OBJ_WANDS: acq_item.plus = acq_item.plus * 2 + random2(2); break; case OBJ_GOLD: acq_item.quantity = 200 + random2(1401); break; case OBJ_MISSILES: if (!divine) acq_item.quantity *= 5; else { int gift_count = you.num_total_gifts[you.religion]; acq_item.quantity = acq_item.quantity * (14 + gift_count) / (12 + 2 * gift_count); } break; default: if (quant > 1) acq_item.quantity = quant; break; } // Remove curse flag from item, unless worshipping Ashenzari. if (have_passive(passive_t::want_curses)) do_curse_item(acq_item, true); else do_uncurse_item(acq_item); if (acq_item.base_type == OBJ_BOOKS) { if (!_do_book_acquirement(acq_item, agent)) { destroy_item(acq_item, true); return _failed_acquirement(quiet); } // That might have changed the item's subtype. item_colour(acq_item); } else if (acq_item.base_type == OBJ_JEWELLERY) { switch (acq_item.sub_type) { case RING_PROTECTION: case RING_STRENGTH: case RING_INTELLIGENCE: case RING_DEXTERITY: case RING_EVASION: case RING_SLAYING: // Make sure plus is >= 1. acq_item.plus = max(abs((int) acq_item.plus), 1); break; case RING_ATTENTION: case RING_TELEPORTATION: case AMU_INACCURACY: // These are the only truly bad pieces of jewellery. if (!one_chance_in(9)) make_item_randart(acq_item); break; default: break; } // bump jewel acq power up a bit if (one_chance_in(2) && !is_artefact(acq_item)) make_item_randart(acq_item); } else if (acq_item.base_type == OBJ_WEAPONS && !is_unrandom_artefact(acq_item)) { // These can never get egos, and mundane versions are quite common, // so guarantee artefact status. Rarity is a bit low to compensate. // ...except actually, trog can give them antimagic brand, so... if (is_giant_club_type(acq_item.sub_type) && get_weapon_brand(acq_item) == SPWPN_NORMAL && !one_chance_in(25)) { make_item_randart(acq_item, true); } if (agent == GOD_TROG || agent == GOD_OKAWARU) { if (agent == GOD_TROG) acq_item.plus += random2(3); // On a weapon, an enchantment of less than 0 is never viable. acq_item.plus = max(static_cast<int>(acq_item.plus), random2(2)); } } // Last check: don't acquire items your god hates. // Temporarily mark the type as ID'd for the purpose of checking if // it is a hated brand (this addresses, e.g., Elyvilon followers // immediately identifying evil weapons). // Note that Xom will happily give useless items! int oldflags = acq_item.flags; acq_item.flags |= ISFLAG_KNOW_TYPE; if ((is_useless_item(acq_item, false) && agent != GOD_XOM) || god_hates_item(acq_item)) { if (!quiet) dprf("destroying useless item"); destroy_item(thing_created); thing_created = NON_ITEM; continue; } acq_item.flags = oldflags; break; } if (thing_created == NON_ITEM) return _failed_acquirement(quiet); item_set_appearance(mitm[thing_created]); // cleanup ASSERT(!is_useless_item(mitm[thing_created], false) || agent == GOD_XOM); ASSERT(!god_hates_item(mitm[thing_created])); // Moving this above the move since it might not exist after falling. if (thing_created != NON_ITEM && !quiet) canned_msg(MSG_SOMETHING_APPEARS); // If a god wants to give you something but the floor doesn't want it, // it counts as a failed acquirement - no piety, etc cost. if (feat_destroys_items(grd(pos)) && agent > GOD_NO_GOD && agent < NUM_GODS) { if (agent == GOD_XOM) simple_god_message(" snickers.", GOD_XOM); else return _failed_acquirement(quiet); } if(move) { move_item_to_grid(&thing_created, pos); } if (thing_created != NON_ITEM) { ASSERT(mitm[thing_created].is_valid()); mitm[thing_created].props[ACQUIRE_KEY].get_int() = agent; } return thing_created; } //dtsund: Wrapper, since I needed to modify the original function to pass //an assert. int acquirement_create_item(object_class_type class_wanted, int agent, bool quiet, const coord_def &pos, bool debug) { return acquirement_create_item_general(class_wanted, agent, quiet, pos, debug, true); } //dtsund: Acquirement was changed rather drastically. Now lets you choose from //specific items, rather than classes of item. bool acquirement(object_class_type class_wanted, int agent, bool quiet, int* item_index, bool debug, bool known_scroll) { if(class_wanted == OBJ_RANDOM) { unwind_bool in_acquirement(_acquiring_now, true); cursor_control coff(false); bool tempQuiet = true; const std::string hello = "What would you like to acquire?"; int item_type_count = 8; if(you.species == SP_FELID) item_type_count -= 2; if(you.get_mutation_level(MUT_NO_ARTIFICE)) item_type_count -= 1; bool no_food = you_foodless(); if(no_food) item_type_count -= 1; bool usable_book = false; if(you.religion == GOD_TROG) for (skill_type sk = SK_FIRST_SKILL; sk < NUM_SKILLS; ++sk) { int skl = _skill_rdiv(sk); if (skl < 27 && !is_useless_skill(sk) && !_skill_useless_with_god(sk)) { usable_book = true; break; } } else usable_book = true; if(!usable_book) item_type_count -= 1; std::vector<int> stock(item_type_count); //dtsund: I don't really know what half of this does. coord_def stock_loc = coord_def(0, 65); // ?? int index = 0; if(you.species != SP_FELID) { stock[index] = acquirement_create_item_general(OBJ_WEAPONS, agent, tempQuiet, stock_loc, debug, false); index++; } stock[index] = acquirement_create_item_general(OBJ_ARMOUR, agent, tempQuiet, stock_loc, debug, false); index++; stock[index] = acquirement_create_item_general(OBJ_JEWELLERY, agent, tempQuiet, stock_loc, debug, false); index++; if(usable_book) { stock[index] = acquirement_create_item_general(OBJ_BOOKS, agent, tempQuiet, stock_loc, debug, false); index++; } if(you.species != SP_FELID) { stock[index] = acquirement_create_item_general(OBJ_STAVES, agent, tempQuiet, stock_loc, debug, false); index++; } if(!you.get_mutation_level(MUT_NO_ARTIFICE)) { stock[index] = acquirement_create_item_general(OBJ_MISCELLANY, agent, tempQuiet, stock_loc, debug, false); index++; } if(!no_food) { stock[index] = acquirement_create_item_general(OBJ_FOOD, agent, tempQuiet, stock_loc, debug, false); index++; } stock[index] = acquirement_create_item_general(OBJ_GOLD, agent, tempQuiet, stock_loc, debug, false); index++; // Autoinscribe randarts in the menu. for (unsigned int i = 0; i < stock.size(); i++) { item_def& item = mitm[stock[i]]; if(is_artefact(item) || item.base_type == OBJ_JEWELLERY) { set_ident_type(item, true); set_ident_flags(item, ISFLAG_IDENT_MASK); } } std::vector<bool> selected; selected.resize(stock.size(), false); const bool id_stock = true; bool viewing = false; while (true) { if (crawl_state.seen_hups) { for (unsigned int i =0; i < selected.size(); i++) { item_def& item = mitm[stock[i]]; destroy_item(item); } mprf(MSGCH_WARN, "Cancelling acquirement."); return false; } if (stock.empty()) mprf(MSGCH_WARN, "ACQUIREMENT ERROR"); if (viewing) mprf(MSGCH_PROMPT, "\nView which item? (Press ! for selection.)"); else mprf(MSGCH_PROMPT, "\nAcquire which item? (Press ! for descriptions.)"); bool failed = false; vector<string> item_strings; char selection_key = 'A'; for (unsigned int i = 0; i < stock.size(); ++i) { const item_def& item = mitm[stock[i]]; string item_name = item.name(DESC_PLAIN, false, true); if (item_name[0] != '!') item_strings.push_back(make_stringf("%c: %s", selection_key, item_name.c_str())); else failed = true; selection_key++; } // temp fix for failed acq bug: return the scroll if (failed) { for (unsigned int i =0; i < selected.size(); i++) { item_def& item = mitm[stock[i]]; destroy_item(item); } string error; create_item_named("scroll of acquirement q:1", you.pos(), &error); if (!error.empty()) mprf(MSGCH_ERROR, "Error: %s", error.c_str()); else mpr("The scroll of acquirement finds you a scroll of acquirement!"); return false; } else for (string msg : item_strings) mpr(msg); flush_prev_message(); mouse_control mc(MOUSE_MODE_MORE); int key = getchm(); if (key == '\\') check_item_knowledge(); else if (key == 'x' || key_is_escape(key) || key == CK_MOUSE_CMD) { mprf(MSGCH_WARN, "\nThis will waste the scroll!\nReally cancel your acquirement? (Y/N)"); flush_prev_message(); if (yesno(NULL, false, 'n', false, false, true)) { for (unsigned int i =0; i < selected.size(); i++) { item_def& item = mitm[stock[i]]; destroy_item(item); } mpr("Cancelling acquirement."); break; } } else if (key == '\r' || key == CK_MOUSE_CLICK) continue; else if (key == '!') { // Toggle between browsing and shopping. viewing = !viewing; } else if (key == '?') viewing = true; else if (key == '$') shopping_list.display(true); else if (key == 'i') display_inventory(); else { key = tolower(key) - 'a'; if (key >= static_cast<int>(stock.size()) || key < 0) { mpr("No such item."); continue; } item_def& item = mitm[stock[key]]; if (viewing) { // A hack to make the description more useful. // In theory, the user could kill the process at this // point and end up with valid ID for the item. // That's not very useful, though, because it doesn't set // type-ID and once you can access the item (by buying it) // you have its full ID anyway. Worst case, it won't get // noted when you buy it. const uint64_t old_flags = item.flags; if (id_stock) { item.flags |= (ISFLAG_IDENT_MASK | ISFLAG_NOTED_ID | ISFLAG_NOTED_GET); } describe_item(item); if (id_stock) item.flags = old_flags; } else { for(unsigned int i = 0; i < selected.size(); i++) { selected[i] = false; } selected[key] = true; mprf(MSGCH_PROMPT, "\nAcquire %s? (y/n)", item.name(DESC_THE, false, true).c_str()); flush_prev_message(); if (yesno(NULL, true, 'n', false, false, true)) { for (unsigned int i = 0; i < selected.size(); i++) { item_def& item = mitm[stock[i]]; if (selected[i]) { // ID it before giving it to the player. set_ident_type(item, true); set_ident_flags(item, ISFLAG_IDENT_MASK); move_item_to_grid(&stock[i], you.pos()); } else { destroy_item(item); } } canned_msg(MSG_SOMETHING_APPEARS); break; } continue; } } } return(true); } int thing_created = NON_ITEM; if (item_index == nullptr) item_index = &thing_created; *item_index = NON_ITEM; *item_index = acquirement_create_item(class_wanted, agent, quiet, you.pos(), debug); ASSERT(*item_index == NON_ITEM || !god_hates_item(mitm[*item_index])); return true; }
32.744729
118
0.572555
[ "vector" ]
4f6f002abb1ac7ecbfd401ebbc2fafb4da0b05a8
933
cpp
C++
combination-sum-ii/solution-0.cpp
tsenmu/leetcode
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
[ "Apache-2.0" ]
null
null
null
combination-sum-ii/solution-0.cpp
tsenmu/leetcode
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
[ "Apache-2.0" ]
null
null
null
combination-sum-ii/solution-0.cpp
tsenmu/leetcode
6f6d11dec4e5ee0fbc0c59fd6fa97b2c556e05ee
[ "Apache-2.0" ]
null
null
null
class Solution { public: vector<vector<int>> results; void dfs(vector<int>& result, int sum, int lastIndex, vector<int>& candidates, int target) { if (sum == target) { results.push_back(result); return; } if (sum > target) { return; } for (int i = lastIndex + 1; i < candidates.size(); ++i) { int candidate = candidates[i]; if (i > lastIndex + 1 && candidates[i] == candidates[i - 1]) { continue; } result.push_back(candidate); dfs(result, sum + candidate, i, candidates, target); result.pop_back(); } } vector<vector<int>> combinationSum2(vector<int>& candidates, int target) { sort(candidates.begin(), candidates.end()); vector<int> result; dfs(result, 0, -1, candidates, target); return results; } };
28.272727
96
0.5209
[ "vector" ]
4f6f296725944eb23a548769e70d834ff7986091
11,825
cpp
C++
camera/camera_lookAt/main.cpp
tianxiawuzhei/learn_opengl
d472a77f0d3ba87dcc4244df023d87dcf4d65897
[ "MIT" ]
1
2021-01-28T07:24:18.000Z
2021-01-28T07:24:18.000Z
camera/camera_lookAt/main.cpp
tianxiawuzhei/learn_opengl
d472a77f0d3ba87dcc4244df023d87dcf4d65897
[ "MIT" ]
null
null
null
camera/camera_lookAt/main.cpp
tianxiawuzhei/learn_opengl
d472a77f0d3ba87dcc4244df023d87dcf4d65897
[ "MIT" ]
null
null
null
/* 摄像机 https://learnopengl-cn.github.io/01%20Getting%20started/09%20Camera/ glm::mat4 view; view = glm::lookAt(glm::vec3(0.0f, 0.0f, 3.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); */ #include <glad/glad.h> #include <GLFW/glfw3.h> #include <iostream> #include <common/Shader.hpp> #include <common/stb_image.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> void framebuffer_size_callback(GLFWwindow* window, int width, int height); void processInput(GLFWwindow *window); // settings const unsigned int SCR_WIDTH = 800; const unsigned int SCR_HEIGHT = 600; int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); #ifdef __APPLE__ glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); #endif // glfw window creation // -------------------- GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", NULL, NULL); if (window == NULL) { std::cout << "Failed to create GLFW window" << std::endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); // glad: load all OpenGL function pointers // --------------------------------------- if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { std::cout << "Failed to initialize GLAD" << std::endl; return -1; } // build and compile our shader program // ------------------------------------ // vertex shader auto shader = new Shader("./shader_res/shader.vs", "./shader_res/shader_two.fs"); // set up vertex data (and buffer(s)) and configure vertex attributes // ------------------------------------------------------------------ float vertices[] = { -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, 0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 1.0f, -0.5f, 0.5f, 0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, -0.5f, 1.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, 0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.5f, -0.5f, 0.5f, 1.0f, 0.0f, -0.5f, -0.5f, 0.5f, 0.0f, 0.0f, -0.5f, -0.5f, -0.5f, 0.0f, 1.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.5f, 0.5f, -0.5f, 1.0f, 1.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.5f, 0.5f, 0.5f, 1.0f, 0.0f, -0.5f, 0.5f, 0.5f, 0.0f, 0.0f, -0.5f, 0.5f, -0.5f, 0.0f, 1.0f }; glm::vec3 cubePositions[] = { glm::vec3( 0.0f, 0.0f, 0.0f), glm::vec3( 2.0f, 5.0f, -15.0f), glm::vec3(-1.5f, -2.2f, -2.5f), glm::vec3(-3.8f, -2.0f, -12.3f), glm::vec3( 2.4f, -0.4f, -3.5f), glm::vec3(-1.7f, 3.0f, -7.5f), glm::vec3( 1.3f, -2.0f, -2.5f), glm::vec3( 1.5f, 2.0f, -2.5f), glm::vec3( 1.5f, 0.2f, -1.5f), glm::vec3(-1.3f, 1.0f, -1.5f) }; unsigned int indices[] = { // note that we start from 0! 0, 1, 3, // first Triangle 1, 2, 3 // second Triangle }; unsigned int VBO, VAO, EBO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); // glGenBuffers(1, &EBO); // bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s). glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); // glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO); // glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3*sizeof(float))); glEnableVertexAttribArray(1); // // glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6*sizeof(float))); // glEnableVertexAttribArray(2); // note that this is allowed, the call to glVertexAttribPointer registered VBO as the vertex attribute's bound vertex buffer object so afterwards we can safely unbind glBindBuffer(GL_ARRAY_BUFFER, 0); // You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens. Modifying other // VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary. glBindVertexArray(0); //texture GLuint texture1, texture2; glGenTextures(1, &texture1); glBindTexture(GL_TEXTURE_2D, texture1); // all upcoming GL_TEXTURE_2D operations now have effect on this texture object // 为当前绑定的纹理对象设置环绕、过滤方式 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // 加载并生成纹理 int width, height, nrChannels; unsigned char *data = stbi_load("./shader_res/wall.jpg", &width, &height, &nrChannels, 0); if (data) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data); glGenTextures(1, &texture2); glBindTexture(GL_TEXTURE_2D, texture2); // all upcoming GL_TEXTURE_2D operations now have effect on this texture object // 为当前绑定的纹理对象设置环绕、过滤方式 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // 加载并生成纹理 stbi_set_flip_vertically_on_load(true); unsigned char *data2 = stbi_load("./shader_res/awesomeface.png", &width, &height, &nrChannels, 0); if (data2) { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, data2); glGenerateMipmap(GL_TEXTURE_2D); } else { std::cout << "Failed to load texture" << std::endl; } stbi_image_free(data2); shader->use(); // 不要忘记在设置uniform变量之前激活着色器程序! glUniform1i(glGetUniformLocation(shader->ID, "texture1"), 0); // 手动设置 shader->setInt("texture2", 1); // 或者使用着色器类设置 // uncomment this call to draw in wireframe polygons. //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); // glm::mat4 trans = glm::mat4(1.0f); // trans = glm::rotate(trans, glm::radians(90.0f), glm::vec3(0.0, 0.0, 1.0)); // trans = glm::translate(trans, glm::vec3(0.5f, -0.5f, 0.0f)); // trans = glm::scale(trans, glm::vec3(0.5, 0.5, 0.5)); // unsigned int transformLoc = glGetUniformLocation(shader->ID, "transform"); // glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm::value_ptr(trans)); glEnable(GL_DEPTH_TEST); auto mix_ratio = 0.2f; // render loop // ----------- while (!glfwWindowShouldClose(window)) { // input // ----- processInput(window); // render // ------ glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glm::mat4 model = glm::mat4(1.0f); model = glm::rotate(model, (float)glfwGetTime() * glm::radians(50.0f), glm::vec3(0.5f, 1.0f, 0.0f)); float radius = 10.0f; float camX = sin(glfwGetTime()) * radius; float camZ = cos(glfwGetTime()) * radius; glm::mat4 view = glm::mat4(1.0f); view = glm::lookAt(glm::vec3(camX, 0.0f, camZ), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); glm::mat4 projection = glm::mat4(1.0f); projection = glm::perspective(glm::radians(45.0f), (float)SCR_WIDTH / SCR_HEIGHT, 0.1f, 100.0f); // draw our first triangle shader->use(); // shader->setFloat("mix_ratio", mix_ratio); // shader->setMatrix4fv("model", glm::value_ptr(model)); shader->setMat4("view", view); shader->setMat4("projection", projection); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture1); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, texture2); glBindVertexArray(VAO); // seeing as we only have a single VAO there's no need to bind it every time, but we'll do so to keep things a bit more organized // glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0); for(unsigned int i = 0; i < 10; i++) { glm::mat4 model = glm::mat4(1.0f); model = glm::translate(model, cubePositions[i]); float angle = 20.0f * i; model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f)); shader->setMat4("model", model); glDrawArrays(GL_TRIANGLES, 0, 36); } // glBindVertexArray(0); // no need to unbind it every time // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) // ------------------------------------------------------------------------------- glfwSwapBuffers(window); glfwPollEvents(); } // optional: de-allocate all resources once they've outlived their purpose: // ------------------------------------------------------------------------ glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); glDeleteBuffers(1, &EBO); // glfw: terminate, clearing all previously allocated GLFW resources. // ------------------------------------------------------------------ glfwTerminate(); return 0; } // process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly // --------------------------------------------------------------------------------------------------------- void processInput(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); } // glfw: whenever the window size changed (by OS or user resize) this callback function executes // --------------------------------------------------------------------------------------------- void framebuffer_size_callback(GLFWwindow* window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); }
36.609907
170
0.574968
[ "render", "object", "model", "transform" ]
4f6f7367c9763f264d2354ea96dc179296a3ed48
56,817
cc
C++
lib/jxl/jxl_test.cc
zeroheure/libjxl
08dcb04eb2bed2a9f6875859b4bb9a4080a2d7ec
[ "BSD-3-Clause" ]
null
null
null
lib/jxl/jxl_test.cc
zeroheure/libjxl
08dcb04eb2bed2a9f6875859b4bb9a4080a2d7ec
[ "BSD-3-Clause" ]
null
null
null
lib/jxl/jxl_test.cc
zeroheure/libjxl
08dcb04eb2bed2a9f6875859b4bb9a4080a2d7ec
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) the JPEG XL 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 <stdint.h> #include <stdio.h> #include <array> #include <string> #include <utility> #include <vector> #include "gtest/gtest.h" #include "lib/extras/codec.h" #include "lib/extras/codec_jpg.h" #include "lib/jxl/aux_out.h" #include "lib/jxl/base/compiler_specific.h" #include "lib/jxl/base/data_parallel.h" #include "lib/jxl/base/override.h" #include "lib/jxl/base/padded_bytes.h" #include "lib/jxl/base/thread_pool_internal.h" #include "lib/jxl/codec_in_out.h" #include "lib/jxl/color_encoding_internal.h" #include "lib/jxl/color_management.h" #include "lib/jxl/dec_file.h" #include "lib/jxl/dec_params.h" #include "lib/jxl/enc_butteraugli_comparator.h" #include "lib/jxl/enc_cache.h" #include "lib/jxl/enc_file.h" #include "lib/jxl/enc_params.h" #include "lib/jxl/image.h" #include "lib/jxl/image_bundle.h" #include "lib/jxl/image_ops.h" #include "lib/jxl/image_test_utils.h" #include "lib/jxl/jpeg/enc_jpeg_data.h" #include "lib/jxl/modular/options.h" #include "lib/jxl/test_utils.h" #include "lib/jxl/testdata.h" #include "tools/box/box.h" namespace jxl { namespace { using test::Roundtrip; #define JXL_TEST_NL 0 // Disabled in code void CreateImage1x1(CodecInOut* io) { Image3F image(1, 1); ZeroFillImage(&image); io->metadata.m.SetUintSamples(8); io->metadata.m.color_encoding = ColorEncoding::SRGB(); io->SetFromImage(std::move(image), io->metadata.m.color_encoding); } TEST(JxlTest, HeaderSize) { CodecInOut io; CreateImage1x1(&io); CompressParams cparams; cparams.butteraugli_distance = 1.5; DecompressParams dparams; ThreadPool* pool = nullptr; { CodecInOut io2; AuxOut aux_out; Roundtrip(&io, cparams, dparams, pool, &io2, &aux_out); EXPECT_LE(aux_out.layers[kLayerHeader].total_bits, 34u); } { CodecInOut io2; io.metadata.m.SetAlphaBits(8); ImageF alpha(1, 1); alpha.Row(0)[0] = 1; io.Main().SetAlpha(std::move(alpha), /*alpha_is_premultiplied=*/false); AuxOut aux_out; Roundtrip(&io, cparams, dparams, pool, &io2, &aux_out); EXPECT_LE(aux_out.layers[kLayerHeader].total_bits, 57u); } } TEST(JxlTest, RoundtripSinglePixel) { CodecInOut io; CreateImage1x1(&io); CompressParams cparams; cparams.butteraugli_distance = 1.0; DecompressParams dparams; ThreadPool* pool = nullptr; CodecInOut io2; Roundtrip(&io, cparams, dparams, pool, &io2); } // Changing serialized signature causes Decode to fail. #ifndef JXL_CRASH_ON_ERROR TEST(JxlTest, RoundtripMarker) { CodecInOut io; CreateImage1x1(&io); CompressParams cparams; cparams.butteraugli_distance = 1.0; DecompressParams dparams; AuxOut* aux_out = nullptr; ThreadPool* pool = nullptr; PassesEncoderState enc_state; for (size_t i = 0; i < 2; ++i) { PaddedBytes compressed; EXPECT_TRUE( EncodeFile(cparams, &io, &enc_state, &compressed, aux_out, pool)); compressed[i] ^= 0xFF; CodecInOut io2; EXPECT_FALSE(DecodeFile(dparams, compressed, &io2, pool)); } } #endif TEST(JxlTest, RoundtripTinyFast) { ThreadPool* pool = nullptr; const PaddedBytes orig = ReadTestData("wesaturate/500px/u76c0g_bliznaca_srgb8.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, pool)); io.ShrinkTo(32, 32); CompressParams cparams; cparams.speed_tier = SpeedTier::kSquirrel; cparams.butteraugli_distance = 4.0f; DecompressParams dparams; CodecInOut io2; const size_t enc_bytes = Roundtrip(&io, cparams, dparams, pool, &io2); printf("32x32 image size %zu bytes\n", enc_bytes); } TEST(JxlTest, RoundtripSmallD1) { ThreadPool* pool = nullptr; const PaddedBytes orig = ReadTestData("wesaturate/500px/u76c0g_bliznaca_srgb8.png"); CompressParams cparams; cparams.butteraugli_distance = 1.0; DecompressParams dparams; CodecInOut io_out; size_t compressed_size; { CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, pool)); io.ShrinkTo(io.xsize() / 8, io.ysize() / 8); compressed_size = Roundtrip(&io, cparams, dparams, pool, &io_out); EXPECT_LE(compressed_size, 1000u); EXPECT_LE(ButteraugliDistance(io, io_out, cparams.ba_params, /*distmap=*/nullptr, pool), 1.5); } { // And then, with a lower intensity target than the default, the bitrate // should be smaller. CodecInOut io_dim; io_dim.target_nits = 100; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io_dim, pool)); io_dim.ShrinkTo(io_dim.xsize() / 8, io_dim.ysize() / 8); EXPECT_LT(Roundtrip(&io_dim, cparams, dparams, pool, &io_out), compressed_size); EXPECT_LE(ButteraugliDistance(io_dim, io_out, cparams.ba_params, /*distmap=*/nullptr, pool), 1.5); EXPECT_EQ(io_dim.metadata.m.IntensityTarget(), io_out.metadata.m.IntensityTarget()); } } TEST(JxlTest, RoundtripOtherTransforms) { ThreadPool* pool = nullptr; const PaddedBytes orig = ReadTestData("wesaturate/64px/a2d1un_nkitzmiller_srgb8.png"); std::unique_ptr<CodecInOut> io = jxl::make_unique<CodecInOut>(); ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), io.get(), pool)); CompressParams cparams; // Slow modes access linear image for adaptive quant search cparams.speed_tier = SpeedTier::kKitten; cparams.color_transform = ColorTransform::kNone; cparams.butteraugli_distance = 5.0f; DecompressParams dparams; std::unique_ptr<CodecInOut> io2 = jxl::make_unique<CodecInOut>(); const size_t compressed_size = Roundtrip(io.get(), cparams, dparams, pool, io2.get()); EXPECT_LE(compressed_size, 23000u); EXPECT_LE(ButteraugliDistance(*io, *io2, cparams.ba_params, /*distmap=*/nullptr, pool), 6); // Check the consistency when performing another roundtrip. std::unique_ptr<CodecInOut> io3 = jxl::make_unique<CodecInOut>(); const size_t compressed_size2 = Roundtrip(io.get(), cparams, dparams, pool, io3.get()); EXPECT_LE(compressed_size2, 23000u); EXPECT_LE(ButteraugliDistance(*io, *io3, cparams.ba_params, /*distmap=*/nullptr, pool), 6); } TEST(JxlTest, RoundtripResample2) { ThreadPool* pool = nullptr; const PaddedBytes orig = ReadTestData("wesaturate/500px/u76c0g_bliznaca_srgb8.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, pool)); io.ShrinkTo(io.xsize(), io.ysize()); CompressParams cparams; cparams.resampling = 2; DecompressParams dparams; CodecInOut io2; EXPECT_LE(Roundtrip(&io, cparams, dparams, pool, &io2), 17000u); EXPECT_LE(ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, pool), 12); } TEST(JxlTest, RoundtripResample2MT) { ThreadPoolInternal pool(4); const PaddedBytes orig = ReadTestData("imagecompression.info/flower_foveon.png"); // image has to be large enough to have multiple groups after downsampling CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, &pool)); CompressParams cparams; cparams.resampling = 2; DecompressParams dparams; CodecInOut io2; // TODO(veluca): Figure out why msan and release produce different // file size. EXPECT_LE(Roundtrip(&io, cparams, dparams, &pool, &io2), 64500u); EXPECT_LE(ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, &pool), #if JXL_HIGH_PRECISION 5.5); #else 13.5); #endif } TEST(JxlTest, RoundtripResample4) { ThreadPool* pool = nullptr; const PaddedBytes orig = ReadTestData("wesaturate/500px/u76c0g_bliznaca_srgb8.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, pool)); io.ShrinkTo(io.xsize(), io.ysize()); CompressParams cparams; cparams.resampling = 4; DecompressParams dparams; CodecInOut io2; EXPECT_LE(Roundtrip(&io, cparams, dparams, pool, &io2), 6000u); EXPECT_LE(ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, pool), 28); } TEST(JxlTest, RoundtripResample8) { ThreadPool* pool = nullptr; const PaddedBytes orig = ReadTestData("wesaturate/500px/u76c0g_bliznaca_srgb8.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, pool)); io.ShrinkTo(io.xsize(), io.ysize()); CompressParams cparams; cparams.resampling = 8; DecompressParams dparams; CodecInOut io2; EXPECT_LE(Roundtrip(&io, cparams, dparams, pool, &io2), 2100u); EXPECT_LE(ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, pool), 80); } TEST(JxlTest, RoundtripUnalignedD2) { ThreadPool* pool = nullptr; const PaddedBytes orig = ReadTestData("wesaturate/500px/u76c0g_bliznaca_srgb8.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, pool)); io.ShrinkTo(io.xsize() / 12, io.ysize() / 7); CompressParams cparams; cparams.butteraugli_distance = 2.0; DecompressParams dparams; CodecInOut io2; EXPECT_LE(Roundtrip(&io, cparams, dparams, pool, &io2), 700u); EXPECT_LE(ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, pool), 3.2); } #if JXL_TEST_NL TEST(JxlTest, RoundtripMultiGroupNL) { ThreadPoolInternal pool(4); const PaddedBytes orig = ReadTestData("imagecompression.info/flower_foveon.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, &pool)); io.ShrinkTo(600, 1024); // partial X, full Y group CompressParams cparams; DecompressParams dparams; cparams.fast_mode = true; cparams.butteraugli_distance = 1.0f; CodecInOut io2; Roundtrip(&io, cparams, dparams, &pool, &io2); EXPECT_LE(ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, &pool), 0.9f); cparams.butteraugli_distance = 2.0f; CodecInOut io3; EXPECT_LE(Roundtrip(&io, cparams, dparams, &pool, &io3), 80000u); EXPECT_LE(ButteraugliDistance(io, io3, cparams.ba_params, /*distmap=*/nullptr, &pool), 1.5f); } #endif TEST(JxlTest, RoundtripMultiGroup) { ThreadPoolInternal pool(4); const PaddedBytes orig = ReadTestData("imagecompression.info/flower_foveon.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, &pool)); io.ShrinkTo(600, 1024); CompressParams cparams; DecompressParams dparams; cparams.butteraugli_distance = 1.0f; cparams.speed_tier = SpeedTier::kKitten; CodecInOut io2; EXPECT_LE(Roundtrip(&io, cparams, dparams, &pool, &io2), 40000u); EXPECT_LE(ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, &pool), 1.99f); cparams.butteraugli_distance = 2.0f; CodecInOut io3; EXPECT_LE(Roundtrip(&io, cparams, dparams, &pool, &io3), 22100u); EXPECT_LE(ButteraugliDistance(io, io3, cparams.ba_params, /*distmap=*/nullptr, &pool), 3.0f); } TEST(JxlTest, RoundtripLargeFast) { ThreadPoolInternal pool(8); const PaddedBytes orig = ReadTestData("imagecompression.info/flower_foveon.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, &pool)); CompressParams cparams; cparams.speed_tier = SpeedTier::kSquirrel; DecompressParams dparams; CodecInOut io2; EXPECT_LE(Roundtrip(&io, cparams, dparams, &pool, &io2), 265000u); } TEST(JxlTest, RoundtripDotsForceEpf) { ThreadPoolInternal pool(8); const PaddedBytes orig = ReadTestData("wesaturate/500px/cvo9xd_keong_macan_srgb8.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, &pool)); CompressParams cparams; cparams.epf = 2; cparams.dots = Override::kOn; cparams.speed_tier = SpeedTier::kSquirrel; DecompressParams dparams; CodecInOut io2; EXPECT_LE(Roundtrip(&io, cparams, dparams, &pool, &io2), 265000u); } // Checks for differing size/distance in two consecutive runs of distance 2, // which involves additional processing including adaptive reconstruction. // Failing this may be a sign of race conditions or invalid memory accesses. TEST(JxlTest, RoundtripD2Consistent) { ThreadPoolInternal pool(8); const PaddedBytes orig = ReadTestData("imagecompression.info/flower_foveon.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, &pool)); CompressParams cparams; cparams.speed_tier = SpeedTier::kSquirrel; cparams.butteraugli_distance = 2.0; DecompressParams dparams; // Try each xsize mod kBlockDim to verify right border handling. for (size_t xsize = 48; xsize > 40; --xsize) { io.ShrinkTo(xsize, 15); CodecInOut io2; const size_t size2 = Roundtrip(&io, cparams, dparams, &pool, &io2); CodecInOut io3; const size_t size3 = Roundtrip(&io, cparams, dparams, &pool, &io3); // Exact same compressed size. EXPECT_EQ(size2, size3); // Exact same distance. const float dist2 = ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, &pool); const float dist3 = ButteraugliDistance(io, io3, cparams.ba_params, /*distmap=*/nullptr, &pool); EXPECT_EQ(dist2, dist3); } } // Same as above, but for full image, testing multiple groups. TEST(JxlTest, RoundtripLargeConsistent) { ThreadPoolInternal pool(8); const PaddedBytes orig = ReadTestData("imagecompression.info/flower_foveon.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, &pool)); CompressParams cparams; cparams.speed_tier = SpeedTier::kSquirrel; cparams.butteraugli_distance = 2.0; DecompressParams dparams; // Try each xsize mod kBlockDim to verify right border handling. CodecInOut io2; const size_t size2 = Roundtrip(&io, cparams, dparams, &pool, &io2); CodecInOut io3; const size_t size3 = Roundtrip(&io, cparams, dparams, &pool, &io3); // Exact same compressed size. EXPECT_EQ(size2, size3); // Exact same distance. const float dist2 = ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, &pool); const float dist3 = ButteraugliDistance(io, io3, cparams.ba_params, /*distmap=*/nullptr, &pool); EXPECT_EQ(dist2, dist3); } #if JXL_TEST_NL TEST(JxlTest, RoundtripSmallNL) { ThreadPool* pool = nullptr; const PaddedBytes orig = ReadTestData("wesaturate/500px/u76c0g_bliznaca_srgb8.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, pool)); io.ShrinkTo(io.xsize() / 8, io.ysize() / 8); CompressParams cparams; cparams.butteraugli_distance = 1.0; DecompressParams dparams; CodecInOut io2; EXPECT_LE(Roundtrip(&io, cparams, dparams, pool, &io2), 1500u); EXPECT_LE(ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, pool), 1.7); } #endif TEST(JxlTest, RoundtripNoGaborishNoAR) { ThreadPool* pool = nullptr; const PaddedBytes orig = ReadTestData("wesaturate/500px/u76c0g_bliznaca_srgb8.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, pool)); CompressParams cparams; cparams.gaborish = Override::kOff; cparams.epf = 0; cparams.butteraugli_distance = 1.0; DecompressParams dparams; CodecInOut io2; EXPECT_LE(Roundtrip(&io, cparams, dparams, pool, &io2), 40000u); EXPECT_LE(ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, pool), 2.5); } TEST(JxlTest, RoundtripSmallNoGaborish) { ThreadPool* pool = nullptr; const PaddedBytes orig = ReadTestData("wesaturate/500px/u76c0g_bliznaca_srgb8.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, pool)); io.ShrinkTo(io.xsize() / 8, io.ysize() / 8); CompressParams cparams; cparams.gaborish = Override::kOff; cparams.butteraugli_distance = 1.0; DecompressParams dparams; CodecInOut io2; EXPECT_LE(Roundtrip(&io, cparams, dparams, pool, &io2), 900u); EXPECT_LE(ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, pool), 1.7); } TEST(JxlTest, RoundtripSmallPatchesAlpha) { ThreadPool* pool = nullptr; CodecInOut io; io.metadata.m.color_encoding = ColorEncoding::LinearSRGB(); Image3F black_with_small_lines(256, 256); ImageF alpha(black_with_small_lines.xsize(), black_with_small_lines.ysize()); ZeroFillImage(&black_with_small_lines); // This pattern should be picked up by the patch detection heuristics. for (size_t y = 0; y < black_with_small_lines.ysize(); y++) { float* JXL_RESTRICT row = black_with_small_lines.PlaneRow(1, y); for (size_t x = 0; x < black_with_small_lines.xsize(); x++) { if (x % 4 == 0 && (y / 32) % 4 == 0) row[x] = 127.0f; } } io.metadata.m.SetAlphaBits(8); io.SetFromImage(std::move(black_with_small_lines), ColorEncoding::LinearSRGB()); FillImage(1.0f, &alpha); io.Main().SetAlpha(std::move(alpha), /*alpha_is_premultiplied=*/false); CompressParams cparams; cparams.speed_tier = SpeedTier::kSquirrel; cparams.butteraugli_distance = 0.1f; DecompressParams dparams; CodecInOut io2; EXPECT_LE(Roundtrip(&io, cparams, dparams, pool, &io2), 2000u); EXPECT_LE(ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, pool), 0.5f); } TEST(JxlTest, RoundtripSmallPatches) { ThreadPool* pool = nullptr; CodecInOut io; io.metadata.m.color_encoding = ColorEncoding::LinearSRGB(); Image3F black_with_small_lines(256, 256); ZeroFillImage(&black_with_small_lines); // This pattern should be picked up by the patch detection heuristics. for (size_t y = 0; y < black_with_small_lines.ysize(); y++) { float* JXL_RESTRICT row = black_with_small_lines.PlaneRow(1, y); for (size_t x = 0; x < black_with_small_lines.xsize(); x++) { if (x % 4 == 0 && (y / 32) % 4 == 0) row[x] = 127.0f; } } io.SetFromImage(std::move(black_with_small_lines), ColorEncoding::LinearSRGB()); CompressParams cparams; cparams.speed_tier = SpeedTier::kSquirrel; cparams.butteraugli_distance = 0.1f; DecompressParams dparams; CodecInOut io2; EXPECT_LE(Roundtrip(&io, cparams, dparams, pool, &io2), 2000u); EXPECT_LE(ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, pool), 0.5f); } // Test header encoding of original bits per sample TEST(JxlTest, RoundtripImageBundleOriginalBits) { ThreadPool* pool = nullptr; // Image does not matter, only io.metadata.m and io2.metadata.m are tested. Image3F image(1, 1); ZeroFillImage(&image); CodecInOut io; io.metadata.m.color_encoding = ColorEncoding::LinearSRGB(); io.SetFromImage(std::move(image), ColorEncoding::LinearSRGB()); CompressParams cparams; DecompressParams dparams; // Test unsigned integers from 1 to 32 bits for (uint32_t bit_depth = 1; bit_depth <= 32; bit_depth++) { if (bit_depth == 32) { // TODO(lode): allow testing 32, however the code below ends up in // enc_modular which does not support 32. We only want to test the header // encoding though, so try without modular. break; } io.metadata.m.SetUintSamples(bit_depth); CodecInOut io2; Roundtrip(&io, cparams, dparams, pool, &io2); EXPECT_EQ(bit_depth, io2.metadata.m.bit_depth.bits_per_sample); EXPECT_FALSE(io2.metadata.m.bit_depth.floating_point_sample); EXPECT_EQ(0u, io2.metadata.m.bit_depth.exponent_bits_per_sample); EXPECT_EQ(0u, io2.metadata.m.GetAlphaBits()); } // Test various existing and non-existing floating point formats for (uint32_t bit_depth = 8; bit_depth <= 32; bit_depth++) { if (bit_depth != 32) { // TODO: test other float types once they work break; } uint32_t exponent_bit_depth; if (bit_depth < 10) { exponent_bit_depth = 2; } else if (bit_depth < 12) { exponent_bit_depth = 3; } else if (bit_depth < 16) { exponent_bit_depth = 4; } else if (bit_depth < 20) { exponent_bit_depth = 5; } else if (bit_depth < 24) { exponent_bit_depth = 6; } else if (bit_depth < 28) { exponent_bit_depth = 7; } else { exponent_bit_depth = 8; } io.metadata.m.bit_depth.bits_per_sample = bit_depth; io.metadata.m.bit_depth.floating_point_sample = true; io.metadata.m.bit_depth.exponent_bits_per_sample = exponent_bit_depth; CodecInOut io2; Roundtrip(&io, cparams, dparams, pool, &io2); EXPECT_EQ(bit_depth, io2.metadata.m.bit_depth.bits_per_sample); EXPECT_TRUE(io2.metadata.m.bit_depth.floating_point_sample); EXPECT_EQ(exponent_bit_depth, io2.metadata.m.bit_depth.exponent_bits_per_sample); EXPECT_EQ(0u, io2.metadata.m.GetAlphaBits()); } } TEST(JxlTest, RoundtripGrayscale) { ThreadPool* pool = nullptr; const PaddedBytes orig = ReadTestData("wesaturate/500px/cvo9xd_keong_macan_grayscale.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, pool)); ASSERT_NE(io.xsize(), 0u); io.ShrinkTo(128, 128); EXPECT_TRUE(io.Main().IsGray()); EXPECT_EQ(8u, io.metadata.m.bit_depth.bits_per_sample); EXPECT_FALSE(io.metadata.m.bit_depth.floating_point_sample); EXPECT_EQ(0u, io.metadata.m.bit_depth.exponent_bits_per_sample); EXPECT_TRUE(io.metadata.m.color_encoding.tf.IsSRGB()); PassesEncoderState enc_state; AuxOut* aux_out = nullptr; { CompressParams cparams; cparams.butteraugli_distance = 1.0; DecompressParams dparams; PaddedBytes compressed; EXPECT_TRUE( EncodeFile(cparams, &io, &enc_state, &compressed, aux_out, pool)); CodecInOut io2; EXPECT_TRUE(DecodeFile(dparams, compressed, &io2, pool)); EXPECT_TRUE(io2.Main().IsGray()); EXPECT_LE(compressed.size(), 7000u); EXPECT_LE(ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, pool), 1.7777777); } // Test with larger butteraugli distance and other settings enabled so // different jxl codepaths trigger. { CompressParams cparams; cparams.butteraugli_distance = 8.0; DecompressParams dparams; PaddedBytes compressed; EXPECT_TRUE( EncodeFile(cparams, &io, &enc_state, &compressed, aux_out, pool)); CodecInOut io2; EXPECT_TRUE(DecodeFile(dparams, compressed, &io2, pool)); EXPECT_TRUE(io2.Main().IsGray()); EXPECT_LE(compressed.size(), 1300u); EXPECT_LE(ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, pool), 9.0); } } TEST(JxlTest, RoundtripAlpha) { ThreadPool* pool = nullptr; const PaddedBytes orig = ReadTestData("wesaturate/500px/tmshre_riaphotographs_alpha.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, pool)); ASSERT_NE(io.xsize(), 0u); ASSERT_TRUE(io.metadata.m.HasAlpha()); ASSERT_TRUE(io.Main().HasAlpha()); io.ShrinkTo(300, 300); CompressParams cparams; cparams.butteraugli_distance = 1.0; DecompressParams dparams; EXPECT_EQ(8u, io.metadata.m.bit_depth.bits_per_sample); EXPECT_FALSE(io.metadata.m.bit_depth.floating_point_sample); EXPECT_EQ(0u, io.metadata.m.bit_depth.exponent_bits_per_sample); EXPECT_TRUE(io.metadata.m.color_encoding.tf.IsSRGB()); PassesEncoderState enc_state; AuxOut* aux_out = nullptr; PaddedBytes compressed; EXPECT_TRUE(EncodeFile(cparams, &io, &enc_state, &compressed, aux_out, pool)); CodecInOut io2; EXPECT_TRUE(DecodeFile(dparams, compressed, &io2, pool)); EXPECT_LE(compressed.size(), 10077u); EXPECT_LE(ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, pool), 1.4); } TEST(JxlTest, RoundtripAlphaPremultiplied) { ThreadPool* pool = nullptr; const PaddedBytes orig = ReadTestData("wesaturate/500px/tmshre_riaphotographs_alpha.png"); CodecInOut io, io_nopremul; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, pool)); ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io_nopremul, pool)); ASSERT_NE(io.xsize(), 0u); ASSERT_TRUE(io.metadata.m.HasAlpha()); ASSERT_TRUE(io.Main().HasAlpha()); io.ShrinkTo(300, 300); io_nopremul.ShrinkTo(300, 300); CompressParams cparams; cparams.butteraugli_distance = 1.0; DecompressParams dparams; io.PremultiplyAlpha(); EXPECT_TRUE(io.Main().AlphaIsPremultiplied()); PassesEncoderState enc_state; AuxOut* aux_out = nullptr; PaddedBytes compressed; EXPECT_TRUE(EncodeFile(cparams, &io, &enc_state, &compressed, aux_out, pool)); CodecInOut io2; EXPECT_TRUE(DecodeFile(dparams, compressed, &io2, pool)); EXPECT_LE(compressed.size(), 10000u); EXPECT_LE(ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, pool), 1.4); io2.Main().UnpremultiplyAlpha(); EXPECT_LE(ButteraugliDistance(io_nopremul, io2, cparams.ba_params, /*distmap=*/nullptr, pool), 1.8); } TEST(JxlTest, RoundtripAlphaResampling) { ThreadPool* pool = nullptr; const PaddedBytes orig = ReadTestData("wesaturate/500px/tmshre_riaphotographs_alpha.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, pool)); ASSERT_NE(io.xsize(), 0u); ASSERT_TRUE(io.metadata.m.HasAlpha()); ASSERT_TRUE(io.Main().HasAlpha()); CompressParams cparams; cparams.resampling = 2; cparams.ec_resampling = 2; cparams.butteraugli_distance = 1.0; DecompressParams dparams; PassesEncoderState enc_state; AuxOut* aux_out = nullptr; PaddedBytes compressed; EXPECT_TRUE(EncodeFile(cparams, &io, &enc_state, &compressed, aux_out, pool)); CodecInOut io2; EXPECT_TRUE(DecodeFile(dparams, compressed, &io2, pool)); EXPECT_LE(compressed.size(), 15000u); EXPECT_LE(ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, pool), 6.0); } TEST(JxlTest, RoundtripAlphaResamplingOnlyAlpha) { ThreadPool* pool = nullptr; const PaddedBytes orig = ReadTestData("wesaturate/500px/tmshre_riaphotographs_alpha.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, pool)); ASSERT_NE(io.xsize(), 0u); ASSERT_TRUE(io.metadata.m.HasAlpha()); ASSERT_TRUE(io.Main().HasAlpha()); CompressParams cparams; cparams.ec_resampling = 2; cparams.butteraugli_distance = 1.0; DecompressParams dparams; PassesEncoderState enc_state; AuxOut* aux_out = nullptr; PaddedBytes compressed; EXPECT_TRUE(EncodeFile(cparams, &io, &enc_state, &compressed, aux_out, pool)); CodecInOut io2; EXPECT_TRUE(DecodeFile(dparams, compressed, &io2, pool)); EXPECT_LE(compressed.size(), 31000u); EXPECT_LE(ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, pool), 1.5); } TEST(JxlTest, RoundtripAlphaNonMultipleOf8) { ThreadPool* pool = nullptr; const PaddedBytes orig = ReadTestData("wesaturate/500px/tmshre_riaphotographs_alpha.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, pool)); ASSERT_NE(io.xsize(), 0u); ASSERT_TRUE(io.metadata.m.HasAlpha()); ASSERT_TRUE(io.Main().HasAlpha()); io.ShrinkTo(12, 12); CompressParams cparams; cparams.butteraugli_distance = 1.0; DecompressParams dparams; EXPECT_EQ(8u, io.metadata.m.bit_depth.bits_per_sample); EXPECT_FALSE(io.metadata.m.bit_depth.floating_point_sample); EXPECT_EQ(0u, io.metadata.m.bit_depth.exponent_bits_per_sample); EXPECT_TRUE(io.metadata.m.color_encoding.tf.IsSRGB()); PassesEncoderState enc_state; AuxOut* aux_out = nullptr; PaddedBytes compressed; EXPECT_TRUE(EncodeFile(cparams, &io, &enc_state, &compressed, aux_out, pool)); CodecInOut io2; EXPECT_TRUE(DecodeFile(dparams, compressed, &io2, pool)); EXPECT_LE(compressed.size(), 200u); // TODO(robryk): Fix the following line in presence of different alpha_bits in // the two contexts. // EXPECT_TRUE(SamePixels(io.Main().alpha(), io2.Main().alpha())); // TODO(robryk): Fix the distance estimate used in the encoder. EXPECT_LE(ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, pool), 6.3); } TEST(JxlTest, RoundtripAlpha16) { ThreadPoolInternal pool(4); size_t xsize = 1200, ysize = 160; Image3F color(xsize, ysize); ImageF alpha(xsize, ysize); // Generate 16-bit pattern that uses various colors and alpha values. for (size_t y = 0; y < ysize; y++) { for (size_t x = 0; x < xsize; x++) { color.PlaneRow(0, y)[x] = (y * 65535 / ysize) * (1.0f / 65535); color.PlaneRow(1, y)[x] = (x * 65535 / xsize) * (1.0f / 65535); color.PlaneRow(2, y)[x] = ((y + x) * 65535 / (xsize + ysize)) * (1.0f / 65535); alpha.Row(y)[x] = (x * 65535 / xsize) * (1.0f / 65535); } } const bool is_gray = false; CodecInOut io; io.metadata.m.SetUintSamples(16); io.metadata.m.SetAlphaBits(16); io.metadata.m.color_encoding = ColorEncoding::SRGB(is_gray); io.SetFromImage(std::move(color), io.metadata.m.color_encoding); io.Main().SetAlpha(std::move(alpha), /*alpha_is_premultiplied=*/false); // The image is wider than 512 pixels to ensure multiple groups are tested. ASSERT_NE(io.xsize(), 0u); ASSERT_TRUE(io.metadata.m.HasAlpha()); ASSERT_TRUE(io.Main().HasAlpha()); CompressParams cparams; cparams.butteraugli_distance = 0.5; // Prevent the test to be too slow, does not affect alpha cparams.speed_tier = SpeedTier::kSquirrel; DecompressParams dparams; io.metadata.m.SetUintSamples(16); EXPECT_TRUE(io.metadata.m.color_encoding.tf.IsSRGB()); PassesEncoderState enc_state; AuxOut* aux_out = nullptr; PaddedBytes compressed; EXPECT_TRUE( EncodeFile(cparams, &io, &enc_state, &compressed, aux_out, &pool)); CodecInOut io2; EXPECT_TRUE(DecodeFile(dparams, compressed, &io2, &pool)); EXPECT_TRUE(SamePixels(*io.Main().alpha(), *io2.Main().alpha())); } namespace { CompressParams CParamsForLossless() { CompressParams cparams; cparams.modular_mode = true; cparams.color_transform = jxl::ColorTransform::kNone; cparams.quality_pair = {100, 100}; cparams.options.predictor = {Predictor::Weighted}; return cparams; } } // namespace TEST(JxlTest, JXL_SLOW_TEST(RoundtripLossless8)) { ThreadPoolInternal pool(8); const PaddedBytes orig = ReadTestData("wesaturate/500px/tmshre_riaphotographs_srgb8.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, &pool)); CompressParams cparams = CParamsForLossless(); DecompressParams dparams; CodecInOut io2; EXPECT_LE(Roundtrip(&io, cparams, dparams, &pool, &io2), 3500000u); // If this test fails with a very close to 0.0 but not exactly 0.0 butteraugli // distance, then there is likely a floating point issue, that could be // happening either in io or io2. The values of io are generated by // external_image.cc, and those in io2 by the jxl decoder. If they use // slightly different floating point operations (say, one casts int to float // while other divides the int through 255.0f and later multiplies it by // 255 again) they will get slightly different values. To fix, ensure both // sides do the following formula for converting integer range 0-255 to // floating point range 0.0f-255.0f: static_cast<float>(i) // without any further intermediate operations. // Note that this precision issue is not a problem in practice if the values // are equal when rounded to 8-bit int, but currently full exact precision is // tested. EXPECT_EQ(0.0, ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, &pool)); } TEST(JxlTest, JXL_SLOW_TEST(RoundtripLosslessNoEncoderFastPathWP)) { ThreadPoolInternal pool(8); const PaddedBytes orig = ReadTestData("wesaturate/500px/tmshre_riaphotographs_srgb8.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, &pool)); CompressParams cparams = CParamsForLossless(); cparams.speed_tier = SpeedTier::kFalcon; cparams.options.skip_encoder_fast_path = true; DecompressParams dparams; CodecInOut io2; EXPECT_LE(Roundtrip(&io, cparams, dparams, &pool, &io2), 3500000u); EXPECT_EQ(0.0, ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, &pool)); } TEST(JxlTest, JXL_SLOW_TEST(RoundtripLosslessNoEncoderFastPathGradient)) { ThreadPoolInternal pool(8); const PaddedBytes orig = ReadTestData("wesaturate/500px/tmshre_riaphotographs_srgb8.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, &pool)); CompressParams cparams = CParamsForLossless(); cparams.speed_tier = SpeedTier::kThunder; cparams.options.skip_encoder_fast_path = true; cparams.options.predictor = {Predictor::Gradient}; DecompressParams dparams; CodecInOut io2; EXPECT_LE(Roundtrip(&io, cparams, dparams, &pool, &io2), 3500000u); EXPECT_EQ(0.0, ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, &pool)); } TEST(JxlTest, JXL_SLOW_TEST(RoundtripLosslessNoEncoderVeryFastPathGradient)) { ThreadPoolInternal pool(8); const PaddedBytes orig = ReadTestData("wesaturate/500px/tmshre_riaphotographs_srgb8.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, &pool)); CompressParams cparams = CParamsForLossless(); cparams.speed_tier = SpeedTier::kLightning; cparams.options.skip_encoder_fast_path = true; cparams.options.predictor = {Predictor::Gradient}; DecompressParams dparams; CodecInOut io2, io3; EXPECT_LE(Roundtrip(&io, cparams, dparams, &pool, &io2), 3500000u); EXPECT_EQ(0.0, ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, &pool)); cparams.options.skip_encoder_fast_path = false; EXPECT_LE(Roundtrip(&io, cparams, dparams, &pool, &io3), 3500000u); EXPECT_EQ(0.0, ButteraugliDistance(io, io3, cparams.ba_params, /*distmap=*/nullptr, &pool)); } TEST(JxlTest, JXL_SLOW_TEST(RoundtripLossless8Falcon)) { ThreadPoolInternal pool(8); const PaddedBytes orig = ReadTestData("wesaturate/500px/tmshre_riaphotographs_srgb8.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, &pool)); CompressParams cparams = CParamsForLossless(); cparams.speed_tier = SpeedTier::kFalcon; DecompressParams dparams; CodecInOut io2; EXPECT_LE(Roundtrip(&io, cparams, dparams, &pool, &io2), 3500000u); EXPECT_EQ(0.0, ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, &pool)); } TEST(JxlTest, RoundtripLossless8Alpha) { ThreadPool* pool = nullptr; const PaddedBytes orig = ReadTestData("wesaturate/500px/tmshre_riaphotographs_alpha.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, pool)); EXPECT_EQ(8u, io.metadata.m.GetAlphaBits()); EXPECT_EQ(8u, io.metadata.m.bit_depth.bits_per_sample); EXPECT_FALSE(io.metadata.m.bit_depth.floating_point_sample); EXPECT_EQ(0u, io.metadata.m.bit_depth.exponent_bits_per_sample); CompressParams cparams = CParamsForLossless(); DecompressParams dparams; CodecInOut io2; EXPECT_LE(Roundtrip(&io, cparams, dparams, pool, &io2), 350000u); // If fails, see note about floating point in RoundtripLossless8. EXPECT_EQ(0.0, ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, pool)); EXPECT_TRUE(SamePixels(*io.Main().alpha(), *io2.Main().alpha())); EXPECT_EQ(8u, io2.metadata.m.GetAlphaBits()); EXPECT_EQ(8u, io2.metadata.m.bit_depth.bits_per_sample); EXPECT_FALSE(io2.metadata.m.bit_depth.floating_point_sample); EXPECT_EQ(0u, io2.metadata.m.bit_depth.exponent_bits_per_sample); } TEST(JxlTest, RoundtripLossless16Alpha) { ThreadPool* pool = nullptr; size_t xsize = 1200, ysize = 160; Image3F color(xsize, ysize); ImageF alpha(xsize, ysize); // Generate 16-bit pattern that uses various colors and alpha values. for (size_t y = 0; y < ysize; y++) { for (size_t x = 0; x < xsize; x++) { color.PlaneRow(0, y)[x] = (y * 65535 / ysize) * (1.0f / 65535); color.PlaneRow(1, y)[x] = (x * 65535 / xsize) * (1.0f / 65535); color.PlaneRow(2, y)[x] = ((y + x) * 65535 / (xsize + ysize)) * (1.0f / 65535); alpha.Row(y)[x] = (x * 65535 / xsize) * (1.0f / 65535); } } const bool is_gray = false; CodecInOut io; io.metadata.m.SetUintSamples(16); io.metadata.m.SetAlphaBits(16); io.metadata.m.color_encoding = ColorEncoding::SRGB(is_gray); io.SetFromImage(std::move(color), io.metadata.m.color_encoding); io.Main().SetAlpha(std::move(alpha), /*alpha_is_premultiplied=*/false); EXPECT_EQ(16u, io.metadata.m.GetAlphaBits()); EXPECT_EQ(16u, io.metadata.m.bit_depth.bits_per_sample); EXPECT_FALSE(io.metadata.m.bit_depth.floating_point_sample); EXPECT_EQ(0u, io.metadata.m.bit_depth.exponent_bits_per_sample); CompressParams cparams = CParamsForLossless(); DecompressParams dparams; CodecInOut io2; EXPECT_LE(Roundtrip(&io, cparams, dparams, pool, &io2), 7100u); // If this test fails with a very close to 0.0 but not exactly 0.0 butteraugli // distance, then there is likely a floating point issue, that could be // happening either in io or io2. The values of io are generated by // external_image.cc, and those in io2 by the jxl decoder. If they use // slightly different floating point operations (say, one does "i / 257.0f" // while the other does "i * (1.0f / 257)" they will get slightly different // values. To fix, ensure both sides do the following formula for converting // integer range 0-65535 to Image3F floating point range 0.0f-255.0f: // "i * (1.0f / 257)". // Note that this precision issue is not a problem in practice if the values // are equal when rounded to 16-bit int, but currently full exact precision is // tested. EXPECT_EQ(0.0, ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, pool)); EXPECT_TRUE(SamePixels(*io.Main().alpha(), *io2.Main().alpha())); EXPECT_EQ(16u, io2.metadata.m.GetAlphaBits()); EXPECT_EQ(16u, io2.metadata.m.bit_depth.bits_per_sample); EXPECT_FALSE(io2.metadata.m.bit_depth.floating_point_sample); EXPECT_EQ(0u, io2.metadata.m.bit_depth.exponent_bits_per_sample); } TEST(JxlTest, RoundtripLossless16AlphaNotMisdetectedAs8Bit) { ThreadPool* pool = nullptr; size_t xsize = 128, ysize = 128; Image3F color(xsize, ysize); ImageF alpha(xsize, ysize); // All 16-bit values, both color and alpha, of this image are below 64. // This allows testing if a code path wrongly concludes it's an 8-bit instead // of 16-bit image (or even 6-bit). for (size_t y = 0; y < ysize; y++) { for (size_t x = 0; x < xsize; x++) { color.PlaneRow(0, y)[x] = (y * 64 / ysize) * (1.0f / 65535); color.PlaneRow(1, y)[x] = (x * 64 / xsize) * (1.0f / 65535); color.PlaneRow(2, y)[x] = ((y + x) * 64 / (xsize + ysize)) * (1.0f / 65535); alpha.Row(y)[x] = (64 * x / xsize) * (1.0f / 65535); } } const bool is_gray = false; CodecInOut io; io.metadata.m.SetUintSamples(16); io.metadata.m.SetAlphaBits(16); io.metadata.m.color_encoding = ColorEncoding::SRGB(is_gray); io.SetFromImage(std::move(color), io.metadata.m.color_encoding); io.Main().SetAlpha(std::move(alpha), /*alpha_is_premultiplied=*/false); EXPECT_EQ(16u, io.metadata.m.GetAlphaBits()); EXPECT_EQ(16u, io.metadata.m.bit_depth.bits_per_sample); EXPECT_FALSE(io.metadata.m.bit_depth.floating_point_sample); EXPECT_EQ(0u, io.metadata.m.bit_depth.exponent_bits_per_sample); CompressParams cparams = CParamsForLossless(); DecompressParams dparams; CodecInOut io2; EXPECT_LE(Roundtrip(&io, cparams, dparams, pool, &io2), 3100u); EXPECT_EQ(16u, io2.metadata.m.GetAlphaBits()); EXPECT_EQ(16u, io2.metadata.m.bit_depth.bits_per_sample); EXPECT_FALSE(io2.metadata.m.bit_depth.floating_point_sample); EXPECT_EQ(0u, io2.metadata.m.bit_depth.exponent_bits_per_sample); // If fails, see note about floating point in RoundtripLossless8. EXPECT_EQ(0.0, ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, pool)); EXPECT_TRUE(SamePixels(*io.Main().alpha(), *io2.Main().alpha())); } TEST(JxlTest, RoundtripYCbCr420) { ThreadPool* pool = nullptr; const PaddedBytes orig = ReadTestData("imagecompression.info/flower_foveon.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, pool)); const PaddedBytes yuv420 = ReadTestData("imagecompression.info/flower_foveon.png.ffmpeg.y4m"); CodecInOut io2; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(yuv420), &io2, pool)); CompressParams cparams = CParamsForLossless(); cparams.speed_tier = SpeedTier::kThunder; DecompressParams dparams; PassesEncoderState enc_state; AuxOut* aux_out = nullptr; PaddedBytes compressed; EXPECT_TRUE( EncodeFile(cparams, &io2, &enc_state, &compressed, aux_out, pool)); CodecInOut io3; EXPECT_TRUE(DecodeFile(dparams, compressed, &io3, pool)); EXPECT_LE(compressed.size(), 1320000u); // we're comparing an original PNG with a YCbCr 4:2:0 version EXPECT_LE(ButteraugliDistance(io, io3, cparams.ba_params, /*distmap=*/nullptr, pool), 2.8); } TEST(JxlTest, RoundtripDots) { ThreadPool* pool = nullptr; const PaddedBytes orig = ReadTestData("wesaturate/500px/cvo9xd_keong_macan_srgb8.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, pool)); ASSERT_NE(io.xsize(), 0u); CompressParams cparams; cparams.dots = Override::kOn; cparams.butteraugli_distance = 0.04; cparams.speed_tier = SpeedTier::kSquirrel; DecompressParams dparams; EXPECT_EQ(8u, io.metadata.m.bit_depth.bits_per_sample); EXPECT_EQ(0u, io.metadata.m.bit_depth.exponent_bits_per_sample); EXPECT_FALSE(io.metadata.m.bit_depth.floating_point_sample); EXPECT_TRUE(io.metadata.m.color_encoding.tf.IsSRGB()); PassesEncoderState enc_state; AuxOut* aux_out = nullptr; PaddedBytes compressed; EXPECT_TRUE(EncodeFile(cparams, &io, &enc_state, &compressed, aux_out, pool)); CodecInOut io2; EXPECT_TRUE(DecodeFile(dparams, compressed, &io2, pool)); EXPECT_LE(compressed.size(), 400000u); EXPECT_LE(ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, pool), 2.2); } TEST(JxlTest, RoundtripNoise) { ThreadPool* pool = nullptr; const PaddedBytes orig = ReadTestData("wesaturate/500px/cvo9xd_keong_macan_srgb8.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, pool)); ASSERT_NE(io.xsize(), 0u); CompressParams cparams; cparams.noise = Override::kOn; cparams.speed_tier = SpeedTier::kSquirrel; DecompressParams dparams; EXPECT_EQ(8u, io.metadata.m.bit_depth.bits_per_sample); EXPECT_EQ(0u, io.metadata.m.bit_depth.exponent_bits_per_sample); EXPECT_FALSE(io.metadata.m.bit_depth.floating_point_sample); EXPECT_TRUE(io.metadata.m.color_encoding.tf.IsSRGB()); PassesEncoderState enc_state; AuxOut* aux_out = nullptr; PaddedBytes compressed; EXPECT_TRUE(EncodeFile(cparams, &io, &enc_state, &compressed, aux_out, pool)); CodecInOut io2; EXPECT_TRUE(DecodeFile(dparams, compressed, &io2, pool)); EXPECT_LE(compressed.size(), 40000u); EXPECT_LE(ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, pool), 2.2); } TEST(JxlTest, RoundtripLossless8Gray) { ThreadPool* pool = nullptr; const PaddedBytes orig = ReadTestData("wesaturate/500px/cvo9xd_keong_macan_grayscale.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, pool)); CompressParams cparams = CParamsForLossless(); DecompressParams dparams; EXPECT_TRUE(io.Main().IsGray()); EXPECT_EQ(8u, io.metadata.m.bit_depth.bits_per_sample); EXPECT_FALSE(io.metadata.m.bit_depth.floating_point_sample); EXPECT_EQ(0u, io.metadata.m.bit_depth.exponent_bits_per_sample); CodecInOut io2; EXPECT_LE(Roundtrip(&io, cparams, dparams, pool, &io2), 130000u); // If fails, see note about floating point in RoundtripLossless8. EXPECT_EQ(0.0, ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, pool)); EXPECT_TRUE(io2.Main().IsGray()); EXPECT_EQ(8u, io2.metadata.m.bit_depth.bits_per_sample); EXPECT_FALSE(io2.metadata.m.bit_depth.floating_point_sample); EXPECT_EQ(0u, io2.metadata.m.bit_depth.exponent_bits_per_sample); } #if JPEGXL_ENABLE_GIF TEST(JxlTest, RoundtripAnimation) { ThreadPool* pool = nullptr; const PaddedBytes orig = ReadTestData("jxl/traffic_light.gif"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, pool)); ASSERT_EQ(4u, io.frames.size()); CompressParams cparams; DecompressParams dparams; CodecInOut io2; EXPECT_LE(Roundtrip(&io, cparams, dparams, pool, &io2), 3000u); EXPECT_EQ(io2.frames.size(), io.frames.size()); test::CoalesceGIFAnimationWithAlpha(&io); EXPECT_LE(ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, pool), #if JXL_HIGH_PRECISION 1.55); #else 1.75); #endif } TEST(JxlTest, RoundtripLosslessAnimation) { ThreadPool* pool = nullptr; const PaddedBytes orig = ReadTestData("jxl/traffic_light.gif"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, pool)); ASSERT_EQ(4u, io.frames.size()); CompressParams cparams = CParamsForLossless(); DecompressParams dparams; CodecInOut io2; EXPECT_LE(Roundtrip(&io, cparams, dparams, pool, &io2), 1200u); EXPECT_EQ(io2.frames.size(), io.frames.size()); test::CoalesceGIFAnimationWithAlpha(&io); EXPECT_LE(ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, pool), 5e-4); } #endif // JPEGXL_ENABLE_GIF #if JPEGXL_ENABLE_JPEG namespace { jxl::Status DecompressJxlToJPEGForTest( const jpegxl::tools::JpegXlContainer& container, jxl::ThreadPool* pool, jxl::PaddedBytes* output) { output->clear(); jxl::Span<const uint8_t> compressed(container.codestream, container.codestream_size); JXL_RETURN_IF_ERROR(compressed.size() >= 2); // JXL case // Decode to DCT when possible and generate a JPG file. jxl::CodecInOut io; jxl::DecompressParams params; params.keep_dct = true; if (!jpegxl::tools::DecodeJpegXlToJpeg(params, container, &io, pool)) { return JXL_FAILURE("Failed to decode JXL to JPEG"); } io.jpeg_quality = 95; if (!extras::EncodeImageJPGCoefficients(&io, output)) { return JXL_FAILURE("Failed to generate JPEG"); } return true; } } // namespace size_t RoundtripJpeg(const PaddedBytes& jpeg_in, ThreadPool* pool) { CodecInOut io; io.dec_target = jxl::DecodeTarget::kQuantizedCoeffs; EXPECT_TRUE(SetFromBytes(Span<const uint8_t>(jpeg_in), &io, pool)); CompressParams cparams; cparams.color_transform = jxl::ColorTransform::kYCbCr; PassesEncoderState passes_enc_state; PaddedBytes compressed, codestream; EXPECT_TRUE(EncodeFile(cparams, &io, &passes_enc_state, &codestream, /*aux_out=*/nullptr, pool)); jpegxl::tools::JpegXlContainer enc_container; enc_container.codestream = codestream.data(); enc_container.codestream_size = codestream.size(); jpeg::JPEGData data_in = *io.Main().jpeg_data; jxl::PaddedBytes jpeg_data; EXPECT_TRUE(EncodeJPEGData(data_in, &jpeg_data)); enc_container.jpeg_reconstruction = jpeg_data.data(); enc_container.jpeg_reconstruction_size = jpeg_data.size(); EXPECT_TRUE(EncodeJpegXlContainerOneShot(enc_container, &compressed)); jpegxl::tools::JpegXlContainer container; EXPECT_TRUE(DecodeJpegXlContainerOneShot(compressed.data(), compressed.size(), &container)); PaddedBytes out; EXPECT_TRUE(DecompressJxlToJPEGForTest(container, pool, &out)); EXPECT_EQ(out.size(), jpeg_in.size()); size_t failures = 0; for (size_t i = 0; i < std::min(out.size(), jpeg_in.size()); i++) { if (out[i] != jpeg_in[i]) { EXPECT_EQ(out[i], jpeg_in[i]) << "byte mismatch " << i << " " << out[i] << " != " << jpeg_in[i]; if (++failures > 4) { return compressed.size(); } } } return compressed.size(); } TEST(JxlTest, JXL_TRANSCODE_JPEG_TEST(RoundtripJpegRecompression444)) { ThreadPoolInternal pool(8); const PaddedBytes orig = ReadTestData("imagecompression.info/flower_foveon.png.im_q85_444.jpg"); // JPEG size is 326'916 bytes. EXPECT_LE(RoundtripJpeg(orig, &pool), 256000u); } TEST(JxlTest, JXL_TRANSCODE_JPEG_TEST(RoundtripJpegRecompressionToPixels)) { ThreadPoolInternal pool(8); const PaddedBytes orig = ReadTestData("imagecompression.info/flower_foveon.png.im_q85_444.jpg"); CodecInOut io; io.dec_target = jxl::DecodeTarget::kQuantizedCoeffs; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, &pool)); CodecInOut io2; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io2, &pool)); CompressParams cparams; cparams.color_transform = jxl::ColorTransform::kYCbCr; DecompressParams dparams; CodecInOut io3; Roundtrip(&io, cparams, dparams, &pool, &io3); // TODO(eustas): investigate, why SJPEG and JpegRecompression pixels are // different. EXPECT_GE(1.8, ButteraugliDistance(io2, io3, cparams.ba_params, /*distmap=*/nullptr, &pool)); } TEST(JxlTest, JXL_TRANSCODE_JPEG_TEST(RoundtripJpegRecompressionToPixels420)) { ThreadPoolInternal pool(8); const PaddedBytes orig = ReadTestData("imagecompression.info/flower_foveon.png.im_q85_420.jpg"); CodecInOut io; io.dec_target = jxl::DecodeTarget::kQuantizedCoeffs; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, &pool)); CodecInOut io2; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io2, &pool)); CompressParams cparams; cparams.color_transform = jxl::ColorTransform::kYCbCr; DecompressParams dparams; CodecInOut io3; Roundtrip(&io, cparams, dparams, &pool, &io3); EXPECT_GE(1.5, ButteraugliDistance(io2, io3, cparams.ba_params, /*distmap=*/nullptr, &pool)); } TEST(JxlTest, JXL_TRANSCODE_JPEG_TEST(RoundtripJpegRecompressionToPixels420Mul16)) { ThreadPoolInternal pool(8); const PaddedBytes orig = ReadTestData("imagecompression.info/flower_foveon_cropped.jpg"); CodecInOut io; io.dec_target = jxl::DecodeTarget::kQuantizedCoeffs; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, &pool)); CodecInOut io2; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io2, &pool)); CompressParams cparams; cparams.color_transform = jxl::ColorTransform::kYCbCr; DecompressParams dparams; CodecInOut io3; Roundtrip(&io, cparams, dparams, &pool, &io3); EXPECT_GE(1.5, ButteraugliDistance(io2, io3, cparams.ba_params, /*distmap=*/nullptr, &pool)); } TEST(JxlTest, JXL_TRANSCODE_JPEG_TEST(RoundtripJpegRecompressionToPixels_asymmetric)) { ThreadPoolInternal pool(8); const PaddedBytes orig = ReadTestData( "imagecompression.info/flower_foveon.png.im_q85_asymmetric.jpg"); CodecInOut io; io.dec_target = jxl::DecodeTarget::kQuantizedCoeffs; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, &pool)); CodecInOut io2; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io2, &pool)); CompressParams cparams; cparams.color_transform = jxl::ColorTransform::kYCbCr; DecompressParams dparams; CodecInOut io3; Roundtrip(&io, cparams, dparams, &pool, &io3); EXPECT_GE(1.5, ButteraugliDistance(io2, io3, cparams.ba_params, /*distmap=*/nullptr, &pool)); } TEST(JxlTest, JXL_TRANSCODE_JPEG_TEST(RoundtripJpegRecompressionGray)) { ThreadPoolInternal pool(8); const PaddedBytes orig = ReadTestData("imagecompression.info/flower_foveon.png.im_q85_gray.jpg"); // JPEG size is 167'025 bytes. EXPECT_LE(RoundtripJpeg(orig, &pool), 140000u); } TEST(JxlTest, JXL_TRANSCODE_JPEG_TEST(RoundtripJpegRecompression420)) { ThreadPoolInternal pool(8); const PaddedBytes orig = ReadTestData("imagecompression.info/flower_foveon.png.im_q85_420.jpg"); // JPEG size is 226'018 bytes. EXPECT_LE(RoundtripJpeg(orig, &pool), 181050u); } TEST(JxlTest, JXL_TRANSCODE_JPEG_TEST(RoundtripJpegRecompression_luma_subsample)) { ThreadPoolInternal pool(8); const PaddedBytes orig = ReadTestData( "imagecompression.info/flower_foveon.png.im_q85_luma_subsample.jpg"); // JPEG size is 216'069 bytes. EXPECT_LE(RoundtripJpeg(orig, &pool), 181000u); } TEST(JxlTest, JXL_TRANSCODE_JPEG_TEST(RoundtripJpegRecompression444_12)) { // 444 JPEG that has an interesting sampling-factor (1x2, 1x2, 1x2). ThreadPoolInternal pool(8); const PaddedBytes orig = ReadTestData( "imagecompression.info/flower_foveon.png.im_q85_444_1x2.jpg"); // JPEG size is 329'942 bytes. EXPECT_LE(RoundtripJpeg(orig, &pool), 256000u); } TEST(JxlTest, JXL_TRANSCODE_JPEG_TEST(RoundtripJpegRecompression422)) { ThreadPoolInternal pool(8); const PaddedBytes orig = ReadTestData("imagecompression.info/flower_foveon.png.im_q85_422.jpg"); // JPEG size is 265'590 bytes. EXPECT_LE(RoundtripJpeg(orig, &pool), 209000u); } TEST(JxlTest, JXL_TRANSCODE_JPEG_TEST(RoundtripJpegRecompression440)) { ThreadPoolInternal pool(8); const PaddedBytes orig = ReadTestData("imagecompression.info/flower_foveon.png.im_q85_440.jpg"); // JPEG size is 262'249 bytes. EXPECT_LE(RoundtripJpeg(orig, &pool), 209000u); } TEST(JxlTest, JXL_TRANSCODE_JPEG_TEST(RoundtripJpegRecompression_asymmetric)) { // 2x vertical downsample of one chroma channel, 2x horizontal downsample of // the other. ThreadPoolInternal pool(8); const PaddedBytes orig = ReadTestData( "imagecompression.info/flower_foveon.png.im_q85_asymmetric.jpg"); // JPEG size is 262'249 bytes. EXPECT_LE(RoundtripJpeg(orig, &pool), 209000u); } TEST(JxlTest, JXL_TRANSCODE_JPEG_TEST(RoundtripJpegRecompression420Progr)) { ThreadPoolInternal pool(8); const PaddedBytes orig = ReadTestData( "imagecompression.info/flower_foveon.png.im_q85_420_progr.jpg"); EXPECT_LE(RoundtripJpeg(orig, &pool), 181000u); } #endif // JPEGXL_ENABLE_JPEG TEST(JxlTest, RoundtripProgressive) { ThreadPoolInternal pool(4); const PaddedBytes orig = ReadTestData("imagecompression.info/flower_foveon.png"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, &pool)); io.ShrinkTo(600, 1024); CompressParams cparams; DecompressParams dparams; cparams.butteraugli_distance = 1.0f; cparams.progressive_dc = true; cparams.responsive = true; cparams.progressive_mode = true; CodecInOut io2; EXPECT_LE(Roundtrip(&io, cparams, dparams, &pool, &io2), 40000u); EXPECT_LE(ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, &pool), 4.0f); } TEST(JxlTest, RoundtripAnimationPatches) { ThreadPool* pool = nullptr; const PaddedBytes orig = ReadTestData("jxl/animation_patches.gif"); CodecInOut io; ASSERT_TRUE(SetFromBytes(Span<const uint8_t>(orig), &io, pool)); ASSERT_EQ(2u, io.frames.size()); CompressParams cparams; cparams.patches = Override::kOn; DecompressParams dparams; CodecInOut io2; // 40k with no patches, 27k with patch frames encoded multiple times. EXPECT_LE(Roundtrip(&io, cparams, dparams, pool, &io2), 24000u); EXPECT_EQ(io2.frames.size(), io.frames.size()); // >10 with broken patches EXPECT_LE(ButteraugliDistance(io, io2, cparams.ba_params, /*distmap=*/nullptr, pool), 2.0); } } // namespace } // namespace jxl
34.878453
80
0.700002
[ "vector" ]
4f6fe44aae80b51edf4d3dffb43608dcbfd4ee72
6,530
cc
C++
src/metadata_repo.cc
kev0960/md2
f8480b664b1111f3f5d4b5202fb2b5db3ee434bd
[ "MIT" ]
5
2021-01-27T03:55:00.000Z
2022-03-07T02:35:37.000Z
src/metadata_repo.cc
kev0960/md2
f8480b664b1111f3f5d4b5202fb2b5db3ee434bd
[ "MIT" ]
null
null
null
src/metadata_repo.cc
kev0960/md2
f8480b664b1111f3f5d4b5202fb2b5db3ee434bd
[ "MIT" ]
null
null
null
#include "metadata_repo.h" #include <nlohmann/json.hpp> #include <unordered_set> #include "string_util.h" namespace md2 { namespace { using json = nlohmann::json; std::string ConvertPathnameToFilename(std::string_view path_name) { // Instruction name. if (!std::all_of(path_name.begin(), path_name.end(), isdigit) || path_name.empty()) { return StrCat(path_name, ".md"); } return StrCat(path_name, ".md"); } std::vector<std::string> PathToVec(std::string_view path) { std::vector<std::string> paths; size_t current = 0; while (true) { size_t delim = path.find('/', current); if (delim == std::string::npos) { paths.push_back(std::string(path.substr(current))); break; } paths.push_back(std::string(path.substr(current, delim - current))); current = delim + 1; } return paths; } void ConstructPathJson(json& path, const std::vector<std::string>& paths, size_t index, const std::string& file_name) { if (paths.size() == index) { path["files"].push_back(file_name); return; } // Every path should have "files" field. if (path["files"].empty()) { path["files"] = json::array(); } ConstructPathJson(path[paths[index]], paths, index + 1, file_name); } } // namespace bool MetadataRepo::RegisterMetadata(std::string_view filename, std::unique_ptr<Metadata> metadata) { // Do not register if the file is already there. if (repo_.count(std::string(filename))) { return false; } Metadata* metadata_ptr = metadata.get(); repo_[std::string(filename)] = std::move(metadata); for (const auto& ref : metadata_ptr->GetRefNames()) { auto ref_metadata_itr = ref_to_metadata_.find(ref); if (ref_metadata_itr == ref_to_metadata_.end()) { auto [itr, ok] = ref_to_metadata_.insert({ref, std::vector<const Metadata*>()}); ref_metadata_itr = itr; } ref_metadata_itr->second.push_back(metadata_ptr); } return true; } const Metadata* MetadataRepo::FindMetadata(std::string_view ref) const { std::string lowercase_ref; std::transform(ref.begin(), ref.end(), std::back_inserter(lowercase_ref), [](const char c) { return std::tolower(c); }); auto itr = ref_to_metadata_.find(lowercase_ref); if (itr == ref_to_metadata_.end()) { return nullptr; } if (itr->second.empty()) { return nullptr; } return itr->second.front(); } const Metadata* MetadataRepo::FindMetadata(std::string_view ref, std::string_view path) const { std::string lowercase_ref; std::transform(ref.begin(), ref.end(), std::back_inserter(lowercase_ref), [](const char c) { return std::tolower(c); }); auto itr = ref_to_metadata_.find(lowercase_ref); if (itr == ref_to_metadata_.end()) { return nullptr; } if (itr->second.empty()) { return nullptr; } for (const Metadata* metadata : itr->second) { if (metadata->GetPath().find(path) != std::string_view::npos) { return metadata; } } return nullptr; } const Metadata* MetadataRepo::FindMetadataByFilename( std::string_view filename) const { if (auto itr = repo_.find(std::string(filename)); itr != repo_.end()) { return itr->second.get(); } return nullptr; } const Metadata* MetadataRepo::FindMetadataByPathname( std::string_view filename) const { if (filename.empty()) { return nullptr; } return FindMetadataByFilename(ConvertPathnameToFilename(filename)); } std::string MetadataRepo::DumpFileHeaderAsJson() const { json file_headers; // Construct prev_page mapping. std::unordered_map<std::string, std::string> next_page_to_prev_map; for (auto& [file_name, metadata] : repo_) { next_page_to_prev_map[std::string(metadata->GetNextPage())] = NormalizeFileName(file_name); } for (auto& [file_name, metadata] : repo_) { json file; for (auto& [field_name, field] : metadata->GetAllFields()) { file[field_name] = field; } std::string normalized_file_name(NormalizeFileName(file_name)); if (auto itr = next_page_to_prev_map.find(normalized_file_name); itr != next_page_to_prev_map.end()) { file["prev_page"] = itr->second; } file_headers[normalized_file_name] = file; } return file_headers.dump(1); } std::string MetadataRepo::DumpPathAsJson() const { json path_db; std::vector<std::pair<std::string_view, const Metadata*>> file_and_metadata; file_and_metadata.reserve(repo_.size()); for (auto& [file_name, metadata] : repo_) { file_and_metadata.emplace_back(file_name, metadata.get()); } // Sort by the published date. std::sort(file_and_metadata.begin(), file_and_metadata.end(), [](const auto& left, const auto& right) { const Metadata* left_meta = left.second; const Metadata* right_meta = right.second; if (left_meta->GetPublishDate() == right_meta->GetPublishDate()) { return left_meta->GetTitle() < right_meta->GetTitle(); } return left_meta->GetPublishDate() < right_meta->GetPublishDate(); }); std::unordered_set<std::string_view> handled_files; handled_files.reserve(repo_.size()); for (auto& [file_name, metadata] : file_and_metadata) { std::string_view current_file = NormalizeFileName(file_name); if (handled_files.count(current_file)) { continue; } // Keep finding the next pages. const Metadata* current_meta = metadata; while (current_meta != nullptr) { std::string_view path = current_meta->GetPath(); auto paths = PathToVec(path); ConstructPathJson(path_db, paths, 0, std::string(current_file)); handled_files.insert(current_file); // Find the next page if exist. current_file = current_meta->GetNextPage(); current_meta = FindMetadataByPathname(current_file); // Break from errorneous loop. if (handled_files.count(current_file)) { break; } } } return path_db.dump(1); } std::string_view MetadataRepo::NormalizeFileName(std::string_view file_name) { size_t name_start = file_name.find_last_of("/"); if (name_start != std::string_view::npos) { file_name = file_name.substr(name_start + 1); } size_t ext_start = file_name.find_last_of("."); if (ext_start != std::string_view::npos) { file_name = file_name.substr(0, ext_start); } return file_name; } } // namespace md2
27.436975
80
0.65513
[ "vector", "transform" ]
4f700348e14fbf069e9e82b22dbc9afafe4c0cad
31,578
cpp
C++
src/zelnode/zelnode.cpp
blondfrogs/zelcash
3f4de3c68b9ce13175f5fc8e1d0a1f939cfbed3c
[ "MIT" ]
null
null
null
src/zelnode/zelnode.cpp
blondfrogs/zelcash
3f4de3c68b9ce13175f5fc8e1d0a1f939cfbed3c
[ "MIT" ]
null
null
null
src/zelnode/zelnode.cpp
blondfrogs/zelcash
3f4de3c68b9ce13175f5fc8e1d0a1f939cfbed3c
[ "MIT" ]
null
null
null
// Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2019 The PIVX developers // Copyright (c) 2019 The Zel developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <consensus/validation.h> #include "zelnode/zelnode.h" #include "addrman.h" #include "zelnode/zelnodeman.h" #include "zelnode/obfuscation.h" #include "sync.h" #include "util.h" #include "key_io.h" #include "spork.h" #include "zelnode/benchmarks.h" // keep track of the scanning errors I've seen map<uint256, int> mapSeenZelnodeScanningErrors; // cache block hashes as we calculate them std::map<int64_t, uint256> mapCacheBlockHashes; //Get the last hash that matches the modulus given. Processed in reverse order bool GetBlockHash(uint256& hash, int nBlockHeight) { if (chainActive.Tip() == NULL) return false; if (nBlockHeight == 0) nBlockHeight = chainActive.Tip()->nHeight; if (mapCacheBlockHashes.count(nBlockHeight)) { hash = mapCacheBlockHashes[nBlockHeight]; return true; } const CBlockIndex* BlockLastSolved = chainActive.Tip(); const CBlockIndex* BlockReading = chainActive.Tip(); if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || chainActive.Tip()->nHeight + 1 < nBlockHeight) return false; int nBlocksAgo = 0; if (nBlockHeight > 0) nBlocksAgo = (chainActive.Tip()->nHeight + 1) - nBlockHeight; assert(nBlocksAgo >= 0); int n = 0; for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) { if (n >= nBlocksAgo) { hash = BlockReading->GetBlockHash(); mapCacheBlockHashes[nBlockHeight] = hash; return true; } n++; if (BlockReading->pprev == NULL) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } return false; } Zelnode::Zelnode() { LOCK(cs); vin = CTxIn(); addr = CService(); pubKeyCollateralAddress = CPubKey(); pubKeyZelnode = CPubKey(); sig = std::vector<unsigned char>(); activeState = ZELNODE_ENABLED; sigTime = GetAdjustedTime(); lastPing = ZelnodePing(); cacheInputAge = 0; cacheInputAgeBlock = 0; unitTest = false; allowFreeTx = true; nActiveState = ZELNODE_ENABLED, protocolVersion = PROTOCOL_VERSION; nLastDsq = 0; nScanningErrorCount = 0; nLastScanningErrorBlockHeight = 0; lastTimeChecked = 0; tier = NONE; nLastDsee = 0; // temporary, do not save. Remove after migration to v12 nLastDseep = 0; // temporary, do not save. Remove after migration to v12 } Zelnode::Zelnode(const Zelnode& other) { LOCK(cs); vin = other.vin; addr = other.addr; pubKeyCollateralAddress = other.pubKeyCollateralAddress; pubKeyZelnode = other.pubKeyZelnode; sig = other.sig; activeState = other.activeState; sigTime = other.sigTime; lastPing = other.lastPing; cacheInputAge = other.cacheInputAge; cacheInputAgeBlock = other.cacheInputAgeBlock; unitTest = other.unitTest; allowFreeTx = other.allowFreeTx; nActiveState = ZELNODE_ENABLED, protocolVersion = other.protocolVersion; nLastDsq = other.nLastDsq; nScanningErrorCount = other.nScanningErrorCount; nLastScanningErrorBlockHeight = other.nLastScanningErrorBlockHeight; lastTimeChecked = 0; tier = other.tier; nLastDsee = other.nLastDsee; // temporary, do not save. Remove after migration to v12 nLastDseep = other.nLastDseep; // temporary, do not save. Remove after migration to v12 } Zelnode::Zelnode(const ZelnodeBroadcast& znb) { LOCK(cs); vin = znb.vin; addr = znb.addr; pubKeyCollateralAddress = znb.pubKeyCollateralAddress; pubKeyZelnode = znb.pubKeyZelnode; sig = znb.sig; activeState = ZELNODE_ENABLED; sigTime = znb.sigTime; lastPing = znb.lastPing; cacheInputAge = 0; cacheInputAgeBlock = 0; unitTest = false; allowFreeTx = true; nActiveState = ZELNODE_ENABLED, protocolVersion = znb.protocolVersion; nLastDsq = znb.nLastDsq; nScanningErrorCount = 0; nLastScanningErrorBlockHeight = 0; lastTimeChecked = 0; tier = znb.tier; nLastDsee = 0; // temporary, do not save. Remove after migration to v12 nLastDseep = 0; // temporary, do not save. Remove after migration to v12 } ZelnodeBroadcast::ZelnodeBroadcast() { vin = CTxIn(); addr = CService(); pubKeyCollateralAddress = CPubKey(); pubKeyZelnode = CPubKey(); sig = std::vector<unsigned char>(); activeState = ZELNODE_ENABLED; sigTime = GetAdjustedTime(); lastPing = ZelnodePing(); cacheInputAge = 0; cacheInputAgeBlock = 0; unitTest = false; allowFreeTx = true; protocolVersion = PROTOCOL_VERSION; nLastDsq = 0; nScanningErrorCount = 0; nLastScanningErrorBlockHeight = 0; tier = NONE; } ZelnodeBroadcast::ZelnodeBroadcast(CService newAddr, CTxIn newVin, CPubKey pubKeyCollateralAddressNew, CPubKey pubKeyZelnodeNew, int protocolVersionIn) { vin = newVin; addr = newAddr; pubKeyCollateralAddress = pubKeyCollateralAddressNew; pubKeyZelnode = pubKeyZelnodeNew; sig = std::vector<unsigned char>(); activeState = ZELNODE_ENABLED; sigTime = GetAdjustedTime(); lastPing = ZelnodePing(); cacheInputAge = 0; cacheInputAgeBlock = 0; unitTest = false; allowFreeTx = true; protocolVersion = protocolVersionIn; nLastDsq = 0; nScanningErrorCount = 0; nLastScanningErrorBlockHeight = 0; tier = NONE; } ZelnodeBroadcast::ZelnodeBroadcast(const Zelnode& zelnode) { vin = zelnode.vin; addr = zelnode.addr; pubKeyCollateralAddress = zelnode.pubKeyCollateralAddress; pubKeyZelnode = zelnode.pubKeyZelnode; sig = zelnode.sig; activeState = zelnode.activeState; sigTime = zelnode.sigTime; lastPing = zelnode.lastPing; cacheInputAge = zelnode.cacheInputAge; cacheInputAgeBlock = zelnode.cacheInputAgeBlock; unitTest = zelnode.unitTest; allowFreeTx = zelnode.allowFreeTx; protocolVersion = zelnode.protocolVersion; nLastDsq = zelnode.nLastDsq; nScanningErrorCount = zelnode.nScanningErrorCount; nLastScanningErrorBlockHeight = zelnode.nLastScanningErrorBlockHeight; tier = zelnode.tier; } void Zelnode::Check(bool forceCheck) { if (ShutdownRequested()) return; if (!forceCheck && (GetTime() - lastTimeChecked < ZELNODE_CHECK_SECONDS)) return; lastTimeChecked = GetTime(); //once spent, stop doing the checks if (activeState == ZELNODE_VIN_SPENT) return; if (!IsPingedWithin(ZELNODE_REMOVAL_SECONDS)) { activeState = ZELNODE_REMOVE; return; } if (!IsPingedWithin(ZELNODE_EXPIRATION_SECONDS)) { activeState = ZELNODE_EXPIRED; return; } if(lastPing.sigTime - sigTime < ZELNODE_MIN_ZNP_SECONDS){ activeState = ZELNODE_PRE_ENABLED; return; } if(lastTimeChecked - benchmarkSigTime > ZELNODE_MIN_BENCHMARK_SECONDS){ activeState = ZELNODE_EXPIRED; return; } if (!unitTest) { CValidationState state; CMutableTransaction tx = CMutableTransaction(); CScript scriptPubKey; if (!GetTestingCollateralScript(Params().ZelnodeTestingDummyAddress(), scriptPubKey)){ LogPrintf("%s: Failed to get a valid scriptPubkey\n", __func__); return; } CTxOut vout; if (tier == BASIC) { vout = CTxOut(9999.99 * COIN, scriptPubKey); } else if (tier == SUPER) { vout = CTxOut(24999.99 * COIN, scriptPubKey); } else if (tier == BAMF) { vout = CTxOut(99999.99 * COIN, scriptPubKey); } tx.vin.push_back(vin); tx.vout.push_back(vout); { TRY_LOCK(cs_main, lockMain); if (!lockMain) return; if (!AcceptableInputs(mempool, state, CTransaction(tx), false, NULL)) { activeState = ZELNODE_VIN_SPENT; return; } } } activeState = ZELNODE_ENABLED; // OK } bool Zelnode::IsValidNetAddr() { // TODO: regtest is fine with any addresses for now, // should probably be a bit smarter if one day we start to implement tests for this return Params().NetworkID() == CBaseChainParams::REGTEST || (IsReachable(addr) && addr.IsRoutable()); } // // When a new zelnode broadcast is sent, update our information // bool Zelnode::UpdateFromNewBroadcast(ZelnodeBroadcast& znb) { if (znb.sigTime > sigTime) { pubKeyZelnode = znb.pubKeyZelnode; pubKeyCollateralAddress = znb.pubKeyCollateralAddress; sigTime = znb.sigTime; sig = znb.sig; protocolVersion = znb.protocolVersion; addr = znb.addr; lastTimeChecked = 0; int nDoS = 0; if (znb.lastPing == ZelnodePing() || (znb.lastPing != ZelnodePing() && znb.lastPing.CheckAndUpdate(nDoS, false))) { lastPing = znb.lastPing; zelnodeman.mapSeenZelnodePing.insert(make_pair(lastPing.GetHash(), lastPing)); } if (protocolVersion > BENCHMARKD_PROTO_VERSION) { benchmarkSigTime = znb.benchmarkSigTime; benchmarkSig = znb.benchmarkSig; } return true; } return false; } int64_t Zelnode::SecondsSincePayment() { CScript pubkeyScript; pubkeyScript = GetScriptForDestination(pubKeyCollateralAddress.GetID()); int64_t sec = (GetAdjustedTime() - GetLastPaid()); int64_t month = 60 * 60 * 24 * 30; if (sec < month) return sec; //if it's less than 30 days, give seconds CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << vin; ss << sigTime; uint256 hash = ss.GetHash(); // return some deterministic value for unknown/unpaid but force it to be more than 30 days old return month + UintToArith256(hash).GetCompact(false); } int64_t Zelnode::GetLastPaid() { CBlockIndex* pindexPrev = chainActive.Tip(); if (pindexPrev == NULL) return false; CScript mnpayee; mnpayee = GetScriptForDestination(pubKeyCollateralAddress.GetID()); CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << vin; ss << sigTime; uint256 hash = ss.GetHash(); // use a deterministic offset to break a tie -- 2.5 minutes int64_t nOffset = UintToArith256(hash).GetCompact(false) % 150; if (chainActive.Tip() == NULL) return false; const CBlockIndex* BlockReading = chainActive.Tip(); int nMnCount = zelnodeman.CountEnabled() * 1.25; int n = 0; for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) { if (n >= nMnCount) { return 0; } n++; if (zelnodePayments.mapZelnodeBlocks.count(BlockReading->nHeight)) { /* Search for this payee, with at least 2 votes. This will aid in consensus allowing the network to converge on the same payees quickly, then keep the same schedule. */ if (zelnodePayments.mapZelnodeBlocks[BlockReading->nHeight].HasPayeeWithVotes(mnpayee, 2)) { return BlockReading->nTime + nOffset; } } if (BlockReading->pprev == NULL) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } return 0; } // // Deterministically calculate a given "score" for a Zelnode depending on how close it's hash is to // the proof of work for that block. The further away they are the better, the furthest will win the election // and get paid this block // uint256 Zelnode::CalculateScore(int mod, int64_t nBlockHeight) { if (chainActive.Tip() == NULL) return uint256(); uint256 hash = uint256(); COutPoint out(vin.prevout.hash, vin.prevout.n); uint256 aux = Hash(BEGIN(out.hash), END(out.n)); if (!GetBlockHash(hash, nBlockHeight)) { LogPrint("zelnode","CalculateScore ERROR - nHeight %d - Returned 0\n", nBlockHeight); return uint256(); } CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << hash; uint256 hash2 = ss.GetHash(); CHashWriter ss2(SER_GETHASH, PROTOCOL_VERSION); ss2 << hash; ss2 << aux; uint256 hash3 = ss2.GetHash(); uint256 r = (hash3 > hash2 ? hash3 - hash2 : hash2 - hash3); return r; } bool ZelnodeBroadcast::Create(std::string strService, std::string strKeyZelnode, std::string strTxHash, std::string strOutputIndex, std::string& strErrorRet, ZelnodeBroadcast& znbRet, bool fOffline) { CTxIn txin; CPubKey pubKeyCollateralAddressNew; CKey keyCollateralAddressNew; CPubKey pubKeyZelnodeNew; CKey keyZelnodeNew; //need correct blocks to send ping if (!fOffline && !zelnodeSync.IsBlockchainSynced()) { strErrorRet = "Sync in progress. Must wait until sync is complete to start Zelnode"; LogPrint("zelnode","%s -- %s\n", __func__, strErrorRet); return false; } if (!obfuScationSigner.GetKeysFromSecret(strKeyZelnode, keyZelnodeNew, pubKeyZelnodeNew)) { strErrorRet = strprintf("Invalid zelnode key %s", strKeyZelnode); LogPrint("zelnode","%s -- %s\n", __func__, strErrorRet); return false; } #ifdef ENABLE_WALLET if (!pwalletMain->GetZelnodeVinAndKeys(txin, pubKeyCollateralAddressNew, keyCollateralAddressNew, strTxHash, strOutputIndex)) { strErrorRet = strprintf("Could not allocate txin %s:%s for zelnode %s", strTxHash, strOutputIndex, strService); LogPrint("zelnode","%s -- %s\n", __func__, strErrorRet); return false; } #else LogPrint("%s -- Wallet must be enabled\n", __func__); return false; #endif // The service needs the correct default port to work properly if(!CheckDefaultPort(strService, strErrorRet, "ZelnodeBroadcast::Create")) return false; return Create(txin, CService(strService), keyCollateralAddressNew, pubKeyCollateralAddressNew, keyZelnodeNew, pubKeyZelnodeNew, strErrorRet, znbRet); } bool ZelnodeBroadcast::Create(CTxIn txin, CService service, CKey keyCollateralAddressNew, CPubKey pubKeyCollateralAddressNew, CKey keyZelnodeNew, CPubKey pubKeyZelnodeNew, std::string& strErrorRet, ZelnodeBroadcast& znbRet) { // wait for reindex and/or import to finish if (fImporting || fReindex) return false; LogPrint("zelnode", "%s -- pubKeyCollateralAddressNew = %s, pubKeyZelnodeNew.GetID() = %s\n", __func__, EncodeDestination(pubKeyCollateralAddressNew.GetID()), pubKeyZelnodeNew.GetID().ToString()); ZelnodePing znp(txin); if (!znp.Sign(keyZelnodeNew, pubKeyZelnodeNew)) { strErrorRet = strprintf("Failed to sign ping, zelnode=%s", txin.prevout.hash.ToString()); LogPrint("zelnode","%s -- %s\n", __func__, strErrorRet); znbRet = ZelnodeBroadcast(); return false; } znbRet = ZelnodeBroadcast(service, txin, pubKeyCollateralAddressNew, pubKeyZelnodeNew, PROTOCOL_VERSION); if (!znbRet.IsValidNetAddr()) { strErrorRet = strprintf("Invalid IP address %s, zelnode=%s", znbRet.addr.ToStringIP (), txin.prevout.hash.ToString()); LogPrint("zelnode","%s -- %s\n", __func__, strErrorRet); znbRet = ZelnodeBroadcast(); return false; } znbRet.lastPing = znp; if (!znbRet.Sign(keyCollateralAddressNew)) { strErrorRet = strprintf("Failed to sign broadcast, zelnode=%s", txin.prevout.hash.ToString()); LogPrint("zelnode","%s -- %s\n", __func__, strErrorRet); znbRet = ZelnodeBroadcast(); return false; } return true; } bool ZelnodeBroadcast::CheckDefaultPort(std::string strService, std::string& strErrorRet, std::string strContext) { CService service = CService(strService); int nDefaultPort = Params().GetDefaultPort(); if (service.GetPort() != nDefaultPort) { strErrorRet = strprintf("Invalid port %u for zelnode %s, only %d is supported on %s-net.", service.GetPort(), strService, nDefaultPort, Params().NetworkIDString()); LogPrint("zelnode", "%s -- %s - %s\n", __func__, strContext, strErrorRet); return false; } return true; } bool ZelnodeBroadcast::CheckAndUpdate(int& nDos) { // make sure signature isn't in the future (past is OK) if (sigTime > GetAdjustedTime() + 60 * 60) { LogPrint("zelnode","znb - Signature rejected, too far into the future %s\n", vin.prevout.hash.ToString()); nDos = 1; return false; } // incorrect ping or its sigTime if(lastPing == ZelnodePing() || !lastPing.CheckAndUpdate(nDos, false, true)) return false; if (protocolVersion < zelnodePayments.GetMinZelnodePaymentsProto()) { LogPrint("zelnode","znb - ignoring outdated Zelnode %s protocol version %d\n", vin.prevout.hash.ToString(), protocolVersion); return false; } CScript pubkeyScript; pubkeyScript = GetScriptForDestination(pubKeyCollateralAddress.GetID()); if (pubkeyScript.size() != 25) { LogPrint("zelnode","znb - pubkey the wrong size\n"); nDos = 100; return false; } CScript pubkeyScript2; pubkeyScript2 = GetScriptForDestination(pubKeyZelnode.GetID()); if (pubkeyScript2.size() != 25) { LogPrint("zelnode","znb - pubkey2 the wrong size\n"); nDos = 100; return false; } if (!vin.scriptSig.empty()) { LogPrint("zelnode","znb - Ignore Not Empty ScriptSig %s\n", vin.prevout.hash.ToString()); return false; } std::string errorMessage = ""; if (!obfuScationSigner.VerifyMessage(pubKeyCollateralAddress, sig, GetStrMessage(), errorMessage)) { // don't ban for old zelnodes, their sigs could be broken because of the bug nDos = protocolVersion < MIN_PEER_PROTO_VERSION_ZELNODE ? 0 : 100; return error("%s - Got bad Zelnode address signature : %s", __func__, errorMessage); } /// Benchmarkd Start if (protocolVersion >= BENCHMARKD_PROTO_VERSION) { if (!BenchmarkVerifySignature()) { if (IsSporkActive(SPORK_3_ZELNODE_BENCHMARKD_ENFORCEMENT)) { nDos = 100; return error("%s - Got bad benchmarkd signature", __func__); } else { LogPrintf("Failed to Verify Benchmarkd Signature - But the spork is disabled. So Skipping check\n"); } } // TODO Should we check for the signatures for the sigTime, and benchMarkSigTime to be within a certain time frame? } /// Benchmarkd End if (Params().NetworkID() == CBaseChainParams::MAIN) { if (addr.GetPort() != 16125) return false; } else if (addr.GetPort() == 16125) return false; //search existing Zelnode list, this is where we update existing Zelnodes with new znb broadcasts Zelnode* pzn = zelnodeman.Find(vin); // no such zelnode, nothing to update if (pzn == NULL) return true; // this broadcast is older or equal than the one that we already have - it's bad and should never happen // unless someone is doing something fishy // (mapSeenZelnodeBroadcast in ZelnodeMan::ProcessMessage should filter legit duplicates) if(pzn->sigTime >= sigTime) { return error("%s - Bad sigTime %d for Zelnode %20s %105s (existing broadcast is at %d)", __func__, sigTime, addr.ToString(), vin.ToString(), pzn->sigTime); } // zelnode is not enabled yet/already, nothing to update if (!pzn->IsEnabled()) return true; // zn.pubkey = pubkey, IsVinAssociatedWithPubkey is validated once below, // after that they just need to match if (pzn->pubKeyCollateralAddress == pubKeyCollateralAddress && !pzn->IsBroadcastedWithin(ZELNODE_MIN_ZNB_SECONDS)) { //take the newest entry LogPrint("zelnode","znb - Got updated entry for %s\n", vin.prevout.hash.ToString()); if (pzn->UpdateFromNewBroadcast((*this))) { pzn->Check(); if (pzn->IsEnabled()) Relay(); } zelnodeSync.AddedZelnodeList(GetHash()); } return true; } // Zelnode broadcast has been checked and has been assigned a tier before this method is called bool ZelnodeBroadcast::CheckInputsAndAdd(int& nDoS) { // we are a zelnode with the same vin (i.e. already activated) and this znb is ours (matches our Zelnode privkey) // so nothing to do here for us if (fZelnode && vin.prevout == activeZelnode.vin.prevout && pubKeyZelnode == activeZelnode.pubKeyZelnode) return true; // incorrect ping or its sigTime if(lastPing == ZelnodePing() || !lastPing.CheckAndUpdate(nDoS, false, true)) return false; // search existing Zelnode list Zelnode* pzn = zelnodeman.Find(vin); if (pzn != NULL) { // nothing to do here if we already know about this zelnode and it's enabled if (pzn->IsEnabled()) return true; // if it's not enabled, remove old ZN first and continue else zelnodeman.Remove(pzn->vin); } { TRY_LOCK(cs_main, lockMain); if (!lockMain) { // not znb fault, let it to be checked again later zelnodeman.mapSeenZelnodeBroadcast.erase(GetHash()); zelnodeSync.mapSeenSyncZNB.erase(GetHash()); return false; } } LogPrint("zelnode", "znb - Accepted Zelnode entry\n"); if (GetInputAge(vin) < ZELNODE_MIN_CONFIRMATIONS) { LogPrint("zelnode","znb - Input must have at least %d confirmations\n", ZELNODE_MIN_CONFIRMATIONS); // maybe we miss few blocks, let this znb to be checked again later zelnodeman.mapSeenZelnodeBroadcast.erase(GetHash()); zelnodeSync.mapSeenSyncZNB.erase(GetHash()); return false; } // verify that sig time is legit in past // should be at least not earlier than block when 10000, 25000, 100000 ZEL tx got ZELNODE_MIN_CONFIRMATIONS uint256 hashBlock = uint256(); CTransaction tx2; GetTransaction(vin.prevout.hash, tx2, Params().GetConsensus(), hashBlock, true); BlockMap::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end() && (*mi).second) { CBlockIndex* pZNIndex = (*mi).second; // block for 10000, 25000, 100000 ZEL tx -> 1 confirmation CBlockIndex* pConfIndex = chainActive[pZNIndex->nHeight + ZELNODE_MIN_CONFIRMATIONS - 1]; // block where tx got ZELNODE_MIN_CONFIRMATIONS if (pConfIndex->GetBlockTime() > sigTime) { LogPrint("zelnode","znb - Bad sigTime %d for Zelnode %s (%i conf block is at %d)\n", sigTime, vin.prevout.hash.ToString(), ZELNODE_MIN_CONFIRMATIONS, pConfIndex->GetBlockTime()); return false; } } LogPrint("zelnode","znb - Got NEW Zelnode entry - %s - %lli \n", vin.prevout.hash.ToString(), sigTime); Zelnode zn(*this); zelnodeman.Add(zn); // if it matches our Zelnode privkey, then we've been remotely activated if (pubKeyZelnode == activeZelnode.pubKeyZelnode && protocolVersion == PROTOCOL_VERSION) { activeZelnode.EnableHotColdZelnode(vin, addr); } bool isLocal = addr.IsRFC1918() || addr.IsLocal(); if (Params().NetworkID() == CBaseChainParams::REGTEST) isLocal = false; if (!isLocal) Relay(); return true; } void ZelnodeBroadcast::Relay() { CInv inv(MSG_ZELNODE_ANNOUNCE, GetHash()); RelayInv(inv); } bool ZelnodeBroadcast::Sign(CKey& keyCollateralAddress) { std::string errorMessage; sigTime = GetAdjustedTime(); std::string strMessage = GetStrMessage(); if (!obfuScationSigner.SignMessage(strMessage, errorMessage, sig, keyCollateralAddress)) return error("%s - Error: %s", __func__, errorMessage); if (!obfuScationSigner.VerifyMessage(pubKeyCollateralAddress, sig, strMessage, errorMessage)) return error("%s - Error: %s", __func__, errorMessage); return true; } bool ZelnodeBroadcast::VerifySignature() { std::string errorMessage; if(!obfuScationSigner.VerifyMessage(pubKeyCollateralAddress, sig, GetStrMessage(), errorMessage)) return error("%s - Error: %s", __func__, errorMessage); return true; } std::string ZelnodeBroadcast::GetStrMessage() { std::string strMessage; strMessage = addr.ToString() + std::to_string(sigTime) + pubKeyCollateralAddress.GetID().ToString() + pubKeyZelnode.GetID().ToString() + std::to_string(protocolVersion); return strMessage; } bool ZelnodeBroadcast::BenchmarkSign() { CKey key2; CPubKey pubkey2; std::string private_key = "5JQ7qb9bRNcoHEDo7uuFkyrDGPDj7y1nbA7tYGCh17Wr8MyMAx1"; if (Params().NetworkID() != CBaseChainParams::Network::MAIN) private_key = "91d42x2JC7uRBEiY7VeenAcxs5agdA2W6DE8vYr3EosMU59SdBb"; std::string errorMessage = ""; benchmarkSigTime = benchmarks.nTime; std::string strMessage = std::string(sig.begin(), sig.end()) + std::to_string(benchmarkTier) + std::to_string(benchmarkSigTime); if (!obfuScationSigner.SetKey(private_key, errorMessage, key2, pubkey2)) { LogPrintf("CZelnodePayments::Sign - ERROR: Invalid zelnodeprivkey: '%s'\n", errorMessage); return false; } if (!obfuScationSigner.SignMessage(strMessage, errorMessage, benchmarkSig, key2)) return error("%s - Error: %s", __func__, errorMessage); if (!obfuScationSigner.VerifyMessage(pubkey2, benchmarkSig, strMessage, errorMessage)) return error("%s - Error: %s", __func__, errorMessage); return true; } bool ZelnodeBroadcast::BenchmarkVerifySignature() { std::string public_key = Params().BenchmarkingPublicKey(); CPubKey pubkey(ParseHex(public_key)); std::string errorMessage = ""; std::string strMessage = std::string(sig.begin(), sig.end()) + std::to_string(benchmarkTier) + std::to_string(benchmarkSigTime); if (!obfuScationSigner.VerifyMessage(pubkey, benchmarkSig, strMessage, errorMessage)) return error("%s - Error: %s", __func__, errorMessage); return true; } ZelnodePing::ZelnodePing() { vin = CTxIn(); blockHash = uint256(); sigTime = 0; vchSig = std::vector<unsigned char>(); } ZelnodePing::ZelnodePing(CTxIn& newVin) { vin = newVin; blockHash = chainActive[chainActive.Height() - 12]->GetBlockHash(); sigTime = GetAdjustedTime(); vchSig = std::vector<unsigned char>(); } bool ZelnodePing::Sign(CKey& keyZelnode, CPubKey& pubKeyZelnode) { std::string errorMessage; sigTime = GetAdjustedTime(); std::string strMessage = vin.ToString() + blockHash.ToString() + std::to_string(sigTime); if (!obfuScationSigner.SignMessage(strMessage, errorMessage, vchSig, keyZelnode)) { LogPrint("zelnode","%s - Error: %s\n", __func__, errorMessage); return false; } if (!obfuScationSigner.VerifyMessage(pubKeyZelnode, vchSig, strMessage, errorMessage)) { LogPrint("zelnode","%s - Error: %s\n", __func__, errorMessage); return false; } return true; } bool ZelnodePing::VerifySignature(CPubKey& pubKeyZelnode, int &nDos) { std::string strMessage = vin.ToString() + blockHash.ToString() + std::to_string(sigTime); std::string errorMessage = ""; if(!obfuScationSigner.VerifyMessage(pubKeyZelnode, vchSig, strMessage, errorMessage)){ nDos = 33; return error("%s - Got bad Zelnode ping signature %s Error: %s", __func__, vin.ToString(), errorMessage); } return true; } bool ZelnodePing::CheckAndUpdate(int& nDos, bool fRequireEnabled, bool fCheckSigTimeOnly) { if (sigTime > GetAdjustedTime() + 60 * 60) { LogPrint("zelnode","%s - Signature rejected, too far into the future %s\n", __func__, vin.prevout.hash.ToString()); nDos = 1; return false; } if (sigTime <= GetAdjustedTime() - 60 * 60) { LogPrint("zelnode","%s - Signature rejected, too far into the past %s - %d %d \n", __func__, vin.prevout.hash.ToString(), sigTime, GetAdjustedTime()); nDos = 1; return false; } if(fCheckSigTimeOnly) { Zelnode* pzn = zelnodeman.Find(vin); if(pzn) return VerifySignature(pzn->pubKeyZelnode, nDos); return true; } LogPrint("zelnode", "%s - New Ping - %s - %s - %lli\n", __func__, GetHash().ToString(), blockHash.ToString(), sigTime); // see if we have this Zelnode Zelnode* pzn = zelnodeman.Find(vin); if (pzn != NULL && pzn->protocolVersion >= zelnodePayments.GetMinZelnodePaymentsProto()) { if (fRequireEnabled && !pzn->IsEnabled()) return false; LogPrint("zelnode","znping - Found corresponding zn for vin: %s\n", vin.ToString()); // update only if there is no known ping for this zelnode or // last ping was more then ZELNODE_MIN_MNP_SECONDS-60 ago comparing to this one if (!pzn->IsPingedWithin(ZELNODE_MIN_ZNP_SECONDS - 60, sigTime)) { if (!VerifySignature(pzn->pubKeyZelnode, nDos)) return false; BlockMap::iterator mi = mapBlockIndex.find(blockHash); if (mi != mapBlockIndex.end() && (*mi).second) { if ((*mi).second->nHeight < chainActive.Height() - 24) { LogPrint("zelnode","%s - Zelnode %s block hash %s is too old\n", __func__, vin.prevout.hash.ToString(), blockHash.ToString()); // Do nothing here (no Zelnode update, no znping relay) // Let this node to be visible but fail to accept znping return false; } } else { if (fDebug) LogPrint("zelnode","%s - Zelnode %s block hash %s is unknown\n", __func__, vin.prevout.hash.ToString(), blockHash.ToString()); // maybe we stuck so we shouldn't ban this node, just fail to accept it // TODO: or should we also request this block? return false; } pzn->lastPing = *this; //zelnodeman.mapSeenZelnodeBroadcast.lastPing is probably outdated, so we'll update it ZelnodeBroadcast znb(*pzn); uint256 hash = znb.GetHash(); if (zelnodeman.mapSeenZelnodeBroadcast.count(hash)) { zelnodeman.mapSeenZelnodeBroadcast[hash].lastPing = *this; } pzn->Check(true); if (!pzn->IsEnabled()) return false; LogPrint("zelnode", "%s - Zelnode ping accepted, vin: %s\n", __func__, vin.prevout.hash.ToString()); Relay(); return true; } LogPrint("zelnode", "%s - Zelnode ping arrived too early, vin: %s\n", __func__, vin.prevout.hash.ToString()); //nDos = 1; //disable, this is happening frequently and causing banned peers return false; } LogPrint("zelnode", "%s - Couldn't find compatible Zelnode entry, vin: %s\n", __func__, vin.prevout.hash.ToString()); return false; } void ZelnodePing::Relay() { CInv inv(MSG_ZELNODE_PING, GetHash()); RelayInv(inv); } std::string TierToString(int tier) { std::string strStatus = "NONE"; if (tier == Zelnode::BASIC) strStatus = "BASIC"; if (tier == Zelnode::SUPER) strStatus = "SUPER"; if (tier == Zelnode::BAMF) strStatus = "BAMF"; if (strStatus == "NONE" && tier != 0) strStatus = "UNKNOWN TIER (" + std::to_string(tier) + ")"; return strStatus; }
34.701099
223
0.656026
[ "vector" ]
4f70519bebfb2affd6101921d78ff25d1aebbaa8
63,222
cpp
C++
server/core/src/rodsServer.cpp
trel/irods
dc462b0e90f3d715546329570f5950dd425dc489
[ "BSD-3-Clause" ]
1
2021-12-06T01:56:30.000Z
2021-12-06T01:56:30.000Z
server/core/src/rodsServer.cpp
trel/irods
dc462b0e90f3d715546329570f5950dd425dc489
[ "BSD-3-Clause" ]
2
2021-03-04T16:08:43.000Z
2021-03-05T01:27:30.000Z
server/core/src/rodsServer.cpp
trel/irods
dc462b0e90f3d715546329570f5950dd425dc489
[ "BSD-3-Clause" ]
null
null
null
#include "irods_at_scope_exit.hpp" #include "irods_configuration_keywords.hpp" #include "irods_configuration_parser.hpp" #include "irods_get_full_path_for_config_file.hpp" #include "rcMisc.h" #include "rodsErrorTable.h" #include "rodsServer.hpp" #include "sharedmemory.hpp" #include "initServer.hpp" #include "miscServerFunct.hpp" #include "irods_exception.hpp" #include "irods_server_state.hpp" #include "irods_client_server_negotiation.hpp" #include "irods_network_factory.hpp" #include "irods_re_plugin.hpp" #include "irods_server_properties.hpp" #include "irods_server_control_plane.hpp" #include "initServer.hpp" #include "procLog.h" #include "rsGlobalExtern.hpp" #include "locks.hpp" #include "sharedmemory.hpp" #include "sockCommNetworkInterface.hpp" #include "irods_random.hpp" #include "replica_access_table.hpp" #include "irods_logger.hpp" #include "hostname_cache.hpp" #include "dns_cache.hpp" #include "server_utilities.hpp" #include "process_manager.hpp" #include <pthread.h> #include <sys/socket.h> #include <sys/un.h> #include <netinet/in.h> #include <arpa/inet.h> #include <fcntl.h> #include <sys/stat.h> #include <boost/filesystem.hpp> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/convenience.hpp> #include <boost/range/iterator_range.hpp> #include <boost/thread/thread.hpp> #include <boost/thread/mutex.hpp> #include <boost/thread/condition.hpp> #include <fmt/format.h> #include <json.hpp> #include <cstring> #include <fstream> #include <regex> #include <algorithm> #include <optional> #include <iterator> // clang-format off namespace ix = irods::experimental; namespace hnc = irods::experimental::net::hostname_cache; namespace dnsc = irods::experimental::net::dns_cache; // clang-format on using namespace boost::filesystem; struct sockaddr_un local_addr{}; int agent_conn_socket{}; bool connected_to_agent{}; pid_t agent_spawning_pid{}; const char socket_dir_template[]{"/tmp/irods_sockets_XXXXXX"}; char agent_factory_socket_dir[sizeof(socket_dir_template)]{}; char agent_factory_socket_file[sizeof(local_addr.sun_path)]{}; uint ServerBootTime; int SvrSock; agentProc_t *ConnectedAgentHead = NULL; agentProc_t *ConnReqHead = NULL; agentProc_t *SpawnReqHead = NULL; agentProc_t *BadReqHead = NULL; boost::mutex ConnectedAgentMutex; boost::mutex BadReqMutex; boost::thread* ReadWorkerThread[NUM_READ_WORKER_THR]; boost::thread* SpawnManagerThread; boost::thread* PurgeLockFileThread; // JMC - backport 4612 boost::mutex ReadReqCondMutex; boost::mutex SpawnReqCondMutex; boost::condition_variable ReadReqCond; boost::condition_variable SpawnReqCond; std::vector<std::string> setExecArg( const char *commandArgv ); int runIrodsAgentFactory(sockaddr_un agent_addr); int queueConnectedAgentProc( int childPid, agentProc_t *connReq, agentProc_t **agentProcHead); namespace { // We incorporate the cache salt into the rule engine's named_mutex and shared memory object. // This prevents (most of the time) an orphaned mutex from halting server standup. Issue most often seen // when a running iRODS installation is uncleanly killed (leaving the file system object used to implement // boost::named_mutex e.g. in /var/run/shm) and then the iRODS user account is recreated, yielding a different // UID. The new iRODS user account is then unable to unlock or remove the existing mutex, blocking the server. irods::error createAndSetRECacheSalt() { // Should only ever set the cache salt once try { const auto& existing_salt = irods::get_server_property<const std::string>(irods::CFG_RE_CACHE_SALT_KW); rodsLog( LOG_ERROR, "createAndSetRECacheSalt: salt already set [%s]", existing_salt.c_str() ); return ERROR( SYS_ALREADY_INITIALIZED, "createAndSetRECacheSalt: cache salt already set" ); } catch ( const irods::exception& ) { irods::buffer_crypt::array_t buf; irods::error ret = irods::buffer_crypt::generate_key( buf, RE_CACHE_SALT_NUM_RANDOM_BYTES ); if ( !ret.ok() ) { rodsLog( LOG_ERROR, "createAndSetRECacheSalt: failed to generate random bytes" ); return PASS( ret ); } std::string cache_salt_random; ret = irods::buffer_crypt::hex_encode( buf, cache_salt_random ); if ( !ret.ok() ) { rodsLog( LOG_ERROR, "createAndSetRECacheSalt: failed to hex encode random bytes" ); return PASS( ret ); } std::stringstream cache_salt; cache_salt << "pid" << static_cast<intmax_t>( getpid() ) << "_" << cache_salt_random; try { irods::set_server_property<std::string>( irods::CFG_RE_CACHE_SALT_KW, cache_salt.str() ); } catch ( const nlohmann::json::exception& e ) { rodsLog( LOG_ERROR, "createAndSetRECacheSalt: failed to set server_properties" ); return ERROR(SYS_INVALID_INPUT_PARAM, e.what()); } catch(const std::exception& e) { } int ret_int = setenv( SP_RE_CACHE_SALT, cache_salt.str().c_str(), 1 ); if ( 0 != ret_int ) { rodsLog( LOG_ERROR, "createAndSetRECacheSalt: failed to set environment variable" ); return ERROR( SYS_SETENV_ERR, "createAndSetRECacheSalt: failed to set environment variable" ); } return SUCCESS(); } } int get64RandomBytes( char *buf ) { const int num_random_bytes = 32; const int num_hex_bytes = 2 * num_random_bytes; unsigned char random_bytes[num_random_bytes]; irods::getRandomBytes( random_bytes, sizeof(random_bytes) ); std::stringstream ss; for ( size_t i = 0; i < sizeof(random_bytes); ++i ) { ss << std::hex << std::setw(2) << std::setfill('0') << (unsigned int)( random_bytes[i] ); } snprintf( buf, num_hex_bytes + 1, "%s", ss.str().c_str() ); return 0; } void init_logger(bool _write_to_stdout = false, bool _enable_test_mode = false) { ix::log::init(_write_to_stdout, _enable_test_mode); irods::server_properties::instance().capture(); ix::log::server::set_level(ix::log::get_level_from_config(irods::CFG_LOG_LEVEL_CATEGORY_SERVER_KW)); ix::log::set_server_type("server"); if (char hostname[HOST_NAME_MAX]{}; gethostname(hostname, sizeof(hostname)) == 0) { ix::log::set_server_host(hostname); } } void remove_leftover_rulebase_pid_files() noexcept { namespace fs = boost::filesystem; try { // Find the server configuration file. std::string config_path; if (const auto err = irods::get_full_path_for_config_file("server_config.json", config_path); !err.ok()) { ix::log::server::error("Could not locate server_config.json. Cannot remove leftover rulebase files."); return; } // Load the server configuration file in as JSON. nlohmann::json config; if (std::ifstream in{config_path}; in) { in >> config; } else { ix::log::server::error("Could not open server configuration file. Cannot remove leftover rulebase files."); return; } // Find the NREP. const auto& plugin_config = config.at(irods::CFG_PLUGIN_CONFIGURATION_KW); const auto& rule_engines = plugin_config.at(irods::PLUGIN_TYPE_RULE_ENGINE); const auto end = std::end(rule_engines); const auto nrep = std::find_if(std::begin(rule_engines), end, [](const nlohmann::json& _object) { return _object.at(irods::CFG_PLUGIN_NAME_KW).get<std::string>() == "irods_rule_engine_plugin-irods_rule_language"; }); // Get the rulebase set. const auto& plugin_specific_config = nrep->at(irods::CFG_PLUGIN_SPECIFIC_CONFIGURATION_KW); const auto& rulebase_set = plugin_specific_config.at(irods::CFG_RE_RULEBASE_SET_KW); // Iterate over the list of rulebases and remove the leftover PID files. for (const auto& rb : rulebase_set) { // Create a pattern based on the rulebase's filename. The pattern will have the following format: // // .+/<rulebase_name>\.re\.\d+ // // Where <rulebase_name> is a placeholder for the target rulebase. std::string pattern_string = ".+/"; pattern_string += rb.get<std::string>(); pattern_string += R"_(\.re\.\d+)_"; const std::regex pattern{pattern_string}; for (const auto& p : fs::directory_iterator{irods::get_irods_config_directory()}) { if (std::regex_match(p.path().c_str(), pattern)) { try { fs::remove(p); } catch (...) {} } } } } catch (...) {} } // remove_leftover_rulebase_pid_files int create_pid_file() { const auto pid_file = boost::filesystem::temp_directory_path() / "irods.pid"; // Open the PID file. If it does not exist, create it and give the owner // permission to read and write to it. const auto fd = open(pid_file.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); if (fd == -1) { ix::log::server::error("Could not open PID file."); return -1; } // Get the current open flags for the open file descriptor. const auto flags = fcntl(fd, F_GETFD); if (flags == -1) { ix::log::server::error("Could not retrieve open flags for PID file."); return -1; } // Enable the FD_CLOEXEC option for the open file descriptor. // This option will cause successful calls to exec() to close the file descriptor. // Keep in mind that record locks are NOT inherited by forked child processes. if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) { ix::log::server::error("Could not set FD_CLOEXEC on PID file."); return -1; } struct flock input; input.l_type = F_WRLCK; input.l_whence = SEEK_SET; input.l_start = 0; input.l_len = 0; // Try to acquire the write lock on the PID file. If we cannot get the lock, // another instance of the application must already be running or something // weird is going on. if (fcntl(fd, F_SETLK, &input) == -1) { if (EAGAIN == errno || EACCES == errno) { ix::log::server::error("Could not acquire write lock for PID file. Another instance " "could be running already."); return -1; } } if (ftruncate(fd, 0) == -1) { ix::log::server::error("Could not truncate PID file's contents."); return -1; } const auto contents = fmt::format("{}\n", getpid()); if (write(fd, contents.data(), contents.size()) != static_cast<long>(contents.size())) { ix::log::server::error("Could not write PID to PID file."); return -1; } return 0; } // create_pid_file } // anonymous namespace static void set_agent_spawner_process_name(const InformationRequiredToSafelyRenameProcess& info) { const char* desired_name = "irodsServer: factory"; const auto l_desired = strlen(desired_name); if (l_desired <= info.argv0_size) { strncpy(info.argv0, desired_name, info.argv0_size); } } void daemonize() { if (fork()) { // End the parent process immediately. exit(0); } if (setsid() < 0) { rodsLog(LOG_NOTICE, "serverize: setsid failed, errno = %d\n", errno); exit(1); } close(0); close(1); close(2); open("/dev/null", O_RDONLY); open("/dev/null", O_WRONLY); open("/dev/null", O_RDWR); } int main(int argc, char** argv) { int c; char tmpStr1[100], tmpStr2[100]; bool write_to_stdout = false; bool enable_test_mode = false; ProcessType = SERVER_PT; /* I am a server */ if (const char* log_level = getenv(SP_LOG_LEVEL); log_level) { rodsLogLevel(atoi(log_level)); } else { rodsLogLevel(LOG_NOTICE); } // Issue #3865 - The mere existence of the environment variable sets // the value to 1. Otherwise it stays at the default level (currently 0). if (const char* sql_log_level = getenv(SP_LOG_SQL); sql_log_level) { rodsLogSqlReq(1); } ServerBootTime = time( 0 ); while ( ( c = getopt( argc, argv, "tuvVqsh" ) ) != EOF ) { switch ( c ) { case 't': enable_test_mode = true; break; case 'u': /* user command level. without serverized */ write_to_stdout = true; break; case 'v': /* verbose Logging */ snprintf( tmpStr1, 100, "%s=%d", SP_LOG_LEVEL, LOG_NOTICE ); putenv( tmpStr1 ); rodsLogLevel( LOG_NOTICE ); break; case 'V': /* very Verbose */ snprintf( tmpStr1, 100, "%s=%d", SP_LOG_LEVEL, LOG_DEBUG10 ); putenv( tmpStr1 ); rodsLogLevel( LOG_DEBUG10 ); break; case 'q': /* quiet (only errors and above) */ snprintf( tmpStr1, 100, "%s=%d", SP_LOG_LEVEL, LOG_ERROR ); putenv( tmpStr1 ); rodsLogLevel( LOG_ERROR ); break; case 's': /* log SQL commands */ snprintf( tmpStr2, 100, "%s=%d", SP_LOG_SQL, 1 ); putenv( tmpStr2 ); break; case 'h': /* help */ usage( argv[0] ); exit( 0 ); default: usage( argv[0] ); exit( 1 ); } } if (!write_to_stdout) { daemonize(); } init_logger(write_to_stdout, enable_test_mode); ix::log::server::info("Initializing server ..."); const auto pid_file_fd = create_pid_file(); if (pid_file_fd == -1) { return 1; } hnc::init("irods_hostname_cache", irods::get_hostname_cache_shared_memory_size()); irods::at_scope_exit deinit_hostname_cache{[] { hnc::deinit(); }}; dnsc::init("irods_dns_cache", irods::get_dns_cache_shared_memory_size()); irods::at_scope_exit deinit_dns_cache{[] { dnsc::deinit(); }}; ix::replica_access_table::init(); irods::at_scope_exit deinit_replica_access_table{[] { ix::replica_access_table::deinit(); }}; remove_leftover_rulebase_pid_files(); using key_path_t = irods::configuration_parser::key_path_t; // Set the default value for evicting DNS cache entries. irods::set_server_property( key_path_t{irods::CFG_ADVANCED_SETTINGS_KW, irods::CFG_DNS_CACHE_KW, irods::CFG_EVICTION_AGE_IN_SECONDS_KW}, irods::get_dns_cache_eviction_age()); // Set the default value for evicting hostname cache entries. irods::set_server_property( key_path_t{irods::CFG_ADVANCED_SETTINGS_KW, irods::CFG_HOSTNAME_CACHE_KW, irods::CFG_EVICTION_AGE_IN_SECONDS_KW}, irods::get_hostname_cache_eviction_age()); /* start of irodsReServer has been moved to serverMain */ signal( SIGTTIN, SIG_IGN ); signal( SIGTTOU, SIG_IGN ); signal( SIGCHLD, SIG_DFL ); /* SIG_IGN causes autoreap. wait get nothing */ signal( SIGPIPE, SIG_IGN ); #ifdef osx_platform signal( SIGINT, ( sig_t ) serverExit ); signal( SIGHUP, ( sig_t ) serverExit ); signal( SIGTERM, ( sig_t ) serverExit ); #else signal( SIGINT, serverExit ); signal( SIGHUP, serverExit ); signal( SIGTERM, serverExit ); #endif // Set up local_addr for socket communication memset( &local_addr, 0, sizeof(local_addr) ); local_addr.sun_family = AF_UNIX; char random_suffix[65]; get64RandomBytes( random_suffix ); char mkdtemp_template[sizeof(socket_dir_template)]{}; snprintf(mkdtemp_template, sizeof(mkdtemp_template), "%s", socket_dir_template); const char* mkdtemp_result = mkdtemp(mkdtemp_template); if (!mkdtemp_result) { rodsLog(LOG_ERROR, "Error creating tmp directory for iRODS sockets, mkdtemp errno [%d]: [%s]", errno, strerror(errno)); return SYS_INTERNAL_ERR; } snprintf(agent_factory_socket_dir, sizeof(agent_factory_socket_dir), "%s", mkdtemp_result); snprintf(agent_factory_socket_file, sizeof(agent_factory_socket_file), "%s/irods_factory_%s", agent_factory_socket_dir, random_suffix); snprintf(local_addr.sun_path, sizeof(local_addr.sun_path), "%s", agent_factory_socket_file); ix::cron::cron_builder agent_watcher; const auto start_agent_server = [&](std::any& _) { int status; int w = waitpid(agent_spawning_pid, &status, WNOHANG); if( w != 0 ) { ix::log::server::info("Starting agent factory"); auto new_pid = fork(); if( new_pid == 0 ) { close(pid_file_fd); ProcessType = AGENT_PT; // This appeared to be the best option at balancing cleanup and correct behavior, // however this may not perform the full cleanup that would happen on a normal return from main. // The other alternative considered here was throwing the code, however this was complicated // by the usage of catch(...) blocks elsewhere. exit(runIrodsAgentFactory(local_addr)); } else { close(agent_conn_socket); ix::log::server::info("Restarting agent factory"); agent_conn_socket = socket( AF_UNIX, SOCK_STREAM, 0 ); time_t sock_connect_start_time = time( 0 ); while (true) { const unsigned int len = sizeof(local_addr); ssize_t status = connect( agent_conn_socket, (const struct sockaddr*) &local_addr, len ); if ( status >= 0 ) { break; } int saved_errno = errno; if ( ( time( 0 ) - sock_connect_start_time ) > 5 ) { rodsLog(LOG_ERROR, "Error connecting to agent factory socket, errno = [%d]: %s", saved_errno, strerror( saved_errno ) ); exit(SYS_SOCK_CONNECT_ERR); } } agent_spawning_pid=new_pid; } } }; std::any dummy; start_agent_server(dummy); agent_watcher.to_execute(start_agent_server).interval(5); ix::cron::cron::get()->add_task(agent_watcher.build()); ix::cron::cron_builder cache_clearer; cache_clearer.to_execute([](std::any& _){ ix::log::server::info("Expiring old cache entries"); irods::experimental::net::hostname_cache::erase_expired_entries(); irods::experimental::net::dns_cache::erase_expired_entries(); }).interval(600); ix::cron::cron::get()->add_task(cache_clearer.build()); return serverMain(enable_test_mode, write_to_stdout); } static bool instantiate_shared_memory_for_plugin( const nlohmann::json& _plugin_object ) { const auto itr = _plugin_object.find(irods::CFG_SHARED_MEMORY_INSTANCE_KW); if(_plugin_object.end() != itr) { const auto mem_name = itr->get<const std::string>(); prepareServerSharedMemory(mem_name); detachSharedMemory(mem_name); return true; } return false; } static bool uninstantiate_shared_memory_for_plugin( const nlohmann::json& _plugin_object ) { const auto itr = _plugin_object.find(irods::CFG_SHARED_MEMORY_INSTANCE_KW); if(_plugin_object.end() != itr) { const auto mem_name = itr->get<const std::string>(); removeSharedMemory(mem_name); resetMutex(mem_name.c_str()); return true; } return false; } static irods::error instantiate_shared_memory( ) { try { for ( const auto& item : irods::get_server_property<const nlohmann::json&>(irods::CFG_PLUGIN_CONFIGURATION_KW).items() ) { for ( const auto& plugin : item.value().items() ) { instantiate_shared_memory_for_plugin(plugin.value()); } } } catch ( const boost::bad_any_cast& e ) { return ERROR(INVALID_ANY_CAST, e.what()); } catch ( const irods::exception& e ) { return irods::error(e); } return SUCCESS(); } // instantiate_shared_memory static irods::error uninstantiate_shared_memory( ) { try { for ( const auto& item : irods::get_server_property<const nlohmann::json&>(irods::CFG_PLUGIN_CONFIGURATION_KW).items()) { for ( const auto& plugin : item.value().items() ) { uninstantiate_shared_memory_for_plugin(plugin.value()); } } } catch ( const boost::bad_any_cast& e ) { return ERROR(INVALID_ANY_CAST, e.what()); } catch ( const irods::exception& e ) { return irods::error(e); } return SUCCESS(); } // uninstantiate_shared_memory int serverMain( const bool enable_test_mode = false, const bool write_to_stdout = false) { int acceptErrCnt = 0; // set re cache salt here irods::error ret = createAndSetRECacheSalt(); if ( !ret.ok() ) { rodsLog( LOG_ERROR, "serverMain: createAndSetRECacheSalt error.\n%s", ret.result().c_str() ); exit( 1 ); } ret = instantiate_shared_memory(); if(!ret.ok()) { irods::log(PASS(ret)); } irods::re_plugin_globals.reset(new irods::global_re_plugin_mgr); rsComm_t svrComm; int status = initServerMain(&svrComm, enable_test_mode, write_to_stdout); if ( status < 0 ) { rodsLog( LOG_ERROR, "serverMain: initServerMain error. status = %d", status ); exit( 1 ); } std::string svc_role; ret = get_catalog_service_role(svc_role); if(!ret.ok()) { irods::log(PASS(ret)); return ret.code(); } uint64_t return_code = 0; // =-=-=-=-=-=-=- // Launch the Control Plane try { irods::server_control_plane ctrl_plane( irods::CFG_SERVER_CONTROL_PLANE_PORT ); status = startProcConnReqThreads(); if(status < 0) { rodsLog(LOG_ERROR, "[%s] - Error in startProcConnReqThreads()", __FUNCTION__); return status; } if( irods::CFG_SERVICE_ROLE_PROVIDER == svc_role ) { try { PurgeLockFileThread = new boost::thread( purgeLockFileWorkerTask ); } catch ( const boost::thread_resource_error& ) { rodsLog( LOG_ERROR, "boost encountered a thread_resource_error during thread construction in serverMain." ); } } fd_set sockMask; FD_ZERO( &sockMask ); SvrSock = svrComm.sock; irods::server_state& server_state = irods::server_state::instance(); while ( true ) { std::string the_server_state = server_state(); if ( irods::server_state::STOPPED == the_server_state ) { procChildren( &ConnectedAgentHead ); // Wake up the agent factory process so it can clean up and exit kill( agent_spawning_pid, SIGTERM ); rodsLog( LOG_NOTICE, "iRODS Server is exiting with state [%s].", the_server_state.c_str() ); break; } else if ( irods::server_state::PAUSED == the_server_state ) { procChildren( &ConnectedAgentHead ); rodsSleep( 0, irods::SERVER_CONTROL_FWD_SLEEP_TIME_MILLI_SEC * 1000 ); continue; } else { if ( irods::server_state::RUNNING != the_server_state ) { rodsLog( LOG_NOTICE, "invalid iRODS server state [%s]", the_server_state.c_str() ); } } ix::cron::cron::get()->run(); FD_SET( svrComm.sock, &sockMask ); int numSock = 0; struct timeval time_out; time_out.tv_sec = 0; time_out.tv_usec = irods::SERVER_CONTROL_POLLING_TIME_MILLI_SEC * 1000; while ( ( numSock = select( svrComm.sock + 1, &sockMask, ( fd_set * ) NULL, ( fd_set * ) NULL, &time_out ) ) < 0 ) { if ( errno == EINTR ) { rodsLog( LOG_NOTICE, "serverMain: select() interrupted" ); FD_SET( svrComm.sock, &sockMask ); continue; } else { rodsLog( LOG_NOTICE, "serverMain: select() error, errno = %d", errno ); return -1; } } procChildren( &ConnectedAgentHead ); if ( 0 == numSock ) { continue; } const int newSock = rsAcceptConn( &svrComm ); if ( newSock < 0 ) { acceptErrCnt++; if ( acceptErrCnt > MAX_ACCEPT_ERR_CNT ) { rodsLog( LOG_ERROR, "serverMain: Too many socket accept error. Exiting" ); break; } else { rodsLog( LOG_NOTICE, "serverMain: acceptConn() error, errno = %d", errno ); continue; } } else { acceptErrCnt = 0; } status = chkAgentProcCnt(); if ( status < 0 ) { rodsLog( LOG_NOTICE, "serverMain: chkAgentProcCnt failed status = %d", status ); // =-=-=-=-=-=-=- // create network object to communicate to the network // plugin interface. repave with newSock as that is the // operational socket at this point irods::network_object_ptr net_obj; irods::error ret = irods::network_factory( &svrComm, net_obj ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); } else { ret = sendVersion( net_obj, status, 0, NULL, 0 ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); } } status = mySockClose( newSock ); printf( "close status = %d\n", status ); continue; } addConnReqToQue( &svrComm, newSock ); } if( irods::CFG_SERVICE_ROLE_PROVIDER == svc_role ) { try { PurgeLockFileThread->join(); } catch ( const boost::thread_resource_error& ) { rodsLog( LOG_ERROR, "boost encountered a thread_resource_error during join in serverMain." ); } } procChildren( &ConnectedAgentHead ); stopProcConnReqThreads(); server_state( irods::server_state::EXITED ); } catch ( const irods::exception& e_ ) { rodsLog( LOG_ERROR, "Exception caught in server loop\n%s", e_.what() ); return_code = e_.code(); } uninstantiate_shared_memory(); close( agent_conn_socket ); unlink( agent_factory_socket_file ); rmdir( agent_factory_socket_dir ); ix::log::server::info("iRODS Server is done."); return return_code; } void #if defined(linux_platform) || defined(aix_platform) || defined(solaris_platform) || defined(osx_platform) serverExit( int sig ) #else serverExit() #endif { #if 0 // RTS - rodsLog calls in signal handlers are unsafe - #3326 rodsLog( LOG_NOTICE, "rodsServer caught signal %d, exiting", sig ); #endif recordServerProcess( NULL ); /* unlink the process id file */ close( agent_conn_socket ); unlink( agent_factory_socket_file ); rmdir( agent_factory_socket_dir ); // Wake and terminate agent spawning process kill( agent_spawning_pid, SIGTERM ); exit( 1 ); } void usage( char *prog ) { printf( "Usage: %s [-uvVqs]\n", prog ); printf( " -u user command level, remain attached to the tty (foreground)\n" ); printf( " -v verbose (LOG_NOTICE)\n" ); printf( " -V very verbose (LOG_DEBUG10)\n" ); printf( " -q quiet (LOG_ERROR)\n" ); printf( " -s log SQL commands\n" ); } int procChildren( agentProc_t **agentProcHead ) { agentProc_t *tmpAgentProc, *prevAgentProc, *finishedAgentProc; prevAgentProc = NULL; boost::unique_lock< boost::mutex > con_agent_lock( ConnectedAgentMutex ); tmpAgentProc = *agentProcHead; while ( tmpAgentProc != NULL ) { // Check if pid is still an active process if ( kill( tmpAgentProc->pid, 0 ) ) { finishedAgentProc = tmpAgentProc; if ( prevAgentProc == NULL ) { *agentProcHead = tmpAgentProc->next; } else { prevAgentProc->next = tmpAgentProc->next; } tmpAgentProc = tmpAgentProc->next; free( finishedAgentProc ); } else { prevAgentProc = tmpAgentProc; tmpAgentProc = tmpAgentProc->next; } } con_agent_lock.unlock(); return 0; } agentProc_t * getAgentProcByPid( int childPid, agentProc_t **agentProcHead ) { agentProc_t *tmpAgentProc, *prevAgentProc; prevAgentProc = NULL; boost::unique_lock< boost::mutex > con_agent_lock( ConnectedAgentMutex ); tmpAgentProc = *agentProcHead; while ( tmpAgentProc != NULL ) { if ( childPid == tmpAgentProc->pid ) { if ( prevAgentProc == NULL ) { *agentProcHead = tmpAgentProc->next; } else { prevAgentProc->next = tmpAgentProc->next; } break; } prevAgentProc = tmpAgentProc; tmpAgentProc = tmpAgentProc->next; } con_agent_lock.unlock(); return tmpAgentProc; } int spawnAgent( agentProc_t *connReq, agentProc_t **agentProcHead ) { int childPid; int newSock; startupPack_t *startupPack; if ( connReq == NULL ) { return USER__NULL_INPUT_ERR; } newSock = connReq->sock; startupPack = &connReq->startupPack; childPid = execAgent( newSock, startupPack ); if (childPid > 0) { queueConnectedAgentProc(childPid, connReq, agentProcHead); } return childPid; } int sendEnvironmentVarIntToSocket ( const char* var, int val, int socket ) { std::stringstream msg; msg << var << "=" << val << ";"; ssize_t status = send( socket, msg.str().c_str(), msg.str().length(), 0 ); if ( status < 0 ) { rodsLog( LOG_ERROR, "Error in sendEnvironmentVarIntToSocket, errno = [%d]: %s", errno, strerror( errno ) ); } else if ( static_cast<size_t>(status) != msg.str().length() ) { rodsLog( LOG_DEBUG, "Failed to send entire message in sendEnvironmentVarIntToSocket - msg [%s] is [%d] bytes long, sent [%d] bytes", msg.str().c_str(), msg.str().length(), status ); } return status; } int sendEnvironmentVarStrToSocket ( const char* var, const char* val, int socket ) { std::stringstream msg; msg << var << "=" << val << ";"; ssize_t status = send( socket, msg.str().c_str(), msg.str().length(), 0 ); if ( status < 0 ) { rodsLog( LOG_ERROR, "Error in sendEnvironmentVarIntToSocket, errno = [%d]: %s", errno, strerror( errno ) ); } else if ( static_cast<size_t>(status) != msg.str().length() ) { rodsLog( LOG_DEBUG, "Failed to send entire message in sendEnvironmentVarIntToSocket - msg [%s] is [%d] bytes long, sent [%d] bytes", msg.str().c_str(), msg.str().length(), status ); } return status; } ssize_t sendSocketOverSocket( int writeFd, int socket ) { struct msghdr msg; struct iovec iov[1]; union { struct cmsghdr cm; char control[CMSG_SPACE(sizeof(int))]; } control_un; struct cmsghdr *cmptr; memset( control_un.control, 0, sizeof(control_un.control) ); msg.msg_control = control_un.control; msg.msg_controllen = sizeof(control_un.control); cmptr = CMSG_FIRSTHDR(&msg); cmptr->cmsg_len = CMSG_LEN(sizeof(int)); cmptr->cmsg_level = SOL_SOCKET; cmptr->cmsg_type = SCM_RIGHTS; *((int *) CMSG_DATA(cmptr)) = socket; msg.msg_name = NULL; msg.msg_namelen = 0; iov[0].iov_base = (void*) "i"; iov[0].iov_len = 1; msg.msg_iov = iov; msg.msg_iovlen = 1; return sendmsg( writeFd, &msg, 0); } int execAgent( int newSock, startupPack_t *startupPack ) { // Create unique socket for each call to exec agent char random_suffix[65]{}; get64RandomBytes(random_suffix); sockaddr_un tmp_socket_addr{}; char tmp_socket_file[sizeof(tmp_socket_addr.sun_path)]{}; snprintf(tmp_socket_file, sizeof(tmp_socket_file), "%s/irods_agent_%s", agent_factory_socket_dir, random_suffix); ssize_t status{send(agent_conn_socket, tmp_socket_file, strlen(tmp_socket_file), 0)}; if ( status < 0 ) { rodsLog( LOG_ERROR, "Error sending socket to agent factory process, errno = [%d]: %s", errno, strerror( errno ) ); } else if ( static_cast<size_t>(status) < strlen( tmp_socket_file ) ) { rodsLog( LOG_DEBUG, "Failed to send entire message - msg [%s] is [%d] bytes long, sent [%d] bytes", tmp_socket_file, strlen( tmp_socket_file ), status ); } tmp_socket_addr.sun_family = AF_UNIX; strncpy(tmp_socket_addr.sun_path, tmp_socket_file, sizeof(tmp_socket_addr.sun_path)); int tmp_socket{socket(AF_UNIX, SOCK_STREAM, 0)}; if ( tmp_socket < 0 ) { rodsLog( LOG_ERROR, "Unable to create socket in execAgent, errno = [%d]: %s", errno, strerror( errno ) ); } const auto cleanup_sockets{[&]() { if (close(tmp_socket) < 0) { rodsLog(LOG_ERROR, "close(tmp_socket) failed with errno = [%d]: %s", errno, strerror(errno)); } if (unlink(tmp_socket_file) < 0) { rodsLog(LOG_ERROR, "unlink(tmp_socket_file) failed with errno = [%d]: %s", errno, strerror(errno)); } }}; // Wait until receiving acknowledgement that socket has been created char in_buf[1024]{}; status = recv( agent_conn_socket, &in_buf, sizeof(in_buf), 0 ); if (status < 0) { rodsLog(LOG_ERROR, "Error in recv acknowledgement from agent factory process, errno = [%d]: %s", errno, strerror(errno)); status = SYS_SOCK_READ_ERR; } else if (0 != strcmp(in_buf, "OK")) { rodsLog(LOG_ERROR, "Bad acknowledgement from agent factory process, message = [%s]", in_buf); status = SYS_SOCK_READ_ERR; } else { status = connect(tmp_socket, (const struct sockaddr*) &tmp_socket_addr, sizeof(local_addr)); if (status < 0) { rodsLog(LOG_ERROR, "Unable to connect to socket in agent factory process, errno = [%d]: %s", errno, strerror(errno)); status = SYS_SOCK_CONNECT_ERR; } } if (status < 0) { // Agent factory expects a message about connection to the agent - send failure const std::string failure_message{"spawn_failure"}; send(agent_conn_socket, failure_message.c_str(), failure_message.length() + 1, 0); cleanup_sockets(); return status; } else { // Notify agent factory of success and send data to agent process const std::string connection_successful{"connection_successful"}; send(agent_conn_socket, connection_successful.c_str(), connection_successful.length() + 1, 0); } status = sendEnvironmentVarStrToSocket( SP_RE_CACHE_SALT,irods::get_server_property<const std::string>( irods::CFG_RE_CACHE_SALT_KW).c_str(), tmp_socket ); if (status < 0) { rodsLog( LOG_ERROR, "Failed to send SP_RE_CACHE_SALT to agent" ); } status = sendEnvironmentVarIntToSocket( SP_CONNECT_CNT, startupPack->connectCnt, tmp_socket); if (status < 0) { rodsLog( LOG_ERROR, "Failed to send SP_CONNECT_CNT to agent" ); } status = sendEnvironmentVarStrToSocket( SP_PROXY_RODS_ZONE, startupPack->proxyRodsZone, tmp_socket ); if (status < 0) { rodsLog( LOG_ERROR, "Failed to send SP_PROXY_RODS_ZONE to agent" ); } status = sendEnvironmentVarIntToSocket( SP_NEW_SOCK, newSock, tmp_socket ); if (status < 0) { rodsLog( LOG_ERROR, "Failed to send SP_NEW_SOCK to agent" ); } status = sendEnvironmentVarIntToSocket( SP_PROTOCOL, startupPack->irodsProt, tmp_socket ); if (status < 0) { rodsLog( LOG_ERROR, "Failed to send SP_PROTOCOL to agent" ); } status = sendEnvironmentVarIntToSocket( SP_RECONN_FLAG, startupPack->reconnFlag, tmp_socket ); if (status < 0) { rodsLog( LOG_ERROR, "Failed to send SP_RECONN_FLAG to agent" ); } status = sendEnvironmentVarStrToSocket( SP_PROXY_USER, startupPack->proxyUser, tmp_socket ); if (status < 0) { rodsLog( LOG_ERROR, "Failed to send SP_PROXY_USER to agent" ); } status = sendEnvironmentVarStrToSocket( SP_CLIENT_USER, startupPack->clientUser, tmp_socket ); if (status < 0) { rodsLog( LOG_ERROR, "Failed to send SP_CLIENT_USER to agent" ); } status = sendEnvironmentVarStrToSocket( SP_CLIENT_RODS_ZONE, startupPack->clientRodsZone, tmp_socket ); if (status < 0) { rodsLog( LOG_ERROR, "Failed to send SP_CLIENT_RODS_ZONE to agent" ); } status = sendEnvironmentVarStrToSocket( SP_REL_VERSION, startupPack->relVersion, tmp_socket ); if (status < 0) { rodsLog( LOG_ERROR, "Failed to send SP_REL_VERSION to agent" ); } status = sendEnvironmentVarStrToSocket( SP_API_VERSION, startupPack->apiVersion, tmp_socket ); if (status < 0) { rodsLog( LOG_ERROR, "Failed to send SP_API_VERSION to agent" ); } // =-=-=-=-=-=-=- // if the client-server negotiation request is in the // option variable, set that env var and strip it out std::string opt_str( startupPack->option ); size_t pos = opt_str.find( REQ_SVR_NEG ); if ( std::string::npos != pos ) { std::string trunc_str = opt_str.substr( 0, pos ); status = sendEnvironmentVarStrToSocket( SP_OPTION, trunc_str.c_str(), tmp_socket ); if (status < 0) { rodsLog( LOG_ERROR, "Failed to send SP_OPTION to agent" ); } status = sendEnvironmentVarStrToSocket( irods::RODS_CS_NEG, REQ_SVR_NEG, tmp_socket ); if (status < 0) { rodsLog( LOG_ERROR, "Failed to send irods::RODS_CS_NEG to agent" ); } } else { status = sendEnvironmentVarStrToSocket( SP_OPTION, startupPack->option, tmp_socket ); if (status < 0) { rodsLog( LOG_ERROR, "Failed to send SP_OPTION to agent" ); } } status = sendEnvironmentVarIntToSocket( SERVER_BOOT_TIME, ServerBootTime, tmp_socket ); if (status < 0) { rodsLog( LOG_ERROR, "Failed to send SERVER_BOOT_TIME to agent" ); } status = send( tmp_socket, "end_of_vars", 12, 0 ); if ( status <= 0 ) { rodsLog( LOG_ERROR, "Failed to send \"end_of_vars;\" to agent" ); } status = recv( tmp_socket, &in_buf, sizeof(in_buf), 0 ); if ( status < 0 ) { rodsLog( LOG_ERROR, "Error in recv acknowledgement from agent factory process, errno = [%d]: %s", errno, strerror( errno ) ); cleanup_sockets(); return SYS_SOCK_READ_ERR; } else if ( strcmp(in_buf, "OK") != 0 ) { rodsLog( LOG_ERROR, "Bad acknowledgement from agent factory process, message = [%s]", in_buf ); cleanup_sockets(); return SYS_SOCK_READ_ERR; } sendSocketOverSocket( tmp_socket, newSock ); status = recv( tmp_socket, &in_buf, sizeof(in_buf), 0 ); if ( status < 0 ) { rodsLog( LOG_ERROR, "Error in recv child_pid from agent factory process, errno = [%d]: %s", errno, strerror( errno ) ); cleanup_sockets(); return SYS_SOCK_READ_ERR; } cleanup_sockets(); return std::atoi(in_buf); } int queueConnectedAgentProc( int childPid, agentProc_t *connReq, agentProc_t **agentProcHead ) { if ( connReq == NULL ) { return USER__NULL_INPUT_ERR; } connReq->pid = childPid; boost::unique_lock< boost::mutex > con_agent_lock( ConnectedAgentMutex ); queueAgentProc( connReq, agentProcHead, TOP_POS ); con_agent_lock.unlock(); return 0; } int getAgentProcCnt() { agentProc_t *tmpAgentProc; int count = 0; boost::unique_lock< boost::mutex > con_agent_lock( ConnectedAgentMutex ); tmpAgentProc = ConnectedAgentHead; while ( tmpAgentProc != NULL ) { count++; tmpAgentProc = tmpAgentProc->next; } con_agent_lock.unlock(); return count; } int getAgentProcPIDs( std::vector<int>& _pids ) { agentProc_t *tmp_proc = 0; int count = 0; boost::unique_lock< boost::mutex > con_agent_lock( ConnectedAgentMutex ); tmp_proc = ConnectedAgentHead; while ( tmp_proc != NULL ) { count++; _pids.push_back( tmp_proc->pid ); tmp_proc = tmp_proc->next; } con_agent_lock.unlock(); return count; } // getAgentProcPIDs int chkAgentProcCnt() { int maximum_connections = NO_MAX_CONNECTION_LIMIT; try { if(irods::server_property_exists("maximum_connections")) { maximum_connections = irods::get_server_property<const int>("maximum_connections"); int count = getAgentProcCnt(); if ( count >= maximum_connections ) { chkConnectedAgentProcQue(); count = getAgentProcCnt(); if ( count >= maximum_connections ) { return SYS_MAX_CONNECT_COUNT_EXCEEDED; } } } } catch ( const nlohmann::json::exception& e ) { rodsLog(LOG_ERROR, "%s failed with message [%s]", e.what()); return SYS_INTERNAL_ERR; } return 0; } int chkConnectedAgentProcQue() { agentProc_t *tmpAgentProc, *prevAgentProc, *unmatchedAgentProc; prevAgentProc = NULL; boost::unique_lock< boost::mutex > con_agent_lock( ConnectedAgentMutex ); tmpAgentProc = ConnectedAgentHead; while ( tmpAgentProc != NULL ) { char procPath[MAX_NAME_LEN]; snprintf( procPath, MAX_NAME_LEN, "%s/%-d", ProcLogDir, tmpAgentProc->pid ); path p( procPath ); if ( !exists( p ) ) { /* the agent proc is gone */ unmatchedAgentProc = tmpAgentProc; rodsLog( LOG_DEBUG, "Agent process %d in Connected queue but not in ProcLogDir", tmpAgentProc->pid ); if ( prevAgentProc == NULL ) { ConnectedAgentHead = tmpAgentProc->next; } else { prevAgentProc->next = tmpAgentProc->next; } tmpAgentProc = tmpAgentProc->next; free( unmatchedAgentProc ); } else { prevAgentProc = tmpAgentProc; tmpAgentProc = tmpAgentProc->next; } } con_agent_lock.unlock(); return 0; } int initServer( rsComm_t *svrComm ) { int status; rodsServerHost_t *rodsServerHost = NULL; status = initServerInfo( 0, svrComm ); if ( status < 0 ) { rodsLog( LOG_NOTICE, "initServer: initServerInfo error, status = %d", status ); return status; } // JMC - legacy resources - printLocalResc (); resc_mgr.print_local_resources(); printZoneInfo(); status = getRcatHost( MASTER_RCAT, NULL, &rodsServerHost ); if ( status < 0 || NULL == rodsServerHost ) { // JMC cppcheck - nullptr return status; } std::string svc_role; irods::error ret = get_catalog_service_role(svc_role); if(!ret.ok()) { irods::log(PASS(ret)); return ret.code(); } if ( rodsServerHost->localFlag == LOCAL_HOST ) { if( irods::CFG_SERVICE_ROLE_PROVIDER == svc_role ) { disconnectRcat(); } } else { if ( rodsServerHost->conn != NULL ) { rcDisconnect( rodsServerHost->conn ); rodsServerHost->conn = NULL; } } if( irods::CFG_SERVICE_ROLE_PROVIDER == svc_role ) { purgeLockFileDir( 0 ); } return status; } /* record the server process number and other information into a well-known file. If svrComm is Null and this has created a file before, just unlink the file. */ int recordServerProcess( rsComm_t *svrComm ) { int myPid; FILE *fd; DIR *dirp; static char filePath[100] = ""; char cwd[1000]; char stateFile[] = "irodsServer"; char *tmp; char *cp; if ( svrComm == NULL ) { if ( filePath[0] != '\0' ) { unlink( filePath ); } return 0; } rodsEnv *myEnv = &( svrComm->myEnv ); /* Use /usr/tmp if it exists, /tmp otherwise */ dirp = opendir( "/usr/tmp" ); if ( dirp != NULL ) { tmp = "/usr/tmp"; ( void )closedir( dirp ); } else { tmp = "/tmp"; } sprintf( filePath, "%s/%s.%d", tmp, stateFile, myEnv->rodsPort ); unlink( filePath ); myPid = getpid(); cp = getcwd( cwd, 1000 ); if ( cp != NULL ) { fd = fopen( filePath, "w" ); if ( fd != NULL ) { fprintf( fd, "%d %s\n", myPid, cwd ); fclose( fd ); int err_code = chmod( filePath, 0664 ); if ( err_code != 0 ) { rodsLog( LOG_ERROR, "chmod failed in recordServerProcess on [%s] with error code %d", filePath, err_code ); } } } return 0; } int initServerMain( rsComm_t *svrComm, const bool enable_test_mode = false, const bool write_to_stdout = false) { memset( svrComm, 0, sizeof( *svrComm ) ); int status = getRodsEnv( &svrComm->myEnv ); if ( status < 0 ) { rodsLog( LOG_ERROR, "initServerMain: getRodsEnv error. status = %d", status ); return status; } initAndClearProcLog(); setRsCommFromRodsEnv( svrComm ); status = initServer( svrComm ); if ( status < 0 ) { rodsLog( LOG_ERROR, "initServerMain: initServer error. status = %d", status ); exit( 1 ); } int zone_port; try { zone_port = irods::get_server_property<const int>(irods::CFG_ZONE_PORT); } catch ( irods::exception& e ) { irods::log( irods::error(e) ); return e.code(); } svrComm->sock = sockOpenForInConn( svrComm, &zone_port, NULL, SOCK_STREAM ); if ( svrComm->sock < 0 ) { rodsLog( LOG_ERROR, "initServerMain: sockOpenForInConn error. status = %d", svrComm->sock ); return svrComm->sock; } if ( listen( svrComm->sock, MAX_LISTEN_QUE ) < 0 ) { rodsLog( LOG_ERROR, "initServerMain: listen failed, errno: %d", errno ); return SYS_SOCK_LISTEN_ERR; } ix::log::server::info("rodsServer Release version {} - API Version {} is up", RODS_REL_VERSION, RODS_API_VERSION); /* Record port, pid, and cwd into a well-known file */ recordServerProcess(svrComm); ix::cron::cron_builder delay_server; const auto start_delay_server = [&](std::any& _){ rodsServerHost_t* reServerHost{}; getReHost(&reServerHost); std::optional<pid_t> delay_pid; if(irods::server_properties::instance().contains(irods::RE_PID_KW)){ delay_pid = irods::get_server_property<int>(irods::RE_PID_KW); } if (reServerHost && LOCAL_HOST == reServerHost->localFlag) { if(!delay_pid.has_value() || waitpid(delay_pid.value(), nullptr, WNOHANG) != 0){ ix::log::server::info("Forking Rule Execution Server (irodsReServer) ..."); const int pid = RODS_FORK(); if (pid == 0) { close(svrComm->sock); std::vector<char*> argv; argv.push_back("irodsReServer"); if (enable_test_mode) { argv.push_back("-t"); } if (write_to_stdout) { argv.push_back("-u"); } argv.push_back(nullptr); // Launch the delay server! execv(argv[0], &argv[0]); exit(1); } else { irods::set_server_property<int>(irods::RE_PID_KW, pid); } } }else if( reServerHost && delay_pid.has_value() && waitpid(delay_pid.value(), nullptr, WNOHANG) == 0 ) { // If the delay server exists but we shouldn't have it on this instance, then kill it. ix::log::server::info("We are no longer the delay server host. Ending process"); // Sending SIGTERM causes the delay server to finish all tasks and exit gracefully. kill(delay_pid.value(), SIGTERM); waitpid(delay_pid.value(), nullptr, WNOHANG); irods::server_properties::instance().remove(irods::RE_PID_KW); } }; std::any dummy; start_delay_server(dummy); delay_server.to_execute(start_delay_server).interval(5); ix::cron::cron::get()->add_task(delay_server.build()); return 0; } /* add incoming connection request to the bottom of the link list */ int addConnReqToQue( rsComm_t *rsComm, int sock ) { agentProc_t *myConnReq; boost::unique_lock< boost::mutex > read_req_lock( ReadReqCondMutex ); myConnReq = ( agentProc_t* )calloc( 1, sizeof( agentProc_t ) ); myConnReq->sock = sock; myConnReq->remoteAddr = rsComm->remoteAddr; queueAgentProc( myConnReq, &ConnReqHead, BOTTOM_POS ); ReadReqCond.notify_all(); // NOTE:: check all vs one read_req_lock.unlock(); return 0; } int initConnThreadEnv() { return 0; } agentProc_t * getConnReqFromQue() { agentProc_t *myConnReq = NULL; irods::server_state& server_state = irods::server_state::instance(); while ( irods::server_state::STOPPED != server_state() && irods::server_state::EXITED != server_state() && myConnReq == NULL ) { boost::unique_lock<boost::mutex> read_req_lock( ReadReqCondMutex ); if ( ConnReqHead != NULL ) { myConnReq = ConnReqHead; ConnReqHead = ConnReqHead->next; read_req_lock.unlock(); break; } ReadReqCond.wait( read_req_lock ); if ( ConnReqHead == NULL ) { read_req_lock.unlock(); continue; } else { myConnReq = ConnReqHead; ConnReqHead = ConnReqHead->next; read_req_lock.unlock(); break; } } return myConnReq; } int startProcConnReqThreads() { initConnThreadEnv(); for ( int i = 0; i < NUM_READ_WORKER_THR; i++ ) { try { ReadWorkerThread[i] = new boost::thread( readWorkerTask ); } catch ( const boost::thread_resource_error& ) { rodsLog( LOG_ERROR, "boost encountered a thread_resource_error during thread construction in startProcConnReqThreads." ); return SYS_THREAD_RESOURCE_ERR; } } try { SpawnManagerThread = new boost::thread( spawnManagerTask ); } catch ( const boost::thread_resource_error& ) { rodsLog( LOG_ERROR, "boost encountered a thread_resource_error during thread construction in startProcConnReqThreads." ); return SYS_THREAD_RESOURCE_ERR; } return 0; } void stopProcConnReqThreads() { SpawnReqCond.notify_all(); try { SpawnManagerThread->join(); } catch ( const boost::thread_resource_error& ) { rodsLog( LOG_ERROR, "boost encountered a thread_resource_error during join in stopProcConnReqThreads." ); } for ( int i = 0; i < NUM_READ_WORKER_THR; i++ ) { ReadReqCond.notify_all(); try { ReadWorkerThread[i]->join(); } catch ( const boost::thread_resource_error& ) { rodsLog( LOG_ERROR, "boost encountered a thread_resource_error during join in stopProcConnReqThreads." ); } } } void readWorkerTask() { // =-=-=-=-=-=-=- // artificially create a conn object in order to // create a network object. this is gratuitous // but necessary to maintain the consistent interface. rcComm_t tmp_comm; std::memset(&tmp_comm, 0, sizeof(rcComm_t)); irods::network_object_ptr net_obj; irods::error ret = irods::network_factory( &tmp_comm, net_obj ); if ( !ret.ok() || !net_obj.get() ) { irods::log( PASS( ret ) ); return; } irods::server_state& server_state = irods::server_state::instance(); while ( irods::server_state::STOPPED != server_state() && irods::server_state::EXITED != server_state() ) { agentProc_t *myConnReq = getConnReqFromQue(); if ( myConnReq == NULL ) { /* someone else took care of it */ continue; } int newSock = myConnReq->sock; // =-=-=-=-=-=-=- // repave the socket handle with the new socket // for this connection net_obj->socket_handle( newSock ); startupPack_t *startupPack = nullptr; struct timeval tv; tv.tv_sec = READ_STARTUP_PACK_TOUT_SEC; tv.tv_usec = 0; irods::error ret = readStartupPack( net_obj, &startupPack, &tv ); if ( !ret.ok() ) { rodsLog( LOG_ERROR, "readWorkerTask - readStartupPack failed. %d", ret.code() ); sendVersion( net_obj, ret.code(), 0, NULL, 0 ); boost::unique_lock<boost::mutex> bad_req_lock( BadReqMutex ); queueAgentProc( myConnReq, &BadReqHead, TOP_POS ); bad_req_lock.unlock(); mySockClose( newSock ); } else if ( strcmp(startupPack->option, RODS_HEARTBEAT_T) == 0 ) { const char* heartbeat = RODS_HEARTBEAT_T; const int heartbeat_length = strlen(heartbeat); int bytes_to_send = heartbeat_length; while ( bytes_to_send ) { const int bytes_sent = send(newSock, &(heartbeat[heartbeat_length - bytes_to_send]), bytes_to_send, 0); const int errsav = errno; if ( bytes_sent > 0 ) { bytes_to_send -= bytes_sent; } else if ( errsav != EINTR ) { rodsLog(LOG_ERROR, "Socket error encountered during heartbeat; socket returned %s", strerror(errsav)); break; } } mySockClose(newSock); free( myConnReq ); free( startupPack ); } else if ( startupPack->connectCnt > MAX_SVR_SVR_CONNECT_CNT ) { sendVersion( net_obj, SYS_EXCEED_CONNECT_CNT, 0, NULL, 0 ); mySockClose( newSock ); free( myConnReq ); free( startupPack ); } else { if ( startupPack->clientUser[0] == '\0' ) { int status = chkAllowedUser( startupPack->clientUser, startupPack->clientRodsZone ); if ( status < 0 ) { sendVersion( net_obj, status, 0, NULL, 0 ); mySockClose( newSock ); free( myConnReq ); continue; } } myConnReq->startupPack = *startupPack; free( startupPack ); boost::unique_lock< boost::mutex > spwn_req_lock( SpawnReqCondMutex ); queueAgentProc( myConnReq, &SpawnReqHead, BOTTOM_POS ); SpawnReqCond.notify_all(); // NOTE:: look into notify_one vs notify_all } // else } // while 1 } // readWorkerTask void spawnManagerTask() { agentProc_t *mySpawnReq = NULL; int status; uint curTime; uint agentQueChkTime = 0; irods::server_state& server_state = irods::server_state::instance(); while ( irods::server_state::STOPPED != server_state() && irods::server_state::EXITED != server_state() ) { boost::unique_lock<boost::mutex> spwn_req_lock( SpawnReqCondMutex ); SpawnReqCond.wait( spwn_req_lock ); while ( SpawnReqHead != NULL ) { mySpawnReq = SpawnReqHead; SpawnReqHead = mySpawnReq->next; spwn_req_lock.unlock(); status = spawnAgent( mySpawnReq, &ConnectedAgentHead ); close( mySpawnReq->sock ); if ( status < 0 ) { rodsLog( LOG_NOTICE, "spawnAgent error for puser=%s and cuser=%s from %s, stat=%d", mySpawnReq->startupPack.proxyUser, mySpawnReq->startupPack.clientUser, inet_ntoa( mySpawnReq->remoteAddr.sin_addr ), status ); free( mySpawnReq ); } else { rodsLog( LOG_DEBUG, "Agent process %d started for puser=%s and cuser=%s from %s", mySpawnReq->pid, mySpawnReq->startupPack.proxyUser, mySpawnReq->startupPack.clientUser, inet_ntoa( mySpawnReq->remoteAddr.sin_addr ) ); } spwn_req_lock.lock(); } spwn_req_lock.unlock(); curTime = time( 0 ); if ( curTime > agentQueChkTime + AGENT_QUE_CHK_INT ) { agentQueChkTime = curTime; procBadReq(); } } } int procSingleConnReq( agentProc_t *connReq ) { if ( connReq == NULL ) { return USER__NULL_INPUT_ERR; } int newSock = connReq->sock; // =-=-=-=-=-=-=- // artificially create a conn object in order to // create a network object. this is gratuitous // but necessary to maintain the consistent interface. rcComm_t tmp_comm; std::memset(&tmp_comm, 0, sizeof(rcComm_t)); irods::network_object_ptr net_obj; irods::error ret = irods::network_factory( &tmp_comm, net_obj ); if ( !ret.ok() ) { irods::log( PASS( ret ) ); return -1; } net_obj->socket_handle( newSock ); startupPack_t *startupPack; ret = readStartupPack( net_obj, &startupPack, NULL ); if ( !ret.ok() ) { rodsLog( LOG_NOTICE, "readStartupPack error from %s, status = %d", inet_ntoa( connReq->remoteAddr.sin_addr ), ret.code() ); sendVersion( net_obj, ret.code(), 0, NULL, 0 ); mySockClose( newSock ); return ret.code(); } if ( startupPack->connectCnt > MAX_SVR_SVR_CONNECT_CNT ) { sendVersion( net_obj, SYS_EXCEED_CONNECT_CNT, 0, NULL, 0 ); mySockClose( newSock ); return SYS_EXCEED_CONNECT_CNT; } connReq->startupPack = *startupPack; free( startupPack ); int status = spawnAgent( connReq, &ConnectedAgentHead ); close( newSock ); if ( status < 0 ) { rodsLog( LOG_NOTICE, "spawnAgent error for puser=%s and cuser=%s from %s, status = %d", connReq->startupPack.proxyUser, connReq->startupPack.clientUser, inet_ntoa( connReq->remoteAddr.sin_addr ), status ); } else { rodsLog( LOG_DEBUG, "Agent process %d started for puser=%s and cuser=%s from %s", connReq->pid, connReq->startupPack.proxyUser, connReq->startupPack.clientUser, inet_ntoa( connReq->remoteAddr.sin_addr ) ); } return status; } /* procBadReq - process bad request */ int procBadReq() { agentProc_t *tmpConnReq, *nextConnReq; /* just free them for now */ boost::unique_lock< boost::mutex > bad_req_lock( BadReqMutex ); tmpConnReq = BadReqHead; while ( tmpConnReq != NULL ) { nextConnReq = tmpConnReq->next; free( tmpConnReq ); tmpConnReq = nextConnReq; } BadReqHead = NULL; bad_req_lock.unlock(); return 0; } // =-=-=-=-=-=-=- // JMC - backport 4612 void purgeLockFileWorkerTask() { size_t wait_time_ms = 0; const size_t purge_time_ms = LOCK_FILE_PURGE_TIME * 1000; // s to ms irods::server_state& server_state = irods::server_state::instance(); while ( irods::server_state::STOPPED != server_state() && irods::server_state::EXITED != server_state() ) { rodsSleep( 0, irods::SERVER_CONTROL_POLLING_TIME_MILLI_SEC * 1000 ); // second, microseconds wait_time_ms += irods::SERVER_CONTROL_POLLING_TIME_MILLI_SEC; if ( wait_time_ms >= purge_time_ms ) { wait_time_ms = 0; int status = purgeLockFileDir( 1 ); if ( status < 0 ) { rodsLogError( LOG_ERROR, status, "purgeLockFileWorkerTask: purgeLockFileDir failed" ); } } // if } // while } // purgeLockFileWorkerTask std::vector<std::string> setExecArg( const char *commandArgv ) { std::vector<std::string> arguments; if ( commandArgv != NULL ) { int len = 0; bool openQuote = false; const char* cur = commandArgv; for ( int i = 0; commandArgv[i] != '\0'; i++ ) { if ( commandArgv[i] == ' ' && !openQuote ) { if ( len > 0 ) { /* end of a argv */ std::string( cur, len ); arguments.push_back( std::string( cur, len ) ); /* reset inx and pointer */ cur = &commandArgv[i + 1]; len = 0; } else { /* skip over blanks */ cur = &commandArgv[i + 1]; } } else if ( commandArgv[i] == '\'' || commandArgv[i] == '\"' ) { openQuote ^= true; if ( openQuote ) { /* skip the quote */ cur = &commandArgv[i + 1]; } } else { len ++; } } if ( len > 0 ) { /* handle the last argv */ arguments.push_back( std::string( cur, len ) ); } } return arguments; } // =-=-=-=-=-=-=-
34.434641
189
0.587454
[ "object", "vector" ]
4f7565ac8ff0189cb49cde83440cd816c3635673
2,141
cpp
C++
euler/tasks/60/main.cpp
pg83/zm
ef9027bd9ee260118fdf80e8b53361da1b7892f3
[ "MIT" ]
null
null
null
euler/tasks/60/main.cpp
pg83/zm
ef9027bd9ee260118fdf80e8b53361da1b7892f3
[ "MIT" ]
null
null
null
euler/tasks/60/main.cpp
pg83/zm
ef9027bd9ee260118fdf80e8b53361da1b7892f3
[ "MIT" ]
null
null
null
#include <euler/lib/euler.h> static bool is_prime(const std::string& s) { return is_prime_stupid(from_string<int>(s)); } template <class S, class K> static bool has(const S& s, const K& k) { return s.find(k) != s.end(); } template <class S> S inter(const S& l, const S& r) { if (l.size() > r.size()) { return inter(r, l); } S res; for (auto v : l) { if (has(r, v)) { res.insert(v); } } return res; } int main() { std::vector<int> primes; for (int i = 0; i < 10000; ++i) { if (is_prime_stupid(i)) { primes.push_back(i); } } std::map<int, std::set<int>> rrr; for (auto a : primes) { for (auto b : primes) { auto sa = std::to_string(a); auto sb = std::to_string(b); if (is_prime(sa + sb) && is_prime(sb + sa)) { rrr[a].insert(b); rrr[b].insert(a); } } } for (auto& [k, iss1] : rrr) { if (iss1.size() > 3) { for (auto& i : iss1) { if (has(rrr, i)) { auto iss2 = inter(rrr[i], iss1); if (iss2.size() > 2) { for (auto& j : iss2) { if (has(rrr, j)) { auto iss3 = inter(rrr[j], iss2); if (iss3.size() > 1) { for (auto& h : iss3) { if (has(rrr, h)) { auto iss4 = inter(rrr[h], iss3); if (iss4.size() > 0) { std::cout << k + i + j + h + *iss4.begin() << std::endl; return 0; } } } } } } } } } } } }
25.488095
104
0.317142
[ "vector" ]
4f7694482c3d141665342c774862de2dae7a8c77
56,756
cpp
C++
Engine/source/T3D/fx/precipitation.cpp
vbillet/Torque3D
ece8823599424ea675e5f79d9bcb44e42cba8cae
[ "MIT" ]
2,113
2015-01-01T11:23:01.000Z
2022-03-28T04:51:46.000Z
Engine/source/T3D/fx/precipitation.cpp
vbillet/Torque3D
ece8823599424ea675e5f79d9bcb44e42cba8cae
[ "MIT" ]
948
2015-01-02T01:50:00.000Z
2022-02-27T05:56:40.000Z
Engine/source/T3D/fx/precipitation.cpp
vbillet/Torque3D
ece8823599424ea675e5f79d9bcb44e42cba8cae
[ "MIT" ]
944
2015-01-01T09:33:53.000Z
2022-03-15T22:23:03.000Z
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- #include "platform/platform.h" #include "T3D/fx/precipitation.h" #include "math/mathIO.h" #include "console/consoleTypes.h" #include "console/typeValidators.h" #include "scene/sceneManager.h" #include "scene/sceneRenderState.h" #include "lighting/lightInfo.h" #include "lighting/lightManager.h" #include "materials/shaderData.h" #include "T3D/gameBase/gameConnection.h" #include "T3D/player.h" #include "core/stream/bitStream.h" #include "platform/profiler.h" #include "renderInstance/renderPassManager.h" #include "sfx/sfxSystem.h" #include "sfx/sfxTrack.h" #include "sfx/sfxSource.h" #include "sfx/sfxTypes.h" #include "console/engineAPI.h" #include "particleEmitter.h" static const U32 dropHitMask = TerrainObjectType | WaterObjectType | StaticShapeObjectType; IMPLEMENT_CO_NETOBJECT_V1(Precipitation); IMPLEMENT_CO_DATABLOCK_V1(PrecipitationData); ConsoleDocClass( Precipitation, "@brief Defines a precipitation based storm (rain, snow, etc).\n\n" "The Precipitation effect works by creating many 'drops' within a fixed size " "box. This box can be configured to move around with the camera (to simulate " "level-wide precipitation), or to remain in a fixed position (to simulate " "localized precipitation). When #followCam is true, the box containing the " "droplets can be thought of as centered on the camera then pushed slightly " "forward in the direction the camera is facing so most of the box is in " "front of the camera (allowing more drops to be visible on screen at once).\n\n" "The effect can also be configured to create a small 'splash' whenever a drop " "hits another world object.\n\n" "@tsexample\n" "// The following is added to a level file (.mis) by the World Editor\n" "new Precipitation( TheRain )\n" "{\n" " dropSize = \"0.5\";\n" " splashSize = \"0.5\";\n" " splashMS = \"250\";\n" " animateSplashes = \"1\";\n" " dropAnimateMS = \"0\";\n" " fadeDist = \"0\";\n" " fadeDistEnd = \"0\";\n" " useTrueBillboards = \"0\";\n" " useLighting = \"0\";\n" " glowIntensity = \"0 0 0 0\";\n" " reflect = \"0\";\n" " rotateWithCamVel = \"1\";\n" " doCollision = \"1\";\n" " hitPlayers = \"0\";\n" " hitVehicles = \"0\";\n" " followCam = \"1\";\n" " useWind = \"0\";\n" " minSpeed = \"1.5\";\n" " maxSpeed = \"2\";\n" " minMass = \"0.75\";\n" " maxMass = \"0.85\";\n" " useTurbulence = \"0\";\n" " maxTurbulence = \"0.1\";\n" " turbulenceSpeed = \"0.2\";\n" " numDrops = \"1024\";\n" " boxWidth = \"200\";\n" " boxHeight = \"100\";\n" " dataBlock = \"HeavyRain\";\n" "};\n" "@endtsexample\n" "@ingroup FX\n" "@ingroup Atmosphere\n" "@see PrecipitationData\n" ); ConsoleDocClass( PrecipitationData, "@brief Defines the droplets used in a storm (raindrops, snowflakes, etc).\n\n" "@tsexample\n" "datablock PrecipitationData( HeavyRain )\n" "{\n" " soundProfile = \"HeavyRainSound\";\n" " dropTexture = \"art/environment/precipitation/rain\";\n" " splashTexture = \"art/environment/precipitation/water_splash\";\n" " dropsPerSide = 4;\n" " splashesPerSide = 2;\n" "};\n" "@endtsexample\n" "@ingroup FX\n" "@ingroup Atmosphere\n" "@see Precipitation\n" ); //---------------------------------------------------------- // PrecipitationData //---------------------------------------------------------- PrecipitationData::PrecipitationData() { soundProfile = NULL; mDropName = StringTable->EmptyString(); mDropShaderName = StringTable->EmptyString(); mSplashName = StringTable->EmptyString(); mSplashShaderName = StringTable->EmptyString(); mDropsPerSide = 4; mSplashesPerSide = 2; } void PrecipitationData::initPersistFields() { addField( "soundProfile", TYPEID< SFXTrack >(), Offset(soundProfile, PrecipitationData), "Looping SFXProfile effect to play while Precipitation is active." ); addField( "dropTexture", TypeFilename, Offset(mDropName, PrecipitationData), "@brief Texture filename for drop particles.\n\n" "The drop texture can contain several different drop sub-textures " "arranged in a grid. There must be the same number of rows as columns. A " "random frame will be chosen for each drop." ); addField( "dropShader", TypeString, Offset(mDropShaderName, PrecipitationData), "The name of the shader used for raindrops." ); addField( "splashTexture", TypeFilename, Offset(mSplashName, PrecipitationData), "@brief Texture filename for splash particles.\n\n" "The splash texture can contain several different splash sub-textures " "arranged in a grid. There must be the same number of rows as columns. A " "random frame will be chosen for each splash." ); addField( "splashShader", TypeString, Offset(mSplashShaderName, PrecipitationData), "The name of the shader used for splashes." ); addField( "dropsPerSide", TypeS32, Offset(mDropsPerSide, PrecipitationData), "@brief How many rows and columns are in the raindrop texture.\n\n" "For example, if the texture has 16 raindrops arranged in a grid, this " "field should be set to 4." ); addField( "splashesPerSide", TypeS32, Offset(mSplashesPerSide, PrecipitationData), "@brief How many rows and columns are in the splash texture.\n\n" "For example, if the texture has 9 splashes arranged in a grid, this " "field should be set to 3." ); Parent::initPersistFields(); } bool PrecipitationData::preload( bool server, String &errorStr ) { if( Parent::preload( server, errorStr) == false) return false; if( !server && !sfxResolve( &soundProfile, errorStr ) ) return false; return true; } void PrecipitationData::packData(BitStream* stream) { Parent::packData(stream); sfxWrite( stream, soundProfile ); stream->writeString(mDropName); stream->writeString(mDropShaderName); stream->writeString(mSplashName); stream->writeString(mSplashShaderName); stream->write(mDropsPerSide); stream->write(mSplashesPerSide); } void PrecipitationData::unpackData(BitStream* stream) { Parent::unpackData(stream); sfxRead( stream, &soundProfile ); mDropName = stream->readSTString(); mDropShaderName = stream->readSTString(); mSplashName = stream->readSTString(); mSplashShaderName = stream->readSTString(); stream->read(&mDropsPerSide); stream->read(&mSplashesPerSide); } //---------------------------------------------------------- // Precipitation! //---------------------------------------------------------- Precipitation::Precipitation() { mTypeMask |= ProjectileObjectType; mDataBlock = NULL; mTexCoords = NULL; mSplashCoords = NULL; mDropShader = NULL; mDropHandle = NULL; mSplashShader = NULL; mSplashHandle = NULL; mDropHead = NULL; mSplashHead = NULL; mNumDrops = 1024; mPercentage = 1.0; mMinSpeed = 1.5; mMaxSpeed = 2.0; mFollowCam = true; mLastRenderFrame = 0; mDropHitMask = 0; mDropSize = 0.5; mSplashSize = 0.5; mUseTrueBillboards = false; mSplashMS = 250; mAnimateSplashes = true; mDropAnimateMS = 0; mUseLighting = false; mGlowIntensity = LinearColorF( 0,0,0,0 ); mReflect = false; mUseWind = false; mBoxWidth = 200; mBoxHeight = 100; mFadeDistance = 0; mFadeDistanceEnd = 0; mMinMass = 0.75f; mMaxMass = 0.85f; mMaxTurbulence = 0.1f; mTurbulenceSpeed = 0.2f; mUseTurbulence = false; mRotateWithCamVel = true; mDoCollision = true; mDropHitPlayers = false; mDropHitVehicles = false; mStormData.valid = false; mStormData.startPct = 0; mStormData.endPct = 0; mStormData.startTime = 0; mStormData.totalTime = 0; mTurbulenceData.valid = false; mTurbulenceData.startTime = 0; mTurbulenceData.totalTime = 0; mTurbulenceData.startMax = 0; mTurbulenceData.startSpeed = 0; mTurbulenceData.endMax = 0; mTurbulenceData.endSpeed = 0; mAmbientSound = NULL; mDropShaderModelViewSC = NULL; mDropShaderFadeStartEndSC = NULL; mDropShaderCameraPosSC = NULL; mDropShaderAmbientSC = NULL; mSplashShaderModelViewSC = NULL; mSplashShaderFadeStartEndSC = NULL; mSplashShaderCameraPosSC = NULL; mSplashShaderAmbientSC = NULL; mMaxVBDrops = 5000; } Precipitation::~Precipitation() { SAFE_DELETE_ARRAY(mTexCoords); SAFE_DELETE_ARRAY(mSplashCoords); } void Precipitation::inspectPostApply() { if (mFollowCam) { setGlobalBounds(); } else { mObjBox.minExtents = -Point3F(mBoxWidth/2, mBoxWidth/2, mBoxHeight/2); mObjBox.maxExtents = Point3F(mBoxWidth/2, mBoxWidth/2, mBoxHeight/2); } resetWorldBox(); setMaskBits(DataMask); } void Precipitation::setTransform(const MatrixF & mat) { Parent::setTransform(mat); setMaskBits(TransformMask); } //-------------------------------------------------------------------------- // Console stuff... //-------------------------------------------------------------------------- IRangeValidator ValidNumDropsRange(1, 100000); void Precipitation::initPersistFields() { addGroup("Precipitation"); addFieldV( "numDrops", TypeS32, Offset(mNumDrops, Precipitation), &ValidNumDropsRange, "@brief Maximum number of drops allowed to exist in the precipitation " "box at any one time.\n\n" "The actual number of drops in the effect depends on the current " "percentage, which can change over time using modifyStorm()." ); addField( "boxWidth", TypeF32, Offset(mBoxWidth, Precipitation), "Width and depth (horizontal dimensions) of the precipitation box." ); addField( "boxHeight", TypeF32, Offset(mBoxHeight, Precipitation), "Height (vertical dimension) of the precipitation box." ); endGroup("Precipitation"); addGroup("Rendering"); addField( "dropSize", TypeF32, Offset(mDropSize, Precipitation), "Size of each drop of precipitation. This will scale the texture." ); addField( "splashSize", TypeF32, Offset(mSplashSize, Precipitation), "Size of each splash animation when a drop collides with another surface." ); addField( "splashMS", TypeS32, Offset(mSplashMS, Precipitation), "Lifetime of splashes in milliseconds." ); addField( "animateSplashes", TypeBool, Offset(mAnimateSplashes, Precipitation), "Set to true to enable splash animations when drops collide with other surfaces." ); addField( "dropAnimateMS", TypeS32, Offset(mDropAnimateMS, Precipitation), "@brief Length (in milliseconds) to display each drop frame.\n\n" "If #dropAnimateMS <= 0, drops select a single random frame at creation " "that does not change throughout the drop's lifetime. If #dropAnimateMS " "> 0, each drop cycles through the the available frames in the drop " "texture at the given rate." ); addField( "fadeDist", TypeF32, Offset(mFadeDistance, Precipitation), "The distance at which drops begin to fade out." ); addField( "fadeDistEnd", TypeF32, Offset(mFadeDistanceEnd, Precipitation), "The distance at which drops are completely faded out." ); addField( "useTrueBillboards", TypeBool, Offset(mUseTrueBillboards, Precipitation), "Set to true to make drops true (non axis-aligned) billboards." ); addField( "useLighting", TypeBool, Offset(mUseLighting, Precipitation), "Set to true to enable shading of the drops and splashes by the sun color." ); addField( "glowIntensity", TypeColorF, Offset(mGlowIntensity, Precipitation), "Set to 0 to disable the glow or or use it to control the intensity of each channel." ); addField( "reflect", TypeBool, Offset(mReflect, Precipitation), "@brief This enables precipitation rendering during reflection passes.\n\n" "@note This is expensive." ); addField( "rotateWithCamVel", TypeBool, Offset(mRotateWithCamVel, Precipitation), "Set to true to include the camera velocity when calculating drop " "rotation speed." ); endGroup("Rendering"); addGroup("Collision"); addField( "doCollision", TypeBool, Offset(mDoCollision, Precipitation), "@brief Allow drops to collide with world objects.\n\n" "If #animateSplashes is true, drops that collide with another object " "will produce a simple splash animation.\n" "@note This can be expensive as each drop will perform a raycast when " "it is created to determine where it will hit." ); addField( "hitPlayers", TypeBool, Offset(mDropHitPlayers, Precipitation), "Allow drops to collide with Player objects; only valid if #doCollision is true." ); addField( "hitVehicles", TypeBool, Offset(mDropHitVehicles, Precipitation), "Allow drops to collide with Vehicle objects; only valid if #doCollision is true." ); endGroup("Collision"); addGroup("Movement"); addField( "followCam", TypeBool, Offset(mFollowCam, Precipitation), "@brief Controls whether the Precipitation system follows the camera " "or remains where it is first placed in the scene.\n\n" "Set to true to make it seem like it is raining everywhere in the " "level (ie. the Player will always be in the rain). Set to false " "to have a single area affected by rain (ie. the Player can move in " "and out of the rainy area)." ); addField( "useWind", TypeBool, Offset(mUseWind, Precipitation), "Controls whether drops are affected by wind.\n" "@see ForestWindEmitter" ); addField( "minSpeed", TypeF32, Offset(mMinSpeed, Precipitation), "@brief Minimum speed at which a drop will fall.\n\n" "On creation, the drop will be assigned a random speed between #minSpeed " "and #maxSpeed." ); addField( "maxSpeed", TypeF32, Offset(mMaxSpeed, Precipitation), "@brief Maximum speed at which a drop will fall.\n\n" "On creation, the drop will be assigned a random speed between #minSpeed " "and #maxSpeed." ); addField( "minMass", TypeF32, Offset(mMinMass, Precipitation), "@brief Minimum mass of a drop.\n\n" "Drop mass determines how strongly the drop is affected by wind and " "turbulence. On creation, the drop will be assigned a random speed " "between #minMass and #minMass." ); addField( "maxMass", TypeF32, Offset(mMaxMass, Precipitation), "@brief Maximum mass of a drop.\n\n" "Drop mass determines how strongly the drop is affected by wind and " "turbulence. On creation, the drop will be assigned a random speed " "between #minMass and #minMass." ); endGroup("Movement"); addGroup("Turbulence"); addField( "useTurbulence", TypeBool, Offset(mUseTurbulence, Precipitation), "Check to enable turbulence. This causes precipitation drops to spiral " "while falling." ); addField( "maxTurbulence", TypeF32, Offset(mMaxTurbulence, Precipitation), "Radius at which precipitation drops spiral when turbulence is enabled." ); addField( "turbulenceSpeed", TypeF32, Offset(mTurbulenceSpeed, Precipitation), "Speed at which precipitation drops spiral when turbulence is enabled." ); endGroup("Turbulence"); Parent::initPersistFields(); } //----------------------------------- // Console methods... DefineEngineMethod(Precipitation, setPercentage, void, (F32 percentage), (1.0f), "Sets the maximum number of drops in the effect, as a percentage of #numDrops.\n" "The change occurs instantly (use modifyStorm() to change the number of drops " "over a period of time.\n" "@param percentage New maximum number of drops value (as a percentage of " "#numDrops). Valid range is 0-1.\n" "@tsexample\n" "%percentage = 0.5; // The percentage, from 0 to 1, of the maximum drops to display\n" "%precipitation.setPercentage( %percentage );\n" "@endtsexample\n" "@see modifyStorm\n" ) { object->setPercentage(percentage); } DefineEngineMethod(Precipitation, modifyStorm, void, (F32 percentage, F32 seconds), (1.0f, 5.0f), "Smoothly change the maximum number of drops in the effect (from current " "value to #numDrops * @a percentage).\n" "This method can be used to simulate a storm building or fading in intensity " "as the number of drops in the Precipitation box changes.\n" "@param percentage New maximum number of drops value (as a percentage of " "#numDrops). Valid range is 0-1.\n" "@param seconds Length of time (in seconds) over which to increase the drops " "percentage value. Set to 0 to change instantly.\n" "@tsexample\n" "%percentage = 0.5; // The percentage, from 0 to 1, of the maximum drops to display\n" "%seconds = 5.0; // The length of time over which to make the change.\n" "%precipitation.modifyStorm( %percentage, %seconds );\n" "@endtsexample\n" ) { object->modifyStorm(percentage, S32(seconds * 1000.0f)); } DefineEngineMethod(Precipitation, setTurbulence, void, (F32 max, F32 speed, F32 seconds), (1.0f, 5.0f, 5.0f), "Smoothly change the turbulence parameters over a period of time.\n" "@param max New #maxTurbulence value. Set to 0 to disable turbulence.\n" "@param speed New #turbulenceSpeed value.\n" "@param seconds Length of time (in seconds) over which to interpolate the " "turbulence settings. Set to 0 to change instantly.\n" "@tsexample\n" "%turbulence = 0.5; // Set the new turbulence value. Set to 0 to disable turbulence.\n" "%speed = 5.0; // The new speed of the turbulance effect.\n" "%seconds = 5.0; // The length of time over which to make the change.\n" "%precipitation.setTurbulence( %turbulence, %speed, %seconds );\n" "@endtsexample\n" ) { object->setTurbulence( max, speed, S32(seconds * 1000.0f)); } //-------------------------------------------------------------------------- // Backend //-------------------------------------------------------------------------- bool Precipitation::onAdd() { if(!Parent::onAdd()) return false; if (mFollowCam) { setGlobalBounds(); } else { mObjBox.minExtents = -Point3F(mBoxWidth/2, mBoxWidth/2, mBoxHeight/2); mObjBox.maxExtents = Point3F(mBoxWidth/2, mBoxWidth/2, mBoxHeight/2); } resetWorldBox(); if (isClientObject()) { fillDropList(); initRenderObjects(); initMaterials(); } addToScene(); return true; } void Precipitation::onRemove() { removeFromScene(); Parent::onRemove(); SFX_DELETE( mAmbientSound ); if (isClientObject()) killDropList(); } bool Precipitation::onNewDataBlock( GameBaseData *dptr, bool reload ) { mDataBlock = dynamic_cast<PrecipitationData*>( dptr ); if ( !mDataBlock || !Parent::onNewDataBlock( dptr, reload ) ) return false; if (isClientObject()) { SFX_DELETE( mAmbientSound ); if ( mDataBlock->soundProfile ) { mAmbientSound = SFX->createSource( mDataBlock->soundProfile, &getTransform() ); if ( mAmbientSound ) mAmbientSound->play(); } initRenderObjects(); initMaterials(); } scriptOnNewDataBlock(); return true; } void Precipitation::initMaterials() { AssertFatal(isClientObject(), "Precipitation is setting materials on the server - BAD!"); if(!mDataBlock) return; PrecipitationData *pd = (PrecipitationData*)mDataBlock; mDropHandle = NULL; mSplashHandle = NULL; mDropShader = NULL; mSplashShader = NULL; if( dStrlen(pd->mDropName) > 0 && !mDropHandle.set(pd->mDropName, &GFXStaticTextureSRGBProfile, avar("%s() - mDropHandle (line %d)", __FUNCTION__, __LINE__)) ) Con::warnf("Precipitation::initMaterials - failed to locate texture '%s'!", pd->mDropName); if ( dStrlen(pd->mDropShaderName) > 0 ) { ShaderData *shaderData; if ( Sim::findObject( pd->mDropShaderName, shaderData ) ) mDropShader = shaderData->getShader(); if( !mDropShader ) Con::warnf( "Precipitation::initMaterials - could not find shader '%s'!", pd->mDropShaderName ); else { mDropShaderConsts = mDropShader->allocConstBuffer(); mDropShaderModelViewSC = mDropShader->getShaderConstHandle("$modelView"); mDropShaderFadeStartEndSC = mDropShader->getShaderConstHandle("$fadeStartEnd"); mDropShaderCameraPosSC = mDropShader->getShaderConstHandle("$cameraPos"); mDropShaderAmbientSC = mDropShader->getShaderConstHandle("$ambient"); } } if( dStrlen(pd->mSplashName) > 0 && !mSplashHandle.set(pd->mSplashName, &GFXStaticTextureSRGBProfile, avar("%s() - mSplashHandle (line %d)", __FUNCTION__, __LINE__)) ) Con::warnf("Precipitation::initMaterials - failed to locate texture '%s'!", pd->mSplashName); if ( dStrlen(pd->mSplashShaderName) > 0 ) { ShaderData *shaderData; if ( Sim::findObject( pd->mSplashShaderName, shaderData ) ) mSplashShader = shaderData->getShader(); if( !mSplashShader ) Con::warnf( "Precipitation::initMaterials - could not find shader '%s'!", pd->mSplashShaderName ); else { mSplashShaderConsts = mSplashShader->allocConstBuffer(); mSplashShaderModelViewSC = mSplashShader->getShaderConstHandle("$modelView"); mSplashShaderFadeStartEndSC = mSplashShader->getShaderConstHandle("$fadeStartEnd"); mSplashShaderCameraPosSC = mSplashShader->getShaderConstHandle("$cameraPos"); mSplashShaderAmbientSC = mSplashShader->getShaderConstHandle("$ambient"); } } } U32 Precipitation::packUpdate(NetConnection* con, U32 mask, BitStream* stream) { Parent::packUpdate(con, mask, stream); if (stream->writeFlag( !mFollowCam && mask & TransformMask)) stream->writeAffineTransform(mObjToWorld); if (stream->writeFlag(mask & DataMask)) { stream->write(mDropSize); stream->write(mSplashSize); stream->write(mSplashMS); stream->write(mDropAnimateMS); stream->write(mNumDrops); stream->write(mMinSpeed); stream->write(mMaxSpeed); stream->write(mBoxWidth); stream->write(mBoxHeight); stream->write(mMinMass); stream->write(mMaxMass); stream->write(mMaxTurbulence); stream->write(mTurbulenceSpeed); stream->write(mFadeDistance); stream->write(mFadeDistanceEnd); stream->write(mGlowIntensity.red); stream->write(mGlowIntensity.green); stream->write(mGlowIntensity.blue); stream->write(mGlowIntensity.alpha); stream->writeFlag(mReflect); stream->writeFlag(mRotateWithCamVel); stream->writeFlag(mDoCollision); stream->writeFlag(mDropHitPlayers); stream->writeFlag(mDropHitVehicles); stream->writeFlag(mUseTrueBillboards); stream->writeFlag(mUseTurbulence); stream->writeFlag(mUseLighting); stream->writeFlag(mUseWind); stream->writeFlag(mFollowCam); stream->writeFlag(mAnimateSplashes); } if (stream->writeFlag(!(mask & DataMask) && (mask & TurbulenceMask))) { stream->write(mTurbulenceData.endMax); stream->write(mTurbulenceData.endSpeed); stream->write(mTurbulenceData.totalTime); } if (stream->writeFlag(mask & PercentageMask)) { stream->write(mPercentage); } if (stream->writeFlag(!(mask & ~(DataMask | PercentageMask | StormMask)) && (mask & StormMask))) { stream->write(mStormData.endPct); stream->write(mStormData.totalTime); } return 0; } void Precipitation::unpackUpdate(NetConnection* con, BitStream* stream) { Parent::unpackUpdate(con, stream); if (stream->readFlag()) { MatrixF mat; stream->readAffineTransform(&mat); Parent::setTransform(mat); } U32 oldDrops = U32(mNumDrops * mPercentage); if (stream->readFlag()) { stream->read(&mDropSize); stream->read(&mSplashSize); stream->read(&mSplashMS); stream->read(&mDropAnimateMS); stream->read(&mNumDrops); stream->read(&mMinSpeed); stream->read(&mMaxSpeed); stream->read(&mBoxWidth); stream->read(&mBoxHeight); stream->read(&mMinMass); stream->read(&mMaxMass); stream->read(&mMaxTurbulence); stream->read(&mTurbulenceSpeed); stream->read(&mFadeDistance); stream->read(&mFadeDistanceEnd); stream->read(&mGlowIntensity.red); stream->read(&mGlowIntensity.green); stream->read(&mGlowIntensity.blue); stream->read(&mGlowIntensity.alpha); mReflect = stream->readFlag(); mRotateWithCamVel = stream->readFlag(); mDoCollision = stream->readFlag(); mDropHitPlayers = stream->readFlag(); mDropHitVehicles = stream->readFlag(); mUseTrueBillboards = stream->readFlag(); mUseTurbulence = stream->readFlag(); mUseLighting = stream->readFlag(); mUseWind = stream->readFlag(); mFollowCam = stream->readFlag(); mAnimateSplashes = stream->readFlag(); mDropHitMask = dropHitMask | ( mDropHitPlayers ? PlayerObjectType : 0 ) | ( mDropHitVehicles ? VehicleObjectType : 0 ); mTurbulenceData.valid = false; } if (stream->readFlag()) { F32 max, speed; U32 ms; stream->read(&max); stream->read(&speed); stream->read(&ms); setTurbulence( max, speed, ms ); } if (stream->readFlag()) { F32 pct; stream->read(&pct); setPercentage(pct); } if (stream->readFlag()) { F32 pct; U32 time; stream->read(&pct); stream->read(&time); modifyStorm(pct, time); } AssertFatal(isClientObject(), "Precipitation::unpackUpdate() should only be called on the client!"); U32 newDrops = U32(mNumDrops * mPercentage); if (oldDrops != newDrops) { fillDropList(); initRenderObjects(); } if (mFollowCam) { setGlobalBounds(); } else { mObjBox.minExtents = -Point3F(mBoxWidth/2, mBoxWidth/2, mBoxHeight/2); mObjBox.maxExtents = Point3F(mBoxWidth/2, mBoxWidth/2, mBoxHeight/2); } resetWorldBox(); } //-------------------------------------------------------------------------- // Support functions //-------------------------------------------------------------------------- VectorF Precipitation::getWindVelocity() { // The WindManager happens to set global-wind velocity here, it is not just for particles. return mUseWind ? ParticleEmitter::mWindVelocity : Point3F::Zero; } void Precipitation::fillDropList() { AssertFatal(isClientObject(), "Precipitation is doing stuff on the server - BAD!"); F32 density = Con::getFloatVariable("$pref::precipitationDensity", 1.0f); U32 newDropCount = (U32)(mNumDrops * mPercentage * density); U32 dropCount = 0; if (newDropCount == 0) killDropList(); if (mDropHead) { Raindrop* curr = mDropHead; while (curr) { dropCount++; curr = curr->next; if (dropCount == newDropCount && curr) { //delete the remaining drops Raindrop* next = curr->next; curr->next = NULL; while (next) { Raindrop* last = next; next = next->next; last->next = NULL; destroySplash(last); delete last; } break; } } } if (dropCount < newDropCount) { //move to the end Raindrop* curr = mDropHead; if (curr) { while (curr->next) curr = curr->next; } else { mDropHead = curr = new Raindrop; spawnNewDrop(curr); dropCount++; } //and add onto it while (dropCount < newDropCount) { curr->next = new Raindrop; curr = curr->next; spawnNewDrop(curr); dropCount++; } } } void Precipitation::initRenderObjects() { AssertFatal(isClientObject(), "Precipitation is doing stuff on the server - BAD!"); SAFE_DELETE_ARRAY(mTexCoords); SAFE_DELETE_ARRAY(mSplashCoords); if (!mDataBlock) return; mTexCoords = new Point2F[4*mDataBlock->mDropsPerSide*mDataBlock->mDropsPerSide]; // Setup the texcoords for the drop texture. // The order of the coords when animating is... // // +---+---+---+ // | 1 | 2 | 3 | // |---|---|---+ // | 4 | 5 | 6 | // +---+---+---+ // | 7 | etc... // +---+ // U32 count = 0; for (U32 v = 0; v < mDataBlock->mDropsPerSide; v++) { F32 y1 = (F32) v / mDataBlock->mDropsPerSide; F32 y2 = (F32)(v+1) / mDataBlock->mDropsPerSide; for (U32 u = 0; u < mDataBlock->mDropsPerSide; u++) { F32 x1 = (F32) u / mDataBlock->mDropsPerSide; F32 x2 = (F32)(u+1) / mDataBlock->mDropsPerSide; mTexCoords[4*count+0].x = x1; mTexCoords[4*count+0].y = y1; mTexCoords[4*count+1].x = x2; mTexCoords[4*count+1].y = y1; mTexCoords[4*count+2].x = x2; mTexCoords[4*count+2].y = y2; mTexCoords[4*count+3].x = x1; mTexCoords[4*count+3].y = y2; count++; } } count = 0; mSplashCoords = new Point2F[4*mDataBlock->mSplashesPerSide*mDataBlock->mSplashesPerSide]; for (U32 v = 0; v < mDataBlock->mSplashesPerSide; v++) { F32 y1 = (F32) v / mDataBlock->mSplashesPerSide; F32 y2 = (F32)(v+1) / mDataBlock->mSplashesPerSide; for (U32 u = 0; u < mDataBlock->mSplashesPerSide; u++) { F32 x1 = (F32) u / mDataBlock->mSplashesPerSide; F32 x2 = (F32)(u+1) / mDataBlock->mSplashesPerSide; mSplashCoords[4*count+0].x = x1; mSplashCoords[4*count+0].y = y1; mSplashCoords[4*count+1].x = x2; mSplashCoords[4*count+1].y = y1; mSplashCoords[4*count+2].x = x2; mSplashCoords[4*count+2].y = y2; mSplashCoords[4*count+3].x = x1; mSplashCoords[4*count+3].y = y2; count++; } } // Cap the number of precipitation drops so that we don't blow out the max verts mMaxVBDrops = getMin( (U32)mNumDrops, ( GFX->getMaxDynamicVerts() / 4 ) - 1 ); // If we have no drops then skip allocating anything! if ( mMaxVBDrops == 0 ) return; // Create a volitile vertex buffer which // we'll lock and fill every frame. mRainVB.set(GFX, mMaxVBDrops * 4, GFXBufferTypeDynamic); // Init the index buffer for rendering the // entire or a partially filled vb. mRainIB.set(GFX, mMaxVBDrops * 6, 0, GFXBufferTypeStatic); U16 *idxBuff; mRainIB.lock(&idxBuff, NULL, NULL, NULL); for( U32 i=0; i < mMaxVBDrops; i++ ) { // // The vertex pattern in the VB for each // particle is as follows... // // 0----1 // |\ | // | \ | // | \ | // | \| // 3----2 // // We setup the index order below to ensure // sequential, cache friendly, access. // U32 offset = i * 4; idxBuff[i*6+0] = 0 + offset; idxBuff[i*6+1] = 1 + offset; idxBuff[i*6+2] = 2 + offset; idxBuff[i*6+3] = 2 + offset; idxBuff[i*6+4] = 3 + offset; idxBuff[i*6+5] = 0 + offset; } mRainIB.unlock(); } void Precipitation::killDropList() { AssertFatal(isClientObject(), "Precipitation is doing stuff on the server - BAD!"); Raindrop* curr = mDropHead; while (curr) { Raindrop* next = curr->next; delete curr; curr = next; } mDropHead = NULL; mSplashHead = NULL; } void Precipitation::spawnDrop(Raindrop *drop) { PROFILE_START(PrecipSpawnDrop); AssertFatal(isClientObject(), "Precipitation is doing stuff on the server - BAD!"); drop->velocity = Platform::getRandom() * (mMaxSpeed - mMinSpeed) + mMinSpeed; drop->position.x = Platform::getRandom() * mBoxWidth; drop->position.y = Platform::getRandom() * mBoxWidth; // The start time should be randomized so that // all the drops are not animating at the same time. drop->animStartTime = (SimTime)(Platform::getVirtualMilliseconds() * Platform::getRandom()); if (mDropAnimateMS <= 0 && mDataBlock) drop->texCoordIndex = (U32)(Platform::getRandom() * ((F32)mDataBlock->mDropsPerSide*mDataBlock->mDropsPerSide - 0.5)); drop->valid = true; drop->time = Platform::getRandom() * M_2PI; drop->mass = Platform::getRandom() * (mMaxMass - mMinMass) + mMinMass; PROFILE_END(); } void Precipitation::spawnNewDrop(Raindrop *drop) { AssertFatal(isClientObject(), "Precipitation is doing stuff on the server - BAD!"); spawnDrop(drop); drop->position.z = Platform::getRandom() * mBoxHeight - (mBoxHeight / 2); } void Precipitation::wrapDrop(Raindrop *drop, const Box3F &box, const U32 currTime, const VectorF &windVel) { //could probably be slightly optimized to get rid of the while loops if (drop->position.z < box.minExtents.z) { spawnDrop(drop); drop->position.x += box.minExtents.x; drop->position.y += box.minExtents.y; while (drop->position.z < box.minExtents.z) drop->position.z += mBoxHeight; findDropCutoff(drop, box, windVel); } else if (drop->position.z > box.maxExtents.z) { while (drop->position.z > box.maxExtents.z) drop->position.z -= mBoxHeight; findDropCutoff(drop, box, windVel); } else if (drop->position.x < box.minExtents.x) { while (drop->position.x < box.minExtents.x) drop->position.x += mBoxWidth; findDropCutoff(drop, box, windVel); } else if (drop->position.x > box.maxExtents.x) { while (drop->position.x > box.maxExtents.x) drop->position.x -= mBoxWidth; findDropCutoff(drop, box, windVel); } else if (drop->position.y < box.minExtents.y) { while (drop->position.y < box.minExtents.y) drop->position.y += mBoxWidth; findDropCutoff(drop, box, windVel); } else if (drop->position.y > box.maxExtents.y) { while (drop->position.y > box.maxExtents.y) drop->position.y -= mBoxWidth; findDropCutoff(drop, box, windVel); } } void Precipitation::findDropCutoff(Raindrop *drop, const Box3F &box, const VectorF &windVel) { PROFILE_START(PrecipFindDropCutoff); AssertFatal(isClientObject(), "Precipitation is doing stuff on the server - BAD!"); if (mDoCollision) { VectorF velocity = windVel / drop->mass - VectorF(0, 0, drop->velocity); velocity.normalize(); Point3F end = drop->position + 100 * velocity; Point3F start = drop->position - (mFollowCam ? 500.0f : 0.0f) * velocity; if (!mFollowCam) { mObjToWorld.mulP(start); mObjToWorld.mulP(end); } // Look for a collision... make sure we don't // collide with backfaces. RayInfo rInfo; if (getContainer()->castRay(start, end, mDropHitMask, &rInfo)) { // TODO: Add check to filter out hits on backfaces. if (!mFollowCam) mWorldToObj.mulP(rInfo.point); drop->hitPos = rInfo.point; drop->hitType = rInfo.object->getTypeMask(); } else drop->hitPos = Point3F(0,0,-1000); drop->valid = drop->position.z > drop->hitPos.z; } else { drop->hitPos = Point3F(0,0,-1000); drop->valid = true; } PROFILE_END(); } void Precipitation::createSplash(Raindrop *drop) { if (!mDataBlock) return; PROFILE_START(PrecipCreateSplash); if (drop != mSplashHead && !(drop->nextSplashDrop || drop->prevSplashDrop)) { if (!mSplashHead) { mSplashHead = drop; drop->prevSplashDrop = NULL; drop->nextSplashDrop = NULL; } else { mSplashHead->prevSplashDrop = drop; drop->nextSplashDrop = mSplashHead; drop->prevSplashDrop = NULL; mSplashHead = drop; } } drop->animStartTime = Platform::getVirtualMilliseconds(); if (!mAnimateSplashes) drop->texCoordIndex = (U32)(Platform::getRandom() * ((F32)mDataBlock->mSplashesPerSide*mDataBlock->mSplashesPerSide - 0.5)); PROFILE_END(); } void Precipitation::destroySplash(Raindrop *drop) { PROFILE_START(PrecipDestroySplash); if (drop == mSplashHead) { mSplashHead = mSplashHead->nextSplashDrop; } if (drop->nextSplashDrop) drop->nextSplashDrop->prevSplashDrop = drop->prevSplashDrop; if (drop->prevSplashDrop) drop->prevSplashDrop->nextSplashDrop = drop->nextSplashDrop; drop->nextSplashDrop = NULL; drop->prevSplashDrop = NULL; PROFILE_END(); } //-------------------------------------------------------------------------- // Processing //-------------------------------------------------------------------------- void Precipitation::setPercentage(F32 pct) { mPercentage = mClampF(pct, 0, 1); mStormData.valid = false; if (isServerObject()) { setMaskBits(PercentageMask); } } void Precipitation::modifyStorm(F32 pct, U32 ms) { if ( ms == 0 ) { setPercentage( pct ); return; } pct = mClampF(pct, 0, 1); mStormData.endPct = pct; mStormData.totalTime = ms; if (isServerObject()) { setMaskBits(StormMask); return; } mStormData.startTime = Platform::getVirtualMilliseconds(); mStormData.startPct = mPercentage; mStormData.valid = true; } void Precipitation::setTurbulence(F32 max, F32 speed, U32 ms) { if ( ms == 0 && !isServerObject() ) { mUseTurbulence = max > 0; mMaxTurbulence = max; mTurbulenceSpeed = speed; return; } mTurbulenceData.endMax = max; mTurbulenceData.endSpeed = speed; mTurbulenceData.totalTime = ms; if (isServerObject()) { setMaskBits(TurbulenceMask); return; } mTurbulenceData.startTime = Platform::getVirtualMilliseconds(); mTurbulenceData.startMax = mMaxTurbulence; mTurbulenceData.startSpeed = mTurbulenceSpeed; mTurbulenceData.valid = true; } void Precipitation::interpolateTick(F32 delta) { AssertFatal(isClientObject(), "Precipitation is doing stuff on the server - BAD!"); // If we're not being seen then the simulation // is paused and we don't need any interpolation. if (mLastRenderFrame != ShapeBase::sLastRenderFrame) return; PROFILE_START(PrecipInterpolate); const F32 dt = 1-delta; const VectorF windVel = dt * getWindVelocity(); const F32 turbSpeed = dt * mTurbulenceSpeed; Raindrop* curr = mDropHead; VectorF turbulence; F32 renderTime; while (curr) { if (!curr->valid || !curr->toRender) { curr = curr->next; continue; } if (mUseTurbulence) { renderTime = curr->time + turbSpeed; turbulence.x = windVel.x + ( mSin(renderTime) * mMaxTurbulence ); turbulence.y = windVel.y + ( mCos(renderTime) * mMaxTurbulence ); turbulence.z = windVel.z; curr->renderPosition = curr->position + turbulence / curr->mass; } else curr->renderPosition = curr->position + windVel / curr->mass; curr->renderPosition.z -= dt * curr->velocity; curr = curr->next; } PROFILE_END(); } void Precipitation::processTick(const Move *) { //nothing to do on the server if (isServerObject() || mDataBlock == NULL || isHidden()) return; const U32 currTime = Platform::getVirtualMilliseconds(); // Update the storm if necessary if (mStormData.valid) { F32 t = (currTime - mStormData.startTime) / (F32)mStormData.totalTime; if (t >= 1) { mPercentage = mStormData.endPct; mStormData.valid = false; } else mPercentage = mStormData.startPct * (1-t) + mStormData.endPct * t; fillDropList(); } // Do we need to update the turbulence? if ( mTurbulenceData.valid ) { F32 t = (currTime - mTurbulenceData.startTime) / (F32)mTurbulenceData.totalTime; if (t >= 1) { mMaxTurbulence = mTurbulenceData.endMax; mTurbulenceSpeed = mTurbulenceData.endSpeed; mTurbulenceData.valid = false; } else { mMaxTurbulence = mTurbulenceData.startMax * (1-t) + mTurbulenceData.endMax * t; mTurbulenceSpeed = mTurbulenceData.startSpeed * (1-t) + mTurbulenceData.endSpeed * t; } mUseTurbulence = mMaxTurbulence > 0; } // If we're not being seen then pause the // simulation. Precip is generally noisy // enough that no one should notice. if (mLastRenderFrame != ShapeBase::sLastRenderFrame) return; //we need to update positions and do some collision here GameConnection* conn = GameConnection::getConnectionToServer(); if (!conn) return; //need connection to server ShapeBase* camObj = dynamic_cast<ShapeBase*>(conn->getCameraObject()); if (!camObj) return; PROFILE_START(PrecipProcess); MatrixF camMat; camObj->getEyeTransform(&camMat); const F32 camFov = camObj->getCameraFov(); Point3F camPos, camDir; Box3F box; if (mFollowCam) { camMat.getColumn(3, &camPos); box = Box3F(camPos.x - mBoxWidth / 2, camPos.y - mBoxWidth / 2, camPos.z - mBoxHeight / 2, camPos.x + mBoxWidth / 2, camPos.y + mBoxWidth / 2, camPos.z + mBoxHeight / 2); camMat.getColumn(1, &camDir); camDir.normalize(); } else { box = mObjBox; camMat.getColumn(3, &camPos); mWorldToObj.mulP(camPos); camMat.getColumn(1, &camDir); camDir.normalize(); mWorldToObj.mulV(camDir); } const VectorF windVel = getWindVelocity(); const F32 fovDot = camFov / 180; Raindrop* curr = mDropHead; //offset the renderbox in the direction of the camera direction //in order to have more of the drops actually rendered if (mFollowCam) { box.minExtents.x += camDir.x * mBoxWidth / 4; box.maxExtents.x += camDir.x * mBoxWidth / 4; box.minExtents.y += camDir.y * mBoxWidth / 4; box.maxExtents.y += camDir.y * mBoxWidth / 4; box.minExtents.z += camDir.z * mBoxHeight / 4; box.maxExtents.z += camDir.z * mBoxHeight / 4; } VectorF lookVec; F32 pct; const S32 dropCount = mDataBlock->mDropsPerSide*mDataBlock->mDropsPerSide; while (curr) { // Update the position. This happens even if this // is a splash so that the drop respawns when it wraps // around to the top again. if (mUseTurbulence) curr->time += mTurbulenceSpeed; curr->position += windVel / curr->mass; curr->position.z -= curr->velocity; // Wrap the drop if it reaches an edge of the box. wrapDrop(curr, box, currTime, windVel); // Did the drop pass below the hit position? if (curr->valid && curr->position.z < curr->hitPos.z) { // If this drop was to hit a player or vehicle double // check to see if the object has moved out of the way. // This keeps us from leaving phantom trails of splashes // behind a moving player/vehicle. if (curr->hitType & (PlayerObjectType | VehicleObjectType)) { findDropCutoff(curr, box, windVel); if (curr->position.z > curr->hitPos.z) goto NO_SPLASH; // Ugly, yet simple. } // The drop is dead. curr->valid = false; // Convert the drop into a splash or let it // wrap around and respawn in wrapDrop(). if (mSplashMS > 0) createSplash(curr); // So ugly... yet simple. NO_SPLASH:; } // We do not do cull individual drops when we're not // following as it is usually a tight box and all of // the particles are in view. if (!mFollowCam) curr->toRender = true; else { lookVec = curr->position - camPos; curr->toRender = mDot(lookVec, camDir) > fovDot; } // Do we need to animate the drop? if (curr->valid && mDropAnimateMS > 0 && curr->toRender) { pct = (F32)(currTime - curr->animStartTime) / mDropAnimateMS; pct = mFmod(pct, 1); curr->texCoordIndex = (U32)(dropCount * pct); } curr = curr->next; } //update splashes curr = mSplashHead; Raindrop *next; const S32 splashCount = mDataBlock->mSplashesPerSide * mDataBlock->mSplashesPerSide; while (curr) { pct = (F32)(currTime - curr->animStartTime) / mSplashMS; if (pct >= 1.0f) { next = curr->nextSplashDrop; destroySplash(curr); curr = next; continue; } if (mAnimateSplashes) curr->texCoordIndex = (U32)(splashCount * pct); curr = curr->nextSplashDrop; } PROFILE_END_NAMED(PrecipProcess); } //-------------------------------------------------------------------------- // Rendering //-------------------------------------------------------------------------- void Precipitation::prepRenderImage(SceneRenderState* state) { PROFILE_SCOPE(Precipitation_prepRenderImage); // We we have no drops then skip rendering // and don't bother with the sound. if (mMaxVBDrops == 0) return; // We do nothing if we're not supposed to be reflected. if ( state->isReflectPass() && !mReflect ) return; // This should be sufficient for most objects that don't manage zones, and // don't need to return a specialized RenderImage... ObjectRenderInst *ri = state->getRenderPass()->allocInst<ObjectRenderInst>(); ri->renderDelegate.bind(this, &Precipitation::renderObject); ri->type = RenderPassManager::RIT_Foliage; state->getRenderPass()->addInst( ri ); } void Precipitation::renderObject(ObjectRenderInst *ri, SceneRenderState *state, BaseMatInstance* overrideMat) { if (overrideMat) return; GameConnection* conn = GameConnection::getConnectionToServer(); if (!conn) return; //need connection to server ShapeBase* camObj = dynamic_cast<ShapeBase*>(conn->getCameraObject()); if (!camObj) return; // need camera object PROFILE_START(PrecipRender); GFX->pushWorldMatrix(); MatrixF world = GFX->getWorldMatrix(); MatrixF proj = GFX->getProjectionMatrix(); if (!mFollowCam) { world.mul( getRenderTransform() ); world.scale( getScale() ); GFX->setWorldMatrix( world ); } proj.mul(world); //GFX2 doesn't require transpose? //proj.transpose(); Point3F camPos = state->getCameraPosition(); VectorF camVel = camObj->getVelocity(); if (!mFollowCam) { getRenderWorldTransform().mulP(camPos); getRenderWorldTransform().mulV(camVel); } const VectorF windVel = getWindVelocity(); const bool useBillboards = mUseTrueBillboards; const F32 dropSize = mDropSize; Point3F pos; VectorF orthoDir, velocity, right, up, rightUp(0.0f, 0.0f, 0.0f), leftUp(0.0f, 0.0f, 0.0f); F32 distance = 0; GFXVertexPCT* vertPtr = NULL; const Point2F *tc; // Do this here and we won't have to in the loop! if (useBillboards) { MatrixF camMat = state->getCameraTransform(); camMat.inverse(); camMat.getRow(0,&right); camMat.getRow(2,&up); if (!mFollowCam) { mWorldToObj.mulV(right); mWorldToObj.mulV(up); } right.normalize(); up.normalize(); right *= mDropSize; up *= mDropSize; rightUp = right + up; leftUp = -right + up; } // We pass the sunlight as a constant to the // shader. Once the lighting and shadow systems // are added into TSE we can expand this to include // the N nearest lights to the camera + the ambient. LinearColorF ambient( 1, 1, 1 ); if ( mUseLighting ) { const LightInfo *sunlight = LIGHTMGR->getSpecialLight(LightManager::slSunLightType); ambient = sunlight->getColor(); } if ( mGlowIntensity.red > 0 || mGlowIntensity.green > 0 || mGlowIntensity.blue > 0 ) { ambient *= mGlowIntensity; } // Setup render state if (mDefaultSB.isNull()) { GFXStateBlockDesc desc; desc.zWriteEnable = false; desc.setAlphaTest(true, GFXCmpGreaterEqual, 1); desc.setBlend(true, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha); mDefaultSB = GFX->createStateBlock(desc); desc.samplersDefined = true; desc.samplers[0].textureColorOp = GFXTOPModulate; desc.samplers[0].colorArg1 = GFXTATexture; desc.samplers[0].colorArg2 = GFXTADiffuse; desc.samplers[0].alphaOp = GFXTOPSelectARG1; desc.samplers[0].alphaArg1 = GFXTATexture; desc.samplers[1].textureColorOp = GFXTOPDisable; desc.samplers[1].alphaOp = GFXTOPDisable; mDistantSB = GFX->createStateBlock(desc); } GFX->setStateBlock(mDefaultSB); // Everything is rendered from these buffers. GFX->setPrimitiveBuffer(mRainIB); GFX->setVertexBuffer(mRainVB); // Set the constants used by the shaders. if (mDropShader) { Point2F fadeStartEnd( mFadeDistance, mFadeDistanceEnd ); mDropShaderConsts->setSafe(mDropShaderModelViewSC, proj); mDropShaderConsts->setSafe(mDropShaderFadeStartEndSC, fadeStartEnd); mDropShaderConsts->setSafe(mDropShaderCameraPosSC, camPos); mDropShaderConsts->setSafe(mDropShaderAmbientSC, Point3F(ambient.red, ambient.green, ambient.blue)); } if (mSplashShader) { Point2F fadeStartEnd( mFadeDistance, mFadeDistanceEnd ); mSplashShaderConsts->setSafe(mSplashShaderModelViewSC, proj); mSplashShaderConsts->setSafe(mSplashShaderFadeStartEndSC, fadeStartEnd); mSplashShaderConsts->setSafe(mSplashShaderCameraPosSC, camPos); mSplashShaderConsts->setSafe(mSplashShaderAmbientSC, Point3F(ambient.red, ambient.green, ambient.blue)); } // Time to render the drops... const Raindrop *curr = mDropHead; U32 vertCount = 0; GFX->setTexture(0, mDropHandle); // Use the shader or setup the pipeline // for fixed function rendering. if (mDropShader) { GFX->setShader( mDropShader ); GFX->setShaderConstBuffer( mDropShaderConsts ); } else { GFX->setupGenericShaders(GFXDevice::GSTexture); // We don't support distance fade or lighting without shaders. GFX->setStateBlock(mDistantSB); } while (curr) { // Skip ones that are not drops (hit something and // may have been converted into a splash) or they // are behind the camera. if (!curr->valid || !curr->toRender) { curr = curr->next; continue; } pos = curr->renderPosition; // two forms of billboards - true billboards (which we set // above outside this loop) or axis-aligned with velocity // (this codeblock) the axis-aligned billboards are aligned // with the velocity of the raindrop, and tilted slightly // towards the camera if (!useBillboards) { orthoDir = camPos - pos; distance = orthoDir.len(); // Inline the normalize so we don't // calculate the ortho len twice. if (distance > 0.0) orthoDir *= 1.0f / distance; else orthoDir.set( 0, 0, 1 ); velocity = windVel / curr->mass; // We do not optimize this for the "still" case // because its not a typical scenario. if (mRotateWithCamVel) velocity -= camVel / (distance > 2.0f ? distance : 2.0f) * 0.3f; velocity.z -= curr->velocity; velocity.normalize(); right = mCross(-velocity, orthoDir); right.normalize(); up = mCross(orthoDir, right) * 0.5 - velocity * 0.5; up.normalize(); right *= dropSize; up *= dropSize; rightUp = right + up; leftUp = -right + up; } // Do we need to relock the buffer? if ( !vertPtr ) vertPtr = mRainVB.lock(); if(!vertPtr) return; // Set the proper texture coords... (it's fun!) tc = &mTexCoords[4*curr->texCoordIndex]; vertPtr->point = pos + leftUp; vertPtr->texCoord = *tc; tc++; vertPtr++; vertPtr->point = pos + rightUp; vertPtr->texCoord = *tc; tc++; vertPtr++; vertPtr->point = pos - leftUp; vertPtr->texCoord = *tc; tc++; vertPtr++; vertPtr->point = pos - rightUp; vertPtr->texCoord = *tc; tc++; vertPtr++; // Do we need to render to clear the buffer? vertCount += 4; if ( (vertCount + 4) >= mRainVB->mNumVerts ) { mRainVB.unlock(); GFX->drawIndexedPrimitive(GFXTriangleList, 0, 0, vertCount, 0, vertCount / 2); vertPtr = NULL; vertCount = 0; } curr = curr->next; } // Do we have stuff left to render? if ( vertCount > 0 ) { mRainVB.unlock(); GFX->drawIndexedPrimitive(GFXTriangleList, 0, 0, vertCount, 0, vertCount / 2); vertCount = 0; vertPtr = NULL; } // Setup the billboard for the splashes. MatrixF camMat = state->getCameraTransform(); camMat.inverse(); camMat.getRow(0, &right); camMat.getRow(2, &up); if (!mFollowCam) { mWorldToObj.mulV(right); mWorldToObj.mulV(up); } right.normalize(); up.normalize(); right *= mSplashSize; up *= mSplashSize; rightUp = right + up; leftUp = -right + up; // Render the visible splashes. curr = mSplashHead; GFX->setTexture(0, mSplashHandle); if (mSplashShader) { GFX->setShader( mSplashShader ); GFX->setShaderConstBuffer(mSplashShaderConsts); } else GFX->setupGenericShaders(GFXDevice::GSTexture); while (curr) { if (!curr->toRender) { curr = curr->nextSplashDrop; continue; } pos = curr->hitPos; tc = &mSplashCoords[4*curr->texCoordIndex]; // Do we need to relock the buffer? if ( !vertPtr ) vertPtr = mRainVB.lock(); if(!vertPtr) return; vertPtr->point = pos + leftUp; vertPtr->texCoord = *tc; tc++; vertPtr++; vertPtr->point = pos + rightUp; vertPtr->texCoord = *tc; tc++; vertPtr++; vertPtr->point = pos - leftUp; vertPtr->texCoord = *tc; tc++; vertPtr++; vertPtr->point = pos - rightUp; vertPtr->texCoord = *tc; tc++; vertPtr++; // Do we need to flush the buffer by rendering? vertCount += 4; if ( (vertCount + 4) >= mRainVB->mNumVerts ) { mRainVB.unlock(); GFX->drawIndexedPrimitive(GFXTriangleList, 0, 0, vertCount, 0, vertCount / 2); vertPtr = NULL; vertCount = 0; } curr = curr->nextSplashDrop; } // Do we have stuff left to render? if ( vertCount > 0 ) { mRainVB.unlock(); GFX->drawIndexedPrimitive(GFXTriangleList, 0, 0, vertCount, 0, vertCount / 2); } mLastRenderFrame = ShapeBase::sLastRenderFrame; GFX->popWorldMatrix(); PROFILE_END(); }
30.448498
170
0.624533
[ "render", "object" ]
4f779643f095567980327b128203c1ae32d3a293
28,186
cpp
C++
src/soferox.cpp
apollygon/Soferox-Core
796870ec26ba5ed80038af4e55983b3d39d93ed4
[ "MIT" ]
4
2017-10-03T11:17:50.000Z
2019-05-04T03:22:08.000Z
src/soferox.cpp
apollygon/Soferox-Core
796870ec26ba5ed80038af4e55983b3d39d93ed4
[ "MIT" ]
null
null
null
src/soferox.cpp
apollygon/Soferox-Core
796870ec26ba5ed80038af4e55983b3d39d93ed4
[ "MIT" ]
null
null
null
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin Core developers // Copyright (c) 2014-2015 The Soferox developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "soferox.h" #include <boost/assign/list_of.hpp> #include "arith_uint256.h" #include "chain.h" #include "chainparams.h" #include "consensus/merkle.h" #include "consensus/params.h" #include "utilstrencodings.h" #include "crypto/sha256.h" #include "bignum.h" #include "chainparamsseeds.h" #ifdef _MSC_VER # include <intrin.h> #endif extern "C" { #if !defined(UCFG_LIBEXT) && (defined(_M_IX86) || defined(_M_X64)) && defined(_MSC_VER) static __inline void Cpuid(int a[4], int level) { # ifdef _MSC_VER __cpuid(a, level); # else __cpuid(level, a[0], a[1], a[2], a[3]); # endif } char g_bHasSse2; static int InitBignumFuns() { int a[4]; ::Cpuid(a, 1); g_bHasSse2 = a[3] & 0x02000000; return 1; } static int s_initBignumFuns = InitBignumFuns(); #endif // defined(_M_IX86) || defined(_M_X64) } // "C" using namespace std; static const int64_t nGenesisBlockRewardCoin = 1 * COIN; int64_t minimumSubsidy = 5.0 * COIN; static const int64_t nPremine = 20000000 * COIN; int64_t static GetBlockSubsidy(int nHeight){ if (nHeight == 0) { return nGenesisBlockRewardCoin; } if (nHeight == 1) { return nPremine; /* optimized standalone cpu miner 60*512=30720 standalone gpu miner 120*512=61440 first pool 70*512 =35840 block-explorer 60*512 =30720 mac wallet binary 30*512 =15360 linux wallet binary 30*512 =15360 web-site 100*512 =51200 total =240640 */ } int64_t nSubsidy = 512 * COIN; // Subsidy is reduced by 6% every 10080 blocks, which will occur approximately every 1 week int exponent=(nHeight / 10080); for(int i=0;i<exponent;i++){ nSubsidy=nSubsidy*47; nSubsidy=nSubsidy/50; } if(nSubsidy<minimumSubsidy){nSubsidy=minimumSubsidy;} return nSubsidy; } int64_t static GetBlockSubsidy120000(int nHeight) { // Subsidy is reduced by 10% every day (1440 blocks) int64_t nSubsidy = 250 * COIN; int exponent = ((nHeight - 120000) / 1440); for(int i=0; i<exponent; i++) nSubsidy = (nSubsidy * 45) / 50; return nSubsidy; } int64_t static GetBlockSubsidy150000(int nHeight) { static int heightOfMinSubsidy = INT_MAX; if (nHeight < heightOfMinSubsidy) { // Subsidy is reduced by 1% every week (10080 blocks) int64_t nSubsidy = 25 * COIN; int exponent = ((nHeight - 150000) / 10080); for (int i = 0; i < exponent; i++) nSubsidy = (nSubsidy * 99) / 100; if (nSubsidy >= minimumSubsidy) return nSubsidy; heightOfMinSubsidy = (min)(heightOfMinSubsidy, nHeight); } return minimumSubsidy; } CAmount GetBlockSubsidy(int nHeight, const Consensus::Params& consensusParams) { return nHeight >= 150000 ? GetBlockSubsidy150000(nHeight) : nHeight >= 120000 ? GetBlockSubsidy120000(nHeight) : GetBlockSubsidy(nHeight); } // // minimum amount of work that could possibly be required nTime after // minimum work required was nBase // static const int64_t nTargetSpacing = 1 * 60; // soferox every 60 seconds //!!!BUG this function is non-deterministic because FP-arithetics unsigned int static DarkGravityWave(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params) { /* current difficulty formula, darkcoin - DarkGravity, written by Evan Duffield - evan@darkcoin.io */ const CBlockIndex *BlockLastSolved = pindexLast; const CBlockIndex *BlockReading = pindexLast; int64_t nBlockTimeAverage = 0; int64_t nBlockTimeAveragePrev = 0; int64_t nBlockTimeCount = 0; int64_t nBlockTimeSum2 = 0; int64_t nBlockTimeCount2 = 0; int64_t LastBlockTime = 0; int64_t PastBlocksMin = 12; int64_t PastBlocksMax = 120; int64_t CountBlocks = 0; CBigNum PastDifficultyAverage; CBigNum PastDifficultyAveragePrev; if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || BlockLastSolved->nHeight < PastBlocksMin) { return UintToArith256(params.powLimit).GetCompact(); } for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) { if (PastBlocksMax > 0 && i > PastBlocksMax) { break; } CountBlocks++; if(CountBlocks <= PastBlocksMin) { if (CountBlocks == 1) { PastDifficultyAverage.SetCompact(BlockReading->nBits); } else { PastDifficultyAverage = ((CBigNum().SetCompact(BlockReading->nBits) - PastDifficultyAveragePrev) / CountBlocks) + PastDifficultyAveragePrev; } PastDifficultyAveragePrev = PastDifficultyAverage; } if(LastBlockTime > 0){ int64_t Diff = (LastBlockTime - BlockReading->GetBlockTime()); if(Diff < 0) Diff = 0; if(nBlockTimeCount <= PastBlocksMin) { nBlockTimeCount++; if (nBlockTimeCount == 1) { nBlockTimeAverage = Diff; } else { nBlockTimeAverage = ((Diff - nBlockTimeAveragePrev) / nBlockTimeCount) + nBlockTimeAveragePrev; } nBlockTimeAveragePrev = nBlockTimeAverage; } nBlockTimeCount2++; nBlockTimeSum2 += Diff; } LastBlockTime = BlockReading->GetBlockTime(); if (BlockReading->pprev == NULL) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } CBigNum bnNew(PastDifficultyAverage); if (nBlockTimeCount != 0 && nBlockTimeCount2 != 0) { double SmartAverage = (((nBlockTimeAverage)*0.7)+((nBlockTimeSum2 / nBlockTimeCount2)*0.3)); if(SmartAverage < 1) SmartAverage = 1; double Shift = nTargetSpacing/SmartAverage; int64_t nActualTimespan = (CountBlocks*nTargetSpacing)/Shift; int64_t nTargetTimespan = (CountBlocks*nTargetSpacing); if (nActualTimespan < nTargetTimespan/3) nActualTimespan = nTargetTimespan/3; if (nActualTimespan > nTargetTimespan*3) nActualTimespan = nTargetTimespan*3; // Retarget bnNew *= nActualTimespan; bnNew /= nTargetTimespan; } if (bnNew > CBigNum(params.powLimit)){ bnNew = CBigNum(params.powLimit); } return bnNew.GetCompact(); } unsigned int static DarkGravityWave3(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params) { /* current difficulty formula, darkcoin - DarkGravity v3, written by Evan Duffield - evan@darkcoin.io */ const CBlockIndex *BlockLastSolved = pindexLast; const CBlockIndex *BlockReading = pindexLast; int64_t nActualTimespan = 0; int64_t LastBlockTime = 0; int64_t PastBlocksMin = 24; int64_t PastBlocksMax = 24; int64_t CountBlocks = 0; CBigNum PastDifficultyAverage; CBigNum PastDifficultyAveragePrev; if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || BlockLastSolved->nHeight < PastBlocksMin) { return UintToArith256(params.powLimit).GetCompact(); } for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) { if (PastBlocksMax > 0 && i > PastBlocksMax) { break; } CountBlocks++; if(CountBlocks <= PastBlocksMin) { if (CountBlocks == 1) { PastDifficultyAverage.SetCompact(BlockReading->nBits); } else { PastDifficultyAverage = ((PastDifficultyAveragePrev * CountBlocks)+(CBigNum().SetCompact(BlockReading->nBits))) / (CountBlocks+1); } PastDifficultyAveragePrev = PastDifficultyAverage; } if(LastBlockTime > 0){ int64_t Diff = (LastBlockTime - BlockReading->GetBlockTime()); nActualTimespan += Diff; } LastBlockTime = BlockReading->GetBlockTime(); if (BlockReading->pprev == NULL) { assert(BlockReading); break; } BlockReading = BlockReading->pprev; } CBigNum bnNew(PastDifficultyAverage); int64_t nTargetTimespan = CountBlocks*nTargetSpacing; if (nActualTimespan < nTargetTimespan/3) nActualTimespan = nTargetTimespan/3; if (nActualTimespan > nTargetTimespan*3) nActualTimespan = nTargetTimespan*3; // Retarget bnNew *= nActualTimespan; bnNew /= nTargetTimespan; if (bnNew > CBigNum(params.powLimit)) { bnNew = CBigNum(params.powLimit); } return bnNew.GetCompact(); } //---------------------- unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params) { if (params.fPowAllowMinDifficultyBlocks) { // Special difficulty rule for testnet: // If the new block's timestamp is more than 2* 10 minutes // then allow mining of a min-difficulty block. if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2) return UintToArith256(params.powLimit).GetCompact(); } if (pindexLast->nHeight >= (100000 - 1)) return DarkGravityWave3(pindexLast, pblock, params); return DarkGravityWave(pindexLast, pblock, params); } static CBlock CreateGenesisBlock(const char* pszTimestamp, const CScript& genesisOutputScript, uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward) { CMutableTransaction txNew; txNew.nVersion = 1; txNew.vin.resize(1); txNew.vout.resize(1); txNew.vin[0].scriptSig = CScript() << 486604799 << CScriptNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp)); txNew.vout[0].nValue = genesisReward; txNew.vout[0].scriptPubKey = genesisOutputScript; CBlock genesis; genesis.nTime = nTime; genesis.nBits = nBits; genesis.nNonce = nNonce; genesis.nVersion = nVersion; genesis.vtx.push_back(MakeTransactionRef(std::move(txNew))); genesis.hashPrevBlock.SetNull(); genesis.hashMerkleRoot = BlockMerkleRoot(genesis); return genesis; } /** * Build the genesis block. Note that the output of its generation * transaction cannot be spent since it did not originally exist in the * database. * * CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1) * CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0) * CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73) * CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B) * vMerkleTree: 4a5e1e */ static CBlock CreateGenesisBlock(uint32_t nTime, uint32_t nNonce, uint32_t nBits, int32_t nVersion, const CAmount& genesisReward) { const char* pszTimestamp = "We always make good coin and future"; const CScript genesisOutputScript = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG; return CreateGenesisBlock(pszTimestamp, genesisOutputScript, nTime, nNonce, nBits, nVersion, genesisReward); } void CChainParams::UpdateVersionBitsParameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout) { consensus.vDeployments[d].nStartTime = nStartTime; consensus.vDeployments[d].nTimeout = nTimeout; } /** * Main network */ /** * What makes a good checkpoint block? * + Is surrounded by blocks with reasonable timestamps * (no blocks before with a timestamp after, none after with * timestamp before) * + Contains no strange transactions */ class CMainParams : public CChainParams { public: CMainParams() { strNetworkID = "main"; consensus.BIP16Height = 1439423; consensus.BIP34Height = 800000; consensus.BIP34Hash = uint256S("0x0000000007f3f37410d5f7e71a07bf09bb802d5af6726fc891f0248ad857708c"); consensus.BIP66Height = 800000; consensus.BIP65Height = INT_MAX; //!!!? consensus.powLimit = uint256S("00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); consensus.nPowTargetTimespan = 14 * 24 * 60 * 60; // two weeks consensus.nPowTargetSpacing = 60; consensus.fPowAllowMinDifficultyBlocks = false; consensus.nRuleChangeActivationThreshold = 1916; // 95% of 2016 consensus.nMinerConfirmationWindow = 2016; consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28; consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008 consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008 // Deployment of BIP68, BIP112, and BIP113. consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0; consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1535500800; // Aug 29, 2018 consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1546214400; // Dec 31, 2018 // Deployment of SegWit (BIP141 and BIP143) consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].bit = 1; consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 1535500800; // Aug 29, 2018 consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 1546214400; // Dec 31, 2018 // Deployment of BIP65 consensus.vDeployments[Consensus::DEPLOYMENT_BIP65].bit = 5; consensus.vDeployments[Consensus::DEPLOYMENT_BIP65].nStartTime = 1535500800; // Aug 29, 2018 consensus.vDeployments[Consensus::DEPLOYMENT_BIP65].nTimeout = 1546214400; // Dec 31, 2018 /** * The best chain should have at least this much work. * Don't set a value bigger than 0 if blockchain doesn't have any blocks yet. * Set your current ChainWork if you want nodes to wait until the whole blockchain is downloaded */ consensus.nMinimumChainWork = uint256S("0x00"); // By default assume that the signatures in ancestors of this block are valid. consensus.defaultAssumeValid = uint256S("0x0000000000002cb0ac72cf044034b93d43244501e496e55576aa5c5111bdc362"); //2035383 /** * The message start string is designed to be unlikely to occur in normal data. * The characters are rarely used upper ASCII, not valid as UTF-8, and produce * a large 32-bit integer with any alignment. */ pchMessageStart[0] = 0xf9; pchMessageStart[1] = 0xbe; pchMessageStart[2] = 0xb4; pchMessageStart[3] = 0xd4; nDefaultPort = 5332; nPruneAfterHeight = 10000000; // for (int nonce=1; nonce < 0x7FFFFFFF; ++nonce) { // genesis = CreateGenesisBlock(1530728779, nonce, 0x1e0fffff, 112, 0); // consensus.hashGenesisBlock = genesis.GetHash(); // if (UintToArith256(consensus.hashGenesisBlock) < UintToArith256(consensus.powLimit)) { // printf("Wonderfull__mainnet_genesis.merklroot = %s\n", genesis.hashMerkleRoot.ToString().c_str()); // printf("Wonderfull__mainnet_genesis.nonce = %d\n", genesis.nNonce); // printf("Wonderfull__mainnet_genesis.version = %d\n", genesis.nVersion); // printf("Wonderfull__mainnet_genesis.bits = %x\n", genesis.nBits); // printf("Wonderfull__mainnet_genesis.time = %d\n", genesis.nTime); // printf("Wonderfull__mainnet_genesis.GetHash = %s\n", genesis.GetHash().ToString().c_str()); // break; // } // } genesis = CreateGenesisBlock(1532449604, 1394613, 0x1e0fffff, 112, 0); /** * Build the genesis block. Note that the output of its generation * transaction cannot be spent since it did not originally exist in the * database. * * CBlock(hash=000000000019d6, ver=1, hashPrevBlock=00000000000000, hashMerkleRoot=4a5e1e, nTime=1231006505, nBits=1d00ffff, nNonce=2083236893, vtx=1) * CTransaction(hash=4a5e1e, ver=1, vin.size=1, vout.size=1, nLockTime=0) * CTxIn(COutPoint(000000, -1), coinbase 04ffff001d0104455468652054696d65732030332f4a616e2f32303039204368616e63656c6c6f72206f6e206272696e6b206f66207365636f6e64206261696c6f757420666f722062616e6b73) * CTxOut(nValue=50.00000000, scriptPubKey=0x5F1DF16B2B704C8A578D0B) * vMerkleTree: 4a5e1e */ /*!!!R CMutableTransaction txNew; txNew.vin.resize(1); txNew.vout.resize(1); genesis.vtx.push_back(txNew); genesis.hashPrevBlock.SetNull(); genesis.hashMerkleRoot = genesis.BuildMerkleTree(); */ consensus.hashGenesisBlock = genesis.GetHash(); // printf("main_genesis.GetHash = %s\n", genesis.GetHash().ToString().c_str()); // printf("main_genesis.merklroot = %s\n", genesis.hashMerkleRoot.ToString().c_str()); assert(consensus.hashGenesisBlock == uint256S("0x00000cb4df2fa9b4d6bc09d9502ed67f23397fcd4064512695c8a752f85d3f5f")); assert(genesis.hashMerkleRoot == uint256S("0x414d960e0ee8546bd482abc7d409c6d6f984ff7569b64750468386b70a0da1e5")); // vSeeds.push_back("soferox.org"); // vSeeds.push_back("electrum1.soferox.org"); // vSeeds.push_back("electrum2.soferox.org"); // vSeeds.push_back("jswallet.soferox.org"); // vSeeds.push_back("soferosight.soferox.org"); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,63); // guarantees the first character is S base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,125); // guarantees the first character is s base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,190); // guarantees the first character is V base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x88)(0xB2)(0x1E).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x88)(0xAD)(0xE4).convert_to_container<std::vector<unsigned char> >(); bech32_hrp = "sfx"; vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_main, pnSeed6_main + ARRAYLEN(pnSeed6_main)); //!!!? fMiningRequiresPeers = true; fDefaultConsistencyChecks = false; fRequireStandard = true; fMineBlocksOnDemand = false; #ifdef _MSC_VER //!!! checkpointData = CCheckpointData{ #else checkpointData = (CCheckpointData) { #endif { {0 , uint256S("0x000001b75fb6cfc7ee94f1552595c1e95ba4b149cbbb1d94bd05f23f2d432dce")}, // {28888, uint256S("0x00000000000228ce19f55cf0c45e04c7aa5a6a873ed23902b3654c3c49884502")}, // {58888, uint256S("0x0000000000dd85f4d5471febeb174a3f3f1598ab0af6616e9f266b56272274ef")}, // {111111, uint256S("0x00000000013de206275ee83f93bee57622335e422acbf126a37020484c6e113c")}, // {1000000, uint256S("0x000000000df8560f2612d5f28b52ed1cf81b0f87ac0c9c7242cbcf721ca6854a")}, // {2000000, uint256S("0x00000000000434d5b8d1c3308df7b6e3fd773657dfb28f5dd2f70854ef94cc66")}, } }; chainTxData = ChainTxData{ 1436539093, // * UNIX timestamp of last checkpoint block 0, // * total number of transactions between genesis and last checkpoint // (the tx=... number in the SetBestChain debug.log lines) 100.0 // * estimated number of transactions per day after checkpoint }; } }; static CMainParams mainParams; /** * Testnet (v3) */ class CTestNetParams : public CMainParams { public: CTestNetParams() { strNetworkID = "test"; consensus.BIP16Height = 1; consensus.BIP34Height = 286; consensus.BIP34Hash = uint256S("0x0000004b7778ba253a75b716c55b2c6609b5fb97691b3260978f9ce4a633106d"); consensus.BIP66Height = 286; consensus.BIP65Height = INT_MAX; //!!!? consensus.nPowTargetSpacing = 60; consensus.fPowAllowMinDifficultyBlocks = true; consensus.nRuleChangeActivationThreshold = 1512; // 75% for testchains consensus.nMinerConfirmationWindow = 2016; consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28; consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 1199145601; // January 1, 2008 consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = 1230767999; // December 31, 2008 // Deployment of BIP68, BIP112, and BIP113. consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0; consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 1535500800; // Aug 29, 2018 consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = 1546214400; // Dec 31, 2018 // Deployment of SegWit (BIP141, BIP143, and BIP147) consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].bit = 1; consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = 1535500800; // Aug 29, 2018 consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = 1546214400; // Dec 31, 2018 consensus.powLimit = uint256S("000000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); // The best chain should have at least this much work. consensus.nMinimumChainWork = uint256S("0x000000000000000000000000000000000000000000000000000000000000ffff"); // By default assume that the signatures in ancestors of this block are valid. consensus.defaultAssumeValid = uint256S("0x000000d6c9c013173e2313f24edc791a9134d379522901f7e40d9fc4f0e25bb0"); //525313 pchMessageStart[0] = 0x0b; pchMessageStart[1] = 0x11; pchMessageStart[2] = 0x09; pchMessageStart[3] = 0x07; nDefaultPort = 16644; nPruneAfterHeight = 1000000; /*!!!R for (int nonce=1; nonce < 0x7FFFFFFF; ++nonce) { genesis = CreateGenesisBlock(1440000002, nonce, 0x1e00ffff, 3, 0); consensus.hashGenesisBlock = genesis.GetHash(); if (UintToArith256(consensus.hashGenesisBlock) < UintToArith256(consensus.powLimit)) break; } */ //! Modify the testnet genesis block so the timestamp is valid for a later start. // for (int nonce=1; nonce < 0x7FFFFFFF; ++nonce) { // genesis = CreateGenesisBlock(1530728750, nonce, 0x1e00ffff, 3, 0); // consensus.hashGenesisBlock = genesis.GetHash(); // if (UintToArith256(consensus.hashGenesisBlock) < UintToArith256(consensus.powLimit)) { // printf("Wonderfull__testnet_genesis.GetHash = %s\n", genesis.GetHash().ToString().c_str()); // printf("Wonderfull__testnet_genesis.merklroot = %s\n", genesis.hashMerkleRoot.ToString().c_str()); // printf("Wonderfull__testnet_genesis.nonce = %d\n", genesis.nNonce); // break; // } // } genesis = CreateGenesisBlock(1530728750, 10742868, 0x1e00ffff, 3, 0); consensus.hashGenesisBlock = genesis.GetHash(); // printf("testnet_genesis.GetHash = %s\n", genesis.GetHash().ToString().c_str()); // printf("testnet_genesis.merklroot = %s\n", genesis.hashMerkleRoot.ToString().c_str()); // printf("testnet_nNounce = %d\n", genesis.nNonce); assert(consensus.hashGenesisBlock == uint256S("0x000000cf9bf4a0d7bc29ebdd9051fb68d3caa3e950b8be1dfbf35fea32a99fb7")); vFixedSeeds.clear(); vSeeds.clear(); // vSeeds.push_back("testnet1.soferox.org"); // vSeeds.push_back("testnet2.soferox.org"); // vSeeds.push_back("testp2pool.soferox.org"); // vSeeds.push_back("testp2pool2.soferox.org"); base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1,111); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1,196); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1,239); base58Prefixes[EXT_PUBLIC_KEY] = boost::assign::list_of(0x04)(0x35)(0x87)(0xCF).convert_to_container<std::vector<unsigned char> >(); base58Prefixes[EXT_SECRET_KEY] = boost::assign::list_of(0x04)(0x35)(0x83)(0x94).convert_to_container<std::vector<unsigned char> >(); bech32_hrp = "tsfx"; vFixedSeeds = std::vector<SeedSpec6>(pnSeed6_test, pnSeed6_test + ARRAYLEN(pnSeed6_test)); //!!!? fMiningRequiresPeers = false; //SFX Testnet can have single node fDefaultConsistencyChecks = false; fRequireStandard = false; fMineBlocksOnDemand = false; #ifdef _MSC_VER checkpointData = CCheckpointData{ #else checkpointData = (CCheckpointData) { #endif { //{0 , uint256S("0xbef0b3124119637ecd010cf263a47192eca747e9ef9c4d4f43eacb8fc2266644")}, // { 50000 , uint256S("0x00000081951486bb535f8cffec8ac0641bd24b814f89641f6cc2cad737f18950") }, } }; chainTxData = ChainTxData{ 1440000002, 0, 10 }; } }; static CTestNetParams testNetParams; /** * Regression test */ class CRegTestParams : public CMainParams { public: CRegTestParams() { strNetworkID = "regtest"; consensus.BIP16Height = 0; // always enforce P2SH BIP16 on regtest consensus.powLimit = uint256S("00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); consensus.nPowTargetSpacing = 1; consensus.fPowAllowMinDifficultyBlocks = true; consensus.nRuleChangeActivationThreshold = 108; // 75% for testchains consensus.nMinerConfirmationWindow = 144; // Faster than normal for regtest (144 instead of 2016) consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].bit = 28; consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nStartTime = 0; consensus.vDeployments[Consensus::DEPLOYMENT_TESTDUMMY].nTimeout = Consensus::BIP9Deployment::NO_TIMEOUT; consensus.vDeployments[Consensus::DEPLOYMENT_CSV].bit = 0; consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nStartTime = 0; consensus.vDeployments[Consensus::DEPLOYMENT_CSV].nTimeout = Consensus::BIP9Deployment::NO_TIMEOUT; consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].bit = 1; consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nStartTime = Consensus::BIP9Deployment::ALWAYS_ACTIVE; consensus.vDeployments[Consensus::DEPLOYMENT_SEGWIT].nTimeout = Consensus::BIP9Deployment::NO_TIMEOUT; // The best chain should have at least this much work. consensus.nMinimumChainWork = uint256S("0x00"); // By default assume that the signatures in ancestors of this block are valid. consensus.defaultAssumeValid = uint256S("0x00"); pchMessageStart[0] = 0xfa; pchMessageStart[1] = 0xbf; pchMessageStart[2] = 0xb5; pchMessageStart[3] = 0xda; nDefaultPort = 18888; nPruneAfterHeight = 1000; genesis = CreateGenesisBlock(1440000002, 6556309, 0x1e00ffff, 3, 0); consensus.hashGenesisBlock = genesis.GetHash(); assert(consensus.hashGenesisBlock == uint256S("0x000000ffbb50fc9898cdd36ec163e6ba23230164c0052a28876255b7dcf2cd36")); vFixedSeeds.clear(); //!< Regtest mode doesn't have any fixed seeds. vSeeds.clear(); //!< Regtest mode doesn't have any DNS seeds. fDefaultConsistencyChecks = true; fRequireStandard = false; fMineBlocksOnDemand = true; #ifdef _MSC_VER checkpointData = CCheckpointData{ #else checkpointData = (CCheckpointData) { #endif { // {0, uint256S("0x000000ffbb50fc9898cdd36ec163e6ba23230164c0052a28876255b7dcf2cd36")}, } }; chainTxData = ChainTxData{ 0, 0, 0 }; base58Prefixes[PUBKEY_ADDRESS] = std::vector<unsigned char>(1, 111); base58Prefixes[SCRIPT_ADDRESS] = std::vector<unsigned char>(1, 196); base58Prefixes[SECRET_KEY] = std::vector<unsigned char>(1, 239); base58Prefixes[EXT_PUBLIC_KEY] = { 0x04, 0x35, 0x87, 0xCF }; base58Prefixes[EXT_SECRET_KEY] = { 0x04, 0x35, 0x83, 0x94 }; bech32_hrp = "sfxrt"; } }; static std::unique_ptr<CChainParams> globalChainParams; const CChainParams &Params() { assert(globalChainParams); return *globalChainParams; } std::unique_ptr<CChainParams> CreateChainParams(const std::string& chain) { if (chain == CBaseChainParams::MAIN) return std::unique_ptr<CChainParams>(new CMainParams()); else if (chain == CBaseChainParams::TESTNET) return std::unique_ptr<CChainParams>(new CTestNetParams()); else if (chain == CBaseChainParams::REGTEST) return std::unique_ptr<CChainParams>(new CRegTestParams()); throw std::runtime_error(strprintf("%s: Unknown chain %s.", __func__, chain)); } void SelectParams(const std::string& network) { SelectBaseParams(network); globalChainParams = CreateChainParams(network); } void UpdateVersionBitsParameters(Consensus::DeploymentPos d, int64_t nStartTime, int64_t nTimeout) { globalChainParams->UpdateVersionBitsParameters(d, nStartTime, nTimeout); }
39.980142
208
0.715497
[ "vector" ]
4f78d914609e06361059dc79576056ebca22ef14
843
cxx
C++
phys-services/private/test/I3FunctionTest.cxx
hschwane/offline_production
e14a6493782f613b8bbe64217559765d5213dc1e
[ "MIT" ]
1
2020-12-24T22:00:01.000Z
2020-12-24T22:00:01.000Z
phys-services/private/test/I3FunctionTest.cxx
hschwane/offline_production
e14a6493782f613b8bbe64217559765d5213dc1e
[ "MIT" ]
null
null
null
phys-services/private/test/I3FunctionTest.cxx
hschwane/offline_production
e14a6493782f613b8bbe64217559765d5213dc1e
[ "MIT" ]
3
2020-07-17T09:20:29.000Z
2021-03-30T16:44:18.000Z
/** copyright (C) 2004 the icecube collaboration $Id: I3FunctionTest.cxx 124369 2014-10-09 16:17:40Z nega $ @version $Revision: 124369 $ @date $Date: 2014-10-09 10:17:40 -0600 (Thu, 09 Oct 2014) $ @author dule @todo */ #include <I3Test.h> #include "phys-services/I3Functions.h" #include <string> using namespace std; TEST_GROUP(I3Functions) TEST(ParseFilename) { string searchpattern(getenv("I3_TESTDATA")); searchpattern.append("/amanda/*.f2k"); //4 searchpattern.append(";"); searchpattern.append(getenv("I3_TESTDATA")); searchpattern.append("/ama-*.*"); // 4 vector<string> v = I3Functions::ParseFilename(searchpattern); for(vector<string>::iterator iter=v.begin(); iter!=v.end(); iter++) { cout<<*iter<<endl; } ENSURE(v.size()==8,"Didn't find the expected number of files"); }
22.783784
69
0.666667
[ "vector" ]
4f7ea1ee2a5b1151e2168f1a856e14f1b4957fcc
4,205
cpp
C++
Computer-Graphics/Fase-4/engine/Models/catmull-rom.cpp
paulob122/CG_19-20
6962e83ed4867a79b9b07c83da9ab609cd73c909
[ "MIT" ]
null
null
null
Computer-Graphics/Fase-4/engine/Models/catmull-rom.cpp
paulob122/CG_19-20
6962e83ed4867a79b9b07c83da9ab609cd73c909
[ "MIT" ]
null
null
null
Computer-Graphics/Fase-4/engine/Models/catmull-rom.cpp
paulob122/CG_19-20
6962e83ed4867a79b9b07c83da9ab609cd73c909
[ "MIT" ]
null
null
null
#define _USE_MATH_DEFINES #include <math.h> #include <model-info.h> #ifdef __APPLE__ #include <GLUT/glut.h> #else #include <GL/glut.h> #endif using namespace std; void buildRotMatrix(float *x, float *y, float *z, float *m) { m[0] = x[0]; m[1] = x[1]; m[2] = x[2]; m[3] = 0; m[4] = y[0]; m[5] = y[1]; m[6] = y[2]; m[7] = 0; m[8] = z[0]; m[9] = z[1]; m[10] = z[2]; m[11] = 0; m[12] = 0; m[13] = 0; m[14] = 0; m[15] = 1; } void cross(float *a, float *b, float *res) { res[0] = a[1]*b[2] - a[2]*b[1]; res[1] = a[2]*b[0] - a[0]*b[2]; res[2] = a[0]*b[1] - a[1]*b[0]; } void normalize(float *a) { float l = sqrt(a[0]*a[0] + a[1] * a[1] + a[2] * a[2]); a[0] = a[0]/l; a[1] = a[1]/l; a[2] = a[2]/l; } float length(float *v) { float res = sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]); return res; } void multMatrixVector(float *m, float *v, float *res) { for (int j = 0; j < 4; ++j) { res[j] = 0; for (int k = 0; k < 4; ++k) { res[j] += v[k] * m[j * 4 + k]; } } } void getCatmullRomPoint(float t, float *p0, float *p1, float *p2, float *p3, float *pos, float *deriv) { //---------------------------------------------------------------------------------------------------- // catmull-rom matrix float m[4][4] = { {-0.5f, 1.5f, -1.5f, 0.5f}, { 1.0f, -2.5f, 2.0f, -0.5f}, {-0.5f, 0.0f, 0.5f, 0.0f}, { 0.0f, 1.0f, 0.0f, 0.0f}}; //---------------------------------------------------------------------------------------------------- float T[4] = { t*t*t, t*t, t, 1 }; float TD[4] = { 3*t*t, 2*t, 1, 0 }; //---------------------------------------------------------------------------------------------------- // Compute A = M * P float P[3][4] = { { p0[0], p1[0], p2[0], p3[0] }, { p0[1], p1[1], p2[1], p3[1] }, { p0[2], p1[2], p2[2], p3[2] } }; float A[3][4]; multMatrixVector(*m, P[0], A[0]); multMatrixVector(*m, P[1], A[1]); multMatrixVector(*m, P[2], A[2]); //---------------------------------------------------------------------------------------------------- // Compute pos = T * A for (int i = 0; i < 4; i++) { pos[0] += T[i] * A[0][i]; pos[1] += T[i] * A[1][i]; pos[2] += T[i] * A[2][i]; } //---------------------------------------------------------------------------------------------------- // compute deriv = T' * A for (int i = 0; i < 4; i++) { deriv[0] += TD[i] * A[0][i]; deriv[1] += TD[i] * A[1][i]; deriv[2] += TD[i] * A[2][i]; } } void getGlobalCatmullRomPoint(vector<POINT_3D>* points, float gt, float *pos, float *deriv) { int POINT_COUNT = points -> size(); float t = gt * POINT_COUNT; // this is the real global t int index = floor(t); // which segment t = t - index; // where within the segment // indices store the points int indices[4]; indices[0] = (index + POINT_COUNT-1)%POINT_COUNT; indices[1] = (indices[0]+1)%POINT_COUNT; indices[2] = (indices[1]+1)%POINT_COUNT; indices[3] = (indices[2]+1)%POINT_COUNT; //stores the base points for the curve float p[4][3]; for (int i = 0; i < 4; i++) { p[i][0] = points -> at(indices[i]).x; p[i][1] = points -> at(indices[i]).y; p[i][2] = points -> at(indices[i]).z; } getCatmullRomPoint(t, p[0], p[1], p[2], p[3], pos, deriv); } void renderCatmullRomCurve(vector<POINT_3D>* points) { //cout << "Inicio" << endl; //---------------------------------------------------------- // draw curve using line segments with GL_LINE_LOOP glBegin(GL_POINTS); for (int i = 0; i < 200; i++) { float pos[3] = { 0.0, 0.0, 0.0 }; float deriv[3] = { 0.0, 0.0, 0.0 }; float gt = i / 200.0f; getGlobalCatmullRomPoint(points, gt, (float*)pos, (float*)deriv); glVertex3f(pos[0], pos[1], pos[2]); } glEnd(); //---------------------------------------------------------- //cout << "Fim..." << endl; }
25.331325
106
0.388823
[ "vector", "model" ]
4f802d53121ba9d851e19493534ff60f249c4f81
21,853
cpp
C++
src/Util/SceneDrawables.cpp
roto5296/choreonoid
ffe12df8db71e32aea18833afb80dffc42c373d0
[ "MIT" ]
66
2020-03-11T14:06:01.000Z
2022-03-23T23:18:27.000Z
src/Util/SceneDrawables.cpp
roto5296/choreonoid
ffe12df8db71e32aea18833afb80dffc42c373d0
[ "MIT" ]
12
2020-07-23T06:13:11.000Z
2022-01-13T14:25:01.000Z
src/Util/SceneDrawables.cpp
roto5296/choreonoid
ffe12df8db71e32aea18833afb80dffc42c373d0
[ "MIT" ]
18
2020-07-17T15:57:54.000Z
2022-03-29T13:18:59.000Z
/*! @file @author Shin'ichiro Nakaoka */ #include "SceneDrawables.h" #include "CloneMap.h" #include "SceneNodeClassRegistry.h" using namespace std; using namespace cnoid; namespace { const bool USE_FACES_FOR_BOUNDING_BOX_CALCULATION = true; struct NodeClassRegistration { NodeClassRegistration() { SceneNodeClassRegistry::instance() .registerClass<SgShape, SgNode>() .registerClass<SgPlot, SgNode>() .registerClass<SgPointSet, SgPlot>() .registerClass<SgLineSet, SgPlot>() .registerClass<SgOverlay, SgGroup>() .registerClass<SgViewportOverlay, SgOverlay>(); } } registration; } SgMaterial::SgMaterial() { setAttribute(Appearance); ambientIntensity_ = 1.0f; diffuseColor_ << 1.0f, 1.0f, 1.0f; emissiveColor_.setZero(); specularColor_.setZero(); specularExponent_ = 25.0f; transparency_ = 0.0f; } SgMaterial::SgMaterial(const SgMaterial& org) : SgObject(org) { ambientIntensity_ = org.ambientIntensity_; diffuseColor_ = org.diffuseColor_; emissiveColor_ = org.emissiveColor_; specularColor_ = org.specularColor_; specularExponent_ = org.specularExponent_; transparency_ = org.transparency_; } Referenced* SgMaterial::doClone(CloneMap*) const { return new SgMaterial(*this); } float SgMaterial::shininess() const { return std::max(0.0f, std::min(specularExponent_ - 1.0f, 127.0f)) / 127.0f; } void SgMaterial::setShininess(float s) { specularExponent_ = 127.0f * std::max(0.0f, std::min(s, 1.0f)) + 1.0f; } SgImage::SgImage() : image_(std::make_shared<Image>()) { setAttribute(Appearance); } SgImage::SgImage(const Image& image) : image_(std::make_shared<Image>(image)) { setAttribute(Appearance); } SgImage::SgImage(std::shared_ptr<Image> sharedImage) : image_(sharedImage) { setAttribute(Appearance); } SgImage::SgImage(const SgImage& org) : SgObject(org), image_(org.image_) { } Referenced* SgImage::doClone(CloneMap*) const { return new SgImage(*this); } Image& SgImage::image() { if(image_.use_count() > 1){ image_ = std::make_shared<Image>(*image_); } return *image_; } unsigned char* SgImage::pixels() { if(image_.use_count() > 1){ image_ = std::make_shared<Image>(*image_); } return image_->pixels(); } void SgImage::setSize(int width, int height, int nComponents) { image().setSize(width, height, nComponents); } void SgImage::setSize(int width, int height) { image().setSize(width, height); } SgTextureTransform::SgTextureTransform() { setAttribute(Appearance); center_ << 0.0, 0.0; rotation_ = 0; scale_ << 1.0, 1.0; translation_ << 0.0, 0.0; } SgTextureTransform::SgTextureTransform(const SgTextureTransform& org) : SgObject(org) { center_ = org.center_; rotation_ = org.rotation_; scale_ = org.scale_; translation_ = org.translation_; } Referenced* SgTextureTransform::doClone(CloneMap*) const { return new SgTextureTransform(*this); } SgTexture::SgTexture() { setAttributes(Composite | Appearance); repeatS_ = true; repeatT_ = true; } SgTexture::SgTexture(const SgTexture& org, CloneMap* cloneMap) : SgObject(org) { if(cloneMap && checkNonNodeCloning(*cloneMap)){ if(org.image()){ setImage(cloneMap->getClone<SgImage>(org.image())); } if(org.textureTransform()){ setTextureTransform(cloneMap->getClone<SgTextureTransform>(org.textureTransform())); } } else { setImage(const_cast<SgImage*>(org.image())); setTextureTransform(const_cast<SgTextureTransform*>(org.textureTransform())); } repeatS_ = org.repeatS_; repeatT_ = org.repeatT_; } SgTexture::~SgTexture() { if(image_){ image_->removeParent(this); } if(textureTransform_){ textureTransform_->removeParent(this); } } Referenced* SgTexture::doClone(CloneMap* cloneMap) const { return new SgTexture(*this, cloneMap); } int SgTexture::numChildObjects() const { int n = 0; if(image_) ++n; if(textureTransform_) ++n; return n; } SgObject* SgTexture::childObject(int index) { SgObject* objects[2] = { 0, 0 }; int i = 0; if(image_) objects[i++] = image_; if(textureTransform_) objects[i++] = textureTransform_; return objects[index]; } SgImage* SgTexture::setImage(SgImage* image) { if(image_){ image_->removeParent(this); } image_ = image; if(image){ image->addParent(this); } return image; } SgImage* SgTexture::getOrCreateImage() { if(!image_){ setImage(new SgImage); } return image_; } SgTextureTransform* SgTexture::setTextureTransform(SgTextureTransform* textureTransform) { if(textureTransform_){ textureTransform_->removeParent(this); } textureTransform_ = textureTransform; if(textureTransform){ textureTransform->addParent(this); } return textureTransform; } SgTextureTransform* SgTexture::getOrCreateTextureTransform() { if(!textureTransform_){ setTextureTransform(new SgTextureTransform); } return textureTransform_; } SgMeshBase::SgMeshBase() { setAttribute(Composite | Geometry); creaseAngle_ = 0.0f; isSolid_ = false; } SgMeshBase::SgMeshBase(const SgMeshBase& org, CloneMap* cloneMap) : SgObject(org), faceVertexIndices_(org.faceVertexIndices_), normalIndices_(org.normalIndices_), colorIndices_(org.colorIndices_), texCoordIndices_(org.texCoordIndices_) { if(cloneMap && checkNonNodeCloning(*cloneMap)){ if(org.vertices_){ setVertices(cloneMap->getClone<SgVertexArray>(org.vertices())); } if(org.normals_){ setNormals(cloneMap->getClone<SgNormalArray>(org.normals())); } if(org.colors_){ setColors(cloneMap->getClone<SgColorArray>(org.colors())); } if(org.texCoords_){ setTexCoords(cloneMap->getClone<SgTexCoordArray>(org.texCoords())); } } else { setVertices(const_cast<SgVertexArray*>(org.vertices())); setNormals(const_cast<SgNormalArray*>(org.normals())); setColors(const_cast<SgColorArray*>(org.colors())); setTexCoords(const_cast<SgTexCoordArray*>(org.texCoords())); } creaseAngle_ = org.creaseAngle_; isSolid_ = org.isSolid_; bbox = org.bbox; } SgMeshBase::~SgMeshBase() { if(vertices_){ vertices_->removeParent(this); } if(normals_){ normals_->removeParent(this); } if(colors_){ colors_->removeParent(this); } if(texCoords_){ texCoords_->removeParent(this); } } int SgMeshBase::numChildObjects() const { int n = 0; if(vertices_) ++n; if(normals_) ++n; if(colors_) ++n; return n; } SgObject* SgMeshBase::childObject(int index) { SgObject* objects[3] = { 0, 0, 0 }; int i = 0; if(vertices_) objects[i++] = vertices_.get(); if(normals_) objects[i++] = normals_.get(); if(colors_) objects[i++] = colors_.get(); return objects[index]; } void SgMeshBase::updateBoundingBox() { if(!vertices_){ bbox.clear(); } else { BoundingBoxf bboxf; for(SgVertexArray::const_iterator p = vertices_->begin(); p != vertices_->end(); ++p){ bboxf.expandBy(*p); } bbox = bboxf; } } SgVertexArray* SgMeshBase::setVertices(SgVertexArray* vertices) { if(vertices_){ vertices_->removeParent(this); } vertices_ = vertices; if(vertices){ vertices->setAttribute(Geometry); vertices->addParent(this); } return vertices; } SgVertexArray* SgMeshBase::getOrCreateVertices(int size) { if(!vertices_){ setVertices(new SgVertexArray(size)); } else if(size > 0){ vertices_->resize(size); } return vertices_; } SgNormalArray* SgMeshBase::setNormals(SgNormalArray* normals) { if(normals_){ normals_->removeParent(this); } normals_ = normals; if(normals){ normals->setAttribute(Appearance); normals->addParent(this); } return normals; } SgNormalArray* SgMeshBase::getOrCreateNormals() { if(!normals_){ setNormals(new SgNormalArray); } return normals_; } SgColorArray* SgMeshBase::setColors(SgColorArray* colors) { if(colors_){ colors_->removeParent(this); } colors_ = colors; if(colors){ colors->setAttribute(Appearance); colors->addParent(this); } return colors; } SgColorArray* SgMeshBase::getOrCreateColors(int size) { if(!colors_){ setColors(new SgColorArray(size)); } else if(size > 0){ colors_->resize(size); } return colors_; } SgTexCoordArray* SgMeshBase::setTexCoords(SgTexCoordArray* texCoords) { if(texCoords_){ texCoords_->removeParent(this); } texCoords_ = texCoords; if(texCoords){ texCoords->setAttribute(Appearance); texCoords->addParent(this); } return texCoords; } SgTexCoordArray* SgMeshBase::getOrCreateTexCoords() { if(!texCoords_){ setTexCoords(new SgTexCoordArray); } return texCoords_; } SgMesh::SgMesh() { divisionNumber_ = -1; extraDivisionNumber_ = -1; extraDivisionMode_ = ExtraDivisionPreferred; } SgMesh::SgMesh(Primitive primitive) : SgMesh() { primitive_ = primitive; } SgMesh::SgMesh(const SgMesh& org, CloneMap* cloneMap) : SgMeshBase(org, cloneMap), primitive_(org.primitive_), divisionNumber_(org.divisionNumber_), extraDivisionNumber_(org.extraDivisionNumber_), extraDivisionMode_(org.extraDivisionMode_) { } Referenced* SgMesh::doClone(CloneMap* cloneMap) const { return new SgMesh(*this, cloneMap); } void SgMesh::updateBoundingBox() { if(!USE_FACES_FOR_BOUNDING_BOX_CALCULATION){ SgMeshBase::updateBoundingBox(); } else { if(!hasVertices()){ bbox.clear(); } else { BoundingBoxf bboxf; const SgVertexArray& v = *vertices(); for(auto& index : faceVertexIndices_){ bboxf.expandBy(v[index]); } bbox = bboxf; } } } void SgMesh::transform(const Affine3& T) { if(hasVertices()){ auto& v = *vertices(); for(size_t i=0; i < v.size(); ++i){ v[i] = (T * v[i].cast<Affine3::Scalar>()).cast<Vector3f::Scalar>(); } if(hasNormals()){ Matrix3 R = T.linear(); auto& n = *normals(); for(size_t i=0; i < n.size(); ++i){ n[i] = (R * n[i].cast<Affine3::Scalar>()).cast<Vector3f::Scalar>(); } } } setPrimitive(SgMesh::Mesh()); // clear the primitive information } void SgMesh::transform(const Affine3f& T) { if(hasVertices()){ auto& v = *vertices(); for(size_t i=0; i < v.size(); ++i){ v[i] = T.linear() * v[i] + T.translation(); } if(hasNormals()){ auto& n = *normals(); for(size_t i=0; i < n.size(); ++i){ n[i] = T.linear() * n[i]; } } } setPrimitive(SgMesh::Mesh()); // clear the primitive information } void SgMesh::translate(const Vector3f& translation) { if(hasVertices()){ auto& v = *vertices(); for(size_t i=0; i < v.size(); ++i){ v[i] += translation; } } setPrimitive(SgMesh::Mesh()); // clear the primitive information } void SgMesh::rotate(const Matrix3f& R) { if(hasVertices()){ auto& v = *vertices(); for(size_t i=0; i < v.size(); ++i){ v[i] = R * v[i]; } if(hasNormals()){ auto& n = *normals(); for(size_t i=0; i < n.size(); ++i){ n[i] = R * n[i]; } } } setPrimitive(SgMesh::Mesh()); // clear the primitive information } SgPolygonMesh::SgPolygonMesh() { } SgPolygonMesh::SgPolygonMesh(const SgPolygonMesh& org, CloneMap* cloneMap) : SgMeshBase(org, cloneMap) { } Referenced* SgPolygonMesh::doClone(CloneMap* cloneMap) const { return new SgPolygonMesh(*this, cloneMap); } void SgPolygonMesh::updateBoundingBox() { if(!USE_FACES_FOR_BOUNDING_BOX_CALCULATION){ SgMeshBase::updateBoundingBox(); } else { if(!hasVertices()){ bbox.clear(); } else { BoundingBoxf bboxf; const SgVertexArray& v = *vertices(); for(auto& index : faceVertexIndices_){ if(index >= 0){ bboxf.expandBy(v[index]); } } bbox = bboxf; } } } SgShape::SgShape(int classId) : SgNode(classId) { setAttribute(Composite | Geometry | Appearance); } SgShape::SgShape() : SgShape(findClassId<SgShape>()) { } SgShape::SgShape(const SgShape& org, CloneMap* cloneMap) : SgNode(org) { if(cloneMap && checkNonNodeCloning(*cloneMap)){ if(org.mesh()){ setMesh(cloneMap->getClone<SgMesh>(org.mesh())); } if(org.material()){ setMaterial(cloneMap->getClone<SgMaterial>(org.material())); } if(org.texture()){ setTexture(cloneMap->getClone<SgTexture>(org.texture())); } } else { setMesh(const_cast<SgMesh*>(org.mesh())); setMaterial(const_cast<SgMaterial*>(org.material())); setTexture(const_cast<SgTexture*>(org.texture())); } } SgShape::~SgShape() { if(mesh_){ mesh_->removeParent(this); } if(material_){ material_->removeParent(this); } if(texture_){ texture_->removeParent(this); } } Referenced* SgShape::doClone(CloneMap* cloneMap) const { return new SgShape(*this, cloneMap); } int SgShape::numChildObjects() const { int n = 0; if(mesh_) ++n; if(material_) ++n; if(texture_) ++n; return n; } SgObject* SgShape::childObject(int index) { SgObject* objects[3] = { 0, 0, 0 }; int i = 0; if(mesh_) objects[i++] = mesh_.get(); if(material_) objects[i++] = material_.get(); if(texture_) objects[i++] = texture_.get(); return objects[index]; } const BoundingBox& SgShape::boundingBox() const { if(mesh()){ return mesh()->boundingBox(); } return SgNode::boundingBox(); } const BoundingBox& SgShape::untransformedBoundingBox() const { return SgShape::boundingBox(); } SgMesh* SgShape::setMesh(SgMesh* mesh) { if(mesh_){ mesh_->removeParent(this); } mesh_ = mesh; if(mesh){ mesh->addParent(this); } return mesh; } SgMesh* SgShape::getOrCreateMesh() { if(!mesh_){ setMesh(new SgMesh); } return mesh_; } SgMaterial* SgShape::setMaterial(SgMaterial* material) { if(material_){ material_->removeParent(this); } material_ = material; if(material){ material->addParent(this); } return material; } SgMaterial* SgShape::getOrCreateMaterial() { if(!material_){ setMaterial(new SgMaterial); } return material_; } SgTexture* SgShape::setTexture(SgTexture* texture) { if(texture_){ texture_->removeParent(this); } texture_ = texture; if(texture){ texture->addParent(this); } return texture; } SgTexture* SgShape::getOrCreateTexture() { if(!texture_){ setTexture(new SgTexture); } return texture_; } SgPlot::SgPlot(int classId) : SgNode(classId) { setAttribute(Composite | Geometry | Appearance); } SgPlot::SgPlot(const SgPlot& org, CloneMap* cloneMap) : SgNode(org) { bbox = org.bbox; if(cloneMap && checkNonNodeCloning(*cloneMap)){ if(org.vertices()){ setVertices(cloneMap->getClone<SgVertexArray>(org.vertices())); } if(org.material()){ setMaterial(cloneMap->getClone<SgMaterial>(org.material())); } if(org.colors()){ setColors(cloneMap->getClone<SgColorArray>(org.colors())); } if(org.normals()){ setNormals(cloneMap->getClone<SgNormalArray>(org.normals())); } } else { setVertices(const_cast<SgVertexArray*>(org.vertices())); setMaterial(const_cast<SgMaterial*>(org.material())); setColors(const_cast<SgColorArray*>(org.colors())); setNormals(const_cast<SgNormalArray*>(org.normals())); } colorIndices_ = org.colorIndices_; normalIndices_ = org.normalIndices_; } SgPlot::~SgPlot() { if(vertices_){ vertices_->removeParent(this); } if(material_){ material_->removeParent(this); } if(colors_){ colors_->removeParent(this); } if(normals_){ normals_->removeParent(this); } } int SgPlot::numChildObjects() const { int n = 0; if(vertices_) ++n; if(colors_) ++n; if(normals_) ++n; return n; } SgObject* SgPlot::childObject(int index) { SgObject* objects[3] = { nullptr, nullptr, nullptr }; int i = 0; if(vertices_) objects[i++] = vertices_.get(); if(colors_) objects[i++] = colors_.get(); if(normals_) objects[i++] = normals_.get(); return objects[index]; } const BoundingBox& SgPlot::boundingBox() const { return bbox; } const BoundingBox& SgPlot::untransformedBoundingBox() const { return bbox; } void SgPlot::updateBoundingBox() { if(!vertices_){ bbox.clear(); } else { BoundingBoxf bboxf; for(SgVertexArray::const_iterator p = vertices_->begin(); p != vertices_->end(); ++p){ bboxf.expandBy(*p); } bbox = bboxf; } } void SgPlot::clear() { if(vertices_){ vertices_->clear(); } if(colors_){ colors_->clear(); } colorIndices_.clear(); if(normals_){ normals_->clear(); } normalIndices_.clear(); } SgVertexArray* SgPlot::setVertices(SgVertexArray* vertices) { if(vertices_){ vertices_->removeParent(this); } vertices_ = vertices; if(vertices){ vertices->setAttribute(Geometry); vertices->addParent(this); } return vertices; } SgVertexArray* SgPlot::getOrCreateVertices(int size) { if(!vertices_){ setVertices(new SgVertexArray(size)); } else if(size > 0){ vertices_->resize(size); } return vertices_; } SgMaterial* SgPlot::setMaterial(SgMaterial* material) { if(material_){ material_->removeParent(this); } material_ = material; if(material){ material->addParent(this); } return material; } SgMaterial* SgPlot::getOrCreateMaterial() { if(!material_){ setMaterial(new SgMaterial); } return material_; } SgColorArray* SgPlot::setColors(SgColorArray* colors) { if(colors_){ colors_->removeParent(this); } colors_ = colors; if(colors){ colors->setAttribute(Appearance); colors->addParent(this); } return colors; } SgColorArray* SgPlot::getOrCreateColors(int size) { if(!colors_){ setColors(new SgColorArray(size)); } else if(size > 0){ colors_->resize(size); } return colors_; } SgNormalArray* SgPlot::setNormals(SgNormalArray* normals) { if(normals_){ normals_->removeParent(this); } normals_ = normals; if(normals){ normals->setAttribute(Appearance); normals->addParent(this); } return normals; } SgNormalArray* SgPlot::getOrCreateNormals() { if(!normals_){ setNormals(new SgNormalArray); } return normals_; } SgPointSet::SgPointSet(int classId) : SgPlot(classId) { pointSize_ = 0.0; } SgPointSet::SgPointSet() : SgPointSet(findClassId<SgPointSet>()) { } SgPointSet::SgPointSet(const SgPointSet& org, CloneMap* cloneMap) : SgPlot(org, cloneMap) { pointSize_ = org.pointSize_; } Referenced* SgPointSet::doClone(CloneMap* cloneMap) const { return new SgPointSet(*this, cloneMap); } SgLineSet::SgLineSet(int classId) : SgPlot(classId) { lineWidth_ = 0.0; } SgLineSet::SgLineSet() : SgLineSet(findClassId<SgLineSet>()) { lineWidth_ = 0.0; } SgLineSet::SgLineSet(const SgLineSet& org, CloneMap* cloneMap) : SgPlot(org, cloneMap), lineVertexIndices_(org.lineVertexIndices_) { lineWidth_ = org.lineWidth_; } Referenced* SgLineSet::doClone(CloneMap* cloneMap) const { return new SgLineSet(*this, cloneMap); } SgOverlay::SgOverlay(int classId) : SgGroup(classId) { } SgOverlay::SgOverlay() : SgGroup(findClassId<SgOverlay>()) { } SgOverlay::SgOverlay(const SgOverlay& org, CloneMap* cloneMap) : SgGroup(org, cloneMap) { } SgOverlay::~SgOverlay() { } Referenced* SgOverlay::doClone(CloneMap* cloneMap) const { return new SgOverlay(*this, cloneMap); } SgViewportOverlay::SgViewportOverlay(int classId) : SgOverlay(classId) { } SgViewportOverlay::SgViewportOverlay() : SgOverlay(findClassId<SgViewportOverlay>()) { } SgViewportOverlay::SgViewportOverlay(const SgViewportOverlay& org, CloneMap* cloneMap) : SgOverlay(org, cloneMap) { } SgViewportOverlay::~SgViewportOverlay() { } Referenced* SgViewportOverlay::doClone(CloneMap* cloneMap) const { return new SgViewportOverlay(*this, cloneMap); } void SgViewportOverlay::calcViewVolume(double /* viewportWidth */, double /* viewportHeight */, ViewVolume& io_volume) { io_volume.left = -1.0; io_volume.right = 1.0; io_volume.bottom = -1.0; io_volume.top = 1.0; io_volume.zNear = 1.0; io_volume.zFar = -1.0; }
19.459484
118
0.614607
[ "mesh", "geometry", "transform" ]
4f80805a495916e371b4bf35b5454cfa169daff0
223,366
cpp
C++
src/third_party/icu4c-57.1/source/common/ucnvmbcs.cpp
SunguckLee/real-mongodb
fef0e44fafc6d3709a84101327e7d2f54dd18d88
[ "Apache-2.0" ]
4
2018-02-06T01:53:12.000Z
2018-02-20T01:47:36.000Z
src/third_party/icu4c-57.1/source/common/ucnvmbcs.cpp
SunguckLee/real-mongodb
fef0e44fafc6d3709a84101327e7d2f54dd18d88
[ "Apache-2.0" ]
null
null
null
src/third_party/icu4c-57.1/source/common/ucnvmbcs.cpp
SunguckLee/real-mongodb
fef0e44fafc6d3709a84101327e7d2f54dd18d88
[ "Apache-2.0" ]
3
2018-02-06T01:53:18.000Z
2021-07-28T09:48:15.000Z
/* ****************************************************************************** * * Copyright (C) 2000-2016, International Business Machines * Corporation and others. All Rights Reserved. * ****************************************************************************** * file name: ucnvmbcs.cpp * encoding: US-ASCII * tab size: 8 (not used) * indentation:4 * * created on: 2000jul03 * created by: Markus W. Scherer * * The current code in this file replaces the previous implementation * of conversion code from multi-byte codepages to Unicode and back. * This implementation supports the following: * - legacy variable-length codepages with up to 4 bytes per character * - all Unicode code points (up to 0x10ffff) * - efficient distinction of unassigned vs. illegal byte sequences * - it is possible in fromUnicode() to directly deal with simple * stateful encodings (used for EBCDIC_STATEFUL) * - it is possible to convert Unicode code points * to a single zero byte (but not as a fallback except for SBCS) * * Remaining limitations in fromUnicode: * - byte sequences must not have leading zero bytes * - except for SBCS codepages: no fallback mapping from Unicode to a zero byte * - limitation to up to 4 bytes per character * * ICU 2.8 (late 2003) adds a secondary data structure which lifts some of these * limitations and adds m:n character mappings and other features. * See ucnv_ext.h for details. * * Change history: * * 5/6/2001 Ram Moved MBCS_SINGLE_RESULT_FROM_U,MBCS_STAGE_2_FROM_U, * MBCS_VALUE_2_FROM_STAGE_2, MBCS_VALUE_4_FROM_STAGE_2 * macros to ucnvmbcs.h file */ #include "unicode/utypes.h" #if !UCONFIG_NO_CONVERSION && !UCONFIG_NO_LEGACY_CONVERSION #include "unicode/ucnv.h" #include "unicode/ucnv_cb.h" #include "unicode/udata.h" #include "unicode/uset.h" #include "unicode/utf8.h" #include "unicode/utf16.h" #include "ucnv_bld.h" #include "ucnvmbcs.h" #include "ucnv_ext.h" #include "ucnv_cnv.h" #include "cmemory.h" #include "cstring.h" #include "umutex.h" /* control optimizations according to the platform */ #define MBCS_UNROLL_SINGLE_TO_BMP 1 #define MBCS_UNROLL_SINGLE_FROM_BMP 0 /* * _MBCSHeader versions 5.3 & 4.3 * (Note that the _MBCSHeader version is in addition to the converter formatVersion.) * * This version is optional. Version 5 is used for incompatible data format changes. * makeconv will continue to generate version 4 files if possible. * * Changes from version 4: * * The main difference is an additional _MBCSHeader field with * - the length (number of uint32_t) of the _MBCSHeader * - flags for further incompatible data format changes * - flags for further, backward compatible data format changes * * The MBCS_OPT_FROM_U flag indicates that most of the fromUnicode data is omitted from * the file and needs to be reconstituted at load time. * This requires a utf8Friendly format with an additional mbcsIndex table for fast * (and UTF-8-friendly) fromUnicode conversion for Unicode code points up to maxFastUChar. * (For details about these structures see below, and see ucnvmbcs.h.) * * utf8Friendly also implies that the fromUnicode mappings are stored in ascending order * of the Unicode code points. (This requires that the .ucm file has the |0 etc. * precision markers for all mappings.) * * All fallbacks have been moved to the extension table, leaving only roundtrips in the * omitted data that can be reconstituted from the toUnicode data. * * Of the stage 2 table, the part corresponding to maxFastUChar and below is omitted. * With only roundtrip mappings in the base fromUnicode data, this part is fully * redundant with the mbcsIndex and will be reconstituted from that (also using the * stage 1 table which contains the information about how stage 2 was compacted). * * The rest of the stage 2 table, the part for code points above maxFastUChar, * is stored in the file and will be appended to the reconstituted part. * * The entire fromUBytes array is omitted from the file and will be reconstitued. * This is done by enumerating all toUnicode roundtrip mappings, performing * each mapping (using the stage 1 and reconstituted stage 2 tables) and * writing instead of reading the byte values. * * _MBCSHeader version 4.3 * * Change from version 4.2: * - Optional utf8Friendly data structures, with 64-entry stage 3 block * allocation for parts of the BMP, and an additional mbcsIndex in non-SBCS * files which can be used instead of stages 1 & 2. * Faster lookups for roundtrips from most commonly used characters, * and lookups from UTF-8 byte sequences with a natural bit distribution. * See ucnvmbcs.h for more details. * * Change from version 4.1: * - Added an optional extension table structure at the end of the .cnv file. * It is present if the upper bits of the header flags field contains a non-zero * byte offset to it. * Files that contain only a conversion table and no base table * use the special outputType MBCS_OUTPUT_EXT_ONLY. * These contain the base table name between the MBCS header and the extension * data. * * Change from version 4.0: * - Replace header.reserved with header.fromUBytesLength so that all * fields in the data have length. * * Changes from version 3 (for performance improvements): * - new bit distribution for state table entries * - reordered action codes * - new data structure for single-byte fromUnicode * + stage 2 only contains indexes * + stage 3 stores 16 bits per character with classification bits 15..8 * - no multiplier for stage 1 entries * - stage 2 for non-single-byte codepages contains the index and the flags in * one 32-bit value * - 2-byte and 4-byte fromUnicode results are stored directly as 16/32-bit integers * * For more details about old versions of the MBCS data structure, see * the corresponding versions of this file. * * Converting stateless codepage data ---------------------------------------*** * (or codepage data with simple states) to Unicode. * * Data structure and algorithm for converting from complex legacy codepages * to Unicode. (Designed before 2000-may-22.) * * The basic idea is that the structure of legacy codepages can be described * with state tables. * When reading a byte stream, each input byte causes a state transition. * Some transitions result in the output of a code point, some result in * "unassigned" or "illegal" output. * This is used here for character conversion. * * The data structure begins with a state table consisting of a row * per state, with 256 entries (columns) per row for each possible input * byte value. * Each entry is 32 bits wide, with two formats distinguished by * the sign bit (bit 31): * * One format for transitional entries (bit 31 not set) for non-final bytes, and * one format for final entries (bit 31 set). * Both formats contain the number of the next state in the same bit * positions. * State 0 is the initial state. * * Most of the time, the offset values of subsequent states are added * up to a scalar value. This value will eventually be the index of * the Unicode code point in a table that follows the state table. * The effect is that the code points for final state table rows * are contiguous. The code points of final state rows follow each other * in the order of the references to those final states by previous * states, etc. * * For some terminal states, the offset is itself the output Unicode * code point (16 bits for a BMP code point or 20 bits for a supplementary * code point (stored as code point minus 0x10000 so that 20 bits are enough). * For others, the code point in the Unicode table is stored with either * one or two code units: one for BMP code points, two for a pair of * surrogates. * All code points for a final state entry take up the same number of code * units, regardless of whether they all actually _use_ the same number * of code units. This is necessary for simple array access. * * An additional feature comes in with what in ICU is called "fallback" * mappings: * * In addition to round-trippable, precise, 1:1 mappings, there are often * mappings defined between similar, though not the same, characters. * Typically, such mappings occur only in fromUnicode mapping tables because * Unicode has a superset repertoire of most other codepages. However, it * is possible to provide such mappings in the toUnicode tables, too. * In this case, the fallback mappings are partly integrated into the * general state tables because the structure of the encoding includes their * byte sequences. * For final entries in an initial state, fallback mappings are stored in * the entry itself like with roundtrip mappings. * For other final entries, they are stored in the code units table if * the entry is for a pair of code units. * For single-unit results in the code units table, there is no space to * alternatively hold a fallback mapping; in this case, the code unit * is stored as U+fffe (unassigned), and the fallback mapping needs to * be looked up by the scalar offset value in a separate table. * * "Unassigned" state entries really mean "structurally unassigned", * i.e., such a byte sequence will never have a mapping result. * * The interpretation of the bits in each entry is as follows: * * Bit 31 not set, not a terminal entry ("transitional"): * 30..24 next state * 23..0 offset delta, to be added up * * Bit 31 set, terminal ("final") entry: * 30..24 next state (regardless of action code) * 23..20 action code: * action codes 0 and 1 result in precise-mapping Unicode code points * 0 valid byte sequence * 19..16 not used, 0 * 15..0 16-bit Unicode BMP code point * never U+fffe or U+ffff * 1 valid byte sequence * 19..0 20-bit Unicode supplementary code point * never U+fffe or U+ffff * * action codes 2 and 3 result in fallback (unidirectional-mapping) Unicode code points * 2 valid byte sequence (fallback) * 19..16 not used, 0 * 15..0 16-bit Unicode BMP code point as fallback result * 3 valid byte sequence (fallback) * 19..0 20-bit Unicode supplementary code point as fallback result * * action codes 4 and 5 may result in roundtrip/fallback/unassigned/illegal results * depending on the code units they result in * 4 valid byte sequence * 19..9 not used, 0 * 8..0 final offset delta * pointing to one 16-bit code unit which may be * fffe unassigned -- look for a fallback for this offset * ffff illegal * 5 valid byte sequence * 19..9 not used, 0 * 8..0 final offset delta * pointing to two 16-bit code units * (typically UTF-16 surrogates) * the result depends on the first code unit as follows: * 0000..d7ff roundtrip BMP code point (1st alone) * d800..dbff roundtrip surrogate pair (1st, 2nd) * dc00..dfff fallback surrogate pair (1st-400, 2nd) * e000 roundtrip BMP code point (2nd alone) * e001 fallback BMP code point (2nd alone) * fffe unassigned * ffff illegal * (the final offset deltas are at most 255 * 2, * times 2 because of storing code unit pairs) * * 6 unassigned byte sequence * 19..16 not used, 0 * 15..0 16-bit Unicode BMP code point U+fffe (new with version 2) * this does not contain a final offset delta because the main * purpose of this action code is to save scalar offset values; * therefore, fallback values cannot be assigned to byte * sequences that result in this action code * 7 illegal byte sequence * 19..16 not used, 0 * 15..0 16-bit Unicode BMP code point U+ffff (new with version 2) * 8 state change only * 19..0 not used, 0 * useful for state changes in simple stateful encodings, * at Shift-In/Shift-Out codes * * * 9..15 reserved for future use * current implementations will only perform a state change * and ignore bits 19..0 * * An encoding with contiguous ranges of unassigned byte sequences, like * Shift-JIS and especially EUC-TW, can be stored efficiently by having * at least two states for the trail bytes: * One trail byte state that results in code points, and one that only * has "unassigned" and "illegal" terminal states. * * Note: partly by accident, this data structure supports simple stateful * encodings without any additional logic. * Currently, only simple Shift-In/Shift-Out schemes are handled with * appropriate state tables (especially EBCDIC_STATEFUL!). * * MBCS version 2 added: * unassigned and illegal action codes have U+fffe and U+ffff * instead of unused bits; this is useful for _MBCS_SINGLE_SIMPLE_GET_NEXT_BMP() * * Converting from Unicode to codepage bytes --------------------------------*** * * The conversion data structure for fromUnicode is designed for the known * structure of Unicode. It maps from 21-bit code points (0..0x10ffff) to * a sequence of 1..4 bytes, in addition to a flag that indicates if there is * a roundtrip mapping. * * The lookup is done with a 3-stage trie, using 11/6/4 bits for stage 1/2/3 * like in the character properties table. * The beginning of the trie is at offsetFromUTable, the beginning of stage 3 * with the resulting bytes is at offsetFromUBytes. * * Beginning with version 4, single-byte codepages have a significantly different * trie compared to other codepages. * In all cases, the entry in stage 1 is directly the index of the block of * 64 entries in stage 2. * * Single-byte lookup: * * Stage 2 only contains 16-bit indexes directly to the 16-blocks in stage 3. * Stage 3 contains one 16-bit word per result: * Bits 15..8 indicate the kind of result: * f roundtrip result * c fallback result from private-use code point * 8 fallback result from other code points * 0 unassigned * Bits 7..0 contain the codepage byte. A zero byte is always possible. * * In version 4.3, the runtime code can build an sbcsIndex for a utf8Friendly * file. For 2-byte UTF-8 byte sequences and some 3-byte sequences the lookup * becomes a 2-stage (single-index) trie lookup with 6 bits for stage 3. * ASCII code points can be looked up with a linear array access into stage 3. * See maxFastUChar and other details in ucnvmbcs.h. * * Multi-byte lookup: * * Stage 2 contains a 32-bit word for each 16-block in stage 3: * Bits 31..16 contain flags for which stage 3 entries contain roundtrip results * test: MBCS_FROM_U_IS_ROUNDTRIP(stage2Entry, c) * If this test is false, then a non-zero result will be interpreted as * a fallback mapping. * Bits 15..0 contain the index to stage 3, which must be multiplied by 16*(bytes per char) * * Stage 3 contains 2, 3, or 4 bytes per result. * 2 or 4 bytes are stored as uint16_t/uint32_t in platform endianness, * while 3 bytes are stored as bytes in big-endian order. * Leading zero bytes are ignored, and the number of bytes is counted. * A zero byte mapping result is possible as a roundtrip result. * For some output types, the actual result is processed from this; * see ucnv_MBCSFromUnicodeWithOffsets(). * * Note that stage 1 always contains 0x440=1088 entries (0x440==0x110000>>10), * or (version 3 and up) for BMP-only codepages, it contains 64 entries. * * In version 4.3, a utf8Friendly file contains an mbcsIndex table. * For 2-byte UTF-8 byte sequences and most 3-byte sequences the lookup * becomes a 2-stage (single-index) trie lookup with 6 bits for stage 3. * ASCII code points can be looked up with a linear array access into stage 3. * See maxFastUChar, mbcsIndex and other details in ucnvmbcs.h. * * In version 3, stage 2 blocks may overlap by multiples of the multiplier * for compaction. * In version 4, stage 2 blocks (and for single-byte codepages, stage 3 blocks) * may overlap by any number of entries. * * MBCS version 2 added: * the converter checks for known output types, which allows * adding new ones without crashing an unaware converter */ /** * Callback from ucnv_MBCSEnumToUnicode(), takes 32 mappings from * consecutive sequences of bytes, starting from the one encoded in value, * to Unicode code points. (Multiple mappings to reduce per-function call overhead.) * Does not currently support m:n mappings or reverse fallbacks. * This function will not be called for sequences of bytes with leading zeros. * * @param context an opaque pointer, as passed into ucnv_MBCSEnumToUnicode() * @param value contains 1..4 bytes of the first byte sequence, right-aligned * @param codePoints resulting Unicode code points, or negative if a byte sequence does * not map to anything * @return TRUE to continue enumeration, FALSE to stop */ typedef UBool U_CALLCONV UConverterEnumToUCallback(const void *context, uint32_t value, UChar32 codePoints[32]); static void ucnv_MBCSLoad(UConverterSharedData *sharedData, UConverterLoadArgs *pArgs, const uint8_t *raw, UErrorCode *pErrorCode); static void ucnv_MBCSUnload(UConverterSharedData *sharedData); static void ucnv_MBCSOpen(UConverter *cnv, UConverterLoadArgs *pArgs, UErrorCode *pErrorCode); static UChar32 ucnv_MBCSGetNextUChar(UConverterToUnicodeArgs *pArgs, UErrorCode *pErrorCode); static void ucnv_MBCSGetStarters(const UConverter* cnv, UBool starters[256], UErrorCode *pErrorCode); static const char * ucnv_MBCSGetName(const UConverter *cnv); static void ucnv_MBCSWriteSub(UConverterFromUnicodeArgs *pArgs, int32_t offsetIndex, UErrorCode *pErrorCode); static UChar32 ucnv_MBCSGetNextUChar(UConverterToUnicodeArgs *pArgs, UErrorCode *pErrorCode); static void ucnv_SBCSFromUTF8(UConverterFromUnicodeArgs *pFromUArgs, UConverterToUnicodeArgs *pToUArgs, UErrorCode *pErrorCode); static void ucnv_MBCSGetUnicodeSet(const UConverter *cnv, const USetAdder *sa, UConverterUnicodeSet which, UErrorCode *pErrorCode); static void ucnv_DBCSFromUTF8(UConverterFromUnicodeArgs *pFromUArgs, UConverterToUnicodeArgs *pToUArgs, UErrorCode *pErrorCode); static const UConverterImpl _SBCSUTF8Impl={ UCNV_MBCS, ucnv_MBCSLoad, ucnv_MBCSUnload, ucnv_MBCSOpen, NULL, NULL, ucnv_MBCSToUnicodeWithOffsets, ucnv_MBCSToUnicodeWithOffsets, ucnv_MBCSFromUnicodeWithOffsets, ucnv_MBCSFromUnicodeWithOffsets, ucnv_MBCSGetNextUChar, ucnv_MBCSGetStarters, ucnv_MBCSGetName, ucnv_MBCSWriteSub, NULL, ucnv_MBCSGetUnicodeSet, NULL, ucnv_SBCSFromUTF8 }; static const UConverterImpl _DBCSUTF8Impl={ UCNV_MBCS, ucnv_MBCSLoad, ucnv_MBCSUnload, ucnv_MBCSOpen, NULL, NULL, ucnv_MBCSToUnicodeWithOffsets, ucnv_MBCSToUnicodeWithOffsets, ucnv_MBCSFromUnicodeWithOffsets, ucnv_MBCSFromUnicodeWithOffsets, ucnv_MBCSGetNextUChar, ucnv_MBCSGetStarters, ucnv_MBCSGetName, ucnv_MBCSWriteSub, NULL, ucnv_MBCSGetUnicodeSet, NULL, ucnv_DBCSFromUTF8 }; static const UConverterImpl _MBCSImpl={ UCNV_MBCS, ucnv_MBCSLoad, ucnv_MBCSUnload, ucnv_MBCSOpen, NULL, NULL, ucnv_MBCSToUnicodeWithOffsets, ucnv_MBCSToUnicodeWithOffsets, ucnv_MBCSFromUnicodeWithOffsets, ucnv_MBCSFromUnicodeWithOffsets, ucnv_MBCSGetNextUChar, ucnv_MBCSGetStarters, ucnv_MBCSGetName, ucnv_MBCSWriteSub, NULL, ucnv_MBCSGetUnicodeSet, NULL, NULL }; /* Static data is in tools/makeconv/ucnvstat.c for data-based * converters. Be sure to update it as well. */ const UConverterSharedData _MBCSData={ sizeof(UConverterSharedData), 1, NULL, NULL, FALSE, TRUE, &_MBCSImpl, 0, UCNV_MBCS_TABLE_INITIALIZER }; /* GB 18030 data ------------------------------------------------------------ */ /* helper macros for linear values for GB 18030 four-byte sequences */ #define LINEAR_18030(a, b, c, d) ((((a)*10+(b))*126L+(c))*10L+(d)) #define LINEAR_18030_BASE LINEAR_18030(0x81, 0x30, 0x81, 0x30) #define LINEAR(x) LINEAR_18030(x>>24, (x>>16)&0xff, (x>>8)&0xff, x&0xff) /* * Some ranges of GB 18030 where both the Unicode code points and the * GB four-byte sequences are contiguous and are handled algorithmically by * the special callback functions below. * The values are start & end of Unicode & GB codes. * * Note that single surrogates are not mapped by GB 18030 * as of the re-released mapping tables from 2000-nov-30. */ static const uint32_t gb18030Ranges[14][4]={ {0x10000, 0x10FFFF, LINEAR(0x90308130), LINEAR(0xE3329A35)}, {0x9FA6, 0xD7FF, LINEAR(0x82358F33), LINEAR(0x8336C738)}, {0x0452, 0x1E3E, LINEAR(0x8130D330), LINEAR(0x8135F436)}, {0x1E40, 0x200F, LINEAR(0x8135F438), LINEAR(0x8136A531)}, {0xE865, 0xF92B, LINEAR(0x8336D030), LINEAR(0x84308534)}, {0x2643, 0x2E80, LINEAR(0x8137A839), LINEAR(0x8138FD38)}, {0xFA2A, 0xFE2F, LINEAR(0x84309C38), LINEAR(0x84318537)}, {0x3CE1, 0x4055, LINEAR(0x8231D438), LINEAR(0x8232AF32)}, {0x361B, 0x3917, LINEAR(0x8230A633), LINEAR(0x8230F237)}, {0x49B8, 0x4C76, LINEAR(0x8234A131), LINEAR(0x8234E733)}, {0x4160, 0x4336, LINEAR(0x8232C937), LINEAR(0x8232F837)}, {0x478E, 0x4946, LINEAR(0x8233E838), LINEAR(0x82349638)}, {0x44D7, 0x464B, LINEAR(0x8233A339), LINEAR(0x8233C931)}, {0xFFE6, 0xFFFF, LINEAR(0x8431A234), LINEAR(0x8431A439)} }; /* bit flag for UConverter.options indicating GB 18030 special handling */ #define _MBCS_OPTION_GB18030 0x8000 /* bit flag for UConverter.options indicating KEIS,JEF,JIF special handling */ #define _MBCS_OPTION_KEIS 0x01000 #define _MBCS_OPTION_JEF 0x02000 #define _MBCS_OPTION_JIPS 0x04000 #define KEIS_SO_CHAR_1 0x0A #define KEIS_SO_CHAR_2 0x42 #define KEIS_SI_CHAR_1 0x0A #define KEIS_SI_CHAR_2 0x41 #define JEF_SO_CHAR 0x28 #define JEF_SI_CHAR 0x29 #define JIPS_SO_CHAR_1 0x1A #define JIPS_SO_CHAR_2 0x70 #define JIPS_SI_CHAR_1 0x1A #define JIPS_SI_CHAR_2 0x71 enum SISO_Option { SI, SO }; typedef enum SISO_Option SISO_Option; static int32_t getSISOBytes(SISO_Option option, uint32_t cnvOption, uint8_t *value) { int32_t SISOLength = 0; switch (option) { case SI: if ((cnvOption&_MBCS_OPTION_KEIS)!=0) { value[0] = KEIS_SI_CHAR_1; value[1] = KEIS_SI_CHAR_2; SISOLength = 2; } else if ((cnvOption&_MBCS_OPTION_JEF)!=0) { value[0] = JEF_SI_CHAR; SISOLength = 1; } else if ((cnvOption&_MBCS_OPTION_JIPS)!=0) { value[0] = JIPS_SI_CHAR_1; value[1] = JIPS_SI_CHAR_2; SISOLength = 2; } else { value[0] = UCNV_SI; SISOLength = 1; } break; case SO: if ((cnvOption&_MBCS_OPTION_KEIS)!=0) { value[0] = KEIS_SO_CHAR_1; value[1] = KEIS_SO_CHAR_2; SISOLength = 2; } else if ((cnvOption&_MBCS_OPTION_JEF)!=0) { value[0] = JEF_SO_CHAR; SISOLength = 1; } else if ((cnvOption&_MBCS_OPTION_JIPS)!=0) { value[0] = JIPS_SO_CHAR_1; value[1] = JIPS_SO_CHAR_2; SISOLength = 2; } else { value[0] = UCNV_SO; SISOLength = 1; } break; default: /* Should never happen. */ break; } return SISOLength; } /* Miscellaneous ------------------------------------------------------------ */ /* similar to ucnv_MBCSGetNextUChar() but recursive */ static UBool enumToU(UConverterMBCSTable *mbcsTable, int8_t stateProps[], int32_t state, uint32_t offset, uint32_t value, UConverterEnumToUCallback *callback, const void *context, UErrorCode *pErrorCode) { UChar32 codePoints[32]; const int32_t *row; const uint16_t *unicodeCodeUnits; UChar32 anyCodePoints; int32_t b, limit; row=mbcsTable->stateTable[state]; unicodeCodeUnits=mbcsTable->unicodeCodeUnits; value<<=8; anyCodePoints=-1; /* becomes non-negative if there is a mapping */ b=(stateProps[state]&0x38)<<2; if(b==0 && stateProps[state]>=0x40) { /* skip byte sequences with leading zeros because they are not stored in the fromUnicode table */ codePoints[0]=U_SENTINEL; b=1; } limit=((stateProps[state]&7)+1)<<5; while(b<limit) { int32_t entry=row[b]; if(MBCS_ENTRY_IS_TRANSITION(entry)) { int32_t nextState=MBCS_ENTRY_TRANSITION_STATE(entry); if(stateProps[nextState]>=0) { /* recurse to a state with non-ignorable actions */ if(!enumToU( mbcsTable, stateProps, nextState, offset+MBCS_ENTRY_TRANSITION_OFFSET(entry), value|(uint32_t)b, callback, context, pErrorCode)) { return FALSE; } } codePoints[b&0x1f]=U_SENTINEL; } else { UChar32 c; int32_t action; /* * An if-else-if chain provides more reliable performance for * the most common cases compared to a switch. */ action=MBCS_ENTRY_FINAL_ACTION(entry); if(action==MBCS_STATE_VALID_DIRECT_16) { /* output BMP code point */ c=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); } else if(action==MBCS_STATE_VALID_16) { int32_t finalOffset=offset+MBCS_ENTRY_FINAL_VALUE_16(entry); c=unicodeCodeUnits[finalOffset]; if(c<0xfffe) { /* output BMP code point */ } else { c=U_SENTINEL; } } else if(action==MBCS_STATE_VALID_16_PAIR) { int32_t finalOffset=offset+MBCS_ENTRY_FINAL_VALUE_16(entry); c=unicodeCodeUnits[finalOffset++]; if(c<0xd800) { /* output BMP code point below 0xd800 */ } else if(c<=0xdbff) { /* output roundtrip or fallback supplementary code point */ c=((c&0x3ff)<<10)+unicodeCodeUnits[finalOffset]+(0x10000-0xdc00); } else if(c==0xe000) { /* output roundtrip BMP code point above 0xd800 or fallback BMP code point */ c=unicodeCodeUnits[finalOffset]; } else { c=U_SENTINEL; } } else if(action==MBCS_STATE_VALID_DIRECT_20) { /* output supplementary code point */ c=(UChar32)(MBCS_ENTRY_FINAL_VALUE(entry)+0x10000); } else { c=U_SENTINEL; } codePoints[b&0x1f]=c; anyCodePoints&=c; } if(((++b)&0x1f)==0) { if(anyCodePoints>=0) { if(!callback(context, value|(uint32_t)(b-0x20), codePoints)) { return FALSE; } anyCodePoints=-1; } } } return TRUE; } /* * Only called if stateProps[state]==-1. * A recursive call may do stateProps[state]|=0x40 if this state is the target of an * MBCS_STATE_CHANGE_ONLY. */ static int8_t getStateProp(const int32_t (*stateTable)[256], int8_t stateProps[], int state) { const int32_t *row; int32_t min, max, entry, nextState; row=stateTable[state]; stateProps[state]=0; /* find first non-ignorable state */ for(min=0;; ++min) { entry=row[min]; nextState=MBCS_ENTRY_STATE(entry); if(stateProps[nextState]==-1) { getStateProp(stateTable, stateProps, nextState); } if(MBCS_ENTRY_IS_TRANSITION(entry)) { if(stateProps[nextState]>=0) { break; } } else if(MBCS_ENTRY_FINAL_ACTION(entry)<MBCS_STATE_UNASSIGNED) { break; } if(min==0xff) { stateProps[state]=-0x40; /* (int8_t)0xc0 */ return stateProps[state]; } } stateProps[state]|=(int8_t)((min>>5)<<3); /* find last non-ignorable state */ for(max=0xff; min<max; --max) { entry=row[max]; nextState=MBCS_ENTRY_STATE(entry); if(stateProps[nextState]==-1) { getStateProp(stateTable, stateProps, nextState); } if(MBCS_ENTRY_IS_TRANSITION(entry)) { if(stateProps[nextState]>=0) { break; } } else if(MBCS_ENTRY_FINAL_ACTION(entry)<MBCS_STATE_UNASSIGNED) { break; } } stateProps[state]|=(int8_t)(max>>5); /* recurse further and collect direct-state information */ while(min<=max) { entry=row[min]; nextState=MBCS_ENTRY_STATE(entry); if(stateProps[nextState]==-1) { getStateProp(stateTable, stateProps, nextState); } if(MBCS_ENTRY_IS_FINAL(entry)) { stateProps[nextState]|=0x40; if(MBCS_ENTRY_FINAL_ACTION(entry)<=MBCS_STATE_FALLBACK_DIRECT_20) { stateProps[state]|=0x40; } } ++min; } return stateProps[state]; } /* * Internal function enumerating the toUnicode data of an MBCS converter. * Currently only used for reconstituting data for a MBCS_OPT_NO_FROM_U * table, but could also be used for a future ucnv_getUnicodeSet() option * that includes reverse fallbacks (after updating this function's implementation). * Currently only handles roundtrip mappings. * Does not currently handle extensions. */ static void ucnv_MBCSEnumToUnicode(UConverterMBCSTable *mbcsTable, UConverterEnumToUCallback *callback, const void *context, UErrorCode *pErrorCode) { /* * Properties for each state, to speed up the enumeration. * Ignorable actions are unassigned/illegal/state-change-only: * They do not lead to mappings. * * Bits 7..6: * 1 direct/initial state (stateful converters have multiple) * 0 non-initial state with transitions or with non-ignorable result actions * -1 final state with only ignorable actions * * Bits 5..3: * The lowest byte value with non-ignorable actions is * value<<5 (rounded down). * * Bits 2..0: * The highest byte value with non-ignorable actions is * (value<<5)&0x1f (rounded up). */ int8_t stateProps[MBCS_MAX_STATE_COUNT]; int32_t state; uprv_memset(stateProps, -1, sizeof(stateProps)); /* recurse from state 0 and set all stateProps */ getStateProp(mbcsTable->stateTable, stateProps, 0); for(state=0; state<mbcsTable->countStates; ++state) { /*if(stateProps[state]==-1) { printf("unused/unreachable <icu:state> %d\n", state); }*/ if(stateProps[state]>=0x40) { /* start from each direct state */ enumToU( mbcsTable, stateProps, state, 0, 0, callback, context, pErrorCode); } } } U_CFUNC void ucnv_MBCSGetFilteredUnicodeSetForUnicode(const UConverterSharedData *sharedData, const USetAdder *sa, UConverterUnicodeSet which, UConverterSetFilter filter, UErrorCode *pErrorCode) { const UConverterMBCSTable *mbcsTable; const uint16_t *table; uint32_t st3; uint16_t st1, maxStage1, st2; UChar32 c; /* enumerate the from-Unicode trie table */ mbcsTable=&sharedData->mbcs; table=mbcsTable->fromUnicodeTable; if(mbcsTable->unicodeMask&UCNV_HAS_SUPPLEMENTARY) { maxStage1=0x440; } else { maxStage1=0x40; } c=0; /* keep track of the current code point while enumerating */ if(mbcsTable->outputType==MBCS_OUTPUT_1) { const uint16_t *stage2, *stage3, *results; uint16_t minValue; results=(const uint16_t *)mbcsTable->fromUnicodeBytes; /* * Set a threshold variable for selecting which mappings to use. * See ucnv_MBCSSingleFromBMPWithOffsets() and * MBCS_SINGLE_RESULT_FROM_U() for details. */ if(which==UCNV_ROUNDTRIP_SET) { /* use only roundtrips */ minValue=0xf00; } else /* UCNV_ROUNDTRIP_AND_FALLBACK_SET */ { /* use all roundtrip and fallback results */ minValue=0x800; } for(st1=0; st1<maxStage1; ++st1) { st2=table[st1]; if(st2>maxStage1) { stage2=table+st2; for(st2=0; st2<64; ++st2) { if((st3=stage2[st2])!=0) { /* read the stage 3 block */ stage3=results+st3; do { if(*stage3++>=minValue) { sa->add(sa->set, c); } } while((++c&0xf)!=0); } else { c+=16; /* empty stage 3 block */ } } } else { c+=1024; /* empty stage 2 block */ } } } else { const uint32_t *stage2; const uint8_t *stage3, *bytes; uint32_t st3Multiplier; uint32_t value; UBool useFallback; bytes=mbcsTable->fromUnicodeBytes; useFallback=(UBool)(which==UCNV_ROUNDTRIP_AND_FALLBACK_SET); switch(mbcsTable->outputType) { case MBCS_OUTPUT_3: case MBCS_OUTPUT_4_EUC: st3Multiplier=3; break; case MBCS_OUTPUT_4: st3Multiplier=4; break; default: st3Multiplier=2; break; } for(st1=0; st1<maxStage1; ++st1) { st2=table[st1]; if(st2>(maxStage1>>1)) { stage2=(const uint32_t *)table+st2; for(st2=0; st2<64; ++st2) { if((st3=stage2[st2])!=0) { /* read the stage 3 block */ stage3=bytes+st3Multiplier*16*(uint32_t)(uint16_t)st3; /* get the roundtrip flags for the stage 3 block */ st3>>=16; /* * Add code points for which the roundtrip flag is set, * or which map to non-zero bytes if we use fallbacks. * See ucnv_MBCSFromUnicodeWithOffsets() for details. */ switch(filter) { case UCNV_SET_FILTER_NONE: do { if(st3&1) { sa->add(sa->set, c); stage3+=st3Multiplier; } else if(useFallback) { uint8_t b=0; switch(st3Multiplier) { case 4: b|=*stage3++; U_FALLTHROUGH; case 3: b|=*stage3++; U_FALLTHROUGH; case 2: b|=stage3[0]|stage3[1]; stage3+=2; U_FALLTHROUGH; default: break; } if(b!=0) { sa->add(sa->set, c); } } st3>>=1; } while((++c&0xf)!=0); break; case UCNV_SET_FILTER_DBCS_ONLY: /* Ignore single-byte results (<0x100). */ do { if(((st3&1)!=0 || useFallback) && *((const uint16_t *)stage3)>=0x100) { sa->add(sa->set, c); } st3>>=1; stage3+=2; /* +=st3Multiplier */ } while((++c&0xf)!=0); break; case UCNV_SET_FILTER_2022_CN: /* Only add code points that map to CNS 11643 planes 1 & 2 for non-EXT ISO-2022-CN. */ do { if(((st3&1)!=0 || useFallback) && ((value=*stage3)==0x81 || value==0x82)) { sa->add(sa->set, c); } st3>>=1; stage3+=3; /* +=st3Multiplier */ } while((++c&0xf)!=0); break; case UCNV_SET_FILTER_SJIS: /* Only add code points that map to Shift-JIS codes corresponding to JIS X 0208. */ do { if(((st3&1)!=0 || useFallback) && (value=*((const uint16_t *)stage3))>=0x8140 && value<=0xeffc) { sa->add(sa->set, c); } st3>>=1; stage3+=2; /* +=st3Multiplier */ } while((++c&0xf)!=0); break; case UCNV_SET_FILTER_GR94DBCS: /* Only add code points that map to ISO 2022 GR 94 DBCS codes (each byte A1..FE). */ do { if( ((st3&1)!=0 || useFallback) && (uint16_t)((value=*((const uint16_t *)stage3)) - 0xa1a1)<=(0xfefe - 0xa1a1) && (uint8_t)(value-0xa1)<=(0xfe - 0xa1) ) { sa->add(sa->set, c); } st3>>=1; stage3+=2; /* +=st3Multiplier */ } while((++c&0xf)!=0); break; case UCNV_SET_FILTER_HZ: /* Only add code points that are suitable for HZ DBCS (lead byte A1..FD). */ do { if( ((st3&1)!=0 || useFallback) && (uint16_t)((value=*((const uint16_t *)stage3))-0xa1a1)<=(0xfdfe - 0xa1a1) && (uint8_t)(value-0xa1)<=(0xfe - 0xa1) ) { sa->add(sa->set, c); } st3>>=1; stage3+=2; /* +=st3Multiplier */ } while((++c&0xf)!=0); break; default: *pErrorCode=U_INTERNAL_PROGRAM_ERROR; return; } } else { c+=16; /* empty stage 3 block */ } } } else { c+=1024; /* empty stage 2 block */ } } } ucnv_extGetUnicodeSet(sharedData, sa, which, filter, pErrorCode); } U_CFUNC void ucnv_MBCSGetUnicodeSetForUnicode(const UConverterSharedData *sharedData, const USetAdder *sa, UConverterUnicodeSet which, UErrorCode *pErrorCode) { ucnv_MBCSGetFilteredUnicodeSetForUnicode( sharedData, sa, which, sharedData->mbcs.outputType==MBCS_OUTPUT_DBCS_ONLY ? UCNV_SET_FILTER_DBCS_ONLY : UCNV_SET_FILTER_NONE, pErrorCode); } static void ucnv_MBCSGetUnicodeSet(const UConverter *cnv, const USetAdder *sa, UConverterUnicodeSet which, UErrorCode *pErrorCode) { if(cnv->options&_MBCS_OPTION_GB18030) { sa->addRange(sa->set, 0, 0xd7ff); sa->addRange(sa->set, 0xe000, 0x10ffff); } else { ucnv_MBCSGetUnicodeSetForUnicode(cnv->sharedData, sa, which, pErrorCode); } } /* conversion extensions for input not in the main table -------------------- */ /* * Hardcoded extension handling for GB 18030. * Definition of LINEAR macros and gb18030Ranges see near the beginning of the file. * * In the future, conversion extensions may handle m:n mappings and delta tables, * see http://source.icu-project.org/repos/icu/icuhtml/trunk/design/conversion/conversion_extensions.html * * If an input character cannot be mapped, then these functions set an error * code. The framework will then call the callback function. */ /* * @return if(U_FAILURE) return the code point for cnv->fromUChar32 * else return 0 after output has been written to the target */ static UChar32 _extFromU(UConverter *cnv, const UConverterSharedData *sharedData, UChar32 cp, const UChar **source, const UChar *sourceLimit, uint8_t **target, const uint8_t *targetLimit, int32_t **offsets, int32_t sourceIndex, UBool flush, UErrorCode *pErrorCode) { const int32_t *cx; cnv->useSubChar1=FALSE; if( (cx=sharedData->mbcs.extIndexes)!=NULL && ucnv_extInitialMatchFromU( cnv, cx, cp, source, sourceLimit, (char **)target, (char *)targetLimit, offsets, sourceIndex, flush, pErrorCode) ) { return 0; /* an extension mapping handled the input */ } /* GB 18030 */ if((cnv->options&_MBCS_OPTION_GB18030)!=0) { const uint32_t *range; int32_t i; range=gb18030Ranges[0]; for(i=0; i<UPRV_LENGTHOF(gb18030Ranges); range+=4, ++i) { if(range[0]<=(uint32_t)cp && (uint32_t)cp<=range[1]) { /* found the Unicode code point, output the four-byte sequence for it */ uint32_t linear; char bytes[4]; /* get the linear value of the first GB 18030 code in this range */ linear=range[2]-LINEAR_18030_BASE; /* add the offset from the beginning of the range */ linear+=((uint32_t)cp-range[0]); /* turn this into a four-byte sequence */ bytes[3]=(char)(0x30+linear%10); linear/=10; bytes[2]=(char)(0x81+linear%126); linear/=126; bytes[1]=(char)(0x30+linear%10); linear/=10; bytes[0]=(char)(0x81+linear); /* output this sequence */ ucnv_fromUWriteBytes(cnv, bytes, 4, (char **)target, (char *)targetLimit, offsets, sourceIndex, pErrorCode); return 0; } } } /* no mapping */ *pErrorCode=U_INVALID_CHAR_FOUND; return cp; } /* * Input sequence: cnv->toUBytes[0..length[ * @return if(U_FAILURE) return the length (toULength, byteIndex) for the input * else return 0 after output has been written to the target */ static int8_t _extToU(UConverter *cnv, const UConverterSharedData *sharedData, int8_t length, const uint8_t **source, const uint8_t *sourceLimit, UChar **target, const UChar *targetLimit, int32_t **offsets, int32_t sourceIndex, UBool flush, UErrorCode *pErrorCode) { const int32_t *cx; if( (cx=sharedData->mbcs.extIndexes)!=NULL && ucnv_extInitialMatchToU( cnv, cx, length, (const char **)source, (const char *)sourceLimit, target, targetLimit, offsets, sourceIndex, flush, pErrorCode) ) { return 0; /* an extension mapping handled the input */ } /* GB 18030 */ if(length==4 && (cnv->options&_MBCS_OPTION_GB18030)!=0) { const uint32_t *range; uint32_t linear; int32_t i; linear=LINEAR_18030(cnv->toUBytes[0], cnv->toUBytes[1], cnv->toUBytes[2], cnv->toUBytes[3]); range=gb18030Ranges[0]; for(i=0; i<UPRV_LENGTHOF(gb18030Ranges); range+=4, ++i) { if(range[2]<=linear && linear<=range[3]) { /* found the sequence, output the Unicode code point for it */ *pErrorCode=U_ZERO_ERROR; /* add the linear difference between the input and start sequences to the start code point */ linear=range[0]+(linear-range[2]); /* output this code point */ ucnv_toUWriteCodePoint(cnv, linear, target, targetLimit, offsets, sourceIndex, pErrorCode); return 0; } } } /* no mapping */ *pErrorCode=U_INVALID_CHAR_FOUND; return length; } /* EBCDIC swap LF<->NL ------------------------------------------------------ */ /* * This code modifies a standard EBCDIC<->Unicode mapping table for * OS/390 (z/OS) Unix System Services (Open Edition). * The difference is in the mapping of Line Feed and New Line control codes: * Standard EBCDIC maps * * <U000A> \x25 |0 * <U0085> \x15 |0 * * but OS/390 USS EBCDIC swaps the control codes for LF and NL, * mapping * * <U000A> \x15 |0 * <U0085> \x25 |0 * * This code modifies a loaded standard EBCDIC<->Unicode mapping table * by copying it into allocated memory and swapping the LF and NL values. * It allows to support the same EBCDIC charset in both versions without * duplicating the entire installed table. */ /* standard EBCDIC codes */ #define EBCDIC_LF 0x25 #define EBCDIC_NL 0x15 /* standard EBCDIC codes with roundtrip flag as stored in Unicode-to-single-byte tables */ #define EBCDIC_RT_LF 0xf25 #define EBCDIC_RT_NL 0xf15 /* Unicode code points */ #define U_LF 0x0a #define U_NL 0x85 static UBool _EBCDICSwapLFNL(UConverterSharedData *sharedData, UErrorCode *pErrorCode) { UConverterMBCSTable *mbcsTable; const uint16_t *table, *results; const uint8_t *bytes; int32_t (*newStateTable)[256]; uint16_t *newResults; uint8_t *p; char *name; uint32_t stage2Entry; uint32_t size, sizeofFromUBytes; mbcsTable=&sharedData->mbcs; table=mbcsTable->fromUnicodeTable; bytes=mbcsTable->fromUnicodeBytes; results=(const uint16_t *)bytes; /* * Check that this is an EBCDIC table with SBCS portion - * SBCS or EBCDIC_STATEFUL with standard EBCDIC LF and NL mappings. * * If not, ignore the option. Options are always ignored if they do not apply. */ if(!( (mbcsTable->outputType==MBCS_OUTPUT_1 || mbcsTable->outputType==MBCS_OUTPUT_2_SISO) && mbcsTable->stateTable[0][EBCDIC_LF]==MBCS_ENTRY_FINAL(0, MBCS_STATE_VALID_DIRECT_16, U_LF) && mbcsTable->stateTable[0][EBCDIC_NL]==MBCS_ENTRY_FINAL(0, MBCS_STATE_VALID_DIRECT_16, U_NL) )) { return FALSE; } if(mbcsTable->outputType==MBCS_OUTPUT_1) { if(!( EBCDIC_RT_LF==MBCS_SINGLE_RESULT_FROM_U(table, results, U_LF) && EBCDIC_RT_NL==MBCS_SINGLE_RESULT_FROM_U(table, results, U_NL) )) { return FALSE; } } else /* MBCS_OUTPUT_2_SISO */ { stage2Entry=MBCS_STAGE_2_FROM_U(table, U_LF); if(!( MBCS_FROM_U_IS_ROUNDTRIP(stage2Entry, U_LF)!=0 && EBCDIC_LF==MBCS_VALUE_2_FROM_STAGE_2(bytes, stage2Entry, U_LF) )) { return FALSE; } stage2Entry=MBCS_STAGE_2_FROM_U(table, U_NL); if(!( MBCS_FROM_U_IS_ROUNDTRIP(stage2Entry, U_NL)!=0 && EBCDIC_NL==MBCS_VALUE_2_FROM_STAGE_2(bytes, stage2Entry, U_NL) )) { return FALSE; } } if(mbcsTable->fromUBytesLength>0) { /* * We _know_ the number of bytes in the fromUnicodeBytes array * starting with header.version 4.1. */ sizeofFromUBytes=mbcsTable->fromUBytesLength; } else { /* * Otherwise: * There used to be code to enumerate the fromUnicode * trie and find the highest entry, but it was removed in ICU 3.2 * because it was not tested and caused a low code coverage number. * See Jitterbug 3674. * This affects only some .cnv file formats with a header.version * below 4.1, and only when swaplfnl is requested. * * ucnvmbcs.c revision 1.99 is the last one with the * ucnv_MBCSSizeofFromUBytes() function. */ *pErrorCode=U_INVALID_FORMAT_ERROR; return FALSE; } /* * The table has an appropriate format. * Allocate and build * - a modified to-Unicode state table * - a modified from-Unicode output array * - a converter name string with the swap option appended */ size= mbcsTable->countStates*1024+ sizeofFromUBytes+ UCNV_MAX_CONVERTER_NAME_LENGTH+20; p=(uint8_t *)uprv_malloc(size); if(p==NULL) { *pErrorCode=U_MEMORY_ALLOCATION_ERROR; return FALSE; } /* copy and modify the to-Unicode state table */ newStateTable=(int32_t (*)[256])p; uprv_memcpy(newStateTable, mbcsTable->stateTable, mbcsTable->countStates*1024); newStateTable[0][EBCDIC_LF]=MBCS_ENTRY_FINAL(0, MBCS_STATE_VALID_DIRECT_16, U_NL); newStateTable[0][EBCDIC_NL]=MBCS_ENTRY_FINAL(0, MBCS_STATE_VALID_DIRECT_16, U_LF); /* copy and modify the from-Unicode result table */ newResults=(uint16_t *)newStateTable[mbcsTable->countStates]; uprv_memcpy(newResults, bytes, sizeofFromUBytes); /* conveniently, the table access macros work on the left side of expressions */ if(mbcsTable->outputType==MBCS_OUTPUT_1) { MBCS_SINGLE_RESULT_FROM_U(table, newResults, U_LF)=EBCDIC_RT_NL; MBCS_SINGLE_RESULT_FROM_U(table, newResults, U_NL)=EBCDIC_RT_LF; } else /* MBCS_OUTPUT_2_SISO */ { stage2Entry=MBCS_STAGE_2_FROM_U(table, U_LF); MBCS_VALUE_2_FROM_STAGE_2(newResults, stage2Entry, U_LF)=EBCDIC_NL; stage2Entry=MBCS_STAGE_2_FROM_U(table, U_NL); MBCS_VALUE_2_FROM_STAGE_2(newResults, stage2Entry, U_NL)=EBCDIC_LF; } /* set the canonical converter name */ name=(char *)newResults+sizeofFromUBytes; uprv_strcpy(name, sharedData->staticData->name); uprv_strcat(name, UCNV_SWAP_LFNL_OPTION_STRING); /* set the pointers */ umtx_lock(NULL); if(mbcsTable->swapLFNLStateTable==NULL) { mbcsTable->swapLFNLStateTable=newStateTable; mbcsTable->swapLFNLFromUnicodeBytes=(uint8_t *)newResults; mbcsTable->swapLFNLName=name; newStateTable=NULL; } umtx_unlock(NULL); /* release the allocated memory if another thread beat us to it */ if(newStateTable!=NULL) { uprv_free(newStateTable); } return TRUE; } /* reconstitute omitted fromUnicode data ------------------------------------ */ /* for details, compare with genmbcs.c MBCSAddFromUnicode() and transformEUC() */ static UBool U_CALLCONV writeStage3Roundtrip(const void *context, uint32_t value, UChar32 codePoints[32]) { UConverterMBCSTable *mbcsTable=(UConverterMBCSTable *)context; const uint16_t *table; uint32_t *stage2; uint8_t *bytes, *p; UChar32 c; int32_t i, st3; table=mbcsTable->fromUnicodeTable; bytes=(uint8_t *)mbcsTable->fromUnicodeBytes; /* for EUC outputTypes, modify the value like genmbcs.c's transformEUC() */ switch(mbcsTable->outputType) { case MBCS_OUTPUT_3_EUC: if(value<=0xffff) { /* short sequences are stored directly */ /* code set 0 or 1 */ } else if(value<=0x8effff) { /* code set 2 */ value&=0x7fff; } else /* first byte is 0x8f */ { /* code set 3 */ value&=0xff7f; } break; case MBCS_OUTPUT_4_EUC: if(value<=0xffffff) { /* short sequences are stored directly */ /* code set 0 or 1 */ } else if(value<=0x8effffff) { /* code set 2 */ value&=0x7fffff; } else /* first byte is 0x8f */ { /* code set 3 */ value&=0xff7fff; } break; default: break; } for(i=0; i<=0x1f; ++value, ++i) { c=codePoints[i]; if(c<0) { continue; } /* locate the stage 2 & 3 data */ stage2=((uint32_t *)table)+table[c>>10]+((c>>4)&0x3f); p=bytes; st3=(int32_t)(uint16_t)*stage2*16+(c&0xf); /* write the codepage bytes into stage 3 */ switch(mbcsTable->outputType) { case MBCS_OUTPUT_3: case MBCS_OUTPUT_4_EUC: p+=st3*3; p[0]=(uint8_t)(value>>16); p[1]=(uint8_t)(value>>8); p[2]=(uint8_t)value; break; case MBCS_OUTPUT_4: ((uint32_t *)p)[st3]=value; break; default: /* 2 bytes per character */ ((uint16_t *)p)[st3]=(uint16_t)value; break; } /* set the roundtrip flag */ *stage2|=(1UL<<(16+(c&0xf))); } return TRUE; } static void reconstituteData(UConverterMBCSTable *mbcsTable, uint32_t stage1Length, uint32_t stage2Length, uint32_t fullStage2Length, /* lengths are numbers of units, not bytes */ UErrorCode *pErrorCode) { uint16_t *stage1; uint32_t *stage2; uint32_t dataLength=stage1Length*2+fullStage2Length*4+mbcsTable->fromUBytesLength; mbcsTable->reconstitutedData=(uint8_t *)uprv_malloc(dataLength); if(mbcsTable->reconstitutedData==NULL) { *pErrorCode=U_MEMORY_ALLOCATION_ERROR; return; } uprv_memset(mbcsTable->reconstitutedData, 0, dataLength); /* copy existing data and reroute the pointers */ stage1=(uint16_t *)mbcsTable->reconstitutedData; uprv_memcpy(stage1, mbcsTable->fromUnicodeTable, stage1Length*2); stage2=(uint32_t *)(stage1+stage1Length); uprv_memcpy(stage2+(fullStage2Length-stage2Length), mbcsTable->fromUnicodeTable+stage1Length, stage2Length*4); mbcsTable->fromUnicodeTable=stage1; mbcsTable->fromUnicodeBytes=(uint8_t *)(stage2+fullStage2Length); /* indexes into stage 2 count from the bottom of the fromUnicodeTable */ stage2=(uint32_t *)stage1; /* reconstitute the initial part of stage 2 from the mbcsIndex */ { int32_t stageUTF8Length=((int32_t)mbcsTable->maxFastUChar+1)>>6; int32_t stageUTF8Index=0; int32_t st1, st2, st3, i; for(st1=0; stageUTF8Index<stageUTF8Length; ++st1) { st2=stage1[st1]; if(st2!=(int32_t)stage1Length/2) { /* each stage 2 block has 64 entries corresponding to 16 entries in the mbcsIndex */ for(i=0; i<16; ++i) { st3=mbcsTable->mbcsIndex[stageUTF8Index++]; if(st3!=0) { /* an stage 2 entry's index is per stage 3 16-block, not per stage 3 entry */ st3>>=4; /* * 4 stage 2 entries point to 4 consecutive stage 3 16-blocks which are * allocated together as a single 64-block for access from the mbcsIndex */ stage2[st2++]=st3++; stage2[st2++]=st3++; stage2[st2++]=st3++; stage2[st2++]=st3; } else { /* no stage 3 block, skip */ st2+=4; } } } else { /* no stage 2 block, skip */ stageUTF8Index+=16; } } } /* reconstitute fromUnicodeBytes with roundtrips from toUnicode data */ ucnv_MBCSEnumToUnicode(mbcsTable, writeStage3Roundtrip, mbcsTable, pErrorCode); } /* MBCS setup functions ----------------------------------------------------- */ static void ucnv_MBCSLoad(UConverterSharedData *sharedData, UConverterLoadArgs *pArgs, const uint8_t *raw, UErrorCode *pErrorCode) { UDataInfo info; UConverterMBCSTable *mbcsTable=&sharedData->mbcs; _MBCSHeader *header=(_MBCSHeader *)raw; uint32_t offset; uint32_t headerLength; UBool noFromU=FALSE; if(header->version[0]==4) { headerLength=MBCS_HEADER_V4_LENGTH; } else if(header->version[0]==5 && header->version[1]>=3 && (header->options&MBCS_OPT_UNKNOWN_INCOMPATIBLE_MASK)==0) { headerLength=header->options&MBCS_OPT_LENGTH_MASK; noFromU=(UBool)((header->options&MBCS_OPT_NO_FROM_U)!=0); } else { *pErrorCode=U_INVALID_TABLE_FORMAT; return; } mbcsTable->outputType=(uint8_t)header->flags; if(noFromU && mbcsTable->outputType==MBCS_OUTPUT_1) { *pErrorCode=U_INVALID_TABLE_FORMAT; return; } /* extension data, header version 4.2 and higher */ offset=header->flags>>8; if(offset!=0) { mbcsTable->extIndexes=(const int32_t *)(raw+offset); } if(mbcsTable->outputType==MBCS_OUTPUT_EXT_ONLY) { UConverterLoadArgs args=UCNV_LOAD_ARGS_INITIALIZER; UConverterSharedData *baseSharedData; const int32_t *extIndexes; const char *baseName; /* extension-only file, load the base table and set values appropriately */ if((extIndexes=mbcsTable->extIndexes)==NULL) { /* extension-only file without extension */ *pErrorCode=U_INVALID_TABLE_FORMAT; return; } if(pArgs->nestedLoads!=1) { /* an extension table must not be loaded as a base table */ *pErrorCode=U_INVALID_TABLE_FILE; return; } /* load the base table */ baseName=(const char *)header+headerLength*4; if(0==uprv_strcmp(baseName, sharedData->staticData->name)) { /* forbid loading this same extension-only file */ *pErrorCode=U_INVALID_TABLE_FORMAT; return; } /* TODO parse package name out of the prefix of the base name in the extension .cnv file? */ args.size=sizeof(UConverterLoadArgs); args.nestedLoads=2; args.onlyTestIsLoadable=pArgs->onlyTestIsLoadable; args.reserved=pArgs->reserved; args.options=pArgs->options; args.pkg=pArgs->pkg; args.name=baseName; baseSharedData=ucnv_load(&args, pErrorCode); if(U_FAILURE(*pErrorCode)) { return; } if( baseSharedData->staticData->conversionType!=UCNV_MBCS || baseSharedData->mbcs.baseSharedData!=NULL ) { ucnv_unload(baseSharedData); *pErrorCode=U_INVALID_TABLE_FORMAT; return; } if(pArgs->onlyTestIsLoadable) { /* * Exit as soon as we know that we can load the converter * and the format is valid and supported. * The worst that can happen in the following code is a memory * allocation error. */ ucnv_unload(baseSharedData); return; } /* copy the base table data */ uprv_memcpy(mbcsTable, &baseSharedData->mbcs, sizeof(UConverterMBCSTable)); /* overwrite values with relevant ones for the extension converter */ mbcsTable->baseSharedData=baseSharedData; mbcsTable->extIndexes=extIndexes; /* * It would be possible to share the swapLFNL data with a base converter, * but the generated name would have to be different, and the memory * would have to be free'd only once. * It is easier to just create the data for the extension converter * separately when it is requested. */ mbcsTable->swapLFNLStateTable=NULL; mbcsTable->swapLFNLFromUnicodeBytes=NULL; mbcsTable->swapLFNLName=NULL; /* * The reconstitutedData must be deleted only when the base converter * is unloaded. */ mbcsTable->reconstitutedData=NULL; /* * Set a special, runtime-only outputType if the extension converter * is a DBCS version of a base converter that also maps single bytes. */ if( sharedData->staticData->conversionType==UCNV_DBCS || (sharedData->staticData->conversionType==UCNV_MBCS && sharedData->staticData->minBytesPerChar>=2) ) { if(baseSharedData->mbcs.outputType==MBCS_OUTPUT_2_SISO) { /* the base converter is SI/SO-stateful */ int32_t entry; /* get the dbcs state from the state table entry for SO=0x0e */ entry=mbcsTable->stateTable[0][0xe]; if( MBCS_ENTRY_IS_FINAL(entry) && MBCS_ENTRY_FINAL_ACTION(entry)==MBCS_STATE_CHANGE_ONLY && MBCS_ENTRY_FINAL_STATE(entry)!=0 ) { mbcsTable->dbcsOnlyState=(uint8_t)MBCS_ENTRY_FINAL_STATE(entry); mbcsTable->outputType=MBCS_OUTPUT_DBCS_ONLY; } } else if( baseSharedData->staticData->conversionType==UCNV_MBCS && baseSharedData->staticData->minBytesPerChar==1 && baseSharedData->staticData->maxBytesPerChar==2 && mbcsTable->countStates<=127 ) { /* non-stateful base converter, need to modify the state table */ int32_t (*newStateTable)[256]; int32_t *state; int32_t i, count; /* allocate a new state table and copy the base state table contents */ count=mbcsTable->countStates; newStateTable=(int32_t (*)[256])uprv_malloc((count+1)*1024); if(newStateTable==NULL) { ucnv_unload(baseSharedData); *pErrorCode=U_MEMORY_ALLOCATION_ERROR; return; } uprv_memcpy(newStateTable, mbcsTable->stateTable, count*1024); /* change all final single-byte entries to go to a new all-illegal state */ state=newStateTable[0]; for(i=0; i<256; ++i) { if(MBCS_ENTRY_IS_FINAL(state[i])) { state[i]=MBCS_ENTRY_TRANSITION(count, 0); } } /* build the new all-illegal state */ state=newStateTable[count]; for(i=0; i<256; ++i) { state[i]=MBCS_ENTRY_FINAL(0, MBCS_STATE_ILLEGAL, 0); } mbcsTable->stateTable=(const int32_t (*)[256])newStateTable; mbcsTable->countStates=(uint8_t)(count+1); mbcsTable->stateTableOwned=TRUE; mbcsTable->outputType=MBCS_OUTPUT_DBCS_ONLY; } } /* * unlike below for files with base tables, do not get the unicodeMask * from the sharedData; instead, use the base table's unicodeMask, * which we copied in the memcpy above; * this is necessary because the static data unicodeMask, especially * the UCNV_HAS_SUPPLEMENTARY flag, is part of the base table data */ } else { /* conversion file with a base table; an additional extension table is optional */ /* make sure that the output type is known */ switch(mbcsTable->outputType) { case MBCS_OUTPUT_1: case MBCS_OUTPUT_2: case MBCS_OUTPUT_3: case MBCS_OUTPUT_4: case MBCS_OUTPUT_3_EUC: case MBCS_OUTPUT_4_EUC: case MBCS_OUTPUT_2_SISO: /* OK */ break; default: *pErrorCode=U_INVALID_TABLE_FORMAT; return; } if(pArgs->onlyTestIsLoadable) { /* * Exit as soon as we know that we can load the converter * and the format is valid and supported. * The worst that can happen in the following code is a memory * allocation error. */ return; } mbcsTable->countStates=(uint8_t)header->countStates; mbcsTable->countToUFallbacks=header->countToUFallbacks; mbcsTable->stateTable=(const int32_t (*)[256])(raw+headerLength*4); mbcsTable->toUFallbacks=(const _MBCSToUFallback *)(mbcsTable->stateTable+header->countStates); mbcsTable->unicodeCodeUnits=(const uint16_t *)(raw+header->offsetToUCodeUnits); mbcsTable->fromUnicodeTable=(const uint16_t *)(raw+header->offsetFromUTable); mbcsTable->fromUnicodeBytes=(const uint8_t *)(raw+header->offsetFromUBytes); mbcsTable->fromUBytesLength=header->fromUBytesLength; /* * converter versions 6.1 and up contain a unicodeMask that is * used here to select the most efficient function implementations */ info.size=sizeof(UDataInfo); udata_getInfo((UDataMemory *)sharedData->dataMemory, &info); if(info.formatVersion[0]>6 || (info.formatVersion[0]==6 && info.formatVersion[1]>=1)) { /* mask off possible future extensions to be safe */ mbcsTable->unicodeMask=(uint8_t)(sharedData->staticData->unicodeMask&3); } else { /* for older versions, assume worst case: contains anything possible (prevent over-optimizations) */ mbcsTable->unicodeMask=UCNV_HAS_SUPPLEMENTARY|UCNV_HAS_SURROGATES; } /* * _MBCSHeader.version 4.3 adds utf8Friendly data structures. * Check for the header version, SBCS vs. MBCS, and for whether the * data structures are optimized for code points as high as what the * runtime code is designed for. * The implementation does not handle mapping tables with entries for * unpaired surrogates. */ if( header->version[1]>=3 && (mbcsTable->unicodeMask&UCNV_HAS_SURROGATES)==0 && (mbcsTable->countStates==1 ? (header->version[2]>=(SBCS_FAST_MAX>>8)) : (header->version[2]>=(MBCS_FAST_MAX>>8)) ) ) { mbcsTable->utf8Friendly=TRUE; if(mbcsTable->countStates==1) { /* * SBCS: Stage 3 is allocated in 64-entry blocks for U+0000..SBCS_FAST_MAX or higher. * Build a table with indexes to each block, to be used instead of * the regular stage 1/2 table. */ int32_t i; for(i=0; i<(SBCS_FAST_LIMIT>>6); ++i) { mbcsTable->sbcsIndex[i]=mbcsTable->fromUnicodeTable[mbcsTable->fromUnicodeTable[i>>4]+((i<<2)&0x3c)]; } /* set SBCS_FAST_MAX to reflect the reach of sbcsIndex[] even if header->version[2]>(SBCS_FAST_MAX>>8) */ mbcsTable->maxFastUChar=SBCS_FAST_MAX; } else { /* * MBCS: Stage 3 is allocated in 64-entry blocks for U+0000..MBCS_FAST_MAX or higher. * The .cnv file is prebuilt with an additional stage table with indexes * to each block. */ mbcsTable->mbcsIndex=(const uint16_t *) (mbcsTable->fromUnicodeBytes+ (noFromU ? 0 : mbcsTable->fromUBytesLength)); mbcsTable->maxFastUChar=(((UChar)header->version[2])<<8)|0xff; } } /* calculate a bit set of 4 ASCII characters per bit that round-trip to ASCII bytes */ { uint32_t asciiRoundtrips=0xffffffff; int32_t i; for(i=0; i<0x80; ++i) { if(mbcsTable->stateTable[0][i]!=MBCS_ENTRY_FINAL(0, MBCS_STATE_VALID_DIRECT_16, i)) { asciiRoundtrips&=~((uint32_t)1<<(i>>2)); } } mbcsTable->asciiRoundtrips=asciiRoundtrips; } if(noFromU) { uint32_t stage1Length= mbcsTable->unicodeMask&UCNV_HAS_SUPPLEMENTARY ? 0x440 : 0x40; uint32_t stage2Length= (header->offsetFromUBytes-header->offsetFromUTable)/4- stage1Length/2; reconstituteData(mbcsTable, stage1Length, stage2Length, header->fullStage2Length, pErrorCode); } } /* Set the impl pointer here so that it is set for both extension-only and base tables. */ if(mbcsTable->utf8Friendly) { if(mbcsTable->countStates==1) { sharedData->impl=&_SBCSUTF8Impl; } else { if(mbcsTable->outputType==MBCS_OUTPUT_2) { sharedData->impl=&_DBCSUTF8Impl; } } } if(mbcsTable->outputType==MBCS_OUTPUT_DBCS_ONLY || mbcsTable->outputType==MBCS_OUTPUT_2_SISO) { /* * MBCS_OUTPUT_DBCS_ONLY: No SBCS mappings, therefore ASCII does not roundtrip. * MBCS_OUTPUT_2_SISO: Bypass the ASCII fastpath to handle prevLength correctly. */ mbcsTable->asciiRoundtrips=0; } } static void ucnv_MBCSUnload(UConverterSharedData *sharedData) { UConverterMBCSTable *mbcsTable=&sharedData->mbcs; if(mbcsTable->swapLFNLStateTable!=NULL) { uprv_free(mbcsTable->swapLFNLStateTable); } if(mbcsTable->stateTableOwned) { uprv_free((void *)mbcsTable->stateTable); } if(mbcsTable->baseSharedData!=NULL) { ucnv_unload(mbcsTable->baseSharedData); } if(mbcsTable->reconstitutedData!=NULL) { uprv_free(mbcsTable->reconstitutedData); } } static void ucnv_MBCSOpen(UConverter *cnv, UConverterLoadArgs *pArgs, UErrorCode *pErrorCode) { UConverterMBCSTable *mbcsTable; const int32_t *extIndexes; uint8_t outputType; int8_t maxBytesPerUChar; if(pArgs->onlyTestIsLoadable) { return; } mbcsTable=&cnv->sharedData->mbcs; outputType=mbcsTable->outputType; if(outputType==MBCS_OUTPUT_DBCS_ONLY) { /* the swaplfnl option does not apply, remove it */ cnv->options=pArgs->options&=~UCNV_OPTION_SWAP_LFNL; } if((pArgs->options&UCNV_OPTION_SWAP_LFNL)!=0) { /* do this because double-checked locking is broken */ UBool isCached; umtx_lock(NULL); isCached=mbcsTable->swapLFNLStateTable!=NULL; umtx_unlock(NULL); if(!isCached) { if(!_EBCDICSwapLFNL(cnv->sharedData, pErrorCode)) { if(U_FAILURE(*pErrorCode)) { return; /* something went wrong */ } /* the option does not apply, remove it */ cnv->options=pArgs->options&=~UCNV_OPTION_SWAP_LFNL; } } } if(uprv_strstr(pArgs->name, "18030")!=NULL) { if(uprv_strstr(pArgs->name, "gb18030")!=NULL || uprv_strstr(pArgs->name, "GB18030")!=NULL) { /* set a flag for GB 18030 mode, which changes the callback behavior */ cnv->options|=_MBCS_OPTION_GB18030; } } else if((uprv_strstr(pArgs->name, "KEIS")!=NULL) || (uprv_strstr(pArgs->name, "keis")!=NULL)) { /* set a flag for KEIS converter, which changes the SI/SO character sequence */ cnv->options|=_MBCS_OPTION_KEIS; } else if((uprv_strstr(pArgs->name, "JEF")!=NULL) || (uprv_strstr(pArgs->name, "jef")!=NULL)) { /* set a flag for JEF converter, which changes the SI/SO character sequence */ cnv->options|=_MBCS_OPTION_JEF; } else if((uprv_strstr(pArgs->name, "JIPS")!=NULL) || (uprv_strstr(pArgs->name, "jips")!=NULL)) { /* set a flag for JIPS converter, which changes the SI/SO character sequence */ cnv->options|=_MBCS_OPTION_JIPS; } /* fix maxBytesPerUChar depending on outputType and options etc. */ if(outputType==MBCS_OUTPUT_2_SISO) { cnv->maxBytesPerUChar=3; /* SO+DBCS */ } extIndexes=mbcsTable->extIndexes; if(extIndexes!=NULL) { maxBytesPerUChar=(int8_t)UCNV_GET_MAX_BYTES_PER_UCHAR(extIndexes); if(outputType==MBCS_OUTPUT_2_SISO) { ++maxBytesPerUChar; /* SO + multiple DBCS */ } if(maxBytesPerUChar>cnv->maxBytesPerUChar) { cnv->maxBytesPerUChar=maxBytesPerUChar; } } #if 0 /* * documentation of UConverter fields used for status * all of these fields are (re)set to 0 by ucnv_bld.c and ucnv_reset() */ /* toUnicode */ cnv->toUnicodeStatus=0; /* offset */ cnv->mode=0; /* state */ cnv->toULength=0; /* byteIndex */ /* fromUnicode */ cnv->fromUChar32=0; cnv->fromUnicodeStatus=1; /* prevLength */ #endif } static const char * ucnv_MBCSGetName(const UConverter *cnv) { if((cnv->options&UCNV_OPTION_SWAP_LFNL)!=0 && cnv->sharedData->mbcs.swapLFNLName!=NULL) { return cnv->sharedData->mbcs.swapLFNLName; } else { return cnv->sharedData->staticData->name; } } /* MBCS-to-Unicode conversion functions ------------------------------------- */ static UChar32 ucnv_MBCSGetFallback(UConverterMBCSTable *mbcsTable, uint32_t offset) { const _MBCSToUFallback *toUFallbacks; uint32_t i, start, limit; limit=mbcsTable->countToUFallbacks; if(limit>0) { /* do a binary search for the fallback mapping */ toUFallbacks=mbcsTable->toUFallbacks; start=0; while(start<limit-1) { i=(start+limit)/2; if(offset<toUFallbacks[i].offset) { limit=i; } else { start=i; } } /* did we really find it? */ if(offset==toUFallbacks[start].offset) { return toUFallbacks[start].codePoint; } } return 0xfffe; } /* This version of ucnv_MBCSToUnicodeWithOffsets() is optimized for single-byte, single-state codepages. */ static void ucnv_MBCSSingleToUnicodeWithOffsets(UConverterToUnicodeArgs *pArgs, UErrorCode *pErrorCode) { UConverter *cnv; const uint8_t *source, *sourceLimit; UChar *target; const UChar *targetLimit; int32_t *offsets; const int32_t (*stateTable)[256]; int32_t sourceIndex; int32_t entry; UChar c; uint8_t action; /* set up the local pointers */ cnv=pArgs->converter; source=(const uint8_t *)pArgs->source; sourceLimit=(const uint8_t *)pArgs->sourceLimit; target=pArgs->target; targetLimit=pArgs->targetLimit; offsets=pArgs->offsets; if((cnv->options&UCNV_OPTION_SWAP_LFNL)!=0) { stateTable=(const int32_t (*)[256])cnv->sharedData->mbcs.swapLFNLStateTable; } else { stateTable=cnv->sharedData->mbcs.stateTable; } /* sourceIndex=-1 if the current character began in the previous buffer */ sourceIndex=0; /* conversion loop */ while(source<sourceLimit) { /* * This following test is to see if available input would overflow the output. * It does not catch output of more than one code unit that * overflows as a result of a surrogate pair or callback output * from the last source byte. * Therefore, those situations also test for overflows and will * then break the loop, too. */ if(target>=targetLimit) { /* target is full */ *pErrorCode=U_BUFFER_OVERFLOW_ERROR; break; } entry=stateTable[0][*source++]; /* MBCS_ENTRY_IS_FINAL(entry) */ /* test the most common case first */ if(MBCS_ENTRY_FINAL_IS_VALID_DIRECT_16(entry)) { /* output BMP code point */ *target++=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); if(offsets!=NULL) { *offsets++=sourceIndex; } /* normal end of action codes: prepare for a new character */ ++sourceIndex; continue; } /* * An if-else-if chain provides more reliable performance for * the most common cases compared to a switch. */ action=(uint8_t)(MBCS_ENTRY_FINAL_ACTION(entry)); if(action==MBCS_STATE_VALID_DIRECT_20 || (action==MBCS_STATE_FALLBACK_DIRECT_20 && UCNV_TO_U_USE_FALLBACK(cnv)) ) { entry=MBCS_ENTRY_FINAL_VALUE(entry); /* output surrogate pair */ *target++=(UChar)(0xd800|(UChar)(entry>>10)); if(offsets!=NULL) { *offsets++=sourceIndex; } c=(UChar)(0xdc00|(UChar)(entry&0x3ff)); if(target<targetLimit) { *target++=c; if(offsets!=NULL) { *offsets++=sourceIndex; } } else { /* target overflow */ cnv->UCharErrorBuffer[0]=c; cnv->UCharErrorBufferLength=1; *pErrorCode=U_BUFFER_OVERFLOW_ERROR; break; } ++sourceIndex; continue; } else if(action==MBCS_STATE_FALLBACK_DIRECT_16) { if(UCNV_TO_U_USE_FALLBACK(cnv)) { /* output BMP code point */ *target++=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); if(offsets!=NULL) { *offsets++=sourceIndex; } ++sourceIndex; continue; } } else if(action==MBCS_STATE_UNASSIGNED) { /* just fall through */ } else if(action==MBCS_STATE_ILLEGAL) { /* callback(illegal) */ *pErrorCode=U_ILLEGAL_CHAR_FOUND; } else { /* reserved, must never occur */ ++sourceIndex; continue; } if(U_FAILURE(*pErrorCode)) { /* callback(illegal) */ break; } else /* unassigned sequences indicated with byteIndex>0 */ { /* try an extension mapping */ pArgs->source=(const char *)source; cnv->toUBytes[0]=*(source-1); cnv->toULength=_extToU(cnv, cnv->sharedData, 1, &source, sourceLimit, &target, targetLimit, &offsets, sourceIndex, pArgs->flush, pErrorCode); sourceIndex+=1+(int32_t)(source-(const uint8_t *)pArgs->source); if(U_FAILURE(*pErrorCode)) { /* not mappable or buffer overflow */ break; } } } /* write back the updated pointers */ pArgs->source=(const char *)source; pArgs->target=target; pArgs->offsets=offsets; } /* * This version of ucnv_MBCSSingleToUnicodeWithOffsets() is optimized for single-byte, single-state codepages * that only map to and from the BMP. * In addition to single-byte optimizations, the offset calculations * become much easier. */ static void ucnv_MBCSSingleToBMPWithOffsets(UConverterToUnicodeArgs *pArgs, UErrorCode *pErrorCode) { UConverter *cnv; const uint8_t *source, *sourceLimit, *lastSource; UChar *target; int32_t targetCapacity, length; int32_t *offsets; const int32_t (*stateTable)[256]; int32_t sourceIndex; int32_t entry; uint8_t action; /* set up the local pointers */ cnv=pArgs->converter; source=(const uint8_t *)pArgs->source; sourceLimit=(const uint8_t *)pArgs->sourceLimit; target=pArgs->target; targetCapacity=(int32_t)(pArgs->targetLimit-pArgs->target); offsets=pArgs->offsets; if((cnv->options&UCNV_OPTION_SWAP_LFNL)!=0) { stateTable=(const int32_t (*)[256])cnv->sharedData->mbcs.swapLFNLStateTable; } else { stateTable=cnv->sharedData->mbcs.stateTable; } /* sourceIndex=-1 if the current character began in the previous buffer */ sourceIndex=0; lastSource=source; /* * since the conversion here is 1:1 UChar:uint8_t, we need only one counter * for the minimum of the sourceLength and targetCapacity */ length=(int32_t)(sourceLimit-source); if(length<targetCapacity) { targetCapacity=length; } #if MBCS_UNROLL_SINGLE_TO_BMP /* unrolling makes it faster on Pentium III/Windows 2000 */ /* unroll the loop with the most common case */ unrolled: if(targetCapacity>=16) { int32_t count, loops, oredEntries; loops=count=targetCapacity>>4; do { oredEntries=entry=stateTable[0][*source++]; *target++=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); oredEntries|=entry=stateTable[0][*source++]; *target++=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); oredEntries|=entry=stateTable[0][*source++]; *target++=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); oredEntries|=entry=stateTable[0][*source++]; *target++=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); oredEntries|=entry=stateTable[0][*source++]; *target++=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); oredEntries|=entry=stateTable[0][*source++]; *target++=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); oredEntries|=entry=stateTable[0][*source++]; *target++=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); oredEntries|=entry=stateTable[0][*source++]; *target++=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); oredEntries|=entry=stateTable[0][*source++]; *target++=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); oredEntries|=entry=stateTable[0][*source++]; *target++=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); oredEntries|=entry=stateTable[0][*source++]; *target++=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); oredEntries|=entry=stateTable[0][*source++]; *target++=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); oredEntries|=entry=stateTable[0][*source++]; *target++=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); oredEntries|=entry=stateTable[0][*source++]; *target++=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); oredEntries|=entry=stateTable[0][*source++]; *target++=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); oredEntries|=entry=stateTable[0][*source++]; *target++=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); /* were all 16 entries really valid? */ if(!MBCS_ENTRY_FINAL_IS_VALID_DIRECT_16(oredEntries)) { /* no, return to the first of these 16 */ source-=16; target-=16; break; } } while(--count>0); count=loops-count; targetCapacity-=16*count; if(offsets!=NULL) { lastSource+=16*count; while(count>0) { *offsets++=sourceIndex++; *offsets++=sourceIndex++; *offsets++=sourceIndex++; *offsets++=sourceIndex++; *offsets++=sourceIndex++; *offsets++=sourceIndex++; *offsets++=sourceIndex++; *offsets++=sourceIndex++; *offsets++=sourceIndex++; *offsets++=sourceIndex++; *offsets++=sourceIndex++; *offsets++=sourceIndex++; *offsets++=sourceIndex++; *offsets++=sourceIndex++; *offsets++=sourceIndex++; *offsets++=sourceIndex++; --count; } } } #endif /* conversion loop */ while(targetCapacity > 0 && source < sourceLimit) { entry=stateTable[0][*source++]; /* MBCS_ENTRY_IS_FINAL(entry) */ /* test the most common case first */ if(MBCS_ENTRY_FINAL_IS_VALID_DIRECT_16(entry)) { /* output BMP code point */ *target++=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); --targetCapacity; continue; } /* * An if-else-if chain provides more reliable performance for * the most common cases compared to a switch. */ action=(uint8_t)(MBCS_ENTRY_FINAL_ACTION(entry)); if(action==MBCS_STATE_FALLBACK_DIRECT_16) { if(UCNV_TO_U_USE_FALLBACK(cnv)) { /* output BMP code point */ *target++=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); --targetCapacity; continue; } } else if(action==MBCS_STATE_UNASSIGNED) { /* just fall through */ } else if(action==MBCS_STATE_ILLEGAL) { /* callback(illegal) */ *pErrorCode=U_ILLEGAL_CHAR_FOUND; } else { /* reserved, must never occur */ continue; } /* set offsets since the start or the last extension */ if(offsets!=NULL) { int32_t count=(int32_t)(source-lastSource); /* predecrement: do not set the offset for the callback-causing character */ while(--count>0) { *offsets++=sourceIndex++; } /* offset and sourceIndex are now set for the current character */ } if(U_FAILURE(*pErrorCode)) { /* callback(illegal) */ break; } else /* unassigned sequences indicated with byteIndex>0 */ { /* try an extension mapping */ lastSource=source; cnv->toUBytes[0]=*(source-1); cnv->toULength=_extToU(cnv, cnv->sharedData, 1, &source, sourceLimit, &target, pArgs->targetLimit, &offsets, sourceIndex, pArgs->flush, pErrorCode); sourceIndex+=1+(int32_t)(source-lastSource); if(U_FAILURE(*pErrorCode)) { /* not mappable or buffer overflow */ break; } /* recalculate the targetCapacity after an extension mapping */ targetCapacity=(int32_t)(pArgs->targetLimit-target); length=(int32_t)(sourceLimit-source); if(length<targetCapacity) { targetCapacity=length; } } #if MBCS_UNROLL_SINGLE_TO_BMP /* unrolling makes it faster on Pentium III/Windows 2000 */ goto unrolled; #endif } if(U_SUCCESS(*pErrorCode) && source<sourceLimit && target>=pArgs->targetLimit) { /* target is full */ *pErrorCode=U_BUFFER_OVERFLOW_ERROR; } /* set offsets since the start or the last callback */ if(offsets!=NULL) { size_t count=source-lastSource; while(count>0) { *offsets++=sourceIndex++; --count; } } /* write back the updated pointers */ pArgs->source=(const char *)source; pArgs->target=target; pArgs->offsets=offsets; } static UBool hasValidTrailBytes(const int32_t (*stateTable)[256], uint8_t state) { const int32_t *row=stateTable[state]; int32_t b, entry; /* First test for final entries in this state for some commonly valid byte values. */ entry=row[0xa1]; if( !MBCS_ENTRY_IS_TRANSITION(entry) && MBCS_ENTRY_FINAL_ACTION(entry)!=MBCS_STATE_ILLEGAL ) { return TRUE; } entry=row[0x41]; if( !MBCS_ENTRY_IS_TRANSITION(entry) && MBCS_ENTRY_FINAL_ACTION(entry)!=MBCS_STATE_ILLEGAL ) { return TRUE; } /* Then test for final entries in this state. */ for(b=0; b<=0xff; ++b) { entry=row[b]; if( !MBCS_ENTRY_IS_TRANSITION(entry) && MBCS_ENTRY_FINAL_ACTION(entry)!=MBCS_STATE_ILLEGAL ) { return TRUE; } } /* Then recurse for transition entries. */ for(b=0; b<=0xff; ++b) { entry=row[b]; if( MBCS_ENTRY_IS_TRANSITION(entry) && hasValidTrailBytes(stateTable, (uint8_t)MBCS_ENTRY_TRANSITION_STATE(entry)) ) { return TRUE; } } return FALSE; } /* * Is byte b a single/lead byte in this state? * Recurse for transition states, because here we don't want to say that * b is a lead byte if all byte sequences that start with b are illegal. */ static UBool isSingleOrLead(const int32_t (*stateTable)[256], uint8_t state, UBool isDBCSOnly, uint8_t b) { const int32_t *row=stateTable[state]; int32_t entry=row[b]; if(MBCS_ENTRY_IS_TRANSITION(entry)) { /* lead byte */ return hasValidTrailBytes(stateTable, (uint8_t)MBCS_ENTRY_TRANSITION_STATE(entry)); } else { uint8_t action=(uint8_t)(MBCS_ENTRY_FINAL_ACTION(entry)); if(action==MBCS_STATE_CHANGE_ONLY && isDBCSOnly) { return FALSE; /* SI/SO are illegal for DBCS-only conversion */ } else { return action!=MBCS_STATE_ILLEGAL; } } } U_CFUNC void ucnv_MBCSToUnicodeWithOffsets(UConverterToUnicodeArgs *pArgs, UErrorCode *pErrorCode) { UConverter *cnv; const uint8_t *source, *sourceLimit; UChar *target; const UChar *targetLimit; int32_t *offsets; const int32_t (*stateTable)[256]; const uint16_t *unicodeCodeUnits; uint32_t offset; uint8_t state; int8_t byteIndex; uint8_t *bytes; int32_t sourceIndex, nextSourceIndex; int32_t entry; UChar c; uint8_t action; /* use optimized function if possible */ cnv=pArgs->converter; if(cnv->preToULength>0) { /* * pass sourceIndex=-1 because we continue from an earlier buffer * in the future, this may change with continuous offsets */ ucnv_extContinueMatchToU(cnv, pArgs, -1, pErrorCode); if(U_FAILURE(*pErrorCode) || cnv->preToULength<0) { return; } } if(cnv->sharedData->mbcs.countStates==1) { if(!(cnv->sharedData->mbcs.unicodeMask&UCNV_HAS_SUPPLEMENTARY)) { ucnv_MBCSSingleToBMPWithOffsets(pArgs, pErrorCode); } else { ucnv_MBCSSingleToUnicodeWithOffsets(pArgs, pErrorCode); } return; } /* set up the local pointers */ source=(const uint8_t *)pArgs->source; sourceLimit=(const uint8_t *)pArgs->sourceLimit; target=pArgs->target; targetLimit=pArgs->targetLimit; offsets=pArgs->offsets; if((cnv->options&UCNV_OPTION_SWAP_LFNL)!=0) { stateTable=(const int32_t (*)[256])cnv->sharedData->mbcs.swapLFNLStateTable; } else { stateTable=cnv->sharedData->mbcs.stateTable; } unicodeCodeUnits=cnv->sharedData->mbcs.unicodeCodeUnits; /* get the converter state from UConverter */ offset=cnv->toUnicodeStatus; byteIndex=cnv->toULength; bytes=cnv->toUBytes; /* * if we are in the SBCS state for a DBCS-only converter, * then load the DBCS state from the MBCS data * (dbcsOnlyState==0 if it is not a DBCS-only converter) */ if((state=(uint8_t)(cnv->mode))==0) { state=cnv->sharedData->mbcs.dbcsOnlyState; } /* sourceIndex=-1 if the current character began in the previous buffer */ sourceIndex=byteIndex==0 ? 0 : -1; nextSourceIndex=0; /* conversion loop */ while(source<sourceLimit) { /* * This following test is to see if available input would overflow the output. * It does not catch output of more than one code unit that * overflows as a result of a surrogate pair or callback output * from the last source byte. * Therefore, those situations also test for overflows and will * then break the loop, too. */ if(target>=targetLimit) { /* target is full */ *pErrorCode=U_BUFFER_OVERFLOW_ERROR; break; } if(byteIndex==0) { /* optimized loop for 1/2-byte input and BMP output */ if(offsets==NULL) { do { entry=stateTable[state][*source]; if(MBCS_ENTRY_IS_TRANSITION(entry)) { state=(uint8_t)MBCS_ENTRY_TRANSITION_STATE(entry); offset=MBCS_ENTRY_TRANSITION_OFFSET(entry); ++source; if( source<sourceLimit && MBCS_ENTRY_IS_FINAL(entry=stateTable[state][*source]) && MBCS_ENTRY_FINAL_ACTION(entry)==MBCS_STATE_VALID_16 && (c=unicodeCodeUnits[offset+MBCS_ENTRY_FINAL_VALUE_16(entry)])<0xfffe ) { ++source; *target++=c; state=(uint8_t)MBCS_ENTRY_FINAL_STATE(entry); /* typically 0 */ offset=0; } else { /* set the state and leave the optimized loop */ bytes[0]=*(source-1); byteIndex=1; break; } } else { if(MBCS_ENTRY_FINAL_IS_VALID_DIRECT_16(entry)) { /* output BMP code point */ ++source; *target++=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); state=(uint8_t)MBCS_ENTRY_FINAL_STATE(entry); /* typically 0 */ } else { /* leave the optimized loop */ break; } } } while(source<sourceLimit && target<targetLimit); } else /* offsets!=NULL */ { do { entry=stateTable[state][*source]; if(MBCS_ENTRY_IS_TRANSITION(entry)) { state=(uint8_t)MBCS_ENTRY_TRANSITION_STATE(entry); offset=MBCS_ENTRY_TRANSITION_OFFSET(entry); ++source; if( source<sourceLimit && MBCS_ENTRY_IS_FINAL(entry=stateTable[state][*source]) && MBCS_ENTRY_FINAL_ACTION(entry)==MBCS_STATE_VALID_16 && (c=unicodeCodeUnits[offset+MBCS_ENTRY_FINAL_VALUE_16(entry)])<0xfffe ) { ++source; *target++=c; if(offsets!=NULL) { *offsets++=sourceIndex; sourceIndex=(nextSourceIndex+=2); } state=(uint8_t)MBCS_ENTRY_FINAL_STATE(entry); /* typically 0 */ offset=0; } else { /* set the state and leave the optimized loop */ ++nextSourceIndex; bytes[0]=*(source-1); byteIndex=1; break; } } else { if(MBCS_ENTRY_FINAL_IS_VALID_DIRECT_16(entry)) { /* output BMP code point */ ++source; *target++=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); if(offsets!=NULL) { *offsets++=sourceIndex; sourceIndex=++nextSourceIndex; } state=(uint8_t)MBCS_ENTRY_FINAL_STATE(entry); /* typically 0 */ } else { /* leave the optimized loop */ break; } } } while(source<sourceLimit && target<targetLimit); } /* * these tests and break statements could be put inside the loop * if C had "break outerLoop" like Java */ if(source>=sourceLimit) { break; } if(target>=targetLimit) { /* target is full */ *pErrorCode=U_BUFFER_OVERFLOW_ERROR; break; } ++nextSourceIndex; bytes[byteIndex++]=*source++; } else /* byteIndex>0 */ { ++nextSourceIndex; entry=stateTable[state][bytes[byteIndex++]=*source++]; } if(MBCS_ENTRY_IS_TRANSITION(entry)) { state=(uint8_t)MBCS_ENTRY_TRANSITION_STATE(entry); offset+=MBCS_ENTRY_TRANSITION_OFFSET(entry); continue; } /* save the previous state for proper extension mapping with SI/SO-stateful converters */ cnv->mode=state; /* set the next state early so that we can reuse the entry variable */ state=(uint8_t)MBCS_ENTRY_FINAL_STATE(entry); /* typically 0 */ /* * An if-else-if chain provides more reliable performance for * the most common cases compared to a switch. */ action=(uint8_t)(MBCS_ENTRY_FINAL_ACTION(entry)); if(action==MBCS_STATE_VALID_16) { offset+=MBCS_ENTRY_FINAL_VALUE_16(entry); c=unicodeCodeUnits[offset]; if(c<0xfffe) { /* output BMP code point */ *target++=c; if(offsets!=NULL) { *offsets++=sourceIndex; } byteIndex=0; } else if(c==0xfffe) { if(UCNV_TO_U_USE_FALLBACK(cnv) && (entry=(int32_t)ucnv_MBCSGetFallback(&cnv->sharedData->mbcs, offset))!=0xfffe) { /* output fallback BMP code point */ *target++=(UChar)entry; if(offsets!=NULL) { *offsets++=sourceIndex; } byteIndex=0; } } else { /* callback(illegal) */ *pErrorCode=U_ILLEGAL_CHAR_FOUND; } } else if(action==MBCS_STATE_VALID_DIRECT_16) { /* output BMP code point */ *target++=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); if(offsets!=NULL) { *offsets++=sourceIndex; } byteIndex=0; } else if(action==MBCS_STATE_VALID_16_PAIR) { offset+=MBCS_ENTRY_FINAL_VALUE_16(entry); c=unicodeCodeUnits[offset++]; if(c<0xd800) { /* output BMP code point below 0xd800 */ *target++=c; if(offsets!=NULL) { *offsets++=sourceIndex; } byteIndex=0; } else if(UCNV_TO_U_USE_FALLBACK(cnv) ? c<=0xdfff : c<=0xdbff) { /* output roundtrip or fallback surrogate pair */ *target++=(UChar)(c&0xdbff); if(offsets!=NULL) { *offsets++=sourceIndex; } byteIndex=0; if(target<targetLimit) { *target++=unicodeCodeUnits[offset]; if(offsets!=NULL) { *offsets++=sourceIndex; } } else { /* target overflow */ cnv->UCharErrorBuffer[0]=unicodeCodeUnits[offset]; cnv->UCharErrorBufferLength=1; *pErrorCode=U_BUFFER_OVERFLOW_ERROR; offset=0; break; } } else if(UCNV_TO_U_USE_FALLBACK(cnv) ? (c&0xfffe)==0xe000 : c==0xe000) { /* output roundtrip BMP code point above 0xd800 or fallback BMP code point */ *target++=unicodeCodeUnits[offset]; if(offsets!=NULL) { *offsets++=sourceIndex; } byteIndex=0; } else if(c==0xffff) { /* callback(illegal) */ *pErrorCode=U_ILLEGAL_CHAR_FOUND; } } else if(action==MBCS_STATE_VALID_DIRECT_20 || (action==MBCS_STATE_FALLBACK_DIRECT_20 && UCNV_TO_U_USE_FALLBACK(cnv)) ) { entry=MBCS_ENTRY_FINAL_VALUE(entry); /* output surrogate pair */ *target++=(UChar)(0xd800|(UChar)(entry>>10)); if(offsets!=NULL) { *offsets++=sourceIndex; } byteIndex=0; c=(UChar)(0xdc00|(UChar)(entry&0x3ff)); if(target<targetLimit) { *target++=c; if(offsets!=NULL) { *offsets++=sourceIndex; } } else { /* target overflow */ cnv->UCharErrorBuffer[0]=c; cnv->UCharErrorBufferLength=1; *pErrorCode=U_BUFFER_OVERFLOW_ERROR; offset=0; break; } } else if(action==MBCS_STATE_CHANGE_ONLY) { /* * This serves as a state change without any output. * It is useful for reading simple stateful encodings, * for example using just Shift-In/Shift-Out codes. * The 21 unused bits may later be used for more sophisticated * state transitions. */ if(cnv->sharedData->mbcs.dbcsOnlyState==0) { byteIndex=0; } else { /* SI/SO are illegal for DBCS-only conversion */ state=(uint8_t)(cnv->mode); /* restore the previous state */ /* callback(illegal) */ *pErrorCode=U_ILLEGAL_CHAR_FOUND; } } else if(action==MBCS_STATE_FALLBACK_DIRECT_16) { if(UCNV_TO_U_USE_FALLBACK(cnv)) { /* output BMP code point */ *target++=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); if(offsets!=NULL) { *offsets++=sourceIndex; } byteIndex=0; } } else if(action==MBCS_STATE_UNASSIGNED) { /* just fall through */ } else if(action==MBCS_STATE_ILLEGAL) { /* callback(illegal) */ *pErrorCode=U_ILLEGAL_CHAR_FOUND; } else { /* reserved, must never occur */ byteIndex=0; } /* end of action codes: prepare for a new character */ offset=0; if(byteIndex==0) { sourceIndex=nextSourceIndex; } else if(U_FAILURE(*pErrorCode)) { /* callback(illegal) */ if(byteIndex>1) { /* * Ticket 5691: consistent illegal sequences: * - We include at least the first byte in the illegal sequence. * - If any of the non-initial bytes could be the start of a character, * we stop the illegal sequence before the first one of those. */ UBool isDBCSOnly=(UBool)(cnv->sharedData->mbcs.dbcsOnlyState!=0); int8_t i; for(i=1; i<byteIndex && !isSingleOrLead(stateTable, state, isDBCSOnly, bytes[i]); ++i) {} if(i<byteIndex) { /* Back out some bytes. */ int8_t backOutDistance=byteIndex-i; int32_t bytesFromThisBuffer=(int32_t)(source-(const uint8_t *)pArgs->source); byteIndex=i; /* length of reported illegal byte sequence */ if(backOutDistance<=bytesFromThisBuffer) { source-=backOutDistance; } else { /* Back out bytes from the previous buffer: Need to replay them. */ cnv->preToULength=(int8_t)(bytesFromThisBuffer-backOutDistance); /* preToULength is negative! */ uprv_memcpy(cnv->preToU, bytes+i, -cnv->preToULength); source=(const uint8_t *)pArgs->source; } } } break; } else /* unassigned sequences indicated with byteIndex>0 */ { /* try an extension mapping */ pArgs->source=(const char *)source; byteIndex=_extToU(cnv, cnv->sharedData, byteIndex, &source, sourceLimit, &target, targetLimit, &offsets, sourceIndex, pArgs->flush, pErrorCode); sourceIndex=nextSourceIndex+=(int32_t)(source-(const uint8_t *)pArgs->source); if(U_FAILURE(*pErrorCode)) { /* not mappable or buffer overflow */ break; } } } /* set the converter state back into UConverter */ cnv->toUnicodeStatus=offset; cnv->mode=state; cnv->toULength=byteIndex; /* write back the updated pointers */ pArgs->source=(const char *)source; pArgs->target=target; pArgs->offsets=offsets; } /* * This version of ucnv_MBCSGetNextUChar() is optimized for single-byte, single-state codepages. * We still need a conversion loop in case we find reserved action codes, which are to be ignored. */ static UChar32 ucnv_MBCSSingleGetNextUChar(UConverterToUnicodeArgs *pArgs, UErrorCode *pErrorCode) { UConverter *cnv; const int32_t (*stateTable)[256]; const uint8_t *source, *sourceLimit; int32_t entry; uint8_t action; /* set up the local pointers */ cnv=pArgs->converter; source=(const uint8_t *)pArgs->source; sourceLimit=(const uint8_t *)pArgs->sourceLimit; if((cnv->options&UCNV_OPTION_SWAP_LFNL)!=0) { stateTable=(const int32_t (*)[256])cnv->sharedData->mbcs.swapLFNLStateTable; } else { stateTable=cnv->sharedData->mbcs.stateTable; } /* conversion loop */ while(source<sourceLimit) { entry=stateTable[0][*source++]; /* MBCS_ENTRY_IS_FINAL(entry) */ /* write back the updated pointer early so that we can return directly */ pArgs->source=(const char *)source; if(MBCS_ENTRY_FINAL_IS_VALID_DIRECT_16(entry)) { /* output BMP code point */ return (UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); } /* * An if-else-if chain provides more reliable performance for * the most common cases compared to a switch. */ action=(uint8_t)(MBCS_ENTRY_FINAL_ACTION(entry)); if( action==MBCS_STATE_VALID_DIRECT_20 || (action==MBCS_STATE_FALLBACK_DIRECT_20 && UCNV_TO_U_USE_FALLBACK(cnv)) ) { /* output supplementary code point */ return (UChar32)(MBCS_ENTRY_FINAL_VALUE(entry)+0x10000); } else if(action==MBCS_STATE_FALLBACK_DIRECT_16) { if(UCNV_TO_U_USE_FALLBACK(cnv)) { /* output BMP code point */ return (UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); } } else if(action==MBCS_STATE_UNASSIGNED) { /* just fall through */ } else if(action==MBCS_STATE_ILLEGAL) { /* callback(illegal) */ *pErrorCode=U_ILLEGAL_CHAR_FOUND; } else { /* reserved, must never occur */ continue; } if(U_FAILURE(*pErrorCode)) { /* callback(illegal) */ break; } else /* unassigned sequence */ { /* defer to the generic implementation */ pArgs->source=(const char *)source-1; return UCNV_GET_NEXT_UCHAR_USE_TO_U; } } /* no output because of empty input or only state changes */ *pErrorCode=U_INDEX_OUTOFBOUNDS_ERROR; return 0xffff; } /* * Version of _MBCSToUnicodeWithOffsets() optimized for single-character * conversion without offset handling. * * When a character does not have a mapping to Unicode, then we return to the * generic ucnv_getNextUChar() code for extension/GB 18030 and error/callback * handling. * We also defer to the generic code in other complicated cases and have them * ultimately handled by _MBCSToUnicodeWithOffsets() itself. * * All normal mappings and errors are handled here. */ static UChar32 ucnv_MBCSGetNextUChar(UConverterToUnicodeArgs *pArgs, UErrorCode *pErrorCode) { UConverter *cnv; const uint8_t *source, *sourceLimit, *lastSource; const int32_t (*stateTable)[256]; const uint16_t *unicodeCodeUnits; uint32_t offset; uint8_t state; int32_t entry; UChar32 c; uint8_t action; /* use optimized function if possible */ cnv=pArgs->converter; if(cnv->preToULength>0) { /* use the generic code in ucnv_getNextUChar() to continue with a partial match */ return UCNV_GET_NEXT_UCHAR_USE_TO_U; } if(cnv->sharedData->mbcs.unicodeMask&UCNV_HAS_SURROGATES) { /* * Using the generic ucnv_getNextUChar() code lets us deal correctly * with the rare case of a codepage that maps single surrogates * without adding the complexity to this already complicated function here. */ return UCNV_GET_NEXT_UCHAR_USE_TO_U; } else if(cnv->sharedData->mbcs.countStates==1) { return ucnv_MBCSSingleGetNextUChar(pArgs, pErrorCode); } /* set up the local pointers */ source=lastSource=(const uint8_t *)pArgs->source; sourceLimit=(const uint8_t *)pArgs->sourceLimit; if((cnv->options&UCNV_OPTION_SWAP_LFNL)!=0) { stateTable=(const int32_t (*)[256])cnv->sharedData->mbcs.swapLFNLStateTable; } else { stateTable=cnv->sharedData->mbcs.stateTable; } unicodeCodeUnits=cnv->sharedData->mbcs.unicodeCodeUnits; /* get the converter state from UConverter */ offset=cnv->toUnicodeStatus; /* * if we are in the SBCS state for a DBCS-only converter, * then load the DBCS state from the MBCS data * (dbcsOnlyState==0 if it is not a DBCS-only converter) */ if((state=(uint8_t)(cnv->mode))==0) { state=cnv->sharedData->mbcs.dbcsOnlyState; } /* conversion loop */ c=U_SENTINEL; while(source<sourceLimit) { entry=stateTable[state][*source++]; if(MBCS_ENTRY_IS_TRANSITION(entry)) { state=(uint8_t)MBCS_ENTRY_TRANSITION_STATE(entry); offset+=MBCS_ENTRY_TRANSITION_OFFSET(entry); /* optimization for 1/2-byte input and BMP output */ if( source<sourceLimit && MBCS_ENTRY_IS_FINAL(entry=stateTable[state][*source]) && MBCS_ENTRY_FINAL_ACTION(entry)==MBCS_STATE_VALID_16 && (c=unicodeCodeUnits[offset+MBCS_ENTRY_FINAL_VALUE_16(entry)])<0xfffe ) { ++source; state=(uint8_t)MBCS_ENTRY_FINAL_STATE(entry); /* typically 0 */ /* output BMP code point */ break; } } else { /* save the previous state for proper extension mapping with SI/SO-stateful converters */ cnv->mode=state; /* set the next state early so that we can reuse the entry variable */ state=(uint8_t)MBCS_ENTRY_FINAL_STATE(entry); /* typically 0 */ /* * An if-else-if chain provides more reliable performance for * the most common cases compared to a switch. */ action=(uint8_t)(MBCS_ENTRY_FINAL_ACTION(entry)); if(action==MBCS_STATE_VALID_DIRECT_16) { /* output BMP code point */ c=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); break; } else if(action==MBCS_STATE_VALID_16) { offset+=MBCS_ENTRY_FINAL_VALUE_16(entry); c=unicodeCodeUnits[offset]; if(c<0xfffe) { /* output BMP code point */ break; } else if(c==0xfffe) { if(UCNV_TO_U_USE_FALLBACK(cnv) && (c=ucnv_MBCSGetFallback(&cnv->sharedData->mbcs, offset))!=0xfffe) { break; } } else { /* callback(illegal) */ *pErrorCode=U_ILLEGAL_CHAR_FOUND; } } else if(action==MBCS_STATE_VALID_16_PAIR) { offset+=MBCS_ENTRY_FINAL_VALUE_16(entry); c=unicodeCodeUnits[offset++]; if(c<0xd800) { /* output BMP code point below 0xd800 */ break; } else if(UCNV_TO_U_USE_FALLBACK(cnv) ? c<=0xdfff : c<=0xdbff) { /* output roundtrip or fallback supplementary code point */ c=((c&0x3ff)<<10)+unicodeCodeUnits[offset]+(0x10000-0xdc00); break; } else if(UCNV_TO_U_USE_FALLBACK(cnv) ? (c&0xfffe)==0xe000 : c==0xe000) { /* output roundtrip BMP code point above 0xd800 or fallback BMP code point */ c=unicodeCodeUnits[offset]; break; } else if(c==0xffff) { /* callback(illegal) */ *pErrorCode=U_ILLEGAL_CHAR_FOUND; } } else if(action==MBCS_STATE_VALID_DIRECT_20 || (action==MBCS_STATE_FALLBACK_DIRECT_20 && UCNV_TO_U_USE_FALLBACK(cnv)) ) { /* output supplementary code point */ c=(UChar32)(MBCS_ENTRY_FINAL_VALUE(entry)+0x10000); break; } else if(action==MBCS_STATE_CHANGE_ONLY) { /* * This serves as a state change without any output. * It is useful for reading simple stateful encodings, * for example using just Shift-In/Shift-Out codes. * The 21 unused bits may later be used for more sophisticated * state transitions. */ if(cnv->sharedData->mbcs.dbcsOnlyState!=0) { /* SI/SO are illegal for DBCS-only conversion */ state=(uint8_t)(cnv->mode); /* restore the previous state */ /* callback(illegal) */ *pErrorCode=U_ILLEGAL_CHAR_FOUND; } } else if(action==MBCS_STATE_FALLBACK_DIRECT_16) { if(UCNV_TO_U_USE_FALLBACK(cnv)) { /* output BMP code point */ c=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); break; } } else if(action==MBCS_STATE_UNASSIGNED) { /* just fall through */ } else if(action==MBCS_STATE_ILLEGAL) { /* callback(illegal) */ *pErrorCode=U_ILLEGAL_CHAR_FOUND; } else { /* reserved (must never occur), or only state change */ offset=0; lastSource=source; continue; } /* end of action codes: prepare for a new character */ offset=0; if(U_FAILURE(*pErrorCode)) { /* callback(illegal) */ break; } else /* unassigned sequence */ { /* defer to the generic implementation */ cnv->toUnicodeStatus=0; cnv->mode=state; pArgs->source=(const char *)lastSource; return UCNV_GET_NEXT_UCHAR_USE_TO_U; } } } if(c<0) { if(U_SUCCESS(*pErrorCode) && source==sourceLimit && lastSource<source) { /* incomplete character byte sequence */ uint8_t *bytes=cnv->toUBytes; cnv->toULength=(int8_t)(source-lastSource); do { *bytes++=*lastSource++; } while(lastSource<source); *pErrorCode=U_TRUNCATED_CHAR_FOUND; } else if(U_FAILURE(*pErrorCode)) { /* callback(illegal) */ /* * Ticket 5691: consistent illegal sequences: * - We include at least the first byte in the illegal sequence. * - If any of the non-initial bytes could be the start of a character, * we stop the illegal sequence before the first one of those. */ UBool isDBCSOnly=(UBool)(cnv->sharedData->mbcs.dbcsOnlyState!=0); uint8_t *bytes=cnv->toUBytes; *bytes++=*lastSource++; /* first byte */ if(lastSource==source) { cnv->toULength=1; } else /* lastSource<source: multi-byte character */ { int8_t i; for(i=1; lastSource<source && !isSingleOrLead(stateTable, state, isDBCSOnly, *lastSource); ++i ) { *bytes++=*lastSource++; } cnv->toULength=i; source=lastSource; } } else { /* no output because of empty input or only state changes */ *pErrorCode=U_INDEX_OUTOFBOUNDS_ERROR; } c=0xffff; } /* set the converter state back into UConverter, ready for a new character */ cnv->toUnicodeStatus=0; cnv->mode=state; /* write back the updated pointer */ pArgs->source=(const char *)source; return c; } #if 0 /* * Code disabled 2002dec09 (ICU 2.4) because it is not currently used in ICU. markus * Removal improves code coverage. */ /** * This version of ucnv_MBCSSimpleGetNextUChar() is optimized for single-byte, single-state codepages. * It does not handle the EBCDIC swaplfnl option (set in UConverter). * It does not handle conversion extensions (_extToU()). */ U_CFUNC UChar32 ucnv_MBCSSingleSimpleGetNextUChar(UConverterSharedData *sharedData, uint8_t b, UBool useFallback) { int32_t entry; uint8_t action; entry=sharedData->mbcs.stateTable[0][b]; /* MBCS_ENTRY_IS_FINAL(entry) */ if(MBCS_ENTRY_FINAL_IS_VALID_DIRECT_16(entry)) { /* output BMP code point */ return (UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); } /* * An if-else-if chain provides more reliable performance for * the most common cases compared to a switch. */ action=(uint8_t)(MBCS_ENTRY_FINAL_ACTION(entry)); if(action==MBCS_STATE_VALID_DIRECT_20) { /* output supplementary code point */ return 0x10000+MBCS_ENTRY_FINAL_VALUE(entry); } else if(action==MBCS_STATE_FALLBACK_DIRECT_16) { if(!TO_U_USE_FALLBACK(useFallback)) { return 0xfffe; } /* output BMP code point */ return (UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); } else if(action==MBCS_STATE_FALLBACK_DIRECT_20) { if(!TO_U_USE_FALLBACK(useFallback)) { return 0xfffe; } /* output supplementary code point */ return 0x10000+MBCS_ENTRY_FINAL_VALUE(entry); } else if(action==MBCS_STATE_UNASSIGNED) { return 0xfffe; } else if(action==MBCS_STATE_ILLEGAL) { return 0xffff; } else { /* reserved, must never occur */ return 0xffff; } } #endif /* * This is a simple version of _MBCSGetNextUChar() that is used * by other converter implementations. * It only returns an "assigned" result if it consumes the entire input. * It does not use state from the converter, nor error codes. * It does not handle the EBCDIC swaplfnl option (set in UConverter). * It handles conversion extensions but not GB 18030. * * Return value: * U+fffe unassigned * U+ffff illegal * otherwise the Unicode code point */ U_CFUNC UChar32 ucnv_MBCSSimpleGetNextUChar(UConverterSharedData *sharedData, const char *source, int32_t length, UBool useFallback) { const int32_t (*stateTable)[256]; const uint16_t *unicodeCodeUnits; uint32_t offset; uint8_t state, action; UChar32 c; int32_t i, entry; if(length<=0) { /* no input at all: "illegal" */ return 0xffff; } #if 0 /* * Code disabled 2002dec09 (ICU 2.4) because it is not currently used in ICU. markus * TODO In future releases, verify that this function is never called for SBCS * conversions, i.e., that sharedData->mbcs.countStates==1 is still true. * Removal improves code coverage. */ /* use optimized function if possible */ if(sharedData->mbcs.countStates==1) { if(length==1) { return ucnv_MBCSSingleSimpleGetNextUChar(sharedData, (uint8_t)*source, useFallback); } else { return 0xffff; /* illegal: more than a single byte for an SBCS converter */ } } #endif /* set up the local pointers */ stateTable=sharedData->mbcs.stateTable; unicodeCodeUnits=sharedData->mbcs.unicodeCodeUnits; /* converter state */ offset=0; state=sharedData->mbcs.dbcsOnlyState; /* conversion loop */ for(i=0;;) { entry=stateTable[state][(uint8_t)source[i++]]; if(MBCS_ENTRY_IS_TRANSITION(entry)) { state=(uint8_t)MBCS_ENTRY_TRANSITION_STATE(entry); offset+=MBCS_ENTRY_TRANSITION_OFFSET(entry); if(i==length) { return 0xffff; /* truncated character */ } } else { /* * An if-else-if chain provides more reliable performance for * the most common cases compared to a switch. */ action=(uint8_t)(MBCS_ENTRY_FINAL_ACTION(entry)); if(action==MBCS_STATE_VALID_16) { offset+=MBCS_ENTRY_FINAL_VALUE_16(entry); c=unicodeCodeUnits[offset]; if(c!=0xfffe) { /* done */ } else if(UCNV_TO_U_USE_FALLBACK(cnv)) { c=ucnv_MBCSGetFallback(&sharedData->mbcs, offset); /* else done with 0xfffe */ } break; } else if(action==MBCS_STATE_VALID_DIRECT_16) { /* output BMP code point */ c=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); break; } else if(action==MBCS_STATE_VALID_16_PAIR) { offset+=MBCS_ENTRY_FINAL_VALUE_16(entry); c=unicodeCodeUnits[offset++]; if(c<0xd800) { /* output BMP code point below 0xd800 */ } else if(UCNV_TO_U_USE_FALLBACK(cnv) ? c<=0xdfff : c<=0xdbff) { /* output roundtrip or fallback supplementary code point */ c=(UChar32)(((c&0x3ff)<<10)+unicodeCodeUnits[offset]+(0x10000-0xdc00)); } else if(UCNV_TO_U_USE_FALLBACK(cnv) ? (c&0xfffe)==0xe000 : c==0xe000) { /* output roundtrip BMP code point above 0xd800 or fallback BMP code point */ c=unicodeCodeUnits[offset]; } else if(c==0xffff) { return 0xffff; } else { c=0xfffe; } break; } else if(action==MBCS_STATE_VALID_DIRECT_20) { /* output supplementary code point */ c=0x10000+MBCS_ENTRY_FINAL_VALUE(entry); break; } else if(action==MBCS_STATE_FALLBACK_DIRECT_16) { if(!TO_U_USE_FALLBACK(useFallback)) { c=0xfffe; break; } /* output BMP code point */ c=(UChar)MBCS_ENTRY_FINAL_VALUE_16(entry); break; } else if(action==MBCS_STATE_FALLBACK_DIRECT_20) { if(!TO_U_USE_FALLBACK(useFallback)) { c=0xfffe; break; } /* output supplementary code point */ c=0x10000+MBCS_ENTRY_FINAL_VALUE(entry); break; } else if(action==MBCS_STATE_UNASSIGNED) { c=0xfffe; break; } /* * forbid MBCS_STATE_CHANGE_ONLY for this function, * and MBCS_STATE_ILLEGAL and reserved action codes */ return 0xffff; } } if(i!=length) { /* illegal for this function: not all input consumed */ return 0xffff; } if(c==0xfffe) { /* try an extension mapping */ const int32_t *cx=sharedData->mbcs.extIndexes; if(cx!=NULL) { return ucnv_extSimpleMatchToU(cx, source, length, useFallback); } } return c; } /* MBCS-from-Unicode conversion functions ----------------------------------- */ /* This version of ucnv_MBCSFromUnicodeWithOffsets() is optimized for double-byte codepages. */ static void ucnv_MBCSDoubleFromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, UErrorCode *pErrorCode) { UConverter *cnv; const UChar *source, *sourceLimit; uint8_t *target; int32_t targetCapacity; int32_t *offsets; const uint16_t *table; const uint16_t *mbcsIndex; const uint8_t *bytes; UChar32 c; int32_t sourceIndex, nextSourceIndex; uint32_t stage2Entry; uint32_t asciiRoundtrips; uint32_t value; uint8_t unicodeMask; /* use optimized function if possible */ cnv=pArgs->converter; unicodeMask=cnv->sharedData->mbcs.unicodeMask; /* set up the local pointers */ source=pArgs->source; sourceLimit=pArgs->sourceLimit; target=(uint8_t *)pArgs->target; targetCapacity=(int32_t)(pArgs->targetLimit-pArgs->target); offsets=pArgs->offsets; table=cnv->sharedData->mbcs.fromUnicodeTable; mbcsIndex=cnv->sharedData->mbcs.mbcsIndex; if((cnv->options&UCNV_OPTION_SWAP_LFNL)!=0) { bytes=cnv->sharedData->mbcs.swapLFNLFromUnicodeBytes; } else { bytes=cnv->sharedData->mbcs.fromUnicodeBytes; } asciiRoundtrips=cnv->sharedData->mbcs.asciiRoundtrips; /* get the converter state from UConverter */ c=cnv->fromUChar32; /* sourceIndex=-1 if the current character began in the previous buffer */ sourceIndex= c==0 ? 0 : -1; nextSourceIndex=0; /* conversion loop */ if(c!=0 && targetCapacity>0) { goto getTrail; } while(source<sourceLimit) { /* * This following test is to see if available input would overflow the output. * It does not catch output of more than one byte that * overflows as a result of a multi-byte character or callback output * from the last source character. * Therefore, those situations also test for overflows and will * then break the loop, too. */ if(targetCapacity>0) { /* * Get a correct Unicode code point: * a single UChar for a BMP code point or * a matched surrogate pair for a "supplementary code point". */ c=*source++; ++nextSourceIndex; if(c<=0x7f && IS_ASCII_ROUNDTRIP(c, asciiRoundtrips)) { *target++=(uint8_t)c; if(offsets!=NULL) { *offsets++=sourceIndex; sourceIndex=nextSourceIndex; } --targetCapacity; c=0; continue; } /* * utf8Friendly table: Test for <=0xd7ff rather than <=MBCS_FAST_MAX * to avoid dealing with surrogates. * MBCS_FAST_MAX must be >=0xd7ff. */ if(c<=0xd7ff) { value=DBCS_RESULT_FROM_MOST_BMP(mbcsIndex, (const uint16_t *)bytes, c); /* There are only roundtrips (!=0) and no-mapping (==0) entries. */ if(value==0) { goto unassigned; } /* output the value */ } else { /* * This also tests if the codepage maps single surrogates. * If it does, then surrogates are not paired but mapped separately. * Note that in this case unmatched surrogates are not detected. */ if(U16_IS_SURROGATE(c) && !(unicodeMask&UCNV_HAS_SURROGATES)) { if(U16_IS_SURROGATE_LEAD(c)) { getTrail: if(source<sourceLimit) { /* test the following code unit */ UChar trail=*source; if(U16_IS_TRAIL(trail)) { ++source; ++nextSourceIndex; c=U16_GET_SUPPLEMENTARY(c, trail); if(!(unicodeMask&UCNV_HAS_SUPPLEMENTARY)) { /* BMP-only codepages are stored without stage 1 entries for supplementary code points */ /* callback(unassigned) */ goto unassigned; } /* convert this supplementary code point */ /* exit this condition tree */ } else { /* this is an unmatched lead code unit (1st surrogate) */ /* callback(illegal) */ *pErrorCode=U_ILLEGAL_CHAR_FOUND; break; } } else { /* no more input */ break; } } else { /* this is an unmatched trail code unit (2nd surrogate) */ /* callback(illegal) */ *pErrorCode=U_ILLEGAL_CHAR_FOUND; break; } } /* convert the Unicode code point in c into codepage bytes */ stage2Entry=MBCS_STAGE_2_FROM_U(table, c); /* get the bytes and the length for the output */ /* MBCS_OUTPUT_2 */ value=MBCS_VALUE_2_FROM_STAGE_2(bytes, stage2Entry, c); /* is this code point assigned, or do we use fallbacks? */ if(!(MBCS_FROM_U_IS_ROUNDTRIP(stage2Entry, c) || (UCNV_FROM_U_USE_FALLBACK(cnv, c) && value!=0)) ) { /* * We allow a 0 byte output if the "assigned" bit is set for this entry. * There is no way with this data structure for fallback output * to be a zero byte. */ unassigned: /* try an extension mapping */ pArgs->source=source; c=_extFromU(cnv, cnv->sharedData, c, &source, sourceLimit, &target, target+targetCapacity, &offsets, sourceIndex, pArgs->flush, pErrorCode); nextSourceIndex+=(int32_t)(source-pArgs->source); if(U_FAILURE(*pErrorCode)) { /* not mappable or buffer overflow */ break; } else { /* a mapping was written to the target, continue */ /* recalculate the targetCapacity after an extension mapping */ targetCapacity=(int32_t)(pArgs->targetLimit-(char *)target); /* normal end of conversion: prepare for a new character */ sourceIndex=nextSourceIndex; continue; } } } /* write the output character bytes from value and length */ /* from the first if in the loop we know that targetCapacity>0 */ if(value<=0xff) { /* this is easy because we know that there is enough space */ *target++=(uint8_t)value; if(offsets!=NULL) { *offsets++=sourceIndex; } --targetCapacity; } else /* length==2 */ { *target++=(uint8_t)(value>>8); if(2<=targetCapacity) { *target++=(uint8_t)value; if(offsets!=NULL) { *offsets++=sourceIndex; *offsets++=sourceIndex; } targetCapacity-=2; } else { if(offsets!=NULL) { *offsets++=sourceIndex; } cnv->charErrorBuffer[0]=(char)value; cnv->charErrorBufferLength=1; /* target overflow */ targetCapacity=0; *pErrorCode=U_BUFFER_OVERFLOW_ERROR; c=0; break; } } /* normal end of conversion: prepare for a new character */ c=0; sourceIndex=nextSourceIndex; continue; } else { /* target is full */ *pErrorCode=U_BUFFER_OVERFLOW_ERROR; break; } } /* set the converter state back into UConverter */ cnv->fromUChar32=c; /* write back the updated pointers */ pArgs->source=source; pArgs->target=(char *)target; pArgs->offsets=offsets; } /* This version of ucnv_MBCSFromUnicodeWithOffsets() is optimized for single-byte codepages. */ static void ucnv_MBCSSingleFromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, UErrorCode *pErrorCode) { UConverter *cnv; const UChar *source, *sourceLimit; uint8_t *target; int32_t targetCapacity; int32_t *offsets; const uint16_t *table; const uint16_t *results; UChar32 c; int32_t sourceIndex, nextSourceIndex; uint16_t value, minValue; UBool hasSupplementary; /* set up the local pointers */ cnv=pArgs->converter; source=pArgs->source; sourceLimit=pArgs->sourceLimit; target=(uint8_t *)pArgs->target; targetCapacity=(int32_t)(pArgs->targetLimit-pArgs->target); offsets=pArgs->offsets; table=cnv->sharedData->mbcs.fromUnicodeTable; if((cnv->options&UCNV_OPTION_SWAP_LFNL)!=0) { results=(uint16_t *)cnv->sharedData->mbcs.swapLFNLFromUnicodeBytes; } else { results=(uint16_t *)cnv->sharedData->mbcs.fromUnicodeBytes; } if(cnv->useFallback) { /* use all roundtrip and fallback results */ minValue=0x800; } else { /* use only roundtrips and fallbacks from private-use characters */ minValue=0xc00; } hasSupplementary=(UBool)(cnv->sharedData->mbcs.unicodeMask&UCNV_HAS_SUPPLEMENTARY); /* get the converter state from UConverter */ c=cnv->fromUChar32; /* sourceIndex=-1 if the current character began in the previous buffer */ sourceIndex= c==0 ? 0 : -1; nextSourceIndex=0; /* conversion loop */ if(c!=0 && targetCapacity>0) { goto getTrail; } while(source<sourceLimit) { /* * This following test is to see if available input would overflow the output. * It does not catch output of more than one byte that * overflows as a result of a multi-byte character or callback output * from the last source character. * Therefore, those situations also test for overflows and will * then break the loop, too. */ if(targetCapacity>0) { /* * Get a correct Unicode code point: * a single UChar for a BMP code point or * a matched surrogate pair for a "supplementary code point". */ c=*source++; ++nextSourceIndex; if(U16_IS_SURROGATE(c)) { if(U16_IS_SURROGATE_LEAD(c)) { getTrail: if(source<sourceLimit) { /* test the following code unit */ UChar trail=*source; if(U16_IS_TRAIL(trail)) { ++source; ++nextSourceIndex; c=U16_GET_SUPPLEMENTARY(c, trail); if(!hasSupplementary) { /* BMP-only codepages are stored without stage 1 entries for supplementary code points */ /* callback(unassigned) */ goto unassigned; } /* convert this supplementary code point */ /* exit this condition tree */ } else { /* this is an unmatched lead code unit (1st surrogate) */ /* callback(illegal) */ *pErrorCode=U_ILLEGAL_CHAR_FOUND; break; } } else { /* no more input */ break; } } else { /* this is an unmatched trail code unit (2nd surrogate) */ /* callback(illegal) */ *pErrorCode=U_ILLEGAL_CHAR_FOUND; break; } } /* convert the Unicode code point in c into codepage bytes */ value=MBCS_SINGLE_RESULT_FROM_U(table, results, c); /* is this code point assigned, or do we use fallbacks? */ if(value>=minValue) { /* assigned, write the output character bytes from value and length */ /* length==1 */ /* this is easy because we know that there is enough space */ *target++=(uint8_t)value; if(offsets!=NULL) { *offsets++=sourceIndex; } --targetCapacity; /* normal end of conversion: prepare for a new character */ c=0; sourceIndex=nextSourceIndex; } else { /* unassigned */ unassigned: /* try an extension mapping */ pArgs->source=source; c=_extFromU(cnv, cnv->sharedData, c, &source, sourceLimit, &target, target+targetCapacity, &offsets, sourceIndex, pArgs->flush, pErrorCode); nextSourceIndex+=(int32_t)(source-pArgs->source); if(U_FAILURE(*pErrorCode)) { /* not mappable or buffer overflow */ break; } else { /* a mapping was written to the target, continue */ /* recalculate the targetCapacity after an extension mapping */ targetCapacity=(int32_t)(pArgs->targetLimit-(char *)target); /* normal end of conversion: prepare for a new character */ sourceIndex=nextSourceIndex; } } } else { /* target is full */ *pErrorCode=U_BUFFER_OVERFLOW_ERROR; break; } } /* set the converter state back into UConverter */ cnv->fromUChar32=c; /* write back the updated pointers */ pArgs->source=source; pArgs->target=(char *)target; pArgs->offsets=offsets; } /* * This version of ucnv_MBCSFromUnicode() is optimized for single-byte codepages * that map only to and from the BMP. * In addition to single-byte/state optimizations, the offset calculations * become much easier. * It would be possible to use the sbcsIndex for UTF-8-friendly tables, * but measurements have shown that this diminishes performance * in more cases than it improves it. * See SVN revision 21013 (2007-feb-06) for the last version with #if switches * for various MBCS and SBCS optimizations. */ static void ucnv_MBCSSingleFromBMPWithOffsets(UConverterFromUnicodeArgs *pArgs, UErrorCode *pErrorCode) { UConverter *cnv; const UChar *source, *sourceLimit, *lastSource; uint8_t *target; int32_t targetCapacity, length; int32_t *offsets; const uint16_t *table; const uint16_t *results; UChar32 c; int32_t sourceIndex; uint32_t asciiRoundtrips; uint16_t value, minValue; /* set up the local pointers */ cnv=pArgs->converter; source=pArgs->source; sourceLimit=pArgs->sourceLimit; target=(uint8_t *)pArgs->target; targetCapacity=(int32_t)(pArgs->targetLimit-pArgs->target); offsets=pArgs->offsets; table=cnv->sharedData->mbcs.fromUnicodeTable; if((cnv->options&UCNV_OPTION_SWAP_LFNL)!=0) { results=(uint16_t *)cnv->sharedData->mbcs.swapLFNLFromUnicodeBytes; } else { results=(uint16_t *)cnv->sharedData->mbcs.fromUnicodeBytes; } asciiRoundtrips=cnv->sharedData->mbcs.asciiRoundtrips; if(cnv->useFallback) { /* use all roundtrip and fallback results */ minValue=0x800; } else { /* use only roundtrips and fallbacks from private-use characters */ minValue=0xc00; } /* get the converter state from UConverter */ c=cnv->fromUChar32; /* sourceIndex=-1 if the current character began in the previous buffer */ sourceIndex= c==0 ? 0 : -1; lastSource=source; /* * since the conversion here is 1:1 UChar:uint8_t, we need only one counter * for the minimum of the sourceLength and targetCapacity */ length=(int32_t)(sourceLimit-source); if(length<targetCapacity) { targetCapacity=length; } /* conversion loop */ if(c!=0 && targetCapacity>0) { goto getTrail; } #if MBCS_UNROLL_SINGLE_FROM_BMP /* unrolling makes it slower on Pentium III/Windows 2000?! */ /* unroll the loop with the most common case */ unrolled: if(targetCapacity>=4) { int32_t count, loops; uint16_t andedValues; loops=count=targetCapacity>>2; do { c=*source++; andedValues=value=MBCS_SINGLE_RESULT_FROM_U(table, results, c); *target++=(uint8_t)value; c=*source++; andedValues&=value=MBCS_SINGLE_RESULT_FROM_U(table, results, c); *target++=(uint8_t)value; c=*source++; andedValues&=value=MBCS_SINGLE_RESULT_FROM_U(table, results, c); *target++=(uint8_t)value; c=*source++; andedValues&=value=MBCS_SINGLE_RESULT_FROM_U(table, results, c); *target++=(uint8_t)value; /* were all 4 entries really valid? */ if(andedValues<minValue) { /* no, return to the first of these 4 */ source-=4; target-=4; break; } } while(--count>0); count=loops-count; targetCapacity-=4*count; if(offsets!=NULL) { lastSource+=4*count; while(count>0) { *offsets++=sourceIndex++; *offsets++=sourceIndex++; *offsets++=sourceIndex++; *offsets++=sourceIndex++; --count; } } c=0; } #endif while(targetCapacity>0) { /* * Get a correct Unicode code point: * a single UChar for a BMP code point or * a matched surrogate pair for a "supplementary code point". */ c=*source++; /* * Do not immediately check for single surrogates: * Assume that they are unassigned and check for them in that case. * This speeds up the conversion of assigned characters. */ /* convert the Unicode code point in c into codepage bytes */ if(c<=0x7f && IS_ASCII_ROUNDTRIP(c, asciiRoundtrips)) { *target++=(uint8_t)c; --targetCapacity; c=0; continue; } value=MBCS_SINGLE_RESULT_FROM_U(table, results, c); /* is this code point assigned, or do we use fallbacks? */ if(value>=minValue) { /* assigned, write the output character bytes from value and length */ /* length==1 */ /* this is easy because we know that there is enough space */ *target++=(uint8_t)value; --targetCapacity; /* normal end of conversion: prepare for a new character */ c=0; continue; } else if(!U16_IS_SURROGATE(c)) { /* normal, unassigned BMP character */ } else if(U16_IS_SURROGATE_LEAD(c)) { getTrail: if(source<sourceLimit) { /* test the following code unit */ UChar trail=*source; if(U16_IS_TRAIL(trail)) { ++source; c=U16_GET_SUPPLEMENTARY(c, trail); /* this codepage does not map supplementary code points */ /* callback(unassigned) */ } else { /* this is an unmatched lead code unit (1st surrogate) */ /* callback(illegal) */ *pErrorCode=U_ILLEGAL_CHAR_FOUND; break; } } else { /* no more input */ if (pArgs->flush) { *pErrorCode=U_TRUNCATED_CHAR_FOUND; } break; } } else { /* this is an unmatched trail code unit (2nd surrogate) */ /* callback(illegal) */ *pErrorCode=U_ILLEGAL_CHAR_FOUND; break; } /* c does not have a mapping */ /* get the number of code units for c to correctly advance sourceIndex */ length=U16_LENGTH(c); /* set offsets since the start or the last extension */ if(offsets!=NULL) { int32_t count=(int32_t)(source-lastSource); /* do not set the offset for this character */ count-=length; while(count>0) { *offsets++=sourceIndex++; --count; } /* offsets and sourceIndex are now set for the current character */ } /* try an extension mapping */ lastSource=source; c=_extFromU(cnv, cnv->sharedData, c, &source, sourceLimit, &target, (const uint8_t *)(pArgs->targetLimit), &offsets, sourceIndex, pArgs->flush, pErrorCode); sourceIndex+=length+(int32_t)(source-lastSource); lastSource=source; if(U_FAILURE(*pErrorCode)) { /* not mappable or buffer overflow */ break; } else { /* a mapping was written to the target, continue */ /* recalculate the targetCapacity after an extension mapping */ targetCapacity=(int32_t)(pArgs->targetLimit-(char *)target); length=(int32_t)(sourceLimit-source); if(length<targetCapacity) { targetCapacity=length; } } #if MBCS_UNROLL_SINGLE_FROM_BMP /* unrolling makes it slower on Pentium III/Windows 2000?! */ goto unrolled; #endif } if(U_SUCCESS(*pErrorCode) && source<sourceLimit && target>=(uint8_t *)pArgs->targetLimit) { /* target is full */ *pErrorCode=U_BUFFER_OVERFLOW_ERROR; } /* set offsets since the start or the last callback */ if(offsets!=NULL) { size_t count=source-lastSource; if (count > 0 && *pErrorCode == U_TRUNCATED_CHAR_FOUND) { /* Caller gave us a partial supplementary character, which this function couldn't convert in any case. The callback will handle the offset. */ count--; } while(count>0) { *offsets++=sourceIndex++; --count; } } /* set the converter state back into UConverter */ cnv->fromUChar32=c; /* write back the updated pointers */ pArgs->source=source; pArgs->target=(char *)target; pArgs->offsets=offsets; } U_CFUNC void ucnv_MBCSFromUnicodeWithOffsets(UConverterFromUnicodeArgs *pArgs, UErrorCode *pErrorCode) { UConverter *cnv; const UChar *source, *sourceLimit; uint8_t *target; int32_t targetCapacity; int32_t *offsets; const uint16_t *table; const uint16_t *mbcsIndex; const uint8_t *p, *bytes; uint8_t outputType; UChar32 c; int32_t prevSourceIndex, sourceIndex, nextSourceIndex; uint32_t stage2Entry; uint32_t asciiRoundtrips; uint32_t value; /* Shift-In and Shift-Out byte sequences differ by encoding scheme. */ uint8_t siBytes[2] = {0, 0}; uint8_t soBytes[2] = {0, 0}; uint8_t siLength, soLength; int32_t length = 0, prevLength; uint8_t unicodeMask; cnv=pArgs->converter; if(cnv->preFromUFirstCP>=0) { /* * pass sourceIndex=-1 because we continue from an earlier buffer * in the future, this may change with continuous offsets */ ucnv_extContinueMatchFromU(cnv, pArgs, -1, pErrorCode); if(U_FAILURE(*pErrorCode) || cnv->preFromULength<0) { return; } } /* use optimized function if possible */ outputType=cnv->sharedData->mbcs.outputType; unicodeMask=cnv->sharedData->mbcs.unicodeMask; if(outputType==MBCS_OUTPUT_1 && !(unicodeMask&UCNV_HAS_SURROGATES)) { if(!(unicodeMask&UCNV_HAS_SUPPLEMENTARY)) { ucnv_MBCSSingleFromBMPWithOffsets(pArgs, pErrorCode); } else { ucnv_MBCSSingleFromUnicodeWithOffsets(pArgs, pErrorCode); } return; } else if(outputType==MBCS_OUTPUT_2 && cnv->sharedData->mbcs.utf8Friendly) { ucnv_MBCSDoubleFromUnicodeWithOffsets(pArgs, pErrorCode); return; } /* set up the local pointers */ source=pArgs->source; sourceLimit=pArgs->sourceLimit; target=(uint8_t *)pArgs->target; targetCapacity=(int32_t)(pArgs->targetLimit-pArgs->target); offsets=pArgs->offsets; table=cnv->sharedData->mbcs.fromUnicodeTable; if(cnv->sharedData->mbcs.utf8Friendly) { mbcsIndex=cnv->sharedData->mbcs.mbcsIndex; } else { mbcsIndex=NULL; } if((cnv->options&UCNV_OPTION_SWAP_LFNL)!=0) { bytes=cnv->sharedData->mbcs.swapLFNLFromUnicodeBytes; } else { bytes=cnv->sharedData->mbcs.fromUnicodeBytes; } asciiRoundtrips=cnv->sharedData->mbcs.asciiRoundtrips; /* get the converter state from UConverter */ c=cnv->fromUChar32; if(outputType==MBCS_OUTPUT_2_SISO) { prevLength=cnv->fromUnicodeStatus; if(prevLength==0) { /* set the real value */ prevLength=1; } } else { /* prevent fromUnicodeStatus from being set to something non-0 */ prevLength=0; } /* sourceIndex=-1 if the current character began in the previous buffer */ prevSourceIndex=-1; sourceIndex= c==0 ? 0 : -1; nextSourceIndex=0; /* Get the SI/SO character for the converter */ siLength = getSISOBytes(SI, cnv->options, siBytes); soLength = getSISOBytes(SO, cnv->options, soBytes); /* conversion loop */ /* * This is another piece of ugly code: * A goto into the loop if the converter state contains a first surrogate * from the previous function call. * It saves me to check in each loop iteration a check of if(c==0) * and duplicating the trail-surrogate-handling code in the else * branch of that check. * I could not find any other way to get around this other than * using a function call for the conversion and callback, which would * be even more inefficient. * * Markus Scherer 2000-jul-19 */ if(c!=0 && targetCapacity>0) { goto getTrail; } while(source<sourceLimit) { /* * This following test is to see if available input would overflow the output. * It does not catch output of more than one byte that * overflows as a result of a multi-byte character or callback output * from the last source character. * Therefore, those situations also test for overflows and will * then break the loop, too. */ if(targetCapacity>0) { /* * Get a correct Unicode code point: * a single UChar for a BMP code point or * a matched surrogate pair for a "supplementary code point". */ c=*source++; ++nextSourceIndex; if(c<=0x7f && IS_ASCII_ROUNDTRIP(c, asciiRoundtrips)) { *target++=(uint8_t)c; if(offsets!=NULL) { *offsets++=sourceIndex; prevSourceIndex=sourceIndex; sourceIndex=nextSourceIndex; } --targetCapacity; c=0; continue; } /* * utf8Friendly table: Test for <=0xd7ff rather than <=MBCS_FAST_MAX * to avoid dealing with surrogates. * MBCS_FAST_MAX must be >=0xd7ff. */ if(c<=0xd7ff && mbcsIndex!=NULL) { value=mbcsIndex[c>>6]; /* get the bytes and the length for the output (copied from below and adapted for utf8Friendly data) */ /* There are only roundtrips (!=0) and no-mapping (==0) entries. */ switch(outputType) { case MBCS_OUTPUT_2: value=((const uint16_t *)bytes)[value +(c&0x3f)]; if(value<=0xff) { if(value==0) { goto unassigned; } else { length=1; } } else { length=2; } break; case MBCS_OUTPUT_2_SISO: /* 1/2-byte stateful with Shift-In/Shift-Out */ /* * Save the old state in the converter object * right here, then change the local prevLength state variable if necessary. * Then, if this character turns out to be unassigned or a fallback that * is not taken, the callback code must not save the new state in the converter * because the new state is for a character that is not output. * However, the callback must still restore the state from the converter * in case the callback function changed it for its output. */ cnv->fromUnicodeStatus=prevLength; /* save the old state */ value=((const uint16_t *)bytes)[value +(c&0x3f)]; if(value<=0xff) { if(value==0) { goto unassigned; } else if(prevLength<=1) { length=1; } else { /* change from double-byte mode to single-byte */ if (siLength == 1) { value|=(uint32_t)siBytes[0]<<8; length = 2; } else if (siLength == 2) { value|=(uint32_t)siBytes[1]<<8; value|=(uint32_t)siBytes[0]<<16; length = 3; } prevLength=1; } } else { if(prevLength==2) { length=2; } else { /* change from single-byte mode to double-byte */ if (soLength == 1) { value|=(uint32_t)soBytes[0]<<16; length = 3; } else if (soLength == 2) { value|=(uint32_t)soBytes[1]<<16; value|=(uint32_t)soBytes[0]<<24; length = 4; } prevLength=2; } } break; case MBCS_OUTPUT_DBCS_ONLY: /* table with single-byte results, but only DBCS mappings used */ value=((const uint16_t *)bytes)[value +(c&0x3f)]; if(value<=0xff) { /* no mapping or SBCS result, not taken for DBCS-only */ goto unassigned; } else { length=2; } break; case MBCS_OUTPUT_3: p=bytes+(value+(c&0x3f))*3; value=((uint32_t)*p<<16)|((uint32_t)p[1]<<8)|p[2]; if(value<=0xff) { if(value==0) { goto unassigned; } else { length=1; } } else if(value<=0xffff) { length=2; } else { length=3; } break; case MBCS_OUTPUT_4: value=((const uint32_t *)bytes)[value +(c&0x3f)]; if(value<=0xff) { if(value==0) { goto unassigned; } else { length=1; } } else if(value<=0xffff) { length=2; } else if(value<=0xffffff) { length=3; } else { length=4; } break; case MBCS_OUTPUT_3_EUC: value=((const uint16_t *)bytes)[value +(c&0x3f)]; /* EUC 16-bit fixed-length representation */ if(value<=0xff) { if(value==0) { goto unassigned; } else { length=1; } } else if((value&0x8000)==0) { value|=0x8e8000; length=3; } else if((value&0x80)==0) { value|=0x8f0080; length=3; } else { length=2; } break; case MBCS_OUTPUT_4_EUC: p=bytes+(value+(c&0x3f))*3; value=((uint32_t)*p<<16)|((uint32_t)p[1]<<8)|p[2]; /* EUC 16-bit fixed-length representation applied to the first two bytes */ if(value<=0xff) { if(value==0) { goto unassigned; } else { length=1; } } else if(value<=0xffff) { length=2; } else if((value&0x800000)==0) { value|=0x8e800000; length=4; } else if((value&0x8000)==0) { value|=0x8f008000; length=4; } else { length=3; } break; default: /* must not occur */ /* * To avoid compiler warnings that value & length may be * used without having been initialized, we set them here. * In reality, this is unreachable code. * Not having a default branch also causes warnings with * some compilers. */ value=0; length=0; break; } /* output the value */ } else { /* * This also tests if the codepage maps single surrogates. * If it does, then surrogates are not paired but mapped separately. * Note that in this case unmatched surrogates are not detected. */ if(U16_IS_SURROGATE(c) && !(unicodeMask&UCNV_HAS_SURROGATES)) { if(U16_IS_SURROGATE_LEAD(c)) { getTrail: if(source<sourceLimit) { /* test the following code unit */ UChar trail=*source; if(U16_IS_TRAIL(trail)) { ++source; ++nextSourceIndex; c=U16_GET_SUPPLEMENTARY(c, trail); if(!(unicodeMask&UCNV_HAS_SUPPLEMENTARY)) { /* BMP-only codepages are stored without stage 1 entries for supplementary code points */ cnv->fromUnicodeStatus=prevLength; /* save the old state */ /* callback(unassigned) */ goto unassigned; } /* convert this supplementary code point */ /* exit this condition tree */ } else { /* this is an unmatched lead code unit (1st surrogate) */ /* callback(illegal) */ *pErrorCode=U_ILLEGAL_CHAR_FOUND; break; } } else { /* no more input */ break; } } else { /* this is an unmatched trail code unit (2nd surrogate) */ /* callback(illegal) */ *pErrorCode=U_ILLEGAL_CHAR_FOUND; break; } } /* convert the Unicode code point in c into codepage bytes */ /* * The basic lookup is a triple-stage compact array (trie) lookup. * For details see the beginning of this file. * * Single-byte codepages are handled with a different data structure * by _MBCSSingle... functions. * * The result consists of a 32-bit value from stage 2 and * a pointer to as many bytes as are stored per character. * The pointer points to the character's bytes in stage 3. * Bits 15..0 of the stage 2 entry contain the stage 3 index * for that pointer, while bits 31..16 are flags for which of * the 16 characters in the block are roundtrip-assigned. * * For 2-byte and 4-byte codepages, the bytes are stored as uint16_t * respectively as uint32_t, in the platform encoding. * For 3-byte codepages, the bytes are always stored in big-endian order. * * For EUC encodings that use only either 0x8e or 0x8f as the first * byte of their longest byte sequences, the first two bytes in * this third stage indicate with their 7th bits whether these bytes * are to be written directly or actually need to be preceeded by * one of the two Single-Shift codes. With this, the third stage * stores one byte fewer per character than the actual maximum length of * EUC byte sequences. * * Other than that, leading zero bytes are removed and the other * bytes output. A single zero byte may be output if the "assigned" * bit in stage 2 was on. * The data structure does not support zero byte output as a fallback, * and also does not allow output of leading zeros. */ stage2Entry=MBCS_STAGE_2_FROM_U(table, c); /* get the bytes and the length for the output */ switch(outputType) { case MBCS_OUTPUT_2: value=MBCS_VALUE_2_FROM_STAGE_2(bytes, stage2Entry, c); if(value<=0xff) { length=1; } else { length=2; } break; case MBCS_OUTPUT_2_SISO: /* 1/2-byte stateful with Shift-In/Shift-Out */ /* * Save the old state in the converter object * right here, then change the local prevLength state variable if necessary. * Then, if this character turns out to be unassigned or a fallback that * is not taken, the callback code must not save the new state in the converter * because the new state is for a character that is not output. * However, the callback must still restore the state from the converter * in case the callback function changed it for its output. */ cnv->fromUnicodeStatus=prevLength; /* save the old state */ value=MBCS_VALUE_2_FROM_STAGE_2(bytes, stage2Entry, c); if(value<=0xff) { if(value==0 && MBCS_FROM_U_IS_ROUNDTRIP(stage2Entry, c)==0) { /* no mapping, leave value==0 */ length=0; } else if(prevLength<=1) { length=1; } else { /* change from double-byte mode to single-byte */ if (siLength == 1) { value|=(uint32_t)siBytes[0]<<8; length = 2; } else if (siLength == 2) { value|=(uint32_t)siBytes[1]<<8; value|=(uint32_t)siBytes[0]<<16; length = 3; } prevLength=1; } } else { if(prevLength==2) { length=2; } else { /* change from single-byte mode to double-byte */ if (soLength == 1) { value|=(uint32_t)soBytes[0]<<16; length = 3; } else if (soLength == 2) { value|=(uint32_t)soBytes[1]<<16; value|=(uint32_t)soBytes[0]<<24; length = 4; } prevLength=2; } } break; case MBCS_OUTPUT_DBCS_ONLY: /* table with single-byte results, but only DBCS mappings used */ value=MBCS_VALUE_2_FROM_STAGE_2(bytes, stage2Entry, c); if(value<=0xff) { /* no mapping or SBCS result, not taken for DBCS-only */ value=stage2Entry=0; /* stage2Entry=0 to reset roundtrip flags */ length=0; } else { length=2; } break; case MBCS_OUTPUT_3: p=MBCS_POINTER_3_FROM_STAGE_2(bytes, stage2Entry, c); value=((uint32_t)*p<<16)|((uint32_t)p[1]<<8)|p[2]; if(value<=0xff) { length=1; } else if(value<=0xffff) { length=2; } else { length=3; } break; case MBCS_OUTPUT_4: value=MBCS_VALUE_4_FROM_STAGE_2(bytes, stage2Entry, c); if(value<=0xff) { length=1; } else if(value<=0xffff) { length=2; } else if(value<=0xffffff) { length=3; } else { length=4; } break; case MBCS_OUTPUT_3_EUC: value=MBCS_VALUE_2_FROM_STAGE_2(bytes, stage2Entry, c); /* EUC 16-bit fixed-length representation */ if(value<=0xff) { length=1; } else if((value&0x8000)==0) { value|=0x8e8000; length=3; } else if((value&0x80)==0) { value|=0x8f0080; length=3; } else { length=2; } break; case MBCS_OUTPUT_4_EUC: p=MBCS_POINTER_3_FROM_STAGE_2(bytes, stage2Entry, c); value=((uint32_t)*p<<16)|((uint32_t)p[1]<<8)|p[2]; /* EUC 16-bit fixed-length representation applied to the first two bytes */ if(value<=0xff) { length=1; } else if(value<=0xffff) { length=2; } else if((value&0x800000)==0) { value|=0x8e800000; length=4; } else if((value&0x8000)==0) { value|=0x8f008000; length=4; } else { length=3; } break; default: /* must not occur */ /* * To avoid compiler warnings that value & length may be * used without having been initialized, we set them here. * In reality, this is unreachable code. * Not having a default branch also causes warnings with * some compilers. */ value=stage2Entry=0; /* stage2Entry=0 to reset roundtrip flags */ length=0; break; } /* is this code point assigned, or do we use fallbacks? */ if(!(MBCS_FROM_U_IS_ROUNDTRIP(stage2Entry, c)!=0 || (UCNV_FROM_U_USE_FALLBACK(cnv, c) && value!=0)) ) { /* * We allow a 0 byte output if the "assigned" bit is set for this entry. * There is no way with this data structure for fallback output * to be a zero byte. */ unassigned: /* try an extension mapping */ pArgs->source=source; c=_extFromU(cnv, cnv->sharedData, c, &source, sourceLimit, &target, target+targetCapacity, &offsets, sourceIndex, pArgs->flush, pErrorCode); nextSourceIndex+=(int32_t)(source-pArgs->source); prevLength=cnv->fromUnicodeStatus; /* restore SISO state */ if(U_FAILURE(*pErrorCode)) { /* not mappable or buffer overflow */ break; } else { /* a mapping was written to the target, continue */ /* recalculate the targetCapacity after an extension mapping */ targetCapacity=(int32_t)(pArgs->targetLimit-(char *)target); /* normal end of conversion: prepare for a new character */ if(offsets!=NULL) { prevSourceIndex=sourceIndex; sourceIndex=nextSourceIndex; } continue; } } } /* write the output character bytes from value and length */ /* from the first if in the loop we know that targetCapacity>0 */ if(length<=targetCapacity) { if(offsets==NULL) { switch(length) { /* each branch falls through to the next one */ case 4: *target++=(uint8_t)(value>>24); U_FALLTHROUGH; case 3: *target++=(uint8_t)(value>>16); U_FALLTHROUGH; case 2: *target++=(uint8_t)(value>>8); U_FALLTHROUGH; case 1: *target++=(uint8_t)value; U_FALLTHROUGH; default: /* will never occur */ break; } } else { switch(length) { /* each branch falls through to the next one */ case 4: *target++=(uint8_t)(value>>24); *offsets++=sourceIndex; U_FALLTHROUGH; case 3: *target++=(uint8_t)(value>>16); *offsets++=sourceIndex; U_FALLTHROUGH; case 2: *target++=(uint8_t)(value>>8); *offsets++=sourceIndex; U_FALLTHROUGH; case 1: *target++=(uint8_t)value; *offsets++=sourceIndex; U_FALLTHROUGH; default: /* will never occur */ break; } } targetCapacity-=length; } else { uint8_t *charErrorBuffer; /* * We actually do this backwards here: * In order to save an intermediate variable, we output * first to the overflow buffer what does not fit into the * regular target. */ /* we know that 1<=targetCapacity<length<=4 */ length-=targetCapacity; charErrorBuffer=(uint8_t *)cnv->charErrorBuffer; switch(length) { /* each branch falls through to the next one */ case 3: *charErrorBuffer++=(uint8_t)(value>>16); U_FALLTHROUGH; case 2: *charErrorBuffer++=(uint8_t)(value>>8); U_FALLTHROUGH; case 1: *charErrorBuffer=(uint8_t)value; U_FALLTHROUGH; default: /* will never occur */ break; } cnv->charErrorBufferLength=(int8_t)length; /* now output what fits into the regular target */ value>>=8*length; /* length was reduced by targetCapacity */ switch(targetCapacity) { /* each branch falls through to the next one */ case 3: *target++=(uint8_t)(value>>16); if(offsets!=NULL) { *offsets++=sourceIndex; } U_FALLTHROUGH; case 2: *target++=(uint8_t)(value>>8); if(offsets!=NULL) { *offsets++=sourceIndex; } U_FALLTHROUGH; case 1: *target++=(uint8_t)value; if(offsets!=NULL) { *offsets++=sourceIndex; } U_FALLTHROUGH; default: /* will never occur */ break; } /* target overflow */ targetCapacity=0; *pErrorCode=U_BUFFER_OVERFLOW_ERROR; c=0; break; } /* normal end of conversion: prepare for a new character */ c=0; if(offsets!=NULL) { prevSourceIndex=sourceIndex; sourceIndex=nextSourceIndex; } continue; } else { /* target is full */ *pErrorCode=U_BUFFER_OVERFLOW_ERROR; break; } } /* * the end of the input stream and detection of truncated input * are handled by the framework, but for EBCDIC_STATEFUL conversion * we need to emit an SI at the very end * * conditions: * successful * EBCDIC_STATEFUL in DBCS mode * end of input and no truncated input */ if( U_SUCCESS(*pErrorCode) && outputType==MBCS_OUTPUT_2_SISO && prevLength==2 && pArgs->flush && source>=sourceLimit && c==0 ) { /* EBCDIC_STATEFUL ending with DBCS: emit an SI to return the output stream to SBCS */ if(targetCapacity>0) { *target++=(uint8_t)siBytes[0]; if (siLength == 2) { if (targetCapacity<2) { cnv->charErrorBuffer[0]=(uint8_t)siBytes[1]; cnv->charErrorBufferLength=1; *pErrorCode=U_BUFFER_OVERFLOW_ERROR; } else { *target++=(uint8_t)siBytes[1]; } } if(offsets!=NULL) { /* set the last source character's index (sourceIndex points at sourceLimit now) */ *offsets++=prevSourceIndex; } } else { /* target is full */ cnv->charErrorBuffer[0]=(uint8_t)siBytes[0]; if (siLength == 2) { cnv->charErrorBuffer[1]=(uint8_t)siBytes[1]; } cnv->charErrorBufferLength=siLength; *pErrorCode=U_BUFFER_OVERFLOW_ERROR; } prevLength=1; /* we switched into SBCS */ } /* set the converter state back into UConverter */ cnv->fromUChar32=c; cnv->fromUnicodeStatus=prevLength; /* write back the updated pointers */ pArgs->source=source; pArgs->target=(char *)target; pArgs->offsets=offsets; } /* * This is another simple conversion function for internal use by other * conversion implementations. * It does not use the converter state nor call callbacks. * It does not handle the EBCDIC swaplfnl option (set in UConverter). * It handles conversion extensions but not GB 18030. * * It converts one single Unicode code point into codepage bytes, encoded * as one 32-bit value. The function returns the number of bytes in *pValue: * 1..4 the number of bytes in *pValue * 0 unassigned (*pValue undefined) * -1 illegal (currently not used, *pValue undefined) * * *pValue will contain the resulting bytes with the last byte in bits 7..0, * the second to last byte in bits 15..8, etc. * Currently, the function assumes but does not check that 0<=c<=0x10ffff. */ U_CFUNC int32_t ucnv_MBCSFromUChar32(UConverterSharedData *sharedData, UChar32 c, uint32_t *pValue, UBool useFallback) { const int32_t *cx; const uint16_t *table; #if 0 /* #if 0 because this is not currently used in ICU - reduce code, increase code coverage */ const uint8_t *p; #endif uint32_t stage2Entry; uint32_t value; int32_t length; /* BMP-only codepages are stored without stage 1 entries for supplementary code points */ if(c<=0xffff || (sharedData->mbcs.unicodeMask&UCNV_HAS_SUPPLEMENTARY)) { table=sharedData->mbcs.fromUnicodeTable; /* convert the Unicode code point in c into codepage bytes (same as in _MBCSFromUnicodeWithOffsets) */ if(sharedData->mbcs.outputType==MBCS_OUTPUT_1) { value=MBCS_SINGLE_RESULT_FROM_U(table, (uint16_t *)sharedData->mbcs.fromUnicodeBytes, c); /* is this code point assigned, or do we use fallbacks? */ if(useFallback ? value>=0x800 : value>=0xc00) { *pValue=value&0xff; return 1; } } else /* outputType!=MBCS_OUTPUT_1 */ { stage2Entry=MBCS_STAGE_2_FROM_U(table, c); /* get the bytes and the length for the output */ switch(sharedData->mbcs.outputType) { case MBCS_OUTPUT_2: value=MBCS_VALUE_2_FROM_STAGE_2(sharedData->mbcs.fromUnicodeBytes, stage2Entry, c); if(value<=0xff) { length=1; } else { length=2; } break; #if 0 /* #if 0 because this is not currently used in ICU - reduce code, increase code coverage */ case MBCS_OUTPUT_DBCS_ONLY: /* table with single-byte results, but only DBCS mappings used */ value=MBCS_VALUE_2_FROM_STAGE_2(sharedData->mbcs.fromUnicodeBytes, stage2Entry, c); if(value<=0xff) { /* no mapping or SBCS result, not taken for DBCS-only */ value=stage2Entry=0; /* stage2Entry=0 to reset roundtrip flags */ length=0; } else { length=2; } break; case MBCS_OUTPUT_3: p=MBCS_POINTER_3_FROM_STAGE_2(sharedData->mbcs.fromUnicodeBytes, stage2Entry, c); value=((uint32_t)*p<<16)|((uint32_t)p[1]<<8)|p[2]; if(value<=0xff) { length=1; } else if(value<=0xffff) { length=2; } else { length=3; } break; case MBCS_OUTPUT_4: value=MBCS_VALUE_4_FROM_STAGE_2(sharedData->mbcs.fromUnicodeBytes, stage2Entry, c); if(value<=0xff) { length=1; } else if(value<=0xffff) { length=2; } else if(value<=0xffffff) { length=3; } else { length=4; } break; case MBCS_OUTPUT_3_EUC: value=MBCS_VALUE_2_FROM_STAGE_2(sharedData->mbcs.fromUnicodeBytes, stage2Entry, c); /* EUC 16-bit fixed-length representation */ if(value<=0xff) { length=1; } else if((value&0x8000)==0) { value|=0x8e8000; length=3; } else if((value&0x80)==0) { value|=0x8f0080; length=3; } else { length=2; } break; case MBCS_OUTPUT_4_EUC: p=MBCS_POINTER_3_FROM_STAGE_2(sharedData->mbcs.fromUnicodeBytes, stage2Entry, c); value=((uint32_t)*p<<16)|((uint32_t)p[1]<<8)|p[2]; /* EUC 16-bit fixed-length representation applied to the first two bytes */ if(value<=0xff) { length=1; } else if(value<=0xffff) { length=2; } else if((value&0x800000)==0) { value|=0x8e800000; length=4; } else if((value&0x8000)==0) { value|=0x8f008000; length=4; } else { length=3; } break; #endif default: /* must not occur */ return -1; } /* is this code point assigned, or do we use fallbacks? */ if( MBCS_FROM_U_IS_ROUNDTRIP(stage2Entry, c) || (FROM_U_USE_FALLBACK(useFallback, c) && value!=0) ) { /* * We allow a 0 byte output if the "assigned" bit is set for this entry. * There is no way with this data structure for fallback output * to be a zero byte. */ /* assigned */ *pValue=value; return length; } } } cx=sharedData->mbcs.extIndexes; if(cx!=NULL) { length=ucnv_extSimpleMatchFromU(cx, c, pValue, useFallback); return length>=0 ? length : -length; /* return abs(length); */ } /* unassigned */ return 0; } #if 0 /* * This function has been moved to ucnv2022.c for inlining. * This implementation is here only for documentation purposes */ /** * This version of ucnv_MBCSFromUChar32() is optimized for single-byte codepages. * It does not handle the EBCDIC swaplfnl option (set in UConverter). * It does not handle conversion extensions (_extFromU()). * * It returns the codepage byte for the code point, or -1 if it is unassigned. */ U_CFUNC int32_t ucnv_MBCSSingleFromUChar32(UConverterSharedData *sharedData, UChar32 c, UBool useFallback) { const uint16_t *table; int32_t value; /* BMP-only codepages are stored without stage 1 entries for supplementary code points */ if(c>=0x10000 && !(sharedData->mbcs.unicodeMask&UCNV_HAS_SUPPLEMENTARY)) { return -1; } /* convert the Unicode code point in c into codepage bytes (same as in _MBCSFromUnicodeWithOffsets) */ table=sharedData->mbcs.fromUnicodeTable; /* get the byte for the output */ value=MBCS_SINGLE_RESULT_FROM_U(table, (uint16_t *)sharedData->mbcs.fromUnicodeBytes, c); /* is this code point assigned, or do we use fallbacks? */ if(useFallback ? value>=0x800 : value>=0xc00) { return value&0xff; } else { return -1; } } #endif /* MBCS-from-UTF-8 conversion functions ------------------------------------- */ /* minimum code point values for n-byte UTF-8 sequences, n=0..4 */ static const UChar32 utf8_minLegal[5]={ 0, 0, 0x80, 0x800, 0x10000 }; /* offsets for n-byte UTF-8 sequences that were calculated with ((lead<<6)+trail)<<6+trail... */ static const UChar32 utf8_offsets[7]={ 0, 0, 0x3080, 0xE2080, 0x3C82080 }; static void ucnv_SBCSFromUTF8(UConverterFromUnicodeArgs *pFromUArgs, UConverterToUnicodeArgs *pToUArgs, UErrorCode *pErrorCode) { UConverter *utf8, *cnv; const uint8_t *source, *sourceLimit; uint8_t *target; int32_t targetCapacity; const uint16_t *table, *sbcsIndex; const uint16_t *results; int8_t oldToULength, toULength, toULimit; UChar32 c; uint8_t b, t1, t2; uint32_t asciiRoundtrips; uint16_t value, minValue; UBool hasSupplementary; /* set up the local pointers */ utf8=pToUArgs->converter; cnv=pFromUArgs->converter; source=(uint8_t *)pToUArgs->source; sourceLimit=(uint8_t *)pToUArgs->sourceLimit; target=(uint8_t *)pFromUArgs->target; targetCapacity=(int32_t)(pFromUArgs->targetLimit-pFromUArgs->target); table=cnv->sharedData->mbcs.fromUnicodeTable; sbcsIndex=cnv->sharedData->mbcs.sbcsIndex; if((cnv->options&UCNV_OPTION_SWAP_LFNL)!=0) { results=(uint16_t *)cnv->sharedData->mbcs.swapLFNLFromUnicodeBytes; } else { results=(uint16_t *)cnv->sharedData->mbcs.fromUnicodeBytes; } asciiRoundtrips=cnv->sharedData->mbcs.asciiRoundtrips; if(cnv->useFallback) { /* use all roundtrip and fallback results */ minValue=0x800; } else { /* use only roundtrips and fallbacks from private-use characters */ minValue=0xc00; } hasSupplementary=(UBool)(cnv->sharedData->mbcs.unicodeMask&UCNV_HAS_SUPPLEMENTARY); /* get the converter state from the UTF-8 UConverter */ c=(UChar32)utf8->toUnicodeStatus; if(c!=0) { toULength=oldToULength=utf8->toULength; toULimit=(int8_t)utf8->mode; } else { toULength=oldToULength=toULimit=0; } /* * Make sure that the last byte sequence before sourceLimit is complete * or runs into a lead byte. * Do not go back into the bytes that will be read for finishing a partial * sequence from the previous buffer. * In the conversion loop compare source with sourceLimit only once * per multi-byte character. */ { int32_t i, length; length=(int32_t)(sourceLimit-source) - (toULimit-oldToULength); for(i=0; i<3 && i<length;) { b=*(sourceLimit-i-1); if(U8_IS_TRAIL(b)) { ++i; } else { if(i<U8_COUNT_TRAIL_BYTES(b)) { /* exit the conversion loop before the lead byte if there are not enough trail bytes for it */ sourceLimit-=i+1; } break; } } } if(c!=0 && targetCapacity>0) { utf8->toUnicodeStatus=0; utf8->toULength=0; goto moreBytes; /* * Note: We could avoid the goto by duplicating some of the moreBytes * code, but only up to the point of collecting a complete UTF-8 * sequence; then recurse for the toUBytes[toULength] * and then continue with normal conversion. * * If so, move this code to just after initializing the minimum * set of local variables for reading the UTF-8 input * (utf8, source, target, limits but not cnv, table, minValue, etc.). * * Potential advantages: * - avoid the goto * - oldToULength could become a local variable in just those code blocks * that deal with buffer boundaries * - possibly faster if the goto prevents some compiler optimizations * (this would need measuring to confirm) * Disadvantage: * - code duplication */ } /* conversion loop */ while(source<sourceLimit) { if(targetCapacity>0) { b=*source++; if((int8_t)b>=0) { /* convert ASCII */ if(IS_ASCII_ROUNDTRIP(b, asciiRoundtrips)) { *target++=(uint8_t)b; --targetCapacity; continue; } else { c=b; value=SBCS_RESULT_FROM_UTF8(sbcsIndex, results, 0, c); } } else { if(b<0xe0) { if( /* handle U+0080..U+07FF inline */ b>=0xc2 && (t1=(uint8_t)(*source-0x80)) <= 0x3f ) { c=b&0x1f; ++source; value=SBCS_RESULT_FROM_UTF8(sbcsIndex, results, c, t1); if(value>=minValue) { *target++=(uint8_t)value; --targetCapacity; continue; } else { c=(c<<6)|t1; } } else { c=-1; } } else if(b==0xe0) { if( /* handle U+0800..U+0FFF inline */ (t1=(uint8_t)(source[0]-0x80)) <= 0x3f && t1 >= 0x20 && (t2=(uint8_t)(source[1]-0x80)) <= 0x3f ) { c=t1; source+=2; value=SBCS_RESULT_FROM_UTF8(sbcsIndex, results, c, t2); if(value>=minValue) { *target++=(uint8_t)value; --targetCapacity; continue; } else { c=(c<<6)|t2; } } else { c=-1; } } else { c=-1; } if(c<0) { /* handle "complicated" and error cases, and continuing partial characters */ oldToULength=0; toULength=1; toULimit=U8_COUNT_TRAIL_BYTES(b)+1; c=b; moreBytes: while(toULength<toULimit) { /* * The sourceLimit may have been adjusted before the conversion loop * to stop before a truncated sequence. * Here we need to use the real limit in case we have two truncated * sequences at the end. * See ticket #7492. */ if(source<(uint8_t *)pToUArgs->sourceLimit) { b=*source; if(U8_IS_TRAIL(b)) { ++source; ++toULength; c=(c<<6)+b; } else { break; /* sequence too short, stop with toULength<toULimit */ } } else { /* store the partial UTF-8 character, compatible with the regular UTF-8 converter */ source-=(toULength-oldToULength); while(oldToULength<toULength) { utf8->toUBytes[oldToULength++]=*source++; } utf8->toUnicodeStatus=c; utf8->toULength=toULength; utf8->mode=toULimit; pToUArgs->source=(char *)source; pFromUArgs->target=(char *)target; return; } } if( toULength==toULimit && /* consumed all trail bytes */ (toULength==3 || toULength==2) && /* BMP */ (c-=utf8_offsets[toULength])>=utf8_minLegal[toULength] && (c<=0xd7ff || 0xe000<=c) /* not a surrogate */ ) { value=MBCS_SINGLE_RESULT_FROM_U(table, results, c); } else if( toULength==toULimit && toULength==4 && (0x10000<=(c-=utf8_offsets[4]) && c<=0x10ffff) ) { /* supplementary code point */ if(!hasSupplementary) { /* BMP-only codepages are stored without stage 1 entries for supplementary code points */ value=0; } else { value=MBCS_SINGLE_RESULT_FROM_U(table, results, c); } } else { /* error handling: illegal UTF-8 byte sequence */ source-=(toULength-oldToULength); while(oldToULength<toULength) { utf8->toUBytes[oldToULength++]=*source++; } utf8->toULength=toULength; pToUArgs->source=(char *)source; pFromUArgs->target=(char *)target; *pErrorCode=U_ILLEGAL_CHAR_FOUND; return; } } } if(value>=minValue) { /* output the mapping for c */ *target++=(uint8_t)value; --targetCapacity; } else { /* value<minValue means c is unassigned (unmappable) */ /* * Try an extension mapping. * Pass in no source because we don't have UTF-16 input. * If we have a partial match on c, we will return and revert * to UTF-8->UTF-16->charset conversion. */ static const UChar nul=0; const UChar *noSource=&nul; c=_extFromU(cnv, cnv->sharedData, c, &noSource, noSource, &target, target+targetCapacity, NULL, -1, pFromUArgs->flush, pErrorCode); if(U_FAILURE(*pErrorCode)) { /* not mappable or buffer overflow */ cnv->fromUChar32=c; break; } else if(cnv->preFromUFirstCP>=0) { /* * Partial match, return and revert to pivoting. * In normal from-UTF-16 conversion, we would just continue * but then exit the loop because the extension match would * have consumed the source. */ *pErrorCode=U_USING_DEFAULT_WARNING; break; } else { /* a mapping was written to the target, continue */ /* recalculate the targetCapacity after an extension mapping */ targetCapacity=(int32_t)(pFromUArgs->targetLimit-(char *)target); } } } else { /* target is full */ *pErrorCode=U_BUFFER_OVERFLOW_ERROR; break; } } /* * The sourceLimit may have been adjusted before the conversion loop * to stop before a truncated sequence. * If so, then collect the truncated sequence now. */ if(U_SUCCESS(*pErrorCode) && cnv->preFromUFirstCP<0 && source<(sourceLimit=(uint8_t *)pToUArgs->sourceLimit)) { c=utf8->toUBytes[0]=b=*source++; toULength=1; toULimit=U8_COUNT_TRAIL_BYTES(b)+1; while(source<sourceLimit) { utf8->toUBytes[toULength++]=b=*source++; c=(c<<6)+b; } utf8->toUnicodeStatus=c; utf8->toULength=toULength; utf8->mode=toULimit; } /* write back the updated pointers */ pToUArgs->source=(char *)source; pFromUArgs->target=(char *)target; } static void ucnv_DBCSFromUTF8(UConverterFromUnicodeArgs *pFromUArgs, UConverterToUnicodeArgs *pToUArgs, UErrorCode *pErrorCode) { UConverter *utf8, *cnv; const uint8_t *source, *sourceLimit; uint8_t *target; int32_t targetCapacity; const uint16_t *table, *mbcsIndex; const uint16_t *results; int8_t oldToULength, toULength, toULimit; UChar32 c; uint8_t b, t1, t2; uint32_t stage2Entry; uint32_t asciiRoundtrips; uint16_t value; UBool hasSupplementary; /* set up the local pointers */ utf8=pToUArgs->converter; cnv=pFromUArgs->converter; source=(uint8_t *)pToUArgs->source; sourceLimit=(uint8_t *)pToUArgs->sourceLimit; target=(uint8_t *)pFromUArgs->target; targetCapacity=(int32_t)(pFromUArgs->targetLimit-pFromUArgs->target); table=cnv->sharedData->mbcs.fromUnicodeTable; mbcsIndex=cnv->sharedData->mbcs.mbcsIndex; if((cnv->options&UCNV_OPTION_SWAP_LFNL)!=0) { results=(uint16_t *)cnv->sharedData->mbcs.swapLFNLFromUnicodeBytes; } else { results=(uint16_t *)cnv->sharedData->mbcs.fromUnicodeBytes; } asciiRoundtrips=cnv->sharedData->mbcs.asciiRoundtrips; hasSupplementary=(UBool)(cnv->sharedData->mbcs.unicodeMask&UCNV_HAS_SUPPLEMENTARY); /* get the converter state from the UTF-8 UConverter */ c=(UChar32)utf8->toUnicodeStatus; if(c!=0) { toULength=oldToULength=utf8->toULength; toULimit=(int8_t)utf8->mode; } else { toULength=oldToULength=toULimit=0; } /* * Make sure that the last byte sequence before sourceLimit is complete * or runs into a lead byte. * Do not go back into the bytes that will be read for finishing a partial * sequence from the previous buffer. * In the conversion loop compare source with sourceLimit only once * per multi-byte character. */ { int32_t i, length; length=(int32_t)(sourceLimit-source) - (toULimit-oldToULength); for(i=0; i<3 && i<length;) { b=*(sourceLimit-i-1); if(U8_IS_TRAIL(b)) { ++i; } else { if(i<U8_COUNT_TRAIL_BYTES(b)) { /* exit the conversion loop before the lead byte if there are not enough trail bytes for it */ sourceLimit-=i+1; } break; } } } if(c!=0 && targetCapacity>0) { utf8->toUnicodeStatus=0; utf8->toULength=0; goto moreBytes; /* See note in ucnv_SBCSFromUTF8() about this goto. */ } /* conversion loop */ while(source<sourceLimit) { if(targetCapacity>0) { b=*source++; if((int8_t)b>=0) { /* convert ASCII */ if(IS_ASCII_ROUNDTRIP(b, asciiRoundtrips)) { *target++=b; --targetCapacity; continue; } else { value=DBCS_RESULT_FROM_UTF8(mbcsIndex, results, 0, b); if(value==0) { c=b; goto unassigned; } } } else { if(b>0xe0) { if( /* handle U+1000..U+D7FF inline */ (((t1=(uint8_t)(source[0]-0x80), b<0xed) && (t1 <= 0x3f)) || (b==0xed && (t1 <= 0x1f))) && (t2=(uint8_t)(source[1]-0x80)) <= 0x3f ) { c=((b&0xf)<<6)|t1; source+=2; value=DBCS_RESULT_FROM_UTF8(mbcsIndex, results, c, t2); if(value==0) { c=(c<<6)|t2; goto unassigned; } } else { c=-1; } } else if(b<0xe0) { if( /* handle U+0080..U+07FF inline */ b>=0xc2 && (t1=(uint8_t)(*source-0x80)) <= 0x3f ) { c=b&0x1f; ++source; value=DBCS_RESULT_FROM_UTF8(mbcsIndex, results, c, t1); if(value==0) { c=(c<<6)|t1; goto unassigned; } } else { c=-1; } } else { c=-1; } if(c<0) { /* handle "complicated" and error cases, and continuing partial characters */ oldToULength=0; toULength=1; toULimit=U8_COUNT_TRAIL_BYTES(b)+1; c=b; moreBytes: while(toULength<toULimit) { /* * The sourceLimit may have been adjusted before the conversion loop * to stop before a truncated sequence. * Here we need to use the real limit in case we have two truncated * sequences at the end. * See ticket #7492. */ if(source<(uint8_t *)pToUArgs->sourceLimit) { b=*source; if(U8_IS_TRAIL(b)) { ++source; ++toULength; c=(c<<6)+b; } else { break; /* sequence too short, stop with toULength<toULimit */ } } else { /* store the partial UTF-8 character, compatible with the regular UTF-8 converter */ source-=(toULength-oldToULength); while(oldToULength<toULength) { utf8->toUBytes[oldToULength++]=*source++; } utf8->toUnicodeStatus=c; utf8->toULength=toULength; utf8->mode=toULimit; pToUArgs->source=(char *)source; pFromUArgs->target=(char *)target; return; } } if( toULength==toULimit && /* consumed all trail bytes */ (toULength==3 || toULength==2) && /* BMP */ (c-=utf8_offsets[toULength])>=utf8_minLegal[toULength] && (c<=0xd7ff || 0xe000<=c) /* not a surrogate */ ) { stage2Entry=MBCS_STAGE_2_FROM_U(table, c); } else if( toULength==toULimit && toULength==4 && (0x10000<=(c-=utf8_offsets[4]) && c<=0x10ffff) ) { /* supplementary code point */ if(!hasSupplementary) { /* BMP-only codepages are stored without stage 1 entries for supplementary code points */ stage2Entry=0; } else { stage2Entry=MBCS_STAGE_2_FROM_U(table, c); } } else { /* error handling: illegal UTF-8 byte sequence */ source-=(toULength-oldToULength); while(oldToULength<toULength) { utf8->toUBytes[oldToULength++]=*source++; } utf8->toULength=toULength; pToUArgs->source=(char *)source; pFromUArgs->target=(char *)target; *pErrorCode=U_ILLEGAL_CHAR_FOUND; return; } /* get the bytes and the length for the output */ /* MBCS_OUTPUT_2 */ value=MBCS_VALUE_2_FROM_STAGE_2(results, stage2Entry, c); /* is this code point assigned, or do we use fallbacks? */ if(!(MBCS_FROM_U_IS_ROUNDTRIP(stage2Entry, c) || (UCNV_FROM_U_USE_FALLBACK(cnv, c) && value!=0)) ) { goto unassigned; } } } /* write the output character bytes from value and length */ /* from the first if in the loop we know that targetCapacity>0 */ if(value<=0xff) { /* this is easy because we know that there is enough space */ *target++=(uint8_t)value; --targetCapacity; } else /* length==2 */ { *target++=(uint8_t)(value>>8); if(2<=targetCapacity) { *target++=(uint8_t)value; targetCapacity-=2; } else { cnv->charErrorBuffer[0]=(char)value; cnv->charErrorBufferLength=1; /* target overflow */ *pErrorCode=U_BUFFER_OVERFLOW_ERROR; break; } } continue; unassigned: { /* * Try an extension mapping. * Pass in no source because we don't have UTF-16 input. * If we have a partial match on c, we will return and revert * to UTF-8->UTF-16->charset conversion. */ static const UChar nul=0; const UChar *noSource=&nul; c=_extFromU(cnv, cnv->sharedData, c, &noSource, noSource, &target, target+targetCapacity, NULL, -1, pFromUArgs->flush, pErrorCode); if(U_FAILURE(*pErrorCode)) { /* not mappable or buffer overflow */ cnv->fromUChar32=c; break; } else if(cnv->preFromUFirstCP>=0) { /* * Partial match, return and revert to pivoting. * In normal from-UTF-16 conversion, we would just continue * but then exit the loop because the extension match would * have consumed the source. */ *pErrorCode=U_USING_DEFAULT_WARNING; break; } else { /* a mapping was written to the target, continue */ /* recalculate the targetCapacity after an extension mapping */ targetCapacity=(int32_t)(pFromUArgs->targetLimit-(char *)target); continue; } } } else { /* target is full */ *pErrorCode=U_BUFFER_OVERFLOW_ERROR; break; } } /* * The sourceLimit may have been adjusted before the conversion loop * to stop before a truncated sequence. * If so, then collect the truncated sequence now. */ if(U_SUCCESS(*pErrorCode) && cnv->preFromUFirstCP<0 && source<(sourceLimit=(uint8_t *)pToUArgs->sourceLimit)) { c=utf8->toUBytes[0]=b=*source++; toULength=1; toULimit=U8_COUNT_TRAIL_BYTES(b)+1; while(source<sourceLimit) { utf8->toUBytes[toULength++]=b=*source++; c=(c<<6)+b; } utf8->toUnicodeStatus=c; utf8->toULength=toULength; utf8->mode=toULimit; } /* write back the updated pointers */ pToUArgs->source=(char *)source; pFromUArgs->target=(char *)target; } /* miscellaneous ------------------------------------------------------------ */ static void ucnv_MBCSGetStarters(const UConverter* cnv, UBool starters[256], UErrorCode *) { const int32_t *state0; int i; state0=cnv->sharedData->mbcs.stateTable[cnv->sharedData->mbcs.dbcsOnlyState]; for(i=0; i<256; ++i) { /* all bytes that cause a state transition from state 0 are lead bytes */ starters[i]= (UBool)MBCS_ENTRY_IS_TRANSITION(state0[i]); } } /* * This is an internal function that allows other converter implementations * to check whether a byte is a lead byte. */ U_CFUNC UBool ucnv_MBCSIsLeadByte(UConverterSharedData *sharedData, char byte) { return (UBool)MBCS_ENTRY_IS_TRANSITION(sharedData->mbcs.stateTable[0][(uint8_t)byte]); } static void ucnv_MBCSWriteSub(UConverterFromUnicodeArgs *pArgs, int32_t offsetIndex, UErrorCode *pErrorCode) { UConverter *cnv=pArgs->converter; char *p, *subchar; char buffer[4]; int32_t length; /* first, select between subChar and subChar1 */ if( cnv->subChar1!=0 && (cnv->sharedData->mbcs.extIndexes!=NULL ? cnv->useSubChar1 : (cnv->invalidUCharBuffer[0]<=0xff)) ) { /* select subChar1 if it is set (not 0) and the unmappable Unicode code point is up to U+00ff (IBM MBCS behavior) */ subchar=(char *)&cnv->subChar1; length=1; } else { /* select subChar in all other cases */ subchar=(char *)cnv->subChars; length=cnv->subCharLen; } /* reset the selector for the next code point */ cnv->useSubChar1=FALSE; if (cnv->sharedData->mbcs.outputType == MBCS_OUTPUT_2_SISO) { p=buffer; /* fromUnicodeStatus contains prevLength */ switch(length) { case 1: if(cnv->fromUnicodeStatus==2) { /* DBCS mode and SBCS sub char: change to SBCS */ cnv->fromUnicodeStatus=1; *p++=UCNV_SI; } *p++=subchar[0]; break; case 2: if(cnv->fromUnicodeStatus<=1) { /* SBCS mode and DBCS sub char: change to DBCS */ cnv->fromUnicodeStatus=2; *p++=UCNV_SO; } *p++=subchar[0]; *p++=subchar[1]; break; default: *pErrorCode=U_ILLEGAL_ARGUMENT_ERROR; return; } subchar=buffer; length=(int32_t)(p-buffer); } ucnv_cbFromUWriteBytes(pArgs, subchar, length, offsetIndex, pErrorCode); } U_CFUNC UConverterType ucnv_MBCSGetType(const UConverter* converter) { /* SBCS, DBCS, and EBCDIC_STATEFUL are replaced by MBCS, but here we cheat a little */ if(converter->sharedData->mbcs.countStates==1) { return (UConverterType)UCNV_SBCS; } else if((converter->sharedData->mbcs.outputType&0xff)==MBCS_OUTPUT_2_SISO) { return (UConverterType)UCNV_EBCDIC_STATEFUL; } else if(converter->sharedData->staticData->minBytesPerChar==2 && converter->sharedData->staticData->maxBytesPerChar==2) { return (UConverterType)UCNV_DBCS; } return (UConverterType)UCNV_MBCS; } #endif /* #if !UCONFIG_NO_LEGACY_CONVERSION */
38.98185
131
0.51926
[ "object" ]
4f80a0331aaf637b2c6965bfd5abdf3c2f17a314
3,773
cpp
C++
src/cryptonote_core/tx_sanity_check.cpp
blackrangersoftware/brs-italo-core
0837150243470bb45b388aea376cc1c12479fd91
[ "BSD-3-Clause" ]
null
null
null
src/cryptonote_core/tx_sanity_check.cpp
blackrangersoftware/brs-italo-core
0837150243470bb45b388aea376cc1c12479fd91
[ "BSD-3-Clause" ]
null
null
null
src/cryptonote_core/tx_sanity_check.cpp
blackrangersoftware/brs-italo-core
0837150243470bb45b388aea376cc1c12479fd91
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2019, The Monero And Italo Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <stdint.h> #include <vector> #include "cryptonote_basic/cryptonote_basic.h" #include "cryptonote_basic/cryptonote_format_utils.h" #include "blockchain.h" #include "tx_sanity_check.h" #undef MONERO_DEFAULT_LOG_CATEGORY #define MONERO_DEFAULT_LOG_CATEGORY "verify" namespace cryptonote { bool tx_sanity_check(const cryptonote::blobdata &tx_blob, uint64_t rct_outs_available) { cryptonote::transaction tx; if (!cryptonote::parse_and_validate_tx_from_blob(tx_blob, tx)) { MERROR("Failed to parse transaction"); return false; } if (cryptonote::is_coinbase(tx)) { MERROR("Transaction is coinbase"); return false; } std::set<uint64_t> rct_indices; size_t n_indices = 0; for (const auto &txin : tx.vin) { if (txin.type() != typeid(cryptonote::txin_to_key)) continue; const cryptonote::txin_to_key &in_to_key = boost::get<cryptonote::txin_to_key>(txin); if (in_to_key.amount != 0) continue; const std::vector<uint64_t> absolute = cryptonote::relative_output_offsets_to_absolute(in_to_key.key_offsets); for (uint64_t offset: absolute) rct_indices.insert(offset); n_indices += in_to_key.key_offsets.size(); } return tx_sanity_check(rct_indices, n_indices, rct_outs_available); } bool tx_sanity_check(const std::set<uint64_t> &rct_indices, size_t n_indices, uint64_t rct_outs_available) { if (n_indices <= 10) { MDEBUG("n_indices is only " << n_indices << ", not checking"); return true; } if (rct_outs_available < 10000) return true; if (rct_indices.size() < n_indices * 8 / 10) { MERROR("amount of unique indices is too low (amount of rct indices is " << rct_indices.size() << ", out of total " << n_indices << "indices."); return false; } std::vector<uint64_t> offsets(rct_indices.begin(), rct_indices.end()); uint64_t median = epee::misc_utils::median(offsets); if (median < rct_outs_available * 6 / 10) { MERROR("median offset index is too low (median is " << median << " out of total " << rct_outs_available << "offsets). Transactions should contain a higher fraction of recent outputs."); return false; } return true; } }
36.278846
189
0.732839
[ "vector" ]
4f8163031032883c7cedd5385e39458f63a716bb
250,055
cc
C++
quic/core/quic_framer.cc
linjunmian/quiche
4b63155d124a94c1505233de72b4123bb5858b6c
[ "BSD-3-Clause" ]
null
null
null
quic/core/quic_framer.cc
linjunmian/quiche
4b63155d124a94c1505233de72b4123bb5858b6c
[ "BSD-3-Clause" ]
null
null
null
quic/core/quic_framer.cc
linjunmian/quiche
4b63155d124a94c1505233de72b4123bb5858b6c
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "quic/core/quic_framer.h" #include <cstddef> #include <cstdint> #include <limits> #include <memory> #include <string> #include <utility> #include "quic/core/crypto/crypto_framer.h" #include "quic/core/crypto/crypto_handshake.h" #include "quic/core/crypto/crypto_handshake_message.h" #include "quic/core/crypto/crypto_protocol.h" #include "quic/core/crypto/crypto_utils.h" #include "quic/core/crypto/null_decrypter.h" #include "quic/core/crypto/null_encrypter.h" #include "quic/core/crypto/quic_decrypter.h" #include "quic/core/crypto/quic_encrypter.h" #include "quic/core/crypto/quic_random.h" #include "quic/core/frames/quic_ack_frequency_frame.h" #include "quic/core/quic_connection_id.h" #include "quic/core/quic_constants.h" #include "quic/core/quic_data_reader.h" #include "quic/core/quic_data_writer.h" #include "quic/core/quic_error_codes.h" #include "quic/core/quic_packets.h" #include "quic/core/quic_socket_address_coder.h" #include "quic/core/quic_stream_frame_data_producer.h" #include "quic/core/quic_time.h" #include "quic/core/quic_types.h" #include "quic/core/quic_utils.h" #include "quic/core/quic_versions.h" #include "quic/platform/api/quic_aligned.h" #include "quic/platform/api/quic_bug_tracker.h" #include "quic/platform/api/quic_client_stats.h" #include "quic/platform/api/quic_fallthrough.h" #include "quic/platform/api/quic_flag_utils.h" #include "quic/platform/api/quic_flags.h" #include "quic/platform/api/quic_logging.h" #include "quic/platform/api/quic_map_util.h" #include "quic/platform/api/quic_stack_trace.h" #include "common/platform/api/quiche_arraysize.h" #include "common/platform/api/quiche_str_cat.h" #include "common/platform/api/quiche_string_piece.h" #include "common/platform/api/quiche_text_utils.h" namespace quic { namespace { #define ENDPOINT \ (perspective_ == Perspective::IS_SERVER ? "Server: " : "Client: ") // Number of bits the packet number length bits are shifted from the right // edge of the header. const uint8_t kPublicHeaderSequenceNumberShift = 4; // There are two interpretations for the Frame Type byte in the QUIC protocol, // resulting in two Frame Types: Special Frame Types and Regular Frame Types. // // Regular Frame Types use the Frame Type byte simply. Currently defined // Regular Frame Types are: // Padding : 0b 00000000 (0x00) // ResetStream : 0b 00000001 (0x01) // ConnectionClose : 0b 00000010 (0x02) // GoAway : 0b 00000011 (0x03) // WindowUpdate : 0b 00000100 (0x04) // Blocked : 0b 00000101 (0x05) // // Special Frame Types encode both a Frame Type and corresponding flags // all in the Frame Type byte. Currently defined Special Frame Types // are: // Stream : 0b 1xxxxxxx // Ack : 0b 01xxxxxx // // Semantics of the flag bits above (the x bits) depends on the frame type. // Masks to determine if the frame type is a special use // and for specific special frame types. const uint8_t kQuicFrameTypeBrokenMask = 0xE0; // 0b 11100000 const uint8_t kQuicFrameTypeSpecialMask = 0xC0; // 0b 11000000 const uint8_t kQuicFrameTypeStreamMask = 0x80; const uint8_t kQuicFrameTypeAckMask = 0x40; static_assert(kQuicFrameTypeSpecialMask == (kQuicFrameTypeStreamMask | kQuicFrameTypeAckMask), "Invalid kQuicFrameTypeSpecialMask"); // The stream type format is 1FDOOOSS, where // F is the fin bit. // D is the data length bit (0 or 2 bytes). // OO/OOO are the size of the offset. // SS is the size of the stream ID. // Note that the stream encoding can not be determined by inspection. It can // be determined only by knowing the QUIC Version. // Stream frame relative shifts and masks for interpreting the stream flags. // StreamID may be 1, 2, 3, or 4 bytes. const uint8_t kQuicStreamIdShift = 2; const uint8_t kQuicStreamIDLengthMask = 0x03; // Offset may be 0, 2, 4, or 8 bytes. const uint8_t kQuicStreamShift = 3; const uint8_t kQuicStreamOffsetMask = 0x07; // Data length may be 0 or 2 bytes. const uint8_t kQuicStreamDataLengthShift = 1; const uint8_t kQuicStreamDataLengthMask = 0x01; // Fin bit may be set or not. const uint8_t kQuicStreamFinShift = 1; const uint8_t kQuicStreamFinMask = 0x01; // The format is 01M0LLOO, where // M if set, there are multiple ack blocks in the frame. // LL is the size of the largest ack field. // OO is the size of the ack blocks offset field. // packet number size shift used in AckFrames. const uint8_t kQuicSequenceNumberLengthNumBits = 2; const uint8_t kActBlockLengthOffset = 0; const uint8_t kLargestAckedOffset = 2; // Acks may have only one ack block. const uint8_t kQuicHasMultipleAckBlocksOffset = 5; // Timestamps are 4 bytes followed by 2 bytes. const uint8_t kQuicNumTimestampsLength = 1; const uint8_t kQuicFirstTimestampLength = 4; const uint8_t kQuicTimestampLength = 2; // Gaps between packet numbers are 1 byte. const uint8_t kQuicTimestampPacketNumberGapLength = 1; // Maximum length of encoded error strings. const int kMaxErrorStringLength = 256; const uint8_t kConnectionIdLengthAdjustment = 3; const uint8_t kDestinationConnectionIdLengthMask = 0xF0; const uint8_t kSourceConnectionIdLengthMask = 0x0F; // Returns the absolute value of the difference between |a| and |b|. uint64_t Delta(uint64_t a, uint64_t b) { // Since these are unsigned numbers, we can't just return abs(a - b) if (a < b) { return b - a; } return a - b; } uint64_t ClosestTo(uint64_t target, uint64_t a, uint64_t b) { return (Delta(target, a) < Delta(target, b)) ? a : b; } QuicPacketNumberLength ReadSequenceNumberLength(uint8_t flags) { switch (flags & PACKET_FLAGS_8BYTE_PACKET) { case PACKET_FLAGS_8BYTE_PACKET: return PACKET_6BYTE_PACKET_NUMBER; case PACKET_FLAGS_4BYTE_PACKET: return PACKET_4BYTE_PACKET_NUMBER; case PACKET_FLAGS_2BYTE_PACKET: return PACKET_2BYTE_PACKET_NUMBER; case PACKET_FLAGS_1BYTE_PACKET: return PACKET_1BYTE_PACKET_NUMBER; default: QUIC_BUG << "Unreachable case statement."; return PACKET_6BYTE_PACKET_NUMBER; } } QuicPacketNumberLength ReadAckPacketNumberLength( uint8_t flags) { switch (flags & PACKET_FLAGS_8BYTE_PACKET) { case PACKET_FLAGS_8BYTE_PACKET: return PACKET_6BYTE_PACKET_NUMBER; case PACKET_FLAGS_4BYTE_PACKET: return PACKET_4BYTE_PACKET_NUMBER; case PACKET_FLAGS_2BYTE_PACKET: return PACKET_2BYTE_PACKET_NUMBER; case PACKET_FLAGS_1BYTE_PACKET: return PACKET_1BYTE_PACKET_NUMBER; default: QUIC_BUG << "Unreachable case statement."; return PACKET_6BYTE_PACKET_NUMBER; } } uint8_t PacketNumberLengthToOnWireValue( QuicPacketNumberLength packet_number_length) { return packet_number_length - 1; } QuicPacketNumberLength GetShortHeaderPacketNumberLength(uint8_t type) { DCHECK(!(type & FLAGS_LONG_HEADER)); return static_cast<QuicPacketNumberLength>((type & 0x03) + 1); } uint8_t LongHeaderTypeToOnWireValue(QuicLongHeaderType type) { switch (type) { case INITIAL: return 0; case ZERO_RTT_PROTECTED: return 1 << 4; case HANDSHAKE: return 2 << 4; case RETRY: return 3 << 4; case VERSION_NEGOTIATION: return 0xF0; // Value does not matter default: QUIC_BUG << "Invalid long header type: " << type; return 0xFF; } } bool GetLongHeaderType(uint8_t type, QuicLongHeaderType* long_header_type) { DCHECK((type & FLAGS_LONG_HEADER)); switch ((type & 0x30) >> 4) { case 0: *long_header_type = INITIAL; break; case 1: *long_header_type = ZERO_RTT_PROTECTED; break; case 2: *long_header_type = HANDSHAKE; break; case 3: *long_header_type = RETRY; break; default: QUIC_BUG << "Unreachable statement"; *long_header_type = INVALID_PACKET_TYPE; return false; } return true; } QuicPacketNumberLength GetLongHeaderPacketNumberLength(uint8_t type) { return static_cast<QuicPacketNumberLength>((type & 0x03) + 1); } // Used to get packet number space before packet gets decrypted. PacketNumberSpace GetPacketNumberSpace(const QuicPacketHeader& header) { switch (header.form) { case GOOGLE_QUIC_PACKET: QUIC_BUG << "Try to get packet number space of Google QUIC packet"; break; case IETF_QUIC_SHORT_HEADER_PACKET: return APPLICATION_DATA; case IETF_QUIC_LONG_HEADER_PACKET: switch (header.long_packet_type) { case INITIAL: return INITIAL_DATA; case HANDSHAKE: return HANDSHAKE_DATA; case ZERO_RTT_PROTECTED: return APPLICATION_DATA; case VERSION_NEGOTIATION: case RETRY: case INVALID_PACKET_TYPE: QUIC_BUG << "Try to get packet number space of long header type: " << QuicUtils::QuicLongHeaderTypetoString( header.long_packet_type); break; } } return NUM_PACKET_NUMBER_SPACES; } EncryptionLevel GetEncryptionLevel(const QuicPacketHeader& header) { switch (header.form) { case GOOGLE_QUIC_PACKET: QUIC_BUG << "Cannot determine EncryptionLevel from Google QUIC header"; break; case IETF_QUIC_SHORT_HEADER_PACKET: return ENCRYPTION_FORWARD_SECURE; case IETF_QUIC_LONG_HEADER_PACKET: switch (header.long_packet_type) { case INITIAL: return ENCRYPTION_INITIAL; case HANDSHAKE: return ENCRYPTION_HANDSHAKE; case ZERO_RTT_PROTECTED: return ENCRYPTION_ZERO_RTT; case VERSION_NEGOTIATION: case RETRY: case INVALID_PACKET_TYPE: QUIC_BUG << "No encryption used with type " << QuicUtils::QuicLongHeaderTypetoString( header.long_packet_type); } } return NUM_ENCRYPTION_LEVELS; } quiche::QuicheStringPiece TruncateErrorString(quiche::QuicheStringPiece error) { if (error.length() <= kMaxErrorStringLength) { return error; } return quiche::QuicheStringPiece(error.data(), kMaxErrorStringLength); } size_t TruncatedErrorStringSize(const quiche::QuicheStringPiece& error) { if (error.length() < kMaxErrorStringLength) { return error.length(); } return kMaxErrorStringLength; } uint8_t GetConnectionIdLengthValue(QuicConnectionIdLength length) { if (length == 0) { return 0; } return static_cast<uint8_t>(length - kConnectionIdLengthAdjustment); } bool IsValidPacketNumberLength(QuicPacketNumberLength packet_number_length) { size_t length = packet_number_length; return length == 1 || length == 2 || length == 4 || length == 6 || length == 8; } bool IsValidFullPacketNumber(uint64_t full_packet_number, ParsedQuicVersion version) { return full_packet_number > 0 || version.HasIetfQuicFrames(); } bool AppendIetfConnectionIds(bool version_flag, bool use_length_prefix, QuicConnectionId destination_connection_id, QuicConnectionId source_connection_id, QuicDataWriter* writer) { if (!version_flag) { return writer->WriteConnectionId(destination_connection_id); } if (use_length_prefix) { return writer->WriteLengthPrefixedConnectionId(destination_connection_id) && writer->WriteLengthPrefixedConnectionId(source_connection_id); } // Compute connection ID length byte. uint8_t dcil = GetConnectionIdLengthValue( static_cast<QuicConnectionIdLength>(destination_connection_id.length())); uint8_t scil = GetConnectionIdLengthValue( static_cast<QuicConnectionIdLength>(source_connection_id.length())); uint8_t connection_id_length = dcil << 4 | scil; return writer->WriteUInt8(connection_id_length) && writer->WriteConnectionId(destination_connection_id) && writer->WriteConnectionId(source_connection_id); } enum class DroppedPacketReason { // General errors INVALID_PUBLIC_HEADER, VERSION_MISMATCH, // Version negotiation packet errors INVALID_VERSION_NEGOTIATION_PACKET, // Public reset packet errors, pre-v44 INVALID_PUBLIC_RESET_PACKET, // Data packet errors INVALID_PACKET_NUMBER, INVALID_DIVERSIFICATION_NONCE, DECRYPTION_FAILURE, NUM_REASONS, }; void RecordDroppedPacketReason(DroppedPacketReason reason) { QUIC_CLIENT_HISTOGRAM_ENUM("QuicDroppedPacketReason", reason, DroppedPacketReason::NUM_REASONS, "The reason a packet was not processed. Recorded " "each time such a packet is dropped"); } PacketHeaderFormat GetIetfPacketHeaderFormat(uint8_t type_byte) { return type_byte & FLAGS_LONG_HEADER ? IETF_QUIC_LONG_HEADER_PACKET : IETF_QUIC_SHORT_HEADER_PACKET; } std::string GenerateErrorString(std::string initial_error_string, QuicErrorCode quic_error_code) { if (quic_error_code == QUIC_IETF_GQUIC_ERROR_MISSING) { // QUIC_IETF_GQUIC_ERROR_MISSING is special -- it means not to encode // the error value in the string. return initial_error_string; } return quiche::QuicheStrCat( std::to_string(static_cast<unsigned>(quic_error_code)), ":", initial_error_string); } } // namespace QuicFramer::QuicFramer(const ParsedQuicVersionVector& supported_versions, QuicTime creation_time, Perspective perspective, uint8_t expected_server_connection_id_length) : visitor_(nullptr), error_(QUIC_NO_ERROR), last_serialized_server_connection_id_(EmptyQuicConnectionId()), last_serialized_client_connection_id_(EmptyQuicConnectionId()), version_(ParsedQuicVersion::Unsupported()), supported_versions_(supported_versions), decrypter_level_(ENCRYPTION_INITIAL), alternative_decrypter_level_(NUM_ENCRYPTION_LEVELS), alternative_decrypter_latch_(false), perspective_(perspective), validate_flags_(true), process_timestamps_(false), creation_time_(creation_time), last_timestamp_(QuicTime::Delta::Zero()), first_sending_packet_number_(FirstSendingPacketNumber()), data_producer_(nullptr), infer_packet_header_type_from_version_(perspective == Perspective::IS_CLIENT), expected_server_connection_id_length_( expected_server_connection_id_length), expected_client_connection_id_length_(0), supports_multiple_packet_number_spaces_(false), last_written_packet_number_length_(0), peer_ack_delay_exponent_(kDefaultAckDelayExponent), local_ack_delay_exponent_(kDefaultAckDelayExponent), current_received_frame_type_(0) { DCHECK(!supported_versions.empty()); version_ = supported_versions_[0]; DCHECK(version_.IsKnown()) << ParsedQuicVersionVectorToString(supported_versions_); } QuicFramer::~QuicFramer() {} // static size_t QuicFramer::GetMinStreamFrameSize(QuicTransportVersion version, QuicStreamId stream_id, QuicStreamOffset offset, bool last_frame_in_packet, size_t data_length) { if (VersionHasIetfQuicFrames(version)) { return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(stream_id) + (last_frame_in_packet ? 0 : QuicDataWriter::GetVarInt62Len(data_length)) + (offset != 0 ? QuicDataWriter::GetVarInt62Len(offset) : 0); } return kQuicFrameTypeSize + GetStreamIdSize(stream_id) + GetStreamOffsetSize(offset) + (last_frame_in_packet ? 0 : kQuicStreamPayloadLengthSize); } // static size_t QuicFramer::GetMinCryptoFrameSize(QuicStreamOffset offset, QuicPacketLength data_length) { return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(offset) + QuicDataWriter::GetVarInt62Len(data_length); } // static size_t QuicFramer::GetMessageFrameSize(QuicTransportVersion version, bool last_frame_in_packet, QuicByteCount length) { QUIC_BUG_IF(!VersionSupportsMessageFrames(version)) << "Try to serialize MESSAGE frame in " << version; return kQuicFrameTypeSize + (last_frame_in_packet ? 0 : QuicDataWriter::GetVarInt62Len(length)) + length; } // static size_t QuicFramer::GetMinAckFrameSize(QuicTransportVersion version, const QuicAckFrame& ack_frame, uint32_t local_ack_delay_exponent) { if (VersionHasIetfQuicFrames(version)) { // The minimal ack frame consists of the following fields: Largest // Acknowledged, ACK Delay, 0 ACK Block Count, First ACK Block and ECN // counts. // Type byte + largest acked. size_t min_size = kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(LargestAcked(ack_frame).ToUint64()); // Ack delay. min_size += QuicDataWriter::GetVarInt62Len( ack_frame.ack_delay_time.ToMicroseconds() >> local_ack_delay_exponent); // 0 ack block count. min_size += QuicDataWriter::GetVarInt62Len(0); // First ack block. min_size += QuicDataWriter::GetVarInt62Len( ack_frame.packets.Empty() ? 0 : ack_frame.packets.rbegin()->Length() - 1); // ECN counts. if (ack_frame.ecn_counters_populated && (ack_frame.ect_0_count || ack_frame.ect_1_count || ack_frame.ecn_ce_count)) { min_size += (QuicDataWriter::GetVarInt62Len(ack_frame.ect_0_count) + QuicDataWriter::GetVarInt62Len(ack_frame.ect_1_count) + QuicDataWriter::GetVarInt62Len(ack_frame.ecn_ce_count)); } return min_size; } return kQuicFrameTypeSize + GetMinPacketNumberLength(LargestAcked(ack_frame)) + kQuicDeltaTimeLargestObservedSize + kQuicNumTimestampsSize; } // static size_t QuicFramer::GetStopWaitingFrameSize( QuicPacketNumberLength packet_number_length) { size_t min_size = kQuicFrameTypeSize + packet_number_length; return min_size; } // static size_t QuicFramer::GetRstStreamFrameSize(QuicTransportVersion version, const QuicRstStreamFrame& frame) { if (VersionHasIetfQuicFrames(version)) { return QuicDataWriter::GetVarInt62Len(frame.stream_id) + QuicDataWriter::GetVarInt62Len(frame.byte_offset) + kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.ietf_error_code); } return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize + kQuicErrorCodeSize; } // static size_t QuicFramer::GetConnectionCloseFrameSize( QuicTransportVersion version, const QuicConnectionCloseFrame& frame) { if (!VersionHasIetfQuicFrames(version)) { // Not IETF QUIC, return Google QUIC CONNECTION CLOSE frame size. return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize + TruncatedErrorStringSize(frame.error_details); } // Prepend the extra error information to the string and get the result's // length. const size_t truncated_error_string_size = TruncatedErrorStringSize( GenerateErrorString(frame.error_details, frame.quic_error_code)); const size_t frame_size = truncated_error_string_size + QuicDataWriter::GetVarInt62Len(truncated_error_string_size) + kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.wire_error_code); if (frame.close_type == IETF_QUIC_APPLICATION_CONNECTION_CLOSE) { return frame_size; } // The Transport close frame has the transport_close_frame_type, so include // its length. return frame_size + QuicDataWriter::GetVarInt62Len(frame.transport_close_frame_type); } // static size_t QuicFramer::GetMinGoAwayFrameSize() { return kQuicFrameTypeSize + kQuicErrorCodeSize + kQuicErrorDetailsLengthSize + kQuicMaxStreamIdSize; } // static size_t QuicFramer::GetWindowUpdateFrameSize( QuicTransportVersion version, const QuicWindowUpdateFrame& frame) { if (!VersionHasIetfQuicFrames(version)) { return kQuicFrameTypeSize + kQuicMaxStreamIdSize + kQuicMaxStreamOffsetSize; } if (frame.stream_id == QuicUtils::GetInvalidStreamId(version)) { // Frame would be a MAX DATA frame, which has only a Maximum Data field. return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.max_data); } // Frame would be MAX STREAM DATA, has Maximum Stream Data and Stream ID // fields. return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.max_data) + QuicDataWriter::GetVarInt62Len(frame.stream_id); } // static size_t QuicFramer::GetMaxStreamsFrameSize(QuicTransportVersion version, const QuicMaxStreamsFrame& frame) { if (!VersionHasIetfQuicFrames(version)) { QUIC_BUG << "In version " << version << ", which does not support IETF Frames, and tried to serialize " "MaxStreams Frame."; } return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.stream_count); } // static size_t QuicFramer::GetStreamsBlockedFrameSize( QuicTransportVersion version, const QuicStreamsBlockedFrame& frame) { if (!VersionHasIetfQuicFrames(version)) { QUIC_BUG << "In version " << version << ", which does not support IETF frames, and tried to serialize " "StreamsBlocked Frame."; } return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.stream_count); } // static size_t QuicFramer::GetBlockedFrameSize(QuicTransportVersion version, const QuicBlockedFrame& frame) { if (!VersionHasIetfQuicFrames(version)) { return kQuicFrameTypeSize + kQuicMaxStreamIdSize; } if (frame.stream_id == QuicUtils::GetInvalidStreamId(version)) { // return size of IETF QUIC Blocked frame return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.offset); } // return size of IETF QUIC Stream Blocked frame. return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.offset) + QuicDataWriter::GetVarInt62Len(frame.stream_id); } // static size_t QuicFramer::GetStopSendingFrameSize(const QuicStopSendingFrame& frame) { return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.stream_id) + QuicDataWriter::GetVarInt62Len(frame.ietf_error_code); } // static size_t QuicFramer::GetAckFrequencyFrameSize( const QuicAckFrequencyFrame& frame) { return QuicDataWriter::GetVarInt62Len(IETF_ACK_FREQUENCY) + QuicDataWriter::GetVarInt62Len(frame.sequence_number) + QuicDataWriter::GetVarInt62Len(frame.packet_tolerance) + QuicDataWriter::GetVarInt62Len(frame.max_ack_delay.ToMicroseconds()) + // One byte for encoding boolean 1; } // static size_t QuicFramer::GetPathChallengeFrameSize( const QuicPathChallengeFrame& frame) { return kQuicFrameTypeSize + sizeof(frame.data_buffer); } // static size_t QuicFramer::GetPathResponseFrameSize( const QuicPathResponseFrame& frame) { return kQuicFrameTypeSize + sizeof(frame.data_buffer); } // static size_t QuicFramer::GetRetransmittableControlFrameSize( QuicTransportVersion version, const QuicFrame& frame) { switch (frame.type) { case PING_FRAME: // Ping has no payload. return kQuicFrameTypeSize; case RST_STREAM_FRAME: return GetRstStreamFrameSize(version, *frame.rst_stream_frame); case CONNECTION_CLOSE_FRAME: return GetConnectionCloseFrameSize(version, *frame.connection_close_frame); case GOAWAY_FRAME: return GetMinGoAwayFrameSize() + TruncatedErrorStringSize(frame.goaway_frame->reason_phrase); case WINDOW_UPDATE_FRAME: // For IETF QUIC, this could be either a MAX DATA or MAX STREAM DATA. // GetWindowUpdateFrameSize figures this out and returns the correct // length. return GetWindowUpdateFrameSize(version, *frame.window_update_frame); case BLOCKED_FRAME: return GetBlockedFrameSize(version, *frame.blocked_frame); case NEW_CONNECTION_ID_FRAME: return GetNewConnectionIdFrameSize(*frame.new_connection_id_frame); case RETIRE_CONNECTION_ID_FRAME: return GetRetireConnectionIdFrameSize(*frame.retire_connection_id_frame); case NEW_TOKEN_FRAME: return GetNewTokenFrameSize(*frame.new_token_frame); case MAX_STREAMS_FRAME: return GetMaxStreamsFrameSize(version, frame.max_streams_frame); case STREAMS_BLOCKED_FRAME: return GetStreamsBlockedFrameSize(version, frame.streams_blocked_frame); case PATH_RESPONSE_FRAME: return GetPathResponseFrameSize(*frame.path_response_frame); case PATH_CHALLENGE_FRAME: return GetPathChallengeFrameSize(*frame.path_challenge_frame); case STOP_SENDING_FRAME: return GetStopSendingFrameSize(*frame.stop_sending_frame); case HANDSHAKE_DONE_FRAME: // HANDSHAKE_DONE has no payload. return kQuicFrameTypeSize; case ACK_FREQUENCY_FRAME: return GetAckFrequencyFrameSize(*frame.ack_frequency_frame); case STREAM_FRAME: case ACK_FRAME: case STOP_WAITING_FRAME: case MTU_DISCOVERY_FRAME: case PADDING_FRAME: case MESSAGE_FRAME: case CRYPTO_FRAME: case NUM_FRAME_TYPES: DCHECK(false); return 0; } // Not reachable, but some Chrome compilers can't figure that out. *sigh* DCHECK(false); return 0; } // static size_t QuicFramer::GetStreamIdSize(QuicStreamId stream_id) { // Sizes are 1 through 4 bytes. for (int i = 1; i <= 4; ++i) { stream_id >>= 8; if (stream_id == 0) { return i; } } QUIC_BUG << "Failed to determine StreamIDSize."; return 4; } // static size_t QuicFramer::GetStreamOffsetSize(QuicStreamOffset offset) { // 0 is a special case. if (offset == 0) { return 0; } // 2 through 8 are the remaining sizes. offset >>= 8; for (int i = 2; i <= 8; ++i) { offset >>= 8; if (offset == 0) { return i; } } QUIC_BUG << "Failed to determine StreamOffsetSize."; return 8; } // static size_t QuicFramer::GetNewConnectionIdFrameSize( const QuicNewConnectionIdFrame& frame) { return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.sequence_number) + QuicDataWriter::GetVarInt62Len(frame.retire_prior_to) + kConnectionIdLengthSize + frame.connection_id.length() + sizeof(frame.stateless_reset_token); } // static size_t QuicFramer::GetRetireConnectionIdFrameSize( const QuicRetireConnectionIdFrame& frame) { return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.sequence_number); } // static size_t QuicFramer::GetNewTokenFrameSize(const QuicNewTokenFrame& frame) { return kQuicFrameTypeSize + QuicDataWriter::GetVarInt62Len(frame.token.length()) + frame.token.length(); } // TODO(nharper): Change this method to take a ParsedQuicVersion. bool QuicFramer::IsSupportedTransportVersion( const QuicTransportVersion version) const { for (const ParsedQuicVersion& supported_version : supported_versions_) { if (version == supported_version.transport_version) { return true; } } return false; } bool QuicFramer::IsSupportedVersion(const ParsedQuicVersion version) const { for (const ParsedQuicVersion& supported_version : supported_versions_) { if (version == supported_version) { return true; } } return false; } size_t QuicFramer::GetSerializedFrameLength( const QuicFrame& frame, size_t free_bytes, bool first_frame, bool last_frame, QuicPacketNumberLength packet_number_length) { // Prevent a rare crash reported in b/19458523. if (frame.type == ACK_FRAME && frame.ack_frame == nullptr) { QUIC_BUG << "Cannot compute the length of a null ack frame. free_bytes:" << free_bytes << " first_frame:" << first_frame << " last_frame:" << last_frame << " seq num length:" << packet_number_length; set_error(QUIC_INTERNAL_ERROR); visitor_->OnError(this); return 0; } if (frame.type == PADDING_FRAME) { if (frame.padding_frame.num_padding_bytes == -1) { // Full padding to the end of the packet. return free_bytes; } else { // Lite padding. return free_bytes < static_cast<size_t>(frame.padding_frame.num_padding_bytes) ? free_bytes : frame.padding_frame.num_padding_bytes; } } size_t frame_len = ComputeFrameLength(frame, last_frame, packet_number_length); if (frame_len <= free_bytes) { // Frame fits within packet. Note that acks may be truncated. return frame_len; } // Only truncate the first frame in a packet, so if subsequent ones go // over, stop including more frames. if (!first_frame) { return 0; } bool can_truncate = frame.type == ACK_FRAME && free_bytes >= GetMinAckFrameSize(version_.transport_version, *frame.ack_frame, local_ack_delay_exponent_); if (can_truncate) { // Truncate the frame so the packet will not exceed kMaxOutgoingPacketSize. // Note that we may not use every byte of the writer in this case. QUIC_DLOG(INFO) << ENDPOINT << "Truncating large frame, free bytes: " << free_bytes; return free_bytes; } return 0; } QuicFramer::AckFrameInfo::AckFrameInfo() : max_block_length(0), first_block_length(0), num_ack_blocks(0) {} QuicFramer::AckFrameInfo::AckFrameInfo(const AckFrameInfo& other) = default; QuicFramer::AckFrameInfo::~AckFrameInfo() {} bool QuicFramer::WriteIetfLongHeaderLength(const QuicPacketHeader& header, QuicDataWriter* writer, size_t length_field_offset, EncryptionLevel level) { if (!QuicVersionHasLongHeaderLengths(transport_version()) || !header.version_flag || length_field_offset == 0) { return true; } if (writer->length() < length_field_offset || writer->length() - length_field_offset < kQuicDefaultLongHeaderLengthLength) { set_detailed_error("Invalid length_field_offset."); QUIC_BUG << "Invalid length_field_offset."; return false; } size_t length_to_write = writer->length() - length_field_offset - kQuicDefaultLongHeaderLengthLength; // Add length of auth tag. length_to_write = GetCiphertextSize(level, length_to_write); QuicDataWriter length_writer(writer->length() - length_field_offset, writer->data() + length_field_offset); if (!length_writer.WriteVarInt62(length_to_write, kQuicDefaultLongHeaderLengthLength)) { set_detailed_error("Failed to overwrite long header length."); QUIC_BUG << "Failed to overwrite long header length."; return false; } return true; } size_t QuicFramer::BuildDataPacket(const QuicPacketHeader& header, const QuicFrames& frames, char* buffer, size_t packet_length, EncryptionLevel level) { QUIC_BUG_IF(header.version_flag && VersionHasIetfInvariantHeader(transport_version()) && header.long_packet_type == RETRY && !frames.empty()) << "IETF RETRY packets cannot contain frames " << header; QuicDataWriter writer(packet_length, buffer); size_t length_field_offset = 0; if (!AppendPacketHeader(header, &writer, &length_field_offset)) { QUIC_BUG << "AppendPacketHeader failed"; return 0; } if (VersionHasIetfQuicFrames(transport_version())) { if (AppendIetfFrames(frames, &writer) == 0) { return 0; } if (!WriteIetfLongHeaderLength(header, &writer, length_field_offset, level)) { return 0; } return writer.length(); } size_t i = 0; for (const QuicFrame& frame : frames) { // Determine if we should write stream frame length in header. const bool last_frame_in_packet = i == frames.size() - 1; if (!AppendTypeByte(frame, last_frame_in_packet, &writer)) { QUIC_BUG << "AppendTypeByte failed"; return 0; } switch (frame.type) { case PADDING_FRAME: if (!AppendPaddingFrame(frame.padding_frame, &writer)) { QUIC_BUG << "AppendPaddingFrame of " << frame.padding_frame.num_padding_bytes << " failed"; return 0; } break; case STREAM_FRAME: if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet, &writer)) { QUIC_BUG << "AppendStreamFrame failed"; return 0; } break; case ACK_FRAME: if (!AppendAckFrameAndTypeByte(*frame.ack_frame, &writer)) { QUIC_BUG << "AppendAckFrameAndTypeByte failed: " << detailed_error_; return 0; } break; case STOP_WAITING_FRAME: if (!AppendStopWaitingFrame(header, frame.stop_waiting_frame, &writer)) { QUIC_BUG << "AppendStopWaitingFrame failed"; return 0; } break; case MTU_DISCOVERY_FRAME: // MTU discovery frames are serialized as ping frames. QUIC_FALLTHROUGH_INTENDED; case PING_FRAME: // Ping has no payload. break; case RST_STREAM_FRAME: if (!AppendRstStreamFrame(*frame.rst_stream_frame, &writer)) { QUIC_BUG << "AppendRstStreamFrame failed"; return 0; } break; case CONNECTION_CLOSE_FRAME: if (!AppendConnectionCloseFrame(*frame.connection_close_frame, &writer)) { QUIC_BUG << "AppendConnectionCloseFrame failed"; return 0; } break; case GOAWAY_FRAME: if (!AppendGoAwayFrame(*frame.goaway_frame, &writer)) { QUIC_BUG << "AppendGoAwayFrame failed"; return 0; } break; case WINDOW_UPDATE_FRAME: if (!AppendWindowUpdateFrame(*frame.window_update_frame, &writer)) { QUIC_BUG << "AppendWindowUpdateFrame failed"; return 0; } break; case BLOCKED_FRAME: if (!AppendBlockedFrame(*frame.blocked_frame, &writer)) { QUIC_BUG << "AppendBlockedFrame failed"; return 0; } break; case NEW_CONNECTION_ID_FRAME: set_detailed_error( "Attempt to append NEW_CONNECTION_ID frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case RETIRE_CONNECTION_ID_FRAME: set_detailed_error( "Attempt to append RETIRE_CONNECTION_ID frame and not in IETF " "QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case NEW_TOKEN_FRAME: set_detailed_error( "Attempt to append NEW_TOKEN_ID frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case MAX_STREAMS_FRAME: set_detailed_error( "Attempt to append MAX_STREAMS frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case STREAMS_BLOCKED_FRAME: set_detailed_error( "Attempt to append STREAMS_BLOCKED frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case PATH_RESPONSE_FRAME: set_detailed_error( "Attempt to append PATH_RESPONSE frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case PATH_CHALLENGE_FRAME: set_detailed_error( "Attempt to append PATH_CHALLENGE frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case STOP_SENDING_FRAME: set_detailed_error( "Attempt to append STOP_SENDING frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case MESSAGE_FRAME: if (!AppendMessageFrameAndTypeByte(*frame.message_frame, last_frame_in_packet, &writer)) { QUIC_BUG << "AppendMessageFrame failed"; return 0; } break; case CRYPTO_FRAME: if (!QuicVersionUsesCryptoFrames(version_.transport_version)) { set_detailed_error( "Attempt to append CRYPTO frame in version prior to 47."); return RaiseError(QUIC_INTERNAL_ERROR); } if (!AppendCryptoFrame(*frame.crypto_frame, &writer)) { QUIC_BUG << "AppendCryptoFrame failed"; return 0; } break; case HANDSHAKE_DONE_FRAME: // HANDSHAKE_DONE has no payload. break; default: RaiseError(QUIC_INVALID_FRAME_DATA); QUIC_BUG << "QUIC_INVALID_FRAME_DATA"; return 0; } ++i; } if (!WriteIetfLongHeaderLength(header, &writer, length_field_offset, level)) { return 0; } return writer.length(); } size_t QuicFramer::AppendIetfFrames(const QuicFrames& frames, QuicDataWriter* writer) { size_t i = 0; for (const QuicFrame& frame : frames) { // Determine if we should write stream frame length in header. const bool last_frame_in_packet = i == frames.size() - 1; if (!AppendIetfFrameType(frame, last_frame_in_packet, writer)) { QUIC_BUG << "AppendIetfFrameType failed: " << detailed_error(); return 0; } switch (frame.type) { case PADDING_FRAME: if (!AppendPaddingFrame(frame.padding_frame, writer)) { QUIC_BUG << "AppendPaddingFrame of " << frame.padding_frame.num_padding_bytes << " failed: " << detailed_error(); return 0; } break; case STREAM_FRAME: if (!AppendStreamFrame(frame.stream_frame, last_frame_in_packet, writer)) { QUIC_BUG << "AppendStreamFrame failed: " << detailed_error(); return 0; } break; case ACK_FRAME: if (!AppendIetfAckFrameAndTypeByte(*frame.ack_frame, writer)) { QUIC_BUG << "AppendIetfAckFrameAndTypeByte failed: " << detailed_error(); return 0; } break; case STOP_WAITING_FRAME: set_detailed_error( "Attempt to append STOP WAITING frame in IETF QUIC."); RaiseError(QUIC_INTERNAL_ERROR); QUIC_BUG << detailed_error(); return 0; case MTU_DISCOVERY_FRAME: // MTU discovery frames are serialized as ping frames. QUIC_FALLTHROUGH_INTENDED; case PING_FRAME: // Ping has no payload. break; case RST_STREAM_FRAME: if (!AppendRstStreamFrame(*frame.rst_stream_frame, writer)) { QUIC_BUG << "AppendRstStreamFrame failed: " << detailed_error(); return 0; } break; case CONNECTION_CLOSE_FRAME: if (!AppendIetfConnectionCloseFrame(*frame.connection_close_frame, writer)) { QUIC_BUG << "AppendIetfConnectionCloseFrame failed: " << detailed_error(); return 0; } break; case GOAWAY_FRAME: set_detailed_error("Attempt to append GOAWAY frame in IETF QUIC."); RaiseError(QUIC_INTERNAL_ERROR); QUIC_BUG << detailed_error(); return 0; case WINDOW_UPDATE_FRAME: // Depending on whether there is a stream ID or not, will be either a // MAX STREAM DATA frame or a MAX DATA frame. if (frame.window_update_frame->stream_id == QuicUtils::GetInvalidStreamId(transport_version())) { if (!AppendMaxDataFrame(*frame.window_update_frame, writer)) { QUIC_BUG << "AppendMaxDataFrame failed: " << detailed_error(); return 0; } } else { if (!AppendMaxStreamDataFrame(*frame.window_update_frame, writer)) { QUIC_BUG << "AppendMaxStreamDataFrame failed: " << detailed_error(); return 0; } } break; case BLOCKED_FRAME: if (!AppendBlockedFrame(*frame.blocked_frame, writer)) { QUIC_BUG << "AppendBlockedFrame failed: " << detailed_error(); return 0; } break; case MAX_STREAMS_FRAME: if (!AppendMaxStreamsFrame(frame.max_streams_frame, writer)) { QUIC_BUG << "AppendMaxStreamsFrame failed: " << detailed_error(); return 0; } break; case STREAMS_BLOCKED_FRAME: if (!AppendStreamsBlockedFrame(frame.streams_blocked_frame, writer)) { QUIC_BUG << "AppendStreamsBlockedFrame failed: " << detailed_error(); return 0; } break; case NEW_CONNECTION_ID_FRAME: if (!AppendNewConnectionIdFrame(*frame.new_connection_id_frame, writer)) { QUIC_BUG << "AppendNewConnectionIdFrame failed: " << detailed_error(); return 0; } break; case RETIRE_CONNECTION_ID_FRAME: if (!AppendRetireConnectionIdFrame(*frame.retire_connection_id_frame, writer)) { QUIC_BUG << "AppendRetireConnectionIdFrame failed: " << detailed_error(); return 0; } break; case NEW_TOKEN_FRAME: if (!AppendNewTokenFrame(*frame.new_token_frame, writer)) { QUIC_BUG << "AppendNewTokenFrame failed: " << detailed_error(); return 0; } break; case STOP_SENDING_FRAME: if (!AppendStopSendingFrame(*frame.stop_sending_frame, writer)) { QUIC_BUG << "AppendStopSendingFrame failed: " << detailed_error(); return 0; } break; case PATH_CHALLENGE_FRAME: if (!AppendPathChallengeFrame(*frame.path_challenge_frame, writer)) { QUIC_BUG << "AppendPathChallengeFrame failed: " << detailed_error(); return 0; } break; case PATH_RESPONSE_FRAME: if (!AppendPathResponseFrame(*frame.path_response_frame, writer)) { QUIC_BUG << "AppendPathResponseFrame failed: " << detailed_error(); return 0; } break; case MESSAGE_FRAME: if (!AppendMessageFrameAndTypeByte(*frame.message_frame, last_frame_in_packet, writer)) { QUIC_BUG << "AppendMessageFrame failed: " << detailed_error(); return 0; } break; case CRYPTO_FRAME: if (!AppendCryptoFrame(*frame.crypto_frame, writer)) { QUIC_BUG << "AppendCryptoFrame failed: " << detailed_error(); return 0; } break; case HANDSHAKE_DONE_FRAME: // HANDSHAKE_DONE has no payload. break; case ACK_FREQUENCY_FRAME: if (!AppendAckFrequencyFrame(*frame.ack_frequency_frame, writer)) { QUIC_BUG << "AppendAckFrequencyFrame failed: " << detailed_error(); return 0; } break; default: set_detailed_error("Tried to append unknown frame type."); RaiseError(QUIC_INVALID_FRAME_DATA); QUIC_BUG << "QUIC_INVALID_FRAME_DATA: " << frame.type; return 0; } ++i; } return writer->length(); } // static std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildPublicResetPacket( const QuicPublicResetPacket& packet) { CryptoHandshakeMessage reset; reset.set_tag(kPRST); reset.SetValue(kRNON, packet.nonce_proof); if (packet.client_address.host().address_family() != IpAddressFamily::IP_UNSPEC) { // packet.client_address is non-empty. QuicSocketAddressCoder address_coder(packet.client_address); std::string serialized_address = address_coder.Encode(); if (serialized_address.empty()) { return nullptr; } reset.SetStringPiece(kCADR, serialized_address); } if (!packet.endpoint_id.empty()) { reset.SetStringPiece(kEPID, packet.endpoint_id); } const QuicData& reset_serialized = reset.GetSerialized(); size_t len = kPublicFlagsSize + packet.connection_id.length() + reset_serialized.length(); std::unique_ptr<char[]> buffer(new char[len]); QuicDataWriter writer(len, buffer.get()); uint8_t flags = static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_RST | PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID); // This hack makes post-v33 public reset packet look like pre-v33 packets. flags |= static_cast<uint8_t>(PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD); if (!writer.WriteUInt8(flags)) { return nullptr; } if (!writer.WriteConnectionId(packet.connection_id)) { return nullptr; } if (!writer.WriteBytes(reset_serialized.data(), reset_serialized.length())) { return nullptr; } return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true); } // static std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildIetfStatelessResetPacket( QuicConnectionId /*connection_id*/, QuicUint128 stateless_reset_token) { QUIC_DVLOG(1) << "Building IETF stateless reset packet."; size_t len = kPacketHeaderTypeSize + kMinRandomBytesLengthInStatelessReset + sizeof(stateless_reset_token); std::unique_ptr<char[]> buffer(new char[len]); QuicDataWriter writer(len, buffer.get()); uint8_t type = 0; type |= FLAGS_FIXED_BIT; type |= FLAGS_SHORT_HEADER_RESERVED_1; type |= FLAGS_SHORT_HEADER_RESERVED_2; type |= PacketNumberLengthToOnWireValue(PACKET_1BYTE_PACKET_NUMBER); // Append type byte. if (!writer.WriteUInt8(type)) { return nullptr; } // Append random bytes. if (!writer.WriteRandomBytes(QuicRandom::GetInstance(), kMinRandomBytesLengthInStatelessReset)) { return nullptr; } // Append stateless reset token. if (!writer.WriteBytes(&stateless_reset_token, sizeof(stateless_reset_token))) { return nullptr; } return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true); } // static std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildVersionNegotiationPacket( QuicConnectionId server_connection_id, QuicConnectionId client_connection_id, bool ietf_quic, bool use_length_prefix, const ParsedQuicVersionVector& versions) { ParsedQuicVersionVector wire_versions = versions; // Add a version reserved for negotiation as suggested by the // "Using Reserved Versions" section of draft-ietf-quic-transport. if (wire_versions.empty()) { // Ensure that version negotiation packets we send have at least two // versions. This guarantees that, under all circumstances, all QUIC // packets we send are at least 14 bytes long. wire_versions = {QuicVersionReservedForNegotiation(), QuicVersionReservedForNegotiation()}; } else { // This is not uniformely distributed but is acceptable since no security // depends on this randomness. size_t version_index = 0; const bool disable_randomness = GetQuicFlag(FLAGS_quic_disable_version_negotiation_grease_randomness); if (!disable_randomness) { version_index = QuicRandom::GetInstance()->RandUint64() % (wire_versions.size() + 1); } wire_versions.insert(wire_versions.begin() + version_index, QuicVersionReservedForNegotiation()); } if (ietf_quic) { return BuildIetfVersionNegotiationPacket( use_length_prefix, server_connection_id, client_connection_id, wire_versions); } // The GQUIC encoding does not support encoding client connection IDs. DCHECK(client_connection_id.IsEmpty()); // The GQUIC encoding does not support length-prefixed connection IDs. DCHECK(!use_length_prefix); DCHECK(!wire_versions.empty()); size_t len = kPublicFlagsSize + server_connection_id.length() + wire_versions.size() * kQuicVersionSize; std::unique_ptr<char[]> buffer(new char[len]); QuicDataWriter writer(len, buffer.get()); uint8_t flags = static_cast<uint8_t>( PACKET_PUBLIC_FLAGS_VERSION | PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID | PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD); if (!writer.WriteUInt8(flags)) { return nullptr; } if (!writer.WriteConnectionId(server_connection_id)) { return nullptr; } for (const ParsedQuicVersion& version : wire_versions) { if (!writer.WriteUInt32(CreateQuicVersionLabel(version))) { return nullptr; } } return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true); } // static std::unique_ptr<QuicEncryptedPacket> QuicFramer::BuildIetfVersionNegotiationPacket( bool use_length_prefix, QuicConnectionId server_connection_id, QuicConnectionId client_connection_id, const ParsedQuicVersionVector& versions) { QUIC_DVLOG(1) << "Building IETF version negotiation packet with" << (use_length_prefix ? "" : "out") << " length prefix, server_connection_id " << server_connection_id << " client_connection_id " << client_connection_id << " versions " << ParsedQuicVersionVectorToString(versions); DCHECK(!versions.empty()); size_t len = kPacketHeaderTypeSize + kConnectionIdLengthSize + client_connection_id.length() + server_connection_id.length() + (versions.size() + 1) * kQuicVersionSize; if (use_length_prefix) { // When using length-prefixed connection IDs, packets carry two lengths // instead of one. len += kConnectionIdLengthSize; } std::unique_ptr<char[]> buffer(new char[len]); QuicDataWriter writer(len, buffer.get()); // TODO(fayang): Randomly select a value for the type. uint8_t type = static_cast<uint8_t>(FLAGS_LONG_HEADER | FLAGS_FIXED_BIT); if (!writer.WriteUInt8(type)) { return nullptr; } if (!writer.WriteUInt32(0)) { return nullptr; } if (!AppendIetfConnectionIds(true, use_length_prefix, client_connection_id, server_connection_id, &writer)) { return nullptr; } for (const ParsedQuicVersion& version : versions) { if (!writer.WriteUInt32(CreateQuicVersionLabel(version))) { return nullptr; } } return std::make_unique<QuicEncryptedPacket>(buffer.release(), len, true); } bool QuicFramer::ProcessPacket(const QuicEncryptedPacket& packet) { QuicDataReader reader(packet.data(), packet.length()); bool packet_has_ietf_packet_header = false; if (infer_packet_header_type_from_version_) { packet_has_ietf_packet_header = VersionHasIetfInvariantHeader(version_.transport_version); } else if (!reader.IsDoneReading()) { uint8_t type = reader.PeekByte(); packet_has_ietf_packet_header = QuicUtils::IsIetfPacketHeader(type); } if (packet_has_ietf_packet_header) { QUIC_DVLOG(1) << ENDPOINT << "Processing IETF QUIC packet."; } visitor_->OnPacket(); QuicPacketHeader header; if (!ProcessPublicHeader(&reader, packet_has_ietf_packet_header, &header)) { DCHECK_NE("", detailed_error_); QUIC_DVLOG(1) << ENDPOINT << "Unable to process public header. Error: " << detailed_error_; DCHECK_NE("", detailed_error_); RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_HEADER); return RaiseError(QUIC_INVALID_PACKET_HEADER); } if (!visitor_->OnUnauthenticatedPublicHeader(header)) { // The visitor suppresses further processing of the packet. return true; } if (IsVersionNegotiation(header, packet_has_ietf_packet_header)) { if (perspective_ == Perspective::IS_CLIENT) { QUIC_DVLOG(1) << "Client received version negotiation packet"; return ProcessVersionNegotiationPacket(&reader, header); } else { QUIC_DLOG(ERROR) << "Server received version negotiation packet"; set_detailed_error("Server received version negotiation packet."); return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET); } } if (header.version_flag && header.version != version_) { if (perspective_ == Perspective::IS_SERVER) { if (!visitor_->OnProtocolVersionMismatch(header.version)) { RecordDroppedPacketReason(DroppedPacketReason::VERSION_MISMATCH); return true; } } else { // A client received a packet of a different version but that packet is // not a version negotiation packet. It is therefore invalid and dropped. QUIC_DLOG(ERROR) << "Client received unexpected version " << ParsedQuicVersionToString(header.version) << " instead of " << ParsedQuicVersionToString(version_); set_detailed_error("Client received unexpected version."); return RaiseError(QUIC_INVALID_VERSION); } } bool rv; if (header.long_packet_type == RETRY) { rv = ProcessRetryPacket(&reader, header); } else if (header.reset_flag) { rv = ProcessPublicResetPacket(&reader, header); } else if (packet.length() <= kMaxIncomingPacketSize) { // The optimized decryption algorithm implementations run faster when // operating on aligned memory. QUIC_CACHELINE_ALIGNED char buffer[kMaxIncomingPacketSize]; if (packet_has_ietf_packet_header) { rv = ProcessIetfDataPacket(&reader, &header, packet, buffer, QUICHE_ARRAYSIZE(buffer)); } else { rv = ProcessDataPacket(&reader, &header, packet, buffer, QUICHE_ARRAYSIZE(buffer)); } } else { std::unique_ptr<char[]> large_buffer(new char[packet.length()]); if (packet_has_ietf_packet_header) { rv = ProcessIetfDataPacket(&reader, &header, packet, large_buffer.get(), packet.length()); } else { rv = ProcessDataPacket(&reader, &header, packet, large_buffer.get(), packet.length()); } QUIC_BUG_IF(rv) << "QUIC should never successfully process packets larger" << "than kMaxIncomingPacketSize. packet size:" << packet.length(); } return rv; } bool QuicFramer::ProcessVersionNegotiationPacket( QuicDataReader* reader, const QuicPacketHeader& header) { DCHECK_EQ(Perspective::IS_CLIENT, perspective_); QuicVersionNegotiationPacket packet( GetServerConnectionIdAsRecipient(header, perspective_)); // Try reading at least once to raise error if the packet is invalid. do { QuicVersionLabel version_label; if (!ProcessVersionLabel(reader, &version_label)) { set_detailed_error("Unable to read supported version in negotiation."); RecordDroppedPacketReason( DroppedPacketReason::INVALID_VERSION_NEGOTIATION_PACKET); return RaiseError(QUIC_INVALID_VERSION_NEGOTIATION_PACKET); } ParsedQuicVersion parsed_version = ParseQuicVersionLabel(version_label); if (parsed_version != UnsupportedQuicVersion()) { packet.versions.push_back(parsed_version); } } while (!reader->IsDoneReading()); QUIC_DLOG(INFO) << ENDPOINT << "parsed version negotiation: " << ParsedQuicVersionVectorToString(packet.versions); visitor_->OnVersionNegotiationPacket(packet); return true; } bool QuicFramer::ProcessRetryPacket(QuicDataReader* reader, const QuicPacketHeader& header) { DCHECK_EQ(Perspective::IS_CLIENT, perspective_); if (version_.HasRetryIntegrityTag()) { DCHECK(version_.HasLengthPrefixedConnectionIds()) << version_; const size_t bytes_remaining = reader->BytesRemaining(); if (bytes_remaining <= kRetryIntegrityTagLength) { set_detailed_error("Retry packet too short to parse integrity tag."); return false; } const size_t retry_token_length = bytes_remaining - kRetryIntegrityTagLength; DCHECK_GT(retry_token_length, 0u); quiche::QuicheStringPiece retry_token; if (!reader->ReadStringPiece(&retry_token, retry_token_length)) { set_detailed_error("Failed to read retry token."); return false; } quiche::QuicheStringPiece retry_without_tag = reader->PreviouslyReadPayload(); quiche::QuicheStringPiece integrity_tag = reader->ReadRemainingPayload(); DCHECK_EQ(integrity_tag.length(), kRetryIntegrityTagLength); visitor_->OnRetryPacket(EmptyQuicConnectionId(), header.source_connection_id, retry_token, integrity_tag, retry_without_tag); return true; } QuicConnectionId original_destination_connection_id; if (version_.HasLengthPrefixedConnectionIds()) { // Parse Original Destination Connection ID. if (!reader->ReadLengthPrefixedConnectionId( &original_destination_connection_id)) { set_detailed_error("Unable to read Original Destination ConnectionId."); return false; } } else { // Parse Original Destination Connection ID Length. uint8_t odcil = header.type_byte & 0xf; if (odcil != 0) { odcil += kConnectionIdLengthAdjustment; } // Parse Original Destination Connection ID. if (!reader->ReadConnectionId(&original_destination_connection_id, odcil)) { set_detailed_error("Unable to read Original Destination ConnectionId."); return false; } } if (!QuicUtils::IsConnectionIdValidForVersion( original_destination_connection_id, transport_version())) { set_detailed_error( "Received Original Destination ConnectionId with invalid length."); return false; } quiche::QuicheStringPiece retry_token = reader->ReadRemainingPayload(); visitor_->OnRetryPacket(original_destination_connection_id, header.source_connection_id, retry_token, /*retry_integrity_tag=*/quiche::QuicheStringPiece(), /*retry_without_tag=*/quiche::QuicheStringPiece()); return true; } // Seeks the current packet to check for a coalesced packet at the end. // If the IETF length field only spans part of the outer packet, // then there is a coalesced packet after this one. void QuicFramer::MaybeProcessCoalescedPacket( const QuicDataReader& encrypted_reader, uint64_t remaining_bytes_length, const QuicPacketHeader& header) { if (header.remaining_packet_length >= remaining_bytes_length) { // There is no coalesced packet. return; } quiche::QuicheStringPiece remaining_data = encrypted_reader.PeekRemainingPayload(); DCHECK_EQ(remaining_data.length(), remaining_bytes_length); const char* coalesced_data = remaining_data.data() + header.remaining_packet_length; uint64_t coalesced_data_length = remaining_bytes_length - header.remaining_packet_length; QuicDataReader coalesced_reader(coalesced_data, coalesced_data_length); QuicPacketHeader coalesced_header; if (!ProcessIetfPacketHeader(&coalesced_reader, &coalesced_header)) { // Some implementations pad their INITIAL packets by sending random invalid // data after the INITIAL, and that is allowed by the specification. If we // fail to parse a subsequent coalesced packet, simply ignore it. QUIC_DLOG(INFO) << ENDPOINT << "Failed to parse received coalesced header of length " << coalesced_data_length << " with error: " << detailed_error_ << ": " << quiche::QuicheTextUtils::HexEncode(coalesced_data, coalesced_data_length) << " previous header was " << header; return; } if (coalesced_header.destination_connection_id != header.destination_connection_id) { // Drop coalesced packets with mismatched connection IDs. QUIC_DLOG(INFO) << ENDPOINT << "Received mismatched coalesced header " << coalesced_header << " previous header was " << header; QUIC_CODE_COUNT( quic_received_coalesced_packets_with_mismatched_connection_id); return; } QuicEncryptedPacket coalesced_packet(coalesced_data, coalesced_data_length, /*owns_buffer=*/false); visitor_->OnCoalescedPacket(coalesced_packet); } bool QuicFramer::MaybeProcessIetfLength(QuicDataReader* encrypted_reader, QuicPacketHeader* header) { if (!QuicVersionHasLongHeaderLengths(header->version.transport_version) || header->form != IETF_QUIC_LONG_HEADER_PACKET || (header->long_packet_type != INITIAL && header->long_packet_type != HANDSHAKE && header->long_packet_type != ZERO_RTT_PROTECTED)) { return true; } header->length_length = encrypted_reader->PeekVarInt62Length(); if (!encrypted_reader->ReadVarInt62(&header->remaining_packet_length)) { set_detailed_error("Unable to read long header payload length."); return RaiseError(QUIC_INVALID_PACKET_HEADER); } uint64_t remaining_bytes_length = encrypted_reader->BytesRemaining(); if (header->remaining_packet_length > remaining_bytes_length) { set_detailed_error("Long header payload length longer than packet."); return RaiseError(QUIC_INVALID_PACKET_HEADER); } MaybeProcessCoalescedPacket(*encrypted_reader, remaining_bytes_length, *header); if (!encrypted_reader->TruncateRemaining(header->remaining_packet_length)) { set_detailed_error("Length TruncateRemaining failed."); QUIC_BUG << "Length TruncateRemaining failed."; return RaiseError(QUIC_INVALID_PACKET_HEADER); } return true; } bool QuicFramer::ProcessIetfDataPacket(QuicDataReader* encrypted_reader, QuicPacketHeader* header, const QuicEncryptedPacket& packet, char* decrypted_buffer, size_t buffer_length) { DCHECK_NE(GOOGLE_QUIC_PACKET, header->form); DCHECK(!header->has_possible_stateless_reset_token); header->length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0; header->remaining_packet_length = 0; if (header->form == IETF_QUIC_SHORT_HEADER_PACKET && perspective_ == Perspective::IS_CLIENT) { // Peek possible stateless reset token. Will only be used on decryption // failure. quiche::QuicheStringPiece remaining = encrypted_reader->PeekRemainingPayload(); if (remaining.length() >= sizeof(header->possible_stateless_reset_token)) { header->has_possible_stateless_reset_token = true; memcpy(&header->possible_stateless_reset_token, &remaining.data()[remaining.length() - sizeof(header->possible_stateless_reset_token)], sizeof(header->possible_stateless_reset_token)); } } if (!MaybeProcessIetfLength(encrypted_reader, header)) { return false; } quiche::QuicheStringPiece associated_data; std::vector<char> ad_storage; QuicPacketNumber base_packet_number; if (header->form == IETF_QUIC_SHORT_HEADER_PACKET || header->long_packet_type != VERSION_NEGOTIATION) { DCHECK(header->form == IETF_QUIC_SHORT_HEADER_PACKET || header->long_packet_type == INITIAL || header->long_packet_type == HANDSHAKE || header->long_packet_type == ZERO_RTT_PROTECTED); // Process packet number. if (supports_multiple_packet_number_spaces_) { PacketNumberSpace pn_space = GetPacketNumberSpace(*header); if (pn_space == NUM_PACKET_NUMBER_SPACES) { return RaiseError(QUIC_INVALID_PACKET_HEADER); } base_packet_number = largest_decrypted_packet_numbers_[pn_space]; } else { base_packet_number = largest_packet_number_; } uint64_t full_packet_number; bool hp_removal_failed = false; if (version_.HasHeaderProtection()) { if (!RemoveHeaderProtection(encrypted_reader, packet, header, &full_packet_number, &ad_storage)) { hp_removal_failed = true; } associated_data = quiche::QuicheStringPiece(ad_storage.data(), ad_storage.size()); } else if (!ProcessAndCalculatePacketNumber( encrypted_reader, header->packet_number_length, base_packet_number, &full_packet_number)) { set_detailed_error("Unable to read packet number."); RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER); return RaiseError(QUIC_INVALID_PACKET_HEADER); } if (hp_removal_failed || !IsValidFullPacketNumber(full_packet_number, version())) { if (IsIetfStatelessResetPacket(*header)) { // This is a stateless reset packet. QuicIetfStatelessResetPacket packet( *header, header->possible_stateless_reset_token); visitor_->OnAuthenticatedIetfStatelessResetPacket(packet); return true; } if (hp_removal_failed) { const EncryptionLevel decryption_level = GetEncryptionLevel(*header); const bool has_decryption_key = decrypter_[decryption_level] != nullptr; visitor_->OnUndecryptablePacket( QuicEncryptedPacket(encrypted_reader->FullPayload()), decryption_level, has_decryption_key); RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE); set_detailed_error(quiche::QuicheStrCat( "Unable to decrypt ", EncryptionLevelToString(decryption_level), " header protection", has_decryption_key ? "" : " (missing key)", ".")); return RaiseError(QUIC_DECRYPTION_FAILURE); } RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER); set_detailed_error("packet numbers cannot be 0."); return RaiseError(QUIC_INVALID_PACKET_HEADER); } header->packet_number = QuicPacketNumber(full_packet_number); } // A nonce should only present in SHLO from the server to the client when // using QUIC crypto. if (header->form == IETF_QUIC_LONG_HEADER_PACKET && header->long_packet_type == ZERO_RTT_PROTECTED && perspective_ == Perspective::IS_CLIENT && version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO) { if (!encrypted_reader->ReadBytes( reinterpret_cast<uint8_t*>(last_nonce_.data()), last_nonce_.size())) { set_detailed_error("Unable to read nonce."); RecordDroppedPacketReason( DroppedPacketReason::INVALID_DIVERSIFICATION_NONCE); return RaiseError(QUIC_INVALID_PACKET_HEADER); } header->nonce = &last_nonce_; } else { header->nonce = nullptr; } if (!visitor_->OnUnauthenticatedHeader(*header)) { set_detailed_error( "Visitor asked to stop processing of unauthenticated header."); return false; } quiche::QuicheStringPiece encrypted = encrypted_reader->ReadRemainingPayload(); if (!version_.HasHeaderProtection()) { associated_data = GetAssociatedDataFromEncryptedPacket( version_.transport_version, packet, GetIncludedDestinationConnectionIdLength(*header), GetIncludedSourceConnectionIdLength(*header), header->version_flag, header->nonce != nullptr, header->packet_number_length, header->retry_token_length_length, header->retry_token.length(), header->length_length); } size_t decrypted_length = 0; EncryptionLevel decrypted_level; if (!DecryptPayload(encrypted, associated_data, *header, decrypted_buffer, buffer_length, &decrypted_length, &decrypted_level)) { if (IsIetfStatelessResetPacket(*header)) { // This is a stateless reset packet. QuicIetfStatelessResetPacket packet( *header, header->possible_stateless_reset_token); visitor_->OnAuthenticatedIetfStatelessResetPacket(packet); return true; } const EncryptionLevel decryption_level = GetEncryptionLevel(*header); const bool has_decryption_key = version_.KnowsWhichDecrypterToUse() && decrypter_[decryption_level] != nullptr; visitor_->OnUndecryptablePacket( QuicEncryptedPacket(encrypted_reader->FullPayload()), decryption_level, has_decryption_key); set_detailed_error(quiche::QuicheStrCat( "Unable to decrypt ", EncryptionLevelToString(decryption_level), " payload with reconstructed packet number ", header->packet_number.ToString(), " (largest decrypted was ", base_packet_number.ToString(), ")", has_decryption_key || !version_.KnowsWhichDecrypterToUse() ? "" : " (missing key)", ".")); RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE); return RaiseError(QUIC_DECRYPTION_FAILURE); } QuicDataReader reader(decrypted_buffer, decrypted_length); // Update the largest packet number after we have decrypted the packet // so we are confident is not attacker controlled. if (supports_multiple_packet_number_spaces_) { largest_decrypted_packet_numbers_[QuicUtils::GetPacketNumberSpace( decrypted_level)] .UpdateMax(header->packet_number); } else { largest_packet_number_.UpdateMax(header->packet_number); } if (!visitor_->OnPacketHeader(*header)) { RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER); // The visitor suppresses further processing of the packet. return true; } if (packet.length() > kMaxIncomingPacketSize) { set_detailed_error("Packet too large."); return RaiseError(QUIC_PACKET_TOO_LARGE); } // Handle the payload. if (VersionHasIetfQuicFrames(version_.transport_version)) { current_received_frame_type_ = 0; if (!ProcessIetfFrameData(&reader, *header)) { current_received_frame_type_ = 0; DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessIetfFrameData sets the error. DCHECK_NE("", detailed_error_); QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: " << detailed_error_; return false; } current_received_frame_type_ = 0; } else { if (!ProcessFrameData(&reader, *header)) { DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error. DCHECK_NE("", detailed_error_); QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: " << detailed_error_; return false; } } visitor_->OnPacketComplete(); return true; } bool QuicFramer::ProcessDataPacket(QuicDataReader* encrypted_reader, QuicPacketHeader* header, const QuicEncryptedPacket& packet, char* decrypted_buffer, size_t buffer_length) { if (!ProcessUnauthenticatedHeader(encrypted_reader, header)) { DCHECK_NE("", detailed_error_); QUIC_DVLOG(1) << ENDPOINT << "Unable to process packet header. Stopping parsing. Error: " << detailed_error_; RecordDroppedPacketReason(DroppedPacketReason::INVALID_PACKET_NUMBER); return false; } quiche::QuicheStringPiece encrypted = encrypted_reader->ReadRemainingPayload(); quiche::QuicheStringPiece associated_data = GetAssociatedDataFromEncryptedPacket( version_.transport_version, packet, GetIncludedDestinationConnectionIdLength(*header), GetIncludedSourceConnectionIdLength(*header), header->version_flag, header->nonce != nullptr, header->packet_number_length, header->retry_token_length_length, header->retry_token.length(), header->length_length); size_t decrypted_length = 0; EncryptionLevel decrypted_level; if (!DecryptPayload(encrypted, associated_data, *header, decrypted_buffer, buffer_length, &decrypted_length, &decrypted_level)) { const EncryptionLevel decryption_level = decrypter_level_; // This version uses trial decryption so we always report to our visitor // that we are not certain we have the correct decryption key. const bool has_decryption_key = false; visitor_->OnUndecryptablePacket( QuicEncryptedPacket(encrypted_reader->FullPayload()), decryption_level, has_decryption_key); RecordDroppedPacketReason(DroppedPacketReason::DECRYPTION_FAILURE); set_detailed_error(quiche::QuicheStrCat( "Unable to decrypt ", EncryptionLevelToString(decryption_level), " payload.")); return RaiseError(QUIC_DECRYPTION_FAILURE); } QuicDataReader reader(decrypted_buffer, decrypted_length); // Update the largest packet number after we have decrypted the packet // so we are confident is not attacker controlled. if (supports_multiple_packet_number_spaces_) { largest_decrypted_packet_numbers_[QuicUtils::GetPacketNumberSpace( decrypted_level)] .UpdateMax(header->packet_number); } else { largest_packet_number_.UpdateMax(header->packet_number); } if (!visitor_->OnPacketHeader(*header)) { // The visitor suppresses further processing of the packet. return true; } if (packet.length() > kMaxIncomingPacketSize) { set_detailed_error("Packet too large."); return RaiseError(QUIC_PACKET_TOO_LARGE); } // Handle the payload. if (!ProcessFrameData(&reader, *header)) { DCHECK_NE(QUIC_NO_ERROR, error_); // ProcessFrameData sets the error. DCHECK_NE("", detailed_error_); QUIC_DLOG(WARNING) << ENDPOINT << "Unable to process frame data. Error: " << detailed_error_; return false; } visitor_->OnPacketComplete(); return true; } bool QuicFramer::ProcessPublicResetPacket(QuicDataReader* reader, const QuicPacketHeader& header) { QuicPublicResetPacket packet( GetServerConnectionIdAsRecipient(header, perspective_)); std::unique_ptr<CryptoHandshakeMessage> reset( CryptoFramer::ParseMessage(reader->ReadRemainingPayload())); if (!reset) { set_detailed_error("Unable to read reset message."); RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET); return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET); } if (reset->tag() != kPRST) { set_detailed_error("Incorrect message tag."); RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET); return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET); } if (reset->GetUint64(kRNON, &packet.nonce_proof) != QUIC_NO_ERROR) { set_detailed_error("Unable to read nonce proof."); RecordDroppedPacketReason(DroppedPacketReason::INVALID_PUBLIC_RESET_PACKET); return RaiseError(QUIC_INVALID_PUBLIC_RST_PACKET); } // TODO(satyamshekhar): validate nonce to protect against DoS. quiche::QuicheStringPiece address; if (reset->GetStringPiece(kCADR, &address)) { QuicSocketAddressCoder address_coder; if (address_coder.Decode(address.data(), address.length())) { packet.client_address = QuicSocketAddress(address_coder.ip(), address_coder.port()); } } quiche::QuicheStringPiece endpoint_id; if (perspective_ == Perspective::IS_CLIENT && reset->GetStringPiece(kEPID, &endpoint_id)) { packet.endpoint_id = std::string(endpoint_id); packet.endpoint_id += '\0'; } visitor_->OnPublicResetPacket(packet); return true; } bool QuicFramer::IsIetfStatelessResetPacket( const QuicPacketHeader& header) const { QUIC_BUG_IF(header.has_possible_stateless_reset_token && perspective_ != Perspective::IS_CLIENT) << "has_possible_stateless_reset_token can only be true at client side."; return header.form == IETF_QUIC_SHORT_HEADER_PACKET && header.has_possible_stateless_reset_token && visitor_->IsValidStatelessResetToken( header.possible_stateless_reset_token); } bool QuicFramer::HasEncrypterOfEncryptionLevel(EncryptionLevel level) const { return encrypter_[level] != nullptr; } bool QuicFramer::HasDecrypterOfEncryptionLevel(EncryptionLevel level) const { return decrypter_[level] != nullptr; } bool QuicFramer::AppendPacketHeader(const QuicPacketHeader& header, QuicDataWriter* writer, size_t* length_field_offset) { if (VersionHasIetfInvariantHeader(transport_version())) { return AppendIetfPacketHeader(header, writer, length_field_offset); } QUIC_DVLOG(1) << ENDPOINT << "Appending header: " << header; uint8_t public_flags = 0; if (header.reset_flag) { public_flags |= PACKET_PUBLIC_FLAGS_RST; } if (header.version_flag) { public_flags |= PACKET_PUBLIC_FLAGS_VERSION; } public_flags |= GetPacketNumberFlags(header.packet_number_length) << kPublicHeaderSequenceNumberShift; if (header.nonce != nullptr) { DCHECK_EQ(Perspective::IS_SERVER, perspective_); public_flags |= PACKET_PUBLIC_FLAGS_NONCE; } QuicConnectionId server_connection_id = GetServerConnectionIdAsSender(header, perspective_); QuicConnectionIdIncluded server_connection_id_included = GetServerConnectionIdIncludedAsSender(header, perspective_); DCHECK_EQ(CONNECTION_ID_ABSENT, GetClientConnectionIdIncludedAsSender(header, perspective_)) << ENDPOINT << ParsedQuicVersionToString(version_) << " invalid header: " << header; switch (server_connection_id_included) { case CONNECTION_ID_ABSENT: if (!writer->WriteUInt8(public_flags | PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID)) { return false; } break; case CONNECTION_ID_PRESENT: QUIC_BUG_IF(!QuicUtils::IsConnectionIdValidForVersion( server_connection_id, transport_version())) << "AppendPacketHeader: attempted to use connection ID " << server_connection_id << " which is invalid with version " << QuicVersionToString(transport_version()); public_flags |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID; if (perspective_ == Perspective::IS_CLIENT) { public_flags |= PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID_OLD; } if (!writer->WriteUInt8(public_flags) || !writer->WriteConnectionId(server_connection_id)) { return false; } break; } last_serialized_server_connection_id_ = server_connection_id; if (header.version_flag) { DCHECK_EQ(Perspective::IS_CLIENT, perspective_); QuicVersionLabel version_label = CreateQuicVersionLabel(version_); if (!writer->WriteUInt32(version_label)) { return false; } QUIC_DVLOG(1) << ENDPOINT << "label = '" << QuicVersionLabelToString(version_label) << "'"; } if (header.nonce != nullptr && !writer->WriteBytes(header.nonce, kDiversificationNonceSize)) { return false; } if (!AppendPacketNumber(header.packet_number_length, header.packet_number, writer)) { return false; } return true; } bool QuicFramer::AppendIetfHeaderTypeByte(const QuicPacketHeader& header, QuicDataWriter* writer) { uint8_t type = 0; if (header.version_flag) { type = static_cast<uint8_t>( FLAGS_LONG_HEADER | FLAGS_FIXED_BIT | LongHeaderTypeToOnWireValue(header.long_packet_type) | PacketNumberLengthToOnWireValue(header.packet_number_length)); } else { type = static_cast<uint8_t>( FLAGS_FIXED_BIT | PacketNumberLengthToOnWireValue(header.packet_number_length)); } return writer->WriteUInt8(type); } bool QuicFramer::AppendIetfPacketHeader(const QuicPacketHeader& header, QuicDataWriter* writer, size_t* length_field_offset) { QUIC_DVLOG(1) << ENDPOINT << "Appending IETF header: " << header; QuicConnectionId server_connection_id = GetServerConnectionIdAsSender(header, perspective_); QUIC_BUG_IF(!QuicUtils::IsConnectionIdValidForVersion(server_connection_id, transport_version())) << "AppendIetfPacketHeader: attempted to use connection ID " << server_connection_id << " which is invalid with version " << QuicVersionToString(transport_version()); if (!AppendIetfHeaderTypeByte(header, writer)) { return false; } if (header.version_flag) { DCHECK_NE(VERSION_NEGOTIATION, header.long_packet_type) << "QuicFramer::AppendIetfPacketHeader does not support sending " "version negotiation packets, use " "QuicFramer::BuildVersionNegotiationPacket instead " << header; // Append version for long header. QuicVersionLabel version_label = CreateQuicVersionLabel(version_); if (!writer->WriteUInt32(version_label)) { return false; } } // Append connection ID. if (!AppendIetfConnectionIds( header.version_flag, version_.HasLengthPrefixedConnectionIds(), header.destination_connection_id_included != CONNECTION_ID_ABSENT ? header.destination_connection_id : EmptyQuicConnectionId(), header.source_connection_id_included != CONNECTION_ID_ABSENT ? header.source_connection_id : EmptyQuicConnectionId(), writer)) { return false; } last_serialized_server_connection_id_ = server_connection_id; if (version_.SupportsClientConnectionIds()) { last_serialized_client_connection_id_ = GetClientConnectionIdAsSender(header, perspective_); } // TODO(b/141924462) Remove this QUIC_BUG once we do support sending RETRY. QUIC_BUG_IF(header.version_flag && header.long_packet_type == RETRY) << "Sending IETF RETRY packets is not currently supported " << header; if (QuicVersionHasLongHeaderLengths(transport_version()) && header.version_flag) { if (header.long_packet_type == INITIAL) { DCHECK_NE(VARIABLE_LENGTH_INTEGER_LENGTH_0, header.retry_token_length_length) << ENDPOINT << ParsedQuicVersionToString(version_) << " bad retry token length length in header: " << header; // Write retry token length. if (!writer->WriteVarInt62(header.retry_token.length(), header.retry_token_length_length)) { return false; } // Write retry token. if (!header.retry_token.empty() && !writer->WriteStringPiece(header.retry_token)) { return false; } } if (length_field_offset != nullptr) { *length_field_offset = writer->length(); } // Add fake length to reserve two bytes to add length in later. writer->WriteVarInt62(256); } else if (length_field_offset != nullptr) { *length_field_offset = 0; } // Append packet number. if (!AppendPacketNumber(header.packet_number_length, header.packet_number, writer)) { return false; } last_written_packet_number_length_ = header.packet_number_length; if (!header.version_flag) { return true; } if (header.nonce != nullptr) { DCHECK(header.version_flag); DCHECK_EQ(ZERO_RTT_PROTECTED, header.long_packet_type); DCHECK_EQ(Perspective::IS_SERVER, perspective_); if (!writer->WriteBytes(header.nonce, kDiversificationNonceSize)) { return false; } } return true; } const QuicTime::Delta QuicFramer::CalculateTimestampFromWire( uint32_t time_delta_us) { // The new time_delta might have wrapped to the next epoch, or it // might have reverse wrapped to the previous epoch, or it might // remain in the same epoch. Select the time closest to the previous // time. // // epoch_delta is the delta between epochs. A delta is 4 bytes of // microseconds. const uint64_t epoch_delta = UINT64_C(1) << 32; uint64_t epoch = last_timestamp_.ToMicroseconds() & ~(epoch_delta - 1); // Wrapping is safe here because a wrapped value will not be ClosestTo below. uint64_t prev_epoch = epoch - epoch_delta; uint64_t next_epoch = epoch + epoch_delta; uint64_t time = ClosestTo( last_timestamp_.ToMicroseconds(), epoch + time_delta_us, ClosestTo(last_timestamp_.ToMicroseconds(), prev_epoch + time_delta_us, next_epoch + time_delta_us)); return QuicTime::Delta::FromMicroseconds(time); } uint64_t QuicFramer::CalculatePacketNumberFromWire( QuicPacketNumberLength packet_number_length, QuicPacketNumber base_packet_number, uint64_t packet_number) const { // The new packet number might have wrapped to the next epoch, or // it might have reverse wrapped to the previous epoch, or it might // remain in the same epoch. Select the packet number closest to the // next expected packet number, the previous packet number plus 1. // epoch_delta is the delta between epochs the packet number was serialized // with, so the correct value is likely the same epoch as the last sequence // number or an adjacent epoch. if (!base_packet_number.IsInitialized()) { return packet_number; } const uint64_t epoch_delta = UINT64_C(1) << (8 * packet_number_length); uint64_t next_packet_number = base_packet_number.ToUint64() + 1; uint64_t epoch = base_packet_number.ToUint64() & ~(epoch_delta - 1); uint64_t prev_epoch = epoch - epoch_delta; uint64_t next_epoch = epoch + epoch_delta; return ClosestTo(next_packet_number, epoch + packet_number, ClosestTo(next_packet_number, prev_epoch + packet_number, next_epoch + packet_number)); } bool QuicFramer::ProcessPublicHeader(QuicDataReader* reader, bool packet_has_ietf_packet_header, QuicPacketHeader* header) { if (packet_has_ietf_packet_header) { return ProcessIetfPacketHeader(reader, header); } uint8_t public_flags; if (!reader->ReadBytes(&public_flags, 1)) { set_detailed_error("Unable to read public flags."); return false; } header->reset_flag = (public_flags & PACKET_PUBLIC_FLAGS_RST) != 0; header->version_flag = (public_flags & PACKET_PUBLIC_FLAGS_VERSION) != 0; if (validate_flags_ && !header->version_flag && public_flags > PACKET_PUBLIC_FLAGS_MAX) { set_detailed_error("Illegal public flags value."); return false; } if (header->reset_flag && header->version_flag) { set_detailed_error("Got version flag in reset packet"); return false; } QuicConnectionId* header_connection_id = &header->destination_connection_id; QuicConnectionIdIncluded* header_connection_id_included = &header->destination_connection_id_included; if (perspective_ == Perspective::IS_CLIENT) { header_connection_id = &header->source_connection_id; header_connection_id_included = &header->source_connection_id_included; } switch (public_flags & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) { case PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID: if (!reader->ReadConnectionId(header_connection_id, kQuicDefaultConnectionIdLength)) { set_detailed_error("Unable to read ConnectionId."); return false; } *header_connection_id_included = CONNECTION_ID_PRESENT; break; case PACKET_PUBLIC_FLAGS_0BYTE_CONNECTION_ID: *header_connection_id_included = CONNECTION_ID_ABSENT; *header_connection_id = last_serialized_server_connection_id_; break; } header->packet_number_length = ReadSequenceNumberLength( public_flags >> kPublicHeaderSequenceNumberShift); // Read the version only if the packet is from the client. // version flag from the server means version negotiation packet. if (header->version_flag && perspective_ == Perspective::IS_SERVER) { QuicVersionLabel version_label; if (!ProcessVersionLabel(reader, &version_label)) { set_detailed_error("Unable to read protocol version."); return false; } // If the version from the new packet is the same as the version of this // framer, then the public flags should be set to something we understand. // If not, this raises an error. ParsedQuicVersion version = ParseQuicVersionLabel(version_label); if (version == version_ && public_flags > PACKET_PUBLIC_FLAGS_MAX) { set_detailed_error("Illegal public flags value."); return false; } header->version = version; } // A nonce should only be present in packets from the server to the client, // which are neither version negotiation nor public reset packets. if (public_flags & PACKET_PUBLIC_FLAGS_NONCE && !(public_flags & PACKET_PUBLIC_FLAGS_VERSION) && !(public_flags & PACKET_PUBLIC_FLAGS_RST) && // The nonce flag from a client is ignored and is assumed to be an older // client indicating an eight-byte connection ID. perspective_ == Perspective::IS_CLIENT) { if (!reader->ReadBytes(reinterpret_cast<uint8_t*>(last_nonce_.data()), last_nonce_.size())) { set_detailed_error("Unable to read nonce."); return false; } header->nonce = &last_nonce_; } else { header->nonce = nullptr; } return true; } // static QuicPacketNumberLength QuicFramer::GetMinPacketNumberLength( QuicPacketNumber packet_number) { DCHECK(packet_number.IsInitialized()); if (packet_number < QuicPacketNumber(1 << (PACKET_1BYTE_PACKET_NUMBER * 8))) { return PACKET_1BYTE_PACKET_NUMBER; } else if (packet_number < QuicPacketNumber(1 << (PACKET_2BYTE_PACKET_NUMBER * 8))) { return PACKET_2BYTE_PACKET_NUMBER; } else if (packet_number < QuicPacketNumber(UINT64_C(1) << (PACKET_4BYTE_PACKET_NUMBER * 8))) { return PACKET_4BYTE_PACKET_NUMBER; } else { return PACKET_6BYTE_PACKET_NUMBER; } } // static uint8_t QuicFramer::GetPacketNumberFlags( QuicPacketNumberLength packet_number_length) { switch (packet_number_length) { case PACKET_1BYTE_PACKET_NUMBER: return PACKET_FLAGS_1BYTE_PACKET; case PACKET_2BYTE_PACKET_NUMBER: return PACKET_FLAGS_2BYTE_PACKET; case PACKET_4BYTE_PACKET_NUMBER: return PACKET_FLAGS_4BYTE_PACKET; case PACKET_6BYTE_PACKET_NUMBER: case PACKET_8BYTE_PACKET_NUMBER: return PACKET_FLAGS_8BYTE_PACKET; default: QUIC_BUG << "Unreachable case statement."; return PACKET_FLAGS_8BYTE_PACKET; } } // static QuicFramer::AckFrameInfo QuicFramer::GetAckFrameInfo( const QuicAckFrame& frame) { AckFrameInfo new_ack_info; if (frame.packets.Empty()) { return new_ack_info; } // The first block is the last interval. It isn't encoded with the gap-length // encoding, so skip it. new_ack_info.first_block_length = frame.packets.LastIntervalLength(); auto itr = frame.packets.rbegin(); QuicPacketNumber previous_start = itr->min(); new_ack_info.max_block_length = itr->Length(); ++itr; // Don't do any more work after getting information for 256 ACK blocks; any // more can't be encoded anyway. for (; itr != frame.packets.rend() && new_ack_info.num_ack_blocks < std::numeric_limits<uint8_t>::max(); previous_start = itr->min(), ++itr) { const auto& interval = *itr; const QuicPacketCount total_gap = previous_start - interval.max(); new_ack_info.num_ack_blocks += (total_gap + std::numeric_limits<uint8_t>::max() - 1) / std::numeric_limits<uint8_t>::max(); new_ack_info.max_block_length = std::max(new_ack_info.max_block_length, interval.Length()); } return new_ack_info; } bool QuicFramer::ProcessUnauthenticatedHeader(QuicDataReader* encrypted_reader, QuicPacketHeader* header) { QuicPacketNumber base_packet_number; if (supports_multiple_packet_number_spaces_) { PacketNumberSpace pn_space = GetPacketNumberSpace(*header); if (pn_space == NUM_PACKET_NUMBER_SPACES) { set_detailed_error("Unable to determine packet number space."); return RaiseError(QUIC_INVALID_PACKET_HEADER); } base_packet_number = largest_decrypted_packet_numbers_[pn_space]; } else { base_packet_number = largest_packet_number_; } uint64_t full_packet_number; if (!ProcessAndCalculatePacketNumber( encrypted_reader, header->packet_number_length, base_packet_number, &full_packet_number)) { set_detailed_error("Unable to read packet number."); return RaiseError(QUIC_INVALID_PACKET_HEADER); } if (!IsValidFullPacketNumber(full_packet_number, version())) { set_detailed_error("packet numbers cannot be 0."); return RaiseError(QUIC_INVALID_PACKET_HEADER); } header->packet_number = QuicPacketNumber(full_packet_number); if (!visitor_->OnUnauthenticatedHeader(*header)) { set_detailed_error( "Visitor asked to stop processing of unauthenticated header."); return false; } // The function we are in is called because the framer believes that it is // processing a packet that uses the non-IETF (i.e. Google QUIC) packet header // type. Usually, the framer makes that decision based on the framer's // version, but when the framer is used with Perspective::IS_SERVER, then // before version negotiation is complete (specifically, before // InferPacketHeaderTypeFromVersion is called), this decision is made based on // the type byte of the packet. // // If the framer's version KnowsWhichDecrypterToUse, then that version expects // to use the IETF packet header type. If that's the case and we're in this // function, then the packet received is invalid: the framer was expecting an // IETF packet header and didn't get one. if (version().KnowsWhichDecrypterToUse()) { set_detailed_error("Invalid public header type for expected version."); return RaiseError(QUIC_INVALID_PACKET_HEADER); } return true; } bool QuicFramer::ProcessIetfHeaderTypeByte(QuicDataReader* reader, QuicPacketHeader* header) { uint8_t type; if (!reader->ReadBytes(&type, 1)) { set_detailed_error("Unable to read first byte."); return false; } header->type_byte = type; // Determine whether this is a long or short header. header->form = GetIetfPacketHeaderFormat(type); if (header->form == IETF_QUIC_LONG_HEADER_PACKET) { // Version is always present in long headers. header->version_flag = true; // In versions that do not support client connection IDs, we mark the // corresponding connection ID as absent. header->destination_connection_id_included = (perspective_ == Perspective::IS_SERVER || version_.SupportsClientConnectionIds()) ? CONNECTION_ID_PRESENT : CONNECTION_ID_ABSENT; header->source_connection_id_included = (perspective_ == Perspective::IS_CLIENT || version_.SupportsClientConnectionIds()) ? CONNECTION_ID_PRESENT : CONNECTION_ID_ABSENT; // Read version tag. QuicVersionLabel version_label; if (!ProcessVersionLabel(reader, &version_label)) { set_detailed_error("Unable to read protocol version."); return false; } if (!version_label) { // Version label is 0 indicating this is a version negotiation packet. header->long_packet_type = VERSION_NEGOTIATION; } else { header->version = ParseQuicVersionLabel(version_label); if (header->version.IsKnown()) { if (!(type & FLAGS_FIXED_BIT)) { set_detailed_error("Fixed bit is 0 in long header."); return false; } if (!GetLongHeaderType(type, &header->long_packet_type)) { set_detailed_error("Illegal long header type value."); return false; } if (header->long_packet_type == RETRY) { if (!version().SupportsRetry()) { set_detailed_error("RETRY not supported in this version."); return false; } if (perspective_ == Perspective::IS_SERVER) { set_detailed_error("Client-initiated RETRY is invalid."); return false; } } else if (!header->version.HasHeaderProtection()) { header->packet_number_length = GetLongHeaderPacketNumberLength(type); } } } QUIC_DVLOG(1) << ENDPOINT << "Received IETF long header: " << QuicUtils::QuicLongHeaderTypetoString( header->long_packet_type); return true; } QUIC_DVLOG(1) << ENDPOINT << "Received IETF short header"; // Version is not present in short headers. header->version_flag = false; // In versions that do not support client connection IDs, the client will not // receive destination connection IDs. header->destination_connection_id_included = (perspective_ == Perspective::IS_SERVER || version_.SupportsClientConnectionIds()) ? CONNECTION_ID_PRESENT : CONNECTION_ID_ABSENT; header->source_connection_id_included = CONNECTION_ID_ABSENT; if (!(type & FLAGS_FIXED_BIT)) { set_detailed_error("Fixed bit is 0 in short header."); return false; } if (!version_.HasHeaderProtection()) { header->packet_number_length = GetShortHeaderPacketNumberLength(type); } QUIC_DVLOG(1) << "packet_number_length = " << header->packet_number_length; return true; } // static bool QuicFramer::ProcessVersionLabel(QuicDataReader* reader, QuicVersionLabel* version_label) { if (!reader->ReadUInt32(version_label)) { return false; } return true; } // static bool QuicFramer::ProcessAndValidateIetfConnectionIdLength( QuicDataReader* reader, ParsedQuicVersion version, Perspective perspective, bool should_update_expected_server_connection_id_length, uint8_t* expected_server_connection_id_length, uint8_t* destination_connection_id_length, uint8_t* source_connection_id_length, std::string* detailed_error) { uint8_t connection_id_lengths_byte; if (!reader->ReadBytes(&connection_id_lengths_byte, 1)) { *detailed_error = "Unable to read ConnectionId length."; return false; } uint8_t dcil = (connection_id_lengths_byte & kDestinationConnectionIdLengthMask) >> 4; if (dcil != 0) { dcil += kConnectionIdLengthAdjustment; } uint8_t scil = connection_id_lengths_byte & kSourceConnectionIdLengthMask; if (scil != 0) { scil += kConnectionIdLengthAdjustment; } if (should_update_expected_server_connection_id_length) { uint8_t server_connection_id_length = perspective == Perspective::IS_SERVER ? dcil : scil; if (*expected_server_connection_id_length != server_connection_id_length) { QUIC_DVLOG(1) << "Updating expected_server_connection_id_length: " << static_cast<int>(*expected_server_connection_id_length) << " -> " << static_cast<int>(server_connection_id_length); *expected_server_connection_id_length = server_connection_id_length; } } if (!should_update_expected_server_connection_id_length && (dcil != *destination_connection_id_length || scil != *source_connection_id_length) && version.IsKnown() && !version.AllowsVariableLengthConnectionIds()) { QUIC_DVLOG(1) << "dcil: " << static_cast<uint32_t>(dcil) << ", scil: " << static_cast<uint32_t>(scil); *detailed_error = "Invalid ConnectionId length."; return false; } *destination_connection_id_length = dcil; *source_connection_id_length = scil; return true; } bool QuicFramer::ValidateReceivedConnectionIds(const QuicPacketHeader& header) { if (!QuicUtils::IsConnectionIdValidForVersion( GetServerConnectionIdAsRecipient(header, perspective_), transport_version())) { set_detailed_error("Received server connection ID with invalid length."); return false; } if (version_.SupportsClientConnectionIds() && !QuicUtils::IsConnectionIdValidForVersion( GetClientConnectionIdAsRecipient(header, perspective_), transport_version())) { set_detailed_error("Received client connection ID with invalid length."); return false; } return true; } bool QuicFramer::ProcessIetfPacketHeader(QuicDataReader* reader, QuicPacketHeader* header) { if (version_.HasLengthPrefixedConnectionIds()) { uint8_t expected_destination_connection_id_length = perspective_ == Perspective::IS_CLIENT ? expected_client_connection_id_length_ : expected_server_connection_id_length_; QuicVersionLabel version_label; bool has_length_prefix; std::string detailed_error; QuicErrorCode parse_result = QuicFramer::ParsePublicHeader( reader, expected_destination_connection_id_length, VersionHasIetfInvariantHeader(version_.transport_version), &header->type_byte, &header->form, &header->version_flag, &has_length_prefix, &version_label, &header->version, &header->destination_connection_id, &header->source_connection_id, &header->long_packet_type, &header->retry_token_length_length, &header->retry_token, &detailed_error); if (parse_result != QUIC_NO_ERROR) { set_detailed_error(detailed_error); return false; } header->destination_connection_id_included = CONNECTION_ID_PRESENT; header->source_connection_id_included = header->version_flag ? CONNECTION_ID_PRESENT : CONNECTION_ID_ABSENT; if (header->source_connection_id_included == CONNECTION_ID_ABSENT) { DCHECK(header->source_connection_id.IsEmpty()); if (perspective_ == Perspective::IS_CLIENT) { header->source_connection_id = last_serialized_server_connection_id_; } else { header->source_connection_id = last_serialized_client_connection_id_; } } if (!ValidateReceivedConnectionIds(*header)) { return false; } if (header->version_flag && header->long_packet_type != VERSION_NEGOTIATION && !(header->type_byte & FLAGS_FIXED_BIT)) { set_detailed_error("Fixed bit is 0 in long header."); return false; } if (!header->version_flag && !(header->type_byte & FLAGS_FIXED_BIT)) { set_detailed_error("Fixed bit is 0 in short header."); return false; } if (!header->version_flag) { if (!version_.HasHeaderProtection()) { header->packet_number_length = GetShortHeaderPacketNumberLength(header->type_byte); } return true; } if (header->long_packet_type == RETRY) { if (!version().SupportsRetry()) { set_detailed_error("RETRY not supported in this version."); return false; } if (perspective_ == Perspective::IS_SERVER) { set_detailed_error("Client-initiated RETRY is invalid."); return false; } return true; } if (header->version.IsKnown() && !header->version.HasHeaderProtection()) { header->packet_number_length = GetLongHeaderPacketNumberLength(header->type_byte); } return true; } if (!ProcessIetfHeaderTypeByte(reader, header)) { return false; } uint8_t destination_connection_id_length = header->destination_connection_id_included == CONNECTION_ID_PRESENT ? (perspective_ == Perspective::IS_SERVER ? expected_server_connection_id_length_ : expected_client_connection_id_length_) : 0; uint8_t source_connection_id_length = header->source_connection_id_included == CONNECTION_ID_PRESENT ? (perspective_ == Perspective::IS_CLIENT ? expected_server_connection_id_length_ : expected_client_connection_id_length_) : 0; if (header->form == IETF_QUIC_LONG_HEADER_PACKET) { if (!ProcessAndValidateIetfConnectionIdLength( reader, header->version, perspective_, /*should_update_expected_server_connection_id_length=*/false, &expected_server_connection_id_length_, &destination_connection_id_length, &source_connection_id_length, &detailed_error_)) { return false; } } // Read connection ID. if (!reader->ReadConnectionId(&header->destination_connection_id, destination_connection_id_length)) { set_detailed_error("Unable to read destination connection ID."); return false; } if (!reader->ReadConnectionId(&header->source_connection_id, source_connection_id_length)) { set_detailed_error("Unable to read source connection ID."); return false; } if (header->source_connection_id_included == CONNECTION_ID_ABSENT) { if (!header->source_connection_id.IsEmpty()) { DCHECK(!version_.SupportsClientConnectionIds()); set_detailed_error("Client connection ID not supported in this version."); return false; } if (perspective_ == Perspective::IS_CLIENT) { header->source_connection_id = last_serialized_server_connection_id_; } else { header->source_connection_id = last_serialized_client_connection_id_; } } return ValidateReceivedConnectionIds(*header); } bool QuicFramer::ProcessAndCalculatePacketNumber( QuicDataReader* reader, QuicPacketNumberLength packet_number_length, QuicPacketNumber base_packet_number, uint64_t* packet_number) { uint64_t wire_packet_number; if (!reader->ReadBytesToUInt64(packet_number_length, &wire_packet_number)) { return false; } // TODO(ianswett): Explore the usefulness of trying multiple packet numbers // in case the first guess is incorrect. *packet_number = CalculatePacketNumberFromWire( packet_number_length, base_packet_number, wire_packet_number); return true; } bool QuicFramer::ProcessFrameData(QuicDataReader* reader, const QuicPacketHeader& header) { DCHECK(!VersionHasIetfQuicFrames(version_.transport_version)) << "IETF QUIC Framing negotiated but attempting to process frames as " "non-IETF QUIC."; if (reader->IsDoneReading()) { set_detailed_error("Packet has no frames."); return RaiseError(QUIC_MISSING_PAYLOAD); } QUIC_DVLOG(2) << ENDPOINT << "Processing packet with header " << header; while (!reader->IsDoneReading()) { uint8_t frame_type; if (!reader->ReadBytes(&frame_type, 1)) { set_detailed_error("Unable to read frame type."); return RaiseError(QUIC_INVALID_FRAME_DATA); } const uint8_t special_mask = version_.HasIetfInvariantHeader() ? kQuicFrameTypeSpecialMask : kQuicFrameTypeBrokenMask; if (frame_type & special_mask) { // Stream Frame if (frame_type & kQuicFrameTypeStreamMask) { QuicStreamFrame frame; if (!ProcessStreamFrame(reader, frame_type, &frame)) { return RaiseError(QUIC_INVALID_STREAM_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing stream frame " << frame; if (!visitor_->OnStreamFrame(frame)) { QUIC_DVLOG(1) << ENDPOINT << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } continue; } // Ack Frame if (frame_type & kQuicFrameTypeAckMask) { if (!ProcessAckFrame(reader, frame_type)) { return RaiseError(QUIC_INVALID_ACK_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing ACK frame"; continue; } // This was a special frame type that did not match any // of the known ones. Error. set_detailed_error("Illegal frame type."); QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: " << static_cast<int>(frame_type); return RaiseError(QUIC_INVALID_FRAME_DATA); } switch (frame_type) { case PADDING_FRAME: { QuicPaddingFrame frame; ProcessPaddingFrame(reader, &frame); QUIC_DVLOG(2) << ENDPOINT << "Processing padding frame " << frame; if (!visitor_->OnPaddingFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } continue; } case RST_STREAM_FRAME: { QuicRstStreamFrame frame; if (!ProcessRstStreamFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_RST_STREAM_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing reset stream frame " << frame; if (!visitor_->OnRstStreamFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } continue; } case CONNECTION_CLOSE_FRAME: { QuicConnectionCloseFrame frame; if (!ProcessConnectionCloseFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing connection close frame " << frame; if (!visitor_->OnConnectionCloseFrame(frame)) { QUIC_DVLOG(1) << ENDPOINT << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } continue; } case GOAWAY_FRAME: { QuicGoAwayFrame goaway_frame; if (!ProcessGoAwayFrame(reader, &goaway_frame)) { return RaiseError(QUIC_INVALID_GOAWAY_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing go away frame " << goaway_frame; if (!visitor_->OnGoAwayFrame(goaway_frame)) { QUIC_DVLOG(1) << ENDPOINT << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } continue; } case WINDOW_UPDATE_FRAME: { QuicWindowUpdateFrame window_update_frame; if (!ProcessWindowUpdateFrame(reader, &window_update_frame)) { return RaiseError(QUIC_INVALID_WINDOW_UPDATE_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing window update frame " << window_update_frame; if (!visitor_->OnWindowUpdateFrame(window_update_frame)) { QUIC_DVLOG(1) << ENDPOINT << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } continue; } case BLOCKED_FRAME: { QuicBlockedFrame blocked_frame; if (!ProcessBlockedFrame(reader, &blocked_frame)) { return RaiseError(QUIC_INVALID_BLOCKED_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing blocked frame " << blocked_frame; if (!visitor_->OnBlockedFrame(blocked_frame)) { QUIC_DVLOG(1) << ENDPOINT << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } continue; } case STOP_WAITING_FRAME: { if (GetQuicReloadableFlag(quic_do_not_accept_stop_waiting) && version_.HasIetfInvariantHeader()) { QUIC_RELOADABLE_FLAG_COUNT(quic_do_not_accept_stop_waiting); set_detailed_error("STOP WAITING not supported in version 44+."); return RaiseError(QUIC_INVALID_STOP_WAITING_DATA); } QuicStopWaitingFrame stop_waiting_frame; if (!ProcessStopWaitingFrame(reader, header, &stop_waiting_frame)) { return RaiseError(QUIC_INVALID_STOP_WAITING_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing stop waiting frame " << stop_waiting_frame; if (!visitor_->OnStopWaitingFrame(stop_waiting_frame)) { QUIC_DVLOG(1) << ENDPOINT << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } continue; } case PING_FRAME: { // Ping has no payload. QuicPingFrame ping_frame; if (!visitor_->OnPingFrame(ping_frame)) { QUIC_DVLOG(1) << ENDPOINT << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } QUIC_DVLOG(2) << ENDPOINT << "Processing ping frame " << ping_frame; continue; } case IETF_EXTENSION_MESSAGE_NO_LENGTH: QUIC_FALLTHROUGH_INTENDED; case IETF_EXTENSION_MESSAGE: { QuicMessageFrame message_frame; if (!ProcessMessageFrame(reader, frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH, &message_frame)) { return RaiseError(QUIC_INVALID_MESSAGE_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing message frame " << message_frame; if (!visitor_->OnMessageFrame(message_frame)) { QUIC_DVLOG(1) << ENDPOINT << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } break; } case CRYPTO_FRAME: { if (!QuicVersionUsesCryptoFrames(version_.transport_version)) { set_detailed_error("Illegal frame type."); return RaiseError(QUIC_INVALID_FRAME_DATA); } QuicCryptoFrame frame; if (!ProcessCryptoFrame(reader, GetEncryptionLevel(header), &frame)) { return RaiseError(QUIC_INVALID_FRAME_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing crypto frame " << frame; if (!visitor_->OnCryptoFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } break; } case HANDSHAKE_DONE_FRAME: { // HANDSHAKE_DONE has no payload. QuicHandshakeDoneFrame handshake_done_frame; QUIC_DVLOG(2) << ENDPOINT << "Processing handshake done frame " << handshake_done_frame; if (!visitor_->OnHandshakeDoneFrame(handshake_done_frame)) { QUIC_DVLOG(1) << ENDPOINT << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } break; } default: set_detailed_error("Illegal frame type."); QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: " << static_cast<int>(frame_type); return RaiseError(QUIC_INVALID_FRAME_DATA); } } return true; } bool QuicFramer::ProcessIetfFrameData(QuicDataReader* reader, const QuicPacketHeader& header) { DCHECK(VersionHasIetfQuicFrames(version_.transport_version)) << "Attempt to process frames as IETF frames but version (" << version_.transport_version << ") does not support IETF Framing."; if (reader->IsDoneReading()) { set_detailed_error("Packet has no frames."); return RaiseError(QUIC_MISSING_PAYLOAD); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF packet with header " << header; while (!reader->IsDoneReading()) { uint64_t frame_type; // Will be the number of bytes into which frame_type was encoded. size_t encoded_bytes = reader->BytesRemaining(); if (!reader->ReadVarInt62(&frame_type)) { set_detailed_error("Unable to read frame type."); return RaiseError(QUIC_INVALID_FRAME_DATA); } current_received_frame_type_ = frame_type; // Is now the number of bytes into which the frame type was encoded. encoded_bytes -= reader->BytesRemaining(); // Check that the frame type is minimally encoded. if (encoded_bytes != static_cast<size_t>(QuicDataWriter::GetVarInt62Len(frame_type))) { // The frame type was not minimally encoded. set_detailed_error("Frame type not minimally encoded."); return RaiseError(IETF_QUIC_PROTOCOL_VIOLATION); } if (IS_IETF_STREAM_FRAME(frame_type)) { QuicStreamFrame frame; if (!ProcessIetfStreamFrame(reader, frame_type, &frame)) { return RaiseError(QUIC_INVALID_STREAM_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stream frame " << frame; if (!visitor_->OnStreamFrame(frame)) { QUIC_DVLOG(1) << ENDPOINT << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } } else { switch (frame_type) { case IETF_PADDING: { QuicPaddingFrame frame; ProcessPaddingFrame(reader, &frame); QUIC_DVLOG(2) << ENDPOINT << "Processing IETF padding frame " << frame; if (!visitor_->OnPaddingFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } break; } case IETF_RST_STREAM: { QuicRstStreamFrame frame; if (!ProcessIetfResetStreamFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_RST_STREAM_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF reset stream frame " << frame; if (!visitor_->OnRstStreamFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } break; } case IETF_APPLICATION_CLOSE: case IETF_CONNECTION_CLOSE: { QuicConnectionCloseFrame frame; if (!ProcessIetfConnectionCloseFrame( reader, (frame_type == IETF_CONNECTION_CLOSE) ? IETF_QUIC_TRANSPORT_CONNECTION_CLOSE : IETF_QUIC_APPLICATION_CONNECTION_CLOSE, &frame)) { return RaiseError(QUIC_INVALID_CONNECTION_CLOSE_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF connection close frame " << frame; if (!visitor_->OnConnectionCloseFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } break; } case IETF_MAX_DATA: { QuicWindowUpdateFrame frame; if (!ProcessMaxDataFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_MAX_DATA_FRAME_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max data frame " << frame; if (!visitor_->OnWindowUpdateFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } break; } case IETF_MAX_STREAM_DATA: { QuicWindowUpdateFrame frame; if (!ProcessMaxStreamDataFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_MAX_STREAM_DATA_FRAME_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max stream data frame " << frame; if (!visitor_->OnWindowUpdateFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } break; } case IETF_MAX_STREAMS_BIDIRECTIONAL: case IETF_MAX_STREAMS_UNIDIRECTIONAL: { QuicMaxStreamsFrame frame; if (!ProcessMaxStreamsFrame(reader, &frame, frame_type)) { return RaiseError(QUIC_MAX_STREAMS_DATA); } QUIC_CODE_COUNT_N(quic_max_streams_received, 1, 2); QUIC_DVLOG(2) << ENDPOINT << "Processing IETF max streams frame " << frame; if (!visitor_->OnMaxStreamsFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } break; } case IETF_PING: { // Ping has no payload. QuicPingFrame ping_frame; QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ping frame " << ping_frame; if (!visitor_->OnPingFrame(ping_frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } break; } case IETF_DATA_BLOCKED: { QuicBlockedFrame frame; if (!ProcessDataBlockedFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_BLOCKED_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF blocked frame " << frame; if (!visitor_->OnBlockedFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } break; } case IETF_STREAM_DATA_BLOCKED: { QuicBlockedFrame frame; if (!ProcessStreamDataBlockedFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_STREAM_BLOCKED_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stream blocked frame " << frame; if (!visitor_->OnBlockedFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } break; } case IETF_STREAMS_BLOCKED_UNIDIRECTIONAL: case IETF_STREAMS_BLOCKED_BIDIRECTIONAL: { QuicStreamsBlockedFrame frame; if (!ProcessStreamsBlockedFrame(reader, &frame, frame_type)) { return RaiseError(QUIC_STREAMS_BLOCKED_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF streams blocked frame " << frame; if (!visitor_->OnStreamsBlockedFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } break; } case IETF_NEW_CONNECTION_ID: { QuicNewConnectionIdFrame frame; if (!ProcessNewConnectionIdFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_NEW_CONNECTION_ID_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF new connection ID frame " << frame; if (!visitor_->OnNewConnectionIdFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } break; } case IETF_RETIRE_CONNECTION_ID: { QuicRetireConnectionIdFrame frame; if (!ProcessRetireConnectionIdFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_RETIRE_CONNECTION_ID_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF retire connection ID frame " << frame; if (!visitor_->OnRetireConnectionIdFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } break; } case IETF_NEW_TOKEN: { QuicNewTokenFrame frame; if (!ProcessNewTokenFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_NEW_TOKEN); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF new token frame " << frame; if (!visitor_->OnNewTokenFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } break; } case IETF_STOP_SENDING: { QuicStopSendingFrame frame; if (!ProcessStopSendingFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_STOP_SENDING_FRAME_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF stop sending frame " << frame; if (!visitor_->OnStopSendingFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } break; } case IETF_ACK_ECN: case IETF_ACK: { QuicAckFrame frame; if (!ProcessIetfAckFrame(reader, frame_type, &frame)) { return RaiseError(QUIC_INVALID_ACK_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ACK frame " << frame; break; } case IETF_PATH_CHALLENGE: { QuicPathChallengeFrame frame; if (!ProcessPathChallengeFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_PATH_CHALLENGE_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF path challenge frame " << frame; if (!visitor_->OnPathChallengeFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } break; } case IETF_PATH_RESPONSE: { QuicPathResponseFrame frame; if (!ProcessPathResponseFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_PATH_RESPONSE_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF path response frame " << frame; if (!visitor_->OnPathResponseFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } break; } case IETF_EXTENSION_MESSAGE_NO_LENGTH_V99: QUIC_FALLTHROUGH_INTENDED; case IETF_EXTENSION_MESSAGE_V99: { QuicMessageFrame message_frame; if (!ProcessMessageFrame( reader, frame_type == IETF_EXTENSION_MESSAGE_NO_LENGTH_V99, &message_frame)) { return RaiseError(QUIC_INVALID_MESSAGE_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF message frame " << message_frame; if (!visitor_->OnMessageFrame(message_frame)) { QUIC_DVLOG(1) << ENDPOINT << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } break; } case IETF_CRYPTO: { QuicCryptoFrame frame; if (!ProcessCryptoFrame(reader, GetEncryptionLevel(header), &frame)) { return RaiseError(QUIC_INVALID_FRAME_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF crypto frame " << frame; if (!visitor_->OnCryptoFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } break; } case IETF_HANDSHAKE_DONE: { // HANDSHAKE_DONE has no payload. QuicHandshakeDoneFrame handshake_done_frame; if (!visitor_->OnHandshakeDoneFrame(handshake_done_frame)) { QUIC_DVLOG(1) << ENDPOINT << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } QUIC_DVLOG(2) << ENDPOINT << "Processing handshake done frame " << handshake_done_frame; break; } case IETF_ACK_FREQUENCY: { QuicAckFrequencyFrame frame; if (!ProcessAckFrequencyFrame(reader, &frame)) { return RaiseError(QUIC_INVALID_FRAME_DATA); } QUIC_DVLOG(2) << ENDPOINT << "Processing IETF ack frequency frame " << frame; if (!visitor_->OnAckFrequencyFrame(frame)) { QUIC_DVLOG(1) << "Visitor asked to stop further processing."; // Returning true since there was no parsing error. return true; } break; } default: set_detailed_error("Illegal frame type."); QUIC_DLOG(WARNING) << ENDPOINT << "Illegal frame type: " << static_cast<int>(frame_type); return RaiseError(QUIC_INVALID_FRAME_DATA); } } } return true; } namespace { // Create a mask that sets the last |num_bits| to 1 and the rest to 0. inline uint8_t GetMaskFromNumBits(uint8_t num_bits) { return (1u << num_bits) - 1; } // Extract |num_bits| from |flags| offset by |offset|. uint8_t ExtractBits(uint8_t flags, uint8_t num_bits, uint8_t offset) { return (flags >> offset) & GetMaskFromNumBits(num_bits); } // Extract the bit at position |offset| from |flags| as a bool. bool ExtractBit(uint8_t flags, uint8_t offset) { return ((flags >> offset) & GetMaskFromNumBits(1)) != 0; } // Set |num_bits|, offset by |offset| to |val| in |flags|. void SetBits(uint8_t* flags, uint8_t val, uint8_t num_bits, uint8_t offset) { DCHECK_LE(val, GetMaskFromNumBits(num_bits)); *flags |= val << offset; } // Set the bit at position |offset| to |val| in |flags|. void SetBit(uint8_t* flags, bool val, uint8_t offset) { SetBits(flags, val ? 1 : 0, 1, offset); } } // namespace bool QuicFramer::ProcessStreamFrame(QuicDataReader* reader, uint8_t frame_type, QuicStreamFrame* frame) { uint8_t stream_flags = frame_type; uint8_t stream_id_length = 0; uint8_t offset_length = 4; bool has_data_length = true; stream_flags &= ~kQuicFrameTypeStreamMask; // Read from right to left: StreamID, Offset, Data Length, Fin. stream_id_length = (stream_flags & kQuicStreamIDLengthMask) + 1; stream_flags >>= kQuicStreamIdShift; offset_length = (stream_flags & kQuicStreamOffsetMask); // There is no encoding for 1 byte, only 0 and 2 through 8. if (offset_length > 0) { offset_length += 1; } stream_flags >>= kQuicStreamShift; has_data_length = (stream_flags & kQuicStreamDataLengthMask) == kQuicStreamDataLengthMask; stream_flags >>= kQuicStreamDataLengthShift; frame->fin = (stream_flags & kQuicStreamFinMask) == kQuicStreamFinShift; uint64_t stream_id; if (!reader->ReadBytesToUInt64(stream_id_length, &stream_id)) { set_detailed_error("Unable to read stream_id."); return false; } frame->stream_id = static_cast<QuicStreamId>(stream_id); if (!reader->ReadBytesToUInt64(offset_length, &frame->offset)) { set_detailed_error("Unable to read offset."); return false; } // TODO(ianswett): Don't use quiche::QuicheStringPiece as an intermediary. quiche::QuicheStringPiece data; if (has_data_length) { if (!reader->ReadStringPiece16(&data)) { set_detailed_error("Unable to read frame data."); return false; } } else { if (!reader->ReadStringPiece(&data, reader->BytesRemaining())) { set_detailed_error("Unable to read frame data."); return false; } } frame->data_buffer = data.data(); frame->data_length = static_cast<uint16_t>(data.length()); return true; } bool QuicFramer::ProcessIetfStreamFrame(QuicDataReader* reader, uint8_t frame_type, QuicStreamFrame* frame) { // Read stream id from the frame. It's always present. if (!ReadUint32FromVarint62(reader, IETF_STREAM, &frame->stream_id)) { return false; } // If we have a data offset, read it. If not, set to 0. if (frame_type & IETF_STREAM_FRAME_OFF_BIT) { if (!reader->ReadVarInt62(&frame->offset)) { set_detailed_error("Unable to read stream data offset."); return false; } } else { // no offset in the frame, ensure it's 0 in the Frame. frame->offset = 0; } // If we have a data length, read it. If not, set to 0. if (frame_type & IETF_STREAM_FRAME_LEN_BIT) { uint64_t length; if (!reader->ReadVarInt62(&length)) { set_detailed_error("Unable to read stream data length."); return false; } if (length > std::numeric_limits<decltype(frame->data_length)>::max()) { set_detailed_error("Stream data length is too large."); return false; } frame->data_length = length; } else { // no length in the frame, it is the number of bytes remaining in the // packet. frame->data_length = reader->BytesRemaining(); } if (frame_type & IETF_STREAM_FRAME_FIN_BIT) { frame->fin = true; } else { frame->fin = false; } // TODO(ianswett): Don't use quiche::QuicheStringPiece as an intermediary. quiche::QuicheStringPiece data; if (!reader->ReadStringPiece(&data, frame->data_length)) { set_detailed_error("Unable to read frame data."); return false; } frame->data_buffer = data.data(); DCHECK_EQ(frame->data_length, data.length()); return true; } bool QuicFramer::ProcessCryptoFrame(QuicDataReader* reader, EncryptionLevel encryption_level, QuicCryptoFrame* frame) { frame->level = encryption_level; if (!reader->ReadVarInt62(&frame->offset)) { set_detailed_error("Unable to read crypto data offset."); return false; } uint64_t len; if (!reader->ReadVarInt62(&len) || len > std::numeric_limits<QuicPacketLength>::max()) { set_detailed_error("Invalid data length."); return false; } frame->data_length = len; // TODO(ianswett): Don't use quiche::QuicheStringPiece as an intermediary. quiche::QuicheStringPiece data; if (!reader->ReadStringPiece(&data, frame->data_length)) { set_detailed_error("Unable to read frame data."); return false; } frame->data_buffer = data.data(); return true; } bool QuicFramer::ProcessAckFrequencyFrame(QuicDataReader* reader, QuicAckFrequencyFrame* frame) { if (!reader->ReadVarInt62(&frame->sequence_number)) { set_detailed_error("Unable to read sequence number."); return false; } if (!reader->ReadVarInt62(&frame->packet_tolerance)) { set_detailed_error("Unable to read packet tolerance."); return false; } if (frame->packet_tolerance == 0) { set_detailed_error("Invalid packet tolerance."); return false; } uint64_t max_ack_delay_us; if (!reader->ReadVarInt62(&max_ack_delay_us)) { set_detailed_error("Unable to read max_ack_delay_us."); return false; } constexpr uint64_t kMaxAckDelayUsBound = 1u << 24; if (max_ack_delay_us > kMaxAckDelayUsBound) { set_detailed_error("Invalid max_ack_delay_us."); return false; } frame->max_ack_delay = QuicTime::Delta::FromMicroseconds(max_ack_delay_us); uint8_t ignore_order; if (!reader->ReadUInt8(&ignore_order)) { set_detailed_error("Unable to read ignore_order."); return false; } if (ignore_order > 1) { set_detailed_error("Invalid ignore_order."); return false; } frame->ignore_order = ignore_order; return true; } bool QuicFramer::ProcessAckFrame(QuicDataReader* reader, uint8_t frame_type) { const bool has_ack_blocks = ExtractBit(frame_type, kQuicHasMultipleAckBlocksOffset); uint8_t num_ack_blocks = 0; uint8_t num_received_packets = 0; // Determine the two lengths from the frame type: largest acked length, // ack block length. const QuicPacketNumberLength ack_block_length = ReadAckPacketNumberLength( ExtractBits(frame_type, kQuicSequenceNumberLengthNumBits, kActBlockLengthOffset)); const QuicPacketNumberLength largest_acked_length = ReadAckPacketNumberLength( ExtractBits(frame_type, kQuicSequenceNumberLengthNumBits, kLargestAckedOffset)); uint64_t largest_acked; if (!reader->ReadBytesToUInt64(largest_acked_length, &largest_acked)) { set_detailed_error("Unable to read largest acked."); return false; } if (largest_acked < first_sending_packet_number_.ToUint64()) { // Connection always sends packet starting from kFirstSendingPacketNumber > // 0, peer has observed an unsent packet. set_detailed_error("Largest acked is 0."); return false; } uint64_t ack_delay_time_us; if (!reader->ReadUFloat16(&ack_delay_time_us)) { set_detailed_error("Unable to read ack delay time."); return false; } if (!visitor_->OnAckFrameStart( QuicPacketNumber(largest_acked), ack_delay_time_us == kUFloat16MaxValue ? QuicTime::Delta::Infinite() : QuicTime::Delta::FromMicroseconds(ack_delay_time_us))) { // The visitor suppresses further processing of the packet. Although this is // not a parsing error, returns false as this is in middle of processing an // ack frame, set_detailed_error("Visitor suppresses further processing of ack frame."); return false; } if (has_ack_blocks && !reader->ReadUInt8(&num_ack_blocks)) { set_detailed_error("Unable to read num of ack blocks."); return false; } uint64_t first_block_length; if (!reader->ReadBytesToUInt64(ack_block_length, &first_block_length)) { set_detailed_error("Unable to read first ack block length."); return false; } if (first_block_length == 0) { set_detailed_error("First block length is zero."); return false; } bool first_ack_block_underflow = first_block_length > largest_acked + 1; if (first_block_length + first_sending_packet_number_.ToUint64() > largest_acked + 1) { first_ack_block_underflow = true; } if (first_ack_block_underflow) { set_detailed_error( quiche::QuicheStrCat("Underflow with first ack block length ", first_block_length, " largest acked is ", largest_acked, ".") .c_str()); return false; } uint64_t first_received = largest_acked + 1 - first_block_length; if (!visitor_->OnAckRange(QuicPacketNumber(first_received), QuicPacketNumber(largest_acked + 1))) { // The visitor suppresses further processing of the packet. Although // this is not a parsing error, returns false as this is in middle // of processing an ack frame, set_detailed_error("Visitor suppresses further processing of ack frame."); return false; } if (num_ack_blocks > 0) { for (size_t i = 0; i < num_ack_blocks; ++i) { uint8_t gap = 0; if (!reader->ReadUInt8(&gap)) { set_detailed_error("Unable to read gap to next ack block."); return false; } uint64_t current_block_length; if (!reader->ReadBytesToUInt64(ack_block_length, &current_block_length)) { set_detailed_error("Unable to ack block length."); return false; } bool ack_block_underflow = first_received < gap + current_block_length; if (first_received < gap + current_block_length + first_sending_packet_number_.ToUint64()) { ack_block_underflow = true; } if (ack_block_underflow) { set_detailed_error( quiche::QuicheStrCat("Underflow with ack block length ", current_block_length, ", end of block is ", first_received - gap, ".") .c_str()); return false; } first_received -= (gap + current_block_length); if (current_block_length > 0) { if (!visitor_->OnAckRange( QuicPacketNumber(first_received), QuicPacketNumber(first_received) + current_block_length)) { // The visitor suppresses further processing of the packet. Although // this is not a parsing error, returns false as this is in middle // of processing an ack frame, set_detailed_error( "Visitor suppresses further processing of ack frame."); return false; } } } } if (!reader->ReadUInt8(&num_received_packets)) { set_detailed_error("Unable to read num received packets."); return false; } if (!ProcessTimestampsInAckFrame(num_received_packets, QuicPacketNumber(largest_acked), reader)) { return false; } // Done processing the ACK frame. if (!visitor_->OnAckFrameEnd(QuicPacketNumber(first_received))) { set_detailed_error( "Error occurs when visitor finishes processing the ACK frame."); return false; } return true; } bool QuicFramer::ProcessTimestampsInAckFrame(uint8_t num_received_packets, QuicPacketNumber largest_acked, QuicDataReader* reader) { if (num_received_packets == 0) { return true; } uint8_t delta_from_largest_observed; if (!reader->ReadUInt8(&delta_from_largest_observed)) { set_detailed_error("Unable to read sequence delta in received packets."); return false; } if (largest_acked.ToUint64() <= delta_from_largest_observed) { set_detailed_error( quiche::QuicheStrCat("delta_from_largest_observed too high: ", delta_from_largest_observed, ", largest_acked: ", largest_acked.ToUint64()) .c_str()); return false; } // Time delta from the framer creation. uint32_t time_delta_us; if (!reader->ReadUInt32(&time_delta_us)) { set_detailed_error("Unable to read time delta in received packets."); return false; } QuicPacketNumber seq_num = largest_acked - delta_from_largest_observed; if (process_timestamps_) { last_timestamp_ = CalculateTimestampFromWire(time_delta_us); visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_); } for (uint8_t i = 1; i < num_received_packets; ++i) { if (!reader->ReadUInt8(&delta_from_largest_observed)) { set_detailed_error("Unable to read sequence delta in received packets."); return false; } if (largest_acked.ToUint64() <= delta_from_largest_observed) { set_detailed_error( quiche::QuicheStrCat("delta_from_largest_observed too high: ", delta_from_largest_observed, ", largest_acked: ", largest_acked.ToUint64()) .c_str()); return false; } seq_num = largest_acked - delta_from_largest_observed; // Time delta from the previous timestamp. uint64_t incremental_time_delta_us; if (!reader->ReadUFloat16(&incremental_time_delta_us)) { set_detailed_error( "Unable to read incremental time delta in received packets."); return false; } if (process_timestamps_) { last_timestamp_ = last_timestamp_ + QuicTime::Delta::FromMicroseconds( incremental_time_delta_us); visitor_->OnAckTimestamp(seq_num, creation_time_ + last_timestamp_); } } return true; } bool QuicFramer::ProcessIetfAckFrame(QuicDataReader* reader, uint64_t frame_type, QuicAckFrame* ack_frame) { uint64_t largest_acked; if (!reader->ReadVarInt62(&largest_acked)) { set_detailed_error("Unable to read largest acked."); return false; } if (largest_acked < first_sending_packet_number_.ToUint64()) { // Connection always sends packet starting from kFirstSendingPacketNumber > // 0, peer has observed an unsent packet. set_detailed_error("Largest acked is 0."); return false; } ack_frame->largest_acked = static_cast<QuicPacketNumber>(largest_acked); uint64_t ack_delay_time_in_us; if (!reader->ReadVarInt62(&ack_delay_time_in_us)) { set_detailed_error("Unable to read ack delay time."); return false; } if (ack_delay_time_in_us >= (kVarInt62MaxValue >> peer_ack_delay_exponent_)) { ack_frame->ack_delay_time = QuicTime::Delta::Infinite(); } else { ack_delay_time_in_us = (ack_delay_time_in_us << peer_ack_delay_exponent_); ack_frame->ack_delay_time = QuicTime::Delta::FromMicroseconds(ack_delay_time_in_us); } if (!visitor_->OnAckFrameStart(QuicPacketNumber(largest_acked), ack_frame->ack_delay_time)) { // The visitor suppresses further processing of the packet. Although this is // not a parsing error, returns false as this is in middle of processing an // ACK frame. set_detailed_error("Visitor suppresses further processing of ACK frame."); return false; } // Get number of ACK blocks from the packet. uint64_t ack_block_count; if (!reader->ReadVarInt62(&ack_block_count)) { set_detailed_error("Unable to read ack block count."); return false; } // There always is a first ACK block, which is the (number of packets being // acked)-1, up to and including the packet at largest_acked. Therefore if the // value is 0, then only largest is acked. If it is 1, then largest-1, // largest] are acked, etc uint64_t ack_block_value; if (!reader->ReadVarInt62(&ack_block_value)) { set_detailed_error("Unable to read first ack block length."); return false; } // Calculate the packets being acked in the first block. // +1 because AddRange implementation requires [low,high) uint64_t block_high = largest_acked + 1; uint64_t block_low = largest_acked - ack_block_value; // ack_block_value is the number of packets preceding the // largest_acked packet which are in the block being acked. Thus, // its maximum value is largest_acked-1. Test this, reporting an // error if the value is wrong. if (ack_block_value + first_sending_packet_number_.ToUint64() > largest_acked) { set_detailed_error( quiche::QuicheStrCat("Underflow with first ack block length ", ack_block_value + 1, " largest acked is ", largest_acked, ".") .c_str()); return false; } if (!visitor_->OnAckRange(QuicPacketNumber(block_low), QuicPacketNumber(block_high))) { // The visitor suppresses further processing of the packet. Although // this is not a parsing error, returns false as this is in middle // of processing an ACK frame. set_detailed_error("Visitor suppresses further processing of ACK frame."); return false; } while (ack_block_count != 0) { uint64_t gap_block_value; // Get the sizes of the gap and ack blocks, if (!reader->ReadVarInt62(&gap_block_value)) { set_detailed_error("Unable to read gap block value."); return false; } // It's an error if the gap is larger than the space from packet // number 0 to the start of the block that's just been acked, PLUS // there must be space for at least 1 packet to be acked. For // example, if block_low is 10 and gap_block_value is 9, it means // the gap block is 10 packets long, leaving no room for a packet // to be acked. Thus, gap_block_value+2 can not be larger than // block_low. // The test is written this way to detect wrap-arounds. if ((gap_block_value + 2) > block_low) { set_detailed_error( quiche::QuicheStrCat("Underflow with gap block length ", gap_block_value + 1, " previous ack block start is ", block_low, ".") .c_str()); return false; } // Adjust block_high to be the top of the next ack block. // There is a gap of |gap_block_value| packets between the bottom // of ack block N and top of block N+1. Note that gap_block_value // is he size of the gap minus 1 (per the QUIC protocol), and // block_high is the packet number of the first packet of the gap // (per the implementation of OnAckRange/AddAckRange, below). block_high = block_low - 1 - gap_block_value; if (!reader->ReadVarInt62(&ack_block_value)) { set_detailed_error("Unable to read ack block value."); return false; } if (ack_block_value + first_sending_packet_number_.ToUint64() > (block_high - 1)) { set_detailed_error( quiche::QuicheStrCat("Underflow with ack block length ", ack_block_value + 1, " latest ack block end is ", block_high - 1, ".") .c_str()); return false; } // Calculate the low end of the new nth ack block. The +1 is // because the encoded value is the blocksize-1. block_low = block_high - 1 - ack_block_value; if (!visitor_->OnAckRange(QuicPacketNumber(block_low), QuicPacketNumber(block_high))) { // The visitor suppresses further processing of the packet. Although // this is not a parsing error, returns false as this is in middle // of processing an ACK frame. set_detailed_error("Visitor suppresses further processing of ACK frame."); return false; } // Another one done. ack_block_count--; } if (frame_type == IETF_ACK_ECN) { ack_frame->ecn_counters_populated = true; if (!reader->ReadVarInt62(&ack_frame->ect_0_count)) { set_detailed_error("Unable to read ack ect_0_count."); return false; } if (!reader->ReadVarInt62(&ack_frame->ect_1_count)) { set_detailed_error("Unable to read ack ect_1_count."); return false; } if (!reader->ReadVarInt62(&ack_frame->ecn_ce_count)) { set_detailed_error("Unable to read ack ecn_ce_count."); return false; } } else { ack_frame->ecn_counters_populated = false; ack_frame->ect_0_count = 0; ack_frame->ect_1_count = 0; ack_frame->ecn_ce_count = 0; } // TODO(fayang): Report ECN counts to visitor when they are actually used. if (!visitor_->OnAckFrameEnd(QuicPacketNumber(block_low))) { set_detailed_error( "Error occurs when visitor finishes processing the ACK frame."); return false; } return true; } bool QuicFramer::ProcessStopWaitingFrame(QuicDataReader* reader, const QuicPacketHeader& header, QuicStopWaitingFrame* stop_waiting) { uint64_t least_unacked_delta; if (!reader->ReadBytesToUInt64(header.packet_number_length, &least_unacked_delta)) { set_detailed_error("Unable to read least unacked delta."); return false; } if (header.packet_number.ToUint64() <= least_unacked_delta) { set_detailed_error("Invalid unacked delta."); return false; } stop_waiting->least_unacked = header.packet_number - least_unacked_delta; return true; } bool QuicFramer::ProcessRstStreamFrame(QuicDataReader* reader, QuicRstStreamFrame* frame) { if (!reader->ReadUInt32(&frame->stream_id)) { set_detailed_error("Unable to read stream_id."); return false; } if (!reader->ReadUInt64(&frame->byte_offset)) { set_detailed_error("Unable to read rst stream sent byte offset."); return false; } uint32_t error_code; if (!reader->ReadUInt32(&error_code)) { set_detailed_error("Unable to read rst stream error code."); return false; } if (error_code >= QUIC_STREAM_LAST_ERROR) { // Ignore invalid stream error code if any. error_code = QUIC_STREAM_LAST_ERROR; } frame->error_code = static_cast<QuicRstStreamErrorCode>(error_code); return true; } bool QuicFramer::ProcessConnectionCloseFrame(QuicDataReader* reader, QuicConnectionCloseFrame* frame) { uint32_t error_code; frame->close_type = GOOGLE_QUIC_CONNECTION_CLOSE; if (!reader->ReadUInt32(&error_code)) { set_detailed_error("Unable to read connection close error code."); return false; } if (error_code >= QUIC_LAST_ERROR) { // Ignore invalid QUIC error code if any. error_code = QUIC_LAST_ERROR; } // For Google QUIC connection closes, |wire_error_code| and |quic_error_code| // must have the same value. frame->wire_error_code = error_code; frame->quic_error_code = static_cast<QuicErrorCode>(error_code); quiche::QuicheStringPiece error_details; if (!reader->ReadStringPiece16(&error_details)) { set_detailed_error("Unable to read connection close error details."); return false; } frame->error_details = std::string(error_details); return true; } bool QuicFramer::ProcessGoAwayFrame(QuicDataReader* reader, QuicGoAwayFrame* frame) { uint32_t error_code; if (!reader->ReadUInt32(&error_code)) { set_detailed_error("Unable to read go away error code."); return false; } if (error_code >= QUIC_LAST_ERROR) { // Ignore invalid QUIC error code if any. error_code = QUIC_LAST_ERROR; } frame->error_code = static_cast<QuicErrorCode>(error_code); uint32_t stream_id; if (!reader->ReadUInt32(&stream_id)) { set_detailed_error("Unable to read last good stream id."); return false; } frame->last_good_stream_id = static_cast<QuicStreamId>(stream_id); quiche::QuicheStringPiece reason_phrase; if (!reader->ReadStringPiece16(&reason_phrase)) { set_detailed_error("Unable to read goaway reason."); return false; } frame->reason_phrase = std::string(reason_phrase); return true; } bool QuicFramer::ProcessWindowUpdateFrame(QuicDataReader* reader, QuicWindowUpdateFrame* frame) { if (!reader->ReadUInt32(&frame->stream_id)) { set_detailed_error("Unable to read stream_id."); return false; } if (!reader->ReadUInt64(&frame->max_data)) { set_detailed_error("Unable to read window byte_offset."); return false; } return true; } bool QuicFramer::ProcessBlockedFrame(QuicDataReader* reader, QuicBlockedFrame* frame) { DCHECK(!VersionHasIetfQuicFrames(version_.transport_version)) << "Attempt to process non-IETF QUIC frames in an IETF QUIC version."; if (!reader->ReadUInt32(&frame->stream_id)) { set_detailed_error("Unable to read stream_id."); return false; } return true; } void QuicFramer::ProcessPaddingFrame(QuicDataReader* reader, QuicPaddingFrame* frame) { // Type byte has been read. frame->num_padding_bytes = 1; uint8_t next_byte; while (!reader->IsDoneReading() && reader->PeekByte() == 0x00) { reader->ReadBytes(&next_byte, 1); DCHECK_EQ(0x00, next_byte); ++frame->num_padding_bytes; } } bool QuicFramer::ProcessMessageFrame(QuicDataReader* reader, bool no_message_length, QuicMessageFrame* frame) { if (no_message_length) { quiche::QuicheStringPiece remaining(reader->ReadRemainingPayload()); frame->data = remaining.data(); frame->message_length = remaining.length(); return true; } uint64_t message_length; if (!reader->ReadVarInt62(&message_length)) { set_detailed_error("Unable to read message length"); return false; } quiche::QuicheStringPiece message_piece; if (!reader->ReadStringPiece(&message_piece, message_length)) { set_detailed_error("Unable to read message data"); return false; } frame->data = message_piece.data(); frame->message_length = message_length; return true; } // static quiche::QuicheStringPiece QuicFramer::GetAssociatedDataFromEncryptedPacket( QuicTransportVersion version, const QuicEncryptedPacket& encrypted, QuicConnectionIdLength destination_connection_id_length, QuicConnectionIdLength source_connection_id_length, bool includes_version, bool includes_diversification_nonce, QuicPacketNumberLength packet_number_length, QuicVariableLengthIntegerLength retry_token_length_length, uint64_t retry_token_length, QuicVariableLengthIntegerLength length_length) { // TODO(ianswett): This is identical to QuicData::AssociatedData. return quiche::QuicheStringPiece( encrypted.data(), GetStartOfEncryptedData(version, destination_connection_id_length, source_connection_id_length, includes_version, includes_diversification_nonce, packet_number_length, retry_token_length_length, retry_token_length, length_length)); } void QuicFramer::SetDecrypter(EncryptionLevel level, std::unique_ptr<QuicDecrypter> decrypter) { DCHECK_EQ(alternative_decrypter_level_, NUM_ENCRYPTION_LEVELS); DCHECK_GE(level, decrypter_level_); DCHECK(!version_.KnowsWhichDecrypterToUse()); QUIC_DVLOG(1) << ENDPOINT << "Setting decrypter from level " << decrypter_level_ << " to " << level; decrypter_[decrypter_level_] = nullptr; decrypter_[level] = std::move(decrypter); decrypter_level_ = level; } void QuicFramer::SetAlternativeDecrypter( EncryptionLevel level, std::unique_ptr<QuicDecrypter> decrypter, bool latch_once_used) { DCHECK_NE(level, decrypter_level_); DCHECK(!version_.KnowsWhichDecrypterToUse()); QUIC_DVLOG(1) << ENDPOINT << "Setting alternative decrypter from level " << alternative_decrypter_level_ << " to " << level; if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) { decrypter_[alternative_decrypter_level_] = nullptr; } decrypter_[level] = std::move(decrypter); alternative_decrypter_level_ = level; alternative_decrypter_latch_ = latch_once_used; } void QuicFramer::InstallDecrypter(EncryptionLevel level, std::unique_ptr<QuicDecrypter> decrypter) { DCHECK(version_.KnowsWhichDecrypterToUse()); QUIC_DVLOG(1) << ENDPOINT << "Installing decrypter at level " << level; decrypter_[level] = std::move(decrypter); } void QuicFramer::RemoveDecrypter(EncryptionLevel level) { DCHECK(version_.KnowsWhichDecrypterToUse()); QUIC_DVLOG(1) << ENDPOINT << "Removing decrypter at level " << level; decrypter_[level] = nullptr; } const QuicDecrypter* QuicFramer::GetDecrypter(EncryptionLevel level) const { DCHECK(version_.KnowsWhichDecrypterToUse()); return decrypter_[level].get(); } const QuicDecrypter* QuicFramer::decrypter() const { return decrypter_[decrypter_level_].get(); } const QuicDecrypter* QuicFramer::alternative_decrypter() const { if (alternative_decrypter_level_ == NUM_ENCRYPTION_LEVELS) { return nullptr; } return decrypter_[alternative_decrypter_level_].get(); } void QuicFramer::SetEncrypter(EncryptionLevel level, std::unique_ptr<QuicEncrypter> encrypter) { DCHECK_GE(level, 0); DCHECK_LT(level, NUM_ENCRYPTION_LEVELS); QUIC_DVLOG(1) << ENDPOINT << "Setting encrypter at level " << level; encrypter_[level] = std::move(encrypter); } void QuicFramer::RemoveEncrypter(EncryptionLevel level) { QUIC_DVLOG(1) << ENDPOINT << "Removing encrypter of " << level; encrypter_[level] = nullptr; } void QuicFramer::SetInitialObfuscators(QuicConnectionId connection_id) { CrypterPair crypters; CryptoUtils::CreateInitialObfuscators(perspective_, version_, connection_id, &crypters); encrypter_[ENCRYPTION_INITIAL] = std::move(crypters.encrypter); decrypter_[ENCRYPTION_INITIAL] = std::move(crypters.decrypter); } size_t QuicFramer::EncryptInPlace(EncryptionLevel level, QuicPacketNumber packet_number, size_t ad_len, size_t total_len, size_t buffer_len, char* buffer) { DCHECK(packet_number.IsInitialized()); if (encrypter_[level] == nullptr) { QUIC_BUG << ENDPOINT << "Attempted to encrypt in place without encrypter at level " << level; RaiseError(QUIC_ENCRYPTION_FAILURE); return 0; } size_t output_length = 0; if (!encrypter_[level]->EncryptPacket( packet_number.ToUint64(), quiche::QuicheStringPiece(buffer, ad_len), // Associated data quiche::QuicheStringPiece(buffer + ad_len, total_len - ad_len), // Plaintext buffer + ad_len, // Destination buffer &output_length, buffer_len - ad_len)) { RaiseError(QUIC_ENCRYPTION_FAILURE); return 0; } if (version_.HasHeaderProtection() && !ApplyHeaderProtection(level, buffer, ad_len + output_length, ad_len)) { QUIC_DLOG(ERROR) << "Applying header protection failed."; RaiseError(QUIC_ENCRYPTION_FAILURE); return 0; } return ad_len + output_length; } namespace { const size_t kHPSampleLen = 16; constexpr bool IsLongHeader(uint8_t type_byte) { return (type_byte & FLAGS_LONG_HEADER) != 0; } } // namespace bool QuicFramer::ApplyHeaderProtection(EncryptionLevel level, char* buffer, size_t buffer_len, size_t ad_len) { QuicDataReader buffer_reader(buffer, buffer_len); QuicDataWriter buffer_writer(buffer_len, buffer); // The sample starts 4 bytes after the start of the packet number. if (ad_len < last_written_packet_number_length_) { return false; } size_t pn_offset = ad_len - last_written_packet_number_length_; // Sample the ciphertext and generate the mask to use for header protection. size_t sample_offset = pn_offset + 4; QuicDataReader sample_reader(buffer, buffer_len); quiche::QuicheStringPiece sample; if (!sample_reader.Seek(sample_offset) || !sample_reader.ReadStringPiece(&sample, kHPSampleLen)) { QUIC_BUG << "Not enough bytes to sample: sample_offset " << sample_offset << ", sample len: " << kHPSampleLen << ", buffer len: " << buffer_len; return false; } if (encrypter_[level] == nullptr) { QUIC_BUG << ENDPOINT << "Attempted to apply header protection without encrypter at level " << level << " using " << version_; return false; } std::string mask = encrypter_[level]->GenerateHeaderProtectionMask(sample); if (mask.empty()) { QUIC_BUG << "Unable to generate header protection mask."; return false; } QuicDataReader mask_reader(mask.data(), mask.size()); // Apply the mask to the 4 or 5 least significant bits of the first byte. uint8_t bitmask = 0x1f; uint8_t type_byte; if (!buffer_reader.ReadUInt8(&type_byte)) { return false; } QuicLongHeaderType header_type; if (IsLongHeader(type_byte)) { bitmask = 0x0f; if (!GetLongHeaderType(type_byte, &header_type)) { return false; } } uint8_t mask_byte; if (!mask_reader.ReadUInt8(&mask_byte) || !buffer_writer.WriteUInt8(type_byte ^ (mask_byte & bitmask))) { return false; } // Adjust |pn_offset| to account for the diversification nonce. if (IsLongHeader(type_byte) && header_type == ZERO_RTT_PROTECTED && perspective_ == Perspective::IS_SERVER && version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO) { if (pn_offset <= kDiversificationNonceSize) { QUIC_BUG << "Expected diversification nonce, but not enough bytes"; return false; } pn_offset -= kDiversificationNonceSize; } // Advance the reader and writer to the packet number. Both the reader and // writer have each read/written one byte. if (!buffer_writer.Seek(pn_offset - 1) || !buffer_reader.Seek(pn_offset - 1)) { return false; } // Apply the rest of the mask to the packet number. for (size_t i = 0; i < last_written_packet_number_length_; ++i) { uint8_t buffer_byte; uint8_t mask_byte; if (!mask_reader.ReadUInt8(&mask_byte) || !buffer_reader.ReadUInt8(&buffer_byte) || !buffer_writer.WriteUInt8(buffer_byte ^ mask_byte)) { return false; } } return true; } bool QuicFramer::RemoveHeaderProtection(QuicDataReader* reader, const QuicEncryptedPacket& packet, QuicPacketHeader* header, uint64_t* full_packet_number, std::vector<char>* associated_data) { EncryptionLevel expected_decryption_level = GetEncryptionLevel(*header); QuicDecrypter* decrypter = decrypter_[expected_decryption_level].get(); if (decrypter == nullptr) { QUIC_DVLOG(1) << ENDPOINT << "No decrypter available for removing header protection at level " << expected_decryption_level; return false; } bool has_diversification_nonce = header->form == IETF_QUIC_LONG_HEADER_PACKET && header->long_packet_type == ZERO_RTT_PROTECTED && perspective_ == Perspective::IS_CLIENT && version_.handshake_protocol == PROTOCOL_QUIC_CRYPTO; // Read a sample from the ciphertext and compute the mask to use for header // protection. quiche::QuicheStringPiece remaining_packet = reader->PeekRemainingPayload(); QuicDataReader sample_reader(remaining_packet); // The sample starts 4 bytes after the start of the packet number. quiche::QuicheStringPiece pn; if (!sample_reader.ReadStringPiece(&pn, 4)) { QUIC_DVLOG(1) << "Not enough data to sample"; return false; } if (has_diversification_nonce) { // In Google QUIC, the diversification nonce comes between the packet number // and the sample. if (!sample_reader.Seek(kDiversificationNonceSize)) { QUIC_DVLOG(1) << "No diversification nonce to skip over"; return false; } } std::string mask = decrypter->GenerateHeaderProtectionMask(&sample_reader); QuicDataReader mask_reader(mask.data(), mask.size()); if (mask.empty()) { QUIC_DVLOG(1) << "Failed to compute mask"; return false; } // Unmask the rest of the type byte. uint8_t bitmask = 0x1f; if (IsLongHeader(header->type_byte)) { bitmask = 0x0f; } uint8_t mask_byte; if (!mask_reader.ReadUInt8(&mask_byte)) { QUIC_DVLOG(1) << "No first byte to read from mask"; return false; } header->type_byte ^= (mask_byte & bitmask); // Compute the packet number length. header->packet_number_length = static_cast<QuicPacketNumberLength>((header->type_byte & 0x03) + 1); char pn_buffer[IETF_MAX_PACKET_NUMBER_LENGTH] = {}; QuicDataWriter pn_writer(QUICHE_ARRAYSIZE(pn_buffer), pn_buffer); // Read the (protected) packet number from the reader and unmask the packet // number. for (size_t i = 0; i < header->packet_number_length; ++i) { uint8_t protected_pn_byte, mask_byte; if (!mask_reader.ReadUInt8(&mask_byte) || !reader->ReadUInt8(&protected_pn_byte) || !pn_writer.WriteUInt8(protected_pn_byte ^ mask_byte)) { QUIC_DVLOG(1) << "Failed to unmask packet number"; return false; } } QuicDataReader packet_number_reader(pn_writer.data(), pn_writer.length()); QuicPacketNumber base_packet_number; if (supports_multiple_packet_number_spaces_) { PacketNumberSpace pn_space = GetPacketNumberSpace(*header); if (pn_space == NUM_PACKET_NUMBER_SPACES) { return false; } base_packet_number = largest_decrypted_packet_numbers_[pn_space]; } else { base_packet_number = largest_packet_number_; } if (!ProcessAndCalculatePacketNumber( &packet_number_reader, header->packet_number_length, base_packet_number, full_packet_number)) { return false; } // Get the associated data, and apply the same unmasking operations to it. quiche::QuicheStringPiece ad = GetAssociatedDataFromEncryptedPacket( version_.transport_version, packet, GetIncludedDestinationConnectionIdLength(*header), GetIncludedSourceConnectionIdLength(*header), header->version_flag, has_diversification_nonce, header->packet_number_length, header->retry_token_length_length, header->retry_token.length(), header->length_length); *associated_data = std::vector<char>(ad.begin(), ad.end()); QuicDataWriter ad_writer(associated_data->size(), associated_data->data()); // Apply the unmasked type byte and packet number to |associated_data|. if (!ad_writer.WriteUInt8(header->type_byte)) { return false; } // Put the packet number at the end of the AD, or if there's a diversification // nonce, before that (which is at the end of the AD). size_t seek_len = ad_writer.remaining() - header->packet_number_length; if (has_diversification_nonce) { seek_len -= kDiversificationNonceSize; } if (!ad_writer.Seek(seek_len) || !ad_writer.WriteBytes(pn_writer.data(), pn_writer.length())) { QUIC_DVLOG(1) << "Failed to apply unmasking operations to AD"; return false; } return true; } size_t QuicFramer::EncryptPayload(EncryptionLevel level, QuicPacketNumber packet_number, const QuicPacket& packet, char* buffer, size_t buffer_len) { DCHECK(packet_number.IsInitialized()); if (encrypter_[level] == nullptr) { QUIC_BUG << ENDPOINT << "Attempted to encrypt without encrypter at level " << level; RaiseError(QUIC_ENCRYPTION_FAILURE); return 0; } quiche::QuicheStringPiece associated_data = packet.AssociatedData(version_.transport_version); // Copy in the header, because the encrypter only populates the encrypted // plaintext content. const size_t ad_len = associated_data.length(); if (packet.length() < ad_len) { QUIC_BUG << ENDPOINT << "packet is shorter than associated data length. version:" << version() << ", packet length:" << packet.length() << ", associated data length:" << ad_len; RaiseError(QUIC_ENCRYPTION_FAILURE); return 0; } memmove(buffer, associated_data.data(), ad_len); // Encrypt the plaintext into the buffer. size_t output_length = 0; if (!encrypter_[level]->EncryptPacket( packet_number.ToUint64(), associated_data, packet.Plaintext(version_.transport_version), buffer + ad_len, &output_length, buffer_len - ad_len)) { RaiseError(QUIC_ENCRYPTION_FAILURE); return 0; } if (version_.HasHeaderProtection() && !ApplyHeaderProtection(level, buffer, ad_len + output_length, ad_len)) { QUIC_DLOG(ERROR) << "Applying header protection failed."; RaiseError(QUIC_ENCRYPTION_FAILURE); return 0; } return ad_len + output_length; } size_t QuicFramer::GetCiphertextSize(EncryptionLevel level, size_t plaintext_size) const { if (encrypter_[level] == nullptr) { QUIC_BUG << ENDPOINT << "Attempted to get ciphertext size without encrypter at level " << level << " using " << version_; return plaintext_size; } return encrypter_[level]->GetCiphertextSize(plaintext_size); } size_t QuicFramer::GetMaxPlaintextSize(size_t ciphertext_size) { // In order to keep the code simple, we don't have the current encryption // level to hand. Both the NullEncrypter and AES-GCM have a tag length of 12. size_t min_plaintext_size = ciphertext_size; for (int i = ENCRYPTION_INITIAL; i < NUM_ENCRYPTION_LEVELS; i++) { if (encrypter_[i] != nullptr) { size_t size = encrypter_[i]->GetMaxPlaintextSize(ciphertext_size); if (size < min_plaintext_size) { min_plaintext_size = size; } } } return min_plaintext_size; } bool QuicFramer::DecryptPayload(quiche::QuicheStringPiece encrypted, quiche::QuicheStringPiece associated_data, const QuicPacketHeader& header, char* decrypted_buffer, size_t buffer_length, size_t* decrypted_length, EncryptionLevel* decrypted_level) { if (!EncryptionLevelIsValid(decrypter_level_)) { QUIC_BUG << "Attempted to decrypt with bad decrypter_level_"; return false; } EncryptionLevel level = decrypter_level_; QuicDecrypter* decrypter = decrypter_[level].get(); QuicDecrypter* alternative_decrypter = nullptr; if (version().KnowsWhichDecrypterToUse()) { if (header.form == GOOGLE_QUIC_PACKET) { QUIC_BUG << "Attempted to decrypt GOOGLE_QUIC_PACKET with a version that " "knows which decrypter to use"; return false; } level = GetEncryptionLevel(header); if (!EncryptionLevelIsValid(level)) { QUIC_BUG << "Attempted to decrypt with bad level"; return false; } decrypter = decrypter_[level].get(); if (decrypter == nullptr) { return false; } if (level == ENCRYPTION_ZERO_RTT && perspective_ == Perspective::IS_CLIENT && header.nonce != nullptr) { decrypter->SetDiversificationNonce(*header.nonce); } } else if (alternative_decrypter_level_ != NUM_ENCRYPTION_LEVELS) { if (!EncryptionLevelIsValid(alternative_decrypter_level_)) { QUIC_BUG << "Attempted to decrypt with bad alternative_decrypter_level_"; return false; } alternative_decrypter = decrypter_[alternative_decrypter_level_].get(); } if (decrypter == nullptr) { QUIC_BUG << "Attempting to decrypt without decrypter, encryption level:" << level << " version:" << version(); return false; } bool success = decrypter->DecryptPacket( header.packet_number.ToUint64(), associated_data, encrypted, decrypted_buffer, decrypted_length, buffer_length); if (success) { visitor_->OnDecryptedPacket(level); *decrypted_level = level; } else if (alternative_decrypter != nullptr) { if (header.nonce != nullptr) { DCHECK_EQ(perspective_, Perspective::IS_CLIENT); alternative_decrypter->SetDiversificationNonce(*header.nonce); } bool try_alternative_decryption = true; if (alternative_decrypter_level_ == ENCRYPTION_ZERO_RTT) { if (perspective_ == Perspective::IS_CLIENT) { if (header.nonce == nullptr) { // Can not use INITIAL decryption without a diversification nonce. try_alternative_decryption = false; } } else { DCHECK(header.nonce == nullptr); } } if (try_alternative_decryption) { success = alternative_decrypter->DecryptPacket( header.packet_number.ToUint64(), associated_data, encrypted, decrypted_buffer, decrypted_length, buffer_length); } if (success) { visitor_->OnDecryptedPacket(alternative_decrypter_level_); *decrypted_level = decrypter_level_; if (alternative_decrypter_latch_) { if (!EncryptionLevelIsValid(alternative_decrypter_level_)) { QUIC_BUG << "Attempted to latch alternate decrypter with bad " "alternative_decrypter_level_"; return false; } // Switch to the alternative decrypter and latch so that we cannot // switch back. decrypter_level_ = alternative_decrypter_level_; alternative_decrypter_level_ = NUM_ENCRYPTION_LEVELS; } else { // Switch the alternative decrypter so that we use it first next time. EncryptionLevel level = alternative_decrypter_level_; alternative_decrypter_level_ = decrypter_level_; decrypter_level_ = level; } } } if (!success) { QUIC_DVLOG(1) << ENDPOINT << "DecryptPacket failed for: " << header; return false; } return true; } size_t QuicFramer::GetIetfAckFrameSize(const QuicAckFrame& frame) { // Type byte, largest_acked, and delay_time are straight-forward. size_t ack_frame_size = kQuicFrameTypeSize; QuicPacketNumber largest_acked = LargestAcked(frame); ack_frame_size += QuicDataWriter::GetVarInt62Len(largest_acked.ToUint64()); uint64_t ack_delay_time_us; ack_delay_time_us = frame.ack_delay_time.ToMicroseconds(); ack_delay_time_us = ack_delay_time_us >> local_ack_delay_exponent_; ack_frame_size += QuicDataWriter::GetVarInt62Len(ack_delay_time_us); if (frame.packets.Empty() || frame.packets.Max() != largest_acked) { QUIC_BUG << "Malformed ack frame"; // ACK frame serialization will fail and connection will be closed. return ack_frame_size; } // Ack block count. ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.packets.NumIntervals() - 1); // First Ack range. auto iter = frame.packets.rbegin(); ack_frame_size += QuicDataWriter::GetVarInt62Len(iter->Length() - 1); QuicPacketNumber previous_smallest = iter->min(); ++iter; // Ack blocks. for (; iter != frame.packets.rend(); ++iter) { const uint64_t gap = previous_smallest - iter->max() - 1; const uint64_t ack_range = iter->Length() - 1; ack_frame_size += (QuicDataWriter::GetVarInt62Len(gap) + QuicDataWriter::GetVarInt62Len(ack_range)); previous_smallest = iter->min(); } // ECN counts. if (frame.ecn_counters_populated && (frame.ect_0_count || frame.ect_1_count || frame.ecn_ce_count)) { ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ect_0_count); ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ect_1_count); ack_frame_size += QuicDataWriter::GetVarInt62Len(frame.ecn_ce_count); } return ack_frame_size; } size_t QuicFramer::GetAckFrameSize( const QuicAckFrame& ack, QuicPacketNumberLength /*packet_number_length*/) { DCHECK(!ack.packets.Empty()); size_t ack_size = 0; if (VersionHasIetfQuicFrames(version_.transport_version)) { return GetIetfAckFrameSize(ack); } AckFrameInfo ack_info = GetAckFrameInfo(ack); QuicPacketNumberLength ack_block_length = GetMinPacketNumberLength(QuicPacketNumber(ack_info.max_block_length)); ack_size = GetMinAckFrameSize(version_.transport_version, ack, local_ack_delay_exponent_); // First ack block length. ack_size += ack_block_length; if (ack_info.num_ack_blocks != 0) { ack_size += kNumberOfAckBlocksSize; ack_size += std::min(ack_info.num_ack_blocks, kMaxAckBlocks) * (ack_block_length + PACKET_1BYTE_PACKET_NUMBER); } // Include timestamps. if (process_timestamps_) { ack_size += GetAckFrameTimeStampSize(ack); } return ack_size; } size_t QuicFramer::GetAckFrameTimeStampSize(const QuicAckFrame& ack) { if (ack.received_packet_times.empty()) { return 0; } return kQuicNumTimestampsLength + kQuicFirstTimestampLength + (kQuicTimestampLength + kQuicTimestampPacketNumberGapLength) * (ack.received_packet_times.size() - 1); } size_t QuicFramer::ComputeFrameLength( const QuicFrame& frame, bool last_frame_in_packet, QuicPacketNumberLength packet_number_length) { switch (frame.type) { case STREAM_FRAME: return GetMinStreamFrameSize( version_.transport_version, frame.stream_frame.stream_id, frame.stream_frame.offset, last_frame_in_packet, frame.stream_frame.data_length) + frame.stream_frame.data_length; case CRYPTO_FRAME: return GetMinCryptoFrameSize(frame.crypto_frame->offset, frame.crypto_frame->data_length) + frame.crypto_frame->data_length; case ACK_FRAME: { return GetAckFrameSize(*frame.ack_frame, packet_number_length); } case STOP_WAITING_FRAME: return GetStopWaitingFrameSize(packet_number_length); case MTU_DISCOVERY_FRAME: // MTU discovery frames are serialized as ping frames. return kQuicFrameTypeSize; case MESSAGE_FRAME: return GetMessageFrameSize(version_.transport_version, last_frame_in_packet, frame.message_frame->message_length); case PADDING_FRAME: DCHECK(false); return 0; default: return GetRetransmittableControlFrameSize(version_.transport_version, frame); } } bool QuicFramer::AppendTypeByte(const QuicFrame& frame, bool last_frame_in_packet, QuicDataWriter* writer) { if (VersionHasIetfQuicFrames(version_.transport_version)) { return AppendIetfFrameType(frame, last_frame_in_packet, writer); } uint8_t type_byte = 0; switch (frame.type) { case STREAM_FRAME: type_byte = GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet); break; case ACK_FRAME: return true; case MTU_DISCOVERY_FRAME: type_byte = static_cast<uint8_t>(PING_FRAME); break; case NEW_CONNECTION_ID_FRAME: set_detailed_error( "Attempt to append NEW_CONNECTION_ID frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case RETIRE_CONNECTION_ID_FRAME: set_detailed_error( "Attempt to append RETIRE_CONNECTION_ID frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case NEW_TOKEN_FRAME: set_detailed_error( "Attempt to append NEW_TOKEN frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case MAX_STREAMS_FRAME: set_detailed_error( "Attempt to append MAX_STREAMS frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case STREAMS_BLOCKED_FRAME: set_detailed_error( "Attempt to append STREAMS_BLOCKED frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case PATH_RESPONSE_FRAME: set_detailed_error( "Attempt to append PATH_RESPONSE frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case PATH_CHALLENGE_FRAME: set_detailed_error( "Attempt to append PATH_CHALLENGE frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case STOP_SENDING_FRAME: set_detailed_error( "Attempt to append STOP_SENDING frame and not in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case MESSAGE_FRAME: return true; default: type_byte = static_cast<uint8_t>(frame.type); break; } return writer->WriteUInt8(type_byte); } bool QuicFramer::AppendIetfFrameType(const QuicFrame& frame, bool last_frame_in_packet, QuicDataWriter* writer) { uint8_t type_byte = 0; switch (frame.type) { case PADDING_FRAME: type_byte = IETF_PADDING; break; case RST_STREAM_FRAME: type_byte = IETF_RST_STREAM; break; case CONNECTION_CLOSE_FRAME: switch (frame.connection_close_frame->close_type) { case IETF_QUIC_APPLICATION_CONNECTION_CLOSE: type_byte = IETF_APPLICATION_CLOSE; break; case IETF_QUIC_TRANSPORT_CONNECTION_CLOSE: type_byte = IETF_CONNECTION_CLOSE; break; default: set_detailed_error(quiche::QuicheStrCat( "Invalid QuicConnectionCloseFrame type: ", static_cast<int>(frame.connection_close_frame->close_type))); return RaiseError(QUIC_INTERNAL_ERROR); } break; case GOAWAY_FRAME: set_detailed_error( "Attempt to create non-IETF QUIC GOAWAY frame in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case WINDOW_UPDATE_FRAME: // Depending on whether there is a stream ID or not, will be either a // MAX_STREAM_DATA frame or a MAX_DATA frame. if (frame.window_update_frame->stream_id == QuicUtils::GetInvalidStreamId(transport_version())) { type_byte = IETF_MAX_DATA; } else { type_byte = IETF_MAX_STREAM_DATA; } break; case BLOCKED_FRAME: if (frame.blocked_frame->stream_id == QuicUtils::GetInvalidStreamId(transport_version())) { type_byte = IETF_DATA_BLOCKED; } else { type_byte = IETF_STREAM_DATA_BLOCKED; } break; case STOP_WAITING_FRAME: set_detailed_error( "Attempt to append type byte of STOP WAITING frame in IETF QUIC."); return RaiseError(QUIC_INTERNAL_ERROR); case PING_FRAME: type_byte = IETF_PING; break; case STREAM_FRAME: type_byte = GetStreamFrameTypeByte(frame.stream_frame, last_frame_in_packet); break; case ACK_FRAME: // Do nothing here, AppendIetfAckFrameAndTypeByte() will put the type byte // in the buffer. return true; case MTU_DISCOVERY_FRAME: // The path MTU discovery frame is encoded as a PING frame on the wire. type_byte = IETF_PING; break; case NEW_CONNECTION_ID_FRAME: type_byte = IETF_NEW_CONNECTION_ID; break; case RETIRE_CONNECTION_ID_FRAME: type_byte = IETF_RETIRE_CONNECTION_ID; break; case NEW_TOKEN_FRAME: type_byte = IETF_NEW_TOKEN; break; case MAX_STREAMS_FRAME: if (frame.max_streams_frame.unidirectional) { type_byte = IETF_MAX_STREAMS_UNIDIRECTIONAL; } else { type_byte = IETF_MAX_STREAMS_BIDIRECTIONAL; } break; case STREAMS_BLOCKED_FRAME: if (frame.streams_blocked_frame.unidirectional) { type_byte = IETF_STREAMS_BLOCKED_UNIDIRECTIONAL; } else { type_byte = IETF_STREAMS_BLOCKED_BIDIRECTIONAL; } break; case PATH_RESPONSE_FRAME: type_byte = IETF_PATH_RESPONSE; break; case PATH_CHALLENGE_FRAME: type_byte = IETF_PATH_CHALLENGE; break; case STOP_SENDING_FRAME: type_byte = IETF_STOP_SENDING; break; case MESSAGE_FRAME: return true; case CRYPTO_FRAME: type_byte = IETF_CRYPTO; break; case HANDSHAKE_DONE_FRAME: type_byte = IETF_HANDSHAKE_DONE; break; case ACK_FREQUENCY_FRAME: type_byte = IETF_ACK_FREQUENCY; break; default: QUIC_BUG << "Attempt to generate a frame type for an unsupported value: " << frame.type; return false; } return writer->WriteVarInt62(type_byte); } // static bool QuicFramer::AppendPacketNumber(QuicPacketNumberLength packet_number_length, QuicPacketNumber packet_number, QuicDataWriter* writer) { DCHECK(packet_number.IsInitialized()); if (!IsValidPacketNumberLength(packet_number_length)) { QUIC_BUG << "Invalid packet_number_length: " << packet_number_length; return false; } return writer->WriteBytesToUInt64(packet_number_length, packet_number.ToUint64()); } // static bool QuicFramer::AppendStreamId(size_t stream_id_length, QuicStreamId stream_id, QuicDataWriter* writer) { if (stream_id_length == 0 || stream_id_length > 4) { QUIC_BUG << "Invalid stream_id_length: " << stream_id_length; return false; } return writer->WriteBytesToUInt64(stream_id_length, stream_id); } // static bool QuicFramer::AppendStreamOffset(size_t offset_length, QuicStreamOffset offset, QuicDataWriter* writer) { if (offset_length == 1 || offset_length > 8) { QUIC_BUG << "Invalid stream_offset_length: " << offset_length; return false; } return writer->WriteBytesToUInt64(offset_length, offset); } // static bool QuicFramer::AppendAckBlock(uint8_t gap, QuicPacketNumberLength length_length, uint64_t length, QuicDataWriter* writer) { if (length == 0) { if (!IsValidPacketNumberLength(length_length)) { QUIC_BUG << "Invalid packet_number_length: " << length_length; return false; } return writer->WriteUInt8(gap) && writer->WriteBytesToUInt64(length_length, length); } return writer->WriteUInt8(gap) && AppendPacketNumber(length_length, QuicPacketNumber(length), writer); } bool QuicFramer::AppendStreamFrame(const QuicStreamFrame& frame, bool no_stream_frame_length, QuicDataWriter* writer) { if (VersionHasIetfQuicFrames(version_.transport_version)) { return AppendIetfStreamFrame(frame, no_stream_frame_length, writer); } if (!AppendStreamId(GetStreamIdSize(frame.stream_id), frame.stream_id, writer)) { QUIC_BUG << "Writing stream id size failed."; return false; } if (!AppendStreamOffset(GetStreamOffsetSize(frame.offset), frame.offset, writer)) { QUIC_BUG << "Writing offset size failed."; return false; } if (!no_stream_frame_length) { static_assert( std::numeric_limits<decltype(frame.data_length)>::max() <= std::numeric_limits<uint16_t>::max(), "If frame.data_length can hold more than a uint16_t than we need to " "check that frame.data_length <= std::numeric_limits<uint16_t>::max()"); if (!writer->WriteUInt16(static_cast<uint16_t>(frame.data_length))) { QUIC_BUG << "Writing stream frame length failed"; return false; } } if (data_producer_ != nullptr) { DCHECK_EQ(nullptr, frame.data_buffer); if (frame.data_length == 0) { return true; } if (data_producer_->WriteStreamData(frame.stream_id, frame.offset, frame.data_length, writer) != WRITE_SUCCESS) { QUIC_BUG << "Writing frame data failed."; return false; } return true; } if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) { QUIC_BUG << "Writing frame data failed."; return false; } return true; } bool QuicFramer::AppendNewTokenFrame(const QuicNewTokenFrame& frame, QuicDataWriter* writer) { if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.token.length()))) { set_detailed_error("Writing token length failed."); return false; } if (!writer->WriteBytes(frame.token.data(), frame.token.length())) { set_detailed_error("Writing token buffer failed."); return false; } return true; } bool QuicFramer::ProcessNewTokenFrame(QuicDataReader* reader, QuicNewTokenFrame* frame) { uint64_t length; if (!reader->ReadVarInt62(&length)) { set_detailed_error("Unable to read new token length."); return false; } if (length > kMaxNewTokenTokenLength) { set_detailed_error("Token length larger than maximum."); return false; } // TODO(ianswett): Don't use quiche::QuicheStringPiece as an intermediary. quiche::QuicheStringPiece data; if (!reader->ReadStringPiece(&data, length)) { set_detailed_error("Unable to read new token data."); return false; } frame->token = std::string(data); return true; } // Add a new ietf-format stream frame. // Bits controlling whether there is a frame-length and frame-offset // are in the QuicStreamFrame. bool QuicFramer::AppendIetfStreamFrame(const QuicStreamFrame& frame, bool last_frame_in_packet, QuicDataWriter* writer) { if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) { set_detailed_error("Writing stream id failed."); return false; } if (frame.offset != 0) { if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) { set_detailed_error("Writing data offset failed."); return false; } } if (!last_frame_in_packet) { if (!writer->WriteVarInt62(frame.data_length)) { set_detailed_error("Writing data length failed."); return false; } } if (frame.data_length == 0) { return true; } if (data_producer_ == nullptr) { if (!writer->WriteBytes(frame.data_buffer, frame.data_length)) { set_detailed_error("Writing frame data failed."); return false; } } else { DCHECK_EQ(nullptr, frame.data_buffer); if (data_producer_->WriteStreamData(frame.stream_id, frame.offset, frame.data_length, writer) != WRITE_SUCCESS) { set_detailed_error("Writing frame data failed."); return false; } } return true; } bool QuicFramer::AppendCryptoFrame(const QuicCryptoFrame& frame, QuicDataWriter* writer) { if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.offset))) { set_detailed_error("Writing data offset failed."); return false; } if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.data_length))) { set_detailed_error("Writing data length failed."); return false; } if (data_producer_ == nullptr) { if (frame.data_buffer == nullptr || !writer->WriteBytes(frame.data_buffer, frame.data_length)) { set_detailed_error("Writing frame data failed."); return false; } } else { DCHECK_EQ(nullptr, frame.data_buffer); if (!data_producer_->WriteCryptoData(frame.level, frame.offset, frame.data_length, writer)) { return false; } } return true; } bool QuicFramer::AppendAckFrequencyFrame(const QuicAckFrequencyFrame& frame, QuicDataWriter* writer) { if (!writer->WriteVarInt62(frame.sequence_number)) { set_detailed_error("Writing sequence number failed."); return false; } if (!writer->WriteVarInt62(frame.packet_tolerance)) { set_detailed_error("Writing packet tolerance failed."); return false; } if (!writer->WriteVarInt62( static_cast<uint64_t>(frame.max_ack_delay.ToMicroseconds()))) { set_detailed_error("Writing max_ack_delay_us failed."); return false; } if (!writer->WriteUInt8(static_cast<uint8_t>(frame.ignore_order))) { set_detailed_error("Writing ignore_order failed."); return false; } return true; } void QuicFramer::set_version(const ParsedQuicVersion version) { DCHECK(IsSupportedVersion(version)) << ParsedQuicVersionToString(version); version_ = version; } bool QuicFramer::AppendAckFrameAndTypeByte(const QuicAckFrame& frame, QuicDataWriter* writer) { if (VersionHasIetfQuicFrames(transport_version())) { return AppendIetfAckFrameAndTypeByte(frame, writer); } const AckFrameInfo new_ack_info = GetAckFrameInfo(frame); QuicPacketNumber largest_acked = LargestAcked(frame); QuicPacketNumberLength largest_acked_length = GetMinPacketNumberLength(largest_acked); QuicPacketNumberLength ack_block_length = GetMinPacketNumberLength(QuicPacketNumber(new_ack_info.max_block_length)); // Calculate available bytes for timestamps and ack blocks. int32_t available_timestamp_and_ack_block_bytes = writer->capacity() - writer->length() - ack_block_length - GetMinAckFrameSize(version_.transport_version, frame, local_ack_delay_exponent_) - (new_ack_info.num_ack_blocks != 0 ? kNumberOfAckBlocksSize : 0); DCHECK_LE(0, available_timestamp_and_ack_block_bytes); uint8_t type_byte = 0; SetBit(&type_byte, new_ack_info.num_ack_blocks != 0, kQuicHasMultipleAckBlocksOffset); SetBits(&type_byte, GetPacketNumberFlags(largest_acked_length), kQuicSequenceNumberLengthNumBits, kLargestAckedOffset); SetBits(&type_byte, GetPacketNumberFlags(ack_block_length), kQuicSequenceNumberLengthNumBits, kActBlockLengthOffset); type_byte |= kQuicFrameTypeAckMask; if (!writer->WriteUInt8(type_byte)) { return false; } size_t max_num_ack_blocks = available_timestamp_and_ack_block_bytes / (ack_block_length + PACKET_1BYTE_PACKET_NUMBER); // Number of ack blocks. size_t num_ack_blocks = std::min(new_ack_info.num_ack_blocks, max_num_ack_blocks); if (num_ack_blocks > std::numeric_limits<uint8_t>::max()) { num_ack_blocks = std::numeric_limits<uint8_t>::max(); } // Largest acked. if (!AppendPacketNumber(largest_acked_length, largest_acked, writer)) { return false; } // Largest acked delta time. uint64_t ack_delay_time_us = kUFloat16MaxValue; if (!frame.ack_delay_time.IsInfinite()) { DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds()); ack_delay_time_us = frame.ack_delay_time.ToMicroseconds(); } if (!writer->WriteUFloat16(ack_delay_time_us)) { return false; } if (num_ack_blocks > 0) { if (!writer->WriteBytes(&num_ack_blocks, 1)) { return false; } } // First ack block length. if (!AppendPacketNumber(ack_block_length, QuicPacketNumber(new_ack_info.first_block_length), writer)) { return false; } // Ack blocks. if (num_ack_blocks > 0) { size_t num_ack_blocks_written = 0; // Append, in descending order from the largest ACKed packet, a series of // ACK blocks that represents the successfully acknoweldged packets. Each // appended gap/block length represents a descending delta from the previous // block. i.e.: // |--- length ---|--- gap ---|--- length ---|--- gap ---|--- largest ---| // For gaps larger than can be represented by a single encoded gap, a 0 // length gap of the maximum is used, i.e.: // |--- length ---|--- gap ---|- 0 -|--- gap ---|--- largest ---| auto itr = frame.packets.rbegin(); QuicPacketNumber previous_start = itr->min(); ++itr; for (; itr != frame.packets.rend() && num_ack_blocks_written < num_ack_blocks; previous_start = itr->min(), ++itr) { const auto& interval = *itr; const uint64_t total_gap = previous_start - interval.max(); const size_t num_encoded_gaps = (total_gap + std::numeric_limits<uint8_t>::max() - 1) / std::numeric_limits<uint8_t>::max(); // Append empty ACK blocks because the gap is longer than a single gap. for (size_t i = 1; i < num_encoded_gaps && num_ack_blocks_written < num_ack_blocks; ++i) { if (!AppendAckBlock(std::numeric_limits<uint8_t>::max(), ack_block_length, 0, writer)) { return false; } ++num_ack_blocks_written; } if (num_ack_blocks_written >= num_ack_blocks) { if (QUIC_PREDICT_FALSE(num_ack_blocks_written != num_ack_blocks)) { QUIC_BUG << "Wrote " << num_ack_blocks_written << ", expected to write " << num_ack_blocks; } break; } const uint8_t last_gap = total_gap - (num_encoded_gaps - 1) * std::numeric_limits<uint8_t>::max(); // Append the final ACK block with a non-empty size. if (!AppendAckBlock(last_gap, ack_block_length, interval.Length(), writer)) { return false; } ++num_ack_blocks_written; } DCHECK_EQ(num_ack_blocks, num_ack_blocks_written); } // Timestamps. // If we don't process timestamps or if we don't have enough available space // to append all the timestamps, don't append any of them. if (process_timestamps_ && writer->capacity() - writer->length() >= GetAckFrameTimeStampSize(frame)) { if (!AppendTimestampsToAckFrame(frame, writer)) { return false; } } else { uint8_t num_received_packets = 0; if (!writer->WriteBytes(&num_received_packets, 1)) { return false; } } return true; } bool QuicFramer::AppendTimestampsToAckFrame(const QuicAckFrame& frame, QuicDataWriter* writer) { DCHECK_GE(std::numeric_limits<uint8_t>::max(), frame.received_packet_times.size()); // num_received_packets is only 1 byte. if (frame.received_packet_times.size() > std::numeric_limits<uint8_t>::max()) { return false; } uint8_t num_received_packets = frame.received_packet_times.size(); if (!writer->WriteBytes(&num_received_packets, 1)) { return false; } if (num_received_packets == 0) { return true; } auto it = frame.received_packet_times.begin(); QuicPacketNumber packet_number = it->first; uint64_t delta_from_largest_observed = LargestAcked(frame) - packet_number; DCHECK_GE(std::numeric_limits<uint8_t>::max(), delta_from_largest_observed); if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) { return false; } if (!writer->WriteUInt8(delta_from_largest_observed)) { return false; } // Use the lowest 4 bytes of the time delta from the creation_time_. const uint64_t time_epoch_delta_us = UINT64_C(1) << 32; uint32_t time_delta_us = static_cast<uint32_t>((it->second - creation_time_).ToMicroseconds() & (time_epoch_delta_us - 1)); if (!writer->WriteUInt32(time_delta_us)) { return false; } QuicTime prev_time = it->second; for (++it; it != frame.received_packet_times.end(); ++it) { packet_number = it->first; delta_from_largest_observed = LargestAcked(frame) - packet_number; if (delta_from_largest_observed > std::numeric_limits<uint8_t>::max()) { return false; } if (!writer->WriteUInt8(delta_from_largest_observed)) { return false; } uint64_t frame_time_delta_us = (it->second - prev_time).ToMicroseconds(); prev_time = it->second; if (!writer->WriteUFloat16(frame_time_delta_us)) { return false; } } return true; } bool QuicFramer::AppendStopWaitingFrame(const QuicPacketHeader& header, const QuicStopWaitingFrame& frame, QuicDataWriter* writer) { DCHECK(!VersionHasIetfInvariantHeader(version_.transport_version)); DCHECK(frame.least_unacked.IsInitialized()); DCHECK_GE(header.packet_number, frame.least_unacked); const uint64_t least_unacked_delta = header.packet_number - frame.least_unacked; const uint64_t length_shift = header.packet_number_length * 8; if (least_unacked_delta >> length_shift > 0) { QUIC_BUG << "packet_number_length " << header.packet_number_length << " is too small for least_unacked_delta: " << least_unacked_delta << " packet_number:" << header.packet_number << " least_unacked:" << frame.least_unacked << " version:" << version_.transport_version; return false; } if (least_unacked_delta == 0) { return writer->WriteBytesToUInt64(header.packet_number_length, least_unacked_delta); } if (!AppendPacketNumber(header.packet_number_length, QuicPacketNumber(least_unacked_delta), writer)) { QUIC_BUG << " seq failed: " << header.packet_number_length; return false; } return true; } bool QuicFramer::AppendIetfAckFrameAndTypeByte(const QuicAckFrame& frame, QuicDataWriter* writer) { uint8_t type = IETF_ACK; uint64_t ecn_size = 0; if (frame.ecn_counters_populated && (frame.ect_0_count || frame.ect_1_count || frame.ecn_ce_count)) { // Change frame type to ACK_ECN if any ECN count is available. type = IETF_ACK_ECN; ecn_size = (QuicDataWriter::GetVarInt62Len(frame.ect_0_count) + QuicDataWriter::GetVarInt62Len(frame.ect_1_count) + QuicDataWriter::GetVarInt62Len(frame.ecn_ce_count)); } if (!writer->WriteVarInt62(type)) { set_detailed_error("No room for frame-type"); return false; } QuicPacketNumber largest_acked = LargestAcked(frame); if (!writer->WriteVarInt62(largest_acked.ToUint64())) { set_detailed_error("No room for largest-acked in ack frame"); return false; } uint64_t ack_delay_time_us = kVarInt62MaxValue; if (!frame.ack_delay_time.IsInfinite()) { DCHECK_LE(0u, frame.ack_delay_time.ToMicroseconds()); ack_delay_time_us = frame.ack_delay_time.ToMicroseconds(); ack_delay_time_us = ack_delay_time_us >> local_ack_delay_exponent_; } if (!writer->WriteVarInt62(ack_delay_time_us)) { set_detailed_error("No room for ack-delay in ack frame"); return false; } if (frame.packets.Empty() || frame.packets.Max() != largest_acked) { QUIC_BUG << "Malformed ack frame: " << frame; set_detailed_error("Malformed ack frame"); return false; } // Latch ack_block_count for potential truncation. const uint64_t ack_block_count = frame.packets.NumIntervals() - 1; QuicDataWriter count_writer(QuicDataWriter::GetVarInt62Len(ack_block_count), writer->data() + writer->length()); if (!writer->WriteVarInt62(ack_block_count)) { set_detailed_error("No room for ack block count in ack frame"); return false; } auto iter = frame.packets.rbegin(); if (!writer->WriteVarInt62(iter->Length() - 1)) { set_detailed_error("No room for first ack block in ack frame"); return false; } QuicPacketNumber previous_smallest = iter->min(); ++iter; // Append remaining ACK blocks. uint64_t appended_ack_blocks = 0; for (; iter != frame.packets.rend(); ++iter) { const uint64_t gap = previous_smallest - iter->max() - 1; const uint64_t ack_range = iter->Length() - 1; if (writer->remaining() < ecn_size || static_cast<size_t>(writer->remaining() - ecn_size) < QuicDataWriter::GetVarInt62Len(gap) + QuicDataWriter::GetVarInt62Len(ack_range)) { // ACK range does not fit, truncate it. break; } const bool success = writer->WriteVarInt62(gap) && writer->WriteVarInt62(ack_range); DCHECK(success); previous_smallest = iter->min(); ++appended_ack_blocks; } if (appended_ack_blocks < ack_block_count) { // Truncation is needed, rewrite the ack block count. if (QuicDataWriter::GetVarInt62Len(appended_ack_blocks) != QuicDataWriter::GetVarInt62Len(ack_block_count) || !count_writer.WriteVarInt62(appended_ack_blocks)) { // This should never happen as ack_block_count is limited by // max_ack_ranges_. QUIC_BUG << "Ack frame truncation fails. ack_block_count: " << ack_block_count << ", appended count: " << appended_ack_blocks; set_detailed_error("ACK frame truncation fails"); return false; } QUIC_DLOG(INFO) << ENDPOINT << "ACK ranges get truncated from " << ack_block_count << " to " << appended_ack_blocks; } if (type == IETF_ACK_ECN) { // Encode the ECN counts. if (!writer->WriteVarInt62(frame.ect_0_count)) { set_detailed_error("No room for ect_0_count in ack frame"); return false; } if (!writer->WriteVarInt62(frame.ect_1_count)) { set_detailed_error("No room for ect_1_count in ack frame"); return false; } if (!writer->WriteVarInt62(frame.ecn_ce_count)) { set_detailed_error("No room for ecn_ce_count in ack frame"); return false; } } return true; } bool QuicFramer::AppendRstStreamFrame(const QuicRstStreamFrame& frame, QuicDataWriter* writer) { if (VersionHasIetfQuicFrames(version_.transport_version)) { return AppendIetfResetStreamFrame(frame, writer); } if (!writer->WriteUInt32(frame.stream_id)) { return false; } if (!writer->WriteUInt64(frame.byte_offset)) { return false; } uint32_t error_code = static_cast<uint32_t>(frame.error_code); if (!writer->WriteUInt32(error_code)) { return false; } return true; } bool QuicFramer::AppendConnectionCloseFrame( const QuicConnectionCloseFrame& frame, QuicDataWriter* writer) { if (VersionHasIetfQuicFrames(version_.transport_version)) { return AppendIetfConnectionCloseFrame(frame, writer); } uint32_t error_code = static_cast<uint32_t>(frame.wire_error_code); if (!writer->WriteUInt32(error_code)) { return false; } if (!writer->WriteStringPiece16(TruncateErrorString(frame.error_details))) { return false; } return true; } bool QuicFramer::AppendGoAwayFrame(const QuicGoAwayFrame& frame, QuicDataWriter* writer) { uint32_t error_code = static_cast<uint32_t>(frame.error_code); if (!writer->WriteUInt32(error_code)) { return false; } uint32_t stream_id = static_cast<uint32_t>(frame.last_good_stream_id); if (!writer->WriteUInt32(stream_id)) { return false; } if (!writer->WriteStringPiece16(TruncateErrorString(frame.reason_phrase))) { return false; } return true; } bool QuicFramer::AppendWindowUpdateFrame(const QuicWindowUpdateFrame& frame, QuicDataWriter* writer) { uint32_t stream_id = static_cast<uint32_t>(frame.stream_id); if (!writer->WriteUInt32(stream_id)) { return false; } if (!writer->WriteUInt64(frame.max_data)) { return false; } return true; } bool QuicFramer::AppendBlockedFrame(const QuicBlockedFrame& frame, QuicDataWriter* writer) { if (VersionHasIetfQuicFrames(version_.transport_version)) { if (frame.stream_id == QuicUtils::GetInvalidStreamId(transport_version())) { return AppendDataBlockedFrame(frame, writer); } return AppendStreamDataBlockedFrame(frame, writer); } uint32_t stream_id = static_cast<uint32_t>(frame.stream_id); if (!writer->WriteUInt32(stream_id)) { return false; } return true; } bool QuicFramer::AppendPaddingFrame(const QuicPaddingFrame& frame, QuicDataWriter* writer) { if (frame.num_padding_bytes == 0) { return false; } if (frame.num_padding_bytes < 0) { QUIC_BUG_IF(frame.num_padding_bytes != -1); writer->WritePadding(); return true; } // Please note, num_padding_bytes includes type byte which has been written. return writer->WritePaddingBytes(frame.num_padding_bytes - 1); } bool QuicFramer::AppendMessageFrameAndTypeByte(const QuicMessageFrame& frame, bool last_frame_in_packet, QuicDataWriter* writer) { uint8_t type_byte; if (VersionHasIetfQuicFrames(version_.transport_version)) { type_byte = last_frame_in_packet ? IETF_EXTENSION_MESSAGE_NO_LENGTH_V99 : IETF_EXTENSION_MESSAGE_V99; } else { type_byte = last_frame_in_packet ? IETF_EXTENSION_MESSAGE_NO_LENGTH : IETF_EXTENSION_MESSAGE; } if (!writer->WriteUInt8(type_byte)) { return false; } if (!last_frame_in_packet && !writer->WriteVarInt62(frame.message_length)) { return false; } for (const auto& slice : frame.message_data) { if (!writer->WriteBytes(slice.data(), slice.length())) { return false; } } return true; } bool QuicFramer::RaiseError(QuicErrorCode error) { QUIC_DLOG(INFO) << ENDPOINT << "Error: " << QuicErrorCodeToString(error) << " detail: " << detailed_error_; set_error(error); if (visitor_) { visitor_->OnError(this); } return false; } bool QuicFramer::IsVersionNegotiation( const QuicPacketHeader& header, bool packet_has_ietf_packet_header) const { if (!packet_has_ietf_packet_header && perspective_ == Perspective::IS_CLIENT) { return header.version_flag; } if (header.form == IETF_QUIC_SHORT_HEADER_PACKET) { return false; } return header.long_packet_type == VERSION_NEGOTIATION; } bool QuicFramer::AppendIetfConnectionCloseFrame( const QuicConnectionCloseFrame& frame, QuicDataWriter* writer) { if (frame.close_type != IETF_QUIC_TRANSPORT_CONNECTION_CLOSE && frame.close_type != IETF_QUIC_APPLICATION_CONNECTION_CLOSE) { QUIC_BUG << "Invalid close_type for writing IETF CONNECTION CLOSE."; set_detailed_error("Invalid close_type for writing IETF CONNECTION CLOSE."); return false; } if (!writer->WriteVarInt62(frame.wire_error_code)) { set_detailed_error("Can not write connection close frame error code"); return false; } if (frame.close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) { // Write the frame-type of the frame causing the error only // if it's a CONNECTION_CLOSE/Transport. if (!writer->WriteVarInt62(frame.transport_close_frame_type)) { set_detailed_error("Writing frame type failed."); return false; } } // There may be additional error information available in the extracted error // code. Encode the error information in the reason phrase and serialize the // result. std::string final_error_string = GenerateErrorString(frame.error_details, frame.quic_error_code); if (!writer->WriteStringPieceVarInt62( TruncateErrorString(final_error_string))) { set_detailed_error("Can not write connection close phrase"); return false; } return true; } bool QuicFramer::ProcessIetfConnectionCloseFrame( QuicDataReader* reader, QuicConnectionCloseType type, QuicConnectionCloseFrame* frame) { frame->close_type = type; uint64_t error_code; if (!reader->ReadVarInt62(&error_code)) { set_detailed_error("Unable to read connection close error code."); return false; } frame->wire_error_code = error_code; if (type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE) { // The frame-type of the frame causing the error is present only // if it's a CONNECTION_CLOSE/Transport. if (!reader->ReadVarInt62(&frame->transport_close_frame_type)) { set_detailed_error("Unable to read connection close frame type."); return false; } } uint64_t phrase_length; if (!reader->ReadVarInt62(&phrase_length)) { set_detailed_error("Unable to read connection close error details."); return false; } quiche::QuicheStringPiece phrase; if (!reader->ReadStringPiece(&phrase, static_cast<size_t>(phrase_length))) { set_detailed_error("Unable to read connection close error details."); return false; } frame->error_details = std::string(phrase); // The frame may have an extracted error code in it. Look for it and // extract it. If it's not present, MaybeExtract will return // QUIC_IETF_GQUIC_ERROR_MISSING. MaybeExtractQuicErrorCode(frame); return true; } // IETF Quic Path Challenge/Response frames. bool QuicFramer::ProcessPathChallengeFrame(QuicDataReader* reader, QuicPathChallengeFrame* frame) { if (!reader->ReadBytes(frame->data_buffer.data(), frame->data_buffer.size())) { set_detailed_error("Can not read path challenge data."); return false; } return true; } bool QuicFramer::ProcessPathResponseFrame(QuicDataReader* reader, QuicPathResponseFrame* frame) { if (!reader->ReadBytes(frame->data_buffer.data(), frame->data_buffer.size())) { set_detailed_error("Can not read path response data."); return false; } return true; } bool QuicFramer::AppendPathChallengeFrame(const QuicPathChallengeFrame& frame, QuicDataWriter* writer) { if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) { set_detailed_error("Writing Path Challenge data failed."); return false; } return true; } bool QuicFramer::AppendPathResponseFrame(const QuicPathResponseFrame& frame, QuicDataWriter* writer) { if (!writer->WriteBytes(frame.data_buffer.data(), frame.data_buffer.size())) { set_detailed_error("Writing Path Response data failed."); return false; } return true; } // Add a new ietf-format stream reset frame. // General format is // stream id // application error code // final offset bool QuicFramer::AppendIetfResetStreamFrame(const QuicRstStreamFrame& frame, QuicDataWriter* writer) { if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.stream_id))) { set_detailed_error("Writing reset-stream stream id failed."); return false; } if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.ietf_error_code))) { set_detailed_error("Writing reset-stream error code failed."); return false; } if (!writer->WriteVarInt62(static_cast<uint64_t>(frame.byte_offset))) { set_detailed_error("Writing reset-stream final-offset failed."); return false; } return true; } bool QuicFramer::ProcessIetfResetStreamFrame(QuicDataReader* reader, QuicRstStreamFrame* frame) { // Get Stream ID from frame. ReadVarIntStreamID returns false // if either A) there is a read error or B) the resulting value of // the Stream ID is larger than the maximum allowed value. if (!ReadUint32FromVarint62(reader, IETF_RST_STREAM, &frame->stream_id)) { return false; } if (!reader->ReadVarInt62(&frame->ietf_error_code)) { set_detailed_error("Unable to read rst stream error code."); return false; } frame->error_code = IetfResetStreamErrorCodeToRstStreamErrorCode(frame->ietf_error_code); if (!reader->ReadVarInt62(&frame->byte_offset)) { set_detailed_error("Unable to read rst stream sent byte offset."); return false; } return true; } bool QuicFramer::ProcessStopSendingFrame( QuicDataReader* reader, QuicStopSendingFrame* stop_sending_frame) { if (!ReadUint32FromVarint62(reader, IETF_STOP_SENDING, &stop_sending_frame->stream_id)) { return false; } if (!reader->ReadVarInt62(&stop_sending_frame->ietf_error_code)) { set_detailed_error("Unable to read stop sending application error code."); return false; } if (GetQuicReloadableFlag(quic_stop_sending_uses_ietf_error_code)) { QUIC_RELOADABLE_FLAG_COUNT_N(quic_stop_sending_uses_ietf_error_code, 2, 2); stop_sending_frame->error_code = IetfResetStreamErrorCodeToRstStreamErrorCode( stop_sending_frame->ietf_error_code); return true; } // TODO(fkastenholz): when error codes go to uint64_t, remove this. if (stop_sending_frame->ietf_error_code > 0xffff) { stop_sending_frame->error_code = static_cast<QuicRstStreamErrorCode>(0xffff); QUIC_DLOG(ERROR) << "Stop sending error code (" << stop_sending_frame->ietf_error_code << ") > 0xffff"; } else { stop_sending_frame->error_code = static_cast<QuicRstStreamErrorCode>( stop_sending_frame->ietf_error_code); } return true; } bool QuicFramer::AppendStopSendingFrame( const QuicStopSendingFrame& stop_sending_frame, QuicDataWriter* writer) { if (!writer->WriteVarInt62(stop_sending_frame.stream_id)) { set_detailed_error("Can not write stop sending stream id"); return false; } if (!writer->WriteVarInt62( static_cast<uint64_t>(stop_sending_frame.ietf_error_code))) { set_detailed_error("Can not write application error code"); return false; } return true; } // Append/process IETF-Format MAX_DATA Frame bool QuicFramer::AppendMaxDataFrame(const QuicWindowUpdateFrame& frame, QuicDataWriter* writer) { if (!writer->WriteVarInt62(frame.max_data)) { set_detailed_error("Can not write MAX_DATA byte-offset"); return false; } return true; } bool QuicFramer::ProcessMaxDataFrame(QuicDataReader* reader, QuicWindowUpdateFrame* frame) { frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version()); if (!reader->ReadVarInt62(&frame->max_data)) { set_detailed_error("Can not read MAX_DATA byte-offset"); return false; } return true; } // Append/process IETF-Format MAX_STREAM_DATA Frame bool QuicFramer::AppendMaxStreamDataFrame(const QuicWindowUpdateFrame& frame, QuicDataWriter* writer) { if (!writer->WriteVarInt62(frame.stream_id)) { set_detailed_error("Can not write MAX_STREAM_DATA stream id"); return false; } if (!writer->WriteVarInt62(frame.max_data)) { set_detailed_error("Can not write MAX_STREAM_DATA byte-offset"); return false; } return true; } bool QuicFramer::ProcessMaxStreamDataFrame(QuicDataReader* reader, QuicWindowUpdateFrame* frame) { if (!ReadUint32FromVarint62(reader, IETF_MAX_STREAM_DATA, &frame->stream_id)) { return false; } if (!reader->ReadVarInt62(&frame->max_data)) { set_detailed_error("Can not read MAX_STREAM_DATA byte-count"); return false; } return true; } bool QuicFramer::AppendMaxStreamsFrame(const QuicMaxStreamsFrame& frame, QuicDataWriter* writer) { if (!writer->WriteVarInt62(frame.stream_count)) { set_detailed_error("Can not write MAX_STREAMS stream count"); return false; } return true; } bool QuicFramer::ProcessMaxStreamsFrame(QuicDataReader* reader, QuicMaxStreamsFrame* frame, uint64_t frame_type) { if (!ReadUint32FromVarint62(reader, static_cast<QuicIetfFrameType>(frame_type), &frame->stream_count)) { return false; } frame->unidirectional = (frame_type == IETF_MAX_STREAMS_UNIDIRECTIONAL); return true; } bool QuicFramer::AppendDataBlockedFrame(const QuicBlockedFrame& frame, QuicDataWriter* writer) { if (!writer->WriteVarInt62(frame.offset)) { set_detailed_error("Can not write blocked offset."); return false; } return true; } bool QuicFramer::ProcessDataBlockedFrame(QuicDataReader* reader, QuicBlockedFrame* frame) { // Indicates that it is a BLOCKED frame (as opposed to STREAM_BLOCKED). frame->stream_id = QuicUtils::GetInvalidStreamId(transport_version()); if (!reader->ReadVarInt62(&frame->offset)) { set_detailed_error("Can not read blocked offset."); return false; } return true; } bool QuicFramer::AppendStreamDataBlockedFrame(const QuicBlockedFrame& frame, QuicDataWriter* writer) { if (!writer->WriteVarInt62(frame.stream_id)) { set_detailed_error("Can not write stream blocked stream id."); return false; } if (!writer->WriteVarInt62(frame.offset)) { set_detailed_error("Can not write stream blocked offset."); return false; } return true; } bool QuicFramer::ProcessStreamDataBlockedFrame(QuicDataReader* reader, QuicBlockedFrame* frame) { if (!ReadUint32FromVarint62(reader, IETF_STREAM_DATA_BLOCKED, &frame->stream_id)) { return false; } if (!reader->ReadVarInt62(&frame->offset)) { set_detailed_error("Can not read stream blocked offset."); return false; } return true; } bool QuicFramer::AppendStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame, QuicDataWriter* writer) { if (!writer->WriteVarInt62(frame.stream_count)) { set_detailed_error("Can not write STREAMS_BLOCKED stream count"); return false; } return true; } bool QuicFramer::ProcessStreamsBlockedFrame(QuicDataReader* reader, QuicStreamsBlockedFrame* frame, uint64_t frame_type) { if (!ReadUint32FromVarint62(reader, static_cast<QuicIetfFrameType>(frame_type), &frame->stream_count)) { return false; } if (frame->stream_count > QuicUtils::GetMaxStreamCount()) { // If stream count is such that the resulting stream ID would exceed our // implementation limit, generate an error. set_detailed_error( "STREAMS_BLOCKED stream count exceeds implementation limit."); return false; } frame->unidirectional = (frame_type == IETF_STREAMS_BLOCKED_UNIDIRECTIONAL); return true; } bool QuicFramer::AppendNewConnectionIdFrame( const QuicNewConnectionIdFrame& frame, QuicDataWriter* writer) { if (!writer->WriteVarInt62(frame.sequence_number)) { set_detailed_error("Can not write New Connection ID sequence number"); return false; } if (!writer->WriteVarInt62(frame.retire_prior_to)) { set_detailed_error("Can not write New Connection ID retire_prior_to"); return false; } if (!writer->WriteLengthPrefixedConnectionId(frame.connection_id)) { set_detailed_error("Can not write New Connection ID frame connection ID"); return false; } if (!writer->WriteBytes( static_cast<const void*>(&frame.stateless_reset_token), sizeof(frame.stateless_reset_token))) { set_detailed_error("Can not write New Connection ID Reset Token"); return false; } return true; } bool QuicFramer::ProcessNewConnectionIdFrame(QuicDataReader* reader, QuicNewConnectionIdFrame* frame) { if (!reader->ReadVarInt62(&frame->sequence_number)) { set_detailed_error( "Unable to read new connection ID frame sequence number."); return false; } if (!reader->ReadVarInt62(&frame->retire_prior_to)) { set_detailed_error( "Unable to read new connection ID frame retire_prior_to."); return false; } if (frame->retire_prior_to > frame->sequence_number) { set_detailed_error("Retire_prior_to > sequence_number."); return false; } if (!reader->ReadLengthPrefixedConnectionId(&frame->connection_id)) { set_detailed_error("Unable to read new connection ID frame connection id."); return false; } if (!QuicUtils::IsConnectionIdValidForVersion(frame->connection_id, transport_version())) { set_detailed_error("Invalid new connection ID length for version."); return false; } if (!reader->ReadBytes(&frame->stateless_reset_token, sizeof(frame->stateless_reset_token))) { set_detailed_error("Can not read new connection ID frame reset token."); return false; } return true; } bool QuicFramer::AppendRetireConnectionIdFrame( const QuicRetireConnectionIdFrame& frame, QuicDataWriter* writer) { if (!writer->WriteVarInt62(frame.sequence_number)) { set_detailed_error("Can not write Retire Connection ID sequence number"); return false; } return true; } bool QuicFramer::ProcessRetireConnectionIdFrame( QuicDataReader* reader, QuicRetireConnectionIdFrame* frame) { if (!reader->ReadVarInt62(&frame->sequence_number)) { set_detailed_error( "Unable to read retire connection ID frame sequence number."); return false; } return true; } bool QuicFramer::ReadUint32FromVarint62(QuicDataReader* reader, QuicIetfFrameType type, QuicStreamId* id) { uint64_t temp_uint64; if (!reader->ReadVarInt62(&temp_uint64)) { set_detailed_error("Unable to read " + QuicIetfFrameTypeString(type) + " frame stream id/count."); return false; } if (temp_uint64 > kMaxQuicStreamId) { set_detailed_error("Stream id/count of " + QuicIetfFrameTypeString(type) + "frame is too large."); return false; } *id = static_cast<uint32_t>(temp_uint64); return true; } uint8_t QuicFramer::GetStreamFrameTypeByte(const QuicStreamFrame& frame, bool last_frame_in_packet) const { if (VersionHasIetfQuicFrames(version_.transport_version)) { return GetIetfStreamFrameTypeByte(frame, last_frame_in_packet); } uint8_t type_byte = 0; // Fin bit. type_byte |= frame.fin ? kQuicStreamFinMask : 0; // Data Length bit. type_byte <<= kQuicStreamDataLengthShift; type_byte |= last_frame_in_packet ? 0 : kQuicStreamDataLengthMask; // Offset 3 bits. type_byte <<= kQuicStreamShift; const size_t offset_len = GetStreamOffsetSize(frame.offset); if (offset_len > 0) { type_byte |= offset_len - 1; } // stream id 2 bits. type_byte <<= kQuicStreamIdShift; type_byte |= GetStreamIdSize(frame.stream_id) - 1; type_byte |= kQuicFrameTypeStreamMask; // Set Stream Frame Type to 1. return type_byte; } uint8_t QuicFramer::GetIetfStreamFrameTypeByte( const QuicStreamFrame& frame, bool last_frame_in_packet) const { DCHECK(VersionHasIetfQuicFrames(version_.transport_version)); uint8_t type_byte = IETF_STREAM; if (!last_frame_in_packet) { type_byte |= IETF_STREAM_FRAME_LEN_BIT; } if (frame.offset != 0) { type_byte |= IETF_STREAM_FRAME_OFF_BIT; } if (frame.fin) { type_byte |= IETF_STREAM_FRAME_FIN_BIT; } return type_byte; } void QuicFramer::InferPacketHeaderTypeFromVersion() { // This function should only be called when server connection negotiates the // version. DCHECK_EQ(perspective_, Perspective::IS_SERVER); DCHECK(!infer_packet_header_type_from_version_); infer_packet_header_type_from_version_ = true; } void QuicFramer::EnableMultiplePacketNumberSpacesSupport() { if (supports_multiple_packet_number_spaces_) { QUIC_BUG << "Multiple packet number spaces has already been enabled"; return; } if (largest_packet_number_.IsInitialized()) { QUIC_BUG << "Try to enable multiple packet number spaces support after any " "packet has been received."; return; } supports_multiple_packet_number_spaces_ = true; } // static QuicErrorCode QuicFramer::ParsePublicHeaderDispatcher( const QuicEncryptedPacket& packet, uint8_t expected_destination_connection_id_length, PacketHeaderFormat* format, QuicLongHeaderType* long_packet_type, bool* version_present, bool* has_length_prefix, QuicVersionLabel* version_label, ParsedQuicVersion* parsed_version, QuicConnectionId* destination_connection_id, QuicConnectionId* source_connection_id, bool* retry_token_present, quiche::QuicheStringPiece* retry_token, std::string* detailed_error) { QuicDataReader reader(packet.data(), packet.length()); if (reader.IsDoneReading()) { *detailed_error = "Unable to read first byte."; return QUIC_INVALID_PACKET_HEADER; } const uint8_t first_byte = reader.PeekByte(); const bool ietf_format = QuicUtils::IsIetfPacketHeader(first_byte); uint8_t unused_first_byte; QuicVariableLengthIntegerLength retry_token_length_length; QuicErrorCode error_code = ParsePublicHeader( &reader, expected_destination_connection_id_length, ietf_format, &unused_first_byte, format, version_present, has_length_prefix, version_label, parsed_version, destination_connection_id, source_connection_id, long_packet_type, &retry_token_length_length, retry_token, detailed_error); *retry_token_present = retry_token_length_length != VARIABLE_LENGTH_INTEGER_LENGTH_0; return error_code; } // static QuicErrorCode QuicFramer::ParsePublicHeaderGoogleQuic( QuicDataReader* reader, uint8_t* first_byte, PacketHeaderFormat* format, bool* version_present, QuicVersionLabel* version_label, ParsedQuicVersion* parsed_version, QuicConnectionId* destination_connection_id, std::string* detailed_error) { *format = GOOGLE_QUIC_PACKET; *version_present = (*first_byte & PACKET_PUBLIC_FLAGS_VERSION) != 0; uint8_t destination_connection_id_length = 0; if ((*first_byte & PACKET_PUBLIC_FLAGS_8BYTE_CONNECTION_ID) != 0) { destination_connection_id_length = kQuicDefaultConnectionIdLength; } if (!reader->ReadConnectionId(destination_connection_id, destination_connection_id_length)) { *detailed_error = "Unable to read ConnectionId."; return QUIC_INVALID_PACKET_HEADER; } if (*version_present) { if (!ProcessVersionLabel(reader, version_label)) { *detailed_error = "Unable to read protocol version."; return QUIC_INVALID_PACKET_HEADER; } *parsed_version = ParseQuicVersionLabel(*version_label); } return QUIC_NO_ERROR; } namespace { const QuicVersionLabel kProxVersionLabel = 0x50524F58; // "PROX" inline bool PacketHasLengthPrefixedConnectionIds( const QuicDataReader& reader, ParsedQuicVersion parsed_version, QuicVersionLabel version_label, uint8_t first_byte) { if (parsed_version.IsKnown()) { return parsed_version.HasLengthPrefixedConnectionIds(); } // Received unsupported version, check known old unsupported versions. if (QuicVersionLabelUses4BitConnectionIdLength(version_label)) { return false; } // Received unknown version, check connection ID length byte. if (reader.IsDoneReading()) { // This check is required to safely peek the connection ID length byte. return true; } const uint8_t connection_id_length_byte = reader.PeekByte(); // Check for packets produced by older versions of // QuicFramer::WriteClientVersionNegotiationProbePacket if (first_byte == 0xc0 && (connection_id_length_byte & 0x0f) == 0 && connection_id_length_byte >= 0x50 && version_label == 0xcabadaba) { return false; } // Check for munged packets with version tag PROX. if ((connection_id_length_byte & 0x0f) == 0 && connection_id_length_byte >= 0x20 && version_label == kProxVersionLabel) { return false; } return true; } inline bool ParseLongHeaderConnectionIds( QuicDataReader* reader, bool has_length_prefix, QuicVersionLabel version_label, QuicConnectionId* destination_connection_id, QuicConnectionId* source_connection_id, std::string* detailed_error) { if (has_length_prefix) { if (!reader->ReadLengthPrefixedConnectionId(destination_connection_id)) { *detailed_error = "Unable to read destination connection ID."; return false; } if (!reader->ReadLengthPrefixedConnectionId(source_connection_id)) { if (version_label == kProxVersionLabel) { // The "PROX" version does not follow the length-prefixed invariants, // and can therefore attempt to read a payload byte and interpret it // as the source connection ID length, which could fail to parse. // In that scenario we keep the source connection ID empty but mark // parsing as successful. return true; } *detailed_error = "Unable to read source connection ID."; return false; } } else { // Parse connection ID lengths. uint8_t connection_id_lengths_byte; if (!reader->ReadUInt8(&connection_id_lengths_byte)) { *detailed_error = "Unable to read connection ID lengths."; return false; } uint8_t destination_connection_id_length = (connection_id_lengths_byte & kDestinationConnectionIdLengthMask) >> 4; if (destination_connection_id_length != 0) { destination_connection_id_length += kConnectionIdLengthAdjustment; } uint8_t source_connection_id_length = connection_id_lengths_byte & kSourceConnectionIdLengthMask; if (source_connection_id_length != 0) { source_connection_id_length += kConnectionIdLengthAdjustment; } // Read destination connection ID. if (!reader->ReadConnectionId(destination_connection_id, destination_connection_id_length)) { *detailed_error = "Unable to read destination connection ID."; return false; } // Read source connection ID. if (!reader->ReadConnectionId(source_connection_id, source_connection_id_length)) { *detailed_error = "Unable to read source connection ID."; return false; } } return true; } } // namespace // static QuicErrorCode QuicFramer::ParsePublicHeader( QuicDataReader* reader, uint8_t expected_destination_connection_id_length, bool ietf_format, uint8_t* first_byte, PacketHeaderFormat* format, bool* version_present, bool* has_length_prefix, QuicVersionLabel* version_label, ParsedQuicVersion* parsed_version, QuicConnectionId* destination_connection_id, QuicConnectionId* source_connection_id, QuicLongHeaderType* long_packet_type, QuicVariableLengthIntegerLength* retry_token_length_length, quiche::QuicheStringPiece* retry_token, std::string* detailed_error) { *version_present = false; *has_length_prefix = false; *version_label = 0; *parsed_version = UnsupportedQuicVersion(); *source_connection_id = EmptyQuicConnectionId(); *long_packet_type = INVALID_PACKET_TYPE; *retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0; *retry_token = quiche::QuicheStringPiece(); *detailed_error = ""; if (!reader->ReadUInt8(first_byte)) { *detailed_error = "Unable to read first byte."; return QUIC_INVALID_PACKET_HEADER; } if (!ietf_format) { return ParsePublicHeaderGoogleQuic( reader, first_byte, format, version_present, version_label, parsed_version, destination_connection_id, detailed_error); } *format = GetIetfPacketHeaderFormat(*first_byte); if (*format == IETF_QUIC_SHORT_HEADER_PACKET) { // Read destination connection ID using // expected_destination_connection_id_length to determine its length. if (!reader->ReadConnectionId(destination_connection_id, expected_destination_connection_id_length)) { *detailed_error = "Unable to read destination connection ID."; return QUIC_INVALID_PACKET_HEADER; } return QUIC_NO_ERROR; } DCHECK_EQ(IETF_QUIC_LONG_HEADER_PACKET, *format); *version_present = true; if (!ProcessVersionLabel(reader, version_label)) { *detailed_error = "Unable to read protocol version."; return QUIC_INVALID_PACKET_HEADER; } if (*version_label == 0) { *long_packet_type = VERSION_NEGOTIATION; } // Parse version. *parsed_version = ParseQuicVersionLabel(*version_label); // Figure out which IETF QUIC invariants this packet follows. *has_length_prefix = PacketHasLengthPrefixedConnectionIds( *reader, *parsed_version, *version_label, *first_byte); // Parse connection IDs. if (!ParseLongHeaderConnectionIds(reader, *has_length_prefix, *version_label, destination_connection_id, source_connection_id, detailed_error)) { return QUIC_INVALID_PACKET_HEADER; } if (!parsed_version->IsKnown()) { // Skip parsing of long packet type and retry token for unknown versions. return QUIC_NO_ERROR; } // Parse long packet type. if (!GetLongHeaderType(*first_byte, long_packet_type)) { *detailed_error = "Unable to parse long packet type."; return QUIC_INVALID_PACKET_HEADER; } if (!parsed_version->SupportsRetry() || *long_packet_type != INITIAL) { // Retry token is only present on initial packets for some versions. return QUIC_NO_ERROR; } *retry_token_length_length = reader->PeekVarInt62Length(); uint64_t retry_token_length; if (!reader->ReadVarInt62(&retry_token_length)) { *retry_token_length_length = VARIABLE_LENGTH_INTEGER_LENGTH_0; *detailed_error = "Unable to read retry token length."; return QUIC_INVALID_PACKET_HEADER; } if (!reader->ReadStringPiece(retry_token, retry_token_length)) { *detailed_error = "Unable to read retry token."; return QUIC_INVALID_PACKET_HEADER; } return QUIC_NO_ERROR; } // static bool QuicFramer::WriteClientVersionNegotiationProbePacket( char* packet_bytes, QuicByteCount packet_length, const char* destination_connection_id_bytes, uint8_t destination_connection_id_length) { if (packet_bytes == nullptr) { QUIC_BUG << "Invalid packet_bytes"; return false; } if (packet_length < kMinPacketSizeForVersionNegotiation || packet_length > 65535) { QUIC_BUG << "Invalid packet_length"; return false; } if (destination_connection_id_length > kQuicMaxConnectionId4BitLength || destination_connection_id_length < kQuicMinimumInitialConnectionIdLength) { QUIC_BUG << "Invalid connection_id_length"; return false; } const bool use_length_prefix = GetQuicFlag(FLAGS_quic_prober_uses_length_prefixed_connection_ids); const uint8_t last_version_byte = use_length_prefix ? 0xda : 0xba; // clang-format off const unsigned char packet_start_bytes[] = { // IETF long header with fixed bit set, type initial, all-0 encrypted bits. 0xc0, // Version, part of the IETF space reserved for negotiation. // This intentionally differs from QuicVersionReservedForNegotiation() // to allow differentiating them over the wire. 0xca, 0xba, 0xda, last_version_byte, }; // clang-format on static_assert(sizeof(packet_start_bytes) == 5, "bad packet_start_bytes size"); QuicDataWriter writer(packet_length, packet_bytes); if (!writer.WriteBytes(packet_start_bytes, sizeof(packet_start_bytes))) { QUIC_BUG << "Failed to write packet start"; return false; } QuicConnectionId destination_connection_id(destination_connection_id_bytes, destination_connection_id_length); if (!AppendIetfConnectionIds( /*version_flag=*/true, use_length_prefix, destination_connection_id, EmptyQuicConnectionId(), &writer)) { QUIC_BUG << "Failed to write connection IDs"; return false; } // Add 8 bytes of zeroes followed by 8 bytes of ones to ensure that this does // not parse with any known version. The zeroes make sure that packet numbers, // retry token lengths and payload lengths are parsed as zero, and if the // zeroes are treated as padding frames, 0xff is known to not parse as a // valid frame type. if (!writer.WriteUInt64(0) || !writer.WriteUInt64(std::numeric_limits<uint64_t>::max())) { QUIC_BUG << "Failed to write 18 bytes"; return false; } // Make sure the polite greeting below is padded to a 16-byte boundary to // make it easier to read in tcpdump. while (writer.length() % 16 != 0) { if (!writer.WriteUInt8(0)) { QUIC_BUG << "Failed to write padding byte"; return false; } } // Add a polite greeting in case a human sees this in tcpdump. static const char polite_greeting[] = "This packet only exists to trigger IETF QUIC version negotiation. " "Please respond with a Version Negotiation packet indicating what " "versions you support. Thank you and have a nice day."; if (!writer.WriteBytes(polite_greeting, sizeof(polite_greeting))) { QUIC_BUG << "Failed to write polite greeting"; return false; } // Fill the rest of the packet with zeroes. writer.WritePadding(); DCHECK_EQ(0u, writer.remaining()); return true; } // static bool QuicFramer::ParseServerVersionNegotiationProbeResponse( const char* packet_bytes, QuicByteCount packet_length, char* source_connection_id_bytes, uint8_t* source_connection_id_length_out, std::string* detailed_error) { if (detailed_error == nullptr) { QUIC_BUG << "Invalid error_details"; return false; } *detailed_error = ""; if (packet_bytes == nullptr) { *detailed_error = "Invalid packet_bytes"; return false; } if (packet_length < 6) { *detailed_error = "Invalid packet_length"; return false; } if (source_connection_id_bytes == nullptr) { *detailed_error = "Invalid source_connection_id_bytes"; return false; } if (source_connection_id_length_out == nullptr) { *detailed_error = "Invalid source_connection_id_length_out"; return false; } QuicDataReader reader(packet_bytes, packet_length); uint8_t type_byte = 0; if (!reader.ReadUInt8(&type_byte)) { *detailed_error = "Failed to read type byte"; return false; } if ((type_byte & 0x80) == 0) { *detailed_error = "Packet does not have long header"; return false; } uint32_t version = 0; if (!reader.ReadUInt32(&version)) { *detailed_error = "Failed to read version"; return false; } if (version != 0) { *detailed_error = "Packet is not a version negotiation packet"; return false; } const bool use_length_prefix = GetQuicFlag(FLAGS_quic_prober_uses_length_prefixed_connection_ids); QuicConnectionId destination_connection_id, source_connection_id; if (use_length_prefix) { if (!reader.ReadLengthPrefixedConnectionId(&destination_connection_id)) { *detailed_error = "Failed to read destination connection ID"; return false; } if (!reader.ReadLengthPrefixedConnectionId(&source_connection_id)) { *detailed_error = "Failed to read source connection ID"; return false; } } else { uint8_t expected_server_connection_id_length = 0, destination_connection_id_length = 0, source_connection_id_length = 0; if (!ProcessAndValidateIetfConnectionIdLength( &reader, UnsupportedQuicVersion(), Perspective::IS_CLIENT, /*should_update_expected_server_connection_id_length=*/true, &expected_server_connection_id_length, &destination_connection_id_length, &source_connection_id_length, detailed_error)) { return false; } if (!reader.ReadConnectionId(&destination_connection_id, destination_connection_id_length)) { *detailed_error = "Failed to read destination connection ID"; return false; } if (!reader.ReadConnectionId(&source_connection_id, source_connection_id_length)) { *detailed_error = "Failed to read source connection ID"; return false; } } if (destination_connection_id.length() != 0) { *detailed_error = "Received unexpected destination connection ID length"; return false; } memcpy(source_connection_id_bytes, source_connection_id.data(), source_connection_id.length()); *source_connection_id_length_out = source_connection_id.length(); return true; } // Look for and parse the error code from the "<quic_error_code>:" text that // may be present at the start of the CONNECTION_CLOSE error details string. // This text, inserted by the peer if it's using Google's QUIC implementation, // contains additional error information that narrows down the exact error. If // the string is not found, or is not properly formed, it returns // ErrorCode::QUIC_IETF_GQUIC_ERROR_MISSING void MaybeExtractQuicErrorCode(QuicConnectionCloseFrame* frame) { std::vector<quiche::QuicheStringPiece> ed = quiche::QuicheTextUtils::Split(frame->error_details, ':'); uint64_t extracted_error_code; if (ed.size() < 2 || !quiche::QuicheTextUtils::IsAllDigits(ed[0]) || !quiche::QuicheTextUtils::StringToUint64(ed[0], &extracted_error_code)) { if (frame->close_type == IETF_QUIC_TRANSPORT_CONNECTION_CLOSE && frame->wire_error_code == NO_IETF_QUIC_ERROR) { frame->quic_error_code = QUIC_NO_ERROR; } else { frame->quic_error_code = QUIC_IETF_GQUIC_ERROR_MISSING; } return; } // Return the error code (numeric) and the error details string without the // error code prefix. Note that Split returns everything up to, but not // including, the split character, so the length of ed[0] is just the number // of digits in the error number. In removing the prefix, 1 is added to the // length to account for the : quiche::QuicheStringPiece x = quiche::QuicheStringPiece(frame->error_details); x.remove_prefix(ed[0].length() + 1); frame->error_details = std::string(x); frame->quic_error_code = static_cast<QuicErrorCode>(extracted_error_code); } #undef ENDPOINT // undef for jumbo builds } // namespace quic
37.061657
80
0.67226
[ "vector" ]
4f83b8ee12bb80a7dbcbf67fc814e9c4d0d1c958
55,906
cpp
C++
drivers/wdm/audio/filters/swmidi/mmx.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
drivers/wdm/audio/filters/swmidi/mmx.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
drivers/wdm/audio/filters/swmidi/mmx.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// MMX.cpp // Copyright (c) Intel Corporation 1996 // Copyright (c) 1996-2000 Microsoft Corporation. All Rights Reserved. // MMX Mix engines for SWMIDI /* Most of the mix engines have been converted into assembler via .asm output from the 4.2 release compiler. I did this because the 5.0 backend turns off optimization when it encounters _asm statements, so it generates worse code. However, the original code is still intact within the ! _X86_ versions, and can be used to generate new assembler, should that be needed at a later date. */ /* Variable useage. Variable register pfSamplePos eax pfPitch ebx dwI ecx dwIncDelta edx (edx is sometimes a temporary register) dwPosition1 esi dwPostiion2 edi vfRvolume and vfLvolume mm0 vfRVolume, vfLVolume mm2 mm4 - mm7 are temporary mmx registers. */ // Notes about calculation. // Loop is unrolled once. // *1 shifting volumne to 15 bit values to get rid of shifts and simplify code. // This make the packed mulitply work better later since I keep the sound interpolated // wave value at 16 bit signed value. For a PMULHW, this results in 15 bit results // which is the same as the original code. // *2 linear interpolation can be done very quickly with MMX by re-arranging the // way that the interpolation is done. Here is code in C that shows the difference. // Original C code //lM1 = ((pcWave[dwPosition1 + 1] - pcWave[dwPosition1]) * dwFract1) >> 12; //lM2 = ((pcWave[dwPosition2 + 1] - pcWave[dwPosition2]) * dwFract2) >> 12; //lM1 += pcWave[dwPosition1]; //lM2 += pcWave[dwPosition2]; // Equivalent C Code that can be done with a pmadd //lM1 = (pcWave[dwPosition1 + 1] * dwFract1 + pcWave[dwPosition1]*(0x1000-dwFract1)) >> 12; //lM2 = (pcWave[dwPosition2 + 1] * dwFract2 + pcWave[dwPosition2]*(0x1000-dwFract2)) >> 12; #include "common.h" typedef unsigned __int64 QWORD; DWORD DigitalAudio::MixMono8X(short * pBuffer, DWORD dwLength,DWORD dwDeltaPeriod, VFRACT vfDeltaVolume, PFRACT pfDeltaPitch, PFRACT pfSampleLength, PFRACT pfLoopLength) { DWORD dwI; DWORD dwIncDelta = dwDeltaPeriod; char * pcWave = (char *)m_Source.m_pWave->m_pnWave; PFRACT pfSamplePos = m_pfLastSample; VFRACT vfVolume = m_vfLastLVolume; PFRACT pfPitch = m_pfLastPitch; PFRACT pfPFract = pfPitch << 8; VFRACT vfVFract = vfVolume << 8; // Keep high res version around. QWORD dwFractMASK = 0x000000000FFF0FFF; QWORD dwFractOne = 0x0000000010001000; QWORD wordmask = 0x0000FFFF0000FFFF; QWORD vfDeltaLandRVolume; _asm{ // vfLVFract and vfRVFract are in mm0 //VFRACT vfLVFract = vfLVolume1 << 8; // Keep high res version around. //VFRACT vfRVFract = vfRVolume1 << 8; movd mm0, vfVolume movd mm7, vfVolume // vfDeltaLVolume and vfDeltaRVolume are put in mm1 so that they can be stored in vfDeltaLandRVolume movd mm1, vfDeltaVolume movd mm6, vfDeltaVolume punpckldq mm1, mm6 // dwI = 0 mov ecx, 0 movq vfDeltaLandRVolume, mm1 movq mm1, dwFractOne movq mm4, dwFractMASK mov eax, pfSamplePos punpckldq mm0, mm7 mov ebx, pfPitch pslld mm0, 8 mov edx, dwIncDelta movq mm2, mm0 // vfLVolume and vfRVolume in mm2 // need to be set before first pass. // *1 I shift by 5 so that volume is a 15 bit value instead of a 12 bit value psrld mm2, 5 //for (dwI = 0; dwI < dwLength; ) //{ mainloop: cmp ecx, dwLength jae done cmp eax, pfSampleLength //if (pfSamplePos >= pfSampleLength) jb NotPastEndOfSample1 //{ cmp pfLoopLength, 0 //if (!pfLoopLength) je done // break; sub eax, pfLoopLength // else pfSamplePos -= pfLoopLength; NotPastEndOfSample1: //} mov esi, eax // dwPosition1 = pfSamplePos; add eax, ebx // pfSamplePos += pfPitch; sub edx, 2 // dwIncDelta-=2; jnz DontIncreaseValues1 //if (!dwIncDelta) { // Since edx was use for dwIncDelta and now its zero, we can use if for a temporary // for a bit. All code that TestLVol and TestRVol is doing is zeroing out the volume // if it goes below zero. paddd mm0, vfDeltaLandRVolume // vfVFract += vfDeltaVolume; // vfVFract += vfDeltaVolume; pxor mm5, mm5 // TestLVol = 0; TestRVol = 0; mov edx, pfPFract // Temp = pfPFract; pcmpgtd mm5, mm0 // if (TestLVol > vfLVFract) TestLVol = 0xffffffff; // if (TestRVol > vfRVFract) TestRVol = 0xffffffff; add edx, pfDeltaPitch // Temp += pfDeltaPitch; pandn mm5, mm0 // TestLVol = vfLVFract & (~TestLVol); // TestRVol = vfRVFract & (~TestRVol); mov pfPFract, edx // pfPFract = Temp; movq mm2, mm5 // vfLVolume = TestLVol; // vfRVolume = TestRVol; shr edx, 8 // Temp = Temp >> 8; psrld mm2, 5 // vfLVolume = vfLVolume >> 5; // vfRVolume = vfRVolume >> 5; mov ebx, edx // pfPitch = Temp; mov edx, dwDeltaPeriod //dwIncDelta = dwDeltaPeriod; //} DontIncreaseValues1: movd mm6, esi // dwFract1 = dwPosition1; movq mm5, mm1 // words in mm5 = 0, 0, 0x1000, 0x1000 shr esi, 12 // dwPosition1 = dwPosition1 >> 12; inc ecx //dwI++; // if (dwI < dwLength) break; cmp ecx, dwLength jae StoreOne //if (pfSamplePos >= pfSampleLength) //{ cmp eax, pfSampleLength jb NotPastEndOfSample2 // Original if in C was not negated //if (!pfLoopLength) cmp pfLoopLength, 0 //break; je StoreOne //else //pfSamplePos -= pfLoopLength; sub eax, pfLoopLength //} NotPastEndOfSample2: //shl esi, 1 // do not shift left since pcWave is array of chars mov edi, eax // dwPosition2 = pfSamplePos; add esi, pcWave // Put address of pcWave[dwPosition1] in esi movd mm7, eax // dwFract2 = pfSamplePos; shr edi, 12 // dwPosition2 = dwPosition2 >> 12; punpcklwd mm6, mm7 // combine dwFract Values. Words in mm6 after unpack are // 0, 0, dwFract2, dwFract1 pand mm6, mm4 // dwFract2 &= 0xfff; dwFract1 &= 0xfff; movzx esi, word ptr[esi] //lLM1 = pcWave[dwPosition1]; movd mm3, esi psubw mm5, mm6 // 0, 0, 0x1000 - dwFract2, 0x1000 - dwFract1 //shl edi, 1 //do not shift left since pcWave is array of chars punpcklwd mm5, mm6 // dwFract2, 0x1000 - dwFract2, dwFract1, 0x1000 - dwFract1 add edi, pcWave // Put address of pcWave[dwPosition2] in edi mov esi, ecx // Temp = dWI; shl esi, 1 // Temp = Temp << 1; movzx edi, word ptr[edi] //lLM2 = pcWave[dwPoisition2]; movd mm6, edi pxor mm7, mm7 // zero out mm7 to make 8 bit into 16 bit // low 4 bytes in mm3 punpcklwd mm3, mm6 // pcWave[dwPos2+1], pcWave[dwPos2], pcWave[dwPos1+1], pcWave[dwPos1] add esi, pBuffer // punpcklbw mm7, mm3 // low four bytes bytes in // pcWave[dwPos2+1], pcWave[dwPos2], pcWave[dwPos1+1], pcWave[dwPos1] pmaddwd mm7, mm5 // high dword = lM2 = //(pcWave[dwPosition2 + 1] * dwFract2 + pcWave[dwPosition2]*(0x1000-dwFract2)) // low dword = lM1 = //(pcWave[dwPosition1 + 1] * dwFract1 + pcWave[dwPosition1]*(0x1000-dwFract1)) movq mm3, mm2 // put left and right volume levels in mm3 add eax, ebx //pfSamplePos += pfPitch; packssdw mm3, mm2 // words in mm7 // vfVolume, vfVolume, vfVolume, vfVolume movd mm5, dword ptr[esi-2] // Load values from buffer inc ecx // dwI++; psrad mm7, 12 // shift back down to 16 bits. packssdw mm7, mm4 // only need one word in mono case. // low word are lm2 and lm1 // above multiplies and shifts are all done with this one pmul. Low two word are only // interest in mono case pmulhw mm3, mm7 // lLM1 *= vfVolume; // lLM2 *= vfVolume; paddsw mm5, mm3 // Add values to buffer with saturation movd dword ptr[esi-2], mm5 // Store values back into buffer. // } jmp mainloop // Need to write only one. //if (dwI < dwLength) //{ StoreOne: #if 1 // Linearly interpolate between points and store only one value. // combine dwFract Values. // Make mm7 zero for unpacking //shl esi, 1 // do not shift left since pcWave is array of chars add esi, pcWave // Put address of pcWave[dwPosition1] in esi pxor mm7, mm7 //lLM1 = pcWave[dwPosition1]; movzx esi, word ptr[esi] // Doing AND that was not done for dwFract1 and dwFract2 pand mm6, mm4 // words in MMX register after operation is complete. psubw mm5, mm6 // 0, 0, 0x1000 - 0, 0x1000 - dwFract1 punpcklwd mm5, mm6 // 0 , 0x1000 - 0, dwFract1, 0x1000 - dwFract1 // put values of pcWave into MMX registers. They are read into a regular register so // that the routine does not read past the end of the buffer otherwise, it could read // directly into the MMX registers. // words in MMX registers pxor mm7, mm7 // low four bytes movd mm4, esi // 0, 0, pcWave[dwPos1+1], pcWave[dwPos1] // 8 bytes after unpakc punpcklbw mm7, mm4 // 0, 0, 0, 0, pcWave[dwPos1+1], 0, pcWave[dwPos1], 0 // *2 pmadd efficent code. //lM2 = (pcWave[dwPosition2 + 1] * dwFract2 + pcWave[dwPosition2]*(0x1000-dwFract2)) >> 12; //lM1 = (pcWave[dwPosition1 + 1] * dwFract1 + pcWave[dwPosition1]*(0x1000-dwFract1)) >> 12; pmaddwd mm7, mm5// low dword = lM1 = //(pcWave[dwPosition1 + 1] * dwFract1 + pcWave[dwPosition1]*(0x1000-dwFract1)) psrad mm7, 12 // shift back down to 16 bits movq mm5, mm2 // move volume into mm5 /* // Set lLM to be same as lM lLM1 = lM1; lLM1 *= vfLVolume1; lLM1 >>= 5; // Signal bumps up to 15 bits. lM1 *= vfRVolume1; lM1 >>= 5; // Set lLM to be same as lM lLM2 = lM2; lLM2 *= vfLVolume2; lLM2 >>= 5; // Signal bumps up to 15 bits. lM2 *= vfRVolume2; lM2 >>= 5; */ // above multiplies and shifts are all done with this one pmul pmulhw mm5, mm7 // calculate buffer location. mov edi, ecx shl edi, 1 add edi, pBuffer movd edx, mm5 //pBuffer[dwI+1] += (short) lM1; add word ptr[edi-2], dx jno no_oflowr1 //pBuffer[dwI+1] = 0x7fff; mov word ptr[edi-2], 0x7fff js no_oflowr1 //pBuffer[dwI+1] = (short) 0x8000; mov word ptr[edi-2], 0x8000 no_oflowr1: //} #endif done: mov edx, this // get address of class object //m_vfLastLVolume = vfVolume; //m_vfLastRVolume = vfVolume; // need to shift volume back down to 12 bits before storing psrld mm2, 3 movd [edx]this.m_vfLastLVolume, mm2 movd [edx]this.m_vfLastRVolume, mm2 //m_pfLastPitch = pfPitch; mov [edx]this.m_pfLastPitch, ebx //m_pfLastSample = pfSamplePos; mov [edx]this.m_pfLastSample, eax // put value back into dwI to be returned. This could just be passed back in eax I think. mov dwI, ecx emms } // ASM block return (dwI); } DWORD DigitalAudio::Mix8X(short * pBuffer, DWORD dwLength, DWORD dwDeltaPeriod, VFRACT vfDeltaLVolume, VFRACT vfDeltaRVolume, PFRACT pfDeltaPitch, PFRACT pfSampleLength, PFRACT pfLoopLength) { DWORD dwI; //DWORD dwPosition1, dwPosition2; //long lM1, lLM1; //long lM2, lLM2; DWORD dwIncDelta = dwDeltaPeriod; //VFRACT dwFract1, dwFract2; char * pcWave = (char *) m_Source.m_pWave->m_pnWave; PFRACT pfSamplePos = m_pfLastSample; VFRACT vfLVolume = m_vfLastLVolume; VFRACT vfRVolume = m_vfLastRVolume; VFRACT vfLVolume2 = m_vfLastLVolume; VFRACT vfRVolume2 = m_vfLastRVolume; PFRACT pfPitch = m_pfLastPitch; PFRACT pfPFract = pfPitch << 8; dwLength <<= 1; QWORD dwFractMASK = 0x000000000FFF0FFF; QWORD dwFractOne = 0x0000000010001000; QWORD wordmask = 0x0000FFFF0000FFFF; QWORD vfDeltaLandRVolume; _asm{ // vfLVFract and vfRVFract are in mm0 //VFRACT vfLVFract = vfLVolume1 << 8; // Keep high res version around. //VFRACT vfRVFract = vfRVolume1 << 8; movd mm0, vfLVolume movd mm7, vfRVolume // vfDeltaLVolume and vfDeltaRVolume are put in mm1 so that they can be stored in vfDeltaLandRVolume movd mm1, vfDeltaLVolume movd mm6, vfDeltaRVolume punpckldq mm1, mm6 // dwI = 0 mov ecx, 0 movq vfDeltaLandRVolume, mm1 movq mm1, dwFractOne movq mm4, dwFractMASK mov eax, pfSamplePos punpckldq mm0, mm7 mov ebx, pfPitch pslld mm0, 8 mov edx, dwIncDelta movq mm2, mm0 // vfLVolume and vfRVolume in mm2 // need to be set before first pass. // *1 I shift by 5 so that volume is a 15 bit value instead of a 12 bit value psrld mm2, 5 //for (dwI = 0; dwI < dwLength; ) //{ mainloop: cmp ecx, dwLength jae done cmp eax, pfSampleLength //if (pfSamplePos >= pfSampleLength) jb NotPastEndOfSample1 //{ cmp pfLoopLength, 0 //if (!pfLoopLength) je done // break; sub eax, pfLoopLength // else pfSamplePos -= pfLoopLength; NotPastEndOfSample1: //} mov esi, eax // dwPosition1 = pfSamplePos; add eax, ebx // pfSamplePos += pfPitch; sub edx, 2 // dwIncDelta-=2; jnz DontIncreaseValues1 //if (!dwIncDelta) { // Since edx was use for dwIncDelta and now its zero, we can use if for a temporary // for a bit. All code that TestLVol and TestRVol is doing is zeroing out the volume // if it goes below zero. paddd mm0, vfDeltaLandRVolume // vfLVFract += vfDeltaLVolume; // vfRVFract += vfDeltaRVolume; pxor mm5, mm5 // TestLVol = 0; TestRVol = 0; mov edx, pfPFract // Temp = pfPFract; pcmpgtd mm5, mm0 // if (TestLVol > vfLVFract) TestLVol = 0xffffffff; // if (TestRVol > vfRVFract) TestRVol = 0xffffffff; add edx, pfDeltaPitch // Temp += pfDeltaPitch; pandn mm5, mm0 // TestLVol = vfLVFract & (~TestLVol); // TestRVol = vfRVFract & (~TestRVol); mov pfPFract, edx // pfPFract = Temp; movq mm2, mm5 // vfLVolume = TestLVol; // vfRVolume = TestRVol; shr edx, 8 // Temp = Temp >> 8; psrld mm2, 5 // vfLVolume = vfLVolume >> 5; // vfRVolume = vfRVolume >> 5; mov ebx, edx // pfPitch = Temp; mov edx, dwDeltaPeriod //dwIncDelta = dwDeltaPeriod; //} DontIncreaseValues1: movd mm6, esi // dwFract1 = dwPosition1; movq mm5, mm1 // words in mm5 = 0, 0, 0x1000, 0x1000 shr esi, 12 // dwPosition1 = dwPosition1 >> 12; add ecx, 2 //dwI += 2; // if (dwI < dwLength) break; cmp ecx, dwLength jae StoreOne //if (pfSamplePos >= pfSampleLength) //{ cmp eax, pfSampleLength jb NotPastEndOfSample2 // Original if in C was not negated //if (!pfLoopLength) cmp pfLoopLength, 0 //break; je StoreOne //else //pfSamplePos -= pfLoopLength; sub eax, pfLoopLength //} NotPastEndOfSample2: //shl esi, 1 // do not shift left since pcWave is array of chars mov edi, eax // dwPosition2 = pfSamplePos; add esi, pcWave // Put address of pcWave[dwPosition1] in esi movd mm7, eax // dwFract2 = pfSamplePos; shr edi, 12 // dwPosition2 = dwPosition2 >> 12; punpcklwd mm6, mm7 // combine dwFract Values. Words in mm6 after unpack are // 0, 0, dwFract2, dwFract1 pand mm6, mm4 // dwFract2 &= 0xfff; dwFract1 &= 0xfff; movzx esi, word ptr[esi] //lLM1 = pcWave[dwPosition1]; movd mm3, esi psubw mm5, mm6 // 0, 0, 0x1000 - dwFract2, 0x1000 - dwFract1 //shl edi, 1 // do not shift left since pcWave is array of chars punpcklwd mm5, mm6 // dwFract2, 0x1000 - dwFract2, dwFract1, 0x1000 - dwFract1 add edi, pcWave // Put address of pcWave[dwPosition2] in edi mov esi, ecx // Temp = dWI; shl esi, 1 // Temp = Temp << 1; movzx edi, word ptr[edi] //lLM2 = pcWave[dwPosition2]; movd mm6, edi pxor mm7, mm7 // zero out mm7 to make 8 bit into 16 bit // low 4 bytes bytes in mm3 punpcklwd mm3, mm6 // pcWave[dwPos2+1], pcWave[dwPos2], pcWave[dwPos1+1], pcWave[dwPos1] add esi, pBuffer // punpcklbw mm7, mm3 // bytes in mm7 // pcWave[dwPos2+1], 0, pcWave[dwPos2], 0, pcWave[dwPos1+1], pcWave[dwPos1], 0 pmaddwd mm7, mm5 // high dword = lM2 = //(pcWave[dwPosition2 + 1] * dwFract2 + pcWave[dwPosition2]*(0x1000-dwFract2)) // low dword = lM1 = //(pcWave[dwPosition1 + 1] * dwFract1 + pcWave[dwPosition1]*(0x1000-dwFract1)) movq mm3, mm2 // put left and right volume levels in mm3 add eax, ebx //pfSamplePos += pfPitch; packssdw mm3, mm2 // words in mm3 // vfRVolume2, vfLVolume2, vfRVolume1, vfLVolume1 movq mm5, qword ptr[esi-4] // Load values from buffer add ecx, 2 // dwI += 2; psrad mm7, 12 // shift back down to 16 bits. pand mm7, wordmask // combine results to get ready to multiply by left and right movq mm6, mm7 // volume levels. pslld mm6, 16 // por mm7, mm6 // words in mm7 // lM2, lM2, lM1, lM1 // above multiplies and shifts are all done with this one pmul pmulhw mm3, mm7 // lLM1 *= vfLVolume; // lM1 *= vfRVolume; // lLM2 *= vfLVolume; // lM2 *= vfRVolume; paddsw mm5, mm3 // Add values to buffer with saturation movq qword ptr[esi-4], mm5 // Store values back into buffer. // } jmp mainloop // Need to write only one. //if (dwI < dwLength) //{ StoreOne: #if 1 // Linearly interpolate between points and store only one value. // combine dwFract Values. // Make mm7 zero for unpacking //shl esi, 1 // do not shift left since pcWave is array of chars add esi, pcWave // Put address of pcWave[dwPosition1] in esi pxor mm7, mm7 //lLM1 = pcWave[dwPosition1]; movzx esi, word ptr[esi] // Doing AND that was not done for dwFract1 and dwFract2 pand mm6, mm4 // words in MMX register after operation is complete. psubw mm5, mm6 // 0, 0, 0x1000 - 0, 0x1000 - dwFract1 punpcklwd mm5, mm6 // 0 , 0x1000 - 0, dwFract1, 0x1000 - dwFract1 // put values of pcWave into MMX registers. They are read into a regular register so // that the routine does not read past the end of the buffer otherwise, it could read // directly into the MMX registers. pxor mm7, mm7 // byte in MMX registers movd mm4, esi // 0, 0, pcWave[dwPos1+1], pcWave[dwPos1] punpcklbw mm7, mm4 // 0, 0, 0, 0, pcWave[dwPos1+1], 0, pcWave[dwPos1], 0 // *2 pmadd efficent code. //lM2 = (pcWave[dwPosition2 + 1] * dwFract2 + pcWave[dwPosition2]*(0x1000-dwFract2)) >> 12; //lM1 = (pcWave[dwPosition1 + 1] * dwFract1 + pcWave[dwPosition1]*(0x1000-dwFract1)) >> 12; pmaddwd mm7, mm5// low dword = lM1 = //(pcWave[dwPosition1 + 1] * dwFract1 + pcWave[dwPosition1]*(0x1000-dwFract1)) psrad mm7, 12 // shift back down to 16 bits pand mm7, wordmask // combine results to get ready to multiply by left and right movq mm6, mm7 // volume levels. pslld mm6, 16 // por mm7, mm6 // words in mm7 // lM2, lM2, lM1, lM1 pxor mm6, mm6 movq mm5, mm2 // move volume1 into mm5 // use pack to get 4 volume values together for multiplication. packssdw mm5, mm6 // words in mm7 // 0, 0, vfRVolume1, vfLVolume1 /* // Set lLM to be same as lM lLM1 = lM1; lLM1 *= vfLVolume1; lLM1 >>= 5; // Signal bumps up to 15 bits. lM1 *= vfRVolume1; lM1 >>= 5; // Set lLM to be same as lM lLM2 = lM2; lLM2 *= vfLVolume2; lLM2 >>= 5; // Signal bumps up to 15 bits. lM2 *= vfRVolume2; lM2 >>= 5; */ // above multiplies and shifts are all done with this one pmul pmulhw mm5, mm7 // calculate buffer location. mov edi, ecx shl edi, 1 add edi, pBuffer /* add word ptr[edi-4], si jno no_oflowl1 // pBuffer[dwI] = 0x7fff; mov word ptr[edi-4], 0x7fff js no_oflowl1 //pBuffer[dwI] = (short) 0x8000; mov word ptr[edi-4], 0x8000 no_oflowl1: //pBuffer[dwI+1] += (short) lM1; add word ptr[edi-2], dx jno no_oflowr1 //pBuffer[dwI+1] = 0x7fff; mov word ptr[edi-2], 0x7fff js no_oflowr1 //pBuffer[dwI+1] = (short) 0x8000; mov word ptr[edi-2], 0x8000 no_oflowr1: */ movd mm7, dword ptr[edi-4] paddsw mm7, mm5 movd dword ptr[edi-4], mm7 //} #endif done: mov edx, this // get address of class object //m_vfLastLVolume = vfLVolume; //m_vfLastRVolume = vfRVolume; // need to shift volume back down to 12 bits before storing psrld mm2, 3 movd [edx]this.m_vfLastLVolume, mm2 psrlq mm2, 32 movd [edx]this.m_vfLastRVolume, mm2 //m_pfLastPitch = pfPitch; mov [edx]this.m_pfLastPitch, ebx //m_pfLastSample = pfSamplePos; mov [edx]this.m_pfLastSample, eax // put value back into dwI to be returned. This could just be passed back in eax I think. mov dwI, ecx emms } // ASM block return (dwI >> 1); } DWORD DigitalAudio::MixMono16X(short * pBuffer, DWORD dwLength,DWORD dwDeltaPeriod, VFRACT vfDeltaVolume, PFRACT pfDeltaPitch, PFRACT pfSampleLength, PFRACT pfLoopLength) { DWORD dwI; DWORD dwIncDelta = dwDeltaPeriod; short * pcWave = (short*)m_Source.m_pWave->m_pnWave; PFRACT pfSamplePos = m_pfLastSample; VFRACT vfVolume = m_vfLastLVolume; PFRACT pfPitch = m_pfLastPitch; PFRACT pfPFract = pfPitch << 8; VFRACT vfVFract = vfVolume << 8; // Keep high res version around. QWORD dwFractMASK = 0x000000000FFF0FFF; QWORD dwFractOne = 0x0000000010001000; QWORD wordmask = 0x0000FFFF0000FFFF; QWORD vfDeltaLandRVolume; _asm{ // vfLVFract and vfRVFract are in mm0 //VFRACT vfLVFract = vfLVolume1 << 8; // Keep high res version around. //VFRACT vfRVFract = vfRVolume1 << 8; movd mm0, vfVolume movd mm7, vfVolume // vfDeltaLVolume and vfDeltaRVolume are put in mm1 so that they can be stored in vfDeltaLandRVolume movd mm1, vfDeltaVolume movd mm6, vfDeltaVolume punpckldq mm1, mm6 // dwI = 0 mov ecx, 0 movq vfDeltaLandRVolume, mm1 movq mm1, dwFractOne movq mm4, dwFractMASK mov eax, pfSamplePos punpckldq mm0, mm7 mov ebx, pfPitch pslld mm0, 8 mov edx, dwIncDelta movq mm2, mm0 // vfLVolume and vfRVolume in mm2 // need to be set before first pass. // *1 I shift by 5 so that volume is a 15 bit value instead of a 12 bit value psrld mm2, 5 //for (dwI = 0; dwI < dwLength; ) //{ mainloop: cmp ecx, dwLength jae done cmp eax, pfSampleLength //if (pfSamplePos >= pfSampleLength) jb NotPastEndOfSample1 //{ cmp pfLoopLength, 0 //if (!pfLoopLength) je done // break; sub eax, pfLoopLength // else pfSamplePos -= pfLoopLength; NotPastEndOfSample1: //} mov esi, eax // dwPosition1 = pfSamplePos; add eax, ebx // pfSamplePos += pfPitch; sub edx, 2 // dwIncDelta-=2; jnz DontIncreaseValues1 //if (!dwIncDelta) { // Since edx was use for dwIncDelta and now its zero, we can use if for a temporary // for a bit. All code that TestLVol and TestRVol is doing is zeroing out the volume // if it goes below zero. paddd mm0, vfDeltaLandRVolume // vfVFract += vfDeltaVolume; // vfVFract += vfDeltaVolume; pxor mm5, mm5 // TestLVol = 0; TestRVol = 0; mov edx, pfPFract // Temp = pfPFract; pcmpgtd mm5, mm0 // if (TestLVol > vfLVFract) TestLVol = 0xffffffff; // if (TestRVol > vfRVFract) TestRVol = 0xffffffff; add edx, pfDeltaPitch // Temp += pfDeltaPitch; pandn mm5, mm0 // TestLVol = vfLVFract & (~TestLVol); // TestRVol = vfRVFract & (~TestRVol); mov pfPFract, edx // pfPFract = Temp; movq mm2, mm5 // vfLVolume = TestLVol; // vfRVolume = TestRVol; shr edx, 8 // Temp = Temp >> 8; psrld mm2, 5 // vfLVolume = vfLVolume >> 5; // vfRVolume = vfRVolume >> 5; mov ebx, edx // pfPitch = Temp; mov edx, dwDeltaPeriod //dwIncDelta = dwDeltaPeriod; //} DontIncreaseValues1: movd mm6, esi // dwFract1 = dwPosition1; movq mm5, mm1 // words in mm5 = 0, 0, 0x1000, 0x1000 shr esi, 12 // dwPosition1 = dwPosition1 >> 12; inc ecx //dwI++; // if (dwI < dwLength) break; cmp ecx, dwLength jae StoreOne //if (pfSamplePos >= pfSampleLength) //{ cmp eax, pfSampleLength jb NotPastEndOfSample2 // Original if in C was not negated //if (!pfLoopLength) cmp pfLoopLength, 0 //break; je StoreOne //else //pfSamplePos -= pfLoopLength; sub eax, pfLoopLength //} NotPastEndOfSample2: shl esi, 1 // shift left since pcWave is array of shorts mov edi, eax // dwPosition2 = pfSamplePos; add esi, pcWave // Put address of pcWave[dwPosition1] in esi movd mm7, eax // dwFract2 = pfSamplePos; shr edi, 12 // dwPosition2 = dwPosition2 >> 12; punpcklwd mm6, mm7 // combine dwFract Values. Words in mm6 after unpack are // 0, 0, dwFract2, dwFract1 pand mm6, mm4 // dwFract2 &= 0xfff; dwFract1 &= 0xfff; movd mm7, dword ptr[esi] //lLM1 = pcWave[dwPosition1]; psubw mm5, mm6 // 0, 0, 0x1000 - dwFract2, 0x1000 - dwFract1 shl edi, 1 // shift left since pcWave is array of shorts punpcklwd mm5, mm6 // dwFract2, 0x1000 - dwFract2, dwFract1, 0x1000 - dwFract1 add edi, pcWave // Put address of pcWave[dwPosition2] in edi mov esi, ecx // Temp = dWI; shl esi, 1 // Temp = Temp << 1; movq mm3, mm2 // put left and right volume levels in mm3 movd mm6, dword ptr[edi] //lLM2 = pcWave[dwPosition2]; packssdw mm3, mm2 // words in mm7 // vfRVolume2, vfLVolume2, vfRVolume1, vfLVolume1 add esi, pBuffer // punpckldq mm7, mm6 // low four bytes bytes in // pcWave[dwPos2+1], pcWave[dwPos2], pcWave[dwPos1+1], pcWave[dwPos1] pmaddwd mm7, mm5 // high dword = lM2 = //(pcWave[dwPosition2 + 1] * dwFract2 + pcWave[dwPosition2]*(0x1000-dwFract2)) // low dword = lM1 = //(pcWave[dwPosition1 + 1] * dwFract1 + pcWave[dwPosition1]*(0x1000-dwFract1)) add eax, ebx //pfSamplePos += pfPitch; movd mm5, dword ptr[esi-2] // Load values from buffer inc ecx // dwI++; psrad mm7, 12 // shift back down to 16 bits. packssdw mm7, mm4 // only need one word in mono case. // low word are lm2 and lm1 // above multiplies and shifts are all done with this one pmul. Low two word are only // interest in mono case pmulhw mm3, mm7 // lLM1 *= vfVolume; // lLM2 *= vfVolume; paddsw mm5, mm3 // Add values to buffer with saturation movd dword ptr[esi-2], mm5 // Store values back into buffer. // } jmp mainloop // Need to write only one. //if (dwI < dwLength) //{ StoreOne: #if 1 // Linearly interpolate between points and store only one value. // combine dwFract Values. // Make mm7 zero for unpacking shl esi, 1 // shift left since pcWave is array of shorts add esi, pcWave // Put address of pcWave[dwPosition1] in esi pxor mm7, mm7 //lLM1 = pcWave[dwPosition1]; mov esi, dword ptr[esi] // Doing AND that was not done for dwFract1 and dwFract2 pand mm6, mm4 // words in MMX register after operation is complete. psubw mm5, mm6 // 0, 0, 0x1000 - 0, 0x1000 - dwFract1 punpcklwd mm5, mm6 // 0 , 0x1000 - 0, dwFract1, 0x1000 - dwFract1 // put values of pcWave into MMX registers. They are read into a regular register so // that the routine does not read past the end of the buffer otherwise, it could read // directly into the MMX registers. // words in MMX registers movd mm7, esi // 0, 0, pcWave[dwPos1+1], pcWave[dwPos1] // *2 pmadd efficent code. //lM2 = (pcWave[dwPosition2 + 1] * dwFract2 + pcWave[dwPosition2]*(0x1000-dwFract2)) >> 12; //lM1 = (pcWave[dwPosition1 + 1] * dwFract1 + pcWave[dwPosition1]*(0x1000-dwFract1)) >> 12; pmaddwd mm7, mm5// low dword = lM1 = //(pcWave[dwPosition1 + 1] * dwFract1 + pcWave[dwPosition1]*(0x1000-dwFract1)) psrad mm7, 12 // shift back down to 16 bits movq mm5, mm2 // move volume into mm5 /* // Set lLM to be same as lM lLM1 = lM1; lLM1 *= vfLVolume1; lLM1 >>= 5; // Signal bumps up to 15 bits. lM1 *= vfRVolume1; lM1 >>= 5; // Set lLM to be same as lM lLM2 = lM2; lLM2 *= vfLVolume2; lLM2 >>= 5; // Signal bumps up to 15 bits. lM2 *= vfRVolume2; lM2 >>= 5; */ // above multiplies and shifts are all done with this one pmul pmulhw mm5, mm7 // calculate buffer location. mov edi, ecx shl edi, 1 add edi, pBuffer movd edx, mm5 //pBuffer[dwI+1] += (short) lM1; add word ptr[edi-2], dx jno no_oflowr1 //pBuffer[dwI+1] = 0x7fff; mov word ptr[edi-2], 0x7fff js no_oflowr1 //pBuffer[dwI+1] = (short) 0x8000; mov word ptr[edi-2], 0x8000 no_oflowr1: //} #endif done: mov edx, this // get address of class object //m_vfLastLVolume = vfVolume; //m_vfLastRVolume = vfVolume; // need to shift volume back down to 12 bits before storing psrld mm2, 3 movd [edx]this.m_vfLastLVolume, mm2 movd [edx]this.m_vfLastRVolume, mm2 //m_pfLastPitch = pfPitch; mov [edx]this.m_pfLastPitch, ebx //m_pfLastSample = pfSamplePos; mov [edx]this.m_pfLastSample, eax // put value back into dwI to be returned. This could just be passed back in eax I think. mov dwI, ecx emms } // ASM block return (dwI); } DWORD DigitalAudio::Mix16X(short * pBuffer, DWORD dwLength, DWORD dwDeltaPeriod, VFRACT vfDeltaLVolume, VFRACT vfDeltaRVolume, PFRACT pfDeltaPitch, PFRACT pfSampleLength, PFRACT pfLoopLength) { DWORD dwI; //DWORD dwPosition1, dwPosition2; //long lM1, lLM1; //long lM2, lLM2; DWORD dwIncDelta = dwDeltaPeriod; //VFRACT dwFract1, dwFract2; short * pcWave = (short *) m_Source.m_pWave->m_pnWave; PFRACT pfSamplePos = m_pfLastSample; VFRACT vfLVolume = m_vfLastLVolume; VFRACT vfRVolume = m_vfLastRVolume; VFRACT vfLVolume2 = m_vfLastLVolume; VFRACT vfRVolume2 = m_vfLastRVolume; PFRACT pfPitch = m_pfLastPitch; PFRACT pfPFract = pfPitch << 8; dwLength <<= 1; QWORD dwFractMASK = 0x000000000FFF0FFF; QWORD dwFractOne = 0x0000000010001000; QWORD wordmask = 0x0000FFFF0000FFFF; QWORD vfDeltaLandRVolume; _asm{ // vfLVFract and vfRVFract are in mm0 //VFRACT vfLVFract = vfLVolume1 << 8; // Keep high res version around. //VFRACT vfRVFract = vfRVolume1 << 8; movd mm0, vfLVolume movd mm7, vfRVolume // vfDeltaLVolume and vfDeltaRVolume are put in mm1 so that they can be stored in vfDeltaLandRVolume movd mm1, vfDeltaLVolume movd mm6, vfDeltaRVolume punpckldq mm1, mm6 // dwI = 0 mov ecx, 0 movq vfDeltaLandRVolume, mm1 movq mm1, dwFractOne movq mm4, dwFractMASK mov eax, pfSamplePos punpckldq mm0, mm7 mov ebx, pfPitch pslld mm0, 8 mov edx, dwIncDelta movq mm2, mm0 // vfLVolume and vfRVolume in mm2 // need to be set before first pass. // *1 I shift by 5 so that volume is a 15 bit value instead of a 12 bit value psrld mm2, 5 //for (dwI = 0; dwI < dwLength; ) //{ mainloop: cmp ecx, dwLength jae done cmp eax, pfSampleLength //if (pfSamplePos >= pfSampleLength) jb NotPastEndOfSample1 //{ cmp pfLoopLength, 0 //if (!pfLoopLength) je done // break; sub eax, pfLoopLength // else pfSamplePos -= pfLoopLength; NotPastEndOfSample1: //} mov esi, eax // dwPosition1 = pfSamplePos; add eax, ebx // pfSamplePos += pfPitch; sub edx, 2 // dwIncDelta-=2; jnz DontIncreaseValues1 //if (!dwIncDelta) { // Since edx was use for dwIncDelta and now its zero, we can use if for a temporary // for a bit. All code that TestLVol and TestRVol is doing is zeroing out the volume // if it goes below zero. paddd mm0, vfDeltaLandRVolume // vfLVFract += vfDeltaLVolume; // vfRVFract += vfDeltaRVolume; pxor mm5, mm5 // TestLVol = 0; TestRVol = 0; mov edx, pfPFract // Temp = pfPFract; pcmpgtd mm5, mm0 // if (TestLVol > vfLVFract) TestLVol = 0xffffffff; // if (TestRVol > vfRVFract) TestRVol = 0xffffffff; add edx, pfDeltaPitch // Temp += pfDeltaPitch; pandn mm5, mm0 // TestLVol = vfLVFract & (~TestLVol); // TestRVol = vfRVFract & (~TestRVol); mov pfPFract, edx // pfPFract = Temp; movq mm2, mm5 // vfLVolume = TestLVol; // vfRVolume = TestRVol; shr edx, 8 // Temp = Temp >> 8; psrld mm2, 5 // vfLVolume = vfLVolume >> 5; // vfRVolume = vfRVolume >> 5; mov ebx, edx // pfPitch = Temp; mov edx, dwDeltaPeriod //dwIncDelta = dwDeltaPeriod; //} DontIncreaseValues1: movd mm6, esi // dwFract1 = dwPosition1; movq mm5, mm1 // words in mm5 = 0, 0, 0x1000, 0x1000 shr esi, 12 // dwPosition1 = dwPosition1 >> 12; add ecx, 2 //dwI += 2; // if (dwI < dwLength) break; cmp ecx, dwLength jae StoreOne //if (pfSamplePos >= pfSampleLength) //{ cmp eax, pfSampleLength jb NotPastEndOfSample2 // Original if in C was not negated //if (!pfLoopLength) cmp pfLoopLength, 0 //break; je StoreOne //else //pfSamplePos -= pfLoopLength; sub eax, pfLoopLength //} NotPastEndOfSample2: shl esi, 1 // shift left since pcWave is array of shorts mov edi, eax // dwPosition2 = pfSamplePos; add esi, pcWave // Put address of pcWave[dwPosition1] in esi movd mm7, eax // dwFract2 = pfSamplePos; shr edi, 12 // dwPosition2 = dwPosition2 >> 12; punpcklwd mm6, mm7 // combine dwFract Values. Words in mm6 after unpack are // 0, 0, dwFract2, dwFract1 pand mm6, mm4 // dwFract2 &= 0xfff; dwFract1 &= 0xfff; movd mm7, dword ptr[esi] //lLM1 = pcWave[dwPosition1]; psubw mm5, mm6 // 0, 0, 0x1000 - dwFract2, 0x1000 - dwFract1 shl edi, 1 // shift left since pcWave is array of shorts punpcklwd mm5, mm6 // dwFract2, 0x1000 - dwFract2, dwFract1, 0x1000 - dwFract1 add edi, pcWave // Put address of pcWave[dwPosition2] in edi mov esi, ecx // Temp = dWI; shl esi, 1 // Temp = Temp << 1; movq mm3, mm2 // put left and right volume levels in mm3 movd mm6, dword ptr[edi] //lLM2 = pcWave[dwPosition2]; packssdw mm3, mm2 // words in mm7 // vfRVolume2, vfLVolume2, vfRVolume1, vfLVolume1 add esi, pBuffer // punpckldq mm7, mm6 // low four bytes bytes in // pcWave[dwPos2+1], pcWave[dwPos2], pcWave[dwPos1+1], pcWave[dwPos1] pmaddwd mm7, mm5 // high dword = lM2 = //(pcWave[dwPosition2 + 1] * dwFract2 + pcWave[dwPosition2]*(0x1000-dwFract2)) // low dword = lM1 = //(pcWave[dwPosition1 + 1] * dwFract1 + pcWave[dwPosition1]*(0x1000-dwFract1)) add eax, ebx //pfSamplePos += pfPitch; movq mm5, qword ptr[esi-4] // Load values from buffer add ecx, 2 // dwI += 2; psrad mm7, 12 // shift back down to 16 bits. pand mm7, wordmask // combine results to get ready to multiply by left and right movq mm6, mm7 // volume levels. pslld mm6, 16 // por mm7, mm6 // words in mm7 // lM2, lM2, lM1, lM1 // above multiplies and shifts are all done with this one pmul pmulhw mm3, mm7 // lLM1 *= vfLVolume; // lM1 *= vfRVolume; // lLM2 *= vfLVolume; // lM2 *= vfRVolume; paddsw mm5, mm3 // Add values to buffer with saturation movq qword ptr[esi-4], mm5 // Store values back into buffer. // } jmp mainloop // Need to write only one. //if (dwI < dwLength) //{ StoreOne: #if 1 // Linearly interpolate between points and store only one value. // combine dwFract Values. // Make mm7 zero for unpacking shl esi, 1 // shift left since pcWave is array of shorts add esi, pcWave // Put address of pcWave[dwPosition1] in esi pxor mm7, mm7 //lLM1 = pcWave[dwPosition1]; mov esi, dword ptr[esi] // Doing AND that was not done for dwFract1 and dwFract2 pand mm6, mm4 // words in MMX register after operation is complete. psubw mm5, mm6 // 0, 0, 0x1000 - 0, 0x1000 - dwFract1 punpcklwd mm5, mm6 // 0 , 0x1000 - 0, dwFract1, 0x1000 - dwFract1 // put values of pcWave into MMX registers. They are read into a regular register so // that the routine does not read past the end of the buffer otherwise, it could read // directly into the MMX registers. // words in MMX registers movd mm7, esi // 0, 0, pcWave[dwPos1+1], pcWave[dwPos1] // *2 pmadd efficent code. //lM2 = (pcWave[dwPosition2 + 1] * dwFract2 + pcWave[dwPosition2]*(0x1000-dwFract2)) >> 12; //lM1 = (pcWave[dwPosition1 + 1] * dwFract1 + pcWave[dwPosition1]*(0x1000-dwFract1)) >> 12; pmaddwd mm7, mm5// low dword = lM1 = //(pcWave[dwPosition1 + 1] * dwFract1 + pcWave[dwPosition1]*(0x1000-dwFract1)) psrad mm7, 12 // shift back down to 16 bits pand mm7, wordmask // combine results to get ready to multiply by left and right movq mm6, mm7 // volume levels. pslld mm6, 16 // por mm7, mm6 // words in mm7 // lM2, lM2, lM1, lM1 pxor mm6, mm6 movq mm5, mm2 // move volume1 into mm5 // use pack to get 4 volume values together for multiplication. packssdw mm5, mm6 // words in mm7 // 0, 0, vfRVolume1, vfLVolume1 /* // Set lLM to be same as lM lLM1 = lM1; lLM1 *= vfLVolume1; lLM1 >>= 5; // Signal bumps up to 15 bits. lM1 *= vfRVolume1; lM1 >>= 5; // Set lLM to be same as lM lLM2 = lM2; lLM2 *= vfLVolume2; lLM2 >>= 5; // Signal bumps up to 15 bits. lM2 *= vfRVolume2; lM2 >>= 5; */ // above multiplies and shifts are all done with this one pmul pmulhw mm5, mm7 // calculate buffer location. mov edi, ecx shl edi, 1 add edi, pBuffer /* add word ptr[edi-4], si jno no_oflowl1 // pBuffer[dwI] = 0x7fff; mov word ptr[edi-4], 0x7fff js no_oflowl1 //pBuffer[dwI] = (short) 0x8000; mov word ptr[edi-4], 0x8000 no_oflowl1: //pBuffer[dwI+1] += (short) lM1; add word ptr[edi-2], dx jno no_oflowr1 //pBuffer[dwI+1] = 0x7fff; mov word ptr[edi-2], 0x7fff js no_oflowr1 //pBuffer[dwI+1] = (short) 0x8000; mov word ptr[edi-2], 0x8000 no_oflowr1: */ movd mm7, dword ptr[edi-4] paddsw mm7, mm5 movd dword ptr[edi-4], mm7 //} #endif done: mov edx, this // get address of class object //m_vfLastLVolume = vfLVolume; //m_vfLastRVolume = vfRVolume; // need to shift volume back down to 12 bits before storing psrld mm2, 3 movd [edx]this.m_vfLastLVolume, mm2 psrlq mm2, 32 movd [edx]this.m_vfLastRVolume, mm2 //m_pfLastPitch = pfPitch; mov [edx]this.m_pfLastPitch, ebx //m_pfLastSample = pfSamplePos; mov [edx]this.m_pfLastSample, eax // put value back into dwI to be returned. This could just be passed back in eax I think. mov dwI, ecx emms } // ASM block return (dwI >> 1); } #define CPU_ID _asm _emit 0x0f _asm _emit 0xa2 BOOL MultiMediaInstructionsSupported() { static BOOL bMultiMediaInstructionsSupported = FALSE; static BOOL bFlagNotSetYet = TRUE; // No need to keep interogating the CPU after it has been checked the first time if (bFlagNotSetYet) { bFlagNotSetYet = FALSE; // Don't repeat the check for each call _asm { pushfd // Store original EFLAGS on stack pop eax // Get original EFLAGS in EAX mov ecx, eax // Duplicate original EFLAGS in ECX for toggle check xor eax, 0x00200000L // Flip ID bit in EFLAGS push eax // Save new EFLAGS value on stack popfd // Replace current EFLAGS value pushfd // Store new EFLAGS on stack pop eax // Get new EFLAGS in EAX xor eax, ecx // Can we toggle ID bit? jz Done // Jump if no, Processor is older than a Pentium so CPU_ID is not supported mov eax, 1 // Set EAX to tell the CPUID instruction what to return push ebx // CPU_ID trashes eax-edx CPU_ID // Get family/model/stepping/features pop ebx // CPU_ID trashes eax-edx test edx, 0x00800000L // Check if mmx technology available jz Done // Jump if no //Don't need to do this now - P55C's are adequate, so any MMX chip is good enough. // also check for GenuineIntel // GenuineIntel and clones work differently. // if not, jump to Success: // The clones' implementations work. // check family // Initial implementation of MMX is inefficient for EMMS, // if 5 or earlier, jump to Done: // so use only family 6 or higher. } //Success: // Tests have passed, this machine supports MMX Instruction Set! bMultiMediaInstructionsSupported = TRUE; Done: NULL; } return (bMultiMediaInstructionsSupported); }
39.370423
145
0.469037
[ "object", "model" ]
4f8727b43bce5602538a31d1f582194d43c64c4e
3,010
cpp
C++
src/ms/env/charge_cmp.cpp
toppic-suite/toppic-suite
b5f0851f437dde053ddc646f45f9f592c16503ec
[ "Apache-2.0" ]
8
2018-05-23T14:37:31.000Z
2022-02-04T23:48:38.000Z
src/ms/env/charge_cmp.cpp
toppic-suite/toppic-suite
b5f0851f437dde053ddc646f45f9f592c16503ec
[ "Apache-2.0" ]
9
2019-08-31T08:17:45.000Z
2022-02-11T20:58:06.000Z
src/ms/env/charge_cmp.cpp
toppic-suite/toppic-suite
b5f0851f437dde053ddc646f45f9f592c16503ec
[ "Apache-2.0" ]
4
2018-04-25T01:39:38.000Z
2020-05-20T19:25:07.000Z
//Copyright (c) 2014 - 2020, The Trustees of Indiana University. // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. #include <cmath> #include "ms/env/charge_cmp.hpp" namespace toppic { namespace charge_cmp { // get common peaks in two peak lists std::vector<int> getCommonPeak(RealEnvPtr env_a, RealEnvPtr env_b) { int len = env_a->getPeakNum(); std::vector<int> common_peaks(len, -1); for (int i = 0; i < len; i++) { int a_idx = env_a->getPeakIdx(i); for (int j = 0; j < env_b->getPeakNum(); j++) { int b_idx = env_b->getPeakIdx(j); if (env_a->isExist(i) && a_idx == b_idx) { common_peaks[i] = a_idx; } } } return common_peaks; } // count the number of common peaks. int cntCommonPeak(std::vector<int> &list_a) { int cnt = 0; for (size_t i = 0; i < list_a.size(); i++) { if (list_a[i] >= 0) { cnt++; } } return cnt; } // check if the second charge state is better bool isSecondBetter(const PeakPtrVec &peak_list, MatchEnvPtr a, MatchEnvPtr b, double tolerance) { // get common peak std::vector<int> common_peaks = getCommonPeak(a->getRealEnvPtr(), b->getRealEnvPtr()); int common_num = cntCommonPeak(common_peaks); if (common_num <= 6) { return false; } /* get distance list */ std::vector<double> dist; for (size_t i = 0; i < common_peaks.size(); i++) { for (size_t j = i + 1; j < common_peaks.size(); j++) { if (common_peaks[i] >= 0 && common_peaks[j] >= 0) { dist.push_back( (peak_list[common_peaks[j]]->getPosition() - peak_list[common_peaks[i]]->getPosition()) / (j - i)); } } } // check if the distance is near to 1/(chrg_a) or 1/(chrg+b) int cnt_a = 0; int cnt_b = 0; double center_a = 1 / a->getTheoEnvPtr()->getCharge(); double center_b = 1 / b->getTheoEnvPtr()->getCharge(); for (size_t i = 0; i < dist.size(); i++) { double d = dist[i]; if (std::abs(d - center_a) < std::abs(d - center_b) && std::abs(d - center_a) < tolerance) { cnt_a++; } if (std::abs(d - center_b) < std::abs(d - center_a) && std::abs(d - center_b) < tolerance) { cnt_b++; } } if (cnt_b > cnt_a) { return true; } else { return false; } } int comp(const PeakPtrVec &peak_list, MatchEnvPtr a, MatchEnvPtr b, double tolerance) { if (isSecondBetter(peak_list, a, b, tolerance)) { return -1; } if (isSecondBetter(peak_list, b, a, tolerance)) { return 1; } return 0; } } }
28.666667
111
0.623588
[ "vector" ]
4f8b1761a53c5396c849b5e86c387356336347c4
2,055
cpp
C++
cpp/0004_findMedianSortedArrays.cpp
linhx25/leetcode
9cf1d6d2372fd8777825c8107780b7f3c934fe20
[ "MIT" ]
1
2021-04-16T12:54:56.000Z
2021-04-16T12:54:56.000Z
cpp/0004_findMedianSortedArrays.cpp
linhx25/leetcode
9cf1d6d2372fd8777825c8107780b7f3c934fe20
[ "MIT" ]
null
null
null
cpp/0004_findMedianSortedArrays.cpp
linhx25/leetcode
9cf1d6d2372fd8777825c8107780b7f3c934fe20
[ "MIT" ]
1
2021-04-26T13:20:41.000Z
2021-04-26T13:20:41.000Z
using namespace std; // 1.brute force 是合并两个数组,选择中位数 // 2.不完全合并两个数组,可以先确定中位数的位置,两个队列依次取小的入栈,栈满则计算中位数 class Solution { public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { auto p1 = nums1.begin(); auto p2 = nums2.begin(); auto m = nums1.size(); auto n = nums2.size(); if (m==0) { if(n%2==0) { return (double)(nums2.at(n/2-1)+nums2.at(n/2))/2; } else { return (double)(nums2.at(n/2)); } } if (n==0) { if(m%2==0) { return (double)(nums1.at(m/2-1)+nums1.at(m/2))/2; } else { return (double)(nums1.at(m/2)); } } vector<int> vec_res; auto size = 1+(m+n)/2; for(auto p=0;p<size;p++) { if (p1!=nums1.end() && p2!=nums2.end()) { if (*p1>*p2) { vec_res.push_back(*p2); p2++; continue; } else { vec_res.push_back(*p1); p1++; continue; } } else { if (p2!=nums2.end()) { vec_res.push_back(*p2); p2++; continue; } if (p1!=nums1.end()) { vec_res.push_back(*p1); p1++; continue; } } } if ((m+n)%2 ==0) { auto t = (double)vec_res.at(vec_res.size()-1); auto tt = (double)vec_res.at(vec_res.size()-2); return (t + tt)/2; } else { return (double) vec_res.at(vec_res.size()-1); } } };
24.464286
75
0.3309
[ "vector" ]
4f8b7facc810af6bd75d423f72016a61278e85af
6,267
cpp
C++
Libraries/LibCore/CObject.cpp
MWGuy/serenity
548dd7ebd1c640297fd7f2828e3c7ecb6d3765bd
[ "BSD-2-Clause" ]
null
null
null
Libraries/LibCore/CObject.cpp
MWGuy/serenity
548dd7ebd1c640297fd7f2828e3c7ecb6d3765bd
[ "BSD-2-Clause" ]
null
null
null
Libraries/LibCore/CObject.cpp
MWGuy/serenity
548dd7ebd1c640297fd7f2828e3c7ecb6d3765bd
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <AK/Assertions.h> #include <AK/JsonObject.h> #include <AK/kstdio.h> #include <LibCore/CEvent.h> #include <LibCore/CEventLoop.h> #include <LibCore/CObject.h> #include <stdio.h> IntrusiveList<CObject, &CObject::m_all_objects_list_node>& CObject::all_objects() { static IntrusiveList<CObject, &CObject::m_all_objects_list_node> objects; return objects; } CObject::CObject(CObject* parent, bool is_widget) : m_parent(parent) , m_widget(is_widget) { all_objects().append(*this); if (m_parent) m_parent->add_child(*this); } CObject::~CObject() { // NOTE: We move our children out to a stack vector to prevent other // code from trying to iterate over them. auto children = move(m_children); // NOTE: We also unparent the children, so that they won't try to unparent // themselves in their own destructors. for (auto& child : children) child.m_parent = nullptr; all_objects().remove(*this); stop_timer(); if (m_parent) m_parent->remove_child(*this); } void CObject::event(CEvent& event) { switch (event.type()) { case CEvent::Timer: return timer_event(static_cast<CTimerEvent&>(event)); case CEvent::ChildAdded: case CEvent::ChildRemoved: return child_event(static_cast<CChildEvent&>(event)); case CEvent::Invalid: ASSERT_NOT_REACHED(); break; case CEvent::Custom: return custom_event(static_cast<CCustomEvent&>(event)); default: break; } } void CObject::add_child(CObject& object) { // FIXME: Should we support reparenting objects? ASSERT(!object.parent() || object.parent() == this); object.m_parent = this; m_children.append(object); event(*make<CChildEvent>(CEvent::ChildAdded, object)); } void CObject::insert_child_before(CObject& new_child, CObject& before_child) { // FIXME: Should we support reparenting objects? ASSERT(!new_child.parent() || new_child.parent() == this); new_child.m_parent = this; m_children.insert_before_matching(new_child, [&](auto& existing_child) { return existing_child.ptr() == &before_child; }); event(*make<CChildEvent>(CEvent::ChildAdded, new_child, &before_child)); } void CObject::remove_child(CObject& object) { for (int i = 0; i < m_children.size(); ++i) { if (m_children.ptr_at(i).ptr() == &object) { // NOTE: We protect the child so it survives the handling of ChildRemoved. NonnullRefPtr<CObject> protector = object; object.m_parent = nullptr; m_children.remove(i); event(*make<CChildEvent>(CEvent::ChildRemoved, object)); return; } } ASSERT_NOT_REACHED(); } void CObject::timer_event(CTimerEvent&) { } void CObject::child_event(CChildEvent&) { } void CObject::custom_event(CCustomEvent&) { } void CObject::start_timer(int ms, TimerShouldFireWhenNotVisible fire_when_not_visible) { if (m_timer_id) { dbgprintf("CObject{%p} already has a timer!\n", this); ASSERT_NOT_REACHED(); } m_timer_id = CEventLoop::register_timer(*this, ms, true, fire_when_not_visible); } void CObject::stop_timer() { if (!m_timer_id) return; bool success = CEventLoop::unregister_timer(m_timer_id); ASSERT(success); m_timer_id = 0; } void CObject::dump_tree(int indent) { for (int i = 0; i < indent; ++i) { printf(" "); } printf("%s{%p}\n", class_name(), this); for_each_child([&](auto& child) { child.dump_tree(indent + 2); return IterationDecision::Continue; }); } void CObject::deferred_invoke(Function<void(CObject&)> invokee) { CEventLoop::current().post_event(*this, make<CDeferredInvocationEvent>(move(invokee))); } void CObject::save_to(JsonObject& json) { json.set("class_name", class_name()); json.set("address", String::format("%p", this)); json.set("name", name()); json.set("parent", String::format("%p", parent())); } bool CObject::is_ancestor_of(const CObject& other) const { if (&other == this) return false; for (auto* ancestor = other.parent(); ancestor; ancestor = ancestor->parent()) { if (ancestor == this) return true; } return false; } void CObject::dispatch_event(CEvent& e, CObject* stay_within) { ASSERT(!stay_within || stay_within == this || stay_within->is_ancestor_of(*this)); auto* target = this; do { target->event(e); target = target->parent(); if (target == stay_within) { // Prevent the event from bubbling any further. e.accept(); break; } } while (target && !e.is_accepted()); } bool CObject::is_visible_for_timer_purposes() const { if (parent()) return parent()->is_visible_for_timer_purposes(); return true; }
30.42233
126
0.674485
[ "object", "vector" ]
4f8bbffb72cb755a4bfdb383cf2bcb80c2914252
8,530
cc
C++
cfs/src/FsProc_FsMain.cc
chenhao-ye/uFS
c344d689b33e30dd83bcd1b4de26602549a90fc3
[ "MIT" ]
13
2021-08-23T03:37:46.000Z
2022-02-16T03:00:09.000Z
cfs/src/FsProc_FsMain.cc
chenhao-ye/uFS
c344d689b33e30dd83bcd1b4de26602549a90fc3
[ "MIT" ]
2
2021-11-12T10:19:47.000Z
2021-12-21T14:26:36.000Z
cfs/src/FsProc_FsMain.cc
chenhao-ye/uFS
c344d689b33e30dd83bcd1b4de26602549a90fc3
[ "MIT" ]
4
2021-09-03T13:55:05.000Z
2021-11-09T10:59:33.000Z
#include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <experimental/filesystem> #include <iostream> #include <memory> #include "FsLibShared.h" #include "FsProc_Fs.h" #include "config4cpp/Configuration.h" #include "spdlog/spdlog.h" #include "typedefs.h" // global fs object FsProc *gFsProcPtr = nullptr; static const char *gFspConfigFname = nullptr; void handle_sigint(int sig); // Main function of FSP // @numworkers: number of thread of FSP // @numAppProc: number of application process it is going to handle (will // @provision memory ring accordingly) // @shmBaseOffset: if specified, the intention is to run multiple FSP // processes at a time, then each use different shmkey group. E.g., FSP1: // Base+1+ProcID, FSP2: Base+2+ProcID // @exitSignalFileName: file name for FSP to monitor and thus decide to exit. // @configFileName: the config file used to initialize SPDK dev only, all the // parameter will be used as SPDK options int fsMain(int numWorkers, int numAppProc, std::vector<int> &shmBaseOffsets, const char *exitSignalFileName, const char *configFileName, bool isSpdk, std::vector<int> &workerCores) { #if CFS_JOURNAL(OFF) fprintf(stdout, "Journal is disabled\n"); #else fprintf(stdout, "Journal is enabled\n"); #endif #ifdef NDEBUG fprintf(stdout, "NDEBUG defined\n"); #else fprintf(stdout, "NDEBUG not defined\n"); #endif macro_print(NMEM_DATA_BLOCK); CurBlkDev *devPtr = nullptr; SPDLOG_INFO("fsMain"); std::vector<CurBlkDev *> devVec; // NOTE: devPtr is used as a global variable previously if (configFileName == nullptr) { if (isSpdk) { devPtr = new CurBlkDev("", DEV_SIZE / BSIZE, BSIZE); } else { devPtr = new CurBlkDev(BLK_DEV_POSIX_FILE_NAME, DEV_SIZE / BSIZE, BSIZE); } devPtr->updateWorkerNum(numWorkers); devVec.push_back(devPtr); } else { std::string configNameStr(configFileName); if (isSpdk) { devPtr = new CurBlkDev("", DEV_SIZE / BSIZE, BSIZE, configNameStr); } else { devPtr = new CurBlkDev(BLK_DEV_POSIX_FILE_NAME, DEV_SIZE / BSIZE, BSIZE, configFileName); } devPtr->updateWorkerNum(numWorkers); // For both BlkDevSpdk and BlkDevPosix, we let all threads share the same // virtual block device for (int i = 0; i < numWorkers; i++) { devVec.push_back(devPtr); } } // devVec[0]->enableReportStats(true); gFsProcPtr = new FsProc(numWorkers, numAppProc, exitSignalFileName); // std::cout << "len devVec:" << devVec.size() << std::endl; if (gFspConfigFname != nullptr) { fprintf(stderr, "setConfigFname\n"); gFsProcPtr->setConfigFname(gFspConfigFname); } #ifdef FSP_ENABLE_ALLOC_READ_RA std::cout << "READAHEAD raNumBlocks:" << gFsProcPtr->getRaNumBlock() << std::endl; #endif std::cout << "ServerCorePolicy:" << gFsProcPtr->getServerCorePolicyNo() << std::endl; std::cout << "lb_cgst_ql:" << gFsProcPtr->GetLbCgstQl() << std::endl; std::cout << "nc_percore_ut:" << gFsProcPtr->GetNcPerCoreUt() << std::endl; signal(SIGINT, handle_sigint); // start workers gFsProcPtr->startWorkers(shmBaseOffsets, devVec, workerCores); return 0; } void usage(char **argv) { std::cerr << "Usage:" << argv[0] << " <numWorkers> <numAppProc> <shmBaseOffset> <exitFileName> " "<devConfigName> <workerCores> [FspConfigName]\n" << " numWorkers: number of threads for running FSP\n" << " numAppProc: number of application's pre-registered apps\n" << " shnBaseOffset: offset of shmkey compared to FS_SHM_KEY_BASE\n" << " - e.g., 1,11 (for numWorkers=2)\n" << " exitFileName: a file that once show up <=> fs exit\n" << " [devConfigName] REQUIRED when numWorker>1\n" << " workerCores: comma separated list of cores to pin workers\n" << " ENVIRONMENTAL VARIABLES: \n" << " READY_FILE_NAME : write to filepath when ready\n"; } void check_root() { int uid = getuid(); if (uid != 0) { printOnErrorExitSymbol(); std::cerr << "Error, must be invoked in root mode. \nExit ......\n"; exit(1); } } void logFeatureMacros() { #if CFS_JOURNAL(NO_JOURNAL) SPDLOG_INFO("CFS_JOURNAL(NO_JOURNAL) = True"); #endif #if CFS_JOURNAL(ON) SPDLOG_INFO("CFS_JOURNAL(ON) = True"); #endif #if CFS_JOURNAL(LOCAL_JOURNAL) SPDLOG_INFO("CFS_JOURNAL(LOCAL_JOURNAL) = True"); #endif #if CFS_JOURNAL(GLOBAL_JOURNAL) SPDLOG_INFO("CFS_JOURNAL(GLOBAL_JOURNAL) = True"); #endif #if CFS_JOURNAL(PERF_METRICS) SPDLOG_INFO("CFS_JOURNAL(PERF_METRICS) = True"); #endif #if !CFS_JOURNAL(CHECKPOINTING) // This should only be used when testing writes where you don't want // checkpointing to be measured. It will fail offlineCheckpointer so it cannot // be used accross multiple runs of fsp. Mkfs must be called after this run of // fsp. SPDLOG_WARN("CFS_JOURNAL(CHECKPOINTING) = False"); #endif } static const int gHostNameLen = 512; static char gHostName[gHostNameLen]; int main(int argc, char **argv) { check_root(); google::InitGoogleLogging(argv[0]); // print hostname gethostname(gHostName, gHostNameLen); std::cout << argv[0] << " started in host:" << gHostName << "\n"; // Print macro configuration here bool isSpdk = false; #ifdef USE_SPDK isSpdk = true; #endif #ifndef NONE_MT_LOCK std::cout << "NONE_MT_LOC - OFF" << std::endl; #else std::cout << "NONE_MT_LOC - ON" << std::endl; #endif #ifndef MIMIC_FSP_ZC std::cout << "MIMIC_FSP_ZC - OFF" << std::endl; #else std::cout << "MIMIC_FSP_ZC - ON" << std::endl; #endif #if (FS_LIB_USE_APP_CACHE) std::cout << "FS_LIB_USE_APP_CACHE - ON" << std::endl; #else std::cout << "FS_LIB_USE_APP_CACHE - OFF" << std::endl; #endif #ifdef FSP_ENABLE_ALLOC_READ_RA std::cout << "FS_ENABLE_ALLOC_READ_RA - ON" << std::endl; #else std::cout << "FS_ENABLE_ALLOC_READ_RA - OFF" << std::endl; #endif logFeatureMacros(); std::vector<int> shmBaseOffsetVec = {0}; std::vector<int> workerCores; // empty by default if (argc == 3) { // By Default no shmBaseOffset specified, this is to be compatible with old // experiments. fsMain(std::stoi(std::string(argv[1])), std::stoi(std::string(argv[2])), /*shmBaseOffset*/ shmBaseOffsetVec, /*exitSignalFileName*/ nullptr, /*configFileName*/ nullptr, isSpdk, workerCores); } else if (argc == 5) { shmBaseOffsetVec[0] = std::stoi(std::string(argv[3])); fsMain(std::stoi(std::string(argv[1])), std::stoi(std::string(argv[2])), shmBaseOffsetVec, argv[4], nullptr, isSpdk, workerCores); } else if (argc >= 6) { // NOTE: now this argument list is preferable. (2020/07/29) auto numWorkers = std::stoi(std::string(argv[1])); auto strs = splitStr(std::string(argv[3]), ','); fprintf(stdout, "======= FSP: config file (%s), shmOffsetList:%s =======\n", argv[5], argv[3]); shmBaseOffsetVec.clear(); for (const auto &str : strs) shmBaseOffsetVec.push_back(std::stoi(str)); if (shmBaseOffsetVec.size() != (unsigned)numWorkers) { fprintf(stderr, "numWorkers should match shmBaseOffset. Exit...\n"); exit(1); } if (argc == 7 || argc == 8) { // last argument is a comma separated list of cores to pin workers on // TODO convert code to use getopt - will be much cleaner // e.g. cfs/test/shmipc/client.c and cfs/test/shmipc/myargs.h // NOTE: these changes would also require changing all benchmark // scripts and experiments to make sure they work with the new format. auto strs = splitStr(std::string(argv[6]), ','); for (const auto &str : strs) workerCores.push_back(std::stoi(str)); if (workerCores.size() != (unsigned)numWorkers) { fprintf(stderr, "numWorkers should match workerCores. Exit...\n"); exit(1); } } if (argc == 8 && std::experimental::filesystem::exists(argv[7])) { // optional argument // use this to pass in a configuration file to configure FSP behavior // mostly specify the policy gFspConfigFname = argv[7]; SPDLOG_INFO("FSP configuration file is set to :{}", gFspConfigFname); } fsMain(numWorkers, std::stoi(std::string(argv[2])), shmBaseOffsetVec, argv[4], argv[5], isSpdk, workerCores); } else { usage(argv); return -1; } return 0; } void handle_sigint(int sig) { gFsProcPtr->stop(); // delete gFsProcPtr; // exit(0); }
33.582677
80
0.658499
[ "object", "vector" ]
4f8cc3f34305211141ef284590523ef9f1afd089
9,747
cpp
C++
arangod/RestHandler/RestTasksHandler.cpp
Korov/arangodb
d1f8df028f8af60d1cd5708890f0d6ae75f9dd06
[ "Apache-2.0" ]
null
null
null
arangod/RestHandler/RestTasksHandler.cpp
Korov/arangodb
d1f8df028f8af60d1cd5708890f0d6ae75f9dd06
[ "Apache-2.0" ]
null
null
null
arangod/RestHandler/RestTasksHandler.cpp
Korov/arangodb
d1f8df028f8af60d1cd5708890f0d6ae75f9dd06
[ "Apache-2.0" ]
1
2020-10-01T08:49:12.000Z
2020-10-01T08:49:12.000Z
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2020 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Dan Larkin-York //////////////////////////////////////////////////////////////////////////////// #include "RestTasksHandler.h" #include "ApplicationFeatures/ApplicationServer.h" #include "Basics/StaticStrings.h" #include "Basics/VelocyPackHelper.h" #include "Cluster/ClusterFeature.h" #include "Cluster/ClusterInfo.h" #include "Cluster/ServerState.h" #include "V8/JavaScriptSecurityContext.h" #include "V8/v8-globals.h" #include "V8/v8-vpack.h" #include "V8Server/V8DealerFeature.h" #include "VocBase/Methods/Tasks.h" #include <velocypack/Builder.h> #include <velocypack/velocypack-aliases.h> using namespace arangodb::basics; using namespace arangodb::rest; namespace arangodb { RestTasksHandler::RestTasksHandler(application_features::ApplicationServer& server, GeneralRequest* request, GeneralResponse* response) : RestVocbaseBaseHandler(server, request, response) {} RestStatus RestTasksHandler::execute() { if (!server().isEnabled<V8DealerFeature>()) { generateError(rest::ResponseCode::NOT_IMPLEMENTED, TRI_ERROR_NOT_IMPLEMENTED, "JavaScript operations are disabled"); return RestStatus::DONE; } auto const type = _request->requestType(); switch (type) { case rest::RequestType::POST: { registerTask(false); break; } case rest::RequestType::PUT: { registerTask(true); break; } case rest::RequestType::DELETE_REQ: { deleteTask(); break; } case rest::RequestType::GET: { getTasks(); break; } default: { generateError(rest::ResponseCode::METHOD_NOT_ALLOWED, TRI_ERROR_HTTP_METHOD_NOT_ALLOWED); } } return RestStatus::DONE; } /// @brief returns the short id of the server which should handle this request ResultT<std::pair<std::string, bool>> RestTasksHandler::forwardingTarget() { auto base = RestVocbaseBaseHandler::forwardingTarget(); if (base.ok() && !std::get<0>(base.get()).empty()) { return base; } rest::RequestType const type = _request->requestType(); if (type != rest::RequestType::POST && type != rest::RequestType::PUT && type != rest::RequestType::GET && type != rest::RequestType::DELETE_REQ) { return {std::make_pair(StaticStrings::Empty, false)}; } std::vector<std::string> const& suffixes = _request->suffixes(); if (suffixes.size() < 1) { return {std::make_pair(StaticStrings::Empty, false)}; } uint64_t tick = arangodb::basics::StringUtils::uint64(suffixes[0]); uint32_t sourceServer = TRI_ExtractServerIdFromTick(tick); if (sourceServer == ServerState::instance()->getShortId()) { return {std::make_pair(StaticStrings::Empty, false)}; } auto& ci = server().getFeature<ClusterFeature>().clusterInfo(); return {std::make_pair(ci.getCoordinatorByShortID(sourceServer), false)}; } void RestTasksHandler::getTasks() { std::vector<std::string> const& suffixes = _request->decodedSuffixes(); if (suffixes.size() > 1) { generateError(rest::ResponseCode::BAD, TRI_ERROR_HTTP_SUPERFLUOUS_SUFFICES, "superfluous parameter, expecting /_api/tasks[/<id>]"); return; } std::shared_ptr<VPackBuilder> builder; if (suffixes.size() == 1) { // get a single task builder = Task::registeredTask(suffixes[0]); } else { // get all tasks builder = Task::registeredTasks(); } if (builder == nullptr) { generateError(TRI_ERROR_TASK_NOT_FOUND); return; } generateResult(rest::ResponseCode::OK, builder->slice()); } void RestTasksHandler::registerTask(bool byId) { bool parseSuccess = false; VPackSlice body = this->parseVPackBody(parseSuccess); if (!parseSuccess) { // error message generated in parseVPackBody return; } std::vector<std::string> const& suffixes = _request->decodedSuffixes(); // job id std::string id; if (byId) { if ((suffixes.size() != 1) || suffixes[0].empty()) { generateError(rest::ResponseCode::BAD, TRI_ERROR_BAD_PARAMETER, "expected PUT /_api/tasks/<task-id>"); return; } else { id = suffixes[0]; } } ExecContext const& exec = ExecContext::current(); if (exec.databaseAuthLevel() != auth::Level::RW) { generateError(rest::ResponseCode::FORBIDDEN, TRI_ERROR_FORBIDDEN, "registering a task needs db RW permissions"); return; } // job id if (id.empty()) { id = VelocyPackHelper::getStringValue(body, "id", std::to_string(TRI_NewServerSpecificTick())); } // job name std::string name = VelocyPackHelper::getStringValue(body, "name", "user-defined task"); bool isSystem = VelocyPackHelper::getBooleanValue(body, StaticStrings::DataSourceSystem, false); // offset in seconds into period or from now on if no period double offset = VelocyPackHelper::getNumericValue<double>(body, "offset", 0.0); // period in seconds & count double period = 0.0; auto periodSlice = body.get("period"); if (periodSlice.isNumber()) { period = VelocyPackHelper::getNumericValue<double>(body, "period", 0.0); if (period <= 0.0) { generateError(rest::ResponseCode::BAD, TRI_ERROR_BAD_PARAMETER, "task period must be specified and positive"); return; } } std::string runAsUser = VelocyPackHelper::getStringValue(body, "runAsUser", ""); // only the superroot is allowed to run tasks as an arbitrary user if (runAsUser.empty()) { // execute task as the same user runAsUser = exec.user(); } else if (exec.user() != runAsUser) { generateError(rest::ResponseCode::FORBIDDEN, TRI_ERROR_FORBIDDEN, "cannot run task as a different user"); return; } // extract the command std::string command; auto cmdSlice = body.get("command"); if (!cmdSlice.isString()) { generateError(rest::ResponseCode::BAD, TRI_ERROR_BAD_PARAMETER, "command must be specified"); return; } try { JavaScriptSecurityContext securityContext = JavaScriptSecurityContext::createRestrictedContext(); V8ContextGuard guard(&_vocbase, securityContext); v8::Isolate* isolate = guard.isolate(); v8::HandleScope scope(isolate); auto context = TRI_IGETC; v8::Handle<v8::Object> bv8 = TRI_VPackToV8(isolate, body).As<v8::Object>(); if (bv8->Get(context, TRI_V8_ASCII_STRING(isolate, "command")).FromMaybe(v8::Handle<v8::Value>())->IsFunction()) { // need to add ( and ) around function because call will otherwise break command = "(" + cmdSlice.copyString() + ")(params)"; } else { command = cmdSlice.copyString(); } if (!Task::tryCompile(isolate, command)) { generateError(rest::ResponseCode::BAD, TRI_ERROR_BAD_PARAMETER, "cannot compile command"); return; } } catch (arangodb::basics::Exception const& ex) { generateError(Result{ex.code(), ex.what()}); return; } catch (std::exception const& ex) { generateError(Result{TRI_ERROR_INTERNAL, ex.what()}); return; } catch (...) { generateError(TRI_ERROR_INTERNAL); return; } // extract the parameters auto parameters = std::make_shared<VPackBuilder>(body.get("params")); command = "(function (params) { " + command + " } )(params);"; int res; std::shared_ptr<Task> task = Task::createTask(id, name, &_vocbase, command, isSystem, res); if (res != TRI_ERROR_NO_ERROR) { generateError(res); return; } // set the user this will run as if (!runAsUser.empty()) { task->setUser(runAsUser); } // set execution parameters task->setParameter(parameters); if (period > 0.0) { // create a new periodic task task->setPeriod(offset, period); } else { // create a run-once timer task task->setOffset(offset); } // get the VelocyPack representation of the task std::shared_ptr<VPackBuilder> builder = task->toVelocyPack(); if (builder == nullptr) { generateError(TRI_ERROR_INTERNAL); return; } task->start(); generateResult(rest::ResponseCode::OK, builder->slice()); } void RestTasksHandler::deleteTask() { std::vector<std::string> const& suffixes = _request->decodedSuffixes(); if ((suffixes.size() != 1) || suffixes[0].empty()) { generateError(rest::ResponseCode::BAD, TRI_ERROR_HTTP_SUPERFLUOUS_SUFFICES, "bad parameter, expecting /_api/tasks/<id>"); return; } ExecContext const& exec = ExecContext::current(); if (exec.databaseAuthLevel() != auth::Level::RW) { generateError(rest::ResponseCode::FORBIDDEN, TRI_ERROR_FORBIDDEN, "unregister task needs db RW permissions"); return; } int res = Task::unregisterTask(suffixes[0], true); if (res != TRI_ERROR_NO_ERROR) { generateError(res); return; } generateOk(rest::ResponseCode::OK, velocypack::Slice()); } } // namespace arangodb
31.240385
120
0.659177
[ "object", "vector" ]
4f8d9334249cf0a0507398f9176108945c921a8c
97,635
cpp
C++
src/coreclr/jit/liveness.cpp
pyracanda/runtime
72bee25ab532a4d0636118ec2ed3eabf3fd55245
[ "MIT" ]
9,402
2019-11-25T23:26:24.000Z
2022-03-31T23:19:41.000Z
src/coreclr/jit/liveness.cpp
pyracanda/runtime
72bee25ab532a4d0636118ec2ed3eabf3fd55245
[ "MIT" ]
37,522
2019-11-25T23:30:32.000Z
2022-03-31T23:58:30.000Z
src/coreclr/jit/liveness.cpp
pyracanda/runtime
72bee25ab532a4d0636118ec2ed3eabf3fd55245
[ "MIT" ]
3,629
2019-11-25T23:29:16.000Z
2022-03-31T21:52:28.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ================================================================================= // Code that works with liveness and related concepts (interference, debug scope) // ================================================================================= #include "jitpch.h" #ifdef _MSC_VER #pragma hdrstop #endif #if !defined(TARGET_64BIT) #include "decomposelongs.h" #endif #include "lower.h" // for LowerRange() /***************************************************************************** * * Helper for Compiler::fgPerBlockLocalVarLiveness(). * The goal is to compute the USE and DEF sets for a basic block. */ void Compiler::fgMarkUseDef(GenTreeLclVarCommon* tree) { assert((tree->OperIsLocal() && (tree->OperGet() != GT_PHI_ARG)) || tree->OperIsLocalAddr()); const unsigned lclNum = tree->GetLclNum(); LclVarDsc* const varDsc = lvaGetDesc(lclNum); // We should never encounter a reference to a lclVar that has a zero refCnt. if (varDsc->lvRefCnt() == 0 && (!varTypeIsPromotable(varDsc) || !varDsc->lvPromoted)) { JITDUMP("Found reference to V%02u with zero refCnt.\n", lclNum); assert(!"We should never encounter a reference to a lclVar that has a zero refCnt."); varDsc->setLvRefCnt(1); } const bool isDef = (tree->gtFlags & GTF_VAR_DEF) != 0; const bool isUse = !isDef || ((tree->gtFlags & GTF_VAR_USEASG) != 0); if (varDsc->lvTracked) { assert(varDsc->lvVarIndex < lvaTrackedCount); // We don't treat stores to tracked locals as modifications of ByrefExposed memory; // Make sure no tracked local is addr-exposed, to make sure we don't incorrectly CSE byref // loads aliasing it across a store to it. assert(!varDsc->IsAddressExposed()); if (compRationalIRForm && (varDsc->lvType != TYP_STRUCT) && !varTypeIsMultiReg(varDsc)) { // If this is an enregisterable variable that is not marked doNotEnregister, // we should only see direct references (not ADDRs). assert(varDsc->lvDoNotEnregister || tree->OperIs(GT_LCL_VAR, GT_STORE_LCL_VAR)); } if (isUse && !VarSetOps::IsMember(this, fgCurDefSet, varDsc->lvVarIndex)) { // This is an exposed use; add it to the set of uses. VarSetOps::AddElemD(this, fgCurUseSet, varDsc->lvVarIndex); } if (isDef) { // This is a def, add it to the set of defs. VarSetOps::AddElemD(this, fgCurDefSet, varDsc->lvVarIndex); } } else { if (varDsc->IsAddressExposed()) { // Reflect the effect on ByrefExposed memory if (isUse) { fgCurMemoryUse |= memoryKindSet(ByrefExposed); } if (isDef) { fgCurMemoryDef |= memoryKindSet(ByrefExposed); // We've found a store that modifies ByrefExposed // memory but not GcHeap memory, so track their // states separately. byrefStatesMatchGcHeapStates = false; } } if (varTypeIsStruct(varDsc)) { lvaPromotionType promotionType = lvaGetPromotionType(varDsc); if (promotionType != PROMOTION_TYPE_NONE) { VARSET_TP bitMask(VarSetOps::MakeEmpty(this)); for (unsigned i = varDsc->lvFieldLclStart; i < varDsc->lvFieldLclStart + varDsc->lvFieldCnt; ++i) { noway_assert(lvaTable[i].lvIsStructField); if (lvaTable[i].lvTracked) { noway_assert(lvaTable[i].lvVarIndex < lvaTrackedCount); VarSetOps::AddElemD(this, bitMask, lvaTable[i].lvVarIndex); } } // For pure defs (i.e. not an "update" def which is also a use), add to the (all) def set. if (!isUse) { assert(isDef); VarSetOps::UnionD(this, fgCurDefSet, bitMask); } else if (!VarSetOps::IsSubset(this, bitMask, fgCurDefSet)) { // Mark as used any struct fields that are not yet defined. VarSetOps::UnionD(this, fgCurUseSet, bitMask); } } } } } /*****************************************************************************/ void Compiler::fgLocalVarLiveness() { #ifdef DEBUG if (verbose) { printf("*************** In fgLocalVarLiveness()\n"); if (compRationalIRForm) { lvaTableDump(); } } #endif // DEBUG // Init liveness data structures. fgLocalVarLivenessInit(); EndPhase(PHASE_LCLVARLIVENESS_INIT); // Make sure we haven't noted any partial last uses of promoted structs. ClearPromotedStructDeathVars(); // Initialize the per-block var sets. fgInitBlockVarSets(); fgLocalVarLivenessChanged = false; do { /* Figure out use/def info for all basic blocks */ fgPerBlockLocalVarLiveness(); EndPhase(PHASE_LCLVARLIVENESS_PERBLOCK); /* Live variable analysis. */ fgStmtRemoved = false; fgInterBlockLocalVarLiveness(); } while (fgStmtRemoved && fgLocalVarLivenessChanged); EndPhase(PHASE_LCLVARLIVENESS_INTERBLOCK); } /*****************************************************************************/ void Compiler::fgLocalVarLivenessInit() { JITDUMP("In fgLocalVarLivenessInit\n"); // Sort locals first, if precise reference counts are required, e.g. we're optimizing if (PreciseRefCountsRequired()) { lvaSortByRefCount(); } // We mark a lcl as must-init in a first pass of local variable // liveness (Liveness1), then assertion prop eliminates the // uninit-use of a variable Vk, asserting it will be init'ed to // null. Then, in a second local-var liveness (Liveness2), the // variable Vk is no longer live on entry to the method, since its // uses have been replaced via constant propagation. // // This leads to a bug: since Vk is no longer live on entry, the // register allocator sees Vk and an argument Vj as having // disjoint lifetimes, and allocates them to the same register. // But Vk is still marked "must-init", and this initialization (of // the register) trashes the value in Vj. // // Therefore, initialize must-init to false for all variables in // each liveness phase. for (unsigned lclNum = 0; lclNum < lvaCount; ++lclNum) { lvaTable[lclNum].lvMustInit = false; } } //------------------------------------------------------------------------ // fgPerNodeLocalVarLiveness: // Set fgCurMemoryUse and fgCurMemoryDef when memory is read or updated // Call fgMarkUseDef for any Local variables encountered // // Arguments: // tree - The current node. // void Compiler::fgPerNodeLocalVarLiveness(GenTree* tree) { assert(tree != nullptr); switch (tree->gtOper) { case GT_QMARK: case GT_COLON: // We never should encounter a GT_QMARK or GT_COLON node noway_assert(!"unexpected GT_QMARK/GT_COLON"); break; case GT_LCL_VAR: case GT_LCL_FLD: case GT_LCL_VAR_ADDR: case GT_LCL_FLD_ADDR: case GT_STORE_LCL_VAR: case GT_STORE_LCL_FLD: fgMarkUseDef(tree->AsLclVarCommon()); break; case GT_CLS_VAR: // For Volatile indirection, first mutate GcHeap/ByrefExposed. // See comments in ValueNum.cpp (under case GT_CLS_VAR) // This models Volatile reads as def-then-use of memory // and allows for a CSE of a subsequent non-volatile read. if ((tree->gtFlags & GTF_FLD_VOLATILE) != 0) { // For any Volatile indirection, we must handle it as a // definition of GcHeap/ByrefExposed fgCurMemoryDef |= memoryKindSet(GcHeap, ByrefExposed); } // If the GT_CLS_VAR is the lhs of an assignment, we'll handle it as a GcHeap/ByrefExposed def, when we get // to the assignment. // Otherwise, we treat it as a use here. if ((tree->gtFlags & GTF_CLS_VAR_ASG_LHS) == 0) { fgCurMemoryUse |= memoryKindSet(GcHeap, ByrefExposed); } break; case GT_IND: // For Volatile indirection, first mutate GcHeap/ByrefExposed // see comments in ValueNum.cpp (under case GT_CLS_VAR) // This models Volatile reads as def-then-use of memory. // and allows for a CSE of a subsequent non-volatile read if ((tree->gtFlags & GTF_IND_VOLATILE) != 0) { // For any Volatile indirection, we must handle it as a // definition of the GcHeap/ByrefExposed fgCurMemoryDef |= memoryKindSet(GcHeap, ByrefExposed); } // If the GT_IND is the lhs of an assignment, we'll handle it // as a memory def, when we get to assignment. // Otherwise, we treat it as a use here. if ((tree->gtFlags & GTF_IND_ASG_LHS) == 0) { GenTreeLclVarCommon* dummyLclVarTree = nullptr; bool dummyIsEntire = false; GenTree* addrArg = tree->AsOp()->gtOp1->gtEffectiveVal(/*commaOnly*/ true); if (!addrArg->DefinesLocalAddr(this, /*width doesn't matter*/ 0, &dummyLclVarTree, &dummyIsEntire)) { fgCurMemoryUse |= memoryKindSet(GcHeap, ByrefExposed); } else { // Defines a local addr assert(dummyLclVarTree != nullptr); fgMarkUseDef(dummyLclVarTree->AsLclVarCommon()); } } break; // These should have been morphed away to become GT_INDs: case GT_FIELD: case GT_INDEX: unreached(); break; // We'll assume these are use-then-defs of memory. case GT_LOCKADD: case GT_XORR: case GT_XAND: case GT_XADD: case GT_XCHG: case GT_CMPXCHG: fgCurMemoryUse |= memoryKindSet(GcHeap, ByrefExposed); fgCurMemoryDef |= memoryKindSet(GcHeap, ByrefExposed); fgCurMemoryHavoc |= memoryKindSet(GcHeap, ByrefExposed); break; case GT_MEMORYBARRIER: // Simliar to any Volatile indirection, we must handle this as a definition of GcHeap/ByrefExposed fgCurMemoryDef |= memoryKindSet(GcHeap, ByrefExposed); break; #ifdef FEATURE_SIMD case GT_SIMD: { GenTreeSIMD* simdNode = tree->AsSIMD(); if (simdNode->OperIsMemoryLoad()) { // This instruction loads from memory and we need to record this information fgCurMemoryUse |= memoryKindSet(GcHeap, ByrefExposed); } break; } #endif // FEATURE_SIMD #ifdef FEATURE_HW_INTRINSICS case GT_HWINTRINSIC: { GenTreeHWIntrinsic* hwIntrinsicNode = tree->AsHWIntrinsic(); // We can't call fgMutateGcHeap unless the block has recorded a MemoryDef // if (hwIntrinsicNode->OperIsMemoryStore()) { // We currently handle this like a Volatile store, so it counts as a definition of GcHeap/ByrefExposed fgCurMemoryDef |= memoryKindSet(GcHeap, ByrefExposed); } if (hwIntrinsicNode->OperIsMemoryLoad()) { // This instruction loads from memory and we need to record this information fgCurMemoryUse |= memoryKindSet(GcHeap, ByrefExposed); } break; } #endif // FEATURE_HW_INTRINSICS // For now, all calls read/write GcHeap/ByrefExposed, writes in their entirety. Might tighten this case later. case GT_CALL: { GenTreeCall* call = tree->AsCall(); bool modHeap = true; if (call->gtCallType == CT_HELPER) { CorInfoHelpFunc helpFunc = eeGetHelperNum(call->gtCallMethHnd); if (!s_helperCallProperties.MutatesHeap(helpFunc) && !s_helperCallProperties.MayRunCctor(helpFunc)) { modHeap = false; } } if (modHeap) { fgCurMemoryUse |= memoryKindSet(GcHeap, ByrefExposed); fgCurMemoryDef |= memoryKindSet(GcHeap, ByrefExposed); fgCurMemoryHavoc |= memoryKindSet(GcHeap, ByrefExposed); } // If this is a p/invoke unmanaged call or if this is a tail-call via helper, // and we have an unmanaged p/invoke call in the method, // then we're going to run the p/invoke epilog. // So we mark the FrameRoot as used by this instruction. // This ensures that the block->bbVarUse will contain // the FrameRoot local var if is it a tracked variable. if ((call->IsUnmanaged() || call->IsTailCallViaJitHelper()) && compMethodRequiresPInvokeFrame()) { assert((!opts.ShouldUsePInvokeHelpers()) || (info.compLvFrameListRoot == BAD_VAR_NUM)); if (!opts.ShouldUsePInvokeHelpers() && !call->IsSuppressGCTransition()) { // Get the FrameRoot local and mark it as used. LclVarDsc* varDsc = lvaGetDesc(info.compLvFrameListRoot); if (varDsc->lvTracked) { if (!VarSetOps::IsMember(this, fgCurDefSet, varDsc->lvVarIndex)) { VarSetOps::AddElemD(this, fgCurUseSet, varDsc->lvVarIndex); } } } } break; } default: // Determine what memory locations it defines. if (tree->OperIs(GT_ASG) || tree->OperIsBlkOp()) { GenTreeLclVarCommon* dummyLclVarTree = nullptr; if (tree->DefinesLocal(this, &dummyLclVarTree)) { if (lvaVarAddrExposed(dummyLclVarTree->GetLclNum())) { fgCurMemoryDef |= memoryKindSet(ByrefExposed); // We've found a store that modifies ByrefExposed // memory but not GcHeap memory, so track their // states separately. byrefStatesMatchGcHeapStates = false; } } else { // If it doesn't define a local, then it might update GcHeap/ByrefExposed. fgCurMemoryDef |= memoryKindSet(GcHeap, ByrefExposed); } } break; } } /*****************************************************************************/ void Compiler::fgPerBlockLocalVarLiveness() { #ifdef DEBUG if (verbose) { printf("*************** In fgPerBlockLocalVarLiveness()\n"); } #endif // DEBUG unsigned livenessVarEpoch = GetCurLVEpoch(); BasicBlock* block; // If we don't require accurate local var lifetimes, things are simple. if (!backendRequiresLocalVarLifetimes()) { unsigned lclNum; LclVarDsc* varDsc; VARSET_TP liveAll(VarSetOps::MakeEmpty(this)); /* We simply make everything live everywhere */ for (lclNum = 0, varDsc = lvaTable; lclNum < lvaCount; lclNum++, varDsc++) { if (varDsc->lvTracked) { VarSetOps::AddElemD(this, liveAll, varDsc->lvVarIndex); } } for (block = fgFirstBB; block; block = block->bbNext) { // Strictly speaking, the assignments for the "Def" cases aren't necessary here. // The empty set would do as well. Use means "use-before-def", so as long as that's // "all", this has the right effect. VarSetOps::Assign(this, block->bbVarUse, liveAll); VarSetOps::Assign(this, block->bbVarDef, liveAll); VarSetOps::Assign(this, block->bbLiveIn, liveAll); block->bbMemoryUse = fullMemoryKindSet; block->bbMemoryDef = fullMemoryKindSet; block->bbMemoryLiveIn = fullMemoryKindSet; block->bbMemoryLiveOut = fullMemoryKindSet; switch (block->bbJumpKind) { case BBJ_EHFINALLYRET: case BBJ_THROW: case BBJ_RETURN: VarSetOps::AssignNoCopy(this, block->bbLiveOut, VarSetOps::MakeEmpty(this)); break; default: VarSetOps::Assign(this, block->bbLiveOut, liveAll); break; } } // In minopts, we don't explicitly build SSA or value-number; GcHeap and // ByrefExposed implicitly (conservatively) change state at each instr. byrefStatesMatchGcHeapStates = true; return; } // Avoid allocations in the long case. VarSetOps::AssignNoCopy(this, fgCurUseSet, VarSetOps::MakeEmpty(this)); VarSetOps::AssignNoCopy(this, fgCurDefSet, VarSetOps::MakeEmpty(this)); // GC Heap and ByrefExposed can share states unless we see a def of byref-exposed // memory that is not a GC Heap def. byrefStatesMatchGcHeapStates = true; for (block = fgFirstBB; block; block = block->bbNext) { VarSetOps::ClearD(this, fgCurUseSet); VarSetOps::ClearD(this, fgCurDefSet); fgCurMemoryUse = emptyMemoryKindSet; fgCurMemoryDef = emptyMemoryKindSet; fgCurMemoryHavoc = emptyMemoryKindSet; compCurBB = block; if (block->IsLIR()) { for (GenTree* node : LIR::AsRange(block)) { fgPerNodeLocalVarLiveness(node); } } else { for (Statement* const stmt : block->NonPhiStatements()) { compCurStmt = stmt; for (GenTree* const node : stmt->TreeList()) { fgPerNodeLocalVarLiveness(node); } } } // Mark the FrameListRoot as used, if applicable. if (block->bbJumpKind == BBJ_RETURN && compMethodRequiresPInvokeFrame()) { assert((!opts.ShouldUsePInvokeHelpers()) || (info.compLvFrameListRoot == BAD_VAR_NUM)); if (!opts.ShouldUsePInvokeHelpers()) { // 32-bit targets always pop the frame in the epilog. // For 64-bit targets, we only do this in the epilog for IL stubs; // for non-IL stubs the frame is popped after every PInvoke call. CLANG_FORMAT_COMMENT_ANCHOR; #ifdef TARGET_64BIT if (opts.jitFlags->IsSet(JitFlags::JIT_FLAG_IL_STUB)) #endif { LclVarDsc* varDsc = lvaGetDesc(info.compLvFrameListRoot); if (varDsc->lvTracked) { if (!VarSetOps::IsMember(this, fgCurDefSet, varDsc->lvVarIndex)) { VarSetOps::AddElemD(this, fgCurUseSet, varDsc->lvVarIndex); } } } } } #ifdef DEBUG if (verbose) { VARSET_TP allVars(VarSetOps::Union(this, fgCurUseSet, fgCurDefSet)); printf(FMT_BB, block->bbNum); printf(" USE(%d)=", VarSetOps::Count(this, fgCurUseSet)); lvaDispVarSet(fgCurUseSet, allVars); for (MemoryKind memoryKind : allMemoryKinds()) { if ((fgCurMemoryUse & memoryKindSet(memoryKind)) != 0) { printf(" + %s", memoryKindNames[memoryKind]); } } printf("\n DEF(%d)=", VarSetOps::Count(this, fgCurDefSet)); lvaDispVarSet(fgCurDefSet, allVars); for (MemoryKind memoryKind : allMemoryKinds()) { if ((fgCurMemoryDef & memoryKindSet(memoryKind)) != 0) { printf(" + %s", memoryKindNames[memoryKind]); } if ((fgCurMemoryHavoc & memoryKindSet(memoryKind)) != 0) { printf("*"); } } printf("\n\n"); } #endif // DEBUG VarSetOps::Assign(this, block->bbVarUse, fgCurUseSet); VarSetOps::Assign(this, block->bbVarDef, fgCurDefSet); block->bbMemoryUse = fgCurMemoryUse; block->bbMemoryDef = fgCurMemoryDef; block->bbMemoryHavoc = fgCurMemoryHavoc; /* also initialize the IN set, just in case we will do multiple DFAs */ VarSetOps::AssignNoCopy(this, block->bbLiveIn, VarSetOps::MakeEmpty(this)); block->bbMemoryLiveIn = emptyMemoryKindSet; } noway_assert(livenessVarEpoch == GetCurLVEpoch()); #ifdef DEBUG if (verbose) { printf("** Memory liveness computed, GcHeap states and ByrefExposed states %s\n", (byrefStatesMatchGcHeapStates ? "match" : "diverge")); } #endif // DEBUG } // Helper functions to mark variables live over their entire scope void Compiler::fgBeginScopeLife(VARSET_TP* inScope, VarScopeDsc* var) { assert(var); LclVarDsc* lclVarDsc1 = lvaGetDesc(var->vsdVarNum); if (lclVarDsc1->lvTracked) { VarSetOps::AddElemD(this, *inScope, lclVarDsc1->lvVarIndex); } } void Compiler::fgEndScopeLife(VARSET_TP* inScope, VarScopeDsc* var) { assert(var); LclVarDsc* lclVarDsc1 = lvaGetDesc(var->vsdVarNum); if (lclVarDsc1->lvTracked) { VarSetOps::RemoveElemD(this, *inScope, lclVarDsc1->lvVarIndex); } } /*****************************************************************************/ void Compiler::fgMarkInScope(BasicBlock* block, VARSET_VALARG_TP inScope) { #ifdef DEBUG if (verbose) { printf("Scope info: block " FMT_BB " marking in scope: ", block->bbNum); dumpConvertedVarSet(this, inScope); printf("\n"); } #endif // DEBUG /* Record which vars are artifically kept alive for debugging */ VarSetOps::Assign(this, block->bbScope, inScope); /* Being in scope implies a use of the variable. Add the var to bbVarUse so that redoing fgLiveVarAnalysis() will work correctly */ VarSetOps::UnionD(this, block->bbVarUse, inScope); /* Artifically mark all vars in scope as alive */ VarSetOps::UnionD(this, block->bbLiveIn, inScope); VarSetOps::UnionD(this, block->bbLiveOut, inScope); } void Compiler::fgUnmarkInScope(BasicBlock* block, VARSET_VALARG_TP unmarkScope) { #ifdef DEBUG if (verbose) { printf("Scope info: block " FMT_BB " UNmarking in scope: ", block->bbNum); dumpConvertedVarSet(this, unmarkScope); printf("\n"); } #endif // DEBUG assert(VarSetOps::IsSubset(this, unmarkScope, block->bbScope)); VarSetOps::DiffD(this, block->bbScope, unmarkScope); VarSetOps::DiffD(this, block->bbVarUse, unmarkScope); VarSetOps::DiffD(this, block->bbLiveIn, unmarkScope); VarSetOps::DiffD(this, block->bbLiveOut, unmarkScope); } #ifdef DEBUG void Compiler::fgDispDebugScopes() { printf("\nDebug scopes:\n"); for (BasicBlock* const block : Blocks()) { printf(FMT_BB ": ", block->bbNum); dumpConvertedVarSet(this, block->bbScope); printf("\n"); } } #endif // DEBUG /***************************************************************************** * * Mark variables live across their entire scope. */ #if defined(FEATURE_EH_FUNCLETS) void Compiler::fgExtendDbgScopes() { compResetScopeLists(); #ifdef DEBUG if (verbose) { printf("\nMarking vars alive over their entire scope :\n\n"); } if (verbose) { compDispScopeLists(); } #endif // DEBUG VARSET_TP inScope(VarSetOps::MakeEmpty(this)); // Mark all tracked LocalVars live over their scope - walk the blocks // keeping track of the current life, and assign it to the blocks. for (BasicBlock* const block : Blocks()) { // If we get to a funclet, reset the scope lists and start again, since the block // offsets will be out of order compared to the previous block. if (block->bbFlags & BBF_FUNCLET_BEG) { compResetScopeLists(); VarSetOps::ClearD(this, inScope); } // Process all scopes up to the current offset if (block->bbCodeOffs != BAD_IL_OFFSET) { compProcessScopesUntil(block->bbCodeOffs, &inScope, &Compiler::fgBeginScopeLife, &Compiler::fgEndScopeLife); } // Assign the current set of variables that are in scope to the block variables tracking this. fgMarkInScope(block, inScope); } #ifdef DEBUG if (verbose) { fgDispDebugScopes(); } #endif // DEBUG } #else // !FEATURE_EH_FUNCLETS void Compiler::fgExtendDbgScopes() { compResetScopeLists(); #ifdef DEBUG if (verbose) { printf("\nMarking vars alive over their entire scope :\n\n"); compDispScopeLists(); } #endif // DEBUG VARSET_TP inScope(VarSetOps::MakeEmpty(this)); compProcessScopesUntil(0, &inScope, &Compiler::fgBeginScopeLife, &Compiler::fgEndScopeLife); IL_OFFSET lastEndOffs = 0; // Mark all tracked LocalVars live over their scope - walk the blocks // keeping track of the current life, and assign it to the blocks. for (BasicBlock* const block : Blocks()) { // Find scopes becoming alive. If there is a gap in the instr // sequence, we need to process any scopes on those missing offsets. if (block->bbCodeOffs != BAD_IL_OFFSET) { if (lastEndOffs != block->bbCodeOffs) { noway_assert(lastEndOffs < block->bbCodeOffs); compProcessScopesUntil(block->bbCodeOffs, &inScope, &Compiler::fgBeginScopeLife, &Compiler::fgEndScopeLife); } else { while (VarScopeDsc* varScope = compGetNextEnterScope(block->bbCodeOffs)) { fgBeginScopeLife(&inScope, varScope); } } } // Assign the current set of variables that are in scope to the block variables tracking this. fgMarkInScope(block, inScope); // Find scopes going dead. if (block->bbCodeOffsEnd != BAD_IL_OFFSET) { VarScopeDsc* varScope; while ((varScope = compGetNextExitScope(block->bbCodeOffsEnd)) != nullptr) { fgEndScopeLife(&inScope, varScope); } lastEndOffs = block->bbCodeOffsEnd; } } /* Everything should be out of scope by the end of the method. But if the last BB got removed, then inScope may not be empty. */ noway_assert(VarSetOps::IsEmpty(this, inScope) || lastEndOffs < info.compILCodeSize); } #endif // !FEATURE_EH_FUNCLETS /***************************************************************************** * * For debuggable code, we allow redundant assignments to vars * by marking them live over their entire scope. */ void Compiler::fgExtendDbgLifetimes() { #ifdef DEBUG if (verbose) { printf("*************** In fgExtendDbgLifetimes()\n"); } #endif // DEBUG noway_assert(opts.compDbgCode && (info.compVarScopesCount > 0)); /*------------------------------------------------------------------------- * Extend the lifetimes over the entire reported scope of the variable. */ fgExtendDbgScopes(); /*------------------------------------------------------------------------- * Partly update liveness info so that we handle any funky BBF_INTERNAL * blocks inserted out of sequence. */ #ifdef DEBUG if (verbose && 0) { fgDispBBLiveness(); } #endif fgLiveVarAnalysis(true); /* For compDbgCode, we prepend an empty BB which will hold the initializations of variables which are in scope at IL offset 0 (but not initialized by the IL code). Since they will currently be marked as live on entry to fgFirstBB, unmark the liveness so that the following code will know to add the initializations. */ assert(fgFirstBBisScratch()); VARSET_TP trackedArgs(VarSetOps::MakeEmpty(this)); for (unsigned argNum = 0; argNum < info.compArgsCount; argNum++) { LclVarDsc* argDsc = lvaGetDesc(argNum); if (argDsc->lvPromoted) { lvaPromotionType promotionType = lvaGetPromotionType(argDsc); if (promotionType == PROMOTION_TYPE_INDEPENDENT) { noway_assert(argDsc->lvFieldCnt == 1); // We only handle one field here unsigned fieldVarNum = argDsc->lvFieldLclStart; argDsc = lvaGetDesc(fieldVarNum); } } noway_assert(argDsc->lvIsParam); if (argDsc->lvTracked) { noway_assert(!VarSetOps::IsMember(this, trackedArgs, argDsc->lvVarIndex)); // Each arg should define a // different bit. VarSetOps::AddElemD(this, trackedArgs, argDsc->lvVarIndex); } } // Don't unmark struct locals, either. VARSET_TP noUnmarkVars(trackedArgs); for (unsigned i = 0; i < lvaCount; i++) { LclVarDsc* varDsc = lvaGetDesc(i); if (varTypeIsStruct(varDsc) && varDsc->lvTracked) { VarSetOps::AddElemD(this, noUnmarkVars, varDsc->lvVarIndex); } } fgUnmarkInScope(fgFirstBB, VarSetOps::Diff(this, fgFirstBB->bbScope, noUnmarkVars)); /*------------------------------------------------------------------------- * As we keep variables artifically alive over their entire scope, * we need to also artificially initialize them if the scope does * not exactly match the real lifetimes, or they will contain * garbage until they are initialized by the IL code. */ VARSET_TP initVars(VarSetOps::MakeEmpty(this)); // Vars which are artificially made alive for (BasicBlock* const block : Blocks()) { VarSetOps::ClearD(this, initVars); switch (block->bbJumpKind) { case BBJ_NONE: PREFIX_ASSUME(block->bbNext != nullptr); VarSetOps::UnionD(this, initVars, block->bbNext->bbScope); break; case BBJ_ALWAYS: case BBJ_EHCATCHRET: case BBJ_EHFILTERRET: VarSetOps::UnionD(this, initVars, block->bbJumpDest->bbScope); break; case BBJ_CALLFINALLY: if (!(block->bbFlags & BBF_RETLESS_CALL)) { assert(block->isBBCallAlwaysPair()); PREFIX_ASSUME(block->bbNext != nullptr); VarSetOps::UnionD(this, initVars, block->bbNext->bbScope); } VarSetOps::UnionD(this, initVars, block->bbJumpDest->bbScope); break; case BBJ_COND: PREFIX_ASSUME(block->bbNext != nullptr); VarSetOps::UnionD(this, initVars, block->bbNext->bbScope); VarSetOps::UnionD(this, initVars, block->bbJumpDest->bbScope); break; case BBJ_SWITCH: for (BasicBlock* const bTarget : block->SwitchTargets()) { VarSetOps::UnionD(this, initVars, bTarget->bbScope); } break; case BBJ_EHFINALLYRET: case BBJ_RETURN: break; case BBJ_THROW: /* We don't have to do anything as we mark * all vars live on entry to a catch handler as * volatile anyway */ break; default: noway_assert(!"Unexpected bbJumpKind"); break; } /* If the var is already live on entry to the current BB, we would have already initialized it. So ignore bbLiveIn */ VarSetOps::DiffD(this, initVars, block->bbLiveIn); /* Add statements initializing the vars, if there are any to initialize */ VarSetOps::Iter iter(this, initVars); unsigned varIndex = 0; while (iter.NextElem(&varIndex)) { /* Create initialization tree */ unsigned varNum = lvaTrackedIndexToLclNum(varIndex); LclVarDsc* varDsc = lvaGetDesc(varNum); var_types type = varDsc->TypeGet(); // Don't extend struct lifetimes -- they aren't enregistered, anyway. if (type == TYP_STRUCT) { continue; } // If we haven't already done this ... if (!fgLocalVarLivenessDone) { // Create a "zero" node GenTree* zero = gtNewZeroConNode(genActualType(type)); // Create initialization node if (!block->IsLIR()) { GenTree* varNode = gtNewLclvNode(varNum, type); GenTree* initNode = gtNewAssignNode(varNode, zero); // Create a statement for the initializer, sequence it, and append it to the current BB. Statement* initStmt = gtNewStmt(initNode); gtSetStmtInfo(initStmt); fgSetStmtSeq(initStmt); fgInsertStmtNearEnd(block, initStmt); } else { GenTree* store = new (this, GT_STORE_LCL_VAR) GenTreeLclVar(GT_STORE_LCL_VAR, type, varNum); store->AsOp()->gtOp1 = zero; store->gtFlags |= (GTF_VAR_DEF | GTF_ASG); LIR::Range initRange = LIR::EmptyRange(); initRange.InsertBefore(nullptr, zero, store); #if !defined(TARGET_64BIT) DecomposeLongs::DecomposeRange(this, initRange); #endif // !defined(TARGET_64BIT) m_pLowering->LowerRange(block, initRange); // Naively inserting the initializer at the end of the block may add code after the block's // terminator, in which case the inserted code will never be executed (and the IR for the // block will be invalid). Use `LIR::InsertBeforeTerminator` to avoid this problem. LIR::InsertBeforeTerminator(block, std::move(initRange)); } #ifdef DEBUG if (verbose) { printf("Created zero-init of V%02u in " FMT_BB "\n", varNum, block->bbNum); } #endif // DEBUG block->bbFlags |= BBF_CHANGED; // indicates that the contents of the block have changed. } /* Update liveness information so that redoing fgLiveVarAnalysis() will work correctly if needed */ VarSetOps::AddElemD(this, block->bbVarDef, varIndex); VarSetOps::AddElemD(this, block->bbLiveOut, varIndex); } } // raMarkStkVars() reserves stack space for unused variables (which // needs to be initialized). However, arguments don't need to be initialized. // So just ensure that they don't have a 0 ref cnt unsigned lclNum = 0; for (LclVarDsc *varDsc = lvaTable; lclNum < lvaCount; lclNum++, varDsc++) { if (lclNum >= info.compArgsCount) { break; // early exit for loop } if (varDsc->lvIsRegArg) { varDsc->lvImplicitlyReferenced = true; } } #ifdef DEBUG if (verbose) { printf("\nBB liveness after fgExtendDbgLifetimes():\n\n"); fgDispBBLiveness(); printf("\n"); } #endif // DEBUG } //------------------------------------------------------------------------ // fgGetHandlerLiveVars: determine set of locals live because of implicit // exception flow from a block. // // Arguments: // block - the block in question // // Returns: // Additional set of locals to be considered live throughout the block. // // Notes: // Assumes caller has screened candidate blocks to only those with // exception flow, via `ehBlockHasExnFlowDsc`. // // Exception flow can arise because of a newly raised exception (for // blocks within try regions) or because of an actively propagating exception // (for filter blocks). This flow effectively creates additional successor // edges in the flow graph that the jit does not model. This method computes // the net contribution from all the missing successor edges. // // For example, with the following C# source, during EH processing of the throw, // the outer filter will execute in pass1, before the inner handler executes // in pass2, and so the filter blocks should show the inner handler's local is live. // // try // { // using (AllocateObject()) // ==> try-finally; handler calls Dispose // { // throw new Exception(); // } // } // catch (Exception e1) when (IsExpectedException(e1)) // { // Console.WriteLine("In catch 1"); // } VARSET_VALRET_TP Compiler::fgGetHandlerLiveVars(BasicBlock* block) { noway_assert(block); noway_assert(ehBlockHasExnFlowDsc(block)); VARSET_TP liveVars(VarSetOps::MakeEmpty(this)); EHblkDsc* HBtab = ehGetBlockExnFlowDsc(block); do { /* Either we enter the filter first or the catch/finally */ if (HBtab->HasFilter()) { VarSetOps::UnionD(this, liveVars, HBtab->ebdFilter->bbLiveIn); #if defined(FEATURE_EH_FUNCLETS) // The EH subsystem can trigger a stack walk after the filter // has returned, but before invoking the handler, and the only // IP address reported from this method will be the original // faulting instruction, thus everything in the try body // must report as live any variables live-out of the filter // (which is the same as those live-in to the handler) VarSetOps::UnionD(this, liveVars, HBtab->ebdHndBeg->bbLiveIn); #endif // FEATURE_EH_FUNCLETS } else { VarSetOps::UnionD(this, liveVars, HBtab->ebdHndBeg->bbLiveIn); } /* If we have nested try's edbEnclosing will provide them */ noway_assert((HBtab->ebdEnclosingTryIndex == EHblkDsc::NO_ENCLOSING_INDEX) || (HBtab->ebdEnclosingTryIndex > ehGetIndex(HBtab))); unsigned outerIndex = HBtab->ebdEnclosingTryIndex; if (outerIndex == EHblkDsc::NO_ENCLOSING_INDEX) { break; } HBtab = ehGetDsc(outerIndex); } while (true); // If this block is within a filter, we also need to report as live // any vars live into enclosed finally or fault handlers, since the // filter will run during the first EH pass, and enclosed or enclosing // handlers will run during the second EH pass. So all these handlers // are "exception flow" successors of the filter. // // Note we are relying on ehBlockHasExnFlowDsc to return true // for any filter block that we should examine here. if (block->hasHndIndex()) { const unsigned thisHndIndex = block->getHndIndex(); EHblkDsc* enclosingHBtab = ehGetDsc(thisHndIndex); if (enclosingHBtab->InFilterRegionBBRange(block)) { assert(enclosingHBtab->HasFilter()); // Search the EH table for enclosed regions. // // All the enclosed regions will be lower numbered and // immediately prior to and contiguous with the enclosing // region in the EH tab. unsigned index = thisHndIndex; while (index > 0) { index--; unsigned enclosingIndex = ehGetEnclosingTryIndex(index); bool isEnclosed = false; // To verify this is an enclosed region, search up // through the enclosing regions until we find the // region associated with the filter. while (enclosingIndex != EHblkDsc::NO_ENCLOSING_INDEX) { if (enclosingIndex == thisHndIndex) { isEnclosed = true; break; } enclosingIndex = ehGetEnclosingTryIndex(enclosingIndex); } // If we found an enclosed region, check if the region // is a try fault or try finally, and if so, add any // locals live into the enclosed region's handler into this // block's live-in set. if (isEnclosed) { EHblkDsc* enclosedHBtab = ehGetDsc(index); if (enclosedHBtab->HasFinallyOrFaultHandler()) { VarSetOps::UnionD(this, liveVars, enclosedHBtab->ebdHndBeg->bbLiveIn); } } // Once we run across a non-enclosed region, we can stop searching. else { break; } } } } return liveVars; } class LiveVarAnalysis { Compiler* m_compiler; bool m_hasPossibleBackEdge; unsigned m_memoryLiveIn; unsigned m_memoryLiveOut; VARSET_TP m_liveIn; VARSET_TP m_liveOut; LiveVarAnalysis(Compiler* compiler) : m_compiler(compiler) , m_hasPossibleBackEdge(false) , m_memoryLiveIn(emptyMemoryKindSet) , m_memoryLiveOut(emptyMemoryKindSet) , m_liveIn(VarSetOps::MakeEmpty(compiler)) , m_liveOut(VarSetOps::MakeEmpty(compiler)) { } bool PerBlockAnalysis(BasicBlock* block, bool updateInternalOnly, bool keepAliveThis) { /* Compute the 'liveOut' set */ VarSetOps::ClearD(m_compiler, m_liveOut); m_memoryLiveOut = emptyMemoryKindSet; if (block->endsWithJmpMethod(m_compiler)) { // A JMP uses all the arguments, so mark them all // as live at the JMP instruction // const LclVarDsc* varDscEndParams = m_compiler->lvaTable + m_compiler->info.compArgsCount; for (LclVarDsc* varDsc = m_compiler->lvaTable; varDsc < varDscEndParams; varDsc++) { noway_assert(!varDsc->lvPromoted); if (varDsc->lvTracked) { VarSetOps::AddElemD(m_compiler, m_liveOut, varDsc->lvVarIndex); } } } // Additionally, union in all the live-in tracked vars of successors. for (BasicBlock* succ : block->GetAllSuccs(m_compiler)) { VarSetOps::UnionD(m_compiler, m_liveOut, succ->bbLiveIn); m_memoryLiveOut |= succ->bbMemoryLiveIn; if (succ->bbNum <= block->bbNum) { m_hasPossibleBackEdge = true; } } /* For lvaKeepAliveAndReportThis methods, "this" has to be kept alive everywhere Note that a function may end in a throw on an infinite loop (as opposed to a return). "this" has to be alive everywhere even in such methods. */ if (keepAliveThis) { VarSetOps::AddElemD(m_compiler, m_liveOut, m_compiler->lvaTable[m_compiler->info.compThisArg].lvVarIndex); } /* Compute the 'm_liveIn' set */ VarSetOps::LivenessD(m_compiler, m_liveIn, block->bbVarDef, block->bbVarUse, m_liveOut); // Even if block->bbMemoryDef is set, we must assume that it doesn't kill memory liveness from m_memoryLiveOut, // since (without proof otherwise) the use and def may touch different memory at run-time. m_memoryLiveIn = m_memoryLiveOut | block->bbMemoryUse; // Does this block have implicit exception flow to a filter or handler? // If so, include the effects of that flow. if (m_compiler->ehBlockHasExnFlowDsc(block)) { const VARSET_TP& liveVars(m_compiler->fgGetHandlerLiveVars(block)); VarSetOps::UnionD(m_compiler, m_liveIn, liveVars); VarSetOps::UnionD(m_compiler, m_liveOut, liveVars); // Implicit eh edges can induce loop-like behavior, // so make sure we iterate to closure. m_hasPossibleBackEdge = true; } /* Has there been any change in either live set? */ bool liveInChanged = !VarSetOps::Equal(m_compiler, block->bbLiveIn, m_liveIn); if (liveInChanged || !VarSetOps::Equal(m_compiler, block->bbLiveOut, m_liveOut)) { if (updateInternalOnly) { // Only "extend" liveness over BBF_INTERNAL blocks noway_assert(block->bbFlags & BBF_INTERNAL); liveInChanged = !VarSetOps::IsSubset(m_compiler, m_liveIn, block->bbLiveIn); if (liveInChanged || !VarSetOps::IsSubset(m_compiler, m_liveOut, block->bbLiveOut)) { #ifdef DEBUG if (m_compiler->verbose) { printf("Scope info: block " FMT_BB " LiveIn+ ", block->bbNum); dumpConvertedVarSet(m_compiler, VarSetOps::Diff(m_compiler, m_liveIn, block->bbLiveIn)); printf(", LiveOut+ "); dumpConvertedVarSet(m_compiler, VarSetOps::Diff(m_compiler, m_liveOut, block->bbLiveOut)); printf("\n"); } #endif // DEBUG VarSetOps::UnionD(m_compiler, block->bbLiveIn, m_liveIn); VarSetOps::UnionD(m_compiler, block->bbLiveOut, m_liveOut); } } else { VarSetOps::Assign(m_compiler, block->bbLiveIn, m_liveIn); VarSetOps::Assign(m_compiler, block->bbLiveOut, m_liveOut); } } const bool memoryLiveInChanged = (block->bbMemoryLiveIn != m_memoryLiveIn); if (memoryLiveInChanged || (block->bbMemoryLiveOut != m_memoryLiveOut)) { block->bbMemoryLiveIn = m_memoryLiveIn; block->bbMemoryLiveOut = m_memoryLiveOut; } return liveInChanged || memoryLiveInChanged; } void Run(bool updateInternalOnly) { const bool keepAliveThis = m_compiler->lvaKeepAliveAndReportThis() && m_compiler->lvaTable[m_compiler->info.compThisArg].lvTracked; /* Live Variable Analysis - Backward dataflow */ bool changed; do { changed = false; /* Visit all blocks and compute new data flow values */ VarSetOps::ClearD(m_compiler, m_liveIn); VarSetOps::ClearD(m_compiler, m_liveOut); m_memoryLiveIn = emptyMemoryKindSet; m_memoryLiveOut = emptyMemoryKindSet; for (BasicBlock* block = m_compiler->fgLastBB; block; block = block->bbPrev) { // sometimes block numbers are not monotonically increasing which // would cause us not to identify backedges if (block->bbNext && block->bbNext->bbNum <= block->bbNum) { m_hasPossibleBackEdge = true; } if (updateInternalOnly) { /* Only update BBF_INTERNAL blocks as they may be syntactically out of sequence. */ noway_assert(m_compiler->opts.compDbgCode && (m_compiler->info.compVarScopesCount > 0)); if (!(block->bbFlags & BBF_INTERNAL)) { continue; } } if (PerBlockAnalysis(block, updateInternalOnly, keepAliveThis)) { changed = true; } } // if there is no way we could have processed a block without seeing all of its predecessors // then there is no need to iterate if (!m_hasPossibleBackEdge) { break; } } while (changed); } public: static void Run(Compiler* compiler, bool updateInternalOnly) { LiveVarAnalysis analysis(compiler); analysis.Run(updateInternalOnly); } }; /***************************************************************************** * * This is the classic algorithm for Live Variable Analysis. * If updateInternalOnly==true, only update BBF_INTERNAL blocks. */ void Compiler::fgLiveVarAnalysis(bool updateInternalOnly) { if (!backendRequiresLocalVarLifetimes()) { return; } LiveVarAnalysis::Run(this, updateInternalOnly); #ifdef DEBUG if (verbose && !updateInternalOnly) { printf("\nBB liveness after fgLiveVarAnalysis():\n\n"); fgDispBBLiveness(); } #endif // DEBUG } //------------------------------------------------------------------------ // Compiler::fgComputeLifeCall: compute the changes to local var liveness // due to a GT_CALL node. // // Arguments: // life - The live set that is being computed. // call - The call node in question. // void Compiler::fgComputeLifeCall(VARSET_TP& life, GenTreeCall* call) { assert(call != nullptr); // If this is a tail-call via helper, and we have any unmanaged p/invoke calls in // the method, then we're going to run the p/invoke epilog // So we mark the FrameRoot as used by this instruction. // This ensure that this variable is kept alive at the tail-call if (call->IsTailCallViaJitHelper() && compMethodRequiresPInvokeFrame()) { assert((!opts.ShouldUsePInvokeHelpers()) || (info.compLvFrameListRoot == BAD_VAR_NUM)); if (!opts.ShouldUsePInvokeHelpers()) { // Get the FrameListRoot local and make it live. LclVarDsc* frameVarDsc = lvaGetDesc(info.compLvFrameListRoot); if (frameVarDsc->lvTracked) { VarSetOps::AddElemD(this, life, frameVarDsc->lvVarIndex); } } } // TODO: we should generate the code for saving to/restoring // from the inlined N/Direct frame instead. /* Is this call to unmanaged code? */ if (call->IsUnmanaged() && compMethodRequiresPInvokeFrame()) { // Get the FrameListRoot local and make it live. assert((!opts.ShouldUsePInvokeHelpers()) || (info.compLvFrameListRoot == BAD_VAR_NUM)); if (!opts.ShouldUsePInvokeHelpers() && !call->IsSuppressGCTransition()) { LclVarDsc* frameVarDsc = lvaGetDesc(info.compLvFrameListRoot); if (frameVarDsc->lvTracked) { unsigned varIndex = frameVarDsc->lvVarIndex; noway_assert(varIndex < lvaTrackedCount); // Is the variable already known to be alive? // if (VarSetOps::IsMember(this, life, varIndex)) { // Since we may call this multiple times, clear the GTF_CALL_M_FRAME_VAR_DEATH if set. // call->gtCallMoreFlags &= ~GTF_CALL_M_FRAME_VAR_DEATH; } else { // The variable is just coming to life // Since this is a backwards walk of the trees // that makes this change in liveness a 'last-use' // VarSetOps::AddElemD(this, life, varIndex); call->gtCallMoreFlags |= GTF_CALL_M_FRAME_VAR_DEATH; } } } } } //------------------------------------------------------------------------ // Compiler::fgComputeLifeTrackedLocalUse: // Compute the changes to local var liveness due to a use of a tracked local var. // // Arguments: // life - The live set that is being computed. // varDsc - The LclVar descriptor for the variable being used or defined. // node - The node that is defining the lclVar. void Compiler::fgComputeLifeTrackedLocalUse(VARSET_TP& life, LclVarDsc& varDsc, GenTreeLclVarCommon* node) { assert(node != nullptr); assert((node->gtFlags & GTF_VAR_DEF) == 0); assert(varDsc.lvTracked); const unsigned varIndex = varDsc.lvVarIndex; // Is the variable already known to be alive? if (VarSetOps::IsMember(this, life, varIndex)) { // Since we may do liveness analysis multiple times, clear the GTF_VAR_DEATH if set. node->gtFlags &= ~GTF_VAR_DEATH; return; } #ifdef DEBUG if (verbose && 0) { printf("Ref V%02u,T%02u] at ", node->GetLclNum(), varIndex); printTreeID(node); printf(" life %s -> %s\n", VarSetOps::ToString(this, life), VarSetOps::ToString(this, VarSetOps::AddElem(this, life, varIndex))); } #endif // DEBUG // The variable is being used, and it is not currently live. // So the variable is just coming to life node->gtFlags |= GTF_VAR_DEATH; VarSetOps::AddElemD(this, life, varIndex); } //------------------------------------------------------------------------ // Compiler::fgComputeLifeTrackedLocalDef: // Compute the changes to local var liveness due to a def of a tracked local var and return `true` if the def is a // dead store. // // Arguments: // life - The live set that is being computed. // keepAliveVars - The current set of variables to keep alive regardless of their actual lifetime. // varDsc - The LclVar descriptor for the variable being used or defined. // node - The node that is defining the lclVar. // // Returns: // `true` if the def is a dead store; `false` otherwise. bool Compiler::fgComputeLifeTrackedLocalDef(VARSET_TP& life, VARSET_VALARG_TP keepAliveVars, LclVarDsc& varDsc, GenTreeLclVarCommon* node) { assert(node != nullptr); assert((node->gtFlags & GTF_VAR_DEF) != 0); assert(varDsc.lvTracked); const unsigned varIndex = varDsc.lvVarIndex; if (VarSetOps::IsMember(this, life, varIndex)) { // The variable is live if ((node->gtFlags & GTF_VAR_USEASG) == 0) { // Remove the variable from the live set if it is not in the keepalive set. if (!VarSetOps::IsMember(this, keepAliveVars, varIndex)) { VarSetOps::RemoveElemD(this, life, varIndex); } #ifdef DEBUG if (verbose && 0) { printf("Def V%02u,T%02u at ", node->GetLclNum(), varIndex); printTreeID(node); printf(" life %s -> %s\n", VarSetOps::ToString(this, VarSetOps::Union(this, life, VarSetOps::MakeSingleton(this, varIndex))), VarSetOps::ToString(this, life)); } #endif // DEBUG } } else { // Dead store node->gtFlags |= GTF_VAR_DEATH; if (!opts.MinOpts()) { // keepAliveVars always stay alive noway_assert(!VarSetOps::IsMember(this, keepAliveVars, varIndex)); // Do not consider this store dead if the target local variable represents // a promoted struct field of an address exposed local or if the address // of the variable has been exposed. Improved alias analysis could allow // stores to these sorts of variables to be removed at the cost of compile // time. return !varDsc.IsAddressExposed() && !(varDsc.lvIsStructField && lvaTable[varDsc.lvParentLcl].IsAddressExposed()); } } return false; } //------------------------------------------------------------------------ // Compiler::fgComputeLifeUntrackedLocal: // Compute the changes to local var liveness due to a use or a def of an untracked local var. // // Note: // It may seem a bit counter-intuitive that a change to an untracked lclVar could affect the liveness of tracked // lclVars. In theory, this could happen with promoted (especially dependently-promoted) structs: in these cases, // a use or def of the untracked struct var is treated as a use or def of any of its component fields that are // tracked. // // Arguments: // life - The live set that is being computed. // keepAliveVars - The current set of variables to keep alive regardless of their actual lifetime. // varDsc - The LclVar descriptor for the variable being used or defined. // lclVarNode - The node that corresponds to the local var def or use. // // Returns: // `true` if the node is a dead store (i.e. all fields are dead); `false` otherwise. // bool Compiler::fgComputeLifeUntrackedLocal(VARSET_TP& life, VARSET_VALARG_TP keepAliveVars, LclVarDsc& varDsc, GenTreeLclVarCommon* lclVarNode) { assert(lclVarNode != nullptr); bool isDef = ((lclVarNode->gtFlags & GTF_VAR_DEF) != 0); // We have accurate ref counts when running late liveness so we can eliminate // some stores if the lhs local has a ref count of 1. if (isDef && compRationalIRForm && (varDsc.lvRefCnt() == 1) && !varDsc.lvPinned) { if (varDsc.lvIsStructField) { if ((lvaGetDesc(varDsc.lvParentLcl)->lvRefCnt() == 1) && (lvaGetParentPromotionType(&varDsc) == PROMOTION_TYPE_DEPENDENT)) { return true; } } else if (varTypeIsStruct(varDsc.lvType)) { if (lvaGetPromotionType(&varDsc) != PROMOTION_TYPE_INDEPENDENT) { return true; } } else { return true; } } if (!varTypeIsStruct(varDsc.lvType) || (lvaGetPromotionType(&varDsc) == PROMOTION_TYPE_NONE)) { return false; } VARSET_TP fieldSet(VarSetOps::MakeEmpty(this)); bool fieldsAreTracked = true; for (unsigned i = varDsc.lvFieldLclStart; i < varDsc.lvFieldLclStart + varDsc.lvFieldCnt; ++i) { LclVarDsc* fieldVarDsc = lvaGetDesc(i); #if !defined(TARGET_64BIT) if (!varTypeIsLong(fieldVarDsc->lvType) || !fieldVarDsc->lvPromoted) #endif // !defined(TARGET_64BIT) { noway_assert(fieldVarDsc->lvIsStructField); } if (fieldVarDsc->lvTracked) { const unsigned varIndex = fieldVarDsc->lvVarIndex; noway_assert(varIndex < lvaTrackedCount); VarSetOps::AddElemD(this, fieldSet, varIndex); if (isDef && lclVarNode->IsMultiRegLclVar() && !VarSetOps::IsMember(this, life, varIndex)) { // Dead definition. lclVarNode->AsLclVar()->SetLastUse(i - varDsc.lvFieldLclStart); } } else { fieldsAreTracked = false; } } if (isDef) { VARSET_TP liveFields(VarSetOps::Intersection(this, life, fieldSet)); if ((lclVarNode->gtFlags & GTF_VAR_USEASG) == 0) { VarSetOps::DiffD(this, fieldSet, keepAliveVars); VarSetOps::DiffD(this, life, fieldSet); } if (fieldsAreTracked && VarSetOps::IsEmpty(this, liveFields)) { // None of the fields were live, so this is a dead store. if (!opts.MinOpts()) { // keepAliveVars always stay alive VARSET_TP keepAliveFields(VarSetOps::Intersection(this, fieldSet, keepAliveVars)); noway_assert(VarSetOps::IsEmpty(this, keepAliveFields)); // Do not consider this store dead if the parent local variable is an address exposed local or // if the struct has a custom layout and holes. return !(varDsc.IsAddressExposed() || (varDsc.lvCustomLayout && varDsc.lvContainsHoles)); } } return false; } // This is a use. // Are the variables already known to be alive? if (VarSetOps::IsSubset(this, fieldSet, life)) { lclVarNode->gtFlags &= ~GTF_VAR_DEATH; // Since we may now call this multiple times, reset if live. return false; } // Some variables are being used, and they are not currently live. // So they are just coming to life, in the backwards traversal; in a forwards // traversal, one or more are dying. Mark this. lclVarNode->gtFlags |= GTF_VAR_DEATH; // Are all the variables becoming alive (in the backwards traversal), or just a subset? if (!VarSetOps::IsEmptyIntersection(this, fieldSet, life)) { // Only a subset of the variables are becoming alive; we must record that subset. // (Lack of an entry for "lclVarNode" will be considered to imply all become dead in the // forward traversal.) VARSET_TP* deadVarSet = new (this, CMK_bitset) VARSET_TP; VarSetOps::AssignNoCopy(this, *deadVarSet, VarSetOps::Diff(this, fieldSet, life)); GetPromotedStructDeathVars()->Set(lclVarNode, deadVarSet, NodeToVarsetPtrMap::Overwrite); } // In any case, all the field vars are now live (in the backwards traversal). VarSetOps::UnionD(this, life, fieldSet); return false; } //------------------------------------------------------------------------ // Compiler::fgComputeLifeLocal: // Compute the changes to local var liveness due to a use or a def of a local var and indicates whether the use/def // is a dead store. // // Arguments: // life - The live set that is being computed. // keepAliveVars - The current set of variables to keep alive regardless of their actual lifetime. // lclVarNode - The node that corresponds to the local var def or use. // // Returns: // `true` if the local var node corresponds to a dead store; `false` otherwise. bool Compiler::fgComputeLifeLocal(VARSET_TP& life, VARSET_VALARG_TP keepAliveVars, GenTree* lclVarNode) { unsigned lclNum = lclVarNode->AsLclVarCommon()->GetLclNum(); assert(lclNum < lvaCount); LclVarDsc& varDsc = lvaTable[lclNum]; bool isDef = ((lclVarNode->gtFlags & GTF_VAR_DEF) != 0); // Is this a tracked variable? if (varDsc.lvTracked) { /* Is this a definition or use? */ if (isDef) { return fgComputeLifeTrackedLocalDef(life, keepAliveVars, varDsc, lclVarNode->AsLclVarCommon()); } else { fgComputeLifeTrackedLocalUse(life, varDsc, lclVarNode->AsLclVarCommon()); } } else { return fgComputeLifeUntrackedLocal(life, keepAliveVars, varDsc, lclVarNode->AsLclVarCommon()); } return false; } /***************************************************************************** * * Compute the set of live variables at each node in a given statement * or subtree of a statement moving backward from startNode to endNode */ void Compiler::fgComputeLife(VARSET_TP& life, GenTree* startNode, GenTree* endNode, VARSET_VALARG_TP volatileVars, bool* pStmtInfoDirty DEBUGARG(bool* treeModf)) { // Don't kill vars in scope VARSET_TP keepAliveVars(VarSetOps::Union(this, volatileVars, compCurBB->bbScope)); noway_assert(VarSetOps::IsSubset(this, keepAliveVars, life)); noway_assert(endNode || (startNode == compCurStmt->GetRootNode())); // NOTE: Live variable analysis will not work if you try // to use the result of an assignment node directly! for (GenTree* tree = startNode; tree != endNode; tree = tree->gtPrev) { AGAIN: assert(tree->OperGet() != GT_QMARK); if (tree->gtOper == GT_CALL) { fgComputeLifeCall(life, tree->AsCall()); } else if (tree->OperIsNonPhiLocal() || tree->OperIsLocalAddr()) { bool isDeadStore = fgComputeLifeLocal(life, keepAliveVars, tree); if (isDeadStore) { LclVarDsc* varDsc = lvaGetDesc(tree->AsLclVarCommon()); bool doAgain = false; if (fgRemoveDeadStore(&tree, varDsc, life, &doAgain, pStmtInfoDirty DEBUGARG(treeModf))) { assert(!doAgain); break; } if (doAgain) { goto AGAIN; } } } } } void Compiler::fgComputeLifeLIR(VARSET_TP& life, BasicBlock* block, VARSET_VALARG_TP volatileVars) { // Don't kill volatile vars and vars in scope. VARSET_TP keepAliveVars(VarSetOps::Union(this, volatileVars, block->bbScope)); noway_assert(VarSetOps::IsSubset(this, keepAliveVars, life)); LIR::Range& blockRange = LIR::AsRange(block); GenTree* firstNode = blockRange.FirstNode(); if (firstNode == nullptr) { return; } for (GenTree *node = blockRange.LastNode(), *next = nullptr, *end = firstNode->gtPrev; node != end; node = next) { next = node->gtPrev; bool isDeadStore; switch (node->OperGet()) { case GT_CALL: { GenTreeCall* const call = node->AsCall(); if (((call->TypeGet() == TYP_VOID) || call->IsUnusedValue()) && !call->HasSideEffects(this)) { JITDUMP("Removing dead call:\n"); DISPNODE(call); node->VisitOperands([](GenTree* operand) -> GenTree::VisitResult { if (operand->IsValue()) { operand->SetUnusedValue(); } // Special-case PUTARG_STK: since this operator is not considered a value, DCE will not remove // these nodes. if (operand->OperIs(GT_PUTARG_STK)) { operand->AsPutArgStk()->gtOp1->SetUnusedValue(); operand->gtBashToNOP(); } return GenTree::VisitResult::Continue; }); blockRange.Remove(node); // Removing a call does not affect liveness unless it is a tail call in a method with P/Invokes or // is itself a P/Invoke, in which case it may affect the liveness of the frame root variable. if (!opts.MinOpts() && !opts.ShouldUsePInvokeHelpers() && ((call->IsTailCall() && compMethodRequiresPInvokeFrame()) || (call->IsUnmanaged() && !call->IsSuppressGCTransition())) && lvaTable[info.compLvFrameListRoot].lvTracked) { fgStmtRemoved = true; } } else { fgComputeLifeCall(life, call); } break; } case GT_LCL_VAR: case GT_LCL_FLD: { GenTreeLclVarCommon* const lclVarNode = node->AsLclVarCommon(); LclVarDsc& varDsc = lvaTable[lclVarNode->GetLclNum()]; if (node->IsUnusedValue()) { JITDUMP("Removing dead LclVar use:\n"); DISPNODE(lclVarNode); blockRange.Delete(this, block, node); if (varDsc.lvTracked && !opts.MinOpts()) { fgStmtRemoved = true; } } else if (varDsc.lvTracked) { fgComputeLifeTrackedLocalUse(life, varDsc, lclVarNode); } else { fgComputeLifeUntrackedLocal(life, keepAliveVars, varDsc, lclVarNode); } break; } case GT_LCL_VAR_ADDR: case GT_LCL_FLD_ADDR: if (node->IsUnusedValue()) { JITDUMP("Removing dead LclVar address:\n"); DISPNODE(node); const bool isTracked = lvaTable[node->AsLclVarCommon()->GetLclNum()].lvTracked; blockRange.Delete(this, block, node); if (isTracked && !opts.MinOpts()) { fgStmtRemoved = true; } } else { isDeadStore = fgComputeLifeLocal(life, keepAliveVars, node); if (isDeadStore) { LIR::Use addrUse; if (blockRange.TryGetUse(node, &addrUse) && (addrUse.User()->OperIs(GT_STOREIND, GT_STORE_BLK, GT_STORE_OBJ))) { // Remove the store. DCE will iteratively clean up any ununsed operands. GenTreeIndir* const store = addrUse.User()->AsIndir(); JITDUMP("Removing dead indirect store:\n"); DISPNODE(store); assert(store->Addr() == node); blockRange.Delete(this, block, node); GenTree* data = store->OperIs(GT_STOREIND) ? store->AsStoreInd()->Data() : store->AsBlk()->Data(); data->SetUnusedValue(); if (data->isIndir()) { Lowering::TransformUnusedIndirection(data->AsIndir(), this, block); } fgRemoveDeadStoreLIR(store, block); } } } break; case GT_STORE_LCL_VAR: case GT_STORE_LCL_FLD: { GenTreeLclVarCommon* const lclVarNode = node->AsLclVarCommon(); LclVarDsc& varDsc = lvaTable[lclVarNode->GetLclNum()]; if (varDsc.lvTracked) { isDeadStore = fgComputeLifeTrackedLocalDef(life, keepAliveVars, varDsc, lclVarNode); } else { isDeadStore = fgComputeLifeUntrackedLocal(life, keepAliveVars, varDsc, lclVarNode); } if (isDeadStore) { JITDUMP("Removing dead store:\n"); DISPNODE(lclVarNode); // Remove the store. DCE will iteratively clean up any ununsed operands. lclVarNode->gtOp1->SetUnusedValue(); fgRemoveDeadStoreLIR(node, block); } break; } case GT_LABEL: case GT_FTN_ADDR: case GT_CNS_INT: case GT_CNS_LNG: case GT_CNS_DBL: case GT_CNS_STR: case GT_CLS_VAR_ADDR: case GT_PHYSREG: // These are all side-effect-free leaf nodes. if (node->IsUnusedValue()) { JITDUMP("Removing dead node:\n"); DISPNODE(node); blockRange.Remove(node); } break; case GT_LOCKADD: case GT_XORR: case GT_XAND: case GT_XADD: case GT_XCHG: case GT_CMPXCHG: case GT_MEMORYBARRIER: case GT_JMP: case GT_STOREIND: case GT_BOUNDS_CHECK: case GT_STORE_OBJ: case GT_STORE_BLK: case GT_STORE_DYN_BLK: case GT_JCMP: case GT_CMP: case GT_JCC: case GT_JTRUE: case GT_RETURN: case GT_SWITCH: case GT_RETFILT: case GT_START_NONGC: case GT_START_PREEMPTGC: case GT_PROF_HOOK: #if !defined(FEATURE_EH_FUNCLETS) case GT_END_LFIN: #endif // !FEATURE_EH_FUNCLETS case GT_SWITCH_TABLE: case GT_PINVOKE_PROLOG: case GT_PINVOKE_EPILOG: case GT_RETURNTRAP: case GT_PUTARG_STK: case GT_IL_OFFSET: case GT_KEEPALIVE: #ifdef FEATURE_HW_INTRINSICS case GT_HWINTRINSIC: #endif // FEATURE_HW_INTRINSICS // Never remove these nodes, as they are always side-effecting. // // NOTE: the only side-effect of some of these nodes (GT_CMP, GT_SUB_HI) is a write to the flags // register. // Properly modeling this would allow these nodes to be removed. break; case GT_NOP: { // NOTE: we need to keep some NOPs around because they are referenced by calls. See the dead store // removal code above (case GT_STORE_LCL_VAR) for more explanation. if ((node->gtFlags & GTF_ORDER_SIDEEFF) != 0) { break; } fgTryRemoveNonLocal(node, &blockRange); } break; case GT_BLK: case GT_OBJ: case GT_DYN_BLK: { bool removed = fgTryRemoveNonLocal(node, &blockRange); if (!removed && node->IsUnusedValue()) { // IR doesn't expect dummy uses of `GT_OBJ/BLK/DYN_BLK`. JITDUMP("Transform an unused OBJ/BLK node [%06d]\n", dspTreeID(node)); Lowering::TransformUnusedIndirection(node->AsIndir(), this, block); } } break; default: fgTryRemoveNonLocal(node, &blockRange); break; } } } //--------------------------------------------------------------------- // fgTryRemoveNonLocal - try to remove a node if it is unused and has no direct // side effects. // // Arguments // node - the non-local node to try; // blockRange - the block range that contains the node. // // Return value: // None // // Notes: local nodes are processed independently and are not expected in this function. // bool Compiler::fgTryRemoveNonLocal(GenTree* node, LIR::Range* blockRange) { assert(!node->OperIsLocal()); if (!node->IsValue() || node->IsUnusedValue()) { // We are only interested in avoiding the removal of nodes with direct side effects // (as opposed to side effects of their children). // This default case should never include calls or assignments. assert(!node->OperRequiresAsgFlag() && !node->OperIs(GT_CALL)); if (!node->gtSetFlags() && !node->OperMayThrow(this)) { JITDUMP("Removing dead node:\n"); DISPNODE(node); node->VisitOperands([](GenTree* operand) -> GenTree::VisitResult { operand->SetUnusedValue(); return GenTree::VisitResult::Continue; }); blockRange->Remove(node); return true; } } return false; } //--------------------------------------------------------------------- // fgRemoveDeadStoreSimple - remove a dead store // // pTree - GenTree** to local, including store-form local or local addr (post-rationalize) // varDsc - var that is being stored to // life - current live tracked vars (maintained as we walk backwards) // doAgain - out parameter, true if we should restart the statement // pStmtInfoDirty - should defer the cost computation to the point after the reverse walk is completed? // void Compiler::fgRemoveDeadStoreLIR(GenTree* store, BasicBlock* block) { LIR::Range& blockRange = LIR::AsRange(block); // If the store is marked as a late argument, it is referenced by a call. // Instead of removing it, bash it to a NOP. if ((store->gtFlags & GTF_LATE_ARG) != 0) { JITDUMP("node is a late arg; replacing with NOP\n"); store->gtBashToNOP(); // NOTE: this is a bit of a hack. We need to keep these nodes around as they are // referenced by the call, but they're considered side-effect-free non-value-producing // nodes, so they will be removed if we don't do this. store->gtFlags |= GTF_ORDER_SIDEEFF; } else { blockRange.Remove(store); } assert(!opts.MinOpts()); fgStmtRemoved = true; } //--------------------------------------------------------------------- // fgRemoveDeadStore - remove a store to a local which has no exposed uses. // // pTree - GenTree** to local, including store-form local or local addr (post-rationalize) // varDsc - var that is being stored to // life - current live tracked vars (maintained as we walk backwards) // doAgain - out parameter, true if we should restart the statement // pStmtInfoDirty - should defer the cost computation to the point after the reverse walk is completed? // // Returns: true if we should skip the rest of the statement, false if we should continue bool Compiler::fgRemoveDeadStore(GenTree** pTree, LclVarDsc* varDsc, VARSET_VALARG_TP life, bool* doAgain, bool* pStmtInfoDirty DEBUGARG(bool* treeModf)) { assert(!compRationalIRForm); // Vars should have already been checked for address exposure by this point. assert(!varDsc->lvIsStructField || !lvaTable[varDsc->lvParentLcl].IsAddressExposed()); assert(!varDsc->IsAddressExposed()); GenTree* asgNode = nullptr; GenTree* rhsNode = nullptr; GenTree* addrNode = nullptr; GenTree* const tree = *pTree; GenTree* nextNode = tree->gtNext; // First, characterize the lclVarTree and see if we are taking its address. if (tree->OperIsLocalStore()) { rhsNode = tree->AsOp()->gtOp1; asgNode = tree; } else if (tree->OperIsLocal()) { if (nextNode == nullptr) { return false; } if (nextNode->OperGet() == GT_ADDR) { addrNode = nextNode; nextNode = nextNode->gtNext; } } else { assert(tree->OperIsLocalAddr()); addrNode = tree; } // Next, find the assignment (i.e. if we didn't have a LocalStore) if (asgNode == nullptr) { if (addrNode == nullptr) { asgNode = nextNode; } else { // This may be followed by GT_IND/assign or GT_STOREIND. if (nextNode == nullptr) { return false; } if (nextNode->OperIsIndir()) { // This must be a non-nullcheck form of indir, or it would not be a def. assert(nextNode->OperGet() != GT_NULLCHECK); if (nextNode->OperIsStore()) { // This is a store, which takes a location and a value to be stored. // It's 'rhsNode' is the value to be stored. asgNode = nextNode; if (asgNode->OperIsBlk()) { rhsNode = asgNode->AsBlk()->Data(); } else { // This is a non-block store. rhsNode = asgNode->gtGetOp2(); } } else { // This is a non-store indirection, and the assignment will com after it. asgNode = nextNode->gtNext; } } } } if (asgNode == nullptr) { return false; } if (asgNode->OperIs(GT_ASG)) { rhsNode = asgNode->gtGetOp2(); } else if (rhsNode == nullptr) { return false; } if (asgNode->gtFlags & GTF_ASG) { noway_assert(rhsNode); noway_assert(tree->gtFlags & GTF_VAR_DEF); assert(asgNode->OperIs(GT_ASG)); // Do not remove if this local variable represents // a promoted struct field of an address exposed local. if (varDsc->lvIsStructField && lvaTable[varDsc->lvParentLcl].IsAddressExposed()) { return false; } // Do not remove if the address of the variable has been exposed. if (varDsc->IsAddressExposed()) { return false; } // Check for side effects GenTree* sideEffList = nullptr; if (rhsNode->gtFlags & GTF_SIDE_EFFECT) { #ifdef DEBUG if (verbose) { printf(FMT_BB " - Dead assignment has side effects...\n", compCurBB->bbNum); gtDispTree(asgNode); printf("\n"); } #endif // DEBUG // Extract the side effects gtExtractSideEffList(rhsNode, &sideEffList); } // Test for interior statement if (asgNode->gtNext == nullptr) { // This is a "NORMAL" statement with the assignment node hanging from the statement. noway_assert(compCurStmt->GetRootNode() == asgNode); JITDUMP("top level assign\n"); if (sideEffList != nullptr) { noway_assert(sideEffList->gtFlags & GTF_SIDE_EFFECT); #ifdef DEBUG if (verbose) { printf("Extracted side effects list...\n"); gtDispTree(sideEffList); printf("\n"); } #endif // DEBUG // Replace the assignment statement with the list of side effects *pTree = sideEffList; compCurStmt->SetRootNode(sideEffList); #ifdef DEBUG *treeModf = true; #endif // DEBUG // Update ordering, costs, FP levels, etc. gtSetStmtInfo(compCurStmt); // Re-link the nodes for this statement fgSetStmtSeq(compCurStmt); // Since the whole statement gets replaced it is safe to // re-thread and update order. No need to compute costs again. *pStmtInfoDirty = false; // Compute the live set for the new statement *doAgain = true; return false; } else { JITDUMP("removing stmt with no side effects\n"); // No side effects - remove the whole statement from the block->bbStmtList. fgRemoveStmt(compCurBB, compCurStmt); // Since we removed it do not process the rest (i.e. RHS) of the statement // variables in the RHS will not be marked as live, so we get the benefit of // propagating dead variables up the chain return true; } } else { // This is an INTERIOR STATEMENT with a dead assignment - remove it // TODO-Cleanup: I'm not sure this assert is valuable; we've already determined this when // we computed that it was dead. if (varDsc->lvTracked) { noway_assert(!VarSetOps::IsMember(this, life, varDsc->lvVarIndex)); } else { for (unsigned i = 0; i < varDsc->lvFieldCnt; ++i) { unsigned fieldVarNum = varDsc->lvFieldLclStart + i; { LclVarDsc* fieldVarDsc = lvaGetDesc(fieldVarNum); noway_assert(fieldVarDsc->lvTracked && !VarSetOps::IsMember(this, life, fieldVarDsc->lvVarIndex)); } } } if (sideEffList != nullptr) { noway_assert(sideEffList->gtFlags & GTF_SIDE_EFFECT); #ifdef DEBUG if (verbose) { printf("Extracted side effects list from condition...\n"); gtDispTree(sideEffList); printf("\n"); } #endif // DEBUG if (sideEffList->gtOper == asgNode->gtOper) { #ifdef DEBUG *treeModf = true; #endif // DEBUG asgNode->AsOp()->gtOp1 = sideEffList->AsOp()->gtOp1; asgNode->AsOp()->gtOp2 = sideEffList->AsOp()->gtOp2; asgNode->gtType = sideEffList->gtType; } else { #ifdef DEBUG *treeModf = true; #endif // DEBUG // Change the node to a GT_COMMA holding the side effect list asgNode->gtBashToNOP(); asgNode->ChangeOper(GT_COMMA); asgNode->gtFlags |= sideEffList->gtFlags & GTF_ALL_EFFECT; if (sideEffList->gtOper == GT_COMMA) { asgNode->AsOp()->gtOp1 = sideEffList->AsOp()->gtOp1; asgNode->AsOp()->gtOp2 = sideEffList->AsOp()->gtOp2; } else { asgNode->AsOp()->gtOp1 = sideEffList; asgNode->AsOp()->gtOp2 = gtNewNothingNode(); } } } else { #ifdef DEBUG if (verbose) { printf("\nRemoving tree "); printTreeID(asgNode); printf(" in " FMT_BB " as useless\n", compCurBB->bbNum); gtDispTree(asgNode); printf("\n"); } #endif // DEBUG // No side effects - Change the assignment to a GT_NOP node asgNode->gtBashToNOP(); #ifdef DEBUG *treeModf = true; #endif // DEBUG } // Re-link the nodes for this statement - Do not update ordering! // Do not update costs by calling gtSetStmtInfo. fgSetStmtSeq modifies // the tree threading based on the new costs. Removing nodes could // cause a subtree to get evaluated first (earlier second) during the // liveness walk. Instead just set a flag that costs are dirty and // caller has to call gtSetStmtInfo. *pStmtInfoDirty = true; fgSetStmtSeq(compCurStmt); // Continue analysis from this node *pTree = asgNode; return false; } } return false; } /***************************************************************************** * * Iterative data flow for live variable info and availability of range * check index expressions. */ void Compiler::fgInterBlockLocalVarLiveness() { #ifdef DEBUG if (verbose) { printf("*************** In fgInterBlockLocalVarLiveness()\n"); } #endif /* This global flag is set whenever we remove a statement */ fgStmtRemoved = false; // keep track if a bbLiveIn changed due to dead store removal fgLocalVarLivenessChanged = false; /* Compute the IN and OUT sets for tracked variables */ fgLiveVarAnalysis(); /* For debuggable code, we mark vars as live over their entire * reported scope, so that it will be visible over the entire scope */ if (opts.compDbgCode && (info.compVarScopesCount > 0)) { fgExtendDbgLifetimes(); } // Nothing more to be done if the backend does not require accurate local var lifetimes. if (!backendRequiresLocalVarLifetimes()) { fgLocalVarLivenessDone = true; return; } //------------------------------------------------------------------------- // Variables involved in exception-handlers and finally blocks need // to be specially marked // VARSET_TP exceptVars(VarSetOps::MakeEmpty(this)); // vars live on entry to a handler VARSET_TP finallyVars(VarSetOps::MakeEmpty(this)); // vars live on exit of a 'finally' block for (BasicBlock* const block : Blocks()) { if (block->hasEHBoundaryIn()) { // Note the set of variables live on entry to exception handler. VarSetOps::UnionD(this, exceptVars, block->bbLiveIn); } if (block->hasEHBoundaryOut()) { // Get the set of live variables on exit from an exception region. VarSetOps::UnionD(this, exceptVars, block->bbLiveOut); if (block->bbJumpKind == BBJ_EHFINALLYRET) { // Live on exit from finally. // We track these separately because, in addition to having EH live-out semantics, // they are must-init. VarSetOps::UnionD(this, finallyVars, block->bbLiveOut); } } } LclVarDsc* varDsc; unsigned varNum; for (varNum = 0, varDsc = lvaTable; varNum < lvaCount; varNum++, varDsc++) { // Ignore the variable if it's not tracked if (!varDsc->lvTracked) { continue; } // Fields of dependently promoted structs may be tracked. We shouldn't set lvMustInit on them since // the whole parent struct will be initialized; however, lvLiveInOutOfHndlr should be set on them // as appropriate. bool fieldOfDependentlyPromotedStruct = lvaIsFieldOfDependentlyPromotedStruct(varDsc); // Un-init locals may need auto-initialization. Note that the // liveness of such locals will bubble to the top (fgFirstBB) // in fgInterBlockLocalVarLiveness() if (!varDsc->lvIsParam && VarSetOps::IsMember(this, fgFirstBB->bbLiveIn, varDsc->lvVarIndex) && (info.compInitMem || varTypeIsGC(varDsc->TypeGet())) && !fieldOfDependentlyPromotedStruct) { varDsc->lvMustInit = true; } // Mark all variables that are live on entry to an exception handler // or on exit from a filter handler or finally. bool isFinallyVar = VarSetOps::IsMember(this, finallyVars, varDsc->lvVarIndex); if (isFinallyVar || VarSetOps::IsMember(this, exceptVars, varDsc->lvVarIndex)) { // Mark the variable appropriately. lvaSetVarLiveInOutOfHandler(varNum); // Mark all pointer variables live on exit from a 'finally' block as // 'explicitly initialized' (must-init) for GC-ref types. if (isFinallyVar) { // Set lvMustInit only if we have a non-arg, GC pointer. if (!varDsc->lvIsParam && varTypeIsGC(varDsc->TypeGet())) { varDsc->lvMustInit = true; } } } } /*------------------------------------------------------------------------- * Now fill in liveness info within each basic block - Backward DataFlow */ for (BasicBlock* const block : Blocks()) { /* Tell everyone what block we're working on */ compCurBB = block; /* Remember those vars live on entry to exception handlers */ /* if we are part of a try block */ VARSET_TP volatileVars(VarSetOps::MakeEmpty(this)); if (ehBlockHasExnFlowDsc(block)) { VarSetOps::Assign(this, volatileVars, fgGetHandlerLiveVars(block)); // volatileVars is a subset of exceptVars noway_assert(VarSetOps::IsSubset(this, volatileVars, exceptVars)); } /* Start with the variables live on exit from the block */ VARSET_TP life(VarSetOps::MakeCopy(this, block->bbLiveOut)); /* Mark any interference we might have at the end of the block */ if (block->IsLIR()) { fgComputeLifeLIR(life, block, volatileVars); } else { /* Get the first statement in the block */ Statement* firstStmt = block->FirstNonPhiDef(); if (firstStmt == nullptr) { continue; } /* Walk all the statements of the block backwards - Get the LAST stmt */ Statement* nextStmt = block->lastStmt(); do { #ifdef DEBUG bool treeModf = false; #endif // DEBUG noway_assert(nextStmt != nullptr); compCurStmt = nextStmt; nextStmt = nextStmt->GetPrevStmt(); /* Compute the liveness for each tree node in the statement */ bool stmtInfoDirty = false; fgComputeLife(life, compCurStmt->GetRootNode(), nullptr, volatileVars, &stmtInfoDirty DEBUGARG(&treeModf)); if (stmtInfoDirty) { gtSetStmtInfo(compCurStmt); fgSetStmtSeq(compCurStmt); gtUpdateStmtSideEffects(compCurStmt); } #ifdef DEBUG if (verbose && treeModf) { printf("\nfgComputeLife modified tree:\n"); gtDispTree(compCurStmt->GetRootNode()); printf("\n"); } #endif // DEBUG } while (compCurStmt != firstStmt); } /* Done with the current block - if we removed any statements, some * variables may have become dead at the beginning of the block * -> have to update bbLiveIn */ if (!VarSetOps::Equal(this, life, block->bbLiveIn)) { /* some variables have become dead all across the block So life should be a subset of block->bbLiveIn */ // We changed the liveIn of the block, which may affect liveOut of others, // which may expose more dead stores. fgLocalVarLivenessChanged = true; noway_assert(VarSetOps::IsSubset(this, life, block->bbLiveIn)); /* set the new bbLiveIn */ VarSetOps::Assign(this, block->bbLiveIn, life); /* compute the new bbLiveOut for all the predecessors of this block */ } noway_assert(compCurBB == block); #ifdef DEBUG compCurBB = nullptr; #endif } fgLocalVarLivenessDone = true; } #ifdef DEBUG /*****************************************************************************/ void Compiler::fgDispBBLiveness(BasicBlock* block) { VARSET_TP allVars(VarSetOps::Union(this, block->bbLiveIn, block->bbLiveOut)); printf(FMT_BB, block->bbNum); printf(" IN (%d)=", VarSetOps::Count(this, block->bbLiveIn)); lvaDispVarSet(block->bbLiveIn, allVars); for (MemoryKind memoryKind : allMemoryKinds()) { if ((block->bbMemoryLiveIn & memoryKindSet(memoryKind)) != 0) { printf(" + %s", memoryKindNames[memoryKind]); } } printf("\n OUT(%d)=", VarSetOps::Count(this, block->bbLiveOut)); lvaDispVarSet(block->bbLiveOut, allVars); for (MemoryKind memoryKind : allMemoryKinds()) { if ((block->bbMemoryLiveOut & memoryKindSet(memoryKind)) != 0) { printf(" + %s", memoryKindNames[memoryKind]); } } printf("\n\n"); } void Compiler::fgDispBBLiveness() { for (BasicBlock* const block : Blocks()) { fgDispBBLiveness(block); } } #endif // DEBUG
35.311031
120
0.547631
[ "model", "transform" ]
4f8f9bae3f6adbc9c42dd51d9606658a8e7880c1
12,482
cc
C++
runtime/browser/runtime.cc
junmin-zhu/crosswalk
6c2ab70dcdbdda99da85fa6c8f79b5371aafbb1d
[ "BSD-3-Clause" ]
null
null
null
runtime/browser/runtime.cc
junmin-zhu/crosswalk
6c2ab70dcdbdda99da85fa6c8f79b5371aafbb1d
[ "BSD-3-Clause" ]
null
null
null
runtime/browser/runtime.cc
junmin-zhu/crosswalk
6c2ab70dcdbdda99da85fa6c8f79b5371aafbb1d
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "xwalk/runtime/browser/runtime.h" #include <string> #include <utility> #include "base/command_line.h" #include "base/message_loop/message_loop.h" #include "xwalk/runtime/browser/image_util.h" #include "xwalk/runtime/browser/media/media_capture_devices_dispatcher.h" #include "xwalk/runtime/browser/runtime_context.h" #include "xwalk/runtime/browser/runtime_file_select_helper.h" #include "xwalk/runtime/browser/ui/color_chooser.h" #include "xwalk/runtime/browser/xwalk_runner.h" #include "xwalk/runtime/common/xwalk_notification_types.h" #include "xwalk/runtime/common/xwalk_switches.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "grit/xwalk_resources.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/native_widget_types.h" using content::FaviconURL; using content::WebContents; namespace xwalk { namespace { // The default size for web content area size. const int kDefaultWidth = 840; const int kDefaultHeight = 600; } // namespace // static Runtime* Runtime::CreateWithDefaultWindow( RuntimeContext* runtime_context, const GURL& url, Observer* observer) { Runtime* runtime = Runtime::Create(runtime_context, observer); runtime->LoadURL(url); runtime->AttachDefaultWindow(); return runtime; } // static Runtime* Runtime::Create(RuntimeContext* runtime_context, Observer* observer, content::SiteInstance* site) { WebContents::CreateParams params(runtime_context, site); params.routing_id = MSG_ROUTING_NONE; WebContents* web_contents = WebContents::Create(params); Runtime* runtime = new Runtime(web_contents, observer); #if defined(OS_TIZEN_MOBILE) runtime->InitRootWindow(); #endif return runtime; } Runtime::Runtime(content::WebContents* web_contents, Observer* observer) : WebContentsObserver(web_contents), web_contents_(web_contents), window_(NULL), weak_ptr_factory_(this), fullscreen_options_(NO_FULLSCREEN), remote_debugging_enabled_(false), observer_(observer) { web_contents_->SetDelegate(this); content::NotificationService::current()->Notify( xwalk::NOTIFICATION_RUNTIME_OPENED, content::Source<Runtime>(this), content::NotificationService::NoDetails()); #if defined(OS_TIZEN_MOBILE) root_window_ = NULL; #endif if (observer_) observer_->OnRuntimeAdded(this); } Runtime::~Runtime() { content::NotificationService::current()->Notify( xwalk::NOTIFICATION_RUNTIME_CLOSED, content::Source<Runtime>(this), content::NotificationService::NoDetails()); if (observer_) observer_->OnRuntimeRemoved(this); } void Runtime::AttachDefaultWindow() { NativeAppWindow::CreateParams params; AttachWindow(params); } void Runtime::AttachWindow(const NativeAppWindow::CreateParams& params) { #if defined(OS_ANDROID) NOTIMPLEMENTED(); #else CHECK(!window_); NativeAppWindow::CreateParams effective_params(params); ApplyWindowDefaultParams(&effective_params); // Set the app icon if it is passed from command line. CommandLine* command_line = CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kAppIcon)) { base::FilePath icon_file = command_line->GetSwitchValuePath(switches::kAppIcon); app_icon_ = xwalk_utils::LoadImageFromFilePath(icon_file); } else { // Otherwise, use the default icon for Crosswalk app. ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance(); app_icon_ = rb.GetNativeImageNamed(IDR_XWALK_ICON_48); } registrar_.Add(this, content::NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED, content::Source<content::WebContents>(web_contents_.get())); window_ = NativeAppWindow::Create(effective_params); if (!app_icon_.IsEmpty()) window_->UpdateIcon(app_icon_); window_->Show(); #if defined(OS_TIZEN_MOBILE) if (root_window_) root_window_->Show(); #endif #endif } void Runtime::LoadURL(const GURL& url) { content::NavigationController::LoadURLParams params(url); params.transition_type = content::PageTransitionFromInt( content::PAGE_TRANSITION_TYPED | content::PAGE_TRANSITION_FROM_ADDRESS_BAR); web_contents_->GetController().LoadURLWithParams(params); web_contents_->Focus(); } void Runtime::Close() { if (window_) { window_->Close(); return; } // Runtime should not free itself on Close but be owned // by Application. delete this; } content::RenderProcessHost* Runtime::GetRenderProcessHost() { return web_contents_->GetRenderProcessHost(); } ////////////////////////////////////////////////////// // content::WebContentsDelegate: ////////////////////////////////////////////////////// content::WebContents* Runtime::OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) { // The only one disposition we would take into consideration. DCHECK(params.disposition == CURRENT_TAB); source->GetController().LoadURL( params.url, params.referrer, params.transition, std::string()); return source; } void Runtime::LoadingStateChanged(content::WebContents* source, bool to_different_document) { } void Runtime::ToggleFullscreenModeForTab(content::WebContents* web_contents, bool enter_fullscreen) { if (enter_fullscreen) fullscreen_options_ |= FULLSCREEN_FOR_TAB; else fullscreen_options_ &= ~FULLSCREEN_FOR_TAB; if (enter_fullscreen) { window_->SetFullscreen(true); } else if (!fullscreen_options_ & FULLSCREEN_FOR_LAUNCH) { window_->SetFullscreen(false); } } bool Runtime::IsFullscreenForTabOrPending( const content::WebContents* web_contents) const { return (fullscreen_options_ & FULLSCREEN_FOR_TAB) != 0; } void Runtime::RequestToLockMouse(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) { web_contents->GotResponseToLockMouseRequest(true); } void Runtime::CloseContents(content::WebContents* source) { window_->Close(); } bool Runtime::CanOverscrollContent() const { return false; } bool Runtime::PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event, bool* is_keyboard_shortcut) { // Escape exits tabbed fullscreen mode. if (event.windowsKeyCode == 27 && IsFullscreenForTabOrPending(source)) { ToggleFullscreenModeForTab(source, false); return true; } return false; } void Runtime::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { } void Runtime::WebContentsCreated( content::WebContents* source_contents, int opener_render_frame_id, const base::string16& frame_name, const GURL& target_url, content::WebContents* new_contents) { Runtime* new_runtime = new Runtime(new_contents, observer_); #if defined(OS_TIZEN_MOBILE) new_runtime->SetRootWindow(root_window_); #endif new_runtime->AttachDefaultWindow(); } void Runtime::DidNavigateMainFramePostCommit( content::WebContents* web_contents) { } content::JavaScriptDialogManager* Runtime::GetJavaScriptDialogManager() { return NULL; } void Runtime::ActivateContents(content::WebContents* contents) { contents->GetRenderViewHost()->Focus(); } void Runtime::DeactivateContents(content::WebContents* contents) { contents->GetRenderViewHost()->Blur(); } content::ColorChooser* Runtime::OpenColorChooser( content::WebContents* web_contents, SkColor initial_color, const std::vector<content::ColorSuggestion>& suggestions) { return xwalk::ShowColorChooser(web_contents, initial_color); } void Runtime::RunFileChooser( content::WebContents* web_contents, const content::FileChooserParams& params) { #if defined(USE_AURA) && defined(OS_LINUX) NOTIMPLEMENTED(); #else RuntimeFileSelectHelper::RunFileChooser(web_contents, params); #endif } void Runtime::EnumerateDirectory(content::WebContents* web_contents, int request_id, const base::FilePath& path) { #if defined(USE_AURA) && defined(OS_LINUX) NOTIMPLEMENTED(); #else RuntimeFileSelectHelper::EnumerateDirectory(web_contents, request_id, path); #endif } void Runtime::DidUpdateFaviconURL(const std::vector<FaviconURL>& candidates) { DLOG(INFO) << "Candidates: "; for (size_t i = 0; i < candidates.size(); ++i) DLOG(INFO) << candidates[i].icon_url.spec(); if (candidates.empty()) return; // Avoid using any previous download. weak_ptr_factory_.InvalidateWeakPtrs(); // We only select the first favicon as the window app icon. FaviconURL favicon = candidates[0]; // Passing 0 as the |image_size| parameter results in only receiving the first // bitmap, according to content/public/browser/web_contents.h web_contents()->DownloadImage( favicon.icon_url, true, // Is a favicon 0, // No maximum size base::Bind( &Runtime::DidDownloadFavicon, weak_ptr_factory_.GetWeakPtr())); } void Runtime::DidDownloadFavicon(int id, int http_status_code, const GURL& image_url, const std::vector<SkBitmap>& bitmaps, const std::vector<gfx::Size>& sizes) { if (bitmaps.empty()) return; app_icon_ = gfx::Image::CreateFrom1xBitmap(bitmaps[0]); window_->UpdateIcon(app_icon_); } void Runtime::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { if (type == content::NOTIFICATION_WEB_CONTENTS_TITLE_UPDATED) { std::pair<content::NavigationEntry*, bool>* title = content::Details<std::pair<content::NavigationEntry*, bool> >( details).ptr(); if (title->first) { base::string16 text = title->first->GetTitle(); window_->UpdateTitle(text); } } } void Runtime::OnWindowDestroyed() { // Runtime should not free itself on Close but be owned // by Application. delete this; } void Runtime::RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, const content::MediaResponseCallback& callback) { XWalkMediaCaptureDevicesDispatcher::RunRequestMediaAccessPermission( web_contents, request, callback); } void Runtime::ApplyWindowDefaultParams(NativeAppWindow::CreateParams* params) { if (!params->delegate) params->delegate = this; if (!params->web_contents) params->web_contents = web_contents_.get(); if (params->bounds.IsEmpty()) params->bounds = gfx::Rect(0, 0, kDefaultWidth, kDefaultHeight); #if defined(OS_TIZEN_MOBILE) if (root_window_) params->parent = root_window_->GetNativeWindow(); #endif ApplyFullScreenParam(params); } void Runtime::ApplyFullScreenParam(NativeAppWindow::CreateParams* params) { DCHECK(params); if (params->state == ui::SHOW_STATE_FULLSCREEN) fullscreen_options_ |= FULLSCREEN_FOR_LAUNCH; else fullscreen_options_ &= ~FULLSCREEN_FOR_LAUNCH; } #if defined(OS_TIZEN_MOBILE) void Runtime::CloseRootWindow() { if (root_window_) { root_window_->Close(); root_window_ = NULL; } } void Runtime::ApplyRootWindowParams(NativeAppWindow::CreateParams* params) { if (!params->delegate) params->delegate = this; if (params->bounds.IsEmpty()) params->bounds = gfx::Rect(0, 0, kDefaultWidth, kDefaultHeight); ApplyFullScreenParam(params); } void Runtime::InitRootWindow() { if (root_window_) return; NativeAppWindow::CreateParams params; ApplyRootWindowParams(&params); root_window_ = NativeAppWindow::Create(params); } void Runtime::SetRootWindow(NativeAppWindow* window) { root_window_= window; } #endif } // namespace xwalk
31.127182
80
0.714629
[ "vector" ]
4f91ecc4debd8b2d11f5306733889e80d43c144d
13,938
cc
C++
src/test/encoding.cc
rpratap-bot/ceph
9834961a66927ae856935591f2fd51082e2ee484
[ "MIT" ]
4
2020-04-08T03:42:02.000Z
2020-10-01T20:34:48.000Z
src/test/encoding.cc
rpratap-bot/ceph
9834961a66927ae856935591f2fd51082e2ee484
[ "MIT" ]
93
2020-03-26T14:29:14.000Z
2020-11-12T05:54:55.000Z
src/test/encoding.cc
rpratap-bot/ceph
9834961a66927ae856935591f2fd51082e2ee484
[ "MIT" ]
23
2020-03-24T10:28:44.000Z
2020-09-24T09:42:19.000Z
#include "include/buffer.h" #include "include/encoding.h" #include "gtest/gtest.h" using namespace std; template < typename T > static void test_encode_and_decode(const T& src) { bufferlist bl(1000000); encode(src, bl); T dst; auto i = bl.cbegin(); decode(dst, i); ASSERT_EQ(src, dst) << "Encoding roundtrip changed the string: orig=" << src << ", but new=" << dst; } TEST(EncodingRoundTrip, StringSimple) { string my_str("I am the very model of a modern major general"); test_encode_and_decode < std::string >(my_str); } TEST(EncodingRoundTrip, StringEmpty) { string my_str(""); test_encode_and_decode < std::string >(my_str); } TEST(EncodingRoundTrip, StringNewline) { string my_str("foo bar baz\n"); test_encode_and_decode < std::string >(my_str); } template <typename Size, typename T> static void test_encode_and_nohead_nohead(Size len, const T& src) { bufferlist bl(1000000); encode(len, bl); encode_nohead(src, bl); T dst; auto i = bl.cbegin(); decode(len, i); decode_nohead(len, dst, i); ASSERT_EQ(src, dst) << "Encoding roundtrip changed the string: orig=" << src << ", but new=" << dst; } TEST(EncodingRoundTrip, StringNoHead) { const string str("The quick brown fox jumps over the lazy dog"); auto size = str.size(); test_encode_and_nohead_nohead(static_cast<int>(size), str); test_encode_and_nohead_nohead(static_cast<unsigned>(size), str); test_encode_and_nohead_nohead(static_cast<uint32_t>(size), str); test_encode_and_nohead_nohead(static_cast<__u32>(size), str); test_encode_and_nohead_nohead(static_cast<size_t>(size), str); } TEST(EncodingRoundTrip, BufferListNoHead) { bufferlist bl; bl.append("is this a dagger which i see before me?"); auto size = bl.length(); test_encode_and_nohead_nohead(static_cast<int>(size), bl); test_encode_and_nohead_nohead(static_cast<unsigned>(size), bl); test_encode_and_nohead_nohead(static_cast<uint32_t>(size), bl); test_encode_and_nohead_nohead(static_cast<__u32>(size), bl); test_encode_and_nohead_nohead(static_cast<size_t>(size), bl); } typedef std::multimap < int, std::string > multimap_t; typedef multimap_t::value_type my_val_ty; namespace std { static std::ostream& operator<<(std::ostream& oss, const multimap_t &multimap) { for (multimap_t::const_iterator m = multimap.begin(); m != multimap.end(); ++m) { oss << m->first << "->" << m->second << " "; } return oss; } } TEST(EncodingRoundTrip, Multimap) { multimap_t multimap; multimap.insert( my_val_ty(1, "foo") ); multimap.insert( my_val_ty(2, "bar") ); multimap.insert( my_val_ty(2, "baz") ); multimap.insert( my_val_ty(3, "lucky number 3") ); multimap.insert( my_val_ty(10000, "large number") ); test_encode_and_decode < multimap_t >(multimap); } /////////////////////////////////////////////////////// // ConstructorCounter /////////////////////////////////////////////////////// template <typename T> class ConstructorCounter { public: ConstructorCounter() : data(0) { default_ctor++; } explicit ConstructorCounter(const T& data_) : data(data_) { one_arg_ctor++; } ConstructorCounter(const ConstructorCounter &rhs) : data(rhs.data) { copy_ctor++; } ConstructorCounter &operator=(const ConstructorCounter &rhs) { data = rhs.data; assigns++; return *this; } static void init(void) { default_ctor = 0; one_arg_ctor = 0; copy_ctor = 0; assigns = 0; } static int get_default_ctor(void) { return default_ctor; } static int get_one_arg_ctor(void) { return one_arg_ctor; } static int get_copy_ctor(void) { return copy_ctor; } static int get_assigns(void) { return assigns; } bool operator<(const ConstructorCounter &rhs) const { return data < rhs.data; } bool operator==(const ConstructorCounter &rhs) const { return data == rhs.data; } friend void decode(ConstructorCounter &s, bufferlist::const_iterator& p) { decode(s.data, p); } friend void encode(const ConstructorCounter &s, bufferlist& p) { encode(s.data, p); } friend ostream& operator<<(ostream &oss, const ConstructorCounter &cc) { oss << cc.data; return oss; } T data; private: static int default_ctor; static int one_arg_ctor; static int copy_ctor; static int assigns; }; template class ConstructorCounter <int32_t>; template class ConstructorCounter <int16_t>; typedef ConstructorCounter <int32_t> my_key_t; typedef ConstructorCounter <int16_t> my_val_t; typedef std::multimap < my_key_t, my_val_t > multimap2_t; typedef multimap2_t::value_type val2_ty; template <class T> int ConstructorCounter<T>::default_ctor = 0; template <class T> int ConstructorCounter<T>::one_arg_ctor = 0; template <class T> int ConstructorCounter<T>::copy_ctor = 0; template <class T> int ConstructorCounter<T>::assigns = 0; static std::ostream& operator<<(std::ostream& oss, const multimap2_t &multimap) { for (multimap2_t::const_iterator m = multimap.begin(); m != multimap.end(); ++m) { oss << m->first << "->" << m->second << " "; } return oss; } TEST(EncodingRoundTrip, MultimapConstructorCounter) { multimap2_t multimap2; multimap2.insert( val2_ty(my_key_t(1), my_val_t(10)) ); multimap2.insert( val2_ty(my_key_t(2), my_val_t(20)) ); multimap2.insert( val2_ty(my_key_t(2), my_val_t(30)) ); multimap2.insert( val2_ty(my_key_t(3), my_val_t(40)) ); multimap2.insert( val2_ty(my_key_t(10000), my_val_t(1)) ); my_key_t::init(); my_val_t::init(); test_encode_and_decode < multimap2_t >(multimap2); EXPECT_EQ(my_key_t::get_default_ctor(), 5); EXPECT_EQ(my_key_t::get_one_arg_ctor(), 0); EXPECT_EQ(my_key_t::get_copy_ctor(), 5); EXPECT_EQ(my_key_t::get_assigns(), 0); EXPECT_EQ(my_val_t::get_default_ctor(), 5); EXPECT_EQ(my_val_t::get_one_arg_ctor(), 0); EXPECT_EQ(my_val_t::get_copy_ctor(), 5); EXPECT_EQ(my_val_t::get_assigns(), 0); } namespace ceph { // make sure that the legacy encode/decode methods are selected // over the ones defined using templates. the later is likely to // be slower, see also the definition of "WRITE_INT_DENC" in // include/denc.h template<> void encode<uint64_t, denc_traits<uint64_t>>(const uint64_t&, bufferlist&, uint64_t f) { static_assert(denc_traits<uint64_t>::supported, "should support new encoder"); static_assert(!denc_traits<uint64_t>::featured, "should not be featured"); ASSERT_EQ(0UL, f); // make sure the test fails if i get called ASSERT_TRUE(false); } template<> void encode<ceph_le64, denc_traits<ceph_le64>>(const ceph_le64&, bufferlist&, uint64_t f) { static_assert(denc_traits<ceph_le64>::supported, "should support new encoder"); static_assert(!denc_traits<ceph_le64>::featured, "should not be featured"); ASSERT_EQ(0UL, f); // make sure the test fails if i get called ASSERT_TRUE(false); } } namespace { // search `underlying_type` in denc.h for supported underlying types enum class Colour : int8_t { R,G,B }; ostream& operator<<(ostream& os, Colour c) { switch (c) { case Colour::R: return os << "Colour::R"; case Colour::G: return os << "Colour::G"; case Colour::B: return os << "Colour::B"; default: return os << "Colour::???"; } } } TEST(EncodingRoundTrip, Integers) { // int types { uint64_t i = 42; test_encode_and_decode(i); } { int16_t i = 42; test_encode_and_decode(i); } { bool b = true; test_encode_and_decode(b); } { bool b = false; test_encode_and_decode(b); } // raw encoder { ceph_le64 i; i = 42; test_encode_and_decode(i); } // enum { test_encode_and_decode(Colour::R); // this should not build, as the size of unsigned is not the same on // different archs, that's why denc_traits<> intentionally leaves // `int` and `unsigned int` out of supported types. // // enum E { R, G, B }; // test_encode_and_decode(R); } } const char* expected_what[] = { "buffer::malformed_input: void lame_decoder(int) no longer understand old encoding version 100 < 200", "buffer::malformed_input: void lame_decoder(int) decode past end of struct encoding", }; void lame_decoder(int which) { switch (which) { case 0: throw buffer::malformed_input(DECODE_ERR_OLDVERSION(__PRETTY_FUNCTION__, 100, 200)); case 1: throw buffer::malformed_input(DECODE_ERR_PAST(__PRETTY_FUNCTION__)); } } TEST(EncodingException, Macros) { for (unsigned i = 0; i < sizeof(expected_what)/sizeof(expected_what[0]); i++) { try { lame_decoder(i); } catch (const exception& e) { ASSERT_EQ(string(expected_what[i]), string(e.what())); } } } TEST(small_encoding, varint) { uint32_t v[][4] = { /* value, varint bytes, signed varint bytes, signed varint bytes (neg) */ {0, 1, 1, 1}, {1, 1, 1, 1}, {2, 1, 1, 1}, {31, 1, 1, 1}, {32, 1, 1, 1}, {0xff, 2, 2, 2}, {0x100, 2, 2, 2}, {0xfff, 2, 2, 2}, {0x1000, 2, 2, 2}, {0x2000, 2, 3, 3}, {0x3fff, 2, 3, 3}, {0x4000, 3, 3, 3}, {0x4001, 3, 3, 3}, {0x10001, 3, 3, 3}, {0x20001, 3, 3, 3}, {0x40001, 3, 3, 3}, {0x80001, 3, 3, 3}, {0x7f0001, 4, 4, 4}, {0xff00001, 4, 5, 5}, {0x1ff00001, 5, 5, 5}, {0xffff0001, 5, 5, 5}, {0xffffffff, 5, 5, 5}, {1074790401, 5, 5, 5}, {0, 0, 0, 0} }; for (unsigned i=0; v[i][1]; ++i) { { bufferlist bl; { auto app = bl.get_contiguous_appender(16, true); denc_varint(v[i][0], app); } cout << std::hex << v[i][0] << "\t" << v[i][1] << "\t"; bl.hexdump(cout, false); cout << std::endl; ASSERT_EQ(bl.length(), v[i][1]); uint32_t u; auto p = bl.begin().get_current_ptr().cbegin(); denc_varint(u, p); ASSERT_EQ(v[i][0], u); } { bufferlist bl; { auto app = bl.get_contiguous_appender(16, true); denc_signed_varint(v[i][0], app); } cout << std::hex << v[i][0] << "\t" << v[i][2] << "\t"; bl.hexdump(cout, false); cout << std::endl; ASSERT_EQ(bl.length(), v[i][2]); int32_t u; auto p = bl.begin().get_current_ptr().cbegin(); denc_signed_varint(u, p); ASSERT_EQ((int32_t)v[i][0], u); } { bufferlist bl; int64_t x = -(int64_t)v[i][0]; { auto app = bl.get_contiguous_appender(16, true); denc_signed_varint(x, app); } cout << std::dec << x << std::hex << "\t" << v[i][3] << "\t"; bl.hexdump(cout, false); cout << std::endl; ASSERT_EQ(bl.length(), v[i][3]); int64_t u; auto p = bl.begin().get_current_ptr().cbegin(); denc_signed_varint(u, p); ASSERT_EQ(x, u); } } } TEST(small_encoding, varint_lowz) { uint32_t v[][4] = { /* value, bytes encoded */ {0, 1, 1, 1}, {1, 1, 1, 1}, {2, 1, 1, 1}, {15, 1, 1, 1}, {16, 1, 1, 1}, {31, 1, 2, 2}, {63, 2, 2, 2}, {64, 1, 1, 1}, {0xff, 2, 2, 2}, {0x100, 1, 1, 1}, {0x7ff, 2, 2, 2}, {0xfff, 2, 3, 3}, {0x1000, 1, 1, 1}, {0x4000, 1, 1, 1}, {0x8000, 1, 1, 1}, {0x10000, 1, 2, 2}, {0x20000, 2, 2, 2}, {0x40000, 2, 2, 2}, {0x80000, 2, 2, 2}, {0x7f0000, 2, 2, 2}, {0xffff0000, 4, 4, 4}, {0xffffffff, 5, 5, 5}, {0x41000000, 3, 4, 4}, {0, 0, 0, 0} }; for (unsigned i=0; v[i][1]; ++i) { { bufferlist bl; { auto app = bl.get_contiguous_appender(16, true); denc_varint_lowz(v[i][0], app); } cout << std::hex << v[i][0] << "\t" << v[i][1] << "\t"; bl.hexdump(cout, false); cout << std::endl; ASSERT_EQ(bl.length(), v[i][1]); uint32_t u; auto p = bl.begin().get_current_ptr().cbegin(); denc_varint_lowz(u, p); ASSERT_EQ(v[i][0], u); } { bufferlist bl; int64_t x = v[i][0]; { auto app = bl.get_contiguous_appender(16, true); denc_signed_varint_lowz(x, app); } cout << std::hex << x << "\t" << v[i][1] << "\t"; bl.hexdump(cout, false); cout << std::endl; ASSERT_EQ(bl.length(), v[i][2]); int64_t u; auto p = bl.begin().get_current_ptr().cbegin(); denc_signed_varint_lowz(u, p); ASSERT_EQ(x, u); } { bufferlist bl; int64_t x = -(int64_t)v[i][0]; { auto app = bl.get_contiguous_appender(16, true); denc_signed_varint_lowz(x, app); } cout << std::dec << x << "\t" << v[i][1] << "\t"; bl.hexdump(cout, false); cout << std::endl; ASSERT_EQ(bl.length(), v[i][3]); int64_t u; auto p = bl.begin().get_current_ptr().cbegin(); denc_signed_varint_lowz(u, p); ASSERT_EQ(x, u); } } } TEST(small_encoding, lba) { uint64_t v[][2] = { /* value, bytes encoded */ {0, 4}, {1, 4}, {0xff, 4}, {0x10000, 4}, {0x7f0000, 4}, {0xffff0000, 4}, {0x0fffffff, 4}, {0x1fffffff, 5}, {0xffffffff, 5}, {0x3fffffff000, 4}, {0x7fffffff000, 5}, {0x1fffffff0000, 4}, {0x3fffffff0000, 5}, {0xfffffff00000, 4}, {0x1fffffff00000, 5}, {0x41000000, 4}, {0, 0} }; for (unsigned i=0; v[i][1]; ++i) { bufferlist bl; { auto app = bl.get_contiguous_appender(16, true); denc_lba(v[i][0], app); } cout << std::hex << v[i][0] << "\t" << v[i][1] << "\t"; bl.hexdump(cout, false); cout << std::endl; ASSERT_EQ(bl.length(), v[i][1]); uint64_t u; auto p = bl.begin().get_current_ptr().cbegin(); denc_lba(u, p); ASSERT_EQ(v[i][0], u); } }
25.715867
104
0.595136
[ "model" ]
4f92633fb1098ae1f8c83f71d4221cc3bc75e4e0
17,507
cpp
C++
WickedEngine/wiHairParticle.cpp
jdswebb/WickedEngine
4972763039261d3bc8b66c3acdb31eb81f1c3718
[ "MIT" ]
null
null
null
WickedEngine/wiHairParticle.cpp
jdswebb/WickedEngine
4972763039261d3bc8b66c3acdb31eb81f1c3718
[ "MIT" ]
null
null
null
WickedEngine/wiHairParticle.cpp
jdswebb/WickedEngine
4972763039261d3bc8b66c3acdb31eb81f1c3718
[ "MIT" ]
null
null
null
#include "wiHairParticle.h" #include "wiRenderer.h" #include "wiResourceManager.h" #include "wiMath.h" #include "wiIntersect.h" #include "wiRandom.h" #include "shaders/ResourceMapping.h" #include "wiArchive.h" #include "shaders/ShaderInterop.h" #include "wiTextureHelper.h" #include "wiScene.h" #include "shaders/ShaderInterop_HairParticle.h" #include "wiBackLog.h" #include "wiEvent.h" #include "wiTimer.h" using namespace wiGraphics; namespace wiScene { static Shader vs; static Shader ps_prepass; static Shader ps; static Shader ps_simple; static Shader cs_simulate; static Shader cs_finishUpdate; static DepthStencilState dss_default, dss_equal; static RasterizerState rs, ncrs, wirers; static BlendState bs; static PipelineState PSO[RENDERPASS_COUNT]; static PipelineState PSO_wire; void wiHairParticle::UpdateCPU(const TransformComponent& transform, const MeshComponent& mesh, float dt) { world = transform.world; XMFLOAT3 _min = mesh.aabb.getMin(); XMFLOAT3 _max = mesh.aabb.getMax(); _max.x += length; _max.y += length; _max.z += length; _min.x -= length; _min.y -= length; _min.z -= length; aabb = AABB(_min, _max); aabb = aabb.transform(world); GraphicsDevice* device = wiGraphics::GetDevice(); if (_flags & REBUILD_BUFFERS || !constantBuffer.IsValid() || (strandCount * segmentCount) != simulationBuffer.GetDesc().size / sizeof(PatchSimulationData)) { _flags &= ~REBUILD_BUFFERS; regenerate_frame = true; GPUBufferDesc bd; bd.usage = Usage::DEFAULT; bd.bind_flags = BindFlag::SHADER_RESOURCE | BindFlag::UNORDERED_ACCESS; bd.misc_flags = ResourceMiscFlag::BUFFER_STRUCTURED; const uint32_t particleCount = strandCount * segmentCount; if (particleCount > 0) { bd.stride = sizeof(PatchSimulationData); bd.size = bd.stride * particleCount; device->CreateBuffer(&bd, nullptr, &simulationBuffer); device->SetName(&simulationBuffer, "simulationBuffer"); bd.misc_flags = ResourceMiscFlag::BUFFER_RAW; if (device->CheckCapability(GraphicsDeviceCapability::RAYTRACING)) { bd.misc_flags |= ResourceMiscFlag::RAY_TRACING; } bd.stride = sizeof(MeshComponent::Vertex_POS); bd.size = bd.stride * 4 * particleCount; device->CreateBuffer(&bd, nullptr, &vertexBuffer_POS[0]); device->SetName(&vertexBuffer_POS[0], "vertexBuffer_POS[0]"); device->CreateBuffer(&bd, nullptr, &vertexBuffer_POS[1]); device->SetName(&vertexBuffer_POS[1], "vertexBuffer_POS[1]"); bd.misc_flags = ResourceMiscFlag::BUFFER_RAW; bd.stride = sizeof(MeshComponent::Vertex_TEX); bd.size = bd.stride * 4 * particleCount; device->CreateBuffer(&bd, nullptr, &vertexBuffer_TEX); device->SetName(&vertexBuffer_TEX, "vertexBuffer_TEX"); bd.bind_flags = BindFlag::SHADER_RESOURCE; bd.misc_flags = ResourceMiscFlag::NONE; if (device->CheckCapability(GraphicsDeviceCapability::RAYTRACING)) { bd.misc_flags |= ResourceMiscFlag::RAY_TRACING; } bd.format = Format::R32_UINT; bd.stride = sizeof(uint); bd.size = bd.stride * 6 * particleCount; std::vector<uint> primitiveData(6 * particleCount); for (uint particleID = 0; particleID < particleCount; ++particleID) { uint v0 = particleID * 4; uint i0 = particleID * 6; primitiveData[i0 + 0] = v0 + 0; primitiveData[i0 + 1] = v0 + 1; primitiveData[i0 + 2] = v0 + 2; primitiveData[i0 + 3] = v0 + 2; primitiveData[i0 + 4] = v0 + 1; primitiveData[i0 + 5] = v0 + 3; } device->CreateBuffer(&bd, primitiveData.data(), &primitiveBuffer); device->SetName(&primitiveBuffer, "primitiveBuffer"); bd.bind_flags = BindFlag::INDEX_BUFFER | BindFlag::UNORDERED_ACCESS; bd.misc_flags = ResourceMiscFlag::NONE; bd.format = Format::R32_UINT; bd.stride = sizeof(uint); bd.size = bd.stride * 6 * particleCount; device->CreateBuffer(&bd, nullptr, &culledIndexBuffer); device->SetName(&culledIndexBuffer, "culledIndexBuffer"); } bd.usage = Usage::DEFAULT; bd.size = sizeof(HairParticleCB); bd.bind_flags = BindFlag::CONSTANT_BUFFER; bd.misc_flags = ResourceMiscFlag::NONE; device->CreateBuffer(&bd, nullptr, &constantBuffer); device->SetName(&constantBuffer, "constantBuffer"); if (vertex_lengths.size() != mesh.vertex_positions.size()) { vertex_lengths.resize(mesh.vertex_positions.size()); std::fill(vertex_lengths.begin(), vertex_lengths.end(), 1.0f); } indices.clear(); for (size_t j = 0; j < mesh.indices.size(); j += 3) { const uint32_t triangle[] = { mesh.indices[j + 0], mesh.indices[j + 1], mesh.indices[j + 2], }; if (vertex_lengths[triangle[0]] > 0 || vertex_lengths[triangle[1]] > 0 || vertex_lengths[triangle[2]] > 0) { indices.push_back(triangle[0]); indices.push_back(triangle[1]); indices.push_back(triangle[2]); } } if (!vertex_lengths.empty()) { std::vector<uint8_t> ulengths; ulengths.reserve(vertex_lengths.size()); for (auto& x : vertex_lengths) { ulengths.push_back(uint8_t(wiMath::Clamp(x, 0, 1) * 255.0f)); } bd.misc_flags = ResourceMiscFlag::NONE; bd.bind_flags = BindFlag::SHADER_RESOURCE; bd.format = Format::R8_UNORM; bd.stride = sizeof(uint8_t); bd.size = bd.stride * (uint32_t)ulengths.size(); device->CreateBuffer(&bd, ulengths.data(), &vertexBuffer_length); } if (!indices.empty()) { bd.misc_flags = ResourceMiscFlag::NONE; bd.bind_flags = BindFlag::SHADER_RESOURCE; bd.format = Format::R32_UINT; bd.stride = sizeof(uint32_t); bd.size = bd.stride * (uint32_t)indices.size(); device->CreateBuffer(&bd, indices.data(), &indexBuffer); } if (device->CheckCapability(GraphicsDeviceCapability::RAYTRACING) && primitiveBuffer.IsValid()) { RaytracingAccelerationStructureDesc desc; desc.type = RaytracingAccelerationStructureDesc::Type::BOTTOMLEVEL; desc.flags |= RaytracingAccelerationStructureDesc::FLAG_ALLOW_UPDATE; desc.flags |= RaytracingAccelerationStructureDesc::FLAG_PREFER_FAST_BUILD; desc.bottom_level.geometries.emplace_back(); auto& geometry = desc.bottom_level.geometries.back(); geometry.type = RaytracingAccelerationStructureDesc::BottomLevel::Geometry::Type::TRIANGLES; geometry.triangles.vertex_buffer = vertexBuffer_POS[0]; geometry.triangles.index_buffer = primitiveBuffer; geometry.triangles.index_format = IndexBufferFormat::UINT32; geometry.triangles.index_count = (uint32_t)(primitiveBuffer.desc.size / primitiveBuffer.desc.stride); geometry.triangles.index_offset = 0; geometry.triangles.vertex_count = (uint32_t)(vertexBuffer_POS[0].desc.size / vertexBuffer_POS[0].desc.stride); geometry.triangles.vertex_format = Format::R32G32B32_FLOAT; geometry.triangles.vertex_stride = sizeof(MeshComponent::Vertex_POS); bool success = device->CreateRaytracingAccelerationStructure(&desc, &BLAS); assert(success); device->SetName(&BLAS, "BLAS_hair"); } } if (!indirectBuffer.IsValid()) { GPUBufferDesc desc; desc.size = sizeof(uint) + sizeof(IndirectDrawArgsIndexedInstanced); // counter + draw args desc.misc_flags = ResourceMiscFlag::BUFFER_RAW | ResourceMiscFlag::INDIRECT_ARGS; desc.bind_flags = BindFlag::UNORDERED_ACCESS; device->CreateBuffer(&desc, nullptr, &indirectBuffer); } if (!subsetBuffer.IsValid()) { GPUBufferDesc desc; desc.stride = sizeof(ShaderMeshSubset); desc.size = desc.stride; desc.misc_flags = ResourceMiscFlag::BUFFER_RAW; desc.bind_flags = BindFlag::SHADER_RESOURCE; device->CreateBuffer(&desc, nullptr, &subsetBuffer); } std::swap(vertexBuffer_POS[0], vertexBuffer_POS[1]); if (BLAS.IsValid() && !BLAS.desc.bottom_level.geometries.empty()) { BLAS.desc.bottom_level.geometries.back().triangles.vertex_buffer = vertexBuffer_POS[0]; } } void wiHairParticle::UpdateGPU(uint32_t instanceIndex, uint32_t materialIndex, const MeshComponent& mesh, const MaterialComponent& material, CommandList cmd) const { if (strandCount == 0 || !simulationBuffer.IsValid()) { return; } GraphicsDevice* device = wiGraphics::GetDevice(); device->EventBegin("HairParticle - UpdateGPU", cmd); TextureDesc desc; if (material.textures[MaterialComponent::BASECOLORMAP].resource != nullptr) { desc = material.textures[MaterialComponent::BASECOLORMAP].resource->texture.GetDesc(); } HairParticleCB hcb; hcb.xHairWorld = world; hcb.xHairRegenerate = regenerate_frame ? 1 : 0; hcb.xLength = length; hcb.xStiffness = stiffness; hcb.xHairRandomness = randomness; hcb.xHairStrandCount = strandCount; hcb.xHairSegmentCount = std::max(segmentCount, 1u); hcb.xHairParticleCount = hcb.xHairStrandCount * hcb.xHairSegmentCount; hcb.xHairRandomSeed = randomSeed; hcb.xHairViewDistance = viewDistance; hcb.xHairBaseMeshIndexCount = (indices.empty() ? (uint)mesh.indices.size() : (uint)indices.size()); hcb.xHairBaseMeshVertexPositionStride = sizeof(MeshComponent::Vertex_POS); // segmentCount will be loop in the shader, not a threadgroup so we don't need it here: hcb.xHairNumDispatchGroups = (hcb.xHairParticleCount + THREADCOUNT_SIMULATEHAIR - 1) / THREADCOUNT_SIMULATEHAIR; hcb.xHairFramesXY = uint2(std::max(1u, framesX), std::max(1u, framesY)); hcb.xHairFrameCount = std::max(1u, frameCount); hcb.xHairFrameStart = frameStart; hcb.xHairTexMul = float2(1.0f / (float)hcb.xHairFramesXY.x, 1.0f / (float)hcb.xHairFramesXY.y); hcb.xHairAspect = (float)std::max(1u, desc.width) / (float)std::max(1u, desc.height); hcb.xHairLayerMask = layerMask; hcb.xHairInstanceIndex = instanceIndex; device->UpdateBuffer(&constantBuffer, &hcb, cmd); ShaderMeshSubset subset; subset.init(); subset.indexOffset = 0; subset.materialIndex = materialIndex; device->UpdateBuffer(&subsetBuffer, &subset, cmd); { GPUBarrier barriers[] = { GPUBarrier::Buffer(&constantBuffer, ResourceState::COPY_DST, ResourceState::CONSTANT_BUFFER), GPUBarrier::Buffer(&subsetBuffer, ResourceState::COPY_DST, ResourceState::SHADER_RESOURCE), }; device->Barrier(barriers, arraysize(barriers), cmd); } // Simulate: { device->BindComputeShader(&cs_simulate, cmd); device->BindConstantBuffer(&constantBuffer, CB_GETBINDSLOT(HairParticleCB), cmd); const GPUResource* uavs[] = { &simulationBuffer, &vertexBuffer_POS[0], &vertexBuffer_TEX, &culledIndexBuffer, &indirectBuffer }; device->BindUAVs(uavs, 0, arraysize(uavs), cmd); const GPUResource* res[] = { indexBuffer.IsValid() ? &indexBuffer : &mesh.indexBuffer, mesh.streamoutBuffer_POS.IsValid() ? &mesh.streamoutBuffer_POS : &mesh.vertexBuffer_POS, &vertexBuffer_length }; device->BindResources(res, TEXSLOT_ONDEMAND0, arraysize(res), cmd); device->Dispatch(hcb.xHairNumDispatchGroups, 1, 1, cmd); GPUBarrier barriers[] = { GPUBarrier::Memory() }; device->Barrier(barriers, arraysize(barriers), cmd); } // Finish update (reset counter, create indirect draw args): { device->BindComputeShader(&cs_finishUpdate, cmd); const GPUResource* uavs[] = { &indirectBuffer }; device->BindUAVs(uavs, 0, arraysize(uavs), cmd); device->Dispatch(1, 1, 1, cmd); GPUBarrier barriers[] = { GPUBarrier::Memory(&indirectBuffer), GPUBarrier::Buffer(&indirectBuffer, ResourceState::UNORDERED_ACCESS, ResourceState::INDIRECT_ARGUMENT), GPUBarrier::Buffer(&vertexBuffer_POS[0], ResourceState::UNORDERED_ACCESS, ResourceState::SHADER_RESOURCE), GPUBarrier::Buffer(&vertexBuffer_TEX, ResourceState::UNORDERED_ACCESS, ResourceState::SHADER_RESOURCE), GPUBarrier::Buffer(&culledIndexBuffer, ResourceState::UNORDERED_ACCESS, ResourceState::INDEX_BUFFER), }; device->Barrier(barriers, arraysize(barriers), cmd); } device->EventEnd(cmd); regenerate_frame = false; } void wiHairParticle::Draw(const MaterialComponent& material, RENDERPASS renderPass, CommandList cmd) const { if (strandCount == 0 || !constantBuffer.IsValid()) { return; } GraphicsDevice* device = wiGraphics::GetDevice(); device->EventBegin("HairParticle - Draw", cmd); device->BindStencilRef(STENCILREF_DEFAULT, cmd); if (wiRenderer::IsWireRender()) { if (renderPass == RENDERPASS_PREPASS) { return; } device->BindPipelineState(&PSO_wire, cmd); device->BindResource(wiTextureHelper::getWhite(), TEXSLOT_ONDEMAND0, cmd); } else { device->BindPipelineState(&PSO[renderPass], cmd); if (renderPass != RENDERPASS_PREPASS) // depth only alpha test will be full res { device->BindShadingRate(material.shadingRate, cmd); } } device->BindConstantBuffer(&constantBuffer, CB_GETBINDSLOT(HairParticleCB), cmd); device->BindResource(&primitiveBuffer, 0, cmd); device->BindIndexBuffer(&culledIndexBuffer, IndexBufferFormat::UINT32, 0, cmd); device->DrawIndexedInstancedIndirect(&indirectBuffer, 4, cmd); device->EventEnd(cmd); } void wiHairParticle::Serialize(wiArchive& archive, wiECS::EntitySerializer& seri) { if (archive.IsReadMode()) { archive >> _flags; wiECS::SerializeEntity(archive, meshID, seri); archive >> strandCount; archive >> segmentCount; archive >> randomSeed; archive >> length; archive >> stiffness; archive >> randomness; archive >> viewDistance; if (archive.GetVersion() >= 39) { archive >> vertex_lengths; } if (archive.GetVersion() >= 42) { archive >> framesX; archive >> framesY; archive >> frameCount; archive >> frameStart; } if (archive.GetVersion() == 48) { uint8_t shadingRate; archive >> shadingRate; // no longer needed } } else { archive << _flags; wiECS::SerializeEntity(archive, meshID, seri); archive << strandCount; archive << segmentCount; archive << randomSeed; archive << length; archive << stiffness; archive << randomness; archive << viewDistance; if (archive.GetVersion() >= 39) { archive << vertex_lengths; } if (archive.GetVersion() >= 42) { archive << framesX; archive << framesY; archive << frameCount; archive << frameStart; } } } namespace wiHairParticle_Internal { void LoadShaders() { wiRenderer::LoadShader(ShaderStage::VS, vs, "hairparticleVS.cso"); wiRenderer::LoadShader(ShaderStage::PS, ps_simple, "hairparticlePS_simple.cso"); wiRenderer::LoadShader(ShaderStage::PS, ps_prepass, "hairparticlePS_prepass.cso"); wiRenderer::LoadShader(ShaderStage::PS, ps, "hairparticlePS.cso"); wiRenderer::LoadShader(ShaderStage::CS, cs_simulate, "hairparticle_simulateCS.cso"); wiRenderer::LoadShader(ShaderStage::CS, cs_finishUpdate, "hairparticle_finishUpdateCS.cso"); GraphicsDevice* device = wiGraphics::GetDevice(); for (int i = 0; i < RENDERPASS_COUNT; ++i) { if (i == RENDERPASS_PREPASS || i == RENDERPASS_MAIN) { PipelineStateDesc desc; desc.vs = &vs; desc.bs = &bs; desc.rs = &ncrs; desc.dss = &dss_default; desc.pt = PrimitiveTopology::TRIANGLELIST; switch (i) { case RENDERPASS_PREPASS: desc.ps = &ps_prepass; break; case RENDERPASS_MAIN: desc.ps = &ps; desc.dss = &dss_equal; break; } device->CreatePipelineState(&desc, &PSO[i]); } } { PipelineStateDesc desc; desc.vs = &vs; desc.ps = &ps_simple; desc.bs = &bs; desc.rs = &wirers; desc.dss = &dss_default; desc.pt = PrimitiveTopology::TRIANGLELIST; device->CreatePipelineState(&desc, &PSO_wire); } } } void wiHairParticle::Initialize() { wiTimer timer; RasterizerState rsd; rsd.fill_mode = FillMode::SOLID; rsd.cull_mode = CullMode::BACK; rsd.front_counter_clockwise = true; rsd.depth_bias = 0; rsd.depth_bias_clamp = 0; rsd.slope_scaled_depth_bias = 0; rsd.depth_clip_enable = true; rsd.multisample_enable = false; rsd.antialiased_line_enable = false; rs = rsd; rsd.fill_mode = FillMode::SOLID; rsd.cull_mode = CullMode::NONE; rsd.front_counter_clockwise = true; rsd.depth_bias = 0; rsd.depth_bias_clamp = 0; rsd.slope_scaled_depth_bias = 0; rsd.depth_clip_enable = true; rsd.multisample_enable = false; rsd.antialiased_line_enable = false; ncrs = rsd; rsd.fill_mode = FillMode::WIREFRAME; rsd.cull_mode = CullMode::NONE; rsd.front_counter_clockwise = true; rsd.depth_bias = 0; rsd.depth_bias_clamp = 0; rsd.slope_scaled_depth_bias = 0; rsd.depth_clip_enable = true; rsd.multisample_enable = false; rsd.antialiased_line_enable = false; wirers = rsd; DepthStencilState dsd; dsd.depth_enable = true; dsd.depth_write_mask = DepthWriteMask::ALL; dsd.depth_func = ComparisonFunc::GREATER; dsd.stencil_enable = true; dsd.stencil_read_mask = 0xFF; dsd.stencil_write_mask = 0xFF; dsd.front_face.stencil_func = ComparisonFunc::ALWAYS; dsd.front_face.stencil_pass_op = StencilOp::REPLACE; dsd.front_face.stencil_fail_op = StencilOp::KEEP; dsd.front_face.stencil_depth_fail_op = StencilOp::KEEP; dsd.back_face.stencil_func = ComparisonFunc::ALWAYS; dsd.back_face.stencil_pass_op = StencilOp::REPLACE; dsd.back_face.stencil_fail_op = StencilOp::KEEP; dsd.back_face.stencil_depth_fail_op = StencilOp::KEEP; dss_default = dsd; dsd.depth_write_mask = DepthWriteMask::ZERO; dsd.depth_func = ComparisonFunc::EQUAL; dsd.stencil_enable = false; dss_equal = dsd; BlendState bld; bld.render_target[0].blend_enable = false; bld.alpha_to_coverage_enable = false; // maybe for msaa bs = bld; static wiEvent::Handle handle = wiEvent::Subscribe(SYSTEM_EVENT_RELOAD_SHADERS, [](uint64_t userdata) { wiHairParticle_Internal::LoadShaders(); }); wiHairParticle_Internal::LoadShaders(); wiBackLog::post("wiHairParticle Initialized (" + std::to_string((int)std::round(timer.elapsed())) + " ms)"); } }
30.768014
163
0.726452
[ "mesh", "geometry", "vector", "transform", "solid" ]
4f94724eef8c0ae2aadcc56fae93a44affe96707
1,039
hpp
C++
third_party/boost/simd/function/is_not_nan.hpp
xmar/pythran
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
[ "BSD-3-Clause" ]
5
2018-02-20T11:21:12.000Z
2019-11-12T13:45:09.000Z
third_party/boost/simd/function/is_not_nan.hpp
xmar/pythran
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
[ "BSD-3-Clause" ]
null
null
null
third_party/boost/simd/function/is_not_nan.hpp
xmar/pythran
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
[ "BSD-3-Clause" ]
2
2017-12-12T12:29:52.000Z
2019-04-08T15:55:25.000Z
//================================================================================================== /*! @file @copyright 2016 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_FUNCTION_IS_NOT_NAN_HPP_INCLUDED #define BOOST_SIMD_FUNCTION_IS_NOT_NAN_HPP_INCLUDED #if defined(DOXYGEN_ONLY) namespace boost { namespace simd { /*! @ingroup group-predicates Function object implementing is_not_nan capabilities Returns @ref False or @ref True according x is @ref Nan or not. @par Semantic: @code auto r = is_not_nan(x); @endcode is similar to: @code auto r = x == x; @endcode **/ as_logical_t<Value> is_not_nan(Value const& x); } } #endif #include <boost/simd/function/scalar/is_not_nan.hpp> #include <boost/simd/function/simd/is_not_nan.hpp> #endif
22.586957
100
0.577478
[ "object" ]
4f95ea1933aba35fcbb216c6293723200a3baec1
4,048
cpp
C++
src/beast/beast/module/core/system/SystemStats.cpp
globalpaylab/GLPd
83bf1c224037a21a06835c16fffc33b017783f10
[ "BSL-1.0" ]
2
2019-05-26T15:10:15.000Z
2019-06-15T10:18:41.000Z
src/beast/beast/module/core/system/SystemStats.cpp
globalpaylab/GLPd
83bf1c224037a21a06835c16fffc33b017783f10
[ "BSL-1.0" ]
null
null
null
src/beast/beast/module/core/system/SystemStats.cpp
globalpaylab/GLPd
83bf1c224037a21a06835c16fffc33b017783f10
[ "BSL-1.0" ]
3
2017-06-29T02:41:16.000Z
2021-08-28T07:42:24.000Z
//------------------------------------------------------------------------------ /* This file is part of Beast: https://github.com/vinniefalco/Beast Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com> Portions of this file are from JUCE. Copyright (c) 2013 - Raw Material Software Ltd. Please visit http://www.juce.com Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #include <cstdlib> #include <iterator> #include <memory> // Some basic tests, to keep an eye on things and make sure these types work ok // on all platforms. static_assert (sizeof (std::intptr_t) == sizeof (void*), "std::intptr_t must be the same size as void*"); static_assert (sizeof (std::int8_t) == 1, "std::int8_t must be exactly 1 byte!"); static_assert (sizeof (std::int16_t) == 2, "std::int16_t must be exactly 2 bytes!"); static_assert (sizeof (std::int32_t) == 4, "std::int32_t must be exactly 4 bytes!"); static_assert (sizeof (std::int64_t) == 8, "std::int64_t must be exactly 8 bytes!"); static_assert (sizeof (std::uint8_t) == 1, "std::uint8_t must be exactly 1 byte!"); static_assert (sizeof (std::uint16_t) == 2, "std::uint16_t must be exactly 2 bytes!"); static_assert (sizeof (std::uint32_t) == 4, "std::uint32_t must be exactly 4 bytes!"); static_assert (sizeof (std::uint64_t) == 8, "std::uint64_t must be exactly 8 bytes!"); namespace beast { //============================================================================== std::vector <std::string> getStackBacktrace() { std::vector <std::string> result; #if BEAST_ANDROID || BEAST_MINGW || BEAST_BSD bassertfalse; // sorry, not implemented yet! #elif BEAST_WINDOWS HANDLE process = GetCurrentProcess(); SymInitialize (process, nullptr, TRUE); void* stack[128]; int frames = (int) CaptureStackBackTrace (0, std::distance(std::begin(stack), std::end(stack)), stack, nullptr); HeapBlock<SYMBOL_INFO> symbol; symbol.calloc (sizeof (SYMBOL_INFO) + 256, 1); symbol->MaxNameLen = 255; symbol->SizeOfStruct = sizeof (SYMBOL_INFO); for (int i = 0; i < frames; ++i) { DWORD64 displacement = 0; if (SymFromAddr (process, (DWORD64) stack[i], &displacement, symbol)) { std::string frame; frame.append (std::to_string (i) + ": "); IMAGEHLP_MODULE64 moduleInfo; zerostruct (moduleInfo); moduleInfo.SizeOfStruct = sizeof (moduleInfo); if (::SymGetModuleInfo64 (process, symbol->ModBase, &moduleInfo)) { frame.append (moduleInfo.ModuleName); frame.append (": "); } frame.append (symbol->Name); if (displacement) { frame.append ("+"); frame.append (std::to_string (displacement)); } result.push_back (frame); } } #else void* stack[128]; int frames = backtrace (stack, std::distance(std::begin(stack), std::end(stack))); std::unique_ptr<char*[], void(*)(void*)> frame ( backtrace_symbols (stack, frames), std::free); for (int i = 0; i < frames; ++i) result.push_back (frame[i]); #endif return result; } } // beast
34.896552
105
0.603508
[ "vector" ]
4f9bd78f5421c25ee7d035988496c3562bd2d57a
5,453
cpp
C++
sources/libClangSharp/CXType.cpp
kant2002/ClangSharp
be69d0b7d2a9a84ea8dbd6f3198977a202b96c2c
[ "NCSA" ]
1
2021-11-22T17:48:53.000Z
2021-11-22T17:48:53.000Z
sources/libClangSharp/CXType.cpp
hermann-noll/ClangSharp
13191c279203ae7b3d7614a6927f05e0fd7d0b0d
[ "NCSA" ]
1
2021-09-07T23:03:56.000Z
2021-09-07T23:03:56.000Z
sources/libClangSharp/CXType.cpp
LaudateCorpus1/ClangSharp
84e5f96b45f543422b593b7ccf5d3493bc807031
[ "NCSA" ]
null
null
null
// Copyright (c) Microsoft and Contributors. All rights reserved. Licensed under the University of Illinois/NCSA Open Source License. See LICENSE.txt in the project root for license information. // Ported from https://github.com/llvm/llvm-project/tree/llvmorg-12.0.0/clang/tools/libclang // Original source is Copyright (c) the LLVM Project and Contributors. Licensed under the Apache License v2.0 with LLVM Exceptions. See NOTICE.txt in the project root for license information. #include "ClangSharp.h" #include "CXTranslationUnit.h" #include "CXType.h" using namespace clang; QualType GetQualType(CXType CT) { return QualType::getFromOpaquePtr(CT.data[0]); } CXTranslationUnit GetTypeTU(CXType CT) { return static_cast<CXTranslationUnit>(CT.data[1]); } namespace clang::cxtype { static CXTypeKind GetBuiltinTypeKind(const BuiltinType* BT) { #define BTCASE(K) case BuiltinType::K: return CXType_##K switch (BT->getKind()) { BTCASE(Void); BTCASE(Bool); BTCASE(Char_U); BTCASE(UChar); BTCASE(Char16); BTCASE(Char32); BTCASE(UShort); BTCASE(UInt); BTCASE(ULong); BTCASE(ULongLong); BTCASE(UInt128); BTCASE(Char_S); BTCASE(SChar); case BuiltinType::WChar_S: return CXType_WChar; case BuiltinType::WChar_U: return CXType_WChar; BTCASE(Short); BTCASE(Int); BTCASE(Long); BTCASE(LongLong); BTCASE(Int128); BTCASE(Half); BTCASE(Float); BTCASE(Double); BTCASE(LongDouble); BTCASE(ShortAccum); BTCASE(Accum); BTCASE(LongAccum); BTCASE(UShortAccum); BTCASE(UAccum); BTCASE(ULongAccum); BTCASE(Float16); BTCASE(Float128); BTCASE(NullPtr); BTCASE(Overload); BTCASE(Dependent); BTCASE(ObjCId); BTCASE(ObjCClass); BTCASE(ObjCSel); #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) BTCASE(Id); #include "clang/Basic/OpenCLImageTypes.def" #undef IMAGE_TYPE #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) BTCASE(Id); #include "clang/Basic/OpenCLExtensionTypes.def" BTCASE(OCLSampler); BTCASE(OCLEvent); BTCASE(OCLQueue); BTCASE(OCLReserveID); default: return CXType_Unexposed; } #undef BTCASE } static CXTypeKind GetTypeKind(QualType T) { const Type* TP = T.getTypePtrOrNull(); if (!TP) return CXType_Invalid; #define TKCASE(K) case Type::K: return CXType_##K switch (TP->getTypeClass()) { case Type::Builtin: return GetBuiltinTypeKind(cast<BuiltinType>(TP)); TKCASE(Complex); TKCASE(Pointer); TKCASE(BlockPointer); TKCASE(LValueReference); TKCASE(RValueReference); TKCASE(Record); TKCASE(Enum); TKCASE(Typedef); TKCASE(ObjCInterface); TKCASE(ObjCObject); TKCASE(ObjCObjectPointer); TKCASE(ObjCTypeParam); TKCASE(FunctionNoProto); TKCASE(FunctionProto); TKCASE(ConstantArray); TKCASE(IncompleteArray); TKCASE(VariableArray); TKCASE(DependentSizedArray); TKCASE(Vector); TKCASE(ExtVector); TKCASE(MemberPointer); TKCASE(Auto); TKCASE(Elaborated); TKCASE(Pipe); TKCASE(Attributed); TKCASE(Atomic); default: return CXType_Unexposed; } #undef TKCASE } CXType MakeCXType(QualType T, CXTranslationUnit TU) { CXTypeKind TK = CXType_Invalid; if (TU && !T.isNull()) { // Handle attributed types as the original type if (auto* ATT = T->getAs<AttributedType>()) { if (!(TU->ParsingOptions & CXTranslationUnit_IncludeAttributedTypes)) { // Return the equivalent type which represents the canonically // equivalent type. return MakeCXType(ATT->getEquivalentType(), TU); } } // Handle paren types as the original type if (auto* PTT = T->getAs<ParenType>()) { return MakeCXType(PTT->getInnerType(), TU); } ASTContext& Ctx = cxtu::getASTUnit(TU)->getASTContext(); if (Ctx.getLangOpts().ObjC) { QualType UnqualT = T.getUnqualifiedType(); if (Ctx.isObjCIdType(UnqualT)) TK = CXType_ObjCId; else if (Ctx.isObjCClassType(UnqualT)) TK = CXType_ObjCClass; else if (Ctx.isObjCSelType(UnqualT)) TK = CXType_ObjCSel; } /* Handle decayed types as the original type */ if (const DecayedType* DT = T->getAs<DecayedType>()) { return MakeCXType(DT->getOriginalType(), TU); } } if (TK == CXType_Invalid) TK = GetTypeKind(T); CXType CT = { TK, { TK == CXType_Invalid ? nullptr : T.getAsOpaquePtr(), TU } }; return CT; } }
34.295597
194
0.559142
[ "vector" ]
4f9c5f9061b34f52754a58c373a9df2ef7bb2530
30,833
cc
C++
chrome/browser/printing/print_dialog_cloud.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
4
2017-04-05T01:51:34.000Z
2018-02-15T03:11:54.000Z
chrome/browser/printing/print_dialog_cloud.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-12-13T19:44:12.000Z
2021-12-13T19:44:12.000Z
chrome/browser/printing/print_dialog_cloud.cc
nagineni/chromium-crosswalk
5725642f1c67d0f97e8613ec1c3e8107ab53fdf8
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
4
2017-04-05T01:52:03.000Z
2022-02-13T17:58:45.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/printing/print_dialog_cloud.h" #include "base/base64.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" #include "base/file_util.h" #include "base/json/json_reader.h" #include "base/prefs/pref_service.h" #include "base/strings/utf_string_conversions.h" #include "base/values.h" #include "chrome/browser/devtools/devtools_window.h" #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/browser/printing/cloud_print/cloud_print_url.h" #include "chrome/browser/printing/print_dialog_cloud_internal.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/browser_dialogs.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/common/print_messages.h" #include "chrome/common/url_constants.h" #include "components/user_prefs/pref_registry_syncable.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/navigation_controller.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/notification_registrar.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/web_contents_view.h" #include "content/public/browser/web_ui.h" #include "grit/generated_resources.h" #include "ui/base/l10n/l10n_util.h" #include "webkit/common/webpreferences.h" #if defined(USE_AURA) #include "ui/aura/root_window.h" #include "ui/aura/window.h" #endif #if defined(OS_WIN) #include "ui/base/win/foreground_helper.h" #endif // This module implements the UI support in Chrome for cloud printing. // This means hosting a dialog containing HTML/JavaScript and using // the published cloud print user interface integration APIs to get // page setup settings from the dialog contents and provide the // generated print data to the dialog contents for uploading to the // cloud print service. // Currently, the flow between these classes is as follows: // PrintDialogCloud::CreatePrintDialogForFile is called from // resource_message_filter_gtk.cc once the renderer has informed the // renderer host that print data generation into the renderer host provided // temp file has been completed. That call is on the FILE thread. // That, in turn, hops over to the UI thread to create an instance of // PrintDialogCloud. // The constructor for PrintDialogCloud creates a // CloudPrintWebDialogDelegate and asks the current active browser to // show an HTML dialog using that class as the delegate. That class // hands in the kChromeUICloudPrintResourcesURL as the URL to visit. That is // recognized by the GetWebUIFactoryFunction as a signal to create an // ExternalWebDialogUI. // CloudPrintWebDialogDelegate also temporarily owns a // CloudPrintFlowHandler, a class which is responsible for the actual // interactions with the dialog contents, including handing in the // print data and getting any page setup parameters that the dialog // contents provides. As part of bringing up the dialog, // WebDialogUI::RenderViewCreated is called (an override of // WebUI::RenderViewCreated). That routine, in turn, calls the // delegate's GetWebUIMessageHandlers routine, at which point the // ownership of the CloudPrintFlowHandler is handed over. A pointer // to the flow handler is kept to facilitate communication back and // forth between the two classes. // The WebUI continues dialog bring-up, calling // CloudPrintFlowHandler::RegisterMessages. This is where the // additional object model capabilities are registered for the dialog // contents to use. It is also at this time that capabilities for the // dialog contents are adjusted to allow the dialog contents to close // the window. In addition, the pending URL is redirected to the // actual cloud print service URL. The flow controller also registers // for notification of when the dialog contents finish loading, which // is currently used to send the data to the dialog contents. // In order to send the data to the dialog contents, the flow // handler uses a CloudPrintDataSender. It creates one, letting it // know the name of the temporary file containing the data, and // posts the task of reading the file // (CloudPrintDataSender::ReadPrintDataFile) to the file thread. That // routine reads in the file, and then hops over to the IO thread to // send that data to the dialog contents. // When the dialog contents are finished (by either being cancelled or // hitting the print button), the delegate is notified, and responds // that the dialog should be closed, at which point things are torn // down and released. using content::BrowserThread; using content::NavigationController; using content::NavigationEntry; using content::RenderViewHost; using content::WebContents; using content::WebUIMessageHandler; using ui::WebDialogDelegate; const int kDefaultWidth = 912; const int kDefaultHeight = 633; namespace internal_cloud_print_helpers { // From the JSON parsed value, get the entries for the page setup // parameters. bool GetPageSetupParameters(const std::string& json, PrintMsg_Print_Params& parameters) { scoped_ptr<Value> parsed_value(base::JSONReader::Read(json)); DLOG_IF(ERROR, (!parsed_value.get() || !parsed_value->IsType(Value::TYPE_DICTIONARY))) << "PageSetup call didn't have expected contents"; if (!parsed_value.get() || !parsed_value->IsType(Value::TYPE_DICTIONARY)) return false; bool result = true; DictionaryValue* params = static_cast<DictionaryValue*>(parsed_value.get()); result &= params->GetDouble("dpi", &parameters.dpi); result &= params->GetDouble("min_shrink", &parameters.min_shrink); result &= params->GetDouble("max_shrink", &parameters.max_shrink); result &= params->GetBoolean("selection_only", &parameters.selection_only); return result; } string16 GetSwitchValueString16(const CommandLine& command_line, const char* switchName) { #if defined(OS_WIN) CommandLine::StringType native_switch_val; native_switch_val = command_line.GetSwitchValueNative(switchName); return string16(native_switch_val); #elif defined(OS_POSIX) // POSIX Command line string types are different. CommandLine::StringType native_switch_val; native_switch_val = command_line.GetSwitchValueASCII(switchName); // Convert the ASCII string to UTF16 to prepare to pass. return string16(ASCIIToUTF16(native_switch_val)); #endif } void CloudPrintDataSenderHelper::CallJavascriptFunction( const std::wstring& function_name) { web_ui_->CallJavascriptFunction(WideToASCII(function_name)); } void CloudPrintDataSenderHelper::CallJavascriptFunction( const std::wstring& function_name, const Value& arg) { web_ui_->CallJavascriptFunction(WideToASCII(function_name), arg); } void CloudPrintDataSenderHelper::CallJavascriptFunction( const std::wstring& function_name, const Value& arg1, const Value& arg2) { web_ui_->CallJavascriptFunction(WideToASCII(function_name), arg1, arg2); } void CloudPrintDataSenderHelper::CallJavascriptFunction( const std::wstring& function_name, const Value& arg1, const Value& arg2, const Value& arg3) { web_ui_->CallJavascriptFunction( WideToASCII(function_name), arg1, arg2, arg3); } // Clears out the pointer we're using to communicate. Either routine is // potentially expensive enough that stopping whatever is in progress // is worth it. void CloudPrintDataSender::CancelPrintDataFile() { base::AutoLock lock(lock_); // We don't own helper, it was passed in to us, so no need to // delete, just let it go. helper_ = NULL; } CloudPrintDataSender::CloudPrintDataSender(CloudPrintDataSenderHelper* helper, const string16& print_job_title, const string16& print_ticket, const std::string& file_type, const base::RefCountedMemory* data) : helper_(helper), print_job_title_(print_job_title), print_ticket_(print_ticket), file_type_(file_type), data_(data) { } CloudPrintDataSender::~CloudPrintDataSender() {} // We have the data in hand that needs to be pushed into the dialog // contents; do so from the IO thread. // TODO(scottbyer): If the print data ends up being larger than the // upload limit (currently 10MB), what we need to do is upload that // large data to google docs and set the URL in the printing // JavaScript to that location, and make sure it gets deleted when not // needed. - 4/1/2010 void CloudPrintDataSender::SendPrintData() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); if (!data_.get() || !data_->size()) return; std::string base64_data; base::Base64Encode( base::StringPiece(reinterpret_cast<const char*>(data_->front()), data_->size()), &base64_data); std::string header("data:"); header.append(file_type_); header.append(";base64,"); base64_data.insert(0, header); base::AutoLock lock(lock_); if (helper_) { StringValue title(print_job_title_); StringValue ticket(print_ticket_); // TODO(abodenha): Change Javascript call to pass in print ticket // after server side support is added. Add test for it. // Send the print data to the dialog contents. The JavaScript // function is a preliminary API for prototyping purposes and is // subject to change. const_cast<CloudPrintDataSenderHelper*>(helper_)->CallJavascriptFunction( L"printApp._printDataUrl", StringValue(base64_data), title); } } CloudPrintFlowHandler::CloudPrintFlowHandler(const base::RefCountedMemory* data, const string16& print_job_title, const string16& print_ticket, const std::string& file_type, bool close_after_signin, const base::Closure& callback) : dialog_delegate_(NULL), data_(data), print_job_title_(print_job_title), print_ticket_(print_ticket), file_type_(file_type), close_after_signin_(close_after_signin), callback_(callback) { } CloudPrintFlowHandler::~CloudPrintFlowHandler() { // This will also cancel any task in flight. CancelAnyRunningTask(); } void CloudPrintFlowHandler::SetDialogDelegate( CloudPrintWebDialogDelegate* delegate) { // Even if setting a new WebUI, it means any previous task needs // to be canceled, its now invalid. DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); CancelAnyRunningTask(); dialog_delegate_ = delegate; } // Cancels any print data sender we have in flight and removes our // reference to it, so when the task that is calling it finishes and // removes its reference, it goes away. void CloudPrintFlowHandler::CancelAnyRunningTask() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (print_data_sender_.get()) { print_data_sender_->CancelPrintDataFile(); print_data_sender_ = NULL; } } void CloudPrintFlowHandler::RegisterMessages() { // TODO(scottbyer) - This is where we will register messages for the // UI JS to use. Needed: Call to update page setup parameters. web_ui()->RegisterMessageCallback("ShowDebugger", base::Bind(&CloudPrintFlowHandler::HandleShowDebugger, base::Unretained(this))); web_ui()->RegisterMessageCallback("SendPrintData", base::Bind(&CloudPrintFlowHandler::HandleSendPrintData, base::Unretained(this))); web_ui()->RegisterMessageCallback("SetPageParameters", base::Bind(&CloudPrintFlowHandler::HandleSetPageParameters, base::Unretained(this))); // Register for appropriate notifications, and re-direct the URL // to the real server URL, now that we've gotten an HTML dialog // going. NavigationController* controller = &web_ui()->GetWebContents()->GetController(); NavigationEntry* pending_entry = controller->GetPendingEntry(); if (pending_entry) { Profile* profile = Profile::FromWebUI(web_ui()); if (close_after_signin_) { pending_entry->SetURL( CloudPrintURL(profile).GetCloudPrintSigninURL()); } else { pending_entry->SetURL( CloudPrintURL(profile).GetCloudPrintServiceDialogURL()); } } registrar_.Add(this, content::NOTIFICATION_LOAD_STOP, content::Source<NavigationController>(controller)); registrar_.Add(this, content::NOTIFICATION_NAV_ENTRY_COMMITTED, content::Source<NavigationController>(controller)); } void CloudPrintFlowHandler::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case content::NOTIFICATION_NAV_ENTRY_COMMITTED: { NavigationEntry* entry = web_ui()->GetWebContents()->GetController().GetActiveEntry(); if (entry) NavigationToURLDidCloseDialog(entry->GetURL()); break; } case content::NOTIFICATION_LOAD_STOP: { GURL url = web_ui()->GetWebContents()->GetURL(); if (IsCloudPrintDialogUrl(url)) { // Take the opportunity to set some (minimal) additional // script permissions required for the web UI. RenderViewHost* rvh = web_ui()->GetWebContents()->GetRenderViewHost(); if (rvh) { WebPreferences webkit_prefs = rvh->GetWebkitPreferences(); webkit_prefs.allow_scripts_to_close_windows = true; rvh->UpdateWebkitPreferences(webkit_prefs); } else { NOTREACHED(); } // Choose one or the other. If you need to debug, bring up the // debugger. You can then use the various chrome.send() // registrations above to kick of the various function calls, // including chrome.send("SendPrintData") in the javaScript // console and watch things happen with: // HandleShowDebugger(NULL); HandleSendPrintData(NULL); } break; } } } void CloudPrintFlowHandler::HandleShowDebugger(const ListValue* args) { ShowDebugger(); } void CloudPrintFlowHandler::ShowDebugger() { if (web_ui()) { RenderViewHost* rvh = web_ui()->GetWebContents()->GetRenderViewHost(); if (rvh) DevToolsWindow::OpenDevToolsWindow(rvh); } } scoped_refptr<CloudPrintDataSender> CloudPrintFlowHandler::CreateCloudPrintDataSender() { DCHECK(web_ui()); print_data_helper_.reset(new CloudPrintDataSenderHelper(web_ui())); scoped_refptr<CloudPrintDataSender> sender( new CloudPrintDataSender(print_data_helper_.get(), print_job_title_, print_ticket_, file_type_, data_.get())); return sender; } void CloudPrintFlowHandler::HandleSendPrintData(const ListValue* args) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); // This will cancel any ReadPrintDataFile() or SendPrintDataFile() // requests in flight (this is anticipation of when setting page // setup parameters becomes asynchronous and may be set while some // data is in flight). Then we can clear out the print data. CancelAnyRunningTask(); if (web_ui()) { print_data_sender_ = CreateCloudPrintDataSender(); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&CloudPrintDataSender::SendPrintData, print_data_sender_)); } } void CloudPrintFlowHandler::HandleSetPageParameters(const ListValue* args) { std::string json; bool ret = args->GetString(0, &json); if (!ret || json.empty()) { NOTREACHED() << "Empty json string"; return; } // These are backstop default values - 72 dpi to match the screen, // 8.5x11 inch paper with margins subtracted (1/4 inch top, left, // right and 0.56 bottom), and the min page shrink and max page // shrink values appear all over the place with no explanation. // TODO(scottbyer): Get a Linux/ChromeOS edge for PrintSettings // working so that we can get the default values from there. Fix up // PrintWebViewHelper to do the same. const int kDPI = 72; const int kWidth = static_cast<int>((8.5-0.25-0.25)*kDPI); const int kHeight = static_cast<int>((11-0.25-0.56)*kDPI); const double kMinPageShrink = 1.25; const double kMaxPageShrink = 2.0; PrintMsg_Print_Params default_settings; default_settings.content_size = gfx::Size(kWidth, kHeight); default_settings.printable_area = gfx::Rect(0, 0, kWidth, kHeight); default_settings.dpi = kDPI; default_settings.min_shrink = kMinPageShrink; default_settings.max_shrink = kMaxPageShrink; default_settings.desired_dpi = kDPI; default_settings.document_cookie = 0; default_settings.selection_only = false; default_settings.preview_request_id = 0; default_settings.is_first_request = true; default_settings.print_to_pdf = false; if (!GetPageSetupParameters(json, default_settings)) { NOTREACHED(); return; } // TODO(scottbyer) - Here is where we would kick the originating // renderer thread with these new parameters in order to get it to // re-generate the PDF data and hand it back to us. window.print() is // currently synchronous, so there's a lot of work to do to get to // that point. } void CloudPrintFlowHandler::StoreDialogClientSize() const { if (web_ui() && web_ui()->GetWebContents() && web_ui()->GetWebContents()->GetView()) { gfx::Size size = web_ui()->GetWebContents()->GetView()->GetContainerSize(); Profile* profile = Profile::FromWebUI(web_ui()); profile->GetPrefs()->SetInteger(prefs::kCloudPrintDialogWidth, size.width()); profile->GetPrefs()->SetInteger(prefs::kCloudPrintDialogHeight, size.height()); } } bool CloudPrintFlowHandler::NavigationToURLDidCloseDialog(const GURL& url) { if (close_after_signin_) { if (IsCloudPrintDialogUrl(url)) { StoreDialogClientSize(); web_ui()->GetWebContents()->GetRenderViewHost()->ClosePage(); callback_.Run(); return true; } } return false; } bool CloudPrintFlowHandler::IsCloudPrintDialogUrl(const GURL& url) { GURL cloud_print_url = CloudPrintURL(Profile::FromWebUI(web_ui())).GetCloudPrintServiceURL(); return url.host() == cloud_print_url.host() && StartsWithASCII(url.path(), cloud_print_url.path(), false) && url.scheme() == cloud_print_url.scheme(); } CloudPrintWebDialogDelegate::CloudPrintWebDialogDelegate( content::BrowserContext* browser_context, gfx::NativeWindow modal_parent, const base::RefCountedMemory* data, const std::string& json_arguments, const string16& print_job_title, const string16& print_ticket, const std::string& file_type, bool close_after_signin, const base::Closure& callback) : flow_handler_( new CloudPrintFlowHandler(data, print_job_title, print_ticket, file_type, close_after_signin, callback)), modal_parent_(modal_parent), owns_flow_handler_(true), keep_alive_when_non_modal_(true) { Init(browser_context, json_arguments); } // For unit testing. CloudPrintWebDialogDelegate::CloudPrintWebDialogDelegate( CloudPrintFlowHandler* flow_handler, const std::string& json_arguments) : flow_handler_(flow_handler), modal_parent_(NULL), owns_flow_handler_(true), keep_alive_when_non_modal_(false) { Init(NULL, json_arguments); } // Returns the persisted width/height for the print dialog. void GetDialogWidthAndHeightFromPrefs(content::BrowserContext* browser_context, int* width, int* height) { if (!browser_context) { *width = kDefaultWidth; *height = kDefaultHeight; return; } PrefService* prefs = Profile::FromBrowserContext(browser_context)->GetPrefs(); *width = prefs->GetInteger(prefs::kCloudPrintDialogWidth); *height = prefs->GetInteger(prefs::kCloudPrintDialogHeight); } void CloudPrintWebDialogDelegate::Init(content::BrowserContext* browser_context, const std::string& json_arguments) { // This information is needed to show the dialog HTML content. DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); params_.url = GURL(chrome::kChromeUICloudPrintResourcesURL); GetDialogWidthAndHeightFromPrefs(browser_context, &params_.width, &params_.height); params_.json_input = json_arguments; flow_handler_->SetDialogDelegate(this); // If we're not modal we can show the dialog with no browser. // We need this to keep Chrome alive while our dialog is up. if (!modal_parent_ && keep_alive_when_non_modal_) chrome::StartKeepAlive(); } CloudPrintWebDialogDelegate::~CloudPrintWebDialogDelegate() { // If the flow_handler_ is about to outlive us because we don't own // it anymore, we need to have it remove its reference to us. DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); flow_handler_->SetDialogDelegate(NULL); if (owns_flow_handler_) { delete flow_handler_; } } ui::ModalType CloudPrintWebDialogDelegate::GetDialogModalType() const { return modal_parent_ ? ui::MODAL_TYPE_WINDOW : ui::MODAL_TYPE_NONE; } string16 CloudPrintWebDialogDelegate::GetDialogTitle() const { return string16(); } GURL CloudPrintWebDialogDelegate::GetDialogContentURL() const { return params_.url; } void CloudPrintWebDialogDelegate::GetWebUIMessageHandlers( std::vector<WebUIMessageHandler*>* handlers) const { handlers->push_back(flow_handler_); // We don't own flow_handler_ anymore, but it sticks around until at // least right after OnDialogClosed() is called (and this object is // destroyed). owns_flow_handler_ = false; } void CloudPrintWebDialogDelegate::GetDialogSize(gfx::Size* size) const { size->set_width(params_.width); size->set_height(params_.height); } std::string CloudPrintWebDialogDelegate::GetDialogArgs() const { return params_.json_input; } void CloudPrintWebDialogDelegate::OnDialogClosed( const std::string& json_retval) { // Get the final dialog size and store it. flow_handler_->StoreDialogClientSize(); // If we're modal we can show the dialog with no browser. // End the keep-alive so that Chrome can exit. if (!modal_parent_ && keep_alive_when_non_modal_) chrome::EndKeepAlive(); delete this; } void CloudPrintWebDialogDelegate::OnCloseContents(WebContents* source, bool* out_close_dialog) { if (out_close_dialog) *out_close_dialog = true; } bool CloudPrintWebDialogDelegate::ShouldShowDialogTitle() const { return false; } bool CloudPrintWebDialogDelegate::HandleContextMenu( const content::ContextMenuParams& params) { return true; } bool CloudPrintWebDialogDelegate::HandleOpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params, content::WebContents** out_new_contents) { return flow_handler_->NavigationToURLDidCloseDialog(params.url); } // Called from the UI thread, starts up the dialog. void CreateDialogImpl(content::BrowserContext* browser_context, gfx::NativeWindow modal_parent, const base::RefCountedMemory* data, const string16& print_job_title, const string16& print_ticket, const std::string& file_type, bool close_after_signin, const base::Closure& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); WebDialogDelegate* dialog_delegate = new internal_cloud_print_helpers::CloudPrintWebDialogDelegate( browser_context, modal_parent, data, std::string(), print_job_title, print_ticket, file_type, close_after_signin, callback); #if defined(OS_WIN) gfx::NativeWindow window = #endif chrome::ShowWebDialog(modal_parent, Profile::FromBrowserContext(browser_context), dialog_delegate); #if defined(OS_WIN) if (window) { HWND dialog_handle; #if defined(USE_AURA) dialog_handle = window->GetDispatcher()->GetAcceleratedWidget(); #else dialog_handle = window; #endif if (::GetForegroundWindow() != dialog_handle) { ui::ForegroundHelper::SetForeground(dialog_handle); } } #endif } void CreateDialogSigninImpl(content::BrowserContext* browser_context, gfx::NativeWindow modal_parent, const base::Closure& callback) { CreateDialogImpl(browser_context, modal_parent, NULL, string16(), string16(), std::string(), true, callback); } void CreateDialogForFileImpl(content::BrowserContext* browser_context, gfx::NativeWindow modal_parent, const base::FilePath& path_to_file, const string16& print_job_title, const string16& print_ticket, const std::string& file_type, bool delete_on_close) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); scoped_refptr<base::RefCountedMemory> data; int64 file_size = 0; if (file_util::GetFileSize(path_to_file, &file_size) && file_size != 0) { std::string file_data; if (file_size < kuint32max) { file_data.reserve(static_cast<unsigned int>(file_size)); } else { DLOG(WARNING) << " print data file too large to reserve space"; } if (base::ReadFileToString(path_to_file, &file_data)) { data = base::RefCountedString::TakeString(&file_data); } } // Proceed even for empty data to simplify testing. BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&print_dialog_cloud::CreatePrintDialogForBytes, browser_context, modal_parent, data, print_job_title, print_ticket, file_type)); if (delete_on_close) base::DeleteFile(path_to_file, false); } } // namespace internal_cloud_print_helpers namespace print_dialog_cloud { void RegisterProfilePrefs(user_prefs::PrefRegistrySyncable* registry) { registry->RegisterIntegerPref( prefs::kCloudPrintDialogWidth, kDefaultWidth, user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); registry->RegisterIntegerPref( prefs::kCloudPrintDialogHeight, kDefaultHeight, user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF); } // Called on the FILE or UI thread. This is the main entry point into creating // the dialog. void CreatePrintDialogForFile(content::BrowserContext* browser_context, gfx::NativeWindow modal_parent, const base::FilePath& path_to_file, const string16& print_job_title, const string16& print_ticket, const std::string& file_type, bool delete_on_close) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE) || BrowserThread::CurrentlyOn(BrowserThread::UI)); BrowserThread::PostTask( BrowserThread::FILE, FROM_HERE, base::Bind(&internal_cloud_print_helpers::CreateDialogForFileImpl, browser_context, modal_parent, path_to_file, print_job_title, print_ticket, file_type, delete_on_close)); } void CreateCloudPrintSigninDialog(content::BrowserContext* browser_context, gfx::NativeWindow modal_parent, const base::Closure& callback) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&internal_cloud_print_helpers::CreateDialogSigninImpl, browser_context, modal_parent, callback)); } void CreatePrintDialogForBytes(content::BrowserContext* browser_context, gfx::NativeWindow modal_parent, const base::RefCountedMemory* data, const string16& print_job_title, const string16& print_ticket, const std::string& file_type) { internal_cloud_print_helpers::CreateDialogImpl(browser_context, modal_parent, data, print_job_title, print_ticket, file_type, false, base::Closure()); } bool CreatePrintDialogFromCommandLine(const CommandLine& command_line) { DCHECK(command_line.HasSwitch(switches::kCloudPrintFile)); if (!command_line.GetSwitchValuePath(switches::kCloudPrintFile).empty()) { base::FilePath cloud_print_file; cloud_print_file = command_line.GetSwitchValuePath(switches::kCloudPrintFile); if (!cloud_print_file.empty()) { string16 print_job_title; string16 print_job_print_ticket; if (command_line.HasSwitch(switches::kCloudPrintJobTitle)) { print_job_title = internal_cloud_print_helpers::GetSwitchValueString16( command_line, switches::kCloudPrintJobTitle); } if (command_line.HasSwitch(switches::kCloudPrintPrintTicket)) { print_job_print_ticket = internal_cloud_print_helpers::GetSwitchValueString16( command_line, switches::kCloudPrintPrintTicket); } std::string file_type = "application/pdf"; if (command_line.HasSwitch(switches::kCloudPrintFileType)) { file_type = command_line.GetSwitchValueASCII( switches::kCloudPrintFileType); } bool delete_on_close = CommandLine::ForCurrentProcess()->HasSwitch( switches::kCloudPrintDeleteFile); print_dialog_cloud::CreatePrintDialogForFile( ProfileManager::GetDefaultProfile(), NULL, cloud_print_file, print_job_title, print_job_print_ticket, file_type, delete_on_close); return true; } } return false; } } // end namespace
39.128173
80
0.698635
[ "object", "vector", "model" ]
4f9d55932ffa3f3ef65afb66b6e7fe186b6087a8
6,855
cc
C++
src/browser.cc
legnaleurc/node-chimera
e51b94ffe8730a93f07549e55413cc84fc43549f
[ "MIT" ]
1
2015-04-19T23:32:57.000Z
2015-04-19T23:32:57.000Z
src/browser.cc
legnaleurc/node-chimera
e51b94ffe8730a93f07549e55413cc84fc43549f
[ "MIT" ]
null
null
null
src/browser.cc
legnaleurc/node-chimera
e51b94ffe8730a93f07549e55413cc84fc43549f
[ "MIT" ]
null
null
null
#define BUILDING_NODE_EXTENSION #include <node.h> #include "browser.h" #include "top_v8.h" using namespace v8; Persistent<Function> Browser::constructor; Browser::Browser(QString userAgent, QString libraryCode, QString cookies, bool disableImages) { userAgent_ = userAgent; libraryCode_ = libraryCode; cookies_ = cookies; disableImages_ = disableImages; chimera_ = 0; } Browser::~Browser() { delete chimera_; } void Browser::Initialize(Handle<Object> target) { Local<FunctionTemplate> tpl = FunctionTemplate::New(New); tpl->SetClassName(String::NewSymbol("Browser")); tpl->InstanceTemplate()->SetInternalFieldCount(1); tpl->PrototypeTemplate()->Set(String::NewSymbol("open"), FunctionTemplate::New(Open)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("close"), FunctionTemplate::New(Close)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("capture"), FunctionTemplate::New(Capture)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("cookies"), FunctionTemplate::New(Cookies)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("setCookies"), FunctionTemplate::New(SetCookies)->GetFunction()); tpl->PrototypeTemplate()->Set(String::NewSymbol("setProxy"), FunctionTemplate::New(SetProxy)->GetFunction()); constructor = Persistent<Function>::New( tpl->GetFunction()); target->Set(String::NewSymbol("Browser"), constructor); } Handle<Value> Browser::New(const Arguments& args) { HandleScope scope; QString userAgent = top_v8::ToQString(args[0]->ToString()); QString libraryCode = top_v8::ToQString(args[1]->ToString()); QString cookies = top_v8::ToQString(args[2]->ToString()); bool disableImages = args[3]->BooleanValue(); Browser* w = new Browser(userAgent, libraryCode, cookies, disableImages); w->Wrap(args.This()); return args.This(); } void AsyncWork(uv_work_t* req) { BWork* work = static_cast<BWork*>(req->data); work->chimera->wait(); work->result = work->chimera->getResult(); work->errorResult = work->chimera->getError(); } void AsyncAfter(uv_work_t* req) { HandleScope scope; BWork* work = static_cast<BWork*>(req->data); if (work->error) { Local<Value> err = Exception::Error(String::New(work->error_message.c_str())); const unsigned argc = 1; Local<Value> argv[argc] = { err }; TryCatch try_catch; work->callback->Call(Context::GetCurrent()->Global(), argc, argv); if (try_catch.HasCaught()) { node::FatalException(try_catch); } } else { const unsigned argc = 2; Local<Value> argv[argc] = { Local<Value>::New(Null()), Local<Value>::New(top_v8::FromQString(work->result)) }; TryCatch try_catch; work->callback->Call(Context::GetCurrent()->Global(), argc, argv); if (try_catch.HasCaught()) { node::FatalException(try_catch); } } uv_queue_work(uv_default_loop(), &work->request, AsyncWork, AsyncAfter); // TODO: we need to figure out where to dispose the callback & free up work // work->callback.Dispose(); // delete work; } Handle<Value> Browser::Cookies(const Arguments& args) { HandleScope scope; QString cookies = ""; Browser* w = ObjectWrap::Unwrap<Browser>(args.This()); Chimera* chimera = w->getChimera(); if (0 != chimera) { cookies = chimera->getCookies(); } return scope.Close(top_v8::FromQString(cookies)); } Handle<Value> Browser::SetCookies(const Arguments& args) { HandleScope scope; if (!args[0]->IsString()) { return ThrowException(Exception::TypeError( String::New("First argument must be a cookie string"))); } Browser* w = ObjectWrap::Unwrap<Browser>(args.This()); Chimera* chimera = w->getChimera(); if (0 != chimera) { chimera->setCookies(top_v8::ToQString(args[0]->ToString())); } return scope.Close(Undefined()); } Handle<Value> Browser::SetProxy(const Arguments& args) { HandleScope scope; if (!args[0]->IsString()) { return ThrowException(Exception::TypeError( String::New("First argument must be the type of proxy (socks/http)"))); } Browser* w = ObjectWrap::Unwrap<Browser>(args.This()); Chimera* chimera = w->getChimera(); if (0 != chimera) { chimera->setProxy(top_v8::ToQString(args[0]->ToString()), top_v8::ToQString(args[1]->ToString()), args[2]->Int32Value(), top_v8::ToQString(args[3]->ToString()), top_v8::ToQString(args[4]->ToString())); } return scope.Close(Undefined()); } Handle<Value> Browser::Capture(const Arguments& args) { HandleScope scope; if (!args[0]->IsString()) { return ThrowException(Exception::TypeError( String::New("First argument must be a filename string"))); } Browser* w = ObjectWrap::Unwrap<Browser>(args.This()); Chimera* chimera = w->getChimera(); if (0 != chimera) { chimera->capture(top_v8::ToQString(args[0]->ToString())); } return scope.Close(Undefined()); } Handle<Value> Browser::Close(const Arguments& args) { HandleScope scope; Browser* w = ObjectWrap::Unwrap<Browser>(args.This()); Chimera* chimera = w->getChimera(); if (0 != chimera) { chimera->exit(1); w->setChimera(0); chimera->deleteLater(); } return scope.Close(Undefined()); } Handle<Value> Browser::Open(const Arguments& args) { HandleScope scope; if (!args[1]->IsString()) { return ThrowException(Exception::TypeError( String::New("Second argument must be a javascript string"))); } if (!args[2]->IsFunction()) { return ThrowException(Exception::TypeError( String::New("Third argument must be a callback function"))); } Local<Function> callback = Local<Function>::Cast(args[2]); BWork* work = new BWork(); work->error = false; work->request.data = work; work->callback = Persistent<Function>::New(callback); Browser* w = ObjectWrap::Unwrap<Browser>(args.This()); Chimera* chimera = w->getChimera(); if (0 != chimera) { work->chimera = chimera; } else { work->chimera = new Chimera(); work->chimera->setUserAgent(w->userAgent()); work->chimera->setLibraryCode(w->libraryCode()); work->chimera->setCookies(w->cookies()); if (w->disableImages_) { work->chimera->disableImages(); } w->setChimera(work->chimera); } work->chimera->setEmbedScript(top_v8::ToQString(args[1]->ToString())); if (args[0]->IsString()) { work->url = top_v8::ToQString(args[0]->ToString()); work->chimera->open(work->url); } else { std::cout << "debug -- about to call execute" << std::endl; work->chimera->execute(); } int status = uv_queue_work(uv_default_loop(), &work->request, AsyncWork, AsyncAfter); assert(status == 0); return Undefined(); }
29.675325
125
0.65733
[ "object" ]
4f9ea6cf4148aff860b5266a905c6fc9ff21c3b8
46,031
cpp
C++
src/condor_starter.V6.1/vm_proc.cpp
pavlo-svirin/htcondor
9e00a5874cc2579f5fdc81bb778f540b40b48c87
[ "Apache-2.0" ]
null
null
null
src/condor_starter.V6.1/vm_proc.cpp
pavlo-svirin/htcondor
9e00a5874cc2579f5fdc81bb778f540b40b48c87
[ "Apache-2.0" ]
null
null
null
src/condor_starter.V6.1/vm_proc.cpp
pavlo-svirin/htcondor
9e00a5874cc2579f5fdc81bb778f540b40b48c87
[ "Apache-2.0" ]
null
null
null
/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ***************************************************************/ #include "condor_common.h" #include "condor_classad.h" #include "condor_debug.h" #include "condor_daemon_core.h" #include "condor_attributes.h" #include "exit.h" #include "env.h" #include "user_proc.h" #include "os_proc.h" #include "vm_proc.h" #include "starter.h" #include "condor_config.h" #include "condor_mkstemp.h" #include "basename.h" #include "directory.h" #include "filename_tools.h" #include "daemon.h" #include "daemon_types.h" #include "vm_gahp_request.h" #include "../condor_vm-gahp/vmgahp_error_codes.h" #include "vm_univ_utils.h" #include "condor_daemon_client.h" extern CStarter *Starter; #define NULLSTRING "NULL" VMProc::VMProc(ClassAd *jobAd) : OsProc(jobAd) { m_vmgahp = NULL; m_is_cleanuped = false; m_vm_id = 0; m_vm_pid = 0; memset(&m_vm_exited_pinfo, 0, sizeof(m_vm_exited_pinfo)); memset(&m_vm_alive_pinfo, 0, sizeof(m_vm_alive_pinfo)); m_vm_checkpoint = false; m_is_vacate_ckpt = false; m_last_ckpt_result = false; m_is_soft_suspended = false; m_vm_ckpt_count = 0; m_vmstatus_tid = -1; m_vmstatus_notify_tid = -1; m_status_req = NULL; m_status_error_count = 0; m_vm_cputime = 0; m_vm_utilization = -1.0; m_vm_max_memory = 0; m_vm_memory = 0; m_vm_last_ckpt_time = 0; //Find the interval of sending vm status command to vmgahp server m_vmstatus_interval = param_integer( "VM_STATUS_INTERVAL", VM_DEFAULT_STATUS_INTERVAL); if( m_vmstatus_interval < VM_MIN_STATUS_INTERVAL ) { // vm_status interval must be at least more than // VM_MIN_STATUS_INTERVAL for performance issue dprintf(D_ALWAYS,"Even if Condor config file defines %d secs " "for vm status interval, vm status interval is set to " "%d seconds for performance.\n", m_vmstatus_interval, VM_MIN_STATUS_INTERVAL); m_vmstatus_interval = VM_MIN_STATUS_INTERVAL; } m_vmstatus_max_error_cnt = param_integer( "VM_STATUS_MAX_ERROR", VM_STATUS_MAX_ERROR_COUNT); m_vmoperation_timeout = param_integer( "VM_GAHP_REQ_TIMEOUT", VM_GAHP_REQ_TIMEOUT ); m_use_soft_suspend = param_boolean("VM_SOFT_SUSPEND", false); } VMProc::~VMProc() { // destroy the vmgahp server cleanup(); } void VMProc::cleanup() { dprintf(D_FULLDEBUG,"Inside VMProc::cleanup()\n"); if( m_is_cleanuped ) { return; } m_is_cleanuped = true; if(m_status_req) { delete m_status_req; m_status_req = NULL; } if(m_vmgahp) { delete m_vmgahp; m_vmgahp = NULL; } if( m_vmstatus_tid != -1 ) { if( daemonCore ) { daemonCore->Cancel_Timer(m_vmstatus_tid); } m_vmstatus_tid = -1; } if( m_vmstatus_notify_tid != -1 ) { if( daemonCore ) { daemonCore->Cancel_Timer(m_vmstatus_notify_tid); } m_vmstatus_notify_tid = -1; } m_vm_id = 0; m_vm_pid = 0; m_vm_type = ""; m_vmgahp_server = ""; // set is_suspended to false in os_proc.h is_suspended = false; m_is_soft_suspended = false; is_checkpointed = false; m_is_vacate_ckpt = false; } bool handleFTL( const char * reason ) { if( reason != NULL ) { dprintf( D_ALWAYS, "Failed to launch VM universe job (%s).\n", reason ); std::string errorString; formatstr( errorString, "An internal error prevented HTCondor " "from starting the VM. This job will be rescheduled. " "(%s).\n", reason ); Starter->jic->notifyStarterError( errorString.c_str(), false, 0, 0 ); Starter->jic->notifyJobExit( -1, JOB_SHOULD_REQUEUE, NULL ); } // // If we failed to launch the job (as opposed to aborted the takeoff // because there was something wrong with the payload), we also need // to force the startd to advertise this fact so other jobs can avoid // this machine. // DCStartd startd( (const char * const)NULL, (const char * const)NULL ); if( ! startd.locate() ) { dprintf( D_ALWAYS | D_FAILURE, "Unable to locate startd: %s\n", startd.error() ); return false; } // // The startd will update the list 'OfflineUniverses' for us. // ClassAd update; if( reason != NULL ) { update.Assign( "HasVM", false ); update.Assign( "VMOfflineReason", reason ); } else { update.Assign( "HasVM", true ); } ClassAd reply; if( ! startd.updateMachineAd( & update, & reply ) ) { dprintf( D_ALWAYS | D_FAILURE, "Unable to update machine ad: %s\n", startd.error() ); return false; } return true; } int VMProc::StartJob() { MyString err_msg; dprintf(D_FULLDEBUG,"Inside VMProc::StartJob()\n"); // set up a FamilyInfo structure to register a family // with the ProcD in its call to DaemonCore::Create_Process FamilyInfo fi; // take snapshots at no more than 15 seconds in between, by default fi.max_snapshot_interval = param_integer("PID_SNAPSHOT_INTERVAL", 15); m_dedicated_account = Starter->jic->getExecuteAccountIsDedicated(); if (m_dedicated_account) { // using login-based family tracking fi.login = m_dedicated_account; // The following message is documented in the manual as the // way to tell whether the dedicated execution account // configuration is being used. dprintf(D_ALWAYS, "Tracking process family by login \"%s\"\n", fi.login); } // Find vmgahp server location char* vmgahpfile = param( "VM_GAHP_SERVER" ); if( !vmgahpfile || (access(vmgahpfile,X_OK) < 0) ) { // make certain the vmgahp server program is executable dprintf(D_ALWAYS, "vmgahp server cannot be found/executed\n"); reportErrorToStartd(); if (vmgahpfile) { free(vmgahpfile); vmgahpfile = NULL; } return false; } m_vmgahp_server = vmgahpfile; free(vmgahpfile); if( !JobAd ) { dprintf(D_ALWAYS, "No JobAd in VMProc::StartJob()!\n"); return false; } // // // // // // // Environment // // // // // // // Now, instantiate an Env object so we can manipulate the // environment as needed. Env job_env; char *env_str = param( "STARTER_JOB_ENVIRONMENT" ); MyString env_errors; if( ! job_env.MergeFromV1RawOrV2Quoted(env_str,&env_errors) ) { dprintf( D_ALWAYS, "Aborting VMProc::StartJob: " "%s\nThe full value for STARTER_JOB_ENVIRONMENT: " "%s\n",env_errors.Value(),env_str); if( env_str ) { free(env_str); } return false; } if( env_str ) { free(env_str); } // Now, let the starter publish any env vars it wants to into // the mainjob's env... Starter->PublishToEnv( &job_env ); // // // // // // // Misc + Exec // // // // // // // compute job's renice value by evaluating the machine's // JOB_RENICE_INCREMENT in the context of the job ad... int nice_inc = 0; char* ptmp = param( "JOB_RENICE_INCREMENT" ); if( ptmp ) { // insert renice expr into our copy of the job ad MyString reniceAttr = "Renice = "; reniceAttr += ptmp; if( !JobAd->Insert( reniceAttr.Value() ) ) { dprintf( D_ALWAYS, "ERROR: failed to insert JOB_RENICE_INCREMENT " "into job ad, Aborting OsProc::StartJob...\n" ); free( ptmp ); return 0; } // evaluate if( JobAd->LookupInteger( "Renice", nice_inc ) ) { dprintf( D_ALWAYS, "Renice expr \"%s\" evaluated to %d\n", ptmp, nice_inc ); } else { dprintf( D_ALWAYS, "WARNING: job renice expr (\"%s\") doesn't " "eval to int! Using default of 10...\n", ptmp ); nice_inc = 10; } // enforce valid ranges for nice_inc if( nice_inc < 0 ) { dprintf( D_FULLDEBUG, "WARNING: job renice value (%d) is too " "low: adjusted to 0\n", nice_inc ); nice_inc = 0; } else if( nice_inc > 19 ) { dprintf( D_FULLDEBUG, "WARNING: job renice value (%d) is too " "high: adjusted to 19\n", nice_inc ); nice_inc = 19; } ASSERT( ptmp ); free( ptmp ); ptmp = NULL; } else { // if JOB_RENICE_INCREMENT is undefined, default to 10 nice_inc = 10; } // Get job name std::string vm_job_name; if( JobAd->LookupString( ATTR_JOB_CMD, vm_job_name) != 1 ) { err_msg.formatstr("%s cannot be found in job classAd.", ATTR_JOB_CMD); dprintf(D_ALWAYS, "%s\n", err_msg.Value()); Starter->jic->notifyStarterError( err_msg.Value(), true, CONDOR_HOLD_CODE_FailedToCreateProcess, 0); return false; } m_job_name = vm_job_name; // vm_type should be from ClassAd std::string vm_type_name; if( JobAd->LookupString( ATTR_JOB_VM_TYPE, vm_type_name) != 1 ) { err_msg.formatstr("%s cannot be found in job classAd.", ATTR_JOB_VM_TYPE); dprintf(D_ALWAYS, "%s\n", err_msg.Value()); Starter->jic->notifyStarterError( err_msg.Value(), true, CONDOR_HOLD_CODE_FailedToCreateProcess, 0); return false; } lower_case(vm_type_name); m_vm_type = vm_type_name; // get vm checkpoint flag from ClassAd m_vm_checkpoint = false; JobAd->LookupBool(ATTR_JOB_VM_CHECKPOINT, m_vm_checkpoint); // If there exists MAC or IP address for a checkpointed VM, // we use them as initial values. std::string string_value; if( JobAd->LookupString(ATTR_VM_CKPT_MAC, string_value) == 1 ) { m_vm_mac = string_value; } /* string_value = ""; if( JobAd->LookupString(ATTR_VM_CKPT_IP, string_value) == 1 ) { m_vm_ip = string_value; } */ // For Xen and KVM jobs, the vm-gahp issues libvirt commands as root // (since some common configurations only allow root to create VMs). // Libvirt will refuse to create the VM if the acting user doesn't // have explicit permission to access the VM's disk image files, // even though root can ignore those permission settings. // Therefore, we need to relax the permissions on the execute // directory. if ( strcasecmp( m_vm_type.Value(), CONDOR_VM_UNIVERSE_KVM ) == MATCH || strcasecmp( m_vm_type.Value(), CONDOR_VM_UNIVERSE_XEN ) == MATCH ) { priv_state oldpriv = set_user_priv(); if ( chmod( Starter->GetWorkingDir(), 0755 ) == -1 ) { set_priv( oldpriv ); dprintf( D_ALWAYS, "Failed to chmod execute directory for Xen/KVM job: %s\n", strerror( errno ) ); return false; } set_priv( oldpriv ); } ClassAd recovery_ad = *JobAd; MyString vm_name; if ( strcasecmp( m_vm_type.Value(), CONDOR_VM_UNIVERSE_KVM ) == MATCH || strcasecmp( m_vm_type.Value(), CONDOR_VM_UNIVERSE_XEN ) == MATCH ) { ASSERT( create_name_for_VM( JobAd, vm_name ) ); } else { vm_name = Starter->GetWorkingDir(); } recovery_ad.Assign( "JobVMId", vm_name.Value() ); Starter->WriteRecoveryFile( &recovery_ad ); // // // Now everything is ready to start a vmgahp server // // dprintf( D_ALWAYS, "About to start new VM\n"); Starter->jic->notifyJobPreSpawn(); //create vmgahp server m_vmgahp = new VMGahpServer(m_vmgahp_server.Value(), m_vm_type.Value(), JobAd); ASSERT(m_vmgahp); m_vmgahp->start_err_msg = ""; if( m_vmgahp->startUp(&job_env, Starter->GetWorkingDir(), nice_inc, &fi) == false ) { JobPid = -1; err_msg = "Failed to start vm-gahp server"; dprintf( D_ALWAYS, "%s\n", err_msg.Value()); if( m_vmgahp->start_err_msg.Length() > 0 ) { m_vmgahp->start_err_msg.chomp(); err_msg = m_vmgahp->start_err_msg; } reportErrorToStartd(); Starter->jic->notifyStarterError( err_msg.Value(), true, 0, 0); delete m_vmgahp; m_vmgahp = NULL; return false; } // Set JobPid and num_pids in user_proc.h and os_proc.h JobPid = m_vmgahp->getVMGahpServerPid(); num_pids++; VMGahpRequest *new_req = new VMGahpRequest(m_vmgahp); ASSERT(new_req); new_req->setMode(VMGahpRequest::BLOCKING); // When we call vmStart, vmStart may create an ISO file. // So we need to give some more time to vmgahp. new_req->setTimeout(m_vmoperation_timeout + 120); int p_result; if( param_integer( "VMU_TESTING" ) == 1 ) { switch( rand() % 6 ) { case 0: p_result = VMGAHP_REQ_COMMAND_PENDING; break; case 1: default: p_result = new_req->vmStart( m_vm_type.Value(), Starter->GetWorkingDir() ); break; case 2: p_result = VMGAHP_REQ_COMMAND_TIMED_OUT; break; case 3: p_result = VMGAHP_REQ_COMMAND_NOT_SUPPORTED; break; case 4: p_result = VMGAHP_REQ_VMTYPE_NOT_SUPPORTED; break; case 5: p_result = VMGAHP_REQ_COMMAND_ERROR; break; } } else { p_result = new_req->vmStart( m_vm_type.Value(), Starter->GetWorkingDir() ); } // // Distinguish between failures that are HTCondor's fault (bugs), failures // that are the user's fault (disk image is not in the specified format?), // and failures that are the fault of the machine (libvirt is wedged). // // // In this and subsequent result code lists, a trailing // * (C) means [HT]Condor's fault // * (U) mean user's fault // * and (M) mean machine's fault. // * (U?) means that the user screwed up but HTCondor could or should // have noticed before the bad data got all the way to the VM GAHP. // * (?) means that we don't what caused the failure. // // VMGahpRequest::vmStart() can return the following results: // // Failures: // VMGAHP_REQ_COMMAND_ERROR (C) is an internal logic error. // VMGAHP_REQ_COMMAND_NOT_SUPPORTED (C) is nonsensical. // VMGAHP_REQ_VMTYPE_NOT_SUPPORTED (C) means a match-making failure. // VMGAHP_REQ_COMMAND_PENDING (C) is logically impossible. // VMGAHP_REQ_COMMAND_TIMED_OUT (?) // // Successes: // VMGAHP_REQ_COMMAND_DONE // // // We assume, for now, that a request timing out is a machine problem. // if( p_result != VMGAHP_REQ_COMMAND_DONE ) { m_vmgahp->printSystemErrorMsg(); // reportErrorToStartd() forces the startd to re-run its VM universe // check(s). This may result in the startd and the starter disagreeing // about whether the VM universe is working, so don't do it. // reportErrorToStartd(); handleFTL( VMGAHP_REQ_RETURN_TABLE[ p_result ] ); delete new_req; delete m_vmgahp; m_vmgahp = NULL; // Make sure the VM GAHP is dead. daemonCore->Kill_Family( JobPid ); return false; } if( param_integer( "VMU_TESTING" ) == 2 ) { // A newly-constructed request can not have a valid result. new_req = new VMGahpRequest( new_req->getVMGahpServer() ); } // // I've split checkResult() into two parts: the first checks that the // result is valid, and the second its value. An invalid result is // obviously a (C)-type error. // if( ! new_req->hasValidResult() ) { m_vmgahp->printSystemErrorMsg(); // reportErrorToStartd() forces the startd to re-run its VM universe // check(s). This may result in the startd and the starter disagreeing // about whether the VM universe is working, so don't do it. // reportErrorToStartd(); handleFTL( VMGAHP_ERR_INTERNAL ); delete new_req; delete m_vmgahp; m_vmgahp = NULL; // Make sure the VM GAHP is dead. daemonCore->Kill_Family( JobPid ); return false; } // // The GAHP can return the error strings listed below. // // VMGAHP_ERR_NO_JOBCLASSAD_INFO (C) // VMGAHP_ERR_NO_SUPPORTED_VM_TYPE (C) // // from CreateConfigFile(): // from parseCommonParamFromClassAd() // VMGAHP_ERR_JOBCLASSAD_NO_VM_MEMORY_PARAM (U?) // VMGAHP_ERR_JOBCLASSAD_TOO_MUCH_MEMORY_REQUEST (C) // VMGAHP_ERR_JOBCLASSAD_MISMATCHED_NETWORKING (C) // VMGAHP_ERR_JOBCLASSAD_MISMATCHED_NETWORKING_TYPE (C) // VMGAHP_ERR_CRITICAL (C) // VMGAHP_ERR_JOBCLASSAD_MISMATCHED_HARDWARE_VT (C) // VMGAHP_ERR_CANNOT_CREATE_ARG_FILE (M) // // VMGAHP_ERR_JOBCLASSAD_XEN_NO_KERNEL_PARAM (U?) // VMGAHP_ERR_CRITICAL (M) // VMGAHP_ERR_JOBCLASSAD_MISMATCHED_HARDWARE_VT (U?) // VMGAHP_ERR_JOBCLASSAD_XEN_KERNEL_NOT_FOUND (U?) // VMGAHP_ERR_JOBCLASSAD_XEN_INITRD_NOT_FOUND (U?) // VMGAHP_ERR_JOBCLASSAD_XEN_NO_ROOT_DEVICE_PARAM (U?) // VMGAHP_ERR_JOBCLASSAD_XEN_NO_DISK_PARAM (U?) // VMGAHP_ERR_JOBCLASSAD_XEN_INVALID_DISK_PARAM (U?) // VMGAHP_ERR_JOBCLASSAD_XEN_MISMATCHED_CHECKPOINT (U?) // // VMGAHP_ERR_JOBCLASSAD_KVM_NO_DISK_PARAM (U?) // VMGAHP_ERR_JOBCLASSAD_KVM_INVALID_DISK_PARAM (U?) // VMGAHP_ERR_JOBCLASSAD_KVM_MISMATCHED_CHECKPOINT (U?) // // VMGAHP_ERR_JOBCLASSAD_NO_VMWARE_VMX_PARAM (U?) // VMGAHP_ERR_INTERNAL (M) // VMGAHP_ERR_CRITICAL (M) // // from Start(): // VMGAHP_ERR_INTERNAL (C) // VMGAHP_ERR_VM_INVALID_OPERATION (C) // VMGAHP_ERR_CRITICAL (C) // from condor_vm_vmware: // "Can't create vm with $vmconfig" (?) // "vmconfig $vmconfig does not exist" (C) // "vmconfig $vmconfig is not readable" (C) // VMGAHP_ERR_BAD_IMAGE (U) // Gahp_Args * result = new_req->getResult(); int resultNo = (int)strtol( result->argv[1], (char **)NULL, 10 ); if( param_integer( "VMU_TESTING" ) == 3 ) { resultNo = 1; result->reset(); result->add_arg( strdup( "x" ) ); result->add_arg( strdup( "y" ) ); // These two were somewhat arbitrarily chosen, but it'd take more // time than it's worth to create the exhaustive list to randomly // select from. if( rand() % 2 == 0 ) { result->add_arg( strdup( "VMGAHP_ERR_JOBCLASSAD_XEN_MISMATCHED_CHECKPOINT" ) ); } else { result->add_arg( strdup( "VMGAHP_ERR_JOBCLASSAD_MISMATCHED_NETWORKING" ) ); } } // // We assume, for now, that the unknown failures aren't the user's fault. // We also, for now, don't distinguish between machine and Condor faults. // if( resultNo == 0 ) { m_vm_id = (int)strtol( result->argv[2], (char **)NULL, 10 ); // A success with an invalid virtual machine ID is clearly a (C) error. if( m_vm_id <= 0 ) { handleFTL( VMGAHP_ERR_INTERNAL ); return false; } } else { char * errorString = strdup( result->argv[2] ); if( strcmp( NULLSTRING, errorString ) == 0 ) { free( errorString ); errorString = strdup( VMGAHP_ERR_INTERNAL ); } m_vmgahp->printSystemErrorMsg(); delete new_req; delete m_vmgahp; m_vmgahp = NULL; daemonCore->Kill_Family( JobPid ); const char * const holdingErrors[] = { "VMGAHP_ERR_JOBCLASSAD_NO_VM_MEMORY_PARAM", "VMGAHP_ERR_JOBCLASSAD_XEN_NO_KERNEL_PARAM", "VMGAHP_ERR_JOBCLASSAD_MISMATCHED_HARDWARE_VT", "VMGAHP_ERR_JOBCLASSAD_XEN_KERNEL_NOT_FOUND", "VMGAHP_ERR_JOBCLASSAD_XEN_INITRD_NOT_FOUND", "VMGAHP_ERR_JOBCLASSAD_XEN_NO_ROOT_DEVICE_PARAM", "VMGAHP_ERR_JOBCLASSAD_XEN_NO_DISK_PARAM", "VMGAHP_ERR_JOBCLASSAD_XEN_INVALID_DISK_PARAM", "VMGAHP_ERR_JOBCLASSAD_XEN_MISMATCHED_CHECKPOINT", "VMGAHP_ERR_JOBCLASSAD_KVM_NO_DISK_PARAM", "VMGAHP_ERR_JOBCLASSAD_KVM_INVALID_DISK_PARAM", "VMGAHP_ERR_JOBCLASSAD_KVM_MISMATCHED_CHECKPOINT", "VMGAHP_ERR_JOBCLASSAD_NO_VMWARE_VMX_PARAM", "VMGAHP_ERR_BAD_IMAGE" }; unsigned holdingErrorCount = sizeof( holdingErrors ) / sizeof( const char * const ); for( unsigned i = 0; i < holdingErrorCount; ++i ) { if( strcmp( holdingErrors[i], errorString ) == 0 ) { dprintf( D_ALWAYS, "Job failed to launch, potentially because of a user's mistake. (%s) Putting the job on hold.\n", errorString ); std::string holdReason; formatstr( holdReason, "%s", errorString ); // Using i for the hold reason subcode is entirely arbitrary, // but may assist in writing periodic release expressions, // which I understand to be the point. Starter->jic->notifyStarterError( holdReason.c_str(), true, CONDOR_HOLD_CODE_FailedToCreateProcess, i ); free( errorString ); return false; } } handleFTL( errorString ); free( errorString ); return false; } delete new_req; new_req = NULL; m_vmgahp->setVMid(m_vm_id); // We give considerable time(30 secs) to bring // the just created VM into a fully compliant state sleep(30); // Initialize data structures for VM process m_vm_pid = 0; memset(&m_vm_exited_pinfo, 0, sizeof(m_vm_exited_pinfo)); memset(&m_vm_alive_pinfo, 0, sizeof(m_vm_alive_pinfo)); // Find the actual process dealing with VM // Most virtual machine programs except Xen creates a process // that actually deals with a created VM. The process may be // directly created by a virtual machine program and // the parent pid of the process may be 1. // So our default Procd daemon is unable to include this process. // Here, we don't need to create a new Procd daemon for this process. // In VMware, this process is a single process that has no childs. // So we will just use simple ProcAPI to get usage of this process. // PIDofVM will return the pid of such process. // If there is no such process like in Xen, PIDofVM will return 0. int vm_pid = PIDofVM(); setVMPID(vm_pid); m_vmstatus_tid = daemonCore->Register_Timer(m_vmstatus_interval, m_vmstatus_interval, (TimerHandlercpp)&VMProc::CheckStatus, "VMProc::CheckStatus", this); // Set job_start_time in user_proc.h condor_gettimestamp( job_start_time ); dprintf( D_ALWAYS, "StartJob for VM succeeded\n"); // If we do manage to launch, clear the FTL attributes. handleFTL( NULL ); return true; } bool VMProc::process_vm_status_result(Gahp_Args *result_args) { // status result // argv[1] : should be 0, it means success. // From argv[2] : representing some info about VM if( !result_args || ( result_args->argc < 3) ) { dprintf(D_ALWAYS, "Bad Result for VM status\n"); vm_status_error(); return true; } int tmp_argv = (int)strtol(result_args->argv[1], (char **)NULL, 10); if( tmp_argv != 0 || !strcasecmp(result_args->argv[2], NULLSTRING)) { dprintf(D_ALWAYS, "Received VM status, result(%s,%s)\n", result_args->argv[1], result_args->argv[2]); vm_status_error(); return true; } // We got valid info about VM MyString vm_status; float cpu_time = 0; int vm_pid = 0; MyString vm_ip; MyString vm_mac; MyString tmp_name; MyString tmp_value; MyString one_arg; int i = 2; m_vm_utilization = 0.0; for( ; i < result_args->argc; i++ ) { one_arg = result_args->argv[i]; one_arg.trim(); if(one_arg.IsEmpty()) { continue; } parse_param_string(one_arg.Value(), tmp_name, tmp_value, true); if( tmp_name.IsEmpty() || tmp_value.IsEmpty() ) { continue; } if(!strcasecmp(tmp_name.Value(), VMGAHP_STATUS_COMMAND_STATUS)) { vm_status = tmp_value; }else if( !strcasecmp(tmp_name.Value(), VMGAHP_STATUS_COMMAND_CPUTIME) ) { cpu_time = (float)strtod(tmp_value.Value(), (char **)NULL); if( cpu_time <= 0 ) { cpu_time = 0; } }else if( !strcasecmp(tmp_name.Value(), VMGAHP_STATUS_COMMAND_PID) ) { vm_pid = (int)strtol(tmp_value.Value(), (char **)NULL, 10); if( vm_pid <= 0 ) { vm_pid = 0; } }else if( !strcasecmp(tmp_name.Value(), VMGAHP_STATUS_COMMAND_MAC) ) { vm_mac = tmp_value; }else if( !strcasecmp(tmp_name.Value(), VMGAHP_STATUS_COMMAND_IP) ) { vm_ip = tmp_value; }else if ( !strcasecmp(tmp_name.Value(),VMGAHP_STATUS_COMMAND_CPUUTILIZATION) ) { /* This is here for vm's which are spun via libvirt*/ m_vm_utilization = (float)strtod(tmp_value.Value(), (char **)NULL); } else if ( !strcasecmp( tmp_name.Value(), VMGAHP_STATUS_COMMAND_MEMORY ) ) { // This comes from the GAHP in kbytes. m_vm_memory = strtoul( tmp_value.Value(), (char **)NULL, 10 ); } else if ( !strcasecmp( tmp_name.Value(), VMGAHP_STATUS_COMMAND_MAX_MEMORY ) ) { // This comes from the GAHP in kbytes. m_vm_max_memory = strtoul( tmp_value.Value(), (char **)NULL, 10 ); } } if( vm_status.IsEmpty() ) { // We don't receive status of VM dprintf(D_ALWAYS, "No VM status in result\n"); vm_status_error(); return true; } if( vm_mac.IsEmpty() == false ) { setVMMAC(vm_mac.Value()); } if( vm_ip.IsEmpty() == false ) { setVMIP(vm_ip.Value()); } int old_status_error_count = m_status_error_count; // Reset status error count to 0 m_status_error_count = 0; if( !strcasecmp(vm_status.Value(),"Stopped") ) { dprintf(D_ALWAYS, "Virtual machine is stopped\n"); is_suspended = false; m_is_soft_suspended = false; is_checkpointed = false; // VM finished. setVMPID(0); // destroy the vmgahp server cleanup(); return false; }else { dprintf(D_FULLDEBUG, "Virtual machine status is %s, utilization is %f\n", vm_status.Value(), m_vm_utilization ); if( !strcasecmp(vm_status.Value(), "Running") ) { is_suspended = false; m_is_soft_suspended = false; is_checkpointed = false; if( cpu_time > 0 ) { // update statistics for Xen m_vm_cputime = cpu_time; } if( vm_pid > 0 ) { setVMPID(vm_pid); } // Update usage of process for a VM updateUsageOfVM(); }else if( !strcasecmp(vm_status.Value(), "Suspended") ) { if( !is_checkpointed ) { is_suspended = true; } m_is_soft_suspended = false; // VM is suspended setVMPID(0); }else if( !strcasecmp(vm_status.Value(), "SoftSuspended") ) { is_suspended = true; m_is_soft_suspended = true; is_checkpointed = false; }else { dprintf(D_ALWAYS, "Unknown VM status: %s\n", vm_status.Value()); // Restore status error count m_status_error_count = old_status_error_count; vm_status_error(); } } return true; } void VMProc::notify_status_fn() { // this function will be called from timer function bool has_error = false; if( !m_status_req || !m_vm_id ) { return; } dprintf( D_FULLDEBUG, "VM status notify function is called\n"); //reset timer id for this function m_status_req->setNotificationTimerId(-1); m_vmstatus_notify_tid = -1; // check the status of VM status command reqstatus v_status = m_status_req->getPendingStatus(); if(v_status == REQ_DONE) { Gahp_Args *result_args; result_args = m_status_req->getResult(); // If vm_status is 'stopped', cleanup function will be called // inside this function process_vm_status_result(result_args); if(m_status_req) { delete m_status_req; m_status_req = NULL; } return; }else { // We didn't get result from vmgahp server in timeout. dprintf(D_ALWAYS, "Failed to receive VM status\n"); has_error = true; } if(m_status_req) { delete m_status_req; m_status_req = NULL; } if( has_error ) { vm_status_error(); } return; } void VMProc::CheckStatus() { if( !m_vm_id || !m_vmgahp ) { return; } if( m_status_req != NULL ) { delete m_status_req; m_status_req = NULL; m_vmstatus_notify_tid = -1; } m_status_req = new VMGahpRequest(m_vmgahp); ASSERT(m_status_req); m_status_req->setMode(VMGahpRequest::NORMAL); m_status_req->setTimeout(m_vmstatus_interval - 3); m_vmstatus_notify_tid = daemonCore->Register_Timer( m_vmstatus_interval - 1, (TimerHandlercpp)&VMProc::notify_status_fn, "VMProc::notify_status_fn", this); if( m_vmstatus_notify_tid == -1 ) { dprintf( D_ALWAYS, "Failed to regiseter timer for vm status Timeout\n"); delete m_status_req; m_status_req = NULL; return; } m_status_req->setNotificationTimerId(m_vmstatus_notify_tid); int p_result; p_result = m_status_req->vmStatus(m_vm_id); if( p_result == VMGAHP_REQ_COMMAND_PENDING ) { return; }else if( p_result == VMGAHP_REQ_COMMAND_DONE) { m_status_req->setNotificationTimerId(-1); if( m_vmstatus_notify_tid != -1 ) { daemonCore->Cancel_Timer(m_vmstatus_notify_tid); m_vmstatus_notify_tid = -1; } Gahp_Args *result_args; result_args = m_status_req->getResult(); // If vm_status is 'stopped', cleanup function will be called // inside this function process_vm_status_result(result_args); if(m_status_req) { delete m_status_req; m_status_req = NULL; } return; }else { m_status_req->setNotificationTimerId(-1); if( m_vmstatus_notify_tid != -1 ) { daemonCore->Reset_Timer(m_vmstatus_notify_tid, 0); }else { delete m_status_req; m_status_req = NULL; } return; } return; } bool VMProc::JobReaper(int pid, int status) { dprintf(D_FULLDEBUG,"Inside VMProc::JobReaper()\n"); // Ok, vm_gahp server exited // Make sure that all allocated structures are freed cleanup(); // This will reset num_pids for us, too. return OsProc::JobReaper( pid, status ); } bool VMProc::JobExit(void) { dprintf(D_FULLDEBUG,"Inside VMProc::JobExit()\n"); // Do nothing here, just call OsProc::JobExit return OsProc::JobExit(); } void VMProc::Suspend() { dprintf(D_FULLDEBUG,"Inside VMProc::Suspend()\n"); if( !m_vm_id || !m_vmgahp ) { return; } if( is_suspended ) { // VM is already suspended if( is_checkpointed ) { // VM has been hard suspended m_is_soft_suspended = false; is_checkpointed = false; } return; } VMGahpRequest *new_req = new VMGahpRequest(m_vmgahp); ASSERT(new_req); new_req->setMode(VMGahpRequest::BLOCKING); new_req->setTimeout(m_vmoperation_timeout); int p_result; if( m_use_soft_suspend ) { dprintf(D_FULLDEBUG,"Calling Soft Suspend in VMProc::Suspend()\n"); p_result = new_req->vmSoftSuspend(m_vm_id); }else { dprintf(D_FULLDEBUG,"Calling Hard Suspend in VMProc::Suspend()\n"); p_result = new_req->vmSuspend(m_vm_id); } // Because req is blocking mode, result should be VMGAHP_REQ_COMMAND_DONE if(p_result != VMGAHP_REQ_COMMAND_DONE) { dprintf(D_ALWAYS, "Failed to suspend the VM\n"); m_vmgahp->printSystemErrorMsg(); delete new_req; internalVMGahpError(); return; } MyString gahpmsg; if( new_req->checkResult(gahpmsg) == false ) { dprintf(D_ALWAYS, "Failed to suspend the VM(%s)", gahpmsg.Value()); m_vmgahp->printSystemErrorMsg(); delete new_req; if( strcmp(gahpmsg.Value(), VMGAHP_ERR_VM_NO_SUPPORT_SUSPEND) ) { // It is possible that a VM job is just finished. // So we reset the timer for status if( m_vmstatus_tid != -1 ) { daemonCore->Reset_Timer(m_vmstatus_tid, 0, m_vmstatus_interval); } } return; } delete new_req; new_req = NULL; if( !m_use_soft_suspend ) { #if defined(LINUX) // To avoid lazy-write behavior to disk sync(); #endif // After hard suspending, there is no VM process. setVMPID(0); } // set is_suspended to true in os_proc.h is_suspended = true; m_is_soft_suspended = m_use_soft_suspend; is_checkpointed = false; return; } void VMProc::Continue() { dprintf(D_FULLDEBUG,"Inside VMProc::Continue()\n"); if( !m_vm_id || !m_vmgahp ) { return; } VMGahpRequest *new_req = new VMGahpRequest(m_vmgahp); ASSERT(new_req); new_req->setMode(VMGahpRequest::BLOCKING); new_req->setTimeout(m_vmoperation_timeout); int p_result; p_result = new_req->vmResume(m_vm_id); // Because req is blocking mode, result should be VMGAHP_REQ_COMMAND_DONE if(p_result != VMGAHP_REQ_COMMAND_DONE) { dprintf(D_ALWAYS, "Failed to resume the VM\n"); m_vmgahp->printSystemErrorMsg(); delete new_req; internalVMGahpError(); return; } MyString gahpmsg; if( new_req->checkResult(gahpmsg) == false ) { dprintf(D_ALWAYS, "Failed to resume the VM(%s)", gahpmsg.Value()); m_vmgahp->printSystemErrorMsg(); delete new_req; internalVMGahpError(); return; } delete new_req; new_req = NULL; // When we resume a suspended VM, // PID of process for the VM may change // So, we may have a new PID of the process. int vm_pid = PIDofVM(); setVMPID(vm_pid); // set is_suspended to false in os_proc.h is_suspended = false; m_is_soft_suspended = false; is_checkpointed = false; return; } bool VMProc::ShutdownGraceful() { dprintf(D_FULLDEBUG,"Inside VMProc::ShutdownGraceful()\n"); if( !m_vmgahp ) { return true; } if( JobPid == -1 ) { delete m_vmgahp; m_vmgahp = NULL; return true; } if( m_vm_checkpoint ) { // We need to do checkpoint before vacating. // The reason we call checkpoint explicitly here // is to make sure the file uploading for checkpoint. // If file uploading failed, we will not update job classAd // such as the total count of checkpoint and last checkpoint time. m_is_vacate_ckpt = true; is_checkpointed = false; Starter->RemotePeriodicCkpt(1); // Check the success of checkpoint and file transfer if( is_checkpointed && !m_last_ckpt_result ) { // This means the checkpoint succeeded but file transfer failed. // We will not delete files in the working directory so that // file transfer will be retried dprintf(D_ALWAYS, "Vacating checkpoint succeeded but " "file transfer failed\n"); } } // stop the running VM StopVM(); is_suspended = false; m_is_soft_suspended = false; is_checkpointed = false; requested_exit = true; return false; // return false says shutdown is pending } bool VMProc::ShutdownFast() { dprintf(D_FULLDEBUG,"Inside VMProc::ShutdownFast()\n"); if( !m_vmgahp ) { return true; } if( JobPid == -1 ) { delete m_vmgahp; m_vmgahp = NULL; return true; } // stop the running VM StopVM(); is_suspended = false; m_is_soft_suspended = false; is_checkpointed = false; requested_exit = true; // destroy vmgahp server if( m_vmgahp->cleanup() == false ) { //daemonCore->Send_Signal(JobPid, SIGKILL); daemonCore->Kill_Family(JobPid); // To make sure that the process dealing with a VM exits, killProcessForVM(); } // final cleanup.. cleanup(); return false; // shutdown is pending, so return false } bool VMProc::Remove() { return ShutdownFast(); } bool VMProc::Hold() { return ShutdownFast(); } bool VMProc::StopVM() { dprintf(D_FULLDEBUG,"Inside VMProc::StopVM\n"); if( !m_vm_id || !m_vmgahp ) { return true; } VMGahpRequest *new_req = new VMGahpRequest(m_vmgahp); ASSERT(new_req); new_req->setMode(VMGahpRequest::BLOCKING); new_req->setTimeout(m_vmoperation_timeout); int p_result; p_result = new_req->vmStop(m_vm_id); // Because req is blocking mode, result should be VMGAHP_REQ_COMMAND_DONE if(p_result != VMGAHP_REQ_COMMAND_DONE) { dprintf(D_ALWAYS, "Failed to stop VM\n"); m_vmgahp->printSystemErrorMsg(); reportErrorToStartd(); delete new_req; return false; } MyString gahpmsg; if( new_req->checkResult(gahpmsg) == false ) { dprintf(D_ALWAYS, "Failed to stop the VM(%s)\n", gahpmsg.Value()); m_vmgahp->printSystemErrorMsg(); reportErrorToStartd(); delete new_req; return false; } delete new_req; new_req = NULL; // VM is successfully stopped. setVMPID(0); is_suspended = false; m_is_soft_suspended = false; is_checkpointed = false; return true; } bool VMProc::Ckpt() { dprintf(D_FULLDEBUG,"Inside VMProc::Ckpt()\n"); if( !m_vm_id || !m_vmgahp ) { return false; } // Check the flag for vm checkpoint in job classAd if( !m_vm_checkpoint ) { return false; } if( (strcasecmp(m_vm_type.Value(), CONDOR_VM_UNIVERSE_XEN) == MATCH) || (strcasecmp(m_vm_type.Value(), CONDOR_VM_UNIVERSE_KVM) == MATCH) ) { if( !m_is_vacate_ckpt ) { // Xen doesn't support periodic checkpoint return false; } } VMGahpRequest *new_req = new VMGahpRequest(m_vmgahp); ASSERT(new_req); new_req->setMode(VMGahpRequest::BLOCKING); new_req->setTimeout(m_vmoperation_timeout); int p_result; p_result = new_req->vmCheckpoint(m_vm_id); // Because req is blocking mode, result should be VMGAHP_REQ_COMMAND_DONE if(p_result != VMGAHP_REQ_COMMAND_DONE) { dprintf(D_ALWAYS, "Failed to checkpoint the VM\n"); m_vmgahp->printSystemErrorMsg(); delete new_req; internalVMGahpError(); return false; } MyString gahpmsg; if( new_req->checkResult(gahpmsg) == false ) { dprintf(D_ALWAYS, "Failed to checkpoint the VM(%s)", gahpmsg.Value()); m_vmgahp->printSystemErrorMsg(); delete new_req; if( strcmp(gahpmsg.Value(), VMGAHP_ERR_VM_NO_SUPPORT_CHECKPOINT) ) { // It is possible that a VM job is just finished. // So we reset the timer for status if( m_vmstatus_tid != -1 ) { daemonCore->Reset_Timer(m_vmstatus_tid, 0, m_vmstatus_interval); } } return false; } delete new_req; new_req = NULL; #if defined(LINUX) // To avoid lazy-write behavior to disk sync(); #endif // After checkpointing, VM process exits. setVMPID(0); m_is_soft_suspended = false; is_checkpointed = true; return true; } void VMProc::CkptDone(bool success) { if( !is_checkpointed ) { return; } dprintf(D_FULLDEBUG,"Inside VMProc::CkptDone()\n"); m_last_ckpt_result = success; if( success ) { // File uploading succeeded // update checkpoint counter and last ckpt timestamp m_vm_ckpt_count++; m_vm_last_ckpt_time = time(NULL); } if( m_is_vacate_ckpt ) { // This is a vacate checkpoint. // So we don't need to call continue. return; } if( is_suspended ) { // The status before checkpoint was suspended. Starter->RemoteSuspend(1); }else { Starter->RemoteContinue(1); } } int VMProc::PIDofVM() { dprintf(D_FULLDEBUG,"Inside VMProc::PIDofVM()\n"); if( !m_vm_id || !m_vmgahp ) { return 0; } VMGahpRequest *new_req = new VMGahpRequest(m_vmgahp); ASSERT(new_req); new_req->setMode(VMGahpRequest::BLOCKING); new_req->setTimeout(m_vmoperation_timeout); int p_result; p_result = new_req->vmGetPid(m_vm_id); // Because req is blocking mode, result should be VMGAHP_REQ_COMMAND_DONE if(p_result != VMGAHP_REQ_COMMAND_DONE) { dprintf(D_ALWAYS, "Failed to get PID of VM\n"); m_vmgahp->printSystemErrorMsg(); delete new_req; internalVMGahpError(); return 0; } MyString gahpmsg; if( new_req->checkResult(gahpmsg) == false ) { dprintf(D_ALWAYS, "Failed to get PID of VM(%s)", gahpmsg.Value()); m_vmgahp->printSystemErrorMsg(); delete new_req; return 0; } Gahp_Args *result_args; result_args = new_req->getResult(); // Get PID of VM int return_pid = (int)strtol(result_args->argv[2], (char **)NULL, 10); if( return_pid <= 0 ) { return_pid = 0; } delete new_req; new_req = NULL; return return_pid; } bool VMProc::PublishUpdateAd( ClassAd* ad ) { dprintf( D_FULLDEBUG, "Inside VMProc::PublishUpdateAd()\n" ); std::string memory_usage; if (param(memory_usage, "MEMORY_USAGE_METRIC_VM", ATTR_VM_MEMORY)) { ad->AssignExpr(ATTR_MEMORY_USAGE, memory_usage.c_str()); } if( (strcasecmp(m_vm_type.Value(), CONDOR_VM_UNIVERSE_XEN) == MATCH) || (strcasecmp(m_vm_type.Value(), CONDOR_VM_UNIVERSE_KVM) == MATCH) ) { double sys_time = 0.0; double user_time = m_vm_cputime; // Publish it into the ad. ad->Assign(ATTR_JOB_REMOTE_SYS_CPU, sys_time ); ad->Assign(ATTR_JOB_REMOTE_USER_CPU, user_time ); ad->Assign(ATTR_JOB_VM_CPU_UTILIZATION, m_vm_utilization); ad->Assign( ATTR_IMAGE_SIZE, m_vm_max_memory ); ad->Assign( ATTR_RESIDENT_SET_SIZE, m_vm_memory ); }else { // Update usage of process for VM long sys_time = 0; long user_time = 0; unsigned long max_image = 0; unsigned long rss = 0; unsigned long pss = 0; bool pss_available = false; getUsageOfVM(sys_time, user_time, max_image, rss, pss, pss_available); // Added to update CPU Usage of VM in ESX if ( long(m_vm_cputime) > user_time ) { user_time = long(m_vm_cputime); } // Publish it into the ad. ad->Assign(ATTR_JOB_REMOTE_SYS_CPU, (double)sys_time); ad->Assign(ATTR_JOB_REMOTE_USER_CPU, (double)user_time); ad->Assign(ATTR_IMAGE_SIZE, max_image); ad->Assign(ATTR_RESIDENT_SET_SIZE, rss); if( pss_available ) { ad->Assign(ATTR_PROPORTIONAL_SET_SIZE,pss); } } if( m_vm_checkpoint ) { if( m_vm_mac.IsEmpty() == false ) { // Update MAC addresss of VM ad->Assign(ATTR_VM_CKPT_MAC, m_vm_mac); } if( m_vm_ip.IsEmpty() == false ) { // Update IP addresss of VM ad->Assign(ATTR_VM_CKPT_IP, m_vm_ip); } } // Now, call our parent class's version return OsProc::PublishUpdateAd(ad); } void VMProc::internalVMGahpError() { // Reports vmgahp error to local startd // thus local startd will disable vm universe if( reportErrorToStartd() == false ) { dprintf(D_ALWAYS,"ERROR: Failed to report a VMGahp error to local startd\n"); } daemonCore->Send_Signal(daemonCore->getpid(), DC_SIGHARDKILL); } MSC_DISABLE_WARNING(6262) // function uses 60844 bytes of stack. bool VMProc::reportErrorToStartd() { Daemon startd(DT_STARTD, NULL); if( !startd.locate() ) { dprintf(D_ALWAYS,"ERROR: %s\n", startd.error()); return false; } const char* addr = startd.addr(); if( !addr ) { dprintf(D_ALWAYS,"Can't find the address of local startd\n"); return false; } // Using udp packet SafeSock ssock; ssock.timeout( 5 ); // 5 seconds timeout ssock.encode(); if( !ssock.connect(addr) ) { dprintf( D_ALWAYS, "Failed to connect to local startd(%s)\n", addr); return false; } int cmd = VM_UNIV_GAHP_ERROR; if( !startd.startCommand(cmd, &ssock) ) { dprintf( D_ALWAYS, "Failed to send UDP command(%s) to local startd %s\n", getCommandString(cmd), addr); return false; } // Send pid of this starter ssock.put( IntToStr( (int)daemonCore->getpid() ) ); if( !ssock.end_of_message() ) { dprintf( D_FULLDEBUG, "Failed to send EOM to local startd %s\n", addr); return false; } sleep(1); return true; } bool VMProc::reportVMInfoToStartd(int cmd, const char *value) { Daemon startd(DT_STARTD, NULL); if( !startd.locate() ) { dprintf(D_ALWAYS,"ERROR: %s\n", startd.error()); return false; } const char* addr = startd.addr(); if( !addr ) { dprintf(D_ALWAYS,"Can't find the address of local startd\n"); return false; } // Using udp packet SafeSock ssock; ssock.timeout( 5 ); // 5 seconds timeout ssock.encode(); if( !ssock.connect(addr) ) { dprintf( D_ALWAYS, "Failed to connect to local startd(%s)\n", addr); return false; } if( !startd.startCommand(cmd, &ssock) ) { dprintf( D_ALWAYS, "Failed to send UDP command(%s) " "to local startd %s\n", getCommandString(cmd), addr); return false; } // Send the pid of this starter ssock.put( IntToStr( (int)daemonCore->getpid() ) ); // Send vm info ssock.put(value); if( !ssock.end_of_message() ) { dprintf( D_FULLDEBUG, "Failed to send EOM to local startd %s\n", addr); return false; } sleep(1); return true; } MSC_RESTORE_WARNING(6262) // function uses 60844 bytes of stack. bool VMProc::vm_univ_detect() { return true; } void VMProc::setVMPID(int vm_pid) { if( m_vm_pid == vm_pid ) { // PID doesn't change return; } dprintf(D_FULLDEBUG,"PID for VM is changed from [%d] to [%d]\n", m_vm_pid, vm_pid); //PID changes m_vm_pid = vm_pid; // Add the old usage to m_vm_exited_pinfo m_vm_exited_pinfo.sys_time += m_vm_alive_pinfo.sys_time; m_vm_exited_pinfo.user_time += m_vm_alive_pinfo.user_time; if( m_vm_alive_pinfo.rssize > m_vm_exited_pinfo.rssize ) { m_vm_exited_pinfo.rssize = m_vm_alive_pinfo.rssize; } if( m_vm_alive_pinfo.imgsize > m_vm_exited_pinfo.imgsize ) { m_vm_exited_pinfo.imgsize = m_vm_alive_pinfo.imgsize; } // Reset usage of the current process for VM memset(&m_vm_alive_pinfo, 0, sizeof(m_vm_alive_pinfo)); // Get initial usage of the process updateUsageOfVM(); MyString pid_string = IntToStr( (int)m_vm_pid ); // Report this PID to local startd reportVMInfoToStartd(VM_UNIV_VMPID, pid_string.Value()); } void VMProc::setVMMAC(const char* mac) { if( !strcasecmp(m_vm_mac.Value(), mac) ) { // MAC for VM doesn't change return; } dprintf(D_FULLDEBUG,"MAC for VM is changed from [%s] to [%s]\n", m_vm_mac.Value(), mac); m_vm_mac = mac; // Report this MAC to local startd reportVMInfoToStartd(VM_UNIV_GUEST_MAC, m_vm_mac.Value()); } void VMProc::setVMIP(const char* ip) { if( !strcasecmp(m_vm_ip.Value(), ip) ) { // IP for VM doesn't change return; } dprintf(D_FULLDEBUG,"IP for VM is changed from [%s] to [%s]\n", m_vm_ip.Value(), ip); m_vm_ip = ip; // Report this IP to local startd reportVMInfoToStartd(VM_UNIV_GUEST_IP, m_vm_ip.Value()); } void VMProc::updateUsageOfVM() { if( m_vm_pid == 0 ) { return; } int proc_status = PROCAPI_OK; struct procInfo pinfo; memset(&pinfo, 0, sizeof(pinfo)); piPTR pi = &pinfo; if( ProcAPI::getProcInfo(m_vm_pid, pi, proc_status) == PROCAPI_SUCCESS ) { memcpy(&m_vm_alive_pinfo, &pinfo, sizeof(m_vm_alive_pinfo)); dprintf(D_FULLDEBUG,"Usage of process[%d] for a VM is updated\n", m_vm_pid); #if defined(WIN32) dprintf(D_FULLDEBUG,"sys_time=%lu, user_time=%lu, image_size=%lu\n", pinfo.sys_time, pinfo.user_time, pinfo.rssize); #else dprintf(D_FULLDEBUG,"sys_time=%lu, user_time=%lu, image_size=%lu\n", pinfo.sys_time, pinfo.user_time, pinfo.imgsize); #endif } } void VMProc::getUsageOfVM(long &sys_time, long& user_time, unsigned long &max_image, unsigned long& rss, unsigned long& pss, bool &pss_available) { updateUsageOfVM(); sys_time = m_vm_exited_pinfo.sys_time + m_vm_alive_pinfo.sys_time; user_time = m_vm_exited_pinfo.user_time + m_vm_alive_pinfo.user_time; rss = (m_vm_exited_pinfo.rssize > m_vm_alive_pinfo.rssize) ? m_vm_exited_pinfo.rssize : m_vm_alive_pinfo.rssize; #if HAVE_PSS pss = (m_vm_exited_pinfo.pssize > m_vm_alive_pinfo.pssize) ? m_vm_exited_pinfo.pssize : m_vm_alive_pinfo.pssize; pss_available = m_vm_exited_pinfo.pssize_available || m_vm_alive_pinfo.pssize_available; #else pss_available = false; pss = 0; #endif #if defined(WIN32) max_image = (m_vm_exited_pinfo.rssize > m_vm_alive_pinfo.rssize) ? m_vm_exited_pinfo.rssize : m_vm_alive_pinfo.rssize; #else max_image = (m_vm_exited_pinfo.imgsize > m_vm_alive_pinfo.imgsize) ? m_vm_exited_pinfo.imgsize : m_vm_alive_pinfo.imgsize; #endif } void VMProc::killProcessForVM() { if( m_vm_pid > 0 ) { updateUsageOfVM(); dprintf(D_FULLDEBUG,"Sending SIGKILL to process for VM\n"); daemonCore->Send_Signal(m_vm_pid, SIGKILL); } return; } void VMProc::vm_status_error() { // If there is a error, we will retry up to m_vmstatus_max_error_cnt // If we still have a problem after that, we will destroy vmgahp. // Unless there is an error, m_status_error_count will be reset to 0 m_status_error_count++; if( m_status_error_count >= m_vmstatus_max_error_cnt ) { if( m_vmgahp ) { m_vmgahp->printSystemErrorMsg(); } dprintf(D_ALWAYS, "Repeated attempts to receive valid VM status " "failed up to %d times\n", m_vmstatus_max_error_cnt); // something is wrong internalVMGahpError(); } return; }
26.348598
141
0.700441
[ "object" ]
4fa098e45f68881b43d1168fa5fda154c4daa445
11,171
cpp
C++
Siv3D/src/Siv3D-Platform/OpenGL4/Siv3D/Texture/GL4/CTexture_GL4.cpp
emadurandal/OpenSiv3D
2c7a77526be7bb8669a223066210337d74bdc9c6
[ "MIT" ]
709
2016-03-19T07:55:58.000Z
2022-03-31T08:02:22.000Z
Siv3D/src/Siv3D-Platform/OpenGL4/Siv3D/Texture/GL4/CTexture_GL4.cpp
emadurandal/OpenSiv3D
2c7a77526be7bb8669a223066210337d74bdc9c6
[ "MIT" ]
415
2017-05-21T05:05:02.000Z
2022-03-29T16:08:27.000Z
Siv3D/src/Siv3D-Platform/OpenGL4/Siv3D/Texture/GL4/CTexture_GL4.cpp
emadurandal/OpenSiv3D
2c7a77526be7bb8669a223066210337d74bdc9c6
[ "MIT" ]
123
2016-03-19T12:47:08.000Z
2022-03-25T03:47:51.000Z
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2021 Ryo Suzuki // Copyright (c) 2016-2021 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # include "CTexture_GL4.hpp" # include <Siv3D/Error.hpp> # include <Siv3D/System.hpp> # include <Siv3D/EngineLog.hpp> # include <Siv3D/Texture/TextureCommon.hpp> namespace s3d { CTexture_GL4::CTexture_GL4() { // do nothing } CTexture_GL4::~CTexture_GL4() { LOG_SCOPED_TRACE(U"CTexture_GL4::~CTexture_GL4()"); m_textures.destroy(); } void CTexture_GL4::init() { // null Texture を管理に登録 { const Image image{ 16, Palette::Yellow }; const Array<Image> mips = { Image{ 8, Palette::Yellow }, Image{ 4, Palette::Yellow }, Image{ 2, Palette::Yellow }, Image{ 1, Palette::Yellow } }; // null Texture を作成 auto nullTexture = std::make_unique<GL4Texture>(image, mips, TextureDesc::Mipped); if (not nullTexture->isInitialized()) // もし作成に失敗していたら { throw EngineError(U"Null Texture initialization failed"); } // 管理に登録 m_textures.setNullData(std::move(nullTexture)); } } void CTexture_GL4::updateAsyncTextureLoad(const size_t maxUpdate) { if (not isMainThread()) { return; } // 終了時は即座に全消去 if (maxUpdate == Largest<size_t>) { std::lock_guard lock{ m_requestsMutex }; for (auto& request : m_requests) { request.waiting.get() = false; } m_requests.clear(); return; } std::lock_guard lock{ m_requestsMutex }; const size_t loadCount = Min(maxUpdate, m_requests.size()); for (size_t i = 0; i < loadCount; ++i) { auto& request = m_requests[i]; if (*request.pMipmaps) { request.idResult.get() = createMipped(*request.pImage, *request.pMipmaps, *request.pDesc); } else { request.idResult.get() = createUnmipped(*request.pImage, *request.pDesc); } request.waiting.get() = false; } m_requests.pop_front_N(loadCount); } size_t CTexture_GL4::getTextureCount() const { return m_textures.size(); } Texture::IDType CTexture_GL4::createUnmipped(const Image& image, const TextureDesc desc) { if (not image) { return Texture::IDType::NullAsset(); } // OpenGL は異なるスレッドで Texture を作成できないので、実際の作成は updateAsyncTextureLoad() にさせる if (not isMainThread()) { return pushRequest(image, {}, desc); } auto texture = std::make_unique<GL4Texture>(image, desc); if (not texture->isInitialized()) { return Texture::IDType::NullAsset(); } const String info = U"(type: Default, size:{0}x{1}, format: {2})"_fmt(image.width(), image.height(), texture->getFormat().name()); return m_textures.add(std::move(texture), info); } Texture::IDType CTexture_GL4::createMipped(const Image& image, const Array<Image>& mips, const TextureDesc desc) { if (not image) { return Texture::IDType::NullAsset(); } // OpenGL は異なるスレッドで Texture を作成できないので、実際の作成は updateAsyncTextureLoad() にさせる if (not isMainThread()) { return pushRequest(image, mips, desc); } auto texture = std::make_unique<GL4Texture>(image, mips, desc); if (not texture->isInitialized()) { return Texture::IDType::NullAsset(); } const String info = U"(type: Default, size: {0}x{1}, format: {2})"_fmt(image.width(), image.height(), texture->getFormat().name()); return m_textures.add(std::move(texture), info); } Texture::IDType CTexture_GL4::createDynamic(const Size& size, const void* pData, uint32 stride, const TextureFormat& format, const TextureDesc desc) { if ((size.x <= 0) || (size.y <= 0)) { return Texture::IDType::NullAsset(); } auto texture = std::make_unique<GL4Texture>(GL4Texture::Dynamic{}, size, pData, stride, format, desc); if (not texture->isInitialized()) { return Texture::IDType::NullAsset(); } const String info = U"(type: Dynamic, size: {0}x{1}, format: {2})"_fmt(size.x, size.y, texture->getFormat().name()); return m_textures.add(std::move(texture), info); } Texture::IDType CTexture_GL4::createDynamic(const Size& size, const ColorF& color, const TextureFormat& format, const TextureDesc desc) { const Array<Byte> initialData = GenerateInitialColorBuffer(size, color, format); if (not initialData) { return Texture::IDType::NullAsset(); } return createDynamic(size, initialData.data(), static_cast<uint32>(initialData.size() / size.y), format, desc); } Texture::IDType CTexture_GL4::createRT(const Size& size, const TextureFormat& format, const HasDepth hasDepth) { if ((size.x <= 0) || (size.y <= 0)) { return Texture::IDType::NullAsset(); } const TextureDesc desc = (format.isSRGB() ? TextureDesc::UnmippedSRGB : TextureDesc::Unmipped); auto texture = std::make_unique<GL4Texture>(GL4Texture::Render{}, size, format, desc, hasDepth); if (not texture->isInitialized()) { return Texture::IDType::NullAsset(); } const String info = U"(type: Render, size:{0}x{1}, format: {2})"_fmt(size.x, size.y, texture->getFormat().name()); return m_textures.add(std::move(texture), info); } Texture::IDType CTexture_GL4::createRT(const Image& image, const HasDepth hasDepth) { if (not image) { return Texture::IDType::NullAsset(); } const TextureDesc desc = TextureDesc::Unmipped; const TextureFormat format = TextureFormat::R8G8B8A8_Unorm; auto texture = std::make_unique<GL4Texture>(GL4Texture::Render{}, image, format, desc, hasDepth); if (not texture->isInitialized()) { return Texture::IDType::NullAsset(); } const String info = U"(type: Render, size:{0}x{1}, format: {2})"_fmt(image.width(), image.height(), texture->getFormat().name()); return m_textures.add(std::move(texture), info); } Texture::IDType CTexture_GL4::createRT(const Grid<float>& image, const HasDepth hasDepth) { if (not image) { return Texture::IDType::NullAsset(); } const TextureDesc desc = TextureDesc::Unmipped; const TextureFormat format = TextureFormat::R32_Float; auto texture = std::make_unique<GL4Texture>(GL4Texture::Render{}, image, format, desc, hasDepth); if (not texture->isInitialized()) { return Texture::IDType::NullAsset(); } const String info = U"(type: Render, size:{0}x{1}, format: {2})"_fmt(image.width(), image.height(), texture->getFormat().name()); return m_textures.add(std::move(texture), info); } Texture::IDType CTexture_GL4::createRT(const Grid<Float2>& image, const HasDepth hasDepth) { if (not image) { return Texture::IDType::NullAsset(); } const TextureDesc desc = TextureDesc::Unmipped; const TextureFormat format = TextureFormat::R32G32_Float; auto texture = std::make_unique<GL4Texture>(GL4Texture::Render{}, image, format, desc, hasDepth); if (not texture->isInitialized()) { return Texture::IDType::NullAsset(); } const String info = U"(type: Render, size:{0}x{1}, format: {2})"_fmt(image.width(), image.height(), texture->getFormat().name()); return m_textures.add(std::move(texture), info); } Texture::IDType CTexture_GL4::createRT(const Grid<Float4>& image, const HasDepth hasDepth) { if (not image) { return Texture::IDType::NullAsset(); } const TextureDesc desc = TextureDesc::Unmipped; const TextureFormat format = TextureFormat::R32G32B32A32_Float; auto texture = std::make_unique<GL4Texture>(GL4Texture::Render{}, image, format, desc, hasDepth); if (not texture->isInitialized()) { return Texture::IDType::NullAsset(); } const String info = U"(type: Render, size:{0}x{1}, format: {2})"_fmt(image.width(), image.height(), texture->getFormat().name()); return m_textures.add(std::move(texture), info); } Texture::IDType CTexture_GL4::createMSRT(const Size& size, const TextureFormat& format, const HasDepth hasDepth) { if ((size.x <= 0) || (size.y <= 0)) { return Texture::IDType::NullAsset(); } const TextureDesc desc = (format.isSRGB() ? TextureDesc::UnmippedSRGB : TextureDesc::Unmipped); auto texture = std::make_unique<GL4Texture>(GL4Texture::MSRender{}, size, format, desc, hasDepth); if (not texture->isInitialized()) { return Texture::IDType::NullAsset(); } const String info = U"(type: MSRender, size:{0}x{1}, format: {2})"_fmt(size.x, size.y, texture->getFormat().name()); return m_textures.add(std::move(texture), info); } void CTexture_GL4::release(const Texture::IDType handleID) { m_textures.erase(handleID); } Size CTexture_GL4::getSize(const Texture::IDType handleID) { return m_textures[handleID]->getSize(); } TextureDesc CTexture_GL4::getDesc(const Texture::IDType handleID) { return m_textures[handleID]->getDesc(); } TextureFormat CTexture_GL4::getFormat(const Texture::IDType handleID) { return m_textures[handleID]->getFormat(); } bool CTexture_GL4::hasDepth(const Texture::IDType handleID) { return m_textures[handleID]->hasDepth(); } bool CTexture_GL4::fill(const Texture::IDType handleID, const ColorF& color, const bool wait) { return m_textures[handleID]->fill(color, wait); } bool CTexture_GL4::fillRegion(const Texture::IDType handleID, const ColorF& color, const Rect& rect) { return m_textures[handleID]->fillRegion(color, rect); } bool CTexture_GL4::fill(const Texture::IDType handleID, const void* src, uint32 stride, const bool wait) { return m_textures[handleID]->fill(src, stride, wait); } bool CTexture_GL4::fillRegion(const Texture::IDType handleID, const void* src, const uint32 stride, const Rect& rect, const bool wait) { return m_textures[handleID]->fillRegion(src, stride, rect, wait); } void CTexture_GL4::clearRT(const Texture::IDType handleID, const ColorF& color) { m_textures[handleID]->clearRT(color); } void CTexture_GL4::readRT(const Texture::IDType handleID, Image& image) { m_textures[handleID]->readRT(image); } void CTexture_GL4::readRT(const Texture::IDType handleID, Grid<float>& image) { m_textures[handleID]->readRT(image); } void CTexture_GL4::readRT(const Texture::IDType handleID, Grid<Float2>& image) { m_textures[handleID]->readRT(image); } void CTexture_GL4::readRT(const Texture::IDType handleID, Grid<Float4>& image) { m_textures[handleID]->readRT(image); } void CTexture_GL4::resolveMSRT(const Texture::IDType handleID) { m_textures[handleID]->resolveMSRT(); } GLuint CTexture_GL4::getTexture(const Texture::IDType handleID) { return m_textures[handleID]->getTexture(); } GLuint CTexture_GL4::getFrameBuffer(const Texture::IDType handleID) { return m_textures[handleID]->getFrameBuffer(); } bool CTexture_GL4::isMainThread() const noexcept { return (std::this_thread::get_id() == m_mainThreadID); } Texture::IDType CTexture_GL4::pushRequest(const Image& image, const Array<Image>& mipmaps, const TextureDesc desc) { std::atomic<bool> waiting = true; Texture::IDType result = Texture::IDType::NullAsset(); { std::lock_guard lock{ m_requestsMutex }; m_requests.push_back(Request{ &image, &mipmaps, &desc, std::ref(result), std::ref(waiting) }); } // [Siv3D ToDo] conditional_variable を使う while (waiting) { System::Sleep(3); } return result; } }
27.180049
149
0.688927
[ "render" ]
4fa392ff46ac1c7c0dec2622df8d29eb7a4e439d
16,518
cpp
C++
MediaPlayer/AndroidSLESMediaPlayer/src/FFmpegDecoder.cpp
grvweb/avs-device-sdk
3adeb12230b02a182c928de45d26bc7268d49bb7
[ "Apache-2.0" ]
1
2018-09-05T05:29:21.000Z
2018-09-05T05:29:21.000Z
MediaPlayer/AndroidSLESMediaPlayer/src/FFmpegDecoder.cpp
grvweb/avs-device-sdk
3adeb12230b02a182c928de45d26bc7268d49bb7
[ "Apache-2.0" ]
null
null
null
MediaPlayer/AndroidSLESMediaPlayer/src/FFmpegDecoder.cpp
grvweb/avs-device-sdk
3adeb12230b02a182c928de45d26bc7268d49bb7
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #include <atomic> #include <fstream> #include <thread> extern "C" { #include <libavcodec/avcodec.h> #include <libavformat/avformat.h> #include <libswresample/swresample.h> } #include <AVSCommon/Utils/AudioFormat.h> #include <AVSCommon/Utils/Logger/Logger.h> #include <AVSCommon/Utils/Memory/Memory.h> #include <AVSCommon/Utils/RetryTimer.h> #include <AVSCommon/Utils/String/StringUtils.h> #include "AndroidSLESMediaPlayer/FFmpegDecoder.h" #include "AndroidSLESMediaPlayer/FFmpegDeleter.h" /// String to identify log entries originating from this file. static const std::string TAG("FFmpegDecoder"); /** * Create a LogEntry using this file's TAG and the specified event string. * * @param The event string for this @c LogEntry. */ #define LX(event) alexaClientSDK::avsCommon::utils::logger::LogEntry(TAG, event) namespace alexaClientSDK { namespace mediaPlayer { namespace android { /// The target output sample rate. static constexpr int OUTPUT_SAMPLE_RATE{48000}; /// Represent scenario where there is no flag enabled. static constexpr int NO_FLAGS{0}; /// Represent the timeout for the initialization step. /// /// The timeout value should be long enough to avoid interrupting a normal initialization but it shouldn't sacrifice /// the user perception in case something goes wrong and we require to restart the initialization. static const std::chrono::milliseconds INITIALIZE_TIMEOUT{200}; /// Constant representing a "no error" return value for FFmpeg callback methods. static const int NO_ERROR = 0; using namespace avsCommon::utils; std::unique_ptr<FFmpegDecoder> FFmpegDecoder::create(std::unique_ptr<FFmpegInputControllerInterface> inputController) { if (!inputController) { ACSDK_ERROR(LX("createFailed").d("reason", "nullInputController")); return nullptr; } return std::unique_ptr<FFmpegDecoder>(new FFmpegDecoder(std::move(inputController))); } FFmpegDecoder::FFmpegDecoder(std::unique_ptr<FFmpegInputControllerInterface> input) : m_state{DecodingState::INITIALIZING}, m_inputController{std::move(input)} { } std::pair<FFmpegDecoder::Status, size_t> FFmpegDecoder::read(int16_t* buffer, size_t size) { if (!buffer || size == 0) { ACSDK_ERROR(LX("readFailed").d("reason", "invalidInput").d("buffer", buffer).d("size", size)); return {Status::ERROR, 0}; } if (m_state == DecodingState::INVALID) { ACSDK_ERROR(LX("readFailed").d("reason", "currentStateInvalid")); return {Status::ERROR, 0}; } if (m_state == DecodingState::FINISHED) { ACSDK_DEBUG3(LX("readEmpty").d("reason", "doneDecoding")); return {Status::DONE, 0}; } m_retryCount = 0; size_t wordsRead = 0; auto decodedFrame = std::shared_ptr<AVFrame>(av_frame_alloc(), AVFrameDeleter()); while (m_state != DecodingState::FINISHED && m_state != DecodingState::INVALID) { if (!m_unreadData.isEmpty()) { auto lastReadSize = readData(buffer, size, wordsRead); if (lastReadSize == 0) { if (wordsRead == 0) { ACSDK_ERROR(LX("readFailed").d("reason", "bufferTooSmall").d("bufferSize", size)); return {Status::ERROR, wordsRead}; } break; } wordsRead += lastReadSize; } else { if (m_state == DecodingState::INITIALIZING) { initialize(); } if (m_state == DecodingState::FLUSHING_RESAMPLER) { setState(DecodingState::FINISHED); } if (DecodingState::DECODING == m_state) { decode(); } if (m_state <= DecodingState::FLUSHING_DECODER) { readDecodedFrame(decodedFrame); } if (m_state < DecodingState::FLUSHING_RESAMPLER && (decodedFrame->nb_samples > 0)) { resample(decodedFrame); } } } auto status = (DecodingState::INVALID == m_state) ? Status::ERROR : (DecodingState::FINISHED == m_state) ? Status::DONE : Status::OK; return {status, wordsRead}; } static int shouldInterrupt(void* decoderPtr) { if (!decoderPtr) { ACSDK_ERROR(LX("wasInterruptedFailed").d("reason", "nullDecoderPtr")); return AVERROR_EXTERNAL; } if (static_cast<FFmpegDecoder*>(decoderPtr)->shouldInterruptFFmpeg()) { ACSDK_INFO(LX(__func__).m("FFmpeg was interrupted.")); return AVERROR(EAGAIN); } return NO_ERROR; } bool FFmpegDecoder::shouldInterruptFFmpeg() { auto runtime = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - m_initializeStartTime); return (DecodingState::INVALID == m_state) || ((DecodingState::INITIALIZING == m_state) && (runtime > INITIALIZE_TIMEOUT)); } void FFmpegDecoder::initialize() { FFmpegInputControllerInterface::Result result; std::chrono::milliseconds initialPosition; std::tie(result, m_formatContext, initialPosition) = m_inputController->getCurrentFormatContext(); if (!m_formatContext) { if (FFmpegInputControllerInterface::Result::TRY_AGAIN == result) { ACSDK_DEBUG(LX("initializedFailed").d("reason", "Data unavailable. Try again.")); sleep(); return; } ACSDK_ERROR(LX("initializeFailed").d("reason", "getInputFormatContextFailed").d("result", result)); setState(DecodingState::INVALID); return; } m_formatContext->interrupt_callback.callback = shouldInterrupt; m_formatContext->interrupt_callback.opaque = this; m_initializeStartTime = std::chrono::steady_clock::now(); auto status = avformat_find_stream_info(m_formatContext.get(), nullptr); if (!transitionStateUsingStatus(status, DecodingState::INVALID, "initialize::findStreamInfo")) { return; } AVCodec* codec = nullptr; // We don't own the codec. auto streamIndex = av_find_best_stream(m_formatContext.get(), AVMEDIA_TYPE_AUDIO, -1, -1, &codec, NO_FLAGS); if (!transitionStateUsingStatus(streamIndex, DecodingState::INVALID, "initialize::findBestStream")) { return; } if (initialPosition != std::chrono::milliseconds::zero()) { // Convert the offset given in millisecond to the codec timebase. ACSDK_DEBUG(LX("initialPosition").d("offset(ms)", initialPosition.count())); auto timebase = m_formatContext->streams[streamIndex]->time_base; int64_t timestamp = std::chrono::duration_cast<std::chrono::seconds>(initialPosition).count() * timebase.den / timebase.num; status = av_seek_frame(m_formatContext.get(), streamIndex, timestamp, NO_FLAGS); if (!transitionStateUsingStatus(status, DecodingState::INVALID, "initialize::seekFrame")) { return; } } m_codecContext = std::shared_ptr<AVCodecContext>(avcodec_alloc_context3(codec), AVContextDeleter()); avcodec_parameters_to_context(m_codecContext.get(), m_formatContext->streams[streamIndex]->codecpar); status = avcodec_open2(m_codecContext.get(), codec, nullptr); if (!transitionStateUsingStatus(status, m_state, "initialize::openCodec")) { return; } if (0 == m_codecContext->channel_layout) { // Some codecs do not fill up this property, so use default layout. m_codecContext->channel_layout = av_get_default_channel_layout(m_codecContext->channels); } m_swrContext = std::shared_ptr<SwrContext>( swr_alloc_set_opts( nullptr, AV_CH_LAYOUT_STEREO, // output channels AV_SAMPLE_FMT_S16, // output format (signed 16 bits) OUTPUT_SAMPLE_RATE, // output sample rate m_codecContext->channel_layout, // input channel layout m_codecContext->sample_fmt, // input sample format m_codecContext->sample_rate, // input sample rate 0, // logging NULL), SwrContextDeleter()); if (!m_swrContext) { ACSDK_ERROR(LX("initializeFailed").d("reason", "allocResamplerFailed")); setState(DecodingState::INVALID); return; } status = swr_init(m_swrContext.get()); if (!transitionStateUsingStatus(status, DecodingState::INVALID, "initialize::initContext")) { return; } setState(DecodingState::DECODING); } size_t FFmpegDecoder::readData(int16_t* buffer, size_t size, size_t wordsRead) { // TODO(ACSDK-1517): use av_samples_copy to partially copy the frame and avoid buffer too small issue. auto& frame = m_unreadData.getFrame(); size_t sampleSizeBytes = av_samples_get_buffer_size(nullptr, frame.channels, frame.nb_samples, (AVSampleFormat)frame.format, NO_FLAGS); if ((sampleSizeBytes % (sizeof(buffer[0]) * frame.channels)) != 0) { // Sample size should be format size * number of channels. This may cause glitches in the audio. ACSDK_WARN(LX("readDataTruncated") .d("reason", "Unexpected sample size") .d("sampleSize", sampleSizeBytes) .d("wordSize", sizeof(buffer[0])) .d("channels", frame.channels)); } size_t sampleSizeWords = sampleSizeBytes / sizeof(buffer[0]); if (size >= wordsRead + sampleSizeWords) { // Have enough space. Read the entire frame. size_t writeOffset = wordsRead; memcpy(buffer + writeOffset, frame.data[0], sampleSizeBytes); m_unreadData.setOffset(frame.nb_samples); return sampleSizeWords; } return 0; } void FFmpegDecoder::resample(std::shared_ptr<AVFrame> inputFrame) { int outSamples = av_rescale_rnd( swr_get_delay(m_swrContext.get(), m_codecContext->sample_rate) + inputFrame->nb_samples, OUTPUT_SAMPLE_RATE, m_codecContext->sample_rate, AV_ROUND_UP); m_unreadData.resize(outSamples); auto error = swr_convert_frame(m_swrContext.get(), &m_unreadData.getFrame(), inputFrame.get()); transitionStateUsingStatus(error, DecodingState::INVALID, __func__); } void FFmpegDecoder::decode() { auto packet = std::shared_ptr<AVPacket>(av_packet_alloc(), AVPacketDeleter()); auto status = av_read_frame(m_formatContext.get(), packet.get()); if (transitionStateUsingStatus(status, m_state, "decode::readFrame")) { if (AVERROR_EOF == status) { if (!m_inputController->hasNext()) { setState(DecodingState::FLUSHING_DECODER); } else { next(); } } // Note: We still need to send empty packet when we find an EOF. status = avcodec_send_packet(m_codecContext.get(), packet.get()); transitionStateUsingStatus(status, m_state, "decode::sendPacket"); } } void FFmpegDecoder::next() { if (!m_inputController->next()) { ACSDK_ERROR(LX("nextFailed").d("reason", "inputNextFailed")); setState(DecodingState::INVALID); } else { setState(DecodingState::INITIALIZING); } } void FFmpegDecoder::readDecodedFrame(std::shared_ptr<AVFrame>& decodedFrame) { auto status = avcodec_receive_frame(m_codecContext.get(), decodedFrame.get()); transitionStateUsingStatus(status, DecodingState::FLUSHING_RESAMPLER, __func__); } void FFmpegDecoder::abort() { setState(DecodingState::INVALID); m_abortCondition.notify_one(); } void FFmpegDecoder::sleep() { /// Approximate amount of time to wait between retries in ms. static std::vector<int> retryTable = {10, 25, 50, 100, 200}; auto waitTime = avsCommon::utils::RetryTimer(retryTable).calculateTimeToRetry(m_retryCount); std::mutex mutex; std::unique_lock<std::mutex> lock{mutex}; m_abortCondition.wait_for(lock, waitTime); m_retryCount++; } void FFmpegDecoder::setState(FFmpegDecoder::DecodingState nextState) { DecodingState expectedState; switch (nextState) { case DecodingState::INITIALIZING: expectedState = DecodingState::DECODING; break; case DecodingState::DECODING: expectedState = DecodingState::INITIALIZING; break; case DecodingState::FLUSHING_DECODER: expectedState = DecodingState::DECODING; break; case DecodingState::FLUSHING_RESAMPLER: expectedState = DecodingState::FLUSHING_DECODER; break; case DecodingState::FINISHED: expectedState = DecodingState::FLUSHING_RESAMPLER; break; case DecodingState::INVALID: // All transitions to invalid are possible. ACSDK_DEBUG5(LX("setState").d("from", m_state).d("to", DecodingState::INVALID)); m_state = DecodingState::INVALID; return; } if (!m_state.compare_exchange_strong(expectedState, nextState)) { ACSDK_ERROR(LX("InvalidTransition").d("from", m_state).d("to", nextState)); return; } ACSDK_DEBUG5(LX("setState").d("from", expectedState).d("to", nextState)); } bool FFmpegDecoder::transitionStateUsingStatus( int status, FFmpegDecoder::DecodingState nextState, const std::string& functionName) { if (status < 0) { // We'll try to keep decoding if error was due to buffer under run or corrupted data (e.g.: ACSDK-1684). if (-EAGAIN == status || AVERROR_INVALIDDATA == status) { ACSDK_ERROR(LX(functionName + "Failed").d("error", "tryAgain")); // Manually reset these variables since aviobuf::fill_buffer() set eof_reached even for EAGAIN error, which // invalidate future read operations. m_formatContext->pb->eof_reached = 0; m_formatContext->pb->error = 0; sleep(); return false; } if (status != AVERROR_EOF) { ACSDK_ERROR(LX(functionName + "Failed").d("error", av_err2str(status))); setState(DecodingState::INVALID); return false; } if (nextState != m_state) { setState(nextState); } } return true; } FFmpegDecoder::UnreadData::UnreadData() : m_capacity{0}, m_offset{0}, m_frame{av_frame_alloc(), AVFrameDeleter()} { m_frame->sample_rate = OUTPUT_SAMPLE_RATE; m_frame->channel_layout = AV_CH_LAYOUT_STEREO; m_frame->format = AV_SAMPLE_FMT_S16; } AVFrame& FFmpegDecoder::UnreadData::getFrame() { return *m_frame; } int FFmpegDecoder::UnreadData::getOffset() const { return m_offset; } void FFmpegDecoder::UnreadData::resize(size_t minimumCapacity) { if (m_capacity < minimumCapacity) { m_frame = std::shared_ptr<AVFrame>(av_frame_alloc(), AVFrameDeleter()); m_frame->sample_rate = OUTPUT_SAMPLE_RATE; m_frame->channel_layout = AV_CH_LAYOUT_STEREO; m_frame->format = AV_SAMPLE_FMT_S16; m_capacity = minimumCapacity; } m_frame->nb_samples = m_capacity; m_offset = 0; } bool FFmpegDecoder::UnreadData::isEmpty() const { return m_frame->nb_samples <= m_offset || !m_frame->data[0]; } void FFmpegDecoder::UnreadData::setOffset(int offset) { m_offset = offset; } #define STATE_TO_STREAM(name, stream) \ case FFmpegDecoder::DecodingState::name: \ stream << #name; \ break; std::ostream& operator<<(std::ostream& stream, const FFmpegDecoder::DecodingState state) { switch (state) { STATE_TO_STREAM(DECODING, stream) STATE_TO_STREAM(FLUSHING_DECODER, stream) STATE_TO_STREAM(FLUSHING_RESAMPLER, stream) STATE_TO_STREAM(FINISHED, stream) STATE_TO_STREAM(INVALID, stream) STATE_TO_STREAM(INITIALIZING, stream) } return stream; } } // namespace android } // namespace mediaPlayer } // namespace alexaClientSDK
37.540909
120
0.659281
[ "vector" ]
4fa8049beb71e3d3030b81867bb295d0c12b5b01
1,848
hpp
C++
test/unit/math/rev/fun/jacobian.hpp
christophernhill/math
dc41aba296d592c7099be15eed6ba136d0f140b3
[ "BSD-3-Clause" ]
null
null
null
test/unit/math/rev/fun/jacobian.hpp
christophernhill/math
dc41aba296d592c7099be15eed6ba136d0f140b3
[ "BSD-3-Clause" ]
null
null
null
test/unit/math/rev/fun/jacobian.hpp
christophernhill/math
dc41aba296d592c7099be15eed6ba136d0f140b3
[ "BSD-3-Clause" ]
null
null
null
#ifndef TEST_UNIT_MATH_REV_FUN_JACOBIAN_HPP #define TEST_UNIT_MATH_REV_FUN_JACOBIAN_HPP // ********* here because it's only used for testing ********** // ********* superseded by version in autodiff.hpp for API **** #include <stan/math/rev.hpp> #include <vector> namespace stan { namespace math { /** * Return the Jacobian of the function producing the specified * dependent variables with respect to the specified independent * variables. * * A typical use case would be to take the Jacobian of a function * from independent variables to dependentant variables. For instance, * * <pre> * std::vector<var> f(std::vector<var>& x) { ... } * std::vector<var> x = ...; * std::vector<var> y = f(x); * std::vector<std::vector<double> > J; * jacobian(y, x, J); * </pre> * * After executing this code, <code>J</code> will contain the * Jacobian, stored as a standard vector of gradients. * Specifically, <code>J[m]</code> will be the gradient of <code>y[m]</code> * with respect to <code>x</code>, and thus <code>J[m][n]</code> will be * <code><i>d</i>y[m]/<i>d</i>x[n]</code>. * * @param[in] dependents Dependent (output) variables. * @param[in] independents Indepent (input) variables. * @param[out] jacobian Jacobian of the transform. */ inline void jacobian(std::vector<var>& dependents, std::vector<var>& independents, std::vector<std::vector<double> >& jacobian) { jacobian.resize(dependents.size()); for (size_t i = 0; i < dependents.size(); ++i) { jacobian[i].resize(independents.size()); if (i > 0) set_zero_all_adjoints(); jacobian.push_back(std::vector<double>(0)); grad(dependents[i].vi_); for (size_t j = 0; j < independents.size(); ++j) jacobian[i][j] = independents[j].adj(); } } } // namespace math } // namespace stan #endif
31.862069
76
0.647186
[ "vector", "transform" ]
4fa82b85619c96d1a9648de2081525eb649efa64
12,556
cpp
C++
Engine/source/module/moduleDefinition.cpp
John3/t3d_benchmarking
27a5780ad704aa91b45ff1bb0d69ed07668d03be
[ "MIT" ]
10
2015-03-12T20:20:34.000Z
2021-02-03T08:07:31.000Z
Engine/source/module/moduleDefinition.cpp
John3/t3d_benchmarking
27a5780ad704aa91b45ff1bb0d69ed07668d03be
[ "MIT" ]
3
2015-07-04T23:50:43.000Z
2016-08-01T09:19:52.000Z
Engine/source/module/moduleDefinition.cpp
John3/t3d_benchmarking
27a5780ad704aa91b45ff1bb0d69ed07668d03be
[ "MIT" ]
6
2015-11-28T16:18:26.000Z
2020-03-29T17:14:56.000Z
//----------------------------------------------------------------------------- // Copyright (c) 2013 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- #include "moduleDefinition.h" #ifndef _MODULE_MANAGER_H #include "moduleManager.h" #endif // Script bindings. #include "moduleDefinition_ScriptBinding.h" #ifndef _CONSOLETYPES_H_ #include "console/consoleTypes.h" #endif #ifndef _TAML_H_ #include "persistence/taml/taml.h" #endif //----------------------------------------------------------------------------- IMPLEMENT_CONOBJECT( ModuleDefinition ); //----------------------------------------------------------------------------- ModuleDefinition::ModuleDefinition() : mModuleId(StringTable->EmptyString()), mVersionId( 0 ), mBuildId( 0 ), mEnabled( true ), mSynchronized( false ), mDeprecated( false ), mCriticalMerge( false ), mModuleDescription( StringTable->EmptyString() ), mAuthor(StringTable->EmptyString()), mModuleGroup(StringTable->EmptyString()), mModuleType(StringTable->EmptyString()), mScriptFile(StringTable->EmptyString()), mCreateFunction(StringTable->EmptyString()), mDestroyFunction(StringTable->EmptyString()), mAssetTagsManifest(StringTable->EmptyString()), mModulePath(StringTable->EmptyString()), mModuleFile(StringTable->EmptyString()), mModuleFilePath(StringTable->EmptyString()), mModuleScriptFilePath(StringTable->EmptyString()), mSignature(StringTable->EmptyString()), mLoadCount( 0 ), mLocked( false ), mScopeSet( 0 ), mpModuleManager( NULL ) { // Set Vector Associations. VECTOR_SET_ASSOCIATION( mDependencies ); VECTOR_SET_ASSOCIATION( mModuleAssets ); } //----------------------------------------------------------------------------- void ModuleDefinition::initPersistFields() { // Call parent. Parent::initPersistFields(); addProtectedField("ModuleId", TypeString, Offset(mModuleId, ModuleDefinition), &defaultProtectedSetFn, &defaultProtectedGetFn, ""); /// Module configuration. addProtectedField( "ModuleId", TypeString, Offset(mModuleId, ModuleDefinition), &setModuleId, &defaultProtectedGetFn, "A unique string Id for the module. It can contain any characters except a comma or semi-colon (the asset scope character)." ); addProtectedField( "VersionId", TypeS32, Offset(mVersionId, ModuleDefinition), &setVersionId, &defaultProtectedGetFn, "The version Id. Breaking changes to a module should use a higher version Id." ); addProtectedField( "BuildId", TypeS32, Offset(mBuildId, ModuleDefinition), &setBuildId, &defaultProtectedGetFn, &writeBuildId, "The build Id. Non-breaking changes to a module should use a higher build Id. Optional: If not specified then the build Id will be zero." ); addProtectedField( "enabled", TypeBool, Offset(mEnabled, ModuleDefinition), &setEnabled, &defaultProtectedGetFn, &writeEnabled, "Whether the module is enabled or not. When disabled, it is effectively ignored. Optional: If not specified then the module is enabled." ); addProtectedField( "Synchronized", TypeBool, Offset(mSynchronized, ModuleDefinition), &setSynchronized, &defaultProtectedGetFn, &writeSynchronized, "Whether the module should be synchronized or not. Optional: If not specified then the module is not synchronized." ); addProtectedField( "Deprecated", TypeBool, Offset(mDeprecated, ModuleDefinition), &setDeprecated, &defaultProtectedGetFn, &writeDeprecated, "Whether the module is deprecated or not. Optional: If not specified then the module is not deprecated." ); addProtectedField( "CriticalMerge", TypeBool, Offset(mCriticalMerge, ModuleDefinition), &setDeprecated, &defaultProtectedGetFn, &writeCriticalMerge, "Whether the merging of a module prior to a restart is critical or not. Optional: If not specified then the module is not merge critical." ); addProtectedField( "Description", TypeString, Offset(mModuleDescription, ModuleDefinition), &setModuleDescription, &defaultProtectedGetFn, &writeModuleDescription, "The description typically used for debugging purposes but can be used for anything." ); addProtectedField( "Author", TypeString, Offset(mAuthor, ModuleDefinition), &setAuthor, &defaultProtectedGetFn, &writeAuthor, "The author of the module." ); addProtectedField( "Group", TypeString, Offset(mModuleGroup, ModuleDefinition), &setModuleGroup, &defaultProtectedGetFn, "The module group used typically when loading modules as a group." ); addProtectedField( "Type", TypeString, Offset(mModuleType, ModuleDefinition), &setModuleType, &defaultProtectedGetFn, &writeModuleType, "The module type typically used to distinguish modules during module enumeration. Optional: If not specified then the type is empty although this can still be used as a pseudo 'global' type for instance." ); addProtectedField( "Dependencies", TypeString, Offset(mDependencies, ModuleDefinition), &setDependencies, &getDependencies, &writeDependencies, "A comma-separated list of module Ids/VersionIds (<ModuleId>=<VersionId>,<ModuleId>=<VersionId>,etc) which this module depends upon. Optional: If not specified then no dependencies are assumed." ); addProtectedField( "ScriptFile", TypeString, Offset(mScriptFile, ModuleDefinition), &setScriptFile, &defaultProtectedGetFn, &writeScriptFile, "The name of the script file to compile when loading the module. Optional." ); addProtectedField( "CreateFunction", TypeString, Offset(mCreateFunction, ModuleDefinition), &setCreateFunction, &defaultProtectedGetFn, &writeCreateFunction, "The name of the function used to create the module. Optional: If not specified then no create function is called." ); addProtectedField( "DestroyFunction", TypeString, Offset(mDestroyFunction, ModuleDefinition), &setDestroyFunction, &defaultProtectedGetFn, &writeDestroyFunction, "The name of the function used to destroy the module. Optional: If not specified then no destroy function is called." ); addProtectedField( "AssetTagsManifest", TypeString, Offset(mAssetTagsManifest, ModuleDefinition), &setAssetTagsManifest, &defaultProtectedGetFn, &writeAssetTagsManifest, "The name of tags asset manifest file if this module contains asset tags. Optional: If not specified then no asset tags will be found for this module. Currently, only a single asset tag manifest should exist." ); addProtectedField( "ScopeSet", TypeS32, Offset( mScopeSet, ModuleDefinition ), &defaultProtectedNotSetFn, &getScopeSet, &defaultProtectedNotWriteFn, "The scope set used to control the lifetime scope of objects that the module uses. Objects added to this set are destroyed automatically when the module is unloaded." ); /// Module location (Read-only). addProtectedField( "ModulePath", TypeString, Offset(mModulePath, ModuleDefinition), &defaultProtectedNotSetFn, &defaultProtectedGetFn, &defaultProtectedNotWriteFn, "The path of the module. This is read-only and is available only after the module has been registered by a module manager." ); addProtectedField( "ModuleFile", TypeString, Offset(mModuleFile, ModuleDefinition), &defaultProtectedNotSetFn, &defaultProtectedGetFn, &defaultProtectedNotWriteFn, "The file of the module. This is read-only and is available only after the module has been registered by a module manager." ); addProtectedField( "ModuleFilePath", TypeString, Offset(mModuleFilePath, ModuleDefinition), &defaultProtectedNotSetFn, &defaultProtectedGetFn, &defaultProtectedNotWriteFn, "The file-path of the module definition. This is read-only and is available only after the module has been registered by a module manager." ); addProtectedField( "ModuleScriptFilePath", TypeString, Offset(mModuleScriptFilePath, ModuleDefinition), &defaultProtectedNotSetFn, &defaultProtectedGetFn, &defaultProtectedNotWriteFn, "The file-path of the script-file referenced in the module definition. This is read-only and is available only after the module has been registered by a module manager." ); /// Misc. addProtectedField( "Signature", TypeString, 0, &defaultProtectedNotSetFn, &getSignature, &defaultProtectedNotWriteFn, "A unique signature of the module definition based upon its Id, version and build. This is read-only and is available only after the module has been registered by a module manager." ); } //----------------------------------------------------------------------------- bool ModuleDefinition::getDependency( const U32 dependencyIndex, ModuleDependency& dependency ) const { // Is dependency index out of bounds? if ( dependencyIndex >= (U32)mDependencies.size() ) { // Yes, so warn. Con::warnf("Could not get module dependency '%d' as it is out of range.", dependencyIndex); return false; } // Fetch module dependency. dependency = mDependencies[dependencyIndex]; return true; } //----------------------------------------------------------------------------- bool ModuleDefinition::addDependency( const char* pModuleId, const U32 versionId ) { // Fetch module Id. StringTableEntry moduleId = StringTable->insert( pModuleId ); // Do we have any existing dependencies? if ( mDependencies.size() > 0 ) { // Yes, so is the module Id already a dependency? for( typeModuleDependencyVector::iterator dependencyItr = mDependencies.begin(); dependencyItr != mDependencies.end(); ++dependencyItr ) { // Skip if not the same module Id. if ( dependencyItr->mModuleId != moduleId ) continue; // Dependency already exists so warn. Con::warnf("Could not add dependency of module Id '%s' at version Id '%d' as the module Id is already a dependency.", pModuleId, versionId ); return false; } } // Populate module dependency. ModuleDefinition::ModuleDependency dependency( moduleId, versionId ); // Store dependency. mDependencies.push_back( dependency ); return true; } //----------------------------------------------------------------------------- bool ModuleDefinition::removeDependency( const char* pModuleId ) { // Fetch module Id. StringTableEntry moduleId = StringTable->insert( pModuleId ); // Do we have any existing dependencies? if ( mDependencies.size() > 0 ) { // Yes, so is the module Id a dependency? for( typeModuleDependencyVector::iterator dependencyItr = mDependencies.begin(); dependencyItr != mDependencies.end(); ++dependencyItr ) { // Skip if not the same module Id. if ( dependencyItr->mModuleId != moduleId ) continue; // Remove dependency. mDependencies.erase( dependencyItr ); return true; } } // No, so warn. Con::warnf("Could not remove dependency of module Id '%s' as the module Id is not a dependency.", pModuleId ); return false; } //----------------------------------------------------------------------------- bool ModuleDefinition::save( void ) { // Does the module have a file-path yet? if (mModuleFilePath == StringTable->EmptyString()) { // No, so warn. Con::warnf("Save() - Cannot save module definition '%s' as it does not have a file-path.", mModuleId ); return false; } // Save the module file. Taml taml; return taml.write( this, mModuleFilePath ); }
59.790476
388
0.701099
[ "vector" ]
4fa88ba83d3bffdf2a2c5890ab70258aa8196600
141,597
cpp
C++
cppcache/src/ThinClientRegion.cpp
davebarnes97/geode-native
3f2333f4dc527d2ac799e55801e18d9048ddfd8a
[ "Apache-2.0" ]
null
null
null
cppcache/src/ThinClientRegion.cpp
davebarnes97/geode-native
3f2333f4dc527d2ac799e55801e18d9048ddfd8a
[ "Apache-2.0" ]
null
null
null
cppcache/src/ThinClientRegion.cpp
davebarnes97/geode-native
3f2333f4dc527d2ac799e55801e18d9048ddfd8a
[ "Apache-2.0" ]
null
null
null
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ThinClientRegion.hpp" #include <algorithm> #include <regex> #include <geode/PoolManager.hpp> #include <geode/Struct.hpp> #include <geode/SystemProperties.hpp> #include <geode/UserFunctionExecutionException.hpp> #include "AutoDelete.hpp" #include "CacheImpl.hpp" #include "CacheRegionHelper.hpp" #include "DataInputInternal.hpp" #include "PutAllPartialResultServerException.hpp" #include "ReadWriteLock.hpp" #include "RegionGlobalLocks.hpp" #include "RemoteQuery.hpp" #include "TcrConnectionManager.hpp" #include "TcrDistributionManager.hpp" #include "TcrEndpoint.hpp" #include "ThinClientBaseDM.hpp" #include "ThinClientPoolDM.hpp" #include "UserAttributes.hpp" #include "Utils.hpp" #include "VersionedCacheableObjectPartList.hpp" #include "util/bounds.hpp" #include "util/exception.hpp" namespace apache { namespace geode { namespace client { static const std::regex PREDICATE_IS_FULL_QUERY_REGEX( "^\\s*(?:select|import)\\b", std::regex::icase); void setThreadLocalExceptionMessage(std::string exMsg); class PutAllWork : public PooledWork<GfErrType> { ThinClientPoolDM* m_poolDM; std::shared_ptr<BucketServerLocation> m_serverLocation; TcrMessage* m_request; TcrMessageReply* m_reply; bool m_attemptFailover; bool m_isBGThread; std::shared_ptr<UserAttributes> m_userAttribute; const std::shared_ptr<Region> m_region; std::shared_ptr<HashMapOfCacheable> m_map; std::shared_ptr<VersionedCacheableObjectPartList> m_verObjPartListPtr; std::chrono::milliseconds m_timeout; std::shared_ptr<PutAllPartialResultServerException> m_papException; ChunkedPutAllResponse* m_resultCollector; public: PutAllWork(const PutAllWork&) = delete; PutAllWork& operator=(const PutAllWork&) = delete; PutAllWork( ThinClientPoolDM* poolDM, const std::shared_ptr<BucketServerLocation>& serverLocation, const std::shared_ptr<Region>& region, bool attemptFailover, bool isBGThread, const std::shared_ptr<HashMapOfCacheable> map, const std::shared_ptr<std::vector<std::shared_ptr<CacheableKey>>> keys, std::chrono::milliseconds timeout, const std::shared_ptr<Serializable>& aCallbackArgument) : m_poolDM(poolDM), m_serverLocation(serverLocation), m_attemptFailover(attemptFailover), m_isBGThread(isBGThread), m_userAttribute(nullptr), m_region(region), m_map(map), m_timeout(timeout), m_papException(nullptr) { m_request = new TcrMessagePutAll( new DataOutput(m_region->getCache().createDataOutput()), m_region.get(), *m_map, m_timeout, m_poolDM, aCallbackArgument); m_reply = new TcrMessageReply(true, m_poolDM); // create new instanceof VCOPL std::recursive_mutex responseLock; m_verObjPartListPtr = std::make_shared<VersionedCacheableObjectPartList>(keys, responseLock); if (m_poolDM->isMultiUserMode()) { m_userAttribute = UserAttributes::threadLocalUserAttributes; } m_request->setTimeout(m_timeout); m_reply->setTimeout(m_timeout); m_resultCollector = new ChunkedPutAllResponse( m_region, *m_reply, responseLock, m_verObjPartListPtr); m_reply->setChunkedResultHandler(m_resultCollector); } ~PutAllWork() noexcept override { delete m_request; delete m_reply; delete m_resultCollector; } std::shared_ptr<HashMapOfCacheable> getPutAllMap() { return m_map; } ChunkedPutAllResponse* getResultCollector() { return m_resultCollector; } std::shared_ptr<BucketServerLocation> getServerLocation() { return m_serverLocation; } std::shared_ptr<PutAllPartialResultServerException> getPaPResultException() { return m_papException; } void init() {} GfErrType execute(void) override { GuardUserAttributes gua; if (m_userAttribute != nullptr) { gua.setAuthenticatedView(m_userAttribute->getAuthenticatedView()); } GfErrType err = GF_NOERR; err = m_poolDM->sendSyncRequest(*m_request, *m_reply, m_attemptFailover, m_isBGThread, m_serverLocation); // Set Version Tags LOGDEBUG(" m_verObjPartListPtr size = %d err = %d ", m_resultCollector->getList()->size(), err); m_verObjPartListPtr->setVersionedTagptr( m_resultCollector->getList()->getVersionedTagptr()); if (err != GF_NOERR) { return err; } /*This can be GF_NOTCON, counterpart to java ServerConnectivityException*/ switch (m_reply->getMessageType()) { case TcrMessage::REPLY: break; case TcrMessage::RESPONSE: LOGDEBUG("PutAllwork execute err = %d ", err); break; case TcrMessage::EXCEPTION: // TODO::Check for the PAPException and READ // PutAllPartialResultServerException and set its member for later use. // set m_papException and m_isPapeReceived if (m_poolDM->isNotAuthorizedException(m_reply->getException())) { LOGDEBUG("received NotAuthorizedException"); err = GF_AUTHENTICATION_FAILED_EXCEPTION; } else if (m_poolDM->isPutAllPartialResultException( m_reply->getException())) { LOGDEBUG("received PutAllPartialResultException"); err = GF_PUTALL_PARTIAL_RESULT_EXCEPTION; } else { LOGDEBUG("received unknown exception:" + m_reply->getException()); err = GF_PUTALL_PARTIAL_RESULT_EXCEPTION; // TODO should assign a new err code } break; case TcrMessage::PUT_DATA_ERROR: err = GF_CACHESERVER_EXCEPTION; break; default: LOGERROR("Unknown message type %d during region put-all", m_reply->getMessageType()); err = GF_NOTOBJ; break; } return err; } }; class RemoveAllWork : public PooledWork<GfErrType> { ThinClientPoolDM* m_poolDM; std::shared_ptr<BucketServerLocation> m_serverLocation; TcrMessage* m_request; TcrMessageReply* m_reply; bool m_attemptFailover; bool m_isBGThread; std::shared_ptr<UserAttributes> m_userAttribute; const std::shared_ptr<Region> m_region; const std::shared_ptr<Serializable>& m_aCallbackArgument; std::shared_ptr<VersionedCacheableObjectPartList> m_verObjPartListPtr; std::shared_ptr<PutAllPartialResultServerException> m_papException; ChunkedRemoveAllResponse* m_resultCollector; public: RemoveAllWork(const RemoveAllWork&) = delete; RemoveAllWork& operator=(const RemoveAllWork&) = delete; RemoveAllWork( ThinClientPoolDM* poolDM, const std::shared_ptr<BucketServerLocation>& serverLocation, const std::shared_ptr<Region>& region, bool attemptFailover, bool isBGThread, const std::shared_ptr<std::vector<std::shared_ptr<CacheableKey>>> keys, const std::shared_ptr<Serializable>& aCallbackArgument) : m_poolDM(poolDM), m_serverLocation(serverLocation), m_attemptFailover(attemptFailover), m_isBGThread(isBGThread), m_userAttribute(nullptr), m_region(region), m_aCallbackArgument(aCallbackArgument), m_papException(nullptr) { m_request = new TcrMessageRemoveAll( new DataOutput(m_region->getCache().createDataOutput()), m_region.get(), *keys, m_aCallbackArgument, m_poolDM); m_reply = new TcrMessageReply(true, m_poolDM); // create new instanceof VCOPL std::recursive_mutex responseLock; m_verObjPartListPtr = std::make_shared<VersionedCacheableObjectPartList>(keys, responseLock); if (m_poolDM->isMultiUserMode()) { m_userAttribute = UserAttributes::threadLocalUserAttributes; } m_resultCollector = new ChunkedRemoveAllResponse(m_region, *m_reply, m_verObjPartListPtr); m_reply->setChunkedResultHandler(m_resultCollector); } ~RemoveAllWork() noexcept override { delete m_request; delete m_reply; delete m_resultCollector; } ChunkedRemoveAllResponse* getResultCollector() { return m_resultCollector; } std::shared_ptr<BucketServerLocation> getServerLocation() { return m_serverLocation; } std::shared_ptr<PutAllPartialResultServerException> getPaPResultException() { return m_papException; } void init() {} GfErrType execute(void) override { GuardUserAttributes gua; if (m_userAttribute != nullptr) { gua.setAuthenticatedView(m_userAttribute->getAuthenticatedView()); } GfErrType err = GF_NOERR; err = m_poolDM->sendSyncRequest(*m_request, *m_reply, m_attemptFailover, m_isBGThread, m_serverLocation); // Set Version Tags LOGDEBUG(" m_verObjPartListPtr size = %d err = %d ", m_resultCollector->getList()->size(), err); m_verObjPartListPtr->setVersionedTagptr( m_resultCollector->getList()->getVersionedTagptr()); if (err != GF_NOERR) { return err; } /*This can be GF_NOTCON, counterpart to java ServerConnectivityException*/ switch (m_reply->getMessageType()) { case TcrMessage::REPLY: break; case TcrMessage::RESPONSE: LOGDEBUG("RemoveAllWork execute err = %d ", err); break; case TcrMessage::EXCEPTION: // TODO::Check for the PAPException and READ // PutAllPartialResultServerException and set its member for later use. // set m_papException and m_isPapeReceived if (m_poolDM->isNotAuthorizedException(m_reply->getException())) { LOGDEBUG("received NotAuthorizedException"); err = GF_AUTHENTICATION_FAILED_EXCEPTION; } else if (m_poolDM->isPutAllPartialResultException( m_reply->getException())) { LOGDEBUG("received PutAllPartialResultException"); err = GF_PUTALL_PARTIAL_RESULT_EXCEPTION; } else { LOGDEBUG("received unknown exception:" + m_reply->getException()); err = GF_PUTALL_PARTIAL_RESULT_EXCEPTION; // TODO should assign a new err code } break; case TcrMessage::PUT_DATA_ERROR: err = GF_CACHESERVER_EXCEPTION; break; default: LOGERROR("Unknown message type %d during region remove-all", m_reply->getMessageType()); err = GF_NOTOBJ; break; } return err; } }; ThinClientRegion::ThinClientRegion( const std::string& name, CacheImpl* cacheImpl, const std::shared_ptr<RegionInternal>& rPtr, RegionAttributes attributes, const std::shared_ptr<CacheStatistics>& stats, bool shared) : LocalRegion(name, cacheImpl, rPtr, attributes, stats, shared), m_tcrdm(nullptr), m_notifyRelease(false), m_isMetaDataRefreshed(false) { m_transactionEnabled = true; m_isDurableClnt = !cacheImpl->getDistributedSystem() .getSystemProperties() .durableClientId() .empty(); } void ThinClientRegion::initTCR() { try { m_tcrdm = std::make_shared<TcrDistributionManager>( this, m_cacheImpl->tcrConnectionManager()); m_tcrdm->init(); } catch (const Exception& ex) { LOGERROR("Exception while initializing region: %s: %s", ex.getName().c_str(), ex.what()); throw; } } void ThinClientRegion::registerKeys( const std::vector<std::shared_ptr<CacheableKey>>& keys, bool isDurable, bool getInitialValues, bool receiveValues) { auto pool = m_cacheImpl->getPoolManager().find(getAttributes().getPoolName()); if (pool != nullptr) { if (!pool->getSubscriptionEnabled()) { LOGERROR( "Registering keys is supported " "only if subscription-enabled attribute is true for pool " + pool->getName()); throw UnsupportedOperationException( "Registering keys is supported " "only if pool subscription-enabled attribute is true."); } } if (keys.empty()) { LOGERROR("Register keys list is empty"); throw IllegalArgumentException( "Register keys " "keys vector is empty"); } if (isDurable && !isDurableClient()) { LOGERROR( "Register keys durable flag is only applicable for durable clients"); throw IllegalStateException( "Durable flag only applicable for " "durable clients"); } if (getInitialValues && !m_regionAttributes.getCachingEnabled()) { LOGERROR( "Register keys getInitialValues flag is only applicable for caching" "clients"); throw IllegalStateException( "getInitialValues flag only applicable for caching clients"); } InterestResultPolicy interestPolicy = InterestResultPolicy::NONE; if (getInitialValues) { interestPolicy = InterestResultPolicy::KEYS_VALUES; } LOGDEBUG("ThinClientRegion::registerKeys : interestpolicy is %d", interestPolicy.ordinal); GfErrType err = registerKeysNoThrow(keys, true, nullptr, isDurable, interestPolicy, receiveValues); if (m_tcrdm->isFatalError(err)) { throwExceptionIfError("Region::registerKeys", err); } throwExceptionIfError("Region::registerKeys", err); } void ThinClientRegion::unregisterKeys( const std::vector<std::shared_ptr<CacheableKey>>& keys) { auto pool = m_cacheImpl->getPoolManager().find(getAttributes().getPoolName()); if (pool != nullptr) { if (!pool->getSubscriptionEnabled()) { LOGERROR( "Unregister keys is supported " "only if subscription-enabled attribute is true for pool " + pool->getName()); throw UnsupportedOperationException( "Unregister keys is supported " "only if pool subscription-enabled attribute is true."); } } else { if (!getAttributes().getClientNotificationEnabled()) { LOGERROR( "Unregister keys is supported " "only if region client-notification attribute is true."); throw UnsupportedOperationException( "Unregister keys is supported " "only if region client-notification attribute is true."); } } if (keys.empty()) { LOGERROR("Unregister keys list is empty"); throw IllegalArgumentException( "Unregister keys " "keys vector is empty"); } GfErrType err = unregisterKeysNoThrow(keys); throwExceptionIfError("Region::unregisterKeys", err); } void ThinClientRegion::registerAllKeys(bool isDurable, bool getInitialValues, bool receiveValues) { auto pool = m_cacheImpl->getPoolManager().find(getAttributes().getPoolName()); if (pool != nullptr) { if (!pool->getSubscriptionEnabled()) { LOGERROR( "Register all keys is supported only " "if subscription-enabled attribute is true for pool " + pool->getName()); throw UnsupportedOperationException( "Register all keys is supported only " "if pool subscription-enabled attribute is true."); } } if (isDurable && !isDurableClient()) { LOGERROR( "Register all keys durable flag is only applicable for durable " "clients"); throw IllegalStateException( "Durable flag only applicable for durable clients"); } if (getInitialValues && !m_regionAttributes.getCachingEnabled()) { LOGERROR( "Register all keys getInitialValues flag is only applicable for caching" "clients"); throw IllegalStateException( "getInitialValues flag only applicable for caching clients"); } InterestResultPolicy interestPolicy = InterestResultPolicy::NONE; if (getInitialValues) { interestPolicy = InterestResultPolicy::KEYS_VALUES; } else { interestPolicy = InterestResultPolicy::KEYS; } LOGDEBUG("ThinClientRegion::registerAllKeys : interestpolicy is %d", interestPolicy.ordinal); std::shared_ptr<std::vector<std::shared_ptr<CacheableKey>>> resultKeys; // if we need to fetch initial data, then we get the keys in // that call itself using the special GET_ALL message and do not need // to get the keys in the initial register interest call GfErrType err = registerRegexNoThrow(".*", true, nullptr, isDurable, resultKeys, interestPolicy, receiveValues); if (m_tcrdm->isFatalError(err)) { throwExceptionIfError("Region::registerAllKeys", err); } // Get the entries from the server using a special GET_ALL message throwExceptionIfError("Region::registerAllKeys", err); } void ThinClientRegion::registerRegex(const std::string& regex, bool isDurable, bool getInitialValues, bool receiveValues) { auto pool = m_cacheImpl->getPoolManager().find(getAttributes().getPoolName()); if (pool != nullptr) { if (!pool->getSubscriptionEnabled()) { LOGERROR( "Register regex is supported only if " "subscription-enabled attribute is true for pool " + pool->getName()); throw UnsupportedOperationException( "Register regex is supported only if " "pool subscription-enabled attribute is true."); } } if (isDurable && !isDurableClient()) { LOGERROR("Register regex durable flag only applicable for durable clients"); throw IllegalStateException( "Durable flag only applicable for durable clients"); } if (regex.empty()) { throw IllegalArgumentException( "Region::registerRegex: Regex string is empty"); } auto interestPolicy = InterestResultPolicy::NONE; if (getInitialValues) { interestPolicy = InterestResultPolicy::KEYS_VALUES; } else { interestPolicy = InterestResultPolicy::KEYS; } LOGDEBUG("ThinClientRegion::registerRegex : interestpolicy is %d", interestPolicy.ordinal); auto resultKeys2 = std::make_shared<std::vector<std::shared_ptr<CacheableKey>>>(); // if we need to fetch initial data for "allKeys" case, then we // get the keys in that call itself using the special GET_ALL message and // do not need to get the keys in the initial register interest call GfErrType err = registerRegexNoThrow(regex, true, nullptr, isDurable, resultKeys2, interestPolicy, receiveValues); if (m_tcrdm->isFatalError(err)) { throwExceptionIfError("Region::registerRegex", err); } throwExceptionIfError("Region::registerRegex", err); } void ThinClientRegion::unregisterRegex(const std::string& regex) { auto pool = m_cacheImpl->getPoolManager().find(getAttributes().getPoolName()); if (pool != nullptr) { if (!pool->getSubscriptionEnabled()) { LOGERROR( "Unregister regex is supported only if " "subscription-enabled attribute is true for pool " + pool->getName()); throw UnsupportedOperationException( "Unregister regex is supported only if " "pool subscription-enabled attribute is true."); } } if (regex.empty()) { LOGERROR("Unregister regex string is empty"); throw IllegalArgumentException("Unregister regex string is empty"); } GfErrType err = unregisterRegexNoThrow(regex); throwExceptionIfError("Region::unregisterRegex", err); } void ThinClientRegion::unregisterAllKeys() { auto pool = m_cacheImpl->getPoolManager().find(getAttributes().getPoolName()); if (pool != nullptr) { if (!pool->getSubscriptionEnabled()) { LOGERROR( "Unregister all keys is supported only if " "subscription-enabled attribute is true for pool " + pool->getName()); throw UnsupportedOperationException( "Unregister all keys is supported only if " "pool subscription-enabled attribute is true."); } } GfErrType err = unregisterRegexNoThrow(".*"); throwExceptionIfError("Region::unregisterAllKeys", err); } std::shared_ptr<SelectResults> ThinClientRegion::query( const std::string& predicate, std::chrono::milliseconds timeout) { util::PROTOCOL_OPERATION_TIMEOUT_BOUNDS(timeout); CHECK_DESTROY_PENDING(TryReadGuard, Region::query); if (predicate.empty()) { LOGERROR("Region query predicate string is empty"); throw IllegalArgumentException("Region query predicate string is empty"); } std::string squery; if (std::regex_search(predicate, PREDICATE_IS_FULL_QUERY_REGEX)) { squery = predicate; } else { squery = "select distinct * from "; squery += getFullPath(); squery += " this where "; squery += predicate; } std::shared_ptr<RemoteQuery> queryPtr; if (auto poolDM = std::dynamic_pointer_cast<ThinClientPoolDM>(m_tcrdm)) { queryPtr = std::dynamic_pointer_cast<RemoteQuery>( poolDM->getQueryServiceWithoutCheck()->newQuery(squery.c_str())); } else { queryPtr = std::dynamic_pointer_cast<RemoteQuery>( m_cacheImpl->getQueryService()->newQuery(squery.c_str())); } return queryPtr->execute(timeout, "Region::query", m_tcrdm.get(), nullptr); } bool ThinClientRegion::existsValue(const std::string& predicate, std::chrono::milliseconds timeout) { util::PROTOCOL_OPERATION_TIMEOUT_BOUNDS(timeout); auto results = query(predicate, timeout); if (results == nullptr) { return false; } return results->size() > 0; } GfErrType ThinClientRegion::unregisterKeysBeforeDestroyRegion() { auto pool = m_cacheImpl->getPoolManager().find(getAttributes().getPoolName()); if (pool != nullptr) { if (!pool->getSubscriptionEnabled()) { LOGDEBUG( "pool subscription-enabled attribute is false, No need to Unregister " "keys"); return GF_NOERR; } } GfErrType err = GF_NOERR; GfErrType opErr = GF_NOERR; opErr = unregisterStoredRegexLocalDestroy(m_interestListRegex); err = opErr != GF_NOERR ? opErr : err; opErr = unregisterStoredRegexLocalDestroy(m_durableInterestListRegex); err = opErr != GF_NOERR ? opErr : err; opErr = unregisterStoredRegexLocalDestroy( m_interestListRegexForUpdatesAsInvalidates); err = opErr != GF_NOERR ? opErr : err; opErr = unregisterStoredRegexLocalDestroy( m_durableInterestListRegexForUpdatesAsInvalidates); err = opErr != GF_NOERR ? opErr : err; std::vector<std::shared_ptr<CacheableKey>> keysVec; copyInterestList(keysVec, m_interestList); opErr = unregisterKeysNoThrowLocalDestroy(keysVec, false); err = opErr != GF_NOERR ? opErr : err; std::vector<std::shared_ptr<CacheableKey>> keysVecDurable; copyInterestList(keysVecDurable, m_durableInterestList); opErr = unregisterKeysNoThrowLocalDestroy(keysVecDurable, false); err = opErr != GF_NOERR ? opErr : err; std::vector<std::shared_ptr<CacheableKey>> keysVecForUpdatesAsInvalidates; copyInterestList(keysVecForUpdatesAsInvalidates, m_interestListForUpdatesAsInvalidates); opErr = unregisterKeysNoThrowLocalDestroy(keysVecForUpdatesAsInvalidates, false); err = opErr != GF_NOERR ? opErr : err; std::vector<std::shared_ptr<CacheableKey>> keysVecDurableForUpdatesAsInvalidates; copyInterestList(keysVecDurableForUpdatesAsInvalidates, m_durableInterestListForUpdatesAsInvalidates); opErr = unregisterKeysNoThrowLocalDestroy( keysVecDurableForUpdatesAsInvalidates, false); err = opErr != GF_NOERR ? opErr : err; return err; } std::shared_ptr<Serializable> ThinClientRegion::selectValue( const std::string& predicate, std::chrono::milliseconds timeout) { auto results = query(predicate, timeout); if (results == nullptr || results->size() == 0) { return nullptr; } if (results->size() > 1) { throw QueryException("selectValue has more than one result"); } return results->operator[](0); } std::vector<std::shared_ptr<CacheableKey>> ThinClientRegion::serverKeys() { CHECK_DESTROY_PENDING(TryReadGuard, Region::serverKeys); TcrMessageReply reply(true, m_tcrdm.get()); TcrMessageKeySet request(new DataOutput(m_cacheImpl->createDataOutput()), m_fullPath, m_tcrdm.get()); reply.setMessageTypeRequest(TcrMessage::KEY_SET); std::vector<std::shared_ptr<CacheableKey>> serverKeys; ChunkedKeySetResponse resultCollector(request, serverKeys, reply); reply.setChunkedResultHandler(&resultCollector); GfErrType err = GF_NOERR; err = m_tcrdm->sendSyncRequest(request, reply); throwExceptionIfError("Region::serverKeys", err); switch (reply.getMessageType()) { case TcrMessage::RESPONSE: { // keyset result is handled by ChunkedKeySetResponse break; } case TcrMessage::EXCEPTION: { err = handleServerException("Region:serverKeys", reply.getException()); break; } case TcrMessage::KEY_SET_DATA_ERROR: { LOGERROR("Region serverKeys: an error occurred on the server"); err = GF_CACHESERVER_EXCEPTION; break; } default: { LOGERROR("Unknown message type %d during region serverKeys", reply.getMessageType()); err = GF_MSG; break; } } throwExceptionIfError("Region::serverKeys", err); return serverKeys; } bool ThinClientRegion::containsKeyOnServer( const std::shared_ptr<CacheableKey>& keyPtr) const { GfErrType err = GF_NOERR; bool ret = false; /** @brief Create message and send to bridge server */ TcrMessageContainsKey request( new DataOutput(m_cacheImpl->createDataOutput()), this, keyPtr, static_cast<std::shared_ptr<Serializable>>(nullptr), true, m_tcrdm.get()); TcrMessageReply reply(true, m_tcrdm.get()); reply.setMessageTypeRequest(TcrMessage::CONTAINS_KEY); err = m_tcrdm->sendSyncRequest(request, reply); switch (reply.getMessageType()) { case TcrMessage::RESPONSE: ret = reply.getBoolValue(); break; case TcrMessage::EXCEPTION: err = handleServerException("Region::containsKeyOnServer:", reply.getException()); break; case TcrMessage::REQUEST_DATA_ERROR: LOGERROR( "Region::containsKeyOnServer: read error occurred on the endpoint %s", m_tcrdm->getActiveEndpoint()->name().c_str()); err = GF_CACHESERVER_EXCEPTION; break; default: LOGERROR("Unknown message type in Region::containsKeyOnServer %d", reply.getMessageType()); err = GF_MSG; break; } auto rptr = CacheableBoolean::create(ret); rptr = std::dynamic_pointer_cast<CacheableBoolean>(handleReplay(err, rptr)); throwExceptionIfError("Region::containsKeyOnServer ", err); return rptr->value(); } bool ThinClientRegion::containsValueForKey_remote( const std::shared_ptr<CacheableKey>& keyPtr) const { GfErrType err = GF_NOERR; bool ret = false; /** @brief Create message and send to bridge server */ TcrMessageContainsKey request( new DataOutput(m_cacheImpl->createDataOutput()), this, keyPtr, static_cast<std::shared_ptr<Serializable>>(nullptr), false, m_tcrdm.get()); TcrMessageReply reply(true, m_tcrdm.get()); reply.setMessageTypeRequest(TcrMessage::CONTAINS_KEY); err = m_tcrdm->sendSyncRequest(request, reply); // if ( err != GF_NOERR ) return ret; switch (reply.getMessageType()) { case TcrMessage::RESPONSE: ret = reply.getBoolValue(); break; case TcrMessage::EXCEPTION: err = handleServerException("Region::containsValueForKey:", reply.getException()); break; case TcrMessage::REQUEST_DATA_ERROR: LOGERROR( "Region::containsValueForKey: read error occurred on the endpoint %s", m_tcrdm->getActiveEndpoint()->name().c_str()); err = GF_CACHESERVER_EXCEPTION; break; default: LOGERROR("Unknown message type in Region::containsValueForKey %d", reply.getMessageType()); err = GF_MSG; break; } auto rptr = CacheableBoolean::create(ret); rptr = std::dynamic_pointer_cast<CacheableBoolean>(handleReplay(err, rptr)); throwExceptionIfError("Region::containsValueForKey ", err); return rptr->value(); } void ThinClientRegion::clear( const std::shared_ptr<Serializable>& aCallbackArgument) { GfErrType err = GF_NOERR; err = localClearNoThrow(aCallbackArgument, CacheEventFlags::NORMAL); if (err != GF_NOERR) throwExceptionIfError("Region::clear", err); /** @brief Create message and send to bridge server */ TcrMessageClearRegion request(new DataOutput(m_cacheImpl->createDataOutput()), this, aCallbackArgument, std::chrono::milliseconds(-1), m_tcrdm.get()); TcrMessageReply reply(true, m_tcrdm.get()); err = m_tcrdm->sendSyncRequest(request, reply); if (err != GF_NOERR) throwExceptionIfError("Region::clear", err); switch (reply.getMessageType()) { case TcrMessage::REPLY: LOGFINE("Region %s clear message sent to server successfully", m_fullPath.c_str()); break; case TcrMessage::EXCEPTION: err = handleServerException("Region::clear:", reply.getException()); break; case TcrMessage::CLEAR_REGION_DATA_ERROR: LOGERROR("Region clear read error occurred on the endpoint %s", m_tcrdm->getActiveEndpoint()->name().c_str()); err = GF_CACHESERVER_EXCEPTION; break; default: LOGERROR("Unknown message type %d during region clear", reply.getMessageType()); err = GF_MSG; break; } if (err == GF_NOERR) { err = invokeCacheListenerForRegionEvent( aCallbackArgument, CacheEventFlags::NORMAL, AFTER_REGION_CLEAR); } throwExceptionIfError("Region::clear", err); } GfErrType ThinClientRegion::getNoThrow_remote( const std::shared_ptr<CacheableKey>& keyPtr, std::shared_ptr<Cacheable>& valPtr, const std::shared_ptr<Serializable>& aCallbackArgument, std::shared_ptr<VersionTag>& versionTag) { GfErrType err = GF_NOERR; /** @brief Create message and send to bridge server */ TcrMessageRequest request(new DataOutput(m_cacheImpl->createDataOutput()), this, keyPtr, aCallbackArgument, m_tcrdm.get()); TcrMessageReply reply(true, m_tcrdm.get()); err = m_tcrdm->sendSyncRequest(request, reply); if (err != GF_NOERR) return err; // put the object into local region switch (reply.getMessageType()) { case TcrMessage::RESPONSE: { valPtr = reply.getValue(); versionTag = reply.getVersionTag(); break; } case TcrMessage::EXCEPTION: { err = handleServerException("Region::get", reply.getException()); break; } case TcrMessage::REQUEST_DATA_ERROR: { // LOGERROR("A read error occurred on the endpoint %s", // m_tcrdm->getActiveEndpoint()->name().c_str()); err = GF_CACHESERVER_EXCEPTION; break; } default: { LOGERROR("Unknown message type %d while getting entry from region", reply.getMessageType()); err = GF_MSG; break; } } return err; } GfErrType ThinClientRegion::invalidateNoThrow_remote( const std::shared_ptr<CacheableKey>& keyPtr, const std::shared_ptr<Serializable>& aCallbackArgument, std::shared_ptr<VersionTag>& versionTag) { GfErrType err = GF_NOERR; TcrMessageInvalidate request(new DataOutput(m_cacheImpl->createDataOutput()), this, keyPtr, aCallbackArgument, m_tcrdm.get()); TcrMessageReply reply(true, m_tcrdm.get()); err = m_tcrdm->sendSyncRequest(request, reply); if (err != GF_NOERR) return err; // put the object into local region switch (reply.getMessageType()) { case TcrMessage::REPLY: { versionTag = reply.getVersionTag(); break; } case TcrMessage::EXCEPTION: { err = handleServerException("Region::get", reply.getException()); break; } case TcrMessage::INVALIDATE_ERROR: { err = GF_CACHESERVER_EXCEPTION; break; } default: { LOGERROR("Unknown message type %d while getting entry from region", reply.getMessageType()); err = GF_MSG; break; } } return err; } GfErrType ThinClientRegion::putNoThrow_remote( const std::shared_ptr<CacheableKey>& keyPtr, const std::shared_ptr<Cacheable>& valuePtr, const std::shared_ptr<Serializable>& aCallbackArgument, std::shared_ptr<VersionTag>& versionTag, bool checkDelta) { GfErrType err = GF_NOERR; // do TCR put // bool delta = valuePtr->hasDelta(); bool delta = false; auto&& conFlationValue = getCacheImpl() ->getDistributedSystem() .getSystemProperties() .conflateEvents(); if (checkDelta && valuePtr && conFlationValue != "true" && ThinClientBaseDM::isDeltaEnabledOnServer()) { auto&& temp = std::dynamic_pointer_cast<Delta>(valuePtr); delta = temp && temp->hasDelta(); } TcrMessagePut request(new DataOutput(m_cacheImpl->createDataOutput()), this, keyPtr, valuePtr, aCallbackArgument, delta, m_tcrdm.get()); auto reply = std::unique_ptr<TcrMessageReply>( new TcrMessageReply(true, m_tcrdm.get())); err = m_tcrdm->sendSyncRequest(request, *reply); if (delta) { // Does not check whether success of failure.. m_cacheImpl->getCachePerfStats().incDeltaPut(); if (reply->getMessageType() == TcrMessage::PUT_DELTA_ERROR) { // Try without delta TcrMessagePut putRequest(new DataOutput(m_cacheImpl->createDataOutput()), this, keyPtr, valuePtr, aCallbackArgument, false, m_tcrdm.get(), false, true); reply = std::unique_ptr<TcrMessageReply>( new TcrMessageReply(true, m_tcrdm.get())); err = m_tcrdm->sendSyncRequest(putRequest, *reply); } } if (err != GF_NOERR) return err; // put the object into local region switch (reply->getMessageType()) { case TcrMessage::REPLY: { versionTag = reply->getVersionTag(); break; } case TcrMessage::EXCEPTION: { err = handleServerException("Region::put", reply->getException()); break; } case TcrMessage::PUT_DATA_ERROR: { err = GF_CACHESERVER_EXCEPTION; break; } default: { LOGERROR("Unknown message type %d during region put reply", reply->getMessageType()); err = GF_MSG; } } return err; } GfErrType ThinClientRegion::createNoThrow_remote( const std::shared_ptr<CacheableKey>& keyPtr, const std::shared_ptr<Cacheable>& valuePtr, const std::shared_ptr<Serializable>& aCallbackArgument, std::shared_ptr<VersionTag>& versionTag) { return putNoThrow_remote(keyPtr, valuePtr, aCallbackArgument, versionTag, false); } GfErrType ThinClientRegion::destroyNoThrow_remote( const std::shared_ptr<CacheableKey>& keyPtr, const std::shared_ptr<Serializable>& aCallbackArgument, std::shared_ptr<VersionTag>& versionTag) { GfErrType err = GF_NOERR; // do TCR destroy TcrMessageDestroy request(new DataOutput(m_cacheImpl->createDataOutput()), this, keyPtr, nullptr, aCallbackArgument, m_tcrdm.get()); TcrMessageReply reply(true, m_tcrdm.get()); err = m_tcrdm->sendSyncRequest(request, reply); if (err != GF_NOERR) return err; switch (reply.getMessageType()) { case TcrMessage::REPLY: { if (reply.getEntryNotFound() == 1) { err = GF_CACHE_ENTRY_NOT_FOUND; } else { LOGDEBUG("Remote key [%s] is destroyed successfully in region %s", Utils::nullSafeToString(keyPtr).c_str(), m_fullPath.c_str()); } versionTag = reply.getVersionTag(); break; } case TcrMessage::EXCEPTION: { err = handleServerException("Region::destroy", reply.getException()); break; } case TcrMessage::DESTROY_DATA_ERROR: { err = GF_CACHE_ENTRY_DESTROYED_EXCEPTION; break; } default: { LOGERROR("Unknown message type %d while destroying region entry", reply.getMessageType()); err = GF_MSG; } } return err; } // destroyNoThrow_remote() GfErrType ThinClientRegion::removeNoThrow_remote( const std::shared_ptr<CacheableKey>& keyPtr, const std::shared_ptr<Cacheable>& cvalue, const std::shared_ptr<Serializable>& aCallbackArgument, std::shared_ptr<VersionTag>& versionTag) { GfErrType err = GF_NOERR; // do TCR remove TcrMessageDestroy request(new DataOutput(m_cacheImpl->createDataOutput()), this, keyPtr, cvalue, aCallbackArgument, m_tcrdm.get()); TcrMessageReply reply(true, m_tcrdm.get()); err = m_tcrdm->sendSyncRequest(request, reply); if (err != GF_NOERR) { return err; } switch (reply.getMessageType()) { case TcrMessage::REPLY: { if (reply.getEntryNotFound() == 1) { err = GF_ENOENT; } else { LOGDEBUG("Remote key [%s] is removed successfully in region %s", Utils::nullSafeToString(keyPtr).c_str(), m_fullPath.c_str()); } versionTag = reply.getVersionTag(); break; } case TcrMessage::EXCEPTION: { err = handleServerException("Region::remove", reply.getException()); break; } case TcrMessage::DESTROY_DATA_ERROR: { err = GF_CACHE_ENTRY_DESTROYED_EXCEPTION; break; } default: { LOGERROR("Unknown message type %d while removing region entry", reply.getMessageType()); err = GF_MSG; } } return err; } GfErrType ThinClientRegion::removeNoThrowEX_remote( const std::shared_ptr<CacheableKey>& keyPtr, const std::shared_ptr<Serializable>& aCallbackArgument, std::shared_ptr<VersionTag>& versionTag) { GfErrType err = GF_NOERR; // do TCR remove TcrMessageDestroy request(new DataOutput(m_cacheImpl->createDataOutput()), this, keyPtr, nullptr, aCallbackArgument, m_tcrdm.get()); TcrMessageReply reply(true, m_tcrdm.get()); err = m_tcrdm->sendSyncRequest(request, reply); if (err != GF_NOERR) { return err; } switch (reply.getMessageType()) { case TcrMessage::REPLY: { versionTag = reply.getVersionTag(); if (reply.getEntryNotFound() == 1) { err = GF_ENOENT; } else { LOGDEBUG("Remote key [%s] is removed successfully in region %s", Utils::nullSafeToString(keyPtr).c_str(), m_fullPath.c_str()); } break; } case TcrMessage::EXCEPTION: { err = handleServerException("Region::removeEx", reply.getException()); break; } case TcrMessage::DESTROY_DATA_ERROR: { err = GF_CACHE_ENTRY_DESTROYED_EXCEPTION; break; } default: { LOGERROR("Unknown message type %d while removing region entry", reply.getMessageType()); err = GF_MSG; } } return err; } GfErrType ThinClientRegion::getAllNoThrow_remote( const std::vector<std::shared_ptr<CacheableKey>>* keys, const std::shared_ptr<HashMapOfCacheable>& values, const std::shared_ptr<HashMapOfException>& exceptions, const std::shared_ptr<std::vector<std::shared_ptr<CacheableKey>>>& resultKeys, bool addToLocalCache, const std::shared_ptr<Serializable>& aCallbackArgument) { GfErrType err = GF_NOERR; MapOfUpdateCounters updateCountMap; int32_t destroyTracker = 0; addToLocalCache = addToLocalCache && m_regionAttributes.getCachingEnabled(); if (addToLocalCache && !m_regionAttributes.getConcurrencyChecksEnabled()) { // start tracking the entries if (keys == nullptr) { // track all entries with destroy tracking for non-existent entries destroyTracker = m_entries->addTrackerForAllEntries(updateCountMap, true); } else { for (const auto& key : *keys) { std::shared_ptr<Cacheable> oldValue; int updateCount = m_entries->addTrackerForEntry(key, oldValue, true, false, false); updateCountMap.emplace(key, updateCount); } } } // create the GET_ALL request TcrMessageGetAll request(new DataOutput(m_cacheImpl->createDataOutput()), this, keys, m_tcrdm.get(), aCallbackArgument); TcrMessageReply reply(true, m_tcrdm.get()); std::recursive_mutex responseLock; // need to check TcrChunkedResult* resultCollector(new ChunkedGetAllResponse( reply, this, keys, values, exceptions, resultKeys, updateCountMap, destroyTracker, addToLocalCache, responseLock)); reply.setChunkedResultHandler(resultCollector); err = m_tcrdm->sendSyncRequest(request, reply); if (addToLocalCache && !m_regionAttributes.getConcurrencyChecksEnabled()) { // remove the tracking for remaining keys in case some keys do not have // values from server in GII for (MapOfUpdateCounters::const_iterator iter = updateCountMap.begin(); iter != updateCountMap.end(); ++iter) { if (iter->second >= 0) { m_entries->removeTrackerForEntry(iter->first); } } // remove tracking for destroys if (destroyTracker > 0) { m_entries->removeDestroyTracking(); } } delete resultCollector; if (err != GF_NOERR) { return err; } switch (reply.getMessageType()) { case TcrMessage::RESPONSE: { // nothing to be done; put in local region, if required, // is handled by ChunkedGetAllResponse break; } case TcrMessage::EXCEPTION: { err = handleServerException("Region:getAll", reply.getException()); break; } case TcrMessage::GET_ALL_DATA_ERROR: { LOGERROR("Region get-all: a read error occurred on the endpoint %s", m_tcrdm->getActiveEndpoint()->name().c_str()); err = GF_CACHESERVER_EXCEPTION; break; } default: { LOGERROR("Unknown message type %d during region get-all", reply.getMessageType()); err = GF_MSG; break; } } return err; } GfErrType ThinClientRegion::singleHopPutAllNoThrow_remote( ThinClientPoolDM* tcrdm, const HashMapOfCacheable& map, std::shared_ptr<VersionedCacheableObjectPartList>& versionedObjPartList, std::chrono::milliseconds timeout, const std::shared_ptr<Serializable>& aCallbackArgument) { LOGDEBUG(" ThinClientRegion::singleHopPutAllNoThrow_remote map size = %zu", map.size()); auto region = shared_from_this(); auto error = GF_NOERR; /*Step-1:: * populate the keys vector from the user Map and pass it to the * getServerToFilterMap to generate locationMap * If locationMap is nullptr try the old, existing putAll impl that may take * multiple n/w hops */ auto userKeys = std::vector<std::shared_ptr<CacheableKey>>(); for (const auto& iter : map) { userKeys.push_back(iter.first); } // last param in getServerToFilterMap() is false for putAll // LOGDEBUG("ThinClientRegion::singleHopPutAllNoThrow_remote keys.size() = %d // ", userKeys->size()); auto locationMap = tcrdm->getClientMetaDataService()->getServerToFilterMap( userKeys, region, true); if (!locationMap) { // putAll with multiple hop implementation LOGDEBUG("locationMap is Null or Empty"); return multiHopPutAllNoThrow_remote(map, versionedObjPartList, timeout, aCallbackArgument); } // set this flag that indicates putAll on PR is invoked with singlehop // enabled. m_isPRSingleHopEnabled = true; // LOGDEBUG("locationMap.size() = %d ", locationMap->size()); /*Step-2 * a. create vector of PutAllWork * b. locationMap<std::shared_ptr<BucketServerLocation>, * std::shared_ptr<std::vector<std::shared_ptr<CacheableKey>> >>. Create * server specific filteredMap/subMap by populating all keys * (locationIter.second()) and its corr. values from the user Map. * c. create new instance of PutAllWork, i.e worker with required params. * //TODO:: Add details of each parameter later * d. enqueue the worker for thread from threadPool to perform/run execute * method. * e. insert the worker into the vector. */ std::vector<std::shared_ptr<PutAllWork>> putAllWorkers; auto& threadPool = m_cacheImpl->getThreadPool(); int locationMapIndex = 0; for (const auto& locationIter : *locationMap) { const auto& serverLocation = locationIter.first; if (serverLocation == nullptr) { LOGDEBUG("serverLocation is nullptr"); } const auto& keys = locationIter.second; // Create server specific Sub-Map by iterating over keys. auto filteredMap = std::make_shared<HashMapOfCacheable>(); if (keys != nullptr && keys->size() > 0) { for (const auto& key : *keys) { const auto& iter = map.find(key); if (iter != map.end()) { filteredMap->emplace(iter->first, iter->second); } } } auto worker = std::make_shared<PutAllWork>( tcrdm, serverLocation, region, true /*attemptFailover*/, false /*isBGThread*/, filteredMap, keys, timeout, aCallbackArgument); threadPool.perform(worker); putAllWorkers.push_back(worker); locationMapIndex++; } // TODO::CHECK, do we need to set following ..?? // reply.setMessageType(TcrMessage::RESPONSE); int cnt = 1; /** * Step::3 * a. Iterate over all vector of putAllWorkers and populate worker specific * information into the HashMap * resultMap<std::shared_ptr<BucketServerLocation>, * std::shared_ptr<Serializable>>, 2nd part, Value can be a * std::shared_ptr<VersionedCacheableObjectPartList> or * std::shared_ptr<PutAllPartialResultServerException>. * failedServers<std::shared_ptr<BucketServerLocation>, * std::shared_ptr<CacheableInt32>>, 2nd part, Value is a ErrorCode. b. delete * the worker */ auto resultMap = ResultMap(); auto failedServers = FailedServersMap(); for (const auto& worker : putAllWorkers) { auto err = worker->getResult(); // wait() or blocking call for worker thread. LOGDEBUG("Error code :: %s:%d err = %d ", __FILE__, __LINE__, err); if (GF_NOERR == err) { // No Exception from server resultMap.emplace(worker->getServerLocation(), worker->getResultCollector()->getList()); } else { error = err; if (error == GF_PUTALL_PARTIAL_RESULT_EXCEPTION) { resultMap.emplace(worker->getServerLocation(), worker->getPaPResultException()); } else if (error == GF_NOTCON) { // Refresh the metadata in case of GF_NOTCON. tcrdm->getClientMetaDataService()->enqueueForMetadataRefresh( region->getFullPath(), 0); } failedServers.emplace(worker->getServerLocation(), CacheableInt32::create(error)); } LOGDEBUG("worker->getPutAllMap()->size() = %zu ", worker->getPutAllMap()->size()); LOGDEBUG( "worker->getResultCollector()->getList()->getVersionedTagsize() = %d ", worker->getResultCollector()->getList()->getVersionedTagsize()); // TODO::CHECK, why do we need following code... ?? // TcrMessage* currentReply = worker->getReply(); /* if(currentReply->getMessageType() != TcrMessage::REPLY) { reply.setMessageType(currentReply->getMessageType()); } */ cnt++; } /** * Step:4 * a. create instance of std::shared_ptr<PutAllPartialResult> with total size= * map.size() b. Iterate over the resultMap and value for the particular * serverlocation is of type VersionedCacheableObjectPartList add keys and * versions. C. ToDO:: what if the value in the resultMap is of type * PutAllPartialResultServerException */ std::recursive_mutex responseLock; auto result = std::make_shared<PutAllPartialResult>( static_cast<int>(map.size()), responseLock); LOGDEBUG( " TCRegion:: %s:%d " "result->getSucceededKeysAndVersions()->getVersionedTagsize() = %d ", __FILE__, __LINE__, result->getSucceededKeysAndVersions()->getVersionedTagsize()); LOGDEBUG(" TCRegion:: %s:%d resultMap->size() ", __FILE__, __LINE__, resultMap.size()); for (const auto& resultMapIter : resultMap) { const auto& value = resultMapIter.second; if (const auto papException = std::dynamic_pointer_cast<PutAllPartialResultServerException>( value)) { // PutAllPartialResultServerException CASE:: value in resultMap is of type // PutAllPartialResultServerException. // TODO:: Add failedservers.keySet= all fialed servers, i.e list out all // keys in map failedServers, // that is set view of the keys contained in failedservers map. // TODO:: need to read papException and populate PutAllPartialResult. result->consolidate(papException->getResult()); } else if (const auto list = std::dynamic_pointer_cast<VersionedCacheableObjectPartList>( value)) { // value in resultMap is of type VCOPL. result->addKeysAndVersions(list); } else { // ERROR CASE if (value) { LOGERROR( "ERROR:: ThinClientRegion::singleHopPutAllNoThrow_remote value " "could not Cast to either VCOPL or " "PutAllPartialResultServerException:%s", value->toString().c_str()); } else { LOGERROR( "ERROR:: ThinClientRegion::singleHopPutAllNoThrow_remote value is " "nullptr"); } } } /** * a. if PutAllPartialResult result does not contains any entry, Iterate over * locationMap. * b. Create std::vector<std::shared_ptr<CacheableKey>> succeedKeySet, and * keep adding set of keys (locationIter.second()) in locationMap for which * failedServers->contains(locationIter.first()is false. */ LOGDEBUG("ThinClientRegion:: %s:%d failedServers->size() = %zu", __FILE__, __LINE__, failedServers.size()); // if the partial result set doesn't already have keys (for tracking version // tags) // then we need to gather up the keys that we know have succeeded so far and // add them to the partial result set (See bug Id #955) if (!failedServers.empty()) { auto succeedKeySet = std::make_shared<std::vector<std::shared_ptr<CacheableKey>>>(); if (result->getSucceededKeysAndVersions()->size() == 0) { for (const auto& locationIter : *locationMap) { if (failedServers.find(locationIter.first) != failedServers.end()) { for (const auto& i : *(locationIter.second)) { succeedKeySet->push_back(i); } } } result->addKeys(succeedKeySet); } } /** * a. Iterate over the failedServers map * c. if failedServer map contains "GF_PUTALL_PARTIAL_RESULT_EXCEPTION" then * continue, Do not retry putAll for corr. keys. * b. Retry for all the failed server. * Generate a newSubMap by finding Keys specific to failedServers from * locationMap and finding their respective values from the usermap. */ error = GF_NOERR; bool oneSubMapRetryFailed = false; for (const auto& failedServerIter : failedServers) { if (failedServerIter.second->value() == GF_PUTALL_PARTIAL_RESULT_EXCEPTION) { // serverLocation // will not retry for PutAllPartialResultException // but it means at least one sub map ever failed oneSubMapRetryFailed = true; error = GF_PUTALL_PARTIAL_RESULT_EXCEPTION; continue; } std::shared_ptr<std::vector<std::shared_ptr<CacheableKey>>> failedKeys = nullptr; const auto& failedSerInLocMapIter = locationMap->find(failedServerIter.first); if (failedSerInLocMapIter != locationMap->end()) { failedKeys = failedSerInLocMapIter->second; } if (failedKeys == nullptr) { LOGERROR( "TCRegion::singleHopPutAllNoThrow_remote :: failedKeys are nullptr " "that is not valid"); } auto newSubMap = std::make_shared<HashMapOfCacheable>(); if (failedKeys && !failedKeys->empty()) { for (const auto& key : *failedKeys) { const auto& iter = map.find(key); if (iter != map.end()) { newSubMap->emplace(iter->first, iter->second); } else { LOGERROR( "DEBUG:: TCRegion.cpp singleHopPutAllNoThrow_remote KEY not " "found in user failedSubMap"); } } } std::shared_ptr<VersionedCacheableObjectPartList> vcopListPtr; GfErrType errCode = multiHopPutAllNoThrow_remote( *newSubMap, vcopListPtr, timeout, aCallbackArgument); if (errCode == GF_NOERR) { result->addKeysAndVersions(vcopListPtr); } else if (errCode == GF_PUTALL_PARTIAL_RESULT_EXCEPTION) { oneSubMapRetryFailed = true; // TODO:: Commented it as papResultServerExc is nullptr this time // UnComment it once you read papResultServerExc. // result->consolidate(papResultServerExc->getResult()); error = errCode; } else /*if(errCode != GF_NOERR)*/ { oneSubMapRetryFailed = true; const auto& firstKey = newSubMap->begin()->first; std::shared_ptr<Exception> excptPtr = nullptr; // TODO:: formulat excptPtr from the errCode result->saveFailedKey(firstKey, excptPtr); error = errCode; } } if (!oneSubMapRetryFailed) { error = GF_NOERR; } versionedObjPartList = result->getSucceededKeysAndVersions(); LOGDEBUG("singlehop versionedObjPartList = %d error=%d", versionedObjPartList->size(), error); return error; } GfErrType ThinClientRegion::multiHopPutAllNoThrow_remote( const HashMapOfCacheable& map, std::shared_ptr<VersionedCacheableObjectPartList>& versionedObjPartList, std::chrono::milliseconds timeout, const std::shared_ptr<Serializable>& aCallbackArgument) { // Multiple hop implementation LOGDEBUG("ThinClientRegion::multiHopPutAllNoThrow_remote "); auto err = GF_NOERR; // Construct request/reply for putAll TcrMessagePutAll request(new DataOutput(m_cacheImpl->createDataOutput()), this, map, timeout, m_tcrdm.get(), aCallbackArgument); TcrMessageReply reply(true, m_tcrdm.get()); request.setTimeout(timeout); reply.setTimeout(timeout); std::recursive_mutex responseLock; versionedObjPartList = std::make_shared<VersionedCacheableObjectPartList>(this, responseLock); // need to check ChunkedPutAllResponse* resultCollector(new ChunkedPutAllResponse( shared_from_this(), reply, responseLock, versionedObjPartList)); reply.setChunkedResultHandler(resultCollector); err = m_tcrdm->sendSyncRequest(request, reply); versionedObjPartList = resultCollector->getList(); LOGDEBUG("multiple hop versionedObjPartList size = %d , err = %d ", versionedObjPartList->size(), err); delete resultCollector; if (err != GF_NOERR) return err; LOGDEBUG( "ThinClientRegion::multiHopPutAllNoThrow_remote reply.getMessageType() = " "%d ", reply.getMessageType()); switch (reply.getMessageType()) { case TcrMessage::REPLY: // LOGDEBUG("Map is written into remote server at region %s", // m_fullPath.c_str()); break; case TcrMessage::RESPONSE: LOGDEBUG( "multiHopPutAllNoThrow_remote TcrMessage::RESPONSE %s, err = %d ", m_fullPath.c_str(), err); break; case TcrMessage::EXCEPTION: err = handleServerException("ThinClientRegion::putAllNoThrow", reply.getException()); // TODO:: Do we need to read PutAllPartialServerException for multiple // hop. break; case TcrMessage::PUT_DATA_ERROR: // LOGERROR( "A write error occurred on the endpoint %s", // m_tcrdm->getActiveEndpoint( )->name( ).c_str( ) ); err = GF_CACHESERVER_EXCEPTION; break; default: LOGERROR("Unknown message type %d during region put-all", reply.getMessageType()); err = GF_NOTOBJ; break; } return err; } GfErrType ThinClientRegion::putAllNoThrow_remote( const HashMapOfCacheable& map, std::shared_ptr<VersionedCacheableObjectPartList>& versionedObjPartList, std::chrono::milliseconds timeout, const std::shared_ptr<Serializable>& aCallbackArgument) { LOGDEBUG("ThinClientRegion::putAllNoThrow_remote"); if (auto poolDM = std::dynamic_pointer_cast<ThinClientPoolDM>(m_tcrdm)) { if (poolDM->getPRSingleHopEnabled() && poolDM->getClientMetaDataService() && !TSSTXStateWrapper::get().getTXState()) { return singleHopPutAllNoThrow_remote( poolDM.get(), map, versionedObjPartList, timeout, aCallbackArgument); } else { return multiHopPutAllNoThrow_remote(map, versionedObjPartList, timeout, aCallbackArgument); } } else { LOGERROR("ThinClientRegion::putAllNoThrow_remote :: Pool Not Specified "); return GF_NOTSUP; } } GfErrType ThinClientRegion::singleHopRemoveAllNoThrow_remote( ThinClientPoolDM* tcrdm, const std::vector<std::shared_ptr<CacheableKey>>& keys, std::shared_ptr<VersionedCacheableObjectPartList>& versionedObjPartList, const std::shared_ptr<Serializable>& aCallbackArgument) { LOGDEBUG( " ThinClientRegion::singleHopRemoveAllNoThrow_remote keys size = %zu", keys.size()); auto region = shared_from_this(); GfErrType error = GF_NOERR; auto locationMap = tcrdm->getClientMetaDataService()->getServerToFilterMap( keys, region, true); if (!locationMap) { // removeAll with multiple hop implementation LOGDEBUG("locationMap is Null or Empty"); return multiHopRemoveAllNoThrow_remote(keys, versionedObjPartList, aCallbackArgument); } // set this flag that indicates putAll on PR is invoked with singlehop // enabled. m_isPRSingleHopEnabled = true; LOGDEBUG("locationMap.size() = %zu ", locationMap->size()); /*Step-2 * a. create vector of RemoveAllWork * b. locationMap<std::shared_ptr<BucketServerLocation>, * std::shared_ptr<std::vector<std::shared_ptr<CacheableKey>> >>. Create * server specific filteredMap/subMap by populating all keys * (locationIter.second()) and its corr. values from the user Map. * c. create new instance of RemoveAllWork, i.e worker with required params. * //TODO:: Add details of each parameter later * d. enqueue the worker for thread from threadPool to perform/run execute * method. * e. insert the worker into the vector. */ std::vector<std::shared_ptr<RemoveAllWork>> removeAllWorkers; auto& threadPool = m_cacheImpl->getThreadPool(); int locationMapIndex = 0; for (const auto& locationIter : *locationMap) { const auto& serverLocation = locationIter.first; if (serverLocation == nullptr) { LOGDEBUG("serverLocation is nullptr"); } const auto& mappedkeys = locationIter.second; auto worker = std::make_shared<RemoveAllWork>( tcrdm, serverLocation, region, true /*attemptFailover*/, false /*isBGThread*/, mappedkeys, aCallbackArgument); threadPool.perform(worker); removeAllWorkers.push_back(worker); locationMapIndex++; } // TODO::CHECK, do we need to set following ..?? // reply.setMessageType(TcrMessage::RESPONSE); int cnt = 1; /** * Step::3 * a. Iterate over all vector of putAllWorkers and populate worker specific * information into the HashMap * resultMap<std::shared_ptr<BucketServerLocation>, * std::shared_ptr<Serializable>>, 2nd part, Value can be a * std::shared_ptr<VersionedCacheableObjectPartList> or * std::shared_ptr<PutAllPartialResultServerException>. * failedServers<std::shared_ptr<BucketServerLocation>, * std::shared_ptr<CacheableInt32>>, 2nd part, Value is a ErrorCode. b. delete * the worker */ auto resultMap = ResultMap(); auto failedServers = FailedServersMap(); for (const auto& worker : removeAllWorkers) { auto err = worker->getResult(); // wait() or blocking call for worker thread. LOGDEBUG("Error code :: %s:%d err = %d ", __FILE__, __LINE__, err); if (GF_NOERR == err) { // No Exception from server resultMap.emplace(worker->getServerLocation(), worker->getResultCollector()->getList()); } else { error = err; if (error == GF_PUTALL_PARTIAL_RESULT_EXCEPTION) { resultMap.emplace(worker->getServerLocation(), worker->getPaPResultException()); } else if (error == GF_NOTCON) { // Refresh the metadata in case of GF_NOTCON. tcrdm->getClientMetaDataService()->enqueueForMetadataRefresh( region->getFullPath(), 0); } failedServers.emplace(worker->getServerLocation(), CacheableInt32::create(error)); } LOGDEBUG( "worker->getResultCollector()->getList()->getVersionedTagsize() = %d ", worker->getResultCollector()->getList()->getVersionedTagsize()); cnt++; } /** * Step:4 * a. create instance of std::shared_ptr<PutAllPartialResult> with total size= * map.size() b. Iterate over the resultMap and value for the particular * serverlocation is of type VersionedCacheableObjectPartList add keys and * versions. C. ToDO:: what if the value in the resultMap is of type * PutAllPartialResultServerException */ std::recursive_mutex responseLock; auto result = std::make_shared<PutAllPartialResult>( static_cast<int>(keys.size()), responseLock); LOGDEBUG( " TCRegion:: %s:%d " "result->getSucceededKeysAndVersions()->getVersionedTagsize() = %d ", __FILE__, __LINE__, result->getSucceededKeysAndVersions()->getVersionedTagsize()); LOGDEBUG(" TCRegion:: %s:%d resultMap->size() ", __FILE__, __LINE__, resultMap.size()); for (const auto& resultMapIter : resultMap) { const auto& value = resultMapIter.second; if (const auto papException = std::dynamic_pointer_cast<PutAllPartialResultServerException>( value)) { // PutAllPartialResultServerException CASE:: value in resultMap is of type // PutAllPartialResultServerException. // TODO:: Add failedservers.keySet= all fialed servers, i.e list out all // keys in map failedServers, // that is set view of the keys contained in failedservers map. // TODO:: need to read papException and populate PutAllPartialResult. result->consolidate(papException->getResult()); } else if (const auto list = std::dynamic_pointer_cast<VersionedCacheableObjectPartList>( value)) { // value in resultMap is of type VCOPL. result->addKeysAndVersions(list); } else { // ERROR CASE if (value) { LOGERROR( "ERROR:: ThinClientRegion::singleHopRemoveAllNoThrow_remote value " "could not Cast to either VCOPL or " "PutAllPartialResultServerException:%s", value->toString().c_str()); } else { LOGERROR( "ERROR:: ThinClientRegion::singleHopRemoveAllNoThrow_remote value " "is nullptr"); } } } /** * a. if PutAllPartialResult result does not contains any entry, Iterate over * locationMap. * b. Create std::vector<std::shared_ptr<CacheableKey>> succeedKeySet, and * keep adding set of keys (locationIter.second()) in locationMap for which * failedServers->contains(locationIter.first()is false. */ LOGDEBUG("ThinClientRegion:: %s:%d failedServers->size() = %zu", __FILE__, __LINE__, failedServers.size()); // if the partial result set doesn't already have keys (for tracking version // tags) // then we need to gather up the keys that we know have succeeded so far and // add them to the partial result set (See bug Id #955) if (!failedServers.empty()) { auto succeedKeySet = std::make_shared<std::vector<std::shared_ptr<CacheableKey>>>(); if (result->getSucceededKeysAndVersions()->size() == 0) { for (const auto& locationIter : *locationMap) { if (failedServers.find(locationIter.first) != failedServers.end()) { for (const auto& i : *(locationIter.second)) { succeedKeySet->push_back(i); } } } result->addKeys(succeedKeySet); } } /** * a. Iterate over the failedServers map * c. if failedServer map contains "GF_PUTALL_PARTIAL_RESULT_EXCEPTION" then * continue, Do not retry putAll for corr. keys. * b. Retry for all the failed server. * Generate a newSubMap by finding Keys specific to failedServers from * locationMap and finding their respective values from the usermap. */ error = GF_NOERR; bool oneSubMapRetryFailed = false; for (const auto& failedServerIter : failedServers) { if (failedServerIter.second->value() == GF_PUTALL_PARTIAL_RESULT_EXCEPTION) { // serverLocation // will not retry for PutAllPartialResultException // but it means at least one sub map ever failed oneSubMapRetryFailed = true; error = GF_PUTALL_PARTIAL_RESULT_EXCEPTION; continue; } std::shared_ptr<std::vector<std::shared_ptr<CacheableKey>>> failedKeys = nullptr; const auto& failedSerInLocMapIter = locationMap->find(failedServerIter.first); if (failedSerInLocMapIter != locationMap->end()) { failedKeys = failedSerInLocMapIter->second; } if (failedKeys == nullptr) { LOGERROR( "TCRegion::singleHopRemoveAllNoThrow_remote :: failedKeys are " "nullptr " "that is not valid"); } std::shared_ptr<VersionedCacheableObjectPartList> vcopListPtr; std::shared_ptr<PutAllPartialResultServerException> papResultServerExc = nullptr; GfErrType errCode = multiHopRemoveAllNoThrow_remote( *failedKeys, vcopListPtr, aCallbackArgument); if (errCode == GF_NOERR) { result->addKeysAndVersions(vcopListPtr); } else if (errCode == GF_PUTALL_PARTIAL_RESULT_EXCEPTION) { oneSubMapRetryFailed = true; error = errCode; } else /*if(errCode != GF_NOERR)*/ { oneSubMapRetryFailed = true; std::shared_ptr<Exception> excptPtr = nullptr; result->saveFailedKey(failedKeys->at(0), excptPtr); error = errCode; } } if (!oneSubMapRetryFailed) { error = GF_NOERR; } versionedObjPartList = result->getSucceededKeysAndVersions(); LOGDEBUG("singlehop versionedObjPartList = %d error=%d", versionedObjPartList->size(), error); return error; } GfErrType ThinClientRegion::multiHopRemoveAllNoThrow_remote( const std::vector<std::shared_ptr<CacheableKey>>& keys, std::shared_ptr<VersionedCacheableObjectPartList>& versionedObjPartList, const std::shared_ptr<Serializable>& aCallbackArgument) { // Multiple hop implementation LOGDEBUG("ThinClientRegion::multiHopRemoveAllNoThrow_remote "); GfErrType err = GF_NOERR; // Construct request/reply for putAll TcrMessageRemoveAll request(new DataOutput(m_cacheImpl->createDataOutput()), this, keys, aCallbackArgument, m_tcrdm.get()); TcrMessageReply reply(true, m_tcrdm.get()); std::recursive_mutex responseLock; versionedObjPartList = std::make_shared<VersionedCacheableObjectPartList>(this, responseLock); // need to check ChunkedRemoveAllResponse* resultCollector(new ChunkedRemoveAllResponse( shared_from_this(), reply, versionedObjPartList)); reply.setChunkedResultHandler(resultCollector); err = m_tcrdm->sendSyncRequest(request, reply); versionedObjPartList = resultCollector->getList(); LOGDEBUG("multiple hop versionedObjPartList size = %d , err = %d ", versionedObjPartList->size(), err); delete resultCollector; if (err != GF_NOERR) return err; LOGDEBUG( "ThinClientRegion::multiHopRemoveAllNoThrow_remote " "reply.getMessageType() = %d ", reply.getMessageType()); switch (reply.getMessageType()) { case TcrMessage::REPLY: // LOGDEBUG("Map is written into remote server at region %s", // m_fullPath.c_str()); break; case TcrMessage::RESPONSE: LOGDEBUG( "multiHopRemoveAllNoThrow_remote TcrMessage::RESPONSE %s, err = %d ", m_fullPath.c_str(), err); break; case TcrMessage::EXCEPTION: err = handleServerException("ThinClientRegion::putAllNoThrow", reply.getException()); break; default: LOGERROR("Unknown message type %d during region remove-all", reply.getMessageType()); err = GF_NOTOBJ; break; } return err; } GfErrType ThinClientRegion::removeAllNoThrow_remote( const std::vector<std::shared_ptr<CacheableKey>>& keys, std::shared_ptr<VersionedCacheableObjectPartList>& versionedObjPartList, const std::shared_ptr<Serializable>& aCallbackArgument) { LOGDEBUG("ThinClientRegion::removeAllNoThrow_remote"); if (auto poolDM = std::dynamic_pointer_cast<ThinClientPoolDM>(m_tcrdm)) { if (poolDM->getPRSingleHopEnabled() && poolDM->getClientMetaDataService() && !TSSTXStateWrapper::get().getTXState()) { return singleHopRemoveAllNoThrow_remote( poolDM.get(), keys, versionedObjPartList, aCallbackArgument); } else { return multiHopRemoveAllNoThrow_remote(keys, versionedObjPartList, aCallbackArgument); } } else { LOGERROR( "ThinClientRegion::removeAllNoThrow_remote :: Pool Not Specified "); return GF_NOTSUP; } } uint32_t ThinClientRegion::size_remote() { LOGDEBUG("ThinClientRegion::size_remote"); GfErrType err = GF_NOERR; // do TCR size TcrMessageSize request(new DataOutput(m_cacheImpl->createDataOutput()), m_fullPath.c_str()); TcrMessageReply reply(true, m_tcrdm.get()); err = m_tcrdm->sendSyncRequest(request, reply); if (err != GF_NOERR) { throwExceptionIfError("Region::size", err); } switch (reply.getMessageType()) { case TcrMessage::RESPONSE: { auto size = std::dynamic_pointer_cast<CacheableInt32>(reply.getValue()); return size->value(); } case TcrMessage::EXCEPTION: err = handleServerException("ThinClientRegion::size", reply.getException()); break; case TcrMessage::SIZE_ERROR: err = GF_CACHESERVER_EXCEPTION; break; default: LOGERROR("Unknown message type %d during region size", reply.getMessageType()); err = GF_NOTOBJ; } throwExceptionIfError("Region::size", err); return 0; } GfErrType ThinClientRegion::registerStoredRegex( TcrEndpoint* endpoint, std::unordered_map<std::string, InterestResultPolicy>& interestListRegex, bool isDurable, bool receiveValues) { GfErrType opErr = GF_NOERR; GfErrType retVal = GF_NOERR; for (std::unordered_map<std::string, InterestResultPolicy>::iterator it = interestListRegex.begin(); it != interestListRegex.end(); ++it) { opErr = registerRegexNoThrow(it->first, false, endpoint, isDurable, nullptr, it->second, receiveValues); if (opErr != GF_NOERR) { retVal = opErr; } } return retVal; } GfErrType ThinClientRegion::registerKeys(TcrEndpoint* endpoint, const TcrMessage* request, TcrMessageReply* reply) { GfErrType err = GF_NOERR; GfErrType opErr = GF_NOERR; // called when failover to a different server opErr = registerStoredRegex(endpoint, m_interestListRegex); err = opErr != GF_NOERR ? opErr : err; opErr = registerStoredRegex( endpoint, m_interestListRegexForUpdatesAsInvalidates, false, false); err = opErr != GF_NOERR ? opErr : err; opErr = registerStoredRegex(endpoint, m_durableInterestListRegex, true); err = opErr != GF_NOERR ? opErr : err; opErr = registerStoredRegex( endpoint, m_durableInterestListRegexForUpdatesAsInvalidates, true, false); err = opErr != GF_NOERR ? opErr : err; std::vector<std::shared_ptr<CacheableKey>> keysVec; InterestResultPolicy interestPolicy = copyInterestList(keysVec, m_interestList); opErr = registerKeysNoThrow(keysVec, false, endpoint, false, interestPolicy); err = opErr != GF_NOERR ? opErr : err; std::vector<std::shared_ptr<CacheableKey>> keysVecForUpdatesAsInvalidates; interestPolicy = copyInterestList(keysVecForUpdatesAsInvalidates, m_interestListForUpdatesAsInvalidates); opErr = registerKeysNoThrow(keysVecForUpdatesAsInvalidates, false, endpoint, false, interestPolicy, false); err = opErr != GF_NOERR ? opErr : err; std::vector<std::shared_ptr<CacheableKey>> keysVecDurable; interestPolicy = copyInterestList(keysVecDurable, m_durableInterestList); opErr = registerKeysNoThrow(keysVecDurable, false, endpoint, true, interestPolicy); err = opErr != GF_NOERR ? opErr : err; std::vector<std::shared_ptr<CacheableKey>> keysVecDurableForUpdatesAsInvalidates; interestPolicy = copyInterestList(keysVecDurableForUpdatesAsInvalidates, m_durableInterestListForUpdatesAsInvalidates); opErr = registerKeysNoThrow(keysVecDurableForUpdatesAsInvalidates, false, endpoint, true, interestPolicy, false); err = opErr != GF_NOERR ? opErr : err; if (request != nullptr && request->getRegionName() == m_fullPath && (request->getMessageType() == TcrMessage::REGISTER_INTEREST || request->getMessageType() == TcrMessage::REGISTER_INTEREST_LIST)) { const std::vector<std::shared_ptr<CacheableKey>>* newKeysVec = request->getKeys(); bool isDurable = request->isDurable(); bool receiveValues = request->receiveValues(); if (newKeysVec == nullptr || newKeysVec->empty()) { const std::string& newRegex = request->getRegex(); if (!newRegex.empty()) { if (request->getRegionName() != m_fullPath) { reply = nullptr; } opErr = registerRegexNoThrow( newRegex, false, endpoint, isDurable, nullptr, request->getInterestResultPolicy(), receiveValues, reply); err = opErr != GF_NOERR ? opErr : err; } } else { opErr = registerKeysNoThrow(*newKeysVec, false, endpoint, isDurable, request->getInterestResultPolicy(), receiveValues, reply); err = opErr != GF_NOERR ? opErr : err; } } return err; } GfErrType ThinClientRegion::unregisterStoredRegex( std::unordered_map<std::string, InterestResultPolicy>& interestListRegex) { GfErrType opErr = GF_NOERR; GfErrType retVal = GF_NOERR; for (std::unordered_map<std::string, InterestResultPolicy>::iterator it = interestListRegex.begin(); it != interestListRegex.end(); ++it) { opErr = unregisterRegexNoThrow(it->first, false); if (opErr != GF_NOERR) { retVal = opErr; } } return retVal; } GfErrType ThinClientRegion::unregisterStoredRegexLocalDestroy( std::unordered_map<std::string, InterestResultPolicy>& interestListRegex) { GfErrType opErr = GF_NOERR; GfErrType retVal = GF_NOERR; for (std::unordered_map<std::string, InterestResultPolicy>::iterator it = interestListRegex.begin(); it != interestListRegex.end(); ++it) { opErr = unregisterRegexNoThrowLocalDestroy(it->first, false); if (opErr != GF_NOERR) { retVal = opErr; } } return retVal; } GfErrType ThinClientRegion::unregisterKeys() { GfErrType err = GF_NOERR; GfErrType opErr = GF_NOERR; // called when disconnect from a server opErr = unregisterStoredRegex(m_interestListRegex); err = opErr != GF_NOERR ? opErr : err; opErr = unregisterStoredRegex(m_durableInterestListRegex); err = opErr != GF_NOERR ? opErr : err; opErr = unregisterStoredRegex(m_interestListRegexForUpdatesAsInvalidates); err = opErr != GF_NOERR ? opErr : err; opErr = unregisterStoredRegex(m_durableInterestListRegexForUpdatesAsInvalidates); err = opErr != GF_NOERR ? opErr : err; std::vector<std::shared_ptr<CacheableKey>> keysVec; copyInterestList(keysVec, m_interestList); opErr = unregisterKeysNoThrow(keysVec, false); err = opErr != GF_NOERR ? opErr : err; std::vector<std::shared_ptr<CacheableKey>> keysVecDurable; copyInterestList(keysVecDurable, m_durableInterestList); opErr = unregisterKeysNoThrow(keysVecDurable, false); err = opErr != GF_NOERR ? opErr : err; std::vector<std::shared_ptr<CacheableKey>> keysVecForUpdatesAsInvalidates; copyInterestList(keysVecForUpdatesAsInvalidates, m_interestListForUpdatesAsInvalidates); opErr = unregisterKeysNoThrow(keysVecForUpdatesAsInvalidates, false); err = opErr != GF_NOERR ? opErr : err; std::vector<std::shared_ptr<CacheableKey>> keysVecDurableForUpdatesAsInvalidates; copyInterestList(keysVecDurableForUpdatesAsInvalidates, m_durableInterestListForUpdatesAsInvalidates); opErr = unregisterKeysNoThrow(keysVecDurableForUpdatesAsInvalidates, false); err = opErr != GF_NOERR ? opErr : err; return err; } GfErrType ThinClientRegion::destroyRegionNoThrow_remote( const std::shared_ptr<Serializable>& aCallbackArgument) { GfErrType err = GF_NOERR; // do TCR destroyRegion TcrMessageDestroyRegion request( new DataOutput(m_cacheImpl->createDataOutput()), this, aCallbackArgument, std::chrono::milliseconds(-1), m_tcrdm.get()); TcrMessageReply reply(true, m_tcrdm.get()); err = m_tcrdm->sendSyncRequest(request, reply); if (err != GF_NOERR) return err; switch (reply.getMessageType()) { case TcrMessage::REPLY: { // LOGINFO("Region %s at remote is destroyed successfully", // m_fullPath.c_str()); break; } case TcrMessage::EXCEPTION: { err = handleServerException("Region::destroyRegion", reply.getException()); break; } case TcrMessage::DESTROY_REGION_DATA_ERROR: { err = GF_CACHE_REGION_DESTROYED_EXCEPTION; break; } default: { LOGERROR("Unknown message type %d during destroy region", reply.getMessageType()); err = GF_MSG; } } return err; } GfErrType ThinClientRegion::registerKeysNoThrow( const std::vector<std::shared_ptr<CacheableKey>>& keys, bool attemptFailover, TcrEndpoint* endpoint, bool isDurable, InterestResultPolicy interestPolicy, bool receiveValues, TcrMessageReply* reply) { RegionGlobalLocks acquireLocksRedundancy(this, false); RegionGlobalLocks acquireLocksFailover(this); CHECK_DESTROY_PENDING_NOTHROW(TryReadGuard); GfErrType err = GF_NOERR; std::lock_guard<decltype(m_keysLock)> keysGuard(m_keysLock); if (keys.empty()) { return err; } TcrMessageReply replyLocal(true, m_tcrdm.get()); bool needToCreateRC = true; if (reply == nullptr) { reply = &replyLocal; } else { needToCreateRC = false; } LOGDEBUG("ThinClientRegion::registerKeysNoThrow : interestpolicy is %d", interestPolicy.ordinal); TcrMessageRegisterInterestList request( new DataOutput(m_cacheImpl->createDataOutput()), this, keys, isDurable, getAttributes().getCachingEnabled(), receiveValues, interestPolicy, m_tcrdm.get()); std::recursive_mutex responseLock; TcrChunkedResult* resultCollector = nullptr; if (interestPolicy.ordinal == InterestResultPolicy::KEYS_VALUES.ordinal) { auto values = std::make_shared<HashMapOfCacheable>(); auto exceptions = std::make_shared<HashMapOfException>(); MapOfUpdateCounters trackers; int32_t destroyTracker = 1; if (needToCreateRC) { resultCollector = (new ChunkedGetAllResponse( request, this, &keys, values, exceptions, nullptr, trackers, destroyTracker, true, responseLock)); reply->setChunkedResultHandler(resultCollector); } } else { if (needToCreateRC) { resultCollector = (new ChunkedInterestResponse(request, nullptr, *reply)); reply->setChunkedResultHandler(resultCollector); } } err = m_tcrdm->sendSyncRequestRegisterInterest( request, *reply, attemptFailover, this, endpoint); if (err == GF_NOERR /*|| err == GF_CACHE_REDUNDANCY_FAILURE*/) { if (reply->getMessageType() == TcrMessage::RESPONSE_FROM_SECONDARY && endpoint) { LOGFINER( "registerKeysNoThrow - got response from secondary for " "endpoint %s, ignoring.", endpoint->name().c_str()); } else if (attemptFailover) { addKeys(keys, isDurable, receiveValues, interestPolicy); if (!(interestPolicy.ordinal == InterestResultPolicy::KEYS_VALUES.ordinal)) { localInvalidateForRegisterInterest(keys); } } } if (needToCreateRC) { delete resultCollector; } return err; } GfErrType ThinClientRegion::unregisterKeysNoThrow( const std::vector<std::shared_ptr<CacheableKey>>& keys, bool attemptFailover) { RegionGlobalLocks acquireLocksRedundancy(this, false); RegionGlobalLocks acquireLocksFailover(this); CHECK_DESTROY_PENDING_NOTHROW(TryReadGuard); GfErrType err = GF_NOERR; std::lock_guard<decltype(m_keysLock)> keysGuard(m_keysLock); TcrMessageReply reply(true, m_tcrdm.get()); if (keys.empty()) { return err; } if (m_interestList.empty() && m_durableInterestList.empty() && m_interestListForUpdatesAsInvalidates.empty() && m_durableInterestListForUpdatesAsInvalidates.empty()) { // did not register any keys before. return GF_CACHE_ILLEGAL_STATE_EXCEPTION; } TcrMessageUnregisterInterestList request( new DataOutput(m_cacheImpl->createDataOutput()), this, keys, false, true, InterestResultPolicy::NONE, m_tcrdm.get()); err = m_tcrdm->sendSyncRequestRegisterInterest(request, reply); if (err == GF_NOERR /*|| err == GF_CACHE_REDUNDANCY_FAILURE*/) { if (attemptFailover) { for (const auto& key : keys) { m_interestList.erase(key); m_durableInterestList.erase(key); m_interestListForUpdatesAsInvalidates.erase(key); m_durableInterestListForUpdatesAsInvalidates.erase(key); } } } return err; } GfErrType ThinClientRegion::unregisterKeysNoThrowLocalDestroy( const std::vector<std::shared_ptr<CacheableKey>>& keys, bool attemptFailover) { RegionGlobalLocks acquireLocksRedundancy(this, false); RegionGlobalLocks acquireLocksFailover(this); GfErrType err = GF_NOERR; std::lock_guard<decltype(m_keysLock)> keysGuard(m_keysLock); TcrMessageReply reply(true, m_tcrdm.get()); if (keys.empty()) { return err; } if (m_interestList.empty() && m_durableInterestList.empty() && m_interestListForUpdatesAsInvalidates.empty() && m_durableInterestListForUpdatesAsInvalidates.empty()) { // did not register any keys before. return GF_CACHE_ILLEGAL_STATE_EXCEPTION; } TcrMessageUnregisterInterestList request( new DataOutput(m_cacheImpl->createDataOutput()), this, keys, false, true, InterestResultPolicy::NONE, m_tcrdm.get()); err = m_tcrdm->sendSyncRequestRegisterInterest(request, reply); if (err == GF_NOERR) { if (attemptFailover) { for (const auto& key : keys) { m_interestList.erase(key); m_durableInterestList.erase(key); m_interestListForUpdatesAsInvalidates.erase(key); m_durableInterestListForUpdatesAsInvalidates.erase(key); } } } return err; } bool ThinClientRegion::isRegexRegistered( std::unordered_map<std::string, InterestResultPolicy>& interestListRegex, const std::string& regex, bool allKeys) { if (interestListRegex.find(".*") != interestListRegex.end() || (!allKeys && interestListRegex.find(regex) != interestListRegex.end())) { return true; } return false; } GfErrType ThinClientRegion::registerRegexNoThrow( const std::string& regex, bool attemptFailover, TcrEndpoint* endpoint, bool isDurable, std::shared_ptr<std::vector<std::shared_ptr<CacheableKey>>> resultKeys, InterestResultPolicy interestPolicy, bool receiveValues, TcrMessageReply* reply) { RegionGlobalLocks acquireLocksRedundancy(this, false); RegionGlobalLocks acquireLocksFailover(this); CHECK_DESTROY_PENDING_NOTHROW(TryReadGuard); GfErrType err = GF_NOERR; bool allKeys = (regex == ".*"); std::lock_guard<decltype(m_keysLock)> keysGuard(m_keysLock); if (attemptFailover) { if ((isDurable && (isRegexRegistered(m_durableInterestListRegex, regex, allKeys) || isRegexRegistered(m_durableInterestListRegexForUpdatesAsInvalidates, regex, allKeys))) || (!isDurable && (isRegexRegistered(m_interestListRegex, regex, allKeys) || isRegexRegistered(m_interestListRegexForUpdatesAsInvalidates, regex, allKeys)))) { return err; } } ChunkedInterestResponse* resultCollector = nullptr; ChunkedGetAllResponse* getAllResultCollector = nullptr; if (reply != nullptr) { // need to check resultCollector = dynamic_cast<ChunkedInterestResponse*>( reply->getChunkedResultHandler()); if (resultCollector != nullptr) { resultKeys = resultCollector->getResultKeys(); } else { getAllResultCollector = dynamic_cast<ChunkedGetAllResponse*>( reply->getChunkedResultHandler()); resultKeys = getAllResultCollector->getResultKeys(); } } bool isRCCreatedLocally = false; LOGDEBUG("ThinClientRegion::registerRegexNoThrow : interestpolicy is %d", interestPolicy.ordinal); // TODO: TcrMessageRegisterInterest request( new DataOutput(m_cacheImpl->createDataOutput()), m_fullPath, regex.c_str(), interestPolicy, isDurable, getAttributes().getCachingEnabled(), receiveValues, m_tcrdm.get()); std::recursive_mutex responseLock; if (reply == nullptr) { TcrMessageReply replyLocal(true, m_tcrdm.get()); auto values = std::make_shared<HashMapOfCacheable>(); auto exceptions = std::make_shared<HashMapOfException>(); reply = &replyLocal; if (interestPolicy.ordinal == InterestResultPolicy::KEYS_VALUES.ordinal) { MapOfUpdateCounters trackers; int32_t destroyTracker = 1; if (resultKeys == nullptr) { resultKeys = std::shared_ptr<std::vector<std::shared_ptr<CacheableKey>>>( new std::vector<std::shared_ptr<CacheableKey>>()); } // need to check getAllResultCollector = (new ChunkedGetAllResponse( request, this, nullptr, values, exceptions, resultKeys, trackers, destroyTracker, true, responseLock)); reply->setChunkedResultHandler(getAllResultCollector); isRCCreatedLocally = true; } else { isRCCreatedLocally = true; // need to check resultCollector = new ChunkedInterestResponse(request, resultKeys, replyLocal); reply->setChunkedResultHandler(resultCollector); } err = m_tcrdm->sendSyncRequestRegisterInterest( request, replyLocal, attemptFailover, this, endpoint); } else { err = m_tcrdm->sendSyncRequestRegisterInterest( request, *reply, attemptFailover, this, endpoint); } if (err == GF_NOERR /*|| err == GF_CACHE_REDUNDANCY_FAILURE*/) { if (reply->getMessageType() == TcrMessage::RESPONSE_FROM_SECONDARY && endpoint) { LOGFINER( "registerRegexNoThrow - got response from secondary for " "endpoint %s, ignoring.", endpoint->name().c_str()); } else if (attemptFailover) { addRegex(regex, isDurable, receiveValues, interestPolicy); if (interestPolicy.ordinal != InterestResultPolicy::KEYS_VALUES.ordinal) { if (allKeys) { localInvalidateRegion_internal(); } else { const std::shared_ptr<std::vector<std::shared_ptr<CacheableKey>>>& keys = resultCollector != nullptr ? resultCollector->getResultKeys() : getAllResultCollector->getResultKeys(); if (keys != nullptr) { localInvalidateForRegisterInterest(*keys); } } } } } if (isRCCreatedLocally == true) { if (resultCollector != nullptr) delete resultCollector; if (getAllResultCollector != nullptr) delete getAllResultCollector; } return err; } GfErrType ThinClientRegion::unregisterRegexNoThrow(const std::string& regex, bool attemptFailover) { RegionGlobalLocks acquireLocksRedundancy(this, false); RegionGlobalLocks acquireLocksFailover(this); CHECK_DESTROY_PENDING_NOTHROW(TryReadGuard); GfErrType err = GF_NOERR; err = findRegex(regex); if (err == GF_NOERR) { TcrMessageReply reply(false, m_tcrdm.get()); TcrMessageUnregisterInterest request( new DataOutput(m_cacheImpl->createDataOutput()), m_fullPath, regex, InterestResultPolicy::NONE, false, true, m_tcrdm.get()); err = m_tcrdm->sendSyncRequestRegisterInterest(request, reply); if (err == GF_NOERR /*|| err == GF_CACHE_REDUNDANCY_FAILURE*/) { if (attemptFailover) { clearRegex(regex); } } } return err; } GfErrType ThinClientRegion::findRegex(const std::string& regex) { GfErrType err = GF_NOERR; std::lock_guard<decltype(m_keysLock)> keysGuard(m_keysLock); if (m_interestListRegex.find(regex) == m_interestListRegex.end() && m_durableInterestListRegex.find(regex) == m_durableInterestListRegex.end() && m_interestListRegexForUpdatesAsInvalidates.find(regex) == m_interestListRegexForUpdatesAsInvalidates.end() && m_durableInterestListRegexForUpdatesAsInvalidates.find(regex) == m_durableInterestListRegexForUpdatesAsInvalidates.end()) { return GF_CACHE_ILLEGAL_STATE_EXCEPTION; } else { return err; } } void ThinClientRegion::clearRegex(const std::string& regex) { std::lock_guard<decltype(m_keysLock)> keysGuard(m_keysLock); m_interestListRegex.erase(regex); m_durableInterestListRegex.erase(regex); m_interestListRegexForUpdatesAsInvalidates.erase(regex); m_durableInterestListRegexForUpdatesAsInvalidates.erase(regex); } GfErrType ThinClientRegion::unregisterRegexNoThrowLocalDestroy( const std::string& regex, bool attemptFailover) { GfErrType err = GF_NOERR; err = findRegex(regex); if (err == GF_NOERR) { TcrMessageReply reply(false, m_tcrdm.get()); TcrMessageUnregisterInterest request( new DataOutput(m_cacheImpl->createDataOutput()), m_fullPath, regex, InterestResultPolicy::NONE, false, true, m_tcrdm.get()); err = m_tcrdm->sendSyncRequestRegisterInterest(request, reply); if (err == GF_NOERR) { if (attemptFailover) { clearRegex(regex); } } } return err; } void ThinClientRegion::addKeys( const std::vector<std::shared_ptr<CacheableKey>>& keys, bool isDurable, bool receiveValues, InterestResultPolicy interestpolicy) { std::unordered_map<std::shared_ptr<CacheableKey>, InterestResultPolicy>& interestList = isDurable ? (receiveValues ? m_durableInterestList : m_durableInterestListForUpdatesAsInvalidates) : (receiveValues ? m_interestList : m_interestListForUpdatesAsInvalidates); for (const auto& key : keys) { interestList.insert( std::pair<std::shared_ptr<CacheableKey>, InterestResultPolicy>( key, interestpolicy)); } } void ThinClientRegion::addRegex(const std::string& regex, bool isDurable, bool receiveValues, InterestResultPolicy interestpolicy) { std::unordered_map<std::shared_ptr<CacheableKey>, InterestResultPolicy>& interestList = isDurable ? (receiveValues ? m_durableInterestList : m_durableInterestListForUpdatesAsInvalidates) : (receiveValues ? m_interestList : m_interestListForUpdatesAsInvalidates); std::unordered_map<std::string, InterestResultPolicy>& interestListRegex = isDurable ? (receiveValues ? m_durableInterestListRegex : m_durableInterestListRegexForUpdatesAsInvalidates) : (receiveValues ? m_interestListRegex : m_interestListRegexForUpdatesAsInvalidates); if (regex == ".*") { interestListRegex.clear(); interestList.clear(); } interestListRegex.insert( std::pair<std::string, InterestResultPolicy>(regex, interestpolicy)); } std::vector<std::shared_ptr<CacheableKey>> ThinClientRegion::getInterestList() const { auto nthis = const_cast<ThinClientRegion*>(this); RegionGlobalLocks acquireLocksRedundancy(nthis, false); RegionGlobalLocks acquireLocksFailover(nthis); CHECK_DESTROY_PENDING(TryReadGuard, getInterestList); std::lock_guard<decltype(m_keysLock)> keysGuard(nthis->m_keysLock); std::vector<std::shared_ptr<CacheableKey>> vlist; std::transform(std::begin(m_durableInterestList), std::end(m_durableInterestList), std::back_inserter(vlist), [](const decltype(m_durableInterestList)::value_type& e) { return e.first; }); std::transform( std::begin(m_interestList), std::end(m_interestList), std::back_inserter(vlist), [](const decltype(m_interestList)::value_type& e) { return e.first; }); return vlist; } std::vector<std::shared_ptr<CacheableString>> ThinClientRegion::getInterestListRegex() const { auto nthis = const_cast<ThinClientRegion*>(this); RegionGlobalLocks acquireLocksRedundancy(nthis, false); RegionGlobalLocks acquireLocksFailover(nthis); CHECK_DESTROY_PENDING(TryReadGuard, getInterestListRegex); std::lock_guard<decltype(m_keysLock)> keysGuard(nthis->m_keysLock); std::vector<std::shared_ptr<CacheableString>> vlist; std::transform(std::begin(m_durableInterestListRegex), std::end(m_durableInterestListRegex), std::back_inserter(vlist), [](const decltype(m_durableInterestListRegex)::value_type& e) { return CacheableString::create(e.first.c_str()); }); std::transform(std::begin(m_interestListRegex), std::end(m_interestListRegex), std::back_inserter(vlist), [](const decltype(m_interestListRegex)::value_type& e) { return CacheableString::create(e.first.c_str()); }); return vlist; } GfErrType ThinClientRegion::clientNotificationHandler(TcrMessage& msg) { GfErrType err = GF_NOERR; std::shared_ptr<Cacheable> oldValue; switch (msg.getMessageType()) { case TcrMessage::LOCAL_INVALIDATE: { LocalRegion::invalidateNoThrow( msg.getKey(), msg.getCallbackArgument(), -1, CacheEventFlags::NOTIFICATION | CacheEventFlags::LOCAL, msg.getVersionTag()); break; } case TcrMessage::LOCAL_DESTROY: { err = LocalRegion::destroyNoThrow( msg.getKey(), msg.getCallbackArgument(), -1, CacheEventFlags::NOTIFICATION | CacheEventFlags::LOCAL, msg.getVersionTag()); break; } case TcrMessage::CLEAR_REGION: { LOGDEBUG("remote clear region event for reigon[%s]", msg.getRegionName().c_str()); err = localClearNoThrow( nullptr, CacheEventFlags::NOTIFICATION | CacheEventFlags::LOCAL); break; } case TcrMessage::LOCAL_DESTROY_REGION: { m_notifyRelease = true; err = LocalRegion::destroyRegionNoThrow( msg.getCallbackArgument(), true, CacheEventFlags::NOTIFICATION | CacheEventFlags::LOCAL); break; } case TcrMessage::LOCAL_CREATE: err = LocalRegion::putNoThrow( msg.getKey(), msg.getValue(), msg.getCallbackArgument(), oldValue, -1, CacheEventFlags::NOTIFICATION | CacheEventFlags::LOCAL, msg.getVersionTag()); break; case TcrMessage::LOCAL_UPDATE: { // for update set the NOTIFICATION_UPDATE to trigger the // afterUpdate event even if the key is not present in local cache err = LocalRegion::putNoThrow( msg.getKey(), msg.getValue(), msg.getCallbackArgument(), oldValue, -1, CacheEventFlags::NOTIFICATION | CacheEventFlags::NOTIFICATION_UPDATE | CacheEventFlags::LOCAL, msg.getVersionTag(), msg.getDelta(), msg.getEventId()); break; } case TcrMessage::TOMBSTONE_OPERATION: LocalRegion::tombstoneOperationNoThrow(msg.getTombstoneVersions(), msg.getTombstoneKeys()); break; default: { if (TcrMessage::getAllEPDisMess() == &msg) { setProcessedMarker(false); LocalRegion::invokeAfterAllEndPointDisconnected(); } else { LOGERROR( "Unknown message type %d in subscription event handler; possible " "serialization mismatch", msg.getMessageType()); err = GF_MSG; } break; } } // Update EventIdMap to mark event processed, Only for durable client. // In case of closing, don't send it as listener might not be invoked. if (!m_destroyPending && (m_isDurableClnt || msg.hasDelta()) && TcrMessage::getAllEPDisMess() != &msg) { m_tcrdm->checkDupAndAdd(msg.getEventId()); } return err; } GfErrType ThinClientRegion::handleServerException( const std::string& func, const std::string& exceptionMsg) { GfErrType error = GF_NOERR; setThreadLocalExceptionMessage(exceptionMsg); if (exceptionMsg.find("org.apache.geode.security.NotAuthorizedException") != std::string::npos) { error = GF_NOT_AUTHORIZED_EXCEPTION; } else if (exceptionMsg.find("org.apache.geode.cache.CacheWriterException") != std::string::npos) { error = GF_CACHE_WRITER_EXCEPTION; } else if (exceptionMsg.find( "org.apache.geode.security.AuthenticationFailedException") != std::string::npos) { error = GF_AUTHENTICATION_FAILED_EXCEPTION; } else if (exceptionMsg.find("org.apache.geode.internal.cache.execute." "InternalFunctionInvocationTargetException") != std::string::npos) { error = GF_FUNCTION_EXCEPTION; } else if (exceptionMsg.find( "org.apache.geode.cache.CommitConflictException") != std::string::npos) { error = GF_COMMIT_CONFLICT_EXCEPTION; } else if (exceptionMsg.find("org.apache.geode.cache." "TransactionDataNodeHasDepartedException") != std::string::npos) { error = GF_TRANSACTION_DATA_NODE_HAS_DEPARTED_EXCEPTION; } else if (exceptionMsg.find( "org.apache.geode.cache.TransactionDataRebalancedException") != std::string::npos) { error = GF_TRANSACTION_DATA_REBALANCED_EXCEPTION; } else if (exceptionMsg.find( "org.apache.geode.security.AuthenticationRequiredException") != std::string::npos) { error = GF_AUTHENTICATION_REQUIRED_EXCEPTION; } else if (exceptionMsg.find("org.apache.geode.cache.LowMemoryException") != std::string::npos) { error = GF_LOW_MEMORY_EXCEPTION; } else if (exceptionMsg.find("org.apache.geode.cache.query." "QueryExecutionLowMemoryException") != std::string::npos) { error = GF_QUERY_EXECUTION_LOW_MEMORY_EXCEPTION; } else { error = GF_CACHESERVER_EXCEPTION; } if (error != GF_AUTHENTICATION_REQUIRED_EXCEPTION) { LOGERROR(func + ": An exception (" + exceptionMsg + ") happened at remote server."); } else { LOGFINER(func + ": An exception (" + exceptionMsg + ") happened at remote server."); } return error; } void ThinClientRegion::receiveNotification(TcrMessage* msg) { std::unique_lock<std::mutex> lock(m_notificationMutex, std::defer_lock); { TryReadGuard guard(m_rwLock, m_destroyPending); if (m_destroyPending) { if (msg != TcrMessage::getAllEPDisMess()) { _GEODE_SAFE_DELETE(msg); } return; } lock.lock(); } if (msg->getMessageType() == TcrMessage::CLIENT_MARKER) { handleMarker(); } else { clientNotificationHandler(*msg); } lock.unlock(); if (TcrMessage::getAllEPDisMess() != msg) _GEODE_SAFE_DELETE(msg); } void ThinClientRegion::localInvalidateRegion_internal() { std::shared_ptr<MapEntryImpl> me; std::shared_ptr<Cacheable> oldValue; std::vector<std::shared_ptr<CacheableKey>> keysVec = keys_internal(); for (const auto& key : keysVec) { std::shared_ptr<VersionTag> versionTag; m_entries->invalidate(key, me, oldValue, versionTag); } } void ThinClientRegion::invalidateInterestList( std::unordered_map<std::shared_ptr<CacheableKey>, InterestResultPolicy>& interestList) { std::shared_ptr<MapEntryImpl> me; std::shared_ptr<Cacheable> oldValue; if (!m_regionAttributes.getCachingEnabled()) { return; } for (const auto& iter : interestList) { std::shared_ptr<VersionTag> versionTag; m_entries->invalidate(iter.first, me, oldValue, versionTag); } } void ThinClientRegion::localInvalidateFailover() { CHECK_DESTROY_PENDING(TryReadGuard, ThinClientRegion::localInvalidateFailover); // No need to invalidate from the "m_xxxForUpdatesAsInvalidates" lists? if (m_interestListRegex.empty() && m_durableInterestListRegex.empty()) { invalidateInterestList(m_interestList); invalidateInterestList(m_durableInterestList); } else { localInvalidateRegion_internal(); } } void ThinClientRegion::localInvalidateForRegisterInterest( const std::vector<std::shared_ptr<CacheableKey>>& keys) { CHECK_DESTROY_PENDING(TryReadGuard, ThinClientRegion::localInvalidateForRegisterInterest); if (!m_regionAttributes.getCachingEnabled()) { return; } std::shared_ptr<Cacheable> oldValue; std::shared_ptr<MapEntryImpl> me; for (const auto& key : keys) { std::shared_ptr<VersionTag> versionTag; m_entries->invalidate(key, me, oldValue, versionTag); updateAccessAndModifiedTimeForEntry(me, true); } } InterestResultPolicy ThinClientRegion::copyInterestList( std::vector<std::shared_ptr<CacheableKey>>& keysVector, std::unordered_map<std::shared_ptr<CacheableKey>, InterestResultPolicy>& interestList) const { InterestResultPolicy interestPolicy = InterestResultPolicy::NONE; for (std::unordered_map<std::shared_ptr<CacheableKey>, InterestResultPolicy>::const_iterator iter = interestList.begin(); iter != interestList.end(); ++iter) { keysVector.push_back(iter->first); interestPolicy = iter->second; } return interestPolicy; } void ThinClientRegion::destroyDM(bool keepEndpoints) { if (m_tcrdm != nullptr) { m_tcrdm->destroy(keepEndpoints); } } void ThinClientRegion::release(bool invokeCallbacks) { if (m_released) { return; } std::unique_lock<std::mutex> lock(m_notificationMutex, std::defer_lock); if (!m_notifyRelease) { lock.lock(); } // TODO suspect // NOLINTNEXTLINE(clang-analyzer-optin.cplusplus.VirtualCall) destroyDM(invokeCallbacks); m_interestList.clear(); m_interestListRegex.clear(); m_durableInterestList.clear(); m_durableInterestListRegex.clear(); m_interestListForUpdatesAsInvalidates.clear(); m_interestListRegexForUpdatesAsInvalidates.clear(); m_durableInterestListForUpdatesAsInvalidates.clear(); m_durableInterestListRegexForUpdatesAsInvalidates.clear(); LocalRegion::release(invokeCallbacks); } ThinClientRegion::~ThinClientRegion() noexcept { TryWriteGuard guard(m_rwLock, m_destroyPending); if (!m_destroyPending) { // TODO suspect // NOLINTNEXTLINE(clang-analyzer-optin.cplusplus.VirtualCall) release(false); } } void ThinClientRegion::acquireGlobals(bool isFailover) { if (isFailover) { m_tcrdm->acquireFailoverLock(); } } void ThinClientRegion::releaseGlobals(bool isFailover) { if (isFailover) { m_tcrdm->releaseFailoverLock(); } } void ThinClientRegion::executeFunction( const std::string& func, const std::shared_ptr<Cacheable>& args, std::shared_ptr<CacheableVector> routingObj, uint8_t getResult, std::shared_ptr<ResultCollector> rc, int32_t retryAttempts, std::chrono::milliseconds timeout) { int32_t attempt = 0; auto failedNodes = CacheableHashSet::create(); // if pools retry attempts are not set then retry once on all available // endpoints if (retryAttempts == -1) { retryAttempts = static_cast<int32_t>(m_tcrdm->getNumberOfEndPoints()); } bool reExecute = false; bool reExecuteForServ = false; do { TcrMessage* msg; if (reExecuteForServ) { msg = new TcrMessageExecuteRegionFunction( new DataOutput(m_cacheImpl->createDataOutput()), func, this, args, routingObj, getResult, failedNodes, timeout, m_tcrdm.get(), static_cast<int8_t>(1)); } else { msg = new TcrMessageExecuteRegionFunction( new DataOutput(m_cacheImpl->createDataOutput()), func, this, args, routingObj, getResult, failedNodes, timeout, m_tcrdm.get(), static_cast<int8_t>(0)); } TcrMessageReply reply(true, m_tcrdm.get()); // need to check ChunkedFunctionExecutionResponse* resultCollector( new ChunkedFunctionExecutionResponse(reply, (getResult & 2) == 2, rc)); reply.setChunkedResultHandler(resultCollector); reply.setTimeout(timeout); GfErrType err = GF_NOERR; err = m_tcrdm->sendSyncRequest(*msg, reply, !(getResult & 1)); resultCollector->reset(); delete msg; delete resultCollector; if (err == GF_NOERR && (reply.getMessageType() == TcrMessage::EXCEPTION || reply.getMessageType() == TcrMessage::EXECUTE_REGION_FUNCTION_ERROR)) { err = ThinClientRegion::handleServerException("Execute", reply.getException()); } if (ThinClientBaseDM::isFatalClientError(err)) { throwExceptionIfError("ExecuteOnRegion:", err); } else if (err != GF_NOERR) { if (err == GF_FUNCTION_EXCEPTION) { reExecute = true; rc->clearResults(); std::shared_ptr<CacheableHashSet> failedNodesIds(reply.getFailedNode()); failedNodes->clear(); if (failedNodesIds) { LOGDEBUG( "ThinClientRegion::executeFunction with GF_FUNCTION_EXCEPTION " "failedNodesIds size = %zu ", failedNodesIds->size()); failedNodes->insert(failedNodesIds->begin(), failedNodesIds->end()); } } else if (err == GF_NOTCON) { attempt++; LOGDEBUG( "ThinClientRegion::executeFunction with GF_NOTCON retry attempt = " "%d ", attempt); if (attempt > retryAttempts) { throwExceptionIfError("ExecuteOnRegion:", err); } reExecuteForServ = true; rc->clearResults(); failedNodes->clear(); } else if (err == GF_TIMEOUT) { LOGINFO("function timeout. Name: %s, timeout: %s, params: %" PRIu8 ", " "retryAttempts: %d ", func.c_str(), to_string(timeout).c_str(), getResult, retryAttempts); throwExceptionIfError("ExecuteOnRegion", GF_TIMEOUT); } else if (err == GF_CLIENT_WAIT_TIMEOUT || err == GF_CLIENT_WAIT_TIMEOUT_REFRESH_PRMETADATA) { LOGINFO( "function timeout, possibly bucket is not available. Name: %s, " "timeout: %s, params: %" PRIu8 ", retryAttempts: %d ", func.c_str(), to_string(timeout).c_str(), getResult, retryAttempts); throwExceptionIfError("ExecuteOnRegion", GF_CLIENT_WAIT_TIMEOUT); } else { LOGDEBUG("executeFunction err = %d ", err); throwExceptionIfError("ExecuteOnRegion:", err); } } else { reExecute = false; reExecuteForServ = false; } } while (reExecuteForServ); if (reExecute && (getResult & 1)) { reExecuteFunction(func, args, routingObj, getResult, rc, retryAttempts, failedNodes, timeout); } } std::shared_ptr<CacheableVector> ThinClientRegion::reExecuteFunction( const std::string& func, const std::shared_ptr<Cacheable>& args, std::shared_ptr<CacheableVector> routingObj, uint8_t getResult, std::shared_ptr<ResultCollector> rc, int32_t retryAttempts, std::shared_ptr<CacheableHashSet>& failedNodes, std::chrono::milliseconds timeout) { int32_t attempt = 0; bool reExecute = true; // if pools retry attempts are not set then retry once on all available // endpoints if (retryAttempts == -1) { retryAttempts = static_cast<int32_t>(m_tcrdm->getNumberOfEndPoints()); } do { reExecute = false; TcrMessageExecuteRegionFunction msg( new DataOutput(m_cacheImpl->createDataOutput()), func, this, args, routingObj, getResult, failedNodes, timeout, m_tcrdm.get(), static_cast<int8_t>(1)); TcrMessageReply reply(true, m_tcrdm.get()); // need to check ChunkedFunctionExecutionResponse* resultCollector( new ChunkedFunctionExecutionResponse(reply, (getResult & 2) == 2, rc)); reply.setChunkedResultHandler(resultCollector); reply.setTimeout(timeout); GfErrType err = GF_NOERR; err = m_tcrdm->sendSyncRequest(msg, reply, !(getResult & 1)); delete resultCollector; if (err == GF_NOERR && (reply.getMessageType() == TcrMessage::EXCEPTION || reply.getMessageType() == TcrMessage::EXECUTE_REGION_FUNCTION_ERROR)) { err = ThinClientRegion::handleServerException("Execute", reply.getException()); } if (ThinClientBaseDM::isFatalClientError(err)) { throwExceptionIfError("ExecuteOnRegion:", err); } else if (err != GF_NOERR) { if (err == GF_FUNCTION_EXCEPTION) { reExecute = true; rc->clearResults(); std::shared_ptr<CacheableHashSet> failedNodesIds(reply.getFailedNode()); failedNodes->clear(); if (failedNodesIds) { LOGDEBUG( "ThinClientRegion::reExecuteFunction with GF_FUNCTION_EXCEPTION " "failedNodesIds size = %zu ", failedNodesIds->size()); failedNodes->insert(failedNodesIds->begin(), failedNodesIds->end()); } } else if ((err == GF_NOTCON) || (err == GF_CLIENT_WAIT_TIMEOUT) || (err == GF_CLIENT_WAIT_TIMEOUT_REFRESH_PRMETADATA)) { attempt++; LOGDEBUG( "ThinClientRegion::reExecuteFunction with GF_NOTCON OR TIMEOUT " "retry attempt " "= %d ", attempt); if (attempt > retryAttempts) { throwExceptionIfError("ExecuteOnRegion:", err); } reExecute = true; rc->clearResults(); failedNodes->clear(); } else if (err == GF_TIMEOUT) { LOGINFO("function timeout"); throwExceptionIfError("ExecuteOnRegion", GF_CACHE_TIMEOUT_EXCEPTION); } else { LOGDEBUG("reExecuteFunction err = %d ", err); throwExceptionIfError("ExecuteOnRegion:", err); } } } while (reExecute); return nullptr; } bool ThinClientRegion::executeFunctionSH( const std::string& func, const std::shared_ptr<Cacheable>& args, uint8_t getResult, std::shared_ptr<ResultCollector> rc, const std::shared_ptr<ClientMetadataService::ServerToKeysMap>& locationMap, std::shared_ptr<CacheableHashSet>& failedNodes, std::chrono::milliseconds timeout, bool allBuckets) { bool reExecute = false; auto resultCollectorLock = std::make_shared<std::recursive_mutex>(); const auto& userAttr = UserAttributes::threadLocalUserAttributes; std::vector<std::shared_ptr<OnRegionFunctionExecution>> feWorkers; auto& threadPool = CacheRegionHelper::getCacheImpl(&getCache())->getThreadPool(); for (const auto& locationIter : *locationMap) { const auto& serverLocation = locationIter.first; const auto& routingObj = locationIter.second; auto worker = std::make_shared<OnRegionFunctionExecution>( func, this, args, routingObj, getResult, timeout, dynamic_cast<ThinClientPoolDM*>(m_tcrdm.get()), resultCollectorLock, rc, userAttr, false, serverLocation, allBuckets); threadPool.perform(worker); feWorkers.push_back(worker); } GfErrType abortError = GF_NOERR; for (auto worker : feWorkers) { auto err = worker->getResult(); auto currentReply = worker->getReply(); if (err == GF_NOERR && (currentReply->getMessageType() == TcrMessage::EXCEPTION || currentReply->getMessageType() == TcrMessage::EXECUTE_REGION_FUNCTION_ERROR)) { err = ThinClientRegion::handleServerException( "Execute", currentReply->getException()); } if (err != GF_NOERR) { if (err == GF_FUNCTION_EXCEPTION) { reExecute = true; if (auto poolDM = std::dynamic_pointer_cast<ThinClientPoolDM>(m_tcrdm)) { if (poolDM->getClientMetaDataService()) { poolDM->getClientMetaDataService()->enqueueForMetadataRefresh( this->getFullPath(), 0); } } worker->getResultCollector()->reset(); { std::lock_guard<decltype(*resultCollectorLock)> guard( *resultCollectorLock); rc->clearResults(); } std::shared_ptr<CacheableHashSet> failedNodeIds( currentReply->getFailedNode()); if (failedNodeIds) { LOGDEBUG( "ThinClientRegion::executeFunctionSH with GF_FUNCTION_EXCEPTION " "failedNodeIds size = %zu ", failedNodeIds->size()); failedNodes->insert(failedNodeIds->begin(), failedNodeIds->end()); } } else if ((err == GF_NOTCON) || (err == GF_CLIENT_WAIT_TIMEOUT) || (err == GF_CLIENT_WAIT_TIMEOUT_REFRESH_PRMETADATA)) { reExecute = true; LOGINFO( "ThinClientRegion::executeFunctionSH with GF_NOTCON or " "GF_CLIENT_WAIT_TIMEOUT "); if (auto poolDM = std::dynamic_pointer_cast<ThinClientPoolDM>(m_tcrdm)) { if (poolDM->getClientMetaDataService()) { poolDM->getClientMetaDataService()->enqueueForMetadataRefresh( this->getFullPath(), 0); } } worker->getResultCollector()->reset(); { std::lock_guard<decltype(*resultCollectorLock)> guard( *resultCollectorLock); rc->clearResults(); } } else { if (ThinClientBaseDM::isFatalClientError(err)) { LOGERROR("ThinClientRegion::executeFunctionSH: Fatal Exception"); } else { LOGWARN("ThinClientRegion::executeFunctionSH: Unexpected Exception"); } if (abortError == GF_NOERR) { abortError = err; } } } } if (abortError != GF_NOERR) { throwExceptionIfError("ExecuteOnRegion:", abortError); } return reExecute; } GfErrType ThinClientRegion::getFuncAttributes( const std::string& func, std::shared_ptr<std::vector<int8_t>>* attr) { GfErrType err = GF_NOERR; // do TCR GET_FUNCTION_ATTRIBUTES LOGDEBUG("Tcrmessage request GET_FUNCTION_ATTRIBUTES "); TcrMessageGetFunctionAttributes request( new DataOutput(m_cacheImpl->createDataOutput()), func, m_tcrdm.get()); TcrMessageReply reply(true, m_tcrdm.get()); err = m_tcrdm->sendSyncRequest(request, reply); if (err != GF_NOERR) { return err; } switch (reply.getMessageType()) { case TcrMessage::RESPONSE: { *attr = reply.getFunctionAttributes(); break; } case TcrMessage::EXCEPTION: { err = handleServerException("Region::GET_FUNCTION_ATTRIBUTES", reply.getException()); break; } case TcrMessage::REQUEST_DATA_ERROR: { LOGERROR("Error message from server: " + reply.getValue()->toString()); throw FunctionExecutionException(reply.getValue()->toString()); } default: { LOGERROR("Unknown message type %d while getting function attributes.", reply.getMessageType()); err = GF_MSG; break; } } return err; } GfErrType ThinClientRegion::getNoThrow_FullObject( std::shared_ptr<EventId> eventId, std::shared_ptr<Cacheable>& fullObject, std::shared_ptr<VersionTag>& versionTag) { TcrMessageRequestEventValue fullObjectMsg( new DataOutput(m_cacheImpl->createDataOutput()), eventId); TcrMessageReply reply(true, nullptr); GfErrType err = GF_NOTCON; err = m_tcrdm->sendSyncRequest(fullObjectMsg, reply, false, true); if (err == GF_NOERR) { fullObject = reply.getValue(); } versionTag = reply.getVersionTag(); return err; } void ThinClientRegion::txDestroy( const std::shared_ptr<CacheableKey>& key, const std::shared_ptr<Serializable>& aCallbackArgument, std::shared_ptr<VersionTag> versionTag) { GfErrType err = destroyNoThrowTX(key, aCallbackArgument, -1, CacheEventFlags::NORMAL, versionTag); throwExceptionIfError("Region::destroyTX", err); } void ThinClientRegion::txInvalidate( const std::shared_ptr<CacheableKey>& key, const std::shared_ptr<Serializable>& aCallbackArgument, std::shared_ptr<VersionTag> versionTag) { GfErrType err = invalidateNoThrowTX(key, aCallbackArgument, -1, CacheEventFlags::NORMAL, versionTag); throwExceptionIfError("Region::invalidateTX", err); } void ThinClientRegion::txPut( const std::shared_ptr<CacheableKey>& key, const std::shared_ptr<Cacheable>& value, const std::shared_ptr<Serializable>& aCallbackArgument, std::shared_ptr<VersionTag> versionTag) { std::shared_ptr<Cacheable> oldValue; int64_t sampleStartNanos = startStatOpTime(); GfErrType err = putNoThrowTX(key, value, aCallbackArgument, oldValue, -1, CacheEventFlags::NORMAL, versionTag); updateStatOpTime(m_regionStats->getStat(), m_regionStats->getPutTimeId(), sampleStartNanos); throwExceptionIfError("Region::putTX", err); } void ThinClientRegion::setProcessedMarker(bool) {} void ChunkedInterestResponse::reset() { if (m_resultKeys != nullptr && m_resultKeys->size() > 0) { m_resultKeys->clear(); } } void ChunkedInterestResponse::handleChunk(const uint8_t* chunk, int32_t chunkLen, uint8_t isLastChunkWithSecurity, const CacheImpl* cacheImpl) { auto input = cacheImpl->createDataInput(chunk, chunkLen, m_replyMsg.getPool()); uint32_t partLen; if (TcrMessageHelper::readChunkPartHeader( m_msg, input, DSCode::FixedIDDefault, static_cast<int32_t>(DSCode::CacheableArrayList), "ChunkedInterestResponse", partLen, isLastChunkWithSecurity) != TcrMessageHelper::ChunkObjectType::OBJECT) { // encountered an exception part, so return without reading more m_replyMsg.readSecureObjectPart(input, false, true, isLastChunkWithSecurity); return; } if (m_resultKeys == nullptr) { m_resultKeys = std::make_shared<std::vector<std::shared_ptr<CacheableKey>>>(); } serializer::readObject(input, *m_resultKeys); m_replyMsg.readSecureObjectPart(input, false, true, isLastChunkWithSecurity); } void ChunkedKeySetResponse::reset() { if (m_resultKeys.size() > 0) { m_resultKeys.clear(); } } void ChunkedKeySetResponse::handleChunk(const uint8_t* chunk, int32_t chunkLen, uint8_t isLastChunkWithSecurity, const CacheImpl* cacheImpl) { auto input = cacheImpl->createDataInput(chunk, chunkLen, m_replyMsg.getPool()); uint32_t partLen; if (TcrMessageHelper::readChunkPartHeader( m_msg, input, DSCode::FixedIDDefault, static_cast<int32_t>(DSCode::CacheableArrayList), "ChunkedKeySetResponse", partLen, isLastChunkWithSecurity) != TcrMessageHelper::ChunkObjectType::OBJECT) { // encountered an exception part, so return without reading more m_replyMsg.readSecureObjectPart(input, false, true, isLastChunkWithSecurity); return; } serializer::readObject(input, m_resultKeys); m_replyMsg.readSecureObjectPart(input, false, true, isLastChunkWithSecurity); } void ChunkedQueryResponse::reset() { m_queryResults->clear(); m_structFieldNames.clear(); } void ChunkedQueryResponse::readObjectPartList(DataInput& input, bool isResultSet) { if (input.readBoolean()) { LOGERROR("Query response has keys which is unexpected."); throw IllegalStateException("Query response has keys which is unexpected."); } int32_t len = input.readInt32(); for (int32_t index = 0; index < len; ++index) { if (input.read() == 2 /* for exception*/) { input.advanceCursor(input.readArrayLength()); // skipLen auto exMsgPtr = input.readString(); throw IllegalStateException(exMsgPtr); } else { if (isResultSet) { std::shared_ptr<Cacheable> value; input.readObject(value); m_queryResults->push_back(value); } else { auto code = static_cast<DSCode>(input.read()); if (code == DSCode::FixedIDByte) { auto arrayType = static_cast<DSFid>(input.read()); if (arrayType != DSFid::CacheableObjectPartList) { LOGERROR( "Query response got unhandled message format %d while " "expecting struct set object part list; possible serialization " "mismatch", arrayType); throw MessageException( "Query response got unhandled message format while expecting " "struct set object part list; possible serialization mismatch"); } readObjectPartList(input, true); } else { LOGERROR( "Query response got unhandled message format %" PRId8 "while expecting " "struct set object part list; possible serialization mismatch", code); throw MessageException( "Query response got unhandled message format while expecting " "struct set object part list; possible serialization mismatch"); } } } } } void ChunkedQueryResponse::handleChunk(const uint8_t* chunk, int32_t chunkLen, uint8_t isLastChunkWithSecurity, const CacheImpl* cacheImpl) { LOGDEBUG("ChunkedQueryResponse::handleChunk.."); auto input = cacheImpl->createDataInput(chunk, chunkLen, m_msg.getPool()); uint32_t partLen; auto objType = TcrMessageHelper::readChunkPartHeader( m_msg, input, DSCode::FixedIDByte, static_cast<int32_t>(DSFid::CollectionTypeImpl), "ChunkedQueryResponse", partLen, isLastChunkWithSecurity); if (objType == TcrMessageHelper::ChunkObjectType::EXCEPTION) { // encountered an exception part, so return without reading more m_msg.readSecureObjectPart(input, false, true, isLastChunkWithSecurity); return; } else if (objType == TcrMessageHelper::ChunkObjectType::NULL_OBJECT) { // special case for scalar result input.readInt32(); // ignored part length input.read(); // ignored is object auto intVal = std::dynamic_pointer_cast<CacheableInt32>(input.readObject()); m_queryResults->push_back(intVal); m_msg.readSecureObjectPart(input, false, true, isLastChunkWithSecurity); return; } // ignoring parent classes for now // we will require to look at it once CQ is to be implemented. // skipping HashSet/StructSet // qhe: It was agreed upon that we'll use set for all kinds of results. // to avoid dealing with compare operator for user objets. // If the results on server are in a bag, or the user need to manipulate // the elements, then we have to revisit this issue. // For now, we'll live with duplicate records, hoping they do not cost much. skipClass(input); // skipping CollectionTypeImpl // skipClass(input); // no longer, since GFE 5.7 input.read(); // this is Fixed ID byte (1) input.read(); // this is DataSerializable (45) input.read(); // this is Class 43 const auto isStructTypeImpl = input.readString(); if (isStructTypeImpl == "org.apache.geode.cache.query.Struct") { int32_t numOfFldNames = input.readArrayLength(); bool skip = false; if (m_structFieldNames.size() != 0) { skip = true; } for (int i = 0; i < numOfFldNames; i++) { auto sptr = input.readString(); if (!skip) { m_structFieldNames.push_back(sptr); } } } // skip the remaining part input.reset(); // skip the whole part including partLen and isObj (4+1) input.advanceCursor(partLen + 5); input.readInt32(); // skip part length if (!input.read()) { LOGERROR( "Query response part is not an object; possible serialization " "mismatch"); throw MessageException( "Query response part is not an object; possible serialization " "mismatch"); } bool isResultSet = (m_structFieldNames.size() == 0); auto arrayType = static_cast<DSCode>(input.read()); if (arrayType == DSCode::CacheableObjectArray) { int32_t arraySize = input.readArrayLength(); skipClass(input); for (int32_t arrayItem = 0; arrayItem < arraySize; ++arrayItem) { std::shared_ptr<Serializable> value; if (isResultSet) { input.readObject(value); m_queryResults->push_back(value); } else { input.read(); int32_t arraySize2 = input.readArrayLength(); skipClass(input); for (int32_t index = 0; index < arraySize2; ++index) { input.readObject(value); m_queryResults->push_back(value); } } } } else if (arrayType == DSCode::FixedIDByte) { arrayType = static_cast<DSCode>(input.read()); if (static_cast<int32_t>(arrayType) != static_cast<int32_t>(DSFid::CacheableObjectPartList)) { LOGERROR( "Query response got unhandled message format %d while expecting " "object part list; possible serialization mismatch", arrayType); throw MessageException( "Query response got unhandled message format while expecting object " "part list; possible serialization mismatch"); } readObjectPartList(input, isResultSet); } else { LOGERROR( "Query response got unhandled message format %d; possible " "serialization mismatch", arrayType); throw MessageException( "Query response got unhandled message format; possible serialization " "mismatch"); } m_msg.readSecureObjectPart(input, false, true, isLastChunkWithSecurity); } void ChunkedQueryResponse::skipClass(DataInput& input) { auto classByte = static_cast<DSCode>(input.read()); if (classByte == DSCode::Class) { // ignore string type id - assuming its a normal (under 64k) string. input.read(); uint16_t classLen = input.readInt16(); input.advanceCursor(classLen); } else { throw IllegalStateException( "ChunkedQueryResponse::skipClass: " "Did not get expected class header byte"); } } void ChunkedFunctionExecutionResponse::reset() { // m_functionExecutionResults->clear(); } void ChunkedFunctionExecutionResponse::handleChunk( const uint8_t* chunk, int32_t chunkLen, uint8_t isLastChunkWithSecurity, const CacheImpl* cacheImpl) { LOGDEBUG("ChunkedFunctionExecutionResponse::handleChunk"); auto input = cacheImpl->createDataInput(chunk, chunkLen, m_msg.getPool()); uint32_t partLen; TcrMessageHelper::ChunkObjectType arrayType; if ((arrayType = TcrMessageHelper::readChunkPartHeader( m_msg, input, "ChunkedFunctionExecutionResponse", partLen, isLastChunkWithSecurity)) == TcrMessageHelper::ChunkObjectType::EXCEPTION) { // encountered an exception part, so return without reading more m_msg.readSecureObjectPart(input, false, true, isLastChunkWithSecurity); return; } if (m_getResult == false) { return; } if (static_cast<TcrMessageHelper::ChunkObjectType>(arrayType) == TcrMessageHelper::ChunkObjectType::NULL_OBJECT) { LOGDEBUG("ChunkedFunctionExecutionResponse::handleChunk nullptr object"); // m_functionExecutionResults->push_back(nullptr); m_msg.readSecureObjectPart(input, false, true, isLastChunkWithSecurity); return; } auto startLen = static_cast<size_t>( input.getBytesRead() - 1); // from here need to look value part + memberid AND -1 for array type // read and ignore array length input.readArrayLength(); // read a byte to determine whether to read exception part for sendException // or read objects. auto partType = static_cast<DSCode>(input.read()); bool isExceptionPart = false; // See If partType is JavaSerializable const int CHUNK_HDR_LEN = 5; const int SECURE_PART_LEN = 5 + 8; bool readPart = true; LOGDEBUG( "ChunkedFunctionExecutionResponse::handleChunk chunkLen = %d & partLen = " "%d ", chunkLen, partLen); if (partType == DSCode::JavaSerializable) { isExceptionPart = true; // reset the input. input.reset(); if (((isLastChunkWithSecurity & 0x02) && (chunkLen - static_cast<int32_t>(partLen) <= CHUNK_HDR_LEN + SECURE_PART_LEN)) || (((isLastChunkWithSecurity & 0x02) == 0) && (chunkLen - static_cast<int32_t>(partLen) <= CHUNK_HDR_LEN))) { readPart = false; partLen = input.readInt32(); input.advanceCursor(1); // skip isObject byte input.advanceCursor(partLen); } else { // skip first part i.e JavaSerializable. TcrMessageHelper::skipParts(m_msg, input, 1); // read the second part which is string in usual manner, first its length. partLen = input.readInt32(); // then isObject byte input.read(); // ignore iSobject startLen = input.getBytesRead(); // reset from here need to look value // part + memberid AND -1 for array type // Since it is contained as a part of other results, read arrayType which // is arrayList = 65. input.read(); // read and ignore its len which is 2 input.readArrayLength(); } } else { // rewind cursor by 1 to what we had read a byte to determine whether to // read exception part or read objects. input.rewindCursor(1); } // Read either object or exception string from sendException. std::shared_ptr<Serializable> value; // std::shared_ptr<Cacheable> memberId; if (readPart) { input.readObject(value); // TODO: track this memberId for PrFxHa // input.readObject(memberId); auto objectlen = input.getBytesRead() - startLen; auto memberIdLen = partLen - objectlen; input.advanceCursor(memberIdLen); LOGDEBUG("function partlen = %d , objectlen = %z, memberidlen = %z ", partLen, objectlen, memberIdLen); LOGDEBUG("function input.getBytesRemaining() = %z ", input.getBytesRemaining()); } else { value = CacheableString::create("Function exception result."); } if (m_rc != nullptr) { std::shared_ptr<Cacheable> result = nullptr; if (isExceptionPart) { result = std::make_shared<UserFunctionExecutionException>( std::dynamic_pointer_cast<CacheableString>(value)->value()); } else { result = value; } if (m_resultCollectorLock) { std::lock_guard<decltype(*m_resultCollectorLock)> guard( *m_resultCollectorLock); m_rc->addResult(result); } else { m_rc->addResult(result); } } m_msg.readSecureObjectPart(input, false, true, isLastChunkWithSecurity); // m_functionExecutionResults->push_back(value); } void ChunkedGetAllResponse::reset() { m_keysOffset = 0; if (m_resultKeys != nullptr && m_resultKeys->size() > 0) { m_resultKeys->clear(); } } // process a GET_ALL response chunk void ChunkedGetAllResponse::handleChunk(const uint8_t* chunk, int32_t chunkLen, uint8_t isLastChunkWithSecurity, const CacheImpl* cacheImpl) { auto input = cacheImpl->createDataInput(chunk, chunkLen, m_msg.getPool()); uint32_t partLen; if (TcrMessageHelper::readChunkPartHeader( m_msg, input, DSCode::FixedIDByte, static_cast<int32_t>(DSFid::VersionedObjectPartList), "ChunkedGetAllResponse", partLen, isLastChunkWithSecurity) != TcrMessageHelper::ChunkObjectType::OBJECT) { // encountered an exception part, so return without reading more m_msg.readSecureObjectPart(input, false, true, isLastChunkWithSecurity); return; } VersionedCacheableObjectPartList objectList( m_keys, &m_keysOffset, m_values, m_exceptions, m_resultKeys, m_region, &m_trackerMap, m_destroyTracker, m_addToLocalCache, m_dsmemId, m_responseLock); objectList.fromData(input); m_msg.readSecureObjectPart(input, false, true, isLastChunkWithSecurity); } void ChunkedGetAllResponse::add(const ChunkedGetAllResponse* other) { if (m_values) { for (const auto& iter : *m_values) { m_values->emplace(iter.first, iter.second); } } if (m_exceptions) { m_exceptions->insert(other->m_exceptions->begin(), other->m_exceptions->end()); } for (const auto& iter : other->m_trackerMap) { m_trackerMap[iter.first] = iter.second; } if (m_resultKeys) { m_resultKeys->insert(m_resultKeys->end(), other->m_resultKeys->begin(), other->m_resultKeys->end()); } } void ChunkedPutAllResponse::reset() { if (m_list != nullptr && m_list->size() > 0) { m_list->getVersionedTagptr().clear(); } } // process a PUT_ALL response chunk void ChunkedPutAllResponse::handleChunk(const uint8_t* chunk, int32_t chunkLen, uint8_t isLastChunkWithSecurity, const CacheImpl* cacheImpl) { auto input = cacheImpl->createDataInput(chunk, chunkLen, m_msg.getPool()); uint32_t partLen; TcrMessageHelper::ChunkObjectType chunkType; if ((chunkType = TcrMessageHelper::readChunkPartHeader( m_msg, input, DSCode::FixedIDByte, static_cast<int32_t>(DSFid::VersionedObjectPartList), "ChunkedPutAllResponse", partLen, isLastChunkWithSecurity)) == TcrMessageHelper::ChunkObjectType::NULL_OBJECT) { LOGDEBUG("ChunkedPutAllResponse::handleChunk nullptr object"); // No issues it will be empty in case of disabled caching. m_msg.readSecureObjectPart(input, false, true, isLastChunkWithSecurity); return; } if (chunkType == TcrMessageHelper::ChunkObjectType::OBJECT) { LOGDEBUG("ChunkedPutAllResponse::handleChunk object"); std::recursive_mutex responseLock; auto vcObjPart = std::make_shared<VersionedCacheableObjectPartList>( dynamic_cast<ThinClientRegion*>(m_region.get()), m_msg.getChunkedResultHandler()->getEndpointMemId(), responseLock); vcObjPart->fromData(input); m_list->addAll(vcObjPart); m_msg.readSecureObjectPart(input, false, true, isLastChunkWithSecurity); } else { LOGDEBUG("ChunkedPutAllResponse::handleChunk BYTES PART"); const auto byte0 = input.read(); LOGDEBUG("ChunkedPutAllResponse::handleChunk single-hop bytes byte0 = %d ", byte0); const auto byte1 = input.read(); m_msg.readSecureObjectPart(input, false, true, isLastChunkWithSecurity); auto pool = m_msg.getPool(); if (pool != nullptr && !pool->isDestroyed() && pool->getPRSingleHopEnabled()) { auto poolDM = dynamic_cast<ThinClientPoolDM*>(pool); if ((poolDM != nullptr) && (poolDM->getClientMetaDataService() != nullptr) && (byte0 != 0)) { LOGFINE("enqueued region " + m_region->getFullPath() + " for metadata refresh for singlehop for PUTALL operation."); poolDM->getClientMetaDataService()->enqueueForMetadataRefresh( m_region->getFullPath(), byte1); } } } } void ChunkedRemoveAllResponse::reset() { if (m_list != nullptr && m_list->size() > 0) { m_list->getVersionedTagptr().clear(); } } // process a REMOVE_ALL response chunk void ChunkedRemoveAllResponse::handleChunk(const uint8_t* chunk, int32_t chunkLen, uint8_t isLastChunkWithSecurity, const CacheImpl* cacheImpl) { auto input = cacheImpl->createDataInput(chunk, chunkLen, m_msg.getPool()); uint32_t partLen; TcrMessageHelper::ChunkObjectType chunkType; if ((chunkType = TcrMessageHelper::readChunkPartHeader( m_msg, input, DSCode::FixedIDByte, static_cast<int32_t>(DSFid::VersionedObjectPartList), "ChunkedRemoveAllResponse", partLen, isLastChunkWithSecurity)) == TcrMessageHelper::ChunkObjectType::NULL_OBJECT) { LOGDEBUG("ChunkedRemoveAllResponse::handleChunk nullptr object"); // No issues it will be empty in case of disabled caching. m_msg.readSecureObjectPart(input, false, true, isLastChunkWithSecurity); return; } if (chunkType == TcrMessageHelper::ChunkObjectType::OBJECT) { LOGDEBUG("ChunkedRemoveAllResponse::handleChunk object"); std::recursive_mutex responseLock; auto vcObjPart = std::make_shared<VersionedCacheableObjectPartList>( dynamic_cast<ThinClientRegion*>(m_region.get()), m_msg.getChunkedResultHandler()->getEndpointMemId(), responseLock); vcObjPart->fromData(input); m_list->addAll(vcObjPart); m_msg.readSecureObjectPart(input, false, true, isLastChunkWithSecurity); } else { LOGDEBUG("ChunkedRemoveAllResponse::handleChunk BYTES PART"); const auto byte0 = input.read(); LOGDEBUG( "ChunkedRemoveAllResponse::handleChunk single-hop bytes byte0 = %d ", byte0); const auto byte1 = input.read(); m_msg.readSecureObjectPart(input, false, true, isLastChunkWithSecurity); auto pool = m_msg.getPool(); if (pool != nullptr && !pool->isDestroyed() && pool->getPRSingleHopEnabled()) { auto poolDM = dynamic_cast<ThinClientPoolDM*>(pool); if ((poolDM != nullptr) && (poolDM->getClientMetaDataService() != nullptr) && (byte0 != 0)) { LOGFINE("enqueued region " + m_region->getFullPath() + " for metadata refresh for singlehop for REMOVEALL operation."); poolDM->getClientMetaDataService()->enqueueForMetadataRefresh( m_region->getFullPath(), byte1); } } } } void ChunkedDurableCQListResponse::reset() { if (m_resultList) { m_resultList->clear(); } } // handles the chunk response for GETDURABLECQS_MSG_TYPE void ChunkedDurableCQListResponse::handleChunk(const uint8_t* chunk, int32_t chunkLen, uint8_t, const CacheImpl* cacheImpl) { auto input = cacheImpl->createDataInput(chunk, chunkLen, m_msg.getPool()); // read and ignore part length input.readInt32(); if (!input.readBoolean()) { // we're currently always expecting an object char exMsg[256]; std::snprintf( exMsg, 255, "ChunkedDurableCQListResponse::handleChunk: part is not object"); throw MessageException(exMsg); } input.advanceCursor(1); // skip the CacheableArrayList type ID byte const auto stringParts = input.read(); // read the number of strings in the // message this is one byte for (int i = 0; i < stringParts; i++) { m_resultList->push_back( std::dynamic_pointer_cast<CacheableString>(input.readObject())); } } } // namespace client } // namespace geode } // namespace apache
36.607291
80
0.672225
[ "object", "vector", "transform" ]
4fab1235a0e8042018140aedfab2f5612207e9d0
17,967
cpp
C++
dbms/src/Processors/Formats/Impl/ParquetBlockOutputFormat.cpp
rodrigargar/ClickHouse
48a2b46499300d2ab2b8d1302e8ab45feb20fa57
[ "Apache-2.0" ]
3
2021-09-14T08:36:18.000Z
2022-02-24T02:55:38.000Z
dbms/src/Processors/Formats/Impl/ParquetBlockOutputFormat.cpp
rodrigargar/ClickHouse
48a2b46499300d2ab2b8d1302e8ab45feb20fa57
[ "Apache-2.0" ]
1
2020-04-04T04:25:47.000Z
2020-04-04T04:25:47.000Z
dbms/src/Processors/Formats/Impl/ParquetBlockOutputFormat.cpp
rodrigargar/ClickHouse
48a2b46499300d2ab2b8d1302e8ab45feb20fa57
[ "Apache-2.0" ]
1
2020-12-11T10:30:36.000Z
2020-12-11T10:30:36.000Z
#include "ParquetBlockOutputFormat.h" #if USE_PARQUET // TODO: clean includes #include <Columns/ColumnDecimal.h> #include <Columns/ColumnFixedString.h> #include <Columns/ColumnNullable.h> #include <Columns/ColumnString.h> #include <Columns/ColumnVector.h> #include <Columns/ColumnsNumber.h> #include <Common/assert_cast.h> #include <Core/ColumnWithTypeAndName.h> #include <Core/callOnTypeIndex.h> #include <DataTypes/DataTypeDateTime.h> #include <DataTypes/DataTypeNullable.h> #include <DataTypes/DataTypesDecimal.h> #include <DataStreams/SquashingBlockOutputStream.h> #include <Formats/FormatFactory.h> #include <IO/WriteHelpers.h> #include <arrow/api.h> #include <arrow/io/api.h> #include <arrow/util/decimal.h> #include <arrow/util/memory.h> #include <parquet/arrow/writer.h> #include <parquet/exception.h> #include <parquet/deprecated_io.h> namespace DB { namespace ErrorCodes { extern const int UNKNOWN_EXCEPTION; extern const int UNKNOWN_TYPE; } ParquetBlockOutputFormat::ParquetBlockOutputFormat(WriteBuffer & out_, const Block & header_, const FormatSettings & format_settings_) : IOutputFormat(header_, out_), format_settings{format_settings_} { } static void checkStatus(arrow::Status & status, const std::string & column_name) { if (!status.ok()) throw Exception{"Error with a parquet column \"" + column_name + "\": " + status.ToString(), ErrorCodes::UNKNOWN_EXCEPTION}; } template <typename NumericType, typename ArrowBuilderType> static void fillArrowArrayWithNumericColumnData( ColumnPtr write_column, std::shared_ptr<arrow::Array> & arrow_array, const PaddedPODArray<UInt8> * null_bytemap) { const PaddedPODArray<NumericType> & internal_data = assert_cast<const ColumnVector<NumericType> &>(*write_column).getData(); ArrowBuilderType builder; arrow::Status status; const UInt8 * arrow_null_bytemap_raw_ptr = nullptr; PaddedPODArray<UInt8> arrow_null_bytemap; if (null_bytemap) { /// Invert values since Arrow interprets 1 as a non-null value, while CH as a null arrow_null_bytemap.reserve(null_bytemap->size()); for (auto is_null : *null_bytemap) arrow_null_bytemap.emplace_back(!is_null); arrow_null_bytemap_raw_ptr = arrow_null_bytemap.data(); } if constexpr (std::is_same_v<NumericType, UInt8>) status = builder.AppendValues( reinterpret_cast<const uint8_t *>(internal_data.data()), internal_data.size(), reinterpret_cast<const uint8_t *>(arrow_null_bytemap_raw_ptr)); else status = builder.AppendValues(internal_data.data(), internal_data.size(), reinterpret_cast<const uint8_t *>(arrow_null_bytemap_raw_ptr)); checkStatus(status, write_column->getName()); status = builder.Finish(&arrow_array); checkStatus(status, write_column->getName()); } template <typename ColumnType> static void fillArrowArrayWithStringColumnData( ColumnPtr write_column, std::shared_ptr<arrow::Array> & arrow_array, const PaddedPODArray<UInt8> * null_bytemap) { const auto & internal_column = assert_cast<const ColumnType &>(*write_column); arrow::StringBuilder builder; arrow::Status status; for (size_t string_i = 0, size = internal_column.size(); string_i < size; ++string_i) { if (null_bytemap && (*null_bytemap)[string_i]) { status = builder.AppendNull(); } else { StringRef string_ref = internal_column.getDataAt(string_i); status = builder.Append(string_ref.data, string_ref.size); } checkStatus(status, write_column->getName()); } status = builder.Finish(&arrow_array); checkStatus(status, write_column->getName()); } static void fillArrowArrayWithDateColumnData( ColumnPtr write_column, std::shared_ptr<arrow::Array> & arrow_array, const PaddedPODArray<UInt8> * null_bytemap) { const PaddedPODArray<UInt16> & internal_data = assert_cast<const ColumnVector<UInt16> &>(*write_column).getData(); //arrow::Date32Builder date_builder; arrow::UInt16Builder builder; arrow::Status status; for (size_t value_i = 0, size = internal_data.size(); value_i < size; ++value_i) { if (null_bytemap && (*null_bytemap)[value_i]) status = builder.AppendNull(); else /// Implicitly converts UInt16 to Int32 status = builder.Append(internal_data[value_i]); checkStatus(status, write_column->getName()); } status = builder.Finish(&arrow_array); checkStatus(status, write_column->getName()); } static void fillArrowArrayWithDateTimeColumnData( ColumnPtr write_column, std::shared_ptr<arrow::Array> & arrow_array, const PaddedPODArray<UInt8> * null_bytemap) { auto & internal_data = assert_cast<const ColumnVector<UInt32> &>(*write_column).getData(); //arrow::Date64Builder builder; arrow::UInt32Builder builder; arrow::Status status; for (size_t value_i = 0, size = internal_data.size(); value_i < size; ++value_i) { if (null_bytemap && (*null_bytemap)[value_i]) status = builder.AppendNull(); else /// Implicitly converts UInt16 to Int32 //status = date_builder.Append(static_cast<int64_t>(internal_data[value_i]) * 1000); // now ms. TODO check other units status = builder.Append(internal_data[value_i]); checkStatus(status, write_column->getName()); } status = builder.Finish(&arrow_array); checkStatus(status, write_column->getName()); } template <typename DataType> static void fillArrowArrayWithDecimalColumnData( ColumnPtr write_column, std::shared_ptr<arrow::Array> & arrow_array, const PaddedPODArray<UInt8> * null_bytemap, const DataType * decimal_type) { const auto & column = static_cast<const typename DataType::ColumnType &>(*write_column); arrow::DecimalBuilder builder(arrow::decimal(decimal_type->getPrecision(), decimal_type->getScale())); arrow::Status status; for (size_t value_i = 0, size = column.size(); value_i < size; ++value_i) { if (null_bytemap && (*null_bytemap)[value_i]) status = builder.AppendNull(); else status = builder.Append( arrow::Decimal128(reinterpret_cast<const uint8_t *>(&column.getElement(value_i).value))); // TODO: try copy column checkStatus(status, write_column->getName()); } status = builder.Finish(&arrow_array); checkStatus(status, write_column->getName()); /* TODO column copy const auto & internal_data = static_cast<const typename DataType::ColumnType &>(*write_column).getData(); //ArrowBuilderType numeric_builder; arrow::DecimalBuilder builder(arrow::decimal(decimal_type->getPrecision(), decimal_type->getScale())); arrow::Status status; const uint8_t * arrow_null_bytemap_raw_ptr = nullptr; PaddedPODArray<UInt8> arrow_null_bytemap; if (null_bytemap) { /// Invert values since Arrow interprets 1 as a non-null value, while CH as a null arrow_null_bytemap.reserve(null_bytemap->size()); for (size_t i = 0, size = null_bytemap->size(); i < size; ++i) arrow_null_bytemap.emplace_back(1 ^ (*null_bytemap)[i]); arrow_null_bytemap_raw_ptr = arrow_null_bytemap.data(); } if constexpr (std::is_same_v<NumericType, UInt8>) status = builder.AppendValues( reinterpret_cast<const uint8_t *>(internal_data.data()), internal_data.size(), reinterpret_cast<const uint8_t *>(arrow_null_bytemap_raw_ptr)); else status = builder.AppendValues(internal_data.data(), internal_data.size(), reinterpret_cast<const uint8_t *>(arrow_null_bytemap_raw_ptr)); checkStatus(status, write_column->getName()); status = builder.Finish(&arrow_array); checkStatus(status, write_column->getName()); */ } #define FOR_INTERNAL_NUMERIC_TYPES(M) \ M(UInt8, arrow::UInt8Builder) \ M(Int8, arrow::Int8Builder) \ M(UInt16, arrow::UInt16Builder) \ M(Int16, arrow::Int16Builder) \ M(UInt32, arrow::UInt32Builder) \ M(Int32, arrow::Int32Builder) \ M(UInt64, arrow::UInt64Builder) \ M(Int64, arrow::Int64Builder) \ M(Float32, arrow::FloatBuilder) \ M(Float64, arrow::DoubleBuilder) const std::unordered_map<String, std::shared_ptr<arrow::DataType>> internal_type_to_arrow_type = { {"UInt8", arrow::uint8()}, {"Int8", arrow::int8()}, {"UInt16", arrow::uint16()}, {"Int16", arrow::int16()}, {"UInt32", arrow::uint32()}, {"Int32", arrow::int32()}, {"UInt64", arrow::uint64()}, {"Int64", arrow::int64()}, {"Float32", arrow::float32()}, {"Float64", arrow::float64()}, //{"Date", arrow::date64()}, //{"Date", arrow::date32()}, {"Date", arrow::uint16()}, // CHECK //{"DateTime", arrow::date64()}, // BUG! saves as date32 {"DateTime", arrow::uint32()}, // TODO: ClickHouse can actually store non-utf8 strings! {"String", arrow::utf8()}, {"FixedString", arrow::utf8()}, }; static const PaddedPODArray<UInt8> * extractNullBytemapPtr(ColumnPtr column) { ColumnPtr null_column = assert_cast<const ColumnNullable &>(*column).getNullMapColumnPtr(); const PaddedPODArray<UInt8> & null_bytemap = assert_cast<const ColumnVector<UInt8> &>(*null_column).getData(); return &null_bytemap; } class OstreamOutputStream : public arrow::io::OutputStream { public: explicit OstreamOutputStream(WriteBuffer & ostr_) : ostr(ostr_) { is_open = true; } ~OstreamOutputStream() override = default; // FileInterface ::arrow::Status Close() override { is_open = false; return ::arrow::Status::OK(); } ::arrow::Status Tell(int64_t* position) const override { *position = total_length; return ::arrow::Status::OK(); } bool closed() const override { return !is_open; } // Writable ::arrow::Status Write(const void* data, int64_t length) override { ostr.write(reinterpret_cast<const char *>(data), length); total_length += length; return ::arrow::Status::OK(); } private: WriteBuffer & ostr; int64_t total_length = 0; bool is_open = false; PARQUET_DISALLOW_COPY_AND_ASSIGN(OstreamOutputStream); }; void ParquetBlockOutputFormat::consume(Chunk chunk) { auto & header = getPort(PortKind::Main).getHeader(); const size_t columns_num = chunk.getNumColumns(); /// For arrow::Schema and arrow::Table creation std::vector<std::shared_ptr<arrow::Field>> arrow_fields; std::vector<std::shared_ptr<arrow::Array>> arrow_arrays; arrow_fields.reserve(columns_num); arrow_arrays.reserve(columns_num); for (size_t column_i = 0; column_i < columns_num; ++column_i) { // TODO: constructed every iteration ColumnWithTypeAndName column = header.safeGetByPosition(column_i); column.column = chunk.getColumns()[column_i]; const bool is_column_nullable = column.type->isNullable(); const auto & column_nested_type = is_column_nullable ? static_cast<const DataTypeNullable *>(column.type.get())->getNestedType() : column.type; const std::string column_nested_type_name = column_nested_type->getFamilyName(); if (isDecimal(column_nested_type)) { const auto add_decimal_field = [&](const auto & types) -> bool { using Types = std::decay_t<decltype(types)>; using ToDataType = typename Types::LeftType; if constexpr ( std::is_same_v< ToDataType, DataTypeDecimal< Decimal32>> || std::is_same_v<ToDataType, DataTypeDecimal<Decimal64>> || std::is_same_v<ToDataType, DataTypeDecimal<Decimal128>>) { const auto & decimal_type = static_cast<const ToDataType *>(column_nested_type.get()); arrow_fields.emplace_back(std::make_shared<arrow::Field>( column.name, arrow::decimal(decimal_type->getPrecision(), decimal_type->getScale()), is_column_nullable)); } return false; }; callOnIndexAndDataType<void>(column_nested_type->getTypeId(), add_decimal_field); } else { if (internal_type_to_arrow_type.find(column_nested_type_name) == internal_type_to_arrow_type.end()) { throw Exception{"The type \"" + column_nested_type_name + "\" of a column \"" + column.name + "\"" " is not supported for conversion into a Parquet data format", ErrorCodes::UNKNOWN_TYPE}; } arrow_fields.emplace_back(std::make_shared<arrow::Field>(column.name, internal_type_to_arrow_type.at(column_nested_type_name), is_column_nullable)); } std::shared_ptr<arrow::Array> arrow_array; ColumnPtr nested_column = is_column_nullable ? assert_cast<const ColumnNullable &>(*column.column).getNestedColumnPtr() : column.column; const PaddedPODArray<UInt8> * null_bytemap = is_column_nullable ? extractNullBytemapPtr(column.column) : nullptr; if ("String" == column_nested_type_name) { fillArrowArrayWithStringColumnData<ColumnString>(nested_column, arrow_array, null_bytemap); } else if ("FixedString" == column_nested_type_name) { fillArrowArrayWithStringColumnData<ColumnFixedString>(nested_column, arrow_array, null_bytemap); } else if ("Date" == column_nested_type_name) { fillArrowArrayWithDateColumnData(nested_column, arrow_array, null_bytemap); } else if ("DateTime" == column_nested_type_name) { fillArrowArrayWithDateTimeColumnData(nested_column, arrow_array, null_bytemap); } else if (isDecimal(column_nested_type)) { auto fill_decimal = [&](const auto & types) -> bool { using Types = std::decay_t<decltype(types)>; using ToDataType = typename Types::LeftType; if constexpr ( std::is_same_v< ToDataType, DataTypeDecimal< Decimal32>> || std::is_same_v<ToDataType, DataTypeDecimal<Decimal64>> || std::is_same_v<ToDataType, DataTypeDecimal<Decimal128>>) { const auto & decimal_type = static_cast<const ToDataType *>(column_nested_type.get()); fillArrowArrayWithDecimalColumnData(nested_column, arrow_array, null_bytemap, decimal_type); } return false; }; callOnIndexAndDataType<void>(column_nested_type->getTypeId(), fill_decimal); } #define DISPATCH(CPP_NUMERIC_TYPE, ARROW_BUILDER_TYPE) \ else if (#CPP_NUMERIC_TYPE == column_nested_type_name) \ { \ fillArrowArrayWithNumericColumnData<CPP_NUMERIC_TYPE, ARROW_BUILDER_TYPE>(nested_column, arrow_array, null_bytemap); \ } FOR_INTERNAL_NUMERIC_TYPES(DISPATCH) #undef DISPATCH else { throw Exception{"Internal type \"" + column_nested_type_name + "\" of a column \"" + column.name + "\"" " is not supported for conversion into a Parquet data format", ErrorCodes::UNKNOWN_TYPE}; } arrow_arrays.emplace_back(std::move(arrow_array)); } std::shared_ptr<arrow::Schema> arrow_schema = std::make_shared<arrow::Schema>(std::move(arrow_fields)); std::shared_ptr<arrow::Table> arrow_table = arrow::Table::Make(arrow_schema, arrow_arrays); auto sink = std::make_shared<OstreamOutputStream>(out); if (!file_writer) { parquet::WriterProperties::Builder builder; #if USE_SNAPPY builder.compression(parquet::Compression::SNAPPY); #endif auto props = builder.build(); auto status = parquet::arrow::FileWriter::Open( *arrow_table->schema(), arrow::default_memory_pool(), sink, props, /*parquet::default_writer_properties(),*/ &file_writer); if (!status.ok()) throw Exception{"Error while opening a table: " + status.ToString(), ErrorCodes::UNKNOWN_EXCEPTION}; } // TODO: calculate row_group_size depending on a number of rows and table size auto status = file_writer->WriteTable(*arrow_table, format_settings.parquet.row_group_size); if (!status.ok()) throw Exception{"Error while writing a table: " + status.ToString(), ErrorCodes::UNKNOWN_EXCEPTION}; } void ParquetBlockOutputFormat::finalize() { if (file_writer) { auto status = file_writer->Close(); if (!status.ok()) throw Exception{"Error while closing a table: " + status.ToString(), ErrorCodes::UNKNOWN_EXCEPTION}; } } void registerOutputFormatProcessorParquet(FormatFactory & factory) { factory.registerOutputFormatProcessor( "Parquet", [](WriteBuffer & buf, const Block & sample, FormatFactory::WriteCallback, const FormatSettings & format_settings) { auto impl = std::make_shared<ParquetBlockOutputFormat>(buf, sample, format_settings); /// TODO // auto res = std::make_shared<SquashingBlockOutputStream>(impl, impl->getHeader(), format_settings.parquet.row_group_size, 0); // res->disableFlush(); return impl; }); } } #else namespace DB { class FormatFactory; void registerOutputFormatProcessorParquet(FormatFactory &) { } } #endif
37.121901
160
0.655646
[ "vector" ]
4fad7c396f2717f345e999d69a52136568211b1a
9,123
cc
C++
third_party/blink/renderer/modules/webcodecs/image_decoder_fuzzer.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
76
2020-09-02T03:05:41.000Z
2022-03-30T04:40:55.000Z
third_party/blink/renderer/modules/webcodecs/image_decoder_fuzzer.cc
blueboxd/chromium-legacy
07223bc94bd97499909c9ed3c3f5769d718fe2e0
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
45
2020-09-02T03:21:37.000Z
2022-03-31T22:19:45.000Z
third_party/blink/renderer/modules/webcodecs/image_decoder_fuzzer.cc
Yannic/chromium
ab32e8aacb08c9fce0dc4bf09eec456ba46e3710
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2020-07-22T18:49:18.000Z
2022-02-08T10:27:16.000Z
// 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 "base/run_loop.h" #include "base/test/scoped_feature_list.h" #include "testing/libfuzzer/proto/lpm_interface.h" #include "third_party/blink/public/common/features.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h" #include "third_party/blink/renderer/bindings/core/v8/v8_union_arraybufferallowshared_arraybufferviewallowshared_readablestream.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_image_decode_options.h" #include "third_party/blink/renderer/bindings/modules/v8/v8_image_decoder_init.h" #include "third_party/blink/renderer/core/frame/local_frame.h" #include "third_party/blink/renderer/core/frame/settings.h" #include "third_party/blink/renderer/core/streams/readable_stream.h" #include "third_party/blink/renderer/core/streams/test_underlying_source.h" #include "third_party/blink/renderer/core/testing/dummy_page_holder.h" #include "third_party/blink/renderer/modules/webcodecs/fuzzer_inputs.pb.h" #include "third_party/blink/renderer/modules/webcodecs/fuzzer_utils.h" #include "third_party/blink/renderer/modules/webcodecs/image_decoder_external.h" #include "third_party/blink/renderer/modules/webcodecs/image_track.h" #include "third_party/blink/renderer/modules/webcodecs/image_track_list.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/bindings/script_state.h" #include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h" #include "third_party/blink/renderer/platform/heap/persistent.h" #include "third_party/blink/renderer/platform/testing/blink_fuzzer_test_support.h" #include "third_party/blink/renderer/platform/wtf/text/wtf_string.h" #include "third_party/blink/renderer/platform/wtf/vector.h" #include <string> namespace blink { namespace { String ToPremultiplyAlpha(wc_fuzzer::ImageBitmapOptions_PremultiplyAlpha type) { switch (type) { case wc_fuzzer::ImageBitmapOptions_PremultiplyAlpha_PREMULTIPLY_NONE: return "none"; case wc_fuzzer::ImageBitmapOptions_PremultiplyAlpha_PREMULTIPLY: return "premultiply"; case wc_fuzzer::ImageBitmapOptions_PremultiplyAlpha_PREMULTIPLY_DEFAULT: return "default"; } } String ToColorSpaceConversion( wc_fuzzer::ImageBitmapOptions_ColorSpaceConversion type) { switch (type) { case wc_fuzzer::ImageBitmapOptions_ColorSpaceConversion_CS_NONE: return "none"; case wc_fuzzer::ImageBitmapOptions_ColorSpaceConversion_CS_DEFAULT: return "default"; } } void RunFuzzingLoop(ImageDecoderExternal* image_decoder, const google::protobuf::RepeatedPtrField< wc_fuzzer::ImageDecoderApiInvocation>& invocations) { Persistent<ImageDecodeOptions> options = ImageDecodeOptions::Create(); for (auto& invocation : invocations) { switch (invocation.Api_case()) { case wc_fuzzer::ImageDecoderApiInvocation::kDecodeImage: options->setFrameIndex(invocation.decode_image().frame_index()); options->setCompleteFramesOnly( invocation.decode_image().complete_frames_only()); image_decoder->decode(options); break; case wc_fuzzer::ImageDecoderApiInvocation::kDecodeMetadata: // Deprecated. break; case wc_fuzzer::ImageDecoderApiInvocation::kSelectTrack: { auto* track = image_decoder->tracks().AnonymousIndexedGetter( invocation.select_track().track_id()); if (track) track->setSelected(invocation.select_track().selected()); break; } case wc_fuzzer::ImageDecoderApiInvocation::API_NOT_SET: break; } // Give other tasks a chance to run (e.g. calling our output callback). base::RunLoop().RunUntilIdle(); } } } // namespace DEFINE_BINARY_PROTO_FUZZER( const wc_fuzzer::ImageDecoderApiInvocationSequence& proto) { static BlinkFuzzerTestSupport test_support = BlinkFuzzerTestSupport(); static DummyPageHolder* page_holder = []() { auto page_holder = std::make_unique<DummyPageHolder>(); page_holder->GetFrame().GetSettings()->SetScriptEnabled(true); return page_holder.release(); }(); base::test::ScopedFeatureList scoped_feature_list; scoped_feature_list.InitAndEnableFeature(features::kJXL); // // NOTE: GC objects that need to survive iterations of the loop below // must be Persistent<>! // // GC may be triggered by the RunLoop().RunUntilIdle() below, which will GC // raw pointers on the stack. This is not required in production code because // GC typically runs at the top of the stack, or is conservative enough to // keep stack pointers alive. // // Scoping Persistent<> refs so GC can collect these at the end. { Persistent<ScriptState> script_state = ToScriptStateForMainWorld(&page_holder->GetFrame()); ScriptState::Scope scope(script_state); // Fuzz the isTypeSupported() API explicitly. ImageDecoderExternal::isTypeSupported(script_state, proto.config().type().c_str()); Persistent<ImageDecoderInit> image_decoder_init = MakeGarbageCollected<ImageDecoderInit>(); image_decoder_init->setType(proto.config().type().c_str()); Persistent<DOMArrayBuffer> data_copy = DOMArrayBuffer::Create( proto.config().data().data(), proto.config().data().size()); image_decoder_init->setData( MakeGarbageCollected<V8ImageBufferSource>(data_copy)); image_decoder_init->setPremultiplyAlpha( ToPremultiplyAlpha(proto.config().options().premultiply_alpha())); image_decoder_init->setColorSpaceConversion(ToColorSpaceConversion( proto.config().options().color_space_conversion())); // Limit resize support to a reasonable value to prevent fuzzer oom. constexpr uint32_t kMaxDimension = 4096u; image_decoder_init->setDesiredWidth( std::min(proto.config().options().resize_width(), kMaxDimension)); image_decoder_init->setDesiredHeight( std::min(proto.config().options().resize_height(), kMaxDimension)); image_decoder_init->setPreferAnimation(proto.config().prefer_animation()); Persistent<ImageDecoderExternal> image_decoder = ImageDecoderExternal::Create(script_state, image_decoder_init, IGNORE_EXCEPTION_FOR_TESTING); if (image_decoder) { // Promises will be fulfilled synchronously since we're using an array // buffer based source. RunFuzzingLoop(image_decoder, proto.invocations()); // Close out underlying decoder to simplify reproduction analysis. image_decoder->close(); image_decoder = nullptr; base::RunLoop().RunUntilIdle(); // Collect what we can after the first fuzzing loop; this keeps memory // pressure down during ReadableStream fuzzing. V8PerIsolateData::MainThreadIsolate()->RequestGarbageCollectionForTesting( v8::Isolate::kFullGarbageCollection); } Persistent<TestUnderlyingSource> underlying_source = MakeGarbageCollected<TestUnderlyingSource>(script_state); Persistent<ReadableStream> stream = ReadableStream::CreateWithCountQueueingStrategy(script_state, underlying_source, 0); image_decoder_init->setData( MakeGarbageCollected<V8ImageBufferSource>(stream)); image_decoder = ImageDecoderExternal::Create( script_state, image_decoder_init, IGNORE_EXCEPTION_FOR_TESTING); image_decoder_init = nullptr; if (image_decoder) { // Split the image data into chunks. constexpr size_t kNumChunks = 2; const size_t chunk_size = (data_copy->ByteLength() + 1) / kNumChunks; size_t offset = 0; for (size_t i = 0; i < kNumChunks; ++i) { RunFuzzingLoop(image_decoder, proto.invocations()); const size_t current_chunk_size = std::min(data_copy->ByteLength() - offset, chunk_size); underlying_source->Enqueue(ScriptValue( script_state->GetIsolate(), ToV8(DOMUint8Array::Create(data_copy, offset, current_chunk_size), script_state))); offset += chunk_size; } underlying_source->Close(); data_copy = nullptr; // Run one additional loop after all data has been appended. RunFuzzingLoop(image_decoder, proto.invocations()); } } // Request a V8 GC. Oilpan will be invoked by the GC epilogue. // // Multiple GCs may be required to ensure everything is collected (due to // a chain of persistent handles), so some objects may not be collected until // a subsequent iteration. This is slow enough as is, so we compromise on one // major GC, as opposed to the 5 used in V8GCController for unit tests. base::RunLoop().RunUntilIdle(); V8PerIsolateData::MainThreadIsolate()->RequestGarbageCollectionForTesting( v8::Isolate::kFullGarbageCollection); } } // namespace blink
43.033019
130
0.730461
[ "vector" ]
4fb0a1c7ec2725b8bb2d0ca0f8ae741dcea65756
32,562
cpp
C++
Alien Engine/Alien Engine/ModuleImporter.cpp
OverPowered-Team/Alien-GameEngine
713a8846a95fdf253d0869bdcad4ecd006b2e166
[ "MIT" ]
7
2020-02-20T15:11:11.000Z
2020-05-19T00:29:04.000Z
Alien Engine/Alien Engine/ModuleImporter.cpp
OverPowered-Team/Alien-GameEngine
713a8846a95fdf253d0869bdcad4ecd006b2e166
[ "MIT" ]
125
2020-02-29T17:17:31.000Z
2020-05-06T19:50:01.000Z
Alien Engine/Alien Engine/ModuleImporter.cpp
OverPowered-Team/Alien-GameEngine
713a8846a95fdf253d0869bdcad4ecd006b2e166
[ "MIT" ]
1
2020-05-19T00:29:06.000Z
2020-05-19T00:29:06.000Z
#include "ModuleImporter.h" #include "Application.h" #include "ModuleObjects.h" #include "Devil/include/il.h" #include "Devil/include/ilu.h" #include "Devil/include/ilut.h" #include "stb_image.h" #include "FreeImage/src/FreeImage.h" #pragma comment ( lib, "FreeImage/lib/FreeImage.lib ") #include "ModuleUI.h" #include "ComponentTransform.h" #include "ComponentMaterial.h" #include "ComponentParticleSystem.h" #include "GameObject.h" #include "ModuleCamera3D.h" #include "ModuleFileSystem.h" #include "ModuleResources.h" #include "ResourceMesh.h" #include "ResourceModel.h" #include "PanelProject.h" #include "ResourceTexture.h" #include "ResourceShader.h" #include "ResourceAnimation.h" #include "ResourceBone.h" #include "ResourceMaterial.h" #include "ResourceFont.h" #include "ReturnZ.h" #define _SILENCE_EXPERIMENTAL_FILESYSTEM_DEPRECATION_WARNING #include <experimental/filesystem> #include "mmgr/mmgr.h" #include "FreeType/include/freetype/freetype.h" #include "Optick/include/optick.h" #define DAE_FPS 30 ModuleImporter::ModuleImporter(bool start_enabled) : Module(start_enabled) { name = "Importer"; } ModuleImporter::~ModuleImporter() { } bool ModuleImporter::Init() { struct aiLogStream stream; stream = aiGetPredefinedLogStream(aiDefaultLogStream_DEBUGGER, nullptr); aiAttachLogStream(&stream); ilInit(); iluInit(); ilutInit(); LOG_ENGINE("Initing Devil"); if (FT_Init_FreeType(&library)) { LOG_ENGINE("Error when it's initialization FreeType"); } else LOG_ENGINE("FreeType initialized!"); return true; } bool ModuleImporter::Start() { return true; } bool ModuleImporter::CleanUp() { aiDetachAllLogStreams(); FT_Done_FreeType(library); return true; } bool ModuleImporter::LoadModelFile(const char *path, const char *extern_path) { OPTICK_EVENT(); bool ret = true; LOG_ENGINE("Loading %s", path); // if this file has been already imported just load the .alienModel Resource *model = nullptr; if (!App->resources->Exists(path, &model)) { const aiScene *scene = aiImportFile(path, aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_FlipUVs | aiProcess_JoinIdenticalVertices | aiProcessPreset_TargetRealtime_MaxQuality | aiProcess_GenBoundingBoxes | aiProcess_LimitBoneWeights); if (scene != nullptr) { InitScene(path, scene, extern_path); LOG_ENGINE("Succesfully loaded %s", path); } else { ret = false; LOG_ENGINE("Error loading model %s", path); LOG_ENGINE("Error type: %s", aiGetErrorString()); } aiReleaseImport(scene); if(ret) App->resources->AddNewFileNode(path, true); } else { App->resources->CreateNewModelInstanceOf(model->GetLibraryPath()); } return ret; } void ModuleImporter::InitScene(const char *path, const aiScene *scene, const char *extern_path) { OPTICK_EVENT(); model = new ResourceModel(); model->name = App->file_system->GetBaseFileName(path); model->path = std::string(path); //Import meshes & bones if (scene->HasMeshes()) { for (int i = 0; i < scene->mNumMeshes; ++i) { //Import mesh here. LoadMesh(scene->mMeshes[i]); //Import bones of mesh if (scene->mMeshes[i]->HasBones()) { model->meshes_attached[i]->deformable = true; for (int j = 0; j < scene->mMeshes[i]->mNumBones; ++j) { LoadBone(scene->mMeshes[i]->mBones[j], model->meshes_attached[i]->name); } } } } if (scene->HasMaterials()) { for (uint i = 0; i < scene->mNumMaterials; ++i) { LoadMaterials(scene->mMaterials[i], extern_path); } } // Import animations if (scene->HasAnimations()) { for (int i = 0; i < scene->mNumAnimations; ++i) { LoadAnimation(scene->mAnimations[i]); } } // start recursive function to all nodes for (uint i = 0; i < scene->mRootNode->mNumChildren; ++i) { LoadNode(scene->mRootNode->mChildren[i], scene, 1); } // create the meta data files like .alien if (model->CreateMetaData()) { App->resources->AddResource(model); if (App->ui->panel_project != nullptr) { App->ui->panel_project->RefreshAllNodes(); model->ConvertToGameObjects(); ReturnZ::AddNewAction(ReturnZ::ReturnActions::ADD_OBJECT, App->objects->GetRoot(false)->children.back()); } } model = nullptr; } void ModuleImporter::LoadAnimation(const aiAnimation *anim) { OPTICK_EVENT(); bool is_dae = anim->mTicksPerSecond == 1; ResourceAnimation* resource_animation = new ResourceAnimation(); resource_animation->name = std::string(anim->mName.C_Str()) == "" ? "Take 001" : anim->mName.C_Str(); resource_animation->ticks_per_second = is_dae ? DAE_FPS : anim->mTicksPerSecond; resource_animation->num_channels = anim->mNumChannels; resource_animation->channels = new ResourceAnimation::Channel[resource_animation->num_channels]; resource_animation->start_tick = 0; resource_animation->end_tick = is_dae ? anim->mDuration * DAE_FPS : anim->mDuration; resource_animation->max_tick = resource_animation->end_tick; for (uint i = 0u; i < resource_animation->num_channels; ++i) { ResourceAnimation::Channel &channel = resource_animation->channels[i]; channel.name = anim->mChannels[i]->mNodeName.C_Str(); channel.num_position_keys = anim->mChannels[i]->mNumPositionKeys; channel.num_scale_keys = anim->mChannels[i]->mNumScalingKeys; channel.num_rotation_keys = anim->mChannels[i]->mNumRotationKeys; channel.position_keys = new KeyAnimation<float3>[channel.num_position_keys](); channel.scale_keys = new KeyAnimation<float3>[channel.num_scale_keys](); channel.rotation_keys = new KeyAnimation<Quat>[channel.num_rotation_keys](); //Load position keys for (uint j = 0; j < channel.num_position_keys; j++) { channel.position_keys[j].value.Set(anim->mChannels[i]->mPositionKeys[j].mValue.x, anim->mChannels[i]->mPositionKeys[j].mValue.y, anim->mChannels[i]->mPositionKeys[j].mValue.z); channel.position_keys[j].time = is_dae ? std::round(anim->mChannels[i]->mPositionKeys[j].mTime * DAE_FPS) : anim->mChannels[i]->mPositionKeys[j].mTime; } //Load scaling keys for (uint j = 0; j < channel.num_scale_keys; j++) { channel.scale_keys[j].value.Set(anim->mChannels[i]->mScalingKeys[j].mValue.x, anim->mChannels[i]->mScalingKeys[j].mValue.y, anim->mChannels[i]->mScalingKeys[j].mValue.z); channel.scale_keys[j].time = is_dae ? std::round(anim->mChannels[i]->mScalingKeys[j].mTime * DAE_FPS) : anim->mChannels[i]->mScalingKeys[j].mTime; } //Load rotation keys for (uint j = 0; j < channel.num_rotation_keys; j++) { channel.rotation_keys[j].value.Set(anim->mChannels[i]->mRotationKeys[j].mValue.x, anim->mChannels[i]->mRotationKeys[j].mValue.y, anim->mChannels[i]->mRotationKeys[j].mValue.z, anim->mChannels[i]->mRotationKeys[j].mValue.w); channel.rotation_keys[j].time = is_dae ? std::round(anim->mChannels[i]->mRotationKeys[j].mTime * DAE_FPS) : anim->mChannels[i]->mRotationKeys[j].mTime; } } App->resources->AddResource(resource_animation); model->animations_attached.push_back(resource_animation); } void ModuleImporter::LoadBone(const aiBone *bone, std::string mesh_name) { OPTICK_EVENT(); ResourceBone* r_bone = new ResourceBone(); r_bone->name = bone->mName.C_Str(); r_bone->mesh_name = mesh_name; r_bone->matrix = float4x4(float4(bone->mOffsetMatrix.a1, bone->mOffsetMatrix.b1, bone->mOffsetMatrix.c1, bone->mOffsetMatrix.d1), float4(bone->mOffsetMatrix.a2, bone->mOffsetMatrix.b2, bone->mOffsetMatrix.c2, bone->mOffsetMatrix.d2), float4(bone->mOffsetMatrix.a3, bone->mOffsetMatrix.b3, bone->mOffsetMatrix.c3, bone->mOffsetMatrix.d3), float4(bone->mOffsetMatrix.a4, bone->mOffsetMatrix.b4, bone->mOffsetMatrix.c4, bone->mOffsetMatrix.d4)); r_bone->num_weights = bone->mNumWeights; r_bone->weights = new float[r_bone->num_weights]; r_bone->vertex_ids = new uint[r_bone->num_weights]; for (uint i = 0; i < r_bone->num_weights; i++) { memcpy(&r_bone->weights[i], &bone->mWeights[i].mWeight, sizeof(float)); memcpy(&r_bone->vertex_ids[i], &bone->mWeights[i].mVertexId, sizeof(uint)); } App->resources->AddResource(r_bone); model->bones_attached.push_back(r_bone); } void ModuleImporter::LoadMesh(const aiMesh *mesh) { OPTICK_EVENT(); ResourceMesh* ret = new ResourceMesh(); // get vertex ret->vertex = new float[mesh->mNumVertices * 3]; memcpy(ret->vertex, mesh->mVertices, sizeof(float) * mesh->mNumVertices * 3); ret->num_vertex = mesh->mNumVertices; // get index if (mesh->HasFaces()) { ret->num_index = mesh->mNumFaces * 3; ret->index = new uint[ret->num_index]; // assume each face is a triangle for (uint i = 0; i < mesh->mNumFaces; ++i) { if (mesh->mFaces[i].mNumIndices != 3) { uint non[3] = {0, 0, 0}; memcpy(&ret->index[i * 3], non, 3 * sizeof(uint)); LOG_ENGINE("WARNING, geometry face with != 3 indices!"); } else { memcpy(&ret->index[i * 3], mesh->mFaces[i].mIndices, 3 * sizeof(uint)); } } } // get normals if (mesh->HasNormals()) { ret->normals = new float[mesh->mNumVertices * 3]; memcpy(ret->normals, mesh->mNormals, sizeof(float) * mesh->mNumVertices * 3); ret->center_point_normal = new float[mesh->mNumFaces * 3]; ret->center_point = new float[mesh->mNumFaces * 3]; ret->num_faces = mesh->mNumFaces; for (uint i = 0; i < ret->num_index; i += 3) { uint index1 = ret->index[i] * 3; uint index2 = ret->index[i + 1] * 3; uint index3 = ret->index[i + 2] * 3; float3 x0(ret->vertex[index1], ret->vertex[index1 + 1], ret->vertex[index1 + 2]); float3 x1(ret->vertex[index2], ret->vertex[index2 + 1], ret->vertex[index2 + 2]); float3 x2(ret->vertex[index3], ret->vertex[index3 + 1], ret->vertex[index3 + 2]); float3 v0 = x0 - x2; float3 v1 = x1 - x2; float3 n = v0.Cross(v1); float3 normalized = n.Normalized(); ret->center_point[i] = (x0.x + x1.x + x2.x) / 3; ret->center_point[i + 1] = (x0.y + x1.y + x2.y) / 3; ret->center_point[i + 2] = (x0.z + x1.z + x2.z) / 3; ret->center_point_normal[i] = normalized.x; ret->center_point_normal[i + 1] = normalized.y; ret->center_point_normal[i + 2] = normalized.z; } } // get UV if (mesh->HasTextureCoords(0)) { ret->uv_cords = new float[mesh->mNumVertices * 3]; memcpy(ret->uv_cords, (float *)mesh->mTextureCoords[0], sizeof(float) * mesh->mNumVertices * 3); } if (mesh->HasTangentsAndBitangents()) { ret->tangents = new float[mesh->mNumVertices * 3]; memcpy(ret->tangents, (float*)mesh->mTangents, sizeof(float) * mesh->mNumVertices * 3); ret->biTangents = new float[mesh->mNumVertices * 3]; memcpy(ret->biTangents, (float*)mesh->mBitangents, sizeof(float) * mesh->mNumVertices * 3); } ret->name = std::string(mesh->mName.C_Str()); ret->InitBuffers(); App->resources->AddResource(ret); model->meshes_attached.push_back(ret); } void ModuleImporter::LoadNode(const aiNode *node, const aiScene *scene, uint nodeNum) { OPTICK_EVENT(); aiMatrix4x4 mat; while (std::string(node->mName.C_Str()).find("_$AssimpFbx$_") != std::string::npos) { mat = mat * node->mTransformation; node = node->mChildren[0]; } if (mat.IsIdentity()) mat = node->mTransformation; ModelNode model_node; model_node.name = std::string(node->mName.C_Str()); const aiNode* pNode = node; while (std::string(pNode->mParent->mName.C_Str()).find("_$AssimpFbx$_") != std::string::npos) { pNode = pNode->mParent; } model_node.parent_name = (pNode->mParent == scene->mRootNode) ? model->name : std::string(pNode->mParent->mName.C_Str()); model_node.parent_num = nodeNum; model_node.node_num = nodeNum + 1; if (node->mNumMeshes == 1) { model_node.mesh = node->mMeshes[0]; model_node.material = scene->mMeshes[node->mMeshes[0]]->mMaterialIndex; } else if (node->mNumMeshes > 1) { for (uint i = 0; i < node->mNumMeshes; ++i) { ModelNode nodeMesh; nodeMesh.name = std::string(node->mName.C_Str() + std::to_string(i)); nodeMesh.mesh = node->mMeshes[i]; nodeMesh.material = scene->mMeshes[node->mMeshes[i]]->mMaterialIndex; nodeMesh.parent_name = model_node.name; nodeMesh.node_num = nodeNum + 2; nodeMesh.parent_num = nodeNum + 1; model->model_nodes.push_back(nodeMesh); } } for (uint i = 0; i < model->bones_attached.size(); ++i) { if (model->bones_attached[i]->name == model_node.name) { model_node.bones.push_back(i); } } aiVector3D pos, scale; aiQuaternion rot; mat.Decompose(scale, rot, pos); model_node.pos = float3(pos.x, pos.y, pos.z); model_node.scale = float3(scale.x, scale.y, scale.z); model_node.rot = Quat(rot.x, rot.y, rot.z, rot.w); for (uint i = 0; i < node->mNumChildren; ++i) { LoadNode(node->mChildren[i], scene, nodeNum + 1); } model->model_nodes.push_back(model_node); } void ModuleImporter::LoadMaterials(aiMaterial *material, const char *extern_path) { OPTICK_EVENT(); ResourceMaterial* mat = new ResourceMaterial(); mat->SetName(material->GetName().C_Str()); aiColor4D col; if (AI_SUCCESS == material->Get(AI_MATKEY_COLOR_DIFFUSE, col)) { mat->color.x = col.r; mat->color.y = col.g; mat->color.z = col.b; mat->color.w = col.a; } LoadModelTexture(material, mat, aiTextureType_DIFFUSE, TextureType::DIFFUSE, extern_path); LoadModelTexture(material, mat, aiTextureType_SPECULAR, TextureType::SPECULAR, extern_path); LoadModelTexture(material, mat, aiTextureType_NORMALS, TextureType::NORMALS, extern_path); model->materials_attached.push_back(mat); } void ModuleImporter::LoadModelTexture(const aiMaterial *material, ResourceMaterial *mat, aiTextureType assimp_type, TextureType type, const char *extern_path) { OPTICK_EVENT(); aiString ai_path; if (AI_SUCCESS == material->GetTexture(assimp_type, 0, &ai_path)) { std::string name = ai_path.C_Str(); App->file_system->NormalizePath(name); ResourceTexture *tex = (ResourceTexture *)App->resources->GetTextureByName(name.data()); if (tex != nullptr) { mat->textures[(uint)type].first = tex->GetID(); mat->textures[(uint)type].second = tex; } else if (extern_path != nullptr) { std::string normExtern(extern_path); App->file_system->NormalizePath(normExtern); std::string textureName = App->file_system->GetBaseFileNameWithExtension(name.data()); App->file_system->NormalizePath(textureName); std::string texturePath = App->file_system->GetCurrentHolePathFolder(normExtern) + textureName; while (texturePath[0] == '.' || texturePath[1] == '/') { texturePath.erase(texturePath.begin()); } if (std::experimental::filesystem::exists(texturePath)) { std::string assets_path = TEXTURES_FOLDER + textureName; App->file_system->CopyFromOutsideFS(texturePath.data(), assets_path.data()); tex = new ResourceTexture(assets_path.data()); tex->CreateMetaData(); App->resources->AddNewFileNode(assets_path, true); mat->textures[(uint)type].first = tex->GetID(); mat->textures[(uint)type].second = tex; } } } } ResourceTexture *ModuleImporter::LoadTextureFile(const char *path, bool has_been_dropped, bool is_custom) { OPTICK_EVENT(); ResourceTexture* texture = nullptr; if (!has_been_dropped && !App->file_system->Exists(path)) { return nullptr; } Resource *tex = nullptr; if (App->resources->Exists(path, &tex)) { std::string meta_path_in_assets = App->file_system->GetPathWithoutExtension(path) + "_meta.alien"; u64 ID = App->resources->GetIDFromAlienPath(meta_path_in_assets.data()); texture = (ResourceTexture *)App->resources->GetResourceWithID(ID); if (has_been_dropped && !App->objects->GetSelectedObjects().empty()) { ApplyTextureToSelectedObject(texture); } LOG_ENGINE("This texture was already loaded"); return texture; } else { texture = new ResourceTexture(path); texture->CreateMetaData(); App->resources->AddNewFileNode(path, true); if (has_been_dropped && !App->objects->GetSelectedObjects().empty()) { ApplyTextureToSelectedObject(texture); } } return texture; } ResourceTexture *ModuleImporter::LoadEngineTexture(const char *path) { OPTICK_EVENT(); ResourceTexture* texture = nullptr; ILuint new_image_id = 0; ilGenImages(1, &new_image_id); ilBindImage(new_image_id); ilutRenderer(ILUT_OPENGL); if (ilLoadImage(path)) { iluFlipImage(); texture = new ResourceTexture(path, ilutGLBindTexImage(), ilGetInteger(IL_IMAGE_WIDTH), ilGetInteger(IL_IMAGE_HEIGHT)); texture->is_custom = false; glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glBindTexture(GL_TEXTURE_2D, texture->id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glBindTexture(GL_TEXTURE_2D, 0); App->resources->AddResource(texture); LOG_ENGINE("Texture successfully loaded: %s", path); } else { LOG_ENGINE("Error while loading image in %s", path); LOG_ENGINE("Error: %s", ilGetString(ilGetError())); } ilDeleteImages(1, &new_image_id); return texture; } ResourceFont *ModuleImporter::LoadFontFile(const char *path) { ResourceFont *font = nullptr; if (!App->resources->GetFontByName(App->file_system->GetBaseFileName(path).c_str())) { font = ResourceFont::ImportFile(path); } return font; } bool ModuleImporter::LoadTextureToResource(const char *path, ResourceTexture *texture) { bool ret = true; ILuint new_image_id = 0; ilGenImages(1, &new_image_id); ilBindImage(new_image_id); ilutRenderer(ILUT_OPENGL); if (ilLoadImage(path)) { iluFlipImage(); texture->id = ilutGLBindTexImage(); texture->is_custom = true; texture->width = ilGetInteger(IL_IMAGE_WIDTH); texture->height = ilGetInteger(IL_IMAGE_HEIGHT); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); glBindTexture(GL_TEXTURE_2D, texture->id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); //select wrap parameter //switch (texture->wrap_type) //{ //case 0: // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // break; //case 1: // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); // break; //case 3: // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_MIRRORED_REPEAT); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT); // break; //case 4: // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER); // break; //default: // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); // break; //} ////select tex filter //switch (texture->texture_filter) //{ //case 0: // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // break; //case 1: // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); // break; //case 2: // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST_MIPMAP_NEAREST); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST); // break; //case 3: // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_NEAREST); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_NEAREST); // break; //case 4: // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST_MIPMAP_LINEAR); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_LINEAR); // break; //case 5: // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR); // break; //default: // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); // break; //} glBindTexture(GL_TEXTURE_2D, 0); ilBindImage(0); } else { //ILenum Error; //while ((Error = ilGetError()) != IL_NO_ERROR) //{ // const char* txt = iluErrorString(Error); // LOG_ENGINE("%d: %s", Error, txt); //} ////LOG_ENGINE("Error while loading image in %s", path); ////LOG_ENGINE("Error: %s", ilGetString(ilGetError())); ret = false; } ilDeleteImages(1, &new_image_id); return ret; } void ModuleImporter::ApplyTextureToSelectedObject(ResourceTexture *texture) { std::list<GameObject *> selected = App->objects->GetSelectedObjects(); auto item = selected.begin(); for (; item != selected.end(); ++item) { if (*item != nullptr) { ComponentMaterial *compMaterial = (ComponentMaterial *)(*item)->GetComponent(ComponentType::MATERIAL); if ((*item)->HasComponent(ComponentType::MESH) || (*item)->HasComponent(ComponentType::DEFORMABLE_MESH)) { bool exists = true; if (compMaterial == nullptr) { exists = false; compMaterial = new ComponentMaterial((*item)); (*item)->AddComponent(compMaterial); } compMaterial->SetTexture(texture, TextureType::DIFFUSE); if (!exists) { ReturnZ::AddNewAction(ReturnZ::ReturnActions::ADD_COMPONENT, compMaterial); } else { ReturnZ::AddNewAction(ReturnZ::ReturnActions::CHANGE_COMPONENT, compMaterial); } } else LOG_ENGINE("Selected GameObject has no mesh"); /*if ((*item)->HasComponent(ComponentType::PARTICLES)) { ComponentParticleSystem *particleSystem = (ComponentParticleSystem *)(*item)->GetComponent(ComponentType::PARTICLES); if (texture->NeedToLoad()) texture->LoadMemory(); particleSystem->SetTexture(texture); } else LOG_ENGINE("Selected GameObject has no particle system");*/ } } } ResourceShader *ModuleImporter::LoadShaderFile(const char *path, bool has_been_dropped, bool is_custom) { ResourceShader *shader = nullptr; if (!has_been_dropped && !App->file_system->Exists(path)) { return nullptr; } Resource *shad = nullptr; if (App->resources->Exists(path, &shad)) { std::string meta_path_in_assets = App->file_system->GetPathWithoutExtension(path) + "_meta.alien"; u64 ID = App->resources->GetIDFromAlienPath(meta_path_in_assets.data()); shader = (ResourceShader *)App->resources->GetResourceWithID(ID); if (has_been_dropped && !App->objects->GetSelectedObjects().empty()) { ApplyShaderToSelectedObject(shader); } LOG_ENGINE("This shader was already loaded"); return shader; } else { shader = new ResourceShader(path); shader->CreateMetaData(); App->resources->AddNewFileNode(path, true); if (has_been_dropped && !App->objects->GetSelectedObjects().empty()) { ApplyShaderToSelectedObject(shader); } } return shader; } void ModuleImporter::ApplyShaderToSelectedObject(ResourceShader *shader) { // TODO } void ModuleImporter::ApplyMaterialToSelectedObject(ResourceMaterial* material) { std::list<GameObject*> selected = App->objects->GetSelectedObjects(); auto item = selected.begin(); for (; item != selected.end(); ++item) { if (*item != nullptr) { if (!(*item)->HasComponent(ComponentType::MESH) && !(*item)->HasComponent(ComponentType::DEFORMABLE_MESH) && !(*item)->HasComponent(ComponentType::PARTICLES)) continue; ComponentMaterial* materialComp = (ComponentMaterial*)(*item)->GetComponent(ComponentType::MATERIAL); if (materialComp == nullptr) { materialComp = new ComponentMaterial(*item); (*item)->AddComponent(materialComp); } materialComp->SetMaterial(material); } } } void ModuleImporter::ApplyParticleSystemToSelectedObject(std::string path) { std::list<GameObject *> selected = App->objects->GetSelectedObjects(); auto item = selected.begin(); for (; item != selected.end(); ++item) { if (*item != nullptr) { if (!(*item)->HasComponent(ComponentType::PARTICLES)) (*item)->AddComponent(new ComponentParticleSystem(*item)); std::string name = path; App->file_system->NormalizePath(name); JSON_Value *value = json_parse_file(name.data()); JSON_Object *object = json_value_get_object(value); if (value != nullptr && object != nullptr) { JSONfilepack *particles = new JSONfilepack(name.data(), object, value); JSONArraypack *properties = particles->GetArray("ParticleSystem.Properties"); if (properties != nullptr) { ComponentParticleSystem *particleSystem = (ComponentParticleSystem *)(*item)->GetComponent(ComponentType::PARTICLES); particleSystem->LoadComponent(properties); } delete particles; } else { LOG_ENGINE("Error loading particle system %s", name.data()); } } } } void ModuleImporter::LoadParShapesMesh(par_shapes_mesh *shape, ResourceMesh *mesh) { par_shapes_unweld(shape, true); par_shapes_compute_normals(shape); mesh->num_vertex = shape->npoints; mesh->num_index = shape->ntriangles * 3; mesh->vertex = new float[mesh->num_vertex * 3]; mesh->index = new uint[mesh->num_index * 3]; memcpy(mesh->vertex, shape->points, sizeof(float) * mesh->num_vertex * 3); memcpy(mesh->index, shape->triangles, sizeof(PAR_SHAPES_T) * mesh->num_index); if (shape->tcoords != nullptr) { mesh->uv_cords = new float[mesh->num_vertex * 3]; memcpy(mesh->uv_cords, shape->tcoords, sizeof(float) * mesh->num_vertex * 3); } if (shape->normals != nullptr) { mesh->normals = new float[mesh->num_vertex * 3]; memcpy(mesh->normals, shape->normals, sizeof(float) * mesh->num_vertex * 3); mesh->center_point_normal = new float[shape->ntriangles * 3]; mesh->center_point = new float[shape->ntriangles * 3]; mesh->num_faces = shape->ntriangles; for (uint i = 0; i < mesh->num_index; i += 3) { uint index1 = mesh->index[i] * 3; uint index2 = mesh->index[i + 1] * 3; uint index3 = mesh->index[i + 2] * 3; float3 x0(mesh->vertex[index1], mesh->vertex[index1 + 1], mesh->vertex[index1 + 2]); float3 x1(mesh->vertex[index2], mesh->vertex[index2 + 1], mesh->vertex[index2 + 2]); float3 x2(mesh->vertex[index3], mesh->vertex[index3 + 1], mesh->vertex[index3 + 2]); float3 v0 = x0 - x2; float3 v1 = x1 - x2; float3 n = v0.Cross(v1); float3 normalized = n.Normalized(); mesh->center_point[i] = (x0.x + x1.x + x2.x) / 3; mesh->center_point[i + 1] = (x0.y + x1.y + x2.y) / 3; mesh->center_point[i + 2] = (x0.z + x1.z + x2.z) / 3; mesh->center_point_normal[i] = normalized.x; mesh->center_point_normal[i + 1] = normalized.y; mesh->center_point_normal[i + 2] = normalized.z; } } mesh->InitBuffers(); } ResourceMesh *ModuleImporter::LoadEngineModels(const char *path) { ResourceMesh *ret = nullptr; const aiScene *scene = aiImportFile(path, aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_FlipUVs | aiProcess_JoinIdenticalVertices | aiProcessPreset_TargetRealtime_MaxQuality | aiProcess_GenBoundingBoxes); ret = new ResourceMesh(); // get vertex ret->vertex = new float[scene->mMeshes[0]->mNumVertices * 3]; memcpy(ret->vertex, scene->mMeshes[0]->mVertices, sizeof(float) * scene->mMeshes[0]->mNumVertices * 3); ret->num_vertex = scene->mMeshes[0]->mNumVertices; // get index if (scene->mMeshes[0]->HasFaces()) { ret->num_index = scene->mMeshes[0]->mNumFaces * 3; ret->index = new uint[ret->num_index]; // assume each face is a triangle for (uint i = 0; i < scene->mMeshes[0]->mNumFaces; ++i) { if (scene->mMeshes[0]->mFaces[i].mNumIndices != 3) { uint non[3] = {0, 0, 0}; memcpy(&ret->index[i * 3], non, 3 * sizeof(uint)); LOG_ENGINE("WARNING, geometry face with != 3 indices!"); } else { memcpy(&ret->index[i * 3], scene->mMeshes[0]->mFaces[i].mIndices, 3 * sizeof(uint)); } } } // get normals if (scene->mMeshes[0]->HasNormals()) { ret->normals = new float[scene->mMeshes[0]->mNumVertices * 3]; memcpy(ret->normals, scene->mMeshes[0]->mNormals, sizeof(float) * scene->mMeshes[0]->mNumVertices * 3); ret->center_point_normal = new float[scene->mMeshes[0]->mNumFaces * 3]; ret->center_point = new float[scene->mMeshes[0]->mNumFaces * 3]; ret->num_faces = scene->mMeshes[0]->mNumFaces; for (uint i = 0; i < ret->num_index; i += 3) { uint index1 = ret->index[i] * 3; uint index2 = ret->index[i + 1] * 3; uint index3 = ret->index[i + 2] * 3; float3 x0(ret->vertex[index1], ret->vertex[index1 + 1], ret->vertex[index1 + 2]); float3 x1(ret->vertex[index2], ret->vertex[index2 + 1], ret->vertex[index2 + 2]); float3 x2(ret->vertex[index3], ret->vertex[index3 + 1], ret->vertex[index3 + 2]); float3 v0 = x0 - x2; float3 v1 = x1 - x2; float3 n = v0.Cross(v1); float3 normalized = n.Normalized(); ret->center_point[i] = (x0.x + x1.x + x2.x) / 3; ret->center_point[i + 1] = (x0.y + x1.y + x2.y) / 3; ret->center_point[i + 2] = (x0.z + x1.z + x2.z) / 3; ret->center_point_normal[i] = normalized.x; ret->center_point_normal[i + 1] = normalized.y; ret->center_point_normal[i + 2] = normalized.z; } } // get UV if (scene->mMeshes[0]->HasTextureCoords(0)) { ret->uv_cords = new float[scene->mMeshes[0]->mNumVertices * 3]; memcpy(ret->uv_cords, (float *)scene->mMeshes[0]->mTextureCoords[0], sizeof(float) * scene->mMeshes[0]->mNumVertices * 3); } ret->InitBuffers(); aiReleaseImport(scene); if (ret != nullptr) { ret->is_custom = false; } return ret; } bool ModuleImporter::ReImportModel(ResourceModel *model) { bool ret = true; const aiScene *scene = aiImportFile(model->GetAssetsPath(), aiProcess_Triangulate | aiProcess_GenSmoothNormals | aiProcess_FlipUVs | aiProcess_JoinIdenticalVertices | aiProcessPreset_TargetRealtime_MaxQuality | aiProcess_GenBoundingBoxes); if (scene != nullptr) { model->name = App->file_system->GetBaseFileName(model->GetAssetsPath()); this->model = model; //Import meshes & bones if (scene->HasMeshes()) { for (int i = 0; i < scene->mNumMeshes; ++i) { //Import mesh here. LoadMesh(scene->mMeshes[i]); //Import bones of mesh if (scene->mMeshes[i]->HasBones()) { model->meshes_attached[i]->deformable = true; for (int j = 0; j < scene->mMeshes[i]->mNumBones; ++j) { LoadBone(scene->mMeshes[i]->mBones[j], model->meshes_attached[i]->name); } } } } ReImportAnimations(model, scene); // start recursive function to all nodes for (uint i = 0; i < scene->mRootNode->mNumChildren; ++i) { LoadNode(scene->mRootNode->mChildren[i], scene, 1); } // create the meta data files like .alien if (model->CreateMetaData(model->ID)) { App->resources->AddResource(model); model->FreeMemory(); } this->model = nullptr; } else { ret = false; LOG_ENGINE("Error loading model %s", model->GetAssetsPath()); LOG_ENGINE("Error type: %s", aiGetErrorString()); } aiReleaseImport(scene); return ret; } void ModuleImporter::ReImportAnimations(ResourceModel *model, const aiScene *scene) { if (scene->HasAnimations()) { for (int i = 0; i < scene->mNumAnimations; i++) { LoadAnimation(scene->mAnimations[i]); } JSON_Value *value = json_parse_file(model->meta_data_path.data()); JSON_Object *object = json_value_get_object(value); if (value != nullptr && object != nullptr) { JSONfilepack *meta = new JSONfilepack(model->meta_data_path.data(), object, value); uint num_anims = meta->GetNumber("Meta.NumAnimations"); JSONArraypack *anims_meta = meta->GetArray("Meta.Animations"); for (int i = 0; i < num_anims; ++i) { if (i > 0) { ResourceAnimation *new_anim = new ResourceAnimation(); model->animations_attached.push_back(new_anim); App->resources->AddResource(new_anim); model->animations_attached[i]->Copy(model->animations_attached[0]); } anims_meta->GetNode(i); model->animations_attached[i]->name = anims_meta->GetString("Name"); model->animations_attached[i]->loops = anims_meta->GetBoolean("Loops"); model->animations_attached[i]->start_tick = anims_meta->GetNumber("Start_Tick"); model->animations_attached[i]->end_tick = anims_meta->GetNumber("End_Tick"); } delete meta; } } }
30.15
170
0.697347
[ "mesh", "geometry", "object", "shape", "model" ]
4fb247bb5dc8de549a7cb61d74dfa0bc36dda80e
2,185
cpp
C++
Software/Luminary/rpc/rcp_responder.cpp
brandonbraun653/Luminary
c9b4e4d6598f09de945fdbcf5aee1508c1687fa9
[ "MIT" ]
null
null
null
Software/Luminary/rpc/rcp_responder.cpp
brandonbraun653/Luminary
c9b4e4d6598f09de945fdbcf5aee1508c1687fa9
[ "MIT" ]
1
2020-02-29T05:54:15.000Z
2020-02-29T05:54:15.000Z
Software/Luminary/rpc/rcp_responder.cpp
brandonbraun653/Luminary
c9b4e4d6598f09de945fdbcf5aee1508c1687fa9
[ "MIT" ]
null
null
null
/******************************************************************************** * File Name: * rcp_responder.cpp * * Description: * Implementation of various responses to RPC commands * * 2020 | Brandon Braun | brandonbraun653@gmail.com *******************************************************************************/ /* STL Includes */ #include <cstring> /* Chimera Includes */ #include <Chimera/common> /* Luminary Includes */ #include <Luminary/model/mdl_observables.hpp> #include <Luminary/rpc/rpc_responder.hpp> #include <Luminary/rpc/types.hpp> namespace Luminary::RPC { /*------------------------------------------------------------------------------- Generic Response Function Definitions -------------------------------------------------------------------------------*/ size_t ackResponse( MessageBuffer &message, const CommandID cmd ) { message.fill( 0 ); snprintf( reinterpret_cast<char *>( message.data() ), message.size(), "@R:ACK:%d~", static_cast<size_t>( cmd ) ); return strlen( reinterpret_cast<char *>( message.data() ) ); } size_t nackResponse( MessageBuffer &message, const CommandID cmd ) { message.fill( 0 ); snprintf( reinterpret_cast<char *>( message.data() ), message.size(), "@R:NACK:%d~", static_cast<size_t>( cmd ) ); return strlen( reinterpret_cast<char *>( message.data() ) ); } size_t unknownResponse( MessageBuffer &message ) { message.fill( 0 ); snprintf( reinterpret_cast<char *>( message.data() ), message.size(), "@R:NACK:Unknown Command~" ); return strlen( reinterpret_cast<char *>( message.data() ) ); } size_t unregisteredResponse( MessageBuffer &message ) { message.fill( 0 ); snprintf( reinterpret_cast<char *>( message.data() ), message.size(), "@R:NACK:Unregistered Command~" ); return strlen( reinterpret_cast<char *>( message.data() ) ); } size_t invalidHandlerResponse( MessageBuffer &message ) { message.fill( 0 ); snprintf( reinterpret_cast<char *>( message.data() ), message.size(), "@R:NACK:Invalid Handler~" ); return strlen( reinterpret_cast<char *>( message.data() ) ); } } // namespace Luminary::RPC
32.61194
118
0.571625
[ "model" ]
4fb288b40d1373ef4d852816f9657ccdd6d8b9eb
9,209
cpp
C++
src/Rect.cpp
filipecaixeta/NeonEdgeGame
7dbc825507d731d60a96b4a82975a70e6aa68d7e
[ "MIT" ]
6
2017-05-10T19:25:23.000Z
2021-04-08T23:55:17.000Z
src/Rect.cpp
filipecaixeta/NeonEdgeGame
7dbc825507d731d60a96b4a82975a70e6aa68d7e
[ "MIT" ]
1
2017-11-10T12:17:26.000Z
2017-11-10T12:17:26.000Z
src/Rect.cpp
filipecaixeta/NeonEdgeGame
7dbc825507d731d60a96b4a82975a70e6aa68d7e
[ "MIT" ]
5
2017-05-30T01:07:46.000Z
2021-04-08T23:55:19.000Z
/** * Copyright 2017 Neon Edge Game * File Name: Rect.cpp * Header File Name: Rect.h * Class Name: Rect * Function Objective:: Define a class to represent retangles. */ #include "Rect.h" #include "Logger.h" /** * Objective: Method responsible for testing float parameters received in functions. * * @param float testFloat - Value to be tested. * @return - False whether the value is valid or true if the value is valid. */ bool CheckFloatRect(float testFloat) { bool veryValue = false; if ((testFloat >= FLOAT_SIZE_MIN) && (testFloat <= FLOAT_SIZE_MAX)) { veryValue = true; } else { // It does nothing. } return veryValue; } /** * Objective: Constructor of the class Rect. * * @param None. * @return: Instance of Rect. */ Rect::Rect() { if (CheckFloatRect(VALUE_INITIAL_FLOAT)) { x = VALUE_INITIAL_FLOAT; y = VALUE_INITIAL_FLOAT; w = VALUE_INITIAL_FLOAT; h = VALUE_INITIAL_FLOAT; } else { Log::instance.error("Float out of bounds!"); } } /** * Objective: overload of the constructor of Rect class. * * @param float x -position x axis ofthe rect instance) * @param float y - position y axis of the rect instance * @param float w- width of the rect * @param float h - height of the rect * @return: Instance of Rect. */ Rect::Rect(float x, float y, float w, float h) { if (CheckFloatRect(y) && CheckFloatRect(x) && CheckFloatRect(w) && CheckFloatRect(h)) { Rect::x = x; Rect::y = y; Rect::w = w; Rect::h = h; } else { Log::instance.error("Float out of bounds!"); } } /** * Objective: Destructor of the class Rect. * * @param None. * @return: Void */ Rect::~Rect() { } /** * Objective: Return the vector acting in the position of the rect. * * @param: None * @return: Vec2(x,y) */ Vec2 Rect::GetXY() { if (CheckFloatRect(x) && CheckFloatRect(y)) { return Vec2(x, y); } else { Log::instance.error("Float out of bounds!"); } } /** * Objective:: Set the position vector that act in the rect. * * @param: Vec2 v - vector to be setble. * @return: void. */ void Rect::SetXY(Vec2 v) { if (CheckFloatRect(v.x) && CheckFloatRect(v.y)) { x = v.x; y = v.y; } else { Log::instance.error("Float out of bounds!"); } } /** * Objective: Return the vector acting in the height and width of the rect. * * @param None. * @return: Void */ Vec2 Rect::GetWH() { if (CheckFloatRect(w) && CheckFloatRect(h)) { return Vec2(w, h); } else { Log::instance.error("Float out of bounds!"); } } /** * Objective: Set the heigth and width vector that act in the rect. * * @param: Vec2 v. * @return: void. */ void Rect::SetWH(Vec2 v) { if (CheckFloatRect(v.x) && CheckFloatRect(v.y)) { w = v.x; h = v.y; } else { Log::instance.error("Float out of bounds!"); } } /** * Objective: Return the center point of the rect. * * @param None. * @return Vec2 center - the center point of the rect. */ Vec2 Rect::GetCenter() { if (CheckFloatRect(x + w) && CheckFloatRect(y + h)) { Vec2 center = Vec2(x + w / CENTER_AJUST, y + h / CENTER_AJUST); return center; //Calculate the center and return. } else { Log::instance.error("Float out of bounds!"); } } /** * Objective: Return the left botton of the rect. * * @param None. * @return point of the botton left. */ Vec2 Rect::GetBottomLeft() { if (CheckFloatRect(x) && CheckFloatRect(y+h)) { Vec2 bottomLeft = Vec2(x, y + h); return bottomLeft; } else { Log::instance.error("Float out of bounds!"); } } /** * Objective:: Check if a point is inside the rect. * * @param Vec2 dot - dot to be checked. * @return bool(True if is inside. False if is not) */ bool Rect::IsInside(Vec2 dot) { bool isInside = false; if (CheckFloatRect(dot.x) && CheckFloatRect(dot.y)) { bool checkPositionX = (dot.x > x); bool checkPositionY = (dot.y > y); bool checkWeigth = (dot.x < x + w); bool checkHeight = (dot.y < y + h); isInside = (checkPositionX && checkWeigth && checkPositionY && checkPositionY); } else { // It does nothing. } return isInside; } /** * Objective: Overlap a rect. * * @param: Rect r - rect to be overlaped. * @return: Rect Overlaped. */ Rect Rect::GetOverlap(const Rect &r) { if (CheckFloatRect(VALUE_INITIAL_FLOAT)) { float minX = VALUE_INITIAL_FLOAT; float maxX = VALUE_INITIAL_FLOAT; float minY = VALUE_INITIAL_FLOAT; float maxY = VALUE_INITIAL_FLOAT; if (CheckFloatRect(r.x) && CheckFloatRect(r.y) && CheckFloatRect(r.w) && CheckFloatRect(r.h) && CheckFloatRect(x + w) && CheckFloatRect(r.x + r.w) && CheckFloatRect(y + h) && CheckFloatRect(r.y + r.h)) { minX = std::max(x, r.x); maxX = std::min(x + w, r.x + r.w); minY = std::max(y, r.y); maxY = std::min(y + h, r.y + r.h); } else { // It does nothing. } if (CheckFloatRect(maxX - minX && maxY - minY)) { return Rect(minX, minY, maxX - minX, maxY - minY); } else { Log::instance.error("Float out of bounds!"); } } else { Log::instance.error("Float out of bounds!"); } } /** * Objective: Check with rect is overlaped. * * @param: Rect r - Rect to be checked. * @return: bool - true if is overlaped, false if is not. */ bool Rect::OverlapsWith(const Rect &r) { bool testBoolean = true; if ((CheckFloatRect(r.x)) && (CheckFloatRect(r.y)) && CheckFloatRect(r.w) && CheckFloatRect(r.h) ) { float distX = x - r.x; float distY = y - r.y; if ((distX >= r.w || -distX >= w || distY >= r.h || -distY >= h)) { testBoolean = false; } else { // It does nothing. } } else { // It does nothing. } return testBoolean; } /** * Objective: Sum a point with the position of the rect. * * @param Vec2 v1 - (point to be summed) * @return: Rect - position summed. */ Rect Rect::operator+(const Vec2& v1) { if (CheckFloatRect(VALUE_INITIAL_FLOAT)) { float sumX = VALUE_INITIAL_FLOAT; float sumY = VALUE_INITIAL_FLOAT; float sumW = VALUE_INITIAL_FLOAT; float sumH = VALUE_INITIAL_FLOAT; if (CheckFloatRect(v1.x) && CheckFloatRect(v1.y) && CheckFloatRect(x) && CheckFloatRect(y) && CheckFloatRect(w) && CheckFloatRect(h) && CheckFloatRect(x + v1.x) && CheckFloatRect(y + v1.y) && CheckFloatRect(w + v1.x) && CheckFloatRect(h + v1.y)) { sumX = x + v1.x; sumY = y + v1.y; sumW = w + v1.x; sumH = h + v1.y; } else { Log::instance.error("Float out of bounds!"); } if (CheckFloatRect(sumX) && CheckFloatRect(sumY) && CheckFloatRect(sumW) && CheckFloatRect(sumH)) { return Rect(sumX, sumY, sumW, sumH); } else { Log::instance.error("Float out of bounds!"); } } else { Log::instance.error("Float out of bounds!"); } } /** * Objective: Subtract position of the rect with a dot. * * @param: Vec2 v1 - Dot to be subtracted. * @return: Rect - Return the new rect in new position. */ Rect Rect::operator-(const Vec2& v1) { if (CheckFloatRect(VALUE_INITIAL_FLOAT)) { float subX = VALUE_INITIAL_FLOAT; float subY = VALUE_INITIAL_FLOAT; float subW = VALUE_INITIAL_FLOAT; float subH = VALUE_INITIAL_FLOAT; if (CheckFloatRect(v1.x) && CheckFloatRect(v1.y) && CheckFloatRect(x) && CheckFloatRect(y) && CheckFloatRect(w) && CheckFloatRect(h) && CheckFloatRect(x - v1.x) && CheckFloatRect(y - v1.y) && CheckFloatRect(w - v1.x) && CheckFloatRect(h - v1.y)) { subX = x - v1.x; subY = y - v1.y; subW = w - v1.x; subH = h - v1.y; } else { Log::instance.error("Float out of bounds!"); } if (CheckFloatRect(subX) && CheckFloatRect(subY) && CheckFloatRect(subW) && CheckFloatRect(subH)) { return Rect(subX, subY, subW, subH); } else { Log::instance.error("Float out of bounds!"); } } else { Log::instance.error("Float out of bounds!"); } }
29.802589
108
0.52731
[ "vector" ]
4fb34486f5e2496db5ca744e419ee72952cf695a
4,577
cpp
C++
src/python/dataset.cpp
lf-shaw/operon
09a6ac1932d552b8be505f235318e50e923b0da1
[ "MIT" ]
50
2020-10-14T10:08:21.000Z
2022-03-10T12:55:05.000Z
src/python/dataset.cpp
lf-shaw/operon
09a6ac1932d552b8be505f235318e50e923b0da1
[ "MIT" ]
16
2020-10-26T13:05:47.000Z
2022-02-22T20:24:41.000Z
src/python/dataset.cpp
lf-shaw/operon
09a6ac1932d552b8be505f235318e50e923b0da1
[ "MIT" ]
16
2020-10-26T13:05:38.000Z
2022-01-14T02:52:13.000Z
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: Copyright 2019-2021 Heal Research #include <pybind11/pybind11.h> #include <pybind11/numpy.h> #include <pybind11/stl.h> #include <pybind11/eigen.h> #include <pybind11/functional.h> #include "core/dataset.hpp" #include "operon.hpp" namespace py = pybind11; template<typename T> Operon::Dataset MakeDataset(py::array_t<T> array) { static_assert(std::is_arithmetic_v<T>, "T must be an arithmetic type."); // sanity check if (array.ndim() != 2) { throw std::runtime_error("The input array must have exactly two dimensions.\n"); } // check if the array satisfies our data storage requirements (contiguous, column-major order) if (std::is_same_v<T, Operon::Scalar> && (array.flags() & py::array::f_style)) { auto ref = array.template cast<Eigen::Ref<Operon::Dataset::Matrix const>>(); return Operon::Dataset(ref); } else { fmt::print(stderr, "operon warning: array does not satisfy contiguity or storage-order requirements. data will be copied.\n"); auto m = array.template cast<Operon::Dataset::Matrix>(); return Operon::Dataset(std::move(m)); } } template<typename T> Operon::Dataset MakeDataset(std::vector<std::vector<T>> const& values) { static_assert(std::is_arithmetic_v<T>, "T must be an arithmetic type."); auto rows = values[0].size(); auto cols = values.size(); Operon::Dataset::Matrix m(rows, cols); for (size_t i = 0; i < values.size(); ++i) { m.col(i) = Eigen::Map<Eigen::Matrix<T, Eigen::Dynamic, 1, Eigen::ColMajor> const>(values[i].data(), rows).template cast<Operon::Scalar>(); } return Operon::Dataset(std::move(m)); } Operon::Dataset MakeDataset(py::buffer buf) { auto info = buf.request(); if (info.ndim != 2) { throw std::runtime_error("The buffer must have two dimensions.\n"); } if (info.format == py::format_descriptor<Operon::Scalar>::format()) { auto ref = buf.template cast<Eigen::Ref<Operon::Dataset::Matrix const>>(); return Operon::Dataset(ref); } else { fmt::print(stderr, "operon warning: array does not satisfy contiguity or storage-order requirements. data will be copied.\n"); auto m = buf.template cast<Operon::Dataset::Matrix>(); return Operon::Dataset(std::move(m)); } } void init_dataset(py::module_ &m) { // dataset py::class_<Operon::Dataset>(m, "Dataset") .def(py::init<std::string const&, bool>(), py::arg("filename"), py::arg("has_header")) .def(py::init<Operon::Dataset const&>()) .def(py::init<std::vector<Operon::Variable> const&, const std::vector<std::vector<Operon::Scalar>>&>()) .def(py::init([](py::array_t<float> array){ return MakeDataset(array); }), py::arg("data").noconvert()) .def(py::init([](py::array_t<double> array){ return MakeDataset(array); }), py::arg("data").noconvert()) .def(py::init([](std::vector<std::vector<float>> const& values) { return MakeDataset(values); }), py::arg("data").noconvert()) .def(py::init([](std::vector<std::vector<double>> const& values) { return MakeDataset(values); }), py::arg("data").noconvert()) .def(py::init([](py::buffer buf) { return MakeDataset(buf); }), py::arg("data").noconvert()) .def_property_readonly("Rows", &Operon::Dataset::Rows) .def_property_readonly("Cols", &Operon::Dataset::Cols) .def_property_readonly("Values", &Operon::Dataset::Values) .def_property("VariableNames", &Operon::Dataset::VariableNames, &Operon::Dataset::SetVariableNames) .def("GetValues", [](Operon::Dataset const& self, std::string const& name) { return MakeView(self.GetValues(name)); }) .def("GetValues", [](Operon::Dataset const& self, Operon::Hash hash) { return MakeView(self.GetValues(hash)); }) .def("GetValues", [](Operon::Dataset const& self, int index) { return MakeView(self.GetValues(index)); }) .def("GetVariable", py::overload_cast<const std::string&>(&Operon::Dataset::GetVariable, py::const_)) .def("GetVariable", py::overload_cast<Operon::Hash>(&Operon::Dataset::GetVariable, py::const_)) .def_property_readonly("Variables", [](Operon::Dataset const& self) { auto vars = self.Variables(); return std::vector<Operon::Variable>(vars.begin(), vars.end()); }) .def("Shuffle", &Operon::Dataset::Shuffle) .def("Normalize", &Operon::Dataset::Normalize) .def("Standardize", &Operon::Dataset::Standardize) ; }
44.872549
146
0.644964
[ "vector" ]
4fb6ad1087cfaebf5dbb2d84f8b655de22647d15
1,996
cpp
C++
LeetCodeCPP/1208. Get Equal Substrings Within Budget/main.cpp
18600130137/leetcode
fd2dc72c0b85da50269732f0fcf91326c4787d3a
[ "Apache-2.0" ]
1
2019-03-29T03:33:56.000Z
2019-03-29T03:33:56.000Z
LeetCodeCPP/1208. Get Equal Substrings Within Budget/main.cpp
18600130137/leetcode
fd2dc72c0b85da50269732f0fcf91326c4787d3a
[ "Apache-2.0" ]
null
null
null
LeetCodeCPP/1208. Get Equal Substrings Within Budget/main.cpp
18600130137/leetcode
fd2dc72c0b85da50269732f0fcf91326c4787d3a
[ "Apache-2.0" ]
null
null
null
// // main.cpp // 1208. Get Equal Substrings Within Budget // // Created by admin on 2019/10/10. // Copyright © 2019年 liu. All rights reserved. // #include <iostream> #include <vector> using namespace std; class Solution { private: int find(vector<int> helper2,int i,int l,int r,int maxCost){ while(l<r){ int mid=l+(r-l)/2; if(helper2[i]-helper2[mid]<=maxCost){ r=mid; }else if(helper2[i]-helper2[mid]>maxCost){ l=mid+1; } } return i-l; } public: int equalSubstring(string s, string t,int maxCost) { int m=s.size(); if(m==0){ return 0; } vector<int> helper1(m,0); for(int i=0;i<m;i++){ helper1[i]=abs(s[i]-t[i]); } vector<int> helper2(m+1,0); for(int i=1;i<m+1;i++){ helper2[i]=helper2[i-1]+helper1[i-1]; } int ret=0; for(int i=m;i>=1;i--){ if(helper2[i]-helper2[i-1]<=maxCost){ int local=find(helper2,i,0,i-1,maxCost); ret=max(ret,local); } } return ret; } int equalSubstring1(string s, string t,int maxCost) { int m=s.size(); if(m==0){ return 0; } vector<int> helper1(m,0); for(int i=0;i<m;i++){ helper1[i]=abs(s[i]-t[i]); } int i=0,j=0,ret=0,acc=0; while(i<m){ while(j<m && acc+helper1[j]<=maxCost){ acc+=helper1[j]; j++; } ret=max(ret,j-i); acc-=helper1[i]; i++; } return ret; }}; int main(int argc, const char * argv[]) { string s = "abcd", t = "bcdf"; int maxCost = 3; Solution so=Solution(); int ret=so.equalSubstring(s, t, maxCost); cout<<"The ret is:"<<ret<<endl; return 0; }
23.209302
65
0.446894
[ "vector" ]
4fb7bc660cf7792085e8a3d7e7c56c998d73f08e
23,475
cpp
C++
modules/dnn/test/test_darknet_importer.cpp
Williamzww/opencv
7f453ade7396cbf63d381e343e9f671d01ba7d8a
[ "BSD-3-Clause" ]
1
2020-11-16T16:58:56.000Z
2020-11-16T16:58:56.000Z
modules/dnn/test/test_darknet_importer.cpp
Williamzww/opencv
7f453ade7396cbf63d381e343e9f671d01ba7d8a
[ "BSD-3-Clause" ]
1
2020-11-05T21:16:10.000Z
2020-11-05T21:16:10.000Z
modules/dnn/test/test_darknet_importer.cpp
Williamzww/opencv
7f453ade7396cbf63d381e343e9f671d01ba7d8a
[ "BSD-3-Clause" ]
1
2020-06-12T03:25:44.000Z
2020-06-12T03:25:44.000Z
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // (3-clause BSD License) // // Copyright (C) 2017, Intel Corporation, all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * 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 names of the copyright holders nor the names of the 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 copyright holders or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "test_precomp.hpp" #include "npy_blob.hpp" #include <opencv2/dnn/shape_utils.hpp> namespace opencv_test { namespace { template<typename TString> static std::string _tf(TString filename) { return (getOpenCVExtraDir() + "/dnn/") + filename; } TEST(Test_Darknet, read_tiny_yolo_voc) { Net net = readNetFromDarknet(_tf("tiny-yolo-voc.cfg")); ASSERT_FALSE(net.empty()); } TEST(Test_Darknet, read_yolo_voc) { Net net = readNetFromDarknet(_tf("yolo-voc.cfg")); ASSERT_FALSE(net.empty()); } TEST(Test_Darknet, read_yolo_voc_stream) { applyTestTag(CV_TEST_TAG_MEMORY_1GB); Mat ref; Mat sample = imread(_tf("dog416.png")); Mat inp = blobFromImage(sample, 1.0/255, Size(416, 416), Scalar(), true, false); const std::string cfgFile = findDataFile("dnn/yolo-voc.cfg"); const std::string weightsFile = findDataFile("dnn/yolo-voc.weights", false); // Import by paths. { Net net = readNetFromDarknet(cfgFile, weightsFile); net.setInput(inp); net.setPreferableBackend(DNN_BACKEND_OPENCV); ref = net.forward(); } // Import from bytes array. { std::vector<char> cfg, weights; readFileContent(cfgFile, cfg); readFileContent(weightsFile, weights); Net net = readNetFromDarknet(cfg.data(), cfg.size(), weights.data(), weights.size()); net.setInput(inp); net.setPreferableBackend(DNN_BACKEND_OPENCV); Mat out = net.forward(); normAssert(ref, out); } } class Test_Darknet_layers : public DNNTestLayer { public: void testDarknetLayer(const std::string& name, bool hasWeights = false, bool testBatchProcessing = true) { SCOPED_TRACE(name); Mat inp = blobFromNPY(findDataFile("dnn/darknet/" + name + "_in.npy")); Mat ref = blobFromNPY(findDataFile("dnn/darknet/" + name + "_out.npy")); std::string cfg = findDataFile("dnn/darknet/" + name + ".cfg"); std::string model = ""; if (hasWeights) model = findDataFile("dnn/darknet/" + name + ".weights"); checkBackend(&inp, &ref); Net net = readNet(cfg, model); net.setPreferableBackend(backend); net.setPreferableTarget(target); net.setInput(inp); Mat out = net.forward(); normAssert(out, ref, "", default_l1, default_lInf); if (inp.size[0] == 1 && testBatchProcessing) // test handling of batch size { SCOPED_TRACE("batch size 2"); #if defined(INF_ENGINE_RELEASE) if (target == DNN_TARGET_MYRIAD && name == "shortcut") applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD); #endif std::vector<int> sz2 = shape(inp); sz2[0] = 2; Net net2 = readNet(cfg, model); net2.setPreferableBackend(backend); net2.setPreferableTarget(target); Range ranges0[4] = { Range(0, 1), Range::all(), Range::all(), Range::all() }; Range ranges1[4] = { Range(1, 2), Range::all(), Range::all(), Range::all() }; Mat inp2(sz2, inp.type(), Scalar::all(0)); inp.copyTo(inp2(ranges0)); inp.copyTo(inp2(ranges1)); net2.setInput(inp2); Mat out2 = net2.forward(); EXPECT_EQ(0, cv::norm(out2(ranges0), out2(ranges1), NORM_INF)) << "Batch result is not equal: " << name; Mat ref2 = ref; if (ref.dims == 2 && out2.dims == 3) { int ref_3d_sizes[3] = {1, ref.rows, ref.cols}; ref2 = Mat(3, ref_3d_sizes, ref.type(), (void*)ref.data); } /*else if (ref.dims == 3 && out2.dims == 4) { int ref_4d_sizes[4] = {1, ref.size[0], ref.size[1], ref.size[2]}; ref2 = Mat(4, ref_4d_sizes, ref.type(), (void*)ref.data); }*/ ASSERT_EQ(out2.dims, ref2.dims) << ref.dims; normAssert(out2(ranges0), ref2, "", default_l1, default_lInf); normAssert(out2(ranges1), ref2, "", default_l1, default_lInf); } } }; class Test_Darknet_nets : public DNNTestLayer { public: // Test object detection network from Darknet framework. void testDarknetModel(const std::string& cfg, const std::string& weights, const std::vector<std::vector<int> >& refClassIds, const std::vector<std::vector<float> >& refConfidences, const std::vector<std::vector<Rect2d> >& refBoxes, double scoreDiff, double iouDiff, float confThreshold = 0.24, float nmsThreshold = 0.4) { checkBackend(); Mat img1 = imread(_tf("dog416.png")); Mat img2 = imread(_tf("street.png")); std::vector<Mat> samples(2); samples[0] = img1; samples[1] = img2; // determine test type, whether batch or single img int batch_size = refClassIds.size(); CV_Assert(batch_size == 1 || batch_size == 2); samples.resize(batch_size); Mat inp = blobFromImages(samples, 1.0/255, Size(416, 416), Scalar(), true, false); Net net = readNet(findDataFile("dnn/" + cfg), findDataFile("dnn/" + weights, false)); net.setPreferableBackend(backend); net.setPreferableTarget(target); net.setInput(inp); std::vector<Mat> outs; net.forward(outs, net.getUnconnectedOutLayersNames()); for (int b = 0; b < batch_size; ++b) { std::vector<int> classIds; std::vector<float> confidences; std::vector<Rect2d> boxes; for (int i = 0; i < outs.size(); ++i) { Mat out; if (batch_size > 1){ // get the sample slice from 3D matrix (batch, box, classes+5) Range ranges[3] = {Range(b, b+1), Range::all(), Range::all()}; out = outs[i](ranges).reshape(1, outs[i].size[1]); }else{ out = outs[i]; } for (int j = 0; j < out.rows; ++j) { Mat scores = out.row(j).colRange(5, out.cols); double confidence; Point maxLoc; minMaxLoc(scores, 0, &confidence, 0, &maxLoc); if (confidence > confThreshold) { float* detection = out.ptr<float>(j); double centerX = detection[0]; double centerY = detection[1]; double width = detection[2]; double height = detection[3]; boxes.push_back(Rect2d(centerX - 0.5 * width, centerY - 0.5 * height, width, height)); confidences.push_back(confidence); classIds.push_back(maxLoc.x); } } } // here we need NMS of boxes std::vector<int> indices; NMSBoxes(boxes, confidences, confThreshold, nmsThreshold, indices); std::vector<int> nms_classIds; std::vector<float> nms_confidences; std::vector<Rect2d> nms_boxes; for (size_t i = 0; i < indices.size(); ++i) { int idx = indices[i]; Rect2d box = boxes[idx]; float conf = confidences[idx]; int class_id = classIds[idx]; nms_boxes.push_back(box); nms_confidences.push_back(conf); nms_classIds.push_back(class_id); } normAssertDetections(refClassIds[b], refConfidences[b], refBoxes[b], nms_classIds, nms_confidences, nms_boxes, format("batch size %d, sample %d\n", batch_size, b).c_str(), confThreshold, scoreDiff, iouDiff); } } void testDarknetModel(const std::string& cfg, const std::string& weights, const std::vector<int>& refClassIds, const std::vector<float>& refConfidences, const std::vector<Rect2d>& refBoxes, double scoreDiff, double iouDiff, float confThreshold = 0.24, float nmsThreshold = 0.4) { testDarknetModel(cfg, weights, std::vector<std::vector<int> >(1, refClassIds), std::vector<std::vector<float> >(1, refConfidences), std::vector<std::vector<Rect2d> >(1, refBoxes), scoreDiff, iouDiff, confThreshold, nmsThreshold); } void testDarknetModel(const std::string& cfg, const std::string& weights, const cv::Mat& ref, double scoreDiff, double iouDiff, float confThreshold = 0.24, float nmsThreshold = 0.4) { CV_Assert(ref.cols == 7); std::vector<std::vector<int> > refClassIds; std::vector<std::vector<float> > refScores; std::vector<std::vector<Rect2d> > refBoxes; for (int i = 0; i < ref.rows; ++i) { int batchId = static_cast<int>(ref.at<float>(i, 0)); int classId = static_cast<int>(ref.at<float>(i, 1)); float score = ref.at<float>(i, 2); float left = ref.at<float>(i, 3); float top = ref.at<float>(i, 4); float right = ref.at<float>(i, 5); float bottom = ref.at<float>(i, 6); Rect2d box(left, top, right - left, bottom - top); if (batchId >= refClassIds.size()) { refClassIds.resize(batchId + 1); refScores.resize(batchId + 1); refBoxes.resize(batchId + 1); } refClassIds[batchId].push_back(classId); refScores[batchId].push_back(score); refBoxes[batchId].push_back(box); } testDarknetModel(cfg, weights, refClassIds, refScores, refBoxes, scoreDiff, iouDiff, confThreshold, nmsThreshold); } }; TEST_P(Test_Darknet_nets, YoloVoc) { applyTestTag( #if defined(OPENCV_32BIT_CONFIGURATION) && defined(HAVE_OPENCL) CV_TEST_TAG_MEMORY_2GB, #else CV_TEST_TAG_MEMORY_1GB, #endif CV_TEST_TAG_LONG ); #if defined(INF_ENGINE_RELEASE) && INF_ENGINE_VER_MAJOR_GE(2019010000) if (backend == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019 && target == DNN_TARGET_OPENCL_FP16) applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_OPENCL_FP16); #endif #if defined(INF_ENGINE_RELEASE) if ((backend == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019 || backend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH) && target == DNN_TARGET_MYRIAD && getInferenceEngineVPUType() == CV_DNN_INFERENCE_ENGINE_VPU_TYPE_MYRIAD_X) applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD_X); // need to update check function #endif // batchId, classId, confidence, left, top, right, bottom Mat ref = (Mat_<float>(6, 7) << 0, 6, 0.750469f, 0.577374f, 0.127391f, 0.902949f, 0.300809f, // a car 0, 1, 0.780879f, 0.270762f, 0.264102f, 0.732475f, 0.745412f, // a bicycle 0, 11, 0.901615f, 0.1386f, 0.338509f, 0.421337f, 0.938789f, // a dog 1, 14, 0.623813f, 0.183179f, 0.381921f, 0.247726f, 0.625847f, // a person 1, 6, 0.667770f, 0.446555f, 0.453578f, 0.499986f, 0.519167f, // a car 1, 6, 0.844947f, 0.637058f, 0.460398f, 0.828508f, 0.66427f); // a car double nmsThreshold = (target == DNN_TARGET_MYRIAD) ? 0.397 : 0.4; double scoreDiff = 8e-5, iouDiff = 3e-4; if (target == DNN_TARGET_OPENCL_FP16 || target == DNN_TARGET_MYRIAD) { scoreDiff = 1e-2; iouDiff = 0.018; } else if (target == DNN_TARGET_CUDA_FP16) { scoreDiff = 0.03; iouDiff = 0.018; } std::string config_file = "yolo-voc.cfg"; std::string weights_file = "yolo-voc.weights"; { SCOPED_TRACE("batch size 1"); testDarknetModel(config_file, weights_file, ref.rowRange(0, 3), scoreDiff, iouDiff); } { SCOPED_TRACE("batch size 2"); testDarknetModel(config_file, weights_file, ref, scoreDiff, iouDiff, 0.24, nmsThreshold); } } TEST_P(Test_Darknet_nets, TinyYoloVoc) { applyTestTag(CV_TEST_TAG_MEMORY_512MB); #if defined(INF_ENGINE_RELEASE) if ((backend == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019 || backend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH) && target == DNN_TARGET_MYRIAD && getInferenceEngineVPUType() == CV_DNN_INFERENCE_ENGINE_VPU_TYPE_MYRIAD_X) applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD_X); // need to update check function #endif // batchId, classId, confidence, left, top, right, bottom Mat ref = (Mat_<float>(4, 7) << 0, 6, 0.761967f, 0.579042f, 0.159161f, 0.894482f, 0.31994f, // a car 0, 11, 0.780595f, 0.129696f, 0.386467f, 0.445275f, 0.920994f, // a dog 1, 6, 0.651450f, 0.460526f, 0.458019f, 0.522527f, 0.5341f, // a car 1, 6, 0.928758f, 0.651024f, 0.463539f, 0.823784f, 0.654998f); // a car double scoreDiff = 8e-5, iouDiff = 3e-4; if (target == DNN_TARGET_OPENCL_FP16 || target == DNN_TARGET_MYRIAD) { scoreDiff = 8e-3; iouDiff = 0.018; } else if(target == DNN_TARGET_CUDA_FP16) { scoreDiff = 0.008; iouDiff = 0.02; } std::string config_file = "tiny-yolo-voc.cfg"; std::string weights_file = "tiny-yolo-voc.weights"; { SCOPED_TRACE("batch size 1"); testDarknetModel(config_file, weights_file, ref.rowRange(0, 2), scoreDiff, iouDiff); } { SCOPED_TRACE("batch size 2"); testDarknetModel(config_file, weights_file, ref, scoreDiff, iouDiff); } } #ifdef HAVE_INF_ENGINE static const std::chrono::milliseconds async_timeout(10000); typedef testing::TestWithParam<tuple<std::string, tuple<Backend, Target> > > Test_Darknet_nets_async; TEST_P(Test_Darknet_nets_async, Accuracy) { Backend backendId = get<0>(get<1>(GetParam())); Target targetId = get<1>(get<1>(GetParam())); if (INF_ENGINE_VER_MAJOR_LT(2019020000) && backendId == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019) applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_NN_BUILDER); applyTestTag(CV_TEST_TAG_MEMORY_512MB); if (backendId == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH) applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_NGRAPH); std::string prefix = get<0>(GetParam()); if (backendId != DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019 && backendId != DNN_BACKEND_INFERENCE_ENGINE_NGRAPH) throw SkipTestException("No support for async forward"); const int numInputs = 2; std::vector<Mat> inputs(numInputs); int blobSize[] = {1, 3, 416, 416}; for (int i = 0; i < numInputs; ++i) { inputs[i].create(4, &blobSize[0], CV_32F); randu(inputs[i], 0, 1); } Net netSync = readNet(findDataFile("dnn/" + prefix + ".cfg"), findDataFile("dnn/" + prefix + ".weights", false)); netSync.setPreferableBackend(backendId); netSync.setPreferableTarget(targetId); // Run synchronously. std::vector<Mat> refs(numInputs); for (int i = 0; i < numInputs; ++i) { netSync.setInput(inputs[i]); refs[i] = netSync.forward().clone(); } Net netAsync = readNet(findDataFile("dnn/" + prefix + ".cfg"), findDataFile("dnn/" + prefix + ".weights", false)); netAsync.setPreferableBackend(backendId); netAsync.setPreferableTarget(targetId); // Run asynchronously. To make test more robust, process inputs in the reversed order. for (int i = numInputs - 1; i >= 0; --i) { netAsync.setInput(inputs[i]); AsyncArray out = netAsync.forwardAsync(); ASSERT_TRUE(out.valid()); Mat result; EXPECT_TRUE(out.get(result, async_timeout)); normAssert(refs[i], result, format("Index: %d", i).c_str(), 0, 0); } } INSTANTIATE_TEST_CASE_P(/**/, Test_Darknet_nets_async, Combine( Values("yolo-voc", "tiny-yolo-voc", "yolov3"), dnnBackendsAndTargets() )); #endif TEST_P(Test_Darknet_nets, YOLOv3) { applyTestTag(CV_TEST_TAG_LONG, (target == DNN_TARGET_CPU ? CV_TEST_TAG_MEMORY_1GB : CV_TEST_TAG_MEMORY_2GB)); if (backend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH && target == DNN_TARGET_MYRIAD) applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD, CV_TEST_TAG_DNN_SKIP_IE_NGRAPH); // batchId, classId, confidence, left, top, right, bottom Mat ref = (Mat_<float>(9, 7) << 0, 7, 0.952983f, 0.614622f, 0.150257f, 0.901369f, 0.289251f, // a truck 0, 1, 0.987908f, 0.150913f, 0.221933f, 0.742255f, 0.74626f, // a bicycle 0, 16, 0.998836f, 0.160024f, 0.389964f, 0.417885f, 0.943716f, // a dog (COCO) 1, 9, 0.384801f, 0.659824f, 0.372389f, 0.673926f, 0.429412f, // a traffic light 1, 9, 0.733283f, 0.376029f, 0.315694f, 0.401776f, 0.395165f, // a traffic light 1, 9, 0.785352f, 0.665503f, 0.373543f, 0.688893f, 0.439245f, // a traffic light 1, 0, 0.980052f, 0.195856f, 0.378454f, 0.258626f, 0.629258f, // a person 1, 2, 0.989633f, 0.450719f, 0.463353f, 0.496305f, 0.522258f, // a car 1, 2, 0.997412f, 0.647584f, 0.459939f, 0.821038f, 0.663947f); // a car double scoreDiff = 8e-5, iouDiff = 3e-4; if (target == DNN_TARGET_OPENCL_FP16 || target == DNN_TARGET_MYRIAD) { scoreDiff = 0.006; iouDiff = 0.042; } else if (target == DNN_TARGET_CUDA_FP16) { scoreDiff = 0.04; iouDiff = 0.03; } std::string config_file = "yolov3.cfg"; std::string weights_file = "yolov3.weights"; #if defined(INF_ENGINE_RELEASE) if ((backend == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019 || backend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH) && target == DNN_TARGET_MYRIAD && getInferenceEngineVPUType() == CV_DNN_INFERENCE_ENGINE_VPU_TYPE_MYRIAD_X) { scoreDiff = 0.04; iouDiff = 0.2; } #endif { SCOPED_TRACE("batch size 1"); testDarknetModel(config_file, weights_file, ref.rowRange(0, 3), scoreDiff, iouDiff); } #if defined(INF_ENGINE_RELEASE) if (backend == DNN_BACKEND_INFERENCE_ENGINE_NN_BUILDER_2019) { if (target == DNN_TARGET_OPENCL) applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_OPENCL, CV_TEST_TAG_DNN_SKIP_IE_VERSION); else if (target == DNN_TARGET_OPENCL_FP16 && INF_ENGINE_VER_MAJOR_LE(202010000)) applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_OPENCL_FP16, CV_TEST_TAG_DNN_SKIP_IE_VERSION); else if (target == DNN_TARGET_MYRIAD && getInferenceEngineVPUType() == CV_DNN_INFERENCE_ENGINE_VPU_TYPE_MYRIAD_X) applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD_X); } #endif { SCOPED_TRACE("batch size 2"); testDarknetModel(config_file, weights_file, ref, scoreDiff, iouDiff); } } INSTANTIATE_TEST_CASE_P(/**/, Test_Darknet_nets, dnnBackendsAndTargets()); TEST_P(Test_Darknet_layers, shortcut) { testDarknetLayer("shortcut"); testDarknetLayer("shortcut_leaky"); testDarknetLayer("shortcut_unequal"); testDarknetLayer("shortcut_unequal_2"); } TEST_P(Test_Darknet_layers, upsample) { testDarknetLayer("upsample"); } TEST_P(Test_Darknet_layers, mish) { testDarknetLayer("mish", true); } TEST_P(Test_Darknet_layers, avgpool_softmax) { testDarknetLayer("avgpool_softmax"); } TEST_P(Test_Darknet_layers, region) { #if defined(INF_ENGINE_RELEASE) if (backend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH && INF_ENGINE_VER_MAJOR_GE(2020020000)) applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_NGRAPH, CV_TEST_TAG_DNN_SKIP_IE_VERSION); #endif testDarknetLayer("region"); } TEST_P(Test_Darknet_layers, reorg) { testDarknetLayer("reorg"); } TEST_P(Test_Darknet_layers, maxpool) { #if defined(INF_ENGINE_RELEASE) && INF_ENGINE_VER_MAJOR_GE(2020020000) if (backend == DNN_BACKEND_INFERENCE_ENGINE_NGRAPH && target == DNN_TARGET_MYRIAD) applyTestTag(CV_TEST_TAG_DNN_SKIP_IE_MYRIAD, CV_TEST_TAG_DNN_SKIP_IE_NGRAPH, CV_TEST_TAG_DNN_SKIP_IE_VERSION); #endif testDarknetLayer("maxpool"); } TEST_P(Test_Darknet_layers, convolutional) { if (target == DNN_TARGET_MYRIAD) { default_l1 = 0.01f; } testDarknetLayer("convolutional", true); } TEST_P(Test_Darknet_layers, scale_channels) { bool testBatches = backend == DNN_BACKEND_CUDA; testDarknetLayer("scale_channels", false, testBatches); } TEST_P(Test_Darknet_layers, connected) { if (backend == DNN_BACKEND_OPENCV && target == DNN_TARGET_OPENCL_FP16) applyTestTag(CV_TEST_TAG_DNN_SKIP_OPENCL_FP16); testDarknetLayer("connected", true); } INSTANTIATE_TEST_CASE_P(/**/, Test_Darknet_layers, dnnBackendsAndTargets()); }} // namespace
38.801653
153
0.609883
[ "object", "shape", "vector", "model", "3d" ]
4fbc788a83abc1ac5743e69f2475d08b1dd69df9
2,131
hpp
C++
core/src/impl/Cabana_TypeTraits.hpp
suchyta1/Cabana
126d67ce76645b90042197174fcc4cf494e6a56d
[ "Unlicense" ]
null
null
null
core/src/impl/Cabana_TypeTraits.hpp
suchyta1/Cabana
126d67ce76645b90042197174fcc4cf494e6a56d
[ "Unlicense" ]
null
null
null
core/src/impl/Cabana_TypeTraits.hpp
suchyta1/Cabana
126d67ce76645b90042197174fcc4cf494e6a56d
[ "Unlicense" ]
null
null
null
/**************************************************************************** * Copyright (c) 2018-2019 by the Cabana authors * * All rights reserved. * * * * This file is part of the Cabana library. Cabana is distributed under a * * BSD 3-clause license. For the licensing terms see the LICENSE file in * * the top-level directory. * * * * SPDX-License-Identifier: BSD-3-Clause * ****************************************************************************/ #ifndef CABANA_TYPETRAITS_HPP #define CABANA_TYPETRAITS_HPP #include <Kokkos_Core.hpp> #include <type_traits> namespace Cabana { namespace Impl { //---------------------------------------------------------------------------// // Checks if an integer is a power of two. N must be greater than 0. template <int N> struct IsPowerOfTwo { static_assert( N > 0, "Vector length must be greather than 0" ); static constexpr bool value = ( ( N & ( N - 1 ) ) == 0 ); }; //---------------------------------------------------------------------------// // Calculate the base-2 logarithm of an integer which must be a power of 2 and // greater than 0. template <int N> struct LogBase2 { static_assert( IsPowerOfTwo<N>::value, "Vector length must be a power of two" ); static constexpr int value = 1 + LogBase2<( N >> 1U )>::value; }; template <> struct LogBase2<1> { static constexpr int value = 0; }; //---------------------------------------------------------------------------// // Check that the provided vector length is valid. template <int N> struct IsVectorLengthValid { static constexpr bool value = ( IsPowerOfTwo<N>::value && N > 0 ); }; //---------------------------------------------------------------------------// } // end namespace Impl } // end namespace Cabana #endif // CABANA_TYPETRAITS_HPP
33.825397
79
0.429845
[ "vector" ]
4fc1269e8a079b13aa11b2266ba0c5be71a42646
37,918
cc
C++
chrome/browser/extensions/extension_bindings_apitest.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
chrome/browser/extensions/extension_bindings_apitest.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/browser/extensions/extension_bindings_apitest.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Contains holistic tests of the bindings infrastructure #include "base/run_loop.h" #include "build/build_config.h" #include "chrome/browser/extensions/api/permissions/permissions_api.h" #include "chrome/browser/extensions/extension_apitest.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/test/base/ui_test_utils.h" #include "components/embedder_support/switches.h" #include "components/sessions/content/session_tab_helper.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/common/content_features.h" #include "content/public/test/browser_test.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_navigation_observer.h" #include "extensions/browser/event_router.h" #include "extensions/browser/extension_host.h" #include "extensions/browser/process_manager.h" #include "extensions/test/extension_test_message_listener.h" #include "extensions/test/result_catcher.h" #include "extensions/test/test_extension_dir.h" #include "net/dns/mock_host_resolver.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "third_party/blink/public/common/input/web_mouse_event.h" #include "third_party/blink/public/common/switches.h" namespace extensions { namespace { void MouseDownInWebContents(content::WebContents* web_contents) { blink::WebMouseEvent mouse_event( blink::WebInputEvent::Type::kMouseDown, blink::WebInputEvent::kNoModifiers, blink::WebInputEvent::GetStaticTimeStampForTests()); mouse_event.button = blink::WebMouseEvent::Button::kLeft; mouse_event.SetPositionInWidget(10, 10); mouse_event.click_count = 1; web_contents->GetMainFrame() ->GetRenderViewHost() ->GetWidget() ->ForwardMouseEvent(mouse_event); } void MouseUpInWebContents(content::WebContents* web_contents) { blink::WebMouseEvent mouse_event( blink::WebInputEvent::Type::kMouseUp, blink::WebInputEvent::kNoModifiers, blink::WebInputEvent::GetStaticTimeStampForTests()); mouse_event.button = blink::WebMouseEvent::Button::kLeft; mouse_event.SetPositionInWidget(10, 10); mouse_event.click_count = 1; web_contents->GetMainFrame() ->GetRenderViewHost() ->GetWidget() ->ForwardMouseEvent(mouse_event); } class ExtensionBindingsApiTest : public ExtensionApiTest { public: ExtensionBindingsApiTest() {} ~ExtensionBindingsApiTest() override {} void SetUpOnMainThread() override { ExtensionApiTest::SetUpOnMainThread(); host_resolver()->AddRule("*", "127.0.0.1"); ASSERT_TRUE(StartEmbeddedTestServer()); } void SetUpCommandLine(base::CommandLine* command_line) override { ExtensionApiTest::SetUpCommandLine(command_line); // Some bots are flaky due to slower loading interacting with // deferred commits. command_line->AppendSwitch(blink::switches::kAllowPreCommitInput); } private: DISALLOW_COPY_AND_ASSIGN(ExtensionBindingsApiTest); }; IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, UnavailableBindingsNeverRegistered) { // Test will request the 'storage' permission. PermissionsRequestFunction::SetIgnoreUserGestureForTests(true); ASSERT_TRUE(RunExtensionTest( "bindings/unavailable_bindings_never_registered")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, ExceptionInHandlerShouldNotCrash) { ASSERT_TRUE(RunExtensionSubtest( "bindings/exception_in_handler_should_not_crash", "page.html")) << message_; } // Tests that an error raised during an async function still fires // the callback, but sets chrome.runtime.lastError. IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, LastError) { ExtensionTestMessageListener ready_listener("ready", /*will_reply=*/false); ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("bindings").AppendASCII("last_error"))); ASSERT_TRUE(ready_listener.WaitUntilSatisfied()); // Get the ExtensionHost that is hosting our background page. extensions::ProcessManager* manager = extensions::ProcessManager::Get(browser()->profile()); extensions::ExtensionHost* host = FindHostWithPath(manager, "/bg.html", 1); ASSERT_TRUE(host); bool result = false; ASSERT_TRUE(content::ExecuteScriptAndExtractBool(host->host_contents(), "testLastError()", &result)); EXPECT_TRUE(result); } // Regression test that we don't delete our own bindings with about:blank // iframes. IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, AboutBlankIframe) { ResultCatcher catcher; ExtensionTestMessageListener listener("load", true); ASSERT_TRUE(LoadExtension(test_data_dir_.AppendASCII("bindings") .AppendASCII("about_blank_iframe"))); ASSERT_TRUE(listener.WaitUntilSatisfied()); const Extension* extension = LoadExtension( test_data_dir_.AppendASCII("bindings") .AppendASCII("internal_apis_not_on_chrome_object")); ASSERT_TRUE(extension); listener.Reply(extension->id()); ASSERT_TRUE(catcher.GetNextResult()) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, InternalAPIsNotOnChromeObject) { ASSERT_TRUE(RunExtensionSubtest( "bindings/internal_apis_not_on_chrome_object", "page.html")) << message_; } // Tests that we don't override events when bindings are re-injected. // Regression test for http://crbug.com/269149. // Regression test for http://crbug.com/436593. // Flaky http://crbug.com/733064. IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, DISABLED_EventOverriding) { ASSERT_TRUE(RunExtensionTest("bindings/event_overriding")) << message_; // The extension test removes a window and, during window removal, sends the // success message. Make sure we flush all pending tasks. base::RunLoop().RunUntilIdle(); } // Tests the effectiveness of the 'nocompile' feature file property. // Regression test for http://crbug.com/356133. IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, Nocompile) { ASSERT_TRUE(RunExtensionSubtest("bindings/nocompile", "page.html")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, ApiEnums) { ASSERT_TRUE(RunExtensionTest("bindings/api_enums")) << message_; } // Regression test for http://crbug.com/504011 - proper access checks on // getModuleSystem(). IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, ModuleSystem) { ASSERT_TRUE(RunExtensionTest("bindings/module_system")) << message_; } IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, NoExportOverriding) { // We need to create runtime bindings in the web page. An extension that's // externally connectable will do that for us. ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("bindings") .AppendASCII("externally_connectable_everywhere"))); ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL( "/extensions/api_test/bindings/override_exports.html")); // See chrome/test/data/extensions/api_test/bindings/override_exports.html. std::string result; EXPECT_TRUE(content::ExecuteScriptAndExtractString( browser()->tab_strip_model()->GetActiveWebContents(), "window.domAutomationController.send(" "document.getElementById('status').textContent.trim());", &result)); EXPECT_EQ("success", result); } IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, NoGinDefineOverriding) { // We need to create runtime bindings in the web page. An extension that's // externally connectable will do that for us. ASSERT_TRUE(LoadExtension( test_data_dir_.AppendASCII("bindings") .AppendASCII("externally_connectable_everywhere"))); ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL( "/extensions/api_test/bindings/override_gin_define.html")); ASSERT_FALSE( browser()->tab_strip_model()->GetActiveWebContents()->IsCrashed()); // See chrome/test/data/extensions/api_test/bindings/override_gin_define.html. std::string result; EXPECT_TRUE(content::ExecuteScriptAndExtractString( browser()->tab_strip_model()->GetActiveWebContents(), "window.domAutomationController.send(" "document.getElementById('status').textContent.trim());", &result)); EXPECT_EQ("success", result); } IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, HandlerFunctionTypeChecking) { ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL( "/extensions/api_test/bindings/handler_function_type_checking.html")); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); EXPECT_FALSE(web_contents->IsCrashed()); // See handler_function_type_checking.html. std::string result; EXPECT_TRUE(content::ExecuteScriptAndExtractString( web_contents, "window.domAutomationController.send(" "document.getElementById('status').textContent.trim());", &result)); EXPECT_EQ("success", result); } IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, MoreNativeFunctionInterceptionTests) { // We need to create runtime bindings in the web page. An extension that's // externally connectable will do that for us. ASSERT_TRUE( LoadExtension(test_data_dir_.AppendASCII("bindings") .AppendASCII("externally_connectable_everywhere"))); ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL( "/extensions/api_test/bindings/function_interceptions.html")); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); EXPECT_FALSE(web_contents->IsCrashed()); // See function_interceptions.html. std::string result; EXPECT_TRUE(content::ExecuteScriptAndExtractString( web_contents, "window.domAutomationController.send(window.testStatus);", &result)); EXPECT_EQ("success", result); } class FramesExtensionBindingsApiTest : public ExtensionBindingsApiTest { public: void SetUpCommandLine(base::CommandLine* command_line) override { ExtensionBindingsApiTest::SetUpCommandLine(command_line); command_line->AppendSwitch(embedder_support::kDisablePopupBlocking); } }; // This tests that web pages with iframes or child windows pointing at // chrome-extenison:// urls, both web_accessible and nonexistent pages, don't // get improper extensions bindings injected while they briefly still point at // about:blank and are still scriptable by their parent. // // The general idea is to load up 2 extensions, one which listens for external // messages ("receiver") and one which we'll try first faking messages from in // the web page's iframe, as well as actually send a message from later // ("sender"). IN_PROC_BROWSER_TEST_F(FramesExtensionBindingsApiTest, FramesBeforeNavigation) { // Load the sender and receiver extensions, and make sure they are ready. ExtensionTestMessageListener sender_ready("sender_ready", true); const Extension* sender = LoadExtension( test_data_dir_.AppendASCII("bindings").AppendASCII("message_sender")); ASSERT_NE(nullptr, sender); ASSERT_TRUE(sender_ready.WaitUntilSatisfied()); ExtensionTestMessageListener receiver_ready("receiver_ready", false); const Extension* receiver = LoadExtension(test_data_dir_.AppendASCII("bindings") .AppendASCII("external_message_listener")); ASSERT_NE(nullptr, receiver); ASSERT_TRUE(receiver_ready.WaitUntilSatisfied()); // Load the web page which tries to impersonate the sender extension via // scripting iframes/child windows before they finish navigating to pages // within the sender extension. ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL( "/extensions/api_test/bindings/frames_before_navigation.html")); bool page_success = false; ASSERT_TRUE(content::ExecuteScriptAndExtractBool( browser()->tab_strip_model()->GetWebContentsAt(0), "getResult()", &page_success)); EXPECT_TRUE(page_success); // Reply to |sender|, causing it to send a message over to |receiver|, and // then ask |receiver| for the total message count. It should be 1 since // |receiver| should not have received any impersonated messages. sender_ready.Reply(receiver->id()); int message_count = 0; ASSERT_TRUE(content::ExecuteScriptAndExtractInt( ProcessManager::Get(profile()) ->GetBackgroundHostForExtension(receiver->id()) ->host_contents(), "getMessageCountAfterReceivingRealSenderMessage()", &message_count)); EXPECT_EQ(1, message_count); } IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, TestFreezingChrome) { ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL( "/extensions/api_test/bindings/freeze.html")); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_FALSE(web_contents->IsCrashed()); } // Tests interaction with event filter parsing. IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, TestEventFilterParsing) { ExtensionTestMessageListener listener("ready", false); ASSERT_TRUE( LoadExtension(test_data_dir_.AppendASCII("bindings/event_filter"))); ASSERT_TRUE(listener.WaitUntilSatisfied()); ResultCatcher catcher; ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL("example.com", "/title1.html")); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } // crbug.com/733337 IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, ValidationInterception) { // We need to create runtime bindings in the web page. An extension that's // externally connectable will do that for us. ASSERT_TRUE( LoadExtension(test_data_dir_.AppendASCII("bindings") .AppendASCII("externally_connectable_everywhere"))); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL( "/extensions/api_test/bindings/validation_interception.html")); EXPECT_TRUE(content::WaitForLoadStop(web_contents)); ASSERT_FALSE(web_contents->IsCrashed()); bool caught = false; ASSERT_TRUE(content::ExecuteScriptAndExtractBool( web_contents, "domAutomationController.send(caught)", &caught)); EXPECT_TRUE(caught); } IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, UncaughtExceptionLogging) { ASSERT_TRUE(RunExtensionTest("bindings/uncaught_exception_logging")) << message_; } // Verify that when a web frame embeds an extension subframe, and that subframe // is the only active portion of the extension, the subframe gets proper JS // bindings. See https://crbug.com/760341. IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, ExtensionSubframeGetsBindings) { // Load an extension that does not have a background page or popup, so it // won't be activated just yet. const extensions::Extension* extension = LoadExtension(test_data_dir_.AppendASCII("bindings") .AppendASCII("extension_subframe_gets_bindings")); ASSERT_TRUE(extension); // Navigate current tab to a web URL with a subframe. content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); ui_test_utils::NavigateToURL(browser(), embedded_test_server()->GetURL("/iframe.html")); // Navigate the subframe to the extension URL, which should activate the // extension. GURL extension_url(extension->GetResourceURL("page.html")); ResultCatcher catcher; content::NavigateIframeToURL(web_contents, "test", extension_url); ASSERT_TRUE(catcher.GetNextResult()) << catcher.message(); } IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, ExtensionListenersRemoveContext) { const Extension* extension = LoadExtension( test_data_dir_.AppendASCII("bindings/listeners_destroy_context")); ASSERT_TRUE(extension); ExtensionTestMessageListener listener("ready", true); // Navigate to a web page with an iframe (the iframe is title1.html). GURL main_frame_url = embedded_test_server()->GetURL("a.com", "/iframe.html"); ui_test_utils::NavigateToURL(browser(), main_frame_url); content::WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); content::RenderFrameHost* main_frame = tab->GetMainFrame(); content::RenderFrameHost* subframe = ChildFrameAt(main_frame, 0); content::RenderFrameDeletedObserver subframe_deleted(subframe); // Wait for the extension's content script to be ready. ASSERT_TRUE(listener.WaitUntilSatisfied()); // It's actually critical to the test that these frames are in the same // process, because otherwise a crash in the iframe wouldn't be detectable // (since we rely on JS execution in the main frame to tell if the renderer // crashed - see comment below). content::RenderProcessHost* main_frame_process = main_frame->GetProcess(); EXPECT_EQ(main_frame_process, subframe->GetProcess()); ExtensionTestMessageListener failure_listener("failed", false); // Tell the extension to register listeners that will remove the iframe, and // trigger them. listener.Reply("go!"); // The frame will be deleted. subframe_deleted.WaitUntilDeleted(); // Unfortunately, we don't have a good way of checking if something crashed // after the frame was removed. WebContents::IsCrashed() seems like it should // work, but is insufficient. Instead, use JS execution as the source of // true. EXPECT_FALSE(tab->IsCrashed()); EXPECT_EQ(main_frame_url, main_frame->GetLastCommittedURL()); EXPECT_EQ(main_frame_process, main_frame->GetProcess()); bool renderer_valid = false; EXPECT_TRUE(content::ExecuteScriptAndExtractBool( main_frame, "domAutomationController.send(true);", &renderer_valid)); EXPECT_TRUE(renderer_valid); EXPECT_FALSE(failure_listener.was_satisfied()); } IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, UseAPIsAfterContextRemoval) { EXPECT_TRUE(RunExtensionTest("bindings/invalidate_context")) << message_; } // Tests that we don't crash if the extension invalidates the context in a // callback with a runtime.lastError present. Regression test for // https://crbug.com/944014. IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, InvalidateContextInCallbackWithLastError) { TestExtensionDir dir; dir.WriteManifest( R"({ "name": "Invalidate Context in onDisconnect", "version": "0.1", "manifest_version": 2, "background": {"scripts": ["background.js"]} })"); constexpr char kFrameHtml[] = R"(<html> <body></body> <script src="frame.js"></script> </html>)"; constexpr char kFrameJs[] = R"(chrome.tabs.executeScript({code: ''}, () => { // We expect a last error to be present, since we don't have access // to the tab. chrome.test.assertTrue(!!chrome.runtime.lastError); // Remove the frame from the DOM. This causes blink to remove the // associated script contexts. parent.document.body.removeChild( parent.document.body.querySelector('iframe')); });)"; constexpr char kBackgroundJs[] = R"(let frame = document.createElement('iframe'); frame.src = 'frame.html'; let observer = new MutationObserver((mutationList) => { for (let mutation of mutationList) { if (mutation.removedNodes.length == 0) continue; chrome.test.assertEq(1, mutation.removedNodes.length); chrome.test.assertEq('IFRAME', mutation.removedNodes[0].tagName); chrome.test.notifyPass(); break; } }); observer.observe(document.body, {childList: true}); document.body.appendChild(frame);)"; dir.WriteFile(FILE_PATH_LITERAL("frame.html"), kFrameHtml); dir.WriteFile(FILE_PATH_LITERAL("frame.js"), kFrameJs); dir.WriteFile(FILE_PATH_LITERAL("background.js"), kBackgroundJs); ResultCatcher catcher; const Extension* extension = LoadExtension(dir.UnpackedPath()); ASSERT_TRUE(extension); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); } // TODO(devlin): Can this be combined with // ExtensionBindingsApiTest.UseAPIsAfterContextRemoval? IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, UseAppAPIAfterFrameRemoval) { ASSERT_TRUE(RunExtensionTest("crazy_extension")); } // Tests attaching two listeners from the same extension but different pages, // then removing one, and ensuring the second is still notified. // Regression test for https://crbug.com/868763. IN_PROC_BROWSER_TEST_F( ExtensionBindingsApiTest, MultipleEventListenersFromDifferentContextsAndTheSameExtension) { // A script that listens for tab creation and populates the result in a // global variable. constexpr char kTestPageScript[] = R"( window.tabEventId = -1; function registerListener() { chrome.tabs.onCreated.addListener((tab) => { window.tabEventId = tab.id; }); } )"; TestExtensionDir test_dir; test_dir.WriteManifest(R"( { "name": "Duplicate event listeners", "manifest_version": 2, "version": "0.1" })"); test_dir.WriteFile(FILE_PATH_LITERAL("page.html"), R"(<html><script src="page.js"></script></html>)"); test_dir.WriteFile(FILE_PATH_LITERAL("page.js"), kTestPageScript); const Extension* extension = LoadExtension(test_dir.UnpackedPath()); ASSERT_TRUE(extension); // Set up: open two tabs to the same extension page, and wait for each to // load. const GURL page_url = extension->GetResourceURL("page.html"); ui_test_utils::NavigateToURLWithDisposition( browser(), page_url, WindowOpenDisposition::NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP); content::WebContents* first_tab = browser()->tab_strip_model()->GetActiveWebContents(); ui_test_utils::NavigateToURLWithDisposition( browser(), page_url, WindowOpenDisposition::NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP); content::WebContents* second_tab = browser()->tab_strip_model()->GetActiveWebContents(); // Initially, there are no listeners registered. EventRouter* event_router = EventRouter::Get(profile()); EXPECT_FALSE(event_router->ExtensionHasEventListener(extension->id(), "tabs.onCreated")); // Register both lsiteners, and verify they were added. ASSERT_TRUE(content::ExecuteScript(first_tab, "registerListener()")); ASSERT_TRUE(content::ExecuteScript(second_tab, "registerListener()")); EXPECT_TRUE(event_router->ExtensionHasEventListener(extension->id(), "tabs.onCreated")); // Close one of the extension pages. constexpr bool add_to_history = false; content::WebContentsDestroyedWatcher watcher(second_tab); chrome::CloseWebContents(browser(), second_tab, add_to_history); watcher.Wait(); // Hacky round trip to the renderer to flush IPCs. ASSERT_TRUE(content::ExecuteScript(first_tab, "")); // Since the second page is still open, the extension should still be // registered as a listener. EXPECT_TRUE(event_router->ExtensionHasEventListener(extension->id(), "tabs.onCreated")); // Open a new tab. ui_test_utils::NavigateToURLWithDisposition( browser(), GURL("chrome://newtab"), WindowOpenDisposition::NEW_FOREGROUND_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_LOAD_STOP); content::WebContents* new_tab = browser()->tab_strip_model()->GetActiveWebContents(); // The extension should have been notified about the new tab, and have // recorded the result. int result_tab_id = -1; EXPECT_TRUE(content::ExecuteScriptAndExtractInt( first_tab, "domAutomationController.send(window.tabEventId)", &result_tab_id)); EXPECT_EQ(sessions::SessionTabHelper::IdForTab(new_tab).id(), result_tab_id); } // Verifies that user gestures are carried through extension messages. IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, UserGestureFromExtensionMessageTest) { TestExtensionDir test_dir; test_dir.WriteManifest( R"({ "name": "User Gesture Content Script", "manifest_version": 2, "version": "0.1", "background": { "scripts": ["background.js"] }, "content_scripts": [{ "matches": ["*://*.example.com:*/*"], "js": ["content_script.js"], "run_at": "document_end" }] })"); test_dir.WriteFile(FILE_PATH_LITERAL("content_script.js"), R"(const button = document.getElementById('go-button'); button.addEventListener('click', () => { chrome.runtime.sendMessage('clicked'); });)"); test_dir.WriteFile(FILE_PATH_LITERAL("background.js"), R"(chrome.runtime.onMessage.addListener((message) => { chrome.test.sendMessage( 'Clicked: ' + chrome.test.isProcessingUserGesture()); });)"); const Extension* extension = LoadExtension(test_dir.UnpackedPath()); ASSERT_TRUE(extension); const GURL url = embedded_test_server()->GetURL( "example.com", "/extensions/page_with_button.html"); ui_test_utils::NavigateToURL(browser(), url); content::WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); { // Passing a message without an active user gesture shouldn't result in a // gesture being active on the receiving end. ExtensionTestMessageListener listener(false); content::EvalJsResult result = content::EvalJs(tab, "document.getElementById('go-button').click()", content::EXECUTE_SCRIPT_NO_USER_GESTURE); EXPECT_TRUE(result.value.is_none()); EXPECT_TRUE(listener.WaitUntilSatisfied()); EXPECT_EQ("Clicked: false", listener.message()); } { // If there is an active user gesture when the message is sent, we should // synthesize a user gesture on the receiving end. ExtensionTestMessageListener listener(false); content::EvalJsResult result = content::EvalJs(tab, "document.getElementById('go-button').click()"); EXPECT_TRUE(result.value.is_none()); EXPECT_TRUE(listener.WaitUntilSatisfied()); EXPECT_EQ("Clicked: true", listener.message()); } } // Verifies that user gestures from API calls are active when the callback is // triggered. IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, UserGestureInExtensionAPICallback) { TestExtensionDir test_dir; test_dir.WriteManifest( R"({ "name": "User Gesture Extension API Callback", "manifest_version": 2, "version": "0.1" })"); test_dir.WriteFile(FILE_PATH_LITERAL("page.html"), "<html></html>"); const Extension* extension = LoadExtension(test_dir.UnpackedPath()); ASSERT_TRUE(extension); const GURL extension_page = extension->GetResourceURL("page.html"); ui_test_utils::NavigateToURL(browser(), extension_page); content::WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); constexpr char kScript[] = R"(chrome.tabs.query({}, (tabs) => { let message; if (chrome.runtime.lastError) message = 'Unexpected error: ' + chrome.runtime.lastError; else message = 'Has gesture: ' + chrome.test.isProcessingUserGesture(); domAutomationController.send(message); });)"; { // Triggering an API without an active gesture shouldn't result in a // gesture in the callback. std::string message; EXPECT_TRUE(content::ExecuteScriptWithoutUserGestureAndExtractString( tab, kScript, &message)); EXPECT_EQ("Has gesture: false", message); } { // If there was an active gesture at the time of the API call, there should // be an active gesture in the callback. std::string message; EXPECT_TRUE(content::ExecuteScriptAndExtractString(tab, kScript, &message)); EXPECT_EQ("Has gesture: true", message); } } // Tests that a web page can consume a user gesture after an extension sends and // receives a reply during the same user gesture. // Regression test for https://crbug.com/921141. IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, WebUserGestureAfterMessagingCallback) { TestExtensionDir test_dir; test_dir.WriteManifest( R"({ "name": "User Gesture Messaging Test", "version": "0.1", "manifest_version": 2, "content_scripts": [{ "matches": ["*://*/*"], "js": ["content_script.js"], "run_at": "document_start" }], "background": { "scripts": ["background.js"] } })"); test_dir.WriteFile(FILE_PATH_LITERAL("content_script.js"), R"(window.addEventListener('mousedown', () => { chrome.runtime.sendMessage('hello', () => { let message = chrome.test.isProcessingUserGesture() ? 'got reply' : 'no user gesture'; chrome.test.sendMessage(message); }); });)"); test_dir.WriteFile( FILE_PATH_LITERAL("background.js"), R"(chrome.runtime.onMessage.addListener((message, sender, respond) => { respond('reply'); }); chrome.test.sendMessage('ready');)"); const Extension* extension = nullptr; { ExtensionTestMessageListener listener("ready", false); extension = LoadExtension(test_dir.UnpackedPath()); ASSERT_TRUE(extension); EXPECT_TRUE(listener.WaitUntilSatisfied()); } ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL( "/extensions/api_test/bindings/user_gesture_test.html")); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_TRUE(web_contents); { ExtensionTestMessageListener listener("got reply", false); listener.set_failure_message("no user gesture"); MouseDownInWebContents(web_contents); EXPECT_TRUE(listener.WaitUntilSatisfied()); } MouseUpInWebContents(web_contents); EXPECT_EQ("success", content::EvalJs(web_contents, "window.getEnteredFullscreen", content::EXECUTE_SCRIPT_NO_USER_GESTURE)); } // Tests that a web page can consume a user gesture after an extension calls a // method and receives the response in the callback. // Regression test for https://crbug.com/921141. IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, WebUserGestureAfterApiCallback) { TestExtensionDir test_dir; test_dir.WriteManifest( R"({ "name": "User Gesture Messaging Test", "version": "0.1", "manifest_version": 2, "content_scripts": [{ "matches": ["*://*/*"], "js": ["content_script.js"], "run_at": "document_start" }], "permissions": ["storage"] })"); test_dir.WriteFile(FILE_PATH_LITERAL("content_script.js"), R"(window.addEventListener('mousedown', () => { chrome.storage.local.get('foo', () => { let message = chrome.test.isProcessingUserGesture() ? 'got reply' : 'no user gesture'; chrome.test.sendMessage(message); }); });)"); const Extension* extension = LoadExtension(test_dir.UnpackedPath()); ASSERT_TRUE(extension); ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL( "/extensions/api_test/bindings/user_gesture_test.html")); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_TRUE(web_contents); { ExtensionTestMessageListener listener("got reply", false); listener.set_failure_message("no user gesture"); MouseDownInWebContents(web_contents); EXPECT_TRUE(listener.WaitUntilSatisfied()); } MouseUpInWebContents(web_contents); EXPECT_EQ("success", content::EvalJs(web_contents, "window.getEnteredFullscreen", content::EXECUTE_SCRIPT_NO_USER_GESTURE)); } // Tests that bindings are properly instantiated for a window navigated to an // extension URL after being opened with an undefined URL. // Regression test for https://crbug.com/925118. IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, TestBindingsAvailableWithNavigatedBlankWindow) { constexpr char kManifest[] = R"({ "name": "chrome.runtime bug checker", "description": "test case for crbug.com/925118", "version": "0", "manifest_version": 2 })"; constexpr char kOpenerHTML[] = R"(<!DOCTYPE html> <html> <head> <script src='opener.js'></script> </head> <body> </body> </html>)"; // opener.js opens a blank window and then navigates it to an extension URL // (where extension APIs should be available). constexpr char kOpenerJS[] = R"(const url = chrome.runtime.getURL('/page.html'); const win = window.open(undefined, ''); win.location = url; chrome.test.notifyPass())"; constexpr char kPageHTML[] = R"(<!DOCTYPE html> <html> This space intentionally left blank. </html>)"; TestExtensionDir extension_dir; extension_dir.WriteManifest(kManifest); extension_dir.WriteFile(FILE_PATH_LITERAL("opener.html"), kOpenerHTML); extension_dir.WriteFile(FILE_PATH_LITERAL("opener.js"), kOpenerJS); extension_dir.WriteFile(FILE_PATH_LITERAL("page.html"), kPageHTML); const Extension* extension = LoadExtension(extension_dir.UnpackedPath()); const GURL target_url = extension->GetResourceURL("page.html"); ResultCatcher catcher; content::TestNavigationObserver observer(target_url); observer.StartWatchingNewWebContents(); ui_test_utils::NavigateToURL(browser(), extension->GetResourceURL("opener.html")); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); observer.Wait(); EXPECT_TRUE(observer.last_navigation_succeeded()); content::WebContents* web_contents = browser()->tab_strip_model()->GetActiveWebContents(); EXPECT_EQ(target_url, web_contents->GetLastCommittedURL()); // Check whether bindings are available. They should be. constexpr char kScript[] = R"(let message; if (!chrome.runtime) message = 'Runtime not defined'; else if (!chrome.tabs) message = 'Tabs not defined'; else message = 'success'; domAutomationController.send(message);)"; std::string result; // Note: Can't use EvalJs() because of CSP in extension pages. EXPECT_TRUE( content::ExecuteScriptAndExtractString(web_contents, kScript, &result)); EXPECT_EQ("success", result); } // Tests the aliasing of chrome.extension methods to their chrome.runtime // equivalents. IN_PROC_BROWSER_TEST_F(ExtensionBindingsApiTest, ChromeExtensionIsAliasedToChromeRuntime) { constexpr char kManifest[] = R"({ "name": "Test", "version": "0.1", "manifest_version": 2, "background": { "scripts": ["background.js"] } })"; constexpr char kBackground[] = R"(chrome.test.runTests([ function chromeExtensionIsAliased() { // Sanity check: chrome.extension is directly aliased to // chrome.runtime. chrome.test.assertTrue(!!chrome.runtime); chrome.test.assertTrue(!!chrome.runtime.sendMessage); chrome.test.assertEq(chrome.runtime.sendMessage, chrome.extension.sendMessage); chrome.test.succeed(); }, function testOverridingFailsGracefully() { let intercepted = false; // Modify the chrome.runtime object, which is the source for the // chrome.extension API, to throw an error when sendMessage is // accessed. Nothing should blow up. // Regression test for https://crbug.com/949170. Object.defineProperty( chrome.runtime, 'sendMessage', { get() { intercepted = true; throw new Error('Mwahaha'); } }); chrome.extension.sendMessage; chrome.test.assertTrue(intercepted); chrome.test.succeed(); } ]);)"; TestExtensionDir extension_dir; extension_dir.WriteManifest(kManifest); extension_dir.WriteFile(FILE_PATH_LITERAL("background.js"), kBackground); ResultCatcher catcher; ASSERT_TRUE(LoadExtension(extension_dir.UnpackedPath())); EXPECT_TRUE(catcher.GetNextResult()) << catcher.message(); } } // namespace } // namespace extensions
39.829832
80
0.692837
[ "object" ]
4fc297c244f92c6bd6dbd85ca400b62da6f8773c
6,751
cpp
C++
trunk/suicore/src/Framework/Controls/Button.cpp
redrains/MPFUI
f7511ecbd220fb5069cd13a16d0067b7aec6e684
[ "MIT" ]
2
2017-10-16T08:16:50.000Z
2017-10-18T07:07:51.000Z
trunk/suicore/src/Framework/Controls/Button.cpp
redrains/MPFUI
f7511ecbd220fb5069cd13a16d0067b7aec6e684
[ "MIT" ]
null
null
null
trunk/suicore/src/Framework/Controls/Button.cpp
redrains/MPFUI
f7511ecbd220fb5069cd13a16d0067b7aec6e684
[ "MIT" ]
4
2017-11-02T03:55:34.000Z
2022-02-16T07:02:51.000Z
#include <Framework/Controls/Button.h> #include <Framework/Controls/Window.h> #include <Framework/Controls/TextBlock.h> #include <System/Tools/HwndHelper.h> #include <System/Tools/VisualTreeOp.h> #include <System/Tools/LogicalTreeOp.h> #include <System/Windows/CoreTool.h> #include <System/Windows/Binding.h> namespace suic { ImplementRTTIOfClass(Button, ButtonBase) DpProperty* Button::IsCancelProperty; DpProperty* Button::IsDefaultedProperty; DpProperty* Button::IsDefaultProperty; Button::Button() { _animationType = 1; } Button::~Button() { } void Button::OnIsDefaultedPropChanged(DpObject* d, DpPropChangedEventArg* e) { Button* btn = DynamicCast<Button>(d); if (btn != NULL) { if (e->GetNewValue()->ToInt() != 0) { btn->Focus(); } } } static DataTemplate* CreateContentTemplate(RTTIOfInfo* rttiInfo) { DataTemplate* temp = new DataTemplate(); FEFactory* root = new FEFactory(TextBlock::RTTIType(), _U("TextBlock")); Binding* bind = new Binding(); suic::TextBlock::StaticInit(); root->SetValue(TextBlock::TextProperty, bind); root->SetValue(TextBlock::TextAlignmentProperty, Integer::GetPosInt(TextAlignment::tCenter)); root->SetValue(TextBlock::HorizontalAlignmentProperty, HoriAlignBox::LeftBox); root->SetValue(TextBlock::VerticalAlignmentProperty, VertAlignBox::CenterBox); temp->SetVisualTree(root); //temp->SetTargetType(rttiInfo); return temp; } bool Button::StaticInit() { if (NULL == IsDefaultedProperty) { ButtonBase::StaticInit(); IsDefaultedProperty = DpProperty::Register(_T("IsDefaulted"), RTTIType(), Boolean::RTTIType() , DpPropMemory::GetPropMeta(Boolean::False, PropMetadataOptions::AffectsNone, &Button::OnIsDefaultedPropChanged)); IsDefaultProperty = DpProperty::Register(_T("IsDefault"), RTTIType(), Boolean::RTTIType() , DpPropMemory::GetPropMeta(Boolean::False, PropMetadataOptions::AffectsNone)); ContentTemplateProperty->OverrideMetadata(RTTIType(), new PropMetadata(CreateContentTemplate(RTTIType()))); } return true; } void Button::OnClick() { ButtonBase::OnClick(); } void Button::OnDataContextChanged(DpPropChangedEventArg* e) { ButtonBase::OnDataContextChanged(e); } //=========================================================== // ImplementRTTIOfClass(SysButton, ButtonBase) ImplementRTTIOfClass(MinimizeButton, SysButton) ImplementRTTIOfClass(MaximizeButton, SysButton) ImplementRTTIOfClass(CloseButton, SysButton) //------------------------------------------- MinimizeButton::MinimizeButton() { _animationType = 1; } MinimizeButton::~MinimizeButton() { ; } void MinimizeButton::OnClick() { HwndHelper::MinimizeWindow(this); } //------------------------------------------- MaximizeButton::MaximizeButton() { } MaximizeButton::~MaximizeButton() { ; } DpProperty* MaximizeButton::WindowStateProperty; /*void MaximizeButton::OnWindowStateChanged(Object* sender, EventArg* e) { Window* pWnd = RTTICast<Window>(sender); if (pWnd) { SetValue(WindowStateProperty, pWnd->GetValue(Window::WindowStateProperty)); } }*/ bool MaximizeButton::StaticInit() { if (NULL == WindowStateProperty) { WindowStateProperty = DpProperty::Register(_T("WindowState"), RTTIType(), Integer::RTTIType() , DpPropMemory::GetPropMeta(WindowStateBox::NormalBox, PropMetadataOptions::AffectsRender)); WindowStateProperty->SetConvertValueCb(WindowStateConvert::Convert); FocusableProperty->OverrideMetadata(RTTIType(), new PropMetadata(Boolean::False)); } return true; } SysButton::SysButton() { } SysButton::~SysButton() { } bool SysButton::StaticInit() { static bool s_init = false; if (!s_init) { s_init = true; FocusableProperty->OverrideMetadata(RTTIType(), new PropMetadata(Boolean::False)); } return true; } void MaximizeButton::OnInitialized(EventArg* e) { SysButton::OnInitialized(e); Binding* binding = new Binding(); RelativeSource* obj = new RelativeSource(RelativeSourceMode::FindAncestor); obj->AncestorType = Window::RTTIType(); PropertyPath ppath; ppath.Path = _U("WindowState"); binding->SetPath(ppath); binding->SetSourceRef(obj); SetBinding(WindowStateProperty, binding); /*int iLevel = 0; FrameworkElement* parent = GetParent(); while (parent != NULL) { Window* pWnd = RTTICast<Window>(parent); parent = parent->GetParent(); if (NULL != pWnd) { ++iLevel; if (parent == NULL) { Binding* binding = new Binding(); RelativeSource* obj = new RelativeSource(); obj->AncestorLevel = iLevel; obj->Mode = RelativeSourceMode::FindAncestor; obj->AncestorType = Window::RTTIType(); PropertyPath ppath; ppath.Path = _U("WindowState"); binding->SetPath(ppath); binding->SetSourceRef(obj); SetBinding(WindowStateProperty, binding); break; } } }*/ } /*void MaximizeButton::OnLoaded(LoadedEventArg* e) { SysButton::OnLoaded(e); Window* pWnd = RTTICast<Window>(VisualTreeOp::GetVisualRoot(this)); if (pWnd) { pWnd->StateChanged.Clear(); pWnd->StateChanged += EventHandler(this, &MaximizeButton::OnWindowStateChanged); SetValue(WindowStateProperty, pWnd->GetValue(Window::WindowStateProperty)); } } void MaximizeButton::OnUnloaded(LoadedEventArg* e) { Window* pWnd = RTTICast<Window>(VisualTreeOp::GetVisualRoot(this)); if (pWnd) { pWnd->StateChanged -= EventHandler(this, &MaximizeButton::OnWindowStateChanged); } }*/ void MaximizeButton::OnClick() { Window* pWnd = RTTICast<Window>(VisualTreeOp::GetVisualRoot(this)); if (pWnd && pWnd->GetWindowStyle() != WindowStyle::wsNone) { if (HwndHelper::IsWindowMaximize(pWnd)) { HwndHelper::RestoreWindow(pWnd); } else { HwndHelper::MaximizeWindow(pWnd); } /*if (pWnd->GetWindowState() != WindowState::wsMaximized) { pWnd->SetWindowState(WindowState::wsMaximized); } else if (pWnd->GetWindowState() == WindowState::wsMaximized) { pWnd->SetWindowState(WindowState::wsNormal); }*/ } } //------------------------------------------- CloseButton::CloseButton() { _animationType = 1; } CloseButton::~CloseButton() { ; } void CloseButton::OnClick() { HwndHelper::CloseWindow(this, true); } }
25.379699
126
0.64035
[ "object" ]
4fc2e82fd85e5f8239e2df94dad7de5dcf438f93
9,820
cpp
C++
oneflow/core/framework/consistent_tensor_infer_cache.cpp
Zhangchangh/oneflow
4ea3935458cc83dcea0abd88dd613f09c57dc01a
[ "Apache-2.0" ]
null
null
null
oneflow/core/framework/consistent_tensor_infer_cache.cpp
Zhangchangh/oneflow
4ea3935458cc83dcea0abd88dd613f09c57dc01a
[ "Apache-2.0" ]
null
null
null
oneflow/core/framework/consistent_tensor_infer_cache.cpp
Zhangchangh/oneflow
4ea3935458cc83dcea0abd88dd613f09c57dc01a
[ "Apache-2.0" ]
null
null
null
/* Copyright 2020 The OneFlow Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "oneflow/core/framework/consistent_tensor_infer_cache.h" #include "oneflow/core/framework/tensor_tuple.h" #include "oneflow/core/job/placement_scope.h" #include "oneflow/core/operator/operator.h" #include "oneflow/core/framework/to_string.h" #include "oneflow/core/framework/tensor.h" #include "oneflow/core/framework/op_expr.h" namespace oneflow { namespace one { size_t InputConsistentTensorMeta::hash_value() const { return std::hash<Symbol<ConsistentTensorMeta>>()(tensor_meta()) ^ std::hash<Symbol<cfg::ParallelDistribution>>()( consumer_parallel_distribution_constraint()); } bool InputConsistentTensorMeta::operator==(const InputConsistentTensorMeta& other) const { return this->tensor_meta() == other.tensor_meta() && this->consumer_parallel_distribution_constraint() == other.consumer_parallel_distribution_constraint(); } void InputConsistentTensorMeta::assign( Symbol<ConsistentTensorMeta> tensor_meta, Symbol<cfg::ParallelDistribution> consumer_parallel_distribution_constraint) { tensor_meta_ = tensor_meta; consumer_parallel_distribution_constraint_ = consumer_parallel_distribution_constraint; } size_t ConsistentTensorMetaInferArgs::hash_value() const { size_t hash_value = std::hash<Symbol<PlacementScope>>()(placement_scope_); hash_value ^= std::hash<AttrMap>()(attrs_); const auto& tensor_meta_hash_functor = std::hash<InputConsistentTensorMeta>(); for (const auto& tensor_meta : input_consistent_tensor_metas_) { HashCombine(&hash_value, tensor_meta_hash_functor(tensor_meta)); } return hash_value; } bool ConsistentTensorMetaInferArgs::operator==(const ConsistentTensorMetaInferArgs& other) const { return this->input_consistent_tensor_metas_ == other.input_consistent_tensor_metas_ && this->placement_scope_ == other.placement_scope_ && this->attrs_ == other.attrs_; } Maybe<void> ConsistentTensorMetaInferArgs::MakeParallelDistributionConstraints( const UserOpExpr& user_op_expr, cfg::ParallelDistributionSignature* parallel_distribution_signature) const { const auto& input_arg_tuple = *user_op_expr.input_arg_tuple(); auto* map = parallel_distribution_signature->mutable_bn_in_op2parallel_distribution(); for (int i = 0; i < input_arg_tuple.size(); ++i) { const auto& constaint = input_consistent_tensor_metas_.at(i).consumer_parallel_distribution_constraint(); if (constaint) { (*map)[input_arg_tuple.indexed_bns().at(i)] = *constaint; } } return Maybe<void>::Ok(); } Maybe<void> ConsistentTensorMetaInferArgs::MakeInputBlobDescs( const UserOpExpr& user_op_expr, std::vector<BlobDesc>* blob_descs) const { CHECK_OR_RETURN(blob_descs->empty()); const auto& input_arg_tuple = *user_op_expr.input_arg_tuple(); blob_descs->reserve(input_arg_tuple.size()); for (int i = 0; i < input_arg_tuple.size(); ++i) { const auto& tensor_meta = *input_consistent_tensor_metas_.at(i).tensor_meta(); const auto& shape = std::const_pointer_cast<Shape>(tensor_meta.shape_ptr()); blob_descs->emplace_back(shape, tensor_meta.data_type()); } return Maybe<void>::Ok(); } Maybe<void> ConsistentTensorMetaInferArgs::MakeParallelDistributionInferHints( const UserOpExpr& user_op_expr, const std::vector<BlobDesc>& blob_descs, std::vector<ParallelDistributionInferHint>* hints) const { CHECK_OR_RETURN(hints->empty()); const auto& input_arg_tuple = *user_op_expr.input_arg_tuple(); hints->reserve(input_arg_tuple.size()); for (int i = 0; i < input_arg_tuple.size(); ++i) { const auto& tensor_meta = *input_consistent_tensor_metas_.at(i).tensor_meta(); const auto* parallel_desc = &*tensor_meta.parallel_desc(); const auto* blob_desc = &blob_descs.at(i); const auto* parallel_distribution = &*tensor_meta.parallel_distribution(); hints->emplace_back(parallel_desc, blob_desc, parallel_distribution); } return Maybe<void>::Ok(); } Maybe<ConsistentTensorMetaInferArgs> ConsistentTensorMetaInferArgs::New( const TensorTuple& input_tensors, Symbol<PlacementScope> placement_scope, const AttrMap& attrs) { std::shared_ptr<ConsistentTensorMetaInferArgs> infer_args(new ConsistentTensorMetaInferArgs()); infer_args->input_consistent_tensor_metas_.resize(input_tensors.size()); infer_args->placement_scope_ = placement_scope; infer_args->attrs_ = attrs; JUST(infer_args->InitInputConsistentTensorMetas(input_tensors)); return infer_args; } Maybe<void> ConsistentTensorMetaInferArgs::InitInputConsistentTensorMetas( const TensorTuple& input_tensors) { for (int i = 0; i < input_tensors.size(); ++i) { const auto& tensor = *input_tensors.at(i); const auto& tensor_meta = JUST(tensor.consistent_tensor_meta()); const auto& constraints = JUST(tensor.consumer_parallel_distribution_constraint()); input_consistent_tensor_metas_.at(i).assign(tensor_meta, constraints); } return Maybe<void>::Ok(); } namespace { Maybe<Operator> MakeOp(const UserOpExpr& user_op_expr, const AttrMap& attrs, const std::string& device_tag) { OperatorConf op_conf; JUST(user_op_expr.BuildOpConf(&op_conf, attrs)); DeviceType device_type = JUST(DeviceType4DeviceTag(device_tag)); return JUST(ConstructOp(op_conf, device_type)); } } // namespace /* static */ Maybe<const ConsistentTensorInferResult> ConsistentTensorInferCache::Infer( const UserOpExpr& user_op_expr, const ConsistentTensorMetaInferArgs& infer_args) { Symbol<ParallelDesc> parallel_desc; { // Get parallel description. const auto& placement_scope = infer_args.placement_scope(); parallel_desc = JUST(placement_scope->GetParallelDesc(user_op_expr.op_type_name())); } std::vector<OpArgMutConsistentTensorMeta> output_mut_metas(user_op_expr.output_size()); { // Infer OpArgMutConsistentTensorMeta. const auto& input_metas = infer_args.input_consistent_tensor_metas(); JUST(user_op_expr.InferLogicalShapeAndDType( infer_args.attrs(), parallel_desc->device_tag(), [&](int32_t i) { return &*input_metas.at(i).tensor_meta(); }, [&](int32_t i) { return output_mut_metas.at(i).mut_tensor_meta(); })); } const auto& op = JUST(MakeOp(user_op_expr, infer_args.attrs(), parallel_desc->device_tag())); JUST(op->FillOpParallelDesc(parallel_desc.shared_from_symbol())); { // Infer parallel distribution. cfg::ParallelDistributionSignature parallel_distribution_constraints; JUST(infer_args.MakeParallelDistributionConstraints(user_op_expr, &parallel_distribution_constraints)); std::vector<BlobDesc> blob_descs; JUST(infer_args.MakeInputBlobDescs(user_op_expr, &blob_descs)); std::vector<ParallelDistributionInferHint> pd_infer_hints; JUST(infer_args.MakeParallelDistributionInferHints(user_op_expr, blob_descs, &pd_infer_hints)); const auto& input_arg_tuple = *user_op_expr.input_arg_tuple(); const auto& ParallelDistributionInferHint4Ibn = [&](const std::string& ibn) -> Maybe<const ParallelDistributionInferHint*> { int32_t input_index = input_arg_tuple.bn_in_op2tensor_tuple_index().at(ibn); CHECK_GE_OR_RETURN(input_index, 0); CHECK_LT_OR_RETURN(input_index, pd_infer_hints.size()); return &pd_infer_hints.at(input_index); }; // The inferred results can be retrieved by op->ParallelDistribution4BnInOp(obn). JUST(op->InferParallelDistributionSignatureIf(parallel_distribution_constraints, *parallel_desc, ParallelDistributionInferHint4Ibn)); } auto* result = new ConsistentTensorInferResult(user_op_expr.input_size(), user_op_expr.output_size()); auto* input_pd = result->mut_input_parallel_distributions(); for (int32_t i = 0; i < user_op_expr.input_size(); ++i) { const auto& ibn = user_op_expr.input_arg_tuple()->indexed_bns().at(i); input_pd->at(i) = SymbolOf(*JUST(op->ParallelDistribution4BnInOp(ibn))); } auto* output_metas = result->mut_output_tensor_metas(); for (int32_t i = 0; i < user_op_expr.output_size(); ++i) { const auto& output_mut_meta = output_mut_metas.at(i); const auto& shape = output_mut_meta.tensor_meta().shape_ptr(); DataType data_type = output_mut_meta.tensor_meta().data_type(); const auto& obn = user_op_expr.output_arg_tuple()->indexed_bns().at(i); const auto& parallel_distribution = SymbolOf(*JUST(op->ParallelDistribution4BnInOp(obn))); ConsistentTensorMeta tensor_meta(shape, data_type, parallel_distribution, parallel_desc); output_metas->at(i) = SymbolOf(tensor_meta); } return std::shared_ptr<const ConsistentTensorInferResult>(result); } Maybe<const ConsistentTensorInferResult> ConsistentTensorInferCache::GetOrInfer( const ConsistentTensorMetaInferArgs& infer_args) { auto iter = cache_.find(infer_args); if (iter == cache_.end()) { const auto& user_op_expr = user_op_expr_.lock(); CHECK_OR_RETURN(static_cast<bool>(user_op_expr)); const auto& output_tensor_metas = JUST(Infer(*user_op_expr, infer_args)); iter = cache_.emplace(infer_args, output_tensor_metas).first; } return iter->second; } } // namespace one } // namespace oneflow
46.540284
100
0.753666
[ "shape", "vector" ]
4fc38c76f1590965ed0a472b6ba5dbcafb07d418
6,057
hpp
C++
src/include/duckdb/function/scalar_function.hpp
rainmaple/duckdb
d3df77ba6740b8b089bddbfef77e2b969245b5cf
[ "MIT" ]
null
null
null
src/include/duckdb/function/scalar_function.hpp
rainmaple/duckdb
d3df77ba6740b8b089bddbfef77e2b969245b5cf
[ "MIT" ]
null
null
null
src/include/duckdb/function/scalar_function.hpp
rainmaple/duckdb
d3df77ba6740b8b089bddbfef77e2b969245b5cf
[ "MIT" ]
null
null
null
//===----------------------------------------------------------------------===// // DuckDB // // duckdb/function/scalar_function.hpp // // //===----------------------------------------------------------------------===// #pragma once #include "duckdb/function/function.hpp" #include "duckdb/common/vector_operations/vector_operations.hpp" #include "duckdb/common/vector_operations/unary_executor.hpp" #include "duckdb/common/vector_operations/binary_executor.hpp" #include "duckdb/execution/expression_executor_state.hpp" namespace duckdb { class BoundFunctionExpression; class ScalarFunctionCatalogEntry; //! The type used for scalar functions typedef void (*scalar_function_t)(DataChunk &input, ExpressionState &state, Vector &result); //! Binds the scalar function and creates the function data typedef unique_ptr<FunctionData> (*bind_scalar_function_t)(BoundFunctionExpression &expr, ClientContext &context); //! Adds the dependencies of this BoundFunctionExpression to the set of dependencies typedef void (*dependency_function_t)(BoundFunctionExpression &expr, unordered_set<CatalogEntry *> &dependencies); class ScalarFunction : public SimpleFunction { public: ScalarFunction(string name, vector<SQLType> arguments, SQLType return_type, scalar_function_t function, bool has_side_effects = false, bind_scalar_function_t bind = nullptr, dependency_function_t dependency = nullptr) : SimpleFunction(name, arguments, return_type, has_side_effects), function(function), bind(bind), dependency(dependency) { } ScalarFunction(vector<SQLType> arguments, SQLType return_type, scalar_function_t function, bool has_side_effects = false, bind_scalar_function_t bind = nullptr, dependency_function_t dependency = nullptr) : ScalarFunction(string(), arguments, return_type, function, has_side_effects, bind, dependency) { } //! The main scalar function to execute scalar_function_t function; //! The bind function (if any) bind_scalar_function_t bind; // The dependency function (if any) dependency_function_t dependency; static unique_ptr<BoundFunctionExpression> BindScalarFunction(ClientContext &context, string schema, string name, vector<SQLType> &arguments, vector<unique_ptr<Expression>> children, bool is_operator = false); static unique_ptr<BoundFunctionExpression> BindScalarFunction(ClientContext &context, ScalarFunctionCatalogEntry &function, vector<SQLType> &arguments, vector<unique_ptr<Expression>> children, bool is_operator = false); bool operator==(const ScalarFunction &rhs) const { return function == rhs.function && bind == rhs.bind && dependency == rhs.dependency; } bool operator!=(const ScalarFunction &rhs) const { return !(*this == rhs); } public: static void NopFunction(DataChunk &input, ExpressionState &state, Vector &result) { assert(input.column_count() >= 1); result.Reference(input.data[0]); }; template <class TA, class TR, class OP, bool SKIP_NULLS = false> static void UnaryFunction(DataChunk &input, ExpressionState &state, Vector &result) { assert(input.column_count() >= 1); UnaryExecutor::Execute<TA, TR, OP, SKIP_NULLS>(input.data[0], result); }; template <class TA, class TB, class TR, class OP, bool IGNORE_NULL = false> static void BinaryFunction(DataChunk &input, ExpressionState &state, Vector &result) { assert(input.column_count() == 2); BinaryExecutor::ExecuteStandard<TA, TB, TR, OP, IGNORE_NULL>(input.data[0], input.data[1], result); }; public: template <class OP> static scalar_function_t GetScalarUnaryFunction(SQLType type) { switch (type.id) { case SQLTypeId::TINYINT: return ScalarFunction::UnaryFunction<int8_t, int8_t, OP>; case SQLTypeId::SMALLINT: return ScalarFunction::UnaryFunction<int16_t, int16_t, OP>; case SQLTypeId::INTEGER: return ScalarFunction::UnaryFunction<int32_t, int32_t, OP>; case SQLTypeId::BIGINT: return ScalarFunction::UnaryFunction<int64_t, int64_t, OP>; case SQLTypeId::FLOAT: return ScalarFunction::UnaryFunction<float, float, OP>; case SQLTypeId::DOUBLE: return ScalarFunction::UnaryFunction<double, double, OP>; case SQLTypeId::DECIMAL: return ScalarFunction::UnaryFunction<double, double, OP>; default: throw NotImplementedException("Unimplemented type for GetScalarUnaryFunction"); } } template <class TR, class OP> static scalar_function_t GetScalarUnaryFunctionFixedReturn(SQLType type) { switch (type.id) { case SQLTypeId::TINYINT: return ScalarFunction::UnaryFunction<int8_t, TR, OP>; case SQLTypeId::SMALLINT: return ScalarFunction::UnaryFunction<int16_t, TR, OP>; case SQLTypeId::INTEGER: return ScalarFunction::UnaryFunction<int32_t, TR, OP>; case SQLTypeId::BIGINT: return ScalarFunction::UnaryFunction<int64_t, TR, OP>; case SQLTypeId::FLOAT: return ScalarFunction::UnaryFunction<float, TR, OP>; case SQLTypeId::DOUBLE: return ScalarFunction::UnaryFunction<double, TR, OP>; case SQLTypeId::DECIMAL: return ScalarFunction::UnaryFunction<double, TR, OP>; default: throw NotImplementedException("Unimplemented type for GetScalarUnaryFunctionFixedReturn"); } } template <class OP> static scalar_function_t GetScalarIntegerBinaryFunction(SQLType type) { switch (type.id) { case SQLTypeId::TINYINT: return ScalarFunction::BinaryFunction<int8_t, int8_t, int8_t, OP>; case SQLTypeId::SMALLINT: return ScalarFunction::BinaryFunction<int16_t, int16_t, int16_t, OP>; case SQLTypeId::INTEGER: return ScalarFunction::BinaryFunction<int32_t, int32_t, int32_t, OP>; case SQLTypeId::BIGINT: return ScalarFunction::BinaryFunction<int64_t, int64_t, int64_t, OP>; default: throw NotImplementedException("Unimplemented type for GetScalarIntegerBinaryFunction"); } } }; } // namespace duckdb
42.356643
114
0.715206
[ "vector" ]
4fc40f6fe6aed96be9a221ee88128e3139c4875e
2,995
hpp
C++
src/transformations/defmodel_exceptions.hpp
mlptownsend/PROJ
4920c22637d05cd7aa0aecc6de69736dd4c6845b
[ "MIT" ]
653
2015-03-27T10:12:52.000Z
2019-06-03T02:00:49.000Z
src/transformations/defmodel_exceptions.hpp
mlptownsend/PROJ
4920c22637d05cd7aa0aecc6de69736dd4c6845b
[ "MIT" ]
987
2019-06-05T11:42:40.000Z
2022-03-31T20:35:18.000Z
src/transformations/defmodel_exceptions.hpp
mlptownsend/PROJ
4920c22637d05cd7aa0aecc6de69736dd4c6845b
[ "MIT" ]
360
2019-06-20T23:50:36.000Z
2022-03-31T11:47:00.000Z
/****************************************************************************** * Project: PROJ * Purpose: Functionality related to deformation model * Author: Even Rouault, <even.rouault at spatialys.com> * ****************************************************************************** * Copyright (c) 2020, Even Rouault, <even.rouault at spatialys.com> * * 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 DEFORMATON_MODEL_NAMESPACE #error "Should be included only by defmodel.hpp" #endif #include <exception> namespace DEFORMATON_MODEL_NAMESPACE { // --------------------------------------------------------------------------- /** Parsing exception. */ class ParsingException : public std::exception { public: explicit ParsingException(const std::string &msg) : msg_(msg) {} const char *what() const noexcept override; private: std::string msg_; }; const char *ParsingException::what() const noexcept { return msg_.c_str(); } // --------------------------------------------------------------------------- class UnimplementedException : public std::exception { public: explicit UnimplementedException(const std::string &msg) : msg_(msg) {} const char *what() const noexcept override; private: std::string msg_; }; const char *UnimplementedException::what() const noexcept { return msg_.c_str(); } // --------------------------------------------------------------------------- /** Evaluator exception. */ class EvaluatorException : public std::exception { public: explicit EvaluatorException(const std::string &msg) : msg_(msg) {} const char *what() const noexcept override; private: std::string msg_; }; const char *EvaluatorException::what() const noexcept { return msg_.c_str(); } // --------------------------------------------------------------------------- } // namespace DEFORMATON_MODEL_NAMESPACE
36.52439
79
0.602671
[ "model" ]
4fca2a789071baa5e8727195909264e78f6e5a26
31,236
cpp
C++
DarkBit/src/SunNeutrinos.cpp
GambitBSM/gambit_2.0
a4742ac94a0352585a3b9dcb9b222048a5959b91
[ "Unlicense" ]
1
2021-09-17T22:53:26.000Z
2021-09-17T22:53:26.000Z
DarkBit/src/SunNeutrinos.cpp
GambitBSM/gambit_2.0
a4742ac94a0352585a3b9dcb9b222048a5959b91
[ "Unlicense" ]
3
2021-07-22T11:23:48.000Z
2021-08-22T17:24:41.000Z
DarkBit/src/SunNeutrinos.cpp
GambitBSM/gambit_2.0
a4742ac94a0352585a3b9dcb9b222048a5959b91
[ "Unlicense" ]
1
2021-08-14T10:31:41.000Z
2021-08-14T10:31:41.000Z
// GAMBIT: Global and Modular BSM Inference Tool // ********************************************* /// \file /// /// Solar neutrino likelihoods. /// /// ********************************************* /// /// Authors (add name and date if you modify): /// /// \author Pat Scott /// (pscott@imperial.ac.uk) /// \date 2015 Apr /// 2018 Sep /// /// \author Sebastian Wild /// (sebastian.wild@ph.tum.de) /// \date 2016 Aug /// /// \author Ankit Beniwal /// (ankit.beniwal@adelaide.edu.au) /// \date 2018 Jan, Aug /// /// ********************************************* #include "gambit/Elements/gambit_module_headers.hpp" #include "gambit/DarkBit/DarkBit_rollcall.hpp" #include "gambit/DarkBit/DarkBit_utils.hpp" //#define DARKBIT_DEBUG namespace Gambit { namespace DarkBit { ////////////////////////////////////////////////////////////////////////// // // Neutrino telescope likelihoods and observables // ////////////////////////////////////////////////////////////////////////// /*! \brief Capture rate of regular dark matter in the Sun (no v-dependent * or q-dependent cross-sections) (s^-1). DarkSUSY 5 version. */ void capture_rate_Sun_const_xsec_DS5(double &result) { using namespace Pipes::capture_rate_Sun_const_xsec_DS5; if (BEreq::cap_Sun_v0q0_isoscalar.origin()=="DarkSUSY") if(!(*Dep::DarkSUSY5_PointInit_LocalHalo)) DarkBit_error().raise(LOCAL_INFO,"DarkSUSY halo model not initialized!"); // When calculating the solar capture rate, DarkSUSY assumes that the // proton and neutron scattering cross-sections are the same; we // assume that whichever backend has been hooked up here does so too. result = BEreq::cap_Sun_v0q0_isoscalar(*Dep::mwimp, *Dep::sigma_SI_p, *Dep::sigma_SD_p); } /*! \brief Capture rate of regular dark matter in the Sun (no v-dependent * or q-dependent cross-sections) (s^-1). DarkSUSY 6 version. */ void capture_rate_Sun_const_xsec(double &result) { using namespace Pipes::capture_rate_Sun_const_xsec; if (BEreq::cap_Sun_v0q0_isoscalar.origin()=="DarkSUSY") if(!(*Dep::DarkSUSY_PointInit_LocalHalo)) DarkBit_error().raise(LOCAL_INFO,"DarkSUSY halo model not initialized!"); LocalMaxwellianHalo LocalHaloParameters = *Dep::LocalHalo; double rho0 = LocalHaloParameters.rho0; double rho0_eff = (*Dep::RD_fraction)*rho0; // When calculating the solar capture rate, DarkSUSY assumes that the // proton and neutron scattering cross-sections are the same; we // assume that whichever backend has been hooked up here does so too. result = BEreq::cap_Sun_v0q0_isoscalar(*Dep::mwimp, rho0_eff, *Dep::sigma_SI_p, *Dep::sigma_SD_p); } ///Alternative to the darkSusy fct, using captn_specific from capgen instead void capture_rate_Sun_const_xsec_capgen(double &result) { using namespace Pipes::capture_rate_Sun_const_xsec_capgen; double resultSD; double resultSI; double maxcap; BEreq::cap_sun_saturation(*Dep::mwimp,maxcap); BEreq::cap_Sun_v0q0_isoscalar(*Dep::mwimp,*Dep::sigma_SD_p,*Dep::sigma_SI_p,resultSD,resultSI); result = resultSI + resultSD; if (maxcap < result) { result = maxcap; } } ///Capture rate for v^n and q^n-dependent cross sections. ///Isoscalar (same proton/neutron coupling) ///SD only couples to Hydrogen. ///See DirectDetection.cpp to see how to define the cross sections sigma_SD_p, sigma_SI_pi void capture_rate_Sun_vnqn(double &result) { using namespace Pipes::capture_rate_Sun_vnqn; double resultSD; double resultSI; double capped; int qpow; int vpow; const int nelems = 29; double maxcap; BEreq::cap_sun_saturation(*Dep::mwimp,maxcap); resultSI = 0e0; resultSD = 0e0; typedef map_intpair_dbl::const_iterator it_type; //Spin-dependent: for(it_type iterator = Dep::sigma_SD_p->begin(); iterator != Dep::sigma_SD_p->end(); iterator++) { //don't capture anything if cross section is zero or all the DM is already capped if((iterator->second > 1e-90) && (resultSD < maxcap)) { qpow = (iterator->first).first/2 ; vpow = (iterator->first).second/2; //Capture BEreq::cap_Sun_vnqn_isoscalar(*Dep::mwimp,iterator->second,1,qpow,vpow,capped); resultSD = resultSD+capped; } } //Spin independent: for(it_type iterator = Dep::sigma_SI_p->begin(); iterator != Dep::sigma_SI_p->end(); iterator++) { if((iterator->second > 1e-90) && (resultSI+resultSD < maxcap)) { qpow = (iterator->first).first/2 ; vpow = (iterator->first).second/2; //Capture BEreq::cap_Sun_vnqn_isoscalar(*Dep::mwimp,iterator->second,nelems,qpow,vpow,capped); resultSI = resultSI+capped; } } result = resultSI+resultSD; logger() << "Capgen captured: SI: " << resultSI << " SD: " << resultSD << " total: " << result << "max = " << maxcap << "\n" << EOM; // If capture is above saturation, return saturation value. if (maxcap < result) { result = maxcap; } //cout << "capture rate via capture_rate_Sun_vnqn = " << result << "\n"; } /*! \brief Equilibration time for capture and annihilation of dark matter * in the Sun (s) */ void equilibration_time_Sun(double &result) { using namespace Pipes::equilibration_time_Sun; double sigmav = 0; double T_Sun_core = 1.35e-6; // Sun's core temperature (GeV) std::string DMid = *Dep::DarkMatter_ID; std::string DMbarid = *Dep::DarkMatterConj_ID; // Make sure that we're not trying to work with decaying DM. const TH_Process* p = Dep::TH_ProcessCatalog->find(DMid, DMbarid); if (p == NULL) DarkBit_error().raise(LOCAL_INFO, "Sorry, decaying DM is not supported yet by the DarkBit neutrino routines."); TH_Process annProc = Dep::TH_ProcessCatalog->getProcess(DMid, DMbarid); // Add all the regular channels for (std::vector<TH_Channel>::iterator it = annProc.channelList.begin(); it != annProc.channelList.end(); ++it) { if ( it->nFinalStates == 2 ) { // (sv)(v = sqrt(2T/mDM)) for two-body final state sigmav += it->genRate->bind("v")->eval(sqrt(2.0*T_Sun_core/(*Dep::mwimp))); } } // Add invisible contributions sigmav += annProc.genRateMisc->bind("v")->eval(sqrt(2.0*T_Sun_core/(*Dep::mwimp))); double ca = sigmav/6.6e28 * pow(*Dep::mwimp/20.0, 1.5); // Scale the annihilation rate down by a factor of two if the DM is not self-conjugate if (not (*Dep::TH_ProcessCatalog).getProcess(*Dep::DarkMatter_ID, *Dep::DarkMatterConj_ID).isSelfConj) ca *= 0.5; result = pow(*Dep::capture_rate_Sun * ca, -0.5); // std::cout << "v = " << sqrt(2.0*T_Sun_core/(*Dep::mwimp)) << " and sigmav inside equilibration_time_Sun = " << sigmav << std::endl; // std::cout << "capture_rate_Sun inside equilibration_time_Sun = " << *Dep::capture_rate_Sun << std::endl; } /// Annihilation rate of dark matter in the Sun (s^-1) void annihilation_rate_Sun(double &result) { using namespace Pipes::annihilation_rate_Sun; double tt_sun = 1.5e17 / *Dep::equilibration_time_Sun; result = *Dep::capture_rate_Sun * 0.5 * pow(tanh(tt_sun),2.0); } /// Neutrino yield function pointer and setup void nuyield_from_DS(nuyield_info &result) { using namespace Pipes::nuyield_from_DS; double annihilation_bf[29]; double Higgs_decay_BFs_neutral[29][3]; double Higgs_decay_BFs_charged[15]; double Higgs_masses_neutral[3]; double Higgs_mass_charged; // Set annihilation branching fractions std::string DMid = *Dep::DarkMatter_ID; std::string DMbarid = *Dep::DarkMatterConj_ID; TH_Process annProc = Dep::TH_ProcessCatalog->getProcess(DMid, DMbarid); std::vector< std::vector<str> > neutral_channels = BEreq::get_DS_neutral_h_decay_channels(); // the missing channel const std::vector<str> adhoc_chan = initVector<str>("W-", "H+"); for (int i=0; i<29; i++) { const TH_Channel* channel = annProc.find(neutral_channels[i]); if (channel == NULL or i == 26) // Channel 26 has not been implemented in DarkSUSY. { annihilation_bf[i] = 0.; } else { annihilation_bf[i] = channel->genRate->bind("v")->eval(0.); if (i == 10) // Add W- H+ for this channel { channel = annProc.find(adhoc_chan); if (channel == NULL) DarkBit_error().raise(LOCAL_INFO, "W+H- exists in process catalog but not W-H+." " That's some suspiciously severe CP violation yo."); annihilation_bf[i] += channel->genRate->bind("v")->eval(0.); } annihilation_bf[i] /= *Dep::sigmav; // Check that having this channel turned on makes sense at all. #ifdef DARKBIT_DEBUG double mtot = 0; cout << "Particles and masses in DM annihilation final state: " << endl; for (auto p = neutral_channels[i].begin(); p != neutral_channels[i].end(); ++p) { double m = Dep::TH_ProcessCatalog->getParticleProperty(*p).mass; cout << " " << *p << " " << m << endl; mtot += m; } cout << "Sqrt(s) vs total mass of final states: " << 2 * *Dep::mwimp << " vs. " << mtot << endl; cout << "Branching fraction in v=0 limit: " << annihilation_bf[i] << endl << endl; if (mtot > 2 * *Dep::mwimp and annihilation_bf[i] > 0.0) DarkBit_error().raise(LOCAL_INFO, "Channel is open in process catalog but should not be kinematically allowed."); #endif } } // Set Higgs masses if (Dep::TH_ProcessCatalog->hasParticleProperty("h0_1")) Higgs_masses_neutral[1] = Dep::TH_ProcessCatalog->getParticleProperty("h0_1").mass; else DarkBit_error().raise(LOCAL_INFO, "No SM-like Higgs in ProcessCatalog!"); Higgs_masses_neutral[0] = Dep::TH_ProcessCatalog->hasParticleProperty("h0_2") ? Dep::TH_ProcessCatalog->getParticleProperty("h0_2").mass : 0.; Higgs_masses_neutral[2] = Dep::TH_ProcessCatalog->hasParticleProperty("A0") ? Dep::TH_ProcessCatalog->getParticleProperty("A0").mass : 0.; Higgs_mass_charged = Dep::TH_ProcessCatalog->hasParticleProperty("H+") ? Dep::TH_ProcessCatalog->getParticleProperty("H+").mass : 0.; // Find out which Higgs exist and have decay data in the process // catalog. const TH_Process* h0_decays[3]; h0_decays[0] = Dep::TH_ProcessCatalog->find("h0_2"); h0_decays[1] = Dep::TH_ProcessCatalog->find("h0_1"); h0_decays[2] = Dep::TH_ProcessCatalog->find("A0"); const TH_Process* Hplus_decays = Dep::TH_ProcessCatalog->find("H+"); const TH_Process* Hminus_decays = Dep::TH_ProcessCatalog->find("H-"); if (Hplus_decays != NULL and Hminus_decays == NULL) DarkBit_error().raise( LOCAL_INFO, "H+ decays exist in process catalog but not H-."); if (Hplus_decays == NULL and Hminus_decays != NULL) DarkBit_error().raise( LOCAL_INFO, "H- decays exist in process catalog but not H+."); // Set the neutral Higgs decay branching fractions for (int i=0; i<3; i++) // Loop over the three neutral Higgs { // If this Higgs exists, set its decay properties. if (h0_decays[i] != NULL) { // Get the total decay width, for normalising partial widths to BFs. // TODO: Replace when BFs become directly available. double totalwidth = 0.0; for (std::vector<TH_Channel>::const_iterator it = h0_decays[i]->channelList.begin(); it != h0_decays[i]->channelList.end(); ++it) { // decay width in GeV for two-body final state if ( it->nFinalStates == 2 ) totalwidth += it->genRate->bind()->eval(); } std::vector<str> neutral_channel; // Loop over the decay channels for neutral scalars for (int j=0; j<29; j++) { neutral_channel.clear(); neutral_channel.push_back(DarkBit_utils::str_flav_to_mass((neutral_channels[j])[0])); neutral_channel.push_back(DarkBit_utils::str_flav_to_mass((neutral_channels[j])[1])); const TH_Channel* channel = h0_decays[i]->find(neutral_channel); // If this Higgs can decay into this channel, set the BF. if (channel != NULL) { Higgs_decay_BFs_neutral[j][i] = channel->genRate->bind()->eval(); if (j == 10) // Add W- H+ for this channel { channel = h0_decays[i]->find(adhoc_chan); if (channel == NULL) DarkBit_error().raise(LOCAL_INFO, "W+H- exists in process catalog but not W-H+." " That's some suspiciously severe CP violation yo."); Higgs_decay_BFs_neutral[j][i] += channel->genRate->bind()->eval(); } // This channel has not been implemented in DarkSUSY. if (j == 26) Higgs_decay_BFs_neutral[j][i] = 0.; Higgs_decay_BFs_neutral[j][i] /= totalwidth; } else { Higgs_decay_BFs_neutral[j][i] = 0.; } } } else { // Loop over the decay channels for neutral scalars, setting all BFs // for this Higgs to zero. for (int j=0; j<29; j++) Higgs_decay_BFs_neutral[j][i] = 0.; } } // If they exist, set the charged Higgs decay branching fractions // (DarkSUSY assumes that H+/H- decays are CP-invariant) if (Hplus_decays != NULL) { // Define the charged Higgs decay channels std::vector< std::vector<str> > charged_channels = BEreq::get_DS_charged_h_decay_channels(); // Get the total decay width, for normalising partial widths to BFs. // TODO: Replace when BFs become directly available. double totalwidth = 0.0; for (std::vector<TH_Channel>::const_iterator it = Hplus_decays->channelList.begin(); it != Hplus_decays->channelList.end(); ++it) { // decay width in GeV for two-body final state if (it->nFinalStates == 2) totalwidth += it->genRate->bind()->eval(); } std::vector<str> charged_channel; // Loop over the decay channels for charged scalars for (int j=0; j<15; j++) { charged_channel.clear(); charged_channel.push_back(DarkBit_utils::str_flav_to_mass((charged_channels[j])[0])); charged_channel.push_back(DarkBit_utils::str_flav_to_mass((charged_channels[j])[1])); const TH_Channel* channel = Hplus_decays->find(charged_channel); // If this Higgs can decay into this channel, set the BF. if (channel != NULL) { Higgs_decay_BFs_charged[j] = channel->genRate->bind()->eval(); Higgs_decay_BFs_charged[j] /= totalwidth; } else { Higgs_decay_BFs_charged[j] = 0.; } } } else { // Loop over the decay channels for charged scalars, setting all BFs // for this Higgs to zero. for (int j=0; j<15; j++) Higgs_decay_BFs_charged[j] = 0.; } // Debug output #ifdef DARKBIT_DEBUG for (int j=0; j<29; j++) { cout<< "annihilation bfs: " << j << " " << annihilation_bf[j] << endl; } cout<< endl; for (int i=0; i<3; i++) { for (int j=0; j<29; j++) { cout<< "higgs neutral bfs: " << i << " " << j << " " << Higgs_decay_BFs_neutral[j][i] << endl; } } cout<< endl; for (int j=0; j<15; j++) { cout<< "higgs charged bfs: " << j << " " << Higgs_decay_BFs_charged[j] << endl; } cout<< endl; for (int j=0; j<3; j++) { cout<< "higgs masses neutral: " << j << " " << Higgs_masses_neutral[j] << endl; } cout<< endl; cout<< "higgs charged mass: " << Higgs_mass_charged << endl; cout<< endl; cout<< "*Dep::mwimp: " << *Dep::mwimp << endl; cout<< endl; cout<< "*Dep::sigmav: " << *Dep::sigmav << endl; cout<< endl; #endif // Set up DarkSUSY to do neutrino yields for this particular WIMP BEreq::DS_nuyield_setup(annihilation_bf, Higgs_decay_BFs_neutral, Higgs_decay_BFs_charged, Higgs_masses_neutral, Higgs_mass_charged, *Dep::mwimp); // Hand back the pointer to the DarkSUSY neutrino yield function result.pointer = BEreq::nuyield.pointer(); //TODO: change below to >= when version numbers are available as ints // Treat the yield function as threadsafe only if the loaded version of DarkSUSY supports it. result.threadsafe = (BEreq::nuyield.version() == "5.1.3"); // Avoid OpenMP with gfortran 6.x and later, as the implementation seems to be buggy (causes stack overflows). #ifdef __GNUC__ #define GCC_VERSION (__GNUC__ * 10000 \ + __GNUC_MINOR__ * 100 \ + __GNUC_PATCHLEVEL__) #if GCC_VERSION > 60000 result.threadsafe = false; #endif #undef GCC_VERSION #endif } /// \brief Likelihood calculators for different IceCube event samples /// These functions all include the likelihood of the background-only model for the respective sample. /// We define the final log-likelihood as delta = sum over analyses of (lnL_model - lnL_BG), conservatively /// forbidding delta > 0 in order to always just use the neutrino likelihood as a limit. This ignores small /// low-E excesses caused by impending breakdown of approximations used in IceCube response data and the nulike /// likelihood at very low E. This implies conditioning on all but one parameter (e.g. the cross-section), /// such that including any particular IC analysis adds just *one* additional degree of freedom to the fit. /// @{ /// \brief 22-string IceCube sample: predicted signal and background /// counts, observed counts and likelihoods. void IC22_full(nudata &result) { using namespace Pipes::IC22_full; static bool first = true; const double bgloglike = -808.4581; double sigpred, bgpred, lnLike, pval; int totobs; char experiment[300] = "IC-22"; void* context = NULL; double theoryError = (*Dep::mwimp > 100.0 ? 0.05*sqrt(*Dep::mwimp*0.01) : 0.05); /// Option nulike_speed<int>: Speed setting for nulike backend (default 3) int speed = runOptions->getValueOrDef<int>(3,"nulike_speed"); BEreq::nubounds(experiment[0], *Dep::mwimp, *Dep::annihilation_rate_Sun, byVal(Dep::nuyield_ptr->pointer), sigpred, bgpred, totobs, lnLike, pval, 4, theoryError, speed, false, 0.0, 0.0, context, Dep::nuyield_ptr->threadsafe); piped_invalid_point.check(); piped_errors.check(DarkBit_error()); piped_warnings.check(DarkBit_warning()); result.signal = sigpred; result.bg = bgpred; result.nobs = totobs; result.loglike = lnLike; result.pvalue = pval; if (first) { result.bgloglike = bgloglike; first = false; } } /// \brief 79-string IceCube WH sample: predicted signal and background /// counts, observed counts and likelihoods. void IC79WH_full(nudata &result) { static bool first = true; using namespace Pipes::IC79WH_full; const double bgloglike = -11874.8689; double sigpred, bgpred, lnLike, pval; int totobs; char experiment[300] = "IC-79 WH"; void* context = NULL; double theoryError = (*Dep::mwimp > 100.0 ? 0.05*sqrt(*Dep::mwimp*0.01) : 0.05); /// Option nulike_speed<int>: Speed setting for nulike backend (default 3) int speed = runOptions->getValueOrDef<int>(3,"nulike_speed"); BEreq::nubounds(experiment[0], *Dep::mwimp, *Dep::annihilation_rate_Sun, byVal(Dep::nuyield_ptr->pointer), sigpred, bgpred, totobs, lnLike, pval, 4, theoryError, speed, false, 0.0, 0.0, context, Dep::nuyield_ptr->threadsafe); piped_invalid_point.check(); piped_errors.check(DarkBit_error()); piped_warnings.check(DarkBit_warning()); result.signal = sigpred; result.bg = bgpred; result.nobs = totobs; result.loglike = lnLike; result.pvalue = pval; if (first) { result.bgloglike = bgloglike; first = false; } } /// \brief 79-string IceCube WL sample: predicted signal and background /// counts, observed counts and likelihoods. void IC79WL_full(nudata &result) { static bool first = true; using namespace Pipes::IC79WL_full; const double bgloglike = -1813.4503; double sigpred, bgpred, lnLike, pval; int totobs; char experiment[300] = "IC-79 WL"; void* context = NULL; double theoryError = (*Dep::mwimp > 100.0 ? 0.05*sqrt(*Dep::mwimp*0.01) : 0.05); /// Option nulike_speed<int>: Speed setting for nulike backend (default 3) int speed = runOptions->getValueOrDef<int>(3,"nulike_speed"); BEreq::nubounds(experiment[0], *Dep::mwimp, *Dep::annihilation_rate_Sun, byVal(Dep::nuyield_ptr->pointer), sigpred, bgpred, totobs, lnLike, pval, 4, theoryError, speed, false, 0.0, 0.0, context, Dep::nuyield_ptr->threadsafe); piped_invalid_point.check(); piped_errors.check(DarkBit_error()); piped_warnings.check(DarkBit_warning()); result.signal = sigpred; result.bg = bgpred; result.nobs = totobs; result.loglike = lnLike; result.pvalue = pval; if (first) { result.bgloglike = bgloglike; first = false; } } /// \brief 79-string IceCube SL sample: predicted signal and background /// counts, observed counts and likelihoods. void IC79SL_full(nudata &result) { static bool first = true; using namespace Pipes::IC79SL_full; const double bgloglike = -5015.6474; double sigpred, bgpred, lnLike, pval; int totobs; char experiment[300] = "IC-79 SL"; void* context = NULL; double theoryError = (*Dep::mwimp > 100.0 ? 0.05*sqrt(*Dep::mwimp*0.01) : 0.05); /// Option nulike_speed<int>: Speed setting for nulike backend (default 3) int speed = runOptions->getValueOrDef<int>(3,"nulike_speed"); BEreq::nubounds(experiment[0], *Dep::mwimp, *Dep::annihilation_rate_Sun, byVal(Dep::nuyield_ptr->pointer), sigpred, bgpred, totobs, lnLike, pval, 4, theoryError, speed, false, 0.0, 0.0, context, Dep::nuyield_ptr->threadsafe); piped_invalid_point.check(); piped_errors.check(DarkBit_error()); piped_warnings.check(DarkBit_warning()); result.signal = sigpred; result.bg = bgpred; result.nobs = totobs; result.loglike = lnLike; result.pvalue = pval; if (first) { result.bgloglike = bgloglike; first = false; } } /// @} /// 22-string extractor module functions /// @{ void IC22_signal (double &result) { result = Pipes::IC22_signal ::Dep::IC22_data->signal; } void IC22_bg (double &result) { result = Pipes::IC22_bg ::Dep::IC22_data->bg; } void IC22_nobs (int &result) { result = Pipes::IC22_nobs ::Dep::IC22_data->nobs; } void IC22_loglike(double &result) { result = Pipes::IC22_loglike::Dep::IC22_data->loglike; } void IC22_bgloglike(double &result) { result = Pipes::IC22_bgloglike::Dep::IC22_data->bgloglike; } void IC22_pvalue (double &result) { result = Pipes::IC22_pvalue ::Dep::IC22_data->pvalue; } /// @} /// 79-string WH extractor module functions /// @{ void IC79WH_signal (double &result) { result = Pipes::IC79WH_signal ::Dep::IC79WH_data->signal; } void IC79WH_bg (double &result) { result = Pipes::IC79WH_bg ::Dep::IC79WH_data->bg; } void IC79WH_nobs (int &result) { result = Pipes::IC79WH_nobs ::Dep::IC79WH_data->nobs; } void IC79WH_loglike(double &result) { result = Pipes::IC79WH_loglike::Dep::IC79WH_data->loglike; } void IC79WH_bgloglike(double &result) { result = Pipes::IC79WH_bgloglike::Dep::IC79WH_data->bgloglike; } void IC79WH_pvalue (double &result) { result = Pipes::IC79WH_pvalue ::Dep::IC79WH_data->pvalue; } /// @} /// 79-string WL extractor module functions /// @{ void IC79WL_signal (double &result) { result = Pipes::IC79WL_signal ::Dep::IC79WL_data->signal; } void IC79WL_bg (double &result) { result = Pipes::IC79WL_bg ::Dep::IC79WL_data->bg; } void IC79WL_nobs (int &result) { result = Pipes::IC79WL_nobs ::Dep::IC79WL_data->nobs; } void IC79WL_loglike(double &result) { result = Pipes::IC79WL_loglike::Dep::IC79WL_data->loglike; } void IC79WL_bgloglike(double &result) { result = Pipes::IC79WL_bgloglike::Dep::IC79WL_data->bgloglike; } void IC79WL_pvalue (double &result) { result = Pipes::IC79WL_pvalue ::Dep::IC79WL_data->pvalue; } /// @} /// 79-string SL extractor module functions /// @{ void IC79SL_signal (double &result) { result = Pipes::IC79SL_signal ::Dep::IC79SL_data->signal; } void IC79SL_bg (double &result) { result = Pipes::IC79SL_bg ::Dep::IC79SL_data->bg; } void IC79SL_nobs (int &result) { result = Pipes::IC79SL_nobs ::Dep::IC79SL_data->nobs; } void IC79SL_loglike(double &result) { result = Pipes::IC79SL_loglike::Dep::IC79SL_data->loglike; } void IC79SL_bgloglike(double &result) { result = Pipes::IC79SL_bgloglike::Dep::IC79SL_data->bgloglike; } void IC79SL_pvalue (double &result) { result = Pipes::IC79SL_pvalue ::Dep::IC79SL_data->pvalue; } /// @} /// Composite IceCube 79-string likelihood function. void IC79_loglike(double &result) { using namespace Pipes::IC79_loglike; result = *Dep::IC79SL_loglike - *Dep::IC79SL_bgloglike + *Dep::IC79WL_loglike - *Dep::IC79WL_bgloglike + *Dep::IC79WH_loglike - *Dep::IC79WH_bgloglike; if (result > 0.0) result = 0.0; } /// Complete composite IceCube likelihood function. void IC_loglike(double &result) { using namespace Pipes::IC_loglike; result = *Dep::IC22_loglike - *Dep::IC22_bgloglike + *Dep::IC79SL_loglike - *Dep::IC79SL_bgloglike + *Dep::IC79WL_loglike - *Dep::IC79WL_bgloglike + *Dep::IC79WH_loglike - *Dep::IC79WH_bgloglike; if (result > 0.0) result = 0.0; #ifdef DARKBIT_DEBUG cout << "IC likelihood: " << result << endl; cout << "IC79SL contribution: " << *Dep::IC79SL_loglike - *Dep::IC79SL_bgloglike << endl; cout << "IC79WL contribution: " << *Dep::IC79WL_loglike - *Dep::IC79WL_bgloglike << endl; cout << "IC79WH contribution: " << *Dep::IC79WH_loglike - *Dep::IC79WH_bgloglike << endl; cout << "IC22 contribution: " << *Dep::IC22_loglike - *Dep::IC22_bgloglike << endl; #endif } /// Function to set Local Halo Parameters in DarkSUSY (DS5 only) void DarkSUSY5_PointInit_LocalHalo_func(bool &result) { using namespace Pipes::DarkSUSY5_PointInit_LocalHalo_func; LocalMaxwellianHalo LocalHaloParameters = *Dep::LocalHalo; double rho0 = LocalHaloParameters.rho0; double rho0_eff = (*Dep::RD_fraction)*rho0; double vrot = LocalHaloParameters.vrot; double vd_3d = sqrt(3./2.)*LocalHaloParameters.v0; double vesc = LocalHaloParameters.vesc; /// Option v_earth<double>: Keplerian velocity of the Earth around the Sun in km/s (default 29.78) double v_earth = runOptions->getValueOrDef<double>(29.78, "v_earth"); BEreq::dshmcom->rho0 = rho0; BEreq::dshmcom->v_sun = vrot; BEreq::dshmcom->v_earth = v_earth; BEreq::dshmcom->rhox = rho0_eff; BEreq::dshmframevelcom->v_obs = vrot; BEreq::dshmisodf->vd_3d = vd_3d; BEreq::dshmisodf->vgalesc = vesc; BEreq::dshmnoclue->vobs = vrot; logger() << LogTags::debug << "Updating DarkSUSY halo parameters:" << std::endl << " rho0 [GeV/cm^3] = " << rho0 << std::endl << " rho0_eff [GeV/cm^3] = " << rho0_eff << std::endl << " v_sun [km/s] = " << vrot<< std::endl << " v_earth [km/s] = " << v_earth << std::endl << " v_obs [km/s] = " << vrot << std::endl << " vd_3d [km/s] = " << vd_3d << std::endl << " v_esc [km/s] = " << vesc << EOM; result = true; return; } /// Function to set Local Halo Parameters in DarkSUSY (DS 6) void DarkSUSY_PointInit_LocalHalo_func(bool &result) { using namespace Pipes::DarkSUSY_PointInit_LocalHalo_func; LocalMaxwellianHalo LocalHaloParameters = *Dep::LocalHalo; double rho0 = LocalHaloParameters.rho0; double vrot = LocalHaloParameters.vrot; double vd_3d = sqrt(3./2.)*LocalHaloParameters.v0; double vesc = LocalHaloParameters.vesc; /// Option v_earth<double>: Keplerian velocity of the Earth around the Sun in km/s (default 29.78) double v_earth = runOptions->getValueOrDef<double>(29.78, "v_earth"); BEreq::dshmcom->rho0 = rho0; BEreq::dshmcom->v_sun = vrot; BEreq::dshmcom->v_earth = v_earth; BEreq::dshmframevelcom->v_obs = vrot; BEreq::dshmisodf->vd_3d = vd_3d; BEreq::dshmisodf->vgalesc = vesc; BEreq::dshmnoclue->vobs = vrot; logger() << LogTags::debug << "Updating DarkSUSY halo parameters:" << std::endl << " rho0 [GeV/cm^3] = " << rho0 << std::endl << " v_sun [km/s] = " << vrot<< std::endl << " v_earth [km/s] = " << v_earth << std::endl << " v_obs [km/s] = " << vrot << std::endl << " vd_3d [km/s] = " << vd_3d << std::endl << " v_esc [km/s] = " << vesc << EOM; result = true; return; } } }
39.34005
140
0.597003
[ "vector", "model" ]
4fcd9f122765f6b9579fa506d0e0293ee4a22ac8
20,853
cpp
C++
src/Databases/DatabaseAtomic.cpp
antarctictardigrade/ClickHouse
70a4d7ca74d8f8f11063286fef93e80f7e040883
[ "Apache-2.0" ]
2
2021-03-25T06:53:00.000Z
2021-04-29T07:32:51.000Z
src/Databases/DatabaseAtomic.cpp
antarctictardigrade/ClickHouse
70a4d7ca74d8f8f11063286fef93e80f7e040883
[ "Apache-2.0" ]
1
2020-03-26T01:50:51.000Z
2020-03-26T01:50:51.000Z
src/Databases/DatabaseAtomic.cpp
antarctictardigrade/ClickHouse
70a4d7ca74d8f8f11063286fef93e80f7e040883
[ "Apache-2.0" ]
null
null
null
#include <Databases/DatabaseAtomic.h> #include <Databases/DatabaseOnDisk.h> #include <Poco/File.h> #include <Poco/Path.h> #include <IO/ReadHelpers.h> #include <IO/WriteHelpers.h> #include <Parsers/formatAST.h> #include <Common/renameat2.h> #include <Storages/StorageMaterializedView.h> #include <Interpreters/Context.h> #include <Interpreters/ExternalDictionariesLoader.h> #include <filesystem> namespace DB { namespace ErrorCodes { extern const int UNKNOWN_TABLE; extern const int UNKNOWN_DATABASE; extern const int TABLE_ALREADY_EXISTS; extern const int CANNOT_ASSIGN_ALTER; extern const int DATABASE_NOT_EMPTY; extern const int NOT_IMPLEMENTED; extern const int FILE_ALREADY_EXISTS; extern const int INCORRECT_QUERY; } class AtomicDatabaseTablesSnapshotIterator final : public DatabaseTablesSnapshotIterator { public: explicit AtomicDatabaseTablesSnapshotIterator(DatabaseTablesSnapshotIterator && base) : DatabaseTablesSnapshotIterator(std::move(base)) {} UUID uuid() const override { return table()->getStorageID().uuid; } }; DatabaseAtomic::DatabaseAtomic(String name_, String metadata_path_, UUID uuid, Context & context_) : DatabaseOrdinary(name_, std::move(metadata_path_), "store/", "DatabaseAtomic (" + name_ + ")", context_) , path_to_table_symlinks(global_context.getPath() + "data/" + escapeForFileName(name_) + "/") , path_to_metadata_symlink(global_context.getPath() + "metadata/" + escapeForFileName(name_)) , db_uuid(uuid) { assert(db_uuid != UUIDHelpers::Nil); Poco::File(path_to_table_symlinks).createDirectories(); tryCreateMetadataSymlink(); } String DatabaseAtomic::getTableDataPath(const String & table_name) const { std::lock_guard lock(mutex); auto it = table_name_to_path.find(table_name); if (it == table_name_to_path.end()) throw Exception("Table " + table_name + " not found in database " + database_name, ErrorCodes::UNKNOWN_TABLE); assert(it->second != data_path && !it->second.empty()); return it->second; } String DatabaseAtomic::getTableDataPath(const ASTCreateQuery & query) const { auto tmp = data_path + DatabaseCatalog::getPathForUUID(query.uuid); assert(tmp != data_path && !tmp.empty()); return tmp; } void DatabaseAtomic::drop(const Context &) { assert(tables.empty()); try { Poco::File(path_to_metadata_symlink).remove(); Poco::File(path_to_table_symlinks).remove(true); } catch (...) { LOG_WARNING(log, getCurrentExceptionMessage(true)); } Poco::File(getMetadataPath()).remove(true); } void DatabaseAtomic::attachTable(const String & name, const StoragePtr & table, const String & relative_table_path) { assert(relative_table_path != data_path && !relative_table_path.empty()); DetachedTables not_in_use; std::unique_lock lock(mutex); not_in_use = cleanupDetachedTables(); auto table_id = table->getStorageID(); assertDetachedTableNotInUse(table_id.uuid); DatabaseWithDictionaries::attachTableUnlocked(name, table, lock); table_name_to_path.emplace(std::make_pair(name, relative_table_path)); } StoragePtr DatabaseAtomic::detachTable(const String & name) { DetachedTables not_in_use; std::unique_lock lock(mutex); auto table = DatabaseWithDictionaries::detachTableUnlocked(name, lock); table_name_to_path.erase(name); detached_tables.emplace(table->getStorageID().uuid, table); not_in_use = cleanupDetachedTables(); return table; } void DatabaseAtomic::dropTable(const Context &, const String & table_name, bool no_delay) { String table_metadata_path = getObjectMetadataPath(table_name); String table_metadata_path_drop; StoragePtr table; { std::unique_lock lock(mutex); table = getTableUnlocked(table_name, lock); table_metadata_path_drop = DatabaseCatalog::instance().getPathForDroppedMetadata(table->getStorageID()); Poco::File(table_metadata_path).renameTo(table_metadata_path_drop); /// Mark table as dropped DatabaseWithDictionaries::detachTableUnlocked(table_name, lock); /// Should never throw table_name_to_path.erase(table_name); } tryRemoveSymlink(table_name); /// Remove the inner table (if any) to avoid deadlock /// (due to attempt to execute DROP from the worker thread) if (auto * mv = dynamic_cast<StorageMaterializedView *>(table.get())) mv->dropInnerTable(no_delay); /// Notify DatabaseCatalog that table was dropped. It will remove table data in background. /// Cleanup is performed outside of database to allow easily DROP DATABASE without waiting for cleanup to complete. DatabaseCatalog::instance().enqueueDroppedTableCleanup(table->getStorageID(), table, table_metadata_path_drop, no_delay); } void DatabaseAtomic::renameTable(const Context & context, const String & table_name, IDatabase & to_database, const String & to_table_name, bool exchange, bool dictionary) { if (typeid(*this) != typeid(to_database)) { if (!typeid_cast<DatabaseOrdinary *>(&to_database)) throw Exception("Moving tables between databases of different engines is not supported", ErrorCodes::NOT_IMPLEMENTED); /// Allow moving tables between Atomic and Ordinary (with table lock) DatabaseOnDisk::renameTable(context, table_name, to_database, to_table_name, exchange, dictionary); return; } if (exchange && dictionary) throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Cannot exchange dictionaries"); auto & other_db = dynamic_cast<DatabaseAtomic &>(to_database); bool inside_database = this == &other_db; String old_metadata_path = getObjectMetadataPath(table_name); String new_metadata_path = to_database.getObjectMetadataPath(to_table_name); auto detach = [](DatabaseAtomic & db, const String & table_name_) { auto it = db.table_name_to_path.find(table_name_); String table_data_path_saved; /// Path can be not set for DDL dictionaries, but it does not matter for StorageDictionary. if (it != db.table_name_to_path.end()) table_data_path_saved = it->second; assert(!table_data_path_saved.empty() || db.dictionaries.find(table_name_) != db.dictionaries.end()); db.tables.erase(table_name_); db.table_name_to_path.erase(table_name_); if (!table_data_path_saved.empty()) db.tryRemoveSymlink(table_name_); return table_data_path_saved; }; auto attach = [](DatabaseAtomic & db, const String & table_name_, const String & table_data_path_, const StoragePtr & table_) { db.tables.emplace(table_name_, table_); if (table_data_path_.empty()) return; db.table_name_to_path.emplace(table_name_, table_data_path_); db.tryCreateSymlink(table_name_, table_data_path_); }; auto assert_can_move_mat_view = [inside_database](const StoragePtr & table_) { if (inside_database) return; if (const auto * mv = dynamic_cast<const StorageMaterializedView *>(table_.get())) if (mv->hasInnerTable()) throw Exception("Cannot move MaterializedView with inner table to other database", ErrorCodes::NOT_IMPLEMENTED); }; String table_data_path; String other_table_data_path; if (inside_database && table_name == to_table_name) return; std::unique_lock<std::mutex> db_lock; std::unique_lock<std::mutex> other_db_lock; if (inside_database) db_lock = std::unique_lock{mutex}; else if (this < &other_db) { db_lock = std::unique_lock{mutex}; other_db_lock = std::unique_lock{other_db.mutex}; } else { other_db_lock = std::unique_lock{other_db.mutex}; db_lock = std::unique_lock{mutex}; } bool is_dictionary = dictionaries.find(table_name) != dictionaries.end(); if (exchange && other_db.dictionaries.find(to_table_name) != other_db.dictionaries.end()) throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Cannot exchange dictionaries"); if (dictionary != is_dictionary) throw Exception(ErrorCodes::INCORRECT_QUERY, "Use RENAME DICTIONARY for dictionaries and RENAME TABLE for tables."); if (is_dictionary && !inside_database) throw Exception(ErrorCodes::NOT_IMPLEMENTED, "Cannot move dictionary to other database"); StoragePtr table = getTableUnlocked(table_name, db_lock); table->checkTableCanBeRenamed(); assert_can_move_mat_view(table); StoragePtr other_table; if (exchange) { other_table = other_db.getTableUnlocked(to_table_name, other_db_lock); other_table->checkTableCanBeRenamed(); assert_can_move_mat_view(other_table); } /// Table renaming actually begins here if (exchange) renameExchange(old_metadata_path, new_metadata_path); else renameNoReplace(old_metadata_path, new_metadata_path); /// After metadata was successfully moved, the following methods should not throw (if them do, it's a logical error) table_data_path = detach(*this, table_name); if (exchange) other_table_data_path = detach(other_db, to_table_name); auto old_table_id = table->getStorageID(); table->renameInMemory({other_db.database_name, to_table_name, old_table_id.uuid}); if (exchange) other_table->renameInMemory({database_name, table_name, other_table->getStorageID().uuid}); if (!inside_database) { DatabaseCatalog::instance().updateUUIDMapping(old_table_id.uuid, other_db.shared_from_this(), table); if (exchange) DatabaseCatalog::instance().updateUUIDMapping(other_table->getStorageID().uuid, shared_from_this(), other_table); } attach(other_db, to_table_name, table_data_path, table); if (exchange) attach(*this, table_name, other_table_data_path, other_table); if (is_dictionary) { auto new_table_id = StorageID(other_db.database_name, to_table_name, old_table_id.uuid); renameDictionaryInMemoryUnlocked(old_table_id, new_table_id); } } void DatabaseAtomic::commitCreateTable(const ASTCreateQuery & query, const StoragePtr & table, const String & table_metadata_tmp_path, const String & table_metadata_path) { DetachedTables not_in_use; auto table_data_path = getTableDataPath(query); bool locked_uuid = false; try { std::unique_lock lock{mutex}; if (query.database != database_name) throw Exception(ErrorCodes::UNKNOWN_DATABASE, "Database was renamed to `{}`, cannot create table in `{}`", database_name, query.database); /// Do some checks before renaming file from .tmp to .sql not_in_use = cleanupDetachedTables(); assertDetachedTableNotInUse(query.uuid); /// We will get en exception if some table with the same UUID exists (even if it's detached table or table from another database) DatabaseCatalog::instance().addUUIDMapping(query.uuid); locked_uuid = true; /// It throws if `table_metadata_path` already exists (it's possible if table was detached) renameNoReplace(table_metadata_tmp_path, table_metadata_path); /// Commit point (a sort of) attachTableUnlocked(query.table, table, lock); /// Should never throw table_name_to_path.emplace(query.table, table_data_path); } catch (...) { Poco::File(table_metadata_tmp_path).remove(); if (locked_uuid) DatabaseCatalog::instance().removeUUIDMappingFinally(query.uuid); throw; } tryCreateSymlink(query.table, table_data_path); } void DatabaseAtomic::commitAlterTable(const StorageID & table_id, const String & table_metadata_tmp_path, const String & table_metadata_path) { bool check_file_exists = true; SCOPE_EXIT({ std::error_code code; if (check_file_exists) std::filesystem::remove(table_metadata_tmp_path, code); }); std::unique_lock lock{mutex}; auto actual_table_id = getTableUnlocked(table_id.table_name, lock)->getStorageID(); if (table_id.uuid != actual_table_id.uuid) throw Exception("Cannot alter table because it was renamed", ErrorCodes::CANNOT_ASSIGN_ALTER); check_file_exists = renameExchangeIfSupported(table_metadata_tmp_path, table_metadata_path); if (!check_file_exists) std::filesystem::rename(table_metadata_tmp_path, table_metadata_path); } void DatabaseAtomic::assertDetachedTableNotInUse(const UUID & uuid) { /// Without this check the following race is possible since table RWLocks are not used: /// 1. INSERT INTO table ...; /// 2. DETACH TABLE table; (INSERT still in progress, it holds StoragePtr) /// 3. ATTACH TABLE table; (new instance of Storage with the same UUID is created, instances share data on disk) /// 4. INSERT INTO table ...; (both Storage instances writes data without any synchronization) /// To avoid it, we remember UUIDs of detached tables and does not allow ATTACH table with such UUID until detached instance still in use. if (detached_tables.count(uuid)) throw Exception("Cannot attach table with UUID " + toString(uuid) + ", because it was detached but still used by some query. Retry later.", ErrorCodes::TABLE_ALREADY_EXISTS); } DatabaseAtomic::DetachedTables DatabaseAtomic::cleanupDetachedTables() { DetachedTables not_in_use; auto it = detached_tables.begin(); while (it != detached_tables.end()) { if (it->second.unique()) { not_in_use.emplace(it->first, it->second); it = detached_tables.erase(it); } else ++it; } /// It should be destroyed in caller with released database mutex return not_in_use; } void DatabaseAtomic::assertCanBeDetached(bool cleanup) { if (cleanup) { DetachedTables not_in_use; { std::lock_guard lock(mutex); not_in_use = cleanupDetachedTables(); } } std::lock_guard lock(mutex); if (!detached_tables.empty()) throw Exception("Database " + backQuoteIfNeed(database_name) + " cannot be detached, " "because some tables are still in use. Retry later.", ErrorCodes::DATABASE_NOT_EMPTY); } DatabaseTablesIteratorPtr DatabaseAtomic::getTablesIterator(const Context & context, const IDatabase::FilterByNameFunction & filter_by_table_name) { auto base_iter = DatabaseWithOwnTablesBase::getTablesIterator(context, filter_by_table_name); return std::make_unique<AtomicDatabaseTablesSnapshotIterator>(std::move(typeid_cast<DatabaseTablesSnapshotIterator &>(*base_iter))); } UUID DatabaseAtomic::tryGetTableUUID(const String & table_name) const { if (auto table = tryGetTable(table_name, global_context)) return table->getStorageID().uuid; return UUIDHelpers::Nil; } void DatabaseAtomic::loadStoredObjects(Context & context, bool has_force_restore_data_flag, bool force_attach) { /// Recreate symlinks to table data dirs in case of force restore, because some of them may be broken if (has_force_restore_data_flag) Poco::File(path_to_table_symlinks).remove(true); DatabaseOrdinary::loadStoredObjects(context, has_force_restore_data_flag, force_attach); if (has_force_restore_data_flag) { NameToPathMap table_names; { std::lock_guard lock{mutex}; table_names = table_name_to_path; } Poco::File(path_to_table_symlinks).createDirectories(); for (const auto & table : table_names) tryCreateSymlink(table.first, table.second); } } void DatabaseAtomic::tryCreateSymlink(const String & table_name, const String & actual_data_path) { try { String link = path_to_table_symlinks + escapeForFileName(table_name); String data = Poco::Path(global_context.getPath()).makeAbsolute().toString() + actual_data_path; Poco::File{data}.linkTo(link, Poco::File::LINK_SYMBOLIC); } catch (...) { LOG_WARNING(log, getCurrentExceptionMessage(true)); } } void DatabaseAtomic::tryRemoveSymlink(const String & table_name) { try { String path = path_to_table_symlinks + escapeForFileName(table_name); Poco::File{path}.remove(); } catch (...) { LOG_WARNING(log, getCurrentExceptionMessage(true)); } } void DatabaseAtomic::tryCreateMetadataSymlink() { /// Symlinks in data/db_name/ directory and metadata/db_name/ are not used by ClickHouse, /// it's needed only for convenient introspection. assert(path_to_metadata_symlink != metadata_path); Poco::File metadata_symlink(path_to_metadata_symlink); if (metadata_symlink.exists()) { if (!metadata_symlink.isLink()) throw Exception(ErrorCodes::FILE_ALREADY_EXISTS, "Directory {} exists", path_to_metadata_symlink); } else { try { Poco::File{metadata_path}.linkTo(path_to_metadata_symlink, Poco::File::LINK_SYMBOLIC); } catch (...) { tryLogCurrentException(log); } } } void DatabaseAtomic::renameDatabase(const String & new_name) { /// CREATE, ATTACH, DROP, DETACH and RENAME DATABASE must hold DDLGuard try { Poco::File(path_to_metadata_symlink).remove(); } catch (...) { LOG_WARNING(log, getCurrentExceptionMessage(true)); } auto new_name_escaped = escapeForFileName(new_name); auto old_database_metadata_path = global_context.getPath() + "metadata/" + escapeForFileName(getDatabaseName()) + ".sql"; auto new_database_metadata_path = global_context.getPath() + "metadata/" + new_name_escaped + ".sql"; renameNoReplace(old_database_metadata_path, new_database_metadata_path); String old_path_to_table_symlinks; { std::lock_guard lock(mutex); DatabaseCatalog::instance().updateDatabaseName(database_name, new_name); database_name = new_name; for (auto & table : tables) { auto table_id = table.second->getStorageID(); table_id.database_name = database_name; table.second->renameInMemory(table_id); } for (auto & dict : dictionaries) { auto old_name = StorageID(dict.second.create_query); auto name = old_name; name.database_name = database_name; renameDictionaryInMemoryUnlocked(old_name, name); } path_to_metadata_symlink = global_context.getPath() + "metadata/" + new_name_escaped; old_path_to_table_symlinks = path_to_table_symlinks; path_to_table_symlinks = global_context.getPath() + "data/" + new_name_escaped + "/"; } Poco::File(old_path_to_table_symlinks).renameTo(path_to_table_symlinks); tryCreateMetadataSymlink(); } void DatabaseAtomic::renameDictionaryInMemoryUnlocked(const StorageID & old_name, const StorageID & new_name) { auto it = dictionaries.find(old_name.table_name); assert(it != dictionaries.end()); assert(it->second.config->getString("dictionary.uuid") == toString(old_name.uuid)); assert(old_name.uuid == new_name.uuid); it->second.config->setString("dictionary.database", new_name.database_name); it->second.config->setString("dictionary.name", new_name.table_name); auto & create = it->second.create_query->as<ASTCreateQuery &>(); create.database = new_name.database_name; create.table = new_name.table_name; assert(create.uuid == new_name.uuid); if (old_name.table_name != new_name.table_name) { auto attach_info = std::move(it->second); dictionaries.erase(it); dictionaries.emplace(new_name.table_name, std::move(attach_info)); } auto result = external_loader.getLoadResult(toString(old_name.uuid)); if (!result.object) return; const auto & dict = dynamic_cast<const IDictionaryBase &>(*result.object); dict.updateDictionaryName(new_name); } void DatabaseAtomic::waitDetachedTableNotInUse(const UUID & uuid) { { std::lock_guard lock{mutex}; if (detached_tables.count(uuid) == 0) return; } /// Table is in use while its shared_ptr counter is greater than 1. /// We cannot trigger condvar on shared_ptr destruction, so it's busy wait. while (true) { DetachedTables not_in_use; { std::lock_guard lock{mutex}; not_in_use = cleanupDetachedTables(); if (detached_tables.count(uuid) == 0) return; } std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } }
38.616667
146
0.696015
[ "object" ]
4fd0287f259911a31a09dd44ad91b938174d3c4f
1,474
hpp
C++
Systems/Physics/MeshDebug.hpp
RachelWilSingh/ZeroCore
e9a2f82d395e5c89fb98eceac44ce60d016dbff3
[ "MIT" ]
52
2018-09-11T17:18:35.000Z
2022-03-13T15:28:21.000Z
Systems/Physics/MeshDebug.hpp
RachelWilSingh/ZeroCore
e9a2f82d395e5c89fb98eceac44ce60d016dbff3
[ "MIT" ]
1,409
2018-09-19T18:03:43.000Z
2021-06-09T08:33:33.000Z
Systems/Physics/MeshDebug.hpp
RachelWilSingh/ZeroCore
e9a2f82d395e5c89fb98eceac44ce60d016dbff3
[ "MIT" ]
26
2018-09-11T17:16:32.000Z
2021-11-22T06:21:19.000Z
/////////////////////////////////////////////////////////////////////////////// /// /// Authors: Joshua Davis /// Copyright 2012, DigiPen Institute of Technology /// /////////////////////////////////////////////////////////////////////////////// #pragma once namespace Zero { class GenericPhysicsMesh; class HeightMapCollider; /// A helper class to test internal edges in script. /// Shouldn't really be committed but I need this for further testing. class MeshDebug : public Component { public: ZilchDeclareType(TypeCopyMode::ReferenceType); void CacheData(); void Initialize(CogInitializer& initializer) override; void DrawTriangles(); void DrawVoronoiRegion(Vec3Param p0, Vec3Param p1, real angle, Vec3Param triNormal, Mat4Param transform); void DrawTriangleVoronoiRegion(uint triIndex); void DrawVectorAtPoint(Vec3Param start, Vec3Param dir, Vec3Param vec); void DrawAllTriangleVoronoiRegions(); void TestManifoldPoint(Vec3Param start, Vec3Param dir, Vec3Param contactNormal); uint GetTriangleIndexFromCast(Vec3Param start, Vec3Param dir); Vec3 GetTriangleNormal(uint index); Vec3 GetPointFromCastOnTriangle(uint index, Vec3Param start, Vec3Param dir); void DrawTriangleFromCast(Vec3Param start, Vec3Param dir); void GenerateInfoForTriangles(Vec3Param start1, Vec3Param dir1, Vec3Param start2, Vec3Param dir2); GenericPhysicsMesh* mMesh; HeightMapCollider* mHeightMap; }; }//namespace Zero
35.095238
108
0.684532
[ "transform" ]
4fd090e9d53f2b3d03ab997b486c0dcbf197d115
2,207
cpp
C++
vendor/github.com/Benau/go_rlottie/lottie_lottiekeypath.cpp
keenan-v1/matterbridge
53cafa9f3d0c8be33821fc7338b1da97e91d9cc6
[ "Apache-2.0" ]
4,999
2015-10-24T00:48:13.000Z
2022-03-31T23:06:12.000Z
vendor/github.com/Benau/go_rlottie/lottie_lottiekeypath.cpp
keenan-v1/matterbridge
53cafa9f3d0c8be33821fc7338b1da97e91d9cc6
[ "Apache-2.0" ]
1,674
2015-11-03T19:56:18.000Z
2022-03-31T22:22:06.000Z
vendor/github.com/Benau/go_rlottie/lottie_lottiekeypath.cpp
tank0226/matterbridge
e3ffbcadd82d71e87e7f5841f9a037f9358a010b
[ "Apache-2.0" ]
602
2015-11-04T16:13:32.000Z
2022-03-22T07:08:27.000Z
#include "lottie_lottiekeypath.h" #include <sstream> LOTKeyPath::LOTKeyPath(const std::string &keyPath) { std::stringstream ss(keyPath); std::string item; while (getline(ss, item, '.')) { mKeys.push_back(item); } } bool LOTKeyPath::matches(const std::string &key, uint depth) { if (skip(key)) { // This is an object we programatically create. return true; } if (depth > size()) { return false; } if ((mKeys[depth] == key) || (mKeys[depth] == "*") || (mKeys[depth] == "**")) { return true; } return false; } uint LOTKeyPath::nextDepth(const std::string key, uint depth) { if (skip(key)) { // If it's a container then we added programatically and it isn't a part // of the keypath. return depth; } if (mKeys[depth] != "**") { // If it's not a globstar then it is part of the keypath. return depth + 1; } if (depth == size()) { // The last key is a globstar. return depth; } if (mKeys[depth + 1] == key) { // We are a globstar and the next key is our current key so consume // both. return depth + 2; } return depth; } bool LOTKeyPath::fullyResolvesTo(const std::string key, uint depth) { if (depth > mKeys.size()) { return false; } bool isLastDepth = (depth == size()); if (!isGlobstar(depth)) { bool matches = (mKeys[depth] == key) || isGlob(depth); return (isLastDepth || (depth == size() - 1 && endsWithGlobstar())) && matches; } bool isGlobstarButNextKeyMatches = !isLastDepth && mKeys[depth + 1] == key; if (isGlobstarButNextKeyMatches) { return depth == size() - 1 || (depth == size() - 2 && endsWithGlobstar()); } if (isLastDepth) { return true; } if (depth + 1 < size()) { // We are a globstar but there is more than 1 key after the globstar we // we can't fully match. return false; } // Return whether the next key (which we now know is the last one) is the // same as the current key. return mKeys[depth + 1] == key; }
25.367816
80
0.552333
[ "object" ]
4fd72331e96a74a7b95ac7bf49dbf4c8dc269837
4,198
cpp
C++
src/scene/data/geometric/BSWSVectors.cpp
danielroth1/CAE
7eaa096e45fd32f55bd6de94c30dcf706c6f2093
[ "MIT" ]
5
2019-04-20T17:48:10.000Z
2022-01-06T01:39:33.000Z
src/scene/data/geometric/BSWSVectors.cpp
danielroth1/CAE
7eaa096e45fd32f55bd6de94c30dcf706c6f2093
[ "MIT" ]
null
null
null
src/scene/data/geometric/BSWSVectors.cpp
danielroth1/CAE
7eaa096e45fd32f55bd6de94c30dcf706c6f2093
[ "MIT" ]
2
2020-08-04T20:21:00.000Z
2022-03-16T15:01:04.000Z
#include "BSWSVectors.h" using namespace Eigen; BSWSVectors::BSWSVectors() { mInitialized = false; } BSWSVectors::BSWSVectors(size_t size) { Vectors vectors; vectors.resize(size); for (size_t i = 0; i < size; ++i) { vectors[i] = Eigen::Vector::Zero(); } initializeFromWorldSpace(vectors); } BSWSVectors::BSWSVectors( const Vectors& vectorsWS) { initializeFromWorldSpace(vectorsWS); } BSWSVectors::BSWSVectors( Vectors* vectorsBS, const Affine3d& transform) { initializeFromBodySpace(vectorsBS, transform); } BSWSVectors::BSWSVectors(const BSWSVectors& posData) { if (!posData.mInitialized) { mInitialized = false; return; } switch(posData.mType) { case BODY_SPACE: initializeFromBodySpace(posData.mVectorsBS, posData.mTransform); break; case WORLD_SPACE: initializeFromWorldSpace(posData.mVectorsWS); break; } } // go to BSWSVectors void BSWSVectors::update() { if (!mInitialized) return; switch (mType) { case BODY_SPACE: updateWorldSpace(); break; case WORLD_SPACE: // do nothing. // The body space can only be synchronized with // a center vertex. In general it is not necessary // to keep the body space synchronized. The relevant // data are the world space positions and they are // already given. //updateBodySpace(); break; } } void BSWSVectors::removeVector(ID index) { // TODO: this only works in WS representation? VectorOperations::removeVector(mVectorsWS, index); } // go to BSWSVectors without center ( = (0, 0, 0) ) // setting the center should be done only in SharedPolygonData void BSWSVectors::changeRepresentationToBS( Vectors* vectorsBS, const Eigen::Affine3d& transform) { if (!mInitialized) return; // one may only change the representation type to // body space if it was in world space before because // then it is ensured that the world space representation // is valid. if (mType == WORLD_SPACE) { mVectorsBS = vectorsBS; mVectorsWS = *vectorsBS; mTransform = transform; mType = BODY_SPACE; updateWorldSpace(); } } // go to BSWSVectors void BSWSVectors::changeRepresentationToWS() { if (!mInitialized) return; // one may only change the representation type to // world space if it was in body space before because // then it is ensured that the body space representation // is valid. if (mType == BODY_SPACE) { mTransform.setIdentity(); updateWorldSpace(); mType = WORLD_SPACE; } } // go to BSWSVectors void BSWSVectors::translate(const Vector& t) { if (!mInitialized) return; switch(mType) { case BODY_SPACE: mTransform.pretranslate(t); break; case WORLD_SPACE: for (Vector& v : mVectorsWS) { v += t; } } } void BSWSVectors::transform(const Affine3d& transform) { if (!mInitialized) return; switch(mType) { case BODY_SPACE: mTransform = mTransform * transform; break; case WORLD_SPACE: for (Vector& v : mVectorsWS) { v = transform * v; } } } void BSWSVectors::updateWorldSpace() { if (!mInitialized) return; size_t nVectors = mVectorsWS.size(); #pragma omp parallel for if (nVectors > 10000) for (size_t i = 0; i < mVectorsWS.size(); ++i) { mVectorsWS[i] = mTransform * (*mVectorsBS)[i]; } } void BSWSVectors::initializeFromWorldSpace(Vectors vectorsWS) { mVectorsWS = vectorsWS; mVectorsBS = nullptr; mTransform.setIdentity(); mType = WORLD_SPACE; mInitialized = true; } void BSWSVectors::initializeFromBodySpace( Vectors* vectorsBS, const Affine3d& transform) { mVectorsBS = vectorsBS; mTransform = transform; // world space positions is simply equal body Ogespace // positions. mVectorsWS = *vectorsBS; mType = BODY_SPACE; mInitialized = true; }
21.20202
72
0.624583
[ "vector", "transform" ]
4fdce267db93e969e907502a1177cb62924d3aaa
3,262
cpp
C++
Engine/Input/ButtonId.cpp
OGRECave/scape
9c95ec7b6d8372a7a2a4eb6b96dcb5f2219e2bf2
[ "BSD-2-Clause" ]
48
2018-06-18T01:38:41.000Z
2022-03-25T10:29:27.000Z
Engine/Input/ButtonId.cpp
OGRECave/scape
9c95ec7b6d8372a7a2a4eb6b96dcb5f2219e2bf2
[ "BSD-2-Clause" ]
32
2018-07-23T14:17:23.000Z
2020-11-02T23:28:48.000Z
Engine/Input/ButtonId.cpp
OGRECave/scape
9c95ec7b6d8372a7a2a4eb6b96dcb5f2219e2bf2
[ "BSD-2-Clause" ]
7
2018-07-23T09:34:06.000Z
2022-02-15T09:54:16.000Z
/** * Giliam de Carpentier, Copyright (c) 2007. * Licensed under the Simplified BSD license. * See Docs/ScapeLicense.txt for details. */ #include "ScapeEngineStableHeaders.h" #include "ButtonId.h" using namespace ScapeEngine; std::map<ButtonId::EButtonId, std::string> ButtonId::getButtonIdMap() { static std::map<EButtonId, string> table; if (table.empty()) { #define ENUMID(a) \ { \ string name(#a); \ std::transform(name.begin(), name.end(), name.begin(), toupper); \ table[a] = name; \ } #define ENUM_OIS_KEYBOARD(a) a #define ENUM_OIS_MOUSE(a) a #include "ButtonId.def" #undef ENUMID #undef ENUM_OIS_KEYBOARD #undef ENUM_OIS_MOUSE } return table; } ButtonId::EButtonId ButtonId::getButtonIdFromUpperName(const string& buttonName) { #define ENUMID(a) \ { \ string name(#a); \ std::transform(name.begin(), name.end(), name.begin(), toupper); \ table[name] = a; \ } #define ENUM_OIS_KEYBOARD(a) a #define ENUM_OIS_MOUSE(a) a static std::map<string, EButtonId> table; if (table.empty()) { #include "ButtonId.def" } #undef ENUMID #undef ENUM_OIS_KEYBOARD #undef ENUM_OIS_MOUSE std::map<string, EButtonId>::iterator it = table.find(buttonName); return it != table.end() ? it->second : BUTTONID_UNKNOWN; } ButtonId::EButtonId ButtonId::getButtonIdFromName(const string& buttonName) { string name(buttonName); std::transform(name.begin(), name.end(), name.begin(), toupper); return getButtonIdFromUpperName(name); } string ButtonId::getButtonIdToUpperName(ButtonId::EButtonId button) { #define ENUMID(a) \ { \ string name(#a); \ std::transform(name.begin(), name.end(), name.begin(), toupper); \ table[(size_t)a] = name; \ } #define ENUM_OIS_KEYBOARD(a) a #define ENUM_OIS_MOUSE(a) a static std::vector<string> table; if (table.empty()) { table.resize(BUTTONID_ENUM_LENGTH, _T("BUTTONID_UNKNOWN")); #include "ButtonId.def" } return table[(int)button]; #undef ENUMID #undef ENUM_OIS_KEYBOARD #undef ENUM_OIS_MOUSE }
37.494253
108
0.431024
[ "vector", "transform" ]
4fdcf96192b5bc20a3b99514e23b2078cd0738d3
16,823
cpp
C++
Blizzlike/Trinity/Scripts/Dungeons/FrozenHalls/ForgeOfSouls/boss_devourer_of_souls.cpp
499453466/Lua-Other
43fd2b72405faf3f2074fd2a2706ef115d16faa6
[ "Unlicense" ]
2
2015-06-23T16:26:32.000Z
2019-06-27T07:45:59.000Z
Blizzlike/Trinity/Scripts/Dungeons/FrozenHalls/ForgeOfSouls/boss_devourer_of_souls.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
null
null
null
Blizzlike/Trinity/Scripts/Dungeons/FrozenHalls/ForgeOfSouls/boss_devourer_of_souls.cpp
Eduardo-Silla/Lua-Other
db610f946dbcaf81b3de9801f758e11a7bf2753f
[ "Unlicense" ]
3
2015-01-10T18:22:59.000Z
2021-04-27T21:28:28.000Z
/* * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * * 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, see <http://www.gnu.org/licenses/>. */ #include "ScriptMgr.h" #include "ScriptedCreature.h" #include "forge_of_souls.h" /* * TODO: * - Fix model id during unleash soul -> seems DB issue 36503 is missing (likewise 36504 is also missing). * - Fix outro npc movement */ enum Yells { SAY_FACE_ANGER_AGGRO = -1632010, SAY_FACE_DESIRE_AGGRO = -1632011, SAY_FACE_ANGER_SLAY_1 = -1632012, SAY_FACE_SORROW_SLAY_1 = -1632013, SAY_FACE_DESIRE_SLAY_1 = -1632014, SAY_FACE_ANGER_SLAY_2 = -1632015, SAY_FACE_SORROW_SLAY_2 = -1632016, SAY_FACE_DESIRE_SLAY_2 = -1632017, SAY_FACE_SORROW_DEATH = -1632019, SAY_FACE_DESIRE_DEATH = -1632020, EMOTE_MIRRORED_SOUL = -1632021, EMOTE_UNLEASH_SOUL = -1632022, SAY_FACE_ANGER_UNLEASH_SOUL = -1632023, SAY_FACE_SORROW_UNLEASH_SOUL = -1632024, SAY_FACE_DESIRE_UNLEASH_SOUL = -1632025, EMOTE_WAILING_SOUL = -1632026, SAY_FACE_ANGER_WAILING_SOUL = -1632027, SAY_FACE_DESIRE_WAILING_SOUL = -1632028, SAY_JAINA_OUTRO = -1632029, SAY_SYLVANAS_OUTRO = -1632030, }; enum Spells { SPELL_PHANTOM_BLAST = 68982, H_SPELL_PHANTOM_BLAST = 70322, SPELL_MIRRORED_SOUL = 69051, SPELL_WELL_OF_SOULS = 68820, SPELL_UNLEASHED_SOULS = 68939, SPELL_WAILING_SOULS_STARTING = 68912, // Initial spell cast at begining of wailing souls phase SPELL_WAILING_SOULS_BEAM = 68875, // the beam visual SPELL_WAILING_SOULS = 68873, // the actual spell H_SPELL_WAILING_SOULS = 70324, // 68871, 68873, 68875, 68876, 68899, 68912, 70324, // 68899 trigger 68871 }; enum Events { EVENT_PHANTOM_BLAST = 1, EVENT_MIRRORED_SOUL = 2, EVENT_WELL_OF_SOULS = 3, EVENT_UNLEASHED_SOULS = 4, EVENT_WAILING_SOULS = 5, EVENT_WAILING_SOULS_TICK = 6, EVENT_FACE_ANGER = 7, }; enum eEnum { DISPLAY_ANGER = 30148, DISPLAY_SORROW = 30149, DISPLAY_DESIRE = 30150, }; struct outroPosition { uint32 entry[2]; Position movePosition; } outroPositions[] = { { { NPC_CHAMPION_1_ALLIANCE, NPC_CHAMPION_1_HORDE }, { 5590.47f, 2427.79f, 705.935f, 0.802851f } }, { { NPC_CHAMPION_1_ALLIANCE, NPC_CHAMPION_1_HORDE }, { 5593.59f, 2428.34f, 705.935f, 0.977384f } }, { { NPC_CHAMPION_1_ALLIANCE, NPC_CHAMPION_1_HORDE }, { 5600.81f, 2429.31f, 705.935f, 0.890118f } }, { { NPC_CHAMPION_1_ALLIANCE, NPC_CHAMPION_1_HORDE }, { 5600.81f, 2421.12f, 705.935f, 0.890118f } }, { { NPC_CHAMPION_1_ALLIANCE, NPC_CHAMPION_1_HORDE }, { 5601.43f, 2426.53f, 705.935f, 0.890118f } }, { { NPC_CHAMPION_1_ALLIANCE, NPC_CHAMPION_1_HORDE }, { 5601.55f, 2418.36f, 705.935f, 1.15192f } }, { { NPC_CHAMPION_1_ALLIANCE, NPC_CHAMPION_1_HORDE }, { 5598, 2429.14f, 705.935f, 1.0472f } }, { { NPC_CHAMPION_1_ALLIANCE, NPC_CHAMPION_1_HORDE }, { 5594.04f, 2424.87f, 705.935f, 1.15192f } }, { { NPC_CHAMPION_1_ALLIANCE, NPC_CHAMPION_1_HORDE }, { 5597.89f, 2421.54f, 705.935f, 0.610865f } }, { { NPC_CHAMPION_2_ALLIANCE, NPC_CHAMPION_2_HORDE }, { 5598.57f, 2434.62f, 705.935f, 1.13446f } }, { { NPC_CHAMPION_2_ALLIANCE, NPC_CHAMPION_2_HORDE }, { 5585.46f, 2417.99f, 705.935f, 1.06465f } }, { { NPC_CHAMPION_2_ALLIANCE, NPC_CHAMPION_2_HORDE }, { 5605.81f, 2428.42f, 705.935f, 0.820305f } }, { { NPC_CHAMPION_2_ALLIANCE, NPC_CHAMPION_2_HORDE }, { 5591.61f, 2412.66f, 705.935f, 0.925025f } }, { { NPC_CHAMPION_2_ALLIANCE, NPC_CHAMPION_2_HORDE }, { 5593.9f, 2410.64f, 705.935f, 0.872665f } }, { { NPC_CHAMPION_2_ALLIANCE, NPC_CHAMPION_2_HORDE }, { 5586.76f, 2416.73f, 705.935f, 0.942478f } }, { { NPC_CHAMPION_2_ALLIANCE, NPC_CHAMPION_3_HORDE }, { 5592.23f, 2419.14f, 705.935f, 0.855211f } }, { { NPC_CHAMPION_2_ALLIANCE, NPC_CHAMPION_3_HORDE }, { 5594.61f, 2416.87f, 705.935f, 0.907571f } }, { { NPC_CHAMPION_2_ALLIANCE, NPC_CHAMPION_3_HORDE }, { 5589.77f, 2421.03f, 705.935f, 0.855211f } }, { { NPC_KORELN, NPC_LORALEN }, { 5602.58f, 2435.95f, 705.935f, 0.959931f } }, { { NPC_ELANDRA, NPC_KALIRA }, { 5606.13f, 2433.16f, 705.935f, 0.785398f } }, { { NPC_JAINA_PART2, NPC_SYLVANAS_PART2 }, { 5606.12f, 2436.6f, 705.935f, 0.890118f } }, { { 0, 0 }, { 0.0f, 0.0f, 0.0f, 0.0f } } }; Position const CrucibleSummonPos = {5672.294f,2520.686f, 713.4386f, 0.9599311f}; #define DATA_THREE_FACED 1 class boss_devourer_of_souls : public CreatureScript { public: boss_devourer_of_souls() : CreatureScript("boss_devourer_of_souls") { } struct boss_devourer_of_soulsAI : public BossAI { boss_devourer_of_soulsAI(Creature* creature) : BossAI(creature, DATA_DEVOURER_EVENT) { } void InitializeAI() { if (!instance || static_cast<InstanceMap*>(me->GetMap())->GetScriptId() != sObjectMgr->GetScriptId(FoSScriptName)) me->IsAIEnabled = false; else if (!me->isDead()) Reset(); } void Reset() { me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); me->SetDisplayId(DISPLAY_ANGER); me->SetReactState(REACT_AGGRESSIVE); events.Reset(); summons.DespawnAll(); threeFaced = true; mirroredSoulTarget = 0; instance->SetData(DATA_DEVOURER_EVENT, NOT_STARTED); } void EnterCombat(Unit* /*who*/) { DoScriptText(RAND(SAY_FACE_ANGER_AGGRO, SAY_FACE_DESIRE_AGGRO), me); if (!me->FindNearestCreature(NPC_CRUCIBLE_OF_SOULS, 60)) // Prevent double spawn instance->instance->SummonCreature(NPC_CRUCIBLE_OF_SOULS, CrucibleSummonPos); events.ScheduleEvent(EVENT_PHANTOM_BLAST, 5000); events.ScheduleEvent(EVENT_MIRRORED_SOUL, 8000); events.ScheduleEvent(EVENT_WELL_OF_SOULS, 30000); events.ScheduleEvent(EVENT_UNLEASHED_SOULS, 20000); events.ScheduleEvent(EVENT_WAILING_SOULS, urand(60000, 70000)); instance->SetData(DATA_DEVOURER_EVENT, IN_PROGRESS); } void DamageTaken(Unit* /*pDoneBy*/, uint32 &uiDamage) { if (mirroredSoulTarget && me->HasAura(SPELL_MIRRORED_SOUL)) { if (Player* player = Unit::GetPlayer(*me, mirroredSoulTarget)) { if (player->GetAura(SPELL_MIRRORED_SOUL)) { int32 mirrorDamage = (uiDamage* 45)/100; me->CastCustomSpell(player, 69034, &mirrorDamage, 0, 0, true); } else mirroredSoulTarget = 0; } } } void KilledUnit(Unit* victim) { if (victim->GetTypeId() != TYPEID_PLAYER) return; int32 textId = 0; switch (me->GetDisplayId()) { case DISPLAY_ANGER: textId = RAND(SAY_FACE_ANGER_SLAY_1, SAY_FACE_ANGER_SLAY_2); break; case DISPLAY_SORROW: textId = RAND(SAY_FACE_SORROW_SLAY_1, SAY_FACE_SORROW_SLAY_2); break; case DISPLAY_DESIRE: textId = RAND(SAY_FACE_DESIRE_SLAY_1, SAY_FACE_DESIRE_SLAY_2); break; default: break; } if (textId) DoScriptText(textId, me); } void JustDied(Unit* /*killer*/) { summons.DespawnAll(); Position spawnPoint = {5618.139f, 2451.873f, 705.854f, 0}; DoScriptText(RAND(SAY_FACE_SORROW_DEATH, SAY_FACE_DESIRE_DEATH), me); instance->SetData(DATA_DEVOURER_EVENT, DONE); int32 entryIndex; if (instance->GetData(DATA_TEAM_IN_INSTANCE) == ALLIANCE) entryIndex = 0; else entryIndex = 1; for (int8 i = 0; outroPositions[i].entry[entryIndex] != 0; ++i) { if (Creature* summon = me->SummonCreature(outroPositions[i].entry[entryIndex], spawnPoint, TEMPSUMMON_DEAD_DESPAWN)) { summon->GetMotionMaster()->MovePoint(0, outroPositions[i].movePosition); if (summon->GetEntry() == NPC_JAINA_PART2) DoScriptText(SAY_JAINA_OUTRO, summon); else if (summon->GetEntry() == NPC_SYLVANAS_PART2) DoScriptText(SAY_SYLVANAS_OUTRO, summon); } } } void SpellHitTarget(Unit* /*target*/, const SpellInfo* spell) { if (spell->Id == H_SPELL_PHANTOM_BLAST) threeFaced = false; } uint32 GetData(uint32 type) { if (type == DATA_THREE_FACED) return threeFaced; return 0; } void UpdateAI(const uint32 diff) { // Return since we have no target if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STATE_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_PHANTOM_BLAST: DoCastVictim(SPELL_PHANTOM_BLAST); events.ScheduleEvent(EVENT_PHANTOM_BLAST, 5000); break; case EVENT_MIRRORED_SOUL: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 0, true)) { mirroredSoulTarget = target->GetGUID(); DoCast(target, SPELL_MIRRORED_SOUL); DoScriptText(EMOTE_MIRRORED_SOUL, me); } events.ScheduleEvent(EVENT_MIRRORED_SOUL, urand(15000, 30000)); break; case EVENT_WELL_OF_SOULS: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) DoCast(target, SPELL_WELL_OF_SOULS); events.ScheduleEvent(EVENT_WELL_OF_SOULS, 20000); break; case EVENT_UNLEASHED_SOULS: if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) DoCast(target, SPELL_UNLEASHED_SOULS); me->SetDisplayId(DISPLAY_SORROW); DoScriptText(RAND(SAY_FACE_ANGER_UNLEASH_SOUL, SAY_FACE_SORROW_UNLEASH_SOUL, SAY_FACE_DESIRE_UNLEASH_SOUL), me); DoScriptText(EMOTE_UNLEASH_SOUL, me); events.ScheduleEvent(EVENT_UNLEASHED_SOULS, 30000); events.ScheduleEvent(EVENT_FACE_ANGER, 5000); break; case EVENT_FACE_ANGER: me->SetDisplayId(DISPLAY_ANGER); break; case EVENT_WAILING_SOULS: me->SetDisplayId(DISPLAY_DESIRE); DoScriptText(RAND(SAY_FACE_ANGER_WAILING_SOUL, SAY_FACE_DESIRE_WAILING_SOUL), me); DoScriptText(EMOTE_WAILING_SOUL, me); DoCast(me, SPELL_WAILING_SOULS_STARTING); if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0)) { me->SetOrientation(me->GetAngle(target)); me->SendMovementFlagUpdate(); DoCast(me, SPELL_WAILING_SOULS_BEAM); } beamAngle = me->GetOrientation(); beamAngleDiff = M_PI/30.0f; // PI/2 in 15 sec = PI/30 per tick if (RAND(true, false)) beamAngleDiff = -beamAngleDiff; me->InterruptNonMeleeSpells(false); me->SetReactState(REACT_PASSIVE); //Remove any target me->SetTarget(0); me->GetMotionMaster()->Clear(); me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); wailingSoulTick = 15; events.DelayEvents(18000); // no other events during wailing souls events.ScheduleEvent(EVENT_WAILING_SOULS_TICK, 3000); // first one after 3 secs. break; case EVENT_WAILING_SOULS_TICK: beamAngle += beamAngleDiff; me->SetOrientation(beamAngle); me->SendMovementFlagUpdate(); me->StopMoving(); DoCast(me, SPELL_WAILING_SOULS); if (--wailingSoulTick) events.ScheduleEvent(EVENT_WAILING_SOULS_TICK, 1000); else { me->SetReactState(REACT_AGGRESSIVE); me->SetDisplayId(DISPLAY_ANGER); me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_DISABLE_MOVE); me->GetMotionMaster()->MoveChase(me->getVictim()); events.ScheduleEvent(EVENT_WAILING_SOULS, urand(60000, 70000)); } break; } } DoMeleeAttackIfReady(); } private: bool threeFaced; // wailing soul event float beamAngle; float beamAngleDiff; int8 wailingSoulTick; uint64 mirroredSoulTarget; }; CreatureAI* GetAI(Creature* creature) const { return new boss_devourer_of_soulsAI(creature); } }; class achievement_three_faced : public AchievementCriteriaScript { public: achievement_three_faced() : AchievementCriteriaScript("achievement_three_faced") { } bool OnCheck(Player* /*player*/, Unit* target) { if (!target) return false; if (Creature* Devourer = target->ToCreature()) if (Devourer->AI()->GetData(DATA_THREE_FACED)) return true; return false; } }; void AddSC_boss_devourer_of_souls() { new boss_devourer_of_souls(); new achievement_three_faced(); }
41.952618
140
0.517625
[ "model" ]
4fe2568726971f999376334a59288f576a86f5f0
3,250
cpp
C++
code archive/USACO/2019jan-platinum1.cpp
brianbbsu/program
c4505f2b8c0b91010e157db914a63c49638516bc
[ "MIT" ]
4
2018-04-08T08:07:58.000Z
2021-06-07T14:55:24.000Z
code archive/USACO/2019jan-platinum1.cpp
brianbbsu/program
c4505f2b8c0b91010e157db914a63c49638516bc
[ "MIT" ]
null
null
null
code archive/USACO/2019jan-platinum1.cpp
brianbbsu/program
c4505f2b8c0b91010e157db914a63c49638516bc
[ "MIT" ]
1
2018-10-29T12:37:25.000Z
2018-10-29T12:37:25.000Z
//{ #include<bits/stdc++.h> using namespace std; typedef int ll; typedef double lf; typedef pair<ll,ll> ii; #define REP(i,n) for(ll i=0;i<n;i++) #define REP1(i,n) for(ll i=1;i<=n;i++) #define FILL(i,n) memset(i,n,sizeof i) #define X first #define Y second #define SZ(_a) (int)_a.size() #define ALL(_a) _a.begin(),_a.end() #define pb push_back #ifdef brian #define debug(...) do{\ fprintf(stderr,"%s - %d (%s) = ",__PRETTY_FUNCTION__,__LINE__,#__VA_ARGS__);\ _do(__VA_ARGS__);\ }while(0) template<typename T>void _do(T &&_x){cerr<<_x<<endl;} template<typename T,typename ...S> void _do(T &&_x,S &&..._t){cerr<<_x<<" ,";_do(_t...);} template<typename _a,typename _b> ostream& operator << (ostream &_s,const pair<_a,_b> &_p){return _s<<"("<<_p.X<<","<<_p.Y<<")";} template<typename It> ostream& _OUTC(ostream &_s,It _ita,It _itb) { _s<<"{"; for(It _it=_ita;_it!=_itb;_it++) { _s<<(_it==_ita?"":",")<<*_it; } _s<<"}"; return _s; } template<typename _a> ostream &operator << (ostream &_s,vector<_a> &_c){return _OUTC(_s,ALL(_c));} template<typename _a> ostream &operator << (ostream &_s,set<_a> &_c){return _OUTC(_s,ALL(_c));} template<typename _a,typename _b> ostream &operator << (ostream &_s,map<_a,_b> &_c){return _OUTC(_s,ALL(_c));} template<typename _t> void pary(_t _a,_t _b){_OUTC(cerr,_a,_b);cerr<<endl;} #define IOS() #else #define debug(...) #define pary(...) #define endl '\n' #define IOS() ios_base::sync_with_stdio(0);cin.tie(0); #endif // brian //} string _taskname; void _init() { #ifndef brian freopen((_taskname+".in").c_str(), "r", stdin); freopen((_taskname+".out").c_str(),"w",stdout); #endif } void _end() { #ifndef brian fclose( stdin); fclose(stdout); #endif } const ll MAXn=3e5+5,MAXlg=__lg(MAXn)+2; const ll MOD=1000000007; const ll INF=ll(1e9); namespace seg{ ll N, d[4 * MAXn]; void build(ll n) { N = n; for(int i = 1;i < 2 * N;i++)d[i] = INF; } void ins(ll x,ll k) { for(d[x += N] = k;x > 1;x>>=1)d[x>>1] = min(d[x], d[x^1]); } ll qr(ll l,ll r) { ll ret = INF; for(l += N, r += N;l < r;l >>= 1, r >>= 1) { if(l&1)ret = min(ret, d[l++]); if(r&1)ret = min(ret, d[--r]); } return ret; } }; ll d[MAXn]; map<ll, deque<ii>> dq; ll n, k; void ins(deque<ii> &q, ii p) { while(SZ(q) && q.back().Y >= p.Y)q.pop_back(); q.pb(p); } int main() { //IOS(); _taskname = "redistricting"; _init(); cin>>n>>k; string s; cin>>s; REP1(i,n)d[i] = (s[i-1] == 'H'?1:-1); REP1(i,n)d[i] = d[i-1] + d[i]; seg::build(2 * n + 1); ins(dq[0+n], ii(0, 0)); seg::ins(0+n, 0); ll lst = 0; REP1(i, n) { ll t = i - k - 1; if(t >= 0 && dq[d[t]+n].front().X == t) { dq[d[t]+n].pop_front(); if(SZ(dq[d[t]+n]))seg::ins(d[t]+n, dq[d[t]+n].front().Y); else seg::ins(d[t]+n, INF); } ll tmp; tmp = min(seg::qr(0, d[i] + n), seg::qr(d[i] + n, 2 * n + 1) + 1); ins(dq[d[i] + n], ii(i, tmp)); seg::ins(d[i] + n, dq[d[i] + n].front().Y); lst = tmp; } cout<<lst<<endl; _end(); }
24.43609
129
0.52
[ "vector" ]
4fe27fb7833c9df78a6bba58f58fde1a5b9b4575
11,233
cpp
C++
src/Storage.cpp
j9263178/Cytnx
cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b
[ "Apache-2.0" ]
11
2020-04-14T15:45:42.000Z
2022-03-31T14:37:03.000Z
src/Storage.cpp
j9263178/Cytnx
cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b
[ "Apache-2.0" ]
38
2019-08-02T15:15:51.000Z
2022-03-04T19:07:02.000Z
src/Storage.cpp
j9263178/Cytnx
cf7fb1cff75c1cea14fbbc370fd8e4d86d0ddc8b
[ "Apache-2.0" ]
7
2019-07-17T07:50:55.000Z
2021-07-03T06:44:52.000Z
#ifdef UNI_OMP #include <omp.h> #endif #include "Storage.hpp" #include <iostream> using namespace std; namespace cytnx{ Storage_init_interface __SII; std::ostream& operator<<(std::ostream& os, const Storage &in){ in.print(); return os; } bool Storage::operator==(const Storage &rhs){ cytnx_error_msg(this->dtype() != rhs.dtype(),"[ERROR] cannot compare two Storage with different type.%s","\n"); if(this->size() != rhs.size()) return false; switch(this->dtype()){ case Type.ComplexDouble: for(cytnx_uint64 i=0;i<this->size();i++){ if(this->at<cytnx_complex128>(i) != rhs.at<cytnx_complex128>(i)) return false; } break; case Type.ComplexFloat: for(cytnx_uint64 i=0;i<this->size();i++){ if(this->at<cytnx_complex64>(i) != rhs.at<cytnx_complex64>(i)) return false; } break; case Type.Double: for(cytnx_uint64 i=0;i<this->size();i++){ if(this->at<cytnx_double>(i) != rhs.at<cytnx_double>(i)) return false; } break; case Type.Float: for(cytnx_uint64 i=0;i<this->size();i++){ if(this->at<cytnx_float>(i) != rhs.at<cytnx_float>(i)) return false; } break; case Type.Int64: for(cytnx_uint64 i=0;i<this->size();i++){ if(this->at<cytnx_int64>(i) != rhs.at<cytnx_int64>(i)) return false; } break; case Type.Uint64: for(cytnx_uint64 i=0;i<this->size();i++){ if(this->at<cytnx_uint64>(i) != rhs.at<cytnx_uint64>(i)) return false; } break; case Type.Int32: for(cytnx_uint64 i=0;i<this->size();i++){ if(this->at<cytnx_int32>(i) != rhs.at<cytnx_int32>(i)) return false; } break; case Type.Uint32: for(cytnx_uint64 i=0;i<this->size();i++){ if(this->at<cytnx_uint32>(i) != rhs.at<cytnx_uint32>(i)) return false; } break; case Type.Int16: for(cytnx_uint64 i=0;i<this->size();i++){ if(this->at<cytnx_int16>(i) != rhs.at<cytnx_int16>(i)) return false; } break; case Type.Uint16: for(cytnx_uint64 i=0;i<this->size();i++){ if(this->at<cytnx_uint16>(i) != rhs.at<cytnx_uint16>(i)) return false; } break; case Type.Bool: for(cytnx_uint64 i=0;i<this->size();i++){ if(this->at<cytnx_bool>(i) != rhs.at<cytnx_bool>(i)) return false; } break; default: cytnx_error_msg(true,"[ERROR] fatal internal, Storage has invalid type.%s","\n"); } return true; } bool Storage::operator!=(const Storage &rhs){ return !(*this==rhs); } void Storage::Save(const std::string &fname) const{ fstream f; f.open((fname+".cyst"),ios::out|ios::trunc|ios::binary); if(!f.is_open()){ cytnx_error_msg(true,"[ERROR] invalid file path for save.%s","\n"); } this->_Save(f); f.close(); } void Storage::Save(const char* fname) const{ fstream f; string ffname = string(fname) + ".cyst"; f.open(ffname,ios::out|ios::trunc|ios::binary); if(!f.is_open()){ cytnx_error_msg(true,"[ERROR] invalid file path for save.%s","\n"); } this->_Save(f); f.close(); } void Storage::Tofile(const std::string &fname) const{ fstream f; f.open(fname,ios::out|ios::trunc|ios::binary); if(!f.is_open()){ cytnx_error_msg(true,"[ERROR] invalid file path for save.%s","\n"); } this->_Savebinary(f); f.close(); } void Storage::Tofile(const char* fname) const{ fstream f; string ffname = string(fname); f.open(ffname,ios::out|ios::trunc|ios::binary); if(!f.is_open()){ cytnx_error_msg(true,"[ERROR] invalid file path for save.%s","\n"); } this->_Savebinary(f); f.close(); } void Storage::Tofile(fstream &f) const{ if(!f.is_open()){ cytnx_error_msg(true,"[ERROR] invalid file path for save.%s","\n"); } this->_Savebinary(f); } void Storage::_Save(fstream &f) const{ //header //check: cytnx_error_msg(!f.is_open(),"[ERROR] invalid fstream!.%s","\n"); unsigned int IDDs = 999; f.write((char*)&IDDs,sizeof(unsigned int)); f.write((char*)&this->size(),sizeof(unsigned long long)); f.write((char*)&this->dtype(),sizeof(unsigned int)); f.write((char*)&this->device(),sizeof(int)); //data: if(this->device() == Device.cpu){ f.write((char*)this->_impl->Mem,Type.typeSize(this->dtype())*this->size()); }else{ #ifdef UNI_GPU checkCudaErrors(cudaSetDevice(this->device())); void *htmp = malloc(Type.typeSize(this->dtype())*this->size()); checkCudaErrors(cudaMemcpy(htmp,this->_impl->Mem,Type.typeSize(this->dtype())*this->size(),cudaMemcpyDeviceToHost)); f.write((char*)htmp,Type.typeSize(this->dtype())*this->size()); free(htmp); #else cytnx_error_msg(true,"ERROR internal fatal error in Save Storage%s","\n"); #endif } } void Storage::_Savebinary(fstream &f) const{ //header //check: cytnx_error_msg(!f.is_open(),"[ERROR] invalid fstream!.%s","\n"); //data: if(this->device() == Device.cpu){ f.write((char*)this->_impl->Mem,Type.typeSize(this->dtype())*this->size()); }else{ #ifdef UNI_GPU checkCudaErrors(cudaSetDevice(this->device())); void *htmp = malloc(Type.typeSize(this->dtype())*this->size()); checkCudaErrors(cudaMemcpy(htmp,this->_impl->Mem,Type.typeSize(this->dtype())*this->size(),cudaMemcpyDeviceToHost)); f.write((char*)htmp,Type.typeSize(this->dtype())*this->size()); free(htmp); #else cytnx_error_msg(true,"ERROR internal fatal error in Save Storage%s","\n"); #endif } } Storage Storage::Fromfile(const char* fname, const unsigned int &dtype, const cytnx_int64 &count){ return Storage::Fromfile(string(fname),dtype,count); } Storage Storage::Fromfile(const std::string &fname, const unsigned int &dtype, const cytnx_int64 &count){ cytnx_error_msg(dtype==Type.Void,"[ERROR] cannot have Void dtype.%s","\n"); cytnx_error_msg(count==0,"[ERROR] count cannot be zero!%s","\n"); Storage out; cytnx_uint64 Nbytes; cytnx_uint64 Nelem; //check size: ifstream jf; //std::cout << fname << std::endl; jf.open(fname,ios::ate|ios::binary); if(!jf.is_open()){ cytnx_error_msg(true,"[ERROR] invalid file path for load.%s","\n"); } Nbytes = jf.tellg(); jf.close(); fstream f; //check if type match? cytnx_error_msg(Nbytes%Type.typeSize(dtype),"[ERROR] the total size of file is not an interval of assigned dtype.%s","\n"); //check count smaller than Nelem: if(count < 0 ) Nelem = Nbytes/Type.typeSize(dtype); else{ cytnx_error_msg(count > Nelem, "[ERROR] count exceed the total # of elements %d in file.\n",Nelem); Nelem = count; } f.open(fname,ios::in|ios::binary); if(!f.is_open()){ cytnx_error_msg(true,"[ERROR] invalid file path for load.%s","\n"); } out._Loadbinary(f,dtype,Nelem); f.close(); return out; } Storage Storage::Load(const std::string &fname){ Storage out; fstream f; f.open(fname,ios::in|ios::binary); if(!f.is_open()){ cytnx_error_msg(true,"[ERROR] invalid file path for load.%s","\n"); } out._Load(f); f.close(); return out; } Storage Storage::Load(const char* fname){ Storage out; fstream f; f.open(fname,ios::in|ios::binary); if(!f.is_open()){ cytnx_error_msg(true,"[ERROR] invalid file path for load.%s","\n"); } out._Load(f); f.close(); return out; } void Storage::_Load(fstream &f){ //header unsigned long long sz; unsigned int dt; int dv; //check: cytnx_error_msg(!f.is_open(),"[ERROR] invalid fstream!.%s","\n"); //checking IDD unsigned int tmpIDDs; f.read((char*)&tmpIDDs,sizeof(unsigned int)); if(tmpIDDs != 999){ cytnx_error_msg(true,"[ERROR] the Load file is not the Storage object!\n","%s"); } f.read((char*)&sz,sizeof(unsigned long long)); f.read((char*)&dt,sizeof(unsigned int)); f.read((char*)&dv,sizeof(int)); if(dv != Device.cpu){ if(dv >= Device.Ngpus){ cytnx_warning_msg(true,"[Warning!!] the original device ID does not exists. the tensor will be put on CPU, please use .to() or .to_() to move to desire devices.%s","\n"); dv = -1; } } this->_impl = __SII.USIInit[dt](); this->_impl->Init(sz,dv); //data: if(dv == Device.cpu){ f.read((char*)this->_impl->Mem,Type.typeSize(dt)*sz); }else{ #ifdef UNI_GPU checkCudaErrors(cudaSetDevice(dv)); void *htmp = malloc(Type.typeSize(dt)*sz); f.read((char*)htmp,Type.typeSize(dt)*sz); checkCudaErrors(cudaMemcpy(this->_impl->Mem,htmp,Type.typeSize(dt)*sz,cudaMemcpyHostToDevice)); free(htmp); #else cytnx_error_msg(true,"ERROR internal fatal error in Load Storage%s","\n"); #endif } } void Storage::_Loadbinary(fstream &f, const unsigned int &dtype, const cytnx_uint64 &Nelem){ // before enter this func, makesure // 1. dtype is not void. // 2. the Nelement is consistent and smaller than the file size, and should not be zero! //check: cytnx_error_msg(!f.is_open(),"[ERROR] invalid fstream!.%s","\n"); this->_impl = __SII.USIInit[dtype](); this->_impl->Init(Nelem,Device.cpu); f.read((char*)this->_impl->Mem,Type.typeSize(dtype)*Nelem); } Scalar::Sproxy Storage::operator()(const cytnx_uint64 &idx){ Scalar::Sproxy out(this->_impl,idx); return out; } }
34.457055
186
0.519274
[ "object" ]
4fe379245d8b48a0f844611962557cda8c960127
254
cpp
C++
Source/SA/Render/Base/Shader/Bindings/AShaderBinding.cpp
SapphireSuite/Engine
f29821853aec6118508f31d3e063e83e603f52dd
[ "MIT" ]
1
2022-01-20T23:17:18.000Z
2022-01-20T23:17:18.000Z
Source/SA/Render/Base/Shader/Bindings/AShaderBinding.cpp
SapphireSuite/Engine
f29821853aec6118508f31d3e063e83e603f52dd
[ "MIT" ]
null
null
null
Source/SA/Render/Base/Shader/Bindings/AShaderBinding.cpp
SapphireSuite/Engine
f29821853aec6118508f31d3e063e83e603f52dd
[ "MIT" ]
null
null
null
// Copyright (c) 2021 Sapphire's Suite. All Rights Reserved. #include <Render/Base/Shader/Bindings/AShaderBinding.hpp> namespace Sa { AShaderBinding::AShaderBinding(uint32 _binding, uint32 _set) noexcept : binding{ _binding }, set{ _set } { } }
19.538462
72
0.732283
[ "render" ]
4fe6ecae47d2cfd21f6d5075c12ef98ba10b848b
14,590
cpp
C++
neopg/parser/openpgp.cpp
mehrdad-shokri/neopg
05b370c04ffc019e55d75ab262d17abe6e69cafc
[ "BSD-2-Clause" ]
224
2017-10-29T09:48:00.000Z
2021-07-21T10:27:14.000Z
neopg/parser/openpgp.cpp
mehrdad-shokri/neopg
05b370c04ffc019e55d75ab262d17abe6e69cafc
[ "BSD-2-Clause" ]
66
2017-10-29T16:17:55.000Z
2020-11-30T18:53:40.000Z
neopg/parser/openpgp.cpp
mehrdad-shokri/neopg
05b370c04ffc019e55d75ab262d17abe6e69cafc
[ "BSD-2-Clause" ]
22
2017-10-29T19:55:45.000Z
2020-01-04T13:25:50.000Z
// OpenPGP parser // Copyright 2017-2018 The NeoPG developers // // NeoPG is released under the Simplified BSD License (see license.txt) #include <neopg/parser/openpgp.h> #include <neopg/intern/cplusplus.h> #include <neopg/intern/pegtl.h> #include <functional> using namespace NeoPG; using namespace tao::neopg_pegtl; namespace openpgp { // The OpenPGP parser is stateful (due to the length field), so the state, // grammar and actions are tightly coupled. struct state { RawPacketSink& sink; PacketType packet_type; size_t packet_pos; std::unique_ptr<PacketHeader> header; std::unique_ptr<NewPacketLength> length; // The exception object if a packet could not be parsed. std::unique_ptr<ParserError> exc; // The length of the current packet body (or part of it). size_t packet_len; // This indicates that we have a partial packet data frame. bool partial; // This indicates that we have started a partial packet. bool started; state(RawPacketSink& a_sink) : sink(a_sink) {} }; // A custom rule to match packet data. This is stateful, because it requires // the preceeding length information, and matches exactly st.packet_len bytes. struct packet_body_data { using analyze_t = analysis::generic<analysis::rule_type::ANY>; template <apply_mode A, rewind_mode M, template <typename...> class Action, template <typename...> class Control, typename Input> static bool match(Input& in, state& st) { size_t available = in.size(st.packet_len); if (available >= st.packet_len) { in.bump(st.packet_len); return true; } else { uint32_t max = RawPacketParser::MAX_PARSER_BUFFER; available = in.size(max); if (st.packet_len > max && available == max) { // Best we can do at this point is to skip over the packet and set an // error. uint32_t skip = st.packet_len; while (skip > 0) { assert(skip >= available); in.bump(available); in.discard(); skip -= available; uint32_t skip_this = max; if (skip < skip_this) skip_this = skip; available = in.size(skip_this); if (available < skip_this) { st.exc = NeoPG::make_unique<ParserError>(parser_error( "packet too short (while skipping too large packet)", in)); skip = available; // Fallthrough for one last iteration. } } if (!st.exc) st.exc = NeoPG::make_unique<ParserError>( parser_error("packet too large", in)); st.packet_len = 0; return true; } else { in.bump(available); in.discard(); st.packet_len = 0; st.exc = NeoPG::make_unique<ParserError>( parser_error("packet too short", in)); return true; } } // Not reached. return false; } }; // namespace openpgp // We discard the input buffer so that we do not need to account for the // packet or length header in the max buffer size calculation (so we can use a // power of two rather than a power of two plus a small number of bytes). struct packet_body : seq<discard, packet_body_data> {}; // For old packets of indeterminate length, we set an arbitrary chunk size with // the packet_body rule, and finish up with packet_body_data_rest. #define INDETERMINATE_LENGTH_CHUNK_SIZE 8192 // We do not discard the input buffer here, as we come here after // back-tracking from packet_body, and we want to preserve the data. struct packet_body_data_rest : until<eof> {}; struct packet_body_indeterminate : seq<star<packet_body>, packet_body_data_rest> {}; struct old_packet_length_one : bytes<1> {}; struct old_packet_length_two : bytes<2> {}; struct old_packet_length_four : bytes<4> {}; // Action here sets the packet length to INDETERMINATE_LENGTH_CHUNK_SIZE. struct old_packet_length_na : success {}; struct old_packet_tag : any {}; struct is_old_packet_with_length_one : at<uint8::mask_one<0x03, 0x00>> {}; struct is_old_packet_with_length_two : at<uint8::mask_one<0x03, 0x01>> {}; struct is_old_packet_with_length_four : at<uint8::mask_one<0x03, 0x02>> {}; struct is_old_packet_with_length_na : at<uint8::mask_one<0x03, 0x03>> {}; struct old_packet_with_length_one : seq<is_old_packet_with_length_one, old_packet_tag, old_packet_length_one, packet_body> {}; struct old_packet_with_length_two : seq<is_old_packet_with_length_two, old_packet_tag, old_packet_length_two, packet_body> {}; struct old_packet_with_length_four : seq<is_old_packet_with_length_four, old_packet_tag, old_packet_length_four, packet_body> {}; struct old_packet_with_length_na : seq<is_old_packet_with_length_na, old_packet_tag, old_packet_length_na, packet_body_indeterminate> {}; // Old packets have bit 6 clear. struct is_old_packet : at<uint8::mask_one<0x40, 0x00>> {}; // For old packets, the length type is encoded in the tag. We differentiate // before consuming the tag. struct old_packet : seq<is_old_packet, sor<old_packet_with_length_one, old_packet_with_length_two, old_packet_with_length_four, old_packet_with_length_na>> {}; struct new_packet_length_one : uint8::range<0x00, 0xbf> {}; struct new_packet_length_two : seq<uint8::range<0xc0, 0xdf>, any> {}; struct new_packet_length_partial : uint8::range<0xe0, 0xfe> {}; struct new_packet_length_five : seq<one<(char)0xff>, bytes<4>> {}; struct new_packet_data_partial : seq<new_packet_length_partial, packet_body> {}; struct new_packet_data_definite : seq<sor<new_packet_length_one, new_packet_length_two, new_packet_length_five>, packet_body> {}; // New packet data always ends with a definite length part, optionally // preceeded by an arbitrary number of partial data parts. struct new_packet_data : seq<star<new_packet_data_partial>, new_packet_data_definite> {}; // A new packet tag has the packet type in bit 0-5 (see action). struct new_packet_tag : any {}; // A new packet tag has bit 6 set. struct is_new_packet : at<uint8::mask_one<0x40, 0x40>> {}; // A new packet consists of a tag and one or more length and data parts. struct new_packet : seq<is_new_packet, new_packet_tag, new_packet_data> {}; // Every packet starts with a tag that has bit 7 set. struct is_packet : at<uint8::mask_one<0x80, 0x80>> {}; // A packet is either in the new or old format. struct packet : seq<discard, is_packet, sor<new_packet, old_packet>> {}; // OpenPGP consists of a sequence of packets. struct grammar : seq<until<eof, packet>, must<eof>> {}; template <typename Rule> struct action : nothing<Rule> {}; template <> struct action<old_packet_tag> { template <typename Input> static void apply(const Input& in, state& st) { auto val0 = (in.peek_byte() >> 2) & 0xf; st.packet_type = (PacketType)val0; st.packet_pos = in.position().byte; } }; template <> struct action<old_packet_length_one> { template <typename Input> static void apply(const Input& in, state& st) { auto match = in.begin(); st.packet_len = in.peek_byte(); st.header = NeoPG::make_unique<OldPacketHeader>( st.packet_type, st.packet_len, PacketLengthType::OneOctet); st.header->m_offset = st.packet_pos; } }; template <> struct action<old_packet_length_two> { template <typename Input> static void apply(const Input& in, state& st) { std::string str = in.string(); st.packet_len = (in.peek_byte(0) << 8) + in.peek_byte(1); st.header = NeoPG::make_unique<OldPacketHeader>( st.packet_type, st.packet_len, PacketLengthType::TwoOctet); st.header->m_offset = st.packet_pos; } }; template <> struct action<old_packet_length_four> { template <typename Input> static void apply(const Input& in, state& st) { auto val0 = (uint32_t)in.peek_byte(0); auto val1 = (uint32_t)in.peek_byte(1); auto val2 = (uint32_t)in.peek_byte(2); auto val3 = (uint32_t)in.peek_byte(3); st.packet_len = (val0 << 24) + (val1 << 16) + (val2 << 8) + val3; st.header = NeoPG::make_unique<OldPacketHeader>( st.packet_type, st.packet_len, PacketLengthType::FourOctet); st.header->m_offset = st.packet_pos; } }; template <> struct action<old_packet_length_na> { template <typename Input> static void apply(const Input& in, state& st) { st.packet_len = INDETERMINATE_LENGTH_CHUNK_SIZE; st.header = NeoPG::make_unique<OldPacketHeader>( st.packet_type, st.packet_len, PacketLengthType::Indeterminate); st.header->m_offset = st.packet_pos; // Simulate a partial packet (we finish differently with // packet_body_data_rest). st.partial = true; } }; // Extract packet type from new packet tag. template <> struct action<new_packet_tag> { template <typename Input> static void apply(const Input& in, state& st) { auto val0 = in.peek_byte() & 0x3f; st.packet_type = (PacketType)val0; st.packet_pos = in.position().byte; } }; template <> struct action<new_packet_length_one> { template <typename Input> static void apply(const Input& in, state& st) { st.packet_len = in.peek_byte(); if (st.started == false) { st.header = NeoPG::make_unique<NewPacketHeader>( st.packet_type, st.packet_len, PacketLengthType::OneOctet); st.header->m_offset = st.packet_pos; } else { st.length = NeoPG::make_unique<NewPacketLength>( st.packet_len, PacketLengthType::OneOctet); } st.partial = false; } }; // namespace openpgp template <> struct action<new_packet_length_two> { template <typename Input> static void apply(const Input& in, state& st) { st.packet_len = ((in.peek_byte() - 0xc0) << 8) + in.peek_byte(1) + 192; if (st.started == false) { st.header = NeoPG::make_unique<NewPacketHeader>( st.packet_type, st.packet_len, PacketLengthType::TwoOctet); st.header->m_offset = st.packet_pos; } else { st.length = NeoPG::make_unique<NewPacketLength>( st.packet_len, PacketLengthType::TwoOctet); } st.partial = false; } }; template <> struct action<new_packet_length_five> { template <typename Input> static void apply(const Input& in, state& st) { auto val0 = (uint32_t)in.peek_byte(1); auto val1 = (uint32_t)in.peek_byte(2); auto val2 = (uint32_t)in.peek_byte(3); auto val3 = (uint32_t)in.peek_byte(4); st.packet_len = (val0 << 24) + (val1 << 16) + (val2 << 8) + val3; if (st.started == false) { st.header = NeoPG::make_unique<NewPacketHeader>( st.packet_type, st.packet_len, PacketLengthType::FiveOctet); st.header->m_offset = st.packet_pos; } else { st.length = NeoPG::make_unique<NewPacketLength>( st.packet_len, PacketLengthType::FiveOctet); } st.partial = false; } }; template <> struct action<new_packet_length_partial> { template <typename Input> static void apply(const Input& in, state& st) { st.packet_len = 1 << (in.peek_byte() & 0x1f); // FIXME: Not necessary if started == true. Would save one allocation. if (st.started == false) { st.header = NeoPG::make_unique<NewPacketHeader>( st.packet_type, st.packet_len, PacketLengthType::Partial); st.header->m_offset = st.packet_pos; } else { st.length = NeoPG::make_unique<NewPacketLength>( st.packet_len, PacketLengthType::Partial); } st.partial = true; } }; template <> struct action<is_packet> { template <typename Input> static void apply(const Input& in, state& st) { st.packet_type = PacketType::Reserved; st.header.reset(nullptr); st.length.reset(nullptr); st.exc.reset(nullptr); st.partial = false; st.started = false; } }; template <> struct action<packet_body_data> { template <typename Input> static void apply(const Input& in, state& st) { const char* data = in.begin(); size_t length = st.packet_len; if (!st.started) { if (!st.partial) { if (st.exc) st.sink.error_packet(std::move(st.header), std::move(st.exc)); else st.sink.next_packet(std::move(st.header), data, length); } else { // At this point, we don't support error packets for partial packets, // because we can't skip them easily. The semantics would be unclear. if (st.exc) throw *st.exc; st.sink.start_packet(std::move(st.header)); st.sink.continue_packet(nullptr, data, length); } st.started = true; } else { // At this point, we don't support error packets for partial packets, // because we can't skip them easily. The semantics would be unclear. if (st.exc) throw *st.exc; if (st.partial) { st.sink.continue_packet(std::move(st.length), data, length); } else { st.sink.finish_packet(std::move(st.length), data, length); } } // auto packet = NeoPG::make_unique::make_unique<NeoPG::RawPacket>(); // st.sink.next_packet(std::move(packet)); // //st.sink.next_packet(NeoPG::make_unique<NeoPG::RawPacket>(st.packet_type)); } }; template <> struct action<packet_body_data_rest> { template <typename Input> static void apply(const Input& in, state& st) { const char* data = in.begin(); size_t length = st.packet_len; st.sink.finish_packet(nullptr, data, length); } }; // Control template <typename Rule> struct control : pegtl::normal<Rule> { static const std::string error_message; template <typename Input, typename... States> static void raise(const Input& in, States&&...) { throw parser_error(error_message, in); } }; template <> const std::string control<eof>::error_message = "input has trailing data"; } // namespace openpgp // FIXME: Pass filename to ParserInput (everywhere). void RawPacketParser::process(Botan::DataSource& source) { using reader_t = std::function<std::size_t(char* buffer, const std::size_t length)>; auto state = openpgp::state{m_sink}; auto reader = [this, &source, &state]( char* buffer, const std::size_t length) mutable -> size_t { size_t count = source.read(reinterpret_cast<uint8_t*>(buffer), length); return count; }; buffer_input<reader_t> input("reader", MAX_PARSER_BUFFER, reader); parse<openpgp::grammar, openpgp::action, openpgp::control>(input, state); } void RawPacketParser::process(std::istream& source) { Botan::DataSource_Stream in{source}; process(in); } void RawPacketParser::process(const std::string& source) { std::stringstream in{source}; process(in); }
33.617512
83
0.681357
[ "object" ]
4fec1abbbe3b2901b2152772d50a84edcd91c7c1
16,123
cpp
C++
cegui/src/WindowManager.cpp
cbeck88/cegui-mirror
50d3a670b22fd957eba06549a9a7e04796d0b92f
[ "MIT" ]
null
null
null
cegui/src/WindowManager.cpp
cbeck88/cegui-mirror
50d3a670b22fd957eba06549a9a7e04796d0b92f
[ "MIT" ]
null
null
null
cegui/src/WindowManager.cpp
cbeck88/cegui-mirror
50d3a670b22fd957eba06549a9a7e04796d0b92f
[ "MIT" ]
null
null
null
/*********************************************************************** created: 21/2/2004 author: Paul D Turner purpose: Implements the WindowManager class *************************************************************************/ /*************************************************************************** * Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team * * 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 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 "CEGUI/WindowManager.h" #include "CEGUI/WindowFactoryManager.h" #include "CEGUI/WindowFactory.h" #include "CEGUI/Window.h" #include "CEGUI/Exceptions.h" #include "CEGUI/GUILayout_xmlHandler.h" #include "CEGUI/XMLParser.h" #include "CEGUI/RenderEffectManager.h" #include "CEGUI/RenderingWindow.h" #include "CEGUI/SharedStringStream.h" #include <iostream> #include <sstream> #include <algorithm> // Start of CEGUI namespace section namespace CEGUI { /************************************************************************* Static Data Definitions *************************************************************************/ // singleton instance pointer template<> WindowManager* Singleton<WindowManager>::ms_Singleton = 0; // default resource group String WindowManager::d_defaultResourceGroup; /************************************************************************* Definition of constant data for WindowManager *************************************************************************/ // Declared in WindowManager const String WindowManager::GUILayoutSchemaName("GUILayout.xsd"); const String WindowManager::GeneratedWindowNameBase("__cewin_uid_"); const String WindowManager::EventNamespace("WindowManager"); const String WindowManager::EventWindowCreated("WindowCreated"); const String WindowManager::EventWindowDestroyed("WindowDestroyed"); /************************************************************************* Constructor *************************************************************************/ WindowManager::WindowManager(void) : d_uid_counter(0), d_lockCount(0) { String addressStr = SharedStringstream::GetPointerAddressAsString(this); Logger::getSingleton().logEvent( "CEGUI::WindowManager Singleton created. (" + addressStr + ")"); } /************************************************************************* Destructor *************************************************************************/ WindowManager::~WindowManager(void) { destroyAllWindows(); cleanDeadPool(); String addressStr = SharedStringstream::GetPointerAddressAsString(this); Logger::getSingleton().logEvent( "CEGUI::WindowManager singleton destroyed (" + addressStr + ")"); } /************************************************************************* Create a new window of the specified type *************************************************************************/ Window* WindowManager::createWindow(const String& type, const String& name) { // only allow creation of Window objects if we are in unlocked state if (isLocked()) throw InvalidRequestException( "WindowManager is in the locked state."); String finalName(name.empty() ? generateUniqueWindowName() : name); WindowFactoryManager& wfMgr = WindowFactoryManager::getSingleton(); WindowFactory* factory = wfMgr.getFactory(type); Window* newWindow = factory->createWindow(finalName); String addressStr = SharedStringstream::GetPointerAddressAsString(newWindow); Logger::getSingleton().logEvent("Window '" + finalName +"' of type '" + type + "' has been created. " + addressStr, Informative); // see if we need to assign a look to this window if (wfMgr.isFalagardMappedType(type)) { const WindowFactoryManager::FalagardWindowMapping& fwm = wfMgr.getFalagardMappingForType(type); // this was a mapped type, so assign a look to the window so it can finalise // its initialisation newWindow->d_falagardType = type; newWindow->setWindowRenderer(fwm.d_rendererType); newWindow->setLookNFeel(fwm.d_lookName); initialiseRenderEffect(newWindow, fwm.d_effectName); } d_windowRegistry.push_back(newWindow); // fire event to notify interested parites about the new window. WindowEventArgs args(newWindow); fireEvent(EventWindowCreated, args, EventNamespace); return newWindow; } //---------------------------------------------------------------------------// void WindowManager::initialiseRenderEffect( Window* wnd, const String& effect) const { Logger& logger(Logger::getSingleton()); // nothing to do if effect is empty string if (effect.empty()) return; // if requested RenderEffect is not available, log that and continue if (!RenderEffectManager::getSingleton().isEffectAvailable(effect)) { logger.logEvent("Missing RenderEffect '" + effect + "' requested for " "window '" + wnd->getName() + "' - continuing without effect...", Errors); return; } // If we do not have a RenderingSurface, enable AutoRenderingSurface to // try and create one if (!wnd->getRenderingSurface()) { logger.logEvent("Enabling AutoRenderingSurface on '" + wnd->getName() + "' for RenderEffect support."); wnd->setUsingAutoRenderingSurface(true); } // If we have a RenderingSurface and it's a RenderingWindow if (wnd->getRenderingSurface() && wnd->getRenderingSurface()->isRenderingWindow()) { // Set an instance of the requested RenderEffect static_cast<RenderingWindow*>(wnd->getRenderingSurface())-> setRenderEffect(&RenderEffectManager::getSingleton(). create(effect, wnd)); } // log fact that we could not get a usable RenderingSurface else { logger.logEvent("Unable to set effect for window '" + wnd->getName() + "' since RenderingSurface is either missing " "or of wrong type (i.e. not a RenderingWindow).", Errors); } } /************************************************************************* Destroy the given window by pointer *************************************************************************/ void WindowManager::destroyWindow(Window* window) { WindowVector::iterator iter = std::find(d_windowRegistry.begin(), d_windowRegistry.end(), window); String addressStr = SharedStringstream::GetPointerAddressAsString(&window); if (iter == d_windowRegistry.end()) { Logger::getSingleton().logEvent("[WindowManager] Attempt to delete " "Window that does not exist! Address was: " + addressStr + ". WARNING: This could indicate a double-deletion issue!!", Errors); return; } d_windowRegistry.erase(iter); Logger::getSingleton().logEvent("Window at '" + window->getNamePath() + "' will be added to dead pool. " + addressStr, Informative); // do 'safe' part of cleanup window->destroy(); // add window to dead pool d_deathrow.push_back(window); // fire event to notify interested parites about window destruction. // TODO: Perhaps this should fire first, so window is still usable? WindowEventArgs args(window); fireEvent(EventWindowDestroyed, args, EventNamespace); } /************************************************************************* Destroy all Window objects *************************************************************************/ void WindowManager::destroyAllWindows(void) { while (!d_windowRegistry.empty()) destroyWindow(*d_windowRegistry.begin()); } //----------------------------------------------------------------------------// bool WindowManager::isAlive(const Window* window) const { WindowVector::const_iterator iter = std::find(d_windowRegistry.begin(), d_windowRegistry.end(), window); return iter != d_windowRegistry.end(); } Window* WindowManager::loadLayoutFromContainer(const RawDataContainer& source, PropertyCallback* callback, void* userdata) { // log the fact we are about to load a layout Logger::getSingleton().logEvent("---- Beginning loading of GUI layout from a RawDataContainer ----", Informative); // create handler object GUILayout_xmlHandler handler(callback, userdata); // do parse (which uses handler to create actual data) try { System::getSingleton().getXMLParser()->parseXML(handler, source, GUILayoutSchemaName); } catch (...) { Logger::getSingleton().logEvent("WindowManager::loadWindowLayout - loading of layout from a RawDataContainer failed.", Errors); throw; } // log the completion of loading Logger::getSingleton().logEvent("---- Successfully completed loading of GUI layout from a RawDataContainer ----", Standard); return handler.getLayoutRootWindow(); } Window* WindowManager::loadLayoutFromFile(const String& filename, const String& resourceGroup, PropertyCallback* callback, void* userdata) { if (filename.empty()) { throw InvalidRequestException( "Filename supplied for gui-layout loading must be valid."); } // log the fact we are about to load a layout Logger::getSingleton().logEvent("---- Beginning loading of GUI layout from '" + filename + "' ----", Informative); // create handler object GUILayout_xmlHandler handler(callback, userdata); // do parse (which uses handler to create actual data) try { System::getSingleton().getXMLParser()->parseXMLFile(handler, filename, GUILayoutSchemaName, resourceGroup.empty() ? d_defaultResourceGroup : resourceGroup); } catch (...) { Logger::getSingleton().logEvent("WindowManager::loadLayoutFromFile - loading of layout from file '" + filename +"' failed.", Errors); throw; } // log the completion of loading Logger::getSingleton().logEvent("---- Successfully completed loading of GUI layout from '" + filename + "' ----", Standard); return handler.getLayoutRootWindow(); } Window* WindowManager::loadLayoutFromString(const String& source, PropertyCallback* callback, void* userdata) { // log the fact we are about to load a layout Logger::getSingleton().logEvent("---- Beginning loading of GUI layout from string ----", Informative); // create handler object GUILayout_xmlHandler handler(callback, userdata); // do parse (which uses handler to create actual data) try { System::getSingleton().getXMLParser()->parseXMLString(handler, source, GUILayoutSchemaName); } catch (...) { Logger::getSingleton().logEvent("WindowManager::loadLayoutFromString - loading of layout from string failed.", Errors); throw; } // log the completion of loading Logger::getSingleton().logEvent("---- Successfully completed loading of GUI layout from string ----", Standard); return handler.getLayoutRootWindow(); } bool WindowManager::isDeadPoolEmpty(void) const { return d_deathrow.empty(); } void WindowManager::cleanDeadPool(void) { WindowVector::reverse_iterator curr = d_deathrow.rbegin(); for (; curr != d_deathrow.rend(); ++curr) { // in debug mode, log what gets cleaned from the dead pool (insane level) #if defined(DEBUG) || defined (_DEBUG) CEGUI_LOGINSANE("Window '" + (*curr)->getName() + "' about to be finally destroyed from dead pool."); #endif WindowFactory* factory = WindowFactoryManager::getSingleton().getFactory((*curr)->getType()); factory->destroyWindow(*curr); } // all done here, so clear all pointers from dead pool d_deathrow.clear(); } void WindowManager::writeLayoutToStream(const Window& window, OutStream& out_stream) const { XMLSerializer xml(out_stream); // output GUILayout start element xml.openTag(GUILayout_xmlHandler::GUILayoutElement); xml.attribute(GUILayout_xmlHandler::GUILayoutVersionAttribute, GUILayout_xmlHandler::NativeVersion); // write windows window.writeXMLToStream(xml); // write closing GUILayout element xml.closeTag(); } String WindowManager::getLayoutAsString(const Window& window) const { std::ostringstream str; writeLayoutToStream(window, str); return String(str.str().c_str()); } //----------------------------------------------------------------------------// void WindowManager::saveLayoutToFile(const Window& window, const String& filename) const { std::ofstream stream; stream << filename; if (!stream.good()) throw FileIOException( "failed to create stream for writing."); writeLayoutToStream(window, stream); } String WindowManager::generateUniqueWindowName() { const String ret = GeneratedWindowNameBase + PropertyHelper<std::uint32_t>::toString(d_uid_counter); // update counter for next time std::uint32_t old_uid = d_uid_counter; ++d_uid_counter; // log if we ever wrap-around (which should be pretty unlikely) if (d_uid_counter < old_uid) Logger::getSingleton().logEvent("UID counter for generated Window " "names has wrapped around - the fun shall now commence!"); return ret; } /************************************************************************* Return a WindowManager::WindowIterator object to iterate over the currently defined Windows. *************************************************************************/ WindowManager::WindowIterator WindowManager::getIterator(void) const { return WindowIterator(d_windowRegistry.begin(), d_windowRegistry.end()); } /************************************************************************* Outputs the names of ALL existing windows to log (DEBUG function). *************************************************************************/ void WindowManager::DEBUG_dumpWindowNames(String zone) const { Logger::getSingleton().logEvent("WINDOW NAMES DUMP (" + zone + ")"); Logger::getSingleton().logEvent("-----------------"); for (WindowVector::const_iterator i = d_windowRegistry.begin(); i != d_windowRegistry.end(); ++i) { Logger::getSingleton().logEvent("Window : " + (*i)->getNamePath()); } Logger::getSingleton().logEvent("-----------------"); } //----------------------------------------------------------------------------// void WindowManager::lock() { ++d_lockCount; } //----------------------------------------------------------------------------// void WindowManager::unlock() { if (d_lockCount > 0) --d_lockCount; } //----------------------------------------------------------------------------// bool WindowManager::isLocked() const { return d_lockCount != 0; } //----------------------------------------------------------------------------// } // End of CEGUI namespace section
35.670354
141
0.597718
[ "object" ]
4fed45539b92fa31a6249e8d7e6f49cb44d54399
32,479
cpp
C++
Source/Scripting/bsfScript/Serialization/BsScriptAssemblyManager.cpp
hachmeister/bsf
d0f65169d7737b8df9b2cc00bcbb2f8d45b3b5fa
[ "MIT" ]
null
null
null
Source/Scripting/bsfScript/Serialization/BsScriptAssemblyManager.cpp
hachmeister/bsf
d0f65169d7737b8df9b2cc00bcbb2f8d45b3b5fa
[ "MIT" ]
null
null
null
Source/Scripting/bsfScript/Serialization/BsScriptAssemblyManager.cpp
hachmeister/bsf
d0f65169d7737b8df9b2cc00bcbb2f8d45b3b5fa
[ "MIT" ]
null
null
null
//********************************* bs::framework - Copyright 2018-2019 Marko Pintera ************************************// //*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********// #include "Serialization/BsScriptAssemblyManager.h" #include "Serialization/BsManagedSerializableObjectInfo.h" #include "BsMonoManager.h" #include "BsMonoAssembly.h" #include "BsMonoClass.h" #include "BsMonoField.h" #include "BsMonoMethod.h" #include "BsMonoProperty.h" #include "Wrappers/BsScriptManagedResource.h" #include "Wrappers/BsScriptComponent.h" #include "Wrappers/BsScriptReflectable.h" #include "BsManagedSerializableObject.h" namespace bs { BuiltinTypeMappings BuiltinTypeMappings::EMPTY; Vector<String> ScriptAssemblyManager::getScriptAssemblies() const { Vector<String> initializedAssemblies; for (auto& assemblyPair : mAssemblyInfos) initializedAssemblies.push_back(assemblyPair.first); return initializedAssemblies; } void ScriptAssemblyManager::loadAssemblyInfo(const String& assemblyName, const BuiltinTypeMappings& typeMappings) { if(!mBaseTypesInitialized) initializeBaseTypes(); // Process all classes and fields UINT32 mUniqueTypeId = 1; MonoAssembly* curAssembly = MonoManager::instance().getAssembly(assemblyName); if(curAssembly == nullptr) return; loadTypeMappings(*curAssembly, typeMappings); SPtr<ManagedSerializableAssemblyInfo> assemblyInfo = bs_shared_ptr_new<ManagedSerializableAssemblyInfo>(); assemblyInfo->mName = assemblyName; mAssemblyInfos[assemblyName] = assemblyInfo; MonoClass* resourceClass = ScriptResource::getMetaData()->scriptClass; MonoClass* managedResourceClass = ScriptManagedResource::getMetaData()->scriptClass; // Populate class data const Vector<MonoClass*>& allClasses = curAssembly->getAllClasses(); for(auto& curClass : allClasses) { const bool isSerializable = curClass->isSubClassOf(mBuiltin.componentClass) || curClass->isSubClassOf(resourceClass) || curClass->hasAttribute(mBuiltin.serializeObjectAttribute); const bool isInspectable = curClass->hasAttribute(mBuiltin.showInInspectorAttribute); if ((isSerializable || isInspectable) && curClass != mBuiltin.componentClass && curClass != resourceClass && curClass != mBuiltin.managedComponentClass && curClass != managedResourceClass) { SPtr<ManagedSerializableTypeInfoObject> typeInfo = bs_shared_ptr_new<ManagedSerializableTypeInfoObject>(); typeInfo->mTypeNamespace = curClass->getNamespace(); typeInfo->mTypeName = curClass->getTypeName(); typeInfo->mTypeId = mUniqueTypeId++; if(isSerializable) typeInfo->mFlags |= ScriptTypeFlag::Serializable; if(isSerializable || isInspectable) typeInfo->mFlags |= ScriptTypeFlag::Inspectable; MonoPrimitiveType monoPrimitiveType = MonoUtil::getPrimitiveType(curClass->_getInternalClass()); if(monoPrimitiveType == MonoPrimitiveType::ValueType) typeInfo->mValueType = true; else typeInfo->mValueType = false; ::MonoReflectionType* type = MonoUtil::getType(curClass->_getInternalClass()); // Is this a wrapper for some reflectable type? ReflectableTypeInfo* reflTypeInfo = getReflectableTypeInfo(type); if(reflTypeInfo != nullptr) typeInfo->mRTIITypeId = reflTypeInfo->typeId; else typeInfo->mRTIITypeId = 0; SPtr<ManagedSerializableObjectInfo> objInfo = bs_shared_ptr_new<ManagedSerializableObjectInfo>(); objInfo->mTypeInfo = typeInfo; objInfo->mMonoClass = curClass; assemblyInfo->mTypeNameToId[objInfo->getFullTypeName()] = typeInfo->mTypeId; assemblyInfo->mObjectInfos[typeInfo->mTypeId] = objInfo; } } // Populate field & property data for(auto& curClassInfo : assemblyInfo->mObjectInfos) { SPtr<ManagedSerializableObjectInfo> objInfo = curClassInfo.second; UINT32 mUniqueFieldId = 1; const Vector<MonoField*>& fields = objInfo->mMonoClass->getAllFields(); for(auto& field : fields) { if(field->isStatic()) continue; SPtr<ManagedSerializableTypeInfo> typeInfo = getTypeInfo(field->getType()); if (typeInfo == nullptr) continue; bool typeIsSerializable = true; bool typeIsInspectable = true; if(const auto* objTypeInfo = rtti_cast<ManagedSerializableTypeInfoObject>(typeInfo.get())) { typeIsSerializable = objTypeInfo->mFlags.isSet(ScriptTypeFlag::Serializable); typeIsInspectable = typeIsSerializable || objTypeInfo->mFlags.isSet(ScriptTypeFlag::Inspectable); } SPtr<ManagedSerializableFieldInfo> fieldInfo = bs_shared_ptr_new<ManagedSerializableFieldInfo>(); fieldInfo->mFieldId = mUniqueFieldId++; fieldInfo->mName = field->getName(); fieldInfo->mMonoField = field; fieldInfo->mTypeInfo = typeInfo; fieldInfo->mParentTypeId = objInfo->mTypeInfo->mTypeId; MonoMemberVisibility visibility = field->getVisibility(); if (visibility == MonoMemberVisibility::Public) { if (typeIsSerializable && !field->hasAttribute(mBuiltin.dontSerializeFieldAttribute)) fieldInfo->mFlags |= ScriptFieldFlag::Serializable; if (typeIsInspectable && !field->hasAttribute(mBuiltin.hideInInspectorAttribute)) fieldInfo->mFlags |= ScriptFieldFlag::Inspectable; fieldInfo->mFlags |= ScriptFieldFlag::Animable; } else { if (typeIsSerializable && field->hasAttribute(mBuiltin.serializeFieldAttribute)) fieldInfo->mFlags |= ScriptFieldFlag::Serializable; if (typeIsInspectable && field->hasAttribute(mBuiltin.showInInspectorAttribute)) fieldInfo->mFlags |= ScriptFieldFlag::Inspectable; } if (field->hasAttribute(mBuiltin.rangeAttribute)) fieldInfo->mFlags |= ScriptFieldFlag::Range; if (field->hasAttribute(mBuiltin.stepAttribute)) fieldInfo->mFlags |= ScriptFieldFlag::Step; if (field->hasAttribute(mBuiltin.layerMaskAttribute)) { // Layout mask attribute is only relevant for 64-bit integer types if (const auto* primTypeInfo = rtti_cast<ManagedSerializableTypeInfoPrimitive>(typeInfo.get())) { if (primTypeInfo->mType == ScriptPrimitiveType::I64 || primTypeInfo->mType == ScriptPrimitiveType::U64) { fieldInfo->mFlags |= ScriptFieldFlag::AsLayerMask; } } } if (field->hasAttribute(mBuiltin.asQuaternionAttribute)) fieldInfo->mFlags |= ScriptFieldFlag::AsQuaternion; if(field->hasAttribute(mBuiltin.notNullAttribute)) fieldInfo->mFlags |= ScriptFieldFlag::NotNull; if(field->hasAttribute(mBuiltin.categoryAttribute)) fieldInfo->mFlags |= ScriptFieldFlag::Category; if(field->hasAttribute(mBuiltin.orderAttribute)) fieldInfo->mFlags |= ScriptFieldFlag::Order; if(field->hasAttribute(mBuiltin.inlineAttribute)) fieldInfo->mFlags |= ScriptFieldFlag::Inline; objInfo->mFieldNameToId[fieldInfo->mName] = fieldInfo->mFieldId; objInfo->mFields[fieldInfo->mFieldId] = fieldInfo; } const Vector<MonoProperty*>& properties = objInfo->mMonoClass->getAllProperties(); for (auto& property : properties) { SPtr<ManagedSerializableTypeInfo> typeInfo = getTypeInfo(property->getReturnType()); if (typeInfo == nullptr) continue; bool typeIsSerializable = true; bool typeIsInspectable = true; if(const auto* objTypeInfo = rtti_cast<ManagedSerializableTypeInfoObject>(typeInfo.get())) { typeIsSerializable = objTypeInfo->mFlags.isSet(ScriptTypeFlag::Serializable); typeIsInspectable = typeIsSerializable || objTypeInfo->mFlags.isSet(ScriptTypeFlag::Inspectable); } SPtr<ManagedSerializablePropertyInfo> propertyInfo = bs_shared_ptr_new<ManagedSerializablePropertyInfo>(); propertyInfo->mFieldId = mUniqueFieldId++; propertyInfo->mName = property->getName(); propertyInfo->mMonoProperty = property; propertyInfo->mTypeInfo = typeInfo; propertyInfo->mParentTypeId = objInfo->mTypeInfo->mTypeId; if (!property->isIndexed()) { MonoMemberVisibility visibility = property->getVisibility(); if (visibility == MonoMemberVisibility::Public) propertyInfo->mFlags |= ScriptFieldFlag::Animable; if (typeIsSerializable && property->hasAttribute(mBuiltin.serializeFieldAttribute)) propertyInfo->mFlags |= ScriptFieldFlag::Serializable; if (typeIsInspectable && property->hasAttribute(mBuiltin.showInInspectorAttribute)) propertyInfo->mFlags |= ScriptFieldFlag::Inspectable; if (property->hasAttribute(mBuiltin.rangeAttribute)) propertyInfo->mFlags |= ScriptFieldFlag::Range; if (property->hasAttribute(mBuiltin.stepAttribute)) propertyInfo->mFlags |= ScriptFieldFlag::Step; if (property->hasAttribute(mBuiltin.layerMaskAttribute)) { // Layout mask attribute is only relevant for 64-bit integer types if (const auto* primTypeInfo = rtti_cast<ManagedSerializableTypeInfoPrimitive>(typeInfo.get())) { if (primTypeInfo->mType == ScriptPrimitiveType::I64 || primTypeInfo->mType == ScriptPrimitiveType::U64) { propertyInfo->mFlags |= ScriptFieldFlag::AsLayerMask; } } } if (property->hasAttribute(mBuiltin.asQuaternionAttribute)) propertyInfo->mFlags |= ScriptFieldFlag::AsQuaternion; if (property->hasAttribute(mBuiltin.notNullAttribute)) propertyInfo->mFlags |= ScriptFieldFlag::NotNull; if (property->hasAttribute(mBuiltin.passByCopyAttribute)) propertyInfo->mFlags |= ScriptFieldFlag::PassByCopy; if (property->hasAttribute(mBuiltin.applyOnDirtyAttribute)) propertyInfo->mFlags |= ScriptFieldFlag::ApplyOnDirty; if (property->hasAttribute(mBuiltin.nativeWrapperAttribute)) propertyInfo->mFlags |= ScriptFieldFlag::NativeWrapper; if (property->hasAttribute(mBuiltin.categoryAttribute)) propertyInfo->mFlags |= ScriptFieldFlag::Category; if (property->hasAttribute(mBuiltin.orderAttribute)) propertyInfo->mFlags |= ScriptFieldFlag::Order; if (property->hasAttribute(mBuiltin.inlineAttribute)) propertyInfo->mFlags |= ScriptFieldFlag::Inline; } objInfo->mFieldNameToId[propertyInfo->mName] = propertyInfo->mFieldId; objInfo->mFields[propertyInfo->mFieldId] = propertyInfo; } } // Form parent/child connections for(auto& curClass : assemblyInfo->mObjectInfos) { MonoClass* base = curClass.second->mMonoClass->getBaseClass(); while(base != nullptr) { SPtr<ManagedSerializableObjectInfo> baseObjInfo; if(getSerializableObjectInfo(base->getNamespace(), base->getTypeName(), baseObjInfo)) { curClass.second->mBaseClass = baseObjInfo; baseObjInfo->mDerivedClasses.push_back(curClass.second); break; } base = base->getBaseClass(); } } } void ScriptAssemblyManager::clearAssemblyInfo() { clearScriptObjects(); mAssemblyInfos.clear(); mBuiltinComponentInfos.clear(); mBuiltinComponentInfosByTID.clear(); mBuiltinResourceInfos.clear(); mBuiltinResourceInfosByTID.clear(); mBuiltinResourceInfosByType.clear(); mReflectableTypeInfos.clear(); mReflectableTypeInfosByTID.clear(); } SPtr<ManagedSerializableTypeInfo> ScriptAssemblyManager::getTypeInfo(MonoClass* monoClass) { if(!mBaseTypesInitialized) BS_EXCEPT(InvalidStateException, "Calling getTypeInfo without previously initializing base types."); MonoPrimitiveType monoPrimitiveType = MonoUtil::getPrimitiveType(monoClass->_getInternalClass()); // If enum get the enum base data type bool isEnum = MonoUtil::isEnum(monoClass->_getInternalClass()); if (isEnum) monoPrimitiveType = MonoUtil::getEnumPrimitiveType(monoClass->_getInternalClass()); // Determine field type //// Check for simple types or enums first ScriptPrimitiveType scriptPrimitiveType = ScriptPrimitiveType::U32; bool isSimpleType = false; switch(monoPrimitiveType) { case MonoPrimitiveType::Boolean: scriptPrimitiveType = ScriptPrimitiveType::Bool; isSimpleType = true; break; case MonoPrimitiveType::Char: scriptPrimitiveType = ScriptPrimitiveType::Char; isSimpleType = true; break; case MonoPrimitiveType::I8: scriptPrimitiveType = ScriptPrimitiveType::I8; isSimpleType = true; break; case MonoPrimitiveType::U8: scriptPrimitiveType = ScriptPrimitiveType::U8; isSimpleType = true; break; case MonoPrimitiveType::I16: scriptPrimitiveType = ScriptPrimitiveType::I16; isSimpleType = true; break; case MonoPrimitiveType::U16: scriptPrimitiveType = ScriptPrimitiveType::U16; isSimpleType = true; break; case MonoPrimitiveType::I32: scriptPrimitiveType = ScriptPrimitiveType::I32; isSimpleType = true; break; case MonoPrimitiveType::U32: scriptPrimitiveType = ScriptPrimitiveType::U32; isSimpleType = true; break; case MonoPrimitiveType::I64: scriptPrimitiveType = ScriptPrimitiveType::I64; isSimpleType = true; break; case MonoPrimitiveType::U64: scriptPrimitiveType = ScriptPrimitiveType::U64; isSimpleType = true; break; case MonoPrimitiveType::String: scriptPrimitiveType = ScriptPrimitiveType::String; isSimpleType = true; break; case MonoPrimitiveType::R32: scriptPrimitiveType = ScriptPrimitiveType::Float; isSimpleType = true; break; case MonoPrimitiveType::R64: scriptPrimitiveType = ScriptPrimitiveType::Double; isSimpleType = true; break; default: break; }; if(isSimpleType) { if(!isEnum) { SPtr<ManagedSerializableTypeInfoPrimitive> typeInfo = bs_shared_ptr_new<ManagedSerializableTypeInfoPrimitive>(); typeInfo->mType = scriptPrimitiveType; return typeInfo; } else { SPtr<ManagedSerializableTypeInfoEnum> typeInfo = bs_shared_ptr_new<ManagedSerializableTypeInfoEnum>(); typeInfo->mUnderlyingType = scriptPrimitiveType; typeInfo->mTypeNamespace = monoClass->getNamespace(); typeInfo->mTypeName = monoClass->getTypeName(); return typeInfo; } } //// Check complex types switch(monoPrimitiveType) { case MonoPrimitiveType::Class: if(monoClass->isSubClassOf(ScriptResource::getMetaData()->scriptClass)) // Resource { SPtr<ManagedSerializableTypeInfoRef> typeInfo = bs_shared_ptr_new<ManagedSerializableTypeInfoRef>(); typeInfo->mTypeNamespace = monoClass->getNamespace(); typeInfo->mTypeName = monoClass->getTypeName(); typeInfo->mRTIITypeId = 0; if(monoClass == ScriptResource::getMetaData()->scriptClass) typeInfo->mType = ScriptReferenceType::BuiltinResourceBase; else if (monoClass == ScriptManagedResource::getMetaData()->scriptClass) typeInfo->mType = ScriptReferenceType::ManagedResourceBase; else if (monoClass->isSubClassOf(ScriptManagedResource::getMetaData()->scriptClass)) typeInfo->mType = ScriptReferenceType::ManagedResource; else if (monoClass->isSubClassOf(ScriptResource::getMetaData()->scriptClass)) { typeInfo->mType = ScriptReferenceType::BuiltinResource; ::MonoReflectionType* type = MonoUtil::getType(monoClass->_getInternalClass()); BuiltinResourceInfo* builtinInfo = getBuiltinResourceInfo(type); if (builtinInfo == nullptr) { assert(false && "Unable to find information about a built-in resource. Did you update BuiltinResourceTypes list?"); return nullptr; } typeInfo->mRTIITypeId = builtinInfo->typeId; } return typeInfo; } else if(monoClass == ScriptRRefBase::getMetaData()->scriptClass) // Resource reference return bs_shared_ptr_new<ManagedSerializableTypeInfoRRef>(); else if (monoClass->isSubClassOf(mBuiltin.sceneObjectClass) || monoClass->isSubClassOf(mBuiltin.componentClass)) // Game object { SPtr<ManagedSerializableTypeInfoRef> typeInfo = bs_shared_ptr_new<ManagedSerializableTypeInfoRef>(); typeInfo->mTypeNamespace = monoClass->getNamespace(); typeInfo->mTypeName = monoClass->getTypeName(); typeInfo->mRTIITypeId = 0; if (monoClass == mBuiltin.componentClass) typeInfo->mType = ScriptReferenceType::BuiltinComponentBase; else if (monoClass == mBuiltin.managedComponentClass) typeInfo->mType = ScriptReferenceType::ManagedComponentBase; else if (monoClass->isSubClassOf(mBuiltin.sceneObjectClass)) typeInfo->mType = ScriptReferenceType::SceneObject; else if (monoClass->isSubClassOf(mBuiltin.managedComponentClass)) typeInfo->mType = ScriptReferenceType::ManagedComponent; else if (monoClass->isSubClassOf(mBuiltin.componentClass)) { typeInfo->mType = ScriptReferenceType::BuiltinComponent; ::MonoReflectionType* type = MonoUtil::getType(monoClass->_getInternalClass()); BuiltinComponentInfo* builtinInfo = getBuiltinComponentInfo(type); if(builtinInfo == nullptr) { assert(false && "Unable to find information about a built-in component. Did you update BuiltinComponents list?"); return nullptr; } typeInfo->mRTIITypeId = builtinInfo->typeId; } return typeInfo; } else { ::MonoReflectionType* type = MonoUtil::getType(monoClass->_getInternalClass()); // Is this a wrapper for some reflectable type? ReflectableTypeInfo* reflTypeInfo = getReflectableTypeInfo(type); if(reflTypeInfo != nullptr) { SPtr<ManagedSerializableTypeInfoRef> typeInfo = bs_shared_ptr_new<ManagedSerializableTypeInfoRef>(); typeInfo->mTypeNamespace = monoClass->getNamespace(); typeInfo->mTypeName = monoClass->getTypeName(); typeInfo->mRTIITypeId = reflTypeInfo->typeId; typeInfo->mType = ScriptReferenceType::ReflectableObject; return typeInfo; } else { // Finally, it's either a normal managed object, or a non-reflectable type wrapper SPtr<ManagedSerializableObjectInfo> objInfo; if (getSerializableObjectInfo(monoClass->getNamespace(), monoClass->getTypeName(), objInfo)) return objInfo->mTypeInfo; } } break; case MonoPrimitiveType::ValueType: { SPtr<ManagedSerializableObjectInfo> objInfo; if (getSerializableObjectInfo(monoClass->getNamespace(), monoClass->getTypeName(), objInfo)) return objInfo->mTypeInfo; } break; case MonoPrimitiveType::Generic: if(monoClass->getFullName() == mBuiltin.systemGenericListClass->getFullName()) // Full name is part of CIL spec, so it is just fine to compare like this { SPtr<ManagedSerializableTypeInfoList> typeInfo = bs_shared_ptr_new<ManagedSerializableTypeInfoList>(); MonoProperty* itemProperty = monoClass->getProperty("Item"); MonoClass* itemClass = itemProperty->getReturnType(); if (itemClass != nullptr) typeInfo->mElementType = getTypeInfo(itemClass); if (typeInfo->mElementType == nullptr) return nullptr; return typeInfo; } else if(monoClass->getFullName() == mBuiltin.systemGenericDictionaryClass->getFullName()) { SPtr<ManagedSerializableTypeInfoDictionary> typeInfo = bs_shared_ptr_new<ManagedSerializableTypeInfoDictionary>(); MonoMethod* getEnumerator = monoClass->getMethod("GetEnumerator"); MonoClass* enumClass = getEnumerator->getReturnType(); MonoProperty* currentProp = enumClass->getProperty("Current"); MonoClass* keyValuePair = currentProp->getReturnType(); MonoProperty* keyProperty = keyValuePair->getProperty("Key"); MonoProperty* valueProperty = keyValuePair->getProperty("Value"); MonoClass* keyClass = keyProperty->getReturnType(); if(keyClass != nullptr) typeInfo->mKeyType = getTypeInfo(keyClass); MonoClass* valueClass = valueProperty->getReturnType(); if(valueClass != nullptr) typeInfo->mValueType = getTypeInfo(valueClass); if (typeInfo->mKeyType == nullptr || typeInfo->mValueType == nullptr) return nullptr; return typeInfo; } else if(monoClass->getFullName() == mBuiltin.genericRRefClass->getFullName()) { SPtr<ManagedSerializableTypeInfoRRef> typeInfo = bs_shared_ptr_new<ManagedSerializableTypeInfoRRef>(); MonoProperty* itemProperty = monoClass->getProperty("Value"); MonoClass* itemClass = itemProperty->getReturnType(); if (itemClass != nullptr) typeInfo->mResourceType = getTypeInfo(itemClass); if (typeInfo->mResourceType == nullptr) return nullptr; return typeInfo; } break; case MonoPrimitiveType::Array: { SPtr<ManagedSerializableTypeInfoArray> typeInfo = bs_shared_ptr_new<ManagedSerializableTypeInfoArray>(); ::MonoClass* elementClass = ScriptArray::getElementClass(monoClass->_getInternalClass()); if(elementClass != nullptr) { MonoClass* monoElementClass = MonoManager::instance().findClass(elementClass); if(monoElementClass != nullptr) typeInfo->mElementType = getTypeInfo(monoElementClass); } if (typeInfo->mElementType == nullptr) return nullptr; typeInfo->mRank = ScriptArray::getRank(monoClass->_getInternalClass()); return typeInfo; } default: break; } return nullptr; } void ScriptAssemblyManager::clearScriptObjects() { mBaseTypesInitialized = false; mBuiltin = BuiltinScriptClasses(); } void ScriptAssemblyManager::initializeBaseTypes() { // Get necessary classes for detecting needed class & field information MonoAssembly* corlib = MonoManager::instance().getAssembly("corlib"); if(corlib == nullptr) BS_EXCEPT(InvalidStateException, "corlib assembly is not loaded."); MonoAssembly* engineAssembly = MonoManager::instance().getAssembly(ENGINE_ASSEMBLY); if(engineAssembly == nullptr) BS_EXCEPT(InvalidStateException, String(ENGINE_ASSEMBLY) + " assembly is not loaded."); mBuiltin.systemArrayClass = corlib->getClass("System", "Array"); if(mBuiltin.systemArrayClass == nullptr) BS_EXCEPT(InvalidStateException, "Cannot find System.Array managed class."); mBuiltin.systemGenericListClass = corlib->getClass("System.Collections.Generic", "List`1"); if(mBuiltin.systemGenericListClass == nullptr) BS_EXCEPT(InvalidStateException, "Cannot find List<T> managed class."); mBuiltin.systemGenericDictionaryClass = corlib->getClass("System.Collections.Generic", "Dictionary`2"); if(mBuiltin.systemGenericDictionaryClass == nullptr) BS_EXCEPT(InvalidStateException, "Cannot find Dictionary<TKey, TValue> managed class."); mBuiltin.systemTypeClass = corlib->getClass("System", "Type"); if (mBuiltin.systemTypeClass == nullptr) BS_EXCEPT(InvalidStateException, "Cannot find Type managed class."); mBuiltin.serializeObjectAttribute = engineAssembly->getClass(ENGINE_NS, "SerializeObject"); if(mBuiltin.serializeObjectAttribute == nullptr) BS_EXCEPT(InvalidStateException, "Cannot find SerializableObject managed class."); mBuiltin.dontSerializeFieldAttribute = engineAssembly->getClass(ENGINE_NS, "DontSerializeField"); if(mBuiltin.dontSerializeFieldAttribute == nullptr) BS_EXCEPT(InvalidStateException, "Cannot find DontSerializeField managed class."); mBuiltin.rangeAttribute = engineAssembly->getClass(ENGINE_NS, "Range"); if (mBuiltin.rangeAttribute == nullptr) BS_EXCEPT(InvalidStateException, "Cannot find Range managed class."); mBuiltin.stepAttribute = engineAssembly->getClass(ENGINE_NS, "Step"); if (mBuiltin.stepAttribute == nullptr) BS_EXCEPT(InvalidStateException, "Cannot find Step managed class."); mBuiltin.layerMaskAttribute = engineAssembly->getClass(ENGINE_NS, "LayerMask"); if (mBuiltin.layerMaskAttribute == nullptr) BS_EXCEPT(InvalidStateException, "Cannot find LayerMask managed class."); mBuiltin.asQuaternionAttribute = engineAssembly->getClass(ENGINE_NS, "AsQuaternion"); if (mBuiltin.asQuaternionAttribute == nullptr) BS_EXCEPT(InvalidStateException, "Cannot find AsQuaternion managed class."); mBuiltin.nativeWrapperAttribute = engineAssembly->getClass(ENGINE_NS, "NativeWrapper"); if (mBuiltin.nativeWrapperAttribute == nullptr) BS_EXCEPT(InvalidStateException, "Cannot find NativeWrapper managed class."); mBuiltin.notNullAttribute = engineAssembly->getClass(ENGINE_NS, "NotNull"); if (mBuiltin.notNullAttribute == nullptr) BS_EXCEPT(InvalidStateException, "Cannot find NotNull managed class."); mBuiltin.passByCopyAttribute = engineAssembly->getClass(ENGINE_NS, "PassByCopy"); if (mBuiltin.passByCopyAttribute == nullptr) BS_EXCEPT(InvalidStateException, "Cannot find PassByCopy managed class."); mBuiltin.applyOnDirtyAttribute = engineAssembly->getClass(ENGINE_NS, "ApplyOnDirty"); if (mBuiltin.applyOnDirtyAttribute == nullptr) BS_EXCEPT(InvalidStateException, "Cannot find ApplyOnDirty managed class."); mBuiltin.componentClass = engineAssembly->getClass(ENGINE_NS, "Component"); if(mBuiltin.componentClass == nullptr) BS_EXCEPT(InvalidStateException, "Cannot find Component managed class."); mBuiltin.managedComponentClass = engineAssembly->getClass(ENGINE_NS, "ManagedComponent"); if (mBuiltin.managedComponentClass == nullptr) BS_EXCEPT(InvalidStateException, "Cannot find ManagedComponent managed class."); mBuiltin.missingComponentClass = engineAssembly->getClass(ENGINE_NS, "MissingComponent"); if (mBuiltin.missingComponentClass == nullptr) BS_EXCEPT(InvalidStateException, "Cannot find MissingComponent managed class."); mBuiltin.sceneObjectClass = engineAssembly->getClass(ENGINE_NS, "SceneObject"); if(mBuiltin.sceneObjectClass == nullptr) BS_EXCEPT(InvalidStateException, "Cannot find SceneObject managed class."); mBuiltin.rrefBaseClass = engineAssembly->getClass(ENGINE_NS, "RRefBase"); if(mBuiltin.rrefBaseClass == nullptr) BS_EXCEPT(InvalidStateException, "Cannot find RRefBase managed class."); mBuiltin.genericRRefClass = engineAssembly->getClass(ENGINE_NS, "RRef`1"); if(mBuiltin.genericRRefClass == nullptr) BS_EXCEPT(InvalidStateException, "Cannot find RRef<T> managed class."); mBuiltin.serializeFieldAttribute = engineAssembly->getClass(ENGINE_NS, "SerializeField"); if(mBuiltin.serializeFieldAttribute == nullptr) BS_EXCEPT(InvalidStateException, "Cannot find SerializeField managed class."); mBuiltin.hideInInspectorAttribute = engineAssembly->getClass(ENGINE_NS, "HideInInspector"); if(mBuiltin.hideInInspectorAttribute == nullptr) BS_EXCEPT(InvalidStateException, "Cannot find HideInInspector managed class."); mBuiltin.showInInspectorAttribute = engineAssembly->getClass(ENGINE_NS, "ShowInInspector"); if (mBuiltin.showInInspectorAttribute == nullptr) BS_EXCEPT(InvalidStateException, "Cannot find ShowInInspector managed class."); mBuiltin.categoryAttribute = engineAssembly->getClass(ENGINE_NS, "Category"); if (mBuiltin.categoryAttribute == nullptr) BS_EXCEPT(InvalidStateException, "Cannot find Category managed class."); mBuiltin.orderAttribute = engineAssembly->getClass(ENGINE_NS, "Order"); if (mBuiltin.orderAttribute == nullptr) BS_EXCEPT(InvalidStateException, "Cannot find Order managed class."); mBuiltin.inlineAttribute = engineAssembly->getClass(ENGINE_NS, "Inline"); if (mBuiltin.inlineAttribute == nullptr) BS_EXCEPT(InvalidStateException, "Cannot find Inline managed class."); mBaseTypesInitialized = true; } void ScriptAssemblyManager::loadTypeMappings(MonoAssembly& assembly, const BuiltinTypeMappings& mapping) { for(auto& entry : mapping.components) { BuiltinComponentInfo info = entry; info.monoClass = assembly.getClass(entry.metaData->ns, entry.metaData->name); ::MonoReflectionType* type = MonoUtil::getType(info.monoClass->_getInternalClass()); mBuiltinComponentInfos[type] = info; mBuiltinComponentInfosByTID[info.typeId] = info; } for (auto& entry : mapping.resources) { BuiltinResourceInfo info = entry; info.monoClass = assembly.getClass(entry.metaData->ns, entry.metaData->name); ::MonoReflectionType* type = MonoUtil::getType(info.monoClass->_getInternalClass()); mBuiltinResourceInfos[type] = info; mBuiltinResourceInfosByTID[info.typeId] = info; mBuiltinResourceInfosByType[(UINT32)info.resType] = info; } for(auto& entry : mapping.reflectableObjects) { ReflectableTypeInfo info = entry; info.monoClass = assembly.getClass(entry.metaData->ns, entry.metaData->name); ::MonoReflectionType* type = MonoUtil::getType(info.monoClass->_getInternalClass()); mReflectableTypeInfos[type] = info; mReflectableTypeInfosByTID[info.typeId] = info; } } BuiltinComponentInfo* ScriptAssemblyManager::getBuiltinComponentInfo(::MonoReflectionType* type) { auto iterFind = mBuiltinComponentInfos.find(type); if (iterFind == mBuiltinComponentInfos.end()) return nullptr; return &(iterFind->second); } BuiltinComponentInfo* ScriptAssemblyManager::getBuiltinComponentInfo(UINT32 rttiTypeId) { auto iterFind = mBuiltinComponentInfosByTID.find(rttiTypeId); if (iterFind == mBuiltinComponentInfosByTID.end()) return nullptr; return &(iterFind->second); } BuiltinResourceInfo* ScriptAssemblyManager::getBuiltinResourceInfo(::MonoReflectionType* type) { auto iterFind = mBuiltinResourceInfos.find(type); if (iterFind == mBuiltinResourceInfos.end()) return nullptr; return &(iterFind->second); } BuiltinResourceInfo* ScriptAssemblyManager::getBuiltinResourceInfo(UINT32 rttiTypeId) { auto iterFind = mBuiltinResourceInfosByTID.find(rttiTypeId); if (iterFind == mBuiltinResourceInfosByTID.end()) return nullptr; return &(iterFind->second); } BuiltinResourceInfo* ScriptAssemblyManager::getBuiltinResourceInfo(ScriptResourceType type) { auto iterFind = mBuiltinResourceInfosByType.find((UINT32)type); if (iterFind == mBuiltinResourceInfosByType.end()) return nullptr; return &(iterFind->second); } ReflectableTypeInfo* ScriptAssemblyManager::getReflectableTypeInfo(::MonoReflectionType* type) { auto iterFind = mReflectableTypeInfos.find(type); if (iterFind == mReflectableTypeInfos.end()) return nullptr; return &(iterFind->second); } ReflectableTypeInfo* ScriptAssemblyManager::getReflectableTypeInfo(uint32_t rttiTypeId) { auto iterFind = mReflectableTypeInfosByTID.find(rttiTypeId); if (iterFind == mReflectableTypeInfosByTID.end()) return nullptr; return &(iterFind->second); } bool ScriptAssemblyManager::getSerializableObjectInfo(const String& ns, const String& typeName, SPtr<ManagedSerializableObjectInfo>& outInfo) { String fullName = ns + "." + typeName; for(auto& curAssembly : mAssemblyInfos) { if (curAssembly.second == nullptr) continue; auto iterFind = curAssembly.second->mTypeNameToId.find(fullName); if(iterFind != curAssembly.second->mTypeNameToId.end()) { outInfo = curAssembly.second->mObjectInfos[iterFind->second]; return true; } } return false; } bool ScriptAssemblyManager::hasSerializableObjectInfo(const String& ns, const String& typeName) { String fullName = ns + "." + typeName; for(auto& curAssembly : mAssemblyInfos) { auto iterFind = curAssembly.second->mTypeNameToId.find(fullName); if(iterFind != curAssembly.second->mTypeNameToId.end()) return true; } return false; } SPtr<IReflectable> ScriptAssemblyManager::getReflectableFromManagedObject(MonoObject* value) { SPtr<IReflectable> nativeValue; if (value != nullptr) { String elementNs; String elementTypeName; MonoUtil::getClassName(value, elementNs, elementTypeName); SPtr<ManagedSerializableObjectInfo> objInfo; if (!instance().getSerializableObjectInfo(elementNs, elementTypeName, objInfo)) { LOGERR("Object has no serialization meta-data."); return nullptr; } if (objInfo->mTypeInfo->mRTIITypeId != 0) { ::MonoClass* monoClass = MonoUtil::getClass(value); ::MonoReflectionType* monoType = MonoUtil::getType(monoClass); const ReflectableTypeInfo* reflTypeInfo = instance().getReflectableTypeInfo(monoType); assert(reflTypeInfo); ScriptReflectableBase* scriptReflectable = nullptr; if (reflTypeInfo->metaData->thisPtrField != nullptr) reflTypeInfo->metaData->thisPtrField->get(value, &scriptReflectable); nativeValue = scriptReflectable->getReflectable(); } else { SPtr<ManagedSerializableObject> managedObj = ManagedSerializableObject::createFromExisting(value); if (!managedObj) { LOGERR("Object failed to serialize due to an internal error."); return nullptr; } managedObj->serialize(); nativeValue = managedObj; } } return nativeValue; } }
36.168151
155
0.744543
[ "object", "vector" ]
4ff0ddfb26d75bd51fb6bd3a7006e5c109c00826
12,827
cpp
C++
src/lib/profiles/fabric-provisioning/FabricProvisioning.cpp
lanyuwen/openweave-core
fbed1743a7b62657f5d310b98909c59474a6404d
[ "Apache-2.0" ]
null
null
null
src/lib/profiles/fabric-provisioning/FabricProvisioning.cpp
lanyuwen/openweave-core
fbed1743a7b62657f5d310b98909c59474a6404d
[ "Apache-2.0" ]
null
null
null
src/lib/profiles/fabric-provisioning/FabricProvisioning.cpp
lanyuwen/openweave-core
fbed1743a7b62657f5d310b98909c59474a6404d
[ "Apache-2.0" ]
1
2020-11-04T06:58:12.000Z
2020-11-04T06:58:12.000Z
/* * * Copyright (c) 2013-2017 Nest Labs, Inc. * All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file * This file implements the Fabric Provisioning Profile, used to * manage membership to Weave Fabrics. * * The Fabric Provisioning Profile facilitates client-server operations * such that the client (the controlling device) can trigger specific * functionality on the server (the device undergoing provisioning), * to allow it to create, join, and leave Weave Fabrics. This includes * communicating Fabric configuration information such as identifiers, * keys, security schemes, and related data. * */ #include <Weave/Core/WeaveCore.h> #include <Weave/Core/WeaveTLV.h> #include <Weave/Support/CodeUtils.h> #include <Weave/Core/WeaveEncoding.h> #include <Weave/Profiles/WeaveProfiles.h> #include "FabricProvisioning.h" #include <Weave/Profiles/common/CommonProfile.h> namespace nl { namespace Weave { namespace Profiles { namespace FabricProvisioning { using namespace nl::Weave::Crypto; using namespace nl::Weave::Encoding; using namespace nl::Weave::TLV; FabricProvisioningServer::FabricProvisioningServer() { FabricState = NULL; ExchangeMgr = NULL; mDelegate = NULL; mCurClientOp = NULL; } /** * Initialize the Fabric Provisioning Server state and register to receive * Fabric Provisioning messages. * * @param[in] exchangeMgr A pointer to the system Weave Exchange Manager. * * @retval #WEAVE_ERROR_TOO_MANY_UNSOLICITED_MESSAGE_HANDLERS If too many message handlers have * already been registered. * @retval #WEAVE_NO_ERROR On success. */ WEAVE_ERROR FabricProvisioningServer::Init(WeaveExchangeManager *exchangeMgr) { FabricState = exchangeMgr->FabricState; ExchangeMgr = exchangeMgr; mDelegate = NULL; mCurClientOp = NULL; // Register to receive unsolicited Service Provisioning messages from the exchange manager. WEAVE_ERROR err = ExchangeMgr->RegisterUnsolicitedMessageHandler(kWeaveProfile_FabricProvisioning, HandleClientRequest, this); return err; } /** * Shutdown the Fabric Provisioning Server. * * @retval #WEAVE_NO_ERROR unconditionally. */ // TODO: Additional documentation detail required (i.e. how this function impacts object lifecycle). WEAVE_ERROR FabricProvisioningServer::Shutdown() { if (ExchangeMgr != NULL) ExchangeMgr->UnregisterUnsolicitedMessageHandler(kWeaveProfile_FabricProvisioning); FabricState = NULL; ExchangeMgr = NULL; mDelegate = NULL; mCurClientOp = NULL; return WEAVE_NO_ERROR; } /** * Set the delegate to process Fabric Provisioning events. * * @param[in] delegate A pointer to the Fabric Provisioning Delegate. */ void FabricProvisioningServer::SetDelegate(FabricProvisioningDelegate *delegate) { mDelegate = delegate; } /** * Send a success response to a Fabric Provisioning request. * * @retval #WEAVE_ERROR_INCORRECT_STATE If there is no request being processed. * @retval #WEAVE_NO_ERROR On success. * @retval other Other Weave or platform-specific error codes indicating that an error * occurred preventing the sending of the success response. */ WEAVE_ERROR FabricProvisioningServer::SendSuccessResponse() { return SendStatusReport(kWeaveProfile_Common, Common::kStatus_Success); } /** * Send a status report response to a request. * * @param[in] statusProfileId The Weave profile ID this status report pertains to. * @param[in] statusCode The status code to be included in this response. * @param[in] sysError The system error code to be included in this response. * * @retval #WEAVE_ERROR_INCORRECT_STATE If there is no request being processed. * @retval #WEAVE_NO_ERROR On success. * @retval other Other Weave or platform-specific error codes indicating that an error * occurred preventing the sending of the status report. */ WEAVE_ERROR FabricProvisioningServer::SendStatusReport(uint32_t statusProfileId, uint16_t statusCode, WEAVE_ERROR sysError) { WEAVE_ERROR err; VerifyOrExit(mCurClientOp != NULL, err = WEAVE_ERROR_INCORRECT_STATE); err = WeaveServerBase::SendStatusReport(mCurClientOp, statusProfileId, statusCode, sysError); exit: if (mCurClientOp != NULL) { mCurClientOp->Close(); mCurClientOp = NULL; } return err; } void FabricProvisioningServer::HandleClientRequest(ExchangeContext *ec, const IPPacketInfo *pktInfo, const WeaveMessageInfo *msgInfo, uint32_t profileId, uint8_t msgType, PacketBuffer *msgBuf) { WEAVE_ERROR err = WEAVE_NO_ERROR; FabricProvisioningServer *server = (FabricProvisioningServer *) ec->AppState; FabricProvisioningDelegate *delegate = server->mDelegate; // Fail messages for the wrong profile. This shouldn't happen, but better safe than sorry. if (profileId != kWeaveProfile_FabricProvisioning) { WeaveServerBase::SendStatusReport(ec, kWeaveProfile_Common, Common::kStatus_BadRequest, WEAVE_NO_ERROR); ec->Close(); goto exit; } // Call on the delegate to enforce message-level access control. If policy dictates the message should NOT // be processed, then simply end the exchange and return. If an error response was warranted, the appropriate // response will have been sent within EnforceAccessControl(). if (!server->EnforceAccessControl(ec, profileId, msgType, msgInfo, server->mDelegate)) { ec->Close(); ExitNow(); } // Disallow simultaneous requests. if (server->mCurClientOp != NULL) { WeaveServerBase::SendStatusReport(ec, kWeaveProfile_Common, Common::kStatus_Busy, WEAVE_NO_ERROR); ec->Close(); goto exit; } // Record that we have a request in process. server->mCurClientOp = ec; // Decode and dispatch the message. switch (msgType) { case kMsgType_CreateFabric: // Return an error if the node is already a member of a fabric. if (server->FabricState->FabricId != 0) { server->SendStatusReport(kWeaveProfile_FabricProvisioning, kStatusCode_AlreadyMemberOfFabric); ExitNow(); } // Create a new fabric. err = server->FabricState->CreateFabric(); SuccessOrExit(err); // Call the application to perform any creation-time operations (such as address assignment). // Note that this can fail, in which case we abort the fabric creation. err = delegate->HandleCreateFabric(); if (err != WEAVE_NO_ERROR) server->FabricState->ClearFabricState(); SuccessOrExit(err); break; case kMsgType_LeaveFabric: // Return an error if the node is not a member of a fabric. if (server->FabricState->FabricId == 0) { server->SendStatusReport(kWeaveProfile_FabricProvisioning, kStatusCode_NotMemberOfFabric); ExitNow(); } // Clear the fabric state. server->FabricState->ClearFabricState(); // Call the application to perform any leave-time operations. err = delegate->HandleLeaveFabric(); SuccessOrExit(err); break; case kMsgType_GetFabricConfig: // Return an error if the node is not a member of a fabric. if (server->FabricState->FabricId == 0) { server->SendStatusReport(kWeaveProfile_FabricProvisioning, kStatusCode_NotMemberOfFabric); ExitNow(); } // Get the encoded fabric state from the fabric state object. PacketBuffer::Free(msgBuf); msgBuf = PacketBuffer::New(); VerifyOrExit(msgBuf != NULL, err = WEAVE_ERROR_NO_MEMORY); uint32_t fabricStateLen; err = server->FabricState->GetFabricState(msgBuf->Start(), msgBuf->AvailableDataLength(), fabricStateLen); SuccessOrExit(err); msgBuf->SetDataLength(fabricStateLen); // Send the get fabric config response. err = server->mCurClientOp->SendMessage(kWeaveProfile_FabricProvisioning, kMsgType_GetFabricConfigComplete, msgBuf, 0); SuccessOrExit(err); msgBuf = NULL; server->mCurClientOp->Close(); server->mCurClientOp = NULL; err = delegate->HandleGetFabricConfig(); SuccessOrExit(err); break; case kMsgType_JoinExistingFabric: // Return an error if the node is already a member of a fabric. if (server->FabricState->FabricId != 0) { server->SendStatusReport(kWeaveProfile_FabricProvisioning, kStatusCode_AlreadyMemberOfFabric); ExitNow(); } // Join an existing fabric identified by the supplied fabric state. Right now the only possible // reason for this to fail is bad input data. err = server->FabricState->JoinExistingFabric(msgBuf->Start(), msgBuf->DataLength()); if (err != WEAVE_NO_ERROR) { server->SendStatusReport(kWeaveProfile_FabricProvisioning, kStatusCode_InvalidFabricConfig); ExitNow(); } // Call the application to perform any join-time operations (such as address assignment). // Note that this can fail, in which case we abort the fabric join. err = delegate->HandleJoinExistingFabric(); if (err != WEAVE_NO_ERROR) server->FabricState->ClearFabricState(); SuccessOrExit(err); break; default: server->SendStatusReport(kWeaveProfile_Common, Common::kStatus_BadRequest); break; } exit: if (msgBuf != NULL) PacketBuffer::Free(msgBuf); if (err != WEAVE_NO_ERROR && server->mCurClientOp != NULL && ec == server->mCurClientOp) { uint16_t statusCode = (err == WEAVE_ERROR_INVALID_MESSAGE_LENGTH) ? Common::kStatus_BadRequest : Common::kStatus_InternalError; server->SendStatusReport(kWeaveProfile_Common, statusCode, err); } } void FabricProvisioningDelegate::EnforceAccessControl(ExchangeContext *ec, uint32_t msgProfileId, uint8_t msgType, const WeaveMessageInfo *msgInfo, AccessControlResult& result) { // If the result has not already been determined by a subclass... if (result == kAccessControlResult_NotDetermined) { switch (msgType) { #if WEAVE_CONFIG_REQUIRE_AUTH_FABRIC_PROV case kMsgType_CreateFabric: case kMsgType_JoinExistingFabric: if (msgInfo->PeerAuthMode == kWeaveAuthMode_CASE_AccessToken || (msgInfo->PeerAuthMode == kWeaveAuthMode_PASE_PairingCode && !IsPairedToAccount())) { result = kAccessControlResult_Accepted; } break; case kMsgType_LeaveFabric: case kMsgType_GetFabricConfig: if (msgInfo->PeerAuthMode == kWeaveAuthMode_CASE_AccessToken) { result = kAccessControlResult_Accepted; } break; #else // WEAVE_CONFIG_REQUIRE_AUTH_FABRIC_PROV case kMsgType_CreateFabric: case kMsgType_JoinExistingFabric: case kMsgType_LeaveFabric: case kMsgType_GetFabricConfig: result = kAccessControlResult_Accepted; break; #endif // WEAVE_CONFIG_REQUIRE_AUTH_FABRIC_PROV default: WeaveServerBase::SendStatusReport(ec, kWeaveProfile_Common, Common::kStatus_UnsupportedMessage, WEAVE_NO_ERROR); result = kAccessControlResult_Rejected_RespSent; break; } } // Call up to the base class. WeaveServerDelegateBase::EnforceAccessControl(ec, msgProfileId, msgType, msgInfo, result); } // TODO: eliminate this method when device code provides appropriate implementations. bool FabricProvisioningDelegate::IsPairedToAccount() const { return false; } } /* namespace FabricProvisioning */ } /* namespace Profiles */ } /* namespace Weave */ } /* namespace nl */
34.481183
133
0.67662
[ "object" ]
4ff5abd01881f2be8f86a3dd17fa2443985634ba
7,786
cpp
C++
libs/opengl/src/CPointCloudColoured.cpp
feroze/mrpt-shivang
95bf524c5e10ed2e622bd199f1b0597951b45370
[ "BSD-3-Clause" ]
2
2017-03-25T18:09:17.000Z
2017-05-22T08:14:48.000Z
libs/opengl/src/CPointCloudColoured.cpp
feroze/mrpt-shivang
95bf524c5e10ed2e622bd199f1b0597951b45370
[ "BSD-3-Clause" ]
null
null
null
libs/opengl/src/CPointCloudColoured.cpp
feroze/mrpt-shivang
95bf524c5e10ed2e622bd199f1b0597951b45370
[ "BSD-3-Clause" ]
1
2018-07-29T09:40:46.000Z
2018-07-29T09:40:46.000Z
/* +---------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2017, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +---------------------------------------------------------------------------+ */ #include "opengl-precomp.h" // Precompiled header #include <mrpt/opengl/CPointCloudColoured.h> #include <mrpt/utils/round.h> // round() #include <mrpt/utils/CStream.h> #include <mrpt/math/ops_containers.h> // for << ops #include <mrpt/utils/stl_serialization.h> #include "opengl_internals.h" using namespace mrpt; using namespace mrpt::opengl; using namespace mrpt::utils; //using namespace mrpt::slam; using namespace mrpt::math; using namespace std; IMPLEMENTS_SERIALIZABLE( CPointCloudColoured, CRenderizable, mrpt::opengl ) /*--------------------------------------------------------------- render ---------------------------------------------------------------*/ void CPointCloudColoured::render() const { #if MRPT_HAS_OPENGL_GLUT octree_assure_uptodate(); // Rebuild octree if needed m_last_rendered_count_ongoing = 0; // Info needed by octree renderer: gl_utils::TRenderInfo ri; gl_utils::getCurrentRenderingInfo(ri); if ( m_color.A != 255 ) { glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); } glPointSize( m_pointSize ); if (m_pointSmooth) glEnable ( GL_POINT_SMOOTH ); else glDisable( GL_POINT_SMOOTH ); // Disable lighting for point clouds: glDisable(GL_LIGHTING); glBegin( GL_POINTS ); octree_render(ri); // Render all points recursively: glEnd(); glEnable(GL_LIGHTING); // Undo flags: if ( m_color.A != 255 ) glDisable(GL_BLEND); if (m_pointSmooth) glDisable( GL_POINT_SMOOTH ); m_last_rendered_count = m_last_rendered_count_ongoing; checkOpenGLError(); #endif } /** Render a subset of points (required by octree renderer) */ void CPointCloudColoured::render_subset(const bool all, const std::vector<size_t>& idxs, const float render_area_sqpixels ) const { #if MRPT_HAS_OPENGL_GLUT const size_t N = all ? m_points.size() : idxs.size(); const size_t decimation = mrpt::utils::round( std::max(1.0f, static_cast<float>(N / (mrpt::global_settings::OCTREE_RENDER_MAX_DENSITY_POINTS_PER_SQPIXEL * render_area_sqpixels)) ) ); m_last_rendered_count_ongoing += N/decimation; m_last_rendered_count_ongoing += (all ? m_points.size() : idxs.size())/decimation; if (all) { for (size_t i=0;i<N;i+=decimation) { const TPointColour &p = m_points[i]; glColor4f( p.R, p.G, p.B,m_color.A*1.0f/255.f ); glVertex3f( p.x,p.y,p.z ); } } else { for (size_t i=0;i<N;i+=decimation) { const TPointColour &p = m_points[idxs[i]]; glColor4f( p.R, p.G, p.B,m_color.A*1.0f/255.f ); glVertex3f( p.x,p.y,p.z ); } } #else MRPT_UNUSED_PARAM(all); MRPT_UNUSED_PARAM(idxs); MRPT_UNUSED_PARAM(render_area_sqpixels); #endif } /*--------------------------------------------------------------- Implements the writing to a CStream capability of CSerializable objects ---------------------------------------------------------------*/ void CPointCloudColoured::writeToStream(mrpt::utils::CStream &out,int *version) const { if (version) *version = 2; else { writeToStreamRender(out); out << m_points; out << m_pointSize; out << m_pointSmooth; // Added in v2 } } /*--------------------------------------------------------------- Implements the reading from a CStream capability of CSerializable objects ---------------------------------------------------------------*/ void CPointCloudColoured::readFromStream(mrpt::utils::CStream &in,int version) { switch(version) { case 1: case 2: { readFromStreamRender(in); in >> m_points >> m_pointSize; if (version>=2) in >> m_pointSmooth; else m_pointSmooth = false; } break; case 0: { readFromStreamRender(in); // Old vector_serializable: uint32_t n; in >> n; m_points.resize(n); for (uint32_t i=0;i<n;i++) in >> m_points[i]; in >> m_pointSize; } break; default: MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(version) }; markAllPointsAsNew(); } CStream& mrpt::opengl::operator >> (mrpt::utils::CStream& in, CPointCloudColoured::TPointColour &o) { in >> o.x >> o.y >> o.z >> o.R >> o.G >> o.B; return in; } CStream& mrpt::opengl::operator << (mrpt::utils::CStream& out, const CPointCloudColoured::TPointColour &o) { out << o.x << o.y << o.z << o.R << o.G << o.B; return out; } /** Write an individual point (checks for "i" in the valid range only in Debug). */ void CPointCloudColoured::setPoint(size_t i, const TPointColour &p ) { #ifdef _DEBUG ASSERT_BELOW_(i,size()) #endif m_points[i] = p; // JL: TODO note: Well, this can be clearly done much more efficiently but...I don't have time! :-( markAllPointsAsNew(); } /** Inserts a new point into the point cloud. */ void CPointCloudColoured::push_back(float x,float y,float z, float R, float G, float B) { m_points.push_back(TPointColour(x,y,z,R,G,B)); // JL: TODO note: Well, this can be clearly done much more efficiently but...I don't have time! :-( markAllPointsAsNew(); } // Do needed internal work if all points are new (octree rebuilt,...) void CPointCloudColoured::markAllPointsAsNew() { octree_mark_as_outdated(); } /** In a base class, reserve memory to prepare subsequent calls to PLY_import_set_vertex */ void CPointCloudColoured::PLY_import_set_vertex_count(const size_t N) { this->resize(N); } /** In a base class, will be called after PLY_import_set_vertex_count() once for each loaded point. * \param pt_color Will be NULL if the loaded file does not provide color info. */ void CPointCloudColoured::PLY_import_set_vertex(const size_t idx, const mrpt::math::TPoint3Df &pt, const mrpt::utils::TColorf *pt_color) { if (!pt_color) this->setPoint(idx,TPointColour(pt.x,pt.y,pt.z,1,1,1)); else this->setPoint(idx,TPointColour(pt.x,pt.y,pt.z,pt_color->R,pt_color->G,pt_color->B)); } /** In a base class, return the number of vertices */ size_t CPointCloudColoured::PLY_export_get_vertex_count() const { return this->size(); } /** In a base class, will be called after PLY_export_get_vertex_count() once for each exported point. * \param pt_color Will be NULL if the loaded file does not provide color info. */ void CPointCloudColoured::PLY_export_get_vertex( const size_t idx, mrpt::math::TPoint3Df &pt, bool &pt_has_color, mrpt::utils::TColorf &pt_color) const { const TPointColour &p = m_points[idx]; pt.x = p.x; pt.y = p.y; pt.z = p.z; pt_color.R = p.R; pt_color.G = p.G; pt_color.B = p.B; pt_has_color=true; } void CPointCloudColoured::recolorizeByCoordinate(const float coord_min, const float coord_max, const int coord_index, const mrpt::utils::TColormap color_map) { ASSERT_ABOVEEQ_(coord_index,0); ASSERT_BELOW_(coord_index,3); const float coord_range = coord_max-coord_min; const float coord_range_1 = coord_range!=0.0f ? 1.0f/coord_range : 1.0f; for (size_t i=0;i<m_points.size();i++) { float coord =.0f; switch (coord_index) { case 0: coord = m_points[i].x; break; case 1: coord = m_points[i].y; break; case 2: coord = m_points[i].z; break; }; const float col_idx = std::max(0.0f, std::min(1.0f,(coord-coord_min)*coord_range_1 ) ); float r,g,b; mrpt::utils::colormap(color_map, col_idx,r,g,b); this->setPointColor_fast(i,r,g,b); } }
28.625
183
0.639353
[ "render", "vector" ]
4ff74dbb3ff11a44170f51f2cb682f3b09d13048
166,877
cpp
C++
scene/gui/text_edit.cpp
TailyFair/godot
36787621f95a74a8f02cfead23e8dd959e08b527
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
scene/gui/text_edit.cpp
TailyFair/godot
36787621f95a74a8f02cfead23e8dd959e08b527
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
scene/gui/text_edit.cpp
TailyFair/godot
36787621f95a74a8f02cfead23e8dd959e08b527
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
/*************************************************************************/ /* text_edit.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */ /* */ /* 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 "text_edit.h" #include "message_queue.h" #include "os/input.h" #include "os/keyboard.h" #include "os/os.h" #include "project_settings.h" #include "scene/main/viewport.h" #ifdef TOOLS_ENABLED #include "editor/editor_scale.h" #endif #define TAB_PIXELS inline bool _is_symbol(CharType c) { return is_symbol(c); } static bool _is_text_char(CharType c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_'; } static bool _is_whitespace(CharType c) { return c == '\t' || c == ' '; } static bool _is_char(CharType c) { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_'; } static bool _is_number(CharType c) { return (c >= '0' && c <= '9'); } static bool _is_hex_symbol(CharType c) { return ((c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')); } static bool _is_pair_right_symbol(CharType c) { return c == '"' || c == '\'' || c == ')' || c == ']' || c == '}'; } static bool _is_pair_left_symbol(CharType c) { return c == '"' || c == '\'' || c == '(' || c == '[' || c == '{'; } static bool _is_pair_symbol(CharType c) { return _is_pair_left_symbol(c) || _is_pair_right_symbol(c); } static CharType _get_right_pair_symbol(CharType c) { if (c == '"') return '"'; if (c == '\'') return '\''; if (c == '(') return ')'; if (c == '[') return ']'; if (c == '{') return '}'; return 0; } void TextEdit::Text::set_font(const Ref<Font> &p_font) { font = p_font; } void TextEdit::Text::set_indent_size(int p_indent_size) { indent_size = p_indent_size; } void TextEdit::Text::_update_line_cache(int p_line) const { int w = 0; int tab_w = font->get_char_size(' ').width * indent_size; int len = text[p_line].data.length(); const CharType *str = text[p_line].data.c_str(); //update width for (int i = 0; i < len; i++) { if (str[i] == '\t') { int left = w % tab_w; if (left == 0) w += tab_w; else w += tab_w - w % tab_w; // is right... } else { w += font->get_char_size(str[i], str[i + 1]).width; } } text[p_line].width_cache = w; //update regions text[p_line].region_info.clear(); for (int i = 0; i < len; i++) { if (!_is_symbol(str[i])) continue; if (str[i] == '\\') { i++; //skip quoted anything continue; } int left = len - i; for (int j = 0; j < color_regions->size(); j++) { const ColorRegion &cr = color_regions->operator[](j); /* BEGIN */ int lr = cr.begin_key.length(); if (lr == 0 || lr > left) continue; const CharType *kc = cr.begin_key.c_str(); bool match = true; for (int k = 0; k < lr; k++) { if (kc[k] != str[i + k]) { match = false; break; } } if (match) { ColorRegionInfo cri; cri.end = false; cri.region = j; text[p_line].region_info[i] = cri; i += lr - 1; break; } /* END */ lr = cr.end_key.length(); if (lr == 0 || lr > left) continue; kc = cr.end_key.c_str(); match = true; for (int k = 0; k < lr; k++) { if (kc[k] != str[i + k]) { match = false; break; } } if (match) { ColorRegionInfo cri; cri.end = true; cri.region = j; text[p_line].region_info[i] = cri; i += lr - 1; break; } } } } const Map<int, TextEdit::Text::ColorRegionInfo> &TextEdit::Text::get_color_region_info(int p_line) const { static Map<int, ColorRegionInfo> cri; ERR_FAIL_INDEX_V(p_line, text.size(), cri); if (text[p_line].width_cache == -1) { _update_line_cache(p_line); } return text[p_line].region_info; } int TextEdit::Text::get_line_width(int p_line) const { ERR_FAIL_INDEX_V(p_line, text.size(), -1); if (text[p_line].width_cache == -1) { _update_line_cache(p_line); } return text[p_line].width_cache; } void TextEdit::Text::clear_caches() { for (int i = 0; i < text.size(); i++) text[i].width_cache = -1; } void TextEdit::Text::clear() { text.clear(); insert(0, ""); } int TextEdit::Text::get_max_width(bool p_exclude_hidden) const { //quite some work.. but should be fast enough. int max = 0; for (int i = 0; i < text.size(); i++) { if (!p_exclude_hidden || !is_hidden(i)) max = MAX(max, get_line_width(i)); } return max; } void TextEdit::Text::set(int p_line, const String &p_text) { ERR_FAIL_INDEX(p_line, text.size()); text[p_line].width_cache = -1; text[p_line].data = p_text; } void TextEdit::Text::insert(int p_at, const String &p_text) { Line line; line.marked = false; line.breakpoint = false; line.hidden = false; line.width_cache = -1; line.data = p_text; text.insert(p_at, line); } void TextEdit::Text::remove(int p_at) { text.remove(p_at); } void TextEdit::_update_scrollbars() { Size2 size = get_size(); Size2 hmin = h_scroll->get_combined_minimum_size(); Size2 vmin = v_scroll->get_combined_minimum_size(); v_scroll->set_begin(Point2(size.width - vmin.width, cache.style_normal->get_margin(MARGIN_TOP))); v_scroll->set_end(Point2(size.width, size.height - cache.style_normal->get_margin(MARGIN_TOP) - cache.style_normal->get_margin(MARGIN_BOTTOM))); h_scroll->set_begin(Point2(0, size.height - hmin.height)); h_scroll->set_end(Point2(size.width - vmin.width, size.height)); int hscroll_rows = ((hmin.height - 1) / get_row_height()) + 1; int visible_rows = get_visible_rows(); int num_rows = MAX(visible_rows, num_lines_from(CLAMP(cursor.line_ofs, 0, text.size() - 1), MIN(visible_rows, text.size() - 1 - cursor.line_ofs))); int total_rows = (is_hiding_enabled() ? get_total_unhidden_rows() : text.size()); if (scroll_past_end_of_file_enabled) { total_rows += visible_rows - 1; } int vscroll_pixels = v_scroll->get_combined_minimum_size().width; int visible_width = size.width - cache.style_normal->get_minimum_size().width; int total_width = text.get_max_width(true) + vmin.x; if (line_numbers) total_width += cache.line_number_w; if (draw_breakpoint_gutter) { total_width += cache.breakpoint_gutter_width; } if (draw_fold_gutter) { total_width += cache.fold_gutter_width; } bool use_hscroll = true; bool use_vscroll = true; if (total_rows <= visible_rows && total_width <= visible_width) { //thanks yessopie for this clever bit of logic use_hscroll = false; use_vscroll = false; } else { if (total_rows > visible_rows && total_width <= visible_width - vscroll_pixels) { //thanks yessopie for this clever bit of logic use_hscroll = false; } if (total_rows <= visible_rows - hscroll_rows && total_width > visible_width) { //thanks yessopie for this clever bit of logic use_vscroll = false; } } updating_scrolls = true; if (use_vscroll) { v_scroll->show(); v_scroll->set_max(total_rows); v_scroll->set_page(visible_rows); if (smooth_scroll_enabled) { v_scroll->set_step(0.25); } else { v_scroll->set_step(1); } update_line_scroll_pos(); if (fabs(v_scroll->get_value() - get_line_scroll_pos()) >= 1) { cursor.line_ofs += v_scroll->get_value() - get_line_scroll_pos(); } } else { cursor.line_ofs = 0; line_scroll_pos = 0; v_scroll->set_value(0); v_scroll->hide(); } if (use_hscroll) { h_scroll->show(); h_scroll->set_max(total_width); h_scroll->set_page(visible_width); if (cursor.x_ofs > (total_width - visible_width)) cursor.x_ofs = (total_width - visible_width); if (fabs(h_scroll->get_value() - (double)cursor.x_ofs) >= 1) { h_scroll->set_value(cursor.x_ofs); } } else { cursor.x_ofs = 0; h_scroll->set_value(0); h_scroll->hide(); } updating_scrolls = false; } void TextEdit::_click_selection_held() { if (Input::get_singleton()->is_mouse_button_pressed(BUTTON_LEFT) && selection.selecting_mode != Selection::MODE_NONE) { switch (selection.selecting_mode) { case Selection::MODE_POINTER: { _update_selection_mode_pointer(); } break; case Selection::MODE_WORD: { _update_selection_mode_word(); } break; case Selection::MODE_LINE: { _update_selection_mode_line(); } break; default: { break; } } } else { click_select_held->stop(); } } void TextEdit::_update_selection_mode_pointer() { Point2 mp = Input::get_singleton()->get_mouse_position() - get_global_position(); int row, col; _get_mouse_pos(Point2i(mp.x, mp.y), row, col); select(selection.selecting_line, selection.selecting_column, row, col); cursor_set_line(row); cursor_set_column(col); update(); click_select_held->start(); } void TextEdit::_update_selection_mode_word() { Point2 mp = Input::get_singleton()->get_mouse_position() - get_global_position(); int row, col; _get_mouse_pos(Point2i(mp.x, mp.y), row, col); String line = text[row]; int beg = CLAMP(col, 0, line.length()); // if its the first selection and on whitespace make sure we grab the word instead.. if (!selection.active) { while (beg > 0 && line[beg] <= 32) { beg--; } } int end = beg; bool symbol = beg < line.length() && _is_symbol(line[beg]); // get the word end and begin points while (beg > 0 && line[beg - 1] > 32 && (symbol == _is_symbol(line[beg - 1]))) { beg--; } while (end < line.length() && line[end + 1] > 32 && (symbol == _is_symbol(line[end + 1]))) { end++; } if (end < line.length()) { end += 1; } // initial selection if (!selection.active) { select(row, beg, row, end); selection.selecting_column = beg; selection.selected_word_beg = beg; selection.selected_word_end = end; selection.selected_word_origin = beg; cursor_set_column(selection.to_column); } else { if ((col <= selection.selected_word_origin && row == selection.selecting_line) || row < selection.selecting_line) { selection.selecting_column = selection.selected_word_end; select(row, beg, selection.selecting_line, selection.selected_word_end); cursor_set_column(selection.from_column); } else { selection.selecting_column = selection.selected_word_beg; select(selection.selecting_line, selection.selected_word_beg, row, end); cursor_set_column(selection.to_column); } } cursor_set_line(row); update(); click_select_held->start(); } void TextEdit::_update_selection_mode_line() { Point2 mp = Input::get_singleton()->get_mouse_position() - get_global_position(); int row, col; _get_mouse_pos(Point2i(mp.x, mp.y), row, col); col = 0; if (row < selection.selecting_line) { // cursor is above us cursor_set_line(row - 1); selection.selecting_column = text[selection.selecting_line].length(); } else { // cursor is below us cursor_set_line(row + 1); selection.selecting_column = 0; col = text[row].length(); } cursor_set_column(0); select(selection.selecting_line, selection.selecting_column, row, col); update(); click_select_held->start(); } void TextEdit::_notification(int p_what) { switch (p_what) { case NOTIFICATION_ENTER_TREE: { _update_caches(); if (cursor_changed_dirty) MessageQueue::get_singleton()->push_call(this, "_cursor_changed_emit"); if (text_changed_dirty) MessageQueue::get_singleton()->push_call(this, "_text_changed_emit"); } break; case NOTIFICATION_RESIZED: { cache.size = get_size(); adjust_viewport_to_cursor(); } break; case NOTIFICATION_THEME_CHANGED: { _update_caches(); } break; case MainLoop::NOTIFICATION_WM_FOCUS_IN: { window_has_focus = true; draw_caret = true; update(); } break; case MainLoop::NOTIFICATION_WM_FOCUS_OUT: { window_has_focus = false; draw_caret = false; update(); } break; case NOTIFICATION_INTERNAL_PHYSICS_PROCESS: { if (scrolling && v_scroll->get_value() != target_v_scroll) { double target_y = target_v_scroll - v_scroll->get_value(); double dist = sqrt(target_y * target_y); double vel = ((target_y / dist) * v_scroll_speed) * get_physics_process_delta_time(); if (Math::abs(vel) >= dist) { v_scroll->set_value(target_v_scroll); scrolling = false; set_physics_process_internal(false); } else { v_scroll->set_value(v_scroll->get_value() + vel); } } else { scrolling = false; set_physics_process_internal(false); } } break; case NOTIFICATION_DRAW: { if ((!has_focus() && !menu->has_focus()) || !window_has_focus) { draw_caret = false; } if (draw_breakpoint_gutter) { breakpoint_gutter_width = (get_row_height() * 55) / 100; cache.breakpoint_gutter_width = breakpoint_gutter_width; } else { cache.breakpoint_gutter_width = 0; } if (draw_fold_gutter) { fold_gutter_width = (get_row_height() * 55) / 100; cache.fold_gutter_width = fold_gutter_width; } else { cache.fold_gutter_width = 0; } int line_number_char_count = 0; { int lc = text.size(); cache.line_number_w = 0; while (lc) { cache.line_number_w += 1; lc /= 10; }; if (line_numbers) { line_number_char_count = cache.line_number_w; cache.line_number_w = (cache.line_number_w + 1) * cache.font->get_char_size('0').width; } else { cache.line_number_w = 0; } } _update_scrollbars(); RID ci = get_canvas_item(); VisualServer::get_singleton()->canvas_item_set_clip(get_canvas_item(), true); int xmargin_beg = cache.style_normal->get_margin(MARGIN_LEFT) + cache.line_number_w + cache.breakpoint_gutter_width + cache.fold_gutter_width; int xmargin_end = cache.size.width - cache.style_normal->get_margin(MARGIN_RIGHT); //let's do it easy for now: cache.style_normal->draw(ci, Rect2(Point2(), cache.size)); float readonly_alpha = 1.0; // used to set the input text color when in read-only mode if (readonly) { cache.style_readonly->draw(ci, Rect2(Point2(), cache.size)); readonly_alpha = .5; draw_caret = false; } if (has_focus()) cache.style_focus->draw(ci, Rect2(Point2(), cache.size)); int ascent = cache.font->get_ascent(); int visible_rows = get_visible_rows() + 1; int tab_w = cache.font->get_char_size(' ').width * indent_size; Color color = cache.font_color; color.a *= readonly_alpha; if (syntax_coloring) { if (cache.background_color.a > 0.01) { VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2i(), get_size()), cache.background_color); } } int brace_open_match_line = -1; int brace_open_match_column = -1; bool brace_open_matching = false; bool brace_open_mismatch = false; int brace_close_match_line = -1; int brace_close_match_column = -1; bool brace_close_matching = false; bool brace_close_mismatch = false; if (brace_matching_enabled) { if (cursor.column < text[cursor.line].length()) { //check for open CharType c = text[cursor.line][cursor.column]; CharType closec = 0; if (c == '[') { closec = ']'; } else if (c == '{') { closec = '}'; } else if (c == '(') { closec = ')'; } if (closec != 0) { int stack = 1; for (int i = cursor.line; i < text.size(); i++) { int from = i == cursor.line ? cursor.column + 1 : 0; for (int j = from; j < text[i].length(); j++) { CharType cc = text[i][j]; //ignore any brackets inside a string if (cc == '"' || cc == '\'') { CharType quotation = cc; do { j++; if (!(j < text[i].length())) { break; } cc = text[i][j]; //skip over escaped quotation marks inside strings if (cc == '\\') { bool escaped = true; while (j + 1 < text[i].length() && text[i][j + 1] == '\\') { escaped = !escaped; j++; } if (escaped) { j++; continue; } } } while (cc != quotation); } else if (cc == c) stack++; else if (cc == closec) stack--; if (stack == 0) { brace_open_match_line = i; brace_open_match_column = j; brace_open_matching = true; break; } } if (brace_open_match_line != -1) break; } if (!brace_open_matching) brace_open_mismatch = true; } } if (cursor.column > 0) { CharType c = text[cursor.line][cursor.column - 1]; CharType closec = 0; if (c == ']') { closec = '['; } else if (c == '}') { closec = '{'; } else if (c == ')') { closec = '('; } if (closec != 0) { int stack = 1; for (int i = cursor.line; i >= 0; i--) { int from = i == cursor.line ? cursor.column - 2 : text[i].length() - 1; for (int j = from; j >= 0; j--) { CharType cc = text[i][j]; //ignore any brackets inside a string if (cc == '"' || cc == '\'') { CharType quotation = cc; do { j--; if (!(j >= 0)) { break; } cc = text[i][j]; //skip over escaped quotation marks inside strings if (cc == quotation) { bool escaped = false; while (j - 1 >= 0 && text[i][j - 1] == '\\') { escaped = !escaped; j--; } if (escaped) { cc = '\\'; continue; } } } while (cc != quotation); } else if (cc == c) stack++; else if (cc == closec) stack--; if (stack == 0) { brace_close_match_line = i; brace_close_match_column = j; brace_close_matching = true; break; } } if (brace_close_match_line != -1) break; } if (!brace_close_matching) brace_close_mismatch = true; } } } Point2 cursor_pos; // get the highlighted words String highlighted_text = get_selection_text(); String line_num_padding = line_numbers_zero_padded ? "0" : " "; update_line_scroll_pos(); int line = cursor.line_ofs - 1; // another row may be visible during smooth scrolling int draw_amount = visible_rows + (smooth_scroll_enabled ? 1 : 0); FontDrawer drawer(cache.font, Color(1, 1, 1)); for (int i = 0; i < draw_amount; i++) { line++; if (line < 0 || line >= (int)text.size()) continue; while (is_line_hidden(line)) { line++; if (line < 0 || line >= (int)text.size()) { break; } } if (line < 0 || line >= (int)text.size()) continue; const String &str = text[line]; int char_margin = xmargin_beg - cursor.x_ofs; int char_ofs = 0; int ofs_readonly = 0; int ofs_x = 0; if (readonly) { ofs_readonly = cache.style_readonly->get_offset().y / 2; ofs_x = cache.style_readonly->get_offset().x / 2; } int ofs_y = (i * get_row_height() + cache.line_spacing / 2) + ofs_readonly; if (smooth_scroll_enabled) ofs_y -= ((v_scroll->get_value() - get_line_scroll_pos()) * get_row_height()); bool underlined = false; // check if line contains highlighted word int highlighted_text_col = -1; int search_text_col = -1; int highlighted_word_col = -1; if (!search_text.empty()) search_text_col = _get_column_pos_of_word(search_text, str, search_flags, 0); if (highlighted_text.length() != 0 && highlighted_text != search_text) highlighted_text_col = _get_column_pos_of_word(highlighted_text, str, SEARCH_MATCH_CASE | SEARCH_WHOLE_WORDS, 0); if (select_identifiers_enabled && highlighted_word.length() != 0) { if (_is_char(highlighted_word[0])) { highlighted_word_col = _get_column_pos_of_word(highlighted_word, str, SEARCH_MATCH_CASE | SEARCH_WHOLE_WORDS, 0); } } if (text.is_marked(line)) { VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(xmargin_beg + ofs_x, ofs_y, xmargin_end - xmargin_beg, get_row_height()), cache.mark_color); } if (str.length() == 0) { // draw line background if empty as we won't loop at at all if (line == cursor.line && highlight_current_line) { VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(ofs_x, ofs_y, xmargin_end, get_row_height()), cache.current_line_color); } // give visual indication of empty selected line if (selection.active && line >= selection.from_line && line <= selection.to_line && char_margin >= xmargin_beg) { int char_w = cache.font->get_char_size(' ').width; VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(xmargin_beg + ofs_x, ofs_y, char_w, get_row_height()), cache.selection_color); } } else { // if it has text, then draw current line marker in the margin, as line number etc will draw over it, draw the rest of line marker later. if (line == cursor.line && highlight_current_line) { VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(0, ofs_y, xmargin_beg + ofs_x, get_row_height()), cache.current_line_color); } } if (text.is_breakpoint(line) && !draw_breakpoint_gutter) { #ifdef TOOLS_ENABLED VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(xmargin_beg + ofs_x, ofs_y + get_row_height() - EDSCALE, xmargin_end - xmargin_beg, EDSCALE), cache.breakpoint_color); #else VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(xmargin_beg + ofs_x, ofs_y, xmargin_end - xmargin_beg, get_row_height()), cache.breakpoint_color); #endif } // draw breakpoint marker if (text.is_breakpoint(line)) { if (draw_breakpoint_gutter) { int vertical_gap = (get_row_height() * 40) / 100; int horizontal_gap = (cache.breakpoint_gutter_width * 30) / 100; int marker_height = get_row_height() - (vertical_gap * 2); int marker_width = cache.breakpoint_gutter_width - (horizontal_gap * 2); // no transparency on marker VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(cache.style_normal->get_margin(MARGIN_LEFT) + horizontal_gap - 2, ofs_y + vertical_gap, marker_width, marker_height), Color(cache.breakpoint_color.r, cache.breakpoint_color.g, cache.breakpoint_color.b)); } } // draw fold markers if (draw_fold_gutter) { int horizontal_gap = (cache.fold_gutter_width * 30) / 100; int gutter_left = cache.style_normal->get_margin(MARGIN_LEFT) + cache.breakpoint_gutter_width + cache.line_number_w; if (is_folded(line)) { int xofs = horizontal_gap - (cache.can_fold_icon->get_width()) / 2; int yofs = (get_row_height() - cache.folded_icon->get_height()) / 2; cache.folded_icon->draw(ci, Point2(gutter_left + xofs + ofs_x, ofs_y + yofs), cache.code_folding_color); } else if (can_fold(line)) { int xofs = -cache.can_fold_icon->get_width() / 2 - horizontal_gap + 3; int yofs = (get_row_height() - cache.can_fold_icon->get_height()) / 2; cache.can_fold_icon->draw(ci, Point2(gutter_left + xofs + ofs_x, ofs_y + yofs), cache.code_folding_color); } } if (cache.line_number_w) { String fc = String::num(line + 1); while (fc.length() < line_number_char_count) { fc = line_num_padding + fc; } cache.font->draw(ci, Point2(cache.style_normal->get_margin(MARGIN_LEFT) + cache.breakpoint_gutter_width + ofs_x, ofs_y + cache.font->get_ascent()), fc, cache.line_number_color); } //loop through characters in one line Map<int, HighlighterInfo> color_map; if (syntax_coloring) { color_map = _get_line_syntax_highlighting(line); } // ensure we at least use the font color Color current_color = cache.font_color; if (readonly) { current_color.a *= readonly_alpha; } for (int j = 0; j < str.length(); j++) { if (syntax_coloring) { if (color_map.has(j)) { current_color = color_map[j].color; if (readonly) { current_color.a *= readonly_alpha; } } color = current_color; } int char_w; //handle tabulator if (str[j] == '\t') { int left = char_ofs % tab_w; if (left == 0) char_w = tab_w; else char_w = tab_w - char_ofs % tab_w; // is right... } else { char_w = cache.font->get_char_size(str[j], str[j + 1]).width; } if ((char_ofs + char_margin) < xmargin_beg) { char_ofs += char_w; // line highlighting handle horizontal clipping if (line == cursor.line && highlight_current_line) { if (j == str.length() - 1) { // end of line when last char is skipped VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(xmargin_beg + ofs_x, ofs_y, xmargin_end - (xmargin_beg + ofs_x), get_row_height()), cache.current_line_color); } else if ((char_ofs + char_margin) > xmargin_beg) { // char next to margin is skipped VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(xmargin_beg + ofs_x, ofs_y, (char_ofs + char_margin) - xmargin_beg, get_row_height()), cache.current_line_color); } } continue; } if ((char_ofs + char_margin + char_w) >= xmargin_end) { if (syntax_coloring) continue; else break; } bool in_search_result = false; if (search_text_col != -1) { // if we are at the end check for new search result on same line if (j >= search_text_col + search_text.length()) search_text_col = _get_column_pos_of_word(search_text, str, search_flags, j); in_search_result = j >= search_text_col && j < search_text_col + search_text.length(); if (in_search_result) { VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2i(char_ofs + char_margin, ofs_y), Size2i(char_w, get_row_height())), cache.search_result_color); } } //current line highlighting bool in_selection = (selection.active && line >= selection.from_line && line <= selection.to_line && (line > selection.from_line || j >= selection.from_column) && (line < selection.to_line || j < selection.to_column)); if (line == cursor.line && highlight_current_line) { // if its the last char draw to end of the line if (j == str.length() - 1) { VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(char_ofs + char_margin + char_w, ofs_y, xmargin_end - (char_ofs + char_margin + char_w), get_row_height()), cache.current_line_color); } // actual text if (!in_selection) { VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2i(char_ofs + char_margin + ofs_x, ofs_y), Size2i(char_w, get_row_height())), cache.current_line_color); } } if (in_selection) { VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2i(char_ofs + char_margin + ofs_x, ofs_y), Size2i(char_w, get_row_height())), cache.selection_color); } if (in_search_result) { Color border_color = (line == search_result_line && j >= search_result_col && j < search_result_col + search_text.length()) ? cache.font_color : cache.search_result_border_color; VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2i(char_ofs + char_margin + ofs_x, ofs_y), Size2i(char_w, 1)), border_color); VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2i(char_ofs + char_margin + ofs_x, ofs_y + get_row_height() - 1), Size2i(char_w, 1)), border_color); if (j == search_text_col) VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2i(char_ofs + char_margin + ofs_x, ofs_y), Size2i(1, get_row_height())), border_color); if (j == search_text_col + search_text.length() - 1) VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2i(char_ofs + char_margin + char_w + ofs_x - 1, ofs_y), Size2i(1, get_row_height())), border_color); } if (highlight_all_occurrences) { if (highlighted_text_col != -1) { // if we are at the end check for new word on same line if (j > highlighted_text_col + highlighted_text.length()) { highlighted_text_col = _get_column_pos_of_word(highlighted_text, str, SEARCH_MATCH_CASE | SEARCH_WHOLE_WORDS, j); } bool in_highlighted_word = (j >= highlighted_text_col && j < highlighted_text_col + highlighted_text.length()); /* if this is the original highlighted text we don't want to highlight it again */ if (cursor.line == line && (cursor.column >= highlighted_text_col && cursor.column <= highlighted_text_col + highlighted_text.length())) { in_highlighted_word = false; } if (in_highlighted_word) { VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2i(char_ofs + char_margin + ofs_x, ofs_y), Size2i(char_w, get_row_height())), cache.word_highlighted_color); } } } if (highlighted_word_col != -1) { if (j > highlighted_word_col + highlighted_word.length()) { highlighted_word_col = _get_column_pos_of_word(highlighted_word, str, SEARCH_MATCH_CASE | SEARCH_WHOLE_WORDS, j); } underlined = (j >= highlighted_word_col && j < highlighted_word_col + highlighted_word.length()); } if (brace_matching_enabled) { if ((brace_open_match_line == line && brace_open_match_column == j) || (cursor.column == j && cursor.line == line && (brace_open_matching || brace_open_mismatch))) { if (brace_open_mismatch) color = cache.brace_mismatch_color; drawer.draw_char(ci, Point2i(char_ofs + char_margin + ofs_x, ofs_y + ascent), '_', str[j + 1], in_selection && override_selected_font_color ? cache.font_selected_color : color); } if ( (brace_close_match_line == line && brace_close_match_column == j) || (cursor.column == j + 1 && cursor.line == line && (brace_close_matching || brace_close_mismatch))) { if (brace_close_mismatch) color = cache.brace_mismatch_color; drawer.draw_char(ci, Point2i(char_ofs + char_margin + ofs_x, ofs_y + ascent), '_', str[j + 1], in_selection && override_selected_font_color ? cache.font_selected_color : color); } } if (cursor.column == j && cursor.line == line) { cursor_pos = Point2i(char_ofs + char_margin + ofs_x, ofs_y); if (insert_mode) { cursor_pos.y += (get_row_height() - 3); } int caret_w = (str[j] == '\t') ? cache.font->get_char_size(' ').width : char_w; if (ime_text.length() > 0) { int ofs = 0; while (true) { if (ofs >= ime_text.length()) break; CharType cchar = ime_text[ofs]; CharType next = ime_text[ofs + 1]; int im_char_width = cache.font->get_char_size(cchar, next).width; if ((char_ofs + char_margin + im_char_width) >= xmargin_end) break; bool selected = ofs >= ime_selection.x && ofs < ime_selection.x + ime_selection.y; if (selected) { VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2(char_ofs + char_margin, ofs_y + get_row_height()), Size2(im_char_width, 3)), color); } else { VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2(char_ofs + char_margin, ofs_y + get_row_height()), Size2(im_char_width, 1)), color); } drawer.draw_char(ci, Point2(char_ofs + char_margin + ofs_x, ofs_y + ascent), cchar, next, color); char_ofs += im_char_width; ofs++; } } if (ime_text.length() == 0) { if (draw_caret) { if (insert_mode) { int caret_h = (block_caret) ? 4 : 1; VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(cursor_pos, Size2i(caret_w, caret_h)), cache.caret_color); } else { caret_w = (block_caret) ? caret_w : 1; VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(cursor_pos, Size2i(caret_w, get_row_height())), cache.caret_color); } } } } if (cursor.column == j && cursor.line == line && block_caret && draw_caret && !insert_mode) { color = cache.caret_background_color; } else if (!syntax_coloring && block_caret) { color = cache.font_color; color.a *= readonly_alpha; } if (str[j] >= 32) { int w = drawer.draw_char(ci, Point2i(char_ofs + char_margin + ofs_x, ofs_y + ascent), str[j], str[j + 1], in_selection && override_selected_font_color ? cache.font_selected_color : color); if (underlined) { draw_rect(Rect2(char_ofs + char_margin + ofs_x, ofs_y + ascent + 2, w, 1), in_selection && override_selected_font_color ? cache.font_selected_color : color); } } else if (draw_tabs && str[j] == '\t') { int yofs = (get_row_height() - cache.tab_icon->get_height()) / 2; cache.tab_icon->draw(ci, Point2(char_ofs + char_margin + ofs_x, ofs_y + yofs), in_selection && override_selected_font_color ? cache.font_selected_color : color); } char_ofs += char_w; if (j == str.length() - 1 && is_folded(line)) { int yofs = (get_row_height() - cache.folded_eol_icon->get_height()) / 2; int xofs = cache.folded_eol_icon->get_width() / 2; Color eol_color = cache.code_folding_color; eol_color.a = 1; cache.folded_eol_icon->draw(ci, Point2(char_ofs + char_margin + xofs + ofs_x, ofs_y + yofs), eol_color); } } if (cursor.column == str.length() && cursor.line == line && (char_ofs + char_margin) >= xmargin_beg) { cursor_pos = Point2i(char_ofs + char_margin + ofs_x, ofs_y); if (insert_mode) { cursor_pos.y += (get_row_height() - 3); } if (ime_text.length() > 0) { int ofs = 0; while (true) { if (ofs >= ime_text.length()) break; CharType cchar = ime_text[ofs]; CharType next = ime_text[ofs + 1]; int im_char_width = cache.font->get_char_size(cchar, next).width; if ((char_ofs + char_margin + im_char_width) >= xmargin_end) break; bool selected = ofs >= ime_selection.x && ofs < ime_selection.x + ime_selection.y; if (selected) { VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2(char_ofs + char_margin, ofs_y + get_row_height()), Size2(im_char_width, 3)), color); } else { VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2(char_ofs + char_margin, ofs_y + get_row_height()), Size2(im_char_width, 1)), color); } drawer.draw_char(ci, Point2(char_ofs + char_margin + ofs_x, ofs_y + ascent), cchar, next, color); char_ofs += im_char_width; ofs++; } } if (ime_text.length() == 0) { if (draw_caret) { if (insert_mode) { int char_w = cache.font->get_char_size(' ').width; int caret_h = (block_caret) ? 4 : 1; VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(cursor_pos, Size2i(char_w, caret_h)), cache.caret_color); } else { int char_w = cache.font->get_char_size(' ').width; int caret_w = (block_caret) ? char_w : 1; VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(cursor_pos, Size2i(caret_w, get_row_height())), cache.caret_color); } } } } } if (line_length_guideline) { int x = xmargin_beg + cache.font->get_char_size('0').width * line_length_guideline_col - cursor.x_ofs; if (x > xmargin_beg && x < xmargin_end) { VisualServer::get_singleton()->canvas_item_add_line(ci, Point2(x, 0), Point2(x, cache.size.height), cache.line_length_guideline_color); } } bool completion_below = false; if (completion_active) { // code completion box Ref<StyleBox> csb = get_stylebox("completion"); int maxlines = get_constant("completion_lines"); int cmax_width = get_constant("completion_max_width") * cache.font->get_char_size('x').x; int scrollw = get_constant("completion_scroll_width"); Color scrollc = get_color("completion_scroll_color"); int lines = MIN(completion_options.size(), maxlines); int w = 0; int h = lines * get_row_height(); int nofs = cache.font->get_string_size(completion_base).width; if (completion_options.size() < 50) { for (int i = 0; i < completion_options.size(); i++) { int w2 = MIN(cache.font->get_string_size(completion_options[i]).x, cmax_width); if (w2 > w) w = w2; } } else { w = cmax_width; } int th = h + csb->get_minimum_size().y; if (cursor_pos.y + get_row_height() + th > get_size().height) { completion_rect.position.y = cursor_pos.y - th; } else { completion_rect.position.y = cursor_pos.y + get_row_height() + csb->get_offset().y; completion_below = true; } if (cursor_pos.x - nofs + w + scrollw > get_size().width) { completion_rect.position.x = get_size().width - w - scrollw; } else { completion_rect.position.x = cursor_pos.x - nofs; } completion_rect.size.width = w + 2; completion_rect.size.height = h; if (completion_options.size() <= maxlines) scrollw = 0; draw_style_box(csb, Rect2(completion_rect.position - csb->get_offset(), completion_rect.size + csb->get_minimum_size() + Size2(scrollw, 0))); if (cache.completion_background_color.a > 0.01) { VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(completion_rect.position, completion_rect.size + Size2(scrollw, 0)), cache.completion_background_color); } int line_from = CLAMP(completion_index - lines / 2, 0, completion_options.size() - lines); VisualServer::get_singleton()->canvas_item_add_rect(ci, Rect2(Point2(completion_rect.position.x, completion_rect.position.y + (completion_index - line_from) * get_row_height()), Size2(completion_rect.size.width, get_row_height())), cache.completion_selected_color); draw_rect(Rect2(completion_rect.position, Size2(nofs, completion_rect.size.height)), cache.completion_existing_color); for (int i = 0; i < lines; i++) { int l = line_from + i; ERR_CONTINUE(l < 0 || l >= completion_options.size()); Color text_color = cache.completion_font_color; for (int j = 0; j < color_regions.size(); j++) { if (completion_options[l].begins_with(color_regions[j].begin_key)) { text_color = color_regions[j].color; } } draw_string(cache.font, Point2(completion_rect.position.x, completion_rect.position.y + i * get_row_height() + cache.font->get_ascent()), completion_options[l], text_color, completion_rect.size.width); } if (scrollw) { //draw a small scroll rectangle to show a position in the options float r = maxlines / (float)completion_options.size(); float o = line_from / (float)completion_options.size(); draw_rect(Rect2(completion_rect.position.x + completion_rect.size.width, completion_rect.position.y + o * completion_rect.size.y, scrollw, completion_rect.size.y * r), scrollc); } completion_line_ofs = line_from; } // check to see if the hint should be drawn bool show_hint = false; if (completion_hint != "") { if (completion_active) { if (completion_below && !callhint_below) { show_hint = true; } else if (!completion_below && callhint_below) { show_hint = true; } } else { show_hint = true; } } if (show_hint) { Ref<StyleBox> sb = get_stylebox("panel", "TooltipPanel"); Ref<Font> font = cache.font; Color font_color = get_color("font_color", "TooltipLabel"); int max_w = 0; int sc = completion_hint.get_slice_count("\n"); int offset = 0; int spacing = 0; for (int i = 0; i < sc; i++) { String l = completion_hint.get_slice("\n", i); int len = font->get_string_size(l).x; max_w = MAX(len, max_w); if (i == 0) { offset = font->get_string_size(l.substr(0, l.find(String::chr(0xFFFF)))).x; } else { spacing += cache.line_spacing; } } Size2 size = Size2(max_w, sc * font->get_height() + spacing); Size2 minsize = size + sb->get_minimum_size(); if (completion_hint_offset == -0xFFFF) { completion_hint_offset = cursor_pos.x - offset; } Point2 hint_ofs = Vector2(completion_hint_offset, cursor_pos.y) + callhint_offset; if (callhint_below) { hint_ofs.y += get_row_height() + sb->get_offset().y; } else { hint_ofs.y -= minsize.y + sb->get_offset().y; } draw_style_box(sb, Rect2(hint_ofs, minsize)); spacing = 0; for (int i = 0; i < sc; i++) { int begin = 0; int end = 0; String l = completion_hint.get_slice("\n", i); if (l.find(String::chr(0xFFFF)) != -1) { begin = font->get_string_size(l.substr(0, l.find(String::chr(0xFFFF)))).x; end = font->get_string_size(l.substr(0, l.rfind(String::chr(0xFFFF)))).x; } draw_string(font, hint_ofs + sb->get_offset() + Vector2(0, font->get_ascent() + font->get_height() * i + spacing), l.replace(String::chr(0xFFFF), ""), font_color); if (end > 0) { Vector2 b = hint_ofs + sb->get_offset() + Vector2(begin, font->get_height() + font->get_height() * i + spacing - 1); draw_line(b, b + Vector2(end - begin, 0), font_color); } spacing += cache.line_spacing; } } if (has_focus()) { OS::get_singleton()->set_ime_position(get_global_position() + cursor_pos + Point2(0, get_row_height())); OS::get_singleton()->set_ime_intermediate_text_callback(_ime_text_callback, this); } } break; case NOTIFICATION_FOCUS_ENTER: { if (!caret_blink_enabled) { draw_caret = true; } Point2 cursor_pos = Point2(cursor_get_column(), cursor_get_line()) * get_row_height(); OS::get_singleton()->set_ime_position(get_global_position() + cursor_pos); OS::get_singleton()->set_ime_intermediate_text_callback(_ime_text_callback, this); if (OS::get_singleton()->has_virtual_keyboard()) OS::get_singleton()->show_virtual_keyboard(get_text(), get_global_rect()); if (raised_from_completion) { VisualServer::get_singleton()->canvas_item_set_z_index(get_canvas_item(), 1); } } break; case NOTIFICATION_FOCUS_EXIT: { OS::get_singleton()->set_ime_position(Point2()); OS::get_singleton()->set_ime_intermediate_text_callback(NULL, NULL); ime_text = ""; ime_selection = Point2(); if (OS::get_singleton()->has_virtual_keyboard()) OS::get_singleton()->hide_virtual_keyboard(); if (raised_from_completion) { VisualServer::get_singleton()->canvas_item_set_z_index(get_canvas_item(), 0); } } break; } } void TextEdit::_ime_text_callback(void *p_self, String p_text, Point2 p_selection) { TextEdit *self = (TextEdit *)p_self; self->ime_text = p_text; self->ime_selection = p_selection; self->update(); } void TextEdit::_consume_pair_symbol(CharType ch) { int cursor_position_to_move = cursor_get_column() + 1; CharType ch_single[2] = { ch, 0 }; CharType ch_single_pair[2] = { _get_right_pair_symbol(ch), 0 }; CharType ch_pair[3] = { ch, _get_right_pair_symbol(ch), 0 }; if (is_selection_active()) { int new_column, new_line; begin_complex_operation(); _insert_text(get_selection_from_line(), get_selection_from_column(), ch_single, &new_line, &new_column); int to_col_offset = 0; if (get_selection_from_line() == get_selection_to_line()) to_col_offset = 1; _insert_text(get_selection_to_line(), get_selection_to_column() + to_col_offset, ch_single_pair, &new_line, &new_column); end_complex_operation(); cursor_set_line(get_selection_to_line()); cursor_set_column(get_selection_to_column() + to_col_offset); deselect(); update(); return; } if ((ch == '\'' || ch == '"') && cursor_get_column() > 0 && _is_text_char(text[cursor.line][cursor_get_column() - 1])) { insert_text_at_cursor(ch_single); cursor_set_column(cursor_position_to_move); return; } if (cursor_get_column() < text[cursor.line].length()) { if (_is_text_char(text[cursor.line][cursor_get_column()])) { insert_text_at_cursor(ch_single); cursor_set_column(cursor_position_to_move); return; } if (_is_pair_right_symbol(ch) && text[cursor.line][cursor_get_column()] == ch) { cursor_set_column(cursor_position_to_move); return; } } insert_text_at_cursor(ch_pair); cursor_set_column(cursor_position_to_move); return; } void TextEdit::_consume_backspace_for_pair_symbol(int prev_line, int prev_column) { bool remove_right_symbol = false; if (cursor.column < text[cursor.line].length() && cursor.column > 0) { CharType left_char = text[cursor.line][cursor.column - 1]; CharType right_char = text[cursor.line][cursor.column]; if (right_char == _get_right_pair_symbol(left_char)) { remove_right_symbol = true; } } if (remove_right_symbol) { _remove_text(prev_line, prev_column, cursor.line, cursor.column + 1); } else { _remove_text(prev_line, prev_column, cursor.line, cursor.column); } } void TextEdit::backspace_at_cursor() { if (readonly) return; if (cursor.column == 0 && cursor.line == 0) return; int prev_line = cursor.column ? cursor.line : cursor.line - 1; int prev_column = cursor.column ? (cursor.column - 1) : (text[cursor.line - 1].length()); if (is_line_hidden(cursor.line)) set_line_as_hidden(prev_line, true); if (is_line_set_as_breakpoint(cursor.line)) set_line_as_breakpoint(prev_line, true); if (auto_brace_completion_enabled && cursor.column > 0 && _is_pair_left_symbol(text[cursor.line][cursor.column - 1])) { _consume_backspace_for_pair_symbol(prev_line, prev_column); } else { // handle space indentation if (cursor.column - indent_size >= 0 && indent_using_spaces) { // if there is enough spaces to count as a tab bool unindent = true; for (int i = 1; i <= indent_size; i++) { if (text[cursor.line][cursor.column - i] != ' ') { unindent = false; break; } } // and it is before the first character int i = 0; while (i < cursor.column && i < text[cursor.line].length()) { if (text[cursor.line][i] != ' ' && text[cursor.line][i] != '\t') { unindent = false; break; } i++; } // then we can remove it as a single character. if (unindent) { _remove_text(cursor.line, cursor.column - indent_size, cursor.line, cursor.column); prev_column = cursor.column - indent_size; } else { _remove_text(prev_line, prev_column, cursor.line, cursor.column); } } else { _remove_text(prev_line, prev_column, cursor.line, cursor.column); } } cursor_set_line(prev_line, true, true); cursor_set_column(prev_column); } void TextEdit::indent_right() { int start_line; int end_line; begin_complex_operation(); if (is_selection_active()) { start_line = get_selection_from_line(); end_line = get_selection_to_line(); } else { start_line = cursor.line; end_line = start_line; } // ignore if the cursor is not past the first column if (is_selection_active() && get_selection_to_column() == 0) { end_line--; } for (int i = start_line; i <= end_line; i++) { String line_text = get_line(i); if (indent_using_spaces) { line_text = space_indent + line_text; } else { line_text = '\t' + line_text; } set_line(i, line_text); } // fix selection and cursor being off by one on the last line if (is_selection_active()) { select(selection.from_line, selection.from_column + 1, selection.to_line, selection.to_column + 1); } cursor_set_column(cursor.column + 1, false); end_complex_operation(); update(); } void TextEdit::indent_left() { int start_line; int end_line; begin_complex_operation(); if (is_selection_active()) { start_line = get_selection_from_line(); end_line = get_selection_to_line(); } else { start_line = cursor.line; end_line = start_line; } // ignore if the cursor is not past the first column if (is_selection_active() && get_selection_to_column() == 0) { end_line--; } String last_line_text = get_line(end_line); for (int i = start_line; i <= end_line; i++) { String line_text = get_line(i); if (line_text.begins_with("\t")) { line_text = line_text.substr(1, line_text.length()); set_line(i, line_text); } else if (line_text.begins_with(space_indent)) { line_text = line_text.substr(indent_size, line_text.length()); set_line(i, line_text); } } // fix selection and cursor being off by one on the last line if (is_selection_active() && last_line_text != get_line(end_line)) { select(selection.from_line, selection.from_column - 1, selection.to_line, selection.to_column - 1); } cursor_set_column(cursor.column - 1, false); end_complex_operation(); update(); } void TextEdit::_get_mouse_pos(const Point2i &p_mouse, int &r_row, int &r_col) const { float rows = p_mouse.y; rows -= cache.style_normal->get_margin(MARGIN_TOP); rows += (CLAMP(v_scroll->get_value() - get_line_scroll_pos(true), 0, 1) * get_row_height()); rows /= get_row_height(); int first_vis_line = CLAMP(cursor.line_ofs, 0, text.size() - 1); int row = first_vis_line + Math::floor(rows); if (is_hiding_enabled()) { // row will be offset by the hidden rows int f_ofs = num_lines_from(first_vis_line, rows + 1) - 1; row = first_vis_line + f_ofs; row = CLAMP(row, 0, text.size() - num_lines_from(text.size() - 1, -1)); } if (row < 0) row = 0; //todo int col = 0; if (row >= text.size()) { row = text.size() - 1; col = text[row].size(); } else { col = p_mouse.x - (cache.style_normal->get_margin(MARGIN_LEFT) + cache.line_number_w + cache.breakpoint_gutter_width + cache.fold_gutter_width); col += cursor.x_ofs; col = get_char_pos_for(col, get_line(row)); } r_row = row; r_col = col; } void TextEdit::_gui_input(const Ref<InputEvent> &p_gui_input) { Ref<InputEventMouseButton> mb = p_gui_input; if (mb.is_valid()) { if (completion_active && completion_rect.has_point(mb->get_position())) { if (!mb->is_pressed()) return; if (mb->get_button_index() == BUTTON_WHEEL_UP) { if (completion_index > 0) { completion_index--; completion_current = completion_options[completion_index]; update(); } } if (mb->get_button_index() == BUTTON_WHEEL_DOWN) { if (completion_index < completion_options.size() - 1) { completion_index++; completion_current = completion_options[completion_index]; update(); } } if (mb->get_button_index() == BUTTON_LEFT) { completion_index = CLAMP(completion_line_ofs + (mb->get_position().y - completion_rect.position.y) / get_row_height(), 0, completion_options.size() - 1); completion_current = completion_options[completion_index]; update(); if (mb->is_doubleclick()) _confirm_completion(); } return; } else { _cancel_completion(); _cancel_code_hint(); } if (mb->is_pressed()) { if (mb->get_button_index() == BUTTON_WHEEL_UP && !mb->get_command()) { if (mb->get_shift()) { h_scroll->set_value(h_scroll->get_value() - (100 * mb->get_factor())); } else { _scroll_up(3 * mb->get_factor()); } } if (mb->get_button_index() == BUTTON_WHEEL_DOWN && !mb->get_command()) { if (mb->get_shift()) { h_scroll->set_value(h_scroll->get_value() + (100 * mb->get_factor())); } else { _scroll_down(3 * mb->get_factor()); } } if (mb->get_button_index() == BUTTON_WHEEL_LEFT) { h_scroll->set_value(h_scroll->get_value() - (100 * mb->get_factor())); } if (mb->get_button_index() == BUTTON_WHEEL_RIGHT) { h_scroll->set_value(h_scroll->get_value() + (100 * mb->get_factor())); } if (mb->get_button_index() == BUTTON_LEFT) { _reset_caret_blink_timer(); int row, col; update_line_scroll_pos(); _get_mouse_pos(Point2i(mb->get_position().x, mb->get_position().y), row, col); if (mb->get_command() && highlighted_word != String()) { emit_signal("symbol_lookup", highlighted_word, row, col); return; } // toggle breakpoint on gutter click if (draw_breakpoint_gutter) { int gutter = cache.style_normal->get_margin(MARGIN_LEFT); if (mb->get_position().x > gutter && mb->get_position().x <= gutter + cache.breakpoint_gutter_width + 3) { set_line_as_breakpoint(row, !is_line_set_as_breakpoint(row)); emit_signal("breakpoint_toggled", row); return; } } // toggle fold on gutter click if can if (draw_fold_gutter) { int left_margin = cache.style_normal->get_margin(MARGIN_LEFT); int gutter_left = left_margin + cache.breakpoint_gutter_width + cache.line_number_w; if (mb->get_position().x > gutter_left - 6 && mb->get_position().x <= gutter_left + cache.fold_gutter_width - 3) { if (is_folded(row)) { unfold_line(row); } else if (can_fold(row)) { fold_line(row); } return; } } // unfold on folded icon click if (is_folded(row)) { int line_width = text.get_line_width(row); line_width += cache.style_normal->get_margin(MARGIN_LEFT) + cache.line_number_w + cache.breakpoint_gutter_width + cache.fold_gutter_width - cursor.x_ofs; if (mb->get_position().x > line_width - 3 && mb->get_position().x <= line_width + cache.folded_eol_icon->get_width() + 3) { unfold_line(row); return; } } int prev_col = cursor.column; int prev_line = cursor.line; cursor_set_line(row, true, false); cursor_set_column(col); if (mb->get_shift() && (cursor.column != prev_col || cursor.line != prev_line)) { if (!selection.active) { selection.active = true; selection.selecting_mode = Selection::MODE_POINTER; selection.from_column = prev_col; selection.from_line = prev_line; selection.to_column = cursor.column; selection.to_line = cursor.line; if (selection.from_line > selection.to_line || (selection.from_line == selection.to_line && selection.from_column > selection.to_column)) { SWAP(selection.from_column, selection.to_column); SWAP(selection.from_line, selection.to_line); selection.shiftclick_left = false; } else { selection.shiftclick_left = true; } selection.selecting_line = prev_line; selection.selecting_column = prev_col; update(); } else { if (cursor.line < selection.selecting_line || (cursor.line == selection.selecting_line && cursor.column < selection.selecting_column)) { if (selection.shiftclick_left) { SWAP(selection.from_column, selection.to_column); SWAP(selection.from_line, selection.to_line); selection.shiftclick_left = !selection.shiftclick_left; } selection.from_column = cursor.column; selection.from_line = cursor.line; } else if (cursor.line > selection.selecting_line || (cursor.line == selection.selecting_line && cursor.column > selection.selecting_column)) { if (!selection.shiftclick_left) { SWAP(selection.from_column, selection.to_column); SWAP(selection.from_line, selection.to_line); selection.shiftclick_left = !selection.shiftclick_left; } selection.to_column = cursor.column; selection.to_line = cursor.line; } else { selection.active = false; } update(); } } else { //if sel active and dblick last time < something //else selection.active = false; selection.selecting_mode = Selection::MODE_POINTER; selection.selecting_line = row; selection.selecting_column = col; } if (!mb->is_doubleclick() && (OS::get_singleton()->get_ticks_msec() - last_dblclk) < 600 && cursor.line == prev_line) { //tripleclick select line selection.selecting_mode = Selection::MODE_LINE; _update_selection_mode_line(); last_dblclk = 0; } else if (mb->is_doubleclick() && text[cursor.line].length()) { //doubleclick select word selection.selecting_mode = Selection::MODE_WORD; _update_selection_mode_word(); last_dblclk = OS::get_singleton()->get_ticks_msec(); } update(); } if (mb->get_button_index() == BUTTON_RIGHT && context_menu_enabled) { _reset_caret_blink_timer(); int row, col; update_line_scroll_pos(); _get_mouse_pos(Point2i(mb->get_position().x, mb->get_position().y), row, col); if (is_right_click_moving_caret()) { if (is_selection_active()) { int from_line = get_selection_from_line(); int to_line = get_selection_to_line(); int from_column = get_selection_from_column(); int to_column = get_selection_to_column(); if (row < from_line || row > to_line || (row == from_line && col < from_column) || (row == to_line && col > to_column)) { // Right click is outside the seleted text deselect(); } } if (!is_selection_active()) { cursor_set_line(row, true, false); cursor_set_column(col); } } menu->set_position(get_global_transform().xform(get_local_mouse_position())); menu->set_size(Vector2(1, 1)); menu->popup(); grab_focus(); } } else { if (mb->get_button_index() == BUTTON_LEFT) click_select_held->stop(); // notify to show soft keyboard notification(NOTIFICATION_FOCUS_ENTER); } } const Ref<InputEventPanGesture> pan_gesture = p_gui_input; if (pan_gesture.is_valid()) { const real_t delta = pan_gesture->get_delta().y; if (delta < 0) { _scroll_up(-delta); } else { _scroll_down(delta); } h_scroll->set_value(h_scroll->get_value() + pan_gesture->get_delta().x * 100); return; } Ref<InputEventMouseMotion> mm = p_gui_input; if (mm.is_valid()) { if (select_identifiers_enabled) { if (mm->get_command() && mm->get_button_mask() == 0) { String new_word = get_word_at_pos(mm->get_position()); if (new_word != highlighted_word) { highlighted_word = new_word; update(); } } else { if (highlighted_word != String()) { highlighted_word = String(); update(); } } } if (mm->get_button_mask() & BUTTON_MASK_LEFT && get_viewport()->gui_get_drag_data() == Variant()) { //ignore if dragging _reset_caret_blink_timer(); switch (selection.selecting_mode) { case Selection::MODE_POINTER: { _update_selection_mode_pointer(); } break; case Selection::MODE_WORD: { _update_selection_mode_word(); } break; case Selection::MODE_LINE: { _update_selection_mode_line(); } break; default: { break; } } } } Ref<InputEventKey> k = p_gui_input; if (k.is_valid()) { k = k->duplicate(); //it will be modified later on #ifdef OSX_ENABLED if (k->get_scancode() == KEY_META) { #else if (k->get_scancode() == KEY_CONTROL) { #endif if (select_identifiers_enabled) { if (k->is_pressed()) { highlighted_word = get_word_at_pos(get_local_mouse_position()); update(); } else { highlighted_word = String(); update(); } } } if (!k->is_pressed()) return; if (completion_active) { if (readonly) return; bool valid = true; if (k->get_command() || k->get_metakey()) valid = false; if (valid) { if (!k->get_alt()) { if (k->get_scancode() == KEY_UP) { if (completion_index > 0) { completion_index--; } else { completion_index = completion_options.size() - 1; } completion_current = completion_options[completion_index]; update(); accept_event(); return; } if (k->get_scancode() == KEY_DOWN) { if (completion_index < completion_options.size() - 1) { completion_index++; } else { completion_index = 0; } completion_current = completion_options[completion_index]; update(); accept_event(); return; } if (k->get_scancode() == KEY_PAGEUP) { completion_index -= get_constant("completion_lines"); if (completion_index < 0) completion_index = 0; completion_current = completion_options[completion_index]; update(); accept_event(); return; } if (k->get_scancode() == KEY_PAGEDOWN) { completion_index += get_constant("completion_lines"); if (completion_index >= completion_options.size()) completion_index = completion_options.size() - 1; completion_current = completion_options[completion_index]; update(); accept_event(); return; } if (k->get_scancode() == KEY_HOME && completion_index > 0) { completion_index = 0; completion_current = completion_options[completion_index]; update(); accept_event(); return; } if (k->get_scancode() == KEY_END && completion_index < completion_options.size() - 1) { completion_index = completion_options.size() - 1; completion_current = completion_options[completion_index]; update(); accept_event(); return; } if (k->get_scancode() == KEY_KP_ENTER || k->get_scancode() == KEY_ENTER || k->get_scancode() == KEY_TAB) { _confirm_completion(); accept_event(); return; } if (k->get_scancode() == KEY_BACKSPACE) { _reset_caret_blink_timer(); backspace_at_cursor(); _update_completion_candidates(); accept_event(); return; } if (k->get_scancode() == KEY_SHIFT) { accept_event(); return; } } if (k->get_unicode() > 32) { _reset_caret_blink_timer(); const CharType chr[2] = { (CharType)k->get_unicode(), 0 }; if (auto_brace_completion_enabled && _is_pair_symbol(chr[0])) { _consume_pair_symbol(chr[0]); } else { // remove the old character if in insert mode if (insert_mode) { begin_complex_operation(); // make sure we don't try and remove empty space if (cursor.column < get_line(cursor.line).length()) { _remove_text(cursor.line, cursor.column, cursor.line, cursor.column + 1); } } _insert_text_at_cursor(chr); if (insert_mode) { end_complex_operation(); } } _update_completion_candidates(); accept_event(); return; } } _cancel_completion(); } /* TEST CONTROL FIRST!! */ // some remaps for duplicate functions.. if (k->get_command() && !k->get_shift() && !k->get_alt() && !k->get_metakey() && k->get_scancode() == KEY_INSERT) { k->set_scancode(KEY_C); } if (!k->get_command() && k->get_shift() && !k->get_alt() && !k->get_metakey() && k->get_scancode() == KEY_INSERT) { k->set_scancode(KEY_V); k->set_command(true); k->set_shift(false); } if (!k->get_command()) { _reset_caret_blink_timer(); } // save here for insert mode, just in case it is cleared in the following section bool had_selection = selection.active; // stuff to do when selection is active.. if (selection.active) { if (readonly) return; bool clear = false; bool unselect = false; bool dobreak = false; switch (k->get_scancode()) { case KEY_TAB: { if (k->get_shift()) { indent_left(); } else { indent_right(); } dobreak = true; accept_event(); } break; case KEY_X: case KEY_C: //special keys often used with control, wait... clear = (!k->get_command() || k->get_shift() || k->get_alt()); break; case KEY_DELETE: if (!k->get_shift()) { accept_event(); clear = true; dobreak = true; } else if (k->get_command() || k->get_alt()) { dobreak = true; } break; case KEY_BACKSPACE: accept_event(); clear = true; dobreak = true; break; case KEY_LEFT: case KEY_RIGHT: case KEY_UP: case KEY_DOWN: case KEY_PAGEUP: case KEY_PAGEDOWN: case KEY_HOME: case KEY_END: // ignore arrows if any modifiers are held (shift = selecting, others may be used for editor hotkeys) if (k->get_command() || k->get_shift() || k->get_alt()) break; unselect = true; break; default: if (k->get_unicode() >= 32 && !k->get_command() && !k->get_alt() && !k->get_metakey()) clear = true; if (auto_brace_completion_enabled && _is_pair_left_symbol(k->get_unicode())) clear = false; } if (unselect) { selection.active = false; selection.selecting_mode = Selection::MODE_NONE; update(); } if (clear) { if (!dobreak) { begin_complex_operation(); } selection.active = false; update(); _remove_text(selection.from_line, selection.from_column, selection.to_line, selection.to_column); cursor_set_line(selection.from_line, true, false); cursor_set_column(selection.from_column); update(); } if (dobreak) return; } selection.selecting_text = false; bool scancode_handled = true; // special scancode test... switch (k->get_scancode()) { case KEY_KP_ENTER: case KEY_ENTER: { if (readonly) break; String ins = "\n"; //keep indentation int space_count = 0; for (int i = 0; i < cursor.column; i++) { if (text[cursor.line][i] == '\t') { if (indent_using_spaces) { ins += space_indent; } else { ins += "\t"; } space_count = 0; } else if (text[cursor.line][i] == ' ') { space_count++; if (space_count == indent_size) { if (indent_using_spaces) { ins += space_indent; } else { ins += "\t"; } space_count = 0; } } else { break; } } if (is_folded(cursor.line)) unfold_line(cursor.line); bool brace_indent = false; // no need to indent if we are going upwards. if (auto_indent && !(k->get_command() && k->get_shift())) { // indent once again if previous line will end with ':' or '{' // (i.e. colon/brace precedes current cursor position) if (cursor.column > 0 && (text[cursor.line][cursor.column - 1] == ':' || text[cursor.line][cursor.column - 1] == '{')) { if (indent_using_spaces) { ins += space_indent; } else { ins += "\t"; } // no need to move the brace below if we are not taking the text with us. if (text[cursor.line][cursor.column] == '}' && !k->get_command()) { brace_indent = true; ins += "\n" + ins.substr(1, ins.length() - 2); } } } begin_complex_operation(); bool first_line = false; if (k->get_command()) { if (k->get_shift()) { if (cursor.line > 0) { cursor_set_line(cursor.line - 1); cursor_set_column(text[cursor.line].length()); } else { cursor_set_column(0); first_line = true; } } else { cursor_set_column(text[cursor.line].length()); } } insert_text_at_cursor(ins); if (first_line) { cursor_set_line(0); } else if (brace_indent) { cursor_set_line(cursor.line - 1); cursor_set_column(text[cursor.line].length()); } end_complex_operation(); } break; case KEY_ESCAPE: { if (completion_hint != "") { completion_hint = ""; update(); } else { scancode_handled = false; } } break; case KEY_TAB: { if (k->get_command()) break; // avoid tab when command if (readonly) break; if (is_selection_active()) { if (k->get_shift()) { indent_left(); } else { indent_right(); } } else { if (k->get_shift()) { //simple unindent int cc = cursor.column; const int len = text[cursor.line].length(); const String &line = text[cursor.line]; int left = 0; // number of whitespace chars at beginning of line while (left < len && (line[left] == '\t' || line[left] == ' ')) left++; cc = MIN(cc, left); while (cc < indent_size && cc < left && line[cc] == ' ') cc++; if (cc > 0 && cc <= text[cursor.line].length()) { if (text[cursor.line][cc - 1] == '\t') { _remove_text(cursor.line, cc - 1, cursor.line, cc); if (cursor.column >= left) cursor_set_column(MAX(0, cursor.column - 1)); update(); } else { int n = 0; for (int i = 1; i <= MIN(cc, indent_size); i++) { if (line[cc - i] != ' ') { break; } n++; } if (n > 0) { _remove_text(cursor.line, cc - n, cursor.line, cc); if (cursor.column > left - n) // inside text? cursor_set_column(MAX(0, cursor.column - n)); update(); } } } else if (cc == 0 && line.length() > 0 && line[0] == '\t') { _remove_text(cursor.line, 0, cursor.line, 1); update(); } } else { //simple indent if (indent_using_spaces) { _insert_text_at_cursor(space_indent); } else { _insert_text_at_cursor("\t"); } } } } break; case KEY_BACKSPACE: { if (readonly) break; #ifdef APPLE_STYLE_KEYS if (k->get_alt() && cursor.column > 1) { #else if (k->get_alt()) { scancode_handled = false; break; } else if (k->get_command() && cursor.column > 1) { #endif int line = cursor.line; int column = cursor.column; // check if we are removing a single whitespace, if so remove it and the next char type // else we just remove the whitespace bool only_whitespace = false; if (_is_whitespace(text[line][column - 1]) && _is_whitespace(text[line][column - 2])) { only_whitespace = true; } else if (_is_whitespace(text[line][column - 1])) { // remove the single whitespace column--; } // check if its a text char bool only_char = (_is_text_char(text[line][column - 1]) && !only_whitespace); // if its not whitespace or char then symbol. bool only_symbols = !(only_whitespace || only_char); while (column > 0) { bool is_whitespace = _is_whitespace(text[line][column - 1]); bool is_text_char = _is_text_char(text[line][column - 1]); if (only_whitespace && !is_whitespace) { break; } else if (only_char && !is_text_char) { break; } else if (only_symbols && (is_whitespace || is_text_char)) { break; } column--; } _remove_text(line, column, cursor.line, cursor.column); cursor_set_line(line); cursor_set_column(column); #ifdef APPLE_STYLE_KEYS } else if (k->get_command()) { int cursor_current_column = cursor.column; cursor.column = 0; _remove_text(cursor.line, 0, cursor.line, cursor_current_column); #endif } else { if (cursor.line > 0 && is_line_hidden(cursor.line - 1)) unfold_line(cursor.line - 1); backspace_at_cursor(); } } break; case KEY_KP_4: { if (k->get_unicode() != 0) { scancode_handled = false; break; } // numlock disabled. fallthrough to key_left } case KEY_LEFT: { if (k->get_shift()) _pre_shift_selection(); #ifdef APPLE_STYLE_KEYS else #else else if (!k->get_alt()) #endif deselect(); #ifdef APPLE_STYLE_KEYS if (k->get_command()) { cursor_set_column(0); } else if (k->get_alt()) { #else if (k->get_alt()) { scancode_handled = false; break; } else if (k->get_command()) { #endif bool prev_char = false; int cc = cursor.column; if (cc == 0 && cursor.line > 0) { cursor_set_line(cursor.line - 1); cursor_set_column(text[cursor.line].length()); } else { while (cc > 0) { bool ischar = _is_text_char(text[cursor.line][cc - 1]); if (prev_char && !ischar) break; prev_char = ischar; cc--; } cursor_set_column(cc); } } else if (cursor.column == 0) { if (cursor.line > 0) { cursor_set_line(cursor.line - num_lines_from(CLAMP(cursor.line - 1, 0, text.size() - 1), -1)); cursor_set_column(text[cursor.line].length()); } } else { cursor_set_column(cursor_get_column() - 1); } if (k->get_shift()) _post_shift_selection(); } break; case KEY_KP_6: { if (k->get_unicode() != 0) { scancode_handled = false; break; } // numlock disabled. fallthrough to key_right } case KEY_RIGHT: { if (k->get_shift()) _pre_shift_selection(); #ifdef APPLE_STYLE_KEYS else #else else if (!k->get_alt()) #endif deselect(); #ifdef APPLE_STYLE_KEYS if (k->get_command()) { cursor_set_column(text[cursor.line].length()); } else if (k->get_alt()) { #else if (k->get_alt()) { scancode_handled = false; break; } else if (k->get_command()) { #endif bool prev_char = false; int cc = cursor.column; if (cc == text[cursor.line].length() && cursor.line < text.size() - 1) { cursor_set_line(cursor.line + 1); cursor_set_column(0); } else { while (cc < text[cursor.line].length()) { bool ischar = _is_text_char(text[cursor.line][cc]); if (prev_char && !ischar) break; prev_char = ischar; cc++; } cursor_set_column(cc); } } else if (cursor.column == text[cursor.line].length()) { if (cursor.line < text.size() - 1) { cursor_set_line(cursor_get_line() + num_lines_from(CLAMP(cursor.line + 1, 0, text.size() - 1), 1), true, false); cursor_set_column(0); } } else { cursor_set_column(cursor_get_column() + 1); } if (k->get_shift()) _post_shift_selection(); } break; case KEY_KP_8: { if (k->get_unicode() != 0) { scancode_handled = false; break; } // numlock disabled. fallthrough to key_up } case KEY_UP: { if (k->get_shift()) _pre_shift_selection(); if (k->get_alt()) { scancode_handled = false; break; } #ifndef APPLE_STYLE_KEYS if (k->get_command()) { _scroll_lines_up(); break; } #else if (k->get_command() && k->get_alt()) { _scroll_lines_up(); break; } if (k->get_command()) cursor_set_line(0); else #endif cursor_set_line(cursor_get_line() - num_lines_from(CLAMP(cursor.line - 1, 0, text.size() - 1), -1)); if (k->get_shift()) _post_shift_selection(); _cancel_code_hint(); } break; case KEY_KP_2: { if (k->get_unicode() != 0) { scancode_handled = false; break; } // numlock disabled. fallthrough to key_down } case KEY_DOWN: { if (k->get_shift()) _pre_shift_selection(); if (k->get_alt()) { scancode_handled = false; break; } #ifndef APPLE_STYLE_KEYS if (k->get_command()) { _scroll_lines_down(); break; } { #else if (k->get_command() && k->get_alt()) { _scroll_lines_down(); break; } if (k->get_command()) cursor_set_line(text.size() - 1, true, false); else { #endif if (!is_last_visible_line(cursor.line)) { cursor_set_line(cursor_get_line() + num_lines_from(CLAMP(cursor.line + 1, 0, text.size() - 1), 1), true, false); } else { cursor_set_line(text.size() - 1); cursor_set_column(get_line(cursor.line).length(), true); } } if (k->get_shift()) _post_shift_selection(); _cancel_code_hint(); } break; case KEY_DELETE: { if (readonly) break; if (k->get_shift() && !k->get_command() && !k->get_alt()) { cut(); break; } int curline_len = text[cursor.line].length(); if (cursor.line == text.size() - 1 && cursor.column == curline_len) break; //nothing to do int next_line = cursor.column < curline_len ? cursor.line : cursor.line + 1; int next_column; #ifdef APPLE_STYLE_KEYS if (k->get_alt() && cursor.column < curline_len - 1) { #else if (k->get_alt()) { scancode_handled = false; break; } else if (k->get_command() && cursor.column < curline_len - 1) { #endif int line = cursor.line; int column = cursor.column; // check if we are removing a single whitespace, if so remove it and the next char type // else we just remove the whitespace bool only_whitespace = false; if (_is_whitespace(text[line][column]) && _is_whitespace(text[line][column + 1])) { only_whitespace = true; } else if (_is_whitespace(text[line][column])) { // remove the single whitespace column++; } // check if its a text char bool only_char = (_is_text_char(text[line][column]) && !only_whitespace); // if its not whitespace or char then symbol. bool only_symbols = !(only_whitespace || only_char); while (column < curline_len) { bool is_whitespace = _is_whitespace(text[line][column]); bool is_text_char = _is_text_char(text[line][column]); if (only_whitespace && !is_whitespace) { break; } else if (only_char && !is_text_char) { break; } else if (only_symbols && (is_whitespace || is_text_char)) { break; } column++; } next_line = line; next_column = column; #ifdef APPLE_STYLE_KEYS } else if (k->get_command()) { next_column = curline_len; next_line = cursor.line; #endif } else { next_column = cursor.column < curline_len ? (cursor.column + 1) : 0; } _remove_text(cursor.line, cursor.column, next_line, next_column); update(); } break; case KEY_KP_7: { if (k->get_unicode() != 0) { scancode_handled = false; break; } // numlock disabled. fallthrough to key_home } #ifdef APPLE_STYLE_KEYS case KEY_HOME: { if (k->get_shift()) _pre_shift_selection(); cursor_set_line(0); if (k->get_shift()) _post_shift_selection(); else if (k->get_command() || k->get_control()) deselect(); } break; #else case KEY_HOME: { if (k->get_shift()) _pre_shift_selection(); if (k->get_command()) { cursor_set_line(0); cursor_set_column(0); } else { // compute whitespace symbols seq length int current_line_whitespace_len = 0; while (current_line_whitespace_len < text[cursor.line].length()) { CharType c = text[cursor.line][current_line_whitespace_len]; if (c != '\t' && c != ' ') break; current_line_whitespace_len++; } if (cursor_get_column() == current_line_whitespace_len) cursor_set_column(0); else cursor_set_column(current_line_whitespace_len); } if (k->get_shift()) _post_shift_selection(); else if (k->get_command() || k->get_control()) deselect(); _cancel_completion(); completion_hint = ""; } break; #endif case KEY_KP_1: { if (k->get_unicode() != 0) { scancode_handled = false; break; } // numlock disabled. fallthrough to key_end } #ifdef APPLE_STYLE_KEYS case KEY_END: { if (k->get_shift()) _pre_shift_selection(); cursor_set_line(text.size() - 1, true, false); if (k->get_shift()) _post_shift_selection(); else if (k->get_command() || k->get_control()) deselect(); } break; #else case KEY_END: { if (k->get_shift()) _pre_shift_selection(); if (k->get_command()) cursor_set_line(text.size() - 1, true, false); cursor_set_column(text[cursor.line].length()); if (k->get_shift()) _post_shift_selection(); else if (k->get_command() || k->get_control()) deselect(); _cancel_completion(); completion_hint = ""; } break; #endif case KEY_KP_9: { if (k->get_unicode() != 0) { scancode_handled = false; break; } // numlock disabled. fallthrough to key_pageup } case KEY_PAGEUP: { if (k->get_shift()) _pre_shift_selection(); cursor_set_line(cursor_get_line() - num_lines_from(cursor.line, -get_visible_rows()), true, false); if (k->get_shift()) _post_shift_selection(); _cancel_completion(); completion_hint = ""; } break; case KEY_KP_3: { if (k->get_unicode() != 0) { scancode_handled = false; break; } // numlock disabled. fallthrough to key_pageup } case KEY_PAGEDOWN: { if (k->get_shift()) _pre_shift_selection(); cursor_set_line(cursor_get_line() + num_lines_from(cursor.line, get_visible_rows()), true, false); if (k->get_shift()) _post_shift_selection(); _cancel_completion(); completion_hint = ""; } break; case KEY_A: { #ifndef APPLE_STYLE_KEYS if (!k->get_command() || k->get_shift() || k->get_alt()) { scancode_handled = false; break; } select_all(); #else if (k->get_alt()) { scancode_handled = false; break; } if (!k->get_shift() && k->get_command()) select_all(); else if (k->get_control()) { if (k->get_shift()) _pre_shift_selection(); int current_line_whitespace_len = 0; while (current_line_whitespace_len < text[cursor.line].length()) { CharType c = text[cursor.line][current_line_whitespace_len]; if (c != '\t' && c != ' ') break; current_line_whitespace_len++; } if (cursor_get_column() == current_line_whitespace_len) cursor_set_column(0); else cursor_set_column(current_line_whitespace_len); if (k->get_shift()) _post_shift_selection(); else if (k->get_command() || k->get_control()) deselect(); } } break; case KEY_E: { if (!k->get_control() || k->get_command() || k->get_alt()) { scancode_handled = false; break; } if (k->get_shift()) _pre_shift_selection(); if (k->get_command()) cursor_set_line(text.size() - 1, true, false); cursor_set_column(text[cursor.line].length()); if (k->get_shift()) _post_shift_selection(); else if (k->get_command() || k->get_control()) deselect(); _cancel_completion(); completion_hint = ""; #endif } break; case KEY_X: { if (readonly) { break; } if (!k->get_command() || k->get_shift() || k->get_alt()) { scancode_handled = false; break; } cut(); } break; case KEY_C: { if (!k->get_command() || k->get_shift() || k->get_alt()) { scancode_handled = false; break; } copy(); } break; case KEY_Z: { if (!k->get_command()) { scancode_handled = false; break; } if (k->get_shift()) redo(); else undo(); } break; case KEY_Y: { if (!k->get_command()) { scancode_handled = false; break; } redo(); } break; case KEY_V: { if (readonly) { break; } if (!k->get_command() || k->get_shift() || k->get_alt()) { scancode_handled = false; break; } paste(); } break; case KEY_SPACE: { #ifdef OSX_ENABLED if (completion_enabled && k->get_metakey()) { //cmd-space is spotlight shortcut in OSX #else if (completion_enabled && k->get_command()) { #endif query_code_comple(); scancode_handled = true; } else { scancode_handled = false; } } break; case KEY_U: { if (!k->get_command() || k->get_shift()) { scancode_handled = false; break; } else { if (selection.active) { int ini = selection.from_line; int end = selection.to_line; for (int i = ini; i <= end; i++) { if (get_line(i).begins_with("#")) _remove_text(i, 0, i, 1); } } else { if (get_line(cursor.line).begins_with("#")) { _remove_text(cursor.line, 0, cursor.line, 1); if (cursor.column >= get_line(cursor.line).length()) { cursor.column = MAX(0, get_line(cursor.line).length() - 1); } } } update(); } } break; default: { scancode_handled = false; } break; } if (scancode_handled) accept_event(); /* if (!scancode_handled && !k->get_command() && !k->get_alt()) { if (k->get_unicode()>=32) { if (readonly) break; accept_event(); } else { break; } } */ if (k->get_scancode() == KEY_INSERT) { set_insert_mode(!insert_mode); accept_event(); return; } if (!scancode_handled && !k->get_command()) { //for German kbds if (k->get_unicode() >= 32) { if (readonly) return; // remove the old character if in insert mode and no selection if (insert_mode && !had_selection) { begin_complex_operation(); // make sure we don't try and remove empty space if (cursor.column < get_line(cursor.line).length()) { _remove_text(cursor.line, cursor.column, cursor.line, cursor.column + 1); } } const CharType chr[2] = { (CharType)k->get_unicode(), 0 }; if (completion_hint != "" && k->get_unicode() == ')') { completion_hint = ""; } if (auto_brace_completion_enabled && _is_pair_symbol(chr[0])) { _consume_pair_symbol(chr[0]); } else { _insert_text_at_cursor(chr); } if (insert_mode && !had_selection) { end_complex_operation(); } if (selection.active != had_selection) { end_complex_operation(); } accept_event(); } else { } } return; } } void TextEdit::_scroll_up(real_t p_delta) { if (scrolling && smooth_scroll_enabled && SGN(target_v_scroll - v_scroll->get_value()) != SGN(-p_delta)) scrolling = false; if (scrolling) { target_v_scroll = (target_v_scroll - p_delta); } else { target_v_scroll = (v_scroll->get_value() - p_delta); } if (smooth_scroll_enabled) { if (target_v_scroll <= 0) { target_v_scroll = 0; } if (Math::abs(target_v_scroll - v_scroll->get_value()) < 1.0) { v_scroll->set_value(target_v_scroll); } else { scrolling = true; set_physics_process_internal(true); } } else { v_scroll->set_value(target_v_scroll); } } void TextEdit::_scroll_down(real_t p_delta) { if (scrolling && smooth_scroll_enabled && SGN(target_v_scroll - v_scroll->get_value()) != SGN(p_delta)) scrolling = false; if (scrolling) { target_v_scroll = (target_v_scroll + p_delta); } else { target_v_scroll = (v_scroll->get_value() + p_delta); } if (smooth_scroll_enabled) { int max_v_scroll = get_total_unhidden_rows(); if (!scroll_past_end_of_file_enabled) { max_v_scroll -= get_visible_rows(); max_v_scroll = CLAMP(max_v_scroll, 0, get_total_unhidden_rows()); } if (target_v_scroll > max_v_scroll) { target_v_scroll = max_v_scroll; } if (Math::abs(target_v_scroll - v_scroll->get_value()) < 1.0) { v_scroll->set_value(target_v_scroll); } else { scrolling = true; set_physics_process_internal(true); } } else { v_scroll->set_value(target_v_scroll); } } void TextEdit::_pre_shift_selection() { if (!selection.active || selection.selecting_mode == Selection::MODE_NONE) { selection.selecting_line = cursor.line; selection.selecting_column = cursor.column; selection.active = true; } selection.selecting_mode = Selection::MODE_SHIFT; } void TextEdit::_post_shift_selection() { if (selection.active && selection.selecting_mode == Selection::MODE_SHIFT) { select(selection.selecting_line, selection.selecting_column, cursor.line, cursor.column); update(); } selection.selecting_text = true; } void TextEdit::_scroll_lines_up() { scrolling = false; // adjust the vertical scroll if (get_v_scroll() >= 0) { set_v_scroll(get_v_scroll() - 1); } // adjust the cursor int num_lines = num_lines_from(CLAMP(cursor.line_ofs, 0, text.size() - 1), get_visible_rows()); if (cursor.line >= cursor.line_ofs + num_lines && !selection.active) { cursor_set_line(cursor.line_ofs + num_lines, false, false); } } void TextEdit::_scroll_lines_down() { scrolling = false; // calculate the maximum vertical scroll position int max_v_scroll = get_total_unhidden_rows(); if (!scroll_past_end_of_file_enabled) { max_v_scroll -= get_visible_rows(); max_v_scroll = CLAMP(max_v_scroll, 0, get_total_unhidden_rows()); } // adjust the vertical scroll if (get_v_scroll() < max_v_scroll) { set_v_scroll(get_v_scroll() + 1); } // adjust the cursor if (cursor.line <= cursor.line_ofs - 1 && !selection.active) { cursor_set_line(cursor.line_ofs, false, false); } } /**** TEXT EDIT CORE API ****/ void TextEdit::_base_insert_text(int p_line, int p_char, const String &p_text, int &r_end_line, int &r_end_column) { //save for undo... ERR_FAIL_INDEX(p_line, text.size()); ERR_FAIL_COND(p_char < 0); /* STEP 1 add spaces if the char is greater than the end of the line */ while (p_char > text[p_line].length()) { text.set(p_line, text[p_line] + String::chr(' ')); } /* STEP 2 separate dest string in pre and post text */ String preinsert_text = text[p_line].substr(0, p_char); String postinsert_text = text[p_line].substr(p_char, text[p_line].size()); /* STEP 3 remove \r from source text and separate in substrings */ //buh bye \r and split Vector<String> substrings = p_text.replace("\r", "").split("\n"); for (int i = 0; i < substrings.size(); i++) { //insert the substrings if (i == 0) { text.set(p_line, preinsert_text + substrings[i]); } else { text.insert(p_line + i, substrings[i]); } if (i == substrings.size() - 1) { text.set(p_line + i, text[p_line + i] + postinsert_text); } } // if we are just making a new empty line, reset breakpoints and hidden status if (p_char == 0 && p_text.replace("\r", "") == "\n") { text.set_breakpoint(p_line + 1, text.is_breakpoint(p_line)); text.set_hidden(p_line + 1, text.is_hidden(p_line)); text.set_breakpoint(p_line, false); text.set_hidden(p_line, false); } r_end_line = p_line + substrings.size() - 1; r_end_column = text[r_end_line].length() - postinsert_text.length(); if (!text_changed_dirty && !setting_text) { if (is_inside_tree()) MessageQueue::get_singleton()->push_call(this, "_text_changed_emit"); text_changed_dirty = true; } _line_edited_from(p_line); } String TextEdit::_base_get_text(int p_from_line, int p_from_column, int p_to_line, int p_to_column) const { ERR_FAIL_INDEX_V(p_from_line, text.size(), String()); ERR_FAIL_INDEX_V(p_from_column, text[p_from_line].length() + 1, String()); ERR_FAIL_INDEX_V(p_to_line, text.size(), String()); ERR_FAIL_INDEX_V(p_to_column, text[p_to_line].length() + 1, String()); ERR_FAIL_COND_V(p_to_line < p_from_line, String()); // from > to ERR_FAIL_COND_V(p_to_line == p_from_line && p_to_column < p_from_column, String()); // from > to String ret; for (int i = p_from_line; i <= p_to_line; i++) { int begin = (i == p_from_line) ? p_from_column : 0; int end = (i == p_to_line) ? p_to_column : text[i].length(); if (i > p_from_line) ret += "\n"; ret += text[i].substr(begin, end - begin); } return ret; } void TextEdit::_base_remove_text(int p_from_line, int p_from_column, int p_to_line, int p_to_column) { ERR_FAIL_INDEX(p_from_line, text.size()); ERR_FAIL_INDEX(p_from_column, text[p_from_line].length() + 1); ERR_FAIL_INDEX(p_to_line, text.size()); ERR_FAIL_INDEX(p_to_column, text[p_to_line].length() + 1); ERR_FAIL_COND(p_to_line < p_from_line); // from > to ERR_FAIL_COND(p_to_line == p_from_line && p_to_column < p_from_column); // from > to String pre_text = text[p_from_line].substr(0, p_from_column); String post_text = text[p_to_line].substr(p_to_column, text[p_to_line].length()); for (int i = p_from_line; i < p_to_line; i++) { text.remove(p_from_line + 1); } text.set(p_from_line, pre_text + post_text); if (!text_changed_dirty && !setting_text) { if (is_inside_tree()) MessageQueue::get_singleton()->push_call(this, "_text_changed_emit"); text_changed_dirty = true; } _line_edited_from(p_from_line); } void TextEdit::_insert_text(int p_line, int p_char, const String &p_text, int *r_end_line, int *r_end_char) { if (!setting_text) idle_detect->start(); if (undo_enabled) { _clear_redo(); } int retline, retchar; _base_insert_text(p_line, p_char, p_text, retline, retchar); if (r_end_line) *r_end_line = retline; if (r_end_char) *r_end_char = retchar; if (!undo_enabled) return; /* UNDO!! */ TextOperation op; op.type = TextOperation::TYPE_INSERT; op.from_line = p_line; op.from_column = p_char; op.to_line = retline; op.to_column = retchar; op.text = p_text; op.version = ++version; op.chain_forward = false; op.chain_backward = false; //see if it shold just be set as current op if (current_op.type != op.type) { op.prev_version = get_version(); _push_current_op(); current_op = op; return; //set as current op, return } //see if it can be merged if (current_op.to_line != p_line || current_op.to_column != p_char) { op.prev_version = get_version(); _push_current_op(); current_op = op; return; //set as current op, return } //merge current op current_op.text += p_text; current_op.to_column = retchar; current_op.to_line = retline; current_op.version = op.version; } void TextEdit::_remove_text(int p_from_line, int p_from_column, int p_to_line, int p_to_column) { if (!setting_text) idle_detect->start(); String text; if (undo_enabled) { _clear_redo(); text = _base_get_text(p_from_line, p_from_column, p_to_line, p_to_column); } _base_remove_text(p_from_line, p_from_column, p_to_line, p_to_column); if (!undo_enabled) return; /* UNDO!! */ TextOperation op; op.type = TextOperation::TYPE_REMOVE; op.from_line = p_from_line; op.from_column = p_from_column; op.to_line = p_to_line; op.to_column = p_to_column; op.text = text; op.version = ++version; op.chain_forward = false; op.chain_backward = false; //see if it shold just be set as current op if (current_op.type != op.type) { op.prev_version = get_version(); _push_current_op(); current_op = op; return; //set as current op, return } //see if it can be merged if (current_op.from_line == p_to_line && current_op.from_column == p_to_column) { //basckace or similar current_op.text = text + current_op.text; current_op.from_line = p_from_line; current_op.from_column = p_from_column; return; //update current op } if (current_op.from_line == p_from_line && current_op.from_column == p_from_column) { //current_op.text=text+current_op.text; //current_op.from_line=p_from_line; //current_op.from_column=p_from_column; //return; //update current op } op.prev_version = get_version(); _push_current_op(); current_op = op; } void TextEdit::_insert_text_at_cursor(const String &p_text) { int new_column, new_line; _insert_text(cursor.line, cursor.column, p_text, &new_line, &new_column); cursor_set_line(new_line); cursor_set_column(new_column); update(); } void TextEdit::_line_edited_from(int p_line) { int cache_size = color_region_cache.size(); for (int i = p_line; i < cache_size; i++) { color_region_cache.erase(i); } } int TextEdit::get_char_count() { int totalsize = 0; for (int i = 0; i < text.size(); i++) { if (i > 0) totalsize++; // incliude \n totalsize += text[i].length(); } return totalsize; // omit last \n } Size2 TextEdit::get_minimum_size() const { return cache.style_normal->get_minimum_size(); } int TextEdit::get_visible_rows() const { int total = cache.size.height; total -= cache.style_normal->get_minimum_size().height; total /= get_row_height(); return total; } int TextEdit::get_total_unhidden_rows() const { if (!is_hiding_enabled()) return text.size(); int total_unhidden = 0; for (int i = 0; i < text.size(); i++) { if (!text.is_hidden(i)) total_unhidden++; } return total_unhidden; } double TextEdit::get_line_scroll_pos(bool p_recalculate) const { if (!is_hiding_enabled()) return cursor.line_ofs; if (!p_recalculate) return line_scroll_pos; // count num unhidden lines to the cursor line ofs double new_line_scroll_pos = 0; int to = CLAMP(cursor.line_ofs, 0, text.size() - 1); for (int i = 0; i < to; i++) { if (!text.is_hidden(i)) new_line_scroll_pos++; } return new_line_scroll_pos; } void TextEdit::update_line_scroll_pos() { if (!is_hiding_enabled()) { line_scroll_pos = cursor.line_ofs; return; } // count num unhidden lines to the cursor line ofs double new_line_scroll_pos = 0; int to = CLAMP(cursor.line_ofs, 0, text.size() - 1); for (int i = 0; i < to; i++) { if (!text.is_hidden(i)) new_line_scroll_pos++; } line_scroll_pos = new_line_scroll_pos; } void TextEdit::adjust_viewport_to_cursor() { scrolling = false; if (cursor.line_ofs > cursor.line) { cursor.line_ofs = cursor.line; } int visible_width = cache.size.width - cache.style_normal->get_minimum_size().width - cache.line_number_w - cache.breakpoint_gutter_width - cache.fold_gutter_width; if (v_scroll->is_visible_in_tree()) visible_width -= v_scroll->get_combined_minimum_size().width; visible_width -= 20; // give it a little more space int visible_rows = get_visible_rows(); if (h_scroll->is_visible_in_tree() && !scroll_past_end_of_file_enabled) visible_rows -= ((h_scroll->get_combined_minimum_size().height - 1) / get_row_height()); int num_rows = num_lines_from(CLAMP(cursor.line_ofs, 0, text.size() - 1), MIN(visible_rows, text.size() - 1 - cursor.line_ofs)); // make sure the cursor is on the screen // above the caret if (cursor.line > (cursor.line_ofs + MAX(num_rows, visible_rows))) { cursor.line_ofs = cursor.line - num_lines_from(cursor.line, -visible_rows) + 1; } // below the caret if (cursor.line_ofs == cursor.line) { cursor.line_ofs = cursor.line - 2; } int line_ofs_max = text.size() - 1; if (!scroll_past_end_of_file_enabled) { line_ofs_max -= num_lines_from(text.size() - 1, -visible_rows) - 1; line_ofs_max += (h_scroll->is_visible_in_tree() ? 1 : 0); line_ofs_max += (cursor.line == text.size() - 1 ? 1 : 0); } line_ofs_max = MAX(line_ofs_max, 0); cursor.line_ofs = CLAMP(cursor.line_ofs, 0, line_ofs_max); // adjust x offset int cursor_x = get_column_x_offset(cursor.column, text[cursor.line]); if (cursor_x > (cursor.x_ofs + visible_width)) cursor.x_ofs = cursor_x - visible_width + 1; if (cursor_x < cursor.x_ofs) cursor.x_ofs = cursor_x; updating_scrolls = true; h_scroll->set_value(cursor.x_ofs); update_line_scroll_pos(); double new_v_scroll = get_line_scroll_pos(); // keep offset if smooth scroll is enabled if (smooth_scroll_enabled) { new_v_scroll += fmod(v_scroll->get_value(), 1.0); } v_scroll->set_value(new_v_scroll); updating_scrolls = false; update(); } void TextEdit::center_viewport_to_cursor() { scrolling = false; if (cursor.line_ofs > cursor.line) cursor.line_ofs = cursor.line; if (is_line_hidden(cursor.line)) unfold_line(cursor.line); int visible_width = cache.size.width - cache.style_normal->get_minimum_size().width - cache.line_number_w - cache.breakpoint_gutter_width - cache.fold_gutter_width; if (v_scroll->is_visible_in_tree()) visible_width -= v_scroll->get_combined_minimum_size().width; visible_width -= 20; // give it a little more space int visible_rows = get_visible_rows(); if (h_scroll->is_visible_in_tree()) visible_rows -= ((h_scroll->get_combined_minimum_size().height - 1) / get_row_height()); if (text.size() >= visible_rows) { int max_ofs = text.size() - (scroll_past_end_of_file_enabled ? 1 : MAX(num_lines_from(text.size() - 1, -visible_rows), 0)); cursor.line_ofs = CLAMP(cursor.line - num_lines_from(MAX(cursor.line - visible_rows / 2, 0), -visible_rows / 2), 0, max_ofs); } int cursor_x = get_column_x_offset(cursor.column, text[cursor.line]); if (cursor_x > (cursor.x_ofs + visible_width)) cursor.x_ofs = cursor_x - visible_width + 1; if (cursor_x < cursor.x_ofs) cursor.x_ofs = cursor_x; updating_scrolls = true; h_scroll->set_value(cursor.x_ofs); update_line_scroll_pos(); double new_v_scroll = get_line_scroll_pos(); // keep offset if smooth scroll is enabled if (smooth_scroll_enabled) { new_v_scroll += fmod(v_scroll->get_value(), 1.0); } v_scroll->set_value(new_v_scroll); updating_scrolls = false; update(); } void TextEdit::cursor_set_column(int p_col, bool p_adjust_viewport) { if (p_col < 0) p_col = 0; cursor.column = p_col; if (cursor.column > get_line(cursor.line).length()) cursor.column = get_line(cursor.line).length(); cursor.last_fit_x = get_column_x_offset(cursor.column, get_line(cursor.line)); if (p_adjust_viewport) adjust_viewport_to_cursor(); if (!cursor_changed_dirty) { if (is_inside_tree()) MessageQueue::get_singleton()->push_call(this, "_cursor_changed_emit"); cursor_changed_dirty = true; } } void TextEdit::cursor_set_line(int p_row, bool p_adjust_viewport, bool p_can_be_hidden) { if (setting_row) return; setting_row = true; if (p_row < 0) p_row = 0; if (p_row >= (int)text.size()) p_row = (int)text.size() - 1; if (!p_can_be_hidden) { if (is_line_hidden(CLAMP(p_row, 0, text.size() - 1))) { int move_down = num_lines_from(p_row, 1) - 1; if (p_row + move_down <= text.size() - 1 && !is_line_hidden(p_row + move_down)) { p_row += move_down; } else { int move_up = num_lines_from(p_row, -1) - 1; if (p_row - move_up > 0 && !is_line_hidden(p_row - move_up)) { p_row -= move_up; } else { WARN_PRINTS(("Cursor set to hidden line " + itos(p_row) + " and there are no nonhidden lines.")); } } } } cursor.line = p_row; cursor.column = get_char_pos_for(cursor.last_fit_x, get_line(cursor.line)); if (p_adjust_viewport) adjust_viewport_to_cursor(); setting_row = false; if (!cursor_changed_dirty) { if (is_inside_tree()) MessageQueue::get_singleton()->push_call(this, "_cursor_changed_emit"); cursor_changed_dirty = true; } } int TextEdit::cursor_get_column() const { return cursor.column; } int TextEdit::cursor_get_line() const { return cursor.line; } bool TextEdit::cursor_get_blink_enabled() const { return caret_blink_enabled; } void TextEdit::cursor_set_blink_enabled(const bool p_enabled) { caret_blink_enabled = p_enabled; if (p_enabled) { caret_blink_timer->start(); } else { caret_blink_timer->stop(); } draw_caret = true; } float TextEdit::cursor_get_blink_speed() const { return caret_blink_timer->get_wait_time(); } void TextEdit::cursor_set_blink_speed(const float p_speed) { ERR_FAIL_COND(p_speed <= 0); caret_blink_timer->set_wait_time(p_speed); } void TextEdit::cursor_set_block_mode(const bool p_enable) { block_caret = p_enable; update(); } bool TextEdit::cursor_is_block_mode() const { return block_caret; } void TextEdit::set_right_click_moves_caret(bool p_enable) { right_click_moves_caret = p_enable; } bool TextEdit::is_right_click_moving_caret() const { return right_click_moves_caret; } void TextEdit::_v_scroll_input() { scrolling = false; } void TextEdit::_scroll_moved(double p_to_val) { if (updating_scrolls) return; if (h_scroll->is_visible_in_tree()) cursor.x_ofs = h_scroll->get_value(); if (v_scroll->is_visible_in_tree()) { double val = v_scroll->get_value(); cursor.line_ofs = num_lines_from(0, (int)floor(val)); line_scroll_pos = (int)floor(val); } update(); } int TextEdit::get_row_height() const { return cache.font->get_height() + cache.line_spacing; } int TextEdit::get_char_pos_for(int p_px, String p_str) const { int px = 0; int c = 0; int tab_w = cache.font->get_char_size(' ').width * indent_size; while (c < p_str.length()) { int w = 0; if (p_str[c] == '\t') { int left = px % tab_w; if (left == 0) w = tab_w; else w = tab_w - px % tab_w; // is right... } else { w = cache.font->get_char_size(p_str[c], p_str[c + 1]).width; } if (p_px < (px + w / 2)) break; px += w; c++; } return c; } int TextEdit::get_column_x_offset(int p_char, String p_str) { int px = 0; int tab_w = cache.font->get_char_size(' ').width * indent_size; for (int i = 0; i < p_char; i++) { if (i >= p_str.length()) break; if (p_str[i] == '\t') { int left = px % tab_w; if (left == 0) px += tab_w; else px += tab_w - px % tab_w; // is right... } else { px += cache.font->get_char_size(p_str[i], p_str[i + 1]).width; } } return px; } void TextEdit::insert_text_at_cursor(const String &p_text) { if (selection.active) { cursor_set_line(selection.from_line); cursor_set_column(selection.from_column); _remove_text(selection.from_line, selection.from_column, selection.to_line, selection.to_column); selection.active = false; selection.selecting_mode = Selection::MODE_NONE; } _insert_text_at_cursor(p_text); update(); } Control::CursorShape TextEdit::get_cursor_shape(const Point2 &p_pos) const { if (highlighted_word != String()) return CURSOR_POINTING_HAND; int gutter = cache.style_normal->get_margin(MARGIN_LEFT) + cache.line_number_w + cache.breakpoint_gutter_width + cache.fold_gutter_width; if ((completion_active && completion_rect.has_point(p_pos))) { return CURSOR_ARROW; } if (p_pos.x < gutter) { int row, col; _get_mouse_pos(p_pos, row, col); int left_margin = cache.style_normal->get_margin(MARGIN_LEFT); // breakpoint icon if (draw_breakpoint_gutter && p_pos.x > left_margin && p_pos.x <= left_margin + cache.breakpoint_gutter_width + 3) { return CURSOR_POINTING_HAND; } // fold icon int gutter_left = left_margin + cache.breakpoint_gutter_width + cache.line_number_w; if (draw_fold_gutter && p_pos.x > gutter_left - 6 && p_pos.x <= gutter_left + cache.fold_gutter_width - 3) { if (is_folded(row) || can_fold(row)) return CURSOR_POINTING_HAND; else return CURSOR_ARROW; } return CURSOR_ARROW; } else { int row, col; _get_mouse_pos(p_pos, row, col); // eol fold icon if (is_folded(row)) { int line_width = text.get_line_width(row); line_width += cache.style_normal->get_margin(MARGIN_LEFT) + cache.line_number_w + cache.breakpoint_gutter_width + cache.fold_gutter_width - cursor.x_ofs; if (p_pos.x > line_width - 3 && p_pos.x <= line_width + cache.folded_eol_icon->get_width() + 3) { return CURSOR_POINTING_HAND; } } } return CURSOR_IBEAM; } void TextEdit::set_text(String p_text) { setting_text = true; clear(); _insert_text_at_cursor(p_text); clear_undo_history(); cursor.column = 0; cursor.line = 0; cursor.x_ofs = 0; cursor.line_ofs = 0; line_scroll_pos = 0; cursor.last_fit_x = 0; cursor_set_line(0); cursor_set_column(0); update(); setting_text = false; _text_changed_emit(); //get_range()->set(0); }; String TextEdit::get_text() { String longthing; int len = text.size(); for (int i = 0; i < len; i++) { longthing += text[i]; if (i != len - 1) longthing += "\n"; } return longthing; }; String TextEdit::get_text_for_lookup_completion() { int row, col; _get_mouse_pos(get_local_mouse_position(), row, col); String longthing; int len = text.size(); for (int i = 0; i < len; i++) { if (i == row) { longthing += text[i].substr(0, col); longthing += String::chr(0xFFFF); //not unicode, represents the cursor longthing += text[i].substr(col, text[i].size()); } else { longthing += text[i]; } if (i != len - 1) longthing += "\n"; } return longthing; } String TextEdit::get_text_for_completion() { String longthing; int len = text.size(); for (int i = 0; i < len; i++) { if (i == cursor.line) { longthing += text[i].substr(0, cursor.column); longthing += String::chr(0xFFFF); //not unicode, represents the cursor longthing += text[i].substr(cursor.column, text[i].size()); } else { longthing += text[i]; } if (i != len - 1) longthing += "\n"; } return longthing; }; String TextEdit::get_line(int line) const { if (line < 0 || line >= text.size()) return ""; return text[line]; }; void TextEdit::_clear() { clear_undo_history(); text.clear(); cursor.column = 0; cursor.line = 0; cursor.x_ofs = 0; cursor.line_ofs = 0; line_scroll_pos = 0; cursor.last_fit_x = 0; } void TextEdit::clear() { setting_text = true; _clear(); setting_text = false; }; void TextEdit::set_readonly(bool p_readonly) { readonly = p_readonly; update(); } bool TextEdit::is_readonly() const { return readonly; } void TextEdit::set_wrap(bool p_wrap) { wrap = p_wrap; } bool TextEdit::is_wrapping() const { return wrap; } void TextEdit::set_max_chars(int p_max_chars) { max_chars = p_max_chars; } int TextEdit::get_max_chars() const { return max_chars; } void TextEdit::_reset_caret_blink_timer() { if (caret_blink_enabled) { caret_blink_timer->stop(); caret_blink_timer->start(); draw_caret = true; update(); } } void TextEdit::_toggle_draw_caret() { draw_caret = !draw_caret; if (is_visible_in_tree() && has_focus() && window_has_focus) { update(); } } void TextEdit::_update_caches() { cache.style_normal = get_stylebox("normal"); cache.style_focus = get_stylebox("focus"); cache.style_readonly = get_stylebox("read_only"); cache.completion_background_color = get_color("completion_background_color"); cache.completion_selected_color = get_color("completion_selected_color"); cache.completion_existing_color = get_color("completion_existing_color"); cache.completion_font_color = get_color("completion_font_color"); cache.font = get_font("font"); cache.caret_color = get_color("caret_color"); cache.caret_background_color = get_color("caret_background_color"); cache.line_number_color = get_color("line_number_color"); cache.font_color = get_color("font_color"); cache.font_selected_color = get_color("font_selected_color"); cache.keyword_color = get_color("keyword_color"); cache.function_color = get_color("function_color"); cache.member_variable_color = get_color("member_variable_color"); cache.number_color = get_color("number_color"); cache.selection_color = get_color("selection_color"); cache.mark_color = get_color("mark_color"); cache.current_line_color = get_color("current_line_color"); cache.line_length_guideline_color = get_color("line_length_guideline_color"); cache.breakpoint_color = get_color("breakpoint_color"); cache.code_folding_color = get_color("code_folding_color"); cache.brace_mismatch_color = get_color("brace_mismatch_color"); cache.word_highlighted_color = get_color("word_highlighted_color"); cache.search_result_color = get_color("search_result_color"); cache.search_result_border_color = get_color("search_result_border_color"); cache.symbol_color = get_color("symbol_color"); cache.background_color = get_color("background_color"); cache.line_spacing = get_constant("line_spacing"); cache.row_height = cache.font->get_height() + cache.line_spacing; cache.tab_icon = get_icon("tab"); cache.folded_icon = get_icon("GuiTreeArrowRight", "EditorIcons"); cache.can_fold_icon = get_icon("GuiTreeArrowDown", "EditorIcons"); cache.folded_eol_icon = get_icon("GuiEllipsis", "EditorIcons"); text.set_font(cache.font); if (syntax_highlighter) { syntax_highlighter->_update_cache(); } } SyntaxHighlighter *TextEdit::_get_syntax_highlighting() { return syntax_highlighter; } void TextEdit::_set_syntax_highlighting(SyntaxHighlighter *p_syntax_highlighter) { syntax_highlighter = p_syntax_highlighter; if (syntax_highlighter) { syntax_highlighter->set_text_editor(this); syntax_highlighter->_update_cache(); } update(); } int TextEdit::_is_line_in_region(int p_line) { // do we have in cache? if (color_region_cache.has(p_line)) { return color_region_cache[p_line]; } // if not find the closest line we have int previous_line = p_line - 1; for (previous_line; previous_line > -1; previous_line--) { if (color_region_cache.has(p_line)) { break; } } // calculate up to line we need and update the cache along the way. int in_region = color_region_cache[previous_line]; if (previous_line == -1) { in_region = -1; } for (int i = previous_line; i < p_line; i++) { const Map<int, Text::ColorRegionInfo> &cri_map = _get_line_color_region_info(i); for (const Map<int, Text::ColorRegionInfo>::Element *E = cri_map.front(); E; E = E->next()) { const Text::ColorRegionInfo &cri = E->get(); if (in_region == -1) { if (!cri.end) { in_region = cri.region; } } else if (in_region == cri.region && !_get_color_region(cri.region).line_only) { if (cri.end || _get_color_region(cri.region).eq) { in_region = -1; } } } if (in_region >= 0 && _get_color_region(in_region).line_only) { in_region = -1; } color_region_cache[i + 1] = in_region; } return in_region; } TextEdit::ColorRegion TextEdit::_get_color_region(int p_region) const { if (p_region < 0 || p_region >= color_regions.size()) { return ColorRegion(); } return color_regions[p_region]; } Map<int, TextEdit::Text::ColorRegionInfo> TextEdit::_get_line_color_region_info(int p_line) const { if (p_line < 0 || p_line > text.size() - 1) { return Map<int, Text::ColorRegionInfo>(); } return text.get_color_region_info(p_line); } void TextEdit::clear_colors() { keywords.clear(); color_regions.clear(); color_region_cache.clear(); text.clear_caches(); } void TextEdit::add_keyword_color(const String &p_keyword, const Color &p_color) { keywords[p_keyword] = p_color; update(); } bool TextEdit::has_keyword_color(String p_keyword) const { return keywords.has(p_keyword); } Color TextEdit::get_keyword_color(String p_keyword) const { return keywords[p_keyword]; } void TextEdit::add_color_region(const String &p_begin_key, const String &p_end_key, const Color &p_color, bool p_line_only) { color_regions.push_back(ColorRegion(p_begin_key, p_end_key, p_color, p_line_only)); text.clear_caches(); update(); } void TextEdit::add_member_keyword(const String &p_keyword, const Color &p_color) { member_keywords[p_keyword] = p_color; update(); } bool TextEdit::has_member_color(String p_member) const { return member_keywords.has(p_member); } Color TextEdit::get_member_color(String p_member) const { return member_keywords[p_member]; } void TextEdit::clear_member_keywords() { member_keywords.clear(); update(); } void TextEdit::set_syntax_coloring(bool p_enabled) { syntax_coloring = p_enabled; update(); } bool TextEdit::is_syntax_coloring_enabled() const { return syntax_coloring; } void TextEdit::set_auto_indent(bool p_auto_indent) { auto_indent = p_auto_indent; } void TextEdit::cut() { if (!selection.active) { String clipboard = text[cursor.line]; OS::get_singleton()->set_clipboard(clipboard); cursor_set_line(cursor.line); cursor_set_column(0); _remove_text(cursor.line, 0, cursor.line, text[cursor.line].length()); backspace_at_cursor(); update(); cursor_set_line(cursor.line + 1); cut_copy_line = clipboard; } else { String clipboard = _base_get_text(selection.from_line, selection.from_column, selection.to_line, selection.to_column); OS::get_singleton()->set_clipboard(clipboard); _remove_text(selection.from_line, selection.from_column, selection.to_line, selection.to_column); cursor_set_line(selection.from_line); // set afterwards else it causes the view to be offset cursor_set_column(selection.from_column); selection.active = false; selection.selecting_mode = Selection::MODE_NONE; update(); cut_copy_line = ""; } } void TextEdit::copy() { if (!selection.active) { String clipboard = _base_get_text(cursor.line, 0, cursor.line, text[cursor.line].length()); OS::get_singleton()->set_clipboard(clipboard); cut_copy_line = clipboard; } else { String clipboard = _base_get_text(selection.from_line, selection.from_column, selection.to_line, selection.to_column); OS::get_singleton()->set_clipboard(clipboard); cut_copy_line = ""; } } void TextEdit::paste() { String clipboard = OS::get_singleton()->get_clipboard(); begin_complex_operation(); if (selection.active) { selection.active = false; selection.selecting_mode = Selection::MODE_NONE; _remove_text(selection.from_line, selection.from_column, selection.to_line, selection.to_column); cursor_set_line(selection.from_line); cursor_set_column(selection.from_column); } else if (!cut_copy_line.empty() && cut_copy_line == clipboard) { cursor_set_column(0); String ins = "\n"; clipboard += ins; } _insert_text_at_cursor(clipboard); end_complex_operation(); update(); } void TextEdit::select_all() { if (text.size() == 1 && text[0].length() == 0) return; selection.active = true; selection.from_line = 0; selection.from_column = 0; selection.selecting_line = 0; selection.selecting_column = 0; selection.to_line = text.size() - 1; selection.to_column = text[selection.to_line].length(); selection.selecting_mode = Selection::MODE_SHIFT; selection.shiftclick_left = true; cursor_set_line(selection.to_line, false); cursor_set_column(selection.to_column, false); update(); } void TextEdit::deselect() { selection.active = false; update(); } void TextEdit::select(int p_from_line, int p_from_column, int p_to_line, int p_to_column) { if (p_from_line >= text.size()) p_from_line = text.size() - 1; if (p_from_column >= text[p_from_line].length()) p_from_column = text[p_from_line].length(); if (p_from_column < 0) p_from_column = 0; if (p_to_line >= text.size()) p_to_line = text.size() - 1; if (p_to_column >= text[p_to_line].length()) p_to_column = text[p_to_line].length(); if (p_to_column < 0) p_to_column = 0; selection.from_line = p_from_line; selection.from_column = p_from_column; selection.to_line = p_to_line; selection.to_column = p_to_column; selection.active = true; if (selection.from_line == selection.to_line) { if (selection.from_column == selection.to_column) { selection.active = false; } else if (selection.from_column > selection.to_column) { selection.shiftclick_left = false; SWAP(selection.from_column, selection.to_column); } else { selection.shiftclick_left = true; } } else if (selection.from_line > selection.to_line) { selection.shiftclick_left = false; SWAP(selection.from_line, selection.to_line); SWAP(selection.from_column, selection.to_column); } else { selection.shiftclick_left = true; } update(); } void TextEdit::swap_lines(int line1, int line2) { String tmp = get_line(line1); String tmp2 = get_line(line2); set_line(line2, tmp); set_line(line1, tmp2); } bool TextEdit::is_selection_active() const { return selection.active; } int TextEdit::get_selection_from_line() const { ERR_FAIL_COND_V(!selection.active, -1); return selection.from_line; } int TextEdit::get_selection_from_column() const { ERR_FAIL_COND_V(!selection.active, -1); return selection.from_column; } int TextEdit::get_selection_to_line() const { ERR_FAIL_COND_V(!selection.active, -1); return selection.to_line; } int TextEdit::get_selection_to_column() const { ERR_FAIL_COND_V(!selection.active, -1); return selection.to_column; } String TextEdit::get_selection_text() const { if (!selection.active) return ""; return _base_get_text(selection.from_line, selection.from_column, selection.to_line, selection.to_column); } String TextEdit::get_word_under_cursor() const { int prev_cc = cursor.column; while (prev_cc > 0) { bool is_char = _is_text_char(text[cursor.line][prev_cc - 1]); if (!is_char) break; --prev_cc; } int next_cc = cursor.column; while (next_cc < text[cursor.line].length()) { bool is_char = _is_text_char(text[cursor.line][next_cc]); if (!is_char) break; ++next_cc; } if (prev_cc == cursor.column || next_cc == cursor.column) return ""; return text[cursor.line].substr(prev_cc, next_cc - prev_cc); } void TextEdit::set_search_text(const String &p_search_text) { search_text = p_search_text; } void TextEdit::set_search_flags(uint32_t p_flags) { search_flags = p_flags; } void TextEdit::set_current_search_result(int line, int col) { search_result_line = line; search_result_col = col; update(); } void TextEdit::set_highlight_all_occurrences(const bool p_enabled) { highlight_all_occurrences = p_enabled; update(); } bool TextEdit::is_highlight_all_occurrences_enabled() const { return highlight_all_occurrences; } int TextEdit::_get_column_pos_of_word(const String &p_key, const String &p_search, uint32_t p_search_flags, int p_from_column) { int col = -1; if (p_key.length() > 0 && p_search.length() > 0) { if (p_from_column < 0 || p_from_column > p_search.length()) { p_from_column = 0; } while (col == -1 && p_from_column <= p_search.length()) { if (p_search_flags & SEARCH_MATCH_CASE) { col = p_search.find(p_key, p_from_column); } else { col = p_search.findn(p_key, p_from_column); } // whole words only if (col != -1 && p_search_flags & SEARCH_WHOLE_WORDS) { p_from_column = col; if (col > 0 && _is_text_char(p_search[col - 1])) { col = -1; } else if ((col + p_key.length()) < p_search.length() && _is_text_char(p_search[col + p_key.length()])) { col = -1; } } p_from_column += 1; } } return col; } PoolVector<int> TextEdit::_search_bind(const String &p_key, uint32_t p_search_flags, int p_from_line, int p_from_column) const { int col, line; if (search(p_key, p_search_flags, p_from_line, p_from_column, col, line)) { PoolVector<int> result; result.resize(2); result.set(0, line); result.set(1, col); return result; } else { return PoolVector<int>(); } } bool TextEdit::search(const String &p_key, uint32_t p_search_flags, int p_from_line, int p_from_column, int &r_line, int &r_column) const { if (p_key.length() == 0) return false; ERR_FAIL_INDEX_V(p_from_line, text.size(), false); ERR_FAIL_INDEX_V(p_from_column, text[p_from_line].length() + 1, false); //search through the whole document, but start by current line int line = p_from_line; int pos = -1; for (int i = 0; i < text.size() + 1; i++) { //backwards is broken... //int idx=(p_search_flags&SEARCH_BACKWARDS)?(text.size()-i):i; //do backwards seearch if (line < 0) { line = text.size() - 1; } if (line == text.size()) { line = 0; } String text_line = text[line]; int from_column = 0; if (line == p_from_line) { if (i == text.size()) { //wrapped if (p_search_flags & SEARCH_BACKWARDS) { from_column = text_line.length(); } else { from_column = 0; } } else { from_column = p_from_column; } } else { if (p_search_flags & SEARCH_BACKWARDS) from_column = text_line.length() - 1; else from_column = 0; } pos = -1; int pos_from = 0; int last_pos = -1; while (true) { while ((last_pos = (p_search_flags & SEARCH_MATCH_CASE) ? text_line.find(p_key, pos_from) : text_line.findn(p_key, pos_from)) != -1) { if (p_search_flags & SEARCH_BACKWARDS) { if (last_pos > from_column) break; pos = last_pos; } else { if (last_pos >= from_column) { pos = last_pos; break; } } pos_from = last_pos + p_key.length(); } bool is_match = true; if (pos != -1 && (p_search_flags & SEARCH_WHOLE_WORDS)) { //validate for whole words if (pos > 0 && _is_text_char(text_line[pos - 1])) is_match = false; else if (pos + p_key.length() < text_line.length() && _is_text_char(text_line[pos + p_key.length()])) is_match = false; } if (is_match || last_pos == -1 || pos == -1) { break; } pos_from = pos + 1; pos = -1; } if (pos != -1) break; if (p_search_flags & SEARCH_BACKWARDS) line--; else line++; } if (pos == -1) { r_line = -1; r_column = -1; return false; } r_line = line; r_column = pos; return true; } void TextEdit::_cursor_changed_emit() { emit_signal("cursor_changed"); cursor_changed_dirty = false; } void TextEdit::_text_changed_emit() { emit_signal("text_changed"); text_changed_dirty = false; } void TextEdit::set_line_as_marked(int p_line, bool p_marked) { ERR_FAIL_INDEX(p_line, text.size()); text.set_marked(p_line, p_marked); update(); } bool TextEdit::is_line_set_as_breakpoint(int p_line) const { ERR_FAIL_INDEX_V(p_line, text.size(), false); return text.is_breakpoint(p_line); } void TextEdit::set_line_as_breakpoint(int p_line, bool p_breakpoint) { ERR_FAIL_INDEX(p_line, text.size()); text.set_breakpoint(p_line, p_breakpoint); update(); } void TextEdit::get_breakpoints(List<int> *p_breakpoints) const { for (int i = 0; i < text.size(); i++) { if (text.is_breakpoint(i)) p_breakpoints->push_back(i); } } void TextEdit::set_line_as_hidden(int p_line, bool p_hidden) { ERR_FAIL_INDEX(p_line, text.size()); if (is_hiding_enabled() || !p_hidden) text.set_hidden(p_line, p_hidden); update(); } bool TextEdit::is_line_hidden(int p_line) const { ERR_FAIL_INDEX_V(p_line, text.size(), false); return text.is_hidden(p_line); } void TextEdit::fold_all_lines() { for (int i = 0; i < text.size(); i++) { fold_line(i); } _update_scrollbars(); update(); } void TextEdit::unhide_all_lines() { for (int i = 0; i < text.size(); i++) { text.set_hidden(i, false); } _update_scrollbars(); update(); } int TextEdit::num_lines_from(int p_line_from, int unhidden_amount) const { // returns the number of hidden and unhidden lines from p_line_from to p_line_from + amount of visible lines ERR_FAIL_INDEX_V(p_line_from, text.size(), ABS(unhidden_amount)); if (!is_hiding_enabled()) return ABS(unhidden_amount); int num_visible = 0; int num_total = 0; if (unhidden_amount >= 0) { for (int i = p_line_from; i < text.size(); i++) { num_total++; if (!is_line_hidden(i)) num_visible++; if (num_visible >= unhidden_amount) break; } } else { unhidden_amount = ABS(unhidden_amount); for (int i = p_line_from; i >= 0; i--) { num_total++; if (!is_line_hidden(i)) num_visible++; if (num_visible >= unhidden_amount) break; } } return num_total; } bool TextEdit::is_last_visible_line(int p_line) const { ERR_FAIL_INDEX_V(p_line, text.size(), false); if (p_line == text.size() - 1) return true; if (!is_hiding_enabled()) return false; for (int i = p_line + 1; i < text.size(); i++) { if (!is_line_hidden(i)) return false; } return true; } int TextEdit::get_indent_level(int p_line) const { ERR_FAIL_INDEX_V(p_line, text.size(), 0); // counts number of tabs and spaces before line starts int tab_count = 0; int whitespace_count = 0; int line_length = text[p_line].size(); for (int i = 0; i < line_length - 1; i++) { if (text[p_line][i] == '\t') { tab_count++; } else if (text[p_line][i] == ' ') { whitespace_count++; } else { break; } } return tab_count + whitespace_count / indent_size; } bool TextEdit::is_line_comment(int p_line) const { // checks to see if this line is the start of a comment ERR_FAIL_INDEX_V(p_line, text.size(), false); const Map<int, Text::ColorRegionInfo> &cri_map = text.get_color_region_info(p_line); int line_length = text[p_line].size(); for (int i = 0; i < line_length - 1; i++) { if (_is_symbol(text[p_line][i]) && cri_map.has(i)) { const Text::ColorRegionInfo &cri = cri_map[i]; if (color_regions[cri.region].begin_key == "#" || color_regions[cri.region].begin_key == "//") { return true; } else { return false; } } else if (_is_whitespace(text[p_line][i])) { continue; } else { break; } } return false; } bool TextEdit::can_fold(int p_line) const { ERR_FAIL_INDEX_V(p_line, text.size(), false); if (!is_hiding_enabled()) return false; if (p_line + 1 >= text.size()) return false; if (text[p_line].size() == 0) return false; if (is_folded(p_line)) return false; if (is_line_hidden(p_line)) return false; if (is_line_comment(p_line)) return false; int start_indent = get_indent_level(p_line); for (int i = p_line + 1; i < text.size(); i++) { if (text[i].size() == 0) continue; int next_indent = get_indent_level(i); if (is_line_comment(i)) { continue; } else if (next_indent > start_indent) { return true; } else { return false; } } return false; } bool TextEdit::is_folded(int p_line) const { ERR_FAIL_INDEX_V(p_line, text.size(), false); if (p_line + 1 >= text.size()) return false; if (!is_line_hidden(p_line) && is_line_hidden(p_line + 1)) return true; return false; } void TextEdit::fold_line(int p_line) { ERR_FAIL_INDEX(p_line, text.size()); if (!is_hiding_enabled()) return; if (!can_fold(p_line)) return; // hide lines below this one int start_indent = get_indent_level(p_line); int last_line = start_indent; for (int i = p_line + 1; i < text.size(); i++) { if (text[i].strip_edges().size() != 0) { if (is_line_comment(i)) { continue; } else if (get_indent_level(i) > start_indent) { last_line = i; } else { break; } } } for (int i = p_line + 1; i <= last_line; i++) { set_line_as_hidden(i, true); } // fix selection if (is_selection_active()) { if (is_line_hidden(selection.from_line) && is_line_hidden(selection.to_line)) { deselect(); } else if (is_line_hidden(selection.from_line)) { select(p_line, 9999, selection.to_line, selection.to_column); } else if (is_line_hidden(selection.to_line)) { select(selection.from_line, selection.from_column, p_line, 9999); } } // reset cursor if (is_line_hidden(cursor.line)) { cursor_set_line(p_line, false, false); cursor_set_column(get_line(p_line).length(), false); } _update_scrollbars(); update(); } void TextEdit::unfold_line(int p_line) { ERR_FAIL_INDEX(p_line, text.size()); if (!is_folded(p_line) && !is_line_hidden(p_line)) return; int fold_start = p_line; for (fold_start = p_line; fold_start > 0; fold_start--) { if (is_folded(fold_start)) break; } fold_start = is_folded(fold_start) ? fold_start : p_line; for (int i = fold_start + 1; i < text.size(); i++) { if (is_line_hidden(i)) { set_line_as_hidden(i, false); } else { break; } } _update_scrollbars(); update(); } void TextEdit::toggle_fold_line(int p_line) { ERR_FAIL_INDEX(p_line, text.size()); if (!is_folded(p_line)) fold_line(p_line); else unfold_line(p_line); } int TextEdit::get_line_count() const { return text.size(); } void TextEdit::_do_text_op(const TextOperation &p_op, bool p_reverse) { ERR_FAIL_COND(p_op.type == TextOperation::TYPE_NONE); bool insert = p_op.type == TextOperation::TYPE_INSERT; if (p_reverse) insert = !insert; if (insert) { int check_line; int check_column; _base_insert_text(p_op.from_line, p_op.from_column, p_op.text, check_line, check_column); ERR_FAIL_COND(check_line != p_op.to_line); // BUG ERR_FAIL_COND(check_column != p_op.to_column); // BUG } else { _base_remove_text(p_op.from_line, p_op.from_column, p_op.to_line, p_op.to_column); } } void TextEdit::_clear_redo() { if (undo_stack_pos == NULL) return; //nothing to clear _push_current_op(); while (undo_stack_pos) { List<TextOperation>::Element *elem = undo_stack_pos; undo_stack_pos = undo_stack_pos->next(); undo_stack.erase(elem); } } void TextEdit::undo() { _push_current_op(); if (undo_stack_pos == NULL) { if (!undo_stack.size()) return; //nothing to undo undo_stack_pos = undo_stack.back(); } else if (undo_stack_pos == undo_stack.front()) return; // at the bottom of the undo stack else undo_stack_pos = undo_stack_pos->prev(); deselect(); TextOperation op = undo_stack_pos->get(); _do_text_op(op, true); current_op.version = op.prev_version; if (undo_stack_pos->get().chain_backward) { while (true) { ERR_BREAK(!undo_stack_pos->prev()); undo_stack_pos = undo_stack_pos->prev(); op = undo_stack_pos->get(); _do_text_op(op, true); current_op.version = op.prev_version; if (undo_stack_pos->get().chain_forward) { break; } } } if (undo_stack_pos->get().type == TextOperation::TYPE_REMOVE) { cursor_set_line(undo_stack_pos->get().to_line); cursor_set_column(undo_stack_pos->get().to_column); _cancel_code_hint(); } else { cursor_set_line(undo_stack_pos->get().from_line); cursor_set_column(undo_stack_pos->get().from_column); } update(); } void TextEdit::redo() { _push_current_op(); if (undo_stack_pos == NULL) return; //nothing to do. deselect(); TextOperation op = undo_stack_pos->get(); _do_text_op(op, false); current_op.version = op.version; if (undo_stack_pos->get().chain_forward) { while (true) { ERR_BREAK(!undo_stack_pos->next()); undo_stack_pos = undo_stack_pos->next(); op = undo_stack_pos->get(); _do_text_op(op, false); current_op.version = op.version; if (undo_stack_pos->get().chain_backward) break; } } cursor_set_line(undo_stack_pos->get().to_line); cursor_set_column(undo_stack_pos->get().to_column); undo_stack_pos = undo_stack_pos->next(); update(); } void TextEdit::clear_undo_history() { saved_version = 0; current_op.type = TextOperation::TYPE_NONE; undo_stack_pos = NULL; undo_stack.clear(); } void TextEdit::begin_complex_operation() { _push_current_op(); next_operation_is_complex = true; } void TextEdit::end_complex_operation() { _push_current_op(); ERR_FAIL_COND(undo_stack.size() == 0); if (undo_stack.back()->get().chain_forward) { undo_stack.back()->get().chain_forward = false; return; } undo_stack.back()->get().chain_backward = true; } void TextEdit::_push_current_op() { if (current_op.type == TextOperation::TYPE_NONE) return; // do nothing if (next_operation_is_complex) { current_op.chain_forward = true; next_operation_is_complex = false; } undo_stack.push_back(current_op); current_op.type = TextOperation::TYPE_NONE; current_op.text = ""; current_op.chain_forward = false; } void TextEdit::set_indent_using_spaces(const bool p_use_spaces) { indent_using_spaces = p_use_spaces; } bool TextEdit::is_indent_using_spaces() const { return indent_using_spaces; } void TextEdit::set_indent_size(const int p_size) { ERR_FAIL_COND(p_size <= 0); indent_size = p_size; text.set_indent_size(p_size); space_indent = ""; for (int i = 0; i < p_size; i++) { space_indent += " "; } update(); } int TextEdit::get_indent_size() { return indent_size; } void TextEdit::set_draw_tabs(bool p_draw) { draw_tabs = p_draw; } bool TextEdit::is_drawing_tabs() const { return draw_tabs; } void TextEdit::set_override_selected_font_color(bool p_override_selected_font_color) { override_selected_font_color = p_override_selected_font_color; } bool TextEdit::is_overriding_selected_font_color() const { return override_selected_font_color; } void TextEdit::set_insert_mode(bool p_enabled) { insert_mode = p_enabled; update(); } bool TextEdit::is_insert_mode() const { return insert_mode; } bool TextEdit::is_insert_text_operation() { return (current_op.type == TextOperation::TYPE_INSERT); } uint32_t TextEdit::get_version() const { return current_op.version; } uint32_t TextEdit::get_saved_version() const { return saved_version; } void TextEdit::tag_saved_version() { saved_version = get_version(); } int TextEdit::get_v_scroll() const { return v_scroll->get_value(); } void TextEdit::set_v_scroll(int p_scroll) { if (p_scroll < 0) { p_scroll = 0; } if (!scroll_past_end_of_file_enabled) { if (p_scroll + get_visible_rows() > get_total_unhidden_rows()) { int num_rows = num_lines_from(CLAMP(p_scroll, 0, text.size() - 1), MIN(get_visible_rows(), text.size() - 1 - p_scroll)); p_scroll = text.size() - num_rows; } } v_scroll->set_value(p_scroll); cursor.line_ofs = num_lines_from(0, p_scroll); line_scroll_pos = p_scroll; } int TextEdit::get_h_scroll() const { return h_scroll->get_value(); } void TextEdit::set_h_scroll(int p_scroll) { h_scroll->set_value(p_scroll); } void TextEdit::set_smooth_scroll_enabled(bool p_enable) { v_scroll->set_smooth_scroll_enabled(p_enable); smooth_scroll_enabled = p_enable; } bool TextEdit::is_smooth_scroll_enabled() const { return smooth_scroll_enabled; } void TextEdit::set_v_scroll_speed(float p_speed) { v_scroll_speed = p_speed; } float TextEdit::get_v_scroll_speed() const { return v_scroll_speed; } void TextEdit::set_completion(bool p_enabled, const Vector<String> &p_prefixes) { completion_prefixes.clear(); completion_enabled = p_enabled; for (int i = 0; i < p_prefixes.size(); i++) completion_prefixes.insert(p_prefixes[i]); } void TextEdit::_confirm_completion() { begin_complex_operation(); _remove_text(cursor.line, cursor.column - completion_base.length(), cursor.line, cursor.column); cursor_set_column(cursor.column - completion_base.length(), false); insert_text_at_cursor(completion_current); if (completion_current.ends_with("(") && auto_brace_completion_enabled) { insert_text_at_cursor(")"); cursor.column--; } end_complex_operation(); _cancel_completion(); } void TextEdit::_cancel_code_hint() { VisualServer::get_singleton()->canvas_item_set_z_index(get_canvas_item(), 0); raised_from_completion = false; completion_hint = ""; update(); } void TextEdit::_cancel_completion() { VisualServer::get_singleton()->canvas_item_set_z_index(get_canvas_item(), 0); raised_from_completion = false; if (!completion_active) return; completion_active = false; completion_forced = false; update(); } static bool _is_completable(CharType c) { return !_is_symbol(c) || c == '"' || c == '\''; } void TextEdit::_update_completion_candidates() { String l = text[cursor.line]; int cofs = CLAMP(cursor.column, 0, l.length()); String s; //look for keywords first bool inquote = false; int first_quote = -1; int c = cofs - 1; while (c >= 0) { if (l[c] == '"' || l[c] == '\'') { inquote = !inquote; if (first_quote == -1) first_quote = c; } c--; } bool pre_keyword = false; bool cancel = false; //print_line("inquote: "+itos(inquote)+"first quote "+itos(first_quote)+" cofs-1 "+itos(cofs-1)); if (!inquote && first_quote == cofs - 1) { //no completion here //print_line("cancel!"); cancel = true; } else if (inquote && first_quote != -1) { s = l.substr(first_quote, cofs - first_quote); //print_line("s: 1"+s); } else if (cofs > 0 && l[cofs - 1] == ' ') { int kofs = cofs - 1; String kw; while (kofs >= 0 && l[kofs] == ' ') kofs--; while (kofs >= 0 && l[kofs] > 32 && _is_completable(l[kofs])) { kw = String::chr(l[kofs]) + kw; kofs--; } pre_keyword = keywords.has(kw); //print_line("KW "+kw+"? "+itos(pre_keyword)); } else { while (cofs > 0 && l[cofs - 1] > 32 && (l[cofs - 1] == '/' || _is_completable(l[cofs - 1]))) { s = String::chr(l[cofs - 1]) + s; if (l[cofs - 1] == '\'' || l[cofs - 1] == '"' || l[cofs - 1] == '$') break; cofs--; } } if (cursor.column > 0 && l[cursor.column - 1] == '(' && !pre_keyword && !completion_forced) { cancel = true; } update(); bool prev_is_prefix = false; if (cofs > 0 && completion_prefixes.has(String::chr(l[cofs - 1]))) prev_is_prefix = true; if (cofs > 1 && l[cofs - 1] == ' ' && completion_prefixes.has(String::chr(l[cofs - 2]))) //check with one space before prefix, to allow indent prev_is_prefix = true; if (cancel || (!pre_keyword && s == "" && (cofs == 0 || !prev_is_prefix))) { //none to complete, cancel _cancel_completion(); return; } completion_options.clear(); completion_index = 0; completion_base = s; Vector<float> sim_cache; bool single_quote = s.begins_with("'"); for (int i = 0; i < completion_strings.size(); i++) { if (single_quote && completion_strings[i].is_quoted()) { completion_strings[i] = completion_strings[i].unquote().quote("'"); } if (s == completion_strings[i]) { // A perfect match, stop completion _cancel_completion(); return; } if (s.is_subsequence_ofi(completion_strings[i])) { // don't remove duplicates if no input is provided if (s != "" && completion_options.find(completion_strings[i]) != -1) { continue; } // Calculate the similarity to keep completions in good order float similarity; if (completion_strings[i].to_lower().begins_with(s.to_lower())) { // Substrings are the best candidates similarity = 1.1; } else { // Otherwise compute the similarity similarity = s.to_lower().similarity(completion_strings[i].to_lower()); } int comp_size = completion_options.size(); if (comp_size == 0) { completion_options.push_back(completion_strings[i]); sim_cache.push_back(similarity); } else { float comp_sim; int pos = 0; do { comp_sim = sim_cache[pos++]; } while (pos < comp_size && similarity < comp_sim); pos = similarity > comp_sim ? pos - 1 : pos; // Pos will be off by one completion_options.insert(pos, completion_strings[i]); sim_cache.insert(pos, similarity); } } } if (completion_options.size() == 0) { //no options to complete, cancel _cancel_completion(); return; } // The top of the list is the best match completion_current = completion_options[0]; completion_enabled = true; } void TextEdit::query_code_comple() { String l = text[cursor.line]; int ofs = CLAMP(cursor.column, 0, l.length()); bool inquote = false; int c = ofs - 1; while (c >= 0) { if (l[c] == '"' || l[c] == '\'') inquote = !inquote; c--; } if (ofs > 0 && (inquote || _is_completable(l[ofs - 1]) || completion_prefixes.has(String::chr(l[ofs - 1])))) emit_signal("request_completion"); else if (ofs > 1 && l[ofs - 1] == ' ' && completion_prefixes.has(String::chr(l[ofs - 2]))) //make it work with a space too, it's good enough emit_signal("request_completion"); } void TextEdit::set_code_hint(const String &p_hint) { VisualServer::get_singleton()->canvas_item_set_z_index(get_canvas_item(), 1); raised_from_completion = true; completion_hint = p_hint; completion_hint_offset = -0xFFFF; update(); } void TextEdit::code_complete(const Vector<String> &p_strings, bool p_forced) { VisualServer::get_singleton()->canvas_item_set_z_index(get_canvas_item(), 1); raised_from_completion = true; completion_strings = p_strings; completion_active = true; completion_forced = p_forced; completion_current = ""; completion_index = 0; _update_completion_candidates(); // } String TextEdit::get_word_at_pos(const Vector2 &p_pos) const { int row, col; _get_mouse_pos(p_pos, row, col); String s = text[row]; if (s.length() == 0) return ""; int beg, end; if (select_word(s, col, beg, end)) { bool inside_quotes = false; int qbegin = 0, qend = 0; for (int i = 0; i < s.length(); i++) { if (s[i] == '"') { if (inside_quotes) { qend = i; inside_quotes = false; if (col >= qbegin && col <= qend) { return s.substr(qbegin, qend - qbegin); } } else { qbegin = i + 1; inside_quotes = true; } } } return s.substr(beg, end - beg); } return String(); } String TextEdit::get_tooltip(const Point2 &p_pos) const { if (!tooltip_obj) return Control::get_tooltip(p_pos); int row, col; _get_mouse_pos(p_pos, row, col); String s = text[row]; if (s.length() == 0) return Control::get_tooltip(p_pos); int beg, end; if (select_word(s, col, beg, end)) { String tt = tooltip_obj->call(tooltip_func, s.substr(beg, end - beg), tooltip_ud); return tt; } return Control::get_tooltip(p_pos); } void TextEdit::set_tooltip_request_func(Object *p_obj, const StringName &p_function, const Variant &p_udata) { tooltip_obj = p_obj; tooltip_func = p_function; tooltip_ud = p_udata; } void TextEdit::set_line(int line, String new_text) { if (line < 0 || line > text.size()) return; _remove_text(line, 0, line, text[line].length()); _insert_text(line, 0, new_text); if (cursor.line == line) { cursor.column = MIN(cursor.column, new_text.length()); } } void TextEdit::insert_at(const String &p_text, int at) { cursor_set_column(0); cursor_set_line(at, false, true); _insert_text(at, 0, p_text + "\n"); } void TextEdit::set_show_line_numbers(bool p_show) { line_numbers = p_show; update(); } void TextEdit::set_line_numbers_zero_padded(bool p_zero_padded) { line_numbers_zero_padded = p_zero_padded; update(); } bool TextEdit::is_show_line_numbers_enabled() const { return line_numbers; } void TextEdit::set_show_line_length_guideline(bool p_show) { line_length_guideline = p_show; update(); } void TextEdit::set_line_length_guideline_column(int p_column) { line_length_guideline_col = p_column; update(); } void TextEdit::set_draw_breakpoint_gutter(bool p_draw) { draw_breakpoint_gutter = p_draw; update(); } bool TextEdit::is_drawing_breakpoint_gutter() const { return draw_breakpoint_gutter; } void TextEdit::set_breakpoint_gutter_width(int p_gutter_width) { breakpoint_gutter_width = p_gutter_width; update(); } int TextEdit::get_breakpoint_gutter_width() const { return cache.breakpoint_gutter_width; } void TextEdit::set_draw_fold_gutter(bool p_draw) { draw_fold_gutter = p_draw; update(); } bool TextEdit::is_drawing_fold_gutter() const { return draw_fold_gutter; } void TextEdit::set_fold_gutter_width(int p_gutter_width) { fold_gutter_width = p_gutter_width; update(); } int TextEdit::get_fold_gutter_width() const { return cache.fold_gutter_width; } void TextEdit::set_hiding_enabled(int p_enabled) { if (!p_enabled) unhide_all_lines(); hiding_enabled = p_enabled; update(); } int TextEdit::is_hiding_enabled() const { return hiding_enabled; } void TextEdit::set_highlight_current_line(bool p_enabled) { highlight_current_line = p_enabled; update(); } bool TextEdit::is_highlight_current_line_enabled() const { return highlight_current_line; } bool TextEdit::is_text_field() const { return true; } void TextEdit::menu_option(int p_option) { switch (p_option) { case MENU_CUT: { if (!readonly) { cut(); } } break; case MENU_COPY: { copy(); } break; case MENU_PASTE: { if (!readonly) { paste(); } } break; case MENU_CLEAR: { if (!readonly) { clear(); } } break; case MENU_SELECT_ALL: { select_all(); } break; case MENU_UNDO: { undo(); } break; }; } void TextEdit::set_select_identifiers_on_hover(bool p_enable) { select_identifiers_enabled = p_enable; } bool TextEdit::is_selecting_identifiers_on_hover_enabled() const { return select_identifiers_enabled; } void TextEdit::set_context_menu_enabled(bool p_enable) { context_menu_enabled = p_enable; } bool TextEdit::is_context_menu_enabled() { return context_menu_enabled; } PopupMenu *TextEdit::get_menu() const { return menu; } void TextEdit::_bind_methods() { ClassDB::bind_method(D_METHOD("_gui_input"), &TextEdit::_gui_input); ClassDB::bind_method(D_METHOD("_scroll_moved"), &TextEdit::_scroll_moved); ClassDB::bind_method(D_METHOD("_cursor_changed_emit"), &TextEdit::_cursor_changed_emit); ClassDB::bind_method(D_METHOD("_text_changed_emit"), &TextEdit::_text_changed_emit); ClassDB::bind_method(D_METHOD("_push_current_op"), &TextEdit::_push_current_op); ClassDB::bind_method(D_METHOD("_click_selection_held"), &TextEdit::_click_selection_held); ClassDB::bind_method(D_METHOD("_toggle_draw_caret"), &TextEdit::_toggle_draw_caret); ClassDB::bind_method(D_METHOD("_v_scroll_input"), &TextEdit::_v_scroll_input); BIND_ENUM_CONSTANT(SEARCH_MATCH_CASE); BIND_ENUM_CONSTANT(SEARCH_WHOLE_WORDS); BIND_ENUM_CONSTANT(SEARCH_BACKWARDS); /* ClassDB::bind_method(D_METHOD("delete_char"),&TextEdit::delete_char); ClassDB::bind_method(D_METHOD("delete_line"),&TextEdit::delete_line); */ ClassDB::bind_method(D_METHOD("set_text", "text"), &TextEdit::set_text); ClassDB::bind_method(D_METHOD("insert_text_at_cursor", "text"), &TextEdit::insert_text_at_cursor); ClassDB::bind_method(D_METHOD("get_line_count"), &TextEdit::get_line_count); ClassDB::bind_method(D_METHOD("get_text"), &TextEdit::get_text); ClassDB::bind_method(D_METHOD("get_line", "line"), &TextEdit::get_line); ClassDB::bind_method(D_METHOD("cursor_set_column", "column", "adjust_viewport"), &TextEdit::cursor_set_column, DEFVAL(true)); ClassDB::bind_method(D_METHOD("cursor_set_line", "line", "adjust_viewport", "can_be_hidden"), &TextEdit::cursor_set_line, DEFVAL(true), DEFVAL(true)); ClassDB::bind_method(D_METHOD("cursor_get_column"), &TextEdit::cursor_get_column); ClassDB::bind_method(D_METHOD("cursor_get_line"), &TextEdit::cursor_get_line); ClassDB::bind_method(D_METHOD("cursor_set_blink_enabled", "enable"), &TextEdit::cursor_set_blink_enabled); ClassDB::bind_method(D_METHOD("cursor_get_blink_enabled"), &TextEdit::cursor_get_blink_enabled); ClassDB::bind_method(D_METHOD("cursor_set_blink_speed", "blink_speed"), &TextEdit::cursor_set_blink_speed); ClassDB::bind_method(D_METHOD("cursor_get_blink_speed"), &TextEdit::cursor_get_blink_speed); ClassDB::bind_method(D_METHOD("cursor_set_block_mode", "enable"), &TextEdit::cursor_set_block_mode); ClassDB::bind_method(D_METHOD("cursor_is_block_mode"), &TextEdit::cursor_is_block_mode); ClassDB::bind_method(D_METHOD("set_right_click_moves_caret", "enable"), &TextEdit::set_right_click_moves_caret); ClassDB::bind_method(D_METHOD("is_right_click_moving_caret"), &TextEdit::is_right_click_moving_caret); ClassDB::bind_method(D_METHOD("set_readonly", "enable"), &TextEdit::set_readonly); ClassDB::bind_method(D_METHOD("is_readonly"), &TextEdit::is_readonly); ClassDB::bind_method(D_METHOD("set_wrap", "enable"), &TextEdit::set_wrap); ClassDB::bind_method(D_METHOD("is_wrapping"), &TextEdit::is_wrapping); // ClassDB::bind_method(D_METHOD("set_max_chars", "amount"), &TextEdit::set_max_chars); // ClassDB::bind_method(D_METHOD("get_max_char"), &TextEdit::get_max_chars); ClassDB::bind_method(D_METHOD("set_context_menu_enabled", "enable"), &TextEdit::set_context_menu_enabled); ClassDB::bind_method(D_METHOD("is_context_menu_enabled"), &TextEdit::is_context_menu_enabled); ClassDB::bind_method(D_METHOD("cut"), &TextEdit::cut); ClassDB::bind_method(D_METHOD("copy"), &TextEdit::copy); ClassDB::bind_method(D_METHOD("paste"), &TextEdit::paste); ClassDB::bind_method(D_METHOD("select", "from_line", "from_column", "to_line", "to_column"), &TextEdit::select); ClassDB::bind_method(D_METHOD("select_all"), &TextEdit::select_all); ClassDB::bind_method(D_METHOD("deselect"), &TextEdit::deselect); ClassDB::bind_method(D_METHOD("is_selection_active"), &TextEdit::is_selection_active); ClassDB::bind_method(D_METHOD("get_selection_from_line"), &TextEdit::get_selection_from_line); ClassDB::bind_method(D_METHOD("get_selection_from_column"), &TextEdit::get_selection_from_column); ClassDB::bind_method(D_METHOD("get_selection_to_line"), &TextEdit::get_selection_to_line); ClassDB::bind_method(D_METHOD("get_selection_to_column"), &TextEdit::get_selection_to_column); ClassDB::bind_method(D_METHOD("get_selection_text"), &TextEdit::get_selection_text); ClassDB::bind_method(D_METHOD("get_word_under_cursor"), &TextEdit::get_word_under_cursor); ClassDB::bind_method(D_METHOD("search", "key", "flags", "from_line", "from_column"), &TextEdit::_search_bind); ClassDB::bind_method(D_METHOD("undo"), &TextEdit::undo); ClassDB::bind_method(D_METHOD("redo"), &TextEdit::redo); ClassDB::bind_method(D_METHOD("clear_undo_history"), &TextEdit::clear_undo_history); ClassDB::bind_method(D_METHOD("set_show_line_numbers", "enable"), &TextEdit::set_show_line_numbers); ClassDB::bind_method(D_METHOD("is_show_line_numbers_enabled"), &TextEdit::is_show_line_numbers_enabled); ClassDB::bind_method(D_METHOD("set_hiding_enabled", "enable"), &TextEdit::set_hiding_enabled); ClassDB::bind_method(D_METHOD("is_hiding_enabled"), &TextEdit::is_hiding_enabled); ClassDB::bind_method(D_METHOD("set_line_as_hidden", "line", "enable"), &TextEdit::set_line_as_hidden); ClassDB::bind_method(D_METHOD("is_line_hidden", "line"), &TextEdit::is_line_hidden); ClassDB::bind_method(D_METHOD("fold_all_lines"), &TextEdit::fold_all_lines); ClassDB::bind_method(D_METHOD("unhide_all_lines"), &TextEdit::unhide_all_lines); ClassDB::bind_method(D_METHOD("fold_line", "line"), &TextEdit::fold_line); ClassDB::bind_method(D_METHOD("unfold_line", "line"), &TextEdit::unfold_line); ClassDB::bind_method(D_METHOD("toggle_fold_line", "line"), &TextEdit::toggle_fold_line); ClassDB::bind_method(D_METHOD("can_fold", "line"), &TextEdit::can_fold); ClassDB::bind_method(D_METHOD("is_folded", "line"), &TextEdit::is_folded); ClassDB::bind_method(D_METHOD("set_highlight_all_occurrences", "enable"), &TextEdit::set_highlight_all_occurrences); ClassDB::bind_method(D_METHOD("is_highlight_all_occurrences_enabled"), &TextEdit::is_highlight_all_occurrences_enabled); ClassDB::bind_method(D_METHOD("set_override_selected_font_color", "override"), &TextEdit::set_override_selected_font_color); ClassDB::bind_method(D_METHOD("is_overriding_selected_font_color"), &TextEdit::is_overriding_selected_font_color); ClassDB::bind_method(D_METHOD("set_syntax_coloring", "enable"), &TextEdit::set_syntax_coloring); ClassDB::bind_method(D_METHOD("is_syntax_coloring_enabled"), &TextEdit::is_syntax_coloring_enabled); ClassDB::bind_method(D_METHOD("set_highlight_current_line", "enabled"), &TextEdit::set_highlight_current_line); ClassDB::bind_method(D_METHOD("is_highlight_current_line_enabled"), &TextEdit::is_highlight_current_line_enabled); ClassDB::bind_method(D_METHOD("set_smooth_scroll_enable", "enable"), &TextEdit::set_smooth_scroll_enabled); ClassDB::bind_method(D_METHOD("is_smooth_scroll_enabled"), &TextEdit::is_smooth_scroll_enabled); ClassDB::bind_method(D_METHOD("set_v_scroll_speed", "speed"), &TextEdit::set_v_scroll_speed); ClassDB::bind_method(D_METHOD("get_v_scroll_speed"), &TextEdit::get_v_scroll_speed); ClassDB::bind_method(D_METHOD("add_keyword_color", "keyword", "color"), &TextEdit::add_keyword_color); ClassDB::bind_method(D_METHOD("has_keyword_color", "keyword"), &TextEdit::has_keyword_color); ClassDB::bind_method(D_METHOD("get_keyword_color", "keyword"), &TextEdit::get_keyword_color); ClassDB::bind_method(D_METHOD("add_color_region", "begin_key", "end_key", "color", "line_only"), &TextEdit::add_color_region, DEFVAL(false)); ClassDB::bind_method(D_METHOD("clear_colors"), &TextEdit::clear_colors); ClassDB::bind_method(D_METHOD("menu_option", "option"), &TextEdit::menu_option); ClassDB::bind_method(D_METHOD("get_menu"), &TextEdit::get_menu); ADD_PROPERTY(PropertyInfo(Variant::STRING, "text", PROPERTY_HINT_MULTILINE_TEXT), "set_text", "get_text"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "readonly"), "set_readonly", "is_readonly"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "highlight_current_line"), "set_highlight_current_line", "is_highlight_current_line_enabled"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "syntax_highlighting"), "set_syntax_coloring", "is_syntax_coloring_enabled"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "show_line_numbers"), "set_show_line_numbers", "is_show_line_numbers_enabled"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "highlight_all_occurrences"), "set_highlight_all_occurrences", "is_highlight_all_occurrences_enabled"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "override_selected_font_color"), "set_override_selected_font_color", "is_overriding_selected_font_color"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "context_menu_enabled"), "set_context_menu_enabled", "is_context_menu_enabled"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "smooth_scrolling"), "set_smooth_scroll_enable", "is_smooth_scroll_enabled"); ADD_PROPERTY(PropertyInfo(Variant::REAL, "v_scroll_speed"), "set_v_scroll_speed", "get_v_scroll_speed"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "hiding_enabled"), "set_hiding_enabled", "is_hiding_enabled"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "wrap_lines"), "set_wrap", "is_wrapping"); // ADD_PROPERTY(PropertyInfo(Variant::BOOL, "max_chars"), "set_max_chars", "get_max_chars"); ADD_GROUP("Caret", "caret_"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "caret_block_mode"), "cursor_set_block_mode", "cursor_is_block_mode"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "caret_blink"), "cursor_set_blink_enabled", "cursor_get_blink_enabled"); ADD_PROPERTYNZ(PropertyInfo(Variant::REAL, "caret_blink_speed", PROPERTY_HINT_RANGE, "0.1,10,0.01"), "cursor_set_blink_speed", "cursor_get_blink_speed"); ADD_PROPERTY(PropertyInfo(Variant::BOOL, "caret_moving_by_right_click"), "set_right_click_moves_caret", "is_right_click_moving_caret"); ADD_SIGNAL(MethodInfo("cursor_changed")); ADD_SIGNAL(MethodInfo("text_changed")); ADD_SIGNAL(MethodInfo("request_completion")); ADD_SIGNAL(MethodInfo("breakpoint_toggled", PropertyInfo(Variant::INT, "row"))); ADD_SIGNAL(MethodInfo("symbol_lookup", PropertyInfo(Variant::STRING, "symbol"), PropertyInfo(Variant::INT, "row"), PropertyInfo(Variant::INT, "column"))); BIND_ENUM_CONSTANT(MENU_CUT); BIND_ENUM_CONSTANT(MENU_COPY); BIND_ENUM_CONSTANT(MENU_PASTE); BIND_ENUM_CONSTANT(MENU_CLEAR); BIND_ENUM_CONSTANT(MENU_SELECT_ALL); BIND_ENUM_CONSTANT(MENU_UNDO); BIND_ENUM_CONSTANT(MENU_MAX); GLOBAL_DEF("gui/timers/text_edit_idle_detect_sec", 3); } TextEdit::TextEdit() { readonly = false; setting_row = false; draw_tabs = false; override_selected_font_color = false; draw_caret = true; max_chars = 0; clear(); wrap = false; set_focus_mode(FOCUS_ALL); syntax_highlighter = NULL; _update_caches(); cache.size = Size2(1, 1); cache.row_height = 1; cache.line_spacing = 1; cache.line_number_w = 1; cache.breakpoint_gutter_width = 0; breakpoint_gutter_width = 0; cache.fold_gutter_width = 0; fold_gutter_width = 0; indent_size = 4; text.set_indent_size(indent_size); text.clear(); //text.insert(1,"Mongolia..."); //text.insert(2,"PAIS GENEROSO!!"); text.set_color_regions(&color_regions); h_scroll = memnew(HScrollBar); v_scroll = memnew(VScrollBar); add_child(h_scroll); add_child(v_scroll); updating_scrolls = false; selection.active = false; h_scroll->connect("value_changed", this, "_scroll_moved"); v_scroll->connect("value_changed", this, "_scroll_moved"); v_scroll->connect("scrolling", this, "_v_scroll_input"); cursor_changed_dirty = false; text_changed_dirty = false; selection.selecting_mode = Selection::MODE_NONE; selection.selecting_line = 0; selection.selecting_column = 0; selection.selecting_text = false; selection.active = false; syntax_coloring = false; block_caret = false; caret_blink_enabled = false; caret_blink_timer = memnew(Timer); add_child(caret_blink_timer); caret_blink_timer->set_wait_time(0.65); caret_blink_timer->connect("timeout", this, "_toggle_draw_caret"); cursor_set_blink_enabled(false); right_click_moves_caret = true; idle_detect = memnew(Timer); add_child(idle_detect); idle_detect->set_one_shot(true); idle_detect->set_wait_time(GLOBAL_GET("gui/timers/text_edit_idle_detect_sec")); idle_detect->connect("timeout", this, "_push_current_op"); click_select_held = memnew(Timer); add_child(click_select_held); click_select_held->set_wait_time(0.05); click_select_held->connect("timeout", this, "_click_selection_held"); current_op.type = TextOperation::TYPE_NONE; undo_enabled = true; undo_stack_pos = NULL; setting_text = false; last_dblclk = 0; current_op.version = 0; version = 0; saved_version = 0; completion_enabled = false; completion_active = false; completion_line_ofs = 0; tooltip_obj = NULL; line_numbers = false; line_numbers_zero_padded = false; line_length_guideline = false; line_length_guideline_col = 80; draw_breakpoint_gutter = false; draw_fold_gutter = false; hiding_enabled = false; next_operation_is_complex = false; scroll_past_end_of_file_enabled = false; auto_brace_completion_enabled = false; brace_matching_enabled = false; highlight_all_occurrences = false; highlight_current_line = false; indent_using_spaces = false; space_indent = " "; auto_indent = false; insert_mode = false; window_has_focus = true; select_identifiers_enabled = false; smooth_scroll_enabled = false; scrolling = false; target_v_scroll = 0; v_scroll_speed = 80; raised_from_completion = false; context_menu_enabled = true; menu = memnew(PopupMenu); add_child(menu); menu->add_item(RTR("Cut"), MENU_CUT, KEY_MASK_CMD | KEY_X); menu->add_item(RTR("Copy"), MENU_COPY, KEY_MASK_CMD | KEY_C); menu->add_item(RTR("Paste"), MENU_PASTE, KEY_MASK_CMD | KEY_V); menu->add_separator(); menu->add_item(RTR("Select All"), MENU_SELECT_ALL, KEY_MASK_CMD | KEY_A); menu->add_item(RTR("Clear"), MENU_CLEAR); menu->add_separator(); menu->add_item(RTR("Undo"), MENU_UNDO, KEY_MASK_CMD | KEY_Z); menu->connect("id_pressed", this, "menu_option"); } TextEdit::~TextEdit() { } /////////////////////////////////////////////////////////////////////////////// Map<int, TextEdit::HighlighterInfo> TextEdit::_get_line_syntax_highlighting(int p_line) { if (syntax_highlighter != NULL) { return syntax_highlighter->_get_line_syntax_highlighting(p_line); } Map<int, HighlighterInfo> color_map; bool prev_is_char = false; bool prev_is_number = false; bool in_keyword = false; bool in_word = false; bool in_function_name = false; bool in_member_variable = false; bool is_hex_notation = false; Color keyword_color; Color color; int in_region = _is_line_in_region(p_line); int deregion = 0; const Map<int, TextEdit::Text::ColorRegionInfo> cri_map = text.get_color_region_info(p_line); const String &str = text[p_line]; Color prev_color; for (int j = 0; j < str.length(); j++) { HighlighterInfo highlighter_info; if (deregion > 0) { deregion--; if (deregion == 0) { in_region = -1; } } if (deregion != 0) { if (color != prev_color) { prev_color = color; highlighter_info.color = color; color_map[j] = highlighter_info; } continue; } color = cache.font_color; bool is_char = _is_text_char(str[j]); bool is_symbol = _is_symbol(str[j]); bool is_number = _is_number(str[j]); // allow ABCDEF in hex notation if (is_hex_notation && (_is_hex_symbol(str[j]) || is_number)) { is_number = true; } else { is_hex_notation = false; } // check for dot or underscore or 'x' for hex notation in floating point number if ((str[j] == '.' || str[j] == 'x' || str[j] == '_') && !in_word && prev_is_number && !is_number) { is_number = true; is_symbol = false; is_char = false; if (str[j] == 'x' && str[j - 1] == '0') { is_hex_notation = true; } } if (!in_word && _is_char(str[j]) && !is_number) { in_word = true; } if ((in_keyword || in_word) && !is_hex_notation) { is_number = false; } if (is_symbol && str[j] != '.' && in_word) { in_word = false; } if (is_symbol && cri_map.has(j)) { const TextEdit::Text::ColorRegionInfo &cri = cri_map[j]; if (in_region == -1) { if (!cri.end) { in_region = cri.region; } } else if (in_region == cri.region && !color_regions[cri.region].line_only) { //ignore otherwise if (cri.end || color_regions[cri.region].eq) { deregion = color_regions[cri.region].eq ? color_regions[cri.region].begin_key.length() : color_regions[cri.region].end_key.length(); } } } if (!is_char) { in_keyword = false; } if (in_region == -1 && !in_keyword && is_char && !prev_is_char) { int to = j; while (to < str.length() && _is_text_char(str[to])) to++; uint32_t hash = String::hash(&str[j], to - j); StrRange range(&str[j], to - j); const Color *col = keywords.custom_getptr(range, hash); if (!col) { col = member_keywords.custom_getptr(range, hash); if (col) { for (int k = j - 1; k >= 0; k--) { if (str[k] == '.') { col = NULL; //member indexing not allowed break; } else if (str[k] > 32) { break; } } } } if (col) { in_keyword = true; keyword_color = *col; } } if (!in_function_name && in_word && !in_keyword) { int k = j; while (k < str.length() && !_is_symbol(str[k]) && str[k] != '\t' && str[k] != ' ') { k++; } // check for space between name and bracket while (k < str.length() && (str[k] == '\t' || str[k] == ' ')) { k++; } if (str[k] == '(') { in_function_name = true; } } if (!in_function_name && !in_member_variable && !in_keyword && !is_number && in_word) { int k = j; while (k > 0 && !_is_symbol(str[k]) && str[k] != '\t' && str[k] != ' ') { k--; } if (str[k] == '.') { in_member_variable = true; } } if (is_symbol) { in_function_name = false; in_member_variable = false; } if (in_region >= 0) color = color_regions[in_region].color; else if (in_keyword) color = keyword_color; else if (in_member_variable) color = cache.member_variable_color; else if (in_function_name) color = cache.function_color; else if (is_symbol) color = cache.symbol_color; else if (is_number) color = cache.number_color; prev_is_char = is_char; prev_is_number = is_number; if (color != prev_color) { prev_color = color; highlighter_info.color = color; color_map[j] = highlighter_info; } } return color_map; } void SyntaxHighlighter::set_text_editor(TextEdit *p_text_editor) { text_editor = p_text_editor; } TextEdit *SyntaxHighlighter::get_text_editor() { return text_editor; }
27.528373
271
0.663734
[ "object", "vector" ]
4ffaea80ad4cafa8e6e50eb26eea88a7dc5e23f5
15,965
cpp
C++
Samples/WiFiDirectServices/cpp/WiFiDirectServicesManager.cpp
lythix/Windows-universal-samples
773db9338b5de0b1058097f77ad3ac68dbc0a73d
[ "MIT" ]
2
2019-04-09T20:32:41.000Z
2022-02-03T12:41:05.000Z
Samples/WiFiDirectServices/cpp/WiFiDirectServicesManager.cpp
lythix/Windows-universal-samples
773db9338b5de0b1058097f77ad3ac68dbc0a73d
[ "MIT" ]
null
null
null
Samples/WiFiDirectServices/cpp/WiFiDirectServicesManager.cpp
lythix/Windows-universal-samples
773db9338b5de0b1058097f77ad3ac68dbc0a73d
[ "MIT" ]
2
2020-07-13T03:05:00.000Z
2021-08-11T15:16:12.000Z
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // //********************************************************* #include "pch.h" #include "WiFiDirectServicesManager.h" #include "Scenario1_AdvertiserCreate.xaml.h" #include "Scenario2_AdvertiserAccept.xaml.h" #include "Scenario3_SeekerDiscover.xaml.h" #include "Scenario4_SeekerSession.xaml.h" #include "Scenario5_SendData.xaml.h" using namespace SDKTemplate; using namespace SDKTemplate::WiFiDirectServices; using namespace Concurrency; using namespace Platform; using namespace Platform::Collections; using namespace Windows::Devices::Enumeration; using namespace Windows::Devices::WiFiDirect::Services; using namespace Windows::Foundation::Collections; using namespace Windows::Storage::Streams; using namespace Windows::UI::Core; using namespace std; WiFiDirectServiceManager^ WiFiDirectServiceManager::_instance = nullptr; WiFiDirectServiceManager::WiFiDirectServiceManager() { _rootPage = MainPage::Current; } WiFiDirectServiceManager^ WiFiDirectServiceManager::Instance::get() { if (_instance == nullptr) { _instance = ref new WiFiDirectServiceManager(); } return _instance; } MainPage^ WiFiDirectServiceManager::RootPage::get() { if (_rootPage == nullptr) { _rootPage = MainPage::Current; } return _rootPage; } void WiFiDirectServiceManager::NotifyUser(String ^ strMessage, NotifyType type) { // Always dispatch to UI thread _rootPage->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, strMessage, type]() { _rootPage->NotifyUser(strMessage, type); })); } void WiFiDirectServiceManager::StartAdvertisement( String^ serviceName, bool autoAccept, bool preferGO, String^ pin, IVector<WiFiDirectServiceConfigurationMethod>^ configMethods, WiFiDirectServiceStatus status, unsigned int customStatus, String^ serviceInfo, String^ deferredServiceInfo, IVector<String^>^ prefixList ) { // Create Advertiser object for the service // NOTE: service name is internally limited to up to 255 bytes in UTF-8 encoding // Valid characters include alpha-numeric, '.', '-', and any multi-byte character // characters a-z, A-Z are case-insensitive when discovering services WiFiDirectServiceAdvertiser^ advertiser = ref new WiFiDirectServiceAdvertiser(serviceName); // Auto-accept services will connect without interaction from advertiser // NOTE: if the config method used for a connection requires a PIN, then the advertiser will have to accept the connection advertiser->AutoAcceptSession = autoAccept; // Set the Group Owner intent to a large value so that the advertiser will try to become the group owner (GO) // NOTE: The GO of a P2P connection can connect to multiple clients while the client can connect to a single GO only advertiser->PreferGroupOwnerMode = preferGO; // Default status is "Available", but services may use a custom status code (value > 1) if applicable advertiser->ServiceStatus = status; advertiser->CustomServiceStatusCode = customStatus; // Service information can be up to 65000 bytes. // Service Seeker may explicitly discover this by specifying a short buffer that is a subset of this buffer. // If seeker portion matches, then entire buffer is returned, otherwise, the service information is not returned to the seeker // This sample uses a string for the buffer but it can be any data if (serviceInfo != nullptr && serviceInfo->Length() > 0) { auto serviceInfoDataWriter = ref new DataWriter(ref new InMemoryRandomAccessStream()); serviceInfoDataWriter->WriteString(serviceInfo); advertiser->ServiceInfo = serviceInfoDataWriter->DetachBuffer(); } else { advertiser->ServiceInfo = nullptr; } // This is a buffer of up to 144 bytes that is sent to the seeker in case the connection is "deferred" (i.e. not auto-accepted) // This buffer will be sent when auto-accept is false, or if a PIN is required to complete the connection // For the sample, we use a string, but it can contain any data if (deferredServiceInfo != nullptr && deferredServiceInfo->Length() > 0) { auto deferredSessionInfoDataWriter = ref new DataWriter(ref new InMemoryRandomAccessStream()); deferredSessionInfoDataWriter->WriteString(deferredServiceInfo); advertiser->DeferredSessionInfo = deferredSessionInfoDataWriter->DetachBuffer(); } else { advertiser->DeferredSessionInfo = nullptr; } // The advertiser supported configuration methods // Valid values are PIN-only (either keypad entry, display, or both), or PIN (keypad entry, display, or both) and WFD Services default // WFD Services Default config method does not require explicit PIN entry and offers a more seamless connection experience // Typically, an advertiser will support PIN display (and WFD Services Default), and a seeker will connect with either PIN entry or WFD Services Default if (configMethods != nullptr) { advertiser->PreferredConfigurationMethods->Clear(); for (auto&& configMethod : configMethods) { advertiser->PreferredConfigurationMethods->Append(configMethod); } } // Advertiser may also be discoverable by a prefix of the service name. Must explicitly specify prefixes allowed here. if (prefixList != nullptr && prefixList->Size > 0) { advertiser->ServiceNamePrefixes->Clear(); for (auto&& prefix : prefixList) { advertiser->ServiceNamePrefixes->Append(prefix); } } // For this sample, we wrap the advertiser in our own object which handles the advertiser events AdvertisementWrapper^ advertiserWrapper = ref new AdvertisementWrapper(advertiser, this, pin); AddAdvertiser(advertiserWrapper); RootPage->NotifyUser("Starting service...", NotifyType::StatusMessage); try { // This may fail if the driver is unable to handle the request or if services is not supported // NOTE: this must be called from the UI thread of the app advertiser->Start(); } catch (Exception^ ex) { RootPage->NotifyUser("Failed to start service: " + ex->Message, NotifyType::ErrorMessage); throw; } } void WiFiDirectServiceManager::UnpublishService(unsigned int index) { AdvertisementWrapper^ advertiser = nullptr; { lock_guard<mutex> lock(_managerMutex); if (index > _advertisers->Size - 1) { throw ref new OutOfBoundsException("Attempted to stop service not found in list"); } advertiser = _advertisers->GetAt(index); } try { advertiser->Advertiser->Stop(); } catch (Exception^ ex) { RootPage->NotifyUser("Stop Advertisement Failed: " + ex->Message, NotifyType::ErrorMessage); } } void WiFiDirectServiceManager::DiscoverServicesAsync(String^ serviceName, String^ requestedServiceInfo) { RootPage->NotifyUser("Discover services... (name='" + serviceName + "', requestedInfo='" + requestedServiceInfo + "')", NotifyType::StatusMessage); // Clear old results _discoveredDevices->Clear(); // Discovery depends on whether service information is requested String^ serviceSelector = ""; if (requestedServiceInfo == "") { // Just search by name serviceSelector = WiFiDirectService::GetSelector(serviceName); } else { auto serviceInfoDataWriter = ref new DataWriter(ref new InMemoryRandomAccessStream()); serviceInfoDataWriter->WriteString(requestedServiceInfo); // Discover by name and try to discover service information serviceSelector = WiFiDirectService::GetSelector(serviceName, serviceInfoDataWriter->DetachBuffer()); } auto additionalProperties = ref new Vector<String^>(); additionalProperties->Append("System.Devices.WiFiDirectServices.ServiceAddress"); additionalProperties->Append("System.Devices.WiFiDirectServices.ServiceName"); additionalProperties->Append("System.Devices.WiFiDirectServices.ServiceInformation"); additionalProperties->Append("System.Devices.WiFiDirectServices.AdvertisementId"); additionalProperties->Append("System.Devices.WiFiDirectServices.ServiceConfigMethods"); // Note: This sample demonstrates finding services with FindAllAsync, which does a discovery and returns a list // It is also possible to use DeviceWatcher to receive updates as soon as services are found and to continue the discovery until it is stopped // See the DeviceWatcher sample for an example on how to use that class instead of DeviceInformation.FindAllAsync create_task(DeviceInformation::FindAllAsync(serviceSelector, additionalProperties)).then([this](DeviceInformationCollection^ deviceInfoCollection) { if (deviceInfoCollection != nullptr && deviceInfoCollection->Size > 0) { NotifyUser("Done discovering services, found " + deviceInfoCollection->Size + " services", NotifyType::StatusMessage); for (auto&& device : deviceInfoCollection) { _discoveredDevices->Append(ref new DiscoveredDeviceWrapper(device, this)); } } else { NotifyUser("Done discovering services, No services found", NotifyType::StatusMessage); } // Update UI list if (_scenario3 != nullptr) { _scenario3->UpdateDiscoveryList(_discoveredDevices); } }).then([this](task<void> previousTask) { try { // Try getting all exceptions from the continuation chain above this point. previousTask.get(); } catch (Exception^ ex) { NotifyUser("FindAllAsync Failed: " + ex->Message, NotifyType::ErrorMessage); } }); } void WiFiDirectServiceManager::RemoveAdvertiser(AdvertisementWrapper^ advertiser) { unsigned int index = 0; bool fFound = false; { lock_guard<mutex> lock(_managerMutex); // Lookup the index for (auto&& a : _advertisers) { if (a->InternalId == advertiser->InternalId) { fFound = true; break; } ++index; } } if (fFound) { RemoveAdvertiser(index); } else { NotifyUser("Advertiser not found in list", NotifyType::ErrorMessage); } } void WiFiDirectServiceManager::AddSessionRequest(WiFiDirectServiceSessionRequest^ request, AdvertisementWrapper^ advertiser) { // Update UI to add this to list if (_scenario2 != nullptr) { _scenario2->AddSessionRequest(request, advertiser); } } void WiFiDirectServiceManager::RemoveSessionRequest(WiFiDirectServiceSessionRequest^ request, AdvertisementWrapper^ advertiser) { // Update UI to remove from list if (_scenario2 != nullptr) { _scenario2->RemoveSessionRequest(request, advertiser); } } void WiFiDirectServiceManager::AdvertiserStatusChanged(AdvertisementWrapper^ advertiser) { if (advertiser->Advertiser->AdvertisementStatus == WiFiDirectServiceAdvertisementStatus::Aborted || advertiser->Advertiser->AdvertisementStatus == WiFiDirectServiceAdvertisementStatus::Stopped) { RemoveAdvertiser(advertiser); } else { if (_scenario2 != nullptr) { _scenario2->UpdateAdvertiserStatus(advertiser); } } } void WiFiDirectServiceManager::AddSession(SessionWrapper^ session) { { lock_guard<mutex> lock(_managerMutex); _connectedSessions->Append(session); } // Update UI to add this to list if (_scenario2 != nullptr) { _scenario2->AddSession(session); } if (_scenario4 != nullptr) { _scenario4->AddSession(session); } if (_scenario3 != nullptr) { _scenario3->SessionConnected(); } } void WiFiDirectServiceManager::RemoveSession(unsigned int index) { { lock_guard<mutex> lock(_managerMutex); // Invalidate selection _selectedSession = -1; _connectedSessions->RemoveAt(index); } // Update UI to remove from list if (_scenario2 != nullptr) { _scenario2->RemoveSession(index); } if (_scenario4 != nullptr) { _scenario4->RemoveSession(index); } } void WiFiDirectServiceManager::RemoveSession(SessionWrapper^ session) { int index = 0; bool fFound = false; { lock_guard<mutex> lock(_managerMutex); // Lookup the index for (auto&& s : _connectedSessions) { if (s->Session->SessionId == session->Session->SessionId && s->Session->SessionAddress == session->Session->SessionAddress && s->Session->AdvertisementId == session->Session->AdvertisementId && s->Session->ServiceAddress == session->Session->ServiceAddress) { fFound = true; break; } ++index; } } if (fFound) { RemoveSession(index); } else { NotifyUser("Session not found in list", NotifyType::ErrorMessage); } } void WiFiDirectServiceManager::CloseSession(unsigned int index) { SessionWrapper^ session = nullptr; // First remove from list { lock_guard<mutex> lock(_managerMutex); if (index > _connectedSessions->Size - 1) { throw ref new OutOfBoundsException("Attempted to close session not found in list"); } session = _connectedSessions->GetAt(index); // Session will remove self from list when its status changes } // Close session by disposing underlying WiFiDirectServiceSession session->Close(); RootPage->NotifyUser("Closed Session", NotifyType::StatusMessage); } void WiFiDirectServiceManager::SelectSession(unsigned int index) { { lock_guard<mutex> lock(_managerMutex); if (index > _connectedSessions->Size - 1) { throw ref new OutOfBoundsException("Attempted to select session not found in list"); } _selectedSession = index; } } void WiFiDirectServiceManager::AddSocket(SocketWrapper^ socket) { // Update UI to add this to list if (_scenario5 != nullptr) { _scenario5->AddSocket(socket); } } void WiFiDirectServiceManager::AddAdvertiser(AdvertisementWrapper^ advertiser) { { lock_guard<mutex> lock(_managerMutex); _advertisers->Append(advertiser); } // Update UI to add this to list if (_scenario2 != nullptr) { _scenario2->AddAdvertiser(advertiser); } } void WiFiDirectServiceManager::RemoveAdvertiser(unsigned int index) { { lock_guard<mutex> lock(_managerMutex); _advertisers->RemoveAt(index); } // Update UI to add this to list if (_scenario2 != nullptr) { _scenario2->RemoveAdvertiser(index); } }
34.040512
157
0.655121
[ "object", "vector" ]
4ffec37802750fe52d7e59662386c9894f04da5e
28,234
cpp
C++
develop/managers/assetmanager/src/assetmanager.cpp
marcotaranta/thunder
8b9249a1599cfb9bf0187cb653c23257404172be
[ "Apache-2.0" ]
null
null
null
develop/managers/assetmanager/src/assetmanager.cpp
marcotaranta/thunder
8b9249a1599cfb9bf0187cb653c23257404172be
[ "Apache-2.0" ]
null
null
null
develop/managers/assetmanager/src/assetmanager.cpp
marcotaranta/thunder
8b9249a1599cfb9bf0187cb653c23257404172be
[ "Apache-2.0" ]
null
null
null
#include "assetmanager.h" #include <QCoreApplication> #include <QDirIterator> #include <QFileSystemWatcher> #include <QDir> #include <QUuid> #include <QJsonDocument> #include <QJsonObject> #include <QJsonArray> #include <QMetaProperty> #include <QUrl> #include <zlib.h> #include <cstring> #include "config.h" #include <json.h> #include "converters/converter.h" #include "converters/builder.h" #include "components/scene.h" #include "components/actor.h" #include "animconverter.h" #include "textconverter.h" #include "textureconverter.h" #include "shaderbuilder.h" #include "fbxconverter.h" #include "fontconverter.h" #include "prefabconverter.h" #include "effectconverter.h" #include "animationbuilder.h" #include "translatorconverter.h" #include "projectmanager.h" #include "pluginmodel.h" #include "log.h" #define BUFF_SIZE 1024 const QString gCRC("crc"); const QString gGUID("guid"); const QString gEntry(".entry"); const QString gCompany(".company"); const QString gProject(".project"); AssetManager *AssetManager::m_pInstance = nullptr; Q_DECLARE_METATYPE(IConverterSettings *) Object *findObject(const uint32_t uuid, Object *parent) { Object *result = nullptr; for(Object *it : parent->getChildren()) { if(it->uuid() == uuid) { return it; } else { result = findObject(uuid, it); if(result != nullptr) { return result; } } } return result; } AssetManager::AssetManager() : m_pEngine(nullptr) { m_pProjectManager = ProjectManager::instance(); m_pDirWatcher = new QFileSystemWatcher(this); m_pFileWatcher = new QFileSystemWatcher(this); m_pTimer = new QTimer(this); connect(m_pTimer, SIGNAL(timeout()), this, SLOT(onPerform())); } AssetManager::~AssetManager() { foreach(auto it, m_Editors) { delete it; } m_Editors.clear(); } AssetManager *AssetManager::instance() { if(!m_pInstance) { m_pInstance = new AssetManager; } return m_pInstance; } void AssetManager::destroy() { delete m_pInstance; m_pInstance = nullptr; } void AssetManager::init(Engine *engine) { m_pEngine = engine; registerConverter(new AnimConverter()); registerConverter(new AnimationBuilder()); registerConverter(new TextConverter()); registerConverter(new TextureConverter()); registerConverter(new ShaderBuilder()); registerConverter(new FBXConverter()); registerConverter(new FontConverter()); registerConverter(new PrefabConverter()); registerConverter(new EffectConverter()); registerConverter(new TranslatorConverter()); m_Formats["map"] = IConverter::ContentMap; m_Paths["{00000000-0101-0000-0000-000000000000}"] = "Scripts"; m_ContentTypes[MetaType::type<Mesh *>()] = IConverter::ContentMesh; } void AssetManager::rescan() { QStringList paths = m_pDirWatcher->directories(); if(!paths.isEmpty()) { m_pDirWatcher->removePaths(paths); } QString target = m_pProjectManager->targetPath(); QFileInfo info(m_pProjectManager->importPath() + "/" + gIndex); m_pEngine->file()->fsearchPathAdd(qPrintable(m_pProjectManager->importPath()), true); bool force = !target.isEmpty() || !info.exists(); if(target.isEmpty()) { connect(m_pDirWatcher, SIGNAL(directoryChanged(QString)), this, SIGNAL(directoryChanged(QString))); connect(m_pDirWatcher, SIGNAL(directoryChanged(QString)), this, SLOT(onDirectoryChanged(QString))); connect(m_pDirWatcher, SIGNAL(directoryChanged(QString)), this, SLOT(reimport())); connect(m_pFileWatcher, SIGNAL(fileChanged(QString)), this, SIGNAL(fileChanged(QString))); connect(m_pFileWatcher, SIGNAL(fileChanged(QString)), this, SLOT(onFileChanged(QString))); connect(m_pFileWatcher, SIGNAL(fileChanged(QString)), this, SLOT(reimport())); } onDirectoryChanged(m_pProjectManager->resourcePath() + "/engine/materials",force); onDirectoryChanged(m_pProjectManager->resourcePath() + "/engine/textures", force); onDirectoryChanged(m_pProjectManager->resourcePath() + "/engine/meshes", force); #ifndef BUILDER onDirectoryChanged(m_pProjectManager->resourcePath() + "/editor/materials",force); onDirectoryChanged(m_pProjectManager->resourcePath() + "/editor/textures", force); onDirectoryChanged(m_pProjectManager->resourcePath() + "/editor/meshes", force); #endif m_pDirWatcher->addPath(m_pProjectManager->contentPath()); onDirectoryChanged(m_pProjectManager->contentPath(), force); emit directoryChanged(m_pProjectManager->contentPath()); reimport(); cleanupBundle(); } void AssetManager::addEditor(uint8_t type, IAssetEditor *editor) { m_Editors[type] = editor; } QObject *AssetManager::openEditor(const QFileInfo &source) { auto it = m_Editors.find(resourceType(source)); if(it != m_Editors.end()) { IAssetEditor *editor = it.value(); QDir dir(m_pProjectManager->contentPath()); editor->loadAsset(createSettings(dir.absoluteFilePath(source.filePath()))); return dynamic_cast<QObject *>(editor); } return nullptr; } int32_t AssetManager::resourceType(const QFileInfo &source) { QString s = source.completeSuffix().toLower(); auto it = m_Formats.find(s); if(it != m_Formats.end()) { return it.value(); } return IConverter::ContentInvalid; } int32_t AssetManager::assetType(const QString &uuid) { auto it = m_Types.find(uuid); if(it != m_Types.end()) { return it.value(); } return IConverter::ContentInvalid; } int32_t AssetManager::toContentType(int32_t type) { auto it = m_ContentTypes.find(type); if(it != m_ContentTypes.end()) { return it.value(); } return type; } bool AssetManager::pushToImport(const QFileInfo &source) { onFileChanged(source.absoluteFilePath(), true); return true; } bool AssetManager::pushToImport(IConverterSettings *settings) { if(settings) { m_ImportQueue.push_back(settings); } return true; } void AssetManager::reimport() { if(!m_ImportQueue.isEmpty()) { emit importStarted(m_ImportQueue.size(), tr("Importing resources")); m_pTimer->start(10); } else { emit importFinished(); } } bool AssetManager::isOutdated(IConverterSettings *settings) { bool result = true; uint32_t crc = crc32(0L, nullptr, 0); QFile file(settings->source()); if(file.open(QIODevice::ReadOnly)) { char buffer[BUFF_SIZE]; while(!file.atEnd()) { memset(buffer, 0, BUFF_SIZE); file.read(buffer, BUFF_SIZE); crc = crc32(crc, reinterpret_cast<Bytef *>(buffer), BUFF_SIZE); } file.close(); if(settings->crc() == crc) { QFileInfo info(settings->absoluteDestination()); if(settings->type() == IConverter::ContentCode || info.exists()) { result = false; } } settings->setCRC(crc); } return result; } void AssetManager::removeResource(const QFileInfo &source) { QFileInfo src(m_pProjectManager->contentPath() + "/" + source.filePath()); if(src.isDir()) { m_pDirWatcher->removePath(src.absoluteFilePath()); QDir dir(m_pProjectManager->contentPath()); QDirIterator it(src.absoluteFilePath(), QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot); while(it.hasNext()) { removeResource(QFileInfo(dir.relativeFilePath(it.next()))); } QDir().rmdir(src.absoluteFilePath()); return; } else { m_pFileWatcher->removePath(src.absoluteFilePath()); auto guid = m_Guids.find(source.filePath().toStdString()); if(guid != m_Guids.end()) { string uuid = guid->second.toString(); QFile::remove(m_pProjectManager->importPath() + "/" + uuid.c_str()); QFile::remove(m_pProjectManager->iconPath() + "/" + uuid.c_str() + ".png"); auto path = m_Paths.find(guid->second.toString()); if(path != m_Paths.end() && !path->second.toString().empty()) { m_Guids.erase(guid); m_Paths.erase(path); m_Types.remove(uuid.c_str()); } } QFile::remove(src.absoluteFilePath() + gMetaExt); QFile::remove(src.absoluteFilePath()); } dumpBundle(); } void AssetManager::renameResource(const QFileInfo &oldName, const QFileInfo &newName) { if(oldName.filePath() != newName.filePath()) { QFileInfo src(m_pProjectManager->contentPath() + "/" + oldName.filePath()); QFileInfo dst(m_pProjectManager->contentPath() + "/" + newName.filePath()); if(src.isDir()) { QStringList dirs = m_pDirWatcher->directories(); QStringList files = m_pFileWatcher->files(); if(!dirs.isEmpty()) { m_pDirWatcher->removePaths(dirs); m_pDirWatcher->addPaths(dirs.replaceInStrings(src.absoluteFilePath(), dst.absoluteFilePath())); } if(!files.isEmpty()) { m_pFileWatcher->removePaths(files); m_pFileWatcher->addPaths(files.replaceInStrings(src.absoluteFilePath(), dst.absoluteFilePath())); } QDir dir; if(dir.rename(src.absoluteFilePath(), dst.absoluteFilePath())) { QMap<QString, QString> back; for(auto guid = m_Guids.cbegin(); guid != m_Guids.cend();) { QString path = m_pProjectManager->contentPath() + "/" + guid->first.c_str(); if(path.startsWith(src.filePath())) { back[path] = guid->second.toString().c_str(); guid = m_Guids.erase(guid); } else { ++guid; } } QDir dir(m_pProjectManager->contentPath()); QMapIterator<QString, QString> it(back); while(it.hasNext()) { it.next(); QString newPath = it.key(); newPath.replace(src.filePath(), dst.filePath()); newPath = dir.relativeFilePath(newPath); string source = qPrintable(newPath); m_Guids[source] = qPrintable(it.value()); m_Paths[qPrintable(it.value())] = source; } dumpBundle(); } else { if(!dirs.isEmpty()) { m_pDirWatcher->addPaths(dirs); } if(!files.isEmpty()) { m_pFileWatcher->addPaths(files); } } } else { if(QFile::rename(src.absoluteFilePath(), dst.absoluteFilePath()) && QFile::rename(src.absoluteFilePath() + gMetaExt, dst.absoluteFilePath() + gMetaExt)) { auto guid = m_Guids.find(oldName.filePath().toStdString()); if(guid != m_Guids.end()) { string uuid = guid->second.toString(); m_Guids.erase(guid); string source = newName.filePath().toStdString(); m_Guids[source] = uuid; m_Paths[uuid] = source; dumpBundle(); } } } } } void AssetManager::duplicateResource(const QFileInfo &source) { QDir dir(m_pProjectManager->contentPath()); QFileInfo src(m_pProjectManager->contentPath() + "/" + source.filePath()); QString name = src.baseName(); QString path = src.absolutePath() + "/"; QString suff = "." + src.suffix(); findFreeName(name, path, suff); QFileInfo target(src.absoluteFilePath(), path + name + suff); // Source and meta QFile::copy(src.absoluteFilePath(), target.filePath()); QFile::copy(src.absoluteFilePath() + gMetaExt, target.filePath() + gMetaExt); IConverterSettings *settings = createSettings(target); QString guid = settings->destination(); settings->setDestination(qPrintable(QUuid::createUuid().toString())); settings->setAbsoluteDestination(qPrintable(ProjectManager::instance()->importPath() + "/" + settings->destination())); saveSettings(settings); if(settings->type() != IConverter::ContentCode) { string source = dir.relativeFilePath(settings->source()).toStdString(); m_Guids[source] = settings->destination(); m_Paths[settings->destination()] = source; IConverterSettings *s = createSettings(src); m_Types[settings->destination()] = m_Types.value(s->destination()); delete s; } // Icon and resource QFile::copy(m_pProjectManager->iconPath() + "/" + guid, m_pProjectManager->iconPath() + "/" + settings->destination()+ ".png"); QFile::copy(m_pProjectManager->importPath() + "/" + guid, m_pProjectManager->importPath() + "/" + settings->destination()); dumpBundle(); } void AssetManager::makePrefab(const QString &source, const QFileInfo &target) { int index = source.indexOf(':'); QString id = source.left(index); QString name = source.mid(index + 1); Actor *actor = dynamic_cast<Actor *>(findObject(id.toUInt(), m_pEngine->scene())); if(actor) { Actor *prefab = static_cast<Actor *>(actor->clone()); QString path = target.absoluteFilePath() + "/" + name + ".fab"; QFile file(path); if(file.open(QIODevice::WriteOnly)) { string str = Json::save(Engine::toVariant(prefab), 0); file.write(static_cast<const char *>(&str[0]), str.size()); file.close(); IConverterSettings *settings = createSettings(path); saveSettings(settings); if(settings->type() != IConverter::ContentCode) { QDir dir(m_pProjectManager->contentPath()); string source = dir.relativeFilePath(settings->source()).toStdString(); const char *uuid = settings->destination(); m_Guids[source] = uuid; m_Paths[uuid] = source; m_Types[uuid] = settings->type(); string dest = settings->destination(); Engine::setResource(prefab, dest); } dumpBundle(); actor->setPrefab(prefab); } } } bool AssetManager::import(const QFileInfo &source, const QFileInfo &target) { QString name = source.baseName(); QString path; if(!target.isAbsolute()) { path = m_pProjectManager->contentPath() + "/"; } path += target.filePath() + "/"; QString suff = "." + source.suffix(); findFreeName(name, path, suff); return QFile::copy(source.absoluteFilePath(), path + name + suff); } IConverterSettings *AssetManager::createSettings(const QFileInfo &source) { IConverterSettings *settings; uint32_t type = MetaType::INVALID; auto it = m_Converters.find(source.completeSuffix().toLower()); if(it != m_Converters.end()) { type = it.value()->contentType(); settings = it.value()->createSettings(); } else { settings = new IConverterSettings(); type = resourceType(source); } settings->setType(type); settings->setSource(qPrintable(source.absoluteFilePath())); QFile meta(source.absoluteFilePath() + gMetaExt); if(meta.open(QIODevice::ReadOnly)) { QJsonObject object = QJsonDocument::fromJson(meta.readAll()).object(); meta.close(); QObject *obj = dynamic_cast<QObject *>(settings); if(obj) { const QMetaObject *meta = obj->metaObject(); QVariantMap map = object.value(gSettings).toObject().toVariantMap(); for(int32_t index = 0; index < meta->propertyCount(); index++) { QMetaProperty property = meta->property(index); QVariant v = map.value(property.name(), property.read(obj)); v.convert(property.userType()); property.write(obj, v); } } settings->setDestination( qPrintable(object.value(gGUID).toString()) ); settings->setCRC( uint32_t(object.value(gCRC).toInt()) ); QJsonObject sub = object.value(gSubItems).toObject(); foreach(QString it, sub.keys()) { QJsonArray array = sub.value(it).toArray(); settings->setSubItem(it, array.first().toString(), array.last().toInt()); } } else { settings->setDestination( qPrintable(QUuid::createUuid().toString()) ); } settings->setAbsoluteDestination(qPrintable(ProjectManager::instance()->importPath() + "/" + settings->destination())); return settings; } void AssetManager::registerConverter(IConverter *converter) { if(converter) { foreach (QString format, converter->suffixes()) { m_Formats[format.toLower()] = converter->contentType(); m_ContentTypes[converter->type()] = converter->contentType(); m_Converters[format.toLower()] = converter; IBuilder *builder = dynamic_cast<IBuilder *>(converter); if(builder) { m_pBuilders.push_back(builder); } } } } void AssetManager::findFreeName(QString &name, const QString &path, const QString &suff) { QString base = name; uint32_t it = 1; while(QFileInfo(path + QDir::separator() + name + suff).exists()) { name = base + QString::number(it); it++; } } string AssetManager::guidToPath(const string &guid) { auto it = m_Paths.find(guid); if(it != m_Paths.end()) { return it->second.toString(); } return string(); } string AssetManager::pathToGuid(const string &path) { auto it = m_Guids.find(path); if(it != m_Guids.end()) { return it->second.toString(); } return string(); } QImage AssetManager::icon(const QString &path) { QImage icon; if(!icon.load(m_pProjectManager->iconPath() + "/" + pathToGuid(path.toStdString()).c_str() + ".png", "PNG")) { switch(resourceType(path)) { case IConverter::ContentText: case IConverter::ContentTexture: case IConverter::ContentMaterial: case IConverter::ContentMesh: case IConverter::ContentAtlas: break; case IConverter::ContentFont: { icon.load(":/Style/styles/dark/images/ttf.png", "PNG"); } break; case IConverter::ContentAnimation: { icon.load(":/Style/styles/dark/images/anim.png", "PNG"); } break; case IConverter::ContentEffect: { icon.load(":/Style/styles/dark/images/effect.png", "PNG"); } break; case IConverter::ContentSound: { icon.load(":/Style/styles/dark/images/wav.png", "PNG"); } break; case IConverter::ContentCode: { icon.load(":/Style/styles/dark/images/cpp.png", "PNG"); } break; case IConverter::ContentMap: { icon.load(":/Style/styles/dark/images/map.png", "PNG"); } break; case IConverter::ContentPipeline: break; case IConverter::ContentPrefab: { icon.load(":/Style/styles/dark/images/prefab.png", "PNG"); } break; case IConverter::ContentAnimationStateMachine: { icon.load(":/Style/styles/dark/images/actl.png", "PNG"); } break; case IConverter::ContentLocalization: { icon.load(":/Style/styles/dark/images/l10n.png", "PNG"); } break; default: break; } } return icon; } void AssetManager::cleanupBundle() { QDirIterator it(m_pProjectManager->importPath(), QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot, QDirIterator::Subdirectories); while(it.hasNext()) { QFileInfo info(it.next()); if(!info.isDir() && info.fileName() != gIndex && guidToPath(info.fileName().toStdString()).empty()) { QFile::remove(info.absoluteFilePath()); } } dumpBundle(); } void AssetManager::dumpBundle() { QFile file(m_pProjectManager->importPath() + "/" + gIndex); if(file.open(QIODevice::WriteOnly)) { VariantMap root; root[qPrintable(gContent)] = m_Paths; VariantMap settings; settings[qPrintable(gEntry)] = qPrintable(m_pProjectManager->firstMap().path); settings[qPrintable(gCompany)] = qPrintable(m_pProjectManager->projectCompany()); settings[qPrintable(gProject)] = qPrintable(m_pProjectManager->projectName()); root[qPrintable(gSettings)] = settings; string data = Json::save(root, 0); file.write(&data[0], data.size()); file.close(); Engine::reloadBundle(); } } void AssetManager::onPerform() { QDir dir(m_pProjectManager->contentPath()); if(!m_ImportQueue.isEmpty()) { IConverterSettings *settings = m_ImportQueue.takeFirst(); if(!convert(settings)) { QString dst = m_pProjectManager->importPath() + "/" + settings->destination(); dir.mkpath(QFileInfo(dst).absoluteDir().absolutePath()); QFile::copy(settings->source(), dst); QFileInfo info(settings->source()); string source = dir.relativeFilePath(info.absoluteFilePath()).toStdString(); if(!info.absoluteFilePath().contains(dir.absolutePath())) { source = string(".embedded/") + info.fileName().toStdString(); } string guid = settings->destination(); int32_t type = settings->type(); m_Guids[source] = guid; m_Paths[guid] = source; m_Types[guid.c_str()] = type; for(QString it : settings->subKeys()) { string value = settings->subItem(it).toStdString(); int32_t type = settings->subType(it); string path = source + "/" + it.toStdString(); m_Guids[path] = value; m_Paths[value] = path; m_Types[value.c_str()] = type; emit imported(QString::fromStdString(path), type); } emit imported(QString::fromStdString(source), type); saveSettings(settings); } } else { dumpBundle(); if(isOutdated()) { foreach(IBuilder *it, m_pBuilders) { it->rescanSources(ProjectManager::instance()->contentPath()); it->buildProject(); } return; } m_pTimer->stop(); emit importFinished(); } } void AssetManager::onFileChanged(const QString &path, bool force) { QDir dir(m_pProjectManager->contentPath()); QFileInfo info(path); if(info.exists() && (QString(".") + info.suffix()) != gMetaExt) { IConverterSettings *settings = createSettings(info); //settings->setDestination(settings->source()); settings->setType(resourceType(info)); if(force || isOutdated(settings)) { pushToImport(settings); } else { if(settings->type() != IConverter::ContentCode) { string source = dir.relativeFilePath(info.absoluteFilePath()).toStdString(); if(!info.absoluteFilePath().contains(dir.absolutePath())) { source = string(".embedded/") + info.fileName().toStdString(); } string guid = settings->destination(); int32_t type = settings->type(); m_Guids[source] = guid; m_Paths[guid] = source; m_Types[guid.c_str()] = type; for(QString it : settings->subKeys()) { string value = settings->subItem(it).toStdString(); int32_t type = settings->subType(it); string path = source + "/" + it.toStdString(); m_Guids[path] = value; m_Paths[value] = path; m_Types[value.c_str()] = type; } } } } } void AssetManager::onDirectoryChanged(const QString &path, bool force) { QDirIterator it(path, QDir::Files | QDir::Dirs | QDir::NoDotAndDotDot, QDirIterator::Subdirectories); while(it.hasNext()) { QString item = it.next(); QFileInfo info(item); if((QString(".") + info.suffix()) == gMetaExt || info.isDir()) { if(info.isDir()) { m_pDirWatcher->addPath(info.absoluteFilePath()); } continue; } m_pFileWatcher->addPath(info.absoluteFilePath()); onFileChanged(item, force); } } IConverter *AssetManager::getConverter(IConverterSettings *settings) { QFileInfo info(settings->source()); QDir dir(m_pProjectManager->contentPath()); QString format = info.completeSuffix().toLower(); auto it = m_Converters.find(format); if(it != m_Converters.end()) { return it.value(); } return nullptr; } bool AssetManager::convert(IConverterSettings *settings) { QFileInfo info(settings->source()); QDir dir(m_pProjectManager->contentPath()); QString format = info.completeSuffix().toLower(); auto it = m_Converters.find(format); if(it != m_Converters.end()) { Log(Log::INF) << "Converting:" << settings->source(); settings->setType(it.value()->contentType()); if(it.value()->convertFile(settings) == 0) { string source = dir.relativeFilePath(settings->source()).toStdString(); if(!info.absoluteFilePath().contains(dir.absolutePath())) { source = string(".embedded/") + info.fileName().toStdString(); } string guid = settings->destination(); int32_t type = settings->type(); m_Guids[source] = guid; m_Paths[guid] = source; m_Types[guid.c_str()] = type; for(QString it : settings->subKeys()) { string value = settings->subItem(it).toStdString(); int32_t type = settings->subType(it); string path = source + "/" + it.toStdString(); m_Guids[path] = value; m_Paths[value] = path; m_Types[value.c_str()] = type; emit imported(QString::fromStdString(path), type); } emit imported(QString::fromStdString(source), type); saveSettings(settings); return true; } } return false; } void AssetManager::saveSettings(IConverterSettings *settings) { QJsonObject set; QObject *object = dynamic_cast<QObject *>(settings); if(object) { const QMetaObject *meta = object->metaObject(); for(int i = 0; i < meta->propertyCount(); i++) { QMetaProperty property = meta->property(i); if(QString(property.name()) != "objectName") { set.insert(property.name(), QJsonValue::fromVariant(property.read(object))); } } } QJsonObject obj; obj.insert(gCRC, int(settings->crc())); obj.insert(gGUID, settings->destination()); obj.insert(gSettings, set); obj.insert(gType, static_cast<int>(settings->type())); QJsonObject sub; for(QString it : settings->subKeys()) { QJsonArray array; array.push_back(settings->subItem(it)); array.push_back(settings->subType(it)); sub[it] = array; } obj.insert(gSubItems, sub); QFile fp(QString(settings->source()) + gMetaExt); if(fp.open(QIODevice::WriteOnly)) { fp.write(QJsonDocument(obj).toJson(QJsonDocument::Indented)); fp.close(); } } bool AssetManager::isOutdated() const { foreach(IBuilder *it, m_pBuilders) { if(it->isOutdated()) { return true; } } return false; } QString AssetManager::artifact() const { return m_Artifact; } void AssetManager::setArtifact(const QString &value) { m_Artifact = value; }
34.986369
132
0.596657
[ "mesh", "object" ]
4fff98d2028505fdc115130dbc6fd0a3f0352a98
2,627
cpp
C++
devices/MatrixBlock6_ESP32S3/Drivers/LED.cpp
203Electronics/MatrixOS
ea6d84b21a97f58e2077d37d5645c5339f344d77
[ "MIT" ]
8
2021-12-30T05:29:16.000Z
2022-03-30T08:44:45.000Z
devices/MatrixBlock6_ESP32S3/Drivers/LED.cpp
203Electronics/MatrixOS
ea6d84b21a97f58e2077d37d5645c5339f344d77
[ "MIT" ]
null
null
null
devices/MatrixBlock6_ESP32S3/Drivers/LED.cpp
203Electronics/MatrixOS
ea6d84b21a97f58e2077d37d5645c5339f344d77
[ "MIT" ]
null
null
null
#include "Device.h" namespace Device { namespace LED { void Init() { WS2812::Init(RMT_CHANNEL_0, LED_Pin, numsOfLED); } void Update(Color* frameBuffer, uint8_t brightness) //Render LED { // ESP_LOGI("LED", "LED Update"); // ESP_LOGI("LED", "%d", frameBuffer[0].RGB()); WS2812::Show(frameBuffer, brightness); } uint16_t XY2Index(Point xy) { if(xy.x >= 0 && xy.x < 8 && xy.y >= 0 && xy.y < 8) //Main grid { return xy.x + xy.y * 8; } else if(xy.x == 8 && xy.y >= 0 && xy.y < 8) //Underglow Right Column { return 84 + xy.y; } else if(xy.y == 8 && xy.x >= 0 && xy.x < 8) //Underglow Bottom Row { if(xy.x < 4) return 64 + (3 - xy.x); else return 92 + (7 - xy.x); } else if(xy.x == -1 && xy.y >= 0 && xy.y < 8) //Underglow Left Column { return 68 + (7 - xy.y); } else if(xy.y == -1 && xy.x >= 0 && xy.x < 8) //Underglow Top Row { return 76 + xy.x; } return UINT16_MAX; } // Point Index2XY(uint16_t index) // { // if(xy.x >= 0 && xy.x < 8 && xy.y >= 0 && xy.y < 8) //Main grid // { // return xy.x + xy.y * 8; // } // if(index < 64) // { // } // return UINT16_MAX; // } //TODO This text is very wrong (GRID) //Matrix use the following ID Struct // CCCC IIIIIIIIIIII // C as class (4 bits), I as index (12 bits). I could be spilted by the class defination, for example, class 1 (grid), it's spilted to XXXXXXX YYYYYYY. // Class List: // Class 0 - System - IIIIIIIIIIII // Class 1 - Grid - XXXXXX YYYYYY // Class 2 - TouchBar - IIIIIIIIIIII // Class 3 - Underglow - IIIIIIIIIIII uint16_t ID2Index(uint16_t ledID) { uint8_t ledClass = ledID >> 12; switch(ledClass) { case 1: //Main Grid { uint16_t index = ledID & (0b0000111111111111); if(index < 64) return index; break; } case 3: //Underglow break;//TODO: Underglow } return UINT16_MAX; } } }
29.852273
159
0.408451
[ "render" ]
8b0384d817b78e0f0ce12dc91445ef137258fc3d
25,180
cpp
C++
lib/src/chromalightnessdiagram.cpp
sommerluk/perceptualcolorpickertest
8df8055e594239cf967431e70a74e87d7da1f684
[ "BSD-3-Clause", "MIT" ]
null
null
null
lib/src/chromalightnessdiagram.cpp
sommerluk/perceptualcolorpickertest
8df8055e594239cf967431e70a74e87d7da1f684
[ "BSD-3-Clause", "MIT" ]
null
null
null
lib/src/chromalightnessdiagram.cpp
sommerluk/perceptualcolorpickertest
8df8055e594239cf967431e70a74e87d7da1f684
[ "BSD-3-Clause", "MIT" ]
null
null
null
// // SPDX-License-Identifier: MIT /* * Copyright (c) 2020 Lukas Sommer sommerluk@gmail.com * * 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. */ // Own headers // First the interface, which forces the header to be self-contained. #include "chromalightnessdiagram.h" // Second, the private implementation. #include "chromalightnessdiagram_p.h" // IWYU pragma: associated #include "PerceptualColor/abstractdiagram.h" #include "PerceptualColor/constpropagatinguniquepointer.h" #include "PerceptualColor/lchdouble.h" #include "chromalightnessimage.h" #include "constpropagatingrawpointer.h" #include "helper.h" #include "lchvalues.h" #include "rgbcolorspace.h" #include <memory> #include <qevent.h> #include <qimage.h> #include <qmath.h> #include <qnamespace.h> #include <qpainter.h> #include <qpen.h> #include <qpoint.h> #include <qsizepolicy.h> #include <qwidget.h> namespace PerceptualColor { /** @brief The constructor. * * @param colorSpace The color space within which the widget should operate. * Can be created with @ref RgbColorSpaceFactory. * * @param parent Passed to the QWidget base class constructor */ ChromaLightnessDiagram::ChromaLightnessDiagram(const QSharedPointer<PerceptualColor::RgbColorSpace> &colorSpace, QWidget *parent) : AbstractDiagram(parent) , d_pointer(new ChromaLightnessDiagramPrivate(this, colorSpace)) { // Setup the color space must be the first thing to do because // other operations rely on a working color space. d_pointer->m_rgbColorSpace = colorSpace; // Initialization d_pointer->m_currentColor = LchValues::srgbVersatileInitialColor(); setFocusPolicy(Qt::FocusPolicy::StrongFocus); setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); d_pointer->m_chromaLightnessImage.setImageSize( // Update the image size will free memory of the cache immediately. d_pointer->calculateImageSizePhysical()); } /** @brief Default destructor */ ChromaLightnessDiagram::~ChromaLightnessDiagram() noexcept { } /** @brief Constructor * * @param backLink Pointer to the object from which <em>this</em> object * is the private implementation. * @param colorSpace The color space within which this widget should operate. */ ChromaLightnessDiagramPrivate::ChromaLightnessDiagramPrivate(ChromaLightnessDiagram *backLink, const QSharedPointer<PerceptualColor::RgbColorSpace> &colorSpace) : m_chromaLightnessImage(colorSpace) , q_pointer(backLink) { } /** @brief Updates @ref ChromaLightnessDiagram::currentColor corresponding * to the given widget pixel position. * * @param widgetPixelPosition The position of a pixel within the widget’s * coordinate system. This does not necessarily need to intersect with the * actually displayed diagram or the gamut. It might even be negative or * outside the widget. * * @post If the pixel position is within the gamut, then the corresponding * @ref ChromaLightnessDiagram::currentColor is set. If the pixel position * is outside the gamut, than a nearby in-gamut color is set (hue is * preserved, chroma and lightness are adjusted). Exception: If the * widget is so small that no diagram is displayed, nothing will happen. */ void ChromaLightnessDiagramPrivate::setCurrentColorFromWidgetPixelPosition(const QPoint widgetPixelPosition) { const LchDouble color = fromWidgetPixelPositionToColor(widgetPixelPosition); q_pointer->setCurrentColor( // Search for the nearest color without changing the hue: nearestInGamutColorByAdjustingChromaLightness(color.c, color.l)); } /** @brief The border between the widget outer top, right and bottom * border and the diagram itself. * * The diagram is not painted on the whole extend of the widget. * A border is left to allow that the selection handle can be painted * completely even when a pixel on the border of the diagram is * selected. * * This is the value for the top, right and bottom border. For the left * border, see @ref leftBorderPhysical() instead. * * Measured in <em>physical pixels</em>. */ int ChromaLightnessDiagramPrivate::defaultBorderPhysical() const { const qreal border = q_pointer->handleRadius() // + q_pointer->handleOutlineThickness() / 2.0; return qCeil(border * q_pointer->devicePixelRatioF()); } /** @brief The left border between the widget outer left border and the * diagram itself. * * The diagram is not painted on the whole extend of the widget. * A border is left to allow that the selection handle can be painted * completely even when a pixel on the border of the diagram is * selected. Also, there is space left for the focus indicator. * * This is the value for the left border. For the other three borders, * see @ref defaultBorderPhysical() instead. * * Measured in <em>physical pixels</em>. */ int ChromaLightnessDiagramPrivate::leftBorderPhysical() const { const int focusIndicatorThickness = qCeil( // q_pointer->handleOutlineThickness() * q_pointer->devicePixelRatioF()); // Candidate 1: const int candidateOne = defaultBorderPhysical() + focusIndicatorThickness; // Candidate 2: Generally recommended value for focus indicator: const int candidateTwo = qCeil( // q_pointer->spaceForFocusIndicator() * q_pointer->devicePixelRatioF()); return qMax(candidateOne, candidateTwo); } /** @brief Calculate a size for @ref m_chromaLightnessImage that corresponds * to the current widget size. * * @returns The size for @ref m_chromaLightnessImage that corresponds * to the current widget size. Measured in <em>physical pixels</em>. */ QSize ChromaLightnessDiagramPrivate::calculateImageSizePhysical() const { const QSize borderSizePhysical( // Borders: leftBorderPhysical() + defaultBorderPhysical(), // left + right 2 * defaultBorderPhysical() // top + bottom ); return q_pointer->physicalPixelSize() - borderSizePhysical; } /** @brief Converts widget pixel positions to color. * * @param widgetPixelPosition The position of a pixel of the widget * coordinate system. The given value does not necessarily need to * be within the actual displayed widget. It might even be negative. * * @returns The corresponding color for the (center of the) given * widget pixel position. (The value is not normalized. It might have * a negative C value if the position is on the left of the diagram, * or an L value smaller than 0 or bigger than 100…) Exception: If * the widget is too small to show a diagram, a default color is * returned. * * @sa @ref measurementdetails */ LchDouble ChromaLightnessDiagramPrivate::fromWidgetPixelPositionToColor(const QPoint widgetPixelPosition) const { const QPointF offset(leftBorderPhysical(), defaultBorderPhysical()); const QPointF imageCoordinatePoint = widgetPixelPosition // Offset to pass from widget reference system // to image reference system: - offset / q_pointer->devicePixelRatioF() // Offset to pass from pixel positions to coordinate points: + QPointF(0.5, 0.5); LchDouble color; color.h = m_currentColor.h; const qreal diagramHeight = // calculateImageSizePhysical().height() / q_pointer->devicePixelRatioF(); if (diagramHeight > 0) { color.l = imageCoordinatePoint.y() * 100.0 / diagramHeight * (-1.0) + 100.0; color.c = imageCoordinatePoint.x() * 100.0 / diagramHeight; } else { color.l = 50; color.c = 0; } return color; } /** @brief React on a mouse press event. * * Reimplemented from base class. * * Does not differentiate between left, middle and right mouse click. * * If the mouse moves inside the <em>displayed</em> gamut, the handle * is displaced there. If the mouse moves outside the <em>displayed</em> * gamut, the handle is displaced to a nearby in-gamut color. * * @param event The corresponding mouse event * * @internal * * @todo This widget reacts on mouse press events also when they occur * within the border. It might be nice if it would not. On the other * hand: The border is small. Would it really be worth the pain to * implement this? */ void ChromaLightnessDiagram::mousePressEvent(QMouseEvent *event) { d_pointer->m_isMouseEventActive = true; d_pointer->setCurrentColorFromWidgetPixelPosition(event->pos()); if (d_pointer->isWidgetPixelPositionInGamut(event->pos())) { setCursor(Qt::BlankCursor); } else { unsetCursor(); } } /** @brief React on a mouse move event. * * Reimplemented from base class. * * If the mouse moves inside the <em>displayed</em> gamut, the handle * is displaced there. If the mouse moves outside the <em>displayed</em> * gamut, the handle is displaced to a nearby in-gamut color. * * @param event The corresponding mouse event */ void ChromaLightnessDiagram::mouseMoveEvent(QMouseEvent *event) { d_pointer->setCurrentColorFromWidgetPixelPosition(event->pos()); if (d_pointer->isWidgetPixelPositionInGamut(event->pos())) { setCursor(Qt::BlankCursor); } else { unsetCursor(); } } /** @brief React on a mouse release event. * * Reimplemented from base class. Does not differentiate between left, * middle and right mouse click. * * If the mouse moves inside the <em>displayed</em> gamut, the handle * is displaced there. If the mouse moves outside the <em>displayed</em> * gamut, the handle is displaced to a nearby in-gamut color. * * @param event The corresponding mouse event */ void ChromaLightnessDiagram::mouseReleaseEvent(QMouseEvent *event) { d_pointer->setCurrentColorFromWidgetPixelPosition(event->pos()); unsetCursor(); } /** @brief Paint the widget. * * Reimplemented from base class. * * @param event the paint event */ void ChromaLightnessDiagram::paintEvent(QPaintEvent *event) { Q_UNUSED(event) // We do not paint directly on the widget, but on a QImage buffer first: // Render anti-aliased looks better. But as Qt documentation says: // // “Renderhints are used to specify flags to QPainter that may or // may not be respected by any given engine.” // // Painting here directly on the widget might lead to different // anti-aliasing results depending on the underlying window system. This // is especially problematic as anti-aliasing might shift or not a pixel // to the left or to the right. So we paint on a QImage first. As QImage // (at difference to QPixmap and a QWidget) is independent of native // platform rendering, it guarantees identical anti-aliasing results on // all platforms. Here the quote from QPainter class documentation: // // “To get the optimal rendering result using QPainter, you should // use the platform independent QImage as paint device; i.e. using // QImage will ensure that the result has an identical pixel // representation on any platform.” QImage paintBuffer(physicalPixelSize(), QImage::Format_ARGB32_Premultiplied); paintBuffer.fill(Qt::transparent); QPainter painter(&paintBuffer); QPen pen; // Paint the diagram itself as available in the cache. painter.setRenderHint(QPainter::Antialiasing, false); painter.drawImage( // Operating in physical pixels: d_pointer->leftBorderPhysical(), // x position (top-left) d_pointer->defaultBorderPhysical(), // y position (top-left) d_pointer->m_chromaLightnessImage.getImage() // image ); // Paint a focus indicator. // // We could paint a focus indicator (round or rectangular) around the // handle. Depending on the currently selected hue for the diagram, // it looks ugly because the colors of focus indicator and diagram // do not harmonize, or it is mostly invisible the the colors are // similar. So this approach does not work well. // // It seems better to paint a focus indicator for the whole widget. // We could use the style primitives to paint a rectangular focus // indicator around the whole widget: // // style()->drawPrimitive( // QStyle::PE_FrameFocusRect, // &option, // &painter, // this // ); // // However, this does not work well because the chroma-lightness // diagram has usually a triangular shape. The style primitive, however, // often paints just a line at the bottom of the widget. That does not // look good. An alternative approach is that we paint ourselves a focus // indicator only on the left of the diagram (which is the place of // black/gray/white, so the won't be any problems with non-harmonic // colors). // // Then we have to design the line that we want to display. It is better // to do that ourselves instead of relying on generic QStyle::PE_Frame or // similar solutions as their result seems to be quite unpredictable across // various styles. So we use handleOutlineThickness as line width and // paint it at the left-most possible position. if (hasFocus()) { pen = QPen(); pen.setWidthF(handleOutlineThickness() * devicePixelRatioF()); pen.setColor(focusIndicatorColor()); pen.setCapStyle(Qt::PenCapStyle::FlatCap); painter.setPen(pen); painter.setRenderHint(QPainter::Antialiasing, true); const QPointF pointOne( // x: handleOutlineThickness() * devicePixelRatioF() / 2.0, // y: 0 + d_pointer->defaultBorderPhysical()); const QPointF pointTwo( // x: handleOutlineThickness() * devicePixelRatioF() / 2.0, // y: physicalPixelSize().height() - d_pointer->defaultBorderPhysical()); painter.drawLine(pointOne, pointTwo); } // Paint the handle on-the-fly. const int diagramHeight = d_pointer->calculateImageSizePhysical().height(); QPointF colorCoordinatePoint = QPointF( // x: d_pointer->m_currentColor.c * diagramHeight / 100.0, // y: d_pointer->m_currentColor.l * diagramHeight / 100.0 * (-1) + diagramHeight); colorCoordinatePoint += QPointF(d_pointer->leftBorderPhysical(), // horizontal offset d_pointer->defaultBorderPhysical() // vertical offset ); pen = QPen(); pen.setWidthF(handleOutlineThickness() * devicePixelRatioF()); pen.setColor(handleColorFromBackgroundLightness(d_pointer->m_currentColor.l)); painter.setPen(pen); painter.setRenderHint(QPainter::Antialiasing, true); painter.drawEllipse(colorCoordinatePoint, // center handleRadius() * devicePixelRatioF(), // x radius handleRadius() * devicePixelRatioF() // y radius ); // Paint the buffer to the actual widget paintBuffer.setDevicePixelRatio(devicePixelRatioF()); QPainter widgetPainter(this); widgetPainter.setRenderHint(QPainter::Antialiasing, true); widgetPainter.drawImage(0, 0, paintBuffer); } /** @brief React on key press events. * * Reimplemented from base class. * * When the arrow keys are pressed, it moves the * handle a small step into the desired direction. * When <tt>Qt::Key_PageUp</tt>, <tt>Qt::Key_PageDown</tt>, * <tt>Qt::Key_Home</tt> or <tt>Qt::Key_End</tt> are pressed, it moves the * handle a big step into the desired direction. * * Other key events are forwarded to the base class. * * @param event the event * * @internal * * @todo Is the current behaviour (when pressing right arrow while yet * at the right border of the gamut, also the lightness is adjusted to * allow moving actually to the right) really a good idea? Anyway, it * has a bug, and arrow-down does not work on blue hues because the * gamut has some sort of corner, and there, the curser blocks. */ void ChromaLightnessDiagram::keyPressEvent(QKeyEvent *event) { LchDouble temp = d_pointer->m_currentColor; switch (event->key()) { case Qt::Key_Up: temp.l += singleStepLightness; break; case Qt::Key_Down: temp.l -= singleStepLightness; break; case Qt::Key_Left: temp.c = qMax<double>(0, temp.c - singleStepChroma); break; case Qt::Key_Right: temp.c += singleStepChroma; temp = d_pointer->m_rgbColorSpace->reduceChromaToFitIntoGamut(temp); break; case Qt::Key_PageUp: temp.l += pageStepLightness; break; case Qt::Key_PageDown: temp.l -= pageStepLightness; break; case Qt::Key_Home: temp.c += pageStepChroma; temp = d_pointer->m_rgbColorSpace->reduceChromaToFitIntoGamut(temp); break; case Qt::Key_End: temp.c = qMax<double>(0, temp.c - pageStepChroma); break; default: // Quote from Qt documentation: // // “If you reimplement this handler, it is very important that // you call the base class implementation if you do not act // upon the key. // // The default implementation closes popup widgets if the // user presses the key sequence for QKeySequence::Cancel // (typically the Escape key). Otherwise the event is // ignored, so that the widget’s parent can interpret it.“ QWidget::keyPressEvent(event); return; } // Here we reach only if the key has been recognized. If not, in the // default branch of the switch statement, we would have passed the // keyPressEvent yet to the parent and returned. // Set the new color (only takes effect when the color is indeed different). setCurrentColor( // Search for the nearest color without changing the hue: d_pointer->m_rgbColorSpace->reduceChromaToFitIntoGamut(temp)); // TODO Instead of this, simply do setCurrentColor(temp); but guarantee // for up, down, page-up and page-down that the lightness is raised // or reduced until fitting into the gamut. Maybe find a way to share // code with reduceChromaToFitIntoGamut ? } /** @brief Tests if a given widget pixel position is within * the <em>displayed</em> gamut. * * @param widgetPixelPosition The position of a pixel of the widget coordinate * system. The given value does not necessarily need to be within the * actual displayed diagram or even the gamut itself. It might even be * negative. * * @returns <tt>true</tt> if the widget pixel position is within the * <em>currently displayed gamut</em>. Otherwise <tt>false</tt>. * * @internal * * @todo How does isInGamut() react? Does it also control valid chroma * and lightness ranges? */ bool ChromaLightnessDiagramPrivate::isWidgetPixelPositionInGamut(const QPoint widgetPixelPosition) const { if (calculateImageSizePhysical().isEmpty()) { // If there is no displayed gamut, the answer must be false. // But fromWidgetPixelPositionToColor() would return an in-gamut // fallback color nevertheless. Therefore, we have to catch // the special case with an empty diagram here manually. return false; } const LchDouble color = fromWidgetPixelPositionToColor(widgetPixelPosition); // Test if C is in range. This is important because a negative C value // can be in-gamut, but is not in the _displayed_ gamut. if (color.c < 0) { return false; } // Actually for in-gamut color: return m_rgbColorSpace->isInGamut(color); } /** @brief Setter for the @ref currentColor() property. * * @param newCurrentColor the new @ref currentColor * * @todo When an out-of-gamut color is given, both lightness and chroma * are adjusted. But does this really make sense? In @ref WheelColorPicker, * when using the hue wheel, also <em>both</em>, lightness <em>and</em> chroma * will change. Isn’t that confusing? */ void ChromaLightnessDiagram::setCurrentColor(const PerceptualColor::LchDouble &newCurrentColor) { if (newCurrentColor.hasSameCoordinates(d_pointer->m_currentColor)) { return; } double oldHue = d_pointer->m_currentColor.h; d_pointer->m_currentColor = newCurrentColor; if (d_pointer->m_currentColor.h != oldHue) { // Update the diagram (only if the hue has changed): d_pointer->m_chromaLightnessImage.setHue(d_pointer->m_currentColor.h); } update(); // Schedule a paint event Q_EMIT currentColorChanged(newCurrentColor); } /** @brief React on a resize event. * * Reimplemented from base class. * * @param event The corresponding event */ void ChromaLightnessDiagram::resizeEvent(QResizeEvent *event) { Q_UNUSED(event) d_pointer->m_chromaLightnessImage.setImageSize( // Update the image size will free memory of the cache immediately. d_pointer->calculateImageSizePhysical()); // As by Qt documentation: // “The widget will be erased and receive a paint event // immediately after processing the resize event. No drawing // need be (or should be) done inside this handler.” } /** @brief Recommended size for the widget. * * Reimplemented from base class. * * @returns Recommended size for the widget. * * @sa @ref minimumSizeHint() */ QSize ChromaLightnessDiagram::sizeHint() const { return minimumSizeHint() * scaleFromMinumumSizeHintToSizeHint; } /** @brief Recommended minimum size for the widget * * Reimplemented from base class. * * @returns Recommended minimum size for the widget. * * @sa @ref sizeHint() */ QSize ChromaLightnessDiagram::minimumSizeHint() const { const int minimumHeight = qRound( // Top border and bottom border: 2.0 * d_pointer->defaultBorderPhysical() / devicePixelRatioF() // Add the height for the diagram: + gradientMinimumLength()); const int minimumWidth = qRound( // Left border and right border: (d_pointer->leftBorderPhysical() + d_pointer->defaultBorderPhysical()) / devicePixelRatioF() // Add the gradient minimum length from y axis, multiplied with // the factor to allow at correct scaling showing up the whole // chroma range of the gamut. + gradientMinimumLength() * d_pointer->m_rgbColorSpace->profileMaximumChroma() / 100.0); // Expand to the global minimum size for GUI elements return QSize(minimumWidth, minimumHeight); } // No documentation here (documentation of properties // and its getters are in the header) LchDouble PerceptualColor::ChromaLightnessDiagram::currentColor() const { return d_pointer->m_currentColor; } /** @brief Find the nearest in-gamut pixel. * * The hue is assumed to be the current hue at @ref m_currentColor. * Chroma and lightness are sacrificed, but the hue is preserved. This function * works at the precision of the current @ref m_chromaLightnessImage. * * @pre @ref m_chromaLightnessImage has a width and a height ≥ 2. * * @param chroma Chroma of the original color. * * @param lightness Lightness of the original color. * * @returns The nearest in-gamut pixel with the same hue as the original * color. */ PerceptualColor::LchDouble ChromaLightnessDiagramPrivate::nearestInGamutColorByAdjustingChromaLightness(const double chroma, const double lightness) { // Initialization LchDouble temp; temp.l = lightness; temp.c = chroma; temp.h = m_currentColor.h; if (temp.c < 0) { temp.c = 0; } if (m_rgbColorSpace->isInGamut(temp)) { // This is slower than testing for the pixel, but more exact. return temp; } const auto imageHeight = calculateImageSizePhysical().height(); QPoint myPixelPosition( // qRound(temp.c * (imageHeight - 1) / 100.0), qRound(imageHeight - 1 - temp.l * (imageHeight - 1) / 100.0)); m_chromaLightnessImage.setHue(temp.h); myPixelPosition = // m_chromaLightnessImage.nearestInGamutPixelPosition(myPixelPosition); LchDouble result = temp; result.c = myPixelPosition.x() * 100.0 / (imageHeight - 1); result.l = 100 - myPixelPosition.y() * 100.0 / (imageHeight - 1); return result; } } // namespace PerceptualColor
39.34375
160
0.704845
[ "render", "object", "shape" ]
8b04764bc0eb60968f949fdf021aebb860290470
3,257
cc
C++
src/encoder.cc
joshleeb/Huffman
54660f62c6a7adf7dfb63388ed9e4f4e41306058
[ "MIT" ]
null
null
null
src/encoder.cc
joshleeb/Huffman
54660f62c6a7adf7dfb63388ed9e4f4e41306058
[ "MIT" ]
null
null
null
src/encoder.cc
joshleeb/Huffman
54660f62c6a7adf7dfb63388ed9e4f4e41306058
[ "MIT" ]
null
null
null
#include <iostream> #include <unordered_map> #include <vector> #include <gsl/gsl> #include "huffman.h" #include "interface.h" #include "minqueue.h" huffman_encoder::huffman_encoder() { this->encoding = std::unordered_map<char, std::vector<int>>(); this->stats = statistics(); } std::vector<int> huffman_encoder::encode(std::vector<char> buf) { if (buf.empty()) return std::vector<int>(); auto freq = this->count_chars(buf); // Set length of original data for statistics (in bits). this->stats.original = buf.size() * 8; // Push items onto the queue to be sorted by frequency. minqueue* queue = new minqueue(); for (const auto& [value, score] : freq) { queue->push(new minqueue_node(value, score)); } minqueue_node* left; minqueue_node* right; // Combine nodes to form a heap where the root node will be the only node in the queue. while (queue->size() > 1) { left = queue->pop(); right = queue->pop(); minqueue_node* new_node = new minqueue_node(EMPTY_NODE, left->score + right->score); new_node->left = left; new_node->right = right; queue->push(new_node); } minqueue_node* root = queue->pop(); delete queue; this->evaluate(root, std::vector<int>()); std::vector<int> encoded = std::vector<int>(); delete root; for (auto& c : buf) { std::vector<int> encoding = this->encoding[c]; encoded.insert(encoded.end(), encoding.begin(), encoding.end()); } // Set length of encoded data for statistics. Each 0|1 character represents a bit, not a byte. this->stats.modified = encoded.size(); return encoded; } void huffman_encoder::display_encoding() { std::cout << "\n------- Encoding -------\n"; for (const auto& [c, bits] : this->encoding) { std::cout << c << " -> "; for (const auto& bit : bits) { std::cout << std::hex << bit; } std::cout << "\n"; } std::cout << "------------------------\n\n"; } void huffman_encoder::display_stats() { double delta = this->stats.original - this->stats.modified; double percentage = 100 * delta / this->stats.original; std::cout << "\n------ Statistics ------\n"; std::cout << "Original size = " << this->stats.original << " bits\n"; std::cout << "Modified size = " << this->stats.modified << " bits\n"; std::cout << "Space saved = " << percentage << "%\n"; std::cout << "------------------------\n\n"; } std::unordered_map<char, int> huffman_encoder::count_chars(std::vector<char> buf) { std::unordered_map<char, int> freq = {}; for (const auto& c : buf) { if (freq.find(c) == freq.end()) { freq[c] = 0; } freq[c]++; } return freq; } void huffman_encoder::evaluate(minqueue_node* root, std::vector<int> encoding) { if (!root) return; if (root->value != EMPTY_NODE) { this->encoding[root->value] = encoding; } std::vector<int> left_encoding = encoding; left_encoding.push_back(0); std::vector<int> right_encoding = encoding; right_encoding.push_back(1); this->evaluate(root->left, left_encoding); this->evaluate(root->right, right_encoding); }
28.321739
98
0.588885
[ "vector" ]
8b06511135c3b29b02ada6bad951c9ea3ebc70e3
7,984
cc
C++
rtc_stack/myrtc/video/pps_parser.cc
anjisuan783/media_server
443fdbda8a778c7302020ea16f4fb25cd3fd8dae
[ "MIT" ]
9
2022-01-07T03:10:45.000Z
2022-03-31T03:29:02.000Z
src/myrtc/video/pps_parser.cc
maleRjc/rtc_stack
7a94302f59d2e801b84c577ee0b296d8c4407ff8
[ "MIT" ]
16
2021-12-17T08:32:57.000Z
2022-03-10T06:16:14.000Z
rtc_stack/myrtc/video/pps_parser.cc
anjisuan783/media_lib
c09c7d48f495a803df79e39cf837bbcb1320ceb8
[ "MIT" ]
1
2022-02-21T15:47:21.000Z
2022-02-21T15:47:21.000Z
/* * Copyright (c) 2016 The WebRTC 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 in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "video/pps_parser.h" #include <cstdint> #include <vector> #include "video/h264_common.h" #include "rtc_base/bit_buffer.h" #include "rtc_base/checks.h" #define RETURN_EMPTY_ON_FAIL(x) \ if (!(x)) { \ return std::nullopt; \ } namespace { const int kMaxPicInitQpDeltaValue = 25; const int kMinPicInitQpDeltaValue = -26; } // namespace namespace webrtc { // General note: this is based off the 02/2014 version of the H.264 standard. // You can find it on this page: // http://www.itu.int/rec/T-REC-H.264 std::optional<PpsParser::PpsState> PpsParser::ParsePps(const uint8_t* data, size_t length) { // First, parse out rbsp, which is basically the source buffer minus emulation // bytes (the last byte of a 0x00 0x00 0x03 sequence). RBSP is defined in // section 7.3.1 of the H.264 standard. std::vector<uint8_t> unpacked_buffer = H264::ParseRbsp(data, length); rtc::BitBuffer bit_buffer(unpacked_buffer.data(), unpacked_buffer.size()); return ParseInternal(&bit_buffer); } bool PpsParser::ParsePpsIds(const uint8_t* data, size_t length, uint32_t* pps_id, uint32_t* sps_id) { RTC_DCHECK(pps_id); RTC_DCHECK(sps_id); // First, parse out rbsp, which is basically the source buffer minus emulation // bytes (the last byte of a 0x00 0x00 0x03 sequence). RBSP is defined in // section 7.3.1 of the H.264 standard. std::vector<uint8_t> unpacked_buffer = H264::ParseRbsp(data, length); rtc::BitBuffer bit_buffer(unpacked_buffer.data(), unpacked_buffer.size()); return ParsePpsIdsInternal(&bit_buffer, pps_id, sps_id); } std::optional<uint32_t> PpsParser::ParsePpsIdFromSlice(const uint8_t* data, size_t length) { std::vector<uint8_t> unpacked_buffer = H264::ParseRbsp(data, length); rtc::BitBuffer slice_reader(unpacked_buffer.data(), unpacked_buffer.size()); uint32_t golomb_tmp; // first_mb_in_slice: ue(v) if (!slice_reader.ReadExponentialGolomb(&golomb_tmp)) return std::nullopt; // slice_type: ue(v) if (!slice_reader.ReadExponentialGolomb(&golomb_tmp)) return std::nullopt; // pic_parameter_set_id: ue(v) uint32_t slice_pps_id; if (!slice_reader.ReadExponentialGolomb(&slice_pps_id)) return std::nullopt; return slice_pps_id; } std::optional<PpsParser::PpsState> PpsParser::ParseInternal( rtc::BitBuffer* bit_buffer) { PpsState pps; RETURN_EMPTY_ON_FAIL(ParsePpsIdsInternal(bit_buffer, &pps.id, &pps.sps_id)); uint32_t bits_tmp; uint32_t golomb_ignored; // entropy_coding_mode_flag: u(1) uint32_t entropy_coding_mode_flag; RETURN_EMPTY_ON_FAIL(bit_buffer->ReadBits(&entropy_coding_mode_flag, 1)); pps.entropy_coding_mode_flag = entropy_coding_mode_flag != 0; // bottom_field_pic_order_in_frame_present_flag: u(1) uint32_t bottom_field_pic_order_in_frame_present_flag; RETURN_EMPTY_ON_FAIL( bit_buffer->ReadBits(&bottom_field_pic_order_in_frame_present_flag, 1)); pps.bottom_field_pic_order_in_frame_present_flag = bottom_field_pic_order_in_frame_present_flag != 0; // num_slice_groups_minus1: ue(v) uint32_t num_slice_groups_minus1; RETURN_EMPTY_ON_FAIL( bit_buffer->ReadExponentialGolomb(&num_slice_groups_minus1)); if (num_slice_groups_minus1 > 0) { uint32_t slice_group_map_type; // slice_group_map_type: ue(v) RETURN_EMPTY_ON_FAIL( bit_buffer->ReadExponentialGolomb(&slice_group_map_type)); if (slice_group_map_type == 0) { for (uint32_t i_group = 0; i_group <= num_slice_groups_minus1; ++i_group) { // run_length_minus1[iGroup]: ue(v) RETURN_EMPTY_ON_FAIL( bit_buffer->ReadExponentialGolomb(&golomb_ignored)); } } else if (slice_group_map_type == 1) { // TODO(sprang): Implement support for dispersed slice group map type. // See 8.2.2.2 Specification for dispersed slice group map type. } else if (slice_group_map_type == 2) { for (uint32_t i_group = 0; i_group <= num_slice_groups_minus1; ++i_group) { // top_left[iGroup]: ue(v) RETURN_EMPTY_ON_FAIL( bit_buffer->ReadExponentialGolomb(&golomb_ignored)); // bottom_right[iGroup]: ue(v) RETURN_EMPTY_ON_FAIL( bit_buffer->ReadExponentialGolomb(&golomb_ignored)); } } else if (slice_group_map_type == 3 || slice_group_map_type == 4 || slice_group_map_type == 5) { // slice_group_change_direction_flag: u(1) RETURN_EMPTY_ON_FAIL(bit_buffer->ReadBits(&bits_tmp, 1)); // slice_group_change_rate_minus1: ue(v) RETURN_EMPTY_ON_FAIL(bit_buffer->ReadExponentialGolomb(&golomb_ignored)); } else if (slice_group_map_type == 6) { // pic_size_in_map_units_minus1: ue(v) uint32_t pic_size_in_map_units_minus1; RETURN_EMPTY_ON_FAIL( bit_buffer->ReadExponentialGolomb(&pic_size_in_map_units_minus1)); uint32_t slice_group_id_bits = 0; uint32_t num_slice_groups = num_slice_groups_minus1 + 1; // If num_slice_groups is not a power of two an additional bit is required // to account for the ceil() of log2() below. if ((num_slice_groups & (num_slice_groups - 1)) != 0) ++slice_group_id_bits; while (num_slice_groups > 0) { num_slice_groups >>= 1; ++slice_group_id_bits; } for (uint32_t i = 0; i <= pic_size_in_map_units_minus1; i++) { // slice_group_id[i]: u(v) // Represented by ceil(log2(num_slice_groups_minus1 + 1)) bits. RETURN_EMPTY_ON_FAIL( bit_buffer->ReadBits(&bits_tmp, slice_group_id_bits)); } } } // num_ref_idx_l0_default_active_minus1: ue(v) RETURN_EMPTY_ON_FAIL(bit_buffer->ReadExponentialGolomb(&golomb_ignored)); // num_ref_idx_l1_default_active_minus1: ue(v) RETURN_EMPTY_ON_FAIL(bit_buffer->ReadExponentialGolomb(&golomb_ignored)); // weighted_pred_flag: u(1) uint32_t weighted_pred_flag; RETURN_EMPTY_ON_FAIL(bit_buffer->ReadBits(&weighted_pred_flag, 1)); pps.weighted_pred_flag = weighted_pred_flag != 0; // weighted_bipred_idc: u(2) RETURN_EMPTY_ON_FAIL(bit_buffer->ReadBits(&pps.weighted_bipred_idc, 2)); // pic_init_qp_minus26: se(v) RETURN_EMPTY_ON_FAIL( bit_buffer->ReadSignedExponentialGolomb(&pps.pic_init_qp_minus26)); // Sanity-check parsed value if (pps.pic_init_qp_minus26 > kMaxPicInitQpDeltaValue || pps.pic_init_qp_minus26 < kMinPicInitQpDeltaValue) { RETURN_EMPTY_ON_FAIL(false); } // pic_init_qs_minus26: se(v) RETURN_EMPTY_ON_FAIL(bit_buffer->ReadExponentialGolomb(&golomb_ignored)); // chroma_qp_index_offset: se(v) RETURN_EMPTY_ON_FAIL(bit_buffer->ReadExponentialGolomb(&golomb_ignored)); // deblocking_filter_control_present_flag: u(1) // constrained_intra_pred_flag: u(1) RETURN_EMPTY_ON_FAIL(bit_buffer->ReadBits(&bits_tmp, 2)); // redundant_pic_cnt_present_flag: u(1) RETURN_EMPTY_ON_FAIL( bit_buffer->ReadBits(&pps.redundant_pic_cnt_present_flag, 1)); return pps; } bool PpsParser::ParsePpsIdsInternal(rtc::BitBuffer* bit_buffer, uint32_t* pps_id, uint32_t* sps_id) { // pic_parameter_set_id: ue(v) if (!bit_buffer->ReadExponentialGolomb(pps_id)) return false; // seq_parameter_set_id: ue(v) if (!bit_buffer->ReadExponentialGolomb(sps_id)) return false; return true; } } // namespace webrtc
39.524752
80
0.701904
[ "vector" ]
8b06a8a55515042bd64aa904b9af793283a76bd4
22,734
cpp
C++
ogsr_engine/Layers/xrRender/SkeletonCustom.cpp
LVutner/OGSR-Engine
fea725c29e1a1b3e72295e1419c124097ed98dfd
[ "Apache-2.0" ]
3
2018-07-04T07:35:05.000Z
2020-02-11T03:07:16.000Z
ogsr_engine/Layers/xrRender/SkeletonCustom.cpp
LVutner/OGSR-Engine
fea725c29e1a1b3e72295e1419c124097ed98dfd
[ "Apache-2.0" ]
null
null
null
ogsr_engine/Layers/xrRender/SkeletonCustom.cpp
LVutner/OGSR-Engine
fea725c29e1a1b3e72295e1419c124097ed98dfd
[ "Apache-2.0" ]
1
2019-10-16T19:26:08.000Z
2019-10-16T19:26:08.000Z
#include "stdafx.h" #include "SkeletonCustom.h" #include "SkeletonX.h" #include "../../xr_3da/fmesh.h" #include "../../xr_3da/Render.h" #include "../../COMMON_AI/smart_cast.h" int psSkeletonUpdate = 32; ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// bool pred_N(const std::pair<shared_str,u32>& N, LPCSTR B) { return xr_strcmp(*N.first,B)<0; } u16 CKinematics::LL_BoneID (LPCSTR B) { accel::iterator I = std::lower_bound (bone_map_N->begin(),bone_map_N->end(),B,pred_N); if (I == bone_map_N->end()) return BI_NONE; if (0 != xr_strcmp(*(I->first),B)) return BI_NONE; return u16(I->second); } bool pred_P(const std::pair<shared_str,u32>& N, const shared_str& B) { return N.first._get() < B._get(); } u16 CKinematics::LL_BoneID (const shared_str& B) { accel::iterator I = std::lower_bound (bone_map_P->begin(),bone_map_P->end(),B,pred_P); if (I == bone_map_P->end()) return BI_NONE; if (I->first._get() != B._get() ) return BI_NONE; return u16(I->second); } // LPCSTR CKinematics::LL_BoneName_dbg (u16 ID) { CKinematics::accel::iterator _I, _E=bone_map_N->end(); for (_I = bone_map_N->begin(); _I!=_E; ++_I) if (_I->second==ID) return *_I->first; return 0; } #ifdef DEBUG void CKinematics::DebugRender(Fmatrix& XFORM) { CalculateBones (); CBoneData::BoneDebug dbgLines; (*bones)[iRoot]->DebugQuery (dbgLines); Fvector Z; Z.set(0,0,0); Fvector H1; H1.set(0.01f,0.01f,0.01f); Fvector H2; H2.mul(H1,2); for (u32 i=0; i<dbgLines.size(); i+=2) { Fmatrix& M1 = bone_instances[dbgLines[i]].mTransform; Fmatrix& M2 = bone_instances[dbgLines[i+1]].mTransform; Fvector P1,P2; M1.transform_tiny(P1,Z); M2.transform_tiny(P2,Z); RCache.dbg_DrawLINE(XFORM,P1,P2,D3DCOLOR_XRGB(0,255,0)); Fmatrix M; M.mul_43(XFORM,M2); RCache.dbg_DrawOBB(M,H1,D3DCOLOR_XRGB(255,255,255)); RCache.dbg_DrawOBB(M,H2,D3DCOLOR_XRGB(255,255,255)); } for (u32 b=0; b<bones->size(); b++) { Fobb& obb = (*bones)[b]->obb; Fmatrix& Mbone = bone_instances[b].mTransform; Fmatrix Mbox; obb.xform_get(Mbox); Fmatrix X; X.mul(Mbone,Mbox); Fmatrix W; W.mul(XFORM,X); RCache.dbg_DrawOBB(W,obb.m_halfsize,D3DCOLOR_XRGB(0,0,255)); } } #endif CKinematics::CKinematics() { #ifdef DEBUG dbg_single_use_marker = FALSE; #endif m_is_original_lod = false; } CKinematics::~CKinematics () { IBoneInstances_Destroy (); // wallmarks ClearWallmarks (); if(m_lod) { if ( CKinematics* lod_kinematics = dynamic_cast<CKinematics*>(m_lod) ) { if ( lod_kinematics->m_is_original_lod ) { lod_kinematics->Release(); } } xr_delete(m_lod); } } void CKinematics::IBoneInstances_Create() { // VERIFY2 (bones->size() < 64, "More than 64 bones is a crazy thing!"); u32 size = bones->size(); bone_instances =xr_alloc<CBoneInstance>(size); for (u32 i=0; i<size; i++) bone_instances[i].construct(); } void CKinematics::IBoneInstances_Destroy() { if (bone_instances) { xr_free(bone_instances); bone_instances = NULL; } } bool pred_sort_N(const std::pair<shared_str,u32>& A, const std::pair<shared_str,u32>& B) { return xr_strcmp(A.first,B.first)<0; } bool pred_sort_P(const std::pair<shared_str,u32>& A, const std::pair<shared_str,u32>& B) { return A.first._get() < B.first._get(); } CSkeletonX* CKinematics::LL_GetChild (u32 idx) { IRenderVisual* V = children[idx]; CSkeletonX* B = dynamic_cast<CSkeletonX*>(V); return B ; } void CKinematics::Load(const char* N, IReader *data, u32 dwFlags) { //Msg ("skeleton: %s",N); inherited::Load (N, data, dwFlags); pUserData = NULL; m_lod = NULL; // loading lods IReader* LD = data->open_chunk(OGF_S_LODS); if (LD) { // From stream { string_path lod_name; LD->r_string (lod_name, sizeof(lod_name)); //. strconcat (sizeof(name_load),name_load, short_name, ":lod:", lod_name.c_str()); m_lod = (dxRender_Visual*) ::Render->model_CreateChild(lod_name, NULL); if ( CKinematics* lod_kinematics = dynamic_cast<CKinematics*>(m_lod) ) { lod_kinematics->m_is_original_lod = true; } VERIFY3(m_lod,"Cant create LOD model for", N); //. VERIFY2 (m_lod->Type==MT_HIERRARHY || m_lod->Type==MT_PROGRESSIVE || m_lod->Type==MT_NORMAL,lod_name.c_str()); /* strconcat (name_load, short_name, ":lod:1"); m_lod = ::Render->model_CreateChild(name_load,LD); VERIFY (m_lod->Type==MT_SKELETON_GEOMDEF_PM || m_lod->Type==MT_SKELETON_GEOMDEF_ST); */ } LD->close (); } string_path ini_path; strcpy_s(ini_path, N); if (strext(ini_path)) *strext(ini_path) = 0; strcat_s(ini_path, ".ltx"); // try to read custom user data for module from ltx file IReader* UD = FS.r_open("$game_meshes$", ini_path); pUserData = UD ? xr_new<CInifile>(UD, FS.get_path("$game_config$")->m_Path) : nullptr; if (UD) UD->close(); // read user data from model if no custom found if (!pUserData) { // User data UD = data->open_chunk(OGF_S_USERDATA); pUserData = UD ? xr_new<CInifile>(UD, FS.get_path("$game_config$")->m_Path) : nullptr; if (UD) UD->close(); } // Globals bone_map_N = xr_new<accel> (); bone_map_P = xr_new<accel> (); bones = xr_new<vecBones> (); bone_instances = NULL; // Load bones #pragma todo("container is created in stack!") xr_vector<shared_str> L_parents; R_ASSERT (data->find_chunk(OGF_S_BONE_NAMES)); visimask.zero (); int dwCount = data->r_u32(); // Msg ("!!! %d bones",dwCount); // if (dwCount >= 64) Msg ("!!! More than 64 bones is a crazy thing! (%d), %s",dwCount,N); VERIFY3 (dwCount <= 64, "More than 64 bones is a crazy thing!",N); for (; dwCount; dwCount--) { string256 buf; // Bone u16 ID = u16(bones->size()); data->r_stringZ (buf,sizeof(buf)); strlwr(buf); CBoneData* pBone = CreateBoneData(ID); pBone->name = shared_str(buf); pBone->child_faces.resize (children.size()); bones->push_back (pBone); bone_map_N->push_back (mk_pair(pBone->name,ID)); bone_map_P->push_back (mk_pair(pBone->name,ID)); // It's parent data->r_stringZ (buf,sizeof(buf)); strlwr(buf); L_parents.push_back (buf); data->r (&pBone->obb,sizeof(Fobb)); visimask.set(ID, true); } std::sort (bone_map_N->begin(),bone_map_N->end(),pred_sort_N); std::sort (bone_map_P->begin(),bone_map_P->end(),pred_sort_P); // Attach bones to their parents iRoot = BI_NONE; for (u32 i=0; i<bones->size(); i++) { shared_str P = L_parents[i]; CBoneData* B = (*bones)[i]; if (!P||!P[0]) { // no parent - this is root bone R_ASSERT (BI_NONE==iRoot); iRoot = u16(i); B->SetParentID(BI_NONE); continue; } else { u16 ID = LL_BoneID(P); R_ASSERT (ID!=BI_NONE); (*bones)[ID]->children.push_back(B); B->SetParentID(ID); } } R_ASSERT (BI_NONE != iRoot); // Free parents L_parents.clear(); // IK data IReader* IKD = data->open_chunk(OGF_S_IKDATA); if (IKD){ bool fix_cop_joints = pUserData ? READ_IF_EXISTS(pUserData, r_bool, "compat", "fix_cop_joints", false) : false; for (u32 i=0; i<bones->size(); i++) { CBoneData* B = (*bones)[i]; u16 vers = (u16)IKD->r_u32(); IKD->r_stringZ (B->game_mtl_name); IKD->r (&B->shape,sizeof(SBoneShape)); B->IK_data.Import(*IKD,vers); Fvector vXYZ,vT; IKD->r_fvector3 (vXYZ); IKD->r_fvector3 (vT); B->bind_transform.setXYZi(vXYZ); B->bind_transform.translate_over(vT); B->mass = IKD->r_float(); IKD->r_fvector3 (B->center_of_mass); if (fix_cop_joints) { // https://bitbucket.org/stalker/xray_re-tools/commits/209b9014129ceeb7d92375a77f60835553266bf1 for (auto& it : B->IK_data.limits) { Fvector2 vec = it.limit; float tmp = vec.x; it.limit.x = -vec.y; it.limit.y = -tmp; } } } // calculate model to bone converting matrix (*bones)[LL_GetBoneRoot()]->CalculateM2B(Fidentity); IKD->close(); } // after load process { for (u16 child_idx=0; child_idx<(u16)children.size(); child_idx++) LL_GetChild(child_idx)->AfterLoad (this,child_idx); } // unique bone faces { for (u32 bone_idx=0; bone_idx<bones->size(); bone_idx++) { CBoneData* B = (*bones)[bone_idx]; for (u32 child_idx=0; child_idx<children.size(); child_idx++){ CBoneData::FacesVec faces = B->child_faces[child_idx]; std::sort (faces.begin(),faces.end()); CBoneData::FacesVecIt new_end = std::unique(faces.begin(),faces.end()); faces.erase (new_end,faces.end()); B->child_faces[child_idx].clear_and_free(); B->child_faces[child_idx] = faces; } } } // reset update_callback Update_Callback = NULL; // reset update frame wm_frame = u32(-1); LL_Validate (); } IC void iBuildGroups(CBoneData* B, U16Vec& tgt, u16 id, u16& last_id) { if (B->IK_data.ik_flags.is(SJointIKData::flBreakable)) id = ++last_id; tgt[B->GetSelfID()] = id; for (xr_vector<CBoneData*>::iterator bone_it=B->children.begin(); bone_it!=B->children.end(); bone_it++) iBuildGroups (*bone_it,tgt,id,last_id); } void CKinematics::LL_Validate() { // check breakable BOOL bCheckBreakable = FALSE; for (u16 k=0; k<LL_BoneCount(); k++){ if (LL_GetData(k).IK_data.ik_flags.is(SJointIKData::flBreakable)&&(LL_GetData(k).IK_data.type!=jtNone)) { bCheckBreakable = TRUE; break; } } if (bCheckBreakable){ BOOL bValidBreakable = TRUE; #pragma todo("container is created in stack!") xr_vector<xr_vector<u16> > groups; LL_GetBoneGroups (groups); #pragma todo("container is created in stack!") xr_vector<u16> b_parts(LL_BoneCount(),BI_NONE); CBoneData* root = &LL_GetData(LL_GetBoneRoot()); u16 last_id = 0; iBuildGroups (root,b_parts,0,last_id); for (u16 g=0; g<(u16)groups.size(); ++g){ xr_vector<u16>& group = groups[g]; u16 bp_id = b_parts[group[0]]; for (u32 b=1; b<groups[g].size(); b++) if (bp_id!=b_parts[groups[g][b]]){ bValidBreakable = FALSE; break; } } if (bValidBreakable==FALSE){ for (u16 k=0; k<LL_BoneCount(); k++){ CBoneData& BD = LL_GetData(k); if (BD.IK_data.ik_flags.is(SJointIKData::flBreakable)) BD.IK_data.ik_flags.set(SJointIKData::flBreakable,FALSE); } #ifdef DEBUG Msg ("! ERROR: Invalid breakable object: '%s'",*dbg_name); #endif } } } void CKinematics::Copy(dxRender_Visual *P) { inherited::Copy (P); CKinematics* pFrom = dynamic_cast<CKinematics*>(P); VERIFY(pFrom); pUserData = pFrom->pUserData; bones = pFrom->bones; iRoot = pFrom->iRoot; bone_map_N = pFrom->bone_map_N; bone_map_P = pFrom->bone_map_P; visimask = pFrom->visimask; IBoneInstances_Create (); for (u32 i=0; i<children.size(); i++) LL_GetChild(i)->SetParent(this); CalculateBones_Invalidate (); m_lod = (pFrom->m_lod)?(dxRender_Visual*)::Render->model_Duplicate (pFrom->m_lod):0; } void CKinematics::CalculateBones_Invalidate () { UCalc_Time = 0x0; UCalc_Visibox = psSkeletonUpdate; } void CKinematics::Spawn () { inherited::Spawn (); // bones for (u32 i=0; i<bones->size(); i++) bone_instances[i].construct(); Update_Callback = NULL; CalculateBones_Invalidate (); // wallmarks ClearWallmarks (); Visibility_Invalidate (); LL_SetBoneRoot( 0 ); } void CKinematics::Depart () { inherited::Depart (); // wallmarks ClearWallmarks (); // unmask all bones visimask.zero (); if (bones) { for (u16 b = 0; b < bones->size(); b++) visimask.set(b, true); } // visibility children.insert (children.end(),children_invisible.begin(),children_invisible.end()); children_invisible.clear (); } void CKinematics::Release () { // xr_free bones for (u32 i=0; i<bones->size(); i++) { CBoneData* &B = (*bones)[i]; xr_delete(B); } // destroy shared data xr_delete(pUserData ); xr_delete(bones ); xr_delete(bone_map_N); xr_delete(bone_map_P); inherited::Release(); } void CKinematics::LL_SetBoneVisible(u16 bone_id, BOOL val, BOOL bRecursive) { VERIFY (bone_id<LL_BoneCount()); visimask.set(bone_id, !!val); if (!visimask.is(bone_id)) { bone_instances[bone_id].mTransform.scale(0.f,0.f,0.f); }else{ CalculateBones_Invalidate (); } bone_instances[bone_id].mRenderTransform.mul_43(bone_instances[bone_id].mTransform,(*bones)[bone_id]->m2b_transform); if (bRecursive) { for (xr_vector<CBoneData*>::iterator C=(*bones)[bone_id]->children.begin(); C!=(*bones)[bone_id]->children.end(); C++) LL_SetBoneVisible((*C)->GetSelfID(),val,bRecursive); } Visibility_Invalidate (); } void CKinematics::LL_SetBonesVisible(VisMask mask) { visimask.zero(); for (u16 b = 0; b < bones->size(); b++) { if (mask.is(b)) { visimask.set(b, true); } else { Fmatrix& A = bone_instances[b].mTransform; Fmatrix& B = bone_instances[b].mRenderTransform; A.scale(0.f, 0.f, 0.f); B.mul_43(A, (*bones)[b]->m2b_transform); } } CalculateBones_Invalidate(); Visibility_Invalidate(); } void CKinematics::Visibility_Update () { Update_Visibility = FALSE ; // check visible for (u32 c_it=0; c_it<children.size(); c_it++) { CSkeletonX* _c = dynamic_cast<CSkeletonX*> (children[c_it]); VERIFY (_c) ; if (!_c->has_visible_bones()) { // move into invisible list children_invisible.push_back (children[c_it]); swap(children[c_it],children.back()); children.pop_back (); Update_Visibility = TRUE; } } // check invisible for (u32 _it=0; _it<children_invisible.size(); _it++) { CSkeletonX* _c = dynamic_cast<CSkeletonX*> (children_invisible[_it]); VERIFY (_c) ; if (_c->has_visible_bones()) { // move into visible list children.push_back (children_invisible[_it]); swap(children_invisible[_it],children_invisible.back()); children_invisible.pop_back (); Update_Visibility = TRUE; } } } IC static void RecursiveBindTransform(CKinematics* K, xr_vector<Fmatrix>& matrices, u16 bone_id, const Fmatrix& parent) { CBoneData& BD = K->LL_GetData (bone_id); Fmatrix& BM = matrices[bone_id]; // Build matrix BM.mul_43 (parent,BD.bind_transform); for (xr_vector<CBoneData*>::iterator C=BD.children.begin(); C!=BD.children.end(); C++) RecursiveBindTransform(K,matrices,(*C)->GetSelfID(),BM); } void CKinematics::LL_GetBindTransform(xr_vector<Fmatrix>& matrices) { matrices.resize (LL_BoneCount()); RecursiveBindTransform (this,matrices,iRoot,Fidentity); } void BuildMatrix (Fmatrix &mView, float invsz, const Fvector norm, const Fvector& from) { // build projection Fmatrix mScale; Fvector at,up,right,y; at.sub (from,norm); y.set (0,1,0); if (_abs(norm.y)>.99f) y.set(1,0,0); right.crossproduct (y,norm); up.crossproduct (norm,right); mView.build_camera (from,at,up); mScale.scale (invsz,invsz,invsz); mView.mulA_43 (mScale); } void CKinematics::EnumBoneVertices (SEnumVerticesCallback &C, u16 bone_id) { for ( u32 i=0; i<children.size(); i++ ) LL_GetChild( i )->EnumBoneVertices( C, bone_id ); } #include "cl_intersect.h" DEFINE_VECTOR(Fobb,OBBVec,OBBVecIt); bool CKinematics:: PickBone (const Fmatrix &parent_xform, IKinematics::pick_result &r, float dist, const Fvector& start, const Fvector& dir, u16 bone_id) { Fvector S,D;//normal = {0,0,0} // transform ray from world to model Fmatrix P; P.invert (parent_xform); P.transform_tiny (S,start); P.transform_dir (D,dir); for (u32 i=0; i<children.size(); i++) if (LL_GetChild(i)->PickBone(r,dist,S,D,bone_id)) { parent_xform.transform_dir (r.normal); parent_xform.transform_tiny (r.tri[0]); parent_xform.transform_tiny (r.tri[1]); parent_xform.transform_tiny (r.tri[2]); return true; } return false; } void CKinematics::AddWallmark(const Fmatrix* parent_xform, const Fvector3& start, const Fvector3& dir, ref_shader shader, float size) { Fvector S,D,normal = {0,0,0}; // transform ray from world to model Fmatrix P; P.invert (*parent_xform); P.transform_tiny (S,start); P.transform_dir (D,dir); // find pick point float dist = flt_max; BOOL picked = FALSE; DEFINE_VECTOR (Fobb,OBBVec,OBBVecIt); OBBVec cache_obb; cache_obb.resize (LL_BoneCount()); IKinematics::pick_result r;r.normal = normal; r.dist = dist; for (u16 k=0; k<LL_BoneCount(); k++){ CBoneData& BD = LL_GetData(k); if (LL_GetBoneVisible(k)&&!BD.shape.flags.is(SBoneShape::sfNoPickable)){ Fobb& obb = cache_obb[k]; obb.transform (BD.obb,LL_GetBoneInstance(k).mTransform); if (CDB::TestRayOBB(S,D, obb)) for (u32 i=0; i<children.size(); i++) { if (LL_GetChild(i)->PickBone(r,dist,S,D,k)) { picked=TRUE; dist = r.dist; normal = r.normal; //dynamics set wallmarks bug fix } } } } if (!picked) return; // calculate contact point Fvector cp; cp.mad (S,D,dist); // collect collide boxes Fsphere test_sphere; test_sphere.set (cp,size); U16Vec test_bones; test_bones.reserve (LL_BoneCount()); for (u16 k=0; k<LL_BoneCount(); k++){ CBoneData& BD = LL_GetData(k); if (LL_GetBoneVisible(k)&&!BD.shape.flags.is(SBoneShape::sfNoPickable)){ Fobb& obb = cache_obb[k]; if (CDB::TestSphereOBB(test_sphere, obb)) test_bones.push_back(k); } } // find similar wm for (u32 wm_idx=0; wm_idx<wallmarks.size(); wm_idx++){ intrusive_ptr<CSkeletonWallmark>& wm = wallmarks[wm_idx]; if (wm->Similar(shader,cp,0.02f)){ if (wm_idx<wallmarks.size()-1) wm = wallmarks.back(); wallmarks.pop_back(); break; } } // ok. allocate wallmark intrusive_ptr<CSkeletonWallmark> wm = xr_new<CSkeletonWallmark>(this,parent_xform,shader,cp,RDEVICE.fTimeGlobal); wm->m_LocalBounds.set (cp,size*2.f); wm->XFORM()->transform_tiny (wm->m_Bounds.P,cp); wm->m_Bounds.R = wm->m_LocalBounds.R; Fvector tmp; tmp.invert (D); normal.add(tmp).normalize (); // build UV projection matrix Fmatrix mView,mRot; BuildMatrix (mView,1/(0.9f*size),normal,cp); mRot.rotateZ (::Random.randF(deg2rad(-20.f),deg2rad(20.f))); mView.mulA_43 (mRot); // fill vertices for (u32 i=0; i<children.size(); i++){ CSkeletonX* S = LL_GetChild(i); for (U16It b_it=test_bones.begin(); b_it!=test_bones.end(); b_it++) S->FillVertices (mView,*wm,normal,size,*b_it); } wallmarks.push_back (wm); } void CKinematics::CalculateWallmarks() { if (!wallmarks.empty()&&(wm_frame!=RDEVICE.dwFrame)){ wm_frame = RDEVICE.dwFrame; bool need_remove = false; for (SkeletonWMVecIt it=wallmarks.begin(); it!=wallmarks.end(); it++){ intrusive_ptr<CSkeletonWallmark>& wm = *it; float w = (RDEVICE.fTimeGlobal-wm->TimeStart())/ ps_r__WallmarkTTL; if (w<1.f){ // append wm to WallmarkEngine if (::Render->ViewBase.testSphere_dirty(wm->m_Bounds.P,wm->m_Bounds.R)) //::Render->add_SkeletonWallmark (wm); ::RImplementation.add_SkeletonWallmark (wm); }else{ // remove wallmark need_remove = true; } } if (need_remove){ auto new_end = std::remove_if(wallmarks.begin(), wallmarks.end(), [](const auto& x) {return x == 0; }); wallmarks.erase (new_end,wallmarks.end()); } } } void CKinematics::RenderWallmark(intrusive_ptr<CSkeletonWallmark> wm, FVF::LIT* &V) { VERIFY(wm); VERIFY(V); VERIFY2(bones,"Invalid visual. Bones already released."); VERIFY2(bone_instances,"Invalid visual. bone_instances already deleted."); if ((wm == 0) || (0==bones) || (0==bone_instances)) return; // skin vertices for (u32 f_idx=0; f_idx<wm->m_Faces.size(); f_idx++){ CSkeletonWallmark::WMFace F = wm->m_Faces[f_idx]; float w = (RDEVICE.fTimeGlobal-wm->TimeStart())/ ps_r__WallmarkTTL; for (u32 k=0; k<3; k++){ Fvector P; if (F.bone_id[k][0]==F.bone_id[k][1]){ // 1-link Fmatrix& xform0 = LL_GetBoneInstance(F.bone_id[k][0]).mRenderTransform; xform0.transform_tiny (P,F.vert[k]); } else if (F.bone_id[k][1] == F.bone_id[k][2]) { // 2-link Fvector P0,P1; Fmatrix& xform0 = LL_GetBoneInstance(F.bone_id[k][0]).mRenderTransform; Fmatrix& xform1 = LL_GetBoneInstance(F.bone_id[k][1]).mRenderTransform; xform0.transform_tiny (P0,F.vert[k]); xform1.transform_tiny (P1,F.vert[k]); P.lerp(P0, P1, F.weight[k][0]); } else if (F.bone_id[k][2] == F.bone_id[k][3]) { // 3-link Fvector P0, P1, P2; Fmatrix& xform0 = LL_GetBoneInstance(F.bone_id[k][0]).mRenderTransform; Fmatrix& xform1 = LL_GetBoneInstance(F.bone_id[k][1]).mRenderTransform; Fmatrix& xform2 = LL_GetBoneInstance(F.bone_id[k][2]).mRenderTransform; xform0.transform_tiny(P0, F.vert[k]); xform1.transform_tiny(P1, F.vert[k]); xform2.transform_tiny(P2, F.vert[k]); float w0 = F.weight[k][0]; float w1 = F.weight[k][1]; P0.mul(w0); P1.mul(w1); P2.mul(1 - w0 - w1); P = P0; P.add(P1); P.add(P2); } else { // 4-link Fvector PB[4]; for (int i = 0; i < 4; ++i) { Fmatrix& xform = LL_GetBoneInstance(F.bone_id[k][i]).mRenderTransform; xform.transform_tiny(PB[i], F.vert[k]); } float s = 0.f; for (int i = 0; i < 3; ++i) { PB[i].mul(F.weight[k][i]); s += F.weight[k][i]; } PB[3].mul(1 - s); P = PB[0]; for (int i = 1; i < 4; ++i) P.add(PB[i]); } wm->XFORM()->transform_tiny (V->p,P); V->t.set (F.uv[k]); int aC = iFloor ( w * 255.f); clamp (aC,0,255); V->color = color_rgba(128,128,128,aC); V++; } } wm->XFORM()->transform_tiny(wm->m_Bounds.P,wm->m_LocalBounds.P); } void CKinematics::ClearWallmarks() { // for (SkeletonWMVecIt it=wallmarks.begin(); it!=wallmarks.end(); it++) // xr_delete (*it); wallmarks.clear (); } int CKinematics::LL_GetBoneGroups(xr_vector<xr_vector<u16> >& groups) { groups.resize (children.size()); for (u16 bone_idx=0; bone_idx<(u16)bones->size(); bone_idx++) { CBoneData* B = (*bones)[bone_idx]; for (u32 child_idx=0; child_idx<children.size(); child_idx++){ if (!B->child_faces[child_idx].empty()){ groups[child_idx].push_back(bone_idx); } } } return groups.size(); } #ifdef DEBUG CSkeletonWallmark::~CSkeletonWallmark() { if(used_in_render!=u32(-1)) { Msg ("used_in_render=%d",used_in_render); VERIFY (used_in_render==u32(-1)); } } #endif
28.668348
155
0.638647
[ "render", "object", "shape", "model", "transform" ]
8b083ff6b133777cd7f2c141631e9ff904a98f9a
39,550
cpp
C++
emulator/src/mame/drivers/swyft.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
1
2022-01-15T21:38:38.000Z
2022-01-15T21:38:38.000Z
emulator/src/mame/drivers/swyft.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
emulator/src/mame/drivers/swyft.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
// license:BSD-3-Clause // copyright-holders:Miodrag Milanovic, Jonathan Gevaryahu /*************************************************************************** IAI Swyft Model P0001 Copyright (C) 2009-2013 Miodrag Milanovic and Jonathan Gevaryahu AKA Lord Nightmare With information and help from John "Sandy" Bumgarner, Dwight Elvey, Charles Springer, Terry Holmes, Jonathan Sand, Aza Raskin and others. See cat.c for the machine which the swyft later became. This driver is dedicated in memory of Jef Raskin, Dave Boulton, and John "Sandy" Bumgarner (1941-2016) IAI detailed credits: Scott Kim - responsible for fonts on swyft and cat Ralph Voorhees - Model construction and mockups (swyft 'flat cat') Cat HLSL stuff: *scanlines: the cat has somewhat visible and fairly close scanlines with very little fuzziness try hlsl options: hlsl_prescale_x 4 hlsl_prescale_y 4 scanline_alpha 0.3 scanline_size 1.0 scanline_height 0.7 scanline_bright_scale 1.0 scanline_bright_offset 0.6 *phosphor persistence of the original cat CRT is VERY LONG and fades to a greenish-yellow color, though the main color itself is white try hlsl option: phosphor_life 0.93,0.95,0.87 which is fairly close but may actually be too SHORT compared to the real thing. Swyft versions: There are at least 4 variants of machines called 'swyft': * The earliest desktop units which use plexi or rubber-tooled case and an angled monitor; about a dozen were made and at least two of clear plexi. These are sometimes called "wrinkled" swyfts. 5.25" drive, they may be able to read Apple2 Swyftware/Swyftdisk and Swyftcard-created disks. It is possible no prototypes of this type got beyond the 'runs forth console only' stage. http://archive.computerhistory.org/resources/access/physical-object/2011/09/102746929.01.01.lg.JPG http://www.digibarn.com/collections/systems/swyft/Swyft-No2-05-1271.jpg http://www.digibarn.com/friends/jef-raskin/slides/iai/A%20-687%20SWYFTPRO.JPG * The early "flat cat" or "roadkill" portable LCD screen units with a white case and just a keyboard. Model SP0001 http://www.digibarn.com/collections/systems/swyft/Image82.jpg * The later "ur-cat" desktop units which use a machine tooled case and look more or less like the canon cat. Around 100-200 were made. 3.5" drive. These have a fully functional EDDE editor as the cat does, and can even compile forth programs. (the 'swyft' driver is based on one of these) * The very late portable LCD units with a dark grey case and a row of hotkey buttons below the screen. Not dumped yet. At least one functional prototype exists. At least one plastic mockup exists with no innards. http://www.digibarn.com/collections/systems/swyft/swyft.jpg IAI Swyft: Board name: 950-0001C "INFORMATION APPLIANCE INC. COPYRIGHT 1985" _________________|||||||||___________________________________________________________________________________ | J8 [=======J3=======] ____ Trans- | == / \ (E2) former | ==Jx 74LS107 J5 |PB1 | uA339 MC3403 -----| | 7407 \____/ J7 = | Y1 "TIMING B" 74LS132 74LS175 -----| | ____________ 4N37 Relay -----| | TMS4256 74LS161 "DECODE E" "DISK 3.5C" | | J6 = | | MC6850P | -----| | TMS4256 74LS166 74HCT259 74LS299 '------------' MC3403 MC3403 _____| | ___________________ ___________________ || | = | TMS4256 74LS373 | | | | J2 | J1 = | | MC68008P8 | | R6522P | || I P R | = | TMS4256 74F153 '-------------------' '-------------------' MN4053 || MN4053 N R E | B = | (E1) D O S | R = | TMS4256 74F153 74HCT08 __________ ___________________ MC14412 DS1489 U E T I | E = | | | | | || C S E S | A = | TMS4256 74F153 74HC4040E | AM27256 | | R6522P | || T D C T | K = | '----------' '-------------------' || INFORMATION O T O | O = | TMS4256 74F153 "VIDEO 2B" .----------. J4 APPLIANCE INC. R I R | U = | | AM27256 | 74HC02 74HC374 || Copyright 1985 S O S | T = | TMS4256 74F153 74LS393 B1|__________| || UM95089 Y2 N | = |_____________________________[________J9___]__________________________________________________D13______|_____= *Devices of interest: J1: breakout of joystick, serial/rs232, hex-keypad, parallel port, and forth switch (and maybe cassette?) pins DIL 60 pin 2-row right-angle rectangular connector with metal shield contact; not all 60 pins are populated in the connector, only pins 1-6, 8, 13-15, 17-18, 23-30, 35-60 are present (traced partly by dwight) J2: unpopulated 8-pin sip header, serial/rs232-related? (vcc ? ? ? ? ? ? gnd) (random guess: txd, rxd, rts, cts, dsr, dtr, and one pin could be cd/ri though the modem circuit may do that separately?) J3: Floppy Connector (standard DIL 34 pin 2-row rectangular connector for mini-shugart/pc floppy cable; pin 2 IS connected somewhere and ?probably? is used for /DISKCHANGE like on an Amiga, with pin 34 being /TRUEREADY?) (as opposed to normal ibm pc 3.5" drives where pin 2 is unconnected or is /DENSITY *input to drive*, and pin 34 is /DISKCHANGE) J4: 18-pin sip header for keyboard ribbon cable; bottom edge of board is pin 1 Pins: 1: GND through 220k resistor r78 2: ? phone hook related? anode of diode d7; one of the pins of relay k2; topmost (boardwise) pin of transistor Q10 3: 74HCT34 pin J5: locking-tab-type "CONN HEADER VERT 4POS .100 TIN" connector for supplying power through a small cable with a berg connector at the other end, to the floppy drive (5v gnd gnd 12v) J6: Phone connector, rj11 jack J7: Line connector, rj11 jack J8: 9-pin Video out/power in connector "CONN RECEPT 6POS .156 R/A PCB" plus "CONN RECEPT 3POS .156 R/A PCB" acting as one 9-pin connector (NC ? ? ? NC NC ? 12v 5v) (video, vsync, hsync and case/video-gnd are likely here) (the video pinout of the cat is: (Video Vsync Hsync SyncGnd PwrGnd PwrGnd +5v(VCC) +12v(VDD) -12v(VEE)) which is not the same as the swyft. J9: unpopulated DIL 40-pin straight connector for a ROM debug/expansion/RAM-shadow daughterboard the pins after pin 12 connect to that of the ROM-LO 27256 pinout counting pins 1,28,2,27,3,26,etc the ROM-HI rom has a different /HICE pin which is not connected to this connector /LOCE is a15 /HICE is !a15 /ROM_OE comes from pin 14 of DECODE_E pal, and is shorted to /ROM_OE' by the cuttable jumper B1 which is not cut /ROM_OE' goes to the two EPROMS DECODE_18 is DECODE_E pal pin 18 pin 1 (GND) is in the lower left and the pins count low-high then to the right (gnd N/C E_CLK R/W /ROM_OE a17 vcc a14 a13 a8 a9 a11 /ROM_OE' a10 a15 d7 d6 d5 d4 d3 ) (GND /IPL1 DECODE_18 /RESET gnd a16 vcc a12 a7 a6 a5 a4 a3 a2 a1 a0 d0 d1 d2 gnd) Jx: 4 pin on top side, 6 pin on bottom side edge ?debug? connector (doesn't have a Jx number) (trace me!) B1: a cuttable trace on the pcb. Not cut, affects one of the pins on the unpopulated J9 connector only. E1: jumper, unknown purpose, not set E2: jumper, unknown purpose, not set D13: LED R6522P (upper): parallel port via R6522P (lower): keyboard via UM95089: DTMF Tone generator chip (if you read the datasheet this is technically ROM based!) Y1: 15.8976Mhz, main clock? Y2: 3.579545Mhz, used by the DTMF generator chip UM95089 (connects to pins 7 and 8 of it) TMS4256-15NL - 262144 x 1 DRAM PB1 - piezo speaker *Pals: "TIMING B" - AMPAL16R4APC (marked on silkscreen "TIMING PAL") "DECODE E" - AMPAL16L8PC (marked on silkscreen "DECODE PAL") "VIDEO 2B" - AMPAL16R4PC (marked on silkscreen "VIDEO PAL") "DISK 3.5C" - AMPAL16R4PC (marked on silkscreen "DISK PAL") *Deviations from silkscreen: 4N37 (marked on silkscreen "4N35") 74F153 (marked on silkscreen "74ALS153") 74HCT259 is socketed, possibly intended that the rom expansion daughterboard will have a ribbon cable fit in its socket? ToDo: * Swyft - Figure out the keyboard (interrupts are involved? or maybe an NMI on a timer/vblank? It is possible this uses a similar 'keyboard read int' to what the cat does) - get the keyboard scanning actually working; the VIAs are going nuts right now. - Beeper (on one of the vias?) - vblank/hblank stuff - Get the 6850 ACIA working for communications - Floppy (probably similar to the Cat) - Centronics port (attached to one of the VIAs) - Joystick port (also likely on a via) - Keypad? (also likely on a via done as a grid scan?) - Forth button (on the port on the back; keep in mind shift-usefront-space ALWAYS enables forth on a swyft) - Multple undumped firmware revisions exist (330 and 331 are dumped) // 74ls107 @ u18 pin 1 is 68008 /BERR pin // mc6850 @ u33 pin 2 (RX_DATA) is // mc6850 @ u33 pin 3 (RX_CLK) is 6522 @ u35 pin 17 (PB7) // mc6850 @ u33 pin 4 (TX_CLK) is 6522 @ u35 pin 17 (PB7) // mc6850 @ u33 pin 5 (/RTS) is // mc6850 @ u33 pin 6 (TX_DATA) is // mc6850 @ u33 pin 7 (/IRQ) is 68008 /IPL1 pin 41 // mc6850 @ u33 pin 8 (CS0) is 68008 A12 pin 10 // mc6850 @ u33 pin 9 (CS2) is DECODE E pin 18 // mc6850 @ u33 pin 10 (CS1) is 68008 /BERR pin 40 // mc6850 @ u33 pin 11 (RS) is 68008 A0 pin 46 // mc6850 @ u33 pin 13 (R/W) is 68008 R/W pin 30 // mc6850 @ u33 pin 14 (E) is 68008 E pin 38 // mc6850 @ u33 pin 15-22 (D7-D0) are 68008 D7 to D0 pins 20-27 // mc6850 @ u33 pin 23 (/DCD) is 74hc02 @ u35 pin 1 // mc6850 @ u33 pin 24 (/CTS) is N/C? // 6522 @ u34: // pin 2 (PA0) : // pin 3 (PA1) : // pin 4 (PA2) : // pin 5 (PA3) : // pin 6 (PA4) : // pin 7 (PA5) : // pin 8 (PA6) : // pin 9 (PA7) : // pin 10 (PB0) : // pin 11 (PB1) : // pin 12 (PB2) : // pin 13 (PB3) : // pin 14 (PB4) : // pin 15 (PB5) : // pin 16 (PB6) : // pin 17 (PB7) : // pin 18 (CB1) : ?from/to? Floppy connector j3 pin 8 // pin 19 (CB2) : ?from/to? 6522 @ u35 pin 16 (PB6) // pin 21 (/IRQ) : out to 68008 /IPL1 pin 41 // pin 22 (R/W) : in from 68008 R/W pin 30 // pin 23 (/CS2) : in from DECODE E pin 18 // pin 24 (CS1) : in from 68008 A13 pin 11 // pin 25 (Phi2) : in from 68008 E pin 38 // pins 26-33 : in/out from/to 68008 D7 to D0 pins 20-27 // pin 34 (/RES) : in from 68008 /RESET pin 37 AND 68008 /HALT pin 36 // pins 35-38 (RS3-RS0) are 68008 A9-A6 pins 7-4 // pin 39 (CA2) is through inductor L11 and resistor r128 to peripheral connector pin 35 <end minus 26> // pin 40 (CA1) is through inductor L30 and resistor r138 to peripheral connector pin 53 <end minus 8> // 6522 @ u35 // pin 2 (PA0) : // pin 3 (PA1) : // pin 4 (PA2) : // pin 5 (PA3) : // pin 6 (PA4) : // pin 7 (PA5) : // pin 8 (PA6) : // pin 9 (PA7) : // pin 10 (PB0) : // pin 11 (PB1) : in from 74hc02 @ u36 pin 4 // pin 12 (PB2) : // pin 13 (PB3) : // pin 14 (PB4) : // pin 15 (PB5) : // pin 16 (PB6) : 6522 @ u34 pin 19 (CB2) // pin 17 (PB7) : mc6850 @ u33 pins 3 and 4 (RX_CLK, TX_CLK) // pin 18 (CB1) : ds1489an @ u45 pin 11 // pin 19 (CB2) : mn4053b @ u40 pin 11 and mc14412 @ u41 pin 10 // pin 21 (/IRQ) : out to 68008 /IPL1 pin 41 // pin 22 (R/W) : in from 68008 R/W pin 30 // pin 23 (/CS2) : in from DECODE E pin 18 // pin 24 (CS1) : in from 68008 A14 pin 12 // pin 25 (Phi2) : in from 68008 E pin 38 // pins 26-33 : in/out from/to 68008 D7 to D0 pins 20-27 // pin 34 (/RES) : in from 68008 /RESET pin 37 AND 68008 /HALT pin 36 // pins 35-38 (RS3-RS0) : in from 68008 A9-A6 pins 7-4 // pin 39 (CA2) : out to 74HCT34 pin 11 (CLK) (keyboard column latch) // pin 40 (CA1) : out? to? ds1489an @ u45 pin 8 // 74hc02 @ u36: // pin 1 (Y1) : out to mc6850 @ u33 pin 23 /DCD // pin 2 (A1) : in from (2 places: resistor R58 to ua339 @ u38 pin 4 (In1-)) <where does this actually come from? modem offhook?> // pin 3 (B1) : in from mn4053b @ u40 pin 10 <probably from rs232> // pin 4 (Y2) : out to 6522 @u35 pin 11 // pin 5 (A2) : in from 4N37 @ u48 pin 5 (output side emitter pin) (tied via R189 to gnd) <ring indicator?> // pin 6 (B2) : in from 4N37 @ u48 pin 5 (output side emitter pin) (tied via R189 to gnd) <ring indicator?> // pin 8 (B3) : // pin 9 (A3) : // pin 10 (Y3) : // pin 11 (B4) : in from 68008 A15 // pin 12 (A4) : in from 68008 A15 // pin 13 (Y4) : out to EPROM @ U31 /CE ****************************************************************************/ // Includes #include "emu.h" #include "bus/centronics/ctronics.h" #include "cpu/m68000/m68000.h" #include "machine/6522via.h" #include "machine/6850acia.h" #include "machine/clock.h" #include "sound/spkrdev.h" #include "screen.h" // Defines #undef DEBUG_GA2OPR_W #undef DEBUG_VIDEO_CONTROL_W #undef DEBUG_FLOPPY_CONTROL_W #undef DEBUG_FLOPPY_CONTROL_R #undef DEBUG_FLOPPY_DATA_W #undef DEBUG_FLOPPY_DATA_R #undef DEBUG_FLOPPY_STATUS_R #undef DEBUG_PRINTER_DATA_W #undef DEBUG_PRINTER_CONTROL_W #undef DEBUG_MODEM_R #undef DEBUG_MODEM_W #undef DEBUG_DUART_OUTPUT_LINES // data sent to rs232 port #undef DEBUG_DUART_TXA // data sent to modem chip #undef DEBUG_DUART_TXB #undef DEBUG_DUART_IRQ_HANDLER #undef DEBUG_PRN_FF #undef DEBUG_TEST_W #define DEBUG_SWYFT_VIA0 1 #define DEBUG_SWYFT_VIA1 1 class swyft_state : public driver_device { public: swyft_state(const machine_config &mconfig, device_type type, const char *tag) : driver_device(mconfig, type, tag), m_maincpu(*this, "maincpu"), m_ctx(*this, "ctx"), m_ctx_data_out(*this, "ctx_data_out"), m_acia6850(*this, "acia6850"), m_via0(*this, "via6522_0"), m_via1(*this, "via6522_1"), m_speaker(*this, "speaker"), m_p_swyft_videoram(*this, "p_swyft_vram") /*m_y0(*this, "Y0"), m_y1(*this, "Y1"), m_y2(*this, "Y2"), m_y3(*this, "Y3"), m_y4(*this, "Y4"), m_y5(*this, "Y5"), m_y6(*this, "Y6"), m_y7(*this, "Y7")*/ { } required_device<cpu_device> m_maincpu; optional_device<centronics_device> m_ctx; optional_device<output_latch_device> m_ctx_data_out; required_device<acia6850_device> m_acia6850; // only swyft uses this required_device<via6522_device> m_via0; // only swyft uses this required_device<via6522_device> m_via1; // only swyft uses this optional_device<speaker_sound_device> m_speaker; required_shared_ptr<uint8_t> m_p_swyft_videoram; /*optional_ioport m_y0; optional_ioport m_y1; optional_ioport m_y2; optional_ioport m_y3; optional_ioport m_y4; optional_ioport m_y5; optional_ioport m_y6; optional_ioport m_y7;*/ DECLARE_MACHINE_START(swyft); DECLARE_MACHINE_RESET(swyft); DECLARE_VIDEO_START(swyft); uint32_t screen_update_swyft(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect); DECLARE_READ8_MEMBER(swyft_d0000); DECLARE_READ8_MEMBER(swyft_via0_r); DECLARE_WRITE8_MEMBER(swyft_via0_w); DECLARE_READ8_MEMBER(via0_pa_r); DECLARE_WRITE8_MEMBER(via0_pa_w); DECLARE_WRITE_LINE_MEMBER(via0_ca2_w); DECLARE_READ8_MEMBER(via0_pb_r); DECLARE_WRITE8_MEMBER(via0_pb_w); DECLARE_WRITE_LINE_MEMBER(via0_cb1_w); DECLARE_WRITE_LINE_MEMBER(via0_cb2_w); DECLARE_WRITE_LINE_MEMBER(via0_int_w); DECLARE_READ8_MEMBER(swyft_via1_r); DECLARE_WRITE8_MEMBER(swyft_via1_w); DECLARE_READ8_MEMBER(via1_pa_r); DECLARE_WRITE8_MEMBER(via1_pa_w); DECLARE_WRITE_LINE_MEMBER(via1_ca2_w); DECLARE_READ8_MEMBER(via1_pb_r); DECLARE_WRITE8_MEMBER(via1_pb_w); DECLARE_WRITE_LINE_MEMBER(via1_cb1_w); DECLARE_WRITE_LINE_MEMBER(via1_cb2_w); DECLARE_WRITE_LINE_MEMBER(via1_int_w); DECLARE_WRITE_LINE_MEMBER(write_acia_clock); uint8_t m_keyboard_line; uint8_t m_floppy_control; void swyft(machine_config &config); void swyft_mem(address_map &map); //protected: //virtual void device_timer(emu_timer &timer, device_timer_id id, int param, void *ptr); }; static INPUT_PORTS_START( swyft ) // insert dwight and sandy's swyft keyboard map here once we figure out the byte line order PORT_START("Y0") PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_N) PORT_CHAR('n') PORT_CHAR('N') PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_M) PORT_CHAR('m') PORT_CHAR('M') PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_K) PORT_CHAR('k') PORT_CHAR('K') PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_J) PORT_CHAR('j') PORT_CHAR('J') PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_Y) PORT_CHAR('y') PORT_CHAR('Y') PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_T) PORT_CHAR('t') PORT_CHAR('T') PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_6) PORT_CHAR('6') PORT_CHAR(0xA2) PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_5) PORT_CHAR('5') PORT_CHAR('%') PORT_START("Y1") PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_B) PORT_CHAR('n') PORT_CHAR('B') PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_COMMA) PORT_CHAR(',') PORT_CHAR('<') PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_L) PORT_CHAR('l') PORT_CHAR('L') PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_H) PORT_CHAR('h') PORT_CHAR('H') PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_U) PORT_CHAR('u') PORT_CHAR('U') PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_R) PORT_CHAR('r') PORT_CHAR('R') PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_7) PORT_CHAR('7') PORT_CHAR('&') PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_4) PORT_CHAR('4') PORT_CHAR('$') PORT_START("Y2") PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_V) PORT_CHAR('v') PORT_CHAR('V') PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_STOP) PORT_CHAR('.') PORT_CHAR('>') PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_COLON) PORT_CHAR(';') PORT_CHAR(':') PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_G) PORT_CHAR('g') PORT_CHAR('G') PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_I) PORT_CHAR('i') PORT_CHAR('I') PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_UNUSED) // totally unused PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_8) PORT_CHAR('8') PORT_CHAR('*') PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_3) PORT_CHAR('3') PORT_CHAR('#') PORT_START("Y3") PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_C) PORT_CHAR('c') PORT_CHAR('C') PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Left USE FRONT") PORT_CODE(KEYCODE_LCONTROL) PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_QUOTE) PORT_CHAR('\'') PORT_CHAR('"') PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_F) PORT_CHAR('f') PORT_CHAR('F') PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_O) PORT_CHAR('o') PORT_CHAR('O') PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_E) PORT_CHAR('e') PORT_CHAR('E') PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_9) PORT_CHAR('9') PORT_CHAR('(') PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_UNUSED) // totally unused PORT_START("Y4") PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_X) PORT_CHAR('x') PORT_CHAR('X') PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Right USE FRONT") PORT_CODE(KEYCODE_RCONTROL) PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Right Shift") PORT_CODE(KEYCODE_F2) // intl only: latin diaresis and latin !; norway, danish and finnish * and '; others PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_D) PORT_CHAR('d') PORT_CHAR('D') PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_P) PORT_CHAR('p') PORT_CHAR('P') PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_W) PORT_CHAR('w') PORT_CHAR('W') PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_0) PORT_CHAR('0') PORT_CHAR(')') PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_2) PORT_CHAR('2') PORT_CHAR('@') PORT_START("Y5") PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_Z) PORT_CHAR('z') PORT_CHAR('Z') PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_SPACE) PORT_CHAR(' ') PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Return") PORT_CODE(KEYCODE_ENTER) PORT_CHAR(13) PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_S) PORT_CHAR('s') PORT_CHAR('S') PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_OPENBRACE) PORT_CHAR(0xBD) PORT_CHAR(0xBC) //PORT_CHAR('}') PORT_CHAR('{') PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_Q) PORT_CHAR('q') PORT_CHAR('Q') PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_MINUS) PORT_CHAR('-') PORT_CHAR('_') PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_1) PORT_CHAR('1') PORT_CHAR('!') PORT_START("Y6") PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Left Shift") PORT_CODE(KEYCODE_F1) // intl only: latin inv ? and inv !; norway and danish ! and |; finnish <>; others PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Left LEAP") PORT_CODE(KEYCODE_LALT) PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_SLASH) PORT_CHAR('/') PORT_CHAR('?') PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_A) PORT_CHAR('a') PORT_CHAR('A') PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_CLOSEBRACE) PORT_CHAR(']') PORT_CHAR('[') PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_TAB) PORT_CHAR('\t') PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_EQUALS) PORT_CHAR('=') PORT_CHAR('+') PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_UNUSED) // totally unused PORT_START("Y7") PORT_BIT(0x01, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Shift") PORT_CODE(KEYCODE_RSHIFT) PORT_CODE(KEYCODE_LSHIFT) PORT_CHAR(UCHAR_SHIFT_1) PORT_BIT(0x02, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Right Leap") PORT_CODE(KEYCODE_RALT) PORT_BIT(0x04, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Page") PORT_CODE(KEYCODE_PGUP) PORT_CODE(KEYCODE_PGDN) PORT_BIT(0x08, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Shift Lock") PORT_CODE(KEYCODE_CAPSLOCK) PORT_BIT(0x10, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("Erase") PORT_CODE(KEYCODE_BACKSPACE) PORT_BIT(0x20, IP_ACTIVE_LOW, IPT_UNUSED) // totally unused PORT_BIT(0x40, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_NAME("UNDO") PORT_CODE(KEYCODE_BACKSLASH) PORT_BIT(0x80, IP_ACTIVE_LOW, IPT_KEYBOARD) PORT_CODE(KEYCODE_TILDE) PORT_CHAR(0xB1) PORT_CHAR(0xB0) // PORT_CHAR('\\') PORT_CHAR('~') INPUT_PORTS_END /* Swyft rom and ram notes: rom: **Vectors: 0x0000-0x0003: SP boot vector 0x0004-0x0007: PC boot vector **unknown: 0x0009-0x00BF: ? table 0x00C0-0x01DF: ? table 0x01E0-0x02DF: ? table (may be part of next table) 0x02E0-0x03DF: ? table 0x03E0-0x0B3F: int16-packed jump table (expanded to int32s at ram at 0x46000-0x46EC0 on boot) 0x0B40-0x0E83: ? function index tables? 0x0E84-0x1544: binary code (purpose?) 0x1545-0x24CF: ? **Fonts: 0x24D0-0x254F: ? (likely font 1 width lookup table) 0x2550-0x2BCF: Font 1 data 0x2BD0-0x2C4F: ? (likely font 2 width lookup table) 0x2C50-0x32CF: Font 2 data **unknown?: 0x32D0-0x360F: String data (and control codes?) 0x3610-0x364F: ? fill (0x03 0xe8) 0x3650-0x369F: ? fill (0x03 0x20) 0x36A0-0x384d: ? forth code? 0x384e-0x385d: Lookup table for phone keypad 0x385e-...: ? ...-0xC951: ? 0xC952: boot vector 0xC952-0xCAAE: binary code (purpose?) 0xCD26-0xCD3B: ?init forth bytecode? 0xCD3C-0xCEBA: 0xFF fill (unused?) 0xCEEB-0xFFFE: Forth dictionaries for compiling, with <word> then <3 bytes> afterward? (or before it? most likely afterward) ram: (system dram ranges from 0x40000-0x7FFFF) 0x40000-0x425CF - the screen display ram (?0x425D0-0x44BA0 - ?unknown (maybe screen ram page 2?)) 0x44DC6 - SP vector 0x46000-0x46EC0 - jump tables to instructions for ? (each forth word?) on boot: copy/expand packed rom short words 0x3E0-0xB3F to long words at 0x46000-0x46EC0 copy 0x24f longwords of zero beyond that up to 0x47800 CD26->A5 <?pointer to init stream function?> 44DC6->A7 <reset SP... why it does this twice, once by the vector and once here, i'm gonna guess has to do with running the code in a debugger or on a development daughterboard like the cat had, where the 68008 wouldn't get explicitly reset> 44F2A->A6 <?pointer to work ram space?> EA2->A4 <?function> E94->A3 <?function> EAE->A2 <?function> 41800->D7 <?forth? opcode index base; the '1800' portion gets the opcode type added to it then is multiplied by 4 to produce the jump table offset within the 0x46000-0x46EC0 range> 46e3c->D4 <?pointer to more work ram space?> CD22->D5 <?pointer to another function?> write 0xFFFF to d0004.l jump to A4(EA2) read first stream byte (which is 0x03) from address pointed to by A5 (which is CD26), inc A5, OR the opcode (0x03) to D7 (Note: if the forth opcodes are in order in the dictionary, then 0x03 is "!char" which is used to read a char from an arbitrary address) copy D7 to A0 Add A0 low word to itself Add A0 low word to itself again move the long word from address pointed to by A0 (i.e. the specific opcode's area at the 46xxx part of ram) to A1 Jump to A1(11A4) 11A4: move 41b00 to D0 (select an opcode "page" 1bxx) jump to 118E 118E: read next stream byte (in this case, 0x8E) from address pointed to by A5 (which is CD27), inc A5, OR the opcode (0x8e) to D7 add to 41b00 in d0, for 41b8E Add A0 low word to itself Add A0 low word to itself again move the long word from address pointed to by A0 (i.e. the specific opcode's area at the 46xxx part of ram) to A1 Jump to A1(CD06) CD06: jump to A3 (E94) E94: subtract D5 from A5 (cd28 - cd22 = 0x0006) write 6 to address @A5(44f28) and decrement A5 write D4(46e3c) to address @a6(44f26) and decrement a5 lea ($2, A1), A5 - i.e. increment A1 by 2, and write that to A5, so write CD06+2=CD08 to A5 A1->D5 A0->D4 read next stream byte (in this case, 0x03) from address pointed to by A5 (which is CD08), inc A5, OR the opcode (0x03) to D7 */ /* Swyft Memory map, based on watching the infoapp roms do their thing: 68k address map: (a23,a22,a21,a20 lines don't exist on the 68008 so are considered unconnected) a23 a22 a21 a20 a19 a18 a17 a16 a15 a14 a13 a12 a11 a10 a9 a8 a7 a6 a5 a4 a3 a2 a1 a0 x x x x 0 0 ? ? 0 * * * * * * * * * * * * * * * R ROM-LO (/LOCE is 0, /HICE is 1) x x x x 0 0 ? ? 1 * * * * * * * * * * * * * * * R ROM-HI (/LOCE is 1, /HICE is 0) x x x x 0 1 * * * * * * * * * * * * * * * * * a RW RAM x x x x 1 1 ?0? ?1? ? ? ? ? ? ? ? ? ? ? ? ? * * * * R ? status of something? floppy? x x x x 1 1 ?1? ?0? ? 0 0 1 x x x x x x x x x x x * RW 6850 acia @U33, gets 0x55 steadystate and 0x57 written to it to reset it x x x x 1 1 ?1? ?0? ? 0 1 0 x x * * * * x x x x x x RW Parallel VIA 0 @ U34 x x x x 1 1 ?1? ?0? ? 1 0 0 x x * * * * x x x x x x RW Keyboard VIA 1 @ U35 ^ ^ ^ ^ ^ */ void swyft_state::swyft_mem(address_map &map) { map.unmap_value_high(); map.global_mask(0xfffff); map(0x000000, 0x00ffff).rom(); // 64 KB ROM map(0x040000, 0x07ffff).ram().share("p_swyft_vram"); // 256 KB RAM map(0x0d0000, 0x0d000f).r(this, FUNC(swyft_state::swyft_d0000)); // status of something? reads from d0000, d0004, d0008, d000a, d000e map(0x0e1000, 0x0e1000).w(m_acia6850, FUNC(acia6850_device::control_w)); // 6850 ACIA lives here map(0x0e2000, 0x0e2fff).rw(this, FUNC(swyft_state::swyft_via0_r), FUNC(swyft_state::swyft_via0_w)); // io area with selector on a9 a8 a7 a6? map(0x0e4000, 0x0e4fff).rw(this, FUNC(swyft_state::swyft_via1_r), FUNC(swyft_state::swyft_via1_w)); } MACHINE_START_MEMBER(swyft_state,swyft) { m_via0->write_ca1(1); m_via0->write_ca2(1); m_via0->write_cb1(1); m_via0->write_cb2(1); m_via1->write_ca1(1); m_via1->write_ca2(1); m_via1->write_cb1(1); m_via1->write_cb2(1); } MACHINE_RESET_MEMBER(swyft_state,swyft) { } VIDEO_START_MEMBER(swyft_state,swyft) { } uint32_t swyft_state::screen_update_swyft(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect) { uint16_t code; int y, x, b; int addr = 0; for (y = 0; y < 242; y++) { int horpos = 0; for (x = 0; x < 40; x++) { code = m_p_swyft_videoram[addr++]; for (b = 7; b >= 0; b--) { bitmap.pix16(y, horpos++) = (code >> b) & 0x01; } } } return 0; } READ8_MEMBER( swyft_state::swyft_d0000 ) { // wtf is this supposed to be? uint8_t byte = 0xFF; // ? logerror("mystery device: read from 0x%5X, returning %02X\n", offset+0xD0000, byte); return byte; } // if bit is 1 enable: (obviously don't set more than one bit or you get bus contention!) // acia // via0 // via1 // x x x x 1 1 ?1? ?0? ? ^ ^ ^ ? ? * * * * ?*? ? ? ? ? ? // ^ ^ ^ ^ <- these four bits address the VIA registers? is this correct? static const char *const swyft_via_regnames[] = { "0: ORB/IRB", "1: ORA/IRA", "2: DDRB", "3: DDRA", "4: T1C-L", "5: T1C-H", "6: T1L-L", "7: T1L-H", "8: T2C-L", "9: T2C-H", "A: SR", "B: ACR", "C: PCR", "D: IFR", "E: IER", "F: ORA/IRA*" }; READ8_MEMBER( swyft_state::swyft_via0_r ) { if (offset&0x000C3F) fprintf(stderr,"VIA0: read from invalid offset in 68k space: %06X!\n", offset); uint8_t data = m_via0->read(space, (offset>>6)&0xF); #ifdef DEBUG_SWYFT_VIA0 logerror("VIA0 register %s read by cpu: returning %02x\n", swyft_via_regnames[(offset>>5)&0xF], data); #endif return data; } WRITE8_MEMBER( swyft_state::swyft_via0_w ) { #ifdef DEBUG_SWYFT_VIA0 logerror("VIA0 register %s written by cpu with data %02x\n", swyft_via_regnames[(offset>>5)&0xF], data); #endif if (offset&0x000C3F) fprintf(stderr,"VIA0: write to invalid offset in 68k space: %06X, data: %02X!\n", offset, data); m_via1->write(space, (offset>>6)&0xF, data); } READ8_MEMBER( swyft_state::swyft_via1_r ) { if (offset&0x000C3F) fprintf(stderr," VIA1: read from invalid offset in 68k space: %06X!\n", offset); uint8_t data = m_via1->read(space, (offset>>6)&0xF); #ifdef DEBUG_SWYFT_VIA1 logerror(" VIA1 register %s read by cpu: returning %02x\n", swyft_via_regnames[(offset>>5)&0xF], data); #endif return data; } WRITE8_MEMBER( swyft_state::swyft_via1_w ) { #ifdef DEBUG_SWYFT_VIA1 logerror(" VIA1 register %s written by cpu with data %02x\n", swyft_via_regnames[(offset>>5)&0xF], data); #endif if (offset&0x000C3F) fprintf(stderr," VIA1: write to invalid offset in 68k space: %06X, data: %02X!\n", offset, data); m_via0->write(space, (offset>>6)&0xF, data); } // first via READ8_MEMBER( swyft_state::via0_pa_r ) { logerror("VIA0: Port A read!\n"); return 0xFF; } WRITE8_MEMBER( swyft_state::via0_pa_w ) { logerror("VIA0: Port A written with data of 0x%02x!\n", data); } WRITE_LINE_MEMBER ( swyft_state::via0_ca2_w ) { logerror("VIA0: CA2 written with %d!\n", state); } READ8_MEMBER( swyft_state::via0_pb_r ) { logerror("VIA0: Port B read!\n"); return 0xFF; } WRITE8_MEMBER( swyft_state::via0_pb_w ) { logerror("VIA0: Port B written with data of 0x%02x!\n", data); } WRITE_LINE_MEMBER ( swyft_state::via0_cb1_w ) { logerror("VIA0: CB1 written with %d!\n", state); } WRITE_LINE_MEMBER ( swyft_state::via0_cb2_w ) { logerror("VIA0: CB2 written with %d!\n", state); } WRITE_LINE_MEMBER ( swyft_state::via0_int_w ) { logerror("VIA0: INT output set to %d!\n", state); } // second via READ8_MEMBER( swyft_state::via1_pa_r ) { logerror(" VIA1: Port A read!\n"); return 0xFF; } WRITE8_MEMBER( swyft_state::via1_pa_w ) { logerror(" VIA1: Port A written with data of 0x%02x!\n", data); } WRITE_LINE_MEMBER ( swyft_state::via1_ca2_w ) { logerror(" VIA1: CA2 written with %d!\n", state); } READ8_MEMBER( swyft_state::via1_pb_r ) { logerror(" VIA1: Port B read!\n"); return 0xFF; } WRITE8_MEMBER( swyft_state::via1_pb_w ) { logerror(" VIA1: Port B written with data of 0x%02x!\n", data); } WRITE_LINE_MEMBER ( swyft_state::via1_cb1_w ) { logerror(" VIA1: CB1 written with %d!\n", state); } WRITE_LINE_MEMBER ( swyft_state::via1_cb2_w ) { logerror(" VIA1: CB2 written with %d!\n", state); } WRITE_LINE_MEMBER ( swyft_state::via1_int_w ) { logerror(" VIA1: INT output set to %d!\n", state); } WRITE_LINE_MEMBER( swyft_state::write_acia_clock ) { m_acia6850->write_txc(state); m_acia6850->write_rxc(state); } MACHINE_CONFIG_START(swyft_state::swyft) /* basic machine hardware */ MCFG_CPU_ADD("maincpu",M68008, XTAL(15'897'600)/2) //MC68008P8, Y1=15.8976Mhz, clock GUESSED at Y1 / 2 MCFG_CPU_PROGRAM_MAP(swyft_mem) MCFG_MACHINE_START_OVERRIDE(swyft_state,swyft) MCFG_MACHINE_RESET_OVERRIDE(swyft_state,swyft) /* video hardware */ MCFG_SCREEN_ADD("screen", RASTER) MCFG_SCREEN_REFRESH_RATE(50) MCFG_SCREEN_VBLANK_TIME(ATTOSECONDS_IN_USEC(2500)) /* not accurate */ MCFG_SCREEN_SIZE(320, 242) MCFG_SCREEN_VISIBLE_AREA(0, 320-1, 0, 242-1) MCFG_SCREEN_UPDATE_DRIVER(swyft_state, screen_update_swyft) MCFG_SCREEN_PALETTE("palette") MCFG_PALETTE_ADD_MONOCHROME("palette") MCFG_VIDEO_START_OVERRIDE(swyft_state,swyft) MCFG_DEVICE_ADD("acia6850", ACIA6850, 0) // acia rx and tx clocks come from one of the VIA pins and are tied together, fix this below? acia e clock comes from 68008 MCFG_DEVICE_ADD("acia_clock", CLOCK, (XTAL(15'897'600)/2)/5) // out e clock from 68008, ~ 10in clocks per out clock MCFG_CLOCK_SIGNAL_HANDLER(WRITELINE(swyft_state, write_acia_clock)) MCFG_DEVICE_ADD("via6522_0", VIA6522, (XTAL(15'897'600)/2)/5) // out e clock from 68008 MCFG_VIA6522_READPA_HANDLER(READ8(swyft_state, via0_pa_r)) MCFG_VIA6522_READPB_HANDLER(READ8(swyft_state, via0_pb_r)) MCFG_VIA6522_WRITEPA_HANDLER(WRITE8(swyft_state, via0_pa_w)) MCFG_VIA6522_WRITEPB_HANDLER(WRITE8(swyft_state, via0_pb_w)) MCFG_VIA6522_CB1_HANDLER(WRITELINE(swyft_state, via0_cb1_w)) MCFG_VIA6522_CA2_HANDLER(WRITELINE(swyft_state, via0_ca2_w)) MCFG_VIA6522_CB2_HANDLER(WRITELINE(swyft_state, via0_cb2_w)) MCFG_VIA6522_IRQ_HANDLER(WRITELINE(swyft_state, via0_int_w)) MCFG_DEVICE_ADD("via6522_1", VIA6522, (XTAL(15'897'600)/2)/5) // out e clock from 68008 MCFG_VIA6522_READPA_HANDLER(READ8(swyft_state, via1_pa_r)) MCFG_VIA6522_READPB_HANDLER(READ8(swyft_state, via1_pb_r)) MCFG_VIA6522_WRITEPA_HANDLER(WRITE8(swyft_state, via1_pa_w)) MCFG_VIA6522_WRITEPB_HANDLER(WRITE8(swyft_state, via1_pb_w)) MCFG_VIA6522_CB1_HANDLER(WRITELINE(swyft_state, via1_cb1_w)) MCFG_VIA6522_CA2_HANDLER(WRITELINE(swyft_state, via1_ca2_w)) MCFG_VIA6522_CB2_HANDLER(WRITELINE(swyft_state, via1_cb2_w)) MCFG_VIA6522_IRQ_HANDLER(WRITELINE(swyft_state, via1_int_w)) MACHINE_CONFIG_END /* ROM definition */ ROM_START( swyft ) ROM_REGION( 0x10000, "maincpu", ROMREGION_ERASEFF ) ROM_SYSTEM_BIOS( 0, "v331", "IAI Swyft Version 331 Firmware") ROMX_LOAD( "331-lo.u30", 0x0000, 0x8000, CRC(d6cc2e2f) SHA1(39ff26c18b1cf589fc48793263f280ef3780cc61), ROM_BIOS(1)) ROMX_LOAD( "331-hi.u31", 0x8000, 0x8000, CRC(4677630a) SHA1(8845d702fa8b8e1a08352f4c59d3076cc2e1307e), ROM_BIOS(1)) /* this version of the swyft code identifies itself at 0x3FCB as version 330 */ ROM_SYSTEM_BIOS( 1, "v330", "IAI Swyft Version 330 Firmware") ROMX_LOAD( "infoapp.lo.u30", 0x0000, 0x8000, CRC(52c1bd66) SHA1(b3266d72970f9d64d94d405965b694f5dcb23bca), ROM_BIOS(2)) ROMX_LOAD( "infoapp.hi.u31", 0x8000, 0x8000, CRC(83505015) SHA1(693c914819dd171114a8c408f399b56b470f6be0), ROM_BIOS(2)) ROM_REGION( 0x4000, "pals", ROMREGION_ERASEFF ) /* Swyft PALs: * The Swyft has four PALs, whose rough function can be derived from their names: * TIMING - state machine for DRAM refresh/access; handles ras/cas and choosing whether the video out shifter or the 68k is accessing ram. also divides clock * DECODE - address decoder for the 68008 * VIDEO - state machine for the video shifter (and vblank/hblank?) * DISK 3.5 - state machine for the floppy drive interface */ /* U9: Timing AMPAL16R4 * * pins: * 111111111000000000 * 987654321987654321 * ??QQQQ??EIIIIIIIIC * |||||||||||||||||\-< /CK input - 15.8976mhz crystal and transistor oscillator * ||||||||||||||||\--< ? * |||||||||||||||\---< ? * ||||||||||||||\----< ? * |||||||||||||\-----< ?<also input to decode pal pin 1, video pal pin 1, source is ?> * ||||||||||||\------< ? * |||||||||||\-------< ? * ||||||||||\--------< ? * |||||||||\---------< ? * ||||||||\----------< /OE input - shorted to GND * |||||||\-----------? ? * ||||||\------------? ? * |||||\------------Q> /ROM_OE (to both eproms through jumper b1 and optionally j9 connector) * ||||\-------------Q? ? * |||\--------------Q? ? * ||\---------------Q> output to decode pal pin 2 * |\----------------->? output? to ram multiplexer 'A' pins * \------------------< ? */ ROM_LOAD( "timing_b.ampal16r4a.u9.jed", 0x0000, 0xb08, CRC(643e6e83) SHA1(7db167883f9d6cf385ce496d08976dc16fc3e2c3)) /* U20: Decode AMPAL16L8 * * pins: * 111111111000000000 * 987654321987654321 * O??????OIIIIIIIIII * |||||||||||||||||\-< TIMING PAL pin 5 * ||||||||||||||||\--< TIMING PAL pin 17 * |||||||||||||||\---< 68008 R/W (pin 30) * ||||||||||||||\----< 68008 /DS (pin 29) * |||||||||||||\-----< 68008 E (pin 38) * ||||||||||||\------< 68008 A19 * |||||||||||\-------< 68008 A18 * ||||||||||\--------< 68008 A17 * |||||||||\---------< 68008 A16 * ||||||||\----------< ? * |||||||\-----------> ? * ||||||\------------? 68008 /VPA (pin 39) * |||||\-------------> /ROM_OE (to both eproms through jumper b1 and optionally j9 connector) * ||||\--------------? ? * |||\---------------? ? * ||\----------------? ? * |\-----------------? goes to j9 connector pin 5 * \------------------< ? */ ROM_LOAD( "decode_e.ampal16l8.u20.jed", 0x1000, 0xb08, CRC(0b1dbd76) SHA1(08c144ad7a7bbdd53eefd271b2f6813f8b3b1594)) ROM_LOAD( "video_2b.ampal16r4.u25.jed", 0x2000, 0xb08, CRC(caf91148) SHA1(3f8ddcb512a1c05395c74ad9a6ba7b87027ce4ec)) ROM_LOAD( "disk_3.5c.ampal16r4.u28.jed", 0x3000, 0xb08, CRC(fd994d02) SHA1(f910ab16587dd248d63017da1e5b37855e4c1a0c)) ROM_END /* Driver */ // YEAR NAME PARENT COMPAT MACHINE INPUT DEVICE INIT COMPANY FULLNAME FLAGS COMP( 1985, swyft, 0, 0, swyft, swyft, swyft_state, 0, "Information Applicance Inc", "Swyft", MACHINE_NOT_WORKING | MACHINE_NO_SOUND )
44.388328
241
0.670291
[ "object", "vector", "model" ]
8b0afb5a6f4b3e843ce01638279fdaa48c7cc370
9,622
hpp
C++
include/UnityEngine/Tilemaps/TileData.hpp
sc2ad/BeatSaber-Quest-Codegen
ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab
[ "Unlicense" ]
23
2020-08-07T04:09:00.000Z
2022-03-31T22:10:29.000Z
include/UnityEngine/Tilemaps/TileData.hpp
sc2ad/BeatSaber-Quest-Codegen
ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab
[ "Unlicense" ]
6
2021-09-29T23:47:31.000Z
2022-03-30T20:49:23.000Z
include/UnityEngine/Tilemaps/TileData.hpp
sc2ad/BeatSaber-Quest-Codegen
ba8acaae541cfe1161e05fbc3bf87f4bc46bc4ab
[ "Unlicense" ]
17
2020-08-20T19:36:52.000Z
2022-03-30T18:28:24.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: System.ValueType #include "System/ValueType.hpp" // Including type: UnityEngine.Color #include "UnityEngine/Color.hpp" // Including type: UnityEngine.Matrix4x4 #include "UnityEngine/Matrix4x4.hpp" // Including type: UnityEngine.Tilemaps.TileFlags #include "UnityEngine/Tilemaps/TileFlags.hpp" // Including type: UnityEngine.Tilemaps.Tile/UnityEngine.Tilemaps.ColliderType #include "UnityEngine/Tilemaps/Tile.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: Sprite class Sprite; // Forward declaring type: GameObject class GameObject; } // Completed forward declares // Type namespace: UnityEngine.Tilemaps namespace UnityEngine::Tilemaps { // Forward declaring type: TileData struct TileData; } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(UnityEngine::Tilemaps::TileData, "UnityEngine.Tilemaps", "TileData"); // Type namespace: UnityEngine.Tilemaps namespace UnityEngine::Tilemaps { // Size: 0x68 #pragma pack(push, 1) // WARNING Layout: Sequential may not be correctly taken into account! // Autogenerated type: UnityEngine.Tilemaps.TileData // [TokenAttribute] Offset: FFFFFFFF // [NativeTypeAttribute] Offset: ED35F4 // [RequiredByNativeCodeAttribute] Offset: ED35F4 struct TileData/*, public System::ValueType*/ { public: #ifdef USE_CODEGEN_FIELDS public: #else protected: #endif // private UnityEngine.Sprite m_Sprite // Size: 0x8 // Offset: 0x0 UnityEngine::Sprite* m_Sprite; // Field size check static_assert(sizeof(UnityEngine::Sprite*) == 0x8); // private UnityEngine.Color m_Color // Size: 0x10 // Offset: 0x8 UnityEngine::Color m_Color; // Field size check static_assert(sizeof(UnityEngine::Color) == 0x10); // private UnityEngine.Matrix4x4 m_Transform // Size: 0x40 // Offset: 0x18 UnityEngine::Matrix4x4 m_Transform; // Field size check static_assert(sizeof(UnityEngine::Matrix4x4) == 0x40); // private UnityEngine.GameObject m_GameObject // Size: 0x8 // Offset: 0x58 UnityEngine::GameObject* m_GameObject; // Field size check static_assert(sizeof(UnityEngine::GameObject*) == 0x8); // private UnityEngine.Tilemaps.TileFlags m_Flags // Size: 0x4 // Offset: 0x60 UnityEngine::Tilemaps::TileFlags m_Flags; // Field size check static_assert(sizeof(UnityEngine::Tilemaps::TileFlags) == 0x4); // private UnityEngine.Tilemaps.Tile/UnityEngine.Tilemaps.ColliderType m_ColliderType // Size: 0x4 // Offset: 0x64 UnityEngine::Tilemaps::Tile::ColliderType m_ColliderType; // Field size check static_assert(sizeof(UnityEngine::Tilemaps::Tile::ColliderType) == 0x4); public: // Creating value type constructor for type: TileData constexpr TileData(UnityEngine::Sprite* m_Sprite_ = {}, UnityEngine::Color m_Color_ = {}, UnityEngine::Matrix4x4 m_Transform_ = {}, UnityEngine::GameObject* m_GameObject_ = {}, UnityEngine::Tilemaps::TileFlags m_Flags_ = {}, UnityEngine::Tilemaps::Tile::ColliderType m_ColliderType_ = {}) noexcept : m_Sprite{m_Sprite_}, m_Color{m_Color_}, m_Transform{m_Transform_}, m_GameObject{m_GameObject_}, m_Flags{m_Flags_}, m_ColliderType{m_ColliderType_} {} // Creating interface conversion operator: operator System::ValueType operator System::ValueType() noexcept { return *reinterpret_cast<System::ValueType*>(this); } // Get instance field reference: private UnityEngine.Sprite m_Sprite UnityEngine::Sprite*& dyn_m_Sprite(); // Get instance field reference: private UnityEngine.Color m_Color UnityEngine::Color& dyn_m_Color(); // Get instance field reference: private UnityEngine.Matrix4x4 m_Transform UnityEngine::Matrix4x4& dyn_m_Transform(); // Get instance field reference: private UnityEngine.GameObject m_GameObject UnityEngine::GameObject*& dyn_m_GameObject(); // Get instance field reference: private UnityEngine.Tilemaps.TileFlags m_Flags UnityEngine::Tilemaps::TileFlags& dyn_m_Flags(); // Get instance field reference: private UnityEngine.Tilemaps.Tile/UnityEngine.Tilemaps.ColliderType m_ColliderType UnityEngine::Tilemaps::Tile::ColliderType& dyn_m_ColliderType(); // public System.Void set_sprite(UnityEngine.Sprite value) // Offset: 0x260A274 void set_sprite(UnityEngine::Sprite* value); // public System.Void set_color(UnityEngine.Color value) // Offset: 0x260A27C void set_color(UnityEngine::Color value); // public System.Void set_transform(UnityEngine.Matrix4x4 value) // Offset: 0x260A288 void set_transform(UnityEngine::Matrix4x4 value); // public System.Void set_gameObject(UnityEngine.GameObject value) // Offset: 0x260A2A4 void set_gameObject(UnityEngine::GameObject* value); // public System.Void set_flags(UnityEngine.Tilemaps.TileFlags value) // Offset: 0x260A2AC void set_flags(UnityEngine::Tilemaps::TileFlags value); // public System.Void set_colliderType(UnityEngine.Tilemaps.Tile/UnityEngine.Tilemaps.ColliderType value) // Offset: 0x260A2B4 void set_colliderType(UnityEngine::Tilemaps::Tile::ColliderType value); }; // UnityEngine.Tilemaps.TileData #pragma pack(pop) static check_size<sizeof(TileData), 100 + sizeof(UnityEngine::Tilemaps::Tile::ColliderType)> __UnityEngine_Tilemaps_TileDataSizeCheck; static_assert(sizeof(TileData) == 0x68); } #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: UnityEngine::Tilemaps::TileData::set_sprite // Il2CppName: set_sprite template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::Tilemaps::TileData::*)(UnityEngine::Sprite*)>(&UnityEngine::Tilemaps::TileData::set_sprite)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("UnityEngine", "Sprite")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::Tilemaps::TileData), "set_sprite", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: UnityEngine::Tilemaps::TileData::set_color // Il2CppName: set_color template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::Tilemaps::TileData::*)(UnityEngine::Color)>(&UnityEngine::Tilemaps::TileData::set_color)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("UnityEngine", "Color")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::Tilemaps::TileData), "set_color", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: UnityEngine::Tilemaps::TileData::set_transform // Il2CppName: set_transform template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::Tilemaps::TileData::*)(UnityEngine::Matrix4x4)>(&UnityEngine::Tilemaps::TileData::set_transform)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("UnityEngine", "Matrix4x4")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::Tilemaps::TileData), "set_transform", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: UnityEngine::Tilemaps::TileData::set_gameObject // Il2CppName: set_gameObject template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::Tilemaps::TileData::*)(UnityEngine::GameObject*)>(&UnityEngine::Tilemaps::TileData::set_gameObject)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("UnityEngine", "GameObject")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::Tilemaps::TileData), "set_gameObject", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: UnityEngine::Tilemaps::TileData::set_flags // Il2CppName: set_flags template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::Tilemaps::TileData::*)(UnityEngine::Tilemaps::TileFlags)>(&UnityEngine::Tilemaps::TileData::set_flags)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("UnityEngine.Tilemaps", "TileFlags")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::Tilemaps::TileData), "set_flags", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } }; // Writing MetadataGetter for method: UnityEngine::Tilemaps::TileData::set_colliderType // Il2CppName: set_colliderType template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::Tilemaps::TileData::*)(UnityEngine::Tilemaps::Tile::ColliderType)>(&UnityEngine::Tilemaps::TileData::set_colliderType)> { static const MethodInfo* get() { static auto* value = &::il2cpp_utils::GetClassFromName("UnityEngine.Tilemaps", "Tile/ColliderType")->byval_arg; return ::il2cpp_utils::FindMethod(classof(UnityEngine::Tilemaps::TileData), "set_colliderType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value}); } };
52.293478
453
0.744856
[ "vector" ]
8b0c0cc883f48d368e50486bf288061777d9bb43
4,239
cpp
C++
libobs-for-HQ-Windows/plugins/decklink/mac/decklink-sdk/DeckLinkAPIDispatch_v7_6.cpp
jayliu1989/HQ
470d9919742412795447c81c3f160278b4418ba7
[ "MIT" ]
45
2019-01-09T01:50:12.000Z
2021-08-09T20:51:22.000Z
libobs-for-HQ-Windows/plugins/decklink/mac/decklink-sdk/DeckLinkAPIDispatch_v7_6.cpp
jayliu1989/HQ
470d9919742412795447c81c3f160278b4418ba7
[ "MIT" ]
8
2019-01-14T10:30:55.000Z
2021-06-16T11:38:39.000Z
libobs-for-HQ-Windows/plugins/decklink/mac/decklink-sdk/DeckLinkAPIDispatch_v7_6.cpp
jayliu1989/HQ
470d9919742412795447c81c3f160278b4418ba7
[ "MIT" ]
24
2019-02-15T17:24:23.000Z
2021-09-09T23:45:19.000Z
/* -LICENSE-START- ** Copyright (c) 2009 Blackmagic Design ** ** Permission is hereby granted, free of charge, to any person or organization ** obtaining a copy of the software and accompanying documentation covered by ** this license (the "Software") to use, reproduce, display, distribute, ** execute, and transmit the Software, and to prepare derivative works of the ** Software, and to permit third-parties to whom the Software is furnished to ** do so, all subject to the following: ** ** The copyright notices in the Software and this entire statement, including ** the above license grant, this restriction and the following disclaimer, ** must be included in all copies of the Software, in whole or in part, and ** all derivative works of the Software, unless such copies or derivative ** works are solely in the form of machine-executable object code generated by ** a source language processor. ** ** 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT ** SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE ** FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ** ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ** DEALINGS IN THE SOFTWARE. ** -LICENSE-END- */ /* DeckLinkAPIDispatch_v7_6.cpp */ #include "DeckLinkAPI_v7_6.h" #include <pthread.h> #define kDeckLinkAPI_BundlePath "/Library/Frameworks/DeckLinkAPI.framework" typedef IDeckLinkIterator* (*CreateIteratorFunc_v7_6)(void); typedef IDeckLinkGLScreenPreviewHelper_v7_6* (*CreateOpenGLScreenPreviewHelperFunc_v7_6)(void); typedef IDeckLinkCocoaScreenPreviewCallback_v7_6* (*CreateCocoaScreenPreviewFunc_v7_6)(void*); typedef IDeckLinkVideoConversion_v7_6* (*CreateVideoConversionInstanceFunc_v7_6)(void); static pthread_once_t gDeckLinkOnceControl = PTHREAD_ONCE_INIT; static CFBundleRef gBundleRef = NULL; static CreateIteratorFunc_v7_6 gCreateIteratorFunc = NULL; static CreateOpenGLScreenPreviewHelperFunc_v7_6 gCreateOpenGLPreviewFunc = NULL; static CreateCocoaScreenPreviewFunc_v7_6 gCreateCocoaPreviewFunc = NULL; static CreateVideoConversionInstanceFunc_v7_6 gCreateVideoConversionFunc = NULL; void InitDeckLinkAPI_v7_6 (void) { CFURLRef bundleURL; bundleURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, CFSTR(kDeckLinkAPI_BundlePath), kCFURLPOSIXPathStyle, true); if (bundleURL != NULL) { gBundleRef = CFBundleCreate(kCFAllocatorDefault, bundleURL); if (gBundleRef != NULL) { gCreateIteratorFunc = (CreateIteratorFunc_v7_6)CFBundleGetFunctionPointerForName(gBundleRef, CFSTR("CreateDeckLinkIteratorInstance")); gCreateOpenGLPreviewFunc = (CreateOpenGLScreenPreviewHelperFunc_v7_6)CFBundleGetFunctionPointerForName(gBundleRef, CFSTR("CreateOpenGLScreenPreviewHelper")); gCreateCocoaPreviewFunc = (CreateCocoaScreenPreviewFunc_v7_6)CFBundleGetFunctionPointerForName(gBundleRef, CFSTR("CreateCocoaScreenPreview")); gCreateVideoConversionFunc = (CreateVideoConversionInstanceFunc_v7_6)CFBundleGetFunctionPointerForName(gBundleRef, CFSTR("CreateVideoConversionInstance")); } CFRelease(bundleURL); } } IDeckLinkIterator* CreateDeckLinkIteratorInstance_v7_6 (void) { pthread_once(&gDeckLinkOnceControl, InitDeckLinkAPI_v7_6); if (gCreateIteratorFunc == NULL) return NULL; return gCreateIteratorFunc(); } IDeckLinkGLScreenPreviewHelper_v7_6* CreateOpenGLScreenPreviewHelper_v7_6 (void) { pthread_once(&gDeckLinkOnceControl, InitDeckLinkAPI_v7_6); if (gCreateOpenGLPreviewFunc == NULL) return NULL; return gCreateOpenGLPreviewFunc(); } IDeckLinkCocoaScreenPreviewCallback_v7_6* CreateCocoaScreenPreview_v7_6 (void* parentView) { pthread_once(&gDeckLinkOnceControl, InitDeckLinkAPI_v7_6); if (gCreateCocoaPreviewFunc == NULL) return NULL; return gCreateCocoaPreviewFunc(parentView); } IDeckLinkVideoConversion_v7_6* CreateVideoConversionInstance_v7_6 (void) { pthread_once(&gDeckLinkOnceControl, InitDeckLinkAPI_v7_6); if (gCreateVideoConversionFunc == NULL) return NULL; return gCreateVideoConversionFunc(); }
39.990566
160
0.809861
[ "object" ]
8b0dbe13930c58eff840551c450417bc734066e5
4,147
cc
C++
Docker/gperftools/src/heap-checker-bcad.cc
cssl-unist/tweezer
3a6c2c65ff61a525150aa2b1ae30b561ac79d241
[ "MIT" ]
7,062
2015-01-28T11:26:14.000Z
2022-03-31T15:40:50.000Z
Docker/gperftools/src/heap-checker-bcad.cc
cssl-unist/tweezer
3a6c2c65ff61a525150aa2b1ae30b561ac79d241
[ "MIT" ]
690
2015-08-16T17:15:57.000Z
2022-03-30T19:59:32.000Z
Docker/gperftools/src/heap-checker-bcad.cc
cssl-unist/tweezer
3a6c2c65ff61a525150aa2b1ae30b561ac79d241
[ "MIT" ]
1,552
2015-01-16T06:20:39.000Z
2022-03-28T13:03:11.000Z
// -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- // Copyright (c) 2005, Google 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 Google 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. // --- // All Rights Reserved. // // Author: Maxim Lifantsev // // A file to ensure that components of heap leak checker run before // all global object constructors and after all global object // destructors. // // This file must be the last library any binary links against. // Otherwise, the heap checker may not be able to run early enough to // catalog all the global objects in your program. If this happens, // and later in the program you allocate memory and have one of these // "uncataloged" global objects point to it, the heap checker will // consider that allocation to be a leak, even though it's not (since // the allocated object is reachable from global data and hence "live"). #include <stdlib.h> // for abort() #include <gperftools/malloc_extension.h> // A dummy variable to refer from heap-checker.cc. This is to make // sure this file is not optimized out by the linker. bool heap_leak_checker_bcad_variable; extern void HeapLeakChecker_AfterDestructors(); // in heap-checker.cc // A helper class to ensure that some components of heap leak checking // can happen before construction and after destruction // of all global/static objects. class HeapLeakCheckerGlobalPrePost { public: HeapLeakCheckerGlobalPrePost() { if (count_ == 0) { // The 'new int' will ensure that we have run an initial malloc // hook, which will set up the heap checker via // MallocHook_InitAtFirstAllocation_HeapLeakChecker. See malloc_hook.cc. // This is done in this roundabout fashion in order to avoid self-deadlock // if we directly called HeapLeakChecker_BeforeConstructors here. delete new int; // This needs to be called before the first allocation of an STL // object, but after libc is done setting up threads (because it // calls setenv, which requires a thread-aware errno). By // putting it here, we hope it's the first bit of code executed // after the libc global-constructor code. MallocExtension::Initialize(); } ++count_; } ~HeapLeakCheckerGlobalPrePost() { if (count_ <= 0) abort(); --count_; if (count_ == 0) HeapLeakChecker_AfterDestructors(); } private: // Counter of constructions/destructions of objects of this class // (just in case there are more than one of them). static int count_; }; int HeapLeakCheckerGlobalPrePost::count_ = 0; // The early-construction/late-destruction global object. static const HeapLeakCheckerGlobalPrePost heap_leak_checker_global_pre_post;
44.117021
80
0.740776
[ "object" ]
8b0ec9dd4dcfec7b1f0fdf1171d710f97203bf28
1,516
cpp
C++
src/SlotManager.cpp
nexquery/samp-textdraw-streamer
085c532c103eabe1e09e8a3112f74668dbc10121
[ "Apache-2.0" ]
4
2021-11-25T11:19:15.000Z
2022-02-05T10:55:03.000Z
src/SlotManager.cpp
nexquery/samp-textdraw-streamer
085c532c103eabe1e09e8a3112f74668dbc10121
[ "Apache-2.0" ]
3
2021-07-14T08:33:24.000Z
2021-11-26T21:58:45.000Z
src/SlotManager.cpp
nexquery/Textdraw-Streamer
085c532c103eabe1e09e8a3112f74668dbc10121
[ "Apache-2.0" ]
2
2021-09-23T03:55:32.000Z
2021-12-19T02:49:21.000Z
/* * Copyright (C) 2020 Burak (NexoR) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "SlotManager.h" std::map<int, std::priority_queue<size_t, std::vector<size_t>, std::greater<size_t>>> SlotManager::Slot; std::map<int, size_t> SlotManager::Slot_Counter; size_t SlotManager::Free_ID(size_t playerid) { int id = Start_ID; if (Slot[playerid].empty()) { id = Slot_Counter[playerid]++; } else { id = Slot[playerid].top(); Slot[playerid].pop(); } return id; } void SlotManager::Remove_ID(size_t playerid, size_t id) { Slot[playerid].push(id); } void SlotManager::Reset_ID(size_t playerid) { Slot_Counter[playerid] = Start_ID; Slot[playerid] = std::priority_queue<size_t, std::vector<size_t>, std::greater<size_t>>(); } void SlotManager::Reset_All_ID() { for (size_t i = 0; i < MAX_PLAYERS; i++) { Slot_Counter[i] = Start_ID; Slot[i] = std::priority_queue<size_t, std::vector<size_t>, std::greater<size_t>>(); } }
27.563636
105
0.684037
[ "vector" ]
8b1030f360786b0c300a1a56d6dae5cf23e6df36
21,878
cpp
C++
lib/Tooling/InterpolatingCompilationDatabase.cpp
codyrutscher/Clang
f85f82b117c43ff133baabae849080544fa0d2b3
[ "Apache-2.0", "MIT" ]
1
2020-01-15T02:07:41.000Z
2020-01-15T02:07:41.000Z
lib/Tooling/InterpolatingCompilationDatabase.cpp
codyrutscher/Clang
f85f82b117c43ff133baabae849080544fa0d2b3
[ "Apache-2.0", "MIT" ]
2
2018-06-18T13:28:43.000Z
2018-08-15T17:34:55.000Z
lib/Tooling/InterpolatingCompilationDatabase.cpp
codyrutscher/Clang
f85f82b117c43ff133baabae849080544fa0d2b3
[ "Apache-2.0", "MIT" ]
null
null
null
//===- InterpolatingCompilationDatabase.cpp ---------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // InterpolatingCompilationDatabase wraps another CompilationDatabase and // attempts to heuristically determine appropriate compile commands for files // that are not included, such as headers or newly created files. // // Motivating cases include: // Header files that live next to their implementation files. These typically // share a base filename. (libclang/CXString.h, libclang/CXString.cpp). // Some projects separate headers from includes. Filenames still typically // match, maybe other path segments too. (include/llvm/IR/Use.h, lib/IR/Use.cc). // Matches are sometimes only approximate (Sema.h, SemaDecl.cpp). This goes // for directories too (Support/Unix/Process.inc, lib/Support/Process.cpp). // Even if we can't find a "right" compile command, even a random one from // the project will tend to get important flags like -I and -x right. // // We "borrow" the compile command for the closest available file: // - points are awarded if the filename matches (ignoring extension) // - points are awarded if the directory structure matches // - ties are broken by length of path prefix match // // The compile command is adjusted, replacing the filename and removing output // file arguments. The -x and -std flags may be affected too. // // Source language is a tricky issue: is it OK to use a .c file's command // for building a .cc file? What language is a .h file in? // - We only consider compile commands for c-family languages as candidates. // - For files whose language is implied by the filename (e.g. .m, .hpp) // we prefer candidates from the same language. // If we must cross languages, we drop any -x and -std flags. // - For .h files, candidates from any c-family language are acceptable. // We use the candidate's language, inserting e.g. -x c++-header. // // This class is only useful when wrapping databases that can enumerate all // their compile commands. If getAllFilenames() is empty, no inference occurs. // //===----------------------------------------------------------------------===// #include "clang/Driver/Options.h" #include "clang/Driver/Types.h" #include "clang/Frontend/LangStandard.h" #include "clang/Tooling/CompilationDatabase.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Option/ArgList.h" #include "llvm/Option/OptTable.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Path.h" #include "llvm/Support/StringSaver.h" #include "llvm/Support/raw_ostream.h" #include <memory> namespace clang { namespace tooling { namespace { using namespace llvm; namespace types = clang::driver::types; namespace path = llvm::sys::path; // The length of the prefix these two strings have in common. size_t matchingPrefix(StringRef L, StringRef R) { size_t Limit = std::min(L.size(), R.size()); for (size_t I = 0; I < Limit; ++I) if (L[I] != R[I]) return I; return Limit; } // A comparator for searching SubstringWithIndexes with std::equal_range etc. // Optionaly prefix semantics: compares equal if the key is a prefix. template <bool Prefix> struct Less { bool operator()(StringRef Key, std::pair<StringRef, size_t> Value) const { StringRef V = Prefix ? Value.first.substr(0, Key.size()) : Value.first; return Key < V; } bool operator()(std::pair<StringRef, size_t> Value, StringRef Key) const { StringRef V = Prefix ? Value.first.substr(0, Key.size()) : Value.first; return V < Key; } }; // Infer type from filename. If we might have gotten it wrong, set *Certain. // *.h will be inferred as a C header, but not certain. types::ID guessType(StringRef Filename, bool *Certain = nullptr) { // path::extension is ".cpp", lookupTypeForExtension wants "cpp". auto Lang = types::lookupTypeForExtension(path::extension(Filename).substr(1)); if (Certain) *Certain = Lang != types::TY_CHeader && Lang != types::TY_INVALID; return Lang; } // Return Lang as one of the canonical supported types. // e.g. c-header --> c; fortran --> TY_INVALID static types::ID foldType(types::ID Lang) { switch (Lang) { case types::TY_C: case types::TY_CHeader: return types::TY_C; case types::TY_ObjC: case types::TY_ObjCHeader: return types::TY_ObjC; case types::TY_CXX: case types::TY_CXXHeader: return types::TY_CXX; case types::TY_ObjCXX: case types::TY_ObjCXXHeader: return types::TY_ObjCXX; default: return types::TY_INVALID; } } // A CompileCommand that can be applied to another file. struct TransferableCommand { // Flags that should not apply to all files are stripped from CommandLine. CompileCommand Cmd; // Language detected from -x or the filename. Never TY_INVALID. Optional<types::ID> Type; // Standard specified by -std. LangStandard::Kind Std = LangStandard::lang_unspecified; // Whether the command line is for the cl-compatible driver. bool ClangCLMode; TransferableCommand(CompileCommand C) : Cmd(std::move(C)), Type(guessType(Cmd.Filename)), ClangCLMode(checkIsCLMode(Cmd.CommandLine)) { std::vector<std::string> OldArgs = std::move(Cmd.CommandLine); Cmd.CommandLine.clear(); // Wrap the old arguments in an InputArgList. llvm::opt::InputArgList ArgList; { SmallVector<const char *, 16> TmpArgv; for (const std::string &S : OldArgs) TmpArgv.push_back(S.c_str()); ArgList = {TmpArgv.begin(), TmpArgv.end()}; } // Parse the old args in order to strip out and record unwanted flags. // We parse each argument individually so that we can retain the exact // spelling of each argument; re-rendering is lossy for aliased flags. // E.g. in CL mode, /W4 maps to -Wall. auto OptTable = clang::driver::createDriverOptTable(); Cmd.CommandLine.emplace_back(OldArgs.front()); for (unsigned Pos = 1; Pos < OldArgs.size();) { using namespace driver::options; const unsigned OldPos = Pos; std::unique_ptr<llvm::opt::Arg> Arg(OptTable->ParseOneArg( ArgList, Pos, /* Include */ClangCLMode ? CoreOption | CLOption : 0, /* Exclude */ClangCLMode ? 0 : CLOption)); if (!Arg) continue; const llvm::opt::Option &Opt = Arg->getOption(); // Strip input and output files. if (Opt.matches(OPT_INPUT) || Opt.matches(OPT_o) || (ClangCLMode && (Opt.matches(OPT__SLASH_Fa) || Opt.matches(OPT__SLASH_Fe) || Opt.matches(OPT__SLASH_Fi) || Opt.matches(OPT__SLASH_Fo)))) continue; // Strip -x, but record the overridden language. if (const auto GivenType = tryParseTypeArg(*Arg)) { Type = *GivenType; continue; } // Strip -std, but record the value. if (const auto GivenStd = tryParseStdArg(*Arg)) { if (*GivenStd != LangStandard::lang_unspecified) Std = *GivenStd; continue; } Cmd.CommandLine.insert(Cmd.CommandLine.end(), OldArgs.data() + OldPos, OldArgs.data() + Pos); } if (Std != LangStandard::lang_unspecified) // -std take precedence over -x Type = toType(LangStandard::getLangStandardForKind(Std).getLanguage()); Type = foldType(*Type); // The contract is to store None instead of TY_INVALID. if (Type == types::TY_INVALID) Type = llvm::None; } // Produce a CompileCommand for \p filename, based on this one. CompileCommand transferTo(StringRef Filename) const { CompileCommand Result = Cmd; Result.Filename = Filename; bool TypeCertain; auto TargetType = guessType(Filename, &TypeCertain); // If the filename doesn't determine the language (.h), transfer with -x. if ((!TargetType || !TypeCertain) && Type) { // Use *Type, or its header variant if the file is a header. // Treat no/invalid extension as header (e.g. C++ standard library). TargetType = (!TargetType || types::onlyPrecompileType(TargetType)) // header? ? types::lookupHeaderTypeForSourceType(*Type) : *Type; if (ClangCLMode) { const StringRef Flag = toCLFlag(TargetType); if (!Flag.empty()) Result.CommandLine.push_back(Flag); } else { Result.CommandLine.push_back("-x"); Result.CommandLine.push_back(types::getTypeName(TargetType)); } } // --std flag may only be transferred if the language is the same. // We may consider "translating" these, e.g. c++11 -> c11. if (Std != LangStandard::lang_unspecified && foldType(TargetType) == Type) { Result.CommandLine.emplace_back(( llvm::Twine(ClangCLMode ? "/std:" : "-std=") + LangStandard::getLangStandardForKind(Std).getName()).str()); } Result.CommandLine.push_back(Filename); Result.Heuristic = "inferred from " + Cmd.Filename; return Result; } private: // Determine whether the given command line is intended for the CL driver. static bool checkIsCLMode(ArrayRef<std::string> CmdLine) { // First look for --driver-mode. for (StringRef S : llvm::reverse(CmdLine)) { if (S.consume_front("--driver-mode=")) return S == "cl"; } // Otherwise just check the clang executable file name. return llvm::sys::path::stem(CmdLine.front()).endswith_lower("cl"); } // Map the language from the --std flag to that of the -x flag. static types::ID toType(InputKind::Language Lang) { switch (Lang) { case InputKind::C: return types::TY_C; case InputKind::CXX: return types::TY_CXX; case InputKind::ObjC: return types::TY_ObjC; case InputKind::ObjCXX: return types::TY_ObjCXX; default: return types::TY_INVALID; } } // Convert a file type to the matching CL-style type flag. static StringRef toCLFlag(types::ID Type) { switch (Type) { case types::TY_C: case types::TY_CHeader: return "/TC"; case types::TY_CXX: case types::TY_CXXHeader: return "/TP"; default: return StringRef(); } } // Try to interpret the argument as a type specifier, e.g. '-x'. Optional<types::ID> tryParseTypeArg(const llvm::opt::Arg &Arg) { const llvm::opt::Option &Opt = Arg.getOption(); using namespace driver::options; if (ClangCLMode) { if (Opt.matches(OPT__SLASH_TC) || Opt.matches(OPT__SLASH_Tc)) return types::TY_C; if (Opt.matches(OPT__SLASH_TP) || Opt.matches(OPT__SLASH_Tp)) return types::TY_CXX; } else { if (Opt.matches(driver::options::OPT_x)) return types::lookupTypeForTypeSpecifier(Arg.getValue()); } return None; } // Try to interpret the argument as '-std='. Optional<LangStandard::Kind> tryParseStdArg(const llvm::opt::Arg &Arg) { using namespace driver::options; if (Arg.getOption().matches(ClangCLMode ? OPT__SLASH_std : OPT_std_EQ)) { return llvm::StringSwitch<LangStandard::Kind>(Arg.getValue()) #define LANGSTANDARD(id, name, lang, ...) .Case(name, LangStandard::lang_##id) #define LANGSTANDARD_ALIAS(id, alias) .Case(alias, LangStandard::lang_##id) #include "clang/Frontend/LangStandards.def" #undef LANGSTANDARD_ALIAS #undef LANGSTANDARD .Default(LangStandard::lang_unspecified); } return None; } }; // Given a filename, FileIndex picks the best matching file from the underlying // DB. This is the proxy file whose CompileCommand will be reused. The // heuristics incorporate file name, extension, and directory structure. // Strategy: // - Build indexes of each of the substrings we want to look up by. // These indexes are just sorted lists of the substrings. // - Each criterion corresponds to a range lookup into the index, so we only // need O(log N) string comparisons to determine scores. // // Apart from path proximity signals, also takes file extensions into account // when scoring the candidates. class FileIndex { public: FileIndex(std::vector<std::string> Files) : OriginalPaths(std::move(Files)), Strings(Arena) { // Sort commands by filename for determinism (index is a tiebreaker later). llvm::sort(OriginalPaths); Paths.reserve(OriginalPaths.size()); Types.reserve(OriginalPaths.size()); Stems.reserve(OriginalPaths.size()); for (size_t I = 0; I < OriginalPaths.size(); ++I) { StringRef Path = Strings.save(StringRef(OriginalPaths[I]).lower()); Paths.emplace_back(Path, I); Types.push_back(foldType(guessType(Path))); Stems.emplace_back(sys::path::stem(Path), I); auto Dir = ++sys::path::rbegin(Path), DirEnd = sys::path::rend(Path); for (int J = 0; J < DirectorySegmentsIndexed && Dir != DirEnd; ++J, ++Dir) if (Dir->size() > ShortDirectorySegment) // not trivial ones Components.emplace_back(*Dir, I); } llvm::sort(Paths); llvm::sort(Stems); llvm::sort(Components); } bool empty() const { return Paths.empty(); } // Returns the path for the file that best fits OriginalFilename. // Candidates with extensions matching PreferLanguage will be chosen over // others (unless it's TY_INVALID, or all candidates are bad). StringRef chooseProxy(StringRef OriginalFilename, types::ID PreferLanguage) const { assert(!empty() && "need at least one candidate!"); std::string Filename = OriginalFilename.lower(); auto Candidates = scoreCandidates(Filename); std::pair<size_t, int> Best = pickWinner(Candidates, Filename, PreferLanguage); DEBUG_WITH_TYPE( "interpolate", llvm::dbgs() << "interpolate: chose " << OriginalPaths[Best.first] << " as proxy for " << OriginalFilename << " preferring " << (PreferLanguage == types::TY_INVALID ? "none" : types::getTypeName(PreferLanguage)) << " score=" << Best.second << "\n"); return OriginalPaths[Best.first]; } private: using SubstringAndIndex = std::pair<StringRef, size_t>; // Directory matching parameters: we look at the last two segments of the // parent directory (usually the semantically significant ones in practice). // We search only the last four of each candidate (for efficiency). constexpr static int DirectorySegmentsIndexed = 4; constexpr static int DirectorySegmentsQueried = 2; constexpr static int ShortDirectorySegment = 1; // Only look at longer names. // Award points to candidate entries that should be considered for the file. // Returned keys are indexes into paths, and the values are (nonzero) scores. DenseMap<size_t, int> scoreCandidates(StringRef Filename) const { // Decompose Filename into the parts we care about. // /some/path/complicated/project/Interesting.h // [-prefix--][---dir---] [-dir-] [--stem---] StringRef Stem = sys::path::stem(Filename); llvm::SmallVector<StringRef, DirectorySegmentsQueried> Dirs; llvm::StringRef Prefix; auto Dir = ++sys::path::rbegin(Filename), DirEnd = sys::path::rend(Filename); for (int I = 0; I < DirectorySegmentsQueried && Dir != DirEnd; ++I, ++Dir) { if (Dir->size() > ShortDirectorySegment) Dirs.push_back(*Dir); Prefix = Filename.substr(0, Dir - DirEnd); } // Now award points based on lookups into our various indexes. DenseMap<size_t, int> Candidates; // Index -> score. auto Award = [&](int Points, ArrayRef<SubstringAndIndex> Range) { for (const auto &Entry : Range) Candidates[Entry.second] += Points; }; // Award one point if the file's basename is a prefix of the candidate, // and another if it's an exact match (so exact matches get two points). Award(1, indexLookup</*Prefix=*/true>(Stem, Stems)); Award(1, indexLookup</*Prefix=*/false>(Stem, Stems)); // For each of the last few directories in the Filename, award a point // if it's present in the candidate. for (StringRef Dir : Dirs) Award(1, indexLookup</*Prefix=*/false>(Dir, Components)); // Award one more point if the whole rest of the path matches. if (sys::path::root_directory(Prefix) != Prefix) Award(1, indexLookup</*Prefix=*/true>(Prefix, Paths)); return Candidates; } // Pick a single winner from the set of scored candidates. // Returns (index, score). std::pair<size_t, int> pickWinner(const DenseMap<size_t, int> &Candidates, StringRef Filename, types::ID PreferredLanguage) const { struct ScoredCandidate { size_t Index; bool Preferred; int Points; size_t PrefixLength; }; // Choose the best candidate by (preferred, points, prefix length, alpha). ScoredCandidate Best = {size_t(-1), false, 0, 0}; for (const auto &Candidate : Candidates) { ScoredCandidate S; S.Index = Candidate.first; S.Preferred = PreferredLanguage == types::TY_INVALID || PreferredLanguage == Types[S.Index]; S.Points = Candidate.second; if (!S.Preferred && Best.Preferred) continue; if (S.Preferred == Best.Preferred) { if (S.Points < Best.Points) continue; if (S.Points == Best.Points) { S.PrefixLength = matchingPrefix(Filename, Paths[S.Index].first); if (S.PrefixLength < Best.PrefixLength) continue; // hidden heuristics should at least be deterministic! if (S.PrefixLength == Best.PrefixLength) if (S.Index > Best.Index) continue; } } // PrefixLength was only set above if actually needed for a tiebreak. // But it definitely needs to be set to break ties in the future. S.PrefixLength = matchingPrefix(Filename, Paths[S.Index].first); Best = S; } // Edge case: no candidate got any points. // We ignore PreferredLanguage at this point (not ideal). if (Best.Index == size_t(-1)) return {longestMatch(Filename, Paths).second, 0}; return {Best.Index, Best.Points}; } // Returns the range within a sorted index that compares equal to Key. // If Prefix is true, it's instead the range starting with Key. template <bool Prefix> ArrayRef<SubstringAndIndex> indexLookup(StringRef Key, ArrayRef<SubstringAndIndex> Idx) const { // Use pointers as iteratiors to ease conversion of result to ArrayRef. auto Range = std::equal_range(Idx.data(), Idx.data() + Idx.size(), Key, Less<Prefix>()); return {Range.first, Range.second}; } // Performs a point lookup into a nonempty index, returning a longest match. SubstringAndIndex longestMatch(StringRef Key, ArrayRef<SubstringAndIndex> Idx) const { assert(!Idx.empty()); // Longest substring match will be adjacent to a direct lookup. auto It = std::lower_bound(Idx.begin(), Idx.end(), SubstringAndIndex{Key, 0}); if (It == Idx.begin()) return *It; if (It == Idx.end()) return *--It; // Have to choose between It and It-1 size_t Prefix = matchingPrefix(Key, It->first); size_t PrevPrefix = matchingPrefix(Key, (It - 1)->first); return Prefix > PrevPrefix ? *It : *--It; } // Original paths, everything else is in lowercase. std::vector<std::string> OriginalPaths; BumpPtrAllocator Arena; StringSaver Strings; // Indexes of candidates by certain substrings. // String is lowercase and sorted, index points into OriginalPaths. std::vector<SubstringAndIndex> Paths; // Full path. // Lang types obtained by guessing on the corresponding path. I-th element is // a type for the I-th path. std::vector<types::ID> Types; std::vector<SubstringAndIndex> Stems; // Basename, without extension. std::vector<SubstringAndIndex> Components; // Last path components. }; // The actual CompilationDatabase wrapper delegates to its inner database. // If no match, looks up a proxy file in FileIndex and transfers its // command to the requested file. class InterpolatingCompilationDatabase : public CompilationDatabase { public: InterpolatingCompilationDatabase(std::unique_ptr<CompilationDatabase> Inner) : Inner(std::move(Inner)), Index(this->Inner->getAllFiles()) {} std::vector<CompileCommand> getCompileCommands(StringRef Filename) const override { auto Known = Inner->getCompileCommands(Filename); if (Index.empty() || !Known.empty()) return Known; bool TypeCertain; auto Lang = guessType(Filename, &TypeCertain); if (!TypeCertain) Lang = types::TY_INVALID; auto ProxyCommands = Inner->getCompileCommands(Index.chooseProxy(Filename, foldType(Lang))); if (ProxyCommands.empty()) return {}; return {TransferableCommand(ProxyCommands[0]).transferTo(Filename)}; } std::vector<std::string> getAllFiles() const override { return Inner->getAllFiles(); } std::vector<CompileCommand> getAllCompileCommands() const override { return Inner->getAllCompileCommands(); } private: std::unique_ptr<CompilationDatabase> Inner; FileIndex Index; }; } // namespace std::unique_ptr<CompilationDatabase> inferMissingCompileCommands(std::unique_ptr<CompilationDatabase> Inner) { return llvm::make_unique<InterpolatingCompilationDatabase>(std::move(Inner)); } } // namespace tooling } // namespace clang
39.705989
80
0.662538
[ "vector" ]
8b10fd8b2f0003f7723ad940693473f72f7a4504
103,289
cpp
C++
tests/tests/operation_tests2.cpp
crexonline/bitshares-core
3e74426d301f098eb6306309b3dd80bb830a5c49
[ "MIT" ]
14
2018-05-13T06:57:25.000Z
2019-03-14T01:40:47.000Z
tests/tests/operation_tests2.cpp
blockchain7/bitshares-core
6218cdf1fcf5310cace81f86a35044ef6b42abec
[ "MIT" ]
3
2018-05-30T06:50:06.000Z
2019-03-08T04:48:40.000Z
tests/tests/operation_tests2.cpp
blockchain7/bitshares-core
6218cdf1fcf5310cace81f86a35044ef6b42abec
[ "MIT" ]
8
2018-05-30T06:32:08.000Z
2020-06-01T06:38:25.000Z
/* * Copyright (c) 2015 Cryptonomex, Inc., and contributors. * * The MIT 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. */ #include <boost/test/unit_test.hpp> #include <graphene/chain/database.hpp> #include <graphene/chain/hardfork.hpp> #include <graphene/chain/balance_object.hpp> #include <graphene/chain/budget_record_object.hpp> #include <graphene/chain/committee_member_object.hpp> #include <graphene/chain/market_object.hpp> #include <graphene/chain/withdraw_permission_object.hpp> #include <graphene/chain/witness_object.hpp> #include <graphene/chain/worker_object.hpp> #include <graphene/utilities/tempdir.hpp> #include <fc/crypto/digest.hpp> #include "../common/database_fixture.hpp" using namespace graphene::chain; using namespace graphene::chain::test; BOOST_FIXTURE_TEST_SUITE( operation_tests, database_fixture ) /*** * A descriptor of a particular withdrawal period */ struct withdrawal_period_descriptor { withdrawal_period_descriptor(const time_point_sec start, const time_point_sec end, const asset available, const asset claimed) : period_start_time(start), period_end_time(end), available_this_period(available), claimed_this_period(claimed) {} // Start of period time_point_sec period_start_time; // End of period time_point_sec period_end_time; // Quantify how much is still available to be withdrawn during this period asset available_this_period; // Quantify how much has already been claimed during this period asset claimed_this_period; string const to_string() const { string asset_id = fc::to_string(available_this_period.asset_id.space_id) + "." + fc::to_string(available_this_period.asset_id.type_id) + "." + fc::to_string(available_this_period.asset_id.instance.value); string text = fc::to_string(available_this_period.amount.value) + " " + asset_id + " is available from " + period_start_time.to_iso_string() + " to " + period_end_time.to_iso_string(); return text; } }; /*** * Get a description of the current withdrawal period * @param current_time Current time * @return A description of the current period */ withdrawal_period_descriptor current_period(const withdraw_permission_object& permit, fc::time_point_sec current_time) { // @todo [6] Is there a potential race condition where a call to available_this_period might become out of sync with this function's later use of period start time? asset available = permit.available_this_period(current_time); asset claimed = asset(permit.withdrawal_limit.amount - available.amount, permit.withdrawal_limit.asset_id); auto periods = (current_time - permit.period_start_time).to_seconds() / permit.withdrawal_period_sec; time_point_sec current_period_start = permit.period_start_time + (periods * permit.withdrawal_period_sec); time_point_sec current_period_end = current_period_start + permit.withdrawal_period_sec; withdrawal_period_descriptor descriptor = withdrawal_period_descriptor(current_period_start, current_period_end, available, claimed); return descriptor; } /** * This auxiliary test is used for two purposes: * (a) it checks the creation of withdrawal claims, * (b) it is used as a precursor for tests that evaluate withdrawal claims. * * NOTE: This test verifies proper withdrawal claim behavior * as it occurred before (for backward compatibility) * Issue #23 was addressed. * That issue is concerned with ensuring that the first claim * can occur before the first withdrawal period. */ BOOST_AUTO_TEST_CASE( withdraw_permission_create_before_hardfork_23 ) { try { auto nathan_private_key = generate_private_key("nathan"); auto dan_private_key = generate_private_key("dan"); account_id_type nathan_id = create_account("nathan", nathan_private_key.get_public_key()).id; account_id_type dan_id = create_account("dan", dan_private_key.get_public_key()).id; transfer(account_id_type(), nathan_id, asset(1000)); generate_block(); set_expiration( db, trx ); { withdraw_permission_create_operation op; op.authorized_account = dan_id; op.withdraw_from_account = nathan_id; op.withdrawal_limit = asset(5); op.withdrawal_period_sec = fc::hours(1).to_seconds(); op.periods_until_expiration = 5; op.period_start_time = db.head_block_time() + db.get_global_properties().parameters.block_interval*5; // 5 blocks after current blockchain time trx.operations.push_back(op); REQUIRE_OP_VALIDATION_FAILURE(op, withdrawal_limit, asset()); REQUIRE_OP_VALIDATION_FAILURE(op, periods_until_expiration, 0); REQUIRE_OP_VALIDATION_FAILURE(op, withdraw_from_account, dan_id); REQUIRE_OP_VALIDATION_FAILURE(op, withdrawal_period_sec, 0); REQUIRE_THROW_WITH_VALUE(op, withdrawal_limit, asset(10, asset_id_type(10))); REQUIRE_THROW_WITH_VALUE(op, authorized_account, account_id_type(1000)); REQUIRE_THROW_WITH_VALUE(op, period_start_time, fc::time_point_sec(10000)); REQUIRE_THROW_WITH_VALUE(op, withdrawal_period_sec, 1); trx.operations.back() = op; } sign( trx, nathan_private_key ); db.push_transaction( trx ); trx.clear(); } FC_LOG_AND_RETHROW() } /** * This auxiliary test is used for two purposes: * (a) it checks the creation of withdrawal claims, * (b) it is used as a precursor for tests that evaluate withdrawal claims. * * NOTE: This test verifies proper withdrawal claim behavior * as it should occur after Issue #23 is addressed. * That issue is concerned with ensuring that the first claim * can occur before the first withdrawal period. */ BOOST_AUTO_TEST_CASE( withdraw_permission_create_after_hardfork_23 ) { try { auto nathan_private_key = generate_private_key("nathan"); auto dan_private_key = generate_private_key("dan"); account_id_type nathan_id = create_account("nathan", nathan_private_key.get_public_key()).id; account_id_type dan_id = create_account("dan", dan_private_key.get_public_key()).id; transfer(account_id_type(), nathan_id, asset(1000)); generate_block(); set_expiration( db, trx ); { withdraw_permission_create_operation op; op.authorized_account = dan_id; op.withdraw_from_account = nathan_id; op.withdrawal_limit = asset(5); op.withdrawal_period_sec = fc::hours(1).to_seconds(); op.periods_until_expiration = 5; op.period_start_time = HARDFORK_23_TIME + db.get_global_properties().parameters.block_interval*5; // 5 blocks after fork time trx.operations.push_back(op); REQUIRE_OP_VALIDATION_FAILURE(op, withdrawal_limit, asset()); REQUIRE_OP_VALIDATION_FAILURE(op, periods_until_expiration, 0); REQUIRE_OP_VALIDATION_FAILURE(op, withdraw_from_account, dan_id); REQUIRE_OP_VALIDATION_FAILURE(op, withdrawal_period_sec, 0); REQUIRE_THROW_WITH_VALUE(op, withdrawal_limit, asset(10, asset_id_type(10))); REQUIRE_THROW_WITH_VALUE(op, authorized_account, account_id_type(1000)); REQUIRE_THROW_WITH_VALUE(op, period_start_time, fc::time_point_sec(10000)); REQUIRE_THROW_WITH_VALUE(op, withdrawal_period_sec, 1); trx.operations.back() = op; } sign( trx, nathan_private_key ); db.push_transaction( trx ); trx.clear(); } FC_LOG_AND_RETHROW() } /** * Test the claims of withdrawals both before and during * authorized withdrawal periods. * NOTE: The simulated elapse of blockchain time through the use of * generate_blocks() must be carefully used in order to simulate * this test. * NOTE: This test verifies proper withdrawal claim behavior * as it occurred before (for backward compatibility) * Issue #23 was addressed. * That issue is concerned with ensuring that the first claim * can occur before the first withdrawal period. */ BOOST_AUTO_TEST_CASE( withdraw_permission_test_before_hardfork_23 ) { try { INVOKE(withdraw_permission_create_before_hardfork_23); auto nathan_private_key = generate_private_key("nathan"); auto dan_private_key = generate_private_key("dan"); account_id_type nathan_id = get_account("nathan").id; account_id_type dan_id = get_account("dan").id; withdraw_permission_id_type permit; set_expiration( db, trx ); fc::time_point_sec first_start_time; { const withdraw_permission_object& permit_object = permit(db); BOOST_CHECK(permit_object.authorized_account == dan_id); BOOST_CHECK(permit_object.withdraw_from_account == nathan_id); BOOST_CHECK(permit_object.period_start_time > db.head_block_time()); first_start_time = permit_object.period_start_time; BOOST_CHECK(permit_object.withdrawal_limit == asset(5)); BOOST_CHECK(permit_object.withdrawal_period_sec == fc::hours(1).to_seconds()); BOOST_CHECK(permit_object.expiration == first_start_time + permit_object.withdrawal_period_sec*5 ); } generate_blocks(2); // Still before the first period, but BEFORE the real time during which "early" claims are checked { withdraw_permission_claim_operation op; op.withdraw_permission = permit; op.withdraw_from_account = nathan_id; op.withdraw_to_account = dan_id; op.amount_to_withdraw = asset(1); set_expiration( db, trx ); trx.operations.push_back(op); sign( trx, dan_private_key ); // Transaction should be signed to be valid // This operation/transaction will be pushed early/before the first // withdrawal period // However, this will not cause an exception prior to HARDFORK_23_TIME // because withdrawaing before that the first period was acceptable // before the fix PUSH_TX( db, trx ); // <-- Claim #1 //Get to the actual withdrawal period bool miss_intermediate_blocks = false; // Required to have generate_blocks() elapse flush to the time of interest generate_blocks(first_start_time, miss_intermediate_blocks); set_expiration( db, trx ); REQUIRE_THROW_WITH_VALUE(op, withdraw_permission, withdraw_permission_id_type(5)); REQUIRE_THROW_WITH_VALUE(op, withdraw_from_account, dan_id); REQUIRE_THROW_WITH_VALUE(op, withdraw_from_account, account_id_type()); REQUIRE_THROW_WITH_VALUE(op, withdraw_to_account, nathan_id); REQUIRE_THROW_WITH_VALUE(op, withdraw_to_account, account_id_type()); REQUIRE_THROW_WITH_VALUE(op, amount_to_withdraw, asset(10)); REQUIRE_THROW_WITH_VALUE(op, amount_to_withdraw, asset(6)); set_expiration( db, trx ); trx.clear(); trx.operations.push_back(op); sign( trx, dan_private_key ); PUSH_TX( db, trx ); // <-- Claim #2 // would be legal on its own, but doesn't work because trx already withdrew REQUIRE_THROW_WITH_VALUE(op, amount_to_withdraw, asset(5)); // Make sure we can withdraw again this period, as long as we're not exceeding the periodic limit trx.clear(); // withdraw 1 trx.operations = {op}; // make it different from previous trx so it's non-duplicate trx.expiration += fc::seconds(1); sign( trx, dan_private_key ); PUSH_TX( db, trx ); // <-- Claim #3 trx.clear(); } // Account for three (3) claims of one (1) unit BOOST_CHECK_EQUAL(get_balance(nathan_id, asset_id_type()), 997); BOOST_CHECK_EQUAL(get_balance(dan_id, asset_id_type()), 3); { const withdraw_permission_object& permit_object = permit(db); BOOST_CHECK(permit_object.authorized_account == dan_id); BOOST_CHECK(permit_object.withdraw_from_account == nathan_id); BOOST_CHECK(permit_object.period_start_time == first_start_time); BOOST_CHECK(permit_object.withdrawal_limit == asset(5)); BOOST_CHECK(permit_object.withdrawal_period_sec == fc::hours(1).to_seconds()); BOOST_CHECK_EQUAL(permit_object.claimed_this_period.value, 3 ); // <-- Account for three (3) claims of one (1) unit BOOST_CHECK(permit_object.expiration == first_start_time + 5*permit_object.withdrawal_period_sec); generate_blocks(first_start_time + permit_object.withdrawal_period_sec); // lazy update: verify period_start_time isn't updated until new trx occurs BOOST_CHECK(permit_object.period_start_time == first_start_time); } { // Leave Nathan with one unit transfer(nathan_id, dan_id, asset(996)); // Attempt a withdrawal claim for units than available withdraw_permission_claim_operation op; op.withdraw_permission = permit; op.withdraw_from_account = nathan_id; op.withdraw_to_account = dan_id; op.amount_to_withdraw = asset(5); trx.operations.push_back(op); set_expiration( db, trx ); sign( trx, dan_private_key ); //Throws because nathan doesn't have the money GRAPHENE_CHECK_THROW(PUSH_TX( db, trx ), fc::exception); // Attempt a withdrawal claim for which nathan does have sufficient units op.amount_to_withdraw = asset(1); trx.clear(); trx.operations = {op}; set_expiration( db, trx ); sign( trx, dan_private_key ); PUSH_TX( db, trx ); } BOOST_CHECK_EQUAL(get_balance(nathan_id, asset_id_type()), 0); BOOST_CHECK_EQUAL(get_balance(dan_id, asset_id_type()), 1000); trx.clear(); transfer(dan_id, nathan_id, asset(1000)); { const withdraw_permission_object& permit_object = permit(db); BOOST_CHECK(permit_object.authorized_account == dan_id); BOOST_CHECK(permit_object.withdraw_from_account == nathan_id); BOOST_CHECK(permit_object.period_start_time == first_start_time + permit_object.withdrawal_period_sec); BOOST_CHECK(permit_object.expiration == first_start_time + 5*permit_object.withdrawal_period_sec); BOOST_CHECK(permit_object.withdrawal_limit == asset(5)); BOOST_CHECK(permit_object.withdrawal_period_sec == fc::hours(1).to_seconds()); generate_blocks(permit_object.expiration); } // Ensure the permit object has been garbage collected BOOST_CHECK(db.find_object(permit) == nullptr); { withdraw_permission_claim_operation op; op.withdraw_permission = permit; op.withdraw_from_account = nathan_id; op.withdraw_to_account = dan_id; op.amount_to_withdraw = asset(5); trx.operations.push_back(op); set_expiration( db, trx ); sign( trx, dan_private_key ); //Throws because the permission has expired GRAPHENE_CHECK_THROW(PUSH_TX( db, trx ), fc::exception); } } FC_LOG_AND_RETHROW() } /** * Test the claims of withdrawals both before and during * authorized withdrawal periods. * NOTE: The simulated elapse of blockchain time through the use of * generate_blocks() must be carefully used in order to simulate * this test. * NOTE: This test verifies proper withdrawal claim behavior * as it should occur after Issue #23 is addressed. * That issue is concerned with ensuring that the first claim * can occur before the first withdrawal period. */ BOOST_AUTO_TEST_CASE( withdraw_permission_test_after_hardfork_23 ) { try { INVOKE(withdraw_permission_create_after_hardfork_23); auto nathan_private_key = generate_private_key("nathan"); auto dan_private_key = generate_private_key("dan"); account_id_type nathan_id = get_account("nathan").id; account_id_type dan_id = get_account("dan").id; withdraw_permission_id_type permit; set_expiration( db, trx ); fc::time_point_sec first_start_time; { const withdraw_permission_object& permit_object = permit(db); BOOST_CHECK(permit_object.authorized_account == dan_id); BOOST_CHECK(permit_object.withdraw_from_account == nathan_id); BOOST_CHECK(permit_object.period_start_time > db.head_block_time()); first_start_time = permit_object.period_start_time; BOOST_CHECK(permit_object.withdrawal_limit == asset(5)); BOOST_CHECK(permit_object.withdrawal_period_sec == fc::hours(1).to_seconds()); BOOST_CHECK(permit_object.expiration == first_start_time + permit_object.withdrawal_period_sec*5 ); } generate_blocks(HARDFORK_23_TIME); // Still before the first period, but DURING the real time during which "early" claims are checked { withdraw_permission_claim_operation op; op.withdraw_permission = permit; op.withdraw_from_account = nathan_id; op.withdraw_to_account = dan_id; op.amount_to_withdraw = asset(1); set_expiration( db, trx ); trx.operations.push_back(op); sign( trx, dan_private_key ); // Transaction should be signed to be valid //Throws because we haven't entered the first withdrawal period yet. GRAPHENE_REQUIRE_THROW(PUSH_TX( db, trx ), fc::exception); //Get to the actual withdrawal period bool miss_intermediate_blocks = false; // Required to have generate_blocks() elapse flush to the time of interest generate_blocks(first_start_time, miss_intermediate_blocks); set_expiration( db, trx ); REQUIRE_THROW_WITH_VALUE(op, withdraw_permission, withdraw_permission_id_type(5)); REQUIRE_THROW_WITH_VALUE(op, withdraw_from_account, dan_id); REQUIRE_THROW_WITH_VALUE(op, withdraw_from_account, account_id_type()); REQUIRE_THROW_WITH_VALUE(op, withdraw_to_account, nathan_id); REQUIRE_THROW_WITH_VALUE(op, withdraw_to_account, account_id_type()); REQUIRE_THROW_WITH_VALUE(op, amount_to_withdraw, asset(10)); REQUIRE_THROW_WITH_VALUE(op, amount_to_withdraw, asset(6)); set_expiration( db, trx ); trx.clear(); trx.operations.push_back(op); sign( trx, dan_private_key ); PUSH_TX( db, trx ); // <-- Claim #1 // would be legal on its own, but doesn't work because trx already withdrew REQUIRE_THROW_WITH_VALUE(op, amount_to_withdraw, asset(5)); // Make sure we can withdraw again this period, as long as we're not exceeding the periodic limit trx.clear(); // withdraw 1 trx.operations = {op}; // make it different from previous trx so it's non-duplicate trx.expiration += fc::seconds(1); sign( trx, dan_private_key ); PUSH_TX( db, trx ); // <-- Claim #2 trx.clear(); } // Account for two (2) claims of one (1) unit BOOST_CHECK_EQUAL(get_balance(nathan_id, asset_id_type()), 998); BOOST_CHECK_EQUAL(get_balance(dan_id, asset_id_type()), 2); { const withdraw_permission_object& permit_object = permit(db); BOOST_CHECK(permit_object.authorized_account == dan_id); BOOST_CHECK(permit_object.withdraw_from_account == nathan_id); BOOST_CHECK(permit_object.period_start_time == first_start_time); BOOST_CHECK(permit_object.withdrawal_limit == asset(5)); BOOST_CHECK(permit_object.withdrawal_period_sec == fc::hours(1).to_seconds()); BOOST_CHECK_EQUAL(permit_object.claimed_this_period.value, 2 ); // <-- Account for two (2) claims of one (1) unit BOOST_CHECK(permit_object.expiration == first_start_time + 5*permit_object.withdrawal_period_sec); generate_blocks(first_start_time + permit_object.withdrawal_period_sec); // lazy update: verify period_start_time isn't updated until new trx occurs BOOST_CHECK(permit_object.period_start_time == first_start_time); } { // Leave Nathan with one unit transfer(nathan_id, dan_id, asset(997)); // Attempt a withdrawal claim for units than available withdraw_permission_claim_operation op; op.withdraw_permission = permit; op.withdraw_from_account = nathan_id; op.withdraw_to_account = dan_id; op.amount_to_withdraw = asset(5); trx.operations.push_back(op); set_expiration( db, trx ); sign( trx, dan_private_key ); //Throws because nathan doesn't have the money GRAPHENE_CHECK_THROW(PUSH_TX( db, trx ), fc::exception); // Attempt a withdrawal claim for which nathan does have sufficient units op.amount_to_withdraw = asset(1); trx.clear(); trx.operations = {op}; set_expiration( db, trx ); sign( trx, dan_private_key ); PUSH_TX( db, trx ); } BOOST_CHECK_EQUAL(get_balance(nathan_id, asset_id_type()), 0); BOOST_CHECK_EQUAL(get_balance(dan_id, asset_id_type()), 1000); trx.clear(); transfer(dan_id, nathan_id, asset(1000)); { const withdraw_permission_object& permit_object = permit(db); BOOST_CHECK(permit_object.authorized_account == dan_id); BOOST_CHECK(permit_object.withdraw_from_account == nathan_id); BOOST_CHECK(permit_object.period_start_time == first_start_time + permit_object.withdrawal_period_sec); BOOST_CHECK(permit_object.expiration == first_start_time + 5*permit_object.withdrawal_period_sec); BOOST_CHECK(permit_object.withdrawal_limit == asset(5)); BOOST_CHECK(permit_object.withdrawal_period_sec == fc::hours(1).to_seconds()); generate_blocks(permit_object.expiration); } // Ensure the permit object has been garbage collected BOOST_CHECK(db.find_object(permit) == nullptr); { withdraw_permission_claim_operation op; op.withdraw_permission = permit; op.withdraw_from_account = nathan_id; op.withdraw_to_account = dan_id; op.amount_to_withdraw = asset(5); trx.operations.push_back(op); set_expiration( db, trx ); sign( trx, dan_private_key ); //Throws because the permission has expired GRAPHENE_CHECK_THROW(PUSH_TX( db, trx ), fc::exception); } } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( withdraw_permission_nominal_case ) { try { INVOKE(withdraw_permission_create_before_hardfork_23); auto nathan_private_key = generate_private_key("nathan"); auto dan_private_key = generate_private_key("dan"); account_id_type nathan_id = get_account("nathan").id; account_id_type dan_id = get_account("dan").id; withdraw_permission_id_type permit; // Wait until the permission period's start time const withdraw_permission_object& first_permit_object = permit(db); generate_blocks( first_permit_object.period_start_time); // Loop through the withdrawal periods and claim a withdrawal while(true) { const withdraw_permission_object& permit_object = permit(db); //wdump( (permit_object) ); withdraw_permission_claim_operation op; op.withdraw_permission = permit; op.withdraw_from_account = nathan_id; op.withdraw_to_account = dan_id; op.amount_to_withdraw = asset(5); trx.operations.push_back(op); set_expiration( db, trx ); sign( trx, dan_private_key ); PUSH_TX( db, trx ); // tx's involving withdraw_permissions can't delete it even // if no further withdrawals are possible BOOST_CHECK(db.find_object(permit) != nullptr); BOOST_CHECK( permit_object.claimed_this_period == 5 ); BOOST_CHECK_EQUAL( permit_object.available_this_period(db.head_block_time()).amount.value, 0 ); BOOST_CHECK_EQUAL( current_period(permit_object, db.head_block_time()).available_this_period.amount.value, 0 ); trx.clear(); generate_blocks( permit_object.period_start_time + permit_object.withdrawal_period_sec ); if( db.find_object(permit) == nullptr ) break; } BOOST_CHECK_EQUAL(get_balance(nathan_id, asset_id_type()), 975); BOOST_CHECK_EQUAL(get_balance(dan_id, asset_id_type()), 25); } FC_LOG_AND_RETHROW() } /** * Test asset whitelisting feature for withdrawals. * Reproduces https://github.com/bitshares/bitshares-core/issues/942 and tests the fix for it. */ BOOST_AUTO_TEST_CASE( withdraw_permission_whitelist_asset_test ) { try { uint32_t skip = database::skip_witness_signature | database::skip_transaction_signatures | database::skip_transaction_dupe_check | database::skip_block_size_check | database::skip_tapos_check | database::skip_authority_check | database::skip_merkle_check ; generate_blocks( HARDFORK_415_TIME, true, skip ); // get over Graphene 415 asset whitelisting bug generate_block( skip ); for( int i=0; i<2; i++ ) { if( i == 1 ) { generate_blocks( HARDFORK_CORE_942_TIME, true, skip ); generate_block( skip ); } int blocks = 0; set_expiration( db, trx ); ACTORS( (nathan)(dan)(izzy) ); const asset_id_type uia_id = create_user_issued_asset( "ADVANCED", izzy_id(db), white_list ).id; issue_uia( nathan_id, asset(1000, uia_id) ); // Make a whitelist authority { BOOST_TEST_MESSAGE( "Changing the whitelist authority" ); asset_update_operation uop; uop.issuer = izzy_id; uop.asset_to_update = uia_id; uop.new_options = uia_id(db).options; uop.new_options.whitelist_authorities.insert(izzy_id); trx.operations.push_back(uop); PUSH_TX( db, trx, ~0 ); trx.operations.clear(); } // Add dan to whitelist { upgrade_to_lifetime_member( izzy_id ); account_whitelist_operation wop; wop.authorizing_account = izzy_id; wop.account_to_list = dan_id; wop.new_listing = account_whitelist_operation::white_listed; trx.operations.push_back( wop ); PUSH_TX( db, trx, ~0 ); trx.operations.clear(); } // create withdraw permission { withdraw_permission_create_operation op; op.authorized_account = dan_id; op.withdraw_from_account = nathan_id; op.withdrawal_limit = asset(5, uia_id); op.withdrawal_period_sec = fc::hours(1).to_seconds(); op.periods_until_expiration = 5; op.period_start_time = db.head_block_time() + 1; trx.operations.push_back(op); PUSH_TX( db, trx, ~0 ); trx.operations.clear(); } withdraw_permission_id_type first_permit_id; // first object must have id 0 generate_block( skip ); // get to the time point that able to withdraw ++blocks; set_expiration( db, trx ); // try claim a withdrawal { withdraw_permission_claim_operation op; op.withdraw_permission = first_permit_id; op.withdraw_from_account = nathan_id; op.withdraw_to_account = dan_id; op.amount_to_withdraw = asset(5, uia_id); trx.operations.push_back(op); if( i == 0 ) // before hard fork, should pass PUSH_TX( db, trx, ~0 ); else // after hard fork, should throw GRAPHENE_CHECK_THROW( PUSH_TX( db, trx, ~0 ), fc::assert_exception ); trx.operations.clear(); } // TODO add test cases for other white-listing features // undo above tx's and reset generate_block( skip ); ++blocks; while( blocks > 0 ) { db.pop_block(); --blocks; } } } FC_LOG_AND_RETHROW() } /** * This case checks to see whether the amount claimed within any particular withdrawal period * is properly reflected within the permission object. * The maximum withdrawal per period will be limited to 5 units. * There are a total of 5 withdrawal periods that are permitted. * The test will evaluate the following withdrawal pattern: * (1) during Period 1, a withdrawal of 4 units, * (2) during Period 2, a withdrawal of 1 units, * (3) during Period 3, a withdrawal of 0 units, * (4) during Period 4, a withdrawal of 5 units, * (5) during Period 5, a withdrawal of 3 units. * * Total withdrawal will be 13 units. */ BOOST_AUTO_TEST_CASE( withdraw_permission_incremental_case ) { try { INVOKE(withdraw_permission_create_after_hardfork_23); time_point_sec expected_first_period_start_time = HARDFORK_23_TIME + db.get_global_properties().parameters.block_interval*5; // Hard-coded to synchronize with withdraw_permission_create_after_hardfork_23() uint64_t expected_period_duration_seconds = fc::hours(1).to_seconds(); // Hard-coded to synchronize with withdraw_permission_create_after_hardfork_23() auto nathan_private_key = generate_private_key("nathan"); auto dan_private_key = generate_private_key("dan"); account_id_type nathan_id = get_account("nathan").id; account_id_type dan_id = get_account("dan").id; withdraw_permission_id_type permit; // Wait until the permission period's start time { const withdraw_permission_object &before_first_permit_object = permit(db); BOOST_CHECK_EQUAL(before_first_permit_object.period_start_time.sec_since_epoch(), expected_first_period_start_time.sec_since_epoch()); generate_blocks( before_first_permit_object.period_start_time); } // Before withdrawing, check the period description const withdraw_permission_object &first_permit_object = permit(db); const withdrawal_period_descriptor first_period = current_period(first_permit_object, db.head_block_time()); BOOST_CHECK_EQUAL(first_period.period_start_time.sec_since_epoch(), expected_first_period_start_time.sec_since_epoch()); BOOST_CHECK_EQUAL(first_period.period_end_time.sec_since_epoch(), expected_first_period_start_time.sec_since_epoch() + expected_period_duration_seconds); BOOST_CHECK_EQUAL(first_period.available_this_period.amount.value, 5); // Period 1: Withdraw 4 units { // Before claiming, check the period description const withdraw_permission_object& permit_object = permit(db); BOOST_CHECK(db.find_object(permit) != nullptr); withdrawal_period_descriptor period_descriptor = current_period(permit_object, db.head_block_time()); BOOST_CHECK_EQUAL(period_descriptor.available_this_period.amount.value, 5); BOOST_CHECK_EQUAL(period_descriptor.period_start_time.sec_since_epoch(), expected_first_period_start_time.sec_since_epoch() + (expected_period_duration_seconds * 0)); BOOST_CHECK_EQUAL(period_descriptor.period_end_time.sec_since_epoch(), expected_first_period_start_time.sec_since_epoch() + (expected_period_duration_seconds * 1)); // Claim withdraw_permission_claim_operation op; op.withdraw_permission = permit; op.withdraw_from_account = nathan_id; op.withdraw_to_account = dan_id; op.amount_to_withdraw = asset(4); trx.operations.push_back(op); set_expiration( db, trx ); sign( trx, dan_private_key ); PUSH_TX( db, trx ); // After claiming, check the period description BOOST_CHECK(db.find_object(permit) != nullptr); BOOST_CHECK( permit_object.claimed_this_period == 4 ); BOOST_CHECK_EQUAL( permit_object.claimed_this_period.value, 4 ); period_descriptor = current_period(permit_object, db.head_block_time()); BOOST_CHECK_EQUAL(period_descriptor.available_this_period.amount.value, 1); BOOST_CHECK_EQUAL(period_descriptor.period_start_time.sec_since_epoch(), expected_first_period_start_time.sec_since_epoch() + (expected_period_duration_seconds * 0)); BOOST_CHECK_EQUAL(period_descriptor.period_end_time.sec_since_epoch(), expected_first_period_start_time.sec_since_epoch() + (expected_period_duration_seconds * 1)); // Advance to next period trx.clear(); generate_blocks( permit_object.period_start_time + permit_object.withdrawal_period_sec ); } // Period 2: Withdraw 1 units { // Before claiming, check the period description const withdraw_permission_object& permit_object = permit(db); BOOST_CHECK(db.find_object(permit) != nullptr); withdrawal_period_descriptor period_descriptor = current_period(permit_object, db.head_block_time()); BOOST_CHECK_EQUAL(period_descriptor.available_this_period.amount.value, 5); BOOST_CHECK_EQUAL(period_descriptor.period_start_time.sec_since_epoch(), expected_first_period_start_time.sec_since_epoch() + (expected_period_duration_seconds * 1)); BOOST_CHECK_EQUAL(period_descriptor.period_end_time.sec_since_epoch(), expected_first_period_start_time.sec_since_epoch() + (expected_period_duration_seconds * 2)); // Claim withdraw_permission_claim_operation op; op.withdraw_permission = permit; op.withdraw_from_account = nathan_id; op.withdraw_to_account = dan_id; op.amount_to_withdraw = asset(1); trx.operations.push_back(op); set_expiration( db, trx ); sign( trx, dan_private_key ); PUSH_TX( db, trx ); // After claiming, check the period description BOOST_CHECK(db.find_object(permit) != nullptr); BOOST_CHECK( permit_object.claimed_this_period == 1 ); BOOST_CHECK_EQUAL( permit_object.claimed_this_period.value, 1 ); period_descriptor = current_period(permit_object, db.head_block_time()); BOOST_CHECK_EQUAL(period_descriptor.available_this_period.amount.value, 4); BOOST_CHECK_EQUAL(period_descriptor.period_start_time.sec_since_epoch(), expected_first_period_start_time.sec_since_epoch() + (expected_period_duration_seconds * 1)); BOOST_CHECK_EQUAL(period_descriptor.period_end_time.sec_since_epoch(), expected_first_period_start_time.sec_since_epoch() + (expected_period_duration_seconds * 2)); // Advance to next period trx.clear(); generate_blocks( permit_object.period_start_time + permit_object.withdrawal_period_sec ); } // Period 3: Withdraw 0 units { // Before claiming, check the period description const withdraw_permission_object& permit_object = permit(db); BOOST_CHECK(db.find_object(permit) != nullptr); withdrawal_period_descriptor period_descriptor = current_period(permit_object, db.head_block_time()); BOOST_CHECK_EQUAL(period_descriptor.available_this_period.amount.value, 5); BOOST_CHECK_EQUAL(period_descriptor.period_start_time.sec_since_epoch(), expected_first_period_start_time.sec_since_epoch() + (expected_period_duration_seconds * 2)); BOOST_CHECK_EQUAL(period_descriptor.period_end_time.sec_since_epoch(), expected_first_period_start_time.sec_since_epoch() + (expected_period_duration_seconds * 3)); // No claim // After doing nothing, check the period description period_descriptor = current_period(permit_object, db.head_block_time()); BOOST_CHECK_EQUAL(period_descriptor.available_this_period.amount.value, 5); BOOST_CHECK_EQUAL(period_descriptor.period_start_time.sec_since_epoch(), expected_first_period_start_time.sec_since_epoch() + (expected_period_duration_seconds * 2)); BOOST_CHECK_EQUAL(period_descriptor.period_end_time.sec_since_epoch(), expected_first_period_start_time.sec_since_epoch() + (expected_period_duration_seconds * 3)); // Advance to end of Period 3 time_point_sec period_end_time = period_descriptor.period_end_time; generate_blocks(period_end_time); } // Period 4: Withdraw 5 units { // Before claiming, check the period description const withdraw_permission_object& permit_object = permit(db); BOOST_CHECK(db.find_object(permit) != nullptr); withdrawal_period_descriptor period_descriptor = current_period(permit_object, db.head_block_time()); BOOST_CHECK_EQUAL(period_descriptor.available_this_period.amount.value, 5); BOOST_CHECK_EQUAL(period_descriptor.period_start_time.sec_since_epoch(), expected_first_period_start_time.sec_since_epoch() + (expected_period_duration_seconds * 3)); BOOST_CHECK_EQUAL(period_descriptor.period_end_time.sec_since_epoch(), expected_first_period_start_time.sec_since_epoch() + (expected_period_duration_seconds * 4)); // Claim withdraw_permission_claim_operation op; op.withdraw_permission = permit; op.withdraw_from_account = nathan_id; op.withdraw_to_account = dan_id; op.amount_to_withdraw = asset(5); trx.operations.push_back(op); set_expiration( db, trx ); sign( trx, dan_private_key ); PUSH_TX( db, trx ); // After claiming, check the period description BOOST_CHECK(db.find_object(permit) != nullptr); BOOST_CHECK( permit_object.claimed_this_period == 5 ); BOOST_CHECK_EQUAL( permit_object.claimed_this_period.value, 5 ); period_descriptor = current_period(permit_object, db.head_block_time()); BOOST_CHECK_EQUAL(period_descriptor.available_this_period.amount.value, 0); BOOST_CHECK_EQUAL(period_descriptor.period_start_time.sec_since_epoch(), expected_first_period_start_time.sec_since_epoch() + (expected_period_duration_seconds * 3)); BOOST_CHECK_EQUAL(period_descriptor.period_end_time.sec_since_epoch(), expected_first_period_start_time.sec_since_epoch() + (expected_period_duration_seconds * 4)); // Advance to next period trx.clear(); generate_blocks( permit_object.period_start_time + permit_object.withdrawal_period_sec ); } // Period 5: Withdraw 3 units { // Before claiming, check the period description const withdraw_permission_object& permit_object = permit(db); BOOST_CHECK(db.find_object(permit) != nullptr); withdrawal_period_descriptor period_descriptor = current_period(permit_object, db.head_block_time()); BOOST_CHECK_EQUAL(period_descriptor.available_this_period.amount.value, 5); BOOST_CHECK_EQUAL(period_descriptor.period_start_time.sec_since_epoch(), expected_first_period_start_time.sec_since_epoch() + (expected_period_duration_seconds * 4)); BOOST_CHECK_EQUAL(period_descriptor.period_end_time.sec_since_epoch(), expected_first_period_start_time.sec_since_epoch() + (expected_period_duration_seconds * 5)); // Claim withdraw_permission_claim_operation op; op.withdraw_permission = permit; op.withdraw_from_account = nathan_id; op.withdraw_to_account = dan_id; op.amount_to_withdraw = asset(3); trx.operations.push_back(op); set_expiration( db, trx ); sign( trx, dan_private_key ); PUSH_TX( db, trx ); // After claiming, check the period description BOOST_CHECK(db.find_object(permit) != nullptr); BOOST_CHECK( permit_object.claimed_this_period == 3 ); BOOST_CHECK_EQUAL( permit_object.claimed_this_period.value, 3 ); period_descriptor = current_period(permit_object, db.head_block_time()); BOOST_CHECK_EQUAL(period_descriptor.available_this_period.amount.value, 2); BOOST_CHECK_EQUAL(period_descriptor.period_start_time.sec_since_epoch(), expected_first_period_start_time.sec_since_epoch() + (expected_period_duration_seconds * 4)); BOOST_CHECK_EQUAL(period_descriptor.period_end_time.sec_since_epoch(), expected_first_period_start_time.sec_since_epoch() + (expected_period_duration_seconds * 5)); // Advance to next period trx.clear(); generate_blocks( permit_object.period_start_time + permit_object.withdrawal_period_sec ); } // Withdrawal periods completed BOOST_CHECK(db.find_object(permit) == nullptr); BOOST_CHECK_EQUAL(get_balance(nathan_id, asset_id_type()), 987); BOOST_CHECK_EQUAL(get_balance(dan_id, asset_id_type()), 13); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( withdraw_permission_update ) { try { INVOKE(withdraw_permission_create_before_hardfork_23); auto nathan_private_key = generate_private_key("nathan"); account_id_type nathan_id = get_account("nathan").id; account_id_type dan_id = get_account("dan").id; withdraw_permission_id_type permit; set_expiration( db, trx ); { withdraw_permission_update_operation op; op.permission_to_update = permit; op.authorized_account = dan_id; op.withdraw_from_account = nathan_id; op.periods_until_expiration = 2; op.period_start_time = db.head_block_time() + 10; op.withdrawal_period_sec = 10; op.withdrawal_limit = asset(12); trx.operations.push_back(op); REQUIRE_THROW_WITH_VALUE(op, periods_until_expiration, 0); REQUIRE_THROW_WITH_VALUE(op, withdrawal_period_sec, 0); REQUIRE_THROW_WITH_VALUE(op, withdrawal_limit, asset(1, asset_id_type(12))); REQUIRE_THROW_WITH_VALUE(op, withdrawal_limit, asset(0)); REQUIRE_THROW_WITH_VALUE(op, withdraw_from_account, account_id_type(0)); REQUIRE_THROW_WITH_VALUE(op, authorized_account, account_id_type(0)); REQUIRE_THROW_WITH_VALUE(op, period_start_time, db.head_block_time() - 50); trx.operations.back() = op; sign( trx, nathan_private_key ); PUSH_TX( db, trx ); } { const withdraw_permission_object& permit_object = db.get(permit); BOOST_CHECK(permit_object.authorized_account == dan_id); BOOST_CHECK(permit_object.withdraw_from_account == nathan_id); BOOST_CHECK(permit_object.period_start_time == db.head_block_time() + 10); BOOST_CHECK(permit_object.withdrawal_limit == asset(12)); BOOST_CHECK(permit_object.withdrawal_period_sec == 10); // BOOST_CHECK(permit_object.remaining_periods == 2); } } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( withdraw_permission_delete ) { try { INVOKE(withdraw_permission_update); withdraw_permission_delete_operation op; op.authorized_account = get_account("dan").id; op.withdraw_from_account = get_account("nathan").id; set_expiration( db, trx ); trx.operations.push_back(op); sign( trx, generate_private_key("nathan" )); PUSH_TX( db, trx ); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( mia_feeds ) { try { ACTORS((nathan)(dan)(ben)(vikram)); asset_id_type bit_usd_id = create_bitasset("USDBIT").id; { asset_update_operation op; const asset_object& obj = bit_usd_id(db); op.asset_to_update = bit_usd_id; op.issuer = obj.issuer; op.new_issuer = nathan_id; op.new_options = obj.options; op.new_options.flags &= ~witness_fed_asset; trx.operations.push_back(op); PUSH_TX( db, trx, ~0 ); generate_block(); trx.clear(); } { asset_update_feed_producers_operation op; op.asset_to_update = bit_usd_id; op.issuer = nathan_id; op.new_feed_producers = {dan_id, ben_id, vikram_id}; trx.operations.push_back(op); sign( trx, nathan_private_key ); PUSH_TX( db, trx ); generate_block(database::skip_nothing); } { const asset_bitasset_data_object& obj = bit_usd_id(db).bitasset_data(db); BOOST_CHECK_EQUAL(obj.feeds.size(), 3); BOOST_CHECK(obj.current_feed == price_feed()); } { const asset_object& bit_usd = bit_usd_id(db); asset_publish_feed_operation op; op.publisher = vikram_id; op.asset_id = bit_usd_id; op.feed.settlement_price = op.feed.core_exchange_rate = ~price(asset(GRAPHENE_BLOCKCHAIN_PRECISION),bit_usd.amount(30)); // We'll expire margins after a month // Accept defaults for required collateral trx.operations.emplace_back(op); PUSH_TX( db, trx, ~0 ); const asset_bitasset_data_object& bitasset = bit_usd.bitasset_data(db); BOOST_CHECK(bitasset.current_feed.settlement_price.to_real() == 30.0 / GRAPHENE_BLOCKCHAIN_PRECISION); BOOST_CHECK(bitasset.current_feed.maintenance_collateral_ratio == GRAPHENE_DEFAULT_MAINTENANCE_COLLATERAL_RATIO); op.publisher = ben_id; op.feed.settlement_price = op.feed.core_exchange_rate = ~price(asset(GRAPHENE_BLOCKCHAIN_PRECISION),bit_usd.amount(25)); trx.operations.back() = op; PUSH_TX( db, trx, ~0 ); BOOST_CHECK_EQUAL(bitasset.current_feed.settlement_price.to_real(), 30.0 / GRAPHENE_BLOCKCHAIN_PRECISION); BOOST_CHECK(bitasset.current_feed.maintenance_collateral_ratio == GRAPHENE_DEFAULT_MAINTENANCE_COLLATERAL_RATIO); op.publisher = dan_id; op.feed.settlement_price = op.feed.core_exchange_rate = ~price(asset(GRAPHENE_BLOCKCHAIN_PRECISION),bit_usd.amount(40)); op.feed.maximum_short_squeeze_ratio = 1001; op.feed.maintenance_collateral_ratio = 1001; trx.operations.back() = op; PUSH_TX( db, trx, ~0 ); BOOST_CHECK_EQUAL(bitasset.current_feed.settlement_price.to_real(), 30.0 / GRAPHENE_BLOCKCHAIN_PRECISION); BOOST_CHECK(bitasset.current_feed.maintenance_collateral_ratio == GRAPHENE_DEFAULT_MAINTENANCE_COLLATERAL_RATIO); op.publisher = nathan_id; trx.operations.back() = op; GRAPHENE_CHECK_THROW(PUSH_TX( db, trx, ~0 ), fc::exception); } } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( feed_limit_test ) { try { INVOKE( mia_feeds ); const asset_object& bit_usd = get_asset("USDBIT"); const asset_bitasset_data_object& bitasset = bit_usd.bitasset_data(db); GET_ACTOR(nathan); BOOST_CHECK(!bitasset.current_feed.settlement_price.is_null()); BOOST_TEST_MESSAGE("Setting minimum feeds to 4"); asset_update_bitasset_operation op; op.new_options.minimum_feeds = 4; op.asset_to_update = bit_usd.get_id(); op.issuer = bit_usd.issuer; trx.operations = {op}; sign( trx, nathan_private_key ); db.push_transaction(trx); BOOST_TEST_MESSAGE("Checking current_feed is null"); BOOST_CHECK(bitasset.current_feed.settlement_price.is_null()); BOOST_TEST_MESSAGE("Setting minimum feeds to 3"); op.new_options.minimum_feeds = 3; trx.clear(); trx.operations = {op}; sign( trx, nathan_private_key ); db.push_transaction(trx); BOOST_TEST_MESSAGE("Checking current_feed is not null"); BOOST_CHECK(!bitasset.current_feed.settlement_price.is_null()); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( witness_create ) { try { ACTOR(nathan); upgrade_to_lifetime_member(nathan_id); trx.clear(); witness_id_type nathan_witness_id = create_witness(nathan_id, nathan_private_key).id; // Give nathan some voting stake transfer(committee_account, nathan_id, asset(10000000)); generate_block(); set_expiration( db, trx ); { account_update_operation op; op.account = nathan_id; op.new_options = nathan_id(db).options; op.new_options->votes.insert(nathan_witness_id(db).vote_id); op.new_options->num_witness = std::count_if(op.new_options->votes.begin(), op.new_options->votes.end(), [](vote_id_type id) { return id.type() == vote_id_type::witness; }); op.new_options->num_committee = std::count_if(op.new_options->votes.begin(), op.new_options->votes.end(), [](vote_id_type id) { return id.type() == vote_id_type::committee; }); trx.operations.push_back(op); sign( trx, nathan_private_key ); PUSH_TX( db, trx ); trx.clear(); } generate_blocks(db.get_dynamic_global_properties().next_maintenance_time); const auto& witnesses = db.get_global_properties().active_witnesses; // make sure we're in active_witnesses auto itr = std::find(witnesses.begin(), witnesses.end(), nathan_witness_id); BOOST_CHECK(itr != witnesses.end()); // generate blocks until we are at the beginning of a round while( ((db.get_dynamic_global_properties().current_aslot + 1) % witnesses.size()) != 0 ) generate_block(); int produced = 0; // Make sure we get scheduled at least once in witnesses.size()*2 blocks // may take this many unless we measure where in the scheduling round we are // TODO: intense_test that repeats this loop many times for( size_t i=0, n=witnesses.size()*2; i<n; i++ ) { signed_block block = generate_block(); if( block.witness == nathan_witness_id ) produced++; } BOOST_CHECK_GE( produced, 1 ); } FC_LOG_AND_RETHROW() } /** * This test should verify that the asset_global_settle operation works as expected, * make sure that global settling cannot be performed by anyone other than the * issuer and only if the global settle bit is set. */ BOOST_AUTO_TEST_CASE( global_settle_test ) { try { uint32_t skip = database::skip_witness_signature | database::skip_transaction_signatures | database::skip_transaction_dupe_check | database::skip_block_size_check | database::skip_tapos_check | database::skip_authority_check | database::skip_merkle_check ; generate_block( skip ); for( int i=0; i<2; i++ ) { if( i == 1 ) { auto mi = db.get_global_properties().parameters.maintenance_interval; generate_blocks(HARDFORK_CORE_342_TIME - mi, true, skip); generate_blocks(db.get_dynamic_global_properties().next_maintenance_time, true, skip); } set_expiration( db, trx ); ACTORS((nathan)(ben)(valentine)(dan)); asset_id_type bit_usd_id = create_bitasset("USDBIT", nathan_id, 100, global_settle | charge_market_fee).get_id(); update_feed_producers( bit_usd_id(db), { nathan_id } ); price_feed feed; feed.settlement_price = price( asset( 1000, bit_usd_id ), asset( 500 ) ); feed.maintenance_collateral_ratio = 175 * GRAPHENE_COLLATERAL_RATIO_DENOM / 100; feed.maximum_short_squeeze_ratio = 150 * GRAPHENE_COLLATERAL_RATIO_DENOM / 100; publish_feed( bit_usd_id(db), nathan, feed ); transfer(committee_account, ben_id, asset(10000)); transfer(committee_account, valentine_id, asset(10000)); transfer(committee_account, dan_id, asset(10000)); borrow(ben, asset(1000, bit_usd_id), asset(1000)); BOOST_CHECK_EQUAL(get_balance(ben_id, bit_usd_id), 1000); BOOST_CHECK_EQUAL(get_balance(ben_id, asset_id_type()), 9000); create_sell_order(ben_id, asset(1000, bit_usd_id), asset(1000)); BOOST_CHECK_EQUAL(get_balance(ben_id, bit_usd_id), 0); BOOST_CHECK_EQUAL(get_balance(ben_id, asset_id_type()), 9000); create_sell_order(valentine_id, asset(1000), asset(1000, bit_usd_id)); BOOST_CHECK_EQUAL(get_balance(ben_id, bit_usd_id), 0); BOOST_CHECK_EQUAL(get_balance(ben_id, asset_id_type()), 10000); BOOST_CHECK_EQUAL(get_balance(valentine_id, bit_usd_id), 990); BOOST_CHECK_EQUAL(get_balance(valentine_id, asset_id_type()), 9000); borrow(valentine, asset(500, bit_usd_id), asset(600)); BOOST_CHECK_EQUAL(get_balance(valentine_id, bit_usd_id), 1490); BOOST_CHECK_EQUAL(get_balance(valentine_id, asset_id_type()), 8400); create_sell_order(valentine_id, asset(500, bit_usd_id), asset(600)); BOOST_CHECK_EQUAL(get_balance(valentine_id, bit_usd_id), 990); BOOST_CHECK_EQUAL(get_balance(valentine_id, asset_id_type()), 8400); create_sell_order(dan_id, asset(600), asset(500, bit_usd_id)); BOOST_CHECK_EQUAL(get_balance(valentine_id, bit_usd_id), 990); BOOST_CHECK_EQUAL(get_balance(valentine_id, asset_id_type()), 9000); BOOST_CHECK_EQUAL(get_balance(ben_id, bit_usd_id), 0); BOOST_CHECK_EQUAL(get_balance(ben_id, asset_id_type()), 10000); BOOST_CHECK_EQUAL(get_balance(dan_id, bit_usd_id), 495); BOOST_CHECK_EQUAL(get_balance(dan_id, asset_id_type()), 9400); // add some collateral borrow(ben, asset(0, bit_usd_id), asset(1000)); BOOST_CHECK_EQUAL(get_balance(ben_id, asset_id_type()), 9000); { asset_global_settle_operation op; op.asset_to_settle = bit_usd_id; op.issuer = nathan_id; op.settle_price = ~price(asset(10), asset(11, bit_usd_id)); trx.clear(); trx.operations.push_back(op); REQUIRE_THROW_WITH_VALUE(op, settle_price, ~price(asset(2001), asset(1000, bit_usd_id))); REQUIRE_THROW_WITH_VALUE(op, asset_to_settle, asset_id_type()); REQUIRE_THROW_WITH_VALUE(op, asset_to_settle, asset_id_type(100)); REQUIRE_THROW_WITH_VALUE(op, issuer, account_id_type(2)); trx.operations.back() = op; sign( trx, nathan_private_key ); PUSH_TX( db, trx ); } force_settle(valentine_id(db), asset(990, bit_usd_id)); force_settle(dan_id(db), asset(495, bit_usd_id)); BOOST_CHECK_EQUAL(get_balance(valentine_id, bit_usd_id), 0); BOOST_CHECK_EQUAL(get_balance(valentine_id, asset_id_type()), 10045); BOOST_CHECK_EQUAL(get_balance(ben_id, bit_usd_id), 0); if( i == 1 ) // BSIP35: better rounding { BOOST_CHECK_EQUAL(get_balance(ben_id, asset_id_type()), 10090); BOOST_CHECK_EQUAL(get_balance(dan_id, asset_id_type()), 9850); } else { BOOST_CHECK_EQUAL(get_balance(ben_id, asset_id_type()), 10091); BOOST_CHECK_EQUAL(get_balance(dan_id, asset_id_type()), 9849); } BOOST_CHECK_EQUAL(get_balance(dan_id, bit_usd_id), 0); // undo above tx's and reset generate_block( skip ); db.pop_block(); } } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( worker_create_test ) { try { ACTOR(nathan); upgrade_to_lifetime_member(nathan_id); generate_block(); { worker_create_operation op; op.owner = nathan_id; op.daily_pay = 1000; op.initializer = vesting_balance_worker_initializer(1); op.work_begin_date = db.head_block_time() + 10; op.work_end_date = op.work_begin_date + fc::days(2); trx.clear(); trx.operations.push_back(op); REQUIRE_THROW_WITH_VALUE(op, daily_pay, -1); REQUIRE_THROW_WITH_VALUE(op, daily_pay, 0); REQUIRE_THROW_WITH_VALUE(op, owner, account_id_type(1000)); REQUIRE_THROW_WITH_VALUE(op, work_begin_date, db.head_block_time() - 10); REQUIRE_THROW_WITH_VALUE(op, work_end_date, op.work_begin_date); trx.operations.back() = op; sign( trx, nathan_private_key ); PUSH_TX( db, trx ); } const worker_object& worker = worker_id_type()(db); BOOST_CHECK(worker.worker_account == nathan_id); BOOST_CHECK(worker.daily_pay == 1000); BOOST_CHECK(worker.work_begin_date == db.head_block_time() + 10); BOOST_CHECK(worker.work_end_date == db.head_block_time() + 10 + fc::days(2)); BOOST_CHECK(worker.vote_for.type() == vote_id_type::worker); BOOST_CHECK(worker.vote_against.type() == vote_id_type::worker); const vesting_balance_object& balance = worker.worker.get<vesting_balance_worker_type>().balance(db); BOOST_CHECK(balance.owner == nathan_id); BOOST_CHECK(balance.balance == asset(0)); BOOST_CHECK(balance.policy.get<cdd_vesting_policy>().vesting_seconds == fc::days(1).to_seconds()); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( worker_pay_test ) { try { INVOKE(worker_create_test); GET_ACTOR(nathan); generate_blocks(db.get_dynamic_global_properties().next_maintenance_time); transfer(committee_account, nathan_id, asset(100000)); { account_update_operation op; op.account = nathan_id; op.new_options = nathan_id(db).options; op.new_options->votes.insert(worker_id_type()(db).vote_for); trx.operations.push_back(op); PUSH_TX( db, trx, ~0 ); trx.clear(); } { asset_reserve_operation op; op.payer = account_id_type(); op.amount_to_reserve = asset(GRAPHENE_MAX_SHARE_SUPPLY/2); trx.operations.push_back(op); PUSH_TX( db, trx, ~0 ); trx.clear(); } BOOST_CHECK_EQUAL(worker_id_type()(db).worker.get<vesting_balance_worker_type>().balance(db).balance.amount.value, 0); generate_blocks(db.get_dynamic_global_properties().next_maintenance_time); BOOST_CHECK_EQUAL(worker_id_type()(db).worker.get<vesting_balance_worker_type>().balance(db).balance.amount.value, 1000); generate_blocks(db.head_block_time() + fc::hours(12)); { vesting_balance_withdraw_operation op; op.vesting_balance = worker_id_type()(db).worker.get<vesting_balance_worker_type>().balance; op.amount = asset(500); op.owner = nathan_id; set_expiration( db, trx ); trx.operations.push_back(op); sign( trx, nathan_private_key ); PUSH_TX( db, trx ); trx.signatures.clear(); REQUIRE_THROW_WITH_VALUE(op, amount, asset(1)); trx.clear(); } BOOST_CHECK_EQUAL(get_balance(nathan_id, asset_id_type()), 100500); BOOST_CHECK_EQUAL(worker_id_type()(db).worker.get<vesting_balance_worker_type>().balance(db).balance.amount.value, 500); { account_update_operation op; op.account = nathan_id; op.new_options = nathan_id(db).options; op.new_options->votes.erase(worker_id_type()(db).vote_for); trx.operations.push_back(op); PUSH_TX( db, trx, ~0 ); trx.clear(); } generate_blocks(db.head_block_time() + fc::hours(12)); BOOST_CHECK_EQUAL(worker_id_type()(db).worker.get<vesting_balance_worker_type>().balance(db).balance.amount.value, 500); { vesting_balance_withdraw_operation op; op.vesting_balance = worker_id_type()(db).worker.get<vesting_balance_worker_type>().balance; op.amount = asset(500); op.owner = nathan_id; set_expiration( db, trx ); trx.operations.push_back(op); REQUIRE_THROW_WITH_VALUE(op, amount, asset(500)); generate_blocks(db.head_block_time() + fc::hours(12)); set_expiration( db, trx ); REQUIRE_THROW_WITH_VALUE(op, amount, asset(501)); trx.operations.back() = op; sign( trx, nathan_private_key ); PUSH_TX( db, trx ); trx.signatures.clear(); trx.clear(); } BOOST_CHECK_EQUAL(get_balance(nathan_id, asset_id_type()), 101000); BOOST_CHECK_EQUAL(worker_id_type()(db).worker.get<vesting_balance_worker_type>().balance(db).balance.amount.value, 0); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( refund_worker_test ) {try{ ACTOR(nathan); upgrade_to_lifetime_member(nathan_id); generate_block(); generate_blocks(db.get_dynamic_global_properties().next_maintenance_time); set_expiration( db, trx ); { worker_create_operation op; op.owner = nathan_id; op.daily_pay = 1000; op.initializer = refund_worker_initializer(); op.work_begin_date = db.head_block_time() + 10; op.work_end_date = op.work_begin_date + fc::days(2); trx.clear(); trx.operations.push_back(op); REQUIRE_THROW_WITH_VALUE(op, daily_pay, -1); REQUIRE_THROW_WITH_VALUE(op, daily_pay, 0); REQUIRE_THROW_WITH_VALUE(op, owner, account_id_type(1000)); REQUIRE_THROW_WITH_VALUE(op, work_begin_date, db.head_block_time() - 10); REQUIRE_THROW_WITH_VALUE(op, work_end_date, op.work_begin_date); trx.operations.back() = op; sign( trx, nathan_private_key ); PUSH_TX( db, trx ); trx.clear(); } const worker_object& worker = worker_id_type()(db); BOOST_CHECK(worker.worker_account == nathan_id); BOOST_CHECK(worker.daily_pay == 1000); BOOST_CHECK(worker.work_begin_date == db.head_block_time() + 10); BOOST_CHECK(worker.work_end_date == db.head_block_time() + 10 + fc::days(2)); BOOST_CHECK(worker.vote_for.type() == vote_id_type::worker); BOOST_CHECK(worker.vote_against.type() == vote_id_type::worker); transfer(committee_account, nathan_id, asset(100000)); { account_update_operation op; op.account = nathan_id; op.new_options = nathan_id(db).options; op.new_options->votes.insert(worker_id_type()(db).vote_for); trx.operations.push_back(op); PUSH_TX( db, trx, ~0 ); trx.clear(); } { asset_reserve_operation op; op.payer = account_id_type(); op.amount_to_reserve = asset(GRAPHENE_MAX_SHARE_SUPPLY/2); trx.operations.push_back(op); PUSH_TX( db, trx, ~0 ); trx.clear(); } // auto supply = asset_id_type()(db).dynamic_data(db).current_supply; verify_asset_supplies(db); generate_blocks(db.get_dynamic_global_properties().next_maintenance_time); verify_asset_supplies(db); BOOST_CHECK_EQUAL(worker_id_type()(db).worker.get<refund_worker_type>().total_burned.value, 1000); generate_blocks(db.get_dynamic_global_properties().next_maintenance_time); verify_asset_supplies(db); BOOST_CHECK_EQUAL(worker_id_type()(db).worker.get<refund_worker_type>().total_burned.value, 2000); generate_blocks(db.get_dynamic_global_properties().next_maintenance_time); BOOST_CHECK(!db.get(worker_id_type()).is_active(db.head_block_time())); BOOST_CHECK_EQUAL(worker_id_type()(db).worker.get<refund_worker_type>().total_burned.value, 2000); }FC_LOG_AND_RETHROW()} /** * Create a burn worker, vote it in, make sure funds are destroyed. */ BOOST_AUTO_TEST_CASE( burn_worker_test ) {try{ ACTOR(nathan); upgrade_to_lifetime_member(nathan_id); generate_block(); generate_blocks(db.get_dynamic_global_properties().next_maintenance_time); set_expiration( db, trx ); { worker_create_operation op; op.owner = nathan_id; op.daily_pay = 1000; op.initializer = burn_worker_initializer(); op.work_begin_date = db.head_block_time() + 10; op.work_end_date = op.work_begin_date + fc::days(2); trx.clear(); trx.operations.push_back(op); REQUIRE_THROW_WITH_VALUE(op, daily_pay, -1); REQUIRE_THROW_WITH_VALUE(op, daily_pay, 0); REQUIRE_THROW_WITH_VALUE(op, owner, account_id_type(1000)); REQUIRE_THROW_WITH_VALUE(op, work_begin_date, db.head_block_time() - 10); REQUIRE_THROW_WITH_VALUE(op, work_end_date, op.work_begin_date); trx.operations.back() = op; sign( trx, nathan_private_key ); PUSH_TX( db, trx ); trx.clear(); } const worker_object& worker = worker_id_type()(db); BOOST_CHECK(worker.worker_account == nathan_id); BOOST_CHECK(worker.daily_pay == 1000); BOOST_CHECK(worker.work_begin_date == db.head_block_time() + 10); BOOST_CHECK(worker.work_end_date == db.head_block_time() + 10 + fc::days(2)); BOOST_CHECK(worker.vote_for.type() == vote_id_type::worker); BOOST_CHECK(worker.vote_against.type() == vote_id_type::worker); transfer(committee_account, nathan_id, asset(100000)); { account_update_operation op; op.account = nathan_id; op.new_options = nathan_id(db).options; op.new_options->votes.insert(worker_id_type()(db).vote_for); trx.operations.push_back(op); PUSH_TX( db, trx, ~0 ); trx.clear(); } { // refund some asset to fill up the pool asset_reserve_operation op; op.payer = account_id_type(); op.amount_to_reserve = asset(GRAPHENE_MAX_SHARE_SUPPLY/2); trx.operations.push_back(op); PUSH_TX( db, trx, ~0 ); trx.clear(); } BOOST_CHECK_EQUAL( get_balance(GRAPHENE_NULL_ACCOUNT, asset_id_type()), 0 ); verify_asset_supplies(db); generate_blocks(db.get_dynamic_global_properties().next_maintenance_time); verify_asset_supplies(db); BOOST_CHECK_EQUAL(worker_id_type()(db).worker.get<burn_worker_type>().total_burned.value, 1000); BOOST_CHECK_EQUAL( get_balance(GRAPHENE_NULL_ACCOUNT, asset_id_type()), 1000 ); generate_blocks(db.get_dynamic_global_properties().next_maintenance_time); verify_asset_supplies(db); BOOST_CHECK_EQUAL(worker_id_type()(db).worker.get<burn_worker_type>().total_burned.value, 2000); BOOST_CHECK_EQUAL( get_balance(GRAPHENE_NULL_ACCOUNT, asset_id_type()), 2000 ); generate_blocks(db.get_dynamic_global_properties().next_maintenance_time); BOOST_CHECK(!db.get(worker_id_type()).is_active(db.head_block_time())); BOOST_CHECK_EQUAL(worker_id_type()(db).worker.get<burn_worker_type>().total_burned.value, 2000); BOOST_CHECK_EQUAL( get_balance(GRAPHENE_NULL_ACCOUNT, asset_id_type()), 2000 ); }FC_LOG_AND_RETHROW()} BOOST_AUTO_TEST_CASE( force_settle_test ) { uint32_t skip = database::skip_witness_signature | database::skip_transaction_signatures | database::skip_transaction_dupe_check | database::skip_block_size_check | database::skip_tapos_check | database::skip_authority_check | database::skip_merkle_check ; generate_block( skip ); for( int i=0; i<2; i++ ) { if( i == 1 ) { auto mi = db.get_global_properties().parameters.maintenance_interval; generate_blocks(HARDFORK_CORE_342_TIME - mi, true, skip); generate_blocks(db.get_dynamic_global_properties().next_maintenance_time, true, skip); } set_expiration( db, trx ); int blocks = 0; try { ACTORS( (nathan)(shorter1)(shorter2)(shorter3)(shorter4)(shorter5) ); int64_t initial_balance = 100000000; transfer(account_id_type()(db), shorter1_id(db), asset(initial_balance)); transfer(account_id_type()(db), shorter2_id(db), asset(initial_balance)); transfer(account_id_type()(db), shorter3_id(db), asset(initial_balance)); transfer(account_id_type()(db), shorter4_id(db), asset(initial_balance)); transfer(account_id_type()(db), shorter5_id(db), asset(initial_balance)); asset_id_type bitusd_id = create_bitasset( "USDBIT", nathan_id, 100, disable_force_settle ).id; asset_id_type core_id = asset_id_type(); auto update_bitasset_options = [&]( asset_id_type asset_id, std::function< void(bitasset_options&) > update_function ) { const asset_object& _asset = asset_id(db); asset_update_bitasset_operation op; op.asset_to_update = asset_id; op.issuer = _asset.issuer; op.new_options = (*_asset.bitasset_data_id)(db).options; update_function( op.new_options ); signed_transaction tx; tx.operations.push_back( op ); set_expiration( db, tx ); PUSH_TX( db, tx, ~0 ); } ; auto update_asset_options = [&]( asset_id_type asset_id, std::function< void(asset_options&) > update_function ) { const asset_object& _asset = asset_id(db); asset_update_operation op; op.asset_to_update = asset_id; op.issuer = _asset.issuer; op.new_options = _asset.options; update_function( op.new_options ); signed_transaction tx; tx.operations.push_back( op ); set_expiration( db, tx ); PUSH_TX( db, tx, ~0 ); } ; BOOST_TEST_MESSAGE( "Update maximum_force_settlement_volume = 9000" ); BOOST_CHECK( bitusd_id(db).is_market_issued() ); update_bitasset_options( bitusd_id, [&]( bitasset_options& new_options ) { new_options.maximum_force_settlement_volume = 9000; } ); BOOST_TEST_MESSAGE( "Publish price feed" ); update_feed_producers( bitusd_id, { nathan_id } ); { price_feed feed; feed.settlement_price = price( asset( 1, bitusd_id ), asset( 1, core_id ) ); publish_feed( bitusd_id, nathan_id, feed ); } BOOST_TEST_MESSAGE( "First short batch" ); call_order_id_type call1_id = borrow( shorter1_id, asset(1000, bitusd_id), asset(2*1000, core_id) )->id; // 2.0000 call_order_id_type call2_id = borrow( shorter2_id, asset(2000, bitusd_id), asset(2*1999, core_id) )->id; // 1.9990 call_order_id_type call3_id = borrow( shorter3_id, asset(3000, bitusd_id), asset(2*2890, core_id) )->id; // 1.9267 call_order_id_type call4_id = borrow( shorter4_id, asset(4000, bitusd_id), asset(2*3950, core_id) )->id; // 1.9750 call_order_id_type call5_id = borrow( shorter5_id, asset(5000, bitusd_id), asset(2*4900, core_id) )->id; // 1.9600 transfer( shorter1_id, nathan_id, asset(1000, bitusd_id) ); transfer( shorter2_id, nathan_id, asset(2000, bitusd_id) ); transfer( shorter3_id, nathan_id, asset(3000, bitusd_id) ); transfer( shorter4_id, nathan_id, asset(4000, bitusd_id) ); transfer( shorter5_id, nathan_id, asset(5000, bitusd_id) ); BOOST_CHECK_EQUAL( get_balance(nathan_id, bitusd_id), 15000); BOOST_CHECK_EQUAL( get_balance(nathan_id, core_id), 0); BOOST_CHECK_EQUAL( get_balance(shorter1_id, core_id), initial_balance-2000 ); BOOST_CHECK_EQUAL( get_balance(shorter2_id, core_id), initial_balance-3998 ); BOOST_CHECK_EQUAL( get_balance(shorter3_id, core_id), initial_balance-5780 ); BOOST_CHECK_EQUAL( get_balance(shorter4_id, core_id), initial_balance-7900 ); BOOST_CHECK_EQUAL( get_balance(shorter5_id, core_id), initial_balance-9800 ); BOOST_TEST_MESSAGE( "Update force_settlement_delay_sec = 100, force_settlement_offset_percent = 1%" ); update_bitasset_options( bitusd_id, [&]( bitasset_options& new_options ) { new_options.force_settlement_delay_sec = 100; new_options.force_settlement_offset_percent = GRAPHENE_1_PERCENT; } ); // Force settlement is disabled; check that it fails GRAPHENE_REQUIRE_THROW( force_settle( nathan_id, asset( 50, bitusd_id ) ), fc::exception ); update_asset_options( bitusd_id, [&]( asset_options& new_options ) { new_options.flags &= ~disable_force_settle; } ); // Can't settle more BitUSD than you own GRAPHENE_REQUIRE_THROW( force_settle( nathan_id, asset( 999999, bitusd_id ) ), fc::exception ); // settle3 should be least collateralized order according to index BOOST_CHECK( db.get_index_type<call_order_index>().indices().get<by_collateral>().begin()->id == call3_id ); BOOST_CHECK_EQUAL( call3_id(db).debt.value, 3000 ); BOOST_TEST_MESSAGE( "Verify partial settlement of call" ); // Partially settle a call force_settlement_id_type settle_id = force_settle( nathan_id, asset( 50, bitusd_id ) ).get< object_id_type >(); // Call does not take effect immediately BOOST_CHECK_EQUAL( get_balance(nathan_id, bitusd_id), 14950); BOOST_CHECK_EQUAL( settle_id(db).balance.amount.value, 50); BOOST_CHECK_EQUAL( call3_id(db).debt.value, 3000 ); BOOST_CHECK_EQUAL( call3_id(db).collateral.value, 5780 ); BOOST_CHECK( settle_id(db).owner == nathan_id ); // Wait for settlement to take effect generate_blocks( settle_id(db).settlement_date, true, skip ); blocks += 2; BOOST_CHECK(db.find(settle_id) == nullptr); BOOST_CHECK_EQUAL( bitusd_id(db).bitasset_data(db).force_settled_volume.value, 50 ); BOOST_CHECK_EQUAL( get_balance(nathan_id, bitusd_id), 14950); BOOST_CHECK_EQUAL( get_balance(nathan_id, core_id), 49 ); // 1% force_settlement_offset_percent (rounded unfavorably) BOOST_CHECK_EQUAL( call3_id(db).debt.value, 2950 ); BOOST_CHECK_EQUAL( call3_id(db).collateral.value, 5731 ); // 5731 == 5780-49 BOOST_CHECK( db.get_index_type<call_order_index>().indices().get<by_collateral>().begin()->id == call3_id ); BOOST_TEST_MESSAGE( "Verify pending settlement is cancelled when asset's force_settle is disabled" ); // Ensure pending settlement is cancelled when force settle is disabled settle_id = force_settle( nathan_id, asset( 50, bitusd_id ) ).get< object_id_type >(); BOOST_CHECK( !db.get_index_type<force_settlement_index>().indices().empty() ); update_asset_options( bitusd_id, [&]( asset_options& new_options ) { new_options.flags |= disable_force_settle; } ); BOOST_CHECK( db.get_index_type<force_settlement_index>().indices().empty() ); update_asset_options( bitusd_id, [&]( asset_options& new_options ) { new_options.flags &= ~disable_force_settle; } ); BOOST_TEST_MESSAGE( "Perform iterative settlement" ); settle_id = force_settle( nathan_id, asset( 12500, bitusd_id ) ).get< object_id_type >(); // c3 2950 : 5731 1.9427 fully settled // c5 5000 : 9800 1.9600 fully settled // c4 4000 : 7900 1.9750 fully settled // c2 2000 : 3998 1.9990 550 settled // c1 1000 : 2000 2.0000 generate_blocks( settle_id(db).settlement_date, true, skip ); blocks += 2; int64_t call1_payout = 0; int64_t call2_payout = 550*99/100; int64_t call3_payout = 49 + 2950*99/100; int64_t call4_payout = 4000*99/100; int64_t call5_payout = 5000*99/100; if( i == 1 ) // BSIP35: better rounding { call3_payout = 49 + (2950*99+100-1)/100; // round up call4_payout = (4000*99+100-1)/100; // round up call5_payout = (5000*99+100-1)/100; // round up } BOOST_CHECK_EQUAL( get_balance(shorter1_id, core_id), initial_balance-2*1000 ); // full collat still tied up BOOST_CHECK_EQUAL( get_balance(shorter2_id, core_id), initial_balance-2*1999 ); // full collat still tied up BOOST_CHECK_EQUAL( get_balance(shorter3_id, core_id), initial_balance-call3_payout ); // initial balance minus transfer to Nathan (as BitUSD) BOOST_CHECK_EQUAL( get_balance(shorter4_id, core_id), initial_balance-call4_payout ); // initial balance minus transfer to Nathan (as BitUSD) BOOST_CHECK_EQUAL( get_balance(shorter5_id, core_id), initial_balance-call5_payout ); // initial balance minus transfer to Nathan (as BitUSD) BOOST_CHECK_EQUAL( get_balance(nathan_id, core_id), call1_payout + call2_payout + call3_payout + call4_payout + call5_payout ); BOOST_CHECK( db.find(call3_id) == nullptr ); BOOST_CHECK( db.find(call4_id) == nullptr ); BOOST_CHECK( db.find(call5_id) == nullptr ); BOOST_REQUIRE( db.find(call1_id) != nullptr ); BOOST_REQUIRE( db.find(call2_id) != nullptr ); BOOST_CHECK_EQUAL( call1_id(db).debt.value, 1000 ); BOOST_CHECK_EQUAL( call1_id(db).collateral.value, 2000 ); BOOST_CHECK_EQUAL( call2_id(db).debt.value, 2000-550 ); BOOST_CHECK_EQUAL( call2_id(db).collateral.value, 3998-call2_payout ); } catch(fc::exception& e) { edump((e.to_detail_string())); throw; } // undo above tx's and reset generate_block( skip ); ++blocks; while( blocks > 0 ) { db.pop_block(); --blocks; } } } BOOST_AUTO_TEST_CASE( assert_op_test ) { try { // create some objects auto nathan_private_key = generate_private_key("nathan"); public_key_type nathan_public_key = nathan_private_key.get_public_key(); account_id_type nathan_id = create_account("nathan", nathan_public_key).id; assert_operation op; // nathan checks that his public key is equal to the given value. op.fee_paying_account = nathan_id; op.predicates.emplace_back(account_name_eq_lit_predicate{ nathan_id, "nathan" }); trx.operations.push_back(op); sign( trx, nathan_private_key ); PUSH_TX( db, trx ); // nathan checks that his public key is not equal to the given value (fail) trx.clear(); op.predicates.emplace_back(account_name_eq_lit_predicate{ nathan_id, "dan" }); trx.operations.push_back(op); sign( trx, nathan_private_key ); GRAPHENE_CHECK_THROW( PUSH_TX( db, trx ), fc::exception ); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( balance_object_test ) { try { // Intentionally overriding the fixture's db; I need to control genesis on this one. database db; const uint32_t skip_flags = database::skip_undo_history_check; fc::temp_directory td( graphene::utilities::temp_directory_path() ); genesis_state.initial_balances.push_back({generate_private_key("n").get_public_key(), GRAPHENE_SYMBOL, 1}); genesis_state.initial_balances.push_back({generate_private_key("x").get_public_key(), GRAPHENE_SYMBOL, 1}); fc::time_point_sec starting_time = genesis_state.initial_timestamp + 3000; auto n_key = generate_private_key("n"); auto x_key = generate_private_key("x"); auto v1_key = generate_private_key("v1"); auto v2_key = generate_private_key("v2"); genesis_state_type::initial_vesting_balance_type vest; vest.owner = v1_key.get_public_key(); vest.asset_symbol = GRAPHENE_SYMBOL; vest.amount = 500; vest.begin_balance = vest.amount; vest.begin_timestamp = starting_time; vest.vesting_duration_seconds = 60; genesis_state.initial_vesting_balances.push_back(vest); vest.owner = v2_key.get_public_key(); vest.begin_timestamp -= fc::seconds(30); vest.amount = 400; genesis_state.initial_vesting_balances.push_back(vest); genesis_state.initial_accounts.emplace_back("n", n_key.get_public_key()); auto _sign = [&]( signed_transaction& tx, const private_key_type& key ) { tx.sign( key, db.get_chain_id() ); }; db.open(td.path(), [this]{return genesis_state;}, "TEST"); const balance_object& balance = balance_id_type()(db); BOOST_CHECK_EQUAL(balance.balance.amount.value, 1); BOOST_CHECK_EQUAL(balance_id_type(1)(db).balance.amount.value, 1); balance_claim_operation op; op.deposit_to_account = db.get_index_type<account_index>().indices().get<by_name>().find("n")->get_id(); op.total_claimed = asset(1); op.balance_to_claim = balance_id_type(1); op.balance_owner_key = x_key.get_public_key(); trx.operations = {op}; _sign( trx, n_key ); // Fail because I'm claiming from an address which hasn't signed GRAPHENE_CHECK_THROW(db.push_transaction(trx), tx_missing_other_auth); trx.clear(); op.balance_to_claim = balance_id_type(); op.balance_owner_key = n_key.get_public_key(); trx.operations = {op}; _sign( trx, n_key ); db.push_transaction(trx); // Not using fixture's get_balance() here because it uses fixture's db, not my override BOOST_CHECK_EQUAL(db.get_balance(op.deposit_to_account, asset_id_type()).amount.value, 1); BOOST_CHECK(db.find_object(balance_id_type()) == nullptr); BOOST_CHECK(db.find_object(balance_id_type(1)) != nullptr); auto slot = db.get_slot_at_time(starting_time); db.generate_block(starting_time, db.get_scheduled_witness(slot), init_account_priv_key, skip_flags); set_expiration( db, trx ); const balance_object& vesting_balance_1 = balance_id_type(2)(db); const balance_object& vesting_balance_2 = balance_id_type(3)(db); BOOST_CHECK(vesting_balance_1.is_vesting_balance()); BOOST_CHECK_EQUAL(vesting_balance_1.balance.amount.value, 500); BOOST_CHECK_EQUAL(vesting_balance_1.available(db.head_block_time()).amount.value, 0); BOOST_CHECK(vesting_balance_2.is_vesting_balance()); BOOST_CHECK_EQUAL(vesting_balance_2.balance.amount.value, 400); BOOST_CHECK_EQUAL(vesting_balance_2.available(db.head_block_time()).amount.value, 150); op.balance_to_claim = vesting_balance_1.id; op.total_claimed = asset(1); op.balance_owner_key = v1_key.get_public_key(); trx.clear(); trx.operations = {op}; _sign( trx, n_key ); _sign( trx, v1_key ); // Attempting to claim 1 from a balance with 0 available GRAPHENE_CHECK_THROW(db.push_transaction(trx), balance_claim_invalid_claim_amount); op.balance_to_claim = vesting_balance_2.id; op.total_claimed.amount = 151; op.balance_owner_key = v2_key.get_public_key(); trx.operations = {op}; trx.signatures.clear(); _sign( trx, n_key ); _sign( trx, v2_key ); // Attempting to claim 151 from a balance with 150 available GRAPHENE_CHECK_THROW(db.push_transaction(trx), balance_claim_invalid_claim_amount); op.balance_to_claim = vesting_balance_2.id; op.total_claimed.amount = 100; op.balance_owner_key = v2_key.get_public_key(); trx.operations = {op}; trx.signatures.clear(); _sign( trx, n_key ); _sign( trx, v2_key ); db.push_transaction(trx); BOOST_CHECK_EQUAL(db.get_balance(op.deposit_to_account, asset_id_type()).amount.value, 101); BOOST_CHECK_EQUAL(vesting_balance_2.balance.amount.value, 300); op.total_claimed.amount = 10; trx.operations = {op}; trx.signatures.clear(); _sign( trx, n_key ); _sign( trx, v2_key ); // Attempting to claim twice within a day GRAPHENE_CHECK_THROW(db.push_transaction(trx), balance_claim_claimed_too_often); db.generate_block(db.get_slot_time(1), db.get_scheduled_witness(1), init_account_priv_key, skip_flags); slot = db.get_slot_at_time(vesting_balance_1.vesting_policy->begin_timestamp + 60); db.generate_block(db.get_slot_time(slot), db.get_scheduled_witness(slot), init_account_priv_key, skip_flags); set_expiration( db, trx ); op.balance_to_claim = vesting_balance_1.id; op.total_claimed.amount = 500; op.balance_owner_key = v1_key.get_public_key(); trx.operations = {op}; trx.signatures.clear(); _sign( trx, n_key ); _sign( trx, v1_key ); db.push_transaction(trx); BOOST_CHECK(db.find_object(op.balance_to_claim) == nullptr); BOOST_CHECK_EQUAL(db.get_balance(op.deposit_to_account, asset_id_type()).amount.value, 601); op.balance_to_claim = vesting_balance_2.id; op.balance_owner_key = v2_key.get_public_key(); op.total_claimed.amount = 10; trx.operations = {op}; trx.signatures.clear(); _sign( trx, n_key ); _sign( trx, v2_key ); // Attempting to claim twice within a day GRAPHENE_CHECK_THROW(db.push_transaction(trx), balance_claim_claimed_too_often); db.generate_block(db.get_slot_time(1), db.get_scheduled_witness(1), init_account_priv_key, skip_flags); slot = db.get_slot_at_time(db.head_block_time() + fc::days(1)); db.generate_block(db.get_slot_time(slot), db.get_scheduled_witness(slot), init_account_priv_key, skip_flags); set_expiration( db, trx ); op.total_claimed = vesting_balance_2.balance; trx.operations = {op}; trx.signatures.clear(); _sign( trx, n_key ); _sign( trx, v2_key ); db.push_transaction(trx); BOOST_CHECK(db.find_object(op.balance_to_claim) == nullptr); BOOST_CHECK_EQUAL(db.get_balance(op.deposit_to_account, asset_id_type()).amount.value, 901); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE(transfer_with_memo) { try { ACTOR(alice); ACTOR(bob); transfer(account_id_type(), alice_id, asset(1000)); BOOST_CHECK_EQUAL(get_balance(alice_id, asset_id_type()), 1000); transfer_operation op; op.from = alice_id; op.to = bob_id; op.amount = asset(500); op.memo = memo_data(); op.memo->set_message(alice_private_key, bob_public_key, "Dear Bob,\n\nMoney!\n\nLove, Alice"); trx.operations = {op}; trx.sign(alice_private_key, db.get_chain_id()); db.push_transaction(trx); BOOST_CHECK_EQUAL(get_balance(alice_id, asset_id_type()), 500); BOOST_CHECK_EQUAL(get_balance(bob_id, asset_id_type()), 500); auto memo = db.get_recent_transaction(trx.id()).operations.front().get<transfer_operation>().memo; BOOST_CHECK(memo); BOOST_CHECK_EQUAL(memo->get_message(bob_private_key, alice_public_key), "Dear Bob,\n\nMoney!\n\nLove, Alice"); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE(zero_second_vbo) { try { ACTOR(alice); // don't pay witnesses so we have some worker budget to work with transfer(account_id_type(), alice_id, asset(int64_t(100000) * 1100 * 1000 * 1000)); { asset_reserve_operation op; op.payer = alice_id; op.amount_to_reserve = asset(int64_t(100000) * 1000 * 1000 * 1000); transaction tx; tx.operations.push_back( op ); set_expiration( db, tx ); db.push_transaction( tx, database::skip_authority_check | database::skip_tapos_check | database::skip_transaction_signatures ); } enable_fees(); upgrade_to_lifetime_member(alice_id); generate_block(); // Wait for a maintenance interval to ensure we have a full day's budget to work with. // Otherwise we may not have enough to feed the witnesses and the worker will end up starved if we start late in the day. generate_blocks(db.get_dynamic_global_properties().next_maintenance_time); generate_block(); auto check_vesting_1b = [&](vesting_balance_id_type vbid) { // this function checks that Alice can't draw any right now, // but one block later, she can withdraw it all. vesting_balance_withdraw_operation withdraw_op; withdraw_op.vesting_balance = vbid; withdraw_op.owner = alice_id; withdraw_op.amount = asset(1); signed_transaction withdraw_tx; withdraw_tx.operations.push_back( withdraw_op ); sign(withdraw_tx, alice_private_key); GRAPHENE_REQUIRE_THROW( PUSH_TX( db, withdraw_tx ), fc::exception ); generate_block(); withdraw_tx = signed_transaction(); withdraw_op.amount = asset(500); withdraw_tx.operations.push_back( withdraw_op ); set_expiration( db, withdraw_tx ); sign(withdraw_tx, alice_private_key); PUSH_TX( db, withdraw_tx ); }; // This block creates a zero-second VBO with a vesting_balance_create_operation. { cdd_vesting_policy_initializer pinit; pinit.vesting_seconds = 0; vesting_balance_create_operation create_op; create_op.creator = alice_id; create_op.owner = alice_id; create_op.amount = asset(500); create_op.policy = pinit; signed_transaction create_tx; create_tx.operations.push_back( create_op ); set_expiration( db, create_tx ); sign(create_tx, alice_private_key); processed_transaction ptx = PUSH_TX( db, create_tx ); vesting_balance_id_type vbid = ptx.operation_results[0].get<object_id_type>(); check_vesting_1b( vbid ); } // This block creates a zero-second VBO with a worker_create_operation. { worker_create_operation create_op; create_op.owner = alice_id; create_op.work_begin_date = db.head_block_time(); create_op.work_end_date = db.head_block_time() + fc::days(1000); create_op.daily_pay = share_type( 10000 ); create_op.name = "alice"; create_op.url = ""; create_op.initializer = vesting_balance_worker_initializer(0); signed_transaction create_tx; create_tx.operations.push_back(create_op); set_expiration( db, create_tx ); sign(create_tx, alice_private_key); processed_transaction ptx = PUSH_TX( db, create_tx ); worker_id_type wid = ptx.operation_results[0].get<object_id_type>(); // vote it in account_update_operation vote_op; vote_op.account = alice_id; vote_op.new_options = alice_id(db).options; vote_op.new_options->votes.insert(wid(db).vote_for); signed_transaction vote_tx; vote_tx.operations.push_back(vote_op); set_expiration( db, vote_tx ); sign( vote_tx, alice_private_key ); PUSH_TX( db, vote_tx ); // vote it in, wait for one maint. for vote to take effect vesting_balance_id_type vbid = wid(db).worker.get<vesting_balance_worker_type>().balance; // wait for another maint. for worker to be paid generate_blocks(db.get_dynamic_global_properties().next_maintenance_time); BOOST_CHECK( vbid(db).get_allowed_withdraw(db.head_block_time()) == asset(0) ); generate_block(); BOOST_CHECK( vbid(db).get_allowed_withdraw(db.head_block_time()) == asset(10000) ); /* db.get_index_type< simple_index<budget_record_object> >().inspect_all_objects( [&](const object& o) { ilog( "budget: ${brec}", ("brec", static_cast<const budget_record_object&>(o)) ); }); */ } } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( vbo_withdraw_different ) { try { ACTORS((alice)(izzy)); // don't pay witnesses so we have some worker budget to work with // transfer(account_id_type(), alice_id, asset(1000)); asset_id_type stuff_id = create_user_issued_asset( "STUFF", izzy_id(db), 0 ).id; issue_uia( alice_id, asset( 1000, stuff_id ) ); // deposit STUFF with linear vesting policy vesting_balance_id_type vbid; { linear_vesting_policy_initializer pinit; pinit.begin_timestamp = db.head_block_time(); pinit.vesting_cliff_seconds = 30; pinit.vesting_duration_seconds = 30; vesting_balance_create_operation create_op; create_op.creator = alice_id; create_op.owner = alice_id; create_op.amount = asset(100, stuff_id); create_op.policy = pinit; signed_transaction create_tx; create_tx.operations.push_back( create_op ); set_expiration( db, create_tx ); sign(create_tx, alice_private_key); processed_transaction ptx = PUSH_TX( db, create_tx ); vbid = ptx.operation_results[0].get<object_id_type>(); } // wait for VB to mature generate_blocks( 30 ); BOOST_CHECK( vbid(db).get_allowed_withdraw( db.head_block_time() ) == asset(100, stuff_id) ); // bad withdrawal op (wrong asset) { vesting_balance_withdraw_operation op; op.vesting_balance = vbid; op.amount = asset(100); op.owner = alice_id; signed_transaction withdraw_tx; withdraw_tx.operations.push_back(op); set_expiration( db, withdraw_tx ); sign( withdraw_tx, alice_private_key ); GRAPHENE_CHECK_THROW( PUSH_TX( db, withdraw_tx ), fc::exception ); } // good withdrawal op { vesting_balance_withdraw_operation op; op.vesting_balance = vbid; op.amount = asset(100, stuff_id); op.owner = alice_id; signed_transaction withdraw_tx; withdraw_tx.operations.push_back(op); set_expiration( db, withdraw_tx ); sign( withdraw_tx, alice_private_key ); PUSH_TX( db, withdraw_tx ); } } FC_LOG_AND_RETHROW() } // TODO: Write linear VBO tests BOOST_AUTO_TEST_CASE( top_n_special ) { ACTORS( (alice)(bob)(chloe)(dan)(izzy)(stan) ); generate_blocks( HARDFORK_516_TIME ); generate_blocks( HARDFORK_599_TIME ); try { { // // Izzy (issuer) // Stan (special authority) // Alice, Bob, Chloe, Dan (ABCD) // asset_id_type topn_id = create_user_issued_asset( "TOPN", izzy_id(db), 0 ).id; authority stan_owner_auth = stan_id(db).owner; authority stan_active_auth = stan_id(db).active; // set SA, wait for maint interval // TODO: account_create_operation // TODO: multiple accounts with different n for same asset { top_holders_special_authority top2, top3; top2.num_top_holders = 2; top2.asset = topn_id; top3.num_top_holders = 3; top3.asset = topn_id; account_update_operation op; op.account = stan_id; op.extensions.value.active_special_authority = top3; op.extensions.value.owner_special_authority = top2; signed_transaction tx; tx.operations.push_back( op ); set_expiration( db, tx ); sign( tx, stan_private_key ); PUSH_TX( db, tx ); // TODO: Check special_authority is properly set // TODO: Do it in steps } // wait for maint interval // make sure we don't have any authority as account hasn't gotten distributed yet generate_blocks(db.get_dynamic_global_properties().next_maintenance_time); BOOST_CHECK( stan_id(db).owner == stan_owner_auth ); BOOST_CHECK( stan_id(db).active == stan_active_auth ); // issue some to Alice, make sure she gets control of Stan // we need to set_expiration() before issue_uia() because the latter doens't call it #11 set_expiration( db, trx ); // #11 issue_uia( alice_id, asset( 1000, topn_id ) ); BOOST_CHECK( stan_id(db).owner == stan_owner_auth ); BOOST_CHECK( stan_id(db).active == stan_active_auth ); generate_blocks(db.get_dynamic_global_properties().next_maintenance_time); /* NOTE - this was an old check from an earlier implementation that only allowed SA for LTM's // no boost yet, we need to upgrade to LTM before mechanics apply to Stan BOOST_CHECK( stan_id(db).owner == stan_owner_auth ); BOOST_CHECK( stan_id(db).active == stan_active_auth ); set_expiration( db, trx ); // #11 upgrade_to_lifetime_member(stan_id); generate_blocks(db.get_dynamic_global_properties().next_maintenance_time); */ BOOST_CHECK( stan_id(db).owner == authority( 501, alice_id, 1000 ) ); BOOST_CHECK( stan_id(db).active == authority( 501, alice_id, 1000 ) ); // give asset to Stan, make sure owner doesn't change at all set_expiration( db, trx ); // #11 transfer( alice_id, stan_id, asset( 1000, topn_id ) ); generate_blocks(db.get_dynamic_global_properties().next_maintenance_time); BOOST_CHECK( stan_id(db).owner == authority( 501, alice_id, 1000 ) ); BOOST_CHECK( stan_id(db).active == authority( 501, alice_id, 1000 ) ); set_expiration( db, trx ); // #11 issue_uia( chloe_id, asset( 131000, topn_id ) ); // now Chloe has 131,000 and Stan has 1k. Make sure change occurs at next maintenance interval. // NB, 131072 is a power of 2; the number 131000 was chosen so that we need a bitshift, but // if we put the 1000 from Stan's balance back into play, we need a different bitshift. // we use Chloe so she can be displaced by Bob later (showing the tiebreaking logic). // Check Alice is still in control, because we're deferred to next maintenance interval BOOST_CHECK( stan_id(db).owner == authority( 501, alice_id, 1000 ) ); BOOST_CHECK( stan_id(db).active == authority( 501, alice_id, 1000 ) ); generate_blocks(db.get_dynamic_global_properties().next_maintenance_time); BOOST_CHECK( stan_id(db).owner == authority( 32751, chloe_id, 65500 ) ); BOOST_CHECK( stan_id(db).active == authority( 32751, chloe_id, 65500 ) ); // put Alice's stake back in play set_expiration( db, trx ); // #11 transfer( stan_id, alice_id, asset( 1000, topn_id ) ); generate_blocks(db.get_dynamic_global_properties().next_maintenance_time); BOOST_CHECK( stan_id(db).owner == authority( 33001, alice_id, 500, chloe_id, 65500 ) ); BOOST_CHECK( stan_id(db).active == authority( 33001, alice_id, 500, chloe_id, 65500 ) ); // issue 200,000 to Dan to cause another bitshift. set_expiration( db, trx ); // #11 issue_uia( dan_id, asset( 200000, topn_id ) ); generate_blocks(db.get_dynamic_global_properties().next_maintenance_time); // 200000 Dan // 131000 Chloe // 1000 Alice BOOST_CHECK( stan_id(db).owner == authority( 41376, chloe_id, 32750, dan_id, 50000 ) ); BOOST_CHECK( stan_id(db).active == authority( 41501, alice_id, 250, chloe_id, 32750, dan_id, 50000 ) ); // have Alice send all but 1 back to Stan, verify that we clamp Alice at one vote set_expiration( db, trx ); // #11 transfer( alice_id, stan_id, asset( 999, topn_id ) ); generate_blocks(db.get_dynamic_global_properties().next_maintenance_time); BOOST_CHECK( stan_id(db).owner == authority( 41376, chloe_id, 32750, dan_id, 50000 ) ); BOOST_CHECK( stan_id(db).active == authority( 41376, alice_id, 1, chloe_id, 32750, dan_id, 50000 ) ); // send 131k to Bob so he's tied with Chloe, verify he displaces Chloe in top2 set_expiration( db, trx ); // #11 issue_uia( bob_id, asset( 131000, topn_id ) ); generate_blocks(db.get_dynamic_global_properties().next_maintenance_time); BOOST_CHECK( stan_id(db).owner == authority( 41376, bob_id, 32750, dan_id, 50000 ) ); BOOST_CHECK( stan_id(db).active == authority( 57751, bob_id, 32750, chloe_id, 32750, dan_id, 50000 ) ); // TODO more rounding checks } } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( buyback ) { ACTORS( (alice)(bob)(chloe)(dan)(izzy)(philbin) ); upgrade_to_lifetime_member(philbin_id); generate_blocks( HARDFORK_538_TIME ); generate_blocks( HARDFORK_555_TIME ); generate_blocks( HARDFORK_599_TIME ); try { { // // Izzy (issuer) // Alice, Bob, Chloe, Dan (ABCD) // Rex (recycler -- buyback account) // Philbin (registrar) // asset_id_type nono_id = create_user_issued_asset( "NONO", izzy_id(db), 0 ).id; asset_id_type buyme_id = create_user_issued_asset( "BUYME", izzy_id(db), 0 ).id; // Create a buyback account account_id_type rex_id; { buyback_account_options bbo; bbo.asset_to_buy = buyme_id; bbo.asset_to_buy_issuer = izzy_id; bbo.markets.emplace( asset_id_type() ); account_create_operation create_op = make_account( "rex" ); create_op.registrar = philbin_id; create_op.extensions.value.buyback_options = bbo; create_op.owner = authority::null_authority(); create_op.active = authority::null_authority(); // Let's break it... signed_transaction tx; tx.operations.push_back( create_op ); set_expiration( db, tx ); tx.operations.back().get< account_create_operation >().extensions.value.buyback_options->asset_to_buy_issuer = alice_id; sign( tx, alice_private_key ); sign( tx, philbin_private_key ); // Alice and Philbin signed, but asset issuer is invalid GRAPHENE_CHECK_THROW( db.push_transaction(tx), account_create_buyback_incorrect_issuer ); tx.signatures.clear(); tx.operations.back().get< account_create_operation >().extensions.value.buyback_options->asset_to_buy_issuer = izzy_id; sign( tx, philbin_private_key ); // Izzy didn't sign GRAPHENE_CHECK_THROW( db.push_transaction(tx), tx_missing_active_auth ); sign( tx, izzy_private_key ); // OK processed_transaction ptx = db.push_transaction( tx ); rex_id = ptx.operation_results.back().get< object_id_type >(); // Try to create another account rex2 which is bbo on same asset tx.signatures.clear(); tx.operations.back().get< account_create_operation >().name = "rex2"; sign( tx, izzy_private_key ); sign( tx, philbin_private_key ); GRAPHENE_CHECK_THROW( db.push_transaction(tx), account_create_buyback_already_exists ); } // issue some BUYME to Alice // we need to set_expiration() before issue_uia() because the latter doens't call it #11 set_expiration( db, trx ); // #11 issue_uia( alice_id, asset( 1000, buyme_id ) ); issue_uia( alice_id, asset( 1000, nono_id ) ); // Alice wants to sell 100 BUYME for 1000 BTS, a middle price. limit_order_id_type order_id_mid = create_sell_order( alice_id, asset( 100, buyme_id ), asset( 1000, asset_id_type() ) )->id; generate_blocks(db.get_dynamic_global_properties().next_maintenance_time); generate_block(); // no success because buyback has none for sale BOOST_CHECK( order_id_mid(db).for_sale == 100 ); // but we can send some to buyback fund( rex_id(db), asset( 100, asset_id_type() ) ); // no action until next maint BOOST_CHECK( order_id_mid(db).for_sale == 100 ); generate_blocks(db.get_dynamic_global_properties().next_maintenance_time); generate_block(); // partial fill, Alice now sells 90 BUYME for 900 BTS. BOOST_CHECK( order_id_mid(db).for_sale == 90 ); // TODO check burn amount // aagh more state in trx set_expiration( db, trx ); // #11 // Selling 10 BUYME for 50 BTS, a low price. limit_order_id_type order_id_low = create_sell_order( alice_id, asset( 10, buyme_id ), asset( 50, asset_id_type() ) )->id; // Selling 10 BUYME for 150 BTS, a high price. limit_order_id_type order_id_high = create_sell_order( alice_id, asset( 10, buyme_id ), asset( 150, asset_id_type() ) )->id; fund( rex_id(db), asset( 250, asset_id_type() ) ); generate_blocks(db.get_dynamic_global_properties().next_maintenance_time); generate_block(); BOOST_CHECK( db.find( order_id_low ) == nullptr ); BOOST_CHECK( db.find( order_id_mid ) != nullptr ); BOOST_CHECK( db.find( order_id_high ) != nullptr ); // 250 CORE in rex 90 BUYME in mid order 10 BUYME in low order // 50 CORE goes to low order, buy 10 for 50 CORE // 200 CORE goes to mid order, buy 20 for 200 CORE // 70 BUYME in mid order 0 BUYME in low order idump( (order_id_mid(db)) ); BOOST_CHECK( order_id_mid(db).for_sale == 70 ); BOOST_CHECK( order_id_high(db).for_sale == 10 ); BOOST_CHECK( get_balance( rex_id, asset_id_type() ) == 0 ); // clear out the books -- 700 left on mid order, 150 left on high order, so 2000 BTS should result in 1150 left over fund( rex_id(db), asset( 2000, asset_id_type() ) ); generate_blocks(db.get_dynamic_global_properties().next_maintenance_time); idump( (get_balance( rex_id, asset_id_type() )) ); BOOST_CHECK( get_balance( rex_id, asset_id_type() ) == 1150 ); GRAPHENE_CHECK_THROW( transfer( alice_id, rex_id, asset( 1, nono_id ) ), fc::exception ); // TODO: Check cancellation works for account which is BTS-restricted } } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_SUITE_END()
43.126931
209
0.69658
[ "object" ]
8b154002547b295af89fd64d4eda92f89e1c814c
4,507
cpp
C++
driver/api/impl/handles.cpp
MaxFedotov/clickhouse-odbc
f5446f7b5565644bc9ea2b55ed34250c9b7d394d
[ "Apache-2.0" ]
null
null
null
driver/api/impl/handles.cpp
MaxFedotov/clickhouse-odbc
f5446f7b5565644bc9ea2b55ed34250c9b7d394d
[ "Apache-2.0" ]
null
null
null
driver/api/impl/handles.cpp
MaxFedotov/clickhouse-odbc
f5446f7b5565644bc9ea2b55ed34250c9b7d394d
[ "Apache-2.0" ]
null
null
null
#include "driver/utils/utils.h" #include "driver/driver.h" #include "driver/environment.h" #include "driver/connection.h" #include "driver/descriptor.h" #include "driver/statement.h" #include <Poco/Net/HTTPClientSession.h> #include <type_traits> namespace { namespace impl { SQLRETURN allocEnv(SQLHENV * out_environment_handle) noexcept { return CALL([&] () { if (nullptr == out_environment_handle) return SQL_INVALID_HANDLE; *out_environment_handle = Driver::getInstance().allocateChild<Environment>().getHandle(); return SQL_SUCCESS; }); } SQLRETURN allocConnect(SQLHENV environment_handle, SQLHDBC * out_connection_handle) noexcept { return CALL_WITH_HANDLE(environment_handle, [&] (Environment & environment) { if (nullptr == out_connection_handle) return SQL_INVALID_HANDLE; *out_connection_handle = environment.allocateChild<Connection>().getHandle(); return SQL_SUCCESS; }); } SQLRETURN allocStmt(SQLHDBC connection_handle, SQLHSTMT * out_statement_handle) noexcept { return CALL_WITH_HANDLE(connection_handle, [&] (Connection & connection) { if (nullptr == out_statement_handle) return SQL_INVALID_HANDLE; *out_statement_handle = connection.allocateChild<Statement>().getHandle(); return SQL_SUCCESS; }); } SQLRETURN allocDesc(SQLHDBC connection_handle, SQLHDESC * out_descriptor_handle) noexcept { return CALL_WITH_HANDLE(connection_handle, [&] (Connection & connection) { if (nullptr == out_descriptor_handle) return SQL_INVALID_HANDLE; auto & descriptor = connection.allocateChild<Descriptor>(); connection.initAsAD(descriptor, true); *out_descriptor_handle = descriptor.getHandle(); return SQL_SUCCESS; }); } SQLRETURN freeHandle(SQLHANDLE handle) noexcept { return CALL_WITH_HANDLE_SKIP_DIAG(handle, [&] (auto & object) { if ( // Refuse to manually deallocate an automatically allocated descriptor. std::is_convertible<std::decay<decltype(object)> *, Descriptor *>::value && object.template getAttrAs<SQLSMALLINT>(SQL_DESC_ALLOC_TYPE) != SQL_DESC_ALLOC_USER ) { return SQL_ERROR; } object.deallocateSelf(); return SQL_SUCCESS; }); } } } // namespace impl extern "C" { SQLRETURN SQL_API EXPORTED_FUNCTION(SQLAllocHandle)(SQLSMALLINT handle_type, SQLHANDLE input_handle, SQLHANDLE * output_handle) { LOG(__FUNCTION__ << " handle_type=" << handle_type << " input_handle=" << input_handle); switch (handle_type) { case SQL_HANDLE_ENV: return impl::allocEnv((SQLHENV *)output_handle); case SQL_HANDLE_DBC: return impl::allocConnect((SQLHENV)input_handle, (SQLHDBC *)output_handle); case SQL_HANDLE_STMT: return impl::allocStmt((SQLHDBC)input_handle, (SQLHSTMT *)output_handle); case SQL_HANDLE_DESC: return impl::allocDesc((SQLHDBC)input_handle, (SQLHDESC *)output_handle); default: LOG("AllocHandle: Unknown handleType=" << handle_type); return SQL_ERROR; } } SQLRETURN SQL_API EXPORTED_FUNCTION(SQLFreeHandle)(SQLSMALLINT handleType, SQLHANDLE handle) { LOG(__FUNCTION__ << " handleType=" << handleType << " handle=" << handle); switch (handleType) { case SQL_HANDLE_ENV: case SQL_HANDLE_DBC: case SQL_HANDLE_STMT: case SQL_HANDLE_DESC: return impl::freeHandle(handle); default: LOG("FreeHandle: Unknown handleType=" << handleType); return SQL_ERROR; } } SQLRETURN SQL_API EXPORTED_FUNCTION(SQLFreeStmt)(HSTMT statement_handle, SQLUSMALLINT option) { LOG(__FUNCTION__ << " option=" << option); return CALL_WITH_HANDLE(statement_handle, [&] (Statement & statement) -> SQLRETURN { switch (option) { case SQL_CLOSE: /// Close the cursor, ignore the remaining results. If there is no cursor, then noop. statement.closeCursor(); return SQL_SUCCESS; case SQL_DROP: return impl::freeHandle(statement_handle); case SQL_UNBIND: statement.resetColBindings(); return SQL_SUCCESS; case SQL_RESET_PARAMS: statement.resetParamBindings(); return SQL_SUCCESS; } return SQL_ERROR; }); } } // extern "C"
33.634328
129
0.662969
[ "object" ]
8b15ab4004e5bbc7d5405320c2f6933ed364b226
10,534
cpp
C++
examples/resource-forall.cpp
keichi/RAJA
8e8cc96cbccda2bfc33b14b57a8591b2cf9ca342
[ "BSD-3-Clause" ]
null
null
null
examples/resource-forall.cpp
keichi/RAJA
8e8cc96cbccda2bfc33b14b57a8591b2cf9ca342
[ "BSD-3-Clause" ]
null
null
null
examples/resource-forall.cpp
keichi/RAJA
8e8cc96cbccda2bfc33b14b57a8591b2cf9ca342
[ "BSD-3-Clause" ]
null
null
null
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// // Copyright (c) 2016-22, Lawrence Livermore National Security, LLC // and RAJA project contributors. See the RAJA/LICENSE file for details. // // SPDX-License-Identifier: (BSD-3-Clause) //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~// #include <cstdlib> #include <cstring> #include <iostream> #include "memoryManager.hpp" #include "RAJA/RAJA.hpp" #include "RAJA/util/resource.hpp" /* * Vector Addition Example * * Computes c = a + b, where a, b, c are vectors of ints. * It illustrates similarities between a C-style for-loop and a RAJA * forall loop. * * RAJA features shown: * - `forall` loop iteration template method * - Index range segment * - Execution policies * - `forall` with Resource argument * - Cuda/Hip streams w/ Resource * - Resources events * */ // // Functions for checking and printing results // void checkResult(int* res, int len); void printResult(int* res, int len); int main(int RAJA_UNUSED_ARG(argc), char **RAJA_UNUSED_ARG(argv[])) { std::cout << "\n\nRAJA vector addition example...\n"; // // Define vector length // const int N = 100000; // // Allocate and initialize vector data // RAJA::resources::Host host{}; int *a = host.allocate<int>(N); int *b = host.allocate<int>(N); int *c = host.allocate<int>(N); int *a_ = host.allocate<int>(N); int *b_ = host.allocate<int>(N); int *c_ = host.allocate<int>(N); for (int i = 0; i < N; ++i) { a[i] = -i; b[i] = 2 * i; a_[i] = -i; b_[i] = 2 * i; } //----------------------------------------------------------------------------// std::cout << "\n Running C-style vector addition...\n"; for (int i = 0; i < N; ++i) { c[i] = a[i] + b[i]; } checkResult(c, N); //----------------------------------------------------------------------------// // RAJA::seq_exec policy enforces strictly sequential execution.... //----------------------------------------------------------------------------// std::cout << "\n Running RAJA sequential vector addition...\n"; RAJA::forall<RAJA::seq_exec>(host, RAJA::RangeSegment(0, N), [=] (int i) { c[i] = a[i] + b[i]; }); checkResult(c, N); //----------------------------------------------------------------------------// // RAJA::loop_exec policy enforces loop execution.... //----------------------------------------------------------------------------// std::cout << "\n Running RAJA loop vector addition...\n"; RAJA::forall<RAJA::loop_exec>(host, RAJA::RangeSegment(0, N), [=] (int i) { c[i] = a[i] + b[i]; }); checkResult(c, N); //----------------------------------------------------------------------------// // RAJA::sind_exec policy enforces simd execution.... //----------------------------------------------------------------------------// std::cout << "\n Running RAJA simd_exec vector addition...\n"; RAJA::forall<RAJA::simd_exec>(host, RAJA::RangeSegment(0, N), [=] (int i) { c[i] = a[i] + b[i]; }); checkResult(c, N); #if defined(RAJA_ENABLE_OPENMP) //----------------------------------------------------------------------------// // RAJA::omp_for_parallel_exec policy execution.... //----------------------------------------------------------------------------// std::cout << "\n Running RAJA omp_parallel_for_exec vector addition...\n"; RAJA::forall<RAJA::omp_parallel_for_exec>(host, RAJA::RangeSegment(0, N), [=] RAJA_DEVICE (int i) { c[i] = a[i] + b[i]; }); checkResult(c, N); //----------------------------------------------------------------------------// // RAJA::omp_parallel_for_static_exec policy execution.... //----------------------------------------------------------------------------// std::cout << "\n Running RAJA omp_parallel_for_static_exec (default chunksize) vector addition...\n"; RAJA::forall<RAJA::omp_parallel_for_static_exec< >>(host, RAJA::RangeSegment(0, N), [=] (int i) { c[i] = a[i] + b[i]; }); checkResult(c, N); //----------------------------------------------------------------------------// // RAJA::omp_parallel_for_dynamic_exec policy execution.... //----------------------------------------------------------------------------// std::cout << "\n Running RAJA omp_for_dynamic_exec (chunksize = 16) vector addition...\n"; RAJA::forall<RAJA::omp_parallel_for_dynamic_exec<16>>(host, RAJA::RangeSegment(0, N), [=] (int i) { c[i] = a[i] + b[i]; }); checkResult(c, N); #endif #if defined(RAJA_ENABLE_TBB) //----------------------------------------------------------------------------// // RAJA::tbb_for_dynamic policy execution.... //----------------------------------------------------------------------------// std::cout << "\n Running RAJA tbb_for_dynamic vector addition...\n"; RAJA::forall<RAJA::tbb_for_dynamic>(host, RAJA::RangeSegment(0, N), [=] (int i) { c[i] = a[i] + b[i]; }); checkResult(c, N); //----------------------------------------------------------------------------// // RAJA::tbb_for_static policy execution.... //----------------------------------------------------------------------------// std::cout << "\n Running RAJA tbb_for_static<8> vector addition...\n"; RAJA::forall<RAJA::tbb_for_static<8>>(host, RAJA::RangeSegment(0, N), [=] (int i) { c[i] = a[i] + b[i]; }); checkResult(c, N); #endif #if defined(RAJA_ENABLE_CUDA) || defined(RAJA_ENABLE_HIP) || defined(RAJA_ENABLE_SYCL) /* GPU_BLOCK_SIZE - specifies the number of threads in a CUDA/HIP thread block */ const int GPU_BLOCK_SIZE = 256; //----------------------------------------------------------------------------// // RAJA::cuda/hip_exec policy execution.... //----------------------------------------------------------------------------// { std::cout << "\n Running RAJA GPU vector addition on 2 seperate streams...\n"; #if defined(RAJA_ENABLE_CUDA) RAJA::resources::Cuda res_gpu1; RAJA::resources::Cuda res_gpu2; using EXEC_POLICY = RAJA::cuda_exec_async<GPU_BLOCK_SIZE>; #elif defined(RAJA_ENABLE_HIP) RAJA::resources::Hip res_gpu1; RAJA::resources::Hip res_gpu2; using EXEC_POLICY = RAJA::hip_exec_async<GPU_BLOCK_SIZE>; #elif defined(RAJA_ENABLE_SYCL) RAJA::resources::Sycl res_gpu1; RAJA::resources::Sycl res_gpu2; using EXEC_POLICY = RAJA::sycl_exec<GPU_BLOCK_SIZE>; #endif int* d_a1 = res_gpu1.allocate<int>(N); int* d_b1 = res_gpu1.allocate<int>(N); int* d_c1 = res_gpu1.allocate<int>(N); int* d_a2 = res_gpu2.allocate<int>(N); int* d_b2 = res_gpu2.allocate<int>(N); int* d_c2 = res_gpu2.allocate<int>(N); res_gpu1.memcpy(d_a1, a, sizeof(int)* N); res_gpu1.memcpy(d_b1, b, sizeof(int)* N); res_gpu2.memcpy(d_a2, a, sizeof(int)* N); res_gpu2.memcpy(d_b2, b, sizeof(int)* N); RAJA::forall<EXEC_POLICY>(res_gpu1, RAJA::RangeSegment(0, N), [=] RAJA_DEVICE (int i) { d_c1[i] = d_a1[i] + d_b1[i]; }); RAJA::forall<EXEC_POLICY>(res_gpu2, RAJA::RangeSegment(0, N), [=] RAJA_DEVICE (int i) { d_c2[i] = d_a2[i] + d_b2[i]; }); res_gpu1.memcpy(c, d_c1, sizeof(int)*N ); res_gpu2.memcpy(c_, d_c2, sizeof(int)*N ); checkResult(c, N); checkResult(c_, N); res_gpu1.deallocate(d_a1); res_gpu1.deallocate(d_b1); res_gpu1.deallocate(d_c1); res_gpu2.deallocate(d_a2); res_gpu2.deallocate(d_b2); res_gpu2.deallocate(d_c2); } //----------------------------------------------------------------------------// // RAJA::cuda/hip_exec policy with waiting event.... //----------------------------------------------------------------------------// { std::cout << "\n Running RAJA GPU vector with dependency between two seperate streams...\n"; #if defined(RAJA_ENABLE_CUDA) // _raja_res_defres_start RAJA::resources::Cuda res_gpu1; RAJA::resources::Cuda res_gpu2; RAJA::resources::Host res_host; using EXEC_POLICY = RAJA::cuda_exec_async<GPU_BLOCK_SIZE>; // _raja_res_defres_end #elif defined(RAJA_ENABLE_HIP) RAJA::resources::Hip res_gpu1; RAJA::resources::Hip res_gpu2; RAJA::resources::Host res_host; using EXEC_POLICY = RAJA::hip_exec_async<GPU_BLOCK_SIZE>; #elif defined(RAJA_ENABLE_SYCL) RAJA::resources::Sycl res_gpu1; RAJA::resources::Sycl res_gpu2; RAJA::resources::Host res_host; using EXEC_POLICY = RAJA::sycl_exec<GPU_BLOCK_SIZE>; #endif // _raja_res_alloc_start int* d_array1 = res_gpu1.allocate<int>(N); int* d_array2 = res_gpu2.allocate<int>(N); int* h_array = res_host.allocate<int>(N); // _raja_res_alloc_end // _raja_res_k1_start RAJA::forall<EXEC_POLICY>(res_gpu1, RAJA::RangeSegment(0,N), [=] RAJA_HOST_DEVICE (int i) { d_array1[i] = i; } ); // _raja_res_k1_end // _raja_res_k2_start RAJA::resources::Event e = RAJA::forall<EXEC_POLICY>(res_gpu2, RAJA::RangeSegment(0,N), [=] RAJA_HOST_DEVICE (int i) { d_array2[i] = -1; } ); // _raja_res_k2_end // _raja_res_wait_start res_gpu2.wait_for(&e); // _raja_res_wait_end // _raja_res_k3_start RAJA::forall<EXEC_POLICY>(res_gpu1, RAJA::RangeSegment(0,N), [=] RAJA_HOST_DEVICE (int i) { d_array1[i] *= d_array2[i]; } ); // _raja_res_k3_end // _raja_res_memcpy_start res_gpu1.memcpy(h_array, d_array1, sizeof(int) * N); // _raja_res_memcpy_end // _raja_res_k4_start bool check = true; RAJA::forall<RAJA::seq_exec>(res_host, RAJA::RangeSegment(0,N), [&check, h_array] (int i) { if(h_array[i] != -i) {check = false;} } ); // _raja_res_k4_end std::cout << "\n result -- "; if (check) std::cout << "PASS\n"; else std::cout << "FAIL\n"; res_gpu1.deallocate(d_array1); res_gpu2.deallocate(d_array2); res_host.deallocate(h_array); } #endif // // // Clean up. // host.deallocate(a); host.deallocate(b); host.deallocate(c); host.deallocate(a_); host.deallocate(b_); host.deallocate(c_); std::cout << "\n DONE!...\n"; return 0; } // // Function to check result and report P/F. // void checkResult(int* res, int len) { bool correct = true; for (int i = 0; i < len; i++) { if ( res[i] != i ) { correct = false; } } if ( correct ) { std::cout << "\n\t result -- PASS\n"; } else { std::cout << "\n\t result -- FAIL\n"; } } // // Function to print result. // void printResult(int* res, int len) { std::cout << std::endl; for (int i = 0; i < len; i++) { std::cout << "result[" << i << "] = " << res[i] << std::endl; } std::cout << std::endl; }
27.219638
103
0.529334
[ "vector" ]
8b1601d0c42514b7c88f3c7fe969f2f95e338e02
1,610
hpp
C++
src/arcturus/arcturus_struct_type.hpp
aamshukov/arcturus
4d10cd15ff2b79f23621853961a2178c0bde7d79
[ "MIT" ]
1
2020-12-10T02:33:41.000Z
2020-12-10T02:33:41.000Z
src/arcturus/arcturus_struct_type.hpp
aamshukov/arcturus
4d10cd15ff2b79f23621853961a2178c0bde7d79
[ "MIT" ]
null
null
null
src/arcturus/arcturus_struct_type.hpp
aamshukov/arcturus
4d10cd15ff2b79f23621853961a2178c0bde7d79
[ "MIT" ]
null
null
null
//.............................. // UI Lab Inc. Arthur Amshukov . //.............................. #ifndef __ARCTURUS_STRUCT_TYPE_H__ #define __ARCTURUS_STRUCT_TYPE_H__ #pragma once BEGIN_NAMESPACE(arcturus) USING_NAMESPACE(core) USING_NAMESPACE(frontend) class arcturus_struct_type : public arcturus_scalar_type { public: using member_type = std::shared_ptr<arcturus_type>; using members_type = std::vector<member_type>; private: members_type my_members; public: arcturus_struct_type(); arcturus_struct_type(const arcturus_struct_type& other) = default; arcturus_struct_type(arcturus_struct_type&& other) = default; ~arcturus_struct_type(); arcturus_struct_type& operator = (const arcturus_struct_type& other) = default; arcturus_struct_type& operator = (arcturus_struct_type&& other) = default; friend bool operator == (const arcturus_struct_type& lhs, const arcturus_struct_type& rhs); friend bool operator != (const arcturus_struct_type& lhs, const arcturus_struct_type& rhs); const members_type& members() const; members_type& members(); }; inline const typename arcturus_struct_type::members_type& arcturus_struct_type::members() const { return my_members; } inline typename arcturus_struct_type::members_type& arcturus_struct_type::members() { return my_members; } END_NAMESPACE #endif // __ARCTURUS_STRUCT_TYPE_H__
29.814815
111
0.642236
[ "vector" ]
8b16045874e4077dec2b2de0226faae1cfad6a1f
4,270
hpp
C++
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Middlewares/ST/TouchGFX/touchgfx/framework/include/touchgfx/widgets/Image.hpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
3
2020-11-07T07:01:59.000Z
2022-03-06T10:54:52.000Z
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Middlewares/ST/TouchGFX/touchgfx/framework/include/touchgfx/widgets/Image.hpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
1
2020-11-14T16:53:09.000Z
2020-11-14T16:53:09.000Z
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Middlewares/ST/TouchGFX/touchgfx/framework/include/touchgfx/widgets/Image.hpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
3
2020-03-15T14:35:38.000Z
2021-04-07T14:55:42.000Z
/** ****************************************************************************** * This file is part of the TouchGFX 4.10.0 distribution. * * <h2><center>&copy; Copyright (c) 2018 STMicroelectronics. * All rights reserved.</center></h2> * * This software component is licensed by ST under Ultimate Liberty license * SLA0044, the "License"; You may not use this file except in compliance with * the License. You may obtain a copy of the License at: * www.st.com/SLA0044 * ****************************************************************************** */ #ifndef IMAGE_HPP #define IMAGE_HPP #include <touchgfx/hal/Types.hpp> #include <touchgfx/widgets/Widget.hpp> #include <touchgfx/Bitmap.hpp> #include <touchgfx/lcd/LCD.hpp> namespace touchgfx { /** * @class Image Image.hpp touchgfx/widgets/Image.hpp * * @brief Simple widget capable of showing a bitmap. * * Simple widget capable of showing a bitmap. The bitmap can be alpha-blended with the * background and have areas of transparency. * * @see Widget */ class Image : public Widget { public: /** * @fn Image::Image(const Bitmap& bmp = Bitmap()) * * @brief Default Constructor. * * Constructs a new Image with a default alpha value of 255 (solid) and a default * Bitmap if none is specified. * * @param bmp The bitmap to display. */ Image(const Bitmap& bmp = Bitmap()) : Widget(), alpha(255) { setBitmap(bmp); } /** * @fn virtual void Image::setBitmap(const Bitmap& bmp); * * @brief Sets the bitmap ID for this Image. * * Sets the bitmap ID for this Image. Updates the width and height of this widget to * match that of the bitmap. * * @param bmp The bitmap instance. * * @see Bitmap */ virtual void setBitmap(const Bitmap& bmp); /** * @fn void Image::setAlpha(uint8_t alpha) * * @brief Sets the alpha channel for the image. * * Sets the alpha channel for the image. * * @param alpha The alpha value. 255 = completely solid. */ void setAlpha(uint8_t alpha) { this->alpha = alpha; } /** * @fn virtual void Image::draw(const Rect& invalidatedArea) const; * * @brief Draws the image. * * Draws the image. This class supports partial drawing, so only the area described * by the rectangle will be drawn. * * @param invalidatedArea The rectangle to draw, with coordinates relative to this drawable. */ virtual void draw(const Rect& invalidatedArea) const; /** * @fn BitmapId Image::getBitmap() const * * @brief Gets the BitmapId currently contained by the widget. * * Gets the BitmapId currently contained by the widget. * * @return The current BitmapId of the widget. */ BitmapId getBitmap() const { return bitmap.getId(); } /** * @fn uint8_t Image::getAlpha() const * * @brief Gets the current alpha value. * * Gets the current alpha value. * * @return The current alpha value. */ uint8_t getAlpha() const { return alpha; } /** * @fn virtual Rect Image::getSolidRect() const; * * @brief Gets the largest solid (non-transparent) rectangle. * * Gets the largest solid (non-transparent) rectangle. This value is pre-calculated * by the imageconverter tool. * * @return The largest solid (non-transparent) rectangle. */ virtual Rect getSolidRect() const; /** * @fn virtual uint16_t Image::getType() const * * @brief For GUI testing only. * * For GUI testing only. Returns type of this drawable. * * @return TYPE_IMAGE. */ virtual uint16_t getType() const { return (uint16_t)TYPE_IMAGE; } protected: Bitmap bitmap; ///< The Bitmap to display. uint8_t alpha; ///< The Alpha for this image. bool hasTransparentPixels; ///< true if this object has transparent pixels }; } // namespace touchgfx #endif // IMAGE_HPP
27.371795
96
0.576815
[ "object", "solid" ]
8b187f6bae2a484d87733de7ae01aede9ea8c5b0
26,088
cpp
C++
src/benchmarks/tpch/queries/q9.cpp
t1mm3/weld_tpch
0e70518de7d510a225b934043879a635b57790d3
[ "MIT" ]
4
2020-06-23T07:39:33.000Z
2021-11-16T02:22:11.000Z
src/benchmarks/tpch/queries/q9.cpp
t1mm3/weld_tpch
0e70518de7d510a225b934043879a635b57790d3
[ "MIT" ]
null
null
null
src/benchmarks/tpch/queries/q9.cpp
t1mm3/weld_tpch
0e70518de7d510a225b934043879a635b57790d3
[ "MIT" ]
null
null
null
#include "benchmarks/tpch/Queries.hpp" #include "common/runtime/Concurrency.hpp" #include "common/runtime/Hash.hpp" #include "common/runtime/Types.hpp" #include "hyper/GroupBy.hpp" #include "hyper/ParallelHelper.hpp" #include "tbb/tbb.h" #include "vectorwise/Operations.hpp" #include "vectorwise/Operators.hpp" #include "vectorwise/Primitives.hpp" #include "vectorwise/QueryBuilder.hpp" #include "vectorwise/VectorAllocator.hpp" #include <iostream> using namespace runtime; using namespace std; using vectorwise::primitives::Char_10; using vectorwise::primitives::Char_25; using vectorwise::primitives::hash_t; inline void splitJulianDay(unsigned jd, unsigned& year, unsigned& month, unsigned& day) // Algorithm from the Calendar FAQ { unsigned a = jd + 32044; unsigned b = (4*a+3)/146097; unsigned c = a-((146097*b)/4); unsigned d = (4*c+3)/1461; unsigned e = c-((1461*d)/4); unsigned m = (5*e+2)/153; day = e - ((153*m+2)/5) + 1; month = m + 3 - (12*(m/10)); year = (100*b) + d - 4800 + (m/10); } extern "C" void weld_extract_year(uint32_t* date, uint16_t *result) { static_assert(sizeof(char*) == sizeof(int64_t), "only works with 64-bit pointers"); unsigned year,month,day; splitJulianDay(*date,year,month,day); *result = year; } std::string extractyear(const std::string& var, const std::string& arg, bool native) { std::ostringstream r; if (!native) { r << "let " << var << " = cudf[weld_extract_year,i16](" << arg << ")"; return r.str(); } std::string pre = "extractyear_"; r << "let " << pre << "a = " << arg << " + 32044;"; r << "let " << pre << "b = ((4*" << pre << "a) +3)/146097;"; r << "let " << pre << "c = " << pre << "a - ((146097* " << pre << "b)/4);"; r << "let " << pre << "d = ((4* " << pre << "c) + 3)/1461;"; r << "let " << pre << "e = " << pre << "c-((1461*"<<pre<<"d)/4);"; r << "let " << pre << "m = ((5*" << pre << "e)+2)/153;"; r << "let " << var << " = i16((100*" << pre << "b) + "<<pre<< "d - 4800 + ("<<pre<<"m/10))"; return r.str(); } extern "C" void weld_str_like_green(int64_t* xlen, int64_t *xstr, bool *result) { static_assert(sizeof(char*) == sizeof(int64_t), "only works with 64-bit pointers"); const char* c1 = "green"; *result = memmem((char*)(*xstr), *xlen, c1, 5) != nullptr; } struct vec { int64_t len; char* data; }; extern "C" void weld_str_print(vec* x, vec* result) { for (uint16_t i=0; i<x->len; i++) { printf("%c", x->data[i]); } printf("\n"); } WeldQuery* q9_weld_prepare(Database& db, size_t nrThreads, bool native_extractyear) { std::ostringstream program; auto& cu = db["customer"]; auto& ord = db["orders"]; auto& li = db["lineitem"]; auto& na = db["nation"]; auto& supp = db["supplier"]; auto& part = db["part"]; auto& partsupp = db["partsupp"]; const auto one = types::Numeric<12, 2>::castString("1.00"); program << "|" << "n_nationkey:vec[i32]," << "n_name:vec[i64]," << "s_suppkey:vec[i32]," << "s_nationkey:vec[i32]," << "p_partkey:vec[i32]," << "p_name:vec[{i64,i64}]," << "ps_partkey:vec[i32]," << "ps_suppkey:vec[i32]," << "ps_supplycost:vec[i64]," << "l_orderkey:vec[i32]," << "l_partkey:vec[i32]," << "l_suppkey:vec[i32]," << "l_extendedprice:vec[i64]," << "l_discount:vec[i64]," << "l_quantity:vec[i64]," << "o_orderkey:vec[i32]," << "o_orderdate:vec[i32]" << "|" ; #if 0 program << "let supplier = zip(s_suppkey, s_nationkey);" << "let part = zip(p_partkey, p_name);" << "let partsupp = zip(ps_partkey, ps_suppkey, ps_supplycost);" << "let lineitem = zip(l_orderkey, l_partkey, l_suppkey, l_extendedprice, l_discount, l_quantity);" << "let orders = zip(o_orderkey, o_orderdate);" ; #endif program << "let ht_nation = result(for(" << "zip(n_nationkey, n_name), " << "groupmerger[i32, i64], " << " |b0,i0,e0| merge(b0, { e0.$0, e0.$1 })" << "));" ; // FK join, but Weld only allows full N join program // [s_suppkey, n_name] << "let ht_nationsupp = result(for(" << "zip(s_suppkey, s_nationkey), " << "groupmerger[i32, i64], " << "|b0,i0,e0| " << "let optres = optlookup(ht_nation, e0.$1);" << "if(optres.$0, " << "for(optres.$1, b0, |b1,i1,e1| merge(b1, {e0.$0, e1}))" << ", b0)" << "));" ; // Semi Join doesn't need payload program << "let ht_part = result(for(" << "zip(p_partkey, p_name), " << "groupmerger[i32, i32]," << "|b0,i0,e0|" << "let pred = cudf[weld_str_like_green,bool](e0.$1.$0, e0.$1.$1);" << "if(pred, merge(b0, {e0.$0, 1}), b0)" << "));" ; // program << "tovec(part_filtered)"; // SemiJoin program << "let partpartsupp = filter(" << "zip(ps_partkey, ps_suppkey, ps_supplycost)," << "|e0| keyexists(ht_part, e0.$0)" << ");" ; // program << "partpartsupp"; // FK join // ps_partkey, ps_suppkey, n_name, ps_supplycost program << "let ht_nsps = result(for(" << "partpartsupp, " << "groupmerger[{i32, i32}, {i64, i64}], " << "|b0,i0,e0|" << "let optres = optlookup(ht_nationsupp, e0.$1);" << "if(optres.$0, " << "for(optres.$1, b0, |b1,i1,e1| merge(b1, { {e0.$0, e0.$1}, { e1, e0.$2 }}))" << ", b0)" << "));" ; // program << "tovec(ht_nsps)"; // [l_orderkey | l_extendedprice, l_discount, l_quantity, n_name, ps_supplycost] program << "let ht_lineitem = result(for(" << "zip(l_orderkey, l_partkey, l_suppkey, l_extendedprice, l_discount, l_quantity), " << "groupmerger[i32, {i64,i64,i64,i64,i64}], " << "|b0,i0,e0|" << "let optres = optlookup(ht_nsps, {e0.$1, e0.$2});" << "if(optres.$0, " << "for(optres.$1, b0, |b1,i1,e1| merge(b1, { e0.$0, {e0.$3, e0.$4, e0.$5, e1.$0, e1.$1} }))" << ", b0)" << "));" ; // program << "tovec(ht_lineitem)"; // Only non-key join // o_orderdate, l_extendedprice, l_discount, l_quantity, n_name, ps_supplycost program << "let lineorders = result(for(" << "zip(o_orderkey, o_orderdate), " << "appender[{i32,i64,i64,i64,i64,i64}], " << "|b0,i0,e0|" << "let optres = optlookup(ht_lineitem, e0.$0);" << "if(optres.$0, " << "for(optres.$1, b0, |b1,i1,e1| merge(b1, { e0.$1, e1.$0, e1.$1, e1.$2, e1.$3, e1.$4}))" << ", b0)" << "));" ; // program << "lineorders"; program << "let aggr = result(for(" << "lineorders, " << "dictmerger[{i64, i16}, i64, +], " << "|b0,i0,e0|" << " let eprice = e0.$1;" << " let disc = e0.$2;" << " let quant = e0.$3;" << " let cost = e0.$5;" << " let a = i64(eprice) * (" << one.value << "l - i64(disc));" << " let amount = a - (i64(quant)*i64(cost));" << extractyear("year", "e0.$0", native_extractyear) << ";" // << " let year = cudf[weld_extract_year,i16](e0.$0);" << " let name = e0.$4;" << "merge(b0, {{name, year}, amount})" << "));" ; program << "tovec(aggr)"; auto inputs = std::make_unique<WeldInRelation>(std::vector<std::pair<size_t, void*>> { { na.nrTuples, na["n_nationkey"].data<types::Integer>() }, { na.nrTuples, &na["n_name"].varchar_codes[0] }, { supp.nrTuples, supp["s_suppkey"].data<types::Integer>()}, { supp.nrTuples, supp["s_nationkey"].data<types::Integer>()}, { part.nrTuples, part["p_partkey"].data<types::Integer>()}, { part.nrTuples, &part["p_name"].varchar_data[0] }, { partsupp.nrTuples, partsupp["ps_partkey"].data<types::Integer>() }, { partsupp.nrTuples, partsupp["ps_suppkey"].data<types::Integer>() }, { partsupp.nrTuples, partsupp["ps_supplycost"].data<types::Numeric<12, 2>>() }, { li.nrTuples, li["l_orderkey"].data<types::Integer>() }, { li.nrTuples, li["l_partkey"].data<types::Integer>() }, { li.nrTuples, li["l_suppkey"].data<types::Integer>() }, { li.nrTuples, li["l_extendedprice"].data<types::Numeric<12, 2>>() }, { li.nrTuples, li["l_discount"].data<types::Numeric<12, 2>>() }, { li.nrTuples, li["l_quantity"].data<types::Numeric<12, 2>>() }, { ord.nrTuples, ord["o_orderkey"].data<types::Integer>() }, { ord.nrTuples, ord["o_orderdate"].data<types::Date>() } }); return new WeldQuery(nrThreads, program.str(), std::move(inputs)); } std::unique_ptr<runtime::Query> q9_weld(Database& db, size_t nrThreads, WeldQuery* q) { auto resources = initQuery(nrThreads); auto res_val = q->run(nrThreads); // translate result struct Result { struct Group { int64_t name; int16_t year; int64_t sum; }; Group* groups; size_t num_groups; }; auto wresult = (Result*)weld_value_data(res_val); #ifdef PRINT_RESULTS printf("Q9 Results: num %d\n", (int)wresult->num_groups); auto& na = db["nation"]; const auto names = &na["n_name"].varchar_data[0]; for (size_t i=0; i<wresult->num_groups; i++) { auto& grp = wresult->groups[i]; names[grp.name].print(); printf(" %d %lld\n", (int)grp.year, grp.sum); } #endif leaveQuery(nrThreads); weld_value_free(res_val); return move(resources.query); } /* select nation, o_year, sum(amount) as sum_profit from ( select n_name as nation, extract(year from o_orderdate) as o_year, l_extendedprice * (1 - l_discount) - ps_supplycost * l_quantity as amount from part, supplier, lineitem, partsupp, orders, nation where s_suppkey = l_suppkey and ps_suppkey = l_suppkey and ps_partkey = l_partkey and p_partkey = l_partkey and o_orderkey = l_orderkey and s_nationkey = n_nationkey and p_name like '%green%' ) as profit group by nation, o_year */ std::unique_ptr<runtime::Query> q9_hyper(runtime::Database& db, size_t nrThreads) { // --- aggregates auto resources = initQuery(nrThreads); using hash = runtime::CRC32Hash; // --- constants auto contains = types::Varchar<55>::castString("green"); auto& na = db["nation"]; auto& supp = db["supplier"]; // --- build ht for nation auto n_nationkey = na["n_nationkey"].data<types::Integer>(); auto n_name = na["n_name"].data<types::Char<25>>(); Hashmapx<types::Integer, types::Char<25>, hash> ht1; tbb::enumerable_thread_specific<runtime::Stack<decltype(ht1)::Entry>> entries1; PARALLEL_SCAN(na.nrTuples, entries1, { auto& key = n_nationkey[i]; entries.emplace_back(ht1.hash(key), key, n_name[i]); }); ht1.setSize(na.nrTuples); parallel_insert(entries1, ht1); // --- ht for bushy join Hashmapx<types::Integer, types::Char<25>, hash> ht2; tbb::enumerable_thread_specific<runtime::Stack<decltype(ht2)::Entry>> entries2; auto s_suppkey = supp["s_suppkey"].data<types::Integer>(); auto s_nationkey = supp["s_nationkey"].data<types::Integer>(); // do join nation-supplier and put result into bushy ht auto found2 = PARALLEL_SELECT(supp.nrTuples, entries2, { auto& suppkey = s_suppkey[i]; auto& nationkey = s_nationkey[i]; auto name = ht1.findOne(nationkey); if (name) { entries.emplace_back(ht2.hash(suppkey), suppkey, *name); found++; } }); ht2.setSize(found2); parallel_insert(entries2, ht2); // --- ht for join part-partsupp Hashset<types::Integer, hash> ht3; tbb::enumerable_thread_specific<runtime::Stack<decltype(ht3)::Entry>> entries3; auto& part = db["part"]; auto p_partkey = part["p_partkey"].data<types::Integer>(); auto p_name = part["p_name"].data<types::Varchar<55>>(); // do selection on part and put selected elements into ht auto found3 = PARALLEL_SELECT(part.nrTuples, entries3, { auto& pk = p_partkey[i]; auto& pn = p_name[i]; if (memmem(pn.value, pn.len, contains.value, contains.len) != nullptr){ entries.emplace_back(ht3.hash(pk), pk); found++; } }); ht3.setSize(found3); parallel_insert(entries3, ht3); Hashmapx<tuple<types::Integer, types::Integer>, tuple<types::Char<25>, types::Numeric<12, 2>>, hash> ht4; tbb::enumerable_thread_specific<runtime::Stack<decltype(ht4)::Entry>> entries4; auto& partsupp = db["partsupp"]; auto ps_partkey = partsupp["ps_partkey"].data<types::Integer>(); auto ps_suppkey = partsupp["ps_suppkey"].data<types::Integer>(); auto ps_supplycost = partsupp["ps_supplycost"].data<types::Numeric<12, 2>>(); auto found4 = PARALLEL_SELECT(partsupp.nrTuples, entries4, { if (ht3.contains(ps_partkey[i])) { auto nation = ht2.findOne(ps_suppkey[i]); if (nation) { auto key = make_tuple(ps_partkey[i], ps_suppkey[i]); auto value = make_tuple(*nation, ps_supplycost[i]); entries.emplace_back(ht4.hash(key), key, value); found++; } } }); ht4.setSize(found4); parallel_insert(entries4, ht4); Hashmapx< types::Integer, tuple<types::Numeric<12, 2>, types::Numeric<12, 2>, types::Numeric<12, 2>, types::Numeric<12, 2>, types::Char<25>>, hash> ht5; tbb::enumerable_thread_specific<runtime::Stack<decltype(ht5)::Entry>> entries5; auto& li = db["lineitem"]; auto l_orderkey = li["l_orderkey"].data<types::Integer>(); auto l_partkey = li["l_partkey"].data<types::Integer>(); auto l_suppkey = li["l_suppkey"].data<types::Integer>(); auto l_extendedprice = li["l_extendedprice"].data<types::Numeric<12, 2>>(); auto l_discount = li["l_discount"].data<types::Numeric<12, 2>>(); auto l_quantity = li["l_quantity"].data<types::Numeric<12, 2>>(); auto found5 = PARALLEL_SELECT(li.nrTuples, entries5, { auto part = ht4.findOne(make_tuple(l_partkey[i], l_suppkey[i])); if (part) { auto& key = l_orderkey[i]; auto value = make_tuple(l_extendedprice[i], l_discount[i], l_quantity[i], get<1>(*part), get<0>(*part)); entries.emplace_back(ht5.hash(key), key, value); found++; } }); ht5.setSize(found5); parallel_insert(entries5, ht5); auto& ord = db["orders"]; auto o_orderkey = ord["o_orderkey"].template data<types::Integer>(); auto o_orderdate = ord["o_orderdate"].template data<types::Date>(); const auto one = types::Numeric<12, 2>::castString("1.00"); const auto zero = types::Numeric<12, 4>::castString("0.00"); auto groupOp = make_GroupBy<tuple<types::Char<25>, types::Integer>, types::Numeric<12, 4>, hash>( [](auto& acc, auto&& value) { acc += value; }, zero, nrThreads); // preaggregation tbb::parallel_for( tbb::blocked_range<size_t>(0, ord.nrTuples, morselSize), [&](const tbb::blocked_range<size_t>& r) { auto groupLocals = groupOp.preAggLocals(); for (size_t i = r.begin(), end = r.end(); i != end; ++i) { auto h = ht5.hash(o_orderkey[i]); auto entry = ht5.findOneEntry(o_orderkey[i], h); for (; entry; entry = reinterpret_cast<decltype(entry)>(entry->h.next)) { if (entry->h.hash != h || entry->k != o_orderkey[i]) continue; auto& v = entry->v; auto year = extractYear(o_orderdate[i]); auto& extp = get<0>(v); auto& disc = get<1>(v); auto& quant = get<2>(v); auto& supplcost = get<3>(v); auto& name = get<4>(v); // l_extendedprice * (1 - l_discount) - ps_supplycost * l_quantity as auto amount = (extp * (one - disc)) - (supplcost * quant); groupLocals.consume(make_tuple(name, year), amount); } } }); // --- output auto& result = resources.query->result; auto nationAttr = result->addAttribute("nation", sizeof(types::Char<25>)); auto yearAttr = result->addAttribute("o_year", sizeof(types::Integer)); auto profitAttr = result->addAttribute("sum_profit", sizeof(types::Numeric<12, 4>)); groupOp.forallGroups([&](auto& groups) { // write aggregates to result auto block = result->createBlock(groups.size()); auto nation = reinterpret_cast<types::Char<25>*>(block.data(nationAttr)); auto year = reinterpret_cast<types::Integer*>(block.data(yearAttr)); auto profit = reinterpret_cast<types::Numeric<12, 4>*>(block.data(profitAttr)); for (auto block : groups) for (auto& group : block) { *nation++ = get<0>(group.k); *year++ = get<1>(group.k); *profit++ = group.v; } block.addedElements(groups.size()); }); leaveQuery(nrThreads); return move(resources.query); } std::unique_ptr<Q9Builder::Q9> Q9Builder::getQuery(){ using namespace vectorwise; auto result = Result(); previous = result.resultWriter.shared.result->participate(); auto r = make_unique<Q9>(); auto nation = Scan("nation"); auto supplier = Scan("supplier"); //join nation supplier HashJoin(Buffer(nation_supplier, sizeof(pos_t)), conf.joinAll()) .addBuildKey(Column(nation, "n_nationkey"), // conf.hash_int32_t_col(), // primitives::scatter_int32_t_col) .addBuildValue(Column(nation, "n_name"), // primitives::scatter_Char_25_col, Buffer(n_name, sizeof(Char_25)), primitives::gather_col_Char_25_col) .addProbeKey(Column(supplier, "s_nationkey"), // conf.hash_int32_t_col(), // primitives::keys_equal_int32_t_col); auto part = Scan("part"); Select(Expression().addOp(primitives::sel_contains_Varchar_55_col_Varchar_55_val, Buffer(sel_part, sizeof(pos_t)), Column(part, "p_name"), // Value(&r->contains))); auto partsupp = Scan("partsupp"); HashJoin(Buffer(part_partsupp, sizeof(pos_t)), conf.joinAll()) .addBuildKey(Column(part, "p_partkey"), // Buffer(sel_part), // conf.hash_sel_int32_t_col(), primitives::scatter_sel_int32_t_col) .addProbeKey(Column(partsupp, "ps_partkey"), // conf.hash_int32_t_col(), // primitives::keys_equal_int32_t_col); HashJoin(Buffer(pspp, sizeof(pos_t)), conf.joinAll()) .addBuildKey(Column(supplier, "s_suppkey"), // Buffer(nation_supplier), // conf.hash_sel_int32_t_col(), primitives::scatter_sel_int32_t_col) .addBuildValue(Buffer(n_name), // primitives::scatter_Char_25_col, Buffer(n_name), primitives::gather_col_Char_25_col) .setProbeSelVector(Buffer(part_partsupp), conf.joinSel()) .addProbeKey(Column(partsupp, "ps_suppkey"), // Buffer(part_partsupp), // conf.hash_sel_int32_t_col(), primitives::keys_equal_int32_t_col); auto lineitem = Scan("lineitem"); HashJoin(Buffer(xlineitem, sizeof(pos_t)), conf.joinAll()) .addBuildKey(Column(partsupp, "ps_partkey"), // Buffer(pspp), // conf.hash_sel_int32_t_col(), primitives::scatter_sel_int32_t_col) .addBuildKey(Column(partsupp, "ps_suppkey"), // Buffer(pspp), // conf.rehash_sel_int32_t_col(), primitives::scatter_sel_int32_t_col) .addBuildValue(Buffer(n_name), // primitives::scatter_Char_25_col, // Buffer(n_name), // primitives::gather_col_Char_25_col) .addBuildValue(Column(partsupp, "ps_supplycost"), // Buffer(pspp), // primitives::scatter_sel_int64_t_col, Buffer(ps_supplycost, sizeof(int64_t)), // primitives::gather_col_int64_t_col) .addProbeKey(Column(lineitem, "l_partkey"), // conf.hash_int32_t_col(), primitives::keys_equal_int32_t_col) .addProbeKey(Column(lineitem, "l_suppkey"), // conf.rehash_int32_t_col(), primitives::keys_equal_int32_t_col); auto orders = Scan("orders"); HashJoin(Buffer(ordersx, sizeof(pos_t)), conf.joinAll()) .addBuildKey(Column(lineitem, "l_orderkey"), // Buffer(xlineitem), // conf.hash_sel_int32_t_col(), primitives::scatter_sel_int32_t_col) .addProbeKey(Column(orders, "o_orderkey"), // conf.hash_int32_t_col(), // primitives::keys_equal_int32_t_col) .addBuildValue(Column(lineitem, "l_extendedprice"), // Buffer(xlineitem), // primitives::scatter_sel_int64_t_col, Buffer(l_extendedprice, sizeof(int64_t)), primitives::gather_col_int64_t_col) .addBuildValue(Column(lineitem, "l_discount"), // Buffer(xlineitem), // primitives::scatter_sel_int64_t_col, Buffer(l_discount, sizeof(int64_t)), primitives::gather_col_int64_t_col) .addBuildValue(Column(lineitem, "l_quantity"), // Buffer(xlineitem), // primitives::scatter_sel_int64_t_col, Buffer(l_quantity, sizeof(int64_t)), primitives::gather_col_int64_t_col) .addBuildValue(Buffer(ps_supplycost), // primitives::scatter_int64_t_col, // Buffer(ps_supplycost), // primitives::gather_col_int64_t_col) .addBuildValue(Buffer(n_name), // primitives::scatter_Char_25_col, // Buffer(n_name), // primitives::gather_col_Char_25_col); Project() // l_extendedprice * (1 - l_discount) - ps_supplycost * l_quantity as // amount .addExpression( Expression() .addOp(primitives::proj_minus_int64_t_val_int64_t_col, Buffer(result_proj_minus, sizeof(int64_t)), Value(&r->one), Buffer(l_discount)) .addOp(primitives::proj_multiplies_int64_t_col_int64_t_col, Buffer(disc_price, sizeof(int64_t)), Buffer(l_extendedprice), Buffer(result_proj_minus, sizeof(int64_t))) .addOp(primitives::proj_multiplies_int64_t_col_int64_t_col, Buffer(total_cost, sizeof(int64_t)), Buffer(ps_supplycost), // Buffer(l_quantity)) .addOp(primitives::proj_minus_int64_t_col_int64_t_col, Buffer(amount, sizeof(int64_t)), Buffer(disc_price, sizeof(int64_t)), // Buffer(total_cost, sizeof(int64_t)))) .addExpression( Expression().addOp(primitives::apply_extract_year_sel_col, Buffer(o_year, sizeof(types::Integer)), // Buffer(ordersx), // Column(orders, "o_orderdate"))); // HashGroup() .addKey(Buffer(n_name), // primitives::hash_Char_25_col, primitives::keys_not_equal_Char_25_col, primitives::partition_by_key_Char_25_col, primitives::scatter_sel_Char_25_col, primitives::keys_not_equal_row_Char_25_col, primitives::partition_by_key_row_Char_25_col, primitives::scatter_sel_row_Char_25_col, primitives::gather_val_Char_25_col, Buffer(n_name)) .addKey(Buffer(o_year), // conf.rehash_int32_t_col(), // primitives::keys_not_equal_int32_t_col, primitives::partition_by_key_int32_t_col, primitives::scatter_sel_int32_t_col, primitives::keys_not_equal_row_int32_t_col, primitives::partition_by_key_row_int32_t_col, primitives::scatter_sel_row_int32_t_col, primitives::gather_val_int32_t_col, Buffer(o_year)) .addValue(Buffer(amount), // primitives::aggr_init_plus_int64_t_col, primitives::aggr_plus_int64_t_col, primitives::aggr_row_plus_int64_t_col, primitives::gather_val_int64_t_col, Buffer(sum_profit, sizeof(int64_t))); result.addValue("nation", Buffer(n_name)) .addValue("o_year", Buffer(o_year)) .addValue("sum_profit", Buffer(sum_profit)) .finalize(); r->rootOp = popOperator(); return r; } std::unique_ptr<runtime::Query> q9_vectorwise(runtime::Database& db, size_t nrThreads, size_t vectorSize) { using namespace vectorwise; WorkerGroup workers(nrThreads); vectorwise::SharedStateManager shared; std::unique_ptr<runtime::Query> result; workers.run([&]() { Q9Builder builder(db, shared, vectorSize); auto query = builder.getQuery(); /* auto found = */ query->rootOp->next(); auto leader = barrier(); if (leader) result = move( dynamic_cast<ResultWriter*>(query->rootOp.get())->shared.result); }); return result; }
36.033149
103
0.569726
[ "vector" ]
8b1adee883ca653a623b0fef1c0fb8448bb8a82e
4,747
cc
C++
example/computer/computer.cc
madeso/zsh
7884bd41f24038d05669e32b47f2b2aa595b0c55
[ "WTFPL" ]
null
null
null
example/computer/computer.cc
madeso/zsh
7884bd41f24038d05669e32b47f2b2aa595b0c55
[ "WTFPL" ]
null
null
null
example/computer/computer.cc
madeso/zsh
7884bd41f24038d05669e32b47f2b2aa595b0c55
[ "WTFPL" ]
null
null
null
#include "computer/computer.h" #include <iostream> #include <chrono> #include <sstream> namespace computer { std::vector<std::string> split(const std::string& s, char delim) { std::vector<std::string> elems; std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { elems.emplace_back(item); } return elems; } zsh::i64 get_unix_timestamp() { const auto time = std::chrono::system_clock::now().time_since_epoch(); return std::chrono::duration_cast<std::chrono::seconds>(time).count(); } Console::Console() : cwd("~") { } void Console::print_prompt() const { std::cout << cwd << "> "; } void Console::print_error(const std::string& msg) const { std::cerr << "ERROR: " << msg << "\n" << std::endl; } void Console::jump_to(const std::string& path) { cwd = path; } void Console::cd_to_relative(const std::string& path) { const auto parts = split(path, '/'); for (const auto& part : parts) { if (part == "..") { if (cwd == "~") { print_error("Cannot go up from root folder"); return; } cwd = cwd.substr(0, cwd.rfind('/')); } else if (part == ".") { continue; } else { cwd += "/" + part; } } } void Console::cd_to(const std::string& path) { if (path.find('~') == 0) { jump_to(path); } else { cd_to_relative(path); } } struct Computer; void Computer::cd_to(const std::string& path) { console.cd_to(path); zsh.add(console.cwd, get_unix_timestamp()); } void Computer::add(const std::string& name, const CommandHandler& command) { commands[name] = command; } void handle_exit(Computer* computer, const std::vector<std::string>&) { computer->on = false; } void handle_zsh_list(Computer* computer, const std::vector<std::string>& args) { const auto folders = computer->zsh.get_all(args, get_unix_timestamp(), computer->zsh_algorithm); for (const auto& folder : folders) { std::cout << folder.path << ": " << folder.rank << "\n"; } std::cout << std::endl; } void handle_dump(Computer* computer, const std::vector<std::string>& args) { if (args.empty() == false) { computer->console.print_error("dump takes 0 arguments"); } else { for(const auto& e: computer->zsh.entries) { std::cout << e.first << ": " << e.second.time << " / " << e.second.rank << "\n"; } std::cout << std::endl; } } void handle_help(Computer* computer, const std::vector<std::string>& args) { if (args.empty() == false) { computer->console.print_error("help takes 0 arguments"); } std::cout << "Available commands:\n"; for (const auto& command : computer->commands) { std::cout << " " << command.first << "\n"; } std::cout << std::endl; } std::vector<std::string> drop_first(const std::vector<std::string>& args) { if (args.empty()) { return {}; } return std::vector(std::next(args.begin()), args.end()); } void add_default_commands(Computer* computer) { computer->add("exit", handle_exit); computer->add("all", handle_zsh_list); computer->add("dump", handle_dump); computer->add("help", handle_help); } int run(Computer* computer) { while(computer->on) { std::string line; computer->console.print_prompt(); if(!std::getline(std::cin, line)) break; const auto command = split(line, ' '); if(command.empty()) continue; const auto& command_name = command[0]; const auto command_args = drop_first(command); if (const auto handler = computer->commands.find(command_name); handler != computer->commands.end()) { handler->second(computer, command_args); } else { computer->console.print_error("Unknown command: " + command_name); } } return 0; } }
24.723958
112
0.48873
[ "vector" ]
8b1d3f5613de34142499fbebff9c282b6342323c
8,451
cpp
C++
Crowny/Source/Crowny/Assets/AssetManager.cpp
bojosos/Crowny
5aef056d2c95e04870d2372a87257ad9dccf168a
[ "MIT" ]
2
2021-05-13T17:57:04.000Z
2021-10-04T07:07:01.000Z
Crowny/Source/Crowny/Assets/AssetManager.cpp
bojosos/Crowny
5aef056d2c95e04870d2372a87257ad9dccf168a
[ "MIT" ]
null
null
null
Crowny/Source/Crowny/Assets/AssetManager.cpp
bojosos/Crowny
5aef056d2c95e04870d2372a87257ad9dccf168a
[ "MIT" ]
null
null
null
#include "cwpch.h" #include "Crowny/Assets/AssetManager.h" #include "Crowny/Common/FileSystem.h" #include "Crowny/Assets/CerealDataStreamArchive.h" #include "Crowny/Audio/AudioSource.h" #include "Crowny/RenderAPI/Shader.h" #include "Crowny/RenderAPI/Texture.h" CEREAL_REGISTER_TYPE(Crowny::Shader) CEREAL_REGISTER_TYPE(Crowny::AudioClip) CEREAL_REGISTER_TYPE(Crowny::Texture) CEREAL_REGISTER_POLYMORPHIC_RELATION(Crowny::Asset, Crowny::Shader) CEREAL_REGISTER_POLYMORPHIC_RELATION(Crowny::Asset, Crowny::AudioClip) CEREAL_REGISTER_POLYMORPHIC_RELATION(Crowny::Asset, Crowny::Texture) namespace Crowny { void Save(BinaryDataStreamOutputArchive& archive, const Asset& asset) { archive(asset.m_KeepData); } void Load(BinaryDataStreamInputArchive& archive, Asset& asset) { archive(asset.m_KeepData); } void Load(BinaryDataStreamInputArchive& archive, AudioClip& clip) { archive(cereal::base_class<Asset>(&clip)); // Save asset base class AudioClipDesc& desc = clip.m_Desc; // Save clip desc archive(desc.ReadMode, desc.Format, desc.Frequency, desc.BitDepth, desc.NumChannels, desc.Is3D); archive(clip.m_Length, clip.m_NumSamples); CW_ENGINE_INFO("Loaded: {0}", clip.m_NumSamples); archive(clip.m_StreamSize); // Load the size of audio data clip.m_StreamData = archive.GetStream()->Clone(); clip.m_StreamOffset = (uint32_t)archive.GetStream()->Tell(); clip.Init(); } void Save(BinaryDataStreamOutputArchive& archive, const AudioClip& clip) { archive(cereal::base_class<Asset>(&clip)); // Save asset base class const AudioClipDesc& desc = clip.m_Desc; // Save clip desc archive(desc.ReadMode, desc.Format, desc.Frequency, desc.BitDepth, desc.NumChannels, desc.Is3D); archive(clip.m_Length, clip.m_NumSamples); uint32_t size = 0; // Save the samples auto sourceStream = clip.GetSourceStream(size); Vector<uint8_t> samples(size); sourceStream->Read(samples.data(), size); // Save the stream data archive(size); archive(cereal::binary_data(samples.data(), size)); } void Load(BinaryDataStreamInputArchive& archive, Texture& texture) { archive(cereal::base_class<Asset>(&texture)); TextureParameters& params = texture.m_Params; archive(params.Width, params.Height, params.Depth, params.MipLevels, params.Samples, params.Type, params.Shape, params.Format); for (uint32_t mip = 0; mip < params.MipLevels; mip++) { for (uint32_t face = 0; face < params.Faces; face++) { uint32_t size = 0; archive(size); Ref<PixelData> pixelData = CreateRef<PixelData>(texture.GetWidth(), texture.GetHeight(), texture.GetDepth(), texture.GetFormat()); archive.GetStream()->Read(pixelData->GetData(), size); texture.WriteData(*pixelData, mip, face); } } } void Save(BinaryDataStreamOutputArchive& archive, Texture& texture) { archive(cereal::base_class<Asset>(&texture)); const TextureParameters& params = texture.GetProperties(); archive(params.Width, params.Height, params.Depth, params.MipLevels, params.Samples, params.Type, params.Shape, params.Format); texture.Init(); for (uint32_t mip = 0; mip < params.MipLevels + 1; mip++) // Save all texture data { for (uint32_t face = 0; face < params.Faces; face++) { Ref<PixelData> pixelData = texture.AllocatePixelData(face, mip); texture.ReadData(*pixelData, face, mip); archive(cereal::binary_data((uint8_t*)pixelData->GetData(), pixelData->GetSize())); // TODO: Save more pixel data } } } template <class Archive> void Serialize(Archive& archive, UniformDesc& desc) { archive(desc.Uniforms, desc.Samplers, desc.Textures, desc.LoadStoreTextures); } void Save(BinaryDataStreamOutputArchive& archive, const ShaderStage& shaderStage) { archive(shaderStage.m_ShaderData->Data); archive(shaderStage.m_ShaderData->EntryPoint); archive(shaderStage.m_ShaderData->Type); archive(shaderStage.m_ShaderData->Description); } void Load(BinaryDataStreamInputArchive& archive, ShaderStage& shaderStage) { archive(shaderStage.m_ShaderData->Data); archive(shaderStage.m_ShaderData->EntryPoint); archive(shaderStage.m_ShaderData->Type); archive(shaderStage.m_ShaderData->Description); // shaderStage.Init(); } void Save(BinaryDataStreamOutputArchive& archive, const Shader& shader) { for (uint32_t i = 0; i < SHADER_COUNT; i++) { if (shader.m_ShaderStages[i]) archive(shader.m_ShaderStages[i]); } } void Load(BinaryDataStreamInputArchive& archive, Shader& shader) { for (uint32_t i = 0; i < SHADER_COUNT; i++) archive(shader.m_ShaderStages[i]); } Ref<Asset> AssetManager::Load(const Path& filepath, bool keepSourceData) { if (!FileSystem::FileExists(filepath)) { CW_ENGINE_WARN("Resource {0} does not exist.", filepath); return nullptr; } UUID uuid; bool exists = GetUUIDFromFilepath(filepath, uuid); if (!exists) uuid = UuidGenerator::Generate(); return Load(uuid, filepath, keepSourceData); } Ref<Asset> AssetManager::LoadFromUUID(const UUID& uuid, bool keepSourceData) { Path filepath; GetFilepathFromUUID(uuid, filepath); return Load(uuid, filepath, keepSourceData); } Ref<Asset> AssetManager::Load(const UUID& uuid, const Path& filepath, bool keepSourceData) { /* auto findIter = m_LoadedAssets.find(uuid); if (findIter != m_LoadedAssets.end()) return findIter->second; AssetHandle assetHandle; auto findIter = m_Handles.find(uuid); if (findIter != m_Handles.end()) assetHandle = findIter->second; else { assetHandle = AssetHandle(uuid); m_Handles[uuid] = assetHandle.GetWeakHandle(); } Ref<DataStream> stream = FileSystem::OpenFile(filepath); BinaryDataStreamInputArchive archive(stream); Ref<Asset> asset; archive(asset); assetHandle.SetAssetHandle(asset); m_LoadedAssets[uuid] = asset; return assetHandle;*/ Ref<DataStream> stream = FileSystem::OpenFile(filepath); BinaryDataStreamInputArchive archive(stream); Ref<Asset> asset; archive(asset); return asset; } void AssetManager::Save(const Ref<Asset>& resource, const Path& filepath) { if (!fs::is_directory(filepath.parent_path())) fs::create_directories(filepath.parent_path()); Ref<DataStream> stream = FileSystem::CreateAndOpenFile(filepath); BinaryDataStreamOutputArchive archive(stream); archive(resource); stream->Close(); } void AssetManager::RegisterAssetManifest(const Ref<AssetManifest>& manifest) { auto iterFind = std::find(m_Manifests.begin(), m_Manifests.end(), manifest); if (iterFind == m_Manifests.end()) m_Manifests.push_back(manifest); else *iterFind = manifest; } void AssetManager::UnregisterAssetManifest(const Ref<AssetManifest>& manifest) { auto iterFind = std::find(m_Manifests.begin(), m_Manifests.end(), manifest); if (iterFind != m_Manifests.end()) m_Manifests.erase(iterFind); } void AssetManager::GetFilepathFromUUID(const UUID& uuid, Path& outFilepath) { for (auto& manifest : m_Manifests) { if (manifest->UuidToFilepath(uuid, outFilepath)) return; } } bool AssetManager::GetUUIDFromFilepath(const Path& filepath, UUID& outUUID) { // broken for (auto& manifest : m_Manifests) { if (manifest->FilepathToUuid(filepath, outUUID)) return true; } return false; } } // namespace Crowny
36.743478
119
0.630931
[ "shape", "vector" ]
8b1f0e7c3f55304e8f119117020cde41191fc3b7
1,516
cpp
C++
ruby/input/xlib.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
10
2019-12-19T01:19:41.000Z
2021-02-18T16:30:29.000Z
ruby/input/xlib.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
null
null
null
ruby/input/xlib.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
1
2021-03-22T16:15:30.000Z
2021-03-22T16:15:30.000Z
#include <sys/ipc.h> #include <sys/shm.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xatom.h> #include "keyboard/xlib.cpp" #include "mouse/xlib.cpp" struct InputXlib : InputDriver { InputXlib& self = *this; InputXlib(Input& super) : InputDriver(super), keyboard(super), mouse(super) {} ~InputXlib() { terminate(); } auto create() -> bool override { return initialize(); } auto driver() -> string override { return "Xlib"; } auto ready() -> bool override { return isReady; } auto hasContext() -> bool override { return true; } auto setContext(uintptr context) -> bool override { return initialize(); } auto acquired() -> bool override { return mouse.acquired(); } auto acquire() -> bool override { return mouse.acquire(); } auto release() -> bool override { return mouse.release(); } auto poll() -> vector<shared_pointer<HID::Device>> override { vector<shared_pointer<HID::Device>> devices; keyboard.poll(devices); mouse.poll(devices); return devices; } auto rumble(uint64_t id, bool enable) -> bool override { return false; } private: auto initialize() -> bool { terminate(); if(!self.context) return false; if(!keyboard.initialize()) return false; if(!mouse.initialize(self.context)) return false; return isReady = true; } auto terminate() -> void { isReady = false; keyboard.terminate(); mouse.terminate(); } bool isReady = false; InputKeyboardXlib keyboard; InputMouseXlib mouse; };
25.266667
80
0.662929
[ "vector" ]
8b1f19e1b4abc104c6e52257e6699e9ff7cd50ad
2,722
c++
C++
test/segmentation.c++
libogonek/ogonek
46b7edbf6b7ff89892f5ba25494749b442e771b3
[ "CC0-1.0" ]
25
2016-10-21T12:37:23.000Z
2021-02-22T05:46:46.000Z
test/segmentation.c++
libogonek/ogonek
46b7edbf6b7ff89892f5ba25494749b442e771b3
[ "CC0-1.0" ]
null
null
null
test/segmentation.c++
libogonek/ogonek
46b7edbf6b7ff89892f5ba25494749b442e771b3
[ "CC0-1.0" ]
4
2016-09-05T10:23:18.000Z
2020-07-09T19:37:37.000Z
// Ogonek // // Written in 2012-2013 by Martinho Fernandes <martinho.fernandes@gmail.com> // // To the extent possible under law, the author(s) have dedicated all copyright and related // and neighboring rights to this software to the public domain worldwide. This software is // distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with this software. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. // Tests for <ogonek/segmentation.h++> #include <ogonek/segmentation.h++> #include <ogonek/types.h++> #include "segmentation.g.h++" #include "utils.h++" #include <catch.hpp> #include <iterator> #include <string> #include <vector> namespace { template <typename Fun> void test_segmentation(test::break_test const& test, Fun fun) { auto items = fun(test.input); auto it = items.begin(); auto last_break = 0; for(auto&& this_break : test.breaks) { CHECK((it->begin() - test.input.begin()) == last_break); CHECK((it->end() - test.input.begin()) == this_break); last_break = this_break; ++it; } CHECK(items.end() == it); } } // namespace namespace { struct { template <typename ForwardRange> auto operator()(ForwardRange const& range) const -> decltype(ogonek::graphemes(range)) { return ogonek::graphemes(range); } } break_graphemes; } // namespace TEST_CASE("graphemes", "Extended grapheme ranges") { SECTION("official", "Official grapheme tests") { for(auto&& test : test::grapheme_test_data) { test_segmentation(test, break_graphemes); } } } namespace { struct { template <typename ForwardRange> auto operator()(ForwardRange const& range) const -> decltype(ogonek::words(range)) { return ogonek::words(range); } } break_words; } // namespace TEST_CASE("words", "Word ranges") { SECTION("official", "Official word tests") { for(auto&& test : test::word_test_data) { test_segmentation(test, break_words); } } SECTION("issue-0019", "test for issue #19") { using text = ogonek::text<ogonek::utf8>; std::vector<text> words; for(auto word : ogonek::words(test::ustring(U"ABC DEF GREG"))) { words.emplace_back(word); } REQUIRE(words[0].storage() == u8"ABC"); REQUIRE(words[1].storage() == u8" "); REQUIRE(words[2].storage() == u8"DEF"); REQUIRE(words[3].storage() == u8" "); REQUIRE(words[4].storage() == u8"GREG"); } } namespace { } // namespace namespace { } // namespace
29.268817
96
0.613519
[ "vector" ]
8b20a8b2911f82c05d54b8bbe14257bfa2333de5
15,764
cpp
C++
src/base/command/If.cpp
ddj116/gmat
39673be967d856f14616462fb6473b27b21b149f
[ "NASA-1.3" ]
1
2020-05-16T16:58:21.000Z
2020-05-16T16:58:21.000Z
src/base/command/If.cpp
ddj116/gmat
39673be967d856f14616462fb6473b27b21b149f
[ "NASA-1.3" ]
null
null
null
src/base/command/If.cpp
ddj116/gmat
39673be967d856f14616462fb6473b27b21b149f
[ "NASA-1.3" ]
null
null
null
//$Id: If.cpp 11387 2013-02-25 16:46:47Z tgrubb $ //------------------------------------------------------------------------------ // If //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool. // // Copyright (c) 2002-2011 United States Government as represented by the // Administrator of The National Aeronautics and Space Administration. // All Other Rights Reserved. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract // number NNG04CC06P // // Author: Joey Gurganus/GSFC // Created: 2004/01/30 // /** * Definition for the If command class */ //------------------------------------------------------------------------------ #include <sstream> #include "gmatdefs.hpp" #include "If.hpp" #include "Parameter.hpp" #include "MessageInterface.hpp" //#define DEBUG_IF_EXEC //#define DEBUG_IF_APPEND //------------------------------------------------------------------------------ // static data //------------------------------------------------------------------------------ const std::string If::PARAMETER_TEXT[IfParamCount - ConditionalBranchParamCount] = { "NestLevel", }; const Gmat::ParameterType If::PARAMETER_TYPE[IfParamCount - ConditionalBranchParamCount] = { Gmat::INTEGER_TYPE, }; //------------------------------------------------------------------------------ // If() //------------------------------------------------------------------------------ /** * Creates a If command. (default constructor) */ //------------------------------------------------------------------------------ If::If() : ConditionalBranch ("If"), nestLevel (0) { } //------------------------------------------------------------------------------ // If(const If &ic) //------------------------------------------------------------------------------ /** * Constructor that replicates an If command. (Copy constructor) */ //------------------------------------------------------------------------------ If::If(const If &ic) : ConditionalBranch (ic), nestLevel (0) { } //------------------------------------------------------------------------------ // If& operator=(const If &ic) //------------------------------------------------------------------------------ /** * Assignment operator for the If command. * * @return A reference to this instance. */ //------------------------------------------------------------------------------ If& If::operator=(const If &ic) { if (this == &ic) return *this; ConditionalBranch::operator=(ic); nestLevel = ic.nestLevel; return *this; } //------------------------------------------------------------------------------ // ~If() //------------------------------------------------------------------------------ /** * Destroys the If command. (destructor) */ //------------------------------------------------------------------------------ If::~If() { } //------------------------------------------------------------------------------ // bool Append(GmatCommand *cmd) //------------------------------------------------------------------------------ /** * Adds a command to the IF statement. * * This method calls the BranchCommand base class method that adds a command * to the command sequence that branches off of the main mission sequence. This * extension was needed so that the EndIf command can be set to point back * to the head of the IF statement. * * @return true if the Command is appended, false if an error occurs. */ //------------------------------------------------------------------------------ bool If::Append(GmatCommand *cmd) { if (!ConditionalBranch::Append(cmd)) return false; #ifdef DEBUG_IF_APPEND MessageInterface::ShowMessage("If::Append .... type being appended is %s\n", (cmd->GetTypeName()).c_str()); #endif // Check for the end of "If" branch, point that end back to this command if (cmd->GetTypeName() == "EndIf" || cmd->GetTypeName() == "Else" || cmd->GetTypeName() == "ElseIf") { #ifdef DEBUG_IF_APPEND MessageInterface::ShowMessage("If::Append (if) .... nestLevel = %d\n", nestLevel); #endif if ((nestLevel== 0) && (branchToFill != -1)) { cmd->Append(this); // IF statement is complete; -1 points us back to the main sequence. if (cmd->GetTypeName() == "EndIf") branchToFill = -1; else // "Else" or "ElseIf" starts another branch ++branchToFill; } else { // only decrease the nextLevel if we've reached the actual end of the // If command if (cmd->GetTypeName() == "EndIf") --nestLevel; } } if (cmd->GetTypeName() == "If") { ++nestLevel; } return true; } //------------------------------------------------------------------------------ // bool Execute() //------------------------------------------------------------------------------ /** * Execute the proper branch for this IF statement. * * @return true if the Command runs to completion, false if an error * occurs. */ //------------------------------------------------------------------------------ bool If::Execute() { bool retval = true; if (branchExecuting) { #ifdef DEBUG_IF_EXEC MessageInterface::ShowMessage ("In If::Execute - Branch Executing -------------\n"); #endif retval = ExecuteBranch(branchToExecute); #ifdef DEBUG_IF_EXEC MessageInterface::ShowMessage ("In If:: retval returned from ExecuteBranch = %s\n", (retval? "true" : "false")); MessageInterface::ShowMessage (" branchExecuting=%d\n", branchExecuting); #endif if (!branchExecuting) { commandComplete = true; commandExecuting = false; } } else { #ifdef DEBUG_IF_EXEC MessageInterface::ShowMessage ("In If::Execute - Branch NOT Executing -------------\n"); #endif if (!commandExecuting) ConditionalBranch::Execute(); if (EvaluateAllConditions()) { #ifdef DEBUG_IF_EXEC MessageInterface::ShowMessage ("In If::Execute all conditions are true - executing first branch\n"); #endif branchToExecute = 0; branchExecuting = true; commandComplete = false; commandExecuting = true; } else if ((Integer)branch.size() > 1) // there could be an 'Else' { #ifdef DEBUG_IF_EXEC MessageInterface::ShowMessage ("In If::Execute some conditions are FALSE - executing second branch\n"); #endif branchExecuting = true; branchToExecute = 1; // @todo - add ElseIf (more than two branches) commandComplete = false; commandExecuting = true; } else { #ifdef DEBUG_IF_EXEC MessageInterface::ShowMessage ("In If::Execute - conditions are FALSE - no other branch to execute\n"); #endif branchToExecute = 0; commandComplete = true; commandExecuting = false; branchExecuting = false; // try this - shouldn't matter } } BuildCommandSummary(true); #ifdef DEBUG_IF_EXEC MessageInterface::ShowMessage ("If::BuildCommandSummary completed\n"); #endif return retval; } // Execute() //------------------------------------------------------------------------------ // std::string GetParameterText(const Integer id) const //------------------------------------------------------------------------------ /** * This method returns the parameter text, given the input parameter ID. * * @param <id> Id for the requested parameter text. * * @return parameter text for the requested parameter. * */ //------------------------------------------------------------------------------ std::string If::GetParameterText(const Integer id) const { if (id >= ConditionalBranchParamCount && id < IfParamCount) return PARAMETER_TEXT[id - ConditionalBranchParamCount]; return ConditionalBranch::GetParameterText(id); } //------------------------------------------------------------------------------ // Integer GetParameterID(const std::string &str) const //------------------------------------------------------------------------------ /** * This method returns the parameter ID, given the input parameter string. * * @param <str> string for the requested parameter. * * @return ID for the requested parameter. * */ //------------------------------------------------------------------------------ Integer If::GetParameterID(const std::string &str) const { for (Integer i = ConditionalBranchParamCount; i < IfParamCount; i++) { if (str == PARAMETER_TEXT[i - ConditionalBranchParamCount]) return i; } return ConditionalBranch::GetParameterID(str); } //------------------------------------------------------------------------------ // Gmat::ParameterType GetParameterType(const Integer id) const //------------------------------------------------------------------------------ /** * This method returns the parameter type, given the input parameter ID. * * @param <id> ID for the requested parameter. * * @return parameter type of the requested parameter. * */ //------------------------------------------------------------------------------ Gmat::ParameterType If::GetParameterType(const Integer id) const { if (id >= ConditionalBranchParamCount && id < IfParamCount) return PARAMETER_TYPE[id - ConditionalBranchParamCount]; return ConditionalBranch::GetParameterType(id); } //------------------------------------------------------------------------------ // std::string GetParameterTypeString(const Integer id) const //------------------------------------------------------------------------------ /** * This method returns the parameter type string, given the input parameter ID. * * @param <id> ID for the requested parameter. * * @return parameter type string of the requested parameter. * */ //------------------------------------------------------------------------------ std::string If::GetParameterTypeString(const Integer id) const { return ConditionalBranch::PARAM_TYPE_STRING[GetParameterType(id)]; } //------------------------------------------------------------------------------ // Integer GetIntegerParameter(const Integer id) const //------------------------------------------------------------------------------ /** * This method returns the Integer parameter value, given the input * parameter ID. * * @param <id> ID for the requested parameter. * * @return Integer value of the requested parameter. * */ //------------------------------------------------------------------------------ Integer If::GetIntegerParameter(const Integer id) const { if (id == NEST_LEVEL) return nestLevel; return ConditionalBranch::GetIntegerParameter(id); } //------------------------------------------------------------------------------ // Integer SetIntegerParameter(const Integer id, const Integer value) //------------------------------------------------------------------------------ /** * This method sets the Integer parameter value, given the input * parameter ID. * * @param <id> ID for the requested parameter. * @param <value> Integer value for the requested parameter. * * @return Integer value of the requested parameter. * */ //------------------------------------------------------------------------------ Integer If::SetIntegerParameter(const Integer id, const Integer value) { if (id == NEST_LEVEL) return (nestLevel = value); return ConditionalBranch::SetIntegerParameter(id,value); } //------------------------------------------------------------------------------ // Integer GetIntegerParameter(const std::string &label) const //------------------------------------------------------------------------------ /** * This method returns the Integer parameter value, given the input * parameter ID. * * @param <label> label for the requested parameter. * * @return Integer value of the requested parameter. * */ //------------------------------------------------------------------------------ Integer If::GetIntegerParameter(const std::string &label) const { return GetIntegerParameter(GetParameterID(label)); } //------------------------------------------------------------------------------ // Integer SetIntegerParameter(const std::string &label, const Integer value) //------------------------------------------------------------------------------ /** * This method sets the Integer parameter value, given the input * parameter label. * * @param <label> label for the requested parameter. * @param <value> Integer value for the requested parameter. * * @return Integer value of the requested parameter. * */ //------------------------------------------------------------------------------ Integer If::SetIntegerParameter(const std::string &label, const Integer value) { return SetIntegerParameter(GetParameterID(label), value); } //------------------------------------------------------------------------------ // GmatBase* Clone() const //------------------------------------------------------------------------------ /** * This method returns a clone of the If. * * @return clone of the If. * */ //------------------------------------------------------------------------------ GmatBase* If::Clone() const { return (new If(*this)); } //------------------------------------------------------------------------------ // const std::string& GetGeneratingString(Gmat::WriteMode mode, // const std::string &prefix, // const std::string &useName) //------------------------------------------------------------------------------ /** * Method used to retrieve the string that was parsed to build this GmatCommand. * * This method is used to retrieve the GmatCommand string from the script that * was parsed to build the GmatCommand. It is used to save the script line, so * that the script can be written to a file without inverting the steps taken to * set up the internal object data. As a side benefit, the script line is * available in the GmatCommand structure for debugging purposes. * * @param mode Specifies the type of serialization requested. * @param prefix Optional prefix appended to the object's name. (Used to * indent commands) * @param useName Name that replaces the object's name. (Not used in * commands) * * @return The script line that, when interpreted, defines this If command. */ //------------------------------------------------------------------------------ const std::string& If::GetGeneratingString(Gmat::WriteMode mode, const std::string &prefix, const std::string &useName) { if (mode == Gmat::NO_COMMENTS) { generatingString = "If " + GetConditionalString(); InsertCommandName(generatingString); return generatingString; } // Build the local string generatingString = prefix + "If " + GetConditionalString(); return ConditionalBranch::GetGeneratingString(mode, prefix, useName); } //------------------------------------------------------------------------------ // protected methods //------------------------------------------------------------------------------ // none
33.683761
91
0.462192
[ "object" ]
8b2118f82ceb34392ed5e181f6afed0f857ea824
14,147
hh
C++
Kaskade/algorithm/adaptationStrategy.hh
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
3
2019-07-03T14:03:31.000Z
2021-12-19T10:18:49.000Z
Kaskade/algorithm/adaptationStrategy.hh
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
6
2020-02-17T12:01:31.000Z
2021-12-09T22:02:36.000Z
Kaskade/algorithm/adaptationStrategy.hh
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
2
2020-12-03T04:41:18.000Z
2021-01-11T21:44:42.000Z
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the library KASKADE 7 */ /* see http://www.zib.de/projects/kaskade7-finite-element-toolbox */ /* */ /* Copyright (C) 2002-2013 Zuse Institute Berlin */ /* */ /* KASKADE 7 is distributed under the terms of the ZIB Academic License. */ /* see $KASKADE/academic.txt */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #ifndef ADAPTATION_STRATEGY_HH #define ADAPTATION_STRATEGY_HH #include <algorithm> #include <utility> #include <vector> namespace Kaskade { namespace AdaptationStrategy_Detail { struct BiggerThanAbs { template <class Scalar, class IndexInt> bool operator()(const std::pair<Scalar, IndexInt>& x1, const std::pair<Scalar,IndexInt>& x2) { return fabs(x1.first) > fabs(x2.first); } }; struct Add { template <class Scalar, class IndexInt> Scalar operator()(Scalar x1, const std::pair<Scalar,IndexInt>& x2) { return x1 + x2.first; } }; } namespace Adaptivity { template <class Grid> class FixedCellFraction { static constexpr int dim = Grid::dimension; typedef size_t IndexInt; public: template <typename... Args> explicit FixedCellFraction(GridManagerBase<Grid>& gridManager_, double fraction_, Args...) : gridManager(gridManager_), fraction(fraction_) {} template <class Err, class ErrorRepresentation, class Scalar> void refineGrid_impl(Err const& err, ErrorRepresentation& errorDistribution, Scalar tol) { std::sort(errorDistribution.begin(), errorDistribution.end(), AdaptationStrategy_Detail::BiggerThanAbs()); std::cout << "max error2: " << std::max_element(errorDistribution.begin(), errorDistribution.end())->first << std::endl; std::cout << "min error2: " << std::min_element(errorDistribution.begin(), errorDistribution.end())->first << std::endl; std::vector<std::pair<Scalar,IndexInt> > bulkErrorDistribution(errorDistribution.begin(), errorDistribution.begin() + static_cast<size_t>(errorDistribution.size() * fraction)); Scalar bulkErrorSquared = std::accumulate(bulkErrorDistribution.begin(),bulkErrorDistribution.end(),0.0,AdaptationStrategy_Detail::Add()); std::cout << "bulkErrorDistribution.size()=" << bulkErrorDistribution.size() << std::endl; std::cout << "bulkErrorSquared=" << bulkErrorSquared << std::endl; std::cout << "remaining error contribution (squared): " << std::accumulate(errorDistribution.begin()+bulkErrorDistribution.size(),errorDistribution.end(), 0.0, AdaptationStrategy_Detail::Add()) << std::endl; // do refinement size_t counter = 0; std::vector<int> visitedCells; auto cend = err.descriptions.gridView.template end<0>(); for (auto ci=gridManager.grid().leafView().template begin<0>(); ci!=cend; ++ci) // iterate over cells { for(int i=0; i<bulkErrorDistribution.size(); ++i) // iterate over chosen part of the error distribution if(gridManager.grid().leafIndexSet().index(*ci) == bulkErrorDistribution[i].second) { visitedCells.push_back(gridManager.grid().leafIndexSet().index(*ci)); ++counter; gridManager.mark(1,*ci); } } std::cout << "FIXED CELL FRACTION: marked " << counter << " of " << gridManager.grid().size(0) << " cells for refinement." << std::endl; gridManager.adaptAtOnce(); } private: GridManagerBase<Grid>& gridManager; double fraction; }; template <class Grid> class FixedErrorFraction { static constexpr int dim = Grid::dimension; typedef size_t IndexInt; public: template <typename... Args> explicit FixedErrorFraction(GridManagerBase<Grid>& gridManager_, double fraction_, Args...) : gridManager(gridManager_), fraction(fraction_) {} template <class Err, class ErrorRepresentation, class Scalar> void refineGrid_impl(Err const& err, ErrorRepresentation& errorDistribution, Scalar tol) { tol *= fraction*fraction; std::cout << "used tolerance: " << tol << std::endl; std::sort(errorDistribution.begin(), errorDistribution.end(), AdaptationStrategy_Detail::BiggerThanAbs()); std::cout << "max error2: " << std::max_element(errorDistribution.begin(), errorDistribution.end())->first << std::endl; std::cout << "min error2: " << std::min_element(errorDistribution.begin(), errorDistribution.end())->first << std::endl; Scalar bulkErrorSquared = 0; std::vector<std::pair<Scalar,IndexInt> > bulkErrorDistribution; while(bulkErrorSquared < tol) { bulkErrorDistribution.push_back(errorDistribution[bulkErrorDistribution.size()]); bulkErrorSquared += bulkErrorDistribution.back().first; } std::cout << "bulkErrorDistribution.size()=" << bulkErrorDistribution.size() << std::endl; std::cout << "bulkErrorSquared=" << bulkErrorSquared << std::endl; std::cout << "remaining error contribution (squared): " << std::accumulate(errorDistribution.begin()+bulkErrorDistribution.size(),errorDistribution.end(), 0.0, AdaptationStrategy_Detail::Add()) << std::endl; // do refinement size_t counter = 0; std::vector<int> visitedCells; auto cend = err.descriptions.gridView.template end<0>(); for (auto ci=gridManager.grid().leafView().template begin<0>(); ci!=cend; ++ci) // iterate over cells { for(int i=0; i<bulkErrorDistribution.size(); ++i) // iterate over chosen part of the error distribution if(gridManager.grid().leafIndexSet().index(*ci) == bulkErrorDistribution[i].second) { visitedCells.push_back(gridManager.grid().leafIndexSet().index(*ci)); ++counter; gridManager.mark(1,*ci); } } std::cout << "FIXED ERROR FRACTION: marked " << counter << " of " << gridManager.grid().size(0) << " cells for refinement." << std::endl; gridManager.adaptAtOnce(); } private: GridManagerBase<Grid>& gridManager; double fraction; }; template <class Grid> class ErrorEquilibration2 { public: template <typename... Args> explicit ErrorEquilibration2(GridManagerBase<Grid>& gridManager_, Args...) : gridManager(gridManager_) {} template <class Err, class ErrorRepresentation, class Scalar> void refineGrid_impl(Err const& err, ErrorRepresentation& errorDistribution, Scalar tol) { std::cout << "ERROR EQUILIBRATION" << std::endl; std::sort(errorDistribution.begin(), errorDistribution.end(), AdaptationStrategy_Detail::BiggerThanAbs()); std::cout << "err distr" << std::endl; // for(auto a : errorDistribution) std::cout << errorDistribution.first << ", " << // // size_t lastIndex = errorDistribution.size()-1; // size_t firstIndex = 0; // // while(firstIndex+3 < lastIndex) // { // if(bulkErrorDistribution.size() > 4) // { // Scalar firstContribution = 15.0/256.0 * errorDistribution[firstIndex].first; // // Scalar lastContributions = bulkErrorDistribution[lastIndex--].first; // lastContributions += bulkErrorDistribution[lastIndex--].first; // lastContributions += bulkErrorDistribution[lastIndex].first; // lastContributions *= 15.0/16.0; // // if(lastContributions < firstContribution) // { // ++lastIndexForDoubleRefinement; // ++firstIndex; // --lastIndex; // bulkErrorDistribution.erase(bulkErrorDistribution.end()-3, bulkErrorDistribution.end()); // } // else break; // } // } Scalar N2 = gridManager.grid().size(0); // N2 *= N2; Scalar relTol = tol/N2; // do refinement auto cend = gridManager.grid().leafView().template end<0>(); size_t counter = 0; Scalar minErr = errorDistribution.back().first, maxErr = errorDistribution[0].first; //constexpr int dim = ErrorRepresentation::Descriptions::Grid::dimension; //Dune::FieldVector<Scalar,dim> x0(0.2); std::cout << "grr" << std::endl; std::cout << "marking cells..." << std::flush; for (auto ci=gridManager.grid().leafView().template begin<0>(); ci!=cend; ++ci) // iterate over cells { // if(counter > N3) break; // std::cout << "counter: " << counter << std::endl; // std::cout << "id: " << is.index(*ci) << std::endl; // std::cout << "corners: " << std::endl; // for(size_t i=0; i<ci->geometry().corners(); ++i) std::cout << "i: " << ci->geometry().corner(i) << std::endl; for(size_t i=0; i<errorDistribution.size(); ++i) // iterate over chosen part of the error distribution if(gridManager.grid().leafIndexSet().index(*ci) == errorDistribution[i].second) { // auto const& tmp = boost::fusion::at_c<0>(err.data); // std::cout << "gsg" << std::endl; // Scalar val = tmp.value(ci->geometry().global(x0)); // val = std::fabs(val); // //Scalar val = boost::fusion::at_c<0>(err.data).value(*ci,x0); // std::cout << "val=" << val << std::endl; // if(minErr > val) minErr = val; // if(maxErr < val) maxErr = val; // if(val > relTol){ // ++counter; // gridManager.mark(1,*ci); // } // if(minErr > errorDistribution[i].first) minErr = errorDistribution[i].first; // if(maxErr < errorDistribution[i].first) maxErr = errorDistribution[i].first; if(errorDistribution[i].first > relTol){ std::cout << "marking cell at position " << i << std::endl; ++counter; gridManager.mark(1,*ci); } } } std::cout << "done." << std::endl; std::cout << "totalErrorSquared: " << tol << " -> tolerance: " << relTol << std::endl; std::cout << "maxErr: " << maxErr << ", minErr: " << minErr << std::endl; std::cout << "refining " << counter << " of " << gridManager.grid().size(0) << " cells" << std::endl; std::cout << "adapting..." << std::flush; gridManager.adaptAtOnce(); std::cout << "done." << std::endl; // adjust error function } private: GridManagerBase<Grid>& gridManager; }; template <class Grid> class ErrorEquilibration { public: template <typename... Args> explicit ErrorEquilibration(GridManagerBase<Grid>& gridManager_, Args...) : gridManager(gridManager_) {} template <class Err, class ErrorRepresentation, class Scalar> void refineGrid_impl(Err const& err, ErrorRepresentation& errorDistribution, Scalar tol) { std::cout << "ERROR EQUILIBRATION" << std::endl; std::sort(errorDistribution.begin(), errorDistribution.end(), AdaptationStrategy_Detail::BiggerThanAbs()); Scalar n2 = gridManager.grid().size(0); Scalar relTol = tol/n2; // do refinement auto cend = gridManager.grid().leafView().template end<0>(); size_t counter = 0; Scalar minErr = errorDistribution.back().first, maxErr = errorDistribution[0].first; std::vector<size_t> mainContributors; //constexpr int dim = ErrorRepresentation::Descriptions::Grid::dimension; //Dune::FieldVector<Scalar,dim> x0(0.2); std::cout << "marking cells..." << std::flush; for (auto ci=gridManager.grid().leafView().template begin<0>(); ci!=cend; ++ci) // iterate over cells { for(size_t i=0; i<errorDistribution.size(); ++i) // iterate over chosen part of the error distribution if(gridManager.grid().leafIndexSet().index(*ci) == errorDistribution[i].second) { if(errorDistribution[i].first > relTol){ if(errorDistribution[i].first > 4 * relTol) mainContributors.push_back(errorDistribution[i].second); ++counter; gridManager.mark(1,*ci); } } } std::cout << "done." << std::endl; std::cout << "totalErrorSquared: " << tol << " -> tolerance: " << relTol << std::endl; std::cout << "maxErr: " << maxErr << ", minErr: " << minErr << std::endl; std::cout << "refining " << counter << " of " << gridManager.grid().size(0) << " cells" << std::endl; std::cout << "adapting..." << std::flush; gridManager.adaptAtOnce(); std::cout << "done." << std::endl; /* std::cout << "second refinement" << std::endl; auto cend2 = gridManager.grid().leafView().template end<0>(); for(auto ci=gridManager.grid().leafView().template begin<0>(); ci!=cend2; ++ci) { if(ci->level() > 0) { auto father = ci->father(); if(ci->level() > father->level()) for(size_t i : mainContributors) if(i == gridManager.grid().levelIndexSet(gridManager.grid().maxLevel()-1).index(*father)) { gridManager.mark(1,*ci); return; } } } std::cout << "adapting..." << std::flush; gridManager.adaptAtOnce(); std::cout << "done." << std::endl;*/ } private: GridManagerBase<Grid>& gridManager; }; } // end namespace Adaptivity } // end namespace Kaskade #endif
43.529231
215
0.574044
[ "geometry", "vector" ]
8b211f28ac0df93e9721a075a7a41d4a24309908
39,125
cpp
C++
Source/CICalendarRecurrence.cpp
mulberry-mail/CICalendar
e22ffb9f4060ad8ae9a60a0b339fbc0a64f0d680
[ "Apache-2.0" ]
3
2018-09-13T22:12:38.000Z
2021-11-05T13:43:17.000Z
Source/CICalendarRecurrence.cpp
mulberry-mail/CICalendar
e22ffb9f4060ad8ae9a60a0b339fbc0a64f0d680
[ "Apache-2.0" ]
null
null
null
Source/CICalendarRecurrence.cpp
mulberry-mail/CICalendar
e22ffb9f4060ad8ae9a60a0b339fbc0a64f0d680
[ "Apache-2.0" ]
1
2019-07-22T20:17:49.000Z
2019-07-22T20:17:49.000Z
/* Copyright (c) 2007 Cyrus Daboo. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /* CICalendarRecurrence.cpp Author: Description: <describe the CICalendarRecurrence class here> */ #include "CICalendarRecurrence.h" #include "CICalendarPeriod.h" #include "CStringUtils.h" #include <cerrno> #include <algorithm> #include <memory> #include <strstream> using namespace iCal; void CICalendarRecurrence::_init_CICalendarRecurrence() { mFreq = eRecurrence_YEARLY; mUseCount = false; mCount = 0; mUseUntil = false; mInterval = 1; mBySeconds.clear(); mByMinutes.clear(); mByHours.clear(); mByDay.clear(); mByMonthDay.clear(); mByYearDay.clear(); mByWeekNo.clear(); mByMonth.clear(); mBySetPos.clear(); mWeekstart = eRecurrence_WEEKDAY_MO; mCached = false; mFullyCached = false; mRecurrences.clear(); } void CICalendarRecurrence::_copy_CICalendarRecurrence(const CICalendarRecurrence& copy) { _init_CICalendarRecurrence(); mFreq = copy.mFreq; mUseCount = copy.mUseCount; mCount = copy.mCount; mUseUntil = copy.mUseUntil; mUntil = copy.mUntil; mInterval = copy.mInterval; mBySeconds = copy.mBySeconds; mByMinutes = copy.mByMinutes; mByHours = copy.mByHours; mByDay = copy.mByDay; mByMonthDay = copy.mByMonthDay; mByYearDay = copy.mByYearDay; mByWeekNo = copy.mByWeekNo; mByMonth = copy.mByMonth; mBySetPos = copy.mBySetPos; mWeekstart = copy.mWeekstart; mCached = copy.mCached; mCacheStart = copy.mCacheStart; mCacheUpto = copy.mCacheUpto; mFullyCached = copy.mFullyCached; mRecurrences = copy.mRecurrences; } bool CICalendarRecurrence::Equals(const CICalendarRecurrence& comp) const { return (mFreq == comp.mFreq) && (mCount == comp.mCount) && (mUseUntil == comp.mUseUntil) && (mUntil == comp.mUntil) && (mInterval == comp.mInterval) && Equals(mBySeconds, comp.mBySeconds) && Equals(mByMinutes, comp.mByMinutes) && Equals(mByHours, comp.mByHours) && Equals(mByDay, comp.mByDay) && Equals(mByMonthDay, comp.mByMonthDay) && Equals(mByYearDay, comp.mByYearDay) && Equals(mByWeekNo, comp.mByWeekNo) && Equals(mByMonth, comp.mByMonth) && Equals(mBySetPos, comp.mBySetPos) && (mWeekstart == comp.mWeekstart); } bool CICalendarRecurrence::Equals(const std::vector<int32_t>& items1, const std::vector<int32_t>& items2) const { // Check sizes first if (items1.size() != items2.size()) return false; else if (items1.size() == 0) return true; // Copy and sort each one for comparison std::vector<int32_t> temp1(items1); std::vector<int32_t> temp2(items2); std::sort(temp1.begin(), temp1.end()); std::sort(temp2.begin(), temp2.end()); return std::equal(temp1.begin(), temp1.end(), temp2.begin()); } bool CICalendarRecurrence::Equals(const std::vector<CWeekDayNum>& items1, const std::vector<CWeekDayNum>& items2) const { // Check sizes first if (items1.size() != items2.size()) return false; else if (items1.size() == 0) return true; // Copy and sort each one for comparison std::vector<CWeekDayNum> temp1(items1); std::vector<CWeekDayNum> temp2(items2); std::sort(temp1.begin(), temp1.end()); std::sort(temp2.begin(), temp2.end()); return std::equal(temp1.begin(), temp1.end(), temp2.begin()); } const char* cFreqMap[] = { cICalValue_RECUR_SECONDLY, cICalValue_RECUR_MINUTELY, cICalValue_RECUR_HOURLY, cICalValue_RECUR_DAILY, cICalValue_RECUR_WEEKLY, cICalValue_RECUR_MONTHLY, cICalValue_RECUR_YEARLY, NULL}; const char* cRecurMap[] = { cICalValue_RECUR_UNTIL, cICalValue_RECUR_COUNT, cICalValue_RECUR_INTERVAL, cICalValue_RECUR_BYSECOND, cICalValue_RECUR_BYMINUTE, cICalValue_RECUR_BYHOUR, cICalValue_RECUR_BYDAY, cICalValue_RECUR_BYMONTHDAY, cICalValue_RECUR_BYYEARDAY, cICalValue_RECUR_BYWEEKNO, cICalValue_RECUR_BYMONTH, cICalValue_RECUR_BYSETPOS, cICalValue_RECUR_WKST, NULL}; const char* cWeekdayMap[] = { cICalValue_RECUR_WEEKDAY_SU, cICalValue_RECUR_WEEKDAY_MO, cICalValue_RECUR_WEEKDAY_TU, cICalValue_RECUR_WEEKDAY_WE, cICalValue_RECUR_WEEKDAY_TH, cICalValue_RECUR_WEEKDAY_FR, cICalValue_RECUR_WEEKDAY_SA, NULL}; const unsigned long cUnknownIndex = 0xFFFFFFFF; void CICalendarRecurrence::Parse(const cdstring& data) { _init_CICalendarRecurrence(); // Tokenise using ';' char* p = const_cast<char*>(data.c_str()); // Look for FREQ= with delimiter { std::auto_ptr<char> freq(::strduptokenstr(&p, ";")); if (freq.get() == NULL) return; // Make sure it is the token we expect if (::strncmp(freq.get(), cICalValue_RECUR_FREQ, cICalValue_RECUR_FREQ_LEN) != 0) return; const char* q = freq.get() + cICalValue_RECUR_FREQ_LEN; // Get the FREQ value unsigned long index = ::strindexfind(q, cFreqMap, cUnknownIndex); if (index == cUnknownIndex) return; mFreq = static_cast<ERecurrence_FREQ>(index); } while(*p) { // Get next token p++; std::auto_ptr<char> item(::strduptokenstr(&p, ";")); if (item.get() == NULL) return; // Determine token type unsigned long index = ::strnindexfind(item.get(), cRecurMap, cUnknownIndex); if (index == cUnknownIndex) return; // Parse remainder based on index const char* q = strchr(item.get(), '=') + 1; switch(index) { case 0: // UNTIL if (mUseCount) return; mUseUntil = true; mUntil.Parse(q); break; case 1: // COUNT if (mUseUntil) return; mUseCount = true; mCount = atol(q); // Must not be less than one if (mCount < 1) mCount = 1; break; case 2: // INTERVAL mInterval = atol(q); // Must NOT be less than one if (mInterval < 1) mInterval = 1; break; case 3: // BYSECOND if (!mBySeconds.empty()) return; ParseList(q, mBySeconds); break; case 4: // BYMINUTE if (!mByMinutes.empty()) return; ParseList(q, mByMinutes); break; case 5: // BYHOUR if (!mByHours.empty()) return; ParseList(q, mByHours); break; case 6: // BYDAY if (!mByDay.empty()) return; ParseList(q, mByDay); break; case 7: // BYMONTHDAY if (!mByMonthDay.empty()) return; ParseList(q, mByMonthDay); break; case 8: // BYYEARDAY if (!mByYearDay.empty()) return; ParseList(q, mByYearDay); break; case 9: // BYWEEKNO if (!mByWeekNo.empty()) return; ParseList(q, mByWeekNo); break; case 10: // BYMONTH if (!mByMonth.empty()) return; ParseList(q, mByMonth); break; case 11: // BYSETPOS if (!mBySetPos.empty()) return; ParseList(q, mBySetPos); break; case 12: // WKST { unsigned long index = ::strindexfind(q, cWeekdayMap, cUnknownIndex); if (index == cUnknownIndex) return; mWeekstart = static_cast<ERecurrence_WEEKDAY>(index); } break; } } } // Parse comma separated list of int32_t's void CICalendarRecurrence::ParseList(const char* txt, std::vector<int32_t>& list) { const char* p = txt; while(p && *p) { errno = 0; int32_t num = strtol(p, (char**) &p, 10); if (errno != 0) return; list.push_back(num); if (*p++ != ',') p = NULL; } } void CICalendarRecurrence::ParseList(const char* txt, std::vector<CWeekDayNum>& list) { const char* p = txt; while(p && *p) { // Get number if present errno = 0; int32_t num = 0; if (isdigit(*p) || (*p == '+') || (*p == '-')) { num = strtol(p, (char**) &p, 10); if (errno != 0) return; } // Get day unsigned long index = ::strnindexfind(p, cWeekdayMap, cUnknownIndex); if (index == cUnknownIndex) return; CICalendarDateTime::EDayOfWeek wday = static_cast<CICalendarDateTime::EDayOfWeek>(index); p += 2; list.push_back(CWeekDayNum(num, wday)); if (*p++ != ',') p = NULL; } } void CICalendarRecurrence::Generate(std::ostream& os) const { os << cICalValue_RECUR_FREQ; switch(mFreq) { case eRecurrence_SECONDLY: os << cICalValue_RECUR_SECONDLY; break; case eRecurrence_MINUTELY: os << cICalValue_RECUR_MINUTELY; break; case eRecurrence_HOURLY: os << cICalValue_RECUR_HOURLY; break; case eRecurrence_DAILY: os << cICalValue_RECUR_DAILY; break; case eRecurrence_WEEKLY: os << cICalValue_RECUR_WEEKLY; break; case eRecurrence_MONTHLY: os << cICalValue_RECUR_MONTHLY; break; case eRecurrence_YEARLY: os << cICalValue_RECUR_YEARLY; break; } if (mUseCount) os << ';' << cICalValue_RECUR_COUNT << mCount; else if (mUseUntil) { os << ';' << cICalValue_RECUR_UNTIL; mUntil.Generate(os); } if (mInterval > 1) os << ';' << cICalValue_RECUR_INTERVAL << mInterval; if (mBySeconds.size() != 0) { os << ';' << cICalValue_RECUR_BYSECOND; for(std::vector<int32_t>::const_iterator iter = mBySeconds.begin(); iter != mBySeconds.end(); iter++) { if (iter != mBySeconds.begin()) os << ','; os << *iter; } } if (mByMinutes.size() != 0) { os << ';' << cICalValue_RECUR_BYMINUTE; for(std::vector<int32_t>::const_iterator iter = mByMinutes.begin(); iter != mByMinutes.end(); iter++) { if (iter != mByMinutes.begin()) os << ','; os << *iter; } } if (mByHours.size() != 0) { os << ';' << cICalValue_RECUR_BYHOUR; for(std::vector<int32_t>::const_iterator iter = mByHours.begin(); iter != mByHours.end(); iter++) { if (iter != mByHours.begin()) os << ','; os << *iter; } } if (mByDay.size() != 0) { os << ';' << cICalValue_RECUR_BYDAY; for(std::vector<CWeekDayNum>::const_iterator iter = mByDay.begin(); iter != mByDay.end(); iter++) { if (iter != mByDay.begin()) os << ','; if ((*iter).first != 0) os << (*iter).first; switch((*iter).second) { case eRecurrence_WEEKDAY_SU: os << cICalValue_RECUR_WEEKDAY_SU; break; case eRecurrence_WEEKDAY_MO: os << cICalValue_RECUR_WEEKDAY_MO; break; case eRecurrence_WEEKDAY_TU: os << cICalValue_RECUR_WEEKDAY_TU; break; case eRecurrence_WEEKDAY_WE: os << cICalValue_RECUR_WEEKDAY_WE; break; case eRecurrence_WEEKDAY_TH: os << cICalValue_RECUR_WEEKDAY_TH; break; case eRecurrence_WEEKDAY_FR: os << cICalValue_RECUR_WEEKDAY_FR; break; case eRecurrence_WEEKDAY_SA: os << cICalValue_RECUR_WEEKDAY_SA; break; } } } if (mByMonthDay.size() != 0) { os << ';' << cICalValue_RECUR_BYMONTHDAY; for(std::vector<int32_t>::const_iterator iter = mByMonthDay.begin(); iter != mByMonthDay.end(); iter++) { if (iter != mByMonthDay.begin()) os << ','; os << *iter; } } if (mByYearDay.size() != 0) { os << ';' << cICalValue_RECUR_BYYEARDAY; for(std::vector<int32_t>::const_iterator iter = mByYearDay.begin(); iter != mByYearDay.end(); iter++) { if (iter != mByYearDay.begin()) os << ','; os << *iter; } } if (mByWeekNo.size() != 0) { os << ';' << cICalValue_RECUR_BYWEEKNO; for(std::vector<int32_t>::const_iterator iter = mByWeekNo.begin(); iter != mByWeekNo.end(); iter++) { if (iter != mByWeekNo.begin()) os << ','; os << *iter; } } if (mByMonth.size() != 0) { os << ';' << cICalValue_RECUR_BYMONTH; for(std::vector<int32_t>::const_iterator iter = mByMonth.begin(); iter != mByMonth.end(); iter++) { if (iter != mByMonth.begin()) os << ','; os << *iter; } } if (mBySetPos.size() != 0) { os << ';' << cICalValue_RECUR_BYSETPOS; for(std::vector<int32_t>::const_iterator iter = mBySetPos.begin(); iter != mBySetPos.end(); iter++) { if (iter != mBySetPos.begin()) os << ','; os << *iter; } } if (mWeekstart != eRecurrence_WEEKDAY_MO) // MO is the default so we do not need it { os << ';' << cICalValue_RECUR_WKST; switch(mWeekstart) { case eRecurrence_WEEKDAY_SU: os << cICalValue_RECUR_WEEKDAY_SU; break; case eRecurrence_WEEKDAY_MO: os << cICalValue_RECUR_WEEKDAY_MO; break; case eRecurrence_WEEKDAY_TU: os << cICalValue_RECUR_WEEKDAY_TU; break; case eRecurrence_WEEKDAY_WE: os << cICalValue_RECUR_WEEKDAY_WE; break; case eRecurrence_WEEKDAY_TH: os << cICalValue_RECUR_WEEKDAY_TH; break; case eRecurrence_WEEKDAY_FR: os << cICalValue_RECUR_WEEKDAY_FR; break; case eRecurrence_WEEKDAY_SA: os << cICalValue_RECUR_WEEKDAY_SA; break; } } } // Is rule capable of simple UI display bool CICalendarRecurrence::IsSimpleRule() const { // One that has no BYxxx rules return !HasBy(); } // Is rule capable of advanced UI display bool CICalendarRecurrence::IsAdvancedRule() const { // One that has BYMONTH, // BYMONTHDAY (with no negative value), // BYDAY (with multiple unumbered, or numbered with all the same number (1..4, -2, -1) // BYSETPOS with +1, or -1 only // no others // First checks the ones we do not handle at all if (!mBySeconds.empty() || !mByMinutes.empty() || !mByHours.empty() || !mByYearDay.empty() || !mByWeekNo.empty()) return false; // Check BYMONTHDAY numbers (we can handle -7...-1, 1..31) for(std::vector<int32_t>::const_iterator iter = mByMonthDay.begin(); iter != mByMonthDay.end(); iter++) { if ((*iter < -7) || (*iter > 31) || (*iter == 0)) return false; } // Check BYDAY numbers int32_t number = 0; for(std::vector<CWeekDayNum>::const_iterator iter = mByDay.begin(); iter != mByDay.end(); iter++) { // Get the first number if (iter == mByDay.begin()) { number = (*iter).first; // Check number range if ((number > 4) || (number < -2)) return false; } // If current differs from last, then we have an error else if (number != (*iter).first) return false; } // Check BYSETPOS numbers if (mBySetPos.size() > 1) return false; if ((mBySetPos.size() == 1) && (mBySetPos[0] != -1) && (mBySetPos[0] != 1)) return false; // If we get here it must be OK return true; } cdstring CICalendarRecurrence::GetUIDescription() const { // For now just use iCal item std::ostrstream ostr; Generate(ostr); ostr << std::ends; cdstring temp; temp.steal(ostr.str()); return temp; } void CICalendarRecurrence::Expand(const CICalendarDateTime& start, const CICalendarPeriod& range, CICalendarDateTimeList& items) const { // Wipe cache if start is different if (mCached && (start != mCacheStart)) { mCached = false; mFullyCached = false; mRecurrences.clear(); } // Is the current cache complete or does it extaned past the requested range end if (!mCached || !mFullyCached && (mCacheUpto < range.GetEnd())) { CICalendarPeriod cache_range(range); // If partially cached just cache from previous cache end up to new end if (mCached) cache_range = CICalendarPeriod(mCacheUpto, range.GetEnd()); // Simple expansion is one where there is no BYXXX rule part if (mBySeconds.empty() && mByMinutes.empty() && mByHours.empty() && mByDay.empty() && mByMonthDay.empty() && mByYearDay.empty() && mByWeekNo.empty() && mByMonth.empty() && mBySetPos.empty()) mFullyCached = SimpleExpand(start, cache_range, mRecurrences); else mFullyCached = ComplexExpand(start, cache_range, mRecurrences); // Set cache values mCached = true; mCacheStart = start; mCacheUpto = range.GetEnd(); } // Just return the cached items in the requested range for(CICalendarDateTimeList::const_iterator iter = mRecurrences.begin(); iter != mRecurrences.end(); iter++) { if (range.IsDateWithinPeriod(*iter)) items.push_back(*iter); } } bool CICalendarRecurrence::SimpleExpand(const CICalendarDateTime& start, const CICalendarPeriod& range, CICalendarDateTimeList& items) const { CICalendarDateTime start_iter(start); int32_t ctr = 0; while(true) { // Exit if after period we want if (range.IsDateAfterPeriod(start_iter)) return false; // Add current one to list items.push_back(start_iter); // Get next item start_iter.Recur(mFreq, mInterval); // Check limits if (mUseCount) { // Bump counter and exit if over ctr++; if (ctr >= mCount) return true; } else if (mUseUntil) { // Exit if next item is after until (its OK if its the same as UNTIL as // UNTIL is inclusive) if (start_iter > mUntil) return true; } } } bool CICalendarRecurrence::ComplexExpand(const CICalendarDateTime& start, const CICalendarPeriod& range, CICalendarDateTimeList& items) const { CICalendarDateTime start_iter(start); int32_t ctr = 0; // Always add the initial instance DTSTART items.push_back(start); if (mUseCount) { // Bump counter and exit if over ctr++; if (ctr >= mCount) return true; } // Need to re-initialise start based on BYxxx rules while(true) { // Behaviour is based on frequency CICalendarDateTimeList set_items; switch(mFreq) { case eRecurrence_SECONDLY: GenerateSecondlySet(start_iter, set_items); break; case eRecurrence_MINUTELY: GenerateMinutelySet(start_iter, set_items); break; case eRecurrence_HOURLY: GenerateHourlySet(start_iter, set_items); break; case eRecurrence_DAILY: GenerateDailySet(start_iter, set_items); break; case eRecurrence_WEEKLY: GenerateWeeklySet(start_iter, set_items); break; case eRecurrence_MONTHLY: GenerateMonthlySet(start_iter, set_items); break; case eRecurrence_YEARLY: GenerateYearlySet(start_iter, set_items); break; } // Always sort the set as BYxxx rules may not be sorted sort(set_items.begin(), set_items.end()); // Process each one in the generated set for(CICalendarDateTimeList::const_iterator iter = set_items.begin(); iter != set_items.end(); iter++) { // Ignore if it is before the actual start - we need this because the expansion // can go back in time from the real start, but we must exclude those when counting // even if they are not within the requested range if (*iter < start) continue; // Exit if after period we want if (range.IsDateAfterPeriod(*iter)) return false; // Exit if beyond the UNTIL limit if (mUseUntil) { // Exit if next item is after until (its OK if its the same as UNTIL as // UNTIL is inclusive) if (*iter > mUntil) return true; } // Special for start instance if ((ctr == 1) && (start == *iter)) continue; // Add current one to list items.push_back(*iter); // Check limits if (mUseCount) { // Bump counter and exit if over ctr++; if (ctr >= mCount) return true; } } // Exit if after period we want if (range.IsDateAfterPeriod(start_iter)) return false; // Get next item start_iter.Recur(mFreq, mInterval); } } // Clear out cached values due to some sort of change void CICalendarRecurrence::Clear() { mCached = false; mFullyCached = false; mRecurrences.clear(); } // IMPORTANT ExcludeFutureRecurrence assumes mCacheStart is setup with the owning VEVENT's DTSTART // Currently this method is only called when a recurrence is being removed so the recurrence data should be cached // Exclude dates on or after the chosen one void CICalendarRecurrence::ExcludeFutureRecurrence(const CICalendarDateTime& exclude) { // Expand the rule upto the exclude date CICalendarDateTimeList items; Expand(mCacheStart,CICalendarPeriod(mCacheStart, exclude), items); // Adjust UNTIL or add one if no COUNT if (GetUseUntil() || !GetUseCount()) { // The last one is just less than the exclude date if (items.size() != 0) { // Now use the data as the UNTIL mUseUntil = true; mUntil = items.back(); } } // Adjust COUNT else if (GetUseCount()) { // The last one is just less than the exclude date mUseCount = true; mCount = items.size(); } // Now clear out the cached set after making changes Clear(); } #pragma mark ____________________________Generate Complex recurrence based on frequency void CICalendarRecurrence::GenerateYearlySet(const CICalendarDateTime& start, CICalendarDateTimeList& items) const { // All possible BYxxx are valid, though some combinations are not // Start with initial date-time items.push_back(start); if (mByMonth.size() != 0) { ByMonthExpand(items); } if (mByWeekNo.size() != 0) { ByWeekNoExpand(items); } if (mByYearDay.size() != 0) { ByYearDayExpand(items); } if (mByMonthDay.size() != 0) { ByMonthDayExpand(items); } if (mByDay.size() != 0) { // BYDAY is complicated: // if BYDAY is included with BYYEARDAY or BYMONTHDAY then it contracts the recurrence set // else it expands it, but the expansion depends on the frequency and other BYxxx periodicities if ((mByYearDay.size() != 0) || (mByMonthDay.size() != 0)) ByDayLimit(items); else if (mByWeekNo.size() != 0) ByDayExpandWeekly(items); else if (mByMonth.size() != 0) ByDayExpandMonthly(items); else ByDayExpandYearly(items); } if (mByHours.size() != 0) { ByHourExpand(items); } if (mByMinutes.size() != 0) { ByMinuteExpand(items); } if (mBySeconds.size() != 0) { BySecondExpand(items); } if (mBySetPos.size() != 0) { BySetPosLimit(items); } } void CICalendarRecurrence::GenerateMonthlySet(const CICalendarDateTime& start, CICalendarDateTimeList& items) const { // Cannot have BYYEARDAY and BYWEEKNO // Start with initial date-time items.push_back(start); if (mByMonth.size() != 0) { // BYMONTH limits the range of possible values ByMonthLimit(items); if (items.size() == 0) return; } // No BYWEEKNO // No BYYEARDAY if (mByMonthDay.size() != 0) { ByMonthDayExpand(items); } if (mByDay.size() != 0) { // BYDAY is complicated: // if BYDAY is included with BYYEARDAY or BYMONTHDAY then it contracts the recurrence set // else it expands it, but the expansion depends on the frequency and other BYxxx periodicities if ((mByYearDay.size() != 0) || (mByMonthDay.size() != 0)) ByDayLimit(items); else ByDayExpandMonthly(items); } if (mByHours.size() != 0) { ByHourExpand(items); } if (mByMinutes.size() != 0) { ByMinuteExpand(items); } if (mBySeconds.size() != 0) { BySecondExpand(items); } if (mBySetPos.size() != 0) { BySetPosLimit(items); } } void CICalendarRecurrence::GenerateWeeklySet(const CICalendarDateTime& start, CICalendarDateTimeList& items) const { // Cannot have BYYEARDAY and BYMONTHDAY // Start with initial date-time items.push_back(start); if (mByMonth.size() != 0) { // BYMONTH limits the range of possible values ByMonthLimit(items); if (items.size() == 0) return; } if (mByWeekNo.size() != 0) { ByWeekNoLimit(items); if (items.size() == 0) return; } // No BYYEARDAY // No BYMONTHDAY if (mByDay.size() != 0) { ByDayExpandWeekly(items); } if (mByHours.size() != 0) { ByHourExpand(items); } if (mByMinutes.size() != 0) { ByMinuteExpand(items); } if (mBySeconds.size() != 0) { BySecondExpand(items); } if (mBySetPos.size() != 0) { BySetPosLimit(items); } } void CICalendarRecurrence::GenerateDailySet(const CICalendarDateTime& start, CICalendarDateTimeList& items) const { // Cannot have BYYEARDAY // Start with initial date-time items.push_back(start); if (mByMonth.size() != 0) { // BYMONTH limits the range of possible values ByMonthLimit(items); if (items.size() == 0) return; } if (mByWeekNo.size() != 0) { ByWeekNoLimit(items); if (items.size() == 0) return; } // No BYYEARDAY if (mByMonthDay.size() != 0) { ByMonthDayLimit(items); if (items.size() == 0) return; } if (mByDay.size() != 0) { ByDayLimit(items); if (items.size() == 0) return; } if (mByHours.size() != 0) { ByHourExpand(items); } if (mByMinutes.size() != 0) { ByMinuteExpand(items); } if (mBySeconds.size() != 0) { BySecondExpand(items); } if (mBySetPos.size() != 0) { BySetPosLimit(items); } } void CICalendarRecurrence::GenerateHourlySet(const CICalendarDateTime& start, CICalendarDateTimeList& items) const { // Cannot have BYYEARDAY // Start with initial date-time items.push_back(start); if (mByMonth.size() != 0) { // BYMONTH limits the range of possible values ByMonthLimit(items); if (items.size() == 0) return; } if (mByWeekNo.size() != 0) { ByWeekNoLimit(items); if (items.size() == 0) return; } // No BYYEARDAY if (mByMonthDay.size() != 0) { ByMonthDayLimit(items); if (items.size() == 0) return; } if (mByDay.size() != 0) { ByDayLimit(items); if (items.size() == 0) return; } if (mByHours.size() != 0) { ByHourLimit(items); if (items.size() == 0) return; } if (mByMinutes.size() != 0) { ByMinuteExpand(items); } if (mBySeconds.size() != 0) { BySecondExpand(items); } if (mBySetPos.size() != 0) { BySetPosLimit(items); } } void CICalendarRecurrence::GenerateMinutelySet(const CICalendarDateTime& start, CICalendarDateTimeList& items) const { // Cannot have BYYEARDAY // Start with initial date-time items.push_back(start); if (mByMonth.size() != 0) { // BYMONTH limits the range of possible values ByMonthLimit(items); if (items.size() == 0) return; } if (mByWeekNo.size() != 0) { ByWeekNoLimit(items); if (items.size() == 0) return; } // No BYYEARDAY if (mByMonthDay.size() != 0) { ByMonthDayLimit(items); if (items.size() == 0) return; } if (mByDay.size() != 0) { ByDayLimit(items); if (items.size() == 0) return; } if (mByHours.size() != 0) { ByHourLimit(items); if (items.size() == 0) return; } if (mByMinutes.size() != 0) { ByMinuteLimit(items); if (items.size() == 0) return; } if (mBySeconds.size() != 0) { BySecondExpand(items); } if (mBySetPos.size() != 0) { BySetPosLimit(items); } } void CICalendarRecurrence::GenerateSecondlySet(const CICalendarDateTime& start, CICalendarDateTimeList& items) const { // Cannot have BYYEARDAY // Start with initial date-time items.push_back(start); if (mByMonth.size() != 0) { // BYMONTH limits the range of possible values ByMonthLimit(items); if (items.size() == 0) return; } if (mByWeekNo.size() != 0) { ByWeekNoLimit(items); if (items.size() == 0) return; } // No BYYEARDAY if (mByMonthDay.size() != 0) { ByMonthDayLimit(items); if (items.size() == 0) return; } if (mByDay.size() != 0) { ByDayLimit(items); if (items.size() == 0) return; } if (mByHours.size() != 0) { ByHourLimit(items); if (items.size() == 0) return; } if (mByMinutes.size() != 0) { ByMinuteLimit(items); if (items.size() == 0) return; } if (mBySeconds.size() != 0) { BySecondLimit(items); if (items.size() == 0) return; } if (mBySetPos.size() != 0) { BySetPosLimit(items); } } #pragma mark ____________________________BYxxx expansions void CICalendarRecurrence::ByMonthExpand(CICalendarDateTimeList& dates) const { // Loop over all input items CICalendarDateTimeList output; for(CICalendarDateTimeList::const_iterator iter1 = dates.begin(); iter1 != dates.end(); iter1++) { // Loop over each BYMONTH and generating a new date-time for it and insert into output for(std::vector<int32_t>::const_iterator iter2 = mByMonth.begin(); iter2 != mByMonth.end(); iter2++) { CICalendarDateTime temp(*iter1); temp.SetMonth(*iter2); output.push_back(temp); } } dates = output; } void CICalendarRecurrence::ByWeekNoExpand(CICalendarDateTimeList& dates) const { // Loop over all input items CICalendarDateTimeList output; for(CICalendarDateTimeList::const_iterator iter1 = dates.begin(); iter1 != dates.end(); iter1++) { // Loop over each BYWEEKNO and generating a new date-time for it and insert into output for(std::vector<int32_t>::const_iterator iter2 = mByWeekNo.begin(); iter2 != mByWeekNo.end(); iter2++) { CICalendarDateTime temp(*iter1); temp.SetWeekNo(*iter2); output.push_back(temp); } } dates = output; } void CICalendarRecurrence::ByYearDayExpand(CICalendarDateTimeList& dates) const { // Loop over all input items CICalendarDateTimeList output; for(CICalendarDateTimeList::const_iterator iter1 = dates.begin(); iter1 != dates.end(); iter1++) { // Loop over each BYYEARDAY and generating a new date-time for it and insert into output for(std::vector<int32_t>::const_iterator iter2 = mByYearDay.begin(); iter2 != mByYearDay.end(); iter2++) { CICalendarDateTime temp(*iter1); temp.SetYearDay(*iter2); output.push_back(temp); } } dates = output; } void CICalendarRecurrence::ByMonthDayExpand(CICalendarDateTimeList& dates) const { // Loop over all input items CICalendarDateTimeList output; for(CICalendarDateTimeList::const_iterator iter1 = dates.begin(); iter1 != dates.end(); iter1++) { // Loop over each BYMONTHDAY and generating a new date-time for it and insert into output for(std::vector<int32_t>::const_iterator iter2 = mByMonthDay.begin(); iter2 != mByMonthDay.end(); iter2++) { CICalendarDateTime temp(*iter1); temp.SetMonthDay(*iter2); output.push_back(temp); } } dates = output; } void CICalendarRecurrence::ByDayExpandYearly(CICalendarDateTimeList& dates) const { // Loop over all input items CICalendarDateTimeList output; for(CICalendarDateTimeList::const_iterator iter1 = dates.begin(); iter1 != dates.end(); iter1++) { // Loop over each BYDAY and generating a new date-time for it and insert into output for(std::vector<CWeekDayNum>::const_iterator iter2 = mByDay.begin(); iter2 != mByDay.end(); iter2++) { // Numeric value means specific instance if ((*iter2).first != 0) { CICalendarDateTime temp(*iter1); temp.SetDayOfWeekInYear((*iter2).first, (*iter2).second); output.push_back(temp); } else { // Every matching day in the year for(int32_t i = 1; i < 54; i++) { CICalendarDateTime temp(*iter1); temp.SetDayOfWeekInYear(i, (*iter2).second); if (temp.GetYear() == (*iter1).GetYear()) output.push_back(temp); } } } } dates = output; } void CICalendarRecurrence::ByDayExpandMonthly(CICalendarDateTimeList& dates) const { // Loop over all input items CICalendarDateTimeList output; for(CICalendarDateTimeList::const_iterator iter1 = dates.begin(); iter1 != dates.end(); iter1++) { // Loop over each BYDAY and generating a new date-time for it and insert into output for(std::vector<CWeekDayNum>::const_iterator iter2 = mByDay.begin(); iter2 != mByDay.end(); iter2++) { // Numeric value means specific instance if ((*iter2).first != 0) { CICalendarDateTime temp(*iter1); temp.SetDayOfWeekInMonth((*iter2).first, (*iter2).second); output.push_back(temp); } else { // Every matching day in the month for(int32_t i = 1; i < 6; i++) { CICalendarDateTime temp(*iter1); temp.SetDayOfWeekInMonth(i, (*iter2).second); if (temp.GetMonth() == (*iter1).GetMonth()) output.push_back(temp); } } } } dates = output; } void CICalendarRecurrence::ByDayExpandWeekly(CICalendarDateTimeList& dates) const { // Must take into account the WKST value // Loop over all input items CICalendarDateTimeList output; for(CICalendarDateTimeList::const_iterator iter1 = dates.begin(); iter1 != dates.end(); iter1++) { // Loop over each BYDAY and generating a new date-time for it and insert into output for(std::vector<CWeekDayNum>::const_iterator iter2 = mByDay.begin(); iter2 != mByDay.end(); iter2++) { // Numeric values are meaningless so ignore them if ((*iter2).first == 0) { CICalendarDateTime temp(*iter1); // Determine amount of offset to apply to temp to shift it to the start of the week (backwards) int32_t week_start_offset = mWeekstart - temp.GetDayOfWeek(); if (week_start_offset > 0) week_start_offset -= 7; // Determine amount of offset from the start of the week to the day we want (forwards) int32_t day_in_week_offset = (*iter2).second - mWeekstart; if (day_in_week_offset < 0) day_in_week_offset += 7; // Apply offsets temp.OffsetDay(week_start_offset + day_in_week_offset); output.push_back(temp); } } } dates = output; } void CICalendarRecurrence::ByHourExpand(CICalendarDateTimeList& dates) const { // Loop over all input items CICalendarDateTimeList output; for(CICalendarDateTimeList::const_iterator iter1 = dates.begin(); iter1 != dates.end(); iter1++) { // Loop over each BYHOUR and generating a new date-time for it and insert into output for(std::vector<int32_t>::const_iterator iter2 = mByHours.begin(); iter2 != mByHours.end(); iter2++) { CICalendarDateTime temp(*iter1); temp.SetHours(*iter2); output.push_back(temp); } } dates = output; } void CICalendarRecurrence::ByMinuteExpand(CICalendarDateTimeList& dates) const { // Loop over all input items CICalendarDateTimeList output; for(CICalendarDateTimeList::const_iterator iter1 = dates.begin(); iter1 != dates.end(); iter1++) { // Loop over each BYMINUTE and generating a new date-time for it and insert into output for(std::vector<int32_t>::const_iterator iter2 = mByMinutes.begin(); iter2 != mByMinutes.end(); iter2++) { CICalendarDateTime temp(*iter1); temp.SetMinutes(*iter2); output.push_back(temp); } } dates = output; } void CICalendarRecurrence::BySecondExpand(CICalendarDateTimeList& dates) const { // Loop over all input items CICalendarDateTimeList output; for(CICalendarDateTimeList::const_iterator iter1 = dates.begin(); iter1 != dates.end(); iter1++) { // Loop over each BYSECOND and generating a new date-time for it and insert into output for(std::vector<int32_t>::const_iterator iter2 = mBySeconds.begin(); iter2 != mBySeconds.end(); iter2++) { CICalendarDateTime temp(*iter1); temp.SetSeconds(*iter2); output.push_back(temp); } } dates = output; } #pragma mark ____________________________BYxxx limits void CICalendarRecurrence::ByMonthLimit(CICalendarDateTimeList& dates) const { // Loop over all input items CICalendarDateTimeList output; for(CICalendarDateTimeList::const_iterator iter1 = dates.begin(); iter1 != dates.end(); iter1++) { // Loop over each BYMONTH and indicate keep if input month matches bool keep = false; for(std::vector<int32_t>::const_iterator iter2 = mByMonth.begin(); !keep && (iter2 != mByMonth.end()); iter2++) { keep = ((*iter1).GetMonth() == *iter2); } if (keep) output.push_back(*iter1); } dates = output; } void CICalendarRecurrence::ByWeekNoLimit(CICalendarDateTimeList& dates) const { // Loop over all input items CICalendarDateTimeList output; for(CICalendarDateTimeList::const_iterator iter1 = dates.begin(); iter1 != dates.end(); iter1++) { // Loop over each BYWEEKNO and indicate keep if input month matches bool keep = false; for(std::vector<int32_t>::const_iterator iter2 = mByWeekNo.begin(); !keep && (iter2 != mByWeekNo.end()); iter2++) { keep = (*iter1).IsWeekNo(*iter2); } if (keep) output.push_back(*iter1); } dates = output; } void CICalendarRecurrence::ByMonthDayLimit(CICalendarDateTimeList& dates) const { // Loop over all input items CICalendarDateTimeList output; for(CICalendarDateTimeList::const_iterator iter1 = dates.begin(); iter1 != dates.end(); iter1++) { // Loop over each BYMONTHDAY and indicate keep if input month matches bool keep = false; for(std::vector<int32_t>::const_iterator iter2 = mByMonthDay.begin(); !keep && (iter2 != mByMonthDay.end()); iter2++) { keep = (*iter1).IsMonthDay(*iter2); } if (keep) output.push_back(*iter1); } dates = output; } void CICalendarRecurrence::ByDayLimit(CICalendarDateTimeList& dates) const { // Loop over all input items CICalendarDateTimeList output; for(CICalendarDateTimeList::const_iterator iter1 = dates.begin(); iter1 != dates.end(); iter1++) { // Loop over each BYDAY and indicate keep if input month matches bool keep = false; for(std::vector<CWeekDayNum>::const_iterator iter2 = mByDay.begin(); !keep && (iter2 != mByDay.end()); iter2++) { keep = (*iter1).IsDayOfWeekInMonth((*iter2).first, (*iter2).second); } if (keep) output.push_back(*iter1); } dates = output; } void CICalendarRecurrence::ByHourLimit(CICalendarDateTimeList& dates) const { // Loop over all input items CICalendarDateTimeList output; for(CICalendarDateTimeList::const_iterator iter1 = dates.begin(); iter1 != dates.end(); iter1++) { // Loop over each BYHOUR and indicate keep if input hour matches bool keep = false; for(std::vector<int32_t>::const_iterator iter2 = mByHours.begin(); !keep && (iter2 != mByHours.end()); iter2++) { keep = ((*iter1).GetHours() == *iter2); } if (keep) output.push_back(*iter1); } dates = output; } void CICalendarRecurrence::ByMinuteLimit(CICalendarDateTimeList& dates) const { // Loop over all input items CICalendarDateTimeList output; for(CICalendarDateTimeList::const_iterator iter1 = dates.begin(); iter1 != dates.end(); iter1++) { // Loop over each BYMINUTE and indicate keep if input minute matches bool keep = false; for(std::vector<int32_t>::const_iterator iter2 = mByMinutes.begin(); !keep && (iter2 != mByMinutes.end()); iter2++) { keep = ((*iter1).GetMinutes() == *iter2); } if (keep) output.push_back(*iter1); } dates = output; } void CICalendarRecurrence::BySecondLimit(CICalendarDateTimeList& dates) const { // Loop over all input items CICalendarDateTimeList output; for(CICalendarDateTimeList::const_iterator iter1 = dates.begin(); iter1 != dates.end(); iter1++) { // Loop over each BYSECOND and indicate keep if input second matches bool keep = false; for(std::vector<int32_t>::const_iterator iter2 = mBySeconds.begin(); !keep && (iter2 != mBySeconds.end()); iter2++) { keep = ((*iter1).GetSeconds() == *iter2); } if (keep) output.push_back(*iter1); } dates = output; } void CICalendarRecurrence::BySetPosLimit(CICalendarDateTimeList& dates) const { // The input dates MUST be sorted in order for this to work properly sort(dates.begin(), dates.end()); // Loop over each BYSETPOS and extract the relevant component from the input array and add to the output CICalendarDateTimeList output; size_t input_size = dates.size(); for(std::vector<int32_t>::const_iterator iter = mBySetPos.begin(); iter != mBySetPos.end(); iter++) { if (*iter > 0) { // Positive values are offset from the start if ((*iter) <= input_size) output.push_back(dates[*iter - 1]); } else if (*iter < 0) { // Negative values are offset from the end if (-(*iter) <= input_size) output.push_back(dates[input_size + *iter]); } } dates = output; }
23.885836
141
0.674607
[ "vector" ]
8b215483085aec7f70ba977d91cfefa093ebc0fc
44,278
cpp
C++
src/validator/test/QueryValidatorTest.cpp
xunliu/nebula-graph
74ebed9527153579cd166ead86ebe9cf6b04835e
[ "Apache-2.0" ]
816
2020-08-17T09:51:45.000Z
2022-03-31T11:04:38.000Z
src/validator/test/QueryValidatorTest.cpp
zzl200012/nebula-graph
c08b248c69d7db40c0ba9011d4429083cf539bbd
[ "Apache-2.0" ]
615
2020-08-18T01:26:52.000Z
2022-02-18T08:19:54.000Z
src/validator/test/QueryValidatorTest.cpp
zzl200012/nebula-graph
c08b248c69d7db40c0ba9011d4429083cf539bbd
[ "Apache-2.0" ]
147
2020-08-17T09:40:52.000Z
2022-03-15T06:21:27.000Z
/* Copyright (c) 2020 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License, * attached with Common Clause Condition 1.0, found in the LICENSES directory. */ #include "common/base/Base.h" #include "validator/test/ValidatorTestBase.h" DECLARE_uint32(max_allowed_statements); namespace nebula { namespace graph { class QueryValidatorTest : public ValidatorTestBase { public: }; using PK = nebula::graph::PlanNode::Kind; TEST_F(QueryValidatorTest, TestFirstSentence) { auto testFirstSentence = [](const std::string &msg) -> bool { return msg.find_first_of("SyntaxError: Could not start with the statement") == 0; }; { auto result = checkResult("LIMIT 2, 10"); EXPECT_FALSE(result); EXPECT_TRUE(testFirstSentence(result.message())); } { auto result = checkResult("LIMIT 2, 10 | YIELD 2"); EXPECT_TRUE(testFirstSentence(result.message())); } { auto result = checkResult("LIMIT 2, 10 | YIELD 2 | YIELD 3"); EXPECT_TRUE(testFirstSentence(result.message())); } { auto result = checkResult("ORDER BY 1"); EXPECT_TRUE(testFirstSentence(result.message())); } { auto result = checkResult("GROUP BY 1"); EXPECT_TRUE(testFirstSentence(result.message())); } } TEST_F(QueryValidatorTest, GoZeroStep) { { std::string query = "GO 0 STEPS FROM \"1\" OVER serve"; std::vector<PlanNode::Kind> expected = { PK::kPassThrough, PK::kStart }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO 0 STEPS FROM \"1\" OVER like YIELD like._dst as id" "| GO FROM $-.id OVER serve"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kInnerJoin, PK::kProject, PK::kGetNeighbors, PK::kDedup, PK::kProject, PK::kPassThrough, PK::kStart }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO 0 TO 0 STEPS FROM \"1\" OVER serve"; std::vector<PlanNode::Kind> expected = { PK::kPassThrough, PK::kStart }; EXPECT_TRUE(checkResult(query, expected)); } } TEST_F(QueryValidatorTest, GoNSteps) { { std::string query = "GO 2 STEPS FROM \"1\" OVER like"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kGetNeighbors, PK::kLoop, PK::kStart, PK::kDedup, PK::kProject, PK::kGetNeighbors, PK::kStart }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO 3 STEPS FROM \"1\",\"2\",\"3\" OVER like WHERE like.likeness > 90"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kFilter, PK::kGetNeighbors, PK::kLoop, PK::kStart, PK::kDedup, PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO 3 steps FROM \"1\",\"2\",\"3\" OVER like WHERE $^.person.age > 20" "YIELD distinct $^.person.name"; std::vector<PlanNode::Kind> expected = { PK::kDataCollect, PK::kDedup, PK::kProject, PK::kFilter, PK::kGetNeighbors, PK::kLoop, PK::kStart, PK::kDedup, PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO 2 STEPS FROM \"1\",\"2\",\"3\" OVER like WHERE $^.person.age > 20" "YIELD distinct $^.person.name "; std::vector<PlanNode::Kind> expected = { PK::kDataCollect, PK::kDedup, PK::kProject, PK::kFilter, PK::kGetNeighbors, PK::kLoop, PK::kStart, PK::kDedup, PK::kProject, PK::kGetNeighbors, PK::kStart }; EXPECT_TRUE(checkResult(query, expected)); } } TEST_F(QueryValidatorTest, GoWithPipe) { { std::string query = "GO 1 STEPS FROM \"1\" OVER like YIELD like._dst AS " "id | GO 2 STEPS FROM $-.id OVER like"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kInnerJoin, PK::kInnerJoin, PK::kProject, PK::kGetNeighbors, PK::kLoop, PK::kDedup, PK::kDedup, PK::kProject, PK::kProject, PK::kDedup, PK::kInnerJoin, PK::kProject, PK::kDedup, PK::kProject, PK::kProject, PK::kGetNeighbors, PK::kDedup, PK::kStart, PK::kProject, PK::kGetNeighbors, PK::kStart }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO 2 STEPS FROM \"1\" OVER like YIELD like._dst AS id" "| GO 1 STEPS FROM $-.id OVER like"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kInnerJoin, PK::kProject, PK::kGetNeighbors, PK::kDedup, PK::kProject, PK::kProject, PK::kGetNeighbors, PK::kLoop, PK::kStart, PK::kDedup, PK::kProject, PK::kGetNeighbors, PK::kStart }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "YIELD \"1\" AS id | GO FROM $-.id OVER like"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kInnerJoin, PK::kProject, PK::kGetNeighbors, PK::kDedup, PK::kProject, PK::kProject, PK::kStart }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO 1 STEPS FROM \"1\" OVER like YIELD like._dst AS " "id | GO 1 STEPS FROM $-.id OVER like YIELD $-.id, like._dst"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kInnerJoin, PK::kProject, PK::kGetNeighbors, PK::kDedup, PK::kProject, PK::kProject, PK::kGetNeighbors, PK::kStart }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO 1 STEPS FROM \"1\" OVER like YIELD like._dst AS " "id | GO 1 STEPS FROM $-.id OVER like " "WHERE $-.id == \"2\" YIELD $-.id, like._dst"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kFilter, PK::kInnerJoin, PK::kProject, PK::kGetNeighbors, PK::kDedup, PK::kProject, PK::kProject, PK::kGetNeighbors, PK::kStart }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO 1 STEPS FROM \"1\" OVER like YIELD like._dst AS " "id | GO 1 STEPS FROM $-.id OVER like " "WHERE $-.id == \"2\" YIELD DISTINCT $-.id, like._dst"; std::vector<PlanNode::Kind> expected = { PK::kDataCollect, PK::kDedup, PK::kProject, PK::kFilter, PK::kInnerJoin, PK::kProject, PK::kGetNeighbors, PK::kDedup, PK::kProject, PK::kProject, PK::kGetNeighbors, PK::kStart }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO 1 STEPS FROM \"1\" OVER like YIELD like._dst AS " "id | GO 2 STEPS FROM $-.id OVER like YIELD $-.id, like._dst"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kInnerJoin, PK::kInnerJoin, PK::kProject, PK::kGetNeighbors, PK::kLoop, PK::kDedup, PK::kDedup, PK::kProject, PK::kProject, PK::kDedup, PK::kInnerJoin, PK::kProject, PK::kDedup, PK::kProject, PK::kProject, PK::kGetNeighbors, PK::kDedup, PK::kStart, PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO 1 STEPS FROM \"1\" OVER like YIELD like._dst AS " "id | GO 2 STEPS FROM $-.id OVER like " "WHERE $-.id == \"2\" YIELD $-.id, like._dst"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kFilter, PK::kInnerJoin, PK::kInnerJoin, PK::kProject, PK::kGetNeighbors, PK::kLoop, PK::kDedup, PK::kDedup, PK::kProject, PK::kProject, PK::kDedup, PK::kInnerJoin, PK::kProject, PK::kDedup, PK::kProject, PK::kProject, PK::kGetNeighbors, PK::kDedup, PK::kStart, PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO 1 STEPS FROM \"1\" OVER like YIELD like._dst AS " "id | GO 2 STEPS FROM $-.id OVER like " "WHERE $-.id == \"2\" YIELD DISTINCT $-.id, like._dst"; std::vector<PlanNode::Kind> expected = { PK::kDataCollect, PK::kDedup, PK::kProject, PK::kFilter, PK::kInnerJoin, PK::kInnerJoin, PK::kProject, PK::kGetNeighbors, PK::kLoop, PK::kDedup, PK::kDedup, PK::kProject, PK::kProject, PK::kDedup, PK::kInnerJoin, PK::kProject, PK::kDedup, PK::kProject, PK::kProject, PK::kGetNeighbors, PK::kDedup, PK::kStart, PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO 1 STEPS FROM \"1\" OVER like YIELD like._dst AS " "id, $$.person.name as name | GO 1 STEPS FROM $-.id OVER like " "YIELD $-.name, like.likeness + 1, $-.id, like._dst, " "$$.person.name"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kInnerJoin, PK::kLeftJoin, PK::kProject, PK::kGetVertices, PK::kProject, PK::kGetNeighbors, PK::kDedup, PK::kProject, PK::kProject, PK::kLeftJoin, PK::kProject, PK::kGetVertices, PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO 1 STEPS FROM \"1\" OVER like YIELD like._dst AS " "id, $$.person.name as name | GO 1 STEPS FROM $-.id OVER like " "YIELD DISTINCT $-.name, like.likeness + 1, $-.id, like._dst, " "$$.person.name"; std::vector<PlanNode::Kind> expected = { PK::kDataCollect, PK::kDedup, PK::kProject, PK::kInnerJoin, PK::kLeftJoin, PK::kProject, PK::kGetVertices, PK::kProject, PK::kGetNeighbors, PK::kDedup, PK::kProject, PK::kProject, PK::kLeftJoin, PK::kProject, PK::kGetVertices, PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO FROM \"1\" OVER like " "YIELD $^.person.name AS name, like._dst AS id " "| GO FROM $-.id OVER like " "YIELD $-.name, $^.person.name, $$.person.name"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kInnerJoin, PK::kLeftJoin, PK::kProject, PK::kGetVertices, PK::kProject, PK::kGetNeighbors, PK::kDedup, PK::kProject, PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO 1 STEPS FROM \"1\" OVER like YIELD like._dst AS " "id, $$.person.name as name | GO 2 STEPS FROM $-.id OVER like " "YIELD $-.name, like.likeness + 1, $-.id, like._dst, " "$$.person.name"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kInnerJoin, PK::kInnerJoin, PK::kLeftJoin, PK::kProject, PK::kGetVertices, PK::kProject, PK::kGetNeighbors, PK::kLoop, PK::kDedup, PK::kDedup, PK::kProject, PK::kProject, PK::kDedup, PK::kInnerJoin, PK::kProject, PK::kDedup, PK::kProject, PK::kProject, PK::kLeftJoin, PK::kDedup, PK::kProject, PK::kProject, PK::kGetVertices, PK::kGetNeighbors, PK::kProject, PK::kStart, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO 1 STEPS FROM \"1\" OVER like YIELD like._dst AS " "id, $$.person.name as name | GO 2 STEPS FROM $-.id OVER like " "YIELD DISTINCT $-.name, like.likeness + 1, $-.id, like._dst, " "$$.person.name"; std::vector<PlanNode::Kind> expected = { PK::kDataCollect, PK::kDedup, PK::kProject, PK::kInnerJoin, PK::kInnerJoin, PK::kLeftJoin, PK::kProject, PK::kGetVertices, PK::kProject, PK::kGetNeighbors, PK::kLoop, PK::kDedup, PK::kDedup, PK::kProject, PK::kProject, PK::kDedup, PK::kInnerJoin, PK::kProject, PK::kDedup, PK::kProject, PK::kProject, PK::kLeftJoin, PK::kDedup, PK::kProject, PK::kProject, PK::kGetVertices, PK::kGetNeighbors, PK::kProject, PK::kStart, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO 1 STEPS FROM \"1\" OVER like YIELD like._dst AS " "id | GO 1 STEPS FROM \"1\" OVER like YIELD like._dst"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kGetNeighbors, PK::kProject, PK::kGetNeighbors, PK::kStart }; EXPECT_TRUE(checkResult(query, expected)); } } TEST_F(QueryValidatorTest, GoWithVariable) { { std::string query = "$var = GO FROM \"1\" OVER like " "YIELD $^.person.name AS name, like._dst AS id;" "GO FROM $var.id OVER like " "YIELD $var.name, $^.person.name, $$.person.name"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kInnerJoin, PK::kLeftJoin, PK::kProject, PK::kGetVertices, PK::kProject, PK::kGetNeighbors, PK::kDedup, PK::kProject, PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } } TEST_F(QueryValidatorTest, GoReversely) { { std::string query = "GO FROM \"1\" OVER like REVERSELY " "YIELD $$.person.name"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kLeftJoin, PK::kProject, PK::kGetVertices, PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO 2 STEPS FROM \"1\" OVER like REVERSELY " "YIELD $$.person.name"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kLeftJoin, PK::kProject, PK::kGetVertices, PK::kProject, PK::kGetNeighbors, PK::kLoop, PK::kStart, PK::kDedup, PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } } TEST_F(QueryValidatorTest, GoBidirectly) { { std::string query = "GO FROM \"1\" OVER like BIDIRECT"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO FROM \"1\" OVER like BIDIRECT " "YIELD $$.person.name"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kLeftJoin, PK::kProject, PK::kGetVertices, PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } } TEST_F(QueryValidatorTest, GoOneStep) { { std::string query = "GO FROM \"1\" OVER like"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO FROM \"1\" OVER like REVERSELY"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO FROM \"1\" OVER like BIDIRECT"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO FROM \"1\" OVER like YIELD like.start"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO FROM \"1\" OVER like " "YIELD $^.person.name,$^.person.age"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO FROM \"1\" OVER like " "YIELD $$.person.name,$$.person.age"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kLeftJoin, PK::kProject, PK::kGetVertices, PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO FROM \"1\" OVER like " "YIELD $^.person.name, like._dst, " "$$.person.name, $$.person.age + 1"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kLeftJoin, PK::kProject, PK::kGetVertices, PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO FROM \"1\" OVER like " "WHERE like._dst == \"2\"" "YIELD $^.person.name, like._dst, " "$$.person.name, $$.person.age + 1"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kFilter, PK::kLeftJoin, PK::kProject, PK::kGetVertices, PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO FROM \"1\" OVER like " "WHERE like._dst == \"2\"" "YIELD DISTINCT $^.person.name, like._dst, " "$$.person.name, $$.person.age + 1"; std::vector<PlanNode::Kind> expected = { PK::kDataCollect, PK::kDedup, PK::kProject, PK::kFilter, PK::kLeftJoin, PK::kProject, PK::kGetVertices, PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO FROM \"1\",\"2\",\"3\" OVER like"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO FROM \"1\",\"2\",\"3\" OVER like WHERE like.likeness > 90"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kFilter, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO FROM \"1\",\"2\",\"3\" OVER like WHERE $^.person.age > 20" "YIELD distinct $^.person.name "; std::vector<PlanNode::Kind> expected = { PK::kDataCollect, PK::kDedup, PK::kProject, PK::kFilter, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO FROM \"1\",\"2\",\"3\" OVER like WHERE $^.person.name == \"me\""; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kFilter, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO FROM \"1\" OVER like YIELD like._dst AS id" "| GO FROM $-.id OVER like"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kInnerJoin, PK::kProject, PK::kGetNeighbors, PK::kDedup, PK::kProject, PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } } TEST_F(QueryValidatorTest, GoOverAll) { { std::string query = "GO FROM \"1\" OVER * REVERSELY " "YIELD serve._src, like._src"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO FROM \"1\" OVER * REVERSELY"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO FROM \"1\" OVER *"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO FROM \"1\" OVER * YIELD $$.person.name"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kLeftJoin, PK::kProject, PK::kGetVertices, PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } } TEST_F(QueryValidatorTest, OutputToAPipe) { { std::string query = "GO FROM '1' OVER like YIELD like._dst as id " "| ( GO FROM $-.id OVER like YIELD like._dst as id | GO FROM $-.id OVER serve )"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kInnerJoin, PK::kProject, PK::kGetNeighbors, PK::kDedup, PK::kProject, PK::kProject, PK::kInnerJoin, PK::kProject, PK::kGetNeighbors, PK::kDedup, PK::kProject, PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } } TEST_F(QueryValidatorTest, GoMToN) { { std::string query = "GO 1 TO 2 STEPS FROM '1' OVER like YIELD DISTINCT like._dst"; std::vector<PlanNode::Kind> expected = { PK::kDataCollect, PK::kLoop, PK::kStart, PK::kDedup, PK::kProject, PK::kDedup, PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO 0 TO 2 STEPS FROM '1' OVER like YIELD DISTINCT like._dst"; std::vector<PlanNode::Kind> expected = { PK::kDataCollect, PK::kLoop, PK::kStart, PK::kDedup, PK::kProject, PK::kDedup, PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO 1 TO 2 STEPS FROM '1' OVER like " "YIELD DISTINCT like._dst, like.likeness, $$.person.name"; std::vector<PlanNode::Kind> expected = { PK::kDataCollect, PK::kLoop, PK::kStart, PK::kDedup, PK::kProject, PK::kLeftJoin, PK::kProject, PK::kGetVertices, PK::kProject, PK::kDedup, PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO 1 TO 2 STEPS FROM '1' OVER like REVERSELY YIELD DISTINCT like._dst"; std::vector<PlanNode::Kind> expected = { PK::kDataCollect, PK::kLoop, PK::kStart, PK::kDedup, PK::kProject, PK::kDedup, PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO 1 TO 2 STEPS FROM '1' OVER like BIDIRECT YIELD DISTINCT like._dst"; std::vector<PlanNode::Kind> expected = { PK::kDataCollect, PK::kLoop, PK::kStart, PK::kDedup, PK::kProject, PK::kDedup, PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO 1 TO 2 STEPS FROM '1' OVER * YIELD serve._dst, like._dst"; std::vector<PlanNode::Kind> expected = { PK::kDataCollect, PK::kLoop, PK::kStart, PK::kProject, PK::kDedup, PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO 1 TO 2 STEPS FROM '1' OVER * " "YIELD serve._dst, like._dst, serve.start, like.likeness, $$.person.name"; std::vector<PlanNode::Kind> expected = { PK::kDataCollect, PK::kLoop, PK::kStart, PK::kProject, PK::kLeftJoin, PK::kProject, PK::kGetVertices, PK::kProject, PK::kDedup, PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "GO FROM 'Tim Duncan' OVER like YIELD like._src as src, like._dst as dst " "| GO 1 TO 2 STEPS FROM $-.src OVER like YIELD $-.src as src, like._dst as dst"; std::vector<PlanNode::Kind> expected = { PK::kDataCollect, PK::kLoop, PK::kDedup, PK::kProject, PK::kProject, PK::kInnerJoin, PK::kDedup, PK::kInnerJoin, PK::kProject, PK::kProject, PK::kProject, PK::kDedup, PK::kGetNeighbors, PK::kProject, PK::kStart, PK::kInnerJoin, PK::kDedup, PK::kProject, PK::kDedup, PK::kProject, PK::kGetNeighbors, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } } TEST_F(QueryValidatorTest, GoInvalid) { { // friend not exist. std::string query = "GO FROM \"1\" OVER friend"; EXPECT_FALSE(checkResult(query)); } { // manager not exist std::string query = "GO FROM \"1\" OVER like " "YIELD $^.manager.name,$^.person.age"; EXPECT_FALSE(checkResult(query)); } { // manager not exist std::string query = "GO FROM \"1\" OVER like " "YIELD $$.manager.name,$$.person.age"; EXPECT_FALSE(checkResult(query)); } { // column not exist std::string query = "GO FROM \"1\" OVER like YIELD like._dst AS id" "| GO FROM $-.col OVER like"; EXPECT_FALSE(checkResult(query)); } { // invalid id type std::string query = "GO FROM \"1\" OVER like YIELD like.likeness AS id" "| GO FROM $-.id OVER like"; EXPECT_FALSE(checkResult(query)); } { // multi inputs std::string query = "$var = GO FROM \"2\" OVER like;" "GO FROM \"1\" OVER like YIELD like._dst AS id" "| GO FROM $-.id OVER like WHERE $var.id == \"\""; EXPECT_FALSE(checkResult(query)); } { // yield agg without groupBy is not supported std::string query = "GO FROM \"2\" OVER like YIELD COUNT(123);"; auto result = checkResult(query); EXPECT_EQ(std::string(result.message()), "SemanticError: `COUNT(123)', " "not support aggregate function in go sentence."); } { std::string query = "GO FROM \"1\" OVER like YIELD like._dst AS id, like._src AS id | GO " "FROM $-.id OVER like"; auto result = checkResult(query); EXPECT_EQ(std::string(result.message()), "SemanticError: Duplicate Column Name : `id'"); } { std::string query = "$a = GO FROM \"1\" OVER like YIELD like._dst AS id, like._src AS id; " "GO FROM $a.id OVER like"; auto result = checkResult(query); EXPECT_EQ(std::string(result.message()), "SemanticError: Duplicate Column Name : `id'"); } { std::string query = "GO FROM \"1\" OVER like, serve YIELD like._dst AS id, serve._src AS " "id, serve._dst AS DST | GO FROM $-.DST OVER like"; auto result = checkResult(query); EXPECT_EQ(std::string(result.message()), "SemanticError: Duplicate Column Name : `id'"); } { std::string query = "$a = GO FROM \"1\" OVER * YIELD like._dst AS id, like._src AS id, serve._dst as DST; " "GO FROM $a.DST OVER like"; auto result = checkResult(query); EXPECT_EQ(std::string(result.message()), "SemanticError: Duplicate Column Name : `id'"); } } TEST_F(QueryValidatorTest, Limit) { // Syntax error { std::string query = "GO FROM \"Ann\" OVER like YIELD like._dst AS like | LIMIT -1, 3"; EXPECT_FALSE(checkResult(query)); } { std::string query = "GO FROM \"Ann\" OVER like YIELD like._dst AS like | LIMIT 1, 3"; std::vector<PlanNode::Kind> expected = { PK::kDataCollect, PK::kLimit, PK::kProject, PK::kGetNeighbors, PK::kStart }; EXPECT_TRUE(checkResult(query, expected)); } } TEST_F(QueryValidatorTest, OrderBy) { { std::string query = "GO FROM \"Ann\" OVER like YIELD $^.person.age AS age" " | ORDER BY $-.age"; std::vector<PlanNode::Kind> expected = { PK::kDataCollect, PK::kSort, PK::kProject, PK::kGetNeighbors, PK::kStart }; EXPECT_TRUE(checkResult(query, expected)); } // not exist factor { std::string query = "GO FROM \"Ann\" OVER like YIELD $^.person.age AS age" " | ORDER BY $-.name"; EXPECT_FALSE(checkResult(query)); } } TEST_F(QueryValidatorTest, OrderByAndLimt) { { std::string query = "GO FROM \"Ann\" OVER like YIELD $^.person.age AS age" " | ORDER BY $-.age | LIMIT 1"; std::vector<PlanNode::Kind> expected = { PK::kDataCollect, PK::kLimit, PK::kSort, PK::kProject, PK::kGetNeighbors, PK::kStart }; EXPECT_TRUE(checkResult(query, expected)); } } TEST_F(QueryValidatorTest, TestSetValidator) { // UNION ALL { std::string query = "GO FROM \"1\" OVER like YIELD like.start AS start UNION ALL GO FROM \"2\" " "OVER like YIELD like.start AS start"; std::vector<PlanNode::Kind> expected = { PK::kDataCollect, PK::kUnion, PK::kProject, PK::kProject, PK::kGetNeighbors, PK::kGetNeighbors, PK::kPassThrough, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } // UNION DISTINCT twice { std::string query = "GO FROM \"1\" OVER like YIELD like.start AS start UNION GO FROM \"2\" " "OVER like YIELD like.start AS start UNION GO FROM \"3\" OVER like YIELD " "like.start AS start"; std::vector<PlanNode::Kind> expected = { PK::kDataCollect, PK::kDedup, PK::kUnion, PK::kDedup, PK::kProject, PK::kUnion, PK::kGetNeighbors, PK::kProject, PK::kProject, PK::kPassThrough, PK::kGetNeighbors, PK::kGetNeighbors, PK::kStart, PK::kPassThrough, }; EXPECT_TRUE(checkResult(query, expected)); } // UNION DISTINCT { std::string query = "GO FROM \"1\" OVER like YIELD like.start AS start UNION DISTINCT GO FROM \"2\" " "OVER like YIELD like.start AS start"; std::vector<PlanNode::Kind> expected = { PK::kDataCollect, PK::kDedup, PK::kUnion, PK::kProject, PK::kProject, PK::kGetNeighbors, PK::kGetNeighbors, PK::kPassThrough, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } // INVALID UNION ALL { std::string query = "GO FROM \"1\" OVER like YIELD like.start AS start, $^.person.name AS " "name UNION GO FROM \"2\" OVER like YIELD like.start AS start"; EXPECT_FALSE(checkResult(query)); } // INTERSECT { std::string query = "GO FROM \"1\" OVER like YIELD like.start AS start INTERSECT GO FROM " "\"2\" OVER like YIELD like.start AS start"; std::vector<PlanNode::Kind> expected = { PK::kDataCollect, PK::kIntersect, PK::kProject, PK::kProject, PK::kGetNeighbors, PK::kGetNeighbors, PK::kPassThrough, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } // MINUS { std::string query = "GO FROM \"1\" OVER like YIELD like.start AS start MINUS GO FROM " "\"2\" OVER like YIELD like.start AS start"; std::vector<PlanNode::Kind> expected = { PK::kDataCollect, PK::kMinus, PK::kProject, PK::kProject, PK::kGetNeighbors, PK::kGetNeighbors, PK::kPassThrough, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } } TEST_F(QueryValidatorTest, TestMaxAllowedStatements) { std::vector<std::string> stmts; for (uint32_t i = 0; i < FLAGS_max_allowed_statements; i++) { stmts.emplace_back(folly::stringPrintf("CREATE TAG tag_%d(name string)", i)); } auto query = folly::join(";", stmts); EXPECT_TRUE(checkResult(query)); stmts.emplace_back( folly::stringPrintf("CREATE TAG tag_%d(name string)", FLAGS_max_allowed_statements)); query = folly::join(";", stmts); auto result = checkResult(query); EXPECT_FALSE(result); EXPECT_EQ(std::string(result.message()), "SemanticError: The maximum number of statements allowed has been exceeded"); } TEST_F(QueryValidatorTest, TestMatch) { { std::string query = "MATCH (v1:person{name: \"LeBron James\"}) -[r]-> (v2) " "RETURN type(r) AS Type, v2.name AS Name"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kFilter, PK::kProject, PK::kInnerJoin, PK::kProject, PK::kGetVertices, PK::kDedup, PK::kProject, PK::kFilter, PK::kProject, PK::kFilter, PK::kGetNeighbors, PK::kDedup, PK::kProject, PK::kIndexScan, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "MATCH (:person{name:'Dwyane Wade'}) -[:like]-> () -[:like]-> (v3) " "RETURN DISTINCT v3.name AS Name"; std::vector<PlanNode::Kind> expected = { PK::kDataCollect, PK::kDedup, PK::kProject, PK::kFilter, PK::kProject, PK::kInnerJoin, PK::kProject, PK::kGetVertices, PK::kDedup, PK::kProject, PK::kInnerJoin, PK::kFilter, PK::kProject, PK::kGetNeighbors, PK::kDedup, PK::kProject, PK::kFilter, PK::kProject, PK::kFilter, PK::kGetNeighbors, PK::kDedup, PK::kProject, PK::kIndexScan, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "MATCH (v1) -[r]-> (v2) " "WHERE id(v1) == \"LeBron James\"" "RETURN type(r) AS Type, v2.name AS Name"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kFilter, PK::kFilter, PK::kProject, PK::kInnerJoin, PK::kProject, PK::kGetVertices, PK::kDedup, PK::kProject, PK::kFilter, PK::kProject, PK::kGetNeighbors, PK::kDedup, PK::kProject, PK::kPassThrough, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "MATCH (v1)-[e:serve*2..3{start_year: 2000}]-(v2) " "WHERE id(v1) == \"LeBron James\"" "RETURN v1, v2"; std::vector<PlanNode::Kind> expected = {PK::kProject, PK::kFilter, PK::kFilter, PK::kProject, PK::kInnerJoin, PK::kProject, PK::kGetVertices, PK::kDedup, PK::kProject, PK::kFilter, PK::kUnionAllVersionVar, PK::kLoop, PK::kProject, PK::kFilter, PK::kFilter, PK::kProject, PK::kGetNeighbors, PK::kInnerJoin, PK::kDedup, PK::kProject, PK::kProject, PK::kFilter, PK::kPassThrough, PK::kGetNeighbors, PK::kStart, PK::kDedup, PK::kProject, PK::kStart}; EXPECT_TRUE(checkResult(query, expected)); } { std::string query = "MATCH p = (n)-[]-(m:person{name:\"LeBron James\"}) RETURN p"; std::vector<PlanNode::Kind> expected = { PK::kProject, PK::kFilter, PK::kProject, PK::kInnerJoin, PK::kProject, PK::kGetVertices, PK::kDedup, PK::kProject, PK::kFilter, PK::kProject, PK::kFilter, PK::kGetNeighbors, PK::kDedup, PK::kProject, PK::kIndexScan, PK::kStart, }; EXPECT_TRUE(checkResult(query, expected)); } } } // namespace graph } // namespace nebula
32.039074
99
0.462013
[ "vector" ]
8b223a6e43387c56ba3efc67e53985babe530909
5,921
cpp
C++
Code/Framework/AzCore/AzCore/Math/Obb.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
8
2021-08-31T02:14:19.000Z
2021-12-28T19:20:59.000Z
Code/Framework/AzCore/AzCore/Math/Obb.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
8
2021-07-12T13:55:00.000Z
2021-10-04T14:53:21.000Z
Code/Framework/AzCore/AzCore/Math/Obb.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
1
2021-07-09T06:02:14.000Z
2021-07-09T06:02:14.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <AzCore/Math/Obb.h> #include <AzCore/Math/Aabb.h> #include <AzCore/Math/Transform.h> #include <AzCore/Math/MathScriptHelpers.h> namespace AZ { namespace Internal { Obb ConstructObbFromValues ( float posX, float posY, float posZ , float axisXX, float axisXY, float axisXZ, float halfX , float axisYX, float axisYY, float axisYZ, float halfY , float axisZX, float axisZY, float axisZZ, float halfZ) { const Vector3 position(posX, posY, posZ); const Quaternion rotation = Quaternion::CreateFromMatrix3x3(Matrix3x3::CreateFromColumns( Vector3(axisXX, axisXY, axisXZ), Vector3(axisYX, axisYY, axisYZ), Vector3(axisZX, axisZY, axisZZ))); const Vector3 halfLengths(halfX, halfY, halfZ); return Obb::CreateFromPositionRotationAndHalfLengths(position, rotation, halfLengths); } void ObbDefaultConstructor(Obb* thisPtr) { new (thisPtr) Obb(Obb::CreateFromPositionRotationAndHalfLengths( Vector3::CreateZero(), Quaternion::CreateIdentity(), Vector3(0.5f))); } AZStd::string ObbToString(const Obb& obb) { return AZStd::string::format("Position %s AxisX %s AxisY %s AxisZ %s halfLengthX=%.7f halfLengthY=%.7f halfLengthZ=%.7f", Vector3ToString(obb.GetPosition()).c_str(), Vector3ToString(obb.GetAxisX()).c_str(), Vector3ToString(obb.GetAxisY()).c_str(), Vector3ToString(obb.GetAxisZ()).c_str(), obb.GetHalfLengthX(), obb.GetHalfLengthY(), obb.GetHalfLengthZ()); } } void Obb::Reflect(ReflectContext* context) { auto serializeContext = azrtti_cast<SerializeContext*>(context); if (serializeContext) { serializeContext->Class<Obb>() ->Field("position", &Obb::m_position) ->Field("rotation", &Obb::m_rotation) ->Field("halfLengths", &Obb::m_halfLengths) ; } auto behaviorContext = azrtti_cast<BehaviorContext*>(context); if (behaviorContext) { behaviorContext->Class<Obb>()-> Attribute(Script::Attributes::ExcludeFrom, Script::Attributes::ExcludeFlags::All)-> Attribute(Script::Attributes::Storage, Script::Attributes::StorageType::Value)-> Attribute(Script::Attributes::GenericConstructorOverride, &Internal::ObbDefaultConstructor)-> Property("position", &Obb::GetPosition, &Obb::SetPosition)-> Property("rotation", &Obb::GetRotation, &Obb::SetRotation)-> Property("halfLengths", &Obb::GetHalfLengths, &Obb::SetHalfLengths)-> Method("ToString", &Internal::ObbToString)-> Attribute(Script::Attributes::Operator, Script::Attributes::OperatorType::ToString)-> Method("CreateFromPositionRotationAndHalfLengths", &Obb::CreateFromPositionRotationAndHalfLengths)-> Method("CreateFromAabb", &Obb::CreateFromAabb)-> Method("ConstructObbFromValues", &Internal::ConstructObbFromValues)-> Method("GetAxis", &Obb::GetAxis)-> Method("GetAxisX", &Obb::GetAxisX)-> Method("GetAxisY", &Obb::GetAxisY)-> Method("GetAxisZ", &Obb::GetAxisZ)-> Method("GetHalfLength", &Obb::GetHalfLength)-> Method("GetHalfLengthX", &Obb::GetHalfLengthX)-> Method("GetHalfLengthY", &Obb::GetHalfLengthY)-> Method("GetHalfLengthZ", &Obb::GetHalfLengthZ)-> Method("SetHalfLength", &Obb::SetHalfLength)-> Method("SetHalfLengthX", &Obb::SetHalfLengthX)-> Method("SetHalfLengthY", &Obb::SetHalfLengthY)-> Method("SetHalfLengthZ", &Obb::SetHalfLengthZ)-> Method("Clone", [](const Obb& rhs) -> Obb { return rhs; })-> Method("IsFinite", &Obb::IsFinite)-> Method("Equal", &Obb::operator==)-> Attribute(Script::Attributes::Operator, Script::Attributes::OperatorType::Equal); } } Obb Obb::CreateFromPositionRotationAndHalfLengths( const Vector3& position, const Quaternion& rotation, const Vector3& halfLengths) { Obb result; result.m_position = position; result.m_rotation = rotation; result.m_halfLengths = halfLengths; return result; } Obb Obb::CreateFromAabb(const Aabb& aabb) { return CreateFromPositionRotationAndHalfLengths( aabb.GetCenter(), Quaternion::CreateIdentity(), 0.5f * aabb.GetExtents() ); } bool Obb::IsFinite() const { return m_position.IsFinite() && m_rotation.IsFinite() && m_halfLengths.IsFinite(); } bool Obb::operator==(const Obb& rhs) const { return m_position.IsClose(rhs.m_position) && m_rotation.IsClose(rhs.m_rotation) && m_halfLengths.IsClose(rhs.m_halfLengths); } bool Obb::operator!=(const Obb& rhs) const { return !(*this == rhs); } Obb operator*(const Transform& transform, const Obb& obb) { return Obb::CreateFromPositionRotationAndHalfLengths( transform.TransformPoint(obb.GetPosition()), transform.GetRotation() * obb.GetRotation(), transform.GetUniformScale() * obb.GetHalfLengths() ); } }
37.713376
133
0.592467
[ "transform", "3d" ]
8b2bd29ede47a528481a487c08fda9ce110b8bc1
1,226
cpp
C++
examples/google-code-jam/bloops/cookie.cpp
rbenic-fer/progauthfp
d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675
[ "MIT" ]
null
null
null
examples/google-code-jam/bloops/cookie.cpp
rbenic-fer/progauthfp
d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675
[ "MIT" ]
null
null
null
examples/google-code-jam/bloops/cookie.cpp
rbenic-fer/progauthfp
d0fd96c31ab0aab1a9acdcb7c75f2b430f51c675
[ "MIT" ]
null
null
null
#include <iostream> #include <sstream> #include <algorithm> #include <iomanip> #include <vector> #include <string> #include <set> #include <queue> #include <stack> #include <map> #include <cstdio> #include <cstring> #include <cassert> #include <cmath> #include <fstream> using namespace std; #define REP(i, n) for(int i=0;i<int(n);i++) #define FOR(i, n) for(int i=1;i<=int(n);i++) #define FORE(it, c) for(typeof(c.begin()) it = c.begin(); it != c.end(); it++) #define all(c) c.begin(), c.end() #define clear(c,v) memset(c,v,sizeof(c)) typedef long long int lli; typedef pair<int,int> ii; long double eps = 1e-15; int main() { int T; cin >> T; REP(q, T){ long double c, f, x; cin >> c >> f >> x; long double step = 0.5 * c, best = 0.5 * x, time = 0.0; int maxfarms = (int) ((x + eps)/ c); long double rate; for(int farms = 0; farms <= maxfarms; farms ++){ rate = 2.0 + (farms * f); best = min(best, time + (x / rate)); // add time to get to buy next farm time += c / rate; } cout << "Case #" << q + 1 << ": "; cout << setprecision(12) << fixed << best << endl; } }
17.267606
78
0.530995
[ "vector" ]