hexsha
stringlengths
40
40
size
int64
22
2.4M
ext
stringclasses
5 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
260
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
78
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
260
max_issues_repo_name
stringlengths
5
109
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
260
max_forks_repo_name
stringlengths
5
109
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
22
2.4M
avg_line_length
float64
5
169k
max_line_length
int64
5
786k
alphanum_fraction
float64
0.06
0.95
matches
listlengths
1
11
fc272b8a67756dbed370d15cb49c8aa6f9d47870
974
h
C
gui/src/wrappers/dialoguserviewwrapper.h
sqglobe/SecureDialogues
bde56c7a62fb72b1cdfba8cebc0a770157b5f751
[ "MIT" ]
3
2019-07-05T12:01:36.000Z
2021-03-19T22:48:48.000Z
gui/src/wrappers/dialoguserviewwrapper.h
sqglobe/SecureDialogues
bde56c7a62fb72b1cdfba8cebc0a770157b5f751
[ "MIT" ]
41
2019-11-26T18:59:54.000Z
2020-05-01T10:52:47.000Z
gui/src/wrappers/dialoguserviewwrapper.h
sqglobe/SecureDialogues
bde56c7a62fb72b1cdfba8cebc0a770157b5f751
[ "MIT" ]
3
2019-05-21T17:48:16.000Z
2021-03-19T22:48:49.000Z
#ifndef DIALOGUSERVIEWWRAPPER_H #define DIALOGUSERVIEWWRAPPER_H #include <QObject> #include <memory> #include <QPoint> #include <QSortFilterProxyModel> #include "primitives/dialog.h" class QListView; class DialogUserModel; /** * @brief Извлекает из модели диалог и передает его в DialogActionMenu */ class DialogUserViewWrapper : public QObject { Q_OBJECT public: explicit DialogUserViewWrapper(QListView* view, std::shared_ptr<DialogUserModel> model, QObject* parent = nullptr); signals: void showMenuForDialog(QPoint pos, Dialog::Status status, std::string dialogId); public slots: void requestToShowMenu(QPoint pos); void requestToActivateItem(const QModelIndex& index); private: QListView* mView; std::unique_ptr<QSortFilterProxyModel> mProxy; std::shared_ptr<DialogUserModel> mModel; }; #endif // DIALOGUSERVIEWWRAPPER_H
23.756098
72
0.688912
[ "model" ]
fc28fb9f666e14c403330032e7b291f754da0963
2,384
h
C
games/xworld3d/glsl/nv_math_glsltypes.h
ziyuli/XWorld
97db71daf1b82a179a5c3a85b58c46c9debbc247
[ "Apache-2.0" ]
83
2017-08-22T20:13:58.000Z
2022-02-14T01:39:00.000Z
games/xworld3d/glsl/nv_math_glsltypes.h
ziyuli/XWorld
97db71daf1b82a179a5c3a85b58c46c9debbc247
[ "Apache-2.0" ]
15
2017-08-24T00:07:29.000Z
2019-04-25T15:24:53.000Z
games/xworld3d/glsl/nv_math_glsltypes.h
ziyuli/XWorld
97db71daf1b82a179a5c3a85b58c46c9debbc247
[ "Apache-2.0" ]
30
2017-08-23T23:19:12.000Z
2022-02-14T01:43:07.000Z
// Copyright (c) 2012 NVIDIA Corporation. All rights reserved. // // TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED // *AS IS* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS // OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, NONINFRINGEMENT,IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA // OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, SPECIAL, INCIDENTAL, INDIRECT, OR // CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS // OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY // OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, // EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. // // Please direct any bugs or questions to SDKFeedback@nvidia.com #ifndef NV_SHADER_TYPES_H #define NV_SHADER_TYPES_H #include "NvFoundation.h" #include "nv_math_types.h" namespace nv_math { #if defined(__amd64__) || defined(__x86_64__) || defined(_M_X64) || defined(__AMD64__) // Matrices, must align to 4 vector (16 bytes) NV_ALIGN(16, typedef mat4f mat4); // vectors, 4-tuples and 3-tuples must align to 16 bytes // 2-vectors must align to 8 bytes NV_ALIGN(16, typedef vec4f vec4 ); NV_ALIGN(16, typedef vec3f vec3 ); NV_ALIGN(8 , typedef vec2f vec2 ); NV_ALIGN(16, typedef vec4i ivec4 ); NV_ALIGN(16, typedef vec3i ivec3 ); NV_ALIGN(8 , typedef vec2i ivec2 ); NV_ALIGN(16, typedef vec4ui uvec4 ); NV_ALIGN(16, typedef vec3ui uvec3 ); NV_ALIGN(8, typedef vec2ui uvec2 ); #else // Matrices, must align to 4 vector (16 bytes) typedef mat4f mat4; // vectors, 4-tuples and 3-tuples must align to 16 bytes // 2-vectors must align to 8 bytes typedef vec4f vec4; typedef vec3f vec3; typedef vec2f vec2; typedef vec4i ivec4; typedef vec3i ivec3; typedef vec2i ivec2; typedef vec4ui uvec4; typedef vec3ui uvec3; typedef vec2ui uvec2; #endif //class to make uint look like bool to make GLSL packing rules happy struct boolClass { unsigned int _rep; boolClass() : _rep(false) {} boolClass( bool b) : _rep(b) {} operator bool() { return _rep == 0 ? false : true; } boolClass& operator=( bool b) { _rep = b; return *this; } }; //NVP_ALIGN_V(4, typedef boolClass bool32); } #endif
31.786667
88
0.720638
[ "vector" ]
fc2e6490de889f29834d0e9efa825be7f110494a
8,709
h
C
include/data_loaders/fb/DataLoaderUSCHair.h
RaduAlexandru/data_loaders
243ea275d55d34b89992965ed666f0a7f2dea250
[ "MIT" ]
7
2020-03-17T13:18:49.000Z
2022-03-03T17:34:16.000Z
include/data_loaders/fb/DataLoaderUSCHair.h
RaduAlexandru/data_loaders
243ea275d55d34b89992965ed666f0a7f2dea250
[ "MIT" ]
null
null
null
include/data_loaders/fb/DataLoaderUSCHair.h
RaduAlexandru/data_loaders
243ea275d55d34b89992965ed666f0a7f2dea250
[ "MIT" ]
1
2021-09-22T12:10:06.000Z
2021-09-22T12:10:06.000Z
#include <thread> #include <unordered_map> #include <vector> #include <memory> //ros // #include <ros/ros.h> // #include <sensor_msgs/PointCloud2.h> // #include <pcl_ros/point_cloud.h> //eigen #include <Eigen/Core> #include <Eigen/Geometry> #include <Eigen/StdVector> //readerwriterqueue #include "readerwriterqueue/readerwriterqueue.h" #include "torch/torch.h" //boost #include <boost/bind.hpp> #include <boost/filesystem.hpp> namespace fs = boost::filesystem; namespace radu { namespace utils{ class RandGenerator; }} namespace easy_pbr{ class LabelMngr; class Mesh; } class DataTransformer; // Struct to contain everything we need for one hair sample class USCHair : public std::enable_shared_from_this<USCHair> { public: std::shared_ptr<easy_pbr::Mesh> full_hair_cloud; //cloud containing the points of the hair std::vector< std::shared_ptr<easy_pbr::Mesh> > strand_meshes; //vector containing a mesh for each strand // Eigen::MatrixXd points; //Nx3 points of the hair // Eigen::MatrixXi per_point_strand_idx; //Nx1 index of strand for each point. Points that belong to the same strand will have the same idx Eigen::MatrixXd uv_roots; // nr_strands x 2 uv for only the points on the roots torch::Tensor tbn_roots_tensor; //nr_strands x 3 x 3 tanent-bitangent-normal for the root points Eigen::MatrixXd position_roots; //nr_strands x 3 positions of the roots in world coords // Eigen::MatrixXd strand_lengths; //nr_strands x 1 strand lengths // Eigen::MatrixXd per_strand_R_rodri_canonical_scalp; //nr_strands x3 rotations in rodrigues format that maps from sclap coordinates to some canonical space that makes learning easier. Applied only after normalizing the strands by the strand_lengths. // Eigen::MatrixXd per_strand_dir_along; //nr_strand x3 directions of the strand after the points were transformed in scalp coords // Eigen::MatrixXd full_hair_cumulative_strand_length; //Nx 1 for each point on the hair store the cumulative lenght along it's corresponding strand // torch::Tensor per_point_rotation_next_cur_tensor; // nr_strands X nr_points_per_strand x 3 of rodrigues towards the next point. Expressed in the local coordinate system of the current point // torch::Tensor per_point_delta_dist_tensor; // nr_strands X nr_points_per_strand x 1 of delta movement applied to the average segment lenght. This is applied to the per_point_rotation_next_cur torch::Tensor per_point_direction_to_next_tensor; // nr_strands X nr_points_per_strand x 3 direction in world coordinates from one point to the next one on the same strand. The last point on the strand since it has no direction to the next, just repeats the direction from the previous //rotation from the canonical space which is z align to anothe canonical space which is x aligned // Eigen::MatrixXd per_strand_R_rodri_across_canonical; //nr_strands x3 // Eigen::MatrixXd per_strand_across_canonical_weight; //nr strands x1 // Eigen::MatrixXd per_strand_dir_across; //nr_strand x3 irections across the strand after the points were transformed in canonical coords } ; class DataLoaderUSCHair { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW DataLoaderUSCHair(const std::string config_file); ~DataLoaderUSCHair(); void start(); //starts the thread that reads the data from disk. This gets called automatically if we have autostart=true // std::shared_ptr<easy_pbr::Mesh> get_cloud(); std::shared_ptr<USCHair> get_hair(); //return the whole usc struct of hair std::shared_ptr<easy_pbr::Mesh> get_mesh_head(); std::shared_ptr<easy_pbr::Mesh> get_mesh_scalp(); bool has_data(); bool is_finished(); //returns true when we have finished reading AND processing everything bool is_finished_reading(); //returns true when we have finished reading everything but maybe not processing void reset(); //starts reading from the beggining int nr_samples(); //returns the number of samples/examples that this loader will iterate over void set_mode_train(); //set the loader so that it starts reading form the training set void set_mode_test(); void set_mode_validation(); std::shared_ptr<USCHair> get_random_roots(const int nr_strands); //create random roots and return their position, uv and tbn private: void init_params(const std::string config_file); void init_data_reading(); //after the parameters this uses the params to initiate all the structures needed for the susequent read_data std::vector<Eigen::Affine3d, Eigen::aligned_allocator<Eigen::Affine3d> >read_pose_file(std::string m_pose_file); void read_data(); // std::tuple< // std::vector< std::shared_ptr<easy_pbr::Mesh> >, // std::shared_ptr<easy_pbr::Mesh> // > read_hair_sample(const std::string data_filepath); //returns a full hair mesha and also a vector of meshes corresponding with the strands std::shared_ptr<USCHair> read_hair_sample(const std::string data_filepath); //returns a full hair mesha and also a vector of meshes corresponding with the strands void compute_root_points_atributes(Eigen::MatrixXd& uv, std::vector<Eigen::Matrix3d>& tbn_per_point, std::shared_ptr<easy_pbr::Mesh> mesh, std::vector<Eigen::Vector3d> points_vec); //project the points onto the closest point on the mesh and get the uv from there void compute_full_hair(std::shared_ptr<USCHair>& usc_hair); void compute_all_atributes(std::shared_ptr<USCHair>& usc_hair); //compute a local representation of the strands // strands_xyz : tensor of nr_strands x nr_points_per_strand x 3 of coordinates in world coordinates // strands_lengths: tensor of nr_strands x 1 // tbn_roots nr_strands x 3 x 3 #Tangent-bitangent-normal for each point at the root of the strand in world coordinates // OUTPUT: // per_point_rotation_next_cur tensor of nr_strands X nr_points_per_strand x 3 of rodrigues towards the next point. Expressed in the local coordinate system of the current point // per_point_delta_dist tensor of nr_strands X nr_points_per_strand x 1 of delta movement applied to the average segment lenght. This is applied to the per_point_rotation_next_cur // per_point_direction_to_next nr_strands X nr_points_per_strand-1 x 3 direction in world coordinates from one point to the next one on the same strand void xyz2local(int nr_strands, int nr_verts_per_strand, const Eigen::MatrixXd& points, const Eigen::MatrixXd& strand_lengths, std::vector<Eigen::Matrix3d>& tbn_roots, torch::Tensor& per_point_rotation_next_cur_tensor, torch::Tensor& per_point_delta_dist_tensor, torch::Tensor& per_point_direction_to_next_tensor); // std::shared_ptr<easy_pbr::Mesh> augment_hair_bounce(std::shared_ptr<easy_pbr::Mesh> mesh); //make the hair bounce by adding a bit of the z direction once it's in tbn //objects std::shared_ptr<radu::utils::RandGenerator> m_rand_gen; std::shared_ptr<DataTransformer> m_transformer; //params bool m_autostart; bool m_is_running;// if the loop of loading is running, it is used to break the loop when the user ctrl-c std::string m_mode; // train or test or val fs::path m_dataset_path; fs::path m_scalp_mesh_path; int m_nr_clouds_to_skip; int m_nr_clouds_to_read; float m_percentage_strand_drop; int m_load_only_strand_with_idx; bool m_shuffle; bool m_do_overfit; // return all the time just one of the clouds, specifically the first one bool m_augment_per_strand; //agument either ech strand indivually or the whole hairstyle bool m_augment_in_tbn_space; //agument in either the normal space or in tbn space // bool m_do_adaptive_subsampling; //randomly drops points from the cloud, dropping with more probability the ones that are closes and with less the ones further std::thread m_loader_thread; uint32_t m_idx_cloud_to_read; int m_nr_resets; bool m_load_buffered; //if true, we start another thread an load clouds in a rinbuffer. If false, we just load everything in memory //internal bool m_is_modified; //indicate that a cloud was finished processind and you are ready to get it int m_nr_sequences; std::vector<fs::path> m_data_filenames; // moodycamel::ReaderWriterQueue<std::shared_ptr<easy_pbr::Mesh> > m_clouds_buffer; // std::vector<std::shared_ptr<easy_pbr::Mesh> > m_clouds_vec; moodycamel::ReaderWriterQueue<std::shared_ptr<USCHair > > m_hairs_buffer; std::vector<std::shared_ptr<USCHair> > m_hairs_vec; std::shared_ptr<easy_pbr::Mesh> m_mesh_head; std::shared_ptr<easy_pbr::Mesh> m_mesh_scalp; };
56.921569
317
0.757492
[ "mesh", "geometry", "vector" ]
fc31ff3b31800389452eb639c96b66a674a7211c
1,240
h
C
lib/commands/include/CommandHelp.h
ica778/adventure2019
51167c67967877eb0be2937b3e38780e6365e1b6
[ "MIT" ]
null
null
null
lib/commands/include/CommandHelp.h
ica778/adventure2019
51167c67967877eb0be2937b3e38780e6365e1b6
[ "MIT" ]
null
null
null
lib/commands/include/CommandHelp.h
ica778/adventure2019
51167c67967877eb0be2937b3e38780e6365e1b6
[ "MIT" ]
null
null
null
#ifndef CommandHelp_h #define CommandHelp_h #include "Command.h" #include <sstream> using usermanager::OnlineUserManager; using charactermanager::CharacterManager; using internationalization::Internationalization; class CommandHelp : public Command { public: CommandHelp(CharacterManager& c, OnlineUserManager& u, WorldManager& w, Internationalization& s): Command(c, u, w, s) {} virtual std::string executePromptReply(const std::string& connectionID, const std::vector<std::string>& fullCommand); virtual std::vector<std::string> reassembleCommand(std::string& fullCommand, bool& commandIsValid); private: std::string printAccountCommands(OnlineUserManager::USER_CODE userRole); std::string printAvatarCommands(OnlineUserManager::USER_CODE userRole); std::string printCommunicationCommands(OnlineUserManager::USER_CODE userRole); std::string printWorldInteractionCommands(OnlineUserManager::USER_CODE userRole); std::string printInventoryCommands(OnlineUserManager::USER_CODE userRole); std::string printMinigameCommands(OnlineUserManager::USER_CODE userRole); std::string printCombatCommands(OnlineUserManager::USER_CODE userRole); std::string printUtilityCommands(OnlineUserManager::USER_CODE userRole); }; #endif
38.75
118
0.817742
[ "vector" ]
fc39a9c2fb92bad612bff1c42d3baaf375ed2924
18,060
h
C
src/include/kerngen.h
JishinMaster/clBLAS
3711b9788b5fd71d5e2f1cae3431753cdcd2ed76
[ "Apache-2.0" ]
615
2015-01-05T13:24:44.000Z
2022-03-31T14:58:04.000Z
src/include/kerngen.h
JishinMaster/clBLAS
3711b9788b5fd71d5e2f1cae3431753cdcd2ed76
[ "Apache-2.0" ]
223
2015-01-12T21:07:18.000Z
2021-11-24T17:00:44.000Z
src/include/kerngen.h
JishinMaster/clBLAS
3711b9788b5fd71d5e2f1cae3431753cdcd2ed76
[ "Apache-2.0" ]
250
2015-01-05T06:39:43.000Z
2022-03-23T09:13:00.000Z
/* ************************************************************************ * Copyright 2013 Advanced Micro Devices, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ************************************************************************/ /* * Kernel generator related common definitions */ #ifndef KERNGEN_H_ #define KERNGEN_H_ #include <sys/types.h> #include <errno.h> #if defined (_MSC_VER) #include <msvc.h> #endif #include <defbool.h> #include <list.h> #include <cltypes.h> #include <mutex.h> #include <granulation.h> #include <trace_malloc.h> /** * @internal * @defgroup KGEN_INFRA Kernel generator infrastructure */ /*@{*/ #ifdef _MSC_VER #define SPREFIX "I" #else #define SPREFIX "z" #endif #define SUBDIM_UNUSED (size_t)-1 enum { MAX_TABS = 16, MAX_STATEMENT_PRIORITY = 63, MAX_STATEMENT_LENGTH = 4096 }; enum { // maximum subproblem dimensions MAX_SUBDIMS = 3, // maximum code nesting MAX_NESTING = 10, KSTRING_MAXLEN = 256, // generated function name max len FUNC_NAME_MAXLEN = KSTRING_MAXLEN }; typedef struct{ SubproblemDim subdims[MAX_SUBDIMS]; PGranularity pgran; }DecompositionStruct; struct KgenContext; struct KgenGuard; struct StatementBatch; /** * @internal * @defgroup KGEN_TYPES Types * @ingroup KGEN_INFRA */ /*@{*/ /** * @internal * @brief Memory fence type */ typedef enum CLMemFence { /** Fence for operations against the local memory */ CLK_LOCAL_MEM_FENCE, /** Fence for operations against the global memory */ CLK_GLOBAL_MEM_FENCE } CLMemFence; // TODO: deprecate typedef enum UptrType { UPTR_GLOBAL, UPTR_LOCAL, UPTR_PRIVATE } UptrType; /** * @internal * @brief Null-terminated string being a part of a kernel */ typedef struct Kstring { /** Buffer storing the string */ char buf[KSTRING_MAXLEN]; } Kstring; /** * @internal * @brief Type of custom generator for loop unrolling */ typedef int (*LoopUnrollGen)(struct KgenContext *ctx, void *priv); /*@}*/ /** * @internal * @brief Unrolled loop control information */ typedef struct LoopCtl { const char *ocName; /**< outer loop counter name */ union { const char *name; unsigned long val; } outBound; /**< outer loop bound */ bool obConst; /**< outer loop bound is constant flag */ unsigned long inBound; /**< inner loop bound */ } LoopCtl; /** * @internal * @brief Set of loop unrolling subgenerators */ typedef struct LoopUnrollers { /** generate preparative code before unrolling */ LoopUnrollGen preUnroll; /** generate single step for unrolled body in the vectorized way */ LoopUnrollGen genSingleVec; /** generated single step for unrolled body in non vectorized way */ LoopUnrollGen genSingle; /** generate code that should be inserted just after unrolled loop body */ LoopUnrollGen postUnroll; /** return veclen*/ LoopUnrollGen getVecLen; } LoopUnrollers; /*@}*/ static __inline void emptyKstring(Kstring *kstr) { kstr->buf[0] = '\0'; } static __inline bool isKstringEmpty(const Kstring *kstr) { return (kstr->buf[0] == '\0'); } /** * @internal * @defgroup KGEN_CORE Core API * @ingroup KGEN_INFRA */ /*@{*/ /** * @internal * @brief Create new generator context * * @param[out] srcBuf Source buffer; if NULL, then any statements * were not actually added to the source buffer, just * their overall size will be calculated * @param[in] srcBufLen Maximal length of the source which is being * generated; ignored if an actual buffer was not * specified * @param[in] fmt Format the source. Code formatting assumes * tabulation and watch line width * * @return New generator context on success. Returns NULL * if there is not enough memory to allocate internal structures */ struct KgenContext *createKgenContext(char *srcBuf, size_t srcBufLen, bool fmt); /** * @internal * @brief Destroy a kernel generator context * * @param[out] ctx An existing generator context to be destroyed */ void destroyKgenContext(struct KgenContext *ctx); /** * @internal * @brief Reset a kernel generator context used before * * @param[out] ctx A generator context to be reset * * Clear the source buffer and another information associated * with this context */ void resetKgenContext(struct KgenContext *ctx); /** * @internal * @brief Synchronize formatting of 2 contexts * * @param[in] srcCtx Source generator context * @param[out] dstCtx Destination generator context * @param[in] nrTabs Tabs number to be inserted in the source context. * It is relative on the current nesting level of the * target context. It must be not less than zero, and * resulting number of tabs which is evaluated as * the target context's nesting level plus 'nrTabs' * must not exceed 'MAX_TABS' * * The function is usable when it's needed to insert a code from * one context into another one, and don't disturb formatting. * * @return 0 on success, -EINVAL if the 'nrTabs' parameter is out * of range */ int kgenSyncFormatting( struct KgenContext *srcCtx, const struct KgenContext *dstCtx, int nrTabs); /** * @internal * @brief Add a function declaration * * @param[out] ctx Generator context * @param[in] decl The declaration to be added * * @return 0 on success; -1 if the source code exceeds the buffer, * or level of the code nesting is not zero, or the returned * type is not defined, or there is not a parenthesis opening * the argument list */ int kgenDeclareFunction(struct KgenContext *ctx, const char *decl); /** * @internal * @brief Begin function body * * @param[out] ctx Generator context * * Adds the opening bracket and increments a nesting counter. * * @return 0 on success; -1 if the source code exceeds the buffer */ int kgenBeginFuncBody(struct KgenContext *ctx); /** * @internal * @brief End function body * * @param[out] ctx Generator context * * Adds the closing bracket and decrements a nesting counter * * @return 0 on success; -1 if the source code exceeds the buffer, * or code nesting is not 1 */ int kgenEndFuncBody(struct KgenContext *ctx); /** * @internal * @brief Get the last declared function name for the context * * @param[out] buf A buffer to store the function name * @param[in] buflen Size of the buffer * @param[in] ctx Generator context * * @return pointer to the gotten function name on success; -1 * if no functions were declared or the passed buffer is * insufficient */ int kgenGetLastFuncName( char *buf, size_t buflen, const struct KgenContext *ctx); /** * @internal * @brief Begin new execution branch: conditional branch or loop * * @param[out] ctx Generator context * @param[in] stmt A statement containing a branch control code. * Ignored if NULL. * * The opening bracket and trailing new line symbol are added * automatically and should not be passed * * @return 0 on success; -1 if the overall source exceeds the set * limit or nesting exceeds the maximum allowed one */ int kgenBeginBranch(struct KgenContext *ctx, const char *stmt); /** * @internal * @brief End the current code branch * * @param[out] ctx Generator context * @param[in] stmt A statement containing a branch control code * * As well closing bracket as trailing ';' and '\n' are added automatically and * should not be passed. * The statement passed in 'stmt' is appended after the closing bracket. * * @return 0 on sucess; -1 if the overall source exceeds the set limit, * or there is not an opened branch */ int kgenEndBranch(struct KgenContext *ctx, const char *stmt); /** * @internal * @brief Add a statement to generated source * * @param[out] ctx Generator context * @param[in] stmt A statement to be added * * If formatting is enabled and the statement is multiline, all the lines are * formatted automatically. It's strongly not recommended to add with this * function any statements containing variables or function declaration, * or branch bounds. The appropriated functions should be used for that to avoid * unexpected side effects. * * @return 0 on success; -1 if the overall source exceeds the set limit */ int kgenAddStmt(struct KgenContext *ctx, const char *stmt); int kgenPrintf(struct KgenContext *ctx, const char *fmt,...); struct StatementBatch *createStmtBatch(void); int kgenAddStmtToBatch( struct StatementBatch *batch, int priority, const char *stmt); int kgenBatchPrintf( struct StatementBatch *batch, int priority, const char *fmt,...); int flushStmtBatch(struct KgenContext *ctx, struct StatementBatch *batch); void destroyStmtBatch(struct StatementBatch *batch); /** * @internal * @brief Add a blank line to generated source * * @param[out] ctx Generator context * * @return 0 on success; -1 if the overall source exceeds * the set limit returns -1 */ int kgenAddBlankLine(struct KgenContext *ctx); /** * @internal * @brief Get resulting source size * * @param[out] ctx Generator context * * @return size of the overall source was added to the * generator context including the trailing null * byte */ size_t kgenSourceSize(struct KgenContext *ctx); /*@}*/ /** * @internal * @defgroup KGEN_BASIC Basic generating functions * @ingroup KGEN_INFRA */ /*@{*/ /** * @internal * @brief Add barrier * * @param[out] ctx Generator context * @param[in] fence Fence type * * @return 0 on success, and -EOVERFLOW on buffer overflowing */ int kgenAddBarrier(struct KgenContext *ctx, CLMemFence fence); /** * @internal * @brief Add memory fence * * @param[out] ctx Generator context * @param[in] fence Fence type * * @return 0 on success, and -EOVERFLOW on buffer overflowing */ int kgenAddMemFence(struct KgenContext *ctx, CLMemFence fence); /** * @internal * @brief Add local ID declaration and evaluating expression * * @param[out] ctx Generator context * @param[in] lidName Local id variable name * @param[in] pgran Data parallelism granularity * * The resulting expression depends on the work group dimension and size * of the first one. * * @return 0 on success, and -EOVERFLOW on buffer overflowing */ int kgenDeclareLocalID( struct KgenContext *ctx, const char *lidName, const PGranularity *pgran); /** * @internal * @brief Add work group ID declaration and evaluating expression * * @param[out] ctx Generator context * @param[in] gidName Group id variable name * @param[in] pgran Data parallelism granularity * * The resulting expression depends on the work group dimension and size * of the first one. * * @return 0 on success, and -EOVERFLOW on buffer overflowing */ int kgenDeclareGroupID( struct KgenContext *ctx, const char *gidName, const PGranularity *pgran); /* * TODO: deprecate when casting is eliminated * * declare unified pointers * * @withDouble: double based types pointers area needed * * On success returns 0, on buffer overflowing returns -EOVERFLOW */ int kgenDeclareUptrs(struct KgenContext *ctx, bool withDouble); /*@}*/ /** * @internal * @defgroup KGEN_HELPERS Generating helpers * @ingroup KGEN_INFRA */ /*@{*/ /** * @internal * @brief Assistant for loop body unrolling * * @param[out] ctx Generator context * @param[in] loopCtl Unrolled loop control information * @param[in] dtype Data type to unroll the loop body for * @param[in] unrollers Set of subgenerators; * If 'preUnroll', 'postUnroll' or 'vecUnroll' * is set to NULL, it is ignored. Vectorized unrolling * is not used for 'COMPLEX_DOUBLE' type * @param[out] priv Private data for generators * * The unrolled loop can be as well single as double. In the case * of the double loop only the inner loop is unrolled, and the outer * loop is generated in the standard way with using the passed loop * counter name and its bound. For the single loop 'ocName' field of the * 'loop' structure should be NULL. * * @return 0 on success. On error returns negated error code:\n *\n * -EOVERFLOW: code buffer overflowed\n * -EINVAL: invalid parameter is passed * (unsupported data type, or 'genSingle' generator * is not specified) */ int kgenLoopUnroll( struct KgenContext *ctx, LoopCtl *loopCtl, DataType dtype, const LoopUnrollers *unrollers, void *priv); /** * @internal * @brief Create code generation guard * * @param[out] ctx Generator context * @param[in] genCallback Generator callback which is invoked it the function * matching to a pattern is not found * @param[in] patSize Pattern size * * The guard doesn't allow to generate several functions matching to the same * pattern and as result having the same name. * * @return a guard object on success; -ENOMEM if there is * not enough of memory to allocate internal structures */ struct KgenGuard *createKgenGuard( struct KgenContext *ctx, int (*genCallback)(struct KgenContext *ctx, const void *pattern), size_t patSize); /** * @internal * @brief Reinitialize generator guard * * @param[out] guard An existing generation guard * @param[out] ctx Generator context * @param[in] genCallback Generator callback which is invoked it the function * matching to a pattern is not found * @param[in] patSize Pattern size */ void reinitKgenGuard( struct KgenGuard *guard, struct KgenContext *ctx, int (*genCallback)(struct KgenContext *ctx, const void *pattern), size_t patSize); /** * @internal * @brief Find an already generated function or generate it * * @param[out] guard An existing generation guard * @param[in] pattern Pattern the function being looked for should match * @param[out] name Buffer to store a name of the function * @param[in] nameLen Name buffer length * * At first it tries to find an already generated function mathing to the passed * pattern. If the guard doesn't find the function, it invokes the generator * callback * * NOTE: names of generated functions should not exceed 'FUNC_NAME_MAXLEN' * constant. * * @return 0 on success, otherwise returns a negated error code:\n * -ENOMEM: enough of memory to allocate internal structures\n * -EOVERFLOW: source buffer overflowing */ int findGenerateFunction( struct KgenGuard *guard, const void *pattern, char *name, size_t nameLen); /** * @internal * @brief Destroy code generation guard * * @param[out] guard A guard instance to be destroyed */ void destroyKgenGuard(struct KgenGuard *guard); /*@}*/ /** * @internal * @defgroup KGEN_AUX_FUNCS Auxiliary functions * @ingroup KGEN_INFRA */ /*@{*/ void kstrcpy(Kstring *kstr, const char *str); void ksprintf(Kstring *kstr, const char *fmt,...); void kstrcatf(Kstring *kstr, const char *fmt,...); // unified pointer type name const char *uptrTypeName(UptrType type); /** * @internal * @brief get a BLAS data type dependendtto function prefix * * @param[in] type Data type * * A literal returned by the function is assumed to be used as the prefix * of some generated function to put the accent on the BLAS data type it * operates with. * * @return 0 if an unknown type is passed */ char dtypeToPrefix(DataType type); /** * @internal * @brief convert a BLAS data type to the respective built-in OpenCL type * * @param[in] dtype Data type * * @return NULL if an unknown type is passed */ const char *dtypeBuiltinType(DataType dtype); /** * internal * @brief Return unified pointer field corresponding to the data type * * @param[in] dtype Data type * * @Returns NULL if an unknown type is passed */ const char *dtypeUPtrField(DataType dtype); /** * @internal * @brief Return "one" value string depending on the data type * * @param[in] dtype Data type * * @return NULL if an unknown type is passed */ const char *strOne(DataType dtype); /** * @internal * @brief Get vector type name * * @param[in] dtype Data type * @param[in] vecLen Vector length for the type. Must be set to 1 if * the type is scalar. * @param[out] typeName Location to store pointer to a constant string * with the type name * @param[out] typePtrName Location to store unified pointer field * corresponding to the vector consisting of elements * of \b dtype \b type */ void getVectorTypeName( DataType dtype, unsigned int vecLen, const char **typeName, const char **typePtrName); /*@}*/ #endif /* KERNGEN_H_ */
26.098266
80
0.659468
[ "object", "vector" ]
fc40b0e9517c68816aaf74c42596674e9d86944c
4,286
h
C
head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/zfs_sa.h
dplbsd/soc2013
c134f5e2a5725af122c94005c5b1af3720706ce3
[ "BSD-2-Clause" ]
4
2016-08-22T22:02:55.000Z
2017-03-04T22:56:44.000Z
head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/zfs_sa.h
dplbsd/soc2013
c134f5e2a5725af122c94005c5b1af3720706ce3
[ "BSD-2-Clause" ]
21
2016-08-11T09:43:43.000Z
2017-01-29T12:52:56.000Z
head/sys/cddl/contrib/opensolaris/uts/common/fs/zfs/sys/zfs_sa.h
dplbsd/soc2013
c134f5e2a5725af122c94005c5b1af3720706ce3
[ "BSD-2-Clause" ]
2
2018-01-11T01:01:12.000Z
2020-11-19T03:07:29.000Z
/* * CDDL HEADER START * * The contents of this file are subject to the terms of the * Common Development and Distribution License (the "License"). * You may not use this file except in compliance with the License. * * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE * or http://www.opensolaris.org/os/licensing. * See the License for the specific language governing permissions * and limitations under the License. * * When distributing Covered Code, include this CDDL HEADER in each * file and include the License file at usr/src/OPENSOLARIS.LICENSE. * If applicable, add the following below this CDDL HEADER, with the * fields enclosed by brackets "[]" replaced with your own identifying * information: Portions Copyright [yyyy] [name of copyright owner] * * CDDL HEADER END */ /* * Copyright 2010 Sun Microsystems, Inc. All rights reserved. * Use is subject to license terms. */ #ifndef _SYS_ZFS_SA_H #define _SYS_ZFS_SA_H #ifdef _KERNEL #include <sys/list.h> #include <sys/dmu.h> #include <sys/zfs_acl.h> #include <sys/zfs_znode.h> #include <sys/sa.h> #include <sys/zil.h> #endif #ifdef __cplusplus extern "C" { #endif /* * This is the list of known attributes * to the ZPL. The values of the actual * attributes are not defined by the order * the enums. It is controlled by the attribute * registration mechanism. Two different file system * could have different numeric values for the same * attributes. this list is only used for dereferencing * into the table that will hold the actual numeric value. */ typedef enum zpl_attr { ZPL_ATIME, ZPL_MTIME, ZPL_CTIME, ZPL_CRTIME, ZPL_GEN, ZPL_MODE, ZPL_SIZE, ZPL_PARENT, ZPL_LINKS, ZPL_XATTR, ZPL_RDEV, ZPL_FLAGS, ZPL_UID, ZPL_GID, ZPL_PAD, ZPL_ZNODE_ACL, ZPL_DACL_COUNT, ZPL_SYMLINK, ZPL_SCANSTAMP, ZPL_DACL_ACES, ZPL_END } zpl_attr_t; #define ZFS_OLD_ZNODE_PHYS_SIZE 0x108 #define ZFS_SA_BASE_ATTR_SIZE (ZFS_OLD_ZNODE_PHYS_SIZE - \ sizeof (zfs_acl_phys_t)) #define SA_MODE_OFFSET 0 #define SA_SIZE_OFFSET 8 #define SA_GEN_OFFSET 16 #define SA_UID_OFFSET 24 #define SA_GID_OFFSET 32 #define SA_PARENT_OFFSET 40 extern sa_attr_reg_t zfs_attr_table[ZPL_END + 1]; extern sa_attr_reg_t zfs_legacy_attr_table[ZPL_END + 1]; /* * This is a deprecated data structure that only exists for * dealing with file systems create prior to ZPL version 5. */ typedef struct znode_phys { uint64_t zp_atime[2]; /* 0 - last file access time */ uint64_t zp_mtime[2]; /* 16 - last file modification time */ uint64_t zp_ctime[2]; /* 32 - last file change time */ uint64_t zp_crtime[2]; /* 48 - creation time */ uint64_t zp_gen; /* 64 - generation (txg of creation) */ uint64_t zp_mode; /* 72 - file mode bits */ uint64_t zp_size; /* 80 - size of file */ uint64_t zp_parent; /* 88 - directory parent (`..') */ uint64_t zp_links; /* 96 - number of links to file */ uint64_t zp_xattr; /* 104 - DMU object for xattrs */ uint64_t zp_rdev; /* 112 - dev_t for VBLK & VCHR files */ uint64_t zp_flags; /* 120 - persistent flags */ uint64_t zp_uid; /* 128 - file owner */ uint64_t zp_gid; /* 136 - owning group */ uint64_t zp_zap; /* 144 - extra attributes */ uint64_t zp_pad[3]; /* 152 - future */ zfs_acl_phys_t zp_acl; /* 176 - 263 ACL */ /* * Data may pad out any remaining bytes in the znode buffer, eg: * * |<---------------------- dnode_phys (512) ------------------------>| * |<-- dnode (192) --->|<----------- "bonus" buffer (320) ---------->| * |<---- znode (264) ---->|<---- data (56) ---->| * * At present, we use this space for the following: * - symbolic links * - 32-byte anti-virus scanstamp (regular files only) */ } znode_phys_t; #ifdef _KERNEL int zfs_sa_readlink(struct znode *, uio_t *); void zfs_sa_symlink(struct znode *, char *link, int len, dmu_tx_t *); void zfs_sa_upgrade(struct sa_handle *, dmu_tx_t *); void zfs_sa_get_scanstamp(struct znode *, xvattr_t *); void zfs_sa_set_scanstamp(struct znode *, xvattr_t *, dmu_tx_t *); void zfs_sa_uprade_pre(struct sa_handle *, void *, dmu_tx_t *); void zfs_sa_upgrade_post(struct sa_handle *, void *, dmu_tx_t *); void zfs_sa_upgrade_txholds(dmu_tx_t *, struct znode *); #endif #ifdef __cplusplus } #endif #endif /* _SYS_ZFS_SA_H */
29.972028
72
0.702753
[ "object" ]
fc47d456b023492b5d0aa705583f0e8886ff6a70
5,776
c
C
numpy_stubs.c
jamesjer/pyml
ca0890ef3c6c53fdd85bc1b0b9aee9d9cf18b185
[ "BSD-2-Clause" ]
133
2017-06-13T06:39:35.000Z
2022-03-12T14:05:26.000Z
numpy_stubs.c
jamesjer/pyml
ca0890ef3c6c53fdd85bc1b0b9aee9d9cf18b185
[ "BSD-2-Clause" ]
78
2017-03-13T11:19:14.000Z
2022-03-21T16:22:34.000Z
numpy_stubs.c
jamesjer/pyml
ca0890ef3c6c53fdd85bc1b0b9aee9d9cf18b185
[ "BSD-2-Clause" ]
23
2017-06-13T20:11:29.000Z
2022-02-22T18:08:30.000Z
#include <caml/mlvalues.h> #include <caml/memory.h> #include <caml/fail.h> #include <caml/alloc.h> #include <caml/bigarray.h> #include <caml/custom.h> #include "pyml_stubs.h" static void numpy_finalize(value v) { struct numpy_custom_operations *ops = (struct numpy_custom_operations *) Custom_ops_val(v); Py_DECREF(ops->obj); free(ops); } CAMLprim value pyarray_of_bigarray_wrapper( value numpy_api_ocaml, value bigarray_type_ocaml, value bigarray_ocaml) { CAMLparam3(numpy_api_ocaml, bigarray_type_ocaml, bigarray_ocaml); pyml_assert_initialized(); PyObject *c_api = pyml_unwrap(numpy_api_ocaml); void **PyArray_API = pyml_get_pyarray_api(c_api); PyObject *(*PyArray_New) (PyTypeObject *, int, npy_intp *, int, npy_intp *, void *, int, int, PyObject *) = PyArray_API[93]; int nd = Caml_ba_array_val(bigarray_ocaml)->num_dims; npy_intp *dims = malloc(nd * sizeof(npy_intp)); int i; for (i = 0; i < nd; i++) { dims[i] = Caml_ba_array_val(bigarray_ocaml)->dim[i]; } int type_num; intnat flags = Caml_ba_array_val(bigarray_ocaml)->flags; switch (flags & BIGARRAY_KIND_MASK) { case CAML_BA_FLOAT32: type_num = NPY_FLOAT; break; case CAML_BA_FLOAT64: type_num = NPY_DOUBLE; break; case CAML_BA_SINT8: type_num = NPY_BYTE; break; case CAML_BA_UINT8: type_num = NPY_UBYTE; break; case CAML_BA_SINT16: type_num = NPY_SHORT; break; case CAML_BA_UINT16: type_num = NPY_USHORT; break; case CAML_BA_INT32: type_num = NPY_INT; break; case CAML_BA_INT64: type_num = NPY_LONGLONG; break; case CAML_BA_CAML_INT: failwith("Caml integers are unsupported for NumPy array"); break; case CAML_BA_NATIVE_INT: type_num = NPY_LONG; break; case CAML_BA_COMPLEX32: type_num = NPY_CFLOAT; break; case CAML_BA_COMPLEX64: type_num = NPY_CDOUBLE; break; #ifdef CAML_BA_CHAR /* introduced in 4.02.0 */ case CAML_BA_CHAR: type_num = NPY_CHAR; break; #endif default: failwith("Unsupported bigarray kind for NumPy array"); } int np_flags; switch (flags & CAML_BA_LAYOUT_MASK) { case CAML_BA_C_LAYOUT: np_flags = NPY_ARRAY_CARRAY; break; case CAML_BA_FORTRAN_LAYOUT: np_flags = NPY_ARRAY_FARRAY; break; default: failwith("Unsupported bigarray layout for NumPy array"); } void *data = Caml_ba_data_val(bigarray_ocaml); PyTypeObject (*PyArray_SubType) = (PyTypeObject *) pyml_unwrap(bigarray_type_ocaml); PyObject *result = PyArray_New( PyArray_SubType, nd, dims, type_num, NULL, data, 0, np_flags, NULL); free(dims); CAMLreturn(pyml_wrap(result, true)); } CAMLprim value bigarray_of_pyarray_wrapper( value numpy_api_ocaml, value pyarray_ocaml) { CAMLparam2(numpy_api_ocaml, pyarray_ocaml); CAMLlocal2(bigarray, result); pyml_assert_initialized(); PyObject *array = pyml_unwrap(pyarray_ocaml); PyArrayObject_fields *fields = (PyArrayObject_fields *) pyobjectdescr(array); int nd = fields->nd; npy_intp *shape = fields->dimensions; intnat *dims = malloc(nd * sizeof(intnat)); int i; for (i = 0; i < nd; i++) { dims[i] = shape[i]; } int type = fields->descr->type_num; enum caml_ba_kind kind; switch (type) { case NPY_BYTE: kind = CAML_BA_SINT8; break; case NPY_UBYTE: kind = CAML_BA_UINT8; break; case NPY_SHORT: kind = CAML_BA_SINT16; break; case NPY_USHORT: kind = CAML_BA_UINT16; break; case NPY_INT: kind = CAML_BA_INT32; break; case NPY_LONG: kind = CAML_BA_NATIVE_INT; break; case NPY_LONGLONG: kind = CAML_BA_INT64; break; case NPY_FLOAT: kind = CAML_BA_FLOAT32; break; case NPY_DOUBLE: kind = CAML_BA_FLOAT64; break; case NPY_CFLOAT: kind = CAML_BA_COMPLEX32; break; case NPY_CDOUBLE: kind = CAML_BA_COMPLEX64; break; case NPY_CHAR: #ifdef CAML_BA_CHAR /* introduced in 4.02.0 */ kind = CAML_BA_CHAR; #else kind = CAML_BA_UINT8; #endif break; default: failwith("Unsupported NumPy kind for bigarray"); } int flags = fields->flags; enum caml_ba_layout layout; if (flags & NPY_ARRAY_C_CONTIGUOUS) { layout = CAML_BA_C_LAYOUT; } else if (flags & NPY_ARRAY_F_CONTIGUOUS) { layout = CAML_BA_FORTRAN_LAYOUT; } else { failwith("Unsupported NumPy layout for bigarray"); } void *data = fields->data; bigarray = caml_ba_alloc(kind | layout, nd, data, dims); free(dims); Py_INCREF(array); struct custom_operations *oldops = Custom_ops_val(bigarray); struct numpy_custom_operations *newops = (struct numpy_custom_operations *) malloc(sizeof(struct numpy_custom_operations)); newops->ops.identifier = oldops->identifier; newops->ops.finalize = numpy_finalize; newops->ops.compare = oldops->compare; newops->ops.hash = oldops->hash; newops->ops.serialize = oldops->serialize; newops->ops.deserialize = oldops->deserialize; newops->ops.compare_ext = oldops->compare_ext; newops->obj = array; Custom_ops_val(bigarray) = (struct custom_operations *) newops; result = caml_alloc_tuple(3); Store_field(result, 0, Val_int(kind)); Store_field(result, 1, Val_int(layout == CAML_BA_FORTRAN_LAYOUT ? 1 : 0)); Store_field(result, 2, bigarray); CAMLreturn(result); }
29.171717
79
0.64491
[ "shape" ]
fc5968ab5136f79ff8e1074f3b2a6fb36e2ae0b6
2,179
h
C
src/roseExtensions/qtWidgets/WidgetCreator/SubWindowFactory.h
maurizioabba/rose
7597292cf14da292bdb9a4ef573001b6c5b9b6c0
[ "BSD-3-Clause" ]
488
2015-01-09T08:54:48.000Z
2022-03-30T07:15:46.000Z
src/roseExtensions/qtWidgets/WidgetCreator/SubWindowFactory.h
sujankh/rose-matlab
7435d4fa1941826c784ba97296c0ec55fa7d7c7e
[ "BSD-3-Clause" ]
174
2015-01-28T18:41:32.000Z
2022-03-31T16:51:05.000Z
src/roseExtensions/qtWidgets/WidgetCreator/SubWindowFactory.h
sujankh/rose-matlab
7435d4fa1941826c784ba97296c0ec55fa7d7c7e
[ "BSD-3-Clause" ]
146
2015-04-27T02:48:34.000Z
2022-03-04T07:32:53.000Z
#ifndef SUBWINDOWFACTORY_H #define SUBWINDOWFACTORY_H #include <QMdiArea> #include <QMap> class WidgetCreatorInterface; class QMenu; /** * \brief QMdiArea with ROSE sub-widgets * * This class implements a QMdiArea which can create ROSE widgets, and link them together. * The use can link widgets together by using a custom widgets-menu which is located in the top left corner of a subwidget * The link mechanism relies on the fact that the subwidgets, i.e. widget which are created by the WidgetCreatorInterface have the following signals and slots: * - slot \c setNode() Takes the given node as base for the whole display. TreeView's usually set the new node as root. * - slot \c gotoNode() Selects the given node (and in tree-view expands until this node is visible), and highlights it, the displayed data set does not change * - signal \c nodeActivated() This signal is usually sent when the user clicks on some node * - signal \c nodeActivatedAlt() Alternative way of activating a node, mostly double-click (but may vary from view to view) * Unfortunately this cannot be enforced by a common abstract base class, since these are signals and slots, this base class whould have to inherit from * QObject, which would result in a diamond shaped class hierarchy. If these signals and slots do not exist the link-mechanism just does not work because connect fails * which result in a warning on the command line) */ class SubWindowFactory : public QMdiArea { Q_OBJECT public: SubWindowFactory( QWidget *parent = NULL ) : QMdiArea( parent ) {} virtual ~SubWindowFactory(); void registerSubWindow( WidgetCreatorInterface *winInterface ); QList<QAction *> getActions() const; private slots: void addSubWindowAction(); void linkAction(); private: bool eventFilter( QObject *object, QEvent *event ); void rebuildSystemMenus(); QList<WidgetCreatorInterface *> interfaces; QMap<QMdiSubWindow *, QWidget *> openWidgets; QMap<QPair<QWidget *, QWidget *>, bool> linked; }; #endif
37.568966
170
0.704911
[ "object" ]
fc649601adb57fc56114633e451c857a44ee8dfe
1,513
h
C
include/tdp/bb/tetrahedron.h
jstraub/tdp
dcab53662be5b88db1538cf831707b07ab96e387
[ "MIT-feh" ]
1
2017-10-17T19:25:47.000Z
2017-10-17T19:25:47.000Z
include/tdp/bb/tetrahedron.h
jstraub/tdp
dcab53662be5b88db1538cf831707b07ab96e387
[ "MIT-feh" ]
1
2018-05-02T06:04:06.000Z
2018-05-02T06:04:06.000Z
include/tdp/bb/tetrahedron.h
jstraub/tdp
dcab53662be5b88db1538cf831707b07ab96e387
[ "MIT-feh" ]
5
2017-09-17T18:46:20.000Z
2019-03-11T12:52:57.000Z
/* Copyright (c) 2015, Julian Straub <jstraub@csail.mit.edu> Licensed * under the MIT license. See the license file LICENSE. */ #pragma once #include <vector> #include <Eigen/Dense> #include <Eigen/LU> namespace tdp { template <typename T> class Tetrahedron4D { public: Tetrahedron4D(const Eigen::Matrix<T, 4, 4>& vertices); Tetrahedron4D(const Eigen::Matrix<T,4,1>& a, const Eigen::Matrix<T,4,1>& b, const Eigen::Matrix<T,4,1>& c, const Eigen::Matrix<T,4,1>& d); ~Tetrahedron4D() = default; Eigen::Matrix<T,4,1> GetCenter() const; Eigen::Quaternion<T> GetCenterQuaternion() const; Eigen::Matrix<T,4,1> GetVertex(uint32_t i) const; Eigen::Quaternion<T> GetVertexQuaternion(uint32_t i) const; std::vector<Tetrahedron4D<T>> Subdivide() const; /// Get the volume of this tetrahedron projected onto S^3 by /// approximating this Tetrahedron with a set of recursively /// subdivided tetrahedra down to the maxLvl subdividision level. T GetVolume(uint32_t maxLvl=5) const; bool Intersects(const Eigen::Matrix<T,4,1>& q) const; /// Get the volume of a given Tetrahedron in 4D static T GetVolume(const Tetrahedron4D<T>& tetra); protected: /// One 4D vertex per column. 4 vertices in total to describe the 4D /// Tetrahedron. Eigen::Matrix<T, 4, 4> vertices_; T RecursivelyApproximateSurfaceArea(Tetrahedron4D<T> tetra, uint32_t lvl) const; void RecursivelySubdivide(Tetrahedron4D<T> tetra, std::vector<Tetrahedron4D<T>>& tetras, uint32_t lvl) const; }; }
32.891304
77
0.719101
[ "vector" ]
fc68325117c948a8d16b79f37a5a0e85c983915e
420
h
C
Src/State_Game.h
photogami/WorldMap
5f82363479c269f9ebb188ff6b5ad6a707af1b86
[ "MIT" ]
null
null
null
Src/State_Game.h
photogami/WorldMap
5f82363479c269f9ebb188ff6b5ad6a707af1b86
[ "MIT" ]
null
null
null
Src/State_Game.h
photogami/WorldMap
5f82363479c269f9ebb188ff6b5ad6a707af1b86
[ "MIT" ]
null
null
null
#pragma once //----------------------------------------------------------------------------- class CState_Game : public CState { public: CState_Game(const char* name, const char* gui_fname) : CState(name,gui_fname){}; virtual bool Init(); virtual void Deinit(); virtual void Update(const float dt); virtual void Render(); virtual void Render2d(); virtual bool ProcessInput(const inputEvent_t* e); };
30
82
0.578571
[ "render" ]
fc6c801b78511b95aa94b32c01466dbed4f90d78
3,249
h
C
src/gamebase/include/gamebase/impl/tools/ObjectsCollection.h
TheMrButcher/opengl_lessons
76ac96c45773a54a85d49c6994770b0c3496303f
[ "MIT" ]
1
2016-10-25T21:15:16.000Z
2016-10-25T21:15:16.000Z
src/gamebase/include/gamebase/impl/tools/ObjectsCollection.h
TheMrButcher/gamebase
76ac96c45773a54a85d49c6994770b0c3496303f
[ "MIT" ]
375
2016-06-04T11:27:40.000Z
2019-04-14T17:11:09.000Z
src/gamebase/include/gamebase/impl/tools/ObjectsCollection.h
TheMrButcher/gamebase
76ac96c45773a54a85d49c6994770b0c3496303f
[ "MIT" ]
null
null
null
/** * Copyright (c) 2018 Slavnejshev Filipp * This file is licensed under the terms of the MIT license. */ #pragma once #include <gamebase/GameBaseAPI.h> #include <gamebase/impl/pos/IPositionable.h> #include <gamebase/impl/engine/IMovable.h> #include <gamebase/impl/engine/Drawable.h> #include <gamebase/impl/engine/ISelectable.h> #include <gamebase/impl/findable/IFindable.h> #include <gamebase/impl/reg/Registrable.h> #include <gamebase/impl/reg/PropertiesRegisterBuilder.h> #include <gamebase/impl/serial/ISerializable.h> #include <gamebase/math/Transform2.h> #include <vector> namespace gamebase { namespace impl { class PropertiesRegisterBuilder; class GAMEBASE_API ObjectsCollection : public Drawable, public Registrable, public IPositionable, public IMovable, public IFindable, public ISerializable { public: ObjectsCollection(IPositionable* position = nullptr); void addObject(const std::shared_ptr<IObject>& object); void replaceObject(int id, const std::shared_ptr<IObject>& object); bool removeObject(int id); int findObject(IObject* obj) const; virtual Transform2 position() const override; virtual void setParentPosition(const IPositionable* parent) override; virtual bool isSelectableByPoint(const Vec2& point) const override { return false; } virtual std::shared_ptr<IObject> findChildByPoint(const Vec2& point) const override; virtual IScrollable* findScrollableByPoint(const Vec2& point) override; virtual void move(float time) override; virtual void loadResources() override; virtual void drawAt(const Transform2& position) const override; virtual void setBox(const BoundingBox& allowedBox) override; virtual BoundingBox box() const override; virtual void registerObject(PropertiesRegisterBuilder* builder) override; virtual void serialize(Serializer& s) const override; struct ObjectDesc { ObjectDesc() : movable(nullptr) , drawable(nullptr) , positionable(nullptr) , findable(nullptr) {} IMovable* movable; IDrawable* drawable; IPositionable* positionable; IFindable* findable; }; std::vector<std::shared_ptr<IObject>>::iterator begin() { return m_objects.begin(); } std::vector<std::shared_ptr<IObject>>::iterator end() { return m_objects.end(); } std::vector<std::shared_ptr<IObject>>::const_iterator begin() const { return m_objects.begin(); } std::vector<std::shared_ptr<IObject>>::const_iterator end() const { return m_objects.end(); } size_t size() const { return m_objects.size(); } bool empty() const { return m_objects.empty(); } void clear(); const std::vector<std::shared_ptr<IObject>>& objects() const { return m_objects; } const std::vector<ObjectDesc>& objectDescs() const { return m_objectDescs; } void setAssociatedSelectable(ISelectable* selectable); private: ObjectDesc registerObject(const std::shared_ptr<IObject>& object); IPositionable* m_position; std::vector<std::shared_ptr<IObject>> m_objects; std::vector<ObjectDesc> m_objectDescs; ISelectable* m_associatedSelectable; std::unique_ptr<PropertiesRegisterBuilder> m_registerBuilder; }; } }
36.1
101
0.728224
[ "object", "vector" ]
fc83363c8e2efd4ddc353c0efa56826fd41df7f1
10,266
h
C
src/kudu/util/mem_tracker.h
attilabukor/kudu
d4942c43880a7b0324388630ff640fe66f16c4b5
[ "Apache-2.0" ]
1,538
2016-08-08T22:34:30.000Z
2022-03-29T05:23:36.000Z
be/src/kudu/util/mem_tracker.h
xwzbupt/impala
97dda2b27da99367f4d07699aa046b16cda16dd4
[ "Apache-2.0" ]
17
2017-05-18T16:05:14.000Z
2022-03-18T22:17:13.000Z
be/src/kudu/util/mem_tracker.h
xwzbupt/impala
97dda2b27da99367f4d07699aa046b16cda16dd4
[ "Apache-2.0" ]
612
2016-08-12T04:09:37.000Z
2022-03-29T16:57:46.000Z
// 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. #ifndef KUDU_UTIL_MEM_TRACKER_H #define KUDU_UTIL_MEM_TRACKER_H #include <cstdint> #include <list> #include <memory> #include <string> #include <utility> #include <vector> #include <glog/logging.h> #include "kudu/util/high_water_mark.h" #include "kudu/util/mutex.h" namespace kudu { class MemTrackerPB; // A MemTracker tracks memory consumption; it contains an optional limit and is // arranged into a tree structure such that the consumption tracked by a // MemTracker is also tracked by its ancestors. // // The MemTracker hierarchy is rooted in a single static MemTracker. // The root MemTracker always exists, and it is the common // ancestor to all MemTrackers. All operations that discover MemTrackers begin // at the root and work their way down the tree, while operations that deal // with adjusting memory consumption begin at a particular MemTracker and work // their way up the tree to the root. All MemTrackers (except the root) must // have a parent. As a rule, all children belonging to a parent should have // unique ids, but this is only enforced during a Find() operation to allow for // transient duplicates (e.g. the web UI grabbing very short-lived references // to all MemTrackers while rendering a web page). This also means id // uniqueness only exists where it's actually needed. // // When a MemTracker begins its life, it has a strong reference to its parent // and the parent has a weak reference to it. Both remain for the lifetime of // the MemTracker. // // Memory consumption is tracked via calls to Consume()/Release(), either to // the tracker itself or to one of its descendants. // // This class is thread-safe. class MemTracker : public std::enable_shared_from_this<MemTracker> { public: ~MemTracker(); // Creates and adds the tracker to the tree so that it can be retrieved with // FindTracker/FindOrCreateTracker. // // byte_limit < 0 means no limit; 'id' is a used as a label to uniquely identify // the MemTracker for the below Find...() calls as well as the web UI. // // Use the two-argument form if there is no parent. static std::shared_ptr<MemTracker> CreateTracker( int64_t byte_limit, const std::string& id, std::shared_ptr<MemTracker> parent = std::shared_ptr<MemTracker>()); // If a tracker with the specified 'id' and 'parent' exists in the tree, sets // 'tracker' to reference that instance. Returns false if no such tracker // exists. // // Use the two-argument form if there is no parent. // // Note: this function will enforce that 'id' is unique amongst the children // of 'parent'. static bool FindTracker( const std::string& id, std::shared_ptr<MemTracker>* tracker, const std::shared_ptr<MemTracker>& parent = std::shared_ptr<MemTracker>()); // If a global tracker with the specified 'id' exists in the tree, returns a // shared_ptr to that instance. Otherwise, creates a new MemTracker with the // specified byte_limit and id, parented to the root MemTracker. // // Note: this function will enforce that 'id' is unique amongst the children // of the root MemTracker. static std::shared_ptr<MemTracker> FindOrCreateGlobalTracker( int64_t byte_limit, const std::string& id); // Returns a list of all the valid trackers. static void ListTrackers(std::vector<std::shared_ptr<MemTracker>>* trackers); // Marshals the tracker tree into 'pb'. static void TrackersToPb(MemTrackerPB* pb); // Gets a shared_ptr to the "root" tracker, creating it if necessary. static std::shared_ptr<MemTracker> GetRootTracker(); // Increases consumption of this tracker and its ancestors by 'bytes'. void Consume(int64_t bytes); // Increases consumption of this tracker and its ancestors by 'bytes' only if // they can all consume 'bytes'. If this brings any of them over, none of them // are updated. // Returns true if the try succeeded. bool TryConsume(int64_t bytes); // Returns true if this tracker could consume 'bytes' without exceeding its // limit, false otherwise. bool CanConsumeNoAncestors(int64_t bytes); // Decreases consumption of this tracker and its ancestors by 'bytes'. // // This will also cause the process to periodically trigger tcmalloc "ReleaseMemory" // to ensure that memory is released to the OS. void Release(int64_t bytes); // Returns true if a valid limit of this tracker or one of its ancestors is // exceeded. bool AnyLimitExceeded(); // If this tracker has a limit, checks the limit and attempts to free up some memory if // the limit is exceeded by calling any added GC functions. Returns true if the limit is // exceeded after calling the GC functions. Returns false if there is no limit. bool LimitExceeded() { return limit_ >= 0 && limit_ < consumption(); } // Returns the maximum consumption that can be made without exceeding the limit on // this tracker or any of its parents. Returns int64_t::max() if there are no // limits and a negative value if any limit is already exceeded. int64_t SpareCapacity() const; int64_t limit() const { return limit_; } bool has_limit() const { return limit_ >= 0; } const std::string& id() const { return id_; } // Returns the memory consumed in bytes. int64_t consumption() const { return consumption_.current_value(); } int64_t peak_consumption() const { return consumption_.max_value(); } // Retrieve the parent tracker, or NULL If one is not set. std::shared_ptr<MemTracker> parent() const { return parent_; } // Returns a textual representation of the tracker that is likely (but not // guaranteed) to be globally unique. std::string ToString() const; private: // byte_limit < 0 means no limit // 'id' is the label for LogUsage() and web UI. MemTracker(int64_t byte_limit, const std::string& id, std::shared_ptr<MemTracker> parent); // Further initializes the tracker. void Init(); // Adds tracker to child_trackers_. void AddChildTracker(const std::shared_ptr<MemTracker>& tracker); // Variant of FindTracker() that must be called with a non-NULL parent. static bool FindTrackerInternal( const std::string& id, std::shared_ptr<MemTracker>* tracker, const std::shared_ptr<MemTracker>& parent); // Creates the root tracker. static void CreateRootTracker(); int64_t limit_; const std::string id_; const std::string descr_; std::shared_ptr<MemTracker> parent_; HighWaterMark consumption_; // this tracker plus all of its ancestors std::vector<MemTracker*> all_trackers_; // all_trackers_ with valid limits std::vector<MemTracker*> limit_trackers_; // All the child trackers of this tracker. Used for error reporting and // listing only (i.e. updating the consumption of a parent tracker does not // update that of its children). mutable Mutex child_trackers_lock_; std::list<std::weak_ptr<MemTracker>> child_trackers_; // Iterator into parent_->child_trackers_ for this object. Stored to have O(1) // remove. std::list<std::weak_ptr<MemTracker>>::iterator child_tracker_it_; }; // An std::allocator that manipulates a MemTracker during allocation // and deallocation. template<typename T, typename Alloc = std::allocator<T> > class MemTrackerAllocator : public Alloc { public: typedef typename Alloc::pointer pointer; typedef typename Alloc::const_pointer const_pointer; typedef typename Alloc::size_type size_type; explicit MemTrackerAllocator(std::shared_ptr<MemTracker> mem_tracker) : mem_tracker_(std::move(mem_tracker)) {} // This constructor is used for rebinding. template <typename U> MemTrackerAllocator(const MemTrackerAllocator<U>& allocator) : Alloc(allocator), mem_tracker_(allocator.mem_tracker()) { } ~MemTrackerAllocator() { } pointer allocate(size_type n, const_pointer hint = 0) { // Ideally we'd use TryConsume() here to enforce the tracker's limit. // However, that means throwing bad_alloc if the limit is exceeded, and // it's not clear that the rest of Kudu can handle that. mem_tracker_->Consume(n * sizeof(T)); return Alloc::allocate(n, hint); } void deallocate(pointer p, size_type n) { Alloc::deallocate(p, n); mem_tracker_->Release(n * sizeof(T)); } // This allows an allocator<T> to be used for a different type. template <class U> struct rebind { typedef MemTrackerAllocator<U, typename Alloc::template rebind<U>::other> other; }; const std::shared_ptr<MemTracker>& mem_tracker() const { return mem_tracker_; } private: std::shared_ptr<MemTracker> mem_tracker_; }; // Convenience class that adds memory consumption to a tracker when declared, // releasing it when the end of scope is reached. class ScopedTrackedConsumption { public: ScopedTrackedConsumption(std::shared_ptr<MemTracker> tracker, int64_t to_consume) : tracker_(std::move(tracker)), consumption_(to_consume) { DCHECK(tracker_); tracker_->Consume(consumption_); } void Reset(int64_t new_consumption) { // Consume(-x) is the same as Release(x). tracker_->Consume(new_consumption - consumption_); consumption_ = new_consumption; } ~ScopedTrackedConsumption() { tracker_->Release(consumption_); } int64_t consumption() const { return consumption_; } private: std::shared_ptr<MemTracker> tracker_; int64_t consumption_; }; } // namespace kudu #endif // KUDU_UTIL_MEM_TRACKER_H
36.404255
92
0.729008
[ "object", "vector" ]
fc8937cd52f14472ce3371fc8dd9ed31f46e506c
12,924
c
C
lib/package_remove.c
abenson/xbps
3a00a9eb9b5ef944551c272ef35cca41df197d46
[ "BSD-2-Clause" ]
null
null
null
lib/package_remove.c
abenson/xbps
3a00a9eb9b5ef944551c272ef35cca41df197d46
[ "BSD-2-Clause" ]
null
null
null
lib/package_remove.c
abenson/xbps
3a00a9eb9b5ef944551c272ef35cca41df197d46
[ "BSD-2-Clause" ]
null
null
null
/*- * Copyright (c) 2009-2015 Juan Romero Pardines. * 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 AUTHOR ``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 AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdio.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <dirent.h> #include <libgen.h> #include <fcntl.h> #include <unistd.h> #include "xbps_api_impl.h" static bool check_remove_pkg_files(struct xbps_handle *xhp, xbps_dictionary_t pkgd, const char *pkgver, uid_t euid) { struct stat st; xbps_array_t array; xbps_object_iterator_t iter; xbps_object_t obj; const char *objs[] = { "files", "conf_files", "links", "dirs" }; const char *file; char path[PATH_MAX]; bool fail = false; for (uint8_t i = 0; i < __arraycount(objs); i++) { array = xbps_dictionary_get(pkgd, objs[i]); if (array == NULL || xbps_array_count(array) == 0) continue; iter = xbps_array_iter_from_dict(pkgd, objs[i]); if (iter == NULL) continue; while ((obj = xbps_object_iterator_next(iter))) { xbps_dictionary_get_cstring_nocopy(obj, "file", &file); snprintf(path, sizeof(path), "%s/%s", xhp->rootdir, file); /* * Check if effective user ID owns the file; this is * enough to ensure the user has write permissions * on the directory. */ if (euid == 0 || (!lstat(path, &st) && euid == st.st_uid)) { /* success */ continue; } if (errno != ENOENT) { /* * only bail out if something else than ENOENT * is returned. */ int rv = errno; if (rv == 0) { /* lstat succeeds but euid != uid */ rv = EPERM; } fail = true; xbps_set_cb_state(xhp, XBPS_STATE_REMOVE_FILE_FAIL, rv, pkgver, "%s: cannot remove `%s': %s", pkgver, file, strerror(rv)); } errno = 0; } xbps_object_iterator_release(iter); } return fail; } struct order_length_t { unsigned int pos; size_t len; }; static int cmp_order_length(const void *l1, const void *l2) { size_t a = ((const struct order_length_t*)l1)->len; size_t b = ((const struct order_length_t*)l2)->len; return (a < b) - (b < a); } static int remove_pkg_files(struct xbps_handle *xhp, xbps_dictionary_t dict, const char *key, const char *pkgver) { xbps_array_t array, dirs; xbps_object_iterator_t iter; xbps_object_t obj; const char *curobj = NULL; /* These are symlinks in Void and must not be removed */ const char *basesymlinks[] = { "/bin", "/sbin", "/usr/sbin", "/lib", "/lib32", "/lib64", "/usr/lib32", "/usr/lib64", "/var/run", }; int rv = 0; assert(xbps_object_type(dict) == XBPS_TYPE_DICTIONARY); assert(key != NULL); array = xbps_dictionary_get(dict, key); if (xbps_array_count(array) == 0) return 0; iter = xbps_array_iter_from_dict(dict, key); if (iter == NULL) return ENOMEM; if (strcmp(key, "files") == 0) curobj = "file"; else if (strcmp(key, "conf_files") == 0) curobj = "configuration file"; else if (strcmp(key, "links") == 0) curobj = "link"; else if (strcmp(key, "dirs") == 0) curobj = "directory"; xbps_object_iterator_reset(iter); /* * directories must be ordered before removal */ if (strcmp(key, "dirs") == 0) { unsigned int i = 0; unsigned int n = xbps_array_count(array); struct order_length_t *lengths = (struct order_length_t*) malloc(sizeof(struct order_length_t) * n); if (lengths == NULL) return ENOMEM; while ((obj = xbps_object_iterator_next(iter))) { const char *file; xbps_dictionary_get_cstring_nocopy(obj, "file", &file); lengths[i].len = strlen(file); lengths[i].pos = i; i++; } qsort(lengths, n, sizeof(struct order_length_t), cmp_order_length); dirs = xbps_array_create_with_capacity(n); for (i = 0; i < n; i++) { xbps_array_add(dirs, xbps_array_get(array, lengths[i].pos)); } xbps_object_iterator_release(iter); iter = xbps_array_iterator(dirs); free(lengths); } xbps_object_iterator_reset(iter); while ((obj = xbps_object_iterator_next(iter))) { const char *file, *sha256; char path[PATH_MAX]; bool found; xbps_dictionary_get_cstring_nocopy(obj, "file", &file); if (strcmp(xhp->rootdir, "/") == 0) snprintf(path, sizeof(path), "%s", file); else snprintf(path, sizeof(path), "%s%s", xhp->rootdir, file); if ((strcmp(key, "files") == 0) || (strcmp(key, "conf_files") == 0)) { /* * Check SHA256 hash in regular files and * configuration files. */ xbps_dictionary_get_cstring_nocopy(obj, "sha256", &sha256); rv = xbps_file_hash_check(path, sha256); if (rv == ENOENT) { /* missing file, ignore it */ xbps_set_cb_state(xhp, XBPS_STATE_REMOVE_FILE_HASH_FAIL, rv, pkgver, "%s: failed to check hash for %s `%s': %s", pkgver, curobj, file, strerror(rv)); rv = 0; continue; } else if (rv == ERANGE) { rv = 0; if ((xhp->flags & XBPS_FLAG_FORCE_REMOVE_FILES) == 0) { xbps_set_cb_state(xhp, XBPS_STATE_REMOVE_FILE_HASH_FAIL, 0, pkgver, "%s: %s `%s' SHA256 mismatch, " "preserving file", pkgver, curobj, file); continue; } else { xbps_set_cb_state(xhp, XBPS_STATE_REMOVE_FILE_HASH_FAIL, 0, pkgver, "%s: %s `%s' SHA256 mismatch, " "forcing removal", pkgver, curobj, file); } } else if (rv != 0 && rv != ERANGE) { xbps_set_cb_state(xhp, XBPS_STATE_REMOVE_FILE_HASH_FAIL, rv, pkgver, "%s: [remove] failed to check hash for " "%s `%s': %s", pkgver, curobj, file, strerror(rv)); break; } } /* * Make sure to not remove any symlink of root directory. */ found = false; for (uint8_t i = 0; i < __arraycount(basesymlinks); i++) { if (strcmp(file, basesymlinks[i]) == 0) { found = true; xbps_dbg_printf(xhp, "[remove] %s ignoring " "%s removal\n", pkgver, file); break; } } if (found) { continue; } if (strcmp(key, "links") == 0) { const char *target = NULL; char *lnk; xbps_dictionary_get_cstring_nocopy(obj, "target", &target); assert(target); lnk = xbps_symlink_target(xhp, path, target); if (lnk == NULL) { xbps_dbg_printf(xhp, "[remove] %s " "symlink_target: %s\n", path, strerror(errno)); continue; } if (strcmp(lnk, target)) { xbps_dbg_printf(xhp, "[remove] %s symlink " "modified (stored %s current %s)\n", path, target, lnk); if ((xhp->flags & XBPS_FLAG_FORCE_REMOVE_FILES) == 0) { free(lnk); continue; } } free(lnk); } /* * Remove the object if possible. */ if (remove(path) == -1) { xbps_set_cb_state(xhp, XBPS_STATE_REMOVE_FILE_FAIL, errno, pkgver, "%s: failed to remove %s `%s': %s", pkgver, curobj, file, strerror(errno)); } else { /* success */ xbps_set_cb_state(xhp, XBPS_STATE_REMOVE_FILE, 0, pkgver, "Removed %s `%s'", curobj, file); } } xbps_object_iterator_release(iter); return rv; } int HIDDEN xbps_remove_pkg(struct xbps_handle *xhp, const char *pkgver, bool update) { xbps_dictionary_t pkgd = NULL, pkgfilesd = NULL; char *pkgname, metafile[PATH_MAX]; int rv = 0; pkg_state_t state = 0; uid_t euid; assert(xhp); assert(pkgver); pkgname = xbps_pkg_name(pkgver); assert(pkgname); euid = geteuid(); if ((pkgd = xbps_pkgdb_get_pkg(xhp, pkgname)) == NULL) { rv = errno; xbps_dbg_printf(xhp, "[remove] cannot find %s in pkgdb: %s\n", pkgver, strerror(rv)); goto out; } if ((rv = xbps_pkg_state_dictionary(pkgd, &state)) != 0) { xbps_dbg_printf(xhp, "[remove] cannot find %s in pkgdb: %s\n", pkgver, strerror(rv)); goto out; } xbps_dbg_printf(xhp, "attempting to remove %s state %d\n", pkgver, state); if (!update) xbps_set_cb_state(xhp, XBPS_STATE_REMOVE, 0, pkgver, NULL); if (chdir(xhp->rootdir) == -1) { rv = errno; xbps_set_cb_state(xhp, XBPS_STATE_REMOVE_FAIL, rv, pkgver, "%s: [remove] failed to chdir to rootdir `%s': %s", pkgver, xhp->rootdir, strerror(rv)); goto out; } /* internalize pkg files dictionary from metadir */ snprintf(metafile, sizeof(metafile), "%s/.%s-files.plist", xhp->metadir, pkgname); pkgfilesd = xbps_plist_dictionary_from_file(xhp, metafile); if (pkgfilesd == NULL) xbps_dbg_printf(xhp, "WARNING: metaplist for %s " "doesn't exist!\n", pkgver); /* If package was "half-removed", remove it fully. */ if (state == XBPS_PKG_STATE_HALF_REMOVED) goto purge; /* * Run the pre remove action and show pre-remove message if exists. */ rv = xbps_pkg_exec_script(xhp, pkgd, "remove-script", "pre", update); if (rv != 0) { xbps_set_cb_state(xhp, XBPS_STATE_REMOVE_FAIL, errno, pkgver, "%s: [remove] REMOVE script failed to " "execute pre ACTION: %s", pkgver, strerror(rv)); goto out; } /* show remove-msg if exists */ if ((rv = xbps_cb_message(xhp, pkgd, "remove-msg")) != 0) goto out; /* unregister alternatives */ if (update) xbps_dictionary_set_bool(pkgd, "alternatives-update", true); if ((rv = xbps_alternatives_unregister(xhp, pkgd)) != 0) goto out; /* * If updating a package, we just need to execute the current * pre-remove action target and we are done. Its files will be * overwritten later in unpack phase. */ if (update) { free(pkgname); return 0; } if (pkgfilesd) { /* * Do the removal in 2 phases: * 1- check if user has enough perms to remove all entries * 2- perform removal */ if (check_remove_pkg_files(xhp, pkgfilesd, pkgver, euid)) { rv = EPERM; goto out; } /* Remove links */ if ((rv = remove_pkg_files(xhp, pkgfilesd, "links", pkgver)) != 0) goto out; /* Remove regular files */ if ((rv = remove_pkg_files(xhp, pkgfilesd, "files", pkgver)) != 0) goto out; /* Remove configuration files */ if ((rv = remove_pkg_files(xhp, pkgfilesd, "conf_files", pkgver)) != 0) goto out; /* Remove dirs */ if ((rv = remove_pkg_files(xhp, pkgfilesd, "dirs", pkgver)) != 0) goto out; } /* * Execute the post REMOVE action if file exists and we aren't * updating the package. */ rv = xbps_pkg_exec_script(xhp, pkgd, "remove-script", "post", false); if (rv != 0) { xbps_set_cb_state(xhp, XBPS_STATE_REMOVE_FAIL, rv, pkgver, "%s: [remove] REMOVE script failed to execute " "post ACTION: %s", pkgver, strerror(rv)); goto out; } /* * Set package state to "half-removed". */ rv = xbps_set_pkg_state_dictionary(pkgd, XBPS_PKG_STATE_HALF_REMOVED); if (rv != 0) { xbps_set_cb_state(xhp, XBPS_STATE_REMOVE_FAIL, rv, pkgver, "%s: [remove] failed to set state to half-removed: %s", pkgver, strerror(rv)); goto out; } purge: /* * Execute the purge REMOVE action if file exists. */ rv = xbps_pkg_exec_script(xhp, pkgd, "remove-script", "purge", false); if (rv != 0) { xbps_set_cb_state(xhp, XBPS_STATE_REMOVE_FAIL, rv, pkgver, "%s: REMOVE script failed to execute " "purge ACTION: %s", pkgver, strerror(rv)); goto out; } /* * Remove package metadata plist. */ if (remove(metafile) == -1) { if (errno != ENOENT) { xbps_set_cb_state(xhp, XBPS_STATE_REMOVE_FAIL, rv, pkgver, "%s: failed to remove metadata file: %s", pkgver, strerror(errno)); } } /* * Unregister package from pkgdb. */ xbps_dictionary_remove(xhp->pkgdb, pkgname); xbps_dbg_printf(xhp, "[remove] unregister %s returned %d\n", pkgver, rv); xbps_set_cb_state(xhp, XBPS_STATE_REMOVE_DONE, 0, pkgver, NULL); out: if (pkgname != NULL) free(pkgname); if (rv != 0) { xbps_set_cb_state(xhp, XBPS_STATE_REMOVE_FAIL, rv, pkgver, "%s: failed to remove package: %s", pkgver, strerror(rv)); } return rv; }
27.265823
83
0.64593
[ "object" ]
fc973f12abbbee8d0025888e2874c9951628cd9b
2,006
h
C
AWSDK.framework/Versions/A/Headers/AWDeviceStatusConfiguration.h
shardulnavare8/gps
0c962668dd9c68f83938c8f38855e96b186a5465
[ "Apache-2.0" ]
null
null
null
AWSDK.framework/Versions/A/Headers/AWDeviceStatusConfiguration.h
shardulnavare8/gps
0c962668dd9c68f83938c8f38855e96b186a5465
[ "Apache-2.0" ]
null
null
null
AWSDK.framework/Versions/A/Headers/AWDeviceStatusConfiguration.h
shardulnavare8/gps
0c962668dd9c68f83938c8f38855e96b186a5465
[ "Apache-2.0" ]
null
null
null
/* AirWatch iOS Software Development Kit Copyright © 2012 AirWatch. All rights reserved. Unless required by applicable law, this Software Development Kit and sample code is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. AirWatch expressly disclaims any and all liability resulting from User’s use of this Software Development Kit. Any modification made to the SDK must have written approval by AirWatch. */ /*! \file AWDeviceStatusConfiguration.h */ /** @brief Configuration used to setup a `AWDeviceStatusController`. @details `AWDeviceStatusConfiguration` is a container that holds server details to retrieve device information. @version 3.7.1 */ @interface AWDeviceStatusConfiguration : NSObject { } /** The URL of the AirWatch device services. This value must conform to RFC 1808. Please see http://www.ietf.org/rfc/rfc1808.txt for more information. */ @property (nonatomic, copy) NSURL *deviceServicesURL AW_DEPRECATED_ATTRIBUTE; /** The path of the device info endpoint. The default value is DeviceInfo.svc. */ @property (nonatomic, copy) NSString *endpointPath AW_DEPRECATED_ATTRIBUTE; /** The device status service action to perform. The default is GetDeviceStatus. */ @property (nonatomic, copy) NSString *deviceStatusAction; /** The designated intializer to create device management configurations. @brief AWDeviceStatusController can be configured by getting AWDeviceStatusConfiguration object. Creates a device management configuration with the specified parameters. @return A new device management configuration object. @param hostName The host name of the AirWatch console conforming to RFC 1808. @param endpointPath The endpoint path of the device info service. @param deviceStatusAction The device status service action to perform. */ - (id)initWithHostName:(NSString *)hostName endpointPath:(NSString *)endpointPath deviceStatusAction:(NSString *)deviceStatusAction; @end
35.821429
218
0.785145
[ "object" ]
fc9aaef03087c105f55725c3554c701273418907
4,519
h
C
y/y/reflect/reflect.h
gan74/yave
c71b5dd7c05b1aa39c59a8071fc243c1472e71d1
[ "MIT" ]
null
null
null
y/y/reflect/reflect.h
gan74/yave
c71b5dd7c05b1aa39c59a8071fc243c1472e71d1
[ "MIT" ]
null
null
null
y/y/reflect/reflect.h
gan74/yave
c71b5dd7c05b1aa39c59a8071fc243c1472e71d1
[ "MIT" ]
null
null
null
/******************************* Copyright (c) 2016-2022 Grégoire Angerand 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 Y_REFLECT_REFLECT_H #define Y_REFLECT_REFLECT_H #include "traits.h" #include <y/utils.h> #include <y/utils/hash.h> #include <y/utils/recmacros.h> #include <tuple> #include <string_view> #include <tuple> namespace y { namespace reflect { template<typename T> struct NamedObject { T& object; const std::string_view name; const u32 name_hash; inline constexpr NamedObject(T& t, std::string_view n, u32 h) : object(t), name(n), name_hash(h) { } inline constexpr NamedObject<const T> make_const_ref() const { return NamedObject<const T>(object, name, name_hash); } }; namespace detail { template<usize I, typename Tpl, typename F> inline void explore_member(Tpl&& tpl, F&& func) { if constexpr(I < std::tuple_size_v<std::decay_t<Tpl>>) { auto&& elem = std::get<I>(tpl); func(elem.name, elem.object); explore_member<I + 1>(tpl, func); } } template<typename T, typename F> void explore_one(T&& t, F&& func); template<typename C, typename F> inline void explore_collection(C&& col, F&& func) { for(auto&& item : col) { explore_one(item, func); } } template<usize I, typename Tpl, typename F> inline void explore_tuple(Tpl&& tpl, F&& func) { if constexpr(I < std::tuple_size_v<std::decay_t<Tpl>>) { explore_one(std::get<I>(tpl), func); explore_tuple<I + 1>(tpl, func); } } template<usize I, typename Tpl, typename F> inline void explore_named_tuple(Tpl&& tpl, F&& func) { if constexpr(I < std::tuple_size_v<std::decay_t<Tpl>>) { explore_one(std::get<I>(tpl).object, func); explore_named_tuple<I + 1>(tpl, func); } } template<typename T, typename F> void explore_one(T&& t, F&& func) { if constexpr(has_reflect_v<T>) { auto elems = t._y_reflect(); explore_named_tuple<0>(elems, func); } else if constexpr(is_tuple_v<T>) { explore_tuple<0>(t); } else if constexpr(is_std_ptr_v<T> || std::is_pointer_v<T>) { if(t != nullptr) { explore_one(*t, func); } } else if constexpr(is_iterable_v<T>) { explore_collection(t, func); } func(t); } } template<typename T, typename F> inline void explore_recursive(T&& t, F&& func) { detail::explore_one(t, func); } template<typename T, typename F> inline void explore_members(T&& t, F&& func) { if constexpr(has_reflect_v<T>) { auto elems = t._y_reflect(); detail::explore_member<0>(elems, func); } } Y_TODO(manage inherited objects) // https://godbolt.org/z/b6j3Ts #define y_reflect_create_item_name_hash(name) y::force_ct<y::ct_str_hash(name)>() #define y_reflect_create_item(object) y::reflect::NamedObject{object, #object, y_reflect_create_item_name_hash(#object)}, #define y_reflect_refl_qual(qual, ...) template<typename = void> auto _y_reflect() qual { return std::tuple{Y_REC_MACRO(Y_MACRO_MAP(y_reflect_create_item, __VA_ARGS__))}; } #define y_reflect_empty() template<typename = void> auto _y_reflect() const { return std::tuple<>{}; } #define y_reflect(...) \ y_reflect_refl_qual(/* */, __VA_ARGS__) \ y_reflect_refl_qual(const, __VA_ARGS__) } } #endif // Y_SERDE3_REFLECT_H
30.741497
173
0.660102
[ "object" ]
fca50584305667e696fe5390e3054297d8ba3e87
4,484
h
C
tf2_src/utils/tfstats/regexp/include/jm/jstack.h
d3fc0n6/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
4
2021-10-03T05:16:55.000Z
2021-12-28T16:49:27.000Z
tf2_src/utils/tfstats/regexp/include/jm/jstack.h
Counter2828/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
null
null
null
tf2_src/utils/tfstats/regexp/include/jm/jstack.h
Counter2828/TeamFortress2
1b81dded673d49adebf4d0958e52236ecc28a956
[ "MIT" ]
3
2022-02-02T18:09:58.000Z
2022-03-06T18:54:39.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ // //=============================================================================// /* * * Copyright (c) 1998-9 * Dr John Maddock * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Dr John Maddock makes no representations * about the suitability of this software for any purpose. * It is provided "as is" without express or implied warranty. * */ /* * FILE jstack.h * VERSION 2.12 */ #ifndef __JSTACH_H #define __JSTACK_H #ifndef JM_CFG_H #include <jm/jm_cfg.h> #endif JM_NAMESPACE(__JM) // // class jstack // simplified stack optimised for push/peek/pop // operations, we could use std::stack<std::vector<T>> instead... // template <class T, class Allocator JM_DEF_ALLOC_PARAM(T) > class jstack { private: typedef JM_MAYBE_TYPENAME REBIND_TYPE(unsigned char, Allocator) alloc_type; typedef typename REBIND_TYPE(T, Allocator)::size_type size_type; struct node { node* next; T* start; // first item T* end; // last item T* last; // end of storage }; // // empty base member optimisation: struct data : public alloc_type { unsigned char buf[sizeof(T)*16]; data(const Allocator& a) : alloc_type(a){} }; data alloc_inst; mutable node* stack; mutable node* unused; node base; size_type block_size; void RE_CALL pop_aux()const; void RE_CALL push_aux(); public: jstack(size_type n = 64, const Allocator& a = Allocator()); ~jstack(); node* RE_CALL get_node() { node* new_stack = (node*)alloc_inst.allocate(sizeof(node) + sizeof(T) * block_size); new_stack->last = (T*)(new_stack+1); new_stack->start = new_stack->end = new_stack->last + block_size; new_stack->next = 0; return new_stack; } bool RE_CALL empty() { return (stack->start == stack->end) && (stack->next == 0); } bool RE_CALL good() { return (stack->start != stack->end) || (stack->next != 0); } T& RE_CALL peek() { if(stack->start == stack->end) pop_aux(); return *stack->end; } const T& RE_CALL peek()const { if(stack->start == stack->end) pop_aux(); return *stack->end; } void RE_CALL pop() { if(stack->start == stack->end) pop_aux(); jm_destroy(stack->end); ++(stack->end); } void RE_CALL pop(T& t) { if(stack->start == stack->end) pop_aux(); t = *stack->end; jm_destroy(stack->end); ++(stack->end); } void RE_CALL push(const T& t) { if(stack->end == stack->last) push_aux(); --(stack->end); jm_construct(stack->end, t); } }; template <class T, class Allocator> jstack<T, Allocator>::jstack(size_type n, const Allocator& a) : alloc_inst(a) { unused = 0; block_size = n; stack = &base; base.last = (T*)alloc_inst.buf; base.end = base.start = base.last + 16; base.next = 0; } template <class T, class Allocator> void RE_CALL jstack<T, Allocator>::push_aux() { // make sure we have spare space on TOS: register node* new_node; if(unused) { new_node = unused; unused = new_node->next; new_node->next = stack; stack = new_node; } else { new_node = get_node(); new_node->next = stack; stack = new_node; } } template <class T, class Allocator> void RE_CALL jstack<T, Allocator>::pop_aux()const { // make sure that we have a valid item // on TOS: jm_assert(stack->next); register node* p = stack; stack = p->next; p->next = unused; unused = p; } template <class T, class Allocator> jstack<T, Allocator>::~jstack() { node* condemned; while(good()) pop(); while(unused) { condemned = unused; unused = unused->next; alloc_inst.deallocate((unsigned char*)condemned, sizeof(node) + sizeof(T) * block_size); } while(stack != &base) { condemned = stack; stack = stack->next; alloc_inst.deallocate((unsigned char*)condemned, sizeof(node) + sizeof(T) * block_size); } } JM_END_NAMESPACE #endif
21.352381
94
0.599242
[ "vector" ]
fca7ec396b7c3e44500443832d9776e33ad6bcf0
1,196
h
C
src/engine/platform/platform.h
RichardMarks/sawd-revival
670aff96e81b6cedf706fa891ca4d2b57ebdc4b4
[ "MIT" ]
null
null
null
src/engine/platform/platform.h
RichardMarks/sawd-revival
670aff96e81b6cedf706fa891ca4d2b57ebdc4b4
[ "MIT" ]
null
null
null
src/engine/platform/platform.h
RichardMarks/sawd-revival
670aff96e81b6cedf706fa891ca4d2b57ebdc4b4
[ "MIT" ]
null
null
null
#ifndef PLATFORM_H #define PLATFORM_H #include <cstdio> #include <allegro5/allegro5.h> #include <allegro5/allegro_font.h> #include <allegro5/allegro_ttf.h> #include <allegro5/allegro_image.h> #include <allegro5/allegro_audio.h> #include <allegro5/allegro_acodec.h> #include "engine/clib/clib.h" #include "controller.h" class Platform { public: bool initialize(int screenWidth, int screenHeight); void destroy(); void openWindow(); void update(); void render(); bool isReadyToDraw(); bool isReadyToUpdate(); bool running; int frames; float width; float height; float scale; float mouseX; float mouseY; unsigned char key[ALLEGRO_KEY_MAX]; void drawPCFontCharacter(float x, float y, unsigned char character, unsigned short attributes); void copyConsoleBufferToDisplayBuffer(); ALLEGRO_TIMER *timer; ALLEGRO_EVENT_QUEUE *queue; ALLEGRO_DISPLAY *disp; ALLEGRO_BITMAP *displayBuffer; ALLEGRO_FONT *debugFont; ALLEGRO_EVENT event; ALLEGRO_COLOR palette[16]; clib *cl; ALLEGRO_BITMAP *pcFontBitmap; bool redraw; bool ticked; float bufferX; float bufferY; float bufferW; float bufferH; _CONTROLLER p1; }; #endif // !PLATFORM_H
19.290323
97
0.744147
[ "render" ]
fca979262a11862d1c7c28bd7a750e1cff7791c1
4,271
h
C
HITSIC_RT1052_MCUX/rtcesl/amclib/AMCLIB_PMSMBemfObsrvAB_A32.h
HITSIC/HITSIC_RT1052
05b0510e65a09b1de2de8e3e49a9755c2ca454e5
[ "Apache-2.0" ]
1
2020-09-21T16:19:51.000Z
2020-09-21T16:19:51.000Z
HITSIC_RT1052_MCUX/rtcesl/amclib/AMCLIB_PMSMBemfObsrvAB_A32.h
HITSIC/HITSIC_RT1052
05b0510e65a09b1de2de8e3e49a9755c2ca454e5
[ "Apache-2.0" ]
null
null
null
HITSIC_RT1052_MCUX/rtcesl/amclib/AMCLIB_PMSMBemfObsrvAB_A32.h
HITSIC/HITSIC_RT1052
05b0510e65a09b1de2de8e3e49a9755c2ca454e5
[ "Apache-2.0" ]
1
2020-10-07T08:45:45.000Z
2020-10-07T08:45:45.000Z
/******************************************************************************* * * Copyright (c) 2013 - 2016, Freescale Semiconductor, Inc. * Copyright 2016-2017 NXP * * SPDX-License-Identifier: BSD-3-Clause * * ****************************************************************************//*! * * @brief Algorithm of PMSM Back Electromotive Force observer in stationary * reference frame * *******************************************************************************/ #ifndef _AMCLIB_PMSM_BEMF_OBSRV_A32_AB_H_ #define _AMCLIB_PMSM_BEMF_OBSRV_A32_AB_H_ #if defined(__cplusplus) extern "C" { #endif /****************************************************************************** * Includes ******************************************************************************/ #include "gflib.h" #include "gmclib.h" /****************************************************************************** * Macros ******************************************************************************/ #define AMCLIB_PMSMBemfObsrvAB_F16_C(psIAlBe, psUAlBe, f16Speed, psCtrl) \ AMCLIB_PMSMBemfObsrvAB_F16_FC(psIAlBe, psUAlBe, f16Speed, psCtrl) #define AMCLIB_PMSMBemfObsrvABInit_F16_Ci(psCtrl) \ AMCLIB_PMSMBemfObsrvABInit_F16_FCi(psCtrl) /****************************************************************************** * Types ******************************************************************************/ typedef struct { GMCLIB_2COOR_ALBE_T_F32 sEObsrv; /* Estimated back-EMF voltage - alpha,beta */ GMCLIB_2COOR_ALBE_T_F32 sIObsrv; /* Estimated current - alpha,beta */ /* Observer parameters for controllers */ struct { frac32_t f32IAlpha_1; /* Integral part state variable for alpha coefficient */ frac32_t f32IBeta_1; /* Integral part state variable for beta coefficient */ acc32_t a32PGain; /* Observer proportional gain coefficient */ acc32_t a32IGain; /* Observer integral gain coefficient */ } sCtrl; /* Configuration parameters */ acc32_t a32IGain; /* Current scaling coefficient */ acc32_t a32UGain; /* Voltage scaling coefficient */ acc32_t a32WIGain; /* Angular speed scaling coefficient */ acc32_t a32EGain; /* Back-emf scaling coefficient */ /* Unity vector */ GMCLIB_2COOR_SINCOS_T_F16 sUnityVctr; } AMCLIB_BEMF_OBSRV_AB_T_A32; /****************************************************************************** * Exported function prototypes ******************************************************************************/ extern void AMCLIB_PMSMBemfObsrvAB_F16_FC(const GMCLIB_2COOR_ALBE_T_F16 *psIAlBe, const GMCLIB_2COOR_ALBE_T_F16 *psUAlBe, frac16_t f16Speed, AMCLIB_BEMF_OBSRV_AB_T_A32 *psCtrl); /****************************************************************************** * Inline functions ******************************************************************************/ /***************************************************************************//*! * * @brief PMSM BEMF in AB reference frame initialization * * @param ptr AMCLIB_BEMF_OBSRV_AB_T_A32 *psCtrl - pointer to the parameters of the observer * * @param in None * * @return None * * @remarks Initializes the structure of the PMSM BEMF in AB reference frame * * sIObsrv_f32Alpha = 0; * sIObsrv_f32beta = 0; * sCtrl_f32IAlpha_1= 0; * sCtrl_f32IBeta_1 = 0; * ****************************************************************************/ static inline void AMCLIB_PMSMBemfObsrvABInit_F16_FCi(AMCLIB_BEMF_OBSRV_AB_T_A32 *psCtrl) { psCtrl -> sIObsrv.f32Alpha = FRAC32(0.0); psCtrl -> sIObsrv.f32Beta = FRAC32(0.0); psCtrl -> sCtrl.f32IAlpha_1= FRAC32(0.0); psCtrl -> sCtrl.f32IBeta_1 = FRAC32(0.0); } #if defined(__cplusplus) } #endif #endif /* _AMCLIB_PMSM_BEMF_OBSRV_A32_AB_H_ */
40.67619
102
0.447904
[ "vector" ]
fcb35da4d01297e54a131157d5bf1978c1bf1b16
5,570
c
C
src/compiler/lexer.c
k-mrm/maxc
49619b71697b3a8c62afb4c02d287f1e14267462
[ "MIT" ]
46
2019-03-16T06:32:49.000Z
2021-04-28T09:48:58.000Z
src/compiler/lexer.c
k-mrm/maxc
49619b71697b3a8c62afb4c02d287f1e14267462
[ "MIT" ]
3
2020-02-10T14:40:57.000Z
2020-04-16T02:10:39.000Z
src/compiler/lexer.c
k-mrm/maxc
49619b71697b3a8c62afb4c02d287f1e14267462
[ "MIT" ]
6
2019-06-29T02:41:17.000Z
2020-04-11T05:19:14.000Z
#include <stdio.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include "lexer.h" #include "error/error.h" #include "maxc.h" #include "util.h" #include "token.h" char *strndup(const char *, size_t); #define STEP() \ do { \ ++i; \ ++col; \ } while(0) #define PREV() \ do { \ --i; \ --col; \ } while(0) #define TWOCHARS(c1, c2) (src[i] == c1 && src[i + 1] == c2) static void scan(Vector *, const char *, const char *); Vector *lexer_run(const char *src, const char *fname) { Vector *tokens = new_vector(); scan(tokens, src, fname); return tokens; } static char escaped[256] = { ['a'] = '\a', ['b'] = '\b', ['f'] = '\f', ['n'] = '\n', ['r'] = '\r', ['t'] = '\t', ['v'] = '\v', ['\\'] = '\\', ['\''] = '\'', ['\"'] = '\"', ['e'] = '\033', ['E'] = '\033' }; char *escapedstrdup(const char *s, size_t n) { char buf[n+1]; int len = 0; char c; for(size_t i = 0; i < n; i++, s++) { if(*s == '\\') { i++; c = escaped[(int)*++s]; } else { c = *s; } buf[len++] = c; } char *new = malloc(sizeof(char) * (len + 1)); memset(new, 0, sizeof(char) * (len + 1)); strncpy(new, buf, sizeof(char) * len); return new; } static void scan(Vector *tk, const char *src, const char *fname) { int line = 1; int col = 1; size_t src_len = strlen(src); for(size_t i = 0; i < src_len; i++, col++) { if(isdigit(src[i])) { SrcPos start = cur_srcpos(fname, line, col); const char *buf = src + i; bool isdot = false; int len = 0; for(; isdigit(src[i]) || (src[i] == '.' && src[i+1] != '.'); i++, col++) { len++; if(src[i] == '.') { if(isdot) break; isdot = true; } } PREV(); if(src[i] == '.') { /* * 30.fibo() * ^ */ PREV(); len--; } SrcPos end = cur_srcpos(fname, line, col); char *str = strndup(buf, len); token_push_num(tk, str, len, start, end); } else if(isalpha(src[i]) || src[i] == '_') { /* (alpha|_) (alpha|digit|_)* */ const char *ident_s = src + i; SrcPos start = cur_srcpos(fname, line, col); int len = 0; for(; isalpha(src[i]) || isdigit(src[i]) || src[i] == '_'; i++, col++) { len++; } if(len > 255) { error("too long identifer"); } PREV(); char *ident = strndup(ident_s, len); SrcPos end = cur_srcpos(fname, line, col); token_push_ident(tk, ident, len, start, end); } else if(TWOCHARS('&', '&') || TWOCHARS('|', '|') || TWOCHARS('.', '.') || TWOCHARS('>', '>') || TWOCHARS('=', '>') || TWOCHARS('<', '<') || TWOCHARS('-', '>')) { SrcPos s = cur_srcpos(fname, line, col); enum tkind kind = tk_char2(src[i], src[i + 1]); STEP(); SrcPos e = cur_srcpos(fname, line, col); token_push_symbol(tk, kind, 2, s, e); } else if((src[i] == '/') && (src[i + 1] == '/')) { for(; src[i] != '\n' && src[i] != '\0'; i++, col++); PREV(); continue; } else if(strchr("(){}&|[]:.,?;@#", src[i])) { SrcPos loc = cur_srcpos(fname, line, col); enum tkind kind = tk_char1(src[i]); token_push_symbol(tk, kind, 1, loc, loc); } else if(strchr("=<>!+-*/%", src[i])) { SrcPos s = cur_srcpos(fname, line, col); SrcPos e; enum tkind kind; if(src[i + 1] == '=') { kind = tk_char2(src[i], src[i + 1]); STEP(); e = cur_srcpos(fname, line, col); token_push_symbol(tk, kind, 2, s, e); } else { kind = tk_char1(src[i]); e = cur_srcpos(fname, line, col); token_push_symbol(tk, kind, 1, s, e); } } else if(src[i] == '\"' || src[i] == '\'') { char quote = src[i]; SrcPos s = cur_srcpos(fname, line, col); STEP(); const char *buf = src + i; int len = 0; for(; src[i] != quote; i++, col++) { if(src[i] == '\n') { error("missing character:`%c`", quote); break; } len++; } SrcPos e = cur_srcpos(fname, line, col); char *str = escapedstrdup(buf, len); token_push_string(tk, str, len, s, e); } else if(src[i] == '`') { SrcPos s = cur_srcpos(fname, line, col); STEP(); const char *buf = src + i; int len = 0; for(; src[i] != '`'; i++, col++) { len++; if(src[i] == '\0') { error("missing charcter:'`'"); return; } } char *str = strndup(buf, len); SrcPos e = cur_srcpos(fname, line, col); token_push_backquote_lit(tk, str, len, s, e); } else if(isblank(src[i])) { continue; } else if(src[i] == '\n') { line++; col = 0; continue; } else { error("invalid syntax: \" %c \"", src[i]); break; } } SrcPos eof = cur_srcpos(fname, ++line, col); token_push_end(tk, eof, eof); }
25.550459
80
0.413824
[ "vector" ]
fcb48d110b26b3e61ab585c00bc53b89e3c98815
519
h
C
src/rotate_basis.h
ccao/WannSymm
3d29170c14076465d7233cdacabcf473f12487d9
[ "BSD-3-Clause" ]
15
2021-10-20T06:53:03.000Z
2022-03-17T11:46:41.000Z
src/rotate_basis.h
ccao/WannSymm
3d29170c14076465d7233cdacabcf473f12487d9
[ "BSD-3-Clause" ]
7
2021-11-06T17:12:01.000Z
2022-03-09T14:04:33.000Z
src/rotate_basis.h
ccao/WannSymm
3d29170c14076465d7233cdacabcf473f12487d9
[ "BSD-3-Clause" ]
1
2021-12-16T10:13:32.000Z
2021-12-16T10:13:32.000Z
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <complex.h> #include "constants.h" #include "vector.h" #include "wanndata.h" #include "rotate_orbital.h" #include "rotate_spinor.h" #include "rotate_ham.h" //use getrvec_and_site() #include <mkl.h> #include <mpi.h> void get_sym_op_reciprocalspace(dcomplex * sym_op, double lattice[3][3], wannorb * orb_info, int norb, int isym_in_doublegp, double rotation[3][3],double translation[3], int TR, double rot_kd[3][3], vector kpt, int flag_soc);
30.529412
225
0.728324
[ "vector" ]
fcb4c3ba20e88509ff55913ab080b74b1433b4ed
68,650
h
C
include/datoviz/vklite.h
pauljurczak/datoviz
6957dfc460f46c8f517e657e4fa0243d48f4804a
[ "MIT" ]
null
null
null
include/datoviz/vklite.h
pauljurczak/datoviz
6957dfc460f46c8f517e657e4fa0243d48f4804a
[ "MIT" ]
null
null
null
include/datoviz/vklite.h
pauljurczak/datoviz
6957dfc460f46c8f517e657e4fa0243d48f4804a
[ "MIT" ]
null
null
null
/*************************************************************************************************/ /* Light wrapper on top of the Vulkan C API */ /*************************************************************************************************/ #ifndef DVZ_VKLITE_HEADER #define DVZ_VKLITE_HEADER #define GLM_FORCE_RADIANS // #define GLM_FORCE_DEPTH_ZERO_TO_ONE #include <assert.h> #include <math.h> #include <pthread.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include <time.h> #include <unistd.h> // #include <vulkan/vulkan.h> #define GLFW_INCLUDE_VULKAN #include <GLFW/glfw3.h> #include "app.h" #include "common.h" BEGIN_INCL_NO_WARN #include <cglm/struct.h> END_INCL_NO_WARN #ifdef __cplusplus extern "C" { #endif /*************************************************************************************************/ /* Constants */ /*************************************************************************************************/ #define DVZ_MAX_BINDINGS_SIZE 32 #define DVZ_MAX_DESCRIPTOR_SETS 1024 #define DVZ_MAX_PRESENT_MODES 16 #define DVZ_MAX_PUSH_CONSTANTS 16 #define DVZ_MAX_QUEUE_FAMILIES 16 #define DVZ_MAX_QUEUES 16 #define DVZ_MAX_SWAPCHAIN_IMAGES 8 // Maximum number of command buffers per DvzCommands struct #define DVZ_MAX_COMMAND_BUFFERS_PER_SET DVZ_MAX_SWAPCHAIN_IMAGES #define DVZ_MAX_BUFFER_REGIONS_PER_SET DVZ_MAX_SWAPCHAIN_IMAGES #define DVZ_MAX_IMAGES_PER_SET DVZ_MAX_SWAPCHAIN_IMAGES #define DVZ_MAX_SEMAPHORES_PER_SET DVZ_MAX_SWAPCHAIN_IMAGES #define DVZ_MAX_FENCES_PER_SET DVZ_MAX_SWAPCHAIN_IMAGES #define DVZ_MAX_COMMANDS_PER_SUBMIT 16 #define DVZ_MAX_BARRIERS_PER_SET 8 #define DVZ_MAX_SEMAPHORES_PER_SUBMIT 8 #define DVZ_MAX_SHADERS_PER_GRAPHICS 8 #define DVZ_MAX_ATTACHMENTS_PER_RENDERPASS 8 #define DVZ_MAX_SUBPASSES_PER_RENDERPASS 8 #define DVZ_MAX_DEPENDENCIES_PER_RENDERPASS 8 #define DVZ_MAX_VERTEX_BINDINGS 16 #define DVZ_MAX_VERTEX_ATTRS 32 /*************************************************************************************************/ /* Type definitions */ /*************************************************************************************************/ typedef struct DvzQueues DvzQueues; typedef struct DvzGpu DvzGpu; typedef struct DvzWindow DvzWindow; typedef struct DvzSwapchain DvzSwapchain; typedef struct DvzCommands DvzCommands; typedef struct DvzBuffer DvzBuffer; typedef struct DvzBufferRegions DvzBufferRegions; typedef struct DvzImages DvzImages; typedef struct DvzSampler DvzSampler; typedef struct DvzSlots DvzSlots; typedef struct DvzBindings DvzBindings; typedef struct DvzCompute DvzCompute; typedef struct DvzVertexBinding DvzVertexBinding; typedef struct DvzVertexAttr DvzVertexAttr; typedef struct DvzGraphics DvzGraphics; typedef struct DvzBarrierBuffer DvzBarrierBuffer; typedef struct DvzBarrierImage DvzBarrierImage; typedef struct DvzBarrier DvzBarrier; typedef struct DvzSemaphores DvzSemaphores; typedef struct DvzFences DvzFences; typedef struct DvzRenderpass DvzRenderpass; typedef struct DvzRenderpassAttachment DvzRenderpassAttachment; typedef struct DvzRenderpassSubpass DvzRenderpassSubpass; typedef struct DvzRenderpassDependency DvzRenderpassDependency; typedef struct DvzFramebuffers DvzFramebuffers; typedef struct DvzSubmit DvzSubmit; // Forward declarations. typedef struct DvzCanvas DvzCanvas; typedef struct DvzContext DvzContext; typedef struct DvzTexture DvzTexture; typedef struct DvzGraphicsData DvzGraphicsData; // Callback definitions typedef void (*DvzGraphicsCallback)(DvzGraphicsData* data, uint32_t item_count, const void* item); /*************************************************************************************************/ /* Enums */ /*************************************************************************************************/ // Queue type. typedef enum { DVZ_QUEUE_TRANSFER = 0x01, DVZ_QUEUE_GRAPHICS = 0x02, DVZ_QUEUE_COMPUTE = 0x04, DVZ_QUEUE_PRESENT = 0x08, DVZ_QUEUE_RENDER = 0x07, DVZ_QUEUE_ALL = 0x0F, } DvzQueueType; // Command buffer type. typedef enum { DVZ_COMMAND_TRANSFERS, DVZ_COMMAND_GRAPHICS, DVZ_COMMAND_COMPUTE, DVZ_COMMAND_GUI, } DvzCommandBufferType; // Buffer type. typedef enum { DVZ_BUFFER_TYPE_UNDEFINED, DVZ_BUFFER_TYPE_STAGING, DVZ_BUFFER_TYPE_VERTEX, DVZ_BUFFER_TYPE_INDEX, DVZ_BUFFER_TYPE_UNIFORM, DVZ_BUFFER_TYPE_STORAGE, DVZ_BUFFER_TYPE_UNIFORM_MAPPABLE, DVZ_BUFFER_TYPE_COUNT, } DvzBufferType; // Graphics flags. typedef enum { DVZ_GRAPHICS_FLAGS_DEPTH_TEST = 0x0100, DVZ_GRAPHICS_FLAGS_PICK = 0x0200, } DvzGraphicsFlags; // Graphics builtins typedef enum { DVZ_GRAPHICS_NONE, DVZ_GRAPHICS_POINT, DVZ_GRAPHICS_LINE, DVZ_GRAPHICS_LINE_STRIP, DVZ_GRAPHICS_TRIANGLE, DVZ_GRAPHICS_TRIANGLE_STRIP, DVZ_GRAPHICS_TRIANGLE_FAN, DVZ_GRAPHICS_MARKER, DVZ_GRAPHICS_SEGMENT, DVZ_GRAPHICS_ARROW, DVZ_GRAPHICS_PATH, DVZ_GRAPHICS_TEXT, DVZ_GRAPHICS_IMAGE, DVZ_GRAPHICS_IMAGE_CMAP, DVZ_GRAPHICS_VOLUME_SLICE, DVZ_GRAPHICS_MESH, DVZ_GRAPHICS_FAKE_SPHERE, DVZ_GRAPHICS_VOLUME, DVZ_GRAPHICS_COUNT, DVZ_GRAPHICS_CUSTOM, } DvzGraphicsType; // Texture axis. typedef enum { DVZ_TEXTURE_AXIS_U, DVZ_TEXTURE_AXIS_V, DVZ_TEXTURE_AXIS_W, } DvzTextureAxis; // Blend type. typedef enum { DVZ_BLEND_DISABLE, DVZ_BLEND_ENABLE, } DvzBlendType; // Depth test. typedef enum { DVZ_DEPTH_TEST_DISABLE, DVZ_DEPTH_TEST_ENABLE, } DvzDepthTest; // Render pass attachment type. typedef enum { DVZ_RENDERPASS_ATTACHMENT_COLOR, DVZ_RENDERPASS_ATTACHMENT_DEPTH, DVZ_RENDERPASS_ATTACHMENT_PICK, } DvzRenderpassAttachmentType; /*************************************************************************************************/ /* Macros */ /*************************************************************************************************/ #define CMD_START \ ASSERT(cmds != NULL); \ VkCommandBuffer cb = {0}; \ uint32_t i = idx; \ cb = cmds->cmds[i]; #define CMD_START_CLIP(cnt) \ ASSERT(cmds != NULL); \ ASSERT(cnt > 0); \ if (!((cnt) == 1 || (cnt) == cmds->count)) \ log_debug("mismatch between image count and cmd buf count"); \ VkCommandBuffer cb = {0}; \ uint32_t iclip = 0; \ uint32_t i = idx; \ iclip = (cnt) == 1 ? 0 : (MIN(i, (cnt)-1)); \ ASSERT(iclip < (cnt)); \ cb = cmds->cmds[i]; #define CMD_END // #define GB 1073741824 #define MB 1048576 #define KB 1024 static char _PRETTY_SIZE[64] = {0}; static inline char* pretty_size(VkDeviceSize size) { float s = (float)size; const char* u; if (size >= GB) { s /= GB; u = "GB"; } else if (size >= MB) { s /= MB; u = "MB"; } else if (size >= KB) { s /= KB; u = "KB"; } else { u = "bytes"; } snprintf(_PRETTY_SIZE, 64, "%.1f %s", s, u); return _PRETTY_SIZE; } /*************************************************************************************************/ /* Structs */ /*************************************************************************************************/ struct DvzQueues { DvzObject obj; // Hardware supported queues // ------------------------- // Number of different queue families supported by the hardware uint32_t queue_family_count; // Properties of the queue families // VkQueueFamilyProperties queue_families[DVZ_MAX_QUEUE_FAMILIES]; bool support_transfer[DVZ_MAX_QUEUE_FAMILIES]; bool support_graphics[DVZ_MAX_QUEUE_FAMILIES]; bool support_compute[DVZ_MAX_QUEUE_FAMILIES]; bool support_present[DVZ_MAX_QUEUE_FAMILIES]; uint32_t max_queue_count[DVZ_MAX_QUEUE_FAMILIES]; // for each queue family, the max # of queues // Requested queues // ---------------- // Number of requested queues uint32_t queue_count; // Requested queue types. DvzQueueType queue_types[DVZ_MAX_QUEUES]; // the VKL type of each queue // Queues and associated command pools uint32_t queue_families[DVZ_MAX_QUEUES]; // for each family, the # of queues uint32_t queue_indices[DVZ_MAX_QUEUES]; // for each requested queue, its # within its family VkQueue queues[DVZ_MAX_QUEUES]; VkCommandPool cmd_pools[DVZ_MAX_QUEUE_FAMILIES]; }; struct DvzGpu { DvzObject obj; DvzApp* app; uint32_t idx; // GPU index within the app const char* name; VkPhysicalDevice physical_device; VkPhysicalDeviceProperties device_properties; VkPhysicalDeviceFeatures device_features; VkPhysicalDeviceMemoryProperties memory_properties; VkDeviceSize vram; // amount of VRAM uint32_t present_mode_count; VkPresentModeKHR present_modes[DVZ_MAX_PRESENT_MODES]; DvzQueues queues; VkDescriptorPool dset_pool; VkPhysicalDeviceFeatures requested_features; VkDevice device; DvzContext* context; }; struct DvzWindow { DvzObject obj; DvzApp* app; void* backend_window; uint32_t width, height; // in screen coordinates bool close_on_esc; VkSurfaceKHR surface; VkSurfaceCapabilitiesKHR caps; // current extent in pixel coordinates (framebuffers) }; struct DvzSwapchain { DvzObject obj; DvzGpu* gpu; DvzWindow* window; VkFormat format; VkPresentModeKHR present_mode; bool support_transfer; // whether the swapchain supports copying the image to another // extent in pixel coordinates if caps.currentExtent is not available uint32_t requested_width, requested_height; uint32_t img_count; uint32_t img_idx; VkSwapchainKHR swapchain; // The actual framebuffer size in pixels is found in the images size DvzImages* images; }; struct DvzCommands { DvzObject obj; DvzGpu* gpu; uint32_t queue_idx; uint32_t count; VkCommandBuffer cmds[DVZ_MAX_COMMAND_BUFFERS_PER_SET]; }; struct DvzBuffer { DvzObject obj; DvzGpu* gpu; DvzBufferType type; VkBuffer buffer; VkDeviceMemory device_memory; // Queues that need access to the buffer. uint32_t queue_count; uint32_t queues[DVZ_MAX_QUEUES]; VkDeviceSize size; VkDeviceSize allocated_size; VkBufferUsageFlags usage; VkMemoryPropertyFlags memory; void* mmap; }; struct DvzBufferRegions { DvzBuffer* buffer; uint32_t count; VkDeviceSize size; VkDeviceSize aligned_size; // NOTE: is non-null only for aligned arrays VkDeviceSize alignment; VkDeviceSize offsets[DVZ_MAX_BUFFER_REGIONS_PER_SET]; }; struct DvzImages { DvzObject obj; DvzGpu* gpu; uint32_t count; bool is_swapchain; // Queues that need access to the buffer. uint32_t queue_count; uint32_t queues[DVZ_MAX_QUEUES]; VkImageType image_type; VkImageViewType view_type; uint32_t width, height, depth; VkFormat format; VkImageLayout layout; VkImageTiling tiling; VkImageUsageFlags usage; VkMemoryPropertyFlags memory; VkImageAspectFlags aspect; VkDeviceSize size; VkImage images[DVZ_MAX_IMAGES_PER_SET]; VkDeviceMemory memories[DVZ_MAX_IMAGES_PER_SET]; VkImageView image_views[DVZ_MAX_IMAGES_PER_SET]; }; struct DvzSampler { DvzObject obj; DvzGpu* gpu; VkFilter min_filter; VkFilter mag_filter; VkSamplerAddressMode address_modes[3]; VkSampler sampler; }; struct DvzSlots { DvzObject obj; DvzGpu* gpu; uint32_t slot_count; VkDescriptorType types[DVZ_MAX_BINDINGS_SIZE]; uint32_t push_count; VkDeviceSize push_offsets[DVZ_MAX_PUSH_CONSTANTS]; VkDeviceSize push_sizes[DVZ_MAX_PUSH_CONSTANTS]; VkShaderStageFlags push_shaders[DVZ_MAX_PUSH_CONSTANTS]; VkPipelineLayout pipeline_layout; VkDescriptorSetLayout dset_layout; }; struct DvzBindings { DvzObject obj; DvzGpu* gpu; DvzSlots* slots; // a Bindings struct holds multiple almost-identical copies of descriptor sets // with the same layout, but possibly with the different idx in the DvzBuffer uint32_t dset_count; VkDescriptorSet dsets[DVZ_MAX_SWAPCHAIN_IMAGES]; DvzBufferRegions br[DVZ_MAX_BINDINGS_SIZE]; DvzImages* images[DVZ_MAX_BINDINGS_SIZE]; DvzSampler* samplers[DVZ_MAX_BINDINGS_SIZE]; }; struct DvzCompute { DvzObject obj; DvzGpu* gpu; DvzContext* context; char shader_path[1024]; const char* shader_code; VkPipeline pipeline; DvzSlots slots; DvzBindings* bindings; VkShaderModule shader_module; }; struct DvzVertexBinding { uint32_t binding; VkDeviceSize stride; }; struct DvzVertexAttr { uint32_t binding; uint32_t location; VkFormat format; VkDeviceSize offset; }; struct DvzGraphics { DvzObject obj; DvzGpu* gpu; DvzGraphicsType type; int flags; bool support_pick; void* user_data; DvzRenderpass* renderpass; uint32_t subpass; VkPrimitiveTopology topology; DvzBlendType blend_type; DvzDepthTest depth_test; VkPolygonMode polygon_mode; VkCullModeFlags cull_mode; VkFrontFace front_face; VkPipeline pipeline; DvzSlots slots; uint32_t vertex_binding_count; DvzVertexBinding vertex_bindings[DVZ_MAX_VERTEX_BINDINGS]; uint32_t vertex_attr_count; DvzVertexAttr vertex_attrs[DVZ_MAX_VERTEX_ATTRS]; uint32_t shader_count; VkShaderStageFlagBits shader_stages[DVZ_MAX_SHADERS_PER_GRAPHICS]; VkShaderModule shader_modules[DVZ_MAX_SHADERS_PER_GRAPHICS]; DvzGraphicsCallback callback; }; struct DvzBarrierBuffer { DvzBufferRegions br; bool queue_transfer; VkAccessFlags src_access; uint32_t src_queue; VkAccessFlags dst_access; uint32_t dst_queue; }; struct DvzBarrierImage { DvzImages* images; bool queue_transfer; VkAccessFlags src_access; uint32_t src_queue; VkImageLayout src_layout; VkAccessFlags dst_access; uint32_t dst_queue; VkImageLayout dst_layout; }; struct DvzBarrier { DvzObject obj; DvzGpu* gpu; // uint32_t idx; // index within the buffer regions or images VkPipelineStageFlagBits src_stage; VkPipelineStageFlagBits dst_stage; uint32_t buffer_barrier_count; DvzBarrierBuffer buffer_barriers[DVZ_MAX_BARRIERS_PER_SET]; uint32_t image_barrier_count; DvzBarrierImage image_barriers[DVZ_MAX_BARRIERS_PER_SET]; }; struct DvzFences { DvzObject obj; DvzGpu* gpu; uint32_t count; VkFence fences[DVZ_MAX_FENCES_PER_SET]; }; struct DvzSemaphores { DvzObject obj; DvzGpu* gpu; uint32_t count; VkSemaphore semaphores[DVZ_MAX_SEMAPHORES_PER_SET]; }; struct DvzRenderpassAttachment { VkImageLayout ref_layout; DvzRenderpassAttachmentType type; VkFormat format; VkImageLayout src_layout; VkImageLayout dst_layout; VkAttachmentLoadOp load_op; VkAttachmentStoreOp store_op; }; struct DvzRenderpassSubpass { uint32_t attachment_count; uint32_t attachments[DVZ_MAX_ATTACHMENTS_PER_RENDERPASS]; }; struct DvzRenderpassDependency { uint32_t src_subpass; VkPipelineStageFlags src_stage; VkAccessFlags src_access; uint32_t dst_subpass; VkPipelineStageFlags dst_stage; VkAccessFlags dst_access; }; struct DvzFramebuffers { DvzObject obj; DvzGpu* gpu; DvzRenderpass* renderpass; uint32_t attachment_count; // by definition, the framebuffers size = the first attachment's size DvzImages* attachments[DVZ_MAX_ATTACHMENTS_PER_RENDERPASS]; uint32_t framebuffer_count; VkFramebuffer framebuffers[DVZ_MAX_SWAPCHAIN_IMAGES]; }; struct DvzRenderpass { DvzObject obj; DvzGpu* gpu; uint32_t attachment_count; DvzRenderpassAttachment attachments[DVZ_MAX_ATTACHMENTS_PER_RENDERPASS]; uint32_t clear_count; VkClearValue clear_values[DVZ_MAX_ATTACHMENTS_PER_RENDERPASS]; uint32_t subpass_count; DvzRenderpassSubpass subpasses[DVZ_MAX_SUBPASSES_PER_RENDERPASS]; uint32_t dependency_count; DvzRenderpassDependency dependencies[DVZ_MAX_DEPENDENCIES_PER_RENDERPASS]; VkRenderPass renderpass; }; struct DvzSubmit { DvzObject obj; DvzGpu* gpu; uint32_t commands_count; DvzCommands* commands[DVZ_MAX_COMMANDS_PER_SUBMIT]; uint32_t wait_semaphores_count; uint32_t wait_semaphores_idx[DVZ_MAX_SEMAPHORES_PER_SUBMIT]; DvzSemaphores* wait_semaphores[DVZ_MAX_SEMAPHORES_PER_SUBMIT]; VkPipelineStageFlags wait_stages[DVZ_MAX_SEMAPHORES_PER_SUBMIT]; uint32_t signal_semaphores_count; uint32_t signal_semaphores_idx[DVZ_MAX_SEMAPHORES_PER_SUBMIT]; DvzSemaphores* signal_semaphores[DVZ_MAX_SEMAPHORES_PER_SUBMIT]; }; struct DvzTexture { DvzObject obj; DvzContext* context; DvzImages* image; DvzSampler* sampler; }; /*************************************************************************************************/ /* App */ /*************************************************************************************************/ /** * Create an application instance. * * There is typically only one App object in a given application. This object holds a pointer to * the Vulkan instance and is responsible for discovering the available GPUs. * * @param backend the backend * @returns a pointer to the created app */ DVZ_EXPORT DvzApp* dvz_app(DvzBackend backend); /** * Parse the DVZ_RUN_* environment variables and setup the application autorun accordingly. * * The DVZ_RUN_* variables may override the backend (offscreen or not), number of frames during the * run, and automatic saving of screenshot or video. * * !!! note * Currently, this function is automatically called by `dvz_app()`, and there is no need to * call it manually. * * @param app the app */ DVZ_EXPORT void dvz_autorun_env(DvzApp* app); /** * Manually setup the application autorun. * * @param app the app * @param autorun a `DvzAutorun` struct */ DVZ_EXPORT void dvz_autorun_setup(DvzApp* app, DvzAutorun autorun); /** * Destroy the application. * * This function automatically destroys all objects created within the application. * * @param app the application to destroy */ DVZ_EXPORT int dvz_app_destroy(DvzApp* app); /** * Destroy the Dear ImGui global context if it was ever initialized. */ DVZ_EXPORT void dvz_imgui_destroy(); /*************************************************************************************************/ /* GPU */ /*************************************************************************************************/ /** * Initialize a GPU. * * A GPU object is the interface to one of the GPUs on the current system. * * @param app the app * @param idx the GPU index among the system's GPUs * @returns a pointer to the created GPU object */ DVZ_EXPORT DvzGpu* dvz_gpu(DvzApp* app, uint32_t idx); /** * Find the "best" GPU on the system. * * For now, this is just the discrete GPU with the most VRAM, or the GPU with the most VRAM if * there are no discrete GPUs. * * @param app the app * @returns a pointer to the best GPU object */ DVZ_EXPORT DvzGpu* dvz_gpu_best(DvzApp* app); /** * Request some features before creating the GPU instance. * * This function needs to be called before creating the GPU with ` dvz_gpu_create()`. * * @param gpu the GPU * @param requested_features the list of requested features */ DVZ_EXPORT void dvz_gpu_request_features(DvzGpu* gpu, VkPhysicalDeviceFeatures requested_features); /** * Request a new Vulkan queue before creating the GPU. * * @param gpu the GPU * @param idx the queue index (should be regularly increasing: 0, 1, 2...) * @param type the queue type */ DVZ_EXPORT void dvz_gpu_queue(DvzGpu* gpu, uint32_t idx, DvzQueueType type); /** * Create a GPU once the features and queues have been set up. * * @param gpu the GPU * @param surface the surface on which the GPU will need to render */ DVZ_EXPORT void dvz_gpu_create(DvzGpu* gpu, VkSurfaceKHR surface); /** * Wait for a queue to be idle. * * This is one of the different GPU synchronization methods. It is not efficient as it waits until * the queue is idle. * * @param gpu the GPU * @param queue_idx the queue index */ DVZ_EXPORT void dvz_queue_wait(DvzGpu* gpu, uint32_t queue_idx); /** * Full synchronization on all GPUs. * * This function waits on all queues of all GPUs. The strongest, least efficient of the * synchronization methods. * * @param app the application instance */ DVZ_EXPORT void dvz_app_wait(DvzApp* app); /** * Full synchronization on a given GPU. * * This function waits on all queues of a given GPU. * * @param gpu the GPU */ DVZ_EXPORT void dvz_gpu_wait(DvzGpu* gpu); /** * Destroy the resources associated to a GPU. * * @param gpu the GPU */ DVZ_EXPORT void dvz_gpu_destroy(DvzGpu* gpu); /*************************************************************************************************/ /* Window */ /*************************************************************************************************/ /** * Create a blank window. * * This function is rarely used on its own. A bare window offers * no functionality that allows one to render to it with Vulkan. One needs a swapchain, an event * loop, and so on, which are provided instead at the level of the Canvas. * * @param app the application instance * @param width the window width, in pixels * @param height the window height, in pixels * @returns the window */ DVZ_EXPORT DvzWindow* dvz_window(DvzApp* app, uint32_t width, uint32_t height); /** * Get the window size, in pixels. * * @param window the window * @param[out] framebuffer_width the width, in pixels * @param[out] framebuffer_height the height, in pixels */ DVZ_EXPORT void dvz_window_get_size(DvzWindow* window, uint32_t* framebuffer_width, uint32_t* framebuffer_height); /** * Set the window size, in pixels. * * @param window the window * @param width the width, in pixels * @param height the height, in pixels */ DVZ_EXPORT void dvz_window_set_size(DvzWindow* window, uint32_t width, uint32_t height); /** * Process the pending windowing events by the backend (glfw by default). * * @param window the window */ DVZ_EXPORT void dvz_window_poll_events(DvzWindow* window); /** * Destroy a window. * * !!! warning * This function must be imperatively called *after* `dvz_swapchain_destroy()`. * * @param window the window */ DVZ_EXPORT void dvz_window_destroy(DvzWindow* window); /** * Destroy a canvas. * * @param canvas the canvas */ DVZ_EXPORT void dvz_canvas_destroy(DvzCanvas* canvas); /** * Destroy all canvases. * * @param canvases the container with the canvases. */ DVZ_EXPORT void dvz_canvases_destroy(DvzContainer* canvases); /*************************************************************************************************/ /* Swapchain */ /*************************************************************************************************/ /** * Initialize a swapchain. * * @param gpu the GPU * @param window the window * @param min_img_count the minimum acceptable number of images in the swapchain * @returns the swapchain */ DVZ_EXPORT DvzSwapchain dvz_swapchain(DvzGpu* gpu, DvzWindow* window, uint32_t min_img_count); /** * Set the swapchain image format. * * @param swapchain the swapchain * @param format the format */ DVZ_EXPORT void dvz_swapchain_format(DvzSwapchain* swapchain, VkFormat format); /** * Set the swapchain present mode. * * @param swapchain the swapchain * @param present_mode the present mode */ DVZ_EXPORT void dvz_swapchain_present_mode(DvzSwapchain* swapchain, VkPresentModeKHR present_mode); /** * Set the swapchain requested image size. * * @param swapchain the swapchain * @param width the requested width * @param height the requested height */ DVZ_EXPORT void dvz_swapchain_requested_size(DvzSwapchain* swapchain, uint32_t width, uint32_t height); /** * Create the swapchain once it has been set up. * * @param swapchain the swapchain */ DVZ_EXPORT void dvz_swapchain_create(DvzSwapchain* swapchain); /** * Recreate a swapchain (for example after a window resize). * * @param swapchain the swapchain */ DVZ_EXPORT void dvz_swapchain_recreate(DvzSwapchain* swapchain); /** * Acquire a swapchain image. * * @param swapchain the swapchain * @param semaphores the set of signal semaphores * @param semaphore_idx the index of the semaphore to signal after image acquisition * @param fences the set of signal fences * @param fence_idx the index of the fence to signal after image acquisition */ DVZ_EXPORT void dvz_swapchain_acquire( DvzSwapchain* swapchain, DvzSemaphores* semaphores, uint32_t semaphore_idx, DvzFences* fences, uint32_t fence_idx); /** * Present a swapchain image to the screen after it has been rendered. * * @param swapchain the swapchain * @param queue_idx the index of the present queue * @param semaphores the set of waiting semaphores * @param semaphore_idx the index of the semaphore to wait on before presentation */ DVZ_EXPORT void dvz_swapchain_present( DvzSwapchain* swapchain, uint32_t queue_idx, DvzSemaphores* semaphores, uint32_t semaphore_idx); /** * Destroy a swapchain * * !!! warning * This function must imperatively be called *before* `dvz_window_destroy()`. * * @param swapchain the swapchain */ DVZ_EXPORT void dvz_swapchain_destroy(DvzSwapchain* swapchain); /*************************************************************************************************/ /* Commands */ /*************************************************************************************************/ /** * Create a set of command buffers. * * !!! note * We use the following convention in vklite and elsewhere in datoviz: the queue #0 **must** * support transfer tasks. This convention makes the implementation a bit simpler. * This convention is respected by the context module, where the first default queue * is the transfer queue, dedicated to transfer tasks. * * @param gpu the GPU * @param queue the queue index within the GPU * @param count the number of command buffers to create * @returns the set of command buffers */ DVZ_EXPORT DvzCommands dvz_commands(DvzGpu* gpu, uint32_t queue, uint32_t count); /** * Start recording a command buffer. * * @param cmds the set of command buffers * @param idx the index of the command buffer to begin recording on */ DVZ_EXPORT void dvz_cmd_begin(DvzCommands* cmds, uint32_t idx); /** * Stop recording a command buffer. * * @param cmds the set of command buffers * @param idx the index of the command buffer to stop the recording on */ DVZ_EXPORT void dvz_cmd_end(DvzCommands* cmds, uint32_t idx); /** * Reset a command buffer. * * @param cmds the set of command buffers * @param idx the index of the command buffer to reset */ DVZ_EXPORT void dvz_cmd_reset(DvzCommands* cmds, uint32_t idx); /** * Free a set of command buffers. * * @param cmds the set of command buffers */ DVZ_EXPORT void dvz_cmd_free(DvzCommands* cmds); /** * Submit a command buffer on its queue with inefficient full synchronization. * * This function is relatively inefficient because it calls `dvz_queue_wait()`. * * @param cmds the set of command buffers * @param idx the index of the command buffer to submit */ DVZ_EXPORT void dvz_cmd_submit_sync(DvzCommands* cmds, uint32_t idx); /** * Destroy a set of command buffers. * * @param cmds the set of command buffers */ DVZ_EXPORT void dvz_commands_destroy(DvzCommands* cmds); /*************************************************************************************************/ /* Buffers */ /*************************************************************************************************/ /** * Initialize a GPU buffer. * * @param gpu the GPU * @returns the buffer */ DVZ_EXPORT DvzBuffer dvz_buffer(DvzGpu* gpu); /** * Set the buffer size. * * @param buffer the buffer * @param size the buffer size, in bytes */ DVZ_EXPORT void dvz_buffer_size(DvzBuffer* buffer, VkDeviceSize size); /** * Set the buffer type. * * @param buffer the buffer * @param type the buffer type */ DVZ_EXPORT void dvz_buffer_type(DvzBuffer* buffer, DvzBufferType type); /** * Set the buffer usage. * * @param buffer the buffer * @param usage the buffer usage */ DVZ_EXPORT void dvz_buffer_usage(DvzBuffer* buffer, VkBufferUsageFlags usage); /** * Set the buffer memory properties. * * @param buffer the buffer * @param memory the memory properties */ DVZ_EXPORT void dvz_buffer_memory(DvzBuffer* buffer, VkMemoryPropertyFlags memory); /** * Set the buffer queue access. * * @param buffer the buffer * @param queue_idx the queue index */ DVZ_EXPORT void dvz_buffer_queue_access(DvzBuffer* buffer, uint32_t queue_idx); /** * Create the buffer after it has been set. * * @param buffer the buffer */ DVZ_EXPORT void dvz_buffer_create(DvzBuffer* buffer); /** * Resize a buffer. * * @param buffer the buffer * @param size the new buffer size, in bytes */ DVZ_EXPORT void dvz_buffer_resize(DvzBuffer* buffer, VkDeviceSize size); /** * Memory-map a buffer. * * @param buffer the buffer * @param offset the offset within the buffer, in bytes * @param size the size to map, in bytes */ DVZ_EXPORT void* dvz_buffer_map(DvzBuffer* buffer, VkDeviceSize offset, VkDeviceSize size); /** * Unmap a buffer. * * @param buffer the buffer */ DVZ_EXPORT void dvz_buffer_unmap(DvzBuffer* buffer); /** * Download a buffer data to the CPU. * * !!! important * This function does **not** use any GPU synchronization primitive: this is the responsibility * of the caller. A simple (but not optimal) method is just to call the following function * after every call to this function: * `dvz_queue_wait(gpu, DVZ_DEFAULT_QUEUE_TRANSFER);` * * @param buffer the buffer * @param offset the offset within the buffer, in bytes * @param size the size of the region to download, in bytes * @param[out] data the buffer to download on (must be allocated with the appropriate size) */ DVZ_EXPORT void dvz_buffer_download(DvzBuffer* buffer, VkDeviceSize offset, VkDeviceSize size, void* data); /** * Upload data to a GPU buffer. * * !!! important * This function does **not** use any GPU synchronization primitive: this is the responsibility * of the caller. A simple (but not optimal) method is just to call the following function * after every call to this function: * `dvz_queue_wait(gpu, DVZ_DEFAULT_QUEUE_TRANSFER);` * * @param buffer the buffer * @param offset the offset within the buffer, in bytes * @param size the buffer size, in bytes * @param data the data to upload */ DVZ_EXPORT void dvz_buffer_upload(DvzBuffer* buffer, VkDeviceSize offset, VkDeviceSize size, const void* data); /** * Destroy a buffer * * @param buffer the buffer */ DVZ_EXPORT void dvz_buffer_destroy(DvzBuffer* buffer); /** * Create buffer regions on an existing GPU buffer. * * @param buffer the buffer * @param count the number of successive regions * @param offset the offset within the buffer * @param size the size of each region, in bytes * @param alignment the alignment requirement for the region offsets */ DVZ_EXPORT DvzBufferRegions dvz_buffer_regions( DvzBuffer* buffer, uint32_t count, // VkDeviceSize offset, VkDeviceSize size, VkDeviceSize alignment); /** * Map a buffer region. * * @param br the buffer regions * @param idx the index of the buffer region to map */ DVZ_EXPORT void* dvz_buffer_regions_map(DvzBufferRegions* br, uint32_t idx); /** * Unmap a set of buffer regions. * * @param br the buffer regions */ DVZ_EXPORT void dvz_buffer_regions_unmap(DvzBufferRegions* br); /** * Upload data to a buffer region. * * !!! important * This function does **not** use any GPU synchronization primitive: this is the responsibility * of the caller. A simple (but not optimal) method is just to call the following function * after every call to this function: * `dvz_queue_wait(gpu, DVZ_DEFAULT_QUEUE_TRANSFER);` * * @param br the set of buffer regions * @param idx the index of the buffer region to upload data to * @param data the data to upload */ DVZ_EXPORT void dvz_buffer_regions_upload(DvzBufferRegions* br, uint32_t idx, const void* data); /** * Copy data between two buffer region. * * @param src the source buffer regions * @param src_offset, the offset, in bytes * @param dst the destination buffer regions * @param dst_offset, the offset, in bytes * @param size the size, in bytes */ DVZ_EXPORT void dvz_buffer_regions_copy( DvzBufferRegions* src, VkDeviceSize src_offset, // DvzBufferRegions* dst, VkDeviceSize dst_offset, VkDeviceSize size); /*************************************************************************************************/ /* Images */ /*************************************************************************************************/ /** * Initialize a set of GPU images. * * @param gpu the GPU * @param type the image type * @param count the number of images * @returns the images */ DVZ_EXPORT DvzImages dvz_images(DvzGpu* gpu, VkImageType type, uint32_t count); /** * Set the images format. * * @param images the images * @param format the image format */ DVZ_EXPORT void dvz_images_format(DvzImages* images, VkFormat format); /** * Set the images layout. * * @param images the images * @param layout the image layout */ DVZ_EXPORT void dvz_images_layout(DvzImages* images, VkImageLayout layout); /** * Set the images size. * * @param images the images * @param width the image width * @param height the image height * @param depth the image depth */ DVZ_EXPORT void dvz_images_size(DvzImages* images, uint32_t width, uint32_t height, uint32_t depth); /** * Set the images tiling. * * @param images the images * @param tiling the image tiling */ DVZ_EXPORT void dvz_images_tiling(DvzImages* images, VkImageTiling tiling); /** * Set the images usage. * * @param images the images * @param usage the image usage */ DVZ_EXPORT void dvz_images_usage(DvzImages* images, VkImageUsageFlags usage); /** * Set the images memory properties. * * @param images the images * @param memory the memory properties */ DVZ_EXPORT void dvz_images_memory(DvzImages* images, VkMemoryPropertyFlags memory); /** * Set the images aspect. * * @param images the images * @param aspect the image aspect */ DVZ_EXPORT void dvz_images_aspect(DvzImages* images, VkImageAspectFlags aspect); /** * Set the images queue access. * * This parameter specifies which queues may access the image from command buffers submitted to * them. * * @param images the images * @param queue_idx the queue index */ DVZ_EXPORT void dvz_images_queue_access(DvzImages* images, uint32_t queue_idx); /** * Create the images after they have been set up. * * @param images the images */ DVZ_EXPORT void dvz_images_create(DvzImages* images); /** * Resize images. * * !!! warning * This function deletes the images contents when resizing. * * @param images the images * @param width the new width * @param height the new height * @param depth the new depth */ DVZ_EXPORT void dvz_images_resize(DvzImages* images, uint32_t width, uint32_t height, uint32_t depth); /** * Transition the images to their layout after creation. * * This function performs a hard synchronization on the queue and submits a command buffer with the * image transition. * * @param images the images */ DVZ_EXPORT void dvz_images_transition(DvzImages* images); /** * Download the data from a staging GPU image. * * @param staging the images to download the data from * @param idx the index of the image * @param bytes_per_component number of bytes per component * @param swizzle whether the RGB(A) values need to be transposed * @param has_alpha whether there is an Alpha component in the output buffer * @param[out] out the buffer that will be filled with the image data (must be already allocated) */ DVZ_EXPORT void dvz_images_download( DvzImages* staging, uint32_t idx, VkDeviceSize bytes_per_component, bool swizzle, bool has_alpha, void* out); /** * Destroy images. * * @param images the images */ DVZ_EXPORT void dvz_images_destroy(DvzImages* images); /*************************************************************************************************/ /* Sampler */ /*************************************************************************************************/ /** * Initialize a texture sampler. * * @param gpu the GPU * @returns the sampler object */ DVZ_EXPORT DvzSampler dvz_sampler(DvzGpu* gpu); /** * Set the sampler min filter. * * @param sampler the sampler * @param filter the filter */ DVZ_EXPORT void dvz_sampler_min_filter(DvzSampler* sampler, VkFilter filter); /** * Set the sampler mag filter. * * @param sampler the sampler * @param filter the filter */ DVZ_EXPORT void dvz_sampler_mag_filter(DvzSampler* sampler, VkFilter filter); /** * Set the sampler address mode * * @param sampler the sampler * @param axis the sampler axis * @param address_mode the address mode */ DVZ_EXPORT void dvz_sampler_address_mode( DvzSampler* sampler, DvzTextureAxis axis, VkSamplerAddressMode address_mode); /** * Create the sampler after it has been set up. * * @param sampler the sampler */ DVZ_EXPORT void dvz_sampler_create(DvzSampler* sampler); /** * Destroy a sampler * * @param sampler the sampler */ DVZ_EXPORT void dvz_sampler_destroy(DvzSampler* sampler); /*************************************************************************************************/ /* Slots */ /*************************************************************************************************/ /** * Initialize pipeline slots (aka Vulkan descriptor set layout). * * @param gpu the GPU * @returns the slots */ DVZ_EXPORT DvzSlots dvz_slots(DvzGpu* gpu); /** * Set the slots binding. * * @param slots the slots * @param idx the slot index to set up * @param type the descriptor type for that slot */ DVZ_EXPORT void dvz_slots_binding(DvzSlots* slots, uint32_t idx, VkDescriptorType type); /** * Set up push constants. * * @param slots the slots * @param offset the push constant offset, in bytes * @param size the push constant size, in bytes * @param shaders the shader stages that will access the push constant */ DVZ_EXPORT void dvz_slots_push( DvzSlots* slots, VkDeviceSize offset, VkDeviceSize size, VkShaderStageFlags shaders); /** * Create the slots after they have been set up. * * @param slots the slots */ DVZ_EXPORT void dvz_slots_create(DvzSlots* slots); /** * Destroy the slots * * @param slots the slots */ DVZ_EXPORT void dvz_slots_destroy(DvzSlots* slots); /*************************************************************************************************/ /* Bindings */ /*************************************************************************************************/ /** * Initialize bindings corresponding to slots. * * @param slots the slots * @param dset_count the number of descriptor sets (number of swapchain images) */ DVZ_EXPORT DvzBindings dvz_bindings(DvzSlots* slots, uint32_t dset_count); /** * Bind a buffer to a slot. * * @param bindings the bindings * @param idx the slot index * @param br the buffer regions to bind to that slot */ DVZ_EXPORT void dvz_bindings_buffer(DvzBindings* bindings, uint32_t idx, DvzBufferRegions br); /** * Bind a texture to a slot. * * @param bindings the bindings * @param idx the slot index * @param br the texture to bind to that slot */ DVZ_EXPORT void dvz_bindings_texture(DvzBindings* bindings, uint32_t idx, DvzTexture* texture); /** * Update the bindings after the buffers/textures have been set up. * * @param bindings the bindings */ DVZ_EXPORT void dvz_bindings_update(DvzBindings* bindings); /** * Destroy bindings. * * @param bindings the bindings */ DVZ_EXPORT void dvz_bindings_destroy(DvzBindings* bindings); /*************************************************************************************************/ /* Compute */ /*************************************************************************************************/ /** * Initialize a compute pipeline. * * @param gpu the GPU * @param shader_path (optional) the path to the `.spirv` file with the compute shader * @returns the compute pipeline */ DVZ_EXPORT DvzCompute dvz_compute(DvzGpu* gpu, const char* shader_path); /** * Create a compute pipeline after it has been set up. * * @param compute the compute pipeline */ DVZ_EXPORT void dvz_compute_create(DvzCompute* compute); /** * Set the GLSL code directly (the library will compile it automatically to SPIRV). * * @param compute the compute pipeline * @param code the GLSL code defining the compute shader */ DVZ_EXPORT void dvz_compute_code(DvzCompute* compute, const char* code); /** * Declare a slot for the compute pipeline. * * @param compute the compute pipeline * @param idx the slot index * @param type the descriptor type */ DVZ_EXPORT void dvz_compute_slot(DvzCompute* compute, uint32_t idx, VkDescriptorType type); /** * Set up push constant. * * @param compute the compute pipeline * @param offset the push constant offset, in bytes * @param size the push constant size, in bytes * @param shaders the shaders that will need to access the push constant */ DVZ_EXPORT void dvz_compute_push( DvzCompute* compute, VkDeviceSize offset, VkDeviceSize size, VkShaderStageFlags shaders); /** * Associate a bindings object to a compute pipeline. * * @param compute the compute pipeline * @param bindings the bindings */ DVZ_EXPORT void dvz_compute_bindings(DvzCompute* compute, DvzBindings* bindings); /** * Destroy a compute pipeline. * * @param compute the compute pipeline */ DVZ_EXPORT void dvz_compute_destroy(DvzCompute* compute); /*************************************************************************************************/ /* Pipeline */ /*************************************************************************************************/ /** * Initialize a graphics pipeline. * * @param gpu the GPU * @returns the graphics pipeline */ DVZ_EXPORT DvzGraphics dvz_graphics(DvzGpu* gpu); /** * Set the renderpass of a graphics pipeline. * * @param graphics the graphics pipeline * @param renderpass the render pass * @param subpass the subpass index */ DVZ_EXPORT void dvz_graphics_renderpass(DvzGraphics* graphics, DvzRenderpass* renderpass, uint32_t subpass); /** * Set the graphics pipeline primitive topology * * @param graphics the graphics pipeline * @param topology the primitive topology */ DVZ_EXPORT void dvz_graphics_topology(DvzGraphics* graphics, VkPrimitiveTopology topology); /** * Set the GLSL code of a graphics pipeline. * * @param graphics the graphics pipeline * @param stage the shader stage * @param code the GLSL code of the shader */ DVZ_EXPORT void dvz_graphics_shader_glsl(DvzGraphics* graphics, VkShaderStageFlagBits stage, const char* code); /** * Set the SPIRV code of a graphics pipeline. * * @param graphics the graphics pipeline * @param stage the shader stage * @param size the size of the SPIRV buffer, in bytes * @param buffer the binary buffer with the SPIRV code */ DVZ_EXPORT void dvz_graphics_shader_spirv( DvzGraphics* graphics, VkShaderStageFlagBits stage, VkDeviceSize size, const uint32_t* buffer); /** * Set the path to a shader for a graphics pipeline. * * @param graphics the graphics pipeline * @param stage the shader stage * @param shader_path the path to the `.spirv` shader file */ DVZ_EXPORT void dvz_graphics_shader(DvzGraphics* graphics, VkShaderStageFlagBits stage, const char* shader_path); /** * Set the vertex binding. * * @param graphics the graphics pipeline * @param binding the binding index * @param stride the stride in the vertex buffer, in bytes */ DVZ_EXPORT void dvz_graphics_vertex_binding(DvzGraphics* graphics, uint32_t binding, VkDeviceSize stride); /** * Add a vertex attribute. * * @param graphics the graphics pipeline * @param binding the binding index (as specified in the vertex shader) * @param location the location index (as specified in the vertex shader) * @param format the format * @param offset the offset, in bytes */ DVZ_EXPORT void dvz_graphics_vertex_attr( DvzGraphics* graphics, uint32_t binding, uint32_t location, VkFormat format, VkDeviceSize offset); /** * Set the graphics blend type. * * @param graphics the graphics pipeline * @param blend_type the blend type */ DVZ_EXPORT void dvz_graphics_blend(DvzGraphics* graphics, DvzBlendType blend_type); /** * Set the graphics depth test. * * @param graphics the graphics pipeline * @param depth_test the depth test */ DVZ_EXPORT void dvz_graphics_depth_test(DvzGraphics* graphics, DvzDepthTest depth_test); /** * Set whether the graphics pipeline supports picking. * * !!! note * Picking support is currently all or nothing: all graphics of a canvas must either support * picking or not. In addition, the canvas must have been created with the * DVZ_CANVAS_FLAGS_PICK flag. * * @param graphics the graphics pipeline * @param support_pick whether the graphics pipeline supports picking */ DVZ_EXPORT void dvz_graphics_pick(DvzGraphics* graphics, bool support_pick); /** * Set the graphics polygon mode. * * @param graphics the graphics pipeline * @param polygon_mode the polygon mode */ DVZ_EXPORT void dvz_graphics_polygon_mode(DvzGraphics* graphics, VkPolygonMode polygon_mode); /** * Set the graphics cull mode. * * @param graphics the graphics pipeline * @param cull_mode the cull mode */ DVZ_EXPORT void dvz_graphics_cull_mode(DvzGraphics* graphics, VkCullModeFlags cull_mode); /** * Set the graphics front face. * * @param graphics the graphics pipeline * @param front_face the front face */ DVZ_EXPORT void dvz_graphics_front_face(DvzGraphics* graphics, VkFrontFace front_face); /** * Create a graphics pipeline after it has been set up. * * @param graphics the graphics pipeline */ DVZ_EXPORT void dvz_graphics_create(DvzGraphics* graphics); /** * Set a binding slot for a graphics pipeline. * * @param graphics the graphics pipeline * @param idx the slot index * @param type the descriptor type */ DVZ_EXPORT void dvz_graphics_slot(DvzGraphics* graphics, uint32_t idx, VkDescriptorType type); /** * Set a graphics pipeline push constant. * * @param graphics the graphics pipeline * @param offset the push constant offset, in bytes * @param offset the push size, in bytes * @param shaders the shader stages that will access the push constant */ DVZ_EXPORT void dvz_graphics_push( DvzGraphics* graphics, VkDeviceSize offset, VkDeviceSize size, VkShaderStageFlags shaders); /** * Destroy a graphics pipeline. * * @param graphics the graphics pipeline */ DVZ_EXPORT void dvz_graphics_destroy(DvzGraphics* graphics); /*************************************************************************************************/ /* Barrier */ /*************************************************************************************************/ /** * Initialize a synchronization barrier (usedwithin a command buffer). * * @param gpu the GPU * @returns the barrier */ DVZ_EXPORT DvzBarrier dvz_barrier(DvzGpu* gpu); /** * Set the barrier stages. * * @param barrier the barrier * @param src_stage the source stage * @param dst_stage the destination stage */ DVZ_EXPORT void dvz_barrier_stages( DvzBarrier* barrier, VkPipelineStageFlags src_stage, VkPipelineStageFlags dst_stage); /** * Set the barrier buffer. * * @param barrier the barrier * @param br the buffer regions */ DVZ_EXPORT void dvz_barrier_buffer(DvzBarrier* barrier, DvzBufferRegions br); /** * Set the barrier buffer queue. * * @param barrier the barrier * @param src_queue the source queue index * @param dst_queue the destination queue index */ DVZ_EXPORT void dvz_barrier_buffer_queue(DvzBarrier* barrier, uint32_t src_queue, uint32_t dst_queue); /** * Set the barrier buffer access. * * @param barrier the barrier * @param src_access the source access flags * @param dst_access the destination access flags */ DVZ_EXPORT void dvz_barrier_buffer_access(DvzBarrier* barrier, VkAccessFlags src_access, VkAccessFlags dst_access); /** * Set the barrier images. * * @param barrier the barrier * @param images the images */ DVZ_EXPORT void dvz_barrier_images(DvzBarrier* barrier, DvzImages* images); /** * Set the barrier images layout. * * @param barrier the barrier * @param src_layout the source layout * @param dst_layout the destination layout */ DVZ_EXPORT void dvz_barrier_images_layout(DvzBarrier* barrier, VkImageLayout src_layout, VkImageLayout dst_layout); /** * Set the barrier images queue. * * @param barrier the barrier * @param src_queue the source queue index * @param dst_queue the destination queue index */ DVZ_EXPORT void dvz_barrier_images_queue(DvzBarrier* barrier, uint32_t src_queue, uint32_t dst_queue); /** * Set the barrier images access. * * @param barrier the barrier * @param src_access the source access flags * @param dst_access the destination access flags */ DVZ_EXPORT void dvz_barrier_images_access(DvzBarrier* barrier, VkAccessFlags src_access, VkAccessFlags dst_access); /*************************************************************************************************/ /* Semaphores */ /*************************************************************************************************/ /** * Initialize a set of semaphores (GPU-GPU synchronization). * * @param gpu the GPU * @param count the number of semaphores * @returns the semaphores */ DVZ_EXPORT DvzSemaphores dvz_semaphores(DvzGpu* gpu, uint32_t count); /** * Recreate semaphores. * * @param semaphores the semaphores */ DVZ_EXPORT void dvz_semaphores_recreate(DvzSemaphores* semaphores); /** * Destroy semaphores. * * @param semaphores the semaphores */ DVZ_EXPORT void dvz_semaphores_destroy(DvzSemaphores* semaphores); /*************************************************************************************************/ /* Fences */ /*************************************************************************************************/ /** * Initialize a set of fences (CPU-GPU synchronization). * * @param gpu the GPU * @param count the number of fences * @param signaled whether the fences are created in the signaled state or not * @returns the fences */ DVZ_EXPORT DvzFences dvz_fences(DvzGpu* gpu, uint32_t count, bool signaled); /** * Copy a fence from a set of fences to another. * * @param src_fences the source fences * @param src_idx the fence index within the source fences * @param dst_fences the destination fences * @param dst_idx the fence index within the destination fences */ DVZ_EXPORT void dvz_fences_copy(DvzFences* src_fences, uint32_t src_idx, DvzFences* dst_fences, uint32_t dst_idx); /** * Wait on the GPU until a fence is signaled. * * @param fences the fences * @param idx the fence index */ DVZ_EXPORT void dvz_fences_wait(DvzFences* fences, uint32_t idx); /** * Return whether a fence is ready. * * @param fences the fences * @param idx the fence index */ DVZ_EXPORT bool dvz_fences_ready(DvzFences* fences, uint32_t idx); /** * Rset the state of a fence. * * @param fences the fences * @param idx the fence index */ DVZ_EXPORT void dvz_fences_reset(DvzFences* fences, uint32_t idx); /** * Destroy fences. * * @param fences the fences */ DVZ_EXPORT void dvz_fences_destroy(DvzFences* fences); /*************************************************************************************************/ /* Renderpass */ /*************************************************************************************************/ /** * Initialize a render pass. * * @param gpu the GPU * @returns the render pass */ DVZ_EXPORT DvzRenderpass dvz_renderpass(DvzGpu* gpu); /** * Set the clear value of a render pass. * * @param renderpass the render pass * @param value the clear value */ DVZ_EXPORT void dvz_renderpass_clear(DvzRenderpass* renderpass, VkClearValue value); /** * Specify a render pass attachment. * * @param renderpass the render pass * @param idx the attachment index * @param type the attachment type * @param format the attachment image format * @param ref_layout the image layout */ DVZ_EXPORT void dvz_renderpass_attachment( DvzRenderpass* renderpass, uint32_t idx, DvzRenderpassAttachmentType type, VkFormat format, VkImageLayout ref_layout); /** * Set the attachment layout. * * @param renderpass the render pass * @param idx the attachment index * @param src_layout the source layout * @param dst_layout the destination layout */ DVZ_EXPORT void dvz_renderpass_attachment_layout( DvzRenderpass* renderpass, uint32_t idx, VkImageLayout src_layout, VkImageLayout dst_layout); /** * Set the attachment load and store operations. * * @param renderpass the render pass * @param idx the attachment index * @param load_op the load operation * @param store_op the store operation */ DVZ_EXPORT void dvz_renderpass_attachment_ops( DvzRenderpass* renderpass, uint32_t idx, // VkAttachmentLoadOp load_op, VkAttachmentStoreOp store_op); /** * Set a subpass attachment. * * @param renderpass the render pass * @param subpass_idx the subpass index * @param attachment_idx the attachment index */ DVZ_EXPORT void dvz_renderpass_subpass_attachment( DvzRenderpass* renderpass, uint32_t subpass_idx, uint32_t attachment_idx); /** * Set a subpass dependency. * * @param renderpass the render pass * @param dependency_idx the dependency index * @param src_subpass the source subpass index * @param dst_subpass the destination subpass index */ DVZ_EXPORT void dvz_renderpass_subpass_dependency( DvzRenderpass* renderpass, uint32_t dependency_idx, // uint32_t src_subpass, uint32_t dst_subpass); /** * Set a subpass dependency access. * * @param renderpass the render pass * @param dependency_idx the dependency index * @param src_access the source access flags * @param dst_access the destinationaccess flags */ DVZ_EXPORT void dvz_renderpass_subpass_dependency_access( DvzRenderpass* renderpass, uint32_t dependency_idx, // VkAccessFlags src_access, VkAccessFlags dst_access); /** * Set a subpass dependency stage. * * @param renderpass the render pass * @param dependency_idx the dependency index * @param src_stage the source pipeline stages * @param dst_stage the destination pipeline stages */ DVZ_EXPORT void dvz_renderpass_subpass_dependency_stage( DvzRenderpass* renderpass, uint32_t dependency_idx, // VkPipelineStageFlags src_stage, VkPipelineStageFlags dst_stage); /** * Create a render pass after it has been set up. * * @param renderpass the render pass */ DVZ_EXPORT void dvz_renderpass_create(DvzRenderpass* renderpass); /** * Destroy a render pass. * * @param renderpass the render pass */ DVZ_EXPORT void dvz_renderpass_destroy(DvzRenderpass* renderpass); /*************************************************************************************************/ /* Framebuffers */ /*************************************************************************************************/ /** * Initialize a set of framebuffers. * * @param gpu the GPU * @returns the framebuffers */ DVZ_EXPORT DvzFramebuffers dvz_framebuffers(DvzGpu* gpu); /** * Set framebuffers attachment. * * @param framebuffers the framebuffers * @param attachment_idx the attachment index * @param images the images */ DVZ_EXPORT void dvz_framebuffers_attachment( DvzFramebuffers* framebuffers, uint32_t attachment_idx, DvzImages* images); /** * Create a set of framebuffers after it has been set up. * * @param framebuffers the framebuffers * @param renderpass the render pass */ DVZ_EXPORT void dvz_framebuffers_create(DvzFramebuffers* framebuffers, DvzRenderpass* renderpass); /** * Destroy a set of framebuffers. * * @param framebuffers the framebuffers */ DVZ_EXPORT void dvz_framebuffers_destroy(DvzFramebuffers* framebuffers); /*************************************************************************************************/ /* Submit */ /*************************************************************************************************/ /** * Create a submit object, used to submit command buffers to a GPU queue. * * @param gpu the GPU * @returns the submit */ DVZ_EXPORT DvzSubmit dvz_submit(DvzGpu* gpu); /** * Set the command buffers to submit. * * @param submit the submit object * @param cmds the set of command buffers */ DVZ_EXPORT void dvz_submit_commands(DvzSubmit* submit, DvzCommands* commands); /** * Set the wait semaphores * * @param submit the submit object * @param stage the pipeline stage * @param semaphores the set of semaphores to wait on * @param idx the semaphore index to wait on */ DVZ_EXPORT void dvz_submit_wait_semaphores( DvzSubmit* submit, VkPipelineStageFlags stage, DvzSemaphores* semaphores, uint32_t idx); /** * Set the signal semaphores * * @param submit the submit object * @param semaphores the set of semaphores to signal after the commands have completed * @param idx the semaphore index to signal */ DVZ_EXPORT void dvz_submit_signal_semaphores(DvzSubmit* submit, DvzSemaphores* semaphores, uint32_t idx); /** * Submit the command buffers to their queue. * * @param submit the submit object * @param cmd_idx the command buffer index to submit * @param fences the fences to signal after completion * @param fence_idx the fence index to signal */ DVZ_EXPORT void dvz_submit_send(DvzSubmit* submit, uint32_t cmd_idx, DvzFences* fences, uint32_t fence_idx); /** * Reset a submit object. * * @param submit the submit object */ DVZ_EXPORT void dvz_submit_reset(DvzSubmit* submit); /*************************************************************************************************/ /* Command buffer filling */ /*************************************************************************************************/ /** * Begin a render pass. * * @param cmds the set of command buffers to record * @param idx the index of the command buffer to record * @param renderpass the render pass * @param framebuffers the framebuffers */ DVZ_EXPORT void dvz_cmd_begin_renderpass( DvzCommands* cmds, uint32_t idx, DvzRenderpass* renderpass, DvzFramebuffers* framebuffers); /** * End a render pass. * * @param cmds the set of command buffers to record * @param idx the index of the command buffer to record */ DVZ_EXPORT void dvz_cmd_end_renderpass(DvzCommands* cmds, uint32_t idx); /** * Launch a compute task. * * @param cmds the set of command buffers to record * @param idx the index of the command buffer to record * @param compute the computer pipeline * @param size the task shape */ DVZ_EXPORT void dvz_cmd_compute(DvzCommands* cmds, uint32_t idx, DvzCompute* compute, uvec3 size); /** * Register a barrier. * * @param cmds the set of command buffers to record * @param idx the index of the command buffer to record * @param barrier the barrier */ DVZ_EXPORT void dvz_cmd_barrier(DvzCommands* cmds, uint32_t idx, DvzBarrier* barrier); /** * Copy a GPU buffer to a GPU image. * * @param cmds the set of command buffers to record * @param idx the index of the command buffer to record * @param buffer the buffer * @param images the image */ DVZ_EXPORT void dvz_cmd_copy_buffer_to_image( DvzCommands* cmds, uint32_t idx, DvzBuffer* buffer, DvzImages* images); /** * Copy a GPU image to a GPU buffer. * * @param cmds the set of command buffers to record * @param idx the index of the command buffer to record * @param images the image * @param buffer the buffer */ DVZ_EXPORT void dvz_cmd_copy_image_to_buffer( DvzCommands* cmds, uint32_t idx, DvzImages* images, DvzBuffer* buffer); /** * Copy a GPU image to another. * * @param cmds the set of command buffers to record * @param idx the index of the command buffer to record * @param src_img the source image * @param src_offset the offset in the source image * @param dst_img the destination image * @param dst_offset the offset in the target image * @param shape the shape of the region to copy */ DVZ_EXPORT void dvz_cmd_copy_image_region( DvzCommands* cmds, uint32_t idx, // DvzImages* src_img, ivec3 src_offset, // DvzImages* dst_img, ivec3 dst_offset, // uvec3 shape); /** * Copy a GPU image to another. * * @param cmds the set of command buffers to record * @param idx the index of the command buffer to record * @param src_img the source image * @param dst_img the destination image */ DVZ_EXPORT void dvz_cmd_copy_image(DvzCommands* cmds, uint32_t idx, DvzImages* src_img, DvzImages* dst_img); /** * Set the viewport. * * @param cmds the set of command buffers to record * @param idx the index of the command buffer to record * @param viewport the viewport */ DVZ_EXPORT void dvz_cmd_viewport(DvzCommands* cmds, uint32_t idx, VkViewport viewport); /** * Bind a graphics pipeline. * * @param cmds the set of command buffers to record * @param idx the index of the command buffer to record * @param graphics the graphics pipeline * @param bindings the bindings associated to the pipeline * @param dynamic_idx the dynamic uniform buffer index */ DVZ_EXPORT void dvz_cmd_bind_graphics( DvzCommands* cmds, uint32_t idx, DvzGraphics* graphics, // DvzBindings* bindings, uint32_t dynamic_idx); /** * Bind a vertex buffer. * * @param cmds the set of command buffers to record * @param idx the index of the command buffer to record * @param br the buffer regions * @param offset the offset within the buffer regions, in bytes */ DVZ_EXPORT void dvz_cmd_bind_vertex_buffer( DvzCommands* cmds, uint32_t idx, DvzBufferRegions br, VkDeviceSize offset); /** * Bind an index buffer. * * @param cmds the set of command buffers to record * @param idx the index of the command buffer to record * @param br the buffer regions * @param offset the offset within the buffer regions, in bytes */ DVZ_EXPORT void dvz_cmd_bind_index_buffer( DvzCommands* cmds, uint32_t idx, DvzBufferRegions br, VkDeviceSize offset); /** * Direct draw. * * @param cmds the set of command buffers to record * @param idx the index of the command buffer to record * @param first_vertex index of the first vertex * @param vertex_count number of vertices to draw */ DVZ_EXPORT void dvz_cmd_draw(DvzCommands* cmds, uint32_t idx, uint32_t first_vertex, uint32_t vertex_count); /** * Direct indexed draw. * * @param cmds the set of command buffers to record * @param idx the index of the command buffer to record * @param first_index index of the first index * @param vertex_offset offset of the vertex * @param index_count number of indices to draw */ DVZ_EXPORT void dvz_cmd_draw_indexed( DvzCommands* cmds, uint32_t idx, uint32_t first_index, uint32_t vertex_offset, uint32_t index_count); /** * Indirect draw. * * @param cmds the set of command buffers to record * @param idx the index of the command buffer to record * @param indirect buffer regions with the indirect draw info */ DVZ_EXPORT void dvz_cmd_draw_indirect(DvzCommands* cmds, uint32_t idx, DvzBufferRegions indirect); /** * Indirect indexed draw. * * @param cmds the set of command buffers to record * @param idx the index of the command buffer to record * @param indirect buffer regions with the indirect draw info */ DVZ_EXPORT void dvz_cmd_draw_indexed_indirect(DvzCommands* cmds, uint32_t idx, DvzBufferRegions indirect); /** * Copy a GPU buffer to another. * * @param cmds the set of command buffers to record * @param idx the index of the command buffer to record * @param src_buf the source buffer * @param src_offset the offset in the source buffer * @param dst_buf the destination buffer, in bytes * @param dst_offset the offset in the destination buffer, in bytes * @param size the size of the region to copy, in bytes */ DVZ_EXPORT void dvz_cmd_copy_buffer( DvzCommands* cmds, uint32_t idx, // DvzBuffer* src_buf, VkDeviceSize src_offset, // DvzBuffer* dst_buf, VkDeviceSize dst_offset, // VkDeviceSize size); /** * Push constants. * * @param cmds the set of command buffers to record * @param idx the index of the command buffer to record * @param slots the slots * @param shaders the shader stages that have access to the push constant * @param offset the offset in the push constant, in bytes * @param size the size in the push constant, in bytes * @param data the data to send via the push constant */ DVZ_EXPORT void dvz_cmd_push( DvzCommands* cmds, uint32_t idx, DvzSlots* slots, VkShaderStageFlagBits shaders, // VkDeviceSize offset, VkDeviceSize size, const void* data); /*************************************************************************************************/ /* Context */ /*************************************************************************************************/ /** * Destroy a context. * * @param context the context */ DVZ_EXPORT void dvz_context_destroy(DvzContext* context); #ifdef __cplusplus } #endif #endif
27.592444
99
0.650269
[ "render", "object", "shape" ]
fcb5a37fb81c925d7b150c9cf7c8b34dbde71797
2,520
h
C
libs/DS4_SDK/include/dzstyledfloatcardpropertywgt.h
Red54/reality
510d4f5fde2f4c5535482f1ea199f914102b8a2a
[ "BSD-3-Clause" ]
null
null
null
libs/DS4_SDK/include/dzstyledfloatcardpropertywgt.h
Red54/reality
510d4f5fde2f4c5535482f1ea199f914102b8a2a
[ "BSD-3-Clause" ]
null
null
null
libs/DS4_SDK/include/dzstyledfloatcardpropertywgt.h
Red54/reality
510d4f5fde2f4c5535482f1ea199f914102b8a2a
[ "BSD-3-Clause" ]
null
null
null
/********************************************************************** Copyright (C) 2002-2012 DAZ 3D, Inc. All Rights Reserved. This file is part of the DAZ Studio SDK. This file may be used only in accordance with the DAZ Studio SDK license provided with the DAZ Studio SDK. The contents of this file may not be disclosed to third parties, copied or duplicated in any form, in whole or in part, without the prior written permission of DAZ 3D, Inc, except as explicitly allowed in the DAZ Studio SDK license. See http://www.daz3d.com to contact DAZ 3D or for more information about the DAZ Studio SDK. **********************************************************************/ /** @sdk @file Defines the DzStyledFloatCardPropertyWgt class. **/ #ifndef DAZ_STYLED_FLOAT_CARD_PROPERTY_WGT_H #define DAZ_STYLED_FLOAT_CARD_PROPERTY_WGT_H /***************************** Include files *****************************/ #include "dzstyledpropertywgt.h" /***************************** Class definitions *****************************/ class DZ_EXPORT DzStyledFloatCardPropertyWgt : public DzStyledPropertyBaseWgt { Q_OBJECT public: // // CREATORS // DzStyledFloatCardPropertyWgt( QWidget *parent = 0, const QString &name = QString::null ); virtual ~DzStyledFloatCardPropertyWgt(); // // REIMPLEMENTATIONS // virtual DzError addProperty( DzProperty *prop ); virtual void removeAllProperties(); void setLevel( int level ); public slots: void setValue( float val ); virtual bool doOptionsDialog(); void setHighLightSlider( bool onOff ); protected slots: virtual void updateLabel(); virtual void updateValue(); virtual void updateFromList(); virtual void setPropertyValueLabel( const QString &val ); void editBoxChange( const QString &text ); virtual void finishTextEdit(); void showEdit( const QRect &rect, QString text, const QFont &fnt ); void valueLabelClicked(); int getLevel(); protected: virtual QString getValueEditText() const; virtual void valueTextChanged( const QString &text ); virtual void paintEvent( QPaintEvent *e ); virtual void changeEvent( QEvent *e ); private slots: void propertyChangeNotify(); void propStateChangeNotify(); void startEdit(); void finishEdit(); void cancelEdit(); private: void setupFromStyle(); void drawLabel( QPainter &p ); struct Data; Data *m_data; }; #endif // DAZ_STYLED_FLOAT_CARD_PROPERTY_WGT_H
26.808511
91
0.645238
[ "3d" ]
118398e63f3134a26ebc7b53e153f71882a4cce8
29,442
c
C
eziprocci/eziclient.c
MarouenMechtri/accords-platform-1
4f950fffd9fbbf911840cc5ad0fe5b5a331edf42
[ "Apache-2.0" ]
1
2015-02-28T21:25:54.000Z
2015-02-28T21:25:54.000Z
eziprocci/eziclient.c
MarouenMechtri/accords-platform-1
4f950fffd9fbbf911840cc5ad0fe5b5a331edf42
[ "Apache-2.0" ]
null
null
null
eziprocci/eziclient.c
MarouenMechtri/accords-platform-1
4f950fffd9fbbf911840cc5ad0fe5b5a331edf42
[ "Apache-2.0" ]
null
null
null
/* -------------------------------------------------------------------- */ /* ACCORDS PLATFORM */ /* (C) 2011 by Iain James Marshall (Prologue) <ijm667@hotmail.com> */ /* -------------------------------------------------------------------- */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. */ /* See the License for the specific language governing permissions and */ /* limitations under the License. */ /* -------------------------------------------------------------------- */ #ifndef _eziclient_c #define _eziclient_c #include "eziclient.h" /* ------------------------------------------------------------ */ /* l i b e r a t e _ e z i _ r e s p o n s e */ /* ------------------------------------------------------------ */ public struct ezi_response * liberate_ezi_response( struct ezi_response * rptr ) { if ( rptr ) { if ( rptr->response ) rptr->response = liberate_rest_response( rptr->response ); if ( rptr->jsonroot ) rptr->jsonroot = drop_data_element( rptr->jsonroot ); if ( rptr->xmlroot ) rptr->xmlroot = document_drop( rptr->xmlroot ); if ( rptr->content ) liberate( rptr->content ); liberate( rptr ); } return((struct ezi_response *) 0); } /* ------------------------------------------------------------ */ /* e z i _ c h e c k */ /* ------------------------------------------------------------ */ private struct ezi_response * ezi_check( struct rest_response * aptr ) { struct ezi_response * rptr=(struct ezi_response *) 0; struct rest_header * hptr=(struct rest_header *) 0;; if ( aptr ) { if ( check_verbose() ) { printf(" OS Client Response : %s %u %s\n",aptr->version,aptr->status,aptr->message); if ( check_debug() ) { for ( hptr=aptr->first; hptr != (struct rest_header *) 0; hptr = hptr->next ) { if (!( hptr->name )) continue; else printf(" %s: %s\n",hptr->name,hptr->value); } if ( aptr->body ) { printf(" [ %s ] \n",aptr->body ); } } } } if (!( rptr = allocate( sizeof( struct ezi_response ) ) )) return( rptr ); else { rptr->nature = _TEXT_NONE; rptr->content= (char *) 0; rptr->xmlroot = (struct xml_element *) 0; rptr->jsonroot = (struct data_element *) 0; rptr->response = aptr; if (!( aptr->body )) return(rptr); if (!( hptr = rest_resolve_header( aptr->first, "Content-Type" ) )) return(rptr); else if (!( rptr->content = allocate_string( hptr->value ) )) return( rptr ); else if ((!( strcmp( rptr->content, "text/json" ))) || (!( strcmp( rptr->content, "application/json" ))) || (!( strcmp( rptr->content, "x-application/json")))) { rptr->nature = _TEXT_JSON; rptr->jsonroot = json_parse_file( aptr->body ); return( rptr ); } else if ((!( strcmp( rptr->content, "text/xml" ))) || (!( strcmp( rptr->content, "application/xml" ))) || (!( strcmp( rptr->content, "x-application/xml")))) { rptr->nature = _TEXT_XML; rptr->xmlroot = document_parse_file( aptr->body ); return( rptr ); } else return( rptr ); } } /* --------------------------------------------------------- */ /* e z i _ c l i e n t _ r a t e _ l i m i t e d */ /* --------------------------------------------------------- */ private int ezi_client_rate_limited( struct rest_response * rptr ) { if (!( rptr )) return(0); else if ( rptr->status < 400 ) return(0); else if ( rptr->status != 413 ) return(0); else return(1); } /* ------------------------------------------------------------ */ /* e z i _ c l i e n t _ g e t _ r e q u e s t */ /* ------------------------------------------------------------ */ public struct ezi_response * ezi_client_get_request( char * target, char * tls, char * nptr, struct rest_header * hptr ) { struct rest_response * rptr; struct rest_header * copy=(struct rest_header *) 0; if (( hptr ) && (!( copy = rest_duplicate_headers( hptr ) ))) return((struct ezi_response *) 0); while ((rptr = rest_client_get_request( target, tls, nptr, hptr )) != (struct rest_response *) 0) { if (!( ezi_client_rate_limited( rptr ) )) break; else if (!( copy )) continue; else if (!( hptr = rest_duplicate_headers( copy ) )) return((struct ezi_response *) 0); else continue; } if (( hptr ) && ( copy )) copy = liberate_rest_headers( copy ); return( ezi_check( rptr ) ); } /* ------------------------------------------------------------ */ /* e z i _ c l i e n t _ h e a d _ r e q u e s t */ /* ------------------------------------------------------------ */ public struct ezi_response * ezi_client_head_request( char * target, char * tls, char * nptr, struct rest_header * hptr ) { struct rest_response * rptr; struct rest_header * copy=(struct rest_header *) 0; if (( hptr ) && (!( copy = rest_duplicate_headers( hptr ) ))) return((struct ezi_response *) 0); while (( rptr = rest_client_head_request( target, tls, nptr, hptr )) != (struct rest_response *) 0) { if (!( ezi_client_rate_limited( rptr ) )) break; else if (!( copy )) continue; else if (!( hptr = rest_duplicate_headers( copy ) )) return((struct ezi_response *) 0); else continue; } if (( hptr ) && ( copy )) copy = liberate_rest_headers( copy ); return( ezi_check( rptr ) ); } /* ------------------------------------------------------------ */ /* e z i _ c l i e n t _ d e l e t e _ r e q u e s t */ /* ------------------------------------------------------------ */ public struct ezi_response * ezi_client_delete_request( char * target, char * tls, char * nptr, struct rest_header * hptr ) { struct rest_response * rptr; struct rest_header * copy=(struct rest_header *) 0; if (( hptr ) && (!( copy = rest_duplicate_headers( hptr ) ))) return((struct ezi_response *) 0); while (( rptr = rest_client_delete_request( target, tls, nptr, hptr )) != (struct rest_response *) 0) { if (!( ezi_client_rate_limited( rptr ) )) break; else if (!( copy )) continue; else if (!( hptr = rest_duplicate_headers( copy ) )) return((struct ezi_response *) 0); else continue; } if (( hptr ) && ( copy )) copy = liberate_rest_headers( copy ); return( ezi_check( rptr ) ); } /* ------------------------------------------------------------ */ /* e z i _ c l i e n t _ p o s t _ r e q u e s t */ /* ------------------------------------------------------------ */ public struct ezi_response * ezi_client_post_request( char * target, char * tls, char * nptr, char * filename, struct rest_header * hptr ) { struct rest_response * rptr; struct rest_header * copy=(struct rest_header *) 0; char * body=(char *) 0; if (( hptr ) && (!( copy = rest_duplicate_headers( hptr ) ))) return((struct ezi_response *) 0); if (( filename ) && (!( body = allocate_string( filename ) ))) { copy = liberate_rest_headers( copy ); return((struct ezi_response *) 0); } while (( rptr = rest_client_post_request( target, tls, nptr, filename, hptr )) != (struct rest_response *) 0) { if (!( ezi_client_rate_limited( rptr ) )) break; if ( copy ) if (!( hptr = rest_duplicate_headers( copy ) )) return((struct ezi_response *) 0); if ( body ) if (!( filename = allocate_string( body ) )) return((struct ezi_response *) 0); } if (( filename ) && ( body )) body = liberate( body ); if (( hptr ) && ( copy )) copy = liberate_rest_headers( copy ); return( ezi_check( rptr ) ); } /* ------------------------------------------------------------ */ /* e z i _ c l i e n t _ p u t _ r e q u e s t */ /* ------------------------------------------------------------ */ public struct ezi_response * ezi_client_put_request( char * target, char * tls, char * nptr, char * filename, struct rest_header * hptr ) { struct rest_response * rptr; struct rest_header * copy=(struct rest_header *) 0; char * body=(char *) 0; if (( hptr ) && (!( copy = rest_duplicate_headers( hptr ) ))) return((struct ezi_response *) 0); if (( filename ) && (!( body = allocate_string( filename ) ))) { copy = liberate_rest_headers( copy ); return((struct ezi_response *) 0); } while (( rptr = rest_client_put_request( target, tls, nptr, filename, hptr )) != (struct rest_response *) 0) { if (!( ezi_client_rate_limited( rptr ) )) break; if ( copy ) if (!( hptr = rest_duplicate_headers( copy ) )) return((struct ezi_response *) 0); if ( body ) if (!( filename = allocate_string( body ) )) return((struct ezi_response *) 0); } if (( filename ) && ( body )) body = liberate( body ); if (( hptr ) && ( copy )) copy = liberate_rest_headers( copy ); return( ezi_check( rptr ) ); } /* ------------------------------------------------- */ /* e z i _ k e y s t o n e _ a u t h _ m e s s a g e */ /* ------------------------------------------------- */ public char * ezi_keystone_auth_message( char * user, char * password, char * tenant ) { char * filename; FILE * h; if (!( filename = rest_temporary_filename("xml"))) return( filename ); else if (!( h = fopen( filename, "wa" ) )) return( liberate( filename ) ); else { fprintf(h,"<?xml version=%c1.0%c encoding=%cUTF-8%c?>\n", 0x0022,0x0022,0x0022,0x0022); fprintf(h,"<auth xmlns:xsi=%c%s%c xmlns=%c%s%c tenantName=%c%s%c>\n", 0x0022,"http://www.w3.org/2001/XMLSchema-instance",0x0022, 0x0022,"http://docs.openstack.com/identity/api/v2.0",0x0022, 0x0022,tenant,0x0022); fprintf(h,"<passwordCredentials username=%c%s%c password=%c%s%c/>\n", 0x0022,user,0x0022,0x0022,password,0x0022); fprintf(h,"</auth>\n"); fclose(h); return( filename ); } } /* --------------------------------------------------------- */ /* c h e c k _ k e y s t o n e _ a u t h o r i z a t i o n */ /* --------------------------------------------------------- */ public int check_keystone_authorization(struct ezi_subscription * sptr) { struct xml_element * document; struct xml_element * eptr; struct xml_element * gptr; struct xml_atribut * aptr; struct rest_response * rptr; struct rest_header * hptr; char * tptr; char * filename; char buffer[1024]; if (!( sptr->Ezi.authenticate )) { sprintf(buffer,"%s/tokens",sptr->Ezi.host); if (!( hptr = rest_create_header( _HTTP_CONTENT_TYPE, sptr->KeyStone.requestauth ) )) return( 0 ); else if (!( hptr->next = rest_create_header( _HTTP_ACCEPT, sptr->KeyStone.acceptauth ) )) { liberate_rest_header( hptr ); return( 0 ); } else hptr->next->previous = hptr; if (!( filename = ezi_keystone_auth_message( sptr->Ezi.user, sptr->Ezi.password, sptr->KeyStone.tenantname ) )) { liberate_rest_header( hptr ); return( 0 ); } else if (!( rptr = rest_client_post_request( buffer, sptr->Ezi.tls, sptr->Ezi.agent, filename, hptr ) )) { return( 0 ); } if (!( hptr = rest_resolve_header( rptr->first, _HTTP_CONTENT_TYPE ) )) { rptr = liberate_rest_response( rptr ); return( 0 ); } else if (!( hptr->value )) { rptr = liberate_rest_response( rptr ); return( 0 ); } else if ( strncasecmp( hptr->value, sptr->KeyStone.acceptauth, strlen(sptr->KeyStone.acceptauth) ) ) { rptr = liberate_rest_response( rptr ); return( 0 ); } else if (!( rptr->body )) { rptr = liberate_rest_response( rptr ); return( 0 ); } else if (!( document = document_parse_file( rptr->body ) )) { rptr = liberate_rest_response( rptr ); return( 0 ); } else if (!( eptr = document_element( document, "token" ) )) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } else if (!( aptr = document_atribut( eptr, "id" ) )) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } else if (!( aptr->value )) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } else if (!( sptr->Ezi.authenticate = allocate_string( aptr->value ))) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } else if (!( sptr->Ezi.authenticate = occi_unquoted_value( sptr->Ezi.authenticate ) )) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } else if (!( eptr = document_element( eptr, "tenant" ) )) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } else if (!( aptr = document_atribut( eptr, "id" ) )) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } else if (!( aptr->value )) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } else if (!( sptr->KeyStone.tenantid = allocate_string( aptr->value ))) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } else if (!( sptr->KeyStone.tenantid = occi_unquoted_value( sptr->KeyStone.tenantid ) )) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } else if (!( eptr = document_element( document, "serviceCatalog" ) )) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } else if (!( eptr = document_element( eptr, "service" ) )) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } else { while ( eptr ) { if (!( aptr = document_atribut( eptr, "type" ) )) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } else if (!( tptr = aptr->value )) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } else if ((!( tptr = allocate_string( tptr ) )) || (!( tptr = occi_unquoted_value( tptr ) ))) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } else if (!( strcasecmp( tptr, "compute" ) )) { liberate( tptr ); if (!( gptr = document_element( eptr, "endpoint" ) )) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } if (!( aptr = document_atribut( gptr, "publicURL" ) )) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } else if (!( aptr->value )) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } else if (!( sptr->Ezi.base = allocate_string( aptr->value ) )) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } else if (!( sptr->Ezi.base = occi_unquoted_value( sptr->Ezi.base ) )) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } } else if (!( strcasecmp( tptr, "image" ) )) { liberate( tptr ); if (!( gptr = document_element( eptr, "endpoint" ) )) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } if (!( aptr = document_atribut( gptr, "publicURL" ) )) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } else if (!( aptr->value )) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } else if (!( sptr->KeyStone.glance = allocate_string( aptr->value ) )) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } else if (!( sptr->KeyStone.glance = occi_unquoted_value( sptr->KeyStone.glance ) )) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } } else if (!( strcasecmp( tptr, "volume" ) )) { liberate( tptr ); if (!( gptr = document_element( eptr, "endpoint" ) )) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } if (!( aptr = document_atribut( gptr, "publicURL" ) )) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } else if (!( aptr->value )) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } else if (!( sptr->KeyStone.volume = allocate_string( aptr->value ) )) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } else if (!( sptr->KeyStone.volume = occi_unquoted_value( sptr->KeyStone.volume ) )) { document = document_drop( document ); rptr = liberate_rest_response( rptr ); return( 0 ); } } else liberate( tptr ); eptr = eptr->next; } document = document_drop( document ); rptr = liberate_rest_response( rptr ); if (!( sptr->Ezi.base )) return( 0 ); else if (!( sptr->Ezi.iaas )) return( 0 ); else return( 1 ); } } return( 1 ); } /* ------------------------------------------------------------ */ /* e z i _ a u t h e n t i c a t e () */ /* ------------------------------------------------------------ */ public struct rest_header * ezi_authenticate(struct ezi_subscription * sptr) { struct rest_header * hptr=(struct rest_header * ) 0; struct ezi_response * rptr; struct url * uptr; char * nptr; int status; char * eptr; char buffer[256]; /* --------------------------------- */ /* check if explicite Diablo Version */ /* --------------------------------- */ if (!( eptr = getenv("NOVADIABLO"))) status = 0; else status = atoi(eptr); if (!( status )) { if (!( check_keystone_authorization(sptr) )) return((struct rest_header * )0); else if (!( sptr->Ezi.authenticate )) return((struct rest_header * )0); } else { /* ------------------------------ */ /* Old Diablo Type Authentication */ /* ------------------------------ */ if (!( sptr->Ezi.user )) return( hptr ); else if (!( sptr->Ezi.password )) return( hptr ); else if (!( sptr->Ezi.version )) return( hptr ); else if (!( sptr->Ezi.authenticate )) { sprintf(buffer,"/%s",sptr->Ezi.version); if (!( uptr = analyse_url( sptr->Ezi.host ))) return( hptr ); else if (!( uptr = validate_url( uptr ) )) return( hptr ); else if (!( uptr->object = allocate_string( buffer ) )) { uptr = liberate_url( uptr ); return( hptr ); } else if (!( nptr = serialise_url( uptr,"" ) )) { uptr = liberate_url( uptr ); return( hptr ); } else uptr = liberate_url( uptr ); if (!( hptr = rest_create_header( "X-Auth-User", sptr->Ezi.user ) )) { liberate( nptr ); return( hptr ); } else if (!( hptr->next = rest_create_header( "X-Auth-Key", sptr->Ezi.password ) )) { liberate( nptr ); return( liberate_rest_header( hptr ) ); } else hptr->next->previous = hptr; if (!( rptr = ezi_client_get_request( nptr, sptr->Ezi.tls, sptr->Ezi.agent, hptr ) )) { liberate( nptr ); return( liberate_rest_header( hptr ) ); } else if (!( hptr = rest_resolve_header(rptr->response->first,"X-Auth-Token") )) { if (!( sptr->Ezi.authenticate = allocate_string("abcde-1234-5678-fgh-ijklm") )) { liberate( nptr ); return( (struct rest_header *) 0 ); } } else if (!( sptr->Ezi.authenticate = allocate_string( hptr->value ) )) { liberate( nptr ); return( (struct rest_header *) 0 ); } else if (( hptr = rest_resolve_header( rptr->response->first,"X-Server-Management-Url")) != (struct rest_header *) 0) { if (!( sptr->Ezi.base = allocate_string( hptr->value ) )) { liberate( nptr ); return( (struct rest_header *) 0 ); } } else if (!( hptr = rest_resolve_header(rptr->response->first,"X-Identity") )) { if (!( sptr->Ezi.base = allocate( strlen( sptr->Ezi.host ) + strlen( sptr->Ezi.version ) + 16 ) )) { liberate( nptr ); return( (struct rest_header *) 0 ); } else sprintf( sptr->Ezi.base, "%s/%s", sptr->Ezi.host, sptr->Ezi.version ); } else if (!( sptr->Ezi.base = allocate_string( hptr->value ) )) { liberate( nptr ); return( (struct rest_header *) 0 ); } } } if (!( sptr->Ezi.authenticate )) return((struct rest_header *) 0); else if (!( hptr = rest_create_header( "X-Auth-Token", sptr->Ezi.authenticate ) )) return( hptr ); else if (!( hptr->next = rest_create_header( _HTTP_ACCEPT, "text/xml" ) )) return( liberate_rest_header( hptr ) ); else return((hptr->next->previous = hptr)); } /* ------------------------------------------------------------ */ /* e z i _ d e l e t e _ o p e r a t i o n */ /* ------------------------------------------------------------ */ private struct ezi_response * ezi_delete_operation(struct ezi_subscription * sptr, char * buffer ) { struct ezi_response * rptr=(struct ezi_response *) 0; struct url * uptr; char * nptr; struct rest_header * hptr=(struct rest_header * ) 0; char uri[2048]; if (!( hptr = ezi_authenticate(sptr) )) return( rptr ); else sprintf(uri,"%s/%s",sptr->Ezi.iaas,sptr->KeyStone.tenantid); if (!( uptr = analyse_url( uri ))) return( rptr ); else if (!( uptr = validate_url( uptr ) )) return( rptr ); else if (!( nptr = serialise_url( uptr,buffer ) )) { uptr = liberate_url( uptr ); return( rptr ); } else if (!( rptr = ezi_client_delete_request( nptr, sptr->Ezi.tls, sptr->Ezi.agent, hptr ) )) { uptr = liberate_url( uptr ); liberate( nptr ); return( rptr ); } else return( rptr ); } /* ------------------------------------------------------------ */ /* e z i _ g e t _ o p e r a t i o n */ /* ------------------------------------------------------------ */ private struct ezi_response * ezi_get_operation(struct ezi_subscription * sptr, char * buffer ) { struct ezi_response * rptr=(struct ezi_response *) 0; struct url * uptr; char * nptr; struct rest_header * hptr=(struct rest_header * ) 0; char uri[2048]; if (!( hptr = ezi_authenticate(sptr) )) return( rptr ); else sprintf(uri,"%s/%s",sptr->Ezi.iaas,sptr->KeyStone.tenantid); if (!( uptr = analyse_url( uri ))) return( rptr ); else if (!( uptr = validate_url( uptr ) )) return( rptr ); else if (!( nptr = serialise_url( uptr,buffer ) )) { uptr = liberate_url( uptr ); return( rptr ); } else if (!( rptr = ezi_client_get_request( nptr, sptr->Ezi.tls, sptr->Ezi.agent, hptr ) )) { uptr = liberate_url( uptr ); liberate( nptr ); return( rptr ); } else return( rptr ); } /* ------------------------------------------------------------ */ /* e z i _ c r e a t e _ o p e r a t i o n */ /* ------------------------------------------------------------ */ private struct ezi_response * ezi_create_operation(struct ezi_subscription * sptr, char * buffer, char * filename ) { struct ezi_response * rptr=(struct ezi_response *) 0; struct url * uptr; char * nptr; struct rest_header * hptr=(struct rest_header * ) 0; char uri[2048]; if (!( hptr = ezi_authenticate(sptr) )) return( rptr ); else sprintf(uri,"%s/%s",sptr->Ezi.iaas,sptr->KeyStone.tenantid); if (!( uptr = analyse_url( uri ))) return( rptr ); else if (!( uptr = validate_url( uptr ) )) return( rptr ); else if (!( nptr = serialise_url( uptr,buffer ) )) { uptr = liberate_url( uptr ); return( rptr ); } else if (!( rptr = ezi_client_post_request( nptr, sptr->Ezi.tls, sptr->Ezi.agent, filename, hptr ) )) { uptr = liberate_url( uptr ); return( rptr ); } else return( rptr ); } /* ------------------------------------------------------------ */ /* e z i _ c r e a t e _ s e r v e r */ /* ------------------------------------------------------------ */ public struct ezi_response * ezi_create_server(struct ezi_subscription * sptr, char * filename ) { char buffer[1024]; sprintf(buffer,"/compound_app"); return( ezi_create_operation( sptr, buffer, filename ) ); } /* ------------------------------------------------------------ */ /* e z i _ d e l e t e _ s e r v e r */ /* ------------------------------------------------------------ */ public struct ezi_response * ezi_delete_server(struct ezi_subscription * sptr, char * id ) { struct ezi_response * rptr=(struct ezi_response *) 0; struct url * uptr; char buffer[1024]; char * nptr; struct rest_header * hptr=(struct rest_header * ) 0; if (!( id )) sprintf(buffer,"/compound_app"); else sprintf(buffer,"/compound_app/%s",id); return( ezi_delete_operation( sptr, buffer ) ); } /* ------------------------------------------------------------ */ /* e z i _ g e t _ s e r v e r */ /* ------------------------------------------------------------ */ public struct ezi_response * ezi_get_server ( struct ezi_subscription * sptr, char * id ) { struct ezi_response * rptr=(struct ezi_response *) 0; struct url * uptr; char buffer[1024]; char * nptr; struct rest_header * hptr=(struct rest_header * ) 0; if (!( id )) sprintf(buffer,"/compoud_app"); else sprintf(buffer,"/compoud_app/%s",id); return( ezi_get_operation( sptr, buffer ) ); } /* ------------------------------------------------------------ */ /* e z i _ l i b e r a t e _ s u b s c r i p t i o n */ /* ------------------------------------------------------------ */ public struct ezi_subscription * ezi_liberate_subscription(struct ezi_subscription * sptr) { if ( sptr ) { liberate( sptr ); } return((struct ezi_subscription *) 0); } /* ------------------------------------------------------------ */ /* e z i _ a l l o c a t e _ s u b s c r i p t i o n */ /* ------------------------------------------------------------ */ public struct ezi_subscription * ezi_allocate_subscription() { struct ezi_subscription * sptr; if (!( sptr = (struct ezi_subscription *) allocate( sizeof( struct ezi_subscription ) ) )) return( sptr ); else { memset( sptr, 0, sizeof( struct ezi_subscription )); if (!( sptr->KeyStone.requestauth = allocate_string( "application/xml" ) )) return( ezi_liberate_subscription( sptr ) ); else if (!( sptr->KeyStone.acceptauth = allocate_string( "application/xml" ) )) return( ezi_liberate_subscription( sptr ) ); else return( sptr ); } } /* ------------------------------------------------------------ */ /* e z i _ i n i t i a l i s e _ c l i e n t */ /* ------------------------------------------------------------ */ public struct ezi_subscription * ezi_initialise_client( char * user, char * password, char * tenant, char * host, char * iaas, char * agent, char * version, char * tls ) { struct ezi_subscription * sptr=(struct ezi_subscription *) 0; char * eptr; struct url * url; char buffer[1024]; if (!( sptr = ezi_allocate_subscription())) return( sptr ); else if (!( url = analyse_url( host ))) return(ezi_liberate_subscription( sptr )); else if (!( sptr->KeyStone.host = serialise_url_host_no_port( url ) )) return(ezi_liberate_subscription( sptr )); else liberate_url( url ); if (!( sptr->Ezi.user = allocate_string( user ))) return(ezi_liberate_subscription( sptr ) ); if (!( sptr->Ezi.password = allocate_string( password ))) return(ezi_liberate_subscription( sptr )); if (!( sptr->Ezi.host = allocate_string( host ))) return(ezi_liberate_subscription( sptr )); else if (!( sptr->Ezi.agent = allocate_string( agent ))) return(ezi_liberate_subscription( sptr )); else if (!( sptr->Ezi.version = allocate_string( version ))) return(ezi_liberate_subscription( sptr )); else if (!( sptr->KeyStone.tenantname = allocate_string( tenant ))) return(ezi_liberate_subscription( sptr )); if (!( sptr->Ezi.iaas = allocate_string( iaas ))) return(ezi_liberate_subscription( sptr )); /* namespace selection */ if (!( strcmp( sptr->Ezi.version, "v1.0" ) )) { if (!( sptr->Ezi.namespace = allocate_string( _OS_NS_COMPUTE_V10 ) )) return(ezi_liberate_subscription( sptr )); } else if (!( strcmp( sptr->Ezi.version, "v1.1" ) )) { if (!( sptr->Ezi.namespace = allocate_string( _OS_NS_COMPUTE_V11 ) )) return(ezi_liberate_subscription( sptr )); } else return(ezi_liberate_subscription( sptr )); sptr->Ezi.authenticate= (char *) 0; if (!( tls )) sptr->Ezi.tls = (char *) 0; else if ((sptr->Ezi.tls = allocate_string(tls)) != (char *) 0) if ( (!( strlen( sptr->Ezi.tls ) )) || ( *(sptr->Ezi.tls) == '0' ) ) sptr->Ezi.tls = liberate( sptr->Ezi.tls ); return( sptr ); } /* ------------ */ #endif /* _eziclient_c */ /* ------------ */
30.636837
115
0.549181
[ "object" ]
1187872be93967f5e81019ab3cf05091f471dc03
6,393
h
C
testcpp/include/ecs/EntitySet.h
phaisarnsut/dependency-graph
dc087ae318c2c8d4fb1213ecd3714773b2ded39f
[ "MIT" ]
37
2019-07-09T15:26:18.000Z
2022-03-23T16:13:38.000Z
testcpp/include/ecs/EntitySet.h
phaisarnsut/dependency-graph
dc087ae318c2c8d4fb1213ecd3714773b2ded39f
[ "MIT" ]
1
2022-02-04T09:56:18.000Z
2022-02-04T09:56:18.000Z
testcpp/include/ecs/EntitySet.h
phaisarnsut/dependency-graph
dc087ae318c2c8d4fb1213ecd3714773b2ded39f
[ "MIT" ]
4
2019-12-03T17:20:26.000Z
2022-02-26T20:47:28.000Z
#pragma once #include <functional> #include <memory> #include "ComponentContainer.h" #include "EntitySetIterator.h" #include "EntitySetType.h" #include "EntityContainer.h" namespace ecs { template<typename ...Ts> class EntitySet; class BaseEntitySet { public: static std::size_t getEntitySetCount() { return sFactories.size(); } static std::unique_ptr<BaseEntitySet> createEntitySet(std::size_t type, EntityContainer& entities, const std::vector<std::unique_ptr<BaseComponentContainer>>& componentContainers, std::vector<std::vector<BaseEntitySet*>>& componentToEntitySets) { return sFactories[type](entities, componentContainers, componentToEntitySets); } BaseEntitySet() { } virtual ~BaseEntitySet() = default; bool hasEntity(Entity entity) const { return mEntityToIndex.find(entity) != std::end(mEntityToIndex); } void onEntityUpdated(Entity entity) { auto satisfied = satisfyRequirements(entity); auto managed = hasEntity(entity); if (satisfied && !managed) addEntity(entity); else if (!satisfied && managed) removeEntity(entity, true); } void onEntityRemoved(Entity entity) { removeEntity(entity, false); } protected: virtual bool satisfyRequirements(Entity entity) = 0; virtual void addEntity(Entity entity) = 0; virtual void removeEntity(Entity entity, bool updateEntity) = 0; std::unordered_map<Entity, std::size_t> mEntityToIndex; template<typename ...Ts> static EntitySetType generateEntitySetType() { sFactories.push_back([](EntityContainer& entities, const std::vector<std::unique_ptr<BaseComponentContainer>>& componentContainers, std::vector<std::vector<BaseEntitySet*>>& componentToEntitySets) -> std::unique_ptr<BaseEntitySet> { auto entitySet = std::make_unique<EntitySet<Ts...>>(entities, std::tie(static_cast<ComponentContainer<Ts>*>(componentContainers[Ts::Type].get())->components...)); (componentToEntitySets[Ts::Type].push_back(entitySet.get()), ...); return std::move(entitySet); }); return sFactories.size() - 1; } private: using EntitySetFactory = std::unique_ptr<BaseEntitySet>(*)( EntityContainer&, const std::vector<std::unique_ptr<BaseComponentContainer>>&, std::vector<std::vector<BaseEntitySet*>>&); static std::vector<EntitySetFactory> sFactories; }; inline std::vector<BaseEntitySet::EntitySetFactory> BaseEntitySet::sFactories; template<typename ...Ts> class EntitySet : public BaseEntitySet { using ValueType = std::pair<Entity, std::array<ComponentId, sizeof...(Ts)>>; using UIterator = typename std::vector<ValueType>::iterator; // Underlying iterator using UConstIterator = typename std::vector<ValueType>::const_iterator; // Underlying const iterator using ComponentContainers = std::tuple<ComponentSparseSet<Ts>&...>; public: using Iterator = EntitySetIterator<UIterator, Ts...>; using ConstIterator = EntitySetIterator<UConstIterator, const Ts...>; using ListenerId = uint32_t; using EntityAddedListener = std::function<void(Entity)>; using EntityRemovedListener = std::function<void(Entity)>; static const EntitySetType Type; EntitySet(EntityContainer& entities, const ComponentContainers& componentContainers) : mEntities(entities), mComponentContainers(componentContainers) { } std::size_t getSize() const { return mManagedEntities.size(); } Iterator begin() { return Iterator(mManagedEntities.begin(), mComponentContainers); } ConstIterator begin() const { return ConstIterator(mManagedEntities.begin(), mComponentContainers); } Iterator end() { return Iterator(mManagedEntities.end(), mComponentContainers); } ConstIterator end() const { return ConstIterator(mManagedEntities.end(), mComponentContainers); } // Listeners ListenerId addEntityAddedListener(EntityAddedListener listener) { return mEntityAddedListeners.emplace(std::move(listener)).first; } void removeEntityAddedListener(ListenerId listenerId) { mEntityAddedListeners.erase(listenerId); } ListenerId addEntityRemovedListener(EntityRemovedListener listener) { return mEntityRemovedListeners.emplace(std::move(listener)).first; } void removeEntityRemovedListener(ListenerId listenerId) { mEntityRemovedListeners.erase(listenerId); } protected: bool satisfyRequirements(Entity entity) override { return mEntities.get(entity).template hasComponents<Ts...>(); } void addEntity(Entity entity) override { mEntityToIndex[entity] = mManagedEntities.size(); auto& entityData = mEntities.get(entity); entityData.addEntitySet(Type); mManagedEntities.emplace_back(entity, std::array<ComponentId, sizeof...(Ts)>{entityData.template getComponent<Ts>()...}); // Call listeners for (const auto& listener : mEntityAddedListeners.getObjects()) listener(entity); } void removeEntity(Entity entity, bool updateEntity) override { // Call listeners for (const auto& listener : mEntityRemovedListeners.getObjects()) listener(entity); auto it = mEntityToIndex.find(entity); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wnull-dereference" auto index = it->second; #pragma GCC diagnostic pop mEntityToIndex[mManagedEntities.back().first] = index; mEntityToIndex.erase(it); mManagedEntities[index] = mManagedEntities.back(); mManagedEntities.pop_back(); if (updateEntity) mEntities.get(entity).removeEntitySet(Type); } private: std::vector<ValueType> mManagedEntities; EntityContainer& mEntities; ComponentContainers mComponentContainers; SparseSet<ListenerId, EntityAddedListener> mEntityAddedListeners; SparseSet<ListenerId, EntityRemovedListener> mEntityRemovedListeners; }; template<typename ...Ts> const EntitySetType EntitySet<Ts...>::Type = BaseEntitySet::generateEntitySetType<Ts...>(); }
30.588517
129
0.683247
[ "vector" ]
1198933ebc6ad7a8cfc702705a30e0682d76dda2
2,425
h
C
include/gdk/vector4.h
jfcameron/GDK-Math
1817c6f4af08a1da9e6efedf2130e20d4f64813f
[ "MIT" ]
null
null
null
include/gdk/vector4.h
jfcameron/GDK-Math
1817c6f4af08a1da9e6efedf2130e20d4f64813f
[ "MIT" ]
7
2019-06-19T15:13:04.000Z
2019-11-20T00:32:33.000Z
include/gdk/vector4.h
jfcameron/gdk-math
1817c6f4af08a1da9e6efedf2130e20d4f64813f
[ "MIT" ]
null
null
null
// © 2018 Joseph Cameron - All Rights Reserved #ifndef GDK_MATH_VECTOR4_H #define GDK_MATH_VECTOR4_H #include <iosfwd> #include <gdk/vector3.h> namespace gdk { /// \brief Like Vector3<component_type> but allows w to != 1. Used in Vector vs Mat4x4 operations template<typename component_type_param = float> struct Vector4 final { using component_type = component_type_param; float x = {0.}, y = {0.}, z = {0.}, w = {1.}; bool operator==(const Vector4<component_type> &other) const { return x == other.x && y == other.y && z == other.z && w == other.w; } bool operator!=(const Vector4<component_type> &other) const { return x != other.x || y != other.y || z != other.z || w != other.w; } Vector4<component_type> &operator+=(const Vector4<component_type> &other) { x += other.x; y += other.y; z += other.z; w += other.w; return *this; } Vector4<component_type> &operator*=(const float &aScalar) { x *= aScalar; y *= aScalar; z *= aScalar; w *= aScalar; return *this; } Vector4<component_type> &operator=(const Vector4<component_type> &) = default; Vector4<component_type>(const Vector3<component_type> &aVector3, const float &aW = 1.) : x(aVector3.x) , y(aVector3.y) , z(aVector3.z) , w(aW) {} Vector4<component_type>(const float &aX, const float &aY, const float &aZ, const float &aW) : x(aX) , y(aY) , z(aZ) , w(aW) {} Vector4<component_type>() : x(0.) , y(0.) , z(0.) , w(1.) {} Vector4<component_type>(const Vector4<component_type> &) = default; Vector4<component_type>(Vector4<component_type> &&) = default; ~Vector4<component_type>() = default; static const Vector4<component_type> Zero; }; template<typename T> const Vector4<T> Vector4<T>::Zero = {0., 0., 0., 0.}; template<typename T> std::ostream &operator<< (std::ostream &s, const Vector4<T> &vector) { return s << "{x: " << vector.x << ", y: " << vector.y << ", z: " << vector.z << ", w: " << vector.w << "}"; } } #endif
27.247191
115
0.517113
[ "vector" ]
119d11fe1dd6ab1c4633ae9bfc4308f487ff92ca
1,942
c
C
dndml/test_dnd_parser.c
DanteFalzone0/tryptobot
f4498d4eafdeeee965df1941f88724e93d250d51
[ "MIT" ]
2
2022-03-28T01:03:23.000Z
2022-03-31T18:09:04.000Z
dndml/test_dnd_parser.c
DanteFalzone0/tryptobot
f4498d4eafdeeee965df1941f88724e93d250d51
[ "MIT" ]
null
null
null
dndml/test_dnd_parser.c
DanteFalzone0/tryptobot
f4498d4eafdeeee965df1941f88724e93d250d51
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "dnd_input_reader.h" #include "dnd_lexer.h" #include "dnd_charsheet.h" #include "dnd_parser.h" // copied straight from tryptobot.c; quick hack but it works static char *load_file_to_str(const char *filename) { FILE *f = fopen(filename, "rb"); char *result; if (f) { fseek(f, 0, SEEK_END); long length = ftell(f); int x; fseek(f, 0, SEEK_SET); result = malloc(length+1); if (result) { x = fread(result, 1, length, f); result[x] = '\0'; } else { fprintf(stderr, "Memory allocation error\n"); fclose(f); return NULL; } } else { fprintf(stderr, "Unable to find `%s`\n", filename); return NULL; } fclose(f); return result; } /* gcc -c dnd_input_reader.c -Wall -std=gnu11 gcc -c dnd_lexer.c -Wall -std=gnu11 gcc -c dnd_charsheet.c -Wall -std=gnu11 gcc -c dnd_parser.c -Wall -std=gnu11 gcc test_dnd_parser.c \ dnd_input_reader.o \ dnd_lexer.o \ dnd_charsheet.o \ dnd_parser.o \ -o test-parser.x86 -Wall -std=gnu11 ./test-parser.x86 [file to parse] */ int main(int argc, char *argv[]) { if (argc < 2) { printf("error: no file passed\n"); return 1; } char *file_contents = load_file_to_str(argv[1]); if (file_contents == NULL) { printf("error: %s: no such file or directory\n", argv[1]); return 1; } input_reader_t ir; construct_input_reader(&ir, file_contents); lexer_t lex; construct_lexer(&lex, &ir); parser_t parser; construct_parser(&parser, &lex, argv[1]); charsheet_t *charsheet = parser.parse(&parser); if (charsheet == NULL) { printf("parser.parse() returned a NULL object.\n"); return 1; } char *output = charsheet_to_str(charsheet); if (output != NULL) printf("%s", output); else printf("Null pointer obtained\n"); free_charsheet(charsheet); free(output); return 0; }
22.321839
62
0.631308
[ "object" ]
11a1095c504dcc4dac567abbeffe11a7e9d91190
2,198
h
C
src/graph.h
IrisChase/IVD
7d319fbd8a8a688987b788d7095d84734a627ba1
[ "Apache-2.0" ]
1
2020-07-02T02:06:21.000Z
2020-07-02T02:06:21.000Z
src/graph.h
IrisChase/IVD
7d319fbd8a8a688987b788d7095d84734a627ba1
[ "Apache-2.0" ]
10
2020-07-05T07:41:34.000Z
2020-12-21T20:33:09.000Z
src/graph.h
IrisChase/IVD
7d319fbd8a8a688987b788d7095d84734a627ba1
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 Iris Chase // // 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. #pragma once #include <vector> #include <string> #include "irisutils/lexcompare.h" #include "codeposition.h" namespace IVD { namespace Animation { class Graph { public: struct Sample { double x; double y; //Constantly double your weight with this one w e i r d t r i c k IRISUTILS_DEFINE_COMP(Sample, x, y) }; private: std::vector<Sample> mySamples; struct TwoSamplePoints { Sample left; Sample right; }; int interpolationMode; TwoSamplePoints getSamplePoints(double percent) const; double getLinearWeightForPercentage(double percent) const; double getSmoothWeightForPercentage(double percent) const; public: Graph(); Graph(const int interpolationMode): interpolationMode(interpolationMode) {} void addSample(const double weight, const double percent) { mySamples.emplace_back(Sample{weight, percent}); } void setSamples(const std::vector<Sample> samples) { mySamples = samples; } int getInterpolatedScalarForPercentage(const int origin, const int dest, const double percentage) const; //Rename this to unleash dragons. CodePosition definedAt; std::string generatePrintout(); IRISUTILS_DEFINE_COMP(Graph, mySamples, interpolationMode, definedAt) }; struct Transition { int miliseconds; Graph graph; //Girafe, what a gaffe... std::string generatePrintout(); IRISUTILS_DEFINE_COMP(Transition, miliseconds, graph) }; }//Animation }//IVD
23.136842
86
0.680619
[ "vector" ]
11c289e6d0262eb33a26cbeb26c7d5437f2358e3
50,475
h
C
numerical_lie_group/rigid3d.h
jk-jeon/jkj
d8915b56702eae39de80a61677a4c4f4afa30924
[ "MIT" ]
1
2021-01-31T11:52:50.000Z
2021-01-31T11:52:50.000Z
numerical_lie_group/rigid3d.h
jk-jeon/jkj
d8915b56702eae39de80a61677a4c4f4afa30924
[ "MIT" ]
1
2018-12-04T17:10:35.000Z
2018-12-09T02:51:10.000Z
numerical_lie_group/rigid3d.h
jk-jeon/jkj
d8915b56702eae39de80a61677a4c4f4afa30924
[ "MIT" ]
null
null
null
///////////////////////////////////////////////////////////////////////////////////////////////////////// /// Copyright (c) 2018 Junekey Jeon /// /// 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. /// ///////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma once #include "../tmp/assert_helper.h" #include "rotation3d.h" namespace jkj { namespace math { // 3-dimensional rigid transform namespace detail { struct use_SO3_tag {}; template <class ComponentType, class SU2Storage, class SU2StorageTraits, class R3Storage, class R3StorageTraits> struct SE3_elmt_base { using rotation_type = SU2_elmt<ComponentType, SU2Storage, SU2StorageTraits>; using translation_type = R3_elmt<ComponentType, R3Storage, R3StorageTraits>; protected: rotation_type rot_; translation_type trans_; SE3_elmt_base() = default; template <class...> struct is_nothrow_constructible : std::false_type {}; template <class RotArg, class TransArg> struct is_nothrow_constructible<RotArg, TransArg> { static constexpr bool value = std::is_nothrow_constructible<rotation_type, RotArg>::value && std::is_nothrow_constructible<translation_type, TransArg>::value; }; template <class RotArg, class TransArg> struct is_nothrow_constructible<use_SO3_tag, RotArg, TransArg> { static constexpr bool value = noexcept(std::declval<RotArg>().template find_quaternion<typename rotation_type::component_type, typename rotation_type::storage_type, typename rotation_type::storage_traits>()) && std::is_nothrow_move_constructible<rotation_type>::value && std::is_nothrow_constructible<translation_type, TransArg>::value; }; template <class RotArg, class TransArg> JKL_GPU_EXECUTABLE constexpr SE3_elmt_base(forward_to_storage_tag, RotArg&& r, TransArg&& t) noexcept(is_nothrow_constructible<RotArg, TransArg>::value) : rot_(std::forward<RotArg>(r)), trans_(std::forward<TransArg>(t)) {} template <class RotArg, class TransArg> JKL_GPU_EXECUTABLE constexpr SE3_elmt_base(forward_to_storage_tag, use_SO3_tag, RotArg&& r, TransArg&& t) noexcept(is_nothrow_constructible<use_SO3_tag, RotArg, TransArg>::value) : rot_(std::forward<RotArg>(r).template find_quaternion<typename rotation_type::component_type, typename rotation_type::storage_type, typename rotation_type::storage_traits>()), trans_(std::forward<TransArg>(t)) {} }; } template <class ComponentType, class SU2Storage, class SU2StorageTraits, class R3Storage, class R3StorageTraits> class SE3_elmt : public tmp::generate_constructors< detail::SE3_elmt_base<ComponentType, SU2Storage, SU2StorageTraits, R3Storage, R3StorageTraits>, detail::forward_to_storage_tag, tmp::copy_or_move<SU2_elmt<ComponentType, SU2Storage, SU2StorageTraits>, R3_elmt<ComponentType, R3Storage, R3StorageTraits>>> { using base_type = tmp::generate_constructors< detail::SE3_elmt_base<ComponentType, SU2Storage, SU2StorageTraits, R3Storage, R3StorageTraits>, detail::forward_to_storage_tag, tmp::copy_or_move<SU2_elmt<ComponentType, SU2Storage, SU2StorageTraits>, R3_elmt<ComponentType, R3Storage, R3StorageTraits>>>; public: using rotation_type = SU2_elmt<ComponentType, SU2Storage, SU2StorageTraits>; using translation_type = R3_elmt<ComponentType, R3Storage, R3StorageTraits>; public: using component_type = ComponentType; static constexpr std::size_t components = 7; JKL_GPU_EXECUTABLE NONCONST_CONSTEXPR rotation_type& rotation_q() & noexcept { return base_type::rot_; } JKL_GPU_EXECUTABLE constexpr rotation_type const& rotation_q() const& noexcept { return base_type::rot_; } JKL_GPU_EXECUTABLE NONCONST_CONSTEXPR rotation_type&& rotation_q() && noexcept { return std::move(base_type::rot_); } JKL_GPU_EXECUTABLE constexpr rotation_type const&& rotation_q() const&& noexcept { return std::move(base_type::rot_); } JKL_GPU_EXECUTABLE NONCONST_CONSTEXPR translation_type& translation() & noexcept { return base_type::trans_; } JKL_GPU_EXECUTABLE constexpr translation_type const& translation() const& noexcept { return base_type::trans_; } JKL_GPU_EXECUTABLE NONCONST_CONSTEXPR translation_type&& translation() && noexcept { return std::move(base_type::trans_); } JKL_GPU_EXECUTABLE constexpr translation_type const&& translation() const&& noexcept { return std::move(base_type::trans_); } JKL_GPU_EXECUTABLE constexpr SO3_elmt<ComponentType> rotation() const& noexcept(noexcept(SO3_elmt<ComponentType>(base_type::rot_))) { return SO3_elmt<ComponentType>(base_type::rot_); } JKL_GPU_EXECUTABLE NONCONST_CONSTEXPR SO3_elmt<ComponentType> rotation() && noexcept(noexcept(SO3_elmt<ComponentType>(std::move(base_type::rot_)))) { return SO3_elmt<ComponentType>(std::move(base_type::rot_)); } using base_type::base_type; // Default constructor; components might be filled with garbages SE3_elmt() = default; // Take SO3_elmt and R3_elmt (both are template) template <class OtherComponentType, class OtherSO3Storage, class OtherSO3StorageTraits, class OtherR3Storage, class OtherR3StorageTraits, class = std::enable_if_t<std::is_convertible<OtherComponentType, ComponentType>::value>> JKL_GPU_EXECUTABLE constexpr SE3_elmt( SO3_elmt<OtherComponentType, OtherSO3Storage, OtherSO3StorageTraits> const& rot, R3_elmt<OtherComponentType, OtherR3Storage, OtherR3StorageTraits> const& trans) noexcept(base_type::template is_nothrow_constructible<detail::use_SO3_tag, SO3_elmt<OtherComponentType, OtherSO3Storage, OtherSO3StorageTraits> const&, R3_elmt<OtherComponentType, OtherR3Storage, OtherR3StorageTraits> const&>::value) : base_type{ detail::forward_to_storage_tag{}, detail::use_SO3_tag{}, rot, trans } {} template <class OtherComponentType, class OtherSO3Storage, class OtherSO3StorageTraits, class OtherR3Storage, class OtherR3StorageTraits, class = std::enable_if_t<std::is_convertible<OtherComponentType, ComponentType>::value>> JKL_GPU_EXECUTABLE constexpr SE3_elmt( SO3_elmt<OtherComponentType, OtherSO3Storage, OtherSO3StorageTraits> const& rot, R3_elmt<OtherComponentType, OtherR3Storage, OtherR3StorageTraits>&& trans) noexcept(base_type::template is_nothrow_constructible<detail::use_SO3_tag, SO3_elmt<OtherComponentType, OtherSO3Storage, OtherSO3StorageTraits> const&, R3_elmt<OtherComponentType, OtherR3Storage, OtherR3StorageTraits>>::value) : base_type{ detail::forward_to_storage_tag{}, detail::use_SO3_tag{}, rot, std::move(trans) } {} template <class OtherComponentType, class OtherSO3Storage, class OtherSO3StorageTraits, class OtherR3Storage, class OtherR3StorageTraits, class = std::enable_if_t<std::is_convertible<OtherComponentType, ComponentType>::value>> JKL_GPU_EXECUTABLE constexpr SE3_elmt( SO3_elmt<OtherComponentType, OtherSO3Storage, OtherSO3StorageTraits>&& rot, R3_elmt<OtherComponentType, OtherR3Storage, OtherR3StorageTraits> const& trans) noexcept(base_type::template is_nothrow_constructible<detail::use_SO3_tag, SO3_elmt<OtherComponentType, OtherSO3Storage, OtherSO3StorageTraits>, R3_elmt<OtherComponentType, OtherR3Storage, OtherR3StorageTraits> const&>::value) : base_type{ detail::forward_to_storage_tag{}, detail::use_SO3_tag{}, std::move(rot), trans } {} template <class OtherComponentType, class OtherSO3Storage, class OtherSO3StorageTraits, class OtherR3Storage, class OtherR3StorageTraits, class = std::enable_if_t<std::is_convertible<OtherComponentType, ComponentType>::value>> JKL_GPU_EXECUTABLE constexpr SE3_elmt( SO3_elmt<OtherComponentType, OtherSO3Storage, OtherSO3StorageTraits>&& rot, R3_elmt<OtherComponentType, OtherR3Storage, OtherR3StorageTraits>&& trans) noexcept(base_type::template is_nothrow_constructible<detail::use_SO3_tag, SO3_elmt<OtherComponentType, OtherSO3Storage, OtherSO3StorageTraits>, R3_elmt<OtherComponentType, OtherR3Storage, OtherR3StorageTraits>>::value) : base_type{ detail::forward_to_storage_tag{}, detail::use_SO3_tag{}, std::move(rot), std::move(trans) } {} // Take SO3_elmt and R3_elmt (R3_elmt is a concrete type) template <class OtherComponentType, class OtherSO3Storage, class OtherSO3StorageTraits, class = std::enable_if_t<std::is_convertible<OtherComponentType, ComponentType>::value>> JKL_GPU_EXECUTABLE constexpr SE3_elmt( SO3_elmt<OtherComponentType, OtherSO3Storage, OtherSO3StorageTraits> const& rot, translation_type const& trans) noexcept(base_type::template is_nothrow_constructible<detail::use_SO3_tag, SO3_elmt<OtherComponentType, OtherSO3Storage, OtherSO3StorageTraits> const&, translation_type const&>::value) : base_type{ detail::forward_to_storage_tag{}, detail::use_SO3_tag{}, rot, trans } {} template <class OtherComponentType, class OtherSO3Storage, class OtherSO3StorageTraits, class = std::enable_if_t<std::is_convertible<OtherComponentType, ComponentType>::value>> JKL_GPU_EXECUTABLE constexpr SE3_elmt( SO3_elmt<OtherComponentType, OtherSO3Storage, OtherSO3StorageTraits> const& rot, translation_type&& trans) noexcept(base_type::template is_nothrow_constructible<detail::use_SO3_tag, SO3_elmt<OtherComponentType, OtherSO3Storage, OtherSO3StorageTraits> const&, translation_type>::value) : base_type{ detail::forward_to_storage_tag{}, detail::use_SO3_tag{}, rot, std::move(trans) } {} template <class OtherComponentType, class OtherSO3Storage, class OtherSO3StorageTraits, class = std::enable_if_t<std::is_convertible<OtherComponentType, ComponentType>::value>> JKL_GPU_EXECUTABLE constexpr SE3_elmt( SO3_elmt<OtherComponentType, OtherSO3Storage, OtherSO3StorageTraits>&& rot, translation_type const& trans) noexcept(base_type::template is_nothrow_constructible<detail::use_SO3_tag, SO3_elmt<OtherComponentType, OtherSO3Storage, OtherSO3StorageTraits>, translation_type const&>::value) : base_type{ detail::forward_to_storage_tag{}, detail::use_SO3_tag{}, std::move(rot), trans } {} template <class OtherComponentType, class OtherSO3Storage, class OtherSO3StorageTraits, class = std::enable_if_t<std::is_convertible<OtherComponentType, ComponentType>::value>> JKL_GPU_EXECUTABLE constexpr SE3_elmt( SO3_elmt<OtherComponentType, OtherSO3Storage, OtherSO3StorageTraits>&& rot, translation_type&& trans) noexcept(base_type::template is_nothrow_constructible<detail::use_SO3_tag, SO3_elmt<OtherComponentType, OtherSO3Storage, OtherSO3StorageTraits>, translation_type>::value) : base_type{ detail::forward_to_storage_tag{}, detail::use_SO3_tag{}, std::move(rot), std::move(trans) } {} // Take SO3_elmt and R3_elmt (both are concrete types) JKL_GPU_EXECUTABLE constexpr SE3_elmt( SO3_elmt<ComponentType> const& rot, translation_type const& trans) noexcept(base_type::template is_nothrow_constructible<detail::use_SO3_tag, SO3_elmt<ComponentType> const&, translation_type const&>::value) : base_type{ detail::forward_to_storage_tag{}, detail::use_SO3_tag{}, rot, trans } {} JKL_GPU_EXECUTABLE constexpr SE3_elmt( SO3_elmt<ComponentType> const& rot, translation_type&& trans) noexcept(base_type::template is_nothrow_constructible<detail::use_SO3_tag, SO3_elmt<ComponentType> const&, translation_type>::value) : base_type{ detail::forward_to_storage_tag{}, detail::use_SO3_tag{}, rot, std::move(trans) } {} JKL_GPU_EXECUTABLE constexpr SE3_elmt( SO3_elmt<ComponentType>&& rot, translation_type const& trans) noexcept(base_type::template is_nothrow_constructible<detail::use_SO3_tag, SO3_elmt<ComponentType>, translation_type const&>::value) : base_type{ detail::forward_to_storage_tag{}, detail::use_SO3_tag{}, std::move(rot), trans } {} JKL_GPU_EXECUTABLE constexpr SE3_elmt( SO3_elmt<ComponentType>&& rot, translation_type&& trans) noexcept(base_type::template is_nothrow_constructible<detail::use_SO3_tag, SO3_elmt<ComponentType>, translation_type>::value) : base_type{ detail::forward_to_storage_tag{}, detail::use_SO3_tag{}, std::move(rot), std::move(trans) } {} // Convert from SE3_elmt of other component type template <class OtherComponentType, class OtherSU2Storage, class OtherSU2StorageTraits, class OtherR3Storage, class OtherR3StorageTraits, class = std::enable_if_t<!std::is_same<SE3_elmt, SE3_elmt<OtherComponentType, OtherSU2Storage, OtherSU2StorageTraits, OtherR3Storage, OtherR3StorageTraits>>::value && std::is_convertible<OtherComponentType, ComponentType>::value>> JKL_GPU_EXECUTABLE constexpr SE3_elmt( SE3_elmt<OtherComponentType, OtherSU2Storage, OtherSU2StorageTraits, OtherR3Storage, OtherR3StorageTraits> const& that) noexcept(noexcept(base_type{ detail::forward_to_storage_tag{}, that.rotation_q(), that.translation() })) : base_type{ detail::forward_to_storage_tag{}, that.rotation_q(), that.translation() } {} template <class OtherComponentType, class OtherSU2Storage, class OtherSU2StorageTraits, class OtherR3Storage, class OtherR3StorageTraits, class = std::enable_if_t<!std::is_same<SE3_elmt, SE3_elmt<OtherComponentType, OtherSU2Storage, OtherSU2StorageTraits, OtherR3Storage, OtherR3StorageTraits>>::value && std::is_convertible<OtherComponentType, ComponentType>::value>> JKL_GPU_EXECUTABLE constexpr SE3_elmt( SE3_elmt<OtherComponentType, OtherSU2Storage, OtherSU2StorageTraits, OtherR3Storage, OtherR3StorageTraits>&& that) noexcept(noexcept(base_type{ detail::forward_to_storage_tag{}, std::move(that).rotation_q(), std::move(that).translation() })) : base_type{ detail::forward_to_storage_tag{}, std::move(that).rotation_q(), std::move(that).translation() } {} // Copy and move SE3_elmt(SE3_elmt const&) = default; SE3_elmt(SE3_elmt&&) = default; SE3_elmt& operator=(SE3_elmt const&) & = default; SE3_elmt& operator=(SE3_elmt&&) & = default; // Assignment from SE3_elmt of other component type template <class OtherComponentType, class OtherSU2Storage, class OtherSU2StorageTraits, class OtherR3Storage, class OtherR3StorageTraits, class = std::enable_if_t<!std::is_same<SE3_elmt, SE3_elmt<OtherComponentType, OtherSU2Storage, OtherSU2StorageTraits, OtherR3Storage, OtherR3StorageTraits>>::value && std::is_assignable<ComponentType&, OtherComponentType const&>::value>> JKL_GPU_EXECUTABLE GENERALIZED_CONSTEXPR SE3_elmt& operator=( SE3_elmt<OtherComponentType, OtherSU2Storage, OtherSU2StorageTraits, OtherR3Storage, OtherR3StorageTraits> const& that) & noexcept(noexcept(rotation_q() = that.rotation_q()) && noexcept(translation() = that.translation())) { rotation_q() = that.rotation_q(); translation() = that.translation(); return *this; } template <class OtherComponentType, class OtherSU2Storage, class OtherSU2StorageTraits, class OtherR3Storage, class OtherR3StorageTraits, class = std::enable_if_t<!std::is_same<SE3_elmt, SE3_elmt<OtherComponentType, OtherSU2Storage, OtherSU2StorageTraits, OtherR3Storage, OtherR3StorageTraits>>::value && std::is_assignable<ComponentType&, OtherComponentType>::value>> JKL_GPU_EXECUTABLE GENERALIZED_CONSTEXPR SE3_elmt& operator=( SE3_elmt<OtherComponentType, OtherSU2Storage, OtherSU2StorageTraits, OtherR3Storage, OtherR3StorageTraits>&& that) & noexcept(noexcept(rotation_q() = std::move(that).rotation_q()) && noexcept(translation() = std::move(that).translation())) { rotation_q() = std::move(that).rotation_q(); translation() = std::move(that).translation(); return *this; } // Exponential map template <class OtherComponentType, class Otherso3Storage, class Otherso3StorageTraits, class OtherR3Storage, class OtherR3StorageTraits> JKL_GPU_EXECUTABLE static SE3_elmt exp( se3_elmt<OtherComponentType, Otherso3Storage, Otherso3StorageTraits, OtherR3Storage, OtherR3StorageTraits> const& exponent) { using std::sin; using std::cos; auto rot = rotation_type::exp(exponent.rotation_part()); auto const angle = exponent.rotation_part().norm(); ComponentType alpha, beta; if( almost_smaller(angle, jkj::math::zero<ComponentType>()) ) { alpha = ComponentType(1) / 2 - angle*angle / 24; beta = ComponentType(1) / 6 - angle*angle / 120; } else { alpha = (ComponentType(1) - cos(angle)) / (angle * angle); beta = (angle - sin(angle)) / (angle * angle * angle); } auto cross_prod = cross(exponent.rotation_part(), exponent.translation_part()); auto trans = exponent.translation_part() + alpha * cross_prod + beta * cross(exponent.rotation_part(), cross_prod); return{ rot, trans }; } private: template <class ThisType> JKL_GPU_EXECUTABLE static GENERALIZED_CONSTEXPR SE3_elmt inv_impl(ThisType&& t) noexcept(noexcept(std::forward<ThisType>(t).rotation_q().inv()) && noexcept(SE3_elmt{ std::declval<rotation_type>(), -std::declval<rotation_type&>().rotate(std::forward<ThisType>(t).translation()) })) { auto r = std::forward<ThisType>(t).rotation_q().inv(); return{ std::move(r), -r.rotate(std::forward<ThisType>(t).translation()) }; } public: JKL_GPU_EXECUTABLE GENERALIZED_CONSTEXPR SE3_elmt inv() const& noexcept(noexcept(inv_impl(*this))) { return inv_impl(*this); } JKL_GPU_EXECUTABLE GENERALIZED_CONSTEXPR SE3_elmt inv() && noexcept(noexcept(inv_impl(std::move(*this)))) { return inv_impl(std::move(*this)); } private: template <class OtherSE3_elmt> JKL_GPU_EXECUTABLE GENERALIZED_CONSTEXPR SE3_elmt& inplace_mul_impl(OtherSE3_elmt&& that) noexcept( noexcept(translation() += rotation_q().rotate(std::forward<OtherSE3_elmt>(that).translation())) && noexcept(rotation_q() *= std::forward<OtherSE3_elmt>(that).rotation_q())) { translation() += rotation_q().rotate(std::forward<OtherSE3_elmt>(that).translation()); rotation_q() *= std::forward<OtherSE3_elmt>(that).rotation_q(); return *this; } public: template <class OtherComponentType, class OtherSU2Storage, class OtherSU2StorageTraits, class OtherR3Storage, class OtherR3StorageTraits> JKL_GPU_EXECUTABLE GENERALIZED_CONSTEXPR SE3_elmt& operator*=( SE3_elmt<OtherComponentType, OtherSU2Storage, OtherSU2StorageTraits, OtherR3Storage, OtherR3StorageTraits> const& that) noexcept(noexcept(inplace_mul_impl(that))) { return inplace_mul_impl(that); } template <class OtherComponentType, class OtherSU2Storage, class OtherSU2StorageTraits, class OtherR3Storage, class OtherR3StorageTraits> JKL_GPU_EXECUTABLE GENERALIZED_CONSTEXPR SE3_elmt& operator*=( SE3_elmt<OtherComponentType, OtherSU2Storage, OtherSU2StorageTraits, OtherR3Storage, OtherR3StorageTraits>&& that) noexcept(noexcept(inplace_mul_impl(std::move(that)))) { return inplace_mul_impl(std::move(that)); } template <class OtherComponentType, class OtherSU2Storage, class OtherSU2StorageTraits, class OtherR3Storage, class OtherR3StorageTraits> JKL_GPU_EXECUTABLE GENERALIZED_CONSTEXPR SE3_elmt& operator/=( SE3_elmt<OtherComponentType, OtherSU2Storage, OtherSU2StorageTraits, OtherR3Storage, OtherR3StorageTraits> const& that) noexcept(noexcept(*this *= that.inv())) { return *this *= that.inv(); } template <class OtherComponentType, class OtherSU2Storage, class OtherSU2StorageTraits, class OtherR3Storage, class OtherR3StorageTraits> JKL_GPU_EXECUTABLE GENERALIZED_CONSTEXPR SE3_elmt& operator/=( SE3_elmt<OtherComponentType, OtherSU2Storage, OtherSU2StorageTraits, OtherR3Storage, OtherR3StorageTraits>&& that) noexcept(noexcept(*this *= std::move(that).inv())) { return *this *= std::move(that).inv(); } private: template <class ReturnType, class ThisType> JKL_GPU_EXECUTABLE static ReturnType log_impl(ThisType&& q) { auto rotation_part = std::forward<ThisType>(q).rotation_q().log(); auto const angle = rotation_part.norm(); ComponentType beta; if( almost_smaller(angle, jkj::math::zero<ComponentType>()) ) beta = ComponentType(1) / 12 + angle / 360; else beta = (ComponentType(1) - (angle / 2) / tan(angle / 2)) / (angle * angle); auto cross_prod = cross(rotation_part, q.translation()); auto translation_part = std::forward<ThisType>(q).translation() - cross_prod/2 + beta * cross(rotation_part, cross_prod); return{ std::move(rotation_part), std::move(translation_part) }; } public: template <class OtherComponentType = ComponentType, class Otherso3Storage = OtherComponentType[3], class Otherso3StorageTraits = default_storage_traits, class OtherR3Storage = OtherComponentType[3], class OtherR3StorageTraits = default_storage_traits> JKL_GPU_EXECUTABLE se3_elmt<OtherComponentType, Otherso3Storage, Otherso3StorageTraits, OtherR3Storage, OtherR3StorageTraits> log() const& { return log_impl<se3_elmt<OtherComponentType, Otherso3Storage, Otherso3StorageTraits, OtherR3Storage, OtherR3StorageTraits>, SE3_elmt const&>(*this); } template <class OtherComponentType = ComponentType, class Otherso3Storage = OtherComponentType[3], class Otherso3StorageTraits = default_storage_traits, class OtherR3Storage = OtherComponentType[3], class OtherR3StorageTraits = default_storage_traits> JKL_GPU_EXECUTABLE se3_elmt<OtherComponentType, Otherso3Storage, Otherso3StorageTraits, OtherR3Storage, OtherR3StorageTraits> log() && { return log_impl<se3_elmt<OtherComponentType, Otherso3Storage, Otherso3StorageTraits, OtherR3Storage, OtherR3StorageTraits>, SE3_elmt>(std::move(*this)); } template <class OtherComponentType, class OtherSU2Storage, class OtherSU2StorageTraits, class OtherR3Storage, class OtherR3StorageTraits> JKL_GPU_EXECUTABLE constexpr bool operator==( SE3_elmt<OtherComponentType, OtherSU2Storage, OtherSU2StorageTraits, OtherR3Storage, OtherR3StorageTraits> const& that) const noexcept(noexcept(translation() == that.translation() && (rotation_q() == that.rotation_q() || rotation_q() == -that.rotation_q()))) { return translation() == that.translation() && (rotation_q() == that.rotation_q() || rotation_q() == -that.rotation_q()); } template <class OtherComponentType, class OtherSU2Storage, class OtherSU2StorageTraits, class OtherR3Storage, class OtherR3StorageTraits> JKL_GPU_EXECUTABLE constexpr bool operator!=( SE3_elmt<OtherComponentType, OtherSU2Storage, OtherSU2StorageTraits, OtherR3Storage, OtherR3StorageTraits> const& that) const noexcept(noexcept(!(*this == that))) { return !(*this == that); } JKL_GPU_EXECUTABLE static constexpr SE3_elmt unity() noexcept(noexcept(SE3_elmt{ rotation_type::unity(), translation_type::zero() })) { return{ rotation_type::unity(), translation_type::zero() }; } // Action on R3 template <class OtherComponentType, class OtherStorage, class OtherStorageTraits> JKL_GPU_EXECUTABLE constexpr decltype(auto) transform( R3_elmt<OtherComponentType, OtherStorage, OtherStorageTraits> const& p) const noexcept(noexcept(rotation_q().rotate(p) + translation())) { return rotation_q().rotate(p) + translation(); } }; namespace detail { template <class ComponentType, class so3Storage, class so3StorageTraits, class R3Storage, class R3StorageTraits> struct se3_elmt_base { using rotation_part_type = so3_elmt<ComponentType, so3Storage, so3StorageTraits>; using translation_part_type = R3_elmt<ComponentType, R3Storage, R3StorageTraits>; se3_elmt_base() = default; protected: rotation_part_type rot_; translation_part_type trans_; template <class RotArg, class TransArg> struct is_nothrow_constructible { static constexpr bool value = std::is_nothrow_constructible<rotation_part_type, RotArg>::value && std::is_nothrow_constructible<translation_part_type, TransArg>::value; }; template <class RotArg, class TransArg> JKL_GPU_EXECUTABLE constexpr se3_elmt_base(forward_to_storage_tag, RotArg&& r, TransArg&& t) noexcept(is_nothrow_constructible<RotArg, TransArg>::value) : rot_(std::forward<RotArg>(r)), trans_(std::forward<TransArg>(t)) {} }; } template <class ComponentType, class so3Storage, class so3StorageTraits, class R3Storage, class R3StorageTraits> class se3_elmt : public tmp::generate_constructors< detail::se3_elmt_base<ComponentType, so3Storage, so3StorageTraits, R3Storage, R3StorageTraits>, detail::forward_to_storage_tag, tmp::copy_or_move<so3_elmt<ComponentType, so3Storage, so3StorageTraits>, R3_elmt<ComponentType, R3Storage, R3StorageTraits>>> { using base_type = tmp::generate_constructors< detail::se3_elmt_base<ComponentType, so3Storage, so3StorageTraits, R3Storage, R3StorageTraits>, detail::forward_to_storage_tag, tmp::copy_or_move<so3_elmt<ComponentType, so3Storage, so3StorageTraits>, R3_elmt<ComponentType, R3Storage, R3StorageTraits>>>; public: using component_type = ComponentType; static constexpr std::size_t components = 6; using rotation_part_type = typename base_type::rotation_part_type; using translation_part_type = typename base_type::translation_part_type; JKL_GPU_EXECUTABLE NONCONST_CONSTEXPR rotation_part_type& rotation_part() & noexcept { return base_type::rot_; } JKL_GPU_EXECUTABLE constexpr rotation_part_type const& rotation_part() const& noexcept { return base_type::rot_; } JKL_GPU_EXECUTABLE NONCONST_CONSTEXPR rotation_part_type&& rotation_part() && noexcept { return std::move(base_type::rot_); } JKL_GPU_EXECUTABLE constexpr rotation_part_type const&& rotation_part() const&& noexcept { return std::move(base_type::rot_); } JKL_GPU_EXECUTABLE NONCONST_CONSTEXPR translation_part_type& translation_part() & noexcept { return base_type::trans_; } JKL_GPU_EXECUTABLE constexpr translation_part_type const& translation_part() const& noexcept { return base_type::trans_; } JKL_GPU_EXECUTABLE NONCONST_CONSTEXPR translation_part_type&& translation_part() && noexcept { return std::move(base_type::trans_); } JKL_GPU_EXECUTABLE constexpr translation_part_type const&& translation_part() const&& noexcept { return std::move(base_type::trans_); } using base_type::base_type; // Default constructor; components might be filled with garbages se3_elmt() = default; // Convert from se3_elmt of other component type template <class OtherComponentType, class Otherso3Storage, class Otherso3StorageTraits, class OtherR3Storage, class OtherR3StorageTraits, class = std::enable_if_t<!std::is_same<se3_elmt, se3_elmt<OtherComponentType, Otherso3Storage, Otherso3StorageTraits, OtherR3Storage, OtherR3StorageTraits>>::value && std::is_convertible<OtherComponentType, ComponentType>::value>> JKL_GPU_EXECUTABLE constexpr se3_elmt( se3_elmt<OtherComponentType, Otherso3Storage, Otherso3StorageTraits, OtherR3Storage, OtherR3StorageTraits> const& that) noexcept(noexcept(base_type{ detail::forward_to_storage_tag{}, that.rotation_part(), that.translation_part() })) : base_type{ detail::forward_to_storage_tag{}, that.rotation_part(), that.translation_part() } {} template <class OtherComponentType, class Otherso3Storage, class Otherso3StorageTraits, class OtherR3Storage, class OtherR3StorageTraits, class = std::enable_if_t<!std::is_same<se3_elmt, se3_elmt<OtherComponentType, Otherso3Storage, Otherso3StorageTraits, OtherR3Storage, OtherR3StorageTraits>>::value && std::is_convertible<OtherComponentType, ComponentType>::value>> JKL_GPU_EXECUTABLE constexpr se3_elmt( se3_elmt<OtherComponentType, Otherso3Storage, Otherso3StorageTraits, OtherR3Storage, OtherR3StorageTraits>&& that) noexcept(noexcept(base_type{ detail::forward_to_storage_tag{}, std::move(that).rotation_part(), std::move(that).translation_part() })) : base_type{ detail::forward_to_storage_tag{}, std::move(that).rotation_part(), std::move(that).translation_part() } {} // Copy and move se3_elmt(se3_elmt const&) = default; se3_elmt(se3_elmt&&) = default; se3_elmt& operator=(se3_elmt const&) & = default; se3_elmt& operator=(se3_elmt&&) & = default; // Assignment from se3_elmt of other component type template <class OtherComponentType, class Otherso3Storage, class Otherso3StorageTraits, class OtherR3Storage, class OtherR3StorageTraits, class = std::enable_if_t<!std::is_same<se3_elmt, se3_elmt<OtherComponentType, Otherso3Storage, Otherso3StorageTraits, OtherR3Storage, OtherR3StorageTraits>>::value && std::is_assignable<ComponentType&, OtherComponentType const&>::value>> JKL_GPU_EXECUTABLE GENERALIZED_CONSTEXPR se3_elmt& operator=( se3_elmt<OtherComponentType, Otherso3Storage, Otherso3StorageTraits, OtherR3Storage, OtherR3StorageTraits> const& that) & noexcept(noexcept(rotation_part() = that.rotation_part()) && noexcept(translation_part() = that.translation_part())) { rotation_part() = that.rotation_part(); translation_part() = that.translation_part(); return *this; } template <class OtherComponentType, class Otherso3Storage, class Otherso3StorageTraits, class OtherR3Storage, class OtherR3StorageTraits, class = std::enable_if_t<!std::is_same<se3_elmt, se3_elmt<OtherComponentType, Otherso3Storage, Otherso3StorageTraits, OtherR3Storage, OtherR3StorageTraits>>::value && std::is_assignable<ComponentType&, OtherComponentType const&>::value>> JKL_GPU_EXECUTABLE GENERALIZED_CONSTEXPR se3_elmt& operator=( se3_elmt<OtherComponentType, Otherso3Storage, Otherso3StorageTraits, OtherR3Storage, OtherR3StorageTraits>&& that) & noexcept(noexcept(rotation_part() = std::move(that).rotation_part()) && noexcept(translation_part() = std::move(that).translation_part())) { rotation_part() = std::move(that).rotation_part(); translation_part() = std::move(that).translation_part(); return *this; } JKL_GPU_EXECUTABLE constexpr se3_elmt operator+() const& noexcept(std::is_nothrow_copy_constructible<se3_elmt>::value) { return *this; } JKL_GPU_EXECUTABLE NONCONST_CONSTEXPR se3_elmt operator+() && noexcept(std::is_nothrow_move_constructible<se3_elmt>::value) { return *this; } JKL_GPU_EXECUTABLE constexpr se3_elmt operator-() const& noexcept(noexcept(se3_elmt{ -rotation_part(), -translation_part() })) { return{ -rotation_part(), -translation_part() }; } JKL_GPU_EXECUTABLE NONCONST_CONSTEXPR se3_elmt operator-() && noexcept(noexcept(se3_elmt{ -std::move(*this).rotation_part(), -std::move(*this).translation_part() })) { return{ -std::move(*this).rotation_part(), -std::move(*this).translation_part() }; } template <class OtherComponentType, class Otherso3Storage, class Otherso3StorageTraits, class OtherR3Storage, class OtherR3StorageTraits> JKL_GPU_EXECUTABLE GENERALIZED_CONSTEXPR se3_elmt& operator+=( se3_elmt<OtherComponentType, Otherso3Storage, Otherso3StorageTraits, OtherR3Storage, OtherR3StorageTraits> const& that) noexcept(noexcept(rotation_part() += that.rotation_part()) && noexcept(translation_part() += that.translation_part())) { rotation_part() += that.rotation_part(); translation_part() += that.translation_part(); return *this; } template <class OtherComponentType, class Otherso3Storage, class Otherso3StorageTraits, class OtherR3Storage, class OtherR3StorageTraits> JKL_GPU_EXECUTABLE GENERALIZED_CONSTEXPR se3_elmt& operator+=( se3_elmt<OtherComponentType, Otherso3Storage, Otherso3StorageTraits, OtherR3Storage, OtherR3StorageTraits>&& that) noexcept(noexcept(rotation_part() += std::move(that).rotation_part()) && noexcept(translation_part() += std::move(that).translation_part())) { rotation_part() += std::move(that).rotation_part(); translation_part() += std::move(that).translation_part(); return *this; } template <class OtherComponentType, class Otherso3Storage, class Otherso3StorageTraits, class OtherR3Storage, class OtherR3StorageTraits> JKL_GPU_EXECUTABLE GENERALIZED_CONSTEXPR se3_elmt& operator-=( se3_elmt<OtherComponentType, Otherso3Storage, Otherso3StorageTraits, OtherR3Storage, OtherR3StorageTraits> const& that) noexcept(noexcept(rotation_part() -= that.rotation_part()) && noexcept(translation_part() -= that.translation_part())) { rotation_part() -= that.rotation_part(); translation_part() -= that.translation_part(); return *this; } template <class OtherComponentType, class Otherso3Storage, class Otherso3StorageTraits, class OtherR3Storage, class OtherR3StorageTraits> JKL_GPU_EXECUTABLE GENERALIZED_CONSTEXPR se3_elmt& operator-=( se3_elmt<OtherComponentType, Otherso3Storage, Otherso3StorageTraits, OtherR3Storage, OtherR3StorageTraits>&& that) noexcept(noexcept(rotation_part() -= std::move(that).rotation_part()) && noexcept(translation_part() -= std::move(that).translation_part())) { rotation_part() -= std::move(that).rotation_part(); translation_part() -= std::move(that).translation_part(); return *this; } template <class OtherComponentType> JKL_GPU_EXECUTABLE GENERALIZED_CONSTEXPR se3_elmt& operator*=(OtherComponentType const& k) noexcept(noexcept(rotation_part() *= k) && noexcept(translation_part() *= k)) { rotation_part() *= k; translation_part() *= k; return *this; } template <class OtherComponentType> JKL_GPU_EXECUTABLE GENERALIZED_CONSTEXPR se3_elmt& operator/=(OtherComponentType const& k) noexcept(noexcept(rotation_part() /= k) && noexcept(translation_part() /= k)) { rotation_part() /= k; translation_part() /= k; return *this; } template <class OtherComponentType, class Otherso3Storage, class Otherso3StorageTraits, class OtherR3Storage, class OtherR3StorageTraits> JKL_GPU_EXECUTABLE constexpr bool operator==( se3_elmt<OtherComponentType, Otherso3Storage, Otherso3StorageTraits, OtherR3Storage, OtherR3StorageTraits> const& that) const noexcept(noexcept(rotation_part() == that.rotation_part() && translation_part() == that.translation_part())) { return rotation_part() == that.rotation_part() && translation_part() == that.translation_part(); } template <class OtherComponentType, class Otherso3Storage, class Otherso3StorageTraits, class OtherR3Storage, class OtherR3StorageTraits> JKL_GPU_EXECUTABLE constexpr bool operator!=( se3_elmt<OtherComponentType, Otherso3Storage, Otherso3StorageTraits, OtherR3Storage, OtherR3StorageTraits> const& that) const noexcept(noexcept(!(*this == that))) { return !(*this == that); } JKL_GPU_EXECUTABLE static constexpr se3_elmt zero() noexcept { return{ rotation_part_type::zero(), translation_part_type::zero() }; } }; //// Binary operations between SE3_elmt's & se3_elmt's namespace detail { template <class LeftOperand, class RightOperand> struct get_SE3_elmt_binary_result_impl {}; template <class LeftComponentType, class LeftSU2Storage, class LeftSU2StorageTraits, class LeftR3Storage, class LeftR3StorageTraits, class RightComponentType, class RightSU2Storage, class RightSU2StorageTraits, class RightR3Storage, class RightR3StorageTraits> struct get_SE3_elmt_binary_result_impl< SE3_elmt<LeftComponentType, LeftSU2Storage, LeftSU2StorageTraits, LeftR3Storage, LeftR3StorageTraits>, SE3_elmt<RightComponentType, RightSU2Storage, RightSU2StorageTraits, RightR3Storage, RightR3StorageTraits>> { using type = SE3_elmt_binary_result< LeftComponentType, LeftSU2Storage, LeftSU2StorageTraits, LeftR3Storage, LeftR3StorageTraits, RightComponentType, RightSU2Storage, RightSU2StorageTraits, RightR3Storage, RightR3StorageTraits>; }; template <class LeftOperand, class RightOperand> using get_SE3_elmt_binary_result = typename get_SE3_elmt_binary_result_impl< tmp::remove_cvref_t<LeftOperand>, tmp::remove_cvref_t<RightOperand>>::type; template <class LeftOperand, class RightOperand> struct get_se3_elmt_binary_result_impl {}; template <class LeftComponentType, class Leftso3Storage, class Leftso3StorageTraits, class LeftR3Storage, class LeftR3StorageTraits, class RightComponentType, class Rightso3Storage, class Rightso3StorageTraits, class RightR3Storage, class RightR3StorageTraits> struct get_se3_elmt_binary_result_impl< se3_elmt<LeftComponentType, Leftso3Storage, Leftso3StorageTraits, LeftR3Storage, LeftR3StorageTraits>, se3_elmt<RightComponentType, Rightso3Storage, Rightso3StorageTraits, RightR3Storage, RightR3StorageTraits>> { using type = se3_elmt_binary_result< LeftComponentType, Leftso3Storage, Leftso3StorageTraits, LeftR3Storage, LeftR3StorageTraits, RightComponentType, Rightso3Storage, Rightso3StorageTraits, RightR3Storage, RightR3StorageTraits>; }; template <class LeftOperand, class RightOperand> using get_se3_elmt_binary_result = typename get_se3_elmt_binary_result_impl< tmp::remove_cvref_t<LeftOperand>, tmp::remove_cvref_t<RightOperand>>::type; template <class Scalar, class Vector, bool from_left> struct get_se3_elmt_scalar_mult_result_impl_impl { static constexpr bool value = false; }; template <class Scalar, bool from_left, class ComponentType, class so3Storage, class so3StorageTraits, class R3Storage, class R3StorageTraits> struct get_se3_elmt_scalar_mult_result_impl_impl<Scalar, se3_elmt<ComponentType, so3Storage, so3StorageTraits, R3Storage, R3StorageTraits>, from_left> { using type = se3_elmt_scalar_mult_result<Scalar, from_left, ComponentType, so3Storage, so3StorageTraits, R3Storage, R3StorageTraits>; // Remove from the overload set if Scalar is not compatible with ComponentType static constexpr bool value = !std::is_same<type, no_operation_tag<no_operation_reason::component_type_not_compatible>>::value; }; template <class Scalar, class Vector, bool from_left> struct get_se3_elmt_scalar_mult_result_impl : std::conditional_t< get_se3_elmt_scalar_mult_result_impl_impl<Scalar, Vector, from_left>::value, get_se3_elmt_scalar_mult_result_impl_impl<Scalar, Vector, from_left>, get_se3_elmt_scalar_mult_result_impl_impl<void, void, false>> {}; template <class Scalar, class Vector, bool from_left> using get_se3_elmt_scalar_mult_result = typename get_se3_elmt_scalar_mult_result_impl< tmp::remove_cvref_t<Scalar>, tmp::remove_cvref_t<Vector>, from_left>::type; } // Binary multiplication of SE3_elmt's template <class LeftOperand, class RightOperand> JKL_GPU_EXECUTABLE constexpr auto operator*(LeftOperand&& s, RightOperand&& t) noexcept(noexcept(detail::get_SE3_elmt_binary_result<LeftOperand, RightOperand>{ s.rotation_q() * std::forward<RightOperand>(t).rotation_q(), s.rotation_q().rotate(std::forward<RightOperand>(t).translation()) + std::forward<LeftOperand>(s).translation() })) -> detail::get_SE3_elmt_binary_result<LeftOperand, RightOperand> { using result_type = detail::get_SE3_elmt_binary_result<LeftOperand, RightOperand>; static_assert(!std::is_same<result_type, no_operation_tag<no_operation_reason::component_type_not_compatible>>::value, "jkj::math: cannot multiply two SE3_elmt's; failed to deduce the resulting component type"); static_assert(!std::is_same<result_type, no_operation_tag<no_operation_reason::storage_not_compatible>>::value, "jkj::math: cannot multiply two SE3_elmt's; failed to deduce the resulting storage type"); return{ s.rotation_q() * std::forward<RightOperand>(t).rotation_q(), s.rotation_q().rotate(std::forward<RightOperand>(t).translation()) + std::forward<LeftOperand>(s).translation() }; } // Binary division of SE3_elmt's template <class LeftOperand, class RightOperand> JKL_GPU_EXECUTABLE constexpr auto operator/(LeftOperand&& p, RightOperand&& q) noexcept(noexcept(std::forward<LeftOperand>(p) * std::forward<RightOperand>(q).inv())) -> detail::get_SE3_elmt_binary_result<LeftOperand, RightOperand> { using result_type = detail::get_SE3_elmt_binary_result<LeftOperand, RightOperand>; static_assert(!std::is_same<result_type, no_operation_tag<no_operation_reason::component_type_not_compatible>>::value, "jkj::math: cannot divide two SE3_elmt's; failed to deduce the resulting component type"); static_assert(!std::is_same<result_type, no_operation_tag<no_operation_reason::storage_not_compatible>>::value, "jkj::math: cannot divide two SE3_elmt's; failed to deduce the resulting storage type"); return std::forward<LeftOperand>(p) * std::forward<RightOperand>(q).inv(); } // Interpolation template <class LeftOperand, class RightOperand, class Parameter> JKL_GPU_EXECUTABLE auto SU2_interpolation(LeftOperand&& p, RightOperand&& q, Parameter&& t) noexcept(noexcept(std::forward<LeftOperand>(p) * detail::get_SE3_elmt_binary_result<LeftOperand, RightOperand>::exp( (p.inv() * std::forward<RightOperand>(q)).log() * std::forward<Parameter>(t)))) -> detail::get_SE3_elmt_binary_result<LeftOperand, RightOperand> { using result_type = detail::get_SE3_elmt_binary_result<LeftOperand, RightOperand>; static_assert(!std::is_same<result_type, no_operation_tag<no_operation_reason::component_type_not_compatible>>::value, "jkj::math: cannot compute SE3 interpolation; failed to deduce the resulting component type"); static_assert(!std::is_same<result_type, no_operation_tag<no_operation_reason::storage_not_compatible>>::value, "jkj::math: cannot compute SE3 interpolation; failed to deduce the resulting storage type"); return std::forward<LeftOperand>(p) * result_type::exp( (p.inv() * std::forward<RightOperand>(q)).log() * std::forward<Parameter>(t)); } // Binary addition of se3_elmt's template <class LeftOperand, class RightOperand> JKL_GPU_EXECUTABLE constexpr auto operator+(LeftOperand&& s, RightOperand&& t) noexcept(noexcept(detail::get_se3_elmt_binary_result<LeftOperand, RightOperand>{ std::forward<LeftOperand>(s).rotation_part() + std::forward<RightOperand>(t).rotation_part(), std::forward<LeftOperand>(s).translation_part() + std::forward<RightOperand>(t).translation_part() })) -> detail::get_se3_elmt_binary_result<LeftOperand, RightOperand> { using result_type = detail::get_se3_elmt_binary_result<LeftOperand, RightOperand>; static_assert(!std::is_same<result_type, no_operation_tag<no_operation_reason::component_type_not_compatible>>::value, "jkj::math: cannot add two se3_elmt's; failed to deduce the resulting component type"); static_assert(!std::is_same<result_type, no_operation_tag<no_operation_reason::storage_not_compatible>>::value, "jkj::math: cannot add two se3_elmt's; failed to deduce the resulting storage type"); return{ std::forward<LeftOperand>(s).rotation_part() + std::forward<RightOperand>(t).rotation_part(), std::forward<LeftOperand>(s).translation_part() + std::forward<RightOperand>(t).translation_part() }; } // Binary subtraction of se3_elmt's template <class LeftOperand, class RightOperand> JKL_GPU_EXECUTABLE constexpr auto operator-(LeftOperand&& s, RightOperand&& t) noexcept(noexcept(detail::get_se3_elmt_binary_result<LeftOperand, RightOperand>{ std::forward<LeftOperand>(s).rotation_part() - std::forward<RightOperand>(t).rotation_part(), std::forward<LeftOperand>(s).translation_part() - std::forward<RightOperand>(t).translation_part() })) -> detail::get_se3_elmt_binary_result<LeftOperand, RightOperand> { using result_type = detail::get_se3_elmt_binary_result<LeftOperand, RightOperand>; static_assert(!std::is_same<result_type, no_operation_tag<no_operation_reason::component_type_not_compatible>>::value, "jkj::math: cannot subtract two se3_elmt's; failed to deduce the resulting component type"); static_assert(!std::is_same<result_type, no_operation_tag<no_operation_reason::storage_not_compatible>>::value, "jkj::math: cannot subtract two se3_elmt's; failed to deduce the resulting storage type"); return{ std::forward<LeftOperand>(s).rotation_part() - std::forward<RightOperand>(t).rotation_part(), std::forward<LeftOperand>(s).translation_part() - std::forward<RightOperand>(t).translation_part() }; } // Commutator of se3_elmt's template <class LeftOperand, class RightOperand> JKL_GPU_EXECUTABLE constexpr auto commutator(LeftOperand&& s, RightOperand&& t) noexcept(noexcept(detail::get_se3_elmt_binary_result<LeftOperand, RightOperand>{ cross(s.rotation_part(), t.rotation_part()), cross(s.rotation_part(), std::forward<RightOperand>(t).translation_part()) - cross(t.rotation_part(), std::forward<LeftOperand>(s).translation_part()) })) -> detail::get_se3_elmt_binary_result<LeftOperand, RightOperand> { using result_type = detail::get_se3_elmt_binary_result<LeftOperand, RightOperand>; static_assert(!std::is_same<result_type, no_operation_tag<no_operation_reason::component_type_not_compatible>>::value, "jkj::math: cannot compute commutator of se3_elmt's; failed to deduce the resulting component type"); static_assert(!std::is_same<result_type, no_operation_tag<no_operation_reason::storage_not_compatible>>::value, "jkj::math: cannot compute commutator of se3_elmt's; failed to deduce the resulting storage type"); return{ cross(s.rotation_part(), t.rotation_part()), cross(s.rotation_part(), std::forward<RightOperand>(t).translation_part()) - cross(t.rotation_part(), std::forward<LeftOperand>(s).translation_part()) }; } // Scalar multiplication of se3_elmt's from right template <class Vector, class Scalar> JKL_GPU_EXECUTABLE constexpr auto operator*(Vector&& v, Scalar const& k) noexcept(noexcept(detail::get_se3_elmt_scalar_mult_result<Scalar, Vector, false>{ std::forward<Vector>(v).rotation_part() * k, std::forward<Vector>(v).translation_part() * k })) -> detail::get_se3_elmt_scalar_mult_result<Scalar, Vector, false> { using result_type = detail::get_se3_elmt_scalar_mult_result<Scalar, Vector, false>; static_assert(!std::is_same<result_type, no_operation_tag<no_operation_reason::storage_not_compatible>>::value, "jkj::math: cannot multiply se3_elmt with a scalar; failed to deduce the resulting storage type"); return{ std::forward<Vector>(v).rotation_part() * k, std::forward<Vector>(v).translation_part() * k }; } // Scalar multiplication of se3_elmt's from left template <class Scalar, class Vector> JKL_GPU_EXECUTABLE constexpr auto operator*(Scalar const& k, Vector&& v) noexcept(noexcept(detail::get_se3_elmt_scalar_mult_result<Scalar, Vector, false>{ k * std::forward<Vector>(v).rotation_part(), k * std::forward<Vector>(v).translation_part()})) -> detail::get_se3_elmt_scalar_mult_result<Scalar, Vector, true> { using result_type = detail::get_se3_elmt_scalar_mult_result<Scalar, Vector, true>; static_assert(!std::is_same<result_type, no_operation_tag<no_operation_reason::storage_not_compatible>>::value, "jkj::math: cannot multiply se3_elmt with a scalar; failed to deduce the resulting storage type"); return{ k * std::forward<Vector>(v).rotation_part(), k * std::forward<Vector>(v).translation_part() }; } // Scalar division of se3_elmt's from right template <class Vector, class Scalar> JKL_GPU_EXECUTABLE constexpr auto operator/(Vector&& v, Scalar const& k) noexcept(noexcept(detail::get_se3_elmt_scalar_mult_result<Scalar, Vector, false>{ std::forward<Vector>(v).rotation_part() / k, std::forward<Vector>(v).translation_part() / k })) -> detail::get_se3_elmt_scalar_mult_result<Scalar, Vector, false> { using result_type = detail::get_se3_elmt_scalar_mult_result<Scalar, Vector, false>; static_assert(!std::is_same<result_type, no_operation_tag<no_operation_reason::storage_not_compatible>>::value, "jkj::math: cannot divide se3_elmt by a scalar; failed to deduce the resulting storage type"); return{ std::forward<Vector>(v).rotation_part() / k, std::forward<Vector>(v).translation_part() / k }; } } }
46.997207
109
0.745399
[ "vector", "transform" ]
11c2c76bd4f27079bd95498154f865119547213a
3,470
h
C
Mercury3/src/renderer/RenderBackend.h
axlecrusher/hgengine3
7eed878015e47a3275e2dae53cac00e93b74dc19
[ "MIT" ]
4
2018-05-27T18:56:59.000Z
2020-08-02T21:41:30.000Z
Mercury3/src/renderer/RenderBackend.h
axlecrusher/hgengine3
7eed878015e47a3275e2dae53cac00e93b74dc19
[ "MIT" ]
null
null
null
Mercury3/src/renderer/RenderBackend.h
axlecrusher/hgengine3
7eed878015e47a3275e2dae53cac00e93b74dc19
[ "MIT" ]
2
2019-05-16T05:23:12.000Z
2020-04-17T10:16:04.000Z
#pragma once #include <stdint.h> #include <vector> #include <HgEntity.h> #include <IFramebuffer.h> #include <IRenderTarget.h> #include <core/Instancing.h> enum RendererType { OPENGL = 0, VULKAN, DIRECTX }; struct Viewport { Viewport() :x(0), y(0), width(0), height(0) {} bool operator==(const Viewport& rhs) const { return (x == rhs.x) && (y == rhs.y) && (width == rhs.width) && (height == rhs.height); } uint16_t x, y; uint16_t width, height; }; //make a viewport look like a render target. For use with getting projection matrices class ViewportRenderTarget : public IRenderTarget { public: ViewportRenderTarget(const Viewport* vp) :m_vp(vp) {} virtual bool Init() { return true; }; virtual void Render(const RenderParamsList& l) {}; virtual HgMath::mat4f getPerspectiveMatrix() const; virtual HgMath::mat4f getOrthoMatrix() const; virtual uint32_t getWidth() const { return m_vp->width; } virtual uint32_t getHeight() const { return m_vp->height; } private: const Viewport* m_vp; }; class RenderBackend { public: virtual void Init() = 0; virtual void Clear() = 0; virtual void BeginFrame() = 0; virtual void EndFrame() = 0; virtual void setRenderAttributes(BlendMode blendMode, RenderData::Flags flags) = 0; virtual void setViewport(const Viewport& vp) = 0; virtual std::unique_ptr<IFramebuffer> CreateFrameBuffer() = 0; RendererType Type() const { return m_type; } //void setup_viewports(uint16_t width, uint16_t height); protected: RendererType m_type; Viewport m_currentViewport; //struct viewport view_port[3]; //uint8_t _currenViewPort_idx = 0xFF; }; struct RenderInstance { RenderInstance(const HgMath::mat4f& _worldSpaceMatrix, RenderData* rd, const vector3f& _velocityVector, int8_t order = 0, const Instancing::InstancingMetaData* imdPtr = nullptr) :renderData(rd), drawOrder(order), velocityVector(_velocityVector) { _worldSpaceMatrix.store(worldSpaceMatrix); _worldSpaceMatrix.store(interpolatedWorldSpaceMatrix); if (imdPtr) { imd = *imdPtr; } } Instancing::InstancingMetaData imd; float worldSpaceMatrix[16]; float interpolatedWorldSpaceMatrix[16]; //RenderDataPtr renderData; RenderData* renderData; int8_t drawOrder; HgTime remainingTime; vector3f velocityVector; }; class RenderQueue { public: void Enqueue(HgEntity* entity, HgTime t); void Enqueue(RenderData* rd); void Enqueue(const Instancing::InstancingMetaData& imd); //sorts queue on draw order for proper rendering void Finalize(const HgTime& remain); //Clears existing queue void Clear() { m_opaqueEntities.clear(); m_transparentEntities.clear(); } const std::vector<RenderInstance>& getOpaqueQueue() const { return m_opaqueEntities; } const std::vector<RenderInstance>& getTransparentQueue() const { return m_transparentEntities; } private: void Enqueue(RenderData* rd, const HgMath::mat4f& wsm, int8_t drawOrder, const vector3f& velocity, const Instancing::InstancingMetaData* imd = nullptr); //Lower draw order is first void sort(std::vector<RenderInstance>& v); std::vector<RenderInstance> m_opaqueEntities; std::vector<RenderInstance> m_transparentEntities; }; class HgCamera; namespace Renderer { //Must happen after window is created; void Init(); void prepare(const Instancing::InstancingMetaData* imd); void Render(const Viewport& vp, const HgMath::mat4f& viewMatrix, const HgMath::mat4f& projection, RenderQueue* queue); } RenderBackend* RENDERER();
23.133333
178
0.742075
[ "render", "vector" ]
11c63987178cdda15a75117ebebafaa4e929f3d7
77,054
h
C
media_driver/agnostic/gen9/hw/vdbox/mhw_vdbox_hcp_g9_X.h
Hongbo913/media-driver
83cbea500ca3852ffffe32ef7c33c7cb8e05c967
[ "Intel", "BSD-3-Clause", "MIT" ]
1
2021-04-08T08:40:21.000Z
2021-04-08T08:40:21.000Z
media_driver/agnostic/gen9/hw/vdbox/mhw_vdbox_hcp_g9_X.h
shawnli2/media-driver
ad8aa5a5a092a1f99d97aaecd04b71e9d770c8a3
[ "Intel", "BSD-3-Clause", "MIT" ]
1
2019-01-05T02:54:19.000Z
2019-01-05T02:54:19.000Z
media_driver/agnostic/gen9/hw/vdbox/mhw_vdbox_hcp_g9_X.h
shawnli2/media-driver
ad8aa5a5a092a1f99d97aaecd04b71e9d770c8a3
[ "Intel", "BSD-3-Clause", "MIT" ]
1
2018-01-12T06:07:55.000Z
2018-01-12T06:07:55.000Z
/* * Copyright (c) 2017-2018, Intel Corporation * * 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. */ //! //! \file mhw_vdbox_hcp_g9_X.h //! \brief Defines functions for constructing Vdbox HCP commands on Gen9-based platforms //! #ifndef __MHW_VDBOX_HCP_G9_X_H__ #define __MHW_VDBOX_HCP_G9_X_H__ #include "mhw_vdbox_hcp_generic.h" #include "mhw_mmio_g9.h" // CU Record structure struct EncodeHevcCuDataG9 { //DW0 uint32_t cu_size : 2; uint32_t cu_pred_mode : 1; uint32_t cu_transquant_bypass_flag : 1; uint32_t cu_part_mode : 3; uint32_t Res_DW0_7 : 1; uint32_t intra_chroma_mode : 3; uint32_t Res_DW0_11_15 : 5; uint32_t CU_QP : 6; uint32_t Res_DW0_22_23 : 2; uint32_t interpred_idc : 8; //DW1 uint8_t intra_mode[4]; //DW2 and DW3 int16_t mvx_l0[4]; //DW4 and DW5 int16_t mvy_l0[4]; //DW6 and DW7 int16_t mvx_l1[4]; //DW8 and DW9 int16_t mvy_l1[4]; //DW10 uint32_t ref_idx_l0_PU1 : 4; uint32_t ref_idx_l0_PU2 : 4; uint32_t ref_idx_l0_PU3 : 4; uint32_t ref_idx_l0_PU4 : 4; uint32_t ref_idx_l1_PU1 : 4; uint32_t ref_idx_l1_PU2 : 4; uint32_t ref_idx_l1_PU3 : 4; uint32_t ref_idx_l1_PU4 : 4; //DW11 uint32_t tu_size : 32; //DW12 uint32_t tu_xform_Yskip : 16; uint32_t Res_DW12_16_27 : 12; uint32_t tu_countm1 : 4; //DW13 uint32_t tu_xform_Uskip : 16; uint32_t tu_xform_Vskip : 16; //DW14 uint32_t Res_DW14 : 32; //DW15 uint32_t Res_DW15 : 32; }; //! MHW Vdbox Hcp interface for Gen9 /*! This class defines the Hcp command construction functions for Gen9 platforms as template */ template <class THcpCmds> class MhwVdboxHcpInterfaceG9 : public MhwVdboxHcpInterfaceGeneric<THcpCmds> { protected: enum HEVC_QM_TYPES { HEVC_QM_4x4 = 0, HEVC_QM_8x8 = 1, HEVC_QM_16x16 = 2, HEVC_QM_32x32 = 3 }; static const uint32_t m_veboxRgbHistogramSizePerSlice = 256 * 4; static const uint32_t m_veboxNumRgbChannel = 3; static const uint32_t m_veboxAceHistogramSizePerFramePerSlice = 256 * 4; static const uint32_t m_veboxNumFramePreviousCurrent = 2; static const uint32_t m_veboxMaxSlices = 2; static const uint32_t m_veboxRgbHistogramSize = m_veboxRgbHistogramSizePerSlice * m_veboxNumRgbChannel * m_veboxMaxSlices; static const uint32_t m_veboxLaceHistogram256BinPerBlock = 256 * 2; static const uint32_t m_veboxStatisticsSize = 32 * 4; //! //! \brief Constructor //! MhwVdboxHcpInterfaceG9<THcpCmds>( PMOS_INTERFACE osInterface, MhwMiInterface *miInterface, MhwCpInterface *cpInterface, bool decodeInUse) : MhwVdboxHcpInterfaceGeneric<THcpCmds>(osInterface, miInterface, cpInterface, decodeInUse) { MHW_FUNCTION_ENTER; this->m_hevcEncCuRecordSize = sizeof(EncodeHevcCuDataG9); InitMmioRegisters(); } //! //! \brief Destructor //! virtual ~MhwVdboxHcpInterfaceG9() { MHW_FUNCTION_ENTER; } void InitMmioRegisters() { MmioRegistersHcp *mmioRegisters = &this->m_mmioRegisters[MHW_VDBOX_NODE_1]; mmioRegisters->hcpEncImageStatusMaskRegOffset = HCP_ENC_IMAGE_STATUS_MASK_REG_OFFSET_INIT_G9; mmioRegisters->hcpEncImageStatusCtrlRegOffset = HCP_ENC_IMAGE_STATUS_CTRL_REG_OFFSET_INIT_G9; mmioRegisters->hcpEncBitstreamBytecountFrameRegOffset = HCP_ENC_BIT_STREAM_BYTE_COUNT_FRAME_REG_OFFSET_INIT_G9; mmioRegisters->hcpEncBitstreamSeBitcountFrameRegOffset = HCP_ENC_BIT_STREAM_SE_BIT_COUNT_FRAME_REG_OFFSET_INIT_G9; mmioRegisters->hcpEncBitstreamBytecountFrameNoHeaderRegOffset = HCP_ENC_BIT_STREAM_BYTE_COUNT_FRAME_NO_HEADER_REG_OFFSET_INIT_G9; mmioRegisters->hcpEncQpStatusCountRegOffset = HCP_ENC_QP_STATUS_COUNT_REG_OFFSET_INIT_G9; mmioRegisters->hcpEncSliceCountRegOffset = HCP_ENC_SLICE_COUNT_REG_OFFSET_INIT_G9; mmioRegisters->hcpEncVdencModeTimerRegOffset = HCP_ENC_VDENC_MODE_TIMER_REG_OFFSET_INIT_G9; mmioRegisters->hcpVp9EncBitstreamBytecountFrameRegOffset = HCP_VP9_ENC_BITSTREAM_BYTE_COUNT_FRAME_REG_OFFSET_INIT_G9; mmioRegisters->hcpVp9EncBitstreamBytecountFrameNoHeaderRegOffset = HCP_VP9_ENC_BITSTREAM_BYTE_COUNT_FRAME_NO_HEADER_REG_OFFSET_INIT_G9; mmioRegisters->hcpVp9EncImageStatusMaskRegOffset = HCP_VP9_ENC_IMAGE_STATUS_MASK_REG_OFFSET_INIT_G9; mmioRegisters->hcpVp9EncImageStatusCtrlRegOffset = HCP_VP9_ENC_IMAGE_STATUS_CTRL_REG_OFFSET_INIT_G9; mmioRegisters->csEngineIdOffset = CS_ENGINE_ID_OFFSET_INIT_G9; mmioRegisters->hcpDecStatusRegOffset = HCP_DEC_STATUS_REG_OFFSET_INIT_G9; mmioRegisters->hcpCabacStatusRegOffset = HCP_CABAC_STATUS_REG_OFFSET_INIT_G9; } void InitRowstoreUserFeatureSettings() { MOS_USER_FEATURE_VALUE_DATA userFeatureData; MOS_ZeroMemory(&userFeatureData, sizeof(userFeatureData)); userFeatureData.u32Data = 0; userFeatureData.i32DataFlag = MOS_USER_FEATURE_VALUE_DATA_FLAG_CUSTOM_DEFAULT_VALUE_TYPE; #if (_DEBUG || _RELEASE_INTERNAL) MOS_UserFeature_ReadValue_ID( nullptr, __MEDIA_USER_FEATURE_VALUE_ROWSTORE_CACHE_DISABLE_ID, &userFeatureData); #endif // _DEBUG || _RELEASE_INTERNAL this->m_rowstoreCachingSupported = userFeatureData.i32Data ? false : true; if (this->m_rowstoreCachingSupported) { MOS_ZeroMemory(&userFeatureData, sizeof(userFeatureData)); #if (_DEBUG || _RELEASE_INTERNAL) MOS_UserFeature_ReadValue_ID( nullptr, __MEDIA_USER_FEATURE_VALUE_HEVCDATROWSTORECACHE_DISABLE_ID, &userFeatureData); #endif // _DEBUG || _RELEASE_INTERNAL this->m_hevcDatRowStoreCache.bSupported = userFeatureData.i32Data ? false : true; MOS_ZeroMemory(&userFeatureData, sizeof(userFeatureData)); #if (_DEBUG || _RELEASE_INTERNAL) MOS_UserFeature_ReadValue_ID( nullptr, __MEDIA_USER_FEATURE_VALUE_HEVCDFROWSTORECACHE_DISABLE_ID, &userFeatureData); #endif // _DEBUG || _RELEASE_INTERNAL this->m_hevcDfRowStoreCache.bSupported = userFeatureData.i32Data ? false : true; MOS_ZeroMemory(&userFeatureData, sizeof(userFeatureData)); #if (_DEBUG || _RELEASE_INTERNAL) MOS_UserFeature_ReadValue_ID( nullptr, __MEDIA_USER_FEATURE_VALUE_HEVCSAOROWSTORECACHE_DISABLE_ID, &userFeatureData); #endif // _DEBUG || _RELEASE_INTERNAL this->m_hevcSaoRowStoreCache.bSupported = userFeatureData.i32Data ? false : true; } } MOS_STATUS GetRowstoreCachingAddrs( PMHW_VDBOX_ROWSTORE_PARAMS rowstoreParams) { MOS_STATUS eStatus = MOS_STATUS_SUCCESS; MHW_FUNCTION_ENTER; MHW_MI_CHK_NULL(rowstoreParams); if (this->m_hevcDatRowStoreCache.bSupported && (rowstoreParams->Mode == CODECHAL_DECODE_MODE_HEVCVLD)) { this->m_hevcDatRowStoreCache.bEnabled = true; if (rowstoreParams->dwPicWidth <= MHW_VDBOX_PICWIDTH_8K) { this->m_hevcDatRowStoreCache.dwAddress = HEVCDATROWSTORE_BASEADDRESS; } else { this->m_hevcDatRowStoreCache.dwAddress = 0; this->m_hevcDatRowStoreCache.bEnabled = false; } } if (this->m_hevcDfRowStoreCache.bSupported && (rowstoreParams->Mode == CODECHAL_DECODE_MODE_HEVCVLD)) { this->m_hevcDfRowStoreCache.bEnabled = true; if (rowstoreParams->dwPicWidth <= MHW_VDBOX_PICWIDTH_2K) { this->m_hevcDfRowStoreCache.dwAddress = HEVCDFROWSTORE_BASEADDRESS_PICWIDTH_LESS_THAN_OR_EQU_TO_2K; } else if ((rowstoreParams->dwPicWidth > MHW_VDBOX_PICWIDTH_2K) && (rowstoreParams->dwPicWidth <= MHW_VDBOX_PICWIDTH_4K)) { if (rowstoreParams->ucBitDepthMinus8 == 0) { this->m_hevcDfRowStoreCache.dwAddress = HEVCDFROWSTORE_BASEADDRESS_PICWIDTH_BETWEEN_2K_AND_4K; } else { this->m_hevcDfRowStoreCache.dwAddress = 0; this->m_hevcDfRowStoreCache.bEnabled = false; } } else { this->m_hevcDfRowStoreCache.dwAddress = 0; this->m_hevcDfRowStoreCache.bEnabled = false; } } if (this->m_hevcSaoRowStoreCache.bSupported && (rowstoreParams->Mode == CODECHAL_DECODE_MODE_HEVCVLD)) { this->m_hevcSaoRowStoreCache.bEnabled = true; if (rowstoreParams->dwPicWidth <= MHW_VDBOX_PICWIDTH_2K) { if (rowstoreParams->ucBitDepthMinus8 == 0) { this->m_hevcSaoRowStoreCache.dwAddress = HEVCSAOROWSTORE_BASEADDRESS_PICWIDTH_LESS_THAN_OR_EQU_TO_2K; } else { this->m_hevcSaoRowStoreCache.dwAddress = 0; this->m_hevcSaoRowStoreCache.bEnabled = false; } } else { this->m_hevcSaoRowStoreCache.dwAddress = 0; this->m_hevcSaoRowStoreCache.bEnabled = false; } } if (this->m_vp9HvdRowStoreCache.bSupported && rowstoreParams->Mode == CODECHAL_DECODE_MODE_VP9VLD) { this->m_vp9HvdRowStoreCache.bEnabled = true; if ((rowstoreParams->dwPicWidth <= MHW_VDBOX_PICWIDTH_8K && rowstoreParams->ucBitDepthMinus8 == 0) || (rowstoreParams->dwPicWidth <= MHW_VDBOX_PICWIDTH_2K && rowstoreParams->ucBitDepthMinus8 == 2)) { this->m_vp9HvdRowStoreCache.dwAddress = VP9HVDROWSTORE_BASEADDRESS; } else { this->m_vp9HvdRowStoreCache.dwAddress = 0; this->m_vp9HvdRowStoreCache.bEnabled = false; } } if (this->m_vp9DfRowStoreCache.bSupported && rowstoreParams->Mode == CODECHAL_DECODE_MODE_VP9VLD) { this->m_vp9DfRowStoreCache.bEnabled = true; if ((rowstoreParams->dwPicWidth <= MHW_VDBOX_PICWIDTH_2K && rowstoreParams->ucBitDepthMinus8 == 0) || (rowstoreParams->dwPicWidth <= MHW_VDBOX_PICWIDTH_1K && rowstoreParams->ucBitDepthMinus8 == 2)) { this->m_vp9DfRowStoreCache.dwAddress = VP9DFROWSTORE_BASEADDRESS_PICWIDTH_LESS_THAN_OR_EQU_TO_2K; } else { this->m_vp9DfRowStoreCache.dwAddress = 0; this->m_vp9DfRowStoreCache.bEnabled = false; } } return eStatus; } MOS_STATUS GetHevcBufferSize( MHW_VDBOX_HCP_INTERNAL_BUFFER_TYPE bufferType, PMHW_VDBOX_HCP_BUFFER_SIZE_PARAMS hcpBufSizeParam) { MOS_STATUS eStatus = MOS_STATUS_SUCCESS; MHW_FUNCTION_ENTER; MHW_MI_CHK_NULL(hcpBufSizeParam); uint32_t mvtSize = 0; uint32_t mvtbSize = 0; uint32_t bufferSize = 0; uint8_t maxBitDepth = hcpBufSizeParam->ucMaxBitDepth; uint32_t picWidth = hcpBufSizeParam->dwPicWidth; uint32_t picHeight = hcpBufSizeParam->dwPicHeight; uint32_t picHeightLCU = picHeight >> 4;//assume smallest LCU to get max height uint32_t picWidthLCU = picWidth >> 4; uint8_t shiftParam = (maxBitDepth == 10) ? 2 : 3; switch (bufferType) { case MHW_VDBOX_HCP_INTERNAL_BUFFER_DBLK_LINE: case MHW_VDBOX_HCP_INTERNAL_BUFFER_DBLK_TILE_LINE: bufferSize = ((picWidth + 31) & 0xFFFFFFE0) >> shiftParam; break; case MHW_VDBOX_HCP_INTERNAL_BUFFER_DBLK_TILE_COL: bufferSize = ((picHeight + picHeightLCU * 6 + 31) & 0xFFFFFFE0) >> shiftParam; break; case MHW_VDBOX_HCP_INTERNAL_BUFFER_META_LINE: bufferSize = (((((picWidth + 15) >> 4) * 188 + picWidthLCU * 9 + 1023) >> 9) + 1) & (-2); break; case MHW_VDBOX_HCP_INTERNAL_BUFFER_META_TILE_LINE: bufferSize = (((((picWidth + 15) >> 4) * 172 + picWidthLCU * 9 + 1023) >> 9) + 1) & (-2); break; case MHW_VDBOX_HCP_INTERNAL_BUFFER_META_TILE_COL: bufferSize = (((((picHeight + 15) >> 4) * 176 + picHeightLCU * 89 + 1023) >> 9) + 1) & (-2); break; case MHW_VDBOX_HCP_INTERNAL_BUFFER_SAO_LINE: bufferSize = (((((picWidth >> 1) + picWidthLCU * 3) + 15) & 0xFFFFFFF0) >> shiftParam); break; case MHW_VDBOX_HCP_INTERNAL_BUFFER_SAO_TILE_LINE: bufferSize = (((((picWidth >> 1) + picWidthLCU * 6) + 15) & 0xFFFFFFF0) >> shiftParam); break; case MHW_VDBOX_HCP_INTERNAL_BUFFER_SAO_TILE_COL: bufferSize = (((((picHeight >> 1) + picHeightLCU * 6) + 15) & 0xFFFFFFF0) >> shiftParam); break; case MHW_VDBOX_HCP_INTERNAL_BUFFER_CURR_MV_TEMPORAL: mvtSize = ((((picWidth + 63) >> 6)*(((picHeight + 15) >> 4)) + 1)&(-2)); mvtbSize = ((((picWidth + 31) >> 5)*(((picHeight + 31) >> 5)) + 1)&(-2)); bufferSize = MOS_MAX(mvtSize, mvtbSize); break; default: eStatus = MOS_STATUS_INVALID_PARAMETER; break; } hcpBufSizeParam->dwBufferSize = bufferSize * MHW_CACHELINE_SIZE; return eStatus; } MOS_STATUS GetVp9BufferSize( MHW_VDBOX_HCP_INTERNAL_BUFFER_TYPE bufferType, PMHW_VDBOX_HCP_BUFFER_SIZE_PARAMS hcpBufSizeParam) { MOS_STATUS eStatus = MOS_STATUS_SUCCESS; MHW_FUNCTION_ENTER; MHW_MI_CHK_NULL(hcpBufSizeParam); uint32_t bufferSize = 0; uint32_t dblkRsbSizeMultiplier = 0; uint32_t dblkCsbSizeMultiplier = 0; uint8_t maxBitDepth = hcpBufSizeParam->ucMaxBitDepth; uint32_t widthInSb = hcpBufSizeParam->dwPicWidth; uint32_t heightInSb = hcpBufSizeParam->dwPicHeight; HCP_CHROMA_FORMAT_IDC chromaFormat = (HCP_CHROMA_FORMAT_IDC)hcpBufSizeParam->ucChromaFormat; uint32_t sizeScale = (maxBitDepth > 8) ? 2 : 1; if (chromaFormat == HCP_CHROMA_FORMAT_YUV420) { dblkRsbSizeMultiplier = sizeScale * 18; dblkCsbSizeMultiplier = sizeScale * 17; } else { eStatus = MOS_STATUS_INVALID_PARAMETER; MHW_ASSERTMESSAGE("Format not supported."); return eStatus; } switch (bufferType) { case MHW_VDBOX_HCP_INTERNAL_BUFFER_DBLK_LINE: case MHW_VDBOX_HCP_INTERNAL_BUFFER_DBLK_TILE_LINE: bufferSize = widthInSb * dblkRsbSizeMultiplier; break; case MHW_VDBOX_HCP_INTERNAL_BUFFER_DBLK_TILE_COL: bufferSize = heightInSb * dblkCsbSizeMultiplier; break; case MHW_VDBOX_HCP_INTERNAL_BUFFER_META_LINE: case MHW_VDBOX_HCP_INTERNAL_BUFFER_META_TILE_LINE: bufferSize = widthInSb * 5; break; case MHW_VDBOX_HCP_INTERNAL_BUFFER_META_TILE_COL: bufferSize = heightInSb * 5; break; case MHW_VDBOX_HCP_INTERNAL_BUFFER_CURR_MV_TEMPORAL: case MHW_VDBOX_HCP_INTERNAL_BUFFER_COLL_MV_TEMPORAL: bufferSize = widthInSb * heightInSb * 9; break; case MHW_VDBOX_VP9_INTERNAL_BUFFER_SEGMENT_ID: bufferSize = widthInSb * heightInSb; break; case MHW_VDBOX_VP9_INTERNAL_BUFFER_HVD_LINE: case MHW_VDBOX_VP9_INTERNAL_BUFFER_HVD_TILE: bufferSize = widthInSb; break; default: eStatus = MOS_STATUS_INVALID_PARAMETER; break; } hcpBufSizeParam->dwBufferSize = bufferSize * MHW_CACHELINE_SIZE; return eStatus; } MOS_STATUS IsHevcBufferReallocNeeded( MHW_VDBOX_HCP_INTERNAL_BUFFER_TYPE bufferType, PMHW_VDBOX_HCP_BUFFER_REALLOC_PARAMS reallocParam) { MOS_STATUS eStatus = MOS_STATUS_SUCCESS; MHW_FUNCTION_ENTER; MHW_MI_CHK_NULL(reallocParam); bool realloc = false; uint32_t picWidth = reallocParam->dwPicWidth; uint32_t picHeight = reallocParam->dwPicHeight; uint32_t picWidthAlloced = reallocParam->dwPicWidthAlloced; uint32_t picHeightAlloced = reallocParam->dwPicHeightAlloced; switch (bufferType) { case MHW_VDBOX_HCP_INTERNAL_BUFFER_DBLK_LINE: case MHW_VDBOX_HCP_INTERNAL_BUFFER_DBLK_TILE_LINE: case MHW_VDBOX_HCP_INTERNAL_BUFFER_META_LINE: case MHW_VDBOX_HCP_INTERNAL_BUFFER_META_TILE_LINE: case MHW_VDBOX_HCP_INTERNAL_BUFFER_SAO_LINE: case MHW_VDBOX_HCP_INTERNAL_BUFFER_SAO_TILE_LINE: realloc = (picWidth > picWidthAlloced) ? true : false; break; case MHW_VDBOX_HCP_INTERNAL_BUFFER_DBLK_TILE_COL: case MHW_VDBOX_HCP_INTERNAL_BUFFER_META_TILE_COL: case MHW_VDBOX_HCP_INTERNAL_BUFFER_SAO_TILE_COL: realloc = (picHeight > picHeightAlloced) ? true : false; break; case MHW_VDBOX_HCP_INTERNAL_BUFFER_CURR_MV_TEMPORAL: realloc = (picWidth > picWidthAlloced || picHeight > picHeightAlloced) ? true : false; break; default: eStatus = MOS_STATUS_INVALID_PARAMETER; break; } reallocParam->bNeedBiggerSize = realloc; return eStatus; } MOS_STATUS IsVp9BufferReallocNeeded( MHW_VDBOX_HCP_INTERNAL_BUFFER_TYPE bufferType, PMHW_VDBOX_HCP_BUFFER_REALLOC_PARAMS reallocParam) { MOS_STATUS eStatus = MOS_STATUS_SUCCESS; MHW_FUNCTION_ENTER; MHW_MI_CHK_NULL(reallocParam); bool realloc = false; uint32_t widthInSb = reallocParam->dwPicWidth; uint32_t heightInSb = reallocParam->dwPicHeight; uint32_t picWidthInSbAlloced = reallocParam->dwPicWidthAlloced; uint32_t picHeightInSbAlloced = reallocParam->dwPicHeightAlloced; switch (bufferType) { case MHW_VDBOX_HCP_INTERNAL_BUFFER_META_LINE: case MHW_VDBOX_HCP_INTERNAL_BUFFER_META_TILE_LINE: case MHW_VDBOX_HCP_INTERNAL_BUFFER_DBLK_LINE: case MHW_VDBOX_HCP_INTERNAL_BUFFER_DBLK_TILE_LINE: case MHW_VDBOX_VP9_INTERNAL_BUFFER_HVD_LINE: case MHW_VDBOX_VP9_INTERNAL_BUFFER_HVD_TILE: realloc = (widthInSb > picWidthInSbAlloced) ? true : false; break; case MHW_VDBOX_HCP_INTERNAL_BUFFER_DBLK_TILE_COL: case MHW_VDBOX_HCP_INTERNAL_BUFFER_META_TILE_COL: realloc = (heightInSb > picHeightInSbAlloced) ? true : false; break; case MHW_VDBOX_HCP_INTERNAL_BUFFER_CURR_MV_TEMPORAL: case MHW_VDBOX_HCP_INTERNAL_BUFFER_COLL_MV_TEMPORAL: case MHW_VDBOX_VP9_INTERNAL_BUFFER_SEGMENT_ID: realloc = (heightInSb > picHeightInSbAlloced || widthInSb > picWidthInSbAlloced) ? true : false; break; default: eStatus = MOS_STATUS_INVALID_PARAMETER; break; } reallocParam->bNeedBiggerSize = realloc; return eStatus; } MOS_STATUS AddHcpVp9PicStateCmd( PMOS_COMMAND_BUFFER cmdBuffer, PMHW_BATCH_BUFFER batchBuffer, PMHW_VDBOX_VP9_PIC_STATE params) { return MOS_STATUS_PLATFORM_NOT_SUPPORTED; } MOS_STATUS AddHcpVp9PicStateEncCmd( PMOS_COMMAND_BUFFER cmdBuffer, PMHW_BATCH_BUFFER batchBuffer, PMHW_VDBOX_VP9_ENCODE_PIC_STATE params) { return MOS_STATUS_PLATFORM_NOT_SUPPORTED; } MOS_STATUS AddHcpHevcVp9RdoqStateCmd( PMOS_COMMAND_BUFFER cmdBuffer, PMHW_VDBOX_HEVC_PIC_STATE params) { return MOS_STATUS_PLATFORM_NOT_SUPPORTED; } MOS_STATUS AddHcpPipeModeSelectCmd( PMOS_COMMAND_BUFFER cmdBuffer, PMHW_VDBOX_PIPE_MODE_SELECT_PARAMS params) { MOS_STATUS eStatus = MOS_STATUS_SUCCESS; MHW_FUNCTION_ENTER; MHW_MI_CHK_NULL(params); typename THcpCmds::HCP_PIPE_MODE_SELECT_CMD cmd; cmd.DW1.CodecStandardSelect = CodecHal_GetStandardFromMode(params->Mode) - CODECHAL_HCP_BASE; cmd.DW1.DeblockerStreamoutEnable = params->bDeblockerStreamOutEnable; if (this->m_decodeInUse) { cmd.DW1.CodecSelect = cmd.CODEC_SELECT_DECODE; } else { cmd.DW1.CodecSelect = cmd.CODEC_SELECT_ENCODE; } MHW_MI_CHK_STATUS(Mos_AddCommand(cmdBuffer, &cmd, cmd.byteSize)); return eStatus; } MOS_STATUS AddHcpQmStateCmd( PMOS_COMMAND_BUFFER cmdBuffer, PMHW_VDBOX_QM_PARAMS params) { MOS_STATUS eStatus = MOS_STATUS_SUCCESS; MHW_FUNCTION_ENTER; MHW_MI_CHK_NULL(cmdBuffer); MHW_MI_CHK_NULL(params); typename THcpCmds::HCP_QM_STATE_CMD cmd; if (params->Standard == CODECHAL_HEVC) { uint8_t* qMatrix = nullptr; MHW_MI_CHK_NULL(params->pHevcIqMatrix); qMatrix = (uint8_t*)cmd.Quantizermatrix; for (uint8_t sizeId = 0; sizeId < 4; sizeId++) // 4x4, 8x8, 16x16, 32x32 { for (uint8_t predType = 0; predType < 2; predType++) // Intra, Inter { for (uint8_t color = 0; color < 3; color++) // Y, Cb, Cr { if ((sizeId == 3) && (color != 0)) break; cmd.DW1.Sizeid = sizeId; cmd.DW1.PredictionType = predType; cmd.DW1.ColorComponent = color; switch (sizeId) { case HEVC_QM_4x4: case HEVC_QM_8x8: default: cmd.DW1.DcCoefficient = 0; break; case HEVC_QM_16x16: cmd.DW1.DcCoefficient = params->pHevcIqMatrix->ListDC16x16[3 * predType + color]; break; case HEVC_QM_32x32: cmd.DW1.DcCoefficient = params->pHevcIqMatrix->ListDC32x32[predType]; break; } if (sizeId == HEVC_QM_4x4) { for (uint8_t i = 0; i < 4; i++) { for (uint8_t ii = 0; ii < 4; ii++) { qMatrix[4 * i + ii] = params->pHevcIqMatrix->List4x4[3 * predType + color][4 * i + ii]; } } } else if (sizeId == HEVC_QM_8x8) { for (uint8_t i = 0; i < 8; i++) { for (uint8_t ii = 0; ii < 8; ii++) { qMatrix[8 * i + ii] = params->pHevcIqMatrix->List8x8[3 * predType + color][8 * i + ii]; } } } else if (sizeId == HEVC_QM_16x16) { for (uint8_t i = 0; i < 8; i++) { for (uint8_t ii = 0; ii < 8; ii++) { qMatrix[8 * i + ii] = params->pHevcIqMatrix->List16x16[3 * predType + color][8 * i + ii]; } } } else // 32x32 { for (uint8_t i = 0; i < 8; i++) { for (uint8_t ii = 0; ii < 8; ii++) { qMatrix[8 * i + ii] = params->pHevcIqMatrix->List32x32[predType][8 * i + ii]; } } } MHW_MI_CHK_STATUS(Mos_AddCommand(cmdBuffer, &cmd, cmd.byteSize)); } } } } else { eStatus = MOS_STATUS_INVALID_PARAMETER; } return eStatus; } MOS_STATUS AddHcpPipeBufAddrCmd( PMOS_COMMAND_BUFFER cmdBuffer, PMHW_VDBOX_PIPE_BUF_ADDR_PARAMS params) { MOS_STATUS eStatus = MOS_STATUS_SUCCESS; MHW_FUNCTION_ENTER; MHW_MI_CHK_NULL(cmdBuffer); MHW_MI_CHK_NULL(params); MHW_RESOURCE_PARAMS resourceParams; typename THcpCmds::HCP_PIPE_BUF_ADDR_STATE_CMD cmd; bool firstRefPic = true; MOS_ZeroMemory(&resourceParams, sizeof(resourceParams)); resourceParams.dwLsbNum = MHW_VDBOX_HCP_DECODED_BUFFER_SHIFT; resourceParams.HwCommandType = MOS_MFX_PIPE_BUF_ADDR; // Decoded Picture // Caching policy change if any of below modes are true // Note for future dev: probably a good idea to add a macro for the below check if (this->m_osInterface->osCpInterface->IsHMEnabled() || this->m_osInterface->osCpInterface->IsIDMEnabled() || this->m_osInterface->osCpInterface->IsSMEnabled()) { cmd.DecodedPictureMemoryAddressAttributes.DW0.Value |= this->m_cacheabilitySettings[MOS_CODEC_RESOURCE_USAGE_PRE_DEBLOCKING_CODEC_PARTIALENCSURFACE].Value; } else { cmd.DecodedPictureMemoryAddressAttributes.DW0.Value |= this->m_cacheabilitySettings[MOS_CODEC_RESOURCE_USAGE_PRE_DEBLOCKING_CODEC].Value; } cmd.DecodedPictureMemoryAddressAttributes.DW0.BaseAddressTiledResourceMode = Mhw_ConvertToTRMode(params->psPreDeblockSurface->TileType); // For HEVC 8bit/10bit mixed case, register App's RenderTarget for specific use case if (params->presP010RTSurface != nullptr) { resourceParams.presResource = &(params->presP010RTSurface->OsResource); resourceParams.dwOffset = params->presP010RTSurface->dwOffset; resourceParams.pdwCmd = (cmd.DecodedPicture.DW0_1.Value); resourceParams.dwLocationInCmd = 1; resourceParams.bIsWritable = true; if (this->m_osInterface->bAllowExtraPatchToSameLoc) { MHW_MI_CHK_STATUS(this->pfnAddResourceToCmd( this->m_osInterface, cmdBuffer, &resourceParams)); } else //if not allowed to patch another OsResource to same location in cmd, just register resource here { MHW_MI_CHK_STATUS(this->m_osInterface->pfnRegisterResource( this->m_osInterface, resourceParams.presResource, resourceParams.bIsWritable, resourceParams.bIsWritable)); } } resourceParams.presResource = &(params->psPreDeblockSurface->OsResource); resourceParams.dwOffset = params->psPreDeblockSurface->dwOffset; resourceParams.pdwCmd = (cmd.DecodedPicture.DW0_1.Value); resourceParams.dwLocationInCmd = 1; resourceParams.bIsWritable = true; MHW_MI_CHK_STATUS(this->pfnAddResourceToCmd( this->m_osInterface, cmdBuffer, &resourceParams)); resourceParams.dwLsbNum = MHW_VDBOX_HCP_GENERAL_STATE_SHIFT; // Deblocking Filter Line Buffer if (this->m_hevcDfRowStoreCache.bEnabled) { cmd.DeblockingFilterLineBufferMemoryAddressAttributes.DW0.BaseAddressRowStoreScratchBufferCacheSelect = BUFFER_TO_INTERNALMEDIASTORAGE; cmd.DeblockingFilterLineBuffer.DW0_1.Graphicsaddress476 = this->m_hevcDfRowStoreCache.dwAddress; } else if (this->m_vp9DfRowStoreCache.bEnabled) { cmd.DeblockingFilterLineBufferMemoryAddressAttributes.DW0.BaseAddressRowStoreScratchBufferCacheSelect = BUFFER_TO_INTERNALMEDIASTORAGE; cmd.DeblockingFilterLineBuffer.DW0_1.Graphicsaddress476 = this->m_vp9DfRowStoreCache.dwAddress; } else if (params->presMfdDeblockingFilterRowStoreScratchBuffer != nullptr) { cmd.DeblockingFilterLineBufferMemoryAddressAttributes.DW0.Value |= this->m_cacheabilitySettings[MOS_CODEC_RESOURCE_USAGE_DEBLOCKINGFILTER_ROWSTORE_SCRATCH_BUFFER_CODEC].Value; resourceParams.presResource = params->presMfdDeblockingFilterRowStoreScratchBuffer; resourceParams.dwOffset = 0; resourceParams.pdwCmd = (cmd.DeblockingFilterLineBuffer.DW0_1.Value); resourceParams.dwLocationInCmd = 4; resourceParams.bIsWritable = true; MHW_MI_CHK_STATUS(this->pfnAddResourceToCmd( this->m_osInterface, cmdBuffer, &resourceParams)); } // Deblocking Filter Tile Line Buffer if (params->presDeblockingFilterTileRowStoreScratchBuffer != nullptr) { cmd.DeblockingFilterTileLineBufferMemoryAddressAttributes.DW0.Value |= this->m_cacheabilitySettings[MOS_CODEC_RESOURCE_USAGE_DEBLOCKINGFILTER_ROWSTORE_SCRATCH_BUFFER_CODEC].Value; resourceParams.presResource = params->presDeblockingFilterTileRowStoreScratchBuffer; resourceParams.dwOffset = 0; resourceParams.pdwCmd = (cmd.DeblockingFilterTileLineBuffer.DW0_1.Value); resourceParams.dwLocationInCmd = 7; resourceParams.bIsWritable = true; MHW_MI_CHK_STATUS(this->pfnAddResourceToCmd( this->m_osInterface, cmdBuffer, &resourceParams)); } // Deblocking Filter Tile Column Buffer if (params->presDeblockingFilterColumnRowStoreScratchBuffer != nullptr) { cmd.DeblockingFilterTileColumnBufferMemoryAddressAttributes.DW0.Value |= this->m_cacheabilitySettings[MOS_CODEC_RESOURCE_USAGE_DEBLOCKINGFILTER_ROWSTORE_SCRATCH_BUFFER_CODEC].Value; resourceParams.presResource = params->presDeblockingFilterColumnRowStoreScratchBuffer; resourceParams.dwOffset = 0; resourceParams.pdwCmd = (cmd.DeblockingFilterTileColumnBuffer.DW0_1.Value); resourceParams.dwLocationInCmd = 10; resourceParams.bIsWritable = true; MHW_MI_CHK_STATUS(this->pfnAddResourceToCmd( this->m_osInterface, cmdBuffer, &resourceParams)); } // Metadata Line Buffer if (this->m_hevcDatRowStoreCache.bEnabled) { cmd.MetadataLineBufferMemoryAddressAttributes.DW0.BaseAddressRowStoreScratchBufferCacheSelect = BUFFER_TO_INTERNALMEDIASTORAGE; cmd.MetadataLineBuffer.DW0_1.Graphicsaddress476 = this->m_hevcDatRowStoreCache.dwAddress; } else if (params->presMetadataLineBuffer != nullptr) { cmd.MetadataLineBufferMemoryAddressAttributes.DW0.Value |= this->m_cacheabilitySettings[MOS_CODEC_RESOURCE_USAGE_HCP_MD_CODEC].Value; resourceParams.presResource = params->presMetadataLineBuffer; resourceParams.dwOffset = 0; resourceParams.pdwCmd = cmd.MetadataLineBuffer.DW0_1.Value; resourceParams.dwLocationInCmd = 13; resourceParams.bIsWritable = true; MHW_MI_CHK_STATUS(this->pfnAddResourceToCmd( this->m_osInterface, cmdBuffer, &resourceParams)); } // Metadata Tile Line Buffer if (params->presMetadataTileLineBuffer != nullptr) { cmd.MetadataTileLineBufferMemoryAddressAttributes.DW0.Value |= this->m_cacheabilitySettings[MOS_CODEC_RESOURCE_USAGE_HCP_MD_CODEC].Value; resourceParams.presResource = params->presMetadataTileLineBuffer; resourceParams.dwOffset = 0; resourceParams.pdwCmd = (cmd.MetadataTileLineBuffer.DW0_1.Value); resourceParams.dwLocationInCmd = 16; resourceParams.bIsWritable = true; MHW_MI_CHK_STATUS(this->pfnAddResourceToCmd( this->m_osInterface, cmdBuffer, &resourceParams)); } // Metadata Tile Column Buffer if (params->presMetadataTileColumnBuffer != nullptr) { cmd.MetadataTileColumnBufferMemoryAddressAttributes.DW0.Value |= this->m_cacheabilitySettings[MOS_CODEC_RESOURCE_USAGE_HCP_MD_CODEC].Value; resourceParams.presResource = params->presMetadataTileColumnBuffer; resourceParams.dwOffset = 0; resourceParams.pdwCmd = (cmd.MetadataTileColumnBuffer.DW0_1.Value); resourceParams.dwLocationInCmd = 19; resourceParams.bIsWritable = true; MHW_MI_CHK_STATUS(this->pfnAddResourceToCmd( this->m_osInterface, cmdBuffer, &resourceParams)); } // SAO Line Buffer if (this->m_hevcSaoRowStoreCache.bEnabled) { cmd.SaoLineBufferMemoryAddressAttributes.DW0.BaseAddressRowStoreScratchBufferCacheSelect = BUFFER_TO_INTERNALMEDIASTORAGE; cmd.SaoLineBuffer.DW0_1.Graphicsaddress476 = this->m_hevcSaoRowStoreCache.dwAddress; } else if (params->presSaoLineBuffer != nullptr) { cmd.SaoLineBufferMemoryAddressAttributes.DW0.Value |= this->m_cacheabilitySettings[MOS_CODEC_RESOURCE_USAGE_HCP_SAO_CODEC].Value; resourceParams.presResource = params->presSaoLineBuffer; resourceParams.dwOffset = 0; resourceParams.pdwCmd = (cmd.SaoLineBuffer.DW0_1.Value); resourceParams.dwLocationInCmd = 22; resourceParams.bIsWritable = true; MHW_MI_CHK_STATUS(this->pfnAddResourceToCmd( this->m_osInterface, cmdBuffer, &resourceParams)); } // SAO Tile Line Buffer if (params->presSaoTileLineBuffer != nullptr) { cmd.SaoTileLineBufferMemoryAddressAttributes.DW0.Value |= this->m_cacheabilitySettings[MOS_CODEC_RESOURCE_USAGE_HCP_SAO_CODEC].Value; resourceParams.presResource = params->presSaoTileLineBuffer; resourceParams.dwOffset = 0; resourceParams.pdwCmd = (cmd.SaoTileLineBuffer.DW0_1.Value); resourceParams.dwLocationInCmd = 25; resourceParams.bIsWritable = true; MHW_MI_CHK_STATUS(this->pfnAddResourceToCmd( this->m_osInterface, cmdBuffer, &resourceParams)); } // SAO Tile Column Buffer if (params->presSaoTileColumnBuffer != nullptr) { cmd.SaoTileColumnBufferMemoryAddressAttributes.DW0.Value |= this->m_cacheabilitySettings[MOS_CODEC_RESOURCE_USAGE_HCP_SAO_CODEC].Value; resourceParams.presResource = params->presSaoTileColumnBuffer; resourceParams.dwOffset = 0; resourceParams.pdwCmd = (cmd.SaoTileColumnBuffer.DW0_1.Value); resourceParams.dwLocationInCmd = 28; resourceParams.bIsWritable = true; MHW_MI_CHK_STATUS(this->pfnAddResourceToCmd( this->m_osInterface, cmdBuffer, &resourceParams)); } // Current Motion Vector Temporal Buffer if (params->presCurMvTempBuffer != nullptr) { cmd.CurrentMotionVectorTemporalBufferMemoryAddressAttributes.DW0.Value |= this->m_cacheabilitySettings[MOS_CODEC_RESOURCE_USAGE_HCP_MV_CODEC].Value; resourceParams.presResource = params->presCurMvTempBuffer; resourceParams.dwOffset = 0; resourceParams.pdwCmd = (cmd.CurrentMotionVectorTemporalBuffer.DW0_1.Value); resourceParams.dwLocationInCmd = 31; resourceParams.bIsWritable = true; MHW_MI_CHK_STATUS(this->pfnAddResourceToCmd( this->m_osInterface, cmdBuffer, &resourceParams)); } // Reference Picture Buffer cmd.ReferencePictureBaseAddressMemoryAddressAttributes.DW0.Value |= this->m_cacheabilitySettings[MOS_CODEC_RESOURCE_USAGE_REFERENCE_PICTURE_CODEC].Value; // NOTE: for both HEVC and VP9, set all the 8 ref pic addresses in HCP_PIPE_BUF_ADDR_STATE command to valid addresses for error concealment purpose for (uint32_t i = 0; i < CODECHAL_MAX_CUR_NUM_REF_FRAME_HEVC; i++) { if (params->presReferences[i] != nullptr) { MOS_SURFACE details; MOS_ZeroMemory(&details, sizeof(details)); details.Format = Format_Invalid; MHW_MI_CHK_STATUS(this->m_osInterface->pfnGetResourceInfo(this->m_osInterface, params->presReferences[i], &details)); if (firstRefPic) { cmd.ReferencePictureBaseAddressMemoryAddressAttributes.DW0.BaseAddressTiledResourceMode = Mhw_ConvertToTRMode(details.TileType); firstRefPic = false; } resourceParams.presResource = params->presReferences[i]; resourceParams.pdwCmd = (cmd.ReferencePictureBaseAddressRefaddr07[i].DW0_1.Value); resourceParams.dwOffset = details.RenderOffset.YUV.Y.BaseOffset; resourceParams.dwLocationInCmd = (i * 2) + 37; // * 2 to account for QW rather than DW resourceParams.bIsWritable = false; resourceParams.dwSharedMocsOffset = 53 - resourceParams.dwLocationInCmd; // Common Prodected Data bit is in DW53 MHW_MI_CHK_STATUS(this->pfnAddResourceToCmd( this->m_osInterface, cmdBuffer, &resourceParams)); } } // Reset dwSharedMocsOffset resourceParams.dwSharedMocsOffset = MOS_MFX_PIPE_BUF_ADDR; // Original Uncompressed Picture Source, Encoder only if (params->psRawSurface != nullptr) { cmd.OriginalUncompressedPictureSourceMemoryAddressAttributes.DW0.Value |= this->m_cacheabilitySettings[MOS_CODEC_RESOURCE_USAGE_ORIGINAL_UNCOMPRESSED_PICTURE_ENCODE].Value; cmd.OriginalUncompressedPictureSourceMemoryAddressAttributes.DW0.BaseAddressTiledResourceMode = Mhw_ConvertToTRMode(params->psRawSurface->TileType); resourceParams.presResource = &params->psRawSurface->OsResource; resourceParams.dwOffset = params->psRawSurface->dwOffset; resourceParams.pdwCmd = (cmd.OriginalUncompressedPictureSource.DW0_1.Value); resourceParams.dwLocationInCmd = 54; resourceParams.bIsWritable = false; MHW_MI_CHK_STATUS(this->pfnAddResourceToCmd( this->m_osInterface, cmdBuffer, &resourceParams)); } // StreamOut Data Destination, Decoder only if (params->presStreamOutBuffer != nullptr) { cmd.StreamoutDataDestinationMemoryAddressAttributes.DW0.Value |= this->m_cacheabilitySettings[MOS_CODEC_RESOURCE_USAGE_STREAMOUT_DATA_CODEC].Value; resourceParams.presResource = params->presStreamOutBuffer; resourceParams.dwOffset = 0; resourceParams.pdwCmd = (cmd.StreamoutDataDestination.DW0_1.Value); resourceParams.dwLocationInCmd = 57; resourceParams.bIsWritable = true; MHW_MI_CHK_STATUS(this->pfnAddResourceToCmd( this->m_osInterface, cmdBuffer, &resourceParams)); } // Decoded Picture Status / Error Buffer Base Address if (params->presLcuBaseAddressBuffer != nullptr) { cmd.DecodedPictureStatusErrorBufferBaseAddressMemoryAddressAttributes.DW0.Value |= this->m_cacheabilitySettings[MOS_CODEC_RESOURCE_USAGE_HCP_STATUS_ERROR_CODEC].Value; resourceParams.presResource = params->presLcuBaseAddressBuffer; resourceParams.dwOffset = 0; resourceParams.pdwCmd = (cmd.DecodedPictureStatusErrorBufferBaseAddressOrEncodedSliceSizeStreamoutBaseAddress.DW0_1.Value); resourceParams.dwLocationInCmd = 60; resourceParams.bIsWritable = true; MHW_MI_CHK_STATUS(this->pfnAddResourceToCmd( this->m_osInterface, cmdBuffer, &resourceParams)); } // LCU ILDB StreamOut Buffer if (params->presLcuILDBStreamOutBuffer != nullptr) { cmd.LcuIldbStreamoutBufferMemoryAddressAttributes.DW0.Value |= this->m_cacheabilitySettings[MOS_CODEC_RESOURCE_USAGE_HCP_LCU_ILDB_STREAMOUT_CODEC].Value; resourceParams.presResource = params->presLcuILDBStreamOutBuffer; resourceParams.dwOffset = 0; resourceParams.pdwCmd = (cmd.LcuIldbStreamoutBuffer.DW0_1.Value); resourceParams.dwLocationInCmd = 63; resourceParams.bIsWritable = true; MHW_MI_CHK_STATUS(this->pfnAddResourceToCmd( this->m_osInterface, cmdBuffer, &resourceParams)); } // Collocated Motion vector Temporal Buffer cmd.CollocatedMotionVectorTemporalBuffer07MemoryAddressAttributes.DW0.Value |= this->m_cacheabilitySettings[MOS_CODEC_RESOURCE_USAGE_HCP_MV_CODEC].Value; for (uint32_t i = 0; i < CODECHAL_MAX_CUR_NUM_REF_FRAME_HEVC; i++) { if (params->presColMvTempBuffer[i] != nullptr) { resourceParams.presResource = params->presColMvTempBuffer[i]; resourceParams.dwOffset = 0; resourceParams.pdwCmd = (cmd.CollocatedMotionVectorTemporalBuffer07[i].DW0_1.Value); resourceParams.dwLocationInCmd = (i * 2) + 66; resourceParams.bIsWritable = false; resourceParams.dwSharedMocsOffset = 82 - resourceParams.dwLocationInCmd; // Common Prodected Data bit is in DW82 MHW_MI_CHK_STATUS(this->pfnAddResourceToCmd( this->m_osInterface, cmdBuffer, &resourceParams)); } } // Reset dwSharedMocsOffset resourceParams.dwSharedMocsOffset = 0; // VP9 Probability Buffer if (params->presVp9ProbBuffer != nullptr) { cmd.Vp9ProbabilityBufferReadWriteMemoryAddressAttributes.DW0.Value |= this->m_cacheabilitySettings[MOS_CODEC_RESOURCE_USAGE_VP9_PROBABILITY_BUFFER_CODEC].Value; resourceParams.presResource = params->presVp9ProbBuffer; resourceParams.dwOffset = 0; resourceParams.pdwCmd = (cmd.Vp9ProbabilityBufferReadWrite.DW0_1.Value); resourceParams.dwLocationInCmd = 83; resourceParams.bIsWritable = true; resourceParams.dwSharedMocsOffset = 85 - resourceParams.dwLocationInCmd; // Common Prodected Data bit is in DW88 MHW_MI_CHK_STATUS(this->pfnAddResourceToCmd( this->m_osInterface, cmdBuffer, &resourceParams)); } // Reset dwSharedMocsOffset resourceParams.dwSharedMocsOffset = 0; // VP9 Segment Id Buffer if (params->presVp9SegmentIdBuffer != nullptr) { cmd.Vp9SegmentIdBufferReadWriteMemoryAddressAttributes.DW0.Value |= this->m_cacheabilitySettings[MOS_CODEC_RESOURCE_USAGE_VP9_SEGMENT_ID_BUFFER_CODEC].Value; resourceParams.presResource = params->presVp9SegmentIdBuffer; resourceParams.dwOffset = 0; resourceParams.pdwCmd = (cmd.DW86_87.Value); resourceParams.dwLocationInCmd = 86; resourceParams.bIsWritable = true; resourceParams.dwSharedMocsOffset = 88 - resourceParams.dwLocationInCmd; // Common Prodected Data bit is in DW88 MHW_MI_CHK_STATUS(this->pfnAddResourceToCmd( this->m_osInterface, cmdBuffer, &resourceParams)); } // Reset dwSharedMocsOffset resourceParams.dwSharedMocsOffset = 0; // HVD Line Row Store Buffer if (this->m_vp9HvdRowStoreCache.bEnabled) { cmd.Vp9HvdLineRowstoreBufferReadWriteMemoryAddressAttributes.DW0.BaseAddressRowStoreScratchBufferCacheSelect = BUFFER_TO_INTERNALMEDIASTORAGE; cmd.Vp9HvdLineRowstoreBufferReadWrite.DW0_1.Graphicsaddress476 = this->m_vp9HvdRowStoreCache.dwAddress; } else if (params->presHvdLineRowStoreBuffer != nullptr) { cmd.Vp9HvdLineRowstoreBufferReadWriteMemoryAddressAttributes.DW0.Value |= this->m_cacheabilitySettings[MOS_CODEC_RESOURCE_USAGE_VP9_HVD_ROWSTORE_BUFFER_CODEC].Value; resourceParams.presResource = params->presHvdLineRowStoreBuffer; resourceParams.dwOffset = 0; resourceParams.pdwCmd = (cmd.Vp9HvdLineRowstoreBufferReadWrite.DW0_1.Value); resourceParams.dwLocationInCmd = 89; resourceParams.bIsWritable = true; MHW_MI_CHK_STATUS(this->pfnAddResourceToCmd( this->m_osInterface, cmdBuffer, &resourceParams)); } // HVD Tile Row Store Buffer if (params->presHvdTileRowStoreBuffer != nullptr) { cmd.Vp9HvdTileRowstoreBufferReadWriteMemoryAddressAttributes.DW0.Value |= this->m_cacheabilitySettings[MOS_CODEC_RESOURCE_USAGE_VP9_HVD_ROWSTORE_BUFFER_CODEC].Value; resourceParams.presResource = params->presHvdTileRowStoreBuffer; resourceParams.dwOffset = 0; resourceParams.pdwCmd = (cmd.Vp9HvdTileRowstoreBufferReadWrite.DW0_1.Value); resourceParams.dwLocationInCmd = 92; resourceParams.bIsWritable = true; MHW_MI_CHK_STATUS(this->pfnAddResourceToCmd( this->m_osInterface, cmdBuffer, &resourceParams)); } MHW_MI_CHK_STATUS(Mos_AddCommand(cmdBuffer, &cmd, cmd.byteSize)); return eStatus; } MOS_STATUS AddHcpIndObjBaseAddrCmd( PMOS_COMMAND_BUFFER cmdBuffer, PMHW_VDBOX_IND_OBJ_BASE_ADDR_PARAMS params) { MOS_STATUS eStatus = MOS_STATUS_SUCCESS;; MHW_FUNCTION_ENTER; MHW_MI_CHK_NULL(params); MHW_RESOURCE_PARAMS resourceParams; typename THcpCmds::HCP_IND_OBJ_BASE_ADDR_STATE_CMD cmd; MOS_ZeroMemory(&resourceParams, sizeof(resourceParams)); resourceParams.dwLsbNum = MHW_VDBOX_HCP_UPPER_BOUND_STATE_SHIFT; resourceParams.HwCommandType = MOS_MFX_INDIRECT_OBJ_BASE_ADDR; // mode specific settings if (CodecHalIsDecodeModeVLD(params->Mode)) { MHW_MI_CHK_NULL(params->presDataBuffer); cmd.HcpIndirectBitstreamObjectMemoryAddressAttributes.DW0.Value |= this->m_cacheabilitySettings[MOS_CODEC_RESOURCE_USAGE_MFX_INDIRECT_BITSTREAM_OBJECT_DECODE].Value; resourceParams.presResource = params->presDataBuffer; resourceParams.dwOffset = params->dwDataOffset; resourceParams.pdwCmd = (cmd.HcpIndirectBitstreamObjectBaseAddress.DW0_1.Value); resourceParams.dwLocationInCmd = 1; resourceParams.dwSize = params->dwDataSize; resourceParams.bIsWritable = false; // upper bound of the allocated resource will be set at 3 DW apart from address location resourceParams.dwUpperBoundLocationOffsetFromCmd = 3; MHW_MI_CHK_STATUS(this->pfnAddResourceToCmd( this->m_osInterface, cmdBuffer, &resourceParams)); resourceParams.dwUpperBoundLocationOffsetFromCmd = 0; } // following is for encoder if (!this->m_decodeInUse) { if (params->presMvObjectBuffer) { cmd.HcpIndirectCuObjectObjectMemoryAddressAttributes.DW0.Value |= this->m_cacheabilitySettings[MOS_CODEC_RESOURCE_USAGE_MFX_INDIRECT_MV_OBJECT_CODEC].Value; resourceParams.presResource = params->presMvObjectBuffer; resourceParams.dwOffset = params->dwMvObjectOffset; resourceParams.pdwCmd = (cmd.DW6_7.Value); resourceParams.dwLocationInCmd = 6; resourceParams.dwSize = MOS_ALIGN_CEIL(params->dwMvObjectSize, 0x1000); resourceParams.bIsWritable = false; // no upper bound for indirect CU object resourceParams.dwUpperBoundLocationOffsetFromCmd = 0; MHW_MI_CHK_STATUS(this->pfnAddResourceToCmd( this->m_osInterface, cmdBuffer, &resourceParams)); } if (params->presPakBaseObjectBuffer) { cmd.HcpPakBseObjectAddressMemoryAddressAttributes.DW0.Value |= this->m_cacheabilitySettings[MOS_CODEC_RESOURCE_USAGE_MFC_INDIRECT_PAKBASE_OBJECT_CODEC].Value; resourceParams.presResource = params->presPakBaseObjectBuffer; resourceParams.dwOffset = 0; resourceParams.pdwCmd = (cmd.DW9_10.Value); resourceParams.dwLocationInCmd = 9; resourceParams.dwSize = MOS_ALIGN_CEIL(params->dwPakBaseObjectSize, 0x1000); resourceParams.bIsWritable = true; // upper bound of the allocated resource will be set at 3 DW apart from address location resourceParams.dwUpperBoundLocationOffsetFromCmd = 3; MHW_MI_CHK_STATUS(this->pfnAddResourceToCmd( this->m_osInterface, cmdBuffer, &resourceParams)); } } MHW_MI_CHK_STATUS(Mos_AddCommand(cmdBuffer, &cmd, cmd.byteSize)); return eStatus; } MOS_STATUS AddHcpFqmStateCmd( PMOS_COMMAND_BUFFER cmdBuffer, PMHW_VDBOX_QM_PARAMS params) { MOS_STATUS eStatus = MOS_STATUS_SUCCESS; MHW_FUNCTION_ENTER; MHW_MI_CHK_NULL(cmdBuffer); MHW_MI_CHK_NULL(params); typename THcpCmds::HCP_FQM_STATE_CMD cmd; if (params->Standard == CODECHAL_HEVC) { MHW_MI_CHK_NULL(params->pHevcIqMatrix); auto iqMatrix = params->pHevcIqMatrix; uint16_t *fqMatrix = (uint16_t*)cmd.Quantizermatrix; /* 4x4 */ for (uint8_t i = 0; i < 32; i++) { cmd.Quantizermatrix[i] = 0; } for (uint8_t intraInter = 0; intraInter <= 1; intraInter++) { cmd.DW1.IntraInter = intraInter; cmd.DW1.Sizeid = 0; cmd.DW1.ColorComponent = 0; for (uint8_t i = 0; i < 16; i++) { fqMatrix[i] = GetReciprocalScalingValue(iqMatrix->List4x4[3 * intraInter][i]); } MHW_MI_CHK_STATUS(Mos_AddCommand(cmdBuffer, &cmd, cmd.byteSize)); } /* 8x8, 16x16 and 32x32 */ for (uint8_t i = 0; i < 32; i++) { cmd.Quantizermatrix[i] = 0; } for (uint8_t intraInter = 0; intraInter <= 1; intraInter++) { cmd.DW1.IntraInter = intraInter; cmd.DW1.Sizeid = 1; cmd.DW1.ColorComponent = 0; for (uint8_t i = 0; i < 64; i++) { fqMatrix[i] = GetReciprocalScalingValue(iqMatrix->List8x8[3 * intraInter][i]); } MHW_MI_CHK_STATUS(Mos_AddCommand(cmdBuffer, &cmd, cmd.byteSize)); } /* 16x16 DC */ for (uint8_t i = 0; i < 32; i++) { cmd.Quantizermatrix[i] = 0; } for (uint8_t intraInter = 0; intraInter <= 1; intraInter++) { cmd.DW1.IntraInter = intraInter; cmd.DW1.Sizeid = 2; cmd.DW1.ColorComponent = 0; cmd.DW1.FqmDcValue1Dc = GetReciprocalScalingValue(iqMatrix->ListDC16x16[3 * intraInter]); for (uint8_t i = 0; i < 64; i++) { fqMatrix[i] = GetReciprocalScalingValue(iqMatrix->List16x16[3 * intraInter][i]); } MHW_MI_CHK_STATUS(Mos_AddCommand(cmdBuffer, &cmd, cmd.byteSize)); } /* 32x32 DC */ for (uint8_t i = 0; i < 32; i++) { cmd.Quantizermatrix[i] = 0; } for (uint8_t intraInter = 0; intraInter <= 1; intraInter++) { cmd.DW1.IntraInter = intraInter; cmd.DW1.Sizeid = 3; cmd.DW1.ColorComponent = 0; cmd.DW1.FqmDcValue1Dc = GetReciprocalScalingValue(iqMatrix->ListDC32x32[intraInter]); for (uint8_t i = 0; i < 64; i++) { fqMatrix[i] = GetReciprocalScalingValue(iqMatrix->List32x32[intraInter][i]); } MHW_MI_CHK_STATUS(Mos_AddCommand(cmdBuffer, &cmd, cmd.byteSize)); } } else { eStatus = MOS_STATUS_INVALID_PARAMETER; } return eStatus; } MOS_STATUS AddHcpEncodePicStateCmd( PMOS_COMMAND_BUFFER cmdBuffer, PMHW_VDBOX_HEVC_PIC_STATE params) { MOS_STATUS eStatus = MOS_STATUS_SUCCESS; MHW_FUNCTION_ENTER; MHW_MI_CHK_NULL(params); MHW_MI_CHK_NULL(params->pHevcEncSeqParams); MHW_MI_CHK_NULL(params->pHevcEncPicParams); typename THcpCmds::HCP_PIC_STATE_CMD cmd; auto hevcSeqParams = params->pHevcEncSeqParams; auto hevcPicParams = params->pHevcEncPicParams; cmd.DW1.Framewidthinmincbminus1 = hevcSeqParams->wFrameWidthInMinCbMinus1; cmd.DW1.Frameheightinmincbminus1 = hevcSeqParams->wFrameHeightInMinCbMinus1; cmd.DW2.Mincusize = hevcSeqParams->log2_min_coding_block_size_minus3; cmd.DW2.CtbsizeLcusize = hevcSeqParams->log2_max_coding_block_size_minus3; cmd.DW2.Maxtusize = hevcSeqParams->log2_max_transform_block_size_minus2; cmd.DW2.Mintusize = hevcSeqParams->log2_min_transform_block_size_minus2; cmd.DW2.Minpcmsize = 0; cmd.DW2.Maxpcmsize = 0; cmd.DW3.Colpicisi = 0; // MBZ cmd.DW3.Curpicisi = 0; // MBZ cmd.DW4.SampleAdaptiveOffsetEnabledFlag = 0; cmd.DW4.PcmEnabledFlag = 0; cmd.DW4.CuQpDeltaEnabledFlag = hevcPicParams->cu_qp_delta_enabled_flag; cmd.DW4.DiffCuQpDeltaDepthOrNamedAsMaxDqpDepth = hevcPicParams->diff_cu_qp_delta_depth; cmd.DW4.PcmLoopFilterDisableFlag = 1; cmd.DW4.ConstrainedIntraPredFlag = 0; cmd.DW4.Log2ParallelMergeLevelMinus2 = 0; cmd.DW4.SignDataHidingFlag = 0; cmd.DW4.TilesEnabledFlag = 0; cmd.DW4.WeightedPredFlag = hevcPicParams->weighted_pred_flag; cmd.DW4.WeightedBipredFlag = hevcPicParams->weighted_bipred_flag; cmd.DW4.Fieldpic = 0; cmd.DW4.Bottomfield = 0; cmd.DW4.TransformSkipEnabledFlag = hevcPicParams->transform_skip_enabled_flag; cmd.DW4.AmpEnabledFlag = hevcSeqParams->amp_enabled_flag; cmd.DW4.Reserved152 = hevcPicParams->LcuMaxBitsizeAllowed > 0; cmd.DW4.TransquantBypassEnableFlag = hevcPicParams->transquant_bypass_enabled_flag; cmd.DW4.StrongIntraSmoothingEnableFlag = hevcSeqParams->strong_intra_smoothing_enable_flag; cmd.DW5.PicCbQpOffset = hevcPicParams->pps_cb_qp_offset & 0x1f; cmd.DW5.PicCrQpOffset = hevcPicParams->pps_cr_qp_offset & 0x1f; cmd.DW5.MaxTransformHierarchyDepthIntraOrNamedAsTuMaxDepthIntra = hevcSeqParams->max_transform_hierarchy_depth_intra; cmd.DW5.MaxTransformHierarchyDepthInterOrNamedAsTuMaxDepthInter = hevcSeqParams->max_transform_hierarchy_depth_inter; cmd.DW5.PcmSampleBitDepthChromaMinus1 = 7; cmd.DW5.PcmSampleBitDepthLumaMinus1 = 7; cmd.DW6.LcumaxbitstatusenLcumaxsizereportmask = 1; cmd.DW6.FrameszoverstatusenFramebitratemaxreportmask = 1; cmd.DW6.FrameszunderstatusenFramebitrateminreportmask = 1; cmd.DW6.LcuMaxBitsizeAllowed = hevcPicParams->LcuMaxBitsizeAllowed; if (params->maxFrameSize && params->currPass) { cmd.DW6.Nonfirstpassflag = 1; } else { cmd.DW6.Nonfirstpassflag = 0; } // Set this to max value cmd.DW7.Framebitratemax = (1 << 14) - 1; // Set this to Kilo Byte (=1) - Framebitratemax is in units of 4KBytes cmd.DW7.Framebitratemaxunit = 1; // Set this to min available value cmd.DW8.Framebitratemin = 0; // Set this to Kilo Byte (=1) - Framebitratemin is in units of 4KBytes cmd.DW8.Framebitrateminunit = 1; // Set frame bitrate max and min delta to 0 cmd.DW9.Framebitratemindelta = 0; cmd.DW9.Framebitratemaxdelta = 0; cmd.DW10_11.Framedeltaqpmax = 0; cmd.DW12_13.Framedeltaqpmin = 0; // Set frame delta QP max and min range array as [0, 1, 2, 4, 8, 16, 32, 255] // Delta QP range = [Framebitratemaxdelta*(FramedeltaQpmaxrange[n]>>5), Framebitratemaxdelta*(FramedeltaQpmaxrange[n]>>5)] cmd.DW14_15.Value[0] = cmd.DW16_17.Value[0] = (4 << 24) | (2 << 16) | (1 << 8); cmd.DW14_15.Value[1] = cmd.DW16_17.Value[1] = (255 << 24) | (32 << 16) | (16 << 8) | 8; // Add for multiple pass if (params->maxFrameSize > 0 && params->deltaQp) { uint8_t hevcMaxPassNum = 8; // When current pass is less than the max number of pass, set the delta QP. if (params->currPass < hevcMaxPassNum) { cmd.DW10_11.Value[0] = (params->deltaQp[params->currPass] << 24) | (params->deltaQp[params->currPass] << 16) | (params->deltaQp[params->currPass] << 8) | params->deltaQp[params->currPass]; cmd.DW10_11.Value[1] = (params->deltaQp[params->currPass] << 24) | (params->deltaQp[params->currPass] << 16) | (params->deltaQp[params->currPass] << 8) | params->deltaQp[params->currPass]; } // If the calculated value of max frame size exceeded 14 bits, need set the unit as 4K byte. Else, set the unit as 32 byte. if (params->maxFrameSize >= (0x1 << 14) * 32) { cmd.DW7.Framebitratemaxunit = 1; cmd.DW7.Framebitratemax = params->maxFrameSize >> 12; cmd.DW9.Framebitratemaxdelta = params->maxFrameSize >> 13; } else { cmd.DW7.Framebitratemaxunit = 0; cmd.DW7.Framebitratemax = params->maxFrameSize >> 5; cmd.DW9.Framebitratemaxdelta = params->maxFrameSize >> 6; } } MHW_MI_CHK_STATUS(Mos_AddCommand(cmdBuffer, &cmd, cmd.byteSize)); return eStatus; } MOS_STATUS AddHcpEncodeSliceStateCmd( PMOS_COMMAND_BUFFER cmdBuffer, PMHW_VDBOX_HEVC_SLICE_STATE hevcSliceState) { MOS_STATUS eStatus = MOS_STATUS_SUCCESS; MHW_FUNCTION_ENTER; MHW_MI_CHK_NULL(hevcSliceState); typename THcpCmds::HCP_SLICE_STATE_CMD cmd; auto hevcSliceParams = hevcSliceState->pEncodeHevcSliceParams; auto hevcPicParams = hevcSliceState->pEncodeHevcPicParams; auto hevcSeqParams = hevcSliceState->pEncodeHevcSeqParams; uint32_t ctbSize = 1 << (hevcSeqParams->log2_max_coding_block_size_minus3 + 3); uint32_t widthInPix = (1 << (hevcSeqParams->log2_min_coding_block_size_minus3 + 3)) * (hevcSeqParams->wFrameWidthInMinCbMinus1 + 1); uint32_t widthInCtb = (widthInPix / ctbSize) + ((widthInPix % ctbSize) ? 1 : 0); // round up uint32_t ctbAddr = hevcSliceParams->slice_segment_address; cmd.DW1.SlicestartctbxOrSliceStartLcuXEncoder = ctbAddr % widthInCtb; cmd.DW1.SlicestartctbyOrSliceStartLcuYEncoder = ctbAddr / widthInCtb; ctbAddr = hevcSliceParams->slice_segment_address + hevcSliceParams->NumLCUsInSlice; cmd.DW2.NextslicestartctbxOrNextSliceStartLcuXEncoder = ctbAddr % widthInCtb; cmd.DW2.NextslicestartctbyOrNextSliceStartLcuYEncoder = ctbAddr / widthInCtb; cmd.DW3.SliceType = hevcSliceParams->slice_type; cmd.DW3.Lastsliceofpic = hevcSliceState->bLastSlice; cmd.DW3.DependentSliceFlag = hevcSliceParams->dependent_slice_segment_flag; cmd.DW3.SliceTemporalMvpEnableFlag = hevcSliceParams->slice_temporal_mvp_enable_flag; cmd.DW3.Sliceqp = hevcSliceParams->slice_qp_delta + hevcPicParams->QpY; cmd.DW3.SliceCbQpOffset = hevcSliceParams->slice_cb_qp_offset; cmd.DW3.SliceCrQpOffset = hevcSliceParams->slice_cr_qp_offset; cmd.DW4.SliceHeaderDisableDeblockingFilterFlag = hevcSliceParams->slice_deblocking_filter_disable_flag; cmd.DW4.SliceTcOffsetDiv2OrFinalTcOffsetDiv2Encoder = hevcSliceParams->tc_offset_div2; cmd.DW4.SliceBetaOffsetDiv2OrFinalBetaOffsetDiv2Encoder = hevcSliceParams->beta_offset_div2; cmd.DW4.SliceLoopFilterAcrossSlicesEnabledFlag = 0; cmd.DW4.SliceSaoChromaFlag = 0; cmd.DW4.SliceSaoLumaFlag = 0; cmd.DW4.MvdL1ZeroFlag = 0; cmd.DW4.Islowdelay = hevcSliceState->bIsLowDelay; cmd.DW4.CollocatedFromL0Flag = hevcSliceParams->collocated_from_l0_flag; cmd.DW4.Chromalog2Weightdenom = hevcSliceParams->luma_log2_weight_denom + hevcSliceParams->delta_chroma_log2_weight_denom; cmd.DW4.LumaLog2WeightDenom = hevcSliceParams->luma_log2_weight_denom; cmd.DW4.CabacInitFlag = hevcSliceParams->cabac_init_flag; cmd.DW4.Maxmergeidx = hevcSliceParams->MaxNumMergeCand - 1; if (cmd.DW3.SliceTemporalMvpEnableFlag) { if (cmd.DW3.SliceType == MhwVdboxHcpInterface::hevcSliceI) { cmd.DW4.Collocatedrefidx = 0; } else { // need to check with Ce for DDI issues uint8_t collocatedFromL0Flag = cmd.DW4.CollocatedFromL0Flag; uint8_t collocatedRefIndex = hevcPicParams->CollocatedRefPicIndex; MHW_ASSERT(collocatedRefIndex < CODEC_MAX_NUM_REF_FRAME_HEVC); uint8_t collocatedFrameIdx = hevcSliceState->pRefIdxMapping[collocatedRefIndex]; MHW_ASSERT(collocatedRefIndex < CODEC_MAX_NUM_REF_FRAME_HEVC); cmd.DW4.Collocatedrefidx = collocatedFrameIdx; } } else { cmd.DW4.Collocatedrefidx = 0; } cmd.DW5.Sliceheaderlength = 0; if(!hevcPicParams->bUsedAsRef && hevcPicParams->CodingType != I_TYPE) { // non reference B frame cmd.DW6.Roundinter = 0; cmd.DW6.Roundintra = 8; } else { //Other frames cmd.DW6.Roundinter = 5; cmd.DW6.Roundintra = 11; } cmd.DW7.Cabaczerowordinsertionenable = 1; cmd.DW7.Emulationbytesliceinsertenable = 1; cmd.DW7.HeaderInsertionEnable = 1; cmd.DW7.TailInsertionEnable = (hevcPicParams->bLastPicInSeq || hevcPicParams->bLastPicInStream) && hevcSliceState->bLastSlice; cmd.DW7.SlicedataEnable = 1; cmd.DW8.IndirectPakBseDataStartOffsetWrite = hevcSliceState->dwHeaderBytesInserted; MHW_MI_CHK_STATUS(Mhw_AddCommandCmdOrBB(cmdBuffer, hevcSliceState->pBatchBufferForPakSlices, &cmd, cmd.byteSize)); return eStatus; } MOS_STATUS AddHcpPakInsertObject( PMOS_COMMAND_BUFFER cmdBuffer, PMHW_VDBOX_PAK_INSERT_PARAMS params) { MOS_STATUS eStatus = MOS_STATUS_SUCCESS; MHW_FUNCTION_ENTER; MHW_MI_CHK_NULL(params); if (cmdBuffer == nullptr && params->pBatchBufferForPakSlices == nullptr) { MHW_ASSERTMESSAGE("There was no valid buffer to add the HW command to."); } typename THcpCmds::HCP_PAK_INSERT_OBJECT_CMD cmd; uint32_t dwordsUsed = cmd.dwSize; if (params->bLastPicInSeq && params->bLastPicInStream) { uint32_t dwPadding[3]; dwordsUsed += sizeof(dwPadding) / sizeof(dwPadding[0]); cmd.DW0.DwordLength = OP_LENGTH(dwordsUsed); cmd.DW1.Headerlengthexcludefrmsize = 0; cmd.DW1.EndofsliceflagLastdstdatainsertcommandflag = 1; cmd.DW1.LastheaderflagLastsrcheaderdatainsertcommandflag = 1; cmd.DW1.EmulationflagEmulationbytebitsinsertenable = 0; cmd.DW1.SkipemulbytecntSkipEmulationByteCount = 0; cmd.DW1.DatabitsinlastdwSrcdataendingbitinclusion50 = 16; cmd.DW1.DatabyteoffsetSrcdatastartingbyteoffset10 = 0; cmd.DW1.IndirectPayloadEnable = 0; MHW_MI_CHK_STATUS(Mhw_AddCommandCmdOrBB(cmdBuffer, params->pBatchBufferForPakSlices, &cmd, cmd.byteSize)); dwPadding[0] = (uint32_t)((1 << 16) | ((HEVC_NAL_UT_EOS << 1) << 24)); dwPadding[1] = (1L | (1L << 24)); dwPadding[2] = (HEVC_NAL_UT_EOB << 1) | (1L << 8); MHW_MI_CHK_STATUS(Mhw_AddCommandCmdOrBB(cmdBuffer, params->pBatchBufferForPakSlices, &dwPadding[0], sizeof(dwPadding))); } else if (params->bLastPicInSeq || params->bLastPicInStream) { uint32_t dwLastPicInSeqData[2], dwLastPicInStreamData[2]; dwordsUsed += params->bLastPicInSeq * 2 + params->bLastPicInStream * 2; cmd.DW0.DwordLength = OP_LENGTH(dwordsUsed); cmd.DW1.Headerlengthexcludefrmsize = 0; cmd.DW1.EndofsliceflagLastdstdatainsertcommandflag = 1; cmd.DW1.LastheaderflagLastsrcheaderdatainsertcommandflag = 1; cmd.DW1.EmulationflagEmulationbytebitsinsertenable = 0; cmd.DW1.SkipemulbytecntSkipEmulationByteCount = 0; cmd.DW1.DatabitsinlastdwSrcdataendingbitinclusion50 = 8; cmd.DW1.DatabyteoffsetSrcdatastartingbyteoffset10 = 0; cmd.DW1.IndirectPayloadEnable = 0; MHW_MI_CHK_STATUS(Mhw_AddCommandCmdOrBB(cmdBuffer, params->pBatchBufferForPakSlices, &cmd, cmd.byteSize)); if (params->bLastPicInSeq) { dwLastPicInSeqData[0] = (uint32_t)((1 << 16) | ((HEVC_NAL_UT_EOS << 1) << 24)); dwLastPicInSeqData[1] = 1; // nuh_temporal_id_plus1 MHW_MI_CHK_STATUS(Mhw_AddCommandCmdOrBB(cmdBuffer, params->pBatchBufferForPakSlices, &dwLastPicInSeqData[0], sizeof(dwLastPicInSeqData))); } if (params->bLastPicInStream) { dwLastPicInStreamData[0] = (uint32_t)((1 << 16) | ((HEVC_NAL_UT_EOB << 1) << 24)); dwLastPicInStreamData[1] = 1; // nuh_temporal_id_plus1 MHW_MI_CHK_STATUS(Mhw_AddCommandCmdOrBB(cmdBuffer, params->pBatchBufferForPakSlices, &dwLastPicInStreamData[0], sizeof(dwLastPicInStreamData))); } } else { uint32_t byteSize = (params->dwBitSize + 7) >> 3; uint32_t dataBitsInLastDw = params->dwBitSize % 32; if (dataBitsInLastDw == 0) { dataBitsInLastDw = 32; } dwordsUsed += (MOS_ALIGN_CEIL(byteSize, sizeof(uint32_t))) / sizeof(uint32_t); cmd.DW0.DwordLength = OP_LENGTH(dwordsUsed); cmd.DW1.Headerlengthexcludefrmsize = 0; cmd.DW1.EndofsliceflagLastdstdatainsertcommandflag = params->bEndOfSlice; cmd.DW1.LastheaderflagLastsrcheaderdatainsertcommandflag = params->bLastHeader; cmd.DW1.EmulationflagEmulationbytebitsinsertenable = params->bEmulationByteBitsInsert; cmd.DW1.SkipemulbytecntSkipEmulationByteCount = params->uiSkipEmulationCheckCount; cmd.DW1.DatabitsinlastdwSrcdataendingbitinclusion50 = dataBitsInLastDw; cmd.DW1.DatabyteoffsetSrcdatastartingbyteoffset10 = 0; cmd.DW1.IndirectPayloadEnable = 0; MHW_MI_CHK_STATUS(Mhw_AddCommandCmdOrBB(cmdBuffer, params->pBatchBufferForPakSlices, &cmd, cmd.byteSize)); if (byteSize) { MHW_MI_CHK_NULL(params->pBsBuffer); MHW_MI_CHK_NULL(params->pBsBuffer->pBase); uint8_t *data = (uint8_t*)(params->pBsBuffer->pBase + params->dwOffset); MHW_MI_CHK_STATUS(Mhw_AddCommandCmdOrBB(cmdBuffer, params->pBatchBufferForPakSlices, data, byteSize)); } } return eStatus; } MOS_STATUS AddHcpHevcPicBrcBuffer( PMOS_RESOURCE hcpImgStates, PMHW_VDBOX_HEVC_PIC_STATE hevcPicState) { MOS_STATUS eStatus = MOS_STATUS_SUCCESS; MHW_FUNCTION_ENTER; MHW_MI_CHK_NULL(hcpImgStates); MOS_COMMAND_BUFFER constructedCmdBuf; typename THcpCmds::HCP_PIC_STATE_CMD cmd; uint32_t* insertion = nullptr; MOS_LOCK_PARAMS lockFlags; this->m_brcNumPakPasses = hevcPicState->brcNumPakPasses; MOS_ZeroMemory(&lockFlags, sizeof(MOS_LOCK_PARAMS)); lockFlags.WriteOnly = 1; uint8_t *data = (uint8_t*)this->m_osInterface->pfnLockResource(this->m_osInterface, hcpImgStates, &lockFlags); MHW_MI_CHK_NULL(data); constructedCmdBuf.pCmdBase = (uint32_t *)data; constructedCmdBuf.pCmdPtr = (uint32_t *)data; constructedCmdBuf.iOffset = 0; constructedCmdBuf.iRemaining = BRC_IMG_STATE_SIZE_PER_PASS * (this->m_brcNumPakPasses); MHW_MI_CHK_STATUS(this->AddHcpPicStateCmd(&constructedCmdBuf, hevcPicState)); cmd = *(typename THcpCmds::HCP_PIC_STATE_CMD *)data; for (uint32_t i = 0; i < this->m_brcNumPakPasses; i++) { if (i == 0) { cmd.DW6.Nonfirstpassflag = false; } else { cmd.DW6.Nonfirstpassflag = true; } cmd.DW6.FrameszoverstatusenFramebitratemaxreportmask = true; cmd.DW6.FrameszunderstatusenFramebitrateminreportmask = true; cmd.DW6.LcumaxbitstatusenLcumaxsizereportmask = false; // BRC update kernel does not consider if there is any LCU whose size is too big *(typename THcpCmds::HCP_PIC_STATE_CMD *)data = cmd; /* add batch buffer end insertion flag */ insertion = (uint32_t*)(data + THcpCmds::HCP_PIC_STATE_CMD::byteSize); *insertion = 0x05000000; data += BRC_IMG_STATE_SIZE_PER_PASS; } MHW_MI_CHK_STATUS(this->m_osInterface->pfnUnlockResource(this->m_osInterface, hcpImgStates)); return eStatus; } MOS_STATUS GetOsResLaceOrAceOrRgbHistogramBufferSize( uint32_t width, uint32_t height, uint32_t *size) { MOS_STATUS eStatus = MOS_STATUS_SUCCESS; *size = this->m_veboxRgbHistogramSize; uint32_t sizeLace = MOS_ROUNDUP_DIVIDE(height, 64) * MOS_ROUNDUP_DIVIDE(width, 64) * this->m_veboxLaceHistogram256BinPerBlock; uint32_t sizeNoLace = m_veboxAceHistogramSizePerFramePerSlice * this->m_veboxNumFramePreviousCurrent * this->m_veboxMaxSlices; *size += MOS_MAX(sizeLace, sizeNoLace); return eStatus; } MOS_STATUS GetOsResStatisticsOutputBufferSize( uint32_t width, uint32_t height, uint32_t *size) { MOS_STATUS eStatus = MOS_STATUS_SUCCESS; width = MOS_ALIGN_CEIL(width, 64); height = MOS_ROUNDUP_DIVIDE(height, 4) + MOS_ROUNDUP_DIVIDE(this->m_veboxStatisticsSize * sizeof(uint32_t), width); *size = width * height; return eStatus; } public: inline uint32_t GetHcpHevcVp9RdoqStateCommandSize() { return THcpCmds::HEVC_VP9_RDOQ_STATE_CMD::byteSize; } }; #endif
41.809007
167
0.609456
[ "object", "vector" ]
11ceb4da14fbe9f8ac34de8ffb757737a70b88a2
2,620
h
C
stratum/hal/lib/phal/tai/tai_wrapper/tai_wrapper.h
maksym-tropets-plvision/stratum
468654ab29050ba6d20a3da146d9c192b1f66b36
[ "Apache-2.0" ]
null
null
null
stratum/hal/lib/phal/tai/tai_wrapper/tai_wrapper.h
maksym-tropets-plvision/stratum
468654ab29050ba6d20a3da146d9c192b1f66b36
[ "Apache-2.0" ]
null
null
null
stratum/hal/lib/phal/tai/tai_wrapper/tai_wrapper.h
maksym-tropets-plvision/stratum
468654ab29050ba6d20a3da146d9c192b1f66b36
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2018 Google LLC * Copyright 2018-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef STRATUM_HAL_LIB_PHAL_TAI_TAI_WRAPPER_TAI_WRAPPER_H_ #define STRATUM_HAL_LIB_PHAL_TAI_TAI_WRAPPER_TAI_WRAPPER_H_ #include <string> #include <vector> #include <utility> #include <memory> #include <thread> // NOLINT(build/c++11) #include "stratum/hal/lib/phal/tai/tai_wrapper/tai_object.h" #include "stratum/hal/lib/phal/tai/tai_wrapper/tai_wrapper_interface.h" namespace stratum { namespace hal { namespace phal { namespace tai { /*! * \brief The TAIWrapper class wrap c TAI lib with c++ layer and give access * for TAI attributes through TAI interface objects (like Module, HostInterface * or NetworkInterface) */ class TAIWrapper : public TAIWrapperInterface { public: TAIWrapper(); ~TAIWrapper() override; std::weak_ptr<Module> GetModule(std::size_t index) const override; std::weak_ptr<TAIObject> GetObject(const TAIPath& objectPath) const override; std::weak_ptr<TAIObject> GetObject( const TAIPathItem& pathItem) const override; std::weak_ptr<Module> GetModuleByLocation(const std::string& location) const; bool IsObjectValid(const TAIPath& path) const override { return !GetObject(path).expired(); } bool IsModuleIdValid(std::size_t id) const override { return modules_.size() > id; } void ModulePresenceHandler(); private: tai_status_t CreateModule(const std::string& location); private: std::vector<std::shared_ptr<Module>> modules_; tai_api_method_table_t api_; TAIPathValidator path_rule_; // thread stops if this value will be set to false. std::atomic<bool> thread_running_{true}; // identify is TAI API initilized. std::atomic<bool> api_initialized_{false}; // TAI module presence monitoring thread for plug/unplug processing. std::thread presence_monitoring_thread_; mutable std::mutex data_mux_; }; /* class TAIWrapper */ } // namespace tai } // namespace phal } // namespace hal } // namespace stratum #endif // STRATUM_HAL_LIB_PHAL_TAI_TAI_WRAPPER_TAI_WRAPPER_H_
31.190476
79
0.754198
[ "vector" ]
11d1c0f0529bbb7aff1145e0a06a9946110effa9
95,776
c
C
source/blender/editors/uvedit/uvedit_ops.c
wycivil08/blendocv
f6cce83e1f149fef39afa8043aade9c64378f33e
[ "Unlicense" ]
30
2015-01-29T14:06:05.000Z
2022-01-10T07:47:29.000Z
source/blender/editors/uvedit/uvedit_ops.c
ttagu99/blendocv
f6cce83e1f149fef39afa8043aade9c64378f33e
[ "Unlicense" ]
1
2017-02-20T20:57:48.000Z
2018-12-19T23:44:38.000Z
source/blender/editors/uvedit/uvedit_ops.c
ttagu99/blendocv
f6cce83e1f149fef39afa8043aade9c64378f33e
[ "Unlicense" ]
15
2015-04-23T02:38:36.000Z
2021-03-01T20:09:39.000Z
/* * $Id: uvedit_ops.c 40455 2011-09-22 14:42:29Z campbellbarton $ * * ***** BEGIN GPL LICENSE BLOCK ***** * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * * The Original Code is Copyright (C) 2001-2002 by NaN Holding BV. * All rights reserved. * * The Original Code is: all of this file. * * Contributor(s): none yet. * * ***** END GPL LICENSE BLOCK ***** */ /** \file blender/editors/uvedit/uvedit_ops.c * \ingroup eduv */ #include <stdlib.h> #include <string.h> #include <math.h> #include "MEM_guardedalloc.h" #include "DNA_object_types.h" #include "DNA_meshdata_types.h" #include "DNA_scene_types.h" #include "BLI_math.h" #include "BLI_blenlib.h" #include "BLI_editVert.h" #include "BLI_utildefines.h" #include "BKE_context.h" #include "BKE_customdata.h" #include "BKE_depsgraph.h" #include "BKE_image.h" #include "BKE_library.h" #include "BKE_mesh.h" #include "BKE_report.h" #include "ED_image.h" #include "ED_mesh.h" #include "ED_uvedit.h" #include "ED_object.h" #include "ED_screen.h" #include "ED_transform.h" #include "RNA_access.h" #include "RNA_define.h" #include "WM_api.h" #include "WM_types.h" #include "UI_view2d.h" #include "uvedit_intern.h" /************************* state testing ************************/ int ED_uvedit_test(Object *obedit) { EditMesh *em; int ret; if(!obedit || obedit->type != OB_MESH) return 0; em = BKE_mesh_get_editmesh(obedit->data); ret = EM_texFaceCheck(em); BKE_mesh_end_editmesh(obedit->data, em); return ret; } /************************* assign image ************************/ void ED_uvedit_assign_image(Scene *scene, Object *obedit, Image *ima, Image *previma) { EditMesh *em; EditFace *efa; MTFace *tf; int update= 0; /* skip assigning these procedural images... */ if(ima && (ima->type==IMA_TYPE_R_RESULT || ima->type==IMA_TYPE_COMPOSITE)) return; /* verify we have a mesh we can work with */ if(!obedit || (obedit->type != OB_MESH)) return; em= BKE_mesh_get_editmesh(((Mesh*)obedit->data)); if(!em || !em->faces.first) { BKE_mesh_end_editmesh(obedit->data, em); return; } /* ensure we have a uv layer */ if(!CustomData_has_layer(&em->fdata, CD_MTFACE)) { EM_add_data_layer(em, &em->fdata, CD_MTFACE, NULL); update= 1; } /* now assign to all visible faces */ for(efa= em->faces.first; efa; efa= efa->next) { tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_face_visible(scene, previma, efa, tf)) { if(ima) { tf->tpage= ima; if(ima->id.us==0) id_us_plus(&ima->id); else id_lib_extern(&ima->id); } else { tf->tpage= NULL; } update = 1; } } /* and update depdency graph */ if(update) DAG_id_tag_update(obedit->data, 0); BKE_mesh_end_editmesh(obedit->data, em); } /* dotile - 1, set the tile flag (from the space image) * 2, set the tile index for the faces. */ static int uvedit_set_tile(Object *obedit, Image *ima, int curtile) { EditMesh *em; EditFace *efa; MTFace *tf; /* verify if we have something to do */ if(!ima || !ED_uvedit_test(obedit)) return 0; if((ima->tpageflag & IMA_TILES) == 0) return 0; /* skip assigning these procedural images... */ if(ima->type==IMA_TYPE_R_RESULT || ima->type==IMA_TYPE_COMPOSITE) return 0; em= BKE_mesh_get_editmesh((Mesh*)obedit->data); for(efa= em->faces.first; efa; efa= efa->next) { tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(efa->h==0 && efa->f & SELECT) tf->tile= curtile; /* set tile index */ } DAG_id_tag_update(obedit->data, 0); BKE_mesh_end_editmesh(obedit->data, em); return 1; } /*********************** space conversion *********************/ static void uvedit_pixel_to_float(SpaceImage *sima, float *dist, float pixeldist) { int width, height; if(sima) { ED_space_image_size(sima, &width, &height); } else { width= 256; height= 256; } dist[0]= pixeldist/width; dist[1]= pixeldist/height; } /*************** visibility and selection utilities **************/ int uvedit_face_visible_nolocal(Scene *scene, EditFace *efa) { ToolSettings *ts= scene->toolsettings; if(ts->uv_flag & UV_SYNC_SELECTION) return (efa->h==0); else return (efa->h==0 && (efa->f & SELECT)); } int uvedit_face_visible(Scene *scene, Image *ima, EditFace *efa, MTFace *tf) { ToolSettings *ts= scene->toolsettings; if(ts->uv_flag & UV_SHOW_SAME_IMAGE) return (tf->tpage==ima)? uvedit_face_visible_nolocal(scene, efa): 0; else return uvedit_face_visible_nolocal(scene, efa); } int uvedit_face_selected(Scene *scene, EditFace *efa, MTFace *tf) { ToolSettings *ts= scene->toolsettings; if(ts->uv_flag & UV_SYNC_SELECTION) return (efa->f & SELECT); else return (!(~tf->flag & (TF_SEL1|TF_SEL2|TF_SEL3)) &&(!efa->v4 || tf->flag & TF_SEL4)); } void uvedit_face_select(Scene *scene, EditFace *efa, MTFace *tf) { ToolSettings *ts= scene->toolsettings; if(ts->uv_flag & UV_SYNC_SELECTION) EM_select_face(efa, 1); else tf->flag |= (TF_SEL1|TF_SEL2|TF_SEL3|TF_SEL4); } void uvedit_face_deselect(Scene *scene, EditFace *efa, MTFace *tf) { ToolSettings *ts= scene->toolsettings; if(ts->uv_flag & UV_SYNC_SELECTION) EM_select_face(efa, 0); else tf->flag &= ~(TF_SEL1|TF_SEL2|TF_SEL3|TF_SEL4); } int uvedit_edge_selected(Scene *scene, EditFace *efa, MTFace *tf, int i) { ToolSettings *ts= scene->toolsettings; int nvert= (efa->v4)? 4: 3; if(ts->uv_flag & UV_SYNC_SELECTION) { if(ts->selectmode & SCE_SELECT_FACE) return (efa->f & SELECT); else if(ts->selectmode & SCE_SELECT_EDGE) return (*(&efa->e1 + i))->f & SELECT; else return (((efa->v1 + i)->f & SELECT) && ((efa->v1 + (i+1)%nvert)->f & SELECT)); } else return (tf->flag & TF_SEL_MASK(i)) && (tf->flag & TF_SEL_MASK((i+1)%nvert)); } void uvedit_edge_select(Scene *scene, EditFace *efa, MTFace *tf, int i) { ToolSettings *ts= scene->toolsettings; int nvert= (efa->v4)? 4: 3; if(ts->uv_flag & UV_SYNC_SELECTION) { if(ts->selectmode & SCE_SELECT_FACE) EM_select_face(efa, 1); else if(ts->selectmode & SCE_SELECT_EDGE) EM_select_edge((*(&efa->e1 + i)), 1); else { (efa->v1 + i)->f |= SELECT; (efa->v1 + (i+1)%nvert)->f |= SELECT; } } else tf->flag |= TF_SEL_MASK(i)|TF_SEL_MASK((i+1)%nvert); } void uvedit_edge_deselect(Scene *scene, EditFace *efa, MTFace *tf, int i) { ToolSettings *ts= scene->toolsettings; int nvert= (efa->v4)? 4: 3; if(ts->uv_flag & UV_SYNC_SELECTION) { if(ts->selectmode & SCE_SELECT_FACE) EM_select_face(efa, 0); else if(ts->selectmode & SCE_SELECT_EDGE) EM_select_edge((*(&efa->e1 + i)), 0); else { (efa->v1 + i)->f &= ~SELECT; (efa->v1 + (i+1)%nvert)->f &= ~SELECT; } } else tf->flag &= ~(TF_SEL_MASK(i)|TF_SEL_MASK((i+1)%nvert)); } int uvedit_uv_selected(Scene *scene, EditFace *efa, MTFace *tf, int i) { ToolSettings *ts= scene->toolsettings; if(ts->uv_flag & UV_SYNC_SELECTION) { if(ts->selectmode & SCE_SELECT_FACE) return (efa->f & SELECT); else return (*(&efa->v1 + i))->f & SELECT; } else return tf->flag & TF_SEL_MASK(i); } void uvedit_uv_select(Scene *scene, EditFace *efa, MTFace *tf, int i) { ToolSettings *ts= scene->toolsettings; if(ts->uv_flag & UV_SYNC_SELECTION) { if(ts->selectmode & SCE_SELECT_FACE) EM_select_face(efa, 1); else (*(&efa->v1 + i))->f |= SELECT; } else tf->flag |= TF_SEL_MASK(i); } void uvedit_uv_deselect(Scene *scene, EditFace *efa, MTFace *tf, int i) { ToolSettings *ts= scene->toolsettings; if(ts->uv_flag & UV_SYNC_SELECTION) { if(ts->selectmode & SCE_SELECT_FACE) EM_select_face(efa, 0); else (*(&efa->v1 + i))->f &= ~SELECT; } else tf->flag &= ~TF_SEL_MASK(i); } /*********************** live unwrap utilities ***********************/ static void uvedit_live_unwrap_update(SpaceImage *sima, Scene *scene, Object *obedit) { if(sima && (sima->flag & SI_LIVE_UNWRAP)) { ED_uvedit_live_unwrap_begin(scene, obedit); ED_uvedit_live_unwrap_re_solve(); ED_uvedit_live_unwrap_end(0); } } /*********************** geometric utilities ***********************/ void uv_center(float uv[][2], float cent[2], int quad) { if(quad) { cent[0] = (uv[0][0] + uv[1][0] + uv[2][0] + uv[3][0]) / 4.0f; cent[1] = (uv[0][1] + uv[1][1] + uv[2][1] + uv[3][1]) / 4.0f; } else { cent[0] = (uv[0][0] + uv[1][0] + uv[2][0]) / 3.0f; cent[1] = (uv[0][1] + uv[1][1] + uv[2][1]) / 3.0f; } } float uv_area(float uv[][2], int quad) { if(quad) return area_tri_v2(uv[0], uv[1], uv[2]) + area_tri_v2(uv[0], uv[2], uv[3]); else return area_tri_v2(uv[0], uv[1], uv[2]); } void uv_copy_aspect(float uv_orig[][2], float uv[][2], float aspx, float aspy) { uv[0][0] = uv_orig[0][0]*aspx; uv[0][1] = uv_orig[0][1]*aspy; uv[1][0] = uv_orig[1][0]*aspx; uv[1][1] = uv_orig[1][1]*aspy; uv[2][0] = uv_orig[2][0]*aspx; uv[2][1] = uv_orig[2][1]*aspy; uv[3][0] = uv_orig[3][0]*aspx; uv[3][1] = uv_orig[3][1]*aspy; } int ED_uvedit_minmax(Scene *scene, Image *ima, Object *obedit, float *min, float *max) { EditMesh *em= BKE_mesh_get_editmesh((Mesh*)obedit->data); EditFace *efa; MTFace *tf; int sel; INIT_MINMAX2(min, max); sel= 0; for(efa= em->faces.first; efa; efa= efa->next) { tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_face_visible(scene, ima, efa, tf)) { if(uvedit_uv_selected(scene, efa, tf, 0)) { DO_MINMAX2(tf->uv[0], min, max); sel = 1; } if(uvedit_uv_selected(scene, efa, tf, 1)) { DO_MINMAX2(tf->uv[1], min, max); sel = 1; } if(uvedit_uv_selected(scene, efa, tf, 2)) { DO_MINMAX2(tf->uv[2], min, max); sel = 1; } if(efa->v4 && (uvedit_uv_selected(scene, efa, tf, 3))) { DO_MINMAX2(tf->uv[3], min, max); sel = 1; } } } BKE_mesh_end_editmesh(obedit->data, em); return sel; } static int ED_uvedit_median(Scene *scene, Image *ima, Object *obedit, float co[3]) { EditMesh *em= BKE_mesh_get_editmesh((Mesh*)obedit->data); EditFace *efa; MTFace *tf; unsigned int sel= 0; zero_v3(co); for(efa= em->faces.first; efa; efa= efa->next) { tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_face_visible(scene, ima, efa, tf)) { if(uvedit_uv_selected(scene, efa, tf, 0)) { add_v3_v3(co, tf->uv[0]); sel++; } if(uvedit_uv_selected(scene, efa, tf, 1)) { add_v3_v3(co, tf->uv[1]); sel++; } if(uvedit_uv_selected(scene, efa, tf, 2)) { add_v3_v3(co, tf->uv[2]); sel++; } if(efa->v4 && (uvedit_uv_selected(scene, efa, tf, 3))) { add_v3_v3(co, tf->uv[3]); sel++; } } } mul_v3_fl(co, 1.0f/(float)sel); BKE_mesh_end_editmesh(obedit->data, em); return (sel != 0); } static int uvedit_center(Scene *scene, Image *ima, Object *obedit, float *cent, char mode) { EditMesh *em= BKE_mesh_get_editmesh((Mesh*)obedit->data); float min[2], max[2]; int change= 0; if(mode==V3D_CENTER) { /* bounding box */ if(ED_uvedit_minmax(scene, ima, obedit, min, max)) { change = 1; cent[0]= (min[0]+max[0])/2.0f; cent[1]= (min[1]+max[1])/2.0f; } } else { if(ED_uvedit_median(scene, ima, obedit, cent)) { change = 1; } } if(change) { BKE_mesh_end_editmesh(obedit->data, em); return 1; } BKE_mesh_end_editmesh(obedit->data, em); return 0; } /************************** find nearest ****************************/ typedef struct NearestHit { EditFace *efa; MTFace *tf; int vert, uv; int edge, vert2; } NearestHit; static void find_nearest_uv_edge(Scene *scene, Image *ima, EditMesh *em, float co[2], NearestHit *hit) { MTFace *tf; EditFace *efa; EditVert *eve; float mindist, dist; int i, nverts; mindist= 1e10f; memset(hit, 0, sizeof(*hit)); for(i=0, eve=em->verts.first; eve; eve=eve->next, i++) eve->tmp.l = i; for(efa= em->faces.first; efa; efa= efa->next) { tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_face_visible(scene, ima, efa, tf)) { nverts= efa->v4? 4: 3; for(i=0; i<nverts; i++) { dist= dist_to_line_segment_v2(co, tf->uv[i], tf->uv[(i+1)%nverts]); if(dist < mindist) { hit->tf= tf; hit->efa= efa; hit->edge= i; mindist= dist; hit->vert= (*(&efa->v1 + i))->tmp.l; hit->vert2= (*(&efa->v1 + ((i+1)%nverts)))->tmp.l; } } } } } static void find_nearest_uv_face(Scene *scene, Image *ima, EditMesh *em, float co[2], NearestHit *hit) { MTFace *tf; EditFace *efa; float mindist, dist, cent[2]; int i, nverts; mindist= 1e10f; memset(hit, 0, sizeof(*hit)); for(efa= em->faces.first; efa; efa= efa->next) { tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_face_visible(scene, ima, efa, tf)) { nverts= efa->v4? 4: 3; cent[0]= cent[1]= 0.0f; for(i=0; i<nverts; i++) { cent[0] += tf->uv[i][0]; cent[1] += tf->uv[i][1]; } cent[0] /= nverts; cent[1] /= nverts; dist= fabs(co[0]- cent[0]) + fabs(co[1]- cent[1]); if(dist < mindist) { hit->tf= tf; hit->efa= efa; mindist= dist; } } } } static int nearest_uv_between(MTFace *tf, int nverts, int id, float co[2], float uv[2]) { float m[3], v1[3], v2[3], c1, c2; int id1, id2; id1= (id+nverts-1)%nverts; id2= (id+nverts+1)%nverts; m[0]= co[0]-uv[0]; m[1]= co[1]-uv[1]; sub_v2_v2v2(v1, tf->uv[id1], tf->uv[id]); sub_v2_v2v2(v2, tf->uv[id2], tf->uv[id]); /* m and v2 on same side of v-v1? */ c1= v1[0]*m[1] - v1[1]*m[0]; c2= v1[0]*v2[1] - v1[1]*v2[0]; if(c1*c2 < 0.0f) return 0; /* m and v1 on same side of v-v2? */ c1= v2[0]*m[1] - v2[1]*m[0]; c2= v2[0]*v1[1] - v2[1]*v1[0]; return (c1*c2 >= 0.0f); } static void find_nearest_uv_vert(Scene *scene, Image *ima, EditMesh *em, float co[2], float penalty[2], NearestHit *hit) { EditFace *efa; EditVert *eve; MTFace *tf; float mindist, dist; int i, nverts; mindist= 1e10f; memset(hit, 0, sizeof(*hit)); for(i=0, eve=em->verts.first; eve; eve=eve->next, i++) eve->tmp.l = i; for(efa= em->faces.first; efa; efa= efa->next) { tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_face_visible(scene, ima, efa, tf)) { nverts= efa->v4? 4: 3; for(i=0; i<nverts; i++) { if(penalty && uvedit_uv_selected(scene, efa, tf, i)) dist= fabsf(co[0]-tf->uv[i][0])+penalty[0] + fabsf(co[1]-tf->uv[i][1]) + penalty[1]; else dist= fabsf(co[0]-tf->uv[i][0]) + fabsf(co[1]-tf->uv[i][1]); if(dist<=mindist) { if(dist==mindist) if(!nearest_uv_between(tf, nverts, i, co, tf->uv[i])) continue; mindist= dist; hit->uv= i; hit->tf= tf; hit->efa= efa; hit->vert= (*(&efa->v1 + i))->tmp.l; } } } } } int ED_uvedit_nearest_uv(Scene *scene, Object *obedit, Image *ima, float co[2], float uv[2]) { EditMesh *em= BKE_mesh_get_editmesh((Mesh*)obedit->data); EditFace *efa; MTFace *tf; float mindist, dist; int i, nverts, found= 0; mindist= 1e10f; uv[0]= co[0]; uv[1]= co[1]; for(efa= em->faces.first; efa; efa= efa->next) { tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_face_visible(scene, ima, efa, tf)) { nverts= efa->v4? 4: 3; for(i=0; i<nverts; i++) { if(uvedit_uv_selected(scene, efa, tf, i)) continue; dist= fabs(co[0]-tf->uv[i][0]) + fabs(co[1]-tf->uv[i][1]); if(dist<=mindist) { mindist= dist; uv[0]= tf->uv[i][0]; uv[1]= tf->uv[i][1]; found= 1; } } } } BKE_mesh_end_editmesh(obedit->data, em); return found; } /*********************** loop select ***********************/ static void uv_vertex_loop_flag(UvMapVert *first) { UvMapVert *iterv; int count= 0; for(iterv=first; iterv; iterv=iterv->next) { if(iterv->separate && iterv!=first) break; count++; } if(count < 5) first->flag= 1; } static UvMapVert *uv_vertex_map_get(UvVertMap *vmap, EditFace *efa, int a) { UvMapVert *iterv, *first; first= EM_get_uv_map_vert(vmap, (*(&efa->v1 + a))->tmp.l); for(iterv=first; iterv; iterv=iterv->next) { if(iterv->separate) first= iterv; if(iterv->f == efa->tmp.l) return first; } return NULL; } static int uv_edge_tag_faces(UvMapVert *first1, UvMapVert *first2, int *totface) { UvMapVert *iterv1, *iterv2; EditFace *efa; int tot = 0; /* count number of faces this edge has */ for(iterv1=first1; iterv1; iterv1=iterv1->next) { if(iterv1->separate && iterv1 != first1) break; for(iterv2=first2; iterv2; iterv2=iterv2->next) { if(iterv2->separate && iterv2 != first2) break; if(iterv1->f == iterv2->f) { /* if face already tagged, don't do this edge */ efa= EM_get_face_for_index(iterv1->f); if(efa->f1) return 0; tot++; break; } } } if(*totface == 0) /* start edge */ *totface= tot; else if(tot != *totface) /* check for same number of faces as start edge */ return 0; /* tag the faces */ for(iterv1=first1; iterv1; iterv1=iterv1->next) { if(iterv1->separate && iterv1 != first1) break; for(iterv2=first2; iterv2; iterv2=iterv2->next) { if(iterv2->separate && iterv2 != first2) break; if(iterv1->f == iterv2->f) { efa= EM_get_face_for_index(iterv1->f); efa->f1= 1; break; } } } return 1; } static int select_edgeloop(Scene *scene, Image *ima, EditMesh *em, NearestHit *hit, float limit[2], int extend) { EditVert *eve; EditFace *efa; MTFace *tf; UvVertMap *vmap; UvMapVert *iterv1, *iterv2; int a, count, looking, nverts, starttotf, select; /* setup */ EM_init_index_arrays(em, 0, 0, 1); vmap= EM_make_uv_vert_map(em, 0, 0, limit); for(count=0, eve=em->verts.first; eve; count++, eve= eve->next) eve->tmp.l = count; for(count=0, efa= em->faces.first; efa; count++, efa= efa->next) { if(!extend) { tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); uvedit_face_deselect(scene, efa, tf); } efa->tmp.l= count; efa->f1= 0; } /* set flags for first face and verts */ nverts= (hit->efa->v4)? 4: 3; iterv1= uv_vertex_map_get(vmap, hit->efa, hit->edge); iterv2= uv_vertex_map_get(vmap, hit->efa, (hit->edge+1)%nverts); uv_vertex_loop_flag(iterv1); uv_vertex_loop_flag(iterv2); starttotf= 0; uv_edge_tag_faces(iterv1, iterv2, &starttotf); /* sorry, first edge isnt even ok */ if(iterv1->flag==0 && iterv2->flag==0) looking= 0; else looking= 1; /* iterate */ while(looking) { looking= 0; /* find correct valence edges which are not tagged yet, but connect to tagged one */ for(efa= em->faces.first; efa; efa=efa->next) { tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(!efa->f1 && uvedit_face_visible(scene, ima, efa, tf)) { nverts= (efa->v4)? 4: 3; for(a=0; a<nverts; a++) { /* check face not hidden and not tagged */ iterv1= uv_vertex_map_get(vmap, efa, a); iterv2= uv_vertex_map_get(vmap, efa, (a+1)%nverts); /* check if vertex is tagged and has right valence */ if(iterv1->flag || iterv2->flag) { if(uv_edge_tag_faces(iterv1, iterv2, &starttotf)) { looking= 1; efa->f1= 1; uv_vertex_loop_flag(iterv1); uv_vertex_loop_flag(iterv2); break; } } } } } } /* do the actual select/deselect */ nverts= (hit->efa->v4)? 4: 3; iterv1= uv_vertex_map_get(vmap, hit->efa, hit->edge); iterv2= uv_vertex_map_get(vmap, hit->efa, (hit->edge+1)%nverts); iterv1->flag= 1; iterv2->flag= 1; if(extend) { tf= CustomData_em_get(&em->fdata, hit->efa->data, CD_MTFACE); if(uvedit_uv_selected(scene, hit->efa, tf, hit->edge)) select= 0; else select= 1; } else select= 1; for(efa= em->faces.first; efa; efa=efa->next) { tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); nverts= (efa->v4)? 4: 3; for(a=0; a<nverts; a++) { iterv1= uv_vertex_map_get(vmap, efa, a); if(iterv1->flag) { if(select) uvedit_uv_select(scene, efa, tf, a); else uvedit_uv_deselect(scene, efa, tf, a); } } } /* cleanup */ EM_free_uv_vert_map(vmap); EM_free_index_arrays(); return (select)? 1: -1; } /*********************** linked select ***********************/ static void select_linked(Scene *scene, Image *ima, EditMesh *em, float limit[2], NearestHit *hit, int extend) { EditFace *efa; MTFace *tf; UvVertMap *vmap; UvMapVert *vlist, *iterv, *startv; int i, nverts, stacksize= 0, *stack; unsigned int a; char *flag; EM_init_index_arrays(em, 0, 0, 1); /* we can use this too */ vmap= EM_make_uv_vert_map(em, 1, 0, limit); if(vmap == NULL) return; stack= MEM_mallocN(sizeof(*stack) * em->totface, "UvLinkStack"); flag= MEM_callocN(sizeof(*flag) * em->totface, "UvLinkFlag"); if(!hit) { for(a=0, efa= em->faces.first; efa; efa= efa->next, a++) { tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_face_visible(scene, ima, efa, tf)) { const char select_flag= efa->v4 ? (TF_SEL1|TF_SEL2|TF_SEL3|TF_SEL4) : (TF_SEL1|TF_SEL2|TF_SEL3); if(tf->flag & select_flag) { stack[stacksize]= a; stacksize++; flag[a]= 1; } } } } else { for(a=0, efa= em->faces.first; efa; efa= efa->next, a++) { if(efa == hit->efa) { stack[stacksize]= a; stacksize++; flag[a]= 1; break; } } } while(stacksize > 0) { stacksize--; a= stack[stacksize]; efa = EM_get_face_for_index(a); nverts= efa->v4? 4: 3; for(i=0; i<nverts; i++) { /* make_uv_vert_map_EM sets verts tmp.l to the indices */ vlist= EM_get_uv_map_vert(vmap, (*(&efa->v1 + i))->tmp.l); startv= vlist; for(iterv=vlist; iterv; iterv=iterv->next) { if(iterv->separate) startv= iterv; if(iterv->f == a) break; } for(iterv=startv; iterv; iterv=iterv->next) { if((startv != iterv) && (iterv->separate)) break; else if(!flag[iterv->f]) { flag[iterv->f]= 1; stack[stacksize]= iterv->f; stacksize++; } } } } if(!extend) { for(a=0, efa= em->faces.first; efa; efa= efa->next, a++) { tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(flag[a]) tf->flag |= (TF_SEL1|TF_SEL2|TF_SEL3|TF_SEL4); else tf->flag &= ~(TF_SEL1|TF_SEL2|TF_SEL3|TF_SEL4); } } else { for(a=0, efa= em->faces.first; efa; efa= efa->next, a++) { if(flag[a]) { const char select_flag= efa->v4 ? (TF_SEL1|TF_SEL2|TF_SEL3|TF_SEL4) : (TF_SEL1|TF_SEL2|TF_SEL3); tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if((tf->flag & select_flag)) break; } } if(efa) { for(a=0, efa= em->faces.first; efa; efa= efa->next, a++) { if(flag[a]) { tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); tf->flag &= ~(TF_SEL1|TF_SEL2|TF_SEL3|TF_SEL4); } } } else { for(a=0, efa= em->faces.first; efa; efa= efa->next, a++) { if(flag[a]) { tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); tf->flag |= (TF_SEL1|TF_SEL2|TF_SEL3|TF_SEL4); } } } } MEM_freeN(stack); MEM_freeN(flag); EM_free_uv_vert_map(vmap); EM_free_index_arrays(); } /* ******************** align operator **************** */ static void weld_align_uv(bContext *C, int tool) { SpaceImage *sima; Scene *scene; Object *obedit; Image *ima; EditMesh *em; EditFace *efa; MTFace *tf; float cent[2], min[2], max[2]; scene= CTX_data_scene(C); obedit= CTX_data_edit_object(C); em= BKE_mesh_get_editmesh((Mesh*)obedit->data); ima= CTX_data_edit_image(C); sima= CTX_wm_space_image(C); INIT_MINMAX2(min, max); if(tool == 'a') { for(efa= em->faces.first; efa; efa= efa->next) { tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_face_visible(scene, ima, efa, tf)) { if(uvedit_uv_selected(scene, efa, tf, 0)) DO_MINMAX2(tf->uv[0], min, max) if(uvedit_uv_selected(scene, efa, tf, 1)) DO_MINMAX2(tf->uv[1], min, max) if(uvedit_uv_selected(scene, efa, tf, 2)) DO_MINMAX2(tf->uv[2], min, max) if(efa->v4 && uvedit_uv_selected(scene, efa, tf, 3)) DO_MINMAX2(tf->uv[3], min, max) } } tool= (max[0]-min[0] >= max[1]-min[1])? 'y': 'x'; } uvedit_center(scene, ima, obedit, cent, 0); if(tool == 'x' || tool == 'w') { for(efa= em->faces.first; efa; efa= efa->next) { tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_face_visible(scene, ima, efa, tf)) { if(uvedit_uv_selected(scene, efa, tf, 0)) tf->uv[0][0]= cent[0]; if(uvedit_uv_selected(scene, efa, tf, 1)) tf->uv[1][0]= cent[0]; if(uvedit_uv_selected(scene, efa, tf, 2)) tf->uv[2][0]= cent[0]; if(efa->v4 && uvedit_uv_selected(scene, efa, tf, 3)) tf->uv[3][0]= cent[0]; } } } if(tool == 'y' || tool == 'w') { for(efa= em->faces.first; efa; efa= efa->next) { tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_face_visible(scene, ima, efa, tf)) { if(uvedit_uv_selected(scene, efa, tf, 0)) tf->uv[0][1]= cent[1]; if(uvedit_uv_selected(scene, efa, tf, 1)) tf->uv[1][1]= cent[1]; if(uvedit_uv_selected(scene, efa, tf, 2)) tf->uv[2][1]= cent[1]; if(efa->v4 && uvedit_uv_selected(scene, efa, tf, 3)) tf->uv[3][1]= cent[1]; } } } if(tool == 's' || tool == 't' || tool == 'u') { /* pass 1&2 variables */ int i, j; int starttmpl= -1, connectedtostarttmpl= -1, startcorner; int endtmpl= -1, connectedtoendtmpl= -1, endcorner; MTFace *startface, *endface; int itmpl, jtmpl; EditVert *eve; int pass; /* first 2 passes find endpoints, 3rd pass moves middle points, 4th pass is fail-on-face-selected */ EditFace *startefa, *endefa= NULL; /* endefa shouldnt need to be initialized but just incase */ /* pass 3 variables */ float startx, starty, firstm, firstb, midx, midy; float endx, endy, secondm, secondb, midmovedx, midmovedy; float IsVertical_check= -1; float IsHorizontal_check= -1; for(i= 0, eve= em->verts.first; eve; eve= eve->next, i++) /* give each point a unique name */ eve->tmp.l= i; for(pass= 1; pass <= 3; pass++) { /* do this for each endpoint */ if(pass == 3){ /* calculate */ startx= startface->uv[startcorner][0]; starty= startface->uv[startcorner][1]; endx= endface->uv[endcorner][0]; endy= endface->uv[endcorner][1]; firstm= (endy-starty)/(endx-startx); firstb= starty-(firstm*startx); secondm= -1.0f/firstm; if(startx == endx) IsVertical_check= startx; if(starty == endy) IsHorizontal_check= starty; } for(efa= em->faces.first; efa; efa= efa->next) { /* for each face */ tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); /* get face */ if(uvedit_face_visible(scene, ima, efa, tf)) { /* if you can see it */ if(uvedit_face_selected(scene, efa, tf)) { /* if the face is selected, get out now! */ pass= 4; break; } for(i= 0; (i < 3 || (i == 3 && efa->v4)); i++) { /* for each point of the face */ itmpl= (*(&efa->v1 + i))->tmp.l; /* get unique name for points */ if(pass == 3) { /* move */ if(uvedit_uv_selected(scene, efa, tf, i)) { if(!(itmpl == starttmpl || itmpl == endtmpl)) { if(IsVertical_check != -1) tf->uv[i][0]= IsVertical_check; if(IsHorizontal_check != -1) tf->uv[i][1]= IsHorizontal_check; if((IsVertical_check == -1) && (IsHorizontal_check == -1)) { midx= tf->uv[i][0]; midy= tf->uv[i][1]; if(tool == 's') { secondb= midy-(secondm*midx); midmovedx= (secondb-firstb)/(firstm-secondm); midmovedy= (secondm*midmovedx)+secondb; tf->uv[i][0]= midmovedx; tf->uv[i][1]= midmovedy; } else if(tool == 't') { tf->uv[i][0]= (midy-firstb)/firstm; /* midmovedx */ } else if(tool == 'u') { tf->uv[i][1]= (firstm*midx)+firstb; /* midmovedy */ } } } } } else { for(j= 0; (j < 3 || (j == 3 && efa->v4)); j++) { /* also for each point on the face */ jtmpl= (*(&efa->v1 + j))->tmp.l; if(i != j && (!efa->v4 || ABS(i-j) != 2)) { /* if the points are connected */ /* quad (0,1,2,3) 0,1 0,3 1,0 1,2 2,1 2,3 3,0 3,2 * triangle (0,1,2) 0,1 0,2 1,0 1,2 2,0 2,1 */ if(uvedit_uv_selected(scene, efa, tf, i) && uvedit_uv_selected(scene, efa, tf, j)) { /* if the edge is selected */ if(pass == 1) { /* if finding first endpoint */ if(starttmpl == -1) { /* if the first endpoint isn't found yet */ starttmpl= itmpl; /* set unique name for endpoint */ connectedtostarttmpl= jtmpl; /* get point that endpoint is connected to */ startface= tf; /* get face it's on */ startcorner= i; /* what corner of the face? */ startefa= efa; efa= em->faces.first; tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); i= -1; break; } if(starttmpl == itmpl && jtmpl != connectedtostarttmpl) { starttmpl= -1; /* not an endpoint */ efa= startefa; tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); i= startcorner; break; } } else if(pass == 2) { /* if finding second endpoint */ if(endtmpl == -1 && itmpl != starttmpl) { endtmpl= itmpl; connectedtoendtmpl= jtmpl; endface= tf; endcorner= i; endefa= efa; efa= em->faces.first; tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); i= -1; break; } if(endtmpl == itmpl && jtmpl != connectedtoendtmpl) { endtmpl= -1; efa= endefa; tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); i= endcorner; break; } } } } } } } } } if(pass == 2 && (starttmpl == -1 || endtmpl == -1)) { /* if endpoints aren't found */ pass=4; } } } uvedit_live_unwrap_update(sima, scene, obedit); DAG_id_tag_update(obedit->data, 0); WM_event_add_notifier(C, NC_GEOM|ND_DATA, obedit->data); BKE_mesh_end_editmesh(obedit->data, em); } static int align_exec(bContext *C, wmOperator *op) { weld_align_uv(C, RNA_enum_get(op->ptr, "axis")); return OPERATOR_FINISHED; } static void UV_OT_align(wmOperatorType *ot) { static EnumPropertyItem axis_items[] = { {'s', "ALIGN_S", 0, "Straighten", "Align UVs along the line defined by the endpoints"}, {'t', "ALIGN_T", 0, "Straighten X", "Align UVs along the line defined by the endpoints along the X axis"}, {'u', "ALIGN_U", 0, "Straighten Y", "Align UVs along the line defined by the endpoints along the Y axis"}, {'a', "ALIGN_AUTO", 0, "Align Auto", "Automatically choose the axis on which there is most alignment already"}, {'x', "ALIGN_X", 0, "Align X", "Align UVs on X axis"}, {'y', "ALIGN_Y", 0, "Align Y", "Align UVs on Y axis"}, {0, NULL, 0, NULL, NULL}}; /* identifiers */ ot->name= "Align"; ot->description= "Align selected UV vertices to an axis"; ot->idname= "UV_OT_align"; ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; /* api callbacks */ ot->exec= align_exec; ot->poll= ED_operator_image_active; /* requires space image */; /* properties */ RNA_def_enum(ot->srna, "axis", axis_items, 'a', "Axis", "Axis to align UV locations on"); } /* ******************** weld operator **************** */ static int weld_exec(bContext *C, wmOperator *UNUSED(op)) { weld_align_uv(C, 'w'); return OPERATOR_FINISHED; } static void UV_OT_weld(wmOperatorType *ot) { /* identifiers */ ot->name= "Weld"; ot->description= "Weld selected UV vertices together"; ot->idname= "UV_OT_weld"; ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; /* api callbacks */ ot->exec= weld_exec; ot->poll= ED_operator_uvedit; } /* ******************** stitch operator **************** */ /* just for averaging UVs */ typedef struct UVVertAverage { float uv[2]; int count; } UVVertAverage; static int stitch_exec(bContext *C, wmOperator *op) { SpaceImage *sima; Scene *scene; Object *obedit; EditMesh *em; EditFace *efa; EditVert *eve; Image *ima; MTFace *tf; scene= CTX_data_scene(C); obedit= CTX_data_edit_object(C); em= BKE_mesh_get_editmesh((Mesh*)obedit->data); ima= CTX_data_edit_image(C); sima= CTX_wm_space_image(C); if(RNA_boolean_get(op->ptr, "use_limit")) { UvVertMap *vmap; UvMapVert *vlist, *iterv; float newuv[2], limit[2]; int a, vtot; limit[0]= RNA_float_get(op->ptr, "limit"); limit[1]= limit[0]; EM_init_index_arrays(em, 0, 0, 1); vmap= EM_make_uv_vert_map(em, 1, 0, limit); if(vmap == NULL) { BKE_mesh_end_editmesh(obedit->data, em); return OPERATOR_CANCELLED; } for(a=0, eve= em->verts.first; eve; a++, eve= eve->next) { vlist= EM_get_uv_map_vert(vmap, a); while(vlist) { newuv[0]= 0; newuv[1]= 0; vtot= 0; for(iterv=vlist; iterv; iterv=iterv->next) { if((iterv != vlist) && iterv->separate) break; efa = EM_get_face_for_index(iterv->f); tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_uv_selected(scene, efa, tf, iterv->tfindex)) { newuv[0] += tf->uv[iterv->tfindex][0]; newuv[1] += tf->uv[iterv->tfindex][1]; vtot++; } } if(vtot > 1) { newuv[0] /= vtot; newuv[1] /= vtot; for(iterv=vlist; iterv; iterv=iterv->next) { if((iterv != vlist) && iterv->separate) break; efa = EM_get_face_for_index(iterv->f); tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_uv_selected(scene, efa, tf, iterv->tfindex)) { tf->uv[iterv->tfindex][0]= newuv[0]; tf->uv[iterv->tfindex][1]= newuv[1]; } } } vlist= iterv; } } EM_free_uv_vert_map(vmap); EM_free_index_arrays(); } else { UVVertAverage *uv_average, *uvav; int count; // index and count verts for(count=0, eve=em->verts.first; eve; count++, eve= eve->next) eve->tmp.l = count; uv_average= MEM_callocN(sizeof(UVVertAverage)*count, "Stitch"); // gather uv averages per vert for(efa= em->faces.first; efa; efa= efa->next) { tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_face_visible(scene, ima, efa, tf)) { if(uvedit_uv_selected(scene, efa, tf, 0)) { uvav = uv_average + efa->v1->tmp.l; uvav->count++; uvav->uv[0] += tf->uv[0][0]; uvav->uv[1] += tf->uv[0][1]; } if(uvedit_uv_selected(scene, efa, tf, 1)) { uvav = uv_average + efa->v2->tmp.l; uvav->count++; uvav->uv[0] += tf->uv[1][0]; uvav->uv[1] += tf->uv[1][1]; } if(uvedit_uv_selected(scene, efa, tf, 2)) { uvav = uv_average + efa->v3->tmp.l; uvav->count++; uvav->uv[0] += tf->uv[2][0]; uvav->uv[1] += tf->uv[2][1]; } if(efa->v4 && uvedit_uv_selected(scene, efa, tf, 3)) { uvav = uv_average + efa->v4->tmp.l; uvav->count++; uvav->uv[0] += tf->uv[3][0]; uvav->uv[1] += tf->uv[3][1]; } } } // apply uv welding for(efa= em->faces.first; efa; efa= efa->next) { tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_face_visible(scene, ima, efa, tf)) { if(uvedit_uv_selected(scene, efa, tf, 0)) { uvav = uv_average + efa->v1->tmp.l; tf->uv[0][0] = uvav->uv[0]/uvav->count; tf->uv[0][1] = uvav->uv[1]/uvav->count; } if(uvedit_uv_selected(scene, efa, tf, 1)) { uvav = uv_average + efa->v2->tmp.l; tf->uv[1][0] = uvav->uv[0]/uvav->count; tf->uv[1][1] = uvav->uv[1]/uvav->count; } if(uvedit_uv_selected(scene, efa, tf, 2)) { uvav = uv_average + efa->v3->tmp.l; tf->uv[2][0] = uvav->uv[0]/uvav->count; tf->uv[2][1] = uvav->uv[1]/uvav->count; } if(efa->v4 && uvedit_uv_selected(scene, efa, tf, 3)) { uvav = uv_average + efa->v4->tmp.l; tf->uv[3][0] = uvav->uv[0]/uvav->count; tf->uv[3][1] = uvav->uv[1]/uvav->count; } } } MEM_freeN(uv_average); } uvedit_live_unwrap_update(sima, scene, obedit); DAG_id_tag_update(obedit->data, 0); WM_event_add_notifier(C, NC_GEOM|ND_DATA, obedit->data); BKE_mesh_end_editmesh(obedit->data, em); return OPERATOR_FINISHED; } static void UV_OT_stitch(wmOperatorType *ot) { /* identifiers */ ot->name= "Stitch"; ot->description= "Stitch selected UV vertices by proximity"; ot->idname= "UV_OT_stitch"; ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; /* api callbacks */ ot->exec= stitch_exec; ot->poll= ED_operator_uvedit; /* properties */ RNA_def_boolean(ot->srna, "use_limit", 1, "Use Limit", "Stitch UVs within a specified limit distance"); RNA_def_float(ot->srna, "limit", 0.01f, 0.0f, FLT_MAX, "Limit", "Limit distance in normalized coordinates", -FLT_MAX, FLT_MAX); } /* ******************** (de)select all operator **************** */ static int select_all_exec(bContext *C, wmOperator *op) { Scene *scene; ToolSettings *ts; Object *obedit; EditMesh *em; EditFace *efa; Image *ima; MTFace *tf; int action = RNA_enum_get(op->ptr, "action"); scene= CTX_data_scene(C); ts= CTX_data_tool_settings(C); obedit= CTX_data_edit_object(C); em= BKE_mesh_get_editmesh((Mesh*)obedit->data); ima= CTX_data_edit_image(C); if(ts->uv_flag & UV_SYNC_SELECTION) { switch (action) { case SEL_TOGGLE: EM_toggle_select_all(em); break; case SEL_SELECT: EM_select_all(em); break; case SEL_DESELECT: EM_deselect_all(em); break; case SEL_INVERT: EM_select_swap(em); break; } } else { if (action == SEL_TOGGLE) { action = SEL_SELECT; for(efa= em->faces.first; efa; efa= efa->next) { const char select_flag= efa->v4 ? (TF_SEL1|TF_SEL2|TF_SEL3|TF_SEL4) : (TF_SEL1|TF_SEL2|TF_SEL3); tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_face_visible(scene, ima, efa, tf)) { if(tf->flag & select_flag) { action = SEL_DESELECT; break; } } } } for(efa= em->faces.first; efa; efa= efa->next) { tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_face_visible(scene, ima, efa, tf)) { const char select_flag= efa->v4 ? (TF_SEL1|TF_SEL2|TF_SEL3|TF_SEL4) : (TF_SEL1|TF_SEL2|TF_SEL3); switch (action) { case SEL_SELECT: tf->flag |= select_flag; break; case SEL_DESELECT: tf->flag &= ~select_flag; break; case SEL_INVERT: tf->flag ^= select_flag; break; } } } } WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data); BKE_mesh_end_editmesh(obedit->data, em); return OPERATOR_FINISHED; } static void UV_OT_select_all(wmOperatorType *ot) { /* identifiers */ ot->name= "Select or Deselect All"; ot->description= "Change selection of all UV vertices"; ot->idname= "UV_OT_select_all"; ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; /* api callbacks */ ot->exec= select_all_exec; ot->poll= ED_operator_uvedit; WM_operator_properties_select_all(ot); } /* ******************** mouse select operator **************** */ static int sticky_select(float *limit, int hitv[4], int v, float *hituv[4], float *uv, int sticky) { int i; /* this function test if some vertex needs to selected * in addition to the existing ones due to sticky select */ if(sticky == SI_STICKY_DISABLE) return 0; for(i=0; i<4; i++) { if(hitv[i] == v) { if(sticky == SI_STICKY_LOC) { if(fabsf(hituv[i][0]-uv[0]) < limit[0] && fabsf(hituv[i][1]-uv[1]) < limit[1]) return 1; } else if(sticky == SI_STICKY_VERTEX) return 1; } } return 0; } static int mouse_select(bContext *C, float co[2], int extend, int loop) { SpaceImage *sima= CTX_wm_space_image(C); Scene *scene= CTX_data_scene(C); ToolSettings *ts= CTX_data_tool_settings(C); Object *obedit= CTX_data_edit_object(C); Image *ima= CTX_data_edit_image(C); EditMesh *em= BKE_mesh_get_editmesh((Mesh*)obedit->data); EditFace *efa; MTFace *tf; NearestHit hit; int a, i, select = 1, selectmode, sticky, sync, hitv[4], nvert; int flush = 0; /* 0 == dont flush, 1 == sel, -1 == desel; only use when selection sync is enabled */ float limit[2], *hituv[4], penalty[2]; /* notice 'limit' is the same no matter the zoom level, since this is like * remove doubles and could annoying if it joined points when zoomed out. * 'penalty' is in screen pixel space otherwise zooming in on a uv-vert and * shift-selecting can consider an adjacent point close enough to add to * the selection rather than de-selecting the closest. */ uvedit_pixel_to_float(sima, limit, 0.05f); uvedit_pixel_to_float(sima, penalty, 5.0f / sima->zoom); /* retrieve operation mode */ if(ts->uv_flag & UV_SYNC_SELECTION) { sync= 1; if(ts->selectmode & SCE_SELECT_FACE) selectmode= UV_SELECT_FACE; else if(ts->selectmode & SCE_SELECT_EDGE) selectmode= UV_SELECT_EDGE; else selectmode= UV_SELECT_VERTEX; sticky= SI_STICKY_DISABLE; } else { sync= 0; selectmode= ts->uv_selectmode; sticky= (sima)? sima->sticky: 1; } /* find nearest element */ if(loop) { /* find edge */ find_nearest_uv_edge(scene, ima, em, co, &hit); if(hit.efa == NULL) { BKE_mesh_end_editmesh(obedit->data, em); return OPERATOR_CANCELLED; } } else if(selectmode == UV_SELECT_VERTEX) { /* find vertex */ find_nearest_uv_vert(scene, ima, em, co, penalty, &hit); if(hit.efa == NULL) { BKE_mesh_end_editmesh(obedit->data, em); return OPERATOR_CANCELLED; } /* mark 1 vertex as being hit */ for(i=0; i<4; i++) hitv[i]= 0xFFFFFFFF; hitv[hit.uv]= hit.vert; hituv[hit.uv]= hit.tf->uv[hit.uv]; } else if(selectmode == UV_SELECT_EDGE) { /* find edge */ find_nearest_uv_edge(scene, ima, em, co, &hit); if(hit.efa == NULL) { BKE_mesh_end_editmesh(obedit->data, em); return OPERATOR_CANCELLED; } /* mark 2 edge vertices as being hit */ for(i=0; i<4; i++) hitv[i]= 0xFFFFFFFF; nvert= (hit.efa->v4)? 4: 3; hitv[hit.edge]= hit.vert; hitv[(hit.edge+1)%nvert]= hit.vert2; hituv[hit.edge]= hit.tf->uv[hit.edge]; hituv[(hit.edge+1)%nvert]= hit.tf->uv[(hit.edge+1)%nvert]; } else if(selectmode == UV_SELECT_FACE) { /* find face */ find_nearest_uv_face(scene, ima, em, co, &hit); if(hit.efa == NULL) { BKE_mesh_end_editmesh(obedit->data, em); return OPERATOR_CANCELLED; } /* make active */ EM_set_actFace(em, hit.efa); /* mark all face vertices as being hit */ for(i=0; i<4; i++) hituv[i]= hit.tf->uv[i]; hitv[0]= hit.efa->v1->tmp.l; hitv[1]= hit.efa->v2->tmp.l; hitv[2]= hit.efa->v3->tmp.l; if(hit.efa->v4) hitv[3]= hit.efa->v4->tmp.l; else hitv[3]= 0xFFFFFFFF; } else if(selectmode == UV_SELECT_ISLAND) { find_nearest_uv_vert(scene, ima, em, co, NULL, &hit); if(hit.efa==NULL) { BKE_mesh_end_editmesh(obedit->data, em); return OPERATOR_CANCELLED; } } else { BKE_mesh_end_editmesh(obedit->data, em); return OPERATOR_CANCELLED; } /* do selection */ if(loop) { flush= select_edgeloop(scene, ima, em, &hit, limit, extend); } else if(selectmode == UV_SELECT_ISLAND) { select_linked(scene, ima, em, limit, &hit, extend); } else if(extend) { if(selectmode == UV_SELECT_VERTEX) { /* (de)select uv vertex */ if(uvedit_uv_selected(scene, hit.efa, hit.tf, hit.uv)) { uvedit_uv_deselect(scene, hit.efa, hit.tf, hit.uv); select= 0; } else { uvedit_uv_select(scene, hit.efa, hit.tf, hit.uv); select= 1; } flush = 1; } else if(selectmode == UV_SELECT_EDGE) { /* (de)select edge */ if(uvedit_edge_selected(scene, hit.efa, hit.tf, hit.edge)) { uvedit_edge_deselect(scene, hit.efa, hit.tf, hit.edge); select= 0; } else { uvedit_edge_select(scene, hit.efa, hit.tf, hit.edge); select= 1; } flush = 1; } else if(selectmode == UV_SELECT_FACE) { /* (de)select face */ if(uvedit_face_selected(scene, hit.efa, hit.tf)) { uvedit_face_deselect(scene, hit.efa, hit.tf); select= 0; } else { uvedit_face_select(scene, hit.efa, hit.tf); select= 1; } flush = -1; } /* (de)select sticky uv nodes */ if(sticky != SI_STICKY_DISABLE) { EditVert *ev; for(a=0, ev=em->verts.first; ev; ev = ev->next, a++) ev->tmp.l = a; /* deselect */ if(select==0) { for(efa= em->faces.first; efa; efa= efa->next) { tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_face_visible(scene, ima, efa, tf)) { if(sticky_select(limit, hitv, efa->v1->tmp.l, hituv, tf->uv[0], sticky)) uvedit_uv_deselect(scene, efa, tf, 0); if(sticky_select(limit, hitv, efa->v2->tmp.l, hituv, tf->uv[1], sticky)) uvedit_uv_deselect(scene, efa, tf, 1); if(sticky_select(limit, hitv, efa->v3->tmp.l, hituv, tf->uv[2], sticky)) uvedit_uv_deselect(scene, efa, tf, 2); if(efa->v4) if(sticky_select(limit, hitv, efa->v4->tmp.l, hituv, tf->uv[3], sticky)) uvedit_uv_deselect(scene, efa, tf, 3); } } flush = -1; } /* select */ else { for(efa= em->faces.first; efa; efa= efa->next) { tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_face_visible(scene, ima, efa, tf)) { if(sticky_select(limit, hitv, efa->v1->tmp.l, hituv, tf->uv[0], sticky)) uvedit_uv_select(scene, efa, tf, 0); if(sticky_select(limit, hitv, efa->v2->tmp.l, hituv, tf->uv[1], sticky)) uvedit_uv_select(scene, efa, tf, 1); if(sticky_select(limit, hitv, efa->v3->tmp.l, hituv, tf->uv[2], sticky)) uvedit_uv_select(scene, efa, tf, 2); if(efa->v4) if(sticky_select(limit, hitv, efa->v4->tmp.l, hituv, tf->uv[3], sticky)) uvedit_uv_select(scene, efa, tf, 3); } } flush = 1; } } } else { /* deselect all */ for(efa= em->faces.first; efa; efa= efa->next) { tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); uvedit_face_deselect(scene, efa, tf); } if(selectmode == UV_SELECT_VERTEX) { /* select vertex */ uvedit_uv_select(scene, hit.efa, hit.tf, hit.uv); flush= 1; } else if(selectmode == UV_SELECT_EDGE) { /* select edge */ uvedit_edge_select(scene, hit.efa, hit.tf, hit.edge); flush= 1; } else if(selectmode == UV_SELECT_FACE) { /* select face */ uvedit_face_select(scene, hit.efa, hit.tf); } /* select sticky uvs */ if(sticky != SI_STICKY_DISABLE) { for(efa= em->faces.first; efa; efa= efa->next) { tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_face_visible(scene, ima, efa, tf)) { if(sticky == SI_STICKY_DISABLE) continue; if(sticky_select(limit, hitv, efa->v1->tmp.l, hituv, tf->uv[0], sticky)) uvedit_uv_select(scene, efa, tf, 0); if(sticky_select(limit, hitv, efa->v2->tmp.l, hituv, tf->uv[1], sticky)) uvedit_uv_select(scene, efa, tf, 1); if(sticky_select(limit, hitv, efa->v3->tmp.l, hituv, tf->uv[2], sticky)) uvedit_uv_select(scene, efa, tf, 2); if(efa->v4) if(sticky_select(limit, hitv, efa->v4->tmp.l, hituv, tf->uv[3], sticky)) uvedit_uv_select(scene, efa, tf, 3); flush= 1; } } } } if(sync) { /* flush for mesh selection */ if(ts->selectmode != SCE_SELECT_FACE) { if(flush==1) EM_select_flush(em); else if(flush==-1) EM_deselect_flush(em); } } DAG_id_tag_update(obedit->data, 0); WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data); BKE_mesh_end_editmesh(obedit->data, em); return OPERATOR_PASS_THROUGH|OPERATOR_FINISHED; } static int select_exec(bContext *C, wmOperator *op) { float co[2]; int extend, loop; RNA_float_get_array(op->ptr, "location", co); extend= RNA_boolean_get(op->ptr, "extend"); loop= 0; return mouse_select(C, co, extend, loop); } static int select_invoke(bContext *C, wmOperator *op, wmEvent *event) { ARegion *ar= CTX_wm_region(C); float co[2]; UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &co[0], &co[1]); RNA_float_set_array(op->ptr, "location", co); return select_exec(C, op); } static void UV_OT_select(wmOperatorType *ot) { /* identifiers */ ot->name= "Select"; ot->description= "Select UV vertices"; ot->idname= "UV_OT_select"; ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; /* api callbacks */ ot->exec= select_exec; ot->invoke= select_invoke; ot->poll= ED_operator_image_active; /* requires space image */; /* properties */ RNA_def_boolean(ot->srna, "extend", 0, "Extend", "Extend selection rather than clearing the existing selection"); RNA_def_float_vector(ot->srna, "location", 2, NULL, -FLT_MAX, FLT_MAX, "Location", "Mouse location in normalized coordinates, 0.0 to 1.0 is within the image bounds", -100.0f, 100.0f); } /* ******************** loop select operator **************** */ static int select_loop_exec(bContext *C, wmOperator *op) { float co[2]; int extend, loop; RNA_float_get_array(op->ptr, "location", co); extend= RNA_boolean_get(op->ptr, "extend"); loop= 1; return mouse_select(C, co, extend, loop); } static int select_loop_invoke(bContext *C, wmOperator *op, wmEvent *event) { ARegion *ar= CTX_wm_region(C); float co[2]; UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &co[0], &co[1]); RNA_float_set_array(op->ptr, "location", co); return select_loop_exec(C, op); } static void UV_OT_select_loop(wmOperatorType *ot) { /* identifiers */ ot->name= "Loop Select"; ot->description= "Select a loop of connected UV vertices"; ot->idname= "UV_OT_select_loop"; ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; /* api callbacks */ ot->exec= select_loop_exec; ot->invoke= select_loop_invoke; ot->poll= ED_operator_image_active; /* requires space image */; /* properties */ RNA_def_boolean(ot->srna, "extend", 0, "Extend", "Extend selection rather than clearing the existing selection"); RNA_def_float_vector(ot->srna, "location", 2, NULL, -FLT_MAX, FLT_MAX, "Location", "Mouse location in normalized coordinates, 0.0 to 1.0 is within the image bounds", -100.0f, 100.0f); } /* ******************** linked select operator **************** */ static int select_linked_internal(bContext *C, wmOperator *op, wmEvent *event, int pick) { SpaceImage *sima= CTX_wm_space_image(C); Scene *scene= CTX_data_scene(C); ToolSettings *ts= CTX_data_tool_settings(C); Object *obedit= CTX_data_edit_object(C); Image *ima= CTX_data_edit_image(C); EditMesh *em= BKE_mesh_get_editmesh((Mesh*)obedit->data); float limit[2]; int extend; NearestHit hit, *hit_p= NULL; if(ts->uv_flag & UV_SYNC_SELECTION) { BKE_report(op->reports, RPT_ERROR, "Can't select linked when sync selection is enabled"); BKE_mesh_end_editmesh(obedit->data, em); return OPERATOR_CANCELLED; } extend= RNA_boolean_get(op->ptr, "extend"); uvedit_pixel_to_float(sima, limit, 0.05f); if(pick) { float co[2]; if(event) { /* invoke */ ARegion *ar= CTX_wm_region(C); UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &co[0], &co[1]); RNA_float_set_array(op->ptr, "location", co); } else { /* exec */ RNA_float_get_array(op->ptr, "location", co); } find_nearest_uv_vert(scene, ima, em, co, NULL, &hit); hit_p= &hit; } select_linked(scene, ima, em, limit, hit_p, extend); DAG_id_tag_update(obedit->data, 0); WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data); BKE_mesh_end_editmesh(obedit->data, em); return OPERATOR_FINISHED; } static int select_linked_exec(bContext *C, wmOperator *op) { return select_linked_internal(C, op, NULL, 0); } static void UV_OT_select_linked(wmOperatorType *ot) { /* identifiers */ ot->name= "Select Linked"; ot->description= "Select all UV vertices linked to the active UV map"; ot->idname= "UV_OT_select_linked"; ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; /* api callbacks */ ot->exec= select_linked_exec; ot->poll= ED_operator_image_active; /* requires space image */ /* properties */ RNA_def_boolean(ot->srna, "extend", 0, "Extend", "Extend selection rather than clearing the existing selection"); } static int select_linked_pick_invoke(bContext *C, wmOperator *op, wmEvent *event) { return select_linked_internal(C, op, event, 1); } static int select_linked_pick_exec(bContext *C, wmOperator *op) { return select_linked_internal(C, op, NULL, 1); } static void UV_OT_select_linked_pick(wmOperatorType *ot) { /* identifiers */ ot->name= "Select Linked Pick"; ot->description= "Select all UV vertices linked under the mouse"; ot->idname= "UV_OT_select_linked_pick"; ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; /* api callbacks */ ot->invoke= select_linked_pick_invoke; ot->exec= select_linked_pick_exec; ot->poll= ED_operator_image_active; /* requires space image */; /* properties */ RNA_def_boolean(ot->srna, "extend", 0, "Extend", "Extend selection rather than clearing the existing selection"); RNA_def_float_vector(ot->srna, "location", 2, NULL, -FLT_MAX, FLT_MAX, "Location", "Mouse location in normalized coordinates, 0.0 to 1.0 is within the image bounds", -100.0f, 100.0f); } /* ******************** unlink selection operator **************** */ static int unlink_selection_exec(bContext *C, wmOperator *op) { Scene *scene= CTX_data_scene(C); ToolSettings *ts= CTX_data_tool_settings(C); Object *obedit= CTX_data_edit_object(C); Image *ima= CTX_data_edit_image(C); EditMesh *em= BKE_mesh_get_editmesh((Mesh*)obedit->data); EditFace *efa; MTFace *tf; if(ts->uv_flag & UV_SYNC_SELECTION) { BKE_report(op->reports, RPT_ERROR, "Can't unlink selection when sync selection is enabled"); BKE_mesh_end_editmesh(obedit->data, em); return OPERATOR_CANCELLED; } for(efa= em->faces.first; efa; efa= efa->next) { tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_face_visible(scene, ima, efa, tf)) { const char select_flag= efa->v4 ? (TF_SEL1|TF_SEL2|TF_SEL3|TF_SEL4) : (TF_SEL1|TF_SEL2|TF_SEL3); if(~tf->flag & select_flag) tf->flag &= ~select_flag; } } DAG_id_tag_update(obedit->data, 0); WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data); BKE_mesh_end_editmesh(obedit->data, em); return OPERATOR_FINISHED; } static void UV_OT_unlink_selected(wmOperatorType *ot) { /* identifiers */ ot->name= "Unlink Selection"; ot->description= "Unlink selected UV vertices from active UV map"; ot->idname= "UV_OT_unlink_selected"; ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; /* api callbacks */ ot->exec= unlink_selection_exec; ot->poll= ED_operator_uvedit; } /* ******************** border select operator **************** */ /* This function sets the selection on tagged faces, need because settings the * selection a face is done in a number of places but it also needs to respect * the sticky modes for the UV verts, so dealing with the sticky modes is best * done in a separate function. * * De-selects faces that have been tagged on efa->tmp.l. */ static void uv_faces_do_sticky(bContext *C, SpaceImage *sima, Scene *scene, Object *obedit, short select) { /* Selecting UV Faces with some modes requires us to change * the selection in other faces (depending on the sticky mode). * * This only needs to be done when the Mesh is not used for * selection (so for sticky modes, vertex or location based). */ ToolSettings *ts= CTX_data_tool_settings(C); EditMesh *em= BKE_mesh_get_editmesh((Mesh*)obedit->data); EditFace *efa; MTFace *tf; int nverts, i; if((ts->uv_flag & UV_SYNC_SELECTION)==0 && sima->sticky == SI_STICKY_VERTEX) { /* Tag all verts as untouched, then touch the ones that have a face center * in the loop and select all MTFace UV's that use a touched vert. */ EditVert *eve; for(eve= em->verts.first; eve; eve= eve->next) eve->tmp.l = 0; for(efa= em->faces.first; efa; efa= efa->next) { if(efa->tmp.l) { if(efa->v4) efa->v1->tmp.l= efa->v2->tmp.l= efa->v3->tmp.l= efa->v4->tmp.l=1; else efa->v1->tmp.l= efa->v2->tmp.l= efa->v3->tmp.l= 1; } } /* now select tagged verts */ for(efa= em->faces.first; efa; efa= efa->next) { tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); nverts= efa->v4? 4: 3; for(i=0; i<nverts; i++) { if((*(&efa->v1 + i))->tmp.l) { if(select) uvedit_uv_select(scene, efa, tf, i); else uvedit_uv_deselect(scene, efa, tf, i); } } } } else if((ts->uv_flag & UV_SYNC_SELECTION)==0 && sima->sticky == SI_STICKY_LOC) { EditFace *efa_vlist; MTFace *tf_vlist; UvMapVert *start_vlist=NULL, *vlist_iter; struct UvVertMap *vmap; float limit[2]; unsigned int efa_index; //EditVert *eve; /* removed vert counting for now */ //int a; uvedit_pixel_to_float(sima, limit, 0.05); EM_init_index_arrays(em, 0, 0, 1); vmap= EM_make_uv_vert_map(em, 0, 0, limit); /* verts are numbered above in make_uv_vert_map_EM, make sure this stays true! */ /*for(a=0, eve= em->verts.first; eve; a++, eve= eve->next) eve->tmp.l = a; */ if(vmap == NULL) { BKE_mesh_end_editmesh(obedit->data, em); return; } for(efa_index=0, efa= em->faces.first; efa; efa_index++, efa= efa->next) { if(efa->tmp.l) { tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); nverts= efa->v4? 4: 3; for(i=0; i<nverts; i++) { if(select) uvedit_uv_select(scene, efa, tf, i); else uvedit_uv_deselect(scene, efa, tf, i); vlist_iter= EM_get_uv_map_vert(vmap, (*(&efa->v1 + i))->tmp.l); while (vlist_iter) { if(vlist_iter->separate) start_vlist = vlist_iter; if(efa_index == vlist_iter->f) break; vlist_iter = vlist_iter->next; } vlist_iter = start_vlist; while (vlist_iter) { if(vlist_iter != start_vlist && vlist_iter->separate) break; if(efa_index != vlist_iter->f) { efa_vlist = EM_get_face_for_index(vlist_iter->f); tf_vlist = CustomData_em_get(&em->fdata, efa_vlist->data, CD_MTFACE); if(select) uvedit_uv_select(scene, efa_vlist, tf_vlist, vlist_iter->tfindex); else uvedit_uv_deselect(scene, efa_vlist, tf_vlist, vlist_iter->tfindex); } vlist_iter = vlist_iter->next; } } } } EM_free_index_arrays(); EM_free_uv_vert_map(vmap); } else { /* SI_STICKY_DISABLE or ts->uv_flag & UV_SYNC_SELECTION */ for(efa= em->faces.first; efa; efa= efa->next) { if(efa->tmp.l) { tf = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(select) uvedit_face_select(scene, efa, tf); else uvedit_face_deselect(scene, efa, tf); } } } BKE_mesh_end_editmesh(obedit->data, em); } static int border_select_exec(bContext *C, wmOperator *op) { SpaceImage *sima= CTX_wm_space_image(C); Scene *scene= CTX_data_scene(C); ToolSettings *ts= CTX_data_tool_settings(C); Object *obedit= CTX_data_edit_object(C); Image *ima= CTX_data_edit_image(C); ARegion *ar= CTX_wm_region(C); EditMesh *em= BKE_mesh_get_editmesh((Mesh*)obedit->data); EditFace *efa; MTFace *tface; rcti rect; rctf rectf; int change, pinned, select, faces; /* get rectangle from operator */ rect.xmin= RNA_int_get(op->ptr, "xmin"); rect.ymin= RNA_int_get(op->ptr, "ymin"); rect.xmax= RNA_int_get(op->ptr, "xmax"); rect.ymax= RNA_int_get(op->ptr, "ymax"); UI_view2d_region_to_view(&ar->v2d, rect.xmin, rect.ymin, &rectf.xmin, &rectf.ymin); UI_view2d_region_to_view(&ar->v2d, rect.xmax, rect.ymax, &rectf.xmax, &rectf.ymax); /* figure out what to select/deselect */ select= (RNA_int_get(op->ptr, "gesture_mode") == GESTURE_MODAL_SELECT); pinned= RNA_boolean_get(op->ptr, "pinned"); if(ts->uv_flag & UV_SYNC_SELECTION) faces= (ts->selectmode == SCE_SELECT_FACE); else faces= (ts->uv_selectmode == UV_SELECT_FACE); /* do actual selection */ if(faces && !pinned) { /* handle face selection mode */ float cent[2]; change= 0; for(efa= em->faces.first; efa; efa= efa->next) { /* assume not touched */ efa->tmp.l = 0; tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_face_visible(scene, ima, efa, tface)) { uv_center(tface->uv, cent, efa->v4 != NULL); if(BLI_in_rctf(&rectf, cent[0], cent[1])) { efa->tmp.l = change = 1; } } } /* (de)selects all tagged faces and deals with sticky modes */ if(change) uv_faces_do_sticky(C, sima, scene, obedit, select); } else { /* other selection modes */ change= 1; for(efa= em->faces.first; efa; efa= efa->next) { tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_face_visible(scene, ima, efa, tface)) { if(!pinned || (ts->uv_flag & UV_SYNC_SELECTION) ) { /* UV_SYNC_SELECTION - can't do pinned selection */ if(BLI_in_rctf(&rectf, tface->uv[0][0], tface->uv[0][1])) { if(select) uvedit_uv_select(scene, efa, tface, 0); else uvedit_uv_deselect(scene, efa, tface, 0); } if(BLI_in_rctf(&rectf, tface->uv[1][0], tface->uv[1][1])) { if(select) uvedit_uv_select(scene, efa, tface, 1); else uvedit_uv_deselect(scene, efa, tface, 1); } if(BLI_in_rctf(&rectf, tface->uv[2][0], tface->uv[2][1])) { if(select) uvedit_uv_select(scene, efa, tface, 2); else uvedit_uv_deselect(scene, efa, tface, 2); } if(efa->v4 && BLI_in_rctf(&rectf, tface->uv[3][0], tface->uv[3][1])) { if(select) uvedit_uv_select(scene, efa, tface, 3); else uvedit_uv_deselect(scene, efa, tface, 3); } } else if(pinned) { if((tface->unwrap & TF_PIN1) && BLI_in_rctf(&rectf, tface->uv[0][0], tface->uv[0][1])) { if(select) uvedit_uv_select(scene, efa, tface, 0); else uvedit_uv_deselect(scene, efa, tface, 0); } if((tface->unwrap & TF_PIN2) && BLI_in_rctf(&rectf, tface->uv[1][0], tface->uv[1][1])) { if(select) uvedit_uv_select(scene, efa, tface, 1); else uvedit_uv_deselect(scene, efa, tface, 1); } if((tface->unwrap & TF_PIN3) && BLI_in_rctf(&rectf, tface->uv[2][0], tface->uv[2][1])) { if(select) uvedit_uv_select(scene, efa, tface, 2); else uvedit_uv_deselect(scene, efa, tface, 2); } if((efa->v4) && (tface->unwrap & TF_PIN4) && BLI_in_rctf(&rectf, tface->uv[3][0], tface->uv[3][1])) { if(select) uvedit_uv_select(scene, efa, tface, 3); else uvedit_uv_deselect(scene, efa, tface, 3); } } } } } if(change) { /* make sure newly selected vert selection is updated*/ if(ts->uv_flag & UV_SYNC_SELECTION) { if(ts->selectmode != SCE_SELECT_FACE) { if(select) EM_select_flush(em); else EM_deselect_flush(em); } } WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data); BKE_mesh_end_editmesh(obedit->data, em); return OPERATOR_FINISHED; } BKE_mesh_end_editmesh(obedit->data, em); return OPERATOR_CANCELLED; } static void UV_OT_select_border(wmOperatorType *ot) { /* identifiers */ ot->name= "Border Select"; ot->description= "Select UV vertices using border selection"; ot->idname= "UV_OT_select_border"; /* api callbacks */ ot->invoke= WM_border_select_invoke; ot->exec= border_select_exec; ot->modal= WM_border_select_modal; ot->poll= ED_operator_image_active; /* requires space image */; ot->cancel= WM_border_select_cancel; /* flags */ ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; /* properties */ RNA_def_boolean(ot->srna, "pinned", 0, "Pinned", "Border select pinned UVs only"); WM_operator_properties_gesture_border(ot, FALSE); } /* ******************** circle select operator **************** */ static void select_uv_inside_ellipse(Scene *scene, int select, EditFace *efa, MTFace *tface, int index, float *offset, float *ell, int select_index) { /* normalized ellipse: ell[0] = scaleX, ell[1] = scaleY */ float x, y, r2, *uv; uv= tface->uv[index]; x= (uv[0] - offset[0])*ell[0]; y= (uv[1] - offset[1])*ell[1]; r2 = x*x + y*y; if(r2 < 1.0f) { if(select) uvedit_uv_select(scene, efa, tface, select_index); else uvedit_uv_deselect(scene, efa, tface, select_index); } } static int circle_select_exec(bContext *C, wmOperator *op) { SpaceImage *sima= CTX_wm_space_image(C); Scene *scene= CTX_data_scene(C); Object *obedit= CTX_data_edit_object(C); EditMesh *em= BKE_mesh_get_editmesh((Mesh*)obedit->data); ARegion *ar= CTX_wm_region(C); EditFace *efa; MTFace *tface; int x, y, radius, width, height, select; float zoomx, zoomy, offset[2], ellipse[2]; int gesture_mode= RNA_int_get(op->ptr, "gesture_mode"); /* get operator properties */ select= (gesture_mode == GESTURE_MODAL_SELECT); x= RNA_int_get(op->ptr, "x"); y= RNA_int_get(op->ptr, "y"); radius= RNA_int_get(op->ptr, "radius"); /* compute ellipse size and location, not a circle since we deal * with non square image. ellipse is normalized, r = 1.0. */ ED_space_image_size(sima, &width, &height); ED_space_image_zoom(sima, ar, &zoomx, &zoomy); ellipse[0]= width*zoomx/radius; ellipse[1]= height*zoomy/radius; UI_view2d_region_to_view(&ar->v2d, x, y, &offset[0], &offset[1]); /* do selection */ for(efa= em->faces.first; efa; efa= efa->next) { tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); select_uv_inside_ellipse(scene, select, efa, tface, 0, offset, ellipse, 0); select_uv_inside_ellipse(scene, select, efa, tface, 1, offset, ellipse, 1); select_uv_inside_ellipse(scene, select, efa, tface, 2, offset, ellipse, 2); if(efa->v4) select_uv_inside_ellipse(scene, select, efa, tface, 3, offset, ellipse, 3); } if(select) EM_select_flush(em); else EM_deselect_flush(em); WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data); BKE_mesh_end_editmesh(obedit->data, em); return OPERATOR_FINISHED; } static void UV_OT_circle_select(wmOperatorType *ot) { /* identifiers */ ot->name= "Circle Select"; ot->description= "Select UV vertices using circle selection"; ot->idname= "UV_OT_circle_select"; /* api callbacks */ ot->invoke= WM_gesture_circle_invoke; ot->modal= WM_gesture_circle_modal; ot->exec= circle_select_exec; ot->poll= ED_operator_image_active; /* requires space image */; ot->cancel= WM_gesture_circle_cancel; /* flags */ ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; /* properties */ RNA_def_int(ot->srna, "x", 0, INT_MIN, INT_MAX, "X", "", INT_MIN, INT_MAX); RNA_def_int(ot->srna, "y", 0, INT_MIN, INT_MAX, "Y", "", INT_MIN, INT_MAX); RNA_def_int(ot->srna, "radius", 0, INT_MIN, INT_MAX, "Radius", "", INT_MIN, INT_MAX); RNA_def_int(ot->srna, "gesture_mode", 0, INT_MIN, INT_MAX, "Gesture Mode", "", INT_MIN, INT_MAX); } /* ******************** snap cursor operator **************** */ static void snap_uv_to_pixel(float *uvco, float w, float h) { uvco[0] = ((float)((int)((uvco[0]*w) + 0.5f)))/w; uvco[1] = ((float)((int)((uvco[1]*h) + 0.5f)))/h; } static void snap_cursor_to_pixels(SpaceImage *sima) { int width= 0, height= 0; ED_space_image_size(sima, &width, &height); snap_uv_to_pixel(sima->cursor, width, height); } static int snap_cursor_to_selection(Scene *scene, Image *ima, Object *obedit, SpaceImage *sima) { return uvedit_center(scene, ima, obedit, sima->cursor, sima->around); } static int snap_cursor_exec(bContext *C, wmOperator *op) { SpaceImage *sima= CTX_wm_space_image(C); Scene *scene= CTX_data_scene(C); Object *obedit= CTX_data_edit_object(C); Image *ima= CTX_data_edit_image(C); int change= 0; switch(RNA_enum_get(op->ptr, "target")) { case 0: snap_cursor_to_pixels(sima); change= 1; break; case 1: change= snap_cursor_to_selection(scene, ima, obedit, sima); break; } if(!change) return OPERATOR_CANCELLED; WM_event_add_notifier(C, NC_SPACE|ND_SPACE_IMAGE, sima); return OPERATOR_FINISHED; } static void UV_OT_snap_cursor(wmOperatorType *ot) { static EnumPropertyItem target_items[] = { {0, "PIXELS", 0, "Pixels", ""}, {1, "SELECTED", 0, "Selected", ""}, {0, NULL, 0, NULL, NULL}}; /* identifiers */ ot->name= "Snap Cursor"; ot->description= "Snap cursor to target type"; ot->idname= "UV_OT_snap_cursor"; ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; /* api callbacks */ ot->exec= snap_cursor_exec; ot->poll= ED_operator_image_active; /* requires space image */; /* properties */ RNA_def_enum(ot->srna, "target", target_items, 0, "Target", "Target to snap the selected UVs to"); } /* ******************** snap selection operator **************** */ static int snap_uvs_to_cursor(Scene *scene, Image *ima, Object *obedit, SpaceImage *sima) { EditMesh *em= BKE_mesh_get_editmesh((Mesh*)obedit->data); EditFace *efa; MTFace *tface; short change= 0; for(efa= em->faces.first; efa; efa= efa->next) { tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_face_visible(scene, ima, efa, tface)) { if(uvedit_uv_selected(scene, efa, tface, 0)) VECCOPY2D(tface->uv[0], sima->cursor); if(uvedit_uv_selected(scene, efa, tface, 1)) VECCOPY2D(tface->uv[1], sima->cursor); if(uvedit_uv_selected(scene, efa, tface, 2)) VECCOPY2D(tface->uv[2], sima->cursor); if(efa->v4) if(uvedit_uv_selected(scene, efa, tface, 3)) VECCOPY2D(tface->uv[3], sima->cursor); change= 1; } } BKE_mesh_end_editmesh(obedit->data, em); return change; } static int snap_uvs_to_adjacent_unselected(Scene *scene, Image *ima, Object *obedit) { EditMesh *em= BKE_mesh_get_editmesh((Mesh*)obedit->data); EditFace *efa; EditVert *eve; MTFace *tface; short change = 0; int count = 0; float *coords; short *usercount, users; /* set all verts to -1 : an unused index*/ for(eve= em->verts.first; eve; eve= eve->next) eve->tmp.l=-1; /* index every vert that has a selected UV using it, but only once so as to * get unique indices and to count how much to malloc */ for(efa= em->faces.first; efa; efa= efa->next) { tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_face_visible(scene, ima, efa, tface)) { if(uvedit_uv_selected(scene, efa, tface, 0) && efa->v1->tmp.l==-1) efa->v1->tmp.l= count++; if(uvedit_uv_selected(scene, efa, tface, 1) && efa->v2->tmp.l==-1) efa->v2->tmp.l= count++; if(uvedit_uv_selected(scene, efa, tface, 2) && efa->v3->tmp.l==-1) efa->v3->tmp.l= count++; if(efa->v4) if(uvedit_uv_selected(scene, efa, tface, 3) && efa->v4->tmp.l==-1) efa->v4->tmp.l= count++; change = 1; /* optional speedup */ efa->tmp.p = tface; } else efa->tmp.p = NULL; } coords = MEM_callocN(sizeof(float)*count*2, "snap to adjacent coords"); usercount = MEM_callocN(sizeof(short)*count, "snap to adjacent counts"); /* add all UV coords from visible, unselected UV coords as well as counting them to average later */ for(efa= em->faces.first; efa; efa= efa->next) { if((tface=(MTFace *)efa->tmp.p)) { /* is this an unselected UV we can snap to? */ if(efa->v1->tmp.l >= 0 && (!uvedit_uv_selected(scene, efa, tface, 0))) { coords[efa->v1->tmp.l*2] += tface->uv[0][0]; coords[(efa->v1->tmp.l*2)+1] += tface->uv[0][1]; usercount[efa->v1->tmp.l]++; change = 1; } if(efa->v2->tmp.l >= 0 && (!uvedit_uv_selected(scene, efa, tface, 1))) { coords[efa->v2->tmp.l*2] += tface->uv[1][0]; coords[(efa->v2->tmp.l*2)+1] += tface->uv[1][1]; usercount[efa->v2->tmp.l]++; change = 1; } if(efa->v3->tmp.l >= 0 && (!uvedit_uv_selected(scene, efa, tface, 2))) { coords[efa->v3->tmp.l*2] += tface->uv[2][0]; coords[(efa->v3->tmp.l*2)+1] += tface->uv[2][1]; usercount[efa->v3->tmp.l]++; change = 1; } if(efa->v4) { if(efa->v4->tmp.l >= 0 && (!uvedit_uv_selected(scene, efa, tface, 3))) { coords[efa->v4->tmp.l*2] += tface->uv[3][0]; coords[(efa->v4->tmp.l*2)+1] += tface->uv[3][1]; usercount[efa->v4->tmp.l]++; change = 1; } } } } /* no other verts selected, bail out */ if(!change) { MEM_freeN(coords); MEM_freeN(usercount); BKE_mesh_end_editmesh(obedit->data, em); return change; } /* copy the averaged unselected UVs back to the selected UVs */ for(efa= em->faces.first; efa; efa= efa->next) { if((tface=(MTFace *)efa->tmp.p)) { if( uvedit_uv_selected(scene, efa, tface, 0) && efa->v1->tmp.l >= 0 && (users = usercount[efa->v1->tmp.l]) ) { tface->uv[0][0] = coords[efa->v1->tmp.l*2] / users; tface->uv[0][1] = coords[(efa->v1->tmp.l*2)+1] / users; } if( uvedit_uv_selected(scene, efa, tface, 1) && efa->v2->tmp.l >= 0 && (users = usercount[efa->v2->tmp.l]) ) { tface->uv[1][0] = coords[efa->v2->tmp.l*2] / users; tface->uv[1][1] = coords[(efa->v2->tmp.l*2)+1] / users; } if( uvedit_uv_selected(scene, efa, tface, 2) && efa->v3->tmp.l >= 0 && (users = usercount[efa->v3->tmp.l]) ) { tface->uv[2][0] = coords[efa->v3->tmp.l*2] / users; tface->uv[2][1] = coords[(efa->v3->tmp.l*2)+1] / users; } if(efa->v4) { if( uvedit_uv_selected(scene, efa, tface, 3) && efa->v4->tmp.l >= 0 && (users = usercount[efa->v4->tmp.l]) ) { tface->uv[3][0] = coords[efa->v4->tmp.l*2] / users; tface->uv[3][1] = coords[(efa->v4->tmp.l*2)+1] / users; } } } } MEM_freeN(coords); MEM_freeN(usercount); BKE_mesh_end_editmesh(obedit->data, em); return change; } static int snap_uvs_to_pixels(SpaceImage *sima, Scene *scene, Object *obedit) { EditMesh *em= BKE_mesh_get_editmesh((Mesh*)obedit->data); Image *ima; EditFace *efa; MTFace *tface; int width= 0, height= 0; float w, h; short change = 0; if(!sima) return 0; ima= sima->image; ED_space_image_size(sima, &width, &height); w = (float)width; h = (float)height; for(efa= em->faces.first; efa; efa= efa->next) { tface= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_face_visible(scene, ima, efa, tface)) { if(uvedit_uv_selected(scene, efa, tface, 0)) snap_uv_to_pixel(tface->uv[0], w, h); if(uvedit_uv_selected(scene, efa, tface, 1)) snap_uv_to_pixel(tface->uv[1], w, h); if(uvedit_uv_selected(scene, efa, tface, 2)) snap_uv_to_pixel(tface->uv[2], w, h); if(efa->v4) if(uvedit_uv_selected(scene, efa, tface, 3)) snap_uv_to_pixel(tface->uv[3], w, h); change = 1; } } BKE_mesh_end_editmesh(obedit->data, em); return change; } static int snap_selection_exec(bContext *C, wmOperator *op) { SpaceImage *sima= CTX_wm_space_image(C); Scene *scene= CTX_data_scene(C); Object *obedit= CTX_data_edit_object(C); Image *ima= CTX_data_edit_image(C); int change= 0; switch(RNA_enum_get(op->ptr, "target")) { case 0: change= snap_uvs_to_pixels(sima, scene, obedit); break; case 1: change= snap_uvs_to_cursor(scene, ima, obedit, sima); break; case 2: change= snap_uvs_to_adjacent_unselected(scene, ima, obedit); break; } if(!change) return OPERATOR_CANCELLED; uvedit_live_unwrap_update(sima, scene, obedit); DAG_id_tag_update(obedit->data, 0); WM_event_add_notifier(C, NC_GEOM|ND_DATA, obedit->data); return OPERATOR_FINISHED; } static void UV_OT_snap_selected(wmOperatorType *ot) { static EnumPropertyItem target_items[] = { {0, "PIXELS", 0, "Pixels", ""}, {1, "CURSOR", 0, "Cursor", ""}, {2, "ADJACENT_UNSELECTED", 0, "Adjacent Unselected", ""}, {0, NULL, 0, NULL, NULL}}; /* identifiers */ ot->name= "Snap Selection"; ot->description= "Snap selected UV vertices to target type"; ot->idname= "UV_OT_snap_selected"; ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; /* api callbacks */ ot->exec= snap_selection_exec; ot->poll= ED_operator_image_active; /* requires space image */; /* properties */ RNA_def_enum(ot->srna, "target", target_items, 0, "Target", "Target to snap the selected UVs to"); } /* ******************** pin operator **************** */ static int pin_exec(bContext *C, wmOperator *op) { Scene *scene= CTX_data_scene(C); Object *obedit= CTX_data_edit_object(C); Image *ima= CTX_data_edit_image(C); EditMesh *em= BKE_mesh_get_editmesh((Mesh*)obedit->data); EditFace *efa; MTFace *tface; int clear= RNA_boolean_get(op->ptr, "clear"); for(efa= em->faces.first; efa; efa= efa->next) { tface = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_face_visible(scene, ima, efa, tface)) { if(!clear) { if(uvedit_uv_selected(scene, efa, tface, 0)) tface->unwrap |= TF_PIN1; if(uvedit_uv_selected(scene, efa, tface, 1)) tface->unwrap |= TF_PIN2; if(uvedit_uv_selected(scene, efa, tface, 2)) tface->unwrap |= TF_PIN3; if(efa->v4) if(uvedit_uv_selected(scene, efa, tface, 3)) tface->unwrap |= TF_PIN4; } else { if(uvedit_uv_selected(scene, efa, tface, 0)) tface->unwrap &= ~TF_PIN1; if(uvedit_uv_selected(scene, efa, tface, 1)) tface->unwrap &= ~TF_PIN2; if(uvedit_uv_selected(scene, efa, tface, 2)) tface->unwrap &= ~TF_PIN3; if(efa->v4) if(uvedit_uv_selected(scene, efa, tface, 3)) tface->unwrap &= ~TF_PIN4; } } } WM_event_add_notifier(C, NC_GEOM|ND_DATA, obedit->data); BKE_mesh_end_editmesh(obedit->data, em); return OPERATOR_FINISHED; } static void UV_OT_pin(wmOperatorType *ot) { /* identifiers */ ot->name= "Pin"; ot->description= "Set/clear selected UV vertices as anchored between multiple unwrap operations"; ot->idname= "UV_OT_pin"; ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; /* api callbacks */ ot->exec= pin_exec; ot->poll= ED_operator_uvedit; /* properties */ RNA_def_boolean(ot->srna, "clear", 0, "Clear", "Clear pinning for the selection instead of setting it"); } /******************* select pinned operator ***************/ static int select_pinned_exec(bContext *C, wmOperator *UNUSED(op)) { Scene *scene= CTX_data_scene(C); Object *obedit= CTX_data_edit_object(C); Image *ima= CTX_data_edit_image(C); EditMesh *em= BKE_mesh_get_editmesh((Mesh*)obedit->data); EditFace *efa; MTFace *tface; for(efa= em->faces.first; efa; efa= efa->next) { tface = CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(uvedit_face_visible(scene, ima, efa, tface)) { if(tface->unwrap & TF_PIN1) uvedit_uv_select(scene, efa, tface, 0); if(tface->unwrap & TF_PIN2) uvedit_uv_select(scene, efa, tface, 1); if(tface->unwrap & TF_PIN3) uvedit_uv_select(scene, efa, tface, 2); if(efa->v4) { if(tface->unwrap & TF_PIN4) uvedit_uv_select(scene, efa, tface, 3); } } } WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data); BKE_mesh_end_editmesh(obedit->data, em); return OPERATOR_FINISHED; } static void UV_OT_select_pinned(wmOperatorType *ot) { /* identifiers */ ot->name= "Selected Pinned"; ot->description= "Select all pinned UV vertices"; ot->idname= "UV_OT_select_pinned"; ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; /* api callbacks */ ot->exec= select_pinned_exec; ot->poll= ED_operator_uvedit; } /********************** hide operator *********************/ static int hide_exec(bContext *C, wmOperator *op) { SpaceImage *sima= CTX_wm_space_image(C); ToolSettings *ts= CTX_data_tool_settings(C); Object *obedit= CTX_data_edit_object(C); EditMesh *em= BKE_mesh_get_editmesh((Mesh*)obedit->data); EditFace *efa; MTFace *tf; int swap= RNA_boolean_get(op->ptr, "unselected"); int facemode= sima ? sima->flag & SI_SELACTFACE : 0; if(ts->uv_flag & UV_SYNC_SELECTION) { EM_hide_mesh(em, swap); WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data); BKE_mesh_end_editmesh(obedit->data, em); return OPERATOR_FINISHED; } if(swap) { for(efa= em->faces.first; efa; efa= efa->next) { if(efa->f & SELECT) { tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(facemode) { /* Pretend face mode */ if(( (efa->v4==NULL && ( tf->flag & (TF_SEL1|TF_SEL2|TF_SEL3)) == (TF_SEL1|TF_SEL2|TF_SEL3) ) || ( tf->flag & (TF_SEL1|TF_SEL2|TF_SEL3|TF_SEL4)) == (TF_SEL1|TF_SEL2|TF_SEL3|TF_SEL4) ) == 0) { if(em->selectmode == SCE_SELECT_FACE) { efa->f &= ~SELECT; /* must re-select after */ efa->e1->f &= ~SELECT; efa->e2->f &= ~SELECT; efa->e3->f &= ~SELECT; if(efa->e4) efa->e4->f &= ~SELECT; } else EM_select_face(efa, 0); } tf->flag &= ~(TF_SEL1|TF_SEL2|TF_SEL3|TF_SEL4); } else if(em->selectmode == SCE_SELECT_FACE) { const char select_flag= efa->v4 ? (TF_SEL1|TF_SEL2|TF_SEL3|TF_SEL4) : (TF_SEL1|TF_SEL2|TF_SEL3); if((tf->flag & select_flag)==0) { EM_select_face(efa, 0); tf->flag &= ~(TF_SEL1|TF_SEL2|TF_SEL3|TF_SEL4); } } else { /* EM_deselect_flush will deselect the face */ if((tf->flag & TF_SEL1)==0) efa->v1->f &= ~SELECT; if((tf->flag & TF_SEL2)==0) efa->v2->f &= ~SELECT; if((tf->flag & TF_SEL3)==0) efa->v3->f &= ~SELECT; if((efa->v4) && (tf->flag & TF_SEL4)==0) efa->v4->f &= ~SELECT; tf->flag &= ~(TF_SEL1|TF_SEL2|TF_SEL3|TF_SEL4); } } } } else { for(efa= em->faces.first; efa; efa= efa->next) { if(efa->f & SELECT) { tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if(facemode) { if( (efa->v4==NULL && ( tf->flag & (TF_SEL1|TF_SEL2|TF_SEL3)) == (TF_SEL1|TF_SEL2|TF_SEL3) ) || ( tf->flag & (TF_SEL1|TF_SEL2|TF_SEL3|TF_SEL4)) == (TF_SEL1|TF_SEL2|TF_SEL3|TF_SEL4) ) { if(em->selectmode == SCE_SELECT_FACE) { efa->f &= ~SELECT; /* must re-select after */ efa->e1->f &= ~SELECT; efa->e2->f &= ~SELECT; efa->e3->f &= ~SELECT; if(efa->e4) efa->e4->f &= ~SELECT; } else EM_select_face(efa, 0); } tf->flag &= ~(TF_SEL1|TF_SEL2|TF_SEL3|TF_SEL4); } else if(em->selectmode == SCE_SELECT_FACE) { const char select_flag= efa->v4 ? (TF_SEL1|TF_SEL2|TF_SEL3|TF_SEL4) : (TF_SEL1|TF_SEL2|TF_SEL3); if(tf->flag & select_flag) EM_select_face(efa, 0); tf->flag &= ~(TF_SEL1|TF_SEL2|TF_SEL3|TF_SEL4); } else { /* EM_deselect_flush will deselect the face */ if(tf->flag & TF_SEL1) efa->v1->f &= ~SELECT; if(tf->flag & TF_SEL2) efa->v2->f &= ~SELECT; if(tf->flag & TF_SEL3) efa->v3->f &= ~SELECT; if((efa->v4) && tf->flag & TF_SEL4) efa->v4->f &= ~SELECT; tf->flag &= ~(TF_SEL1|TF_SEL2|TF_SEL3|TF_SEL4); } } } } /*deselects too many but ok for now*/ if(em->selectmode & (SCE_SELECT_EDGE|SCE_SELECT_VERTEX)) EM_deselect_flush(em); if(em->selectmode==SCE_SELECT_FACE) { /* de-selected all edges from faces that were de-selected. * now make sure all faces that are selected also have selected edges */ for(efa= em->faces.first; efa; efa= efa->next) if(efa->f & SELECT) EM_select_face(efa, 1); } EM_validate_selections(em); WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data); BKE_mesh_end_editmesh(obedit->data, em); return OPERATOR_FINISHED; } static void UV_OT_hide(wmOperatorType *ot) { /* identifiers */ ot->name= "Hide Selected"; ot->description= "Hide (un)selected UV vertices"; ot->idname= "UV_OT_hide"; ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; /* api callbacks */ ot->exec= hide_exec; ot->poll= ED_operator_uvedit; /* props */ RNA_def_boolean(ot->srna, "unselected", 0, "Unselected", "Hide unselected rather than selected"); } /****************** reveal operator ******************/ static int reveal_exec(bContext *C, wmOperator *UNUSED(op)) { SpaceImage *sima= CTX_wm_space_image(C); ToolSettings *ts= CTX_data_tool_settings(C); Object *obedit= CTX_data_edit_object(C); EditMesh *em= BKE_mesh_get_editmesh((Mesh*)obedit->data); EditFace *efa; MTFace *tf; int facemode= sima ? sima->flag & SI_SELACTFACE : 0; int stickymode= sima ? (sima->sticky != SI_STICKY_DISABLE) : 1; /* call the mesh function if we are in mesh sync sel */ if(ts->uv_flag & UV_SYNC_SELECTION) { EM_reveal_mesh(em); WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data); BKE_mesh_end_editmesh(obedit->data, em); return OPERATOR_FINISHED; } if(facemode) { if(em->selectmode == SCE_SELECT_FACE) { for(efa= em->faces.first; efa; efa= efa->next) { if(!(efa->h) && !(efa->f & SELECT)) { tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); EM_select_face(efa, 1); tf->flag |= TF_SEL1|TF_SEL2|TF_SEL3|TF_SEL4; } } } else { /* enable adjacent faces to have disconnected UV selections if sticky is disabled */ if(!stickymode) { for(efa= em->faces.first; efa; efa= efa->next) { if(!(efa->h) && !(efa->f & SELECT)) { /* All verts must be unselected for the face to be selected in the UV view */ if((efa->v1->f&SELECT)==0 && (efa->v2->f&SELECT)==0 && (efa->v3->f&SELECT)==0 && (efa->v4==NULL || (efa->v4->f&SELECT)==0)) { tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); tf->flag |= TF_SEL1|TF_SEL2|TF_SEL3|TF_SEL4; /* Cant use EM_select_face here because it unselects the verts * and we cant tell if the face was totally unselected or not */ /*EM_select_face(efa, 1); * * See Loop with EM_select_face() below... */ efa->f |= SELECT; } } } } else { for(efa= em->faces.first; efa; efa= efa->next) { if(!(efa->h) && !(efa->f & SELECT)) { tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if((efa->v1->f & SELECT)==0) {tf->flag |= TF_SEL1;} if((efa->v2->f & SELECT)==0) {tf->flag |= TF_SEL2;} if((efa->v3->f & SELECT)==0) {tf->flag |= TF_SEL3;} if((efa->v4 && (efa->v4->f & SELECT)==0)) {tf->flag |= TF_SEL4;} efa->f |= SELECT; } } } /* Select all edges and verts now */ for(efa= em->faces.first; efa; efa= efa->next) /* we only selected the face flags, and didnt changes edges or verts, fix this now */ if(!(efa->h) && (efa->f & SELECT)) EM_select_face(efa, 1); EM_select_flush(em); } } else if(em->selectmode == SCE_SELECT_FACE) { for(efa= em->faces.first; efa; efa= efa->next) { if(!(efa->h) && !(efa->f & SELECT)) { tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); efa->f |= SELECT; tf->flag |= TF_SEL1|TF_SEL2|TF_SEL3|TF_SEL4; } } /* Select all edges and verts now */ for(efa= em->faces.first; efa; efa= efa->next) /* we only selected the face flags, and didnt changes edges or verts, fix this now */ if(!(efa->h) && (efa->f & SELECT)) EM_select_face(efa, 1); } else { for(efa= em->faces.first; efa; efa= efa->next) { if(!(efa->h) && !(efa->f & SELECT)) { tf= CustomData_em_get(&em->fdata, efa->data, CD_MTFACE); if((efa->v1->f & SELECT)==0) {tf->flag |= TF_SEL1;} if((efa->v2->f & SELECT)==0) {tf->flag |= TF_SEL2;} if((efa->v3->f & SELECT)==0) {tf->flag |= TF_SEL3;} if((efa->v4 && (efa->v4->f & SELECT)==0)) {tf->flag |= TF_SEL4;} efa->f |= SELECT; } } /* Select all edges and verts now */ for(efa= em->faces.first; efa; efa= efa->next) /* we only selected the face flags, and didnt changes edges or verts, fix this now */ if(!(efa->h) && (efa->f & SELECT)) EM_select_face(efa, 1); } WM_event_add_notifier(C, NC_GEOM|ND_SELECT, obedit->data); BKE_mesh_end_editmesh(obedit->data, em); return OPERATOR_FINISHED; } static void UV_OT_reveal(wmOperatorType *ot) { /* identifiers */ ot->name= "Reveal Hidden"; ot->description= "Reveal all hidden UV vertices"; ot->idname= "UV_OT_reveal"; ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; /* api callbacks */ ot->exec= reveal_exec; ot->poll= ED_operator_uvedit; } /******************** set 3d cursor operator ********************/ static int set_2d_cursor_exec(bContext *C, wmOperator *op) { SpaceImage *sima = CTX_wm_space_image(C); float location[2]; if(!sima) return OPERATOR_CANCELLED; RNA_float_get_array(op->ptr, "location", location); sima->cursor[0]= location[0]; sima->cursor[1]= location[1]; WM_event_add_notifier(C, NC_SPACE|ND_SPACE_IMAGE, NULL); return OPERATOR_FINISHED; } static int set_2d_cursor_invoke(bContext *C, wmOperator *op, wmEvent *event) { ARegion *ar= CTX_wm_region(C); float location[2]; UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &location[0], &location[1]); RNA_float_set_array(op->ptr, "location", location); return set_2d_cursor_exec(C, op); } static void UV_OT_cursor_set(wmOperatorType *ot) { /* identifiers */ ot->name= "Set 2D Cursor"; ot->description= "Set 2D cursor location"; ot->idname= "UV_OT_cursor_set"; /* api callbacks */ ot->exec= set_2d_cursor_exec; ot->invoke= set_2d_cursor_invoke; ot->poll= ED_operator_image_active; /* requires space image */; /* flags */ ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; /* properties */ RNA_def_float_vector(ot->srna, "location", 2, NULL, -FLT_MAX, FLT_MAX, "Location", "Cursor location in normalised (0.0-1.0) coordinates", -10.0f, 10.0f); } /********************** set tile operator **********************/ static int set_tile_exec(bContext *C, wmOperator *op) { Image *ima= CTX_data_edit_image(C); int tile[2]; Object *obedit= CTX_data_edit_object(C); RNA_int_get_array(op->ptr, "tile", tile); if(uvedit_set_tile(obedit, ima, tile[0] + ima->xrep*tile[1])) { WM_event_add_notifier(C, NC_GEOM|ND_DATA, obedit->data); WM_event_add_notifier(C, NC_SPACE|ND_SPACE_IMAGE, NULL); return OPERATOR_FINISHED; } return OPERATOR_CANCELLED; } static int set_tile_invoke(bContext *C, wmOperator *op, wmEvent *event) { SpaceImage *sima= CTX_wm_space_image(C); Image *ima= CTX_data_edit_image(C); ARegion *ar= CTX_wm_region(C); float fx, fy; int tile[2]; if(!ima || !(ima->tpageflag & IMA_TILES)) return OPERATOR_CANCELLED; UI_view2d_region_to_view(&ar->v2d, event->mval[0], event->mval[1], &fx, &fy); if(fx >= 0.0f && fy >= 0.0f && fx < 1.0f && fy < 1.0f) { fx= fx*ima->xrep; fy= fy*ima->yrep; tile[0]= fx; tile[1]= fy; sima->curtile= tile[1]*ima->xrep + tile[0]; RNA_int_set_array(op->ptr, "tile", tile); } return set_tile_exec(C, op); } static void UV_OT_tile_set(wmOperatorType *ot) { /* identifiers */ ot->name= "Set Tile"; ot->description= "Set UV image tile coordinates"; ot->idname= "UV_OT_tile_set"; /* api callbacks */ ot->exec= set_tile_exec; ot->invoke= set_tile_invoke; ot->poll= ED_operator_image_active; /* requires space image */; /* flags */ ot->flag= OPTYPE_REGISTER|OPTYPE_UNDO; /* properties */ RNA_def_int_vector(ot->srna, "tile", 2, NULL, 0, INT_MAX, "Tile", "Tile coordinate", 0, 10); } /* ************************** registration **********************************/ void ED_operatortypes_uvedit(void) { WM_operatortype_append(UV_OT_select_all); WM_operatortype_append(UV_OT_select); WM_operatortype_append(UV_OT_select_loop); WM_operatortype_append(UV_OT_select_linked); WM_operatortype_append(UV_OT_select_linked_pick); WM_operatortype_append(UV_OT_unlink_selected); WM_operatortype_append(UV_OT_select_pinned); WM_operatortype_append(UV_OT_select_border); WM_operatortype_append(UV_OT_circle_select); WM_operatortype_append(UV_OT_snap_cursor); WM_operatortype_append(UV_OT_snap_selected); WM_operatortype_append(UV_OT_align); WM_operatortype_append(UV_OT_stitch); WM_operatortype_append(UV_OT_weld); WM_operatortype_append(UV_OT_pin); WM_operatortype_append(UV_OT_average_islands_scale); WM_operatortype_append(UV_OT_cube_project); WM_operatortype_append(UV_OT_cylinder_project); WM_operatortype_append(UV_OT_from_view); WM_operatortype_append(UV_OT_minimize_stretch); WM_operatortype_append(UV_OT_pack_islands); WM_operatortype_append(UV_OT_reset); WM_operatortype_append(UV_OT_sphere_project); WM_operatortype_append(UV_OT_unwrap); WM_operatortype_append(UV_OT_reveal); WM_operatortype_append(UV_OT_hide); WM_operatortype_append(UV_OT_cursor_set); WM_operatortype_append(UV_OT_tile_set); } void ED_keymap_uvedit(wmKeyConfig *keyconf) { wmKeyMap *keymap; wmKeyMapItem *kmi; keymap= WM_keymap_find(keyconf, "UV Editor", 0, 0); keymap->poll= ED_operator_uvedit; /* pick selection */ WM_keymap_add_item(keymap, "UV_OT_select", SELECTMOUSE, KM_PRESS, 0, 0); RNA_boolean_set(WM_keymap_add_item(keymap, "UV_OT_select", SELECTMOUSE, KM_PRESS, KM_SHIFT, 0)->ptr, "extend", 1); WM_keymap_add_item(keymap, "UV_OT_select_loop", SELECTMOUSE, KM_PRESS, KM_ALT, 0); RNA_boolean_set(WM_keymap_add_item(keymap, "UV_OT_select_loop", SELECTMOUSE, KM_PRESS, KM_SHIFT|KM_ALT, 0)->ptr, "extend", 1); /* border/circle selection */ WM_keymap_add_item(keymap, "UV_OT_select_border", BKEY, KM_PRESS, 0, 0); RNA_boolean_set(WM_keymap_add_item(keymap, "UV_OT_select_border", BKEY, KM_PRESS, KM_SHIFT, 0)->ptr, "pinned", 1); WM_keymap_add_item(keymap, "UV_OT_circle_select", CKEY, KM_PRESS, 0, 0); /* selection manipulation */ WM_keymap_add_item(keymap, "UV_OT_select_linked", LKEY, KM_PRESS, KM_CTRL, 0); WM_keymap_add_item(keymap, "UV_OT_select_linked_pick", LKEY, KM_PRESS, 0, 0); RNA_boolean_set(WM_keymap_add_item(keymap, "UV_OT_select_linked", LKEY, KM_PRESS, KM_CTRL|KM_SHIFT, 0)->ptr, "extend", TRUE); RNA_boolean_set(WM_keymap_add_item(keymap, "UV_OT_select_linked_pick", LKEY, KM_PRESS, KM_SHIFT, 0)->ptr, "extend", TRUE); WM_keymap_add_item(keymap, "UV_OT_unlink_selected", LKEY, KM_PRESS, KM_ALT, 0); WM_keymap_add_item(keymap, "UV_OT_select_all", AKEY, KM_PRESS, 0, 0); RNA_enum_set(WM_keymap_add_item(keymap, "UV_OT_select_all", IKEY, KM_PRESS, KM_CTRL, 0)->ptr, "action", SEL_INVERT); WM_keymap_add_item(keymap, "UV_OT_select_pinned", PKEY, KM_PRESS, KM_SHIFT, 0); WM_keymap_add_menu(keymap, "IMAGE_MT_uvs_weldalign", WKEY, KM_PRESS, 0, 0); /* uv operations */ WM_keymap_add_item(keymap, "UV_OT_stitch", VKEY, KM_PRESS, 0, 0); WM_keymap_add_item(keymap, "UV_OT_pin", PKEY, KM_PRESS, 0, 0); RNA_boolean_set(WM_keymap_add_item(keymap, "UV_OT_pin", PKEY, KM_PRESS, KM_ALT, 0)->ptr, "clear", 1); /* unwrap */ WM_keymap_add_item(keymap, "UV_OT_unwrap", EKEY, KM_PRESS, 0, 0); WM_keymap_add_item(keymap, "UV_OT_minimize_stretch", VKEY, KM_PRESS, KM_CTRL, 0); WM_keymap_add_item(keymap, "UV_OT_pack_islands", PKEY, KM_PRESS, KM_CTRL, 0); WM_keymap_add_item(keymap, "UV_OT_average_islands_scale", AKEY, KM_PRESS, KM_CTRL, 0); /* hide */ WM_keymap_add_item(keymap, "UV_OT_hide", HKEY, KM_PRESS, 0, 0); RNA_boolean_set(WM_keymap_add_item(keymap, "UV_OT_hide", HKEY, KM_PRESS, KM_SHIFT, 0)->ptr, "unselected", 1); WM_keymap_add_item(keymap, "UV_OT_reveal", HKEY, KM_PRESS, KM_ALT, 0); /* cursor */ WM_keymap_add_item(keymap, "UV_OT_cursor_set", ACTIONMOUSE, KM_PRESS, 0, 0); WM_keymap_add_item(keymap, "UV_OT_tile_set", ACTIONMOUSE, KM_PRESS, KM_SHIFT, 0); /* menus */ WM_keymap_add_menu(keymap, "IMAGE_MT_uvs_snap", SKEY, KM_PRESS, KM_SHIFT, 0); WM_keymap_add_menu(keymap, "IMAGE_MT_uvs_select_mode", TABKEY, KM_PRESS, KM_CTRL, 0); /* pivot */ kmi = WM_keymap_add_item(keymap, "WM_OT_context_set_enum", COMMAKEY, KM_PRESS, 0, 0); RNA_string_set(kmi->ptr, "data_path", "space_data.uv_editor.pivot_point"); RNA_string_set(kmi->ptr, "value", "CENTER"); kmi = WM_keymap_add_item(keymap, "WM_OT_context_set_enum", COMMAKEY, KM_PRESS, KM_CTRL, 0); RNA_string_set(kmi->ptr, "data_path", "space_data.uv_editor.pivot_point"); RNA_string_set(kmi->ptr, "value", "MEDIAN"); kmi = WM_keymap_add_item(keymap, "WM_OT_context_set_enum", PERIODKEY, KM_PRESS, 0, 0); RNA_string_set(kmi->ptr, "data_path", "space_data.uv_editor.pivot_point"); RNA_string_set(kmi->ptr, "value", "CURSOR"); ED_object_generic_keymap(keyconf, keymap, 2); transform_keymap_for_space(keyconf, keymap, SPACE_IMAGE); }
28.470868
154
0.638688
[ "mesh", "object", "3d" ]
11d689ec535ee4c3ebe307bf96a46fd23bab97b9
1,478
h
C
ModelViewer/ViewerFoundation/Render/NuoRenderPassAttachment.h
erpapa/NuoModelViewer
0dcb8bf99cb49c6e2c9535ed178e01674fa26824
[ "MIT" ]
265
2017-03-15T17:11:27.000Z
2022-03-30T07:50:00.000Z
ModelViewer/ViewerFoundation/Render/NuoRenderPassAttachment.h
erpapa/NuoModelViewer
0dcb8bf99cb49c6e2c9535ed178e01674fa26824
[ "MIT" ]
6
2017-07-03T01:57:49.000Z
2020-01-24T19:28:22.000Z
ModelViewer/ViewerFoundation/Render/NuoRenderPassAttachment.h
erpapa/NuoModelViewer
0dcb8bf99cb49c6e2c9535ed178e01674fa26824
[ "MIT" ]
39
2016-09-30T03:26:44.000Z
2022-01-24T07:37:20.000Z
// // NuoRenderPassAttachment.h // ModelViewer // // Created by Dong on 5/25/18. // Copyright © 2018 middleware. All rights reserved. // #import <Foundation/Foundation.h> #import <Metal/Metal.h> /** * attachment is the sum of all information and resources need for an attachment to start * a render pass (i.e. an encoder in Metal). it includes a texture (sometimes a frame buffer), * optionally with a resolving target (for MSAA), and the information such as clear color, * load/store action. */ enum NuoRenderPassAttachmentType { kNuoRenderPassAttachment_Color, kNuoRenderPassAttachment_Depth, }; @interface NuoRenderPassAttachment : NSObject @property (strong, nonatomic) NSString* name; @property (assign, nonatomic) CGSize drawableSize; @property (weak, nonatomic) id<MTLDevice> device; @property (assign, nonatomic) BOOL manageTexture; @property (assign, nonatomic) BOOL sharedTexture; @property (strong, nonatomic) id<MTLTexture> texture; @property (assign, nonatomic) MTLPixelFormat pixelFormat; @property (assign, nonatomic) NSUInteger sampleCount; @property (assign, nonatomic) BOOL needResolve; @property (assign, nonatomic) BOOL needStore; @property (assign, nonatomic) BOOL needClear; @property (assign, nonatomic) BOOL needWrite; @property (assign, nonatomic) MTLClearColor clearColor; @property (assign, nonatomic) NuoRenderPassAttachmentType type; - (void)makeTexture; - (MTLRenderPassAttachmentDescriptor*)descriptor; @end
25.929825
95
0.764547
[ "render" ]
ccd1d5f49e4fe32022879413ed9ed335015c6911
10,922
h
C
src/Tetromino.h
eugen-schaefer/Tetris
1f73f332c312e4500e2ea0e7a52e8944ea8fe6f6
[ "MIT" ]
null
null
null
src/Tetromino.h
eugen-schaefer/Tetris
1f73f332c312e4500e2ea0e7a52e8944ea8fe6f6
[ "MIT" ]
null
null
null
src/Tetromino.h
eugen-schaefer/Tetris
1f73f332c312e4500e2ea0e7a52e8944ea8fe6f6
[ "MIT" ]
null
null
null
#ifndef TETROMINO_H_ #define TETROMINO_H_ #include <map> #include <string> #include <utility> #include <vector> #include "IGridLogic.h" enum class Direction { left, right, down }; enum class Color { cyan, // (0x00FFFF) blue, // (0x0000FF) orange, // (0xFF8040) yellow, // (0xFFFF00) green, // (0x00FF00) magenta, // (0xFF00FF) red // (0xFF0000) }; enum class TetrominoType { I, J, L, O, S, T, Z, UNDEFINED }; enum class Orientation { north, east, south, west }; using TetrominoPositionType = std::vector<std::pair<int, int>>; using LogicalSquaresIteratorType = TetrominoPositionType::iterator; TetrominoPositionType operator+(const TetrominoPositionType &position1, const TetrominoPositionType &position2); /// Tetromino class is the base class for all seven tetromino shapes. It /// provides common properties like color and actions like a move in a certain /// direction for all shapes. class Tetromino { public: /// No default constructor provided to enforce creating shapes with a fixed /// number of squares. Tetromino() = delete; /// Creates a tetromino consisting of exactly four squares clearly /// determined by their positions in the grid. /// \param grid_logic: a reference to the logical grid to determine /// tetrominoes' unambiguous position in the grid. /// \param init_position: unambiguous position in the grid where the created /// tetromino is initially placed. Tetromino(IGridLogic &grid_logic, TetrominoPositionType init_position, Color color); /// Retrieves tetrominoes' color. /// \return tetrominoes' color virtual Color GetColor() const { return m_color; } /// Retrieves tetrominoes' position. /// \return position of every tetromino square virtual TetrominoPositionType GetPosition() const { return m_position; } /// SetPositionInDashboard is supposed to be used only to set the tetromino /// in the dashboard. Since SetPosition() places shapes on the grid /// regardless of the grid occupancy at the corresponding place, the /// MoveOneStep() shall be used for game usage instead. /// \param target_position: Position in the logical grid at which the /// Tetromino is to be placed. virtual void SetPosition(TetrominoPositionType target_position) { m_position = std::move(target_position); } /// Moves the tetromino one step towards a specified direction /// \param direction: direction towards which the movement shall take place. /// \return returns true when the movement was successful, false otherwise. virtual bool MoveOneStep(Direction direction); /// Determines whether the tetronimo is locked down or not /// \return true if tetromino is locked down and hence unmovable, false /// otherwise virtual bool IsLocked() const { return m_is_locked; } /// Lock tetromino such that it cant be moved or rotated. virtual void LockDown() { m_is_locked = true; }; /// Unlock tetromino such that it can be moved or rotated. virtual void Release() { m_is_locked = false; }; /// Rotates the concrete shape clockwise virtual void Rotate() {} /// Deletes one specified square within the tetromino initially consisting /// of four squares. This function is supposed to be used in line clearing /// cases. /// \param logical_iterator: iterator to the square being deleted virtual void DeleteTetrominoSquare( LogicalSquaresIteratorType &logical_iterator); /// Retrieved the iterator to tetrominoes first square. virtual LogicalSquaresIteratorType GetIteratorToBeginOfPositionVector() { return m_position.begin(); }; /// Retrieves the information about the concrete shape. Since the base class /// is not meant to represent a concrete shape, its type is undefined. virtual TetrominoType GetTetrominoType() { return TetrominoType::UNDEFINED; }; protected: TetrominoPositionType m_position; IGridLogic &m_grid_logic; private: Color m_color; // m_is_locked indicates whether the tetromino can be moved or not. When // the object is instantiated, the m_is_locked is false and consequently // the tetromino can be moved. Once tetromino has riched the lowest obstacle // (be it the lower grid bound or other tetrominos located already at the // bottom of the grid) m_is_locked is switched to true and hence the // tetromino can't be moved anymore because it's locked down. bool m_is_locked; }; /// The ShapeI class represents concrete shape I. Apart from inherited methods, /// it provides in addition a concrete implementation of the shape rotation. class ShapeI : public Tetromino { public: ShapeI() = delete; ShapeI(IGridLogic &grid_logic, TetrominoPositionType init_position = { {0, 0}, {0, 1}, {0, 2}, {0, 3}}); Orientation GetOrientation() { return m_orientation; } void Rotate() override; TetrominoType GetTetrominoType() override { return m_tetromino_type; }; private: const std::map<std::string, TetrominoPositionType> m_delta_positions{ {"NorthEast", {{-2, 2}, {-1, 1}, {0, 0}, {1, -1}}}, {"EastSouth", {{2, 1}, {1, 0}, {0, -1}, {-1, -2}}}, {"SouthWest", {{1, -2}, {0, -1}, {-1, 0}, {-2, 1}}}, {"WestNorth", {{-1, -1}, {0, 0}, {1, 1}, {2, 2}}}}; Orientation m_orientation; TetrominoType m_tetromino_type; }; /// The ShapeJ class represents concrete shape J. Apart from inherited methods, /// it provides in addition a concrete implementation of the shape rotation. class ShapeJ : public Tetromino { public: ShapeJ() = delete; ShapeJ(IGridLogic &grid_logic, TetrominoPositionType init_position = { {0, 0}, {1, 0}, {1, 1}, {1, 2}}); Orientation GetOrientation() { return m_orientation; } void Rotate() override; TetrominoType GetTetrominoType() override { return m_tetromino_type; }; private: const std::map<std::string, TetrominoPositionType> m_delta_positions{ {"NorthEast", {{0, 2}, {-1, 1}, {0, 0}, {1, -1}}}, {"EastSouth", {{2, 0}, {1, 1}, {0, 0}, {-1, -1}}}, {"SouthWest", {{0, -2}, {1, -1}, {0, 0}, {-1, 1}}}, {"WestNorth", {{-2, 0}, {-1, -1}, {0, 0}, {1, 1}}}}; Orientation m_orientation; TetrominoType m_tetromino_type; }; /// The ShapeL class represents concrete shape L. Apart from inherited methods, /// it provides in addition a concrete implementation of the shape rotation. class ShapeL : public Tetromino { public: ShapeL() = delete; ShapeL(IGridLogic &grid_logic, TetrominoPositionType init_position = { {1, 0}, {1, 1}, {1, 2}, {0, 2}}); Orientation GetOrientation() { return m_orientation; } void Rotate() override; TetrominoType GetTetrominoType() override { return m_tetromino_type; }; private: const std::map<std::string, TetrominoPositionType> m_delta_positions{ {"NorthEast", {{2, 0}, {-1, 1}, {0, 0}, {1, -1}}}, {"EastSouth", {{0, -2}, {1, 1}, {0, 0}, {-1, -1}}}, {"SouthWest", {{-2, 0}, {-1, -1}, {0, 0}, {1, 1}}}, {"WestNorth", {{0, 2}, {1, -1}, {0, 0}, {-1, 1}}}}; Orientation m_orientation; TetrominoType m_tetromino_type; }; /// The ShapeO class represents concrete shape O. Apart from inherited methods, /// it provides in addition a concrete implementation of the shape rotation. class ShapeO : public Tetromino { public: ShapeO() = delete; ShapeO(IGridLogic &grid_logic, TetrominoPositionType init_position = { {0, 0}, {0, 1}, {1, 1}, {1, 0}}); Orientation GetOrientation() { return m_orientation; } void Rotate() override; TetrominoType GetTetrominoType() override { return m_tetromino_type; }; private: Orientation m_orientation; TetrominoType m_tetromino_type; }; /// The ShapeS class represents concrete shape S. Apart from inherited methods, /// it provides in addition a concrete implementation of the shape rotation. class ShapeS : public Tetromino { public: ShapeS() = delete; ShapeS(IGridLogic &grid_logic, TetrominoPositionType init_position = { {0, 1}, {0, 2}, {1, 1}, {1, 0}}); Orientation GetOrientation() { return m_orientation; } void Rotate() override; TetrominoType GetTetrominoType() override { return m_tetromino_type; }; private: const std::map<std::string, TetrominoPositionType> m_delta_positions{ {"NorthEast", {{1, 1}, {2, 0}, {0, 0}, {-1, 1}}}, {"EastSouth", {{1, -1}, {0, -2}, {0, 0}, {1, 1}}}, {"SouthWest", {{-1, -1}, {-2, 0}, {0, 0}, {1, -1}}}, {"WestNorth", {{-1, 1}, {0, 2}, {0, 0}, {-1, -1}}}}; Orientation m_orientation; TetrominoType m_tetromino_type; }; /// The ShapeT class represents concrete shape T. Apart from inherited methods, /// it provides in addition a concrete implementation of the shape rotation. class ShapeT : public Tetromino { public: ShapeT() = delete; ShapeT(IGridLogic &grid_logic, TetrominoPositionType init_position = { {0, 1}, {1, 0}, {1, 1}, {1, 2}}); Orientation GetOrientation() { return m_orientation; } void Rotate() override; TetrominoType GetTetrominoType() override { return m_tetromino_type; }; private: const std::map<std::string, TetrominoPositionType> m_delta_positions{ {"NorthEast", {{0, 0}, {0, 2}, {0, 0}, {1, -1}}}, {"EastSouth", {{2, 0}, {0, 0}, {0, 0}, {-1, -1}}}, {"SouthWest", {{-1, -1}, {1, -1}, {0, 0}, {-1, 1}}}, {"WestNorth", {{-1, 1}, {-1, -1}, {0, 0}, {1, 1}}}}; Orientation m_orientation; TetrominoType m_tetromino_type; }; /// The ShapeZ class represents concrete shape Z. Apart from inherited methods, /// it provides in addition a concrete implementation of the shape rotation. class ShapeZ : public Tetromino { public: ShapeZ() = delete; ShapeZ(IGridLogic &grid_logic, TetrominoPositionType init_position = { {0, 0}, {0, 1}, {1, 1}, {1, 2}}); Orientation GetOrientation() { return m_orientation; } void Rotate() override; TetrominoType GetTetrominoType() override { return m_tetromino_type; }; private: const std::map<std::string, TetrominoPositionType> m_delta_positions{ {"NorthEast", {{0, 2}, {1, 1}, {0, 0}, {1, -1}}}, {"EastSouth", {{2, 0}, {1, -1}, {0, 0}, {-1, -1}}}, {"SouthWest", {{0, -2}, {-1, -1}, {0, 0}, {-1, 1}}}, {"WestNorth", {{-2, 0}, {-1, 1}, {0, 0}, {1, 1}}}}; Orientation m_orientation; TetrominoType m_tetromino_type; }; #endif /* TETROMINO_H_ */
41.06015
80
0.635506
[ "object", "shape", "vector" ]
ccd2728c9fbd8f73d12fe842f07c6e7eff3aa8a5
4,614
h
C
Engine/Source/Editor/BehaviorTreeEditor/Classes/BehaviorTreeGraphNode.h
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
Engine/Source/Editor/BehaviorTreeEditor/Classes/BehaviorTreeGraphNode.h
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
2
2015-06-21T17:38:11.000Z
2015-06-22T20:54:42.000Z
Engine/Source/Editor/BehaviorTreeEditor/Classes/BehaviorTreeGraphNode.h
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #pragma once #include "AIGraphNode.h" #include "BehaviorTreeEditorTypes.h" #include "BehaviorTreeGraphNode.generated.h" UCLASS() class UBehaviorTreeGraphNode : public UAIGraphNode { GENERATED_UCLASS_BODY() /** only some of behavior tree nodes support decorators */ UPROPERTY() TArray<UBehaviorTreeGraphNode*> Decorators; /** only some of behavior tree nodes support services */ UPROPERTY() TArray<UBehaviorTreeGraphNode*> Services; // Begin UEdGraphNode Interface virtual class UBehaviorTreeGraph* GetBehaviorTreeGraph(); virtual void AllocateDefaultPins() override; virtual FText GetTooltipText() const override; virtual bool CanCreateUnderSpecifiedSchema(const UEdGraphSchema* DesiredSchema) const override; virtual void FindDiffs(class UEdGraphNode* OtherNode, struct FDiffResults& Results) override; // End UEdGraphNode Interface virtual FText GetDescription() const override; virtual bool HasErrors() const override; virtual void InitializeInstance() override; virtual void OnSubNodeAdded(UAIGraphNode* SubNode) override; virtual void OnSubNodeRemoved(UAIGraphNode* SubNode) override; virtual void RemoveAllSubNodes() override; virtual int32 FindSubNodeDropIndex(UAIGraphNode* SubNode) const override; virtual void InsertSubNodeAt(UAIGraphNode* SubNode, int32 DropIndex) override; /** check if node can accept breakpoints */ virtual bool CanPlaceBreakpoints() const { return false; } void ClearDebuggerState(); /** gets icon resource name for title bar */ virtual FName GetNameIcon() const; /** if set, this node was injected from subtree and shouldn't be edited */ UPROPERTY() uint32 bInjectedNode : 1; /** if set, this node is root of tree or sub node of it */ uint32 bRootLevel : 1; /** if set, observer setting is invalid (injected nodes only) */ uint32 bHasObserverError : 1; /** highlighting nodes in abort range for more clarity when setting up decorators */ uint32 bHighlightInAbortRange0 : 1; /** highlighting nodes in abort range for more clarity when setting up decorators */ uint32 bHighlightInAbortRange1 : 1; /** highlighting connections in search range for more clarity when setting up decorators */ uint32 bHighlightInSearchRange0 : 1; /** highlighting connections in search range for more clarity when setting up decorators */ uint32 bHighlightInSearchRange1 : 1; /** highlighting nodes during quick find */ uint32 bHighlightInSearchTree : 1; /** highlight other child node indexes when hovering over a child */ uint32 bHighlightChildNodeIndices : 1; /** debugger flag: breakpoint exists */ uint32 bHasBreakpoint : 1; /** debugger flag: breakpoint is enabled */ uint32 bIsBreakpointEnabled : 1; /** debugger flag: mark node as active (current state) */ uint32 bDebuggerMarkCurrentlyActive : 1; /** debugger flag: mark node as active (browsing previous states) */ uint32 bDebuggerMarkPreviouslyActive : 1; /** debugger flag: briefly flash active node */ uint32 bDebuggerMarkFlashActive : 1; /** debugger flag: mark as succeeded search path */ uint32 bDebuggerMarkSearchSucceeded : 1; /** debugger flag: mark as failed on search path */ uint32 bDebuggerMarkSearchFailed : 1; /** debugger flag: mark as trigger of search path */ uint32 bDebuggerMarkSearchTrigger : 1; /** debugger flag: mark as trigger of discarded search path */ uint32 bDebuggerMarkSearchFailedTrigger : 1; /** debugger flag: mark as going to parent */ uint32 bDebuggerMarkSearchReverseConnection : 1; /** debugger flag: mark stopped on this breakpoint */ uint32 bDebuggerMarkBreakpointTrigger : 1; /** debugger variable: index on search path */ int32 DebuggerSearchPathIndex; /** debugger variable: number of nodes on search path */ int32 DebuggerSearchPathSize; /** debugger variable: incremented on change of debugger flags for render updates */ int32 DebuggerUpdateCounter; /** used to show node's runtime description rather than static one */ FString DebuggerRuntimeDescription; protected: /** creates add decorator... submenu */ void CreateAddDecoratorSubMenu(class FMenuBuilder& MenuBuilder, UEdGraph* Graph) const; /** creates add service... submenu */ void CreateAddServiceSubMenu(class FMenuBuilder& MenuBuilder, UEdGraph* Graph) const; /** add right click menu to create subnodes: Decorators */ void AddContextMenuActionsDecorators(const FGraphNodeContextMenuBuilder& Context) const; /** add right click menu to create subnodes: Services */ void AddContextMenuActionsServices(const FGraphNodeContextMenuBuilder& Context) const; };
34.432836
96
0.771998
[ "render" ]
ccd2d1b5b9d81e859782423aa6043d16b01c6ac2
1,952
h
C
Engine/Simulation/SortedParticlesUniform3D.h
jmhong-simulation/LithopiaOpen
49c4c0863714ee11730e4807eb10c1e1ebb520f1
[ "MIT" ]
8
2017-06-01T07:00:10.000Z
2021-12-16T11:01:29.000Z
Engine/Simulation/SortedParticlesUniform3D.h
jmhong-simulation/LithopiaOpen
49c4c0863714ee11730e4807eb10c1e1ebb520f1
[ "MIT" ]
null
null
null
Engine/Simulation/SortedParticlesUniform3D.h
jmhong-simulation/LithopiaOpen
49c4c0863714ee11730e4807eb10c1e1ebb520f1
[ "MIT" ]
null
null
null
// The Lithopia project initiated by Jeong-Mo Hong for 3D Printing Community. // Copyright (c) 2015 Jeong-Mo Hong - All Rights Reserved. // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. #pragma once #include <atomic> #include "DataStructure/Array1D.h" #include "DataStructure/GridUniform3D.h" #include "Parallelism/MultiThreading.h" //#include "SIM_DOMAIN_UNIFORM_3D.h" #include "ParticleDataPV3D.h" template<class T_PARTICLE_DATA_ARRAYS> class SortedParticlesUniform3D { public: // SIM_DOMAIN_UNIFORM_3D domain_; GridUniform3D grid_; T_PARTICLE_DATA_ARRAYS particle_data_arrays_; // reallocated at the head of rebuilding step for exact number of particles to save memory. T_PARTICLE_DATA_ARRAYS particle_data_arrays_temp_; // deleted at the end of rebuilding step to save memory. std::atomic<int>* pts_id_list_; std::atomic<int>* pts_index_list_; std::atomic<int>* num_pts_array_; // the number of particles contained in each cell //TODO: define as integer, use casted as atomic<int> int* pts_start_ix_array_; // the start index of the particle data arrays of the first particle in each cell int num_all_pts_; // number of all particles. newly created particles are not included until data structure is rebuilt. std::atomic<int> count_pts_num_; std::atomic<int> count_pts_start_ix_; public: SortedParticlesUniform3D() : num_pts_array_(0), pts_start_ix_array_(0) {} ~SortedParticlesUniform3D() {} public: void initialize(GridUniform3D& grid_input); void sortThread(); void sort(MT* mt, const int& thread_id); void prepareForSorting(MT* mt, const int& thread_id); void buildNumPtsArray(MT* mt, const int& thread_id); void buildPtsStartIxArray(MT* mt, const int& thread_id); void copyParticles(MT* mt, const int& thread_id); void finalizeSorting(MT* mt, const int& thread_id); };
36.830189
140
0.753586
[ "3d" ]
ccf906e30c256398412e9d966a5f3081cc19e9a9
1,029
h
C
samples/videorecorder/app/MaskView.h
reubenscratton/oaknut
03b37965ad84745bd5c077a27d8b53d58a173662
[ "MIT" ]
5
2019-10-04T05:10:06.000Z
2021-02-03T23:29:10.000Z
samples/videorecorder/app/MaskView.h
reubenscratton/oaknut
03b37965ad84745bd5c077a27d8b53d58a173662
[ "MIT" ]
null
null
null
samples/videorecorder/app/MaskView.h
reubenscratton/oaknut
03b37965ad84745bd5c077a27d8b53d58a173662
[ "MIT" ]
2
2019-09-27T00:34:36.000Z
2020-10-27T09:44:26.000Z
// // IdaaS // // Copyright © 2018 PQ. All rights reserved. // #pragma once #include <oaknut.h> class MaskView : public View { public: MaskView(); enum HoleShape { None, Rect, Oval }; void setHoleShape(HoleShape shape); void setHoleStrokeColour(COLOR color); void setHoleFillColour(COLOR color); RECT getHoleRect() const; // Overrides virtual void layout(RECT constraint) override; //virtual void setBackgroundColour(COLOR color, int duration); protected: bool applySingleStyle(const string& name, const style& value) override; COLOR _backgroundColour; HoleShape _holeShape; MEASURESPEC _holeWidthMeasureSpec; MEASURESPEC _holeHeightMeasureSpec; ALIGNSPEC _holeAlignSpecX; ALIGNSPEC _holeAlignSpecY; RECT _holeRect; COLOR _holeStrokeColour; COLOR _holeFillColour; float _holeStrokeWidth; float _holeCornerRadius; sp<Animation> _strokeColorAnim; friend class MaskRenderOp; };
21
75
0.685131
[ "shape" ]
ccfd14f3ef7c3c923dd5a0b6329b5ddcd5a0905d
6,115
h
C
Plugins/PLVolumeRenderer/src/RaySetup/Hybrid_GLSL.h
ktotheoz/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
83
2015-01-08T15:06:14.000Z
2021-07-20T17:07:00.000Z
Plugins/PLVolumeRenderer/src/RaySetup/Hybrid_GLSL.h
PixelLightFoundation/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
27
2019-06-18T06:46:07.000Z
2020-02-02T11:11:28.000Z
Plugins/PLVolumeRenderer/src/RaySetup/Hybrid_GLSL.h
naetherm/PixelLight
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
40
2015-02-25T18:24:34.000Z
2021-03-06T09:01:48.000Z
/*********************************************************\ * File: Hybrid_GLSL.h * * Vertex and fragment shader source code - GLSL (OpenGL 3.3 ("#version 330") * * Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/) * * This file is part of PixelLight. * * 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. \*********************************************************/ //[-------------------------------------------------------] //[ Define helper macro ] //[-------------------------------------------------------] #define STRINGIFY(ME) #ME //[-------------------------------------------------------] //[ Vertex shader source code ] //[-------------------------------------------------------] static const PLCore::String sSourceCode_Vertex = STRINGIFY( // Attributes in vec3 VertexPosition; // Object space vertex position input in vec3 VertexTexCoord; // Vertex texture coordinate input out vec3 VertexTexCoordVS; // Vertex texture coordinate output // Uniforms uniform mat4 ObjectSpaceToClipSpaceMatrix; // Object space to clip space matrix // Programs void main() { // Calculate the clip space vertex position, lower/left is (-1,-1) and upper/right is (1,1) gl_Position = ObjectSpaceToClipSpaceMatrix*vec4(VertexPosition, 1.0); // Pass through the vertex texture coordinate VertexTexCoordVS = VertexTexCoord; } ); // STRINGIFY //[-------------------------------------------------------] //[ Fragment shader source code ] //[-------------------------------------------------------] static const PLCore::String sSourceCode_Fragment_Header = STRINGIFY( // Attributes in vec3 VertexTexCoordVS; // Interpolated vertex texture coordinate input from vertex shader, the position (volume object space) the ray leaves the volume layout(location = 0) out vec4 OutFragmentColor; // Resulting fragment color // Uniforms uniform vec3 RayOrigin; // Ray origin in volume object space uniform float StepSize; // Step size ); // STRINGIFY static const PLCore::String sSourceCode_Fragment = STRINGIFY( // Programs void main() { // The position (volume object space) the ray leaves the volume is provided by the vertex shader vec3 rayEndPosition = VertexTexCoordVS; // Get normalized ray direction in volume object space vec3 rayDirection = normalize(rayEndPosition - RayOrigin); // Calculate the distance our ray travels through the volume float maximumTravelLength; { // Intersect ray with a cube (http://www.siggraph.org/education/materials/HyperGraph/raytrace/rtinter3.htm) // Compute intersection of ray with all six bbox planes // (due overhead we don't test for division by zero) vec3 tbot = (vec3(0.0, 0.0, 0.0) - RayOrigin) / rayDirection; vec3 ttop = (vec3(1.0, 1.0, 1.0) - RayOrigin) / rayDirection; // Re-order intersections to find smallest and largest on each axis vec3 tmin = min(ttop, tbot); vec3 tmax = max(ttop, tbot); // Find the largest tmin and the smallest tmax float near = max(max(tmin.x, tmin.y), max(tmin.x, tmin.z)); float far = min(min(tmax.x, tmax.y), min(tmax.x, tmax.z)); // Clamp near if (near < 0.0) near = 0.0; // [DEBUG] Fragment color = [0, 1] -> 1 (white) if there was an intersection, else 0 (black) -> result should always be white because we're drawing a cube in order to generate the rays // OutFragmentColor = (far > near) ? vec4(1.0, 1.0, 1.0, 1.0) : vec4(0.0, 0.0, 0.0, 1.0); return; // Calculate the distance our ray travels through the volume maximumTravelLength = far - near; } // Calculate the position (volume object space) the ray enters the volume vec3 rayStartPosition = rayEndPosition - rayDirection*maximumTravelLength; // Calculate the position advance per step along the ray vec3 stepPositionDelta = rayDirection*StepSize; // Call the clip ray function // void ClipRay(inout vec3 RayOrigin, vec3 RayDirection, inout float MaximumTravelLength) ClipRay(rayStartPosition, rayDirection, maximumTravelLength); // Call the jitter position function to add jittering to the start position of the ray in order to reduce wooden grain effect // float JitterPosition(vec3 Position) rayStartPosition += stepPositionDelta*JitterPosition(rayStartPosition); // Call the ray traversal function // vec4 RayTraversal(vec3 StartPosition, int NumberOfSteps, vec3 StepPositionDelta, float MaximumTravelLength) // -> Clamp the result to [0, 1] interval, else the image might flicker ugly on NVIDIA GPU's while working fine on AMD GPU'S (HDR only issue) OutFragmentColor = (maximumTravelLength > 0.0) ? clamp(RayTraversal(rayStartPosition, int(maximumTravelLength/StepSize), stepPositionDelta, maximumTravelLength), vec4(0.0, 0.0, 0.0, 0.0), vec4(1.0, 1.0, 1.0, 1.0)) : vec4(0.0, 0.0, 0.0, 0.0); } ); // STRINGIFY //[-------------------------------------------------------] //[ Undefine helper macro ] //[-------------------------------------------------------] #undef STRINGIFY
46.325758
242
0.650368
[ "object" ]
690295fc262985b522680af9e88ffbc30469f943
5,973
h
C
src/fdm/utils/fdm_VectorN.h
paperoga-dev/mscsim
a5bd3b88745bf8d91e85fd001b0972662ff8e410
[ "MIT" ]
null
null
null
src/fdm/utils/fdm_VectorN.h
paperoga-dev/mscsim
a5bd3b88745bf8d91e85fd001b0972662ff8e410
[ "MIT" ]
null
null
null
src/fdm/utils/fdm_VectorN.h
paperoga-dev/mscsim
a5bd3b88745bf8d91e85fd001b0972662ff8e410
[ "MIT" ]
null
null
null
/****************************************************************************//* * Copyright (C) 2021 Marek M. Cel * * 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 FDM_VECTORN_H #define FDM_VECTORN_H //////////////////////////////////////////////////////////////////////////////// #include <fdm/fdm_Defines.h> #include <fdm/fdm_Exception.h> #include <fdm/fdm_Types.h> //////////////////////////////////////////////////////////////////////////////// namespace fdm { /** * @brief N elements dynamic allocated vector class. */ class FDMEXPORT VectorN { public: /** @brief Constructor. */ VectorN(); /** * @brief Constructor. * @param size vector size */ VectorN( unsigned int size ); /** @brief Copy constructor. */ VectorN( const VectorN &vect ); /** @brief Destructor. */ virtual ~VectorN(); /** @return TRUE if all items are valid */ virtual bool isValid() const; /** @return vector length */ virtual double getLength() const; /** @brief This function normalizes vector. */ virtual void normalize(); /** @brief uts vector items into given array. */ virtual void getArray( double items[] ) const; /** * @brief Gets vector item of given indicies. * This function is bound-checked which may affect performance. * Throws an exception when index is out of range. * @return vector item of given indicies. */ virtual double getItem( unsigned int index ) const; /** @brief Sets vector items from given array. */ virtual void setArray( const double items[] ); /** * @brief Sets vector item of given indicies. * This function is bound-checked which may affect performance. * Throws an exception when index is out of range. */ virtual void setItem( unsigned int index, double val ); virtual void setValue( double val ); /** * @brief Returns vector size (number of elements) * @return vector size (number of elements) */ inline unsigned int getSize() const { return _size; } /** @brief Returns string representation of the vector. */ virtual std::string toString() const; /** @brief Resizes vector if needed. */ virtual void resize( unsigned int size ); /** @brief Sets all vector items to zero. */ virtual void zeroize(); /** * @brief Items accessor. * Please notice that this operator is NOT bound-checked. * If you want bound-checked item accessor use getItem(int) or * setItem(int,double) functions. */ inline double operator() ( unsigned int index ) const { # ifdef _DEBUG if ( index >= _size ) { Exception e; e.setType( Exception::ArrayIndexOverLimit ); e.setInfo( "Index over limit." ); FDM_THROW( e ); } # endif return _items[ index ]; } /** * @brief Items accessor. * Please notice that this operator is NOT bound-checked. * If you want bound-checked item accessor use getItem(int) or * setItem(int,double) functions. */ inline double& operator() ( unsigned int index ) { # ifdef _DEBUG if ( index >= _size ) { Exception e; e.setType( Exception::ArrayIndexOverLimit ); e.setInfo( "Index over limit." ); FDM_THROW( e ); } # endif return _items[ index ]; } /** @brief Assignment operator. */ const VectorN& operator= ( const VectorN &vect ); /** @brief Addition operator. */ VectorN operator+ ( const VectorN &vect ) const; /** @brief Negation operator. */ VectorN operator- () const; /** @brief Subtraction operator. */ VectorN operator- ( const VectorN &vect ) const; /** @brief Multiplication operator (by scalar). */ VectorN operator* ( double val ) const; /** @brief Division operator (by scalar). */ VectorN operator/ ( double val ) const; /** @brief Unary addition operator. */ VectorN& operator+= ( const VectorN &vect ); /** @brief Unary subtraction operator. */ VectorN& operator-= ( const VectorN &vect ); /** @brief Unary multiplication operator (by scalar). */ VectorN& operator*= ( double val ); /** @brief Unary division operator (by scalar). */ VectorN& operator/= ( double val ); protected: unsigned int _size; ///< vector size double *_items; ///< vector items }; } // end of fdm namespace //////////////////////////////////////////////////////////////////////////////// /** @brief Multiplication operator (by scalar). */ inline fdm::VectorN operator* ( double val, const fdm::VectorN & vect ) { return ( vect * val ); } //////////////////////////////////////////////////////////////////////////////// #endif // FDM_VECTORN_H
29.716418
80
0.588147
[ "vector" ]
69039a9b04a7c6dc68d976383c04e529c5b47583
818
h
C
src/dx11/xGSinput.h
livingcreative/xgs
2fc51c8b8f04e23740466414092f0ca1e0acb436
[ "BSD-3-Clause" ]
6
2016-03-17T16:11:39.000Z
2021-02-08T18:03:23.000Z
src/dx11/xGSinput.h
livingcreative/xgs
2fc51c8b8f04e23740466414092f0ca1e0acb436
[ "BSD-3-Clause" ]
6
2016-07-15T07:02:44.000Z
2018-05-24T20:39:57.000Z
src/dx11/xGSinput.h
livingcreative/xgs
2fc51c8b8f04e23740466414092f0ca1e0acb436
[ "BSD-3-Clause" ]
4
2016-03-20T11:43:11.000Z
2022-01-21T21:07:54.000Z
/* xGS 3D Low-level rendering API Low-level 3D rendering wrapper API with multiple back-end support (c) livingcreative, 2015 - 2018 https://github.com/livingcreative/xgs dx11/xGSinput.h Input object implementation class header this object binds source of geometry data with state object */ #pragma once #include "xGSimplbase.h" namespace xGS { // input object class xGSInputImpl : public xGSObjectBase<xGSInputBase, xGSImpl> { public: xGSInputImpl(xGSImpl *owner); ~xGSInputImpl() override; public: GSbool AllocateImpl(GSuint elementbuffers); void apply(const GScaps &caps); void ReleaseRendererResources(); private: // TODO: define DX11 input internal objects }; } // namespace xGS
19.47619
71
0.658924
[ "geometry", "object", "3d" ]
6910e15798b5e62dc0e2b5344dca5947e104bba1
726
c
C
src/core/object/cfunc/cfunc.c
binflowq/xesael
a23cd6ebe999b580ce7e39432d2b1a5c7c7a7394
[ "MIT" ]
1
2020-10-26T11:07:33.000Z
2020-10-26T11:07:33.000Z
src/core/object/cfunc/cfunc.c
binflowq/xesael
a23cd6ebe999b580ce7e39432d2b1a5c7c7a7394
[ "MIT" ]
null
null
null
src/core/object/cfunc/cfunc.c
binflowq/xesael
a23cd6ebe999b580ce7e39432d2b1a5c7c7a7394
[ "MIT" ]
null
null
null
/* File: cfunc.c */ /* Creation date: 2017-02-05 */ /* Creator: Dmitry Guzeev <dmitry.guzeev@yahoo.com> */ /* Description: */ /* The CFunc object */ #include "core/object/cfunc/cfunc.h" #include "lib/types.h" #include "lib/xmalloc.h" #include "lib/xvec.h" #include "core/object/object.h" struct CFuncArguments* cfunc_args_new(void) { struct CFuncArguments* args = xmalloc(sizeof(*args)); if (!args) return NULL; xvec_init(&args->args, obj_free_f); return args; } NoRet cfunc_args_append(struct CFuncArguments* args, struct Object const* arg) { xvec_append(&args->args, CAST(arg, void*)); } struct Object const* cfunc_args_get(struct CFuncArguments* args, const uint64 i) { return xvec_get(&args->args, i); }
22.6875
80
0.706612
[ "object" ]
691191121d3bde7f65ec93ead1af856316534034
274
h
C
WARProfile/Classes/Favorite/View/WARTestViewController.h
qinkai2060/Moya-MVVM
d723d350de80ecc6a188dc231a88566f4493fec4
[ "MIT" ]
null
null
null
WARProfile/Classes/Favorite/View/WARTestViewController.h
qinkai2060/Moya-MVVM
d723d350de80ecc6a188dc231a88566f4493fec4
[ "MIT" ]
null
null
null
WARProfile/Classes/Favorite/View/WARTestViewController.h
qinkai2060/Moya-MVVM
d723d350de80ecc6a188dc231a88566f4493fec4
[ "MIT" ]
null
null
null
// // WARTestViewController.h // WARProfile // // Created by 秦恺 on 2018/5/31. // #import <UIKit/UIKit.h> #import "WARProfileUserModel.h" @interface WARTestViewController : UIViewController /** model */ @property (nonatomic, strong) WARProfileMasksModel *maskModel; @end
19.571429
62
0.733577
[ "model" ]
691210d91cf426ba994a6e6cceb7b1173dfba3fe
619
h
C
src/network.h
pratikunterwegs/pathomove
be6b509442d975909bae2a46cc01d94e74e32a41
[ "MIT" ]
1
2022-03-16T11:20:02.000Z
2022-03-16T11:20:02.000Z
src/network.h
pratikunterwegs/pathomove
be6b509442d975909bae2a46cc01d94e74e32a41
[ "MIT" ]
1
2022-01-18T12:08:44.000Z
2022-01-18T12:08:44.000Z
src/network.h
pratikunterwegs/pathomove
be6b509442d975909bae2a46cc01d94e74e32a41
[ "MIT" ]
1
2022-01-18T20:29:28.000Z
2022-01-18T20:29:28.000Z
#pragma once #include <vector> #include <cassert> #include <Rcpp.h> using namespace Rcpp; /// the network structure, which holds an adjacency matrix // network should be a member of population later // network has funs to return network metrics and the adj matrix struct Network { public: Network(const int popsize) : nVertices(popsize), adjMat (popsize, popsize) {} ~Network() {} // members const int nVertices; Rcpp::NumericMatrix adjMat; // functions Rcpp::DataFrame getNtwkDf(); // std::vector<float> ntwkMeasures(); // std::vector<int> getDegree(); };
20.633333
64
0.66559
[ "vector" ]
692097befb54c38f93abf7f98e12fc286e9cb293
615
h
C
Game Engine/GameEngine/src/graphics/3D/component_types.h
llGuy/gamedev
16aa203934fd767926c58558e021630288556399
[ "MIT" ]
null
null
null
Game Engine/GameEngine/src/graphics/3D/component_types.h
llGuy/gamedev
16aa203934fd767926c58558e021630288556399
[ "MIT" ]
4
2018-12-24T11:16:53.000Z
2018-12-24T11:20:29.000Z
Game Engine/GameEngine/src/graphics/3D/component_types.h
llGuy/gamedev
16aa203934fd767926c58558e021630288556399
[ "MIT" ]
null
null
null
#pragma once #include <vector> #include <glm/glm.hpp> #include "../../api/api.h" struct vertex_buffer_component { buffer value; }; struct vertices_component { std::vector<glm::vec3> vertices; }; struct normal_buffer_component { buffer value; }; struct color_buffer_component { buffer value; }; struct texture_buffer_component { buffer value; }; struct index_buffer_component { buffer value; }; struct texture_component { texture value; u32 point; }; struct weights_buffer_component { buffer value; }; struct joint_ids_buffer_component { buffer value; }; /* in 3D, there will basically always be an index buffer */
38.4375
63
0.764228
[ "vector", "3d" ]
6928bca822465c52a0c96134ff5fc0574fd2cc44
1,882
c
C
tests/api/test-def-prop-convenience.c
jacobmarshall-etc/duktape
62ef74d0dd64edcd518c588dd88780ea4312144a
[ "MIT" ]
2
2019-10-15T06:01:16.000Z
2019-12-21T14:32:50.000Z
tests/api/test-def-prop-convenience.c
KiraanRK/esp32-duktape
1b7fbcb8bd6bfc346d92df30ec099df7f13b03aa
[ "MIT" ]
null
null
null
tests/api/test-def-prop-convenience.c
KiraanRK/esp32-duktape
1b7fbcb8bd6bfc346d92df30ec099df7f13b03aa
[ "MIT" ]
null
null
null
/* * duk_def_prop() convenience flags, added in Duktape 1.4.0. */ /*=== *** test_basic (duk_safe_call) {value:undefined,writable:true,enumerable:true,configurable:true} {value:undefined,writable:false,enumerable:true,configurable:true} {value:undefined,writable:false,enumerable:false,configurable:true} {value:undefined,writable:false,enumerable:false,configurable:false} {value:undefined,writable:false,enumerable:false,configurable:true} {value:undefined,writable:false,enumerable:true,configurable:true} {value:undefined,writable:true,enumerable:true,configurable:true} final top: 1 ==> rc=0, result='undefined' ===*/ static void dump_prop(duk_context *ctx) { duk_eval_string(ctx, "(function (obj) {\n" " print(Duktape.enc('jx', Object.getOwnPropertyDescriptor(obj, 'prop')));\n" "})"); duk_dup(ctx, 0); duk_call(ctx, 1); duk_pop(ctx); } static duk_ret_t test_basic(duk_context *ctx, void *udata) { (void) udata; duk_push_object(ctx); duk_push_string(ctx, "prop"); duk_def_prop(ctx, -2, DUK_DEFPROP_SET_WRITABLE | DUK_DEFPROP_SET_ENUMERABLE | DUK_DEFPROP_SET_CONFIGURABLE); dump_prop(ctx); duk_push_string(ctx, "prop"); duk_def_prop(ctx, -2, DUK_DEFPROP_CLEAR_WRITABLE); dump_prop(ctx); duk_push_string(ctx, "prop"); duk_def_prop(ctx, -2, DUK_DEFPROP_CLEAR_ENUMERABLE); dump_prop(ctx); duk_push_string(ctx, "prop"); duk_def_prop(ctx, -2, DUK_DEFPROP_CLEAR_CONFIGURABLE); dump_prop(ctx); duk_push_string(ctx, "prop"); duk_def_prop(ctx, -2, DUK_DEFPROP_SET_CONFIGURABLE | DUK_DEFPROP_FORCE); dump_prop(ctx); duk_push_string(ctx, "prop"); duk_def_prop(ctx, -2, DUK_DEFPROP_SET_ENUMERABLE); dump_prop(ctx); duk_push_string(ctx, "prop"); duk_def_prop(ctx, -2, DUK_DEFPROP_SET_WRITABLE); dump_prop(ctx); printf("final top: %ld\n", (long) duk_get_top(ctx)); return 0; } void test(duk_context *ctx) { TEST_SAFE_CALL(test_basic); }
27.676471
109
0.752922
[ "object" ]
692910336653aa6b6e50012d7107339d3f550d0d
534
h
C
ember/src/scenes/scene_manager.h
L4ZZA/pyro
37302aaa3739c5092ea852d4abbc5aafc3eb3815
[ "MIT" ]
null
null
null
ember/src/scenes/scene_manager.h
L4ZZA/pyro
37302aaa3739c5092ea852d4abbc5aafc3eb3815
[ "MIT" ]
null
null
null
ember/src/scenes/scene_manager.h
L4ZZA/pyro
37302aaa3739c5092ea852d4abbc5aafc3eb3815
[ "MIT" ]
null
null
null
#pragma once #include "renderer/scene.h" #include <vector> class scene_manager { public: void add_scene(pyro::ref<scene> scene); // initializes the current scene. void init_first_scene(); void next_scene(); void previous_scene(); void go_to(int scene_index); pyro::ref<scene> current_scene() const; void on_update(pyro::timestep const &ts); void on_render() const; void on_event(pyro::event &e); void on_imgui_render(); private: std::vector<pyro::ref<scene>> m_scenes; int m_scene_index = -1; };
22.25
43
0.698502
[ "vector" ]
693af62b475296e454f8342e7c690d91918fab7b
2,608
h
C
include/kiui/Object/mkProto.h
mflagel/asdf_multiplat
9ef5a87b9ea9e38a7c6d409a60a1b8c5dce4b015
[ "MIT" ]
null
null
null
include/kiui/Object/mkProto.h
mflagel/asdf_multiplat
9ef5a87b9ea9e38a7c6d409a60a1b8c5dce4b015
[ "MIT" ]
null
null
null
include/kiui/Object/mkProto.h
mflagel/asdf_multiplat
9ef5a87b9ea9e38a7c6d409a60a1b8c5dce4b015
[ "MIT" ]
null
null
null
// Copyright (c) 2015 Hugo Amiard hugo.amiard@laposte.net // This software is provided 'as-is' under the zlib License, see the LICENSE.txt file. // This notice and the license may not be removed or altered from any source distribution. #ifndef MK_PROTO_H_INCLUDED #define MK_PROTO_H_INCLUDED /* mk */ #include <Object/mkObjectForward.h> #include <Object/mkStem.h> #include <Object/mkIndexer.h> /* Standard */ #include <map> #include <unordered_map> #include <unordered_set> namespace mk { struct ProtoPart { public: ProtoPart() : type(0), index(0) {} Type* type; size_t index; }; /* A Proto represent a fixed layout of parts for an object, allowing for fast part query It is a broader definition of a type, different from the C++ class, it defines a finite object with a finite set of capabilities, which is a sum of components : its parts The parts are members of a prototype, whereas additionnal components are called plugs, and are not part of the object in itself : they can be here or not here, whereas the parts are always here */ class MK_OBJECT_EXPORT _I_ _S_ Proto : public IdObject, public Indexed<Proto> { public: _C_ Proto(Type* type); void init(Type* stem, std::vector<Type*> parts) { mStem = stem; for(Type* type : parts) addPart(*type); } _A_ Type* prototype() { return mType; } _A_ Type* stem() { return mStem; } _A_ const std::vector<Type*>& parts() const { return mParts; } _A_ Id id() const { return mId; } inline void addPart(Type& type) { mHashParts[type.id()].type = &type; mHashParts[type.id()].index = mNumParts++; mParts.push_back(&type); } inline bool hasPart(Type& type) { return (mHashParts[type.id()].type != 0); } inline int partIndex(Type& type) { return mHashParts[type.id()].index; } inline size_t numParts() { return mNumParts; } static Type& cls() { static Type ty; return ty; } protected: Type* mType; Type* mStem; size_t mNumParts; std::vector<ProtoPart> mHashParts; std::vector<Type*> mParts; }; class MK_OBJECT_EXPORT ProtoChunk { public: virtual ~ProtoChunk() {} }; template <class T, class... Parts> class Prototyped { public: static Proto* proto() { return &sProto; } private: static Proto sProto; }; template <class T, class... Parts> Proto Prototyped<T, Parts...>::sProto(T::cls()); template <class T, class S, class... Parts> class TPrototype : public Part, public Indexed<T>, public Prototyped<T, Parts...> { public: TPrototype(Stem* stem) : Part(T::cls(), stem) {} static Type& cls() { static Type ty; return ty; } }; } #endif // MK_PROTO_INCLUDED
27.744681
141
0.692485
[ "object", "vector" ]
69452b3fe91201b020893b46d7b4b442ad67e8bd
876
h
C
RecoTracker/TkMSParametrization/src/MSLayersKeeperX0AtEta.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
13
2015-11-30T15:49:45.000Z
2022-02-08T16:11:30.000Z
RecoTracker/TkMSParametrization/src/MSLayersKeeperX0AtEta.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
640
2015-02-11T18:55:47.000Z
2022-03-31T14:12:23.000Z
RecoTracker/TkMSParametrization/src/MSLayersKeeperX0AtEta.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
51
2015-08-11T21:01:40.000Z
2022-03-30T07:31:34.000Z
#ifndef MSLayersKeeperX0AtEta_H #define MSLayersKeeperX0AtEta_H #include "MSLayersKeeper.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Utilities/interface/Visibility.h" class SumX0AtEtaDataProvider; class MSLayersKeeperX0Averaged; class dso_hidden MSLayersKeeperX0AtEta final : public MSLayersKeeper { public: MSLayersKeeperX0AtEta() : isInitialised(false) {} ~MSLayersKeeperX0AtEta() override {} void init(const edm::EventSetup &iSetup) override; const MSLayersAtAngle &layers(float cotTheta) const override; private: float eta(int idxBin) const; int idxBin(float eta) const; static void setX0(std::vector<MSLayer> &, float eta, const SumX0AtEtaDataProvider &); private: bool isInitialised; int theHalfNBins; float theDeltaEta; std::vector<MSLayersAtAngle> theLayersData; friend class MSLayersKeeperX0Averaged; }; #endif
28.258065
87
0.794521
[ "vector" ]
694985f1d7f4bac16d762201925e500eb1335492
22,957
h
C
CsWeapon/Source/CsWp/Public/Managers/Weapon/CsManager_Weapon.h
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
2
2019-03-17T10:43:53.000Z
2021-04-20T21:24:19.000Z
CsWeapon/Source/CsWp/Public/Managers/Weapon/CsManager_Weapon.h
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
CsWeapon/Source/CsWp/Public/Managers/Weapon/CsManager_Weapon.h
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
// Copyright 2017-2021 Closed Sum Games, LLC. All Rights Reserved. #pragma once #include "UObject/Object.h" #include "Managers/Pool/CsManager_PooledObject_Map.h" #include "Managers/Resource/CsManager_ResourceValueType.h" #include "Payload/CsPayload_Weapon.h" #include "CsWeapon.h" #include "CsWeaponPooled.h" #include "Managers/Weapon/CsSettings_Manager_Weapon.h" #include "CsManager_Weapon.generated.h" // Delegates #pragma region DECLARE_DYNAMIC_MULTICAST_DELEGATE_TwoParams(FCsManagerWeapon_OnSpawn, const FECsWeapon&, Type, TScriptInterface<ICsWeapon>, Weapon); #pragma endregion Delegates // Internal #pragma region class ICsWeapon; namespace NCsWeapon { #define ManagerMapType NCsPooledObject::NManager::TTMap #define PayloadType NCsWeapon::NPayload::IPayload class CSWP_API FManager : public ManagerMapType<ICsWeapon, FCsWeaponPooled, PayloadType, FECsWeapon> { private: typedef ManagerMapType<ICsWeapon, FCsWeaponPooled, PayloadType, FECsWeapon> Super; public: FManager(); FORCEINLINE virtual const FString& KeyTypeToString(const FECsWeapon& Type) const override { return Type.GetName(); } FORCEINLINE virtual bool IsValidKey(const FECsWeapon& Type) const override { return EMCsWeapon::Get().IsValidEnum(Type); } }; #undef ManagerMapType #undef PayloadType } #pragma endregion Internal class ICsGetManagerWeapon; // NCsWeapon::NData::IData CS_FWD_DECLARE_STRUCT_NAMESPACE_2(NCsWeapon, NData, IData) // NCsWeapon::NData::FInterfaceMap CS_FWD_DECLARE_STRUCT_NAMESPACE_2(NCsWeapon, NData, FInterfaceMap) // NCsPooledObject::NManager::NHandler::TClass namespace NCsPooledObject { namespace NManager { namespace NHandler { template<typename InterfacePooledContainerType, typename InterfaceUStructContainerType, typename EnumType> class TClass; } } } // NCsPooledObject::NManager::NHandler::TData namespace NCsPooledObject { namespace NManager { namespace NHandler { template<typename InterfaceDataType, typename DataContainerType, typename DataInterfaceMapType> class TData; } } } struct FCsInterfaceMap; // NCsWeapon::NData::FInterfaceMap CS_FWD_DECLARE_STRUCT_NAMESPACE_2(NCsWeapon, NData, FInterfaceMap) class UDataTable; struct FCsWeaponPtr; struct FCsProjectileWeaponPtr; UCLASS() class CSWP_API UCsManager_Weapon : public UObject { GENERATED_UCLASS_BODY() #define ManagerType NCsWeapon::FManager #define ManagerParamsType NCsWeapon::FManager::FParams #define ConstructParamsType NCsPooledObject::NManager::FConstructParams #define PayloadType NCsWeapon::NPayload::IPayload #define ClassHandlerType NCsPooledObject::NManager::NHandler::TClass #define DataHandlerType NCsPooledObject::NManager::NHandler::TData #define DataType NCsWeapon::NData::IData public: // Singleton #pragma region public: #if WITH_EDITOR static UCsManager_Weapon* Get(UObject* InRoot = nullptr); #else FORCEINLINE static UCsManager_Weapon* Get(UObject* InRoot = nullptr) { return s_bShutdown ? nullptr : s_Instance; } #endif // #if WITH_EDITOR template<typename T> static T* Get(UObject* InRoot = nullptr) { return Cast<T>(Get(InRoot)); } #if WITH_EDITOR static bool IsValid(UObject* InRoot = nullptr); #else FORCEINLINE static bool IsValid(UObject* InRoot = nullptr) { return s_Instance != nullptr; } #endif // #if WITH_EDITOR static void Init(UObject* InRoot, TSubclassOf<UCsManager_Weapon> ManagerWeaponClass, UObject* InOuter = nullptr); static void Shutdown(UObject* InRoot = nullptr); static bool HasShutdown(UObject* InRoot = nullptr); #if WITH_EDITOR protected: static ICsGetManagerWeapon* Get_GetManagerWeapon(UObject* InRoot); static ICsGetManagerWeapon* GetSafe_GetManagerWeapon(UObject* Object); static UCsManager_Weapon* GetSafe(UObject* Object); public: static UCsManager_Weapon* GetFromWorldContextObject(const UObject* WorldContextObject); #endif // #if WITH_EDITOR protected: bool bInitialized; virtual void Initialize(); public: static bool HasInitialized(UObject* InRoot); protected: virtual void CleanUp(); private: // Singleton data static UCsManager_Weapon* s_Instance; static bool s_bShutdown; // Root #pragma region protected: UObject* MyRoot; void SetMyRoot(UObject* InRoot); public: FORCEINLINE UObject* GetMyRoot() { return MyRoot; } #pragma endregion Root #pragma endregion Singleton // Settings #pragma region protected: FCsSettings_Manager_Weapon Settings; /** */ TArray<FECsWeapon> TypeMapArray; public: FORCEINLINE void SetSettings(const FCsSettings_Manager_Weapon& InSettings) { Settings = InSettings; } /** * If SET, * - Get the type this Weapon has been mapped to for pooling. * i.e. If the weapon is completely data driven, then many weapons could share * the same class. * If NOT set, * - Return the same type. * * @param Type * return Weapon Type */ FORCEINLINE const FECsWeapon& GetTypeFromTypeMap(const FECsWeapon& Type) { return TypeMapArray[Type.GetValue()]; } #pragma endregion Settings // Internal #pragma region protected: /** Reference to the internal manager for handling the pool of projectiles. */ ManagerType Internal; /** * Setup the internal manager for handling the pool of projectiles. */ virtual void SetupInternal(); public: /** * */ void InitInternalFromSettings(); /** * * * @param Params */ void InitInternal(const ManagerParamsType& Params); virtual void Clear(); // Pool #pragma region public: /** * * @param Type * @param Size */ virtual void CreatePool(const FECsWeapon& Type, const int32& Size); /** * * * return */ TDelegate<FCsWeaponPooled*(const FECsWeapon&)>& GetConstructContainer_Impl(); /** * * @param Type * return */ virtual FCsWeaponPooled* ConstructContainer(const FECsWeapon& Type); /** * * * @param Type * return */ TMulticastDelegate<void(const FCsWeaponPooled*, const ConstructParamsType&)>& GetOnConstructObject_Event(const FECsWeapon& Type); // Add #pragma region // Pool #pragma region public: /** * Adds an Object to the pool for the appropriate Type. * The Object must implement the interface: ICsWeapon. * * @param Type Type of pool to add the Object to. * @param PooledObject Object that implements the interface: ICsWeapon. * @param Object UObject reference. * return Container holding a reference to a pooled object. * Pooled Object implements the interface: ICsWeapon. */ const FCsWeaponPooled* AddToPool(const FECsWeapon& Type, ICsWeapon* Object); /** * Adds an Object to the pool for the appropriate Type. * Object must implement the interface: ICsWeapon. * * @param Type Type of pool to add the Object to. * @param Object Object that implements the interface: ICsWeapon. * return Container holding a reference to a pooled object. * Pooled Object implements the interface: ICsWeapon. */ const FCsWeaponPooled* AddToPool(const FECsWeapon& Type, const FCsWeaponPooled* Object); /** * Adds an Object to the pool for the appropriate Type. * Object must implement the interface: ICsWeapon or the UClass * associated with the Object have ImplementsInterface(UCsWeapon::StaticClass()) == true. * * @param Type Type of the pool to add the object to. * @param Object Object or Object->GetClass() that implements the interface: ICsWeapon. * return Container holding a reference to a pooled object. * Pooled Object or UClass associated with Pooled Object implements * the interface: ICsWeapon. */ const FCsWeaponPooled* AddToPool(const FECsWeapon& Type, UObject* Object); #pragma endregion Pool // Allocated Objects #pragma region public: /** * Adds an Object to the allocated objects for the appropriate Type. * If the Object is NOT added to the pool, add it to the pool. * Object must implement the interface: ICsWeapon. * * @param Type Type of pool to add the Object to. * @param PooledObject Object that implements the interface: ICsWeapon. * @param Object UObject reference. * return Container holding a reference to a pooled object. * Pooled Object implements the interface: ICsWeapon. */ const FCsWeaponPooled* AddToAllocatedObjects(const FECsWeapon& Type, ICsWeapon* PooledObject, UObject* Object); /** * Adds an Object to the allocated objects for the appropriate Type. * If the Object is NOT added to the pool, add it to the pool. * Object must implement the interface: ICsWeapon. * * @param Type Type of pool to add the Object to. * @param Object Object that implements the interface: ICsWeapon. * return Container holding a reference to a pooled object. * Pooled Object implements the interface: ICsWeapon. */ const FCsWeaponPooled* AddToAllocatedObjects(const FECsWeapon& Type, ICsWeapon* Object); /** * Adds an Object to the allocated objects for the appropriate Type. * If the Object is NOT added to the pool, add it to the pool. * Object must implement the interface: ICsWeapon or the UClass * associated with the Object have ImplementsInterface(UCsWeapon::StaticClass()) == true. * * @param Type Type of pool to add the Object to. * @param Object Object or Object->GetClass() that implements the interface: ICsWeapon. * return Container holding a reference to a pooled object. * Pooled Object or UClass associated with Pooled Object implements * the interface: ICsWeapon. */ const FCsWeaponPooled* AddToAllocatedObjects(const FECsWeapon& Type, UObject* Object); #pragma endregion Allocated Objects #pragma endregion Add public: /** * Get the pool for the appropriate Type. * Pool is an array of containers holding references to objects that * implement the interface: ICsWeapon. * * @param Type Type of pool to get. * return Pool associated with the type. */ const TArray<FCsWeaponPooled*>& GetPool(const FECsWeapon& Type); /** * Get the allocated objects for the appropriate Type. * Allocated Objects are an array of containers holding references to objects that * implement the interface: ICsWeapon. * * @param Type Type of allocated objects to get. * return Allocated Objects associated with the Type. */ const TArray<FCsWeaponPooled*>& GetAllocatedObjects(const FECsWeapon& Type); /** * Get the number of elements in the pool for the appropriate Type. * * * @param Type Type of pool. * return Number of elements in the pool for the associated Type. */ const int32& GetPoolSize(const FECsWeapon& Type); /** * Get the number of allocated objects for the appropriate Type. * * @param Type Type of allocated objects. * return Number of allocated objects for the associated Type. */ int32 GetAllocatedObjectsSize(const FECsWeapon& Type); /** * Get whether all elements in the pool for the appropriate Type * have been allocated. * @ @param Type Type of pool to check against. * return All elements allocated or not. */ bool IsExhausted(const FECsWeapon& Type); // Find #pragma region public: /** * Find the container holding reference to a pooled object from the pool * for the appropriate Type by Index. * * @param Type Type of pool to add the Object to. * @param Index Index of the pooled object. * return Container holding a reference to a pooled object. * Pooled Object implements the interface: ICsWeapon. */ const FCsWeaponPooled* FindObject(const FECsWeapon& Type, const int32& Index); /** * Find the container holding a reference to a pooled object in the pool * for the appropriate Type by Interface. * Object must implement the interface: ICsWeapon. * * @param Type Type of pool to add the Object to. * @param Object Object of interface type: ICsWeapon. * return Container holding a reference to a pooled object. * Pooled Object implements the interface: ICsWeapon. */ const FCsWeaponPooled* FindObject(const FECsWeapon& Type, ICsWeapon* Object); /** * Find the container holding a reference to a pooled object in the pool * for the appropriate Type by UObject. * Object must implement the interface: ICsWeapon or the UClass * associated with the Object have ImplementsInterface(UCsWeapon::StaticClass()) == true. * * @param Type Type of pool to add the Object to. * @param Object Object or Object->GetClass() that implements the interface: ICsWeapon. * return Container holding a reference to a pooled object. * Pooled Object or UClass associated with Pooled Object implements * the interface: ICsWeapon. */ const FCsWeaponPooled* FindObject(const FECsWeapon& Type, UObject* Object); /** * Safely, via checks, find the container holding a reference to a pooled object in the pool * for the appropriate Type by Index. * * @param Type Type of pool to add the Object to. * @param Index Index of the pooled object. * return Container holding a reference to a pooled object. * Pooled Object implements the interface: ICsWeapon. */ const FCsWeaponPooled* FindSafeObject(const FECsWeapon& Type, const int32& Index); /** * Safely, via checks, find the container holding a reference to a pooled object in the pool * for the appropriate Type by the Interface. * * @param Type Type of pool to add the Object to. * @param Object Object that implements the interface: ICsWeapon. * return Container holding a reference to a pooled object. * Pooled Object implements the interface: ICsWeapon. */ const FCsWeaponPooled* FindSafeObject(const FECsWeapon& Type, ICsWeapon* Object); /** * Safely, via checks, find the container holding a reference to a pooled object in the pool * for the appropriate Type by the UObject. * * @param Type Type of pool to add the Object to. * @param Object Object or Object->GetClass() that implements the interface: ICsWeapon. * return Container holding a reference to a pooled object. * Pooled Object or UClass associated with Pooled Object implements * the interface: ICsWeapon. */ const FCsWeaponPooled* FindSafeObject(const FECsWeapon& Type, UObject* Object); #pragma endregion Find #pragma endregion Pool // Update #pragma region public: virtual void Update(const FCsDeltaTime& DeltaTime); private: FECsWeapon CurrentUpdatePoolType; int32 CurrentUpdatePoolObjectIndex; protected: void OnPreUpdate_Pool(const FECsWeapon& Type); void OnUpdate_Object(const FECsWeapon& Type, const FCsWeaponPooled* Object); void OnPostUpdate_Pool(const FECsWeapon& Type); #pragma endregion Update // Payload #pragma region public: /** * * * @param Size */ void ConstructPayloads(const FECsWeapon& Type, const int32& Size); /** * * * @param Type * return */ virtual PayloadType* ConstructPayload(const FECsWeapon& Type); /** * Get a payload object from a pool of payload objects for the appropriate Type. * Payload implements the interface: NCsWeapon::NPayload::IPayload. * * @param Type Type of payload. * return Payload that implements the interface: NCsWeapon::NPayload::IPayload. */ PayloadType* AllocatePayload(const FECsWeapon& Type); #pragma endregion Payload // Spawn #pragma region public: /** * * * @param Type * @param Payload */ const FCsWeaponPooled* Spawn(const FECsWeapon& Type, PayloadType* Payload); /** * Delegate type after a Weapon has been Spawned. * * @param Type * @param Object */ DECLARE_MULTICAST_DELEGATE_TwoParams(FOnSpawn, const FECsWeapon& /*Type*/, const FCsWeaponPooled* /*Object*/); /** */ FOnSpawn OnSpawn_Event; /** */ FCsManagerWeapon_OnSpawn OnSpawn_ScriptEvent; #pragma endregion Spawn // Destroy #pragma region public: /** * * * @param Type * @param Weapon * return */ virtual bool Destroy(const FECsWeapon& Type, ICsWeapon* Weapon); virtual bool Destroy(ICsWeapon* Weapon); /** * Delegate type after a Weapon has been Destroyed. * * @param Type * @param Object */ DECLARE_MULTICAST_DELEGATE_TwoParams(FOnDestroy, const FECsWeapon& /*Type*/, const FCsWeaponPooled* /*Object*/); FOnDestroy OnDestroy_Event; #pragma endregion Destroy // Log #pragma region protected: void Log(const FString& Str); void LogTransaction(const FString& Context, const ECsPoolTransaction& Transaction, const FCsWeaponPooled* Object); #pragma endregion Log #pragma endregion Internal // Pool #pragma region protected: UPROPERTY() TArray<UObject*> Pool; #pragma endregion Pool // Script #pragma region public: // ICsWeapon #pragma region public: /** Delegate for getting the Data of type: NCsWeapon::NData::IData a Weapon is using. The Projectile implements a script interface of type: ICsWeapon. */ FCsWeaponPooled::FScript_GetData Script_GetData_Impl; /** Delegate for getting the current state of a Weapon. The Weapon implements a script interface of type: ICsWeapon. */ FCsWeaponPooled::FScript_GetCurrentState Script_GetCurrentState_Impl; #pragma endregion ICsWeapon // ICsPooledObject #pragma region public: /** Delegate for getting the Cache associated with a Pooled Object. The Pooled Object implements a script interface of type: ICsPooledObject. */ FCsPooledObject::FScript_GetCache Script_GetCache_Impl; /** Delegate called after allocating a Pooled Object. The Pooled Object implements a script interface of type: ICsPooledObject. */ FCsPooledObject::FScript_Allocate Script_Allocate_Impl; /** Delegate called after allocating a Pooled Object. The Pooled Object implements a script interface of type: ICsPooledObject.*/ FCsPooledObject::FScript_Deallocate Script_Deallocate_Impl; #pragma endregion ICsPooledObject // ICsUpdate #pragma region public: /** Delegate for updating a Pooled Object. The Pooled Object implements a script interface of type: ICsPooledObject. */ FCsPooledObject::FScript_Update Script_Update_Impl; #pragma endregion ICsUpdate #pragma endregion Script // Class #pragma region protected: ClassHandlerType<FCsWeapon, FCsWeaponPtr, FECsWeaponClass>* ClassHandler; virtual void ConstructClassHandler(); public: /** * Get the Weapon container (Interface (ICsWeapon), UObject, and / or UClass) associated * with the weapon Type. * * @param Type Type of the weapon. * return Weapon container (Interface (ICsWeapon), UObject, and / or UClass). */ FCsWeapon* GetWeapon(const FECsWeapon& Type); /** * Get the Weapon container (Interface (ICsWeapon), UObject, and / or UClass) associated * with the weapon Type. * "Checked" in regards to returning a valid pointer. * * @param Context The calling context. * @param Type Type of the weapon. * return Weapon container (Interface (ICsWeapon), UObject, and / or UClass). */ FCsWeapon* GetWeaponChecked(const FString& Context, const FECsWeapon& Type); /** * Safely get the Weapon container (Interface (ICsWeapon), UObject, and / or UClass) associated * with the weapon Type. * * @param Context The calling context. * @param Type Type of the weapon. * return Weapon container (Interface (ICsWeapon), UObject, and / or UClass). */ FCsWeapon* GetSafeWeapon(const FString& Context, const FECsWeapon& Type); /** * Get the Weapon container (Interface (ICsWeapon), UObject, and / or UClass) associated * with the weapon class Type. * * @param Type Class type of the weapon. * return Weapon container (Interface (ICsWeapon), UObject, and / or UClass). */ FCsWeapon* GetWeapon(const FECsWeaponClass& Type); /** * Get the Weapon container (Interface (ICsWeapon), UObject, and / or UClass) associated * with the weapon class Type. * "Checked" in regards to returning a valid pointer. * * @param Context The calling context. * @param Type Class type of the weapon. * return Weapon container (Interface (ICsWeapon), UObject, and / or UClass). */ FCsWeapon* GetWeaponChecked(const FString& Context, const FECsWeaponClass& Type); /** * Safely get the Weapon container (Interface (ICsWeapon), UObject, and / or UClass) associated * with the weapon class Type. * * @param Context The calling context. * @param Type Class type of the weapon. * return Weapon container (Interface (ICsWeapon), UObject, and / or UClass). */ FCsWeapon* GetSafeWeapon(const FString& Context, const FECsWeaponClass& Type); bool SafeAddClass(const FString& Context, const FECsWeapon& Type, UObject* Class); bool SafeAddClass(const FString& Context, const FECsWeaponClass& Type, UObject* Class); #pragma endregion Class // Data #pragma region protected: #define DataInterfaceMapType NCsWeapon::NData::FInterfaceMap DataHandlerType<DataType, FCsData_WeaponPtr, DataInterfaceMapType>* DataHandler; virtual void ConstructDataHandler(); public: FORCEINLINE DataHandlerType<DataType, FCsData_WeaponPtr, DataInterfaceMapType>* GetDataHandler() const { return DataHandler; } #undef DataInterfaceMapType public: /** * Get the Data (implements interface: DataType (NCsWeapon::NData::IData)) associated with Name of the weapon type. * * @param Name Name of the Weapon. * return Data that implements the interface: DataType (NCsWeapon::NData::IData). */ DataType* GetData(const FName& Name); /** * Get the Data (implements interface: DataType (NCsWeapon::NData::IData)) associated with Name of the weapon type. * "Checked" in regards to returning a valid pointer. * * @param Context The calling context. * @param Name Name of the Weapon. * return Data that implements the interface: DataType (NCsWeapon::NData::IData). */ DataType* GetDataChecked(const FString& Context, const FName& Name); /** * Safely get the Data (implements interface: DataType (NCsWeapon::NData::IData)) associated with Name of the weapon type. * * @param Context The calling context. * @param Name Name of the Weapon. * return Data that implements the interface: DataType (NCsWeapon::NData::IData). */ DataType* GetSafeData(const FString& Context, const FName& Name); /** * Get the Data (implements interface: DataType (NCsWeapon::NData::IData)) associated with Type. * * @param Type Weapon type. * return Data that implements the interface: DataType (NCsWeapon::NData::IData). */ DataType* GetData(const FECsWeapon& Type); /** * Get the Data (implements interface: DataType (NCsWeapon::NData::IData)) associated with Type. * "Checked" in regards to returning a valid pointer. * * @param Context The calling context. * @param Type Weapon type. * return Data that implements the interface: DataType (NCsWeapon::NData::IData). */ DataType* GetDataChecked(const FString& Context, const FECsWeapon& Type); /** * Get the Data (implements interface: DataType (NCsWeapon::NData::IData)) associated with Type. * * @param Context The calling context. * @param Type Weapon type. * return Data that implements the interface: DataType (NCsWeapon::NData::IData). */ DataType* GetSafeData(const FString& Context, const FECsWeapon& Type); protected: void OnPayloadUnloaded(const FName& Payload); #pragma endregion Data #undef ManagerType #undef ManagerParamsType #undef ConstructParamsType #undef PayloadType #undef ClassHandlerType #undef DataHandlerType #undef DataType };
27.135934
133
0.748312
[ "object" ]
694cf2ede3d582ee45d03328348944dd0c4622ca
137,029
c
C
sdk/sdk/driver/nand/NF_LB8K_HWECC.c
doyaGu/C0501Q_HWJL01
07a71328bd9038453cbb1cf9c276a3dd1e416d63
[ "MIT" ]
1
2021-10-09T08:05:50.000Z
2021-10-09T08:05:50.000Z
sdk/sdk/driver/nand/NF_LB8K_HWECC.c
doyaGu/C0501Q_HWJL01
07a71328bd9038453cbb1cf9c276a3dd1e416d63
[ "MIT" ]
null
null
null
sdk/sdk/driver/nand/NF_LB8K_HWECC.c
doyaGu/C0501Q_HWJL01
07a71328bd9038453cbb1cf9c276a3dd1e416d63
[ "MIT" ]
null
null
null
#include "host/host.h" #include "sys/sys.h" #include "ite/ith.h" #include "mem/mem.h" #include "nandflash/NF_LB_HWECC.h" #ifdef LARGEBLOCK_8KB #ifdef NF_HW_ECC #ifdef NAND_DEBUG_MSG #include <stdarg.h> #include <stdio.h> #include "host/host.h" #endif #ifdef __FREERTOS__ //#include "sys.h" #include "nandflash/nf_dma.h" #endif #include "host/ahb.h" #include "nandflash/NF_Reg.h" //#include "xd/xd_mlayer.h" #include "../../share/fat/ftl/ftl/mlayer.h" //////////////////////////////////////////////////////////// // // Compile Option // //////////////////////////////////////////////////////////// #define ENABLE_HW_ECC //#define LB_ECC_RECORD #define NF_USE_DMA_COPY //#define SHOW_RWE_MSG //#define ENABLE_HW_SCRAMBLER #define PITCH_ECC_1KB_ISSUE //#define ENABLE_NF_TEST_CODE #ifdef ENABLE_HW_ECC #define ECC_PAGE_SIZE 1024 #define BCH_ECC_SIZE (512) //if 4kB/page NAND use BCH 24-bit ECC = (4+((BCH 24-bit)*2))*((page size)/(ECC_PAGE_SIZE)) = (4+48)*(4)= 208 #if defined(LARGEBLOCK_4KB) || defined(LARGEBLOCK_8KB) #define ECC_LENGTH 42 #define BCH_MODE 24 #define ECC_SPARE_SIZE 24 #else #define ECC_LENGTH 21 #define BCH_MODE 12 #define ECC_SPARE_SIZE 16 #endif #endif #define SPARE_SIZE ECC_SPARE_SIZE #define BLOCK_SIZE PAGE_SIZE * g_NfAttrib.pagePerBlock #ifdef NF_LARGE_BLOCK_8KB #define PAGE_SIZE 8192 #define TOTAL_SPARE_SIZE 436 #define DATA_SIZE 8216 //PAGE_SIZE + SPARE_SIZE #elif NF_LARGE_BLOCK_4KB #define PAGE_SIZE 4096 #define TOTAL_SPARE_SIZE 218 #define DATA_SIZE 4120 //PAGE_SIZE + SPARE_SIZE #else #define PAGE_SIZE 2048 #define TOTAL_SPARE_SIZE 64 #define DATA_SIZE 2064 //PAGE_SIZE + SPARE_SIZE #endif //////////////////////////////////////////////////////////// // // Global Variable // //////////////////////////////////////////////////////////// typedef MMP_UINT8 (*BLOCK_CHECK_METHOD) (MMP_UINT32 pba); typedef enum{ NAND_MAKER_TOSHIBA = 0, // 0 NAND_MAKER_SAMSUNG, // 1 NAND_MAKER_HYNIX, // 2 NAND_MAKER_NUMONYX, // 3 NAND_MAKER_POWERFLASH, // 4 NAND_UNKNOWN_MAKER }NAND_MAKER; typedef enum{ NAND_TOSHIBA_METHOD_01 = 0, // Check byte 0 in data & 1st bytes in spare of 1st & 2nd page NAND_TOSHIBA_METHOD_02, // Check byte 0 in data & 1st bytes in spare of last page NAND_TOSHIBA_METHOD_03, // Check byte 0 in data & 1st bytes in spare of 1st page & last page NAND_SAMSUNG_METHOD_01, // Check 1st bytes in spare of 1st & 2nd page NAND_SAMSUNG_METHOD_02, // Check 1st bytes in spare of last page NAND_HYNIX_METHOD_01, // Check 1st bytes in spare of 1st & 2nd page NAND_HYNIX_METHOD_02, // Check 1st bytes in spare of last page & (last-2) page NAND_NUMONYX_METHOD_01, // Check 1st & 6th byte in spare of 1st page NAND_NUMONYX_METHOD_02, // Check 1st byte in spare of last page NAND_POWERFLASH_METHOD_01, NAND_UNKNOWN_METHOD }NAND_BLOCK_CHECK_METHOD; typedef struct NF_ATTRIBUTE_TAG { // --- nandflash object attribute MMP_BOOL bInit; MMP_BOOL bMultiDie; MMP_UINT32 dieNumber; MMP_UINT32 blockPerDie; // --- Physic nandflash attribute MMP_UINT16 ID1; MMP_UINT16 ID2; MMP_UINT32 numOfBlocks; MMP_UINT8 pagePerBlock; MMP_UINT32 pageSize; NAND_MAKER nandMaker; NAND_BLOCK_CHECK_METHOD checkMethod; BLOCK_CHECK_METHOD pfCheckMethod; MMP_CHAR modelName[256]; MMP_UINT32 maxRealAddress; // --- Controller register setting MMP_UINT32 clockValue; MMP_UINT32 register701C; }NF_ATTRIBUTE; static MMP_UINT8 *g_pNFdataBuf = MMP_NULL; static MMP_UINT8 *g_pNFspareBuf = MMP_NULL; static MMP_UINT8 *g_pNFeccBuf = MMP_NULL; static MMP_UINT8 *g_pNFdataBufAllocAdr = MMP_NULL; static MMP_UINT8 *g_pNFspareBufAllocAdr = MMP_NULL; static MMP_UINT8 *g_pNFeccBufAllocAdr = MMP_NULL; #ifdef WIN32 static MMP_UINT8 *g_pW32NFBchBuf = MMP_NULL; #endif static MMP_UINT32 ReservedBlockNum = 0; static NF_ATTRIBUTE g_NfAttrib; #ifdef LB_ECC_RECORD unsigned char* g_pBlockErrorRecord = MMP_NULL; #endif static MMP_UINT32 g_OriGpioValue = 0; static MMP_UINT32 g_LastDieNumber = 0; static MMP_UINT32 g_BchMapMask = 0; static MMP_UINT32 g_TotalNumOfMapBit = 0; static MMP_UINT32 g_pNFeccCurrRdMask = 0; #if defined(NAND_IRQ_ENABLE) static MMP_EVENT NandIsrEvent = MMP_NULL; #endif //3f f6 90 fa 2d cc 75 fb 80 23 36 08 28 69 c2 63 (it is for 2kB/page) //3f f6 90 fa 2d cc 75 fb 80 23 36 08 28 69 c2 63 (it is ?? for 4kB/page) const MMP_UINT8 g_ScramblerTable[16] = {0x3f, 0xf6, 0x90, 0xfa, 0x2d, 0xcc, 0x75, 0xfb, 0x80, 0x23, 0x36, 0x08, 0x28, 0x69, 0xc2, 0x63}; //////////////////////////////////////////////////////////// // // Const variable or Marco // //////////////////////////////////////////////////////////// static MMP_UINT32 REGISTER701C = 0x00002105; #define MAX_DIE_NUMBER 1 #define NF_CLOCK_DIVIDE_VALUE 0x00777777 #define IO_SELECT_MASK 0x0007 #define IO_SELECT_NAND_FLASH 0x0000 #define CF_IOWR_PULL_UP_DOWN_MASK 0x00003000 #define NDCS0_PULL_UP_DOWN_MASK 0x03000000 #define PULL_UP_CF_IOWR 0x00002000 #define PULL_UP_NDCS0 0x02000000 #define READ_STATUS_TIME_OUT_COUNT 100000 #if defined(NAND_IRQ_ENABLE) #define NAND_INTR_MASK 0x00000010 #endif #ifdef ENABLE_HW_SCRAMBLER #define IsEnHwScrambler (1) #else #define IsEnHwScrambler (0) #endif enum { LL_OK, LL_ERASED, LL_ERROR, LL_RETRY }; //////////////////////////////////////////////////////////// // // Function prototype // //////////////////////////////////////////////////////////// #ifdef NAND_DEBUG_MSG void NAND_DbgPrintf(char* str, ...) { va_list ap; char buf[384]; MMP_INT result; va_start(ap, str); result = vsprintf(buf, str, ap); va_end(ap); if (result >= 0) { printf(buf); } } #else #if defined(WIN32) void NAND_DbgPrintf(char* str, ...) {} #elif defined(__FREERTOS__) #define NAND_DbgPrintf(x, ...) #endif #endif #if defined(NAND_IRQ_ENABLE) static void NfIntrEnable(void); static void NfIntrDisable(void); #endif static MMP_UINT8 LB8K_HWECC_WaitCmdReady(NF_CMD_TYPE type); static HWECC_RESP_TYPE LB8K_HWECC_CheckECC(MMP_UINT8 *data, MMP_UINT8 *spare, MMP_BOOL EnableEcc); static MMP_UINT32 GetNandId(MMP_UINT8 chipIndex, NF_ATTRIBUTE* pNfAttrib); static MMP_BOOL SamsungNandflash(MMP_UINT16 ID1,MMP_UINT16 ID2, NF_ATTRIBUTE* pNfAttrib); static MMP_BOOL HynixNandflash(MMP_UINT16 ID1,MMP_UINT16 ID2, NF_ATTRIBUTE* pNfAttrib); static MMP_BOOL ToshibaNandflash(MMP_UINT16 ID1,MMP_UINT16 ID2, NF_ATTRIBUTE* pNfAttrib); static MMP_BOOL NumonyxNandflash(MMP_UINT16 ID1,MMP_UINT16 ID2, NF_ATTRIBUTE* pNfAttrib); static MMP_BOOL PowerFlashNandflash(MMP_UINT16 ID1,MMP_UINT16 ID2, NF_ATTRIBUTE* pNfAttrib); static MMP_BOOL IsErasedBlock(MMP_UINT8* pData, MMP_UINT8* pSpare); static MMP_BOOL NfChipSelect(MMP_UINT32 chipIndex); static void EnableNfControl(); static void ResetChipSelect(); static MMP_UINT8 NAND_CMD_2ND_READ70_STATUS(MMP_UINT32* NfStatus); static MMP_UINT8 NAND_CMD_1ST_READID90(MMP_UINT32* CmdID0, MMP_UINT32* CmdID1, MMP_UINT32 IdCycles); static MMP_UINT8 GetErrorPageNum(MMP_UINT32 ErrMap); static MMP_UINT32 GetCorrectNumInThisSegment(MMP_UINT32 PageLoop); static MMP_UINT16 GetErrorAddr(MMP_UINT8 PageLoop,MMP_UINT8 BitLoop); static MMP_UINT8 GetErrorBit(MMP_UINT8 PageLoop,MMP_UINT8 BitLoop); static MMP_UINT8 GetErrorPage(MMP_UINT8 PageLoop); static void CorrectBitIn8kBDataBuffer(MMP_UINT8 *data, MMP_UINT8 *spare,MMP_UINT8 ErrorPage,MMP_UINT16 ErrorAddr,MMP_UINT8 ErrorBit); static void CorrectAllErrorBitsIn8kBDataBuffer(MMP_UINT8 *data, MMP_UINT8 *spare); static MMP_UINT8 IsAllData0xFF(MMP_UINT8 *pDataPtr, MMP_UINT32 Cprlen); static void GenBchWtPattern(MMP_UINT8 *pDataPtr); static void GenErrBit(MMP_UINT8 *pDataPtr, MMP_UINT32 Address); static void GenErrBitsInWhilePage(MMP_UINT8 *pDataPtr, MMP_UINT8 TotalSizeInkB, MMP_UINT32 ErrBitNumOf1KB); static void BCH_ECC_TEST(void); static MMP_UINT8 LB8K_HWECC_Read1kBytes( MMP_UINT32 pba, MMP_UINT32 ppo, MMP_UINT8* pBuffer, MMP_UINT8 index); static MMP_UINT8 compare2Buf(MMP_UINT8* pBuf1, MMP_UINT8* pBuf2, MMP_UINT32 CprSize); void LB8K_HWECC_RWE_TEST(void); // Check byte 0 in data & 1st bytes in spare of 1st & 2nd page static MMP_UINT8 _IsBadBlockToshibaMethod01( MMP_UINT32 pba); // Check byte 0 in data & 1st bytes in spare of last page static MMP_UINT8 _IsBadBlockToshibaMethod02( MMP_UINT32 pba); // Check byte 0 in data & 1st bytes in spare of 1st page & last page static MMP_UINT8 _IsBadBlockToshibaMethod03( MMP_UINT32 pba); // Check 1st bytes in spare of 1st & 2nd page static MMP_UINT8 _IsBadBlockSamsungMethod01( MMP_UINT32 pba); // Check 1st bytes in spare of last page static MMP_UINT8 _IsBadBlockSamsungMethod02( MMP_UINT32 pba); // Check 1st bytes in spare of 1st & 2nd page static MMP_UINT8 _IsBadBlockHynixMethod01( MMP_UINT32 pba); // Check 1st bytes in spare of last page & (last-2) page static MMP_UINT8 _IsBadBlockHynixMethod02( MMP_UINT32 pba); // Check 1st & 6th byte in spare of 1st page static MMP_UINT8 _IsBadBlockNumonyxMethod01( MMP_UINT32 pba); // Check 1st byte in spare of last page static MMP_UINT8 _IsBadBlockNumonyxMethod02( MMP_UINT32 pba); static MMP_UINT8 _IsBadBlockPowerFlashMethod01( MMP_UINT32 pba); //////////////////////////////////////////////////////////// // // Function Implement // //////////////////////////////////////////////////////////// #if defined(NAND_IRQ_ENABLE) void nand_isr(void* data) { MMP_UINT32 tmp=0; //printf("Nf.isr.in\n"); AHB_ReadRegister(NF_REG_INTR, &tmp); //for reference if(tmp&0x01) { AHB_WriteRegisterMask(NF_REG_INTR, tmp, tmp); /** clear nand interrupt **/ } else { printf("Nf.ISR: something wrong!!\n"); } SYS_SetEventFromIsr(NandIsrEvent); //printf("Nf.isr.out\n"); } #endif #if defined(NAND_IRQ_ENABLE) void NfIntrEnable(void) { // Initialize Timer IRQ printf("Enable NAND IRQ~~\n"); ithIntrDisableIrq(ITH_INTR_NAND); ithIntrClearIrq(ITH_INTR_NAND); #if defined (__FREERTOS__) // register NAND Handler to IRQ //ithIntrRegisterHandlerIrq(ITH_INTR_TIMER1 + i, timer_isr, i); ithIntrRegisterHandlerIrq(ITH_INTR_NAND, nand_isr, MMP_NULL); #endif // defined (__FREERTOS__) // set IRQ to edge trigger //ithIntrSetTriggerModeIrq(ITH_INTR_TIMER1 + i, ITH_INTR_EDGE); ithIntrSetTriggerModeIrq(ITH_INTR_NAND, ITH_INTR_EDGE); // set IRQ to detect rising edge //ithIntrSetTriggerLevelIrq(ITH_INTR_TIMER1 + i, ITH_INTR_HIGH_RISING); ithIntrSetTriggerLevelIrq(ITH_INTR_NAND, ITH_INTR_HIGH_RISING); // Enable IRQ //ithIntrEnableIrq(ITH_INTR_TIMER1 + i); ithIntrEnableIrq(ITH_INTR_NAND); AHB_WriteRegisterMask(NF_REG_INTR, 0x00000000, NAND_INTR_MASK); /** enable nand interrupt **/ if(!NandIsrEvent) NandIsrEvent = SYS_CreateEvent(); printf("NandIsrEvent=%x\n",NandIsrEvent); printf("Enable NAND IRQ~~leave\n"); } void NfIntrDisable(void) { ithIntrDisableIrq(ITH_INTR_NAND); } #else #define intrEnable(a) #define intrDisable() #endif MMP_UINT8 LB8K_HWECC_WaitCmdReady( NF_CMD_TYPE type) { const MMP_UINT32 TIME_OUT = 100000; MMP_UINT32 nfStatus; MMP_UINT8 result = LL_OK; MMP_UINT32 timeOut = TIME_OUT; MMP_INT EventRst; NAND_DbgPrintf("[ENTER]LB8K_HWECC_WaitCmdReady\n"); #if defined(NAND_IRQ_ENABLE) //AHB_ if( (type==NF_READ) || (type==NF_WRITE) || (type==NF_ERASE) ) { //printf("WaitNfReady.in,type=%x\n",type); EventRst = SYS_WaitEvent(NandIsrEvent, 20); //printf("WaitNfReady.event.got!!rst=%x\n",EventRst); if(result) { printf("[Nf ERR]:INTR time out\n"); result = LL_ERROR; goto end; } } #endif // ---------------------------------------- // 1. Read status and wait nandflash finish command do { AHB_ReadRegister(NF_REG_STATUS, &nfStatus); if ( timeOut-- == 0 ) { AHB_ReadRegister(NF_REG_GENERAL, &nfStatus); printf("\tLB8K_HWECC_WaitCmdReady wait idle time out[1]!!!,0X131A=%X.\n",nfStatus); AHB_ReadRegister(NF_REG_CLOCK_DIVIDE, &nfStatus); printf("cLOCK1=%X.\r\n",nfStatus); //AHB_ReadRegister(NF_REG_STORAGE_ADDR3, &nfStatus); //printf("SprSize=%x.\r\n",nfStatus); result = LL_ERROR; goto end; } }while( (nfStatus&0xc000) != NFIDLE ); //NAND_CMD_CHECK_STATUS(); // ---------------------------------------- // 2. Wait 0x70 idle timeOut = TIME_OUT; if(NAND_CMD_2ND_READ70_STATUS(&nfStatus)!=LL_OK) { printf("NAND_CMD_2ND_READ70_STATUS fail\n"); result = LL_ERROR; goto end; } //nfStatus = nfStatus & 0xFF; // ---------------------------------------- // 3. Check status switch(type) { // Check if command is pass or fail case NF_ERASE: case NF_WRITE: if( (nfStatus & 0xFF) == 0xE0 || (nfStatus & 0xFF) == 0xC0 ) result = LL_OK; else result = LL_ERROR; break; case NF_READ: if( (nfStatus & 0x7F) == 0x60 || (nfStatus & 0x7F) == 0x40 ) result = LL_OK; else result = LL_ERROR; break; case NF_READ_ID: if ( (nfStatus & 0x7F) == 0x60 || (nfStatus & 0x7F) == 0x40 ) result = LL_OK; else result = LL_ERROR; break; default: //unknow CMD,return error result = LL_ERROR; break; } end: NAND_DbgPrintf("[LEAVE]LB8K_HWECC_WaitCmdReady: Return %s\n", result == LL_OK ? "LL_OK" : "LL_ERROR"); return result; } HWECC_RESP_TYPE LB8K_HWECC_CheckECC( MMP_UINT8 *data, MMP_UINT8 *spare, MMP_BOOL EnableEcc) { HWECC_RESP_TYPE result; MMP_UINT32 BchStatus=0xFFFFFFFF; MMP_UINT16 erraddr, errvalue; AHB_ReadRegister(NF_REG_BCH_ECC_MAP, &BchStatus); if( EnableEcc == MMP_FALSE ) { result = NF_NOERROR; //printf("1.ECC=%04x\r\n",BchStatus); } else if( ((BchStatus&g_BchMapMask)&g_pNFeccCurrRdMask)==(g_BchMapMask&g_pNFeccCurrRdMask) )//if( (BchStatus&0x0000000F)==0x0000000F) { result = NF_NOERROR; //printf("3.ECC=%08x[%08x,%08x]\r\n",BchStatus, g_BchMapMask, g_pNFeccCurrRdMask); } else { MMP_UINT8 *ECCpt; MMP_UINT32 p,Reg704C,Reg7050; MMP_UINT32 TempReg704C,TempReg7050; AHB_ReadRegister(NF_REG_BCH_ECC_MAP, &Reg704C); //printf("2.ECC=[%08x,%08x]",Reg704C,BchStatus); AHB_ReadRegister(NF_REG_ECC_ERROR_MAP, &Reg7050); //printf(",%08x,[%08x,%08x]\r\n",Reg7050, g_BchMapMask, g_pNFeccCurrRdMask); TempReg704C=((~Reg704C)&g_BchMapMask); TempReg7050=(Reg7050&g_BchMapMask); //1.if in-correctable if( ((TempReg704C & TempReg7050)&g_pNFeccCurrRdMask) == (TempReg704C&g_pNFeccCurrRdMask) ) { //printf("6.ECC, it can correction[%08x,%08x]x\n",Reg704C,Reg7050); CorrectAllErrorBitsIn8kBDataBuffer(data, spare); result = NF_NOERROR; // return BCH can not correct this error } else { printf("5.ECC, it can not correction[%08x,%08x]x\n",Reg704C,Reg7050); result = NF_OVER4ERR; } } return result; } MMP_UINT8 LB8K_HWECC_Initialize( unsigned long* pNumOfBlocks, unsigned char* pPagePerBlock, unsigned long* pPageSize) { MMP_UINT8 result = LL_OK; MMP_UINT8* VramBaseAddress = 0x00; MMP_UINT32 NumOfBlocks, PageSize; MMP_UINT8 PagePerBlock; MMP_UINT32 i,Reg32; NF_ATTRIBUTE nfAttrib; NAND_DbgPrintf("[ENTER]LB8K_HWECC_Initialize: \n"); AHB_ReadRegister(NF_REG_GENERAL, &Reg32); printf("0x701C = %x\n",Reg32); AHB_ReadRegister(0xD070003C, &Reg32); printf("NF_REG_STATUS = %x\n",Reg32); AHB_WriteRegister(NF_REG_CLOCK_DIVIDE, 0x40777777); // Switch controler to nand EnableNfControl(); if(IsEnHwScrambler) { //it's HW limitation, It can not read ID in scramble mode AHB_WriteRegisterMask(NF_REG_GENERAL, 0x00000000,0x00080000); } // Set nandflash clock divider //AHB_WriteRegister(NF_REG_CLOCK_DIVIDE, NF_CLOCK_DIVIDE1_VALUE); AHB_WriteRegister(NF_REG_CLOCK_DIVIDE, 0x40777777); // Reset nandflash attribute memset(&g_NfAttrib, 0x00, sizeof(NF_ATTRIBUTE)); if ( GetNandId(0, &nfAttrib) == LL_OK ) { g_NfAttrib.bInit = MMP_TRUE; g_NfAttrib.dieNumber++; g_NfAttrib.ID1 = nfAttrib.ID1; g_NfAttrib.ID2 = nfAttrib.ID2; g_NfAttrib.blockPerDie = nfAttrib.numOfBlocks; g_NfAttrib.numOfBlocks = nfAttrib.numOfBlocks; g_NfAttrib.pagePerBlock = nfAttrib.pagePerBlock; g_NfAttrib.pageSize = nfAttrib.pageSize; g_NfAttrib.nandMaker = nfAttrib.nandMaker; g_NfAttrib.checkMethod = nfAttrib.checkMethod; g_NfAttrib.pfCheckMethod = nfAttrib.pfCheckMethod; g_NfAttrib.clockValue = nfAttrib.clockValue; g_NfAttrib.register701C = nfAttrib.register701C; g_NfAttrib.maxRealAddress = ((nfAttrib.numOfBlocks - 1) * nfAttrib.pagePerBlock + (nfAttrib.pagePerBlock - 1)) * PAGE_SIZE; strcpy(g_NfAttrib.modelName, nfAttrib.modelName); for ( i=1; i<MAX_DIE_NUMBER; i++ ) { if ( GetNandId((MMP_UINT8)i, &nfAttrib) == LL_OK ) { g_NfAttrib.bMultiDie = MMP_TRUE; g_NfAttrib.dieNumber++; g_NfAttrib.numOfBlocks += NumOfBlocks; } } if ( g_NfAttrib.bMultiDie == MMP_FALSE ) { NfChipSelect(0); ResetChipSelect(); } } NAND_DbgPrintf("\t-------------------- new attribute Nand Flash Initial --------------------\n"); NAND_DbgPrintf("\tInit %s\n", g_NfAttrib.bInit ? "OK" : "FAIL"); NAND_DbgPrintf("\t%s\n", g_NfAttrib.bMultiDie ? "Multi-Die" : "Single-Die"); NAND_DbgPrintf("\tNumber Of Blocks = %u\n", g_NfAttrib.numOfBlocks); NAND_DbgPrintf("\tPages Per Block = %u\n", g_NfAttrib.pagePerBlock); NAND_DbgPrintf("\tPage Size = %u Bytes\n", g_NfAttrib.pageSize); NAND_DbgPrintf("\tTotal Size = %u MB\n", g_NfAttrib.pagePerBlock * g_NfAttrib.pageSize * (g_NfAttrib.numOfBlocks / 1024 )/ 1024); NAND_DbgPrintf("\tID1 = 0x%04X\n", g_NfAttrib.ID1); NAND_DbgPrintf("\tID2 = 0x%04X\n", g_NfAttrib.ID2); NAND_DbgPrintf("\tNand Maker = %u\n", g_NfAttrib.nandMaker); NAND_DbgPrintf("\tCheck Method = %u\n", g_NfAttrib.checkMethod); NAND_DbgPrintf("\tModel Name = %s\n", g_NfAttrib.modelName); NAND_DbgPrintf("\tClock01(0x1320) = 0x%08X\n", g_NfAttrib.clockValue); NAND_DbgPrintf("\t0x131C = 0x%08X\n", g_NfAttrib.register701C); printf("\t-------------------- attribute Nand Flash Initial --------------------\n"); printf("\tInit %s\n", g_NfAttrib.bInit ? "OK" : "FAIL"); printf("\t%s\n", g_NfAttrib.bMultiDie ? "Multi-Die" : "Single-Die"); printf("\tNumber Of Blocks = %u\n", g_NfAttrib.numOfBlocks); printf("\tPages Per Block = %u\n", g_NfAttrib.pagePerBlock); printf("\tPage Size = %u Bytes\n", g_NfAttrib.pageSize); printf("\tTotal Size = %u MB\n", g_NfAttrib.pagePerBlock * g_NfAttrib.pageSize * (g_NfAttrib.numOfBlocks / 1024 )/ 1024); printf("\tID1 = 0x%04X\n", g_NfAttrib.ID1); printf("\tID2 = 0x%04X\n", g_NfAttrib.ID2); printf("\tNand Maker = %u\n", g_NfAttrib.nandMaker); printf("\tCheck Method = %u\n", g_NfAttrib.checkMethod); printf("\tModel Name = %s\n", g_NfAttrib.modelName); printf("\tClock01(0x7024) = 0x%08X\n", g_NfAttrib.clockValue); printf("\t0x701C = 0x%08X\n", g_NfAttrib.register701C); { MMP_UINT32 Reg32; AHB_ReadRegister(NF_REG_GENERAL, &Reg32); } if (g_NfAttrib.bInit) { *pNumOfBlocks = g_NfAttrib.numOfBlocks; *pPagePerBlock = g_NfAttrib.pagePerBlock; *pPageSize = g_NfAttrib.pageSize; switch(g_NfAttrib.pageSize) { case 2048: //gNfInitInfo.EccLen = 21; g_BchMapMask=0x00000003; g_TotalNumOfMapBit = 2; break; case 4096: //gNfInitInfo.EccLen = 21;//not 21 when using 4KB/page NAND g_BchMapMask=0x0000000F; g_TotalNumOfMapBit = 4; break; case 8192: //gNfInitInfo.EccLen = 21;//not 21 when using 8KB/page NAND g_BchMapMask=0x000000FF; g_TotalNumOfMapBit = 8; break; case 16384: //gNfInitInfo.EccLen = 21;//not 21 when using 8KB/page NAND g_BchMapMask=0x0000FFFF; g_TotalNumOfMapBit = 16; break; case 32768: //gNfInitInfo.EccLen = 21;//not 21 when using 8KB/page NAND g_BchMapMask=0xFFFFFFFF; g_TotalNumOfMapBit = 32; break; default: result = LL_ERROR; goto end; break; } g_pNFeccCurrRdMask = g_BchMapMask; // Awin@20071015 NAND_DbgPrintf("\tLB8K_HWECC_Initialize: numOfBlocks = %d.\n\r", g_NfAttrib.numOfBlocks); NAND_DbgPrintf("\tLB8K_HWECC_Initialize: pagePerBlock = %d.\n\r", g_NfAttrib.pagePerBlock); NAND_DbgPrintf("\tLB8K_HWECC_Initialize: pageSize = %d.\n\r", g_NfAttrib.pageSize); #ifdef LB_ECC_RECORD if ( g_pBlockErrorRecord == NULL ) { #ifdef __FREERTOS__ //for ARM g_pBlockErrorRecord = (MMP_UINT8 *)MEM_Allocate(NFNumOfBlocks, MEM_USER_NF); #elif defined(WIN32) g_pBlockErrorRecord = (unsigned char*)SYS_Malloc(NFNumOfBlocks); #endif if( g_pBlockErrorRecord != MMP_NULL ) { memset(g_pBlockErrorRecord, 0x00, NFNumOfBlocks); } } #endif } else { printf("Unknown nandflash ID\n"); result = LL_ERROR; goto end; } // Get Vram base address VramBaseAddress = HOST_GetVramBaseAddress(); if ( g_pNFdataBuf == MMP_NULL ) { g_pNFdataBufAllocAdr = (MMP_UINT8*)MEM_Allocate(PAGE_SIZE+TOTAL_SPARE_SIZE+4, MEM_USER_NF); g_pNFdataBuf = (MMP_UINT8*)(((MMP_UINT32)g_pNFdataBufAllocAdr + 3) & ~3); if(g_pNFdataBuf == MMP_NULL) { result = LL_ERROR; //error goto end; } } if ( g_pNFspareBuf == MMP_NULL ) { g_pNFspareBufAllocAdr = (MMP_UINT8*)MEM_Allocate(SPARE_SIZE+16, MEM_USER_NF); g_pNFspareBuf = (MMP_UINT8*)(((MMP_UINT32)g_pNFspareBufAllocAdr + 3) & ~3); if(g_pNFspareBuf == MMP_NULL) { result = LL_ERROR; //error goto end; } } if ( g_pNFeccBuf == MMP_NULL ) { g_pNFeccBufAllocAdr = (MMP_UINT8*)MEM_Allocate(BCH_ECC_SIZE+4, MEM_USER_NF); g_pNFeccBuf = (MMP_UINT8*)(((MMP_UINT32)g_pNFeccBufAllocAdr + 3) & ~3); if(g_pNFeccBuf == MMP_NULL) { result = LL_ERROR; //error goto end; } } #ifdef __FREERTOS__ //for ARM #elif defined(WIN32) if ( g_pW32NFBchBuf == MMP_NULL ) { g_pW32NFBchBuf = (MMP_UINT8*)SYS_Malloc(BCH_ECC_SIZE+4, MEM_USER_NF); if(g_pW32NFBchBuf == MMP_NULL) { result = LL_ERROR; //error goto end; } } #endif // Set configuration enable bit at nand flash AHB_WriteRegister(NF_REG_GENERAL, g_NfAttrib.register701C); AHB_WriteRegisterMask(NF_REG_STORAGE_ADDR2, (MMP_UINT32)(SPARE_SIZE)<<8, 0x00001F00); // 0x1318 AHB_WriteRegister(NF_REG_CLOCK_DIVIDE, g_NfAttrib.clockValue); // Set source data address at VRAM AHB_WriteRegister(NF_REG_READ_DATA_BASE_ADDR, (MMP_UINT32)(g_pNFdataBuf-VramBaseAddress) ); // Set destination spare address AHB_WriteRegister(NF_REG_READ_SPARE_BASE_ADDR, (MMP_UINT32)(g_pNFspareBuf-VramBaseAddress) ); // Set source data address at VRAM AHB_WriteRegister(NF_REG_WRITE_DATA_BASE_ADDR, (MMP_UINT32)(g_pNFdataBuf-VramBaseAddress) ); // Set destination spare address AHB_WriteRegister(NF_REG_WRITE_SPARE_BASE_ADDR, (MMP_UINT32)(g_pNFspareBuf-VramBaseAddress) ); // Set ECC address AHB_WriteRegister(NF_REG_MEM_DST_CORR_ECC_ADDR, (MMP_UINT32)(g_pNFeccBuf-VramBaseAddress)); //calculate & set the ECC initial value { MMP_UINT32 EccSprInitValue = ((ECC_PAGE_SIZE+SPARE_SIZE)*8)+(BCH_MODE*14)-1; MMP_UINT32 EccDataInitValue = (ECC_PAGE_SIZE*8)+(BCH_MODE*14)-1; if(BCH_MODE==12) { AHB_WriteRegister(NF_REG_ECC_12BIT_SEG_INIT_VAL, EccDataInitValue&0x00003FFF); AHB_WriteRegister(NF_REG_ECC_12BIT_LAST_SEG_INIT_VAL, EccSprInitValue&0x00003FFF); } else if(BCH_MODE==24) { AHB_WriteRegister(NF_REG_ECC_24BIT_SEG_INIT_VAL, EccDataInitValue&0x00003FFF); AHB_WriteRegister(NF_REG_ECC_24BIT_LAST_SEG_INIT_VAL, EccSprInitValue&0x00003FFF); } else if(BCH_MODE==40) { AHB_WriteRegister(NF_REG_ECC_40BIT_SEG_INIT_VAL, EccDataInitValue&0x00003FFF); AHB_WriteRegister(NF_REG_ECC_40BIT_LAST_SEG_INIT_VAL, EccSprInitValue&0x00003FFF); } } //Enable scrambler function!! if(IsEnHwScrambler) { AHB_WriteRegisterMask(NF_REG_GENERAL, 0x00080000,0x00080000); } //for debug //AHB_WriteRegisterMask(NF_REG_GENERAL, 1<<28, 1<<28); // Reset nandflash chip //HOST_WriteRegister(NF_REG_CMD2,RESET_CMD_2ST); AHB_WriteRegister(NF_REG_CMD2, RESET_CMD_2ST); AHB_WriteRegister(NF_REG_CMD_FIRE, NF_CMD_FIRE); result = LB8K_HWECC_WaitCmdReady(NF_READ_ID); //initial NF IRQ #if defined(NAND_IRQ_ENABLE) NfIntrEnable(); #endif #if defined(__FREERTOS__) && defined(NF_USE_DMA_COPY) // Initial DMA if ( !NF_InitDma() ) { printf("LB8K_HWECC_Initialize: Initial DMA fail.\n"); result = LL_ERROR; goto end; } #endif end: NAND_DbgPrintf("[LEAVE]LB8K_HWECC_Initialize: return %s\n", result == LL_OK ? "OK" : "FALSE"); return result; } void LB8K_HWECC_Getwear( MMP_UINT32 blk, MMP_UINT8 *dest) { //NOTHING TO DO NAND_DbgPrintf("[ENTER]LB8K_HWECC_Getwear: \n"); NAND_DbgPrintf("[LEAVE]LB8K_HWECC_Getwear: \n"); } MMP_UINT8 LB8K_HWECC_Erase( MMP_UINT32 pba) { MMP_UINT8 result = LL_ERROR; MMP_UINT32 realAddress = 0x00; MMP_UINT32 dieNumber = 0; NAND_DbgPrintf("[ENTER]LB8K_HWECC_Erase: pba(%d)\n", pba); #ifdef SHOW_RWE_MSG printf("Ers[%x]\r\n",pba); #endif //while(1); // ---------------------------------------- // 1. Switch controller to nand EnableNfControl(); // --- Calculate block position, and set block number if ( g_NfAttrib.bMultiDie ) { dieNumber = pba / g_NfAttrib.blockPerDie; NfChipSelect(dieNumber); pba = pba - (g_NfAttrib.blockPerDie * dieNumber); } // ---------------------------------------- // 2. Calculate real address from input block address realAddress = pba * g_NfAttrib.pagePerBlock * PAGE_SIZE; //realAddress = pba * g_NfAttrib.pagePerBlock * 0x10000; // ---------------------------------------- // 3. Set erase block address at nandflash region AHB_WriteRegister(NF_REG_STORAGE_ADDR1, (MMP_UINT32)realAddress); // ---------------------------------------- // 4. Disable write protect bit AHB_WriteRegisterMask(NF_REG_GENERAL,1<<17, 1<<17); // 0x131C // ---------------------------------------- // 5. Fire HW and wait ready AHB_WriteRegisterMask(NF_REG_GENERAL, 0x00100000, 0x01F00000); AHB_WriteRegister(NF_REG_CMD1, ERASE_CMD_1ST); AHB_WriteRegister(NF_REG_CMD2, ERASE_CMD_2ND); AHB_WriteRegister(NF_REG_CMD_FIRE, NF_CMD_FIRE); #if defined(NAND_IRQ_ENABLE) #else MMP_Sleep(2); #endif result = LB8K_HWECC_WaitCmdReady(NF_WRITE); //NAND write command fire // ---------------------------------------- // 6. Enable write protect bit and disable CE pin //HOST_WriteRegisterMask(NF_REG_GENERAL, (MMP_UINT16)0x0000, 0x0800); // 0x131A NAND_DbgPrintf("[LEAVE]LB8K_HWECC_Erase: return %s\n", result == LL_OK ? "OK" : "FALSE"); return result; } MMP_UINT8 LB8K_HWECC_Write( MMP_UINT32 pba, MMP_UINT32 ppo, MMP_UINT8* pDataBuffer, MMP_UINT8* pSpareBuffer) { MMP_UINT8 result = LL_ERROR; MMP_UINT32 realAddress = 0x00; #ifdef __FREERTOS__ MMP_UINT8* pAlignDataBuf = (MMP_UINT8*)(((MMP_UINT32)pDataBuffer + 3) & ~3); MMP_UINT8* pAlignSpareBuf = (MMP_UINT8*)(((MMP_UINT32)pSpareBuffer + 3) & ~3); #endif NAND_DbgPrintf("[ENTER]LB8K_HWECC_Write: pba(%d), ppo(%d)\n", pba, ppo); #ifdef SHOW_RWE_MSG printf("W1[%x,%x]\r\n",pba,ppo); //printf("W1[%x,%x,%x,%x]\r\n",pba,ppo,pDataBuffer,pSpareBuffer); #endif //while(1); // ---------------------------------------- // 1. Switch controller to nand EnableNfControl(); if(IsEnHwScrambler) { //AHB_WriteRegister(NF_REG_WR_SCRAMB_INIT, 0x000000FF); AHB_WriteRegister(NF_REG_WR_SCRAMB_INIT, ppo);//reset scrambler initial value } // --- Calculate block position, and set block number if ( g_NfAttrib.bMultiDie ) { MMP_UINT32 dieNumber = pba / g_NfAttrib.blockPerDie; NfChipSelect(dieNumber); pba = pba - (g_NfAttrib.blockPerDie * dieNumber); } // ---------------------------------------- // 2. Calculate real address from input block address realAddress = ((pba * g_NfAttrib.pagePerBlock) + ppo) * PAGE_SIZE; //realAddress = ((pba * g_NfAttrib.pagePerBlock) + ppo) * 0x10000; // ---------------------------------------- // 3. Set program block address at nandflash region AHB_WriteRegister(NF_REG_STORAGE_ADDR1, (MMP_UINT32)realAddress); // ---------------------------------------- // 4. Set read/write address #ifdef __FREERTOS__ ithInvalidateDCacheRange(pDataBuffer, PAGE_SIZE); if ( pAlignDataBuf != pDataBuffer ) { memcpy(g_pNFdataBuf, pDataBuffer, PAGE_SIZE); ithInvalidateDCacheRange(g_pNFdataBuf, PAGE_SIZE); // --- Set source data address at VRAM AHB_WriteRegister(NF_REG_WRITE_DATA_BASE_ADDR, (MMP_UINT32)g_pNFdataBuf); } else { // --- Set source data address at VRAM AHB_WriteRegister(NF_REG_WRITE_DATA_BASE_ADDR, (MMP_UINT32)pDataBuffer); //AHB_WriteRegister(NF_REG_WRITE_SPARE_BASE_ADDR, (MMP_UINT32)g_pNFspareBuf); } ithInvalidateDCacheRange(pSpareBuffer, SPARE_SIZE); if ( pAlignSpareBuf != pSpareBuffer ) { ST_SPARE* pSpare = (ST_SPARE*)g_pNFspareBuf; memcpy(g_pNFspareBuf, pSpareBuffer, SPARE_SIZE); #if defined(LARGEBLOCK_4KB) || defined(LARGEBLOCK_8KB) if(SPARE_SIZE==24) { pSpare->dummy1 = WRITE_SYMBOL; pSpare->dummy2 = 0xFFFFFFFF; } #endif ithInvalidateDCacheRange(g_pNFspareBuf, SPARE_SIZE); // --- Set destination spare address AHB_WriteRegister(NF_REG_WRITE_SPARE_BASE_ADDR, (MMP_UINT32)g_pNFspareBuf); } else { ST_SPARE* pSpare = (ST_SPARE*)pSpareBuffer; #if defined(LARGEBLOCK_4KB) || defined(LARGEBLOCK_8KB) if(SPARE_SIZE==24) { pSpare->dummy1 = WRITE_SYMBOL; pSpare->dummy2 = 0xFFFFFFFF; } #endif ithInvalidateDCacheRange(pSpareBuffer, SPARE_SIZE); // --- Set destination spare address AHB_WriteRegister(NF_REG_WRITE_SPARE_BASE_ADDR, (MMP_UINT32)pSpareBuffer); } AHB_WriteRegister(NF_REG_MEM_DST_CORR_ECC_ADDR, (MMP_UINT32)g_pNFeccBuf); #elif defined(WIN32) #if defined(LARGEBLOCK_4KB) || defined(LARGEBLOCK_8KB) if(SPARE_SIZE==24) { ST_SPARE* pSpare = (ST_SPARE*)pSpareBuffer; pSpare->dummy1 = WRITE_SYMBOL; pSpare->dummy2 = 0xFFFFFFFF; } #endif //usb2spi_WriteMemory((MMP_UINT32)g_pNFdataBuf, (MMP_UINT32)pDataBuffer, PAGE_SIZE); //usb2spi_WriteMemory((MMP_UINT32)g_pNFspareBuf, (MMP_UINT32)pSpareBuffer, SPARE_SIZE); HOST_WriteBlockMemory((MMP_UINT32)g_pNFdataBuf, (MMP_UINT32)pDataBuffer, PAGE_SIZE); HOST_WriteBlockMemory((MMP_UINT32)g_pNFspareBuf, (MMP_UINT32)pSpareBuffer, SPARE_SIZE); AHB_WriteRegister(NF_REG_WRITE_DATA_BASE_ADDR, (MMP_UINT32)g_pNFdataBuf); AHB_WriteRegister(NF_REG_WRITE_SPARE_BASE_ADDR, (MMP_UINT32)g_pNFspareBuf); AHB_WriteRegister(NF_REG_MEM_DST_CORR_ECC_ADDR, (MMP_UINT32)g_pNFeccBuf); #endif // ---------------------------------------- // 5. Disable write protect bit AHB_WriteRegisterMask(NF_REG_GENERAL,0x00020000, 0x00020000); // 0x131A // ---------------------------------------- // 6. Fire HW and wait ready AHB_WriteRegisterMask(NF_REG_GENERAL, ((PAGE_SIZE/ECC_PAGE_SIZE)-1)<<20, 0x01F00000); AHB_WriteRegisterMask(NF_REG_STORAGE_ADDR2, (MMP_UINT32)(SPARE_SIZE)<<8, 0x00001F00); // 0x1318 AHB_WriteRegister(NF_REG_CMD1, PROGRAM_CMD_1ST); AHB_WriteRegister(NF_REG_CMD2, PROGRAM_CMD_2ND); AHB_WriteRegister(NF_REG_CMD_FIRE, NF_CMD_FIRE); #if defined(NAND_IRQ_ENABLE) #else MMP_Sleep(1); #endif result = LB8K_HWECC_WaitCmdReady(NF_WRITE); //NAND write command fire // ---------------------------------------- // 7. Enable write protect bit and disable CE pin //HOST_WriteRegisterMask(NF_REG_GENERAL,(MMP_UINT16)0x0000,0x0800); // 0x1316 NAND_DbgPrintf("[LEAVE]LB8K_HWECC_Write: return %s\n", result == LL_OK ? "OK" : "FALSE"); return result; } MMP_UINT8 LB8K_HWECC_LBA_Write( MMP_UINT32 pba, MMP_UINT32 ppo, MMP_UINT8* pDataBuffer, MMP_UINT8* pSpareBuffer) { MMP_UINT8 result = LL_ERROR; MMP_UINT32 realAddress = 0x00; MMP_UINT32 LbaAddr = PAGE_SIZE+TOTAL_SPARE_SIZE; #ifdef __FREERTOS__ MMP_UINT8* pAlignDataBuf = (MMP_UINT8*)(((MMP_UINT32)pDataBuffer + 3) & ~3); MMP_UINT8* pAlignSpareBuf = (MMP_UINT8*)(((MMP_UINT32)pSpareBuffer + 3) & ~3); #endif NAND_DbgPrintf("[ENTER]LB8K_HWECC_Write: pba(%d), ppo(%d)\n", pba, ppo); #ifdef SHOW_RWE_MSG printf("lba.W1[%x,%x]\r\n",pba,ppo); //printf("W1[%x,%x,%x,%x]\r\n",pba,ppo,pDataBuffer,pSpareBuffer); #endif //while(1); // ---------------------------------------- // 1. Switch controller to nand EnableNfControl(); { MMP_UINT32 Reg32; AHB_WriteRegisterMask(NF_REG_CMD_FIRE, NF_CMD_SW_RESET, NF_CMD_SW_RESET); // if(IsEnHwScrambler) { //it's scrambler bug, this register need to be reset after previous reading fire AHB_WriteRegister(NF_REG_WR_SCRAMB_INIT, 0x000000FF); //AHB_WriteRegister(NF_REG_WR_SCRAMB_INIT, ppo); } AHB_WriteRegister(NF_REG_USER_DEF_CTRL, 0x80000000|LbaAddr ); } // --- Calculate block position, and set block number if ( g_NfAttrib.bMultiDie ) { MMP_UINT32 dieNumber = pba / g_NfAttrib.blockPerDie; NfChipSelect(dieNumber); pba = pba - (g_NfAttrib.blockPerDie * dieNumber); } // ---------------------------------------- // 2. Calculate real address from input block address realAddress = ((pba * g_NfAttrib.pagePerBlock) + ppo) * PAGE_SIZE; //realAddress = ((pba * g_NfAttrib.pagePerBlock) + ppo) * 0x10000; // ---------------------------------------- // 3. Set program block address at nandflash region AHB_WriteRegister(NF_REG_STORAGE_ADDR1, (MMP_UINT32)realAddress); // ---------------------------------------- // 4. Set read/write address #ifdef __FREERTOS__ ithInvalidateDCacheRange(pDataBuffer, PAGE_SIZE); if ( pAlignDataBuf != pDataBuffer ) { memcpy(g_pNFdataBuf, pDataBuffer, PAGE_SIZE); ithInvalidateDCacheRange(g_pNFdataBuf, PAGE_SIZE); // --- Set source data address at VRAM AHB_WriteRegister(NF_REG_WRITE_DATA_BASE_ADDR, (MMP_UINT32)g_pNFdataBuf); //HOST_WriteRegister(NF_REG_WRITE_DATA_BASE_ADDR1, (MMP_UINT16)((MMP_UINT32)(g_pNFdataBuf) & 0x0000FFFF)); //HOST_WriteRegister(NF_REG_WRITE_DATA_BASE_ADDR2, (MMP_UINT16)(((MMP_UINT32)(g_pNFdataBuf) & 0xFFFF0000) >> 16)); } else { // --- Set source data address at VRAM AHB_WriteRegister(NF_REG_WRITE_DATA_BASE_ADDR, (MMP_UINT32)pDataBuffer); //HOST_WriteRegister(NF_REG_WRITE_DATA_BASE_ADDR1, (MMP_UINT16)((MMP_UINT32)pDataBuffer & 0x0000FFFF)); //HOST_WriteRegister(NF_REG_WRITE_DATA_BASE_ADDR2, (MMP_UINT16)(((MMP_UINT32)pDataBuffer & 0xFFFF0000) >> 16)); } ithInvalidateDCacheRange(pSpareBuffer, SPARE_SIZE); if ( pAlignSpareBuf != pSpareBuffer ) { ST_SPARE* pSpare = (ST_SPARE*)g_pNFspareBuf; memcpy(g_pNFspareBuf, pSpareBuffer, SPARE_SIZE); #if defined(LARGEBLOCK_4KB) || defined(LARGEBLOCK_8KB) if(SPARE_SIZE==24) { ST_SPARE* pSpare = (ST_SPARE*)pSpareBuffer; pSpare->dummy1 = WRITE_SYMBOL; pSpare->dummy2 = 0xFFFFFFFF; } #endif ithInvalidateDCacheRange(g_pNFspareBuf, SPARE_SIZE); // --- Set destination spare address AHB_WriteRegister(NF_REG_WRITE_SPARE_BASE_ADDR, (MMP_UINT32)g_pNFspareBuf); //HOST_WriteRegister(NF_REG_WRITE_SPARE_BASE_ADDR1, (MMP_UINT16)((MMP_UINT32)g_pNFspareBuf & 0x0000FFFF)); //HOST_WriteRegister(NF_REG_WRITE_SPARE_BASE_ADDR2, (MMP_UINT16)(((MMP_UINT32)g_pNFspareBuf & 0xFFFF0000) >> 16)); } else { ST_SPARE* pSpare = (ST_SPARE*)pSpareBuffer; #if defined(LARGEBLOCK_4KB) || defined(LARGEBLOCK_8KB) if(SPARE_SIZE==24) { ST_SPARE* pSpare = (ST_SPARE*)pSpareBuffer; pSpare->dummy1 = WRITE_SYMBOL; pSpare->dummy2 = 0xFFFFFFFF; } #endif ithInvalidateDCacheRange(pSpareBuffer, SPARE_SIZE); // --- Set destination spare address AHB_WriteRegister(NF_REG_WRITE_DATA_BASE_ADDR, (MMP_UINT32)pSpareBuffer); //HOST_WriteRegister(NF_REG_WRITE_SPARE_BASE_ADDR1, (MMP_UINT16)((MMP_UINT32)pSpareBuffer & 0x0000FFFF)); //HOST_WriteRegister(NF_REG_WRITE_SPARE_BASE_ADDR2, (MMP_UINT16)(((MMP_UINT32)pSpareBuffer & 0xFFFF0000) >> 16)); } AHB_WriteRegister(NF_REG_MEM_DST_CORR_ECC_ADDR, (MMP_UINT32)g_pNFeccBuf); #elif defined(WIN32) HOST_WriteBlockMemory((MMP_UINT32)g_pNFdataBuf, (MMP_UINT32)pDataBuffer, LbaAddr); //HOST_WriteBlockMemory((MMP_UINT32)g_pNFspareBuf, (MMP_UINT32)pSpareBuffer, SPARE_SIZE); AHB_WriteRegister(NF_REG_WRITE_DATA_BASE_ADDR, (MMP_UINT32)g_pNFdataBuf); AHB_WriteRegister(NF_REG_WRITE_SPARE_BASE_ADDR, (MMP_UINT32)g_pNFspareBuf); AHB_WriteRegister(NF_REG_MEM_DST_CORR_ECC_ADDR, (MMP_UINT32)g_pNFeccBuf); #endif // ---------------------------------------- // 5. Disable write protect bit AHB_WriteRegisterMask(NF_REG_GENERAL,0x00020000, 0x00020000); // 0x131A AHB_WriteRegisterMask(NF_REG_STORAGE_ADDR2, (MMP_UINT32)(SPARE_SIZE)<<8, 0x00001F00); // 0x1318 // ---------------------------------------- // 6. Fire HW and wait ready AHB_WriteRegisterMask(NF_REG_GENERAL, 0x00100000, 0x01F00000); AHB_WriteRegisterMask(NF_REG_GENERAL, ((PAGE_SIZE/ECC_PAGE_SIZE)-1)<<20, 0x01F00000); AHB_WriteRegister(NF_REG_CMD1, PROGRAM_CMD_1ST); AHB_WriteRegister(NF_REG_CMD2, PROGRAM_CMD_2ND); AHB_WriteRegister(NF_REG_CMD_FIRE, NF_CMD_FIRE); #if defined(NAND_IRQ_ENABLE) #else MMP_Sleep(1); #endif result = LB8K_HWECC_WaitCmdReady(NF_WRITE); //NAND write command fire AHB_WriteRegister(NF_REG_USER_DEF_CTRL, 0x00000000 ); // ---------------------------------------- // 7. Enable write protect bit and disable CE pin //HOST_WriteRegisterMask(NF_REG_GENERAL,(MMP_UINT16)0x0000,0x0800); // 0x1316 NAND_DbgPrintf("[LEAVE]LB8K_HWECC_Write: return %s\n", result == LL_OK ? "OK" : "FALSE"); return result; } MMP_UINT8 LB8K_HWECC_WriteDouble( MMP_UINT32 pba, MMP_UINT32 ppo, MMP_UINT8* pBuffer0, MMP_UINT8* pBuffer1) { MMP_UINT8 result = LL_ERROR; MMP_UINT32 realAddress = 0x00; #ifdef __FREERTOS__ MMP_UINT8* pAlignBuf0 = (MMP_UINT8*)(((MMP_UINT32)pBuffer0 + 3) & ~3); MMP_UINT8* pAlignBuf1 = (MMP_UINT8*)(((MMP_UINT32)pBuffer1 + 3) & ~3); #endif #ifdef SHOW_RWE_MSG printf("W2[%x,%x]\r\n",pba,ppo); //printf("W1[%x,%x,%x,%x]\r\n",pba,ppo,pDataBuffer,pSpareBuffer); #endif NAND_DbgPrintf("[ENTER]LB8K_HWECC_WriteDouble: pba(0x%X), ppo(0x%X)\n", pba, ppo); // ---------------------------------------- // 1. Switch controller to nand EnableNfControl(); if(IsEnHwScrambler) { AHB_WriteRegister(NF_REG_WR_SCRAMB_INIT, 0x000000FF); //AHB_WriteRegister(NF_REG_WR_SCRAMB_INIT, ppo);//reset scrambler initial value } // --- Calculate block position, and set block number if ( g_NfAttrib.bMultiDie ) { MMP_UINT32 dieNumber = pba / g_NfAttrib.blockPerDie; NfChipSelect(dieNumber); pba = pba - (g_NfAttrib.blockPerDie * dieNumber); } // ---------------------------------------- // 2. Calculate real address from input block address realAddress = ((pba * g_NfAttrib.pagePerBlock) + ppo) * PAGE_SIZE; // ---------------------------------------- // 3. Set program block address at nandflash region AHB_WriteRegister(NF_REG_STORAGE_ADDR1, (MMP_UINT32)realAddress); // ---------------------------------------- // 4. Set read/write address #ifdef __FREERTOS__ ithInvalidateDCacheRange(pBuffer0, PAGE_SIZE/2); if ( pAlignBuf0 != pBuffer0 ) { memcpy(g_pNFdataBuf, pBuffer0, PAGE_SIZE/2); } else { //NF_DmaCopy(g_pNFdataBuf, pBuffer0, PAGE_SIZE/2); memcpy(g_pNFdataBuf, pBuffer0, PAGE_SIZE/2); } ithInvalidateDCacheRange(pBuffer1, PAGE_SIZE/2 + SPARE_SIZE); if ( pAlignBuf1 != pBuffer1 ) { memcpy(g_pNFdataBuf + PAGE_SIZE/2, pBuffer1, PAGE_SIZE/2); memcpy(g_pNFspareBuf, pBuffer1 + PAGE_SIZE/2, SPARE_SIZE); } else { memcpy(g_pNFdataBuf + PAGE_SIZE/2, pBuffer1, PAGE_SIZE/2); memcpy(g_pNFspareBuf, pBuffer1 + PAGE_SIZE/2, SPARE_SIZE); //NF_DmaCopy(g_pNFdataBuf + PAGE_SIZE/2, pBuffer1, PAGE_SIZE/2); //NF_DmaCopy(g_pNFspareBuf, pBuffer1 + PAGE_SIZE/2, SPARE_SIZE); } #if defined(LARGEBLOCK_4KB) || defined(LARGEBLOCK_8KB) { ST_SPARE* pSpare = (ST_SPARE*)(g_pNFspareBuf); pSpare->dummy1 = WRITE_SYMBOL; pSpare->dummy2 = 0xFFFFFFFF; } #endif ithInvalidateDCacheRange(g_pNFdataBuf, PAGE_SIZE); ithInvalidateDCacheRange(g_pNFspareBuf, SPARE_SIZE); // --- Set source data address at VRAM AHB_WriteRegister(NF_REG_WRITE_DATA_BASE_ADDR, (MMP_UINT32)g_pNFdataBuf); AHB_WriteRegister(NF_REG_WRITE_SPARE_BASE_ADDR, (MMP_UINT32)g_pNFspareBuf); AHB_WriteRegister(NF_REG_MEM_DST_CORR_ECC_ADDR, (MMP_UINT32)g_pNFeccBuf); #elif defined(WIN32) #if defined(LARGEBLOCK_4KB) || defined(LARGEBLOCK_8KB) if(SPARE_SIZE==0x18) { ST_SPARE* pSpare = (ST_SPARE*)(pBuffer1 + PAGE_SIZE/2); pSpare->dummy1 = WRITE_SYMBOL; pSpare->dummy2 = 0xFFFFFFFF; } #endif HOST_WriteBlockMemory((MMP_UINT32)g_pNFdataBuf, (MMP_UINT32) pBuffer0, PAGE_SIZE/2); HOST_WriteBlockMemory((MMP_UINT32)g_pNFdataBuf + PAGE_SIZE/2, (MMP_UINT32)pBuffer1, PAGE_SIZE/2); HOST_WriteBlockMemory((MMP_UINT32)g_pNFspareBuf, (MMP_UINT32)(pBuffer1 + PAGE_SIZE/2), SPARE_SIZE); AHB_WriteRegister(NF_REG_WRITE_DATA_BASE_ADDR, (MMP_UINT32)g_pNFdataBuf); AHB_WriteRegister(NF_REG_WRITE_SPARE_BASE_ADDR, (MMP_UINT32)g_pNFspareBuf); AHB_WriteRegister(NF_REG_MEM_DST_CORR_ECC_ADDR, (MMP_UINT32)g_pNFeccBuf); #endif // ---------------------------------------- // 5. Disable write protect bit //HOST_WriteRegisterMask(NF_REG_GENERAL,(MMP_UINT16)0x0800, 0x0800); // 0x131A //HOST_WriteRegisterMask(NF_REG_STORAGE_ADDR3, (MMP_UINT16)0x0600, 0x1F00); // 0x1318 AHB_WriteRegisterMask(NF_REG_GENERAL,0x00020000, 0x00020000); // 0x131C AHB_WriteRegisterMask(NF_REG_STORAGE_ADDR2, (MMP_UINT32)(SPARE_SIZE)<<8, 0x00001F00); // 0x1318 // ---------------------------------------- // 6. Fire HW and wait ready AHB_WriteRegisterMask(NF_REG_GENERAL, ((PAGE_SIZE/ECC_PAGE_SIZE)-1)<<20, 0x01F00000); AHB_WriteRegister(NF_REG_CMD1, PROGRAM_CMD_1ST); AHB_WriteRegister(NF_REG_CMD2, PROGRAM_CMD_2ND); AHB_WriteRegister(NF_REG_CMD_FIRE, NF_CMD_FIRE); //NAND write command fire #if defined(NAND_IRQ_ENABLE) #else MMP_Sleep(1); #endif result = LB8K_HWECC_WaitCmdReady(NF_WRITE); // ---------------------------------------- // 7. Enable write protect bit and disable CE pin //HOST_WriteRegisterMask(NF_REG_GENERAL,(MMP_UINT16)0x0000,0x0800); // 0x1316 NAND_DbgPrintf("[LEAVE]LB8K_HWECC_WriteDouble: return %s\n", result == LL_OK ? "OK" : "FALSE"); return result; } MMP_UINT8 LB8K_HWECC_Read( MMP_UINT32 pba, MMP_UINT32 ppo, MMP_UINT8* pBuffer) { HWECC_RESP_TYPE eccResult; MMP_UINT8 result = LL_ERROR; MMP_UINT32 realAddress = 0x00; MMP_BOOL bIserased = MMP_TRUE; #ifdef __FREERTOS__ MMP_UINT8* pAlignBuf = (MMP_UINT8*)(((MMP_UINT32)pBuffer + 3) & ~3); #endif NAND_DbgPrintf("[ENTER]LB8K_HWECC_Read: pba(0x%X), ppo(0x%X), realAddress = 0x%08x\n", pba, ppo, (((pba * g_NfAttrib.pagePerBlock)+ ppo)* PAGE_SIZE)); #ifdef SHOW_RWE_MSG printf("R1[%x,%x]\n",pba,ppo); #endif // ---------------------------------------- // 1. Switch controller to nand EnableNfControl(); { MMP_UINT32 Reg32; //AHB_WriteRegisterMask(NF_REG_CMD_FIRE, NF_CMD_SW_RESET, NF_CMD_SW_RESET); if(IsEnHwScrambler) { AHB_WriteRegister(NF_REG_RD_SCRAMB_INIT, 0x000000FF); //AHB_WriteRegister(NF_REG_RD_SCRAMB_INIT, ppo);//reset scrambler initial value } } // --- Calculate block position, and set block number if ( g_NfAttrib.bMultiDie ) { MMP_UINT32 dieNumber = pba / g_NfAttrib.blockPerDie; NfChipSelect(dieNumber); pba = pba - (g_NfAttrib.blockPerDie * dieNumber); } // ---------------------------------------- // 2. Calculate real address from input block address realAddress = ((pba * g_NfAttrib.pagePerBlock) + ppo) * PAGE_SIZE; // ---------------------------------------- // 3. Set program block address at nandflash region AHB_WriteRegister(NF_REG_STORAGE_ADDR1, (MMP_UINT32)(realAddress) ); // ---------------------------------------- // 4. Set read/write address #ifdef __FREERTOS__ if ( pAlignBuf != pBuffer ) { // --- Set source data address at VRAM AHB_WriteRegister(NF_REG_READ_DATA_BASE_ADDR, (MMP_UINT32)g_pNFdataBuf); // --- Set destination spare address AHB_WriteRegister(NF_REG_READ_SPARE_BASE_ADDR, (MMP_UINT32)g_pNFspareBuf); } else { // --- Set source data address at VRAM AHB_WriteRegister(NF_REG_READ_DATA_BASE_ADDR, (MMP_UINT32)pBuffer); // --- Set destination spare address AHB_WriteRegister(NF_REG_READ_SPARE_BASE_ADDR, (MMP_UINT32)(pBuffer + PAGE_SIZE)); } #elif defined(WIN32) // // Do nothing in WIN32, because we won't change the address register! // #endif { //MMP_UINT8 TempBuff[PAGE_SIZE]; //MMP_UINT32 m; /* for(m=0;m<PAGE_SIZE;m++) { TempBuff[m]=0xAA; } HOST_WriteBlockMemory((MMP_UINT32)g_pNFdataBuf, (MMP_UINT32)TempBuff, PAGE_SIZE); HOST_WriteBlockMemory((MMP_UINT32)g_pNFspareBuf, (MMP_UINT32)TempBuff, SPARE_SIZE); */ /* for(m=0;m<PAGE_SIZE;m++) { TempBuff[m]=0x55; } HOST_ReadBlockMemory((MMP_UINT32)TempBuff, (MMP_UINT32)g_pNFdataBuf, PAGE_SIZE); for(m=0;m<PAGE_SIZE;m++) { TempBuff[m]=0x55; } HOST_ReadBlockMemory((MMP_UINT32)TempBuff, (MMP_UINT32)g_pNFspareBuf, SPARE_SIZE); */ } // ---------------------------------------- // 5. Fire HW and wait ready AHB_WriteRegister(NF_REG_CMD1, READ_CMD_1ST); AHB_WriteRegister(NF_REG_CMD2, READ_CMD_2ND); AHB_WriteRegisterMask(NF_REG_GENERAL, ((PAGE_SIZE/ECC_PAGE_SIZE)-1)<<20, 0x01F00000);// AHB_WriteRegister(NF_REG_CMD_FIRE, NF_CMD_FIRE); #if defined(NAND_IRQ_ENABLE) #else MMP_Sleep(1); #endif result = LB8K_HWECC_WaitCmdReady(NF_READ); if ( result == LL_OK ) { // ---------------------------------------- // 6. Get data back #ifdef __FREERTOS__ if ( pAlignBuf != pBuffer ) { ithInvalidateDCacheRange(g_pNFdataBuf, PAGE_SIZE); ithInvalidateDCacheRange(g_pNFspareBuf, SPARE_SIZE); memcpy(pBuffer, g_pNFdataBuf, PAGE_SIZE); memcpy(pBuffer + PAGE_SIZE, g_pNFspareBuf, SPARE_SIZE); //NF_DmaCopy(pBuffer, g_pNFdataBuf, PAGE_SIZE); //NF_DmaCopy(pBuffer + PAGE_SIZE, g_pNFspareBuf, SPARE_SIZE); //ithInvalidateDCacheRange(pBuffer, DATA_SIZE); } else { ithInvalidateDCacheRange(pBuffer, DATA_SIZE); } #elif defined(WIN32) HOST_ReadBlockMemory((MMP_UINT32)pBuffer, (MMP_UINT32)g_pNFdataBuf, PAGE_SIZE); HOST_ReadBlockMemory((MMP_UINT32)(pBuffer + PAGE_SIZE), (MMP_UINT32)g_pNFspareBuf, SPARE_SIZE); #endif // ---------------------------------------- // 7. Check if a erased block bIserased = IsErasedBlock((MMP_UINT8*)pBuffer, (MMP_UINT8*)(pBuffer + PAGE_SIZE)); // ---------------------------------------- // 8. Check ECC eccResult = LB8K_HWECC_CheckECC((MMP_UINT8*)pBuffer, (MMP_UINT8*)(pBuffer+PAGE_SIZE), !bIserased); switch(eccResult) { case NF_NOECCEN: case NF_NOERROR: break; case NF_ECCCORPASS: printf("LB8K_HWECC_Read: pba(%u), ppo(%u), eccResult == NF_ECCCORPASS\n", pba, ppo); break; case NF_PARITYADDRERR: printf("LB8K_HWECC_Read: ECC Correction failed. eccResult == PARITYADDRERR\n"); result = LL_ERROR; break; case NF_OVER4ERR: printf("LB8K_HWECC_Read: ECC Correction failed. eccResult == OVER4ERR\n"); result = LL_ERROR; break; default: printf("LB8K_HWECC_Read: Unknown ECC value. eccResult = %d\n", eccResult); result = LL_ERROR; break; } if ( result == LL_OK && bIserased == MMP_TRUE ) { result = LL_ERASED; } } NAND_DbgPrintf("[LEAVE]LB8K_HWECC_Read: return %s\n", result == LL_OK ? "OK" : result == LL_ERASED ? "ERASED" : "FALSE"); return result; } MMP_UINT8 LB8K_HWECC_LBA_Read( MMP_UINT32 pba, MMP_UINT32 ppo, MMP_UINT8* pBuffer) { HWECC_RESP_TYPE eccResult; MMP_UINT8 result = LL_ERROR; MMP_UINT32 realAddress = 0x00; MMP_BOOL bIserased = MMP_TRUE; MMP_UINT32 LbaPageSize = PAGE_SIZE+TOTAL_SPARE_SIZE; #ifdef __FREERTOS__ MMP_UINT8* pAlignBuf = (MMP_UINT8*)(((MMP_UINT32)pBuffer + 3) & ~3); #endif NAND_DbgPrintf("[ENTER]LB8K_HWECC_Read: pba(0x%X), ppo(0x%X), realAddress = 0x%08x\n", pba, ppo, (((pba * g_NfAttrib.pagePerBlock)+ ppo)* PAGE_SIZE)); #ifdef SHOW_RWE_MSG printf("Ru[%x,%x]\n",pba,ppo); #endif // ---------------------------------------- // 1. Switch controller to nand EnableNfControl(); { MMP_UINT32 Reg32; AHB_WriteRegisterMask(NF_REG_CMD_FIRE, NF_CMD_SW_RESET, NF_CMD_SW_RESET); // if(IsEnHwScrambler) { //it's scrambler bug, this register need to be reset after previous reading fire AHB_WriteRegister(NF_REG_RD_SCRAMB_INIT, 0x000000FF); //AHB_WriteRegister(NF_REG_RD_SCRAMB_INIT, ppo);//reset scrambler initial value } AHB_WriteRegister(NF_REG_USER_DEF_CTRL, 0x80000000|LbaPageSize ); } // --- Calculate block position, and set block number if ( g_NfAttrib.bMultiDie ) { MMP_UINT32 dieNumber = pba / g_NfAttrib.blockPerDie; NfChipSelect(dieNumber); pba = pba - (g_NfAttrib.blockPerDie * dieNumber); } // ---------------------------------------- // 2. Calculate real address from input block address realAddress = ((pba * g_NfAttrib.pagePerBlock) + ppo) * PAGE_SIZE; // ---------------------------------------- // 3. Set program block address at nandflash region AHB_WriteRegister(NF_REG_STORAGE_ADDR1, (MMP_UINT32)(realAddress) ); // ---------------------------------------- // 4. Set read/write address #ifdef __FREERTOS__ if ( pAlignBuf != pBuffer ) { // --- Set source data address at VRAM AHB_WriteRegister(NF_REG_READ_DATA_BASE_ADDR, (MMP_UINT32)g_pNFdataBuf); //HOST_WriteRegister(NF_REG_READ_DATA_BASE_ADDR1, (MMP_UINT16)((MMP_UINT32)(g_pNFdataBuf) & 0xffff)); //HOST_WriteRegister(NF_REG_READ_DATA_BASE_ADDR2, (MMP_UINT16)(((MMP_UINT32)(g_pNFdataBuf) & 0xffff0000) >> 16)); // --- Set destination spare address AHB_WriteRegister(NF_REG_READ_SPARE_BASE_ADDR, (MMP_UINT32)g_pNFspareBuf); //HOST_WriteRegister(NF_REG_READ_SPARE_BASE_ADDR1, (MMP_UINT16)((MMP_UINT32)(g_pNFspareBuf) & 0xffff)); //HOST_WriteRegister(NF_REG_READ_SPARE_BASE_ADDR2, (MMP_UINT16)(((MMP_UINT32)(g_pNFspareBuf) & 0xffff0000) >> 16)); } else { // --- Set source data address at VRAM AHB_WriteRegister(NF_REG_READ_DATA_BASE_ADDR, (MMP_UINT32)pBuffer); //HOST_WriteRegister(NF_REG_READ_DATA_BASE_ADDR1, (MMP_UINT16)((MMP_UINT32)pBuffer & 0xffff)); //HOST_WriteRegister(NF_REG_READ_DATA_BASE_ADDR2, (MMP_UINT16)(((MMP_UINT32)pBuffer & 0xffff0000) >> 16)); // --- Set destination spare address AHB_WriteRegister(NF_REG_READ_SPARE_BASE_ADDR, (MMP_UINT32)(pBuffer + PAGE_SIZE)); //HOST_WriteRegister(NF_REG_READ_SPARE_BASE_ADDR1, (MMP_UINT16)((MMP_UINT32)(pBuffer + PAGE_SIZE) & 0xffff)); //HOST_WriteRegister(NF_REG_READ_SPARE_BASE_ADDR2, (MMP_UINT16)(((MMP_UINT32)(pBuffer + PAGE_SIZE) & 0xffff0000) >> 16)); } #elif defined(WIN32) // // Do nothing in WIN32, because we won't change the address register! // #endif { //MMP_UINT8 TempBuff[PAGE_SIZE]; //MMP_UINT32 m; /* for(m=0;m<PAGE_SIZE;m++) { TempBuff[m]=0xAA; } HOST_WriteBlockMemory((MMP_UINT32)g_pNFdataBuf, (MMP_UINT32)TempBuff, PAGE_SIZE); HOST_WriteBlockMemory((MMP_UINT32)g_pNFspareBuf, (MMP_UINT32)TempBuff, SPARE_SIZE); */ /* for(m=0;m<PAGE_SIZE;m++) { TempBuff[m]=0x55; } HOST_ReadBlockMemory((MMP_UINT32)TempBuff, (MMP_UINT32)g_pNFdataBuf, PAGE_SIZE); for(m=0;m<PAGE_SIZE;m++) { TempBuff[m]=0x55; } HOST_ReadBlockMemory((MMP_UINT32)TempBuff, (MMP_UINT32)g_pNFspareBuf, SPARE_SIZE); */ } // ---------------------------------------- // 5. Fire HW and wait ready AHB_WriteRegister(NF_REG_CMD1, READ_CMD_1ST); AHB_WriteRegister(NF_REG_CMD2, READ_CMD_2ND); AHB_WriteRegisterMask(NF_REG_GENERAL, ((PAGE_SIZE/ECC_PAGE_SIZE)-1)<<20, 0x01F00000); AHB_WriteRegister(NF_REG_CMD_FIRE, NF_CMD_FIRE); #if defined(NAND_IRQ_ENABLE) #else MMP_Sleep(1); #endif //HOST_WriteRegister(NF_REG_CMD1,READ_CMD_1ST); //HOST_WriteRegister(NF_REG_CMD2,READ_CMD_2ND); result = LB8K_HWECC_WaitCmdReady(NF_READ); AHB_WriteRegister(NF_REG_USER_DEF_CTRL, 0x00000000 ); if ( result == LL_OK ) { // ---------------------------------------- // 6. Get data back #ifdef __FREERTOS__ if ( pAlignBuf != pBuffer ) { ithInvalidateDCacheRange(g_pNFdataBuf, PAGE_SIZE); ithInvalidateDCacheRange(g_pNFspareBuf, SPARE_SIZE); memcpy(pBuffer, g_pNFdataBuf, PAGE_SIZE); memcpy(pBuffer + PAGE_SIZE, g_pNFspareBuf, SPARE_SIZE); //NF_DmaCopy(pBuffer, g_pNFdataBuf, PAGE_SIZE); //NF_DmaCopy(pBuffer + PAGE_SIZE, g_pNFspareBuf, SPARE_SIZE); ithInvalidateDCacheRange(pBuffer, DATA_SIZE); } else { ithInvalidateDCacheRange(pBuffer, DATA_SIZE); } #elif defined(WIN32) HOST_ReadBlockMemory((MMP_UINT32)pBuffer, (MMP_UINT32)g_pNFdataBuf, LbaPageSize); //HOST_ReadBlockMemory((MMP_UINT32)pBuffer, (MMP_UINT32)g_pNFdataBuf, PAGE_SIZE); //HOST_ReadBlockMemory((MMP_UINT32)(pBuffer + PAGE_SIZE), (MMP_UINT32)g_pNFspareBuf, SPARE_SIZE); #endif // ---------------------------------------- // 7. Check if a erased block //bIserased = IsErasedBlock((MMP_UINT8*)pBuffer, (MMP_UINT8*)(pBuffer + PAGE_SIZE)); bIserased = IsErasedBlock( (MMP_UINT8*)pBuffer, (MMP_UINT8*)(pBuffer + PAGE_SIZE + (ECC_LENGTH*(PAGE_SIZE/ECC_PAGE_SIZE))) ); // ---------------------------------------- // 8. Check ECC //eccResult = LB8K_HWECC_CheckECC(pBuffer, pBuffer+PAGE_SIZE, !bIserased); eccResult = NF_NOERROR;//not finished yet switch(eccResult) { case NF_NOECCEN: case NF_NOERROR: break; case NF_ECCCORPASS: printf("LB8K_HWECC_LBA_Read: pba(%u), ppo(%u), eccResult == NF_ECCCORPASS\n", pba, ppo); break; case NF_PARITYADDRERR: printf("LB8K_HWECC_LBA_Read: ECC Correction failed. eccResult == PARITYADDRERR\n"); result = LL_ERROR; break; case NF_OVER4ERR: printf("LB8K_HWECC_LBA_Read: ECC Correction failed. eccResult == OVER4ERR\n"); result = LL_ERROR; break; default: printf("LB8K_HWECC_LBA_Read: Unknown ECC value. eccResult = %d\n", eccResult); result = LL_ERROR; break; } if ( result == LL_OK && bIserased == MMP_TRUE ) { result = LL_ERASED; } } NAND_DbgPrintf("[LEAVE]LB8K_HWECC_Read: return %s\n", result == LL_OK ? "OK" : result == LL_ERASED ? "ERASED" : "FALSE"); return result; } MMP_UINT8 LB8K_HWECC_ReadPart( MMP_UINT32 pba, MMP_UINT32 ppo, MMP_UINT8* pBuffer, MMP_UINT8 index) { HWECC_RESP_TYPE eccResult; MMP_UINT32 Reg32; MMP_UINT8 IsEnScrambler = 0; MMP_UINT8 result = LL_ERROR; MMP_UINT32 realAddress = 0x00; MMP_BOOL bIserased = MMP_TRUE; MMP_UINT8* pPagePointer = MMP_NULL; MMP_UINT8* pSparePointer = MMP_NULL; #ifdef __FREERTOS__ MMP_UINT8* pPagePt = MMP_NULL; #elif defined(WIN32) MMP_UINT8 tempBuf[DATA_SIZE]; #endif NAND_DbgPrintf("[ENTER]LB8K_HWECC_ReadPart: pba(0x%X), ppo(0x%X), index(0x%X), realAddress = 0x%08x\n", pba, ppo, index, (((pba * g_NfAttrib.pagePerBlock)+ ppo)* PAGE_SIZE)); #ifdef SHOW_RWE_MSG printf("R2[%x,%x,%x]\n",pba,ppo,index); #endif // ---------------------------------------- // 1. Switch controller to nand EnableNfControl(); //if( (pba==1) && (ppo==0x00) && (index==LL_RP_1STHALF) ) { //AHB_WriteRegisterMask(NF_REG_CMD_FIRE, NF_CMD_SW_RESET, NF_CMD_SW_RESET); if(IsEnHwScrambler) { AHB_WriteRegister(NF_REG_RD_SCRAMB_INIT, 0x000000FF);//reset scrambler initial value //AHB_WriteRegister(NF_REG_RD_SCRAMB_INIT, ppo);//reset scrambler initial value } } // --- Calculate block position, and set block number if ( g_NfAttrib.bMultiDie ) { MMP_UINT32 dieNumber = pba / g_NfAttrib.blockPerDie; NfChipSelect(dieNumber); pba = pba - (g_NfAttrib.blockPerDie * dieNumber); } // ---------------------------------------- // 2. Calculate real address from input block address #ifdef PITCH_ECC_1KB_ISSUE realAddress = ((pba * g_NfAttrib.pagePerBlock) + ppo) * PAGE_SIZE; #else switch(index) { case LL_RP_1STHALF: case LL_RP_DATA: realAddress = ((pba * g_NfAttrib.pagePerBlock) + ppo) * PAGE_SIZE; break; case LL_RP_2NDHALF: realAddress = (((pba * g_NfAttrib.pagePerBlock) + ppo) * PAGE_SIZE) + ((ECC_PAGE_SIZE+ECC_LENGTH)*((PAGE_SIZE/ECC_PAGE_SIZE)/2)); break; case LL_RP_SPARE: realAddress = (((pba * g_NfAttrib.pagePerBlock) + ppo) * PAGE_SIZE) + ((ECC_PAGE_SIZE+ECC_LENGTH)*((PAGE_SIZE/ECC_PAGE_SIZE)-1)); break; default: printf("LB8K_HWECC_ReadPart: Unknown ECC value. eccResult = %d\n", eccResult); result = LL_ERROR; break; } #endif // ---------------------------------------- // 3. Set program block address at nandflash region AHB_WriteRegister(NF_REG_STORAGE_ADDR1, (MMP_UINT32)(realAddress) ); // ---------------------------------------- // 4. Set read/write address #ifdef __FREERTOS__ // --- Set source data address at VRAM if( (index==LL_RP_DATA) && (((MMP_UINT32)pBuffer&0x03)==0) ) { // enhance read performance. joseph 2010.02.26 //printf("R2.2:set pBuffer=%x\n",pBuffer); AHB_WriteRegister(NF_REG_READ_DATA_BASE_ADDR, (MMP_UINT32)pBuffer); } else { //printf("R2.2:set g_pNFdataBuf=%x\n",g_pNFdataBuf); AHB_WriteRegister(NF_REG_READ_DATA_BASE_ADDR, (MMP_UINT32)g_pNFdataBuf); } // --- Set destination spare address AHB_WriteRegister(NF_REG_READ_SPARE_BASE_ADDR, (MMP_UINT32)g_pNFspareBuf); #elif defined(WIN32) // // Do nothing in WIN32, because we won't change the address register! // #endif // ---------------------------------------- // 5. Fire HW and wait ready //if( IsEnHwScrambler || ((index==LL_RP_DATA) || (index==LL_RP_SPARE)) ) #ifdef PITCH_ECC_1KB_ISSUE g_pNFeccCurrRdMask = g_BchMapMask; AHB_WriteRegisterMask(NF_REG_GENERAL, ((PAGE_SIZE/ECC_PAGE_SIZE)-1)<<20, 0x01F00000); #else if( IsEnHwScrambler || (index==LL_RP_DATA) ) { //printf("R2.2:set len1=%x\n",((PAGE_SIZE/ECC_PAGE_SIZE)-1) ); g_pNFeccCurrRdMask = g_BchMapMask; AHB_WriteRegisterMask(NF_REG_GENERAL, ((PAGE_SIZE/ECC_PAGE_SIZE)-1)<<20, 0x01F00000); } else if( (index==LL_RP_1STHALF) || (index==LL_RP_2NDHALF) ) { //printf("R2.2:set len2=%x\n",(((PAGE_SIZE/ECC_PAGE_SIZE)/2)-1) ); if(index==LL_RP_1STHALF) { g_pNFeccCurrRdMask = 0x0000000F; } else { g_pNFeccCurrRdMask = 0x000000F0; } AHB_WriteRegisterMask(NF_REG_GENERAL, (((PAGE_SIZE/ECC_PAGE_SIZE)/2)-1)<<20, 0x01F00000); } else if(index==LL_RP_SPARE) { //printf("R2.2:set len3=%x\n",0 ); g_pNFeccCurrRdMask = (1<<((PAGE_SIZE/ECC_PAGE_SIZE)-1)); AHB_WriteRegisterMask(NF_REG_GENERAL, 0x00000000, 0x01F00000); } #endif AHB_WriteRegister(NF_REG_CMD1, READ_CMD_1ST); AHB_WriteRegister(NF_REG_CMD2, READ_CMD_2ND); AHB_WriteRegister(NF_REG_CMD_FIRE, NF_CMD_FIRE); #if defined(NAND_IRQ_ENABLE) #else MMP_Sleep(1); #endif result = LB8K_HWECC_WaitCmdReady(NF_READ); if ( result == LL_OK ) { // ---------------------------------------- // 6. Get data back #if defined(__FREERTOS__) if( (index==LL_RP_DATA) && (((MMP_UINT32)pBuffer&0x03)==0) ) { // enhance read performance. joseph 2010.02.26 ithInvalidateDCacheRange(pBuffer, PAGE_SIZE); } else { #ifdef PITCH_ECC_1KB_ISSUE ithInvalidateDCacheRange(g_pNFdataBuf, PAGE_SIZE); #else ithInvalidateDCacheRange(g_pNFdataBuf, (PAGE_SIZE/2)); #endif } ithInvalidateDCacheRange(g_pNFspareBuf, SPARE_SIZE); if( (index==LL_RP_DATA) && (((MMP_UINT32)pBuffer&0x03)==0) ) { // enhance read performance. joseph 2010.02.26 pPagePointer = pBuffer; } else { pPagePointer = g_pNFdataBuf; } pSparePointer = g_pNFspareBuf; #elif defined(WIN32) if( IsEnHwScrambler || (index==LL_RP_DATA) ) { HOST_ReadBlockMemory((MMP_UINT32)tempBuf, (MMP_UINT32)g_pNFdataBuf, PAGE_SIZE); HOST_ReadBlockMemory((MMP_UINT32)tempBuf+PAGE_SIZE, (MMP_UINT32)g_pNFspareBuf, SPARE_SIZE); } else if( index==LL_RP_1STHALF ) { HOST_ReadBlockMemory((MMP_UINT32)tempBuf, (MMP_UINT32)g_pNFdataBuf, PAGE_SIZE/2); } else if(index==LL_RP_2NDHALF) { HOST_ReadBlockMemory((MMP_UINT32)tempBuf, (MMP_UINT32)g_pNFdataBuf, PAGE_SIZE/2); HOST_ReadBlockMemory((MMP_UINT32)tempBuf+PAGE_SIZE, (MMP_UINT32)g_pNFspareBuf, SPARE_SIZE); } else { HOST_ReadBlockMemory((MMP_UINT32)tempBuf, (MMP_UINT32)g_pNFdataBuf, PAGE_SIZE/4); HOST_ReadBlockMemory((MMP_UINT32)tempBuf+PAGE_SIZE, (MMP_UINT32)g_pNFspareBuf, SPARE_SIZE); } pPagePointer = tempBuf; pSparePointer = tempBuf+PAGE_SIZE; #endif // ---------------------------------------- // 7. Check if a erased block #ifdef PITCH_ECC_1KB_ISSUE bIserased = IsErasedBlock((MMP_UINT8*)pPagePointer, (MMP_UINT8*)pSparePointer); #else switch(index) { case LL_RP_1STHALF: //bIserased = IsErasedBlock((MMP_UINT8*)pPagePointer, (MMP_UINT8*)pPagePointer); bIserased = IsAllData0xFF((MMP_UINT8*)pPagePointer, 16); break; case LL_RP_2NDHALF: case LL_RP_DATA: case LL_RP_SPARE: default: bIserased = IsErasedBlock((MMP_UINT8*)pPagePointer, (MMP_UINT8*)pSparePointer); break; } #endif // ---------------------------------------- // 8. Check ECC eccResult = LB8K_HWECC_CheckECC((MMP_UINT8*)pPagePointer, (MMP_UINT8*)pSparePointer, !bIserased); switch(eccResult) { case NF_NOECCEN: case NF_NOERROR: break; case NF_ECCCORPASS: printf("LB8K_HWECC_ReadPart: pba(%u), ppo(%u), eccResult == NF_ECCCORPASS\n", pba, ppo); break; case NF_PARITYADDRERR: printf("LB8K_HWECC_ReadPart: ECC Correction failed. eccResult == PARITYADDRERR\n"); result = LL_ERROR; break; case NF_OVER4ERR: printf("LB8K_HWECC_ReadPart: ECC Correction failed. eccResult == OVER4ERR\n"); result = LL_ERROR; break; default: printf("LB8K_HWECC_ReadPart: Unknown ECC value. eccResult = %d\n", eccResult); result = LL_ERROR; break; } // ---------------------------------------- // 9. Copy data back to FTL if ( result == LL_OK ) { switch(index) { case LL_RP_1STHALF: #if defined(__FREERTOS__) if(pBuffer!=pPagePointer) { memcpy(pBuffer, pPagePointer, PAGE_SIZE/2); //NF_DmaCopy(pBuffer, pPagePointer, PAGE_SIZE/2); ithInvalidateDCacheRange(pBuffer, PAGE_SIZE/2); } //printf("R2.2:mcp1[%x,%x,%x]\n",pBuffer,pPagePointer,PAGE_SIZE/2 ); #elif defined(WIN32) memcpy(pBuffer, pPagePointer, PAGE_SIZE/2); #endif break; case LL_RP_2NDHALF: #if defined(__FREERTOS__) if(pBuffer!=pPagePointer) { #ifdef PITCH_ECC_1KB_ISSUE memcpy(pBuffer, pPagePointer+(PAGE_SIZE/2), PAGE_SIZE/2); #else memcpy(pBuffer, pPagePointer, PAGE_SIZE/2); #endif //NF_DmaCopy(pBuffer, pPagePointer+(PAGE_SIZE/2), PAGE_SIZE/2); ithInvalidateDCacheRange(pBuffer, PAGE_SIZE/2); } //printf("R2.2:mcp2[%x,%x,%x]\n",pBuffer,pPagePointer+(PAGE_SIZE/2),PAGE_SIZE/2 ); #elif defined(WIN32) if(IsEnHwScrambler) { memcpy(pBuffer, pPagePointer+(PAGE_SIZE/2), PAGE_SIZE/2); } else { memcpy(pBuffer, pPagePointer, PAGE_SIZE/2); } #endif break; case LL_RP_DATA: #if defined(__FREERTOS__) if((MMP_UINT32)pBuffer&0x03) { // enhance read performance. joseph 2010.02.26 memcpy(pBuffer, pPagePointer, PAGE_SIZE); //NF_DmaCopy(pBuffer, pPagePointer, PAGE_SIZE); } ithInvalidateDCacheRange(pBuffer, PAGE_SIZE); //printf("R2.2:mcp3[%x,%x,%x]%x\n",pBuffer,pPagePointer,PAGE_SIZE ); #elif defined(WIN32) memcpy(pBuffer, pPagePointer, PAGE_SIZE); #endif break; case LL_RP_SPARE: #if defined(__FREERTOS__) memcpy(pBuffer, pSparePointer, SPARE_SIZE); //NF_DmaCopy(pBuffer, pSparePointer, SPARE_SIZE); ithInvalidateDCacheRange(pBuffer, SPARE_SIZE); #elif defined(WIN32) memcpy(pBuffer, pSparePointer, SPARE_SIZE); //memcpy(pBuffer, pPagePointer+1024, SPARE_SIZE); #endif break; default: result = LL_ERROR; break; } } if ( result == LL_OK && bIserased == MMP_TRUE ) { result = LL_ERASED; } } g_pNFeccCurrRdMask = g_BchMapMask; NAND_DbgPrintf("[LEAVE]LB8K_HWECC_ReadPart: return %s\n", result == LL_OK ? "OK" : result == LL_ERASED ? "ERASED" : "FALSE"); return result; } MMP_UINT8 LB8K_HWECC_Read1kBytes( MMP_UINT32 pba, MMP_UINT32 ppo, MMP_UINT8* pBuffer, MMP_UINT8 index) { HWECC_RESP_TYPE eccResult; MMP_UINT32 Reg32; MMP_UINT8 IsEnScrambler = 0; MMP_UINT8 result = LL_ERROR; MMP_UINT32 realAddress = 0x00; MMP_BOOL bIserased = MMP_TRUE; MMP_UINT8* pPagePointer = MMP_NULL; MMP_UINT8* pSparePointer = MMP_NULL; #ifdef __FREERTOS__ MMP_UINT8* pPagePt = MMP_NULL; #elif defined(WIN32) MMP_UINT8 tempBuf[DATA_SIZE]; #endif NAND_DbgPrintf("[ENTER]LB8K_HWECC_Read1kB: pba(0x%X), ppo(0x%X), index(0x%X), realAddress = 0x%08x\n", pba, ppo, index, (((pba * g_NfAttrib.pagePerBlock)+ ppo)* PAGE_SIZE)); #ifdef SHOW_RWE_MSG printf("R4[%x,%x,%x]\n",pba,ppo,index); #endif // ---------------------------------------- // 1. Switch controller to nand EnableNfControl(); //if( (pba==1) && (ppo==0x00) && (index==1) ) { //AHB_WriteRegisterMask(NF_REG_CMD_FIRE, NF_CMD_SW_RESET, NF_CMD_SW_RESET); if(IsEnHwScrambler) { if(index==1) { AHB_WriteRegister(NF_REG_RD_SCRAMB_INIT, 0x000000FF);//reset scrambler initial value } } } // --- Calculate block position, and set block number if ( g_NfAttrib.bMultiDie ) { MMP_UINT32 dieNumber = pba / g_NfAttrib.blockPerDie; NfChipSelect(dieNumber); pba = pba - (g_NfAttrib.blockPerDie * dieNumber); } // ---------------------------------------- // 2. Calculate real address from input block address realAddress = (((pba * g_NfAttrib.pagePerBlock) + ppo) * PAGE_SIZE) + ((ECC_PAGE_SIZE+ECC_LENGTH)*(index-1)); // ---------------------------------------- // 3. Set program block address at nandflash region AHB_WriteRegister(NF_REG_STORAGE_ADDR1, (MMP_UINT32)(realAddress) ); // ---------------------------------------- // 4. Set read/write address #ifdef __FREERTOS__ // --- Set source data address at VRAM if( (index==LL_RP_DATA) && (((MMP_UINT32)pBuffer&0x03)==0) ) { // enhance read performance. joseph 2010.02.26 AHB_WriteRegister(NF_REG_READ_DATA_BASE_ADDR, (MMP_UINT32)pBuffer); //HOST_WriteRegister(NF_REG_READ_DATA_BASE_ADDR1, (MMP_UINT16)((MMP_UINT32)(pBuffer) & 0xffff)); //HOST_WriteRegister(NF_REG_READ_DATA_BASE_ADDR2, (MMP_UINT16)(((MMP_UINT32)(pBuffer) & 0xffff0000) >> 16)); } else { AHB_WriteRegister(NF_REG_READ_DATA_BASE_ADDR, (MMP_UINT32)g_pNFdataBuf); //HOST_WriteRegister(NF_REG_READ_DATA_BASE_ADDR1, (MMP_UINT16)((MMP_UINT32)(g_pNFdataBuf) & 0xffff)); //HOST_WriteRegister(NF_REG_READ_DATA_BASE_ADDR2, (MMP_UINT16)(((MMP_UINT32)(g_pNFdataBuf) & 0xffff0000) >> 16)); } // --- Set destination spare address AHB_WriteRegister(NF_REG_READ_DATA_BASE_ADDR, (MMP_UINT32)g_pNFspareBuf); //HOST_WriteRegister(NF_REG_READ_SPARE_BASE_ADDR1, (MMP_UINT16)((MMP_UINT32)(g_pNFspareBuf) & 0xffff)); //HOST_WriteRegister(NF_REG_READ_SPARE_BASE_ADDR2, (MMP_UINT16)(((MMP_UINT32)(g_pNFspareBuf) & 0xffff0000) >> 16)); #elif defined(WIN32) // // Do nothing in WIN32, because we won't change the address register! // #endif // ---------------------------------------- // 5. Fire HW and wait ready //if( IsEnHwScrambler || ((index==LL_RP_DATA) || (index==LL_RP_SPARE)) ) AHB_WriteRegisterMask(NF_REG_GENERAL, 0x00000000, 0x01F00000); AHB_WriteRegister(NF_REG_CMD1, READ_CMD_1ST); AHB_WriteRegister(NF_REG_CMD2, READ_CMD_2ND); AHB_WriteRegister(NF_REG_CMD_FIRE, NF_CMD_FIRE); #if defined(NAND_IRQ_ENABLE) #else MMP_Sleep(1); #endif result = LB8K_HWECC_WaitCmdReady(NF_READ); if ( result == LL_OK ) { // ---------------------------------------- // 6. Get data back #if defined(__FREERTOS__) if( (index==LL_RP_DATA) && (((MMP_UINT32)pBuffer&0x03)==0) ) { // enhance read performance. joseph 2010.02.26 ithInvalidateDCacheRange(pBuffer, PAGE_SIZE); } else { ithInvalidateDCacheRange(g_pNFdataBuf, PAGE_SIZE); } ithInvalidateDCacheRange(g_pNFspareBuf, SPARE_SIZE); if( (index==LL_RP_DATA) && (((MMP_UINT32)pBuffer&0x03)==0) ) { // enhance read performance. joseph 2010.02.26 pPagePointer = pBuffer; } else { pPagePointer = g_pNFdataBuf; } pSparePointer = g_pNFspareBuf; #elif defined(WIN32) HOST_ReadBlockMemory((MMP_UINT32)tempBuf, (MMP_UINT32)g_pNFdataBuf, ECC_PAGE_SIZE); pPagePointer = tempBuf; //pSparePointer = tempBuf+PAGE_SIZE; #endif // ---------------------------------------- // 7. Check if a erased block bIserased = IsAllData0xFF(pPagePointer, 16); // ---------------------------------------- // 8. Check ECC eccResult = LB8K_HWECC_CheckECC(pPagePointer, pSparePointer, !bIserased); switch(eccResult) { case NF_NOECCEN: case NF_NOERROR: break; case NF_ECCCORPASS: printf("LB8K_HWECC_ReadPart: pba(%u), ppo(%u), eccResult == NF_ECCCORPASS\n", pba, ppo); break; case NF_PARITYADDRERR: printf("LB8K_HWECC_ReadPart: ECC Correction failed. eccResult == PARITYADDRERR\n"); result = LL_ERROR; break; case NF_OVER4ERR: printf("LB8K_HWECC_ReadPart: ECC Correction failed. eccResult == OVER4ERR\n"); result = LL_ERROR; break; default: printf("LB8K_HWECC_ReadPart: Unknown ECC value. eccResult = %d\n", eccResult); result = LL_ERROR; break; } // ---------------------------------------- // 9. Copy data back to FTL if ( result == LL_OK ) { memcpy(pBuffer, pPagePointer, ECC_PAGE_SIZE); } if ( result == LL_OK && bIserased == MMP_TRUE ) { result = LL_ERASED; } } NAND_DbgPrintf("[LEAVE]LB8K_HWECC_ReadPart: return %s\n", result == LL_OK ? "OK" : result == LL_ERASED ? "ERASED" : "FALSE"); return result; } MMP_UINT8 LB8K_HWECC_IsBadBlock( MMP_UINT32 pba) { MMP_UINT8 result = LL_ERROR; MMP_UINT8 blockStatus = LL_ERROR; MMP_UINT32 firstPage = 0; MMP_UINT32 lastPage = g_NfAttrib.pagePerBlock - 1; MMP_UINT8 dataBuffer[DATA_SIZE+SPARE_SIZE]; NAND_DbgPrintf("[ENTER]LB8K_HWECC_IsBadBlock: pba(%d), realAddress = 0x%08x\n", pba, ((pba * g_NfAttrib.pagePerBlock)* PAGE_SIZE)); #ifdef SHOW_RWE_MSG printf("IBB[%x,%x]\n",pba,dataBuffer); #endif // ---------------------------------------- // 0. PRECONDITION if ( pba >= g_NfAttrib.numOfBlocks ) { printf("\tLB8K_HWECC_IsBadBlock: ERROR! pba(%u) >= g_NfAttrib.numOfBlocks(%u)\n", pba, g_NfAttrib.numOfBlocks); return LL_ERROR; } // 1. Switch controller to nand EnableNfControl(); // --- Calculate block position, and set block number if ( g_NfAttrib.bMultiDie ) { MMP_UINT32 dieNumber = pba / g_NfAttrib.blockPerDie; NfChipSelect(dieNumber); pba = pba - (g_NfAttrib.blockPerDie * dieNumber); } #ifdef NF_NAND_BOOT // Reserve boot section // Reserve 2M in large block ReservedBlockNum = 8 * 1024 * 1024 / (g_NfAttrib.pagePerBlock * g_NfAttrib.pageSize); if ( (pba >= 0) && (pba < ReservedBlockNum) ) return LL_ERROR; #elif defined(NF_USE_OLD_VERSION) // Reserve boot section // Reserve 8M in small block ReservedBlockNum = 8 * 1024 * 1024 / (g_NfAttrib.pagePerBlock * g_NfAttrib.pageSize); if ( (pba >= 0) && (pba < ReservedBlockNum) ) return LL_ERROR; #endif // ---------------------------------------- // 2. Read first page { MMP_UINT8 bIibResult; ST_SPARE* pSpare = MMP_NULL; bIibResult = LB8K_HWECC_Read(pba, 0, dataBuffer); pSpare = (ST_SPARE*)(dataBuffer + PAGE_SIZE); //printf("Spr->dummy1=%08x,[%08x]\r\n",pSpare->dummy1,WRITE_SYMBOL); #if defined(LARGEBLOCK_4KB) || defined(LARGEBLOCK_8KB) if ( (SPARE_SIZE==0x18) && (pSpare->dummy1 == WRITE_SYMBOL) ) { blockStatus = LL_OK; } else #endif { MMP_UINT8 IfDataEqual00FF=LL_OK; MMP_UINT32 *PtCmprData0,i; if( g_NfAttrib.pagePerBlock==0x80 ) { PtCmprData0=(MMP_UINT32 *)dataBuffer; //try to find out the MLC flash that has error data at page0.(ex:writed by other NAND controller) if(IsEnHwScrambler) { if(IsAllData0xFF(dataBuffer, 16)==MMP_FALSE) { printf("this NAND flash does NOT match our NAND DATA structure[1]\r\n"); IfDataEqual00FF = LL_ERROR; } if(IsErasedBlock((MMP_UINT8*)dataBuffer, (MMP_UINT8*)pSpare)==MMP_FALSE) { printf("this NAND flash does NOT match our NAND DATA structure[2]\r\n"); IfDataEqual00FF = LL_ERROR; } } else { for(i=0;i<DATA_SIZE/4;i++) { if( (PtCmprData0[i]) && (PtCmprData0[i]!=0xFFFFFFFF) ) { printf("this NAND flash does NOT match our NAND DATA structure[3][%x,%x]\n",i,PtCmprData0[i]); { MMP_UINT32 k; for(k=0;k<1024;k++) { printf("%02x ",dataBuffer[k]); if( (k&0x1FF)==0x1FF ) printf("\n[%x]",k+1); if( (k&0x0F)==0x0F ) printf("\n"); } } IfDataEqual00FF = LL_ERROR; break; } } } } if( IfDataEqual00FF == LL_OK ) { if ( g_NfAttrib.pfCheckMethod == MMP_NULL ) { printf("LB8K_HWECC_IsBadBlock: ERROR! g_NfAttrib.pfCheckMethod == MMP_NULL\n"); blockStatus = LL_ERROR; } else { blockStatus = g_NfAttrib.pfCheckMethod(pba); } } } } NAND_DbgPrintf("[LEAVE]LB8K_HWECC_IsBadBlock: pba(%d), %s\n", pba, blockStatus == LL_OK ? "Normal Block" : "Bad Block"); return blockStatus; } MMP_UINT8 LB8K_HWECC_IsBadBlockForBoot( MMP_UINT32 pba) { MMP_UINT8 result = LL_ERROR; MMP_UINT8 blockStatus = LL_ERROR; MMP_UINT32 firstPage = 0; MMP_UINT32 lastPage = g_NfAttrib.pagePerBlock - 1; MMP_UINT8 dataBuffer[DATA_SIZE]; NAND_DbgPrintf("[ENTER]LB8K_HWECC_IsBadBlock: pba(%d), realAddress = 0x%08x\n", pba, ((pba * g_NfAttrib.pagePerBlock)* PAGE_SIZE)); // ---------------------------------------- // 0. PRECONDITION if ( pba >= g_NfAttrib.numOfBlocks ) { printf("\tLB8K_HWECC_IsBadBlock: ERROR! pba(%u) >= g_NfAttrib.numOfBlocks(%u)\n", pba, g_NfAttrib.numOfBlocks); return LL_ERROR; } // 1. Switch controller to nand EnableNfControl(); // --- Calculate block position, and set block number if ( g_NfAttrib.bMultiDie ) { MMP_UINT32 dieNumber = pba / g_NfAttrib.blockPerDie; NfChipSelect(dieNumber); pba = pba - (g_NfAttrib.blockPerDie * dieNumber); } // ---------------------------------------- // 2. Read first page { MMP_UINT8 bIibResult; ST_SPARE* pSpare = MMP_NULL; bIibResult = LB8K_HWECC_Read(pba, 0, dataBuffer); pSpare = (ST_SPARE*)(dataBuffer + PAGE_SIZE); //printf("Spr->dummy1=%08x,[%08x]\r\n",pSpare->dummy1,WRITE_SYMBOL); #if defined(LARGEBLOCK_4KB) || defined(LARGEBLOCK_8KB) if ( (SPARE_SIZE==0x18) && (pSpare->dummy1 == WRITE_SYMBOL) ) { blockStatus = LL_OK; } else #endif { MMP_UINT8 IfDataEqual00FF=LL_OK; MMP_UINT32 *PtCmprData0,i; if( g_NfAttrib.pagePerBlock==0x80 ) { PtCmprData0=(MMP_UINT32 *)dataBuffer; //try to find out the MLC flash that has error data at page0.(ex:writed by other NAND controller) for(i=0;i<DATA_SIZE/4;i++) { if( (PtCmprData0[i]) && (PtCmprData0[i]!=0xFFFFFFFF) ) { printf("this NAND flash does NOT match our NAND DATA structure[0]\r\n"); IfDataEqual00FF = LL_ERROR; break; } } } if( IfDataEqual00FF == LL_OK ) { if ( g_NfAttrib.pfCheckMethod == MMP_NULL ) { printf("LB8K_HWECC_IsBadBlock: ERROR! g_NfAttrib.pfCheckMethod == MMP_NULL\n"); blockStatus = LL_ERROR; } else { blockStatus = g_NfAttrib.pfCheckMethod(pba); } } } } NAND_DbgPrintf("[LEAVE]LB8K_HWECC_IsBadBlock: pba(%d), %s\n", pba, blockStatus == LL_OK ? "Normal Block" : "Bad Block"); return blockStatus; } MMP_UINT8 LB8K_HWECC_ReadOneByte( MMP_UINT32 pba, MMP_UINT32 ppo, MMP_UINT8 offsetPos, MMP_UINT8* pByte) { HWECC_RESP_TYPE eccResult; MMP_UINT8 result = LL_ERROR; MMP_UINT32 realAddress = 0x00; MMP_BOOL bIserased = MMP_TRUE; MMP_UINT8* pPagePointer = MMP_NULL; MMP_UINT8* pSparePointer = MMP_NULL; MMP_UINT8 dataBuffer[DATA_SIZE]; NAND_DbgPrintf("[ENTER]LB8K_HWECC_ReadOneByte: pba(0x%X), ppo(0x%X), sparepos(0x%X), realAddress = 0x%08x\n", pba, ppo, offsetPos, (((pba * g_NfAttrib.pagePerBlock)+ ppo)* PAGE_SIZE)); #ifdef SHOW_RWE_MSG printf("R3[%x,%x,%x]\n",pba,ppo,offsetPos); #endif // ---------------------------------------- // 1. Switch controller to nand EnableNfControl(); { //AHB_WriteRegisterMask(NF_REG_CMD_FIRE, NF_CMD_SW_RESET, NF_CMD_SW_RESET); if(IsEnHwScrambler) { AHB_WriteRegister(NF_REG_RD_SCRAMB_INIT, 0x000000FF); //AHB_WriteRegister(NF_REG_RD_SCRAMB_INIT, ppo);//reset scrambler initial value } } // --- Calculate block position, and set block number if ( g_NfAttrib.bMultiDie ) { MMP_UINT32 dieNumber = pba / g_NfAttrib.blockPerDie; NfChipSelect(dieNumber); pba = pba - (g_NfAttrib.blockPerDie * dieNumber); } // ---------------------------------------- // 2. Calculate real address from input block address if(IsEnHwScrambler) { realAddress = ((pba * g_NfAttrib.pagePerBlock) + ppo) * PAGE_SIZE; } else { #ifdef PITCH_ECC_1KB_ISSUE realAddress = ((pba * g_NfAttrib.pagePerBlock) + ppo) * PAGE_SIZE; #else realAddress = (((pba * g_NfAttrib.pagePerBlock) + ppo) * PAGE_SIZE) + ((ECC_PAGE_SIZE+ECC_LENGTH)*((PAGE_SIZE/ECC_PAGE_SIZE)-1)); #endif } // ---------------------------------------- // 3. Set program block address at nandflash region AHB_WriteRegister(NF_REG_STORAGE_ADDR1, (MMP_UINT32)realAddress); // ---------------------------------------- // 4. Set read/write address #ifdef __FREERTOS__ // --- Set source data address at VRAM AHB_WriteRegister(NF_REG_READ_DATA_BASE_ADDR, (MMP_UINT32)g_pNFdataBuf); // --- Set destination spare address AHB_WriteRegister(NF_REG_READ_SPARE_BASE_ADDR, (MMP_UINT32)g_pNFspareBuf); #elif defined(WIN32) // // Do nothing in WIN32, because we won't change the address register! // #endif // ---------------------------------------- // 5. Fire HW and wait ready if(IsEnHwScrambler) { g_pNFeccCurrRdMask = g_BchMapMask; AHB_WriteRegisterMask(NF_REG_GENERAL, ((PAGE_SIZE/ECC_PAGE_SIZE)-1)<<20, 0x01F00000); } else { #ifdef PITCH_ECC_1KB_ISSUE g_pNFeccCurrRdMask = g_BchMapMask; AHB_WriteRegisterMask(NF_REG_GENERAL, ((PAGE_SIZE/ECC_PAGE_SIZE)-1)<<20, 0x01F00000); #else g_pNFeccCurrRdMask = 0x00000001<<((PAGE_SIZE/ECC_PAGE_SIZE)-1); AHB_WriteRegisterMask(NF_REG_GENERAL, 0x00000000, 0x01F00000); #endif } AHB_WriteRegister(NF_REG_CMD1, READ_CMD_1ST); AHB_WriteRegister(NF_REG_CMD2, READ_CMD_2ND); AHB_WriteRegister(NF_REG_CMD_FIRE, NF_CMD_FIRE); #if defined(NAND_IRQ_ENABLE) #else MMP_Sleep(1); #endif result = LB8K_HWECC_WaitCmdReady(NF_READ); if ( result == LL_OK ) { // ---------------------------------------- // 6. Get data back #ifdef __FREERTOS__ ithInvalidateDCacheRange(g_pNFdataBuf, PAGE_SIZE); ithInvalidateDCacheRange(g_pNFspareBuf, SPARE_SIZE); pPagePointer = g_pNFdataBuf; pSparePointer = g_pNFspareBuf; #elif defined(WIN32) HOST_ReadBlockMemory((MMP_UINT32)(dataBuffer + PAGE_SIZE), (MMP_UINT32)g_pNFspareBuf, SPARE_SIZE); pPagePointer = dataBuffer; pSparePointer = dataBuffer + PAGE_SIZE; #endif // ---------------------------------------- // 7. Check if a erased block bIserased = IsErasedBlock((MMP_UINT8*)pPagePointer, (MMP_UINT8*)pSparePointer); // ---------------------------------------- // 8. Check ECC eccResult = LB8K_HWECC_CheckECC(pPagePointer, pSparePointer, !bIserased); switch(eccResult) { case NF_NOECCEN: case NF_NOERROR: break; case NF_ECCCORPASS: printf("LB8K_HWECC_Read 1B: pba(%u), ppo(%u), eccResult == NF_ECCCORPASS\n", pba, ppo); break; case NF_PARITYADDRERR: printf("LB8K_HWECC_Read 1B: ECC Correction failed. eccResult == PARITYADDRERR\n"); result = LL_ERROR; break; case NF_OVER4ERR: printf("LB8K_HWECC_Read 1B: ECC Correction failed. eccResult == OVER4ERR\n"); result = LL_ERROR; break; default: printf("LB8K_HWECC_Read 1B: Unknown ECC value. eccResult = %d\n", eccResult); result = LL_ERROR; break; } if ( result == LL_OK ) { *pByte= *(pSparePointer + offsetPos); } } g_pNFeccCurrRdMask = g_BchMapMask; NAND_DbgPrintf("[LEAVE]LB8K_HWECC_ReadOneByte: *ch = 0x%X, result(%d)\n", *pByte, result); return result; } /**************************************************************************** * * LB8K_HWECC_GetAttribute * * Get nandflash type * * RETURNS * * NfType-> TRUE: LARGE * FALSE: SMALL * EccStatus-> TRUE: HWECC * FALSE: SWECC * ***************************************************************************/ void LB8K_HWECC_GetAttribute( MMP_BOOL* NfType, MMP_BOOL* EccStatus) { #ifdef LARGEBLOCK_2KB *NfType = MMP_TRUE; #else *NfType = MMP_FALSE; #endif #ifdef NF_HW_ECC *EccStatus = MMP_TRUE; #else *EccStatus = MMP_FALSE; #endif } unsigned char* LB8K_HWECC_GetBlockErrorRecord() { #ifdef LB_ECC_RECORD return g_pBlockErrorRecord; #else return MMP_NULL; #endif } static MMP_UINT32 GetNandId( MMP_UINT8 chipIndex, NF_ATTRIBUTE* pNfAttrib) { MMP_UINT32 result = LL_OK; MMP_UINT16 regData1, regData2; MMP_UINT32 IdCycles = READ_ID_4_CYCLE; MMP_UINT32 ID0=0, ID1=0; MMP_UINT32 NfTmpStatus=0; if ( !NfChipSelect(chipIndex) ) return LL_ERROR; if ( NAND_CMD_2ND_READ70_STATUS(&NfTmpStatus) == LL_ERROR ) return LL_ERROR; AHB_WriteRegister(NF_REG_CMD2, RESET_CMD_2ST); AHB_WriteRegister(NF_REG_CMD_FIRE, NF_CMD_FIRE); result = LB8K_HWECC_WaitCmdReady(NF_READ_ID); result = NAND_CMD_1ST_READID90(&ID0, &ID1, IdCycles); printf("ret=%x\n",result); if ( !result ) { MMP_UINT8 Byte1, Byte2, Byte3, Byte4; regData1 = ID0 & 0x0000FFFF; regData2 = (ID0&0xFFFF0000)>>16; Byte1 = regData1 & 0x00FF; Byte2 = (regData1 & 0xFF00) >> 8; Byte3 = regData2 & 0x00FF; Byte4 = (regData2 & 0xFF00) >> 8; // Awin@20071015 NAND_DbgPrintf("GetNandId: ID1 = 0x%04X.\n\r", regData1); NAND_DbgPrintf("GetNandId: ID2 = 0x%04X.\n\r", regData2); printf("GetNandId: ID1 = 0x%04X.\n\r", regData1); printf("GetNandId: ID2 = 0x%04X.\n\r", regData2); switch(Byte1) { case 0xAD: // Hynix if ( HynixNandflash(regData1, regData2, pNfAttrib) == MMP_FALSE ) { printf("GetNandId: Get Hynix Nandflash ID Failed. ID = 0x%02X 0x%02X 0x%02X 0x%02X\n", Byte1, Byte2, Byte3, Byte4); result = LL_ERROR; } break; case 0x98: // Toshiba if ( ToshibaNandflash(regData1, regData2, pNfAttrib) == MMP_FALSE ) { printf("GetNandId: Get Toshiba Nandflash ID Failed. ID = 0x%02X 0x%02X 0x%02X 0x%02X\n", Byte1, Byte2, Byte3, Byte4); result = LL_ERROR; } break; case 0xEC: // Samsung if ( SamsungNandflash(regData1, regData2, pNfAttrib) == MMP_FALSE ) { printf("GetNandId: Get Samsung Nandflash ID Failed. ID = 0x%02X 0x%02X 0x%02X 0x%02X\n", Byte1, Byte2, Byte3, Byte4); result = LL_ERROR; } break; case 0x20: // Numonyx if ( NumonyxNandflash(regData1, regData2, pNfAttrib) == MMP_FALSE ) { printf("GetNandId: Get Numonyx Nandflash ID Failed. ID = 0x%02X 0x%02X 0x%02X 0x%02X\n", Byte1, Byte2, Byte3, Byte4); result = LL_ERROR; } break; case 0x92: // PowerFlash if ( PowerFlashNandflash(regData1, regData2, pNfAttrib) == MMP_FALSE ) { printf("GetNandId: Get Numonyx Nandflash ID Failed. ID = 0x%02X 0x%02X 0x%02X 0x%02X\n", Byte1, Byte2, Byte3, Byte4); result = LL_ERROR; } break; default: result = LL_ERROR; break; } } return result; } static MMP_BOOL HynixNandflash( MMP_UINT16 ID1, MMP_UINT16 ID2, NF_ATTRIBUTE* pNfAttrib) { MMP_UINT32 BlockSize = 0; MMP_BOOL bResult = MMP_TRUE; MMP_UINT32 NandId = 0; MMP_UINT32 nandSize = 0; MMP_UINT32 blockSize = 0; NandId=((MMP_UINT32)ID2 << 16) | (MMP_UINT32)ID1; switch( NandId) { case 0x1D80F1AD: nandSize = 128 * 1024 * 1024; // Bytes blockSize = 128 * 1024; // Bytes pNfAttrib->ID1 = ID1; pNfAttrib->ID2 = ID2; pNfAttrib->nandMaker = NAND_MAKER_HYNIX; pNfAttrib->checkMethod = NAND_HYNIX_METHOD_01; pNfAttrib->pfCheckMethod = _IsBadBlockHynixMethod01; pNfAttrib->pageSize = 2048; pNfAttrib->pagePerBlock = blockSize / pNfAttrib->pageSize; pNfAttrib->numOfBlocks = nandSize / blockSize; pNfAttrib->clockValue = 0x00333333; pNfAttrib->register701C = 0x0884; strcpy(pNfAttrib->modelName, "HY27UF081G2A"); break; case 0x9510DAAD: // This model has 5 bytes ID, that is 0xAD DA 10 95 44 nandSize = (MMP_UINT32)256 * 1024 * 1024; // Bytes blockSize = 128 * 1024; // Bytes pNfAttrib->ID1 = ID1; pNfAttrib->ID2 = ID2; pNfAttrib->nandMaker = NAND_MAKER_HYNIX; pNfAttrib->checkMethod = NAND_HYNIX_METHOD_01; pNfAttrib->pfCheckMethod = _IsBadBlockHynixMethod01; pNfAttrib->pageSize = 2048; pNfAttrib->pagePerBlock = blockSize / pNfAttrib->pageSize; pNfAttrib->numOfBlocks = nandSize / blockSize; pNfAttrib->clockValue = 0x00333333; pNfAttrib->register701C = 0x0885; strcpy(pNfAttrib->modelName, "HY27UF082G2B"); break; case 0xA514DCAD: nandSize = 512 * 1024 * 1024; // Bytes blockSize = 256 * 1024; // Bytes pNfAttrib->ID1 = ID1; pNfAttrib->ID2 = ID2; pNfAttrib->nandMaker = NAND_MAKER_HYNIX; pNfAttrib->checkMethod = NAND_HYNIX_METHOD_02; pNfAttrib->pfCheckMethod = _IsBadBlockHynixMethod02; pNfAttrib->pageSize = 2048; pNfAttrib->pagePerBlock = blockSize / pNfAttrib->pageSize; pNfAttrib->numOfBlocks = nandSize / blockSize; pNfAttrib->clockValue = 0x00333333; pNfAttrib->register701C = 0x0885; strcpy(pNfAttrib->modelName, "HY27UT084G2A"); break; case 0xA514D3AD: // This model has 5 bytes ID, that is 0xAD D3 14 A5 34 nandSize = (MMP_UINT32)1024 * 1024 * 1024; // Bytes blockSize = 256 * 1024; // Bytes pNfAttrib->ID1 = ID1; pNfAttrib->ID2 = ID2; pNfAttrib->nandMaker = NAND_MAKER_HYNIX; pNfAttrib->checkMethod = NAND_HYNIX_METHOD_02; pNfAttrib->pfCheckMethod = _IsBadBlockHynixMethod02; pNfAttrib->pageSize = 2048; pNfAttrib->pagePerBlock = blockSize / pNfAttrib->pageSize; pNfAttrib->numOfBlocks = nandSize / blockSize; pNfAttrib->clockValue = 0x00333333; pNfAttrib->register701C = 0x0885; strcpy(pNfAttrib->modelName, "HY27UT088G2A"); break; case 0xA555D5AD: // This model has 5 bytes ID, that is 0xAD D5 55 A5 38 nandSize = (MMP_UINT32)2048 * 1024 * 1024; // Bytes blockSize = 256 * 1024; // Bytes pNfAttrib->ID1 = ID1; pNfAttrib->ID2 = ID2; pNfAttrib->nandMaker = NAND_MAKER_HYNIX; pNfAttrib->checkMethod = NAND_HYNIX_METHOD_02; pNfAttrib->pfCheckMethod = _IsBadBlockHynixMethod02; pNfAttrib->pageSize = 2048; pNfAttrib->pagePerBlock = blockSize / pNfAttrib->pageSize; pNfAttrib->numOfBlocks = nandSize / blockSize; pNfAttrib->clockValue = 0x00333333; pNfAttrib->register701C = 0x0885; strcpy(pNfAttrib->modelName, "HY27UV08BG5A"); break; default: bResult = MMP_FALSE; break; } return bResult; } static MMP_BOOL ToshibaNandflash( MMP_UINT16 ID1, MMP_UINT16 ID2, NF_ATTRIBUTE* pNfAttrib) { MMP_UINT32 BlockSize = 0; MMP_BOOL bResult = MMP_TRUE; MMP_UINT32 NandId = 0; MMP_UINT32 nandSize = 0; MMP_UINT32 blockSize = 0; NandId=((MMP_UINT32)ID2 << 16) | (MMP_UINT32)ID1; switch( NandId) { case 0x1590D198: // This model has 4 bytes ID, that is 0x98 D1 90 15 nandSize = 128 * 1024 * 1024; // Bytes blockSize = 128 * 1024; // Bytes pNfAttrib->ID1 = ID1; pNfAttrib->ID2 = ID2; pNfAttrib->nandMaker = NAND_MAKER_TOSHIBA; pNfAttrib->checkMethod = NAND_TOSHIBA_METHOD_01; pNfAttrib->pfCheckMethod = _IsBadBlockToshibaMethod01; pNfAttrib->pageSize = 2048; pNfAttrib->pagePerBlock = blockSize / pNfAttrib->pageSize; pNfAttrib->numOfBlocks = nandSize / blockSize; pNfAttrib->clockValue = 0x00333333; pNfAttrib->register701C = 0x0884; strcpy(pNfAttrib->modelName, "TC58NVG0S3ETA00"); break; case 0x1590DA98: // This model has 5 bytes ID, that is 0x98 DA 90 15 nandSize = 256 * 1024 * 1024; // Bytes blockSize = 128 * 1024; // Bytes pNfAttrib->ID1 = ID1; pNfAttrib->ID2 = ID2; pNfAttrib->nandMaker = NAND_MAKER_TOSHIBA; pNfAttrib->checkMethod = NAND_TOSHIBA_METHOD_01; pNfAttrib->pfCheckMethod = _IsBadBlockToshibaMethod01; pNfAttrib->pageSize = 2048; pNfAttrib->pagePerBlock = blockSize / pNfAttrib->pageSize; pNfAttrib->numOfBlocks = nandSize / blockSize; pNfAttrib->clockValue = 0x00333333; pNfAttrib->register701C = 0x0885; strcpy(pNfAttrib->modelName, "TC58NVG1S3ETA00"); break; default: bResult = MMP_FALSE; break; } return bResult; } static MMP_BOOL SamsungNandflash( MMP_UINT16 ID1, MMP_UINT16 ID2, NF_ATTRIBUTE* pNfAttrib) { MMP_UINT32 BlockSize = 0; MMP_BOOL bResult = MMP_TRUE; MMP_UINT32 NandId = 0; MMP_UINT32 nandSize = 0; MMP_UINT32 blockSize = 0; NandId=((MMP_UINT32)ID2 << 16) | (MMP_UINT32)ID1; switch( NandId) { case 0x7284D5EC: // This model has 5 bytes ID, that is 0xEC D3 14 25 64 nandSize = (MMP_UINT32)2048 * 1024 * 1024; // Bytes blockSize = 1024 * 1024; // Bytes pNfAttrib->ID1 = ID1; pNfAttrib->ID2 = ID2; pNfAttrib->nandMaker = NAND_MAKER_SAMSUNG; pNfAttrib->checkMethod = NAND_SAMSUNG_METHOD_02; pNfAttrib->pfCheckMethod = _IsBadBlockSamsungMethod02; pNfAttrib->pageSize = 8192; pNfAttrib->pagePerBlock = blockSize / pNfAttrib->pageSize; pNfAttrib->numOfBlocks = nandSize / blockSize; //pNfAttrib->clockValue = 0x00343333; pNfAttrib->clockValue = 0x40777777; pNfAttrib->register701C = 0x00003105; strcpy(pNfAttrib->modelName, "K9GAG08U0E"); break; case 0x2514D3EC: // This model has 5 bytes ID, that is 0xEC D3 14 25 64 nandSize = (MMP_UINT32)1024 * 1024 * 1024; // Bytes blockSize = 256 * 1024; // Bytes pNfAttrib->ID1 = ID1; pNfAttrib->ID2 = ID2; pNfAttrib->nandMaker = NAND_MAKER_SAMSUNG; pNfAttrib->checkMethod = NAND_SAMSUNG_METHOD_02; pNfAttrib->pfCheckMethod = _IsBadBlockSamsungMethod02; pNfAttrib->pageSize = 2048; pNfAttrib->pagePerBlock = blockSize / pNfAttrib->pageSize; pNfAttrib->numOfBlocks = nandSize / blockSize; pNfAttrib->clockValue = 0x00333333; pNfAttrib->register701C = 0x00001005; strcpy(pNfAttrib->modelName, "K9GAG08U0M"); break; case 0xA514D3EC: nandSize = (MMP_UINT32)1024 * 1024 * 1024; // Bytes blockSize = 256 * 1024; // Bytes pNfAttrib->ID1 = ID1; pNfAttrib->ID2 = ID2; pNfAttrib->nandMaker = NAND_MAKER_SAMSUNG; pNfAttrib->checkMethod = NAND_SAMSUNG_METHOD_02; pNfAttrib->pfCheckMethod = _IsBadBlockSamsungMethod02; pNfAttrib->pageSize = 2048; pNfAttrib->pagePerBlock = blockSize / pNfAttrib->pageSize; pNfAttrib->numOfBlocks = nandSize / blockSize; pNfAttrib->clockValue = 0x00777777; pNfAttrib->register701C = 0x00001005; strcpy(pNfAttrib->modelName, "K9G8G08U0A,K9G8G08U0B"); break; case 0xA555D5EC: // This model has 5 bytes ID, that is 0xEC D5 55 A5 68 nandSize = (MMP_UINT32)2048 * 1024 * 1024; // Bytes blockSize = 256 * 1024; // Bytes pNfAttrib->ID1 = ID1; pNfAttrib->ID2 = ID2; pNfAttrib->nandMaker = NAND_MAKER_SAMSUNG; pNfAttrib->checkMethod = NAND_SAMSUNG_METHOD_02; pNfAttrib->pfCheckMethod = _IsBadBlockSamsungMethod02; pNfAttrib->pageSize = 2048; pNfAttrib->pagePerBlock = blockSize / pNfAttrib->pageSize; pNfAttrib->numOfBlocks = nandSize / blockSize; pNfAttrib->clockValue = 0x00333333; pNfAttrib->register701C = 0x0885; strcpy(pNfAttrib->modelName, "K9LAG08U0A,K9HBG08U1A"); break; case 0x2555D5EC: // This model has 5 bytes ID, that is 0xEC D5 55 25 68 nandSize = (MMP_UINT32)2048 * 1024 * 1024; // Bytes blockSize = 256 * 1024; // Bytes pNfAttrib->ID1 = ID1; pNfAttrib->ID2 = ID2; pNfAttrib->nandMaker = NAND_MAKER_SAMSUNG; pNfAttrib->checkMethod = NAND_SAMSUNG_METHOD_02; pNfAttrib->pfCheckMethod = _IsBadBlockSamsungMethod02; pNfAttrib->pageSize = 2048; pNfAttrib->pagePerBlock = blockSize / pNfAttrib->pageSize; pNfAttrib->numOfBlocks = nandSize / blockSize; pNfAttrib->clockValue = 0x00333333; pNfAttrib->register701C = 0x0885; strcpy(pNfAttrib->modelName, "K9LAG08U0M"); break; case 0x9500F1EC: nandSize = 128 * 1024 * 1024; // Bytes blockSize = 128 * 1024; // Bytes pNfAttrib->ID1 = ID1; pNfAttrib->ID2 = ID2; pNfAttrib->nandMaker = NAND_MAKER_SAMSUNG; pNfAttrib->checkMethod = NAND_SAMSUNG_METHOD_01; pNfAttrib->pfCheckMethod = _IsBadBlockSamsungMethod01; pNfAttrib->pageSize = 2048; pNfAttrib->pagePerBlock = blockSize / pNfAttrib->pageSize; pNfAttrib->numOfBlocks = nandSize / blockSize; pNfAttrib->clockValue = 0x00333333; pNfAttrib->register701C = 0x0884; strcpy(pNfAttrib->modelName, "K9F1G08U0A"); break; case 0x9510DCEC: // This model has 5 bytes ID, that is 0xEC DC 10 95 54 nandSize = 512 * 1024 * 1024; // Bytes blockSize = 128 * 1024; // Bytes pNfAttrib->ID1 = ID1; pNfAttrib->ID2 = ID2; pNfAttrib->nandMaker = NAND_MAKER_SAMSUNG; pNfAttrib->checkMethod = NAND_SAMSUNG_METHOD_01; pNfAttrib->pfCheckMethod = _IsBadBlockSamsungMethod01; pNfAttrib->pageSize = 2048; pNfAttrib->pagePerBlock = blockSize / pNfAttrib->pageSize; pNfAttrib->numOfBlocks = nandSize / blockSize; pNfAttrib->clockValue = 0x00333333; pNfAttrib->register701C = 0x0885; strcpy(pNfAttrib->modelName, "K9F4G08U0A"); break; case 0x2514DCEC: // This model has 5 bytes ID, that is 0xEC DC 14 25 54 nandSize = 512 * 1024 * 1024; // Bytes blockSize = 256 * 1024; // Bytes pNfAttrib->ID1 = ID1; pNfAttrib->ID2 = ID2; pNfAttrib->nandMaker = NAND_MAKER_SAMSUNG; pNfAttrib->checkMethod = NAND_SAMSUNG_METHOD_02; pNfAttrib->pfCheckMethod = _IsBadBlockSamsungMethod02; pNfAttrib->pageSize = 2048; pNfAttrib->pagePerBlock = blockSize / pNfAttrib->pageSize; pNfAttrib->numOfBlocks = nandSize / blockSize; pNfAttrib->clockValue = 0x40777777; pNfAttrib->register701C = 0x00001005; strcpy(pNfAttrib->modelName, "K9G4G08U0A"); break; case 0xA514DCEC: // This model has 5 bytes ID, that is 0xEC DC 14 A5 54 nandSize = 512 * 1024 * 1024; // Bytes blockSize = 256 * 1024; // Bytes pNfAttrib->ID1 = ID1; pNfAttrib->ID2 = ID2; pNfAttrib->nandMaker = NAND_MAKER_SAMSUNG; pNfAttrib->checkMethod = NAND_SAMSUNG_METHOD_02; pNfAttrib->pfCheckMethod = _IsBadBlockSamsungMethod02; pNfAttrib->pageSize = 2048; pNfAttrib->pagePerBlock = blockSize / pNfAttrib->pageSize; pNfAttrib->numOfBlocks = nandSize / blockSize; pNfAttrib->clockValue = 0x40777777; pNfAttrib->register701C = 0x00001005; strcpy(pNfAttrib->modelName, "K9G4G08U0B"); break; case 0x9551D3EC: // This model has 5 bytes ID, that is 0xEC D3 51 95 58 nandSize = 1024 * 1024 * 1024; // Bytes blockSize = 128 * 1024; // Bytes pNfAttrib->ID1 = ID1; pNfAttrib->ID2 = ID2; pNfAttrib->nandMaker = NAND_MAKER_SAMSUNG; pNfAttrib->checkMethod = NAND_SAMSUNG_METHOD_01; pNfAttrib->pfCheckMethod = _IsBadBlockSamsungMethod01; pNfAttrib->pageSize = 2048; pNfAttrib->pagePerBlock = blockSize / pNfAttrib->pageSize; pNfAttrib->numOfBlocks = nandSize / blockSize; pNfAttrib->clockValue = 0x00333333; pNfAttrib->register701C = 0x0885; strcpy(pNfAttrib->modelName, "K9K8G08U0A"); break; default: bResult = MMP_FALSE; break; } return bResult; } static MMP_BOOL NumonyxNandflash( MMP_UINT16 ID1, MMP_UINT16 ID2, NF_ATTRIBUTE* pNfAttrib) { MMP_UINT32 BlockSize = 0; MMP_BOOL bResult = MMP_TRUE; MMP_UINT32 NandId = 0; MMP_UINT32 nandSize = 0; MMP_UINT32 blockSize = 0; NandId=((MMP_UINT32)ID2 << 16) | (MMP_UINT32)ID1; switch( NandId) { case 0x9510DA20: nandSize = 256 * 1024 * 1024; // Bytes blockSize = 128 * 1024; // Bytes pNfAttrib->ID1 = ID1; pNfAttrib->ID2 = ID2; pNfAttrib->nandMaker = NAND_MAKER_NUMONYX; pNfAttrib->checkMethod = NAND_NUMONYX_METHOD_01; pNfAttrib->pfCheckMethod = _IsBadBlockNumonyxMethod01; pNfAttrib->pageSize = 2048; pNfAttrib->pagePerBlock = blockSize / pNfAttrib->pageSize; pNfAttrib->numOfBlocks = nandSize / blockSize; pNfAttrib->clockValue = 0x00333333; pNfAttrib->register701C = 0x0885; strcpy(pNfAttrib->modelName, "NAND02GW3B2D"); break; case 0xA514D320: nandSize = 1024 * 1024 * 1024; // Bytes blockSize = 256 * 1024; // Bytes pNfAttrib->ID1 = ID1; pNfAttrib->ID2 = ID2; pNfAttrib->nandMaker = NAND_MAKER_NUMONYX; pNfAttrib->checkMethod = NAND_NUMONYX_METHOD_02; pNfAttrib->pfCheckMethod = _IsBadBlockNumonyxMethod02; pNfAttrib->pageSize = 2048; pNfAttrib->pagePerBlock = blockSize / pNfAttrib->pageSize; pNfAttrib->numOfBlocks = nandSize / blockSize; pNfAttrib->clockValue = 0x00333333; pNfAttrib->register701C = 0x0885; strcpy(pNfAttrib->modelName, "NAND08GW3C2B"); break; default: bResult = MMP_FALSE; break; } return bResult; } static MMP_BOOL PowerFlashNandflash( MMP_UINT16 ID1, MMP_UINT16 ID2, NF_ATTRIBUTE* pNfAttrib) { MMP_UINT32 BlockSize = 0; MMP_BOOL bResult = MMP_TRUE; MMP_UINT32 NandId = 0; MMP_UINT32 nandSize = 0; MMP_UINT32 blockSize = 0; NandId=((MMP_UINT32)ID2 << 16) | (MMP_UINT32)ID1; switch( NandId) { case 0x2504DC92: // This model has 5 bytes ID, that is 0x92 DC 04 25 00 nandSize = 512 * 1024 * 1024; // Bytes blockSize = 256 * 1024; // Bytes pNfAttrib->ID1 = ID1; pNfAttrib->ID2 = ID2; pNfAttrib->nandMaker = NAND_MAKER_POWERFLASH; pNfAttrib->checkMethod = NAND_POWERFLASH_METHOD_01; pNfAttrib->pfCheckMethod = _IsBadBlockPowerFlashMethod01; pNfAttrib->pageSize = 2048; pNfAttrib->pagePerBlock = blockSize / pNfAttrib->pageSize; pNfAttrib->numOfBlocks = nandSize / blockSize; pNfAttrib->clockValue = 0x00333333; pNfAttrib->register701C = 0x0885; strcpy(pNfAttrib->modelName, "A1U4GA30GT"); break; default: bResult = MMP_FALSE; break; } return bResult; } MMP_BOOL NfChipSelect( MMP_UINT32 chipIndex) { #ifdef __FREERTOS__ MMP_UINT16 regValue = 0; MMP_UINT32 chipSelect = 0; MMP_BOOL result = MMP_TRUE; #if 0 switch(chipIndex) { case 0: regValue = 0x00; chipSelect = 0x00000008; break; case 1: regValue = 0x08; chipSelect = 0x00010008; break; case 2: regValue = 0x0C; chipSelect = 0x00030008; break; case 3: regValue = 0x04; chipSelect = 0x00030008; break; default: result = MMP_FALSE; break; } #else switch(chipIndex) { case 0: regValue = 0x00; chipSelect = 0x00000008; break; case 1: regValue = 0x04; chipSelect = 0x00010008; break; default: result = MMP_FALSE; break; } #endif //HOST_WriteRegisterMask(0x16B0, regValue, 0x0C); //AHB_WriteRegisterMask(0x68000048, chipSelect, 0x00030008); #if 0 if ( chipIndex == 1 ) { while(1){} } #endif return result; #elif defined(WIN32) MMP_UINT16 regValue = 0; MMP_UINT16 chipSelect = 0; MMP_BOOL result = MMP_TRUE; if ( chipIndex == 1 ) printf("NfChipSelect: Use 2nd die\n"); else if ( chipIndex > 1 ) printf("NfChipSelect: Use unknown die, FATAL ERROR!\n"); switch(chipIndex) { case 0: regValue = 0x00; chipSelect = 0x0000; break; case 1: regValue = 0x04; chipSelect = 0x0001; break; default: result = MMP_FALSE; break; } // Set controller chip select //HOST_WriteRegisterMask(0x16B0, regValue, 0x0C); // Set GPIO8 //HOST_WriteRegisterMask(0x784A, chipSelect, 0x0003); return result; #endif } void ResetChipSelect() { //AHB_WriteRegisterMask(0x68000048, 0x00000000, 0x00030008); return; AHB_WriteRegister(0x68000048, g_OriGpioValue); } MMP_BOOL IsErasedBlock( MMP_UINT8* pData, MMP_UINT8* pSpare) { MMP_UINT32 i; MMP_UINT32 reg32; MMP_BOOL bErased = MMP_TRUE; #ifdef ENABLE_HW_2K_PAGE MMP_UINT8 SprSbr[SPARE_SIZE] = {0x43, 0x07, 0x02, 0x98, 0xc0, 0xd7, 0x8f, 0x22, 0xe6, 0x84, 0xf9, 0x34, 0xf4, 0x94, 0x56, 0xc0}; #else MMP_UINT8 SprSbr[SPARE_SIZE] = {0x32, 0xaf, 0x49, 0x07, 0xd0, 0xc2, 0xe7, 0x40, 0xbb, 0xe4, 0x4c, 0x26, 0x7f, 0x61, 0x63, 0xc3, 0xda, 0x79, 0xc2, 0xae, 0x40, 0x5d, 0xdd, 0x1f}; //BCH 24-bit #endif #if 0 //#ifdef __FREERTOS__ MMP_UINT8* pAlignSpareBuf = (MMP_UINT8*)(((MMP_UINT32)pSpare + 3) & ~3); if ( pAlignSpareBuf == pSpare ) { for ( i=0; i<SPARE_SIZE; i+=4 ) { if ( *((MMP_UINT32*)(pSpare + i)) != 0xFFFFFFFF ) { bErased = MMP_FALSE; break; } } } else #endif #if 0 { printf("---------- SPARE DATA ----------\n"); for ( i=0; i<SPARE_SIZE; i+=8 ) { printf("0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X\n", pSpare[i], pSpare[i+1], pSpare[i+2], pSpare[i+3], pSpare[i+4], pSpare[i+5], pSpare[i+6], pSpare[i+7]); } } #endif AHB_ReadRegister(NF_REG_WR_SCRAMB_INIT, &reg32); AHB_ReadRegister(NF_REG_RD_SCRAMB_INIT, &reg32); AHB_ReadRegister(NF_REG_GENERAL, &reg32); if(reg32&0x0080000) { for ( i=0; i<SPARE_SIZE; i++ ) { if ( pSpare[i] != SprSbr[i] ) { bErased = MMP_FALSE; break; } } } else { for ( i=0; i<SPARE_SIZE; i++ ) { if ( pSpare[i] != 0xFF ) { bErased = MMP_FALSE; break; } } } return bErased; } void EnableNfControl() { //MMP_UINT32 BlockNum;//for FPGA verify, set this variable as 0 MMP_UINT32 BlockNum=0;//for FPGA verify MMP_UINT32 SecLength; MMP_INT Result; //Result = mmpxDGetCapacity(&BlockNum, &SecLength); if(BlockNum) { //if XD card exist, then pull up XDCEN pin //HOST_WriteRegisterMask(0x784E, 0x0080,0x00C0);//pull up XDCE pin } //HOST_WriteRegisterMask(0x784C, 0x0008,0x000C);//pull up CF_RST pin //AHB_WriteRegisterMask((GPIO_BASE+0x4C), PULL_UP_CF_IOWR, CF_IOWR_PULL_UP_DOWN_MASK); //AHB_WriteRegisterMask((GPIO_BASE+0x4C), PULL_UP_NDCS0, NDCS0_PULL_UP_DOWN_MASK); return; } // Check byte 0 in data & 1st bytes in spare of 1st & 2nd page // Read either column 0 or 2048 of the 1st page or the 2nd page of each block. static MMP_UINT8 _IsBadBlockToshibaMethod01( MMP_UINT32 pba) { const MMP_UINT32 CI2048 = 2000; // CI2048 means "column index 2048" MMP_UINT8 result = LL_ERROR; MMP_UINT8 blockStatus = LL_ERROR; MMP_UINT8 dataBuffer[DATA_SIZE]; //printf(" --> _IsBadBlockToshibaMethod01: \n"); // ---------------------------------------- // 1. Read 1st page result = LB8K_HWECC_Read(pba, 0, dataBuffer); if ( result == LL_ERASED && dataBuffer[0] == 0xFF && dataBuffer[CI2048] == 0xFF ) { // ---------------------------------------- // 2. Read 2nd page result = LB8K_HWECC_Read(pba, 1, dataBuffer); if ( result == LL_ERASED && dataBuffer[0] == 0xFF && dataBuffer[CI2048] == 0xFF ) { blockStatus = LL_OK; } } return blockStatus; } // Check byte 0 in data & 1st bytes in spare of last page // Read either column 0 or 2048 of the last page of each block. static MMP_UINT8 _IsBadBlockToshibaMethod02( MMP_UINT32 pba) { const MMP_UINT32 CI2048 = 2000; // CI2048 means "column index 2048" MMP_UINT8 result = LL_ERROR; MMP_UINT8 blockStatus = LL_ERROR; MMP_UINT32 lastPage = g_NfAttrib.pagePerBlock - 1; MMP_UINT8 dataBuffer[DATA_SIZE]; //printf(" --> _IsBadBlockToshibaMethod02: \n"); // ---------------------------------------- // 1. Read 1st page result = LB8K_HWECC_Read(pba, lastPage, dataBuffer); if ( result == LL_ERASED && dataBuffer[0] == 0xFF && dataBuffer[CI2048] == 0xFF ) { // ---------------------------------------- // 2. Read 2nd page result = LB8K_HWECC_Read(pba, 1, dataBuffer); if ( result == LL_ERASED && dataBuffer[0] == 0xFF && dataBuffer[CI2048] == 0xFF ) { blockStatus = LL_OK; } } return blockStatus; } // Check byte 0 in data & 1st bytes in spare of 1st page & last page // Read FFh Check Column 0 or 2048 of the First page // Read FFh Check Column 0 or 2048 of the last page static MMP_UINT8 _IsBadBlockToshibaMethod03( MMP_UINT32 pba) { const MMP_UINT32 CI2048 = 2000; // CI2048 means "column index 2048" MMP_UINT8 result = LL_ERROR; MMP_UINT8 blockStatus = LL_ERROR; MMP_UINT32 lastPage = g_NfAttrib.pagePerBlock - 1; MMP_UINT8 dataBuffer[DATA_SIZE]; //printf(" --> _IsBadBlockToshibaMethod03: \n"); // ---------------------------------------- // 1. Read 1st page result = LB8K_HWECC_Read(pba, 0, dataBuffer); if ( result == LL_ERASED && dataBuffer[0] == 0xFF && dataBuffer[CI2048] == 0xFF ) { // ---------------------------------------- // 2. Read last page result = LB8K_HWECC_Read(pba, lastPage, dataBuffer); if ( result == LL_ERASED && dataBuffer[0] == 0xFF && dataBuffer[CI2048] == 0xFF ) { blockStatus = LL_OK; } } return blockStatus; } // Check 1st bytes in spare of 1st & 2nd page // The invalid block(s) status is defined by the 1st byte in the spare area. // Samsung makes sure that either the 1st or 2nd page of every invalid block has non-FFh data at the column address of 2048. static MMP_UINT8 _IsBadBlockSamsungMethod01( MMP_UINT32 pba) { const MMP_UINT32 CI2048 = 2000; // CI2048 means "column index 2048" MMP_UINT8 result = LL_ERROR; MMP_UINT8 blockStatus = LL_ERROR; MMP_UINT32 lastPage = g_NfAttrib.pagePerBlock - 1; MMP_UINT8 dataBuffer[DATA_SIZE]; MMP_UINT32 i; //printf(" --> _IsBadBlockSamsungMethod01: \n"); // ---------------------------------------- // 1. Read last page // --- Check 1st bytes in spare of 1st & 2nd page result = LB8K_HWECC_Read(pba, 0, dataBuffer); if ( result == LL_ERASED && dataBuffer[CI2048] == 0xFF ) { // ---------------------------------------- // 2. Read 2nd page //printf("R2\r\n"); result = LB8K_HWECC_Read(pba, 1, dataBuffer); if ( result == LL_ERASED && dataBuffer[CI2048] == 0xFF ) { blockStatus = LL_OK; } } return blockStatus; } // Check 1st bytes in spare of last page // The initial invalid block(s) status is defined by the 1st byte in the spare area. // Samsung makes sure that the last page of every initial invalid block has non-FFh data at the column address of 2,048. static MMP_UINT8 _IsBadBlockSamsungMethod02( MMP_UINT32 pba) { //const MMP_UINT32 CI2048 = 2000; // CI2048 means "column index 2048" const MMP_UINT32 CI2048 = 2027; // CI2048 means "column index 2027 in BCH 12-bit mode" MMP_UINT8 CheckValue=0xFF; MMP_UINT8 result = LL_ERROR; MMP_UINT8 blockStatus = LL_ERROR; MMP_UINT32 lastPage = g_NfAttrib.pagePerBlock - 1; MMP_UINT8 dataBuffer[DATA_SIZE+SPARE_SIZE]; //printf(" --> _IsBadBlockSamsungMethod02: \n"); // ---------------------------------------- // 1. Read last page // --- Check 1st bytes in spare of last page result = LB8K_HWECC_Read(pba, lastPage, dataBuffer); if(IsEnHwScrambler) { CheckValue=0x1F; } if ( result == LL_ERASED && dataBuffer[CI2048] == CheckValue ) { blockStatus = LL_OK; } return blockStatus; } // Check 1st bytes in spare of 1st & 2nd page // Any block where the 1st Byte in the spare area of the 1st or 2nd page(if the 1st page is Bad) does not contain FFh is a Bad Block. static MMP_UINT8 _IsBadBlockHynixMethod01( MMP_UINT32 pba) { const MMP_UINT32 CI2048 = 2000; // CI2048 means "column index 2048" MMP_UINT8 result = LL_ERROR; MMP_UINT8 blockStatus = LL_ERROR; MMP_UINT8 dataBuffer[DATA_SIZE]; //printf(" --> _IsBadBlockHynixMethod01: \n"); // ---------------------------------------- // 1. Read 1st page result = LB8K_HWECC_Read(pba, 0, dataBuffer); if ( result == LL_ERASED && dataBuffer[CI2048] == 0xFF ) { // ---------------------------------------- // 2. Read 2nd page result = LB8K_HWECC_Read(pba, 1, dataBuffer); if ( result == LL_ERASED && dataBuffer[CI2048] == 0xFF ) { blockStatus = LL_OK; } } return blockStatus; } // Check 1st bytes in spare of last page & (last-2) page // Any block where the 1st Byte in the spare area of the Last or (Last-2)th page (if the last page is Bad) does not contain FFh is a Bad Block. static MMP_UINT8 _IsBadBlockHynixMethod02( MMP_UINT32 pba) { const MMP_UINT32 CI2048 = 2000; // CI2048 means "column index 2048" MMP_UINT8 result = LL_ERROR; MMP_UINT8 blockStatus = LL_ERROR; MMP_UINT32 lastPage = g_NfAttrib.pagePerBlock - 1; MMP_UINT32 last2Page = lastPage - 2; MMP_UINT8 dataBuffer[DATA_SIZE]; //printf(" --> _IsBadBlockHynixMethod02: \n"); // ---------------------------------------- // 1. Read 1st page result = LB8K_HWECC_Read(pba, lastPage, dataBuffer); if ( (result == LL_ERASED) && (dataBuffer[CI2048] == 0xFF) ) { // ---------------------------------------- // 2. Read 2nd page result = LB8K_HWECC_Read(pba, last2Page, dataBuffer); if ( (result == LL_ERASED) && (dataBuffer[CI2048] == 0xFF) ) { blockStatus = LL_OK; } } return blockStatus; } // Check 1st & 6th byte in spare of 1st page // Any block, where the 1st and 6th bytes or the 1st word in the spare area of the 1st page, does not contain FFh, is a bad block. static MMP_UINT8 _IsBadBlockNumonyxMethod01( MMP_UINT32 pba) { const MMP_UINT32 CI2048 = 2000; // CI2048 means "column index 2048" MMP_UINT8 result = LL_ERROR; MMP_UINT8 blockStatus = LL_ERROR; MMP_UINT8 dataBuffer[DATA_SIZE]; //printf(" --> _IsBadBlockNumonyxMethod01: \n"); // ---------------------------------------- // 1. Read 1st page result = LB8K_HWECC_Read(pba, 0, dataBuffer); if ( result == LL_ERASED && dataBuffer[CI2048] == 0xFF && dataBuffer[CI2048 + 5] == 0xFF ) { blockStatus = LL_OK; } return blockStatus; } // Check 1st byte in spare of last page // Any block, where the 1st and 6th bytes or the 1st word in the spare area of the 1st page, does not contain FFh, is a bad block. static MMP_UINT8 _IsBadBlockNumonyxMethod02( MMP_UINT32 pba) { const MMP_UINT32 CI2048 = 2000; // CI2048 means "column index 2048" MMP_UINT8 result = LL_ERROR; MMP_UINT8 blockStatus = LL_ERROR; MMP_UINT32 lastPage = g_NfAttrib.pagePerBlock - 1; MMP_UINT8 dataBuffer[DATA_SIZE]; //printf(" --> _IsBadBlockNumonyxMethod02: \n"); // ---------------------------------------- // 1. Read 1st page result = LB8K_HWECC_Read(pba, lastPage, dataBuffer); if ( result == LL_ERASED && dataBuffer[CI2048] == 0xFF) { blockStatus = LL_OK; } return blockStatus; } // Bad blocks can be read by accessing the first byte and the 2048th byte of the first page and the last page. static MMP_UINT8 _IsBadBlockPowerFlashMethod01( MMP_UINT32 pba) { const MMP_UINT32 CI2048 = 2000; // CI2048 means "column index 2048" MMP_UINT8 result = LL_ERROR; MMP_UINT8 blockStatus = LL_ERROR; MMP_UINT32 lastPage = g_NfAttrib.pagePerBlock - 1; MMP_UINT8 dataBuffer[DATA_SIZE]; //printf(" --> _IsBadBlockPowerFlashMethod01: \n"); // ---------------------------------------- // 1. Read 1st page result = LB8K_HWECC_Read(pba, 0, dataBuffer); if ( result == LL_ERASED && dataBuffer[0] == 0xFF && dataBuffer[CI2048] == 0xFF ) { // ---------------------------------------- // 2. Read last page result = LB8K_HWECC_Read(pba, lastPage, dataBuffer); if ( result == LL_ERASED && dataBuffer[0] == 0xFF && dataBuffer[CI2048] == 0xFF ) { blockStatus = LL_OK; } } return blockStatus; } static MMP_UINT8 NAND_CMD_2ND_READ70_STATUS( MMP_UINT32* NfStatus) { //MMP_UINT16 nfStatus; MMP_UINT8 result = LL_OK; MMP_UINT32 timeOut = READ_STATUS_TIME_OUT_COUNT; MMP_INT EventRst; *NfStatus = 0; AHB_WriteRegister(NF_REG_CMD2, READSTATUS_CMD_2ND); AHB_WriteRegister(NF_REG_CMD_FIRE, NF_CMD_FIRE); #if defined(NAND_IRQ_ENABLE) //need wait event if(NandIsrEvent) { EventRst = SYS_WaitEvent(NandIsrEvent, 20); //printf("WaitNfReady.event.got!!rst=%x\n",EventRst); if(result) { printf("[Nf ERR]:INTR time out\n"); result = LL_ERROR; goto end; } } #else MMP_Sleep(1); #endif do { AHB_ReadRegister(NF_REG_STATUS, NfStatus); if ( timeOut-- == 0 ) { printf("\tLB8K_HWECC_WaitCmdReady wait idle time out[2]!!!\n"); result = LL_ERROR; goto end; } }while( (*NfStatus&0xc000) != NFIDLE ); *NfStatus = *NfStatus & 0xFF; end: return result; } static MMP_UINT8 NAND_CMD_1ST_READID90( MMP_UINT32* CmdID0, MMP_UINT32* CmdID1, MMP_UINT32 IdCycles) { MMP_UINT8 result = LL_OK; //MMP_UINT32 Reg32Tmp; #ifdef WIN32 HOST_WriteRegister(NF_REG_CMD1, READID90_CMD_1ST); HOST_WriteRegister(NF_REG_IDCYCLE, IdCycles); HOST_WriteRegister(NF_REG_CMD_FIRE, NF_CMD_FIRE); #else AHB_WriteRegister(NF_REG_CMD1, READID90_CMD_1ST); AHB_WriteRegister(NF_REG_IDCYCLE, IdCycles); AHB_WriteRegister(NF_REG_CMD_FIRE, NF_CMD_FIRE); #endif if ( LB8K_HWECC_WaitCmdReady(NF_READ_ID)==LL_OK ) { AHB_ReadRegister(NF_REG_NFMC_ID1, CmdID0); AHB_ReadRegister(NF_REG_NFMC_ID2, CmdID1); } else { result = LL_ERROR; } NAND_DbgPrintf("GetNandId: ID32_1 = 0x%08X.\n\r", *CmdID0); NAND_DbgPrintf("GetNandId: ID32_2 = 0x%08X.\n\r", *CmdID1); return result; } MMP_UINT8 GetErrorPageNum(MMP_UINT32 ErrMap) { MMP_UINT8 i,ErrorPageNum=0; for(i=0;i<g_TotalNumOfMapBit;i++) { if( ((ErrMap>>i)&0x0001)==0x0000 ) ErrorPageNum++; } return ErrorPageNum; } MMP_UINT32 GetCorrectNumInThisSegment(MMP_UINT32 PageLoop) { MMP_UINT32 ErrNum; MMP_UINT16 k; MMP_UINT32 TotalOffset=0; MMP_UINT16 *p16BchPt; //MMP_UINT8 *BCHpt=g_pNFeccBuf; #ifdef WIN32 MMP_UINT16 *BCHpt=(MMP_UINT16 *)g_pW32NFBchBuf; #else MMP_UINT16 *BCHpt=(MMP_UINT16 *)g_pNFeccBuf; MMP_UINT8 *BCH8pt; #endif //printf("GCNTS:PageLoop=%x.\r\n",PageLoop); //printf("GCNTS:g_pNFeccBuf=%x.\r\n",BCHpt); for(k=0;k<(PageLoop+1);k++) { #ifdef WIN32 ErrNum=(((MMP_UINT32)BCHpt[1])<<16)+((MMP_UINT32)BCHpt[0]); BCHpt = &BCHpt[((ErrNum+1)&0xFFFFFFFE)+2]; #else BCH8pt = (MMP_UINT8 *)BCHpt; ErrNum=( (((MMP_UINT32)BCH8pt[3])<<24)+(((MMP_UINT32)BCH8pt[2])<<16)+(((MMP_UINT32)BCH8pt[1])<<8)+(MMP_UINT32)BCH8pt[0] ); BCHpt = &BCHpt[((ErrNum+1)&0xFFFFFFFE)+2]; #endif } return ErrNum; } MMP_UINT16 GetErrorAddr(MMP_UINT8 PageLoop, MMP_UINT8 BitLoop) { MMP_UINT32 ErrNum; MMP_UINT16 ErrAddr,k; //MMP_UINT8 *BCHpt=g_pNFeccBuf; #ifdef WIN32 MMP_UINT16 *BCHpt=(MMP_UINT16 *)g_pW32NFBchBuf; #else MMP_UINT16 *BCHpt=(MMP_UINT16 *)g_pNFeccBuf; MMP_UINT8 *BCH8pt; #endif //printf("GEA:PageLoop=%x,BitLoop=%x.\r\n",PageLoop,BitLoop); //BCHpt=(MMP_UINT8 *)((MMP_UINT32)g_pNFeccBuf+(MMP_UINT32)LocAddr); for(k=0;k<(PageLoop+1);k++) { #ifdef WIN32 ErrNum=(((MMP_UINT32)BCHpt[1])<<16)+((MMP_UINT32)BCHpt[0]); #else BCH8pt = (MMP_UINT8 *)BCHpt; ErrNum=( (((MMP_UINT32)BCH8pt[3])<<24)+(((MMP_UINT32)BCH8pt[2])<<16)+(((MMP_UINT32)BCH8pt[1])<<8)+(MMP_UINT32)BCH8pt[0] ); #endif if(k==PageLoop) { BCHpt = &BCHpt[2]; } else { if(ErrNum&0x01) { BCHpt = &BCHpt[ErrNum+3]; } else { BCHpt = &BCHpt[ErrNum+2]; } } } #ifdef WIN32 ErrAddr = BCHpt[BitLoop]; #else BCH8pt = (MMP_UINT8 *)BCHpt; ErrAddr = (((MMP_UINT32)BCH8pt[(BitLoop*2)+1])<<8) + (MMP_UINT32)BCH8pt[(BitLoop*2)]; #endif ErrAddr = ErrAddr&0x03FF; return ErrAddr; } MMP_UINT8 GetErrorBit(MMP_UINT8 PageLoop,MMP_UINT8 BitLoop) { MMP_UINT32 ErrNum; MMP_UINT16 Errbit; MMP_UINT16 k; //MMP_UINT8 *BCHpt=g_pNFeccBuf; #ifdef WIN32 MMP_UINT16 *BCHpt=(MMP_UINT16 *)g_pW32NFBchBuf; #else MMP_UINT16 *BCHpt=(MMP_UINT16 *)g_pNFeccBuf; MMP_UINT8 *BCH8pt; #endif for(k=0;k<(PageLoop+1);k++) { #ifdef WIN32 ErrNum=(((MMP_UINT32)BCHpt[1])<<16)+((MMP_UINT32)BCHpt[0]); #else BCH8pt = (MMP_UINT8 *)BCHpt; ErrNum=( (((MMP_UINT32)BCH8pt[3])<<24)+(((MMP_UINT32)BCH8pt[2])<<16)+(((MMP_UINT32)BCH8pt[1])<<8)+(MMP_UINT32)BCH8pt[0] ); #endif if(k==PageLoop) { BCHpt = &BCHpt[2]; } else { if(ErrNum&0x01) { BCHpt = &BCHpt[ErrNum+3]; } else { BCHpt = &BCHpt[ErrNum+2]; } } } #ifdef WIN32 Errbit = BCHpt[BitLoop]; #else BCH8pt = (MMP_UINT8 *)BCHpt; Errbit = (((MMP_UINT32)BCH8pt[(BitLoop*2)+1])<<8) + (MMP_UINT32)BCH8pt[BitLoop*2]; #endif Errbit = (Errbit>>12); return Errbit; } MMP_UINT8 GetErrorPage(MMP_UINT8 PageLoop) { MMP_UINT32 Reg704C; MMP_UINT8 i,ErrorPageNum=0; AHB_ReadRegister(NF_REG_BCH_ECC_MAP, &Reg704C); //printf("Reg704C=%x\r\n",Reg704C); for(i=0;i<g_TotalNumOfMapBit;i++) //for 2kB/page nand { if( ((Reg704C>>i)&0x00000001)==0x0000 ) { ErrorPageNum++; //printf("PL=%x,EPN=%x.\r\n",PageLoop,ErrorPageNum); if(ErrorPageNum==(PageLoop+1)) { //printf("i=%x,PL=%x,EPN=%x.\r\n",i,PageLoop,ErrorPageNum); if(g_BchMapMask==g_pNFeccCurrRdMask) { return i; } else { MMP_UINT32 CurrRdLen; CurrRdLen=GetErrorPageNum((~g_pNFeccCurrRdMask)&g_BchMapMask); //printf("CurrRdLen=%x,[%x,%x,%x]\n", CurrRdLen, g_pNFeccCurrRdMask, g_BchMapMask, (~g_pNFeccCurrRdMask)&g_BchMapMask); return i%CurrRdLen; } } } } //printf("2.i=%x,PL=%x,EPN=%x.\r\n",i,PageLoop,ErrorPageNum); return 0xFF; } void CorrectBitIn8kBDataBuffer(MMP_UINT8 *data, MMP_UINT8 *spare, MMP_UINT8 ErrorPage,MMP_UINT16 ErrorAddr,MMP_UINT8 ErrorBit) { MMP_UINT8 *DataBuffer=data; MMP_UINT8 ErrByte,i; MMP_UINT16 ErrorByteAddress,ErrBitMask; MMP_UINT32 Last1kB_Index; MMP_UINT32 IsErrorAtSpareArea=0; //check if Read the last 1kB of all page Last1kB_Index=(MMP_UINT32)0x01<<(g_TotalNumOfMapBit-1); if(g_pNFeccCurrRdMask==0x80) { //printf("0.Last1kB[%x,%x,%x]\n",Last1kB_Index,g_pNFeccCurrRdMask,(Last1kB_Index&g_pNFeccCurrRdMask)); } if( (Last1kB_Index&g_pNFeccCurrRdMask)==Last1kB_Index ) { Last1kB_Index=GetErrorPageNum((~g_pNFeccCurrRdMask)&g_BchMapMask);//get the total read counts(unit:1kB) //printf("1.Last1kB_Index=%x\n",Last1kB_Index); } else { Last1kB_Index=g_TotalNumOfMapBit; //printf("2.Last1kB_Index=%x\n",Last1kB_Index); } //if(ErrorPage>=(g_TotalNumOfMapBit-1)) if(ErrorPage>=(Last1kB_Index-1)) { if(ErrorAddr>=((ECC_PAGE_SIZE/2)+(SPARE_SIZE/2))) { printf("Error Address >= 0x418, means Error bit is in ECC code!!\r\n"); return; } if( ErrorAddr>=(ECC_PAGE_SIZE/2) ) { printf("Error Address >= 0x400, means Error bit is in spare area!!\r\n"); IsErrorAtSpareArea=1; } } else { if(ErrorAddr>=(ECC_PAGE_SIZE/2)) { printf("Error Address >= 0x400, means Error bit is in ECC code!!\r\n"); return; } } if(IsErrorAtSpareArea) { DataBuffer=spare; ErrorByteAddress=(ErrorAddr-0x200)*2; printf("3.DataBuffer=%x,ErrAdr=[%x,%x]\n",DataBuffer,ErrorByteAddress,ErrorAddr); } else { ErrorByteAddress=ErrorPage*1024+ErrorAddr*2; printf("4.DataBuffer=%x,ErrAdr=[%x,%x]\n",DataBuffer,ErrorByteAddress,ErrorAddr); } if(ErrorBit>0x07) { ErrorByteAddress++; ErrorBit=ErrorBit-8; } ErrByte=DataBuffer[ErrorByteAddress]; ErrBitMask=0x01<<ErrorBit; if(ErrByte&ErrBitMask) { ErrByte=ErrByte-ErrBitMask; } else { ErrByte=ErrByte+ErrBitMask; } DataBuffer[ErrorByteAddress]=ErrByte; } void CorrectAllErrorBitsIn8kBDataBuffer(MMP_UINT8 *data, MMP_UINT8 *spare) { MMP_UINT8 TotalErrorPageNum; MMP_UINT32 PageLoop,Reg704C; MMP_UINT8 i,ErrorPageNum=0; MMP_UINT32 j; AHB_ReadRegister(NF_REG_BCH_ECC_MAP, &Reg704C); //it can correct //1.get how many errors TotalErrorPageNum=GetErrorPageNum(Reg704C&g_BchMapMask); //it have to do for 2kB/page NAND printf("TotalErrorPageNum=%x.\r\n",TotalErrorPageNum); #ifdef WIN32 HOST_ReadBlockMemory((MMP_UINT32)g_pW32NFBchBuf, (MMP_UINT32)g_pNFeccBuf, (8+(BCH_MODE*2))*TotalErrorPageNum); #else ithInvalidateDCacheRange(g_pNFeccBuf, (8+(BCH_MODE*2))*TotalErrorPageNum); #endif /* printf("g_pNFeccBuf=["); for(i=0;i<32;i++) { printf("%02x,",g_pNFeccBuf[i] ); if( (i&0x0F)==0x0F) printf("\r\n "); } printf("]\n"); */ /* printf("g_dataBuf=\n"); for(j=0;j<1024;j++) { printf("%02x,",data[j] ); if( (j&0x0F)==0x0F) printf("\r\n"); } printf("\n"); */ for(PageLoop=0;PageLoop<TotalErrorPageNum;PageLoop++) { MMP_UINT32 ErrorNum,BitLoop,ErrorBit,ErrorPage; MMP_UINT16 ErrorAddr; ErrorNum=GetCorrectNumInThisSegment(PageLoop); printf("ErrorNum=%x,loop=%x.\r\n",ErrorNum,PageLoop); for(BitLoop=0;BitLoop<ErrorNum;BitLoop++) { ErrorAddr=GetErrorAddr(PageLoop,BitLoop); ErrorBit=GetErrorBit(PageLoop,BitLoop); ErrorPage=GetErrorPage(PageLoop); printf("PgLp=%x,BtLp=%x,[",PageLoop,BitLoop); printf("ErrPg=%x,ErrAddr=%x,ErrBit=%x.]\r\n", ErrorPage, ErrorAddr, ErrorBit); CorrectBitIn8kBDataBuffer(data, spare, ErrorPage, ErrorAddr, ErrorBit); } } } static MMP_UINT8 compare2Buf(MMP_UINT8* pBuf1, MMP_UINT8* pBuf2, MMP_UINT32 CprSize) { MMP_UINT32 i; MMP_UINT8 CompareResult=LL_OK; for(i=0;i<CprSize;i++) { if(pBuf1[i]!=pBuf2[i]) { printf("Compare error, i=%x,pf1=%x,pf2=%x,Ori=[%x],Dis[%x]\n",i,pBuf1,pBuf2,pBuf1[i],pBuf2[i]); CompareResult = LL_ERROR; //break; } } return CompareResult; } MMP_UINT8 IsAllData0xFF(MMP_UINT8 *pDataPtr, MMP_UINT32 Cprlen) { MMP_UINT32 i; MMP_UINT32 reg32; MMP_BOOL bErased = MMP_TRUE; /* MMP_UINT8 Scrambler[16] = {0x43, 0x07, 0x02, 0x98, 0xc0, 0xd7, 0x8f, 0x22, 0xe6, 0x84, 0xf9, 0x34, 0xf4, 0x94, 0x56, 0xc0}; */ if(IsEnHwScrambler) { for ( i=0; i<Cprlen; i++ ) { if ( pDataPtr[i] != g_ScramblerTable[i] ) { bErased = MMP_FALSE; break; } } } else { for ( i=0; i<Cprlen; i++ ) { if ( pDataPtr[i] != 0xFF ) { bErased = MMP_FALSE; break; } } if( bErased==MMP_TRUE ) { MMP_UINT32 Reg32; AHB_ReadRegister(NF_REG_BCH_ECC_MAP, &Reg32); if( (Reg32 & g_BchMapMask) == g_BchMapMask ) { bErased = MMP_FALSE; } } } return bErased; } #endif // End #ifdef NF_HW_ECC #endif // End #ifdef LARGEBLOCK_8KB
32.234533
144
0.605821
[ "object", "model" ]
6958f605e1a9cf8889c6edef5c6eb5f1616cbb63
8,620
h
C
Horologe/Source/Chrono/HLBasicGJChronology.h
dev2dev/Horologe
50fb3e5400d76301e4a2c7f15cbe50b4846e40c5
[ "Apache-2.0" ]
1
2017-07-30T00:56:10.000Z
2017-07-30T00:56:10.000Z
Horologe/Source/Chrono/HLBasicGJChronology.h
dev2dev/Horologe
50fb3e5400d76301e4a2c7f15cbe50b4846e40c5
[ "Apache-2.0" ]
null
null
null
Horologe/Source/Chrono/HLBasicGJChronology.h
dev2dev/Horologe
50fb3e5400d76301e4a2c7f15cbe50b4846e40c5
[ "Apache-2.0" ]
null
null
null
/* * BasicGJChronology.h * * Horologe * Copyright (c) 2011 Pilgrimage Software * * A Cocoa version of the Joda-Time Java date/time library. * * 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. */ #import <Foundation/Foundation.h> @interface BasicGJChronology { @private } /* * Copyright 2001-2005 Stephen Colebourne * * 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. */ package org.joda.time.chrono; import org.joda.time.Chronology; import org.joda.time.DateTimeConstants; /** * Abstract Chronology for implementing chronologies based on Gregorian/Julian formulae. * Most of the utility methods required by subclasses are package-private, * reflecting the intention that they be defined in the same package. * <p> * BasicGJChronology is thread-safe and immutable, and all subclasses must * be as well. * * @author Stephen Colebourne * @author Brian S O'Neill * @author Guy Allard * @since 1.2, refactored from CommonGJChronology */ abstract class BasicGJChronology extends BasicChronology { /** Serialization lock */ private static final long serialVersionUID = 538276888268L; // These arrays are NOT public. We trust ourselves not to alter the array. // They use zero-based array indexes so the that valid range of months is // automatically checked. private static final int[] MIN_DAYS_PER_MONTH_ARRAY = { 31,28,31,30,31,30,31,31,30,31,30,31 }; private static final int[] MAX_DAYS_PER_MONTH_ARRAY = { 31,29,31,30,31,30,31,31,30,31,30,31 }; private static final long[] MIN_TOTAL_MILLIS_BY_MONTH_ARRAY; private static final long[] MAX_TOTAL_MILLIS_BY_MONTH_ARRAY; private static final long FEB_29 = (31L + 29 - 1) * DateTimeConstants.MILLIS_PER_DAY; static { MIN_TOTAL_MILLIS_BY_MONTH_ARRAY = new long[12]; MAX_TOTAL_MILLIS_BY_MONTH_ARRAY = new long[12]; - (NSInteger)minSum = 0; - (NSInteger)maxSum = 0; for(NSInteger i = 0; i < 11; i++) { - (NSInteger)millis = MIN_DAYS_PER_MONTH_ARRAY[i] * (long)DateTimeConstants.MILLIS_PER_DAY; minSum += millis; MIN_TOTAL_MILLIS_BY_MONTH_ARRAY[i + 1] = minSum; millis = MAX_DAYS_PER_MONTH_ARRAY[i] * (long)DateTimeConstants.MILLIS_PER_DAY; maxSum += millis; MAX_TOTAL_MILLIS_BY_MONTH_ARRAY[i + 1] = maxSum; } } /** * Constructor. */ BasicGJChronology:(HLChronology*)base, Object param :(NSInteger)minDaysInFirstWeek) { super(base, param, minDaysInFirstWeek); } //----------------------------------------------------------------------- int getMonthOfYear:(NSInteger)millis :(NSInteger)year) { // Perform a binary search to get the month. To make it go even faster, // compare using ints instead of longs. The number of milliseconds per // year exceeds the limit of a 32-bit int's capacity, so divide by // 1024. No precision is lost (except time of day) since the number of // milliseconds per day contains 1024 as a factor. After the division, // the instant isn't measured in milliseconds, but in units of // (128/125)seconds. int i = (int)((millis - getYearMillis(year)) >> 10); // There are 86400000 milliseconds per day, but divided by 1024 is // 84375. There are 84375 (128/125)seconds per day. return (isLeapYear(year)) ? ((i < 182 * 84375) ? ((i < 91 * 84375) ? ((i < 31 * 84375) ? 1 : (i < 60 * 84375) ? 2 : 3) : ((i < 121 * 84375) ? 4 : (i < 152 * 84375) ? 5 : 6)) : ((i < 274 * 84375) ? ((i < 213 * 84375) ? 7 : (i < 244 * 84375) ? 8 : 9) : ((i < 305 * 84375) ? 10 : (i < 335 * 84375) ? 11 : 12))) : ((i < 181 * 84375) ? ((i < 90 * 84375) ? ((i < 31 * 84375) ? 1 : (i < 59 * 84375) ? 2 : 3) : ((i < 120 * 84375) ? 4 : (i < 151 * 84375) ? 5 : 6)) : ((i < 273 * 84375) ? ((i < 212 * 84375) ? 7 : (i < 243 * 84375) ? 8 : 9) : ((i < 304 * 84375) ? 10 : (i < 334 * 84375) ? 11 : 12))); } //----------------------------------------------------------------------- /** * Gets the number of days in the specified month and year. * * @param year the year * @param month the month * @return the number of days */ int getDaysInYearMonth:(NSInteger) year :(NSInteger)month) { if (isLeapYear(year)) { return MAX_DAYS_PER_MONTH_ARRAY[month - 1]; } else { return MIN_DAYS_PER_MONTH_ARRAY[month - 1]; } } //----------------------------------------------------------------------- int getDaysInMonthMax:(NSInteger) month) { return MAX_DAYS_PER_MONTH_ARRAY[month - 1]; } //----------------------------------------------------------------------- int getDaysInMonthMaxForSet:(NSInteger)instant :(NSInteger)value) { return (value > 28 ? getDaysInMonthMax(instant) : 28); } //----------------------------------------------------------------------- - (NSInteger)getTotalMillisByYearMonth:(NSInteger) year :(NSInteger)month) { if (isLeapYear(year)) { return MAX_TOTAL_MILLIS_BY_MONTH_ARRAY[month - 1]; } else { return MIN_TOTAL_MILLIS_BY_MONTH_ARRAY[month - 1]; } } //----------------------------------------------------------------------- - (NSInteger)getYearDifference:(NSInteger)minuendInstant :(NSInteger)subtrahendInstant) { int minuendYear = getYear(minuendInstant); int subtrahendYear = getYear(subtrahendInstant); // Inlined remainder method to avoid duplicate calls to get. - (NSInteger)minuendRem = minuendInstant - getYearMillis(minuendYear); - (NSInteger)subtrahendRem = subtrahendInstant - getYearMillis(subtrahendYear); // Balance leap year differences on remainders. if (subtrahendRem >= FEB_29) { if (isLeapYear(subtrahendYear)) { if (!isLeapYear(minuendYear)) { subtrahendRem -= DateTimeConstants.MILLIS_PER_DAY; } } else if (minuendRem >= FEB_29 && isLeapYear(minuendYear)) { minuendRem -= DateTimeConstants.MILLIS_PER_DAY; } } int difference = minuendYear - subtrahendYear; if (minuendRem < subtrahendRem) { difference--; } return difference; } //----------------------------------------------------------------------- - (NSInteger)setYear:(NSInteger)instant :(NSInteger)year) { int thisYear = getYear(instant); int dayOfYear = getDayOfYear(instant, thisYear); int millisOfDay = getMillisOfDay(instant); if (dayOfYear > (31 + 28)) { // after Feb 28 if (isLeapYear(thisYear)) { // Current date is Feb 29 or later. if (!isLeapYear(year)) { // Moving to a non-leap year, Feb 29 does not exist. dayOfYear--; } } else { // Current date is Mar 01 or later. if (isLeapYear(year)) { // Moving to a leap year, account for Feb 29. dayOfYear++; } } } instant = getYearMonthDayMillis(year, 1, dayOfYear); instant += millisOfDay; return instant; } } @end
36.680851
89
0.570302
[ "object" ]
695d0aef89828c88573a0c3db0b52dd8cab75610
9,670
h
C
utils/ring_buffer.h
leobispo/jml
d5e8f91419789fcdb913339fe11b67dbcc75d43d
[ "Apache-2.0" ]
1
2018-02-27T08:01:22.000Z
2018-02-27T08:01:22.000Z
utils/ring_buffer.h
leobispo/jml
d5e8f91419789fcdb913339fe11b67dbcc75d43d
[ "Apache-2.0" ]
null
null
null
utils/ring_buffer.h
leobispo/jml
d5e8f91419789fcdb913339fe11b67dbcc75d43d
[ "Apache-2.0" ]
null
null
null
/* ring_buffer.h -*- C++ -*- Jeremy Barnes, 25 May 2012 Copyright (c) 2012 Datacratic. All rights reserved. Ring buffer for when there are one or more producers and one consumer chasing each other. */ #ifndef __jml_utils__ring_buffer_h__ #define __jml_utils__ring_buffer_h__ #include <vector> #include "jml/arch/futex.h" #include "jml/arch/spinlock.h" #include <mutex> #include <thread> namespace ML { template<typename Request> struct RingBufferBase { RingBufferBase(size_t size) { init(size); } std::vector<Request> ring; int bufferSize; int readPosition; int writePosition; void init(size_t numEntries) { ring.resize(numEntries); bufferSize = numEntries; readPosition = 0; writePosition = 0; } }; /*****************************************************************************/ /* RING BUFFER SINGLE WRITER MULTIPLE READERS */ /*****************************************************************************/ /** Single writer multiple reader ring buffer. */ template<typename Request> struct RingBufferSWMR : public RingBufferBase<Request> { using RingBufferBase<Request>::init; using RingBufferBase<Request>::ring; using RingBufferBase<Request>::bufferSize; using RingBufferBase<Request>::readPosition; using RingBufferBase<Request>::writePosition; RingBufferSWMR(size_t size) : RingBufferBase<Request>(size) { } typedef std::timed_mutex Mutex; mutable Mutex readMutex; // todo: we don't need this... get rid of it typedef std::unique_lock<Mutex> Guard; void push(const Request & request) { for (;;) { // What position would the read position be in if the buffer was // full? unsigned fullReadPosition = (writePosition + 1) % bufferSize; if (readPosition == fullReadPosition) ML::futex_wait(readPosition, fullReadPosition); else break; } ring[writePosition] = request; writePosition = (writePosition + 1) % bufferSize; ML::futex_wake(writePosition); } void push(Request && request) { for (;;) { // What position would the read position be in if the buffer was // full? unsigned fullReadPosition = (writePosition + 1) % bufferSize; if (readPosition == fullReadPosition) ML::futex_wait(readPosition, fullReadPosition); else break; } std::swap(ring[writePosition], request); writePosition = (writePosition + 1) % bufferSize; ML::futex_wake(writePosition); } void waitUntilEmpty() { for (;;) { int readPos = readPosition; if (readPos == writePosition) return; ML::futex_wait(readPosition, readPos); } } bool tryPush(const Request & request) { // What position would the read position be in if the buffer was // full? unsigned fullReadPosition = (writePosition + 1) % bufferSize; if (readPosition == fullReadPosition) return false; ring[writePosition] = request; writePosition = (writePosition + 1) % bufferSize; ML::futex_wake(writePosition); return true; } bool tryPush(Request && request) { // What position would the read position be in if the buffer was // full? unsigned fullReadPosition = (writePosition + 1) % bufferSize; if (readPosition == fullReadPosition) return false; std::swap(ring[writePosition], request); writePosition = (writePosition + 1) % bufferSize; ML::futex_wake(writePosition); return true; } Request pop() { Request result; { Guard guard(readMutex); // todo... can get rid of this one... // Wait until write position != read position, ie not full for (;;) { if (writePosition == readPosition) ML::futex_wait(writePosition, readPosition); else break; } result = ring[readPosition]; ring[readPosition] = Request(); readPosition = (readPosition + 1) % bufferSize; } ML::futex_wake(readPosition); return result; } bool tryPop(Request & result, double maxWaitTime) { { // todo... can get rid of this one... Guard guard(readMutex, std::chrono::microseconds(uint64_t(maxWaitTime * 1000000))); if (!guard) return false; // Wait until write position != read position, ie not full if (writePosition == readPosition) { ML::futex_wait(writePosition, readPosition, maxWaitTime); if (writePosition == readPosition) return false; } //std::swap(result, ring[readPosition]); result = std::move(ring[readPosition]); //ring[readPosition] = Request(); readPosition = (readPosition + 1) % bufferSize; } ML::futex_wake(readPosition); return true; } bool tryPop(Request & result) { { // todo... can get rid of this one... Guard guard(readMutex, std::try_to_lock_t()); if (!guard) return false; // Wait until write position != read position, ie not full if (writePosition == readPosition) return false; //std::swap(result, ring[readPosition]); result = std::move(ring[readPosition]); //ring[readPosition] = Request(); readPosition = (readPosition + 1) % bufferSize; } ML::futex_wake(readPosition); return true; } }; /*****************************************************************************/ /* RING BUFFER SINGLE READER MULTIPLE WRITERS */ /*****************************************************************************/ template<typename Request> struct RingBufferSRMW : public RingBufferBase<Request> { using RingBufferBase<Request>::init; using RingBufferBase<Request>::ring; using RingBufferBase<Request>::bufferSize; using RingBufferBase<Request>::readPosition; using RingBufferBase<Request>::writePosition; RingBufferSRMW(size_t size) : RingBufferBase<Request>(size) { } typedef ML::Spinlock Mutex; mutable Mutex mutex; // todo: get rid of... typedef std::unique_lock<Mutex> Guard; void push(const Request & request) { Guard guard(mutex); for (;;) { // What position would the read position be in if the buffer was // full? unsigned fullReadPosition = (writePosition + 1) % bufferSize; if (readPosition == fullReadPosition) ML::futex_wait(readPosition, fullReadPosition); else break; } //ring[writePosition] = request; ring[writePosition] = request; writePosition = (writePosition + 1) % bufferSize; ML::futex_wake(writePosition); } bool tryPush(const Request & request) { Guard guard(mutex); // What position would the read position be in if the buffer was // full? unsigned fullReadPosition = (writePosition + 1) % bufferSize; if (readPosition == fullReadPosition) return false; //ring[writePosition] = request; ring[writePosition] = request; writePosition = (writePosition + 1) % bufferSize; ML::futex_wake(writePosition); return true; } Request pop() { Request result; { // Wait until write position != read position, ie not full for (;;) { if (writePosition == readPosition) ML::futex_wait(writePosition, readPosition); else break; } result = ring[readPosition]; ring[readPosition] = Request(); readPosition = (readPosition + 1) % bufferSize; } ML::futex_wake(readPosition); return result; } bool tryPop(Request & result) { if (writePosition == readPosition) return false; result = ring[readPosition]; ring[readPosition] = Request(); readPosition = (readPosition + 1) % bufferSize; ML::futex_wake(readPosition); return true; } bool tryPop(Request & result, double maxWaitTime) { { // Wait until write position != read position, ie not full for (;;) { if (writePosition == readPosition) { if (ML::futex_wait(writePosition, readPosition, maxWaitTime) == -1 && errno == ETIMEDOUT) return false; } else break; } result = ring[readPosition]; ring[readPosition] = Request(); readPosition = (readPosition + 1) % bufferSize; } ML::futex_wake(readPosition); return true; } bool couldPop() const { return writePosition != readPosition; } }; } // namespace ML #endif /* __jml_utils__ring_buffer_h__ */
29.30303
86
0.53971
[ "vector" ]
6960d0db3826b367b4cb3597760b6dacb3ad6224
3,519
h
C
Unidad 3- Ciencia de datos/5- Database_Parsing/dataset_types.h
JosueJuarez/ProgramacionCientifica-UV
1bedb7a56239f1c7948260bc490ad26c03effa86
[ "Unlicense" ]
2
2020-09-18T20:28:41.000Z
2020-10-30T20:27:46.000Z
Unidad 3- Ciencia de datos/5- Database_Parsing/dataset_types.h
JosueJuarez/ProgramacionCientifica-UV
1bedb7a56239f1c7948260bc490ad26c03effa86
[ "Unlicense" ]
1
2020-10-22T01:53:17.000Z
2020-10-22T01:53:17.000Z
Unidad 3- Ciencia de datos/5- Database_Parsing/dataset_types.h
JosueJuarez/ProgramacionCientifica-UV
1bedb7a56239f1c7948260bc490ad26c03effa86
[ "Unlicense" ]
6
2020-09-18T21:11:49.000Z
2021-10-01T16:41:35.000Z
#pragma once #include <vector> #include <string> /**************************** * * * Dataset storage * * * ****************************/ struct Indicators { double negativeVolumeIndexNVI; double negativeVolumeIndexCumAvg; double onBalanceVolume; double performance; double positiveVolumeIndexPVI; double positiveVolumeIndexCumAvg; double priceVolumeTrend; double trueRange; double transactionVolume; double williamsAccumulationDistribution; double parabolicStopAndReversal; double medianPrice; double typicalPrice; double weightedClose; double closePrice; double highPrice; double lowPrice; double openPrice; double aroonHigh20, aroonHigh40, aroonHigh60, aroonHigh80; double aroonLow20, aroonLow40, aroonLow60, aroonLow80; double aroonOscillator20, aroonOscillator40, aroonOscillator60, aroonOscillator80; double averageTrueRange20, averageTrueRange40, averageTrueRange60, averageTrueRange80; double detrendedPriceOscillator20, detrendedPriceOscillator40, detrendedPriceOscillator60, detrendedPriceOscillator80; double forceIndex20, forceIndex40, forceIndex60, forceIndex80; double forecastOscillator20, forecastOscillator40, forecastOscillator60, forecastOscillator80; double linearRegressionSlope20, linearRegressionSlope40, linearRegressionSlope60, linearRegressionSlope80; double mESAPhase20, mESAPhase40, mESAPhase60, mESAPhase80; double mESASineWaveSin20, mESASineWaveSin40, mESASineWaveSin60, mESASineWaveSin80; double mESASineWaveCos20, mESASineWaveCos40, mESASineWaveCos60, mESASineWaveCos80; double momentum20, momentum40, momentum60, momentum80; double qStick20, qStick40, qStick60, qStick80; double rateOfChange20, rateOfChange40, rateOfChange60, rateOfChange80; double priceStandardDeviation20, priceStandardDeviation40, priceStandardDeviation60, priceStandardDeviation80; double standardError20, standardError40, standardError60, standardError80; double timeSegmentedVolume20, timeSegmentedVolume40, timeSegmentedVolume60, timeSegmentedVolume80; double sma20, sma40, sma60, sma80; double doubleExponentialMovingAverage20, doubleExponentialMovingAverage40, doubleExponentialMovingAverage60, doubleExponentialMovingAverage80; double ema20, ema40, ema60, ema80; double weightedMovingAverage20, weightedMovingAverage40, weightedMovingAverage60, weightedMovingAverage80; double linearRegressionTrendlines20, linearRegressionTrendlines40, linearRegressionTrendlines60, linearRegressionTrendlines80; double triangularMovingAverage20, triangularMovingAverage40, triangularMovingAverage60, triangularMovingAverage80; double tripleExponentialMovingAverage20, tripleExponentialMovingAverage40, tripleExponentialMovingAverage60, tripleExponentialMovingAverage80; double priceTimeSeriesForecast20, priceTimeSeriesForecast40, priceTimeSeriesForecast60, priceTimeSeriesForecast80; double wildersMovingAverage20, wildersMovingAverage40, wildersMovingAverage60, wildersMovingAverage80; double highestHigh20, highestHigh40, highestHigh60, highestHigh80; double lowestLow20, lowestLow40, lowestLow60, lowestLow80; }; struct TimedIndicators { std::string time; Indicators indicators; }; struct StockData { std::string date; std::vector<TimedIndicators> timedIndicators; }; struct Dataset { std::string stockName; std::vector<StockData> stockData; };
45.115385
146
0.793123
[ "vector" ]
69794e93967d8e0d58140fbde65958645a920fb4
17,754
h
C
Engine/Source/Runtime/Engine/Classes/Kismet/BlueprintSetLibrary.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Runtime/Engine/Classes/Kismet/BlueprintSetLibrary.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Runtime/Engine/Classes/Kismet/BlueprintSetLibrary.h
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "UObject/Script.h" #include "UObject/ObjectMacros.h" #include "UObject/UnrealType.h" #include "UObject/ScriptMacros.h" #include "Kismet/BlueprintFunctionLibrary.h" #include "BlueprintSetLibrary.generated.h" UCLASS(Experimental) class ENGINE_API UBlueprintSetLibrary : public UBlueprintFunctionLibrary { GENERATED_BODY() public: /** * Adds item to set. Output value indicates whether the item was successfully added, meaning an * output of False indicates the item was already in the Set. * * @param TargetSet The set to add item to * @param NewItem The item to add to the set * @return True if NewItem was added to the set (False indicates an equivalent item was present) * */ UFUNCTION(BlueprintCallable, CustomThunk, meta=(DisplayName = "Add", CompactNodeTitle = "ADD", SetParam = "TargetSet|NewItem", AutoCreateRefTerm = "NewItem"), Category="Utilities|Set") static void Set_Add(const TSet<int32>& TargetSet, const int32& NewItem); /** * Adds all elements from an Array to a Set * * @param TargetSet The set to search for the item * @param NewItems The items to add to the set */ UFUNCTION(BlueprintCallable, CustomThunk, meta=(DisplayName = "Add Items", CompactNodeTitle = "ADD ITEMS", SetParam = "TargetSet|NewItems", AutoCreateRefTerm = "NewItems"), Category="Utilities|Set") static void Set_AddItems(const TSet<int32>& TargetSet, const TArray<int32>& NewItems); /** * Remove item from set. Output value indicates if something was actually removed. False * indicates no equivalent item was found. * * @param TargetSet The set to remove from * @param Item The item to remove from the set * @return True if an item was removed (False indicates no equivalent item was present) */ UFUNCTION(BlueprintCallable, CustomThunk, meta=(DisplayName = "Remove", CompactNodeTitle = "REMOVE", SetParam = "TargetSet|Item", AutoCreateRefTerm = "Item"), Category="Utilities|Set") static bool Set_Remove(const TSet<int32>& TargetSet, const int32& Item); /** * Removes all elements in an Array from a set. * * @param TargetSet The set to remove from * @param Items The items to remove from the set */ UFUNCTION(BlueprintCallable, CustomThunk, meta=(DisplayName = "Remove Items", CompactNodeTitle = "REMOVE ITEMS", SetParam = "TargetSet|Items", AutoCreateRefTerm = "Items"), Category="Utilities|Set") static void Set_RemoveItems(const TSet<int32>& TargetSet, const TArray<int32>& Items); /** * Outputs an Array containing copies of the entries of a Set. * * @param A Set * @param Result Array */ UFUNCTION(BlueprintCallable, CustomThunk, meta = (DisplayName = "To Array", CompactNodeTitle = "TO ARRAY", SetParam = "A|Result"), Category = "Utilities|Set") static void Set_ToArray(const TSet<int32>& A, TArray<int32>& Result); /** * Clear a set, removes all content. * * @param TargetSet The set to clear */ UFUNCTION(BlueprintCallable, CustomThunk, meta=(DisplayName = "Clear", CompactNodeTitle = "CLEAR", Keywords = "empty", SetParam = "TargetSet"), Category="Utilities|Set") static void Set_Clear(const TSet<int32>& TargetSet); /** * Get the number of items in a set. * * @param TargetSet The set to get the length of * @return The length of the set */ UFUNCTION(BlueprintPure, CustomThunk, meta=(DisplayName = "Length", CompactNodeTitle = "LENGTH", SetParam = "TargetSet", Keywords = "num size count", BlueprintThreadSafe), Category="Utilities|Set") static int32 Set_Length(const TSet<int32>& TargetSet); /** * Returns true if the set contains the given item. * * @param TargetSet The set to search for the item * @param ItemToFind The item to look for * @return True if the item was found within the set */ UFUNCTION(BlueprintPure, CustomThunk, meta=(DisplayName = "Contains Item", CompactNodeTitle = "CONTAINS", SetParam = "TargetSet|ItemToFind", AutoCreateRefTerm = "ItemToFind", BlueprintThreadSafe), Category="Utilities|Set") static bool Set_Contains(const TSet<int32>& TargetSet, const int32& ItemToFind); /** * Assigns Result to the intersection of Set A and Set B. That is, Result will contain * all elements that are in both Set A and Set B. To intersect with the empty set use * Clear. * * @param A One set to intersect * @param B Another set to intersect * @param Result Set to store results in */ UFUNCTION(BlueprintCallable, CustomThunk, meta=(DisplayName = "Intersection", CompactNodeTitle = "INTERSECTION", SetParam = "A|B|Result"), Category="Utilities|Set") static void Set_Intersection(const TSet<int32>& A, const TSet<int32>& B, TSet<int32>& Result ); /** * Assigns Result to the union of two sets, A and B. That is, Result will contain * all elements that are in Set A and in addition all elements in Set B. Note that * a Set is a collection of unique elements, so duplicates will be eliminated. * * @param A One set to union * @param B Another set to union * @param Result Set to store results in */ UFUNCTION(BlueprintCallable, CustomThunk, meta = (DisplayName = "Union", CompactNodeTitle = "UNION", SetParam = "A|B|Result"), Category = "Utilities|Set") static void Set_Union(const TSet<int32>& A, const TSet<int32>& B, TSet<int32>& Result ); /** * Assigns Result to the relative difference of two sets, A and B. That is, Result will * contain all elements that are in Set A but are not found in Set B. Note that the * difference between two sets is not commutative. The Set whose elements you wish to * preserve should be the first (top) parameter. Also called the relative complement. * * @param A Starting set * @param B Set of elements to remove from set A * @param Result Set containing all elements in A that are not found in B */ UFUNCTION(BlueprintCallable, CustomThunk, meta = (DisplayName = "Difference", CompactNodeTitle = "DIFFERENCE", SetParam = "A|B|Result"), Category = "Utilities|Set") static void Set_Difference(const TSet<int32>& A, const TSet<int32>& B, TSet<int32>& Result ); /** * Not exposed to users. Supports setting a set property on an object by name. */ UFUNCTION(BlueprintCallable, CustomThunk, meta=(BlueprintInternalUseOnly = "true", SetParam = "Value")) static void SetSetPropertyByName(UObject* Object, FName PropertyName, const TSet<int32>& Value); DECLARE_FUNCTION(execSet_Add) { Stack.MostRecentProperty = nullptr; Stack.StepCompiledIn<USetProperty>(NULL); void* SetAddr = Stack.MostRecentPropertyAddress; USetProperty* SetProperty = Cast<USetProperty>(Stack.MostRecentProperty); if (!SetProperty) { Stack.bArrayContextFailed = true; return; } // Since ItemPtr isn't really an int, step the stack manually const UProperty* ElementProp = SetProperty->ElementProp; const int32 PropertySize = ElementProp->ElementSize * ElementProp->ArrayDim; void* StorageSpace = FMemory_Alloca(PropertySize); ElementProp->InitializeValue(StorageSpace); Stack.MostRecentPropertyAddress = NULL; Stack.StepCompiledIn<UProperty>(StorageSpace); void* ItemPtr = StorageSpace; P_FINISH; P_NATIVE_BEGIN; GenericSet_Add(SetAddr, SetProperty, ItemPtr); P_NATIVE_END; ElementProp->DestroyValue(StorageSpace); } DECLARE_FUNCTION(execSet_AddItems) { Stack.MostRecentProperty = nullptr; Stack.StepCompiledIn<USetProperty>(NULL); void* SetAddr = Stack.MostRecentPropertyAddress; USetProperty* SetProperty = Cast<USetProperty>(Stack.MostRecentProperty); if (!SetProperty) { Stack.bArrayContextFailed = true; return; } Stack.MostRecentProperty = nullptr; Stack.StepCompiledIn<UArrayProperty>(NULL); void* TargetArrayAddr = Stack.MostRecentPropertyAddress; UArrayProperty* TargetArrayProperty = Cast<UArrayProperty>(Stack.MostRecentProperty); if (!TargetArrayProperty) { Stack.bArrayContextFailed = true; return; } P_FINISH; P_NATIVE_BEGIN; GenericSet_AddItems(SetAddr, SetProperty, TargetArrayAddr, TargetArrayProperty); P_NATIVE_END; } DECLARE_FUNCTION(execSet_Remove) { Stack.MostRecentProperty = nullptr; Stack.StepCompiledIn<USetProperty>(NULL); void* SetAddr = Stack.MostRecentPropertyAddress; USetProperty* SetProperty = Cast<USetProperty>(Stack.MostRecentProperty); if (!SetProperty) { Stack.bArrayContextFailed = true; return; } // Since ItemPtr isn't really an int, step the stack manually const UProperty* ElementProp = SetProperty->ElementProp; const int32 PropertySize = ElementProp->ElementSize * ElementProp->ArrayDim; void* StorageSpace = FMemory_Alloca(PropertySize); ElementProp->InitializeValue(StorageSpace); Stack.MostRecentPropertyAddress = NULL; Stack.StepCompiledIn<UProperty>(StorageSpace); void* ItemPtr = StorageSpace; P_FINISH; P_NATIVE_BEGIN; *(bool*)RESULT_PARAM = GenericSet_Remove(SetAddr, SetProperty, ItemPtr); P_NATIVE_END; ElementProp->DestroyValue(StorageSpace); } DECLARE_FUNCTION(execSet_RemoveItems) { Stack.MostRecentProperty = nullptr; Stack.StepCompiledIn<USetProperty>(NULL); void* SetAddr = Stack.MostRecentPropertyAddress; USetProperty* SetProperty = Cast<USetProperty>(Stack.MostRecentProperty); if (!SetProperty) { Stack.bArrayContextFailed = true; return; } Stack.MostRecentProperty = nullptr; Stack.StepCompiledIn<UArrayProperty>(NULL); void* TargetArrayAddr = Stack.MostRecentPropertyAddress; UArrayProperty* TargetArrayProperty = Cast<UArrayProperty>(Stack.MostRecentProperty); if (!TargetArrayProperty) { Stack.bArrayContextFailed = true; return; } P_FINISH; P_NATIVE_BEGIN; GenericSet_RemoveItems(SetAddr, SetProperty, TargetArrayAddr, TargetArrayProperty); P_NATIVE_END; } DECLARE_FUNCTION(execSet_ToArray) { Stack.MostRecentProperty = nullptr; Stack.StepCompiledIn<USetProperty>(NULL); void* SetAddr = Stack.MostRecentPropertyAddress; USetProperty* SetProperty = Cast<USetProperty>(Stack.MostRecentProperty); if (!SetProperty) { Stack.bArrayContextFailed = true; return; } Stack.MostRecentProperty = nullptr; Stack.StepCompiledIn<UArrayProperty>(NULL); void* TargetArrayAddr = Stack.MostRecentPropertyAddress; UArrayProperty* TargetArrayProperty = Cast<UArrayProperty>(Stack.MostRecentProperty); if (!TargetArrayProperty) { Stack.bArrayContextFailed = true; return; } P_FINISH; P_NATIVE_BEGIN; GenericSet_ToArray(SetAddr, SetProperty, TargetArrayAddr, TargetArrayProperty); P_NATIVE_END; } DECLARE_FUNCTION(execSet_Clear) { Stack.MostRecentProperty = nullptr; Stack.StepCompiledIn<USetProperty>(NULL); void* SetAddr = Stack.MostRecentPropertyAddress; USetProperty* SetProperty = Cast<USetProperty>(Stack.MostRecentProperty); if (!SetProperty) { Stack.bArrayContextFailed = true; return; } P_FINISH; // Perform the search P_NATIVE_BEGIN; GenericSet_Clear(SetAddr, SetProperty); P_NATIVE_END; } DECLARE_FUNCTION(execSet_Length) { Stack.MostRecentProperty = nullptr; Stack.StepCompiledIn<USetProperty>(NULL); void* SetAddr = Stack.MostRecentPropertyAddress; USetProperty* SetProperty = Cast<USetProperty>(Stack.MostRecentProperty); if (!SetProperty) { Stack.bArrayContextFailed = true; return; } P_FINISH; // Perform the search P_NATIVE_BEGIN; *(int32*)RESULT_PARAM = GenericSet_Length(SetAddr, SetProperty); P_NATIVE_END; } DECLARE_FUNCTION(execSet_Contains) { Stack.MostRecentProperty = nullptr; Stack.StepCompiledIn<USetProperty>(NULL); void* SetAddr = Stack.MostRecentPropertyAddress; USetProperty* SetProperty = Cast<USetProperty>(Stack.MostRecentProperty); if (!SetProperty) { // @todo(dano): rename to 'container context failed' Stack.bArrayContextFailed = true; return; } // Since ItemToFind isn't really an int, step the stack manually const UProperty* ElementProp = SetProperty->ElementProp; const int32 PropertySize = ElementProp->ElementSize * ElementProp->ArrayDim; void* StorageSpace = FMemory_Alloca(PropertySize); ElementProp->InitializeValue(StorageSpace); Stack.MostRecentPropertyAddress = NULL; Stack.StepCompiledIn<UProperty>(StorageSpace); void* ItemToFindPtr = StorageSpace; P_FINISH; P_NATIVE_BEGIN; *(bool*)RESULT_PARAM = GenericSet_Contains(SetAddr, SetProperty, ItemToFindPtr); P_NATIVE_END; ElementProp->DestroyValue(StorageSpace); } DECLARE_FUNCTION(execSet_Intersection) { Stack.MostRecentProperty = nullptr; Stack.StepCompiledIn<USetProperty>(NULL); void* SetAddrA = Stack.MostRecentPropertyAddress; USetProperty* SetPropertyA = Cast<USetProperty>(Stack.MostRecentProperty); if (!SetPropertyA) { Stack.bArrayContextFailed = true; return; } Stack.MostRecentProperty = nullptr; Stack.StepCompiledIn<USetProperty>(NULL); void* SetAddrB = Stack.MostRecentPropertyAddress; USetProperty* SetPropertyB = Cast<USetProperty>(Stack.MostRecentProperty); if (!SetPropertyB) { Stack.bArrayContextFailed = true; return; } Stack.MostRecentProperty = nullptr; Stack.StepCompiledIn<USetProperty>(NULL); void* SetAddrResult = Stack.MostRecentPropertyAddress; USetProperty* SetPropertyResult = Cast<USetProperty>(Stack.MostRecentProperty); if (!SetPropertyResult) { Stack.bArrayContextFailed = true; return; } P_FINISH; P_NATIVE_BEGIN; GenericSet_Intersect(SetAddrA, SetPropertyA, SetAddrB, SetPropertyB, SetAddrResult, SetPropertyResult); P_NATIVE_END; } DECLARE_FUNCTION(execSet_Union) { Stack.MostRecentProperty = nullptr; Stack.StepCompiledIn<USetProperty>(NULL); void* SetAddrA = Stack.MostRecentPropertyAddress; USetProperty* SetPropertyA = Cast<USetProperty>(Stack.MostRecentProperty); if (!SetPropertyA) { Stack.bArrayContextFailed = true; return; } Stack.MostRecentProperty = nullptr; Stack.StepCompiledIn<USetProperty>(NULL); void* SetAddrB = Stack.MostRecentPropertyAddress; USetProperty* SetPropertyB = Cast<USetProperty>(Stack.MostRecentProperty); if (!SetPropertyB) { Stack.bArrayContextFailed = true; return; } Stack.MostRecentProperty = nullptr; Stack.StepCompiledIn<USetProperty>(NULL); void* SetAddrResult = Stack.MostRecentPropertyAddress; USetProperty* SetPropertyResult = Cast<USetProperty>(Stack.MostRecentProperty); if (!SetPropertyResult) { Stack.bArrayContextFailed = true; return; } P_FINISH; P_NATIVE_BEGIN; GenericSet_Union(SetAddrA, SetPropertyA, SetAddrB, SetPropertyB, SetAddrResult, SetPropertyResult); P_NATIVE_END; } DECLARE_FUNCTION(execSet_Difference) { Stack.MostRecentProperty = nullptr; Stack.StepCompiledIn<USetProperty>(NULL); void* SetAddrA = Stack.MostRecentPropertyAddress; USetProperty* SetPropertyA = Cast<USetProperty>(Stack.MostRecentProperty); if (!SetPropertyA) { Stack.bArrayContextFailed = true; return; } Stack.MostRecentProperty = nullptr; Stack.StepCompiledIn<USetProperty>(NULL); void* SetAddrB = Stack.MostRecentPropertyAddress; USetProperty* SetPropertyB = Cast<USetProperty>(Stack.MostRecentProperty); if (!SetPropertyB) { Stack.bArrayContextFailed = true; return; } Stack.MostRecentProperty = nullptr; Stack.StepCompiledIn<USetProperty>(NULL); void* SetAddrResult = Stack.MostRecentPropertyAddress; USetProperty* SetPropertyResult = Cast<USetProperty>(Stack.MostRecentProperty); if (!SetPropertyResult) { Stack.bArrayContextFailed = true; return; } P_FINISH; P_NATIVE_BEGIN; GenericSet_Difference(SetAddrA, SetPropertyA, SetAddrB, SetPropertyB, SetAddrResult, SetPropertyResult); P_NATIVE_END; } DECLARE_FUNCTION(execSetSetPropertyByName) { P_GET_OBJECT(UObject, OwnerObject); P_GET_PROPERTY(UNameProperty, SetPropertyName); Stack.StepCompiledIn<USetProperty>(nullptr); void* SrcSetAddr = Stack.MostRecentPropertyAddress; P_FINISH; P_NATIVE_BEGIN; GenericSet_SetSetPropertyByName(OwnerObject, SetPropertyName, SrcSetAddr); P_NATIVE_END; } static void GenericSet_Add(const void* TargetSet, const USetProperty* SetProperty, const void* ItemPtr); static void GenericSet_AddItems(const void* TargetSet, const USetProperty* SetProperty, const void* TargetArray, const UArrayProperty* ArrayProperty); static bool GenericSet_Remove(const void* TargetSet, const USetProperty* SetProperty, const void* ItemPtr); static void GenericSet_RemoveItems(const void* TargetSet, const USetProperty* SetProperty, const void* TargetArray, const UArrayProperty* ArrayProperty); static void GenericSet_ToArray(const void* TargetSet, const USetProperty* SetProperty, void* TargetArray, const UArrayProperty* ArrayProperty); static void GenericSet_Clear(const void* TargetSet, const USetProperty* SetProperty); static int32 GenericSet_Length(const void* TargetSet, const USetProperty* SetProperty); static bool GenericSet_Contains(const void* TargetSet, const USetProperty* SetProperty, const void* ItemToFind); static void GenericSet_Intersect(const void* SetA, const USetProperty* SetPropertyA, const void* SetB, const USetProperty* SetPropertyB, const void* SetResult, const USetProperty* SetPropertyResult); static void GenericSet_Union(const void* SetA, const USetProperty* SetPropertyA, const void* SetB, const USetProperty* SetPropertyB, const void* SetResult, const USetProperty* SetPropertyResult); static void GenericSet_Difference(const void* SetA, const USetProperty* SetPropertyA, const void* SetB, const USetProperty* SetPropertyB, const void* SetResult, const USetProperty* SetPropertyResult); static void GenericSet_SetSetPropertyByName(UObject* OwnerObject, FName SetPropertyName, const void* SrcSetAddr); };
35.017751
223
0.757519
[ "object" ]
697be33974ce45e9a69ef20ae1a8c322f2b3a7eb
18,383
c
C
B2G/hardware/ti/wlan/wl1271/TWD/MacServices/MacServices.c
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-08-31T15:24:31.000Z
2020-04-24T20:31:29.000Z
B2G/hardware/ti/wlan/wl1271/TWD/MacServices/MacServices.c
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
null
null
null
B2G/hardware/ti/wlan/wl1271/TWD/MacServices/MacServices.c
wilebeast/FireFox-OS
43067f28711d78c429a1d6d58c77130f6899135f
[ "Apache-2.0" ]
3
2015-07-29T07:17:15.000Z
2020-11-04T06:55:37.000Z
/* * MacServices.c * * Copyright(c) 1998 - 2009 Texas Instruments. All rights reserved. * 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 Texas Instruments nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** \file MacServices.c * \brief This file include public definitions for the scan SRV module, comprising its API. * \author Yuval Adler * \date 6-Oct-2005 */ #define __FILE_ID__ FILE_ID_109 #include "report.h" #include "ScanSrv.h" #include "MeasurementSrv.h" #include "MacServices.h" #include "PowerSrv_API.h" /**************************************************************************************** * MacServices_create * ***************************************************************************************** DESCRIPTION: Creates MacServices module INPUT: hOS - handle to the OS object. OUTPUT: RETURN: handle to MacServices Object, NULL on failure . ****************************************************************************************/ TI_HANDLE MacServices_create( TI_HANDLE hOS) { MacServices_t *pMacServices = (MacServices_t*)os_memoryAlloc( hOS, sizeof(MacServices_t) ); if ( NULL == pMacServices ) { WLAN_OS_REPORT( ("ERROR: Failed to create Mac SRV module") ); return NULL; } /* nullify all handles, so that only handles in existence will be released */ pMacServices->hScanSRV = NULL; pMacServices->hPowerSrv = NULL; /* create the scanSRV handle */ pMacServices->hScanSRV = MacServices_scanSRV_create(hOS); if ( NULL == pMacServices->hScanSRV ) { MacServices_destroy( pMacServices ); return NULL; } /* create the measurment handle */ pMacServices->hMeasurementSRV = MacServices_measurementSRV_create( hOS ); if ( NULL == pMacServices->hMeasurementSRV ) { MacServices_destroy(pMacServices); return NULL; } pMacServices->hPowerSrv = powerSrv_create(hOS); if (NULL == pMacServices->hPowerSrv ) { MacServices_destroy(pMacServices); return NULL; } /* store OS handle */ pMacServices->hOS = hOS; return pMacServices; } /**************************************************************************************** * MacServices_destroy * ***************************************************************************************** DESCRIPTION: destroys MacServices module INPUT: hMacServices - handle to the Mac Services object. OUTPUT: RETURN: ****************************************************************************************/ void MacServices_destroy( TI_HANDLE hMacServices ) { MacServices_t *pMacServices = (MacServices_t*)hMacServices; /* destroy all SRV modules */ if ( NULL != pMacServices->hScanSRV ) { MacServices_scanSRV_destroy( pMacServices->hScanSRV ); } if ( NULL != pMacServices->hMeasurementSRV ) { MacServices_measurementSRV_destroy( pMacServices->hMeasurementSRV ); } if(pMacServices->hPowerSrv) powerSrv_destroy(pMacServices->hPowerSrv); /* free the Mac services allocated context */ os_memoryFree( pMacServices->hOS, (TI_HANDLE)pMacServices , sizeof(MacServices_t) ); } /**************************************************************************************** * MacServices_init * ***************************************************************************************** DESCRIPTION: Initializes the MacServices module INPUT: hMacServices - handle to the Mac Services object.\n hReport - handle to the report object.\n hHalCtrl - handle to the HAL ctrl object.\n OUTPUT: RETURN: ****************************************************************************************/ void MacServices_init (TI_HANDLE hMacServices, TI_HANDLE hReport, TI_HANDLE hTWD, TI_HANDLE hCmdBld, TI_HANDLE hEventMbox, TI_HANDLE hTimer) { MacServices_t *pMacServices = (MacServices_t*)hMacServices; MacServices_scanSRV_init (hMacServices, hReport, hTWD, hTimer, hEventMbox, hCmdBld); MacServices_measurementSRV_init (pMacServices->hMeasurementSRV, hReport, hCmdBld, hEventMbox, pMacServices->hPowerSrv, hTimer); if (powerSrv_init (pMacServices->hPowerSrv, hReport, hEventMbox, hCmdBld, hTimer) != TI_OK) { WLAN_OS_REPORT(("\n.....PowerSRV_init configuration failure \n")); /*return TI_NOK;*/ } } /**************************************************************************************** * MacServices_config * ***************************************************************************************** DESCRIPTION: config the MacServices moduleand sub modules INPUT: hMacServices - handle to the Mac Services object.\n pInitParams - pointer to the init params OUTPUT: RETURN: ****************************************************************************************/ void MacServices_config( TI_HANDLE hMacServices, TTwdInitParams *pInitParams) { MacServices_t *pMacServices = (MacServices_t*)hMacServices; if (powerSrv_config(pMacServices->hPowerSrv,&pInitParams->tPowerSrv) != TI_OK) { WLAN_OS_REPORT(("\n.....PowerSRV_config failure \n")); } MacServices_scanSrv_config (pMacServices, &pInitParams->tScanSrv); } /**************************************************************************************** * MacServices_restart * ***************************************************************************************** DESCRIPTION: restart the MacServices moduleand sub modules upon recovery INPUT: hMacServices - handle to the Mac Services object.\n OUTPUT: RETURN: ****************************************************************************************/ void MacServices_restart (TI_HANDLE hMacServices) { MacServices_t *pMacServices = (MacServices_t*)hMacServices; scanSRV_restart (pMacServices->hScanSRV); measurementSRV_restart (pMacServices->hMeasurementSRV); powerSrv_restart (pMacServices->hPowerSrv); } /**************************************************************************************** * MacServices_registerFailureEventCB * ***************************************************************************************** DESCRIPTION: register the centeral error function from the health monitor to the MacService's sub modules INPUT: hMacServices - handle to the Mac Services object. failureEventCB - pointer ro the call back hFailureEventObj -handle of the Callback Object OUTPUT: RETURN: ****************************************************************************************/ void MacServices_registerFailureEventCB (TI_HANDLE hMacServices, void * failureEventCB, TI_HANDLE hFailureEventObj) { MacServices_t *pMacServices = (MacServices_t*)hMacServices; powerSrvRegisterFailureEventCB (pMacServices->hPowerSrv, failureEventCB, hFailureEventObj); measurementSRVRegisterFailureEventCB (pMacServices->hMeasurementSRV, failureEventCB, hFailureEventObj); scanSRV_registerFailureEventCB (pMacServices->hScanSRV, failureEventCB, hFailureEventObj); } /**************************************************************************************** * MacServices_powerSrv_SetPsMode * **************************************************************************************** DESCRIPTION: This function is a wrapper for the power server's powerSrv_SetPsMode function INPUT: - hMacServices - handle to the Mac services object. - psMode - Power save/Active request - sendNullDataOnExit - - powerSaveCBObject - handle to the Callback function module. - powerSaveCompleteCB - Callback function - for success/faild notification. OUTPUT: RETURN: TI_STATUS - TI_OK / PENDING / TI_NOK. ****************************************************************************************/ TI_STATUS MacServices_powerSrv_SetPsMode (TI_HANDLE hMacServices, E80211PsMode psMode, TI_BOOL sendNullDataOnExit, void * powerSaveCompleteCBObject, TPowerSaveCompleteCb powerSaveCompleteCB, TPowerSaveResponseCb powerSavecmdResponseCB) { MacServices_t *pMacServices = (MacServices_t*)hMacServices; return powerSrv_SetPsMode (pMacServices->hPowerSrv, psMode, sendNullDataOnExit, powerSaveCompleteCBObject, powerSaveCompleteCB, powerSavecmdResponseCB); } /**************************************************************************************** * MacServices_powerSrv_ReservePS * **************************************************************************************** DESCRIPTION: This function is a wrapper for the power server's powerSrv_ReservePS function INPUT: - hMacServices - handle to the Mac services object. - psMode - Power save/Active request - sendNullDataOnExit - - powerSaveCBObject - handle to the Callback function module. - powerSaveCompleteCB - Callback function - for success/faild notification. OUTPUT: RETURN: TI_STATUS - TI_OK / PENDING / TI_NOK. ****************************************************************************************/ TI_STATUS MacServices_powerSrv_ReservePS( TI_HANDLE hMacServices, E80211PsMode psMode, TI_BOOL sendNullDataOnExit, void * powerSaveCBObject, TPowerSaveCompleteCb powerSaveCompleteCB) { MacServices_t *pMacServices = (MacServices_t*)hMacServices; return powerSrv_ReservePS(pMacServices->hPowerSrv,psMode,sendNullDataOnExit,powerSaveCBObject,powerSaveCompleteCB); } /**************************************************************************************** * MacServices_powerSrv_ReleasePS * **************************************************************************************** DESCRIPTION: This function is a wrapper for the power server's powerSrv_ReleasePS function INPUT: - hPowerSrv - handle to the PowerSrv object. - sendNullDataOnExit - - powerSaveCBObject - handle to the Callback function module. - powerSaveCompleteCB - Callback function - for success/faild notification. OUTPUT: RETURN: TI_STATUS - TI_OK / PENDING / TI_NOK. ****************************************************************************************/ TI_STATUS MacServices_powerSrv_ReleasePS( TI_HANDLE hMacServices, TI_BOOL sendNullDataOnExit, void * powerSaveCBObject, TPowerSaveCompleteCb powerSaveCompleteCB) { MacServices_t *pMacServices = (MacServices_t*)hMacServices; return powerSrv_ReleasePS(pMacServices->hPowerSrv,sendNullDataOnExit,powerSaveCBObject,powerSaveCompleteCB); } /**************************************************************************************** * MacServices_powerSrv_getPsStatus * ***************************************************************************************** DESCRIPTION: This function is a wrapper for the power server's powerSrv_getPsStatus function INPUT: - hPowerSrv - handle to the PowerSrv object. OUTPUT: RETURN: TI_BOOL - true if the SM is in PS state - false otherwise ****************************************************************************************/ TI_BOOL MacServices_powerSrv_getPsStatus(TI_HANDLE hMacServices) { MacServices_t *pMacServices = (MacServices_t*)hMacServices; return powerSrv_getPsStatus( pMacServices->hPowerSrv); } /**************************************************************************************** * MacServices_powerSrv_SetRateModulation * ***************************************************************************************** DESCRIPTION: This function is a wrapper for the power server's powerSrv_SetRateModulation function INPUT: - hPowerSrv - handle to the PowerSrv object. - dot11mode_e - The current radio mode (A or G) OUTPUT: RETURN: TI_BOOL - true if the SM is in PS state - false otherwise ****************************************************************************************/ void MacServices_powerSrv_SetRateModulation(TI_HANDLE hMacServices, TI_UINT16 rate) { MacServices_t *pMacServices = (MacServices_t*)hMacServices; powerSrv_SetRateModulation( pMacServices->hPowerSrv, rate); } TI_UINT32 MacServices_powerSrv_GetRateModulation(TI_HANDLE hMacServices) { MacServices_t *pMacServices = (MacServices_t*)hMacServices; return powerSrv_GetRateModulation( pMacServices->hPowerSrv); }
48.761273
167
0.435565
[ "object" ]
697f3948ab6877768a46c500f300c30142be2d67
1,220
h
C
src/layout/element.h
Enhex/GUI
b4fef533dcc23da18362365e1db2c031543bfd11
[ "Apache-2.0" ]
2
2019-01-18T20:48:08.000Z
2020-09-24T08:29:37.000Z
src/layout/element.h
Enhex/GUI
b4fef533dcc23da18362365e1db2c031543bfd11
[ "Apache-2.0" ]
null
null
null
src/layout/element.h
Enhex/GUI
b4fef533dcc23da18362365e1db2c031543bfd11
[ "Apache-2.0" ]
1
2021-12-22T12:12:34.000Z
2021-12-22T12:12:34.000Z
#pragma once #include "../math/math.h" #include "orientation.h" #include <array> #include <memory> #include <vector> namespace layout { template <typename derived_element> struct base; template <typename derived> struct element : rectangle { std::vector<std::unique_ptr<derived>> children; std::unique_ptr<layout::base<derived>> child_layout; // should the element expand to fill free space std::array<bool, layout::orientation::count> expand{ false }; vector2 min_size{ 0,0 }; bool visible = true; void apply_min_size() { X(size) = std::max(X(size), X(min_size)); Y(size) = std::max(Y(size), Y(min_size)); } template <typename T> T& create_layout() { child_layout = std::make_unique<T>(); child_layout->parent = this; return static_cast<T&>(*child_layout.get()); } void set_layout(layout::base<derived>* new_layout) { child_layout.reset(new_layout); child_layout->parent = this; } // executes before the parent's layout virtual void pre_layout() { // automatically apply min size by default apply_min_size(); } // executes after done resizing by the parent's layout virtual void post_layout() { // do nothing by default } }; }
21.034483
63
0.680328
[ "vector" ]
6985512b432e220775ed788ae308a3aa9ffbb751
31,796
c
C
mbed-client-pal/Source/Port/Reference-Impl/OS_Specific/ZephyrOS/Networking/pal_plat_network.c
emob-nordic/mbed-cloud-client-1
7e45d92cf759d62c2d881bd7be318c807d8a47c2
[ "Apache-2.0" ]
null
null
null
mbed-client-pal/Source/Port/Reference-Impl/OS_Specific/ZephyrOS/Networking/pal_plat_network.c
emob-nordic/mbed-cloud-client-1
7e45d92cf759d62c2d881bd7be318c807d8a47c2
[ "Apache-2.0" ]
null
null
null
mbed-client-pal/Source/Port/Reference-Impl/OS_Specific/ZephyrOS/Networking/pal_plat_network.c
emob-nordic/mbed-cloud-client-1
7e45d92cf759d62c2d881bd7be318c807d8a47c2
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2021 Pelion IoT * * 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 "pal.h" #include "pal_plat_network.h" #include "fd_work_poll.h" #include <zephyr.h> #include <zephyr/types.h> #ifdef CONFIG_NET_SOCKETS_POSIX_NAMES #include <net/socket.h> #else #include <sys/socket.h> #include <sys/types.h> #include <netdb.h> #include <poll.h> #endif #include <unistd.h> #if 1 #define TRACE_GROUP "PAL" //#include <stdio.h> //#define DEBUG_DEBUG(...) { printf(__VA_ARGS__); printf("\r\n"); } //#define DEBUG_ERROR(...) { printf(__VA_ARGS__); printf("\r\n"); } #define DEBUG_DEBUG PAL_LOG_DBG #define DEBUG_ERROR PAL_LOG_ERR #else #include <logging/log.h> #ifndef CONFIG_PELION_PAL_PLAT_NETWORK_LOG_LEVEL #define CONFIG_PELION_PAL_PLAT_NETWORK_LOG_LEVEL 2 /* Warning */ #endif LOG_MODULE_REGISTER(pal_plat_network, CONFIG_PELION_PAL_PLAT_NETWORK_LOG_LEVEL); #define DEBUG_DEBUG LOG_DBG #define DEBUG_ERROR LOG_ERR #endif #define PAL_SOCKET_FREE (-1) typedef struct { int fd; struct pollfd pollin; struct pollfd pollout; fd_work_poll_t workin; fd_work_poll_t workout; palAsyncSocketCallback_t callback; void* callbackArgument; } pal_socket_t; static pal_socket_t pal_sockets[PAL_SOCKET_MAX] = { 0 }; /******************************************************************************/ /* Required */ /******************************************************************************/ static void pal_workin_callback(fd_work_poll_t* input) { DEBUG_DEBUG("pal_workin_callback"); /** * Get the encapsulating container which contains variables carried across * work queue invocations. */ pal_socket_t* pointer = CONTAINER_OF(input, pal_socket_t, workin); /* invoke callback function with argument if one has been defined * and socket hasn't been closed in the mean time. */ if ((pointer->fd != PAL_SOCKET_FREE) && (pointer->callback)) { pointer->callback(pointer->callbackArgument); } } static void pal_workout_callback(fd_work_poll_t* input) { DEBUG_DEBUG("pal_workout_callback"); /** * Get the encapsulating container which contains variables carried across * work queue invocations. */ pal_socket_t* pointer = CONTAINER_OF(input, pal_socket_t, workout); /* invoke callback function with argument if one has been defined * and socket hasn't been closed in the mean time. */ if ((pointer->fd != PAL_SOCKET_FREE) && (pointer->callback)) { pointer->callback(pointer->callbackArgument); } } palStatus_t pal_plat_socketsInit(void* context) { DEBUG_DEBUG("pal_plat_socketsInit"); /* initialize pre-allocated socket structure */ for (size_t index = 0; index < PAL_SOCKET_MAX; index++) { pal_sockets[index].fd = PAL_SOCKET_FREE; pal_sockets[index].pollin.events = POLLIN; pal_sockets[index].pollout.events = POLLOUT; fd_work_poll_init(&pal_sockets[index].workin, pal_workin_callback); fd_work_poll_init(&pal_sockets[index].workout, pal_workout_callback); } return PAL_SUCCESS; } palStatus_t pal_plat_asynchronousSocket(palSocketDomain_t domain, palSocketType_t type, bool nonBlockingSocket, uint32_t interfaceNum, palAsyncSocketCallback_t callback, void* callbackArgument , palSocket_t* handle) { DEBUG_DEBUG("pal_plat_asynchronousSocket"); palStatus_t result = PAL_ERR_INVALID_ARGUMENT; if (handle) { result = PAL_ERR_SOCKET_ALLOCATION_FAILED; /* switch from PAL types to Zephyr types */ switch (domain) { case PAL_AF_INET: domain = AF_INET; break; case PAL_AF_INET6: domain = AF_INET6; break; default: domain = AF_UNSPEC; break; } int proto = 0; switch (type) { case PAL_SOCK_DGRAM: type = SOCK_DGRAM; proto = IPPROTO_UDP; break; case PAL_SOCK_STREAM: case PAL_SOCK_STREAM_SERVER: type = SOCK_STREAM; proto = IPPROTO_TCP; break; default: /* should not happen */ assert(false); break; } /* find valid index in pre-allocated socket structs */ int current = PAL_SOCKET_FREE; for (size_t index = 0; index < PAL_SOCKET_MAX; index++) { if (pal_sockets[index].fd == PAL_SOCKET_FREE) { current = index; break; } } DEBUG_DEBUG("current: %d", current); if (current != PAL_SOCKET_FREE) { /* create socket */ int fd = socket(domain, type, proto); DEBUG_DEBUG("socket: %d", fd); if (fd != -1) { /* set flags */ if (nonBlockingSocket) { int flags = fcntl(fd, F_GETFL, 0); fcntl(fd, F_SETFL, flags | O_NONBLOCK); } /* store arguments in internal data structure */ pal_socket_t* pointer = &pal_sockets[current]; pointer->fd = fd; pointer->pollin.fd = fd; pointer->pollout.fd = fd; pointer->callback = callback; pointer->callbackArgument = callbackArgument; /* use pointer to structure as PAL socket handle */ *handle = (palSocket_t) pointer; result = PAL_SUCCESS; } } } return result; } palStatus_t pal_plat_connect(palSocket_t handle, const palSocketAddress_t* palAddress, palSocketLength_t addressLen) { DEBUG_DEBUG("pal_plat_connect"); palStatus_t result = PAL_ERR_INVALID_ARGUMENT; if (palAddress) { /* convert PAL address to Zephyr address */ #if PAL_SUPPORT_IP_V4 struct sockaddr_in address = { 0 }; socklen_t addrlen = sizeof(struct sockaddr_in); address.sin_family = AF_INET; pal_getSockAddrPort(palAddress, &address.sin_port); pal_getSockAddrIPV4Addr(palAddress, address.sin_addr.s4_addr); /* FIXME: pal_getSockAddrPort is returning wrong endian, use htons workaround */ address.sin_port = htons(address.sin_port); #else struct sockaddr_in6 address = { 0 }; socklen_t addrlen = sizeof(struct sockaddr_in6); address.sin6_family = AF_INET6; pal_getSockAddrPort(palAddress, &address.sin6_port); pal_getSockAddrIPV6Addr(palAddress, address.sin6_addr.s6_addr); /* FIXME: pal_getSockAddrPort is returning wrong endian, use htons workaround */ address.sin6_port = htons(address.sin6_port); #endif /* get filedescriptor from PAL socket handle */ pal_socket_t* pointer = (pal_socket_t*) handle; /* connect to remote server, this call appears to be syncrhonous on Zephyr? */ int retval = connect(pointer->fd, (struct sockaddr*) &address, addrlen); if(retval == 0) { /* provide callback for when data can be read */ fd_work_poll_submit(&pointer->workin, &pointer->pollin, 1, K_FOREVER); result = PAL_SUCCESS; } else { /* only error codes used by PDMC*/ switch (errno) { case EINPROGRESS: /* As per man connect says, poll for writability for non-blocking socket */ fd_work_poll_submit(&pointer->workout, &pointer->pollout, 1, K_FOREVER); result = PAL_ERR_SOCKET_IN_PROGRES; break; case EWOULDBLOCK: result = PAL_ERR_SOCKET_WOULD_BLOCK; break; case EISCONN: case EALREADY: result = PAL_ERR_SOCKET_ALREADY_CONNECTED; break; default: result = PAL_ERR_SOCKET_GENERIC; break; } } } return result; } palStatus_t pal_plat_isNonBlocking(palSocket_t handle, bool* isNonBlocking) { DEBUG_DEBUG("pal_plat_isNonBlocking"); palStatus_t result = PAL_ERR_INVALID_ARGUMENT; if (handle && isNonBlocking) { /* get PAL socket data structure */ pal_socket_t* pointer = (pal_socket_t*) handle; /* get the socket's configuration flags */ int flags = fcntl(pointer->fd, F_GETFL, 0); if (flags & O_NONBLOCK) { *isNonBlocking = true; } else { *isNonBlocking = false; } result = PAL_SUCCESS; } return result; } palStatus_t pal_plat_send(palSocket_t handle, const void* buf, size_t len, size_t* sentDataSize) { DEBUG_DEBUG("pal_plat_send"); palStatus_t result = PAL_ERR_INVALID_ARGUMENT; if (handle && buf && sentDataSize) { /* get PAL socket data structure */ pal_socket_t* pointer = (pal_socket_t*) handle; /* send data */ ssize_t retval = send(pointer->fd, buf, len, 0); /* check return value */ if (retval != -1) { /* provide callback for when more data can be sent */ fd_work_poll_submit(&pointer->workout, &pointer->pollout, 1, K_FOREVER); /* successful send, report number of bytes sent and set return status */ *sentDataSize = retval; result = PAL_SUCCESS; } else { /* data not sent, set return status, note caller only looks for * ENOBUFS, ENOMEM, and EWOULDBLOCK. */ switch (errno) { case ENOBUFS: case ENOMEM: result = PAL_ERR_NO_MEMORY; break; case EWOULDBLOCK: /* provide callback for when more data can be sent */ fd_work_poll_submit(&pointer->workout, &pointer->pollout, 1, K_FOREVER); result = PAL_ERR_SOCKET_WOULD_BLOCK; break; default: result = PAL_ERR_SOCKET_GENERIC; break; } } } return result; } palStatus_t pal_plat_recv(palSocket_t handle, void* buf, size_t len, size_t* recievedDataSize) { DEBUG_DEBUG("pal_plat_recv"); palStatus_t result = PAL_ERR_INVALID_ARGUMENT; if (handle && buf && recievedDataSize) { /* get PAL socket data structure */ pal_socket_t* pointer = (pal_socket_t*) handle; /* read data from network stack */ ssize_t retval = recv(pointer->fd, buf, len, 0); /* positive return value indicate number of bytes received */ if (retval > 0) { /* invoke callback when more data is available to read */ fd_work_poll_submit(&pointer->workin, &pointer->pollin, 1, K_FOREVER); /* successful receive, set number of bytes received and return value */ *recievedDataSize = retval; result = PAL_SUCCESS; /* for stream connections, zero means end-of-file and the connection has been closed */ } else if (retval == 0) { result = PAL_ERR_SOCKET_CONNECTION_CLOSED; /* negative return value indicates an error */ } else { /* note caller only uses EWOULDBLOCK */ switch (errno) { case EWOULDBLOCK: /* invoke callback when more data is available to read */ fd_work_poll_submit(&pointer->workin, &pointer->pollin, 1, K_FOREVER); result = PAL_ERR_SOCKET_WOULD_BLOCK; break; default: result = PAL_ERR_SOCKET_GENERIC; break; } } } return result; } palStatus_t pal_plat_bind(palSocket_t handle, palSocketAddress_t* palAddress, palSocketLength_t addressLength) { DEBUG_DEBUG("pal_plat_bind"); palStatus_t result = PAL_ERR_INVALID_ARGUMENT; if (handle && palAddress) { /* convert PAL address to Zephyr address */ #if PAL_SUPPORT_IP_V4 struct sockaddr_in address = { 0 }; socklen_t addrlen = sizeof(struct sockaddr_in); address.sin_family = AF_INET; pal_getSockAddrPort(palAddress, &address.sin_port); pal_getSockAddrIPV4Addr(palAddress, address.sin_addr.s4_addr); /* FIXME: pal_getSockAddrPort is returning wrong endian, use htons workaround */ address.sin_port = htons(address.sin_port); #else struct sockaddr_in6 address = { 0 }; socklen_t addrlen = sizeof(struct sockaddr_in6); address.sin6_family = AF_INET6; pal_getSockAddrPort(palAddress, &address.sin6_port); pal_getSockAddrIPV6Addr(palAddress, address.sin6_addr.s6_addr); /* FIXME: pal_getSockAddrPort is returning wrong endian, use htons workaround */ address.sin6_port = htons(address.sin6_port); #endif /* get PAL socket data structure */ pal_socket_t* pointer = (pal_socket_t*) handle; int retval = bind(pointer->fd, (struct sockaddr*) &address, addrlen); if (retval == 0) { /* provide callback for when data can be read */ fd_work_poll_submit(&pointer->workin, &pointer->pollin, 1, K_FOREVER); result = PAL_SUCCESS; } else { /* return value not used by caller, return generic error */ switch (errno) { default: result = PAL_ERR_SOCKET_GENERIC; break; } } } return result; } palStatus_t pal_plat_sendTo(palSocket_t handle, const void* buffer, size_t length, const palSocketAddress_t* palAddress, palSocketLength_t toLength, size_t* bytesSent) { DEBUG_DEBUG("pal_plat_sendTo"); palStatus_t result = PAL_ERR_INVALID_ARGUMENT; if (handle && buffer && palAddress && bytesSent) { /* convert PAL address to Zephyr address */ #if PAL_SUPPORT_IP_V4 struct sockaddr_in address = { 0 }; socklen_t addrlen = sizeof(struct sockaddr_in); address.sin_family = AF_INET; pal_getSockAddrPort(palAddress, &address.sin_port); pal_getSockAddrIPV4Addr(palAddress, address.sin_addr.s4_addr); /* FIXME: pal_getSockAddrPort is returning wrong endian, use htons workaround */ address.sin_port = htons(address.sin_port); #else struct sockaddr_in6 address = { 0 }; socklen_t addrlen = sizeof(struct sockaddr_in6); address.sin6_family = AF_INET6; pal_getSockAddrPort(palAddress, &address.sin6_port); pal_getSockAddrIPV6Addr(palAddress, address.sin6_addr.s6_addr); /* FIXME: pal_getSockAddrPort is returning wrong endian, use htons workaround */ address.sin6_port = htons(address.sin6_port); #endif pal_socket_t* pointer = (pal_socket_t*) handle; ssize_t retval = sendto(pointer->fd, buffer, length, 0, (struct sockaddr*) &address, addrlen); if (retval != -1) { /* provide callback for when more data can be sent */ fd_work_poll_submit(&pointer->workout, &pointer->pollout, 1, K_FOREVER); /* successful send, report number of bytes sent and set return status */ *bytesSent = retval; result = PAL_SUCCESS; } else { /* data not sent, set return status, note caller only looks for * ENOBUFS, ENOMEM, and EWOULDBLOCK. */ switch (errno) { case ENOBUFS: case ENOMEM: result = PAL_ERR_NO_MEMORY; break; case EWOULDBLOCK: /* provide callback for when more data can be sent */ fd_work_poll_submit(&pointer->workout, &pointer->pollout, 1, K_FOREVER); result = PAL_ERR_SOCKET_WOULD_BLOCK; break; default: result = PAL_ERR_SOCKET_GENERIC; break; } } } return result; } palStatus_t pal_plat_receiveFrom(palSocket_t handle, void* buffer, size_t length, palSocketAddress_t* palAddress, palSocketLength_t* fromLength, size_t* bytesReceived) { DEBUG_DEBUG("pal_plat_receiveFrom"); palStatus_t result = PAL_ERR_INVALID_ARGUMENT; if (handle && buffer && palAddress && fromLength && bytesReceived) { struct sockaddr address = { 0 }; socklen_t addrlen = sizeof(struct sockaddr); pal_socket_t* pointer = (pal_socket_t*) handle; ssize_t retval = recvfrom(pointer->fd, buffer, length, 0, &address, &addrlen); if (retval != -1) { /* convert Zephyr address to PAL address */ #if PAL_SUPPORT_IP_V4 /* FIXME: pal_getSockAddrPort is returning wrong endian, use htons workaround */ net_sin(&address)->sin_port = htons(net_sin(&address)->sin_port); pal_setSockAddrPort(palAddress, net_sin(&address)->sin_port); pal_setSockAddrIPV4Addr(palAddress, net_sin(&address)->sin_addr.s4_addr); #else /* FIXME: pal_getSockAddrPort is returning wrong endian, use htons workaround */ net_sin6(&address)->sin6_port = htons(net_sin6(&address)->sin6_port); pal_setSockAddrPort(palAddress, net_sin6(&address)->sin6_port); pal_setSockAddrIPV6Addr(palAddress, net_sin6(&address)->sin6_addr.s6_addr); #endif /* invoke callback when more data is available to read */ fd_work_poll_submit(&pointer->workin, &pointer->pollin, 1, K_FOREVER); /* successful receive, report number of bytes and set return status */ *bytesReceived = retval; result = PAL_SUCCESS; } else { /* note caller only uses EWOULDBLOCK */ switch (errno) { case EWOULDBLOCK: /* invoke callback when more data is available to read */ fd_work_poll_submit(&pointer->workin, &pointer->pollin, 1, K_FOREVER); result = PAL_ERR_SOCKET_WOULD_BLOCK; break; default: result = PAL_ERR_SOCKET_GENERIC; break; } } } return result; } palStatus_t pal_plat_close(palSocket_t* handle) { DEBUG_DEBUG("pal_plat_close"); palStatus_t result = PAL_ERR_INVALID_ARGUMENT; if (handle) { /* get PAL socket data structure */ pal_socket_t* pointer = (pal_socket_t*) *handle; /* mark internal socket structure as free before closing socket to * suppress any late callbacks. */ int fd = pointer->fd; pointer->fd = PAL_SOCKET_FREE; /* cancel any pending work */ fd_work_poll_cancel(&pointer->workin); fd_work_poll_cancel(&pointer->workout); /* close socket using local file descriptor copy */ int retval = close(fd); DEBUG_DEBUG("close socket: %d %d", fd, retval); /* negative return value indicates error */ if (retval == 0) { result = PAL_SUCCESS; } else { /* caller doesn't look at return value, return generic error */ switch (errno) { default: result = PAL_ERR_SOCKET_GENERIC; break; } } } return result; } /******************************************************************************/ /* DNS */ /******************************************************************************/ #if (PAL_DNS_API_VERSION == 0) palStatus_t pal_plat_getAddressInfo(const char* hostname, palSocketAddress_t* address, palSocketLength_t* addressLength) { DEBUG_DEBUG("pal_plat_getAddressInfo"); // addressLength not used in caller function palStatus_t result = PAL_ERR_INVALID_ARGUMENT; if (hostname && address && addressLength) { struct addrinfo *info = NULL; struct addrinfo hints = { 0 }; #if (PAL_SUPPORT_IP_V4 || PAL_SUPPORT_NAT64) hints.ai_family = AF_INET; #else // PAL_SUPPORT_IP_V6 hints.ai_family = AF_INET6; #endif /* use synchronous DNS lookup */ int retval = getaddrinfo(hostname, NULL, &hints, &info); if (retval == 0) { /* convert Zephyr address to PAL address */ if (info->ai_family == AF_INET) { #if !PAL_SUPPORT_IP_V4 && PAL_SUPPORT_NAT64 /* got IPv4 address on IPv6 network, convert to NAT64 address */ result = pal_setSockAddrNAT64Addr(address, net_sin(info->ai_addr)->sin_addr.s4_addr); #else result = pal_setSockAddrIPV4Addr(address, net_sin(info->ai_addr)->sin_addr.s4_addr); #endif } else if (info->ai_family == AF_INET6) { result = pal_setSockAddrIPV6Addr(address, net_sin6(info->ai_addr)->sin6_addr.s6_addr); } else { DEBUG_ERROR("Invalid IP address family %d", info->ai_family); assert(0); } /* release allocated resources */ freeaddrinfo(info); } else { result = PAL_ERR_SOCKET_DNS_ERROR; } } return result; } #elif (PAL_DNS_API_VERSION == 3) #if (PAL_SUPPORT_IP_V4 || PAL_SUPPORT_NAT64) #define PAL_DNS_DEFAULT_QUERY_TYPE DNS_QUERY_TYPE_A #else #define PAL_DNS_DEFAULT_QUERY_TYPE DNS_QUERY_TYPE_AAAA #endif static size_t pal_dns_counter = 0; // number of records in cache static uint16_t pal_dns_id = 0; // handle for cancelling request in progress static palSocketAddress_t pal_dns_cache[PAL_DNS_CACHE_MAX] = { 0 }; // cache /** * @brief Callback function for Zephyr's DNS Resolve. * * @param[in] status Ongoing request's status. * @param info DNS information. * @param user_data User provided context. */ static void pal_plat_dns_resolve_cb(enum dns_resolve_status status, struct dns_addrinfo *info, void *user_data) { DEBUG_DEBUG("pal_plat_dns_resolve_cb: %d", status); /** * Handle DNS record. */ if ((status == DNS_EAI_INPROGRESS) && (pal_dns_counter < PAL_DNS_CACHE_MAX) && info) { DEBUG_DEBUG("PAL DNS in progress"); palStatus_t result = PAL_ERR_SOCKET_DNS_ERROR; /* get pointer to next slot in cache */ palSocketAddress_t* address = &pal_dns_cache[pal_dns_counter]; /* convert Zephyr address to PAL address */ if (info->ai_family == AF_INET) { #if !PAL_SUPPORT_IP_V4 && PAL_SUPPORT_NAT64 /* got IPv4 address on IPv6 network, convert to NAT64 address */ result = pal_setSockAddrNAT64Addr(address, net_sin(&info->ai_addr)->sin_addr.s4_addr); #else result = pal_setSockAddrIPV4Addr(address, net_sin(&info->ai_addr)->sin_addr.s4_addr); #endif } else if (info->ai_family == AF_INET6) { result = pal_setSockAddrIPV6Addr(address, net_sin6(&info->ai_addr)->sin6_addr.s6_addr); } else { DEBUG_ERROR("Invalid IP address family %d", info->ai_family); assert(0); } /* increment number of records in cache */ if (result == PAL_SUCCESS) { pal_dns_counter++; } /** * DNS lookup complete or failed. */ } else { DEBUG_DEBUG("PAL DNS done"); if (user_data) { palStatus_t result = PAL_ERR_SOCKET_DNS_ERROR; /* return success if at least one record has been received*/ if (pal_dns_counter) { result = PAL_SUCCESS; } /* access user provided data */ pal_asyncAddressInfo_t* pal_info = (pal_asyncAddressInfo_t*) user_data; /* invoke callback function with result */ pal_info->callback(pal_info->hostname, (palAddressInfo_t*) pal_dns_cache, result, pal_info->callbackArgument); } } } /*! \brief This function translates a hostname to a `palSocketAddress_t` that can be used with PAL sockets. * @param[in] info address of `pal_asyncAddressInfo_t`. */ palStatus_t pal_plat_getAddressInfoAsync(pal_asyncAddressInfo_t* info) { DEBUG_DEBUG("pal_plat_getAddressInfoAsync"); palStatus_t result = PAL_ERR_SOCKET_DNS_ERROR; if (info) { DEBUG_DEBUG("hostname: %s", info->hostname); /* reset counter */ pal_dns_counter = 0; /* lookup address using Zephyr's DNS Resolve */ int retval = dns_get_addr_info(info->hostname, // const char *query, PAL_DNS_DEFAULT_QUERY_TYPE, // enum dns_query_type type, &pal_dns_id, // uint16_t *dns_id, pal_plat_dns_resolve_cb, // dns_resolve_cb_tcb, (void*) info, // void *user_data, PAL_DNS_TIMEOUT_MS); // int32_t timeout if (retval == 0) { /* return handle for cancelling requests */ *info->queryHandle = pal_dns_id; result = PAL_SUCCESS; } } return result; } /*! \brief This function puts the palSocketAddress_t from the given index in palAddressInfo_t to the given addr * @param[in] addrInfo The palAddressInfo_t which (if any) palSocketAddress_t is get. * @param[in] index Index of the address in addrInfo to fetch. * @param[out] addr palSocketAddress_t is put to this instance is any if found. * \return PAL_SUCCESS (0) in case of success, or a specific negative error code in case of failure. */ palStatus_t pal_plat_getDNSAddress(palAddressInfo_t *addrInfo, uint16_t index, palSocketAddress_t *addr) { DEBUG_DEBUG("pal_plat_getDNSAddress"); palStatus_t result = PAL_ERR_SOCKET_DNS_ERROR; if (addr && (index < PAL_DNS_CACHE_MAX)) { /* copy record from cache */ memcpy(addr, &pal_dns_cache[index], sizeof(palSocketAddress_t)); result = PAL_SUCCESS; } return result; } /*! \brief Return the number of dns addresses in the given addrInfo * @param[in] addrInfo The palAddressInfo_t to be used for countung dns addresses. * \return Number of DNS addresses in the given addrInfo. */ int pal_plat_getDNSCount(palAddressInfo_t *addrInfo) { DEBUG_DEBUG("pal_plat_getDNSCount"); return pal_dns_counter; } /*! \brief This function is cancelation for `pal_plat_getAddressInfoAsync()`. * @param[in] queryHandle ID of ongoing DNS query. */ palStatus_t pal_plat_cancelAddressInfoAsync(palDNSQuery_t queryHandle) { DEBUG_DEBUG("pal_plat_cancelAddressInfoAsync"); /* cancel request */ int result = dns_cancel_addr_info(queryHandle); return (result == 0) ? PAL_SUCCESS : PAL_ERR_SOCKET_DNS_ERROR; } /*! \brief This function free's the thread used in pal_getAddressInfoAsync */ palStatus_t pal_plat_free_addressinfoAsync(palDNSQuery_t queryHandle) { DEBUG_DEBUG("pal_plat_free_addressinfoAsync"); /* reset counter */ pal_dns_counter = 0; return PAL_SUCCESS; } /*! \brief Free the given addrInfo. * @param[in] addrInfo OS specific palAddressInfo_t which holds dns addresses. */ void pal_plat_freeAddrInfo(palAddressInfo_t* addrInfo) { DEBUG_DEBUG("pal_plat_freeAddrInfo"); /* unused */ } #else #error PAL_DNS_API_VERSION must be either 0 or 3 #endif /******************************************************************************/ /* Feature dependant */ /******************************************************************************/ // for blocking sockets palStatus_t pal_plat_setSocketOptions(palSocket_t handle, int optionName, const void* optionValue, palSocketLength_t optionLength) { DEBUG_DEBUG("pal_plat_setSocketOptions"); return PAL_ERR_SOCKET_OPTION_NOT_SUPPORTED; } // for pause/resume low power feature palStatus_t pal_plat_registerNetworkInterface(void* networkInterfaceContext, uint32_t* interfaceIndex) { DEBUG_DEBUG("pal_plat_registerNetworkInterface"); return PAL_ERR_SOCKET_OPTION_NOT_SUPPORTED; } palStatus_t pal_plat_unregisterNetworkInterface(uint32_t interfaceIndex) { DEBUG_DEBUG("pal_plat_unregisterNetworkInterface"); return PAL_ERR_SOCKET_OPTION_NOT_SUPPORTED; } // for cleanup palStatus_t pal_plat_socketsTerminate(void* context) { DEBUG_DEBUG("pal_plat_socketsTerminate"); return PAL_ERR_SOCKET_OPTION_NOT_SUPPORTED; } // for factory provisioning over network and mesh update palStatus_t pal_plat_listen(palSocket_t handle, int backlog) { DEBUG_DEBUG("pal_plat_listen"); return PAL_ERR_SOCKET_OPTION_NOT_SUPPORTED; } palStatus_t pal_plat_accept(palSocket_t handle, palSocketAddress_t* address, palSocketLength_t* addressLen, palSocket_t* acceptedSocket, palAsyncSocketCallback_t callback, void* callbackArgument) { DEBUG_DEBUG("pal_plat_accept"); return PAL_ERR_SOCKET_OPTION_NOT_SUPPORTED; } // for mesh update palStatus_t pal_plat_setSocketOptionsWithLevel(palSocket_t handle, palSocketOptionLevelName_t optionLevel, int optionName, const void* optionValue, palSocketLength_t optionLength) { DEBUG_DEBUG("pal_plat_setSocketOptionsWithLevel"); return PAL_ERR_SOCKET_OPTION_NOT_SUPPORTED; } uint8_t pal_plat_getRttEstimate() { DEBUG_DEBUG("pal_plat_getRttEstimate"); return PAL_DEFAULT_RTT_ESTIMATE; } uint16_t pal_plat_getStaggerEstimate(uint16_t data_amount) { DEBUG_DEBUG("pal_plat_getStaggerEstimate"); return PAL_DEFAULT_STAGGER_ESTIMATE; } /******************************************************************************/ /* Network Interface */ /******************************************************************************/ #if !(defined(PAL_USE_APPLICATION_NETWORK_CALLBACK) && \ (PAL_USE_APPLICATION_NETWORK_CALLBACK == 1)) palStatus_t pal_plat_setConnectionStatusCallback(uint32_t interfaceIndex, connectionStatusCallback callback, void *client_arg) { DEBUG_DEBUG("pal_plat_setConnectionStatusCallback"); return PAL_ERR_SOCKET_OPTION_NOT_SUPPORTED; } #endif /******************************************************************************/ /* Unused */ /******************************************************************************/ palStatus_t pal_plat_getNumberOfNetInterfaces(uint32_t* numInterfaces) { DEBUG_DEBUG("pal_plat_getNumberOfNetInterfaces"); return PAL_ERR_SOCKET_OPTION_NOT_SUPPORTED; } palStatus_t pal_plat_getNetInterfaceInfo(uint32_t interfaceNum, palNetInterfaceInfo_t* interfaceInfo) { DEBUG_DEBUG("pal_plat_getNetInterfaceInfo"); return PAL_ERR_SOCKET_OPTION_NOT_SUPPORTED; }
31.142018
215
0.609762
[ "mesh" ]
6986d95591550cecd69c688c6f67c313f9d73cfe
10,778
h
C
src/utils/objects.h
karwler/Thrones
75a8dd5abb7998c4ae86d34f470f532b387a35df
[ "WTFPL" ]
null
null
null
src/utils/objects.h
karwler/Thrones
75a8dd5abb7998c4ae86d34f470f532b387a35df
[ "WTFPL" ]
null
null
null
src/utils/objects.h
karwler/Thrones
75a8dd5abb7998c4ae86d34f470f532b387a35df
[ "WTFPL" ]
null
null
null
#pragma once #include "settings.h" #include "utils.h" #include "prog/types.h" #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> // vertex data that's shared between objects class Mesh { public: static constexpr GLenum elemType = GL_UNSIGNED_SHORT; private: GLuint vao = 0, vbo = 0, ebo = 0; uint16 ecnt = 0; // number of elements uint8 shape = 0; // GLenum for how to handle elements public: Mesh() = default; Mesh(const vector<Vertex>& vertices, const vector<GLushort>& elements, uint8 type = GL_TRIANGLES); void free(); GLuint getVao() const; uint16 getEcnt() const; uint8 getShape() const; }; inline GLuint Mesh::getVao() const { return vao; } inline uint16 Mesh::getEcnt() const { return ecnt; } inline uint8 Mesh::getShape() const { return shape; } // 3D object with triangles class Object : public Interactable { public: const Mesh* mesh; const Material* matl; GLuint tex; bool show; bool rigid; private: vec3 pos, scl; quat rot; mat4 trans; mat3 normat; public: Object() = default; Object(const Object&) = default; Object(Object&&) = default; Object(const vec3& position, const vec3& rotation = vec3(0.f), const vec3& scale = vec3(1.f), const Mesh* model = nullptr, const Material* material = nullptr, GLuint texture = 0, bool visible = true, bool interactive = false); ~Object() override = default; Object& operator=(const Object&) = default; Object& operator=(Object&&) = default; #ifndef OPENGLES virtual void drawDepth() const; virtual void drawTopDepth() const {} #endif void draw() const; const vec3& getPos() const; void setPos(const vec3& vec); const quat& getRot() const; void setRot(const quat& qut); const vec3& getScl() const; void setScl(const vec3& vec); protected: const mat4& getTrans() const; const mat3& getNormat() const; static void setTransform(mat4& model, const vec3& pos, const quat& rot, const vec3& scl); static void setTransform(mat4& model, mat3& norm, const vec3& pos, const quat& rot, const vec3& scl); }; inline const vec3& Object::getPos() const { return pos; } inline void Object::setPos(const vec3& vec) { setTransform(trans, pos = vec, rot, scl); } inline const quat& Object::getRot() const { return rot; } inline void Object::setRot(const quat& qut) { setTransform(trans, normat, pos, rot = qut, scl); } inline const vec3& Object::getScl() const { return scl; } inline void Object::setScl(const vec3& vec) { setTransform(trans, normat, pos, rot, scl = vec); } inline const mat4& Object::getTrans() const { return trans; } inline const mat3& Object::getNormat() const { return normat; } inline void Object::setTransform(mat4& model, const vec3& pos, const quat& rot, const vec3& scl) { model = glm::scale(glm::translate(mat4(1.f), pos) * glm::mat4_cast(rot), scl); } // square object on a single plane class BoardObject : public Object { public: enum Emission : uint8 { EMI_NONE = 0, EMI_DIM = 1, EMI_SEL = 2, EMI_HIGH = 4 }; float alphaFactor; GCall hgcall = nullptr; GCall ulcall = nullptr; GCall urcall = nullptr; static constexpr float noEngageAlpha = 0.6f; protected: static constexpr float topYpos = 0.1f; static constexpr vec4 moveColorFactor = { 1.f, 1.f, 1.f, 9.9f }; private: float diffuseFactor = 1.f; Emission emission = EMI_NONE; protected: bool leftDrag; public: BoardObject() = default; BoardObject(const BoardObject&) = default; BoardObject(BoardObject&&) = default; BoardObject(const vec3& position, float rotation, float size, const Mesh* model, const Material* material, GLuint texture, bool visible, float alpha); ~BoardObject() override = default; BoardObject& operator=(const BoardObject&) = default; BoardObject& operator=(BoardObject&&) = default; void draw() const; void onDrag(const ivec2& mPos, const ivec2& mMov) override; void onKeyDown(const SDL_KeyboardEvent& key) override; void onKeyUp(const SDL_KeyboardEvent& key) override; void onJButtonDown(uint8 but) override; void onJButtonUp(uint8 but) override; void onJHatDown(uint8 hat, uint8 val) override; void onJHatUp(uint8 hat, uint8 val) override; void onJAxisDown(uint8 axis, bool positive) override; void onJAxisUp(uint8 axis, bool positive) override; void onGButtonDown(SDL_GameControllerButton but) override; void onGButtonUp(SDL_GameControllerButton but) override; void onGAxisDown(SDL_GameControllerAxis axis, bool positive) override; void onGAxisUp(SDL_GameControllerAxis axis, bool positive) override; void onNavSelect(Direction dir) override; void startKeyDrag(uint8 mBut); Emission getEmission() const; virtual void setEmission(Emission emi); protected: #ifndef OPENGLES void drawTopMeshDepth(float ypos) const; #endif void drawTopMesh(float ypos, const Mesh* tmesh, const Material& tmatl, GLuint ttexture) const; private: void onInputDown(Binding::Type bind); void onInputUp(Binding::Type bind); }; inline BoardObject::Emission BoardObject::getEmission() const { return emission; } // piece of terrain class Tile : public BoardObject { public: enum class Interact : uint8 { ignore, recognize, interact }; private: TileType type = TileType::empty; bool breached = false; // only for fortress public: Tile() = default; Tile(const Tile&) = default; Tile(Tile&&) = default; Tile(const vec3& position, float size, bool visible); ~Tile() final = default; Tile& operator=(const Tile&) = default; Tile& operator=(Tile&&) = default; #ifndef OPENGLES void drawDepth() const final; void drawTopDepth() const final; #endif void drawTop() const final; void onHold(const ivec2& mPos, uint8 mBut) final; void onUndrag(uint8 mBut) final; void onHover() final; void onUnhover() final; void onCancelCapture() final; TileType getType() const; void setType(TileType newType); bool isBreachedFortress() const; bool isUnbreachedFortress() const; bool getBreached() const; void setBreached(bool yes); void setInteractivity(Interact lvl, bool dim = false); void setEmission(Emission emi) final; private: const char* pickMesh(); }; inline const char* Tile::pickMesh() { return type != TileType::fortress ? "tile" : breached ? "breached" : "fortress"; } inline TileType Tile::getType() const { return type; } inline bool Tile::isBreachedFortress() const { return type == TileType::fortress && breached; } inline bool Tile::isUnbreachedFortress() const { return type == TileType::fortress && !breached; } inline bool Tile::getBreached() const { return breached; } // tile container class TileCol { private: uptr<Tile[]> tl; uint16 home = 0; // number of home tiles uint16 extra = 0; // home + board width uint16 size = 0; // all tiles public: void update(const Config& conf); uint16 getHome() const; uint16 getExtra() const; uint16 getSize() const; Tile& operator[](uint16 i); const Tile& operator[](uint16 i) const; Tile* begin(); const Tile* begin() const; Tile* end(); const Tile* end() const; Tile* ene(pdift i = 0); const Tile* ene(pdift i = 0) const; Tile* mid(pdift i = 0); const Tile* mid(pdift i = 0) const; Tile* own(pdift i = 0); const Tile* own(pdift i = 0) const; }; inline uint16 TileCol::getHome() const { return home; } inline uint16 TileCol::getExtra() const { return extra; } inline uint16 TileCol::getSize() const { return size; } inline Tile& TileCol::operator[](uint16 i) { return tl[i]; } inline const Tile& TileCol::operator[](uint16 i) const { return tl[i]; } inline Tile* TileCol::begin() { return tl.get(); } inline const Tile* TileCol::begin() const { return tl.get(); } inline Tile* TileCol::end() { return &tl[size]; } inline const Tile* TileCol::end() const { return &tl[size]; } inline Tile* TileCol::ene(pdift i) { return &tl[i]; } inline const Tile* TileCol::ene(pdift i) const { return &tl[i]; } inline Tile* TileCol::mid(pdift i) { return &tl[home+i]; } inline const Tile* TileCol::mid(pdift i) const { return &tl[home+i]; } inline Tile* TileCol::own(pdift i) { return &tl[extra+i]; } inline const Tile* TileCol::own(pdift i) const { return &tl[extra+i]; } // player on tiles class Piece : public BoardObject { public: uint16 lastFortress = UINT16_MAX; // index of last visited fortress (only relevant to throne) private: PieceType type; public: Piece() = default; Piece(const Piece&) = default; Piece(Piece&&) = default; Piece(const vec3& position, float rotation, float size, const Material* material); ~Piece() final = default; Piece& operator=(const Piece&) = default; Piece& operator=(Piece&&) = default; #ifndef OPENGLES void drawTopDepth() const final; #endif void drawTop() const final; void onHold(const ivec2& mPos, uint8 mBut) final; void onUndrag(uint8 mBut) final; void onHover() final; void onUnhover() final; void onCancelCapture() final; PieceType getType() const; void setType(PieceType newType); pair<uint8, uint8> firingArea() const; // 0 if non-firing piece void setActive(bool on); void updatePos(svec2 bpos = svec2(UINT16_MAX), bool forceRigid = false); void setInteractivity(bool on, bool dim, GCall holdCall, GCall leftCall, GCall rightCall); private: float selfTopYpos(const Interactable* occupant) const; }; inline PieceType Piece::getType() const { return type; } inline void Piece::setActive(bool on) { show = rigid = on; } inline float Piece::selfTopYpos(const Interactable* occupant) const { return dynamic_cast<const Piece*>(occupant) && occupant != this ? 1.1f * getScl().y : 0.01f; } // piece container class PieceCol { private: uptr<Piece[]> pc; uint16 num = 0; // number of one player's pieces, i.e. size / 2 uint16 size = 0; // all pieces public: void update(const Config& conf, bool regular); uint16 getNum() const; uint16 getSize() const; Piece& operator[](uint16 i); const Piece& operator[](uint16 i) const; Piece* begin(); const Piece* begin() const; Piece* end(); const Piece* end() const; Piece* own(pdift i = 0); const Piece* own(pdift i = 0) const; Piece* ene(pdift i = 0); const Piece* ene(pdift i = 0) const; }; inline uint16 PieceCol::getNum() const { return num; } inline uint16 PieceCol::getSize() const { return size; } inline Piece& PieceCol::operator[](uint16 i) { return pc[i]; } inline const Piece& PieceCol::operator[](uint16 i) const { return pc[i]; } inline Piece* PieceCol::begin() { return pc.get(); } inline const Piece* PieceCol::begin() const { return pc.get(); } inline Piece* PieceCol::end() { return &pc[size]; } inline const Piece* PieceCol::end() const { return &pc[size]; } inline Piece* PieceCol::own(pdift i) { return &pc[i]; } inline const Piece* PieceCol::own(pdift i) const { return &pc[i]; } inline Piece* PieceCol::ene(pdift i) { return &pc[num+i]; } inline const Piece* PieceCol::ene(pdift i) const { return &pc[num+i]; }
23.228448
227
0.710058
[ "mesh", "object", "shape", "vector", "model", "3d" ]
699bc4a71fb338559fc1fb5b53eef4a4ce4c5151
1,589
h
C
src/test/json_exception_test.h
karekoho/json
ee87dfd5d3e64c0efcd8942a93d67ed5a1adcd03
[ "MIT" ]
null
null
null
src/test/json_exception_test.h
karekoho/json
ee87dfd5d3e64c0efcd8942a93d67ed5a1adcd03
[ "MIT" ]
1
2021-05-13T12:15:09.000Z
2021-06-05T10:30:12.000Z
src/test/json_exception_test.h
karekoho/json
ee87dfd5d3e64c0efcd8942a93d67ed5a1adcd03
[ "MIT" ]
null
null
null
#ifndef JSON_EXCEPTION_TEST #define JSON_EXCEPTION_TEST #include "unit_test.h" namespace format { namespace json { /** * 14. * @brief The json_test class */ class json_syntax_error_test : public unit_test { public: void test_ctor_1 () { struct assert { const wchar_t *token; const char *output; size_t charc; int assert_status; }; std::vector<struct assert > test = { { L"\u0061b\u0063d", "a:'\u0061b\u0063d'", 0, PASS }, // abcd, 97-100 { L"\u2208b\u220Bd", "a:'\u2208b\u220Bd'", 0, PASS }, // ∈, 98, ∋, 100 NOTE: Fails in valgrind container { L"\u0061b\u0063d", "a:'\u0061'", 1, PASS }, // a:'a' { L"\u2208b\u220Bd", "a:'\u2208b'", 2, PASS }, // a:'∈b' NOTE: Fails in valgrind container }; TEST_IT_START json_syntax_error e ("a:", (*it).token, (*it).charc); const char *output = e.what (); CPPUNIT_ASSERT_EQUAL_MESSAGE ("e.what ()", 0, strcmp ((*it).output, output)); TEST_IT_END } /** * 14. * @brief suite * @return */ static CppUnit::Test * suite () { CppUnit::TestSuite *s = new CppUnit::TestSuite ("json exception test"); /* 0. */ s->addTest (new CppUnit::TestCaller<json_syntax_error_test> ("test_ctor_1", &json_syntax_error_test::test_ctor_1)); return s; } }; } // Namespace json } // Namespace format #endif // JSON_EXCEPTION_TEST
24.446154
133
0.529264
[ "vector" ]
699d5a2394f02232db8b5b4149e0b04d27914a24
2,514
h
C
kernel/nvidia/drivers/net/wireless/realtek/rtl8822ce/os_dep/linux/rtw_rhashtable.h
rubedos/l4t_R32.5.1_viper
6aed0062084d9031546f946e63fc74303555e0a6
[ "MIT" ]
null
null
null
kernel/nvidia/drivers/net/wireless/realtek/rtl8822ce/os_dep/linux/rtw_rhashtable.h
rubedos/l4t_R32.5.1_viper
6aed0062084d9031546f946e63fc74303555e0a6
[ "MIT" ]
null
null
null
kernel/nvidia/drivers/net/wireless/realtek/rtl8822ce/os_dep/linux/rtw_rhashtable.h
rubedos/l4t_R32.5.1_viper
6aed0062084d9031546f946e63fc74303555e0a6
[ "MIT" ]
null
null
null
/****************************************************************************** * * Copyright(c) 2007 - 2017 Realtek Corporation. * * This program is free software; you can redistribute it and/or modify it * under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * 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. * *****************************************************************************/ #ifndef __RTW_RHASHTABLE_H__ #define __RTW_RHASHTABLE_H__ #ifdef CONFIG_RTW_MESH /* for now, only promised for kernel versions we support mesh */ /* directly reference rhashtable in kernel */ #if (LINUX_VERSION_CODE >= KERNEL_VERSION(4, 4, 0)) #include <linux/rhashtable.h> #endif /* (LINUX_VERSION_CODE >= KERNEL_VERSION(4, 4, 0)) */ /* Use rhashtable from kernel 4.4 */ #if (LINUX_VERSION_CODE < KERNEL_VERSION(4, 4, 0)) #if (LINUX_VERSION_CODE < KERNEL_VERSION(4, 0, 0)) #define NULLS_MARKER(value) (1UL | (((long)value) << 1)) #endif #include "rhashtable.h" #endif /* (LINUX_VERSION_CODE < KERNEL_VERSION(4, 4, 0)) */ typedef struct rhashtable rtw_rhashtable; typedef struct rhash_head rtw_rhash_head; typedef struct rhashtable_params rtw_rhashtable_params; #define rtw_rhashtable_init(ht, params) rhashtable_init(ht, params) typedef struct rhashtable_iter rtw_rhashtable_iter; int rtw_rhashtable_walk_enter(rtw_rhashtable *ht, rtw_rhashtable_iter *iter); #define rtw_rhashtable_walk_exit(iter) rhashtable_walk_exit(iter) #if (LINUX_VERSION_CODE >= KERNEL_VERSION(4, 16, 0)) #define rtw_rhashtable_walk_start(iter) rhashtable_walk_start_check(iter) #else #define rtw_rhashtable_walk_start(iter) rhashtable_walk_start(iter) #endif #define rtw_rhashtable_walk_next(iter) rhashtable_walk_next(iter) #define rtw_rhashtable_walk_stop(iter) rhashtable_walk_stop(iter) #define rtw_rhashtable_free_and_destroy(ht, free_fn, arg) rhashtable_free_and_destroy((ht), (free_fn), (arg)) #define rtw_rhashtable_lookup_fast(ht, key, params) rhashtable_lookup_fast((ht), (key), (params)) #define rtw_rhashtable_lookup_insert_fast(ht, obj, params) rhashtable_lookup_insert_fast((ht), (obj), (params)) #define rtw_rhashtable_remove_fast(ht, obj, params) rhashtable_remove_fast((ht), (obj), (params)) #endif /* CONFIG_RTW_MESH */ #endif /* __RTW_RHASHTABLE_H__ */
41.9
111
0.733492
[ "mesh" ]
69a304d27d69162353573a5bdf4b4a45110297e1
1,092
h
C
clients/cpp-tizen/src/HTTPValidationError.h
theunifai/unifai-sdk
b010bd37e5a418881ee3747bd8ec6e8e18e08234
[ "MIT" ]
1
2022-03-30T11:33:28.000Z
2022-03-30T11:33:28.000Z
clients/cpp-tizen/src/HTTPValidationError.h
theunifai/unifai-sdk
b010bd37e5a418881ee3747bd8ec6e8e18e08234
[ "MIT" ]
null
null
null
clients/cpp-tizen/src/HTTPValidationError.h
theunifai/unifai-sdk
b010bd37e5a418881ee3747bd8ec6e8e18e08234
[ "MIT" ]
null
null
null
/* * HTTPValidationError.h * * */ #ifndef _HTTPValidationError_H_ #define _HTTPValidationError_H_ #include <string> #include "ValidationError.h" #include <list> #include "Object.h" /** \defgroup Models Data Structures for API * Classes containing all the Data Structures needed for calling/returned by API endpoints * */ namespace Tizen { namespace ArtikCloud { /*! \brief * * \ingroup Models * */ class HTTPValidationError : public Object { public: /*! \brief Constructor. */ HTTPValidationError(); HTTPValidationError(char* str); /*! \brief Destructor. */ virtual ~HTTPValidationError(); /*! \brief Retrieve a string JSON representation of this class. */ char* toJson(); /*! \brief Fills in members of this class from JSON string representing it. */ void fromJson(char* jsonStr); /*! \brief Get */ std::list<ValidationError> getDetail(); /*! \brief Set */ void setDetail(std::list <ValidationError> detail); private: std::list <ValidationError>detail; void __init(); void __cleanup(); }; } } #endif /* _HTTPValidationError_H_ */
16.058824
91
0.693223
[ "object" ]
69b08203f651bffcf872db13e28c68eb03f4bfc8
7,464
c
C
gempak/source/diaglib/dv/dvgeo.c
oxelson/gempak
e7c477814d7084c87d3313c94e192d13d8341fa1
[ "BSD-3-Clause" ]
42
2015-06-03T15:26:21.000Z
2022-02-28T22:36:03.000Z
gempak/source/diaglib/dv/dvgeo.c
oxelson/gempak
e7c477814d7084c87d3313c94e192d13d8341fa1
[ "BSD-3-Clause" ]
60
2015-05-11T21:36:08.000Z
2022-03-29T16:22:42.000Z
gempak/source/diaglib/dv/dvgeo.c
oxelson/gempak
e7c477814d7084c87d3313c94e192d13d8341fa1
[ "BSD-3-Clause" ]
27
2016-06-06T21:55:14.000Z
2022-03-18T18:23:28.000Z
#include "dv.h" void dv_geo ( int *iret ) /************************************************************************ * dv_geo * * * * This subroutine computes the geostrophic wind: * * * * GEO ( S ) = [ - DDY (S) * const / CORL, DDX (S) * const / CORL ]* * * * Where: const S vert.coord. * * ------ ---- ----------- * * GRAVTY ZMSL none * * GRAVTY HGHT PRES * * 1 PSYM THTA * * 100/RO PRES HGHT * * ------ ---- ----------- * * RO = PD_DDEN ( PRES, TMPC ) * * * * GEO generates a vector grid. * * * * dv_geo ( iret ) * * * * Output parameters: * * *iret int Return code * * As for DG_GETS, plus * * -9 = ... calling sequence error* * -11 = ... must be a vector * ** * * Log: * * M. Goodman/RDS 12/85 * * M. desJardins/GSFC 9/88 GEMPAK4 Version * * G. Huffman/GSC 9/88 Error messages * * M. desJardins/GSFC 7/89 Added PA subroutines * * K. Brill/GSC 8/89 Subsetting * * K. Brill/GSC 10/89 Subsetting * * K. Brill/NMC 11/90 Pass grid number to DF_CORL * * K. BRILL/NMC 12/92 Check for too small Coriolis parm * * L. Sager/NMC 4/93 Change to UGEO and VGEO * * M. desJardins/NMC 7/93 Changed update scheme * * D. Keiser/GSC 8/95 Increased Coriolis parm * * T. Lee/GSC 4/96 Single dimension for dgg * * T. Lee/GSC 5/96 Moved IGDPT outside DO loop * * K. Brill/HPC 1/02 CALL DG_SSUB, DG_ESUB; CHK iret & RTRN * * K. Brill/HPC 11/02 Eliminate use of the SUBA logical array * * S. Gilbert/NCEP 11/05 Translation from Fortran * C************************************************************************/ { char grid[13], parm[13], time1[21], time2[21]; int level1, level2, ivcord; char errst[1024]; int i, ier, zero=0, tmp, nval, kxd, kyd, ksub1, ksub2; int kxyd, idlun, ndx, ndy, ignum; int num1, nf, ncnst, nvecu, nvecv; float *grnum1, *grnf, *grcnst, *grvecu, *grvecv; float testit, cnst, dens; /*------------------------------------------------------------------------*/ *iret = 0; dg_ssub ( iret ); /* * Read the information from the top of the stack. */ dg_tops ( grid, &ignum, time1, time2, &level1, &level2, &ivcord, parm, iret ); if ( *iret != 0 ) return; /* * If the name of the vector to be computed is "GEO", replace the * top of the stack with the proper dependent "height" field. * Otherwise, assume that the user has done it. */ if ( strncmp( grid, "GEO",3) == 0 ) { if ( ivcord == 0 ) dg_rpls ( "ZMSL", &zero, &ier ); else if ( ivcord == 1 ) dg_rpls ( "HGHT", &zero, &ier ); else if ( ivcord == 2 ) dg_rpls ( "PSYM", &zero, &ier ); else if ( ivcord == 3 ) dg_rpls ( "PRES", &zero, &ier ); else { *iret = -24; tmp = -1; dg_merr ( "", "", "", &tmp, &tmp, &ivcord, errst, &ier ); dg_cset ( "ERRST", errst, &ier); return; } /* * Else, assume that the user did it. */ } /* * Read in the scalar grid. */ dg_gets ( &num1, iret ); if ( *iret != 0 ) return; /* * Put the scalar field on the stack and compute the y derivative. * Here and following, always get the result after the computation. */ dg_puts ( &num1, iret ); df_ddy ( iret ); if ( *iret != 0 ) return; dg_gets ( &ndy, iret ); /* * Put the scalar back on the stack and compute the x derivative. */ dg_puts ( &num1, iret ); df_ddx ( iret ); if ( *iret != 0 ) return; dg_gets ( &ndx, iret ); /* * Compute the coriolis grid. */ dg_nxts ( &nf, iret ); if ( *iret != 0 ) return; df_corl ( &nf, iret ); if ( *iret != 0 ) return; /* * Set near equatorial ( latitude 4 degrees N/S ) Coriolis to missing. */ dg_getg ( &nf, &grnf, &kxd, &kyd, &ksub1, &ksub2, iret ); for ( i = ksub1 - 1; i < ksub2; i++ ) { if ( ! ERMISS ( grnf[i] ) ) { testit = fabs ( grnf[i] ); if ( testit < 1.25E-05 ) grnf[i] = RMISSD; } } /* * Divide the y derivative by the coriolis (note order of puts). */ dg_puts ( &nf, iret ); dg_puts ( &ndy, iret ); if ( *iret != 0 ) return; df_quo ( iret ); if ( *iret != 0 ) return; dg_gets ( &nvecu, iret ); /* * Divide the x derivative by the coriolis. */ dg_puts ( &nf, iret ); dg_puts ( &ndx, iret ); if ( *iret != 0 ) return; df_quo ( iret ); if( *iret != 0 ) return; dg_gets ( &nvecv, iret ); /* * Compute the numerical "constant" grid for the vertical coordinate. */ dg_nxts ( &ncnst, iret ); if ( *iret != 0 ) return; dg_getg ( &ncnst, &grcnst, &kxd, &kyd, &ksub1, &ksub2, iret); /* * NONE, PRES: the constant is gravity. */ if ( (ivcord == 0 ) || ( ivcord == 1 ) ) { cnst = GRAVTY; dg_real ( &cnst, &ncnst, iret ); } /* * THTA: no additional constant. */ else if ( ivcord == 2 ) { cnst = 1.; dg_real ( &cnst, &ncnst, iret ); } /* * HGHT: the 100 converts mb to Pascals, and 1/DDEN is needed. */ else if ( ivcord == 3 ) { dg_temp ( time1, time2, &level1, &level2, &ivcord, "TMPC", &ncnst, iret ); if ( *iret != 0 ) return; dg_getg ( &num1, &grnum1, &kxd, &kyd, &ksub1, &ksub2, iret ); kxyd = kxd * kyd; pd_dden ( grnum1, grcnst, &kxyd, grcnst, &ier ); for ( i = ksub1 - 1; i < ksub2; i++ ) { dens = grcnst[i]; if ( ERMISS ( dens ) || G_DIFFT( dens, 0.0F, GDIFFD) ) grcnst[i] = RMISSD; else grcnst[i] = 100. / dens; } } /* * Now, compute the components of the geostrophic wind. */ dg_getg ( &nvecu, &grvecu, &kxd, &kyd, &ksub1, &ksub2, iret ); dg_getg ( &nvecv, &grvecv, &kxd, &kyd, &ksub1, &ksub2, iret ); for ( i = ksub1 - 1; i < ksub2; i++ ) { /* * Compute the u-component of the geostrophic wind. */ if ( ERMISS ( grvecu[i] ) || ERMISS ( grcnst[i] ) ) grvecu[i] = RMISSD; else grvecu[i] = - grvecu[i] * grcnst[i]; /* * Compute the v-component of the geostrophic wind. */ if ( ERMISS ( grvecv[i] ) || ERMISS ( grcnst[i] ) ) grvecv[i] = RMISSD; else grvecv[i] = grvecv[i] * grcnst[i]; } /* * Update both grid headers. Use wind type as parameter name. */ dg_iget ( "IDLUN", &nval, &idlun, iret ); dg_upvg ( time1, time2, &level1, &level2, &ivcord, &idlun, "GEO", &nvecu, &nvecv, &ier ); /* * Update stack. */ dg_putv ( &nvecu, &nvecv, iret ); dg_esub ( &nvecu, &nvecv, &zero, &zero, &ier ); if ( ier != 0 ) *iret = ier; return; }
30.218623
80
0.45351
[ "vector" ]
69b17ec514a973b6ba320761fe9b9a1bee08d277
3,362
h
C
src/polygon/bpc.h
BBrumback/Final_project_mesh_unfolder
4fbb1f9b4e34f6061c87ae08dc0c4e7ab256cddc
[ "MIT" ]
1
2021-04-23T09:11:23.000Z
2021-04-23T09:11:23.000Z
src/polygon/bpc.h
jmlien/mesh_unfolder
3f1ed2f4b906a57bebf7b35ed75c7c3fa976de58
[ "MIT" ]
null
null
null
src/polygon/bpc.h
jmlien/mesh_unfolder
3f1ed2f4b906a57bebf7b35ed75c7c3fa976de58
[ "MIT" ]
null
null
null
#pragma once #include "polygon.h" #include "polyline.h" namespace masc{ namespace polygon{ class c_BPC //a class for bridge pocket and concavity { public: c_BPC(); // // core functions // bool build(ply_vertex * s, ply_vertex * e); bool build_for_hole(ply_vertex * s, ply_vertex * e, bool ordered=false); void determineConcavity(float tau, bool bReducePM = false); bool isOverlapping(c_BPC * other); void reorganize_kids_f(); //void determineTip(); void determine_PM(float tau); // // access functions // ply_vertex * getSource1() const { return m_source[0]; } ply_vertex * getSource2() const { return m_source[1]; } const list<ply_vertex *>& getConcavities() const { return m_concavities; } const list<ply_vertex *>& getBridgeEnds() const { return m_bridge_ends; } void addKid(c_BPC * kid){ assert(kid); m_kids.push_back(kid); kid->m_parent=this;} const list<c_BPC *>& getKids() const { return m_kids; } c_BPC * getParent() const { return m_parent; } const c_BPC * getRoot() const { if(m_parent==NULL) return this; return m_parent->getRoot(); } int getPocketSize() const { return m_pocketsize; } void setNext(c_BPC * bpc) { m_next=bpc; if(bpc!=NULL) bpc->m_pre=this; } c_BPC * getNext() const { return m_next; } c_BPC * getPre() const { return m_pre; } bool isKid(c_BPC * other); //compute the area enclosed between p1 and p2 float bridgeArea(ply_vertex * p1, ply_vertex * p2); protected: float dist2Bridge(const Point2d& p); //check if the given vertices will form a bridge //when return 'b', (p1,p2) is a bridge //when return 'r', (p2,p1) is a bridge //when return '0', (p2,p1) nor (p1,p2) are bridges char checkBridge(ply_vertex * p1, ply_vertex * p2); void getVerticesExcludingKidPockets_f(list<ply_vertex*>& vlist); c_plyline bpc2polyline( const list<ply_vertex*>& vlist ); void insert2tree(c_BPC * kid); float dist_in_hierarchy(c_BPC * bpc, const Point2d& p); Point2d proj2Seg(const Point2d& s, const Point2d& t, const Point2d& p); void getSortedFeatures_f(list<ply_vertex*>& PMs,list<ply_vertex*>& features); //create c_ply for a list of vertex c_ply list2Ply(list<ply_vertex*> & vertlist); c_ply seg2Ply(ply_vertex* vstart,ply_vertex* vend); private: ply_vertex * m_source[2]; list<ply_vertex*> m_concavities; list<ply_vertex*> m_bridge_ends; int m_pocketsize; //number of vertics in this pocket //connection at the same level //in the order of polygon traversal c_BPC * m_next; c_BPC * m_pre; //connection in a tree list<c_BPC *> m_kids; c_BPC * m_best_kid; //the kid that has the largest concavity c_BPC * m_parent; //added by Guilin float m_tau; vector<ply_vertex*> kidStartPnts; vector<ply_vertex*> kidEndPnts; void initPointList(); int checkStartPoint(ply_vertex* curVert); int checkEndPoint(ply_vertex* curVert); void markConvexhllPoints(ply_vertex* s,ply_vertex* e,uint marking_flag); //uint getDudeFlag() {return BPCTMPFLAG++;} void getConvexApproximate(list<ply_vertex*>& approxList); //void determineConcavity1(float tau,bool reducePMs = false); void determineConcavity_real(float tau,bool reducePMs = false); }; }//end namespace polygon }//end namespace masc
27.333333
97
0.687388
[ "vector" ]
69b7a4629cefe322c0f8bdc6dc6789d105698a86
1,390
h
C
Source/Plugins/GraphicsPlugins/BladeTerrain/header/BladeTerrain_blang.h
OscarGame/blade
6987708cb011813eb38e5c262c7a83888635f002
[ "MIT" ]
146
2018-12-03T08:08:17.000Z
2022-03-21T06:04:06.000Z
Source/Plugins/GraphicsPlugins/BladeTerrain/header/BladeTerrain_blang.h
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
1
2019-01-18T03:35:49.000Z
2019-01-18T03:36:08.000Z
Source/Plugins/GraphicsPlugins/BladeTerrain/header/BladeTerrain_blang.h
huangx916/blade
3fa398f4d32215bbc7e292d61e38bb92aad1ee1c
[ "MIT" ]
31
2018-12-03T10:32:43.000Z
2021-10-04T06:31:44.000Z
/******************************************************************** created: 2013/10/30 filename: BladeTerrain_blang.h author: Crazii purpose: *********************************************************************/ #ifndef __Blade_BladeTerrain_blang_h__ #define __Blade_BladeTerrain_blang_h__ #include <interface/ILangTable.h> //properties need auto translate #define BLANG_TERRAIN "Terrain" #define BLANG_MESH_QUALITY "Mesh Quality" #define BLANG_BATCH_COMBINE "Batch Combination" #define BLANG_NO_COMBINE "No Combination" #define BLANG_FULL_COMBINE "Full Combination" //full combine for every pass, including shadow pass etc. #define BLANG_SCENE_PASS_COMBINE "Scene Pass Combination" //full combine for scene draw only #define BLANG_LOD_LEVEL "LOD levels" #define BLANG_BLOCK_SIZE "Block Size" #define BLANG_BLENDMAP_SCALE "Blend Map Scale" #define BLANG_MAX_HEIGHT "Max Height" #define BLANG_DATA_PATH "Data Path" #define BLANG_RESOURCE_PATH "Resource Path" #define BLANG_TEXTURE_QUALITY "Texture Quality" #define BLANG_GLOBAL_CONFIG "Terrain Config" #define BLANG_CREATION_CONFIG "Terrain Creation Config" #define BLANG_TERRAIN_ELEMENT "Terrain Element" #define BLANG_TEXTURES "Textures" #define BLANG_INDEX_X "Index X" #define BLANG_INDEX_Z "Index Z" #endif // __Blade_BladeTerrain_blang_h__
37.567568
109
0.692806
[ "mesh" ]
69c585988010ea3b3522be8f68738a44443bcc69
54,094
h
C
geo3d/include/s3dm-client/sessions/sessions.pb.h
vipuserr/vipuserr-Geological-hazard
2b29c03cdac6f5e1ceac4cd2f15b594040ef909c
[ "MIT" ]
null
null
null
geo3d/include/s3dm-client/sessions/sessions.pb.h
vipuserr/vipuserr-Geological-hazard
2b29c03cdac6f5e1ceac4cd2f15b594040ef909c
[ "MIT" ]
null
null
null
geo3d/include/s3dm-client/sessions/sessions.pb.h
vipuserr/vipuserr-Geological-hazard
2b29c03cdac6f5e1ceac4cd2f15b594040ef909c
[ "MIT" ]
null
null
null
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: sessions/sessions.proto #ifndef GOOGLE_PROTOBUF_INCLUDED_sessions_2fsessions_2eproto #define GOOGLE_PROTOBUF_INCLUDED_sessions_2fsessions_2eproto #include <limits> #include <string> #include <google/protobuf/port_def.inc> #if PROTOBUF_VERSION < 3015000 #error This file was generated by a newer version of protoc which is #error incompatible with your Protocol Buffer headers. Please update #error your headers. #endif #if 3015008 < PROTOBUF_MIN_PROTOC_VERSION #error This file was generated by an older version of protoc which is #error incompatible with your Protocol Buffer headers. Please #error regenerate this file with a newer version of protoc. #endif #include <google/protobuf/port_undef.inc> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/arena.h> #include <google/protobuf/arenastring.h> #include <google/protobuf/generated_message_table_driven.h> #include <google/protobuf/generated_message_util.h> #include <google/protobuf/metadata_lite.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/message.h> #include <google/protobuf/repeated_field.h> // IWYU pragma: export #include <google/protobuf/extension_set.h> // IWYU pragma: export #include <google/protobuf/unknown_field_set.h> #include <google/protobuf/timestamp.pb.h> #include <google/protobuf/wrappers.pb.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> #define PROTOBUF_INTERNAL_EXPORT_sessions_2fsessions_2eproto LIBS3DMGRPC_API PROTOBUF_NAMESPACE_OPEN namespace internal { class AnyMetadata; } // namespace internal PROTOBUF_NAMESPACE_CLOSE // Internal implementation detail -- do not use these members. struct LIBS3DMGRPC_API TableStruct_sessions_2fsessions_2eproto { static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTableField entries[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::AuxiliaryParseTableField aux[] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::ParseTable schema[4] PROTOBUF_SECTION_VARIABLE(protodesc_cold); static const ::PROTOBUF_NAMESPACE_ID::internal::FieldMetadata field_metadata[]; static const ::PROTOBUF_NAMESPACE_ID::internal::SerializationTable serialization_table[]; static const ::PROTOBUF_NAMESPACE_ID::uint32 offsets[]; }; extern LIBS3DMGRPC_API const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_sessions_2fsessions_2eproto; LIBS3DMGRPC_API ::PROTOBUF_NAMESPACE_ID::Metadata descriptor_table_sessions_2fsessions_2eproto_metadata_getter(int index); namespace smart3dmap { namespace v1 { class CreateSessionRequest; struct CreateSessionRequestDefaultTypeInternal; LIBS3DMGRPC_API extern CreateSessionRequestDefaultTypeInternal _CreateSessionRequest_default_instance_; class DeleteSessionRequest; struct DeleteSessionRequestDefaultTypeInternal; LIBS3DMGRPC_API extern DeleteSessionRequestDefaultTypeInternal _DeleteSessionRequest_default_instance_; class GetSessionRequest; struct GetSessionRequestDefaultTypeInternal; LIBS3DMGRPC_API extern GetSessionRequestDefaultTypeInternal _GetSessionRequest_default_instance_; class Session; struct SessionDefaultTypeInternal; LIBS3DMGRPC_API extern SessionDefaultTypeInternal _Session_default_instance_; } // namespace v1 } // namespace smart3dmap PROTOBUF_NAMESPACE_OPEN template<> LIBS3DMGRPC_API ::smart3dmap::v1::CreateSessionRequest* Arena::CreateMaybeMessage<::smart3dmap::v1::CreateSessionRequest>(Arena*); template<> LIBS3DMGRPC_API ::smart3dmap::v1::DeleteSessionRequest* Arena::CreateMaybeMessage<::smart3dmap::v1::DeleteSessionRequest>(Arena*); template<> LIBS3DMGRPC_API ::smart3dmap::v1::GetSessionRequest* Arena::CreateMaybeMessage<::smart3dmap::v1::GetSessionRequest>(Arena*); template<> LIBS3DMGRPC_API ::smart3dmap::v1::Session* Arena::CreateMaybeMessage<::smart3dmap::v1::Session>(Arena*); PROTOBUF_NAMESPACE_CLOSE namespace smart3dmap { namespace v1 { // =================================================================== class LIBS3DMGRPC_API Session PROTOBUF_FINAL : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:smart3dmap.v1.Session) */ { public: inline Session() : Session(nullptr) {} virtual ~Session(); explicit constexpr Session(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); Session(const Session& from); Session(Session&& from) noexcept : Session() { *this = ::std::move(from); } inline Session& operator=(const Session& from) { CopyFrom(from); return *this; } inline Session& operator=(Session&& from) noexcept { if (GetArena() == from.GetArena()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const Session& default_instance() { return *internal_default_instance(); } static inline const Session* internal_default_instance() { return reinterpret_cast<const Session*>( &_Session_default_instance_); } static constexpr int kIndexInFileMessages = 0; friend void swap(Session& a, Session& b) { a.Swap(&b); } inline void Swap(Session* other) { if (other == this) return; if (GetArena() == other->GetArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(Session* other) { if (other == this) return; GOOGLE_DCHECK(GetArena() == other->GetArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline Session* New() const final { return CreateMaybeMessage<Session>(nullptr); } Session* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<Session>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const Session& from); void MergeFrom(const Session& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(Session* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "smart3dmap.v1.Session"; } protected: explicit Session(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { return ::descriptor_table_sessions_2fsessions_2eproto_metadata_getter(kIndexInFileMessages); } public: // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kTokenFieldNumber = 1, kClientIdFieldNumber = 3, kCreatedAtFieldNumber = 4, kUpdatedAtFieldNumber = 5, kUserIdFieldNumber = 2, }; // string token = 1; void clear_token(); const std::string& token() const; void set_token(const std::string& value); void set_token(std::string&& value); void set_token(const char* value); void set_token(const char* value, size_t size); std::string* mutable_token(); std::string* release_token(); void set_allocated_token(std::string* token); private: const std::string& _internal_token() const; void _internal_set_token(const std::string& value); std::string* _internal_mutable_token(); public: // string client_id = 3; void clear_client_id(); const std::string& client_id() const; void set_client_id(const std::string& value); void set_client_id(std::string&& value); void set_client_id(const char* value); void set_client_id(const char* value, size_t size); std::string* mutable_client_id(); std::string* release_client_id(); void set_allocated_client_id(std::string* client_id); private: const std::string& _internal_client_id() const; void _internal_set_client_id(const std::string& value); std::string* _internal_mutable_client_id(); public: // .google.protobuf.Timestamp createdAt = 4; bool has_createdat() const; private: bool _internal_has_createdat() const; public: void clear_createdat(); const PROTOBUF_NAMESPACE_ID::Timestamp& createdat() const; PROTOBUF_NAMESPACE_ID::Timestamp* release_createdat(); PROTOBUF_NAMESPACE_ID::Timestamp* mutable_createdat(); void set_allocated_createdat(PROTOBUF_NAMESPACE_ID::Timestamp* createdat); private: const PROTOBUF_NAMESPACE_ID::Timestamp& _internal_createdat() const; PROTOBUF_NAMESPACE_ID::Timestamp* _internal_mutable_createdat(); public: void unsafe_arena_set_allocated_createdat( PROTOBUF_NAMESPACE_ID::Timestamp* createdat); PROTOBUF_NAMESPACE_ID::Timestamp* unsafe_arena_release_createdat(); // .google.protobuf.Timestamp updatedAt = 5; bool has_updatedat() const; private: bool _internal_has_updatedat() const; public: void clear_updatedat(); const PROTOBUF_NAMESPACE_ID::Timestamp& updatedat() const; PROTOBUF_NAMESPACE_ID::Timestamp* release_updatedat(); PROTOBUF_NAMESPACE_ID::Timestamp* mutable_updatedat(); void set_allocated_updatedat(PROTOBUF_NAMESPACE_ID::Timestamp* updatedat); private: const PROTOBUF_NAMESPACE_ID::Timestamp& _internal_updatedat() const; PROTOBUF_NAMESPACE_ID::Timestamp* _internal_mutable_updatedat(); public: void unsafe_arena_set_allocated_updatedat( PROTOBUF_NAMESPACE_ID::Timestamp* updatedat); PROTOBUF_NAMESPACE_ID::Timestamp* unsafe_arena_release_updatedat(); // int32 user_id = 2; void clear_user_id(); ::PROTOBUF_NAMESPACE_ID::int32 user_id() const; void set_user_id(::PROTOBUF_NAMESPACE_ID::int32 value); private: ::PROTOBUF_NAMESPACE_ID::int32 _internal_user_id() const; void _internal_set_user_id(::PROTOBUF_NAMESPACE_ID::int32 value); public: // @@protoc_insertion_point(class_scope:smart3dmap.v1.Session) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr token_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr client_id_; PROTOBUF_NAMESPACE_ID::Timestamp* createdat_; PROTOBUF_NAMESPACE_ID::Timestamp* updatedat_; ::PROTOBUF_NAMESPACE_ID::int32 user_id_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_sessions_2fsessions_2eproto; }; // ------------------------------------------------------------------- class LIBS3DMGRPC_API CreateSessionRequest PROTOBUF_FINAL : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:smart3dmap.v1.CreateSessionRequest) */ { public: inline CreateSessionRequest() : CreateSessionRequest(nullptr) {} virtual ~CreateSessionRequest(); explicit constexpr CreateSessionRequest(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); CreateSessionRequest(const CreateSessionRequest& from); CreateSessionRequest(CreateSessionRequest&& from) noexcept : CreateSessionRequest() { *this = ::std::move(from); } inline CreateSessionRequest& operator=(const CreateSessionRequest& from) { CopyFrom(from); return *this; } inline CreateSessionRequest& operator=(CreateSessionRequest&& from) noexcept { if (GetArena() == from.GetArena()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const CreateSessionRequest& default_instance() { return *internal_default_instance(); } static inline const CreateSessionRequest* internal_default_instance() { return reinterpret_cast<const CreateSessionRequest*>( &_CreateSessionRequest_default_instance_); } static constexpr int kIndexInFileMessages = 1; friend void swap(CreateSessionRequest& a, CreateSessionRequest& b) { a.Swap(&b); } inline void Swap(CreateSessionRequest* other) { if (other == this) return; if (GetArena() == other->GetArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(CreateSessionRequest* other) { if (other == this) return; GOOGLE_DCHECK(GetArena() == other->GetArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline CreateSessionRequest* New() const final { return CreateMaybeMessage<CreateSessionRequest>(nullptr); } CreateSessionRequest* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<CreateSessionRequest>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const CreateSessionRequest& from); void MergeFrom(const CreateSessionRequest& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(CreateSessionRequest* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "smart3dmap.v1.CreateSessionRequest"; } protected: explicit CreateSessionRequest(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { return ::descriptor_table_sessions_2fsessions_2eproto_metadata_getter(kIndexInFileMessages); } public: // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kEmailFieldNumber = 1, kPasswordFieldNumber = 2, kClientIdFieldNumber = 3, }; // string email = 1; void clear_email(); const std::string& email() const; void set_email(const std::string& value); void set_email(std::string&& value); void set_email(const char* value); void set_email(const char* value, size_t size); std::string* mutable_email(); std::string* release_email(); void set_allocated_email(std::string* email); private: const std::string& _internal_email() const; void _internal_set_email(const std::string& value); std::string* _internal_mutable_email(); public: // string password = 2; void clear_password(); const std::string& password() const; void set_password(const std::string& value); void set_password(std::string&& value); void set_password(const char* value); void set_password(const char* value, size_t size); std::string* mutable_password(); std::string* release_password(); void set_allocated_password(std::string* password); private: const std::string& _internal_password() const; void _internal_set_password(const std::string& value); std::string* _internal_mutable_password(); public: // string client_id = 3; void clear_client_id(); const std::string& client_id() const; void set_client_id(const std::string& value); void set_client_id(std::string&& value); void set_client_id(const char* value); void set_client_id(const char* value, size_t size); std::string* mutable_client_id(); std::string* release_client_id(); void set_allocated_client_id(std::string* client_id); private: const std::string& _internal_client_id() const; void _internal_set_client_id(const std::string& value); std::string* _internal_mutable_client_id(); public: // @@protoc_insertion_point(class_scope:smart3dmap.v1.CreateSessionRequest) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr email_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr password_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr client_id_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_sessions_2fsessions_2eproto; }; // ------------------------------------------------------------------- class LIBS3DMGRPC_API GetSessionRequest PROTOBUF_FINAL : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:smart3dmap.v1.GetSessionRequest) */ { public: inline GetSessionRequest() : GetSessionRequest(nullptr) {} virtual ~GetSessionRequest(); explicit constexpr GetSessionRequest(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); GetSessionRequest(const GetSessionRequest& from); GetSessionRequest(GetSessionRequest&& from) noexcept : GetSessionRequest() { *this = ::std::move(from); } inline GetSessionRequest& operator=(const GetSessionRequest& from) { CopyFrom(from); return *this; } inline GetSessionRequest& operator=(GetSessionRequest&& from) noexcept { if (GetArena() == from.GetArena()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const GetSessionRequest& default_instance() { return *internal_default_instance(); } static inline const GetSessionRequest* internal_default_instance() { return reinterpret_cast<const GetSessionRequest*>( &_GetSessionRequest_default_instance_); } static constexpr int kIndexInFileMessages = 2; friend void swap(GetSessionRequest& a, GetSessionRequest& b) { a.Swap(&b); } inline void Swap(GetSessionRequest* other) { if (other == this) return; if (GetArena() == other->GetArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(GetSessionRequest* other) { if (other == this) return; GOOGLE_DCHECK(GetArena() == other->GetArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline GetSessionRequest* New() const final { return CreateMaybeMessage<GetSessionRequest>(nullptr); } GetSessionRequest* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<GetSessionRequest>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const GetSessionRequest& from); void MergeFrom(const GetSessionRequest& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(GetSessionRequest* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "smart3dmap.v1.GetSessionRequest"; } protected: explicit GetSessionRequest(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { return ::descriptor_table_sessions_2fsessions_2eproto_metadata_getter(kIndexInFileMessages); } public: // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kTokenFieldNumber = 1, }; // string token = 1; void clear_token(); const std::string& token() const; void set_token(const std::string& value); void set_token(std::string&& value); void set_token(const char* value); void set_token(const char* value, size_t size); std::string* mutable_token(); std::string* release_token(); void set_allocated_token(std::string* token); private: const std::string& _internal_token() const; void _internal_set_token(const std::string& value); std::string* _internal_mutable_token(); public: // @@protoc_insertion_point(class_scope:smart3dmap.v1.GetSessionRequest) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr token_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_sessions_2fsessions_2eproto; }; // ------------------------------------------------------------------- class LIBS3DMGRPC_API DeleteSessionRequest PROTOBUF_FINAL : public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:smart3dmap.v1.DeleteSessionRequest) */ { public: inline DeleteSessionRequest() : DeleteSessionRequest(nullptr) {} virtual ~DeleteSessionRequest(); explicit constexpr DeleteSessionRequest(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized); DeleteSessionRequest(const DeleteSessionRequest& from); DeleteSessionRequest(DeleteSessionRequest&& from) noexcept : DeleteSessionRequest() { *this = ::std::move(from); } inline DeleteSessionRequest& operator=(const DeleteSessionRequest& from) { CopyFrom(from); return *this; } inline DeleteSessionRequest& operator=(DeleteSessionRequest&& from) noexcept { if (GetArena() == from.GetArena()) { if (this != &from) InternalSwap(&from); } else { CopyFrom(from); } return *this; } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() { return GetDescriptor(); } static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() { return GetMetadataStatic().descriptor; } static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() { return GetMetadataStatic().reflection; } static const DeleteSessionRequest& default_instance() { return *internal_default_instance(); } static inline const DeleteSessionRequest* internal_default_instance() { return reinterpret_cast<const DeleteSessionRequest*>( &_DeleteSessionRequest_default_instance_); } static constexpr int kIndexInFileMessages = 3; friend void swap(DeleteSessionRequest& a, DeleteSessionRequest& b) { a.Swap(&b); } inline void Swap(DeleteSessionRequest* other) { if (other == this) return; if (GetArena() == other->GetArena()) { InternalSwap(other); } else { ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other); } } void UnsafeArenaSwap(DeleteSessionRequest* other) { if (other == this) return; GOOGLE_DCHECK(GetArena() == other->GetArena()); InternalSwap(other); } // implements Message ---------------------------------------------- inline DeleteSessionRequest* New() const final { return CreateMaybeMessage<DeleteSessionRequest>(nullptr); } DeleteSessionRequest* New(::PROTOBUF_NAMESPACE_ID::Arena* arena) const final { return CreateMaybeMessage<DeleteSessionRequest>(arena); } void CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) final; void CopyFrom(const DeleteSessionRequest& from); void MergeFrom(const DeleteSessionRequest& from); PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final; bool IsInitialized() const final; size_t ByteSizeLong() const final; const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final; ::PROTOBUF_NAMESPACE_ID::uint8* _InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final; int GetCachedSize() const final { return _cached_size_.Get(); } private: inline void SharedCtor(); inline void SharedDtor(); void SetCachedSize(int size) const final; void InternalSwap(DeleteSessionRequest* other); friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata; static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() { return "smart3dmap.v1.DeleteSessionRequest"; } protected: explicit DeleteSessionRequest(::PROTOBUF_NAMESPACE_ID::Arena* arena); private: static void ArenaDtor(void* object); inline void RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena* arena); public: ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final; private: static ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadataStatic() { return ::descriptor_table_sessions_2fsessions_2eproto_metadata_getter(kIndexInFileMessages); } public: // nested types ---------------------------------------------------- // accessors ------------------------------------------------------- enum : int { kTokenFieldNumber = 1, }; // string token = 1; void clear_token(); const std::string& token() const; void set_token(const std::string& value); void set_token(std::string&& value); void set_token(const char* value); void set_token(const char* value, size_t size); std::string* mutable_token(); std::string* release_token(); void set_allocated_token(std::string* token); private: const std::string& _internal_token() const; void _internal_set_token(const std::string& value); std::string* _internal_mutable_token(); public: // @@protoc_insertion_point(class_scope:smart3dmap.v1.DeleteSessionRequest) private: class _Internal; template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper; typedef void InternalArenaConstructable_; typedef void DestructorSkippable_; ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr token_; mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_; friend struct ::TableStruct_sessions_2fsessions_2eproto; }; // =================================================================== // =================================================================== #ifdef __GNUC__ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wstrict-aliasing" #endif // __GNUC__ // Session // string token = 1; inline void Session::clear_token() { token_.ClearToEmpty(); } inline const std::string& Session::token() const { // @@protoc_insertion_point(field_get:smart3dmap.v1.Session.token) return _internal_token(); } inline void Session::set_token(const std::string& value) { _internal_set_token(value); // @@protoc_insertion_point(field_set:smart3dmap.v1.Session.token) } inline std::string* Session::mutable_token() { // @@protoc_insertion_point(field_mutable:smart3dmap.v1.Session.token) return _internal_mutable_token(); } inline const std::string& Session::_internal_token() const { return token_.Get(); } inline void Session::_internal_set_token(const std::string& value) { token_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena()); } inline void Session::set_token(std::string&& value) { token_.Set( ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena()); // @@protoc_insertion_point(field_set_rvalue:smart3dmap.v1.Session.token) } inline void Session::set_token(const char* value) { GOOGLE_DCHECK(value != nullptr); token_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena()); // @@protoc_insertion_point(field_set_char:smart3dmap.v1.Session.token) } inline void Session::set_token(const char* value, size_t size) { token_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string( reinterpret_cast<const char*>(value), size), GetArena()); // @@protoc_insertion_point(field_set_pointer:smart3dmap.v1.Session.token) } inline std::string* Session::_internal_mutable_token() { return token_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena()); } inline std::string* Session::release_token() { // @@protoc_insertion_point(field_release:smart3dmap.v1.Session.token) return token_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void Session::set_allocated_token(std::string* token) { if (token != nullptr) { } else { } token_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), token, GetArena()); // @@protoc_insertion_point(field_set_allocated:smart3dmap.v1.Session.token) } // int32 user_id = 2; inline void Session::clear_user_id() { user_id_ = 0; } inline ::PROTOBUF_NAMESPACE_ID::int32 Session::_internal_user_id() const { return user_id_; } inline ::PROTOBUF_NAMESPACE_ID::int32 Session::user_id() const { // @@protoc_insertion_point(field_get:smart3dmap.v1.Session.user_id) return _internal_user_id(); } inline void Session::_internal_set_user_id(::PROTOBUF_NAMESPACE_ID::int32 value) { user_id_ = value; } inline void Session::set_user_id(::PROTOBUF_NAMESPACE_ID::int32 value) { _internal_set_user_id(value); // @@protoc_insertion_point(field_set:smart3dmap.v1.Session.user_id) } // string client_id = 3; inline void Session::clear_client_id() { client_id_.ClearToEmpty(); } inline const std::string& Session::client_id() const { // @@protoc_insertion_point(field_get:smart3dmap.v1.Session.client_id) return _internal_client_id(); } inline void Session::set_client_id(const std::string& value) { _internal_set_client_id(value); // @@protoc_insertion_point(field_set:smart3dmap.v1.Session.client_id) } inline std::string* Session::mutable_client_id() { // @@protoc_insertion_point(field_mutable:smart3dmap.v1.Session.client_id) return _internal_mutable_client_id(); } inline const std::string& Session::_internal_client_id() const { return client_id_.Get(); } inline void Session::_internal_set_client_id(const std::string& value) { client_id_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena()); } inline void Session::set_client_id(std::string&& value) { client_id_.Set( ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena()); // @@protoc_insertion_point(field_set_rvalue:smart3dmap.v1.Session.client_id) } inline void Session::set_client_id(const char* value) { GOOGLE_DCHECK(value != nullptr); client_id_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena()); // @@protoc_insertion_point(field_set_char:smart3dmap.v1.Session.client_id) } inline void Session::set_client_id(const char* value, size_t size) { client_id_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string( reinterpret_cast<const char*>(value), size), GetArena()); // @@protoc_insertion_point(field_set_pointer:smart3dmap.v1.Session.client_id) } inline std::string* Session::_internal_mutable_client_id() { return client_id_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena()); } inline std::string* Session::release_client_id() { // @@protoc_insertion_point(field_release:smart3dmap.v1.Session.client_id) return client_id_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void Session::set_allocated_client_id(std::string* client_id) { if (client_id != nullptr) { } else { } client_id_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), client_id, GetArena()); // @@protoc_insertion_point(field_set_allocated:smart3dmap.v1.Session.client_id) } // .google.protobuf.Timestamp createdAt = 4; inline bool Session::_internal_has_createdat() const { return this != internal_default_instance() && createdat_ != nullptr; } inline bool Session::has_createdat() const { return _internal_has_createdat(); } inline const PROTOBUF_NAMESPACE_ID::Timestamp& Session::_internal_createdat() const { const PROTOBUF_NAMESPACE_ID::Timestamp* p = createdat_; return p != nullptr ? *p : reinterpret_cast<const PROTOBUF_NAMESPACE_ID::Timestamp&>( PROTOBUF_NAMESPACE_ID::_Timestamp_default_instance_); } inline const PROTOBUF_NAMESPACE_ID::Timestamp& Session::createdat() const { // @@protoc_insertion_point(field_get:smart3dmap.v1.Session.createdAt) return _internal_createdat(); } inline void Session::unsafe_arena_set_allocated_createdat( PROTOBUF_NAMESPACE_ID::Timestamp* createdat) { if (GetArena() == nullptr) { delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(createdat_); } createdat_ = createdat; if (createdat) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:smart3dmap.v1.Session.createdAt) } inline PROTOBUF_NAMESPACE_ID::Timestamp* Session::release_createdat() { PROTOBUF_NAMESPACE_ID::Timestamp* temp = createdat_; createdat_ = nullptr; if (GetArena() != nullptr) { temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } return temp; } inline PROTOBUF_NAMESPACE_ID::Timestamp* Session::unsafe_arena_release_createdat() { // @@protoc_insertion_point(field_release:smart3dmap.v1.Session.createdAt) PROTOBUF_NAMESPACE_ID::Timestamp* temp = createdat_; createdat_ = nullptr; return temp; } inline PROTOBUF_NAMESPACE_ID::Timestamp* Session::_internal_mutable_createdat() { if (createdat_ == nullptr) { auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::Timestamp>(GetArena()); createdat_ = p; } return createdat_; } inline PROTOBUF_NAMESPACE_ID::Timestamp* Session::mutable_createdat() { // @@protoc_insertion_point(field_mutable:smart3dmap.v1.Session.createdAt) return _internal_mutable_createdat(); } inline void Session::set_allocated_createdat(PROTOBUF_NAMESPACE_ID::Timestamp* createdat) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena(); if (message_arena == nullptr) { delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(createdat_); } if (createdat) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(createdat)->GetArena(); if (message_arena != submessage_arena) { createdat = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, createdat, submessage_arena); } } else { } createdat_ = createdat; // @@protoc_insertion_point(field_set_allocated:smart3dmap.v1.Session.createdAt) } // .google.protobuf.Timestamp updatedAt = 5; inline bool Session::_internal_has_updatedat() const { return this != internal_default_instance() && updatedat_ != nullptr; } inline bool Session::has_updatedat() const { return _internal_has_updatedat(); } inline const PROTOBUF_NAMESPACE_ID::Timestamp& Session::_internal_updatedat() const { const PROTOBUF_NAMESPACE_ID::Timestamp* p = updatedat_; return p != nullptr ? *p : reinterpret_cast<const PROTOBUF_NAMESPACE_ID::Timestamp&>( PROTOBUF_NAMESPACE_ID::_Timestamp_default_instance_); } inline const PROTOBUF_NAMESPACE_ID::Timestamp& Session::updatedat() const { // @@protoc_insertion_point(field_get:smart3dmap.v1.Session.updatedAt) return _internal_updatedat(); } inline void Session::unsafe_arena_set_allocated_updatedat( PROTOBUF_NAMESPACE_ID::Timestamp* updatedat) { if (GetArena() == nullptr) { delete reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(updatedat_); } updatedat_ = updatedat; if (updatedat) { } else { } // @@protoc_insertion_point(field_unsafe_arena_set_allocated:smart3dmap.v1.Session.updatedAt) } inline PROTOBUF_NAMESPACE_ID::Timestamp* Session::release_updatedat() { PROTOBUF_NAMESPACE_ID::Timestamp* temp = updatedat_; updatedat_ = nullptr; if (GetArena() != nullptr) { temp = ::PROTOBUF_NAMESPACE_ID::internal::DuplicateIfNonNull(temp); } return temp; } inline PROTOBUF_NAMESPACE_ID::Timestamp* Session::unsafe_arena_release_updatedat() { // @@protoc_insertion_point(field_release:smart3dmap.v1.Session.updatedAt) PROTOBUF_NAMESPACE_ID::Timestamp* temp = updatedat_; updatedat_ = nullptr; return temp; } inline PROTOBUF_NAMESPACE_ID::Timestamp* Session::_internal_mutable_updatedat() { if (updatedat_ == nullptr) { auto* p = CreateMaybeMessage<PROTOBUF_NAMESPACE_ID::Timestamp>(GetArena()); updatedat_ = p; } return updatedat_; } inline PROTOBUF_NAMESPACE_ID::Timestamp* Session::mutable_updatedat() { // @@protoc_insertion_point(field_mutable:smart3dmap.v1.Session.updatedAt) return _internal_mutable_updatedat(); } inline void Session::set_allocated_updatedat(PROTOBUF_NAMESPACE_ID::Timestamp* updatedat) { ::PROTOBUF_NAMESPACE_ID::Arena* message_arena = GetArena(); if (message_arena == nullptr) { delete reinterpret_cast< ::PROTOBUF_NAMESPACE_ID::MessageLite*>(updatedat_); } if (updatedat) { ::PROTOBUF_NAMESPACE_ID::Arena* submessage_arena = reinterpret_cast<::PROTOBUF_NAMESPACE_ID::MessageLite*>(updatedat)->GetArena(); if (message_arena != submessage_arena) { updatedat = ::PROTOBUF_NAMESPACE_ID::internal::GetOwnedMessage( message_arena, updatedat, submessage_arena); } } else { } updatedat_ = updatedat; // @@protoc_insertion_point(field_set_allocated:smart3dmap.v1.Session.updatedAt) } // ------------------------------------------------------------------- // CreateSessionRequest // string email = 1; inline void CreateSessionRequest::clear_email() { email_.ClearToEmpty(); } inline const std::string& CreateSessionRequest::email() const { // @@protoc_insertion_point(field_get:smart3dmap.v1.CreateSessionRequest.email) return _internal_email(); } inline void CreateSessionRequest::set_email(const std::string& value) { _internal_set_email(value); // @@protoc_insertion_point(field_set:smart3dmap.v1.CreateSessionRequest.email) } inline std::string* CreateSessionRequest::mutable_email() { // @@protoc_insertion_point(field_mutable:smart3dmap.v1.CreateSessionRequest.email) return _internal_mutable_email(); } inline const std::string& CreateSessionRequest::_internal_email() const { return email_.Get(); } inline void CreateSessionRequest::_internal_set_email(const std::string& value) { email_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena()); } inline void CreateSessionRequest::set_email(std::string&& value) { email_.Set( ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena()); // @@protoc_insertion_point(field_set_rvalue:smart3dmap.v1.CreateSessionRequest.email) } inline void CreateSessionRequest::set_email(const char* value) { GOOGLE_DCHECK(value != nullptr); email_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena()); // @@protoc_insertion_point(field_set_char:smart3dmap.v1.CreateSessionRequest.email) } inline void CreateSessionRequest::set_email(const char* value, size_t size) { email_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string( reinterpret_cast<const char*>(value), size), GetArena()); // @@protoc_insertion_point(field_set_pointer:smart3dmap.v1.CreateSessionRequest.email) } inline std::string* CreateSessionRequest::_internal_mutable_email() { return email_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena()); } inline std::string* CreateSessionRequest::release_email() { // @@protoc_insertion_point(field_release:smart3dmap.v1.CreateSessionRequest.email) return email_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void CreateSessionRequest::set_allocated_email(std::string* email) { if (email != nullptr) { } else { } email_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), email, GetArena()); // @@protoc_insertion_point(field_set_allocated:smart3dmap.v1.CreateSessionRequest.email) } // string password = 2; inline void CreateSessionRequest::clear_password() { password_.ClearToEmpty(); } inline const std::string& CreateSessionRequest::password() const { // @@protoc_insertion_point(field_get:smart3dmap.v1.CreateSessionRequest.password) return _internal_password(); } inline void CreateSessionRequest::set_password(const std::string& value) { _internal_set_password(value); // @@protoc_insertion_point(field_set:smart3dmap.v1.CreateSessionRequest.password) } inline std::string* CreateSessionRequest::mutable_password() { // @@protoc_insertion_point(field_mutable:smart3dmap.v1.CreateSessionRequest.password) return _internal_mutable_password(); } inline const std::string& CreateSessionRequest::_internal_password() const { return password_.Get(); } inline void CreateSessionRequest::_internal_set_password(const std::string& value) { password_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena()); } inline void CreateSessionRequest::set_password(std::string&& value) { password_.Set( ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena()); // @@protoc_insertion_point(field_set_rvalue:smart3dmap.v1.CreateSessionRequest.password) } inline void CreateSessionRequest::set_password(const char* value) { GOOGLE_DCHECK(value != nullptr); password_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena()); // @@protoc_insertion_point(field_set_char:smart3dmap.v1.CreateSessionRequest.password) } inline void CreateSessionRequest::set_password(const char* value, size_t size) { password_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string( reinterpret_cast<const char*>(value), size), GetArena()); // @@protoc_insertion_point(field_set_pointer:smart3dmap.v1.CreateSessionRequest.password) } inline std::string* CreateSessionRequest::_internal_mutable_password() { return password_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena()); } inline std::string* CreateSessionRequest::release_password() { // @@protoc_insertion_point(field_release:smart3dmap.v1.CreateSessionRequest.password) return password_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void CreateSessionRequest::set_allocated_password(std::string* password) { if (password != nullptr) { } else { } password_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), password, GetArena()); // @@protoc_insertion_point(field_set_allocated:smart3dmap.v1.CreateSessionRequest.password) } // string client_id = 3; inline void CreateSessionRequest::clear_client_id() { client_id_.ClearToEmpty(); } inline const std::string& CreateSessionRequest::client_id() const { // @@protoc_insertion_point(field_get:smart3dmap.v1.CreateSessionRequest.client_id) return _internal_client_id(); } inline void CreateSessionRequest::set_client_id(const std::string& value) { _internal_set_client_id(value); // @@protoc_insertion_point(field_set:smart3dmap.v1.CreateSessionRequest.client_id) } inline std::string* CreateSessionRequest::mutable_client_id() { // @@protoc_insertion_point(field_mutable:smart3dmap.v1.CreateSessionRequest.client_id) return _internal_mutable_client_id(); } inline const std::string& CreateSessionRequest::_internal_client_id() const { return client_id_.Get(); } inline void CreateSessionRequest::_internal_set_client_id(const std::string& value) { client_id_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena()); } inline void CreateSessionRequest::set_client_id(std::string&& value) { client_id_.Set( ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena()); // @@protoc_insertion_point(field_set_rvalue:smart3dmap.v1.CreateSessionRequest.client_id) } inline void CreateSessionRequest::set_client_id(const char* value) { GOOGLE_DCHECK(value != nullptr); client_id_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena()); // @@protoc_insertion_point(field_set_char:smart3dmap.v1.CreateSessionRequest.client_id) } inline void CreateSessionRequest::set_client_id(const char* value, size_t size) { client_id_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string( reinterpret_cast<const char*>(value), size), GetArena()); // @@protoc_insertion_point(field_set_pointer:smart3dmap.v1.CreateSessionRequest.client_id) } inline std::string* CreateSessionRequest::_internal_mutable_client_id() { return client_id_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena()); } inline std::string* CreateSessionRequest::release_client_id() { // @@protoc_insertion_point(field_release:smart3dmap.v1.CreateSessionRequest.client_id) return client_id_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void CreateSessionRequest::set_allocated_client_id(std::string* client_id) { if (client_id != nullptr) { } else { } client_id_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), client_id, GetArena()); // @@protoc_insertion_point(field_set_allocated:smart3dmap.v1.CreateSessionRequest.client_id) } // ------------------------------------------------------------------- // GetSessionRequest // string token = 1; inline void GetSessionRequest::clear_token() { token_.ClearToEmpty(); } inline const std::string& GetSessionRequest::token() const { // @@protoc_insertion_point(field_get:smart3dmap.v1.GetSessionRequest.token) return _internal_token(); } inline void GetSessionRequest::set_token(const std::string& value) { _internal_set_token(value); // @@protoc_insertion_point(field_set:smart3dmap.v1.GetSessionRequest.token) } inline std::string* GetSessionRequest::mutable_token() { // @@protoc_insertion_point(field_mutable:smart3dmap.v1.GetSessionRequest.token) return _internal_mutable_token(); } inline const std::string& GetSessionRequest::_internal_token() const { return token_.Get(); } inline void GetSessionRequest::_internal_set_token(const std::string& value) { token_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena()); } inline void GetSessionRequest::set_token(std::string&& value) { token_.Set( ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena()); // @@protoc_insertion_point(field_set_rvalue:smart3dmap.v1.GetSessionRequest.token) } inline void GetSessionRequest::set_token(const char* value) { GOOGLE_DCHECK(value != nullptr); token_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena()); // @@protoc_insertion_point(field_set_char:smart3dmap.v1.GetSessionRequest.token) } inline void GetSessionRequest::set_token(const char* value, size_t size) { token_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string( reinterpret_cast<const char*>(value), size), GetArena()); // @@protoc_insertion_point(field_set_pointer:smart3dmap.v1.GetSessionRequest.token) } inline std::string* GetSessionRequest::_internal_mutable_token() { return token_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena()); } inline std::string* GetSessionRequest::release_token() { // @@protoc_insertion_point(field_release:smart3dmap.v1.GetSessionRequest.token) return token_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void GetSessionRequest::set_allocated_token(std::string* token) { if (token != nullptr) { } else { } token_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), token, GetArena()); // @@protoc_insertion_point(field_set_allocated:smart3dmap.v1.GetSessionRequest.token) } // ------------------------------------------------------------------- // DeleteSessionRequest // string token = 1; inline void DeleteSessionRequest::clear_token() { token_.ClearToEmpty(); } inline const std::string& DeleteSessionRequest::token() const { // @@protoc_insertion_point(field_get:smart3dmap.v1.DeleteSessionRequest.token) return _internal_token(); } inline void DeleteSessionRequest::set_token(const std::string& value) { _internal_set_token(value); // @@protoc_insertion_point(field_set:smart3dmap.v1.DeleteSessionRequest.token) } inline std::string* DeleteSessionRequest::mutable_token() { // @@protoc_insertion_point(field_mutable:smart3dmap.v1.DeleteSessionRequest.token) return _internal_mutable_token(); } inline const std::string& DeleteSessionRequest::_internal_token() const { return token_.Get(); } inline void DeleteSessionRequest::_internal_set_token(const std::string& value) { token_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, value, GetArena()); } inline void DeleteSessionRequest::set_token(std::string&& value) { token_.Set( ::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::move(value), GetArena()); // @@protoc_insertion_point(field_set_rvalue:smart3dmap.v1.DeleteSessionRequest.token) } inline void DeleteSessionRequest::set_token(const char* value) { GOOGLE_DCHECK(value != nullptr); token_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string(value), GetArena()); // @@protoc_insertion_point(field_set_char:smart3dmap.v1.DeleteSessionRequest.token) } inline void DeleteSessionRequest::set_token(const char* value, size_t size) { token_.Set(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, ::std::string( reinterpret_cast<const char*>(value), size), GetArena()); // @@protoc_insertion_point(field_set_pointer:smart3dmap.v1.DeleteSessionRequest.token) } inline std::string* DeleteSessionRequest::_internal_mutable_token() { return token_.Mutable(::PROTOBUF_NAMESPACE_ID::internal::ArenaStringPtr::EmptyDefault{}, GetArena()); } inline std::string* DeleteSessionRequest::release_token() { // @@protoc_insertion_point(field_release:smart3dmap.v1.DeleteSessionRequest.token) return token_.Release(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), GetArena()); } inline void DeleteSessionRequest::set_allocated_token(std::string* token) { if (token != nullptr) { } else { } token_.SetAllocated(&::PROTOBUF_NAMESPACE_ID::internal::GetEmptyStringAlreadyInited(), token, GetArena()); // @@protoc_insertion_point(field_set_allocated:smart3dmap.v1.DeleteSessionRequest.token) } #ifdef __GNUC__ #pragma GCC diagnostic pop #endif // __GNUC__ // ------------------------------------------------------------------- // ------------------------------------------------------------------- // ------------------------------------------------------------------- // @@protoc_insertion_point(namespace_scope) } // namespace v1 } // namespace smart3dmap // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc> #endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_sessions_2fsessions_2eproto
38.419034
141
0.740951
[ "object" ]
f9c8abc833d56a13ec780544e3207647dd6b4660
18,479
h
C
Headers/java/lang/Long.h
tcak76/j2objc
bb9415df98c3fdd1e5e3f4b9e27049d0b2e42633
[ "MIT" ]
11
2015-12-10T13:23:54.000Z
2019-04-23T02:41:13.000Z
Headers/java/lang/Long.h
tcak76/j2objc
bb9415df98c3fdd1e5e3f4b9e27049d0b2e42633
[ "MIT" ]
7
2015-11-05T22:45:53.000Z
2017-11-05T14:36:36.000Z
Headers/java/lang/Long.h
tcak76/j2objc
bb9415df98c3fdd1e5e3f4b9e27049d0b2e42633
[ "MIT" ]
40
2015-12-10T07:30:58.000Z
2022-03-15T02:50:10.000Z
// // Generated by the J2ObjC translator. DO NOT EDIT! // source: android/libcore/luni/src/main/java/java/lang/Long.java // #include "../../J2ObjC_header.h" #pragma push_macro("INCLUDE_ALL_JavaLangLong") #ifdef RESTRICT_JavaLangLong #define INCLUDE_ALL_JavaLangLong 0 #else #define INCLUDE_ALL_JavaLangLong 1 #endif #undef RESTRICT_JavaLangLong #pragma clang diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #if !defined (JavaLangLong_) && (INCLUDE_ALL_JavaLangLong || defined(INCLUDE_JavaLangLong)) #define JavaLangLong_ #define RESTRICT_JavaLangComparable 1 #define INCLUDE_JavaLangComparable 1 #include "../../java/lang/Comparable.h" @class IOSClass; /*! @brief The wrapper for the primitive type <code>long</code>. <p> Implementation note: The "bit twiddling" methods in this class use techniques described in <a href="http://www.hackersdelight.org/">Henry S. Warren, Jr.'s Hacker's Delight, (Addison Wesley, 2002)</a> and <a href= "http://graphics.stanford.edu/~seander/bithacks.html">Sean Anderson's Bit Twiddling Hacks.</a> - seealso: java.lang.Integer @since 1.0 */ @interface JavaLangLong : NSNumber < JavaLangComparable > + (jlong)MAX_VALUE; + (jlong)MIN_VALUE; + (IOSClass *)TYPE; + (jint)SIZE; #pragma mark Public /*! @brief Constructs a new <code>Long</code> with the specified primitive long value. @param value the primitive long value to store in the new instance. */ - (instancetype)initWithLong:(jlong)value; /*! @brief Constructs a new <code>Long</code> from the specified string. @param string the string representation of a long value. @throws NumberFormatException if <code>string</code> cannot be parsed as a long value. - seealso: #parseLong(String) */ - (instancetype)initWithNSString:(NSString *)string; /*! @brief Counts the number of 1 bits in the specified long value; this is also referred to as population count. @param v the long to examine. @return the number of 1 bits in <code>v</code>. @since 1.5 */ + (jint)bitCountWithLong:(jlong)v; - (jbyte)charValue; /*! @brief Compares two <code>long</code> values. @return 0 if lhs = rhs, less than 0 if lhs &lt; rhs, and greater than 0 if lhs &gt; rhs. @since 1.7 */ + (jint)compareWithLong:(jlong)lhs withLong:(jlong)rhs; /*! @brief Compares this object to the specified long object to determine their relative order. @param object the long object to compare this object to. @return a negative value if the value of this long is less than the value of <code>object</code>; 0 if the value of this long and the value of <code>object</code> are equal; a positive value if the value of this long is greater than the value of <code>object</code>. - seealso: java.lang.Comparable @since 1.2 */ - (jint)compareToWithId:(JavaLangLong *)object; /*! @brief Parses the specified string and returns a <code>Long</code> instance if the string can be decoded into a long value. The string may be an optional optional sign character ("-" or "+") followed by a hexadecimal ("0x..." or "#..."), octal ("0..."), or decimal ("...") representation of a long. @param string a string representation of a long value. @return a <code>Long</code> containing the value represented by <code>string</code>. @throws NumberFormatException if <code>string</code> cannot be parsed as a long value. */ + (JavaLangLong *)decodeWithNSString:(NSString *)string; - (jdouble)doubleValue; /*! @brief Compares this instance with the specified object and indicates if they are equal. In order to be equal, <code>o</code> must be an instance of <code>Long</code> and have the same long value as this object. @param o the object to compare this long with. @return <code>true</code> if the specified object is equal to this <code>Long</code>; <code>false</code> otherwise. */ - (jboolean)isEqual:(id)o; - (jfloat)floatValue; /*! @brief Returns the <code>Long</code> value of the system property identified by <code>string</code>. Returns <code>null</code> if <code>string</code> is <code>null</code> or empty, if the property can not be found or if its value can not be parsed as a long. @param string the name of the requested system property. @return the requested property's value as a <code>Long</code> or <code>null</code>. */ + (JavaLangLong *)getLongWithNSString:(NSString *)string; /*! @brief Returns the <code>Long</code> value of the system property identified by <code>string</code>. Returns the specified default value if <code>string</code> is <code>null</code> or empty, if the property can not be found or if its value can not be parsed as a long. @param string the name of the requested system property. @param defaultValue the default value that is returned if there is no long system property with the requested name. @return the requested property's value as a <code>Long</code> or the default value. */ + (JavaLangLong *)getLongWithNSString:(NSString *)string withLong:(jlong)defaultValue; /*! @brief Returns the <code>Long</code> value of the system property identified by <code>string</code>. Returns the specified default value if <code>string</code> is <code>null</code> or empty, if the property can not be found or if its value can not be parsed as a long. @param string the name of the requested system property. @param defaultValue the default value that is returned if there is no long system property with the requested name. @return the requested property's value as a <code>Long</code> or the default value. */ + (JavaLangLong *)getLongWithNSString:(NSString *)string withJavaLangLong:(JavaLangLong *)defaultValue; - (NSUInteger)hash; /*! @brief Determines the highest (leftmost) bit of the specified long value that is 1 and returns the bit mask value for that bit. This is also referred to as the Most Significant 1 Bit. Returns zero if the specified long is zero. @param v the long to examine. @return the bit mask indicating the highest 1 bit in <code>v</code>. @since 1.5 */ + (jlong)highestOneBitWithLong:(jlong)v; - (jint)intValue; /*! @brief Gets the primitive value of this long. @return this object's primitive value. */ - (jlong)longLongValue; /*! @brief Determines the lowest (rightmost) bit of the specified long value that is 1 and returns the bit mask value for that bit. This is also referred to as the Least Significant 1 Bit. Returns zero if the specified long is zero. @param v the long to examine. @return the bit mask indicating the lowest 1 bit in <code>v</code>. @since 1.5 */ + (jlong)lowestOneBitWithLong:(jlong)v; /*! @brief Determines the number of leading zeros in the specified long value prior to the <code>highest one bit</code>. @param v the long to examine. @return the number of leading zeros in <code>v</code>. @since 1.5 */ + (jint)numberOfLeadingZerosWithLong:(jlong)v; /*! @brief Determines the number of trailing zeros in the specified long value after the <code>lowest one bit</code>. @param v the long to examine. @return the number of trailing zeros in <code>v</code>. @since 1.5 */ + (jint)numberOfTrailingZerosWithLong:(jlong)v; /*! @brief Parses the specified string as a signed decimal long value. The ASCII characters \u002d ('-') and \u002b ('+') are recognized as the minus and plus signs. @param string the string representation of a long value. @return the primitive long value represented by <code>string</code>. @throws NumberFormatException if <code>string</code> cannot be parsed as a long value. */ + (jlong)parseLongWithNSString:(NSString *)string; /*! @brief Parses the specified string as a signed long value using the specified radix. The ASCII characters \u002d ('-') and \u002b ('+') are recognized as the minus and plus signs. @param string the string representation of a long value. @param radix the radix to use when parsing. @return the primitive long value represented by <code>string</code> using <code>radix</code>. @throws NumberFormatException if <code>string</code> cannot be parsed as a long value, or <code>radix < Character.MIN_RADIX || radix > Character.MAX_RADIX</code> . */ + (jlong)parseLongWithNSString:(NSString *)string withInt:(jint)radix; /*! @brief Equivalent to <code>parsePositiveLong(string, 10)</code>. - seealso: #parsePositiveLong(String,int) */ + (jlong)parsePositiveLongWithNSString:(NSString *)string; /*! @brief Parses the specified string as a positive long value using the specified radix. 0 is considered a positive long. <p> This method behaves the same as <code>parseLong(String,int)</code> except that it disallows leading '+' and '-' characters. See that method for error conditions. - seealso: #parseLong(String,int) */ + (jlong)parsePositiveLongWithNSString:(NSString *)string withInt:(jint)radix; /*! @brief Reverses the order of the bits of the specified long value. @param v the long value for which to reverse the bit order. @return the reversed value. @since 1.5 */ + (jlong)reverseWithLong:(jlong)v; /*! @brief Reverses the order of the bytes of the specified long value. @param v the long value for which to reverse the byte order. @return the reversed value. @since 1.5 */ + (jlong)reverseBytesWithLong:(jlong)v; /*! @brief Rotates the bits of the specified long value to the left by the specified number of bits. @param v the long value to rotate left. @param distance the number of bits to rotate. @return the rotated value. @since 1.5 */ + (jlong)rotateLeftWithLong:(jlong)v withInt:(jint)distance; /*! @brief Rotates the bits of the specified long value to the right by the specified number of bits. @param v the long value to rotate right. @param distance the number of bits to rotate. @return the rotated value. @since 1.5 */ + (jlong)rotateRightWithLong:(jlong)v withInt:(jint)distance; - (jshort)shortValue; /*! @brief Returns the value of the <code>signum</code> function for the specified long value. @param v the long value to check. @return -1 if <code>v</code> is negative, 1 if <code>v</code> is positive, 0 if <code>v</code> is zero. @since 1.5 */ + (jint)signumWithLong:(jlong)v; /*! @brief Converts the specified long value into its binary string representation. The returned string is a concatenation of '0' and '1' characters. @param v the long value to convert. @return the binary string representation of <code>v</code>. */ + (NSString *)toBinaryStringWithLong:(jlong)v; /*! @brief Converts the specified long value into its hexadecimal string representation. The returned string is a concatenation of characters from '0' to '9' and 'a' to 'f'. @param v the long value to convert. @return the hexadecimal string representation of <code>l</code>. */ + (NSString *)toHexStringWithLong:(jlong)v; /*! @brief Converts the specified long value into its octal string representation. The returned string is a concatenation of characters from '0' to '7'. @param v the long value to convert. @return the octal string representation of <code>l</code>. */ + (NSString *)toOctalStringWithLong:(jlong)v; - (NSString *)description; /*! @brief Converts the specified long value into its decimal string representation. The returned string is a concatenation of a minus sign if the number is negative and characters from '0' to '9'. @param n the long to convert. @return the decimal string representation of <code>l</code>. */ + (NSString *)toStringWithLong:(jlong)n; /*! @brief Converts the specified signed long value into a string representation based on the specified radix. The returned string is a concatenation of a minus sign if the number is negative and characters from '0' to '9' and 'a' to 'z', depending on the radix. If <code>radix</code> is not in the interval defined by <code>Character.MIN_RADIX</code> and <code>Character.MAX_RADIX</code> then 10 is used as the base for the conversion. <p>This method treats its argument as signed. If you want to convert an unsigned value to one of the common non-decimal bases, you may find <code>toBinaryString</code>, <code>#toHexString</code>, or <code>toOctalString</code> more convenient. @param v the signed long to convert. @param radix the base to use for the conversion. @return the string representation of <code>v</code>. */ + (NSString *)toStringWithLong:(jlong)v withInt:(jint)radix; /*! @brief Returns a <code>Long</code> instance for the specified long value. <p> If it is not necessary to get a new <code>Long</code> instance, it is recommended to use this method instead of the constructor, since it maintains a cache of instances which may result in better performance. @param v the long value to store in the instance. @return a <code>Long</code> instance containing <code>v</code>. @since 1.5 */ + (JavaLangLong *)valueOfWithLong:(jlong)v; /*! @brief Parses the specified string as a signed decimal long value. @param string the string representation of a long value. @return a <code>Long</code> instance containing the long value represented by <code>string</code>. @throws NumberFormatException if <code>string</code> cannot be parsed as a long value. - seealso: #parseLong(String) */ + (JavaLangLong *)valueOfWithNSString:(NSString *)string; /*! @brief Parses the specified string as a signed long value using the specified radix. @param string the string representation of a long value. @param radix the radix to use when parsing. @return a <code>Long</code> instance containing the long value represented by <code>string</code> using <code>radix</code>. @throws NumberFormatException if <code>string</code> cannot be parsed as a long value, or <code>radix < Character.MIN_RADIX || radix > Character.MAX_RADIX</code> . - seealso: #parseLong(String,int) */ + (JavaLangLong *)valueOfWithNSString:(NSString *)string withInt:(jint)radix; #pragma mark Package-Private @end J2OBJC_STATIC_INIT(JavaLangLong) /*! @brief Constant for the maximum <code>long</code> value, 2<sup>63</sup>-1. */ inline jlong JavaLangLong_get_MAX_VALUE(); #define JavaLangLong_MAX_VALUE 9223372036854775807LL J2OBJC_STATIC_FIELD_CONSTANT(JavaLangLong, MAX_VALUE, jlong) /*! @brief Constant for the minimum <code>long</code> value, -2<sup>63</sup>. */ inline jlong JavaLangLong_get_MIN_VALUE(); #define JavaLangLong_MIN_VALUE ((jlong) 0x8000000000000000LL) J2OBJC_STATIC_FIELD_CONSTANT(JavaLangLong, MIN_VALUE, jlong) /*! @brief The <code>Class</code> object that represents the primitive type <code>long</code>. */ inline IOSClass *JavaLangLong_get_TYPE(); /*! INTERNAL ONLY - Use accessor function from above. */ FOUNDATION_EXPORT IOSClass *JavaLangLong_TYPE; J2OBJC_STATIC_FIELD_OBJ_FINAL(JavaLangLong, TYPE, IOSClass *) /*! @brief Constant for the number of bits needed to represent a <code>long</code> in two's complement form. @since 1.5 */ inline jint JavaLangLong_get_SIZE(); #define JavaLangLong_SIZE 64 J2OBJC_STATIC_FIELD_CONSTANT(JavaLangLong, SIZE, jint) FOUNDATION_EXPORT void JavaLangLong_initWithLong_(JavaLangLong *self, jlong value); FOUNDATION_EXPORT JavaLangLong *new_JavaLangLong_initWithLong_(jlong value) NS_RETURNS_RETAINED; FOUNDATION_EXPORT JavaLangLong *create_JavaLangLong_initWithLong_(jlong value); FOUNDATION_EXPORT void JavaLangLong_initWithNSString_(JavaLangLong *self, NSString *string); FOUNDATION_EXPORT JavaLangLong *new_JavaLangLong_initWithNSString_(NSString *string) NS_RETURNS_RETAINED; FOUNDATION_EXPORT JavaLangLong *create_JavaLangLong_initWithNSString_(NSString *string); FOUNDATION_EXPORT jint JavaLangLong_compareWithLong_withLong_(jlong lhs, jlong rhs); FOUNDATION_EXPORT JavaLangLong *JavaLangLong_decodeWithNSString_(NSString *string); FOUNDATION_EXPORT JavaLangLong *JavaLangLong_getLongWithNSString_(NSString *string); FOUNDATION_EXPORT JavaLangLong *JavaLangLong_getLongWithNSString_withLong_(NSString *string, jlong defaultValue); FOUNDATION_EXPORT JavaLangLong *JavaLangLong_getLongWithNSString_withJavaLangLong_(NSString *string, JavaLangLong *defaultValue); FOUNDATION_EXPORT jlong JavaLangLong_parseLongWithNSString_(NSString *string); FOUNDATION_EXPORT jlong JavaLangLong_parseLongWithNSString_withInt_(NSString *string, jint radix); FOUNDATION_EXPORT jlong JavaLangLong_parsePositiveLongWithNSString_(NSString *string); FOUNDATION_EXPORT jlong JavaLangLong_parsePositiveLongWithNSString_withInt_(NSString *string, jint radix); FOUNDATION_EXPORT NSString *JavaLangLong_toBinaryStringWithLong_(jlong v); FOUNDATION_EXPORT NSString *JavaLangLong_toHexStringWithLong_(jlong v); FOUNDATION_EXPORT NSString *JavaLangLong_toOctalStringWithLong_(jlong v); FOUNDATION_EXPORT NSString *JavaLangLong_toStringWithLong_(jlong n); FOUNDATION_EXPORT NSString *JavaLangLong_toStringWithLong_withInt_(jlong v, jint radix); FOUNDATION_EXPORT JavaLangLong *JavaLangLong_valueOfWithNSString_(NSString *string); FOUNDATION_EXPORT JavaLangLong *JavaLangLong_valueOfWithNSString_withInt_(NSString *string, jint radix); FOUNDATION_EXPORT jlong JavaLangLong_highestOneBitWithLong_(jlong v); FOUNDATION_EXPORT jlong JavaLangLong_lowestOneBitWithLong_(jlong v); FOUNDATION_EXPORT jint JavaLangLong_numberOfLeadingZerosWithLong_(jlong v); FOUNDATION_EXPORT jint JavaLangLong_numberOfTrailingZerosWithLong_(jlong v); FOUNDATION_EXPORT jint JavaLangLong_bitCountWithLong_(jlong v); FOUNDATION_EXPORT jlong JavaLangLong_rotateLeftWithLong_withInt_(jlong v, jint distance); FOUNDATION_EXPORT jlong JavaLangLong_rotateRightWithLong_withInt_(jlong v, jint distance); FOUNDATION_EXPORT jlong JavaLangLong_reverseBytesWithLong_(jlong v); FOUNDATION_EXPORT jlong JavaLangLong_reverseWithLong_(jlong v); FOUNDATION_EXPORT jint JavaLangLong_signumWithLong_(jlong v); FOUNDATION_EXPORT JavaLangLong *JavaLangLong_valueOfWithLong_(jlong v); J2OBJC_TYPE_LITERAL_HEADER(JavaLangLong) BOXED_INC_AND_DEC(Long, longLongValue, JavaLangLong) BOXED_COMPOUND_ASSIGN_ARITHMETIC(Long, longLongValue, jlong, JavaLangLong) BOXED_COMPOUND_ASSIGN_MOD(Long, longLongValue, jlong, JavaLangLong) BOXED_COMPOUND_ASSIGN_BITWISE(Long, longLongValue, jlong, JavaLangLong) BOXED_SHIFT_ASSIGN_64(Long, longLongValue, jlong, JavaLangLong) #endif #pragma clang diagnostic pop #pragma pop_macro("INCLUDE_ALL_JavaLangLong")
32.764184
129
0.756264
[ "object" ]
f9c8b755682de772969aeea21d44b10b34ac986c
21,030
h
C
Util/OSM2ODR/src/netimport/vissim/NIImporter_Vissim.h
adelbennaceur/carla
4d6fefe73d38f0ffaef8ffafccf71245699fc5db
[ "MIT" ]
5
2020-12-14T00:33:42.000Z
2021-12-22T07:41:49.000Z
Util/OSM2ODR/src/netimport/vissim/NIImporter_Vissim.h
adelbennaceur/carla
4d6fefe73d38f0ffaef8ffafccf71245699fc5db
[ "MIT" ]
2
2021-03-31T20:10:04.000Z
2021-12-13T20:48:30.000Z
Util/OSM2ODR/src/netimport/vissim/NIImporter_Vissim.h
adelbennaceur/carla
4d6fefe73d38f0ffaef8ffafccf71245699fc5db
[ "MIT" ]
4
2021-04-15T03:45:53.000Z
2021-12-24T13:13:39.000Z
/****************************************************************************/ // Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo // Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. // This program and the accompanying materials are made available under the // terms of the Eclipse Public License 2.0 which is available at // https://www.eclipse.org/legal/epl-2.0/ // This Source Code may also be made available under the following Secondary // Licenses when the conditions for such availability set forth in the Eclipse // Public License 2.0 are satisfied: GNU General Public License, version 2 // or later which is available at // https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later /****************************************************************************/ /// @file NIImporter_Vissim.h /// @author Daniel Krajzewicz /// @author Michael Behrisch /// @author Lukas Grohmann (AIT) /// @author Gerald Richter (AIT) /// @date Sept 2002 /// // Importer for networks stored in Vissim format /****************************************************************************/ #pragma once #include <config.h> #include <string> #include <map> #include <vector> #include <utils/common/RGBColor.h> #include <utils/geom/Position.h> #include "tempstructs/NIVissimExtendedEdgePoint.h" #include "NIVissimElements.h" #include <utils/xml/SUMOSAXHandler.h> #include "tempstructs/NIVissimEdge.h" #include "tempstructs/NIVissimConnection.h" #include "tempstructs/NIVissimConflictArea.h" #include <utils/common/StringBijection.h> #include <utils/common/StringTokenizer.h> #include <list> // =========================================================================== // class declarations // =========================================================================== class OptionsCont; class NBNetBuilder; // =========================================================================== // class definitions // =========================================================================== /** * @class NIImporter_Vissim * @brief Importer for networks stored in Vissim format */ class NIImporter_Vissim { public: /** @brief Loads network definition from the assigned option and stores it in the given network builder * * If the option "vissim-file" is set, the file stored therein is read and * the network definition stored therein is stored within the given network * builder. * * If the option "vissim-file" is not set, this method simply returns. * * @param[in] oc The options to use * @param[in] nb The network builder to fill */ static void loadNetwork(const OptionsCont& oc, NBNetBuilder& nb); private: typedef std::map<std::string, std::list<std::string> > nodeMap; nodeMap elementData; /** * @class NIVissimSingleTypeXMLHandler_Streckendefinition * @brief A class which extracts VISSIM-Strecken from a parsed VISSIM-file */ class NIVissimXMLHandler_Streckendefinition : public GenericSAXHandler { public: /** @brief Constructor * @param[in] strecken_dic The strecken dictionary to fill */ //NIVissimXMLHandler_Streckendefinition(std::map<int, VissimXMLEdge>& toFill); NIVissimXMLHandler_Streckendefinition(nodeMap& elemData); /// @brief Destructor ~NIVissimXMLHandler_Streckendefinition(); protected: /// @name inherited from GenericSAXHandler //@{ /** @brief Called on the opening of a tag; * * @param[in] element ID of the currently opened element * @param[in] attrs Attributes within the currently opened element * @exception ProcessError If something fails * @see GenericSAXHandler::myStartElement */ void myStartElement(int element, const SUMOSAXAttributes& attrs); //@} void myEndElement(int element); //@} private: //std::map<int, VissimXMLEdge> myToFill; nodeMap& myElemData; /// @brief The current hierarchy level int myHierarchyLevel; /// @brief check if the link is a connector bool isConnector; /// @brief ID of the currently parsed node, for reporting mainly int myLastNodeID; /** @brief invalidated copy constructor */ NIVissimXMLHandler_Streckendefinition(const NIVissimXMLHandler_Streckendefinition& s); /** @brief invalidated assignment operator */ NIVissimXMLHandler_Streckendefinition& operator=(const NIVissimXMLHandler_Streckendefinition& s); }; private: /** * @class NIVissimSingleTypeXMLHandler_Zuflussdefinition * @brief A class which extracts VISSIM-Zuflüsse from a parsed VISSIM-file */ class NIVissimXMLHandler_Zuflussdefinition : public GenericSAXHandler { public: /** @brief Constructor */ NIVissimXMLHandler_Zuflussdefinition(); /// @brief Destructor ~NIVissimXMLHandler_Zuflussdefinition(); protected: /// @name inherited from GenericSAXHandler //@{ /** @brief Called on the opening of a tag; * * @param[in] element ID of the currently opened element * @param[in] attrs Attributes within the currently opened element * @exception ProcessError If something fails * @see GenericSAXHandler::myStartElement */ void myStartElement(int element, const SUMOSAXAttributes& attrs); //@} private: /** @brief invalidated copy constructor */ NIVissimXMLHandler_Zuflussdefinition(const NIVissimXMLHandler_Zuflussdefinition& z); /** @brief invalidated assignment operator */ NIVissimXMLHandler_Zuflussdefinition& operator=(const NIVissimXMLHandler_Zuflussdefinition& z); }; private: /** * @class NIVissimSingleTypeXMLHandler_Parkplatzdefinition * @brief A class which extracts VISSIM-Parkplätze from a parsed VISSIM-file */ class NIVissimXMLHandler_Parkplatzdefinition : public GenericSAXHandler { public: /** @brief Constructor */ NIVissimXMLHandler_Parkplatzdefinition(); /// @brief Destructor ~NIVissimXMLHandler_Parkplatzdefinition(); protected: /// @name inherited from GenericSAXHandler //@{ /** @brief Called on the opening of a tag; * * @param[in] element ID of the currently opened element * @param[in] attrs Attributes within the currently opened element * @exception ProcessError If something fails * @see GenericSAXHandler::myStartElement */ void myStartElement(int element, const SUMOSAXAttributes& attrs); //@} private: /** @brief invalidated copy constructor */ NIVissimXMLHandler_Parkplatzdefinition(const NIVissimXMLHandler_Parkplatzdefinition& z); /** @brief invalidated assignment operator */ NIVissimXMLHandler_Parkplatzdefinition& operator=(const NIVissimXMLHandler_Parkplatzdefinition& z); }; private: /** * @class NIVissimSingleTypeXMLHandler_Fahrzeugklassendefinition * @brief A class which extracts VISSIM-Fahrzeugklassen from a parsed VISSIM-file */ class NIVissimXMLHandler_Fahrzeugklassendefinition : public GenericSAXHandler { public: /** @brief Constructor * @param[in] elemData The string container to fill */ NIVissimXMLHandler_Fahrzeugklassendefinition(nodeMap& elemData); /// @brief Destructor ~NIVissimXMLHandler_Fahrzeugklassendefinition(); protected: /// @name inherited from GenericSAXHandler //@{ /** @brief Called on the opening of a tag; * * @param[in] element ID of the currently opened element * @param[in] attrs Attributes within the currently opened element * @exception ProcessError If something fails * @see GenericSAXHandler::myStartElement */ void myStartElement(int element, const SUMOSAXAttributes& attrs); //@} void myEndElement(int element); //@} private: //std::map<int, VissimXMLEdge> myToFill; nodeMap& myElemData; /// @brief The current hierarchy level int myHierarchyLevel; /// @brief ID of the currently parsed node, for reporting mainly int myLastNodeID; /** @brief invalidated copy constructor */ NIVissimXMLHandler_Fahrzeugklassendefinition(const NIVissimXMLHandler_Fahrzeugklassendefinition& f); /** @brief invalidated assignment operator */ NIVissimXMLHandler_Fahrzeugklassendefinition& operator=(const NIVissimXMLHandler_Fahrzeugklassendefinition& f); }; private: /** * @class NIVissimSingleTypeXMLHandler_VWunschentscheidungsdefinition * @brief A class which extracts VISSIM-VWunschentscheidungen from a parsed VISSIM-file */ class NIVissimXMLHandler_VWunschentscheidungsdefinition : public GenericSAXHandler { public: /** @brief Constructor * @param[in] elemData The string container to fill */ NIVissimXMLHandler_VWunschentscheidungsdefinition(nodeMap& elemData); /// @brief Destructor ~NIVissimXMLHandler_VWunschentscheidungsdefinition(); protected: /// @name inherited from GenericSAXHandler //@{ /** @brief Called on the opening of a tag; * * @param[in] element ID of the currently opened element * @param[in] attrs Attributes within the currently opened element * @exception ProcessError If something fails * @see GenericSAXHandler::myStartElement */ void myStartElement(int element, const SUMOSAXAttributes& attrs); //@} void myEndElement(int element); //@} private: //std::map<int, VissimXMLEdge> myToFill; nodeMap& myElemData; /// @brief The current hierarchy level int myHierarchyLevel; /// @brief ID of the currently parsed node, for reporting mainly int myLastNodeID; /** @brief invalidated copy constructor */ NIVissimXMLHandler_VWunschentscheidungsdefinition(const NIVissimXMLHandler_VWunschentscheidungsdefinition& vW); /** @brief invalidated assignment operator */ NIVissimXMLHandler_VWunschentscheidungsdefinition& operator=(const NIVissimXMLHandler_VWunschentscheidungsdefinition& vW); }; private: /** * @class NIVissimSingleTypeXMLHandler_Geschwindigkeitsverteilungsdefinition * @brief A class which extracts VISSIM-Geschwindigkeitsverteilung from a parsed VISSIM-file */ class NIVissimXMLHandler_Geschwindigkeitsverteilungsdefinition : public GenericSAXHandler { public: /** @brief Constructor * @param[in] elemData The string container to fill */ NIVissimXMLHandler_Geschwindigkeitsverteilungsdefinition(nodeMap& elemData); /// @brief Destructor ~NIVissimXMLHandler_Geschwindigkeitsverteilungsdefinition(); protected: /// @name inherited from GenericSAXHandler //@{ /** @brief Called on the opening of a tag; * * @param[in] element ID of the currently opened element * @param[in] attrs Attributes within the currently opened element * @exception ProcessError If something fails * @see GenericSAXHandler::myStartElement */ void myStartElement(int element, const SUMOSAXAttributes& attrs); //@} void myEndElement(int element); //@} private: //std::map<int, VissimXMLEdge> myToFill; nodeMap& myElemData; /// @brief The current hierarchy level int myHierarchyLevel; /// @brief ID of the currently parsed node, for reporting mainly int myLastNodeID; /** @brief invalidated copy constructor */ NIVissimXMLHandler_Geschwindigkeitsverteilungsdefinition(const NIVissimXMLHandler_Geschwindigkeitsverteilungsdefinition& vW); /** @brief invalidated assignment operator */ NIVissimXMLHandler_Geschwindigkeitsverteilungsdefinition& operator=(const NIVissimXMLHandler_Geschwindigkeitsverteilungsdefinition& vW); }; private: /** * @class NIVissimXMLHandler_Routenentscheidungsdefinition * @brief A class which extracts VISSIM-Routes from a parsed VISSIM-file */ class NIVissimXMLHandler_Routenentscheidungsdefinition : public GenericSAXHandler { public: /** @brief Constructor * @param[in] elemData The string container to fill */ NIVissimXMLHandler_Routenentscheidungsdefinition(nodeMap& elemData); /// @brief Destructor ~NIVissimXMLHandler_Routenentscheidungsdefinition(); protected: /// @name inherited from GenericSAXHandler //@{ /** @brief Called on the opening of a tag; * * @param[in] element ID of the currently opened element * @param[in] attrs Attributes within the currently opened element * @exception ProcessError If something fails * @see GenericSAXHandler::myStartElement */ void myStartElement(int element, const SUMOSAXAttributes& attrs); //@} void myEndElement(int element); //@} private: //std::map<int, VissimXMLEdge> myToFill; nodeMap& myElemData; /// @brief The current hierarchy level int myHierarchyLevel; /// @brief ID of the currently parsed node, for reporting mainly int myLastNodeID; /** @brief invalidated copy constructor */ NIVissimXMLHandler_Routenentscheidungsdefinition(const NIVissimXMLHandler_Routenentscheidungsdefinition& r); /** @brief invalidated assignment operator */ NIVissimXMLHandler_Routenentscheidungsdefinition& operator=(const NIVissimXMLHandler_Routenentscheidungsdefinition& r); }; private: /** * @class NIVissimSingleTypeXMLHandler_ConflictArea * @brief A class which extracts VISSIM-ConflictAreas from a parsed VISSIM-file */ class NIVissimXMLHandler_ConflictArea : public GenericSAXHandler { public: /** @brief Constructor */ NIVissimXMLHandler_ConflictArea(); /// @brief Destructor ~NIVissimXMLHandler_ConflictArea(); protected: /// @name inherited from GenericSAXHandler //@{ /** @brief Called on the opening of a tag; * * @param[in] element ID of the currently opened element * @param[in] attrs Attributes within the currently opened element * @exception ProcessError If something fails * @see GenericSAXHandler::myStartElement */ void myStartElement(int element, const SUMOSAXAttributes& attrs); //@} private: /** @brief invalidated copy constructor */ NIVissimXMLHandler_ConflictArea(const NIVissimXMLHandler_ConflictArea& c); /** @brief invalidated assignment operator */ NIVissimXMLHandler_ConflictArea& operator=(const NIVissimXMLHandler_ConflictArea& c); }; protected: /// constructor NIImporter_Vissim(NBNetBuilder& nb); /// destructor ~NIImporter_Vissim(); /// loads the vissim file void load(const OptionsCont& options); bool admitContinue(const std::string& tag); public: class VissimSingleTypeParser { public: /// Constructor VissimSingleTypeParser(NIImporter_Vissim& parent); /// Destructor virtual ~VissimSingleTypeParser(); /** @brief Parses a single data type. Returns whether no error occurred */ virtual bool parse(std::istream& from) = 0; protected: /// reads from the stream and returns the lower case version of the read value std::string myRead(std::istream& from); /// as myRead, but returns "DATAEND" when the current field has ended std::string readEndSecure(std::istream& from, const std::string& excl = ""); std::string readEndSecure(std::istream& from, const std::vector<std::string>& excl); /// overrides the optional label definition; returns the next tag as done by readEndSecure std::string overrideOptionalLabel(std::istream& from, const std::string& tag = ""); /// returns the 2d-position saved as next within the stream Position getPosition(std::istream& from); /** @brief parses a listof vehicle types assigned to the current data field One should remeber, that -1 means "all" vehicle types */ std::vector<int> parseAssignedVehicleTypes(std::istream& from, const std::string& next); NIVissimExtendedEdgePoint readExtEdgePointDef(std::istream& from); /** @brief Reads the structures name We cannot use the "<<" operator, as names may contain more than one word which are joined using '"'. */ std::string readName(std::istream& from); /** @brief Overreads the named parameter (if) given and skips the rest until "DATAEND" */ bool skipOverreading(std::istream& from, const std::string& name = ""); /// Reads from the stream until the keywor occurs void readUntil(std::istream& from, const std::string& name); private: NIImporter_Vissim& myVissimParent; private: /// @brief Invalidated assignment operator. VissimSingleTypeParser& operator=(const VissimSingleTypeParser&); }; /// definition of a map from color names to color definitions typedef std::map<std::string, RGBColor> ColorMap; private: bool readContents(std::istream& strm); void postLoadBuild(double offset); /// adds name-to-id - relationships of known elements into myKnownElements void insertKnownElements(); /// adds id-to-parser - relationships of elements to parse into myParsers void buildParsers(); private: /// Definition of a map from element names to their numerical representation typedef std::map<std::string, NIVissimElement> ToElemIDMap; /// Map from element names to their numerical representation ToElemIDMap myKnownElements; /// Definition of a map from an element's numerical id to his parser typedef std::map<NIVissimElement, VissimSingleTypeParser*> ToParserMap; /// Parsers by element id ToParserMap myParsers; /// a map from color names to color definitions ColorMap myColorMap; std::string myLastSecure; NBNetBuilder& myNetBuilder; private: /// @brief Invalidated copy constructor. NIImporter_Vissim(const NIImporter_Vissim&); /// @brief Invalidated assignment operator. NIImporter_Vissim& operator=(const NIImporter_Vissim&); /** * @enum VissimXMLTag * @brief Numbers representing VISSIM-XML - element names * @see GenericSAXHandler */ enum VissimXMLTag { VISSIM_TAG_NOTHING = 0, VISSIM_TAG_NETWORK, VISSIM_TAG_LANES, VISSIM_TAG_LANE, VISSIM_TAG_LINK, VISSIM_TAG_LINKS, VISSIM_TAG_POINTS3D, VISSIM_TAG_POINT3D, VISSIM_TAG_LINKPOLYPOINT, VISSIM_TAG_LINKPOLYPTS, VISSIM_TAG_FROM, VISSIM_TAG_TO, VISSIM_TAG_VEHICLE_INPUT, VISSIM_TAG_PARKINGLOT, VISSIM_TAG_VEHICLE_CLASS, VISSIM_TAG_INTOBJECTREF, VISSIM_TAG_SPEED_DECISION, VISSIM_TAG_SPEED_DIST, VISSIM_TAG_DATAPOINT, VISSIM_TAG_DECISION_STATIC, VISSIM_TAG_ROUTE_STATIC, VISSIM_TAG_CA }; /** * @enum VissimXMLAttr * @brief Numbers representing VISSIM-XML - attributes * @see GenericSAXHandler */ enum VissimXMLAttr { VISSIM_ATTR_NOTHING = 0, VISSIM_ATTR_NO, VISSIM_ATTR_NAME, VISSIM_ATTR_X, VISSIM_ATTR_Y, VISSIM_ATTR_ZOFFSET, VISSIM_ATTR_ZUSCHLAG1, VISSIM_ATTR_ZUSCHLAG2, VISSIM_ATTR_WIDTH, VISSIM_ATTR_LINKBEHAVETYPE, VISSIM_ATTR_LANE, VISSIM_ATTR_POS, VISSIM_ATTR_LINK, VISSIM_ATTR_INTLINK, VISSIM_ATTR_PERCENTAGE, VISSIM_ATTR_DISTRICT, VISSIM_ATTR_COLOR, VISSIM_ATTR_KEY, VISSIM_ATTR_FX, VISSIM_ATTR_DESTLINK, VISSIM_ATTR_DESTPOS, VISSIM_ATTR_LINK1, VISSIM_ATTR_LINK2, VISSIM_ATTR_STATUS }; /// The names of VISSIM-XML elements (for passing to GenericSAXHandler) static StringBijection<int>::Entry vissimTags[]; /// The names of VISSIM-XML attributes (for passing to GenericSAXHandler) static StringBijection<int>::Entry vissimAttrs[]; };
31.960486
144
0.652354
[ "vector" ]
f9d68f1ce086565c86ceb5975b8cf2c7bfafbd40
3,249
h
C
Source/src/core/Entity.h
armandojaga/boxer-engine
47d57989e6bf431eea6732ccee6b64083f03472b
[ "MIT" ]
4
2021-11-19T03:31:02.000Z
2021-12-09T19:33:32.000Z
Source/src/core/Entity.h
armandojaga/boxer-engine
47d57989e6bf431eea6732ccee6b64083f03472b
[ "MIT" ]
3
2021-12-17T22:48:00.000Z
2022-01-11T11:47:57.000Z
Source/src/core/Entity.h
armandojaga/boxer-engine
47d57989e6bf431eea6732ccee6b64083f03472b
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include "util/UUID.h" #include "components/Component.h" namespace BoxerEngine { class Entity : public Serializable { public: Entity(); explicit Entity(Entity* parent); ~Entity() override; void SetId(UID newId); [[nodiscard]] UID GetId() const; void SetName(const std::string& newName); [[nodiscard]] const std::string& GetName() const; void Init(); void Start(); void Update(); void DisplayGizmos() const; // draw the gizmos void Draw() const; void SetParent(Entity* parent); [[nodiscard]] Entity* GetParent() const; void AddChild(Entity* child); [[nodiscard]] bool HasChildren() const; [[nodiscard]] Entity* GetEntity(UID entityId); [[nodiscard]] Entity* GetEntity(const std::string& entityName); void RemoveChild(UID entityId); [[nodiscard]] bool IsChildOf(UID entityId) const; template <typename C> bool Has(); template <typename C> C* CreateComponent(); template <typename C> [[nodiscard]] C* GetComponent() const; template <typename C> void RemoveComponent(); void RemoveComponent(UID componentId); void Enable(); void Disable(); [[nodiscard]] bool IsEnabled() const; [[nodiscard]] std::vector<std::shared_ptr<Component>> GetComponents() const; [[nodiscard]] std::vector<Entity*> GetChildren() const; void Clear(); void Save(YAML::Node) override; void Load(YAML::Node) override; private: UID id = 0; std::string name{}; Entity* parent = nullptr; bool enabled = true; std::vector<std::shared_ptr<Component>> components{}; std::vector<Entity*> children{}; [[nodiscard]] bool Has(UID entityId); Entity* GetEntity(const std::function<bool(Entity*)>& predicate); }; template <typename C> bool Entity::Has() { auto type = [&](const auto c) { return c->GetType() == C::type; }; return std::find_if(std::begin(components), std::end(components), type) != std::end(components); } template <typename C> C* Entity::CreateComponent() { if (!Has<C>()) { std::shared_ptr<C> c = std::make_shared<C>(this); components.push_back(c); return c.get(); } return nullptr; } template <typename C> C* Entity::GetComponent() const { auto type = [&](auto c) { return c->GetType() == C::type; }; auto result = std::find_if(std::begin(components), std::end(components), type); if (result != std::end(components)) { return static_cast<C*>(result->get()); } return nullptr; } template <typename C> void Entity::RemoveComponent() { if (Has<C>()) { auto componentType = [&](const auto c) { return C::type == c->GetType(); }; components.erase( std::remove_if(std::begin(components), std::end(components), componentType), components.end() ); } } }
27.769231
104
0.557094
[ "vector" ]
f9dc25b4b872b229c89b4b665c3243b8a8896edc
10,181
c
C
drivers/wdm/audio/legacy/wdmaud.sys/device.c
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
drivers/wdm/audio/legacy/wdmaud.sys/device.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
drivers/wdm/audio/legacy/wdmaud.sys/device.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/**************************************************************************** * * device.c * * Kernel mode entry point for WDM drivers * * Copyright (C) Microsoft Corporation, 1997 - 1999 All Rights Reserved. * * History * S.Mohanraj (MohanS) * M.McLaughlin (MikeM) * 5-19-97 - Noel Cross (NoelC) * ***************************************************************************/ #define IRPMJFUNCDESC #include "wdmsys.h" KMUTEX wdmaMutex; KMUTEX mtxNote; LIST_ENTRY WdmaContextListHead; KMUTEX WdmaContextListMutex; // // For hardware notifications, we need to init these two values. // extern KSPIN_LOCK HardwareCallbackSpinLock; extern LIST_ENTRY HardwareCallbackListHead; extern PKSWORKER HardwareCallbackWorkerObject; extern WORK_QUEUE_ITEM HardwareCallbackWorkItem; //VOID kmxlPersistHWControlWorker(VOID); //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- NTSTATUS AddFsContextToList(PWDMACONTEXT pWdmaContext) { NTSTATUS Status; PAGED_CODE(); KeEnterCriticalRegion(); Status = KeWaitForMutexObject(&WdmaContextListMutex, Executive, KernelMode, FALSE, NULL); if (NT_SUCCESS(Status)) { InsertTailList(&WdmaContextListHead, &pWdmaContext->Next); KeReleaseMutex(&WdmaContextListMutex, FALSE); } pWdmaContext->fInList = NT_SUCCESS(Status); KeLeaveCriticalRegion(); RETURN( Status ); } NTSTATUS RemoveFsContextFromList(PWDMACONTEXT pWdmaContext) { NTSTATUS Status; PAGED_CODE(); if (pWdmaContext->fInList) { KeEnterCriticalRegion(); Status = KeWaitForMutexObject(&WdmaContextListMutex, Executive, KernelMode, FALSE, NULL); if (NT_SUCCESS(Status)) { RemoveEntryList(&pWdmaContext->Next); KeReleaseMutex(&WdmaContextListMutex, FALSE); } KeLeaveCriticalRegion(); } else { Status = STATUS_SUCCESS; } RETURN( Status ); } // // This routine walks the list of global context structures and calls the callback // routine with the structure. If the callback routine returns STATUS_MORE_DATA // the routine will keep on searching the list. If it returns an error or success // the search will end. // NTSTATUS EnumFsContext( FNCONTEXTCALLBACK fnCallback, PVOID pvoidRefData, PVOID pvoidRefData2 ) { NTSTATUS Status; PLIST_ENTRY ple; PWDMACONTEXT pContext; PAGED_CODE(); // // Make sure that we can walk are list without being interrupted. // KeEnterCriticalRegion(); Status = KeWaitForMutexObject(&WdmaContextListMutex, Executive, KernelMode, FALSE, NULL); if (NT_SUCCESS(Status)) { // // Walk the list here and call the callback routine. // for(ple = WdmaContextListHead.Flink; ple != &WdmaContextListHead; ple = ple->Flink) { pContext = CONTAINING_RECORD(ple, WDMACONTEXT, Next); // // The callback routine will return STATUS_MORE_ENTRIES // if it's not done. // DPF(DL_TRACE|FA_USER,( "Calling fnCallback: %x %x",pvoidRefData,pvoidRefData2 ) ); Status = fnCallback(pContext,pvoidRefData,pvoidRefData2); if( STATUS_MORE_ENTRIES != Status ) { break; } } // // "break;" should bring us here to release our locks. // KeReleaseMutex(&WdmaContextListMutex, FALSE); } else { DPF(DL_WARNING|FA_USER,( "Failed to get Mutex: %x %x",pvoidRefData,pvoidRefData2 ) ); } KeLeaveCriticalRegion(); // // If the callback routine doesn't return a NTSTATUS, it didn't find // what it was looking for, thus, EnumFsContext returns as error. // if( STATUS_MORE_ENTRIES == Status ) { Status = STATUS_UNSUCCESSFUL; } DPF(DL_TRACE|FA_USER,( "Returning Status: %x",Status ) ); return Status; } NTSTATUS DriverEntry ( IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING usRegistryPathName ) { NTSTATUS Status; PAGED_CODE(); #ifdef DEBUG GetuiDebugLevel(); #endif DPF(DL_TRACE|FA_ALL, ("************************************************************") ); DPF(DL_TRACE|FA_ALL, ("* uiDebugLevel=%08X controls the debug output. To change",uiDebugLevel) ); DPF(DL_TRACE|FA_ALL, ("* edit uiDebugLevel like: e uidebuglevel and set to ") ); DPF(DL_TRACE|FA_ALL, ("* 0 - show only fatal error messages and asserts ") ); DPF(DL_TRACE|FA_ALL, ("* 1 (Default) - Also show non-fatal errors and return codes ") ); DPF(DL_TRACE|FA_ALL, ("* 2 - Also show trace messages ") ); DPF(DL_TRACE|FA_ALL, ("* 4 - Show Every message ") ); DPF(DL_TRACE|FA_ALL, ("************************************************************") ); DriverObject->DriverExtension->AddDevice = PnpAddDevice; DriverObject->DriverUnload = PnpDriverUnload; // KsNullDriverUnload; DriverObject->MajorFunction[IRP_MJ_POWER] = KsDefaultDispatchPower; DriverObject->MajorFunction[IRP_MJ_PNP] = DispatchPnp; DriverObject->MajorFunction[IRP_MJ_SYSTEM_CONTROL] = KsDefaultForwardIrp; DriverObject->MajorFunction[IRP_MJ_CREATE] = SoundDispatchCreate; DriverObject->MajorFunction[IRP_MJ_CLOSE] = SoundDispatchClose; DriverObject->MajorFunction[IRP_MJ_DEVICE_CONTROL] = SoundDispatch; DriverObject->MajorFunction[IRP_MJ_CLEANUP] = SoundDispatchCleanup; KeInitializeMutex(&wdmaMutex, 0); KeInitializeMutex(&mtxNote, 0); // // Initialize the hardware event items // InitializeListHead(&HardwareCallbackListHead); KeInitializeSpinLock(&HardwareCallbackSpinLock); ExInitializeWorkItem(&HardwareCallbackWorkItem, (PWORKER_THREAD_ROUTINE)kmxlPersistHWControlWorker, (PVOID)NULL); //pnnode Status = KsRegisterWorker( DelayedWorkQueue, &HardwareCallbackWorkerObject ); if (!NT_SUCCESS(Status)) { DPFBTRAP(); HardwareCallbackWorkerObject = NULL; } return STATUS_SUCCESS; } NTSTATUS DispatchPnp( IN PDEVICE_OBJECT pDeviceObject, IN PIRP pIrp ) { PIO_STACK_LOCATION pIrpStack; PAGED_CODE(); pIrpStack = IoGetCurrentIrpStackLocation( pIrp ); switch(pIrpStack->MinorFunction) { case IRP_MN_QUERY_PNP_DEVICE_STATE: // // Mark the device as not disableable. // pIrp->IoStatus.Information |= PNP_DEVICE_NOT_DISABLEABLE; break; } return(KsDefaultDispatchPnp(pDeviceObject, pIrp)); } NTSTATUS PnpAddDevice( IN PDRIVER_OBJECT DriverObject, IN PDEVICE_OBJECT PhysicalDeviceObject ) /*++ Routine Description: When a new device is detected, PnP calls this entry point with the new PhysicalDeviceObject (PDO). The driver creates an associated FunctionalDeviceObject (FDO). Arguments: DriverObject - Pointer to the driver object. PhysicalDeviceObject - Pointer to the new physical device object. Return Values: STATUS_SUCCESS or an appropriate error condition. --*/ { NTSTATUS Status; PDEVICE_OBJECT FunctionalDeviceObject; PDEVICE_INSTANCE pDeviceInstance; PAGED_CODE(); DPF(DL_TRACE|FA_ALL, ("Entering")); // // The Software Bus Enumerator expects to establish links // using this device name. // Status = IoCreateDevice( DriverObject, sizeof( DEVICE_INSTANCE ), NULL, // FDOs are unnamed FILE_DEVICE_KS, 0, FALSE, &FunctionalDeviceObject ); if (!NT_SUCCESS(Status)) { RETURN( Status ); } pDeviceInstance = (PDEVICE_INSTANCE)FunctionalDeviceObject->DeviceExtension; Status = KsAllocateDeviceHeader( &pDeviceInstance->pDeviceHeader, 0, NULL ); if (NT_SUCCESS(Status)) { KsSetDevicePnpAndBaseObject( pDeviceInstance->pDeviceHeader, IoAttachDeviceToDeviceStack( FunctionalDeviceObject, PhysicalDeviceObject ), FunctionalDeviceObject ); FunctionalDeviceObject->Flags |= (DO_BUFFERED_IO | DO_POWER_PAGABLE); FunctionalDeviceObject->Flags &= ~DO_DEVICE_INITIALIZING; } else { IoDeleteDevice( FunctionalDeviceObject ); } #ifdef PROFILE WdmaInitProfile(); #endif InitializeListHead(&WdmaContextListHead); KeInitializeMutex(&WdmaContextListMutex, 0); InitializeListHead(&wdmaPendingIrpQueue.WdmaPendingIrpListHead); KeInitializeSpinLock(&wdmaPendingIrpQueue.WdmaPendingIrpListSpinLock); IoCsqInitialize( &wdmaPendingIrpQueue.Csq, WdmaCsqInsertIrp, WdmaCsqRemoveIrp, WdmaCsqPeekNextIrp, WdmaCsqAcquireLock, WdmaCsqReleaseLock, WdmaCsqCompleteCanceledIrp ); RETURN( Status ); } VOID PnpDriverUnload( IN PDRIVER_OBJECT DriverObject ) { PAGED_CODE(); DPF(DL_TRACE|FA_ALL,("Entering")); // // Wait for all or our scheduled work items to complete. // if( HardwareCallbackWorkerObject ) { KsUnregisterWorker( HardwareCallbackWorkerObject ); HardwareCallbackWorkerObject = NULL; } kmxlCleanupNoteList(); }
29.944118
102
0.586878
[ "object" ]
f9dd394615bbe4016905eb303efa2585b5247f8a
14,814
h
C
virtual-UE-eNB/srsLTE-5d82f19988bc148d7f4cec7a0f29184375a64b40/srsue/hdr/mac/dl_harq.h
Joanguitar/docker-nextepc
2b606487968fe63ce19a8acf58938a84d97ffb89
[ "MIT" ]
null
null
null
virtual-UE-eNB/srsLTE-5d82f19988bc148d7f4cec7a0f29184375a64b40/srsue/hdr/mac/dl_harq.h
Joanguitar/docker-nextepc
2b606487968fe63ce19a8acf58938a84d97ffb89
[ "MIT" ]
null
null
null
virtual-UE-eNB/srsLTE-5d82f19988bc148d7f4cec7a0f29184375a64b40/srsue/hdr/mac/dl_harq.h
Joanguitar/docker-nextepc
2b606487968fe63ce19a8acf58938a84d97ffb89
[ "MIT" ]
3
2020-04-04T18:26:04.000Z
2021-09-24T18:41:01.000Z
/** * * \section COPYRIGHT * * Copyright 2013-2015 Software Radio Systems Limited * * \section LICENSE * * This file is part of the srsUE library. * * srsUE is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of * the License, or (at your option) any later version. * * srsUE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * A copy of the GNU Affero General Public License can be found in * the LICENSE file in the top-level directory of this distribution * and at http://www.gnu.org/licenses/. * */ #ifndef SRSUE_DL_HARQ_H #define SRSUE_DL_HARQ_H #define Error(fmt, ...) log_h->error(fmt, ##__VA_ARGS__) #define Warning(fmt, ...) log_h->warning(fmt, ##__VA_ARGS__) #define Info(fmt, ...) log_h->info(fmt, ##__VA_ARGS__) #define Debug(fmt, ...) log_h->debug(fmt, ##__VA_ARGS__) #include "srslte/common/log.h" #include "srslte/common/timers.h" #include "demux.h" #include "dl_sps.h" #include "srslte/common/mac_pcap.h" #include "srslte/interfaces/ue_interfaces.h" /* Downlink HARQ entity as defined in 5.3.2 of 36.321 */ namespace srsue { template <std::size_t N, typename Tgrant, typename Taction, typename Tphygrant> class dl_harq_entity { public: const static uint32_t HARQ_BCCH_PID = N; dl_harq_entity() : proc(N+1) { pcap = NULL; } bool init(srslte::log *log_h_, srslte::timers::timer *timer_aligment_timer_, demux *demux_unit_) { timer_aligment_timer = timer_aligment_timer_; demux_unit = demux_unit_; si_window_start = 0; log_h = log_h_; for (uint32_t i=0;i<N+1;i++) { if (!proc[i].init(i, this)) { return false; } } return true; } /***************** PHY->MAC interface for DL processes **************************/ void new_grant_dl(Tgrant grant, Taction *action) { if (grant.rnti_type != SRSLTE_RNTI_SPS) { uint32_t harq_pid; // Set BCCH PID for SI RNTI if (grant.rnti_type == SRSLTE_RNTI_SI) { harq_pid = HARQ_BCCH_PID; } else { harq_pid = grant.pid%N; } if (grant.rnti_type == SRSLTE_RNTI_TEMP && last_temporal_crnti != grant.rnti) { grant.ndi[0] = true; Info("Set NDI=1 for Temp-RNTI DL grant\n"); last_temporal_crnti = grant.rnti; } if (grant.rnti_type == SRSLTE_RNTI_USER && proc[harq_pid].is_sps()) { grant.ndi[0] = true; Info("Set NDI=1 for C-RNTI DL grant\n"); } proc[harq_pid].new_grant_dl(grant, action); } else { /* This is for SPS scheduling */ uint32_t harq_pid = get_harq_sps_pid(grant.tti)%N; if (grant.ndi[0]) { grant.ndi[0] = false; proc[harq_pid].new_grant_dl(grant, action); } else { if (grant.is_sps_release) { dl_sps_assig.clear(); if (timer_aligment_timer->is_running()) { //phy_h->send_sps_ack(); Warning("PHY Send SPS ACK not implemented\n"); } } else { Error("SPS not implemented\n"); //dl_sps_assig.reset(grant.tti, grant); //grant.ndi = true; //procs[harq_pid].save_grant(); } } } } void tb_decoded(bool ack, uint32_t tb_idx, srslte_rnti_type_t rnti_type, uint32_t harq_pid) { if (rnti_type == SRSLTE_RNTI_SI) { proc[N].tb_decoded(ack, 0); } else { proc[harq_pid%N].tb_decoded(ack, tb_idx); } } void reset() { for (uint32_t i=0;i<N+1;i++) { proc[i].reset(); } dl_sps_assig.clear(); } void start_pcap(srslte::mac_pcap* pcap_) { pcap = pcap_; } int get_current_tbs(uint32_t harq_pid, uint32_t tb_idx) { return proc[harq_pid%N].get_current_tbs(tb_idx); } void set_si_window_start(int si_window_start_) { si_window_start = si_window_start_; } float get_average_retx() { return average_retx; } private: class dl_harq_process { public: dl_harq_process() : subproc(SRSLTE_MAX_TB) { } bool init(uint32_t pid_, dl_harq_entity *parent) { bool ret = true; for (uint32_t tb = 0; tb < SRSLTE_MAX_TB; tb++) { ret &= subproc[tb].init(pid_, parent, tb); } return ret; } void reset(void) { for (uint32_t tb = 0; tb < SRSLTE_MAX_TB; tb++) { subproc[tb].reset(); } } void new_grant_dl(Tgrant grant, Taction *action) { /* Fill action structure */ bzero(action, sizeof(Taction)); action->generate_ack = true; action->rnti = grant.rnti; /* For each subprocess... */ for (uint32_t tb = 0; tb < SRSLTE_MAX_TB; tb++) { action->default_ack[tb] = false; action->decode_enabled[tb] = false; action->phy_grant.dl.tb_en[tb] = grant.tb_en[tb]; if (grant.tb_en[tb]) { subproc[tb].new_grant_dl(grant, action); } } } int get_current_tbs(uint32_t tb_idx) { return subproc[tb_idx].get_current_tbs(); } bool is_sps() { return false; } void tb_decoded(bool ack_, uint32_t tb_idx) { subproc[tb_idx].tb_decoded(ack_); } private: const static int RESET_DUPLICATE_TIMEOUT = 8*6; class dl_tb_process { public: dl_tb_process(void) { is_initiated = false; ack = false; bzero(&cur_grant, sizeof(Tgrant)); payload_buffer_ptr = NULL; pthread_mutex_init(&mutex, NULL); } ~dl_tb_process() { if (is_initiated) { srslte_softbuffer_rx_free(&softbuffer); } } bool init(uint32_t pid_, dl_harq_entity *parent, uint32_t tb_idx) { tid = tb_idx; if (srslte_softbuffer_rx_init(&softbuffer, 110)) { Error("Error initiating soft buffer\n"); return false; } else { pid = pid_; is_first_tb = true; is_initiated = true; harq_entity = parent; log_h = harq_entity->log_h; return true; } } void reset(bool lock = true) { if (lock) { pthread_mutex_lock(&mutex); } is_first_tb = true; ack = false; n_retx = 0; if (payload_buffer_ptr) { if (pid != HARQ_BCCH_PID) { harq_entity->demux_unit->deallocate(payload_buffer_ptr); } payload_buffer_ptr = NULL; } bzero(&cur_grant, sizeof(Tgrant)); if (is_initiated && lock) { srslte_softbuffer_rx_reset(&softbuffer); } if (lock) { pthread_mutex_unlock(&mutex); } } void new_grant_dl(Tgrant grant, Taction *action) { pthread_mutex_lock(&mutex); // Compute RV for BCCH when not specified in PDCCH format if (pid == HARQ_BCCH_PID && grant.rv[tid] == -1) { uint32_t k; if ((grant.tti / 10) % 2 == 0 && grant.tti % 10 == 5) { // This is SIB1, k is different k = (grant.tti / 20) % 4; grant.rv[tid] = ((uint32_t) ceilf((float) 1.5 * k)) % 4; } else if (grant.rv[tid] == -1) { k = (grant.tti - harq_entity->si_window_start) % 4; grant.rv[tid] = ((uint32_t) ceilf((float) 1.5 * k)) % 4; } } calc_is_new_transmission(grant); // If this is a new transmission or the size of the TB has changed if (is_new_transmission || (cur_grant.n_bytes[tid] != grant.n_bytes[tid])) { if (!is_new_transmission) { Warning("DL PID %d: Size of grant changed during a retransmission %d!=%d\n", pid, cur_grant.n_bytes[tid], grant.n_bytes[tid]); } ack = false; srslte_softbuffer_rx_reset_tbs(&softbuffer, cur_grant.n_bytes[tid] * 8); n_retx = 0; } // If data has not yet been successfully decoded if (!ack) { // Save grant grant.last_ndi[tid] = cur_grant.ndi[tid]; grant.last_tti = cur_grant.tti; memcpy(&cur_grant, &grant, sizeof(Tgrant)); if (payload_buffer_ptr) { Warning("DL PID %d: Allocating buffer already allocated. Deallocating.\n", pid); if (pid != HARQ_BCCH_PID) { harq_entity->demux_unit->deallocate(payload_buffer_ptr); } } // Instruct the PHY To combine the received data and attempt to decode it if (pid == HARQ_BCCH_PID) { payload_buffer_ptr = harq_entity->demux_unit->request_buffer_bcch(cur_grant.n_bytes[tid]); } else { payload_buffer_ptr = harq_entity->demux_unit->request_buffer(cur_grant.n_bytes[tid]); } action->payload_ptr[tid] = payload_buffer_ptr; if (!action->payload_ptr[tid]) { action->decode_enabled[tid] = false; Error("Can't get a buffer for TBS=%d\n", cur_grant.n_bytes[tid]); pthread_mutex_unlock(&mutex); return; } action->decode_enabled[tid] = true; action->rv[tid] = cur_grant.rv[tid]; action->softbuffers[tid] = &softbuffer; memcpy(&action->phy_grant, &cur_grant.phy_grant, sizeof(Tphygrant)); n_retx++; } else { action->default_ack[tid] = true; uint32_t interval = srslte_tti_interval(grant.tti, cur_grant.tti); Warning("DL PID %d: Received duplicate TB. Discarting and retransmitting ACK (grant_tti=%d, ndi=%d, sz=%d, reset=%s)\n", pid, cur_grant.tti, cur_grant.ndi[tid], cur_grant.n_bytes[tid], interval>RESET_DUPLICATE_TIMEOUT?"yes":"no"); if (interval > RESET_DUPLICATE_TIMEOUT) { reset(false); } } if (pid == HARQ_BCCH_PID || harq_entity->timer_aligment_timer->is_expired()) { // Do not generate ACK Debug("Not generating ACK\n"); action->generate_ack = false; } else { if (cur_grant.rnti_type == SRSLTE_RNTI_TEMP && !ack) { // Postpone ACK after contention resolution is resolved action->generate_ack_callback = harq_entity->generate_ack_callback; action->generate_ack_callback_arg = harq_entity->demux_unit; Debug("ACK pending contention resolution\n"); } else { Debug("Generating ACK\n"); } } if (!action->decode_enabled[tid]) { pthread_mutex_unlock(&mutex); } } void tb_decoded(bool ack_) { ack = ack_; if (ack) { if (pid == HARQ_BCCH_PID) { if (harq_entity->pcap) { harq_entity->pcap->write_dl_sirnti(payload_buffer_ptr, cur_grant.n_bytes[tid], ack, cur_grant.tti); } Debug("Delivering PDU=%d bytes to Dissassemble and Demux unit (BCCH)\n", cur_grant.n_bytes[tid]); harq_entity->demux_unit->push_pdu_bcch(payload_buffer_ptr, cur_grant.n_bytes[tid], cur_grant.tti); } else { if (harq_entity->pcap) { harq_entity->pcap->write_dl_crnti(payload_buffer_ptr, cur_grant.n_bytes[tid], cur_grant.rnti, ack, cur_grant.tti); } if (cur_grant.rnti_type == SRSLTE_RNTI_TEMP) { Debug("Delivering PDU=%d bytes to Dissassemble and Demux unit (Temporal C-RNTI)\n", cur_grant.n_bytes[tid]); harq_entity->demux_unit->push_pdu_temp_crnti(payload_buffer_ptr, cur_grant.n_bytes[tid]); } else { Debug("Delivering PDU=%d bytes to Dissassemble and Demux unit\n", cur_grant.n_bytes[tid]); harq_entity->demux_unit->push_pdu(payload_buffer_ptr, cur_grant.n_bytes[tid], cur_grant.tti); // Compute average number of retransmissions per packet harq_entity->average_retx = SRSLTE_VEC_CMA((float) n_retx, harq_entity->average_retx, harq_entity->nof_pkts++); } } } else if (pid != HARQ_BCCH_PID) { harq_entity->demux_unit->deallocate(payload_buffer_ptr); } payload_buffer_ptr = NULL; Info("DL %d (TB %d): %s tbs=%d, rv=%d, ack=%s, ndi=%d (%d), tti=%d (%d)\n", pid, tid, is_new_transmission ? "newTX" : "reTX ", cur_grant.n_bytes[tid], cur_grant.rv[tid], ack ? "OK" : "KO", cur_grant.ndi[tid], cur_grant.last_ndi[tid], cur_grant.tti, cur_grant.last_tti); pthread_mutex_unlock(&mutex); if (ack && pid == HARQ_BCCH_PID) { reset(); } } int get_current_tbs(void) { return cur_grant.n_bytes[tid] * 8; } private: // Determine if it's a new transmission 5.3.2.2 bool calc_is_new_transmission(Tgrant grant) { if (grant.phy_grant.dl.mcs[tid].idx <= 28 && // mcs 29,30,31 always retx regardless of rest ((grant.ndi[tid] != cur_grant.ndi[tid]) || // 1st condition (NDI has changed) (pid == HARQ_BCCH_PID && grant.rv[tid] == 0) || // 2nd condition (Broadcast and 1st transmission) is_first_tb)) { is_first_tb = false; is_new_transmission = true; Debug("Set HARQ for new transmission\n"); } else { is_new_transmission = false; Debug("Set HARQ for retransmission\n"); } return is_new_transmission; } pthread_mutex_t mutex; bool is_initiated; dl_harq_entity *harq_entity; srslte::log *log_h; bool is_first_tb; bool is_new_transmission; uint32_t pid; /* HARQ Proccess ID */ uint32_t tid; /* Transport block ID */ uint8_t *payload_buffer_ptr; bool ack; uint32_t n_retx; Tgrant cur_grant; srslte_softbuffer_rx_t softbuffer; }; /* Transport blocks */ std::vector<dl_tb_process> subproc; }; // Private members of dl_harq_entity static bool generate_ack_callback(void *arg) { demux *demux_unit = (demux*) arg; return demux_unit->get_uecrid_successful(); } uint32_t get_harq_sps_pid(uint32_t tti) { return 0; } dl_sps dl_sps_assig; std::vector<dl_harq_process> proc; srslte::timers::timer *timer_aligment_timer; demux *demux_unit; srslte::log *log_h; srslte::mac_pcap *pcap; uint16_t last_temporal_crnti; int si_window_start; float average_retx; uint64_t nof_pkts; }; } // namespace srsue #endif // SRSUE_DL_HARQ_H
32.27451
130
0.589105
[ "vector" ]
f9e3bbf294eb69ff5aaf8a3aeb43562bc27ea3d9
4,944
c
C
src/dev/timer.c
johnyob/Tiny-OS
db683c9acc7abecc600088469f5f3fd69f31ed64
[ "MIT" ]
1
2021-03-19T02:38:39.000Z
2021-03-19T02:38:39.000Z
src/dev/timer.c
johnyob/Tiny-OS
db683c9acc7abecc600088469f5f3fd69f31ed64
[ "MIT" ]
1
2022-01-12T08:49:21.000Z
2022-01-17T02:01:52.000Z
src/dev/timer.c
johnyob/Tiny-OS
db683c9acc7abecc600088469f5f3fd69f31ed64
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // - Alistair O'Brien - 7/14/2020 - University of Cambridge //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // File: timer.c // Environment: Tiny OS // Description: //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include <lib/stdint.h> #include <param.h> #include <riscv.h> #include <debug.h> #include <mm/pmm.h> #include <mm/vmm.h> #include <trap/interrupt.h> #include <threads/thread.h> #include <dev/timer.h> //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // CLINT (Core Local Interruptor) // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // The CLINT is used to manage and control software and timer interrupts for each hart. // For QEMU's RISC-V virt architecture, the CLINT is a block of memory-mapped control and status registers // including the msip, mtimecmp and mtime registers. // // For our purposes, we will be using the CLINT to control the timer, using the mtimecmp and mtime registers. // For each hart h_i, there is a single mtimecmp register. The mtimecmp register is the timer compare register, which // causes a timer interrupt to be sent to hart h_i when the mtime register contains a value greater than or equal to the // value in the mtimecmp register. // // To handle the interrupt, we must overwrite the mtimecmp, this notifies the CLINT. // // We note that by the design of Tiny OS and RISC-V, all CLINT code will execute in // machine mode. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #define CLINT_START (0x2000000L) #define CLINT_SIZE (0x10000L) /* * The CLINT controls the timer using a series of mtimecmp registers, timer compare registers. * An interrupt is sent when the mtime register contains a value greater than or equal to * the value in the mtimecmp register. * Each mtimecmp register consists of 8-bytes with a base address of 0x2004000. */ #define CLINT_MTIMECMP_BASE (CLINT_START + 0x4000) #define CLINT_MTIMECMP(id) (CLINT_MTIMECMP_BASE + 8 * id) #define CLINT_MTIME (CLINT_START + 0xbff8) //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // EXTERNAL CLINT METHODS // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /* * To handle timer interrupts, we somewhere to store the mtimecmp mmio address and the * timer interval. We also some additional space to save the values stored in the * temporary registers that we use during the timer interrupt vector. Our assembly code * only uses the registers t1, t2 and t3. Hence our mscratch area requires 5 8 byte entries. */ static uint64_t mscratch[NUM_HART][5]; // The number of timer ticks since the OS booted. static volatile uint64_t ticks; void timer_init() { uint64_t hartid = r_hartid(); uint64_t* scratch = &mscratch[hartid][0]; scratch[0] = CLINT_MTIMECMP(hartid); scratch[1] = TIMER_INTERVAL; *(uint64_t*)scratch[0] = *(uint64_t*)CLINT_MTIME + TIMER_INTERVAL; w_mtvec(MTVEC((uintptr_t)m_trap_vec, MTVEC_MODE_DIRECT)); w_mscratch((uintptr_t)scratch); w_mstatus(r_mstatus() | MSTATUS_MIE); w_mie(r_mie() | MIE_MTIE); } /* * Procedure: timer_vm_init * -------------------------- * This procedure performs the kernel virtual memory mapping required during initialization. * */ void timer_vm_init() { kmap(CLINT_START, CLINT_START, CLINT_SIZE, PTE_R | PTE_W); info("clint: \t%#p -> %#p\n", CLINT_START, CLINT_START + CLINT_SIZE); } uint64_t timer_ticks() { // Disable all interrupts intr_state_t state = intr_disable(); uint64_t t = ticks; // Return the interruptor to it's previous setting intr_set_state(state); return t; } uint64_t timer_elapsed(uint64_t then) { uint64_t t = timer_ticks(); assert(t >= then); return t - then; } void timer_sleep(uint64_t t) { uint64_t ticks0 = timer_ticks(); assert(intr_get_state() == INTR_ON); info("%d thread\n", thread_current()->tid); info("%d ticks0\n", ticks0); while (timer_elapsed(ticks0) < t) { thread_yield(); if (timer_elapsed(ticks0) > 0) info("Yay!\n"); } } void timer_handle_interrupt(UNUSED trap_frame_t* tf) { ticks++; scheduler_tick(); }
36.622222
120
0.535599
[ "vector" ]
f9efe62a5d60edb810ba28bc34463bc554052492
695
h
C
Sources/Internal/Engine/Private/Android/AssetsManagerAndroid.h
stinvi/dava.engine
2b396ca49cdf10cdc98ad8a9ffcf7768a05e285e
[ "BSD-3-Clause" ]
26
2018-09-03T08:48:22.000Z
2022-02-14T05:14:50.000Z
Sources/Internal/Engine/Private/Android/AssetsManagerAndroid.h
ANHELL-blitz/dava.engine
ed83624326f000866e29166c7f4cccfed1bb41d4
[ "BSD-3-Clause" ]
null
null
null
Sources/Internal/Engine/Private/Android/AssetsManagerAndroid.h
ANHELL-blitz/dava.engine
ed83624326f000866e29166c7f4cccfed1bb41d4
[ "BSD-3-Clause" ]
45
2018-05-11T06:47:17.000Z
2022-02-03T11:30:55.000Z
#pragma once #include "Base/BaseTypes.h" #include "Base/Singleton.h" #include "FileSystem/ResourceArchive.h" namespace DAVA { class ZipArchive; class AssetsManagerAndroid : public Singleton<AssetsManagerAndroid> { public: explicit AssetsManagerAndroid(const String& packageName); virtual ~AssetsManagerAndroid(); bool HasDirectory(const String& relativeDirName) const; bool HasFile(const String& relativeFilePath) const; bool LoadFile(const String& relativeFilePath, Vector<uint8>& output) const; bool ListDirectory(const String& relativeDirName, Vector<ResourceArchive::FileInfo>&) const; private: String packageName; std::unique_ptr<ZipArchive> apk; }; };
25.740741
96
0.768345
[ "vector" ]
f9fe6e51821305cf48fe635f5acc55ce746219d7
1,212
h
C
include/observer.h
ptitSeb/freespace2
500ee249f7033aac9b389436b1737a404277259c
[ "Linux-OpenIB" ]
1
2020-07-14T07:29:18.000Z
2020-07-14T07:29:18.000Z
include/observer.h
ptitSeb/freespace2
500ee249f7033aac9b389436b1737a404277259c
[ "Linux-OpenIB" ]
2
2019-01-01T22:35:56.000Z
2022-03-14T07:34:00.000Z
include/observer.h
ptitSeb/freespace2
500ee249f7033aac9b389436b1737a404277259c
[ "Linux-OpenIB" ]
2
2021-03-07T11:40:42.000Z
2021-12-26T21:40:39.000Z
/* * Copyright (C) Volition, Inc. 1999. All rights reserved. * * All source code herein is the property of Volition, Inc. You may not sell * or otherwise commercially exploit the source or things you created based on * the source. */ /* * $Logfile: /Freespace2/code/Observer/Observer.h $ * $Revision: 110 $ * $Date: 2002-06-09 06:41:30 +0200 (Sun, 09 Jun 2002) $ * $Author: relnev $ * * $NoKeywords: $ */ #ifndef _OBSERVER_HEADER_FILE #define _OBSERVER_HEADER_FILE #include "object.h" #include "vecmat.h" #define OBS_MAX_VEL_X (85.0f) // side to side #define OBS_MAX_VEL_Y (85.0f) // side to side #define OBS_MAX_VEL_Z (85.0f) // forwards and backwards #define OBS_FLAG_USED (1<<1) typedef struct observer { int objnum; int target_objnum; // not used as of yet int flags; } observer; #define MAX_OBSERVER_OBS 17 extern observer Observers[MAX_OBSERVER_OBS]; extern int Num_observer_obs; void observer_init(); int observer_create(matrix *orient, vector *pos); // returns objnum void observer_delete(object *obj); // get the eye position and orientation for the passed observer object void observer_get_eye(vector *eye_pos, matrix *eye_orient, object *obj); #endif
23.307692
78
0.718647
[ "object", "vector" ]
e61c3bd8299500e3c07ba99c2c31443d1f5875f3
1,245
h
C
H/UI/Satellite.h
lehtojo/Evie
f41b3872f6a1a7da1778c241c7b01823b36ac78d
[ "MIT" ]
12
2020-07-12T06:22:11.000Z
2022-02-27T13:19:19.000Z
H/UI/Satellite.h
lehtojo/Evie
f41b3872f6a1a7da1778c241c7b01823b36ac78d
[ "MIT" ]
3
2019-04-15T19:24:36.000Z
2020-02-29T13:09:07.000Z
H/UI/Satellite.h
lehtojo/Evie
f41b3872f6a1a7da1778c241c7b01823b36ac78d
[ "MIT" ]
3
2021-09-16T19:02:19.000Z
2021-11-28T00:50:15.000Z
#include <vector> #include <string> using namespace std; enum class INSTALL{ DEFAULT, }; enum class INTRODUCE { LOCAL, HTTPS, CONSOLE, }; namespace OS { const string WIN = "win"; const string UNIX = "unix"; } namespace ARCHITECTURE { const string X86 = "x86"; const string ARM = "arm"; } class Medium { public: //The OS this product is supposed to be installed onto. string Platform = ""; //The system that can fetch the product. INTRODUCE Introducer = INTRODUCE::LOCAL; //string address the finded dependecy is stored up to for later usage. string* Dependency_Location; //Describes the Name of the product in question. string Product_ID = ""; }; class Satellite { public: //Default Depedencies installation Satellite() { this->Installation_Type = INSTALL::DEFAULT; Init_Wanted_Dependencies(); Factory(); } Satellite(INSTALL Installation_Type) { this->Installation_Type = Installation_Type; Init_Wanted_Dependencies(); Factory(); } private: vector<string> Chache; INSTALL Installation_Type; vector<Medium> Dependecies; void Init_Wanted_Dependencies(); void Factory(); void Process_Local_Dependencies(Medium m); void Process_Console_Dependencies(Medium m); void Save_To_Cache(Medium m); };
18.043478
71
0.734137
[ "vector" ]
e61fbac5840fc28cc59750e39fea75f05806a742
2,102
h
C
src/header/openGL/Framebuffer.h
Gregjksmith/Global-Illumination
c8a2c98f3f9b810df18c49956e723a2df9b27a40
[ "MIT" ]
null
null
null
src/header/openGL/Framebuffer.h
Gregjksmith/Global-Illumination
c8a2c98f3f9b810df18c49956e723a2df9b27a40
[ "MIT" ]
null
null
null
src/header/openGL/Framebuffer.h
Gregjksmith/Global-Illumination
c8a2c98f3f9b810df18c49956e723a2df9b27a40
[ "MIT" ]
null
null
null
/********************************************************************** * FILENAME : Framebuffer.h * * DESCRIPTION : * Contains a class 'Framebuffer', which creates a custom render target. * * AUTHOR : Greg Smith START DATE : Jan '13 * **********************************************************************/ #ifndef FRAMEBUFFER_H #define FRAMEBUFFER_H #include "GL\glew.h" /* class Framebuffer contains an instance of a rendering target. -color texture -depth texture */ class Framebuffer { public: /*default constructor*/ Framebuffer(); /* Framebuffer constructor @param int w: screen width @param int h: screen height @param int cIndex: color index */ Framebuffer(int w, int h, int colorFormat); /*destructor*/ virtual ~Framebuffer(); /*framebuffer object*/ GLuint fbo; /*texture objects*/ GLuint colorTex; GLuint colorTex1; GLuint colorTex2; GLuint depthTex; int width; int height; /* GLuint createRGBATexture creates an RGBA Texture, returned as an unsigned int @param int w @param int h */ virtual GLuint createRGBATexture(int w, int h, int colorFormat); /* GLuint createLuminanceTexture creates a luminance Texture, returned as an unsigned int @param int w @param int h */ virtual GLuint createLuminanceTexture(int w, int h); /* GLuint createDepthTexture creates a depth Texture, returned as an unsigned int @param int w @param int h */ virtual GLuint createDepthTexture(int w, int h); protected: /* GLuint createFBO @param int w @param int h creates a framebuffer object, returned as an unsigned int. */ GLuint createFBO(int w, int h); virtual void addTextures(); }; class FramebufferMS : public Framebuffer { public: FramebufferMS(int w, int h, int colorFormat); virtual ~FramebufferMS(); virtual GLuint createRGBATexture(int w, int h, int colorFormat); virtual GLuint createLuminanceTexture(int w, int h); virtual GLuint createDepthTexture(int w, int h); virtual void addTextures(); }; #endif
20.607843
78
0.640343
[ "render", "object" ]
e62a713bb1c4fbe627243569c17b05c2a8d37a90
8,685
h
C
src/user.h
fritzr/voronoi-game
77fcc6a40076ab092795445f4e2a73f475338090
[ "MIT" ]
null
null
null
src/user.h
fritzr/voronoi-game
77fcc6a40076ab092795445f4e2a73f475338090
[ "MIT" ]
null
null
null
src/user.h
fritzr/voronoi-game
77fcc6a40076ab092795445f4e2a73f475338090
[ "MIT" ]
1
2020-07-12T03:44:53.000Z
2020-07-12T03:44:53.000Z
#pragma once #include <vector> #include <string> // #include <set> #ifdef DEBUG #include <iostream> #endif #include "adapt_boost_poly.h" #include "polygon.h" #include "shpReader.h" /* A user has a center point and several layers of rings (like a topological * map). Each ring approximates a known fixed travel time (FTT) radius. * To identify the "distance" from a user, we interpolate between these * rings. We use time rather than distance, because it is a more realistic * measurement of a user's willingness to travel, which is a better heuristic * for determining the ideal facility location. * x------------x * | x-------x | For example; in the simplified diagram to the left, three * | | x--x | | rings are shown around a center point. Each ring is * | |1 x--x | | associated with a FTT in seconds, shown as 1, 2, or 3min. * |2 x-------x | Along all points on the outer ring it would take the user * 3 x------------x */ #if 0 /* */ template<typename point> struct angle_sort { point m_dreference; public: angle_sort(const point reference) : m_dreference(reference) {} bool operator()(const point *a, const point *b) const { const point da = *a, db = *b; const double detb = m_dreference.cross(db); // nothing is less than zero degrees if (detb == 0 && db.x * m_dreference.x + db.y * m_dreference.y >= 0) return false; const double deta = m_dreference.cross(da); // zero degrees is less than anything else if (deta == 0 && da.x * m_dreference.x + da.y * m_dreference.y >= 0) return true; if (deta * detb >= 0) { // both on same side of reference, compare to each other return da.cross(db) > 0; } // vectors "less than" zero degrees are actually large, near 2 pi return deta > 0; } }; class user_ring : public c_polygon { private: typedef std::set<ply_vertex *, angle_sort<Point2d> > angular_vertex_set; public: /* Take the first polygon from cpl (move semantics). */ template<typename It> user_ring(const Point2d &center, c_polygon &cpl) { c_ply &cp = cpl.front(); cpl.pop_front(); push_back(cp); indexing(); sorted.insert(cp.begin(), cp.end()); } private: angular_vertex_set sorted; }; #endif /* Travel-Time adapter for the VGame nn1_type concept. */ template<class UserClass, class SolverClass> class TTNN1 { public: typedef SolverClass solver_type; typedef UserClass user_type; typedef typename user_type::coordinate_type coordinate_type; typedef typename user_type::point_type point_type; typedef std::vector<point_type> facility_container; typedef typename facility_container::iterator iterator; typedef typename facility_container::const_iterator const_iterator; typedef typename facility_container::size_type size_type; typedef typename facility_container::value_type value_type; private: std::vector<point_type> facilities_; public: template<class FacilityIter> TTNN1(FacilityIter begin, FacilityIter end) : facilities_(begin, end) {} /* Return the nearest facility to the given user point. */ point_type operator()(user_type const& u) const { /* Because travel time is essentially an arbitrary metric, we can do no * better than a brute-force approach... As far as I know. Perhaps the * range tree could be adapted somehow. */ auto fit = facilities_.begin(); if (fit == facilities_.end()) return point_type(); const point_type *min_facility = &(*fit); coordinate_type min_dist = solver_type::distance(u, *fit++); while (fit != facilities_.end()) { coordinate_type this_dist = solver_type::distance(u, *fit); if (std::abs(this_dist) < std::abs(min_dist)) min_facility = &(*fit); ++fit; } return *min_facility; } inline void insert(point_type const& p) { return facilities_.push_back(p); } inline const_iterator begin(void) const { return facilities_.begin(); } inline const_iterator end(void) const { return facilities_.end(); } inline size_type size(void) const { return facilities_.size(); } }; template<typename Pt_> class User { public: typedef Pt_ point_type; typedef c_ply<point_type> ring_type; typedef c_polygon<point_type> polygon_type; typedef typename polygon_type::coordinate_type coordinate_type; typedef typename bgm::segment<point_type> segment_type; typedef std::vector<polygon_type> isoline_container; typedef typename isoline_container::iterator iterator; typedef typename isoline_container::const_iterator const_iterator; // One would think we can just use bg::distance, but the method considers // rings to be solid, so inner points have a distance of zero. Therefore we // must manually check the distance to each segment in the polygon. static coordinate_type distance(point_type pt, const ring_type &ring) { auto distance = std::numeric_limits<coordinate_type>::max(); if (bg::within(pt, ring)) { segment_type nearestSegment; bg::for_each_segment(ring, [&distance, &pt, &nearestSegment]( const /*auto*/ bgm::referring_segment<const point_type>& segment) { coordinate_type cmpDst = bg::comparable_distance(segment, pt); if (cmpDst < distance) { distance = cmpDst; nearestSegment = segment_type(segment.first, segment.second); } }); distance = bg::distance(nearestSegment, pt); } else { distance = bg::distance(pt, ring); } return distance; } inline static coordinate_type distance(const ring_type &ring, point_type pt) { return distance(pt, ring); } private: // Find the upper and lower isochrone bounds between which the point belongs. bool isochrone_bounds(point_type const& p, const_iterator& lb, const_iterator& ub) const; public: /* Each c_polygon must contain only one ring for now. */ User(const point_type& pt, std::vector<polygon_type> plys) : center_(pt), isolines_(plys) { // Go ahead and triangulate now -- this will be needed for computing // travel time later. for (auto rit = isolines_.begin(); rit != isolines_.end(); ++rit) { rit->triangulate(); rit->getSize(); // index } } /* Interpolate the travel time to a point based on the nearest isoline(s) * with a known fixed travel time. */ coordinate_type travelTime(point_type pt) const; /* Return an isochrone given a point on its boundary by computing the travel * time from the center to that point. */ polygon_type isochrone(point_type const& boundary) const { polygon_type ply; isochrone(ply, boundary); return ply; } // Write the isochrone to the given object instead of copying. void isochrone(polygon_type &p, point_type const& boundary) const; iterator begin(void) { return isolines_.begin(); } iterator end(void) { return isolines_.end(); } const_iterator begin(void) const { return isolines_.cbegin(); } const_iterator end(void) const { return isolines_.cend(); } const_iterator cbegin(void) const { return isolines_.cbegin(); } const_iterator cend(void) const { return isolines_.cend(); } inline const point_type &center(void) const { return center_; } #ifdef DEBUG template<typename Pt__> friend inline std::ostream& operator<<(std::ostream& os, const User<Pt__> &u) { os << u.center_ << " [ ftts: "; auto cpi = u.isolines_.cbegin(); while (cpi != u.isolines_.cend()) { if (cpi != u.isolines_.cbegin()) os << ", "; os << cpi->front().extra().ftt; ++cpi; } os << " ]"; return os; } #endif // DEBUG private: point_type center_; /* Fixed-travel-time (FTT) isolines_. */ isoline_container isolines_; }; template<typename Pt_> extern std::vector<User<Pt_> > readUsers(const std::string &points_path, const std::string &rings_path) { auto /* point_map */ upoints = shp::readIndexedPoints<Pt_>(points_path); auto /* polygon_map */ rings = shp::readPolygons<Pt_>(rings_path); std::vector<User<Pt_> > users; for (auto uit = upoints.begin(); uit != upoints.end(); ++uit) { unsigned int pointIndex = uit->first; typename User<Pt_>::point_type center = uit->second; /* Match a ring list with the user. */ auto ring_lookup = rings.find(pointIndex); if (ring_lookup != rings.end()) { auto ring_list = ring_lookup->second; users.emplace_back(center, ring_list); } else users.emplace_back(center, std::vector<typename User<Pt_>::polygon_type>()); } return users; } extern template class User<boost::geometry::model::d2::point_xy<double> >;
30.907473
86
0.678756
[ "geometry", "object", "vector", "model", "solid" ]
e6304c26c4cd8d57157530c57e61ab1576435cb2
17,612
c
C
k-ind_aig.c
mgudemann/k-ind_aig
1c6c809f6346c3ef5a3aca2077386ca4d0599b1b
[ "MIT" ]
null
null
null
k-ind_aig.c
mgudemann/k-ind_aig
1c6c809f6346c3ef5a3aca2077386ca4d0599b1b
[ "MIT" ]
null
null
null
k-ind_aig.c
mgudemann/k-ind_aig
1c6c809f6346c3ef5a3aca2077386ca4d0599b1b
[ "MIT" ]
null
null
null
/* This k-induction model-checker for sequential circuits in AIG format is based on the original mcaiger code with the following license: --------------------------------------------------------------------------- -- START OF LICENSE FOR MCAIGER SOURCE CODE ------------------------- --------------------------------------------------------------------------- Copyright (c) 2008 - 2010, Armin Biere, Johannes Kepler University. 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. --------------------------------------------------------------------------- -- START OF LICENSE FOR MCAIGER SOURCE CODE ------------------------- --------------------------------------------------------------------------- */ #include "../aiger/aiger.h" #include "../picosat/picosat.h" #include <stdio.h> #include <string.h> #include <assert.h> #include <stdarg.h> #include <limits.h> #include <ctype.h> #include <signal.h> #include <unistd.h> #include <errno.h> #define SAT PICOSAT_SATISFIABLE #define UNSAT PICOSAT_UNSATISFIABLE /* #define _RUP_PROOF_ */ static aiger * model; static int verbosity; static double start; static int witness; static int ionly, bonly; static int dcs, rcs, mix, ncs; static unsigned * frames, sframes, nframes; static unsigned nrcs; #define SOLVER_NAME_MAX 256 #define SOLVER_RESULT_MAX 256 char solver_name[SOLVER_NAME_MAX]; char solver_result[SOLVER_RESULT_MAX]; char solver_cli[SOLVER_NAME_MAX * 2]; PicoSAT *solver; static void die (const char * fmt, ...) { va_list ap; fprintf (stderr, "*** k-ind_aig: "); va_start (ap, fmt); vfprintf (stderr, fmt, ap); va_end (ap); fputc ('\n', stderr); exit (1); } static void catch (int sig) { fprintf (stderr, "*** k-ind_aig: caught signal(%d)\n", sig); fflush (stderr); fflush (stderr); kill (getpid (), sig); } static void catchall (void) { struct sigaction action; memset (&action, 0, sizeof action); action.sa_handler = catch; action.sa_flags = SA_NODEFER | SA_RESETHAND; sigaction (SIGSEGV, &action, 0); sigaction (SIGTERM, &action, 0); sigaction (SIGINT, &action, 0); sigaction (SIGABRT, &action, 0); } static void msg (int level, int include_time, const char * fmt, ...) { double delta; va_list ap; if (verbosity < level) return; fprintf (stderr, "[k-ind_aig] "); if (include_time) { delta = picosat_time_stamp () - start; fprintf (stderr, "%4.1f ", delta < 0.0 ? 0.0 : delta); } va_start (ap, fmt); vfprintf (stderr, fmt, ap); va_end (ap); fputc ('\n', stderr); fflush (stderr); } static int frame (int k) { int res; res = k * model->maxvar + 2; if (dcs || rcs || mix) res += model->num_latches * k * (k - 1) / 2; return res; } static int lit (unsigned k, unsigned l) { int res; assert (0 <= l && l <= 2 * model->maxvar + 1); res = (l <= 1) ? 1 : frame (k) + (int)((l - 2)/2); if (l & 1) res = -res; return res; } static int input (unsigned k, unsigned i) { assert (0 <= i && i < model->num_inputs); return lit (k, model->inputs[i].lit); } static int latch (unsigned k, unsigned i) { assert (0 <= i && i < model->num_latches); return lit (k, model->latches[i].lit); } static int constraint (unsigned k, unsigned i) { assert (0 <= i && i < model->num_constraint); return lit (k, model->constraints[i].lit); } static int next (unsigned k, unsigned i) { assert (0 <= i && i < model->num_latches); return lit (k, model->latches[i].next); } static int bad_state (unsigned k, unsigned i) { assert (0 <= i && i < model->num_bad); return lit (k, model->bad[i].lit); } static void unary (int a) { assert (a); picosat_add (solver, a); picosat_add (solver, 0); } static void binary (int a, int b) { assert (a); picosat_add (solver, a); assert (b); picosat_add (solver, b); picosat_add (solver, 0); } static void ternary (int a, int b, int c) { assert (a); picosat_add (solver, a); assert (b); picosat_add (solver, b); assert (c); picosat_add (solver, c); picosat_add (solver, 0); } static void and (int lhs, int rhs0, int rhs1) { binary (-lhs, rhs0); binary (-lhs, rhs1); ternary (lhs, -rhs0, -rhs1); } static void eq (int lhs, int rhs) { binary (-lhs, rhs); binary (lhs, -rhs); } static void report (int verbosity, unsigned k, const char * phase) { msg (verbosity, 1, "%4u %-10s %10d %11d %11u", k, phase, picosat_variables (solver), picosat_added_original_clauses (solver)); } static void connect (unsigned k) { unsigned i; if (!k) return; for (i = 0; i < model->num_latches; i++) eq (next (k-1, i), latch (k, i)); report (2, k, "connect"); } static void encode (unsigned k, unsigned po) { aiger_and * a; unsigned i; if (!k) unary (lit (k, 1)); /* true */ for (i = 0; i < model->num_ands; i++) { a = model->ands + i; and (lit (k, a->lhs), lit (k, a->rhs0), lit (k, a->rhs1)); } /* encode constraints */ for (i = 0; i < model->num_constraints; i++) { unary (constraint (k, i)); } if (k) { for (i = 0; i < model->num_latches; i++) picosat_add (solver, latch (k, i)); picosat_add (solver, 0); unary (-bad_state (k - 1, po)); } report (2, k, "encode"); } static int diff (int k, int l, int i) { assert (0 <= i && i < model->num_latches); assert (l < k); return frame (k + 1) - i - l * model->num_latches - 1; } static void diffs (unsigned k, unsigned l) { unsigned i, tmp; assert (k != l); if (l > k) { tmp = k; k = l; l = tmp; } for (i = 0; i < model->num_latches; i++) { ternary (latch (l, i), latch (k, i), -diff (k, l, i)); ternary (-latch (l, i), -latch (k, i), -diff (k, l, i)); } for (i = 0; i < model->num_latches; i++) picosat_add (solver, diff (k, l, i)); picosat_add (solver, 0); msg (2, 1, "diffs %u %u", l, k); } static void diffsk (unsigned k) { unsigned l; if (!k) return; for (l = 0; l < k; l++) diffs (k, l); report (2, k, "diffsk"); } static void simple (unsigned k) { if (dcs) diffsk (k); else assert (rcs || ncs); } static void stimulus (unsigned k) { unsigned i, j; int tmp; for (i = 0; i <= k; i++) { for (j = 0; j < model->num_inputs; j++) { tmp = picosat_deref (solver, input (i, j)); fputc (tmp ? ((tmp < 0) ? '0' : '1') : 'x', stdout); } fputc ('\n', stdout); } } static void bad (unsigned k, unsigned po) { assert (model->num_bad > po); picosat_assume (solver, bad_state (k, po)); report (2, k, "bad"); } static void init (unsigned k) { unsigned i; int l; if (bonly && k) return; for (i = 0; i < model->num_latches; i++) { unsigned reset = model->latches[i].reset; /* treat cases with constant resets */ if (reset <= 1) { if (reset == 0) l = -latch (0, i); else l = latch (0, i); if (bonly) unary (l); else picosat_assume (solver, l); } else { unsigned lit, reset; lit = model->latches[i].lit; reset = model->latches[i].reset; /* if equal, leave initial value undefined */ /* if unequal -> fail, as unsupported by AIG */ if (reset != lit) die ("reset of latch %s (%u / lit: %u) is undefined (%u)\n", model->latches[i].name, i, model->latches[i].lit, model->latches[i].reset); } } report (2, k, "init"); } static int cmp_frames (const void * p, const void * q) { unsigned k = *(unsigned *) p; unsigned l = *(unsigned *) q; int a, b, res; unsigned i; for (i = 0; i < model->num_latches; i++) { a = picosat_deref (solver, latch (k, i)); b = picosat_deref (solver, latch (l, i)); res = a - b; if (res) return res; } return 0; } static int sat (unsigned k, unsigned po, char *cnf_file_name) { unsigned i; int res, external_res; int cmp_res; char *fgets_res; FILE *fp; /* call solver and open pipe for communication */ snprintf(solver_cli, 2*SOLVER_NAME_MAX, "%s %s", solver_name, cnf_file_name); if ((fp = popen(solver_cli, "r")) == NULL) { die ("Error opening pipe to solver"); } /* read result from pipe */ int next_char; while (1) { next_char = fgetc(fp); if (verbosity > 1) putchar(next_char); switch (next_char) { case EOF: die ("end of file from pipe before result from SAT query"); break; default: switch ((char) next_char) { /* read result on "s $RESULT" */ case 's': next_char = fgetc(fp); if (next_char == ' ') { fgets_res = fgets(solver_result, SOLVER_RESULT_MAX, fp); if (verbosity > 1) printf("s %s\n", solver_result); cmp_res = strncmp(solver_result, "UNSATISFIABLE", 13); if (cmp_res == 0) { external_res = PICOSAT_UNSATISFIABLE; goto end; } cmp_res = strncmp(solver_result, "SATISFIABLE", 11); if (cmp_res == 0) { external_res = PICOSAT_SATISFIABLE; goto end; } die ("do not understand SAT solvers answer"); } else ungetc(next_char, fp); break; /* skip whole line if not starting with 's' */ default: while (next_char != '\n') { next_char = fgetc(fp); if (verbosity > 1) putchar(next_char); } } } } end: pclose(fp); /* assume false to force picosat to return immediately TODO add real solution for this to simulate incremental solver */ picosat_assume(solver, -1); picosat_assume(solver, 1); res = picosat_sat (solver, -1); return external_res; } static int step (unsigned k, unsigned po) { int res; bad (k, po); report (1, k, "step"); char *cnfFileName = malloc(sizeof(char) * 30); snprintf(cnfFileName, 30, "step_k%u_po%u.cnf", k, po); FILE * cnfFile = fopen(cnfFileName, "w+"); picosat_print(solver, cnfFile); fclose(cnfFile); res = (sat (k, po, cnfFileName) == UNSAT); unlink (cnfFileName); free (cnfFileName); return res; } static int base (unsigned k, unsigned po) { int res; #ifdef _DEBUG_ printf ("encoding base k = %u\n", k); #endif #ifdef _DEBUG_ printf ("encoding base / init k = %u\n", k); #endif init (k); #ifdef _DEBUG_ printf ("encoding base / bad k = %u\n", k); #endif bad (k, po); report (1, k, "base"); #ifdef _DEBUG_ printf ("checking sat k = %u\n", k); #endif char *cnfFileName = malloc(sizeof(char) * 30); snprintf(cnfFileName, 30, "base_k%u_po%u.cnf", k, po); FILE * cnfFile = fopen(cnfFileName, "w+"); picosat_print(solver, cnfFile); fclose(cnfFile); res = (sat (k, po, cnfFileName) == SAT); unlink (cnfFileName); free(cnfFileName); return res; } #define USAGE \ "k-ind_aig [<option> ...][<aiger>]\n" \ "\n" \ "where <option> is one of the following:\n" \ "\n" \ " -h print this command line summary and exit\n" \ " -v increase verbosity (default 0, max 3)\n" \ " -b base case only (only search for witnesses)\n" \ " -w print witness\n" \ " -s <solver_CLI> command line of external DIMACS solver to use\n" \ " <maxk> maximum bound\n" int main (int argc, char ** argv) { const char * name = 0, * err; unsigned k, maxk = 10; int i, cs, res; double delta; start = picosat_time_stamp (); snprintf(solver_name, SOLVER_NAME_MAX, "glucose"); for (i = 1; i < argc; i++) { if (!strcmp (argv[i], "-h")) { fprintf (stderr, USAGE); exit (0); } else if (!strcmp (argv[i], "-v")) verbosity++; else if (!strcmp (argv[i], "-b")) bonly = 1; else if (!strcmp (argv[i], "-w")) witness = 1; else if (isdigit (argv[i][0])) maxk = (unsigned) atoi (argv[i]); /* get name of external solver */ else if (!strcmp (argv[i], "-s")) { snprintf(solver_name, SOLVER_NAME_MAX, "%s", argv[i+1]); i++; } else if (argv[i][0] == '-') die ("invalid command line option '%s'", argv[i]); else if (name) die ("multiple input files '%s' and '%s'", name, argv[i]); else name = argv[i]; } if (ionly && bonly) die ("'-i' and '-b' can not be combined"); cs = dcs + rcs + mix + ncs; if (cs > 1) die ("at most one of '-a', '-r', '-m', '-d', or '-n' can be used"); if (bonly && (cs && !ncs)) die ("can not combine '-b' with '-[armd]'"); if (bonly) ncs = cs = 1; model = aiger_init (); msg (1, 0, "K-Ind_Aig Version 1 (based on McAiger version 2)"); msg (1, 0, "parsing %s", name ? name : "<stdin>"); if (name) err = aiger_open_and_read_from_file (model, name); else err = aiger_read_from_file (model, stdin); if (err) die (err); if (!model->num_bad) die ("no bad states found"); int numberPOs = model->num_bad; if (numberPOs > 1) msg (1, 0, "more than one bad state found"); aiger_reencode (model); msg (1, 0, "%u literals (MILOABC %u %u %u %u %u %u %u)", model->maxvar + 1, model->maxvar, model->num_inputs, model->num_latches, model->num_outputs, model->num_ands, model->num_bad, model->num_constraints); res = 0; for (int po = 0; po < numberPOs; po++) { solver = picosat_init (); #ifdef _RUP_PROOF_ picosat_enable_trace_generation (solver); #endif catchall (); msg (1, 0, "checking po %u", po); picosat_set_prefix (solver, "[picosat] "); picosat_set_output (solver, stderr); if (verbosity > 2) picosat_set_verbosity (solver, verbosity); for (k = 0; k <= maxk; k++) { #ifdef _DEBUG_ printf("increasing k to %u\n", k); #endif #ifdef _DEBUG_ printf("connecting k = %u\n", k); #endif connect (k); #ifdef _DEBUG_ printf("encoding k = %u\n", k); #endif encode (k, po); #ifdef _DEBUG_ printf("simple k = %u\n", k); #endif simple (k); #ifdef _DEBUG_ printf("step k = %u\n", k); #endif if (!bonly && step (k, po)) { report (1, k, "inductive"); fputs ("0\n", stdout); #ifdef _RUP_PROOF_ report (1, k, "writing CNF/RUP proof file"); char *rupFileName = malloc(sizeof(char) * 30); char *cnfFileName = malloc(sizeof(char) * 30); snprintf(rupFileName, 30, "proof_po%u.rup", po); snprintf(cnfFileName, 30, "proof_po%u.cnf", po); FILE * rupFile = fopen(rupFileName, "w+"); FILE * cnfFile = fopen(cnfFileName, "w+"); picosat_write_rup_trace(solver, rupFile); picosat_print(solver, cnfFile); fclose(rupFile); fclose(cnfFile); #ifdef _DEBUG_ printf("written CNF / RUP files %s / %s\n", cnfFileName, rupFileName); #endif free(rupFileName); free(cnfFileName); #endif res = 20; break; } #ifdef _DEBUG_ printf("inconsistent k = %u\n", k); #endif if (bonly && picosat_inconsistent (solver)) { report (1, k, "inconsistent"); fputs ("0\n", stdout); res = 20; break; } #ifdef _DEBUG_ printf("base k = %u\n", k); #endif if (!ionly && base (k, po)) { report (1, k, "reachable"); fputs ("1\n", stdout); if (witness) stimulus (k); res = 10; break; } } if (k > maxk) { report (1, k, "indeterminate"); fputs ("2\n", stdout); } fflush (stdout); picosat_reset (solver); } aiger_reset (model); free (frames); if (rcs || mix) msg (1, 0, "%u refinements of simple path constraints", nrcs); delta = picosat_time_stamp () - start; msg (1, 0, "%.1f seconds", delta < 0.0 ? 0.0 : delta); return res; }
22.464286
84
0.543152
[ "model" ]
e6356d8abc9d12240918e0f3c2743183adef9722
7,056
h
C
cppzstd.h
vargad/cppzstd
f246a9c03950b3f60b85b4a52c1e1e7564792604
[ "MIT" ]
null
null
null
cppzstd.h
vargad/cppzstd
f246a9c03950b3f60b85b4a52c1e1e7564792604
[ "MIT" ]
null
null
null
cppzstd.h
vargad/cppzstd
f246a9c03950b3f60b85b4a52c1e1e7564792604
[ "MIT" ]
null
null
null
// 2018 Daniel Varga (vargad88@gmail.com) #pragma once #include <zstd.h> #include <vector> #include <stdexcept> namespace Zstd { struct ZError : std::runtime_error { using std::runtime_error::runtime_error; }; struct ZUnknownSize : ZError { using ZError::ZError; }; class TrainData { public: TrainData(std::size_t size=100*1024*1024) : mDictBuffer(size) {} template <typename SampleType> void train(std::vector<SampleType> const &samples) { std::vector<std::size_t> sizes(samples.size(), sizeof(SampleType)); auto err = ZDICT_trainFromBuffer(static_cast<void*>(mDictBuffer.data()), size(), static_cast<void const*>(samples.data()), sizes, samples.size()); if (ZDICT_isError(err)) { throw ZError(std::string("train error: {}")+ZDICT_getErrorName(err)); } } void const* data() const { return static_cast<void const*>(mDictBuffer.data()); } std::size_t size() const { return mDictBuffer.size(); } private: std::vector<char> mDictBuffer; }; class CDict { public: CDict(CDict &&) = default; CDict& operator=(CDict &&) = default; CDict(TrainData const &data, int compressionLevel) { mDict = ZSTD_createCDict(data.data(), data.size(), compressionLevel); if (mDict == nullptr) throw std::bad_alloc(); } CDict(CDict const&) = delete; CDict& operator=(CDict const&) = delete; ~CDict() { ZSTD_freeCDict(mDict); } static int maxCompressionLevel() { return ZSTD_maxCLevel(); } ZSTD_CDict const* get() const { return mDict; } private: ZSTD_CDict *mDict; }; class Compress { public: Compress(Compress&) = delete; Compress(Compress&&) = delete; Compress& operator=(Compress&) = delete; Compress& operator=(Compress&&) = delete; static std::size_t compressbound(std::size_t srcSize) { return ZSTD_compressBound(srcSize); } static void compress(std::vector<char> &dst, const void* src, size_t srcSize, int compressionLevel) { dst.resize(compressbound(srcSize)); auto res = ZSTD_compressCCtx(instance().mContext, static_cast<void*>(dst.data()), dst.size(), src, srcSize, compressionLevel); if (static_cast<bool>(ZSTD_isError(res))) { throw ZError(fmt::format(fmt("compress error: {}"), ZSTD_getErrorName(res))); } dst.resize(res); } static std::size_t compress(void* dst, size_t dstCapacity, const void* src, size_t srcSize, int compressionLevel) { auto res = ZSTD_compressCCtx(instance().mContext, dst, dstCapacity, src, srcSize, compressionLevel); if (static_cast<bool>(ZSTD_isError(res))) { throw ZError(fmt::format(fmt("compress error: {}"), ZSTD_getErrorName(res))); } return res; } static void compress(CDict const &dict, std::vector<char> &dst, const void* src, size_t srcSize) { dst.resize(compressbound(srcSize)); auto res = ZSTD_compress_usingCDict(instance().mContext, static_cast<void*>(dst.data()), dst.size(), src, srcSize, dict.get()); if (static_cast<bool>(ZSTD_isError(res))) { throw ZError(fmt::format(fmt("compress error: {}"), ZSTD_getErrorName(res))); } dst.resize(res); } static std::size_t compress(CDict const &dict, void* dst, size_t dstCapacity, const void* src, size_t srcSize) { auto res = ZSTD_compress_usingCDict(instance().mContext, dst, dstCapacity, src, srcSize, dict.get()); if (static_cast<bool>(ZSTD_isError(res))) { throw ZError(fmt::format(fmt("compress error: {}"), ZSTD_getErrorName(res))); } return res; } private: static Compress& instance() { thread_local Compress instr; return instr; } Compress() { mContext = ZSTD_createCCtx(); if (mContext == nullptr) throw std::bad_alloc(); } ~Compress() { ZSTD_freeCCtx(mContext); } ZSTD_CCtx *mContext; }; class DDict { public: DDict(DDict &&) = default; DDict& operator=(DDict &&) = default; DDict(TrainData const &data) { mDict = ZSTD_createDDict(data.data(), data.size()); if (mDict == nullptr) throw std::bad_alloc(); } DDict(DDict const&) = delete; DDict& operator=(DDict const&) = delete; ~DDict() { ZSTD_freeDDict(mDict); } ZSTD_DDict const* get() const { return mDict; } private: ZSTD_DDict *mDict; }; class Decompress { public: Decompress(Decompress&) = delete; Decompress(Decompress&&) = delete; Decompress& operator=(Decompress&) = delete; Decompress& operator=(Decompress&&) = delete; static std::size_t frameContentSize(const void *src, size_t srcSize) { auto size = ZSTD_getFrameContentSize(src, srcSize); if (size == ZSTD_CONTENTSIZE_UNKNOWN) throw ZUnknownSize("unknown size"); if (size == ZSTD_CONTENTSIZE_ERROR) throw ZError("cannot determine size"); return size; } static std::size_t decompress(void* dst, size_t dstCapacity, const void* src, size_t srcSize) { auto res = ZSTD_decompressDCtx(instance().mContext, dst, dstCapacity, src, srcSize); if (static_cast<bool>(ZSTD_isError(res))) { throw ZError(fmt::format(fmt("compress error: {}"), ZSTD_getErrorName(res))); } return res; } static std::size_t decompress(DDict const &dict, void* dst, size_t dstCapacity, const void* src, size_t srcSize) { auto res = ZSTD_decompress_usingDDict(instance().mContext, dst, dstCapacity, src, srcSize, dict.get()); if (static_cast<bool>(ZSTD_isError(res))) { throw ZError(fmt::format(fmt("compress error: {}"), ZSTD_getErrorName(res))); } return res; } private: static Decompress& instance() { thread_local Decompress instr; return instr; } Decompress() { mContext = ZSTD_createDCtx(); if (mContext == nullptr) throw std::bad_alloc(); } ~Decompress() { ZSTD_freeDCtx(mContext); } ZSTD_DCtx *mContext; }; }
32.072727
112
0.550028
[ "vector" ]
e653cdb76c18da094383e86d215d6f46edf0aaf8
897
h
C
gameobject/enemy/EnemiesGO.h
kamil-sita/cpp-roguelike
6723f56e7785328eb4691626f7339fc05a8c3fef
[ "MIT" ]
1
2021-02-04T17:26:08.000Z
2021-02-04T17:26:08.000Z
gameobject/enemy/EnemiesGO.h
kamil-sita/cpp-roguelike
6723f56e7785328eb4691626f7339fc05a8c3fef
[ "MIT" ]
null
null
null
gameobject/enemy/EnemiesGO.h
kamil-sita/cpp-roguelike
6723f56e7785328eb4691626f7339fc05a8c3fef
[ "MIT" ]
1
2019-09-09T17:24:06.000Z
2019-09-09T17:24:06.000Z
#ifndef ROGUELIKE_ENEMIESGO_H #define ROGUELIKE_ENEMIESGO_H #include "EnemyGO.h" #include "../../levels/LevelTiles.h" #include "../PlayerGO.h" class PlayerGO; class EnemyGO; ///EnemiesGO is composite for many EnemyGO. class EnemiesGO : public GameObject { std::vector<EnemyGO> enemies; protected: void draw(sf::RenderWindow& window) override; public: EnemiesGO(ResourceLoader* resources); void add(EnemyGO&& en, std::shared_ptr<EnemiesGO> thisObject); void add(EnemyGO &en, std::shared_ptr<EnemiesGO> thisObject); void removeAll(); void updatePathfinder(Stage& st, std::shared_ptr<PlayerGO> player, std::shared_ptr<LevelTiles> lt); void update(Stage &stage) override; void renderCall(sf::RenderWindow& window) override; void trueRenderCall(sf::RenderWindow& window); int aliveEnemiesCount(); std::vector<EnemyGO> &getEnemies(); }; #endif
24.243243
103
0.725753
[ "vector" ]
0a768e79fccdad26d5d6a04baecf5f89e6ca130a
33,221
c
C
benchmarks/source/superh/ALPBench/Face_Rec/src/csuCommonFile.c
rhudson2802/sunflower-simulator
9f55e03c9d80c024a75029d0e842cc5c92f31c82
[ "BSD-3-Clause" ]
7
2016-05-07T13:38:33.000Z
2019-07-08T03:42:24.000Z
benchmarks/source/superh/ALPBench/Face_Rec/src/csuCommonFile.c
rhudson2802/sunflower-simulator
9f55e03c9d80c024a75029d0e842cc5c92f31c82
[ "BSD-3-Clause" ]
80
2019-08-27T14:43:46.000Z
2020-12-16T11:56:19.000Z
benchmarks/source/superh/ALPBench/Face_Rec/src/csuCommonFile.c
rhudson2802/sunflower-simulator
9f55e03c9d80c024a75029d0e842cc5c92f31c82
[ "BSD-3-Clause" ]
98
2019-08-30T14:29:16.000Z
2020-11-21T18:22:13.000Z
/* * * This file is part of the ALPBench Benchmark Suite Version 1.0 * * Copyright (c) 2005 The Board of Trustees of the University of Illinois * * All rights reserved. * * ALPBench is a derivative of several codes, and restricted by licenses * for those codes, as indicated in the source files and the ALPBench * license at http://www.cs.uiuc.edu/alp/alpbench/alpbench-license.html * * The multithreading and SSE2 modifications for SpeechRec, FaceRec, * MPEGenc, and MPEGdec were done by Man-Lap (Alex) Li and Ruchira * Sasanka as part of the ALP research project at the University of * Illinois at Urbana-Champaign (http://www.cs.uiuc.edu/alp/), directed * by Prof. Sarita V. Adve, Dr. Yen-Kuang Chen, and Dr. Eric Debes. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal with 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: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimers. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimers in the documentation and/or other materials provided * with the distribution. * * * Neither the names of Professor Sarita Adve's research group, the * University of Illinois at Urbana-Champaign, nor the names of its * contributors may be used to endorse or promote products derived * from this Software without specific prior written permission. * * 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 CONTRIBUTORS 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 WITH THE * SOFTWARE. * */ /* File: csuFileCommon.c Authors: J. Ross Beveridge, David Bolme and Kai She Date: March 15, 2002 */ /* Copyright (c) 2003 Colorado State University 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. */ /** * Purpose: This file contains File IO routines used by csuSubspaceTrain * and csuSubspaceTest. */ /****************************************************************************** * INCLUDES * ******************************************************************************/ #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <ctype.h> #include "csuCommon.h" /****************************************************************************** * GLOBALS * ******************************************************************************/ /** * EL and NUM are used to read binary data and convert to proper internal float representation */ typedef struct {char a, b, c, d;} EL; typedef union {float f; EL elem;} NUM; /****************************************************************************** * FILE UTILITIES * ******************************************************************************/ /* The following six functions are used to read and write binary information to file in a way that is platform independant. Each function checks the endianness of the current architecture and reverses the byte order if nessessary. */ typedef struct {char a,b,c,d;} bytes4; typedef union {float n; bytes4 elem;} float4; typedef union {int n; bytes4 elem;} int4; typedef struct {char a,b,c,d,e,f,g,h;} bytes8; typedef union {double n; bytes8 elem;} double8; void writeInt(FILE* f, int n){ int4 tmp; tmp.n = n; if( isMachineLittleEndian() ){ fwrite(&(tmp.elem.d),1,1,f); fwrite(&(tmp.elem.c),1,1,f); fwrite(&(tmp.elem.b),1,1,f); fwrite(&(tmp.elem.a),1,1,f); } else{ fwrite(&(tmp.elem.a),1,1,f); fwrite(&(tmp.elem.b),1,1,f); fwrite(&(tmp.elem.c),1,1,f); fwrite(&(tmp.elem.d),1,1,f); } } void writeFloat(FILE* f, float n){ float4 tmp; tmp.n = n; if( isMachineLittleEndian() ){ fwrite(&(tmp.elem.d),1,1,f); fwrite(&(tmp.elem.c),1,1,f); fwrite(&(tmp.elem.b),1,1,f); fwrite(&(tmp.elem.a),1,1,f); } else{ fwrite(&(tmp.elem.a),1,1,f); fwrite(&(tmp.elem.b),1,1,f); fwrite(&(tmp.elem.c),1,1,f); fwrite(&(tmp.elem.d),1,1,f); } } void writeDouble(FILE* f, double n){ double8 tmp; tmp.n = n; if( isMachineLittleEndian() ){ fwrite(&(tmp.elem.h),1,1,f); fwrite(&(tmp.elem.g),1,1,f); fwrite(&(tmp.elem.f),1,1,f); fwrite(&(tmp.elem.e),1,1,f); fwrite(&(tmp.elem.d),1,1,f); fwrite(&(tmp.elem.c),1,1,f); fwrite(&(tmp.elem.b),1,1,f); fwrite(&(tmp.elem.a),1,1,f); } else{ fwrite(&(tmp.elem.a),1,1,f); fwrite(&(tmp.elem.b),1,1,f); fwrite(&(tmp.elem.c),1,1,f); fwrite(&(tmp.elem.d),1,1,f); fwrite(&(tmp.elem.e),1,1,f); fwrite(&(tmp.elem.f),1,1,f); fwrite(&(tmp.elem.g),1,1,f); fwrite(&(tmp.elem.h),1,1,f); } } void readInt(FILE* f, int* n){ int4 tmp; if(isMachineLittleEndian() ){ fread(&(tmp.elem.d),1,1,f); fread(&(tmp.elem.c),1,1,f); fread(&(tmp.elem.b),1,1,f); fread(&(tmp.elem.a),1,1,f); } else{ fread(&(tmp.elem.a),1,1,f); fread(&(tmp.elem.b),1,1,f); fread(&(tmp.elem.c),1,1,f); fread(&(tmp.elem.d),1,1,f); } *n = tmp.n; } void readFloat(FILE* f, float* n){ float4 tmp; if(isMachineLittleEndian() ){ fread(&(tmp.elem.d),1,1,f); fread(&(tmp.elem.c),1,1,f); fread(&(tmp.elem.b),1,1,f); fread(&(tmp.elem.a),1,1,f); } else{ fread(&(tmp.elem.a),1,1,f); fread(&(tmp.elem.b),1,1,f); fread(&(tmp.elem.c),1,1,f); fread(&(tmp.elem.d),1,1,f); } *n = tmp.n; } /* void readDouble(FILE* f, double* n){ double8 tmp; fread(&tmp, 8, 1, f); *n = tmp.n; } */ void readDouble(FILE* f, double* n){ double8 tmp; if(isMachineLittleEndian() ){ fread(&(tmp.elem.h),1,1,f); fread(&(tmp.elem.g),1,1,f); fread(&(tmp.elem.f),1,1,f); fread(&(tmp.elem.e),1,1,f); fread(&(tmp.elem.d),1,1,f); fread(&(tmp.elem.c),1,1,f); fread(&(tmp.elem.b),1,1,f); fread(&(tmp.elem.a),1,1,f); } else{ fread(&(tmp.elem.a),1,1,f); fread(&(tmp.elem.b),1,1,f); fread(&(tmp.elem.c),1,1,f); fread(&(tmp.elem.d),1,1,f); fread(&(tmp.elem.e),1,1,f); fread(&(tmp.elem.f),1,1,f); fread(&(tmp.elem.g),1,1,f); fread(&(tmp.elem.h),1,1,f); } *n = tmp.n; } /** * Given a directory name and a file name, this function returns a * correctly formed path string. * * Caveat: This function returns a pointer to an internal buffer, * so the value it returns is valid only until the next * call to makePath * * @param directoryName Directory part * @param fileName File name part * @returns Pointer to buffer containing combined path */ char * makePath (const char *directoryName, const char *fileName) { static char path[255]; const char *osDependentPathSeparator = "/"; sprintf (path, "%s%s%s", directoryName, osDependentPathSeparator, fileName); return path; } /** * Ensures that a given directory is writeable. Prints a error message * and exits if it is not or if it is not a directory. * * @param directory Path to an allegedly writeable directory * @param message Message to print if allegation is false */ void checkWriteableDirectory (const char *directory, const char *message) { struct stat buf; int err = stat (directory, &buf); int ok = (err == 0) && S_ISDIR (buf.st_mode) && (access (directory, W_OK) == 0); if (!ok) { fprintf (stderr, message, directory); fprintf (stderr, "\n"); exit (1); } } /** * Ensures that a given directory is readable. Prints a error message * and exits if it is not or if it is not a directory. * * @param directory Path to an allegedly readable directory * @param message Message to print if allegation is false */ void checkReadableDirectory (const char *directory, const char *message) { struct stat buf; int err = stat (directory, &buf); int ok = (err == 0) && S_ISDIR (buf.st_mode) && (access (directory, R_OK) == 0); if (!ok) { fprintf (stderr, message, directory); fprintf (stderr, "\n"); exit (1); } } /** * Ensures that a given file is readable. Prints a error message * and exits if it is not or if it is not a file. * * @param directory Path to an allegedly readable file * @param message Message to print if allegation is false */ void checkReadableFile (const char *file, const char *message) { struct stat buf; int err = stat (file, &buf); int ok = (err == 0) && S_ISREG (buf.st_mode) && (access (file, R_OK) == 0); if (!ok) { fprintf (stderr, message, file); fprintf (stderr, "\n"); exit (1); } } /****************************************************************************** * SIMILARITY RANKING UTILITIES * ******************************************************************************/ /** * Reads all of the names in a file into an array of * strings. Each element of the array is a char pointer. * * If nStrings is non-NULL, the number of strings is * returned in nStrings. * * The array is always one larger than nStrings elements * long and the last element is a NULL. * * @param fileName Name of file to read * @param nStrings Optional pointer to integer that will on return contain * the count of strings read from the file * @returns A NULL-terminated list of NULL-terminated strings */ ListOfStrings readListOfStrings (const char *fileName, int *nStrings) { Tokenizer tok; void *stringList = NULL; FILE *f; char *string; ListOfStrings array; size_t numStrings; f = fopen (fileName, "r"); DEBUG_CHECK (f, "Unable to read file"); tokenizerInit (&tok, tokenizerStreamReader, f); while (!tokenizerEndOfFile (&tok)) { string = strdup (tokenizerGetWord (&tok)); listAccumulate (&stringList, &string, sizeof (unsigned char *)); } fclose (f); /* Add a terminating NULL */ string = NULL; listAccumulate (&stringList, &string, sizeof (unsigned char *)); array = (ListOfStrings)listToArray (&stringList, sizeof (unsigned char *), &numStrings); if (nStrings) *nStrings = numStrings - 1; /* Don't count the NULL */ return array; } /** * Frees a list of strings. * * @param list A NULL-terminated list of NULL-terminated strings. */ void freeListOfStrings (ListOfStrings list) { char **p = list; while (*p != NULL) free (*p++); free (list); } /** * This function counts the string in a NULL-terminated list of strings * * @param list A NULL-terminated list of NULL-terminated strings. * @returns The count of strings in the list */ int countStrings (ListOfStrings list) { int count = 0; char **p = list; while (*p++ != NULL) count++; return count; } /****************************************************************************** * SIMILARITY RANKING UTILITIES * ******************************************************************************/ /** * A data structure for associating a name with a distance score. * * This structure is used internally by "sortSubjectsBySimilarityToProbe" */ typedef struct { char *subject; double distance; int index; } DistanceMeasure; /** * A qsort helper function for sorting DistanceMeasure records. * * This function is used internally by "sortSubjectsBySimilarityToProbe" * * @param a The first object in the pair to compare * @param b The second object in the pair to compare */ int distanceMeasureComparator (const void *a, const void *b) { const DistanceMeasure *d1 = (DistanceMeasure *)a; const DistanceMeasure *d2 = (DistanceMeasure *)b; if (d1->distance < d2->distance) return -1; if (d1->distance > d2->distance) return 1; return 0; } /** * Given a pointer to an array of names of various subjects, and a probe image, * this function sorts the array by similarity to the probe image. As a special * case, if the probe image appears in the subject list, it is ranked as most * dissimilar. This function takes the name of a distance matrix from which * the scores are read. As a special case, if this is NULL, then scores are * picked at random, which effectively shuffles the array. * * If indices is non-NULL, subjects is not shuffled, but instead the indices * of the rearranged items are returned in indices. * * @param probe A probe image against which the subjects are sorted * @param subjects A NULL-terminated list of NULL-terminated strings. * @param distanceMatrix Distance matrix from which scores are read. * @param indices Optional array of integers that will contain the indices of the sorted * elements in the original sequence. This parameter may be NULL. */ void sortSubjectsBySimilarityToProbe (char *probe, ListOfStrings subjects, char *distanceMatrix, int *indices) { int i, j, nDistances; DistanceMeasure *distances = NULL; DistanceMeasure *toSort = NULL; int nSubjects = countStrings (subjects); /* If we are using a distance matrix, then we load up the * list of distances from the probe image. This allows us * to lookup the distances from the probe quickly */ if (distanceMatrix) { Tokenizer tok; FILE *f = fopen (makePath (distanceMatrix, probe), "r"); void *distanceList = NULL; DEBUG_CHECK_1ARG (f, "Unable to open file %s in scores directory", makePath (distanceMatrix, probe)); tokenizerInit (&tok, tokenizerStreamReader, f); while (!tokenizerEndOfFile (&tok)) { DistanceMeasure m; m.subject = strdup (tokenizerGetWord (&tok)); m.distance = atof (tokenizerGetWord (&tok)); listAccumulate (&distanceList, &m, sizeof (DistanceMeasure)); } fclose (f); distances = (DistanceMeasure*) listToArray (&distanceList, sizeof (DistanceMeasure), (size_t*)&nDistances); } /* Copy the list of names into the intermediate data structure that allows us to sort the * subjects by distance to the probe. */ toSort = (DistanceMeasure*) malloc (nSubjects * sizeof (DistanceMeasure)); for (j = 0; j < nSubjects; j++) { toSort[j].subject = subjects[j]; toSort[j].distance = 0.0; toSort[j].index = j; } /* Read distances between probe and every other image in the subject list. * As a special case, a subject is said to be infinitely far away from him/herself. * Random scores are used when a distanceMatrix is not provided */ for (j = 0; j < nSubjects; j++) { if (strcmp (subjects[j], probe) == 0) { /* Probe and subject are the same. Say they are far apart since * we don't want to treat an image and itself as being two replicates * of a person */ toSort[j].distance = HUGE_VAL; } else if (distanceMatrix != NULL) { /* Look for the subject in the list of distances and return assign the * score */ toSort[j].distance = HUGE_VAL; for (i = 0; i < nDistances; ++i) if (strcmp (distances[i].subject, toSort[j].subject) == 0) toSort[j].distance = distances[i].distance; } else { /* If we are not using a distance matrix, then choose * a random value */ toSort[j].distance = ((double) random ()) / RAND_MAX; } } /* Now sort the list by similarity to the probe */ qsort (toSort, nSubjects, sizeof (DistanceMeasure), distanceMeasureComparator); /* Copy the data back into the subject list or return the permuted indices */ if (indices == NULL) for (j = 0; j < nSubjects; j++) { subjects[j] = toSort[j].subject; } else for (j = 0; j < nSubjects; j++) { indices[j] = toSort[j].index; } /* Clean up */ if (distanceMatrix) { for (i = 0; i < nDistances; ++i) free (distances[i].subject); free (distances); } free (toSort); } #define FREAD_FLOAT_CNT 256 /****************************************************************************** * FUNCTIONS FOR WORKING WITH SFI FILES * ******************************************************************************/ /** * Read a binary image from a file where the pixels are stored as 32 bit * floating point numbers using Sun byte order. The compiler directive WINDOWS * is used to control how the byte order is interpreted when storing the pixels * into the data structure images. Images are a one dimensional array of floats * that contains each successive image in sequence, where each image has in turn * been unrolled into a 1 dimensional vector. * * @param fname The name of the file from which to read the image. * @param n The index of this image in the images array. * @param images The matrix into the image is read. Only the nth column is affected. */ void readFile(const char *fname, int n, Matrix images) { int i; FILE *f; #ifdef FASTREAD float fread_buf[FREAD_FLOAT_CNT]; #endif /* char nan_error[100]; char inf_error[100];*/ char line[FILE_LINE_LENGTH]; char imagetype[FILE_LINE_LENGTH]; /*if (debuglevel > 1)*/ printf("\nReading file: %s\n", fname); fflush(stdout); /* Check to makesure file is of expected size */ if (images->row_dim != autoFileLength(fname)) { DEBUG_CHECK(autoFileLength(fname) < images->row_dim, "File does not contian enough values"); printf("Warning: file length is greater than vector length. Croping file...\n"); } f = fopen( fname, "rb" ); assert(f); /*if ( !f ) { printf("Can't open %s\n", fname); exit(1); }*/ /* check to see if image is of type RASTER_ID */ fgets(line,FILE_LINE_LENGTH,f); /* only read in enough to determine * if the file is of proper type */ sscanf(line,"%s",imagetype); if(strcmp(imagetype,RASTER_ID) == 0 || strcmp(imagetype,"CSU_RASTER") ==0){ rewind(f); /* read in the first line to move the buffer to the data. */ fgets(imagetype,FILE_LINE_LENGTH,f); } else{ /* There is no header info. Just read the data */ rewind(f); } #ifdef FASTREAD for (i = 0; i < images->row_dim; ) { int numread=0, j=0; int toread = images->row_dim - i; if (toread > FREAD_FLOAT_CNT) toread = FREAD_FLOAT_CNT; numread = fread(fread_buf, 4, toread, f); assert((toread == numread) && "fread failure"); for (j=0; j < numread; j++) ME(images, i, n) = (FTYPE) fread_buf[j]; i+= numread; } #else /* Set up error messages for use later */ /* sprintf(nan_error, "Not A Number value in file: %s", fname); sprintf(inf_error, "Infinite value in file: %s", fname); */ for (i = 0;i < images->row_dim;i++) { float flt; /* read in the correct byte order for floating point values */ readFloat(f, &flt); #ifdef CHECK_VALS /* Check values to make sure they are real */ /* FINITE(flt);*/ if(!finite(n)) { assert(0 && "infinite value");} #endif /* Save value to images */ ME(images, i, n) = (FTYPE)flt; } #endif fclose(f); } /** * This code was used to detect the length of old nrm images. That file * format is no longer in use the function was renamed and will soon be deleted * -- DSB * * autoFileLength returns the filelength/4 of imageName. This is used * to check the image files and determine at run time how many * floating point values. Note, stat returns the number of bytes, and * the divide by four converts to the number of floats. autoFileLength * lets the code here auto detect the size of the images, i.e. the row * dimension of the covariance matrix, without requiring the user to * pass this value in as an argument * * @param imageName Path to an image * @return The size of the image */ int autoFileLength(const char* imageName) { FILE* f; char imagetype[FILE_LINE_LENGTH]; char line[FILE_LINE_LENGTH]; /* First, check to see if the file is of type RASTER_ID. This is a newer image format which contains the dimensions in a header */ f = fopen(imageName,"r"); if ( !f ) { printf("Can't open %s\n", imageName); exit(1); } fgets(line,FILE_LINE_LENGTH,f); /* only read in enough to determine * if the file is of proper type */ fclose(f); sscanf(line,"%s",imagetype); if (strcmp(imagetype,RASTER_ID) == 0 || strcmp(imagetype,"CSU_RASTER") == 0){ int w,h,c; sscanf(line,"%s %d %d %d",imagetype,&w,&h,&c); return w*h*c; } else { /* Otherwise, we are using an old format and the we return the filelength/4 as the size */ struct stat filestatus; DEBUG_CHECK(0,"Old nrm image format no longer supported"); if (stat(imageName, &filestatus)) { fprintf(stderr, "Error: Could not stat file %s\n", imageName); exit(1); } return filestatus.st_size / 4; } } /** * Code to read the image names being passed in and to create the 2 dimensional table * of these names. Each row is a different subject. Each column is a replicate for that * subject. Linked lists are used along each dimension since prior to reading the file * the number of subjects is unknown, as is the number of replicates per subject. Finally, * the number of replicates per subject may vary for different subjects. * * @param filename A filename to assign to the node. * @returns A malloc'd ImageList node. */ ImageList* createILNode(char* filename) { ImageList* node = (ImageList*)malloc(sizeof(ImageList)); node->filename = (char*)strdup(filename); node->imageIndex = 0; node->next_replicate = NULL; node->next_subject = NULL; return node; } /** * This function reads in the image list file and sets * up a subject replicates list. First the file is * probed to determine the maximum line length. Then * the lines are read in and replicate names are parsed. * * @params imageNamesFile Path to a file containing an srt * @params numImages Pointer to integer that will hold the number of names read * @return A two dimensional ImageList. */ #ifdef THRD ImageList* getImageNames(char* imageNamesFile, int *numImages, int* numSub) { #else ImageList* getImageNames(char* imageNamesFile, int *numImages) { #endif Tokenizer tok; char* token; FILE* ilf; /* Image List File */ ImageList *subject = NULL, *replicate, *header = NULL; int nImages; #ifdef THRD int nSub=0; #endif DEBUG_STRING(2, "Get image Names from file", imageNamesFile); ilf = fopen( imageNamesFile, "r"); DEBUG_CHECK(ilf, "Problem opening image list file"); nImages = 0; tokenizerInit (&tok, tokenizerStreamReader, ilf); while (!tokenizerEndOfFile (&tok)) { token = tokenizerGetWord (&tok); nImages++; #ifdef THRD nSub++; #endif if (header == NULL) { subject = header = createILNode(token); } else { subject->next_subject = createILNode(token); subject = subject->next_subject; } replicate = subject; /*#ifdef THRD*/ replicate->imageIndex = nImages-1; /*#endif*/ while (!tokenizerEndOfLine(&tok) && !tokenizerEndOfFile(&tok)) { token = tokenizerGetWord (&tok); nImages++; replicate->next_replicate = createILNode(token); replicate = replicate->next_replicate; /*#ifdef THRD*/ replicate->imageIndex = nImages-1; /*#endif*/ } } fclose(ilf); if (numImages) #ifdef THRD { if (numSub) *numSub = nSub; printf("Number of subect is %d\n",nSub); #endif *numImages = nImages; #ifdef THRD } #endif return header; } /** * This function reads in the image list file. It then * takes the image filenames and reads in every file. * * @returns A Matrix containing all of the images */ Matrix readImages(char *imageNamesFile, char *imageDirectory, int *numPixels, int *numImages, int *numSubjects, ImageList **srt) { int i; Matrix images; ImageList *subject, *replicate; DEBUG(1, "Reading training file names from file"); #ifdef THRD *srt = getImageNames(imageNamesFile, numImages, NULL); #else *srt = getImageNames(imageNamesFile, numImages); #endif DEBUG_CHECK(*srt, "Error: header no imagenames found in file image list file"); /* Automatically determine number of pixels in images */ DEBUG(1, "Autodetecting number of pixels, i.e. vector length based on the size of image 0."); *numPixels = autoFileLength(makePath(imageDirectory, (*srt)->filename)); DEBUG_INT(1, "Vector length", * numPixels); DEBUG_CHECK(*numPixels > 0, "Error positive value required for a Vector Length"); /* Images stored in the columns of a matrix */ DEBUG(1, "Allocating image matrix"); images = makeMatrix(*numPixels, *numImages); i = 0; (*numSubjects) = 0; for (subject = *srt; subject; subject = subject->next_subject) { for (replicate = subject; replicate; replicate = replicate->next_replicate) { if (debuglevel > 0) printf("%s ", replicate->filename); replicate->imageIndex = i; readFile(makePath(imageDirectory, replicate->filename), i++, images); } if (debuglevel > 0) printf("\n"); (*numSubjects)++; } return images; } /** * This function returns the count of all images in an ImageList * takes the image filenames and reads in every file. * * @param srt An image list * @returns The count of images */ int numImageInImageList(ImageList *srt) { int num = 0; ImageList *subject, *replicate; for (subject = srt; subject; subject = subject->next_subject) { for (replicate = subject; replicate; replicate = replicate->next_replicate) { num++; } } return num; } /** * This function is supposed to free an image list but is not implemented. * I put this in as a placeholder. * * @param srt An image list */ void freeImageNames(ImageList *srt) { /* Not implemented */ } /*------------------------------------------------------------------------ Utilities integrated directly into this source from elsewhere in FERET code distribution. ------------------------------------------------------------------------*/ /** * Reads a FERET nrm file * * @param fn Filename * @param numpix Number of pixels to read * @returns An malloc'd array of floats */ float *readFeretRaster(const char *fn, int numpix) { FILE *fp; float* data; fp = fopen(fn, "rb"); if (fp == NULL) { fprintf (stderr, "failed to open %s", fn); exit(0); } data = (float*)malloc(sizeof(float)*numpix); DEBUG_CHECK (data, "malloc failed"); if (!fread(data, sizeof(float), numpix, fp)) { fprintf (stderr, "fread in readFeretRaster failed"); exit(0); } if (isMachineLittleEndian()) byteswap_4(data, numpix); fclose(fp); return data; } /** * Writes a FERET nrm file * * @param fn Filename * @param data Pointer to an array of floats * @param numpix Number of pixels to read * @returns Whatever was passed in as data */ float *writeFeretRaster(const char *fn, float *data, int numpix) { FILE *fp; fp = fopen(fn, "wb"); if (fp == NULL) { fprintf (stderr, "failed to open %s", fn); exit(0); } if (isMachineLittleEndian()) byteswap_4(data, numpix); if (numpix != fwrite(data, sizeof(float), numpix, fp)) { fprintf (stderr, "fwrite in writeFeretRaster failed"); exit(0); } fclose(fp); return data; } /** * Reads PGM file * * @param filename The name of the file to read * @param w Pointer to an integer which will receive the width of the image * @param h Pointer to an integer which will receive the height of the image * @param verbose When true, we print status information * @returns A pointer to a malloc'd array of bytes */ unsigned char *readImagePGM(const char *filename, int *w, int *h, int verbose) { int width, height, max, i; int val; char fchar; char line[100]; char ftype[16]; FILE *infile; unsigned char *im; /* Read first line, and test if it is propoer PNM type */ if (verbose) fprintf(stdout,"Going to open file %s\n", filename); infile = fopen(filename, "rb"); if (infile == NULL) { fprintf (stderr, "failed to open %s", filename); exit(0); } fgets(line,100,infile); sscanf(line,"%s",ftype); if (verbose) fprintf(stdout,"File Type is %s.\n", ftype); if (strcmp(ftype,"P5") != 0) { fprintf (stderr, "Currently only binary pgm files, type P5, supported"); exit(0); } /* Read lines, ignoring those starting with Comment Character, until the Image Dimensions are read. */ fchar = '#'; while (fchar == '#') { fgets(line,100,infile); sscanf(line, " %c", &fchar); } if (verbose) fprintf(stdout,"Second non-comment line of image file %s.\n", line); sscanf(line, " %d %d", &width, &height); *w = width; *h = height; if (verbose) fprintf(stdout,"The width, height and size are: %d %d %d\n", width, height, width * height); /* Read lines, ignoring those starting with Comment Character, until the maximum pixel value is read. */ fchar = '#'; while (fchar == '#') { fgets(line,100,infile); sscanf(line, " %c", &fchar); } sscanf(line, "%d", &max); if (verbose) fprintf(stdout,"The max value for the pixels is: %d\n", max); if (! (max == 255)) { fprintf(stdout,"readImagePGM: Warning, max value %d for pixels in image %s is not 255\n", max, filename); } im = (unsigned char*) malloc(sizeof(unsigned char)*width*height); DEBUG_CHECK (im, "malloc failed"); i = 0; val = fgetc(infile); while (!(val == EOF) && i < width*height) { im[i] = (unsigned char) val; i++; val = fgetc(infile); } if (verbose) fprintf(stdout,"Read in %d Pixel Values\n", i); fclose(infile); return( im ); } /** * Writes a PGM file * * @param fn The name of the file to write * @param data An array of floats containing the image data * @param numpix Number of pixels. Must be w * h * @param w Pointer to an integer which will receive the width of the image * @param h Pointer to an integer which will receive the height of the image */ void writeImagePGM(const char *fn, float *data, int numpix,int w, int h) { float min, max, sum, scale; int i, val; FILE *fp; min = data[0]; max = data[0]; sum = 0.0; for (i = 1; i < numpix; i++) { if (data[i] < min) min = data[i]; if (data[i] > max) max = data[i]; sum = sum + data[i]; } scale = 255.0 / (max - min); fp = fopen(fn, "wb"); if (fp == NULL) { fprintf (stderr, "failed to open %s", fn); exit(0); } fprintf(fp,"P5\n"); fprintf(fp,"%d %d\n", w, h); fprintf(fp,"255\n"); for (i = 0; i < numpix; i++) { val = (int) ((data[i] - min) * scale); fputc(val,fp); } fclose(fp); }
29.399115
130
0.612173
[ "object", "vector" ]
0a77acaabe5173879ab031db506edb7c23290ac6
2,851
h
C
esphome/components/tm1637/tm1637.h
OttoWinter/esphomeyaml
6a85259e4d6d1b0a0f819688b8e555efcb99ecb0
[ "MIT" ]
249
2018-04-07T12:04:11.000Z
2019-01-25T01:11:34.000Z
esphome/components/tm1637/tm1637.h
OttoWinter/esphomeyaml
6a85259e4d6d1b0a0f819688b8e555efcb99ecb0
[ "MIT" ]
243
2018-04-11T16:37:11.000Z
2019-01-25T16:50:37.000Z
esphome/components/tm1637/tm1637.h
OttoWinter/esphomeyaml
6a85259e4d6d1b0a0f819688b8e555efcb99ecb0
[ "MIT" ]
40
2018-04-10T05:50:14.000Z
2019-01-25T15:20:36.000Z
#pragma once #include "esphome/core/component.h" #include "esphome/core/defines.h" #include "esphome/core/hal.h" #ifdef USE_TIME #include "esphome/components/time/real_time_clock.h" #endif #ifdef USE_BINARY_SENSOR #include "esphome/components/binary_sensor/binary_sensor.h" #endif namespace esphome { namespace tm1637 { class TM1637Display; #ifdef USE_BINARY_SENSOR class TM1637Key; #endif using tm1637_writer_t = std::function<void(TM1637Display &)>; class TM1637Display : public PollingComponent { public: void set_writer(tm1637_writer_t &&writer) { this->writer_ = writer; } void setup() override; void dump_config() override; void set_clk_pin(GPIOPin *pin) { clk_pin_ = pin; } void set_dio_pin(GPIOPin *pin) { dio_pin_ = pin; } float get_setup_priority() const override; void update() override; /// Evaluate the printf-format and print the result at the given position. uint8_t printf(uint8_t pos, const char *format, ...) __attribute__((format(printf, 3, 4))); /// Evaluate the printf-format and print the result at position 0. uint8_t printf(const char *format, ...) __attribute__((format(printf, 2, 3))); /// Print `str` at the given position. uint8_t print(uint8_t pos, const char *str); /// Print `str` at position 0. uint8_t print(const char *str); void set_intensity(uint8_t intensity) { this->intensity_ = intensity; } void set_inverted(bool inverted) { this->inverted_ = inverted; } void set_length(uint8_t length) { this->length_ = length; } void display(); #ifdef USE_BINARY_SENSOR void loop() override; uint8_t get_keys(); void add_tm1637_key(TM1637Key *tm1637_key) { this->tm1637_keys_.push_back(tm1637_key); } #endif #ifdef USE_TIME /// Evaluate the strftime-format and print the result at the given position. uint8_t strftime(uint8_t pos, const char *format, time::ESPTime time) __attribute__((format(strftime, 3, 0))); /// Evaluate the strftime-format and print the result at position 0. uint8_t strftime(const char *format, time::ESPTime time) __attribute__((format(strftime, 2, 0))); #endif protected: void bit_delay_(); void setup_pins_(); bool send_byte_(uint8_t b); uint8_t read_byte_(); void start_(); void stop_(); GPIOPin *dio_pin_; GPIOPin *clk_pin_; uint8_t intensity_; uint8_t length_; bool inverted_; optional<tm1637_writer_t> writer_{}; uint8_t buffer_[6] = {0}; #ifdef USE_BINARY_SENSOR std::vector<TM1637Key *> tm1637_keys_{}; #endif }; #ifdef USE_BINARY_SENSOR class TM1637Key : public binary_sensor::BinarySensor { friend class TM1637Display; public: void set_keycode(uint8_t key_code) { key_code_ = key_code; } void process(uint8_t data) { this->publish_state(static_cast<bool>(data == this->key_code_)); } protected: uint8_t key_code_{0}; }; #endif } // namespace tm1637 } // namespace esphome
27.413462
112
0.732725
[ "vector" ]
0a7d1f8c51474ac6f4cd82812987ca49e51b1fe2
2,647
h
C
samples/extensions/push_descriptors/push_descriptors.h
NoreChair/Vulkan-Samples
30e0ef953f9492726945d2042400a3808c8408f5
[ "Apache-2.0" ]
2,842
2016-02-16T14:01:31.000Z
2022-03-30T19:10:32.000Z
samples/extensions/push_descriptors/push_descriptors.h
ZandroFargnoli/Vulkan-Samples
04278ed5f0f9847ae6897509eb56d7b21b4e8cde
[ "Apache-2.0" ]
316
2016-02-16T20:41:29.000Z
2022-03-29T02:20:32.000Z
samples/extensions/push_descriptors/push_descriptors.h
ZandroFargnoli/Vulkan-Samples
04278ed5f0f9847ae6897509eb56d7b21b4e8cde
[ "Apache-2.0" ]
504
2016-02-16T16:43:37.000Z
2022-03-31T20:24:35.000Z
/* Copyright (c) 2019-2020, Sascha Willems * * SPDX-License-Identifier: Apache-2.0 * * 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. */ /* * Push descriptors * * Note: Requires a device that supports the VK_KHR_push_descriptor extension * * Push descriptors apply the push constants concept to descriptor sets. So instead of creating * per-model descriptor sets (along with a pool for each descriptor type) for rendering multiple objects, * this example uses push descriptors to pass descriptor sets for per-model textures and matrices * at command buffer creation time. */ #pragma once #include "api_vulkan_sample.h" class PushDescriptors : public ApiVulkanSample { public: bool animate = true; PFN_vkCmdPushDescriptorSetKHR vkCmdPushDescriptorSetKHR; VkPhysicalDevicePushDescriptorPropertiesKHR push_descriptor_properties{}; struct Cube { Texture texture; std::unique_ptr<vkb::core::Buffer> uniform_buffer; glm::vec3 rotation; glm::mat4 model_mat; }; std::array<Cube, 2> cubes; struct Models { std::unique_ptr<vkb::sg::SubMesh> cube; } models; struct UniformBuffers { std::unique_ptr<vkb::core::Buffer> scene; } uniform_buffers; struct UboScene { glm::mat4 projection; glm::mat4 view; } ubo_scene; VkPipeline pipeline; VkPipelineLayout pipeline_layout; VkDescriptorSetLayout descriptor_set_layout; PushDescriptors(); ~PushDescriptors(); virtual void request_gpu_features(vkb::PhysicalDevice &gpu) override; void build_command_buffers() override; void load_assets(); void setup_descriptor_set_layout(); void prepare_pipelines(); void prepare_uniform_buffers(); void update_uniform_buffers(); void update_cube_uniform_buffers(float delta_time); void draw(); bool prepare(vkb::Platform &platform) override; virtual void render(float delta_time) override; virtual void on_update_ui_overlay(vkb::Drawer &drawer) override; }; std::unique_ptr<vkb::VulkanSample> create_push_descriptors();
30.425287
106
0.714771
[ "render", "model" ]
0a7f6f778daf2af6cb76a0b0bd3e9528e7e0e5f4
7,513
c
C
dpsk_buck_vmc.X/sources/common/p33c_pral/p33c_opa.c
microchip-pic-avr-examples/dpsk3-power-buck-voltage-mode-control
02aa8bece5635dd7c3139759e825c79a3356356b
[ "ADSL" ]
2
2021-11-05T20:54:44.000Z
2022-02-14T09:41:09.000Z
dpsk_buck_pcmc.X/sources/common/p33c_pral/p33c_opa.c
microchip-pic-avr-examples/dpsk3-power-buck-peak-current-mode-control
94b13b0aeb4846f3ab2648cd2ebc77ae184d201e
[ "ADSL" ]
null
null
null
dpsk_buck_pcmc.X/sources/common/p33c_pral/p33c_opa.c
microchip-pic-avr-examples/dpsk3-power-buck-peak-current-mode-control
94b13b0aeb4846f3ab2648cd2ebc77ae184d201e
[ "ADSL" ]
2
2022-02-08T06:22:33.000Z
2022-02-26T11:13:51.000Z
/* Microchip Technology Inc. and its subsidiaries. You may use this software * and any derivatives exclusively with Microchip products. * * THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER * EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED * WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A * PARTICULAR PURPOSE, OR ITS INTERACTION WITH MICROCHIP PRODUCTS, COMBINATION * WITH ANY OTHER PRODUCTS, OR USE IN ANY APPLICATION. * * IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE, * INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND * WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS * BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE * FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS * IN ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF * ANY, THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE. * * MICROCHIP PROVIDES THIS SOFTWARE CONDITIONALLY UPON YOUR ACCEPTANCE OF THESE * TERMS. */ // Include standard header files #include <xc.h> // include processor files - each processor file is guarded. #include <stdint.h> // include standard integer data types #include <stdbool.h> // include standard boolean data types #include <stddef.h> // include standard definition data types #include "p33c_opa.h" /********************************************************************************* * @fn struct P33C_OPA_MODULE_s* p33c_OpaModule_GetHandle(void) * @ingroup lib-layer-pral-functions-public-opa * @brief Gets pointer to op-amp Module SFR set * @return struct P33C_OPA_MODULE_s*: Pointer to op-amp module special function register set object * * @details * This function returns the pointer to a op-amp module register set * Special Function Register memory space. This pointer can be used to * directly write to/read from the Special Function Registers of the * op-amp peripheral module configuration. *********************************************************************************/ volatile struct P33C_OPA_MODULE_s* p33c_OpaModule_GetHandle(void) { volatile struct P33C_OPA_MODULE_s* opa; // Capture Handle: set pointer to memory address of desired op-amp instance opa = (volatile struct P33C_OPA_MODULE_s*)((volatile uint8_t*) &AMPCON1L); return(opa); } /********************************************************************************* * @fn uint16_t p33c_OpaModule_Dispose(void) * @ingroup lib-layer-pral-functions-public-opa * @brief Resets all Op-Amp Module registers to their RESET default values * @return unsigned integer * @return 0 = failure, disposing OP-Amp module was not successful * @return 1 = success, disposing OP-Amp module was successful * * @details * This function clears all op-amp module registers to their * default values set when the device comes out of RESET. * * Default configuration: * - all operational amplifiers are turned off * - the operational amplifier module is turned off * - all operational amplifier negative inputs are enabled * *********************************************************************************/ volatile uint16_t p33c_OpaModule_Dispose(void) { volatile uint16_t retval=1; retval = p33c_OpaModule_ConfigWrite(opaModuleConfigClear); return(retval); } /********************************************************************************* * @fn struct P33C_OPA_MODULE_s p33c_OpaModule_ConfigRead(void) * @ingroup lib-layer-pral-functions-public-opa * @brief Read the current configuration from the op-amp module base registers * @return struct P33C_OPA_MODULE_s * * @details * This function reads all registers with their current configuration into * a data structure of type P33C_OPA_MODULE_s. Users can read and * verify or modify the configuration to write it back to the op-amp * module registers. * *********************************************************************************/ volatile struct P33C_OPA_MODULE_s p33c_OpaModule_ConfigRead(void) { volatile struct P33C_OPA_MODULE_s* opa; // Set pointer to memory address of desired Op-Amp instance opa = (volatile struct P33C_OPA_MODULE_s*)((volatile uint8_t*) &AMPCON1L); return(*opa); } /********************************************************************************* * @fn uint16_t p33c_OpaModule_ConfigWrite(volatile struct P33C_OPA_MODULE_s opaModuleConfig) * @ingroup lib-layer-pral-functions-public-opa * @brief Writes a user-defined configuration to the op-amp module base registers * @param opaModuleConfig Operation Amplifier Peripheral SFR data object of type struct P33C_OPA_MODULE_s * @return unsigned integer * @return 0 = failure, writing op-amp module was not successful * @return 1 = success, writing op-amp module was successful * * @details * This function writes a user-defined op-amp module configuration of * type P33C_OPA_MODULE_s to the op-amp module base registers. The * individual register configurations have to be set in user-code * before calling this function. To simplify the configuration process * of standard functions, this driver provides templates, which can be * loaded and written directly. * *********************************************************************************/ volatile uint16_t p33c_OpaModule_ConfigWrite( volatile struct P33C_OPA_MODULE_s opaModuleConfig ) { volatile uint16_t retval=1; volatile struct P33C_OPA_MODULE_s* opa; // Set pointer to memory address of the op-amp module base registers opa = (volatile struct P33C_OPA_MODULE_s*)((volatile uint8_t*) &AMPCON1L); *opa = opaModuleConfig; return(retval); } /********************************************************************************* * @var opaModuleConfigClear * @ingroup lib-layer-pral-functions-public-opa * @brief Default RESET configuration of the op-amp module base SFRs * * @details * Default configuration of the op-amp module SFRs with all its registers * being reset to their default state when the device comes out of RESET. * Programmers can use this template to reset (dispose) a previously used * op-amp module when it's not used anymore or to ensure a known startup * condition before writing individual configurations to its SFRs. * ********************************************************************************/ volatile struct P33C_OPA_MODULE_s opaModuleConfigClear = { .AmpCon1L.value = 0x0000, .AmpCon1H.value = 0x0000 }; /********************************************************************************* * @var opaModuleDefault * @ingroup lib-layer-pral-functions-public-opa * @brief Default configuration of op-amp module running from 500 MHz input clock * * @details * Default configuration of the op-amp module SFRs with all its registers * being reset to their default state when the device comes out of RESET. * * Programmers can use this template to reset a previously used * op-amp module when it's not used anymore or to ensure a known startup * condition before writing individual configurations to its SFRs. * ********************************************************************************/ /* */ volatile struct P33C_OPA_MODULE_s opaModuleDefault = { .AmpCon1L.value = 0x0000, .AmpCon1H.value = 0x0007, }; // end of file
40.392473
106
0.6538
[ "object" ]
0a83fcd16c348a27b7193ee87f573f52c82f4121
1,529
h
C
Solv/C++/sat-problem-la-legacy-cpp/headers/LearningAutomata.h
sirarsalih/Algorithms
42794f6889f58691af4b7510e3e03b420267e65c
[ "MIT" ]
null
null
null
Solv/C++/sat-problem-la-legacy-cpp/headers/LearningAutomata.h
sirarsalih/Algorithms
42794f6889f58691af4b7510e3e03b420267e65c
[ "MIT" ]
null
null
null
Solv/C++/sat-problem-la-legacy-cpp/headers/LearningAutomata.h
sirarsalih/Algorithms
42794f6889f58691af4b7510e3e03b420267e65c
[ "MIT" ]
null
null
null
#pragma once #include "LearningAutomata.h" #include "TimeElapsed.h" #include <iostream> #include <map> #include <vector> #include <algorithm> #include <fstream> #include <math.h> class LearningAutomata { public: LearningAutomata(void); std::vector<int> initializeNumbers(std::string numbersString, int &numberOfLiterals); void LearningAutomata::initializeDataStructure(std::vector<std::string> &vectorStringNumbers, std::vector<int> vectorNumbers, std::multimap<std::string, std::vector<std::string>> &multiMapLiteralClause); int randomAssignValuesAndEvaluateSolution(std::ofstream &foutput, std::map<int, int> &mapLiteralsStates, std::vector<std::string> &vectorSatisfiedClauses, std::vector<std::string> &vectorUnsatisfiedClauses, std::string numberOfXLiterals, std::vector<std::string> &vectorStringNumbers, int numberOfLiterals, std::string numberOfClauses, std::map<std::string, bool> &mapLiteralValues, std::multimap<std::string, bool> &mapClauseValues, clock_t begin); void flip(std::map<std::string, bool> &mapLiteralValues, std::string stringLiteral); void run(std::ofstream &foutput, std::map<int, int> &mapLiteralsStates, std::string noLettersCollectionString, int &numberOfLiterals, std::vector<std::string> vectorStringNumbers, std::map<std::string, bool> &mapLiteralValues, std::multimap<std::string, bool> &mapClauseValues, std::string numberOfXLiterals, std::string numberOfClauses, std::multimap<std::string, std::vector<std::string>> &multiMapLiteralClause, clock_t begin); ~LearningAutomata(void); };
66.478261
450
0.784173
[ "vector" ]
0a84ec411e0286265f3028917f0c71ad98401fbd
2,143
h
C
content/common/gpu/gpu_memory_manager.h
Scopetta197/chromium
b7bf8e39baadfd9089de2ebdc0c5d982de4a9820
[ "BSD-3-Clause" ]
212
2015-01-31T11:55:58.000Z
2022-02-22T06:35:11.000Z
content/common/gpu/gpu_memory_manager.h
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
5
2015-03-27T14:29:23.000Z
2019-09-25T13:23:12.000Z
content/common/gpu/gpu_memory_manager.h
1065672644894730302/Chromium
239dd49e906be4909e293d8991e998c9816eaa35
[ "BSD-3-Clause" ]
221
2015-01-07T06:21:24.000Z
2022-02-11T02:51:12.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. #ifndef CONTENT_COMMON_GPU_GPU_MEMORY_MANAGER_H_ #define CONTENT_COMMON_GPU_GPU_MEMORY_MANAGER_H_ #pragma once #if defined(ENABLE_GPU) #include <vector> #include "base/basictypes.h" #include "base/memory/weak_ptr.h" #include "content/common/content_export.h" class GpuCommandBufferStubBase; class CONTENT_EXPORT GpuMemoryManagerClient { public: virtual ~GpuMemoryManagerClient() {} virtual void AppendAllCommandBufferStubs( std::vector<GpuCommandBufferStubBase*>& stubs) = 0; }; class CONTENT_EXPORT GpuMemoryManager { public: enum { kDefaultMaxSurfacesWithFrontbufferSoftLimit = 8 }; // These are predefined values (in bytes) for // GpuMemoryAllocation::gpuResourceSizeInBytes. // Maximum Allocation for all tabs is a soft limit that can be exceeded // during the time it takes for renderers to respect new allocations, // including when switching tabs or opening a new window. // To alleviate some pressure, we decrease our desired limit by "one tabs' // worth" of memory. enum { #if defined(OS_ANDROID) kMinimumAllocationForTab = 32 * 1024 * 1024, kMaximumAllocationForTabs = 64 * 1024 * 1024, #else kMinimumAllocationForTab = 64 * 1024 * 1024, kMaximumAllocationForTabs = 512 * 1024 * 1024 - kMinimumAllocationForTab, #endif }; GpuMemoryManager(GpuMemoryManagerClient* client, size_t max_surfaces_with_frontbuffer_soft_limit); ~GpuMemoryManager(); void ScheduleManage(); private: friend class GpuMemoryManagerTest; void Manage(); class CONTENT_EXPORT StubWithSurfaceComparator { public: bool operator()(GpuCommandBufferStubBase* lhs, GpuCommandBufferStubBase* rhs); }; GpuMemoryManagerClient* client_; bool manage_scheduled_; size_t max_surfaces_with_frontbuffer_soft_limit_; base::WeakPtrFactory<GpuMemoryManager> weak_factory_; DISALLOW_COPY_AND_ASSIGN(GpuMemoryManager); }; #endif #endif // CONTENT_COMMON_GPU_GPU_MEMORY_MANAGER_H_
28.573333
77
0.761549
[ "vector" ]
0a9995bdfb54e719e90b285214765f90fb206140
357
h
C
Physx.NetCore/Source/ObjectTableEventArgs.h
ronbrogan/Physx.NetCore
ac788494b6aefc4b6633c46e857f199e6ab0a47a
[ "MIT" ]
187
2015-01-02T15:58:10.000Z
2022-02-20T05:23:13.000Z
PhysX.Net-3.4/PhysX.Net-3/Source/ObjectTableEventArgs.h
Golangltd/PhysX.Net
fb71e0422d441a16a05ed51348d8afb0328d4b90
[ "MIT" ]
37
2015-01-10T04:38:23.000Z
2022-03-18T00:52:27.000Z
PhysX.Net-3.4/PhysX.Net-3/Source/ObjectTableEventArgs.h
Golangltd/PhysX.Net
fb71e0422d441a16a05ed51348d8afb0328d4b90
[ "MIT" ]
63
2015-01-11T12:12:44.000Z
2022-02-05T14:12:49.000Z
#pragma once namespace PhysX { public ref class ObjectTableEventArgs : System::EventArgs { public: ObjectTableEventArgs(intptr_t unmanagedObject, Object^ managedObject) { this->UnmanagedObject = unmanagedObject; this->ManagedObject = managedObject; } property intptr_t UnmanagedObject; property Object^ ManagedObject; }; };
21
72
0.736695
[ "object" ]
0a9dd4082f2fd662052684364054ecbeee1f8fdf
3,619
c
C
d/avatars/lurue/glitteringarmor.c
gesslar/shadowgate
97ce5d33a2275bb75c0cf6556602564b7870bc77
[ "MIT" ]
13
2019-07-19T05:24:44.000Z
2021-11-18T04:08:19.000Z
d/avatars/lurue/glitteringarmor.c
gesslar/shadowgate
97ce5d33a2275bb75c0cf6556602564b7870bc77
[ "MIT" ]
null
null
null
d/avatars/lurue/glitteringarmor.c
gesslar/shadowgate
97ce5d33a2275bb75c0cf6556602564b7870bc77
[ "MIT" ]
13
2019-09-12T06:22:38.000Z
2022-01-31T01:15:12.000Z
#include <std.h> inherit ARMOUR; void create(){ ::create(); set_name("sheet of ice"); set_id(({ "armor", "breast plate", "breastplate", "glittering carapace", "carapace", "sheet", "ice sheet" })); set_short("%^BOLD%^%^CYAN%^G%^WHITE%^l%^BLUE%^i%^CYAN%^tte%^WHITE%^r%^BLUE%^i%^CYAN%^ng C%^WHITE%^a%^BLUE%^r%^CYAN%^ap%^WHITE%^a%^BLUE%^c%^CYAN%^e%^RESET%^ "); set_obvious_short("%^BOLD%^%^WHITE%^a sheet of ice%^RESET%^"); set_long( @AVATAR %^BOLD%^%^CYAN%^At first look, this sheet of ice appears to be a misshapen giant's bowl. Small spikes, rimmed in frost, adorn one side, providing a means to keep the bowl upright, while the inside is smooth and polished to a %^WHITE%^g%^CYAN%^l%^BLUE%^i%^WHITE%^tte%^CYAN%^r%^BLUE%^i%^WHITE%^ng %^CYAN%^sheen. Around the edge, peculiar %^BLACK%^d%^WHITE%^i%^BLACK%^vo%^RESET%^t%^BOLD%^%^BLACK%^s %^CYAN%^mar the half-oval shaped rim, their indentations as smooth as the interior. On closer inspection, you realize that this is actually a breastplate fashioned from %^WHITE%^i%^CYAN%^c%^WHITE%^e%^CYAN%^. The divots are where the arms and head go, while the half-oval design allows it to fit comfortably over the body. Providing you can find a way to protect yourself from the cold, that is.%^RESET%^ AVATAR ); set_weight(25); set_value(500); set_lore( @AVATAR The Gelugon, sometimes called ice devils, are fierce and horrible warriors feared by many. Their weapons and armor are made of such cold ice that any contact with them can result in near fatal frostbite or worse. Despite this, some are brave enough to fight such creatures, slaughtering them wherever they're found. Such adventurers often report back that when the Gelugon's have melted, that their armor and weapons are left behind. Bringing sheets of curved ice and spears of pure ice back as proof of their success. A few researchers have suggested that these armors and weapons are in fact the exoskeletons of the creatures due to their horrific appearance. AVATAR ); set_property("lore difficulty",20); set_type("armor"); set_limbs(({ "torso" })); set_size(2); set_property("enchantment",3); set_ac(5); set_wear((:TO,"wear_func":)); set_remove((:TO,"remove_func":)); set_struck((:TO,"strike_func":)); } int wear_func(){ tell_room(environment(ETO),"%^BOLD%^%^BLUE%^"+ETOQCN+" begins to shiver uncontrollably.%^RESET%^",ETO); tell_object(ETO,"%^BOLD%^%^BLUE%^You will the frost to expand and form a lattice work of straps across your back, even as you begin to shiver uncontrollably from the nearness of so much ice.%^RESET%^"); return 1; } int remove_func(){ tell_room(environment(ETO),"%^BOLD%^%^BLUE%^"+ETOQCN+" looks incredibly cold.%^RESET%^",ETO); tell_object(ETO,"%^BOLD%^%^BLUE%^Nearly frozen through and through, you will the frost to unbuckle and pull the ice sheet away, exposing patches of frostbite here and there.%^RESET%^"); return 1; } int strike_func(int damage, object what, object who){ if(random(1000) < 200){ tell_room(environment(query_worn()),"%^BOLD%^%^BLUE%^"+who->QCN+" staggers back as a spray of ice and frost from "+ETOQCN+"'s armor showers them in cold!%^RESET%^",({ETO,who})); tell_object(ETO,"%^BOLD%^%^BLUE%^A spray of freezing cold frost flies up into "+who->QCN+"'s face as their weapon makes contact. Their scream alerts you to just how cold a blast it must have been!%^RESET%^"); tell_object(who,"%^BOLD%^%^BLUE%^Your blow lands upon "+ETOQCN+" causing ice crystals from their armor to explode outward and freeze to your exposed skin. The chill is mindnumbing!%^RESET%^"); who->set_paralyzed(roll_dice(2,3)); return damage; } }
64.625
805
0.717878
[ "object" ]
0aa7d32255b009b4dead3053a5265c26255aa41a
920
h
C
include/Engine.h
isqiwen/Render
176821ee2de6eec02e8e3d824e40fb5c267185a2
[ "MIT" ]
null
null
null
include/Engine.h
isqiwen/Render
176821ee2de6eec02e8e3d824e40fb5c267185a2
[ "MIT" ]
null
null
null
include/Engine.h
isqiwen/Render
176821ee2de6eec02e8e3d824e40fb5c267185a2
[ "MIT" ]
1
2021-08-23T11:42:28.000Z
2021-08-23T11:42:28.000Z
#ifndef RENDER_ENGINE_H #define RENDER_ENGINE_H #include <imgpp/imgpp.hpp> #include "Camera.h" #include "RenderWindow.h" #include "Mesh.h" // TODO Probably to change later // Default window value #define WINDOW_DEFAULT_SIZE_W 960 #define WINDOW_DEFAULT_SIZE_H 780 #define WINDOW_DEFAULT_LEFT 0 #define WINDOW_DEFAULT_TOP 0 /** * The core engine that runs the rendering. * */ class Engine { private: Engine(); public: ~Engine(); static Engine& GetInstance(); private: bool is_runing_; RenderWindow render_window_; Camera camera_; Mesh mesh_; imgpp::Img frame_buffer_; imgpp::Img depth_buffer_; public: bool Init(); bool StartRendering(); bool StopRendering(); void Destroy(); private: bool RenderOneFrame(); void RenderAll(); void HandleEvent(int key); }; #endif
19.166667
43
0.640217
[ "mesh" ]
0aa7f333f7303c5e15a6a73490beb6e93df826e7
5,104
h
C
src/RelatedDoc8643.h
xpilot-project/XPMP2
e4c5fe39ca0c3a5ac83bcff4aa87215931433ca0
[ "MIT" ]
17
2020-03-22T04:37:22.000Z
2021-08-19T18:30:42.000Z
src/RelatedDoc8643.h
xpilot-project/XPMP2
e4c5fe39ca0c3a5ac83bcff4aa87215931433ca0
[ "MIT" ]
28
2020-04-05T01:41:36.000Z
2022-02-28T21:48:25.000Z
src/RelatedDoc8643.h
xpilot-project/XPMP2
e4c5fe39ca0c3a5ac83bcff4aa87215931433ca0
[ "MIT" ]
15
2020-03-22T05:30:13.000Z
2021-11-25T17:05:51.000Z
/// @file RelatedDoc8643.h /// @brief Handling the `related.txt` file for creating groups of similar looking aircraft types, /// and Doc8643, the official list of ICAO aircraft type codes. /// @details A related group is declared simply by a line of ICAO a/c type codes read from the file. /// Internally, the group is just identified by its line number in `related.txt`. /// So the group "44" might be "A306 A30B A310", the Airbus A300 series. /// @details Doc8643 is a list of information maintained by the ICAO /// to list all registered aircraft types. Each type designator can appear multiple times /// in the dataset for slightly differing models, but the classification und the WTC /// will be the same in all those listing.\n /// XPMP2 is only interested in type designator, classification, and WTC. /// @author Birger Hoppe /// @copyright (c) 2020 Birger Hoppe /// @copyright 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:\n /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software.\n /// 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 _RelatedDoc8643_h_ #define _RelatedDoc8643_h_ namespace XPMP2 { // // MARK: related.txt // /// Map of group membership: ICAO a/c type maps to line in related.txt typedef std::map<std::string, int> mapRelatedTy; /// Read the `related.txt` file, full path passed in const char* RelatedLoad (const std::string& _path); /// Find the related group for an ICAO a/c type, 0 if none int RelatedGet (const std::string& _acType); // // MARK: Doc843.txt // /// @brief Represents a line in the Doc8643.txt file, of which we use only classification and WTC /// @details Each line has Example lines: /// `(ANY) Glider GLID - -` /// `AAMSA A-9 Quail A9 L1P L` /// `AIRBUS A-380-800 A388 L4J H` /// `CESSNA 172 C172 L1P L` /// `CESSNA 172 Skyhawk C172 L1P L` /// `FAIRCHILD (1) C-26 Metro SW4 L2T L/M` /// `SOLAR IMPULSE 1 SOL1 L4E L` /// `SOLOY Bell 47 B47T H1T L` struct Doc8643 { public: char classification[4] = {0,0,0,0}; char wtc[4] = {0,0,0,0}; public: Doc8643 () {} Doc8643 (const std::string& _classification, const std::string& _wtc); /// Is empty, doesn't contain anything? bool empty () const { return wtc[0] == 0; } char GetClassType () const { return classification[0]; } char GetClassNumEng () const { return classification[1]; } char GetClassEngType () const { return classification[2]; } bool HasRotor () const { return (classification[0] == 'H' || classification[0] == 'G'); } }; /// Map of Doc8643 information, key is the (icao) type code typedef std::map<std::string, Doc8643> mapDoc8643Ty; /// Load the content of the provided `Doc8643.txt` file const char* Doc8643Load (const std::string& _path); /// @brief Return a reference to the matching Doc8643 object. /// @return If no match can be found a reference to a standard empty object is returned. const Doc8643& Doc8643Get (const std::string& _type); /// Is the given aircraft type a valid ICAO type as per Doc8643? bool Doc8643IsTypeValid (const std::string& _type); // // MARK: Obj8DataRefs.txt // /// A pair of strings, first one to search for, second one to replace it with struct Obj8DataRefs { std::string s; ///< search the `.obj` file for this string std::string r; ///< if found replace it with this string /// Constructor just loads the strings Obj8DataRefs (std::string&& _s, std::string&& _r) : s (std::move(_s)), r (std::move(_r)) {} }; /// a list of Obj8DataRefs definitions typedef std::list<Obj8DataRefs> listObj8DataRefsTy; /// Load the content of the provided `Obj8DataRefs.txt` file const char* Obj8DataRefsLoad (const std::string& _path); } #endif
43.623932
103
0.641654
[ "object" ]
0aadab5395c57787ef363fbf5266f64c18f90154
2,560
h
C
cppsrc/ConvexPMFProduct.h
nickmalleson/AgentBasedMCMC
c31cc5e04e9da28373f402bd0bf61cd39e9183c8
[ "MIT" ]
null
null
null
cppsrc/ConvexPMFProduct.h
nickmalleson/AgentBasedMCMC
c31cc5e04e9da28373f402bd0bf61cd39e9183c8
[ "MIT" ]
null
null
null
cppsrc/ConvexPMFProduct.h
nickmalleson/AgentBasedMCMC
c31cc5e04e9da28373f402bd0bf61cd39e9183c8
[ "MIT" ]
null
null
null
// // Created by daniel on 05/08/2021. // #ifndef GLPKTEST_CONVEXPMFPRODUCT_H #define GLPKTEST_CONVEXPMFPRODUCT_H #include <vector> #include "ConvexPMF.h" #include "PMFProduct.h" // If we're multiplying a very large number of terms, better to // hold them separately to avoid stack overflow when optimisation // is turned off or not possible. // // The cast operator allows this class to be cast to an ordinaary // ConvexPMF when required. template<typename DOMAIN> class ConvexPMFProduct { protected: PMFProduct<DOMAIN> atomicPMFs; public: ConvexPolyhedron convexSupport; int nDimensions; ConvexPMFProduct(int nDimensions): nDimensions(nDimensions) { } // ConvexPMFProduct(std::initializer_list<ConvexPMF> init): atomicPMFs(init.size()) { // assert(init.size() != 0); // nDimensions = init.begin()->nDimensions; // } // // ConvexPMFProduct(std::vector<ConvexPMF> atoms): atomicPMFs(std::move(atoms)) { // assert(atoms.size() != 0); // nDimensions = atomicPMFs[0].nDimensions; // } int size() const { return atomicPMFs.size(); } double logP(const DOMAIN &X) const { return atomicPMFs.logP(X); } ConvexPMFProduct &operator *=(ConvexPMF<DOMAIN> atom) { assert(nDimensions == atom.nDimensions); atomicPMFs *= std::move(atom.extendedLogProb); convexSupport += std::move(atom.convexSupport); return *this; } ConvexPMFProduct &operator *=(ConvexPMFProduct<DOMAIN> others) { assert(nDimensions == others.nDimensions); atomicPMFs *= others.atomicPMFs; convexSupport += std::move(others.convexSupport); return *this; } ConvexPMFProduct operator *(ConvexPMF<DOMAIN> other) const & { assert(nDimensions == other.nDimensions); ConvexPMFProduct prod(nDimensions); prod.atomicPMFs = atomicPMFs * std::move(other.extendedLogProb); prod.convexSupport.reserve(convexSupport.size() + other.convexSupport.size()); prod.convexSupport += convexSupport; prod.convexSupport += std::move(other.convexSupport); return prod; } ConvexPMFProduct operator *(ConvexPMF<DOMAIN> other) && { (*this) *= other; return std::move(*this); } operator ConvexPMF<DOMAIN>() const & { return ConvexPMF<DOMAIN>(atomicPMFs, nDimensions, convexSupport); } operator ConvexPMF<DOMAIN>() && { return ConvexPMF<DOMAIN>(std::move(atomicPMFs), nDimensions, std::move(convexSupport)); } }; #endif //GLPKTEST_CONVEXPMFPRODUCT_H
29.090909
110
0.673047
[ "vector" ]
0ab5b797825e395cd1e0bdb758d915bbfaa528e2
1,462
h
C
modules/task_4/rustamov_a_histogram_stretch/histogram_stretch.h
vla5924-practice/parallel-programming-2
4657fd9c02fdd11bbb64614f2aca04356ff45a60
[ "BSD-3-Clause" ]
null
null
null
modules/task_4/rustamov_a_histogram_stretch/histogram_stretch.h
vla5924-practice/parallel-programming-2
4657fd9c02fdd11bbb64614f2aca04356ff45a60
[ "BSD-3-Clause" ]
null
null
null
modules/task_4/rustamov_a_histogram_stretch/histogram_stretch.h
vla5924-practice/parallel-programming-2
4657fd9c02fdd11bbb64614f2aca04356ff45a60
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2021 Rustamov Azer #ifndef MODULES_TASK_4_RUSTAMOV_A_HISTOGRAM_STRETCH_HISTOGRAM_STRETCH_H_ #define MODULES_TASK_4_RUSTAMOV_A_HISTOGRAM_STRETCH_HISTOGRAM_STRETCH_H_ #include <vector> using Matrix = std::vector<int>; Matrix generate_random_image(int w, int h, int min_y = 30, int max_y = 192); void data_distribution(const int data_size, std::vector<int>* limits, int* num_threads, int* count); Matrix make_histogram(const Matrix& image, int w, int h); int get_min_y(const Matrix& histogram); int get_max_y(const Matrix& histogram); void get_min_max_y_std(const Matrix& image, const int& h, const int& w, int* min_y, int* max_y); Matrix stretch_histogram(const Matrix& histogtram, const int& min_y, const int& max_y); Matrix increase_contrast(const Matrix& image, int w, int h, const int& min_y, const int& max_y); void increase_contrast_part(const Matrix* image, Matrix* result, int start, int size, int min_y, int max_y); Matrix increase_contrast_std(const Matrix& image, int w, int h, const int& min_y, const int& max_y); Matrix histogram_sretch_algorithm(const Matrix& image, const int w, const int h); Matrix histogram_sretch_algorithm_std(const Matrix& image, const int w, const int h); #endif // MODULES_TASK_4_RUSTAMOV_A_HISTOGRAM_STRETCH_HISTOGRAM_STRETCH_H_
34.809524
85
0.70041
[ "vector" ]
61dd684635a88c7ff1b354cecbb76e6d6053bd5c
4,555
h
C
opencv_src/modules/features2d/src/img_align/StitchInfoFilter.h
10dimensions/imgalign
99f18a15a06855dc5ba764679a1d75bfd0d2e782
[ "MIT" ]
163
2019-06-04T02:00:58.000Z
2022-03-26T14:23:10.000Z
opencv_src/modules/features2d/src/img_align/StitchInfoFilter.h
shadowzhougit/imgalign
99f18a15a06855dc5ba764679a1d75bfd0d2e782
[ "MIT" ]
8
2019-11-03T10:16:58.000Z
2022-03-16T17:00:14.000Z
opencv_src/modules/features2d/src/img_align/StitchInfoFilter.h
shadowzhougit/imgalign
99f18a15a06855dc5ba764679a1d75bfd0d2e782
[ "MIT" ]
29
2019-01-08T05:43:58.000Z
2022-03-24T00:07:03.000Z
#ifndef IMGALIGN_STITCHINFOFILTERH #define IMGALIGN_STITCHINFOFILTERH #include "CommonTypes.h" #include "EnumTypes.h" #include "MultiStitcher.h" #include "../precomp.hpp" namespace imgalign { struct StitchInfo; class InputImagesReach { public: InputImagesReach(int inReach, int inRange); virtual ~InputImagesReach() {} bool insideReach(int srcI, int dstI) const; private: int reach; int rangeStart; int rangeEnd; }; class StitchInfoFilter { public: StitchInfoFilter(double confidenceThresh, const InputImagesReach *pReach); virtual ~StitchInfoFilter() {} virtual bool pass(const StitchInfo &stitchInfo) const = 0; virtual bool done() const; virtual void addEdge(int /*srcI*/, int /*dstI*/) {}; virtual void setDone() {} void setIteration(int i); protected: int iteration = 0; double cf = 0.4; const InputImagesReach *reach = nullptr; }; class SIF_Std : public StitchInfoFilter { public: SIF_Std(double confidenceThresh, const InputImagesReach *pReach); virtual bool pass(const StitchInfo &stitchInfo) const override; virtual bool done() const override; }; class SIF_IgnoreEdgesConfidence : public StitchInfoFilter { public: SIF_IgnoreEdgesConfidence( double confidenceThresh, const InputImagesReach *pReach, const std::vector<const StitchInfo *> &stitchInfos); virtual bool pass(const StitchInfo &stitchInfo) const override; virtual bool done() const override; private: std::vector<const StitchInfo *> _stitchInfos; }; class SIF_IgnoreImagesConfidence : public StitchInfoFilter { public: SIF_IgnoreImagesConfidence( double confidenceThresh, const InputImagesReach *pReach, const std::vector<const StitchInfo *> &stitchInfos); virtual bool pass(const StitchInfo &stitchInfo) const override; virtual bool done() const override; private: std::vector<int> imageIndices; }; class SIF_BestNeighbourOnly : public StitchInfoFilter { public: SIF_BestNeighbourOnly( double confidenceThresh, const InputImagesReach *pReach, const std::vector<const StitchInfo *> &stitchOrder); virtual bool pass(const StitchInfo &stitchInfo) const override; virtual bool done() const override; private: const std::vector<const StitchInfo *> &_stitchOrder; }; class SIF_IgnoreImagesDeltaSumHV : public StitchInfoFilter { public: SIF_IgnoreImagesDeltaSumHV( double confidenceThresh, const InputImagesReach *pReach, const std::vector<const StitchInfo *> &stitchInfos); virtual bool pass(const StitchInfo &stitchInfo) const override; virtual bool done() const override; private: std::vector<int> imageIndices; }; class SIF_IgnoreEdgesDeltaSumHV : public StitchInfoFilter { public: SIF_IgnoreEdgesDeltaSumHV( double confidenceThresh, const InputImagesReach *pReach, const std::vector<const StitchInfo *> &stitchInfos); virtual bool pass(const StitchInfo &stitchInfo) const override; virtual bool done() const override; private: std::vector<const StitchInfo *> _stitchInfos; }; class SIF_IgnoreEdgesDistortion : public StitchInfoFilter { public: SIF_IgnoreEdgesDistortion( double confidenceThresh, const InputImagesReach *pReach, const std::vector<const StitchInfo *> &stitchInfos, const std::vector<cv::Size> &srcImagesSizes); virtual bool pass(const StitchInfo &stitchInfo) const override; virtual bool done() const override; private: std::vector<std::pair<const StitchInfo *, double>> _stitchInfos; }; class SIF_IgnoreEdgesBlacklist : public StitchInfoFilter { public: SIF_IgnoreEdgesBlacklist(double confidenceThresh, const InputImagesReach *pReach, int edgesN); virtual void addEdge(int srcI, int dstI) override; virtual bool pass(const StitchInfo &stitchInfo) const override; virtual bool done() const override; virtual void setDone() override { doneFlag = true; } private: std::vector<std::pair<int, int>> blacklist; int _edgesN; bool doneFlag = false; }; class SIF_IgnoreEdgesInlierDistance : public StitchInfoFilter { public: SIF_IgnoreEdgesInlierDistance( double confidenceThresh, const InputImagesReach *pReach, const std::vector<const StitchInfo *> &stitchInfos); virtual bool pass(const StitchInfo &stitchInfo) const override; virtual bool done() const override; private: std::vector<std::pair<const StitchInfo *, double>> _stitchInfos; }; } #endif
29.577922
98
0.726235
[ "vector" ]
61ddb61f4c54afb400c4ba1f397752ec84a1cf07
1,833
h
C
MITK/Modules/Core/Common/niftkPolyDataUtils.h
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
13
2018-07-28T13:36:38.000Z
2021-11-01T19:17:39.000Z
MITK/Modules/Core/Common/niftkPolyDataUtils.h
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
null
null
null
MITK/Modules/Core/Common/niftkPolyDataUtils.h
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
10
2018-08-20T07:06:00.000Z
2021-07-07T07:55:27.000Z
/*============================================================================= NifTK: A software platform for medical image computing. Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt in the top level directory for details. =============================================================================*/ #ifndef niftkPolyDataUtils_h #define niftkPolyDataUtils_h #include "niftkCoreExports.h" #include <mitkDataNode.h> #include <mitkPointSet.h> #include <vtkPolyData.h> #include <vtkSmartPointer.h> namespace niftk { /** * \brief Converts an mitk::PointSet to a vtkPolyData. */ NIFTKCORE_EXPORT void PointSetToPolyData (const mitk::PointSet::Pointer& pointsIn, vtkPolyData& polyOut); /** * \brief Converts a node containing either a mitk::PointSet or mitk::Surface to a vtkPolyData. */ NIFTKCORE_EXPORT void NodeToPolyData (const mitk::DataNode::Pointer& node, vtkPolyData& polyOut, const mitk::DataNode::Pointer& cameraNode = mitk::DataNode::Pointer(), bool flipNormals = false); /** * \brief Takes a vector of nodes, and creates a single poly data. */ NIFTKCORE_EXPORT vtkSmartPointer<vtkPolyData> MergePolyData(const std::vector<mitk::DataNode::Pointer>& nodes, const mitk::DataNode::Pointer& cameraNode = mitk::DataNode::Pointer(), bool flipNormals = false ); } // end namespace #endif
35.25
130
0.558101
[ "vector" ]
61e0a2f09270c234f24580b244233a33c34bfc1b
1,600
h
C
cartographer/mapping/internal/2d/normal_estimation_2d.h
jkammerl/cartographer
363c18892cce884e7fc7daa2520a2c3a34d94db9
[ "Apache-2.0" ]
12
2020-11-24T03:46:44.000Z
2022-03-07T07:35:24.000Z
cartographer/mapping/internal/2d/normal_estimation_2d.h
jkammerl/cartographer
363c18892cce884e7fc7daa2520a2c3a34d94db9
[ "Apache-2.0" ]
7
2019-08-20T23:26:24.000Z
2021-04-09T19:30:28.000Z
cartographer/mapping/internal/2d/normal_estimation_2d.h
thirdwave-ai/cartographer
a7394b6d187c206f1b8f80b4bcc5892a4bf42664
[ "Apache-2.0" ]
9
2021-01-13T08:58:47.000Z
2022-03-29T10:27:07.000Z
/* * Copyright 2018 The Cartographer Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef CARTOGRAPHER_MAPPING_INTERNAL_NORMAL_ESTIMATION_2D_H_ #define CARTOGRAPHER_MAPPING_INTERNAL_NORMAL_ESTIMATION_2D_H_ #include <vector> #include "cartographer/mapping/proto/2d/normal_estimation_options_2d.pb.h" #include "cartographer/sensor/point_cloud.h" #include "cartographer/sensor/range_data.h" #include "cartographer/transform/transform.h" namespace cartographer { namespace mapping { proto::NormalEstimationOptions2D CreateNormalEstimationOptions2D( common::LuaParameterDictionary* parameter_dictionary); // Estimates the normal for each 'return' in 'range_data'. // Assumes the angles in the range data returns are sorted with respect to // the orientation of the vector from 'origin' to 'return'. std::vector<float> EstimateNormals( const sensor::RangeData& range_data, const proto::NormalEstimationOptions2D& normal_estimation_options); } // namespace mapping } // namespace cartographer #endif // CARTOGRAPHER_MAPPING_INTERNAL_NORMAL_ESTIMATION_2D_H_
36.363636
75
0.78875
[ "vector", "transform" ]
61fa86bcba5fc8d4f3ca8a0a5c2852774f31f913
1,642
c
C
source/projects/xray.jit.contourmap/max.xray.jit.contourmap.c
Cycling74/xray.jit-1
58f9c891c5c3a0e4bd42ed9977f8328a71c581c2
[ "MIT" ]
2
2017-03-12T01:52:55.000Z
2021-08-05T10:18:24.000Z
source/projects/xray.jit.contourmap/max.xray.jit.contourmap.c
Cycling74/xray.jit-1
58f9c891c5c3a0e4bd42ed9977f8328a71c581c2
[ "MIT" ]
2
2015-11-04T00:49:55.000Z
2015-11-04T00:52:08.000Z
source/xray.contourmap/max.xray.jit.contourmap.c
weshoke/xray.jit
85a1e5a0f504d12fdc3b54bd079772e191a581c1
[ "MIT" ]
4
2015-11-04T00:12:21.000Z
2017-09-05T18:37:46.000Z
/* xray.jit.contourmap Wesley Smith wesley.hoke@gmail.com last modified: 12-7-2006 */ #include "jit.common.h" #include "max.jit.mop.h" typedef struct _max_xray_jit_contourmap { t_object ob; void *obex; } t_max_xray_jit_contourmap; t_jit_err xray_jit_contourmap_init(void); void *max_xray_jit_contourmap_new(t_symbol *s, long argc, t_atom *argv); void max_xray_jit_contourmap_free(t_max_xray_jit_contourmap *x); void *max_xray_jit_contourmap_class; void C74_EXPORT main(void) { void *p,*q; xray_jit_contourmap_init(); setup((t_messlist **)&max_xray_jit_contourmap_class, max_xray_jit_contourmap_new, (method)max_xray_jit_contourmap_free, (short)sizeof(t_max_xray_jit_contourmap), 0L, A_GIMME, 0); p = max_jit_classex_setup(calcoffset(t_max_xray_jit_contourmap,obex)); q = jit_class_findbyname(gensym("xray_jit_contourmap")); max_jit_classex_mop_wrap(p,q,0); max_jit_classex_standard_wrap(p,q,0); addmess((method)max_jit_mop_assist, "assist", A_CANT,0); } void max_xray_jit_contourmap_free(t_max_xray_jit_contourmap *x) { max_jit_mop_free(x); jit_object_free(max_jit_obex_jitob_get(x)); max_jit_obex_free(x); } void *max_xray_jit_contourmap_new(t_symbol *s, long argc, t_atom *argv) { t_max_xray_jit_contourmap *x; void *o; if (x=(t_max_xray_jit_contourmap *)max_jit_obex_new(max_xray_jit_contourmap_class,gensym("xray_jit_contourmap"))) { if (o=jit_object_new(gensym("xray_jit_contourmap"))) { max_jit_mop_setup_simple(x,o,argc,argv); max_jit_attr_args(x,argc,argv); } else { error("xray.jit.contourmap: could not allocate object"); freeobject((t_object *)x); } } return (x); }
26.483871
162
0.774665
[ "object" ]
111255027fdbbd39cfe4191f650963646db0f1b4
8,146
h
C
src/datajson.h
clems71/cppdataframework
93fc51425056acc45404a98e158b63728cfdc7cd
[ "MIT" ]
3
2015-07-16T11:53:46.000Z
2019-03-09T02:38:34.000Z
src/datajson.h
clems71/cppdataframework
93fc51425056acc45404a98e158b63728cfdc7cd
[ "MIT" ]
null
null
null
src/datajson.h
clems71/cppdataframework
93fc51425056acc45404a98e158b63728cfdc7cd
[ "MIT" ]
null
null
null
#pragma once #include <array> #include <chrono> #include <set> #include <string> #include <unordered_map> #include <vector> #include <data.h> #include <json/json.h> using JsonVal = Json::Value; namespace black_magic { // DECODERS ------------------------------------------------------------------------------------ template<typename Policy> inline void jsonDecode(const JsonVal & js, std::string & obj, const Policy &) { obj = js.asString(); } template<typename Policy> inline void jsonDecode(const JsonVal & js, std::chrono::seconds & obj, const Policy &) { const auto text = static_cast<std::string>(js.asString()); auto digitsStr = std::string(); auto unit = std::string(); // Read digits for (size_t i=0; i<text.size(); i++) { if (!isdigit(text[i])) { digitsStr = text.substr(0, i); unit = text.substr(i); break; } } if (digitsStr.empty()) throw std::runtime_error("invalid std::chrono::seconds value"); const auto value = std::stoul(digitsStr); switch (strHash(unit.c_str())) { case strHash("s"): obj = std::chrono::seconds(value); break; case strHash("sec"): obj = std::chrono::seconds(value); break; case strHash("m"): obj = std::chrono::minutes(value); break; case strHash("min"): obj = std::chrono::minutes(value); break; case strHash("h"): obj = std::chrono::hours(value); break; case strHash("hours"): obj = std::chrono::hours(value); break; default: throw std::runtime_error("invalid unit for std::chrono::seconds value"); break; } } template<typename Policy> inline void jsonDecode(const JsonVal & js, std::chrono::microseconds & obj, const Policy &) { const auto text = static_cast<std::string>(js.asString()); auto digitsStr = std::string(); auto unit = std::string(); // Read digits for (size_t i=0; i<text.size(); i++) { if (!isdigit(text[i])) { digitsStr = text.substr(0, i); unit = text.substr(i); break; } } if (digitsStr.empty()) throw std::runtime_error("invalid std::chrono::microseconds value"); const auto value = std::stoul(digitsStr); switch (strHash(unit.c_str())) { case strHash("us"): obj = std::chrono::microseconds(value); break; case strHash("ms"): obj = std::chrono::milliseconds(value); break; case strHash("s"): obj = std::chrono::seconds(value); break; case strHash("sec"): obj = std::chrono::seconds(value); break; case strHash("m"): obj = std::chrono::minutes(value); break; case strHash("min"): obj = std::chrono::minutes(value); break; case strHash("h"): obj = std::chrono::hours(value); break; case strHash("hours"): obj = std::chrono::hours(value); break; default: throw std::runtime_error("invalid unit for std::chrono::microseconds value"); break; } } template<typename Policy> inline void jsonDecode(const JsonVal & js, int & obj, const Policy &) { obj = static_cast<int>(js.asInt()); } template<typename Policy> inline void jsonDecode(const JsonVal & js, size_t & obj, const Policy &) { obj = static_cast<size_t>(js.asInt()); } template<typename Policy> inline void jsonDecode(const JsonVal & js, float & obj, const Policy &) { obj = static_cast<float>(js.asFloat()); } template<typename Policy> inline void jsonDecode(const JsonVal & js, bool & obj, const Policy &) { obj = js.asBool(); } // SFINAE : serializable types (data types) template<typename T> inline auto jsonDecode(const JsonVal & js, T & obj, const LazyPolicy &) -> typename std::enable_if<is_deserializable<T, JsonVal>::value>::type { obj.decodeLazy(js); } template<typename T> inline auto jsonDecode(const JsonVal & js, T & obj, const StrictPolicy &) -> typename std::enable_if<is_deserializable<T, JsonVal>::value>::type { obj.decodeStrict(js); } // Vector of T specialization template<typename T, typename Policy> inline void jsonDecode(const JsonVal & js, std::vector<T> & obj, const Policy & policy) { obj.resize(js.size()); for (size_t i=0; i<js.size(); i++) { ::black_magic::jsonDecode(js[int(i)], obj[i], policy); } } // Ptr of T specialization template<typename T, typename Policy> inline void jsonDecode(const JsonVal & js, std::shared_ptr<T> & obj, const Policy & policy) { if (js.type() == Json::nullValue) { obj.reset(); } else { obj.reset(new T); ::black_magic::jsonDecode(js, *obj, policy); } } // Array of char specialization template<size_t N, typename Policy> inline void jsonDecode(const JsonVal & js, std::array<char, N> & obj, const Policy &) { if (js.size() != obj.size()) throw std::runtime_error("invalid array size"); for (size_t i=0; i<obj.size(); i++) { obj[i] = js.asString().begin()[int(i)]; } } // ENCODERS ------------------------------------------------------------------------------------ // Default encoder (for non serializable types) template<typename T> inline auto jsonEncode(const T & obj, JsonVal & js) -> typename std::enable_if<!is_serializable<T, JsonVal>::value>::type { js = obj; } // Remove ambiguity with previous function template<> inline void jsonEncode(const unsigned long & obj, JsonVal & js) { js = Json::UInt(obj); } template<size_t N> inline void jsonEncode(const std::array<char, N> & obj, JsonVal & js) { js = std::string(obj.begin(), obj.end()); } template<> inline void jsonEncode(const std::chrono::seconds & obj, JsonVal & js) { js = std::to_string(obj.count()) + 's'; } template<> inline void jsonEncode(const std::chrono::microseconds & obj, JsonVal & js) { js = std::to_string(obj.count()) + "us"; } // SFINAE : serializable types (data types) template<class T> inline auto jsonEncode(const T & obj, JsonVal & js) -> typename std::enable_if<is_serializable<T, JsonVal>::value>::type { obj.encode(js); } // Vector of T specialization template<typename T> inline void jsonEncode(const std::vector<T> & obj, JsonVal & js) { js = JsonVal(Json::arrayValue); js.resize(obj.size()); for (size_t i=0; i<obj.size(); i++) { ::black_magic::jsonEncode(obj[i], js[int(i)]); } } // Set of T specialization template<typename T> inline void jsonEncode(const std::set<T> & obj, JsonVal & js) { js = JsonVal(Json::arrayValue); js.resize(obj.size()); int i = 0; for (const auto & item : obj) { ::black_magic::jsonEncode(item, js[i++]); } } // Map<str, V> specialization template<typename T> inline void jsonEncode(const std::unordered_map<std::string, T> & obj, JsonVal & js) { for (const auto & pair : obj) { ::black_magic::jsonEncode(pair.second, js[pair.first]); } } // Ptr of T specialization : (if obj is NULL, will be null in JSON) template<typename T> inline void jsonEncode(const std::shared_ptr<T> & obj, JsonVal & js) { if (!obj) { js = JsonVal(); // Null object } else { ::black_magic::jsonEncode(*obj, js); } } } // namespace black_magic template<> class Encoder<JsonVal> { public: Encoder(JsonVal & js) : js_(js) {} template<typename T> inline void encodeObjectField(const char * fieldName, const T & fieldValue) { black_magic::jsonEncode(fieldValue, js_[fieldName]); } private: JsonVal & js_; }; template<> class Decoder<JsonVal> { public: Decoder(const JsonVal & js) : js_(js) {} template<typename T> inline void decodeObjectFieldStrict(const char * fieldName, T & fieldValue) { black_magic::jsonDecode(js_[fieldName], fieldValue, black_magic::StrictPolicy()); } template<typename T> inline void decodeObjectFieldLazy(const char * fieldName, T & fieldValue) { if (js_.isMember(fieldName)) { black_magic::jsonDecode(js_[fieldName], fieldValue, black_magic::LazyPolicy()); } } private: const JsonVal & js_; }; // Free function to serialize free variables, not an object necessarily template<typename T> inline void jsonEncode(const T & obj, JsonVal & js) { black_magic::jsonEncode(obj, js); } template<typename T> inline void jsonDecodeStrict(const JsonVal & js, T & obj) { black_magic::jsonDecode(js, obj, black_magic::StrictPolicy()); } template<typename T> inline void jsonDecodeNonStrict(const JsonVal & js, T & obj) { black_magic::jsonDecode(js, obj, black_magic::LazyPolicy()); }
28.089655
97
0.657746
[ "object", "vector" ]
111852f3e00e99937069946557b2d46ae69ad348
2,530
h
C
Reflection/Members/MemberWithArguments.h
dnv-opensource/Reflection
27effb850e9f0cc6acc2d48630ee6aa5d75fa000
[ "BSL-1.0" ]
null
null
null
Reflection/Members/MemberWithArguments.h
dnv-opensource/Reflection
27effb850e9f0cc6acc2d48630ee6aa5d75fa000
[ "BSL-1.0" ]
null
null
null
Reflection/Members/MemberWithArguments.h
dnv-opensource/Reflection
27effb850e9f0cc6acc2d48630ee6aa5d75fa000
[ "BSL-1.0" ]
null
null
null
#pragma once // Copyright (c) 2021 DNV AS // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt #include "IMember.h" #include "MemberWithArgumentsFwd.h" #include "MemberType.h" #include "Reflection/TypeConversions/IConversionSequence.h" #include "Reflection/TypeConversions/IConversionGraph.h" #include "TypeUtilities/IntrusiveClass.h" namespace DNVS {namespace MoFa {namespace Reflection {namespace Members { ///MemberWithArguments tries to convert all the arguments to the correct type, and stores the conversion qualities. class REFLECTION_IMPORT_EXPORT MemberWithArguments : public TypeUtilities::IntrusiveClass<MemberWithArguments> { public: MemberWithArguments(TypeConversions::ConversionGraphPointer conversionGraph, MemberPointer member, const std::vector<Variants::Variant>& arguments, MemberType type = MemberType::TypeAll); ///Compares two members for the best conversion quality. int CompareConversionQuality(MemberWithArgumentsPointer other) const; ///Invokes the method with the arguments passed in the constructor. Variants::Variant Invoke(); void Validate(); ///Checks if the member can be called with the input arguments. bool IsOk() const {return m_isValid && !m_isAmbiguous; } MemberWithArgumentsPointer SelectBestOverload(MemberWithArgumentsPointer other); static MemberWithArgumentsPointer SelectBestOverload(MemberWithArgumentsPointer lhs, MemberWithArgumentsPointer rhs); TypeConversions::ConversionSequencePointer GetConversionSequence(Variants::Variant& input, const Types::DecoratedTypeInfo& resultType); void ThrowIfConversionIsInvalid( const Variants::Variant& var, TypeConversions::ConversionSequencePointer conversion, const Types::DecoratedTypeInfo& toType) const; MemberPointer GetMember() const; private: void PrepareArgumentsForInvoke(); MemberType m_memberType; TypeConversions::ConversionGraphPointer m_conversionGraph; MemberPointer m_member; std::vector<Variants::Variant> m_arguments; std::vector<TypeConversions::ConversionSequencePointer> m_conversionArguments; bool m_isValid; bool m_isAmbiguous; bool m_isConverted; static MemberWithArgumentsPointer ReturnFirstIfArgumentConversionSucceeds(MemberWithArgumentsPointer first, MemberWithArgumentsPointer second); }; }}}}
52.708333
195
0.766798
[ "vector" ]
111a28ef50eea1fe91a122b4ea476af6aa8e9141
1,711
h
C
inc/simularium/network/net_message_ids.h
simularium/simularium-engine
1cf72a2b14e92ee560fee6e23ddb2781ac0146e0
[ "Apache-2.0" ]
null
null
null
inc/simularium/network/net_message_ids.h
simularium/simularium-engine
1cf72a2b14e92ee560fee6e23ddb2781ac0146e0
[ "Apache-2.0" ]
6
2022-01-13T22:05:56.000Z
2022-02-16T22:57:43.000Z
inc/simularium/network/net_message_ids.h
simularium/simularium-engine
1cf72a2b14e92ee560fee6e23ddb2781ac0146e0
[ "Apache-2.0" ]
null
null
null
#ifndef AICS_NET_MESSAGE_IDS #define AICS_NET_MESSAGE_IDS #include <string> #include <unordered_map> #include <vector> namespace aics { namespace simularium { enum WebRequestTypes { id_undefined_web_request = 0, id_vis_data_arrive = 1, id_vis_data_request, id_vis_data_finish, id_vis_data_pause, id_vis_data_resume, id_vis_data_abort, id_update_time_step, id_update_rate_param, id_model_definition, id_heartbeat_ping, id_heartbeat_pong, id_trajectory_file_info, id_goto_simulation_time, id_init_trajectory_file }; // static std::unordered_map<std::size_t, std::string> WebRequestNames { { id_undefined_web_request, "undefined" }, { id_vis_data_arrive, "stream data" }, { id_vis_data_request, "stream request" }, { id_vis_data_finish, "stream finish" }, { id_vis_data_pause, "pause" }, { id_vis_data_resume, "resume" }, { id_vis_data_abort, "abort" }, { id_update_time_step, "update time step" }, { id_update_rate_param, "update rate param" }, { id_model_definition, "model definition" }, { id_heartbeat_ping, "heartbeat ping" }, { id_heartbeat_pong, "heartbeat pong" }, { id_trajectory_file_info, "trajectory file info" }, { id_goto_simulation_time, "go to simulation time" }, { id_init_trajectory_file, "init trajectory file" }, }; enum SimulationMode { id_live_simulation = 0, id_pre_run_simulation = 1, id_traj_file_playback = 2 }; } // namespace simularium } // namespace aics #endif // AICS_NET_MESSAGE_IDS
29.5
73
0.649912
[ "vector", "model" ]
111c5c61d7bc561e51494477300b185a34d5996a
7,121
h
C
include/world.h
KBD2/Terrario
dddedf82a9a81a90f60ba9db21e2fa27f6792b59
[ "CC-BY-4.0" ]
null
null
null
include/world.h
KBD2/Terrario
dddedf82a9a81a90f60ba9db21e2fa27f6792b59
[ "CC-BY-4.0" ]
null
null
null
include/world.h
KBD2/Terrario
dddedf82a9a81a90f60ba9db21e2fa27f6792b59
[ "CC-BY-4.0" ]
null
null
null
#pragma once /* ----- WORLD ----- World API functions. */ #include <gint/display.h> #include <stdbool.h> #include "inventory.h" #include "render.h" #include "entity.h" #include "chest.h" #include "save.h" #include "npc.h" #define MAX_FRIENDS 8 enum SupportTypes { SUPPORT_NONE, SUPPORT_KEEP, SUPPORT_NEED, SUPPORT_TOP }; /* I want to keep as much data as I can in here and not the Tile struct */ typedef struct { bopti_image_t *sprite; enum PhysicsTypes physics; bool render; enum SpriteTypes spriteType; // Stop player breaking tiles below it enum SupportTypes support; /* Tiles with spritesheets will treat tiles in here as this tile e.g. dirt and stone */ unsigned char friends[MAX_FRIENDS]; enum Items item; char *name; bool compress; float hitpoints; bool canFlood; } TileData; extern const TileData tiles[]; typedef struct { // Index in tiles array unsigned char id; } Tile; enum Tiles { TILE_NULL = -1, TILE_NOTHING, TILE_STONE, TILE_DIRT, TILE_GRASS, TILE_WOOD, TILE_TRUNK, TILE_ROOT_L, TILE_ROOT_R, TILE_LEAVES, TILE_PLANT, TILE_WBENCH_L, TILE_WBENCH_R, TILE_PLATFORM, TILE_CHAIR_L, TILE_CHAIR_R, TILE_TORCH, TILE_FURNACE_EDGE, TILE_FURNACE_MID, TILE_IRON_ORE, TILE_ANVIL_L, TILE_ANVIL_R, TILE_CHEST_L, TILE_CHEST_R, TILE_DOOR_C, TILE_DOOR_O_L_L, TILE_DOOR_O_L_R, TILE_DOOR_O_R_L, TILE_DOOR_O_R_R, TILE_VINE, TILE_SAND, TILE_CACTUS, TILE_CACTUS_BRANCH, TILE_WATER, TILE_CRYST_L, TILE_CRYST_R, TILE_MUD, TILE_CLAY, TILE_COPPER_ORE, TILE_TIN_ORE, TILE_MUSHROOM, TILE_BOTTLE, TILE_LESSER_HEALING_POTION, TILE_LESSER_MANA_POTION, TILE_GLASS, TILE_AMETHYST, TILE_DIAMOND, TILE_EMERALD, TILE_RUBY, TILE_SAPPHIRE, TILE_TOPAZ, TILE_POT_L, TILE_POT_R, TILE_COBWEB, TILE_SAWMILL_L, TILE_SAWMILL_R, TILE_LOOM_L, TILE_LOOM_R, TILE_BED_EDGE, TILE_BED_MID, TILES_COUNT }; struct World { Tile *tiles; Entity *entities; int numNPCs; NPC *npcs; int numMarkers; HouseMarker *markers; struct ParticleExplosion explosion; int timeTicks; struct Chests chests; void (*placeTile)(int x, int y, Item *item); void (*removeTile)(int x, int y); int (*spawnEntity)(enum Entities entity, int x, int y); bool (*removeEntity)(int idx); bool (*checkFreeEntitySlot)(); }; extern struct World world; typedef union { Tile tiles[4]; uint32_t aligned; } tilePun; extern tilePun group; typedef struct { int num; const enum Items *items; int amountMin; int amountMax; int ratioLow; int ratioHigh; } ItemLoot; struct ItemLootTable { int num; const ItemLoot *loot; }; enum LootTables { TABLE_UNDERGROUND, TABLE_SURFACE, TABLE_POT }; extern struct ItemLootTable loots[]; static inline Tile getTile(int x, int y) { int tileWanted = y * game.WORLD_WIDTH + x; if(game.HWMODE == MODE_RAM) { return world.tiles[tileWanted]; } else { group.aligned = *(uint32_t *)(save.tileData + (tileWanted & ~3)); return group.tiles[tileWanted & 3]; } } static inline void setTile(int x, int y, enum Tiles tile) { int tileWanted = y * game.WORLD_WIDTH + x; uint32_t *nearest; if(game.HWMODE == MODE_RAM) { world.tiles[tileWanted] = (Tile){tile}; return; } else { nearest = save.tileData + (tileWanted & ~3); group.aligned = *nearest; group.tiles[tileWanted & 3] = (Tile){tile}; *nearest = group.aligned; return; } } /* regionChange Sets the status of the region the given coordinates are in. Used to keep track of which world regions are to be saved to file. x, y: Coordinates of a tile within the world. */ void regionChange(int x, int y); /* makeVar Returns a random number between 0 and 2 inclusive, used for tile variations. Returns the random number. */ unsigned char makeVar(); /* generateTree Generates a tree. x, y: Coordinates of the tree's base. baseHeight: Height of the tree before random variation. */ void generateTree(int x, int y, int baseHeight); /* breakTree Breaks a tree, starting from the given trunk coordinate. x, y: Coordinates of a TILE_TRUNK tile. */ void breakTree(int x, int y); /* generateCactus Generates a cactus. x, y: Coordinates of the base of the cactus. height: Height of the cactus. */ void generateCactus(int x, int y, int height); /* breakCactus Breaks a cactus, starting from the given stem coordinates. x, y: Coordinates of a cactus tile. */ void breakCactus(int x, int y); /* breakPot Breaks a pot, dropping the corresponding items. x, y: Coordinates of a pot tile. */ void breakPot(int x, int y); /* findState Returns the appropriate state for the given tile, given its surroundings. x, y: Coordinates of a tile within the world. Returns the state of the tile. */ unsigned char findState(int x, int y); /* placeTile Places the corresponding tile of an item. Decreases the amount of the item if successful. x, y: Coordinates within the world. item: Pointer to the item. */ void placeTile(int x, int y, Item *item); /* removeTile Removes a tile from the world and gives the player the appropriate item/s. x, y: Coordinates of a tile within the world. */ void removeTile(int x, int y); /* openDoor Opens the door at the given position. x, y: Coordinates of a closed door. */ void openDoor(int x, int y); /* closeDoor Closes the door at the given position. x, y: Coordinates of an open door. */ void closeDoor(int x, int y); /* spawnEntity Spawns the given entity at the given coordinates. entity: The entity type to spawn. x, y: Pixel coordinates of the position the entity should be spawned at. Returns the index in the world entity slots of the entity if successful, or -1 if unsuccessful. */ int spawnEntity(enum Entities entity, int x, int y); /* removeEntity Removes the entity at the given slot index. Works even if there is no entity in the slot, but will return false. idx: Index of the entity to be removed. Returns true if successful, false otherwise. */ bool removeEntity(int idx); /* checkFreeEntitySlot Checks the world entity slots to see if one is available. Returns true if one is available, false if none are available. */ bool checkFreeEntitySlot(); /* timeToTicks Returns the ticks for a given 24-hour time. hour: The hour, from 0 to 23. minute: The minute, from 0 to 59. Returns the corresponding number of day ticks.*/ int timeToTicks(int hour, int minute); /* getTime Fills the given pointers with the hour and minute. hour: Pointer to an hour variable. minute: Pointer to a minute variable. */ void getTime(int *hour, int *minute); /* checkArea Performs a generic check that an object has sufficient space to be placed. x, y: Coordinates of the top left of the area. width, height: Size of the area. support: Whether to check if the tiles below the area fully support the area. */ bool checkArea(int x, int y, int width, int height, bool support); /*isDay Returns true if it's currently daytime. */ bool isDay(); /* addLoot Adds loot to a chest from the given loot table. chest: Pointer to the chest. table: The table to use. */ void addLoot(struct Chest *chest, enum LootTables table); /* dropLoot Gives loot to the player from the given loot table. table: The table to use. */ void dropLoot(enum LootTables table);
20.287749
79
0.738239
[ "render", "object" ]
112dc00475752797c3c01c0c89278a0977d7cd33
3,962
h
C
sdk/mutate_impl.h
GeekerClub/xsheet
bc01a945a919e6974ea6f92f633063fc9fbdbf17
[ "MIT" ]
null
null
null
sdk/mutate_impl.h
GeekerClub/xsheet
bc01a945a919e6974ea6f92f633063fc9fbdbf17
[ "MIT" ]
null
null
null
sdk/mutate_impl.h
GeekerClub/xsheet
bc01a945a919e6974ea6f92f633063fc9fbdbf17
[ "MIT" ]
null
null
null
// Copyright (C) 2018, For GeekerClub authors. // Author: An Qin (anqin.qin@gmail.com) // // Description: #ifndef XSHEET_SDK_MUTATION_IPML_H #define XSHEET_SDK_MUTATION_IPML_H #include <stdint.h> #include <string> #include <vector> #include "xsheet/error_code.h" #include "xsheet/mutation.h" namespace xsheet { class RowMutationImpl : public RowMutation { public: RowMutationImpl(); virtual ~RowMutationImpl(); // Return row key. virtual const std::string& RowKey(); // Set the database entry for "key" to "value". The database should be // created as a key-value storage. // "ttl"(time-to-live) is optional, "value" will expire after "ttl" // second. If ttl <= 0, "value" never expire. virtual void Put(const std::string& value, int32_t ttl = -1); // Set the database entry for the specified column to "value". // "timestamp"(us) is optional, current time by default. virtual void Put(const std::string& family, const std::string& qualifier, const std::string& value, int64_t timestamp = -1); // Put an integer into a cell. This cell can be used as a counter. virtual void Put(const std::string& family, const std::string& qualifier, const int64_t value, int64_t timestamp = -1); // Add "delta" to a specified cell. "delta" can be negative. virtual void Add(const std::string& family, const std::string& qualifier, const int64_t delta); // "value" will take effect when specified cell does not exist. // Otherwise, "value" will be discarded. virtual void PutIfAbsent(const std::string& family, const std::string& qualifier, const std::string& value); // Append "value" to a specified cell. virtual void Append(const std::string& family, const std::string& qualifier, const std::string& value); // Delete updates of a specified row/columnfamily/qualifier before "timestamp"(us). // Delete all versions by default. // "timestamp" will be ignored in key-value mode. virtual void DeleteRow(int64_t timestamp = -1); virtual void DeleteFamily(const std::string& family, int64_t timestamp = -1); virtual void DeleteColumns(const std::string& family, const std::string& qualifier, int64_t timestamp = -1); // Delete the cell specified by "family"&"qualifier"&"timestamp". virtual void DeleteColumn(const std::string& family, const std::string& qualifier, int64_t timestamp); // The status of this row mutation. Returns kOK on success and a non-OK // status on error. virtual const ErrorCode& GetError(); // Users are allowed to register callback/context a two-tuples that // will be invoked when this mutation is finished. typedef void (*Callback)(RowMutation* param); virtual void SetCallBack(Callback callback); virtual Callback GetCallBack(); virtual void SetContext(void* context); virtual void* GetContext(); // Set/get timeout(ms). virtual void SetTimeOut(int64_t timeout_ms); virtual int64_t TimeOut(); // EXPRIMENTAL // Returns transaction if exists. virtual Transaction* GetTransaction(); // Get the mutation count of this row mutaion. virtual uint32_t MutationNum(); // Get total size of all mutations, including size of rowkey, columnfamily, // qualifier, value and timestamp. virtual uint32_t Size(); // Get a mutation specified by "index". virtual const RowMutation::Mutation& GetMutation(uint32_t index); private: RowMutationImpl(const RowMutationImpl&); void operator=(const RowMutationImpl&); std::string row_key_; Mutation mutation_; ErrorCode error_; RowMutation::Callback callback_; void* user_context_; std::vector<RowMutation::Mutation> mu_seq_; }; } // namespace xsheet #endif // XSHEET_SDK_MUTATION_IPML_H
37.377358
87
0.674659
[ "vector" ]