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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c3868a9460e252eb423a5d4d49690395211974f5 | 2,603 | h | C | dnn.h | mikeivanov/libcvc | de843ddc428dd310c247055c3308bdc88840ed33 | [
"MIT"
] | null | null | null | dnn.h | mikeivanov/libcvc | de843ddc428dd310c247055c3308bdc88840ed33 | [
"MIT"
] | null | null | null | dnn.h | mikeivanov/libcvc | de843ddc428dd310c247055c3308bdc88840ed33 | [
"MIT"
] | null | null | null | // This file is a part of the LibCVC project.
// It is subject to the license terms in the LICENSE file found
// in the top-level directory of this distribution.
#ifndef CVC_DNN_H
#define CVC_DNN_H
#include <stdbool.h>
#include "core.h"
#ifdef __cplusplus
#include <opencv2/opencv.hpp>
#include <opencv2/dnn.hpp>
typedef cv::dnn::Net * Net;
typedef cv::Ptr<cv::dnn::Layer> * Layer;
extern "C" {
#else
typedef void* Net;
typedef void* Layer;
#endif
extern CvEnum cv_dnn_backend_enum[];
extern CvEnum cv_dnn_target_enum[];
error_t cv_dnn_read_net(const char * model, const char * config, const char * framework, Net * out_net);
error_t cv_dnn_net_free(Net net);
error_t cv_dnn_net_empty(Net net, bool * out_value);
error_t cv_dnn_net_set_input(Net net, Mat blob, const char* name, double scale_factor, Scalar mean);
error_t cv_dnn_net_forward(Net net, const char * output_name, Mat out_result);
error_t cv_dnn_net_forward_layers(Net net, Strings layer_names, Mats out_result);
error_t cv_dnn_net_set_preferable_backend(Net net, int backend);
error_t cv_dnn_net_set_preferable_target(Net net, int target);
error_t cv_dnn_net_get_perf_profile(Net net, Doubles out_layers, int64_t * out_time);
error_t cv_dnn_blob_from_images(Mats images,
Mat out_blob,
double scale_factor,
Size size,
Scalar mean,
bool swap_rb,
bool crop,
int depth);
error_t cv_dnn_net_get_layer_names(Net net, Strings names);
error_t cv_dnn_net_get_layer_with_name(Net net, const char * layer_name, Layer * out_layer);
error_t cv_dnn_net_get_layer_with_id(Net net, int layer_id, Layer * out_layer);
error_t cv_dnn_layer_blobs(Layer layer, Mats out_mats);
error_t cv_dnn_layer_add_blob(Layer layer, Mat blob);
error_t cv_dnn_layer_free(Layer layer);
error_t cv_dnn_layer_input_name_to_index(Layer layer, const char* name, int * out_index);
error_t cv_dnn_layer_output_name_to_index(Layer layer, const char* name, int * out_index);
error_t cv_dnn_layer_name(Layer layer, const char ** out_name);
error_t cv_dnn_layer_type(Layer layer, const char ** out_type);
error_t cv_dnn_nms_boxes(RotatedRects bboxes,
Floats scores,
float score_threshold,
float nms_threshold,
float eta,
int top_k,
Ints out_indices);
#ifdef __cplusplus
}
#endif
#endif // CVC_DNN_H
| 36.661972 | 104 | 0.682674 | [
"model"
] |
c386b39c0a04f208fe2b2075354528e5e2f3d7c1 | 5,477 | h | C | src/mongo/s/commands/document_shard_key_update_util.h | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/s/commands/document_shard_key_update_util.h | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/s/commands/document_shard_key_update_util.h | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2019-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* 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
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#pragma once
#include <boost/optional.hpp>
#include <string>
#include <vector>
#include "mongo/db/logical_session_id.h"
#include "mongo/db/ops/write_ops.h"
#include "mongo/db/transaction_api.h"
#include "mongo/executor/task_executor_pool.h"
#include "mongo/s/transaction_router.h"
namespace mongo {
class BSONObj;
class BSONObjBuilder;
class NamespaceString;
class OperationContext;
class ShardRegistry;
template <typename T>
class StatusWith;
class TaskExecutor;
/**
* Set of functions used to update a document's shard key.
*/
namespace documentShardKeyUpdateUtil {
static constexpr StringData kDuplicateKeyErrorContext =
"Failed to update document's shard key "
"field. There is either an orphan for this document or _id for this collection is not "
"globally unique."_sd;
static constexpr StringData kNonDuplicateKeyErrorContext =
"Update operation was converted into a "
"distributed transaction because the document being updated would move shards and that "
"transaction failed."_sd;
/**
* TODO SERVER-62375: Remove this function.
*
* Coordinating method and external point of entry for updating a document's shard key. This method
* creates the necessary extra operations. It will then run each operation using the ClusterWriter.
* If any statement throws, an exception will leave this method, and must be handled by external
* callers.
*/
bool updateShardKeyForDocumentLegacy(OperationContext* opCtx,
const NamespaceString& nss,
const WouldChangeOwningShardInfo& documentKeyChangeInfo);
/**
* Coordinating method and external point of entry for updating a document's shard key. This method
* creates the necessary extra operations. It will then run each operation using the given
* transaction client. If any statement throws, an exception will leave this method, and must be
* handled by external callers.
*
* Returns an error on any error returned by a command. If the original update was sent with
* {upsert: false}, returns whether or not we deleted the original doc and inserted the new one
* sucessfully. If the original update was sent with {upsert: true}, returns whether or not we
* inserted the new doc successfully.
*/
SemiFuture<bool> updateShardKeyForDocument(const txn_api::TransactionClient& txnClient,
ExecutorPtr txnExec,
const NamespaceString& nss,
const WouldChangeOwningShardInfo& changeInfo);
/**
* Starts a transaction on this session. This method is called when WouldChangeOwningShard is thrown
* for a write that is not in a transaction already.
*/
void startTransactionForShardKeyUpdate(OperationContext* opCtx);
/**
* Commits the transaction on this session. This method is called to commit the transaction started
* when WouldChangeOwningShard is thrown for a write that is not in a transaction already.
*/
BSONObj commitShardKeyUpdateTransaction(OperationContext* opCtx);
/**
* Creates the BSONObj that will be used to delete the pre-image document. Will also attach
* necessary generic transaction and passthrough field transaction information.
*
* This method should not be called outside of this class. It is only temporarily exposed for
* intermediary test coverage.
*/
BSONObj constructShardKeyDeleteCmdObj(const NamespaceString& nss, const BSONObj& updatePreImage);
/*
* Creates the BSONObj that will be used to insert the new document with the post-update image.
* Will attach all necessary generic transaction and passthrough field transaction information.
*
* This method should not be called outside of this class. It is only temporarily exposed for
* intermediary test coverage.
*/
BSONObj constructShardKeyInsertCmdObj(const NamespaceString& nss, const BSONObj& updatePostImage);
} // namespace documentShardKeyUpdateUtil
} // namespace mongo
| 43.125984 | 100 | 0.740734 | [
"vector"
] |
c38889858dd86abb72015e4ddc7478b4a11bd7ac | 688 | h | C | src/game/scene/CreateGame.h | sleepy-monax/projet-jeu-video | 211b607149299e750ebaf5f9a0127ce3428d74d2 | [
"MIT"
] | 6 | 2020-09-29T10:04:15.000Z | 2020-10-10T18:38:22.000Z | src/game/scene/CreateGame.h | team-pinpin/oke-oyibo | 211b607149299e750ebaf5f9a0127ce3428d74d2 | [
"MIT"
] | null | null | null | src/game/scene/CreateGame.h | team-pinpin/oke-oyibo | 211b607149299e750ebaf5f9a0127ce3428d74d2 | [
"MIT"
] | null | null | null | #pragma once
#include "core/Camera.h"
#include "core/Scene.h"
#include "core/Texture.h"
#include "core/World.h"
namespace game
{
class CreateGame: public core::Scene
{
private:
core::Texture background_image;
core::Camera _camera;
utils::RefPtr<core::World> _world;
double _accumulator = 4;
Font _font;
public:
CreateGame(core::Director &dir, core::Registry ®);
~CreateGame();
void update(core::Time &time) override;
void render() override;
void on_switch_in() override;
void on_switch_out() override;
bool stackFrame(core::Time &time);
};
} // namespace game
| 19.657143 | 61 | 0.611919 | [
"render"
] |
c38ce8c0da014bfb4d2eeb511dde5ffb9a129025 | 604 | h | C | MiniJVM/include/compressed_file_reader.h | lanrobin/minijvm | d6056012494656669a6665c981e6b23d8d121df8 | [
"MIT"
] | null | null | null | MiniJVM/include/compressed_file_reader.h | lanrobin/minijvm | d6056012494656669a6665c981e6b23d8d121df8 | [
"MIT"
] | null | null | null | MiniJVM/include/compressed_file_reader.h | lanrobin/minijvm | d6056012494656669a6665c981e6b23d8d121df8 | [
"MIT"
] | null | null | null | #ifndef __JVM_ZIP_FILE_READER__
#define __JVM_ZIP_FILE_READER__
#include <iostream>
#include <vector>
#include "zip/zip.h"
#include "buffer.h"
struct CompressedFileReader
{
public:
CompressedFileReader(const string &filePath);
CompressedFileReader(const wstring &filePath);
bool isValidCompressedFile() const;
vector<wstring> listItems() const;
shared_ptr<Buffer> getItemContent(wstring &itemName);
~CompressedFileReader();
private:
void init(const char *file);
private:
struct zip_t *zip;
vector<wstring> entries;
wstring fileName;
bool isValidZipFile;
};
#endif //__JVM_ZIP_FILE_READER__ | 21.571429 | 54 | 0.789735 | [
"vector"
] |
c394b5da8e3f5fac9ccf1918186a664d42087b61 | 1,818 | h | C | src/gfx/ModelBank.h | Robograde/Robograde | 2c9a7d0b8250ec240102d504127f5c54532cb2b0 | [
"Zlib"
] | 5 | 2015-10-11T10:22:39.000Z | 2019-07-24T10:09:13.000Z | src/gfx/ModelBank.h | Robograde/Robograde | 2c9a7d0b8250ec240102d504127f5c54532cb2b0 | [
"Zlib"
] | null | null | null | src/gfx/ModelBank.h | Robograde/Robograde | 2c9a7d0b8250ec240102d504127f5c54532cb2b0 | [
"Zlib"
] | null | null | null | /**************************************************
Zlib Copyright 2015 Henrik Johansson
***************************************************/
#pragma once
#include "Model.h"
#include "Vertex.h"
#include "VertexBuffer.h"
#include "gfx/ObjectImporter.h"
#define g_ModelBank ModelBank::GetInstance()
#ifdef _WIN32
#ifdef GFX_DLL_EXPORT
#define GFX_API __declspec(dllexport)
#else
#define GFX_API __declspec(dllimport)
#endif
#else
#define GFX_API
#endif
/*
This class loads and store all models and vertices and indices.
It also generates vertex and index buffers
*/
namespace gfx
{
typedef int ModelHandle;
class ModelBank{
public:
GFX_API ~ModelBank();
GFX_API static ModelBank& GetInstance();
GFX_API const Model& FetchModel(const char* filename);
GFX_API const Model& FetchModel(ModelHandle handle);
GFX_API ModelHandle LoadModel(const char* filename);
GFX_API ModelHandle AddModel(Model& TheModel);
GFX_API ModelHandle AddModel( rVector<VertexPosNormalTexTangent>& vertices, rVector<unsigned int>& indices, Model& outModel );
GFX_API ModelHandle AddModel( rVector<VertexPosNormalTexTangentJointsWeights>& vertices, rVector<unsigned int>& indices, Model& outModel );
GFX_API void UpdateModel(ModelHandle& handle, Model& model);
GFX_API void BuildBuffers();
GFX_API void DeleteModel(ModelHandle& handle);
GFX_API void ApplyBuffers( VertexType vertexType );
GFX_API void Clear();
GFX_API VertexBuffer& GetVertexBuffer( VertexType modelType );
GFX_API GLuint& GetIndexBuffer( VertexType modelType );
private:
ModelBank();
rMap<VertexType, int> m_ModeltypeOffsets;
rMap<VertexType, VertexBuffer> m_VertexBuffers;
rMap<VertexType, GLuint> m_IndexBuffers;
rMap<VertexType, int> m_Numerators;
ObjectImporter m_MeshImporter;
rMap<ModelHandle, Model> m_Models;
};
}
| 32.464286 | 141 | 0.735974 | [
"model"
] |
c39eb7007f727a72dd4ab5dcfb16cd6179a4ebab | 2,200 | h | C | PrivateFrameworks/iWorkImport.framework/TSCH3DChartShadowsSceneObject.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | 36 | 2016-04-20T04:19:04.000Z | 2018-10-08T04:12:25.000Z | PrivateFrameworks/iWorkImport.framework/TSCH3DChartShadowsSceneObject.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | null | null | null | PrivateFrameworks/iWorkImport.framework/TSCH3DChartShadowsSceneObject.h | shaojiankui/iOS10-Runtime-Headers | 6b0d842bed0c52c2a7c1464087b3081af7e10c43 | [
"MIT"
] | 10 | 2016-06-16T02:40:44.000Z | 2019-01-15T03:31:45.000Z | /* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/iWorkImport.framework/iWorkImport
*/
@interface TSCH3DChartShadowsSceneObject : TSCH3DSceneObject
+ (void)invalidateShadowsForScene:(id)arg1;
+ (void)setShadowPlanePadding:(struct box<glm::detail::tvec3<float> > { struct tvec3<float> { union { float x_1_2_1; float x_1_2_2; float x_1_2_3; } x_1_1_1; union { float x_2_2_1; float x_2_2_2; float x_2_2_3; } x_1_1_2; union { float x_3_2_1; float x_3_2_2; float x_3_2_3; } x_1_1_3; } x1; struct tvec3<float> { union { float x_1_2_1; float x_1_2_2; float x_1_2_3; } x_2_1_1; union { float x_2_2_1; float x_2_2_2; float x_2_2_3; } x_2_1_2; union { float x_3_2_1; float x_3_2_2; float x_3_2_3; } x_2_1_3; } x2; })arg1 forScene:(id)arg2;
- (id)TSDShadowFromScene:(id)arg1;
- (struct tvec3<float> { union { float x_1_1_1; float x_1_1_2; float x_1_1_3; } x1; union { float x_2_1_1; float x_2_1_2; float x_2_1_3; } x2; union { float x_3_1_1; float x_3_1_2; float x_3_1_3; } x3; })calculateShadowCameraPosition:(float)arg1 center:(struct tvec3<float> { union { float x_1_1_1; float x_1_1_2; float x_1_1_3; } x1; union { float x_2_1_1; float x_2_1_2; float x_2_1_3; } x2; union { float x_3_1_1; float x_3_1_2; float x_3_1_3; } x3; })arg2 shadowQuality:(float)arg3 depthLimitAdjustment:(float)arg4;
- (id)effects;
- (void)getBounds:(id)arg1;
- (float)p_chartOpacityForScene:(id)arg1;
- (struct box<glm::detail::tvec3<float> > { struct tvec3<float> { union { float x_1_2_1; float x_1_2_2; float x_1_2_3; } x_1_1_1; union { float x_2_2_1; float x_2_2_2; float x_2_2_3; } x_1_1_2; union { float x_3_2_1; float x_3_2_2; float x_3_2_3; } x_1_1_3; } x1; struct tvec3<float> { union { float x_1_2_1; float x_1_2_2; float x_1_2_3; } x_2_1_1; union { float x_2_2_1; float x_2_2_2; float x_2_2_3; } x_2_1_2; union { float x_3_2_1; float x_3_2_2; float x_3_2_3; } x_2_1_3; } x2; })p_shadowPlanePaddingForScene:(id)arg1;
- (void)prerender:(id)arg1;
- (void)prerenderShadows:(id)arg1 blurslack:(float)arg2 angle:(float)arg3 quality:(float)arg4 targetFBO:(id)arg5;
- (id)propertiesForScene:(id)arg1;
- (void)render:(id)arg1;
- (void)renderShadowScene:(id)arg1;
- (void)renderShadows:(id)arg1;
@end
| 91.666667 | 537 | 0.745909 | [
"render"
] |
c3a52f5e53b80a6fa92383e65e637c32c3802183 | 539 | h | C | memory/structs/vector.h | ABCxFF/diepindepth | 498d68d4af6764632838bd9ab663ea1eadecb23f | [
"Apache-2.0"
] | 26 | 2021-03-16T00:51:27.000Z | 2022-03-18T20:21:57.000Z | memory/structs/vector.h | ABCxFF/diepindepth | 498d68d4af6764632838bd9ab663ea1eadecb23f | [
"Apache-2.0"
] | 28 | 2021-03-16T11:15:06.000Z | 2022-03-08T13:16:25.000Z | memory/structs/vector.h | ABCxFF/diepindepth | 498d68d4af6764632838bd9ab663ea1eadecb23f | [
"Apache-2.0"
] | 24 | 2021-03-16T11:09:11.000Z | 2022-03-29T05:46:14.000Z | /*
Vectors store elements of data efficiently(?).
Vectors are 12 bytes of size
In Emscripten, Pointers are 32 bit.
*/
// Explains itself? Kind of a standard way of storing data, but this is its format in emscripten compiled binaries
struct vector {
void* start; // Points to the start of the elements contained - @00
void* end; // Denotes how much of the total space is used (end - start) - @04
void* end_capacity; // Denotes the absolute space that the vector has allocated (end_capacity - start) - @08
};
| 33.6875 | 114 | 0.695733 | [
"vector"
] |
c3a6ef114c47d22e343fa2f3073fb5fbcaf7a5cd | 30,934 | c | C | renderer/r_alias.c | AimHere/thirty-flights-of-linux | cd154b82e1e61535f01445ca46f38b36499a4ca4 | [
"Libpng",
"Zlib"
] | 3 | 2019-02-23T22:38:55.000Z | 2020-03-16T14:08:19.000Z | renderer/r_alias.c | AimHere/thirty-flights-of-linux | cd154b82e1e61535f01445ca46f38b36499a4ca4 | [
"Libpng",
"Zlib"
] | null | null | null | renderer/r_alias.c | AimHere/thirty-flights-of-linux | cd154b82e1e61535f01445ca46f38b36499a4ca4 | [
"Libpng",
"Zlib"
] | null | null | null | /*
Copyright (C) 1997-2001 Id Software, Inc.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
// r_alias.c: alias triangle model functions
#include "r_local.h"
#include "vlights.h"
#include "r_normals.h"
/*
=============================================================
ALIAS MODELS
=============================================================
*/
vec3_t tempVertexArray[MD3_MAX_MESHES][MD3_MAX_VERTS];
vec3_t aliasLightDir;
float aliasShadowAlpha;
/*
=================
R_LightAliasModel
=================
*/
void R_LightAliasModel (vec3_t baselight, vec3_t normal, vec3_t lightOut, byte normalindex, qboolean shaded) //byte oldnormalindex, float backlerp)
{
int i;
float l;
if (r_model_shading->value)
{
if (shaded)
{
if (r_model_shading->value == 3)
l = 2.0 * shadedots[normalindex] - 1;
else if (r_model_shading->value == 2)
l = 1.5 * shadedots[normalindex] - 0.5;
else
l = shadedots[normalindex];
VectorScale(baselight, l, lightOut);
}
else
VectorCopy(baselight, lightOut);
if (model_dlights_num)
for (i=0; i<model_dlights_num; i++)
{
l = 2.0 * VLight_GetLightValue (normal, model_dlights[i].direction,
currententity->angles[PITCH], currententity->angles[YAW], true);
VectorMA(lightOut, l, model_dlights[i].color, lightOut);
}
}
else
{
l = 2.0 * VLight_GetLightValue (normal, aliasLightDir, currententity->angles[PITCH],
currententity->angles[YAW], false);
VectorScale(baselight, l, lightOut);
}
for (i=0; i<3; i++)
lightOut[i] = max(min(lightOut[i], 1.0f), 0.0f);
}
/*
=================
R_DrawAliasFrameLerp
=================
*/
void R_DrawAliasFrameLerp (maliasmodel_t *paliashdr, entity_t *e)
{
int i, j, k, meshnum;
maliasframe_t *frame, *oldframe;
maliasmesh_t mesh;
maliasvertex_t *v, *ov;
vec3_t move, delta, vectors[3];
vec3_t curScale, oldScale, curNormal, oldNormal;
vec3_t tempNormalsArray[MD3_MAX_VERTS];
vec2_t tempSkinCoord;
vec3_t meshlight, lightcolor;
float alpha, meshalpha, thisalpha, shellscale, frontlerp, backlerp = e->backlerp;
image_t *skin;
renderparms_t skinParms;
qboolean shellModel = e->flags & ( RF_SHELL_RED | RF_SHELL_GREEN | RF_SHELL_BLUE | RF_SHELL_DOUBLE | RF_SHELL_HALF_DAM);
frontlerp = 1.0 - backlerp;
if (e->flags & RF_TRANSLUCENT)
alpha = e->alpha;
else
alpha = 1.0;
frame = paliashdr->frames + e->frame;
oldframe = paliashdr->frames + e->oldframe;
VectorScale(frame->scale, frontlerp, curScale);
VectorScale(oldframe->scale, backlerp, oldScale);
// move should be the delta back to the previous frame * backlerp
VectorSubtract (e->oldorigin, e->origin, delta);
AngleVectors (e->angles, vectors[0], vectors[1], vectors[2]);
move[0] = DotProduct (delta, vectors[0]); // forward
move[1] = -DotProduct (delta, vectors[1]); // left
move[2] = DotProduct (delta, vectors[2]); // up
VectorAdd (move, oldframe->translate, move);
for (i=0 ; i<3 ; i++)
move[i] = backlerp*move[i] + frontlerp*frame->translate[i];
R_SetVertexOverbrights(true);
R_SetShellBlend (true);
// new outer loop for whole model
for (k=0, meshnum=0; k < paliashdr->num_meshes; k++, meshnum++)
{
mesh = paliashdr->meshes[k];
skinParms = mesh.skins[e->skinnum].renderparms;
// select skin
if (e->skin)
skin = e->skin; // custom player skin
else
skin = currentmodel->skins[k][e->skinnum];
if (!skin)
skin = r_notexture;
if ( !shellModel )
GL_Bind(skin->texnum);
else if (FlowingShell())
alpha = 0.7;
// md3 skin scripting
if (skinParms.nodraw)
continue; // skip this mesh for this skin
if (skinParms.twosided)
GL_Disable(GL_CULL_FACE);
if (skinParms.alphatest && !shellModel)
GL_Enable(GL_ALPHA_TEST);
if (skinParms.fullbright)
VectorSet(meshlight, 1.0f, 1.0f, 1.0f);
else
VectorCopy(shadelight, meshlight);
meshalpha = alpha * skinParms.basealpha;
if (meshalpha < 1.0f || skinParms.blend)
GL_Enable (GL_BLEND);
else
GL_Disable (GL_BLEND);
if (skinParms.blend && !shellModel)
GL_BlendFunc (skinParms.blendfunc_src, skinParms.blendfunc_dst);
else
GL_BlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// md3 skin scripting
v = mesh.vertexes + e->frame*mesh.num_verts;
ov = mesh.vertexes + e->oldframe*mesh.num_verts;
rb_vertex = 0;
for (i=0; i<mesh.num_verts; i++, v++, ov++)
{
// lerp verts
curNormal[0] = r_sinTable[v->normal[0]] * r_cosTable[v->normal[1]];
curNormal[1] = r_sinTable[v->normal[0]] * r_sinTable[v->normal[1]];
curNormal[2] = r_cosTable[v->normal[0]];
oldNormal[0] = r_sinTable[ov->normal[0]] * r_cosTable[ov->normal[1]];
oldNormal[1] = r_sinTable[ov->normal[0]] * r_sinTable[ov->normal[1]];
oldNormal[2] = r_cosTable[ov->normal[0]];
VectorSet ( tempNormalsArray[i],
curNormal[0] + (oldNormal[0] - curNormal[0])*backlerp,
curNormal[1] + (oldNormal[1] - curNormal[1])*backlerp,
curNormal[2] + (oldNormal[2] - curNormal[2])*backlerp );
if (shellModel)
shellscale = (e->flags & RF_WEAPONMODEL) ? WEAPON_SHELL_SCALE: POWERSUIT_SCALE;
else
shellscale = 0.0;
VectorSet ( tempVertexArray[meshnum][i],
move[0] + ov->point[0]*oldScale[0] + v->point[0]*curScale[0] + tempNormalsArray[i][0]*shellscale,
move[1] + ov->point[1]*oldScale[1] + v->point[1]*curScale[1] + tempNormalsArray[i][1]*shellscale,
move[2] + ov->point[2]*oldScale[2] + v->point[2]*curScale[2] + tempNormalsArray[i][2]*shellscale );
// calc lighting and alpha
if (shellModel)
VectorCopy(meshlight, lightcolor);
else
R_LightAliasModel(meshlight, tempNormalsArray[i], lightcolor, v->lightnormalindex, !skinParms.nodiffuse);
//thisalpha = R_CalcEntAlpha(meshalpha, tempVertexArray[meshnum][i]);
thisalpha = meshalpha;
// get tex coords
if (shellModel && FlowingShell()) {
tempSkinCoord[0] = (tempVertexArray[meshnum][i][0] + tempVertexArray[meshnum][i][1]) / 40.0 + shellFlowH;
tempSkinCoord[1] = tempVertexArray[meshnum][i][2] / 40.0 + shellFlowV;
} else {
tempSkinCoord[0] = mesh.stcoords[i].st[0];
tempSkinCoord[1] = mesh.stcoords[i].st[1];
}
// add to arrays
VA_SetElem2(texCoordArray[0][rb_vertex], tempSkinCoord[0], tempSkinCoord[1]);
VA_SetElem3(vertexArray[rb_vertex], tempVertexArray[meshnum][i][0], tempVertexArray[meshnum][i][1], tempVertexArray[meshnum][i][2]);
VA_SetElem4(colorArray[rb_vertex], lightcolor[0], lightcolor[1], lightcolor[2], thisalpha);
rb_vertex++;
}
if (!shellModel)
RB_ModifyTextureCoords (&texCoordArray[0][0][0], &vertexArray[0][0], rb_vertex, skinParms);
// set indices for each triangle and draw
rb_index = 0;
for (j=0; j < mesh.num_tris; j++)
{
indexArray[rb_index++] = mesh.indexes[3*j+0];
indexArray[rb_index++] = mesh.indexes[3*j+1];
indexArray[rb_index++] = mesh.indexes[3*j+2];
}
RB_DrawArrays (GL_TRIANGLES);
// glow pass
if (mesh.skins[e->skinnum].glowimage && !shellModel)
{
float glowcolor;
if (skinParms.glow.type > -1)
glowcolor = RB_CalcGlowColor (skinParms);
else
glowcolor = 1.0;
qglDisableClientState (GL_COLOR_ARRAY);
qglColor4f(glowcolor, glowcolor, glowcolor, 1.0);
GL_Enable (GL_BLEND);
GL_BlendFunc (GL_ONE, GL_ONE);
GL_Bind(mesh.skins[e->skinnum].glowimage->texnum);
RB_DrawArrays (GL_TRIANGLES);
qglEnableClientState (GL_COLOR_ARRAY);
qglColor4f(1.0, 1.0, 1.0, 1.0);
}
// envmap pass
if (skinParms.envmap > 0.0f && !shellModel)
{
GL_Enable (GL_BLEND);
GL_BlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
qglTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
qglTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP);
// apply alpha to array
for (i=0; i<mesh.num_verts; i++)
//colorArray[i][3] = R_CalcEntAlpha(meshalpha*skinParms.envmap, tempVertexArray[meshnum][i]);
colorArray[i][3] = meshalpha*skinParms.envmap;
GL_Bind(r_envmappic->texnum);
qglEnable(GL_TEXTURE_GEN_S);
qglEnable(GL_TEXTURE_GEN_T);
RB_DrawArrays (GL_TRIANGLES);
qglDisable(GL_TEXTURE_GEN_S);
qglDisable(GL_TEXTURE_GEN_T);
}
RB_DrawMeshTris (GL_TRIANGLES, 1);
// md3 skin scripting
if (skinParms.twosided)
GL_Enable(GL_CULL_FACE);
if (skinParms.alphatest && !shellModel)
GL_Disable(GL_ALPHA_TEST);
GL_Disable (GL_BLEND);
// md3 skin scripting
} // end new outer loop
R_SetShellBlend (false);
R_SetVertexOverbrights(false);
}
int shadow_va, shadow_index;
/*
=============
R_BuildShadowVolume
based on code from BeefQuake R6
=============
*/
void R_BuildShadowVolume (maliasmodel_t *hdr, int meshnum, vec3_t light, float projectdistance, qboolean nocap)
{
int i, j, baseindex;
qboolean trianglefacinglight[MD3_MAX_TRIANGLES];
vec3_t v0, v1, v2, v3;
float thisAlpha;
maliasmesh_t mesh;
maliasvertex_t *verts;
mesh = hdr->meshes[meshnum];
if (mesh.skins[currententity->skinnum].renderparms.nodraw
|| mesh.skins[currententity->skinnum].renderparms.alphatest
|| mesh.skins[currententity->skinnum].renderparms.noshadow)
return;
verts = mesh.vertexes;
thisAlpha = aliasShadowAlpha; // was r_shadowalpha->value
for (i=0; i<mesh.num_tris; i++)
{
VectorCopy(tempVertexArray[meshnum][mesh.indexes[3*i+0]], v0);
VectorCopy(tempVertexArray[meshnum][mesh.indexes[3*i+1]], v1);
VectorCopy(tempVertexArray[meshnum][mesh.indexes[3*i+2]], v2);
trianglefacinglight[i] =
(light[0] - v0[0]) * ((v0[1] - v1[1]) * (v2[2] - v1[2]) - (v0[2] - v1[2]) * (v2[1] - v1[1]))
+ (light[1] - v0[1]) * ((v0[2] - v1[2]) * (v2[0] - v1[0]) - (v0[0] - v1[0]) * (v2[2] - v1[2]))
+ (light[2] - v0[2]) * ((v0[0] - v1[0]) * (v2[1] - v1[1]) - (v0[1] - v1[1]) * (v2[0] - v1[0])) > 0;
}
shadow_va = shadow_index = 0;
for (i=0; i<mesh.num_tris; i++)
{
if (!trianglefacinglight[i])
continue;
if (mesh.trneighbors[i*3+0] < 0 || !trianglefacinglight[mesh.trneighbors[i*3+0]])
{
baseindex = shadow_va;
for (j=0; j<3; j++)
{
v0[j]=tempVertexArray[meshnum][mesh.indexes[3*i+1]][j];
v1[j]=tempVertexArray[meshnum][mesh.indexes[3*i+0]][j];
v2[j]=v1[j]+((v1[j]-light[j]) * projectdistance);
v3[j]=v0[j]+((v0[j]-light[j]) * projectdistance);
}
VA_SetElem3(vertexArray[shadow_va], v0[0], v0[1], v0[2]);
VA_SetElem4(colorArray[shadow_va], 0, 0, 0, thisAlpha);
shadow_va++;
VA_SetElem3(vertexArray[shadow_va], v1[0], v1[1], v1[2]);
VA_SetElem4(colorArray[shadow_va], 0, 0, 0, thisAlpha);
shadow_va++;
VA_SetElem3(vertexArray[shadow_va], v2[0], v2[1], v2[2]);
VA_SetElem4(colorArray[shadow_va], 0, 0, 0, thisAlpha);
shadow_va++;
VA_SetElem3(vertexArray[shadow_va], v3[0], v3[1], v3[2]);
VA_SetElem4(colorArray[shadow_va], 0, 0, 0, thisAlpha);
shadow_va++;
indexArray[shadow_index++] = baseindex+0;
indexArray[shadow_index++] = baseindex+1;
indexArray[shadow_index++] = baseindex+2;
indexArray[shadow_index++] = baseindex+0;
indexArray[shadow_index++] = baseindex+2;
indexArray[shadow_index++] = baseindex+3;
}
if (mesh.trneighbors[i*3+1] < 0 || !trianglefacinglight[mesh.trneighbors[i*3+1]])
{
baseindex = shadow_va;
for (j=0; j<3; j++)
{
v0[j]=tempVertexArray[meshnum][mesh.indexes[3*i+2]][j];
v1[j]=tempVertexArray[meshnum][mesh.indexes[3*i+1]][j];
v2[j]=v1[j]+((v1[j]-light[j]) * projectdistance);
v3[j]=v0[j]+((v0[j]-light[j]) * projectdistance);
}
VA_SetElem3(vertexArray[shadow_va], v0[0], v0[1], v0[2]);
VA_SetElem4(colorArray[shadow_va], 0, 0, 0, thisAlpha);
shadow_va++;
VA_SetElem3(vertexArray[shadow_va], v1[0], v1[1], v1[2]);
VA_SetElem4(colorArray[shadow_va], 0, 0, 0, thisAlpha);
shadow_va++;
VA_SetElem3(vertexArray[shadow_va], v2[0], v2[1], v2[2]);
VA_SetElem4(colorArray[shadow_va], 0, 0, 0, thisAlpha);
shadow_va++;
VA_SetElem3(vertexArray[shadow_va], v3[0], v3[1], v3[2]);
VA_SetElem4(colorArray[shadow_va], 0, 0, 0, thisAlpha);
shadow_va++;
indexArray[shadow_index++] = baseindex+0;
indexArray[shadow_index++] = baseindex+1;
indexArray[shadow_index++] = baseindex+2;
indexArray[shadow_index++] = baseindex+0;
indexArray[shadow_index++] = baseindex+2;
indexArray[shadow_index++] = baseindex+3;
}
if (mesh.trneighbors[i*3+2] < 0 || !trianglefacinglight[mesh.trneighbors[i*3+2]])
{
baseindex = shadow_va;
for (j=0; j<3; j++)
{
v0[j]=tempVertexArray[meshnum][mesh.indexes[3*i+0]][j];
v1[j]=tempVertexArray[meshnum][mesh.indexes[3*i+2]][j];
v2[j]=v1[j]+((v1[j]-light[j]) * projectdistance);
v3[j]=v0[j]+((v0[j]-light[j]) * projectdistance);
}
VA_SetElem3(vertexArray[shadow_va], v0[0], v0[1], v0[2]);
VA_SetElem4(colorArray[shadow_va], 0, 0, 0, thisAlpha);
shadow_va++;
VA_SetElem3(vertexArray[shadow_va], v1[0], v1[1], v1[2]);
VA_SetElem4(colorArray[shadow_va], 0, 0, 0, thisAlpha);
shadow_va++;
VA_SetElem3(vertexArray[shadow_va], v2[0], v2[1], v2[2]);
VA_SetElem4(colorArray[shadow_va], 0, 0, 0, thisAlpha);
shadow_va++;
VA_SetElem3(vertexArray[shadow_va], v3[0], v3[1], v3[2]);
VA_SetElem4(colorArray[shadow_va], 0, 0, 0, thisAlpha);
shadow_va++;
indexArray[shadow_index++] = baseindex+0;
indexArray[shadow_index++] = baseindex+1;
indexArray[shadow_index++] = baseindex+2;
indexArray[shadow_index++] = baseindex+0;
indexArray[shadow_index++] = baseindex+2;
indexArray[shadow_index++] = baseindex+3;
}
}
if (nocap) return;
// cap the volume
for (i=0; i<mesh.num_tris; i++)
{
if (trianglefacinglight[i])
{
VectorCopy(tempVertexArray[meshnum][mesh.indexes[3*i+0]], v0);
VectorCopy(tempVertexArray[meshnum][mesh.indexes[3*i+1]], v1);
VectorCopy(tempVertexArray[meshnum][mesh.indexes[3*i+2]], v2);
VA_SetElem3(vertexArray[shadow_va], v0[0], v0[1], v0[2]);
VA_SetElem4(colorArray[shadow_va], 0, 0, 0, thisAlpha);
indexArray[shadow_index++] = shadow_va;
shadow_va++;
VA_SetElem3(vertexArray[shadow_va], v1[0], v1[1], v1[2]);
VA_SetElem4(colorArray[shadow_va], 0, 0, 0, thisAlpha);
indexArray[shadow_index++] = shadow_va;
shadow_va++;
VA_SetElem3(vertexArray[shadow_va], v2[0], v2[1], v2[2]);
VA_SetElem4(colorArray[shadow_va], 0, 0, 0, thisAlpha);
indexArray[shadow_index++] = shadow_va;
shadow_va++;
continue;
}
for (j=0; j<3; j++)
{
v0[j]=tempVertexArray[meshnum][mesh.indexes[3*i+0]][j];
v1[j]=tempVertexArray[meshnum][mesh.indexes[3*i+1]][j];
v2[j]=tempVertexArray[meshnum][mesh.indexes[3*i+2]][j];
v0[j]=v0[j]+((v0[j]-light[j]) * projectdistance);
v1[j]=v1[j]+((v1[j]-light[j]) * projectdistance);
v2[j]=v2[j]+((v2[j]-light[j]) * projectdistance);
}
VA_SetElem3(vertexArray[shadow_va], v0[0], v0[1], v0[2]);
VA_SetElem4(colorArray[shadow_va], 0, 0, 0, thisAlpha);
indexArray[shadow_index++] = shadow_va;
shadow_va++;
VA_SetElem3(vertexArray[shadow_va], v1[0], v1[1], v1[2]);
VA_SetElem4(colorArray[shadow_va], 0, 0, 0, thisAlpha);
indexArray[shadow_index++] = shadow_va;
shadow_va++;
VA_SetElem3(vertexArray[shadow_va], v2[0], v2[1], v2[2]);
VA_SetElem4(colorArray[shadow_va], 0, 0, 0, thisAlpha);
indexArray[shadow_index++] = shadow_va;
shadow_va++;
}
}
/*
=============
R_DrawShadowVolume
=============
*/
void R_DrawShadowVolume (void)
{
if (gl_config.drawRangeElements)
qglDrawRangeElementsEXT(GL_TRIANGLES, 0, shadow_va, shadow_index, GL_UNSIGNED_INT, indexArray);
else
qglDrawElements(GL_TRIANGLES, shadow_index, GL_UNSIGNED_INT, indexArray);
}
/*
=============
R_DrawAliasVolumeShadow
based on code from BeefQuake R6
=============
*/
void R_DrawAliasVolumeShadow (maliasmodel_t *paliashdr, vec3_t bbox[8])
{
vec3_t light, temp, vecAdd;
float dist, highest, lowest, projected_distance;
float angle, cosp, sinp, cosy, siny, cosr, sinr, ix, iy, iz;
int i, lnum;
dlight_t *dl;
dl = r_newrefdef.dlights;
VectorSet(vecAdd, 680,0,1024); // set base vector, was 576,0,1024
// compute average light vector from dlights
for (i=0, lnum=0; i<r_newrefdef.num_dlights; i++, dl++)
{
if (VectorCompare(dl->origin, currententity->origin))
continue;
VectorSubtract(dl->origin, currententity->origin, temp);
dist = dl->intensity - VectorLength(temp);
if (dist <= 0)
continue;
lnum++;
// Factor in the intensity of a dlight
VectorScale (temp, dist*0.25, temp);
VectorAdd (vecAdd, temp, vecAdd);
}
VectorNormalize(vecAdd);
VectorScale(vecAdd, 1024, vecAdd);
// get projection distance from lightspot height
highest = lowest = bbox[0][2];
for (i=0; i<8; i++) {
if (bbox[i][2] > highest) highest = bbox[i][2];
if (bbox[i][2] < lowest) lowest = bbox[i][2];
}
projected_distance = (fabs(highest - lightspot[2]) + (highest-lowest)) / vecAdd[2];
VectorCopy(vecAdd, light);
/*cosy = cos(-currententity->angles[YAW] / 180 * M_PI);
siny = sin(-currententity->angles[YAW] / 180 * M_PI);
ix = light[0], iy = light[1];
light[0] = (cosy * (ix - 0) + siny * (0 - iy) + 0);
light[1] = (cosy * (iy - 0) + siny * (ix - 0) + 0);
light[2] += 8;*/
// reverse-rotate light vector based on angles
angle = -currententity->angles[PITCH] / 180 * M_PI;
cosp = cos(angle), sinp = sin(angle);
angle = -currententity->angles[YAW] / 180 * M_PI;
cosy = cos(angle), siny = sin(angle);
angle = currententity->angles[ROLL] / 180 * M_PI; // roll is backwards
cosr = cos(angle), sinr = sin(angle);
// rotate for yaw (z axis)
ix = light[0], iy = light[1];
light[0] = cosy * ix - siny * iy + 0;
light[1] = siny * ix + cosy * iy + 0;
// rotate for pitch (y axis)
ix = light[0], iz = light[2];
light[0] = cosp * ix + 0 + sinp * iz;
light[2] = -sinp * ix + 0 + cosp * iz;
// rotate for roll (x axis)
iy = light[1], iz = light[2];
light[1] = 0 + cosr * iy - sinr * iz;
light[2] = 0 + sinr * iy + cosr * iz;
// set up stenciling
if (!r_shadowvolumes->value)
{
qglPushAttrib(GL_STENCIL_BUFFER_BIT); // save stencil buffer
qglClear(GL_STENCIL_BUFFER_BIT);
qglColorMask(0,0,0,0);
GL_DepthMask(0);
GL_DepthFunc(GL_LESS);
GL_Enable(GL_STENCIL_TEST);
qglStencilFunc(GL_ALWAYS, 0, 255);
// qglStencilOp (GL_KEEP, GL_KEEP, GL_KEEP);
// qglStencilMask (255);
}
// build shadow volumes and render each to stencil buffer
for (i=0; i<paliashdr->num_meshes; i++)
{
if (paliashdr->meshes[i].skins[currententity->skinnum].renderparms.nodraw
|| paliashdr->meshes[i].skins[currententity->skinnum].renderparms.alphatest
|| paliashdr->meshes[i].skins[currententity->skinnum].renderparms.noshadow)
continue;
R_BuildShadowVolume (paliashdr, i, light, projected_distance, r_shadowvolumes->value);
GL_LockArrays (shadow_va);
if (!r_shadowvolumes->value)
{
if (gl_config.atiSeparateStencil && gl_config.extStencilWrap) // Barnes ATI stenciling
{
GL_Disable(GL_CULL_FACE);
qglStencilOpSeparateATI (GL_BACK, GL_KEEP, GL_INCR_WRAP_EXT, GL_KEEP);
qglStencilOpSeparateATI (GL_FRONT, GL_KEEP, GL_DECR_WRAP_EXT, GL_KEEP);
R_DrawShadowVolume ();
GL_Enable(GL_CULL_FACE);
}
else if (gl_config.extStencilTwoSide && gl_config.extStencilWrap) // Echon's two-sided stenciling
{
GL_Disable(GL_CULL_FACE);
qglEnable (GL_STENCIL_TEST_TWO_SIDE_EXT);
qglActiveStencilFaceEXT (GL_BACK);
qglStencilOp (GL_KEEP, GL_INCR_WRAP_EXT, GL_KEEP);
qglActiveStencilFaceEXT (GL_FRONT);
qglStencilOp (GL_KEEP, GL_DECR_WRAP_EXT, GL_KEEP);
R_DrawShadowVolume ();
qglDisable (GL_STENCIL_TEST_TWO_SIDE_EXT);
GL_Enable(GL_CULL_FACE);
}
else
{ // increment stencil if backface is behind depthbuffer
GL_CullFace(GL_BACK); // quake is backwards, this culls front faces
qglStencilOp(GL_KEEP, GL_INCR, GL_KEEP);
R_DrawShadowVolume ();
// decrement stencil if frontface is behind depthbuffer
GL_CullFace(GL_FRONT); // quake is backwards, this culls back faces
qglStencilOp(GL_KEEP, GL_DECR, GL_KEEP);
R_DrawShadowVolume ();
}
}
else
R_DrawShadowVolume ();
GL_UnlockArrays ();
}
// end stenciling and draw stenciled volume
if (!r_shadowvolumes->value)
{
GL_CullFace(GL_FRONT);
GL_Disable(GL_STENCIL_TEST);
GL_DepthFunc(GL_LEQUAL);
GL_DepthMask(1);
qglColorMask(1,1,1,1);
// draw shadows for this model now
R_ShadowBlend (aliasShadowAlpha * currententity->alpha); // was r_shadowalpha->value
qglPopAttrib(); // restore stencil buffer
}
}
/*
=================
R_DrawAliasPlanarShadow
=================
*/
void R_DrawAliasPlanarShadow (maliasmodel_t *paliashdr)
{
maliasmesh_t mesh;
float height, lheight, thisAlpha;
vec3_t point, shadevector;
int i, j;
R_ShadowLight (currententity->origin, shadevector);
lheight = currententity->origin[2] - lightspot[2];
height = -lheight + 0.1f;
if (currententity->flags & RF_TRANSLUCENT)
thisAlpha = aliasShadowAlpha * currententity->alpha; // was r_shadowalpha->value
else
thisAlpha = aliasShadowAlpha; // was r_shadowalpha->value
// don't draw shadows above view origin, thnx to MrG
if (r_newrefdef.vieworg[2] < (currententity->origin[2] + height))
return;
GL_Stencil (true, false);
GL_BlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
rb_vertex = rb_index = 0;
for (i=0; i<paliashdr->num_meshes; i++)
{
mesh = paliashdr->meshes[i];
if (mesh.skins[currententity->skinnum].renderparms.nodraw
|| mesh.skins[currententity->skinnum].renderparms.alphatest
|| mesh.skins[currententity->skinnum].renderparms.noshadow)
continue;
for (j=0; j<mesh.num_verts; j++)
{
VectorCopy(tempVertexArray[i][j], point);
point[0] -= shadevector[0]*(point[2]+lheight);
point[1] -= shadevector[1]*(point[2]+lheight);
point[2] = height;
VA_SetElem3(vertexArray[rb_vertex], point[0], point[1], point[2]);
VA_SetElem4(colorArray[rb_vertex], 0, 0, 0, thisAlpha);
rb_vertex++;
}
for (j=0; j < mesh.num_tris; j++)
{
indexArray[rb_index++] = mesh.indexes[3*j+0];
indexArray[rb_index++] = mesh.indexes[3*j+1];
indexArray[rb_index++] = mesh.indexes[3*j+2];
}
}
RB_DrawArrays (GL_TRIANGLES);
GL_Stencil (false, false);
}
/*
=================
R_CullAliasModel
=================
*/
static qboolean R_CullAliasModel ( vec3_t bbox[8], entity_t *e )
{
int i, j;
vec3_t mins, maxs, tmp; //angles;
vec3_t vectors[3];
maliasmodel_t *paliashdr;
maliasframe_t *pframe, *poldframe;
int mask, aggregatemask = ~0;
paliashdr = (maliasmodel_t *)currentmodel->extradata;
if ( ( e->frame >= paliashdr->num_frames ) || ( e->frame < 0 ) )
{
VID_Printf (PRINT_ALL, "R_CullAliasModel %s: no such frame %d\n",
currentmodel->name, e->frame);
e->frame = 0;
}
if ( ( e->oldframe >= paliashdr->num_frames ) || ( e->oldframe < 0 ) )
{
VID_Printf (PRINT_ALL, "R_CullAliasModel %s: no such oldframe %d\n",
currentmodel->name, e->oldframe);
e->oldframe = 0;
}
pframe = paliashdr->frames + e->frame;
poldframe = paliashdr->frames + e->oldframe;
// compute axially aligned mins and maxs
if ( pframe == poldframe )
{
VectorCopy(pframe->mins, mins);
VectorCopy(pframe->maxs, maxs);
}
else
{
for ( i = 0; i < 3; i++ )
{
if (pframe->mins[i] < poldframe->mins[i])
mins[i] = pframe->mins[i];
else
mins[i] = poldframe->mins[i];
if (pframe->maxs[i] > poldframe->maxs[i])
maxs[i] = pframe->maxs[i];
else
maxs[i] = poldframe->maxs[i];
}
}
// jitspoe's bbox rotation fix
// compute and rotate bonding box
e->angles[ROLL] = -e->angles[ROLL]; // roll is backwards
AngleVectors(e->angles, vectors[0], vectors[1], vectors[2]);
e->angles[ROLL] = -e->angles[ROLL]; // roll is backwards
VectorSubtract(vec3_origin, vectors[1], vectors[1]); // AngleVectors returns "right" instead of "left"
for (i = 0; i < 8; i++)
{
tmp[0] = ((i & 1) ? mins[0] : maxs[0]);
tmp[1] = ((i & 2) ? mins[1] : maxs[1]);
tmp[2] = ((i & 4) ? mins[2] : maxs[2]);
bbox[i][0] = vectors[0][0] * tmp[0] + vectors[1][0] * tmp[1] + vectors[2][0] * tmp[2] + e->origin[0];
bbox[i][1] = vectors[0][1] * tmp[0] + vectors[1][1] * tmp[1] + vectors[2][1] * tmp[2] + e->origin[1];
bbox[i][2] = vectors[0][2] * tmp[0] + vectors[1][2] * tmp[1] + vectors[2][2] * tmp[2] + e->origin[2];
}
// cull
for (i=0; i<8; i++)
{
mask = 0;
for (j=0; j<4; j++)
{
float dp = DotProduct(frustum[j].normal, bbox[i]);
if ( ( dp - frustum[j].dist ) < 0 )
mask |= (1<<j);
}
aggregatemask &= mask;
}
if ( aggregatemask )
return true;
return false;
}
/*
=================
R_DrawAliasModel
=================
*/
void R_DrawAliasModel (entity_t *e)
{
maliasmodel_t *paliashdr;
vec3_t bbox[8];
qboolean mirrormodel = false;
int i;
// also skip this for viewermodels and cameramodels
if ( !(e->flags & RF_WEAPONMODEL || e->flags & RF_VIEWERMODEL || e->renderfx & RF2_CAMERAMODEL) )
{
if (R_CullAliasModel(bbox, e))
return;
}
// mirroring support
if (e->flags & RF_WEAPONMODEL)
{
if (r_lefthand->value == 2)
return;
else if (r_lefthand->value == 1)
mirrormodel = true;
}
else if (e->renderfx & RF2_CAMERAMODEL)
{
if (r_lefthand->value==1)
mirrormodel = true;
}
else if (e->flags & RF_MIRRORMODEL)
mirrormodel = true;
// end mirroring support
paliashdr = (maliasmodel_t *)currentmodel->extradata;
R_SetShadeLight ();
if (e->flags & RF_DEPTHHACK) // hack the depth range to prevent view model from poking into walls
{
if (r_newrefdef.rdflags & RDF_NOWORLDMODEL)
GL_DepthRange (gldepthmin, gldepthmin + 0.01*(gldepthmax-gldepthmin));
else
GL_DepthRange (gldepthmin, gldepthmin + 0.3*(gldepthmax-gldepthmin));
}
// mirroring support
if (mirrormodel)
R_FlipModel(true);
for (i=0; i < paliashdr->num_meshes; i++)
c_alias_polys += paliashdr->meshes[i].num_tris;
qglPushMatrix ();
e->angles[ROLL] = -e->angles[ROLL]; // roll is backwards
R_RotateForEntity (e, true);
e->angles[ROLL] = -e->angles[ROLL]; // roll is backwards
GL_ShadeModel (GL_SMOOTH);
GL_TexEnv(GL_MODULATE);
if ( (e->frame >= paliashdr->num_frames) || (e->frame < 0) )
{
VID_Printf (PRINT_ALL, "R_DrawAliasModel %s: no such frame %d\n", currentmodel->name, e->frame);
e->frame = 0;
e->oldframe = 0;
}
if ( (e->oldframe >= paliashdr->num_frames) || (e->oldframe < 0))
{
VID_Printf (PRINT_ALL, "R_DrawAliasModel %s: no such oldframe %d\n",
currentmodel->name, e->oldframe);
e->frame = 0;
e->oldframe = 0;
}
if (!r_lerpmodels->value)
e->backlerp = 0;
R_DrawAliasFrameLerp (paliashdr, e);
GL_TexEnv(GL_REPLACE);
GL_ShadeModel (GL_FLAT);
qglPopMatrix ();
// mirroring support
if (mirrormodel)
R_FlipModel(false);
// show model bounding box
R_DrawAliasModelBBox (bbox, e);
if (e->flags & RF_DEPTHHACK)
GL_DepthRange (gldepthmin, gldepthmax);
aliasShadowAlpha = R_CalcShadowAlpha(e);
if (!(e->flags & (RF_WEAPONMODEL | RF_NOSHADOW))
// no shadows from shells
&& !( (e->flags & (RF_SHELL_RED | RF_SHELL_GREEN | RF_SHELL_BLUE | RF_SHELL_DOUBLE | RF_SHELL_HALF_DAM)) && (e->flags & RF_TRANSLUCENT) )
&& r_shadows->value >= 1 && aliasShadowAlpha >= DIV255)
{
qglPushMatrix ();
GL_DisableTexture(0);
GL_Enable (GL_BLEND);
if (r_shadows->value == 3) {
e->angles[ROLL] = -e->angles[ROLL]; // roll is backwards
R_RotateForEntity (e, true);
e->angles[ROLL] = -e->angles[ROLL]; // roll is backwards
R_DrawAliasVolumeShadow (paliashdr, bbox);
}
else {
R_RotateForEntity (e, false);
R_DrawAliasPlanarShadow (paliashdr);
}
GL_Disable (GL_BLEND);
GL_EnableTexture(0);
qglPopMatrix ();
}
}
#if 0
/*
=================
R_DrawAliasModelShadow
Just draws the shadow for a model
=================
*/
void R_DrawAliasModelShadow (entity_t *e)
{
maliasmodel_t *paliashdr;
vec3_t bbox[8];
qboolean mirrormodel = false;
if (!r_shadows->value)
return;
if (e->flags & (RF_WEAPONMODEL | RF_NOSHADOW))
return;
// no shadows from shells
if ( (e->flags & (RF_SHELL_RED | RF_SHELL_GREEN | RF_SHELL_BLUE | RF_SHELL_DOUBLE | RF_SHELL_HALF_DAM))
&& (e->flags & RF_TRANSLUCENT) )
return;
// also skip this for viewermodels and cameramodels
if ( !(e->flags & RF_WEAPONMODEL || e->flags & RF_VIEWERMODEL || e->renderfx & RF2_CAMERAMODEL) )
{
if (R_CullAliasModel(bbox, e))
return;
}
aliasShadowAlpha = R_CalcShadowAlpha(e);
if (aliasShadowAlpha < DIV255) // out of range
return;
if (e->renderfx & RF2_CAMERAMODEL)
{
if (r_lefthand->value==1)
mirrormodel = true;
}
else if (e->flags & RF_MIRRORMODEL)
mirrormodel = true;
paliashdr = (maliasmodel_t *)currentmodel->extradata;
// mirroring support
// if (mirrormodel)
// R_FlipModel(true);
if ( (e->frame >= paliashdr->num_frames) || (e->frame < 0) )
{
e->frame = 0;
e->oldframe = 0;
}
if ( (e->oldframe >= paliashdr->num_frames) || (e->oldframe < 0))
{
e->frame = 0;
e->oldframe = 0;
}
//if ( !r_lerpmodels->value )
// e->backlerp = 0;
qglPushMatrix ();
GL_DisableTexture(0);
GL_Enable (GL_BLEND);
if (r_shadows->value == 3) {
e->angles[ROLL] = -e->angles[ROLL]; // roll is backwards
R_RotateForEntity (e, true);
e->angles[ROLL] = -e->angles[ROLL]; // roll is backwards
R_DrawAliasVolumeShadow (paliashdr, bbox);
}
else {
R_RotateForEntity (e, false);
R_DrawAliasPlanarShadow (paliashdr);
}
GL_Disable (GL_BLEND);
GL_EnableTexture(0);
qglPopMatrix ();
// mirroring support
// if (mirrormodel)
// R_FlipModel(false);
}
#endif
| 29.432921 | 148 | 0.639684 | [
"mesh",
"render",
"vector",
"model"
] |
c3ab5e044f0d9b187991f11b6dcd591759ba63cb | 4,835 | h | C | mac/pyobjc-core/Modules/objc/objc-class.h | albertz/music-player | d23586f5bf657cbaea8147223be7814d117ae73d | [
"BSD-2-Clause"
] | 132 | 2015-01-01T10:02:42.000Z | 2022-03-09T12:51:01.000Z | mac/pyobjc-core/Modules/objc/objc-class.h | mba811/music-player | 7998986b34cfda2244ef622adefb839331b81a81 | [
"BSD-2-Clause"
] | 6 | 2015-01-06T08:23:19.000Z | 2019-03-14T12:22:06.000Z | mac/pyobjc-core/Modules/objc/objc-class.h | mba811/music-player | 7998986b34cfda2244ef622adefb839331b81a81 | [
"BSD-2-Clause"
] | 27 | 2015-02-23T11:51:43.000Z | 2022-03-07T02:34:18.000Z | #ifndef PyObjC_OBJC_CLASS_H
#define PyObjC_OBJC_CLASS_H
/*!
* @header objc-class.m
* @abstract Definition of the wrapper for Objective-C classes
* @discussion
* This module implements the wrappers for Objective-C classes, included
* subclasses defined in Python.
*
* The class-wrapper maintains a full __dict__ to make it easier to
* support introspection, and to make it easier to detect if someone
* does a super() call of a method.
*
* Maintaining a full dict is problematic because the Objective-C runtime
* is fairly dynamic and does not have hooks to detect these changes. Our
* only way to detect changes is to periodicly check the runtime if
* something has changed. See the definition for PyObjCClassObject for
* an explanation.
*/
/*!
* @const PyObjCClass_Type
* @abstract The type objc.objc_class
*/
extern PyTypeObject PyObjCClass_Type;
/*!
* @function PyObjCClass_Check
* @abstract Check if an object is an Objective-C class
* @param obj An object
* @result Returns True if the object is an Objective-C class, false otherwise
*/
#define PyObjCClass_Check(obj) PyObject_TypeCheck(obj, &PyObjCClass_Type)
// The @const is not correct, but what else can we use here?
/*!
* @const PyObjC_ClassExtender
* @discussion
* PyObjC_ClassExtender is either NULL or a Python function that can
* update a class dictionary.
*
* The interface for the extender function is:
* extender(super_class, class_name, class_dict)
*
* The return value of the function is ignored, it should update the
* class_dict (which represents the __dict__ of an Objective-C class.
*/
extern PyObject* PyObjC_ClassExtender;
/*!
* @struct PyObjCClassObject
* @abstract The type struct for Objective-C classes (Python 2.3 and later)
* @field base Type actual type object
* @field sel_to_py Mapping to speed up finding the correct Python method
* for a selector.
* @field method_magic The most recent PyObjC_methodlist_magic() for the class
* @field dictoffset Offset in the Objective-C instance for the instance
* __dict__
* @field delmethod The method that implements __del__
* @field hasPythonImpl True if the class is implemented in Python
* @field generation The value of PyObjC_MappingCount at the last time
* the method-list was updated.
* @field useKVO should the class implement automatic KVO notifications?
* @field protectedMethods methods whose name starts with an underscore
*
* @discussion
* This struct is the type-object for on Objective-C class. It stores
* some additional information that is used to manage the interface
* with the Objective-C runtime.
*
* (method_magic, generation) is used to detect if the method wrappers
* should be regenerated: if method_magic is no longer equal to
* PyObjC_methodlist_magic() the Objective-C class changed, if generation
* is no longer equal to PyObjC_MappingCount there are new method-mappings
* and we should rescan just in case one of those mappings is needed for
* this class.
*
* dictoffset is used by objc-object.m to find the __dict__ for instances.
* If the offset is 0 there is no __dict__.
*
* We store the __del__ implementation here instead of in the type itself
* to ensure that our teardown code is correctly called.
*/
typedef struct _PyObjCClassObject {
PyHeapTypeObject base;
__strong Class class;
PyObject* sel_to_py;
int method_magic;
Py_ssize_t dictoffset;
PyObject* delmethod;
int hasPythonImpl;
int isCFWrapper;
int generation;
int useKVO;
PyObject* protectedMethods;
PyObject* hiddenSelectors;
PyObject* hiddenClassSelectors;
struct _PyObjCClassObject* meta_class; /* To be dropped */
} PyObjCClassObject;
extern PyObject* PyObjCClass_DefaultModule;
PyObject* PyObjCClass_New(Class objc_class);
Class PyObjCClass_GetClass(PyObject* object);
PyObject* PyObjCClass_FindSelector(PyObject* cls, SEL selector, BOOL class_method);
void PyObjCClass_MaybeRescan(PyObject* class);
int ObjC_RegisterClassProxy(Class cls, PyObject* classProxy);
void PyObjCClass_CheckMethodList(PyObject* cls, int recursive);
Py_ssize_t PyObjCClass_DictOffset(PyObject* cls);
PyObject* PyObjCClass_GetDelMethod(PyObject* cls);
void PyObjCClass_SetDelMethod(PyObject* cls, PyObject* newval);
int PyObjCClass_HasPythonImplementation(PyObject* cls);
PyObject* PyObjCClass_ClassForMetaClass(PyObject* meta);
PyObject* PyObjCClass_HiddenSelector(PyObject* tp, SEL sel, BOOL classMethod); /* returns borrowed */
int PyObjCClass_SetHidden(PyObject* tp, SEL sel, BOOL classMethod, PyObject* metadata);
int PyObjCClass_AddMethods(PyObject* cls, PyObject** methods, Py_ssize_t count);
PyObject* PyObjCClass_ListProperties(PyObject* cls);
#endif /* PyObjC_OBJC_CLASS_H */
| 39.631148 | 101 | 0.75636 | [
"object"
] |
0f09d1e3932ee6bda30c248a442d2e28a166367a | 15,405 | c | C | yametrica/src/cjson/cjson.c | indiesoftby/defold-yametrica | 9de909711253cfa05ba556cf35a565021b72ba44 | [
"MIT"
] | 7 | 2022-01-12T08:43:06.000Z | 2022-01-20T13:10:28.000Z | yametrica/src/cjson/cjson.c | indiesoftby/defold-yametrica | 9de909711253cfa05ba556cf35a565021b72ba44 | [
"MIT"
] | null | null | null | yametrica/src/cjson/cjson.c | indiesoftby/defold-yametrica | 9de909711253cfa05ba556cf35a565021b72ba44 | [
"MIT"
] | null | null | null | //
// Based on the fork by Melsoft Games: https://github.com/Melsoft-Games/defold-cjson
// Now it has only JSON encoding routines.
//
#ifdef _MSC_VER
//not #if defined(_WIN32) || defined(_WIN64) because we have strncasecmp in mingw
#define strncasecmp _strnicmp
#define strcasecmp _stricmp
#endif
#include <stdio.h>
#include <assert.h>
#include <string.h>
#include <math.h>
#include <limits.h>
#include <dmsdk/sdk.h>
#include "strbuf.h"
#include "fpconv.h"
/* Lua CJSON - JSON support for Lua
*
* Copyright (c) 2010-2012 Mark Pulford <mark@kyne.com.au>
*
* 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.
*/
/* Caveats:
* - JSON "null" values are represented as lightuserdata since Lua
* tables cannot contain "nil". Compare with cjson.null.
* - Invalid UTF-8 characters are not detected and will be passed
* untouched. If required, UTF-8 error checking should be done
* outside this library.
* - Javascript comments are not part of the JSON spec, and are not
* currently supported.
*
* Note: Decoding is slower than encoding. Lua spends significant
* time (30%) managing tables when parsing JSON since it is
* difficult to know object/array sizes ahead of time.
*/
#ifndef CJSON_MODNAME
#define CJSON_MODNAME "cjson"
#endif
#ifndef CJSON_VERSION
#define CJSON_VERSION "2.1.0"
#endif
#if !defined(isinf) && (defined(USE_INTERNAL_ISINF) || defined(MISSING_ISINF))
#define isinf(x) (!isnan(x) && isnan((x) - (x)))
#endif
#define DEFAULT_SPARSE_CONVERT 0
#define DEFAULT_SPARSE_RATIO 2
#define DEFAULT_SPARSE_SAFE 10
#define DEFAULT_ENCODE_MAX_DEPTH 1000
#define DEFAULT_DECODE_MAX_DEPTH 1000
#define DEFAULT_ENCODE_INVALID_NUMBERS 0
#define DEFAULT_DECODE_INVALID_NUMBERS 1
#define DEFAULT_ENCODE_KEEP_BUFFER 1
#define DEFAULT_ENCODE_NUMBER_PRECISION 14
#ifdef DISABLE_INVALID_NUMBERS
#undef DEFAULT_DECODE_INVALID_NUMBERS
#define DEFAULT_DECODE_INVALID_NUMBERS 0
#endif
typedef enum {
T_OBJ_BEGIN,
T_OBJ_END,
T_ARR_BEGIN,
T_ARR_END,
T_STRING,
T_NUMBER,
T_BOOLEAN,
T_NULL,
T_COLON,
T_COMMA,
T_END,
T_WHITESPACE,
T_ERROR,
T_UNKNOWN
} json_token_type_t;
static const char *json_token_type_name[] =
{
"T_OBJ_BEGIN",
"T_OBJ_END",
"T_ARR_BEGIN",
"T_ARR_END",
"T_STRING",
"T_NUMBER",
"T_BOOLEAN",
"T_NULL",
"T_COLON",
"T_COMMA",
"T_END",
"T_WHITESPACE",
"T_ERROR",
"T_UNKNOWN",
NULL
};
typedef struct {
json_token_type_t ch2token[256];
char escape2char[256];
strbuf_t encode_buf;
int encode_sparse_convert;
int encode_sparse_ratio;
int encode_sparse_safe;
int encode_max_depth;
int encode_invalid_numbers;
int encode_number_precision;
int encode_keep_buffer;
int decode_invalid_numbers;
int decode_max_depth;
} json_config_t;
typedef struct {
const char *data;
const char *ptr;
strbuf_t *tmp;
json_config_t *cfg;
int current_depth;
} json_parse_t;
typedef struct {
json_token_type_t type;
int index;
union {
const char *string;
double number;
int boolean;
} value;
int string_len;
} json_token_t;
static const char *char2escape[256] = {
"\\u0000", "\\u0001", "\\u0002", "\\u0003",
"\\u0004", "\\u0005", "\\u0006", "\\u0007",
"\\b", "\\t", "\\n", "\\u000b",
"\\f", "\\r", "\\u000e", "\\u000f",
"\\u0010", "\\u0011", "\\u0012", "\\u0013",
"\\u0014", "\\u0015", "\\u0016", "\\u0017",
"\\u0018", "\\u0019", "\\u001a", "\\u001b",
"\\u001c", "\\u001d", "\\u001e", "\\u001f",
NULL, NULL, "\\\"", NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, "\\/",
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, "\\\\", NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, "\\u007f",
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,
};
static json_config_t *cfg;
static int json_destroy_config()
{
if (cfg)
strbuf_free(&cfg->encode_buf);
cfg = NULL;
return 0;
}
static void json_create_config()
{
int i;
cfg = (json_config_t*)malloc(sizeof(*cfg));
cfg->encode_sparse_convert = DEFAULT_SPARSE_CONVERT;
cfg->encode_sparse_ratio = DEFAULT_SPARSE_RATIO;
cfg->encode_sparse_safe = DEFAULT_SPARSE_SAFE;
cfg->encode_max_depth = DEFAULT_ENCODE_MAX_DEPTH;
cfg->decode_max_depth = DEFAULT_DECODE_MAX_DEPTH;
cfg->encode_invalid_numbers = DEFAULT_ENCODE_INVALID_NUMBERS;
cfg->decode_invalid_numbers = DEFAULT_DECODE_INVALID_NUMBERS;
cfg->encode_keep_buffer = DEFAULT_ENCODE_KEEP_BUFFER;
cfg->encode_number_precision = DEFAULT_ENCODE_NUMBER_PRECISION;
#if DEFAULT_ENCODE_KEEP_BUFFER > 0
strbuf_init(&cfg->encode_buf, 0);
#endif
for (i = 0; i < 256; i++)
cfg->ch2token[i] = T_ERROR;
cfg->ch2token['{'] = T_OBJ_BEGIN;
cfg->ch2token['}'] = T_OBJ_END;
cfg->ch2token['['] = T_ARR_BEGIN;
cfg->ch2token[']'] = T_ARR_END;
cfg->ch2token[','] = T_COMMA;
cfg->ch2token[':'] = T_COLON;
cfg->ch2token['\0'] = T_END;
cfg->ch2token[' '] = T_WHITESPACE;
cfg->ch2token['\t'] = T_WHITESPACE;
cfg->ch2token['\n'] = T_WHITESPACE;
cfg->ch2token['\r'] = T_WHITESPACE;
cfg->ch2token['f'] = T_UNKNOWN;
cfg->ch2token['i'] = T_UNKNOWN;
cfg->ch2token['I'] = T_UNKNOWN;
cfg->ch2token['n'] = T_UNKNOWN;
cfg->ch2token['N'] = T_UNKNOWN;
cfg->ch2token['t'] = T_UNKNOWN;
cfg->ch2token['"'] = T_UNKNOWN;
cfg->ch2token['+'] = T_UNKNOWN;
cfg->ch2token['-'] = T_UNKNOWN;
for (i = 0; i < 10; i++)
cfg->ch2token['0' + i] = T_UNKNOWN;
for (i = 0; i < 256; i++)
cfg->escape2char[i] = 0;
cfg->escape2char['"'] = '"';
cfg->escape2char['\\'] = '\\';
cfg->escape2char['/'] = '/';
cfg->escape2char['b'] = '\b';
cfg->escape2char['t'] = '\t';
cfg->escape2char['n'] = '\n';
cfg->escape2char['f'] = '\f';
cfg->escape2char['r'] = '\r';
cfg->escape2char['u'] = 'u';
}
static void json_encode_exception(lua_State *l, json_config_t *cfg, strbuf_t *json, int lindex, const char *reason)
{
if (!cfg->encode_keep_buffer)
strbuf_free(json);
luaL_error(l, "Cannot serialise %s: %s", lua_typename(l, lua_type(l, lindex)), reason);
}
static void json_append_string(lua_State *l, strbuf_t *json, int lindex)
{
const char *escstr;
int i;
const char *str;
size_t len;
str = lua_tolstring(l, lindex, &len);
strbuf_ensure_empty_length(json, len * 6 + 2);
strbuf_append_char_unsafe(json, '\"');
for (i = 0; i < len; i++)
{
escstr = char2escape[(unsigned char)str[i]];
if (escstr)
strbuf_append_string(json, escstr);
else
strbuf_append_char_unsafe(json, str[i]);
}
strbuf_append_char_unsafe(json, '\"');
}
static int lua_array_length(lua_State *l, json_config_t *cfg, strbuf_t *json)
{
double k;
int max;
int items;
max = 0;
items = 0;
lua_pushnil(l);
while (lua_next(l, -2) != 0)
{
if (lua_type(l, -2) == LUA_TNUMBER && (k = lua_tonumber(l, -2)))
{
if (floor(k) == k && k >= 1)
{
if (k > max)
max = k;
items++;
lua_pop(l, 1);
continue;
}
}
lua_pop(l, 2);
return -1;
}
if (cfg->encode_sparse_ratio > 0 &&
max > items * cfg->encode_sparse_ratio &&
max > cfg->encode_sparse_safe)
{
if (!cfg->encode_sparse_convert)
json_encode_exception(l, cfg, json, -1, "excessively sparse array");
return -1;
}
return max;
}
static void json_check_encode_depth(lua_State *l, json_config_t *cfg, int current_depth, strbuf_t *json)
{
if (current_depth <= cfg->encode_max_depth && lua_checkstack(l, 3))
return;
if (!cfg->encode_keep_buffer)
strbuf_free(json);
luaL_error(l, "Cannot serialise, excessive nesting (%d)", current_depth);
}
static void json_append_data(lua_State *l, json_config_t *cfg, int current_depth, strbuf_t *json);
static void json_append_array(lua_State *l, json_config_t *cfg, int current_depth, strbuf_t *json, int array_length)
{
int comma, i;
strbuf_append_char(json, '[');
comma = 0;
for (i = 1; i <= array_length; i++)
{
if (comma)
strbuf_append_char(json, ',');
else
comma = 1;
lua_rawgeti(l, -1, i);
json_append_data(l, cfg, current_depth, json);
lua_pop(l, 1);
}
strbuf_append_char(json, ']');
}
static void json_append_number(lua_State *l, json_config_t *cfg, strbuf_t *json, int lindex)
{
double num = lua_tonumber(l, lindex);
int len;
if (cfg->encode_invalid_numbers == 0)
{
if (isinf(num) || isnan(num))
json_encode_exception(l, cfg, json, lindex, "must not be NaN or Inf");
} else if (cfg->encode_invalid_numbers == 1)
{
if (isnan(num))
{
strbuf_append_mem(json, "nan", 3);
return;
}
} else
{
if (isinf(num) || isnan(num))
{
strbuf_append_mem(json, "null", 4);
return;
}
}
strbuf_ensure_empty_length(json, FPCONV_G_FMT_BUFSIZE);
len = fpconv_g_fmt(strbuf_empty_ptr(json), num, cfg->encode_number_precision);
strbuf_extend_length(json, len);
}
static void json_append_object(lua_State *l, json_config_t *cfg, int current_depth, strbuf_t *json)
{
int comma, keytype;
strbuf_append_char(json, '{');
lua_pushnil(l);
comma = 0;
while (lua_next(l, -2) != 0)
{
if (comma)
strbuf_append_char(json, ',');
else
comma = 1;
keytype = lua_type(l, -2);
if (keytype == LUA_TNUMBER)
{
strbuf_append_char(json, '"');
json_append_number(l, cfg, json, -2);
strbuf_append_mem(json, "\":", 2);
} else if (keytype == LUA_TSTRING)
{
json_append_string(l, json, -2);
strbuf_append_char(json, ':');
} else
{
json_encode_exception(l, cfg, json, -2, "table key must be a number or string");
}
json_append_data(l, cfg, current_depth, json);
lua_pop(l, 1);
}
strbuf_append_char(json, '}');
}
static void json_append_data(lua_State *l, json_config_t *cfg, int current_depth, strbuf_t *json)
{
int len;
switch (lua_type(l, -1))
{
case LUA_TSTRING:
json_append_string(l, json, -1);
break;
case LUA_TNUMBER:
json_append_number(l, cfg, json, -1);
break;
case LUA_TBOOLEAN:
if (lua_toboolean(l, -1))
strbuf_append_mem(json, "true", 4);
else
strbuf_append_mem(json, "false", 5);
break;
case LUA_TTABLE:
current_depth++;
json_check_encode_depth(l, cfg, current_depth, json);
len = lua_array_length(l, cfg, json);
if (len > 0)
json_append_array(l, cfg, current_depth, json, len);
else
json_append_object(l, cfg, current_depth, json);
break;
case LUA_TNIL:
strbuf_append_mem(json, "null", 4);
break;
case LUA_TUSERDATA:
case LUA_TFUNCTION:
case LUA_TTHREAD:
{
unsigned long long pointer_addr = (unsigned long long)lua_topointer(l, -1);
const int buff_size = 16;
char str_buffer[buff_size];
int len = snprintf(str_buffer, buff_size, "%llx", pointer_addr);
strbuf_append_mem(json, "\"object at 0x", 13);
strbuf_append_mem(json, str_buffer, len);
strbuf_append_mem(json, "\"", 1);
break;
}
case LUA_TLIGHTUSERDATA:
if (lua_touserdata(l, -1) == NULL)
{
strbuf_append_mem(json, "null", 4);
break;
}
default:
/* Remaining types (LUA_TLIGHTUSERDATA) cannot be serialised */
json_encode_exception(l, cfg, json, -1, "type not supported");
/* never returns */
}
}
#ifdef __cplusplus
extern "C" {
#endif
//
// Initialize CJSON
//
void YaMetrica_CJSON_Init()
{
json_create_config();
}
//
// Finalize CJSON
//
void YaMetrica_CJSON_Final()
{
json_destroy_config();
}
//
// Encode to JSON the top of the Lua stack.
//
char *YaMetrica_CJSON_Encode(lua_State *L, int arg, int* out_len, bool copy)
{
lua_pushvalue(L, arg);
strbuf_t *encode_buf;
if (!cfg->encode_keep_buffer)
{
assert(0); // It's not supported mode.
} else
{
encode_buf = &cfg->encode_buf;
strbuf_reset(encode_buf);
}
json_append_data(L, cfg, 0, encode_buf);
lua_pop(L, 1);
char *str = strbuf_string(encode_buf, out_len);
if (!copy) {
return str;
}
char *str2 = (char *)malloc(*out_len);
memcpy(str2, str, *out_len);
return str2;
}
#ifdef __cplusplus
}
#endif
| 29.796905 | 116 | 0.610581 | [
"object"
] |
0f0ecbee5f63d6e1c7ae5613b38448d62e3f79b8 | 24,330 | c | C | industry/foc/fixed16/foc_align.c | normanr/incubator-nuttx-apps | b5128c401f5c65f44298f46c3887d6bb57bfb90b | [
"Apache-2.0"
] | 132 | 2019-12-17T23:45:42.000Z | 2022-03-30T11:58:30.000Z | industry/foc/fixed16/foc_align.c | normanr/incubator-nuttx-apps | b5128c401f5c65f44298f46c3887d6bb57bfb90b | [
"Apache-2.0"
] | 443 | 2020-01-01T03:06:24.000Z | 2022-03-31T08:57:35.000Z | industry/foc/fixed16/foc_align.c | normanr/incubator-nuttx-apps | b5128c401f5c65f44298f46c3887d6bb57bfb90b | [
"Apache-2.0"
] | 232 | 2019-12-21T10:18:12.000Z | 2022-03-30T07:42:13.000Z | /****************************************************************************
* apps/industry/foc/fixed16/foc_align.c
* This file implements angle sensor alignment routine for fixed16
*
* 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.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
#include "industry/foc/foc_common.h"
#include "industry/foc/foc_log.h"
#include "industry/foc/fixed16/foc_align.h"
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Align to -90deg = 270deg */
#define FOC_ALIGN_ANGLE (b16muli(b16HALFPI, 3))
/* Direction alignment */
#define ALIGN_DIR_ANGLE_STEP (ftob16(0.001f))
#define ALIGN_DIR_ANGLE_HOLD_0 (ftob16(0.0f))
#define ALIGN_DIR_ANGLE_HOLD_1 (b16divi(b16PI, 3))
#define ALIGN_DIR_ANGLE_HOLD_2 (b16muli(b16divi(b16PI, 3), 2))
#define ALIGN_DIR_ANGLE_HOLD_3 (b16PI)
#define ALIGN_DIR_ANGLE_HOLD_4 (b16muli(b16divi(b16PI, 3), 4))
#define ALIGN_DIR_HOLD_CNTR (10)
/* IDLE steps */
#define IDLE_STEPS (500)
/* Index alignment */
#define ALIGN_INDEX_ANGLE_SIGN (-b16muli(b16PI, 2))
#define ALIGN_INDEX_ANGLE_STEP (ftob16(0.001f))
#define ALIGN_INDEX_ANGLE_NOZERO (ftob16(0.1f))
/****************************************************************************
* Private Data Types
****************************************************************************/
/* Align stage */
enum foc_align_run_stage_e
{
FOC_ALIGN_RUN_INIT,
#ifdef CONFIG_INDUSTRY_FOC_ALIGN_INDEX
FOC_ALIGN_RUN_INDEX,
#endif
FOC_ALIGN_RUN_OFFSET,
FOC_ALIGN_RUN_DIR,
FOC_ALIGN_RUN_IDLE,
FOC_ALIGN_RUN_DONE
};
/* Align routine private data */
struct foc_align_b16_s
{
struct foc_routine_align_cfg_b16_s cfg;
struct foc_routine_aling_final_b16_s final;
int cntr;
int stage;
int dir_step;
#ifdef CONFIG_INDUSTRY_FOC_ALIGN_INDEX
int index_step;
b16_t index_angle;
#endif
b16_t dir_angle;
b16_t angle_last;
b16_t angle_now;
b16_t diff_cw;
b16_t diff_ccw;
};
/****************************************************************************
* Private Function Prototypes
****************************************************************************/
int foc_routine_align_init_b16(FAR foc_routine_b16_t *r);
void foc_routine_align_deinit_b16(FAR foc_routine_b16_t *r);
int foc_routine_align_cfg_b16(FAR foc_routine_b16_t *r, FAR void *cfg);
int foc_routine_align_run_b16(FAR foc_routine_b16_t *r,
FAR struct foc_routine_in_b16_s *in,
FAR struct foc_routine_out_b16_s *out);
int foc_routine_align_final_b16(FAR foc_routine_b16_t *r, FAR void *data);
/****************************************************************************
* Public Data
****************************************************************************/
struct foc_routine_ops_b16_s g_foc_routine_align_b16 =
{
.init = foc_routine_align_init_b16,
.deinit = foc_routine_align_deinit_b16,
.cfg = foc_routine_align_cfg_b16,
.run = foc_routine_align_run_b16,
.final = foc_routine_align_final_b16,
};
/****************************************************************************
* Private Functions
****************************************************************************/
#ifdef CONFIG_INDUSTRY_FOC_ALIGN_INDEX
/****************************************************************************
* Name: foc_align_index_run_b16
*
* Description:
* Run index alignment routine
*
* Input Parameter:
* align - pointer to FOC align routine
* in - pointer to FOC routine input data
* out - pointer to FOC routine output data
*
****************************************************************************/
static int foc_align_index_run_b16(FAR struct foc_align_b16_s *align,
FAR struct foc_routine_in_b16_s *in,
FAR struct foc_routine_out_b16_s *out)
{
static b16_t dir = DIR_CW_B16;
b16_t sign = 0;
int ret = FOC_ROUTINE_RUN_NOTDONE;
/* Get mechanical angles */
align->angle_last = align->angle_now;
align->angle_now = in->angle_m;
/* Normalize angle to <-M_PI, M_PI> range */
align->angle_now = align->angle_now - b16PI;
angle_norm_2pi_b16(&align->angle_now, -b16PI, b16PI);
/* The product of the previous angle with an angle now gives us
* information about the encoder overflow.
* This procedure assumes that the encoder index signal resets the
* encoder value to zero.
*/
sign = b16mulb16(align->angle_now, align->angle_last);
/* Move the motor shaft to approach index signal from both direction.
* After that, the encoder zero should be aligned with the encoder index.
*/
if (align->index_step == 0)
{
/* Move the motor shaft away from zero */
align->index_angle += b16mulb16(dir, ALIGN_INDEX_ANGLE_STEP);
if (align->angle_now < ALIGN_INDEX_ANGLE_NOZERO &&
align->angle_now > -ALIGN_INDEX_ANGLE_NOZERO)
{
align->index_step += 1;
}
}
else if (align->index_step == 1)
{
/* Move the motor shaft to zero in positive direction */
align->index_angle += b16mulb16(dir, ALIGN_INDEX_ANGLE_STEP);
if (sign < 0 && sign < ALIGN_INDEX_ANGLE_SIGN)
{
dir = b16mulb16(DIR_CCW_B16, dir);
align->index_step += 1;
}
}
else if (align->index_step == 2)
{
/* Move the motor shaft away from zero */
align->index_angle += b16mulb16(dir, ALIGN_INDEX_ANGLE_STEP);
if (align->angle_now < ALIGN_INDEX_ANGLE_NOZERO &&
align->angle_now > -ALIGN_INDEX_ANGLE_NOZERO)
{
align->index_step += 1;
}
}
else if (align->index_step == 3)
{
/* Move the motor shaft to zero in negative direction */
align->index_angle += b16mulb16(dir, ALIGN_INDEX_ANGLE_STEP);
if (sign < 0 && sign < ALIGN_INDEX_ANGLE_SIGN)
{
dir = b16mulb16(DIR_CCW_B16, dir);
align->index_step += 1;
}
}
else if (align->index_step == 4)
{
/* Done */
ret = FOC_ROUTINE_RUN_DONE;
}
/* Get output */
if (ret == FOC_ROUTINE_RUN_DONE)
{
/* Force IDLE mode */
out->dq_ref.q = 0;
out->dq_ref.d = 0;
out->vdq_comp.q = 0;
out->vdq_comp.d = 0;
out->angle = 0;
out->foc_mode = FOC_HANDLER_MODE_IDLE;
/* Reset data */
align->angle_last = 0;
align->angle_now = 0;
align->cntr = 0;
}
else
{
/* Force DQ voltage vector */
out->dq_ref.q = align->cfg.volt;
out->dq_ref.d = 0;
out->vdq_comp.q = 0;
out->vdq_comp.d = 0;
out->angle = align->index_angle;
out->foc_mode = FOC_HANDLER_MODE_VOLTAGE;
/* Increase counter */
align->cntr += 1;
}
return ret;
}
#endif
/****************************************************************************
* Name: foc_align_offset_run_b16
*
* Description:
* Run offset alignment routine
*
* Input Parameter:
* align - pointer to FOC align routine
* in - pointer to FOC routine input data
* out - pointer to FOC routine output data
*
****************************************************************************/
static int foc_align_offset_run_b16(FAR struct foc_align_b16_s *align,
FAR struct foc_routine_in_b16_s *in,
FAR struct foc_routine_out_b16_s *out)
{
int ret = FOC_ROUTINE_RUN_NOTDONE;
/* Reset Align angle sensor */
if (align->cntr > align->cfg.offset_steps)
{
/* Align angle sensor */
if (align->cfg.cb.zero != NULL)
{
ret = align->cfg.cb.zero(align->cfg.cb.priv, in->angle);
if (ret < 0)
{
FOCLIBERR("ERROR: align offset callback failed %d!\n", ret);
goto errout;
}
}
/* Offset align done */
align->cntr = 0;
ret = FOC_ROUTINE_RUN_DONE;
/* Force IDLE mode */
out->dq_ref.q = 0;
out->dq_ref.d = 0;
out->vdq_comp.q = 0;
out->vdq_comp.d = 0;
out->angle = 0;
out->foc_mode = FOC_HANDLER_MODE_IDLE;
}
else
{
/* Force DQ voltage vector */
out->dq_ref.q = align->cfg.volt;
out->dq_ref.d = 0;
out->vdq_comp.q = 0;
out->vdq_comp.d = 0;
out->angle = FOC_ALIGN_ANGLE;
out->foc_mode = FOC_HANDLER_MODE_VOLTAGE;
/* Increase counter */
align->cntr += 1;
}
/* Store offset if done */
if (ret == FOC_ROUTINE_RUN_DONE)
{
align->final.offset = in->angle;
}
errout:
return ret;
}
/****************************************************************************
* Name: foc_align_dir_move_b16
****************************************************************************/
static void foc_align_dir_move_b16(FAR struct foc_align_b16_s *align,
b16_t dir, b16_t dest)
{
bool next = false;
DEBUGASSERT(align);
/* Update angle */
align->dir_angle += b16mulb16(dir, ALIGN_DIR_ANGLE_STEP);
/* Check destination */
if (dir == DIR_CW_B16)
{
if (align->dir_angle >= dest)
{
next = true;
}
}
else if (dir == DIR_CCW_B16)
{
if (align->dir_angle <= dest)
{
next = true;
}
}
else
{
DEBUGASSERT(0);
}
/* Next step */
if (next == true)
{
align->dir_step += 1;
}
}
/****************************************************************************
* Name: foc_align_dir_hold_b16
****************************************************************************/
static void foc_align_dir_hold_b16(FAR struct foc_align_b16_s *align,
b16_t dir, bool last, bool diff)
{
DEBUGASSERT(align);
/* Lock angle */
align->dir_angle = align->dir_angle;
/* Increase counter */
align->cntr += 1;
if (align->cntr > ALIGN_DIR_HOLD_CNTR)
{
/* Next step */
align->dir_step += 1;
/* Accumulate diff */
if (diff == true)
{
if (dir == DIR_CW_B16)
{
align->diff_cw += (align->angle_now - align->angle_last);
}
else if (dir == DIR_CCW_B16)
{
align->diff_ccw += (align->angle_now - align->angle_last);
}
else
{
DEBUGASSERT(0);
}
}
/* Store last angle */
if (last == true)
{
align->angle_last = align->angle_now;
}
/* Reset counter */
align->cntr = 0;
}
}
/****************************************************************************
* Name: foc_align_dir_run_b16
*
* Description:
* Run direction alignment routine
*
* Input Parameter:
* align - pointer to FOC align routine
* in - pointer to FOC routine input data
* out - pointer to FOC routine output data
*
****************************************************************************/
int foc_align_dir_run_b16(FAR struct foc_align_b16_s *align,
FAR struct foc_routine_in_b16_s *in,
FAR struct foc_routine_out_b16_s *out)
{
int ret = FOC_ROUTINE_RUN_NOTDONE;
bool last = false;
/* Store angle now */
align->angle_now = in->angle;
/* Handle dir align */
if (align->dir_step == 0)
{
/* Start with position 0 */
align->dir_angle = ALIGN_DIR_ANGLE_HOLD_0;
/* Step 0 - hold position 0 */
foc_align_dir_hold_b16(align, DIR_CW_B16, true, true);
}
else if (align->dir_step == 1)
{
/* Step 1 - move motor in CW direction to position 1 */
foc_align_dir_move_b16(align, DIR_CW_B16, ALIGN_DIR_ANGLE_HOLD_1);
}
else if (align->dir_step == 2)
{
/* Step 2 - hold position 1 */
foc_align_dir_hold_b16(align, DIR_CW_B16, true, false);
}
else if (align->dir_step == 3)
{
/* Step 3 - move motor in CW direction to position 2 */
foc_align_dir_move_b16(align, DIR_CW_B16, ALIGN_DIR_ANGLE_HOLD_2);
}
else if (align->dir_step == 4)
{
/* Step 4 - hold position 2 */
foc_align_dir_hold_b16(align, DIR_CW_B16, true, true);
}
else if (align->dir_step == 5)
{
/* Step 5 - move motor in CW direction to position 3 */
foc_align_dir_move_b16(align, DIR_CW_B16, ALIGN_DIR_ANGLE_HOLD_3);
}
else if (align->dir_step == 6)
{
/* Step 6 - hold position 3 */
foc_align_dir_hold_b16(align, DIR_CW_B16, true, true);
}
else if (align->dir_step == 6)
{
/* Step 6 - move motor in CW direction to position 4 */
foc_align_dir_move_b16(align, DIR_CW_B16, ALIGN_DIR_ANGLE_HOLD_4);
}
else if (align->dir_step == 7)
{
/* Step 7 - hold position 4 */
foc_align_dir_hold_b16(align, DIR_CW_B16, true, true);
}
else if (align->dir_step == 8)
{
/* Step 8 - move motor in CCW direction to position 3 */
foc_align_dir_move_b16(align, DIR_CCW_B16, ALIGN_DIR_ANGLE_HOLD_3);
}
else if (align->dir_step == 9)
{
/* Step 9 - hold position 3 */
foc_align_dir_hold_b16(align, DIR_CCW_B16, true, true);
}
else if (align->dir_step == 10)
{
/* Step 10 - move motor in CCW direction to position 2 */
foc_align_dir_move_b16(align, DIR_CCW_B16, ALIGN_DIR_ANGLE_HOLD_2);
}
else if (align->dir_step == 11)
{
/* Step 11 - hold position 2 */
foc_align_dir_hold_b16(align, DIR_CCW_B16, true, true);
}
else if (align->dir_step == 12)
{
/* Step 12 - move motor in CCW direction to position 1 */
foc_align_dir_move_b16(align, DIR_CCW_B16, ALIGN_DIR_ANGLE_HOLD_1);
}
else if (align->dir_step == 13)
{
/* Step 13 - hold position 1 */
foc_align_dir_hold_b16(align, DIR_CCW_B16, true, true);
}
else if (align->dir_step == 14)
{
/* Step 14 - move motor in CCW direction to position 0 */
foc_align_dir_move_b16(align, DIR_CCW_B16, ALIGN_DIR_ANGLE_HOLD_0);
}
else if (align->dir_step == 15)
{
/* Step 15 - hold position 0 */
foc_align_dir_hold_b16(align, DIR_CCW_B16, true, true);
}
else
{
/* Set flag */
last = true;
/* Get sensor direction according to sampled data */
if (align->diff_cw > 0 && align->diff_ccw < 0)
{
align->final.dir = DIR_CW_B16;
}
else if (align->diff_cw < 0 && align->diff_ccw > 0)
{
align->final.dir = DIR_CCW_B16;
}
else
{
/* Invalid data */
FOCLIBERR("ERROR: direction align failed !\n");
align->final.dir = DIR_NONE_B16;
ret = -EINVAL;
goto errout;
}
/* Align angle sensor */
if (align->cfg.cb.dir != NULL)
{
ret = align->cfg.cb.dir(align->cfg.cb.priv, align->final.dir);
if (ret < 0)
{
FOCLIBERR("ERROR: align dir callback failed %d!\n", ret);
goto errout;
}
}
/* Direction alignment done */
ret = FOC_ROUTINE_RUN_DONE;
}
/* Force DQ voltage vector */
out->dq_ref.q = align->cfg.volt;
out->dq_ref.d = 0;
out->vdq_comp.q = 0;
out->vdq_comp.d = 0;
out->angle = align->dir_angle;
out->foc_mode = FOC_HANDLER_MODE_VOLTAGE;
errout:
/* Force current to zero if alignment done */
if (last == true)
{
out->dq_ref.q = 0;
out->dq_ref.d = 0;
}
return ret;
}
/****************************************************************************
* Name: foc_align_idle_run_b16
*
* Description:
* Force IDLE state
*
* Input Parameter:
* align - pointer to FOC align routine
* in - pointer to FOC routine input data
* out - pointer to FOC routine output data
*
****************************************************************************/
static int foc_align_idle_run_b16(FAR struct foc_align_b16_s *align,
FAR struct foc_routine_in_b16_s *in,
FAR struct foc_routine_out_b16_s *out)
{
int ret = FOC_ROUTINE_RUN_NOTDONE;
/* Get output */
out->dq_ref.q = 0;
out->dq_ref.d = 0;
out->vdq_comp.q = 0;
out->vdq_comp.d = 0;
out->angle = 0;
out->foc_mode = FOC_HANDLER_MODE_IDLE;
/* Increase counter */
align->cntr += 1;
if (align->cntr > IDLE_STEPS)
{
/* Done */
ret = FOC_ROUTINE_RUN_DONE;
/* Reset counter */
align->cntr = 0;
}
return ret;
}
/****************************************************************************
* Name: foc_routine_align_init_b16
*
* Description:
* Initialize the FOC align routine (fixed16)
*
* Input Parameter:
* r - pointer to FOC routine
*
****************************************************************************/
int foc_routine_align_init_b16(FAR foc_routine_b16_t *r)
{
int ret = OK;
DEBUGASSERT(r);
/* Connect angle data */
r->data = zalloc(sizeof(struct foc_align_b16_s));
if (r->data == NULL)
{
ret = -ENOMEM;
goto errout;
}
errout:
return ret;
}
/****************************************************************************
* Name: foc_routine_align_deinit_b16
*
* Description:
* Deinitialize the FOC align routine (fixed16)
*
* Input Parameter:
* r - pointer to FOC routine
*
****************************************************************************/
void foc_routine_align_deinit_b16(FAR foc_routine_b16_t *r)
{
DEBUGASSERT(r);
if (r->data)
{
/* Free routine data */
free(r->data);
}
}
/****************************************************************************
* Name: foc_routine_align_cfg_b16
*
* Description:
* Configure the FOC align routine (fixed16)
*
* Input Parameter:
* r - pointer to FOC routine
* cfg - pointer to align routine configuration data
*
****************************************************************************/
int foc_routine_align_cfg_b16(FAR foc_routine_b16_t *r, FAR void *cfg)
{
FAR struct foc_align_b16_s *a = NULL;
int ret = OK;
DEBUGASSERT(r);
DEBUGASSERT(cfg);
/* Get aling data */
DEBUGASSERT(r->data);
a = r->data;
/* Copy configuration */
memcpy(&a->cfg, cfg, sizeof(struct foc_routine_align_cfg_b16_s));
/* Verify configuration */
if (a->cfg.volt <= 0)
{
ret = -EINVAL;
goto errout;
}
if (a->cfg.offset_steps <= 0)
{
ret = -EINVAL;
goto errout;
}
if (a->cfg.cb.zero == NULL || a->cfg.cb.dir == NULL ||
a->cfg.cb.priv == NULL)
{
FOCLIBWARN("WARN: no align cb data!\n");
}
errout:
return ret;
}
/****************************************************************************
* Name: foc_routine_align_run_b16
*
* Description:
* Run the FOC align routine step (fixed16)
*
* Input Parameter:
* r - pointer to FOC routine
* in - pointer to FOC routine input data
* out - pointer to FOC routine output data
*
****************************************************************************/
int foc_routine_align_run_b16(FAR foc_routine_b16_t *r,
FAR struct foc_routine_in_b16_s *in,
FAR struct foc_routine_out_b16_s *out)
{
FAR struct foc_align_b16_s *a = NULL;
int ret = FOC_ROUTINE_RUN_NOTDONE;
DEBUGASSERT(r);
DEBUGASSERT(in);
DEBUGASSERT(out);
/* Get aling data */
DEBUGASSERT(r->data);
a = r->data;
/* Force IDLE state at default */
out->dq_ref.q = 0;
out->dq_ref.d = 0;
out->vdq_comp.q = 0;
out->vdq_comp.d = 0;
out->angle = 0;
out->foc_mode = FOC_HANDLER_MODE_IDLE;
/* Handle alignment stage */
switch (a->stage)
{
case FOC_ALIGN_RUN_INIT:
{
a->stage += 1;
ret = FOC_ROUTINE_RUN_NOTDONE;
break;
}
#ifdef CONFIG_INDUSTRY_FOC_ALIGN_INDEX
case FOC_ALIGN_RUN_INDEX:
{
/* Align zero procedure */
ret = foc_align_index_run_b16(a, in, out);
if (ret < 0)
{
goto errout;
}
if (ret == FOC_ROUTINE_RUN_DONE)
{
FOCLIBLOG("ALIGN INDEX done!\n");
a->stage += 1;
ret = FOC_ROUTINE_RUN_NOTDONE;
}
break;
}
#endif
case FOC_ALIGN_RUN_OFFSET:
{
/* Align zero procedure */
ret = foc_align_offset_run_b16(a, in, out);
if (ret < 0)
{
goto errout;
}
if (ret == FOC_ROUTINE_RUN_DONE)
{
FOCLIBLOG("ALIGN OFFSET done!\n");
a->stage += 1;
ret = FOC_ROUTINE_RUN_NOTDONE;
}
break;
}
case FOC_ALIGN_RUN_DIR:
{
/* Align direction procedure */
ret = foc_align_dir_run_b16(a, in, out);
if (ret < 0)
{
goto errout;
}
if (ret == FOC_ROUTINE_RUN_DONE)
{
FOCLIBLOG("ALIGN DIR done!\n");
a->stage += 1;
ret = FOC_ROUTINE_RUN_NOTDONE;
}
break;
}
case FOC_ALIGN_RUN_IDLE:
{
/* De-energetize motor */
ret = foc_align_idle_run_b16(a, in, out);
if (ret < 0)
{
goto errout;
}
if (ret == FOC_ROUTINE_RUN_DONE)
{
FOCLIBLOG("ALIGN IDLE done!\n");
a->stage += 1;
ret = FOC_ROUTINE_RUN_NOTDONE;
}
break;
}
case FOC_ALIGN_RUN_DONE:
{
ret = FOC_ROUTINE_RUN_DONE;
break;
}
default:
{
FOCLIBERR("ERROR: invalid alignment stage %d\n", a->stage);
ret = -EINVAL;
goto errout;
}
}
errout:
return ret;
}
/****************************************************************************
* Name: foc_routine_align_final_b16
*
* Description:
* Finalize the FOC routine data (fixed16)
*
* Input Parameter:
* r - pointer to FOC routine
* data - pointer to FOC align routine final data
*
****************************************************************************/
int foc_routine_align_final_b16(FAR foc_routine_b16_t *r, FAR void *data)
{
FAR struct foc_align_b16_s *a = NULL;
DEBUGASSERT(r);
DEBUGASSERT(data);
/* Get aling data */
DEBUGASSERT(r->data);
a = r->data;
/* Get final data */
memcpy(data, &a->final, sizeof(struct foc_routine_aling_final_b16_s));
return OK;
}
| 24.233068 | 78 | 0.511714 | [
"vector"
] |
0f168bfb715d9a5b62a1b65ad8ab49a0c7a24fba | 2,849 | c | C | Codes/aiv2008/leetcode337-house-robber-3/house-robber-3.c | aiv2008/algorithm | ecee5b76af52d9ad55b7fb9cf706be25c76772c1 | [
"Apache-2.0"
] | null | null | null | Codes/aiv2008/leetcode337-house-robber-3/house-robber-3.c | aiv2008/algorithm | ecee5b76af52d9ad55b7fb9cf706be25c76772c1 | [
"Apache-2.0"
] | null | null | null | Codes/aiv2008/leetcode337-house-robber-3/house-robber-3.c | aiv2008/algorithm | ecee5b76af52d9ad55b7fb9cf706be25c76772c1 | [
"Apache-2.0"
] | null | null | null | #include<stdio.h>
#include<stdlib.h>
#include "../common/vector.h"
#include "../common/tree.h"
/**
typedef struct {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
**/
typedef struct{
char* val;
struct StackNode* next;
} StackNode;
typedef struct{
struct StackNode* top;
struct StackNode* bottom;
} Stack;
int max(int a, int b){
return a > b ? a : b;
}
int *postTrasval(TreeNode* node) {
int *dp = (int*)calloc(2, sizeof(int));
*dp = 0;
*(dp+1) = 0;
if(node == NULL) return dp;
if(node->left == NULL && node->right == NULL) {
*dp = 0;
*(dp+1) = node->val < 0 ? 0 : node->val;
return dp;
}
int* left = (int*)calloc(2, sizeof(int));
int* right = (int*)calloc(2, sizeof(int));
memcpy(left, dp, 2*sizeof(int));
memcpy(right, dp, 2*sizeof(int));
left = postTrasval(node->left);
right = postTrasval(node->right);
*dp = max(*left + *right, *(left+1) + *(right+1));
*(dp+1) = max(*left + *right + node->val, *(left+1) + *(right+1));
return dp;
}
int rob(struct TreeNode* root){
int *result = postTrasval(root);
return max(*result, *(result+1));
}
int main(void){
int a[] = {3,4,5,1,3,-1,1};
int size = sizeof(a) / sizeof(a[0]);
int i=0;
int j=0;
Vector* vector = NULL;
TreeNode* root = initTreeNode(a[0]);
TreeNode* thisNode = root;
vectorAdd(&vector, thisNode);
for(i=1;i<size;i++){
TreeNode* node = initTreeNode(a[i]);
vectorAdd(&vector, node);
thisNode = (TreeNode*)vectorGet(vector, j);
if(thisNode == NULL) break;
if(thisNode->left == NULL) {
thisNode->left = node;
} else{
thisNode->right = node;
thisNode = vectorGet(vector, ++j);
}
}
size = vectorSize(vector);
for(i=0;i<size;i++){
TreeNode* node = (TreeNode*)vectorGet(vector, i);
printf("root=%d, left=%d, right=%d\n", node->val, node->left == NULL ? -1 : ((TreeNode*)(node->left))->val, node->right == NULL ? -1 : ((TreeNode*)(node->right))->val);
}
printf("result is %d", rob(root));
return 0;
}
/**
void stackPush(Stack** stack, char* val) {
if(stack == NULL) return;
StackNode* node = (StackNode*)malloc(sizeof(StackNode));
node->val = val;
if(*stack == NULL) {
*stack = (Stack*)malloc(sizeof(Stack));
(*stack)->top = node;
(*stack)->bottom = node;
} else {
((StackNode*)((*stack)->bottom))->next = node;
(*stack)->bottom = node;
}
}
StackNode* stackTop(Stack* stack){
return stack == NULL ? NULL : stack->top;
}
StackNode* stackBottom(Stack* stack) {
return stack == NULL ? NULL : stack->bottom;
}
void stackPop(Stack* stack) {
if(stack == NULL) return;
StackNode* top = stackTop(stack);
StackNode* bottom = stackBottom(stack);
if(top == bottom) {
free(top);
stack->top = NULL;
//free(bottom);
stack->bottom = NULL;
} else {
StackNode* tmpNode = top;
stack->top = top->next;
tmpNode->next = NULL;
free(tmpNode);
tmpNode = NULL;
}
}
**/
| 21.748092 | 170 | 0.610741 | [
"vector"
] |
0f2a19b7f93968095d5b80619257d543f22d6fff | 2,825 | h | C | src/game/client/hltvcamera.h | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 6 | 2022-01-23T09:40:33.000Z | 2022-03-20T20:53:25.000Z | src/game/client/hltvcamera.h | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | null | null | null | src/game/client/hltvcamera.h | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 1 | 2022-02-06T21:05:23.000Z | 2022-02-06T21:05:23.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//=============================================================================//
#ifndef HLTVCAMERA_H
#define HLTVCAMERA_H
#ifdef _WIN32
#pragma once
#endif
#include "GameEventListener.h"
class C_HLTVCamera : CGameEventListener {
public:
C_HLTVCamera();
virtual ~C_HLTVCamera();
void Init();
void Reset();
void CalcView(Vector &origin, QAngle &angles, float &fov);
void FireGameEvent(IGameEvent *event);
void SetMode(int iMode);
void SetChaseCamParams(float flOffset, float flDistance, float flTheta, float flPhi);
void SpecNextPlayer(bool bInverse);
// See UTIL_PlayerByCommandArg for what all might go in here.
void SpecPlayerByPredicate(const char *szPlayerSearch);
void ToggleChaseAsFirstPerson();
bool IsPVSLocked();
void SetAutoDirector(bool bActive);
int GetMode(); // returns current camera mode
C_BaseEntity *GetPrimaryTarget(); // return primary target
void SetPrimaryTarget(int nEntity); // set the primary obs target
C_BaseEntity *GetCameraMan(); // return camera entity if any
void CreateMove(CUserCmd *cmd);
void FixupMovmentParents();
void PostEntityPacketReceived();
const char *GetTitleText() { return m_szTitleText; }
int GetNumSpectators() { return m_nNumSpectators; }
protected:
void CalcChaseCamView(Vector &eyeOrigin, QAngle &eyeAngles, float &fov);
void CalcFixedView(Vector &eyeOrigin, QAngle &eyeAngles, float &fov);
void CalcInEyeCamView(Vector &eyeOrigin, QAngle &eyeAngles, float &fov);
void CalcRoamingView(Vector &eyeOrigin, QAngle &eyeAngles, float &fov);
void SmoothCameraAngle(QAngle &targetAngle);
void SetCameraAngle(QAngle &targetAngle);
void Accelerate(Vector &wishdir, float wishspeed, float accel);
int m_nCameraMode; // current camera mode
int m_iCameraMan; // camera man entindex or 0
Vector m_vCamOrigin; //current camera origin
QAngle m_aCamAngle; //current camera angle
int m_iTraget1; // first tracked target or 0
int m_iTraget2; // second tracked target or 0
float m_flFOV; // current FOV
float m_flOffset; // z-offset from target origin
float m_flDistance; // distance to traget origin+offset
float m_flLastDistance; // too smooth distance
float m_flTheta; // view angle horizontal
float m_flPhi; // view angle vertical
float m_flInertia; // camera inertia 0..100
float m_flLastAngleUpdateTime;
bool m_bEntityPacketReceived; // true after a new packet was received
int m_nNumSpectators;
char m_szTitleText[64];
CUserCmd m_LastCmd;
Vector m_vecVelocity;
};
extern C_HLTVCamera *HLTVCamera(); // get Singleton
#endif // HLTVCAMERA_H
| 27.696078 | 89 | 0.690973 | [
"vector"
] |
0f3f76aa9d9ea8228965c90c9c8f28bbe98443f9 | 4,339 | h | C | src/ThreadedOutputManagerImplementationBase.h | wilseypa/warped | 8842cf88b11213b6b69e53de5e969c4e3c2c8bd5 | [
"MIT"
] | 12 | 2015-03-13T09:58:25.000Z | 2021-09-23T11:48:42.000Z | src/ThreadedOutputManagerImplementationBase.h | wilseypa/warped | 8842cf88b11213b6b69e53de5e969c4e3c2c8bd5 | [
"MIT"
] | 1 | 2015-12-09T05:21:44.000Z | 2015-12-17T19:37:12.000Z | src/ThreadedOutputManagerImplementationBase.h | wilseypa/warped | 8842cf88b11213b6b69e53de5e969c4e3c2c8bd5 | [
"MIT"
] | null | null | null | #ifndef THREADEDOUTPUTMANAGERIMPLEMENTATIONBASE_H_
#define THREADEDOUTPUTMANAGERIMPLEMENTATIONBASE_H_
#include <fstream> // for ofstream
#include <set> // for multiset
#include <vector> // for vector
#include "ObjectID.h" // for ObjectID
#include "ThreadedOutputEvents.h"
#include "ThreadedOutputManager.h" // for ofstream, etc
#include "ThreadedTimeWarpMultiSet.h" // for multiset
#include "ThreadedTimeWarpMultiSetLTSF.h" // for multiset
#include "ThreadedTimeWarpSimulationManager.h"
#include "warped.h"
class Event;
class SimulationObject;
class ThreadedOutputEvents;
class ThreadedTimeWarpSimulationManager;
class TimeWarpSimulationManager;
class VTime;
using std::multiset;
/** The ThreadedOutputManagerImplementationBase class.
This is the implementation base class from which all output
manager implementations are derived from. This class contains all
data common to the three support output managers: Aggressive,
Lazy, and Adaptive.
*/
class ThreadedOutputManagerImplementationBase : public ThreadedOutputManager {
friend class AggressiveOutputManagerTest;
public:
/**@name Public Class Methods of ThreadedOutputManagerImplementationBase. */
//@{
/** Constructor.
@param simMgr Handle to the simulation manager.
*/
ThreadedOutputManagerImplementationBase(ThreadedTimeWarpSimulationManager* simMgr);
/// Destructor
~ThreadedOutputManagerImplementationBase();
/** Insert an event into the event set.
@param event Ptr. to the event to be inserted.
@param object Ptr. to the object who generated the output event.
*/
virtual void insert(const Event* event, int threadID);
/** Delete any unwanted (processed) elements.
@param fossilCollectTime Time up to which to grbg-collect.
@param object Simulation Object for which to grbg-collect
*/
virtual void fossilCollect(SimulationObject* object,
const VTime& fossilCollectTime, int threadID);
/** Delete any unwanted (processed) elements.
@param fossilCollectTime Time up to which to grbg-collect.
@param object Simulation Object for which to grbg-collect
*/
virtual void fossilCollect(SimulationObject* object,
int fossilCollectTime, int threadID);
/** Delete a single event from the output queue.
@param toRemove The event to remove.
*/
virtual void fossilCollectEvent(const Event* toRemove, int threadID);
/** Gets the oldest event in the output set.
@param unsigned int The needed size of the event.
@return The oldest event, or NULL if none found that match the size.
*/
///this Method is not called anywhere. Need to optimize this if called somewhere
virtual const Event* getOldestEvent(unsigned int size, int threadID);
/** Save the output events at the specified checkpoint time.
Only used for the optimistic fossil collection manager.
@param outFile The checkpoint output file.
@param objId The ID of the object being saved.
@param saveTime The checkpoint time.
*/
virtual void saveOutputCheckpoint(std::ofstream* outFile, const ObjectID& objId, unsigned int saveTime,
int threadID);
/**
Remove all events from the output set. Used to restore state after
a catastrophic rollback while using optimistic fossil collection.
*/
virtual void ofcPurge(int threadID);
//@} // End of Public Class Methods of ThreadedOutputManagerImplementationBase.
protected:
/**@name Protected Class Methods of ThreadedOutputManagerImplementationBase. */
//@{
ThreadedOutputEvents& getOutputEventsFor(const ObjectID& objectId);
TimeWarpSimulationManager* getSimulationManager() {
return mySimulationManager;
}
//@} // End of Protected Class Methods of ThreadedOutputManagerImplementationBase.
private:
/// Handle to the simulation manager.
ThreadedTimeWarpSimulationManager* mySimulationManager;
/// Pointer to the event set.
vector< ThreadedOutputEvents*> myOutputEvents;
std::ofstream* myStream;
};
#endif /* ThreadedOUTPUTMANAGERIMPLEMENTATIONBASE_H_ */
| 33.635659 | 107 | 0.704771 | [
"object",
"vector"
] |
0f46e604d42719b9a1673f62273ac266327b3844 | 524 | h | C | pathtrace/fast_rand.h | kiwixz/pathtracer | 62fbcee37ec6a60762061e430b9421a0177dde70 | [
"MIT"
] | 1 | 2019-04-08T07:59:26.000Z | 2019-04-08T07:59:26.000Z | pathtrace/fast_rand.h | kiwixz/pathtracer | 62fbcee37ec6a60762061e430b9421a0177dde70 | [
"MIT"
] | null | null | null | pathtrace/fast_rand.h | kiwixz/pathtracer | 62fbcee37ec6a60762061e430b9421a0177dde70 | [
"MIT"
] | null | null | null | #pragma once
#include <glm/vec3.hpp>
#include <random>
namespace pathtrace {
class FastRand {
public:
FastRand();
/// returns a number in [0; 1)
double operator()();
/// returns a number in [0; max)
double operator()(double max);
/// returns a number in [min; max)
double operator()(double min, double max);
/// returns a normalized vector
glm::dvec3 sphere();
private:
std::mt19937_64 gen_;
};
} // namespace pathtrace
| 19.407407 | 50 | 0.561069 | [
"vector"
] |
0f4f21b4cf9beb27b04c108403f85add1516c7d9 | 21,336 | h | C | DXLProServo.h | SOKamal213/DXLProM42Control | b89cd536f43410d146cddda1fa3f2f5cf48cbced | [
"Apache-2.0"
] | null | null | null | DXLProServo.h | SOKamal213/DXLProM42Control | b89cd536f43410d146cddda1fa3f2f5cf48cbced | [
"Apache-2.0"
] | null | null | null | DXLProServo.h | SOKamal213/DXLProM42Control | b89cd536f43410d146cddda1fa3f2f5cf48cbced | [
"Apache-2.0"
] | null | null | null | #pragma once
/*///////////////////////////////////////////////////////////////////////////////
Created by: Sayyed Omar Kamal
Date: 8 June 2018
For Dynamixel Pro servos, based on MX-64 servo control. Basic C++ function calls working properly in Linux.
*////////////////////////////////////////////////////////////////////////////////
#if defined(__linux__) || defined(__APPLE__)
#include <fcntl.h>
#include <termios.h>
#include <unistd.h>
#include <errno.h>
#define STDIN_FILENO 0
#elif defined(_WIN32) || defined(_WIN64)
#include <conio.h>
#endif
#include <algorithm>
#include <vector>
#include <string>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <cmath>
#include <stdlib.h>
#include <stdio.h>
#include <cstdio>
//#include <time.h>
//#include <chrono>
//#include <thread>
#include "dynamixel_sdk/dynamixel_sdk.h" // Uses Dynamixel SDK library
// Control table address
//EEPROM
#define ADDR_MX_ID 7
#define ADDR_PRO_ID 7
#define ADDR_MX_BAUD_RATE 8
#define ADDR_PRO_BAUD_RATE 8
#define ADDR_MX_OPERATING_MODE 11
#define ADDR_PRO_OPERATING_MODE 11
#define ADDR_MX_PROTOCOL_VERSION 13
// Pro servos fixed at Protocol 2.0
#define ADDR_MX_HOMING_OFFSET 20
#define ADDR_PRO_HOMING_OFFSET 13
#define ADDR_MX_MOVING_THRESHOLD 24
#define ADDR_PRO_MOVING_THRESHOLD 17
#define ADDR_MX_TEMPERATURE_LIMIT 31
#define ADDR_PRO_TEMPERATURE_LIMIT 21
// Voltage supplied with fixed dc-dc converter, no need to alter voltage limits
// MX only: PWM not in use for now, not adding
#define ADDR_MX_CURRENT_LIMIT 38
#define ADDR_PRO_TORQUE_LIMIT 30 //Pro uses Torque as current limit
#define ADDR_MX_ACCELERATION_LIMIT 40
#define ADDR_PRO_ACCELERATION_LIMIT 26
#define ADDR_MX_VELOCITY_LIMIT 44
#define ADDR_PRO_VELOCITY_LIMIT 32
#define ADDR_MX_MAX_POSITION_LIMIT 48
#define ADDR_MX_MIN_POSITION_LIMIT 52
#define ADDR_PRO_MAX_POSITION_LIMIT 36
#define ADDR_PRO_MIN_POSITION_LIMIT 40
// Pro only
#define ADDR_PRO_EXT_PORT_MODE_1 44
#define ADDR_PRO_EXT_PORT_MODE_2 45
#define ADDR_PRO_EXT_PORT_MODE_3 46
#define ADDR_PRO_EXT_PORT_MODE_4 47
#define ADDR_MX_SHUTDOWN 63
#define ADDR_PRO_SHUTDOWN 48
// Pro Indirect Address would be here, not in use at moment so not added
//RAM
#define ADDR_MX_TORQUE_ENABLE 64
#define ADDR_PRO_TORQUE_ENABLE 562
#define ADDR_MX_LED 65
#define ADDR_PRO_LED_RED 563
#define ADDR_PRO_LED_GREEN 564
#define ADDR_PRO_LED_BLUE 565
#define ADDR_MX_STATUS_RETURN_LEVEL 65
#define ADDR_PRO_STATUS_RETURN_LEVEL 891
// Read only
#define ADDR_MX_REGISTERED_INSTRUCTION 69
#define ADDR_PRO_REGISTERED_INSTRUCTION 890
// Read only
#define ADDR_MX_HARDWARE_ERROR_STATUS 70
#define ADDR_PRO_HARDWARE_ERROR_STATUS 892
// Velocity (I,P) Gains not implemented yet
// Position Gains (MX:D,I,P,FF2,FF1; Pro:P)
#define ADDR_MX_POSITION_D_GAIN 80
#define ADDR_MX_POSITION_I_GAIN 82
#define ADDR_MX_POSITION_P_GAIN 84
#define ADDR_MX_POSITION_FF2_GAIN 88
#define ADDR_MX_POSITION_FF1_GAIN 90
#define ADDR_PRO_POSITION_P_GAIN 594
// MX only: Bus Watchdog not in use currently
// MX only: Goal PWM not in use currently
#define ADDR_MX_GOAL_CURRENT 102
#define ADDR_PRO_GOAL_TORQUE 604
#define ADDR_MX_GOAL_VELOCITY 104
#define ADDR_PRO_GOAL_VELOCITY 600
// Profile vars for MX only
#define ADDR_MX_PROFILE_ACCELERATION 108
#define ADDR_MX_PROFILE_VELOCITY 112
#define ADDR_MX_GOAL_POSITION 116
#define ADDR_PRO_GOAL_POSITION 596
// MX only: Realtime Tick not in use currently
#define ADDR_PRO_GOAL_ACCELERATION 606
// Read only
#define ADDR_MX_MOVING 122
#define ADDR_PRO_MOVING 610
// MX only
#define ADDR_MX_MOVING_STATUS 123
// All Present Registers are read-only
#define ADDR_MX_PRESENT_CURRENT 126
#define ADDR_PRO_PRESENT_CURRENT 621
#define ADDR_MX_PRESENT_VELOCITY 128
#define ADDR_PRO_PRESENT_VELOCITY 615
#define ADDR_MX_PRESENT_POSITION 132
#define ADDR_PRO_PRESENT_POSITION 611
// MX only: Velocity and Position Trajectory not in use currently
// Present Input Voltage not in use currently
#define ADDR_MX_PRESENT_TEMPERATURE 146
#define ADDR_PRO_PRESENT_TEMPERATURE 625
// Pro only
#define ADDR_PRO_EXT_PORT_DATA_1 626
#define ADDR_PRO_EXT_PORT_DATA_2 628
#define ADDR_PRO_EXT_PORT_DATA_3 630
#define ADDR_PRO_EXT_PORT_DATA_4 632
// Indirect Data not in use currently
// Default settings
// Protocol version
#define PROTOCOL_VERSION 2.0 // Using Protocol 2.0
//Servo specific values
#define DXL_ID1 1 // Dynamixel1 ID, Pan Servo
#define DXL_ID2 2 // Dynamixel2 ID, Tilt Servo
#define DXL_BAUDRATE_57600 1 // Baudrate set value for 57600 baud, default baudrate
// Operating Mode Values
#define DXL_MX_CURRENT_CONTROL_MODE 0 // Operating Mode set value for Current Control Mode for MX
#define DXL_PRO_TORQUE_CONTROL_MODE 0 // Operating Mode set value for Torque Control Mode for Pro
#define DXL_VELOCITY_CONTROL_MODE 1 // Operating Mode set value for Velocity Control Mode
#define DXL_POSITION_CONTROL_MODE 3 // Operating Mode set value for Position Control (Single turn) Mode
#define DXL_EXTENDED_CONTROL_MODE 4 // Operating Mode set value for Extended Position Control (Multi turn) Mode
#define DXL_MX_CURRENT_POSITION_CONTROL_MODE 5 // Operating Mode set value for Current-based Position Control Mode for MX only
#define DXL_MX_PWM_CONTROL_MODE 16 // Operating Mode set value for PWM Control Mode for MX only
//Parameter Limits precalculated values
#define DXL_MX_CURRENT_LIMIT_MAX 1190 // Current Limit set value for 4 Amps maximum, MX-64R stall current: 4.1A at 12V
#define DXL_MX_ACCELERATION_LIMIT_LOW 30 // Acceleration Limit set value for 6437 rev/min2 maximum, MX
#define DXL_MX_VELOCITY_LIMIT_80 350 // Velocity Limit set value for 80.15 rpm maximum, MX
#define DXL_PRO_M42_TORQUE_LIMIT_MAX 521 // Torque limit for Pro M42, using current, absolute max at ~5.7Nm = 2.16A, use 2.1A
#define DXL_PRO_M42_VELOCITY_LIMIT_80 20562 // Velocity limit for Pro M42, 80 rpm
#define DXL_PRO_M42_ACCEL_LIMIT_LOW 30 // Acceleration limit for Pro M42, 6031 rpm2
//General servo data values
#define TORQUE_ENABLE 1 // Value for enabling the torque
#define TORQUE_DISABLE 0 // Value for disabling the torque
#define PROFILE_ACCELERATION_MAX 15 // Limiting value to ensure DXL does not accelerate too quickly, causing following error
#define PROFILE_MX_VELOCITY_MAX 200 // Limiting value to ensure DXL does not turn too quickly, causing following error
#define PROFILE_PRO_VELOCITY_MAX 2570
#define DXL_MX_MOVING_STATUS_THRESHOLD 10 // Dynamixel moving status threshold
#define DXL_PRO_MOVING_STATUS_THRESHOLD 50
//Values for system commands
#define BAUDRATE 57600 //For use in code, not to set DXL Baudrate
#if defined(__linux__) || defined(__APPLE__)
#define DEVICENAME1 "/dev/ttyUSB1"
#elif defined(_WIN32) || defined(_WIN64)
#define DEVICENAME1 "COM1" // Check which port is being used on each servo
// ex) Windows: "COM1" Linux: "/dev/ttyUSB0" Mac: "/dev/tty.usbserial-*"
#endif
#define ESC_ASCII_VALUE 0x1b
//DXL Servo type defines
#define DXL_MX_64 0
#define DXL_PRO_M42 1
class DXLServo {
private:
std::vector<int> goalPositionVector;
std::vector<double> goalAngleVector;
int limitAccel, limitVel, profileAccel, profileVel, limitCurrent, limitPosMin, limitPosMax, homeOffset;
int externalPort[4]; // External Port Mode indicator. Ports 1 - 4, modes 0 - 3. E.g. externalPort[0] = 1; -> extrenal port 1 set to output mode.
protected:
public:
DXLServo();
~DXLServo();
double protocolVersion;
uint8_t dxl_error;
int dxl_comm_result, baudRate, identity, servoType;
int present_position, present_temperature;
double present_current;
dynamixel::PortHandler *prtHandler;
dynamixel::PacketHandler *pktHandler;
//std::string deviceName = std::string( "/dev/ttyUSB" );
#if defined(__linux__) || defined(__APPLE__)
std::string deviceName = std::string("/dev/ttyUSB");
#elif defined(_WIN32) || defined(_WIN64)
std::string deviceName = std::string("COM");
#endif
void setDXLServo(int servoModel) {
if (servoModel == 0) servoType = DXL_MX_64;
else if (servoModel == 1) servoType = DXL_PRO_M42;
else printf("Error! Invalid Servo selected! Select '0' for MX-64 or '1' for Pro M42!");
}
void setDXLID(int dxlNum) {
identity = dxlNum;
}
int getDXLID() { // get DXL ID set in code memory
return identity;
}
void setDeviceName() { // If default ID used, COM1 or /dev/ttyUSB1
std::stringstream sstm;
sstm << deviceName << 1;
deviceName = sstm.str();
}
void setDeviceName(int deviceNum) { // For multi DXL ID
std::stringstream sstm;
sstm << deviceName << deviceNum;
deviceName = sstm.str();
}
void initPortHandler() {
this->prtHandler = dynamixel::PortHandler::getPortHandler(deviceName.c_str());
}
void setProtocolVersion(double protocolNum) { // Set Protocol 1.0 or 2.0
protocolVersion = protocolNum;
}
void initPacketHandler() {
this->pktHandler = dynamixel::PacketHandler::getPacketHandler(protocolVersion);
}
void openPort() { // Open comms port to DXL
if (this->prtHandler->openPort())
{
printf("Succeeded to open the port!\n");
}
else
{
printf("Failed to open the port!\n");
//printf("Press any key to terminate...\n");
//_getch();
}
}
void setDeviceBaudRate(int desiredRate) {
baudRate = desiredRate;
}
void closePort() {
this->prtHandler->closePort();
}
void setPortBaudRate() {
if (this->prtHandler->setBaudRate(baudRate))
{
printf("Succeeded to change the baudrate!\n");
}
else
{
printf("Failed to change the baudrate!\n");
//printf("Press any key to terminate...\n");
//_getch();
//return 0;
}
}
void enableTorque(); // Enable servo motion. Must be set for servo to operate. Changes to EEPROM registers must be applied before calling this.
void disableTorque(); // Disable servo motion. Call at end of use.
// GoalPos functions use Position values for direct transmission
void addToGoalPosVector(const std::vector<int> &posVector); // Add Position values into internal vector. Uses std::vector<int> as input. CHANGE to int[], more common?
//void addToGoalPosVector(int posVector[]);
void addToGoalPosVector(int posVector) { // Add 1 Position value to internal vector. Use in for loop with int array data.
goalPositionVector.push_back(posVector);
}
int checkGoalPosVector(); // Check internal Position Vector for empty vector or invalid values
void resetGoalPosVector() { // Reset internal Position Vector for new values if needed
goalPositionVector.clear();
}
void writeGoalPosition(int vectorPosition); // Write Goal Position to DXL from internal GoalPos Vector
void writeGoalPosition(int select, int vectorPosition); // Write Goal Position to DXL directly or from internal Goal Position Vector; int select = {0 -> from internal vector, 1 -> direct}
int readCurrentPosition(); // Read Position value from servo, position value does not include homing offset
int getCurrentGoalPos(int index) { // Read value of position in internal Goal Position vector, assumes user already knows size of vector
return goalPositionVector[index];
}
// GoalAngle functions use angle as inputs, require conversion to Position values for transmission
double readCurrentAngle(); // Read Position value and convert to angle, angle value includes homing offset, assumes initial read acquired
void addToGoalAngleVect(const std::vector<double> &angVector); // Add angle values into internal vector. Angle values depend on servo used (e.g. MX-64: 0-360 deg, Pro: -180 to 180).
//void addToGoalAngleVect(double angVector[]);
void addToGoalAngleVect(double angVector) { // Add 1 Angle into internal vector. Use in for loop with double array data.
goalAngleVector.push_back(angVector);
}
int checkGoalAngleVect(); // Check internal vector for empty vector
void resetGoalAngleVect() { // Reset internal Angle Vector for new values if needed
goalAngleVector.clear();
}
void writeGoalAngle(int vectorAngle); // Write Goal Angle to DXL from internal GoalAngle Vector
void writeGoalAngle(int select, double vectorAngle); // Write Goal Angle to DXL directly or from internal Goal Angle Vector; int select = {0 -> from internal vector, 1 -> direct}, conversion to Position value handled, includes home offset
int getCurrentGoalAngle(int index) { // Read value of angle in internal Goal Angle vector, assumes user already knows size of vector
return goalAngleVector[index];
}
int checkOperating(); // Return value of Operating Mode; 0 = Current control, 1 = Velocity control, 3 = Position control (single turn), 4 = Extended Position control (Multi-turn), 5 = Current-based Position control, 16 = PWN control
int checkPositionMode(); // Check if Operating Mode is set to Position Control (Single Turn). Returns 1 if yes, 0 if other control modes, -1 if error.
void setOperatingMode(int mode); // Change DXL Operating Mode; mode selection values 0-5, 0 = Current, 1 = Velocity, 2 = Position (single turn), 3 = Extended Position(Multi turn), 4 = Current based Position, 5 = PWM
void setMaxCurrentLimit(); // Set current limit to max Amps before stall torque occurs, value predefined in header
void setCurrentLimit(double amps); // Set current limit between 0 - servo limit. MX-64: 4.0 A, Pro M42: 0 - 2.1 A
void setCurrentLimit(int limit); // Set current limit between 0 - 1941, current = limit * 3.36mA {externally calculated}
void set80rpmVelLimit(); // Set Velocity limit to 80.15 rpm, value predefined in header
void setVelocityLimit(int limit); // Set Velocity limit between 0 - 1023, velocity = limit * 0.229rpm {externally calculated}
void setVelocityLimit(double limit); // Set Velocity limit between 0 - 235.0 rpm
int getVelocityLimit(); // Return Velocity Limit set in DXL
void setlowAccelLimit(); // Set Acceleration limit to 30 * 214.577 = 6437 rev/min2, value predefined in header
void setAccelLimit(int limit); // Set Acceleration limit between 0 - 100, limited to 100 as actual limit is far too large for safe operation.
void setAccelLimit(double limit); // Set Acceleration limit between 0 - (100 * unit), limited to 100 times for safe operation
int getAccelLimit(); // Return Acceleration Limit set in DXL. Value multiply 214.517rev/mim2.
void setPositionLimit(bool minMax, int position); // Set Position Limit; minMax: false for Min (Lower) limit, true for Max (Upper) limit; Position between 0 and limit
void setPositionLimit(bool minMax, double angle); // Set Position Limit; minMax: false for Min (Lower) limit, true for Max (Upper) limit; angle between 0 to 360 or -180 and +180 degrees, see servo type
void setProfileAcceleration(int accel); // Set Profile Acceleration, accel must be between 1 and limit set in EEPROM, 0 not allowed so no infinite acceleration. Accel value in integer for direct transmission.
void setProfileAcceleration(double accel); // Set Profile Acceleration, accel must be between 1.0 and limit, 0 not allowed so no infinite acceleration. Acceleration in rev/min2 to be converted for transmission.
int checkProfileAcceleration(); // Check value of Profile Acceleration in DXL RAM, return int, conversion available.
void setProfileVelocity(int vel); // Set Profile Velocity, vel must be between 1 and limit set in EEPROM, 0 not allowed so no infinite velocity, Velocity value in integer for direct transmission.
void setProfileVelocity(double vel); // Set Profile Velocity, vel must be between 1.0 and (limit * unit) set in EEPROM, 0 not allowed so no infinite velocity, Velocity in rpm to be converted for transmission
int checkProfileVelocity(); // Check value of Profile Velocity in DXL RAM. Value multiply 0.229rpm
int checkPresentTemperature(); // Check Present Temperature, compare against limit, issues warning at 10% from limit and at or above limit. Returns: -1 if negative error, 0 if no problem, 1 if close to limit, 2 if exceed limit.
int getPresentTemperature(); // Return Present Temperature value, for displaying value externally
int checkPresentCurrent(); // Check Present Current, compare against limit, warning at 10% from limit, error at/beyond limit. Returns: -1 if negative error, 0 if no problem, 1 if close to limit, 2 if exceed limit.
double getPresentCurrent(); // Return Present Current value, for displaying externally
int getHomingOffset(); // Return Homing Offset value
bool isMoving(); // Check if servo is moving after write command
int convertPostoVal(double angle); // Convert input angle (desired position) into Position value for transmission
double convertValtoPos(int position); // Convert Position value from transmission into output angle
int convertCurrtoVal(double current); // Convert input current (amps) into Current value for transmission
double convertValtoCurr(int value); // Convert Current value from transmission into output current
int convertVeltoVal(double velocity); // Convert input velocity (rpm) into Velocity value for transmission
double convertValtoVel(int value); // Convert Velocity value from transmission into output velocity
int convertAcctoVal(double accel); // Convert input acceleration (rev/min2) into Acceleration value for transmission
double convertValtoAcc(int value); // Convert Acceleration value from transmission into output acceleration
void servoReboot(); // Call when servo shuts down due to error to reactivate. Reactivates servo and prints error message with details of last occurred error.
// Pro servos only
void selectExtPortMode(int port, int mode); // Select mode for External Ports 1-4, "port" to select port number, "mode" to select function. port: 1 - 4, mode: 0 - 3.
void setExtPortData(int port, int data); // For External Port output modes (1,3), set output to 0V or 3.3V.
int readExtPortData(int port); // Read value of External Port Datas.
void setLED(int color, int light); // Activate or deactivate LED/s. MX servos, single LED. Pro servos, (r,g,b) LEDs. "color": 0 for MX single LED, (1,2,3) for Pro (Red, Green, Blue) LED. "light": MX: 0 off, 1 on; Pro: 0 - 255 intensity.
void setPositionGain(int gainP, int gainI = 0, int gainD = 0, int gainF1 = 0, int gainF2 = 0); // Set Position Gains for servo motors. Pro servos only have variable P gain, MX servos have (P,I,D,FF1,FF2)
void readPositionGain(vector<int> &setGains); // Read Position Gains currently set in registers, store in vector<int>. MX: 5 gain values. Pro: 1 gain value.
int checkShutdown(int statusBits); // Check Hardware Error Status register for Shutdown condition. If Shutdown detected and not Overheating Error, try reboot. If Overheating Error, disable servo, warn user to disconnect motor for at least half hour.
};
| 50.679335 | 257 | 0.664276 | [
"vector"
] |
0f57b25a5c5dc5e60d448253fccc8565485b1580 | 1,732 | h | C | source/EMath.h | Kair0z/Custom-Rasterizer | f83c636c29b85e12cc3c1c85b25a0bc2da2eaf84 | [
"MIT"
] | null | null | null | source/EMath.h | Kair0z/Custom-Rasterizer | f83c636c29b85e12cc3c1c85b25a0bc2da2eaf84 | [
"MIT"
] | null | null | null | source/EMath.h | Kair0z/Custom-Rasterizer | f83c636c29b85e12cc3c1c85b25a0bc2da2eaf84 | [
"MIT"
] | null | null | null | /*=============================================================================*/
// Copyright 2019 Elite Engine 2.0
// Authors: Matthieu Delaere
/*=============================================================================*/
// EMath.h: General Math header that includes all math types and utilities
/*=============================================================================*/
#ifndef ELITE_MATH
#define ELITE_MATH
/* --- STANDARD --- */
#include <math.h>
#include <cassert>
/* --- UTILITIES --- */
#include "EMathUtilities.h"
/* --- TYPES --- */
#include "EVector.h"
#include "EVector2.h"
#include "EVector3.h"
#include "EVector4.h"
#include "EPoint.h"
#include "EPoint2.h"
#include "EPoint3.h"
#include "EPoint4.h"
#include "EMatrix.h"
#include "EMatrix2.h"
#include "EMatrix3.h"
#include "EMatrix4.h"
namespace Elite
{
/* --- TYPE DEFINES --- */
using FVector2 = Vector<2, float>;
using DVector2 = Vector<2, double>;
using IVector2 = Vector<2, int>;
using FVector3 = Vector<3, float>;
using DVector3 = Vector<3, double>;
using IVector3 = Vector<3, int>;
using FVector4 = Vector<4, float>;
using DVector4 = Vector<4, double>;
using IVector4 = Vector<4, int>;
using FPoint2 = Point<2, float>;
using DPoint2 = Point<2, double>;
using IPoint2 = Point<2, int>;
using FPoint3 = Point<3, float>;
using DPoint3 = Point<3, double>;
using IPoint3 = Point<3, int>;
using FPoint4 = Point<4, float>;
using DPoint4 = Point<4, double>;
using IPoint4 = Point<4, int>;
using FMatrix2 = Matrix<2, 2, float>;
using DMatrix2 = Matrix<2, 2, double>;
using FMatrix3 = Matrix<3, 3, float>;
using DMatrix3 = Matrix<3, 3, double>;
using FMatrix4 = Matrix<4, 4, float>;
using DMatrix4 = Matrix<4, 4, double>;
}
#endif
| 28.866667 | 81 | 0.582564 | [
"vector"
] |
0f6508d076d1e03db526411c556a7cc8137fb0ba | 23,249 | h | C | cpp/client-lite/headers/DataManager.h | CodeApprenticeRai/newt | 0e07a87aa6b8d4b238c1a9fd3fef363133866c57 | [
"Apache-2.0"
] | 1 | 2021-06-21T12:23:55.000Z | 2021-06-21T12:23:55.000Z | cpp/client-lite/headers/DataManager.h | CodeApprenticeRai/newt | 0e07a87aa6b8d4b238c1a9fd3fef363133866c57 | [
"Apache-2.0"
] | null | null | null | cpp/client-lite/headers/DataManager.h | CodeApprenticeRai/newt | 0e07a87aa6b8d4b238c1a9fd3fef363133866c57 | [
"Apache-2.0"
] | 6 | 2019-10-17T21:16:21.000Z | 2020-10-19T08:27:01.000Z | #ifndef _DATAMANAGER_H_
#define _DATAMANAGER_H_
#include <vector>
#include <deque>
#include <ext/hash_map>
#include <algorithm>
#include <cstdio>
#include <Common/MktEnums.h>
#include "Client/lib2/CIndex.h"
#include <holiday2/Holiday.h>
#include <holiday2/HolidaySet.h>
#include <Client/lib3/ordermanagement/common/OrderManager.h>
#include <Client/lib3/bookmanagement/common/Book.h>
#include <Client/lib3/bookmanagement/common/MarketBook.h>
#include <Client/lib3/bookmanagement/common/OrderBook.h>
#include <Client/lib3/bookmanagement/common/BookLevel.h>
#include <Client/lib3/tickmanagement/common/TickHandler.h>
#include <tael/Log.h>
#include <tael/FdLogger.h>
#include <SubOrderBook.h>
#include "c_util/Time.h"
using trc::compat::util::TimeVal;
#include <cl-util/Configurable.h>
#include <cl-util/factory.h>
#include <cl-util/debug_stream.h>
#include <cl-util/table.h>
#include <Markets.h>
#include <DataUpdates.h>
#include <clite/message.h>
#include <BookTools.h>
#include <boost/iterator/filter_iterator.hpp>
#include <boost/iterator/transform_iterator.hpp>
#include <functional>
#include <Client/lib2/LiveSource.h>
class TimedAggrLiveSource;
class AggrDataFileSource;
class LiveSource;
class EventSourceCB;
// GVNOTE: The class PortLiveSource has been changed to PortLiveSourceImpl, and
// it now takes a template parameter. However, PortLiveSource is defined as a type
// using typedef. We want to use that definition.
//class PortLiveSource;
namespace __gnu_cxx {
template <typename T> struct hash<T *> {
size_t operator() (T *__x) const {
return reinterpret_cast<size_t>(__x);
}
};
}
#define MAX_ALLOWED_REJECTS 10
/** A wrapper for all lib2 HF infrastructure.
*
* This will contain and hide all HF infrastructure, and provide a more
* consistent and simpler interface to it. Most other things in this package
* will be UpdateListeners to this class.
*
* It consolidates physical data links and order routes to logical ECNs, with
* separate options to switch data sources and routes without changing the code
* accessing those ECNs. It also supplies a single interface for data updates.
*
* Users will get incremental updates from the UpdateListener, and consistent
* state snapshots from the DataManager itself (see get(Sub)Market).
*
* It supplies some error and debugging logging, but statistic and debugging
* logging should be separate modules that listen to the DataManager whenever
* possible.
*
* Assumptions:
* - Population set / CIndex membership is specified at creation of
* DataManager object, and is constant across life of object.
*
*/
class DataManager :
public Configurable,
public lib3::OMListener,
public lib3::MarketBookListener,
public EventListener,
public CIListener,
public clite::message::coordinator<WakeupHandler>
{
public:
enum TradeSystem {
COLO, SIMTRADE, NONE
};
std::vector<bool> stops;
private:
TradeSystem tradesys; /// COLO / SIMTRADE / NONE
// bool trading_halted;
void construct ( );
std::string ddbgfile_, odbgfile_;
std::string reportfile_;
std::string alphalogfile_;
std::string outfile_;
//int outfd_;
FILE* outfp;
int numRejects;
// dbglvl should ideally be of type trc::tael::Severity::Level instead of int. However,
// if we do that, then Boost libraries complain. Also, it is not clear how would we
// specify a Security::Level in a configuration file. So using int.
int dbglvl;
int useq;
void checkWakeup ( int cid = -1 );
void checkTimes();
static const int mbk_id;
std::string trade_type; // "colo", "sim", "none"
std::string margin_server;
std::string position_server;
std::string sim_config;
std::string colo_config;
//std::string margin_acct;
std::string ps_acct;
struct sim_options {
typedef size_t key_type;
ECN::ECN ecn;
int seq_us, live_us, reply_us, cancel_us;
sim_options ( std::vector<std::string> const &hdr, std::vector<std::string> const &vals );
key_type get_key() { return (size_t)(ecn); }
};
struct colo_options {
typedef size_t key_type;
ECN::ECN ecn;
std::string account, host;
int port;
colo_options ( std::vector<std::string> const &hdr, std::vector<std::string> const &vals );
key_type get_key() { return (size_t)(ecn); }
};
clite::util::factory<clite::util::debug_stream>::pointer sim_exec_logger, sim_action_logger;
std::string sim_outdir;
bool parse_combined_server(std::string const &in, std::string *user, std::string *host, int *port);
bool getPos ( bool async );
bool getPos ( int cid, bool async );
bool getLoc ( bool async );
protected:
clite::util::factory<clite::util::debug_stream>::pointer dbg;
boost::shared_ptr<tael::FdLogger> reportfld;
tael::Logger reportlog;
clite::util::file_table<colo_options> *colos;
clite::util::file_table<sim_options> *sims;
bool live;
bool massive;
bool MOCmode;
std::vector<bool> data_on;
bool useextrd;
bool usepoplus;
int recvbuf;
bool listen_only;
//bool trade_live;
uint32_t seqnum_, seqoff_, seqinc_;
int sdate_;
int edate_;
// int i3date_, i4date_, b3date_, b3fdate_, i4fdate_;
int nysetrdate_, arcatrdate_;
std::string datadir_;
std::vector<std::string> reply_groups;
std::vector<std::string> datastr_;
std::vector<int> symbol_subsets;
//magic numbers all the hell over the place
const static uint32_t seqnum_ecn_mask = 0xf << 26;
inline int32_t next_seqnum (ECN::ECN ecn) {
seqnum_ = std::max(((uint32_t)curtv().sec() % 86400) * 750 + seqoff_, seqnum_ + seqinc_);
return ((uint32_t)(ecn) << 26) | seqnum_;
}
inline ECN::ECN seqnum_ecn ( int seq ) {
return ECN::ECN((uint32_t)(seq & seqnum_ecn_mask) >> 26);
}
holiday2::HolidaySet holidays;
std::string holiday_file;
struct SymbolRecord {
char symbol[9];
int cid;
int position;
int orders;
bool set_exposure;
double exposure;
};
double maxmargin_;
std::vector<SymbolRecord> limits_;
bool setupSymbols ( );
void setLimits ( const SymbolRecord &sr );
// require setup; are pointers
lib3::OrderManager *om;
//lib3::PositionManager *pm;
lib3::MarginServer *ms;
lib3::PositionServer *ps;
EventSourceCB *ecb;
TimedAggrLiveSource *als;
AggrDataFileSource *adfs;
//LiveSource *ls;
EventSource *es;
// containers
CIndex ci_;
std::vector<MarketMaker> ecnToMM; // just for trading?
std::vector<std::string> symbols_;
// various settings
std::vector<std::string> symfile_;
typedef std::priority_queue<TimeUpdate> timerq;
typedef std::set<Timer> timerset;
timerq nexttimes;
timerset timers;
TimeVal midnight_;
TimeVal mktopen_, mktclose_;
bool initialized_, running_, enable_trd_;
TimeVal curtv_;
int date_;
//lib3 infrastructure
//indexed by ECN::ECN
std::vector<lib3::MarketBook *> mktbks;
std::vector<lib3::SubOrderBook *> ordbks;
std::vector<lib3::QuoteHandlerBase<lib3::BookOrder> *> qhs;
// GVNOTE: Perhaps we need to define a tick handler base as well?
// The simulation classes in lib3 need one now
std::vector<std::string> colo_accts;
lib3::AggrMarketBook *mbk;
bool setup_callbacks();
// bool setup_margin_server ( );
bool setup_position_server ( );
bool setup_sim_trade();
bool setup_colo_trade();
bool setup_live_data();
bool setup_hist_data();
bool setup_pls ( PortLiveSource *pls, const char *addr );
template <typename QH>
void setup_book (ECN::ECN ecn) {
QH *qh = new QH(ci_, ECN::desc(ecn), ecb, es->clock, true, dbg.get());
lib3::MarketBook *bk = new lib3::MarketBook(ci_, ecn, es->clock, dbg.get());
bk->add_listener(mbk);
// GVNOTE: Not sure why do we auto correct locked / crossed market.
bk->set_auto_correct(true);
qh->add_listener(bk);
qh->add_listener(mbk);
mktbks[ecn] = bk;
qhs[ecn] = qh;
}
template <typename TRANS, typename TRADE>
void setup_colo_trader (colo_options const &colo) {
using namespace lib3;
TRANS *tx =
new TRANS(colo.host.c_str(), colo.port, es->clock, dbg.get());
if (!tx->connect()) {
TAEL_PRINTF(dbg.get(), TAEL_ERROR, "failed to connect to %s at %s:%d",
ECN::desc(colo.ecn), colo.host.c_str(), colo.port);
}
SingleThreadedScheduler<SockMessageStruct> *comm =
new SingleThreadedScheduler<SockMessageStruct>(tx, dbg.get());
TraderBase *trader = new
TRADE(colo.account.c_str(), om, comm, es->clock, ci_, ecb, dbg.get());
om->add_trader(trader);
//pm->add_account(colo.account.c_str());
colo_accts[colo.ecn] = colo.account;
trader->qh->add_listener(ordbks[colo.ecn]);
// GVNOTE: Don't understand the following comment ;(
// hack to avoid our real account for cxl-on-disconnect
if (listen_only) {
trader->request_position(ci_["SPY"], "_DUMMY_", true);
}
std::cout << "Leaving setup_colo_trader " << ECN::desc(colo.ecn) << std::endl;
}
template <typename SIM, typename TRADE>
void setup_sim_trader (sim_options const &sim) {
using namespace lib3;
using namespace clite::util;
// GVNOTE: Adding a null TickHandlerBase object to make it compile. Revisit this!
//lib3::TickHandlerBase *thb = static_cast<lib3::TickHandlerBase*>(NULL);
std::cout << "In setup_sim_trader " << ECN::desc(sim.ecn) << std::endl;
SIM* simmkt;
if (MOCmode) {
simmkt = new SIM(new lib3::MarketBook(ci_, 0, es->clock, dbg.get()), NULL, ci_, ecb, es->clock, sim_action_logger.get(), sim_exec_logger.get(), dbg.get());
} else {
simmkt = new SIM(qhs[sim.ecn], NULL, ci_, ecb, es->clock, sim_action_logger.get(), sim_exec_logger.get(), dbg.get());
if (simmkt->fqh) {
simmkt->fqh->add_listener(mktbks[sim.ecn]);
simmkt->fqh->add_listener(mbk);
} else {
TAEL_PRINTF(dbg.get(), TAEL_ERROR, "setup_sim_trader: %s has no fqh!", ECN::desc(sim.ecn));
}
}
/* // GVNOTE: Due to the latest hyp2 upgrade, we no longer need to add an event source.
* // In the constructor for SimMarket, they get the event source using ecb->get_src()
if (live) simmkt->add_source(als);
else simmkt->add_source(adfs);
*/
simmkt->tt_seq = TimeVal(0, sim.seq_us);
simmkt->tt_live = TimeVal(0, sim.live_us);
simmkt->tt_conf = TimeVal(0, sim.live_us + sim.reply_us);
simmkt->tt_reply = TimeVal(0, sim.reply_us);
simmkt->tt_nolive = TimeVal(0, sim.cancel_us);
simmkt->use_fake_updates = true;
std::string account = std::string("RTS") + std::string(ECN::desc(sim.ecn));
if (sim.ecn == ECN::ISLD) {
account = std::string("RTSNASD");
}
TraderBase *trader = new TRADE(account.c_str(), om, simmkt, es->clock, ci_, ecb, dbg.get());
std::cout << "In setup_sim_trader. Created trader object for " << ECN::desc(sim.ecn)
<< " using account " << account.c_str() << std::endl;
om->add_trader(trader);
//pm->add_account(account.c_str());
colo_accts[sim.ecn] = account;
trader->qh->add_listener(ordbks[sim.ecn]);
}
bool isShort(int cid, int sz);
void buildImpTick(DataUpdate &d, int cid, double px, int sz, ECN::ECN ecn, TimeVal tv);
/** An exception for unwinding the HF callbacks. */
class Stop {
public:
Mkt::RunStatus status;
std::string what;
Stop(Mkt::RunStatus s, std::string w = "") :status(s), what(w) { }
Stop() { }
};
MarketHandler mh;
TapeHandler th;
TimeHandler tmh;
OrderHandler oh;
UserMessageHandler umh;
public:
/** Default constructor. Sets up configuration options and logging. */
DataManager ( );
/** Constructor with configuration prefix.
*
* Use this to give the configuration parameters a prefix. Otherwise
* the same as the default constructor.
*/
DataManager ( std::string &confname );
/** Initialize all HF infra structure.
*
* This should be implemented by a child class to set up all HF data
* sources and callbacks, using the configuration parameters in DM.
* Implementors should call DataManager::preinit before doing any work,
* and DataManager::postinit afterwards, and should return true only if
* no errors are met.
*/
virtual bool initialize ( );
/** Begin the callback loop, and return status on exit.
*
* Call the HF callbacks, and begin running. Will return a status code
* when the callback loop is either stopped, runs out of data, or
* encounters an error.
*/
virtual Mkt::RunStatus run ( );
/** Stop the HF callback loop in a safe, defined way.
*
* This results in DataManager::run returning with a status of STOPPED.
* TODO: inform listeners that we're about to stop with an Admin
* message, and wake them up.
*/
virtual void stop ( std::string reason ) {
Stop s;
s.status = Mkt::STOPPED;
s.what = reason;
throw s;
};
/** Access the symbol <-> cid mapping.
*
* Securities are referenced by a small non-negative integer called a
* cid. This mapping is accessed by this function.
*/
const char *symbol ( int cid ) const {
return ci_[cid];
}
int cid ( const char *sym ) const {
return ci_[sym];
}
/** I am not happy with this.
*
* In general, all cids should be occupied between 0 and the return
* value of this function. Rather than implementing a proper
* container, we'll just return the max cid + 1.
*/
int cidsize ( ) const {
return ci_.size();
}
/** The current time value. */
inline TimeVal const &curtv ( ) {
if (running_ && ecb->curtv() > curtv_) {
curtv_ = ecb->curtv();
}
return curtv_;
}
/** Is it live mode? */
inline bool isLive() const {
return live;
}
inline const char* getAlphaLogFile() {
return (std::string(getenv("EXEC_LOG_DIR")) + std::string("/") + alphalogfile_).c_str();
}
// inline bool isTradingHalted() const { return trading_halted; }
// inline void setTradingHalted(bool trade_status) const { trading_halted = trade_status; }
/** What trade-system is it? (colo/sim/none) */
inline TradeSystem getTradeSystem() const { return tradesys; }
inline bool isMOCmode( ) const { return MOCmode; }
/** Are we listening to a particular ECN? */
inline bool isDataOn( ECN::ECN ecn ) const { return data_on[ecn]; }
void addTimer ( Timer t );
Timer const & nextTimer ( ) const { return nexttimes.top().timer(); }
inline Timer marketOpen ( ) const { return Timer(mktopen_); }
inline Timer marketClose ( ) const { return Timer(mktclose_); }
inline TimeVal timeValMktClose ( ) const { return mktclose_; }
typedef std::vector<lib3::MarketBook *> SubBookMap;
typedef std::vector<lib3::SubOrderBook *> SubOrderBookMap;
inline SubBookMap const &subBooks ( ) { return mktbks; }
inline lib3::MarketBook *subBook ( ECN::ECN ecn ) { return mktbks[ecn]; }
inline lib3::AggrMarketBook *masterBook ( ) { return mbk; }
inline lib3::OrderBook *orderBook ( ) { return listen_only? om->prom_book:om->book; }
inline lib3::SubOrderBook *subOrderBook ( ECN::ECN ecn ) { return ordbks[ecn]; }
inline SubOrderBookMap const &subOrderBooks ( ) { return ordbks; }
int getSDate() { return sdate_;}
enum BatsRouteMod {
//BATS_ONLY = 'B',
BATS_INTERMARKET = 'I', // IOC + ignore NBBO + no routing
//BATS_POSTONLY = 'P', // do not remove liquidity
BATS_NASDAQ = 'N', // BATS + Nasdaq (INET) only
BATS_NYSE = 'Y', // BATS + NYSE only
BATS_ARCA = 'A', // BATS + Archipelago only
BATS_NSXBLADE = 'C', // BATS + NSX Blade only
BATS_NMS = 'Z', // NSX first, then sweep BATS book
BATS_ALLMARKETS = 'R' // routable to all electronic markets
} __attribute__ ((__packed__)) ; // be only one byte
virtual Mkt::OrderResult placeOrder ( int cid, ECN::ECN ecn, int size, double price,
Mkt::Side dir, int timeout, bool invisible = false, int *seq = 0, long clientOrderID = -1, Mkt::Marking marking=Mkt::UNKWN, const char* placementAlgo=0 );
virtual Mkt::OrderResult placeBatsOrder ( int cid, int size, double price,
Mkt::Side dir, BatsRouteMod routing, int *seq = 0, long clientOrderID = -1, Mkt::Marking marking=Mkt::UNKWN );
/*
virtual bool reduceSize ( const Order *o, int newSize );
virtual bool reduceSize ( int id, int newSize );
virtual int replaceOrder ( const Order *o, int size, double price );
virtual int replaceOrder ( int id, int size, double price );
*/
virtual int position ( int cid );
virtual bool getPosition ( int cid ) { return getPos(cid, false); }
virtual bool getPositionAsync ( int cid ) { return getPos(cid, true); }
virtual bool getPositions ( ) { return getPos(false); }
virtual bool getPositionsAsync ( ) { return getPos(true); }
/** Get positions incrementally.
*
* Equivalent to getPositionAsync for [pos, end_pos)
* Optional bool output to indicate end_pos >= cidsize()
**/
virtual bool getPositionsIncr ( int pos, int end_pos, bool* done = 0 );
virtual int locates ( int cid );
virtual bool getLocates ( ) { return getLoc(false); }
virtual bool getLocatesAsync ( ) { return getLoc(true); }
virtual Order const *getOrder ( int id );
/* Set the PO+ flag. See config. */
void setPOPlus(bool use_po_plus) {
usepoplus = use_po_plus;
}
bool POPlusMode(){
return usepoplus;
}
/** Cancel an order.
*
* You can attempt to cancel any order that you have an update for, but
* you may not succeed, if that order is not currently live.
*/
virtual bool cancelOrder ( const Order *o );
virtual bool cancelOrder ( int id );
/** Cancel several orders, by cid, side, and price.
*
* Uses OrderManager's cancelBatch to cancel a set of orders based on
* one or more of cid, side, ECN, and price.
*/
virtual void cancelAll ( );
void cancelMarket ( int cid );
void cancelMarket ( int cid, Mkt::Side side );
void cancelMarket ( int cid, Mkt::Side side, double px );
void cancelMarket ( int cid, Mkt::Side side, int l );
void cancelMarket ( int cid, ECN::ECN ecn );
void cancelMarket ( int cid, ECN::ECN ecn, Mkt::Side side );
void cancelMarket ( int cid, ECN::ECN ecn, Mkt::Side side, double px );
void cancelMarket ( int cid, ECN::ECN ecn, Mkt::Side side, int l );
virtual int unreadData ( );
WakeUpdate wakeup_message ( );
bool advise_wakeup ( );
virtual ~DataManager ( );
// MarketBookListener interface function
void onBookChange ( int book_id, lib3::BookOrder *bo, lib3::QuoteReason qr, int delta, bool done );
// OMListener interface functions. These are also the listener callback functions
// that are invoked by OrderManager's functions, on receiving events)
void onSequence ( lib3::Order *lo ) { }
void onConfirm ( lib3::Order *lo );
void onFill ( lib3::Order *lo, lib3::FillDetails *fd );
void onCancel ( lib3::Order *lo, lib3::CancelDetails *cd );
void onReject ( lib3::Order *lo, lib3::RejectDetails *rd );
void onCancelReject ( lib3::Order *lo, lib3::CancelRejectDetails *rd );
void onBreak ( lib3::BreakDetails *bd );
void onPositionUpdate ( const char *acct, int cid, int pos );
void onGlobalMismatch ( const char *acct, int cid, int newpos, int oldpos );
void onPositionMismatch ( const char *acct, int cid, int newpos, int oldpos );
void onPositionMismatch ( const char *acct, int cid, int new_total, int new_ts,
int new_yst, int new_adj, int old_total, int old_ts,
int old_yst, int old_adj );
void onNoSequence ( lib3::Order *lo ) { }
void onNoConfirm ( lib3::Order *lo );
void onNoCancel ( lib3::Order *lo );
// EventListener interface function. Invokes the appropriate handler after creating
// the appropriate update object. Takes care of tape updates (TapeHandler), data
// updates (MarketHandler), and user message updates (UserMessageHandler).
int OnEvent ( Event *e );
// CIListener interface function
void CIChange ( CIndex *which );
};
struct Canceler : public std::binary_function<lib3::Order *, size_t, size_t> {
DataManager *dm;
Canceler ( DataManager *dm ) : dm(dm) { }
size_t operator() ( lib3::Order *o, size_t howmany ) {
return dm->cancelOrder(o->seqnum)? howmany+1 : howmany;
}
};
bool isInvisible(lib3::Order const *o);
#endif
| 38.113115 | 170 | 0.593875 | [
"object",
"vector"
] |
0f677d4301f32e56da63bd018d769d9554ae41c7 | 6,226 | h | C | bs_mtx/src/py_dens.h | bs-eagle/bs-eagle | b1017a4f6ac2dcafba2deafec84052ddde792671 | [
"BSD-3-Clause"
] | 7 | 2015-07-16T22:30:36.000Z | 2020-02-06T10:16:42.000Z | bs_mtx/src/py_dens.h | bs-eagle/bs-eagle | b1017a4f6ac2dcafba2deafec84052ddde792671 | [
"BSD-3-Clause"
] | null | null | null | bs_mtx/src/py_dens.h | bs-eagle/bs-eagle | b1017a4f6ac2dcafba2deafec84052ddde792671 | [
"BSD-3-Clause"
] | 3 | 2017-01-05T20:06:28.000Z | 2021-12-20T16:19:10.000Z | /**
* @file py_dens.h
* @brief Python interface for dens_matrix
* @date 2009-12-09
*/
#ifndef __PY_DENS_H
#define __PY_DENS_H
#include "dens_matrix_iface.h"
#include "dens_matrix.h"
#include "dens_matrix_tools.h"
#include "py_matrix_iface.h"
#include BS_FORCE_PLUGIN_IMPORT ()
#include "dummy_base.h"
#include "construct_python_object.h"
#include "make_me_happy.h"
#include BS_STOP_PLUGIN_IMPORT ()
#include "export_python_wrapper.h"
#ifdef BSPY_EXPORTING_PLUGIN
namespace blue_sky
{
namespace python
{
// Sergey Miryanov at 07.04.2008
// Refactored at 16.10.2009
// for casting into python from child classes to parent class
// we should export base class
#if 0
/**
* @brief python wrapper for dens_matrix_iface class
*
*/
CLASS_WRAPPER_T (3, (fp_vector_type, i_vector_type, fp_storage_vector_type), dens_matrix_iface, py_dens_matrix_iface)
{
public:
typedef matrix_iface <fp_vector_type, i_vector_type> matrix_t;
typedef dens_matrix_iface <fp_vector_type, i_vector_type, fp_storage_vector_type> dens_matrix_t;
typedef typename fp_vector_type::value_type t_double;
typedef typename fp_storage_vector_type::value_type t_float;
typedef typename i_vector_type::value_type t_long;
//typedef dens_matrix_iface <fp_vector_type, i_vector_type, fp_storage_vector_type> wrapped_t;
//typedef BOOST_PP_CAT (py_dens_matrix_iface, _base) <fp_vector_type, i_vector_type, fp_storage_vector_type> base_t;
public:
CLASS_WRAPPER_DECL_T (3, (fp_vector_type, i_vector_type, fp_storage_vector_type), py_dens_matrix_iface);
public:
WRAP_PURE_METHOD_R_CONST (matrix_vector_product, int, 2, (const fp_vector_type&, fp_vector_type&));
WRAP_PURE_METHOD_R_CONST (matrix_vector_product_t, int, 2, (const fp_vector_type&, fp_vector_type&));
WRAP_PURE_METHOD_R_CONST (calc_lin_comb, int, 5, (t_double, t_double, const fp_vector_type&, const fp_vector_type&, fp_vector_type&));
WRAP_PURE_METHOD_R_CONST (get_allocated_memory_in_mbytes, t_double, 0, (empty_arg__));
WRAP_PURE_METHOD_R_CONST (get_n_block_size, t_long, 0, (empty_arg__));
WRAP_PURE_METHOD_R_CONST (get_n_rows, t_long, 0, (empty_arg__));
WRAP_PURE_METHOD_R_CONST (get_n_cols, t_long, 0, (empty_arg__));
WRAP_PURE_METHOD_R_CONST (is_square, bool, 0, (empty_arg__));
WRAP_PURE_METHOD_CONST (init_vector, void, 1, (fp_vector_type &));
WRAP_PURE_METHOD_R_CONST (py_str, std::string, 0, (empty_arg__));
WRAP_PURE_METHOD_R (init_by_matrix, int, 1, (const dens_matrix_t&));
WRAP_PURE_METHOD_R (init, int, 3, (const t_long, const t_long, const t_long));
WRAP_PURE_METHOD_R (copy, int, 1, (const dens_matrix_t&));
WRAP_PURE_METHOD_R_CONST (get_calc_block_size, t_long, 0, (empty_arg__));
WRAP_PURE_METHOD (set_calc_block_size, void, 1, (const t_long));
WRAP_PURE_METHOD_R (get_values, fp_storage_vector_type&, 0, (empty_arg__));
WRAP_PURE_METHOD_R_CONST (get_values_const, const fp_storage_vector_type&, 0, (empty_arg__));
WRAP_PURE_METHOD_R_CONST (internal_check, int, 0, (empty_arg__));
};
#endif //0
PY_EXPORTER (py_dens_matrix_iface_exporter, py_matrix_iface_exporter)
.add_property ("calc_block_size",
&T::get_calc_block_size, &T::set_calc_block_size,
"Block size for calculation algorithms")
.def ("init_by_matrix",
&T::init_by_matrix,
args ("matrix"), "Initialize matrix by matrix :)")
.def ("init",
&T::init,
args ("n_rows", "n_cols", "calc_block_size"), "Initialize matrix")
.def ("copy",
&T::copy,
args ("matrix"), "Initialize matrix by matrix and copy all content")
.def ("get_values",
&T::get_values, //return_value_policy <reference_existing_object> (),
args (""), "Return reference to values vector")
//.def ("get_values_const",
// &T::get_values_const, return_value_policy <reference_existing_object> (),
// args (""), "Return const reference to values vector")
.def ("internal_check",
&T::internal_check,
args (""), "Return 0 if OK")
PY_EXPORTER_END;
PY_EXPORTER (py_matrix_dens_tools_exporter, default_exporter)
.def ("random_init",
&T::random_init,
args ("matrix", "n_rows", "n_cols", "calc_block_size", "value_dispertion"),
"Initialize matrix by random values")
PY_EXPORTER_END;
//! export matrices to python
void py_export_dens_matrices ();
} // namespace python
} // namespace blue_sky
#endif //
#endif //__PY_DENS_H
| 51.454545 | 144 | 0.527305 | [
"vector"
] |
0f6e7d323d5d0e079c19dc233ef55dc7f6abf84a | 13,002 | h | C | src/Benchmarks/SpMV/ReferenceFormats/Legacy/ChunkedEllpack.h | grinisrit/tnl-dev | 4403b2dca895e2c32636395d6f1c1210c7afcefd | [
"MIT"
] | null | null | null | src/Benchmarks/SpMV/ReferenceFormats/Legacy/ChunkedEllpack.h | grinisrit/tnl-dev | 4403b2dca895e2c32636395d6f1c1210c7afcefd | [
"MIT"
] | null | null | null | src/Benchmarks/SpMV/ReferenceFormats/Legacy/ChunkedEllpack.h | grinisrit/tnl-dev | 4403b2dca895e2c32636395d6f1c1210c7afcefd | [
"MIT"
] | null | null | null | /***
* Authors:
* Oberhuber Tomas, tomas.oberhuber@fjfi.cvut.cz
* Heller Martin
*
* The algorithm/method was published in:
* Heller M., Oberhuber T., Improved Row-grouped CSR Format for Storing of
* Sparse Matrices on GPU, Proceedings of Algoritmy 2012, 2012, Handlovičová A.,
* Minarechová Z. and Ševčovič D. (ed.), pages 282-290.
*/
#pragma once
#include <Benchmarks/SpMV/ReferenceFormats/Legacy/Sparse.h>
#include <TNL/Containers/Vector.h>
namespace TNL {
namespace Benchmarks {
namespace SpMV {
namespace ReferenceFormats {
namespace Legacy {
template< typename Device >
class ChunkedEllpackDeviceDependentCode;
template< typename Real, typename Device = Devices::Host, typename Index = int >
class ChunkedEllpack;
#ifdef HAVE_CUDA
#endif
template< typename IndexType >
struct tnlChunkedEllpackSliceInfo
{
IndexType size;
IndexType chunkSize;
IndexType firstRow;
IndexType pointer;
};
#ifdef HAVE_CUDA
template< typename Real,
typename Index,
typename Vector >
__global__ void ChunkedEllpackVectorProductCudaKernel( const ChunkedEllpack< Real, Devices::Cuda, Index >* matrix,
const Vector* inVector,
Vector* outVector,
int gridIdx );
#endif
template< typename Real, typename Device, typename Index >
class ChunkedEllpack : public Sparse< Real, Device, Index >
{
private:
// convenient template alias for controlling the selection of copy-assignment operator
template< typename Device2 >
using Enabler = std::enable_if< ! std::is_same< Device2, Device >::value >;
// friend class will be needed for templated assignment operators
template< typename Real2, typename Device2, typename Index2 >
friend class ChunkedEllpack;
public:
typedef Real RealType;
typedef Device DeviceType;
typedef Index IndexType;
typedef tnlChunkedEllpackSliceInfo< IndexType > ChunkedEllpackSliceInfo;
using RowsCapacitiesType = typename Sparse< RealType, DeviceType, IndexType >::RowsCapacitiesType;
using RowsCapacitiesTypeView = typename Sparse< RealType, DeviceType, IndexType >::RowsCapacitiesView;
using ConstRowsCapacitiesTypeView = typename Sparse< RealType, DeviceType, IndexType >::ConstRowsCapacitiesView;
typedef typename Sparse< RealType, DeviceType, IndexType >::ValuesVector ValuesVector;
typedef typename Sparse< RealType, DeviceType, IndexType >::ColumnIndexesVector ColumnIndexesVector;
typedef ChunkedEllpack< Real, Device, Index > ThisType;
typedef ChunkedEllpack< Real, Devices::Host, Index > HostType;
typedef ChunkedEllpack< Real, Devices::Cuda, Index > CudaType;
typedef Sparse< Real, Device, Index > BaseType;
typedef typename BaseType::MatrixRow MatrixRow;
typedef SparseRow< const RealType, const IndexType > ConstMatrixRow;
template< typename _Real = Real,
typename _Device = Device,
typename _Index = Index >
using Self = ChunkedEllpack< _Real, _Device, _Index >;
static constexpr bool isSymmetric() { return false; };
ChunkedEllpack();
static std::string getSerializationType();
std::string getSerializationTypeVirtual() const override;
void setDimensions( const IndexType rows,
const IndexType columns ) override;
void setCompressedRowLengths( ConstRowsCapacitiesTypeView rowLengths );
void setRowCapacities( ConstRowsCapacitiesTypeView rowLengths );
IndexType getRowLength( const IndexType row ) const;
__cuda_callable__
IndexType getRowLengthFast( const IndexType row ) const;
IndexType getNonZeroRowLength( const IndexType row ) const;
template< typename Real2, typename Device2, typename Index2 >
void setLike( const ChunkedEllpack< Real2, Device2, Index2 >& matrix );
void reset();
template< typename Real2, typename Device2, typename Index2 >
bool operator == ( const ChunkedEllpack< Real2, Device2, Index2 >& matrix ) const;
template< typename Real2, typename Device2, typename Index2 >
bool operator != ( const ChunkedEllpack< Real2, Device2, Index2 >& matrix ) const;
void setNumberOfChunksInSlice( const IndexType chunksInSlice );
__cuda_callable__
IndexType getNumberOfChunksInSlice() const;
void setDesiredChunkSize( const IndexType desiredChunkSize );
IndexType getDesiredChunkSize() const;
__cuda_callable__
IndexType getNumberOfSlices() const;
__cuda_callable__
bool setElementFast( const IndexType row,
const IndexType column,
const RealType& value );
bool setElement( const IndexType row,
const IndexType column,
const RealType& value );
__cuda_callable__
bool addElementFast( const IndexType row,
const IndexType column,
const RealType& value,
const RealType& thisElementMultiplicator = 1.0 );
bool addElement( const IndexType row,
const IndexType column,
const RealType& value,
const RealType& thisElementMultiplicator = 1.0 );
__cuda_callable__
bool setRowFast( const IndexType row,
const IndexType* columnIndexes,
const RealType* values,
const IndexType elements );
bool setRow( const IndexType row,
const IndexType* columnIndexes,
const RealType* values,
const IndexType elements );
__cuda_callable__
bool addRowFast( const IndexType row,
const IndexType* columns,
const RealType* values,
const IndexType numberOfElements,
const RealType& thisElementMultiplicator = 1.0 );
bool addRow( const IndexType row,
const IndexType* columns,
const RealType* values,
const IndexType numberOfElements,
const RealType& thisElementMultiplicator = 1.0 );
__cuda_callable__
RealType getElementFast( const IndexType row,
const IndexType column ) const;
RealType getElement( const IndexType row,
const IndexType column ) const;
__cuda_callable__
void getRowFast( const IndexType row,
IndexType* columns,
RealType* values ) const;
/*void getRow( const IndexType row,
IndexType* columns,
RealType* values ) const;*/
__cuda_callable__
MatrixRow getRow( const IndexType rowIndex );
__cuda_callable__
ConstMatrixRow getRow( const IndexType rowIndex ) const;
template< typename Vector >
__cuda_callable__
typename Vector::RealType rowVectorProduct( const IndexType row,
const Vector& vector ) const;
#ifdef HAVE_CUDA
template< typename InVector,
typename OutVector >
__device__ void computeSliceVectorProduct( const InVector* inVector,
OutVector* outVector,
int gridIdx ) const;
#endif
template< typename InVector,
typename OutVector >
void vectorProduct( const InVector& inVector,
OutVector& outVector ) const;
template< typename Real2, typename Index2 >
void addMatrix( const ChunkedEllpack< Real2, Device, Index2 >& matrix,
const RealType& matrixMultiplicator = 1.0,
const RealType& thisMatrixMultiplicator = 1.0 );
template< typename Real2, typename Index2 >
void getTransposition( const ChunkedEllpack< Real2, Device, Index2 >& matrix,
const RealType& matrixMultiplicator = 1.0 );
template< typename Vector1, typename Vector2 >
bool performSORIteration( const Vector1& b,
const IndexType row,
Vector2& x,
const RealType& omega = 1.0 ) const;
// copy assignment
ChunkedEllpack& operator=( const ChunkedEllpack& matrix );
// cross-device copy assignment
template< typename Real2, typename Device2, typename Index2,
typename = typename Enabler< Device2 >::type >
ChunkedEllpack& operator=( const ChunkedEllpack< Real2, Device2, Index2 >& matrix );
void save( File& file ) const override;
void load( File& file ) override;
void save( const String& fileName ) const;
void load( const String& fileName );
void print( std::ostream& str ) const override;
void printStructure( std::ostream& str,
const String& = "" ) const;
protected:
void resolveSliceSizes( ConstRowsCapacitiesTypeView rowLengths );
bool setSlice( ConstRowsCapacitiesTypeView rowLengths,
const IndexType sliceIdx,
IndexType& elementsToAllocation );
bool addElementToChunk( const IndexType sliceOffset,
const IndexType chunkIndex,
const IndexType chunkSize,
IndexType& column,
RealType& value,
RealType& thisElementMultiplicator );
__cuda_callable__
bool addElementToChunkFast( const IndexType sliceOffset,
const IndexType chunkIndex,
const IndexType chunkSize,
IndexType& column,
RealType& value,
RealType& thisElementMultiplicator );
__cuda_callable__
void setChunkFast( const IndexType sliceOffset,
const IndexType chunkIndex,
const IndexType chunkSize,
const IndexType* columnIndexes,
const RealType* values,
const IndexType elements );
void setChunk( const IndexType sliceOffset,
const IndexType chunkIndex,
const IndexType chunkSize,
const IndexType* columnIndexes,
const RealType* values,
const IndexType elements );
bool getElementInChunk( const IndexType sliceOffset,
const IndexType chunkIndex,
const IndexType chunkSize,
const IndexType column,
RealType& value ) const;
__cuda_callable__
bool getElementInChunkFast( const IndexType sliceOffset,
const IndexType chunkIndex,
const IndexType chunkSize,
const IndexType column,
RealType& value ) const;
void getChunk( const IndexType sliceOffset,
const IndexType chunkIndex,
const IndexType chunkSize,
IndexType* columns,
RealType* values ) const;
__cuda_callable__
void getChunkFast( const IndexType sliceOffset,
const IndexType chunkIndex,
const IndexType chunkSize,
IndexType* columns,
RealType* values ) const;
template< typename Vector >
__cuda_callable__
typename Vector::RealType chunkVectorProduct( const IndexType sliceOffset,
const IndexType chunkIndex,
const IndexType chunkSize,
const Vector& vector ) const;
IndexType chunksInSlice, desiredChunkSize;
Containers::Vector< Index, Device, Index > rowToChunkMapping, rowToSliceMapping, rowPointers;
Containers::Array< ChunkedEllpackSliceInfo, Device, Index > slices;
IndexType numberOfSlices;
typedef ChunkedEllpackDeviceDependentCode< DeviceType > DeviceDependentCode;
friend class ChunkedEllpackDeviceDependentCode< DeviceType >;
friend class ChunkedEllpack< RealType, Devices::Host, IndexType >;
friend class ChunkedEllpack< RealType, Devices::Cuda, IndexType >;
#ifdef HAVE_CUDA
template< typename Vector >
friend void ChunkedEllpackVectorProductCudaKernel( const ChunkedEllpack< Real, Devices::Cuda, Index >* matrix,
const Vector* inVector,
Vector* outVector,
int gridIdx );
#endif
};
} //namespace Legacy
} //namespace ReferenceFormats
} //namespace SpMV
} //namespace Benchmarks
} // namespace TNL
#include <Benchmarks/SpMV/ReferenceFormats/Legacy/ChunkedEllpack_impl.h>
| 36.318436 | 115 | 0.621058 | [
"vector"
] |
66798f576b13165e0fc3f5f98127de7d623975d2 | 461 | h | C | kem/kem_hqc128_1/ref/hqc.h | scarv/pq-riscv | 7372af824abe4a71ca6745adc21ddcc57527b0b5 | [
"OpenSSL"
] | 1 | 2019-05-02T17:07:19.000Z | 2019-05-02T17:07:19.000Z | kem/kem_hqc128_1/ref/hqc.h | scarv/pq-riscv | 7372af824abe4a71ca6745adc21ddcc57527b0b5 | [
"OpenSSL"
] | null | null | null | kem/kem_hqc128_1/ref/hqc.h | scarv/pq-riscv | 7372af824abe4a71ca6745adc21ddcc57527b0b5 | [
"OpenSSL"
] | null | null | null | /**
* \file hqc.h
* \brief Functions of the HQC_PKE IND_CPA scheme
*/
#ifndef HQC_H
#define HQC_H
#include "parameters.h"
#include "vector.h"
#include "tensor.h"
#include "parsing.h"
#include "gf2x.h"
void hqc_pke_keygen(unsigned char* pk, unsigned char* sk);
void hqc_pke_encrypt(uint8_t* u, uint8_t* v, uint8_t* m, unsigned char* theta, const unsigned char* pk);
void hqc_pke_decrypt(uint8_t* m, uint8_t* u, uint8_t* v, const unsigned char* sk);
#endif | 24.263158 | 104 | 0.724512 | [
"vector"
] |
6688234802da50ed5ea433a6742feb945e9e0820 | 7,435 | h | C | Plugins/EditorScriptingTools/Source/EditorScriptingTools/Private/EditorScriptingToolsCommon/LevelEditorToolBase.h | Ryan-DowlingSoka/UE4-EditorScriptingToolsPlugin | 999cee0465ce47e658c0e5403a1ea0909c84bf2d | [
"MIT"
] | null | null | null | Plugins/EditorScriptingTools/Source/EditorScriptingTools/Private/EditorScriptingToolsCommon/LevelEditorToolBase.h | Ryan-DowlingSoka/UE4-EditorScriptingToolsPlugin | 999cee0465ce47e658c0e5403a1ea0909c84bf2d | [
"MIT"
] | null | null | null | Plugins/EditorScriptingTools/Source/EditorScriptingTools/Private/EditorScriptingToolsCommon/LevelEditorToolBase.h | Ryan-DowlingSoka/UE4-EditorScriptingToolsPlugin | 999cee0465ce47e658c0e5403a1ea0909c84bf2d | [
"MIT"
] | null | null | null | //====================== Editor Scripting Tools ===========================//
// Copyright 2020 Elhoussine Mehnik (Mhousse1247). All Rights Reserved.
//====================== http://ue4resources.com/ ========================//
#pragma once
#include "CoreMinimal.h"
#include "UObject/ObjectMacros.h"
#include "UObject/Object.h"
#include "UObject/ScriptMacros.h"
#include "Kismet/BlueprintFunctionLibrary.h"
#include "EditorScriptingToolsTypes.h"
#include "EditorTypesWrapperTypes.h"
#include "ILevelEditingContext.h"
#include "LevelEditorToolBase.generated.h"
class UEditorUserDefinedActions;
class UTexture2D;
class AActor;
class USplineComponent;
class UEditorUserWidget;
UCLASS(Abstract)
class ULevelEditorToolBase : public UObject, public ILevelEditingContext
{
GENERATED_UCLASS_BODY()
public:
//~ Begin UObject interface
virtual class UWorld* GetWorld() const final;
//~ End UObject interface
//~ Begin ILevelEditingContext interface
virtual ELevelEditingContextType GetLevelEditingContext() override { return ELevelEditingContextType::Invalid; }
virtual const FDrawPrimitivesContext& GetDrawPrimitivesContext() override { return FDrawPrimitivesContext::InvalidContext; }
virtual const FDrawHUDContext& GetDrawHUDContext() override { return FDrawHUDContext::InvalidContext; }
//~ End UObject interface
//~ Level Viewport Primitives Drawing *****************************************************************************************************************************************/
UFUNCTION(BlueprintCallable, Category = "LevelEditingViewport|DrawPrimitives", meta = (HideSelfPin = "true"))
void DrawPoint(FDummyStruct DrawPrimitivesContext, FVector Position, FLinearColor Color = FLinearColor::White, float PointSize = 0.0f, EDepthPriorityGroup DepthPriorityGroup = EDepthPriorityGroup::World);
UFUNCTION(BlueprintCallable, Category = "LevelEditingViewport|DrawPrimitives", meta = (HideSelfPin = "true"))
void DrawLine(FDummyStruct DrawPrimitivesContext, FVector Start, FVector End, FLinearColor Color = FLinearColor::White, EDepthPriorityGroup DepthPriorityGroup = EDepthPriorityGroup::World, float Thickness = 0.0f, float DepthBias = 0.0f);
UFUNCTION(BlueprintCallable, Category = "LevelEditingViewport|DrawPrimitives", meta = (HideSelfPin = "true"))
void DrawTriangle(FDummyStruct DrawPrimitivesContext, FVector PointA, FVector PointB, FVector PointC, FLinearColor Color = FLinearColor::White, bool bDrawLines = false, UMaterialInterface* Material = nullptr, EDepthPriorityGroup DepthPriorityGroup = EDepthPriorityGroup::World, bool bDisableBackfaceCulling = false, bool bReceivesDecals = false);
UFUNCTION(BlueprintCallable, Category = "LevelEditingViewport|DrawPrimitives", meta = (HideSelfPin = "true"))
void DrawSphere(FDummyStruct DrawPrimitivesContext, FVector Center, float Radius = 50.0f, int32 NumSides = 16, int32 NumRings = 16, UMaterialInterface* Material = nullptr, EDepthPriorityGroup DepthPriorityGroup = EDepthPriorityGroup::World, bool bDisableBackfaceCulling = false);
UFUNCTION(BlueprintCallable, Category = "LevelEditingViewport|DrawPrimitives", meta = (HideSelfPin = "true"))
void DrawWireSphere(FDummyStruct DrawPrimitivesContext, FVector Center, FLinearColor Color = FLinearColor::White, float Radius = 50.0f, int32 NumSides = 16, EDepthPriorityGroup DepthPriority = EDepthPriorityGroup::World, float Thickness = 0.0f, float DepthBias = 0.0f);
UFUNCTION(BlueprintCallable, Category = "LevelEditingViewport|DrawPrimitives", meta = (HideSelfPin = "true"))
void DrawBox(FDummyStruct DrawPrimitivesContext, FTransform Transform, FVector Extent = FVector(50.0f), UMaterialInterface* Material = nullptr, EDepthPriorityGroup DepthPriority = EDepthPriorityGroup::World);
UFUNCTION(BlueprintCallable, Category = "LevelEditingViewport|DrawPrimitives", meta = (HideSelfPin = "true"))
void DrawWireBox(FDummyStruct DrawPrimitivesContext, FTransform Transform, FVector Extent = FVector(50.0f), FLinearColor Color = FLinearColor::White, EDepthPriorityGroup DepthPriority = EDepthPriorityGroup::World, float Thickness = 0.0f, float DepthBias = 0.0f);
UFUNCTION(BlueprintCallable, Category = "LevelEditingViewport|DrawPrimitives", meta = (HideSelfPin = "true"))
void DrawFlatArrow(FDummyStruct DrawPrimitivesContext, FVector Location, FVector XAxis = FVector(1, 0, 0), FVector YAxis = FVector(0, 1, 0), FLinearColor Color = FLinearColor::White, float Length = 1.0f, int32 Width = 1, UMaterialInterface* Material = nullptr, EDepthPriorityGroup DepthPriority = EDepthPriorityGroup::World, float Thickness = 0.0f);
UFUNCTION(BlueprintCallable, Category = "LevelEditingViewport|DrawPrimitives", meta = (HideSelfPin = "true"))
void DrawSpline(FDummyStruct DrawPrimitivesContext, USplineComponent* SplineComponent, FLinearColor LineColor = FLinearColor::White, EDepthPriorityGroup DepthPriorityGroup = EDepthPriorityGroup::World);
//~ Level Viewport Canvas Drawing ********************************************************************************************************************************************/
/**
* Draws a string on the HUD.
* @param Text String to draw
* @param TextColor Color to draw string
* @param ViewportX Screen-space X coordinate of upper left corner of the string.
* @param ViewportY Screen-space Y coordinate of upper left corner of the string.
* @param Font Font to draw text. If NULL, default font is chosen.
* @param TextScale Scale multiplier to control size of the text.
*/
UFUNCTION(BlueprintCallable, Category = "LevelEditingViewport|HUD", meta = (TextColor = "(R=0,G=0,B=0,A=1)"), meta = (HideSelfPin = "true"))
void DrawSimpleText(FDummyStruct DrawHUDContext, const FString& Text, FLinearColor TextColor, float ViewportX, float ViewportY, UFont* Font = nullptr, float TextScale = 1.f);
/**
* Draws a 2D line on the HUD.
* @param StartScreenX Screen-space X coordinate of start of the line.
* @param StartScreenY Screen-space Y coordinate of start of the line.
* @param EndScreenX Screen-space X coordinate of end of the line.
* @param EndScreenY Screen-space Y coordinate of end of the line.
* @param LineColor Color to draw line
* @param LineThickness Thickness of the line to draw
*/
UFUNCTION(BlueprintCallable, Category = "LevelEditingViewport|HUD", meta = (LineColor = "(R=0,G=0,B=0,A=1)"), DisplayName = "Draw Line", meta = (HideSelfPin = "true"))
void DrawCanvasLine(FDummyStruct DrawHUDContext, FVector2D LineStart, FVector2D LineEnd, FLinearColor LineColor, float LineThickness = 0.f);
/**
* Draws a screen space bounding box around the specified actor
*
* @param Actor Actor to draw a bounding box for
* @param Color Color of bounding box
* @param bDrawBracket True to draw a bracket, otherwise a box will be rendered
* @param LabelText Optional label text to draw
*/
UFUNCTION(BlueprintCallable, Category = "LevelEditingViewport|HUD", meta = (Color = "(R=0,G=0,B=0,A=1)"), DisplayName = "Draw Actor Screen Space Bounding Box", meta = (HideSelfPin = "true"))
void DrawActorScreenSpaceBoundingBox(FDummyStruct DrawHUDContext, AActor* Actor, FLinearColor Color, const bool bDrawBracket, FString LabelText = TEXT(""));
/** Returns the DPI scale factor of the native window */
UFUNCTION(BlueprintPure, Category = "LevelEditingViewport|HUD", meta = (HideSelfPin = "true"))
float GetCanvasDPIScale(FDummyStruct DrawHUDContext);
};
| 64.094828 | 351 | 0.739341 | [
"object",
"transform"
] |
6690c8644f60dfa5b2a168b2d0b65673cfda9e4f | 436 | h | C | Include/ObjectFile.h | MohamedBakrAli/SIC-Assembler | d6d30974303f2e4ba9a680f43aeecce73ba48831 | [
"MIT"
] | null | null | null | Include/ObjectFile.h | MohamedBakrAli/SIC-Assembler | d6d30974303f2e4ba9a680f43aeecce73ba48831 | [
"MIT"
] | null | null | null | Include/ObjectFile.h | MohamedBakrAli/SIC-Assembler | d6d30974303f2e4ba9a680f43aeecce73ba48831 | [
"MIT"
] | null | null | null | #ifndef OBJECTFILE_H
#define OBJECTFILE_H
#include <string>
#include <vector>
#include <fstream>
using namespace std;
class ObjectFile
{
public:
ObjectFile();
void WriteFile(long progStart,long progLength,string progEnd,
ofstream &objectfileAddress, vector<string> records,string name);
virtual ~ObjectFile();
protected:
private:
};
#endif // OBJECTFILE_H
| 21.8 | 89 | 0.644495 | [
"vector"
] |
66a921537f75461a9373aa007c2481195419fdb6 | 939 | h | C | OpenShop/BFJSONSerializing.h | aequasi/openshop.io-ios | 88b8285fb9a76266068d9f7fecb43eeca19959c2 | [
"MIT"
] | 418 | 2016-03-22T07:50:49.000Z | 2022-03-04T21:47:50.000Z | OpenShop/BFJSONSerializing.h | aequasi/openshop.io-ios | 88b8285fb9a76266068d9f7fecb43eeca19959c2 | [
"MIT"
] | 26 | 2016-05-24T11:50:45.000Z | 2019-03-03T07:50:04.000Z | OpenShop/BFJSONSerializing.h | aequasi/openshop.io-ios | 88b8285fb9a76266068d9f7fecb43eeca19959c2 | [
"MIT"
] | 215 | 2016-04-24T17:08:31.000Z | 2022-02-15T01:50:31.000Z | //
// BFJSONSerializing.h
// OpenShop
//
// Created by Jirka Apps
// Copyright (c) 2015 Business Factory. All rights reserved.
//
#import "Mantle.h"
NS_ASSUME_NONNULL_BEGIN
/**
* `BFJSONSerializing` protocol extends `MTLJSONSerializing` protocol with method
* to parse a JSON dictionary into an existing model object.
*/
@protocol BFJSONSerializing <MTLJSONSerializing>
/**
* Parses JSON dictionary into an existing model object.
*
* @param JSONDictionary A dictionary representing JSON data. This should match the
* format returned by NSJSONSerialization.
* @param error An error that might occur during parsing or merging data to an existing
* instance of calling model class.
* @return TRUE if an error occured, else FALSE.
*/
- (BOOL)updateWithJSONDictionary:(NSDictionary *)JSONDictionary error:( NSError * _Nullable __autoreleasing* _Nullable)error;
@end
NS_ASSUME_NONNULL_END
| 28.454545 | 125 | 0.735889 | [
"object",
"model"
] |
66aeca934ee441b84dbcfeb1e6b047313344b45e | 4,830 | h | C | liberty/include/liberty/CodeGen/Preprocess.h | PrincetonUniversity/cpf | 68c5b39c92b5eb37e416dd0cf59e575ee5ee2643 | [
"MIT"
] | 18 | 2020-08-14T21:19:59.000Z | 2022-02-22T12:43:52.000Z | liberty/include/liberty/CodeGen/Preprocess.h | PrincetonUniversity/cpf | 68c5b39c92b5eb37e416dd0cf59e575ee5ee2643 | [
"MIT"
] | 23 | 2020-08-17T21:04:36.000Z | 2022-03-02T19:29:27.000Z | liberty/include/liberty/CodeGen/Preprocess.h | PrincetonUniversity/cpf | 68c5b39c92b5eb37e416dd0cf59e575ee5ee2643 | [
"MIT"
] | 2 | 2020-09-17T17:25:19.000Z | 2021-05-21T11:21:43.000Z | // Modifies the code before parallelization.
// - Duplicate functions so that there are
// no side entrances to the parallel region
// - Update the parallel region so that live-out
// register values are saved to a (private) memory
// object
// - Create a recovery function
#ifndef LLVM_LIBERTY_SPECPRIV_PREPROCESS_H
#define LLVM_LIBERTY_SPECPRIV_PREPROCESS_H
#include "llvm/Pass.h"
#include "llvm/Analysis/LoopInfo.h"
#include "scaf/Utilities/InstInsertPt.h"
#include "liberty/Speculation/Classify.h"
#include "liberty/Speculation/Recovery.h"
#include "liberty/CodeGen/RoI.h"
#include "liberty/Redux/Reduction.h"
#include "PDG.hpp"
#include <set>
#include <unordered_set>
#include <unordered_map>
namespace liberty {
namespace SpecPriv {
using namespace llvm;
struct Preprocess : public ModulePass {
static char ID;
Preprocess() : ModulePass(ID), normalCount(0), localCount(0), killCount(0),
predCount(0), privateerCount(0), sharedCount(0) {}
void getAnalysisUsage(AnalysisUsage &au) const;
bool runOnModule(Module &module);
Recovery &getRecovery() { return recovery; }
const RecoveryFunction &getRecoveryFunction(Loop *loop) const;
RoI &getRoI() { return roi; }
const RoI &getRoI() const { return roi; }
void addToLPS(Instruction *nI, Instruction *gravity,
bool forceReplication = false);
void replaceInLPS(Instruction *nI, Instruction *oI);
void getExecutingStages(Instruction *inst, std::vector<unsigned> &stages);
bool ifI2IsInI1IsIn(Instruction *i1, Instruction *i2);
void assert_strategies_consistent_with_ir();
void replaceLiveOutUsage(Instruction *def, unsigned i, Loop *loop,
StringRef name, Instruction *object, bool redux);
std::unordered_set<const Instruction *> *
getSelectedCtrlSpecDeps(const BasicBlock *loopHeader) {
if (selectedCtrlSpecDeps.count(loopHeader))
return &selectedCtrlSpecDeps[loopHeader];
else
return nullptr;
}
std::unordered_map<const BasicBlock *, std::unordered_set<const LoadInst *>> *
getSelectedPrivateSpecLoads() {
return &selectedPrivateSpecLoads;
}
std::unordered_set<const Value *> *
getSelectedLoadedValuePreds(const BasicBlock *loopHeader) {
if (selectedLoadedValuePreds.count(loopHeader))
return &selectedLoadedValuePreds[loopHeader];
else
return nullptr;
}
bool isSeparationSpecUsed(BasicBlock *loopHeader) {
return separationSpecUsed.count(loopHeader);
}
bool isSpecUsed(BasicBlock *loopHeader) const {
return specUsed.count(loopHeader);
}
bool isCheckpointingNeeded(BasicBlock *loopHeader) const {
return checkpointNeeded.count(loopHeader);
}
InstInsertPt getInitFcn() const {
return initFcn;
}
InstInsertPt getFiniFcn() const { return finiFcn; }
private:
typedef std::set<const Value *> VSet;
RoI roi;
Module *mod;
Recovery recovery;
Type *voidty, *voidptr;
IntegerType *u8, *u16, *u32, *u64;
FunctionType *fv2v;
InstInsertPt initFcn, finiFcn;
std::vector<Loop *> loops;
std::unordered_map<const BasicBlock *, std::unordered_set<const Instruction *>>
selectedCtrlSpecDeps;
std::unordered_map<const BasicBlock *, std::unordered_set<const LoadInst *>>
selectedPrivateSpecLoads;
std::unordered_map<const BasicBlock *, std::unordered_set<const Value *>>
selectedLoadedValuePreds;
std::unordered_set<const BasicBlock *> separationSpecUsed;
std::unordered_set<const BasicBlock *> specUsed;
std::unordered_set<const BasicBlock *> checkpointNeeded;
std::unordered_set<const Instruction *> reduxV;
std::unordered_map<const Instruction *, Reduction::ReduxInfo> redux2Info;
std::unordered_map<const BasicBlock *, const Instruction *> reduxUpdateInst;
const PHINode *indVarPhi;
// collect all the AUs that appeared in various types of selected
// privitization remedies
HeapAssignment::AUSet normalPrivAUs;
//HeapAssignment::AUSet localPrivAUs;
HeapAssignment::AUSet killPrivAUs;
HeapAssignment::AUSet predPrivAUs;
HeapAssignment::AUSet privateerPrivAUs;
uint64_t normalCount;
uint64_t localCount;
uint64_t killCount;
uint64_t predCount;
uint64_t privateerCount;
uint64_t sharedCount;
void init(ModuleLoops &mloops);
bool fixStaticContexts();
bool demoteLiveOutsAndPhis(Loop *loop, LiveoutStructure &liveouts,
ModuleLoops &mloops);
void moveStackLocals(HeapAssignment &asgn, const Loop *L);
void moveLocalPrivs(HeapAssignment &asgn);
void moveKillPrivs(HeapAssignment &asgn);
uint64_t collectRelevantAUs(const Value *ptr, const Read &spresults,
Ctx *loop_ctx, HeapAssignment::AUSet &relAUs);
bool addInitializationFunction();
bool addFinalizationFunction();
};
} // namespace SpecPriv
} // namespace liberty
#endif
| 30.764331 | 81 | 0.736439 | [
"object",
"vector"
] |
66afe62e7103b52fe913b63dbf5448e3798ac8cd | 16,517 | c | C | v3d_main/common_lib/src_packages/mylib_tiff/hash.c | lens-biophotonics/v3d_external | 44ff3b60a297a96eaa77ca092e0de9af5c990ed3 | [
"MIT"
] | 39 | 2015-05-10T23:23:03.000Z | 2022-01-26T01:31:30.000Z | v3d_main/common_lib/src_packages/mylib_tiff/hash.c | lens-biophotonics/v3d_external | 44ff3b60a297a96eaa77ca092e0de9af5c990ed3 | [
"MIT"
] | 13 | 2016-03-04T05:29:23.000Z | 2021-02-07T01:11:10.000Z | v3d_main/common_lib/src_packages/mylib_tiff/hash.c | lens-biophotonics/v3d_external | 44ff3b60a297a96eaa77ca092e0de9af5c990ed3 | [
"MIT"
] | 44 | 2015-11-11T07:30:59.000Z | 2021-12-26T16:41:21.000Z | /*****************************************************************************************\
* *
* Hash Table data abstraction. *
* *
* Author: Gene Myers *
* Date : March 2006 *
* *
* (c) June 19, '09, Dr. Gene Myers and Howard Hughes Medical Institute *
* Copyrighted as per the full copy in the associated 'README' file *
* *
\*****************************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "utilities.h"
#include "hash.h"
/* Hash Table cell or entry, index is implicitly given
by position in table->cells array. */
typedef struct
{ int next; /* hash bucket link */
int text; /* offset of string corresponding to entry in string array */
void *user; /* user hook */
} Hash_Entry;
typedef struct
{ int size; /* size of hash vector */
int count; /* number of entries in hash table */
int strmax; /* current max of string array */
int strtop; /* current top of string array */
int *vector; /* hash vector */
Hash_Entry *cells; /* array where hash cells are allocated */
char *strings; /* array of entry strings */
} Table;
#define CELL_RATIO .4 // maximum ratio of cells to hash vector length
#define STRING_RATIO 6 // expected average entry length (including terminating 0-byte)
#define T(x) ((Table *) x)
/* Hash Table memory management */
static inline int table_vsize(Table *table)
{ return (sizeof(int)*table->size); }
static inline int table_csize(Table *table)
{ return (sizeof(Hash_Entry)*((int) (table->size*CELL_RATIO))); }
static inline int table_ssize(Table *table)
{ return (table->strmax); }
typedef struct __Table
{ struct __Table *next;
struct __Table *prev;
int refcnt;
int vsize;
int csize;
int ssize;
Table table;
} _Table;
static _Table *Free_Table_List = NULL;
static _Table *Use_Table_List = NULL;
static _Table Table_Proto;
static int Table_Offset = ((char *) &(Table_Proto.table)) - ((char *) &Table_Proto);
static int Table_Inuse = 0;
int Hash_Table_Refcount(Hash_Table *hash_table)
{ _Table *object = (_Table *) (((char *) hash_table) - Table_Offset);
return (object->refcnt);
}
static inline void allocate_table_vector(Table *table, int vsize, char *routine)
{ _Table *object = (_Table *) (((char *) table) - Table_Offset);
if (object->vsize < vsize)
{ table->vector = Guarded_Realloc(table->vector,vsize,routine);
object->vsize = vsize;
}
}
static inline int sizeof_table_vector(Table *table)
{ _Table *object = (_Table *) (((char *) table) - Table_Offset);
return (object->vsize);
}
static inline void allocate_table_cells(Table *table, int csize, char *routine)
{ _Table *object = (_Table *) (((char *) table) - Table_Offset);
if (object->csize < csize)
{ table->cells = Guarded_Realloc(table->cells,csize,routine);
object->csize = csize;
}
}
static inline int sizeof_table_cells(Table *table)
{ _Table *object = (_Table *) (((char *) table) - Table_Offset);
return (object->csize);
}
static inline void allocate_table_strings(Table *table, int ssize, char *routine)
{ _Table *object = (_Table *) (((char *) table) - Table_Offset);
if (object->ssize < ssize)
{ table->strings = Guarded_Realloc(table->strings,ssize,routine);
object->ssize = ssize;
}
}
static inline int sizeof_table_strings(Table *table)
{ _Table *object = (_Table *) (((char *) table) - Table_Offset);
return (object->ssize);
}
static inline Table *new_table(int vsize, int csize, int ssize, char *routine)
{ _Table *object;
Table *table;
if (Free_Table_List == NULL)
{ object = (_Table *) Guarded_Realloc(NULL,sizeof(_Table),routine);
table = &(object->table);
object->vsize = 0;
table->vector = NULL;
object->csize = 0;
table->cells = NULL;
object->ssize = 0;
table->strings = NULL;
}
else
{ object = Free_Table_List;
Free_Table_List = object->next;
table = &(object->table);
}
Table_Inuse += 1;
object->refcnt = 1;
if (Use_Table_List != NULL)
Use_Table_List->prev = object;
object->next = Use_Table_List;
object->prev = NULL;
Use_Table_List = object;
allocate_table_vector(table,vsize,routine);
allocate_table_cells(table,csize,routine);
allocate_table_strings(table,ssize,routine);
return (table);
}
static inline Table *copy_table(Table *table)
{ Table *copy = new_table(table_vsize(table),table_csize(table),table_ssize(table),"Copy_Hash_Table");
void *_vector = copy->vector;
void *_cells = copy->cells;
void *_strings = copy->strings;
*copy = *table;
copy->vector = _vector;
if (table->vector != NULL)
memcpy(copy->vector,table->vector,table_vsize(table));
copy->cells = _cells;
if (table->cells != NULL)
memcpy(copy->cells,table->cells,table_csize(table));
copy->strings = _strings;
if (table->strings != NULL)
memcpy(copy->strings,table->strings,table_ssize(table));
return (copy);
}
Hash_Table *Copy_Hash_Table(Hash_Table *hash_table)
{ return ((Hash_Table *) copy_table(((Table *) hash_table))); }
static inline void pack_table(Table *table)
{ _Table *object = (_Table *) (((char *) table) - Table_Offset);
if (object->vsize > table_vsize(table))
{ object->vsize = table_vsize(table);
if (object->vsize != 0)
table->vector = Guarded_Realloc(table->vector,
object->vsize,"Pack_Table");
else
{ free(table->vector);
table->vector = NULL;
}
}
if (object->csize > table_csize(table))
{ object->csize = table_csize(table);
if (object->csize != 0)
table->cells = Guarded_Realloc(table->cells,
object->csize,"Pack_Table");
else
{ free(table->cells);
table->cells = NULL;
}
}
if (object->ssize > table_ssize(table))
{ object->ssize = table_ssize(table);
if (object->ssize != 0)
table->strings = Guarded_Realloc(table->strings,
object->ssize,"Pack_Table");
else
{ free(table->strings);
table->strings = NULL;
}
}
}
Hash_Table *Pack_Hash_Table(Hash_Table *hash_table)
{ pack_table(((Table *) hash_table));
return (hash_table);
}
Hash_Table *Inc_Hash_Table(Hash_Table *hash_table)
{ _Table *object = (_Table *) (((char *) hash_table) - Table_Offset);
object->refcnt += 1;
return (hash_table);
}
static inline void free_table(Table *table)
{ _Table *object = (_Table *) (((char *) table) - Table_Offset);
if (--object->refcnt > 0) return;
if (object->refcnt < 0)
fprintf(stderr,"Warning: Freeing previously released Hash_Table\n");
if (object->prev != NULL)
object->prev->next = object->next;
else
Use_Table_List = object->next;
if (object->next != NULL)
object->next->prev = object->prev;
object->next = Free_Table_List;
Free_Table_List = object;
Table_Inuse -= 1;
}
void Free_Hash_Table(Hash_Table *hash_table)
{ free_table(((Table *) hash_table)); }
static inline void kill_table(Table *table)
{ _Table *object = (_Table *) (((char *) table) - Table_Offset);
if (--object->refcnt > 0) return;
if (object->refcnt < 0)
fprintf(stderr,"Warning: Killing previously released Hash_Table\n");
if (object->prev != NULL)
object->prev->next = object->next;
else
Use_Table_List = object->next;
if (object->next != NULL)
object->next->prev = object->prev;
if (object->ssize != 0)
free(table->strings);
if (object->csize != 0)
free(table->cells);
if (object->vsize != 0)
free(table->vector);
free(((char *) table) - Table_Offset);
Table_Inuse -= 1;
}
void Kill_Hash_Table(Hash_Table *hash_table)
{ kill_table(((Table *) hash_table)); }
static inline void reset_table()
{ _Table *object;
Table *table;
while (Free_Table_List != NULL)
{ object = Free_Table_List;
Free_Table_List = object->next;
table = &(object->table);
if (object->ssize != 0)
free(table->strings);
if (object->csize != 0)
free(table->cells);
if (object->vsize != 0)
free(table->vector);
free(object);
}
}
void Reset_Hash_Table()
{ reset_table(); }
int Hash_Table_Usage()
{ return (Table_Inuse); }
void Hash_Table_List(void (*handler)(Hash_Table *))
{ _Table *a, *b;
for (a = Use_Table_List; a != NULL; a = b)
{ b = a->next;
handler((Hash_Table *) &(a->table));
}
}
static inline Table *read_table(FILE *input)
{ char name[10];
fread(name,10,1,input);
if (strncmp(name,"Hash_Table",10) != 0)
return (NULL);
Table *obj = new_table(0,0,0,"Read_Hash_Table");
fread(obj,sizeof(Table),1,input);
obj->vector = NULL;
if (table_vsize(obj) != 0)
{ allocate_table_vector(obj,table_vsize(obj),"Read_Hash_Table");
fread(obj->vector,table_vsize(obj),1,input);
}
obj->cells = NULL;
if (table_csize(obj) != 0)
{ allocate_table_cells(obj,table_csize(obj),"Read_Hash_Table");
fread(obj->cells,table_csize(obj),1,input);
}
obj->strings = NULL;
if (table_ssize(obj) != 0)
{ allocate_table_strings(obj,table_ssize(obj),"Read_Hash_Table");
fread(obj->strings,table_ssize(obj),1,input);
}
return (obj);
}
Hash_Table *Read_Hash_Table(FILE *input)
{ return ((Hash_Table *) read_table(input)); }
static inline void write_table(Table *table, FILE *output)
{ fwrite("Hash_Table",10,1,output);
fwrite(table,sizeof(Table),1,output);
if (table_vsize(table) != 0)
fwrite(table->vector,table_vsize(table),1,output);
if (table_csize(table) != 0)
fwrite(table->cells,table_csize(table),1,output);
if (table_ssize(table) != 0)
fwrite(table->strings,table_ssize(table),1,output);
}
void Write_Hash_Table(Hash_Table *hash_table, FILE *output)
{ write_table(((Table *) hash_table),output); }
/* Hash key for a string is xor of each consecutive 3 bytes. */
static int hash_key(char *entry)
{ int i, key, glob;
key = 0;
glob = 0;
for (i = 0; entry[i] != '\0'; i++)
{ glob = (glob << 8) | entry[i];
if (i % 3 == 2)
{ key = key ^ glob;
glob = 0;
}
}
if (i % 3 != 0)
key = key ^ glob;
return (key);
}
/* Find the next prime larger than size. Variant of Sieve of Arosthenes: First
time its called computes all primes between 2 and 0xFFFF using the basic
sieve algorithm. With these one builds a sieve for the 0xFFFF number from
size upwards, using the primes to x-out sieve elements as being non-prime.
This will work up to 0xFFFFFFF, beyond the largest integer, because it suffices
to sieve agains the square root of the large number in the sieve. */
static int next_prime(int size)
{ static int firstime = 1;
static int Prime[0x4000], Ptop;
static unsigned char Sieve[0x10000];
int p, q, n;
if (firstime)
{ firstime = 0;
Ptop = 0;
for (p = 2; p < 0x10000; p++)
Sieve[p] = 1;
for (p = 2; p < 0x10000; p++)
if (Sieve[p])
{ for (q = 2*p; q < 0x10000; q += p)
Sieve[q] = 0;
Prime[Ptop++] = p;
}
}
while (size < 0x8FFEFFFF)
{ for (q = 0; q < 0x10000; q++)
Sieve[q] = 1;
for (p = 0; p < Ptop; p++)
{ n = Prime[p];
if (n >= size) break;
for (q = ((size-1)/n+1)*n - size; q < 0x10000; q += n)
Sieve[q] = 0;
}
for (q = 0; q < 0x10000; q++)
if (Sieve[q])
return (size+q);
size += 0x10000;
}
return (size);
}
/* Diagnostic output of hash table contents. */
void Print_Hash_Table(FILE *file, Hash_Table *hash_table)
{ Table *table = T(hash_table);
int *vector = table->vector;
Hash_Entry *cells = table->cells;
int i, c;
fprintf(file,"\nHASH TABLE (%d,%d):\n",table->count,table->size);
for (i = 0; i < table->size; i++)
if ((c = vector[i]) >= 0)
{ fprintf(file," Vector %4d:\n",i);
for (; c >= 0; c = cells[c].next)
fprintf(file," %4d: '%s'\n",c,table->strings + cells[c].text);
}
}
Hash_Table *G(New_Hash_Table)(int size)
{ Table *table;
int i, smax;
size = next_prime((int) (size/CELL_RATIO));
smax = size*STRING_RATIO;
table = new_table(sizeof(int)*size,sizeof(Hash_Entry)*((int) (size*CELL_RATIO)),smax,
"New_Hash_Table");
table->count = 0;
table->size = size;
table->strmax = smax;
table->strtop = 0;
for (i = 0; i < size; i++)
table->vector[i] = -1;
return ((Hash_Table *) table);
}
/* Double the size of a hash table
while preserving its contents. */
static Table *double_hash_table(Table *table)
{ int size, smax;
size = next_prime(2*table->size);
smax = 2.1 * table->strtop + 1000;
allocate_table_vector(table,sizeof(int)*size,"Hash_Add");
allocate_table_cells(table,sizeof(Hash_Entry)*((int) (size*CELL_RATIO)),"Hash_Add");
allocate_table_strings(table,smax,"Hash_Add");
{ int *vector = table->vector;
Hash_Entry *cells = table->cells;
int c;
table->size = size;
table->strmax = smax;
for (c = 0; c < size; c++)
vector[c] = -1;
for (c = 0; c < table->count; c++)
{ int key = hash_key(table->strings + cells[c].text) % size;
cells[c].next = vector[key];
vector[key] = c;
}
}
return (table);
}
/* Lookup string 'entry' in table 'table' and return its
unique nonnegative id, or -1 if it is not in the table. */
int Hash_Lookup(Hash_Table *hash_table, char *entry)
{ Table *table = T(hash_table);
int key, chain;
key = hash_key(entry) % table->size;
chain = table->vector[key];
while (chain >= 0)
{ if (strcmp(table->strings + table->cells[chain].text,entry) == 0)
return (chain);
chain = table->cells[chain].next;
}
return (-1);
}
/* Add string 'entry' in table 'table' and return its assigned
uniqe nonnegative id, or -1 if it is already in the table. */
int Hash_Add(Hash_Table *M(hash_table), char *entry)
{ Table *table = T(hash_table);
int key, chain, len;
key = hash_key(entry) % table->size;
chain = table->vector[key];
while (chain >= 0)
{ if (strcmp(table->strings + table->cells[chain].text,entry) == 0)
return (-1);
chain = table->cells[chain].next;
}
if (table->count+1 > table->size*CELL_RATIO)
{ table = double_hash_table(table);
key = hash_key(entry) % table->size;
}
chain = table->count;
table->cells[chain].next = table->vector[key];
table->vector[key] = chain;
len = strlen(entry) + 1;
if (table->strtop + len > table->strmax)
{ int size = table->size;
int smax = (table->strtop + len) * (CELL_RATIO * table->size / table->count) * 1.1 + 1000;
allocate_table_strings(table,smax,"Hash_Add");
table->strmax = smax;
}
strcpy(table->strings + table->strtop, entry);
table->cells[chain].text = table->strtop;
table->strtop += len;
return (table->count++);
}
/* Return the size of the hash table. */
int Get_Hash_Table_Size(Hash_Table *hash_table)
{ return (T(hash_table)->count); }
/* Return the string with unique id i in table. */
char *Get_Hash_String(Hash_Table *hash_table, int i)
{ return (T(hash_table)->strings + T(hash_table)->cells[i].text); }
/* Return a pointer to the user data field for unique id i in table. */
void **Get_Hash_User_Hook(Hash_Table *hash_table, int i)
{ return (& (T(hash_table)->cells[i].user)); }
/* Clear the contents of hash table, reseting it to be empty. */
void Clear_Hash_Table(Hash_Table *M(hash_table))
{ Table *table = T(hash_table);
int i;
table->count = 0;
table->strtop = 0;
for (i = 0; i < table->size; i++)
table->vector[i] = -1;
}
| 30.530499 | 102 | 0.589756 | [
"object",
"vector"
] |
66b688fc50752df49186724d9e94663e5aa0d5a1 | 544 | h | C | src/copper/Operator/OpTable.h | all-in-one-of/CopperFX | 9a50b69a57ebd6aa578d12456e34d792a7c51916 | [
"Unlicense"
] | null | null | null | src/copper/Operator/OpTable.h | all-in-one-of/CopperFX | 9a50b69a57ebd6aa578d12456e34d792a7c51916 | [
"Unlicense"
] | null | null | null | src/copper/Operator/OpTable.h | all-in-one-of/CopperFX | 9a50b69a57ebd6aa578d12456e34d792a7c51916 | [
"Unlicense"
] | null | null | null | #ifndef OP_TABLE_H
#define OP_TABLE_H
#include <vector>
#include <unordered_map>
#include "copper/Plugin/AbstractFactory.h"
#include "copper/Operator/OpBase.h"
namespace copper {
class OpNodeTemplate;
class OpTable {
public:
void registerOpNodeTemplate(OpNodeTemplate *op_template);
OpNodeTemplate *getOpNodeTemplate(const std::string &type_name);
const std::vector<std::string> registeredTypeNames() const;
private:
std::unordered_map<std::string, OpNodeTemplate* > _op_node_templates_by_type_name;
};
}
#endif // OP_TABLE_H | 20.923077 | 84 | 0.779412 | [
"vector"
] |
66d63b46c9df11a49889f9035ed6ded066c6536b | 1,326 | h | C | component/oai-smf/src/api-server/model/HsmfUpdatedData.h | kukkalli/oai-cn5g-fed | 15634fac935ac8671b61654bdf75bf8af07d3c3a | [
"Apache-2.0"
] | null | null | null | component/oai-smf/src/api-server/model/HsmfUpdatedData.h | kukkalli/oai-cn5g-fed | 15634fac935ac8671b61654bdf75bf8af07d3c3a | [
"Apache-2.0"
] | null | null | null | component/oai-smf/src/api-server/model/HsmfUpdatedData.h | kukkalli/oai-cn5g-fed | 15634fac935ac8671b61654bdf75bf8af07d3c3a | [
"Apache-2.0"
] | null | null | null | /**
* Nsmf_PDUSession
* SMF PDU Session Service. © 2019, 3GPP Organizational Partners (ARIB, ATIS,
* CCSA, ETSI, TSDSI, TTA, TTC). All rights reserved.
*
* The version of the OpenAPI document: 1.1.0.alpha-1
*
*
* NOTE: This class is auto generated by OpenAPI Generator
* (https://openapi-generator.tech). https://openapi-generator.tech Do not edit
* the class manually.
*/
/*
* HsmfUpdatedData.h
*
*
*/
#ifndef HsmfUpdatedData_H_
#define HsmfUpdatedData_H_
#include "RefToBinaryData.h"
#include <nlohmann/json.hpp>
namespace oai {
namespace smf_server {
namespace model {
/// <summary>
///
/// </summary>
class HsmfUpdatedData {
public:
HsmfUpdatedData();
virtual ~HsmfUpdatedData();
void validate();
/////////////////////////////////////////////
/// HsmfUpdatedData members
/// <summary>
///
/// </summary>
RefToBinaryData getN1SmInfoToUe() const;
void setN1SmInfoToUe(RefToBinaryData const& value);
bool n1SmInfoToUeIsSet() const;
void unsetN1SmInfoToUe();
friend void to_json(nlohmann::json& j, const HsmfUpdatedData& o);
friend void from_json(const nlohmann::json& j, HsmfUpdatedData& o);
protected:
RefToBinaryData m_N1SmInfoToUe;
bool m_N1SmInfoToUeIsSet;
};
} // namespace model
} // namespace smf_server
} // namespace oai
#endif /* HsmfUpdatedData_H_ */
| 21.047619 | 79 | 0.684012 | [
"model"
] |
66e86a693f2767db9c933c48795b796191a014b7 | 1,290 | h | C | Alchemy/Spell.h | Neko81795/CBREngine | 3ea100f09110d55fcbcadb23c246d47ed46c5121 | [
"CC-BY-4.0",
"MIT"
] | 2 | 2015-08-30T00:26:45.000Z | 2015-11-13T05:58:30.000Z | Alchemy/Spell.h | Neko81795/CBREngine | 3ea100f09110d55fcbcadb23c246d47ed46c5121 | [
"CC-BY-4.0",
"MIT"
] | 1 | 2015-11-25T06:28:13.000Z | 2015-11-25T06:30:32.000Z | Alchemy/Spell.h | Neko81795/CBREngine | 3ea100f09110d55fcbcadb23c246d47ed46c5121 | [
"CC-BY-4.0",
"MIT"
] | null | null | null | #ifndef SpellClass_H
#define SpellClass_H
#include <string>
#include <string.h>
#include "SpellData.h"
using namespace std;
namespace alchemy
{
class Spell
{
public:
//////////////////////////////
//Constructors and Destructors
//////////////////////////////
Spell();
Spell(string str);
~Spell();
//////////////////////////////
//Member Functions
//////////////////////////////
//Returns a value between 0 and 1 that indicates how valid the word string is.
double checkValidity(std::vector<std::string> &dictionary, int dictionarySize);
//Converts all of the characters in the string to uppercase or lowercase.
Spell& toUpper();
Spell& toLower();
//////////////////////////////
//Getters and Setters
//////////////////////////////
//returns the string entered.
string& getString();
//////////////////////////////
//Operator Overloads
//////////////////////////////
//Assingment operator
Spell& operator=(Spell& rhs);
Spell& operator=(string rhs);
//Allow for printing
friend ostream& operator<<(ostream& os, const Spell rhs);
private:
string spell_;
SpellData spellData_;
//////////////////////////////
//Private Member Functions
//////////////////////////////
};
}
#endif //SpellClass_H
| 19.253731 | 81 | 0.520155 | [
"vector"
] |
66ec8a3718cf751e88c859598d87adbcb1fb7ab9 | 2,795 | h | C | mcommon/math/rectstack.h | cmaughan/mgfx | 488453333f23b38b22ba06b984615a8069dadcbf | [
"MIT"
] | 36 | 2017-03-27T16:57:47.000Z | 2022-01-12T04:17:55.000Z | mcommon/math/rectstack.h | cmaughan/mgfx | 488453333f23b38b22ba06b984615a8069dadcbf | [
"MIT"
] | 5 | 2017-03-04T12:13:54.000Z | 2017-03-26T21:55:08.000Z | mcommon/math/rectstack.h | cmaughan/mgfx | 488453333f23b38b22ba06b984615a8069dadcbf | [
"MIT"
] | 7 | 2017-03-04T11:01:44.000Z | 2018-08-28T09:25:47.000Z | #pragma once
#include <vector>
#include <map>
namespace RectStackFlags
{
enum
{
FixedSize = (1 << 0)
};
}
struct RectStackItem
{
Rect4f rc; // Current position
float ratio; // Ratio
float fixedSize; // Preferred size
uint32_t flags; // Flags
std::shared_ptr<RectStack> spChildStack;
};
class RectStack
{
public:
RectStack(bool vertical)
: m_vertical(vertical)
{
}
uint32_t GetNumRectItems() const
{
return uint32_t(m_rects.size());
}
std::shared_ptr<RectStackItem> GetRectItem(uint32_t index) const
{
return m_rects[index];
}
void AddRectItem(std::shared_ptr<RectStackItem> pRC) { m_rects.push_back(pRC); };
void Layout(const Rect4f& boundary)
{
auto totalSize = (m_vertical) ? boundary.Height() : boundary.Width();
auto totalRatio = 0.0f;
for (auto& pRect : m_rects)
{
if (pRect->flags & RectStackFlags::FixedSize)
{
totalSize -= pRect->fixedSize;
}
else
{
totalRatio += pRect->ratio;
}
}
glm::vec2 current = boundary.TopLeft();
for (auto& pRect : m_rects)
{
pRect->rc.x = current.x;
pRect->rc.y = current.y;
if (pRect->flags & RectStackFlags::FixedSize)
{
if (m_vertical)
{
pRect->rc.w = pRect->fixedSize;
pRect->rc.z = boundary.Width();
}
else
{
pRect->rc.z = pRect->fixedSize;
pRect->rc.w = boundary.Height();
}
}
else
{
if (m_vertical)
{
pRect->rc.w = totalSize * (pRect->ratio / totalRatio);
pRect->rc.z = boundary.Width();
}
else
{
pRect->rc.z = totalSize * (pRect->ratio / totalRatio);
pRect->rc.w = boundary.Height();
}
}
if (m_vertical)
{
current.y = pRect->rc.Bottom();
current.x = boundary.Left();
}
else
{
current.x = pRect->rc.Right();
current.y = boundary.Top();
}
}
for (auto& pRect : m_rects)
{
if (pRect->spChildStack)
{
pRect->spChildStack->Layout(pRect->rc);
}
}
}
private:
std::vector<std::shared_ptr<RectStackItem>> m_rects;
bool m_vertical = true;
};
| 23.888889 | 85 | 0.442934 | [
"vector"
] |
66ecfce7b5ad9a778e5e854bc6f231cef6544069 | 174,590 | c | C | kernel/drivers/net/stack/xenomai-3.0.5/kernel/drivers/net/drivers/experimental/e1000/e1000_main.c | oPiZiL/xenomai-deb | 2d0ba1c0b19e482c3f77a80d08d7e34ff4a2f604 | [
"Apache-2.0"
] | 1 | 2019-10-12T01:38:30.000Z | 2019-10-12T01:38:30.000Z | kernel/drivers/net/stack/xenomai-3.0.5/kernel/drivers/net/drivers/experimental/e1000/e1000_main.c | oPiZiL/xenomai-deb | 2d0ba1c0b19e482c3f77a80d08d7e34ff4a2f604 | [
"Apache-2.0"
] | null | null | null | kernel/drivers/net/stack/xenomai-3.0.5/kernel/drivers/net/drivers/experimental/e1000/e1000_main.c | oPiZiL/xenomai-deb | 2d0ba1c0b19e482c3f77a80d08d7e34ff4a2f604 | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
Intel PRO/1000 Linux driver
Copyright(c) 1999 - 2008 Intel Corporation.
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope 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 St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Contact Information:
Linux NICS <linux.nics@intel.com>
e1000-devel Mailing List <e1000-devel@lists.sourceforge.net>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/vmalloc.h>
#include <linux/pagemap.h>
#include <linux/netdevice.h>
#include <linux/tcp.h>
#include <linux/ipv6.h>
// RTNET defines...
#ifdef NETIF_F_TSO
#undef NETIF_F_TSO
#endif
#ifdef NETIF_F_TSO6
#undef NETIF_F_TSO6
#endif
#ifdef NETIF_F_HW_VLAN_TX
#undef NETIF_F_HW_VLAN_TX
#endif
#ifdef CONFIG_E1000_NAPI
#undef CONFIG_E1000_NAPI
#endif
#ifdef MAX_SKB_FRAGS
#undef MAX_SKB_FRAGS
#endif
#ifndef CONFIG_E1000_DISABLE_PACKET_SPLIT
#define CONFIG_E1000_DISABLE_PACKET_SPLIT
#endif
#ifdef CONFIG_E1000_MQ
#undef CONFIG_E1000_MQ
#endif
#ifdef CONFIG_NET_POLL_CONTROLLER
#undef CONFIG_NET_POLL_CONTROLLER
#endif
#ifdef CONFIG_PM
#undef CONFIG_PM
#endif
#ifdef HAVE_PCI_ERS
#error "STOP it here"
#undef HAVE_PCI_ERS
#endif
#ifdef USE_REBOOT_NOTIFIER
#undef USE_REBOOT_NOTIFIER
#endif
#ifdef HAVE_TX_TIMEOUT
#undef HAVE_TX_TIMEOUT
#endif
#ifdef NETIF_F_TSO
#include <net/checksum.h>
#ifdef NETIF_F_TSO6
#include <net/ip6_checksum.h>
#endif
#endif
#ifdef SIOCGMIIPHY
#include <linux/mii.h>
#endif
#ifdef SIOCETHTOOL
#include <linux/ethtool.h>
#endif
#ifdef NETIF_F_HW_VLAN_TX
#include <linux/if_vlan.h>
#endif
#ifdef CONFIG_E1000_MQ
#include <linux/cpu.h>
#include <linux/smp.h>
#endif
#include "e1000.h"
#ifdef HAVE_PCI_ERS
#error "STOP it here"
#endif
char e1000_driver_name[MODULE_NAME_LEN] = "rt_e1000";
static char e1000_driver_string[] = "Intel(R) PRO/1000 Network Driver";
#ifdef CONFIG_E1000_NAPI
#define DRV_NAPI "-NAPI"
#else
#define DRV_NAPI
#endif
#define DRV_DEBUG
#define DRV_HW_PERF
/*
* Port to rtnet based on e1000 driver version 7.6.15.5 (22-Sep-2008 Mathias Koehrer)
*
* */
#define DRV_VERSION "7.6.15.5" DRV_NAPI DRV_DEBUG DRV_HW_PERF " ported to RTnet"
const char e1000_driver_version[] = DRV_VERSION;
static const char e1000_copyright[] = "Copyright (c) 1999-2008 Intel Corporation.";
// RTNET wrappers
#define kmalloc(a,b) rtdm_malloc(a)
#define vmalloc(a) rtdm_malloc(a)
#define kfree(a) rtdm_free(a)
#define vfree(a) rtdm_free(a)
#define skb_reserve(a,b) rtskb_reserve(a,b)
#define net_device rtnet_device
#define sk_buff rtskb
#define netdev_priv(a) a->priv
// ----------------------
/* e1000_pci_tbl - PCI Device ID Table
*
* Last entry must be all 0s
*
* Macro expands to...
* {PCI_DEVICE(PCI_VENDOR_ID_INTEL, device_id)}
*/
#define PCI_ID_LIST_PCI \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82542), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82543GC_FIBER), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82543GC_COPPER), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82544EI_COPPER), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82544EI_FIBER), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82544GC_COPPER), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82544GC_LOM), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82540EM), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82545EM_COPPER), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82546EB_COPPER), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82545EM_FIBER), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82546EB_FIBER), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82541EI), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82541ER_LOM), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82540EM_LOM), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82540EP_LOM), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82540EP), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82541EI_MOBILE), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82547EI), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82547EI_MOBILE), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82546EB_QUAD_COPPER), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82540EP_LP), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82545GM_COPPER), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82545GM_FIBER), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82545GM_SERDES), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82547GI), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82541GI), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82541GI_MOBILE), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82541ER), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82546GB_COPPER), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82546GB_FIBER), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82546GB_SERDES), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82541GI_LF), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82546GB_PCIE), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82546GB_QUAD_COPPER), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82546GB_QUAD_COPPER_KSP3)
#define PCI_ID_LIST_PCIE \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_ICH8_IGP_M_AMT), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_ICH8_IGP_AMT), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_ICH8_IGP_C), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_ICH8_IFE), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_ICH8_IGP_M), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82571EB_COPPER), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82571EB_FIBER), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82571EB_SERDES), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82572EI_COPPER), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82572EI_FIBER), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82572EI_SERDES), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82573E), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82573E_IAMT), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_80003ES2LAN_COPPER_DPT), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_80003ES2LAN_SERDES_DPT), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82573L), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82571EB_QUAD_COPPER), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82571EB_QUAD_FIBER), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82571EB_SERDES_DUAL), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82571EB_SERDES_QUAD), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82572EI), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_80003ES2LAN_COPPER_SPT), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_80003ES2LAN_SERDES_SPT), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82571EB_QUAD_COPPER_LP), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_82571PT_QUAD_COPPER), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_ICH8_IFE_GT), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_ICH8_IFE_G), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_ICH9_IGP_AMT), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_ICH9_IGP_C), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_ICH9_IFE), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_ICH9_IFE_G), \
INTEL_E1000_ETHERNET_DEVICE(E1000_DEV_ID_ICH9_IFE_GT)
static struct pci_device_id e1000_pci_tbl[] = {
PCI_ID_LIST_PCI,
PCI_ID_LIST_PCIE,
/* required last entry */
{0,}
};
MODULE_DEVICE_TABLE(pci, e1000_pci_tbl);
static struct pci_device_id e1000_pcipure_tbl[] = {
PCI_ID_LIST_PCI,
/* required last entry */
{0,}
};
static struct pci_device_id e1000_pcie_tbl[] = {
PCI_ID_LIST_PCIE,
/* required last entry */
{0,}
};
static int e1000_setup_tx_resources(struct e1000_adapter *adapter,
struct e1000_tx_ring *tx_ring);
static int e1000_setup_rx_resources(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring);
static void e1000_free_tx_resources(struct e1000_adapter *adapter,
struct e1000_tx_ring *tx_ring);
static void e1000_free_rx_resources(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring);
static int e1000_init_module(void);
static void e1000_exit_module(void);
static int e1000_probe(struct pci_dev *pdev, const struct pci_device_id *ent);
static void e1000_remove(struct pci_dev *pdev);
static int e1000_alloc_queues(struct e1000_adapter *adapter);
#ifdef CONFIG_E1000_MQ
static void e1000_setup_queue_mapping(struct e1000_adapter *adapter);
#endif
static int e1000_sw_init(struct e1000_adapter *adapter);
static int e1000_open(struct net_device *netdev);
static int e1000_close(struct net_device *netdev);
static void e1000_configure(struct e1000_adapter *adapter);
static void e1000_configure_tx(struct e1000_adapter *adapter);
static void e1000_configure_rx(struct e1000_adapter *adapter);
static void e1000_setup_rctl(struct e1000_adapter *adapter);
static void e1000_clean_all_tx_rings(struct e1000_adapter *adapter);
static void e1000_clean_all_rx_rings(struct e1000_adapter *adapter);
static void e1000_clean_tx_ring(struct e1000_adapter *adapter,
struct e1000_tx_ring *tx_ring);
static void e1000_clean_rx_ring(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring);
static void e1000_set_multi(struct net_device *netdev);
static void e1000_update_phy_info(unsigned long data);
static void e1000_watchdog(unsigned long data);
static void e1000_watchdog_task(struct work_struct *work);
static void e1000_82547_tx_fifo_stall(unsigned long data);
static int e1000_xmit_frame_ring(struct sk_buff *skb, struct net_device *netdev,
struct e1000_tx_ring *tx_ring);
static int e1000_xmit_frame(struct sk_buff *skb, struct net_device *netdev);
#ifdef CONFIG_E1000_MQ
static int e1000_subqueue_xmit_frame(struct sk_buff *skb,
struct net_device *netdev, int queue);
#endif
static void e1000_phy_read_status(struct e1000_adapter *adapter);
#if 0
static struct net_device_stats * e1000_get_stats(struct net_device *netdev);
static int e1000_change_mtu(struct net_device *netdev, int new_mtu);
static int e1000_set_mac(struct net_device *netdev, void *p);
#endif
static int e1000_intr(rtdm_irq_t *irq_handle);
static int e1000_intr_msi(rtdm_irq_t *irq_handle);
static bool e1000_clean_tx_irq(struct e1000_adapter *adapter,
struct e1000_tx_ring *tx_ring);
#ifdef CONFIG_E1000_NAPI
static int e1000_poll(struct napi_struct *napi, int budget);
static bool e1000_clean_rx_irq(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring,
int *work_done, int work_to_do);
static bool e1000_clean_rx_irq_ps(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring,
int *work_done, int work_to_do);
static bool e1000_clean_jumbo_rx_irq(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring,
int *work_done, int work_to_do);
static void e1000_alloc_jumbo_rx_buffers(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring,
int cleaned_count);
#else
static bool e1000_clean_rx_irq(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring,
nanosecs_abs_t *time_stamp);
static bool e1000_clean_rx_irq_ps(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring,
nanosecs_abs_t *time_stamp);
#endif
static void e1000_alloc_rx_buffers(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring,
int cleaned_count);
static void e1000_alloc_rx_buffers_ps(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring,
int cleaned_count);
#if 0
static int e1000_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd);
#ifdef SIOCGMIIPHY
static int e1000_mii_ioctl(struct net_device *netdev, struct ifreq *ifr,
int cmd);
static void e1000_enter_82542_rst(struct e1000_adapter *adapter);
static void e1000_leave_82542_rst(struct e1000_adapter *adapter);
static void e1000_tx_timeout(struct net_device *dev);
#endif
#endif
static void e1000_reset_task(struct work_struct *work);
static void e1000_smartspeed(struct e1000_adapter *adapter);
static int e1000_82547_fifo_workaround(struct e1000_adapter *adapter,
struct sk_buff *skb);
#ifdef NETIF_F_HW_VLAN_TX
static void e1000_vlan_rx_register(struct net_device *netdev,
struct vlan_group *grp);
static void e1000_vlan_rx_add_vid(struct net_device *netdev, u16 vid);
static void e1000_vlan_rx_kill_vid(struct net_device *netdev, u16 vid);
static void e1000_restore_vlan(struct e1000_adapter *adapter);
#endif
// static int e1000_suspend(struct pci_dev *pdev, pm_message_t state);
#ifdef CONFIG_PM
static int e1000_resume(struct pci_dev *pdev);
#endif
#ifndef USE_REBOOT_NOTIFIER
// static void e1000_shutdown(struct pci_dev *pdev);
#else
static int e1000_notify_reboot(struct notifier_block *, unsigned long event,
void *ptr);
static struct notifier_block e1000_notifier_reboot = {
.notifier_call = e1000_notify_reboot,
.next = NULL,
.priority = 0
};
#endif
#ifdef CONFIG_NET_POLL_CONTROLLER
/* for netdump / net console */
static void e1000_netpoll (struct net_device *netdev);
#endif
#define COPYBREAK_DEFAULT 256
static unsigned int copybreak __read_mostly = COPYBREAK_DEFAULT;
module_param(copybreak, uint, 0644);
MODULE_PARM_DESC(copybreak,
"Maximum size of packet that is copied to a new buffer on receive");
#ifdef HAVE_PCI_ERS
static pci_ers_result_t e1000_io_error_detected(struct pci_dev *pdev,
pci_channel_state_t state);
static pci_ers_result_t e1000_io_slot_reset(struct pci_dev *pdev);
static void e1000_io_resume(struct pci_dev *pdev);
static struct pci_error_handlers e1000_err_handler = {
.error_detected = e1000_io_error_detected,
.slot_reset = e1000_io_slot_reset,
.resume = e1000_io_resume,
};
#endif
static struct pci_driver e1000_driver = {
.name = e1000_driver_name,
.id_table = e1000_pci_tbl,
.probe = e1000_probe,
.remove = e1000_remove,
#ifdef HAVE_PCI_ERS
.err_handler = &e1000_err_handler
#endif
};
MODULE_AUTHOR("Intel Corporation, <linux.nics@intel.com>");
MODULE_DESCRIPTION("Intel(R) PRO/1000 Network Driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
#define MAX_UNITS 8
static int cards[MAX_UNITS] = { [0 ... (MAX_UNITS-1)] = 1 };
module_param_array(cards, int, NULL, 0444);
MODULE_PARM_DESC(cards, "array of cards to be supported (eg. 1,0,1)");
static int debug = NETIF_MSG_DRV | NETIF_MSG_PROBE;
module_param(debug, int, 0);
MODULE_PARM_DESC(debug, "Debug level (0=none,...,16=all)");
/* The parameter 'pciif' might be used to use this driver for
* PCI or PCIe only NICs.
* This allows to reflect the situation that newer Linux kernels
* have two different (non real time) drivers for the e1000:
* e1000 for PCI only
* e1000e for PCIe only
*
* Using the 'pciif' parameter allows to load the driver
* modprobe rt_e1000 pciif=pci
* to use it as PCI only
* and a
* modprobe rt_e1000 -o rt_e1000e pciif=pcie
* allows to load a second instance of this driver named 'rt_e1000e'
*
* If the 'pciif' paramter is not specified, all (PCI and PCIe) e1000
* NICs will be used.
* */
static char *pciif = "all";
module_param(pciif, charp, 0);
MODULE_PARM_DESC(pciif, "PCI Interface: 'all' (default), 'pci', 'pcie'");
//#define register_netdev(a) rt_register_rtnetdev(a)
//#define unregister_netdev(a) rt_unregister_rtnetdev(a)
//#define free_netdev(a) rtdev_free(a)
//#define netif_stop_queue(a) rtnetif_stop_queue(a)
/**
* e1000_init_module - Driver Registration Routine
*
* e1000_init_module is the first routine called when the driver is
* loaded. All it does is register with the PCI subsystem.
**/
static int __init e1000_init_module(void)
{
int ret;
strcpy(e1000_driver_name, THIS_MODULE->name);
printk(KERN_INFO "%s - %s version %s (pciif: %s)\n",
e1000_driver_string, e1000_driver_name, e1000_driver_version, pciif);
printk(KERN_INFO "%s\n", e1000_copyright);
if (0 == strcmp(pciif, "pcie"))
{
// PCIe only
e1000_driver.id_table = e1000_pcie_tbl;
}
else if (0 == strcmp(pciif, "pci"))
{
// PCI only
e1000_driver.id_table = e1000_pcipure_tbl;
}
ret = pci_register_driver(&e1000_driver);
#ifdef USE_REBOOT_NOTIFIER
if (ret >= 0) {
register_reboot_notifier(&e1000_notifier_reboot);
}
#endif
if (copybreak != COPYBREAK_DEFAULT) {
if (copybreak == 0)
printk(KERN_INFO "e1000: copybreak disabled\n");
else
printk(KERN_INFO "e1000: copybreak enabled for "
"packets <= %u bytes\n", copybreak);
}
return ret;
}
module_init(e1000_init_module);
/**
* e1000_exit_module - Driver Exit Cleanup Routine
*
* e1000_exit_module is called just before the driver is removed
* from memory.
**/
static void __exit e1000_exit_module(void)
{
#ifdef USE_REBOOT_NOTIFIER
unregister_reboot_notifier(&e1000_notifier_reboot);
#endif
pci_unregister_driver(&e1000_driver);
}
module_exit(e1000_exit_module);
static int e1000_request_irq(struct e1000_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
int err = 0;
if (adapter->flags & E1000_FLAG_HAS_MSI) {
err = pci_enable_msi(adapter->pdev);
if (!err)
adapter->flags |= E1000_FLAG_MSI_ENABLED;
}
rt_stack_connect(netdev, &STACK_manager);
if (adapter->flags & E1000_FLAG_MSI_ENABLED) {
err = rtdm_irq_request(&adapter->irq_handle, adapter->pdev->irq, e1000_intr_msi,
0, netdev->name, netdev);
if (!err) {
return err;
} else {
adapter->flags &= ~E1000_FLAG_MSI_ENABLED;
pci_disable_msi(adapter->pdev);
}
}
err = rtdm_irq_request(&adapter->irq_handle, adapter->pdev->irq,
e1000_intr, RTDM_IRQTYPE_SHARED, netdev->name,
netdev);
if (err)
DPRINTK(PROBE, ERR, "Unable to allocate interrupt Error: %d\n",
err);
return err;
}
static void e1000_free_irq(struct e1000_adapter *adapter)
{
// struct net_device *netdev = adapter->netdev;
rtdm_irq_free(&adapter->irq_handle);
if (adapter->flags & E1000_FLAG_MSI_ENABLED) {
pci_disable_msi(adapter->pdev);
adapter->flags &= ~E1000_FLAG_MSI_ENABLED;
}
}
/**
* e1000_irq_disable - Mask off interrupt generation on the NIC
* @adapter: board private structure
**/
static void e1000_irq_disable(struct e1000_adapter *adapter)
{
atomic_inc(&adapter->irq_sem);
E1000_WRITE_REG(&adapter->hw, E1000_IMC, ~0);
E1000_WRITE_FLUSH(&adapter->hw);
synchronize_irq(adapter->pdev->irq);
}
/**
* e1000_irq_enable - Enable default interrupt generation settings
* @adapter: board private structure
**/
static void e1000_irq_enable(struct e1000_adapter *adapter)
{
if (likely(atomic_dec_and_test(&adapter->irq_sem))) {
E1000_WRITE_REG(&adapter->hw, E1000_IMS, IMS_ENABLE_MASK);
E1000_WRITE_FLUSH(&adapter->hw);
}
}
#ifdef NETIF_F_HW_VLAN_TX
static void e1000_update_mng_vlan(struct e1000_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
u16 vid = adapter->hw.mng_cookie.vlan_id;
u16 old_vid = adapter->mng_vlan_id;
if (adapter->vlgrp) {
if (!vlan_group_get_device(adapter->vlgrp, vid)) {
if (adapter->hw.mng_cookie.status &
E1000_MNG_DHCP_COOKIE_STATUS_VLAN) {
e1000_vlan_rx_add_vid(netdev, vid);
adapter->mng_vlan_id = vid;
} else {
adapter->mng_vlan_id = E1000_MNG_VLAN_NONE;
}
if ((old_vid != (u16)E1000_MNG_VLAN_NONE) &&
(vid != old_vid) &&
!vlan_group_get_device(adapter->vlgrp, old_vid))
e1000_vlan_rx_kill_vid(netdev, old_vid);
} else {
adapter->mng_vlan_id = vid;
}
}
}
#endif
/**
* e1000_release_hw_control - release control of the h/w to f/w
* @adapter: address of board private structure
*
* e1000_release_hw_control resets {CTRL_EXT|SWSM}:DRV_LOAD bit.
* For ASF and Pass Through versions of f/w this means that the
* driver is no longer loaded. For AMT version (only with 82573) i
* of the f/w this means that the network i/f is closed.
*
**/
static void e1000_release_hw_control(struct e1000_adapter *adapter)
{
u32 ctrl_ext;
u32 swsm;
/* Let firmware taken over control of h/w */
switch (adapter->hw.mac.type) {
case e1000_82573:
swsm = E1000_READ_REG(&adapter->hw, E1000_SWSM);
E1000_WRITE_REG(&adapter->hw, E1000_SWSM,
swsm & ~E1000_SWSM_DRV_LOAD);
break;
case e1000_82571:
case e1000_82572:
case e1000_80003es2lan:
case e1000_ich8lan:
case e1000_ich9lan:
ctrl_ext = E1000_READ_REG(&adapter->hw, E1000_CTRL_EXT);
E1000_WRITE_REG(&adapter->hw, E1000_CTRL_EXT,
ctrl_ext & ~E1000_CTRL_EXT_DRV_LOAD);
break;
default:
break;
}
}
/**
* e1000_get_hw_control - get control of the h/w from f/w
* @adapter: address of board private structure
*
* e1000_get_hw_control sets {CTRL_EXT|SWSM}:DRV_LOAD bit.
* For ASF and Pass Through versions of f/w this means that
* the driver is loaded. For AMT version (only with 82573)
* of the f/w this means that the network i/f is open.
*
**/
static void e1000_get_hw_control(struct e1000_adapter *adapter)
{
u32 ctrl_ext;
u32 swsm;
/* Let firmware know the driver has taken over */
switch (adapter->hw.mac.type) {
case e1000_82573:
swsm = E1000_READ_REG(&adapter->hw, E1000_SWSM);
E1000_WRITE_REG(&adapter->hw, E1000_SWSM,
swsm | E1000_SWSM_DRV_LOAD);
break;
case e1000_82571:
case e1000_82572:
case e1000_80003es2lan:
case e1000_ich8lan:
case e1000_ich9lan:
ctrl_ext = E1000_READ_REG(&adapter->hw, E1000_CTRL_EXT);
E1000_WRITE_REG(&adapter->hw, E1000_CTRL_EXT,
ctrl_ext | E1000_CTRL_EXT_DRV_LOAD);
break;
default:
break;
}
}
static void e1000_init_manageability(struct e1000_adapter *adapter)
{
}
static void e1000_release_manageability(struct e1000_adapter *adapter)
{
}
/**
* e1000_configure - configure the hardware for RX and TX
* @adapter: private board structure
**/
static void e1000_configure(struct e1000_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
int i;
e1000_set_multi(netdev);
#ifdef NETIF_F_HW_VLAN_TX
e1000_restore_vlan(adapter);
#endif
e1000_init_manageability(adapter);
e1000_configure_tx(adapter);
e1000_setup_rctl(adapter);
e1000_configure_rx(adapter);
/* call E1000_DESC_UNUSED which always leaves
* at least 1 descriptor unused to make sure
* next_to_use != next_to_clean */
for (i = 0; i < adapter->num_rx_queues; i++) {
struct e1000_rx_ring *ring = &adapter->rx_ring[i];
adapter->alloc_rx_buf(adapter, ring,
E1000_DESC_UNUSED(ring));
}
#ifdef CONFIG_E1000_MQ
e1000_setup_queue_mapping(adapter);
#endif
// adapter->tx_queue_len = netdev->tx_queue_len;
}
static void e1000_napi_enable_all(struct e1000_adapter *adapter)
{
#ifdef CONFIG_E1000_NAPI
int i;
for (i = 0; i < adapter->num_rx_queues; i++)
napi_enable(&adapter->rx_ring[i].napi);
#endif
}
static void e1000_napi_disable_all(struct e1000_adapter *adapter)
{
#ifdef CONFIG_E1000_NAPI
int i;
for (i = 0; i < adapter->num_rx_queues; i++)
napi_disable(&adapter->rx_ring[i].napi);
#endif
}
int e1000_up(struct e1000_adapter *adapter)
{
/* hardware has been reset, we need to reload some things */
e1000_configure(adapter);
clear_bit(__E1000_DOWN, &adapter->state);
e1000_napi_enable_all(adapter);
e1000_irq_enable(adapter);
/* fire a link change interrupt to start the watchdog */
// E1000_WRITE_REG(&adapter->hw, E1000_ICS, E1000_ICS_LSC);
return 0;
}
void e1000_down(struct e1000_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
u32 tctl, rctl;
/* signal that we're down so the interrupt handler does not
* reschedule our watchdog timer */
set_bit(__E1000_DOWN, &adapter->state);
/* disable receives in the hardware */
rctl = E1000_READ_REG(&adapter->hw, E1000_RCTL);
E1000_WRITE_REG(&adapter->hw, E1000_RCTL, rctl & ~E1000_RCTL_EN);
/* flush and sleep below */
#ifdef NETIF_F_LLTX
rtnetif_stop_queue(netdev);
#else
rtnetif_tx_disable(netdev);
#endif
/* disable transmits in the hardware */
tctl = E1000_READ_REG(&adapter->hw, E1000_TCTL);
tctl &= ~E1000_TCTL_EN;
E1000_WRITE_REG(&adapter->hw, E1000_TCTL, tctl);
/* flush both disables and wait for them to finish */
E1000_WRITE_FLUSH(&adapter->hw);
msleep(10);
e1000_napi_disable_all(adapter);
e1000_irq_disable(adapter);
del_timer_sync(&adapter->tx_fifo_stall_timer);
del_timer_sync(&adapter->watchdog_timer);
del_timer_sync(&adapter->phy_info_timer);
// netdev->tx_queue_len = adapter->tx_queue_len;
rtnetif_carrier_off(netdev);
adapter->link_speed = 0;
adapter->link_duplex = 0;
e1000_reset(adapter);
e1000_clean_all_tx_rings(adapter);
e1000_clean_all_rx_rings(adapter);
}
void e1000_reinit_locked(struct e1000_adapter *adapter)
{
WARN_ON(in_interrupt());
while (test_and_set_bit(__E1000_RESETTING, &adapter->state))
msleep(1);
e1000_down(adapter);
e1000_up(adapter);
clear_bit(__E1000_RESETTING, &adapter->state);
}
void e1000_reset(struct e1000_adapter *adapter)
{
struct e1000_mac_info *mac = &adapter->hw.mac;
struct e1000_fc_info *fc = &adapter->hw.fc;
u32 pba = 0, tx_space, min_tx_space, min_rx_space;
bool legacy_pba_adjust = FALSE;
u16 hwm;
/* Repartition Pba for greater than 9k mtu
* To take effect CTRL.RST is required.
*/
switch (mac->type) {
case e1000_82542:
case e1000_82543:
case e1000_82544:
case e1000_82540:
case e1000_82541:
case e1000_82541_rev_2:
legacy_pba_adjust = TRUE;
pba = E1000_PBA_48K;
break;
case e1000_82545:
case e1000_82545_rev_3:
case e1000_82546:
case e1000_82546_rev_3:
pba = E1000_PBA_48K;
break;
case e1000_82547:
case e1000_82547_rev_2:
legacy_pba_adjust = TRUE;
pba = E1000_PBA_30K;
break;
case e1000_82571:
case e1000_82572:
case e1000_80003es2lan:
pba = E1000_PBA_38K;
break;
case e1000_82573:
pba = E1000_PBA_20K;
break;
case e1000_ich8lan:
pba = E1000_PBA_8K;
break;
case e1000_ich9lan:
#define E1000_PBA_10K 0x000A
pba = E1000_PBA_10K;
break;
case e1000_undefined:
case e1000_num_macs:
break;
}
if (legacy_pba_adjust == TRUE) {
if (adapter->max_frame_size > E1000_RXBUFFER_8192)
pba -= 8; /* allocate more FIFO for Tx */
if (mac->type == e1000_82547) {
adapter->tx_fifo_head = 0;
adapter->tx_head_addr = pba << E1000_TX_HEAD_ADDR_SHIFT;
adapter->tx_fifo_size =
(E1000_PBA_40K - pba) << E1000_PBA_BYTES_SHIFT;
atomic_set(&adapter->tx_fifo_stall, 0);
}
} else if (adapter->max_frame_size > ETH_FRAME_LEN + ETHERNET_FCS_SIZE) {
/* adjust PBA for jumbo frames */
E1000_WRITE_REG(&adapter->hw, E1000_PBA, pba);
/* To maintain wire speed transmits, the Tx FIFO should be
* large enough to accommodate two full transmit packets,
* rounded up to the next 1KB and expressed in KB. Likewise,
* the Rx FIFO should be large enough to accommodate at least
* one full receive packet and is similarly rounded up and
* expressed in KB. */
pba = E1000_READ_REG(&adapter->hw, E1000_PBA);
/* upper 16 bits has Tx packet buffer allocation size in KB */
tx_space = pba >> 16;
/* lower 16 bits has Rx packet buffer allocation size in KB */
pba &= 0xffff;
/* the tx fifo also stores 16 bytes of information about the tx
* but don't include ethernet FCS because hardware appends it */
min_tx_space = (adapter->max_frame_size +
sizeof(struct e1000_tx_desc) -
ETHERNET_FCS_SIZE) * 2;
min_tx_space = ALIGN(min_tx_space, 1024);
min_tx_space >>= 10;
/* software strips receive CRC, so leave room for it */
min_rx_space = adapter->max_frame_size;
min_rx_space = ALIGN(min_rx_space, 1024);
min_rx_space >>= 10;
/* If current Tx allocation is less than the min Tx FIFO size,
* and the min Tx FIFO size is less than the current Rx FIFO
* allocation, take space away from current Rx allocation */
if (tx_space < min_tx_space &&
((min_tx_space - tx_space) < pba)) {
pba = pba - (min_tx_space - tx_space);
/* PCI/PCIx hardware has PBA alignment constraints */
switch (mac->type) {
case e1000_82545 ... e1000_82546_rev_3:
pba &= ~(E1000_PBA_8K - 1);
break;
default:
break;
}
/* if short on rx space, rx wins and must trump tx
* adjustment or use Early Receive if available */
if (pba < min_rx_space) {
switch (mac->type) {
case e1000_82573:
case e1000_ich9lan:
/* ERT enabled in e1000_configure_rx */
break;
default:
pba = min_rx_space;
break;
}
}
}
}
E1000_WRITE_REG(&adapter->hw, E1000_PBA, pba);
/* flow control settings */
/* The high water mark must be low enough to fit one full frame
* (or the size used for early receive) above it in the Rx FIFO.
* Set it to the lower of:
* - 90% of the Rx FIFO size, and
* - the full Rx FIFO size minus the early receive size (for parts
* with ERT support assuming ERT set to E1000_ERT_2048), or
* - the full Rx FIFO size minus one full frame */
hwm = min(((pba << 10) * 9 / 10),
((mac->type == e1000_82573 || mac->type == e1000_ich9lan) ?
(u16)((pba << 10) - (E1000_ERT_2048 << 3)) :
((pba << 10) - adapter->max_frame_size)));
fc->high_water = hwm & 0xFFF8; /* 8-byte granularity */
fc->low_water = fc->high_water - 8;
if (mac->type == e1000_80003es2lan)
fc->pause_time = 0xFFFF;
else
fc->pause_time = E1000_FC_PAUSE_TIME;
fc->send_xon = 1;
fc->type = fc->original_type;
/* Allow time for pending master requests to run */
e1000_reset_hw(&adapter->hw);
/* For 82573 and ICHx if AMT is enabled, let the firmware know
* that the network interface is in control */
if (((adapter->hw.mac.type == e1000_82573) ||
(adapter->hw.mac.type == e1000_ich8lan) ||
(adapter->hw.mac.type == e1000_ich9lan)) &&
e1000_check_mng_mode(&adapter->hw))
e1000_get_hw_control(adapter);
if (mac->type >= e1000_82544)
E1000_WRITE_REG(&adapter->hw, E1000_WUC, 0);
if (e1000_init_hw(&adapter->hw))
DPRINTK(PROBE, ERR, "Hardware Error\n");
#ifdef NETIF_F_HW_VLAN_TX
e1000_update_mng_vlan(adapter);
#endif
/* if (adapter->hwflags & HWFLAGS_PHY_PWR_BIT) { */
if (mac->type >= e1000_82544 &&
mac->type <= e1000_82547_rev_2 &&
mac->autoneg == 1 &&
adapter->hw.phy.autoneg_advertised == ADVERTISE_1000_FULL) {
u32 ctrl = E1000_READ_REG(&adapter->hw, E1000_CTRL);
/* clear phy power management bit if we are in gig only mode,
* which if enabled will attempt negotiation to 100Mb, which
* can cause a loss of link at power off or driver unload */
ctrl &= ~E1000_CTRL_SWDPIN3;
E1000_WRITE_REG(&adapter->hw, E1000_CTRL, ctrl);
}
#if defined(CONFIG_PPC64) || defined(CONFIG_PPC)
#define E1000_GCR_DISABLE_TIMEOUT_MECHANISM 0x80000000
if (adapter->hw.mac.type == e1000_82571) {
/* work around pSeries hardware by disabling timeouts */
u32 gcr = E1000_READ_REG(&adapter->hw, E1000_GCR);
gcr |= E1000_GCR_DISABLE_TIMEOUT_MECHANISM;
E1000_WRITE_REG(&adapter->hw, E1000_GCR, gcr);
}
#endif
/* Enable h/w to recognize an 802.1Q VLAN Ethernet packet */
E1000_WRITE_REG(&adapter->hw, E1000_VET, ETHERNET_IEEE_VLAN_TYPE);
e1000_reset_adaptive(&adapter->hw);
e1000_get_phy_info(&adapter->hw);
if (!(adapter->flags & E1000_FLAG_SMART_POWER_DOWN) &&
(mac->type == e1000_82571 || mac->type == e1000_82572)) {
u16 phy_data = 0;
/* speed up time to link by disabling smart power down, ignore
* the return value of this function because there is nothing
* different we would do if it failed */
e1000_read_phy_reg(&adapter->hw, IGP02E1000_PHY_POWER_MGMT,
&phy_data);
phy_data &= ~IGP02E1000_PM_SPD;
e1000_write_phy_reg(&adapter->hw, IGP02E1000_PHY_POWER_MGMT,
phy_data);
}
e1000_release_manageability(adapter);
}
/**
* e1000_probe - Device Initialization Routine
* @pdev: PCI device information struct
* @ent: entry in e1000_pci_tbl
*
* Returns 0 on success, negative on failure
*
* e1000_probe initializes an adapter identified by a pci_dev structure.
* The OS initialization, configuring of the adapter private structure,
* and a hardware reset occur.
**/
static int e1000_probe(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct net_device *netdev;
struct e1000_adapter *adapter;
static int cards_found = 0;
static int global_quad_port_a = 0; /* global ksp3 port a indication */
int i, err, pci_using_dac;
u16 eeprom_data = 0;
u16 eeprom_apme_mask = E1000_EEPROM_APME;
if (cards[cards_found++] == 0)
{
return -ENODEV;
}
if ((err = pci_enable_device(pdev)))
return err;
if (!(err = pci_set_dma_mask(pdev, DMA_64BIT_MASK)) &&
!(err = pci_set_consistent_dma_mask(pdev, DMA_64BIT_MASK))) {
pci_using_dac = 1;
} else {
if ((err = pci_set_dma_mask(pdev, DMA_32BIT_MASK)) &&
(err = pci_set_consistent_dma_mask(pdev, DMA_32BIT_MASK))) {
E1000_ERR("No usable DMA configuration, aborting\n");
goto err_dma;
}
pci_using_dac = 0;
}
if ((err = pci_request_regions(pdev, e1000_driver_name)))
goto err_pci_reg;
pci_set_master(pdev);
err = -ENOMEM;
#ifdef CONFIG_E1000_MQ
netdev = rt_alloc_etherdev(sizeof(struct e1000_adapter) +
(sizeof(struct net_device_subqueue) *
E1000_MAX_TX_QUEUES), 16);
#else
netdev = rt_alloc_etherdev(sizeof(struct e1000_adapter),
2 * E1000_DEFAULT_RXD + E1000_DEFAULT_TXD);
#endif
if (!netdev)
goto err_alloc_etherdev;
memset(netdev->priv, 0, sizeof(struct e1000_adapter));
rt_rtdev_connect(netdev, &RTDEV_manager);
// SET_NETDEV_DEV(netdev, &pdev->dev);
netdev->vers = RTDEV_VERS_2_0;
pci_set_drvdata(pdev, netdev);
adapter = netdev->priv;
adapter->netdev = netdev;
adapter->pdev = pdev;
adapter->hw.back = adapter;
adapter->msg_enable = (1 << debug) - 1;
err = -EIO;
adapter->hw.hw_addr = ioremap(pci_resource_start(pdev, BAR_0),
pci_resource_len(pdev, BAR_0));
if (!adapter->hw.hw_addr)
goto err_ioremap;
for (i = BAR_1; i <= BAR_5; i++) {
if (pci_resource_len(pdev, i) == 0)
continue;
if (pci_resource_flags(pdev, i) & IORESOURCE_IO) {
adapter->hw.io_base = pci_resource_start(pdev, i);
break;
}
}
netdev->open = &e1000_open;
netdev->stop = &e1000_close;
netdev->hard_start_xmit = &e1000_xmit_frame;
#ifdef CONFIG_E1000_MQ
netdev->hard_start_subqueue_xmit = &e1000_subqueue_xmit_frame;
#endif
#ifdef HAVE_TX_TIMEOUT
netdev->tx_timeout = &e1000_tx_timeout;
netdev->watchdog_timeo = 5 * HZ;
#endif
#ifdef NETIF_F_HW_VLAN_TX
netdev->vlan_rx_register = e1000_vlan_rx_register;
netdev->vlan_rx_add_vid = e1000_vlan_rx_add_vid;
netdev->vlan_rx_kill_vid = e1000_vlan_rx_kill_vid;
#endif
#ifdef CONFIG_NET_POLL_CONTROLLER
netdev->poll_controller = e1000_netpoll;
#endif
strncpy(netdev->name, pci_name(pdev), sizeof(netdev->name) - 1);
adapter->bd_number = cards_found;
/* setup the private structure */
if ((err = e1000_sw_init(adapter)))
goto err_sw_init;
err = -EIO;
/* Flash BAR mapping must happen after e1000_sw_init
* because it depends on mac.type */
if (((adapter->hw.mac.type == e1000_ich8lan) ||
(adapter->hw.mac.type == e1000_ich9lan)) &&
(pci_resource_flags(pdev, 1) & IORESOURCE_MEM)) {
adapter->hw.flash_address = ioremap(pci_resource_start(pdev, 1),
pci_resource_len(pdev, 1));
if (!adapter->hw.flash_address)
goto err_flashmap;
}
if ((err = e1000_init_mac_params(&adapter->hw)))
goto err_hw_init;
if ((err = e1000_init_nvm_params(&adapter->hw)))
goto err_hw_init;
if ((err = e1000_init_phy_params(&adapter->hw)))
goto err_hw_init;
e1000_get_bus_info(&adapter->hw);
e1000_init_script_state_82541(&adapter->hw, TRUE);
e1000_set_tbi_compatibility_82543(&adapter->hw, TRUE);
adapter->hw.phy.autoneg_wait_to_complete = FALSE;
adapter->hw.mac.adaptive_ifs = FALSE;
/* Copper options */
if (adapter->hw.phy.media_type == e1000_media_type_copper) {
adapter->hw.phy.mdix = AUTO_ALL_MODES;
adapter->hw.phy.disable_polarity_correction = FALSE;
adapter->hw.phy.ms_type = E1000_MASTER_SLAVE;
}
if (e1000_check_reset_block(&adapter->hw))
DPRINTK(PROBE, INFO, "PHY reset is blocked due to SOL/IDER session.\n");
#ifdef MAX_SKB_FRAGS
if (adapter->hw.mac.type >= e1000_82543) {
#ifdef NETIF_F_HW_VLAN_TX
netdev->features = NETIF_F_SG |
NETIF_F_HW_CSUM |
NETIF_F_HW_VLAN_TX |
NETIF_F_HW_VLAN_RX |
NETIF_F_HW_VLAN_FILTER;
if ((adapter->hw.mac.type == e1000_ich8lan) ||
(adapter->hw.mac.type == e1000_ich9lan))
netdev->features &= ~NETIF_F_HW_VLAN_FILTER;
#else
netdev->features = NETIF_F_SG | NETIF_F_HW_CSUM;
#endif
}
#ifdef NETIF_F_TSO
if ((adapter->hw.mac.type >= e1000_82544) &&
(adapter->hw.mac.type != e1000_82547)) {
adapter->flags |= E1000_FLAG_HAS_TSO;
netdev->features |= NETIF_F_TSO;
}
#ifdef NETIF_F_TSO6
if (adapter->hw.mac.type > e1000_82547_rev_2) {
adapter->flags |= E1000_FLAG_HAS_TSO6;
netdev->features |= NETIF_F_TSO6;
}
#endif
#endif
if (pci_using_dac)
netdev->features |= NETIF_F_HIGHDMA;
#endif
#ifdef NETIF_F_LLTX
netdev->features |= NETIF_F_LLTX;
#endif
/* Hardware features, flags and workarounds */
if (adapter->hw.mac.type >= e1000_82571) {
adapter->flags |= E1000_FLAG_INT_ASSERT_AUTO_MASK;
adapter->flags |= E1000_FLAG_HAS_MSI;
adapter->flags |= E1000_FLAG_HAS_MANC2H;
}
if (adapter->hw.mac.type >= e1000_82540) {
adapter->flags |= E1000_FLAG_HAS_SMBUS;
adapter->flags |= E1000_FLAG_HAS_INTR_MODERATION;
}
if (adapter->hw.mac.type == e1000_82543)
adapter->flags |= E1000_FLAG_BAD_TX_CARRIER_STATS_FD;
/* In rare occasions, ESB2 systems would end up started without
* the RX unit being turned on. */
if (adapter->hw.mac.type == e1000_80003es2lan)
adapter->flags |= E1000_FLAG_RX_NEEDS_RESTART;
adapter->en_mng_pt = e1000_enable_mng_pass_thru(&adapter->hw);
/* before reading the NVM, reset the controller to
* put the device in a known good starting state */
e1000_reset_hw(&adapter->hw);
/* make sure we don't intercept ARP packets until we're up */
e1000_release_manageability(adapter);
/* make sure the NVM is good */
if (e1000_validate_nvm_checksum(&adapter->hw) < 0) {
DPRINTK(PROBE, ERR, "The NVM Checksum Is Not Valid\n");
err = -EIO;
goto err_eeprom;
}
/* copy the MAC address out of the NVM */
if (e1000_read_mac_addr(&adapter->hw))
DPRINTK(PROBE, ERR, "NVM Read Error\n");
memcpy(netdev->dev_addr, adapter->hw.mac.addr, netdev->addr_len);
#ifdef ETHTOOL_GPERMADDR
memcpy(netdev->perm_addr, adapter->hw.mac.addr, netdev->addr_len);
if (!is_valid_ether_addr(netdev->perm_addr)) {
#else
if (!is_valid_ether_addr(netdev->dev_addr)) {
#endif
DPRINTK(PROBE, ERR, "Invalid MAC Address\n");
err = -EIO;
goto err_eeprom;
}
init_timer(&adapter->tx_fifo_stall_timer);
adapter->tx_fifo_stall_timer.function = &e1000_82547_tx_fifo_stall;
adapter->tx_fifo_stall_timer.data = (unsigned long) adapter;
init_timer(&adapter->watchdog_timer);
adapter->watchdog_timer.function = &e1000_watchdog;
adapter->watchdog_timer.data = (unsigned long) adapter;
init_timer(&adapter->phy_info_timer);
adapter->phy_info_timer.function = &e1000_update_phy_info;
adapter->phy_info_timer.data = (unsigned long) adapter;
INIT_WORK(&adapter->reset_task, e1000_reset_task);
INIT_WORK(&adapter->watchdog_task, e1000_watchdog_task);
e1000_check_options(adapter);
/* Initial Wake on LAN setting
* If APM wake is enabled in the EEPROM,
* enable the ACPI Magic Packet filter
*/
switch (adapter->hw.mac.type) {
case e1000_82542:
case e1000_82543:
break;
case e1000_82544:
e1000_read_nvm(&adapter->hw,
NVM_INIT_CONTROL2_REG, 1, &eeprom_data);
eeprom_apme_mask = E1000_EEPROM_82544_APM;
break;
case e1000_ich8lan:
case e1000_ich9lan:
/* APME bit in EEPROM is mapped to WUC.APME */
eeprom_data = E1000_READ_REG(&adapter->hw, E1000_WUC);
eeprom_apme_mask = E1000_WUC_APME;
break;
case e1000_82546:
case e1000_82546_rev_3:
case e1000_82571:
case e1000_80003es2lan:
if (adapter->hw.bus.func == 1) {
e1000_read_nvm(&adapter->hw,
NVM_INIT_CONTROL3_PORT_B, 1, &eeprom_data);
break;
}
/* Fall Through */
default:
e1000_read_nvm(&adapter->hw,
NVM_INIT_CONTROL3_PORT_A, 1, &eeprom_data);
break;
}
if (eeprom_data & eeprom_apme_mask)
adapter->eeprom_wol |= E1000_WUFC_MAG;
/* now that we have the eeprom settings, apply the special cases
* where the eeprom may be wrong or the board simply won't support
* wake on lan on a particular port */
switch (pdev->device) {
case E1000_DEV_ID_82546GB_PCIE:
case E1000_DEV_ID_82571EB_SERDES_QUAD:
adapter->eeprom_wol = 0;
break;
case E1000_DEV_ID_82546EB_FIBER:
case E1000_DEV_ID_82546GB_FIBER:
case E1000_DEV_ID_82571EB_FIBER:
/* Wake events only supported on port A for dual fiber
* regardless of eeprom setting */
if (E1000_READ_REG(&adapter->hw, E1000_STATUS) &
E1000_STATUS_FUNC_1)
adapter->eeprom_wol = 0;
break;
case E1000_DEV_ID_82546GB_QUAD_COPPER_KSP3:
case E1000_DEV_ID_82571EB_QUAD_COPPER:
case E1000_DEV_ID_82571EB_QUAD_FIBER:
case E1000_DEV_ID_82571EB_QUAD_COPPER_LP:
case E1000_DEV_ID_82571PT_QUAD_COPPER:
/* if quad port adapter, disable WoL on all but port A */
if (global_quad_port_a != 0)
adapter->eeprom_wol = 0;
else
adapter->flags |= E1000_FLAG_QUAD_PORT_A;
/* Reset for multiple quad port adapters */
if (++global_quad_port_a == 4)
global_quad_port_a = 0;
break;
}
/* initialize the wol settings based on the eeprom settings */
adapter->wol = adapter->eeprom_wol;
/* print bus type/speed/width info */
{
struct e1000_hw *hw = &adapter->hw;
DPRINTK(PROBE, INFO, "(PCI%s:%s:%s) ",
((hw->bus.type == e1000_bus_type_pcix) ? "-X" :
(hw->bus.type == e1000_bus_type_pci_express ? " Express":"")),
((hw->bus.speed == e1000_bus_speed_2500) ? "2.5Gb/s" :
(hw->bus.speed == e1000_bus_speed_133) ? "133MHz" :
(hw->bus.speed == e1000_bus_speed_120) ? "120MHz" :
(hw->bus.speed == e1000_bus_speed_100) ? "100MHz" :
(hw->bus.speed == e1000_bus_speed_66) ? "66MHz" : "33MHz"),
((hw->bus.width == e1000_bus_width_64) ? "64-bit" :
(hw->bus.width == e1000_bus_width_pcie_x4) ? "Width x4" :
(hw->bus.width == e1000_bus_width_pcie_x1) ? "Width x1" :
"32-bit"));
}
for (i = 0; i < 6; i++)
printk("%2.2x%c", netdev->dev_addr[i], i == 5 ? '\n' : ':');
/* reset the hardware with the new settings */
e1000_reset(adapter);
/* If the controller is 82573 or ICH and f/w is AMT, do not set
* DRV_LOAD until the interface is up. For all other cases,
* let the f/w know that the h/w is now under the control
* of the driver. */
if (((adapter->hw.mac.type != e1000_82573) &&
(adapter->hw.mac.type != e1000_ich8lan) &&
(adapter->hw.mac.type != e1000_ich9lan)) ||
!e1000_check_mng_mode(&adapter->hw))
e1000_get_hw_control(adapter);
/* tell the stack to leave us alone until e1000_open() is called */
rtnetif_carrier_off(netdev);
rtnetif_stop_queue(netdev);
strcpy(netdev->name, "rteth%d");
err = rt_register_rtnetdev(netdev);
if (err)
goto err_register;
DPRINTK(PROBE, INFO, "Intel(R) PRO/1000 Network Connection\n");
cards_found++;
return 0;
err_register:
err_hw_init:
e1000_release_hw_control(adapter);
err_eeprom:
if (!e1000_check_reset_block(&adapter->hw))
e1000_phy_hw_reset(&adapter->hw);
if (adapter->hw.flash_address)
iounmap(adapter->hw.flash_address);
e1000_remove_device(&adapter->hw);
err_flashmap:
kfree(adapter->tx_ring);
kfree(adapter->rx_ring);
err_sw_init:
iounmap(adapter->hw.hw_addr);
err_ioremap:
rtdev_free(netdev);
err_alloc_etherdev:
pci_release_regions(pdev);
err_pci_reg:
err_dma:
pci_disable_device(pdev);
return err;
}
/**
* e1000_remove - Device Removal Routine
* @pdev: PCI device information struct
*
* e1000_remove is called by the PCI subsystem to alert the driver
* that it should release a PCI device. The could be caused by a
* Hot-Plug event, or because the driver is going to be removed from
* memory.
**/
static void e1000_remove(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct e1000_adapter *adapter = netdev_priv(netdev);
/* flush_scheduled work may reschedule our watchdog task, so
* explicitly disable watchdog tasks from being rescheduled */
set_bit(__E1000_DOWN, &adapter->state);
del_timer_sync(&adapter->tx_fifo_stall_timer);
del_timer_sync(&adapter->watchdog_timer);
del_timer_sync(&adapter->phy_info_timer);
flush_scheduled_work();
e1000_release_manageability(adapter);
/* Release control of h/w to f/w. If f/w is AMT enabled, this
* would have already happened in close and is redundant. */
e1000_release_hw_control(adapter);
rt_unregister_rtnetdev(netdev);
if (!e1000_check_reset_block(&adapter->hw))
e1000_phy_hw_reset(&adapter->hw);
e1000_remove_device(&adapter->hw);
kfree(adapter->tx_ring);
kfree(adapter->rx_ring);
iounmap(adapter->hw.hw_addr);
if (adapter->hw.flash_address)
iounmap(adapter->hw.flash_address);
pci_release_regions(pdev);
rtdev_free(netdev);
pci_disable_device(pdev);
}
/**
* e1000_sw_init - Initialize general software structures (struct e1000_adapter)
* @adapter: board private structure to initialize
*
* e1000_sw_init initializes the Adapter private data structure.
* Fields are initialized based on PCI device information and
* OS network device settings (MTU size).
**/
static int e1000_sw_init(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
#ifdef CONFIG_E1000_NAPI
int i;
#endif
/* PCI config space info */
hw->vendor_id = pdev->vendor;
hw->device_id = pdev->device;
hw->subsystem_vendor_id = pdev->subsystem_vendor;
hw->subsystem_device_id = pdev->subsystem_device;
pci_read_config_byte(pdev, PCI_REVISION_ID, &hw->revision_id);
pci_read_config_word(pdev, PCI_COMMAND, &hw->bus.pci_cmd_word);
adapter->rx_buffer_len = MAXIMUM_ETHERNET_VLAN_SIZE;
adapter->rx_ps_bsize0 = E1000_RXBUFFER_128;
adapter->max_frame_size = netdev->mtu + ETH_HLEN + ETHERNET_FCS_SIZE;
adapter->min_frame_size = ETH_ZLEN + ETHERNET_FCS_SIZE;
/* Initialize the hardware-specific values */
if (e1000_setup_init_funcs(hw, FALSE)) {
DPRINTK(PROBE, ERR, "Hardware Initialization Failure\n");
return -EIO;
}
#ifdef CONFIG_E1000_MQ
/* Number of supported queues.
* TODO: It's assumed num_rx_queues >= num_tx_queues, since multi-rx
* queues are much more interesting. Is it worth coding for the
* possibility (however improbable) of num_tx_queues > num_rx_queues?
*/
switch (hw->mac.type) {
case e1000_82571:
case e1000_82572:
case e1000_82573:
case e1000_80003es2lan:
adapter->num_tx_queues = 2;
adapter->num_rx_queues = 2;
break;
case e1000_ich8lan:
case e1000_ich9lan:
if ((adapter->hw.device_id == E1000_DEV_ID_ICH8_IGP_AMT) ||
(adapter->hw.device_id == E1000_DEV_ID_ICH8_IGP_M_AMT) ||
(adapter->hw.device_id == E1000_DEV_ID_ICH9_IGP_AMT)) {
adapter->num_tx_queues = 2;
adapter->num_rx_queues = 2;
break;
}
/* Fall through - remaining ICH SKUs do not support MQ */
default:
/* All hardware before 82571 only have 1 queue each for Rx/Tx.
* However, the 82571 family does not have MSI-X, so multi-
* queue isn't enabled.
* It'd be wise not to mess with this default case. :) */
adapter->num_tx_queues = 1;
adapter->num_rx_queues = 1;
netdev->egress_subqueue_count = 0;
break;
}
adapter->num_rx_queues = min(adapter->num_rx_queues, num_online_cpus());
adapter->num_tx_queues = min(adapter->num_tx_queues, num_online_cpus());
if ((adapter->num_tx_queues > 1) || (adapter->num_rx_queues > 1)) {
netdev->egress_subqueue = (struct net_device_subqueue *)
((void *)adapter +
sizeof(struct e1000_adapter));
netdev->egress_subqueue_count = adapter->num_tx_queues;
DPRINTK(DRV, INFO, "Multiqueue Enabled: RX queues = %u, "
"TX queues = %u\n", adapter->num_rx_queues,
adapter->num_tx_queues);
}
#else
adapter->num_tx_queues = 1;
adapter->num_rx_queues = 1;
#endif
if (e1000_alloc_queues(adapter)) {
DPRINTK(PROBE, ERR, "Unable to allocate memory for queues\n");
return -ENOMEM;
}
#ifdef CONFIG_E1000_NAPI
for (i = 0; i < adapter->num_rx_queues; i++) {
struct e1000_rx_ring *rx_ring = &adapter->rx_ring[i];
netif_napi_add(adapter->netdev, &rx_ring->napi, e1000_poll, 64);
}
rtdm_lock_init(&adapter->tx_queue_lock);
#ifdef CONFIG_E1000_MQ
for (i = 0; i < adapter->num_tx_queues; i++)
rtdm_lock_init(&adapter->tx_ring[i].tx_queue_lock);
#endif
#endif
/* Explicitly disable IRQ since the NIC can be in any state. */
atomic_set(&adapter->irq_sem, 0);
e1000_irq_disable(adapter);
rtdm_lock_init(&adapter->stats_lock);
set_bit(__E1000_DOWN, &adapter->state);
return 0;
}
/**
* e1000_alloc_queues - Allocate memory for all rings
* @adapter: board private structure to initialize
**/
static int e1000_alloc_queues(struct e1000_adapter *adapter)
{
adapter->tx_ring = kcalloc(adapter->num_tx_queues,
sizeof(struct e1000_tx_ring), GFP_KERNEL);
if (!adapter->tx_ring)
return -ENOMEM;
adapter->rx_ring = kcalloc(adapter->num_rx_queues,
sizeof(struct e1000_rx_ring), GFP_KERNEL);
if (!adapter->rx_ring) {
kfree(adapter->tx_ring);
return -ENOMEM;
}
#ifdef CONFIG_E1000_MQ
adapter->cpu_tx_ring = alloc_percpu(struct e1000_tx_ring *);
#endif
return E1000_SUCCESS;
}
#ifdef CONFIG_E1000_MQ
static void e1000_setup_queue_mapping(struct e1000_adapter *adapter)
{
int i, cpu;
lock_cpu_hotplug();
i = 0;
for_each_online_cpu(cpu) {
*per_cpu_ptr(adapter->cpu_tx_ring, cpu) =
&adapter->tx_ring[i % adapter->num_tx_queues];
i++;
}
unlock_cpu_hotplug();
}
#endif
/**
* e1000_intr_msi_test - Interrupt Handler
* @irq: interrupt number
* @data: pointer to a network interface device structure
**/
static irqreturn_t e1000_intr_msi_test(int irq, void *data)
{
struct net_device *netdev = data;
struct e1000_adapter *adapter = netdev_priv(netdev);
u32 icr = E1000_READ_REG(&adapter->hw, E1000_ICR);
DPRINTK(HW,INFO, "icr is %08X\n", icr);
if (icr & E1000_ICR_RXSEQ) {
adapter->flags |= E1000_FLAG_HAS_MSI;
wmb();
}
return IRQ_HANDLED;
}
/**
* e1000_test_msi_interrupt - Returns 0 for successful test
* @adapter: board private struct
*
* code flow taken from tg3.c
**/
static int e1000_test_msi_interrupt(struct e1000_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
int err;
/* poll_enable hasn't been called yet, so don't need disable */
/* clear any pending events */
E1000_READ_REG(&adapter->hw, E1000_ICR);
/* free the real vector and request a test handler */
e1000_free_irq(adapter);
err = pci_enable_msi(adapter->pdev);
err = request_irq(adapter->pdev->irq, &e1000_intr_msi_test, 0,
netdev->name, netdev);
if (err) {
pci_disable_msi(adapter->pdev);
goto msi_test_failed;
}
/* our temporary test variable */
adapter->flags &= ~E1000_FLAG_HAS_MSI;
wmb();
e1000_irq_enable(adapter);
/* fire an unusual interrupt on the test handler */
E1000_WRITE_REG(&adapter->hw, E1000_ICS, E1000_ICS_RXSEQ);
E1000_WRITE_FLUSH(&adapter->hw);
msleep(50);
e1000_irq_disable(adapter);
rmb();
if (!(adapter->flags & E1000_FLAG_HAS_MSI)) {
adapter->flags |= E1000_FLAG_HAS_MSI;
err = -EIO;
DPRINTK(HW, INFO, "MSI interrupt test failed!\n");
}
free_irq(adapter->pdev->irq, netdev);
pci_disable_msi(adapter->pdev);
if (err == -EIO)
goto msi_test_failed;
/* okay so the test worked, restore settings */
DPRINTK(HW, INFO, "MSI interrupt test succeeded!\n");
msi_test_failed:
/* restore the original vector, even if it failed */
e1000_request_irq(adapter);
return err;
}
/**
* e1000_test_msi - Returns 0 if MSI test succeeds and INTx mode is restored
* @adapter: board private struct
*
* code flow taken from tg3.c, called with e1000 interrupts disabled.
**/
static int e1000_test_msi(struct e1000_adapter *adapter)
{
int err;
u16 pci_cmd;
if (!(adapter->flags & E1000_FLAG_MSI_ENABLED) ||
!(adapter->flags & E1000_FLAG_HAS_MSI))
return 0;
/* disable SERR in case the MSI write causes a master abort */
pci_read_config_word(adapter->pdev, PCI_COMMAND, &pci_cmd);
pci_write_config_word(adapter->pdev, PCI_COMMAND,
pci_cmd & ~PCI_COMMAND_SERR);
err = e1000_test_msi_interrupt(adapter);
/* restore previous setting of command word */
pci_write_config_word(adapter->pdev, PCI_COMMAND, pci_cmd);
/* success ! */
if (!err)
return 0;
/* EIO means MSI test failed */
if (err != -EIO)
return err;
/* back to INTx mode */
DPRINTK(PROBE, WARNING, "MSI interrupt test failed, using legacy "
"interrupt.\n");
e1000_free_irq(adapter);
adapter->flags &= ~E1000_FLAG_HAS_MSI;
err = e1000_request_irq(adapter);
return err;
}
/**
* e1000_open - Called when a network interface is made active
* @netdev: network interface device structure
*
* Returns 0 on success, negative value on failure
*
* The open entry point is called when a network interface is made
* active by the system (IFF_UP). At this point all resources needed
* for transmit and receive operations are allocated, the interrupt
* handler is registered with the OS, the watchdog timer is started,
* and the stack is notified that the interface is ready.
**/
static int e1000_open(struct net_device *netdev)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
int err;
/* disallow open during test */
if (test_bit(__E1000_TESTING, &adapter->state))
return -EBUSY;
/* allocate transmit descriptors */
err = e1000_setup_all_tx_resources(adapter);
if (err)
goto err_setup_tx;
/* allocate receive descriptors */
err = e1000_setup_all_rx_resources(adapter);
if (err)
goto err_setup_rx;
if (adapter->hw.phy.media_type == e1000_media_type_copper) {
e1000_power_up_phy(&adapter->hw);
e1000_setup_link(&adapter->hw);
}
#ifdef NETIF_F_HW_VLAN_TX
adapter->mng_vlan_id = E1000_MNG_VLAN_NONE;
if ((adapter->hw.mng_cookie.status &
E1000_MNG_DHCP_COOKIE_STATUS_VLAN)) {
e1000_update_mng_vlan(adapter);
}
#endif
/* For 82573 and ICHx if AMT is enabled, let the firmware know
* that the network interface is now open */
if (((adapter->hw.mac.type == e1000_82573) ||
(adapter->hw.mac.type == e1000_ich8lan) ||
(adapter->hw.mac.type == e1000_ich9lan)) &&
e1000_check_mng_mode(&adapter->hw))
e1000_get_hw_control(adapter);
/* before we allocate an interrupt, we must be ready to handle it.
* Setting DEBUG_SHIRQ in the kernel makes it fire an interrupt
* as soon as we call pci_request_irq, so we have to setup our
* clean_rx handler before we do so. */
e1000_configure(adapter);
err = e1000_request_irq(adapter);
if (err)
goto err_req_irq;
/* work around PCIe errata with MSI interrupts causing some chipsets to
* ignore e1000 MSI messages, which means we need to test our MSI
* interrupt now */
err = e1000_test_msi(adapter);
if (err) {
DPRINTK(PROBE, ERR, "Interrupt allocation failed\n");
goto err_req_irq;
}
/* From here on the code is the same as e1000_up() */
clear_bit(__E1000_DOWN, &adapter->state);
e1000_napi_enable_all(adapter);
mod_timer(&adapter->watchdog_timer, jiffies);
e1000_irq_enable(adapter);
/* fire a link status change interrupt to start the watchdog */
E1000_WRITE_REG(&adapter->hw, E1000_ICS, E1000_ICS_LSC);
return E1000_SUCCESS;
err_req_irq:
e1000_release_hw_control(adapter);
/* Power down the PHY so no link is implied when interface is down *
* The PHY cannot be powered down if any of the following is TRUE *
* (a) WoL is enabled
* (b) AMT is active
* (c) SoL/IDER session is active */
if (!adapter->wol && adapter->hw.mac.type >= e1000_82540 &&
adapter->hw.phy.media_type == e1000_media_type_copper)
e1000_power_down_phy(&adapter->hw);
e1000_free_all_rx_resources(adapter);
err_setup_rx:
e1000_free_all_tx_resources(adapter);
err_setup_tx:
e1000_reset(adapter);
return err;
}
/**
* e1000_close - Disables a network interface
* @netdev: network interface device structure
*
* Returns 0, this is not allowed to fail
*
* The close entry point is called when an interface is de-activated
* by the OS. The hardware is still under the drivers control, but
* needs to be disabled. A global MAC reset is issued to stop the
* hardware, and all transmit and receive resources are freed.
**/
static int e1000_close(struct net_device *netdev)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
WARN_ON(test_bit(__E1000_RESETTING, &adapter->state));
e1000_down(adapter);
/* Power down the PHY so no link is implied when interface is down *
* The PHY cannot be powered down if any of the following is TRUE *
* (a) WoL is enabled
* (b) AMT is active
* (c) SoL/IDER session is active */
if (!adapter->wol && adapter->hw.mac.type >= e1000_82540 &&
adapter->hw.phy.media_type == e1000_media_type_copper)
e1000_power_down_phy(&adapter->hw);
e1000_free_irq(adapter);
e1000_free_all_tx_resources(adapter);
e1000_free_all_rx_resources(adapter);
#ifdef NETIF_F_HW_VLAN_TX
/* kill manageability vlan ID if supported, but not if a vlan with
* the same ID is registered on the host OS (let 8021q kill it) */
if ((adapter->hw.mng_cookie.status &
E1000_MNG_DHCP_COOKIE_STATUS_VLAN) &&
!(adapter->vlgrp &&
vlan_group_get_device(adapter->vlgrp, adapter->mng_vlan_id))) {
e1000_vlan_rx_kill_vid(netdev, adapter->mng_vlan_id);
}
#endif
/* For 82573 and ICHx if AMT is enabled, let the firmware know
* that the network interface is now closed */
if (((adapter->hw.mac.type == e1000_82573) ||
(adapter->hw.mac.type == e1000_ich8lan) ||
(adapter->hw.mac.type == e1000_ich9lan)) &&
e1000_check_mng_mode(&adapter->hw))
e1000_release_hw_control(adapter);
return 0;
}
/**
* e1000_check_64k_bound - check that memory doesn't cross 64kB boundary
* @adapter: address of board private structure
* @start: address of beginning of memory
* @len: length of memory
**/
static bool e1000_check_64k_bound(struct e1000_adapter *adapter,
void *start, unsigned long len)
{
unsigned long begin = (unsigned long) start;
unsigned long end = begin + len;
/* First rev 82545 and 82546 need to not allow any memory
* write location to cross 64k boundary due to errata 23 */
if (adapter->hw.mac.type == e1000_82545 ||
adapter->hw.mac.type == e1000_82546) {
return ((begin ^ (end - 1)) >> 16) != 0 ? FALSE : TRUE;
}
return TRUE;
}
/**
* e1000_setup_tx_resources - allocate Tx resources (Descriptors)
* @adapter: board private structure
* @tx_ring: tx descriptor ring (for a specific queue) to setup
*
* Return 0 on success, negative on failure
**/
static int e1000_setup_tx_resources(struct e1000_adapter *adapter,
struct e1000_tx_ring *tx_ring)
{
struct pci_dev *pdev = adapter->pdev;
int size;
size = sizeof(struct e1000_buffer) * tx_ring->count;
tx_ring->buffer_info = vmalloc(size);
if (!tx_ring->buffer_info) {
DPRINTK(PROBE, ERR,
"Unable to allocate memory for the transmit descriptor ring\n");
return -ENOMEM;
}
memset(tx_ring->buffer_info, 0, size);
/* round up to nearest 4K */
tx_ring->size = tx_ring->count * sizeof(struct e1000_tx_desc);
tx_ring->size = ALIGN(tx_ring->size, 4096);
tx_ring->desc = pci_alloc_consistent(pdev, tx_ring->size,
&tx_ring->dma);
if (!tx_ring->desc) {
setup_tx_desc_die:
vfree(tx_ring->buffer_info);
DPRINTK(PROBE, ERR,
"Unable to allocate memory for the transmit descriptor ring\n");
return -ENOMEM;
}
/* Fix for errata 23, can't cross 64kB boundary */
if (!e1000_check_64k_bound(adapter, tx_ring->desc, tx_ring->size)) {
void *olddesc = tx_ring->desc;
dma_addr_t olddma = tx_ring->dma;
DPRINTK(TX_ERR, ERR, "tx_ring align check failed: %u bytes "
"at %p\n", tx_ring->size, tx_ring->desc);
/* Try again, without freeing the previous */
tx_ring->desc = pci_alloc_consistent(pdev, tx_ring->size,
&tx_ring->dma);
/* Failed allocation, critical failure */
if (!tx_ring->desc) {
pci_free_consistent(pdev, tx_ring->size, olddesc,
olddma);
goto setup_tx_desc_die;
}
if (!e1000_check_64k_bound(adapter, tx_ring->desc,
tx_ring->size)) {
/* give up */
pci_free_consistent(pdev, tx_ring->size, tx_ring->desc,
tx_ring->dma);
pci_free_consistent(pdev, tx_ring->size, olddesc,
olddma);
DPRINTK(PROBE, ERR,
"Unable to allocate aligned memory "
"for the transmit descriptor ring\n");
vfree(tx_ring->buffer_info);
return -ENOMEM;
} else {
/* Free old allocation, new allocation was successful */
pci_free_consistent(pdev, tx_ring->size, olddesc,
olddma);
}
}
memset(tx_ring->desc, 0, tx_ring->size);
tx_ring->next_to_use = 0;
tx_ring->next_to_clean = 0;
rtdm_lock_init(&tx_ring->tx_lock);
return 0;
}
/**
* e1000_setup_all_tx_resources - wrapper to allocate Tx resources
* @adapter: board private structure
*
* this allocates tx resources for all queues, return 0 on success, negative
* on failure
**/
int e1000_setup_all_tx_resources(struct e1000_adapter *adapter)
{
int i, err = 0;
for (i = 0; i < adapter->num_tx_queues; i++) {
err = e1000_setup_tx_resources(adapter, &adapter->tx_ring[i]);
if (err) {
DPRINTK(PROBE, ERR,
"Allocation for Tx Queue %u failed\n", i);
for (i-- ; i >= 0; i--)
e1000_free_tx_resources(adapter,
&adapter->tx_ring[i]);
break;
}
}
return err;
}
/**
* e1000_configure_tx - Configure 8254x Transmit Unit after Reset
* @adapter: board private structure
*
* Configure the Tx unit of the MAC after a reset.
**/
static void e1000_configure_tx(struct e1000_adapter *adapter)
{
u64 tdba;
struct e1000_hw *hw = &adapter->hw;
u32 tdlen, tctl, tipg, tarc;
u32 ipgr1, ipgr2;
int i;
/* Setup the HW Tx Head and Tail descriptor pointers */
for (i = 0; i < adapter->num_tx_queues; i++) {
tdba = adapter->tx_ring[i].dma;
tdlen = adapter->tx_ring[i].count * sizeof(struct e1000_tx_desc);
E1000_WRITE_REG(hw, E1000_TDBAL(i), (tdba & 0x00000000ffffffffULL));
E1000_WRITE_REG(hw, E1000_TDBAH(i), (tdba >> 32));
E1000_WRITE_REG(hw, E1000_TDLEN(i), tdlen);
E1000_WRITE_REG(hw, E1000_TDH(i), 0);
E1000_WRITE_REG(hw, E1000_TDT(i), 0);
adapter->tx_ring[i].tdh = E1000_REGISTER(hw, E1000_TDH(i));
adapter->tx_ring[i].tdt = E1000_REGISTER(hw, E1000_TDT(i));
}
/* Set the default values for the Tx Inter Packet Gap timer */
if (adapter->hw.mac.type <= e1000_82547_rev_2 &&
(hw->phy.media_type == e1000_media_type_fiber ||
hw->phy.media_type == e1000_media_type_internal_serdes))
tipg = DEFAULT_82543_TIPG_IPGT_FIBER;
else
tipg = DEFAULT_82543_TIPG_IPGT_COPPER;
switch (hw->mac.type) {
case e1000_82542:
tipg = DEFAULT_82542_TIPG_IPGT;
ipgr1 = DEFAULT_82542_TIPG_IPGR1;
ipgr2 = DEFAULT_82542_TIPG_IPGR2;
break;
case e1000_80003es2lan:
ipgr1 = DEFAULT_82543_TIPG_IPGR1;
ipgr2 = DEFAULT_80003ES2LAN_TIPG_IPGR2;
break;
default:
ipgr1 = DEFAULT_82543_TIPG_IPGR1;
ipgr2 = DEFAULT_82543_TIPG_IPGR2;
break;
}
tipg |= ipgr1 << E1000_TIPG_IPGR1_SHIFT;
tipg |= ipgr2 << E1000_TIPG_IPGR2_SHIFT;
E1000_WRITE_REG(hw, E1000_TIPG, tipg);
/* Set the Tx Interrupt Delay register */
E1000_WRITE_REG(hw, E1000_TIDV, adapter->tx_int_delay);
if (adapter->flags & E1000_FLAG_HAS_INTR_MODERATION)
E1000_WRITE_REG(hw, E1000_TADV, adapter->tx_abs_int_delay);
/* Program the Transmit Control Register */
tctl = E1000_READ_REG(hw, E1000_TCTL);
tctl &= ~E1000_TCTL_CT;
tctl |= E1000_TCTL_PSP | E1000_TCTL_RTLC |
(E1000_COLLISION_THRESHOLD << E1000_CT_SHIFT);
if (hw->mac.type == e1000_82571 || hw->mac.type == e1000_82572) {
tarc = E1000_READ_REG(hw, E1000_TARC(0));
/* set the speed mode bit, we'll clear it if we're not at
* gigabit link later */
#define SPEED_MODE_BIT (1 << 21)
tarc |= SPEED_MODE_BIT;
E1000_WRITE_REG(hw, E1000_TARC(0), tarc);
} else if (hw->mac.type == e1000_80003es2lan) {
tarc = E1000_READ_REG(hw, E1000_TARC(0));
tarc |= 1;
E1000_WRITE_REG(hw, E1000_TARC(0), tarc);
tarc = E1000_READ_REG(hw, E1000_TARC(1));
tarc |= 1;
E1000_WRITE_REG(hw, E1000_TARC(1), tarc);
}
e1000_config_collision_dist(hw);
/* Setup Transmit Descriptor Settings for eop descriptor */
adapter->txd_cmd = E1000_TXD_CMD_EOP | E1000_TXD_CMD_IFCS;
/* only set IDE if we are delaying interrupts using the timers */
if (adapter->tx_int_delay)
adapter->txd_cmd |= E1000_TXD_CMD_IDE;
if (hw->mac.type < e1000_82543)
adapter->txd_cmd |= E1000_TXD_CMD_RPS;
else
adapter->txd_cmd |= E1000_TXD_CMD_RS;
/* Cache if we're 82544 running in PCI-X because we'll
* need this to apply a workaround later in the send path. */
if (hw->mac.type == e1000_82544 &&
hw->bus.type == e1000_bus_type_pcix)
adapter->pcix_82544 = 1;
E1000_WRITE_REG(hw, E1000_TCTL, tctl);
}
/**
* e1000_setup_rx_resources - allocate Rx resources (Descriptors)
* @adapter: board private structure
* @rx_ring: rx descriptor ring (for a specific queue) to setup
*
* Returns 0 on success, negative on failure
**/
static int e1000_setup_rx_resources(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring)
{
struct pci_dev *pdev = adapter->pdev;
int size, desc_len;
size = sizeof(struct e1000_rx_buffer) * rx_ring->count;
rx_ring->buffer_info = vmalloc(size);
if (!rx_ring->buffer_info) {
DPRINTK(PROBE, ERR,
"Unable to allocate memory for the receive descriptor ring\n");
return -ENOMEM;
}
memset(rx_ring->buffer_info, 0, size);
rx_ring->ps_page = kcalloc(rx_ring->count, sizeof(struct e1000_ps_page),
GFP_KERNEL);
if (!rx_ring->ps_page) {
vfree(rx_ring->buffer_info);
DPRINTK(PROBE, ERR,
"Unable to allocate memory for the receive descriptor ring\n");
return -ENOMEM;
}
rx_ring->ps_page_dma = kcalloc(rx_ring->count,
sizeof(struct e1000_ps_page_dma),
GFP_KERNEL);
if (!rx_ring->ps_page_dma) {
vfree(rx_ring->buffer_info);
kfree(rx_ring->ps_page);
DPRINTK(PROBE, ERR,
"Unable to allocate memory for the receive descriptor ring\n");
return -ENOMEM;
}
if (adapter->hw.mac.type <= e1000_82547_rev_2)
desc_len = sizeof(struct e1000_rx_desc);
else
desc_len = sizeof(union e1000_rx_desc_packet_split);
/* Round up to nearest 4K */
rx_ring->size = rx_ring->count * desc_len;
rx_ring->size = ALIGN(rx_ring->size, 4096);
rx_ring->desc = pci_alloc_consistent(pdev, rx_ring->size,
&rx_ring->dma);
if (!rx_ring->desc) {
DPRINTK(PROBE, ERR,
"Unable to allocate memory for the receive descriptor ring\n");
setup_rx_desc_die:
vfree(rx_ring->buffer_info);
kfree(rx_ring->ps_page);
kfree(rx_ring->ps_page_dma);
return -ENOMEM;
}
/* Fix for errata 23, can't cross 64kB boundary */
if (!e1000_check_64k_bound(adapter, rx_ring->desc, rx_ring->size)) {
void *olddesc = rx_ring->desc;
dma_addr_t olddma = rx_ring->dma;
DPRINTK(RX_ERR, ERR, "rx_ring align check failed: %u bytes "
"at %p\n", rx_ring->size, rx_ring->desc);
/* Try again, without freeing the previous */
rx_ring->desc = pci_alloc_consistent(pdev, rx_ring->size,
&rx_ring->dma);
/* Failed allocation, critical failure */
if (!rx_ring->desc) {
pci_free_consistent(pdev, rx_ring->size, olddesc,
olddma);
DPRINTK(PROBE, ERR,
"Unable to allocate memory "
"for the receive descriptor ring\n");
goto setup_rx_desc_die;
}
if (!e1000_check_64k_bound(adapter, rx_ring->desc,
rx_ring->size)) {
/* give up */
pci_free_consistent(pdev, rx_ring->size, rx_ring->desc,
rx_ring->dma);
pci_free_consistent(pdev, rx_ring->size, olddesc,
olddma);
DPRINTK(PROBE, ERR,
"Unable to allocate aligned memory "
"for the receive descriptor ring\n");
goto setup_rx_desc_die;
} else {
/* Free old allocation, new allocation was successful */
pci_free_consistent(pdev, rx_ring->size, olddesc,
olddma);
}
}
memset(rx_ring->desc, 0, rx_ring->size);
/* set up ring defaults */
rx_ring->next_to_clean = 0;
rx_ring->next_to_use = 0;
rx_ring->rx_skb_top = NULL;
rx_ring->adapter = adapter;
return 0;
}
/**
* e1000_setup_all_rx_resources - wrapper to allocate Rx resources
* @adapter: board private structure
*
* this allocates rx resources for all queues, return 0 on success, negative
* on failure
**/
int e1000_setup_all_rx_resources(struct e1000_adapter *adapter)
{
int i, err = 0;
for (i = 0; i < adapter->num_rx_queues; i++) {
err = e1000_setup_rx_resources(adapter, &adapter->rx_ring[i]);
if (err) {
DPRINTK(PROBE, ERR,
"Allocation for Rx Queue %u failed\n", i);
for (i-- ; i >= 0; i--)
e1000_free_rx_resources(adapter,
&adapter->rx_ring[i]);
break;
}
}
return err;
}
#define PAGE_USE_COUNT(S) (((S) >> PAGE_SHIFT) + \
(((S) & (PAGE_SIZE - 1)) ? 1 : 0))
/**
* e1000_setup_rctl - configure the receive control registers
* @adapter: Board private structure
**/
static void e1000_setup_rctl(struct e1000_adapter *adapter)
{
u32 rctl, rfctl;
u32 psrctl = 0;
#ifndef CONFIG_E1000_DISABLE_PACKET_SPLIT
u32 pages = 0;
#endif
rctl = E1000_READ_REG(&adapter->hw, E1000_RCTL);
rctl &= ~(3 << E1000_RCTL_MO_SHIFT);
rctl |= E1000_RCTL_EN | E1000_RCTL_BAM |
E1000_RCTL_LBM_NO | E1000_RCTL_RDMTS_HALF |
(adapter->hw.mac.mc_filter_type << E1000_RCTL_MO_SHIFT);
/* disable the stripping of CRC because it breaks
* BMC firmware connected over SMBUS
if (adapter->hw.mac.type > e1000_82543)
rctl |= E1000_RCTL_SECRC;
*/
if (e1000_tbi_sbp_enabled_82543(&adapter->hw))
rctl |= E1000_RCTL_SBP;
else
rctl &= ~E1000_RCTL_SBP;
if (adapter->netdev->mtu <= ETH_DATA_LEN)
rctl &= ~E1000_RCTL_LPE;
else
rctl |= E1000_RCTL_LPE;
/* Setup buffer sizes */
rctl &= ~E1000_RCTL_SZ_4096;
rctl |= E1000_RCTL_BSEX;
switch (adapter->rx_buffer_len) {
case E1000_RXBUFFER_256:
rctl |= E1000_RCTL_SZ_256;
rctl &= ~E1000_RCTL_BSEX;
break;
case E1000_RXBUFFER_512:
rctl |= E1000_RCTL_SZ_512;
rctl &= ~E1000_RCTL_BSEX;
break;
case E1000_RXBUFFER_1024:
rctl |= E1000_RCTL_SZ_1024;
rctl &= ~E1000_RCTL_BSEX;
break;
case E1000_RXBUFFER_2048:
default:
rctl |= E1000_RCTL_SZ_2048;
rctl &= ~E1000_RCTL_BSEX;
break;
case E1000_RXBUFFER_4096:
rctl |= E1000_RCTL_SZ_4096;
break;
case E1000_RXBUFFER_8192:
rctl |= E1000_RCTL_SZ_8192;
break;
case E1000_RXBUFFER_16384:
rctl |= E1000_RCTL_SZ_16384;
break;
}
#ifndef CONFIG_E1000_DISABLE_PACKET_SPLIT
/* 82571 and greater support packet-split where the protocol
* header is placed in skb->data and the packet data is
* placed in pages hanging off of skb_shinfo(skb)->nr_frags.
* In the case of a non-split, skb->data is linearly filled,
* followed by the page buffers. Therefore, skb->data is
* sized to hold the largest protocol header.
*/
/* allocations using alloc_page take too long for regular MTU
* so only enable packet split for jumbo frames */
pages = PAGE_USE_COUNT(adapter->netdev->mtu);
if ((adapter->hw.mac.type >= e1000_82571) && (pages <= 3) &&
PAGE_SIZE <= 16384 && (rctl & E1000_RCTL_LPE))
adapter->rx_ps_pages = pages;
else
adapter->rx_ps_pages = 0;
#endif
if (adapter->rx_ps_pages) {
/* Configure extra packet-split registers */
rfctl = E1000_READ_REG(&adapter->hw, E1000_RFCTL);
rfctl |= E1000_RFCTL_EXTEN;
/* disable packet split support for IPv6 extension headers,
* because some malformed IPv6 headers can hang the RX */
rfctl |= (E1000_RFCTL_IPV6_EX_DIS |
E1000_RFCTL_NEW_IPV6_EXT_DIS);
E1000_WRITE_REG(&adapter->hw, E1000_RFCTL, rfctl);
/* disable the stripping of CRC because it breaks
* BMC firmware connected over SMBUS */
rctl |= E1000_RCTL_DTYP_PS /* | E1000_RCTL_SECRC */;
psrctl |= adapter->rx_ps_bsize0 >>
E1000_PSRCTL_BSIZE0_SHIFT;
switch (adapter->rx_ps_pages) {
case 3:
psrctl |= PAGE_SIZE <<
E1000_PSRCTL_BSIZE3_SHIFT;
case 2:
psrctl |= PAGE_SIZE <<
E1000_PSRCTL_BSIZE2_SHIFT;
case 1:
psrctl |= PAGE_SIZE >>
E1000_PSRCTL_BSIZE1_SHIFT;
break;
}
E1000_WRITE_REG(&adapter->hw, E1000_PSRCTL, psrctl);
}
E1000_WRITE_REG(&adapter->hw, E1000_RCTL, rctl);
adapter->flags &= ~E1000_FLAG_RX_RESTART_NOW;
}
/**
* e1000_configure_rx - Configure 8254x Receive Unit after Reset
* @adapter: board private structure
*
* Configure the Rx unit of the MAC after a reset.
**/
static void e1000_configure_rx(struct e1000_adapter *adapter)
{
u64 rdba;
struct e1000_hw *hw = &adapter->hw;
u32 rdlen, rctl, rxcsum, ctrl_ext;
int i;
if (adapter->rx_ps_pages) {
/* this is a 32 byte descriptor */
rdlen = adapter->rx_ring[0].count *
sizeof(union e1000_rx_desc_packet_split);
adapter->clean_rx = e1000_clean_rx_irq_ps;
adapter->alloc_rx_buf = e1000_alloc_rx_buffers_ps;
#ifdef CONFIG_E1000_NAPI
} else if (adapter->netdev->mtu > MAXIMUM_ETHERNET_VLAN_SIZE) {
rdlen = adapter->rx_ring[0].count *
sizeof(struct e1000_rx_desc);
adapter->clean_rx = e1000_clean_jumbo_rx_irq;
adapter->alloc_rx_buf = e1000_alloc_jumbo_rx_buffers;
#endif
} else {
rdlen = adapter->rx_ring[0].count *
sizeof(struct e1000_rx_desc);
adapter->clean_rx = e1000_clean_rx_irq;
adapter->alloc_rx_buf = e1000_alloc_rx_buffers;
}
/* disable receives while setting up the descriptors */
rctl = E1000_READ_REG(hw, E1000_RCTL);
E1000_WRITE_REG(hw, E1000_RCTL, rctl & ~E1000_RCTL_EN);
E1000_WRITE_FLUSH(hw);
mdelay(10);
/* set the Receive Delay Timer Register */
E1000_WRITE_REG(hw, E1000_RDTR, adapter->rx_int_delay);
if (adapter->flags & E1000_FLAG_HAS_INTR_MODERATION) {
E1000_WRITE_REG(hw, E1000_RADV, adapter->rx_abs_int_delay);
if (adapter->itr_setting != 0)
E1000_WRITE_REG(hw, E1000_ITR,
1000000000 / (adapter->itr * 256));
}
if (hw->mac.type >= e1000_82571) {
ctrl_ext = E1000_READ_REG(hw, E1000_CTRL_EXT);
/* Reset delay timers after every interrupt */
ctrl_ext |= E1000_CTRL_EXT_INT_TIMER_CLR;
#ifdef CONFIG_E1000_NAPI
/* Auto-Mask interrupts upon ICR access */
ctrl_ext |= E1000_CTRL_EXT_IAME;
E1000_WRITE_REG(hw, E1000_IAM, 0xffffffff);
#endif
E1000_WRITE_REG(hw, E1000_CTRL_EXT, ctrl_ext);
E1000_WRITE_FLUSH(hw);
}
/* Setup the HW Rx Head and Tail Descriptor Pointers and
* the Base and Length of the Rx Descriptor Ring */
for (i = 0; i < adapter->num_rx_queues; i++) {
rdba = adapter->rx_ring[i].dma;
E1000_WRITE_REG(hw, E1000_RDBAL(i), (rdba & 0x00000000ffffffffULL));
E1000_WRITE_REG(hw, E1000_RDBAH(i), (rdba >> 32));
E1000_WRITE_REG(hw, E1000_RDLEN(i), rdlen);
E1000_WRITE_REG(hw, E1000_RDH(i), 0);
E1000_WRITE_REG(hw, E1000_RDT(i), 0);
adapter->rx_ring[i].rdh = E1000_REGISTER(hw, E1000_RDH(i));
adapter->rx_ring[i].rdt = E1000_REGISTER(hw, E1000_RDT(i));
}
#ifdef CONFIG_E1000_MQ
if (adapter->num_rx_queues > 1) {
u32 random[10];
u32 reta, mrqc;
int i;
get_random_bytes(&random[0], 40);
switch (adapter->num_rx_queues) {
default:
reta = 0x00800080;
mrqc = E1000_MRQC_ENABLE_RSS_2Q;
break;
}
/* Fill out redirection table */
for (i = 0; i < 32; i++)
E1000_WRITE_REG_ARRAY(hw, E1000_RETA, i, reta);
/* Fill out hash function seeds */
for (i = 0; i < 10; i++)
E1000_WRITE_REG_ARRAY(hw, E1000_RSSRK, i, random[i]);
mrqc |= (E1000_MRQC_RSS_FIELD_IPV4 |
E1000_MRQC_RSS_FIELD_IPV4_TCP);
E1000_WRITE_REG(hw, E1000_MRQC, mrqc);
/* Multiqueue and packet checksumming are mutually exclusive. */
rxcsum = E1000_READ_REG(hw, E1000_RXCSUM);
rxcsum |= E1000_RXCSUM_PCSD;
E1000_WRITE_REG(hw, E1000_RXCSUM, rxcsum);
} else if (hw->mac.type >= e1000_82543) {
#else
if (hw->mac.type >= e1000_82543) {
#endif /* CONFIG_E1000_MQ */
/* Enable 82543 Receive Checksum Offload for TCP and UDP */
rxcsum = E1000_READ_REG(hw, E1000_RXCSUM);
if (adapter->rx_csum == TRUE) {
rxcsum |= E1000_RXCSUM_TUOFL;
/* Enable 82571 IPv4 payload checksum for UDP fragments
* Must be used in conjunction with packet-split. */
if ((hw->mac.type >= e1000_82571) &&
(adapter->rx_ps_pages)) {
rxcsum |= E1000_RXCSUM_IPPCSE;
}
} else {
rxcsum &= ~E1000_RXCSUM_TUOFL;
/* don't need to clear IPPCSE as it defaults to 0 */
}
E1000_WRITE_REG(hw, E1000_RXCSUM, rxcsum);
}
/* Enable early receives on supported devices, only takes effect when
* packet size is equal or larger than the specified value (in 8 byte
* units), e.g. using jumbo frames when setting to E1000_ERT_2048 */
if ((hw->mac.type == e1000_82573 || hw->mac.type == e1000_ich9lan) &&
(adapter->netdev->mtu > ETH_DATA_LEN))
E1000_WRITE_REG(hw, E1000_ERT, E1000_ERT_2048);
/* Enable Receives */
E1000_WRITE_REG(hw, E1000_RCTL, rctl);
}
/**
* e1000_free_tx_resources - Free Tx Resources per Queue
* @adapter: board private structure
* @tx_ring: Tx descriptor ring for a specific queue
*
* Free all transmit software resources
**/
static void e1000_free_tx_resources(struct e1000_adapter *adapter,
struct e1000_tx_ring *tx_ring)
{
struct pci_dev *pdev = adapter->pdev;
e1000_clean_tx_ring(adapter, tx_ring);
vfree(tx_ring->buffer_info);
tx_ring->buffer_info = NULL;
pci_free_consistent(pdev, tx_ring->size, tx_ring->desc, tx_ring->dma);
tx_ring->desc = NULL;
}
/**
* e1000_free_all_tx_resources - Free Tx Resources for All Queues
* @adapter: board private structure
*
* Free all transmit software resources
**/
void e1000_free_all_tx_resources(struct e1000_adapter *adapter)
{
int i;
for (i = 0; i < adapter->num_tx_queues; i++)
e1000_free_tx_resources(adapter, &adapter->tx_ring[i]);
}
static void e1000_unmap_and_free_tx_resource(struct e1000_adapter *adapter,
struct e1000_buffer *buffer_info)
{
if (buffer_info->dma) {
pci_unmap_page(adapter->pdev,
buffer_info->dma,
buffer_info->length,
PCI_DMA_TODEVICE);
buffer_info->dma = 0;
}
if (buffer_info->skb) {
kfree_rtskb(buffer_info->skb);
buffer_info->skb = NULL;
}
/* buffer_info must be completely set up in the transmit path */
}
/**
* e1000_clean_tx_ring - Free Tx Buffers
* @adapter: board private structure
* @tx_ring: ring to be cleaned
**/
static void e1000_clean_tx_ring(struct e1000_adapter *adapter,
struct e1000_tx_ring *tx_ring)
{
struct e1000_buffer *buffer_info;
unsigned long size;
unsigned int i;
/* Free all the Tx ring sk_buffs */
for (i = 0; i < tx_ring->count; i++) {
buffer_info = &tx_ring->buffer_info[i];
e1000_unmap_and_free_tx_resource(adapter, buffer_info);
}
size = sizeof(struct e1000_buffer) * tx_ring->count;
memset(tx_ring->buffer_info, 0, size);
/* Zero out the descriptor ring */
memset(tx_ring->desc, 0, tx_ring->size);
tx_ring->next_to_use = 0;
tx_ring->next_to_clean = 0;
tx_ring->last_tx_tso = 0;
writel(0, adapter->hw.hw_addr + tx_ring->tdh);
writel(0, adapter->hw.hw_addr + tx_ring->tdt);
}
/**
* e1000_clean_all_tx_rings - Free Tx Buffers for all queues
* @adapter: board private structure
**/
static void e1000_clean_all_tx_rings(struct e1000_adapter *adapter)
{
int i;
for (i = 0; i < adapter->num_tx_queues; i++)
e1000_clean_tx_ring(adapter, &adapter->tx_ring[i]);
}
/**
* e1000_free_rx_resources - Free Rx Resources
* @adapter: board private structure
* @rx_ring: ring to clean the resources from
*
* Free all receive software resources
**/
static void e1000_free_rx_resources(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring)
{
struct pci_dev *pdev = adapter->pdev;
e1000_clean_rx_ring(adapter, rx_ring);
vfree(rx_ring->buffer_info);
rx_ring->buffer_info = NULL;
kfree(rx_ring->ps_page);
rx_ring->ps_page = NULL;
kfree(rx_ring->ps_page_dma);
rx_ring->ps_page_dma = NULL;
pci_free_consistent(pdev, rx_ring->size, rx_ring->desc, rx_ring->dma);
rx_ring->desc = NULL;
}
/**
* e1000_free_all_rx_resources - Free Rx Resources for All Queues
* @adapter: board private structure
*
* Free all receive software resources
**/
void e1000_free_all_rx_resources(struct e1000_adapter *adapter)
{
int i;
for (i = 0; i < adapter->num_rx_queues; i++)
e1000_free_rx_resources(adapter, &adapter->rx_ring[i]);
}
/**
* e1000_clean_rx_ring - Free Rx Buffers per Queue
* @adapter: board private structure
* @rx_ring: ring to free buffers from
**/
static void e1000_clean_rx_ring(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring)
{
struct e1000_rx_buffer *buffer_info;
struct e1000_ps_page *ps_page;
struct e1000_ps_page_dma *ps_page_dma;
struct pci_dev *pdev = adapter->pdev;
unsigned long size;
unsigned int i, j;
/* Free all the Rx ring sk_buffs */
for (i = 0; i < rx_ring->count; i++) {
buffer_info = &rx_ring->buffer_info[i];
if (buffer_info->dma &&
adapter->clean_rx == e1000_clean_rx_irq) {
pci_unmap_single(pdev, buffer_info->dma,
adapter->rx_buffer_len,
PCI_DMA_FROMDEVICE);
#ifdef CONFIG_E1000_NAPI
} else if (buffer_info->dma &&
adapter->clean_rx == e1000_clean_jumbo_rx_irq) {
pci_unmap_page(pdev, buffer_info->dma, PAGE_SIZE,
PCI_DMA_FROMDEVICE);
#endif
} else if (buffer_info->dma &&
adapter->clean_rx == e1000_clean_rx_irq_ps) {
pci_unmap_single(pdev, buffer_info->dma,
adapter->rx_ps_bsize0,
PCI_DMA_FROMDEVICE);
}
buffer_info->dma = 0;
if (buffer_info->page) {
put_page(buffer_info->page);
buffer_info->page = NULL;
}
if (buffer_info->skb) {
kfree_rtskb(buffer_info->skb);
buffer_info->skb = NULL;
}
ps_page = &rx_ring->ps_page[i];
ps_page_dma = &rx_ring->ps_page_dma[i];
for (j = 0; j < adapter->rx_ps_pages; j++) {
if (!ps_page->ps_page[j]) break;
pci_unmap_page(pdev,
ps_page_dma->ps_page_dma[j],
PAGE_SIZE, PCI_DMA_FROMDEVICE);
ps_page_dma->ps_page_dma[j] = 0;
put_page(ps_page->ps_page[j]);
ps_page->ps_page[j] = NULL;
}
}
#ifdef CONFIG_E1000_NAPI
/* there also may be some cached data from a chained receive */
if (rx_ring->rx_skb_top) {
kfree_rtskb(rx_ring->rx_skb_top);
rx_ring->rx_skb_top = NULL;
}
#endif
size = sizeof(struct e1000_rx_buffer) * rx_ring->count;
memset(rx_ring->buffer_info, 0, size);
size = sizeof(struct e1000_ps_page) * rx_ring->count;
memset(rx_ring->ps_page, 0, size);
size = sizeof(struct e1000_ps_page_dma) * rx_ring->count;
memset(rx_ring->ps_page_dma, 0, size);
/* Zero out the descriptor ring */
memset(rx_ring->desc, 0, rx_ring->size);
rx_ring->next_to_clean = 0;
rx_ring->next_to_use = 0;
writel(0, adapter->hw.hw_addr + rx_ring->rdh);
writel(0, adapter->hw.hw_addr + rx_ring->rdt);
}
/**
* e1000_clean_all_rx_rings - Free Rx Buffers for all queues
* @adapter: board private structure
**/
static void e1000_clean_all_rx_rings(struct e1000_adapter *adapter)
{
int i;
for (i = 0; i < adapter->num_rx_queues; i++)
e1000_clean_rx_ring(adapter, &adapter->rx_ring[i]);
}
/* The 82542 2.0 (revision 2) needs to have the receive unit in reset
* and memory write and invalidate disabled for certain operations
*/
#if 0
static void e1000_enter_82542_rst(struct e1000_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
u32 rctl;
if (adapter->hw.mac.type != e1000_82542)
return;
if (adapter->hw.revision_id != E1000_REVISION_2)
return;
e1000_pci_clear_mwi(&adapter->hw);
rctl = E1000_READ_REG(&adapter->hw, E1000_RCTL);
rctl |= E1000_RCTL_RST;
E1000_WRITE_REG(&adapter->hw, E1000_RCTL, rctl);
E1000_WRITE_FLUSH(&adapter->hw);
mdelay(5);
if (rtnetif_running(netdev))
e1000_clean_all_rx_rings(adapter);
}
static void e1000_leave_82542_rst(struct e1000_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
u32 rctl;
if (adapter->hw.mac.type != e1000_82542)
return;
if (adapter->hw.revision_id != E1000_REVISION_2)
return;
rctl = E1000_READ_REG(&adapter->hw, E1000_RCTL);
rctl &= ~E1000_RCTL_RST;
E1000_WRITE_REG(&adapter->hw, E1000_RCTL, rctl);
E1000_WRITE_FLUSH(&adapter->hw);
mdelay(5);
if (adapter->hw.bus.pci_cmd_word & PCI_COMMAND_INVALIDATE)
e1000_pci_set_mwi(&adapter->hw);
if (rtnetif_running(netdev)) {
/* No need to loop, because 82542 supports only 1 queue */
struct e1000_rx_ring *ring = &adapter->rx_ring[0];
e1000_configure_rx(adapter);
adapter->alloc_rx_buf(adapter, ring, E1000_DESC_UNUSED(ring));
}
}
/**
* e1000_set_mac - Change the Ethernet Address of the NIC
* @netdev: network interface device structure
* @p: pointer to an address structure
*
* Returns 0 on success, negative on failure
**/
static int e1000_set_mac(struct net_device *netdev, void *p)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
struct sockaddr *addr = p;
if (!is_valid_ether_addr(addr->sa_data))
return -EADDRNOTAVAIL;
/* 82542 2.0 needs to be in reset to write receive address registers */
if (adapter->hw.mac.type == e1000_82542)
e1000_enter_82542_rst(adapter);
memcpy(netdev->dev_addr, addr->sa_data, netdev->addr_len);
memcpy(adapter->hw.mac.addr, addr->sa_data, netdev->addr_len);
e1000_rar_set(&adapter->hw, adapter->hw.mac.addr, 0);
/* With 82571 controllers, LAA may be overwritten (with the default)
* due to controller reset from the other port. */
if (adapter->hw.mac.type == e1000_82571) {
/* activate the work around */
e1000_set_laa_state_82571(&adapter->hw, TRUE);
/* Hold a copy of the LAA in RAR[14] This is done so that
* between the time RAR[0] gets clobbered and the time it
* gets fixed (in e1000_watchdog), the actual LAA is in one
* of the RARs and no incoming packets directed to this port
* are dropped. Eventually the LAA will be in RAR[0] and
* RAR[14] */
e1000_rar_set(&adapter->hw,
adapter->hw.mac.addr,
adapter->hw.mac.rar_entry_count - 1);
}
if (adapter->hw.mac.type == e1000_82542)
e1000_leave_82542_rst(adapter);
return 0;
}
#endif
/**
* e1000_set_multi - Multicast and Promiscuous mode set
* @netdev: network interface device structure
*
* The set_multi entry point is called whenever the multicast address
* list or the network interface flags are updated. This routine is
* responsible for configuring the hardware for proper multicast,
* promiscuous mode, and all-multi behavior.
**/
static void e1000_set_multi(struct net_device *netdev)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
u32 rctl;
/* Check for Promiscuous and All Multicast modes */
rctl = E1000_READ_REG(hw, E1000_RCTL);
if (netdev->flags & IFF_PROMISC) {
rctl |= (E1000_RCTL_UPE | E1000_RCTL_MPE);
} else if (netdev->flags & IFF_ALLMULTI) {
rctl |= E1000_RCTL_MPE;
rctl &= ~E1000_RCTL_UPE;
} else {
rctl &= ~(E1000_RCTL_UPE | E1000_RCTL_MPE);
}
E1000_WRITE_REG(hw, E1000_RCTL, rctl);
}
/* Need to wait a few seconds after link up to get diagnostic information from
* the phy */
static void e1000_update_phy_info(unsigned long data)
{
struct e1000_adapter *adapter = (struct e1000_adapter *) data;
e1000_get_phy_info(&adapter->hw);
}
/**
* e1000_82547_tx_fifo_stall - Timer Call-back
* @data: pointer to adapter cast into an unsigned long
**/
static void e1000_82547_tx_fifo_stall(unsigned long data)
{
struct e1000_adapter *adapter = (struct e1000_adapter *) data;
struct net_device *netdev = adapter->netdev;
u32 tctl;
if (atomic_read(&adapter->tx_fifo_stall)) {
if ((E1000_READ_REG(&adapter->hw, E1000_TDT(0)) ==
E1000_READ_REG(&adapter->hw, E1000_TDH(0))) &&
(E1000_READ_REG(&adapter->hw, E1000_TDFT) ==
E1000_READ_REG(&adapter->hw, E1000_TDFH)) &&
(E1000_READ_REG(&adapter->hw, E1000_TDFTS) ==
E1000_READ_REG(&adapter->hw, E1000_TDFHS))) {
tctl = E1000_READ_REG(&adapter->hw, E1000_TCTL);
E1000_WRITE_REG(&adapter->hw, E1000_TCTL,
tctl & ~E1000_TCTL_EN);
E1000_WRITE_REG(&adapter->hw, E1000_TDFT,
adapter->tx_head_addr);
E1000_WRITE_REG(&adapter->hw, E1000_TDFH,
adapter->tx_head_addr);
E1000_WRITE_REG(&adapter->hw, E1000_TDFTS,
adapter->tx_head_addr);
E1000_WRITE_REG(&adapter->hw, E1000_TDFHS,
adapter->tx_head_addr);
E1000_WRITE_REG(&adapter->hw, E1000_TCTL, tctl);
E1000_WRITE_FLUSH(&adapter->hw);
adapter->tx_fifo_head = 0;
atomic_set(&adapter->tx_fifo_stall, 0);
rtnetif_wake_queue(netdev);
} else if (!test_bit(__E1000_DOWN, &adapter->state))
mod_timer(&adapter->tx_fifo_stall_timer, jiffies + 1);
}
}
static bool e1000_has_link(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
bool link_active = FALSE;
s32 ret_val = 0;
/* get_link_status is set on LSC (link status) interrupt or
* rx sequence error interrupt. get_link_status will stay
* false until the e1000_check_for_link establishes link
* for copper adapters ONLY
*/
switch (hw->phy.media_type) {
case e1000_media_type_copper:
if (hw->mac.get_link_status) {
ret_val = e1000_check_for_link(hw);
link_active = !hw->mac.get_link_status;
} else {
link_active = TRUE;
}
break;
case e1000_media_type_fiber:
ret_val = e1000_check_for_link(hw);
link_active = !!(E1000_READ_REG(hw, E1000_STATUS) &
E1000_STATUS_LU);
break;
case e1000_media_type_internal_serdes:
ret_val = e1000_check_for_link(hw);
link_active = adapter->hw.mac.serdes_has_link;
break;
default:
case e1000_media_type_unknown:
break;
}
if ((ret_val == E1000_ERR_PHY) && (hw->phy.type == e1000_phy_igp_3) &&
(E1000_READ_REG(&adapter->hw, E1000_CTRL) & E1000_PHY_CTRL_GBE_DISABLE)) {
/* See e1000_kmrn_lock_loss_workaround_ich8lan() */
DPRINTK(LINK, INFO,
"Gigabit has been disabled, downgrading speed\n");
}
return link_active;
}
static void e1000_enable_receives(struct e1000_adapter *adapter)
{
/* make sure the receive unit is started */
if ((adapter->flags & E1000_FLAG_RX_NEEDS_RESTART) &&
(adapter->flags & E1000_FLAG_RX_RESTART_NOW)) {
struct e1000_hw *hw = &adapter->hw;
u32 rctl = E1000_READ_REG(hw, E1000_RCTL);
E1000_WRITE_REG(hw, E1000_RCTL, rctl | E1000_RCTL_EN);
adapter->flags &= ~E1000_FLAG_RX_RESTART_NOW;
}
}
/**
* e1000_watchdog - Timer Call-back
* @data: pointer to adapter cast into an unsigned long
**/
static void e1000_watchdog(unsigned long data)
{
struct e1000_adapter *adapter = (struct e1000_adapter *) data;
/* Do the rest outside of interrupt context */
schedule_work(&adapter->watchdog_task);
}
static void e1000_watchdog_task(struct work_struct *work)
{
struct e1000_adapter *adapter = container_of(work,
struct e1000_adapter, watchdog_task);
struct net_device *netdev = adapter->netdev;
struct e1000_mac_info *mac = &adapter->hw.mac;
struct e1000_tx_ring *tx_ring;
u32 link, tctl;
int i, tx_pending = 0;
link = e1000_has_link(adapter);
if ((rtnetif_carrier_ok(netdev)) && link) {
e1000_enable_receives(adapter);
goto link_up;
}
if (mac->type == e1000_82573) {
e1000_enable_tx_pkt_filtering(&adapter->hw);
#ifdef NETIF_F_HW_VLAN_TX
if (adapter->mng_vlan_id != adapter->hw.mng_cookie.vlan_id)
e1000_update_mng_vlan(adapter);
#endif
}
if (link) {
if (!rtnetif_carrier_ok(netdev)) {
u32 ctrl;
bool txb2b = 1;
#ifdef SIOCGMIIPHY
/* update snapshot of PHY registers on LSC */
e1000_phy_read_status(adapter);
#endif
e1000_get_speed_and_duplex(&adapter->hw,
&adapter->link_speed,
&adapter->link_duplex);
ctrl = E1000_READ_REG(&adapter->hw, E1000_CTRL);
DPRINTK(LINK, INFO, "NIC Link is Up %d Mbps %s, "
"Flow Control: %s\n",
adapter->link_speed,
adapter->link_duplex == FULL_DUPLEX ?
"Full Duplex" : "Half Duplex",
((ctrl & E1000_CTRL_TFCE) && (ctrl &
E1000_CTRL_RFCE)) ? "RX/TX" : ((ctrl &
E1000_CTRL_RFCE) ? "RX" : ((ctrl &
E1000_CTRL_TFCE) ? "TX" : "None" )));
/* tweak tx_queue_len according to speed/duplex
* and adjust the timeout factor */
//netdev->tx_queue_len = adapter->tx_queue_len;
adapter->tx_timeout_factor = 1;
switch (adapter->link_speed) {
case SPEED_10:
txb2b = 0;
//netdev->tx_queue_len = 10;
adapter->tx_timeout_factor = 16;
break;
case SPEED_100:
txb2b = 0;
//netdev->tx_queue_len = 100;
/* maybe add some timeout factor ? */
break;
}
if ((mac->type == e1000_82571 ||
mac->type == e1000_82572) &&
txb2b == 0) {
u32 tarc0;
tarc0 = E1000_READ_REG(&adapter->hw, E1000_TARC(0));
tarc0 &= ~SPEED_MODE_BIT;
E1000_WRITE_REG(&adapter->hw, E1000_TARC(0), tarc0);
}
#ifdef NETIF_F_TSO
/* disable TSO for pcie and 10/100 speeds, to avoid
* some hardware issues */
if (!(adapter->flags & E1000_FLAG_TSO_FORCE) &&
adapter->hw.bus.type == e1000_bus_type_pci_express){
switch (adapter->link_speed) {
case SPEED_10:
case SPEED_100:
DPRINTK(PROBE,INFO,
"10/100 speed: disabling TSO\n");
netdev->features &= ~NETIF_F_TSO;
#ifdef NETIF_F_TSO6
netdev->features &= ~NETIF_F_TSO6;
#endif
break;
case SPEED_1000:
netdev->features |= NETIF_F_TSO;
#ifdef NETIF_F_TSO6
netdev->features |= NETIF_F_TSO6;
#endif
break;
default:
/* oops */
break;
}
}
#endif
/* enable transmits in the hardware, need to do this
* after setting TARC0 */
tctl = E1000_READ_REG(&adapter->hw, E1000_TCTL);
tctl |= E1000_TCTL_EN;
E1000_WRITE_REG(&adapter->hw, E1000_TCTL, tctl);
rtnetif_carrier_on(netdev);
rtnetif_wake_queue(netdev);
#ifdef CONFIG_E1000_MQ
if (netif_is_multiqueue(netdev))
for (i = 0; i < adapter->num_tx_queues; i++)
netif_wake_subqueue(netdev, i);
#endif
if (!test_bit(__E1000_DOWN, &adapter->state))
mod_timer(&adapter->phy_info_timer,
round_jiffies(jiffies + 2 * HZ));
adapter->smartspeed = 0;
}
} else {
if (rtnetif_carrier_ok(netdev)) {
adapter->link_speed = 0;
adapter->link_duplex = 0;
DPRINTK(LINK, INFO, "NIC Link is Down\n");
rtnetif_carrier_off(netdev);
rtnetif_stop_queue(netdev);
if (!test_bit(__E1000_DOWN, &adapter->state))
mod_timer(&adapter->phy_info_timer,
round_jiffies(jiffies + 2 * HZ));
/* 80003ES2LAN workaround--
* For packet buffer work-around on link down event;
* disable receives in the ISR and
* reset device here in the watchdog
*/
if (adapter->flags & E1000_FLAG_RX_NEEDS_RESTART)
/* reset device */
schedule_work(&adapter->reset_task);
}
e1000_smartspeed(adapter);
}
link_up:
e1000_update_stats(adapter);
mac->tx_packet_delta = adapter->stats.tpt - adapter->tpt_old;
adapter->tpt_old = adapter->stats.tpt;
mac->collision_delta = adapter->stats.colc - adapter->colc_old;
adapter->colc_old = adapter->stats.colc;
adapter->gorc = adapter->stats.gorc - adapter->gorc_old;
adapter->gorc_old = adapter->stats.gorc;
adapter->gotc = adapter->stats.gotc - adapter->gotc_old;
adapter->gotc_old = adapter->stats.gotc;
e1000_update_adaptive(&adapter->hw);
if (!rtnetif_carrier_ok(netdev)) {
for (i = 0 ; i < adapter->num_tx_queues ; i++) {
tx_ring = &adapter->tx_ring[i];
tx_pending |= (E1000_DESC_UNUSED(tx_ring) + 1 <
tx_ring->count);
}
if (tx_pending) {
/* We've lost link, so the controller stops DMA,
* but we've got queued Tx work that's never going
* to get done, so reset controller to flush Tx.
* (Do the reset outside of interrupt context). */
adapter->tx_timeout_count++;
schedule_work(&adapter->reset_task);
}
}
/* Cause software interrupt to ensure rx ring is cleaned */
E1000_WRITE_REG(&adapter->hw, E1000_ICS, E1000_ICS_RXDMT0);
/* Force detection of hung controller every watchdog period */
adapter->detect_tx_hung = TRUE;
/* With 82571 controllers, LAA may be overwritten due to controller
* reset from the other port. Set the appropriate LAA in RAR[0] */
if (e1000_get_laa_state_82571(&adapter->hw) == TRUE)
e1000_rar_set(&adapter->hw, adapter->hw.mac.addr, 0);
/* Reset the timer */
mod_timer(&adapter->watchdog_timer, jiffies + HZ);
}
enum latency_range {
lowest_latency = 0,
low_latency = 1,
bulk_latency = 2,
latency_invalid = 255
};
/**
* e1000_update_itr - update the dynamic ITR value based on statistics
* @adapter: pointer to adapter
* @itr_setting: current adapter->itr
* @packets: the number of packets during this measurement interval
* @bytes: the number of bytes during this measurement interval
*
* Stores a new ITR value based on packets and byte
* counts during the last interrupt. The advantage of per interrupt
* computation is faster updates and more accurate ITR for the current
* traffic pattern. Constants in this function were computed
* based on theoretical maximum wire speed and thresholds were set based
* on testing data as well as attempting to minimize response time
* while increasing bulk throughput.
* this functionality is controlled by the InterruptThrottleRate module
* parameter (see e1000_param.c)
**/
#if 0
static unsigned int e1000_update_itr(struct e1000_adapter *adapter,
u16 itr_setting, int packets,
int bytes)
{
unsigned int retval = itr_setting;
if (unlikely(!(adapter->flags & E1000_FLAG_HAS_INTR_MODERATION)))
goto update_itr_done;
if (packets == 0)
goto update_itr_done;
switch (itr_setting) {
case lowest_latency:
/* handle TSO and jumbo frames */
if (bytes/packets > 8000)
retval = bulk_latency;
else if ((packets < 5) && (bytes > 512)) {
retval = low_latency;
}
break;
case low_latency: /* 50 usec aka 20000 ints/s */
if (bytes > 10000) {
/* this if handles the TSO accounting */
if (bytes/packets > 8000) {
retval = bulk_latency;
} else if ((packets < 10) || ((bytes/packets) > 1200)) {
retval = bulk_latency;
} else if ((packets > 35)) {
retval = lowest_latency;
}
} else if (bytes/packets > 2000) {
retval = bulk_latency;
} else if (packets <= 2 && bytes < 512) {
retval = lowest_latency;
}
break;
case bulk_latency: /* 250 usec aka 4000 ints/s */
if (bytes > 25000) {
if (packets > 35) {
retval = low_latency;
}
} else if (bytes < 6000) {
retval = low_latency;
}
break;
}
update_itr_done:
return retval;
}
#endif
static void e1000_set_itr(struct e1000_adapter *adapter)
{
}
#define E1000_TX_FLAGS_CSUM 0x00000001
#define E1000_TX_FLAGS_VLAN 0x00000002
#define E1000_TX_FLAGS_TSO 0x00000004
#define E1000_TX_FLAGS_IPV4 0x00000008
#define E1000_TX_FLAGS_VLAN_MASK 0xffff0000
#define E1000_TX_FLAGS_VLAN_SHIFT 16
static int e1000_tso(struct e1000_adapter *adapter,
struct e1000_tx_ring *tx_ring, struct sk_buff *skb)
{
#ifdef NETIF_F_TSO
struct e1000_context_desc *context_desc;
struct e1000_buffer *buffer_info;
unsigned int i;
u32 cmd_length = 0;
u16 ipcse = 0, tucse, mss;
u8 ipcss, ipcso, tucss, tucso, hdr_len;
int err;
if (skb_is_gso(skb)) {
if (skb_header_cloned(skb)) {
err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
if (err)
return err;
}
hdr_len = skb_transport_offset(skb) + tcp_hdrlen(skb);
mss = skb_shinfo(skb)->gso_size;
if (skb->protocol == htons(ETH_P_IP)) {
struct iphdr *iph = ip_hdr(skb);
iph->tot_len = 0;
iph->check = 0;
tcp_hdr(skb)->check = ~csum_tcpudp_magic(iph->saddr,
iph->daddr, 0,
IPPROTO_TCP,
0);
cmd_length = E1000_TXD_CMD_IP;
ipcse = skb_transport_offset(skb) - 1;
#ifdef NETIF_F_TSO6
} else if (skb_shinfo(skb)->gso_type == SKB_GSO_TCPV6) {
ipv6_hdr(skb)->payload_len = 0;
tcp_hdr(skb)->check =
~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
&ipv6_hdr(skb)->daddr,
0, IPPROTO_TCP, 0);
ipcse = 0;
#endif
}
ipcss = skb_network_offset(skb);
ipcso = (void *)&(ip_hdr(skb)->check) - (void *)skb->data;
tucss = skb_transport_offset(skb);
tucso = (void *)&(tcp_hdr(skb)->check) - (void *)skb->data;
tucse = 0;
cmd_length |= (E1000_TXD_CMD_DEXT | E1000_TXD_CMD_TSE |
E1000_TXD_CMD_TCP | (skb->len - (hdr_len)));
i = tx_ring->next_to_use;
context_desc = E1000_CONTEXT_DESC(*tx_ring, i);
buffer_info = &tx_ring->buffer_info[i];
context_desc->lower_setup.ip_fields.ipcss = ipcss;
context_desc->lower_setup.ip_fields.ipcso = ipcso;
context_desc->lower_setup.ip_fields.ipcse = cpu_to_le16(ipcse);
context_desc->upper_setup.tcp_fields.tucss = tucss;
context_desc->upper_setup.tcp_fields.tucso = tucso;
context_desc->upper_setup.tcp_fields.tucse = cpu_to_le16(tucse);
context_desc->tcp_seg_setup.fields.mss = cpu_to_le16(mss);
context_desc->tcp_seg_setup.fields.hdr_len = hdr_len;
context_desc->cmd_and_length = cpu_to_le32(cmd_length);
buffer_info->time_stamp = jiffies;
buffer_info->next_to_watch = i;
if (++i == tx_ring->count) i = 0;
tx_ring->next_to_use = i;
return TRUE;
}
#endif
return FALSE;
}
static bool e1000_tx_csum(struct e1000_adapter *adapter,
struct e1000_tx_ring *tx_ring,
struct sk_buff *skb)
{
struct e1000_context_desc *context_desc;
struct e1000_buffer *buffer_info;
unsigned int i;
// u8 css;
u32 cmd_len = E1000_TXD_CMD_DEXT;
if (unlikely(skb->ip_summed != CHECKSUM_PARTIAL))
return FALSE;
switch (skb->protocol) {
case __constant_htons(ETH_P_IP):
break;
default:
if (unlikely(net_ratelimit())) {
DPRINTK(PROBE, WARNING, "checksum_partial proto=%x!\n",
skb->protocol);
}
break;
}
// css = skb_transport_offset(skb);
i = tx_ring->next_to_use;
buffer_info = &tx_ring->buffer_info[i];
context_desc = E1000_CONTEXT_DESC(*tx_ring, i);
context_desc->lower_setup.ip_config = 0;
context_desc->cmd_and_length = cpu_to_le32(cmd_len);
buffer_info->time_stamp = jiffies;
buffer_info->next_to_watch = i;
if (unlikely(++i == tx_ring->count)) i = 0;
tx_ring->next_to_use = i;
return TRUE;
}
#define E1000_MAX_TXD_PWR 12
#define E1000_MAX_DATA_PER_TXD (1<<E1000_MAX_TXD_PWR)
static int e1000_tx_map(struct e1000_adapter *adapter,
struct e1000_tx_ring *tx_ring,
struct sk_buff *skb, unsigned int first,
unsigned int max_per_txd, unsigned int nr_frags,
unsigned int mss)
{
struct e1000_buffer *buffer_info;
unsigned int len = skb->len;
unsigned int offset = 0, size, count = 0, i;
#ifdef MAX_SKB_FRAGS
unsigned int f;
len -= skb->data_len;
#endif
i = tx_ring->next_to_use;
while (len) {
buffer_info = &tx_ring->buffer_info[i];
size = min(len, max_per_txd);
#ifdef NETIF_F_TSO
/* Workaround for Controller erratum --
* descriptor for non-tso packet in a linear SKB that follows a
* tso gets written back prematurely before the data is fully
* DMA'd to the controller */
if (tx_ring->last_tx_tso && !skb_is_gso(skb)) {
tx_ring->last_tx_tso = 0;
if (!skb->data_len)
size -= 4;
}
/* Workaround for premature desc write-backs
* in TSO mode. Append 4-byte sentinel desc */
if (unlikely(mss && !nr_frags && size == len && size > 8))
size -= 4;
#endif
/* work-around for errata 10 and it applies
* to all controllers in PCI-X mode
* The fix is to make sure that the first descriptor of a
* packet is smaller than 2048 - 16 - 16 (or 2016) bytes
*/
if (unlikely((adapter->hw.bus.type == e1000_bus_type_pcix) &&
(size > 2015) && count == 0))
size = 2015;
/* Workaround for potential 82544 hang in PCI-X. Avoid
* terminating buffers within evenly-aligned dwords. */
if (unlikely(adapter->pcix_82544 &&
!((unsigned long)(skb->data + offset + size - 1) & 4) &&
size > 4))
size -= 4;
buffer_info->length = size;
/* set time_stamp *before* dma to help avoid a possible race */
buffer_info->time_stamp = jiffies;
buffer_info->dma =
pci_map_single(adapter->pdev,
skb->data + offset,
size,
PCI_DMA_TODEVICE);
buffer_info->next_to_watch = i;
len -= size;
offset += size;
count++;
if (unlikely(++i == tx_ring->count)) i = 0;
}
#ifdef MAX_SKB_FRAGS
for (f = 0; f < nr_frags; f++) {
struct skb_frag_struct *frag;
frag = &skb_shinfo(skb)->frags[f];
len = frag->size;
offset = frag->page_offset;
while (len) {
buffer_info = &tx_ring->buffer_info[i];
size = min(len, max_per_txd);
#ifdef NETIF_F_TSO
/* Workaround for premature desc write-backs
* in TSO mode. Append 4-byte sentinel desc */
if (unlikely(mss && f == (nr_frags-1) && size == len && size > 8))
size -= 4;
#endif
/* Workaround for potential 82544 hang in PCI-X.
* Avoid terminating buffers within evenly-aligned
* dwords. */
if (unlikely(adapter->pcix_82544 &&
!((unsigned long)(frag->page+offset+size-1) & 4) &&
size > 4))
size -= 4;
buffer_info->length = size;
buffer_info->time_stamp = jiffies;
buffer_info->dma =
pci_map_page(adapter->pdev,
frag->page,
offset,
size,
PCI_DMA_TODEVICE);
buffer_info->next_to_watch = i;
len -= size;
offset += size;
count++;
if (unlikely(++i == tx_ring->count)) i = 0;
}
}
#endif
i = (i == 0) ? tx_ring->count - 1 : i - 1;
tx_ring->buffer_info[i].skb = skb;
tx_ring->buffer_info[first].next_to_watch = i;
return count;
}
static void e1000_tx_queue(struct e1000_adapter *adapter,
struct e1000_tx_ring *tx_ring,
int tx_flags, int count, nanosecs_abs_t *xmit_stamp)
{
struct e1000_tx_desc *tx_desc = NULL;
struct e1000_buffer *buffer_info;
u32 txd_upper = 0, txd_lower = E1000_TXD_CMD_IFCS;
unsigned int i;
rtdm_lockctx_t context;
if (likely(tx_flags & E1000_TX_FLAGS_TSO)) {
txd_lower |= E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_D |
E1000_TXD_CMD_TSE;
txd_upper |= E1000_TXD_POPTS_TXSM << 8;
if (likely(tx_flags & E1000_TX_FLAGS_IPV4))
txd_upper |= E1000_TXD_POPTS_IXSM << 8;
}
if (likely(tx_flags & E1000_TX_FLAGS_CSUM)) {
txd_lower |= E1000_TXD_CMD_DEXT | E1000_TXD_DTYP_D;
txd_upper |= E1000_TXD_POPTS_TXSM << 8;
}
if (unlikely(tx_flags & E1000_TX_FLAGS_VLAN)) {
txd_lower |= E1000_TXD_CMD_VLE;
txd_upper |= (tx_flags & E1000_TX_FLAGS_VLAN_MASK);
}
i = tx_ring->next_to_use;
while (count--) {
buffer_info = &tx_ring->buffer_info[i];
tx_desc = E1000_TX_DESC(*tx_ring, i);
tx_desc->buffer_addr = cpu_to_le64(buffer_info->dma);
tx_desc->lower.data =
cpu_to_le32(txd_lower | buffer_info->length);
tx_desc->upper.data = cpu_to_le32(txd_upper);
if (unlikely(++i == tx_ring->count)) i = 0;
}
tx_desc->lower.data |= cpu_to_le32(adapter->txd_cmd);
rtdm_lock_irqsave(context);
if (xmit_stamp)
*xmit_stamp = cpu_to_be64(rtdm_clock_read() + *xmit_stamp);
/* Force memory writes to complete before letting h/w
* know there are new descriptors to fetch. (Only
* applicable for weak-ordered memory model archs,
* such as IA-64). */
wmb();
tx_ring->next_to_use = i;
writel(i, adapter->hw.hw_addr + tx_ring->tdt);
rtdm_lock_irqrestore(context);
/* we need this if more than one processor can write to our tail
* at a time, it synchronizes IO on IA64/Altix systems */
mmiowb();
}
#define E1000_FIFO_HDR 0x10
#define E1000_82547_PAD_LEN 0x3E0
/**
* 82547 workaround to avoid controller hang in half-duplex environment.
* The workaround is to avoid queuing a large packet that would span
* the internal Tx FIFO ring boundary by notifying the stack to resend
* the packet at a later time. This gives the Tx FIFO an opportunity to
* flush all packets. When that occurs, we reset the Tx FIFO pointers
* to the beginning of the Tx FIFO.
**/
static int e1000_82547_fifo_workaround(struct e1000_adapter *adapter,
struct sk_buff *skb)
{
u32 fifo_space = adapter->tx_fifo_size - adapter->tx_fifo_head;
u32 skb_fifo_len = skb->len + E1000_FIFO_HDR;
skb_fifo_len = ALIGN(skb_fifo_len, E1000_FIFO_HDR);
if (adapter->link_duplex != HALF_DUPLEX)
goto no_fifo_stall_required;
if (atomic_read(&adapter->tx_fifo_stall))
return 1;
if (skb_fifo_len >= (E1000_82547_PAD_LEN + fifo_space)) {
atomic_set(&adapter->tx_fifo_stall, 1);
return 1;
}
no_fifo_stall_required:
adapter->tx_fifo_head += skb_fifo_len;
if (adapter->tx_fifo_head >= adapter->tx_fifo_size)
adapter->tx_fifo_head -= adapter->tx_fifo_size;
return 0;
}
#define MINIMUM_DHCP_PACKET_SIZE 282
static int e1000_transfer_dhcp_info(struct e1000_adapter *adapter,
struct sk_buff *skb)
{
struct e1000_hw *hw = &adapter->hw;
u16 length, offset;
#ifdef NETIF_F_HW_VLAN_TX
if (vlan_tx_tag_present(skb)) {
if (!((vlan_tx_tag_get(skb) == adapter->hw.mng_cookie.vlan_id)
&& (adapter->hw.mng_cookie.status &
E1000_MNG_DHCP_COOKIE_STATUS_VLAN)))
return 0;
}
#endif
if (skb->len > MINIMUM_DHCP_PACKET_SIZE) {
struct ethhdr *eth = (struct ethhdr *) skb->data;
if ((htons(ETH_P_IP) == eth->h_proto)) {
const struct iphdr *ip =
(struct iphdr *)((u8 *)skb->data+14);
if (IPPROTO_UDP == ip->protocol) {
struct udphdr *udp =
(struct udphdr *)((u8 *)ip +
(ip->ihl << 2));
if (ntohs(udp->dest) == 67) {
offset = (u8 *)udp + 8 - skb->data;
length = skb->len - offset;
return e1000_mng_write_dhcp_info(hw,
(u8 *)udp + 8,
length);
}
}
}
}
return 0;
}
static int __e1000_maybe_stop_tx(struct net_device *netdev,
struct e1000_tx_ring *tx_ring, int size)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
rtnetif_stop_queue(netdev);
/* Herbert's original patch had:
* smp_mb__after_netif_stop_queue();
* but since that doesn't exist yet, just open code it. */
smp_mb();
/* We need to check again in a case another CPU has just
* made room available. */
if (likely(E1000_DESC_UNUSED(tx_ring) < size))
return -EBUSY;
/* A reprieve! */
rtnetif_start_queue(netdev);
++adapter->restart_queue;
return 0;
}
static int e1000_maybe_stop_tx(struct net_device *netdev,
struct e1000_tx_ring *tx_ring, int size)
{
if (likely(E1000_DESC_UNUSED(tx_ring) >= size))
return 0;
return __e1000_maybe_stop_tx(netdev, tx_ring, size);
}
#define TXD_USE_COUNT(S, X) (((S) >> (X)) + 1 )
static int e1000_xmit_frame_ring(struct sk_buff *skb,
struct net_device *netdev,
struct e1000_tx_ring *tx_ring)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
unsigned int first, max_per_txd = E1000_MAX_DATA_PER_TXD;
unsigned int max_txd_pwr = E1000_MAX_TXD_PWR;
unsigned int tx_flags = 0;
unsigned int len = skb->len;
unsigned long irq_flags;
unsigned int nr_frags = 0;
unsigned int mss = 0;
int count = 0;
int tso;
#ifdef MAX_SKB_FRAGS
unsigned int f;
len -= skb->data_len;
#endif
if (test_bit(__E1000_DOWN, &adapter->state)) {
kfree_rtskb(skb);
return NETDEV_TX_OK;
}
if (unlikely(skb->len <= 0)) {
kfree_rtskb(skb);
return NETDEV_TX_OK;
}
/* 82571 and newer doesn't need the workaround that limited descriptor
* length to 4kB */
if (adapter->hw.mac.type >= e1000_82571)
max_per_txd = 8192;
#ifdef NETIF_F_TSO
mss = skb_shinfo(skb)->gso_size;
/* The controller does a simple calculation to
* make sure there is enough room in the FIFO before
* initiating the DMA for each buffer. The calc is:
* 4 = ceil(buffer len/mss). To make sure we don't
* overrun the FIFO, adjust the max buffer len if mss
* drops. */
if (mss) {
u8 hdr_len;
max_per_txd = min(mss << 2, max_per_txd);
max_txd_pwr = fls(max_per_txd) - 1;
/* TSO Workaround for 82571/2/3 Controllers -- if skb->data
* points to just header, pull a few bytes of payload from
* frags into skb->data */
hdr_len = skb_transport_offset(skb) + tcp_hdrlen(skb);
if (skb->data_len && (hdr_len == (skb->len - skb->data_len))) {
switch (adapter->hw.mac.type) {
unsigned int pull_size;
case e1000_82544:
/* Make sure we have room to chop off 4 bytes,
* and that the end alignment will work out to
* this hardware's requirements
* NOTE: this is a TSO only workaround
* if end byte alignment not correct move us
* into the next dword */
if ((unsigned long)(skb_tail_pointer(skb) - 1) & 4)
break;
/* fall through */
case e1000_82571:
case e1000_82572:
case e1000_82573:
case e1000_ich8lan:
case e1000_ich9lan:
pull_size = min((unsigned int)4, skb->data_len);
if (!__pskb_pull_tail(skb, pull_size)) {
DPRINTK(DRV, ERR,
"__pskb_pull_tail failed.\n");
kfree_rtskb(skb);
return NETDEV_TX_OK;
}
len = skb->len - skb->data_len;
break;
default:
/* do nothing */
break;
}
}
}
/* reserve a descriptor for the offload context */
if ((mss) || (skb->ip_summed == CHECKSUM_PARTIAL))
count++;
count++;
#else
if (skb->ip_summed == CHECKSUM_PARTIAL)
count++;
#endif
#ifdef NETIF_F_TSO
/* Controller Erratum workaround */
if (!skb->data_len && tx_ring->last_tx_tso && !skb_is_gso(skb))
count++;
#endif
count += TXD_USE_COUNT(len, max_txd_pwr);
if (adapter->pcix_82544)
count++;
/* work-around for errata 10 and it applies to all controllers
* in PCI-X mode, so add one more descriptor to the count
*/
if (unlikely((adapter->hw.bus.type == e1000_bus_type_pcix) &&
(len > 2015)))
count++;
#ifdef MAX_SKB_FRAGS
nr_frags = skb_shinfo(skb)->nr_frags;
for (f = 0; f < nr_frags; f++)
count += TXD_USE_COUNT(skb_shinfo(skb)->frags[f].size,
max_txd_pwr);
if (adapter->pcix_82544)
count += nr_frags;
#endif
if (adapter->hw.mac.tx_pkt_filtering &&
(adapter->hw.mac.type == e1000_82573))
e1000_transfer_dhcp_info(adapter, skb);
#ifdef NETIF_F_LLTX
rtdm_lock_get_irqsave(&tx_ring->tx_lock, irq_flags);
#else
rtdm_lock_get_irqsave(&tx_ring->tx_lock, irq_flags);
#endif
/* need: count + 2 desc gap to keep tail from touching
* head, otherwise try next time */
if (unlikely(e1000_maybe_stop_tx(netdev, tx_ring, count + 2))) {
rtdm_lock_put_irqrestore(&tx_ring->tx_lock, irq_flags);
rtdm_printk("FATAL: rt_e1000 ran into tail close to head situation!\n");
return NETDEV_TX_BUSY;
}
if (unlikely(adapter->hw.mac.type == e1000_82547)) {
if (unlikely(e1000_82547_fifo_workaround(adapter, skb))) {
rtnetif_stop_queue(netdev);
rtdm_lock_put_irqrestore(&tx_ring->tx_lock, irq_flags);
if (!test_bit(__E1000_DOWN, &adapter->state))
mod_timer(&adapter->tx_fifo_stall_timer,
jiffies + 1);
rtdm_lock_put_irqrestore(&tx_ring->tx_lock, irq_flags);
rtdm_printk("FATAL: rt_e1000 ran into tail 82547 controller bug!\n");
return NETDEV_TX_BUSY;
}
}
#ifndef NETIF_F_LLTX
rtdm_lock_put_irqrestore(&tx_ring->tx_lock, irq_flags);
#endif
#ifdef NETIF_F_HW_VLAN_TX
if (unlikely(adapter->vlgrp && vlan_tx_tag_present(skb))) {
tx_flags |= E1000_TX_FLAGS_VLAN;
tx_flags |= (vlan_tx_tag_get(skb) << E1000_TX_FLAGS_VLAN_SHIFT);
}
#endif
first = tx_ring->next_to_use;
tso = e1000_tso(adapter, tx_ring, skb);
if (tso < 0) {
kfree_rtskb(skb);
#ifdef NETIF_F_LLTX
rtdm_lock_put_irqrestore(&tx_ring->tx_lock, irq_flags);
#endif
return NETDEV_TX_OK;
}
if (likely(tso)) {
tx_ring->last_tx_tso = 1;
tx_flags |= E1000_TX_FLAGS_TSO;
} else if (likely(e1000_tx_csum(adapter, tx_ring, skb)))
tx_flags |= E1000_TX_FLAGS_CSUM;
/* Old method was to assume IPv4 packet by default if TSO was enabled.
* 82571 hardware supports TSO capabilities for IPv6 as well...
* no longer assume, we must. */
if (likely(skb->protocol == htons(ETH_P_IP)))
tx_flags |= E1000_TX_FLAGS_IPV4;
e1000_tx_queue(adapter, tx_ring, tx_flags,
e1000_tx_map(adapter, tx_ring, skb, first,
max_per_txd, nr_frags, mss),
skb->xmit_stamp);
// netdev->trans_start = jiffies;
/* Make sure there is space in the ring for the next send. */
// e1000_maybe_stop_tx(netdev, tx_ring, MAX_SKB_FRAGS + 2);
#ifdef NETIF_F_LLTX
rtdm_lock_put_irqrestore(&tx_ring->tx_lock, irq_flags);
#endif
return NETDEV_TX_OK;
}
static int e1000_xmit_frame(struct sk_buff *skb, struct net_device *netdev)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_tx_ring *tx_ring = adapter->tx_ring;
/* This goes back to the question of how to logically map a tx queue
* to a flow. Right now, performance is impacted slightly negatively
* if using multiple tx queues. If the stack breaks away from a
* single qdisc implementation, we can look at this again. */
return (e1000_xmit_frame_ring(skb, netdev, tx_ring));
}
#ifdef CONFIG_E1000_MQ
static int e1000_subqueue_xmit_frame(struct sk_buff *skb,
struct net_device *netdev, int queue)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_tx_ring *tx_ring = &adapter->tx_ring[queue];
return (e1000_xmit_frame_ring(skb, netdev, tx_ring));
}
#endif
/**
* e1000_tx_timeout - Respond to a Tx Hang
* @netdev: network interface device structure
**/
#if 0
static void e1000_tx_timeout(struct net_device *netdev)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
/* Do the reset outside of interrupt context */
adapter->tx_timeout_count++;
schedule_work(&adapter->reset_task);
}
#endif
static void e1000_reset_task(struct work_struct *work)
{
struct e1000_adapter *adapter;
adapter = container_of(work, struct e1000_adapter, reset_task);
e1000_reinit_locked(adapter);
}
#if 0
/**
* e1000_get_stats - Get System Network Statistics
* @netdev: network interface device structure
*
* Returns the address of the device statistics structure.
* The statistics are actually updated from the timer callback.
**/
static struct net_device_stats * e1000_get_stats(struct net_device *netdev)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
/* only return the current stats */
return &adapter->net_stats;
}
/**
* e1000_change_mtu - Change the Maximum Transfer Unit
* @netdev: network interface device structure
* @new_mtu: new value for maximum frame size
*
* Returns 0 on success, negative on failure
**/
static int e1000_change_mtu(struct net_device *netdev, int new_mtu)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
int max_frame = new_mtu + ETH_HLEN + ETHERNET_FCS_SIZE;
u16 eeprom_data = 0;
if ((max_frame < ETH_ZLEN + ETHERNET_FCS_SIZE) ||
(max_frame > MAX_JUMBO_FRAME_SIZE)) {
DPRINTK(PROBE, ERR, "Invalid MTU setting\n");
return -EINVAL;
}
/* Adapter-specific max frame size limits. */
switch (adapter->hw.mac.type) {
case e1000_undefined:
case e1000_82542:
case e1000_ich8lan:
if (max_frame > ETH_FRAME_LEN + ETHERNET_FCS_SIZE) {
DPRINTK(PROBE, ERR, "Jumbo Frames not supported.\n");
return -EINVAL;
}
break;
case e1000_82573:
/* Jumbo Frames not supported if:
* - this is not an 82573L device
* - ASPM is enabled in any way (0x1A bits 3:2) */
e1000_read_nvm(&adapter->hw, NVM_INIT_3GIO_3, 1, &eeprom_data);
if ((adapter->hw.device_id != E1000_DEV_ID_82573L) ||
(eeprom_data & NVM_WORD1A_ASPM_MASK)) {
if (max_frame > ETH_FRAME_LEN + ETHERNET_FCS_SIZE) {
DPRINTK(PROBE, ERR,
"Jumbo Frames not supported.\n");
return -EINVAL;
}
break;
}
/* ERT will be enabled later to enable wire speed receives */
/* fall through to get support */
case e1000_ich9lan:
if ((adapter->hw.phy.type == e1000_phy_ife) &&
(max_frame > ETH_FRAME_LEN + ETHERNET_FCS_SIZE)) {
DPRINTK(PROBE, ERR, "Jumbo Frames not supported.\n");
return -EINVAL;
}
/* fall through to get support */
case e1000_82571:
case e1000_82572:
case e1000_80003es2lan:
#define MAX_STD_JUMBO_FRAME_SIZE 9234
if (max_frame > MAX_STD_JUMBO_FRAME_SIZE) {
DPRINTK(PROBE, ERR, "MTU > 9216 not supported.\n");
return -EINVAL;
}
break;
default:
/* Capable of supporting up to MAX_JUMBO_FRAME_SIZE limit. */
break;
}
while (test_and_set_bit(__E1000_RESETTING, &adapter->state))
msleep(1);
/* e1000_down has a dependency on max_frame_size */
adapter->max_frame_size = max_frame;
if (rtnetif_running(netdev))
e1000_down(adapter);
/* NOTE: netdev_alloc_skb reserves 16 bytes, and typically NET_IP_ALIGN
* means we reserve 2 more, this pushes us to allocate from the next
* larger slab size.
* i.e. RXBUFFER_2048 --> size-4096 slab
* however with the new *_jumbo_rx* routines, jumbo receives will use
* fragmented skbs */
if (max_frame <= E1000_RXBUFFER_256)
adapter->rx_buffer_len = E1000_RXBUFFER_256;
else if (max_frame <= E1000_RXBUFFER_512)
adapter->rx_buffer_len = E1000_RXBUFFER_512;
else if (max_frame <= E1000_RXBUFFER_1024)
adapter->rx_buffer_len = E1000_RXBUFFER_1024;
else if (max_frame <= E1000_RXBUFFER_2048)
adapter->rx_buffer_len = E1000_RXBUFFER_2048;
#ifdef CONFIG_E1000_NAPI
else
adapter->rx_buffer_len = E1000_RXBUFFER_4096;
#else
else if (max_frame <= E1000_RXBUFFER_4096)
adapter->rx_buffer_len = E1000_RXBUFFER_4096;
else if (max_frame <= E1000_RXBUFFER_8192)
adapter->rx_buffer_len = E1000_RXBUFFER_8192;
else if (max_frame <= E1000_RXBUFFER_16384)
adapter->rx_buffer_len = E1000_RXBUFFER_16384;
#endif
/* adjust allocation if LPE protects us, and we aren't using SBP */
if (!e1000_tbi_sbp_enabled_82543(&adapter->hw) &&
((max_frame == ETH_FRAME_LEN + ETHERNET_FCS_SIZE) ||
(max_frame == MAXIMUM_ETHERNET_VLAN_SIZE)))
adapter->rx_buffer_len = MAXIMUM_ETHERNET_VLAN_SIZE;
DPRINTK(PROBE, INFO, "changing MTU from %d to %d\n",
netdev->mtu, new_mtu);
netdev->mtu = new_mtu;
if (rtnetif_running(netdev))
e1000_up(adapter);
else
e1000_reset(adapter);
clear_bit(__E1000_RESETTING, &adapter->state);
return 0;
}
#endif
/**
* e1000_update_stats - Update the board statistics counters
* @adapter: board private structure
**/
void e1000_update_stats(struct e1000_adapter *adapter)
{
}
#ifdef SIOCGMIIPHY
/**
* e1000_phy_read_status - Update the PHY register status snapshot
* @adapter: board private structure
**/
static void e1000_phy_read_status(struct e1000_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
struct e1000_phy_regs *phy = &adapter->phy_regs;
int ret_val = E1000_SUCCESS;
unsigned long irq_flags;
rtdm_lock_get_irqsave(&adapter->stats_lock, irq_flags);
if (E1000_READ_REG(hw, E1000_STATUS)& E1000_STATUS_LU) {
ret_val = e1000_read_phy_reg(hw, PHY_CONTROL, &phy->bmcr);
ret_val |= e1000_read_phy_reg(hw, PHY_STATUS, &phy->bmsr);
ret_val |= e1000_read_phy_reg(hw, PHY_AUTONEG_ADV,
&phy->advertise);
ret_val |= e1000_read_phy_reg(hw, PHY_LP_ABILITY, &phy->lpa);
ret_val |= e1000_read_phy_reg(hw, PHY_AUTONEG_EXP,
&phy->expansion);
ret_val |= e1000_read_phy_reg(hw, PHY_1000T_CTRL,
&phy->ctrl1000);
ret_val |= e1000_read_phy_reg(hw, PHY_1000T_STATUS,
&phy->stat1000);
ret_val |= e1000_read_phy_reg(hw, PHY_EXT_STATUS,
&phy->estatus);
if (ret_val)
DPRINTK(DRV, WARNING, "Error reading PHY register\n");
} else {
/* Do not read PHY registers if link is not up
* Set values to typical power-on defaults */
phy->bmcr = (BMCR_SPEED1000 | BMCR_ANENABLE | BMCR_FULLDPLX);
phy->bmsr = (BMSR_100FULL | BMSR_100HALF | BMSR_10FULL |
BMSR_10HALF | BMSR_ESTATEN | BMSR_ANEGCAPABLE |
BMSR_ERCAP);
phy->advertise = (ADVERTISE_PAUSE_ASYM | ADVERTISE_PAUSE_CAP |
ADVERTISE_ALL | ADVERTISE_CSMA);
phy->lpa = 0;
phy->expansion = EXPANSION_ENABLENPAGE;
phy->ctrl1000 = ADVERTISE_1000FULL;
phy->stat1000 = 0;
phy->estatus = (ESTATUS_1000_TFULL | ESTATUS_1000_THALF);
}
rtdm_lock_put_irqrestore(&adapter->stats_lock, irq_flags);
}
#endif
/**
* e1000_intr_msi - Interrupt Handler
* @irq: interrupt number
* @data: pointer to a network interface device structure
**/
static int e1000_intr_msi(rtdm_irq_t *irq_handle)
{
struct rtnet_device *netdev = rtdm_irq_get_arg(irq_handle, struct rtnet_device);
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
#ifndef CONFIG_E1000_NAPI
int i, j;
int rx_cleaned, tx_cleaned;
#endif
u32 icr = E1000_READ_REG(hw, E1000_ICR);
nanosecs_abs_t time_stamp = rtdm_clock_read();
#ifdef CONFIG_E1000_NAPI
/* read ICR disables interrupts using IAM, so keep up with our
* enable/disable accounting */
atomic_inc(&adapter->irq_sem);
#endif
if (icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC)) {
hw->mac.get_link_status = 1;
/* ICH8 workaround-- Call gig speed drop workaround on cable
* disconnect (LSC) before accessing any PHY registers */
if ((hw->mac.type == e1000_ich8lan) &&
(hw->phy.type == e1000_phy_igp_3) &&
(!(E1000_READ_REG(hw, E1000_STATUS) & E1000_STATUS_LU)))
e1000_gig_downshift_workaround_ich8lan(hw);
/* 80003ES2LAN workaround-- For packet buffer work-around on
* link down event; disable receives here in the ISR and reset
* adapter in watchdog */
if (rtnetif_carrier_ok(netdev) &&
(adapter->flags & E1000_FLAG_RX_NEEDS_RESTART)) {
/* disable receives */
u32 rctl = E1000_READ_REG(hw, E1000_RCTL);
E1000_WRITE_REG(hw, E1000_RCTL, rctl & ~E1000_RCTL_EN);
adapter->flags |= E1000_FLAG_RX_RESTART_NOW;
}
/* guard against interrupt when we're going down */
//if (!test_bit(__E1000_DOWN, &adapter->state))
// mod_timer(&adapter->watchdog_timer, jiffies + 1);
}
#ifdef CONFIG_E1000_NAPI
/* XXX only using ring 0 for napi */
if (likely(netif_rx_schedule_prep(netdev, &adapter->rx_ring[0].napi))) {
adapter->total_tx_bytes = 0;
adapter->total_tx_packets = 0;
adapter->total_rx_bytes = 0;
adapter->total_rx_packets = 0;
__netif_rx_schedule(netdev, &adapter->rx_ring[0].napi);
} else {
atomic_dec(&adapter->irq_sem);
}
#else
adapter->total_tx_bytes = 0;
adapter->total_rx_bytes = 0;
adapter->total_tx_packets = 0;
adapter->total_rx_packets = 0;
adapter->data_received = 0;
for (i = 0; i < E1000_MAX_INTR; i++) {
rx_cleaned = 0;
for (j = 0; j < adapter->num_rx_queues; j++)
rx_cleaned |= adapter->clean_rx(adapter,
&adapter->rx_ring[j], &time_stamp);
tx_cleaned = 0;
for (j = 0 ; j < adapter->num_tx_queues ; j++)
tx_cleaned |= e1000_clean_tx_irq(adapter,
&adapter->tx_ring[j]);
if (!rx_cleaned && !tx_cleaned)
break;
}
if (likely(adapter->itr_setting & 3))
e1000_set_itr(adapter);
#endif
if (adapter->data_received)
rt_mark_stack_mgr(netdev);
return RTDM_IRQ_HANDLED;
}
/**
* e1000_intr - Interrupt Handler
* @irq: interrupt number
* @data: pointer to a network interface device structure
**/
static int e1000_intr(rtdm_irq_t *irq_handle)
{
struct rtnet_device *netdev = rtdm_irq_get_arg(irq_handle, struct rtnet_device);
struct e1000_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
u32 rctl, icr = E1000_READ_REG(hw, E1000_ICR);
#ifndef CONFIG_E1000_NAPI
int i, j;
int rx_cleaned, tx_cleaned;
#endif
nanosecs_abs_t time_stamp = rtdm_clock_read();
if (unlikely(!icr))
return RTDM_IRQ_NONE; /* Not our interrupt */
#ifdef CONFIG_E1000_NAPI
/* IMS will not auto-mask if INT_ASSERTED is not set, and if it is
* not set, then the adapter didn't send an interrupt */
if ((adapter->flags & E1000_FLAG_INT_ASSERT_AUTO_MASK) &&
!(icr & E1000_ICR_INT_ASSERTED))
return IRQ_NONE;
/* Interrupt Auto-Mask...upon reading ICR,
* interrupts are masked. No need for the
* IMC write, but it does mean we should
* account for it ASAP. */
if (likely(hw->mac.type >= e1000_82571))
atomic_inc(&adapter->irq_sem);
#endif
if (unlikely(icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC))) {
hw->mac.get_link_status = 1;
/* ICH8 workaround-- Call gig speed drop workaround on cable
* disconnect (LSC) before accessing any PHY registers */
if ((hw->mac.type == e1000_ich8lan) &&
(hw->phy.type == e1000_phy_igp_3) &&
(!(E1000_READ_REG(hw, E1000_STATUS) & E1000_STATUS_LU)))
e1000_gig_downshift_workaround_ich8lan(hw);
/* 80003ES2LAN workaround--
* For packet buffer work-around on link down event;
* disable receives here in the ISR and
* reset adapter in watchdog
*/
if (rtnetif_carrier_ok(netdev) &&
(adapter->flags & E1000_FLAG_RX_NEEDS_RESTART)) {
/* disable receives */
rctl = E1000_READ_REG(hw, E1000_RCTL);
E1000_WRITE_REG(hw, E1000_RCTL, rctl & ~E1000_RCTL_EN);
adapter->flags |= E1000_FLAG_RX_RESTART_NOW;
}
/* guard against interrupt when we're going down */
//if (!test_bit(__E1000_DOWN, &adapter->state))
// mod_timer(&adapter->watchdog_timer, jiffies + 1);
}
#ifdef CONFIG_E1000_NAPI
if (hw->mac.type < e1000_82571) {
/* disable interrupts, without the synchronize_irq bit */
atomic_inc(&adapter->irq_sem);
E1000_WRITE_REG(hw, E1000_IMC, ~0);
E1000_WRITE_FLUSH(hw);
}
/* XXX only using ring 0 for napi */
if (likely(netif_rx_schedule_prep(netdev, &adapter->rx_ring[0].napi))) {
adapter->total_tx_bytes = 0;
adapter->total_tx_packets = 0;
adapter->total_rx_bytes = 0;
adapter->total_rx_packets = 0;
__netif_rx_schedule(netdev, &adapter->rx_ring[0].napi);
} else {
atomic_dec(&adapter->irq_sem);
}
#else
/* Writing IMC and IMS is needed for 82547.
* Due to Hub Link bus being occupied, an interrupt
* de-assertion message is not able to be sent.
* When an interrupt assertion message is generated later,
* two messages are re-ordered and sent out.
* That causes APIC to think 82547 is in de-assertion
* state, while 82547 is in assertion state, resulting
* in dead lock. Writing IMC forces 82547 into
* de-assertion state.
*/
if (hw->mac.type == e1000_82547 || hw->mac.type == e1000_82547_rev_2) {
atomic_inc(&adapter->irq_sem);
E1000_WRITE_REG(hw, E1000_IMC, ~0);
}
adapter->data_received = 0;
adapter->total_tx_bytes = 0;
adapter->total_rx_bytes = 0;
adapter->total_tx_packets = 0;
adapter->total_rx_packets = 0;
for (i = 0; i < E1000_MAX_INTR; i++) {
rx_cleaned = 0;
for (j = 0; j < adapter->num_rx_queues; j++)
rx_cleaned |= adapter->clean_rx(adapter,
&adapter->rx_ring[j], &time_stamp);
tx_cleaned = 0;
for (j = 0 ; j < adapter->num_tx_queues ; j++)
tx_cleaned |= e1000_clean_tx_irq(adapter,
&adapter->tx_ring[j]);
if (!rx_cleaned && !tx_cleaned)
break;
}
if (likely(adapter->itr_setting & 3))
e1000_set_itr(adapter);
if (hw->mac.type == e1000_82547 || hw->mac.type == e1000_82547_rev_2)
e1000_irq_enable(adapter);
#endif
if (adapter->data_received)
rt_mark_stack_mgr(netdev);
return RTDM_IRQ_HANDLED;
}
#ifdef CONFIG_E1000_NAPI
/**
* e1000_poll - NAPI Rx polling callback
* @napi: struct associated with this polling callback
* @budget: amount of packets driver is allowed to process this poll
**/
static int e1000_poll(struct napi_struct *napi, int budget)
{
struct e1000_rx_ring *rx_ring = container_of(napi, struct e1000_rx_ring,
napi);
struct e1000_adapter *adapter = rx_ring->adapter;
struct net_device *netdev = adapter->netdev;
int tx_clean_complete = 1, work_done = 0;
int i;
/* FIXME: i think this code is un-necessary when using base netdev */
/* Keep link state information with original netdev */
if (!rtnetif_carrier_ok(netdev))
goto quit_polling;
/* e1000_poll is called per-cpu. This lock protects
* tx_ring[i] from being cleaned by multiple cpus
* simultaneously. A failure obtaining the lock means
* tx_ring[i] is currently being cleaned anyway. */
for (i = 0; i < adapter->num_tx_queues; i++) {
#ifdef CONFIG_E1000_MQ
if (spin_trylock(&adapter->tx_ring[i].tx_queue_lock)) {
tx_clean_complete &= e1000_clean_tx_irq(adapter,
&adapter->tx_ring[i]);
spin_unlock(&adapter->tx_ring[i].tx_queue_lock);
}
#else
if (spin_trylock(&adapter->tx_queue_lock)) {
tx_clean_complete &= e1000_clean_tx_irq(adapter,
&adapter->tx_ring[i]);
spin_unlock(&adapter->tx_queue_lock);
}
#endif
}
for (i = 0; i < adapter->num_rx_queues; i++) {
adapter->clean_rx(adapter, &adapter->rx_ring[i],
&work_done, budget);
}
/* If no Tx and not enough Rx work done, exit the polling mode */
if ((tx_clean_complete && (work_done == 0)) ||
!rtnetif_running(netdev)) {
quit_polling:
if (likely(adapter->itr_setting & 3))
e1000_set_itr(adapter);
netif_rx_complete(netdev, napi);
if (test_bit(__E1000_DOWN, &adapter->state))
atomic_dec(&adapter->irq_sem);
else
e1000_irq_enable(adapter);
return 0;
}
/* need to make sure the stack is aware of a tx-only poll loop */
if (!tx_clean_complete)
work_done = budget;
return work_done;
}
#endif
/**
* e1000_clean_tx_irq - Reclaim resources after transmit completes
* @adapter: board private structure
*
* the return value indicates whether actual cleaning was done, there
* is no guarantee that everything was cleaned
**/
static bool e1000_clean_tx_irq(struct e1000_adapter *adapter,
struct e1000_tx_ring *tx_ring)
{
struct net_device *netdev = adapter->netdev;
struct e1000_tx_desc *tx_desc, *eop_desc;
struct e1000_buffer *buffer_info;
unsigned int i, eop;
#ifdef CONFIG_E1000_NAPI
unsigned int count = 0;
#endif
bool cleaned = FALSE;
bool retval = TRUE;
unsigned int total_tx_bytes=0, total_tx_packets=0;
i = tx_ring->next_to_clean;
eop = tx_ring->buffer_info[i].next_to_watch;
eop_desc = E1000_TX_DESC(*tx_ring, eop);
while (eop_desc->upper.data & cpu_to_le32(E1000_TXD_STAT_DD)) {
for (cleaned = FALSE; !cleaned; ) {
tx_desc = E1000_TX_DESC(*tx_ring, i);
buffer_info = &tx_ring->buffer_info[i];
cleaned = (i == eop);
#ifdef CONFIG_E1000_MQ
tx_ring->tx_stats.bytes += buffer_info->length;
#endif
if (cleaned) {
struct sk_buff *skb = buffer_info->skb;
#ifdef NETIF_F_TSO
unsigned int segs, bytecount;
segs = skb_shinfo(skb)->gso_segs ?: 1;
/* multiply data chunks by size of headers */
bytecount = ((segs - 1) * skb_headlen(skb)) +
skb->len;
total_tx_packets += segs;
total_tx_bytes += bytecount;
#else
total_tx_packets++;
total_tx_bytes += skb->len;
#endif
}
e1000_unmap_and_free_tx_resource(adapter, buffer_info);
tx_desc->upper.data = 0;
if (unlikely(++i == tx_ring->count)) i = 0;
}
#ifdef CONFIG_E1000_MQ
tx_ring->tx_stats.packets++;
#endif
eop = tx_ring->buffer_info[i].next_to_watch;
eop_desc = E1000_TX_DESC(*tx_ring, eop);
#ifdef CONFIG_E1000_NAPI
#define E1000_TX_WEIGHT 64
/* weight of a sort for tx, to avoid endless transmit cleanup */
if (count++ == E1000_TX_WEIGHT) {
retval = FALSE;
break;
}
#endif
}
tx_ring->next_to_clean = i;
#define TX_WAKE_THRESHOLD 32
if (unlikely(cleaned && rtnetif_carrier_ok(netdev) &&
E1000_DESC_UNUSED(tx_ring) >= TX_WAKE_THRESHOLD)) {
/* Make sure that anybody stopping the queue after this
* sees the new next_to_clean.
*/
smp_mb();
if (rtnetif_queue_stopped(netdev) &&
!(test_bit(__E1000_DOWN, &adapter->state))) {
rtnetif_wake_queue(netdev);
++adapter->restart_queue;
}
}
if (adapter->detect_tx_hung) {
/* Detect a transmit hang in hardware, this serializes the
* check with the clearing of time_stamp and movement of i */
adapter->detect_tx_hung = FALSE;
if (tx_ring->buffer_info[eop].dma &&
time_after(jiffies, tx_ring->buffer_info[eop].time_stamp +
(adapter->tx_timeout_factor * HZ))
&& !(E1000_READ_REG(&adapter->hw, E1000_STATUS) &
E1000_STATUS_TXOFF)) {
/* detected Tx unit hang */
DPRINTK(DRV, ERR, "Detected Tx Unit Hang\n"
" Tx Queue <%lu>\n"
" TDH <%x>\n"
" TDT <%x>\n"
" next_to_use <%x>\n"
" next_to_clean <%x>\n"
"buffer_info[next_to_clean]\n"
" time_stamp <%lx>\n"
" next_to_watch <%x>\n"
" jiffies <%lx>\n"
" next_to_watch.status <%x>\n",
(unsigned long)((tx_ring - adapter->tx_ring) /
sizeof(struct e1000_tx_ring)),
readl(adapter->hw.hw_addr + tx_ring->tdh),
readl(adapter->hw.hw_addr + tx_ring->tdt),
tx_ring->next_to_use,
tx_ring->next_to_clean,
tx_ring->buffer_info[eop].time_stamp,
eop,
jiffies,
eop_desc->upper.fields.status);
rtnetif_stop_queue(netdev);
}
}
adapter->total_tx_bytes += total_tx_bytes;
adapter->total_tx_packets += total_tx_packets;
adapter->net_stats.tx_bytes += total_tx_bytes;
adapter->net_stats.tx_packets += total_tx_packets;
return retval;
}
/**
* e1000_rx_checksum - Receive Checksum Offload for 82543
* @adapter: board private structure
* @status_err: receive descriptor status and error fields
* @csum: receive descriptor csum field
* @sk_buff: socket buffer with received data
**/
static void e1000_rx_checksum(struct e1000_adapter *adapter, u32 status_err,
u32 csum, struct sk_buff *skb)
{
u16 status = (u16)status_err;
u8 errors = (u8)(status_err >> 24);
skb->ip_summed = CHECKSUM_NONE;
/* 82543 or newer only */
if (unlikely(adapter->hw.mac.type < e1000_82543)) return;
/* Ignore Checksum bit is set */
if (unlikely(status & E1000_RXD_STAT_IXSM)) return;
/* TCP/UDP checksum error bit is set */
if (unlikely(errors & E1000_RXD_ERR_TCPE)) {
/* let the stack verify checksum errors */
adapter->hw_csum_err++;
return;
}
/* TCP/UDP Checksum has not been calculated */
if (adapter->hw.mac.type <= e1000_82547_rev_2) {
if (!(status & E1000_RXD_STAT_TCPCS))
return;
} else {
if (!(status & (E1000_RXD_STAT_TCPCS | E1000_RXD_STAT_UDPCS)))
return;
}
/* It must be a TCP or UDP packet with a valid checksum */
if (likely(status & E1000_RXD_STAT_TCPCS)) {
/* TCP checksum is good */
skb->ip_summed = CHECKSUM_UNNECESSARY;
} else if (adapter->hw.mac.type > e1000_82547_rev_2) {
/* IP fragment with UDP payload */
/* Hardware complements the payload checksum, so we undo it
* and then put the value in host order for further stack use.
*/
csum = ntohl(csum ^ 0xFFFF);
skb->csum = csum;
skb->ip_summed = CHECKSUM_COMPLETE;
}
adapter->hw_csum_good++;
}
/**
* e1000_receive_skb - helper function to handle rx indications
* @adapter: board private structure
* @status: descriptor status field as written by hardware
* @vlan: descriptor vlan field as written by hardware (no le/be conversion)
* @skb: pointer to sk_buff to be indicated to stack
**/
static void e1000_receive_skb(struct e1000_adapter *adapter, u8 status,
u16 vlan, struct sk_buff *skb)
{
#ifdef CONFIG_E1000_NAPI
#ifdef NETIF_F_HW_VLAN_TX
if (unlikely(adapter->vlgrp && (status & E1000_RXD_STAT_VP))) {
vlan_hwaccel_receive_skb(skb, adapter->vlgrp,
le16_to_cpu(vlan) &
E1000_RXD_SPC_VLAN_MASK);
} else {
netif_receive_skb(skb);
}
#else
netif_receive_skb(skb);
#endif
#else /* CONFIG_E1000_NAPI */
#ifdef NETIF_F_HW_VLAN_TX
if (unlikely(adapter->vlgrp && (status & E1000_RXD_STAT_VP))) {
vlan_hwaccel_rx(skb, adapter->vlgrp,
le16_to_cpu(vlan) & E1000_RXD_SPC_VLAN_MASK);
} else {
netif_rx(skb);
}
#else
rtnetif_rx(skb);
#endif
#endif /* CONFIG_E1000_NAPI */
}
#ifdef CONFIG_E1000_NAPI
/* NOTE: these new jumbo frame routines rely on NAPI because of the
* pskb_may_pull call, which eventually must call kmap_atomic which you cannot
* call from hard irq context */
/**
* e1000_consume_page - helper function
**/
static void e1000_consume_page(struct e1000_rx_buffer *bi, struct sk_buff *skb,
u16 length)
{
bi->page = NULL;
skb->len += length;
skb->data_len += length;
skb->truesize += length;
}
/**
* e1000_clean_jumbo_rx_irq - Send received data up the network stack; legacy
* @adapter: board private structure
*
* the return value indicates whether actual cleaning was done, there
* is no guarantee that everything was cleaned
**/
static bool e1000_clean_jumbo_rx_irq(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring,
int *work_done, int work_to_do)
{
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
struct e1000_rx_desc *rx_desc, *next_rxd;
struct e1000_rx_buffer *buffer_info, *next_buffer;
unsigned long irq_flags;
u32 length;
unsigned int i;
int cleaned_count = 0;
bool cleaned = FALSE;
unsigned int total_rx_bytes=0, total_rx_packets=0;
i = rx_ring->next_to_clean;
rx_desc = E1000_RX_DESC(*rx_ring, i);
buffer_info = &rx_ring->buffer_info[i];
while (rx_desc->status & E1000_RXD_STAT_DD) {
struct sk_buff *skb;
u8 status;
if (*work_done >= work_to_do)
break;
(*work_done)++;
status = rx_desc->status;
skb = buffer_info->skb;
buffer_info->skb = NULL;
if (++i == rx_ring->count) i = 0;
next_rxd = E1000_RX_DESC(*rx_ring, i);
prefetch(next_rxd);
next_buffer = &rx_ring->buffer_info[i];
cleaned = TRUE;
cleaned_count++;
pci_unmap_page(pdev,
buffer_info->dma,
PAGE_SIZE,
PCI_DMA_FROMDEVICE);
buffer_info->dma = 0;
length = le16_to_cpu(rx_desc->length);
/* errors is only valid for DD + EOP descriptors */
if (unlikely((status & E1000_RXD_STAT_EOP) &&
(rx_desc->errors & E1000_RXD_ERR_FRAME_ERR_MASK))) {
u8 last_byte = *(skb->data + length - 1);
if (TBI_ACCEPT(&adapter->hw, status,
rx_desc->errors, length, last_byte,
adapter->min_frame_size,
adapter->max_frame_size)) {
rtdm_lock_get_irqsave(&adapter->stats_lock,
irq_flags);
e1000_tbi_adjust_stats_82543(&adapter->hw,
&adapter->stats,
length, skb->data,
adapter->max_frame_size);
rtdm_lock_put_irqrestore(&adapter->stats_lock,
irq_flags);
length--;
} else {
/* recycle both page and skb */
buffer_info->skb = skb;
/* an error means any chain goes out the window
* too */
if (rx_ring->rx_skb_top)
kfree_rtskb(rx_ring->rx_skb_top);
rx_ring->rx_skb_top = NULL;
goto next_desc;
}
}
#define rxtop rx_ring->rx_skb_top
if (!(status & E1000_RXD_STAT_EOP)) {
/* this descriptor is only the beginning (or middle) */
if (!rxtop) {
/* this is the beginning of a chain */
rxtop = skb;
skb_fill_page_desc(rxtop, 0, buffer_info->page,
0, length);
} else {
/* this is the middle of a chain */
skb_fill_page_desc(rxtop,
skb_shinfo(rxtop)->nr_frags,
buffer_info->page, 0, length);
/* re-use the skb, only consumed the page */
buffer_info->skb = skb;
}
e1000_consume_page(buffer_info, rxtop, length);
goto next_desc;
} else {
if (rxtop) {
/* end of the chain */
skb_fill_page_desc(rxtop,
skb_shinfo(rxtop)->nr_frags,
buffer_info->page, 0, length);
/* re-use the current skb, we only consumed the
* page */
buffer_info->skb = skb;
skb = rxtop;
rxtop = NULL;
e1000_consume_page(buffer_info, skb, length);
} else {
/* no chain, got EOP, this buf is the packet
* copybreak to save the put_page/alloc_page */
if (length <= copybreak &&
skb_tailroom(skb) >= length) {
u8 *vaddr;
vaddr = kmap_atomic(buffer_info->page,
KM_SKB_DATA_SOFTIRQ);
memcpy(skb_tail_pointer(skb), vaddr, length);
kunmap_atomic(vaddr,
KM_SKB_DATA_SOFTIRQ);
/* re-use the page, so don't erase
* buffer_info->page */
rtskb_put(skb, length);
} else {
skb_fill_page_desc(skb, 0,
buffer_info->page, 0,
length);
e1000_consume_page(buffer_info, skb,
length);
}
}
}
/* Receive Checksum Offload XXX recompute due to CRC strip? */
e1000_rx_checksum(adapter,
(u32)(status) |
((u32)(rx_desc->errors) << 24),
le16_to_cpu(rx_desc->csum), skb);
pskb_trim(skb, skb->len - 4);
/* probably a little skewed due to removing CRC */
total_rx_bytes += skb->len;
total_rx_packets++;
/* eth type trans needs skb->data to point to something */
if (!pskb_may_pull(skb, ETH_HLEN)) {
DPRINTK(DRV, ERR, "__pskb_pull_tail failed.\n");
kfree_rtskb(skb);
goto next_desc;
}
skb->protocol = rt_eth_type_trans(skb, netdev);
e1000_receive_skb(adapter, status, rx_desc->special, skb);
adapter->data_received = 1; // Set flag for the main interrupt routine
netdev->last_rx = jiffies;
#ifdef CONFIG_E1000_MQ
rx_ring->rx_stats.packets++;
rx_ring->rx_stats.bytes += length;
#endif
next_desc:
rx_desc->status = 0;
/* return some buffers to hardware, one at a time is too slow */
if (unlikely(cleaned_count >= E1000_RX_BUFFER_WRITE)) {
adapter->alloc_rx_buf(adapter, rx_ring, cleaned_count);
cleaned_count = 0;
}
/* use prefetched values */
rx_desc = next_rxd;
buffer_info = next_buffer;
}
rx_ring->next_to_clean = i;
cleaned_count = E1000_DESC_UNUSED(rx_ring);
if (cleaned_count)
adapter->alloc_rx_buf(adapter, rx_ring, cleaned_count);
adapter->total_rx_packets += total_rx_packets;
adapter->total_rx_bytes += total_rx_bytes;
adapter->net_stats.rx_bytes += total_rx_bytes;
adapter->net_stats.rx_packets += total_rx_packets;
return cleaned;
}
#endif /* NAPI */
/**
* e1000_clean_rx_irq - Send received data up the network stack; legacy
* @adapter: board private structure
*
* the return value indicates whether actual cleaning was done, there
* is no guarantee that everything was cleaned
**/
#ifdef CONFIG_E1000_NAPI
static bool e1000_clean_rx_irq(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring,
int *work_done, int work_to_do)
#else
static bool e1000_clean_rx_irq(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring,
nanosecs_abs_t *time_stamp)
#endif
{
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
struct e1000_rx_desc *rx_desc, *next_rxd;
struct e1000_rx_buffer *buffer_info, *next_buffer;
u32 length;
unsigned int i;
int cleaned_count = 0;
bool cleaned = FALSE;
unsigned int total_rx_bytes=0, total_rx_packets=0;
// rtdm_printk("<2> e1000_clean_rx_irq %i\n", __LINE__);
i = rx_ring->next_to_clean;
rx_desc = E1000_RX_DESC(*rx_ring, i);
buffer_info = &rx_ring->buffer_info[i];
while (rx_desc->status & E1000_RXD_STAT_DD) {
struct sk_buff *skb;
u8 status;
#ifdef CONFIG_E1000_NAPI
if (*work_done >= work_to_do)
break;
(*work_done)++;
#endif
status = rx_desc->status;
skb = buffer_info->skb;
buffer_info->skb = NULL;
prefetch(skb->data - NET_IP_ALIGN);
if (++i == rx_ring->count) i = 0;
next_rxd = E1000_RX_DESC(*rx_ring, i);
prefetch(next_rxd);
next_buffer = &rx_ring->buffer_info[i];
cleaned = TRUE;
cleaned_count++;
pci_unmap_single(pdev,
buffer_info->dma,
adapter->rx_buffer_len,
PCI_DMA_FROMDEVICE);
buffer_info->dma = 0;
length = le16_to_cpu(rx_desc->length);
/* !EOP means multiple descriptors were used to store a single
* packet, also make sure the frame isn't just CRC only */
if (unlikely(!(status & E1000_RXD_STAT_EOP) || (length <= 4))) {
/* All receives must fit into a single buffer */
E1000_DBG("%s: Receive packet consumed multiple"
" buffers\n", netdev->name);
/* recycle */
buffer_info->skb = skb;
goto next_desc;
}
if (unlikely(rx_desc->errors & E1000_RXD_ERR_FRAME_ERR_MASK)) {
u8 last_byte = *(skb->data + length - 1);
if (TBI_ACCEPT(&adapter->hw, status,
rx_desc->errors, length, last_byte,
adapter->min_frame_size,
adapter->max_frame_size)) {
length--;
} else {
/* recycle */
buffer_info->skb = skb;
goto next_desc;
}
}
/* adjust length to remove Ethernet CRC, this must be
* done after the TBI_ACCEPT workaround above */
length -= 4;
/* probably a little skewed due to removing CRC */
total_rx_bytes += length;
total_rx_packets++;
rtskb_put(skb, length);
/* Receive Checksum Offload */
e1000_rx_checksum(adapter,
(u32)(status) |
((u32)(rx_desc->errors) << 24),
le16_to_cpu(rx_desc->csum), skb);
skb->protocol = rt_eth_type_trans(skb, netdev);
skb->time_stamp = *time_stamp;
e1000_receive_skb(adapter, status, rx_desc->special, skb);
adapter->data_received = 1; // Set flag for the main interrupt routine
// netdev->last_rx = jiffies;
#ifdef CONFIG_E1000_MQ
rx_ring->rx_stats.packets++;
rx_ring->rx_stats.bytes += length;
#endif
next_desc:
rx_desc->status = 0;
/* return some buffers to hardware, one at a time is too slow */
if (unlikely(cleaned_count >= E1000_RX_BUFFER_WRITE)) {
adapter->alloc_rx_buf(adapter, rx_ring, cleaned_count);
cleaned_count = 0;
}
/* use prefetched values */
rx_desc = next_rxd;
buffer_info = next_buffer;
}
rx_ring->next_to_clean = i;
cleaned_count = E1000_DESC_UNUSED(rx_ring);
if (cleaned_count)
adapter->alloc_rx_buf(adapter, rx_ring, cleaned_count);
adapter->total_rx_packets += total_rx_packets;
adapter->total_rx_bytes += total_rx_bytes;
adapter->net_stats.rx_bytes += total_rx_bytes;
adapter->net_stats.rx_packets += total_rx_packets;
return cleaned;
}
/**
* e1000_clean_rx_irq_ps - Send received data up the network stack; packet split
* @adapter: board private structure
*
* the return value indicates whether actual cleaning was done, there
* is no guarantee that everything was cleaned
**/
#ifdef CONFIG_E1000_NAPI
static bool e1000_clean_rx_irq_ps(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring,
int *work_done, int work_to_do)
#else
static bool e1000_clean_rx_irq_ps(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring,
nanosecs_abs_t *time_stamp)
#endif
{
#ifdef CONFIG_E1000_DISABLE_PACKET_SPLIT
return true;
#else
union e1000_rx_desc_packet_split *rx_desc, *next_rxd;
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
struct e1000_rx_buffer *buffer_info, *next_buffer;
struct e1000_ps_page *ps_page;
struct e1000_ps_page_dma *ps_page_dma;
struct sk_buff *skb;
unsigned int i, j;
u32 length, staterr;
int cleaned_count = 0;
bool cleaned = FALSE;
unsigned int total_rx_bytes=0, total_rx_packets=0;
i = rx_ring->next_to_clean;
rx_desc = E1000_RX_DESC_PS(*rx_ring, i);
staterr = le32_to_cpu(rx_desc->wb.middle.status_error);
buffer_info = &rx_ring->buffer_info[i];
while (staterr & E1000_RXD_STAT_DD) {
ps_page = &rx_ring->ps_page[i];
ps_page_dma = &rx_ring->ps_page_dma[i];
#ifdef CONFIG_E1000_NAPI
if (unlikely(*work_done >= work_to_do))
break;
(*work_done)++;
#endif
skb = buffer_info->skb;
/* in the packet split case this is header only */
prefetch(skb->data - NET_IP_ALIGN);
if (++i == rx_ring->count) i = 0;
next_rxd = E1000_RX_DESC_PS(*rx_ring, i);
prefetch(next_rxd);
next_buffer = &rx_ring->buffer_info[i];
cleaned = TRUE;
cleaned_count++;
pci_unmap_single(pdev, buffer_info->dma,
adapter->rx_ps_bsize0,
PCI_DMA_FROMDEVICE);
buffer_info->dma = 0;
if (unlikely(!(staterr & E1000_RXD_STAT_EOP))) {
E1000_DBG("%s: Packet Split buffers didn't pick up"
" the full packet\n", netdev->name);
dev_kfree_skb_irq(skb);
goto next_desc;
}
if (unlikely(staterr & E1000_RXDEXT_ERR_FRAME_ERR_MASK)) {
dev_kfree_skb_irq(skb);
goto next_desc;
}
length = le16_to_cpu(rx_desc->wb.middle.length0);
if (unlikely(!length)) {
E1000_DBG("%s: Last part of the packet spanning"
" multiple descriptors\n", netdev->name);
dev_kfree_skb_irq(skb);
goto next_desc;
}
/* Good Receive */
rtskb_put(skb, length);
#ifdef CONFIG_E1000_MQ
rx_ring->rx_stats.packets++;
rx_ring->rx_stats.bytes += skb->len;
#endif
#ifdef CONFIG_E1000_NAPI
{
/* this looks ugly, but it seems compiler issues make it
more efficient than reusing j */
int l1 = le16_to_cpu(rx_desc->wb.upper.length[0]);
/* page alloc/put takes too long and effects small packet
* throughput, so unsplit small packets and save the alloc/put
* only valid in softirq (napi) context to call kmap_* */
if (l1 && (l1 <= copybreak) &&
((length + l1) <= adapter->rx_ps_bsize0)) {
u8 *vaddr;
/* there is no documentation about how to call
* kmap_atomic, so we can't hold the mapping
* very long */
pci_dma_sync_single_for_cpu(pdev,
ps_page_dma->ps_page_dma[0],
PAGE_SIZE,
PCI_DMA_FROMDEVICE);
vaddr = kmap_atomic(ps_page->ps_page[0],
KM_SKB_DATA_SOFTIRQ);
memcpy(skb_tail_pointer(skb), vaddr, l1);
kunmap_atomic(vaddr, KM_SKB_DATA_SOFTIRQ);
pci_dma_sync_single_for_device(pdev,
ps_page_dma->ps_page_dma[0],
PAGE_SIZE, PCI_DMA_FROMDEVICE);
/* remove the CRC */
l1 -= 4;
rtskb_put(skb, l1);
goto copydone;
} /* if */
}
#endif
for (j = 0; j < adapter->rx_ps_pages; j++) {
if (!(length= le16_to_cpu(rx_desc->wb.upper.length[j])))
break;
pci_unmap_page(pdev, ps_page_dma->ps_page_dma[j],
PAGE_SIZE, PCI_DMA_FROMDEVICE);
ps_page_dma->ps_page_dma[j] = 0;
skb_fill_page_desc(skb, j, ps_page->ps_page[j], 0,
length);
ps_page->ps_page[j] = NULL;
skb->len += length;
skb->data_len += length;
skb->truesize += length;
}
/* strip the ethernet crc, problem is we're using pages now so
* this whole operation can get a little cpu intensive */
pskb_trim(skb, skb->len - 4);
#ifdef CONFIG_E1000_NAPI
copydone:
#endif
total_rx_bytes += skb->len;
total_rx_packets++;
e1000_rx_checksum(adapter, staterr,
le16_to_cpu(rx_desc->wb.lower.hi_dword.csum_ip.csum), skb);
skb->protocol = rt_eth_type_trans(skb, netdev);
if (likely(rx_desc->wb.upper.header_status &
cpu_to_le16(E1000_RXDPS_HDRSTAT_HDRSP)))
adapter->rx_hdr_split++;
e1000_receive_skb(adapter, staterr, rx_desc->wb.middle.vlan,
skb);
netdev->last_rx = jiffies;
next_desc:
rx_desc->wb.middle.status_error &= cpu_to_le32(~0xFF);
buffer_info->skb = NULL;
/* return some buffers to hardware, one at a time is too slow */
if (unlikely(cleaned_count >= E1000_RX_BUFFER_WRITE)) {
adapter->alloc_rx_buf(adapter, rx_ring, cleaned_count);
cleaned_count = 0;
}
/* use prefetched values */
rx_desc = next_rxd;
buffer_info = next_buffer;
staterr = le32_to_cpu(rx_desc->wb.middle.status_error);
}
rx_ring->next_to_clean = i;
cleaned_count = E1000_DESC_UNUSED(rx_ring);
if (cleaned_count)
adapter->alloc_rx_buf(adapter, rx_ring, cleaned_count);
adapter->total_rx_packets += total_rx_packets;
adapter->total_rx_bytes += total_rx_bytes;
adapter->net_stats.rx_bytes += total_rx_bytes;
adapter->net_stats.rx_packets += total_rx_packets;
return cleaned;
#endif
}
#ifdef CONFIG_E1000_NAPI
/**
* e1000_alloc_jumbo_rx_buffers - Replace used jumbo receive buffers
* @adapter: address of board private structure
* @rx_ring: pointer to receive ring structure
* @cleaned_count: number of buffers to allocate this pass
**/
static void e1000_alloc_jumbo_rx_buffers(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring,
int cleaned_count)
{
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
struct e1000_rx_desc *rx_desc;
struct e1000_rx_buffer *buffer_info;
struct sk_buff *skb;
unsigned int i;
unsigned int bufsz = 256 -
16 /*for skb_reserve */ -
NET_IP_ALIGN;
i = rx_ring->next_to_use;
buffer_info = &rx_ring->buffer_info[i];
while (cleaned_count--) {
skb = buffer_info->skb;
if (skb) {
skb_trim(skb, 0);
goto check_page;
}
skb = rtnetdev_alloc_rtskb(netdev, bufsz);
if (unlikely(!skb)) {
/* Better luck next round */
adapter->alloc_rx_buff_failed++;
break;
}
/* Fix for errata 23, can't cross 64kB boundary */
if (!e1000_check_64k_bound(adapter, skb->data, bufsz)) {
struct sk_buff *oldskb = skb;
DPRINTK(PROBE, ERR, "skb align check failed: %u bytes "
"at %p\n", bufsz, skb->data);
/* Try again, without freeing the previous */
skb = rtnetdev_alloc_rtskb(netdev, bufsz);
/* Failed allocation, critical failure */
if (!skb) {
kfree_rtskb(oldskb);
adapter->alloc_rx_buff_failed++;
break;
}
if (!e1000_check_64k_bound(adapter, skb->data, bufsz)) {
/* give up */
kfree_rtskb(skb);
kfree_rtskb(oldskb);
adapter->alloc_rx_buff_failed++;
break; /* while !buffer_info->skb */
}
/* Use new allocation */
kfree_rtskb(oldskb);
}
/* Make buffer alignment 2 beyond a 16 byte boundary
* this will result in a 16 byte aligned IP header after
* the 14 byte MAC header is removed
*/
skb_reserve(skb, NET_IP_ALIGN);
buffer_info->skb = skb;
check_page:
/* allocate a new page if necessary */
if (!buffer_info->page) {
buffer_info->page = alloc_page(GFP_ATOMIC);
if (unlikely(!buffer_info->page)) {
adapter->alloc_rx_buff_failed++;
break;
}
}
if (!buffer_info->dma)
buffer_info->dma = pci_map_page(pdev,
buffer_info->page, 0,
PAGE_SIZE,
PCI_DMA_FROMDEVICE);
rx_desc = E1000_RX_DESC(*rx_ring, i);
rx_desc->buffer_addr = cpu_to_le64(buffer_info->dma);
if (unlikely(++i == rx_ring->count))
i = 0;
buffer_info = &rx_ring->buffer_info[i];
}
if (likely(rx_ring->next_to_use != i)) {
rx_ring->next_to_use = i;
if (unlikely(i-- == 0))
i = (rx_ring->count - 1);
/* Force memory writes to complete before letting h/w
* know there are new descriptors to fetch. (Only
* applicable for weak-ordered memory model archs,
* such as IA-64). */
wmb();
writel(i, adapter->hw.hw_addr + rx_ring->rdt);
}
}
#endif /* NAPI */
/**
* e1000_alloc_rx_buffers - Replace used receive buffers; legacy & extended
* @adapter: address of board private structure
**/
static void e1000_alloc_rx_buffers(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring,
int cleaned_count)
{
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
struct e1000_rx_desc *rx_desc;
struct e1000_rx_buffer *buffer_info;
struct sk_buff *skb;
unsigned int i;
unsigned int bufsz = adapter->rx_buffer_len + NET_IP_ALIGN;
i = rx_ring->next_to_use;
buffer_info = &rx_ring->buffer_info[i];
while (cleaned_count--) {
skb = buffer_info->skb;
if (skb) {
rtskb_trim(skb, 0);
goto map_skb;
}
skb = rtnetdev_alloc_rtskb(netdev, bufsz);
if (unlikely(!skb)) {
/* Better luck next round */
adapter->alloc_rx_buff_failed++;
break;
}
/* Fix for errata 23, can't cross 64kB boundary */
if (!e1000_check_64k_bound(adapter, skb->data, bufsz)) {
struct sk_buff *oldskb = skb;
DPRINTK(RX_ERR, ERR, "skb align check failed: %u bytes "
"at %p\n", bufsz, skb->data);
/* Try again, without freeing the previous */
skb = rtnetdev_alloc_rtskb(netdev, bufsz);
/* Failed allocation, critical failure */
if (!skb) {
kfree_rtskb(oldskb);
adapter->alloc_rx_buff_failed++;
break;
}
if (!e1000_check_64k_bound(adapter, skb->data, bufsz)) {
/* give up */
kfree_rtskb(skb);
kfree_rtskb(oldskb);
adapter->alloc_rx_buff_failed++;
break; /* while !buffer_info->skb */
}
/* Use new allocation */
kfree_rtskb(oldskb);
}
/* Make buffer alignment 2 beyond a 16 byte boundary
* this will result in a 16 byte aligned IP header after
* the 14 byte MAC header is removed
*/
skb_reserve(skb, NET_IP_ALIGN);
buffer_info->skb = skb;
map_skb:
buffer_info->dma = pci_map_single(pdev,
skb->data,
adapter->rx_buffer_len,
PCI_DMA_FROMDEVICE);
/* Fix for errata 23, can't cross 64kB boundary */
if (!e1000_check_64k_bound(adapter,
(void *)(unsigned long)buffer_info->dma,
adapter->rx_buffer_len)) {
DPRINTK(RX_ERR, ERR,
"dma align check failed: %u bytes at %p\n",
adapter->rx_buffer_len,
(void *)(unsigned long)buffer_info->dma);
kfree_rtskb(skb);
buffer_info->skb = NULL;
pci_unmap_single(pdev, buffer_info->dma,
adapter->rx_buffer_len,
PCI_DMA_FROMDEVICE);
buffer_info->dma = 0;
adapter->alloc_rx_buff_failed++;
break; /* while !buffer_info->skb */
}
rx_desc = E1000_RX_DESC(*rx_ring, i);
rx_desc->buffer_addr = cpu_to_le64(buffer_info->dma);
if (unlikely(++i == rx_ring->count))
i = 0;
buffer_info = &rx_ring->buffer_info[i];
}
if (likely(rx_ring->next_to_use != i)) {
rx_ring->next_to_use = i;
if (unlikely(i-- == 0))
i = (rx_ring->count - 1);
/* Force memory writes to complete before letting h/w
* know there are new descriptors to fetch. (Only
* applicable for weak-ordered memory model archs,
* such as IA-64). */
wmb();
writel(i, adapter->hw.hw_addr + rx_ring->rdt);
}
}
/**
* e1000_alloc_rx_buffers_ps - Replace used receive buffers; packet split
* @adapter: address of board private structure
**/
static void e1000_alloc_rx_buffers_ps(struct e1000_adapter *adapter,
struct e1000_rx_ring *rx_ring,
int cleaned_count)
{
}
/**
* e1000_smartspeed - Workaround for SmartSpeed on 82541 and 82547 controllers.
* @adapter:
**/
static void e1000_smartspeed(struct e1000_adapter *adapter)
{
struct e1000_mac_info *mac = &adapter->hw.mac;
struct e1000_phy_info *phy = &adapter->hw.phy;
u16 phy_status;
u16 phy_ctrl;
if ((phy->type != e1000_phy_igp) || !mac->autoneg ||
!(phy->autoneg_advertised & ADVERTISE_1000_FULL))
return;
if (adapter->smartspeed == 0) {
/* If Master/Slave config fault is asserted twice,
* we assume back-to-back */
e1000_read_phy_reg(&adapter->hw, PHY_1000T_STATUS, &phy_status);
if (!(phy_status & SR_1000T_MS_CONFIG_FAULT)) return;
e1000_read_phy_reg(&adapter->hw, PHY_1000T_STATUS, &phy_status);
if (!(phy_status & SR_1000T_MS_CONFIG_FAULT)) return;
e1000_read_phy_reg(&adapter->hw, PHY_1000T_CTRL, &phy_ctrl);
if (phy_ctrl & CR_1000T_MS_ENABLE) {
phy_ctrl &= ~CR_1000T_MS_ENABLE;
e1000_write_phy_reg(&adapter->hw, PHY_1000T_CTRL,
phy_ctrl);
adapter->smartspeed++;
if (!e1000_phy_setup_autoneg(&adapter->hw) &&
!e1000_read_phy_reg(&adapter->hw, PHY_CONTROL,
&phy_ctrl)) {
phy_ctrl |= (MII_CR_AUTO_NEG_EN |
MII_CR_RESTART_AUTO_NEG);
e1000_write_phy_reg(&adapter->hw, PHY_CONTROL,
phy_ctrl);
}
}
return;
} else if (adapter->smartspeed == E1000_SMARTSPEED_DOWNSHIFT) {
/* If still no link, perhaps using 2/3 pair cable */
e1000_read_phy_reg(&adapter->hw, PHY_1000T_CTRL, &phy_ctrl);
phy_ctrl |= CR_1000T_MS_ENABLE;
e1000_write_phy_reg(&adapter->hw, PHY_1000T_CTRL, phy_ctrl);
if (!e1000_phy_setup_autoneg(&adapter->hw) &&
!e1000_read_phy_reg(&adapter->hw, PHY_CONTROL, &phy_ctrl)) {
phy_ctrl |= (MII_CR_AUTO_NEG_EN |
MII_CR_RESTART_AUTO_NEG);
e1000_write_phy_reg(&adapter->hw, PHY_CONTROL, phy_ctrl);
}
}
/* Restart process after E1000_SMARTSPEED_MAX iterations */
if (adapter->smartspeed++ == E1000_SMARTSPEED_MAX)
adapter->smartspeed = 0;
}
/**
* e1000_ioctl -
* @netdev:
* @ifreq:
* @cmd:
**/
#if 0
static int e1000_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
{
switch (cmd) {
#ifdef SIOCGMIIPHY
case SIOCGMIIPHY:
case SIOCGMIIREG:
case SIOCSMIIREG:
return e1000_mii_ioctl(netdev, ifr, cmd);
#endif
#ifdef ETHTOOL_OPS_COMPAT
case SIOCETHTOOL:
return ethtool_ioctl(ifr);
#endif
default:
return -EOPNOTSUPP;
}
}
#ifdef SIOCGMIIPHY
/**
* e1000_mii_ioctl -
* @netdev:
* @ifreq:
* @cmd:
**/
static int e1000_mii_ioctl(struct net_device *netdev, struct ifreq *ifr,
int cmd)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
struct mii_ioctl_data *data = if_mii(ifr);
if (adapter->hw.phy.media_type != e1000_media_type_copper)
return -EOPNOTSUPP;
switch (cmd) {
case SIOCGMIIPHY:
data->phy_id = adapter->hw.phy.addr;
break;
case SIOCGMIIREG:
if (!capable(CAP_NET_ADMIN))
return -EPERM;
switch (data->reg_num & 0x1F) {
case MII_BMCR:
data->val_out = adapter->phy_regs.bmcr;
break;
case MII_BMSR:
data->val_out = adapter->phy_regs.bmsr;
break;
case MII_PHYSID1:
data->val_out = (adapter->hw.phy.id >> 16);
break;
case MII_PHYSID2:
data->val_out = (adapter->hw.phy.id & 0xFFFF);
break;
case MII_ADVERTISE:
data->val_out = adapter->phy_regs.advertise;
break;
case MII_LPA:
data->val_out = adapter->phy_regs.lpa;
break;
case MII_EXPANSION:
data->val_out = adapter->phy_regs.expansion;
break;
case MII_CTRL1000:
data->val_out = adapter->phy_regs.ctrl1000;
break;
case MII_STAT1000:
data->val_out = adapter->phy_regs.stat1000;
break;
case MII_ESTATUS:
data->val_out = adapter->phy_regs.estatus;
break;
default:
return -EIO;
}
break;
case SIOCSMIIREG:
default:
return -EOPNOTSUPP;
}
return E1000_SUCCESS;
}
#endif
#endif
void e1000_pci_set_mwi(struct e1000_hw *hw)
{
struct e1000_adapter *adapter = hw->back;
int ret_val = pci_set_mwi(adapter->pdev);
if (ret_val)
DPRINTK(PROBE, ERR, "Error in setting MWI\n");
}
void e1000_pci_clear_mwi(struct e1000_hw *hw)
{
struct e1000_adapter *adapter = hw->back;
pci_clear_mwi(adapter->pdev);
}
void e1000_read_pci_cfg(struct e1000_hw *hw, u32 reg, u16 *value)
{
struct e1000_adapter *adapter = hw->back;
pci_read_config_word(adapter->pdev, reg, value);
}
void e1000_write_pci_cfg(struct e1000_hw *hw, u32 reg, u16 *value)
{
struct e1000_adapter *adapter = hw->back;
pci_write_config_word(adapter->pdev, reg, *value);
}
s32 e1000_read_pcie_cap_reg(struct e1000_hw *hw, u32 reg, u16 *value)
{
struct e1000_adapter *adapter = hw->back;
u16 cap_offset;
cap_offset = pci_find_capability(adapter->pdev, PCI_CAP_ID_EXP);
if (!cap_offset)
return -E1000_ERR_CONFIG;
pci_read_config_word(adapter->pdev, cap_offset + reg, value);
return E1000_SUCCESS;
}
#ifdef NETIF_F_HW_VLAN_TX
static void e1000_vlan_rx_register(struct net_device *netdev,
struct vlan_group *grp)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
u32 ctrl, rctl;
e1000_irq_disable(adapter);
adapter->vlgrp = grp;
if (grp) {
/* enable VLAN tag insert/strip */
ctrl = E1000_READ_REG(&adapter->hw, E1000_CTRL);
ctrl |= E1000_CTRL_VME;
E1000_WRITE_REG(&adapter->hw, E1000_CTRL, ctrl);
if ((adapter->hw.mac.type != e1000_ich8lan) &&
(adapter->hw.mac.type != e1000_ich9lan)) {
/* enable VLAN receive filtering */
rctl = E1000_READ_REG(&adapter->hw, E1000_RCTL);
rctl |= E1000_RCTL_VFE;
rctl &= ~E1000_RCTL_CFIEN;
E1000_WRITE_REG(&adapter->hw, E1000_RCTL, rctl);
e1000_update_mng_vlan(adapter);
}
} else {
/* disable VLAN tag insert/strip */
ctrl = E1000_READ_REG(&adapter->hw, E1000_CTRL);
ctrl &= ~E1000_CTRL_VME;
E1000_WRITE_REG(&adapter->hw, E1000_CTRL, ctrl);
if ((adapter->hw.mac.type != e1000_ich8lan) &&
(adapter->hw.mac.type != e1000_ich9lan)) {
/* disable VLAN filtering */
rctl = E1000_READ_REG(&adapter->hw, E1000_RCTL);
rctl &= ~E1000_RCTL_VFE;
E1000_WRITE_REG(&adapter->hw, E1000_RCTL, rctl);
if (adapter->mng_vlan_id !=
(u16)E1000_MNG_VLAN_NONE) {
e1000_vlan_rx_kill_vid(netdev,
adapter->mng_vlan_id);
adapter->mng_vlan_id = E1000_MNG_VLAN_NONE;
}
}
}
e1000_irq_enable(adapter);
}
static void e1000_vlan_rx_add_vid(struct net_device *netdev, u16 vid)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
u32 vfta, index;
struct net_device *v_netdev;
if ((adapter->hw.mng_cookie.status &
E1000_MNG_DHCP_COOKIE_STATUS_VLAN) &&
(vid == adapter->mng_vlan_id))
return;
/* add VID to filter table */
index = (vid >> 5) & 0x7F;
vfta = E1000_READ_REG_ARRAY(&adapter->hw, E1000_VFTA, index);
vfta |= (1 << (vid & 0x1F));
e1000_write_vfta(&adapter->hw, index, vfta);
/* Copy feature flags from netdev to the vlan netdev for this vid.
* This allows things like TSO to bubble down to our vlan device.
*/
v_netdev = vlan_group_get_device(adapter->vlgrp, vid);
v_netdev->features |= adapter->netdev->features;
vlan_group_set_device(adapter->vlgrp, vid, v_netdev);
}
static void e1000_vlan_rx_kill_vid(struct net_device *netdev, u16 vid)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
u32 vfta, index;
e1000_irq_disable(adapter);
vlan_group_set_device(adapter->vlgrp, vid, NULL);
e1000_irq_enable(adapter);
if ((adapter->hw.mng_cookie.status &
E1000_MNG_DHCP_COOKIE_STATUS_VLAN) &&
(vid == adapter->mng_vlan_id)) {
/* release control to f/w */
e1000_release_hw_control(adapter);
return;
}
/* remove VID from filter table */
index = (vid >> 5) & 0x7F;
vfta = E1000_READ_REG_ARRAY(&adapter->hw, E1000_VFTA, index);
vfta &= ~(1 << (vid & 0x1F));
e1000_write_vfta(&adapter->hw, index, vfta);
}
static void e1000_restore_vlan(struct e1000_adapter *adapter)
{
e1000_vlan_rx_register(adapter->netdev, adapter->vlgrp);
if (adapter->vlgrp) {
u16 vid;
for (vid = 0; vid < VLAN_N_VID; vid++) {
if (!vlan_group_get_device(adapter->vlgrp, vid))
continue;
e1000_vlan_rx_add_vid(adapter->netdev, vid);
}
}
}
#endif
int e1000_set_spd_dplx(struct e1000_adapter *adapter, u16 spddplx)
{
struct e1000_mac_info *mac = &adapter->hw.mac;
mac->autoneg = 0;
/* Fiber NICs only allow 1000 gbps Full duplex */
if ((adapter->hw.phy.media_type == e1000_media_type_fiber) &&
spddplx != (SPEED_1000 + DUPLEX_FULL)) {
DPRINTK(PROBE, ERR, "Unsupported Speed/Duplex configuration\n");
return -EINVAL;
}
switch (spddplx) {
case SPEED_10 + DUPLEX_HALF:
mac->forced_speed_duplex = ADVERTISE_10_HALF;
break;
case SPEED_10 + DUPLEX_FULL:
mac->forced_speed_duplex = ADVERTISE_10_FULL;
break;
case SPEED_100 + DUPLEX_HALF:
mac->forced_speed_duplex = ADVERTISE_100_HALF;
break;
case SPEED_100 + DUPLEX_FULL:
mac->forced_speed_duplex = ADVERTISE_100_FULL;
break;
case SPEED_1000 + DUPLEX_FULL:
mac->autoneg = 1;
adapter->hw.phy.autoneg_advertised = ADVERTISE_1000_FULL;
break;
case SPEED_1000 + DUPLEX_HALF: /* not supported */
default:
DPRINTK(PROBE, ERR, "Unsupported Speed/Duplex configuration\n");
return -EINVAL;
}
return 0;
}
#ifdef USE_REBOOT_NOTIFIER
/* only want to do this for 2.4 kernels? */
static int e1000_notify_reboot(struct notifier_block *nb,
unsigned long event, void *p)
{
struct pci_dev *pdev = NULL;
switch (event) {
case SYS_DOWN:
case SYS_HALT:
case SYS_POWER_OFF:
while ((pdev = pci_find_device(PCI_ANY_ID, PCI_ANY_ID, pdev))) {
if (pci_dev_driver(pdev) == &e1000_driver)
e1000_suspend(pdev, PMSG_SUSPEND);
}
}
return NOTIFY_DONE;
}
#endif
#ifdef CONFIG_PM
static int e1000_resume(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct e1000_adapter *adapter = netdev_priv(netdev);
u32 err;
pci_set_power_state(pdev, PCI_D0);
pci_restore_state(pdev);
if ((err = pci_enable_device(pdev))) {
printk(KERN_ERR "e1000: Cannot enable PCI device from suspend\n");
return err;
}
pci_set_master(pdev);
pci_enable_wake(pdev, PCI_D3hot, 0);
pci_enable_wake(pdev, PCI_D3cold, 0);
if (rtnetif_running(netdev) && (err = e1000_request_irq(adapter)))
return err;
if (adapter->hw.phy.media_type == e1000_media_type_copper) {
e1000_power_up_phy(&adapter->hw);
e1000_setup_link(&adapter->hw);
}
e1000_reset(adapter);
E1000_WRITE_REG(&adapter->hw, E1000_WUS, ~0);
e1000_init_manageability(adapter);
if (rtnetif_running(netdev))
e1000_up(adapter);
netif_device_attach(netdev);
/* If the controller is 82573 or ICHx and f/w is AMT, do not set
* DRV_LOAD until the interface is up. For all other cases,
* let the f/w know that the h/w is now under the control
* of the driver. */
if (((adapter->hw.mac.type != e1000_82573) &&
(adapter->hw.mac.type != e1000_ich8lan) &&
(adapter->hw.mac.type != e1000_ich9lan)) ||
!e1000_check_mng_mode(&adapter->hw))
e1000_get_hw_control(adapter);
return 0;
}
#endif
#ifdef CONFIG_NET_POLL_CONTROLLER
/*
* Polling 'interrupt' - used by things like netconsole to send skbs
* without having to re-enable interrupts. It's not called while
* the interrupt routine is executing.
*/
static void e1000_netpoll(struct net_device *netdev)
{
struct e1000_adapter *adapter = netdev_priv(netdev);
int i;
disable_irq(adapter->pdev->irq);
e1000_intr(adapter->pdev->irq, netdev);
for (i = 0; i < adapter->num_tx_queues ; i++ )
e1000_clean_tx_irq(adapter, &adapter->tx_ring[i]);
#ifndef CONFIG_E1000_NAPI
for (i = 0; i < adapter->num_rx_queues ; i++ )
adapter->clean_rx(adapter, &adapter->rx_ring[i], NULL);
#endif
enable_irq(adapter->pdev->irq);
}
#endif
#ifdef HAVE_PCI_ERS
/**
* e1000_io_error_detected - called when PCI error is detected
* @pdev: Pointer to PCI device
* @state: The current pci connection state
*
* This function is called after a PCI bus error affecting
* this device has been detected.
*/
static pci_ers_result_t e1000_io_error_detected(struct pci_dev *pdev,
pci_channel_state_t state)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct e1000_adapter *adapter = netdev->priv;
netif_device_detach(netdev);
if (rtnetif_running(netdev))
e1000_down(adapter);
pci_disable_device(pdev);
/* Request a slot slot reset. */
return PCI_ERS_RESULT_NEED_RESET;
}
/**
* e1000_io_slot_reset - called after the pci bus has been reset.
* @pdev: Pointer to PCI device
*
* Restart the card from scratch, as if from a cold-boot. Implementation
* resembles the first-half of the e1000_resume routine.
*/
static pci_ers_result_t e1000_io_slot_reset(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct e1000_adapter *adapter = netdev->priv;
if (pci_enable_device(pdev)) {
printk(KERN_ERR "e1000: Cannot re-enable PCI device after reset.\n");
return PCI_ERS_RESULT_DISCONNECT;
}
pci_set_master(pdev);
pci_enable_wake(pdev, PCI_D3hot, 0);
pci_enable_wake(pdev, PCI_D3cold, 0);
e1000_reset(adapter);
E1000_WRITE_REG(&adapter->hw, E1000_WUS, ~0);
return PCI_ERS_RESULT_RECOVERED;
}
/**
* e1000_io_resume - called when traffic can start flowing again.
* @pdev: Pointer to PCI device
*
* This callback is called when the error recovery driver tells us that
* its OK to resume normal operation. Implementation resembles the
* second-half of the e1000_resume routine.
*/
static void e1000_io_resume(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct e1000_adapter *adapter = netdev->priv;
e1000_init_manageability(adapter);
if (rtnetif_running(netdev)) {
if (e1000_up(adapter)) {
printk("e1000: can't bring device back up after reset\n");
return;
}
}
netif_device_attach(netdev);
/* If the controller is 82573 or ICHx and f/w is AMT, do not set
* DRV_LOAD until the interface is up. For all other cases,
* let the f/w know that the h/w is now under the control
* of the driver. */
if (((adapter->hw.mac.type != e1000_82573) &&
(adapter->hw.mac.type != e1000_ich8lan) &&
(adapter->hw.mac.type != e1000_ich9lan)) ||
!e1000_check_mng_mode(&adapter->hw))
e1000_get_hw_control(adapter);
}
#endif /* HAVE_PCI_ERS */
s32 e1000_alloc_zeroed_dev_spec_struct(struct e1000_hw *hw, u32 size)
{
hw->dev_spec = kmalloc(size, GFP_KERNEL);
if (!hw->dev_spec)
return -ENOMEM;
memset(hw->dev_spec, 0, size);
return E1000_SUCCESS;
}
void e1000_free_dev_spec_struct(struct e1000_hw *hw)
{
if (!hw->dev_spec)
return;
kfree(hw->dev_spec);
}
/* vim: set ts=4: */
/* e1000_main.c */
| 29.069264 | 85 | 0.71334 | [
"vector",
"model"
] |
5861522ac3bdf2ad301d1be53731efed908edc58 | 5,161 | h | C | cdn/include/tencentcloud/cdn/v20180606/model/ScdnTopData.h | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 43 | 2019-08-14T08:14:12.000Z | 2022-03-30T12:35:09.000Z | cdn/include/tencentcloud/cdn/v20180606/model/ScdnTopData.h | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 12 | 2019-07-15T10:44:59.000Z | 2021-11-02T12:35:00.000Z | cdn/include/tencentcloud/cdn/v20180606/model/ScdnTopData.h | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | 28 | 2019-07-12T09:06:22.000Z | 2022-03-30T08:04:18.000Z | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_CDN_V20180606_MODEL_SCDNTOPDATA_H_
#define TENCENTCLOUD_CDN_V20180606_MODEL_SCDNTOPDATA_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
#include <tencentcloud/core/AbstractModel.h>
namespace TencentCloud
{
namespace Cdn
{
namespace V20180606
{
namespace Model
{
/**
* SCDN攻击数据Top展示
*/
class ScdnTopData : public AbstractModel
{
public:
ScdnTopData();
~ScdnTopData() = default;
void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const;
CoreInternalOutcome Deserialize(const rapidjson::Value &value);
/**
* 获取时间
* @return Time 时间
*/
std::string GetTime() const;
/**
* 设置时间
* @param Time 时间
*/
void SetTime(const std::string& _time);
/**
* 判断参数 Time 是否已赋值
* @return Time 是否已赋值
*/
bool TimeHasBeenSet() const;
/**
* 获取数值
* @return Value 数值
*/
uint64_t GetValue() const;
/**
* 设置数值
* @param Value 数值
*/
void SetValue(const uint64_t& _value);
/**
* 判断参数 Value 是否已赋值
* @return Value 是否已赋值
*/
bool ValueHasBeenSet() const;
/**
* 获取运营商
* @return Isp 运营商
*/
std::string GetIsp() const;
/**
* 设置运营商
* @param Isp 运营商
*/
void SetIsp(const std::string& _isp);
/**
* 判断参数 Isp 是否已赋值
* @return Isp 是否已赋值
*/
bool IspHasBeenSet() const;
/**
* 获取IP地址
* @return Ip IP地址
*/
std::string GetIp() const;
/**
* 设置IP地址
* @param Ip IP地址
*/
void SetIp(const std::string& _ip);
/**
* 判断参数 Ip 是否已赋值
* @return Ip 是否已赋值
*/
bool IpHasBeenSet() const;
/**
* 获取区域
* @return District 区域
*/
std::string GetDistrict() const;
/**
* 设置区域
* @param District 区域
*/
void SetDistrict(const std::string& _district);
/**
* 判断参数 District 是否已赋值
* @return District 是否已赋值
*/
bool DistrictHasBeenSet() const;
private:
/**
* 时间
*/
std::string m_time;
bool m_timeHasBeenSet;
/**
* 数值
*/
uint64_t m_value;
bool m_valueHasBeenSet;
/**
* 运营商
*/
std::string m_isp;
bool m_ispHasBeenSet;
/**
* IP地址
*/
std::string m_ip;
bool m_ipHasBeenSet;
/**
* 区域
*/
std::string m_district;
bool m_districtHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_CDN_V20180606_MODEL_SCDNTOPDATA_H_
| 28.994382 | 116 | 0.391397 | [
"vector",
"model"
] |
58661546cb2c5b45fe16dc34226fe1bd76a2255b | 9,919 | h | C | src/api/libcellml/analyserequationast.h | nickerso/libcellml | 9fe5ecabc3e63c49d5ee8539ed2c8ce572a9712a | [
"Apache-2.0"
] | 1 | 2021-02-15T01:09:04.000Z | 2021-02-15T01:09:04.000Z | src/api/libcellml/analyserequationast.h | nickerso/libcellml | 9fe5ecabc3e63c49d5ee8539ed2c8ce572a9712a | [
"Apache-2.0"
] | 8 | 2019-09-01T23:37:50.000Z | 2021-05-27T21:20:34.000Z | src/api/libcellml/analyserequationast.h | nickerso/libcellml | 9fe5ecabc3e63c49d5ee8539ed2c8ce572a9712a | [
"Apache-2.0"
] | 1 | 2022-02-04T06:11:40.000Z | 2022-02-04T06:11:40.000Z | /*
Copyright libCellML Contributors
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 "libcellml/analyser.h"
#include "libcellml/generator.h"
#ifdef NAN
# undef NAN
#endif
namespace libcellml {
/**
* @brief The AnalyserEquationAst class.
*
* The AnalyserEquationAst class is for representing an equation abstract syntax
* tree (AST) in the context of a CellML Analyser.
*/
class LIBCELLML_EXPORT AnalyserEquationAst
{
friend class Analyser;
public:
/**
* @brief The type of a node in an abstract syntax tree (AST).
*
* A node in an abstract syntax tree (AST) can be of one of the following
* types:
* - Assignment type:
* - ASSIGNMENT: the assignment operator
* - Relational and logical operators:
* - EQ: the equal to function;
* - NEQ: the not equal to function;
* - LT: the less than function;
* - LEQ: the less than or equal to function;
* - GT: the greater than function;
* - GEQ: the greater than or equal to function;
* - AND: the and function;
* - OR: the or function
* - XOR: the exclusive or function;
* - NOT: the not function;
* - Arithmetic operators:
* - PLUS: the plus operator;
* - MINUS: the minus operator;
* - TIMES: the times operator;
* - DIVIDE: the divide operator;
* - POWER: the power operator;
* - ROOT: the root operator;
* - ABS: the absolute value function;
* - EXP: the exponential function;
* - LN: the natural logarithm function;
* - LOG: the common logarithm function;
* - CEILING: the ceiling function;
* - FLOOR: the floor function;
* - MIN: the minimum function;
* - MAX: the maximum function;
* - REM: the remainder function;
* - Calculus elements:
* - DIFF: the differentiation operator;
* - Trigonometric operators:
* - SIN: the sine function;
* - COS: the cosine function;
* - TAN: the tangent function;
* - SEC: the secant function;
* - CSC: the cosecant function;
* - COT: the cotangent function;
* - SINH: the hyperbolic sine function;
* - COSH: the hyperbolic cosine function;
* - TANH: the hyperbolic tangent function;
* - SECH: the hyperbolic secant function;
* - CSCH: the hyperbolic cosecant function;
* - COTH: the hyperbolic cotangent function;
* - ASIN: the arc sine function;
* - ACOS: the arc cosine function;
* - ATAN: the arc tangent function;
* - ASEC: the arc secant function;
* - ACSC: the arc cosecant function;
* - ACOT: the arc cotangent function;
* - ASINH: the arc hyperbolic sine function;
* - ACOSH: the arc hyperbolic cosine function;
* - ATANH: the arc hyperbolic tangent function;
* - ASECH: the arc hyperbolic secant function;
* - ACSCH: the arc hyperbolic cosecant function;
* - ACOTH: the arc hyperbolic cotangent function;
* - Piecewise statement:
* - PIECEWISE: the "piecewise" statement;
* - PIECE: the "piece" part of a "piecewise" statement;
* - OTHERWISE: the "otherwise" part of a "piecewise" statement;
* - Token elements:
* - CI: an identifier (i.e. the name of a model variable);
* - CN: a number;
* - Qualifier elements:
* - DEGREE: the degree of a root operator (it is only used when its
* value is not 2);
* - LOGBASE: the base with respect to which the logarithm is taken;
* - BVAR: the bound variable of a differential equation;
* - Constants:
* - TRUE: the "true" boolean;
* - FALSE: the "false" boolean;
* - E: Euler's number;
* - PI: the π constant;
* - INF: the infinity value; or
* - NAN: the not-a-number value.
*/
enum class Type
{
// Assignment.
ASSIGNMENT,
// Relational and logical operators.
EQ,
NEQ,
LT,
LEQ,
GT,
GEQ,
AND,
OR,
XOR,
NOT,
// Arithmetic operators.
PLUS,
MINUS,
TIMES,
DIVIDE,
POWER,
ROOT,
ABS,
EXP,
LN,
LOG,
CEILING,
FLOOR,
MIN,
MAX,
REM,
// Calculus elements.
DIFF,
// Trigonometric operators.
SIN,
COS,
TAN,
SEC,
CSC,
COT,
SINH,
COSH,
TANH,
SECH,
CSCH,
COTH,
ASIN,
ACOS,
ATAN,
ASEC,
ACSC,
ACOT,
ASINH,
ACOSH,
ATANH,
ASECH,
ACSCH,
ACOTH,
// Piecewise statement.
PIECEWISE,
PIECE,
OTHERWISE,
// Token elements.
CI,
CN,
// Qualifier elements.
DEGREE,
LOGBASE,
BVAR,
// Constants.
TRUE,
FALSE,
E,
PI,
INF,
NAN
};
~AnalyserEquationAst(); /**< Destructor, @private. */
AnalyserEquationAst(const AnalyserEquationAst &rhs) = delete; /**< Copy constructor, @private. */
AnalyserEquationAst(AnalyserEquationAst &&rhs) noexcept = delete; /**< Move constructor, @private. */
AnalyserEquationAst &operator=(AnalyserEquationAst rhs) = delete; /**< Assignment operator, @private. */
/**
* @brief Create an @ref AnalyserEquationAst object.
*
* Factory method to create an @ref AnalyserEquationAst. Create a blank
* equation AST with::
*
* @code
* auto ast = libcellml::AnalyserEquationAst::create();
* @endcode
*
* @return A smart pointer to an @ref AnalyserEquationAst object.
*/
static AnalyserEquationAstPtr create() noexcept;
/**
* @brief Get the @c Type of this @ref AnalyserEquationAst.
*
* Return the @c Type of this @ref AnalyserEquationAst.
*
* @return The @c Type.
*/
Type type() const;
/**
* @brief Set the type of this @ref AnalyserEquationAst.
*
* Set the type of this @ref AnalyserEquationAst.
*
* @param type The @ref AnalyserEquationAst type to be set.
*/
void setType(Type type);
/**
* @brief Get the value for this @ref AnalyserEquationAst.
*
* Return the value for this @ref AnalyserEquationAst.
*
* @return The value.
*/
std::string value() const;
/**
* @brief Set the value for this @ref AnalyserEquationAst.
*
* Set the value for this @ref AnalyserEquationAst.
*
* @param value The @c std::string to be set as the value for this
* @ref AnalyserEquationAst.
*/
void setValue(const std::string &value);
/**
* @brief Get the @c Variable for this @ref AnalyserEquationAst.
*
* Return the @c Variable for this @ref AnalyserEquationAst.
*
* @return The variable.
*/
VariablePtr variable() const;
/**
* @brief Set the @c Variable for this @ref AnalyserEquationAst.
*
* Set the @c Variable for this @ref AnalyserEquationAst.
*
* @param variable The @c Variable to be set as the variable for this
* @ref AnalyserEquationAst.
*/
void setVariable(const VariablePtr &variable);
/**
* @brief Get the parent of this @ref AnalyserEquationAst.
*
* Return the parent of this @ref AnalyserEquationAst.
*
* @return The parent.
*/
AnalyserEquationAstPtr parent() const;
/**
* @brief Set the parent of this @ref AnalyserEquationAst.
*
* Set the parent of this @ref AnalyserEquationAst.
*
* @param parent The @ref AnalyserEquationAst to be set as the parent of this
* @ref AnalyserEquationAst.
*/
void setParent(const AnalyserEquationAstPtr &parent);
/**
* @brief Get the left child for this @ref AnalyserEquationAst.
*
* Return the left child of this @ref AnalyserEquationAst.
*
* @return The left child.
*/
AnalyserEquationAstPtr leftChild() const;
/**
* @brief Set the left child of this @ref AnalyserEquationAst.
*
* Set the left child of this @ref AnalyserEquationAst.
*
* @param leftChild The @ref AnalyserEquationAst to be set as the left child
* of this @ref AnalyserEquationAst.
*/
void setLeftChild(const AnalyserEquationAstPtr &leftChild);
/**
* @brief Get the right child for this @ref AnalyserEquationAst.
*
* Return the right child of this @ref AnalyserEquationAst.
*
* @return The right child.
*/
AnalyserEquationAstPtr rightChild() const;
/**
* @brief Set the right child of this @ref AnalyserEquationAst.
*
* Set the right child of this @ref AnalyserEquationAst.
*
* @param rightChild The @ref AnalyserEquationAst to be set as the right child
* of this @ref AnalyserEquationAst.
*/
void setRightChild(const AnalyserEquationAstPtr &rightChild);
private:
AnalyserEquationAst(); /**< Constructor, @private. */
struct AnalyserEquationAstImpl;
AnalyserEquationAstImpl *mPimpl; /**< Private member to implementation pointer, @private. */
};
} // namespace libcellml
| 27.940845 | 108 | 0.592701 | [
"object",
"model"
] |
586eb0d62d7aab019295a3b95823208d443ef751 | 7,309 | c | C | web/JsResponse.c | Sc-Softs/Multi-Threading-JS-Engine | 3f58ae7c2098b2084a71281d9c911510ae6e0c48 | [
"MIT"
] | null | null | null | web/JsResponse.c | Sc-Softs/Multi-Threading-JS-Engine | 3f58ae7c2098b2084a71281d9c911510ae6e0c48 | [
"MIT"
] | null | null | null | web/JsResponse.c | Sc-Softs/Multi-Threading-JS-Engine | 3f58ae7c2098b2084a71281d9c911510ae6e0c48 | [
"MIT"
] | null | null | null | #include"JsObject.h"
#include"JsContext.h"
#include"JsEngine.h"
#include"JsVm.h"
#include"JsList.h"
#include"JsValue.h"
#include"JsSys.h"
#include"JsDebug.h"
#include"JsException.h"
#include"JsAst.h"
#include"JsParser.h"
#include"JsEval.h"
#include"JsWeb.h"
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<setjmp.h>
#include<unistd.h>
#include <sys/dir.h>
#include <sys/stat.h>
#include <microhttpd.h>
#define JS_RESPONSE_FLOOR 1
/*以下的内存为手动管理*/
struct JsHeader{
char* key;
char* value;
};
struct JsResponse{
//连接
struct MHD_Connection *connection;
//状态码
int code;
//body已经使用的大小
int bUsed;
//body大小
int bTotal;
//HTML BODY
char* body;
//head已经使用
int hUsed;
//head已经使用的大小, 空为NULL
int hTotal;
//HTML Header
struct JsHeader* header;
};
static void JsInitResponse(struct JsObject* response);
static void setHeader(struct JsObject *self, struct JsObject *thisobj, int argc, struct JsValue **argv, struct JsValue *res);
static void setStatus(struct JsObject *self, struct JsObject *thisobj, int argc, struct JsValue **argv, struct JsValue *res);
/*unistd 重名修改为write0*/
static void write0(struct JsObject *self, struct JsObject *thisobj, int argc, struct JsValue **argv, struct JsValue *res);
static void clear(struct JsObject *self, struct JsObject *thisobj, int argc, struct JsValue **argv, struct JsValue *res);
/*
Js:
setHeader(String,String): 是一个通用的标头设定方法,您可以用它来设定任何「名称/值」的标头.
setStatus(Number): 状态码
write(String) : 写入返回文本
*/
struct JsObject* JsCreateResponse(struct MHD_Connection *connection){
struct JsObject* b = JsAllocObject(JS_RESPONSE_FLOOR);
JsCreateStandardObject(b);
b->Class = "Response";
//初始化自己的Sb
struct JsResponse* p = (struct JsResponse*)malloc(sizeof(struct JsResponse));
p->connection = connection;
p->code = 200;
p->bUsed = 0;
p->bTotal = 128;
p->body = calloc(sizeof(char),p->bTotal);
p->hTotal = 2;
p->hUsed = 0;
p->header = (struct JsHeader* )calloc(sizeof(struct JsHeader) ,p->hTotal);
b->sb[JS_RESPONSE_FLOOR] = p;
//初始化Object方法函数
JsInitResponse(b);
return b;
}
/*
将response提交到queue中, 并且销毁
*/
int JsSubmitResponse(struct JsObject* obj){
if(strcmp(obj->Class,"Response")!=0)
JsThrowString("The Object Is't Response");
struct JsResponse* response = (struct JsResponse*)obj->sb[JS_RESPONSE_FLOOR];
if(response == NULL)
JsThrowString("The Response Is Burned");
struct MHD_Response *HTMLResponse = NULL;
//构建HTML response
HTMLResponse = MHD_create_response_from_buffer (response->bUsed,
(void *) response->body,
MHD_RESPMEM_MUST_COPY);
//配置header
int i;
for(i=0;i<response->hUsed;++i){
MHD_add_response_header (HTMLResponse, response->header[i].key, response->header[i].value);
}
//配置状态码
int ret = MHD_queue_response (response->connection, response->code, HTMLResponse);
MHD_destroy_response (HTMLResponse);
//释放内存
free(response->body);
for(i=0;i<response->hUsed;++i){
free(response->header[i].key);
free(response->header[i].value);
}
free(response->header);
free(response);
obj->sb[JS_RESPONSE_FLOOR] = NULL;
return ret;
}
static void JsInitResponse(struct JsObject* response){
struct JsValue* p= NULL;
p= JsCreateValue();
p->type = JS_OBJECT;
p->u.object = JsCreateStandardFunctionObject(NULL,NULL,FALSE);
p->u.object->Call = &setHeader;
(*response->Put)(response,"setHeader",p,JS_OBJECT_ATTR_STRICT);
p= JsCreateValue();
p->type = JS_OBJECT;
p->u.object = JsCreateStandardFunctionObject(NULL,NULL,FALSE);
p->u.object->Call = &setStatus;
(*response->Put)(response,"setStatus",p,JS_OBJECT_ATTR_STRICT);
p= JsCreateValue();
p->type = JS_OBJECT;
p->u.object = JsCreateStandardFunctionObject(NULL,NULL,FALSE);
p->u.object->Call = &write0;
(*response->Put)(response,"write",p,JS_OBJECT_ATTR_STRICT);
p= JsCreateValue();
p->type = JS_OBJECT;
p->u.object = JsCreateStandardFunctionObject(NULL,NULL,FALSE);
p->u.object->Call = &clear;
(*response->Put)(response,"clear",p,JS_OBJECT_ATTR_STRICT);
}
static void setHeader(struct JsObject *self, struct JsObject *thisobj, int argc, struct JsValue **argv, struct JsValue *res){
if(strcmp(thisobj->Class,"Response")!=0)
JsThrowString("The Object Is't Response");
if(argc >= 2 && argv[0]->type == JS_STRING && argv[0]->u.string != NULL
&& argv[1]->type == JS_STRING && argv[1]->u.string != NULL){
struct JsResponse* response = (struct JsResponse*)thisobj->sb[JS_RESPONSE_FLOOR];
if(response == NULL)
JsThrowString("The Response Is Burned");
int i;
int flag = TRUE;
//判断是否已经存在该Header Key
for(i=0;i<response->hUsed;++i){
if(strcmp(response->header[i].key,argv[0]->u.string) == 0){
//已经存在Key在Head中, 仅仅使用覆盖的方式
flag = FALSE;
//释放先前的内存
free(response->header[i].value);
char* value = (char*)malloc(strlen(argv[1]->u.string)+4);
strcpy(value,argv[1]->u.string);
response->header[i].value = value;
break;
}
}
if(flag == TRUE){
//先前不存在Key对应的Header
//检验空间是否足够
if(response->hUsed == response->hTotal){
response->hTotal += 2;
//申请新空间
response->header = realloc(response->header,sizeof(struct JsHeader)*response->hTotal);
}
response->header[response->hUsed].key = (char*)malloc(strlen(argv[0]->u.string)+4);
response->header[response->hUsed].value = (char*)malloc(strlen(argv[1]->u.string)+4);
strcpy(response->header[response->hUsed].key,argv[0]->u.string);
strcpy(response->header[response->hUsed].value,argv[1]->u.string);
response->hUsed++;
}
}else{
JsThrowString("Response Args Is Error");
}
}
static void setStatus(struct JsObject *self, struct JsObject *thisobj, int argc, struct JsValue **argv, struct JsValue *res){
if(strcmp(thisobj->Class,"Response")!=0)
JsThrowString("The Object Is't Response");
if(argc >= 1 && argv[0]->type == JS_NUMBER && argv[0]->u.number >=0){
struct JsResponse* response = (struct JsResponse*)thisobj->sb[JS_RESPONSE_FLOOR];
if(response == NULL)
JsThrowString("The Response Is Burned");
response->code = argv[0]->u.number;
}else{
JsThrowString("setStatus Args Is Error");
}
}
static void write0(struct JsObject *self, struct JsObject *thisobj, int argc, struct JsValue **argv, struct JsValue *res){
if(strcmp(thisobj->Class,"Response")!=0)
JsThrowString("The Object Is't Response");
if(argc >= 1 && argv[0]->type == JS_STRING && argv[0]->u.string != NULL){
struct JsResponse* response = (struct JsResponse*)thisobj->sb[JS_RESPONSE_FLOOR];
if(response == NULL)
JsThrowString("The Response Is Burned");
int sizeOfString = strlen(argv[0]->u.string);
//检查空间大小
if(response->bUsed + sizeOfString > response->bTotal){
//增加空间
response->bTotal += response->bUsed*2 + sizeOfString + 4;
response->body = realloc(response->body,response->bTotal);
}
memcpy(&response->body[response->bUsed],argv[0]->u.string,sizeOfString);
//大小变大
response->bUsed+=sizeOfString;
}else{
JsThrowString("setStatus Args Is Error");
}
}
static void clear(struct JsObject *self, struct JsObject *thisobj, int argc, struct JsValue **argv, struct JsValue *res){
if(strcmp(thisobj->Class,"Response")!=0)
JsThrowString("The Object Is't Response");
struct JsResponse* response = (struct JsResponse*)thisobj->sb[JS_RESPONSE_FLOOR];
if(response == NULL)
JsThrowString("The Response Is Burned");
response->bUsed = 0;
} | 29.591093 | 125 | 0.702695 | [
"object"
] |
58995cbe142059804e67ed50d8d41f79e1b9952e | 8,999 | h | C | Pod/Classes/Model/SKSession.h | ThePantsThief/SnapchatKit | 6c478cb08bc7211d2ccac02c368d92dc7bbbe50e | [
"MIT"
] | 111 | 2015-05-24T11:28:48.000Z | 2017-03-03T01:25:14.000Z | Pod/Classes/Model/SKSession.h | ThePantsThief/SnapchatKit | 6c478cb08bc7211d2ccac02c368d92dc7bbbe50e | [
"MIT"
] | 29 | 2015-06-19T11:05:52.000Z | 2017-02-26T23:35:48.000Z | Pod/Classes/Model/SKSession.h | ThePantsThief/SnapchatKit | 6c478cb08bc7211d2ccac02c368d92dc7bbbe50e | [
"MIT"
] | 28 | 2015-06-25T23:07:10.000Z | 2016-12-29T08:59:21.000Z | //
// SKSession.h
// SnapchatKit
//
// Created by Tanner Bennett on 5/18/15.
// Copyright (c) 2015 Tanner Bennett. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreGraphics/CGBase.h>
#import "SKThing.h"
@class SKMessage, SKConversation, SKSimpleUser, SKUser, SKAddedFriend, SKStoryCollection, SKUserStory, SKStory, SKTrophy;
extern SKStoryPrivacy SKStoryPrivacyFromString(NSString *storyPrivacyString);
@interface SKSession : SKThing //<NSCoding>
+ (instancetype)sessionWithJSONResponse:(NSDictionary *)json;
/** Merges the recieving object with the data in the old object. Returns the recieving object. */
- (SKSession *)mergeWithOldSession:(SKSession *)session;
/** @return An array of unread \c SKSnap and \c SKMessage objects in \c conversations. */
- (NSArray *)unread;
/** Not sure what this is for. Might be "new stories since you last checked". */
@property (nonatomic, readonly) BOOL storiesDelta;
@property (nonatomic, readonly) BOOL emailVerified;
@property (nonatomic, readonly) BOOL highAccuracyRequiredForNearby;
@property (nonatomic, readonly) BOOL requirePhonePasswordConfirmed;
@property (nonatomic, readonly) CGFloat redGearDurationMilliseconds;
@property (nonatomic, readonly) NSUInteger suggestedFriendFetchThresholdHours;
@property (nonatomic, readonly) NSString *backgroundFetchSecret;
/** Contains keys \c "mac" and \c "payload" */
@property (nonatomic, readonly) NSDictionary *messagingGatewayAuth;
@property (nonatomic, readonly) NSString *messagingGatewayServer;
@property (nonatomic, readonly) NSDictionary *serverInfo;
@property (nonatomic, readonly) NSString *checksums;
@property (nonatomic, readonly) NSArray<NSString *> *IAPEnabledCurrencies;
@property (nonatomic, readonly) NSArray<NSString *> *enabledLensStoreCurrencies;
/** Undocumented. */
@property (nonatomic, readonly) NSArray<NSString *> *industries;
#pragma mark User data
@property (nonatomic, readonly) NSString *friendsSyncToken;
@property (nonatomic, readonly) NSString *friendsSyncType;
@property (nonatomic, readonly) NSMutableOrderedSet<SKUser *> *friends;
@property (nonatomic, readonly) NSMutableOrderedSet<SKAddedFriend *> *addedFriends;
@property (nonatomic, readonly) NSMutableOrderedSet<NSString *> *bestFriendUsernames;
/** Array of username strings of users who have added you but not been added back by you. */
@property (nonatomic, readonly) NSMutableOrderedSet<NSString *> *pendingRequests;
@property (nonatomic, readonly) NSMutableOrderedSet<SKConversation *> *conversations;
@property (nonatomic, readonly) NSMutableOrderedSet<SKStoryCollection *> *stories;
@property (nonatomic, readonly) NSMutableOrderedSet<SKUserStory *> *userStories;
@property (nonatomic, readonly) NSMutableOrderedSet<SKStory *> *groupStories;
@property (nonatomic, readonly) NSArray<SKTrophy *> *trophyCase;
/** The date trophies were last checked for. */
@property (nonatomic, readonly) NSDate *lastCheckedTrophies;
/** A dictionary of the friendmoji settings. */
@property (nonatomic, readonly) NSDictionary *friendmojis;
@property (nonatomic, readonly) NSDictionary *friendmojisReadOnly;
@property (nonatomic, readonly) NSDictionary *friendmojisMutable;
#pragma mark Discover
@property (nonatomic, readonly) BOOL discoverSupported;
@property (nonatomic, readonly) BOOL discoverSharingEnabled;
@property (nonatomic, readonly) NSString *discoverGetChannels;
/** Used internally to load Discover snaps. */
@property (nonatomic, readonly) NSString *discoverResourceParamName;
/** Used internally to load Discover snaps. */
@property (nonatomic, readonly) NSString *discoverResourceParamValue;
/** Used internally to load Discover snaps. */
@property (nonatomic, readonly) NSString *discoverVideoCatalog;
/** Undocumented. */
@property (nonatomic, readonly) NSDictionary *sponsored;
#pragma mark Cash information
@property (nonatomic, readonly) BOOL canUseCash;
@property (nonatomic, readonly) BOOL isCashActive;
/** Seems to be your username. */
@property (nonatomic, readonly) NSString *cashCustomerIdentifier;
/** i.e. "SQUARE" */
@property (nonatomic, readonly) NSString *cashProvider;
/** Keys: "snapcash_new_tos_accepted", "snapcash_tos_v2_accepted", "square_tos_accepted", "tou_9_14_accepted" */
@property (nonatomic, readonly) NSDictionary *clientProperties;
#pragma mark Basic user information
@property (nonatomic, readonly) NSString *username;
@property (nonatomic, readonly) NSString *email;
@property (nonatomic, readonly) NSString *mobileNumber;
@property (nonatomic, readonly) NSUInteger recieved;
@property (nonatomic, readonly) NSUInteger sent;
@property (nonatomic, readonly) NSUInteger score;
/** Array of usernames. */
@property (nonatomic, readonly) NSArray *recents;
/** Probably an array of usernames. */
@property (nonatomic, readonly) NSArray *requests;
#pragma mark Account information
@property (nonatomic, readonly) NSDate *addedFriendsTimestamp;
@property (nonatomic, readonly) NSString *authToken;
@property (nonatomic, readonly) BOOL canSeeMatureContent;
/** i.e. "US" */
@property (nonatomic, readonly) NSString *countryCode;
//@property (nonatomic, readonly) NSDate *lastTimestamp;
@property (nonatomic, readonly) NSString *devicetoken;
@property (nonatomic, readonly) BOOL canSaveStoryToGallery;
/** Unknown. */
@property (nonatomic, readonly) BOOL canVideoTranscodingAndroid;
@property (nonatomic, readonly) BOOL imageCaption;
@property (nonatomic, readonly) BOOL requireRefreshingProfileMedia;
/** Whether two-factor-authentication is enabled. */
@property (nonatomic, readonly) BOOL isTwoFAEnabled;
@property (nonatomic, readonly) NSDate *lastAddressBookUpdateDate;
@property (nonatomic, readonly) NSDate *lastReplayedSnapDate;
/** Unknown. */
@property (nonatomic, readonly) BOOL logged;
@property (nonatomic, readonly) NSString *mobileVerificationKey;
@property (nonatomic, readonly) BOOL canUploadRawThumbnail;
/** Array of strings. Known values:
swipe_filters, my_story, profile_pictures, snap, caption,
swipe_down_to_dismiss_tapping_quickly, discover_onboarding,
trophy_case, tap_to_skip, new_friend_request,
swipe_down_to_dismiss, first_location, profile
*/
@property (nonatomic, readonly) NSArray *seenTooltips;
@property (nonatomic, readonly) BOOL shouldCallToVerifyNumber;
@property (nonatomic, readonly) BOOL shouldTextToVerifyNumber;
/** YES if everyone can send you snaps, NO if only friends can. */
/** Unknown. */
@property (nonatomic, readonly) NSString *snapchatPhoneNumber;
@property (nonatomic, readonly) NSDictionary *studySettings;
/** Contains keys "age" and "gender". */
@property (nonatomic, readonly) NSDictionary *targeting;
@property (nonatomic, readonly) NSString *userIdentifier;
@property (nonatomic, readonly) BOOL videoFiltersEnabled;
@property (nonatomic, readonly) NSString *QRPath;
#pragma mark User preferences
@property (nonatomic, readonly) BOOL enableNotificationSounds;
@property (nonatomic, readonly) NSUInteger numberOfBestFriends;
@property (nonatomic, readonly) SKStoryPrivacy storyPrivacy;
@property (nonatomic, readonly) BOOL isSearchableByPhoneNumber;
@property (nonatomic, readonly) BOOL privacyEveryone;
@property (nonatomic, readonly) BOOL ringerSoundOn;
#pragma mark Features
@property (nonatomic, readonly) BOOL enableFrontFacingFlash;
@property (nonatomic, readonly) BOOL enablePowerSaveMode;
@property (nonatomic, readonly) BOOL enableReplaySnaps;
@property (nonatomic, readonly) BOOL enableSmartFilters;
@property (nonatomic, readonly) BOOL enableSpecialText;
@property (nonatomic, readonly) BOOL enableSwipeCashMode;
@property (nonatomic, readonly) BOOL enableVisualFilters;
@property (nonatomic, readonly) BOOL enableTravelMode;
@property (nonatomic, readonly) BOOL enableGuggenheim;
@property (nonatomic, readonly) BOOL lensStoreEnabled;
@property (nonatomic, readonly) BOOL QRCodeEnabled;
@property (nonatomic, readonly) BOOL prefetchStoreLensesEnabled;
@property (nonatomic, readonly) BOOL payReplaySnaps;
@property (nonatomic, readonly) NSDictionary *featuresNotUserConfigurable;
@end
@interface SKSession (Friends)
/** @return The \c SKUser object associated with \e username, or \c nil if the user could not be found. */
- (SKSimpleUser *)userWithUsername:(NSString *)username;
- (SKAddedFriend *)addedFriendWithUsername:(NSString *)username;
- (SKUser *)friendWithUsername:(NSString *)username;
/** @return The \c SKConversation associated \e username, or \c nil if it hasn't been loaded or does not exist. @note It makes no sense to pass in your own username. */
- (SKConversation *)conversationWithUser:(NSString *)username;
@end
@interface SKSession (Stories)
/** @return All stories in \c stories that are shared. */
- (NSArray *)sharedStories;
@end
| 43.684466 | 168 | 0.762307 | [
"object"
] |
589ca783c9cd1f531e4e28df69a59947b8815f09 | 12,721 | h | C | Engine/Source/Runtime/Engine/Classes/PhysicsEngine/PhysicsConstraintComponent.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | Engine/Source/Runtime/Engine/Classes/PhysicsEngine/PhysicsConstraintComponent.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | Engine/Source/Runtime/Engine/Classes/PhysicsEngine/PhysicsConstraintComponent.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "PhysicsEngine/ConstraintInstance.h"
#include "PhysicsConstraintComponent.generated.h"
/** Dynamic delegate to use by components that want to route the broken-event into blueprints */
DECLARE_DYNAMIC_MULTICAST_DELEGATE_OneParam(FConstraintBrokenSignature, int32, ConstraintIndex);
/**
* This is effectively a joint that allows you to connect 2 rigid bodies together. You can create different types of joints using the various parameters of this component.
*/
UCLASS(ClassGroup=Physics, MinimalAPI, meta=(BlueprintSpawnableComponent), HideCategories=(Activation,"Components|Activation", Physics, Mobility), ShowCategories=("Physics|Components|PhysicsConstraint"))
class UPhysicsConstraintComponent : public USceneComponent
{
GENERATED_UCLASS_BODY()
/** Pointer to first Actor to constrain. */
UPROPERTY(EditInstanceOnly, Category=Constraint)
AActor* ConstraintActor1;
/**
* Name of first component property to constrain. If Actor1 is NULL, will look within Owner.
* If this is NULL, will use RootComponent of Actor1
*/
UPROPERTY(EditAnywhere, Category=Constraint)
FConstrainComponentPropName ComponentName1;
/** Pointer to second Actor to constrain. */
UPROPERTY(EditInstanceOnly, Category=Constraint)
AActor* ConstraintActor2;
/**
* Name of second component property to constrain. If Actor2 is NULL, will look within Owner.
* If this is NULL, will use RootComponent of Actor2
*/
UPROPERTY(EditAnywhere, Category=Constraint)
FConstrainComponentPropName ComponentName2;
/** Allows direct setting of first component to constraint. */
TWeakObjectPtr<UPrimitiveComponent> OverrideComponent1;
/** Allows direct setting of second component to constraint. */
TWeakObjectPtr<UPrimitiveComponent> OverrideComponent2;
UPROPERTY(instanced)
class UPhysicsConstraintTemplate* ConstraintSetup_DEPRECATED;
/** Notification when constraint is broken. */
UPROPERTY(BlueprintAssignable)
FConstraintBrokenSignature OnConstraintBroken;
public:
/** All constraint settings */
UPROPERTY(EditAnywhere, Category=ConstraintComponent, meta=(ShowOnlyInnerProperties))
FConstraintInstance ConstraintInstance;
//Begin UObject Interface
virtual void BeginDestroy() override;
virtual void PostLoad() override;
#if WITH_EDITOR
virtual void PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) override;
#endif // WITH_EDITOR
//End UObject interface
//Begin ActorComponent interface
#if WITH_EDITOR
virtual void CheckForErrors() override;
virtual void OnRegister() override;
#endif // WITH_EDITOR
virtual void OnUnregister() override;
virtual void InitializeComponent() override;
//End ActorComponent interface
// Begin SceneComponent interface
#if WITH_EDITOR
virtual void PostEditComponentMove(bool bFinished) override;
#endif // WITH_EDITOR
// End SceneComponent interface
/** Get the body frame. Works without constraint being created */
ENGINE_API FTransform GetBodyTransform(EConstraintFrame::Type Frame) const;
/** Get body bounding box. Works without constraint being created */
ENGINE_API FBox GetBodyBox(EConstraintFrame::Type Frame) const;
/** Initialize the frames and creates constraint */
void InitComponentConstraint();
/** Break the constraint */
void TermComponentConstraint();
/** Directly specify component to connect. Will update frames based on current position. */
UFUNCTION(BlueprintCallable, Category="Physics|Components|PhysicsConstraint")
ENGINE_API void SetConstrainedComponents(UPrimitiveComponent* Component1, FName BoneName1, UPrimitiveComponent* Component2, FName BoneName2);
/** Break this constraint */
UFUNCTION(BlueprintCallable, Category="Physics|Components|PhysicsConstraint")
ENGINE_API void BreakConstraint();
/** Enables/Disables linear position drive
*
* @param bEnableDriveX Indicates whether the drive for the X-Axis should be enabled
* @param bEnableDriveY Indicates whether the drive for the Y-Axis should be enabled
* @param bEnableDriveZ Indicates whether the drive for the Z-Axis should be enabled
*/
UFUNCTION(BlueprintCallable, Category="Physics|Components|PhysicsConstraint")
ENGINE_API void SetLinearPositionDrive(bool bEnableDriveX, bool bEnableDriveY, bool bEnableDriveZ);
/** Enables/Disables linear position drive
*
* @param bEnableDriveX Indicates whether the drive for the X-Axis should be enabled
* @param bEnableDriveY Indicates whether the drive for the Y-Axis should be enabled
* @param bEnableDriveZ Indicates whether the drive for the Z-Axis should be enabled
*/
UFUNCTION(BlueprintCallable, Category="Physics|Components|PhysicsConstraint")
ENGINE_API void SetLinearVelocityDrive(bool bEnableDriveX, bool bEnableDriveY, bool bEnableDriveZ);
/** Enables/Disables angular orientation drive
*
* @param bEnableSwingDrive Indicates whether the drive for the swing axis should be enabled
* @param bEnableTwistDrive Indicates whether the drive for the twist axis should be enabled
*/
UFUNCTION(BlueprintCallable, Category="Physics|Components|PhysicsConstraint")
ENGINE_API void SetAngularOrientationDrive(bool bEnableSwingDrive, bool bEnableTwistDrive);
/** Enables/Disables angular velocity drive
*
* @param bEnableSwingDrive Indicates whether the drive for the swing axis should be enabled
* @param bEnableTwistDrive Indicates whether the drive for the twit axis should be enabled
*/
UFUNCTION(BlueprintCallable, Category="Physics|Components|PhysicsConstraint")
ENGINE_API void SetAngularVelocityDrive(bool bEnableSwingDrive, bool bEnableTwistDrive);
/** Sets the target position for the linear drive.
* @param InPosTarget Target position
*/
UFUNCTION(BlueprintCallable, Category="Physics|Components|PhysicsConstraint")
ENGINE_API void SetLinearPositionTarget(const FVector& InPosTarget);
/** Sets the target velocity for the linear drive.
* @param InVelTarget Target velocity
*/
UFUNCTION(BlueprintCallable, Category="Physics|Components|PhysicsConstraint")
ENGINE_API void SetLinearVelocityTarget(const FVector& InVelTarget);
/** Sets the drive params for the linear drive.
* @param InSpring Spring force for the drive
* @param InDamping Damping of the drive
* @param InForceLimit Max force applied by the drive
*/
UFUNCTION(BlueprintCallable, Category="Physics|Components|PhysicsConstraint")
ENGINE_API void SetLinearDriveParams(float InSpring, float InDamping, float InForceLimit);
/** Sets the target orientation for the angular drive.
* @param InPosTarget Target orientation
*/
UFUNCTION(BlueprintCallable, Category="Physics|Components|PhysicsConstraint")
ENGINE_API void SetAngularOrientationTarget(const FRotator& InPosTarget);
/** Sets the target velocity for the angular drive.
* @param InVelTarget Target velocity
*/
UFUNCTION(BlueprintCallable, Category="Physics|Components|PhysicsConstraint")
ENGINE_API void SetAngularVelocityTarget(const FVector& InVelTarget);
/** Sets the drive params for the angular drive.
* @param InSpring Spring force for the drive
* @param InDamping Damping of the drive
* @param InForceLimit Max force applied by the drive
*/
UFUNCTION(BlueprintCallable, Category="Physics|Components|PhysicsConstraint")
ENGINE_API void SetAngularDriveParams(float InSpring, float InDamping, float InForceLimit);
/** Sets the LinearX Motion Type
* @param ConstraintType New Constraint Type
* @param LimitSize Size of limit
*/
UFUNCTION(BlueprintCallable, Category = "Physics|Components|PhysicsConstraint")
ENGINE_API void SetLinearXLimit(ELinearConstraintMotion ConstraintType, float LimitSize);
/** Sets the LinearY Motion Type
* @param ConstraintType New Constraint Type
* @param LimitSize Size of limit
*/
UFUNCTION(BlueprintCallable, Category = "Physics|Components|PhysicsConstraint")
ENGINE_API void SetLinearYLimit(ELinearConstraintMotion ConstraintType, float LimitSize);
/** Sets the LinearZ Motion Type
* @param ConstraintType New Constraint Type
* @param LimitSize Size of limit
*/
UFUNCTION(BlueprintCallable, Category = "Physics|Components|PhysicsConstraint")
ENGINE_API void SetLinearZLimit(ELinearConstraintMotion ConstraintType, float LimitSize);
/** Sets the Angular Swing1 Motion Type
* @param ConstraintType New Constraint Type
* @param Swing1LimitAngle Size of limit in degrees
*/
UFUNCTION(BlueprintCallable, Category = "Physics|Components|PhysicsConstraint")
ENGINE_API void SetAngularSwing1Limit(EAngularConstraintMotion MotionType, float Swing1LimitAngle);
/** Sets the Angular Swing2 Motion Type
* @param ConstraintType New Constraint Type
* @param Swing2LimitAngle Size of limit in degrees
*/
UFUNCTION(BlueprintCallable, Category = "Physics|Components|PhysicsConstraint")
ENGINE_API void SetAngularSwing2Limit(EAngularConstraintMotion MotionType, float Swing2LimitAngle);
/** Sets the Angular Twist Motion Type
* @param ConstraintType New Constraint Type
* @param TwistLimitAngle Size of limit in degrees
*/
UFUNCTION(BlueprintCallable, Category = "Physics|Components|PhysicsConstraint")
ENGINE_API void SetAngularTwistLimit(EAngularConstraintMotion ConstraintType, float TwistLimitAngle);
/** Gets the current Angular Twist of the constraint */
UFUNCTION(BlueprintCallable, Category = "Physics|Components|PhysicsConstraint")
ENGINE_API float GetCurrentTwist() const;
/** Gets the current Swing1 of the constraint */
UFUNCTION(BlueprintCallable, Category = "Physics|Components|PhysicsConstraint")
ENGINE_API float GetCurrentSwing1() const;
/** Gets the current Swing2 of the constraint */
UFUNCTION(BlueprintCallable, Category = "Physics|Components|PhysicsConstraint")
ENGINE_API float GetCurrentSwing2() const;
/**
* Update the reference frames held inside the constraint that indicate the joint location in the reference frame
* of the two connected bodies. You should call this whenever the constraint or either Component moves, or if you change
* the connected Components. This function does nothing though once the joint has been initialized.
*/
ENGINE_API void UpdateConstraintFrames();
// Pass in reference frame in. If the constraint is currently active, this will set its active local pose. Otherwise the change will take affect in InitConstraint.
UFUNCTION(BlueprintCallable, Category = "Physics|Components|PhysicsConstraint")
ENGINE_API void SetConstraintReferenceFrame(EConstraintFrame::Type Frame, const FTransform& RefFrame);
// Pass in reference position in (maintains reference orientation). If the constraint is currently active, this will set its active local pose. Otherwise the change will take affect in InitConstraint.
UFUNCTION(BlueprintCallable, Category = "Physics|Components|PhysicsConstraint")
ENGINE_API void SetConstraintReferencePosition(EConstraintFrame::Type Frame, const FVector& RefPosition);
// Pass in reference orientation in (maintains reference position). If the constraint is currently active, this will set its active local pose. Otherwise the change will take affect in InitConstraint.
UFUNCTION(BlueprintCallable, Category = "Physics|Components|PhysicsConstraint")
ENGINE_API void SetConstraintReferenceOrientation(EConstraintFrame::Type Frame, const FVector& PriAxis, const FVector& SecAxis);
// If true, the collision between the two rigid bodies of the constraint will be disabled.
UFUNCTION(BlueprintCallable, Category = "Physics|Components|PhysicsConstraint")
ENGINE_API void SetDisableCollision(bool bDisableCollision);
// Retrieve the constraint force most recently applied to maintain this constraint. Returns 0 forces if the constraint is not initialized or broken.
UFUNCTION(BlueprintCallable, Category = "Physics|Components|PhysicsConstraint")
ENGINE_API void GetConstraintForce(FVector& OutLinearForce, FVector& OutAngularForce);
#if WITH_EDITOR
ENGINE_API void UpdateSpriteTexture();
#endif
protected:
/** Get the body instance that we want to constrain to */
FBodyInstance* GetBodyInstance(EConstraintFrame::Type Frame) const;
/** Internal util to get body transform from actor/component name/bone name information */
FTransform GetBodyTransformInternal(EConstraintFrame::Type Frame, FName InBoneName) const;
/** Internal util to get body box from actor/component name/bone name information */
FBox GetBodyBoxInternal(EConstraintFrame::Type Frame, FName InBoneName) const;
/** Internal util to get component from actor/component name */
UPrimitiveComponent* GetComponentInternal(EConstraintFrame::Type Frame) const;
/** Routes the FConstraint callback to the dynamic delegate */
void OnConstraintBrokenHandler(FConstraintInstance* BrokenConstraint);
};
| 45.432143 | 203 | 0.800959 | [
"transform"
] |
58a24679f6aad435eb7d6334d6c73b1c43e3203e | 42,962 | h | C | src/SharedLibrary/IntegrationTests/GeneratedCode/SharedLibraryTests_L2NormalizeFeaturizer.h | Bhaskers-Blu-Org2/FeaturizersLibrary | 229ae38ea233bfb02a6ff92ec3a67c1751c58005 | [
"MIT"
] | 15 | 2019-12-14T07:54:18.000Z | 2021-03-14T14:53:28.000Z | src/SharedLibrary/IntegrationTests/GeneratedCode/SharedLibraryTests_L2NormalizeFeaturizer.h | Bhaskers-Blu-Org2/FeaturizersLibrary | 229ae38ea233bfb02a6ff92ec3a67c1751c58005 | [
"MIT"
] | 30 | 2019-12-03T20:58:56.000Z | 2020-04-21T23:34:39.000Z | src/SharedLibrary/IntegrationTests/GeneratedCode/SharedLibraryTests_L2NormalizeFeaturizer.h | microsoft/FeaturizersLibrary | 229ae38ea233bfb02a6ff92ec3a67c1751c58005 | [
"MIT"
] | 13 | 2020-01-23T00:18:47.000Z | 2021-10-04T17:46:45.000Z | /* ---------------------------------------------------------------------- */
/* Copyright (c) Microsoft Corporation. All rights reserved. */
/* Licensed under the MIT License */
/* ---------------------------------------------------------------------- */
#pragma once
#include "SharedLibrary_L2NormalizeFeaturizer.h"
#include "Traits.h"
#include "Featurizers/Structs.h"
#include "SharedLibraryTests_Common.hpp"
#if (defined _MSC_VER)
# pragma warning(push)
// I don't know why MSVC thinks that there is unreachable
// code in these methods during release builds.
# pragma warning(disable: 4702) // Unreachable code
# pragma warning(disable: 4701) // potentially uninitialized local variable '<name>' used
# pragma warning(disable: 4703) // potentially uninitialized local pointer variable '<name>' used
#endif
/* ---------------------------------------------------------------------- */
/* | L2NormalizeFeaturizer <int8> */
template <typename VectorInputT>
void L2NormalizeFeaturizer_int8_Test(
std::vector<VectorInputT> const &training_input,
std::vector<VectorInputT> const &inference_input,
std::function<bool (std::vector<std::vector<std::double_t>> const &)> const &verify_func
) {
ErrorInfoHandle * pErrorInfo(nullptr);
// Create the estimator
L2NormalizeFeaturizer_int8_EstimatorHandle *pEstimatorHandle(nullptr);
REQUIRE(L2NormalizeFeaturizer_int8_CreateEstimator(&pEstimatorHandle, &pErrorInfo));
REQUIRE(pEstimatorHandle != nullptr);
REQUIRE(pErrorInfo == nullptr);
// Train
if(training_input.empty() == false) {
typename std::vector<VectorInputT>::const_iterator iter(training_input.begin());
while(true) {
TrainingState trainingState(0);
REQUIRE(L2NormalizeFeaturizer_int8_GetState(pEstimatorHandle, &trainingState, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
if(trainingState != Training)
break;
FitResult result(0);
auto const & input(*iter);
REQUIRE(L2NormalizeFeaturizer_int8_Fit(pEstimatorHandle, input.data(), input.size(), &result, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
if(result == ResetAndContinue) {
iter = training_input.begin();
continue;
}
++iter;
if(iter == training_input.end()) {
REQUIRE(L2NormalizeFeaturizer_int8_OnDataCompleted(pEstimatorHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
iter = training_input.begin();
}
}
}
L2NormalizeFeaturizer_int8_CompleteTraining(pEstimatorHandle, &pErrorInfo);
REQUIRE(pErrorInfo == nullptr);
// Once here, training should be complete
{
bool is_complete(false);
REQUIRE(L2NormalizeFeaturizer_int8_IsTrainingComplete(pEstimatorHandle, &is_complete, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
REQUIRE(is_complete);
}
// Create the Transformer
L2NormalizeFeaturizer_int8_TransformerHandle * pTransformerHandle(nullptr);
REQUIRE(L2NormalizeFeaturizer_int8_CreateTransformerFromEstimator(pEstimatorHandle, &pTransformerHandle, &pErrorInfo));
REQUIRE(pTransformerHandle != nullptr);
REQUIRE(pErrorInfo == nullptr);
// Destroy the estimator
REQUIRE(L2NormalizeFeaturizer_int8_DestroyEstimator(pEstimatorHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
// Inference
std::vector<std::vector<std::double_t>> results;
results.reserve(inference_input.size());
for(auto const & input : inference_input) {
std::double_t* results_item_value_items;
size_t results_items;
REQUIRE(L2NormalizeFeaturizer_int8_Transform(pTransformerHandle, input.data(), input.size(), &results_item_value_items, &results_items, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
typename decltype(results)::value_type results_buffer;
results_buffer.reserve(results_items);
std::double_t* results_item_value_items_ptr(results_item_value_items);
while(results_buffer.size() < results_items) {
std::double_t & results_item_value(*results_item_value_items_ptr);
results_buffer.emplace_back(std::move(results_item_value));
++results_item_value_items_ptr;
}
results.emplace_back(std::move(results_buffer));
// Destroy the contents
REQUIRE(L2NormalizeFeaturizer_int8_DestroyTransformedData(results_item_value_items, results_items, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
}
REQUIRE(verify_func(results));
// No trailing destroy statement
// Destroy the transformer
REQUIRE(L2NormalizeFeaturizer_int8_DestroyTransformer(pTransformerHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
}
/* ---------------------------------------------------------------------- */
/* | L2NormalizeFeaturizer <int16> */
template <typename VectorInputT>
void L2NormalizeFeaturizer_int16_Test(
std::vector<VectorInputT> const &training_input,
std::vector<VectorInputT> const &inference_input,
std::function<bool (std::vector<std::vector<std::double_t>> const &)> const &verify_func
) {
ErrorInfoHandle * pErrorInfo(nullptr);
// Create the estimator
L2NormalizeFeaturizer_int16_EstimatorHandle *pEstimatorHandle(nullptr);
REQUIRE(L2NormalizeFeaturizer_int16_CreateEstimator(&pEstimatorHandle, &pErrorInfo));
REQUIRE(pEstimatorHandle != nullptr);
REQUIRE(pErrorInfo == nullptr);
// Train
if(training_input.empty() == false) {
typename std::vector<VectorInputT>::const_iterator iter(training_input.begin());
while(true) {
TrainingState trainingState(0);
REQUIRE(L2NormalizeFeaturizer_int16_GetState(pEstimatorHandle, &trainingState, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
if(trainingState != Training)
break;
FitResult result(0);
auto const & input(*iter);
REQUIRE(L2NormalizeFeaturizer_int16_Fit(pEstimatorHandle, input.data(), input.size(), &result, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
if(result == ResetAndContinue) {
iter = training_input.begin();
continue;
}
++iter;
if(iter == training_input.end()) {
REQUIRE(L2NormalizeFeaturizer_int16_OnDataCompleted(pEstimatorHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
iter = training_input.begin();
}
}
}
L2NormalizeFeaturizer_int16_CompleteTraining(pEstimatorHandle, &pErrorInfo);
REQUIRE(pErrorInfo == nullptr);
// Once here, training should be complete
{
bool is_complete(false);
REQUIRE(L2NormalizeFeaturizer_int16_IsTrainingComplete(pEstimatorHandle, &is_complete, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
REQUIRE(is_complete);
}
// Create the Transformer
L2NormalizeFeaturizer_int16_TransformerHandle * pTransformerHandle(nullptr);
REQUIRE(L2NormalizeFeaturizer_int16_CreateTransformerFromEstimator(pEstimatorHandle, &pTransformerHandle, &pErrorInfo));
REQUIRE(pTransformerHandle != nullptr);
REQUIRE(pErrorInfo == nullptr);
// Destroy the estimator
REQUIRE(L2NormalizeFeaturizer_int16_DestroyEstimator(pEstimatorHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
// Inference
std::vector<std::vector<std::double_t>> results;
results.reserve(inference_input.size());
for(auto const & input : inference_input) {
std::double_t* results_item_value_items;
size_t results_items;
REQUIRE(L2NormalizeFeaturizer_int16_Transform(pTransformerHandle, input.data(), input.size(), &results_item_value_items, &results_items, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
typename decltype(results)::value_type results_buffer;
results_buffer.reserve(results_items);
std::double_t* results_item_value_items_ptr(results_item_value_items);
while(results_buffer.size() < results_items) {
std::double_t & results_item_value(*results_item_value_items_ptr);
results_buffer.emplace_back(std::move(results_item_value));
++results_item_value_items_ptr;
}
results.emplace_back(std::move(results_buffer));
// Destroy the contents
REQUIRE(L2NormalizeFeaturizer_int16_DestroyTransformedData(results_item_value_items, results_items, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
}
REQUIRE(verify_func(results));
// No trailing destroy statement
// Destroy the transformer
REQUIRE(L2NormalizeFeaturizer_int16_DestroyTransformer(pTransformerHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
}
/* ---------------------------------------------------------------------- */
/* | L2NormalizeFeaturizer <int32> */
template <typename VectorInputT>
void L2NormalizeFeaturizer_int32_Test(
std::vector<VectorInputT> const &training_input,
std::vector<VectorInputT> const &inference_input,
std::function<bool (std::vector<std::vector<std::double_t>> const &)> const &verify_func
) {
ErrorInfoHandle * pErrorInfo(nullptr);
// Create the estimator
L2NormalizeFeaturizer_int32_EstimatorHandle *pEstimatorHandle(nullptr);
REQUIRE(L2NormalizeFeaturizer_int32_CreateEstimator(&pEstimatorHandle, &pErrorInfo));
REQUIRE(pEstimatorHandle != nullptr);
REQUIRE(pErrorInfo == nullptr);
// Train
if(training_input.empty() == false) {
typename std::vector<VectorInputT>::const_iterator iter(training_input.begin());
while(true) {
TrainingState trainingState(0);
REQUIRE(L2NormalizeFeaturizer_int32_GetState(pEstimatorHandle, &trainingState, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
if(trainingState != Training)
break;
FitResult result(0);
auto const & input(*iter);
REQUIRE(L2NormalizeFeaturizer_int32_Fit(pEstimatorHandle, input.data(), input.size(), &result, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
if(result == ResetAndContinue) {
iter = training_input.begin();
continue;
}
++iter;
if(iter == training_input.end()) {
REQUIRE(L2NormalizeFeaturizer_int32_OnDataCompleted(pEstimatorHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
iter = training_input.begin();
}
}
}
L2NormalizeFeaturizer_int32_CompleteTraining(pEstimatorHandle, &pErrorInfo);
REQUIRE(pErrorInfo == nullptr);
// Once here, training should be complete
{
bool is_complete(false);
REQUIRE(L2NormalizeFeaturizer_int32_IsTrainingComplete(pEstimatorHandle, &is_complete, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
REQUIRE(is_complete);
}
// Create the Transformer
L2NormalizeFeaturizer_int32_TransformerHandle * pTransformerHandle(nullptr);
REQUIRE(L2NormalizeFeaturizer_int32_CreateTransformerFromEstimator(pEstimatorHandle, &pTransformerHandle, &pErrorInfo));
REQUIRE(pTransformerHandle != nullptr);
REQUIRE(pErrorInfo == nullptr);
// Destroy the estimator
REQUIRE(L2NormalizeFeaturizer_int32_DestroyEstimator(pEstimatorHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
// Inference
std::vector<std::vector<std::double_t>> results;
results.reserve(inference_input.size());
for(auto const & input : inference_input) {
std::double_t* results_item_value_items;
size_t results_items;
REQUIRE(L2NormalizeFeaturizer_int32_Transform(pTransformerHandle, input.data(), input.size(), &results_item_value_items, &results_items, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
typename decltype(results)::value_type results_buffer;
results_buffer.reserve(results_items);
std::double_t* results_item_value_items_ptr(results_item_value_items);
while(results_buffer.size() < results_items) {
std::double_t & results_item_value(*results_item_value_items_ptr);
results_buffer.emplace_back(std::move(results_item_value));
++results_item_value_items_ptr;
}
results.emplace_back(std::move(results_buffer));
// Destroy the contents
REQUIRE(L2NormalizeFeaturizer_int32_DestroyTransformedData(results_item_value_items, results_items, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
}
REQUIRE(verify_func(results));
// No trailing destroy statement
// Destroy the transformer
REQUIRE(L2NormalizeFeaturizer_int32_DestroyTransformer(pTransformerHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
}
/* ---------------------------------------------------------------------- */
/* | L2NormalizeFeaturizer <int64> */
template <typename VectorInputT>
void L2NormalizeFeaturizer_int64_Test(
std::vector<VectorInputT> const &training_input,
std::vector<VectorInputT> const &inference_input,
std::function<bool (std::vector<std::vector<std::double_t>> const &)> const &verify_func
) {
ErrorInfoHandle * pErrorInfo(nullptr);
// Create the estimator
L2NormalizeFeaturizer_int64_EstimatorHandle *pEstimatorHandle(nullptr);
REQUIRE(L2NormalizeFeaturizer_int64_CreateEstimator(&pEstimatorHandle, &pErrorInfo));
REQUIRE(pEstimatorHandle != nullptr);
REQUIRE(pErrorInfo == nullptr);
// Train
if(training_input.empty() == false) {
typename std::vector<VectorInputT>::const_iterator iter(training_input.begin());
while(true) {
TrainingState trainingState(0);
REQUIRE(L2NormalizeFeaturizer_int64_GetState(pEstimatorHandle, &trainingState, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
if(trainingState != Training)
break;
FitResult result(0);
auto const & input(*iter);
REQUIRE(L2NormalizeFeaturizer_int64_Fit(pEstimatorHandle, input.data(), input.size(), &result, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
if(result == ResetAndContinue) {
iter = training_input.begin();
continue;
}
++iter;
if(iter == training_input.end()) {
REQUIRE(L2NormalizeFeaturizer_int64_OnDataCompleted(pEstimatorHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
iter = training_input.begin();
}
}
}
L2NormalizeFeaturizer_int64_CompleteTraining(pEstimatorHandle, &pErrorInfo);
REQUIRE(pErrorInfo == nullptr);
// Once here, training should be complete
{
bool is_complete(false);
REQUIRE(L2NormalizeFeaturizer_int64_IsTrainingComplete(pEstimatorHandle, &is_complete, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
REQUIRE(is_complete);
}
// Create the Transformer
L2NormalizeFeaturizer_int64_TransformerHandle * pTransformerHandle(nullptr);
REQUIRE(L2NormalizeFeaturizer_int64_CreateTransformerFromEstimator(pEstimatorHandle, &pTransformerHandle, &pErrorInfo));
REQUIRE(pTransformerHandle != nullptr);
REQUIRE(pErrorInfo == nullptr);
// Destroy the estimator
REQUIRE(L2NormalizeFeaturizer_int64_DestroyEstimator(pEstimatorHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
// Inference
std::vector<std::vector<std::double_t>> results;
results.reserve(inference_input.size());
for(auto const & input : inference_input) {
std::double_t* results_item_value_items;
size_t results_items;
REQUIRE(L2NormalizeFeaturizer_int64_Transform(pTransformerHandle, input.data(), input.size(), &results_item_value_items, &results_items, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
typename decltype(results)::value_type results_buffer;
results_buffer.reserve(results_items);
std::double_t* results_item_value_items_ptr(results_item_value_items);
while(results_buffer.size() < results_items) {
std::double_t & results_item_value(*results_item_value_items_ptr);
results_buffer.emplace_back(std::move(results_item_value));
++results_item_value_items_ptr;
}
results.emplace_back(std::move(results_buffer));
// Destroy the contents
REQUIRE(L2NormalizeFeaturizer_int64_DestroyTransformedData(results_item_value_items, results_items, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
}
REQUIRE(verify_func(results));
// No trailing destroy statement
// Destroy the transformer
REQUIRE(L2NormalizeFeaturizer_int64_DestroyTransformer(pTransformerHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
}
/* ---------------------------------------------------------------------- */
/* | L2NormalizeFeaturizer <uint8> */
template <typename VectorInputT>
void L2NormalizeFeaturizer_uint8_Test(
std::vector<VectorInputT> const &training_input,
std::vector<VectorInputT> const &inference_input,
std::function<bool (std::vector<std::vector<std::double_t>> const &)> const &verify_func
) {
ErrorInfoHandle * pErrorInfo(nullptr);
// Create the estimator
L2NormalizeFeaturizer_uint8_EstimatorHandle *pEstimatorHandle(nullptr);
REQUIRE(L2NormalizeFeaturizer_uint8_CreateEstimator(&pEstimatorHandle, &pErrorInfo));
REQUIRE(pEstimatorHandle != nullptr);
REQUIRE(pErrorInfo == nullptr);
// Train
if(training_input.empty() == false) {
typename std::vector<VectorInputT>::const_iterator iter(training_input.begin());
while(true) {
TrainingState trainingState(0);
REQUIRE(L2NormalizeFeaturizer_uint8_GetState(pEstimatorHandle, &trainingState, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
if(trainingState != Training)
break;
FitResult result(0);
auto const & input(*iter);
REQUIRE(L2NormalizeFeaturizer_uint8_Fit(pEstimatorHandle, input.data(), input.size(), &result, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
if(result == ResetAndContinue) {
iter = training_input.begin();
continue;
}
++iter;
if(iter == training_input.end()) {
REQUIRE(L2NormalizeFeaturizer_uint8_OnDataCompleted(pEstimatorHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
iter = training_input.begin();
}
}
}
L2NormalizeFeaturizer_uint8_CompleteTraining(pEstimatorHandle, &pErrorInfo);
REQUIRE(pErrorInfo == nullptr);
// Once here, training should be complete
{
bool is_complete(false);
REQUIRE(L2NormalizeFeaturizer_uint8_IsTrainingComplete(pEstimatorHandle, &is_complete, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
REQUIRE(is_complete);
}
// Create the Transformer
L2NormalizeFeaturizer_uint8_TransformerHandle * pTransformerHandle(nullptr);
REQUIRE(L2NormalizeFeaturizer_uint8_CreateTransformerFromEstimator(pEstimatorHandle, &pTransformerHandle, &pErrorInfo));
REQUIRE(pTransformerHandle != nullptr);
REQUIRE(pErrorInfo == nullptr);
// Destroy the estimator
REQUIRE(L2NormalizeFeaturizer_uint8_DestroyEstimator(pEstimatorHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
// Inference
std::vector<std::vector<std::double_t>> results;
results.reserve(inference_input.size());
for(auto const & input : inference_input) {
std::double_t* results_item_value_items;
size_t results_items;
REQUIRE(L2NormalizeFeaturizer_uint8_Transform(pTransformerHandle, input.data(), input.size(), &results_item_value_items, &results_items, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
typename decltype(results)::value_type results_buffer;
results_buffer.reserve(results_items);
std::double_t* results_item_value_items_ptr(results_item_value_items);
while(results_buffer.size() < results_items) {
std::double_t & results_item_value(*results_item_value_items_ptr);
results_buffer.emplace_back(std::move(results_item_value));
++results_item_value_items_ptr;
}
results.emplace_back(std::move(results_buffer));
// Destroy the contents
REQUIRE(L2NormalizeFeaturizer_uint8_DestroyTransformedData(results_item_value_items, results_items, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
}
REQUIRE(verify_func(results));
// No trailing destroy statement
// Destroy the transformer
REQUIRE(L2NormalizeFeaturizer_uint8_DestroyTransformer(pTransformerHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
}
/* ---------------------------------------------------------------------- */
/* | L2NormalizeFeaturizer <uint16> */
template <typename VectorInputT>
void L2NormalizeFeaturizer_uint16_Test(
std::vector<VectorInputT> const &training_input,
std::vector<VectorInputT> const &inference_input,
std::function<bool (std::vector<std::vector<std::double_t>> const &)> const &verify_func
) {
ErrorInfoHandle * pErrorInfo(nullptr);
// Create the estimator
L2NormalizeFeaturizer_uint16_EstimatorHandle *pEstimatorHandle(nullptr);
REQUIRE(L2NormalizeFeaturizer_uint16_CreateEstimator(&pEstimatorHandle, &pErrorInfo));
REQUIRE(pEstimatorHandle != nullptr);
REQUIRE(pErrorInfo == nullptr);
// Train
if(training_input.empty() == false) {
typename std::vector<VectorInputT>::const_iterator iter(training_input.begin());
while(true) {
TrainingState trainingState(0);
REQUIRE(L2NormalizeFeaturizer_uint16_GetState(pEstimatorHandle, &trainingState, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
if(trainingState != Training)
break;
FitResult result(0);
auto const & input(*iter);
REQUIRE(L2NormalizeFeaturizer_uint16_Fit(pEstimatorHandle, input.data(), input.size(), &result, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
if(result == ResetAndContinue) {
iter = training_input.begin();
continue;
}
++iter;
if(iter == training_input.end()) {
REQUIRE(L2NormalizeFeaturizer_uint16_OnDataCompleted(pEstimatorHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
iter = training_input.begin();
}
}
}
L2NormalizeFeaturizer_uint16_CompleteTraining(pEstimatorHandle, &pErrorInfo);
REQUIRE(pErrorInfo == nullptr);
// Once here, training should be complete
{
bool is_complete(false);
REQUIRE(L2NormalizeFeaturizer_uint16_IsTrainingComplete(pEstimatorHandle, &is_complete, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
REQUIRE(is_complete);
}
// Create the Transformer
L2NormalizeFeaturizer_uint16_TransformerHandle * pTransformerHandle(nullptr);
REQUIRE(L2NormalizeFeaturizer_uint16_CreateTransformerFromEstimator(pEstimatorHandle, &pTransformerHandle, &pErrorInfo));
REQUIRE(pTransformerHandle != nullptr);
REQUIRE(pErrorInfo == nullptr);
// Destroy the estimator
REQUIRE(L2NormalizeFeaturizer_uint16_DestroyEstimator(pEstimatorHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
// Inference
std::vector<std::vector<std::double_t>> results;
results.reserve(inference_input.size());
for(auto const & input : inference_input) {
std::double_t* results_item_value_items;
size_t results_items;
REQUIRE(L2NormalizeFeaturizer_uint16_Transform(pTransformerHandle, input.data(), input.size(), &results_item_value_items, &results_items, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
typename decltype(results)::value_type results_buffer;
results_buffer.reserve(results_items);
std::double_t* results_item_value_items_ptr(results_item_value_items);
while(results_buffer.size() < results_items) {
std::double_t & results_item_value(*results_item_value_items_ptr);
results_buffer.emplace_back(std::move(results_item_value));
++results_item_value_items_ptr;
}
results.emplace_back(std::move(results_buffer));
// Destroy the contents
REQUIRE(L2NormalizeFeaturizer_uint16_DestroyTransformedData(results_item_value_items, results_items, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
}
REQUIRE(verify_func(results));
// No trailing destroy statement
// Destroy the transformer
REQUIRE(L2NormalizeFeaturizer_uint16_DestroyTransformer(pTransformerHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
}
/* ---------------------------------------------------------------------- */
/* | L2NormalizeFeaturizer <uint32> */
template <typename VectorInputT>
void L2NormalizeFeaturizer_uint32_Test(
std::vector<VectorInputT> const &training_input,
std::vector<VectorInputT> const &inference_input,
std::function<bool (std::vector<std::vector<std::double_t>> const &)> const &verify_func
) {
ErrorInfoHandle * pErrorInfo(nullptr);
// Create the estimator
L2NormalizeFeaturizer_uint32_EstimatorHandle *pEstimatorHandle(nullptr);
REQUIRE(L2NormalizeFeaturizer_uint32_CreateEstimator(&pEstimatorHandle, &pErrorInfo));
REQUIRE(pEstimatorHandle != nullptr);
REQUIRE(pErrorInfo == nullptr);
// Train
if(training_input.empty() == false) {
typename std::vector<VectorInputT>::const_iterator iter(training_input.begin());
while(true) {
TrainingState trainingState(0);
REQUIRE(L2NormalizeFeaturizer_uint32_GetState(pEstimatorHandle, &trainingState, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
if(trainingState != Training)
break;
FitResult result(0);
auto const & input(*iter);
REQUIRE(L2NormalizeFeaturizer_uint32_Fit(pEstimatorHandle, input.data(), input.size(), &result, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
if(result == ResetAndContinue) {
iter = training_input.begin();
continue;
}
++iter;
if(iter == training_input.end()) {
REQUIRE(L2NormalizeFeaturizer_uint32_OnDataCompleted(pEstimatorHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
iter = training_input.begin();
}
}
}
L2NormalizeFeaturizer_uint32_CompleteTraining(pEstimatorHandle, &pErrorInfo);
REQUIRE(pErrorInfo == nullptr);
// Once here, training should be complete
{
bool is_complete(false);
REQUIRE(L2NormalizeFeaturizer_uint32_IsTrainingComplete(pEstimatorHandle, &is_complete, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
REQUIRE(is_complete);
}
// Create the Transformer
L2NormalizeFeaturizer_uint32_TransformerHandle * pTransformerHandle(nullptr);
REQUIRE(L2NormalizeFeaturizer_uint32_CreateTransformerFromEstimator(pEstimatorHandle, &pTransformerHandle, &pErrorInfo));
REQUIRE(pTransformerHandle != nullptr);
REQUIRE(pErrorInfo == nullptr);
// Destroy the estimator
REQUIRE(L2NormalizeFeaturizer_uint32_DestroyEstimator(pEstimatorHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
// Inference
std::vector<std::vector<std::double_t>> results;
results.reserve(inference_input.size());
for(auto const & input : inference_input) {
std::double_t* results_item_value_items;
size_t results_items;
REQUIRE(L2NormalizeFeaturizer_uint32_Transform(pTransformerHandle, input.data(), input.size(), &results_item_value_items, &results_items, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
typename decltype(results)::value_type results_buffer;
results_buffer.reserve(results_items);
std::double_t* results_item_value_items_ptr(results_item_value_items);
while(results_buffer.size() < results_items) {
std::double_t & results_item_value(*results_item_value_items_ptr);
results_buffer.emplace_back(std::move(results_item_value));
++results_item_value_items_ptr;
}
results.emplace_back(std::move(results_buffer));
// Destroy the contents
REQUIRE(L2NormalizeFeaturizer_uint32_DestroyTransformedData(results_item_value_items, results_items, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
}
REQUIRE(verify_func(results));
// No trailing destroy statement
// Destroy the transformer
REQUIRE(L2NormalizeFeaturizer_uint32_DestroyTransformer(pTransformerHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
}
/* ---------------------------------------------------------------------- */
/* | L2NormalizeFeaturizer <uint64> */
template <typename VectorInputT>
void L2NormalizeFeaturizer_uint64_Test(
std::vector<VectorInputT> const &training_input,
std::vector<VectorInputT> const &inference_input,
std::function<bool (std::vector<std::vector<std::double_t>> const &)> const &verify_func
) {
ErrorInfoHandle * pErrorInfo(nullptr);
// Create the estimator
L2NormalizeFeaturizer_uint64_EstimatorHandle *pEstimatorHandle(nullptr);
REQUIRE(L2NormalizeFeaturizer_uint64_CreateEstimator(&pEstimatorHandle, &pErrorInfo));
REQUIRE(pEstimatorHandle != nullptr);
REQUIRE(pErrorInfo == nullptr);
// Train
if(training_input.empty() == false) {
typename std::vector<VectorInputT>::const_iterator iter(training_input.begin());
while(true) {
TrainingState trainingState(0);
REQUIRE(L2NormalizeFeaturizer_uint64_GetState(pEstimatorHandle, &trainingState, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
if(trainingState != Training)
break;
FitResult result(0);
auto const & input(*iter);
REQUIRE(L2NormalizeFeaturizer_uint64_Fit(pEstimatorHandle, input.data(), input.size(), &result, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
if(result == ResetAndContinue) {
iter = training_input.begin();
continue;
}
++iter;
if(iter == training_input.end()) {
REQUIRE(L2NormalizeFeaturizer_uint64_OnDataCompleted(pEstimatorHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
iter = training_input.begin();
}
}
}
L2NormalizeFeaturizer_uint64_CompleteTraining(pEstimatorHandle, &pErrorInfo);
REQUIRE(pErrorInfo == nullptr);
// Once here, training should be complete
{
bool is_complete(false);
REQUIRE(L2NormalizeFeaturizer_uint64_IsTrainingComplete(pEstimatorHandle, &is_complete, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
REQUIRE(is_complete);
}
// Create the Transformer
L2NormalizeFeaturizer_uint64_TransformerHandle * pTransformerHandle(nullptr);
REQUIRE(L2NormalizeFeaturizer_uint64_CreateTransformerFromEstimator(pEstimatorHandle, &pTransformerHandle, &pErrorInfo));
REQUIRE(pTransformerHandle != nullptr);
REQUIRE(pErrorInfo == nullptr);
// Destroy the estimator
REQUIRE(L2NormalizeFeaturizer_uint64_DestroyEstimator(pEstimatorHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
// Inference
std::vector<std::vector<std::double_t>> results;
results.reserve(inference_input.size());
for(auto const & input : inference_input) {
std::double_t* results_item_value_items;
size_t results_items;
REQUIRE(L2NormalizeFeaturizer_uint64_Transform(pTransformerHandle, input.data(), input.size(), &results_item_value_items, &results_items, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
typename decltype(results)::value_type results_buffer;
results_buffer.reserve(results_items);
std::double_t* results_item_value_items_ptr(results_item_value_items);
while(results_buffer.size() < results_items) {
std::double_t & results_item_value(*results_item_value_items_ptr);
results_buffer.emplace_back(std::move(results_item_value));
++results_item_value_items_ptr;
}
results.emplace_back(std::move(results_buffer));
// Destroy the contents
REQUIRE(L2NormalizeFeaturizer_uint64_DestroyTransformedData(results_item_value_items, results_items, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
}
REQUIRE(verify_func(results));
// No trailing destroy statement
// Destroy the transformer
REQUIRE(L2NormalizeFeaturizer_uint64_DestroyTransformer(pTransformerHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
}
/* ---------------------------------------------------------------------- */
/* | L2NormalizeFeaturizer <float> */
template <typename VectorInputT>
void L2NormalizeFeaturizer_float_Test(
std::vector<VectorInputT> const &training_input,
std::vector<VectorInputT> const &inference_input,
std::function<bool (std::vector<std::vector<std::double_t>> const &)> const &verify_func
) {
ErrorInfoHandle * pErrorInfo(nullptr);
// Create the estimator
L2NormalizeFeaturizer_float_EstimatorHandle *pEstimatorHandle(nullptr);
REQUIRE(L2NormalizeFeaturizer_float_CreateEstimator(&pEstimatorHandle, &pErrorInfo));
REQUIRE(pEstimatorHandle != nullptr);
REQUIRE(pErrorInfo == nullptr);
// Train
if(training_input.empty() == false) {
typename std::vector<VectorInputT>::const_iterator iter(training_input.begin());
while(true) {
TrainingState trainingState(0);
REQUIRE(L2NormalizeFeaturizer_float_GetState(pEstimatorHandle, &trainingState, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
if(trainingState != Training)
break;
FitResult result(0);
auto const & input(*iter);
REQUIRE(L2NormalizeFeaturizer_float_Fit(pEstimatorHandle, input.data(), input.size(), &result, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
if(result == ResetAndContinue) {
iter = training_input.begin();
continue;
}
++iter;
if(iter == training_input.end()) {
REQUIRE(L2NormalizeFeaturizer_float_OnDataCompleted(pEstimatorHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
iter = training_input.begin();
}
}
}
L2NormalizeFeaturizer_float_CompleteTraining(pEstimatorHandle, &pErrorInfo);
REQUIRE(pErrorInfo == nullptr);
// Once here, training should be complete
{
bool is_complete(false);
REQUIRE(L2NormalizeFeaturizer_float_IsTrainingComplete(pEstimatorHandle, &is_complete, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
REQUIRE(is_complete);
}
// Create the Transformer
L2NormalizeFeaturizer_float_TransformerHandle * pTransformerHandle(nullptr);
REQUIRE(L2NormalizeFeaturizer_float_CreateTransformerFromEstimator(pEstimatorHandle, &pTransformerHandle, &pErrorInfo));
REQUIRE(pTransformerHandle != nullptr);
REQUIRE(pErrorInfo == nullptr);
// Destroy the estimator
REQUIRE(L2NormalizeFeaturizer_float_DestroyEstimator(pEstimatorHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
// Inference
std::vector<std::vector<std::double_t>> results;
results.reserve(inference_input.size());
for(auto const & input : inference_input) {
std::double_t* results_item_value_items;
size_t results_items;
REQUIRE(L2NormalizeFeaturizer_float_Transform(pTransformerHandle, input.data(), input.size(), &results_item_value_items, &results_items, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
typename decltype(results)::value_type results_buffer;
results_buffer.reserve(results_items);
std::double_t* results_item_value_items_ptr(results_item_value_items);
while(results_buffer.size() < results_items) {
std::double_t & results_item_value(*results_item_value_items_ptr);
results_buffer.emplace_back(std::move(results_item_value));
++results_item_value_items_ptr;
}
results.emplace_back(std::move(results_buffer));
// Destroy the contents
REQUIRE(L2NormalizeFeaturizer_float_DestroyTransformedData(results_item_value_items, results_items, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
}
REQUIRE(verify_func(results));
// No trailing destroy statement
// Destroy the transformer
REQUIRE(L2NormalizeFeaturizer_float_DestroyTransformer(pTransformerHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
}
/* ---------------------------------------------------------------------- */
/* | L2NormalizeFeaturizer <double> */
template <typename VectorInputT>
void L2NormalizeFeaturizer_double_Test(
std::vector<VectorInputT> const &training_input,
std::vector<VectorInputT> const &inference_input,
std::function<bool (std::vector<std::vector<std::double_t>> const &)> const &verify_func
) {
ErrorInfoHandle * pErrorInfo(nullptr);
// Create the estimator
L2NormalizeFeaturizer_double_EstimatorHandle *pEstimatorHandle(nullptr);
REQUIRE(L2NormalizeFeaturizer_double_CreateEstimator(&pEstimatorHandle, &pErrorInfo));
REQUIRE(pEstimatorHandle != nullptr);
REQUIRE(pErrorInfo == nullptr);
// Train
if(training_input.empty() == false) {
typename std::vector<VectorInputT>::const_iterator iter(training_input.begin());
while(true) {
TrainingState trainingState(0);
REQUIRE(L2NormalizeFeaturizer_double_GetState(pEstimatorHandle, &trainingState, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
if(trainingState != Training)
break;
FitResult result(0);
auto const & input(*iter);
REQUIRE(L2NormalizeFeaturizer_double_Fit(pEstimatorHandle, input.data(), input.size(), &result, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
if(result == ResetAndContinue) {
iter = training_input.begin();
continue;
}
++iter;
if(iter == training_input.end()) {
REQUIRE(L2NormalizeFeaturizer_double_OnDataCompleted(pEstimatorHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
iter = training_input.begin();
}
}
}
L2NormalizeFeaturizer_double_CompleteTraining(pEstimatorHandle, &pErrorInfo);
REQUIRE(pErrorInfo == nullptr);
// Once here, training should be complete
{
bool is_complete(false);
REQUIRE(L2NormalizeFeaturizer_double_IsTrainingComplete(pEstimatorHandle, &is_complete, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
REQUIRE(is_complete);
}
// Create the Transformer
L2NormalizeFeaturizer_double_TransformerHandle * pTransformerHandle(nullptr);
REQUIRE(L2NormalizeFeaturizer_double_CreateTransformerFromEstimator(pEstimatorHandle, &pTransformerHandle, &pErrorInfo));
REQUIRE(pTransformerHandle != nullptr);
REQUIRE(pErrorInfo == nullptr);
// Destroy the estimator
REQUIRE(L2NormalizeFeaturizer_double_DestroyEstimator(pEstimatorHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
// Inference
std::vector<std::vector<std::double_t>> results;
results.reserve(inference_input.size());
for(auto const & input : inference_input) {
std::double_t* results_item_value_items;
size_t results_items;
REQUIRE(L2NormalizeFeaturizer_double_Transform(pTransformerHandle, input.data(), input.size(), &results_item_value_items, &results_items, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
typename decltype(results)::value_type results_buffer;
results_buffer.reserve(results_items);
std::double_t* results_item_value_items_ptr(results_item_value_items);
while(results_buffer.size() < results_items) {
std::double_t & results_item_value(*results_item_value_items_ptr);
results_buffer.emplace_back(std::move(results_item_value));
++results_item_value_items_ptr;
}
results.emplace_back(std::move(results_buffer));
// Destroy the contents
REQUIRE(L2NormalizeFeaturizer_double_DestroyTransformedData(results_item_value_items, results_items, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
}
REQUIRE(verify_func(results));
// No trailing destroy statement
// Destroy the transformer
REQUIRE(L2NormalizeFeaturizer_double_DestroyTransformer(pTransformerHandle, &pErrorInfo));
REQUIRE(pErrorInfo == nullptr);
}
#if (defined _MSC_VER)
# pragma warning(pop)
#endif
| 36.1633 | 161 | 0.653089 | [
"vector"
] |
58a6e862affeb85ef11dc7e49de3a05fb14472e3 | 6,884 | c | C | c2000/C2000Ware_1_00_06_00/driverlib/f2837xd/examples/dual/ram/ram_ex1_management_cpu2.c | ramok/Themis_ForHPSDR | d0f323a843ac0a488ef816ccb7c828032855a40a | [
"Unlicense"
] | null | null | null | c2000/C2000Ware_1_00_06_00/driverlib/f2837xd/examples/dual/ram/ram_ex1_management_cpu2.c | ramok/Themis_ForHPSDR | d0f323a843ac0a488ef816ccb7c828032855a40a | [
"Unlicense"
] | null | null | null | c2000/C2000Ware_1_00_06_00/driverlib/f2837xd/examples/dual/ram/ram_ex1_management_cpu2.c | ramok/Themis_ForHPSDR | d0f323a843ac0a488ef816ccb7c828032855a40a | [
"Unlicense"
] | 1 | 2021-07-21T08:10:37.000Z | 2021-07-21T08:10:37.000Z | //#############################################################################
//
// FILE: ram_ex1_management_cpu2.c
//
// TITLE: RAM Management Example (CPU2)
//
// This example shows how to assign shared RAM for use by both the CPU2 and
// CPU1 core.
//
// Shared RAM regions are defined in both the CPU2 and CPU1 linker files.
//
// In this example GS0 and GS14 are assigned to/owned by CPU2.
// - cpu2RWArray[] is mapped to shared RAM GS0
// - cpu2RArray[] is mapped to shared RAM GS1
// - cpuTimer0ISR is copied to shared RAM GS14, toggles LED1
//
//#############################################################################
// $TI Release: F2837xD Support Library v3.05.00.00 $
// $Release Date: Thu Oct 18 15:48:42 CDT 2018 $
// $Copyright:
// Copyright (C) 2013-2018 Texas Instruments Incorporated - http://www.ti.com/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the
// distribution.
//
// Neither the name of Texas Instruments Incorporated 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.
// $
//#############################################################################
//
// Included Files
//
#include "driverlib.h"
#include "device.h"
#include "F2837xD_Ipc_drivers.h"
//
// Globals
//
uint16_t cpu2RWArray[256]; // Mapped to GS1 of shared RAM owned by CPU02
uint16_t cpu2RArray[256]; // Mapped to GS0 of shared RAM owned by CPU01
#pragma DATA_SECTION(cpu2RArray,"SHARERAMGS1");
#pragma DATA_SECTION(cpu2RWArray,"SHARERAMGS0");
extern uint16_t isrfuncLoadStart;
extern uint16_t isrfuncLoadEnd;
extern uint16_t isrfuncRunStart;
extern uint16_t isrfuncLoadSize;
//
// Function Prototypes
//
void initCPUTimer(uint32_t);
void configCPUTimer(uint32_t, float, float);
__interrupt void cpuTimer0ISR(void);
#pragma CODE_SECTION(cpuTimer0ISR, "isrfunc")
void writeDataCPU2(void);
//
// Main
//
void main(void)
{
//
// Initialize PIE and clear PIE registers. Disables CPU interrupts.
//
Interrupt_initModule();
//
// Initialize the PIE vector table with pointers to the shell Interrupt
// Service Routines (ISR).
//
Interrupt_initVectorTable();
//
// Wait until shared RAM is available.
//
while((HWREGH(MEMCFG_BASE + MEMCFG_O_GSXMSEL) &
(MEMCFG_GSXMSEL_MSEL_GS14 | MEMCFG_GSXMSEL_MSEL_GS15)) == 0U)
{
}
//
// Copy the ISR to a specified RAM location
//
memcpy(&isrfuncRunStart, &isrfuncLoadStart, (uint32_t)&isrfuncLoadSize);
//
// Interrupts that are used in this example are re-mapped to ISR functions
// found within this file.
//
Interrupt_register(INT_TIMER0, &cpuTimer0ISR);
//
// Configure CPU Timer 0 to a 1 second period
//
initCPUTimer(CPUTIMER0_BASE);
configCPUTimer(CPUTIMER0_BASE, DEVICE_SYSCLK_FREQ, 1000000);
//
// Start CPU Timer 0
//
CPUTimer_startTimer(CPUTIMER0_BASE);
//
// Enable CPU Timer 0 interrupt
//
Interrupt_enable(INT_TIMER0);
//
// Enable Global Interrupt (INTM) and realtime interrupt (DBGM)
//
EINT;
ERTM;
//
// Loop indefinitely
//
while(1)
{
if(IPCRtoLFlagBusy(IPC_FLAG10) == 1)
{
//
// Read cpu2RArray and modify cpu2RWArray
//
writeDataCPU2();
IPCRtoLFlagAcknowledge(IPC_FLAG10);
}
}
}
//
// initCPUTimer - This function initializes a CPU Timer to a known state.
//
void
initCPUTimer(uint32_t cpuTimer)
{
//
// Initialize timer period to maximum
//
CPUTimer_setPeriod(cpuTimer, 0xFFFFFFFF);
//
// Initialize pre-scale counter to divide by 1 (SYSCLKOUT)
//
CPUTimer_setPreScaler(cpuTimer, 0);
//
// Make sure timer is stopped
//
CPUTimer_stopTimer(cpuTimer);
//
// Reload all counter registers with period value
//
CPUTimer_reloadTimerCounter(cpuTimer);
}
//
// configCPUTimer - This function initializes the selected timer to the
// period specified by the "freq" and "period" parameters. The "freq" is
// entered as Hz and the period in microseconds. The timer is held in the
// stopped state after configuration.
//
void
configCPUTimer(uint32_t cpuTimer, float freq, float period)
{
uint32_t temp;
//
// Initialize timer period:
//
temp = (uint32_t)(freq / 1000000 * period);
CPUTimer_setPeriod(cpuTimer, temp);
//
// Set pre-scale counter to divide by 1 (SYSCLKOUT):
//
CPUTimer_setPreScaler(cpuTimer, 0);
//
// Initializes timer control register. The timer is stopped, reloaded,
// free run disabled, and interrupt enabled.
//
CPUTimer_stopTimer(cpuTimer);
CPUTimer_reloadTimerCounter(cpuTimer);
CPUTimer_setEmulationMode(cpuTimer,
CPUTIMER_EMULATIONMODE_STOPAFTERNEXTDECREMENT);
CPUTimer_enableInterrupt(cpuTimer);
}
//
// cpuTimer0ISR - CPU Timer0 ISR
//
__interrupt void cpuTimer0ISR(void)
{
GPIO_togglePin(DEVICE_GPIO_PIN_LED1);
Interrupt_clearACKGroup(INTERRUPT_ACK_GROUP1);
}
//
// writeDataCPU2 - Read data from cpu2RArray written by CPU01 and modify and
// write into cpu2RWArray. cpu2RArray[0] is used to hold the
// multiplier value.
//
void writeDataCPU2(void)
{
uint16_t index;
uint16_t multiplier;
multiplier = cpu2RArray[0];
cpu2RWArray[0] = multiplier;
for(index = 1; index < 256; index ++)
{
cpu2RWArray[index] = multiplier * cpu2RArray[index];
}
}
//
// End of File
//
| 27.536 | 79 | 0.662696 | [
"vector"
] |
58adab374e41a6f15432236e18b271dc8d547096 | 8,422 | c | C | jsrc/am1.c | jsoftware/j-playground | fec7be5a9dc92d45c7326556b6058e63fb4f979a | [
"MIT"
] | 4 | 2022-01-19T04:23:49.000Z | 2022-03-28T18:55:38.000Z | jsrc/am1.c | jsoftware/j-playground | fec7be5a9dc92d45c7326556b6058e63fb4f979a | [
"MIT"
] | 15 | 2022-02-28T13:09:29.000Z | 2022-03-11T01:15:39.000Z | jsrc/am1.c | jsoftware/j-playground | fec7be5a9dc92d45c7326556b6058e63fb4f979a | [
"MIT"
] | 2 | 2022-01-29T13:26:27.000Z | 2022-02-23T02:43:31.000Z | /* Copyright 1990-2006, Jsoftware Inc. All rights reserved. */
/* Licensed use only. Any other use is in violation of copyright. */
/* */
/* Adverbs: a ind}z for sparse z & ind is box a0;a1;a2;... or integer */
/* am1e a is the sparse element */
/* am1a a is an arbitrary dense array */
/* am1sp a an arbitrary sparse array */
#include "j.h"
static A jtistd1(J jt,A z,A ind){A*iv,j,*jv,x;I d,i,n,r,*s;
RZ(z&&ind);
ASSERT(1>=AR(ind),EVRANK);
if(AN(ind)&&!(BOX&AT(ind))){ASSERT(NUMERIC&AT(ind),EVINDEX); RZ(ind=every(ind,ds(CRIGHT)));}
s=AS(z); n=AN(ind); iv=AAV(ind);
ASSERT(n<=AR(z),EVINDEX);
DQ(n, x=iv[i]; if(!equ(x,ds(CACE)))break;--n;);
GATV0(j,BOX,n,1); jv=AAV(j);
for(i=0;i<n;++i){
x=iv[i]; d=s[i];
if(BOX&AT(x)){
ASSERT(!AR(x),EVINDEX);
x=AAV(x)[0]; r=AR(x);
RZ(jv[i]=!AN(x)&&1==r?ds(CACE):less(IX(d),pind(d,x)));
}else {RZ(x=pind(d,x)); jv[i]=x;} // INCORP not needed probably, since this use is transient
}
R j;
} /* convert index list ind into standard form */
static A jtastd1(J jt,A a,A z,A ind){A*iv,q,r,s,s1,*sv,x;B b;I ar,*as,d,j,m,n,*rv,zr,*zs;P*zp; I*s1v;
ar=AR(a); as=AS(a);
zr=AR(z); zs=AS(z); zp=PAV(z);
if(!ar)R a;
n=AN(ind); iv=AAV(ind);
GATV0(r,INT,zr,1); rv= AV(r);
GATV0(s,BOX,zr,1); sv=AAV(s);
m=0; j=n;
DO(n, x=iv[i]; b=x==ds(CACE); m+=rv[i]=b?1:AR(x); RZ(sv[i]=b?sc(zs[i]):shape(x)););
DQ(zr-n, rv[j]=1; RZ(sv[j]=sc(zs[j])); ++j;);
d=m+zr-n; ASSERT(ar<=d,EVRANK);
RZ(s1=raze(s)); s1v=AV(s1);
ASSERT(!ICMP(as,AV(s1)+d-ar,ar),EVLENGTH);
if(ar<d)RZ(a=reshape(s1,a));
RZ(q=dgrade1(eps(repeat(r,IX(zr)),SPA(zp,a))));
R equ(q,IX(d))?a:cant2(q,a);
} /* convert replacement array a into standard form relative to index list ind */
static A jtssel(J jt,A z,A ind){A a,*iv,p,q,x,y;B*b;I*av,c,i,j,m,n,*u,*v,*yv;P*zp;
zp=PAV(z);
y=SPA(zp,i); v=AS(y); m=v[0]; c=v[1]; yv=AV(y);
a=SPA(zp,a); n=AN(a); av=AV(a);
GATV0(p,B01,m,1); b=BAV(p); mvc(m,b,1,MEMSET01);
GATV0(q,INT,m,1); v=AV(q); iv=AAV(ind);
for(i=0;i<n;++i){
j=av[i]; if(j>=AN(ind))break;
x=iv[j];
if(x!=ds(CACE)){
u=yv+i; DO(m, v[i]=b[i]?*u:-1; u+=c;);
RZ(p=eps(q,1<AR(x)?ravel(x):x)); b=BAV(p);
}}
R p;
} /* which rows of the index matrix of z are selected by index list ind? */
static B jtipart(J jt,A z,A ind,A*i1,A*i2){A*iv,p,*pv,q,*qv,x;B*b;I c,d,n;P*zp;
n=AN(ind); iv=AAV(ind); zp=PAV(z);
RZ(b=bfi(AR(z),SPA(zp,a),1));
c=0; DO(n, if(b[i])++c;); d=n-c;
GATV0(p,BOX,c,1); pv=AAV(p); *i1=p;
GATV0(q,BOX,d,1); qv=AAV(q); *i2=q;
DO(n, x=iv[i]; if(b[i])*pv++=x; else *qv++=x;);
R 1;
} /* partition index into sparse and dense parts */
static A jtdcube(J jt,A z,A i2){A*iv,x,y;I i,m,n,*s;P*zp;D rkblk[16];
n=AN(i2); iv=AAV(i2);
zp=PAV(z); x=SPA(zp,x); s=1+AS(x);
m=1; y=iv[n-1]; if(y==ds(CACE))RZ(y=IX(s[n-1]));
for(i=n-2;0<=i;--i){
m*=s[1+i]; x=iv[i];
A t; RZ(t=tymes(sc(m),x==ds(CACE)?IX(s[i]):x));
RZ(y=ATOMIC2(jt,t,y,rkblk,0L, RMAX,CPLUS));
}
R y;
} /* index cube relative to dense axes */
static A jtscuba(J jt,A z,A i1,B u){A*iv,q=0,x;I c,d,j,n,*s,*v;P*zp;
n=AN(i1);
if(!n)R mtm;
iv=AAV(i1); s=AS(z); zp=PAV(z); x=SPA(zp,a); v=AV(x);
for(j=n-1;0<=j;--j){
x=iv[j];
if(x==ds(CACE))RZ(x=IX(s[v[j]]))else{if(1<AR(x))RZ(x=ravel(x)); if(u)RZ(x=nub(x));}
c=AN(x);
if(q){d=AS(q)[0]; RZ(q=stitch(repeat(sc(d),x),reitem(sc(c*d),q)));}
else RZ(q=reshape(v2(c,1L),x));
}
R q;
} /* index cube relative to sparse axes; 1=u iff unique (remove duplicates) */
static A jtscubb(J jt,A z,A i1){A a,q,x,y;I c,d,h,j,*s,*v,*xv;P*zp;
RZ(q=scuba(z,i1,1));
if(!AS(q)[0])R mtm;
s=AS(z); zp=PAV(z); y=SPA(zp,i); a=SPA(zp,a); v=AV(a);
c=AS(q)[1]; d=AS(y)[1]; h=d-c;
if(c==d)R less(q,y);
RZ(q=less(q,taker(c,y)));
GATV0(x,INT,h,1); xv=AV(x); j=c; DO(h, xv[i]=s[v[j++]];);
RZ(x=odom(2L,h,xv));
c=AS(q)[0]; d=AS(x)[0];
R stitch(repeat(sc(d),q),reitem(sc(c*d),x));
} /* new rows for the index matrix of z for brand new cells */
static A jtscubc(J jt,A z,A i1,A p){A a,q,s,y,y1;B*qv;I c,d,h,j=-1,m,n,*sv,*u,*v;P*zp;
zp=PAV(z); a=SPA(zp,a); n=AN(i1); h=AN(a)-n;
if(!h)R mtm;
GATV0(s,INT,h,1); sv=AV(s);
d=1; u=AS(z); v=AV(a); DO(h, d*=sv[i]=u[v[n+i]];);
RZ(y=repeat(p,SPA(zp,i))); m=AS(y)[0];
RZ(y1=take(v2(m,n),y)); v=AV(y1);
GATV0(q,B01,m,1); qv=BAV(q);
if(m){mvc(m,qv,1,MEMSET00); DO(m-1, if(ICMP(v,v+n,n)){if(d>i-j)qv[i]=1; j=i;} v+=n;); if(d>(m-1)-j)qv[m-1]=1;}
RZ(y1=repeat(q,y1)); c=AS(y1)[0];
if(!c)R mtm;
R less(stitch(repeat(sc(d),y1),reitem(sc(c*d),odom(2L,h,sv))),y);
} /* new rows for the index matrix of z for existing cells */
static A jtscube(J jt,A z,A i1,A p){A a,y;P*zp;
zp=PAV(z); a=SPA(zp,a); y=SPA(zp,i);
R !AN(a)&&!AS(y)[0]?take(num(1),mtm):over(scubb(z,i1),scubc(z,i1,p));
} /* new rows for the index matrix of z */
static A jtiindx(J jt,A z,A i1){A q,j,j1,y;I c,d,e,h,i,*jv,m,n,*qv,*v,*yv;P*zp;
c=AN(i1); zp=PAV(z); y=SPA(zp,i);
if(c==AS(y)[1])R indexof(y,scuba(z,i1,0));
/* when y has excess columns, do progressive indexing */
RZ(y=taker(c,y));
RZ(j=indexof(y,scuba(z,i1,0))); /* j: group indices */
n= AN(j); jv=AV(j);
m=AS(y)[0]; yv=AV(y);
GATV0(q,INT,n,1); qv=AV(q); /* q: # members in each group */
for(i=h=0;i<n;++i){
e=1; d=jv[i]; v=yv+c*d;
DQ(m-d-1, if(ICMP(v,v+c,c))break; ++e; v+=c;);
qv[i]=e; h+=e;
}
GATV0(j1,INT,h,1); v=AV(j1);
DO(n, e=qv[i]; d=jv[i]; DQ(e, *v++=d++;););
R j1;
} /* index of index list in the index matrix of z */
static A jtzpad1(J jt,A z,A t,B ip){A q,s,x,x0,y,y0;I m;P*zp;
RZ(z&&t);
if(m=AS(t)[0]){ /* new cells being added */
zp=PAV(z);
y0=SPA(zp,i); RZ(y=over(y0,t)); RZ(q=grade1(y)); RZ(y=from(q,y));
x0=SPA(zp,x); RZ(s=shape(x0)); *AV(s)=m; RZ(x=from(q,over(x0,reshape(s,SPA(zp,e)))));
// if z is assigned to a name, the use counts need to be adjusted: the old ones need to be decremented
// to remove the assignment, and the new ones need to be incremented to prevent them from being freed
// until the name is freed. We detect the case from jt->asginfo.assignsym being set to the address of z
// (if the block could not be inplaced, z will have been changed)
if(jt->asginfo.assignsym&&jt->asginfo.assignsym->val==z){RZ(ras(y)); RZ(ras(x)); fa(y0); fa(x0);}
SPB(zp,i,y); SPB(zp,x,x);
}
R z;
} /* pad z with new rows t for its index matrix */
static B mtind(A ind){A*iv,x;
iv=AAV(ind);
DO(AN(ind), x=iv[i]; if(!AN(x))R 1;);
R 0;
} /* 1 iff standardized index ind is an empty selection */
A jtam1e(J jt,A a,A z,A ind,B ip){A e,i1,i2,p,x,y;B*pv;C*u,*v;I*iv,k,m,n,r,*s,vk,xk;P*zp;
RZ(a&&(ind=istd1(z,ind)));
r=AR(z); zp=PAV(z); x=SPA(zp,x); y=SPA(zp,i); e=SPA(zp,e);
RZ(p=ssel(z,ind)); pv=BAV(p);
RZ(ipart(z,ind,&i1,&i2));
m=AN(p); n=AN(i2); u=CAV(e); v=CAV(x);
r=AR(x); s=AS(x); k=bpnoun(AT(x)); xk=k*prod(r-(n+1),s+(n+1)); vk=k*prod(r-1,s+1);
if(!n)DO(m, if(pv[i])mvc(xk,v,k,u); v+=vk;)
else{
RZ(i2=dcube(z,i2)); iv=AV(i2); n=AN(i2);
DO(m, if(pv[i])DO(n, mvc(xk,v+iv[i]*xk,k,u);); v+=vk;);
}
R z;
} /* a (<ind)}z; sparse z; ind is index list; sparse element a replacement */
A jtam1a(J jt,A a,A z,A ind,B ip){A a0=a,a1,e,i1,i2,t,x,y;C*u,*v,*xv;I ar,c,*iv,*jv,k,m,n,r,*s,uk,vk,xk;P*zp;
RZ(a&&(ind=istd1(z,ind)));
RZ(a=astd1(a,z,ind));
if(mtind(ind))R z;
RZ(ipart(z,ind,&i1,&i2));
RZ(z=zpad1(z,scube(z,i1,ssel(z,ind)),ip));
zp=PAV(z); x=SPA(zp,x); y=SPA(zp,i); e=SPA(zp,e);
ar=AR(a); n=AN(i2); r=AR(x); s=AS(x);
k=bpnoun(AT(x)); xk=k*prod(r-1-n,s+1+n); vk=k*prod(r-1,s+1); uk=!ar?k:n?xk:vk;
u=CAV(a); xv=v=CAV(x);
RZ(t=iindx(z,i1)); iv=AV(t); m=AN(t);
if(!n&&!m){a1=SPA(zp,a); R ar?sparseit(a0,a1,e):sparseit(reshape(shape(z),a),a1,a);}
if(n){RZ(t=dcube(z,i2)); jv=AV(t); c=AN(t); v=xv-vk;}
if(!n) DO(m, mvc(vk,v+vk*iv[i],uk,u); if(ar)u+=uk; )
else if(m)DO(m, v=xv+vk*iv[i]; DO(c, mvc(xk,v+xk*jv[i],uk,u); if(ar)u+=uk;);)
else DO(AS(x)[0], v+=vk; DO(c, mvc(xk,v+xk*jv[i],uk,u); if(ar)u+=uk;););
R z;
} /* a (<ind)}z; sparse z; ind is index list; arbitrary dense array a replacement */
A jtam1sp(J jt,A a,A z,A ind,B ip){R amnsp(a,z,ope(catalog(istd1(z,ind))),ip);}
/* a (<ind)}z; sparse z; ind is index list; arbitrary sparse array a replacement */
| 39.914692 | 111 | 0.542389 | [
"shape"
] |
58bbd9a83e2e1b95fe5541c1545283cac8363fde | 476 | h | C | Solution/PhoenixEngine/Source/Utility/Misc/StaticObject.h | rohunb/PhoenixEngine | 4d21f9000c2e0c553c398785e8cebff1bc190a8c | [
"MIT"
] | 2 | 2017-11-09T20:05:36.000Z | 2018-07-05T00:55:01.000Z | Solution/PhoenixEngine/Source/Utility/Misc/StaticObject.h | rohunb/PhoenixEngine | 4d21f9000c2e0c553c398785e8cebff1bc190a8c | [
"MIT"
] | null | null | null | Solution/PhoenixEngine/Source/Utility/Misc/StaticObject.h | rohunb/PhoenixEngine | 4d21f9000c2e0c553c398785e8cebff1bc190a8c | [
"MIT"
] | null | null | null | #ifndef PHOENIX_STATIC_OBJECT_H
#define PHOENIX_STATIC_OBJECT_H
/*! \brief Adds a static instance of the class that can be retrieved.
*
* @desc This can be used in the form of Class::GetStaticObject().
* @warning This is a single object that can be accessed from any thread.
*/
#define F_AddStaticObjectToClass(Type) \
public: \
static Type& GetStaticObject() \
{ \
static Type StaticObject_; \
return StaticObject_; \
} \
private:
#endif
| 25.052632 | 72 | 0.69958 | [
"object"
] |
58c37198ee2b67bfedf1eab0d40fa330ffbe8d28 | 14,346 | h | C | sgf/3.0/headers/Gamecore/sprite/DrawRle.h | rasputtim/SGPacMan | b0fd33f0951a42625a391383b4d1bd378391493c | [
"BSD-2-Clause"
] | null | null | null | sgf/3.0/headers/Gamecore/sprite/DrawRle.h | rasputtim/SGPacMan | b0fd33f0951a42625a391383b4d1bd378391493c | [
"BSD-2-Clause"
] | null | null | null | sgf/3.0/headers/Gamecore/sprite/DrawRle.h | rasputtim/SGPacMan | b0fd33f0951a42625a391383b4d1bd378391493c | [
"BSD-2-Clause"
] | null | null | null | // At this point the following methods should be defined:
// METHODNAME: The name of the drawing method
// METHODNAME_FLIPT: The name of the flipped drawing method
// PIXEL_PTR: type of pointer to the target surface pixels
// PUT_PIXEL(p,c): Draw pixel of color c to pixel ptr type p
// PITCH: This added to PIXEL_PTR type will result in the next scanline
void METHODNAME_FLIP(SDL_Surface* dst, RLE_SPRITE* src, int dx, int dy )
{
#define RLE_PTR signed char*
#define RLE_IS_EOL(c) ((c) == 0)
//#define PIXEL_PTR unsigned char*
#define OFFSET_PIXEL_PTR(p,x) ((PIXEL_PTR) (p) + (x))
#define INC_PIXEL_PTR(p) ((p)++)
#define DEC_PIXEL_PTR(p) ((p)--)
//#define PUT_PIXEL(p,c) (*((unsigned char *)(p)) = (c))
int x, y, w, h; // width and height of visible area
int dxbeg, dybeg; // beginning in destination
int sxbeg, sybeg; // beginning in source
RLE_PTR s;
// Clip to dst->clip_rect
int dst_cl = dst->clip_rect.x;
int dst_cr = dst->clip_rect.w + dst_cl - 1;
int dst_ct = dst->clip_rect.y;
int dst_cb = dst->clip_rect.h + dst_ct;
// if (dst->clip)
if (1)
{
int tmp;
dxbeg = dx;
if ( dst_cl > dx ) dxbeg = dst_cl;
tmp = dx + src->w - dst_cr;
sxbeg = ((tmp < 0) ? 0 : tmp);
tmp = dx + src->w;
if (tmp > dst_cr ) tmp = dst_cr;
w = tmp - dxbeg;
if (w <= 0)
return;
tmp = dst_ct - dy;
sybeg = ((tmp < 0) ? 0 : tmp);
dybeg = sybeg + dy;
tmp = dst_cb - dy;
h = ((tmp > src->h) ? src->h : tmp) - sybeg;
if (h <= 0)
return;
}
else {
w = src->w;
h = src->h;
sxbeg = 0;
sybeg = 0;
dxbeg = dx;
dybeg = dy;
}
s = (RLE_PTR) (src->dat);
dxbeg += w;
// Clip top.
for (y = sybeg - 1; y >= 0; y--)
{
long c = *s++;
while (!RLE_IS_EOL(c))
{
if (c > 0)
s += c;
c = *s++;
}
}
//@@@ bmp_select(dst);
/* Visible part. */
for (y = 0; y < h; y++)
{
//@@@ PIXEL_PTR d = OFFSET_PIXEL_PTR(bmp_write_line(dst, dybeg + y), dxbeg);
PIXEL_PTR d = (PIXEL_PTR) dst->pixels;
d += (dybeg+y)*PITCH; // 24bpp ->(y * dst->pitch)
if (dst->format->BitsPerPixel != 24)
d = OFFSET_PIXEL_PTR( d, dxbeg );
else {
//d = OFFSET_PIXEL_PTR( d, (x * sizeof(Uint8) * 3));
d += (dybeg+y * dst->pitch) + (dxbeg * sizeof(Uint8) * 3);
}
long c = *s++;
// Clip left.
for (x = sxbeg; x > 0; )
{
if (RLE_IS_EOL(c))
goto next_line;
else if (c > 0)
{
// Run of solid pixels.
if ((x - c) >= 0)
{
// Fully clipped.
x -= c;
s += c;
}
else
{
// Visible on the right.
c -= x;
s += x;
break;
}
}
else
{
// Run of transparent pixels.
if ((x + c) >= 0) {
// Fully clipped.
x += c;
}
else {
// Visible on the right.
c += x;
break;
}
}
c = *s++;
}
/* Visible part. */
for (x = w; x > 0; )
{
if (RLE_IS_EOL(c))
goto next_line;
else if (c > 0)
{
/* Run of solid pixels. */
if ((x - c) >= 0)
{
/* Fully visible. */
x -= c;
for (c--; c >= 0; s++, DEC_PIXEL_PTR(d), c--)
{
unsigned long col = *s;
PUT_PIXEL(d, col);
}
}
else
{
/* Clipped on the right. */
c -= x;
for (x--; x >= 0; s++, DEC_PIXEL_PTR(d), x--)
{
unsigned long col = *s;
PUT_PIXEL(d, col);
}
break;
}
}
else
{
/* Run of transparent pixels. */
x += c;
d = OFFSET_PIXEL_PTR(d, c);
}
c = *s++;
}
/* Clip right. */
while (!RLE_IS_EOL(c))
{
if (c > 0)
s += c;
c = *s++;
}
next_line: ;
}
//@@@bmp_unwrite_line(dst);
}
void METHODNAME( SDL_Surface* dst , RLE_SPRITE* src, int dx, int dy )
{
#define RLE_PTR signed char*
#define RLE_IS_EOL(c) ((c) == 0)
//#define PIXEL_PTR unsigned char*
#define OFFSET_PIXEL_PTR(p,x) ((PIXEL_PTR) (p) + (x))
#define INC_PIXEL_PTR(p) ((p)++)
#define DEC_PIXEL_PTR(p) ((p)--)
//#define PUT_PIXEL(p,c) (*((unsigned char *)(p)) = (c))
//#define PUT_PIXEL(p,c) bmp_write8((unsigned long) (p), (c))
int x, y, w, h; // width and height of visible area
int dxbeg, dybeg; // beginning in destination
int sxbeg, sybeg; // beginning in source
RLE_PTR s;
//SDL_Surface* dst = gamescreen;
// Clip to dst->clip_rect
int dst_cl = dst->clip_rect.x;
int dst_cr = dst->clip_rect.w + dst_cl;
int dst_ct = dst->clip_rect.y;
int dst_cb = dst->clip_rect.h + dst_ct;
// if (dst->clip)
if (1)
{
int tmp;
tmp = dst_cl - dx;
sxbeg = ((tmp < 0) ? 0 : tmp);
dxbeg = sxbeg + dx;
tmp = dst_cr - dx;
w = ((tmp > src->w) ? src->w : tmp) - sxbeg;
if ( w<=0 ) return;
tmp = dst_ct - dy;
sybeg = ((tmp < 0) ? 0 : tmp);
dybeg = sybeg + dy;
tmp = dst_cb - dy;
h = ((tmp > src->h) ? src->h : tmp) - sybeg;
if ( h<=0 ) return;
}
else
{
w = src->w;
h = src->h;
sxbeg = 0;
sybeg = 0;
dxbeg = dx;
dybeg = dy;
}
s = (RLE_PTR) (src->dat);
/* Clip top. */
for (y = sybeg - 1; y >= 0; y--)
{
long c = *s++;
while (!RLE_IS_EOL(c))
{
if (c > 0)
s += c;
c = *s++;
}
}
//@@@ bmp_select(dst);
/* Visible part. */
for (y = 0; y < h; y++)
{
//@@@ PIXEL_PTR d = OFFSET_PIXEL_PTR(bmp_write_line(dst, dybeg + y), dxbeg);
PIXEL_PTR d = (PIXEL_PTR) dst->pixels;
d += (dybeg+y)*PITCH;
d = OFFSET_PIXEL_PTR( d, dxbeg );
long c = *s++;
/* Clip left. */
for (x = sxbeg; x > 0; ) {
if (RLE_IS_EOL(c))
goto next_line;
else if (c > 0) {
/* Run of solid pixels. */
if ((x - c) >= 0) {
/* Fully clipped. */
x -= c;
s += c;
}
else {
/* Visible on the right. */
c -= x;
s += x;
break;
}
}
else {
/* Run of transparent pixels. */
if ((x + c) >= 0) {
/* Fully clipped. */
x += c;
}
else {
/* Visible on the right. */
c += x;
break;
}
}
c = *s++;
}
/* Visible part. */
for (x = w; x > 0; ) {
if (RLE_IS_EOL(c))
goto next_line;
else if (c > 0) {
/* Run of solid pixels. */
if ((x - c) >= 0) {
/* Fully visible. */
x -= c;
for (c--; c >= 0; s++, INC_PIXEL_PTR(d), c--) {
unsigned long col = (unsigned char) (*s);
PUT_PIXEL(d, col);
}
}
else {
/* Clipped on the right. */
c -= x;
for (x--; x >= 0; s++, INC_PIXEL_PTR(d), x--) {
unsigned long col = *s;
PUT_PIXEL(d, col);
}
break;
}
}
else {
/* Run of transparent pixels. */
x += c;
d = OFFSET_PIXEL_PTR(d, -c);
}
c = *s++;
}
/* Clip right. */
while (!RLE_IS_EOL(c)) {
if (c > 0)
s += c;
c = *s++;
}
next_line: ;
}
//@@@bmp_unwrite_line(dst);
}
//========24 bpp methods==================
#if 0
static inline Uint8* computeOffset(SDL_Surface * surface, int x, int y){
int bpp = surface->format->BytesPerPixel;
return ((Uint8*)surface->pixels) + (y * surface->pitch) + x * bpp;
}
void draw_rle_sprite_v_flip24(SDL_Surface* dst, RLE_SPRITE* src, int dx, int dy )
{
#define RLE_PTR signed char*
#define RLE_IS_EOL(c) ((c) == 0)
//#define PIXEL_PTR unsigned char*
#define OFFSET_PIXEL_PTR(p,x) ((PIXEL_PTR) (p) + (x))
#define INC_PIXEL_PTR(p) ((p)++)
#define DEC_PIXEL_PTR(p) ((p)--)
//#define PUT_PIXEL(p,c) (*((unsigned char *)(p)) = (c))
int x, y, w, h; // width and height of visible area
int dxbeg, dybeg; // beginning in destination
int sxbeg, sybeg; // beginning in source
RLE_PTR s;
// Clip to dst->clip_rect
int dst_cl = dst->clip_rect.x;
int dst_cr = dst->clip_rect.w + dst_cl - 1;
int dst_ct = dst->clip_rect.y;
int dst_cb = dst->clip_rect.h + dst_ct;
// if (dst->clip)
if (1)
{
int tmp;
dxbeg = dx;
if ( dst_cl > dx ) dxbeg = dst_cl;
tmp = dx + src->w - dst_cr;
sxbeg = ((tmp < 0) ? 0 : tmp);
tmp = dx + src->w;
if (tmp > dst_cr ) tmp = dst_cr;
w = tmp - dxbeg;
if (w <= 0)
return;
tmp = dst_ct - dy;
sybeg = ((tmp < 0) ? 0 : tmp);
dybeg = sybeg + dy;
tmp = dst_cb - dy;
h = ((tmp > src->h) ? src->h : tmp) - sybeg;
if (h <= 0)
return;
}
else {
w = src->w;
h = src->h;
sxbeg = 0;
sybeg = 0;
dxbeg = dx;
dybeg = dy;
}
s = (RLE_PTR) (src->dat);
dxbeg += w;
// Clip top.
for (y = sybeg - 1; y >= 0; y--)
{
long c = *s++;
while (!RLE_IS_EOL(c))
{
if (c > 0)
s += c;
c = *s++;
}
}
//@@@ bmp_select(dst);
/* Visible part. */
for (y = 0; y < h; y++)
{
//@@@ PIXEL_PTR d = OFFSET_PIXEL_PTR(bmp_write_line(dst, dybeg + y), dxbeg);
PIXEL_PTR d = (PIXEL_PTR) dst->pixels;
d += (dybeg+y)*PITCH; // 24bpp ->(y * dst->pitch)
if (dst->format->BitsPerPixel != 24)
d = OFFSET_PIXEL_PTR( d, dxbeg );
else {
//d = OFFSET_PIXEL_PTR( d, (x * sizeof(Uint8) * 3));
d += (dybeg+y * dst->pitch) + (dxbeg * sizeof(Uint8) * 3);
}
long c = *s++;
// Clip left.
for (x = sxbeg; x > 0; )
{
if (RLE_IS_EOL(c))
goto next_line;
else if (c > 0)
{
// Run of solid pixels.
if ((x - c) >= 0)
{
// Fully clipped.
x -= c;
s += c;
}
else
{
// Visible on the right.
c -= x;
s += x;
break;
}
}
else
{
// Run of transparent pixels.
if ((x + c) >= 0) {
// Fully clipped.
x += c;
}
else {
// Visible on the right.
c += x;
break;
}
}
c = *s++;
}
/* Visible part. */
for (x = w; x > 0; )
{
if (RLE_IS_EOL(c))
goto next_line;
else if (c > 0)
{
/* Run of solid pixels. */
if ((x - c) >= 0)
{
/* Fully visible. */
x -= c;
for (c--; c >= 0; s++, DEC_PIXEL_PTR(d), c--)
{
unsigned long col = *s;
PUT_PIXEL(d, col);
}
}
else
{
/* Clipped on the right. */
c -= x;
for (x--; x >= 0; s++, DEC_PIXEL_PTR(d), x--)
{
unsigned long col = *s;
PUT_PIXEL(d, col);
}
break;
}
}
else
{
/* Run of transparent pixels. */
x += c;
d = OFFSET_PIXEL_PTR(d, c);
}
c = *s++;
}
/* Clip right. */
while (!RLE_IS_EOL(c))
{
if (c > 0)
s += c;
c = *s++;
}
next_line: ;
}
//@@@bmp_unwrite_line(dst);
}
void draw_rle_sprite24( SDL_Surface* dst , RLE_SPRITE* src, int dx, int dy )
{
#define RLE_PTR signed char*
#define RLE_IS_EOL(c) ((c) == 0)
//#define PIXEL_PTR unsigned char*
#define OFFSET_PIXEL_PTR(p,x) ((PIXEL_PTR) (p) + (x))
#define INC_PIXEL_PTR(p) ((p)++)
#define DEC_PIXEL_PTR(p) ((p)--)
//#define PUT_PIXEL(p,c) (*((unsigned char *)(p)) = (c))
//#define PUT_PIXEL(p,c) bmp_write8((unsigned long) (p), (c))
int x, y, w, h; // width and height of visible area
int dxbeg, dybeg; // beginning in destination
int sxbeg, sybeg; // beginning in source
RLE_PTR s;
//SDL_Surface* dst = gamescreen;
// Clip to dst->clip_rect
int dst_cl = dst->clip_rect.x;
int dst_cr = dst->clip_rect.w + dst_cl;
int dst_ct = dst->clip_rect.y;
int dst_cb = dst->clip_rect.h + dst_ct;
// if (dst->clip)
if (1)
{
int tmp;
tmp = dst_cl - dx;
sxbeg = ((tmp < 0) ? 0 : tmp);
dxbeg = sxbeg + dx;
tmp = dst_cr - dx;
w = ((tmp > src->w) ? src->w : tmp) - sxbeg;
if ( w<=0 ) return;
tmp = dst_ct - dy;
sybeg = ((tmp < 0) ? 0 : tmp);
dybeg = sybeg + dy;
tmp = dst_cb - dy;
h = ((tmp > src->h) ? src->h : tmp) - sybeg;
if ( h<=0 ) return;
}
else
{
w = src->w;
h = src->h;
sxbeg = 0;
sybeg = 0;
dxbeg = dx;
dybeg = dy;
}
s = (RLE_PTR) (src->dat);
/* Clip top. */
for (y = sybeg - 1; y >= 0; y--)
{
long c = *s++;
while (!RLE_IS_EOL(c))
{
if (c > 0)
s += c;
c = *s++;
}
}
//@@@ bmp_select(dst);
#if 0
/* Visible part. */
for (y = 0; y < h; y++)
{
//@@@ PIXEL_PTR d = OFFSET_PIXEL_PTR(bmp_write_line(dst, dybeg + y), dxbeg);
PIXEL_PTR d = (PIXEL_PTR) dst->pixels;
d += (dybeg+y)*PITCH;
d = OFFSET_PIXEL_PTR( d, dxbeg );
long c = *s++;
/* Clip left. */
for (x = sxbeg; x > 0; ) {
if (RLE_IS_EOL(c))
goto next_line;
else if (c > 0) {
/* Run of solid pixels. */
if ((x - c) >= 0) {
/* Fully clipped. */
x -= c;
s += c;
}
else {
/* Visible on the right. */
c -= x;
s += x;
break;
}
}
else {
/* Run of transparent pixels. */
if ((x + c) >= 0) {
/* Fully clipped. */
x += c;
}
else {
/* Visible on the right. */
c += x;
break;
}
}
c = *s++;
}
/* Visible part. */
for (x = w; x > 0; ) {
if (RLE_IS_EOL(c))
goto next_line;
else if (c > 0) {
/* Run of solid pixels. */
if ((x - c) >= 0) {
/* Fully visible. */
x -= c;
for (c--; c >= 0; s++, INC_PIXEL_PTR(d), c--) {
unsigned long col = (unsigned char) (*s);
PUT_PIXEL(d, col);
}
}
else {
/* Clipped on the right. */
c -= x;
for (x--; x >= 0; s++, INC_PIXEL_PTR(d), x--) {
unsigned long col = *s;
PUT_PIXEL(d, col);
}
break;
}
}
else {
/* Run of transparent pixels. */
x += c;
d = OFFSET_PIXEL_PTR(d, -c);
}
c = *s++;
}
/* Clip right. */
while (!RLE_IS_EOL(c)) {
if (c > 0)
s += c;
c = *s++;
}
next_line: ;
}
#endif
//@@@bmp_unwrite_line(dst);
{
int x_dir = 1;
int y_dir = 1;
//unsigned int mask = maskColor;
int bpp = src->format->BytesPerPixel;
for (y = 0; y < h; y++) {
//Uint8 * sourceLine = computeOffset(src, sxbeg, sybeg + y);
Uint8 * destLine = computeOffset(dst, dxbeg, dybeg + y * y_dir);
for (x = w - 1; x >= 0; sourceLine += bpp, destLine += bpp * x_dir, x--) {
unsigned long sourcePixel = *(Uint32*) sourceLine;
// if (!(sourcePixel == mask)){
// unsigned int destPixel = *(Uint32*) destLine;
// sourcePixel = globalBlend.currentBlender(destPixel, sourcePixel, globalBlend.alpha);
// if (filter != NULL){
// *(Uint32 *)destLine = filter->filter(sourcePixel);
//} else {
*(Uint32 *)destLine = sourcePixel;
//}
//}
}
}
}
}
#endif | 19.706044 | 115 | 0.484944 | [
"solid"
] |
58e419a6308d819aeb161a162b8327d6052da0ec | 7,892 | h | C | include/pr/app/skybox.h | psryland/rylogic_code | f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b | [
"CNRI-Python"
] | 2 | 2020-11-11T16:19:04.000Z | 2021-01-19T01:53:29.000Z | include/pr/app/skybox.h | psryland/rylogic_code | f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b | [
"CNRI-Python"
] | 1 | 2020-07-27T09:00:21.000Z | 2020-07-27T10:58:10.000Z | include/pr/app/skybox.h | psryland/rylogic_code | f79e471fe0d6714c5e0cf8385ddc2a88ab2e082b | [
"CNRI-Python"
] | 1 | 2021-04-04T01:39:55.000Z | 2021-04-04T01:39:55.000Z | //*****************************************************************************************
// Application Framework
// Copyright (c) Rylogic Ltd 2012
//*****************************************************************************************
#pragma once
#include "pr/app/forward.h"
namespace pr::app
{
// A base class for a sky box
struct Skybox
{
// Sky box styles - implies texture organisation as well
enum class EStyle
{
// This is a geosphere with inward facing normals
Geosphere,
// This is a cubic dome, the texture should be a '+' shape with
// the top portion from 0.25->0.75, and sides from 0->0.25, 0.75->1.0
FiveSidedCube,
// The is a full 6-sided cube, 'texpath' should be a filepath with
// the format 'path\filename??.extn' where '??' will be replaced by
// +X,-X,+Y,-Y,+Z,-Z to generate the six texture filepaths
SixSidedCube,
};
// A renderer instance type for the sky box
#define PR_RDR_INST(x)\
x(m4x4 ,m_i2w ,rdr::EInstComp::I2WTransform )\
x(rdr::ModelPtr ,m_model ,rdr::EInstComp::ModelPtr )\
x(rdr::SKOverride ,m_sko ,rdr::EInstComp::SortkeyOverride)
PR_RDR_DEFINE_INSTANCE(Instance, PR_RDR_INST);
#undef PR_RDR_INST
using TexCont = pr::vector<rdr::Texture2DPtr>;
Instance m_inst; // The sky box instance
TexCont m_tex; // The textures used in the sky box
float m_scale; // Model scaler
m4x4 m_i2w; // The base orientation transform for the sky box (updated with camera position in OnEvent)
// Constructs a sky box model and instance.
// 'texpath' should be an unrolled cube texture
Skybox(Renderer& rdr, std::filesystem::path const& texpath, EStyle tex_style, float scale = 100.0f)
:m_inst()
,m_tex()
,m_scale(scale)
,m_i2w(m4x4::Scale(scale, pr::v4Origin))
{
switch (tex_style)
{
default: PR_ASSERT(PR_DBG, false, "Unsupported texture style");
case EStyle::Geosphere: InitGeosphere(rdr, texpath); break;
case EStyle::FiveSidedCube: InitFiveSidedCube(rdr, texpath); break;
case EStyle::SixSidedCube: InitSixSidedCube(rdr, texpath); break;
}
// Set the sort key so that the sky box draws last
m_inst.m_sko.Group(pr::rdr::ESortGroup::Skybox);
m_inst.m_model->m_name = "sky box";
}
// Add the sky box to a viewport
void AddToScene(rdr::Scene& scene)
{
auto& view = scene.m_view;
m_inst.m_i2w = m_i2w;
m_inst.m_i2w.pos = view.m_c2w.pos;
scene.AddInstance(m_inst);
}
private:
// Create a model for a geosphere sky box
void InitGeosphere(Renderer& rdr, std::filesystem::path const& texpath)
{
using namespace pr::rdr;
// Model nugget properties for the sky box
NuggetProps ddata;
ddata.m_tex_diffuse = rdr.m_tex_mgr.CreateTexture2D(AutoId, texpath.c_str(), SamplerDesc::LinearWrap(), false, "skybox");
ddata.m_geom = EGeom::Vert | EGeom::Tex0;
ddata.m_rsb = RSBlock::SolidCullFront();
// Create the sky box model
m_inst.m_model = ModelGenerator<>::Geosphere(rdr, 1.0f, 3, Colour32White, &ddata);
}
// Create a model for a 5-sided cubic dome
void InitFiveSidedCube(Renderer& rdr, std::filesystem::path const& texpath)
{
using namespace pr::rdr;
float const s = 0.5f;
static Vert const verts[] =
{
{{-s, s, s, 1}, ColourWhite, v4Zero, { 0.25f, 0.25f}}, //0
{{-s, s, -s, 1}, ColourWhite, v4Zero, { 0.25f, 0.75f}}, //1
{{ s, s, -s, 1}, ColourWhite, v4Zero, { 0.75f, 0.75f}}, //2
{{ s, s, s, 1}, ColourWhite, v4Zero, { 0.75f, 0.25f}}, //3
{{-s, -s, s, 1}, ColourWhite, v4Zero, {-0.25f, 0.25f}}, //4
{{-s, -s, -s, 1}, ColourWhite, v4Zero, {-0.25f, 0.75f}}, //5
{{-s, -s, -s, 1}, ColourWhite, v4Zero, { 0.25f, 1.25f}}, //6
{{ s, -s, -s, 1}, ColourWhite, v4Zero, { 0.75f, 1.25f}}, //7
{{ s, -s, -s, 1}, ColourWhite, v4Zero, { 1.25f, 0.75f}}, //8
{{ s, -s, s, 1}, ColourWhite, v4Zero, { 1.25f, 0.25f}}, //9
{{ s, -s, s, 1}, ColourWhite, v4Zero, { 0.75f,-0.25f}}, //10
{{-s, -s, s, 1}, ColourWhite, v4Zero, { 0.25f,-0.25f}}, //11
};
static uint16_t const indices[] =
{
0, 1, 2, 0, 2, 3,
0, 4, 5, 0, 5, 1,
1, 6, 7, 1, 7, 2,
2, 8, 9, 2, 9, 3,
3, 10, 11, 3, 11, 0,
};
// Create the sky box model
m_inst.m_model = rdr.m_mdl_mgr.CreateModel(MdlSettings(verts, indices, BBox::Reset(), "sky box"));
// Create a model nugget for the sky box
NuggetProps ddata;
ddata.m_topo = ETopo::TriList;
ddata.m_geom = EGeom::Vert|EGeom::Tex0;
ddata.m_tex_diffuse = rdr.m_tex_mgr.CreateTexture2D(AutoId, texpath.c_str(), SamplerDesc::LinearClamp(), false, "skybox");
m_inst.m_model->CreateNugget(ddata);
}
// Create a model for a 6-sided cube
void InitSixSidedCube(Renderer& rdr, std::filesystem::path const& texpath)
{
using namespace pr::rdr;
constexpr float s = 0.5f, t0 = 0.0f, t1 = 1.0f;
static Vert const verts[] =
{
{{+s, +s, -s, 1}, ColourWhite, v4Zero, {t0, t0}}, // 0 // +X
{{+s, -s, -s, 1}, ColourWhite, v4Zero, {t0, t1}}, // 1
{{+s, -s, +s, 1}, ColourWhite, v4Zero, {t1, t1}}, // 2
{{+s, +s, +s, 1}, ColourWhite, v4Zero, {t1, t0}}, // 3
{{-s, +s, +s, 1}, ColourWhite, v4Zero, {t0, t0}}, // 4 // -X
{{-s, -s, +s, 1}, ColourWhite, v4Zero, {t0, t1}}, // 5
{{-s, -s, -s, 1}, ColourWhite, v4Zero, {t1, t1}}, // 6
{{-s, +s, -s, 1}, ColourWhite, v4Zero, {t1, t0}}, // 7
{{+s, +s, +s, 1}, ColourWhite, v4Zero, {t0, t0}}, // 8 // +Y
{{-s, +s, +s, 1}, ColourWhite, v4Zero, {t0, t1}}, // 9
{{-s, +s, -s, 1}, ColourWhite, v4Zero, {t1, t1}}, // 10
{{+s, +s, -s, 1}, ColourWhite, v4Zero, {t1, t0}}, // 11
{{+s, -s, -s, 1}, ColourWhite, v4Zero, {t0, t0}}, // 12 // -Y
{{-s, -s, -s, 1}, ColourWhite, v4Zero, {t0, t1}}, // 13
{{-s, -s, +s, 1}, ColourWhite, v4Zero, {t1, t1}}, // 14
{{+s, -s, +s, 1}, ColourWhite, v4Zero, {t1, t0}}, // 15
{{+s, +s, +s, 1}, ColourWhite, v4Zero, {t0, t0}}, // 16 // +Z
{{+s, -s, +s, 1}, ColourWhite, v4Zero, {t0, t1}}, // 17
{{-s, -s, +s, 1}, ColourWhite, v4Zero, {t1, t1}}, // 18
{{-s, +s, +s, 1}, ColourWhite, v4Zero, {t1, t0}}, // 19
{{-s, +s, -s, 1}, ColourWhite, v4Zero, {t0, t0}}, // 20 // -Z
{{-s, -s, -s, 1}, ColourWhite, v4Zero, {t0, t1}}, // 21
{{+s, -s, -s, 1}, ColourWhite, v4Zero, {t1, t1}}, // 22
{{+s, +s, -s, 1}, ColourWhite, v4Zero, {t1, t0}}, // 23
};
static uint16_t const indices[] =
{
0, 1, 2, 0, 2, 3, // 0 - 6
4, 5, 6, 4, 6, 7, // 6 - 12
8, 9,10, 8,10,11, // 12 - 18
12,13,14, 12,14,15, // 18 - 24
16,17,18, 16,18,19, // 24 - 30
20,21,22, 20,22,23, // 30 - 36
};
// Create the sky box model
m_inst.m_model = rdr.m_mdl_mgr.CreateModel(MdlSettings(verts, indices, BBox::Reset(), "sky box"));
// Create the model nuggets for the sky box
NuggetProps ddata(ETopo::TriList, EGeom::Vert|EGeom::Tex0);
// One texture per nugget
auto tpath = texpath.wstring();
size_t ofs = tpath.find(L"??", 0, 2);
if (ofs == std::wstring::npos)
throw std::runtime_error("Provided path does not include '??' characters");
wchar_t const axes[6][3] = {{L"+X"},{L"-X"},{L"+Y"},{L"-Y"},{L"+Z"},{L"-Z"}};
for (int i = 0; i != 6; ++i)
{
// Load the texture for this face of the sky box
tpath[ofs+0] = axes[i][0];
tpath[ofs+1] = axes[i][1];
ddata.m_tex_diffuse = rdr.m_tex_mgr.CreateTexture2D(AutoId, tpath.c_str(), SamplerDesc::LinearClamp(), false, "skybox");
// Create the render nugget for this face of the sky box
ddata.m_vrange = rdr::Range(i*4, (i+1)*4);
ddata.m_irange = rdr::Range(i*6, (i+1)*6);
m_inst.m_model->CreateNugget(ddata);
}
}
};
}
| 38.876847 | 126 | 0.554866 | [
"render",
"shape",
"vector",
"model",
"transform"
] |
58e7ed7a954b4e59b0a2e87ecc0a7e116fac9205 | 6,182 | c | C | src/index_helpers.c | OpenNWP/geos95 | b97fa8764c19085186bd2d0308b663b497389eda | [
"MIT"
] | 1 | 2021-08-01T16:28:24.000Z | 2021-08-01T16:28:24.000Z | src/index_helpers.c | OpenNWP/geos95 | b97fa8764c19085186bd2d0308b663b497389eda | [
"MIT"
] | null | null | null | src/index_helpers.c | OpenNWP/geos95 | b97fa8764c19085186bd2d0308b663b497389eda | [
"MIT"
] | null | null | null | /*
This source file is part of the geos95 library, which is released under the MIT license.
Github repository: https://github.com/OpenNWP/geos95
*/
/*
This file contains helper functions concerned with simple algebraic operations on vectors.
*/
#include <math.h>
#include "../include/geos95.h"
int flinspace(double in_vector[], int vector_length, double min, double max)
{
/*
This function separates the interval between a minimum and a maximum into equidistant sections.
*/
double delta = (max - min)/(vector_length - 1);
for(int i = 0; i < vector_length; i++)
{
in_vector[i] = min + i*delta;
if(i == vector_length - 1)
{
in_vector[i] = max;
}
}
return 0;
}
int fwhere_double(double vector[], int vector_length, double wanted_value, double epsilon)
{
/*
This function returns the index where a vector of doubles (almost) assumes a certain value.
*/
int index = -1;
int continue_bool = 1;
int i = 0;
while(continue_bool == 1)
{
if(fabs(vector[i] - wanted_value) < epsilon)
{
index = i;
continue_bool = 0;
}
i++;
if(i == vector_length)
{
continue_bool = 0;
}
}
return index;
}
int find_min_index(double vector[], int vector_length)
{
/*
This function returns the index where a vector has its minimum.
*/
int result = 0;
double current_min = vector[0];
for(int i = 1; i < vector_length; ++i)
{
if (vector[i] < current_min)
{
current_min = vector[i];
result = i;
}
}
return result;
}
int find_max_index(double vector[], int vector_length)
{
/*
This function returns the index where a vector has its maximum.
*/
int result = 0;
double current_max = vector[0];
for(int i = 1; i < vector_length; i++)
{
if(vector[i] > current_max)
{
current_max = vector[i];
result = i;
}
}
return result;
}
int find_min_index_exclude(double vector[], int vector_length, int exclude_indices_vector[], int exclude_indices_vector_length)
{
/*
This function finds the index where a vector has its minimum, excluding the elements of another vector.
*/
int result = 0;
double current_min = vector[0];
for(int i = 1; i < vector_length; ++i)
{
if (vector[i] < current_min)
{
if (in_bool_calculator(i, exclude_indices_vector, exclude_indices_vector_length) == 0)
{
current_min = vector[i];
result = i;
}
}
}
return result;
}
int fmake_abs(double vector[], int vector_length)
{
/*
This function turns each element of a vector of doubles into its absolute value.
*/
for(int i = 0; i < vector_length; i++)
{
vector[i] = fabs(vector[i]);
}
return 0;
}
int fvec_scal(double result[], double vector[], double scalar, int vector_length)
{
/*
This function adds a scalar value to a vector.
*/
for(int i = 0; i < vector_length; i++)
{
result[i] = vector[i] + scalar;
}
return 0;
}
int find_index_n_equal(double time_vector_a[], double time_vector_b[], int n_time_a, int n_time_b)
{
/*
This function detects how many values of two vectors of doubles are equal.
*/
int n_overlap = 0;
for (int i = 0; i < n_time_a; ++i)
{
for (int j = 0; j < n_time_b; ++j)
{
if (time_vector_a[i] == time_vector_b[j])
{
n_overlap = n_overlap + 1;
}
}
}
return n_overlap;
}
int find_index_where_equal_a(double time_vector_a[], double time_vector_b[], int n_time_a, int n_time_b, int time_indices_overlap_a[])
{
/*
This function detects the indices of vector_a where it has a value that is an element of vector_b.
*/
int index = 0;
for (int i = 0; i < n_time_a; ++i)
{
for (int j = 0; j < n_time_b; ++j)
{
if (time_vector_a[i] == time_vector_b[j])
{
time_indices_overlap_a[index] = i;
++index;
}
}
}
return 0;
}
int find_n_between_points(double vector[], int n_values, double min_value, double max_value)
{
/*
This function counts the elements of a vector that are between two given values.
*/
int n_points_between = 0;
for (int i = 0; i < n_values; ++i)
{
if (vector[i] > min_value && vector[i] < max_value)
{
n_points_between = n_points_between + 1;
}
}
return n_points_between;
}
double fsum(double vector[], int vector_length)
{
/*
This function calculates the sum of a vector.
*/
double result = 0;
for (int i = 0; i < vector_length; ++i)
{
result = result + vector[i];
}
return result;
}
int freverse(double vector_in[], int vector_length, double vector_out[])
{
/*
This function reverses a vector of doubles.
*/
for (int i = 0; i < vector_length; ++i)
{
vector_out[i] = vector_in[((int) vector_length) - 1 - i];
}
return 0;
}
int freverse_int(int vector_in[], int vector_length, int vector_out[])
{
/*
This function reverses a vector of integers.
*/
for (int i = 0; i < vector_length; ++i)
{
vector_out[i] = vector_in[((int) vector_length) - 1 - i];
}
return 0;
}
double double_sum_gen(double vector[], int vector_length, int first_index, int second_index)
{
/*
This function calculates the sum of all elements of a vector of doubles between two indices.
*/
double result = 0;
if (first_index <= second_index)
{
for (int i = first_index ; i <= second_index; ++i)
{
result += vector[i];
}
}
else
{
for (int i = first_index; i < vector_length; ++i)
{
result += vector[i];
}
for (int i = 0; i <= second_index; ++i)
{
result += vector[i];
}
}
return result;
}
int in_bool_calculator(int value, int check_array[], int array_length)
{
/*
This function checks if a vector of integers contains a certain value.
*/
int result = 0;
for(int i = 0; i < array_length; i++)
{
if(check_array[i] == value)
{
result = 1;
break;
}
}
return result;
}
| 22.157706 | 134 | 0.598512 | [
"vector"
] |
95aa2ed884645f1817c65ddc2a748156db2a8a3e | 44,721 | c | C | Plugins/MaxQ/Source/ThirdParty/CSpice_Library/cspice/src/cspice/term_pl02.c | gamergenic/Spaceflight-Toolkit-For-Unreal-Engine-5 | 11d81127dd296595bca30cb1565ff3b813210230 | [
"MIT"
] | 6 | 2022-01-21T19:58:08.000Z | 2022-03-28T12:32:24.000Z | Plugins/MaxQ/Source/ThirdParty/CSpice_Library/cspice/src/cspice/term_pl02.c | gamergenic/Spaceflight-Toolkit-For-Unreal-Engine-5 | 11d81127dd296595bca30cb1565ff3b813210230 | [
"MIT"
] | null | null | null | Plugins/MaxQ/Source/ThirdParty/CSpice_Library/cspice/src/cspice/term_pl02.c | gamergenic/Spaceflight-Toolkit-For-Unreal-Engine-5 | 11d81127dd296595bca30cb1565ff3b813210230 | [
"MIT"
] | 4 | 2022-02-12T10:01:40.000Z | 2022-03-28T14:28:52.000Z | /*
-Procedure term_pl02 ( Terminator using DSK type 2 plate model )
-Abstract
Deprecated: This routine has been superseded by the CSPICE routine
termpt_c. This routine is supported for purposes of backward
compatibility only.
Compute a set of points on the umbral or penumbral terminator of a
specified target body, where the target body's surface is
represented by a triangular plate model contained in a type 2 DSK
segment.
-Disclaimer
THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE
CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S.
GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE
ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE
PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS"
TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY
WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A
PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC
SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE
SOFTWARE AND RELATED MATERIALS, HOWEVER USED.
IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA
BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT
LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND,
INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS,
REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE
REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY.
RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF
THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY
CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE
ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE.
-Required_Reading
NAIF_IDS
PCK
SPK
TIME
-Keywords
BODY
GEOMETRY
MATH
*/
#include "SpiceUsr.h"
#include "SpiceZfc.h"
#include "SpiceZst.h"
#include "SpiceZmc.h"
void term_pl02 ( SpiceInt handle,
ConstSpiceDLADescr * dladsc,
ConstSpiceChar * trmtyp,
ConstSpiceChar * source,
ConstSpiceChar * target,
SpiceDouble et,
ConstSpiceChar * fixref,
ConstSpiceChar * abcorr,
ConstSpiceChar * obsrvr,
SpiceInt npts,
SpiceDouble * trgepc,
SpiceDouble obspos [3],
SpiceDouble trmpts [][3],
SpiceInt pltids [] )
/*
-Brief_I/O
VARIABLE I/O DESCRIPTION
-------- --- --------------------------------------------------
handle I DSK handle.
dladsc I DLA descriptor of target body segment.
trmtyp I Terminator type.
source I Light source.
target I Target body.
et I Observation epoch.
fixref I Body-fixed frame associated with target.
abcorr I Aberration correction.
obsrvr I Observer.
npts I Number of points in terminator set.
trgepc O Epoch associated with target center.
obspos O Position of observer in body-fixed frame.
trmpts O Terminator point set.
pltids O DSK plate IDs of surface points.
-Detailed_Input
handle is the DAS file handle of a DSK file open for read
access. This kernel must contain a type 2 segment
that provides a plate model representing the entire
surface of the target body.
dladsc is the DLA descriptor of a DSK segment representing
the surface of a target body.
trmtyp is a string indicating the type of terminator to
compute: umbral or penumbral. The umbral terminator is
the boundary of the portion of the target surface in
total shadow. The penumbral terminator is the boundary
of the portion of the surface that is completely
illuminated. Note that in astronomy references, the
unqualified word "terminator" refers to the umbral
terminator. Here, the unqualified word refers to either
type of terminator.
To compute the terminator points, this routine first
computes a set of points on the terminator of the
indicated type on the surface of a reference ellipsoid
for the target body. Each such point defines the
direction of a ray emanating from the target center and
associated with a terminator point on the actual surface
defined by the plate model. The outermost surface
intercept of each such ray is a considered to be a
terminator point of the surface defined by the plate
model.
Possible values of `trmtyp' are
"UMBRAL"
"PENUMBRAL"
Case and leading or trailing blanks in `trmtyp' are
not significant.
source is the name of the body acting as a light source.
`source' is case-insensitive, and leading and trailing
blanks in `target' are not significant. Optionally, you
may supply a string containing the integer ID code
for the object. For example both "SUN" and "10" are
legitimate strings that indicate the Sun is the light
source.
This routine assumes that a kernel variable
representing the light source's radii is present in
the kernel pool. Normally the kernel variable would
be defined by loading a PCK file.
The shape of the light source is always modeled as a
sphere, regardless of whether radii defining a
triaxial ellipsoidal shape model are available in the
kernel pool. The maximum radius of the body is used
as the radius of the sphere.
target is the name of the target body. `target' is
case-insensitive, and leading and trailing blanks in
`target' are not significant. Optionally, you may supply
a string containing the integer ID code for the object.
For example both "MOON" and "301" are legitimate strings
that indicate the moon is the target body.
This routine assumes that a kernel variable representing
the target's radii is present in the kernel pool.
Normally the kernel variable would be defined by loading
a PCK file.
et is the epoch of participation of the observer,
expressed as ephemeris seconds past J2000 TDB: `et' is
the epoch at which the observer's position is
computed.
When aberration corrections are not used, `et' is also
the epoch at which the position and orientation of the
target body and position of the light source are
computed.
When aberration corrections are used, `et' is the epoch
at which the observer's position relative to the solar
system barycenter is computed; in this case the
position and orientation of the target body are
computed at et-lt or et+lt, where `lt' is the one-way
light time between the target body's center and the
observer, and the sign applied to `lt' depends on the
selected correction. See the description of `abcorr'
below for details.
fixref is the name of the reference frame relative to which
the output terminator points are expressed. This must
a body-centered, body-fixed frame associated with the
target. The frame's axes must be compatible with the
triaxial ellipsoidal shape model associated with the
target body (normally provide via a PCK): this
routine assumes that the first, second, and third
axis lengths correspond, respectively, to the x, y,
and z-axes of the frame designated by `fixref'.
`fixref' may refer to a built-in frame (documented in
the Frames Required Reading) or a frame defined by a
loaded frame kernel (FK).
The orientation of the frame designated by `fixref' is
evaluated at epoch of participation of the target
body. See the descriptions of `et' and `abcorr' for
details.
abcorr indicates the aberration correction to be applied
when computing the observer-target position, the
orientation of the target body, and the target-
source position vector. `abcorr' may be any of
the following.
"NONE" Apply no correction. Compute the
terminator points using the position
of the light source and target, and
the orientation of the target, at `et'.
Let `lt' represent the one-way light time between the
observer and the target body's center. The following
values of `abcorr' apply to the "reception" case in
which photons depart from the target body's center at
the light-time corrected epoch et-lt and *arrive* at
the observer's location at `et':
"LT" Correct for one-way light time (also
called "planetary aberration") using a
Newtonian formulation. This correction
yields the location of the terminator
points at the approximate time they
emitted photons arriving at the
observer at `et' (the difference between
light time to the target center and
light time to the terminator points
is ignored).
The light time correction uses an
iterative solution of the light time
equation. The solution invoked by the
"LT" option uses one iteration.
The target position as seen by the
observer, the position of the light
source as seen from the target at
et-lt, and the rotation of the target
body, are corrected for light time.
'LT+S' Correct for one-way light time and
stellar aberration using a Newtonian
formulation. This option modifies the
positions obtained with the "LT" option
to account for the observer's velocity
relative to the solar system
barycenter. This correction also
applies to the position of the light
source relative to the target. The
result is the apparent terminator as
seen by the observer.
"CN" Converged Newtonian light time
correction. In solving the light time
equation, the "CN" correction iterates
until the solution converges. The
position and rotation of the target
body and the position of the light
source relative to the target are
corrected for light time.
'CN+S' Converged Newtonian light time
and stellar aberration corrections.
obsrvr is the name of the observing body. This is typically
a spacecraft, the Earth, or a surface point on the
Earth. `obsrvr' is case-insensitive, and leading and
trailing blanks in `obsrvr' are not significant.
Optionally, you may supply a string containing the
integer ID code for the object. For example both
"EARTH" and "399" are legitimate strings that indicate
the Earth is the observer.
npts is the number of terminator points to compute.
-Detailed_Output
trgepc is the "target epoch." `trgepc' is defined as follows:
letting `lt' be the one-way light time between the
target center and observer, `trgepc' is either the
epoch et-lt or `et' depending on whether the requested
aberration correction is, respectively, for received
radiation or omitted. `lt' is computed using the
method indicated by `abcorr'.
`trgepc' is expressed as seconds past J2000 TDB.
obspos is the vector from the center of the target body at
epoch `trgepc' to the observer at epoch `et'. `obspos' is
expressed in the target body-fixed reference frame
`fixref', which is evaluated at `trgepc'.
`obspos' is returned to simplify various related
computations that would otherwise be cumbersome. For
example, the vector `xvec' from the observer to the
Ith terminator point can be calculated via the call
vminus_c ( trmpts[i], obspos, xvec );
The components of `obspos' are given in units of km.
trmpts is an array of points on the umbral or penumbral
terminator of the target, as specified by the input
argument `trmtyp'. The ith point is contained in the
array elements
trmpts[i][j], j = 0, 1, 2
As described above, each terminator point lies on a ray
emanating from the center of the target and passing
through a terminator point on the target's reference
ellipsoid. Each terminator point *on the reference
ellipsoid* is the point of tangency of a plane that is
also tangent to the light source. These associated
points of tangency on the light source have uniform
distribution in longitude when expressed in a
cylindrical coordinate system whose Z-axis is the
target-source vector. The magnitude of the separation in
longitude between the tangency points on the light
source is
2*Pi / npts
If the reference ellipsoid for the target is spherical,
the terminator points also are uniformly distributed in
longitude in the cylindrical system described above. If
the reference ellipsoid of the target is non-spherical,
the longitude distribution of the points generally is
not uniform.
The terminator points are expressed in the body-fixed
reference frame designated by `fixref'. Units are km.
pltids is an array of integer ID codes of the plates on which
the terminator points are located. The ith plate ID
corresponds to the ith terminator point. These ID codes can
be use to look up data associated with the plate, such
as the plate's vertices or outward normal vector.
`pltids' should be declared by the caller
SpiceInt pltids [npts];
-Parameters
None.
-Exceptions
1) If the input frame name `fixref' cannot be mapped
to a frame ID code, the error SPICE(NOTRANSLATION) is
signaled.
2) If the target name `target' cannot be mapped to a body ID code,
the error SPICE(IDCODENOTFOUND) is signaled.
3) If the source name `source' cannot be mapped to a body ID
code, an error is signaled by a routine in the call tree of
this routine.
4) If the frame designated by `fixref' is not centered
on the target, the error SPICE(INVALIDFIXREF) is
signaled.
5) If the terminator type is not recognized, an error
is signaled by a routine in the call tree of
this routine.
6) If the set size `npts' is not at least 1, an error
is signaled by a routine in the call tree of
this routine.
7) If any of the reference ellipsoid's semi-axis lengths is
non-positive, an error is signaled by a routine in the
call tree of this routine.
8) If the light source has non-positive radius, an error
is signaled by a routine in the call tree of
this routine.
9) If the light source intersects the smallest sphere centered at
the origin and containing the ellipsoid, an error is signaled
by a routine in the call tree of this routine.
10) If radii for the target body or light source are not
available in the kernel pool, an error is signaled by
a routine in the call tree of this routine.
11) If radii are available but either body does not have three
radii, the error SPICE(INVALIDCOUNT) is signaled.
12) If any SPK look-up fails, an error is signaled by
a routine in the call tree of this routine.
13) If a DSK providing a DSK type 2 plate model has not been
loaded prior to calling term_pl02, an error is signaled by a
routine in the call tree of this routine.
14) If the segment associated with the input DLA descriptor is not
of data type 2, the error SPICE(WRONGDATATYPE) is signaled.
15) If a surface point cannot be computed because the ray
corresponding to a longitude/latitude pair fails to intersect
the target surface as defined by the plate model, an error is
signaled by a routine in the call tree of this routine.
16) If the DSK segment identified by `dladsc' is not for the
body identified by `target', the error SPICE(DSKTARGETMISMATCH)
is signaled.
17) If any input string pointer is null, the error
SPICE(NULLPOINTER) is signaled.
18) If any input string has length zero, the error
SPICE(EMPTYSTRING) is signaled.
-Files
Appropriate DSK, SPK, PCK, and frame kernels must be loaded by the
calling program before this routine is called.
The following data are required:
- DSK data: a DSK file containing a plate model representing the
target body's surface must be loaded. This kernel must contain
a type 2 segment that contains data for the entire surface of
the target body.
- SPK data: ephemeris data for target, observer, and light
source must be loaded. If aberration corrections are used,
the states of all three objects relative to the solar system
barycenter must be calculable from the available ephemeris
data. Typically ephemeris data are made available by loading
one or more SPK files via furnsh_c.
- PCK data: triaxial radii for the target body and
the light source must be loaded into the kernel pool.
Typically this is done by loading a text PCK file via
furnsh_c.
- Further PCK data: rotation data for the target body must
be loaded. These may be provided in a text or binary PCK
file.
- Frame data: if a frame definition is required to convert
the observer and target states to the target body-fixed
frame designated by `fixref', that definition must be
available in the kernel pool. Typically the definitions of
frames not already built-in to SPICE are supplied by loading
a frame kernel.
In all cases, kernel data are normally loaded once per program
run, NOT every time this routine is called.
-Particulars
In this routine, we use the term "umbral terminator" to denote
the curve usually called the "terminator": this curve is the
boundary of the portion of the target body's surface that lies in
total shadow. We use the term "penumbral terminator" to denote
the boundary of the completely illuminated portion of the
surface.
Boundaries of illuminated regions on an arbitrary surface are often
complicated point sets: boundaries of shadows of mountains and
craters, if present, all contribute to the overall set. To make the
terminator computation tractable, we simplify the problem by using a
reference ellipsoid for guidance. We compute a set of terminator
points on the reference ellipsoid for the target body, then use
those points to define the latitudes and longitudes of terminator
points on the surface defined by the specified triangular shape
model. As such, the set of terminator points found by this routine
is just an approximation.
Below we discuss the computation of terminator points on the target
body's reference ellipsoid.
This routine assumes a spherical light source. Light rays are
assumed to travel along straight lines; refraction is not modeled.
Points on the reference ellipsoid at which the entire cap of
the light source is visible are considered to be completely
illuminated. Points on the ellipsoid at which some portion
(or all) of the cap of the light source are blocked are
considered to be in partial (or total) shadow.
In general, the terminator on an ellipsoid is a more complicated
curve than the limb (which is always an ellipse). Aside from
various special cases, the terminator does not lie in a plane.
However, the condition for a point X on the ellipsoid to lie on
the terminator is simple: a plane tangent to the ellipsoid at X
must also be tangent to the light source. If this tangent plane
does not intersect the vector from the center of the ellipsoid to
the center of the light source, then X lies on the umbral
terminator; otherwise X lies on the penumbral terminator.
-Examples
The numerical results shown for this example may differ across
platforms. The results depend on the SPICE kernels used as input,
the compiler and supporting libraries, and the machine specific
arithmetic implementation.
1) Compute sets of umbral and penumbral terminator points on Phobos
as seen from Mars. Perform a consistency check using the solar
incidence angle at each point, where the solar incidence angle
is computed using both a reference ellipsoid and the actual
plate model surface and surface normal. We expect to see a
solar incidence angle of approximately 90 degrees. Since the
solar incidence angle is measured between the local outward
normal and the direction to the Sun, the solar incidence angle
at an umbral or penumbral terminator point should be,
respectively, greater than or less than 90 degrees by
approximately the angular radius of the Sun as seen from each
terminator point.
Use the meta-kernel shown below to load the required SPICE
kernels.
KPL/MK
File: term_pl02_ex1.tm
This meta-kernel is intended to support operation of SPICE
example programs. The kernels shown here should not be
assumed to contain adequate or correct versions of data
required by SPICE-based user applications.
In order for an application to use this meta-kernel, the
kernels referenced here must be present in the user's
current working directory.
The names and contents of the kernels referenced
by this meta-kernel are as follows:
File name Contents
--------- --------
mar097.bsp Mars satellite ephemeris
pck00010.tpc Planet orientation and
radii
naif0010.tls Leapseconds
\begindata
KERNELS_TO_LOAD = ( 'mar097.bsp',
'pck00010.tpc',
'naif0010.tls' )
\begintext
End of meta-kernel
Use the DSK kernel below to provide the plate model representation
of the surface of Phobos.
phobos_3_3.bds
Example code begins here.
/.
Program term_pl02_ex1
./
#include <stdio.h>
#include <math.h>
#include "SpiceUsr.h"
int main()
{
/.
Local parameters
./
#define FILSIZ 256
#define NPOINTS 3
#define NTYPES 2
#define TOL ( 1.e-12 )
#define CORLEN 15
#define TYPLEN 81
#define TIMLEN 41
/.
Local variables
./
SpiceBoolean found;
SpiceChar * abcorr = "LT+S";
SpiceChar dsk [ FILSIZ ];
SpiceChar * fixref = "IAU_PHOBOS";
SpiceChar meta [ FILSIZ ];
SpiceChar * trmtyp;
SpiceChar * trmtypes [ NTYPES ] =
{
"Umbral",
"Penumbral"
};
SpiceChar * obsrvr = "Mars";
SpiceChar * target = "Phobos";
SpiceChar * utcstr = "2007 FEB 9 00:00:00 UTC";
SpiceChar timstr [ TIMLEN];
SpiceDLADescr dladsc;
SpiceDouble delta;
SpiceDouble emissn;
SpiceDouble lt;
SpiceDouble obspos [3];
SpiceDouble phase;
SpiceDouble radius;
SpiceDouble solar;
SpiceDouble sunAngRad;
SpiceDouble sunPos [3];
SpiceDouble sunRadii [3];
SpiceDouble sunVec [3];
SpiceDouble trgepc;
SpiceDouble et;
SpiceDouble lat;
SpiceDouble lon;
SpiceDouble trmpts [NPOINTS][3];
SpiceInt handle;
SpiceInt i;
SpiceInt n;
SpiceInt typidx;
SpiceInt pltids [NPOINTS];
/.
Prompt for the name of a meta-kernel specifying
all of the other kernels we need. Load the
metakernel.
./
prompt_c ( "Enter meta-kernel name > ", FILSIZ, meta );
furnsh_c ( meta );
/.
Prompt for the name of the DSK to read.
./
prompt_c ( "Enter DSK name > ", FILSIZ, dsk );
/.
Open the DSK file for read access.
We use the DAS-level interface for
this function.
./
dasopr_c ( dsk, &handle );
/.
Begin a forward search through the
kernel, treating the file as a DLA.
In this example, it's a very short
search.
./
dlabfs_c ( handle, &dladsc, &found );
if ( !found )
{
/.
We arrive here only if the kernel
contains no segments. This is
unexpected, but we're prepared for it.
./
setmsg_c ( "No segments found in DSK file #.");
errch_c ( "#", dsk );
sigerr_c ( "SPICE(NODATA)" );
}
/.
If we made it this far, `dladsc' is the
DLA descriptor of the first segment.
Convert the observation time to seconds past J2000 TDB.
./
str2et_c ( utcstr, &et );
timout_c ( et,
"YYYY-MON-DD "
"HR:MN:SC.### ::TDB(TDB)",
TIMLEN,
timstr );
printf ( "\n\n"
" Observer: %s\n"
" Target: %s\n"
" Observation epoch: %s\n"
" Aberration correction: %s\n"
" Body-fixed frame: %s\n",
obsrvr,
target,
timstr,
abcorr,
fixref );
/.
Look up the radii of the Sun. We'll use these as
part of a computation to check the solar incidence
angles at the terminator points.
./
bodvrd_c ( "SUN", "RADII", 3, &n, sunRadii );
/.
Now compute grids of terminator points using both
terminator types.
./
for ( typidx = 0; typidx < NTYPES; typidx++ )
{
/.
Select the terminator type.
./
trmtyp = trmtypes [typidx];
printf ( "\n"
" Terminator type: %s\n", trmtyp );
/.
Compute the terminator point set.
./
term_pl02 ( handle, &dladsc, trmtyp, "Sun",
target, et, fixref, abcorr,
obsrvr, NPOINTS, &trgepc, obspos,
trmpts, pltids );
/.
Display the terminator points.
./
for ( i = 0; i < NPOINTS; i++ )
{
printf ( "\n" );
reclat_c ( trmpts[i], &radius, &lon, &lat );
printf (
" Terminator point %d:\n"
" Radius (km): %f\n"
" Planetocentric longitude (deg): %f\n"
" Planetocentric latitude (deg): %f\n"
" Plate ID: %d\n",
(int)i,
radius,
lon * dpr_c(),
lat * dpr_c(),
(int)pltids[i] );
/.
Compute the angular radius of the Sun as seen from
the current terminator point. Subtracting (adding)
this value from (to) the solar incidence angle for
umbral (penumbral) terminator points should yield a
value close to 90 degrees. This provides a sanity
check on the locations of the terminator points.
First find the position of the Sun relative to the
target's center at the light time corrected epoch
trgepc.
./
spkpos_c ( "Sun", trgepc, fixref,
abcorr, target, sunPos, < );
vsub_c ( sunPos, trmpts[i], sunVec );
sunAngRad = asin ( sunRadii[0] / vnorm_c(sunVec) );
/.
Compute the delta by which we adjust the solar
incidence angles.
./
if ( eqstr_c( trmtyp, "umbral" ) )
{
delta = -sunAngRad;
}
else
{
delta = sunAngRad;
}
/.
Compute the illumination angles using an ellipsoidal
representation of the target's surface. The role of
this representation is to provide an outward surface
normal.
./
illum_c ( target, et, abcorr,
obsrvr, trmpts[i], &phase,
&solar, &emissn );
printf (
" "
"Solar incidence angle derived using\n"
" "
" - an ellipsoidal reference surface (deg):"
" %f\n",
solar * dpr_c() );
printf (
" "
" > adjusted for Solar angular radius (deg):"
" %f\n",
(solar+delta) * dpr_c() );
/.
Compute the illumination angles at the terminator point
using the actual plate model surface normal.
./
illum_pl02 ( handle, &dladsc, target, et,
abcorr, obsrvr, trmpts[i],
&phase, &solar, &emissn );
printf (
" "
" - plate model's surface and normal vector (deg):"
" %f\n",
solar * dpr_c() );
}
}
printf ( "\n" );
/.
Close the kernel. This isn't necessary in a stand-
alone program, but it's good practice in subroutines
because it frees program and system resources.
./
dascls_c ( handle );
return ( 0 );
}
When this program was executed on a Mac/Intel/cc/64-bit
platform, using the meta-kernel file named term_pl02_ex1.tm and
the DSK file named phobos_3_3.bds, the output was:
Enter meta-kernel name > term_pl02_ex1.tm
Enter DSK name > phobos_3_3.bds
Observer: Mars
Target: Phobos
Observation epoch: 2007-FEB-09 00:01:05.184 (TDB)
Aberration correction: LT+S
Body-fixed frame: IAU_PHOBOS
Terminator type: Umbral
Terminator point 0:
Radius (km): 12.111257
Planetocentric longitude (deg): 34.584501
Planetocentric latitude (deg): -0.001298
Plate ID: 200400
Solar incidence angle derived using
- an ellipsoidal reference surface (deg): 90.182028
> adjusted for Solar angular radius (deg): 90.000000
- plate model's surface and normal vector (deg): 90.240660
Terminator point 1:
Radius (km): 9.774665
Planetocentric longitude (deg): -143.659941
Planetocentric latitude (deg): 43.397190
Plate ID: 156958
Solar incidence angle derived using
- an ellipsoidal reference surface (deg): 90.182028
> adjusted for Solar angular radius (deg): 90.000000
- plate model's surface and normal vector (deg): 87.138686
Terminator point 2:
Radius (km): 11.500619
Planetocentric longitude (deg): -146.128151
Planetocentric latitude (deg): -43.082379
Plate ID: 25552
Solar incidence angle derived using
- an ellipsoidal reference surface (deg): 90.182029
> adjusted for Solar angular radius (deg): 90.000000
- plate model's surface and normal vector (deg): 91.404206
Terminator type: Penumbral
Terminator point 0:
Radius (km): 12.859785
Planetocentric longitude (deg): -145.415505
Planetocentric latitude (deg): 0.001299
Plate ID: 86763
Solar incidence angle derived using
- an ellipsoidal reference surface (deg): 89.817972
> adjusted for Solar angular radius (deg): 90.000000
- plate model's surface and normal vector (deg): 89.055489
Terminator point 1:
Radius (km): 10.327413
Planetocentric longitude (deg): 36.340069
Planetocentric latitude (deg): -43.397192
Plate ID: 76977
Solar incidence angle derived using
- an ellipsoidal reference surface (deg): 89.817972
> adjusted for Solar angular radius (deg): 90.000000
- plate model's surface and normal vector (deg): 77.351956
Terminator point 2:
Radius (km): 10.086025
Planetocentric longitude (deg): 33.871859
Planetocentric latitude (deg): 43.082380
Plate ID: 282136
Solar incidence angle derived using
- an ellipsoidal reference surface (deg): 89.817972
> adjusted for Solar angular radius (deg): 90.000000
- plate model's surface and normal vector (deg): 88.997322
-Restrictions
1) This routine models light paths as straight lines.
-Literature_References
None.
-Author_and_Institution
N.J. Bachman (JPL)
J. Diaz del Rio (ODC Space)
-Version
-CSPICE Version 1.1.0, 26-OCT-2021 (JDR)
Changed the argument names "npoints" and "plateIDs" to "npts" and
"pltids" for consistency with other routines.
Edited the header to comply with NAIF standard.
Index lines now state that this routine is deprecated.
-CSPICE Version 1.0.0, 22-FEB-2017 (NJB)
Include file references have been updated. Integer output
format in the example program has been updated.
An error in the Detailed_Output header section was corrected.
The text now states that the central axis of the cylindrical
system is the target-source vector.
29-APR-2014 (NJB)
Bug fix: added chkout_c call after call to edterm_.
Bug fix: corrected module name used in check-in and
check-out calls.
Bug fix: added error handling for null input string
pointers and empty strings.
Changed name of argument `fixfrm' to `fixref'.
14-MAY-2010 (NJB)
Updated kernels in example program.
12-FEB-2010 (NJB)
This routine now calls the CSPICE routine
edterm_
instead of
edterm_pl02__
This routine was updated to include
SpiceDSK.h
pl02.h
The header example has been updated to use current
planetary and satellite SPK files.
09-FEB-2007 (NJB)
-Index_Entries
DEPRECATED find terminator on plate model
DEPRECATED find terminator on triangular shape model
DEPRECATED find umbral terminator on plate model
DEPRECATED find umbral terminator on plate model
DEPRECATED find penumbral terminator on plate model
DEPRECATED find penumbral terminator on shape model
-&
*/
{ /* Begin term_pl02_c */
/*
Local variables
*/
SpiceBoolean found;
SpiceDSKDescr dskdsc;
/*
Pointer for a dynamically allocated lon/lat grid
(the type of this pointer is "pointer to an
array of two SpiceDoubles").
*/
SpiceDouble ( * lonLatGridPtr )[2];
SpiceDouble radius;
SpiceInt i;
SpiceInt nBytes;
SpiceInt trgcde;
/*
Participate in error tracing.
*/
chkin_c ( "term_pl02" );
/*
Check the input strings. Make sure none of the pointers are null and
that each string contains at least one non-null character.
*/
CHKFSTR ( CHK_STANDARD, "term_pl02", trmtyp );
CHKFSTR ( CHK_STANDARD, "term_pl02", source );
CHKFSTR ( CHK_STANDARD, "term_pl02", target );
CHKFSTR ( CHK_STANDARD, "term_pl02", fixref );
CHKFSTR ( CHK_STANDARD, "term_pl02", abcorr );
CHKFSTR ( CHK_STANDARD, "term_pl02", obsrvr );
/*
Map the target name to an ID code.
*/
bods2c_c ( target, &trgcde, &found );
if ( failed_c() )
{
chkout_c ( "term_pl02" );
return;
}
if ( !found )
{
setmsg_c ( "The target name # could not be mapped "
"to an ID code." );
errch_c ( "#", target );
sigerr_c ( "SPICE(IDCODENOTFOUND)" );
chkout_c ( "term_pl02" );
return;
}
/*
Check the DSK descriptor of the DSK segment; make sure it's
for the correct body.
*/
dskgd_c ( handle, dladsc, &dskdsc );
if ( failed_c() )
{
chkout_c ( "term_pl02" );
return;
}
if ( dskdsc.center != trgcde )
{
setmsg_c ( "The target is # but the input DSK "
"segment is for body #." );
errint_c ( "#", dskdsc.center );
sigerr_c ( "SPICE(DSKTARGETMISMATCH)" );
chkout_c ( "term_pl02" );
return;
}
/*
First step: find terminator points on the reference ellipsoid. We'll
let the f2c'd routine edterm_pl02__ handle checking of the inputs; if
this routine signals an error, we'll exit.
Note in particular that if a PCK file providing radii for the target
reference ellipsoid hasn't been loaded, we'll find out here.
*/
edterm_ ( ( char * ) trmtyp,
( char * ) source,
( char * ) target,
( doublereal * ) &et,
( char * ) fixref,
( char * ) abcorr,
( char * ) obsrvr,
( integer * ) &npts,
( doublereal * ) trgepc,
( doublereal * ) obspos,
( doublereal * ) trmpts,
( ftnlen ) strlen(trmtyp),
( ftnlen ) strlen(source),
( ftnlen ) strlen(target),
( ftnlen ) strlen(fixref),
( ftnlen ) strlen(abcorr),
( ftnlen ) strlen(obsrvr) );
if ( failed_c() )
{
chkout_c ( "term_pl02" );
return;
}
/*
At this point, the outputs
trgepc
obspos
have been set.
Allocate an array to hold longitude/latitude coordinates
corresponding to the terminator points on the reference
ellipsoid.
*/
nBytes = npts * 2 * sizeof( SpiceDouble );
lonLatGridPtr = ( SpiceDouble(*)[2] ) malloc( nBytes );
if ( !lonLatGridPtr )
{
setmsg_c ( "Call to malloc to allocate # bytes of memory "
"for the lon/lat array failed." );
errint_c ( "#", nBytes );
chkout_c ( "term_pl02" );
return;
}
/*
Fill in the longitude/latitude grid.
*/
for ( i = 0; i < npts; i++ )
{
/*
Convert the ith terminator point on the reference ellipsoid
from rectangular to latitudinal coordinates.
*/
reclat_c ( trmpts[i],
&radius,
&( lonLatGridPtr[i][0] ),
&( lonLatGridPtr[i][1] ) );
}
/*
Find the plate model's surface points at the lon/lat locations
we've computed. Find the plate ID corresponding to each surface
point as well.
We cast the lon/lat grid pointer to "pointer to const array of two
SpiceDoubles" for compatibility with the prototype of llgrid_pl02.
Only the const qualifier is new; the size is unchanged.
*/
llgrid_pl02 ( handle,
dladsc,
npts,
(ConstSpiceDouble (*)[2]) lonLatGridPtr,
trmpts,
pltids );
/*
If no error occurred, the outputs
trmpts
pltids
are set.
Free the dynamically allocated lon/lat array.
*/
free ( lonLatGridPtr );
chkout_c ( "term_pl02" );
} /* End term_pl02_c */
| 37.454774 | 79 | 0.554281 | [
"geometry",
"object",
"shape",
"vector",
"model"
] |
95bbf436aedabd4befa32ed0b73bcfc2b6ffb746 | 2,285 | h | C | src/algebra/algebra.h | zhaowenlan1779/prometry | 8c66a643f4b0de475b8fbcd30a1f14bc35f8c96d | [
"MIT"
] | null | null | null | src/algebra/algebra.h | zhaowenlan1779/prometry | 8c66a643f4b0de475b8fbcd30a1f14bc35f8c96d | [
"MIT"
] | null | null | null | src/algebra/algebra.h | zhaowenlan1779/prometry | 8c66a643f4b0de475b8fbcd30a1f14bc35f8c96d | [
"MIT"
] | null | null | null | // Copyright 2019 Zhupengfei and others
// Licensed under the MIT License.
//
// 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 <memory>
#include <string>
#include <vector>
#include <symengine/expression.h>
#include <symengine/symbol.h>
#include "common/dynamic_bitset.h"
namespace Common {
struct ProofChainNode;
}
namespace Algebra {
using Expression = SymEngine::Expression;
using Symbol = SymEngine::RCP<const SymEngine::Symbol>;
using ProofList = Common::DynamicBitset;
/**
* Solves a single equation with regard to a single symbol, there are no limits
* about what arguments to use to represent the symbol in question.
*
* Eg. 3x + 2y == 0 can solve to x == -2/3y (wrt x) and y == -3/2x (wrt y).
*/
std::vector<Expression> SolveSingle(const Expression& equation, const Symbol& symbol);
class System {
public:
explicit System();
~System();
/**
* Adds an equation to the system (expr == 0), if not already known.
*/
void AddEquation(const Expression& expr, const std::string& transform = "",
const std::vector<std::shared_ptr<Common::ProofChainNode>>& parents = {});
/**
* Checks if a equation holds. i.e. whether it can be reached by the known equations.
* @return true if the equation *always* holds, false otherwise (undetermined or never).
* Second element contains a list of "reasons" for this equation when result is true.
*/
std::pair<bool, std::shared_ptr<Common::ProofChainNode>> CheckEquation(const Expression& expr);
/**
* Checks whether new equations have been added since the last query.
* This clears the new_equations state.
*
* @return whether new equations have been added.
*/
bool HasNewEquations();
private:
struct Impl;
std::unique_ptr<Impl> impl;
};
} // namespace Algebra
| 32.183099 | 99 | 0.701969 | [
"vector",
"transform"
] |
95c6b8c2686645240f27f68fd9001f50abcba0ff | 9,660 | h | C | modules/synApps_5_6/support/motor-6-7/motorApp/HytecSrc/HytecMotorDriver.h | A2-Collaboration/epics | b764a53bf449d9f6b54a1173c5e75a22cf95098c | [
"OML"
] | null | null | null | modules/synApps_5_6/support/motor-6-7/motorApp/HytecSrc/HytecMotorDriver.h | A2-Collaboration/epics | b764a53bf449d9f6b54a1173c5e75a22cf95098c | [
"OML"
] | null | null | null | modules/synApps_5_6/support/motor-6-7/motorApp/HytecSrc/HytecMotorDriver.h | A2-Collaboration/epics | b764a53bf449d9f6b54a1173c5e75a22cf95098c | [
"OML"
] | null | null | null | /********************************************************************************/
/* H H Y Y TTTTT EEEEE CCC HYTEC ELECTRONICS LTD */
/* H H Y Y T E C 5 Cradock Road, */
/* HHHHH Y T EEE C Reading, Berks. Tel: 0118 9757770 */
/* H H Y T E C RG2 0JT Fax: 0118 9757566 */
/* H H Y T EEEEE CCC Web: www.hytec-electronics.co.uk */
/********************************************************************************/
/********************************************************************************/
/* _____________________________________________________________________ */
/* | H Y T E C 8 6 0 1 S T E P M O T E R A s y n D r i v e r | */
/* --------------------------------------------------------------------- */
/* */
/* Source file name :- HytecMotorDriver.c */
/* */
/* Initial creation date :- 29-Mar-2011 */
/* */
/* Original Developers :- Jim Chen. Hytec Electronics Ltd */
/* */
/********************************************************************************/
/* */
/* Description :- This is the "model 3" asyn motor driver for Hytec 8601 */
/* Stepper Motor IP module. The code is based on original */
/* Hytec drvHy8601asyn.c driver and also Mark Rivers' */
/* ACRMotorDriver. */
/* */
/* */
/* (C)2011 Hytec Electronics Ltd. */
/* */
/********************************************************************************/
/* */
/* Revision history: (comment and initial revisions) */
/* */
/* vers. revised modified by date */
/* ----- ----------- ---------------- --------------- */
/* 2.0 Continued version Jim Chen 29/03/2011 */
/* The main contents of this driver are the same as the original */
/* Hytec drvHy8601asyn.c driver but in "model 3" form as defined */
/* by Mark Rivers. Hence it starts from version 2.0. */
/* 2.1 New interfaces Jim Chen 04/04/2011 */
/* This version follows the asyn motor model 3 latest interface */
/* changes that include: */
/* a).New asynMotorAxis base class */
/* b).Moves the axis specific functions from the motor controller */
/* class to individual axis class */
/* c).Changes asynMotorDriver.cpp to asynMotorController.cpp. */
/* 2.2 Bugs fix Jim Chen 14/04/2011 */
/* Fixed setPosition bug */
/* Added firmware version parameter */
/* */
/********************************************************************************/
#include "asynMotorController.h"
#include "asynMotorAxis.h"
static const char *driverName = "HytecMotorDriver";
/* CSR Register bit definitions */
#define CSR_HOMESTOP 0x8000
#define CSR_INTEN 0x4000
#define CSR_DONE 0x2000
#define CSR_CRASHSTOP 0x1000
#define CSR_DIRECTION 0x0800
#define CSR_AUX2 0x0400
#define CSR_AUX1 0x0200
#define CSR_ENCODUSE 0x0100
#define CSR_ENCODDET 0x0080
#define CSR_JOG 0x0040
#define CSR_GO 0x0020
#define CSR_DRVSTAT 0x0010
#define CSR_HOMELMT 0x0008
#define CSR_MAXLMT 0x0004
#define CSR_MINLMT 0x0002
#define CSR_RESET 0x0001
/* New Hardware Register Map */
#define REG_STEPCNTLO 0x00
#define REG_STEPCNTHI 0x02
#define REG_CURRPOSLO 0x04
#define REG_CURRPOSHI 0x06
#define REG_STARTSTOPSPD 0x08
#define REG_HIGHSPD 0x0A
#define REG_RAMPRATE 0x0C
#define REG_CSR 0x0E
#define REG_INTMASK 0x10
#define REG_INTVECTOR 0x12
#define REG_INTREQUEST 0x14
#define REG_CURRENTSPD 0x16
#define REG_SPARE1 0x18
#define REG_SPARE2 0x1A
#define REG_SPARE3 0x1C
#define REG_SPARE4 0x1E
#define PROM_MODEL 0x8601
#define PROM_OFFS 0x80
#define REG_BANK_OFFS 0x00
#define REG_BANK_SZ 0x20
#define INT_LMT (CSR_MINLMT | CSR_MAXLMT | CSR_HOMELMT)
#define INT_SRCS (CSR_RESET | INT_LMT | CSR_DRVSTAT | CSR_DONE)
/* define a mask to enable all sources of interrupts */
#define ALL_INTS (INT_SRCS | CSR_INTEN)
#define DONE_INT (CSR_DONE) /* the only interrupt suggested to use. JC 12-Nov-2009 */
#define HY8601_NUM_AXES 4
#define IP_DETECT_STR "VITA4 "
#define GET_REG(base,reg) (*(volatile epicsUInt16 *)((base)+(reg)))
#define SET_REG(base,reg,val) do { *(volatile epicsUInt16 *)((base)+(reg)) = (val);} while(0)
#define CSR_SET(base,bit) do { *(volatile epicsUInt16 *)((base)+REG_CSR) |= (bit);} while(0)
/* Please NOTE, The DONE bit is cleared by either ORing an "1" or ANDing an "1" (if it is already "1") to it.
* Yet neither ORing nor ANDing it with "0" would affect it. As such, clearing any other bit in the CSR with
* the AND operation need to be very careful so that it doesn't knock down the DONE bit. This is why in the
* following macro after inverting the bit in the CSR, we clear the DONE bit to the inversion result in order
* not to affect the DONE bit. */
#define CSR_CLR(base,bit) do { *(volatile epicsUInt16 *)((base)+REG_CSR) &= ((~(bit)) & 0xDFFF);} while(0)
#define HytecPowerControlString "HYTEC_POWER"
#define HytecBrakeControlString "HYTEC_BRAKE"
#define HytecFirmwareString "HYTEC_FWVERSION"
#define HytecMoveAllString "HYTEC_MOVEALL"
class HytecMotorAxis : public asynMotorAxis
{
public:
HytecMotorAxis(class HytecMotorController *pC, int axis, double ratio, int vector);
asynStatus move(double position, int relative, double min_velocity, double max_velocity, double acceleration);
asynStatus moveVelocity(double min_velocity, double max_velocity, double acceleration);
asynStatus home(double min_velocity, double max_velocity, double acceleration, int forwards);
asynStatus stop(double acceleration);
asynStatus poll(bool *moving);
asynStatus setPosition(double position);
int getVector();
volatile char * getChanbase();
//the following are called from non-member function so they are here
private:
asynStatus InitialiseAxis();
HytecMotorController *pC_;
volatile char *chanbase;
int vector;
int useencoder;
double encoderRatio; /**< (double) Number of encoder counts in one motor count (encoder counts/motor counts) */
double resolution; /**< (double) Number of motor units per engineering unit */
double softLowLimit; /**< (double) Low soft limit in motor units ???? Shouldn't these two in engineering unit? */
double softHighLimit; /**< (double) High soft limit in motor units ???? */
double absPosition;
double desiredMove;
int times; /* to remember the the done bit set the first time */
int absAskingPosition;
friend class HytecMotorController;
};
class HytecMotorController : asynMotorController
{
public:
HytecMotorController(const char *portName, int numAxes, double movingPollPeriod,
double idlePollPeriod, int cardnum, int ip_carrier, int ipslot,
int vector, int useencoder, double encoderRatio0, double encoderRatio1,
double encoderRatio2, double encoderRatio3);
// These are the methods that we override from asynMotorDriver
asynStatus readInt32(asynUser *pasynUser, epicsInt32 *value);
asynStatus writeInt32(asynUser *pasynUser, epicsInt32 value);
asynStatus writeFloat64(asynUser *pasynUser, epicsFloat64 value);
void report(FILE *fp, int level);
HytecMotorAxis* getAxis(asynUser *pasynUser);
HytecMotorAxis* getAxis(int axisNo);
//the following are called from non-member function so they are here
void drvHy8601GetAxisStatus( HytecMotorAxis *pAxis, int csr_data );
int getNumAxes();
int getIPCarrier();
int getIPSlot();
epicsMessageQueueId getINTMsgQID();
void increaseMsgSent();
void increaseMsgFail();
protected:
// New function codes
int HytecPowerControl_;
#define FIRST_HYTEC_PARAM HytecPowerControl_
int HytecBrakeControl_;
int HytecFWVersion_;
int HytecMoveAll_;
#define LAST_HYTEC_PARAM HytecMoveAll_
#define NUM_HYTEC_PARAMS (&LAST_HYTEC_PARAM - &FIRST_HYTEC_PARAM + 1)
private:
asynStatus SetupCard();
int checkprom(char *pr,int expmodel);
int numAxes;
epicsMessageQueueId intMsgQId;
int messagesSent; // for report
int messagesFailed; // for report
int ip_carrier;
int ipslot;
asynUser *pasynUser;
int card;
int vector;
int useencoder;
volatile char *regbase;
epicsThreadId motorThread;
friend class HytecMotorAxis;
};
| 43.318386 | 136 | 0.555694 | [
"vector",
"model"
] |
95c8819e198b59d5bf5e61ce48ec5311222acb9f | 979 | h | C | Include/KAI/Core/DotGraph.h | cschladetsch/KAI | b7078bc73817f0f76805c9330dbaf45584d86a22 | [
"MIT"
] | 13 | 2015-07-23T08:45:31.000Z | 2019-10-10T23:56:00.000Z | Include/KAI/Core/DotGraph.h | cschladetsch/KAI | b7078bc73817f0f76805c9330dbaf45584d86a22 | [
"MIT"
] | 16 | 2016-02-06T12:54:45.000Z | 2020-10-30T14:23:35.000Z | Include/KAI/Core/DotGraph.h | cschladetsch/KAI | b7078bc73817f0f76805c9330dbaf45584d86a22 | [
"MIT"
] | 4 | 2017-02-27T22:24:19.000Z | 2018-12-09T17:54:07.000Z | #pragma once
#include <KAI/Core/Base.h>
// TODO: remove this and have DotGraph use Pimpl
// not very important as few things include this file.
#include <set>
KAI_BEGIN
// Generates GraphViz script showing the depedancy graph given an object _root
struct DotGraph : StringStream
{
private:
std::set<Label> excluded_names;
std::set<Type::Number> excluded_types;
public:
DotGraph();
DotGraph(Object, String const &filename);
void Generate(Object, String const &filename);
void ExcludeLabel(Label const &);
template <class T>
void ExcludeType()
{
excluded_types.insert(Type::Traits<T>::Number);
}
void WriteHeader();
void WriteFooter();
void WriteToFile(const char *);
void Add(Object);
String GetText();
friend DotGraph &operator<<(DotGraph &graph, Object const &object);
protected:
bool IsExcluded(Object const&) const;
};
DotGraph &operator<<(DotGraph &graph, Object const &object);
KAI_END
| 21.282609 | 78 | 0.694586 | [
"object"
] |
95cb2fad07344674fcadc9524d959ae18bd36f7c | 2,194 | h | C | morpho5/geometry/field.h | ConduitDan/morpho | 9df2d652d9bc269ce0f8cdeb4d55cec51d95c2f9 | [
"MIT"
] | 10 | 2021-09-18T14:44:14.000Z | 2022-03-26T11:41:50.000Z | morpho5/geometry/field.h | ConduitDan/morpho | 9df2d652d9bc269ce0f8cdeb4d55cec51d95c2f9 | [
"MIT"
] | 79 | 2021-10-05T17:33:19.000Z | 2022-03-31T16:06:10.000Z | morpho5/geometry/field.h | ConduitDan/morpho | 9df2d652d9bc269ce0f8cdeb4d55cec51d95c2f9 | [
"MIT"
] | 2 | 2021-10-05T16:56:16.000Z | 2021-10-31T19:55:27.000Z | /** @file field.h
* @author T J Atherton
*
* @brief Fields
*/
#ifndef field_h
#define field_h
#include "object.h"
#include "mesh.h"
#include <stdio.h>
#define FIELD_CLASSNAME "Field"
#define FIELD_GRADEOPTION "grade"
#define FIELD_OP_METHOD "op"
#define FIELD_SHAPE_METHOD "shape"
#define FIELD_MESH_METHOD "mesh"
#define FIELD_INDICESOUTSIDEBOUNDS "FldBnds"
#define FIELD_INDICESOUTSIDEBOUNDS_MSG "Field index out of bounds."
#define FIELD_INVLDINDICES "FldInvldIndx"
#define FIELD_INVLDINDICES_MSG "Field indices must be numerical."
#define FIELD_ARITHARGS "FldInvldArg"
#define FIELD_ARITHARGS_MSG "Field arithmetic methods expect a field or number as their argument."
#define FIELD_INCOMPATIBLEMATRICES "FldIncmptbl"
#define FIELD_INCOMPATIBLEMATRICES_MSG "Fields have incompatible shape."
#define FIELD_INCOMPATIBLEVAL "FldIncmptblVal"
#define FIELD_INCOMPATIBLEVAL_MSG "Assignment value has incompatible shape with field elements."
#define FIELD_ARGS "FldArgs"
#define FIELD_ARGS_MSG "Field allows 'grade' as an optional argument."
#define FIELD_OP "FldOp"
#define FIELD_OP_MSG "Method 'op' requires a callable object as the first argument; all other arguments must be fields of compatible shape."
#define FIELD_OPRETURN "FldOpFn"
#define FIELD_OPRETURN_MSG "Could not construct a Field from the return value of the function passed to 'op'."
#define FIELD_MESHARG "FldMshArg"
#define FIELD_MESHARG_MSG "Field expects a mesh as its first argurment"
void field_zero(objectfield *field);
bool field_getelement(objectfield *field, grade grade, elementid el, int indx, value *out);
bool field_getelementwithindex(objectfield *field, int indx, value *out);
bool field_getelementaslist(objectfield *field, grade grade, elementid el, int indx, unsigned int *nentries, double **out);
bool field_setelement(objectfield *field, grade grade, elementid el, int indx, value val);
void field_initialize(void);
#endif /* field_h */
| 37.186441 | 160 | 0.705105 | [
"mesh",
"object",
"shape"
] |
95d09e6e53b72c46f2d0fc850f72c094e97847d9 | 9,084 | c | C | sys/container/hashset.c | krial057/Firedrake | c75687616e637a3d1095dbf1eb90ebec257046a2 | [
"MIT"
] | null | null | null | sys/container/hashset.c | krial057/Firedrake | c75687616e637a3d1095dbf1eb90ebec257046a2 | [
"MIT"
] | null | null | null | sys/container/hashset.c | krial057/Firedrake | c75687616e637a3d1095dbf1eb90ebec257046a2 | [
"MIT"
] | null | null | null | //
// hashset.c
// Firedrake
//
// Created by Sidney Just
// Copyright (c) 2013 by Sidney Just
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#include <memory/memory.h>
#include <libc/string.h>
#include <system/syslog.h>
#include "hashset.h"
static size_t hashet_capacity[42] =
{
5, 11, 23, 41, 67, 113, 199, 317, 521, 839, 1361, 2207, 3571, 5779, 9349, 15121,
24473, 39607, 64081, 103681, 167759, 271429, 439199, 710641, 1149857, 1860503, 3010349,
4870843, 7881193, 12752029, 20633237, 33385273, 54018521, 87403763, 141422317, 228826121,
370248451, 599074561, 969323023, 1568397599, 2537720629, 4106118251
};
static size_t hashset_maxCount[42] =
{
4, 8, 17, 29, 47, 76, 123, 199, 322, 521, 843, 1364, 2207, 3571, 5778, 9349,
15127, 24476, 39603, 64079, 103682, 167761, 271443, 439204, 710647, 1149851, 1860498,
3010349, 4870847, 7881196, 12752043, 20633239, 33385282, 54018521, 87403803, 141422324,
228826127, 370248451, 599074578, 969323029, 1568397607, 2537720636
};
hashset_t *hashset_create(size_t capacity, hashset_hashfunc_t hashFunction, hashset_comparefunc_t compareFunction)
{
hashset_t *set = halloc(NULL, sizeof(hashset_t));
if(set)
{
// Find the right capacity for the object
for(int i=1; i<42; i++)
{
if(hashet_capacity[i] > capacity || i == 41)
{
capacity = hashet_capacity[i - 1];
break;
}
}
// Initialize the set
set->buckets = halloc(NULL, capacity * sizeof(hashset_bucket_t **));
if(!set->buckets)
{
hfree(NULL, set);
return NULL;
}
memset(set->buckets, 0, capacity * sizeof(hashset_bucket_t **));
set->capacity = capacity;
set->count = 0;
set->hashFunction = hashFunction;
set->compareFunction = compareFunction ? compareFunction : hash_pointerCompare;
set->lock = SPINLOCK_INIT;
}
return set;
}
void hashset_destroy(hashset_t *set)
{
for(size_t i=0; i<set->capacity; i++)
{
hashset_bucket_t *bucket = set->buckets[i];
while(bucket)
{
hashset_bucket_t *next = bucket->overflow;
hfree(NULL, bucket);
bucket = next;
}
}
hfree(NULL, set->buckets);
hfree(NULL, set);
}
array_t *hashset_allObjects(hashset_t *set)
{
array_t *array = array_create();
for(size_t i=0; i<set->capacity; i++)
{
hashset_bucket_t *bucket = set->buckets[i];
while(bucket)
{
if(bucket->data)
array_addObject(array, bucket->data);
bucket = bucket->overflow;
}
}
return array;
}
hashset_bucket_t *hashset_findBucket1(hashset_t *set, const void *key)
{
uint32_t hash = set->hashFunction(key);
size_t index = hash % set->capacity;
hashset_bucket_t *bucket = set->buckets[index];
while(bucket)
{
if(set->compareFunction(bucket->key, key))
return bucket;
bucket = bucket->overflow;
}
return NULL;
}
hashset_bucket_t *hashset_findBucket2(hashset_t *set, const void *key)
{
uint32_t hash = set->hashFunction(key);
size_t index = hash % set->capacity;
hashset_bucket_t *bucket = set->buckets[index];
while(bucket)
{
if(set->compareFunction(bucket->key, key))
return bucket;
bucket = bucket->overflow;
}
bucket = halloc(NULL, sizeof(hashset_bucket_t));
if(!bucket)
return NULL;
bucket->key = key;
bucket->data = NULL;
bucket->overflow = set->buckets[index];
set->buckets[index] = bucket;
return bucket;
}
void hashset_rehash(hashset_t *set, size_t capacity)
{
hashset_bucket_t **buckets = set->buckets;
size_t cCapacity = set->capacity;
set->capacity = capacity;
set->buckets = halloc(NULL, capacity * sizeof(hashset_bucket_t **));
if(!set->buckets)
{
set->capacity = cCapacity;
set->buckets = buckets;
return;
}
memset(set->buckets, 0, capacity * sizeof(hashset_bucket_t **));
for(size_t i=0; i<cCapacity; i++)
{
hashset_bucket_t *bucket = buckets[i];
while(bucket)
{
hashset_bucket_t *next = bucket->overflow;
if(bucket->key)
{
uint32_t hash = set->hashFunction(bucket->key);
size_t index = hash % capacity;
bucket->overflow = set->buckets[index];
set->buckets[index] = bucket;
}
else
{
hfree(NULL, bucket);
}
bucket = next;
}
}
hfree(NULL, buckets);
}
void hashset_expandIfNeeded(hashset_t *set)
{
for(size_t i=0; i<41; i++)
{
if(set->capacity == hashet_capacity[i])
{
if(set->count >= hashset_maxCount[i])
{
size_t capacity = hashet_capacity[i + 1];
hashset_rehash(set, capacity);
}
break;
}
}
}
void hashset_shrinkIfNeeded(hashset_t *set)
{
for(size_t i=1; i<41; i++)
{
if(set->capacity == hashet_capacity[i])
{
if(set->count <= hashset_maxCount[i - 1])
{
size_t capacity = hashet_capacity[i - 1];
hashset_rehash(set, capacity);
}
}
}
}
void hashset_lock(hashset_t *set)
{
spinlock_lock(&set->lock);
}
void hashset_unlock(hashset_t *set)
{
spinlock_unlock(&set->lock);
}
void *hashset_objectForKey(hashset_t *set, const void *key)
{
hashset_bucket_t *bucket = hashset_findBucket1(set, key);
return bucket ? bucket->data : NULL;
}
void hashset_removeObjectForKey(hashset_t *set, const void *key)
{
hashset_bucket_t *bucket = hashset_findBucket1(set, key);
if(bucket)
{
bucket->key = NULL;
bucket->data = NULL;
set->count --;
hashset_shrinkIfNeeded(set);
}
}
void hashset_setObjectForKey(hashset_t *set, void *data, const void *key)
{
if(!data)
{
hashset_removeObjectForKey(set, key);
return;
}
hashset_bucket_t *bucket = hashset_findBucket2(set, key);
if(bucket->data == NULL)
{
bucket->data = data;
set->count ++;
hashset_expandIfNeeded(set);
}
}
uint32_t hashset_count(hashset_t *set)
{
return set->count;
}
void *hashset_iteratorGetNextObject(hashset_t *set, uintptr_t *__bucket, uint32_t *__index, bool object)
{
hashset_bucket_t *bucket = (hashset_bucket_t *)*__bucket;
uint32_t index = *__index;
while(bucket)
{
if(bucket->data)
{
*__bucket = (uintptr_t)bucket->overflow;
return (object) ? bucket->data : (void *)bucket->key;
}
bucket = bucket->overflow;
}
*__bucket = 0;
while(index < set->capacity)
{
bucket = set->buckets[index];
while(bucket)
{
if(bucket->data)
{
*__bucket = (uintptr_t)bucket->overflow;
*__index = index + 1;
return (object) ? bucket->data : (void *)bucket->key;
}
bucket = bucket->overflow;
}
index ++;
}
return NULL;
}
size_t hashset_iteratorNextObject(iterator_t *iterator, size_t maxObjects)
{
hashset_t *hashset = iterator->data;
uint32_t i = 0;
for(; i<maxObjects; i++)
{
void *object = hashset_iteratorGetNextObject(hashset, (uintptr_t *)&iterator->custom[0], (uint32_t *)&iterator->custom[1], iterator->custom[3] == 0);
if(!object)
break;
iterator->objects[i] = object;
}
return i;
}
iterator_t *hashset_iterator(hashset_t *set)
{
iterator_t *iterator = iterator_create(hashset_iteratorNextObject, set);
return iterator;
}
iterator_t *hashset_keyIterator(hashset_t *set)
{
iterator_t *iterator = iterator_create(hashset_iteratorNextObject, set);
iterator->custom[3] = 1;
return iterator;
}
// Hashing functions
uint32_t hash_pointer(const void *key)
{
return (uint32_t)key;
}
uint32_t hash_cstring(const void *key)
{
const uint8_t *string = key;
size_t length = strlen((const char *)string);
uint32_t result = 0;
for(size_t i=0; i<length; i++)
{
result += string[i];
result += (result << 10);
result += (result >> 6);
}
result += (result << 3);
result += (result >> 11);
result += (result << 15);
return result;
}
// Source: http://stackoverflow.com/questions/664014/what-integer-hash-function-are-good-that-accepts-an-integer-hash-key
uint32_t hash_integer(const void *key)
{
uint32_t ikey = (uint32_t)key;
ikey = ((ikey >> 16) ^ ikey) * 0x45D9F3B;
ikey = ((ikey >> 16) ^ ikey) * 0x45D9F3B;
ikey = ((ikey >> 16) ^ ikey);
return ikey;
}
bool hash_pointerCompare(const void *key1, const void *key2)
{
return (key1 == key2);
}
bool hash_cstringCompare(const void *key1, const void *key2)
{
return (strcmp((const char *)key1, (const char *)key2) == 0);
}
bool hash_integerCompare(const void *key1, const void *key2)
{
return (key1 == key2);
}
| 21.995157 | 151 | 0.687803 | [
"object"
] |
95d1196b06707bbd2b3d8d681c111c87de40c4fd | 1,934 | h | C | src/filters/MultixFilter.h | PlaymodesStudio/ofxPlaymodes2017 | 13ed5a77f75fa4c48f47d4e38ac10a5f085c7b31 | [
"MIT"
] | null | null | null | src/filters/MultixFilter.h | PlaymodesStudio/ofxPlaymodes2017 | 13ed5a77f75fa4c48f47d4e38ac10a5f085c7b31 | [
"MIT"
] | 1 | 2019-05-03T11:35:22.000Z | 2019-05-03T23:22:58.000Z | src/filters/MultixFilter.h | PlaymodesStudio/ofxPlaymodes2017 | 13ed5a77f75fa4c48f47d4e38ac10a5f085c7b31 | [
"MIT"
] | null | null | null | /*
* AudioFrame.h
*
* Created on: 09-oct-2008
* Author: arturo castro
*/
#ifndef MULTIXFILTER_H
#define MULTIXFILTER_H
#include "VideoBuffer.h"
#include "VideoHeader.h"
#include "VideoRenderer.h"
#include "ofMain.h"
namespace ofxPm{
class MultixFilter: public VideoSource
{
public:
MultixFilter();
MultixFilter(ofxPm::VideoBuffer & buffer, int numHeaders=2);
virtual ~MultixFilter();
void setup(ofxPm::VideoBuffer & buffer, int numHeaders=2);
void updateValuesPct(vector<float> _vf);
void updateValuesMs(vector<float> _vf);
void drawIntoFbo(int x, int y,int w, int h);
void setNumHeaders(int numHeaders);
int getNumHeaders();
ofxPm::VideoHeader * getHeader(int header);
ofxPm::VideoRenderer * getRenderer(int renderer);
ofxPm::VideoBuffer *getVideoBuffer() const;
void setVideoBuffer(ofxPm::VideoBuffer *videoBuffer);
void setVideoHeader(vector<ofxPm::VideoHeader*> videoHeader);
void setVideoRenderer(vector<ofxPm::VideoRenderer*> videoRenderer);
bool isMinmaxBlend() const;
void setMinmaxBlend(bool minmaxBlend);
// +
void newVideoFrame(VideoFrame & _frame);
ofEvent<VideoFrame> newFrameEvent;
VideoFrame getNextVideoFrame();
float getFps(){return videoBuffer->getFps();};
void setOpacityMode(int _m){opacityMode=_m;};
protected:
vector<ofxPm::VideoHeader> videoHeader;
vector<ofxPm::VideoRenderer> videoRenderer;
ofxPm::VideoBuffer * videoBuffer;
private:
int numHeaders;
// rendering
VideoFrame frame;
ofFbo fbo;
bool minmaxBlend;
int opacityMode;
};
}
#endif // MULTIXFILTER_H
| 26.135135 | 84 | 0.601344 | [
"vector"
] |
95d7d6a4d6377e76fcfb2f1f5bfbd056505b59d2 | 20,315 | c | C | drivers/nble_curie/gap.c | CurieBSP/zephyr | f060e13c882066973948393c9c6102d282253697 | [
"Apache-2.0"
] | 6 | 2016-06-07T00:06:31.000Z | 2021-03-20T19:48:54.000Z | drivers/nble_curie/gap.c | CurieBSP/zephyr | f060e13c882066973948393c9c6102d282253697 | [
"Apache-2.0"
] | 2 | 2016-08-30T01:28:57.000Z | 2017-09-27T01:50:28.000Z | drivers/nble_curie/gap.c | CurieBSP/zephyr | f060e13c882066973948393c9c6102d282253697 | [
"Apache-2.0"
] | 5 | 2016-06-11T07:44:20.000Z | 2021-06-12T17:41:37.000Z | /*
* Copyright (c) 2016 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <errno.h>
#include <stddef.h>
#include <atomic.h>
#include <bluetooth/gatt.h>
#include <bluetooth/bluetooth.h>
#include "gap_internal.h"
#include "conn_internal.h"
#include "hci_core.h"
#if defined(CONFIG_BLUETOOTH_SMP)
#include "smp.h"
#endif /* CONFIG_BLUETOOTH_SMP */
/* #define BT_GATT_DEBUG 1 */
extern void on_nble_curie_log(char *fmt, ...);
extern void __assert_fail(void);
#ifdef BT_GATT_DEBUG
#define BT_DBG(fmt, ...) on_nble_curie_log(fmt, ##__VA_ARGS__)
#define BT_ERR(fmt, ...) on_nble_curie_log(fmt, ##__VA_ARGS__)
#define BT_WARN(fmt, ...) on_nble_curie_log(fmt, ##__VA_ARGS__)
#define BT_INFO(fmt, ...) on_nble_curie_log(fmt, ##__VA_ARGS__)
#define BT_ASSERT(cond) ((cond) ? (void)0 : __assert_fail())
#else
#define BT_DBG(fmt, ...) do {} while (0)
#define BT_ERR(fmt, ...) on_nble_curie_log(fmt, ##__VA_ARGS__)
#define BT_WARN(fmt, ...) on_nble_curie_log(fmt, ##__VA_ARGS__)
#define BT_INFO(fmt, ...) on_nble_curie_log(fmt, ##__VA_ARGS__)
#define BT_ASSERT(cond) ((cond) ? (void)0 : __assert_fail())
#endif
static bt_ready_cb_t bt_ready_cb;
static bt_le_scan_cb_t *scan_dev_found_cb;
static rssi_report_t rssi_report_cb;
struct bt_dev bt_dev;
static int set_advertise_enable(void)
{
#if 0
struct net_buf *buf;
int err;
#endif
if (atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
return 0;
}
#if 0
buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_ENABLE, 1);
if (!buf) {
return -ENOBUFS;
}
net_buf_add_u8(buf, BT_HCI_LE_ADV_ENABLE);
err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_ENABLE, buf, NULL);
if (err) {
return err;
}
#endif
nble_gap_start_adv_req();
return 0;
}
static int set_advertise_disable(void)
{
#if 0
struct net_buf *buf;
int err;
#endif
if (!atomic_test_bit(bt_dev.flags, BT_DEV_ADVERTISING)) {
return 0;
}
#if 0
buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_ADV_ENABLE, 1);
if (!buf) {
return -ENOBUFS;
}
net_buf_add_u8(buf, BT_HCI_LE_ADV_DISABLE);
err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_ADV_ENABLE, buf, NULL);
if (err) {
return err;
}
#endif
nble_gap_stop_adv_req(NULL);
atomic_clear_bit(bt_dev.flags, BT_DEV_ADVERTISING);
return 0;
}
void ble_gap_get_bonding_info(ble_bond_info_cb_t func, void *user_data,
bool include_bonded_addrs)
{
struct nble_gap_sm_bond_info_param params;
params.cb = func;
params.user_data = user_data;
params.include_bonded_addrs = include_bonded_addrs;
nble_gap_sm_bond_info_req(¶ms);
}
void on_nble_gap_start_advertise_rsp(const struct nble_response *params)
{
if (params->status == 0)
atomic_set_bit(bt_dev.flags, BT_DEV_ADVERTISING);
else
BT_WARN("start advertise failed with %d", params->status);
}
void on_nble_gap_disconnect_evt(const struct nble_gap_disconnect_evt *evt)
{
struct bt_conn *conn;
#if 0
/* Nordic has no disconnection error */
if (evt->status) {
return;
}
#endif
conn = bt_conn_lookup_handle(evt->conn_handle);
if (!conn) {
BT_DBG("Unable to look up conn with handle %u",
evt->conn_handle);
return;
}
#if 0
/* Check stacks usage (no-ops if not enabled) */
stack_analyze("rx stack", rx_fiber_stack, sizeof(rx_fiber_stack));
stack_analyze("cmd rx stack", rx_prio_fiber_stack,
sizeof(rx_prio_fiber_stack));
stack_analyze("cmd tx stack", cmd_tx_fiber_stack,
sizeof(cmd_tx_fiber_stack));
stack_analyze("conn tx stack", conn->stack, sizeof(conn->stack));
#endif
conn->err = evt->hci_reason;
bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
conn->handle = 0;
#if 0
/* Only LE supported */
if (conn->type != BT_CONN_TYPE_LE) {
bt_conn_unref(conn);
return;
}
/* TODO enabled when autoconn is supported */
if (atomic_test_bit(conn->flags, BT_CONN_AUTO_CONNECT)) {
bt_conn_set_state(conn, BT_CONN_CONNECT_SCAN);
bt_le_scan_update(false);
}
#endif
bt_conn_unref(conn);
if (atomic_test_bit(bt_dev.flags, BT_DEV_KEEP_ADVERTISING)) {
set_advertise_enable();
}
}
void on_nble_gap_connect_evt(const struct nble_gap_connect_evt *evt)
{
struct bt_conn *conn;
/* Make lookup to check if there's a connection object in CONNECT state
* associated with passed peer LE address.
*/
conn = bt_conn_lookup_state_le(&evt->peer_bda, BT_CONN_CONNECT);
#if 0
/* Nordic has no connection error */
if (evt->status) {
if (!conn) {
return;
}
conn->err = BT_HCI_ERR_UNACCEPT_CONN_PARAMS;
bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
/* Drop the reference got by lookup call in CONNECT state.
* We are now in DISCONNECTED state since no successful LE
* link been made.
*/
bt_conn_unref(conn);
return;
}
#endif
/*
* clear advertising even if we are not able to add connection object
* to keep host in sync with controller state
*/
if (evt->role_slave == BT_CONN_ROLE_SLAVE) {
atomic_clear_bit(bt_dev.flags, BT_DEV_ADVERTISING);
}
if (!conn) {
conn = bt_conn_add_le(&evt->peer_bda);
}
if (!conn) {
BT_DBG("Unable to add new conn for handle %u",
evt->conn_handle);
return;
}
conn->handle = evt->conn_handle;
bt_addr_le_copy(&conn->le.dst, &evt->peer_bda);
conn->le.interval = evt->conn_values.interval;
conn->le.latency = evt->conn_values.latency;
conn->le.timeout = evt->conn_values.supervision_to;
conn->role = evt->role_slave;
#if 0
src.type = BT_ADDR_LE_PUBLIC;
memcpy(src.val, bt_dev.bdaddr.val, sizeof(bt_dev.bdaddr.val));
/* use connection address (instead of identity address) as initiator
* or responder address
*/
if (conn->role == BT_HCI_ROLE_MASTER) {
bt_addr_le_copy(&conn->le.init_addr, &src);
bt_addr_le_copy(&conn->le.resp_addr, &evt->peer_addr);
} else {
bt_addr_le_copy(&conn->le.init_addr, &evt->peer_addr);
bt_addr_le_copy(&conn->le.resp_addr, &src);
}
#endif
bt_conn_set_state(conn, BT_CONN_CONNECTED);
/* Note: Connection update removed because Windows interop and BT spec recommendations */
bt_conn_unref(conn);
#if 0
bt_le_scan_update(false);
#endif
}
void on_nble_gap_adv_report_evt(const struct nble_gap_adv_report_evt *evt,
const uint8_t *buf, uint8_t len)
{
#if TODO_IMPLEMENT_CONNECTION
uint8_t num_reports = buf->data[0];
struct bt_hci_ev_le_advertising_info *info;
BT_DBG("Adv number of reports %u", num_reports);
info = net_buf_pull(buf, sizeof(num_reports));
while (num_reports--) {
int8_t rssi = info->data[info->length];
const bt_addr_le_t *addr;
BT_DBG("%s event %u, len %u, rssi %d dBm",
bt_addr_le_str(&info->addr),
info->evt_type, info->length, rssi);
addr = find_id_addr(&info->addr);
#endif
BT_DBG("nble gap: event:%u, len %u", evt->adv_type, len);
if (scan_dev_found_cb) {
scan_dev_found_cb(&evt->addr, evt->rssi, evt->adv_type,
buf, len);
}
#if TODO_IMPLEMENT_CONNECTION
#if defined(CONFIG_BLUETOOTH_CONN)
check_pending_conn(addr, &info->addr, info->evt_type);
#endif /* CONFIG_BLUETOOTH_CONN */
/* Get next report iteration by moving pointer to right offset
* in buf according to spec 4.2, Vol 2, Part E, 7.7.65.2.
*/
info = net_buf_pull(buf, sizeof(*info) + info->length +
sizeof(rssi));
}
#endif
}
void on_nble_gap_conn_update_evt(const struct nble_gap_conn_update_evt *evt)
{
struct bt_conn *conn;
uint16_t handle, interval;
handle = evt->conn_handle;
interval = evt->conn_values.interval;
/* BT_DBG("status %u, handle %u", evt->status, handle); */
conn = bt_conn_lookup_handle(handle);
if (!conn) {
/* BT_ERR("Unable to lookup conn for handle %u", handle); */
return;
}
/* if (!evt->status) { */
conn->le.interval = interval;
conn->le.latency = evt->conn_values.latency;
conn->le.timeout = evt->conn_values.supervision_to;
notify_le_param_updated(conn);
/* } */
bt_conn_unref(conn);
}
void bt_conn_set_param_le(struct bt_conn *conn,
const struct bt_le_conn_param *param)
{
conn->le.interval_min = param->interval_min;
conn->le.interval_max = param->interval_max;
conn->le.latency = param->latency;
conn->le.timeout = param->timeout;
}
int bt_conn_update_param_le(struct bt_conn *conn,
const struct bt_le_conn_param *param)
{
#if 0
BT_DBG("conn %p features 0x%x params (%d-%d %d %d)", conn,
conn->le.features[0], param->interval_min, param->interval_max,
param->latency, param->timeout);
#endif
/* Check if there's a need to update conn params */
if (conn->le.interval >= param->interval_min &&
conn->le.interval <= param->interval_max) {
return -EALREADY;
}
#if 0
if ((conn->role == BT_HCI_ROLE_SLAVE) &&
!(bt_dev.le.features[0] & BT_HCI_LE_CONN_PARAM_REQ_PROC)) {
return bt_l2cap_update_conn_param(conn, param);
}
if ((conn->le.features[0] & BT_HCI_LE_CONN_PARAM_REQ_PROC) &&
(bt_dev.le.features[0] & BT_HCI_LE_CONN_PARAM_REQ_PROC)) {
#endif
return bt_conn_le_conn_update(conn, param);
#if 0
}
return -EBUSY;
#endif
}
void on_nble_gap_scan_start_stop_rsp(const struct nble_response *rsp)
{
if (rsp->status)
BT_INFO("scan start/stop failed: %d", rsp->status);
/* TODO: clear scanning bit atomic_clear_bit(bt_dev.flags, BT_DEV_SCANNING) */
}
static int bt_hci_stop_scanning(void)
{
#ifdef NOT_USED_FOR_NOW
struct net_buf *buf, *rsp;
struct bt_hci_cp_le_set_scan_enable *scan_enable;
int err;
if (!atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) {
return -EALREADY;
}
buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_SCAN_ENABLE,
sizeof(*scan_enable));
if (!buf) {
return -ENOBUFS;
}
scan_enable = net_buf_add(buf, sizeof(*scan_enable));
memset(scan_enable, 0, sizeof(*scan_enable));
scan_enable->filter_dup = BT_HCI_LE_SCAN_FILTER_DUP_DISABLE;
scan_enable->enable = BT_HCI_LE_SCAN_DISABLE;
err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_SCAN_ENABLE, buf, &rsp);
if (err) {
return err;
}
/* Update scan state in case of success (0) status */
err = rsp->data[0];
if (!err) {
atomic_clear_bit(bt_dev.flags, BT_DEV_SCANNING);
}
net_buf_unref(rsp);
return err;
#endif
nble_gap_stop_scan_req();
return 0;
}
#if defined(CONFIG_BLUETOOTH_CENTRAL)
int bt_le_set_auto_conn(bt_addr_le_t *addr,
const struct bt_le_conn_param *param)
{
return -EINVAL;
}
#endif /* CONFIG_BLUETOOTH_CENTRAL */
static int start_le_scan(uint8_t scan_type, uint16_t interval, uint16_t window,
uint8_t filter_dup)
{
struct nble_gap_scan_params params = {
.interval = interval,
.window = window,
.scan_type = scan_type,
};
#ifdef NOT_USED_FOR_NOW
struct net_buf *buf, *rsp;
struct bt_hci_cp_le_set_scan_params *set_param;
struct bt_hci_cp_le_set_scan_enable *scan_enable;
int err;
buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_SCAN_PARAMS,
sizeof(*set_param));
if (!buf) {
return -ENOBUFS;
}
set_param = net_buf_add(buf, sizeof(*set_param));
memset(set_param, 0, sizeof(*set_param));
set_param->scan_type = scan_type;
/* for the rest parameters apply default values according to
* spec 4.2, vol2, part E, 7.8.10
*/
set_param->interval = sys_cpu_to_le16(interval);
set_param->window = sys_cpu_to_le16(window);
set_param->filter_policy = 0x00;
if (scan_type == BT_HCI_LE_SCAN_ACTIVE) {
err = le_set_nrpa();
if (err) {
net_buf_unref(buf);
return err;
}
set_param->addr_type = BT_ADDR_LE_RANDOM;
} else {
set_param->addr_type = BT_ADDR_LE_PUBLIC;
}
bt_hci_cmd_send(BT_HCI_OP_LE_SET_SCAN_PARAMS, buf);
buf = bt_hci_cmd_create(BT_HCI_OP_LE_SET_SCAN_ENABLE,
sizeof(*scan_enable));
if (!buf) {
return -ENOBUFS;
}
scan_enable = net_buf_add(buf, sizeof(*scan_enable));
memset(scan_enable, 0, sizeof(*scan_enable));
scan_enable->filter_dup = filter_dup;
scan_enable->enable = BT_HCI_LE_SCAN_ENABLE;
err = bt_hci_cmd_send_sync(BT_HCI_OP_LE_SET_SCAN_ENABLE, buf, &rsp);
if (err) {
return err;
}
/* Update scan state in case of success (0) status */
err = rsp->data[0];
if (!err) {
atomic_set_bit(bt_dev.flags, BT_DEV_SCANNING);
}
net_buf_unref(rsp);
#endif
nble_gap_start_scan_req(¶ms);
return 0;
}
#if NOT_USED_FOR_NOW
/* Used to determine whether to start scan and which scan type should be used */
int bt_le_scan_update(bool fast_scan)
{
#if defined(CONFIG_BLUETOOTH_CENTRAL)
uint16_t interval, window;
struct bt_conn *conn;
#endif /* CONFIG_BLUETOOTH_CENTRAL */
if (atomic_test_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
return 0;
}
if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) {
int err;
err = bt_hci_stop_scanning();
if (err) {
return err;
}
}
#if defined(CONFIG_BLUETOOTH_CENTRAL)
conn = bt_conn_lookup_state_le(NULL, BT_CONN_CONNECT_SCAN);
if (!conn) {
return 0;
}
bt_conn_unref(conn);
if (fast_scan) {
interval = BT_GAP_SCAN_FAST_INTERVAL;
window = BT_GAP_SCAN_FAST_WINDOW;
} else {
interval = BT_GAP_SCAN_SLOW_INTERVAL_1;
window = BT_GAP_SCAN_SLOW_WINDOW_1;
}
return start_le_scan(BT_HCI_LE_SCAN_PASSIVE, interval, window, 0x01);
#else
return 0;
#endif /* CONFIG_BLUETOOTH_CENTRAL */
}
#endif
static int bt_init(void)
{
#if NOT_USED_FOR_NOW
struct bt_driver *drv = bt_dev.drv;
#endif
int err = 0;
#if NOT_USED_FOR_NOW
err = drv->open();
if (err) {
BT_ERR("HCI driver open failed (%d)", err);
return err;
}
err = hci_init();
#endif
if (!err) {
err = bt_conn_init();
}
scan_dev_found_cb = NULL;
if (!err) {
atomic_set_bit(bt_dev.flags, BT_DEV_READY);
#if 0
bt_le_scan_update(false);
#endif
}
return err;
}
void on_nble_up(void)
{
if (bt_ready_cb)
bt_ready_cb(bt_init());
}
extern void on_nble_curie_init(void);
int bt_enable(bt_ready_cb_t cb)
{
bt_ready_cb = cb;
on_nble_curie_init();
if (!cb) {
return bt_init();
}
return 0;
}
static bool valid_adv_param(const struct bt_le_adv_param *param)
{
switch (param->type) {
case BT_LE_ADV_IND:
case BT_LE_ADV_SCAN_IND:
case BT_LE_ADV_NONCONN_IND:
break;
default:
return false;
}
#if 0
/* checks done in Nordic */
switch (param->addr_type) {
case BT_LE_ADV_ADDR_IDENTITY:
case BT_LE_ADV_ADDR_NRPA:
break;
default:
return false;
}
if (param->interval_min > param->interval_max ||
param->interval_min < 0x0020 || param->interval_max > 0x4000) {
return false;
}
#endif
return true;
}
static int set_ad(struct bt_eir_data *p_ad_data,
const struct bt_data *ad, size_t ad_len)
{
int i;
for (i = 0; i < ad_len; i++) {
/* Check if ad fit in the remaining buffer */
if (p_ad_data->len + ad[i].data_len + 2 > 31) {
return -EINVAL;
}
p_ad_data->data[p_ad_data->len++] = ad[i].data_len + 1;
p_ad_data->data[p_ad_data->len++] = ad[i].type;
memcpy(&p_ad_data->data[p_ad_data->len], ad[i].data,
ad[i].data_len);
p_ad_data->len += ad[i].data_len;
}
return 0;
}
int bt_le_adv_start(const struct bt_le_adv_param *param,
const struct bt_data *ad, size_t ad_len,
const struct bt_data *sd, size_t sd_len)
{
int err;
struct nble_gap_adv_params set_param = {0};
struct nble_gap_ad_data_params data = {0};
if (!valid_adv_param(param)) {
return -EINVAL;
}
if (atomic_test_bit(bt_dev.flags, BT_DEV_KEEP_ADVERTISING)) {
return -EALREADY;
}
err = set_advertise_disable();
if (err) {
return err;
}
err = set_ad(&data.ad, ad, ad_len);
if (err) {
return err;
}
/*
* Don't bother with scan response if the advertising type isn't
* a scannable one.
*/
if (param->type == BT_LE_ADV_IND || param->type == BT_LE_ADV_SCAN_IND) {
err = set_ad(&data.sd, sd, sd_len);
if (err) {
return err;
}
}
nble_gap_set_adv_data_req(&data);
/* Timeout is handled by application timer */
set_param.timeout = 0;
/* forced to none currently (no whitelist support) */
set_param.filter_policy = 0;
set_param.interval_max = param->interval_max;
set_param.interval_min = param->interval_min;
set_param.type = param->type;
nble_gap_set_adv_params_req(&set_param);
#if 0
if (param->addr_type == BT_LE_ADV_ADDR_NRPA) {
err = le_set_nrpa();
if (err) {
net_buf_unref(buf);
return err;
}
set_param->own_addr_type = BT_ADDR_LE_RANDOM;
} else {
set_param->own_addr_type = BT_ADDR_LE_PUBLIC;
}
bt_hci_cmd_send(BT_HCI_OP_LE_SET_ADV_PARAMETERS, buf);
#endif
err = set_advertise_enable();
if (err) {
return err;
}
atomic_set_bit(bt_dev.flags, BT_DEV_KEEP_ADVERTISING);
return 0;
}
void on_nble_gap_dir_adv_timeout_evt(const struct nble_gap_dir_adv_timeout_evt *p_evt)
{
struct bt_conn *conn = bt_conn_lookup_state_le(BT_ADDR_LE_ANY, BT_CONN_CONNECT);
if (conn) {
atomic_clear_bit(bt_dev.flags, BT_DEV_ADVERTISING);
conn->err = p_evt->error;
bt_conn_set_state(conn, BT_CONN_DISCONNECTED);
bt_conn_unref(conn);
}
}
int bt_le_adv_stop(void)
{
int err;
if (!atomic_test_bit(bt_dev.flags, BT_DEV_KEEP_ADVERTISING)) {
return -EALREADY;
}
err = set_advertise_disable();
if (err) {
return err;
}
atomic_clear_bit(bt_dev.flags, BT_DEV_KEEP_ADVERTISING);
return 0;
}
static bool valid_le_scan_param(const struct bt_le_scan_param *param)
{
if (param->type != BT_HCI_LE_SCAN_PASSIVE &&
param->type != BT_HCI_LE_SCAN_ACTIVE) {
return false;
}
if (/* param->filter_dup != BT_HCI_LE_SCAN_FILTER_DUP_DISABLE */
/* && nble always filters duplicates */
param->filter_dup != BT_HCI_LE_SCAN_FILTER_DUP_ENABLE) {
return false;
}
if (param->interval < 0x0004 || param->interval > 0x4000) {
return false;
}
if (param->window < 0x0004 || param->window > 0x4000) {
return false;
}
if (param->window > param->interval) {
return false;
}
return true;
}
int bt_le_scan_start(const struct bt_le_scan_param *param, bt_le_scan_cb_t cb)
{
int err;
/* Check that the parameters have valid values */
if (!valid_le_scan_param(param)) {
return -EINVAL;
}
#if NOT_USED_FOR_NOW
/* Return if active scan is already enabled */
if (atomic_test_and_set_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
return -EALREADY;
}
if (atomic_test_bit(bt_dev.flags, BT_DEV_SCANNING)) {
err = bt_hci_stop_scanning();
if (err) {
atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN);
return err;
}
}
#endif
err = start_le_scan(param->type, param->interval, param->window,
param->filter_dup);
if (err) {
#if NOT_USED_FOR_NOW
atomic_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN);
#endif
return err;
}
scan_dev_found_cb = cb;
return 0;
}
int bt_le_scan_stop(void)
{
#if NOT_USED_FOR_NOW
/* Return if active scanning is already disabled */
if (!atomic_test_and_clear_bit(bt_dev.flags, BT_DEV_EXPLICIT_SCAN)) {
return -EALREADY;
}
#endif
scan_dev_found_cb = NULL;
#if NOT_USED_FOR_NOW
return bt_le_scan_update(false);
#else
return bt_hci_stop_scanning();
#endif
}
/* Temporary RSSI patch for UAS: RPC need definition if UAS not compiled */
__attribute__((weak))
void on_nble_uas_bucket_change(const struct nble_uas_bucket_change *p_params)
{
}
void ble_gap_set_rssi_report(struct nble_rssi_report_params *params,
struct bt_conn *conn,
rssi_report_resp_t resp_cb, rssi_report_t evt_cb)
{
rssi_report_cb = evt_cb;
params->conn_handle = conn->handle;
nble_gap_set_rssi_report_req(params, resp_cb);
}
void on_nble_gap_set_rssi_report_rsp(const struct nble_response *params)
{
rssi_report_resp_t resp_cb = params->user_data;
if (resp_cb)
resp_cb(params->status);
}
void on_nble_gap_rssi_evt(const struct nble_gap_rssi_evt *event)
{
if (rssi_report_cb)
rssi_report_cb(event->rssi_data);
}
void ble_gap_set_tx_power(int8_t tx_power)
{
struct nble_gap_tx_power_params params = {
.tx_power = tx_power,
};
nble_gap_tx_power_req(¶ms);
}
void on_nble_gap_tx_power_rsp(const struct nble_response *params)
{
}
void ble_gap_get_version(ble_get_version_cb_t func)
{
struct nble_gap_get_version_param params;
params.cb = func;
nble_get_version_req(¶ms);
}
void on_nble_get_version_rsp(const struct nble_version_response *par)
{
struct nble_gap_get_version_param param = par->params;
ble_get_version_cb_t cb = param.cb;
if (cb) {
cb(&par->ver);
}
}
| 22.672991 | 90 | 0.723406 | [
"object"
] |
95d9161f097a9630bd0a1b1c612fbece3bec72d0 | 26,277 | h | C | trunk/3rdparty/srt-1-fit/srtcore/common.h | attenuation/srs | 897d2104fb79c4fc1a89e3889645424c077535bd | [
"MIT"
] | 18,396 | 2015-11-11T09:36:37.000Z | 2022-03-31T23:31:51.000Z | trunk/3rdparty/srt-1-fit/srtcore/common.h | attenuation/srs | 897d2104fb79c4fc1a89e3889645424c077535bd | [
"MIT"
] | 2,471 | 2015-11-10T04:01:38.000Z | 2022-03-31T21:37:21.000Z | trunk/3rdparty/srt-1-fit/srtcore/common.h | attenuation/srs | 897d2104fb79c4fc1a89e3889645424c077535bd | [
"MIT"
] | 4,219 | 2015-11-10T12:17:34.000Z | 2022-03-31T10:41:43.000Z | /*
* SRT - Secure, Reliable, Transport
* Copyright (c) 2018 Haivision Systems Inc.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
*/
/*****************************************************************************
Copyright (c) 2001 - 2009, The Board of Trustees of the University of Illinois.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the
above copyright notice, this list of conditions
and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Illinois
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.
*****************************************************************************/
/*****************************************************************************
written by
Yunhong Gu, last updated 08/01/2009
modified by
Haivision Systems Inc.
*****************************************************************************/
#ifndef __UDT_COMMON_H__
#define __UDT_COMMON_H__
#define _CRT_SECURE_NO_WARNINGS 1 // silences windows complaints for sscanf
#include <cstdlib>
#ifndef _WIN32
#include <sys/time.h>
#include <sys/uio.h>
#else
// #include <winsock2.h>
//#include <windows.h>
#endif
#include <pthread.h>
#include "udt.h"
#include "utilities.h"
#ifdef _DEBUG
#include <assert.h>
#define SRT_ASSERT(cond) assert(cond)
#else
#define SRT_ASSERT(cond)
#endif
enum UDTSockType
{
UDT_UNDEFINED = 0, // initial trap representation
UDT_STREAM = 1,
UDT_DGRAM
};
/// The message types used by UDT protocol. This is a part of UDT
/// protocol and should never be changed.
enum UDTMessageType
{
UMSG_HANDSHAKE = 0, //< Connection Handshake. Control: see @a CHandShake.
UMSG_KEEPALIVE = 1, //< Keep-alive.
UMSG_ACK = 2, //< Acknowledgement. Control: past-the-end sequence number up to which packets have been received.
UMSG_LOSSREPORT = 3, //< Negative Acknowledgement (NAK). Control: Loss list.
UMSG_CGWARNING = 4, //< Congestion warning.
UMSG_SHUTDOWN = 5, //< Shutdown.
UMSG_ACKACK = 6, //< Acknowledgement of Acknowledgement. Add info: The ACK sequence number
UMSG_DROPREQ = 7, //< Message Drop Request. Add info: Message ID. Control Info: (first, last) number of the message.
UMSG_PEERERROR = 8, //< Signal from the Peer side. Add info: Error code.
// ... add extra code types here
UMSG_END_OF_TYPES,
UMSG_EXT = 0x7FFF //< For the use of user-defined control packets.
};
// This side's role is: INITIATOR prepares the environment first, and sends
// appropriate information to the peer. The peer must be RESPONDER and be ready
// to receive it. It's important for the encryption: the INITIATOR side generates
// the KM, and sends it to RESPONDER. RESPONDER awaits KM received from the
// INITIATOR. Note that in bidirectional mode - that is always with HSv5 - the
// INITIATOR creates both sending and receiving contexts, then sends the key to
// RESPONDER, which creates both sending and receiving contexts, using the same
// key received from INITIATOR.
//
// The method of selection:
//
// In HSv4, it's always data sender (the party that sets SRTO_SENDER flag on the
// socket) INITIATOR, and receiver - RESPONDER. The HSREQ and KMREQ are done
// AFTER the UDT connection is done using UMSG_EXT extension messages. As this
// is unidirectional, the INITIATOR prepares the sending context only, the
// RESPONDER - receiving context only.
//
// In HSv5, for caller-listener configuration, it's simple: caller is INITIATOR,
// listener is RESPONDER. In case of rendezvous the parties are equivalent,
// so the role is resolved by "cookie contest". Rendezvous sockets both know
// each other's cookie generated during the URQ_WAVEAHAND handshake phase.
// The cookies are simply compared as integer numbers; the party which's cookie
// is a greater number becomes an INITIATOR, and the other party becomes a
// RESPONDER.
//
// The case of a draw - that both occasionally have baked identical cookies -
// is treated as an extremely rare and virtually impossible case, so this
// results in connection rejected.
enum HandshakeSide
{
HSD_DRAW,
HSD_INITIATOR, //< Side that initiates HSREQ/KMREQ. HSv4: data sender, HSv5: connecting socket or winner rendezvous socket
HSD_RESPONDER //< Side that expects HSREQ/KMREQ from the peer. HSv4: data receiver, HSv5: accepted socket or loser rendezvous socket
};
// For debug
std::string MessageTypeStr(UDTMessageType mt, uint32_t extt = 0);
////////////////////////////////////////////////////////////////////////////////
// Commonly used by various reading facilities
enum EReadStatus
{
RST_OK = 0, //< A new portion of data has been received
RST_AGAIN, //< Nothing has been received, try again
RST_ERROR = -1 //< Irrecoverable error, please close descriptor and stop reading.
};
enum EConnectStatus
{
CONN_ACCEPT = 0, //< Received final handshake that confirms connection established
CONN_REJECT = -1, //< Error during processing handshake.
CONN_CONTINUE = 1, //< induction->conclusion phase
CONN_RENDEZVOUS = 2, //< pass to a separate rendezvous processing (HSv5 only)
CONN_CONFUSED = 3, //< listener thinks it's connected, but caller missed conclusion
CONN_RUNNING = 10, //< no connection in progress, already connected
CONN_AGAIN = -2 //< No data was read, don't change any state.
};
std::string ConnectStatusStr(EConnectStatus est);
const int64_t BW_INFINITE = 1000000000/8; //Infinite=> 1 Gbps
enum ETransmissionEvent
{
TEV_INIT, // --> After creation, and after any parameters were updated.
TEV_ACK, // --> When handling UMSG_ACK - older CCC:onAck()
TEV_ACKACK, // --> UDT does only RTT sync, can be read from CUDT::RTT().
TEV_LOSSREPORT, // --> When handling UMSG_LOSSREPORT - older CCC::onLoss()
TEV_CHECKTIMER, // --> See TEV_CHT_REXMIT
TEV_SEND, // --> When the packet is scheduled for sending - older CCC::onPktSent
TEV_RECEIVE, // --> When a data packet was received - older CCC::onPktReceived
TEV_CUSTOM, // --> probably dead call - older CCC::processCustomMsg
TEV__SIZE
};
std::string TransmissionEventStr(ETransmissionEvent ev);
// Special parameter for TEV_CHECKTIMER
enum ECheckTimerStage
{
TEV_CHT_INIT, // --> UDT: just update parameters, don't call any CCC::*
TEV_CHT_FASTREXMIT, // --> not available on UDT
TEV_CHT_REXMIT // --> CCC::onTimeout() in UDT
};
enum EInitEvent
{
TEV_INIT_RESET = 0,
TEV_INIT_INPUTBW,
TEV_INIT_OHEADBW
};
class CPacket;
// XXX Use some more standard less hand-crafted solution, if possible
// XXX Consider creating a mapping between TEV_* values and associated types,
// so that the type is compiler-enforced when calling updateCC() and when
// connecting signals to slots.
struct EventVariant
{
enum Type {UNDEFINED, PACKET, ARRAY, ACK, STAGE, INIT} type;
union U
{
CPacket* packet;
int32_t ack;
struct
{
int32_t* ptr;
size_t len;
} array;
ECheckTimerStage stage;
EInitEvent init;
} u;
EventVariant()
{
type = UNDEFINED;
memset(&u, 0, sizeof u);
}
template<Type t>
struct VariantFor;
template <Type tp, typename Arg>
void Assign(Arg arg)
{
type = tp;
(u.*(VariantFor<tp>::field())) = arg;
//(u.*field) = arg;
}
void operator=(CPacket* arg) { Assign<PACKET>(arg); };
void operator=(int32_t arg) { Assign<ACK>(arg); };
void operator=(ECheckTimerStage arg) { Assign<STAGE>(arg); };
void operator=(EInitEvent arg) { Assign<INIT>(arg); };
// Note: UNDEFINED and ARRAY don't have assignment operator.
// For ARRAY you'll use 'set' function. For UNDEFINED there's nothing.
template <class T>
EventVariant(T arg)
{
*this = arg;
}
const int32_t* get_ptr() const
{
return u.array.ptr;
}
size_t get_len()
{
return u.array.len;
}
void set(int32_t* ptr, size_t len)
{
type = ARRAY;
u.array.ptr = ptr;
u.array.len = len;
}
EventVariant(int32_t* ptr, size_t len)
{
set(ptr, len);
}
template<Type T>
typename VariantFor<T>::type get()
{
return u.*(VariantFor<T>::field());
}
};
/*
Maybe later.
This had to be a solution for automatic extraction of the
type hidden in particular EventArg for particular event so
that it's not runtime-mistaken.
In order that this make sense there would be required an array
indexed by event id (just like a slot array m_Slots in CUDT),
where the "type distiller" function would be extracted and then
combined with the user-connected slot function this would call
it already with correct type. Note that also the ConnectSignal
function would have to get the signal id by template parameter,
not function parameter. For example:
m_parent->ConnectSignal<TEV_ACK>(SSLOT(updateOnSent));
in which updateOnSent would have to receive an appropriate type.
This has a disadvantage that you can't connect multiple signals
with different argument types to the same slot, you'd have to
make slot wrappers to translate arguments.
It seems that a better idea would be to create binders that would
translate the argument from EventArg to the correct type according
to the rules imposed by particular event id. But I'd not make it
until there's a green light on C++11 for SRT, so maybe in a far future.
template <ETransmissionEvent type>
class EventArgType;
#define MAP_EVENT_TYPE(tev, tp) template<> class EventArgType<tev> { typedef tp type; }
*/
// The 'type' field wouldn't be even necessary if we
template<> struct EventVariant::VariantFor<EventVariant::PACKET>
{
typedef CPacket* type;
static type U::*field() {return &U::packet;}
};
template<> struct EventVariant::VariantFor<EventVariant::ACK>
{
typedef int32_t type;
static type U::*field() { return &U::ack; }
};
template<> struct EventVariant::VariantFor<EventVariant::STAGE>
{
typedef ECheckTimerStage type;
static type U::*field() { return &U::stage; }
};
template<> struct EventVariant::VariantFor<EventVariant::INIT>
{
typedef EInitEvent type;
static type U::*field() { return &U::init; }
};
// Using a hand-crafted solution because there's a non-backward-compatible
// change between C++03 and others on the way up to C++17 (and we want this
// code to be compliant with all C++ standards):
//
// - there's std::mem_fun in C++03 - deprecated in C++11, removed in C++17
// - std::function in C++11 would be perfect, but not in C++03
// This can be changed in future to use C++11 way, but only after C++03
// compatibility is finally abaondoned. Until then, this stays with a custom
// class.
class EventSlotBase
{
public:
virtual void emit(ETransmissionEvent tev, EventVariant var) = 0;
typedef void dispatcher_t(void* opaque, ETransmissionEvent tev, EventVariant var);
virtual ~EventSlotBase() {}
};
class SimpleEventSlot: public EventSlotBase
{
public:
void* opaque;
dispatcher_t* dispatcher;
SimpleEventSlot(void* op, dispatcher_t* disp): opaque(op), dispatcher(disp) {}
void emit(ETransmissionEvent tev, EventVariant var) ATR_OVERRIDE
{
(*dispatcher)(opaque, tev, var);
}
};
template <class Class>
class ObjectEventSlot: public EventSlotBase
{
public:
typedef void (Class::*method_ptr_t)(ETransmissionEvent tev, EventVariant var);
method_ptr_t pm;
Class* po;
ObjectEventSlot(Class* o, method_ptr_t m): pm(m), po(o) {}
void emit(ETransmissionEvent tev, EventVariant var) ATR_OVERRIDE
{
(po->*pm)(tev, var);
}
};
struct EventSlot
{
mutable EventSlotBase* slot;
// Create empty slot. Calls are ignored.
EventSlot(): slot(0) {}
// "Stealing" copy constructor, following the auto_ptr method.
// This isn't very nice, but no other way to do it in C++03
// without rvalue-reference and move.
EventSlot(const EventSlot& victim)
{
slot = victim.slot; // Should MOVE.
victim.slot = 0;
}
EventSlot(void* op, EventSlotBase::dispatcher_t* disp)
{
slot = new SimpleEventSlot(op, disp);
}
template <class ObjectClass>
EventSlot(ObjectClass* obj, typename ObjectEventSlot<ObjectClass>::method_ptr_t method)
{
slot = new ObjectEventSlot<ObjectClass>(obj, method);
}
void emit(ETransmissionEvent tev, EventVariant var)
{
if (!slot)
return;
slot->emit(tev, var);
}
~EventSlot()
{
if (slot)
delete slot;
}
};
// Old UDT library specific classes, moved from utilities as utilities
// should now be general-purpose.
class CTimer
{
public:
CTimer();
~CTimer();
public:
/// Sleep for "interval_tk" CCs.
/// @param [in] interval_tk CCs to sleep.
void sleep(uint64_t interval_tk);
/// Seelp until CC "nexttime_tk".
/// @param [in] nexttime_tk next time the caller is waken up.
void sleepto(uint64_t nexttime_tk);
/// Stop the sleep() or sleepto() methods.
void interrupt();
/// trigger the clock for a tick, for better granuality in no_busy_waiting timer.
void tick();
public:
/// Read the CPU clock cycle into x.
/// @param [out] x to record cpu clock cycles.
static void rdtsc(uint64_t &x);
/// return the CPU frequency.
/// @return CPU frequency.
static uint64_t getCPUFrequency();
/// check the current time, 64bit, in microseconds.
/// @return current time in microseconds.
static uint64_t getTime();
/// trigger an event such as new connection, close, new data, etc. for "select" call.
static void triggerEvent();
enum EWait {WT_EVENT, WT_ERROR, WT_TIMEOUT};
/// wait for an event to br triggered by "triggerEvent".
/// @retval WT_EVENT The event has happened
/// @retval WT_TIMEOUT The event hasn't happened, the function exited due to timeout
/// @retval WT_ERROR The function has exit due to an error
static EWait waitForEvent();
/// sleep for a short interval. exact sleep time does not matter
static void sleep();
/// Wait for condition with timeout
/// @param [in] cond Condition variable to wait for
/// @param [in] mutex locked mutex associated with the condition variable
/// @param [in] delay timeout in microseconds
/// @retval 0 Wait was successfull
/// @retval ETIMEDOUT The wait timed out
static int condTimedWaitUS(pthread_cond_t* cond, pthread_mutex_t* mutex, uint64_t delay);
private:
uint64_t getTimeInMicroSec();
private:
uint64_t m_ullSchedTime_tk; // next schedulled time
pthread_cond_t m_TickCond;
pthread_mutex_t m_TickLock;
static pthread_cond_t m_EventCond;
static pthread_mutex_t m_EventLock;
private:
static uint64_t s_ullCPUFrequency; // CPU frequency : clock cycles per microsecond
static uint64_t readCPUFrequency();
static bool m_bUseMicroSecond; // No higher resolution timer available, use gettimeofday().
};
////////////////////////////////////////////////////////////////////////////////
class CGuard
{
public:
/// Constructs CGuard, which locks the given mutex for
/// the scope where this object exists.
/// @param lock Mutex to lock
/// @param if_condition If this is false, CGuard will do completely nothing
CGuard(pthread_mutex_t& lock, bool if_condition = true);
~CGuard();
public:
static int enterCS(pthread_mutex_t& lock);
static int leaveCS(pthread_mutex_t& lock);
static void createMutex(pthread_mutex_t& lock);
static void releaseMutex(pthread_mutex_t& lock);
static void createCond(pthread_cond_t& cond);
static void releaseCond(pthread_cond_t& cond);
void forceUnlock();
private:
pthread_mutex_t& m_Mutex; // Alias name of the mutex to be protected
int m_iLocked; // Locking status
CGuard& operator=(const CGuard&);
};
class InvertedGuard
{
pthread_mutex_t* m_pMutex;
public:
InvertedGuard(pthread_mutex_t* smutex): m_pMutex(smutex)
{
if ( !smutex )
return;
CGuard::leaveCS(*smutex);
}
~InvertedGuard()
{
if ( !m_pMutex )
return;
CGuard::enterCS(*m_pMutex);
}
};
////////////////////////////////////////////////////////////////////////////////
// UDT Sequence Number 0 - (2^31 - 1)
// seqcmp: compare two seq#, considering the wraping
// seqlen: length from the 1st to the 2nd seq#, including both
// seqoff: offset from the 2nd to the 1st seq#
// incseq: increase the seq# by 1
// decseq: decrease the seq# by 1
// incseq: increase the seq# by a given offset
class CSeqNo
{
public:
/// This behaves like seq1 - seq2, in comparison to numbers,
/// and with the statement that only the sign of the result matters.
/// That is, it returns a negative value if seq1 < seq2,
/// positive if seq1 > seq2, and zero if they are equal.
/// The only correct application of this function is when you
/// compare two values and it works faster than seqoff. However
/// the result's meaning is only in its sign. DO NOT USE THE
/// VALUE for any other purpose. It is not meant to be the
/// distance between two sequence numbers.
///
/// Example: to check if (seq1 %> seq2): seqcmp(seq1, seq2) > 0.
inline static int seqcmp(int32_t seq1, int32_t seq2)
{return (abs(seq1 - seq2) < m_iSeqNoTH) ? (seq1 - seq2) : (seq2 - seq1);}
/// This function measures a length of the range from seq1 to seq2,
/// WITH A PRECONDITION that certainly @a seq1 is earlier than @a seq2.
/// This can also include an enormously large distance between them,
/// that is, exceeding the m_iSeqNoTH value (can be also used to test
/// if this distance is larger). Prior to calling this function the
/// caller must be certain that @a seq2 is a sequence coming from a
/// later time than @a seq1, and still, of course, this distance didn't
/// exceed m_iMaxSeqNo.
inline static int seqlen(int32_t seq1, int32_t seq2)
{return (seq1 <= seq2) ? (seq2 - seq1 + 1) : (seq2 - seq1 + m_iMaxSeqNo + 2);}
/// This behaves like seq2 - seq1, with the precondition that the true
/// distance between two sequence numbers never exceeds m_iSeqNoTH.
/// That is, if the difference in numeric values of these two arguments
/// exceeds m_iSeqNoTH, it is treated as if the later of these two
/// sequence numbers has overflown and actually a segment of the
/// MAX+1 value should be added to it to get the proper result.
///
/// Note: this function does more calculations than seqcmp, so it should
/// be used if you need the exact distance between two sequences. If
/// you are only interested with their relationship, use seqcmp.
inline static int seqoff(int32_t seq1, int32_t seq2)
{
if (abs(seq1 - seq2) < m_iSeqNoTH)
return seq2 - seq1;
if (seq1 < seq2)
return seq2 - seq1 - m_iMaxSeqNo - 1;
return seq2 - seq1 + m_iMaxSeqNo + 1;
}
inline static int32_t incseq(int32_t seq)
{return (seq == m_iMaxSeqNo) ? 0 : seq + 1;}
inline static int32_t decseq(int32_t seq)
{return (seq == 0) ? m_iMaxSeqNo : seq - 1;}
inline static int32_t incseq(int32_t seq, int32_t inc)
{return (m_iMaxSeqNo - seq >= inc) ? seq + inc : seq - m_iMaxSeqNo + inc - 1;}
// m_iMaxSeqNo >= inc + sec --- inc + sec <= m_iMaxSeqNo
// if inc + sec > m_iMaxSeqNo then return seq + inc - (m_iMaxSeqNo+1)
inline static int32_t decseq(int32_t seq, int32_t dec)
{
// Check if seq - dec < 0, but before it would have happened
if ( seq < dec )
{
int32_t left = dec - seq; // This is so many that is left after dragging dec to 0
// So now decrement the (m_iMaxSeqNo+1) by "left"
return m_iMaxSeqNo - left + 1;
}
return seq - dec;
}
public:
static const int32_t m_iSeqNoTH = 0x3FFFFFFF; // threshold for comparing seq. no.
static const int32_t m_iMaxSeqNo = 0x7FFFFFFF; // maximum sequence number used in UDT
};
////////////////////////////////////////////////////////////////////////////////
// UDT ACK Sub-sequence Number: 0 - (2^31 - 1)
class CAckNo
{
public:
inline static int32_t incack(int32_t ackno)
{return (ackno == m_iMaxAckSeqNo) ? 0 : ackno + 1;}
public:
static const int32_t m_iMaxAckSeqNo = 0x7FFFFFFF; // maximum ACK sub-sequence number used in UDT
};
////////////////////////////////////////////////////////////////////////////////
struct CIPAddress
{
static bool ipcmp(const struct sockaddr* addr1, const struct sockaddr* addr2, int ver = AF_INET);
static void ntop(const struct sockaddr* addr, uint32_t ip[4], int ver = AF_INET);
static void pton(struct sockaddr* addr, const uint32_t ip[4], int ver = AF_INET);
static std::string show(const struct sockaddr* adr);
};
////////////////////////////////////////////////////////////////////////////////
struct CMD5
{
static void compute(const char* input, unsigned char result[16]);
};
// Debug stats
template <size_t SIZE>
class StatsLossRecords
{
int32_t initseq;
std::bitset<SIZE> array;
public:
StatsLossRecords(): initseq(-1) {}
// To check if this structure still keeps record of that sequence.
// This is to check if the information about this not being found
// is still reliable.
bool exists(int32_t seq)
{
return initseq != -1 && CSeqNo::seqcmp(seq, initseq) >= 0;
}
int32_t base() { return initseq; }
void clear()
{
initseq = -1;
array.reset();
}
void add(int32_t lo, int32_t hi)
{
int32_t end = CSeqNo::incseq(hi);
for (int32_t i = lo; i != end; i = CSeqNo::incseq(i))
add(i);
}
void add(int32_t seq)
{
if ( array.none() )
{
// May happen it wasn't initialized. Set it as initial loss sequence.
initseq = seq;
array[0] = true;
return;
}
// Calculate the distance between this seq and the oldest one.
int seqdiff = CSeqNo::seqoff(initseq, seq);
if ( seqdiff > int(SIZE) )
{
// Size exceeded. Drop the oldest sequences.
// First calculate how many must be removed.
size_t toremove = seqdiff - SIZE;
// Now, since that position, find the nearest 1
while ( !array[toremove] && toremove <= SIZE )
++toremove;
// All have to be dropped, so simply reset the array
if ( toremove == SIZE )
{
initseq = seq;
array[0] = true;
return;
}
// Now do the shift of the first found 1 to position 0
// and its index add to initseq
initseq += toremove;
seqdiff -= toremove;
array >>= toremove;
}
// Now set appropriate bit that represents this seq
array[seqdiff] = true;
}
StatsLossRecords& operator << (int32_t seq)
{
add(seq);
return *this;
}
void remove(int32_t seq)
{
// Check if is in range. If not, ignore.
int seqdiff = CSeqNo::seqoff(initseq, seq);
if ( seqdiff < 0 )
return; // already out of array
if ( seqdiff > SIZE )
return; // never was added!
array[seqdiff] = true;
}
bool find(int32_t seq) const
{
int seqdiff = CSeqNo::seqoff(initseq, seq);
if ( seqdiff < 0 )
return false; // already out of array
if ( size_t(seqdiff) > SIZE )
return false; // never was added!
return array[seqdiff];
}
#if HAVE_CXX11
std::string to_string() const
{
std::string out;
for (size_t i = 0; i < SIZE; ++i)
{
if ( array[i] )
out += std::to_string(initseq+i) + " ";
}
return out;
}
#endif
};
// Version parsing
inline ATR_CONSTEXPR uint32_t SrtVersion(int major, int minor, int patch)
{
return patch + minor*0x100 + major*0x10000;
}
inline int32_t SrtParseVersion(const char* v)
{
int major, minor, patch;
int result = sscanf(v, "%d.%d.%d", &major, &minor, &patch);
if (result != 3)
{
return 0;
}
return major*0x10000 + minor*0x100 + patch;
}
inline std::string SrtVersionString(int version)
{
int patch = version % 0x100;
int minor = (version/0x100)%0x100;
int major = version/0x10000;
char buf[20];
sprintf(buf, "%d.%d.%d", major, minor, patch);
return buf;
}
#endif
| 30.877791 | 137 | 0.644404 | [
"object"
] |
95d9bd3b032ddf8ad455a4e72db2418577506f99 | 5,768 | h | C | DriveFusion/DriveItemRelatedItem.h | JadeTheFlame/google-drive-shell-extension | 917ada8e1a173e43e637db980ac4b9976a34acf9 | [
"Apache-2.0"
] | 155 | 2015-03-25T22:09:37.000Z | 2022-03-07T14:51:31.000Z | DriveFusion/DriveItemRelatedItem.h | Jason-Cooke/google-drive-shell-extension | 917ada8e1a173e43e637db980ac4b9976a34acf9 | [
"Apache-2.0"
] | 13 | 2015-04-01T17:51:45.000Z | 2021-08-21T13:36:39.000Z | DriveFusion/DriveItemRelatedItem.h | Jason-Cooke/google-drive-shell-extension | 917ada8e1a173e43e637db980ac4b9976a34acf9 | [
"Apache-2.0"
] | 73 | 2015-03-26T02:21:54.000Z | 2022-03-26T10:22:46.000Z | /*
Copyright 2014 Google Inc
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include "stdafx.h"
#include "GDriveShlExt.h"
#include <map>
#include "FusionGDShell_i.h"
#if defined(_WIN32_WCE) && !defined(_CE_DCOM) && !defined(_CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA)
#error "Single-threaded COM objects are not properly supported on Windows CE platform, such as the Windows Mobile platforms that do not include full DCOM support. Define _CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA to force ATL to support creating single-thread COM object's and allow use of it's single-threaded COM object implementations. The threading model in your rgs file was set to 'Free' as that is the only threading model supported in non DCOM Windows CE platforms."
#endif
using namespace ATL;
class ATL_NO_VTABLE CDriveItemRelatedItem :
public CComObjectRootEx<CComSingleThreadModel>,
public CComCoClass<CDriveItemRelatedItem, &CLSID_DriveItemRelatedItem>,
public IIdentityName,
public ITransferMediumItem,
public IPreviewItem,
public ICurrentItem,
public IDisplayItem,
public IViewStateIdentityItem,
public ITransferDestination,
public ITransferSource,
public IShellItemResources
{
public:
CDriveItemRelatedItem()
{
Log::WriteOutput(LogType::Debug, L"CDriveItemRelatedItem::CDriveItemRelatedItem()");
_gDriveShlExt = NULL;
}
BEGIN_COM_MAP(CDriveItemRelatedItem)
COM_INTERFACE_ENTRY2(IRelatedItem, IIdentityName)
COM_INTERFACE_ENTRY(IIdentityName)
COM_INTERFACE_ENTRY(ITransferMediumItem)
COM_INTERFACE_ENTRY(IPreviewItem)
COM_INTERFACE_ENTRY(ICurrentItem)
COM_INTERFACE_ENTRY(IDisplayItem)
COM_INTERFACE_ENTRY(IViewStateIdentityItem)
COM_INTERFACE_ENTRY(ITransferDestination)
COM_INTERFACE_ENTRY(ITransferSource)
COM_INTERFACE_ENTRY(IShellItemResources)
END_COM_MAP()
DECLARE_PROTECT_FINAL_CONSTRUCT()
static HRESULT CreateInstanceReturnInterfaceTo(CGDriveShlExt* gDriveShlExt, REFIID riid, __deref_out void **ppv);
HRESULT FinalConstruct()
{
return S_OK;
}
void FinalRelease();
// IRelatedItem
IFACEMETHODIMP GetItem(__RPC__deref_out_opt IShellItem **ppsi);
IFACEMETHODIMP GetItemIDList(__RPC__deref_out_opt PIDLIST_ABSOLUTE *ppidl);
// ITransferDestination and ITransferSource
IFACEMETHODIMP Advise(__in ITransferAdviseSink *psink, __out DWORD *pdwCookie) ;
IFACEMETHODIMP Unadvise(DWORD dwCookie);
IFACEMETHODIMP CreateItem(__in LPCWSTR pszName, __in DWORD dwAttributes, __in ULONGLONG ullSize, __in TRANSFER_SOURCE_FLAGS flags, __in REFIID riidItem, __deref_out void **ppvItem, __in REFIID riidResources, __deref_out void **ppvResources);
IFACEMETHODIMP SetProperties(__in IPropertyChangeArray *pproparray);
IFACEMETHODIMP OpenItem(__in IShellItem *psi, __in TRANSFER_SOURCE_FLAGS flags, __in REFIID riid, __deref_out void **ppv);
IFACEMETHODIMP MoveItem(__in IShellItem *psi, __in IShellItem *psiParentDst, __in LPCWSTR pszNameDst, __in TRANSFER_SOURCE_FLAGS flags, __deref_out IShellItem **ppsiNew);
IFACEMETHODIMP RecycleItem(__in IShellItem *psiSource, __in IShellItem *psiParentDest, __in TRANSFER_SOURCE_FLAGS flags, __deref_out IShellItem **ppsiNewDest);
IFACEMETHODIMP RemoveItem(__in IShellItem *psiSource, __in TRANSFER_SOURCE_FLAGS flags);
IFACEMETHODIMP RenameItem(__in IShellItem *psiSource, __in LPCWSTR pszNewName, __in TRANSFER_SOURCE_FLAGS flags, __deref_out IShellItem **ppsiNewDest);
IFACEMETHODIMP LinkItem(__in IShellItem *psiSource, __in IShellItem *psiParentDest, __in_opt LPCWSTR pszNewName, __in TRANSFER_SOURCE_FLAGS flags, __deref_out IShellItem **ppsiNewDest);
IFACEMETHODIMP ApplyPropertiesToItem(__in IShellItem *psiSource, __deref_out IShellItem **ppsiNew);
IFACEMETHODIMP GetDefaultDestinationName(__in IShellItem *psiSource, __in IShellItem *psiParentDest, __deref_out LPWSTR *ppszDestinationName);
IFACEMETHODIMP EnterFolder(__in IShellItem *psiChildFolderDest);
IFACEMETHODIMP LeaveFolder(__in IShellItem *psiChildFolderDest);
// IShellItemResources
IFACEMETHODIMP GetAttributes(__RPC__out DWORD *pdwAttributes);
IFACEMETHODIMP GetSize(__RPC__out ULONGLONG *pullSize);
IFACEMETHODIMP GetTimes(__RPC__out FILETIME *pftCreation, __RPC__out FILETIME *pftWrite, __RPC__out FILETIME *pftAccess);
IFACEMETHODIMP SetTimes(__RPC__in_opt const FILETIME *pftCreation, __RPC__in_opt const FILETIME *pftWrite, __RPC__in_opt const FILETIME *pftAccess);
IFACEMETHODIMP GetResourceDescription(__RPC__in const SHELL_ITEM_RESOURCE *pcsir, __RPC__deref_out_opt_string LPWSTR *ppszDescription);
IFACEMETHODIMP EnumResources(__RPC__deref_out_opt IEnumResources **ppenumr);
IFACEMETHODIMP SupportsResource(__RPC__in const SHELL_ITEM_RESOURCE *pcsir);
IFACEMETHODIMP OpenResource(__RPC__in const SHELL_ITEM_RESOURCE *pcsir, __RPC__in REFIID riid, __RPC__deref_out_opt void **ppv);
IFACEMETHODIMP CreateResource(__RPC__in const SHELL_ITEM_RESOURCE *pcsir, __RPC__in REFIID riid, __RPC__deref_out_opt void **ppv);
IFACEMETHODIMP MarkForDelete(void);
private:
HRESULT _Initialize(CGDriveShlExt* gDriveShlExt);
private:
CGDriveShlExt* _gDriveShlExt;
typedef std::map<DWORD, ITransferAdviseSink*> AdviseSinkMap;
AdviseSinkMap _sinkMap;
static DWORD _nextCookie;
};
| 49.299145 | 472 | 0.81432 | [
"object",
"model"
] |
95e9d4c4d8545597426aa8456b0f668335335d05 | 13,523 | h | C | printemps/model_component/constraint_proxy.h | snowberryfield/printemps | 53f14da11bfddc90a561be08f6bd73cf7df7399c | [
"MIT"
] | 16 | 2020-12-07T03:47:54.000Z | 2022-03-16T02:14:48.000Z | printemps/model_component/constraint_proxy.h | snowberryfield/printemps | 53f14da11bfddc90a561be08f6bd73cf7df7399c | [
"MIT"
] | 7 | 2020-05-03T06:14:32.000Z | 2020-08-16T08:56:04.000Z | printemps/model_component/constraint_proxy.h | snowberryfield/printemps | 53f14da11bfddc90a561be08f6bd73cf7df7399c | [
"MIT"
] | null | null | null | /*****************************************************************************/
// Copyright (c) 2020-2021 Yuji KOGUMA
// Released under the MIT license
// https://opensource.org/licenses/mit-license.php
/*****************************************************************************/
#ifndef PRINTEMPS_MODEL_COMPONENT_CONSTRAINT_PROXY_H__
#define PRINTEMPS_MODEL_COMPONENT_CONSTRAINT_PROXY_H__
#include "constraint.h"
namespace printemps {
namespace model_component {
/*****************************************************************************/
template <class T_Variable, class T_Expression>
class ConstraintProxy : public multi_array::AbstractMultiArray {
/**
* [Access controls for special member functions]
* -- Default constructor : default, private
* -- Copy constructor : default, private
* -- Copy assignment : delete, (private)
* -- Move constructor : default, public
* -- Move assignment : default, public
*/
private:
std::vector<Constraint<T_Variable, T_Expression>> m_constraints;
/*************************************************************************/
/// Default constructor
ConstraintProxy(void) {
/* nothing to do*/
}
/*************************************************************************/
/// Copy constructor
ConstraintProxy(const ConstraintProxy<T_Variable, T_Expression> &) =
default;
/*************************************************************************/
/// Copy assignment
ConstraintProxy<T_Variable, T_Expression> &operator =(
const ConstraintProxy<T_Variable, T_Expression> &) = delete;
/*************************************************************************/
ConstraintProxy(const int a_ID) : multi_array::AbstractMultiArray(a_ID) {
this->setup_constraints();
}
/*************************************************************************/
ConstraintProxy(const int a_ID, const int a_NUMBER_OF_ELEMENTS)
: multi_array::AbstractMultiArray(a_ID, a_NUMBER_OF_ELEMENTS) {
this->setup_constraints();
}
/*************************************************************************/
ConstraintProxy(int a_ID, const std::vector<int> &a_SHAPE)
: multi_array::AbstractMultiArray(a_ID, a_SHAPE) {
this->setup_constraints();
}
/*************************************************************************/
void setup_constraints(void) {
/**
* m_constraints.resize(this->number_of_elements()) does not work
* because default constructor of Expression class are deleted. for
* reference:
* https://cpprefjp.github.io/reference/vector/vector/resize.html
*/
m_constraints.reserve(this->number_of_elements());
for (auto i = 0; i < this->number_of_elements(); i++) {
m_constraints.emplace_back(
Constraint<T_Variable, T_Expression>::create_instance());
}
int flat_index = 0;
std::vector<int> multi_dimensional_index(this->number_of_dimensions());
for (auto &&constraint : m_constraints) {
constraint.set_proxy_index(m_index);
constraint.set_flat_index(flat_index);
this->update_multi_dimensional_index(&multi_dimensional_index,
flat_index);
constraint.set_multi_dimensional_index(multi_dimensional_index);
flat_index++;
}
}
public:
/*************************************************************************/
/// Move constructor
ConstraintProxy(ConstraintProxy<T_Variable, T_Expression> &&) = default;
/*************************************************************************/
/// Move assignment
ConstraintProxy<T_Variable, T_Expression> &operator=(
ConstraintProxy<T_Variable, T_Expression> &&) = default;
/*************************************************************************/
inline static constexpr ConstraintProxy<T_Variable, T_Expression>
create_instance(const int a_ID) {
/**
* When instantiation, instead of constructor, create_instance() should
* be called.
*/
ConstraintProxy<T_Variable, T_Expression> proxy(a_ID);
return proxy;
}
/*************************************************************************/
inline static constexpr ConstraintProxy<T_Variable, T_Expression>
create_instance(const int a_ID, const int a_NUMBER_OF_ELEMENTS) {
/**
* When instantiation, instead of constructor, create_instance() should
* be called.
*/
ConstraintProxy<T_Variable, T_Expression> proxy(a_ID,
a_NUMBER_OF_ELEMENTS);
return proxy;
}
/*************************************************************************/
inline static constexpr ConstraintProxy<T_Variable, T_Expression>
create_instance(const int a_ID, const std::vector<int> &a_SHAPE) {
/**
* When instantiation, instead of constructor, create_instance() should
* be called.
*/
ConstraintProxy<T_Variable, T_Expression> proxy(a_ID, a_SHAPE);
return proxy;
}
/*************************************************************************/
inline constexpr void set_name(const std::string &a_NAME) {
if (this->number_of_elements() != 1) {
throw std::logic_error(utility::format_error_location(
__FILE__, __LINE__, __func__,
"The number of elements is not one."));
}
m_constraints[0].set_name(a_NAME);
}
/*************************************************************************/
inline constexpr const std::string &name(void) const {
if (this->number_of_elements() != 1) {
throw std::logic_error(utility::format_error_location(
__FILE__, __LINE__, __func__,
"The number of elements is not one."));
}
return m_constraints[0].name();
}
/*************************************************************************/
inline constexpr std::vector<Constraint<T_Variable, T_Expression>>
&flat_indexed_constraints(void) {
return m_constraints;
}
/*************************************************************************/
inline constexpr const std::vector<Constraint<T_Variable, T_Expression>>
&flat_indexed_constraints(void) const {
return m_constraints;
}
/*************************************************************************/
inline constexpr Constraint<T_Variable, T_Expression>
&flat_indexed_constraints(const int a_FLAT_INDEX) {
return m_constraints[a_FLAT_INDEX];
}
/*************************************************************************/
inline constexpr const Constraint<T_Variable, T_Expression>
&flat_indexed_constraints(const int a_FLAT_INDEX) const {
return m_constraints[a_FLAT_INDEX];
}
/*************************************************************************/
inline constexpr T_Expression constraint_value(void) const {
if (this->number_of_elements() != 1) {
throw std::logic_error(utility::format_error_location(
__FILE__, __LINE__, __func__,
"The number of elements is not one."));
}
return m_constraints[0].constraint_value();
}
/*************************************************************************/
inline constexpr T_Expression violation_value(void) const {
if (this->number_of_elements() != 1) {
throw std::logic_error(utility::format_error_location(
__FILE__, __LINE__, __func__,
"The number of elements is not one."));
}
return m_constraints[0].violation_value();
}
/*************************************************************************/
inline constexpr multi_array::ValueProxy<T_Expression>
export_values_and_names(void) const {
multi_array::ValueProxy<T_Expression> proxy(m_index, m_shape);
int number_of_elements = this->number_of_elements();
for (auto i = 0; i < number_of_elements; i++) {
proxy.flat_indexed_values()[i] =
m_constraints[i].constraint_value();
proxy.flat_indexed_names()[i] = m_constraints[i].name();
}
return proxy;
}
/*************************************************************************/
inline constexpr multi_array::ValueProxy<T_Expression>
export_violations_and_names(void) const {
multi_array::ValueProxy<T_Expression> proxy(m_index, m_shape);
int number_of_elements = this->number_of_elements();
for (auto i = 0; i < number_of_elements; i++) {
proxy.flat_indexed_values()[i] = m_constraints[i].violation_value();
proxy.flat_indexed_names()[i] = m_constraints[i].name();
}
return proxy;
}
/*************************************************************************/
inline constexpr bool is_enabled(void) const {
if (this->number_of_elements() != 1) {
throw std::logic_error(utility::format_error_location(
__FILE__, __LINE__, __func__,
"The number of elements is not one."));
}
return m_constraints[0].is_enabled();
}
/*************************************************************************/
inline constexpr void enable(void) {
/// This method enables all expressions simultaneously.
for (auto &&constraint : m_constraints) {
constraint.enable();
}
}
/*************************************************************************/
inline constexpr void disable(void) {
/// This method disables all expressions simultaneously.
for (auto &&constraint : m_constraints) {
constraint.disable();
}
}
/*************************************************************************/
inline constexpr Constraint<T_Variable, T_Expression> &operator[](
int a_FLAT_INDEX) {
return m_constraints[a_FLAT_INDEX];
}
/*************************************************************************/
inline constexpr const Constraint<T_Variable, T_Expression> &operator[](
int a_FLAT_INDEX) const {
return m_constraints[a_FLAT_INDEX];
}
/*************************************************************************/
inline constexpr Constraint<T_Variable, T_Expression> &operator()(
const std::vector<int> &a_MULTI_DIMENSIONAL_INDEX) {
const int MULTI_DIMENSIONAL_INDEX_SIZE =
a_MULTI_DIMENSIONAL_INDEX.size();
if (this->number_of_dimensions() != MULTI_DIMENSIONAL_INDEX_SIZE) {
throw std::logic_error(utility::format_error_location(
__FILE__, __LINE__, __func__,
"The number of dimensions does not match."));
}
auto flat_index = std::inner_product(a_MULTI_DIMENSIONAL_INDEX.begin(),
a_MULTI_DIMENSIONAL_INDEX.end(),
m_strides.begin(), 0);
return m_constraints[flat_index];
}
/*************************************************************************/
inline constexpr const Constraint<T_Variable, T_Expression> &operator()(
const std::vector<int> &a_MULTI_DIMENSIONAL_INDEX) const {
if (this->number_of_dimensions() != a_MULTI_DIMENSIONAL_INDEX.size()) {
throw std::logic_error(utility::format_error_location(
__FILE__, __LINE__, __func__,
"The number of dimensions does not match."));
}
auto flat_index = std::inner_product(a_MULTI_DIMENSIONAL_INDEX.begin(),
a_MULTI_DIMENSIONAL_INDEX.end(),
m_strides.begin(), 0);
return m_constraints[flat_index];
}
/*************************************************************************/
template <class... Args>
inline constexpr Constraint<T_Variable, T_Expression> &operator()(
Args... args) {
return this->operator()({args...});
}
/*************************************************************************/
template <class... Args>
inline constexpr const Constraint<T_Variable, T_Expression> &operator()(
Args... args) const {
return this->operator()({args...});
}
/*************************************************************************/
inline constexpr ConstraintProxy<T_Variable, T_Expression> &operator=(
const Constraint<T_Variable, T_Expression> &a_CONSTRAINT) {
if (this->number_of_elements() != 1) {
throw std::logic_error(utility::format_error_location(
__FILE__, __LINE__, __func__,
"The number of elements is not one."));
}
m_constraints[0] = a_CONSTRAINT;
return *this;
}
};
using IPConstraintProxy = ConstraintProxy<int, double>;
} // namespace model_component
} // namespace printemps
#endif
/*****************************************************************************/
// END
/*****************************************************************************/ | 41.35474 | 80 | 0.492198 | [
"vector"
] |
2538903b39d2bef2372b6c3d7106b120a6f102e3 | 1,110 | h | C | Rendering_Geometry/include/RenderingGeometryApp.h | JeffreyMJohnson/Graphics | fed524574c11281a2f0afe21ac6cc9d521930951 | [
"MIT"
] | null | null | null | Rendering_Geometry/include/RenderingGeometryApp.h | JeffreyMJohnson/Graphics | fed524574c11281a2f0afe21ac6cc9d521930951 | [
"MIT"
] | null | null | null | Rendering_Geometry/include/RenderingGeometryApp.h | JeffreyMJohnson/Graphics | fed524574c11281a2f0afe21ac6cc9d521930951 | [
"MIT"
] | null | null | null | #pragma once
#include "GameApp.h"
#include "FlyCamera.h"
#include "Keyboard.h"
#include "Shader.h"
using glm::vec3;
using glm::vec4;
using glm::mat4;
typedef unsigned int uint;
struct Vertex
{
vec4 position;
vec4 color;
};
class RenderingGeometryApp : public GameApp
{
public:
const int WINDOW_WIDTH = 1280;
const int WINDOW_HEIGHT = 720;
const char* WINDOW_TITLE = "Rendering Geometry";
const vec4 CLEAR_COLOR = vec4(.25f, .25f, .25f, 1);
const float CAMERA_FOV = glm::pi<float>() * .25f;
const float CAMERA_NEAR = .1f;
const float CAMERA_FAR = 1000.0f;
const vec3 CAMERA_FROM = vec3(10, 10, 10);
const vec3 CAMERA_TO = vec3(0);
const vec3 CAMERA_UP = vec3(0, 1, 0);
const bool DEBUG_MODE = true;
bool StartUp();
void ShutDown();
bool Update();
void Draw();
private:
Shader* mShader = new Shader();
FlyCamera* mCamera = nullptr;
uint mVAO = 0;
uint mVBO = 0;
uint mIBO = 0;
const uint ROWS = 25;
const uint COLS = 25;
void InitCamera();
void GenerateGrid(uint rows, uint cols);
void LoadGLBuffer(Vertex* vertices, uint verticesSize, uint* indeces, uint indecesCount);
};
| 20.181818 | 90 | 0.701802 | [
"geometry"
] |
253ae7a14020fae1a82c942b8dff05199c889872 | 783 | h | C | app42/libs/Shephertz_App42_iOS_API.framework/Versions/Current/Headers/PushNotification.h | saqsun/robovm-ios-bindings | dae85f2e573dbbc0973e40a730a22ce356f6a3c1 | [
"Apache-2.0"
] | 90 | 2015-01-01T21:20:50.000Z | 2021-12-28T00:52:27.000Z | app42/libs/Shephertz_App42_iOS_API.framework/Versions/Current/Headers/PushNotification.h | saqsun/robovm-ios-bindings | dae85f2e573dbbc0973e40a730a22ce356f6a3c1 | [
"Apache-2.0"
] | 68 | 2015-01-02T00:22:36.000Z | 2017-02-14T23:49:46.000Z | app42/libs/Shephertz_App42_iOS_API.framework/Versions/Current/Headers/PushNotification.h | saqsun/robovm-ios-bindings | dae85f2e573dbbc0973e40a730a22ce356f6a3c1 | [
"Apache-2.0"
] | 65 | 2015-01-11T23:53:12.000Z | 2021-11-08T06:25:36.000Z | //
// PushNotification.h
// PAE_iOS_SDK
//
// Created by shephertz technologies on 20/06/12.
// Copyright (c) 2012 ShephertzTechnology PVT LTD. All rights reserved.
//
#import "App42Response.h"
/**
*PushNotification class contain the member variables and allowed to be set and get.
*
*/
@interface PushNotification : App42Response
{
NSMutableArray *channelList;
}
/*!
*set and get the fileListArray for Upload Object where fileListArray contain the File Object
*/
@property(nonatomic,retain)NSMutableArray *channelList;
@property(nonatomic,retain)NSString *message;
@property(nonatomic,retain)NSString *userName;
@property(nonatomic,retain)NSString *expiry;
@property(nonatomic,retain)NSString *type;
@property(nonatomic,retain)NSString *deviceToken;
@end
| 21.75 | 93 | 0.758621 | [
"object"
] |
d7a3f800bbfc4e939fae598f4af9a6b64f4438ee | 11,336 | h | C | source/ti/drivers/uart2/UART2CC26X2.h | nbrunner/coresdk_cc13xx_cc26xx | 5d8afb2241f7b79f4e830278cc04df7a1853a18e | [
"BSD-3-Clause"
] | null | null | null | source/ti/drivers/uart2/UART2CC26X2.h | nbrunner/coresdk_cc13xx_cc26xx | 5d8afb2241f7b79f4e830278cc04df7a1853a18e | [
"BSD-3-Clause"
] | null | null | null | source/ti/drivers/uart2/UART2CC26X2.h | nbrunner/coresdk_cc13xx_cc26xx | 5d8afb2241f7b79f4e830278cc04df7a1853a18e | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2019, Texas Instruments Incorporated
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Texas Instruments Incorporated 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 UART2CC26X2.h
*
* @brief UART driver implementation for a CC26X2 UART controller
*
* The UART header file should be included in an application as follows:
* @code
* #include <ti/drivers/UART2.h>
* #include <ti/drivers/uart2/UART2CC26X2.h>
* @endcode
*
* Refer to @ref UART2.h for a complete description of APIs and examples
* of use.
*
* ============================================================================
*/
#ifndef ti_drivers_uart2_UART2CC26X2__include
#define ti_drivers_uart2_UART2CC26X2__include
#include <stddef.h>
#include <stdint.h>
#include <stdint.h>
#include <stdbool.h>
#include <ti/devices/DeviceFamily.h>
#include DeviceFamily_constructPath(inc/hw_types.h)
#include DeviceFamily_constructPath(driverlib/udma.h)
#include <ti/drivers/dpl/HwiP.h>
#include <ti/drivers/dpl/SemaphoreP.h>
#include <ti/drivers/UART2.h>
#include <ti/drivers/pin/PINCC26XX.h>
#include <ti/drivers/dma/UDMACC26XX.h>
#ifdef __cplusplus
extern "C" {
#endif
/*!
* @brief No hardware flow control
*/
#define UART2CC26X2_FLOWCTRL_NONE 0
/*!
* @brief Hardware flow control
*/
#define UART2CC26X2_FLOWCTRL_HARDWARE 1
/*! Size of the TX and RX FIFOs is 32 items */
#define UART2CC26X2_FIFO_SIZE 32
/*!
* @brief UART TX/RX interrupt FIFO threshold select
*
* Defined FIFO thresholds for generation of both TX interrupt and RX
* interrupt. If the RX and TX FIFO and thresholds are not set in the
* HwAttrs, the RX interrupt FIFO threshold is set to 1/8 full, and the
* TX interrupt FIFO threshold is set to 1/8 full.
*/
typedef enum UART2CC26X2_FifoThreshold {
UART2CC26X2_FIFO_THRESHOLD_1_8 = 0, /*!< FIFO threshold of 1/8 full */
UART2CC26X2_FIFO_THRESHOLD_2_8 = 1, /*!< FIFO threshold of 2/8 full */
UART2CC26X2_FIFO_THRESHOLD_4_8 = 2, /*!< FIFO threshold of 4/8 full */
UART2CC26X2_FIFO_THRESHOLD_6_8 = 3, /*!< FIFO threshold of 6/8 full */
UART2CC26X2_FIFO_THRESHOLD_7_8 = 4 /*!< FIFO threshold of 7/8 full */
} UART2CC26X2_FifoThreshold;
/* UART2CC26X2 functions */
extern void UART2CC26X2_close(UART2_Handle handle);
extern void UART2CC26X2_disableRx(UART2_Handle handle);
extern UART2_Handle UART2CC26X2_open(uint_least8_t, UART2_Params *params);
extern int_fast16_t UART2CC26X2_read(UART2_Handle handle, void *buffer, size_t size,
size_t *bytesRead);
extern void UART2CC26X2_readCancel(UART2_Handle handle);
extern int_fast16_t UART2CC26X2_write(UART2_Handle handle, const void *buffer,
size_t size, size_t *bytesWritten);
extern void UART2CC26X2_writeCancel(UART2_Handle handle);
extern void UART2CC26X2_flushRx(UART2_Handle handle);
extern void UART2CC26X2_getParams(UART2_Handle handle, UART2_Params *params);
extern void UART2CC26X2_setParams(UART2_Handle handle, UART2_Params *params);
/* UART2 function table pointer */
extern const UART2_FxnTable UART2CC26X2_fxnTable;
/*!
* @brief UART2CC26X2 Hardware attributes
*
* The fields, baseAddr and intNum are used by driverlib
* APIs and therefore must be populated by
* driverlib macro definitions. These definitions are found under the
* device family in:
* - inc/hw_memmap.h
* - inc/hw_ints.h
* - driverlib/uart.h
*
* intPriority is the UART peripheral's interrupt priority, as defined by the
* underlying OS. It is passed unmodified to the underlying OS's interrupt
* handler creation code, so you need to refer to the OS documentation
* for usage. For example, for SYS/BIOS applications, refer to the
* ti.sysbios.family.arm.m3.Hwi documentation for SYS/BIOS usage of
* interrupt priorities. If the driver uses the ti.dpl interface
* instead of making OS calls directly, then the HwiP port handles the
* interrupt priority in an OS specific way. In the case of the SYS/BIOS
* port, intPriority is passed unmodified to Hwi_create().
* The CC26x2 uses three of the priority bits, meaning ~0 has the same
* effect as (7 << 5).
*
* (7 << 5) will apply the lowest priority.
* (1 << 5) will apply the highest priority.
*
* Setting the priority to 0 is not supported by this driver. HWI's with
* priority 0 ignore the HWI dispatcher to support zero-latency interrupts,
* thus invalidating the critical sections in this driver.
*
* A sample structure is shown below:
* @code
* const UART2CC26X2_HWAttrs uartCC26X2HWAttrs[] = {
* {
* .baseAddr = UARTA0_BASE,
* .intNum = INT_UART0_COMB,
* .intPriority = (~0),
* .swiPriority = 0,
* .flowControl = UART2CC26X2_FLOWCTRL_NONE,
* .rxPin = IOID_2,
* .txPin = IOID_3,
* .ctsPin = PIN_UNASSIGNED,
* .rtsPin = PIN_UNASSIGNED,
* .txIntFifoThr = UART2CC26X2_FIFO_THRESHOLD_1_8,
* .rxIntFifoThr = UART2CC26X2_FIFO_THRESHOLD_4_8,
* },
* {
* .baseAddr = UART1_BASE,
* .intNum = INT_UART1_COMB,
* .intPriority = (~0),
* .swiPriority = 0,
* .flowControl = UART2CC26X2_FLOWCTRL_NONE,
* .rxPin = PIN_UNASSIGNED,
* .txPin = PIN_UNASSIGNED,
* .ctsPin = PIN_UNASSIGNED,
* .rtsPin = PIN_UNASSIGNED,
* .txIntFifoThr = UART2CC26X2_FIFO_THRESHOLD_1_8,
* .rxIntFifoThr = UART2CC26X2_FIFO_THRESHOLD_4_8,
* },
* };
* @endcode
*
* The .ctsPin and .rtsPin must be assigned to enable flow control.
*/
typedef struct UART2CC26X2_HWAttrs {
/*! UART Peripheral's base address */
uint32_t baseAddr;
/*! UART Peripheral's interrupt vector */
int intNum;
/*! UART Peripheral's interrupt priority */
uint8_t intPriority;
/*! Hardware flow control setting */
uint32_t flowControl;
/*! UART RX pin assignment */
uint8_t rxPin;
/*! UART TX pin assignment */
uint8_t txPin;
/*! UART clear to send (CTS) pin assignment */
uint8_t ctsPin;
/*! UART request to send (RTS) pin assignment */
uint8_t rtsPin;
/*! UDMA channel number for RX data */
uint32_t rxChannelMask;
/*! UDMA channel number for TX data */
uint32_t txChannelMask;
/*! UART TX interrupt FIFO threshold select */
UART2CC26X2_FifoThreshold txIntFifoThr;
/*! UART RX interrupt FIFO threshold select */
UART2CC26X2_FifoThreshold rxIntFifoThr;
} UART2CC26X2_HWAttrs;
/*!
* @brief UART2CC26X2 Object
*
* The application must not access any member variables of this structure!
*/
typedef struct UART2CC26X2_Object {
/* UART2 state variable */
struct {
bool opened:1; /* Has the obj been opened */
UART2_Mode readMode; /* Mode for read calls */
UART2_Mode writeMode; /* Mode for write calls */
UART2_ReadReturnMode readReturnMode:1; /* RX return mode (partial/full) */
/* Flag to indicate ongoing transmit */
bool txEnabled:1;
} state;
HwiP_Struct hwi; /* Hwi object for interrupts */
uint32_t baudRate; /* Baud rate for UART */
UART2_DataLen dataLength; /* Data length for UART */
UART2_StopBits stopBits; /* Stop bits for UART */
UART2_Parity parityType; /* Parity bit type for UART */
int32_t rxStatus; /* RX status */
int32_t txStatus; /* TX status */
void *userArg; /* User supplied arg for callbacks */
UDMACC26XX_Handle udmaHandle; /* For setting power dependency */
volatile tDMAControlTable *rxDmaEntry;
volatile tDMAControlTable *txDmaEntry;
/* UART read variables */
unsigned char *readBuf; /* Buffer data pointer */
size_t readSize; /* Number of bytes to read */
uint32_t nReadTransfers; /* Number of DMA transfers needed */
size_t readCount; /* Number of bytes left to read */
size_t rxSize; /* # of bytes to read in DMA xfer */
size_t bytesRead; /* Number of bytes read */
SemaphoreP_Struct readSem; /* UART read semaphore */
unsigned int readTimeout; /* Timeout for read semaphore */
UART2_Callback readCallback; /* Pointer to read callback */
/* UART write variables */
const unsigned char *writeBuf; /* Buffer data pointer */
size_t writeSize; /* Number of bytes to write*/
uint32_t nWriteTransfers; /* Number of DMA transfers needed */
size_t writeCount; /* Number of bytes left to write */
size_t txSize; /* # of bytes to write with DMA */
size_t bytesWritten; /* Number of bytes written */
SemaphoreP_Struct writeSem; /* UART write semaphore*/
unsigned int writeTimeout; /* Timeout for write semaphore */
UART2_Callback writeCallback; /* Pointer to write callback */
/* PIN driver state object and handle */
PIN_State pinState;
PIN_Handle hPin;
/* For Power management */
Power_NotifyObj postNotify;
unsigned int powerMgrId; /* Determined from base address */
} UART2CC26X2_Object, *UART2CC26X2_Handle;
#ifdef __cplusplus
}
#endif
#endif /* ti_drivers_uart2_UART2CC26X2__include */
| 41.52381 | 84 | 0.648465 | [
"object",
"vector"
] |
d7a5af8a10feb64394eff093f06c83197b48357e | 772 | h | C | Project26_CoreData/Role+CoreDataProperties.h | hayasilin/30DaysOBJC | 3f4d20a1b7bee273a1d38ed615aaa161f4804fe6 | [
"MIT"
] | 18 | 2016-09-21T02:02:56.000Z | 2022-03-09T05:55:51.000Z | Project26_CoreData/Role+CoreDataProperties.h | hayasilin/30DaysOBJC | 3f4d20a1b7bee273a1d38ed615aaa161f4804fe6 | [
"MIT"
] | null | null | null | Project26_CoreData/Role+CoreDataProperties.h | hayasilin/30DaysOBJC | 3f4d20a1b7bee273a1d38ed615aaa161f4804fe6 | [
"MIT"
] | 5 | 2016-09-24T03:03:06.000Z | 2022-02-19T14:19:57.000Z | //
// Role+CoreDataProperties.h
// Stuff Manager
//
// Created by Kuan-Wei Lin on 9/27/15.
// Copyright © 2015 Kuan-Wei Lin. All rights reserved.
//
// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu
// to delete and recreate this implementation file for your updated model.
//
#import "Role.h"
NS_ASSUME_NONNULL_BEGIN
@interface Role (CoreDataProperties)
@property (nullable, nonatomic, retain) NSString *name;
@property (nullable, nonatomic, retain) NSSet<Person *> *heldBy;
@end
@interface Role (CoreDataGeneratedAccessors)
- (void)addHeldByObject:(Person *)value;
- (void)removeHeldByObject:(Person *)value;
- (void)addHeldBy:(NSSet<Person *> *)values;
- (void)removeHeldBy:(NSSet<Person *> *)values;
@end
NS_ASSUME_NONNULL_END
| 23.393939 | 76 | 0.737047 | [
"model"
] |
d7a665030352a87f4b96bd443eeec9cd21001964 | 30,032 | h | C | src/gui/NamedElementListController.h | xushengj/PrepPipe | c2497d2ef5529d52e00a3ac34908478908e0098c | [
"MIT"
] | null | null | null | src/gui/NamedElementListController.h | xushengj/PrepPipe | c2497d2ef5529d52e00a3ac34908478908e0098c | [
"MIT"
] | null | null | null | src/gui/NamedElementListController.h | xushengj/PrepPipe | c2497d2ef5529d52e00a3ac34908478908e0098c | [
"MIT"
] | null | null | null | #ifndef NAMEDELEMENTLISTCONTROLLER_H
#define NAMEDELEMENTLISTCONTROLLER_H
#include <QObject>
#include <QListWidget>
#include <QStackedWidget>
#include <QList>
#include <QHash>
#include <QMap>
#include <QStringList>
#include <QStringListModel>
#include <QAction>
#include <QMenu>
#include <QMessageBox>
#include <QInputDialog>
#include <type_traits>
#include "src/utils/BidirStringList.h"
/**
* @brief The NamedElementListControllerObject class wraps all signal/slot connection
*
* QObject does not work in templated class, so a dummy object is needed to use signal/slots in NamedElementListController below.
*/
class NamedElementListControllerObject: public QObject
{
Q_OBJECT
public:
template <typename ElementWidget, bool isSortElementByName>
friend class NamedElementListController;
// --------------------------------------------------------
// signal / slots exposed to outside
signals:
void dirty();
void listUpdated(const QStringList& list);
public slots:
void tryGoToElement(const QString& elementName);
void tryCreateElement(const QString& elementName);
// --------------------------------------------------------
// those that are not exposed (internal use in controller)
private slots:
void currentElementChangeHandler(int index);
void listWidgetContextMenuEventHandler(const QPoint& p);
private:
// only the controller can instantiate it
NamedElementListControllerObject();
void init(QListWidget* listWidgetArg, QStackedWidget* stackedWidgetArg);
void setCurrentElementChangeCallback(std::function<void(int)> cb) {
currentElementChangeCB = cb;
}
void setGotoElementCallback(std::function<void(const QString&)> cb) {
gotoElementCB = cb;
}
void setCreateElementCallback(std::function<void(const QString&)> cb) {
createElementCB = cb;
}
void setListWidgetContextMenuEventCallback(std::function<void(const QPoint&)> cb) {
listWidgetContextMenuEventCB = cb;
}
void emitDirty() {
emit dirty();
}
void emitListUpdated(const QStringList& list) {
emit listUpdated(list);
emit dirty();
}
private:
QListWidget* listWidget = nullptr;
QStackedWidget* stackedWidget = nullptr;
std::function<void(int)> currentElementChangeCB;
std::function<void(const QString&)> gotoElementCB;
std::function<void(const QString&)> createElementCB;
std::function<void(const QPoint&)> listWidgetContextMenuEventCB;
};
template <typename ElementWidget, bool isSortElementByName>
class NamedElementListController {
static_assert (std::is_base_of<QWidget, ElementWidget>::value, "ElementWidget must inherit QWidget!");
static_assert (std::is_class<typename ElementWidget::StorageData>::value, "Element Widget must have a public struct member called StorageData!");
// ElementWidget can optionally have a public struct member caled HelperData, which represent the gui helper data that is not present in base object but in GUI object
// ElementWidget should have the following member functions: (helperData parameter not present if HelperData is void)
// void setData(const QString& name, const StorageData& storageData, const HelperData& helperData);
// void getData(const QString& name, StorageData&, HelperData&);
// ElementWidget should have the following signals:
// void dirty();
// ElementWidget should have the following slots:
// void nameUpdated(const QString& newName);
public:
using ElementStorageData = typename ElementWidget::StorageData;
using ElementHelperData = typename ElementWidget::HelperData;
public:
NamedElementListController() = default;
void init(QListWidget* listWidgetArg, QStackedWidget* stackedWidgetArg);
// get name callback is only used when the name of element is embedded in ElementStorageData
// if ElementStorageData is always organized in a QHash with its name as key, then this callback is not needed
void setGetNameCallback(std::function<QString(const ElementStorageData&)> cb) {
getNameCallback = cb;
}
// if the element widget needs additional initialization (e.g. setting callbacks for input field validation),
// then this callback should be set. If this is not set, then element widgets will be default constructed.
// the object parameter is the result of getObj() and is to help signal/slot connection
void setCreateWidgetCallback(std::function<ElementWidget*(NamedElementListControllerObject*)> cb) {
createWidgetCallback = cb;
}
// all signal/slots connection goes to the embedded object
NamedElementListControllerObject* getObj() {
return &obj;
}
QStringListModel* getNameListModel() {
return nameListModel;
}
bool isElementExist(const QString& name) {
return nameList.contains(name);
}
// for all setData() and getData(), the return type is void; the enable_if are for conditionally enable the function with given signature
// if we have non-void ElementHelperData:
// if we have the name embedded in ElementStorageData:
template <typename Helper = ElementHelperData> typename std::enable_if<!std::is_void<Helper>::value, void>::type setData(const QVector<ElementStorageData>& data, const QVector<ElementHelperData>& helperData);
template <typename Helper = ElementHelperData> typename std::enable_if<!std::is_void<Helper>::value, void>::type getData( QVector<ElementStorageData>& data, QVector<ElementHelperData>& helperData);
// if we have the name stored out-of-band as the key to a QHash:
template <typename Helper = ElementHelperData> typename std::enable_if<!std::is_void<Helper>::value, void>::type setData(const QHash<QString, ElementStorageData>& data, const QHash<QString, ElementHelperData>& helperData);
template <typename Helper = ElementHelperData> typename std::enable_if<!std::is_void<Helper>::value, void>::type getData( QHash<QString, ElementStorageData>& data, QHash<QString, ElementHelperData>& helperData);
// if the ElementHelperData is void:
// if we have the name embedded in ElementStorageData:
template <typename Helper = ElementHelperData> typename std::enable_if<std::is_void<Helper>::value, void>::type setData(const QVector<ElementStorageData>& data);
template <typename Helper = ElementHelperData> typename std::enable_if<std::is_void<Helper>::value, void>::type getData( QVector<ElementStorageData>& data);
// if we have the name stored out-of-band as the key to a QHash:
template <typename Helper = ElementHelperData> typename std::enable_if<std::is_void<Helper>::value, void>::type setData(const QHash<QString, ElementStorageData>& data);
template <typename Helper = ElementHelperData> typename std::enable_if<std::is_void<Helper>::value, void>::type getData( QHash<QString, ElementStorageData>& data);
private:
// private functions that show how ElementWidget would be used
void addElementDuringSetData(const QString& name, ElementWidget* widget) {
nameList.push_back(name);
widgetList.push_back(widget);
QObject::connect(widget, &ElementWidget::dirty, &obj, &NamedElementListControllerObject::dirty);
listWidget->addItem(name);
stackedWidget->addWidget(widget);
}
void notifyNameChange(const QString& newName, ElementWidget* widget) {
widget->nameUpdated(newName);
}
void currentElementChangedHandler(int index) {
if (index == -1) {
stackedWidget->setCurrentWidget(placeHolderPage);
} else {
stackedWidget->setCurrentWidget(widgetList.at(index));
}
}
ElementWidget* createWidget() {
if (createWidgetCallback) {
return createWidgetCallback(getObj());
}
return new ElementWidget;
}
// the two functions below just returns ElementWidget*
template <typename Helper = ElementHelperData> typename std::enable_if<std::is_void<Helper>::value, ElementWidget*>::type
createWidgetWithData(const QString& name) {
ElementWidget* w = createWidget();
w->setData(name, ElementStorageData());
return w;
}
template <typename Helper = ElementHelperData> typename std::enable_if<!std::is_void<Helper>::value, ElementWidget*>::type
createWidgetWithData(const QString& name) {
ElementWidget* w = createWidget();
w->setData(name, ElementStorageData(), ElementHelperData());
return w;
}
// same
template <typename Helper = ElementHelperData> typename std::enable_if<std::is_void<Helper>::value, ElementWidget*>::type
createWidgetWithDataFromSource(const QString& name, const QString& srcName, ElementWidget* src) {
ElementStorageData storage;
src->getData(srcName, storage);
ElementWidget* w = createWidget();
w->setData(name, storage);
return w;
}
template <typename Helper = ElementHelperData> typename std::enable_if<!std::is_void<Helper>::value, ElementWidget*>::type
createWidgetWithDataFromSource(const QString& name, const QString& srcName, ElementWidget* src) {
ElementStorageData storage;
ElementHelperData helper;
src->getData(srcName, storage, helper);
ElementWidget* w = createWidget();
w->setData(name, storage, helper);
return w;
}
// other (ElementWidget type agnostic) helper functions
void clearData();
void finalizeSetData();
void nameListUpdated();
void tryGoToElement(const QString& element);
void listWidgetContextMenuEventHandler(const QPoint& pos);
QString getNameEditDialog(const QString& oldName, bool isNewInsteadofRename);
void handleRename(int index, const QString& newName);
void handleDelete(int index);
void handleNew(const QString& name);
void handleCopyAs(const QString& name, const QString& srcName, ElementWidget* src);
void handleAddElement(const QString& name, ElementWidget* w);
QVector<std::pair<QString, ElementWidget*>> getCombinedPairVec(int reserveSize);
private:
NamedElementListControllerObject obj;
QListWidget* listWidget = nullptr;
QStackedWidget* stackedWidget = nullptr;
std::function<QString(const ElementStorageData&)> getNameCallback;
std::function<ElementWidget*(NamedElementListControllerObject*)> createWidgetCallback;
QWidget* dialogParent = nullptr;
QWidget* placeHolderPage = nullptr;
QStringListModel* nameListModel = nullptr;
BidirStringList nameList;
QList<ElementWidget*> widgetList;
};
template <typename ElementWidget, bool isSortElementByName>
void NamedElementListController<ElementWidget, isSortElementByName>::init(QListWidget* listWidgetArg, QStackedWidget* stackedWidgetArg)
{
listWidget = listWidgetArg;
stackedWidget = stackedWidgetArg;
dialogParent = stackedWidgetArg;
nameListModel = new QStringListModel(&obj);
// there must be a place holder page / widget in the stack widget and nothing else should be there
Q_ASSERT(stackedWidget->count() == 1);
placeHolderPage = stackedWidget->currentWidget();
obj.init(listWidgetArg, stackedWidgetArg);
obj.setCurrentElementChangeCallback(std::bind(&NamedElementListController<ElementWidget, isSortElementByName>::currentElementChangedHandler, this, std::placeholders::_1));
obj.setGotoElementCallback(std::bind(&NamedElementListController<ElementWidget, isSortElementByName>::tryGoToElement, this, std::placeholders::_1));
obj.setCreateElementCallback(std::bind(&NamedElementListController<ElementWidget, isSortElementByName>::handleNew, this, std::placeholders::_1));
obj.setListWidgetContextMenuEventCallback(std::bind(&NamedElementListController<ElementWidget, isSortElementByName>::listWidgetContextMenuEventHandler, this, std::placeholders::_1));
}
template <typename ElementWidget, bool isSortElementByName>
void NamedElementListController<ElementWidget, isSortElementByName>::clearData()
{
if (nameList.isEmpty())
return;
stackedWidget->setCurrentWidget(placeHolderPage);
for (QWidget* editor : widgetList) {
stackedWidget->removeWidget(editor);
editor->deleteLater();
}
nameList.clear();
widgetList.clear();
nameListModel->setStringList(nameList.getList());
}
template <typename ElementWidget, bool isSortElementByName>
void NamedElementListController<ElementWidget, isSortElementByName>::finalizeSetData()
{
nameListModel->setStringList(nameList.getList());
if (!widgetList.isEmpty()) {
listWidget->setCurrentRow(0);
}
}
template <typename ElementWidget, bool isSortElementByName>
void NamedElementListController<ElementWidget, isSortElementByName>::tryGoToElement(const QString& element)
{
// this would also emit signal that cause stackedWidget to be updated
listWidget->setCurrentRow(nameList.indexOf(element));
}
template <typename ElementWidget, bool isSortElementByName>
void NamedElementListController<ElementWidget, isSortElementByName>::nameListUpdated()
{
listWidget->clear();
listWidget->addItems(nameList.getList());
obj.emitListUpdated(nameList.getList());
}
template <typename ElementWidget, bool isSortElementByName> template <typename Helper>
typename std::enable_if<!std::is_void<Helper>::value, void>::type
NamedElementListController<ElementWidget, isSortElementByName>::setData(
const QVector<ElementStorageData>& data,
const QVector<ElementHelperData> &helperData
){
Q_ASSERT(getNameCallback);
int numElements = data.size();
Q_ASSERT(numElements == helperData.size());
clearData();
QVector<std::pair<QString, int>> indexVec;
if (isSortElementByName) {
for (int i = 0; i < numElements; ++i) {
const ElementStorageData& storage = data.at(i);
QString name = getNameCallback(storage);
indexVec.push_back(std::make_pair(name, i));
}
NameSorting::sortNameListWithData(indexVec);
}
for (int i = 0; i < numElements; ++i) {
int indexToUse = (isSortElementByName? indexVec.at(i).second : i);
const ElementStorageData& storage = data.at(indexToUse);
const ElementHelperData& helper = helperData.at(indexToUse);
QString name = (isSortElementByName? indexVec.at(i).first : getNameCallback(storage));
ElementWidget* widget = createWidget();
widget->setData(name, storage, helper);
addElementDuringSetData(name, widget);
}
finalizeSetData();
}
template <typename ElementWidget, bool isSortElementByName> template <typename Helper>
typename std::enable_if<!std::is_void<Helper>::value, void>::type
NamedElementListController<ElementWidget, isSortElementByName>::getData(
QVector<ElementStorageData>& data,
QVector<ElementHelperData>& helperData)
{
int numElement = nameList.size();
Q_ASSERT(numElement == widgetList.size());
data.resize(numElement);
helperData.resize(numElement);
for (int i = 0; i < numElement; ++i) {
ElementWidget* widget = widgetList.at(i);
widget->getData(nameList.at(i), data[i], helperData[i]);
}
}
template <typename ElementWidget, bool isSortElementByName> template <typename Helper>
typename std::enable_if<!std::is_void<Helper>::value, void>::type
NamedElementListController<ElementWidget, isSortElementByName>::setData(
const QHash<QString, ElementStorageData>& data,
const QHash<QString, ElementHelperData>& helperData)
{
int numElements = data.size();
Q_ASSERT(numElements == helperData.size());
clearData();
if (isSortElementByName) {
QStringList keyList = data.uniqueKeys();
Q_ASSERT(keyList.size() == numElements);
NameSorting::sortNameList(keyList);
for (const QString& name : keyList) {
auto iterData = data.find(name);
Q_ASSERT(iterData != data.end());
auto iterHelperData = helperData.find(name);
Q_ASSERT(iterHelperData != helperData.end());
const ElementStorageData& storage = iterData.value();
const ElementHelperData& helper = iterHelperData.value();
ElementWidget* widget = createWidget();
widget->setData(name, storage, helper);
addElementDuringSetData(name, widget);
}
} else {
for (auto iterData = data.begin(), iterDataEnd = data.end(); iterData != iterDataEnd; ++iterData) {
const QString& name = iterData.key();
const ElementStorageData& storage = iterData.value();
auto iterHelperData = helperData.find(name);
Q_ASSERT(iterHelperData != helperData.end());
const ElementHelperData& helper = iterHelperData.value();
ElementWidget* widget = createWidget();
widget->setData(name, storage, helper);
addElementDuringSetData(name, widget);
}
}
finalizeSetData();
}
template <typename ElementWidget, bool isSortElementByName> template <typename Helper>
typename std::enable_if<!std::is_void<Helper>::value, void>::type
NamedElementListController<ElementWidget, isSortElementByName>::getData(
QHash<QString, ElementStorageData>& data,
QHash<QString, ElementHelperData>& helperData)
{
data.clear();
helperData.clear();
for (int i = 0, numElements = nameList.size(); i < numElements; ++i) {
const QString& name = nameList.at(i);
ElementWidget* widget = widgetList.at(i);
ElementStorageData storage;
ElementHelperData helper;
widget->getData(name, storage, helper);
data.insert(name, storage);
helperData.insert(name, helper);
}
}
template <typename ElementWidget, bool isSortElementByName> template <typename Helper>
typename std::enable_if<std::is_void<Helper>::value, void>::type
NamedElementListController<ElementWidget, isSortElementByName>::setData(const QVector<ElementStorageData>& data)
{
Q_ASSERT(getNameCallback);
int numElements = data.size();
clearData();
QVector<std::pair<QString, int>> indexVec;
if (isSortElementByName) {
for (int i = 0; i < numElements; ++i) {
const ElementStorageData& storage = data.at(i);
QString name = getNameCallback(storage);
indexVec.push_back(std::make_pair(name, i));
}
NameSorting::sortNameListWithData(indexVec);
}
for (int i = 0; i < numElements; ++i) {
int indexToUse = (isSortElementByName? indexVec.at(i).second : i);
const ElementStorageData& storage = data.at(indexToUse);
QString name = (isSortElementByName? indexVec.at(i).first : getNameCallback(storage));
ElementWidget* widget = createWidget();
widget->setData(name, storage);
addElementDuringSetData(name, widget);
}
finalizeSetData();
}
template <typename ElementWidget, bool isSortElementByName> template <typename Helper>
typename std::enable_if<std::is_void<Helper>::value, void>::type
NamedElementListController<ElementWidget, isSortElementByName>::getData(QVector<ElementStorageData> &data)
{
int numElement = nameList.size();
Q_ASSERT(numElement == widgetList.size());
data.resize(numElement);
for (int i = 0; i < numElement; ++i) {
ElementWidget* widget = widgetList.at(i);
widget->getData(nameList.at(i), data[i]);
}
}
template <typename ElementWidget, bool isSortElementByName> template <typename Helper>
typename std::enable_if<std::is_void<Helper>::value, void>::type
NamedElementListController<ElementWidget, isSortElementByName>::setData(const QHash<QString, ElementStorageData>& data)
{
int numElements = data.size();
clearData();
if (isSortElementByName) {
QStringList keyList = data.uniqueKeys();
Q_ASSERT(keyList.size() == numElements);
NameSorting::sortNameList(keyList);
for (const QString& name : keyList) {
auto iterData = data.find(name);
Q_ASSERT(iterData != data.end());
const ElementStorageData& storage = iterData.value();
ElementWidget* widget = createWidget();
widget->setData(name, storage);
addElementDuringSetData(name, widget);
}
} else {
for (auto iterData = data.begin(), iterDataEnd = data.end(); iterData != iterDataEnd; ++iterData) {
const QString& name = iterData.key();
const ElementStorageData& storage = iterData.value();
ElementWidget* widget = createWidget();
widget->setData(name, storage);
addElementDuringSetData(name, widget);
}
}
finalizeSetData();
}
template <typename ElementWidget, bool isSortElementByName> template <typename Helper>
typename std::enable_if<std::is_void<Helper>::value, void>::type
NamedElementListController<ElementWidget, isSortElementByName>::getData(QHash<QString, ElementStorageData> &data)
{
data.clear();
for (int i = 0, numElements = nameList.size(); i < numElements; ++i) {
const QString& name = nameList.at(i);
ElementWidget* widget = widgetList.at(i);
ElementStorageData storage;
widget->getData(name, storage);
data.insert(name, storage);
}
}
template <typename ElementWidget, bool isSortElementByName>
QVector<std::pair<QString, ElementWidget*>>
NamedElementListController<ElementWidget, isSortElementByName>::getCombinedPairVec(int reserveSize)
{
QVector<std::pair<QString, ElementWidget*>> combinedPair;
int numElements = nameList.size();
Q_ASSERT(numElements == widgetList.size());
Q_ASSERT(numElements <= reserveSize);
combinedPair.reserve(reserveSize);
for (int i = 0; i < numElements; ++i) {
QString name = nameList.at(i);
ElementWidget* curWidget = widgetList.at(i);
combinedPair.push_back(std::make_pair(name, curWidget));
}
return combinedPair;
}
template <typename ElementWidget, bool isSortElementByName>
void NamedElementListController<ElementWidget, isSortElementByName>::handleRename(int index, const QString& newName)
{
Q_ASSERT(index >= 0 && index < nameList.size());
QStringList curList = nameList.getList();
curList[index] = newName;
// we keep a pointer here and push the notification after all the invariants are recovered
ElementWidget* w = widgetList.at(index);
int numElements = nameList.size();
QVector<std::pair<QString, ElementWidget*>> combinedPair = getCombinedPairVec(numElements);
NameSorting::sortNameListWithData(combinedPair);
int curIndex = -1;
for (int i = 0; i < numElements; ++i) {
auto& p = combinedPair.at(i);
curList[i] = p.first;
widgetList[i] = p.second;
if (p.second == w) {
curIndex = i;
}
}
notifyNameChange(newName, w);
nameList = curList;
nameListUpdated();
Q_ASSERT(curIndex >= 0);
listWidget->setCurrentRow(curIndex);
}
template <typename ElementWidget, bool isSortElementByName>
void NamedElementListController<ElementWidget, isSortElementByName>::handleDelete(int index)
{
Q_ASSERT(index >= 0 && index < widgetList.size());
ElementWidget* currentWidget = widgetList.at(index);
int nextIndex = listWidget->currentRow();
if (stackedWidget->currentWidget() == currentWidget) {
if (widgetList.size() > 1) {
nextIndex = (index == widgetList.size()-1)? index - 1 : index;
} else {
nextIndex = -1;
}
}
stackedWidget->removeWidget(currentWidget);
currentWidget->deleteLater();
widgetList.removeAt(index);
nameList.removeAt(index);
nameListUpdated();
listWidget->setCurrentRow(nextIndex);
}
template <typename ElementWidget, bool isSortElementByName>
void NamedElementListController<ElementWidget, isSortElementByName>::handleAddElement(const QString& name, ElementWidget* newWidget)
{
QVector<std::pair<QString, ElementWidget*>> combinedPairVec = getCombinedPairVec(nameList.size() + 1);
combinedPairVec.push_back(std::make_pair(name, newWidget));
NameSorting::sortNameListWithData(combinedPairVec);
int numElements = combinedPairVec.size();
nameList.clear();
nameList.reserve(numElements);
widgetList.clear();
widgetList.reserve(numElements);
int curIndex = -1;
for (int i = 0; i < numElements; ++i) {
const auto& p = combinedPairVec.at(i);
nameList.push_back(p.first);
widgetList.push_back(p.second);
if (p.second == newWidget) {
curIndex = i;
}
}
stackedWidget->addWidget(newWidget);
nameListUpdated();
Q_ASSERT(curIndex >= 0);
listWidget->setCurrentRow(curIndex);
}
template <typename ElementWidget, bool isSortElementByName>
void NamedElementListController<ElementWidget, isSortElementByName>::handleNew(const QString& name)
{
// because beside the call from right click menu, this function is also called by incoming signal connection,
// we need to check if the name is already used, and just early exit if it is the case.
if (isElementExist(name))
return;
ElementWidget* newWidget = createWidgetWithData(name);
handleAddElement(name, newWidget);
}
template <typename ElementWidget, bool isSortElementByName>
void NamedElementListController<ElementWidget, isSortElementByName>::handleCopyAs(const QString& name, const QString& srcName, ElementWidget* src)
{
ElementWidget* newWidget = createWidgetWithDataFromSource(name, srcName, src);
handleAddElement(name, newWidget);
}
template <typename ElementWidget, bool isSortElementByName>
void NamedElementListController<ElementWidget, isSortElementByName>::listWidgetContextMenuEventHandler(const QPoint& pos)
{
QListWidgetItem* item = listWidget->itemAt(pos);
QMenu menu(listWidget);
QString oldName;
if (item) {
int row = listWidget->row(item);
Q_ASSERT(row >= 0 && row < nameList.size());
oldName = nameList.at(row);
Q_ASSERT(oldName == item->text());
QAction* renameAction = new QAction(NamedElementListControllerObject::tr("Rename"));
QObject::connect(renameAction, &QAction::triggered, getObj(), [=](){
QString newName = getNameEditDialog(oldName, false);
if (newName.isEmpty() || newName == oldName)
return;
if (isElementExist(newName)) {
QMessageBox::warning(dialogParent,
NamedElementListControllerObject::tr("Rename failed"),
NamedElementListControllerObject::tr("There is already an entry named \"%1\".").arg(newName));
tryGoToElement(newName);
return;
}
handleRename(row, newName);
});
menu.addAction(renameAction);
QAction* copyAsAction = new QAction(NamedElementListControllerObject::tr("Copy As"));
QObject::connect(copyAsAction, &QAction::triggered, getObj(), [=](){
QString newName = getNameEditDialog(oldName, true);
if (newName.isEmpty() || newName == oldName)
return;
if (isElementExist(newName)) {
QMessageBox::warning(dialogParent,
NamedElementListControllerObject::tr("Copy failed"),
NamedElementListControllerObject::tr("There is already an entry named \"%1\".").arg(newName));
tryGoToElement(newName);
return;
}
handleCopyAs(newName, oldName, widgetList.at(row));
});
menu.addAction(copyAsAction);
QAction* deleteAction = new QAction(NamedElementListControllerObject::tr("Delete"));
QObject::connect(deleteAction, &QAction::triggered, getObj(), [=](){
if (QMessageBox::question(dialogParent,
NamedElementListControllerObject::tr("Delete confirmation"),
NamedElementListControllerObject::tr("Are you sure you want to delete \"%1\"?").arg(oldName),
QMessageBox::Yes | QMessageBox::Cancel) == QMessageBox::Yes) {
handleDelete(row);
}
});
menu.addAction(deleteAction);
}
QAction* newAction = new QAction(NamedElementListControllerObject::tr("New"));
QObject::connect(newAction, &QAction::triggered, getObj(), [=](){
QString newName = getNameEditDialog(oldName, true);
if (newName.isEmpty() || newName == oldName)
return;
// if the name is already in use, pop up a dialog
if (isElementExist(newName)) {
QMessageBox::warning(dialogParent,
NamedElementListControllerObject::tr("Creation failed"),
NamedElementListControllerObject::tr("There is already an entry named \"%1\".").arg(newName));
tryGoToElement(newName);
return;
}
handleNew(newName);
});
menu.addAction(newAction);
menu.exec(listWidget->mapToGlobal(pos));
}
template <typename ElementWidget, bool isSortElementByName>
QString NamedElementListController<ElementWidget, isSortElementByName>::getNameEditDialog(const QString& oldName, bool isNewInsteadofRename)
{
QString title;
QString prompt;
if (isNewInsteadofRename) {
title = NamedElementListControllerObject::tr("New");
prompt = NamedElementListControllerObject::tr("Please input the name:");
} else {
title = NamedElementListControllerObject::tr("Rename");
prompt = NamedElementListControllerObject::tr("Please input the new name for \"%1\":").arg(oldName);
}
bool ok = false;
QString result = QInputDialog::getText(dialogParent, title, prompt, QLineEdit::Normal, oldName, &ok);
if (ok) {
return result;
}
return QString();
}
#endif // NAMEDELEMENTLISTCONTROLLER_H
| 43.211511 | 229 | 0.691396 | [
"object"
] |
d7a6b1be993d9c66f162ad3253b16d44d97ac0cf | 232 | h | C | GRMFixes/CarnageFatnessFix/Plugin_Header.h | ThielHater/GRMFixes_Union | 839745fbc009db532bb51de8baa0a19c45143ff2 | [
"MIT"
] | null | null | null | GRMFixes/CarnageFatnessFix/Plugin_Header.h | ThielHater/GRMFixes_Union | 839745fbc009db532bb51de8baa0a19c45143ff2 | [
"MIT"
] | null | null | null | GRMFixes/CarnageFatnessFix/Plugin_Header.h | ThielHater/GRMFixes_Union | 839745fbc009db532bb51de8baa0a19c45143ff2 | [
"MIT"
] | 1 | 2021-08-29T11:06:08.000Z | 2021-08-29T11:06:08.000Z | // Header file
// Multi-platform file can not have `#pragma once`!!!
namespace NAMESPACE
{
void SetEnabled();
struct GothicMemoryLocations
{
struct zCModel
{
static const int Render = 0x00560770;
};
};
} | 15.466667 | 54 | 0.642241 | [
"render"
] |
d7b5f1b99b05309592bbdc182004e0a82aa5cad5 | 2,269 | h | C | DNS/Decoders/DNSResourceRecordDecoder.h | victorgama/dns | 38c6887346102187681f1b660f4758bb77500d66 | [
"MIT"
] | 2 | 2021-05-06T08:19:16.000Z | 2021-05-17T09:25:11.000Z | DNS/Decoders/DNSResourceRecordDecoder.h | victorgama/dns | 38c6887346102187681f1b660f4758bb77500d66 | [
"MIT"
] | 1 | 2021-05-05T18:11:29.000Z | 2021-05-05T18:11:29.000Z | DNS/Decoders/DNSResourceRecordDecoder.h | victorgama/dns | 38c6887346102187681f1b660f4758bb77500d66 | [
"MIT"
] | 1 | 2021-11-04T09:43:08.000Z | 2021-11-04T09:43:08.000Z | //
// DNSResourceRecordDecoder.h
// DNS
//
// Created by Victor Gama on 11/10/2018.
// Copyright © 2018 Victor Gama. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "DNSResourceRecord.h"
/*
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| |
/ /
/ NAME /
/ /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| TYPE |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| CLASS |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| TTL |
| |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
| RDLENGTH |
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--|
/ RDATA /
/ /
+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+
*/
NS_ASSUME_NONNULL_BEGIN
/**
Responsible for decoding a DNS Resource Record into an @c DNSResourceRecord
object. Resource Record is defined in RFC1035.
@link https://tools.ietf.org/html/rfc1035#section-3.2
*/
@interface DNSResourceRecordDecoder : NSObject
/**
After decoding is complete, @c resource retains an instance to a
@c DNSResourceRecord
*/
@property (nullable, nonatomic, retain) DNSResourceRecord *resource;
/**
Decodes the provided buffer into a @c DNSResourceRecord, advancing the provided
offset pointer. Length is provided as a mechanism to prevent corrupted or
invalid data from reading more than allocated by the provided buffer
(over-read).
@param buffer Pointer to an array of bytes from which the resource will be
parsed from.
@param offset Offset pointing to the next byte that will be read by the parsing
facilities
@param bufferLength Total length of provided buffer. Used to prevent over-read.
*/
- (void)decodeResourceInBuffer:(uint8_t *)buffer withOffset:(uint32_t *)offset andLength:(uint32_t)bufferLength;
@end
NS_ASSUME_NONNULL_END
| 33.367647 | 112 | 0.460555 | [
"object"
] |
d7b62919ea01fa66c45e2f3e247b291b80684101 | 7,397 | h | C | src/MPLibrary/MPTools/RegionKit.h | parasol-ppl/PPL | 04de04b23e0368e576d2136fee8729de44a3eda5 | [
"BSD-3-Clause"
] | null | null | null | src/MPLibrary/MPTools/RegionKit.h | parasol-ppl/PPL | 04de04b23e0368e576d2136fee8729de44a3eda5 | [
"BSD-3-Clause"
] | null | null | null | src/MPLibrary/MPTools/RegionKit.h | parasol-ppl/PPL | 04de04b23e0368e576d2136fee8729de44a3eda5 | [
"BSD-3-Clause"
] | null | null | null | #ifndef PMPL_REGION_KIT_H_
#define PMPL_REGION_KIT_H_
#include <iostream>
#include <limits>
#include <map>
#include <vector>
#include "Utilities/XMLNode.h"
#include "Workspace/WorkspaceSkeleton.h"
#include "Vector.h"
using namespace mathtool;
class Boundary;
class Cfg;
class XMLNode;
////////////////////////////////////////////////////////////////////////////////
/// Creates and manages a set of dynamic sampling regions that follow a
/// workspace skeleton.
////////////////////////////////////////////////////////////////////////////////
class RegionKit final {
private:
///@name Local Types
///@{
/// Use the skeleton's name for a skeleton edge descriptor.
using ED = WorkspaceSkeleton::ED;
////////////////////////////////////////////////////////////////////////////
/// Auxiliary data for regions.
////////////////////////////////////////////////////////////////////////////
struct RegionData {
///@name Internal State
///@{
ED edgeDescriptor; ///< Descriptor of the edge the region is traveling.
size_t edgeIndex{0}; ///< Region is at this index on the skeleton edge.
size_t successes{0}; ///< Number of valid samples in this region.
size_t attempts{1}; ///< Number of sampling attempts in this region.
double weight{0}; ///< Ratio of successful samples to total samples.
/// Drawable ID when using simulator.
size_t visualizationID{std::numeric_limits<size_t>::max()};
///@}
///@name Construction
///@{
/// Construct region metadata from an edge descriptor.
RegionData(const ED& _ed = ED()) : edgeDescriptor(_ed) {}
///@}
};
///@}
///@name Internal State
///@{
WorkspaceSkeleton* m_skeleton{nullptr}; ///< The workspace skeleton.
/// The set of active dynamic sampling regions and associated metadata.
std::unordered_map<Boundary*, RegionData> m_regionData;
/// Keep track of which skeleton vertices we've visited.
std::unordered_map<WorkspaceSkeleton::VD, bool> m_visited;
/// The dynamic sampling regions will have radius equal to this times the
/// robot's bounding sphere radius.
double m_regionFactor{2};
double m_regionRadius{0}; ///< The region radius.
/// Weight of explore vs. exploit in region selection probabilities.
/// Exploring is a uniform chance to select each region, while exploit
/// favors successful regions.
double m_explore{.5};
/// A configuration is considered to be touching a region when this fraction
/// of its bounding sphere penetrates into the region.
double m_penetrationFactor{1};
bool m_debug{false}; ///< Show debug messages?
///@}
public:
///@name Construction
///@{
RegionKit() = default;
RegionKit(XMLNode& _node);
~RegionKit();
/// Initialize a region kit for following a workspace skeleton.
/// @param _skeleton The skeleton to follow.
/// @param _point The workspace starting point.
/// @param _robotRadius The robot bounding sphere radius.
/// @param _label The label to use for the roadmap hook.
/// @param _graph The roadmap to hook onto.
template <typename RoadmapGraph>
void
Initialize(WorkspaceSkeleton* const _skeleton, const Point3d& _point,
const double _robotRadius, const std::string& _label,
RoadmapGraph* _graph);
/// Release all regions and clear the internal structures.
void Clear();
///@}
///@name Sampling
///@{
/// Select a region based on its weight.
const Boundary* SelectRegion();
/// Increment the failed sampling attempts of a region.
/// @param _region The region which generated an invalid sample.
/// @param _count The number to increment.
void IncrementFailure(const Boundary* const _region, const size_t _count = 1);
/// Increment the sampling success of a region.
/// @param _region The region which generated a successful sample.
/// @param _count The number to increment.
void IncrementSuccess(const Boundary* const _region, const size_t _count = 1);
/// Get the velocity bias for a given sampling region.
/// @param _region The sampling region.
/// @return The prefered velocity direction for samples within _region.
const Vector3d GetVelocityBias(const Boundary* const _region) const;
///@}
///@name I/O
///@{
/// Print parameters.
/// @param _os The out stream to write to.
void Print(std::ostream& _os) const;
///@}
private:
///@name Skeleton Following
///@{
/// Create regions on each edge outbound from the skeleton vertex nearest to
/// some starting point in workspace.
/// @param _start Workspace point.
void InitRegions(const Point3d& _start);
/// Create new regions along outgoing edges at each unvisted vertex within
/// a region radius from some point of interest.
/// @param _p The point.
void CreateRegions(const Point3d& _p);
/// Create new regions along outgoing edges at an unvisted vertex.
/// @param _iter The vertex iterator.
/// @return The set of created regions.
std::vector<Boundary*> CreateRegions(
const WorkspaceSkeleton::vertex_iterator _iter);
/// Test all regions for containment of new configuration and advance if
/// necessary. Any completed regions will spawn new ones at their
/// destinations outbound edges, which will also be advanced if necessary.
/// @param _cfg The new configuration.
void AdvanceRegions(const Cfg& _cfg);
/// Advance a single region until it no longer touches a configuration.
/// @param _cfg The configuration.
/// @param _region The region to advance.
/// @return True iff _region has reached the end of its edge.
bool AdvanceRegionToCompletion(const Cfg& _cfg, Boundary* const _region);
/// Test if a configuration is inside a region
/// @param _cfg The configuration to test.
/// @param _region The region.
/// @return True if the robot's bounding sphere is at least one region
/// radius times one robot factor into the _region.
bool IsTouching(const Cfg& _cfg, const Boundary* const _region) const;
/// Compute the probabilities of selecting each sampling region and
/// environment.
std::vector<double> ComputeProbabilities();
///@}
};
template <typename RoadmapGraph>
void
RegionKit::
Initialize(WorkspaceSkeleton* const _skeleton, const Point3d& _point,
const double _robotRadius, const std::string& _label, RoadmapGraph* _graph) {
if(_graph->IsHook(RoadmapGraph::HookType::AddVertex, _label))
_graph->RemoveHook(RoadmapGraph::HookType::AddVertex, _label);
// Set the skeleton pointer and initialize the regions/auxiliary data.
m_skeleton = _skeleton;
m_regionRadius = m_regionFactor * _robotRadius;
InitRegions(_point);
// On each new sample, check if we need to advance our regions and generate
// new ones. Add a roadmap hook to achieve this.
auto addVertex = [this](typename RoadmapGraph::VI _vi) {
if(this->m_debug)
std::cout << "RegionKit:: checking region advancement..." << std::endl;
this->CreateRegions(_vi->property().GetPoint());
this->AdvanceRegions(_vi->property());
};
_graph->InstallHook(RoadmapGraph::HookType::AddVertex, _label, addVertex);
}
#endif
| 32.585903 | 82 | 0.651075 | [
"vector"
] |
d7bbb6ba0f6c33f421a6321ad67001381319217f | 881 | h | C | tcpconnector.h | JohnnyBeGood34/EmbeddedProject-client | e6a9473c736ed71d263c438bee0bd06bb51e9b40 | [
"Apache-2.0"
] | null | null | null | tcpconnector.h | JohnnyBeGood34/EmbeddedProject-client | e6a9473c736ed71d263c438bee0bd06bb51e9b40 | [
"Apache-2.0"
] | null | null | null | tcpconnector.h | JohnnyBeGood34/EmbeddedProject-client | e6a9473c736ed71d263c438bee0bd06bb51e9b40 | [
"Apache-2.0"
] | null | null | null | #ifndef TCPCONNECTOR_H
#define TCPCONNECTOR_H
#if defined (WIN32)
#include <winsock2.h>
typedef int socklen_t;
#elif defined __linux__
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#endif
#include "tcpstream.h"
/**
* @brief The TCPConnector class provides the connect() method to actively establish
* a connection with a server. It accepts the server port and a string containing
* the server host name or IP address. If successful, a pointer to a TCPStream object is returned to the caller
*/
class TCPConnector
{
public:
TCPStream* connect(const char* server, int port);
//TCPStream* connect(const char* server, int port, int timeout);
private:
int resolveHost(const char* host, struct in_addr* addr);
};
#endif // TCPCONNECTOR_H
| 26.69697 | 112 | 0.69126 | [
"object"
] |
d7c2d12b4b3d60895749fba4db1cc5170ee57226 | 3,721 | h | C | src/qt/qtwebkit/Source/WebKit2/UIProcess/API/efl/ewk_file_chooser_request.h | viewdy/phantomjs | eddb0db1d253fd0c546060a4555554c8ee08c13c | [
"BSD-3-Clause"
] | 1 | 2015-05-27T13:52:20.000Z | 2015-05-27T13:52:20.000Z | src/qt/qtwebkit/Source/WebKit2/UIProcess/API/efl/ewk_file_chooser_request.h | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtwebkit/Source/WebKit2/UIProcess/API/efl/ewk_file_chooser_request.h | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | 1 | 2017-03-19T13:03:23.000Z | 2017-03-19T13:03:23.000Z | /*
* Copyright (C) 2012 Intel Corporation. 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 APPLE INC. AND ITS 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 APPLE INC. OR ITS 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 ewk_file_chooser_request.h
* @brief Describes the Ewk File Chooser API.
*/
#ifndef ewk_file_chooser_request_h
#define ewk_file_chooser_request_h
#include <Eina.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Declare Ewk_File_Chooser_Request as Ewk_Object.
*
* @see Ewk_Object
*/
typedef struct EwkObject Ewk_File_Chooser_Request;
/**
* Queries if it is allowed to select multiple files or not.
*
* @param request request object to query
*
* @return @c EINA_TRUE if it is allowed to select multiple files,
* @c EINA_FALSE otherwise
*/
EAPI Eina_Bool ewk_file_chooser_request_allow_multiple_files_get(const Ewk_File_Chooser_Request *request);
/**
* Queries the list of accepted MIME types.
*
* Possible MIME types are:
* - "audio\/\*": All sound files are accepted
* - "video\/\*": All video files are accepted
* - "image\/\*": All image files are accepted
* - standard IANA MIME type (see http://www.iana.org/assignments/media-types/ for a complete list)
*
* @param request request object to query
*
* @return The list of accepted MIME types. The list items are guaranteed to be stringshared.
* The caller needs to free the list and its items after use
*/
EAPI Eina_List *ewk_file_chooser_request_accepted_mimetypes_get(const Ewk_File_Chooser_Request *request);
/**
* Cancels the file chooser request.
*
* @param request request object to cancel
*
* @return @c EINA_TRUE if successful, @c EINA_FALSE otherwise
*/
EAPI Eina_Bool ewk_file_chooser_request_cancel(Ewk_File_Chooser_Request *request);
/**
* Sets the files chosen by the user.
*
* @param request request object to update
*
* @return @c EINA_TRUE if successful, @c EINA_FALSE otherwise
*
* @see ewk_file_chooser_request_file_choose()
*/
EAPI Eina_Bool ewk_file_chooser_request_files_choose(Ewk_File_Chooser_Request *request, const Eina_List *chosen_files);
/**
* Sets the file chosen by the user.
*
* This is a convenience function in case only one file needs to be set.
*
* @param request request object to update
*
* @return @c EINA_TRUE if successful, @c EINA_FALSE otherwise
*
* @see ewk_file_chooser_request_files_choose()
*/
EAPI Eina_Bool ewk_file_chooser_request_file_choose(Ewk_File_Chooser_Request *request, const char *chosen_file);
#ifdef __cplusplus
}
#endif
#endif /* ewk_file_chooser_request_h */
| 33.522523 | 119 | 0.755711 | [
"object"
] |
d7c8a8cfba266ef1adf3b219604c2ca8e4380e04 | 35,381 | c | C | lib/EMBOSS-6.6.0/nucleus/embprop.c | alegione/CodonShuffle | bd6674b2eb21ee144a39d6d1e9b7264aba887240 | [
"MIT"
] | 5 | 2016-11-11T21:57:49.000Z | 2021-07-27T14:13:31.000Z | lib/EMBOSS-6.6.0/nucleus/embprop.c | frantallukas10/CodonShuffle | 4c408e1a8617f2a52dcb0329bba9617e1be17313 | [
"MIT"
] | 4 | 2016-05-15T07:56:25.000Z | 2020-05-20T05:21:48.000Z | lib/EMBOSS-6.6.0/nucleus/embprop.c | frantallukas10/CodonShuffle | 4c408e1a8617f2a52dcb0329bba9617e1be17313 | [
"MIT"
] | 10 | 2015-08-19T20:37:46.000Z | 2020-04-07T06:49:23.000Z | /* @source embprop ************************************************************
**
** Residue/sequence properties
**
** @author Copyright (c) 1999 Alan Bleasby
** @version $Revision: 1.54 $
** @modified 24 Nov 1999 - GWW - Added embPropProtGaps and embPropProt1to3
** @modified 1 Sept 2000 - GWW - Added embPropTransition embPropTranversion
** @modified 4 July 2001 - DMAM - Modified embPropAminoRead embPropCalcMolwt
** @modified 4 July 2001 - DMAM - Added embPropCalcMolwtMod
** @modified 1 July 2008 - JISON - Added embPropGet* functions
** @modified $Date: 2012/05/14 13:10:09 $ by $Author: uludag $
** @@
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License as published by the Free Software Foundation; either
** version 2.1 of the License, or (at your option) any later version.
**
** This library is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License along with this library; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
** MA 02110-1301, USA.
**
******************************************************************************/
#include "ajlib.h"
#include "embprop.h"
#include "ajbase.h"
#include "ajfileio.h"
#include "ajlist.h"
#include "ajseq.h"
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
char dayhoffstr[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
float dayhoff[] =
{
(float) 8.6, (float) 0.0, (float) 2.9, (float) 5.5, (float) 6.0,
(float) 3.6, (float) 8.4, (float) 2.0, (float) 4.5, (float) 0.0,
(float) 6.6, (float) 7.4, (float) 1.7, (float) 4.3, (float) 0.0,
(float) 5.2, (float) 3.9, (float) 4.9, (float) 7.0, (float) 6.1,
(float) 0.0, (float) 6.6, (float) 1.3, (float) 0.9, (float) 3.4,
(float) 0.0
};
#define PROPENZTRYPSIN 0
#define PROPENZLYSC 1
#define PROPENZARGC 2
#define PROPENZASPN 3
#define PROPENZV8B 4
#define PROPENZV8P 5
#define PROPENZCHYMOT 6
#define PROPENZCNBR 7
#define RAG_MINPEPLEN 3
#define AMINODATFILE "Eamino.dat"
/* static AjBool propInit = 0;*/
static char propPurines[] = "agrAGR";
static char propPyrimidines[] = "ctuyCTUY";
static ajint propFragCompare(const void *a, const void *b);
/* @func embPropEaminoRead ****************************************************
**
** Read amino acid properties from Eamino.dat
**
** @param [u] mfptr [AjPFile] Input file object
** @return [EmbPPropAmino*] array of amino acid properties
**
** @release 6.0.0
** @@
******************************************************************************/
EmbPPropAmino* embPropEaminoRead(AjPFile mfptr)
{
AjPStr line = NULL;
AjPStr token = NULL;
AjBool firstline;
const char *p;
ajuint i;
ajint n;
EmbPPropAmino *ret;
line = ajStrNew();
token = ajStrNew();
firstline = ajTrue;
AJCNEW0(ret,EMBPROPSIZE);
for(i=0; i < EMBPROPSIZE; ++i)
AJNEW0(ret[i]);
while(ajReadline(mfptr, &line))
{
ajStrRemoveWhiteExcess(&line);
p = ajStrGetPtr(line);
if(*p=='#' || *p=='!' || !*p)
continue;
if(firstline)
{
if(!ajStrPrefixC(line,"aa"))
ajFatal("Incorrect (old?) format amino data file");
firstline = ajFalse;
continue;
}
ajFmtScanS(line,"%S",&token);
ajStrFmtUpper(&token);
if(ajStrGetLen(token) != 1)
ajFatal("Amino file line doesn't begin with a single character");
i = ajBasecodeToInt((ajint) *ajStrGetPtr(token));
if(i == 27)
ajFatal("Amino file line doesn't begin with a single A->Z (%S)",
line);
n = ajFmtScanS(line,"%*s%d%d%d%d%d%d%f%d%d%d",
&ret[i]->tiny,
&ret[i]->sm_all,
&ret[i]->aliphatic,
&ret[i]->aromatic,
&ret[i]->nonpolar,
&ret[i]->polar,
&ret[i]->charge,
&ret[i]->pve,
&ret[i]->nve,
&ret[i]->extcoeff);
if(n!= 10)
ajFatal("Only %d columns in amino file - expected %d",n+1,11);
}
ajStrDel(&line);
ajStrDel(&token);
return ret;
}
/* @func embPropGetProperties *************************************************
**
** Returns a string containing a list of defined properties
**
** @param [r] prop [const EmbPPropAmino] Input properties object
** @param [w] Pstr [AjPStr*] String of properties separated by commas
** @return [AjBool] True if properties are defined
**
** @release 6.0.0
** @@
******************************************************************************/
AjBool embPropGetProperties(const EmbPPropAmino prop, AjPStr* Pstr)
{
ajStrAssignC(Pstr, "");
if(prop->tiny)
ajStrAppendC(Pstr, "tiny,");
if(prop->sm_all)
ajStrAppendC(Pstr, "small,");
if(prop->aliphatic)
ajStrAppendC(Pstr, "aliphatic,");
if(prop->aromatic)
ajStrAppendC(Pstr, "aromatic,");
if(prop->polar)
ajStrAppendC(Pstr, "polar,");
if(prop->nonpolar)
ajStrAppendC(Pstr, "nonpolar,");
ajStrTrimEndC(Pstr, ",");
if(!ajStrGetLen(*Pstr))
return ajFalse;
return ajTrue;
}
/* @func embPropEmolwtRead ****************************************************
**
** Read molecular weights from Emolwt.dat
**
** @param [u] mfptr [AjPFile] Input file object
** @return [EmbPPropMolwt*] array of amino acid molecular weights
**
** @release 6.0.0
** @@
******************************************************************************/
EmbPPropMolwt* embPropEmolwtRead(AjPFile mfptr)
{
AjPStr line = NULL;
AjPStr token = NULL;
AjBool firstline;
const char *p;
ajuint i;
ajint n;
EmbPPropMolwt *ret;
line = ajStrNew();
token = ajStrNew();
firstline = ajTrue;
AJCNEW0(ret,EMBPROPSIZE+2);
for(i=0; i < EMBPROPSIZE+2; ++i)
AJNEW0(ret[i]);
while(ajReadline(mfptr, &line))
{
ajStrRemoveWhiteExcess(&line);
p = ajStrGetPtr(line);
if(*p=='#' || *p=='!' || !*p)
continue;
if(firstline)
{
if(!ajStrPrefixC(line,"Mol"))
ajFatal("Incorrect format molwt file: '%S'", line);
firstline = ajFalse;
continue;
}
ajFmtScanS(line,"%S",&token);
ajStrFmtUpper(&token);
if(ajStrGetLen(token) != 1)
{
if(ajStrPrefixC(token,"HYDROGEN"))
{
if(ajFmtScanS(line,"%*s%lf%lf",
&ret[EMBPROPHINDEX]->average,
&ret[EMBPROPHINDEX]->mono) != 2)
ajFatal("Bad format hydrogen data line");
}
else if(ajStrPrefixC(token,"OXYGEN"))
{
if(ajFmtScanS(line,"%*s%lf%lf",
&ret[EMBPROPOINDEX]->average,
&ret[EMBPROPOINDEX]->mono) != 2)
ajFatal("Bad format oxygen data line");
}
else if(ajStrPrefixC(token,"WATER"))
{
if(ajFmtScanS(line,"%*s%lf%lf",
&ret[EMBPROPWINDEX]->average,
&ret[EMBPROPWINDEX]->mono) != 2)
ajFatal("Bad format water data line");
}
else
ajFatal("Unknown molwt token %S",token);
continue;
}
i = ajBasecodeToInt((ajint) *ajStrGetPtr(token));
if(i == 27)
ajFatal("Molwt file line doesn't begin with a single A->Z (%S)",
line);
n = ajFmtScanS(line,"%*s%lf%lf",
&ret[i]->average,
&ret[i]->mono);
if(n != 2)
ajFatal("Only %d columns in amino file - expected %d",n,3);
}
ajStrDel(&line);
ajStrDel(&token);
return ret;
}
/* @func embPropMolwtGetMolwt *************************************************
**
** Return molecular weight
**
** @param [r] prop [const EmbPPropMolwt] Input molecular weights object
** @return [float] molecular weight
**
** @release 6.0.0
** @@
******************************************************************************/
float embPropMolwtGetMolwt(const EmbPPropMolwt prop)
{
float ret;
ret = (float) prop->average; /* satisfy VC++ */
return ret;
}
/* @func embPropGetCharge *****************************************************
**
** Return charge value
**
** @param [r] prop [const EmbPPropAmino] Input properties object
** @return [float] charge
**
** @release 6.0.0
** @@
******************************************************************************/
float embPropGetCharge(const EmbPPropAmino prop)
{
return prop->charge;
}
/* @func embPropGetTiny *******************************************************
**
** Return tiny value
**
** @param [r] prop [const EmbPPropAmino] Input properties object
** @return [ajint] tiny
**
** @release 6.0.0
** @@
******************************************************************************/
ajint embPropGetTiny(const EmbPPropAmino prop)
{
return prop->tiny;
}
/* @func embPropGetSmall ******************************************************
**
** Return small value
**
** @param [r] prop [const EmbPPropAmino] Input properties object
** @return [ajint] small
**
** @release 6.0.0
** @@
******************************************************************************/
ajint embPropGetSmall(const EmbPPropAmino prop)
{
return prop->sm_all;
}
/* @func embPropGetAliphatic **************************************************
**
** Return aliphatic value
**
** @param [r] prop [const EmbPPropAmino] Input properties object
** @return [ajint] aliphatic
**
** @release 6.0.0
** @@
******************************************************************************/
ajint embPropGetAliphatic(const EmbPPropAmino prop)
{
return prop->aliphatic;
}
/* @func embPropGetAromatic ***************************************************
**
** Return aromatic value
**
** @param [r] prop [const EmbPPropAmino] Input properties object
** @return [ajint] aromatic
**
** @release 6.0.0
** @@
******************************************************************************/
ajint embPropGetAromatic(const EmbPPropAmino prop)
{
return prop->aromatic;
}
/* @func embPropGetNonpolar ***************************************************
**
** Return nonpolar value
**
** @param [r] prop [const EmbPPropAmino] Input properties object
** @return [ajint] nonpolar
**
** @release 6.0.0
** @@
******************************************************************************/
ajint embPropGetNonpolar(const EmbPPropAmino prop)
{
return prop->nonpolar;
}
/* @func embPropGetPolar ******************************************************
**
** Return polar value
**
** @param [r] prop [const EmbPPropAmino] Input properties object
** @return [ajint] polar
**
** @release 6.0.0
** @@
******************************************************************************/
ajint embPropGetPolar(const EmbPPropAmino prop)
{
return prop->polar;
}
/* @func embPropGetPve ********************************************************
**
** Return pve value
**
** @param [r] prop [const EmbPPropAmino] Input properties object
** @return [ajint] pve
**
** @release 6.0.0
** @@
******************************************************************************/
ajint embPropGetPve(const EmbPPropAmino prop)
{
return prop->pve;
}
/* @func embPropGetNve ********************************************************
**
** Return nve value
**
** @param [r] prop [const EmbPPropAmino] Input properties object
** @return [ajint] nve
**
** @release 6.0.0
** @@
******************************************************************************/
ajint embPropGetNve(const EmbPPropAmino prop)
{
return prop->nve;
}
/* @func embPropGetExtcoeff ***************************************************
**
** Return extcoeff value
**
** @param [r] prop [const EmbPPropAmino] Input properties object
** @return [ajint] extcoeff
**
** @release 6.0.0
** @@
******************************************************************************/
ajint embPropGetExtcoeff(const EmbPPropAmino prop)
{
return prop->extcoeff;
}
/* @func embPropCalcMolwt ****************************************************
**
** Calculate the molecular weight of a protein sequence
** This is a shell around embPropCalcMolwtMod using water as the modifier.
**
** @param [r] s [const char *] sequence
** @param [r] start [ajint] start position
** @param [r] end [ajint] end position
** @param [r] mwdata [EmbPPropMolwt const *] molecular weight data
** @param [r] mono [AjBool] true for monoisotopic values
**
** @return [double] molecular weight
**
** @release 1.0.0
** @@
******************************************************************************/
double embPropCalcMolwt(const char *s, ajint start, ajint end,
EmbPPropMolwt const *mwdata, AjBool mono)
{
double nmass = 0.;
double cmass = 0.;
nmass = (mono) ? mwdata[EMBPROPHINDEX]->mono :
mwdata[EMBPROPHINDEX]->average;
cmass = (mono) ? mwdata[EMBPROPOINDEX]->mono + nmass :
mwdata[EMBPROPOINDEX]->average + nmass;
return embPropCalcMolwtMod(s,start,end,mwdata,mono,nmass,cmass);
}
/* @func embPropCalcMolwtMod *************************************************
**
** Calculate the molecular weight of a protein sequence
** with chemically modified termini
**
** @param [r] s [const char *] sequence
** @param [r] start [ajint] start position
** @param [r] end [ajint] end position
** @param [r] mwdata [EmbPPropMolwt const *] molecular weight data
** @param [r] mono [AjBool] true for monoisotopic values
** @param [r] nmass [double] mass of the N-terminal group
** @param [r] cmass [double] mass of the C-terminal group
**
** @return [double] molecular weight
**
** @release 2.1.0
** @@
******************************************************************************/
double embPropCalcMolwtMod(const char *s, ajint start, ajint end,
EmbPPropMolwt const *mwdata, AjBool mono,
double nmass, double cmass)
{
const char *p;
double sum;
ajint i;
ajint len;
ajint idx;
double mw = 0.;
len = end - start + 1;
p = s + start;
sum = 0.0;
for(i=0;i<len;++i)
{
idx = ajBasecodeToInt(toupper((ajint)p[i]));
mw = (mono) ? mwdata[idx]->mono : mwdata[idx]->average;
sum += mw;
}
return sum + nmass + cmass;
}
/* @func embPropCalcMolextcoeff************************************************
**
** Calculate the molecular extinction coefficient of a protein sequence
**
** @param [r] s [const char *] sequence
** @param [r] start [ajint] start position
** @param [r] end [ajint] end position
** @param [r] cystine [AjBool] Treat C residues as cystine pairs
** @param [r] aadata [EmbPPropAmino const *] amino acid data
**
** @return [double] molar extinction coefficient
**
** @release 2.8.0
** @@
******************************************************************************/
double embPropCalcMolextcoeff(const char *s, ajint start, ajint end,
AjBool cystine, EmbPPropAmino const *aadata)
{
const char *p;
char aa;
double sum;
ajint i;
ajint len;
ajuint havecystine = 0;
len = end-start+1;
p = s+start;
sum = 0.0;
for(i=0;i<len;++i)
{
aa = toupper((ajint)p[i]);
if(aa == 'C')
{
if(!cystine) continue;
havecystine++;
if(havecystine % 2)
continue;
}
sum += (double) aadata[ajBasecodeToInt(aa)]->extcoeff;
}
return sum;
}
/* @func embPropCharToThree **************************************************
**
** Return 3 letter amino acid code A=Ala B=Asx C=Cys etc
**
** @param [r] c [char] integer code
**
** @return [const char*] three letter amino acid code
**
** @release 1.0.0
** @@
******************************************************************************/
const char* embPropCharToThree(char c)
{
return embPropIntToThree(ajBasecodeToInt(c));
}
/* @func embPropIntToThree ***************************************************
**
** Return 3 letter amino acid code 0=Ala 1=Asx 2=Cys etc
**
** @param [r] c [ajint] integer code
**
** @return [const char*] three letter amino acid code
**
** @release 1.0.0
** @@
******************************************************************************/
const char* embPropIntToThree(ajint c)
{
static const char *tab[]=
{
"Ala","Asx","Cys","Asp","Glu","Phe","Gly","His","Ile","---","Lys",
"Leu","Met","Asn","---","Pro","Gln","Arg","Ser","Thr","---",
"Val","Trp","Xaa","Tyr","Glx"
};
return tab[c];
}
/* @func embPropCalcFragments ************************************************
**
** Read amino acd properties
**
** @param [r] s [const char *] sequence
** @param [r] n [ajint] "enzyme" number
** @param [w] l [AjPList *] list to push hits to
** @param [w] pa [AjPList *] list to push partial hits to
** @param [r] unfavoured [AjBool] allow unfavoured cuts
** @param [r] overlap [AjBool] show overlapping partials
** @param [r] allpartials [AjBool] show all possible partials
** @param [w] ncomp [ajint *] number of complete digest fragments
** @param [w] npart [ajint *] number of partial digest fragments
** @param [w] rname [AjPStr *] name of reagent
** @param [r] nterm [AjBool] nterm ragging
** @param [r] cterm [AjBool] cterm ragging
** @param [r] dorag [AjBool] true if ragging
** @param [r] mwdata [EmbPPropMolwt const *] molecular weight data
** @param [r] mono [AjBool] true for monoisotopic weights
**
** @return [void]
**
** @release 1.0.0
** @@
******************************************************************************/
void embPropCalcFragments(const char *s, ajint n,
AjPList *l, AjPList *pa,
AjBool unfavoured, AjBool overlap,
AjBool allpartials, ajint *ncomp, ajint *npart,
AjPStr *rname, AjBool nterm, AjBool cterm,
AjBool dorag, EmbPPropMolwt const *mwdata,
AjBool mono)
{
static const char *PROPENZReagent[]=
{
"Trypsin","Lys-C","Arg-C","Asp-N","V8-bicarb","V8-phosph",
"Chymotrypsin","CNBr"
};
static const char *PROPENZSite[]=
{
"KR","K","R","D","E","DE","FYWLM","M"
};
static const char *PROPENZAminoCarboxyl[]=
{
"CC","C","C","N","C","CC","CCCCC","C"
};
static const char *PROPENZUnfavoured[]=
{
"KRIFLP","P","P","","KREP","P","P",""
};
ajint i;
ajint j;
ajint lim;
ajint len;
AjPList t;
EmbPPropFrag fr;
ajint *begsa = NULL;
ajint *endsa = NULL;
double molwt;
double *molwtsa = NULL;
AjBool *afrag = NULL;
ajint mark;
ajint bwp;
ajint ewp;
ajint *ival;
ajint defcnt;
ajint it;
ajint st = 0;
ajint mt = 0;
ajint et = 0;
ajStrAssignC(rname,PROPENZReagent[n]);
defcnt = 0;
len = (ajint) strlen(s);
t = ajListNew(); /* Temporary list */
/* First get all potential cut points */
for(i=0;i<len;++i)
{
if(!strchr(PROPENZSite[n],s[i]))
continue;
if(len==i+1)
continue;
if(strchr(PROPENZUnfavoured[n],s[i+1])
&& !unfavoured)
continue;
AJNEW0(ival);
*ival = i;
ajListPushAppend(t,(void *)ival);
++defcnt;
}
if(defcnt)
{
AJCNEW(begsa,(defcnt+1));
AJCNEW(endsa,(defcnt+1));
AJCNEW(molwtsa,(defcnt+1));
AJCNEW(afrag,(defcnt+1));
}
for(i=0;i<defcnt;++i) /* Pop them into a temporary array */
{
ajListPop(t,(void **)&ival);
endsa[i] = *ival;
AJFREE(ival);
}
mark = 0;
for(i=0;i<defcnt;++i) /* Work out true starts, ends and molwts */
{
bwp = mark;
ewp = endsa[i];
if(strchr(PROPENZAminoCarboxyl[n],'N'))
--ewp;
molwt=embPropCalcMolwt(s,bwp,ewp,mwdata,mono);
if(n==PROPENZCNBR)
molwt -= (17.045 + 31.095);
begsa[i] = mark;
endsa[i] = ewp;
molwtsa[i] = molwt;
afrag[i] = ajFalse;
mark = ewp+1;
}
if(defcnt) /* Special treatment for last fragment */
{
molwt = embPropCalcMolwt(s,mark,len-1,mwdata,mono);
if(n==PROPENZCNBR)
molwt -= (17.045 + 31.095);
begsa[i] = mark;
endsa[i] = len-1;
molwtsa[i] = molwt;
afrag[i] = ajFalse;
++defcnt;
}
/* Push the hits */
for(i=0;i<defcnt;++i)
{
if(dorag)
{
st = begsa[i];
et = endsa[i];
for(it=st+RAG_MINPEPLEN-1; it < et; ++it)
{
AJNEW0(fr);
fr->start = st;
fr->end = it;
fr->molwt = embPropCalcMolwt(s,st,it,mwdata,mono);
if(n == PROPENZCNBR)
fr->molwt -= (17.045 + 31.095);
fr->isfrag = ajTrue;
ajListPush(*l,(void *)fr);
}
}
AJNEW0(fr);
fr->start = begsa[i];
fr->end = endsa[i];
fr->molwt = molwtsa[i];
fr->isfrag = afrag[i];
ajListPush(*l,(void *) fr);
if(dorag && nterm)
for(it=st+1; it < et-RAG_MINPEPLEN+2; ++it)
{
AJNEW0(fr);
fr->start = it;
fr->end = et;
fr->molwt = embPropCalcMolwt(s,it,et,mwdata,mono);
if(n == PROPENZCNBR)
fr->molwt -= (17.045 + 31.095);
fr->isfrag = ajTrue;
ajListPush(*l,(void *)fr);
}
}
if(!dorag)
ajListSort(*l, &propFragCompare);
*ncomp = defcnt;
/* Now deal with overlaps */
*npart = 0;
lim = defcnt -1;
if(overlap && !allpartials)
{
for(i=0;i<lim;++i)
{
if(dorag)
{
st = begsa[i];
mt = endsa[i];
et = endsa[i+1];
if(cterm)
for(it=mt+1; it < et; ++it)
{
AJNEW0(fr);
fr->start = st;
fr->end = it;
fr->molwt = embPropCalcMolwt(s,st,it,mwdata,mono);
if(n == PROPENZCNBR)
fr->molwt -= (17.045 + 31.095);
fr->isfrag = ajTrue;
ajListPush(*l,(void *)fr);
}
}
AJNEW0(fr);
fr->isfrag = ajTrue;
fr->molwt = embPropCalcMolwt(s,begsa[i],endsa[i+1],mwdata,mono);
if(n==PROPENZCNBR)
fr->molwt -= (17.045 + 31.095);
fr->start = begsa[i];
fr->end = endsa[i+1];
ajListPush(*pa,(void *)fr);
++(*npart);
if(dorag && nterm)
for(it=st+1; it<mt; ++it)
{
AJNEW0(fr);
fr->start = it;
fr->end = et;
fr->molwt = embPropCalcMolwt(s,it,et,mwdata,mono);
if(n == PROPENZCNBR)
fr->molwt -= (17.045 + 31.095);
fr->isfrag = ajTrue;
ajListPush(*l,(void *)fr);
}
}
if(*npart) /* Remove complete sequence */
{
--(*npart);
ajListPop(*pa,(void **)&fr);
}
if(!dorag)
ajListSort(*pa, &propFragCompare);
}
if(allpartials)
{
lim = defcnt;
for(i=0;i<lim;++i)
for(j=i+1;j<lim;++j)
{
AJNEW0(fr);
fr->isfrag = ajTrue;
fr->molwt = embPropCalcMolwt(s,begsa[i],endsa[j],mwdata,mono);
if(n==PROPENZCNBR)
fr->molwt -= (17.045 + 31.095);
fr->start = begsa[i];
fr->end = endsa[j];
ajListPush(*pa,(void *)fr);
++(*npart);
}
if(*npart) /* Remove complete sequence */
{
--(*npart);
ajListPop(*pa,(void **)&fr);
}
if(!dorag)
ajListSort(*pa, &propFragCompare);
}
if(defcnt)
{
AJFREE(molwtsa);
AJFREE(endsa);
AJFREE(begsa);
AJFREE(afrag);
}
ajListFree(&t);
return;
}
/* @funcstatic propFragCompare ***********************************************
**
** compare two molecular weight AjPFrag list elements for sorting
**
** @param [r] a [const void*] First element
** @param [r] b [const void*] Second element
**
** @return [ajint] 0=equal +ve=(a greater than b) -ve=(a less than b)
**
** @release 1.0.0
** @@
******************************************************************************/
static ajint propFragCompare(const void *a, const void *b)
{
return (ajint)((*(EmbPPropFrag const *)b)->molwt -
(*(EmbPPropFrag const *)a)->molwt);
}
/* @func embPropProtGaps ******************************************************
**
** Creates a string of a protein sequence which has been padded out with
** two spaces after every residue to aid aligning a translation under a
** nucleic sequence
**
** @param [u] seq [AjPSeq] protein sequence to add spaces into
** @param [r] pad [ajint] number of spaces to insert at the start of the result
** @return [AjPStr] New string with the padded sequence
**
** @release 1.0.0
** @@
******************************************************************************/
AjPStr embPropProtGaps(AjPSeq seq, ajint pad)
{
const char *p;
AjPStr temp;
ajint i;
temp = ajStrNewRes(ajSeqGetLen(seq)*3 + pad+1);
/* put any required padding spaces at the start */
for(i=0; i<pad; i++)
ajStrAppendC(&temp, " ");
for(p=ajSeqGetSeqC(seq); *p; p++)
{
ajStrAppendK(&temp, *p);
ajStrAppendC(&temp, " ");
}
return temp;
}
/* @func embPropProt1to3 ******************************************************
**
** Creates a a 3-letter sequence protein string from single-letter sequence
** EMBOSS is bad at reading 3-letter sequences, but this may be useful
** when displaying translations.
**
** @param [u] seq [AjPSeq] protein sequence to convert to 3-letter codes
** @param [r] pad [ajint] number of spaces to insert at the start of the result
** @return [AjPStr] string containing 3-letter protein sequence
**
** @release 1.0.0
** @@
******************************************************************************/
AjPStr embPropProt1to3(AjPSeq seq, ajint pad)
{
const char *p;
const char *p3;
AjPStr temp;
ajint i;
temp = ajStrNewRes(ajSeqGetLen(seq)*3 + pad+1);
/* put any required padding spaces at the start */
for(i=0; i<pad; i++)
ajStrAppendC(&temp, " ");
for(p=ajSeqGetSeqC(seq); *p; p++)
{
if(*p == '*')
ajStrAppendC(&temp, "***");
else if(*p == '.')
ajStrAppendC(&temp, "...");
else if(*p == '-')
ajStrAppendC(&temp, "---");
else if(!isalpha((ajint)*p))
ajStrAppendC(&temp, "???");
else
{
p3 = embPropCharToThree(*p);
ajStrAppendK(&temp, *p3);
ajStrAppendK(&temp, *(p3+1));
ajStrAppendK(&temp, *(p3+2));
}
}
return temp;
}
/* @func embPropProt1to3Rev ***************************************************
**
** Creates a a 3-letter sequence protein string from single-letter sequence
** in the reverse direction.
** EMBOSS is bad at reading 3-letter sequences, but this may be useful
** when displaying translations.
**
** @param [u] seq [AjPSeq] protein sequence to convert to 3-letter codes
** @param [r] pad [ajint] number of characters to skip at the start
** of the result
** @return [AjPStr] string containing 3-letter protein sequence
**
** @release 6.1.0
** @@
******************************************************************************/
AjPStr embPropProt1to3Rev(AjPSeq seq, ajint pad)
{
const char *p;
const char *p3;
AjPStr temp;
ajint i=0;
temp = ajStrNewRes(ajSeqGetLen(seq)*3 + pad+1);
for(p=ajSeqGetSeqC(seq); *p; p++)
{
if(*p == '*')
ajStrAppendC(&temp, "***");
else if(*p == '.')
ajStrAppendC(&temp, "...");
else if(*p == '-')
ajStrAppendC(&temp, "---");
else if(!isalpha((ajint)*p))
ajStrAppendC(&temp, "???");
else
{
p3 = embPropCharToThree(*p);
if(i++)
{
ajStrAppendK(&temp, *(p3+2));
ajStrAppendK(&temp, *(p3+1));
ajStrAppendK(&temp, *p3);
}
else
{
if(pad >= 2)
ajStrAppendK(&temp, *(p3+2));
if(pad >= 1)
ajStrAppendK(&temp, *(p3+1));
ajStrAppendK(&temp, *p3);
}
}
}
return temp;
}
/* @func embPropPurine ********************************************************
**
** Returns ajTrue if the input base is a Purine.
** Returns ajFalse if it is a Pyrimidine or it is ambiguous.
**
** @param [r] base [char] base
** @return [AjBool] return ajTrue if this is a Purine
**
** @release 1.4.3
** @@
******************************************************************************/
AjBool embPropPurine(char base)
{
if(strchr(propPurines, (ajint)base))
return ajTrue;
return ajFalse;
}
/* @func embPropPyrimidine ****************************************************
**
** Returns ajTrue if the input base is a Pyrimidine.
** Returns ajFalse if it is a Purine or it is ambiguous.
**
** @param [r] base [char] base
** @return [AjBool] return ajTrue if this is a Pyrimidine
**
** @release 1.4.3
** @@
******************************************************************************/
AjBool embPropPyrimidine(char base)
{
if(strchr(propPyrimidines, (ajint)base))
return ajTrue;
return ajFalse;
}
/* @func embPropTransversion **************************************************
**
** Returns ajTrue if the input two bases have undergone a tranversion.
** (Pyrimidine to Purine, or vice versa)
** Returns ajFalse if this is not a transversion or it can not be determined
** (e.g. no change A->A, transition C->T, unknown A->N)
**
** @param [r] base1 [char] first base
** @param [r] base2 [char] second base
** @return [AjBool] return ajTrue if this is a transversion
**
** @release 1.4.3
** @@
******************************************************************************/
AjBool embPropTransversion(char base1, char base2)
{
AjBool bu1;
AjBool bu2;
AjBool by1;
AjBool by2;
bu1 = embPropPurine(base1);
bu2 = embPropPurine(base2);
by1 = embPropPyrimidine(base1);
by2 = embPropPyrimidine(base2);
ajDebug("base1 py = %b, pu = %b", bu1, by1);
ajDebug("base2 py = %b, pu = %b", bu2, by2);
/* not a purine or a pyrimidine - ambiguous - return ajFalse */
if(!bu1 && !by1)
return ajFalse;
if(!bu2 && !by2)
return ajFalse;
ajDebug("embPropTransversion result = %d", (bu1 != bu2));
return (bu1 != bu2);
}
/* @func embPropTransition ****************************************************
**
** Returns ajTrue if the input two bases have undergone a transition.
** (Pyrimidine to Pyrimidine, or Purine to Purine)
** Returns ajFalse if this is not a transition or it can not be determined
** (e.g. no change A->A, transversion A->T, unknown A->N)
**
** @param [r] base1 [char] first base
** @param [r] base2 [char] second base
** @return [AjBool] return ajTrue if this is a transition
**
** @release 1.4.3
** @@
******************************************************************************/
AjBool embPropTransition(char base1, char base2)
{
AjBool bu1;
AjBool bu2;
AjBool by1;
AjBool by2;
bu1 = embPropPurine(base1);
bu2 = embPropPurine(base2);
by1 = embPropPyrimidine(base1);
by2 = embPropPyrimidine(base2);
ajDebug("base1 py = %b, pu = %b", bu1, by1);
ajDebug("base2 py = %b, pu = %b", bu2, by2);
/* not a purine or a pyrimidine - ambiguous - return ajFalse */
if(!bu1 && !by1)
return ajFalse;
if(!bu2 && !by2)
return ajFalse;
/* no change - return ajFalse */
if(tolower((int)base1) == tolower((int)base2))
return ajFalse;
/* U to T is not a transition */
if(tolower((int)base1) == 't' && tolower((int)base2) == 'u')
return ajFalse;
if(tolower((int)base1) == 'u' && tolower((int)base2) == 't')
return ajFalse;
/* C to Y, T to Y, A to R, G to R - ambiguous - not a transition */
if(bu1 && tolower((int)base2) == 'r')
return ajFalse;
if(bu2 && tolower((int)base1) == 'r')
return ajFalse;
if(by1 && tolower((int)base2) == 'y')
return ajFalse;
if(by2 && tolower((int)base1) == 'y')
return ajFalse;
ajDebug("embPropTransition result = %b", (bu1 == bu2));
return (bu1 == bu2);
}
/* @func embPropFixF **********************************************************
**
** Fix for missing properties data in a float array
**
** @param [u] matrix [float[]] Matrix
** @param [r] missing [float] Missing data value
** @return [void]
**
** @release 4.1.0
******************************************************************************/
void embPropFixF(float matrix[], float missing)
{
ajint i;
float mtot = 0.0;
float dtot = 0.0;
for(i=0;i<26;i++)
{
if(matrix[i] == missing)
{
switch (i)
{
case 1: /* B: D + N */
matrix[i] = ((matrix[3] * dayhoff[3]) +
(matrix[13] * dayhoff[13])) /
(dayhoff[3] + dayhoff[13]);
ajDebug("Missing %d '%c' %f %f => %f\n",
i, dayhoffstr[i], matrix[3], matrix[13], matrix[i]);
break;
case 9: /* J: I + L */
matrix[i] = ((matrix[8] * dayhoff[8]) +
(matrix[11] * dayhoff[11])) /
(dayhoff[8] + dayhoff[11]);
ajDebug("Missing %d '%c' %f %f => %f\n",
i, dayhoffstr[i], matrix[8], matrix[11], matrix[i]);
break;
case 25: /* Z: E + Q */
matrix[i] = ((matrix[4] * dayhoff[4]) +
(matrix[16] * dayhoff[16])) /
(dayhoff[4] + dayhoff[16]);
ajDebug("Missing %d '%c' %f %f => %f\n",
i, dayhoffstr[i], matrix[4], matrix[16], matrix[i]);
break;
default:
ajDebug("Missing %d '%c' unknown\n", i, dayhoffstr[i]);
break;
}
}
else
{
if(dayhoff[i] > 0.0)
{
dtot += dayhoff[i];
mtot += matrix[i] * dayhoff[i];
}
}
}
mtot /= dtot;
for(i=0;i<26;i++)
if(matrix[i] == missing) /* X:average O,U:X */
{
matrix[i] = mtot;
ajDebug("Missing %d '%c' unknown %f\n",
i, dayhoffstr[i], matrix[i]);
}
return;
}
/* @func embPropNormalF *******************************************************
**
** Normalize data values in a float array to have mean 0.0 and
** standard deviation 1.0
**
** Assume the data values represent all values for a population
** (e.g. values for all standard amino acids) and use
** new value = (old value - mean) / standard deviation
**
** @param [u] matrix [float[]] Matrix
** @param [r] missing [float] Missing data value
** @return [void]
**
** @release 6.1.0
******************************************************************************/
void embPropNormalF(float matrix[], float missing)
{
ajuint i;
double count = 0.0;
double total = 0.0;
double sumsq = 0.0;
double sigma = 0.0;
double mean = 0.0;
const char* alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for(i=0;i<26;i++)
if(matrix[i] != missing)
{
count += 1.0;
total += matrix[i];
sumsq += matrix[i] * matrix[i];
}
if(!count)
return;
sigma = sqrt(count*sumsq - total*total)/count;
mean = total/count;
ajDebug("matrix normalize mean: %.3f sigma: %.3f\n", mean, sigma);
for(i=0;i<26;i++)
if(matrix[i] != missing)
{
ajDebug("matrix[%u] %c %.3f", i, alphabet[i], matrix[i]);
matrix[i] = (float) ((matrix[i] - mean) / sigma);
ajDebug(" => %.3f\n", matrix[i]);
}
return;
}
/* @func embPropAminoDel ******************************************************
**
** Delete array of amino acid properties
**
** @param [w] thys [EmbPPropAmino**] amino acid properties
** @return [void]
**
** @release 6.0.0
******************************************************************************/
void embPropAminoDel(EmbPPropAmino **thys)
{
EmbPPropAmino *pthis = NULL;
ajuint i;
pthis = *thys;
for(i=0; i < EMBPROPSIZE; ++i)
AJFREE(pthis[i]);
AJFREE(pthis);
*thys = NULL;
return;
}
/* @func embPropMolwtDel ******************************************************
**
** Delete array of molwts
**
** @param [w] thys [EmbPPropMolwt**] molwts
** @return [void]
**
** @release 6.0.0
******************************************************************************/
void embPropMolwtDel(EmbPPropMolwt **thys)
{
EmbPPropMolwt *pthis = NULL;
ajuint i;
pthis = *thys;
for(i=0; i < EMBPROPSIZE + 2; ++i)
AJFREE(pthis[i]);
AJFREE(pthis);
*thys = NULL;
return;
}
| 22.535669 | 79 | 0.525565 | [
"object"
] |
01e54657abbb7aa8ba1ae3b290cbcb61d0b60ff2 | 6,055 | w | C | UI2/chat/bex5/funcsDialog/dialog/funcList.w | kaven-lu/dangchat-client | 08300cbcbc66ee11ba70858717ac8cf2b03b6d57 | [
"Apache-2.0"
] | null | null | null | UI2/chat/bex5/funcsDialog/dialog/funcList.w | kaven-lu/dangchat-client | 08300cbcbc66ee11ba70858717ac8cf2b03b6d57 | [
"Apache-2.0"
] | null | null | null | UI2/chat/bex5/funcsDialog/dialog/funcList.w | kaven-lu/dangchat-client | 08300cbcbc66ee11ba70858717ac8cf2b03b6d57 | [
"Apache-2.0"
] | null | null | null | <?xml version="1.0" encoding="utf-8"?>
<div xmlns="http://www.w3.org/1999/xhtml" xid="window" class="window" component="$UI/system/components/justep/window/window"
sysParam="false">
<div component="$UI/system/components/justep/model/model" xid="model" style="height:auto;left:472px;top:72px;"
onParamsReceive="modelParamsReceive">
<div component="$UI/system/components/justep/data/data" xid="funcsData"
idColumn="fID" autoLoad="false" limit="-1" confirmDelete="false" confirmRefresh="false"
onCustomRefresh="funcsDataCustomRefresh">
<column label="ID" name="fID" type="String" xid="default1"></column>
<column label="功能图标" name="fIcon" type="String" xid="default2"></column>
<column label="功能图标" name="fImgUrl" type="String" xid="xid4"></column>
<column label="标题" name="fTitle" type="String" xid="default3"></column>
<column label="功能url" name="fUrl" type="String" xid="default5"></column>
<column label="process" name="fProcess" type="String" xid="xid1"></column>
<column label="activity" name="fActivity" type="String" xid="xid2"></column>
<data xid="default10">[]</data>
<column name="fIsFunc" type="Boolean" xid="xid3"></column>
<column name="selected" type="Boolean" xid="xid5"></column>
<column name="fTitlePY" type="String" xid="xid6"></column>
<column name="fIconColor" type="String" xid="xid7"></column></div>
</div>
<div component="$UI/system/components/justep/panel/panel" class="x-panel x-full"
xid="panel1">
<div class="x-panel-top" xid="top1">
<div component="$UI/system/components/justep/titleBar/titleBar" class="x-titlebar"
xid="titleBar" title="我的应用">
<div class="x-titlebar-left" xid="div1">
<a component="$UI/system/components/justep/button/button" class="btn btn-link btn-only-icon"
xid="btnClose" onClick="{"operation":"window.close"}">
<i xid="i1"/>
<span xid="span1"/>
</a>
</div>
<div class="x-titlebar-title" xid="div2">我的应用</div>
<div class="x-titlebar-right reverse" xid="div3">
<a component="$UI/system/components/justep/button/button" class="btn btn-link btn-only-icon hide"
xid="btnOK" icon="icon-checkmark-round" onClick="btnOKClick" bind-css="{hide:'runFunc'===mode.get()}">
<i xid="i2" class="icon-checkmark-round"/>
<span xid="span2"/>
</a>
</div>
</div>
</div>
<div class="x-panel-content" xid="content1">
<div component="$UI/system/components/justep/panel/panel" class="x-panel x-full"
xid="panel2">
<div class="x-panel-top" xid="top2">
<div class="x-query-input x-flex">
<i class="icon-android-search x-icon-lg"/>
<input type="text" class="x-flex1" data-bind="value:queryText,valueUpdate: 'input'"/>
<i class="icon-close-circled x-icon-lg x-cls-filter hide" bind-css="{hide:!queryText.get()}"
bind-click="clsQueryText"/>
</div>
</div>
<div class="x-panel-content" xid="content2">
<div class="x-scroll" component="$UI/system/components/justep/scrollView/scrollView"
xid="funcs">
<div class="x-content-center x-pull-down container" xid="div4">
<i class="x-pull-down-img glyphicon x-icon-pull-down" xid="i7"/>
<span class="x-pull-down-label" xid="span6">下拉刷新...</span>
</div>
<div class="x-scroll-content" xid="div7">
<div xid="funcsList" class="x-list" component="$UI/system/components/justep/list/list"
data="funcsData" limit="20" filter="$model.funcFilter($row)">
<ul class="x-list-template" style="padding-top:6px;">
<li class="media" style="padding-left:6px; padding-right:6px;">
<div bind-if="!val('fIsFunc')">
<div component="$UI/system/components/justep/output/output"
class="x-output x-title" xid="output1" bind-ref="ref('fTitle')"/>
</div>
<div bind-if="val('fIsFunc')" bind-css="{media:val('fIsFunc'),'x-currentRow':$object===$model.funcsData.getCurrentRow()}">
<div class="pull-left x-func-checkbox" bind-if="'selectFunc'===$model.mode.get()">
<span component="$UI/system/components/justep/button/checkbox"
class="x-checkbox" bind-ref="ref('selected')"/>
</div>
<div class="media-body" bind-click="rowClick">
<div class="media x-func-body">
<div class="x-blob x-blob-radius pull-left media-object x-func-icon"
bind-if="val('fImgUrl')" bind-visible="val('fImgUrl')">
<img class="x-blob-img x-autofill" bind-attr-src="$model.getImageUrl($object)"/>
</div>
<div class="x-blob x-blob-radius pull-left media-object x-func-icon"
bind-if="val('fIcon')" bind-visible="val('fIcon')">
<i bind-attr-class="val('fIcon')" style="font-size: 32px;" bind-style="{color:val('fIconColor')}"/>
</div>
<div class="media-body x-func-info-body">
<h4 class="media-heading" bind-text="ref('fTitle')"/>
<div bind-text="ref('fContent')"/>
</div>
</div>
</div>
</div>
</li>
</ul>
</div>
</div>
<div class="x-content-center x-pull-up" xid="div8">
<span class="x-pull-up-label" xid="span7">加载更多...</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
| 56.588785 | 143 | 0.543848 | [
"object",
"model"
] |
01e5b70f4426732af14cfde8450ba4d70f104470 | 6,122 | h | C | include/ordo.h | TomCrypto/Ordo | 76416946a16900143af7e06635eb4f158bd6029d | [
"BSD-2-Clause-FreeBSD"
] | 1 | 2015-09-29T09:32:22.000Z | 2015-09-29T09:32:22.000Z | include/ordo.h | TomCrypto/Ordo | 76416946a16900143af7e06635eb4f158bd6029d | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | include/ordo.h | TomCrypto/Ordo | 76416946a16900143af7e06635eb4f158bd6029d | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | /*===-- ordo.h -----------------------------------------*- PUBLIC -*- H -*-===*/
/**
*** @file
*** @brief Wrapper
***
*** This is the highest-level API for Ordo, which forgoes the use of
*** cryptographic contexts completely, resulting in more concise code at the
*** cost of reduced flexibility - in other words, if you can afford to use
*** them, you probably want to do so.
***
*** Usage snippet (compare to snippet in \c digest.h):
***
*** @code
*** const char x[] = "Hello, world!";
*** unsigned char out[32]; // 256 bits
*** int err = ordo_digest(HASH_SHA256, 0, x, strlen(x), out);
*** if (err) printf("Error encountered!\n");
*** // out = 315f5bdb76d0...
*** @endcode
***
*** Some specialized headers are *not* included by this header - these are the
*** endianness header & all primitive headers (their parameters are included),
*** if you need their functionality please include them explicitly.
**/
/*===----------------------------------------------------------------------===*/
#ifndef ORDO_ORDO_H
#define ORDO_ORDO_H
/** @cond **/
#include "ordo/common/interface.h"
/** @endcond **/
#include "ordo/common/version.h"
#include "ordo/common/limits.h"
#include "ordo/common/error.h"
#include "ordo/enc/enc_stream.h"
#include "ordo/enc/enc_block.h"
#include "ordo/auth/hmac.h"
#include "ordo/kdf/hkdf.h"
#include "ordo/kdf/pbkdf2.h"
#include "ordo/misc/utils.h"
#include "ordo/misc/os_random.h"
#include "ordo/misc/curve25519.h"
#ifdef __cplusplus
extern "C" {
#endif
/*===----------------------------------------------------------------------===*/
/** Encrypts or decrypts data using a block cipher with a mode of operation.
***
*** @param [in] cipher The block cipher to use.
*** @param [in] cipher_params The block cipher parameters.
*** @param [in] mode The mode of operation to use.
*** @param [in] mode_params The mode of operation parameters.
*** @param [in] direction 1 for encryption, 0 for decryption.
*** @param [in] key The cryptographic key to use.
*** @param [in] key_len The length in bytes of the key.
*** @param [in] iv The initialization vector.
*** @param [in] iv_len The length in bytes of the IV.
*** @param [in] in The input plaintext/ciphertext buffer.
*** @param [in] in_len The length of the input buffer.
*** @param [out] out The output ciphertext/plaintext buffer.
*** @param [out] out_len The length of the output buffer.
***
*** @returns \c #ORDO_SUCCESS on success, else an error code.
***
*** @remarks The \c out buffer should be large enough to accomodate the entire
*** ciphertext which may be larger than the plaintext if a mode where
*** padding is enabled and used, see padding notes in \c enc_block.h.
**/
ORDO_PUBLIC
int ordo_enc_block(prim_t cipher, const void *cipher_params,
prim_t mode, const void *mode_params,
int direction,
const void *key, size_t key_len,
const void *iv, size_t iv_len,
const void *in, size_t in_len,
void *out, size_t *out_len);
/** Encrypts or decrypts data using a stream cipher.
***
*** @param [in] cipher The stream cipher to use.
*** @param [in] params The stream cipher parameters.
*** @param [in,out] inout The plaintext or ciphertext buffer.
*** @param [in] len The length, in bytes, of the buffer.
*** @param [in] key The cryptographic key to use.
*** @param [in] key_len The length, in bytes, of the key.
***
*** @returns \c #ORDO_SUCCESS on success, else an error code.
***
*** @remarks Stream ciphers do not strictly speaking require an initialization
*** vector - if such a feature is needed, it is recommended to use a
*** key derivation function to derive an encryption key from a master
*** key using a pseudorandomly generated nonce.
***
*** @remarks Encryption is always done in place. If you require out-of-place
*** encryption, make a copy of the plaintext prior to encryption.
***
*** @warning By design, encryption and decryption are equivalent for stream
*** ciphers - an implication is that encrypting a message twice using
*** the same key yields the original message.
**/
ORDO_PUBLIC
int ordo_enc_stream(prim_t cipher, const void *params,
const void *key, size_t key_len,
void *inout, size_t len);
/** Calculates the digest of a buffer using any hash function.
***
*** @param [in] hash The hash function to use.
*** @param [in] params The hash function parameters.
*** @param [in] in The input buffer to hash.
*** @param [in] in_len The length in bytes of the buffer.
*** @param [out] digest The output buffer for the digest.
***
*** @returns \c #ORDO_SUCCESS on success, else an error code.
**/
ORDO_PUBLIC
int ordo_digest(prim_t hash, const void *params,
const void *in, size_t in_len,
void *digest);
/** Calculates the HMAC fingerprint of a buffer using any hash function.
***
*** @param [in] hash The hash function to use.
*** @param [in] params The hash function parameters.
*** @param [in] key The key to use for authentication.
*** @param [in] key_len The length in bytes of the key.
*** @param [in] in The input buffer to authenticate.
*** @param [in] in_len The length, in bytes, of the input buffer.
*** @param [out] fingerprint The output buffer for the fingerprint.
***
*** @returns \c #ORDO_SUCCESS on success, else an error code.
**/
ORDO_PUBLIC
int ordo_hmac(prim_t hash, const void *params,
const void *key, size_t key_len,
const void *in, size_t in_len,
void *fingerprint);
/*===----------------------------------------------------------------------===*/
#ifdef __cplusplus
}
#endif
#endif
| 39.496774 | 80 | 0.59327 | [
"vector"
] |
01efe7814b2d2b979568ec4937348262181896bb | 4,645 | h | C | features/vtkITKDescriptorPointSetToPolyDataFilter.h | msofka/LRR | 8c04ab9d27980c98a201943c1fe46e7e451df367 | [
"Apache-2.0"
] | 2 | 2018-01-09T00:33:42.000Z | 2018-01-09T00:33:53.000Z | features/vtkITKDescriptorPointSetToPolyDataFilter.h | msofka/LRR | 8c04ab9d27980c98a201943c1fe46e7e451df367 | [
"Apache-2.0"
] | null | null | null | features/vtkITKDescriptorPointSetToPolyDataFilter.h | msofka/LRR | 8c04ab9d27980c98a201943c1fe46e7e451df367 | [
"Apache-2.0"
] | null | null | null | /*=========================================================================
Program: Visualization Toolkit
Module: $RCSfile: vtkITKDescriptorPointSetToPolyDataFilter.h,v $
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME vtkITKDescriptorPointSetToPolyDataFilter
// .SECTION Description Convert ITK PointSet to VTK PolyData format for saving
// author: Michal Sofka, Rensselaer Polytechnic Institute (RPI)
// sofka at cs dot rpi dot edu
// date: 10/25/2007
// .SECTION See Also
// vtkContourFilter vtkCutter vtkEdgePoints vtkExtractEdges
// vtkGeometryFilter vtkGlyph3D vtkHedgeHog vtkHyperStreamline
// vtkMaskPoints vtkOutlineFilter vtkStreamer vtkTensorGlyph
// vtkThresholdPoints vtkVectorTopology
#ifndef __vtkITKDescriptorPointSetToPolyDataFilter_h
#define __vtkITKDescriptorPointSetToPolyDataFilter_h
#include "vtkPolyDataSource.h"
#include "vtkDataObject.h"
#include "itkPointSet.h"
#include "itkDescriptorMeshFilter.h"
// Point attributes that are stored with each coordinate in the mesh
// (PointSet Pixel type in the PointSet, Mesh and related classes)
//namespace itk {
class DescriptorAttribute;
//}
// In order to be a child of vtkPolyDataSource, input must be of vtkObject type
// so it is not as easy to connect the ITK and VTK filters.
//
// Workaround here is to create a VTK wrapper around an ITK PointSet
// and mimick the pipeline with SetInput and GetOutput methods.
//
// It might be possible to hide this mechanism by including vtkDescriptorAttributeSet
// object in vtkITKDescriptorPointSetToPolyDataFilter
// and providing SetInput( PointSetPointer const & PointSet ).
class vtkDescriptorAttributeSet : public vtkDataObject
{
public:
static vtkDescriptorAttributeSet *New();// { return static_cast<vtkDescriptorAttributeSet*>(new itk::PointSet< itk::DescriptorAttribute >); };
vtkTypeRevisionMacro(vtkDescriptorAttributeSet,vtkDataObject);
typedef itk::PointSet< itk::DescriptorAttribute > PointSetType;
typedef PointSetType::Pointer PointSetPointer;
PointSetType::PointDataContainer *
GetPointData(void) const
{
return m_PointSet->GetPointData();
}
PointSetType::PointsContainer *
GetPoints(void) const
{
return m_PointSet->GetPoints();
}
void
SetInput( PointSetPointer const & PointSet )
{
m_PointSet = PointSet;
}
vtkDescriptorAttributeSet*
GetOutput(void)
{
return this;
}
PointSetPointer m_PointSet;
virtual const char * GetClassName () { return "vtkDescriptorAttributeSet"; };
};
class VTK_FILTERING_EXPORT vtkITKDescriptorPointSetToPolyDataFilter : public vtkPolyDataSource
{
public:
static vtkITKDescriptorPointSetToPolyDataFilter *New();
vtkTypeRevisionMacro(vtkITKDescriptorPointSetToPolyDataFilter,vtkPolyDataSource);
void PrintSelf(ostream& os, vtkIndent indent);
// this class could be eventually templated over attributes
typedef vtkDescriptorAttributeSet FeatureSetType;
typedef vtkDescriptorAttributeSet::PointSetType PointSetType;
typedef vtkDescriptorAttributeSet::PointSetPointer PointSetPointer;
//typedef itk::PointSet< itk::DescriptorAttribute > FeatureSetType;
// Description:
// Set / get the input data or filter.
//virtual void SetInput(FeatureSetType const & input);
//const FeatureSetType & GetInput();
virtual void SetInput(FeatureSetType* input);
FeatureSetType* GetInput();
vtkPolyData *GetOutput();
vtkPolyData *GetOutput(int idx);
void SetOutput(vtkPolyData *output);
// Description:
// Do not let images return more than requested.
virtual void ComputeInputUpdateExtents( vtkDataObject *output );
protected:
vtkITKDescriptorPointSetToPolyDataFilter();
~vtkITKDescriptorPointSetToPolyDataFilter();
virtual int FillInputPortInformation(int, vtkInformation*);
int FillOutputPortInformation(int, vtkInformation*);
void Execute();
void GenerateOutput();
private:
vtkITKDescriptorPointSetToPolyDataFilter(const vtkITKDescriptorPointSetToPolyDataFilter&); // Not implemented.
void operator=(const vtkITKDescriptorPointSetToPolyDataFilter&); // Not implemented.
};
#endif
| 33.417266 | 145 | 0.732831 | [
"mesh",
"object"
] |
bf11aad237b5f0af6e9deddfb3057791e93021d7 | 1,527 | h | C | src/test/include/test_helper_library.h | princeward/ros_vrpn_client | 53fd0e532526366adc472def24b8de55dc6e34a3 | [
"Apache-2.0"
] | 6 | 2018-07-25T14:13:42.000Z | 2021-09-13T13:55:13.000Z | src/test/include/test_helper_library.h | princeward/ros_vrpn_client | 53fd0e532526366adc472def24b8de55dc6e34a3 | [
"Apache-2.0"
] | 42 | 2015-09-04T22:24:12.000Z | 2021-07-05T08:33:21.000Z | src/test/include/test_helper_library.h | princeward/ros_vrpn_client | 53fd0e532526366adc472def24b8de55dc6e34a3 | [
"Apache-2.0"
] | 15 | 2015-10-12T07:56:41.000Z | 2022-03-10T14:35:53.000Z | /*
* Copyright 2015 Alex Millane, ASL, ETH Zurich, Switzerland
* Copyright 2015 Fadri Furrer, ASL, ETH Zurich, Switzerland
* Copyright 2015 Michael Burri, ASL, ETH Zurich, Switzerland
* Copyright 2015 Mina Kamel, ASL, ETH Zurich, Switzerland
* Copyright 2015 Janosch Nikolic, ASL, ETH Zurich, Switzerland
* Copyright 2015 Markus Achtelik, ASL, ETH Zurich, Switzerland
*
* 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 TEST_HELPER_LIBRARY_H
#define TEST_HELPER_LIBRARY_H
#include <math.h>
#include <Eigen/Geometry>
void euler2quat(double roll, double pitch, double yaw, double* q);
void calculate3dRmsError(double truth[][3], double est[][3],
const int trajectory_length, const int start_index,
double* error);
void calculateQuaternionRmsError(double truth[][4], double est[][4],
const int trajectory_length,
const int start_index, double* error);
#endif // TEST_HELPER_LIBRARY_H
| 38.175 | 76 | 0.70334 | [
"geometry"
] |
bf2031b90a778413968076968ce5c28bbcfe14a3 | 384 | h | C | Telecomm/Telecomm/Lib/Componet/StockMarket/include/JFTileStyleCollectionCell.h | telecommai/ios | 0dce4eeba342466ffe0db72fc0b77ba7d708d8cf | [
"BSD-3-Clause"
] | 1 | 2019-04-19T08:05:34.000Z | 2019-04-19T08:05:34.000Z | Telecomm/Telecomm/Lib/Componet/StockMarket/include/JFTileStyleCollectionCell.h | telecommai/ios | 0dce4eeba342466ffe0db72fc0b77ba7d708d8cf | [
"BSD-3-Clause"
] | null | null | null | Telecomm/Telecomm/Lib/Componet/StockMarket/include/JFTileStyleCollectionCell.h | telecommai/ios | 0dce4eeba342466ffe0db72fc0b77ba7d708d8cf | [
"BSD-3-Clause"
] | 1 | 2019-09-05T01:54:54.000Z | 2019-09-05T01:54:54.000Z | //
// JFTileStyleCollectionCell.h
// StockMarket
//
// Created by YRH on 2018/11/13.
// Copyright © 2018 SpiderMan. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "JFStockSegmentBarItem.h"
NS_ASSUME_NONNULL_BEGIN
@interface JFTileStyleCollectionCell : UICollectionViewCell
@property (nonatomic, strong) JFSegmentBarItemChildModel *model;
@end
NS_ASSUME_NONNULL_END
| 18.285714 | 64 | 0.776042 | [
"model"
] |
bf31b0229f3d3f3587e1e275ee2fc1f023694b66 | 4,219 | h | C | resources/home/dnanexus/root/include/RooStats/MinNLLTestStat.h | edawson/parliament2 | 2632aa3484ef64c9539c4885026b705b737f6d1e | [
"Apache-2.0"
] | null | null | null | resources/home/dnanexus/root/include/RooStats/MinNLLTestStat.h | edawson/parliament2 | 2632aa3484ef64c9539c4885026b705b737f6d1e | [
"Apache-2.0"
] | null | null | null | resources/home/dnanexus/root/include/RooStats/MinNLLTestStat.h | edawson/parliament2 | 2632aa3484ef64c9539c4885026b705b737f6d1e | [
"Apache-2.0"
] | 1 | 2020-05-28T23:01:44.000Z | 2020-05-28T23:01:44.000Z | // @(#)root/roostats:$Id: MinNLLTestStat.h 43035 2012-02-16 16:48:57Z sven $
// Author: Kyle Cranmer, Lorenzo Moneta, Gregory Schott, Wouter Verkerke
// Additional Contributions: Giovanni Petrucciani
/*************************************************************************
* Copyright (C) 1995-2008, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#ifndef ROOSTATS_MinNLLTestStat
#define ROOSTATS_MinNLLTestStat
#include "Rtypes.h"
#include <vector>
#include "RooStats/RooStatsUtils.h"
//#include "RooStats/DistributionCreator.h"
#include "RooStats/SamplingDistribution.h"
#include "RooStats/TestStatistic.h"
#include "RooStats/RooStatsUtils.h"
#include "RooRealVar.h"
#include "RooProfileLL.h"
#include "RooNLLVar.h"
#include "RooMsgService.h"
#include "RooMinuit.h"
#include "RooMinimizer.h"
#include "Math/MinimizerOptions.h"
#include "TStopwatch.h"
#include "ProfileLikelihoodTestStat.h"
namespace RooStats {
/** \class MinNLLTestStat
\ingroup Roostats
MinNLLTestStat is an implementation of the TestStatistic interface that
calculates the minimum value of the negative log likelihood
function and returns it as a test statistic.
Internally it operates by delegating to a MinNLLTestStat object.
*/
class MinNLLTestStat : public TestStatistic{
public:
MinNLLTestStat() {
// Proof constructor. Do not use.
fProflts = 0;
}
MinNLLTestStat(RooAbsPdf& pdf) {
fProflts = new ProfileLikelihoodTestStat(pdf);
}
MinNLLTestStat(const MinNLLTestStat& rhs) : TestStatistic(rhs), fProflts(0) {
RooAbsPdf * pdf = rhs.fProflts->GetPdf();
if (pdf) fProflts = new ProfileLikelihoodTestStat(*pdf);
}
MinNLLTestStat & operator=(const MinNLLTestStat& rhs) {
if (this == &rhs) return *this;
RooAbsPdf * pdf = rhs.fProflts->GetPdf();
if (fProflts) delete fProflts;
fProflts = NULL;
if (pdf) fProflts = new ProfileLikelihoodTestStat(*pdf);
return *this;
}
virtual ~MinNLLTestStat() {
delete fProflts;
}
void SetOneSided(Bool_t flag=true) {fProflts->SetOneSided(flag);}
void SetOneSidedDiscovery(Bool_t flag=true) {fProflts->SetOneSidedDiscovery(flag);}
void SetReuseNLL(Bool_t flag) { fProflts->SetReuseNLL(flag); }
void SetMinimizer(const char* minimizer){ fProflts->SetMinimizer(minimizer); }
void SetStrategy(Int_t strategy){ fProflts->SetStrategy(strategy); }
void SetTolerance(double tol){ fProflts->SetTolerance(tol); }
void SetPrintLevel(Int_t printlevel){ fProflts->SetPrintLevel(printlevel); }
void SetLOffset(Bool_t flag=kTRUE) { fProflts->SetLOffset(flag) ; }
// Main interface to evaluate the test statistic on a dataset
virtual Double_t Evaluate(RooAbsData& data, RooArgSet& paramsOfInterest) {
return fProflts->EvaluateProfileLikelihood(1, data, paramsOfInterest); //find unconditional NLL minimum
}
virtual void EnableDetailedOutput( bool e=true ) { fProflts->EnableDetailedOutput(e); }
virtual const RooArgSet* GetDetailedOutput(void) const {
// Returns detailed output. The value returned by this function is updated after each call to Evaluate().
// The returned RooArgSet contains the following:
//
// - the minimum nll, fitstatus and convergence quality for each fit </li>
// - for all non-constant parameters their value, error and pull </li>
return fProflts->GetDetailedOutput();
}
virtual void SetVarName(const char* name) { fProflts->SetVarName(name); }
virtual const TString GetVarName() const { return fProflts->GetVarName(); }
private:
ProfileLikelihoodTestStat* fProflts;
protected:
ClassDef(MinNLLTestStat,1) // implements the minimum NLL as a test statistic to be used with several tools
};
}
#endif
| 34.867769 | 114 | 0.657028 | [
"object",
"vector"
] |
bf32159a4da0d58ab86fb391915d7ef99f4d10c4 | 966 | h | C | src/procwatch.h | joncppl/proc-title-watch | 8aebf0482eea6d806a62a0de07bb05cb668d09f0 | [
"MIT"
] | null | null | null | src/procwatch.h | joncppl/proc-title-watch | 8aebf0482eea6d806a62a0de07bb05cb668d09f0 | [
"MIT"
] | null | null | null | src/procwatch.h | joncppl/proc-title-watch | 8aebf0482eea6d806a62a0de07bb05cb668d09f0 | [
"MIT"
] | null | null | null | #ifndef SRC_PROCWATCH_H_
#define SRC_PROCWATCH_H_
#include <string>
#include <vector>
#include <map>
class WatchWorker : public Nan::AsyncWorker {
public:
WatchWorker(Nan::Callback *callback, std::vector<std::string> searchStrings, bool doDeepSearch)
: AsyncWorker(callback), searchStrings(searchStrings), doDeepSearch(doDeepSearch){};
~WatchWorker() {};
void Execute();
void HandleOKCallback();
private:
BOOL ProcessSearch(/*IN*/std::vector<std::string> search, /*IN*/BOOL doDeepSearch, /*OUT*/std::vector<DWORD> *pids);
BOOL DeepProcessSearch(/*IN*/DWORD pid, /*IN*/std::vector<std::string>search);
BOOL GetVisibleWindowTitle(/*IN*/DWORD pid, /*OUT*/char *title, /*IN*/UINT titlelen);
void printError(TCHAR* msg);
std::vector<std::string> searchStrings;
std::map<unsigned long, std::string> pid_title_map;
bool doDeepSearch;
bool isError;
std::string errorMsg = "";
};
#endif // SRC_PROCWATCH_H_
| 30.1875 | 120 | 0.698758 | [
"vector"
] |
bf3277b4d36b44a63126d11766ebaa5de1c5d68e | 969 | h | C | src/NativeUpload/TrFmtException.h | iqrfsdk/iqrf-gateway-daemon | 8875a9a0bf67003fc7115a59af12ab12d591b487 | [
"Apache-2.0"
] | 1 | 2021-04-28T07:34:14.000Z | 2021-04-28T07:34:14.000Z | src/NativeUpload/TrFmtException.h | iqrf/iqrf-gateway-daemon | adf8585749afefb01f274d5b70959d500d35bd6c | [
"Apache-2.0"
] | 1 | 2019-10-31T13:29:55.000Z | 2019-10-31T13:29:55.000Z | src/NativeUpload/TrFmtException.h | iqrf/iqrf-gateway-daemon | adf8585749afefb01f274d5b70959d500d35bd6c | [
"Apache-2.0"
] | null | null | null | /*
* Class of exceptions for clibtr file format parsers.
* Author: Vlastimil Kosar <kosar@rehivetrch.com>
* License: TBD
*
* Adapted from clibcdc/include/CDCMessageParserException.h licenced under
* the Apache License, Version 2.0.
*/
#ifndef __TRFMTEXCEPTION_H__
#define __TRFMTEXCEPTION_H__
#include "TrException.h"
/**
* Exception, which occurs during running of TR file format parsers.
*/
class TrFmtException : public TrException {
private:
/* Identity string of this exception class. */
std::string identity;
public:
/**
* Constructs exception object.
* @param cause description of exception cause.
*/
TrFmtException(const char* cause);
~TrFmtException() throw();
};
#define TR_THROW_FMT_EXCEPTION(file, line, pos, msg) { \
std::ostringstream ostr; ostr << __FILE__ << " " << __LINE__ << " " << file << "[" << line << "/" << pos << "]: " << msg; \
TrFmtException ex(ostr.str().c_str()); throw ex; }
#endif // __TRFMTEXCEPTION_H__ | 25.5 | 125 | 0.691434 | [
"object"
] |
bf46e12840b82c6d36e0ede079c8b5a1c4dc0e1d | 476 | h | C | pch.h | number201724/ChiririBOT | 6b85aa21d19d8c988310e9d4a46bdade39292d45 | [
"MIT"
] | null | null | null | pch.h | number201724/ChiririBOT | 6b85aa21d19d8c988310e9d4a46bdade39292d45 | [
"MIT"
] | null | null | null | pch.h | number201724/ChiririBOT | 6b85aa21d19d8c988310e9d4a46bdade39292d45 | [
"MIT"
] | null | null | null | #pragma once
#define _USE_MATH_DEFINES
#include <tchar.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <memory.h>
#include <stdint.h>
#include <math.h>
#include <WinSock2.h>
#include <Windows.h>
#include <Shlwapi.h>
#include <dwmapi.h>
#include <ws2tcpip.h>
#include <vector>
#include <list>
#include <curl/curl.h>
#include <jansson.h>
#include "protocol.h"
#include <string>
#include <sstream>
#define APPLICATION_TITLE TEXT("Chiriri Danmaku") | 15.354839 | 49 | 0.718487 | [
"vector"
] |
bf54d77e503b1544f578b51e0d3352e3e2743380 | 2,451 | h | C | Source/Foundation/bsfUtility/Utility/BsLookupTable.h | Milerius/bsf | 8715b344d6b7893f64fd5dccaaf10603a27c7a15 | [
"MIT"
] | 3 | 2020-04-14T06:23:18.000Z | 2020-06-02T11:07:08.000Z | Source/Foundation/bsfUtility/Utility/BsLookupTable.h | Milerius/bsf | 8715b344d6b7893f64fd5dccaaf10603a27c7a15 | [
"MIT"
] | null | null | null | Source/Foundation/bsfUtility/Utility/BsLookupTable.h | Milerius/bsf | 8715b344d6b7893f64fd5dccaaf10603a27c7a15 | [
"MIT"
] | 4 | 2019-06-23T09:55:47.000Z | 2019-07-08T17:23:05.000Z | //************************************ bs::framework - Copyright 2018 Marko Pintera **************************************//
//*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********//
#pragma once
#include "Prerequisites/BsPrerequisitesUtil.h"
namespace bs
{
/** @addtogroup General
* @{
*/
/**
* Contains a set of samples resulting from sampling some function at equal intervals. The table can then be used
* for sampling that function at arbitrary time intervals. The sampling is fast but precision is limited to the number
* of samples.
*/
class BS_UTILITY_EXPORT LookupTable
{
public:
/**
* Constructs a lookup table from the provided set of values.
*
* @param[in] values Buffer containing information about all the samples. Total buffer size must be divisble
* by @p sampleSize.
* @param[in] startTime Time at which the first provided sample has been evaluated at.
* @param[in] endTime Time at which the last provided sample has been evaluate at. All samples in-between
* first and last are assumed to be evaluated to equal intervals in the
* [startTime, endTime] range.
* @param[in] sampleSize Number of 'float's each sample requires. This number must divide the number of elements
* in the @p values buffer.
*/
LookupTable(Vector<float> values, float startTime = 0.0f, float endTime = 1.0f, uint32_t sampleSize = 1);
/**
* Evaluates the lookup table at the specified time.
*
* @param[in] t Time to evaluate the lookup table at.
* @param[out] left Pointer to the set of values contained in the sample left to the time value.
* @param[out] right Pointer to the set of values contained in the sample right to the time value.
* @param[out] fraction Fraction that determines how to interpolate between @p left and @p right values, where
* 0 corresponds to the @p left value, 1 to the @p right value and values in-between
* interpolate linearly between the two.
*/
void evaluate(float t, const float*& left, const float*& right, float& fraction) const;
/** Returns a sample at the specified index. Returns last available sample if index is out of range. */
const float* getSample(uint32_t idx) const;
private:
Vector<float> mValues;
uint32_t mSampleSize;
uint32_t mNumSamples;
float mTimeStart;
float mTimeScale;
};
/** @} */
} | 41.542373 | 124 | 0.678091 | [
"vector"
] |
bf5de077e2df20e3ff28c67c1e9ded2b787d1d4f | 770 | h | C | Chain.h | germanium-diode/ChainSimulation | a652bee07fd90700ce66a88a3ed90315d919675f | [
"MIT"
] | 106 | 2021-08-01T18:42:21.000Z | 2022-02-13T08:08:00.000Z | Chain.h | germanium-diode/ChainSimulation | a652bee07fd90700ce66a88a3ed90315d919675f | [
"MIT"
] | null | null | null | Chain.h | germanium-diode/ChainSimulation | a652bee07fd90700ce66a88a3ed90315d919675f | [
"MIT"
] | 8 | 2021-08-20T20:02:39.000Z | 2021-09-11T22:53:28.000Z | #ifndef CHAIN_H
#define CHAIN_H
class Vector;
class ChainElement;
class Chain {
public:
double stiffness, stiffnessdamping, stiffnessoffsetlength; // restoring force if chain is bent + damping; offset above which force is acting
double stability, stabilitydamping; // restoring force if elements are pulled apart + damping
std::vector<ChainElement*> elements;
Chain();
Chain(Chain *);
void makeSimpleChain(int);
void quickArrangementLine(Vector, Vector);
void quickArrangementEntwined(Vector, double, int, double = 0.5);
void refreshLinks();
void loadFromChain(Chain *);
void loadXYFromSTDVector(std::vector<Vector>);
void loadVXYFromSTDVector(std::vector<Vector>);
std::vector<Vector> XYto_STDVector();
std::vector<Vector> VXYto_STDVector();
};
#endif
| 29.615385 | 141 | 0.77013 | [
"vector"
] |
bf62dce17aa14159d6243b18f80a5aea65af071b | 11,430 | h | C | Cubism/include/Cubism/HDF5SliceDumperMPI.h | mcaldana/CubismUP_3D | 7f428da7299b5e26bdc218569de5d712fe7dbee6 | [
"MIT"
] | 8 | 2020-05-30T02:36:25.000Z | 2022-01-04T23:03:50.000Z | Cubism/include/Cubism/HDF5SliceDumperMPI.h | mcaldana/CubismUP_3D | 7f428da7299b5e26bdc218569de5d712fe7dbee6 | [
"MIT"
] | null | null | null | Cubism/include/Cubism/HDF5SliceDumperMPI.h | mcaldana/CubismUP_3D | 7f428da7299b5e26bdc218569de5d712fe7dbee6 | [
"MIT"
] | 10 | 2020-05-29T17:07:02.000Z | 2022-01-04T13:57:21.000Z | //
// HDF5SliceDumperMPI.h
// Cubism
//
// Created by Fabian Wermelinger 09/28/2016
// Copyright 2016 ETH Zurich. All rights reserved.
//
#ifndef HDF5SLICEDUMPERMPI_H_ZENQHJA6
#define HDF5SLICEDUMPERMPI_H_ZENQHJA6
#include <mpi.h>
#include "HDF5SliceDumper.h"
#include "ArgumentParser.h"
CUBISM_NAMESPACE_BEGIN
///////////////////////////////////////////////////////////////////////////////
// helpers
namespace SliceTypesMPI
{
template <typename TGrid>
class Slice : public SliceTypes::Slice<TGrid>
{
// To generalize, check all occurences of BS and replace with
// the appropriate X/Y/Z.
static_assert(TGrid::BlockType::sizeX == TGrid::BlockType::sizeY
&& TGrid::BlockType::sizeX == TGrid::BlockType::sizeZ,
"Only cubic block type implemented so far.");
static constexpr int BS = TGrid::BlockType::sizeX;
public:
template <typename TSlice>
static std::vector<TSlice> getEntities(ArgumentParser& parser, TGrid& grid)
{
return SliceTypes::Slice<TGrid>::template getEntities<TSlice>(parser, grid);
}
public:
typedef TGrid GridType;
Slice(TGrid* grid, const int id,
const int dir,
const int idx,
const double frac) :
SliceTypes::Slice<TGrid>(grid, id, dir, idx, frac)
{
const int localDim[3] = {
static_cast<int>(this->m_grid->getResidentBlocksPerDimension(0)*TBlock::sizeX),
static_cast<int>(this->m_grid->getResidentBlocksPerDimension(1)*TBlock::sizeY),
static_cast<int>(this->m_grid->getResidentBlocksPerDimension(2)*TBlock::sizeZ)
};
// get MPI related dimensions and offsets
int peIdx[3];
this->m_grid->peindex(peIdx);
int myStart[3], myEnd[3];
for (int i = 0; i < 3; ++i)
{
myStart[i] = localDim[i]*peIdx[i];
myEnd[i] = myStart[i] + localDim[i];
}
if ( !(myStart[this->m_dir] <= this->m_idx && this->m_idx < myEnd[this->m_dir]) )
this->m_valid = false;
// scale index to process local index and recompute intersecting
// blocks
this->m_idx = this->m_idx % localDim[this->m_dir];
std::vector<BlockInfo> clean;
std::vector<BlockInfo> bInfo_local = this->m_grid->getResidentBlocksInfo(); // local
this->m_intersecting_blocks.swap(clean);
for (size_t i = 0; i < bInfo_local.size(); ++i)
{
const int start = bInfo_local[i].index[this->m_dir] * BS;
if (start <= this->m_idx && this->m_idx < (start + BS))
this->m_intersecting_blocks.push_back(bInfo_local[i]);
}
if (this->m_intersecting_blocks.empty())
this->m_valid = false;
// local dimensions and offsets
this->m_localWidth = localDim[ this->m_coord_idx[0] ];
this->m_localHeight = localDim[ this->m_coord_idx[1] ];
m_offsetWidth = peIdx[ this->m_coord_idx[0] ] * localDim[ this->m_coord_idx[0] ];
m_offsetHeight= peIdx[ this->m_coord_idx[1] ] * localDim[ this->m_coord_idx[1] ];
}
Slice(const Slice& c) = default;
inline int offsetWidth() const { return m_offsetWidth; }
inline int offsetHeight() const { return m_offsetHeight; }
protected:
typedef typename SliceTypes::Slice<TGrid>::TBlock TBlock;
int m_offsetWidth, m_offsetHeight;
};
}
///////////////////////////////////////////////////////////////////////////////
// Dumpers
//
// The following requirements for the data TStreamer are required:
// TStreamer::NCHANNELS : Number of data elements (1=Scalar, 3=Vector, 9=Tensor)
// TStreamer::operate : Data access methods for read and write
// TStreamer::getAttributeName : Attribute name of the date ("Scalar", "Vector", "Tensor")
template<typename TStreamer, typename hdf5Real, typename TSlice>
void DumpSliceHDF5MPI(
const TSlice& slice,
const typename TSlice::GridType::Real t,
const std::string &fileroot, // Filename without folder or extension.
const std::string &dirname = ".",
const bool bXMF = true)
{
#ifdef CUBISM_USE_HDF
typedef typename TSlice::GridType::BlockType B;
std::string filename_h5 = fileroot + ".h5";
std::string fullpath_h5 = dirname + "/" + filename_h5;
std::string fullpath_xmf = dirname + "/" + fileroot + ".xmf";
static const unsigned int NCHANNELS = TStreamer::NCHANNELS;
const unsigned int width = slice.localWidth();
const unsigned int height = slice.localHeight();
int myRank;
MPI_Comm comm = slice.getGrid()->getCartComm();
MPI_Comm_rank(comm, &myRank);
herr_t status;
hid_t file_id, dataset_id, fspace_id, fapl_id, mspace_id;
///////////////////////////////////////////////////////////////////////////
// write mesh
std::vector<int> mesh_dims;
std::vector<std::string> dset_name;
dset_name.push_back("/vwidth");
dset_name.push_back("/vheight");
if (0 == myRank)
{
H5open();
fapl_id = H5Pcreate(H5P_FILE_ACCESS);
file_id = H5Fcreate(fullpath_h5.c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, fapl_id);
status = H5Pclose(fapl_id);
for (size_t i = 0; i < 2; ++i)
{
const MeshMap<B>& m = slice.getGrid()->getMeshMap( slice.coord_idx(i) );
std::vector<double> vertices(m.ncells()+1, m.start());
mesh_dims.push_back(vertices.size());
for (size_t j = 0; j < m.ncells(); ++j)
vertices[j+1] = vertices[j] + m.cell_width(j);
hsize_t dim[1] = {vertices.size()};
fspace_id = H5Screate_simple(1, dim, NULL);
#ifndef CUBISM_ON_FERMI
dataset_id = H5Dcreate(file_id, dset_name[i].c_str(), H5T_NATIVE_DOUBLE, fspace_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
#else
dataset_id = H5Dcreate2(file_id, dset_name[i].c_str(), H5T_NATIVE_DOUBLE, fspace_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
#endif
status = H5Dwrite(dataset_id, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, vertices.data());
status = H5Sclose(fspace_id);
status = H5Dclose(dataset_id);
}
// shutdown h5 file
status = H5Fclose(file_id);
H5close();
}
MPI_Barrier(comm);
///////////////////////////////////////////////////////////////////////////
// startup file
H5open();
fapl_id = H5Pcreate(H5P_FILE_ACCESS);
status = H5Pset_fapl_mpio(fapl_id, comm, MPI_INFO_NULL); if(status<0) H5Eprint1(stdout);
file_id = H5Fopen(fullpath_h5.c_str(), H5F_ACC_RDWR, fapl_id);
status = H5Pclose(fapl_id); if(status<0) H5Eprint1(stdout);
///////////////////////////////////////////////////////////////////////////
// write data
if (0 == myRank)
{
std::cout << "Allocating " << (width * height * NCHANNELS * sizeof(hdf5Real))/(1024.*1024.) << " MB of HDF5 slice data";
}
hdf5Real * array_all = NULL;
if (slice.valid())
array_all = new hdf5Real[width * height * NCHANNELS];
hsize_t count[3] = { // local count
static_cast<hsize_t>(height),
static_cast<hsize_t>(width),
static_cast<hsize_t>(NCHANNELS)};
hsize_t dims[3] = { // global dimension
static_cast<hsize_t>(slice.height()),
static_cast<hsize_t>(slice.width()),
static_cast<hsize_t>(NCHANNELS)};
hsize_t offset[3] = { // file offset
static_cast<hsize_t>(slice.offsetHeight()),
static_cast<hsize_t>(slice.offsetWidth()),
0};
if (0 == myRank)
{
std::cout << " (Total " << (dims[0] * dims[1] * dims[2] * sizeof(hdf5Real))/(1024.*1024.) << " MB)" << std::endl;
}
if (slice.valid())
slice.template extract<TStreamer>(array_all);
fapl_id = H5Pcreate(H5P_DATASET_XFER);
H5Pset_dxpl_mpio(fapl_id, H5FD_MPIO_COLLECTIVE);
fspace_id = H5Screate_simple(3, dims, NULL);
#ifndef CUBISM_ON_FERMI
dataset_id = H5Dcreate(file_id, "data", get_hdf5_type<hdf5Real>(), fspace_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
#else
dataset_id = H5Dcreate2(file_id, "data", get_hdf5_type<hdf5Real>(), fspace_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT);
#endif
fspace_id = H5Dget_space(dataset_id);
H5Sselect_hyperslab(fspace_id, H5S_SELECT_SET, offset, NULL, count, NULL);
mspace_id = H5Screate_simple(3, count, NULL);
if (!slice.valid())
{
H5Sselect_none(fspace_id);
H5Sselect_none(mspace_id);
}
status = H5Dwrite(dataset_id, get_hdf5_type<hdf5Real>(), mspace_id, fspace_id, fapl_id, array_all);
if (status < 0) H5Eprint1(stdout);
status = H5Sclose(mspace_id); if(status<0) H5Eprint1(stdout);
status = H5Sclose(fspace_id); if(status<0) H5Eprint1(stdout);
status = H5Dclose(dataset_id); if(status<0) H5Eprint1(stdout);
status = H5Pclose(fapl_id); if(status<0) H5Eprint1(stdout);
status = H5Fclose(file_id); if(status<0) H5Eprint1(stdout);
H5close();
if (slice.valid())
delete [] array_all;
// writing xmf wrapper
if (bXMF && 0 == myRank)
{
FILE *xmf = 0;
xmf = fopen(fullpath_xmf.c_str(), "w");
fprintf(xmf, "<?xml version=\"1.0\" ?>\n");
fprintf(xmf, "<!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\" []>\n");
fprintf(xmf, "<Xdmf Version=\"2.0\">\n");
fprintf(xmf, " <Domain>\n");
fprintf(xmf, " <Grid GridType=\"Uniform\">\n");
fprintf(xmf, " <Time Value=\"%e\"/>\n\n", t);
fprintf(xmf, " <Topology TopologyType=\"2DRectMesh\" Dimensions=\"%d %d\"/>\n\n", mesh_dims[1], mesh_dims[0]);
fprintf(xmf, " <Geometry GeometryType=\"VxVyVz\">\n");
fprintf(xmf, " <DataItem Name=\"mesh_vx\" Dimensions=\"1\" NumberType=\"Float\" Precision=\"8\" Format=\"XML\">\n");
fprintf(xmf, " %e\n", 0.0);
fprintf(xmf, " </DataItem>\n");
fprintf(xmf, " <DataItem Name=\"mesh_vy\" Dimensions=\"%d\" NumberType=\"Float\" Precision=\"8\" Format=\"HDF\">\n", mesh_dims[0]);
fprintf(xmf, " %s:/vwidth\n", filename_h5.c_str());
fprintf(xmf, " </DataItem>\n");
fprintf(xmf, " <DataItem Name=\"mesh_vz\" Dimensions=\"%d\" NumberType=\"Float\" Precision=\"8\" Format=\"HDF\">\n", mesh_dims[1]);
fprintf(xmf, " %s:/vheight\n", filename_h5.c_str());
fprintf(xmf, " </DataItem>\n");
fprintf(xmf, " </Geometry>\n\n");
fprintf(xmf, " <Attribute Name=\"data\" AttributeType=\"%s\" Center=\"Cell\">\n", TStreamer::getAttributeName());
fprintf(xmf, " <DataItem Dimensions=\"%d %d %d\" NumberType=\"Float\" Precision=\"%d\" Format=\"HDF\">\n", (int)dims[0], (int)dims[1], (int)dims[2], (int)sizeof(hdf5Real));
fprintf(xmf, " %s:/data\n", filename_h5.c_str());
fprintf(xmf, " </DataItem>\n");
fprintf(xmf, " </Attribute>\n");
fprintf(xmf, " </Grid>\n");
fprintf(xmf, " </Domain>\n");
fprintf(xmf, "</Xdmf>\n");
fclose(xmf);
}
#else
_warn_no_hdf5();
#endif
}
CUBISM_NAMESPACE_END
#endif /* HDF5SLICEDUMPERMPI_H_ZENQHJA6 */
| 39.825784 | 186 | 0.579878 | [
"mesh",
"geometry",
"vector"
] |
bf632adc5e5d1cefe279ccc4a06dec60c0880e0a | 50,091 | h | C | include/Core/vxmath.h | digirea/HIVE | 8896b0cc858c1ad0683888b925f71c0f0d71bf9d | [
"MIT"
] | null | null | null | include/Core/vxmath.h | digirea/HIVE | 8896b0cc858c1ad0683888b925f71c0f0d71bf9d | [
"MIT"
] | null | null | null | include/Core/vxmath.h | digirea/HIVE | 8896b0cc858c1ad0683888b925f71c0f0d71bf9d | [
"MIT"
] | null | null | null | /**
* @file vxmath.h
* 数学関数
*/
#ifndef INCLUDE_VX_MATH_H
#define INCLUDE_VX_MATH_H
#include <math.h>
namespace VX {
namespace Math {
static const float PI = 3.141592654f;
inline float Floor(float x)
{
return floorf(x);
}
inline float Ceil(float x)
{
return ceilf(x);
}
inline float Mod(float x, float y)
{
return fmodf(x, y);
}
inline float Log(float x)
{
return logf(x);
}
inline float Sin(float rad)
{
return sinf(rad);
}
inline float Cos(float rad)
{
return cosf(rad);
}
inline float Tan(float rad)
{
return tanf(rad);
}
inline float Asin(float x)
{
return asinf(x);
}
inline float Acos(float x)
{
return acosf(x);
}
inline float Atan(float x)
{
return atanf(x);
}
inline float Atan2(float y, float x)
{
return atan2f(y, x);
}
inline float Sqrt(float s)
{
return sqrtf(s);
}
inline float Pow(float x, float y)
{
return powf(x,y);
}
inline float Abs(float s)
{
return (s >= 0.0f) ? s : -s;
}
inline float Clamp(float x, float min_v, float max_v)
{
return (x <= min_v) ? min_v : ((x >= max_v) ? max_v : x);
}
inline float ToRadian(float degree )
{
return degree * (PI / 180.0f);
}
inline float ToDegree(float radian)
{
return radian * (180.0f / PI);
}
#ifndef _WINDOWS_
template<typename T>
inline T max(const T& a, const T& b)
{
return (a < b) ? b : a;
}
template<typename T>
inline T max(const T& a, const T& b, const T& c)
{
return max(max(a,b),c);
}
template<typename T>
inline T min(const T& a, const T& b)
{
return (a < b) ? a : b;
}
template<typename T>
inline T min(const T& a, const T& b, const T& c)
{
return min(min(a,b),c);
}
#endif
//=================================================
#define white_space(c) ((c) == ' ' || (c) == '\t')
#define valid_digit(c) ((c) >= '0' && (c) <= '9')
#define begin_digit(c) (((c) >= '0' && (c) <= '9') || (c)=='-' || (c)=='+')
/*
inline u32 step_atoi (const char *p, s32* val)
{
const char* start_p = p;
s32 sign = 1, value = 0;
// skip white space
while (white_space(*p))
p += 1;
// sign
if (*p == '-') {
sign = -1;
p += 1;
} else if (*p == '+') {
p += 1;
}
while (valid_digit(*p)) {
value = value * 10 + (*p - '0');
p += 1;
}
*val = value;// * sign;
return p - start_p;
}*/
inline unsigned int step_fatof (const char *p, float* val)
{
const char* start_p = p;
int frac=0;
float sign, value, scale;
// skip white space
while (white_space(*p))
p += 1;
// sign
sign = 1.0f;
if (*p == '-') {
sign = -1.0f;
p += 1;
} else if (*p == '+') {
p += 1;
}
// Get digits before decimal point or exponent, if any.
value = 0.0f;
while (valid_digit(*p)) {
value = value * 10.0f + (*p - '0');
p += 1;
}
// Get digits after decimal point, if any.
if (*p == '.') {
float pow10 = 10.0f;
p += 1;
while (valid_digit(*p)) {
value += (*p - '0') / pow10;
pow10 *= 10.0f;
p += 1;
}
}
// Handle exponent, if any.
scale = 1.0f;
if ((*p == 'e') || (*p == 'E')) {
unsigned int expon;
p += 1;
// Get sign of exponent, if any.
frac = 0;
if (*p == '-') {
frac = 1;
p += 1;
} else if (*p == '+') {
p += 1;
}
// Get digits of exponent, if any.
expon = 0;
while (valid_digit(*p)) {
expon = expon * 10 + (*p - '0');
p += 1;
}
if (expon > 38) expon = 38;
// Calculate scaling factor.
while (expon >= 16) { scale *= 1E16f; expon -= 16; }
while (expon >= 8) { scale *= 1E8f; expon -= 8; }
while (expon > 0) { scale *= 10.0f; expon -= 1; }
}
// Return signed and scaled floating point result.
*val = sign * (frac ? (value / scale) : (value * scale));
return static_cast<unsigned int>(p - start_p);
}
// ================= Vector, matrix, Quartanion ====================
/// 2次元ベクトルユーティリティ
struct vec2
{
float x,y;
vec2() {/* to do nothing. */ }
vec2(float x_, float y_) { x = x_; y = y_; }
vec2(const float* const v) { x = v[0]; y = v[1]; }
vec2 operator-() const { return vec2(-x, -y);}
float & operator[](int i) { return (&x)[i]; }
float const & operator[](int i) const { return (&x)[i]; }
vec2& operator+=(const vec2& a) { x += a.x; y += a.y; return *this; }
vec2& operator-=(const vec2& a) { x -= a.x; y -= a.y; return *this; }
vec2& operator*=(const vec2& a) { x *= a.x; y *= a.y; return *this; }
vec2& operator/=(const vec2& a) { x /= a.x; y /= a.y; return *this; }
vec2& operator+=(float s) { x += s; y += s; return *this; }
vec2& operator-=(float s) { x -= s; y -= s; return *this; }
vec2& operator*=(float s) { x *= s; y *= s; return *this; }
vec2& operator/=(float s) { const float inv = 1.0f/s;
x *= inv; y *= inv; return *this; }
};
/// 3次元ベクトルユーティリティ
struct vec3
{
float x,y,z;
vec3() { /* to do nothing. */ }
vec3(const vec2& v, float z_ = 0) { x = v.x; y = v.y; z = z_; }
vec3(float x_, float y_, float z_) { x = x_; y = y_; z = z_; }
vec3(const float* const v) { x = v[0]; y = v[1]; z = v[2]; }
vec3 operator-() const { return vec3(-x, -y, -z); }
float & operator[](int i) { return (&x)[i]; }
float const & operator[](int i) const { return (&x)[i]; }
vec3& operator+=(const vec3& a) { x += a.x; y += a.y; z += a.z; return *this; }
vec3& operator-=(const vec3& a) { x -= a.x; y -= a.y; z -= a.z; return *this; }
vec3& operator*=(const vec3& a) { x *= a.x; y *= a.y; z *= a.z; return *this; }
vec3& operator/=(const vec3& a) { x /= a.x; y /= a.y; z /= a.z; return *this; }
vec3& operator+=(float s) { x += s; y += s; z += s; return *this; }
vec3& operator-=(float s) { x -= s; y -= s; z -= s; return *this; }
vec3& operator*=(float s) { x *= s; y *= s; z *= s; return *this; }
vec3& operator/=(float s) { const float inv = 1.0f/s;
x *= inv; y *= inv; z *= inv; return *this; }
vec2 xy() const { return vec2(x, y); }
vec2 yx() const { return vec2(y, x); }
vec2 xz() const { return vec2(x, z); }
vec2 zx() const { return vec2(z, x); }
vec2 yz() const { return vec2(y, z); }
vec2 zy() const { return vec2(z, y); }
vec2 xx() const { return vec2(x, x); }
vec2 yy() const { return vec2(y, y); }
vec2 zz() const { return vec2(z, z); }
};
/// 4次元ベクトルユーティリティ
struct vec4
{
float x,y,z,w;
vec4() { /* to do nothing. */ }
vec4(const vec2& v, float z_=0, float w_=0) { x = v.x; y = v.y; z = z_; w = w_; }
vec4(const vec3& v, float w_=0) { x = v.x; y = v.y; z = v.z; w = w_; }
vec4(float x_, float y_, float z_, float w_) { x = x_; y = y_; z = z_; w = w_; }
vec4(const float* const v) { x = v[0]; y = v[1]; z = v[2]; w = v[3]; }
vec4 operator-() const { return vec4(-x, -y, -z, -w); }
float & operator[](int i) { return (&x)[i]; }
float const & operator[](int i) const { return (&x)[i]; }
vec4& operator+=(const vec4& a) { x += a.x; y += a.y; z += a.z; w += a.w; return *this; }
vec4& operator-=(const vec4& a) { x -= a.x; y -= a.y; z -= a.z; w -= a.w; return *this; }
vec4& operator*=(const vec4& a) { x *= a.x; y *= a.y; z *= a.z; w *= a.w; return *this; }
vec4& operator/=(const vec4& a) { x /= a.x; y /= a.y; z /= a.z; w /= a.w; return *this; }
vec4& operator+=(float s) { x += s; y += s; z += s; w += s; return *this; }
vec4& operator-=(float s) { x -= s; y -= s; z -= s; w -= s; return *this; }
vec4& operator*=(float s) { x *= s; y *= s; z *= s; w *= s; return *this; }
vec4& operator/=(float s) { const float inv = 1.0f/s;
x *= inv; y *= inv; z *= inv; w *= inv; return *this; }
vec3 xyz() const { return vec3(x, y, z); }
vec3 zyx() const { return vec3(z, y, x); }
vec3 xxx() const { return vec3(x, x, x); }
vec3 yyy() const { return vec3(y, y, y); }
vec3 zzz() const { return vec3(z, z, z); }
vec3 www() const { return vec3(w, w, w); }
vec2 xy () const { return vec2(x, y); }
vec2 yz () const { return vec2(y, z); }
vec2 xz () const { return vec2(x, z); }
vec2 yx () const { return vec2(y, x); }
vec2 zy () const { return vec2(x, y); }
vec2 zx () const { return vec2(z, x); }
vec2 xx () const { return vec2(x, x); }
vec2 yy () const { return vec2(y, y); }
vec2 zz () const { return vec2(z, z); }
};
struct matrix3x3;
struct matrix2x2;
/// 4x4行列ユーティリティ
struct matrix4x4
{
union
{
float m[4][4];
float f[16];
};
matrix4x4() {}
matrix4x4(const float* const v) { for (int i = 0; i < 16; i++) f[i] = v[i]; };
matrix4x4(const float m00, const float m01, const float m02, const float m03,
const float m10, const float m11, const float m12, const float m13,
const float m20, const float m21, const float m22, const float m23,
const float m30, const float m31, const float m32, const float m33)
{
f[ 0] = m00; f[ 1] = m01; f[ 2] = m02; f[ 3] = m03;
f[ 4] = m10; f[ 5] = m11; f[ 6] = m12; f[ 7] = m13;
f[ 8] = m20; f[ 9] = m21; f[10] = m22; f[11] = m23;
f[12] = m30; f[13] = m31; f[14] = m32; f[15] = m33;
};
matrix4x4(const matrix3x3& a)
{
const float* x = reinterpret_cast<const float*>(&a); // force cast
f[0] = x[0]; f[1] = x[1]; f[ 2] = x[2];
f[4] = x[3]; f[5] = x[4]; f[ 6] = x[5];
f[8] = x[6]; f[9] = x[7]; f[10] = x[8];
}
matrix4x4(const vec4& a, const vec4& b, const vec4& c, const vec4& d)
{
f[ 0] = a.x; f[ 1] = a.y; f[ 2] = a.z; f[ 3] = a.w;
f[ 4] = b.x; f[ 5] = b.y; f[ 6] = b.z; f[ 7] = b.w;
f[ 8] = c.x; f[ 9] = c.y; f[10] = c.z; f[11] = c.w;
f[12] = d.x; f[13] = d.y; f[14] = d.z; f[15] = d.w;
}
/*
bool operator!=(const matrix4x4& t)
{
if (f[ 0] != t.f[ 0] || f[ 1] != t.f[ 1] || f[ 2] != t.f[ 2] || f[ 3] != t.f[ 3] ||
f[ 4] != t.f[ 4] || f[ 5] != t.f[ 5] || f[ 6] != t.f[ 6] || f[ 7] != t.f[ 7] ||
f[ 8] != t.f[ 8] || f[ 9] != t.f[ 9] || f[10] != t.f[10] || f[11] != t.f[11] ||
f[12] != t.f[12] || f[13] != t.f[13] || f[14] != t.f[14] || f[15] != t.f[15])
return true;
else
return false;
}*/
};
/// 3x3行列ユーティリティ
struct matrix3x3
{
union
{
float m[3][3];
float f[9];
};
matrix3x3() {}
matrix3x3(const float* const v) { for (int i = 0; i < 9; i++) f[i] = v[i]; };
matrix3x3(const float m00, const float m01, const float m02,
const float m10, const float m11, const float m12,
const float m20, const float m21, const float m22)
{
f[0] = m00; f[1] = m01; f[2] = m02;
f[3] = m10; f[4] = m11; f[5] = m12;
f[6] = m20; f[7] = m21; f[8] = m22;
};
matrix3x3(const vec3& a, const vec3& b, const vec3& c)
{
f[0] = a.x; f[1] = a.y; f[2] = a.z;
f[3] = b.x; f[4] = b.y; f[5] = b.z;
f[6] = c.x; f[7] = c.y; f[8] = c.z;
}
matrix3x3 (const matrix4x4& a)
{
f[0] = a.m[0][0]; f[1] = a.m[0][1]; f[2] = a.m[0][2];
f[3] = a.m[1][0]; f[4] = a.m[1][1]; f[5] = a.m[1][2];
f[6] = a.m[2][0]; f[7] = a.m[2][1]; f[8] = a.m[2][2];
}
};
/// 2x2行列ユーティリティ
struct matrix2x2
{
union
{
float m[2][2];
float f[4];
};
matrix2x2() {}
matrix2x2(const float* const v) { for (int i = 0; i < 4; i++) f[i] = v[i]; };
matrix2x2(const float m00, const float m01,
const float m10, const float m11)
{
f[0] = m00; f[1] = m01;
f[2] = m10; f[2] = m11;
};
matrix2x2(const vec2& a, const vec2& b)
{
f[0] = a.x; f[1] = a.y;
f[2] = b.x; f[3] = b.y;
}
matrix2x2(const matrix4x4& a)
{
f[0] = a.m[0][0]; f[1] = a.m[0][1];
f[2] = a.m[1][0]; f[3] = a.m[1][1];
}
matrix2x2(const matrix3x3& a)
{
f[0] = a.m[0][0]; f[1] = a.m[0][1];
f[2] = a.m[1][0]; f[3] = a.m[1][1];
}
};
/// 四元数ユーティリティ
struct quaternion
{
float x,y,z,w;
quaternion() {}
quaternion(const float* const v)
{
x = v[0]; y = v[1]; z = v[2]; w = v[3];
}
quaternion( float x_, float y_, float z_, float w_ )
{
x = x_; y = y_; z = z_; w = w_;
}
float& operator [](int i) { return (&x)[i]; }
const float& operator [](int i) const { return (&x)[i]; }
quaternion operator-() const { return quaternion(-x, -y, -z, -w); }
quaternion& operator+=(const quaternion& a) { x += a.x; y += a.y; z += a.z; w += a.w; return *this; }
quaternion& operator-=(const quaternion& a) { x -= a.x; y -= a.y; z -= a.z; w -= a.w; return *this; }
quaternion& operator+=(float s) { x += s; y += s; z += s; w += s; return *this; }
quaternion& operator-=(float s) { x -= s; y -= s; z -= s; w -= s; return *this; }
quaternion& operator*=(float s) { x *= s; y *= s; z *= s; w *= s; return *this; }
quaternion& operator/=(float s) { const float inv = 1.0f / s;
x *= inv; y *= inv; z *= inv; w *= inv; return *this; }
};
typedef matrix4x4 matrix;
typedef matrix4x4 mat4;
typedef matrix3x3 mat3;
typedef matrix2x2 mat2;
// ----------------------- vec4 --------------------------------
inline float length(const vec4& v)
{
return Sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
}
inline vec4 normalize(const vec4& v)
{
const float l = length(v);
return vec4(v.x / l, v.y / l, v.z / l, v.w / l);
}
inline vec4 operator+(const vec4& a, const vec4& b)
{
return vec4(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w);
}
inline vec4 operator-(const vec4& a, const vec4& b)
{
return vec4(a.x - b.x, a.y - b.y, a.z - b.z, a.w + b.w);
}
inline vec4 operator+(const vec4& a, const float r)
{
return vec4(a.x + r, a.y + r, a.z + r, a.w + r);
}
inline vec4 operator+(const float r, const vec4& a)
{
return vec4(a.x + r, a.y + r, a.z + r, a.w + r);
}
inline vec4 operator-(const vec4& a, const float r)
{
return vec4(a.x - r, a.y - r, a.z - r, a.w - r);
}
inline vec4 operator-(const float r, const vec4& a)
{
return vec4(r - a.x, r - a.y, r - a.z, r - a.w);
}
inline vec4 operator*(const vec4& a, const float r)
{
return vec4(a.x * r, a.y * r, a.z * r, a.w * r);
}
inline vec4 operator*(const float r, const vec4& a)
{
return vec4(a.x * r, a.y * r, a.z * r, a.w * r);
}
inline vec4 operator/(const vec4& a, const float r)
{
const float inv = 1.0f / r;
return vec4(a.x * inv, a.y * inv, a.z * inv, a.w * inv);
}
inline vec4 operator/(const float r, const vec4& a)
{
return vec4(r / a.x, r / a.y, r / a.z, r /a.w);
}
inline float dot(const vec4& a, const vec4& b)
{
return (a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w);
}
inline vec4 cross(const vec4& a, const vec4& b, const vec4& c)
{
return vec4(
a.y * (b.z * c.w - c.z * b.w) - a.z * (b.y * c.w - c.y * b.w) + a.w * (b.y * c.z - b.z *c.y),
-(a.x * (b.z * c.w - c.z * b.w) - a.z * (b.x * c.w - c.x * b.w) + a.w * (b.x * c.z - c.x * b.z)),
a.x * (b.y * c.w - c.y * b.w) - a.y * (b.x * c.w - c.x * b.w) + a.w * (b.x * c.y - c.x * b.y),
-(a.x * (b.y * c.z - c.y * b.z) - a.y * (b.x * c.z - c.x * b.z) + a.z * (b.x * c.y - c.x * b.y)));
}
inline vec4 lerp(const vec4& a, const vec4& b, const float r)
{
return vec4((b - a) * r + a);
}
inline bool operator==(const vec4& a, const vec4& b)
{
return (a.x == b.x) && (a.y == b.y) && (a.z == b.z) && (a.w == b.w);
}
inline bool operator!=(const vec4& a, const vec4& b)
{
return (a.x != b.x) || (a.y != b.y) || (a.z != b.z) || (a.w != b.w);
}
inline vec4 Maximize(const vec4& a, const vec4& b)
{
return vec4(a.x < b.x ? b.x : a.x,
a.y < b.y ? b.y : a.y,
a.z < b.z ? b.z : a.z,
a.w < b.w ? b.w : a.w);
}
inline vec4 Minimize(const vec4& a, const vec4& b)
{
return vec4(a.x < b.x ? a.x : b.x,
a.y < b.y ? a.y : b.y,
a.z < b.z ? b.z : a.z,
a.w < b.w ? b.w : a.w);
}
// ----------------------- vec3 --------------------------------
inline float length(const vec3& v)
{
return Sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
}
inline vec3 normalize(const vec3& v)
{
const float l = length(v);
return vec3(v.x / l, v.y / l, v.z / l);
}
inline vec3 operator+(const vec3& a, const vec3& b)
{
return vec3(a.x + b.x, a.y + b.y, a.z + b.z);
}
inline vec3 operator-(const vec3& a, const vec3& b)
{
return vec3(a.x - b.x, a.y - b.y, a.z - b.z);
}
inline vec3 operator+(const vec3& a, const float r)
{
return vec3(a.x + r, a.y + r, a.z + r);
}
inline vec3 operator+(const float r, const vec3& a)
{
return vec3(a.x + r, a.y + r, a.z + r);
}
inline vec3 operator-(const vec3& a, const float r)
{
return vec3(a.x - r, a.y - r, a.z - r);
}
inline vec3 operator-(const float r, const vec3& a)
{
return vec3(r - a.x, r - a.y, r - a.z);
}
inline vec3 operator*(const vec3& a, const float r)
{
return vec3(a.x * r, a.y * r, a.z * r);
}
inline vec3 operator*(const float r, const vec3& a)
{
return vec3(a.x * r, a.y * r, a.z * r);
}
inline vec3 operator/(const vec3& a, const vec3& b)
{
return vec3(a.x * b.x, a.y * b.y, a.z * b.z);
}
inline vec3 operator*(const vec3& a, const vec3& b)
{
return vec3(a.x * b.x, a.y * b.y, a.z * b.z);
}
inline vec3 operator/(const vec3& a, const float r)
{
const float inv = 1.0f / r;
return vec3(a.x * inv, a.y * inv, a.z * inv);
}
inline vec3 operator/(const float r, const vec3& a)
{
return vec3(r / a.x, r / a.y, r / a.z);
}
inline float dot(const vec3& a, const vec3& b)
{
return (a.x * b.x + a.y * b.y + a.z * b.z);
}
inline vec3 cross(const vec3& a, const vec3& b)
{
return vec3(a.y * b.z - a.z * b.y,
a.z * b.x - a.x * b.z,
a.x * b.y - a.y * b.x);
}
inline vec3 lerp(const vec3& a, const vec3& b, const float r)
{
return vec3((b - a) * r + a);
}
inline bool operator==(const vec3& a, const vec3& b)
{
return (a.x == b.x) && (a.y == b.y) && (a.z == b.z);
}
inline bool operator!=(const vec3& a, const vec3& b)
{
return (a.x != b.x) || (a.y != b.y) || (a.z != b.z);
}
inline vec3 Maximize(const vec3& a, const vec3& b)
{
return vec3(a.x < b.x ? b.x : a.x,
a.y < b.y ? b.y : a.y,
a.z < b.z ? b.z : a.z);
}
inline vec3 Minimize(const vec3& a, const vec3& b)
{
return vec3(a.x < b.x ? a.x : b.x,
a.y < b.y ? a.y : b.y,
a.z < b.z ? a.z : b.z);
}
// ----------------------- vec2 --------------------------------
inline float length(const vec2& v)
{
return Sqrt(v.x * v.x + v.y * v.y);
}
inline vec2 normalize(const vec2& v)
{
const float l = length(v);
return vec2(v.x / l, v.y / l);
}
inline vec2 operator+(const vec2& a, const vec2& b)
{
return vec2(a.x + b.x, a.y + b.y);
}
inline vec2 operator-(const vec2& a, const vec2& b)
{
return vec2(a.x - b.x, a.y - b.y);
}
inline vec2 operator+(const vec2& a, const float r)
{
return vec2(a.x + r, a.y + r);
}
inline vec2 operator+(const float r, const vec2& a)
{
return vec2(a.x + r, a.y + r);
}
inline vec2 operator-(const vec2& a, const float r)
{
return vec2(a.x - r, a.y - r);
}
inline vec2 operator-(const float r, const vec2& a)
{
return vec2(r - a.x, r - a.y);
}
inline vec2 operator*(const vec2& a, const float r)
{
return vec2(a.x * r, a.y * r);
}
inline vec2 operator*(const float r, const vec2& a)
{
return vec2(a.x * r, a.y * r);
}
inline vec2 operator/(const vec2& a, const float r)
{
const float inv = 1.0f / r;
return vec2(a.x * inv, a.y * inv);
}
inline vec2 operator/(const vec2& a, const vec2& b)
{
return vec2(a.x / b.x, a.y / b.y);
}
inline vec2 operator*(const vec2& a, const vec2& b)
{
return vec2(a.x * b.x, a.y * b.y);
}
inline vec2 operator/(const float r, const vec2& a)
{
return vec2(r / a.x, r / a.y);
}
inline float dot(const vec2& a, const vec2& b)
{
return (a.x * b.x + a.y * b.y);
}
inline vec2 cross(const vec2& a, const vec2& b)
{
return vec2(a.y * b.x - a.x * b.y,
a.x * b.y - a.y * b.x);
}
inline vec2 lerp(const vec2& a, const vec2& b, const float r)
{
return vec2((b - a) * r + a);
}
inline bool operator==(const vec2& a, const vec2& b)
{
return (a.x == b.x) && (a.y == b.y);
}
inline bool operator!=(const vec2& a, const vec2& b)
{
return (a.x != b.x) || (a.y != b.y);
}
inline vec2 Maximize(const vec2& a, const vec2& b)
{
return vec2(a.x < b.x ? b.x : a.x,
a.y < b.y ? b.y : a.y);
}
inline vec2 Minimize(const vec2& a, const vec2& b)
{
return vec2(a.x < b.x ? a.x : b.x,
a.y < b.y ? a.y : b.y);
}
// ----------------------- matrix4x4 --------------------------------
inline matrix4x4 Identity()
{
return matrix4x4(1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1);
}
inline matrix4x4 Translation(float x, float y, float z)
{
return matrix4x4(1,0,0,0, 0,1,0,0, 0,0,1,0, x,y,z,1);
}
inline matrix4x4 Translation(vec3 v)
{
return matrix4x4(1,0,0,0, 0,1,0,0, 0,0,1,0, v.x, v.y, v.z,1);
}
inline matrix4x4 Scaling(float s)
{
return matrix4x4(s,0,0,0, 0,s,0,0, 0,0,s,0, 0,0,0,1);
}
inline matrix4x4 Scaling(float x, float y, float z = 1.0f)
{
return matrix4x4(x,0,0,0, 0,y,0,0, 0,0,z,0, 0,0,0,1);
}
inline matrix4x4 RotationX(float degrees)
{
const float rad = ToRadian(degrees);
const float s = Sin(rad);
const float c = Cos(rad);
return matrix4x4(
1, 0, 0, 0,
0, c, s, 0,
0, -s, c, 0,
0, 0, 0, 1
);
}
inline matrix4x4 RotationY(float degrees)
{
const float rad = ToRadian(degrees);
const float s = Sin(rad);
const float c = Cos(rad);
return matrix4x4(
c, 0, -s, 0,
0, 1, 0, 0,
s, 0, c, 0,
0, 0, 0, 1
);
}
inline matrix4x4 RotationZ(float degrees)
{
const float rad = ToRadian(degrees);
const float s = Sin(rad);
const float c = Cos(rad);
return matrix4x4(
c, s, 0, 0,
-s, c, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
);
}
inline matrix4x4 RotationAxis(const vec3& v, float degree)
{
const float rad = ToRadian(degree);
const float cosa = Cos(rad);
const float sina = Sin(rad);
const float x = v.x, y = v.y, z = v.z;
return matrix4x4(
cosa + (1.0f - cosa) * x * x,
(1.0f - cosa) * x * y + sina * z,
(1.0f - cosa) * x * z - sina * y,
0,
(1.0f - cosa) * x * y - z * sina,
cosa + (1 - cosa) * y * y,
(1.0f - cosa) * y * z + x * sina,
0,
(1.0f - cosa) * x * z + sina * y,
(1.0f - cosa) * y * z - sina * x,
cosa + (1.0f - cosa) * z * z,
0.0f,
0.0f,
0.0f,
0.0f,
1.0f
);
}
inline matrix4x4 RotationYawPitchRoll(float yaw_degree, float pitch_degree, float roll_degree)
{
const float yaw = ToRadian(yaw_degree);
const float pitch = ToRadian(pitch_degree);
const float roll = ToRadian(roll_degree);
const float sin_y = Sin( yaw );
const float cos_y = Cos( yaw );
const float sin_p = Sin( pitch );
const float cos_p = Cos( pitch );
const float sin_r = Sin( roll );
const float cos_r = Cos( roll );
return matrix4x4(
cos_y * cos_r + sin_y * sin_p * sin_r,
sin_r * cos_p,
cos_r * -sin_y + sin_r * sin_p * cos_y,
0.0f,
-sin_r * cos_y + cos_r * sin_p * sin_y,
cos_r * cos_p,
sin_r * sin_y + cos_r * sin_p * cos_y,
0.0f,
cos_p * sin_y,
-sin_p,
cos_p * cos_y,
0.0f, 0.0f, 0.0f, 0.0f, 1.0f
);
}
inline matrix4x4 operator* (const matrix4x4& a, const matrix4x4& b)
{
return matrix4x4(
a.m[0][0] * b.m[0][0] + a.m[1][0] * b.m[0][1] + a.m[2][0] * b.m[0][2] + a.m[3][0] * b.m[0][3],
a.m[0][1] * b.m[0][0] + a.m[1][1] * b.m[0][1] + a.m[2][1] * b.m[0][2] + a.m[3][1] * b.m[0][3],
a.m[0][2] * b.m[0][0] + a.m[1][2] * b.m[0][1] + a.m[2][2] * b.m[0][2] + a.m[3][2] * b.m[0][3],
a.m[0][3] * b.m[0][0] + a.m[1][3] * b.m[0][1] + a.m[2][3] * b.m[0][2] + a.m[3][3] * b.m[0][3],
a.m[0][0] * b.m[1][0] + a.m[1][0] * b.m[1][1] + a.m[2][0] * b.m[1][2] + a.m[3][0] * b.m[1][3],
a.m[0][1] * b.m[1][0] + a.m[1][1] * b.m[1][1] + a.m[2][1] * b.m[1][2] + a.m[3][1] * b.m[1][3],
a.m[0][2] * b.m[1][0] + a.m[1][2] * b.m[1][1] + a.m[2][2] * b.m[1][2] + a.m[3][2] * b.m[1][3],
a.m[0][3] * b.m[1][0] + a.m[1][3] * b.m[1][1] + a.m[2][3] * b.m[1][2] + a.m[3][3] * b.m[1][3],
a.m[0][0] * b.m[2][0] + a.m[1][0] * b.m[2][1] + a.m[2][0] * b.m[2][2] + a.m[3][0] * b.m[2][3],
a.m[0][1] * b.m[2][0] + a.m[1][1] * b.m[2][1] + a.m[2][1] * b.m[2][2] + a.m[3][1] * b.m[2][3],
a.m[0][2] * b.m[2][0] + a.m[1][2] * b.m[2][1] + a.m[2][2] * b.m[2][2] + a.m[3][2] * b.m[2][3],
a.m[0][3] * b.m[2][0] + a.m[1][3] * b.m[2][1] + a.m[2][3] * b.m[2][2] + a.m[3][3] * b.m[2][3],
a.m[0][0] * b.m[3][0] + a.m[1][0] * b.m[3][1] + a.m[2][0] * b.m[3][2] + a.m[3][0] * b.m[3][3],
a.m[0][1] * b.m[3][0] + a.m[1][1] * b.m[3][1] + a.m[2][1] * b.m[3][2] + a.m[3][1] * b.m[3][3],
a.m[0][2] * b.m[3][0] + a.m[1][2] * b.m[3][1] + a.m[2][2] * b.m[3][2] + a.m[3][2] * b.m[3][3],
a.m[0][3] * b.m[3][0] + a.m[1][3] * b.m[3][1] + a.m[2][3] * b.m[3][2] + a.m[3][3] * b.m[3][3]
);
}
inline matrix3x3 operator* (const matrix3x3& a, const matrix3x3& b)
{
return matrix3x3(
a.m[0][0] * b.m[0][0] + a.m[1][0] * b.m[0][1] + a.m[2][0] * b.m[0][2],
a.m[0][1] * b.m[0][0] + a.m[1][1] * b.m[0][1] + a.m[2][1] * b.m[0][2],
a.m[0][2] * b.m[0][0] + a.m[1][2] * b.m[0][1] + a.m[2][2] * b.m[0][2],
a.m[0][0] * b.m[1][0] + a.m[1][0] * b.m[1][1] + a.m[2][0] * b.m[1][2],
a.m[0][1] * b.m[1][0] + a.m[1][1] * b.m[1][1] + a.m[2][1] * b.m[1][2],
a.m[0][2] * b.m[1][0] + a.m[1][2] * b.m[1][1] + a.m[2][2] * b.m[1][2],
a.m[0][0] * b.m[2][0] + a.m[1][0] * b.m[2][1] + a.m[2][0] * b.m[2][2],
a.m[0][1] * b.m[2][0] + a.m[1][1] * b.m[2][1] + a.m[2][1] * b.m[2][2],
a.m[0][2] * b.m[2][0] + a.m[1][2] * b.m[2][1] + a.m[2][2] * b.m[2][2]
);
}
inline matrix2x2 operator* (const matrix2x2& a, const matrix2x2& b)
{
return matrix2x2(
a.m[0][0] * b.m[0][0] + a.m[1][0] * b.m[0][1],
a.m[0][1] * b.m[0][0] + a.m[1][1] * b.m[0][1],
a.m[0][0] * b.m[1][0] + a.m[1][0] * b.m[1][1],
a.m[0][1] * b.m[1][0] + a.m[1][1] * b.m[1][1]
);
}
inline matrix4x4 Transpose (const matrix4x4& a)
{
return matrix4x4(
a.m[0][0], a.m[1][0], a.m[2][0], a.m[3][0],
a.m[0][1], a.m[1][1], a.m[2][1], a.m[3][1],
a.m[0][2], a.m[1][2], a.m[2][2], a.m[3][2],
a.m[0][3], a.m[1][3], a.m[2][3], a.m[3][3]
);
}
inline matrix3x3 Transpose (const matrix3x3& a)
{
return matrix3x3(
a.m[0][0], a.m[1][0], a.m[2][0],
a.m[0][1], a.m[1][1], a.m[2][1],
a.m[0][2], a.m[1][2], a.m[2][2]
);
}
inline matrix2x2 Transpose (const matrix2x2& a)
{
return matrix2x2(
a.m[0][0], a.m[1][0],
a.m[0][1], a.m[1][1]
);
}
inline vec4 operator* (const matrix4x4& a, const vec4& b)
{
return vec4(
a.m[0][0] * b.x + a.m[1][0] * b.y + a.m[2][0] * b.z + a.m[3][0] * b.w,
a.m[0][1] * b.x + a.m[1][1] * b.y + a.m[2][1] * b.z + a.m[3][1] * b.w,
a.m[0][2] * b.x + a.m[1][2] * b.y + a.m[2][2] * b.z + a.m[3][2] * b.w,
a.m[0][3] * b.x + a.m[1][3] * b.y + a.m[2][3] * b.z + a.m[3][3] * b.w
);
}
inline vec3 operator* (const matrix3x3& a, const vec3& b)
{
return vec3(
a.m[0][0] * b.x + a.m[1][0] * b.y + a.m[2][0] * b.z,
a.m[0][1] * b.x + a.m[1][1] * b.y + a.m[2][1] * b.z,
a.m[0][2] * b.x + a.m[1][2] * b.y + a.m[2][2] * b.z
);
}
inline vec2 operator* (const matrix2x2& a, const vec2& b)
{
return vec2(
a.m[0][0] * b.x + a.m[1][0] * b.y,
a.m[0][1] * b.x + a.m[1][1] * b.y
);
}
inline matrix4x4 Ortho(float l, float r, float t, float b, float nearval, float farval)
{
const float x = 2.0f / (r - l);
const float y = 2.0f / (t - b);
const float z = -2.0f / (farval - nearval);
const float tx = - (r + l) / (r - l);
const float ty = - (t + b) / (t - b);
const float tz = - (farval + nearval) / (farval - nearval);
return matrix4x4(x, 0, 0, 0,
0, y, 0, 0,
0, 0, z, 0,
tx, ty, tz, 1
);
}
inline matrix4x4 Frustum(float l, float r, float t, float b, float nearval, float farval)
{
const float x = 2.0f * nearval / (r - l);
const float y = 2.0f * nearval / (t - b);
const float z = (r + l) / (r - l);
const float w = (t + b) / (t - b);
const float e = - (farval + nearval) / (farval - nearval);
const float p = -2.0f * farval * nearval / (farval - nearval);
return matrix4x4(
x, 0, 0, 0,
0, y, 0, 0,
z, w, e, -1,
0, 0, p, 0
);
}
inline matrix4x4 PerspectiveFov(float fovy_degree, float Aspect, float zn, float zf)
{
const float h = 1.0f / Tan(ToRadian(fovy_degree) * 0.5f);
const float w = h / Aspect;
return matrix4x4(w, 0.0f, 0.0f, 0.0f,
0.0f, h, 0.0f, 0.0f,
0.0f, 0.0f, -(zf+zn) / (zf-zn), -1.0f,
0.0f, 0.0f, -2.0f*zn*zf/(zf-zn), 0.0f);
/* return matrix4x4(w, 0.0f, 0.0f, 0.0f,
0.0f, h, 0.0f, 0.0f,
0.0f, 0.0f, (zf+zn) / (zf-zn), -2.0f*zn*zf/(zf-zn),
0.0f, 0.0f, -1.0, 0.0f);*/
}
inline matrix4x4 LookAt(const vec3& eye, const vec3& target, const vec3& up)
{
const vec3 z = normalize(eye - target);
const vec3 x = normalize(cross(up, z));
const vec3 y = normalize(cross(z, x));
return matrix4x4(
x.x, y.x, z.x, 0,
x.y, y.y, z.y, 0,
x.z, y.z, z.z, 0,
-dot(x, eye), -dot(y, eye), -dot(z, eye), 1.0f
);
}
inline float Det(const matrix4x4& mat)
{
const float det =
mat.m[0][0]*mat.m[1][1]*mat.m[2][2]*mat.m[3][3]
+ mat.m[0][0]*mat.m[1][2]*mat.m[2][3]*mat.m[3][1]
+ mat.m[0][0]*mat.m[1][3]*mat.m[2][1]*mat.m[3][2]
+ mat.m[0][1]*mat.m[1][0]*mat.m[2][3]*mat.m[3][2]
+ mat.m[0][1]*mat.m[1][2]*mat.m[2][0]*mat.m[3][3]
+ mat.m[0][1]*mat.m[1][3]*mat.m[2][2]*mat.m[3][0]
+ mat.m[0][2]*mat.m[1][0]*mat.m[2][1]*mat.m[3][3]
+ mat.m[0][2]*mat.m[1][1]*mat.m[2][3]*mat.m[3][0]
+ mat.m[0][2]*mat.m[1][3]*mat.m[2][0]*mat.m[3][1]
+ mat.m[0][3]*mat.m[1][0]*mat.m[2][2]*mat.m[3][1]
+ mat.m[0][3]*mat.m[1][1]*mat.m[2][0]*mat.m[3][2]
+ mat.m[0][3]*mat.m[1][2]*mat.m[2][1]*mat.m[3][0]
- mat.m[0][0]*mat.m[1][1]*mat.m[2][3]*mat.m[3][2]
- mat.m[0][0]*mat.m[1][2]*mat.m[2][1]*mat.m[3][3]
- mat.m[0][0]*mat.m[1][3]*mat.m[2][2]*mat.m[3][1]
- mat.m[0][1]*mat.m[1][0]*mat.m[2][2]*mat.m[3][3]
- mat.m[0][1]*mat.m[1][2]*mat.m[2][3]*mat.m[3][0]
- mat.m[0][1]*mat.m[1][3]*mat.m[2][0]*mat.m[3][2]
- mat.m[0][2]*mat.m[1][0]*mat.m[2][3]*mat.m[3][1]
- mat.m[0][2]*mat.m[1][1]*mat.m[2][0]*mat.m[3][3]
- mat.m[0][2]*mat.m[1][3]*mat.m[2][1]*mat.m[3][0]
- mat.m[0][3]*mat.m[1][0]*mat.m[2][1]*mat.m[3][2]
- mat.m[0][3]*mat.m[1][1]*mat.m[2][2]*mat.m[3][0]
- mat.m[0][3]*mat.m[1][2]*mat.m[2][0]*mat.m[3][1];
return det;
}
inline float Det(const matrix3x3& mat)
{
const float det =
mat.m[0][0] * mat.m[1][1] * mat.m[2][2] -
mat.m[0][0] * mat.m[2][1] * mat.m[0][2] +
mat.m[1][0] * mat.m[2][1] * mat.m[2][2] -
mat.m[1][0] * mat.m[0][0] * mat.m[2][2] -
mat.m[2][0] * mat.m[0][1] * mat.m[1][2] +
mat.m[2][0] * mat.m[1][1] * mat.m[0][2];
return det;
}
inline float Det(const matrix2x2& mat)
{
const float det = mat.m[0][0] * mat.m[1][1] - mat.m[0][1] * mat.m[1][0];
return det;
}
inline matrix2x2 Inverse(const matrix2x2& mat)
{
const float det = Det(mat);
if (det == 0)
return Identity();
return matrix2x2(
mat.m[1][1] / det,
-mat.m[0][1] / det,
-mat.m[1][0] / det,
mat.m[0][0] / det
);
}
inline matrix3x3 Inverse(const matrix3x3& mat)
{
const float det = Det(mat);
if (det == 0)
return Identity();
return matrix3x3(
(mat.m[1][1] * mat.m[2][2] - mat.m[1][2] * mat.m[2][1]) / det,
-(mat.m[0][1] * mat.m[2][2] - mat.m[0][2] * mat.m[2][1]) / det,
-(mat.m[0][1] * mat.m[2][2] - mat.m[0][2] * mat.m[1][1]) / det,
-(mat.m[1][0] * mat.m[2][2] - mat.m[1][2] * mat.m[2][0]) / det,
(mat.m[0][0] * mat.m[2][2] - mat.m[0][2] * mat.m[2][0]) / det,
-(mat.m[0][0] * mat.m[1][2] - mat.m[0][2] * mat.m[1][0]) / det,
(mat.m[1][0] * mat.m[2][1] - mat.m[1][1] * mat.m[2][0]) / det,
-(mat.m[0][0] * mat.m[2][1] - mat.m[1][1] * mat.m[2][0]) / det,
(mat.m[0][0] * mat.m[1][1] - mat.m[0][1] * mat.m[1][0]) / det
);
}
inline matrix4x4 Inverse(const matrix4x4& mat)
{
const float det = Det(mat);
if (det == 0)
return Identity();
matrix4x4 iMat(
( mat.m[1][1]*mat.m[2][2]*mat.m[3][3]
+ mat.m[1][2]*mat.m[2][3]*mat.m[3][1]
+ mat.m[1][3]*mat.m[2][1]*mat.m[3][2]
- mat.m[1][1]*mat.m[2][3]*mat.m[3][2]
- mat.m[1][2]*mat.m[2][1]*mat.m[3][3]
- mat.m[1][3]*mat.m[2][2]*mat.m[3][1])/det,
( mat.m[0][1]*mat.m[2][3]*mat.m[3][2]
+ mat.m[0][2]*mat.m[2][1]*mat.m[3][3]
+ mat.m[0][3]*mat.m[2][2]*mat.m[3][1]
- mat.m[0][1]*mat.m[2][2]*mat.m[3][3]
- mat.m[0][2]*mat.m[2][3]*mat.m[3][1]
- mat.m[0][3]*mat.m[2][1]*mat.m[3][2])/det,
( mat.m[0][1]*mat.m[1][2]*mat.m[3][3]
+ mat.m[0][2]*mat.m[1][3]*mat.m[3][1]
+ mat.m[0][3]*mat.m[1][1]*mat.m[3][2]
- mat.m[0][1]*mat.m[1][3]*mat.m[3][2]
- mat.m[0][2]*mat.m[1][1]*mat.m[3][3]
- mat.m[0][3]*mat.m[1][2]*mat.m[3][1])/det,
( mat.m[0][1]*mat.m[1][3]*mat.m[2][2]
+ mat.m[0][2]*mat.m[1][1]*mat.m[2][3]
+ mat.m[0][3]*mat.m[1][2]*mat.m[2][1]
- mat.m[0][1]*mat.m[1][2]*mat.m[2][3]
- mat.m[0][2]*mat.m[1][3]*mat.m[2][1]
- mat.m[0][3]*mat.m[1][1]*mat.m[2][2])/det,
( mat.m[1][0]*mat.m[2][3]*mat.m[3][2]
+ mat.m[1][2]*mat.m[2][0]*mat.m[3][3]
+ mat.m[1][3]*mat.m[2][2]*mat.m[3][0]
- mat.m[1][0]*mat.m[2][2]*mat.m[3][3]
- mat.m[1][2]*mat.m[2][3]*mat.m[3][0]
- mat.m[1][3]*mat.m[2][0]*mat.m[3][2])/det,
( mat.m[0][0]*mat.m[2][2]*mat.m[3][3]
+ mat.m[0][2]*mat.m[2][3]*mat.m[3][0]
+ mat.m[0][3]*mat.m[2][0]*mat.m[3][2]
- mat.m[0][0]*mat.m[2][3]*mat.m[3][2]
- mat.m[0][2]*mat.m[2][0]*mat.m[3][3]
- mat.m[0][3]*mat.m[2][2]*mat.m[3][0])/det,
( mat.m[0][0]*mat.m[1][3]*mat.m[3][2]
+ mat.m[0][2]*mat.m[1][0]*mat.m[3][3]
+ mat.m[0][3]*mat.m[1][2]*mat.m[3][0]
- mat.m[0][0]*mat.m[1][2]*mat.m[3][3]
- mat.m[0][2]*mat.m[1][3]*mat.m[3][0]
- mat.m[0][3]*mat.m[1][0]*mat.m[3][2])/det,
( mat.m[0][0]*mat.m[1][2]*mat.m[2][3]
+ mat.m[0][2]*mat.m[1][3]*mat.m[2][0]
+ mat.m[0][3]*mat.m[1][0]*mat.m[2][2]
- mat.m[0][0]*mat.m[1][3]*mat.m[2][2]
- mat.m[0][2]*mat.m[1][0]*mat.m[2][3]
- mat.m[0][3]*mat.m[1][2]*mat.m[2][0])/det,
( mat.m[1][0]*mat.m[2][1]*mat.m[3][3]
+ mat.m[1][1]*mat.m[2][3]*mat.m[3][0]
+ mat.m[1][3]*mat.m[2][0]*mat.m[3][1]
- mat.m[1][0]*mat.m[2][3]*mat.m[3][1]
- mat.m[1][1]*mat.m[2][0]*mat.m[3][3]
- mat.m[1][3]*mat.m[2][1]*mat.m[3][0])/det,
( mat.m[0][0]*mat.m[2][3]*mat.m[3][1]
+ mat.m[0][1]*mat.m[2][0]*mat.m[3][3]
+ mat.m[0][3]*mat.m[2][1]*mat.m[3][0]
- mat.m[0][0]*mat.m[2][1]*mat.m[3][3]
- mat.m[0][1]*mat.m[2][3]*mat.m[3][0]
- mat.m[0][3]*mat.m[2][0]*mat.m[3][1])/det,
( mat.m[0][0]*mat.m[1][1]*mat.m[3][3]
+ mat.m[0][1]*mat.m[1][3]*mat.m[3][0]
+ mat.m[0][3]*mat.m[1][0]*mat.m[3][1]
- mat.m[0][0]*mat.m[1][3]*mat.m[3][1]
- mat.m[0][1]*mat.m[1][0]*mat.m[3][3]
- mat.m[0][3]*mat.m[1][1]*mat.m[3][0])/det,
( mat.m[0][0]*mat.m[1][3]*mat.m[2][1]
+ mat.m[0][1]*mat.m[1][0]*mat.m[2][3]
+ mat.m[0][3]*mat.m[1][1]*mat.m[2][0]
- mat.m[0][0]*mat.m[1][1]*mat.m[2][3]
- mat.m[0][1]*mat.m[1][3]*mat.m[2][0]
- mat.m[0][3]*mat.m[1][0]*mat.m[2][1])/det,
( mat.m[1][0]*mat.m[2][2]*mat.m[3][1]
+ mat.m[1][1]*mat.m[2][0]*mat.m[3][2]
+ mat.m[1][2]*mat.m[2][1]*mat.m[3][0]
- mat.m[1][0]*mat.m[2][1]*mat.m[3][2]
- mat.m[1][1]*mat.m[2][2]*mat.m[3][0]
- mat.m[1][2]*mat.m[2][0]*mat.m[3][1])/det,
( mat.m[0][0]*mat.m[2][1]*mat.m[3][2]
+ mat.m[0][1]*mat.m[2][2]*mat.m[3][0]
+ mat.m[0][2]*mat.m[2][0]*mat.m[3][1]
- mat.m[0][0]*mat.m[2][2]*mat.m[3][1]
- mat.m[0][1]*mat.m[2][0]*mat.m[3][2]
- mat.m[0][2]*mat.m[2][1]*mat.m[3][0])/det,
( mat.m[0][0]*mat.m[1][2]*mat.m[3][1]
+ mat.m[0][1]*mat.m[1][0]*mat.m[3][2]
+ mat.m[0][2]*mat.m[1][1]*mat.m[3][0]
- mat.m[0][0]*mat.m[1][1]*mat.m[3][2]
- mat.m[0][1]*mat.m[1][2]*mat.m[3][0]
- mat.m[0][2]*mat.m[1][0]*mat.m[3][1])/det,
( mat.m[0][0]*mat.m[1][1]*mat.m[2][2]
+ mat.m[0][1]*mat.m[1][2]*mat.m[2][0]
+ mat.m[0][2]*mat.m[1][0]*mat.m[2][1]
- mat.m[0][0]*mat.m[1][2]*mat.m[2][1]
- mat.m[0][1]*mat.m[1][0]*mat.m[2][2]
- mat.m[0][2]*mat.m[1][1]*mat.m[2][0])/det);
return iMat;
}
inline bool UnProject(const vec3& winpos,
const matrix& invMatrix,
const int viewport[4],
vec3* ray)
{
if (!ray)
return false;
// convert window coordinate
vec4 inpos(winpos, 1.0);
inpos.x = (inpos.x - viewport[0]) / viewport[2];
inpos.y = (inpos.y - viewport[1]) / viewport[3];
inpos = inpos * 2.0 - 1.0;
inpos.w = 1.0;
vec4 outpos = invMatrix * inpos;
if (outpos.w == 0.0) return false;
*ray = outpos.xyz() / outpos.w;
return true;
}
inline bool UnProject(const vec3& winpos,
const matrix& modelMatrix,
const matrix& projMatrix,
const int viewport[4],
vec3* ray)
{
if (!ray)
return false;
matrix finalMatrix = projMatrix * modelMatrix;
finalMatrix = Inverse(finalMatrix);
return UnProject(winpos, finalMatrix, viewport, ray);
}
inline bool operator==(const matrix4x4& a, const matrix4x4& b)
{
for (int i = 0; i < 16; i++)
{
if (a.f[i] != b.f[i])
return false;
}
return true;
}
inline bool operator!=(const matrix4x4& a, const matrix4x4& b)
{
for (int i = 0; i < 16; i++)
{
if (a.f[i] != b.f[i])
return true;
}
return false;
}
inline bool operator==(const matrix3x3& a, const matrix3x3& b)
{
for (int i = 0; i < 9; i++)
{
if (a.f[i] != b.f[i])
return false;
}
return true;
}
inline bool operator!=(const matrix3x3& a, const matrix3x3& b)
{
for (int i = 0; i < 9; i++)
{
if (a.f[i] != b.f[i])
return true;
}
return false;
}
inline bool operator==(const matrix2x2& a, const matrix2x2& b)
{
for (int i = 0; i < 4; i++)
{
if (a.f[i] != b.f[i])
return false;
}
return true;
}
inline bool operator!=(const matrix2x2& a, const matrix2x2& b)
{
for (int i = 0; i < 4; i++)
{
if (a.f[i] != b.f[i])
return true;
}
return false;
}
// ----------------------- quaternion --------------------------------
inline quaternion QuatIdentity()
{
return quaternion(0,0,0,1);
}
inline quaternion operator+(const quaternion& a, const quaternion& b)
{
return quaternion(a.x + b.x, a.y + b.y, a.z + b.z, a.w + b.w);
}
inline quaternion operator-(const quaternion& a, const quaternion& b)
{
return quaternion(a.x - b.x, a.y - b.y, a.z - b.z, a.w - b.w);
}
inline quaternion operator*(const quaternion& a, const quaternion& b)
{
return quaternion(a.y * b.z - a.z * b.y + a.w * b.x + a.x * b.w,
a.z * b.x - a.x * b.z + a.w * b.y + a.y * b.w,
a.x * b.y - a.y * b.x + a.w * b.z + a.z * b.w,
a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z);
}
inline quaternion operator+(const quaternion& a, const float r)
{
return quaternion(a.x + r, a.y + r, a.z + r, a.w + r);
}
inline quaternion operator+(const float r, const quaternion& a)
{
return quaternion(a.x + r, a.y + r, a.z + r, a.w + r);
}
inline quaternion operator-(const quaternion& a, const float r)
{
return quaternion(a.x - r, a.y - r, a.z - r, a.w - r);
}
inline quaternion operator-(const float r, const quaternion& a)
{
return quaternion(r - a.x, r - a.y, r - a.z, r - a.w);
}
inline quaternion operator*(const quaternion& a, const float r)
{
return quaternion(a.x * r, a.y * r, a.z * r, a.w * r);
}
inline quaternion operator*(const float r, const quaternion& a)
{
return quaternion(a.x * r, a.y * r, a.z * r, a.w * r);
}
inline quaternion operator/(const quaternion& a, const float r)
{
const float inv = 1.0f / r;
return quaternion(a.x * inv, a.y * inv, a.z * inv, a.w * r);
}
inline quaternion operator/(const float r, const quaternion& a)
{
return quaternion(r / a.x, r / a.y, r / a.z, r / a.w);
}
inline float dot(const quaternion& a, const quaternion& b)
{
return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w;
}
inline quaternion lerp(const quaternion& a, const quaternion& b, const float r)
{
return (b - a) * r + a;
}
inline quaternion QuatSlerp(const quaternion& a, const quaternion& b, const float r)
{
quaternion q3;
const float qr = dot(a, b);
const float ss = 1.0f - qr * qr;
float sp;
if (ss <= 0.0f || (sp = Sqrt(ss)) == 0.0f) {
q3 = a;
} else {
const float ph = Acos(qr);
const float pt = ph * r;
const float t1 = Sin(pt) / sp;
const float t0 = Sin(ph - pt) / sp;
q3 = a * t0 + b * t1;
}
return q3;
}
inline quaternion QuatSlerpNoInvert(const quaternion& a, const quaternion& b, const float r)
{
float d = dot(a, b);
if (d > -0.95f && d < 0.95f)
{
float angle = Cos(d);
return (a * Sin(angle*(1.0f - r)) + b * Sin(angle * r)) / Sin(angle);
}
else // if the angle is small, use linear interpolation
{
return lerp(a,b,r);
}
}
inline float QuatLength(const quaternion& a)
{
return Sqrt(a.w * a.w + a.x * a.x + a.y * a.y + a.z * a.z);
}
inline quaternion QuatNormalize(const quaternion& a)
{
return a / QuatLength(a);
}
inline bool operator==(const quaternion& a, const quaternion& b)
{
return (a.x == b.x) && (a.y == b.y) && (a.z == b.z) && (a.w == b.w);
}
inline bool operator!=(const quaternion& a, const quaternion& b)
{
return (a.x != b.x) || (a.y != b.y) || (a.z != b.z) || (a.w != b.w);
}
inline quaternion& operator*=(quaternion& a, const quaternion& b)
{
a = a * b; return a;
}
inline vec4 operator*(const quaternion& q, const vec4& v)
{
const float w = -q.x * v.x - q.y * v.y - q.z * v.z;
const float x = q.y * v.z - q.z * v.y + q.w * v.x;
const float y = q.z * v.x - q.x * v.z + q.w * v.y;
const float z = q.x * v.y - q.y * v.x + q.w * v.z;
return vec4(
y * -q.z + z * q.y - w * q.x + x * q.w,
z * -q.x + x * q.z - w * q.y + y * q.w,
x * -q.y + y * q.x - w * q.z + z * q.w,
w * q.w - x * q.x - y * q.y - z * q.z
);
}
inline quaternion QuatRotationAxis(const vec3& v, float degree)
{
const float rad = ToRadian(degree);
const float s = Sin(rad * 0.5f);
return quaternion(
v.x * s,
v.y * s,
v.z * s,
Cos(rad * 0.5f) );
}
inline float QuatAxisAngle(const quaternion& q, vec3& v)
{
float angle = Cos(q.w);
const float sin_inv = 1.0f / Sin(angle);
v.x = q.x * sin_inv;
v.y = q.y * sin_inv;
v.z = q.z * sin_inv;
angle *= 2.0f;
return angle;
}
inline quaternion QuatRotationYawPitchRoll(float yaw, float pitch, float roll)
{
const float cos_z = Cos(roll * 0.5f);
const float cos_y = Cos(pitch * 0.5f);
const float cos_x = Cos(yaw * 0.5f);
const float sin_z = Sin(roll * 0.5f);
const float sin_y = Sin(pitch * 0.5f);
const float sin_x = Sin(yaw * 0.5f);
return quaternion(
cos_z * cos_y * sin_x - sin_z * sin_y * cos_x,
cos_z * sin_y * cos_x + sin_z * cos_y * sin_x,
sin_z * cos_y * cos_x - cos_z * sin_y * sin_x,
cos_z * cos_y * cos_x + sin_z * sin_y * sin_x);
}
inline quaternion ToQuaternion(const matrix3x3& m)
{
const float tr = m.m[0][0] + m.m[1][1] + m.m[2][2] + 1.0f;
if (tr >= 1.0f)
{
const float s = 0.5f / Sqrt(tr);
return quaternion(
(m.m[1][2] - m.m[2][1]) * s,
(m.m[2][0] - m.m[0][2]) * s,
(m.m[0][1] - m.m[1][0]) * s,
0.25f / s);
}
else
{
float maxv;
if(m.m[1][1] > m.m[2][2]) maxv = m.m[1][1];
else maxv = m.m[2][2];
if (maxv < m.m[0][0])
{
float s = Sqrt(m.m[0][0] - (m.m[1][1] + m.m[2][2]) + 1.0f);
const float x = s * 0.5f;
s = 0.5f / s;
return quaternion(
x,
(m.m[0][1] + m.m[1][0]) * s,
(m.m[2][0] + m.m[0][2]) * s,
(m.m[1][2] - m.m[2][1]) * s);
}
else if (maxv == m.m[1][1])
{
float s = Sqrt(m.m[1][1] - (m.m[2][2] + m.m[0][0]) + 1.0f);
const float y = s * 0.5f;
s = 0.5f / s;
return quaternion(
(m.m[0][1] + m.m[1][0]) * s,
y,
(m.m[1][2] + m.m[2][1]) * s,
(m.m[2][0] - m.m[0][2]) * s);
}
else
{
float s = Sqrt(m.m[2][2] - (m.m[0][0] + m.m[1][1]) + 1.0f);
const float z = s * 0.5f;
s = 0.5f / s;
return quaternion(
(m.m[2][0] + m.m[0][2]) * s,
(m.m[1][2] + m.m[2][1]) * s,
z,
(m.m[0][1] - m.m[1][0]) * s);
}
}
}
inline quaternion ToQuaternion(const matrix4x4& m)
{
return ToQuaternion(matrix3x3(m));
}
inline matrix4x4 ToMatrix(const quaternion& q)
{
const float sx = q.x * q.x;
const float sy = q.y * q.y;
const float sz = q.z * q.z;
const float cx = q.y * q.z;
const float cy = q.x * q.z;
const float cz = q.x * q.y;
const float wx = q.w * q.x;
const float wy = q.w * q.y;
const float wz = q.w * q.z;
return matrix4x4(
1.0f - 2.0f * (sy + sz),
2.0f * (cz + wz),
2.0f * (cy - wy),
0.0f,
2.0f * (cz - wz),
1.0f - 2.0f * (sx + sz),
2.0f * (cx + wx),
0.0f,
2.0f * (cy + wy),
2.0f * (cx - wx),
1.0f - 2.0f * (sx + sy),
0.0f,
0.0f,0.0f,0.0f,1.0f
);
}
inline vec3 HSVtoRGB(float H, float S, float V)
{
vec3 rgb;
int i;
float fl;
float m, n;
i = (int)floor( H / 60 );
fl = ( H / 60 ) - i;
if( !(i & 1)) fl = 1 - fl; // if i is even
m = V * ( 1 - S );
n = V * ( 1 - S * fl );
#if 1
const float table[] = {m,m,n,V,V,n,m,m,n,V};
rgb.x = table[i + 4];
rgb.y = table[i + 2];
rgb.z = table[i ];
#else
switch( i ){
case 0: rgb.x = V; rgb.y = n; rgb.z = m; break;
case 1: rgb.x = n; rgb.y = V; rgb.z = m; break;
case 2: rgb.x = m; rgb.y = V; rgb.z = n; break;
case 3: rgb.x = m; rgb.y = n; rgb.z = V; break;
case 4: rgb.x = n; rgb.y = m; rgb.z = V; break;
case 5: rgb.x = V; rgb.y = m; rgb.z = n; break;
}
#endif
return rgb;
}
// Intersect Triagle
inline bool IntersectTriangle(const vec3& org, const vec3& dir,
const vec3& v0, const vec3 v1, const vec3& v2,
float& t, float& u, float& v)
{
static const float EPSILON = 1.0e-24f;//0.000001f;
const vec3 edge1 = v1 - v0;
const vec3 edge2 = v2 - v0;
const vec3 pvec = cross(dir, edge2);
const float det = dot(edge1, pvec);
// float side hit test
if (det > -EPSILON && det < EPSILON)
return false;
const float inv_det = 1.0f / det;
const vec3 tvec = org - v0;
u = dot(tvec, pvec) * inv_det;
if (u < 0.0f || u > 1.0f)
return false;
const vec3 qvec = cross(tvec, edge1);
v = dot(dir, qvec) * inv_det;
if (v < -0.0f || u + v > 1.0f)
return false;
t = dot(edge2, qvec) * inv_det;
return true;
}
inline float saturate(float x)
{
return ((x < 0.0f ? 0.0f : x) > 1.0f ? 1.0f : x);
}
inline float smoothstep (float a, float b, float x)
{
x = saturate((x - a) / (b - a));
return x*x*(3-2*x);
}
// =================== MultiComponent Index =======================
/// 2元index
struct idx2
{
int x,y;
idx2() { x = 0; y = 0; }
idx2(int x_, int y_) { x = x_; y = y_; }
idx2(const int* const v) { x = v[0]; y = v[1]; }
idx2 operator-() const { return idx2(-x, -y); }
int & operator[](int i) { return (&x)[i]; }
int const & operator[](int i) const { return (&y)[i]; }
idx2& operator+=(const idx2& a) { x += a.x; y += a.y; return *this; }
idx2& operator-=(const idx2& a) { x -= a.x; y -= a.y; return *this; }
idx2& operator+=(int s) { x += s; y += s; return *this; }
idx2& operator-=(int s) { x -= s; y -= s; return *this; }
idx2& operator*=(int s) { x *= s; y *= s; return *this; }
};
/// 3元index
struct idx3
{
int x,y,z;
idx3() { x = 0; y = 0; z = 0; }
idx3(const idx2& v, int z_ = 0) { x = v.x; y = v.y; z = z_; }
idx3(int x_, int y_, int z_) { x = x_; y = y_; z = z_; }
idx3(const int* const v) { x = v[0]; y = v[1]; z = v[2]; }
idx3 operator-() const { return idx3(-x, -y, -z); }
int & operator[](int i) { return (&x)[i]; }
int const & operator[](int i) const { return (&x)[i]; }
idx3& operator+=(const idx3& a) { x += a.x; y += a.y; z += a.z; return *this; }
idx3& operator-=(const idx3& a) { x -= a.x; y -= a.y; z -= a.z; return *this; }
idx3& operator+=(int s) { x += s; y += s; z += s; return *this; }
idx3& operator-=(int s) { x -= s; y -= s; z -= s; return *this; }
idx3& operator*=(int s) { x *= s; y *= s; z *= s; return *this; }
};
// ----------------------------- idx3 -----------------------------------
inline idx3 operator+(const idx3& a, const idx3& b)
{
return idx3(a.x + b.x, a.y + b.y, a.z + b.z);
}
inline idx3 operator+(const int r, const idx3& a)
{
return idx3(a.x + r, a.y + r, a.z + r);
}
inline idx3 operator+(const idx3& a, const int r)
{
return idx3(a.x + r, a.y + r, a.z + r);
}
inline idx3 operator-(const idx3& a, const idx3& b)
{
return idx3(a.x - b.x, a.y - b.y, a.z - b.z);
}
inline idx3 operator-(const int r, const idx3& a)
{
return idx3(a.x - r, a.y - r, a.z - r);
}
inline idx3 operator-(const idx3& a, const int r)
{
return idx3(a.x - r, a.y - r, a.z - r);
}
inline idx3 operator*(const int r, const idx3& a)
{
return idx3(a.x * r, a.y * r, a.z * r);
}
inline idx3 operator*(const idx3& a, const int r)
{
return idx3(a.x * r, a.y * r, a.z * r);
}
inline bool operator==(const idx3& a, const idx3& b)
{
return (a.x == b.x) && (a.y == b.y) && (a.z == b.z);
}
inline bool operator!=(const idx3& a, const idx3& b)
{
return (a.x != b.x) || (a.y != b.y) || (a.z != b.z);
}
// ----------------------------- idx2 -----------------------------------
inline idx2 operator+(const idx2& a, const idx2& b)
{
return idx2(a.x + b.x, a.y + b.y);
}
inline idx2 operator+(const int r, const idx2& a)
{
return idx2(a.x + r, a.y + r);
}
inline idx2 operator+(const idx2& a, const int r)
{
return idx2(a.x + r, a.y + r);
}
inline idx2 operator-(const idx2& a, const idx2& b)
{
return idx2(a.x - b.x, a.y - b.y);
}
inline idx2 operator-(const int r, const idx2& a)
{
return idx2(a.x - r, a.y - r);
}
inline idx2 operator-(const idx2& a, const int r)
{
return idx2(a.x - r, a.y - r);
}
inline idx2 operator*(const int r, const idx2& a)
{
return idx2(a.x * r, a.y * r);
}
inline idx2 operator*(const idx2& a, const int r)
{
return idx2(a.x * r, a.y * r);
}
inline bool operator==(const idx2& a, const idx2& b)
{
return (a.x == b.x) && (a.y == b.y);
}
inline bool operator!=(const idx2& a, const idx2& b)
{
return (a.x != b.x) || (a.y != b.y);
}
} // Math
} // VX
#endif // INCLUDE_VX_MATH_H
| 26.489159 | 102 | 0.497934 | [
"vector"
] |
bf69edbee5e075370575fa9c4f42a3f9def02b4d | 2,579 | h | C | include/user_config.h | istiaqMahbub/espIrKit | 999491ea734a7433bf7cdf49375200f11c297f30 | [
"Unlicense"
] | null | null | null | include/user_config.h | istiaqMahbub/espIrKit | 999491ea734a7433bf7cdf49375200f11c297f30 | [
"Unlicense"
] | null | null | null | include/user_config.h | istiaqMahbub/espIrKit | 999491ea734a7433bf7cdf49375200f11c297f30 | [
"Unlicense"
] | null | null | null | #ifndef __USER_CONFIG_H__
#define __USER_CONFIG_H__
#include "c_types.h"
#define MESH_DEMO_PRINT ets_printf
#define MESH_DEMO_STRLEN ets_strlen
#define MESH_DEMO_MEMCPY ets_memcpy
#define MESH_DEMO_MEMSET ets_memset
#define MESH_DEMO_FREE os_free
#define MESH_DEMO_ZALLOC os_zalloc
#define MESH_DEMO_MALLOC os_malloc
#define MESH_GROUP_ID_LEN 6
static const uint16_t server_port = 7000; /*PORT USED BY USER IOT SERVER FOR MESH SERVICE*/
static const uint8_t server_ip[4] = {192, 168, 0, 105}; /*USER IOT SERVER IP ADDRESS*/
static const uint32_t UART_BAUD_RATIO = 19200; /*UART BAUD RATIO*/
static const uint8_t MESH_GROUP_ID[MESH_GROUP_ID_LEN] = {0x18,0xfe,0x34,0x00,0x00,0x50}; /*MESH_GROUP_ID & MESH_SSID_PREFIX REPRESENTS ONE MESH NETWORK*/
static const uint8_t MESH_ROUTER_BSSID[6] = {0xF0, 0xB4, 0x29, 0x2C, 0x7C, 0x72}; /*MAC OF ROUTER*/
/*
* please change MESH_ROUTER_SSID and MESH_ROUTER_PASSWD according to your router
*/
#define MESH_ROUTER_SSID "kanokshome" /*THE ROUTER SSID*/
#define MESH_ROUTER_PASSWD "amijanina" /*THE ROUTER PASSWORD*/
#define MESH_SSID_PREFIX "MESH_DEMO" /*SET THE DEFAULT MESH SSID PREFIX;THE FINAL SSID OF SOFTAP WOULD BE "MESH_SSID_PREFIX_X_YYYYYY"*/
#define MESH_AUTH AUTH_WPA2_PSK /*AUTH_MODE OF SOFTAP FOR EACH MESH NODE*/
#define MESH_PASSWD "123123123" /*SET PASSWORD OF SOFTAP FOR EACH MESH NODE*/
#define MESH_MAX_HOP (4) /*MAX_HOPS OF MESH NETWORK*/
#ifndef _USER_CONFIG_H_
#define _USER_CONFIG_H_
/*#ifndef ESP_MESH_SUPPORT
//#define ESP_MESH_SUPPORT 1
#endif*/
#define CFG_HOLDER 0x00FF55A7 /* Change this value to load default configurations */
#define CFG_LOCATION 0x3C /* Please don't change or if you know what you doing */
#define CLIENT_SSL_ENABLE
/*DEFAULT CONFIGURATIONS*/
#define MQTT_HOST "m10.cloudmqtt.com" //or "mqtt.yourdomain.com"
#define MQTT_PORT 14081
#define MQTT_BUF_SIZE 1024
#define MQTT_KEEPALIVE 120 /*second*/
#define MQTT_CLIENT_ID "DVES_%08X"
#define MQTT_USER "qdqowxwy"
#define MQTT_PASS "ZEp3mmEAYur-"
#define STA_SSID "testSSID"
#define STA_PASS "123456789"
#define STA_TYPE AUTH_WPA2_PSK
#define SOFTAP_SSID "knk_%08X"
#define SOFTAP_PASS "janina123"
#define MQTT_RECONNECT_TIMEOUT 5 /*second*/
#define DEFAULT_SECURITY 0
#define QUEUE_BUFFER_SIZE 2048
#define PROTOCOL_NAMEv31 /*MQTT version 3.1 compatible with Mosquitto v0.15*/
//#define PROTOCOL_NAMEv311 /*MQTT version 3.11 compatible with https://eclipse.org/paho/clients/testing/*/
#endif
#endif
| 32.2375 | 154 | 0.752617 | [
"mesh"
] |
bf72d16fa150d1699a67f419b220cdb3bd65262d | 3,840 | h | C | samples/common/video_parser.h | YJessicaGao/easydk | e62eecde91886c2679def95edafb48f97650edfa | [
"Apache-2.0"
] | null | null | null | samples/common/video_parser.h | YJessicaGao/easydk | e62eecde91886c2679def95edafb48f97650edfa | [
"Apache-2.0"
] | null | null | null | samples/common/video_parser.h | YJessicaGao/easydk | e62eecde91886c2679def95edafb48f97650edfa | [
"Apache-2.0"
] | null | null | null | /*************************************************************************
* Copyright (C) [2020] by Cambricon, Inc. All rights reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 EDK_SAMPLES_VIDEO_PARSER_H_
#define EDK_SAMPLES_VIDEO_PARSER_H_
#include <atomic>
#include <chrono>
#include <fstream>
#include <memory>
#include <string>
#include <vector>
#include "easycodec/easy_decode.h"
#include "easycodec/vformat.h"
#ifdef __cplusplus
extern "C" {
#endif
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libavutil/avutil.h>
#include <libavutil/imgutils.h>
#ifdef __cplusplus
}
#endif
#define FFMPEG_VERSION_3_1 AV_VERSION_INT(57, 40, 100)
#define FFMPEG_VERSION_4_2_2 AV_VERSION_INT(58, 29, 100)
namespace detail {
struct BeginWith {
explicit BeginWith(const std::string& str) noexcept : s(str) {}
inline bool operator()(const std::string& prefix) noexcept {
if (s.size() < prefix.size()) return false;
return prefix == s.substr(0, prefix.size());
}
std::string s;
}; // struct BeginWith
class FileSaver {
public:
explicit FileSaver(const char* file_name) {
of_.open(file_name);
if (!of_.is_open()) {
throw std::runtime_error("open file failed");
}
}
~FileSaver() { of_.close(); }
void Write(char* buf, size_t len) { of_.write(buf, len); }
private:
std::ofstream of_;
};
} // namespace detail
inline bool IsRtsp(const std::string& url) { return detail::BeginWith(url)("rtsp://"); }
struct VideoInfo {
AVCodecID codec_id = AV_CODEC_ID_NONE;
#if LIBAVFORMAT_VERSION_INT >= FFMPEG_VERSION_3_1
AVCodecParameters* codecpar = nullptr;
#endif
AVCodecContext* codec_ctx = nullptr;
std::vector<uint8_t> extra_data{};
int width = 0;
int height = 0;
int progressive = 0;
};
class IDemuxEventHandle {
public:
virtual bool OnParseInfo(const VideoInfo& info) = 0;
virtual bool OnPacket(const AVPacket* frame) = 0;
virtual void OnEos() = 0;
virtual bool Running() = 0;
virtual void Destroy() = 0;
};
class VideoParser {
public:
explicit VideoParser(IDemuxEventHandle* handle) : handler_(handle) {}
~VideoParser() { Close(); }
bool Open(const char* url, bool save_file = false);
// -1 for error, 1 for eos
int ParseLoop(uint32_t frame_interval);
void Close();
bool CheckTimeout();
bool IsRtsp() { return is_rtsp_; }
const VideoInfo& GetVideoInfo() const { return info_; }
private:
static constexpr uint32_t max_receive_timeout_{3000};
AVFormatContext* p_format_ctx_ = nullptr;
AVPacket packet_;
AVDictionary* options_{nullptr};
VideoInfo info_;
IDemuxEventHandle* handler_;
std::unique_ptr<detail::FileSaver> saver_{nullptr};
std::chrono::time_point<std::chrono::steady_clock> last_receive_frame_time_{};
uint64_t frame_index_{0};
int32_t video_index_{0};
std::atomic<bool> have_video_source_{false};
bool first_frame_{true};
bool is_rtsp_{false};
};
#endif // EDK_SAMPLES_VIDEO_PARSER_H_
| 29.090909 | 88 | 0.696615 | [
"vector"
] |
bf79ee6777557c01a9042d857571031a26637480 | 3,123 | h | C | src/world.h | Niki4tap/asciicker | 1fd314f940d166217deb2dfcedc5a6ccead40243 | [
"MIT"
] | 78 | 2021-06-10T12:02:07.000Z | 2021-09-07T16:22:28.000Z | world.h | Emupedia/asciiid | 777f0a163ddfa65e5704edc88fdcd810356d2c89 | [
"MIT"
] | 3 | 2021-06-10T14:19:40.000Z | 2021-09-09T20:00:02.000Z | world.h | Emupedia/asciiid | 777f0a163ddfa65e5704edc88fdcd810356d2c89 | [
"MIT"
] | 15 | 2021-06-10T13:29:00.000Z | 2021-09-07T16:22:21.000Z |
#pragma once
struct World;
struct Mesh;
struct Inst;
struct Sprite;
struct Item;
World* CreateWorld();
void DeleteWorld(World* w);
void RebuildWorld(World* w, bool boxes = false);
Mesh* LoadMesh(World* w, const char* path, const char* name = 0);
void DeleteMesh(Mesh* m);
bool UpdateMesh(Mesh* m, const char* path);
Mesh* GetFirstMesh(World* w);
Mesh* GetLastMesh(World* w);
Mesh* GetPrevMesh(Mesh* m);
Mesh* GetNextMesh(Mesh* m);
void* GetMeshCookie(Mesh* m);
void SetMeshCookie(Mesh* m, void* cookie);
World* GetMeshWorld(Mesh* m);
int GetMeshName(Mesh* m, char* buf, int size);
void GetMeshBBox(Mesh* m, float bbox[6]);
int GetMeshFaces(Mesh* m);
void QueryMesh(Mesh* m, void (*cb)(float coords[9], uint8_t colors[12], uint32_t visual, void* cookie), void* cookie);
Inst* CreateInst(World* w, Item* item, int flags, float pos[3], float yaw, int story_id);
Inst* CreateInst(World* w, Sprite* s, int flags, float pos[3], float yaw, int anim, int frame, int reps[4], const char* name, int story_id);
Inst* CreateInst(Mesh* m, int flags, const double tm[16], const char* name, int story_id);
void DeleteInst(Inst* i);
World* GetInstWorld(Inst* i);
Mesh* GetInstMesh(Inst* i);
int GetInstFlags(Inst* i);
int GetInstStoryID(Inst* i);
bool GetInstTM(Inst* i, double tm[16]);
void GetInstBBox(Inst* i, double bbox[6]);
void UpdateSpriteInst(World* world, Inst* i, Sprite* sprite, const float pos[3], float yaw, int anim, int frame, const int reps[4]);
Sprite* GetInstSprite(Inst* i, float pos[3], float* yaw, int* anim, int* frame, int reps[4]);
bool SetInstSpriteData(Inst* i, void* data);
void* GetInstSpriteData(Inst* i);
Item* GetInstItem(Inst* i, float pos[3], float* yaw);
int AnimateSpriteInst(Inst* i, uint64_t stamp);
void ShowInst(Inst* i);
void HideInst(Inst* i);
enum INST_FLAGS
{
INST_VISIBLE = 0x1,
INST_USE_TREE = 0x2,
INST_VOLATILE = 0x4
};
// new
// void QueryWorld(World* w, int planes, double plane[][4], void(*cb)(Sprite* s, float pos[3], float yaw, int anim, float frame, void* cookie), void* cookie);
struct QueryWorldCB
{
void(*mesh_cb)(Mesh* m, double tm[16], void* cookie);
void(*sprite_cb)(Inst* inst, Sprite* s, float pos[3], float yaw, int anim, int frame, int reps[4], void* cookie);
};
void QueryWorld(World* w, int planes, double plane[][4], QueryWorldCB* cb, void* cookie);
void QueryWorldBSP(World* w, int planes, double plane[][4], void (*cb)(int level, const float bbox[6], void* cookie), void* cookie);
// if editor==true -> ignore volatile instances
Inst* HitWorld(World* w, double p[3], double v[3], double ret[3], double nrm[3], bool positive_only = false, bool editor = false, bool solid_only = false, bool sprites_too = true);
void SaveWorld(World* w, FILE* f);
// editor==true clones items for test-players
// editor==false changes items purpose directly for player(s)
World* LoadWorld(FILE* f, bool editor);
void PurgeItemInstCache();
void ResetItemInsts(World* w);
bool AttachInst(World* w, Inst* i); // tries to move from flat list to bsp
// undo/redo only!!!
void SoftInstAdd(Inst* i);
void SoftInstDel(Inst* i);
void HardInstDel(Inst* i);
| 31.867347 | 180 | 0.708614 | [
"mesh"
] |
ba8968c1ec56623342f77bb231f64b504225d699 | 3,399 | h | C | MintRobotTeachingPad/app/View/ProjectEditor/Dialog/DialogNodeDelay.h | mintrobot/MTP | f6775ac3552e00f3d69ab78c579d875eac2e1b1e | [
"BSD-3-Clause"
] | 1 | 2021-03-28T07:25:52.000Z | 2021-03-28T07:25:52.000Z | MintRobotTeachingPad/app/View/ProjectEditor/Dialog/DialogNodeDelay.h | mintrobot/MTP | f6775ac3552e00f3d69ab78c579d875eac2e1b1e | [
"BSD-3-Clause"
] | null | null | null | MintRobotTeachingPad/app/View/ProjectEditor/Dialog/DialogNodeDelay.h | mintrobot/MTP | f6775ac3552e00f3d69ab78c579d875eac2e1b1e | [
"BSD-3-Clause"
] | null | null | null | /*
********************************************************************************************
* Copyright (c) 2019 MINTROBOT Co., Ltd.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the <MINTROBOT Co, Ltd.> nor the names of its contributors
may be used to endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
********************************************************************************************
**/
#ifndef WAITNODESETTING_H
#define WAITNODESETTING_H
#include "app/view/util/Dialog.h"
#include "app/view/util/WidgetKeypad.h"
#include "app/model/nodes/ModelNodeDelay.h"
#include "DialogNode.h"
class DialogNodeDelay : public DialogNode
{
Q_OBJECT
//______________________________________________________
public:
explicit DialogNodeDelay(QWidget *parent = nullptr);
virtual ~DialogNodeDelay() override;
void initValue();
void setValue(const ModelNodeDelay& modelNodeDelay);
const ModelNodeDelay& getValue();
//______________________________________________________
protected:
virtual void resizeEvent(QResizeEvent * event) override;
//______________________________________________________
private:
ModelNodeDelay __modelNodeDelay;
double __ratioMargin = 3;
double __ratioWidthLabel = 30;
double __ratioWidthLabelValue = 81;
double __ratioHeightLabel = 10;
double __ratioWidthKeypad = 94;
double __ratioHeightKeypad = 81;
int __widthMargin;
int __heightMargin;
int __widthLabel;
int __heightLabel;
int __widthLabelValue;
int __heightLabelValue;
int __widthKeypad;
int __heightKeypad;
WidgetLabel* __pLabel;
WidgetLabel* __pLabelValue;
WidgetKeypad* __pKeypadNumber;
//---
unsigned int __delayms;
//______________________________________________________
signals:
//______________________________________________________
private slots:
void updateValue(QString value);
};
//__________________________________________________________
#endif // WAITNODESETTING_H
| 36.548387 | 92 | 0.71521 | [
"model"
] |
ba8d7d31f088e6c822fee7e4dabb6aee0ee75852 | 5,943 | h | C | cylinder.h | ryanseys/opengl-molecules | 3383f0732f5bbfda5c51e87d35cee8fa58cde0ce | [
"MIT"
] | 7 | 2015-01-06T13:52:47.000Z | 2021-09-01T16:10:05.000Z | cylinder.h | ryanseys/opengl-molecules | 3383f0732f5bbfda5c51e87d35cee8fa58cde0ce | [
"MIT"
] | 4 | 2015-01-07T16:11:17.000Z | 2018-02-27T07:18:22.000Z | cylinder.h | ryanseys/opengl-molecules | 3383f0732f5bbfda5c51e87d35cee8fa58cde0ce | [
"MIT"
] | 4 | 2018-08-08T12:54:54.000Z | 2021-09-16T13:09:07.000Z | /**
* This sphere class was derived from Professor Nussbaum's solution.
*
* It was modified by Ryan Seys to add colors to the spheres and
* rotation transformation.
*/
#ifndef RYAN_CYLINDER
#define RYAN_CYLINDER
#include <stdlib.h>
#include <cmath>
#include "ryan_vector.h"
#include "ryan_matrix.h"
struct Vertex{
Vertex(){}
Vertex( const Vector3f& _pos, const Vector3f& _nor ){
pos[0] = _pos.x;
pos[1] = _pos.y;
pos[2] = _pos.z;
pos[3] = 1.0f;
norm[0] = _nor.x;
norm[1] = _nor.y;
norm[2] = _nor.z;
norm[3] = 1.0f;
}
float pos[4];
float norm[4];
};
class Cylinder {
protected:
std::vector<Vertex> m_vertices;
std::vector<GLuint> m_indices;
GLuint m_vbo;
GLuint m_idxVbo;
Matrix4f modelMat = Matrix4f::identity();
Matrix4f rotMat = Matrix4f::identity();
public:
Vector4f materialAmbient = Vector4f(1, 1, 1, 1);
Vector4f materialDiffuse = Vector4f(1, 1, 1, 1);
Vector4f materialSpecular = Vector4f(1, 1, 1, 1);
Cylinder(int sectors) {
m_vertices.resize( (sectors * 2) + 2 );
m_indices.resize( (sectors - 1) * 12 );
//create the vertices
float S = 1.0f / ( sectors - 1.0f );
int i = 0;
for( int s = 0; s < sectors; ++s ){
float x = (float) cos( 2 * M_PI * s * S );
float z = (float) sin( 2 * M_PI * s * S );
m_vertices[s] = Vertex( Vector3f( x, 1.0f, z ), Vector3f( x, 1.0f, z ) );
m_vertices[s+sectors] = Vertex( Vector3f( x, -1.0f, z ), Vector3f( x, 1.0f, z ) );
}
m_vertices[sectors*2] = Vertex( Vector3f( 0, 1.0f, 0 ), Vector3f( 0, 1.0f, 0 ));
m_vertices[sectors*2 + 1] = Vertex( Vector3f( 0, -1.0f, 0 ), Vector3f( 0, -1.0f, 0 ));
//create the indices
i = 0;
for( int s = 0; s < sectors - 1; ++s ){
m_indices[i++] = s + 1;
m_indices[i++] = s + sectors;
m_indices[i++] = s;
m_indices[i++] = s + 1 + sectors;
m_indices[i++] = s + sectors;
m_indices[i++] = s + 1;
}
for( int s = 0; s < sectors - 1; ++s ){
m_indices[i++] = s + 1;
m_indices[i++] = s;
m_indices[i++] = sectors * 2;
m_indices[i++] = s + 1 + sectors;
m_indices[i++] = s + sectors;
m_indices[i++] = sectors * 2 + 1;
}
glGenBuffers(1, &m_vbo);
glBindBuffer( GL_ARRAY_BUFFER, m_vbo );
glBufferData( GL_ARRAY_BUFFER, m_vertices.size() * sizeof(Vertex), m_vertices.data(), GL_STATIC_DRAW);
//create index buffer
glGenBuffers( 1, &m_idxVbo );
glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, m_idxVbo );
glBufferData( GL_ELEMENT_ARRAY_BUFFER, m_indices.size() * sizeof(GLuint), m_indices.data(), GL_STATIC_DRAW );
}
/**
* Rotate the sphere around the y-axis.
*
* @param degrees Degrees to rotate it.
*/
void rotateY(GLfloat angle, GLuint deg) {
Matrix4f tempRot = Matrix4f::rotateY(angle, deg);
rotMat = rotMat * tempRot;
modelMat = modelMat * tempRot;
}
void rotateX(GLfloat angle, GLuint deg) {
Matrix4f tempRot = Matrix4f::rotateX(angle, deg);
rotMat = rotMat * tempRot;
modelMat = modelMat * tempRot;
}
void rotateZ(GLfloat angle, GLuint deg) {
Matrix4f tempRot = Matrix4f::rotateZ(angle, deg);
rotMat = rotMat * tempRot;
modelMat = modelMat * tempRot;
}
void rotateVector(Vector3f v, GLfloat angle, int degrees) {
Matrix4f tempRot = Matrix4f::rotateVector(v, angle, degrees);
rotMat = rotMat * tempRot;
modelMat = modelMat * tempRot;
}
/**
* Draw the sphere using the supplied shaderProgram.
* @param shaderProg Shader program to use.
*/
void draw(GLuint shaderProg) {
Matrix4f normalMat = Matrix4f::transpose(Matrix4f::inverse(this->rotMat));
// modelMat = modelMat * Matrix4f::scale(4, 4, 4);
GLuint modelLoc = glGetUniformLocation(shaderProg, "modelMat");
glUniformMatrix4fv(modelLoc, 1, 1, (float *) modelMat.vm);
GLuint normalMatLoc = glGetUniformLocation(shaderProg, "normalMat");
glUniformMatrix4fv(normalMatLoc, 1, 1, (float *) normalMat.vm);
GLuint matAmbLoc = glGetUniformLocation(shaderProg, "materialAmb");
glUniform4fv(matAmbLoc, 1, (float *) &materialAmbient);
GLuint matDiffLoc = glGetUniformLocation(shaderProg, "materialDiff");
glUniform4fv(matDiffLoc, 1, (float *) &materialDiffuse);
GLuint matSpecLoc = glGetUniformLocation(shaderProg, "materialSpec");
glUniform4fv(matSpecLoc, 1, (float *) &materialSpecular);
//copy the vertex position
GLint vtxLoc = glGetAttribLocation( shaderProg, "vPosition");
GLuint normalLoc = glGetAttribLocation(shaderProg, "vNormal");
glEnableVertexAttribArray( vtxLoc );
glEnableVertexAttribArray(normalLoc);
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_idxVbo);
glVertexAttribPointer(vtxLoc, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*) offsetof(Vertex, pos));
glVertexAttribPointer(normalLoc, 4, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*) offsetof(Vertex, norm));
glDrawElements( GL_TRIANGLES, m_indices.size(), GL_UNSIGNED_INT, NULL );
this->clear();
}
void scale(GLfloat xAmt, GLfloat yAmt, GLfloat zAmt) {
modelMat = modelMat * Matrix4f::scale(xAmt, yAmt, zAmt);
}
void translate(GLfloat x, GLfloat y, GLfloat z) {
modelMat = modelMat * Matrix4f::translation(x, y, z);
}
void rotateVector(Vector3f v, float deg) {
modelMat = modelMat * Matrix4f::rotateVector(v, deg, 1);
}
void setAmbient(GLfloat r, GLfloat g, GLfloat b) {
this->materialAmbient = Vector4f(r, g, b, 0.0);
}
void setDiffuse(GLfloat r, GLfloat g, GLfloat b) {
this->materialDiffuse = Vector4f(r, g, b, 0.0);
}
void setSpecular(GLfloat r, GLfloat g, GLfloat b) {
this->materialSpecular = Vector4f(r, g, b, 0.0);
}
void clear() {
this->modelMat = Matrix4f::identity();
this->rotMat = Matrix4f::identity();
}
};
#endif
| 30.953125 | 113 | 0.634191 | [
"vector"
] |
ba8fdd05b2653514ded737762c71819f9d8d54e5 | 3,915 | h | C | Base/QTGUI/qSlicerSettingsViewsPanel.h | forfullstack/slicersources-src | 91bcecf037a27f3fad4c0ab57e8286fc258bb0f5 | [
"Apache-2.0"
] | null | null | null | Base/QTGUI/qSlicerSettingsViewsPanel.h | forfullstack/slicersources-src | 91bcecf037a27f3fad4c0ab57e8286fc258bb0f5 | [
"Apache-2.0"
] | null | null | null | Base/QTGUI/qSlicerSettingsViewsPanel.h | forfullstack/slicersources-src | 91bcecf037a27f3fad4c0ab57e8286fc258bb0f5 | [
"Apache-2.0"
] | null | null | null | /*==============================================================================
Program: 3D Slicer
Copyright (c) Kitware Inc.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
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.
This file was originally developed by Johan Andruejol, Kitware Inc.
and was partially funded by NIH grant 3P41RR013218-12S1
==============================================================================*/
#ifndef __qSlicerSettingsViewsPanel_h
#define __qSlicerSettingsViewsPanel_h
// CTK includes
#include <ctkSettingsPanel.h>
// QtGUI includes
#include "qSlicerBaseQTGUIExport.h"
class QSettings;
class qSlicerSettingsViewsPanelPrivate;
class Q_SLICER_BASE_QTGUI_EXPORT qSlicerSettingsViewsPanel
: public ctkSettingsPanel
{
Q_OBJECT
/// Holds the current MSAA's name for the settings.
/// The current MSAA setting can be accessed using qSlicerApplication
/// \sa currentMSAA(), setCurrentMSAA()
Q_PROPERTY(QString currentMSAA READ currentMSAA WRITE setCurrentMSAA NOTIFY currentMSAAChanged)
Q_PROPERTY(QString sliceOrientationMarkerType READ sliceOrientationMarkerType WRITE setSliceOrientationMarkerType NOTIFY currentSliceOrientationMarkerTypeChanged)
Q_PROPERTY(QString sliceOrientationMarkerSize READ sliceOrientationMarkerSize WRITE setSliceOrientationMarkerSize NOTIFY currentSliceOrientationMarkerSizeChanged)
Q_PROPERTY(QString sliceRulerType READ sliceRulerType WRITE setSliceRulerType NOTIFY currentSliceRulerTypeChanged)
Q_PROPERTY(QString threeDOrientationMarkerType READ threeDOrientationMarkerType WRITE setThreeDOrientationMarkerType NOTIFY currentThreeDOrientationMarkerTypeChanged)
Q_PROPERTY(QString threeDOrientationMarkerSize READ threeDOrientationMarkerSize WRITE setThreeDOrientationMarkerSize NOTIFY currentThreeDOrientationMarkerSizeChanged)
Q_PROPERTY(QString threeDRulerType READ threeDRulerType WRITE setThreeDRulerType NOTIFY currentThreeDRulerTypeChanged)
public:
/// Superclass typedef
typedef ctkSettingsPanel Superclass;
/// Constructor
explicit qSlicerSettingsViewsPanel(QWidget* parent = nullptr);
/// Destructor
~qSlicerSettingsViewsPanel() override;
/// Get current value as string
QString currentMSAA() const;
QString sliceOrientationMarkerType() const;
QString sliceOrientationMarkerSize() const;
QString sliceRulerType() const;
QString threeDOrientationMarkerType() const;
QString threeDOrientationMarkerSize() const;
QString threeDRulerType() const;
public slots:
/// Change the current value based on its name
void setCurrentMSAA(const QString&);
void setSliceOrientationMarkerType(const QString&);
void setSliceOrientationMarkerSize(const QString&);
void setSliceRulerType(const QString&);
void setThreeDOrientationMarkerType(const QString&);
void setThreeDOrientationMarkerSize(const QString&);
void setThreeDRulerType(const QString&);
signals:
/// Signal emitted when the current value is changed
void currentMSAAChanged(const QString&);
void currentSliceOrientationMarkerTypeChanged(const QString&);
void currentSliceOrientationMarkerSizeChanged(const QString&);
void currentSliceRulerTypeChanged(const QString&);
void currentThreeDOrientationMarkerTypeChanged(const QString&);
void currentThreeDOrientationMarkerSizeChanged(const QString&);
void currentThreeDRulerTypeChanged(const QString&);
protected slots:
void onMSAAChanged(const QString&);
protected:
QScopedPointer<qSlicerSettingsViewsPanelPrivate> d_ptr;
private:
Q_DECLARE_PRIVATE(qSlicerSettingsViewsPanel);
Q_DISABLE_COPY(qSlicerSettingsViewsPanel);
};
#endif
| 39.94898 | 168 | 0.795658 | [
"3d"
] |
ba91068c6e06c4a090fc310c9818984b1daca6f4 | 2,359 | h | C | src/BinaryTrigonOp.h | terraform123/metal | 73a76f94fa3fc62210cbc79da76f8c070aeb143b | [
"MIT"
] | 2 | 2019-03-12T18:54:50.000Z | 2020-04-22T14:24:02.000Z | src/BinaryTrigonOp.h | mrspacemankey/metal | 73a76f94fa3fc62210cbc79da76f8c070aeb143b | [
"MIT"
] | null | null | null | src/BinaryTrigonOp.h | mrspacemankey/metal | 73a76f94fa3fc62210cbc79da76f8c070aeb143b | [
"MIT"
] | null | null | null | #ifndef METAL_BINARYTRIGONOP_H
#define METAL_BINARYTRIGONOP_H
#include "src/ScalarBinaryOp.h"
#include <cmath>
namespace metal
{
/**
* @brief Unary operation taken by \ref ScalarBinaryOp object to define the expression for
* computing the sine of an expression.
*/
class Atan2Op
{
public:
/**
* @brief Applies the transformation on the value of an expression.
*
* @param left LHS of the operation
* @param right RHS of the operation
* @return double Result of operation
*/
double applyToValue( double left, double right ) const
{
return std::atan2( left, right );
}
/**
* @brief Computes the partial derivative of the result w.r.t the LHS.
*
* @return double Partial w.r.t. the LHS
*/
double leftPartial( double left, double right ) const
{
return right / cache( left, right );
}
/**
* @brief Computes the partial derivative of the result w.r.t the RHS.
*
* @return double Partial w.r.t. the RHS
*/
double rightPartial( double left, double right ) const
{
return -left / cache( left, right );
}
private:
struct Cache
{
static bool same( double left, double right )
{
return std::fabs( left - right ) <= 0.0;
}
double left;
double right;
double norm;
};
double cache( double left, double right ) const
{
if ( !Cache::same( left, cache_.left ) || !Cache::same( right, cache_.right ) )
{
cache_ = { left, right, left * left + right * right };
}
return cache_.norm;
}
mutable Cache cache_;
};
/**
* @brief Binary arc tangent function for two expressions.
*
* @tparam Left Type of the LHS expression
* @tparam Right Type of the RHS expression
* @param left LHS expression
* @param right RHS expression
* @return ScalarBinaryOp< Left, Right, Atan2Op > Expression that represents the arc tangent
* function
*/
template< typename Left, typename Right >
ScalarBinaryOp< Left, Right, Atan2Op > atan2(
const ScalarBase< Left >& left, const ScalarBase< Right >& right )
{
return ScalarBinaryOp< Left, Right, Atan2Op >(
static_cast< const Left& >( left ), static_cast< const Right& >( right ), Atan2Op{} );
}
} // metal
#endif // METAL_BINARYTRIGONOP_H
| 23.828283 | 94 | 0.622298 | [
"object"
] |
baaf1efe7f53be280366e150f64ba61ec69c03dc | 3,678 | h | C | CombineAnalysis/interface/SampleListing.h | enochnotsocool/TstarAnalysis_in_CMS | 84e695e7fc43188fcabe18468399a5fe4b909efb | [
"MIT"
] | null | null | null | CombineAnalysis/interface/SampleListing.h | enochnotsocool/TstarAnalysis_in_CMS | 84e695e7fc43188fcabe18468399a5fe4b909efb | [
"MIT"
] | null | null | null | CombineAnalysis/interface/SampleListing.h | enochnotsocool/TstarAnalysis_in_CMS | 84e695e7fc43188fcabe18468399a5fe4b909efb | [
"MIT"
] | null | null | null | /*******************************************************************************
*
* Filename : SampleListing.h
* Description : Container classes for SampleMgr to organize by type
* Author : Yi-Mu "Enoch" Chen [ ensc@hep1.phys.ntu.edu.tw ]
*
*******************************************************************************/
#ifndef __SAMPLELISTING_H__
#define __SAMPLELISTING_H__
#include "TstarAnalysis/CombineAnalysis/interface/SampleMgr.h"
#include <vector>
#include <string>
class SampleTable;
extern SampleTable availableSamples;
extern bool InitSampleList(const std::string& );
extern void PrintSampleList();
class SampleList
{
public:
SampleList( const std::string&, const std::string& );
SampleList( const SampleList& );
virtual ~SampleList ();
//----- Container like access functions ---------------------------------------
typedef std::vector<SampleMgr>::iterator iterator;
typedef std::vector<SampleMgr>::const_iterator const_iterator;
iterator begin() { return _sampleList.begin(); }
iterator end() { return _sampleList.end() ; }
const_iterator begin() const { return _sampleList.begin(); }
const_iterator end() const { return _sampleList.end(); }
void AddSample( const SampleMgr& x ) { _sampleList.push_back(x); }
SampleMgr& front() { return _sampleList.front(); }
const SampleMgr& front() const { return _sampleList.front(); }
unsigned size() const { return _sampleList.size(); }
// Self defined access functions
const std::string& Name() const { return _name; }
const std::string RootName() const { return MakeRootTitle() ; }
const std::string LatexName() const { return MakeLatexName() ; }
SampleMgr& operator[]( const std::string& );
const SampleMgr& operator[]( const std::string& ) const ;
bool HasSample( const std::string& ) const;
void SetFillColor( const Color_t , const double=1.0);
void SetLineColor( const Color_t );
const Parameter ExpectedYield( const double)const;
private:
const std::string _name;
const std::string _latex_name;
std::vector<SampleMgr> _sampleList;
const std::string MakeLatexName() const ;
const std::string MakeRootTitle() const ;
};
class SampleTable
{
public:
SampleTable();
SampleTable( const SampleTable& );
virtual ~SampleTable ();
bool InitFromFile( const std::string& );
//----- Container like access functions ---------------------------------------
typedef std::vector<SampleList>::iterator iterator;
typedef std::vector<SampleList>::const_iterator const_iterator;
typedef std::vector<SampleList>::reverse_iterator riterator;
typedef std::vector<SampleList>::const_reverse_iterator rconst_iterator;
iterator begin() { return _table.begin(); }
iterator end() { return _table.end(); }
riterator rbegin() { return _table.rbegin(); }
riterator rend() { return _table.rbegin(); }
const_iterator begin() const { return _table.begin(); }
const_iterator end() const { return _table.end() ; }
rconst_iterator rbegin() const { return _table.rbegin(); }
rconst_iterator rend() const { return _table.rend(); }
void AddList( const SampleList& x ) { _table.push_back(x); }
SampleList& operator[]( const std::string& );
const SampleList& operator[]( const std::string& ) const;
bool HasList( const std::string& ) const;
void Print() const;
SampleMgr& Sample( const std::string& );
const SampleMgr& Sample( const std::string& ) const;
bool HasSample( const std::string& ) const;
private:
std::vector<SampleList> _table;
};
#endif // __SAMPLELISTING_H__
| 37.917526 | 83 | 0.642197 | [
"vector"
] |
bab8cd3d312921c7a37598f21e4f439975960cd7 | 1,088 | h | C | Volume_10/Number_2/Baerentzen2005/Libsrc/CGLA/Vec3i.h | kyeonghopark/jgt-code | 08bbcc298e12582e32cb56a52e70344c57689d73 | [
"MIT"
] | 415 | 2015-10-24T17:37:12.000Z | 2022-02-18T04:09:07.000Z | Volume_10/Number_2/Baerentzen2005/Libsrc/CGLA/Vec3i.h | kyeonghopark/jgt-code | 08bbcc298e12582e32cb56a52e70344c57689d73 | [
"MIT"
] | 8 | 2016-01-15T13:23:16.000Z | 2021-05-27T01:49:50.000Z | Volume_10/Number_2/Baerentzen2005/Libsrc/CGLA/Vec3i.h | kyeonghopark/jgt-code | 08bbcc298e12582e32cb56a52e70344c57689d73 | [
"MIT"
] | 77 | 2015-10-24T22:36:29.000Z | 2022-03-24T01:03:54.000Z | #ifndef __VEC3I_H
#define __VEC3I_H
#include "ArithVec.h"
namespace CGLA
{
class Vec3f;
class Vec3uc;
class Vec3usi;
/** 3D integer vector. This class does not really extend the template
and hence provides only the basic facilities of an ArithVec.
The class is typically used for indices to 3D voxel grids. */
class Vec3i: public ArithVec<int,Vec3i,3>
{
public:
/// Construct 0 vector.
Vec3i() {}
/// Construct a 3D integer vector.
Vec3i(int _a,int _b,int _c): ArithVec<int,Vec3i,3>(_a,_b,_c) {}
/// Construct a 3D integer vector with 3 identical coordinates.
explicit Vec3i(int a): ArithVec<int,Vec3i,3>(a,a,a) {}
/// Construct from a Vec3f.
explicit Vec3i(const Vec3f& v);
/// Construct from a Vec3uc.
explicit Vec3i(const Vec3uc& v);
/// Construct from a Vec3usi.
explicit Vec3i(const Vec3usi& v);
};
/// Returns cross product of arguments
inline Vec3i cross( const Vec3i& x, const Vec3i& y )
{
return Vec3i( x[1] * y[2] - x[2] * y[1],
x[2] * y[0] - x[0] * y[2],
x[0] * y[1] - x[1] * y[0] );
}
}
#endif
| 22.204082 | 70 | 0.644301 | [
"vector",
"3d"
] |
bac02e9ddda1a8005b446c77af8b8f84a934e084 | 1,902 | h | C | dyros_jet_controller/include/dyros_jet_controller/moveit_controller.h | DaegyuLim/dyros_jet | 969233737fb49b42d7fd9e5ec49694953baf4e7d | [
"BSD-2-Clause"
] | 8 | 2018-02-02T07:35:00.000Z | 2019-12-02T13:06:54.000Z | dyros_jet_controller/include/dyros_jet_controller/moveit_controller.h | DonghyunSung-MS/dyros_jet_avatar | 32d04a2bfd55ad5d95cac09fbaa67799dab68fc8 | [
"BSD-2-Clause"
] | 3 | 2018-02-16T23:27:02.000Z | 2021-07-12T04:15:29.000Z | dyros_jet_controller/include/dyros_jet_controller/moveit_controller.h | DonghyunSung-MS/dyros_jet_avatar | 32d04a2bfd55ad5d95cac09fbaa67799dab68fc8 | [
"BSD-2-Clause"
] | 10 | 2018-02-06T23:34:29.000Z | 2022-03-24T20:50:27.000Z | #ifndef MOVEIT_CONTROLLER_H
#define MOVEIT_CONTROLLER_H
#include <ros/ros.h>
#include <actionlib/server/simple_action_server.h>
#include <control_msgs/FollowJointTrajectoryAction.h>
#include <trajectory_msgs/JointTrajectoryPoint.h>
#include <sensor_msgs/JointState.h>
#include <dyros_jet_msgs/JointState.h>
#include <Eigen/Dense>
#include "dyros_jet_controller/dyros_jet_model.h"
#include "math_type_define.h"
namespace dyros_jet_controller
{
class MoveitController
{
public:
static constexpr unsigned int PRIORITY = 4; ///< Joint priority
MoveitController(DyrosJetModel& model, const VectorQd& current_q, const double& control_time);
void compute();
void setEnable(DyrosJetModel::EndEffector ee, bool enable);
void updateControlMask(unsigned int *mask);
void writeDesired(const unsigned int *mask, VectorQd& desired_q);
private:
bool ee_enabled_[4]; ///< End effector enable
const unsigned int total_dof_;
VectorQd start_q_;
VectorQd desired_q_;
VectorQd target_q_;
const VectorQd& current_q_;
const double ¤t_time_;
double start_time_[DyrosJetModel::HW_TOTAL_DOF];
double end_time_[DyrosJetModel::HW_TOTAL_DOF];
const DyrosJetModel& model_;
int moveit_controller_joint_size = 14;
// For action server
ros::NodeHandle nh_;
std::string action_name_;
actionlib::SimpleActionServer<control_msgs::FollowJointTrajectoryAction> as_;
std::vector<trajectory_msgs::JointTrajectoryPoint> joint_trajectory_;
ros::Time goal_start_time_;
ros::Duration goal_last_time_;
control_msgs::FollowJointTrajectoryFeedback feedback_;
control_msgs::FollowJointTrajectoryResult result_;
control_msgs::FollowJointTrajectoryGoalConstPtr goal_;
void moveitGoalCB();
void moveitPreemptCB();
void moveitExecuteCB();
void waitForClient();
int feedback_header_stamp_;
};
} // namespace dyros_jet_controller
#endif // MOVEIT_CONTROLLER_H
| 25.026316 | 96 | 0.790221 | [
"vector",
"model"
] |
bac92d2401d9aa1dc8f6fd46c04388e95424c05b | 1,193 | h | C | private/windows/oleacc/oleacc/button.h | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | windows/oleacc/oleacc/button.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | windows/oleacc/oleacc/button.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | // Copyright (c) 1996-1999 Microsoft Corporation
// --------------------------------------------------------------------------
//
// BUTTON.H
//
// Button object
//
// --------------------------------------------------------------------------
class CButton : public CClient
{
public:
// IAccessible
STDMETHODIMP get_accName(VARIANT varChild, BSTR* pszName);
STDMETHODIMP get_accRole(VARIANT varChild, VARIANT *pvarRole);
STDMETHODIMP get_accState(VARIANT varChild, VARIANT *pvarState);
STDMETHODIMP get_accDefaultAction(VARIANT varChild, BSTR* pszDefAction);
STDMETHODIMP get_accKeyboardShortcut(VARIANT varChild, BSTR* pszShortcut);
STDMETHODIMP get_accChildCount(long *pcCount);
STDMETHODIMP get_accChild(VARIANT varChild, IDispatch ** ppdispChild);
STDMETHODIMP accNavigate(long dwNavDir, VARIANT varStart, VARIANT * pvarEnd);
STDMETHODIMP accDoDefaultAction(VARIANT varChild);
// IEnumVariant
STDMETHODIMP Next(ULONG celt, VARIANT *rgvar, ULONG* pceltFetched);
STDMETHODIMP Skip(ULONG celt);
//Helpers
void SetupChildren(void);
CButton(HWND, long);
};
| 35.088235 | 84 | 0.60855 | [
"object"
] |
bac97b84139336d8fe8ae7117e855c0c625d295b | 2,125 | h | C | TextGameEngine.h | rwojtek/TextGameEngine | 16a28029b95ed1b41ea8ebcbccdd2be65e4ef334 | [
"MIT"
] | null | null | null | TextGameEngine.h | rwojtek/TextGameEngine | 16a28029b95ed1b41ea8ebcbccdd2be65e4ef334 | [
"MIT"
] | null | null | null | TextGameEngine.h | rwojtek/TextGameEngine | 16a28029b95ed1b41ea8ebcbccdd2be65e4ef334 | [
"MIT"
] | null | null | null | #ifndef TextGameEngine_H_
#include "rapidxml-1.13/rapidxml.hpp"
#include "rapidxml-1.13/rapidxml_print.hpp"
#include<fstream>
#include<vector>
using std::string;
using std::vector;
using std::ifstream;
using std::ofstream;
using namespace rapidxml;
///==================== LINK Struct ==========================
struct Link
{
string linkStepID;
string linkText;
string linkTextBold;
string linkTextItalic;
};
///==================== HEADING Struct =======================
struct Heading
{
string headingText;
string headingSize;
string headingBold;
string headingItalic;
};
struct StepText
{
string text;
string stepTextBold;
string stepTextItalic;
};
///==================== STEP Struct ==========================
struct Step
{
int stepTextAmount;
int headingAmount;
int linkAmount;
string stepID;
vector <Heading> heading;
vector <StepText> stepText;
vector <Link> link;
};
///==================== XML to String ==========================
class XMLtoString
{
ifstream XMLfile;
string stringFromXML;
string line;
public:
XMLtoString();
string getStringFromXML()
{
return stringFromXML;
}
};
///==================== String To Containers ==========================
class StringToContainers
{
xml_document<>doc;
xml_node <> *rootNode;
xml_node <> *pStep;
xml_node <> *pDiff;
xml_node <> *pLink;
int stepsAmount;
vector <Step> step;
public:
StringToContainers();
void fillContainers(string stringForParser);
int getStepsAmount()
{
return stepsAmount;
}
vector <Step> & getStepsTable()
{
return step;
}
};
///==================== Containers To File ==========================
class ContainersToFile
{
ofstream file;
public:
void createEngineFile(int stepsAmount, vector <Step> & step);
void fillMainNavigation(int stepsAmount, vector <Step> & step);
void fillSections(int stepsAmount, vector <Step> & step);
void closeEngineFile()
{
file.close();
}
void combineFiles();
};
#endif // TextGameEngine_H_
| 21.683673 | 71 | 0.582118 | [
"vector"
] |
bace8eccf9c33a50a885b26296ba7d7473ce1dd9 | 4,968 | c | C | kernels/linux-2.4.0/fs/devices.c | liuhaozzu/linux | bdf9758cd23e34b5f53e8e6339d9b29348615e14 | [
"Apache-2.0"
] | 4 | 2020-01-01T20:26:42.000Z | 2021-10-17T21:51:58.000Z | kernels/linux-2.4.0/fs/devices.c | liuhaozzu/linux | bdf9758cd23e34b5f53e8e6339d9b29348615e14 | [
"Apache-2.0"
] | 4 | 2020-07-23T11:20:30.000Z | 2020-07-24T20:09:09.000Z | linux/fs/devices.c | CodeAsm/PS1Linux | 8c3c4d9ffccf446dd061a38186efc924da8a66be | [
"CC0-1.0"
] | null | null | null | /*
* linux/fs/devices.c
*
* (C) 1993 Matthias Urlichs -- collected common code and tables.
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* Added kerneld support: Jacques Gelinas and Bjorn Ekwall
* (changed to kmod)
*/
#include <linux/config.h>
#include <linux/fs.h>
#include <linux/major.h>
#include <linux/string.h>
#include <linux/sched.h>
#include <linux/stat.h>
#include <linux/fcntl.h>
#include <linux/errno.h>
#include <linux/module.h>
#include <linux/smp_lock.h>
#ifdef CONFIG_KMOD
#include <linux/kmod.h>
#include <linux/tty.h>
/* serial module kmod load support */
struct tty_driver *get_tty_driver(kdev_t device);
#define isa_tty_dev(ma) (ma == TTY_MAJOR || ma == TTYAUX_MAJOR)
#define need_serial(ma,mi) (get_tty_driver(MKDEV(ma,mi)) == NULL)
#endif
struct device_struct {
const char * name;
struct file_operations * fops;
};
static rwlock_t chrdevs_lock = RW_LOCK_UNLOCKED;
static struct device_struct chrdevs[MAX_CHRDEV];
extern int get_blkdev_list(char *);
int get_device_list(char * page)
{
int i;
int len;
len = sprintf(page, "Character devices:\n");
read_lock(&chrdevs_lock);
for (i = 0; i < MAX_CHRDEV ; i++) {
if (chrdevs[i].fops) {
len += sprintf(page+len, "%3d %s\n", i, chrdevs[i].name);
}
}
read_unlock(&chrdevs_lock);
len += get_blkdev_list(page+len);
return len;
}
/*
Return the function table of a device.
Load the driver if needed.
Increment the reference count of module in question.
*/
static struct file_operations * get_chrfops(unsigned int major, unsigned int minor)
{
struct file_operations *ret = NULL;
if (!major || major >= MAX_CHRDEV)
return NULL;
read_lock(&chrdevs_lock);
ret = fops_get(chrdevs[major].fops);
read_unlock(&chrdevs_lock);
#ifdef CONFIG_KMOD
if (ret && isa_tty_dev(major)) {
lock_kernel();
if (need_serial(major,minor)) {
/* Force request_module anyway, but what for? */
fops_put(ret);
ret = NULL;
}
unlock_kernel();
}
if (!ret) {
char name[20];
sprintf(name, "char-major-%d", major);
request_module(name);
read_lock(&chrdevs_lock);
ret = fops_get(chrdevs[major].fops);
read_unlock(&chrdevs_lock);
}
#endif
return ret;
}
int register_chrdev(unsigned int major, const char * name, struct file_operations *fops)
{
if (major == 0) {
write_lock(&chrdevs_lock);
for (major = MAX_CHRDEV-1; major > 0; major--) {
if (chrdevs[major].fops == NULL) {
chrdevs[major].name = name;
chrdevs[major].fops = fops;
write_unlock(&chrdevs_lock);
return major;
}
}
write_unlock(&chrdevs_lock);
return -EBUSY;
}
if (major >= MAX_CHRDEV)
return -EINVAL;
write_lock(&chrdevs_lock);
if (chrdevs[major].fops && chrdevs[major].fops != fops) {
write_unlock(&chrdevs_lock);
return -EBUSY;
}
chrdevs[major].name = name;
chrdevs[major].fops = fops;
write_unlock(&chrdevs_lock);
return 0;
}
int unregister_chrdev(unsigned int major, const char * name)
{
if (major >= MAX_CHRDEV)
return -EINVAL;
write_lock(&chrdevs_lock);
if (!chrdevs[major].fops || strcmp(chrdevs[major].name, name)) {
write_unlock(&chrdevs_lock);
return -EINVAL;
}
chrdevs[major].name = NULL;
chrdevs[major].fops = NULL;
write_unlock(&chrdevs_lock);
return 0;
}
/*
* Called every time a character special file is opened
*/
int chrdev_open(struct inode * inode, struct file * filp)
{
int ret = -ENODEV;
filp->f_op = get_chrfops(MAJOR(inode->i_rdev), MINOR(inode->i_rdev));
if (filp->f_op) {
ret = 0;
if (filp->f_op->open != NULL) {
lock_kernel();
ret = filp->f_op->open(inode,filp);
unlock_kernel();
}
}
return ret;
}
/*
* Dummy default file-operations: the only thing this does
* is contain the open that then fills in the correct operations
* depending on the special file...
*/
static struct file_operations def_chr_fops = {
open: chrdev_open,
};
/*
* Print device name (in decimal, hexadecimal or symbolic)
* Note: returns pointer to static data!
*/
const char * kdevname(kdev_t dev)
{
static char buffer[32];
sprintf(buffer, "%02x:%02x", MAJOR(dev), MINOR(dev));
return buffer;
}
const char * cdevname(kdev_t dev)
{
static char buffer[32];
const char * name = chrdevs[MAJOR(dev)].name;
if (!name)
name = "unknown-char";
sprintf(buffer, "%s(%d,%d)", name, MAJOR(dev), MINOR(dev));
return buffer;
}
static int sock_no_open(struct inode *irrelevant, struct file *dontcare)
{
return -ENXIO;
}
static struct file_operations bad_sock_fops = {
open: sock_no_open
};
void init_special_inode(struct inode *inode, umode_t mode, int rdev)
{
inode->i_mode = mode;
if (S_ISCHR(mode)) {
inode->i_fop = &def_chr_fops;
inode->i_rdev = to_kdev_t(rdev);
} else if (S_ISBLK(mode)) {
inode->i_fop = &def_blk_fops;
inode->i_rdev = to_kdev_t(rdev);
inode->i_bdev = bdget(rdev);
} else if (S_ISFIFO(mode))
inode->i_fop = &def_fifo_fops;
else if (S_ISSOCK(mode))
inode->i_fop = &bad_sock_fops;
else
printk(KERN_DEBUG "init_special_inode: bogus imode (%o)\n", mode);
}
| 22.894009 | 88 | 0.688607 | [
"3d"
] |
bacf39bc61149a97a8f50341409d9ef5dfe89fcc | 1,246 | h | C | j2objc/include/javax/xml/transform/Source.h | benf1977/j2objc-serialization-example | bc356a2fa4a1f4da680a0f6cfe33985220be74f3 | [
"MIT"
] | null | null | null | j2objc/include/javax/xml/transform/Source.h | benf1977/j2objc-serialization-example | bc356a2fa4a1f4da680a0f6cfe33985220be74f3 | [
"MIT"
] | null | null | null | j2objc/include/javax/xml/transform/Source.h | benf1977/j2objc-serialization-example | bc356a2fa4a1f4da680a0f6cfe33985220be74f3 | [
"MIT"
] | null | null | null | //
// Generated by the J2ObjC translator. DO NOT EDIT!
// source: android/libcore/luni/src/main/java/javax/xml/transform/Source.java
//
#ifndef _JavaxXmlTransformSource_H_
#define _JavaxXmlTransformSource_H_
#include "J2ObjC_header.h"
/*!
@brief An object that implements this interface contains the information
needed to act as source input (XML source or transformation instructions).
*/
@protocol JavaxXmlTransformSource < NSObject, JavaObject >
/*!
@brief Set the system identifier for this Source.
<p>The system identifier is optional if the source does not
get its data from a URL, but it may still be useful to provide one.
The application can use a system identifier, for example, to resolve
relative URIs and to include in error messages and warnings.</p>
@param systemId The system identifier as a URL string.
*/
- (void)setSystemIdWithNSString:(NSString *)systemId;
/*!
@brief Get the system identifier that was set with setSystemId.
@return The system identifier that was set with setSystemId, or null
if setSystemId was not called.
*/
- (NSString *)getSystemId;
@end
J2OBJC_EMPTY_STATIC_INIT(JavaxXmlTransformSource)
J2OBJC_TYPE_LITERAL_HEADER(JavaxXmlTransformSource)
#endif // _JavaxXmlTransformSource_H_
| 30.390244 | 78 | 0.783307 | [
"object",
"transform"
] |
bae60dfa92bdbacbe8274edabea966b4eb701f92 | 44,238 | c | C | XFree86-3.3/xc/programs/Xserver/hw/xfree86/accel/mach64/mach64blt.c | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 46 | 2015-12-04T17:12:58.000Z | 2022-03-11T04:30:49.000Z | XFree86-3.3/xc/programs/Xserver/hw/xfree86/accel/mach64/mach64blt.c | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | null | null | null | XFree86-3.3/xc/programs/Xserver/hw/xfree86/accel/mach64/mach64blt.c | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 23 | 2016-10-24T09:18:14.000Z | 2022-02-25T02:11:35.000Z | /* $XFree86: xc/programs/Xserver/hw/xfree86/accel/mach64/mach64blt.c,v 3.8 1996/12/23 06:39:09 dawes Exp $ */
/*
* Copyright 1989 by the Massachusetts Institute of Technology
* Copyright 1993,1994,1995,1996 by Kevin E. Martin, Chapel Hill, North Carolina.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose and without fee is hereby granted,
* provided that the above copyright notice appear in all copies and that
* both that copyright notice and this permission notice appear in
* supporting documentation, and that the name of M.I.T. not be used in
* advertising or publicity pertaining to distribution of the software
* without specific, written prior permission. M.I.T. makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*
* Author: Keith Packard
*
* Modified for the 8514/A by Kevin E. Martin (martin@cs.unc.edu)
*
* KEVIN E. MARTIN AND RICKARD E. FAITH DISCLAIM ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS, IN NO EVENT SHALL KEVIN E. MARTIN BE LIABLE FOR ANY SPECIAL,
* INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
* LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
* OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*
* Modified for the Mach-8 by Rickard E. Faith (faith@cs.unc.edu)
* Modified for the Mach32 by Kevin E. Martin (martin@cs.unc.edu)
* Modified for the Mach64 by Kevin E. Martin (martin@cs.unc.edu)
*
*/
/* $XConsortium: mach64blt.c /main/7 1996/10/19 17:53:30 kaleb $ */
#include "X.h"
#include "Xmd.h"
#include "Xproto.h"
#include "gcstruct.h"
#include "windowstr.h"
#include "scrnintstr.h"
#include "pixmapstr.h"
#include "regionstr.h"
#include "cfb.h"
#include "cfb16.h"
#include "cfb32.h"
#include "cfbmskbits.h"
#include "cfb8bit.h"
#include "fastblt.h"
#include "mach64.h"
#include "mi.h"
static RegionPtr mach64BitBlt();
static void mach64FindOrdering();
static void mach64CopyPlane1toN();
static void mach64CopyPlaneNto1();
static void cfbCopyPlane32to1();
static void cfbCopyPlane16to1();
static void cfbCopyPlane1to32();
static void cfbCopyPlane1to16();
RegionPtr
mach64CopyArea(pSrcDrawable, pDstDrawable,
pGC, srcx, srcy, width, height, dstx, dsty)
register DrawablePtr pSrcDrawable;
register DrawablePtr pDstDrawable;
GC *pGC;
int srcx, srcy;
int width, height;
int dstx, dsty;
{
RegionPtr pRgnExposed;
if (!xf86VTSema || (pSrcDrawable->type != DRAWABLE_WINDOW &&
pDstDrawable->type != DRAWABLE_WINDOW))
{
switch (max(pSrcDrawable->bitsPerPixel, pDstDrawable->bitsPerPixel))
{
case 8:
return cfbCopyArea(pSrcDrawable, pDstDrawable, pGC,
srcx, srcy, width, height, dstx, dsty);
case 16:
return cfb16CopyArea(pSrcDrawable, pDstDrawable, pGC,
srcx, srcy, width, height, dstx, dsty);
case 32:
return cfb32CopyArea(pSrcDrawable, pDstDrawable, pGC,
srcx, srcy, width, height, dstx, dsty);
default:
ErrorF("mach64CopyArea: unsupported depth %d \n",
max(pSrcDrawable->bitsPerPixel,
pDstDrawable->bitsPerPixel));
return;
}
}
else
{
pRgnExposed = mach64BitBlt (pSrcDrawable, pDstDrawable, pGC,
srcx, srcy, width, height, dstx, dsty,
mach64DoBitBlt, 0);
return pRgnExposed;
}
}
RegionPtr
mach64CopyPlane(pSrcDrawable, pDstDrawable,
pGC, srcx, srcy, width, height, dstx, dsty, bitPlane)
DrawablePtr pSrcDrawable;
DrawablePtr pDstDrawable;
GCPtr pGC;
int srcx, srcy;
int width, height;
int dstx, dsty;
unsigned long bitPlane;
{
RegionPtr ret;
/* xf86VTSema is handled in mach64CopyPlane1toN and mach64CopyPlaneNto1 */
if (pSrcDrawable->bitsPerPixel == 1) /* 1 to N copy */
{
if (bitPlane == 1)
{
ret = mach64BitBlt (pSrcDrawable, pDstDrawable,
pGC, srcx, srcy, width, height,
dstx, dsty, (void *)mach64CopyPlane1toN,
bitPlane);
}
else
{
ret = miHandleExposures(pSrcDrawable, pDstDrawable,
pGC, srcx, srcy, width, height,
dstx, dsty, bitPlane);
}
}
else if (pDstDrawable->bitsPerPixel == 1) /* N to 1 copy */
{
extern int InverseAlu[16];
int oldalu = pGC->alu;
if ((pGC->fgPixel & 1) == 0 && (pGC->bgPixel & 1) == 1)
{
pGC->alu = InverseAlu[pGC->alu];
}
else if ((pGC->fgPixel & 1) == (pGC->bgPixel & 1))
{
pGC->alu = mfbReduceRop(pGC->alu, pGC->fgPixel);
}
ret = mach64BitBlt (pSrcDrawable, pDstDrawable,
pGC, srcx, srcy, width, height, dstx, dsty,
mach64CopyPlaneNto1, bitPlane);
pGC->alu = oldalu;
}
else /* N to N copy */
{
PixmapPtr pBitmap;
ScreenPtr pScreen = pSrcDrawable->pScreen;
GCPtr pGC1;
pBitmap = (*pScreen->CreatePixmap) (pScreen, width, height, 1);
if (!pBitmap)
return NULL;
pGC1 = GetScratchGC (1, pScreen);
if (!pGC1)
{
(*pScreen->DestroyPixmap) (pBitmap);
return NULL;
}
/*
* don't need to set pGC->fgPixel,bgPixel as copyPlane8to1
* ignores pixel values, expecting the rop to "do the
* right thing", which GXcopy will.
*/
ValidateGC ((DrawablePtr) pBitmap, pGC1);
/* no exposures here, scratch GC's don't get graphics expose */
(void) mach64BitBlt (pSrcDrawable, (DrawablePtr) pBitmap,
pGC1, srcx, srcy, width, height, 0, 0,
mach64CopyPlaneNto1, bitPlane);
/* no exposures here, copy bits from inside a pixmap */
(void) mach64BitBlt ((DrawablePtr) pBitmap, pDstDrawable, pGC,
0, 0, width, height, dstx, dsty,
mach64CopyPlane1toN, 1);
FreeScratchGC (pGC1);
(*pScreen->DestroyPixmap) (pBitmap);
/* compute resultant exposures */
ret = miHandleExposures (pSrcDrawable, pDstDrawable, pGC,
srcx, srcy, width, height,
dstx, dsty, bitPlane);
}
return (ret);
}
void
mach64GetImage(pDrawable, sx, sy, w, h, format, planeMask, pdstLine)
DrawablePtr pDrawable;
int sx, sy, w, h;
unsigned int format;
unsigned long planeMask;
char *pdstLine;
{
BoxRec box;
DDXPointRec ptSrc;
RegionRec rgnDst;
ScreenPtr pScreen;
PixmapPtr pPixmap;
GC dummyGC;
if ((w == 0) || (h == 0))
return;
if ((format == ZPixmap) && (pDrawable->type == DRAWABLE_WINDOW))
{
pScreen = pDrawable->pScreen;
pPixmap = GetScratchPixmapHeader(pScreen, w, h,
pDrawable->depth, pDrawable->bitsPerPixel,
PixmapBytePad(w,pDrawable->depth), (pointer)pdstLine);
if (!pPixmap)
return;
if ((planeMask & 0xffffffff) != 0xffffffff)
bzero((char *)pdstLine, pPixmap->devKind * h);
dummyGC.subWindowMode = ~IncludeInferiors;
dummyGC.alu = GXcopy;
dummyGC.planemask = planeMask;
ptSrc.x = sx + pDrawable->x;
ptSrc.y = sy + pDrawable->y;
box.x1 = 0;
box.y1 = 0;
box.x2 = w;
box.y2 = h;
REGION_INIT(pScreen, &rgnDst, &box, 1);
mach64DoBitBlt(pDrawable, (DrawablePtr)pPixmap, &dummyGC, &rgnDst,
&ptSrc, planeMask);
REGION_UNINIT(pScreen, &rgnDst);
FreeScratchPixmapHeader(pPixmap);
}
else
{
switch (pDrawable->bitsPerPixel)
{
case 1:
mfbGetImage (pDrawable, sx, sy, w, h, format, planeMask,
pdstLine);
break;
case 8:
cfbGetImage (pDrawable, sx, sy, w, h, format, planeMask,
pdstLine);
break;
case 16:
cfb16GetImage (pDrawable, sx, sy, w, h, format, planeMask,
pdstLine);
break;
case 32:
cfb32GetImage (pDrawable, sx, sy, w, h, format, planeMask,
pdstLine);
break;
default:
ErrorF("mach64GetImage: unsupported depth %d \n",
pDrawable->bitsPerPixel);
}
}
}
static RegionPtr
mach64BitBlt (pSrc, pDst, pGC, srcX, srcY, copyWidth, copyHeight,
dstX, dstY, doBitBlt, bitPlane)
DrawablePtr pSrc; /* Pointer to source drawable */
DrawablePtr pDst; /* Pointer to destination drawable */
GCPtr pGC; /* Pointer to current GC */
int srcX; /* Upper left coord of source */
int srcY; /* Upper left coord of source */
int copyWidth; /* Width of area to copy */
int copyHeight; /* Height of area to copy */
int dstX; /* Upper left coord of destination */
int dstY; /* Upper left coord of destination */
void (*doBitBlt)(); /* Ptr to function to do the copy */
unsigned long bitPlane; /* Plane number to copy */
{
RegionPtr pRgnSrcClip; /* may be a new region, or just a copy */
RegionPtr pRgnDstClip; /* may be a new region, or just a copy */
Bool freeSrcClip; /* flag stating if you can free pRgnSrcClip */
RegionPtr pRgnExposed; /* region exposed */
RegionRec clippedDstRgn;/* destination region after clipping */
DDXPointRec clippedSrcPt; /* source point after clipping */
register BoxPtr pClipRect; /* list of clip rectangles */
register int nClipRects; /* number of clip rectangles */
register int dx, dy; /* difference in x and y directions */
register int srcX1, srcY1; /* top left corner of source region */
register int srcX2, srcY2; /* bottom right corner of source region */
register int clipXMin; /* min X value */
register int clipXMax; /* max X value */
register int clipYMin; /* min Y value */
register int clipYMax; /* max Y value */
cfbPrivGCPtr pGCPriv; /* pointer to GC's dev private struct */
Bool fastClip; /* for fast clipping with pixmap source */
Bool fastExpose; /* for fast exposures with pixmap source */
freeSrcClip = FALSE;
fastClip = FALSE;
fastExpose = FALSE;
pGCPriv = (cfbPrivGCPtr)(pGC->devPrivates[cfbGCPrivateIndex].ptr);
pRgnDstClip = pGCPriv->pCompositeClip;
if (pDst->type == DRAWABLE_WINDOW)
{
if (!((WindowPtr)pDst)->realized)
{
return NULL;
}
}
/* clip the source */
if (pSrc->type == DRAWABLE_WINDOW)
{
if (pGC->subWindowMode == IncludeInferiors)
{
if (!((WindowPtr)pSrc)->parent)
{
/*
* Special case bitblt from root window in IncludeInferiors
* mode; just like from a pixmap
*/
pRgnSrcClip = NULL;
fastClip = TRUE;
clipXMin = pSrc->x;
clipYMin = pSrc->y;
clipXMax = pSrc->x + pSrc->width;
clipYMax = pSrc->y + pSrc->height;
}
else if ((pSrc == pDst) && (pGC->clientClipType == CT_NONE))
{
pRgnSrcClip = pGCPriv->pCompositeClip;
}
else
{
pRgnSrcClip = NotClippedByChildren((WindowPtr)pSrc);
freeSrcClip = TRUE;
}
}
else
{
pRgnSrcClip = &((WindowPtr)pSrc)->clipList;
}
}
else /* DRAWABLE_PIXMAP */
{
if ((pSrc == pDst) && (pGC->clientClipType == CT_NONE))
{
pRgnSrcClip = pGCPriv->pCompositeClip;
}
else
{
/*
* Pixmap is just one clipping rect so we can avoid allocating a
* full blown region.
*/
pRgnSrcClip = NULL;
fastClip = TRUE;
clipXMin = pSrc->x;
clipYMin = pSrc->y;
clipXMax = pSrc->x + pSrc->width;
clipYMax = pSrc->y + pSrc->height;
}
}
if ((pRgnSrcClip) && (REGION_NUM_RECTS(pRgnSrcClip) == 1))
{
/*
* Optimize if there is only one source clip rect.
*/
fastClip = TRUE;
pClipRect = REGION_RECTS(pRgnSrcClip);
clipXMin = pClipRect->x1;
clipYMin = pClipRect->y1;
clipXMax = pClipRect->x2;
clipYMax = pClipRect->y2;
}
srcX1 = srcX + pSrc->x;
srcY1 = srcY + pSrc->y;
srcX2 = srcX1 + copyWidth;
srcY2 = srcY1 + copyHeight;
dx = srcX1 - (dstX + pDst->x);
dy = srcY1 - (dstY + pDst->y);
if (fastClip)
{
/*
* Don't create a source region if we are doing a fast clip.
* Clip the source; if regions extend beyond the source size,
* make sure exposure events get sent.
*/
fastExpose = TRUE;
if (srcX1 < clipXMin)
{
srcX1 = clipXMin;
fastExpose = FALSE;
}
if (srcY1 < clipYMin)
{
srcY1 = clipYMin;
fastExpose = FALSE;
}
if (srcX2 > clipXMax)
{
srcX2 = clipXMax;
fastExpose = FALSE;
}
if (srcY2 > clipYMax)
{
srcY2 = clipYMax;
fastExpose = FALSE;
}
/*
* Translate and clip the dst to the destination composite clip
*/
srcX1 -= dx;
srcX2 -= dx;
srcY1 -= dy;
srcY2 -= dy;
/*
* If the destination composite clip is one rectangle we can
* do the clip directly. Otherwise we have to create a full
* blown region and call intersect.
*/
nClipRects = REGION_NUM_RECTS(pRgnDstClip);
if (nClipRects == 1)
{
pClipRect = REGION_RECTS(pRgnDstClip);
clippedDstRgn.extents.x1 = max(srcX1, pClipRect->x1);
clippedDstRgn.extents.y1 = max(srcY1, pClipRect->y1);
clippedDstRgn.extents.x2 = min(srcX2, pClipRect->x2);
clippedDstRgn.extents.y2 = min(srcY2, pClipRect->y2);
clippedDstRgn.data = (RegDataPtr)NULL;
clippedSrcPt.x = clippedDstRgn.extents.x1 + dx;
clippedSrcPt.y = clippedDstRgn.extents.y1 + dy;
if ((clippedDstRgn.extents.y2 > clippedDstRgn.extents.y1) &&
(clippedDstRgn.extents.x2 > clippedDstRgn.extents.x1))
{
(*doBitBlt)(pSrc, pDst, pGC, &clippedDstRgn, &clippedSrcPt,
bitPlane);
}
}
else
{
/*
* We must turn off fastClip now, since we must create
* a full blown region. It is intersected with the
* composite clip below.
*/
fastClip = FALSE;
clippedDstRgn.extents.x1 = srcX1;
clippedDstRgn.extents.y1 = srcY1;
clippedDstRgn.extents.x2 = srcX2;
clippedDstRgn.extents.y2 = srcY2;
clippedDstRgn.data = (RegDataPtr)NULL;
(*pGC->pScreen->Intersect)(&clippedDstRgn, &clippedDstRgn,
pRgnDstClip);
}
} /* end section that set up a dest region with fastClip turned on */
else
{
clippedDstRgn.extents.x1 = srcX1;
clippedDstRgn.extents.y1 = srcY1;
clippedDstRgn.extents.x2 = srcX2;
clippedDstRgn.extents.y2 = srcY2;
clippedDstRgn.data = (RegDataPtr)NULL;
(*pGC->pScreen->Intersect)(&clippedDstRgn, &clippedDstRgn,
pRgnSrcClip);
(*pGC->pScreen->TranslateRegion)(&clippedDstRgn, -dx, -dy);
(*pGC->pScreen->Intersect)(&clippedDstRgn, &clippedDstRgn,
pRgnDstClip);
} /* end section that set up a dest region with fastClip turned off */
if (!fastClip)
{
/*
* Do bit blitting if fastClip is not set.
*/
nClipRects = REGION_NUM_RECTS(&clippedDstRgn);
if (nClipRects)
{
register int i; /* counter */
DDXPointPtr pClippedSrcPt;/* source point after clipping */
register DDXPointPtr pPt; /* used to traverse
pClippedSrcPt */
pClippedSrcPt =(DDXPointPtr)ALLOCATE_LOCAL(nClipRects *
sizeof(DDXPointRec));
if(!(pClippedSrcPt))
{
(*pGC->pScreen->RegionUninit)(&clippedDstRgn);
if (freeSrcClip)
{
(*pGC->pScreen->RegionDestroy)(pRgnSrcClip);
}
return NULL;
}
pClipRect = REGION_RECTS(&clippedDstRgn);
pPt = pClippedSrcPt;
for (i = nClipRects; i > 0; i--)
{
pPt->x = pClipRect->x1 + dx;
pPt->y = pClipRect->y1 + dy;
pClipRect++;
pPt++;
}
(*doBitBlt)(pSrc, pDst, pGC, &clippedDstRgn, pClippedSrcPt,
bitPlane);
DEALLOCATE_LOCAL(pClippedSrcPt);
}
(*pGC->pScreen->RegionUninit)(&clippedDstRgn);
}
pRgnExposed = NULL;
if ((!fastExpose) && (pGCPriv->fExpose))
{
/*
* Pixmap sources generate a NoExposed. (we return NULL to do this)
*/
pRgnExposed = miHandleExposures(pSrc, pDst, pGC, srcX, srcY,
copyWidth, copyHeight,
dstX, dstY, (unsigned long)0);
}
if (freeSrcClip)
{
(*pGC->pScreen->RegionDestroy)(pRgnSrcClip);
}
return pRgnExposed;
}
static void
mach64FindOrdering(pSrcDrawable, pDstDrawable, pGC, numRects, boxes,
srcx, srcy, dstx, dsty, ordering)
DrawablePtr pSrcDrawable;
DrawablePtr pDstDrawable;
GC *pGC;
int numRects;
BoxPtr boxes;
int srcx;
int srcy;
int dstx;
int dsty;
unsigned int *ordering;
{
int i, j, y;
int xMax, yMin, yMax;
/* If not the same drawable then order of move doesn't matter.
* Following assumes that boxes are sorted from top
* to bottom and left to right.
*/
if ((pSrcDrawable != pDstDrawable) &&
((pGC->subWindowMode != IncludeInferiors) ||
(pSrcDrawable->type == DRAWABLE_PIXMAP) ||
(pDstDrawable->type == DRAWABLE_PIXMAP))) {
for (i=0; i < numRects; i++)
ordering[i] = i;
} else { /* within same drawable, must sequence moves carefully! */
if (dsty <= srcy) {
/* Scroll up or stationary vertical. Vertical order OK */
if (dstx <= srcx) {
/* Scroll left or stationary horizontal. Horizontal order OK */
for (i=0; i < numRects; i++)
ordering[i] = i;
} else {
/* scroll right. must reverse horizontal banding of rects. */
for (i=0, j=1, xMax=0; i < numRects; j=i+1, xMax=i) {
/* find extent of current horizontal band */
y=boxes[i].y1; /* band has this y coordinate */
while ((j < numRects) && (boxes[j].y1 == y))
j++;
/* reverse the horizontal band in the output ordering */
for (j-- ; j >= xMax; j--, i++)
ordering[i] = j;
}
}
} else { /* Scroll down. Must reverse vertical banding. */
if (dstx < srcx) { /* Scroll left. Horizontal order OK. */
for (i=numRects-1, j=i-1, yMin=i, yMax=0; i >= 0; j=i-1, yMin=i) {
/* find extent of current horizontal band */
y=boxes[i].y1; /* band has this y coordinate */
while ((j >= 0) && (boxes[j].y1 == y))
j--;
/* reverse the horizontal band in the output ordering */
for (j++ ; j <= yMin; j++, i--, yMax++)
ordering[yMax] = j;
}
} else { /* Scroll right or horizontal stationary.
Reverse horizontal order as well (if stationary,
horizontal order can be swapped without penalty and
this is faster to compute). */
for (i=0, j=numRects-1; i < numRects; i++, j--)
ordering[i] = j;
}
}
}
}
void
mach64DoBitBlt (pSrc, pDst, pGC, rgnDst, pptSrc, bitPlane)
DrawablePtr pSrc; /* Pointer to source drawable */
DrawablePtr pDst; /* Pointer to destination drawable */
GCPtr pGC; /* Pointer to current GC */
RegionPtr rgnDst; /* Destination region */
DDXPointPtr pptSrc; /* Source region */
unsigned long bitPlane; /* Not used by this function but part of
function vector parameter list */
{
int numRects; /* number of clip rectangles */
BoxPtr pbox; /* list of clip rectangles */
pbox = REGION_RECTS(rgnDst);
numRects = REGION_NUM_RECTS(rgnDst);
/*
* Copy from window to window.
*/
if ((pSrc->type == DRAWABLE_WINDOW) && (pDst->type == DRAWABLE_WINDOW))
{
unsigned int *ordering;
register BoxPtr prect;
register int i;
register int dx, dy;
int direction = 0;
dx = pptSrc->x - pbox->x1;
dy = pptSrc->y - pbox->y1;
ordering = (unsigned int *)
ALLOCATE_LOCAL(numRects * sizeof(unsigned int));
if(!ordering)
return;
mach64FindOrdering(pSrc, pDst, pGC, numRects, pbox,
pptSrc->x, pptSrc->y,
pbox->x1, pbox->y1, ordering);
if (dx > 0) direction |= INC_X;
if (dy > 0) direction |= INC_Y;
WaitQueue(4);
regw(DP_MIX, (mach64alu[pGC->alu] << 16) | mach64alu[pGC->alu]);
regw(DP_WRITE_MASK, pGC->planemask);
regw(DP_SRC, FRGD_SRC_BLIT);
regw(SRC_CNTL, 0x00000000);
if (direction == (INC_X | INC_Y)) {
for (i = 0; i < numRects; i++) {
prect = &pbox[ordering[i]];
MACH64_BIT_BLT((prect->x1 + dx), (prect->y1 + dy),
prect->x1, prect->y1,
(prect->x2 - prect->x1),
(prect->y2 - prect->y1),
(DST_X_LEFT_TO_RIGHT | DST_Y_TOP_TO_BOTTOM));
}
} else if (direction == INC_X) {
for (i = 0; i < numRects; i++) {
prect = &pbox[ordering[i]];
MACH64_BIT_BLT((prect->x1 + dx), (prect->y2 + dy - 1),
prect->x1, (prect->y2 - 1),
(prect->x2 - prect->x1),
(prect->y2 - prect->y1),
(DST_X_LEFT_TO_RIGHT | DST_Y_BOTTOM_TO_TOP));
}
} else if (direction == INC_Y) {
for (i = 0; i < numRects; i++) {
prect = &pbox[ordering[i]];
MACH64_BIT_BLT((prect->x2 + dx - 1), (prect->y1 + dy),
(prect->x2 - 1), prect->y1,
(prect->x2 - prect->x1),
(prect->y2 - prect->y1),
(DST_X_RIGHT_TO_LEFT | DST_Y_TOP_TO_BOTTOM));
}
} else {
for (i = 0; i < numRects; i++) {
prect = &pbox[ordering[i]];
MACH64_BIT_BLT((prect->x2 + dx - 1), (prect->y2 + dy - 1),
(prect->x2 - 1), (prect->y2 - 1),
(prect->x2 - prect->x1),
(prect->y2 - prect->y1),
(DST_X_RIGHT_TO_LEFT | DST_Y_BOTTOM_TO_TOP));
}
}
WaitIdleEmpty(); /* Make sure that all commands have finished */
/*
* Make sure that the destination trajectory is correctly set
* for subsequent calls. MACH64_BIT_BLT is the only function that
* currently changes the destination trajectory from L->R and T->B.
*/
regw(DST_CNTL, (DST_X_LEFT_TO_RIGHT | DST_Y_TOP_TO_BOTTOM));
}
/*
* Copy from an pixmap to a window.
*/
else if ((pSrc->type != DRAWABLE_WINDOW) && (pDst->type == DRAWABLE_WINDOW))
{
char *psrc = ((PixmapPtr)pSrc)->devPrivate.ptr;
int pixWidth = PixmapBytePad(pSrc->width, pSrc->depth);
while(numRects --)
{
{
(mach64ImageWriteFunc)(pbox->x1, pbox->y1,
pbox->x2 - pbox->x1,
pbox->y2 - pbox->y1,
psrc, pixWidth, pptSrc->x, pptSrc->y,
mach64alu[pGC->alu], pGC->planemask);
pbox++;
pptSrc++;
}
}
}
/*
* Copy from a window to a pixmap.
*/
else if ((pSrc->type == DRAWABLE_WINDOW) && (pDst->type != DRAWABLE_WINDOW))
{
if ((pGC->planemask & 0xffffffff) == 0xffffffff)
{
int pixWidth = PixmapBytePad(pDst->width, pDst->depth);
char *pdst = ((PixmapPtr)pDst)->devPrivate.ptr;
while(numRects --)
{
(mach64ImageReadFunc)(pptSrc->x, pptSrc->y,
pbox->x2 - pbox->x1,
pbox->y2 - pbox->y1,
pdst, pixWidth,
pbox->x1, pbox->y1,
pGC->planemask);
pbox++;
pptSrc++;
}
}
else
{
switch (max(pSrc->bitsPerPixel, pDst->bitsPerPixel))
{
case 8:
cfbDoBitblt (pSrc, pDst, pGC->alu,
rgnDst, pptSrc, pGC->planemask);
break;
case 16:
cfb16DoBitblt (pSrc, pDst, pGC->alu,
rgnDst, pptSrc, pGC->planemask);
break;
case 32:
cfb32DoBitblt (pSrc, pDst, pGC->alu,
rgnDst, pptSrc, pGC->planemask);
break;
default:
ErrorF("mach64DoBitBlt: unsupported depth %d \n",
max(pSrc->bitsPerPixel, pDst->bitsPerPixel));
}
}
}
else
{
ErrorF("mach64DoBitBlt: pixmap to pixmap copy not supported\n");
}
return;
}
static void
mach64CopyPlane1toN(pSrcDrawable, pDstDrawable, pGC, rgnDst, pptSrc, bitPlane)
DrawablePtr pSrcDrawable;
DrawablePtr pDstDrawable;
GCPtr pGC;
RegionPtr rgnDst;
DDXPointPtr pptSrc;
unsigned long bitPlane;
{
BoxPtr pbox;
int pixWidth, i, numRects;
char *psrc;
if ((pSrcDrawable->type != DRAWABLE_WINDOW) &&
(pDstDrawable->type == DRAWABLE_WINDOW) && xf86VTSema)
{
pixWidth = PixmapBytePad(pSrcDrawable->width, pSrcDrawable->depth);
psrc = ((PixmapPtr)pSrcDrawable)->devPrivate.ptr;
pbox = REGION_RECTS(rgnDst);
numRects = REGION_NUM_RECTS(rgnDst);
for (i = numRects; --i >= 0; pbox++, pptSrc++)
{
mach64ImageStippleFunc(pbox->x1, pbox->y1,
pbox->x2 - pbox->x1,
pbox->y2 - pbox->y1,
psrc, pixWidth,
pptSrc->x, pptSrc->y,
pGC->fgPixel, pGC->bgPixel,
mach64alu[pGC->alu], pGC->planemask, 1);
}
}
else
{
switch (pDstDrawable->bitsPerPixel)
{
case 8:
cfb8CheckOpaqueStipple (pGC->alu, pGC->fgPixel, pGC->bgPixel,
pGC->planemask);
cfbCopyPlane1to8(pSrcDrawable, pDstDrawable, pGC->alu,
rgnDst, pptSrc, pGC->planemask, bitPlane);
break;
case 16:
cfbCopyPlane1to16(pSrcDrawable, pDstDrawable, pGC->alu,
rgnDst, pptSrc, pGC->planemask, bitPlane,
pGC);
break;
case 32:
cfbCopyPlane1to32(pSrcDrawable, pDstDrawable, pGC->alu,
rgnDst, pptSrc, pGC->planemask, bitPlane,
pGC);
break;
default:
ErrorF("mach64CopyPlane1toN: unsupported function \n");
break;
}
}
}
static void
mach64CopyPlaneNto1(pSrcDrawable, pDstDrawable, pGC, rgnDst, pptSrc, bitPlane)
DrawablePtr pSrcDrawable;
DrawablePtr pDstDrawable;
GCPtr pGC;
RegionPtr rgnDst;
DDXPointPtr pptSrc;
unsigned long bitPlane;
{
BoxPtr pbox;
int pixWidth, i, numRects;
unsigned char *psrc;
if (!(pGC->planemask & bitPlane))
return;
switch (pSrcDrawable->bitsPerPixel)
{
case 8:
cfbCopyPlane8to1(pSrcDrawable, pDstDrawable, pGC->alu,
rgnDst, pptSrc, pGC->planemask, bitPlane);
break;
case 16:
cfbCopyPlane16to1(pSrcDrawable, pDstDrawable, pGC->alu,
rgnDst, pptSrc, pGC->planemask, bitPlane);
break;
case 32:
cfbCopyPlane32to1(pSrcDrawable, pDstDrawable, pGC->alu,
rgnDst, pptSrc, pGC->planemask, bitPlane);
break;
default:
ErrorF("mach64CopyPlaneNto1: unsupported function \n");
break;
}
}
/******************************************************************/
#define mfbmaskbits(x, w, startmask, endmask, nlw) \
startmask = starttab[(x)&0x1f]; \
endmask = endtab[((x)+(w)) & 0x1f]; \
if (startmask) \
nlw = (((w) - (32 - ((x)&0x1f))) >> 5); \
else \
nlw = (w) >> 5;
#define mfbmaskpartialbits(x, w, mask) \
mask = partmasks[(x)&0x1f][(w)&0x1f];
#define LeftMost 0
#define StepBit(bit, inc) ((bit) += (inc))
#define GetBits(psrc, nBits, curBit, bitPos, bits) {\
bits = 0; \
while (nBits--) \
{ \
bits |= ((*psrc++ >> bitPos) & 1) << curBit; \
StepBit (curBit, 1); \
} \
}
/******************************************************************/
static void
cfbCopyPlane1to32 (pSrcDrawable, pDstDrawable, rop, prgnDst, pptSrc,
planemask, bitPlane, pGC)
DrawablePtr pSrcDrawable;
DrawablePtr pDstDrawable;
int rop;
unsigned long planemask;
RegionPtr prgnDst;
DDXPointPtr pptSrc;
int bitPlane;
GC *pGC;
{
int srcx, srcy, dstx, dsty;
int width, height;
int xoffSrc;
unsigned long *psrcBase, *pdstBase;
int widthSrc, widthDst;
unsigned int *psrcLine, *pdstLine;
register unsigned int *psrc, *pdst;
register unsigned int bits, tmp;
register unsigned int fgpixel, bgpixel;
register unsigned int src;
register int leftShift, rightShift;
register int i, nl;
int nbox;
BoxPtr pbox;
int result;
if (pGC)
{
fgpixel = pGC->fgPixel & planemask;
bgpixel = pGC->bgPixel & planemask;
}
else
{
fgpixel = ~0 & planemask;
bgpixel = 0;
}
/* must explicitly ask for "int" widths, as code below expects it */
/* on some machines (Alpha), "long" and "int" are not the same size */
cfbGetTypedWidthAndPointer (pSrcDrawable, widthSrc, psrcBase, int, unsigned long)
cfbGetTypedWidthAndPointer (pDstDrawable, widthDst, pdstBase, int, unsigned long)
nbox = REGION_NUM_RECTS(prgnDst);
pbox = REGION_RECTS(prgnDst);
while (nbox--)
{
dstx = pbox->x1;
dsty = pbox->y1;
srcx = pptSrc->x;
srcy = pptSrc->y;
width = pbox->x2 - pbox->x1;
height = pbox->y2 - pbox->y1;
pbox++;
pptSrc++;
psrcLine = (unsigned int *)psrcBase + srcy * widthSrc + (srcx >> 5);
pdstLine = (unsigned int *)pdstBase + dsty * widthDst + dstx;
xoffSrc = srcx & 0x1f;
/*
* compute constants for the first four bits to be
* copied. This avoids troubles with partial first
* writes, and difficult shift computation
*/
leftShift = xoffSrc;
rightShift = 32 - leftShift;
if (rop == GXcopy && planemask == 0xffffffff)
{
while (height--)
{
psrc = psrcLine;
pdst = pdstLine;
psrcLine += widthSrc;
pdstLine += widthDst;
bits = *psrc++;
nl = width;
while (nl >= 32)
{
tmp = BitLeft(bits, leftShift);
bits = *psrc++;
if (rightShift != 32)
tmp |= BitRight(bits, rightShift);
i = 32;
while (i--)
{
*pdst = ((tmp >> (31 - i)) & 0x01) ? fgpixel : bgpixel;
pdst++;
}
nl -= 32;
}
if (nl)
{
tmp = BitLeft(bits, leftShift);
/*
* better condition needed -- mustn't run
* off the end of the source...
*/
if (rightShift != 32)
{
bits = *psrc++;
tmp |= BitRight (bits, rightShift);
}
i = 32;
while (nl--)
{
--i;
*pdst = ((tmp >> (31 - i)) & 0x01) ? fgpixel : bgpixel;
pdst++;
}
}
}
}
else
{
while (height--)
{
psrc = psrcLine;
pdst = pdstLine;
psrcLine += widthSrc;
pdstLine += widthDst;
bits = *psrc++;
nl = width;
while (nl >= 32)
{
tmp = BitLeft(bits, leftShift);
bits = *psrc++;
if (rightShift != 32)
tmp |= BitRight(bits, rightShift);
i = 32;
while (i--)
{
src = ((tmp >> (31 - i)) & 0x01) ? fgpixel : bgpixel;
DoRop (result, rop, src, *pdst);
*pdst = (*pdst & ~planemask) |
(result & planemask);
pdst++;
}
nl -= 32;
}
if (nl)
{
tmp = BitLeft(bits, leftShift);
/*
* better condition needed -- mustn't run
* off the end of the source...
*/
if (rightShift != 32)
{
bits = *psrc++;
tmp |= BitRight (bits, rightShift);
}
i = 32;
while (nl--)
{
--i;
src = ((tmp >> (31 - i)) & 0x01) ? fgpixel : bgpixel;
DoRop (result, rop, src, *pdst);
*pdst = (*pdst & ~planemask) |
(result & planemask);
pdst++;
}
}
}
}
}
}
static void
cfbCopyPlane32to1 (pSrcDrawable, pDstDrawable, rop, prgnDst, pptSrc,
planemask, bitPlane)
DrawablePtr pSrcDrawable;
DrawablePtr pDstDrawable;
int rop;
RegionPtr prgnDst;
DDXPointPtr pptSrc;
unsigned long planemask;
unsigned long bitPlane;
{
int srcx, srcy, dstx, dsty, width, height;
unsigned long *psrcBase;
unsigned long *pdstBase;
int widthSrc, widthDst;
unsigned int *psrcLine;
unsigned int *pdstLine;
register unsigned int *psrc;
register int i;
register int curBit;
register int bitPos;
register unsigned int bits;
register unsigned int *pdst;
unsigned int startmask, endmask;
int niStart, niEnd;
int bitStart, bitEnd;
int nl, nlMiddle;
int nbox;
BoxPtr pbox;
int result;
extern int starttab[32], endtab[32];
extern unsigned int partmasks[32][32];
if (!(planemask & 1))
return;
/* must explicitly ask for "int" widths, as code below expects it */
/* on some machines (Alpha), "long" and "int" are not the same size */
cfbGetTypedWidthAndPointer (pSrcDrawable, widthSrc, psrcBase, int, unsigned long)
cfbGetTypedWidthAndPointer (pDstDrawable, widthDst, pdstBase, int, unsigned long)
bitPos = ffs (bitPlane) - 1;
nbox = REGION_NUM_RECTS(prgnDst);
pbox = REGION_RECTS(prgnDst);
while (nbox--)
{
dstx = pbox->x1;
dsty = pbox->y1;
srcx = pptSrc->x;
srcy = pptSrc->y;
width = pbox->x2 - pbox->x1;
height = pbox->y2 - pbox->y1;
pbox++;
pptSrc++;
psrcLine = (unsigned int *)psrcBase + srcy * widthSrc + srcx;
pdstLine = (unsigned int *)pdstBase + dsty * widthDst + (dstx >> 5);
if (dstx + width <= 32)
{
mfbmaskpartialbits(dstx, width, startmask);
nlMiddle = 0;
endmask = 0;
}
else
{
mfbmaskbits (dstx, width, startmask, endmask, nlMiddle);
}
if (startmask)
{
niStart = 32 - (dstx & 0x1f);
bitStart = LeftMost;
StepBit (bitStart, (dstx & 0x1f));
}
if (endmask)
{
niEnd = (dstx + width) & 0x1f;
bitEnd = LeftMost;
}
if (rop == GXcopy)
{
while (height--)
{
psrc = psrcLine;
pdst = pdstLine;
psrcLine += widthSrc;
pdstLine += widthDst;
if (startmask)
{
i = niStart;
curBit = bitStart;
GetBits (psrc, i, curBit, bitPos, bits);
*pdst = (*pdst & ~startmask) | bits;
pdst++;
}
nl = nlMiddle;
while (nl--)
{
i = 32;
curBit = LeftMost;
GetBits (psrc, i, curBit, bitPos, bits);
*pdst++ = bits;
}
if (endmask)
{
i = niEnd;
curBit = bitEnd;
GetBits (psrc, i, curBit, bitPos, bits);
*pdst = (*pdst & ~endmask) | bits;
}
}
}
else
{
while (height--)
{
psrc = psrcLine;
pdst = pdstLine;
psrcLine += widthSrc;
pdstLine += widthDst;
if (startmask)
{
i = niStart;
curBit = bitStart;
GetBits (psrc, i, curBit, bitPos, bits);
DoRop (result, rop, bits, *pdst);
*pdst = (*pdst & ~startmask) |
(result & startmask);
pdst++;
}
nl = nlMiddle;
while (nl--)
{
i = 32;
curBit = LeftMost;
GetBits (psrc, i, curBit, bitPos, bits);
DoRop (result, rop, bits, *pdst);
*pdst = result;
++pdst;
}
if (endmask)
{
i = niEnd;
curBit = bitEnd;
GetBits (psrc, i, curBit, bitPos, bits);
DoRop (result, rop, bits, *pdst);
*pdst = (*pdst & ~endmask) |
(result & endmask);
}
}
}
}
}
static void
cfbCopyPlane1to16 (pSrcDrawable, pDstDrawable, rop, prgnDst, pptSrc,
planeMask, bitPlane, pGC)
DrawablePtr pSrcDrawable;
DrawablePtr pDstDrawable;
int rop;
unsigned long planeMask;
RegionPtr prgnDst;
DDXPointPtr pptSrc;
int bitPlane;
GC *pGC;
{
int srcx, srcy, dstx, dsty;
int width, height;
int xoffSrc;
unsigned long *psrcBase, *pdstBase;
int widthSrc, widthDst;
unsigned int *psrcLine;
unsigned short *pdstLine;
register unsigned int *psrc;
register unsigned short *pdst;
register unsigned int bits, tmp;
register unsigned short fgpixel, bgpixel;
register unsigned short src;
register int leftShift, rightShift;
register int i, nl;
unsigned short planemask = (unsigned short)planeMask;
int nbox;
BoxPtr pbox;
unsigned short result;
if (pGC)
{
fgpixel = (unsigned short)pGC->fgPixel & planemask;
bgpixel = (unsigned short)pGC->bgPixel & planemask;
}
else
{
fgpixel = ~0 & planemask;
bgpixel = 0;
}
/* must explicitly ask for "int" widths, as code below expects it */
/* on some machines (Alpha), "long" and "int" are not the same size */
cfbGetTypedWidthAndPointer (pSrcDrawable, widthSrc, psrcBase, int, unsigned long)
cfbGetTypedWidthAndPointer (pDstDrawable, widthDst, pdstBase, int, unsigned long)
widthDst = widthDst << 1;
nbox = REGION_NUM_RECTS(prgnDst);
pbox = REGION_RECTS(prgnDst);
while (nbox--)
{
dstx = pbox->x1;
dsty = pbox->y1;
srcx = pptSrc->x;
srcy = pptSrc->y;
width = pbox->x2 - pbox->x1;
height = pbox->y2 - pbox->y1;
pbox++;
pptSrc++;
psrcLine = (unsigned int *)psrcBase + srcy * widthSrc + (srcx >> 5);
pdstLine = (unsigned short *)pdstBase + dsty * widthDst + dstx;
xoffSrc = srcx & 0x1f;
/*
* compute constants for the first four bits to be
* copied. This avoids troubles with partial first
* writes, and difficult shift computation
*/
leftShift = xoffSrc;
rightShift = 32 - leftShift;
if (rop == GXcopy && planemask == 0xffff)
{
while (height--)
{
psrc = psrcLine;
pdst = pdstLine;
psrcLine += widthSrc;
pdstLine += widthDst;
bits = *psrc++;
nl = width;
while (nl >= 32)
{
tmp = BitLeft(bits, leftShift);
bits = *psrc++;
if (rightShift != 32)
tmp |= BitRight(bits, rightShift);
i = 32;
while (i--)
{
*pdst = (((tmp >> (31-i)) & 0x01) ? fgpixel : bgpixel);
pdst++;
}
nl -= 32;
}
if (nl)
{
tmp = BitLeft(bits, leftShift);
/*
* better condition needed -- mustn't run
* off the end of the source...
*/
if (rightShift != 32)
{
bits = *psrc++;
tmp |= BitRight (bits, rightShift);
}
i = 32;
while (nl--)
{
--i;
*pdst = (((tmp >> (31-i)) & 0x01) ? fgpixel : bgpixel);
pdst++;
}
}
}
}
else
{
while (height--)
{
psrc = psrcLine;
pdst = pdstLine;
psrcLine += widthSrc;
pdstLine += widthDst;
bits = *psrc++;
nl = width;
while (nl >= 32)
{
tmp = BitLeft(bits, leftShift);
bits = *psrc++;
if (rightShift != 32)
tmp |= BitRight(bits, rightShift);
i = 32;
while (i--)
{
src = ((tmp >> (31-i)) & 0x01) ? fgpixel : bgpixel;
DoRop (result, rop, src, *pdst);
*pdst = (*pdst & ~planemask) |
(result & planemask);
pdst++;
}
nl -= 32;
}
if (nl)
{
tmp = BitLeft(bits, leftShift);
/*
* better condition needed -- mustn't run
* off the end of the source...
*/
if (rightShift != 32)
{
bits = *psrc++;
tmp |= BitRight (bits, rightShift);
}
i = 32;
while (nl--)
{
--i;
src = ((tmp >> (31-i)) & 0x01) ? fgpixel : bgpixel;
DoRop (result, rop, src, *pdst);
*pdst = (*pdst & ~planemask) |
(result & planemask);
pdst++;
}
}
}
}
}
}
static void
cfbCopyPlane16to1 (pSrcDrawable, pDstDrawable, rop, prgnDst, pptSrc,
planemask, bitPlane)
DrawablePtr pSrcDrawable;
DrawablePtr pDstDrawable;
int rop;
RegionPtr prgnDst;
DDXPointPtr pptSrc;
unsigned long planemask;
unsigned long bitPlane;
{
int srcx, srcy, dstx, dsty, width, height;
unsigned long *psrcBase, *pdstBase;
int widthSrc, widthDst;
unsigned short *psrcLine;
unsigned int *pdstLine;
register unsigned short *psrc;
register unsigned int *pdst;
register int i;
register int curBit;
register int bitPos;
register unsigned int bits;
unsigned int startmask, endmask;
int niStart, niEnd;
int bitStart, bitEnd;
int nl, nlMiddle;
int nbox;
BoxPtr pbox;
int result;
extern int starttab[32], endtab[32];
extern unsigned int partmasks[32][32];
if (!(planemask & 1))
return;
/* must explicitly ask for "int" widths, as code below expects it */
/* on some machines (Alpha), "long" and "int" are not the same size */
cfbGetTypedWidthAndPointer (pSrcDrawable, widthSrc, psrcBase, int, unsigned long)
cfbGetTypedWidthAndPointer (pDstDrawable, widthDst, pdstBase, int, unsigned long)
widthSrc = widthSrc << 1;
bitPos = ffs (bitPlane) - 1;
nbox = REGION_NUM_RECTS(prgnDst);
pbox = REGION_RECTS(prgnDst);
while (nbox--)
{
dstx = pbox->x1;
dsty = pbox->y1;
srcx = pptSrc->x;
srcy = pptSrc->y;
width = pbox->x2 - pbox->x1;
height = pbox->y2 - pbox->y1;
pbox++;
pptSrc++;
psrcLine = (unsigned short *)psrcBase + srcy * widthSrc + srcx;
pdstLine = (unsigned int *)pdstBase + dsty * widthDst + (dstx >> 5);
if (dstx + width <= 32)
{
mfbmaskpartialbits(dstx, width, startmask);
nlMiddle = 0;
endmask = 0;
}
else
{
mfbmaskbits (dstx, width, startmask, endmask, nlMiddle);
}
if (startmask)
{
niStart = 32 - (dstx & 0x1f);
bitStart = LeftMost;
StepBit (bitStart, (dstx & 0x1f));
}
if (endmask)
{
niEnd = (dstx + width) & 0x1f;
bitEnd = LeftMost;
}
if (rop == GXcopy)
{
while (height--)
{
psrc = psrcLine;
pdst = pdstLine;
psrcLine += widthSrc;
pdstLine += widthDst;
if (startmask)
{
i = niStart;
curBit = bitStart;
GetBits (psrc, i, curBit, bitPos, bits);
*pdst = (*pdst & ~startmask) | bits;
pdst++;
}
nl = nlMiddle;
while (nl--)
{
i = 32;
curBit = LeftMost;
GetBits (psrc, i, curBit, bitPos, bits);
*pdst++ = bits;
}
if (endmask)
{
i = niEnd;
curBit = bitEnd;
GetBits (psrc, i, curBit, bitPos, bits);
*pdst = (*pdst & ~endmask) | bits;
}
}
}
else
{
while (height--)
{
psrc = psrcLine;
pdst = pdstLine;
psrcLine += widthSrc;
pdstLine += widthDst;
if (startmask)
{
i = niStart;
curBit = bitStart;
GetBits (psrc, i, curBit, bitPos, bits);
DoRop (result, rop, bits, *pdst);
*pdst = (*pdst & ~startmask) |
(result & startmask);
pdst++;
}
nl = nlMiddle;
while (nl--)
{
i = 32;
curBit = LeftMost;
GetBits (psrc, i, curBit, bitPos, bits);
DoRop (result, rop, bits, *pdst);
*pdst = result;
++pdst;
}
if (endmask)
{
i = niEnd;
curBit = bitEnd;
GetBits (psrc, i, curBit, bitPos, bits);
DoRop (result, rop, bits, *pdst);
*pdst = (*pdst & ~endmask) |
(result & endmask);
}
}
}
}
}
| 27.92803 | 109 | 0.556739 | [
"vector"
] |
bae8e99eb467335613a810917d669a2a3b68b95a | 1,407 | h | C | src/mergingType.h | stefani-nik/Huffman-Archivator | bd1c475e59ecadc1cd701bf6b3476623f9cc2620 | [
"Apache-2.0"
] | null | null | null | src/mergingType.h | stefani-nik/Huffman-Archivator | bd1c475e59ecadc1cd701bf6b3476623f9cc2620 | [
"Apache-2.0"
] | null | null | null | src/mergingType.h | stefani-nik/Huffman-Archivator | bd1c475e59ecadc1cd701bf6b3476623f9cc2620 | [
"Apache-2.0"
] | null | null | null | #pragma once
#ifndef MERGINGTYPE_H
#define MERGINGTYPE_H
class mergingType
{
friend class HuffmanCoding;
public:
//constructor copy data and count to class
mergingType(int dat = 0, int cnt = 0)
{
data = dat; count = cnt;
}
//copy right's elements into this class's elements
mergingType &operator=(const mergingType &right)
{
data = right.data; count = right.count; return *this;
}
//both of items must be equal
bool operator==(const mergingType &right) const
{
return ((count == right.count) && (data == right.data));
}
//because equality is checked data is useless
bool operator<=(const mergingType &right) const
{
return count <= right.count;
}
//because equality is checked data is useless
bool operator>=(const mergingType &right) const
{
return count >= right.count;
}
bool operator<(const mergingType &right) const
{
if (count < right.count)
return true;
else if (count > right.count)
return false;
else
return data > right.data;
}
bool operator>(const mergingType &right) const
{
if (count > right.count)
return true;
else if (count < right.count)
return false;
else
return data < right.data;
}
//return a new object containing some of both elements
mergingType operator+(const mergingType &right) const
{
mergingType tmp(data + right.data, count + right.count); return tmp;
}
private:
int data;
int count;
};
#endif | 20.691176 | 70 | 0.695807 | [
"object"
] |
baf109864d75c665d5428b1a302d58bf048cc15e | 1,470 | h | C | OvRender/source/d3d9/d3d9font.h | fengjixuchui/Push | 662cfb8684af63b8c8afbd742aeabdfa195441fb | [
"MIT"
] | 32 | 2015-07-19T05:33:11.000Z | 2021-10-31T10:45:16.000Z | OvRender/source/d3d9/d3d9font.h | fengjixuchui/Push | 662cfb8684af63b8c8afbd742aeabdfa195441fb | [
"MIT"
] | 63 | 2015-03-08T08:41:12.000Z | 2020-01-15T13:50:46.000Z | OvRender/source/d3d9/d3d9font.h | fengjixuchui/Push | 662cfb8684af63b8c8afbd742aeabdfa195441fb | [
"MIT"
] | 11 | 2016-02-14T09:57:27.000Z | 2021-07-03T09:59:23.000Z | #ifndef D3DFONT_H
#define D3DFONT_H
#include <D3D9.h>
#include <font.h>
//-----------------------------------------------------------------------------
// Name: class CD3DFont
// Desc: Texture-based font class for doing text in a 3D scene.
//-----------------------------------------------------------------------------
class Dx9Font : public Font
{
LPDIRECT3DDEVICE9 m_pd3dDevice; // A D3DDevice used for rendering
LPDIRECT3DTEXTURE9 m_pTexture; // The d3d texture for this font
LPDIRECT3DVERTEXBUFFER9 m_pVB; // VertexBuffer for rendering text
// Stateblocks for setting and restoring render states
LPDIRECT3DSTATEBLOCK9 m_pStateBlockSaved;
LPDIRECT3DSTATEBLOCK9 m_pStateBlockDrawText;
public:
// 2D and 3D text drawing functions
HRESULT DrawText( FLOAT x, FLOAT y, DWORD dwColor,
WCHAR* strText, DWORD dwFlags=0L );
HRESULT DrawTextScaled( FLOAT x, FLOAT y, FLOAT z,
FLOAT fXScale, FLOAT fYScale, DWORD dwColor,
const WCHAR* strText, DWORD dwFlags=0L );
HRESULT Render3DText( const WCHAR* strText, DWORD dwFlags=0L );
// Initializing and destroying device-dependent objects
HRESULT RestoreDeviceObjects();
HRESULT InvalidateDeviceObjects();
HRESULT DeleteDeviceObjects();
// Constructor / destructor
Dx9Font(LPDIRECT3DDEVICE9 pd3dDevice, FONT_PROPERTIES* Properties);
~Dx9Font();
};
#endif
| 34.186047 | 79 | 0.615646 | [
"render",
"3d"
] |
baf7eac3e29ecbdd15c8ce5b3e703e81939f3796 | 2,046 | h | C | src/fps_ros_bridge/local_mapper_ros.h | Lab-RoCoCo/fps_mapper | 376e557c8f5012e05187fe85ee3f4044f99f944a | [
"BSD-3-Clause"
] | 1 | 2017-12-01T14:57:16.000Z | 2017-12-01T14:57:16.000Z | src/fps_ros_bridge/local_mapper_ros.h | Lab-RoCoCo/fps_mapper | 376e557c8f5012e05187fe85ee3f4044f99f944a | [
"BSD-3-Clause"
] | null | null | null | src/fps_ros_bridge/local_mapper_ros.h | Lab-RoCoCo/fps_mapper | 376e557c8f5012e05187fe85ee3f4044f99f944a | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include "core/depth_utils.h"
#include "core/nn_aligner.h"
#include "core/projective_aligner.h"
#include "tracker/tracker.h"
#include "tracker/base_triggers.h"
#include "local_mapper/local_map_triggers.h"
#include "tracker/multi_tracker.h"
#include "txt_io/tf_overrider_trigger.h"
#include "ros_wrappers/image_message_listener.h"
#include "txt_io/message_enlister_trigger.h"
#include "txt_io/message_dumper_trigger.h"
#include "txt_io/pinhole_image_message.h"
#include "fps_ros_msgs.h"
#include <ros/ros.h>
#include <sensor_msgs/Image.h>
#include <tf/transform_listener.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <vector>
#include <fstream>
#include <iostream>
namespace fps_mapper {
class LocalMapperRos : public LocalMapTrigger{
public:
LocalMapperRos(Tracker* tracker,
int priorory = 10,
boss::Serializer* ser=0,
boss::IdContext * context=0):
LocalMapTrigger(tracker,
Tracker::TRACK_GOOD|
Tracker::TRACK_BROKEN|
Tracker::REFERENCE_FRAME_RESET|
Tracker::TRACKING_DONE|
Tracker::NEW_CAMERA_ADDED,
priorory,
ser){
_context = context;
cerr << "LOCAL MAPPER ROS" << endl;
}
void init(ros::NodeHandle& nh);
virtual void onCameraInfoCreated(BaseCameraInfo* camera_info);
virtual void onLocalMapCreated(LocalMap* lmap);
virtual void onNewNodeCreated(MapNode* node, BinaryNodeRelation* rel);
virtual void onRelationCreated(BinaryNodeRelation* rel);
protected:
void serializeCameras();
void serializeCamera(BaseCameraInfo* cam);
void serializeTrajectory(MapNodeList& nodes);
void serializeNode(MapNode* n);
void serializeRelation(BinaryNodeRelation* rel);
std::vector<BaseCameraInfo*> _camera_infos;
ros::Publisher _image_node_pub;
ros::Publisher _multi_image_node_pub;
ros::Publisher _camera_info_pub;
ros::Publisher _multi_camera_info_pub;
ros::Publisher _local_map_pub;
ros::Publisher _relations_pub;
boss::IdContext* _context;
};
}
| 28.816901 | 74 | 0.730694 | [
"vector"
] |
baf9feecad3f744b1fae8aa39c63fbfc4b8b2f7f | 10,498 | c | C | src/common.c | aiporre/whisk | e07c381bc5d0df4e5dcabd7d75c0c97d0de3ad2c | [
"BSD-3-Clause"
] | 4 | 2016-06-22T14:30:14.000Z | 2021-05-15T18:24:58.000Z | src/common.c | aiporre/whisk | e07c381bc5d0df4e5dcabd7d75c0c97d0de3ad2c | [
"BSD-3-Clause"
] | 20 | 2015-09-28T14:43:59.000Z | 2020-05-23T00:43:46.000Z | src/common.c | aiporre/whisk | e07c381bc5d0df4e5dcabd7d75c0c97d0de3ad2c | [
"BSD-3-Clause"
] | 9 | 2015-10-12T22:31:39.000Z | 2021-09-09T04:44:20.000Z | /* Author: Nathan Clack <clackn@janelia.hhmi.org>
* Date : May 2009
*
* Copyright 2010 Howard Hughes Medical Institute.
* All rights reserved.
* Use is subject to Janelia Farm Research Campus Software Copyright 1.1
* license terms (http://license.janelia.org/license/jfrc_copyright_1_1.html).
*/
#pragma warning(disable : 4996)
#pragma warning(disable : 4244)
#include "utilities.h"
#include <assert.h>
#include <string.h>
#include "compat.h"
#if 0
#define DEBUG_REQUEST_STORAGE
#endif
//
// MEMORY
// ------
//
//for debugging
void dump_doubles(char* filename, double* a, int n)
{ FILE *fp = fopen(filename,"wb");
fwrite(a, sizeof(double), n, fp);
fclose(fp);
}
void *request_storage( void *buffer, size_t *maxlen, size_t nbytes, size_t minindex, char *msg )
{ if( (nbytes*minindex) > *maxlen )
{ size_t newsize = (size_t) (1.25 * minindex + 64) * nbytes;
#ifdef DEBUG_REQUEST_STORAGE
printf("REQUEST %7d bytes (%7d items) above current %7d bytes by %s\n",minindex * nbytes, minindex, *maxlen,msg);
#endif
buffer = Guarded_Realloc( buffer, newsize, msg );
*maxlen = newsize;
}
return buffer;
}
void *request_storage_zeroed( void *buffer, size_t *maxlen, size_t nbytes, size_t minindex, char *msg )
{ if( (nbytes*minindex) > *maxlen )
{ size_t newsize = (size_t) (1.25 * minindex + 64) * nbytes;
#ifdef DEBUG_REQUEST_STORAGE
printf("REQUEST %7d bytes (%7d items) above current %7d bytes by %s\n",minindex * nbytes, minindex, *maxlen,msg);
#endif
buffer = Guarded_Realloc( buffer, newsize, msg );
memset((char*)buffer+*maxlen,0,newsize-*maxlen);
*maxlen = newsize;
}
return buffer;
}
size_t _next_pow2_uint32(uint32_t v)
{ v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
size_t _next_pow2_uint64(uint64_t v)
{ v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v |= v >> 32;
v++;
return v;
}
// TODO - returns buffers where maxlen_items is a power of 2
void *request_storage_pow2items( void *buffer, size_t *maxlen_bytes, size_t nbytes, size_t minindex, char *msg )
{ if( (nbytes*minindex) > *maxlen_bytes )
{
#ifdef DEBUG_REQUEST_STORAGE
printf("REQUEST %7d bytes (%7d items) above current %7d bytes by %s\n",minindex * nbytes, minindex, *maxlen_bytes,msg);
assert(sizeof(size_t)==4);
#endif
*maxlen_bytes = (size_t) ( _next_pow2_uint32(minindex) ) * nbytes;
buffer = Guarded_Realloc( buffer, *maxlen_bytes, msg );
}
return buffer;
}
//
// FILE IO
// -------
//
int fskipline(FILE* fp, size_t *nch)
{ //return fgetln(fp,nch)!=NULL; // not available on windows :(
size_t i = 0;
int c;
do { c = fgetc(fp); i++; } while( c!=EOF && c!='\n' );
*nch = i;
return (c=='\n');
}
//
// NUMERICAL
// ---------
//
/**
* Threshold estimation using k-means for k=2 on 8 bit images.
*/
float threshold_two_means( uint8_t *array, size_t size )
{ size_t hist[ 256 ],i;
uint8_t *cur = array + size;
float num = 0.0,
dom = 0.0,
thresh,last,
c[2] = {0.0,0.0};
memset(hist,0,256*sizeof(size_t));
while(cur-- > array) ++hist[ *cur ];
for(i=0;i<256;i++)
{ float v = hist[i];
num += i*v;
dom += v;
}
thresh = num/dom; // the mean - compute this way bc we need to compute the hist anyway
// update means
do
{ last = thresh;
num = dom = 0.0;
for(i=0;i<thresh;i++)
{ float v = hist[i];
num += i*v;
dom += v;
}
c[0] = num/dom;
num = dom = 0.0;
for(;i<256;i++)
{ float v = hist[i];
num += i*v;
dom += v;
}
c[1] = num/dom;
thresh = (c[1]+c[0])/2.0;
} while( fabs(last - thresh) > 0.5 );
//debug("Threshold: %f\n",thresh);
return thresh;
}
/**
* Resizes and fills <resizable> with <n> points from <low> to <high>.
* <low> and <high> are inclusive bounds.
*
* Note the location of resizable may change.
*/
void linspace_d( double low, double high, int n, double **resizable, size_t *size )
{ double step = (high-low)/(n-1.0);
int i;
double *a;
*resizable = request_storage(*resizable, size, sizeof(double), n, "linspace_d");
a = *resizable;
for(i=0;i<n;i++)
a[i] = step*i + low;
}
/**
* Based on:
* Daniel Lemire, "Streaming Maximum-minimum filter using no more than
* three comparisons per element', Nordic Journal of Computing, 13(4) pp. 328-339, 2006.
*
* Right now the modulus division for indexing the queue ring buffers is by far
* the most expensive thing. (~97% of the time for arrays with millions of
* elements).
*
* One way around this is to reset the ring buffer indices when the queue is
* emptied. Since the size of the queue is bounded by the support size,
* this might eliminate the need for a ring buffer.
*
*/
#define pushf(x) ( x[++i##x##f & max##x] )
#define popf(x) ( x[i##x##f-- & max##x] )
#define popf_noassign(x) ( i##x##f--)
#define peekf(x) ( x[ i##x##f & max##x] )
#define pushb(x) ( x[--i##x##b & max##x] )
#define popb(x) ( x[i##x##b++ & max##x] )
#define popb_noassign(x) ( i##x##b++)
#define peekb(x) ( x[ i##x##b & max##x] )
#define isempty(x) ( i##x##f+1 == i##x##b )
void maxfilt_centered_double_inplace( double *a, int len, int support )
{ static double **U = NULL;
static size_t maxUbytes = 0;
size_t maxU,maxR;
unsigned int iUf,iUb,iRf,iRb;
static double *R = NULL;
static size_t maxRbytes = 0;
double *e;
int off = support;
int c = support/2+1;
double this,last;
assert(support > 2);
U = request_storage_pow2items(U,&maxUbytes,sizeof(double*), 2*support , "maxfilt_centered_double_inplace");
maxU = maxUbytes / sizeof(double*) - 1;
iUf = maxU/2-1;
iUb = maxU/2;
R = request_storage_pow2items(R,&maxRbytes,sizeof(double), 2*(off-c), "maxfilt_centered_double_inplace");
maxR = maxRbytes / sizeof(double) - 1;
iRf=-1;
iRb=0;
//The middle (support entirely in interval)
last = *a;
for( e=a+1; e < a+len; e++ )
{ this = *e;
if( e-a >= c )
pushf(R) = isempty(U) ? last : *peekf(U);
if( e-a >= off )
e[-off] = popb(R);
//progress("iRf:%5d\tiUf:%5d\tiUb:%5d\tsz:%5d\n",iRf,iUf,iUb,iUf-iUb+1);
if( this > last )
{ while( !isempty(U) )
{ if( this <= *peekb(U) )
{ if( e-off == peekf(U) )
popf_noassign(U);
break;
}
if( !isempty(U) )
popb_noassign(U);
}
} else
{ pushb(U) = e-1;
if( (e-off) == peekf(U) )
popf_noassign(U);
}
last = this;
}
//The end
for( ; e <= a+len+c; e++ )
{ pushf(R) = isempty(U) ? e[-1] : *peekf(U);
e[-off] = popb(R);
pushb(U) = e-1;
if( (e-off) == peekf(U) )
popf_noassign(U);
}
}
#ifdef TEST_MAX_FILT_1
double testdata[] = {-1.0, 2.0,-3.0, 4.0,
3.0, 2.0, 1.0, 0.0,
1.0, 2.0, 3.0, 4.0,
3.0, 2.0, 1.0, 4.0};
//double expected[] = { 2.0, 4.0, 4.0, 4.0,
// 3.0, 2.0, 1.0, 2.0,
// 3.0, 4.0, 4.0, 4.0,
// 3.0, 4.0, 4.0, 4.0};
double expected[] = { 2.0, 2.0, 4.0, 4.0, //window 3
4.0, 3.0, 2.0, 1.0,
2.0, 3.0, 4.0, 4.0,
4.0, 3.0, 4.0, 4.0};
//double expected[] = { 2.0, 4.0, 4.0, 4.0, //window 5
// 4.0, 4.0, 3.0, 2.0,
// 3.0, 4.0, 4.0, 4.0,
// 4.0, 4.0, 4.0, 4.0};
#endif
#ifdef TEST_MAX_FILT_2
double testdata[] = { 1.0, 0.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 0.0, 1.0};
//double expected[] = { 1.0, 0.0, 0.0, 0.0,
// 1.0, 1.0, 1.0, 0.0,
// 0.0, 0.0, 0.0, 0.0,
// 0.0, 1.0, 1.0, 1.0};
double expected[] = { 1.0, 1.0, 0.0, 0.0, //window 3
0.0, 1.0, 1.0, 1.0,
0.0, 0.0, 0.0, 0.0,
0.0, 0.0, 1.0, 1.0};
//double expected[] = { 1.0, 1.0, 0.0, 0.0, //window 4
// 1.0, 1.0, 1.0, 1.0,
// 0.0, 0.0, 0.0, 0.0,
// 0.0, 1.0, 1.0, 1.0};
//double expected[] = { 1.0, 1.0, 1.0, 0.0, // window 5
// 1.0, 1.0, 1.0, 1.0,
// 1.0, 0.0, 0.0, 0.0,
// 0.0, 1.0, 1.0, 1.0};
#endif
#if defined(TEST_MAX_FILT_1) || defined(TEST_MAX_FILT_2)
int main(int argc, char* argv[])
{ int i,j;
double *e = expected;
{ for(i=0;i<16;i++)
progress("%2d %f\n",i,testdata[i]);
maxfilt_centered_double_inplace( testdata, 16, 3 );
progress("\n"
" # R E =\n"
"-- --- --- -\n"
);
for(i=0;i<16;i++)
progress("%2d %2.1f %2.1f %d\n",i,testdata[i],e[i],testdata[i]==e[i]);
}
return 0;
}
#endif
#ifdef TEST_MAX_FILT_3
#include <math.h>
#include <time.h>
#define N (1000000)
int main(int argc, char* argv[])
{ int i = N;
double k = 2*M_PI/N;
double *t;
double *y;
int j = 100;
clock_t clock0;
double t0,t1;
t = Guarded_Malloc(sizeof(double)*N,"t");
y = Guarded_Malloc(sizeof(double)*N,"y");
progress(" w t(ms) type\n"
"--- ----- ----\n");
while((j-=3)>3)
{
i=N;
while(i--)
{ t[i] = i;
y[i] = sin(k*i*4.0);
}
clock0 = clock();
maxfilt_centered_double_inplace( y, N, j );
t0 = (double)(clock()-clock0)/((double)(CLOCKS_PER_SEC));
progress("%3d %4.1f sin\n",j, 1e3*t0 );
clock0 = clock();
maxfilt_centered_double_inplace( t, N, j );
t1 = (double)(clock()-clock0)/((double)(CLOCKS_PER_SEC));
progress("%3d %2.1f ramp\n",j, 1e3*t1 );
}
progress("\n"
"NOTE\n"
"----\n"
"Timings should be constant with respect to window size (w).\n"
"Each time is for an array of %g elements.\n"
"Based on the last times...\n"
"\tThroughput for the sin wave: %4.1f MSamples/s\n"
"\tThroughput for the ramp : %4.1f MSamples/s\n",(double)N, 1e-6*((double)N)/t0, 1e-6*((double)N)/t1 );
free(t);
free(y);
return 0;
}
#endif
| 28.840659 | 123 | 0.517337 | [
"3d"
] |
bafc8cbaa7bb3238d5a34dc762f7efa425251fa9 | 45,943 | c | C | meh_gl.c | he110world/libmeh | 6696363ed79fcd2a8d9bf9a6f88774d0d0861731 | [
"MIT"
] | 2 | 2015-03-05T12:46:29.000Z | 2019-09-10T04:47:44.000Z | meh_gl.c | he110world/libmeh | 6696363ed79fcd2a8d9bf9a6f88774d0d0861731 | [
"MIT"
] | null | null | null | meh_gl.c | he110world/libmeh | 6696363ed79fcd2a8d9bf9a6f88774d0d0861731 | [
"MIT"
] | null | null | null | #include "meh_gl.h"
#include "memory.h"
/*--------------------------------------------------------------------
Shaders
-------------------------------------------------------------------*/
// GL shader
typedef struct vfs_s {
struct vfs_s *prev, *next;
char *nam;
time_t time;
int id;
uint p; // program index
uint vs,fs;
//--------- vert attribs
// char **attrodr;
// int nattr;
int narray; // number of vertex attrib arrays (can be different with nattr -- one attrib like matrix == multiple arrays)
char *dim;// dimension of each vector (attribute)
short *acount; // attrib count for each name (may be the name of array, matrix => have multiple indices)
short *stride; // for interleaved vertex array
short *ofs; // for interleaved VA
short *stream;
int nbytes;
void *amem;
//--------- uniforms
char *multitex; // multitex[uniform_index] == multitex_i
int ntex;
int nu; // num of uniforms
char *ucount;
PFNGLUNIFORM1FVPROC *vectorfunc;
PFNGLUNIFORMMATRIX2FVPROC *matrixfunc;
void *umem; // mem used to store ucount[], vectorfunc[] matrixfunc[] and multitex[]
//--------- render targets
int nrts;
int depthrt;
} vfs_t;
/*-------------------------------------
Parse vertex/fragment shader program file
------------------------------------*/
/*--------------------------------------
Load vertex/fragment shaders
The shader named "nam" will be loaded twice:
Once the string "#define GL_FRAGMENT_SHADER" is inserted at the top of the shader; remove the string after loading.
Then the string "#define GL_VERTEX_SHADER" is inserted ...
-------------------------------------*/
static void vfs_printerr(char *nam, int shader)
{
int infolen;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infolen);
if(!infolen) return;
++infolen; // null terminated
int shaderlen;
int trash;
char *lines[10*1024];
int n=0;
glGetShaderiv(shader, GL_SHADER_SOURCE_LENGTH, &shaderlen);
char *shadersource=alloca(shaderlen);
glGetShaderSource(shader, shaderlen, &trash, shadersource);
char *c=shadersource;
while(1){
lines[n++]=c;
while(*c && *c!='\n') ++c;
if(*c=='\n'){
*c++=0;
}
else break;
assert(n<10*1024); // its quite possible that the user reads in some quite large, non-shader files.
}
char *info = alloca(infolen);
glGetShaderInfoLog(shader, infolen, &trash, info);
// cs_printf("Shader compiling error:\n%s\n", info);
info[infolen-1]=0;
c=info;
char errstr[1024];
int sz=0;
while(*c && *c!='(') ++c; // skip the info header
while(*c){
char numstr[8];
while(!isdigit(*c)) ++c;
char *ch=numstr;
while(isdigit(*c)){
*ch++=*c++;
}
*ch=0;
int line=atoi(numstr);
while(!isalnum(*c)) ++c;
char *bgn=c;
while(*c && *c!='\n') ++c;
if(*c=='\n') *c++=0;
cs_printf("%s:%i: %s\n---%s\n", nam, line, lines[line-1], bgn);
}
}
#define VFS_INCLUDE_MAX_RECURSION 256
static int vfs_createshader(char *nam, char **snippets, int count, int shader, int type)
{
if(!shader){
shader = glCreateShader(type);
}
glShaderSource(shader, count, snippets, NULL);
glCompileShader(shader);
int ok;
glGetShaderiv(shader, GL_COMPILE_STATUS, &ok);
if(!ok){
vfs_printerr(nam, shader);
glDeleteShader(shader);
return 0;
}
return shader;
}
static int vfs_createprog(int p, int vs, int fs)
{
int p0=p;
if(!p){
p = glCreateProgram();
}
int error=glGetError();
if (error) {
printf("%s\n", gluErrorString(error));
assert(!error+111*0);
}
glAttachShader(p, vs);
error=glGetError();
if (error) {
printf("p0=%i, p=%i, vs=%i%s\n", p0,p,vs, gluErrorString(error));
assert(!error+222*0);
}
glAttachShader(p, fs);
glLinkProgram(p);
int ok;
glGetProgramiv(p, GL_LINK_STATUS, &ok);
if(!ok){
int len;
glGetProgramiv(p, GL_INFO_LOG_LENGTH, &len);
if(len){
char *info=alloca(len);
int trash;
glGetProgramInfoLog(p, len, &trash, info);
printf("GLSL linking error:\n%s\n", info);
}
glDeleteProgram(p);
return 0;
}
return p;
}
/*-----------------------------------------------------------
Each glProgram is just ONE file -- all vertex and fragment shaders are combined into a single file.
Q: How do we distinguish between vertex and fragment shaders in one file?
I mean, how do we tell whether e.g. float shit(vec2 abc){ // stuff } is vertex or fragment shader?
A: The file is parsed TWICE:
first time with #define GL_VERTEX_SHADER inserted at the beginning of the file;
second time with #define GL_FRAGMENT_SHADER ...
So:
#ifdef VERTEX_SHADER
//
// your vertex shader code here
//
#endif // VERTEX_SHADER
#ifdef FRAGMENT_SHADER
//
// your fragment shader code here
//
#endif // FRAGMENT_SHADER
And a awesome side-effect is that you can place varying variables outside these #ifdef #endif --
so it will be compiled into both vertex and fragment shaders -- which is the case!
You can put any code you want to share between vertex and fragment shader outside the #ifdef #endif pairs.
----------------------------------------------------------*/
// file's last modified time
static time_t fmodtime(const char *nam)
{
struct tm* clock; // create a time structure
struct stat attrib; // create a file attribute structure
stat(nam, &attrib); // get the attributes of afile.txt
return attrib.st_mtime;
}
/*
Shader should be able to be queried by name, so that in-game shader editting will be possible.
*/
/*
If the shader is already loaded, then reload
*/
static void vfs_init()
{
id1k_gen(&G.vfs_idmngr);
}
#define VFS_ID(vptr) ((int)((vptr)-G.vfs))
#define VFS_PTR(id) (G.vfs+(id))
int vfs_load(const char *nam)
{
/////////////////////// Read in & process shader source codes ///////////////////////////////////
// quit if the shader has already been loaded, and hasn't been modified since then
vfs_t *oldp = cvar_getp__(nam, VFS_CKSUM);
vfs_t *p = alloca(sizeof(vfs_t));
// People may misuse cvar_seti() unintentionally.
if(oldp){// the shader under the same name already exists.
time_t t = fmodtime(nam);
if(t == oldp->time) return oldp->id;
p->p = oldp->p;
p->vs = oldp->vs;
p->fs = oldp->fs;
}
else{
p->p = p->vs = p->fs = 0;
p->time = fmodtime(nam); // DEBUGGED: didn't set p->time
}
char *source=loadtext_alloca(nam);
if(!source){ // error -- no such shader file
printf("Error loading shader %s\n", nam);
return -1;
}
// parse #include stuff
typedef struct snippet_s{
struct snippet_s *next;
char *code;
} snippet_t;
snippet_t *head = alloca(sizeof(snippet_t));
head->next = NULL;
head->code = source;
int ninc=0;
int ns=1;
for(snippet_t *s=head; s; s=s->next){
char *c=s->code;
while(c=strstr(c, "#include")){ // skip some "false alarm", such as "ohyeah#include_hoax"
if(ns > VFS_INCLUDE_MAX_RECURSION){ // error -- too many include, maybe indirect self-inclusion?
return;
}
if(c==s->code || isspace(c[-1]) && isspace(c[8])){
*c=0;
c+=9;
break;
}
c+=8;
}
// if source doesn't contain #include, done.
if(!c) continue;
// parse the remaining part of the line.
// if the #include isn't valid, then just ignore it
// skip white
while(isspace(*c)){
if(*c=='\n'){
if(c[-1] != '\\'){ // error -- #include should be one-line
return -1;
}
}
}
if(*c != '\"'){ // error -- #include invalid stuff (not included in "")
return -1;
}
char *begin=++c;
while(*c!='\"' || c[-1]=='\\'){
if(!*c){ // error -- unexpected EOF
}
if(*c == '\n'){
if(c[-1] != '\\'){ // error -- unexpected newline
}
}
++c;
}
*c=0; // " -> 0
// begin of snippet3
char *code3 = c+1;
// char *begin stores the name of the file to be included
if(!strcmp(begin, nam)){ // error -- self-inclusion
return -1;
}
char *code2 = loadtext_alloca(begin);
if(!code2){ // error -- cannot find the file
return -1;
}
snippet_t *s2 = alloca(sizeof(snippet_t)*2);
snippet_t *s3 = s2+1;
s2->code = code2;
s3->code = code3;
s2->next = s3;
s3->next = s->next;
s->next = s2;
ns+=2;
}
char **snippets = alloca(ns*sizeof(char*)+1);
snippet_t *s=head;
for(int i=1; i<=ns; i++, s=s->next){
snippets[i] = s->code;
}
// #include found
// Source code between and after #include become two code snippets (before=snippet1, after=snippet3)
// The included file becomes the third code snippet (include=snippet2)
// recursively call vfs_include_r() on the snippet2 and snippet3
// tail recursion
/////////////////////// Analysis the shaders -- how many attributes, uniforms ... ////////////////////////////////
snippets[0] = "#define VERTEX_SHADER\n";
p->vs = vfs_createshader(nam, snippets, ns+1, p->vs, GL_VERTEX_SHADER);
snippets[0] = "#define FRAGMENT_SHADER\n";
p->fs = vfs_createshader(nam, snippets, ns+1, p->fs, GL_FRAGMENT_SHADER);
p->p = vfs_createprog(p->p, p->vs, p->fs);
if(!p->p){
return NULL;
}
//---------------------- How many render targets? -----------------------
{
int sz;
glGetShaderiv(p->fs, GL_SHADER_SOURCE_LENGTH, &sz);
char mem[sz];
glGetShaderSource(p->fs, sz, NULL, mem);
mem[sz-1]=0;
char *code=strstr(mem, "gl_Frag");
if (strstr(code, "gl_FragDepth")) { // depth render target
p->nrts=1;
p->depthrt=1;
}
else {
p->nrts=0;
p->depthrt=0;
}
if (strstr(code, "gl_FragColor")) {
++p->nrts;
}
else {
char *c=code;
int n=-1;
while (1) {
c=strstr(c, "gl_FragData");
if (!c) break;
c+=11;
while (isspace(*c)) ++c;
assert(*c);
int i=atoi(c);
if (i>n) n=i;
}
// assert(n!=-1);
p->nrts+=n+1;
}
}
char buf[256];
int len, type;
//----------------------- attributes ---------------------------
int na;
glGetProgramiv(p->p, GL_ACTIVE_ATTRIBUTES, &na);
p->amem = malloc(na + na*sizeof(short)*3);
p->dim = p->amem;
p->acount = p->dim + na;
p->ofs = p->acount+na;
p->stride = p->ofs+na;
p->narray = 0;
int realna=0;
int size;
int totalfloat=0;
int acount=0;
for(int i=0; i<na; i+=acount) {
glGetActiveAttrib(p->p, i, 256, &len, &size, &type, buf);
int j=glGetAttribLocation(p->p, buf); // shit! i2 may be different from i!
if(j==-1) continue; // TODO: error handling
// skip other columns of matrix and array elements
switch(type){
case GL_FLOAT:
p->dim[j] = 1;
p->acount[j] = size;
break;
case GL_FLOAT_VEC2:
case GL_FLOAT_VEC3:
case GL_FLOAT_VEC4:
p->dim[j] = type-GL_FLOAT_VEC2+2;
p->acount[j] = size;
break;
case GL_FLOAT_MAT2:
case GL_FLOAT_MAT3:
case GL_FLOAT_MAT4:
p->dim[j] = type-GL_FLOAT_MAT2+2;
p->acount[j] = size * p->dim[j];
break;
case GL_FLOAT_MAT2x3:
case GL_FLOAT_MAT2x4:
p->dim[j] = type-GL_FLOAT_MAT2x3+3;
p->acount[j] = size * 2;
break;
case GL_FLOAT_MAT3x2:
case GL_FLOAT_MAT3x4:
p->dim[j] = (type-GL_FLOAT_MAT3x2+1)<<1;
p->acount[j] = size * 3;
break;
case GL_FLOAT_MAT4x2:
case GL_FLOAT_MAT4x3:
p->dim[j] = type-GL_FLOAT_MAT4x2+2;
p->acount[j] = size * 4;
break;
}
totalfloat += p->dim[j]*p->acount[j];
p->narray += p->acount[j];
acount = p->acount[j];
}
p->nbytes = totalfloat * sizeof(float);
//-------------- uniforms ----------------------------
int nu;
glGetProgramiv(p->p, GL_ACTIVE_UNIFORMS, &nu);
// find all samplers
p->umem = malloc(nu + nu + nu*sizeof(PFNGLUNIFORM1FVPROC) + nu*sizeof(PFNGLUNIFORMMATRIX2FVPROC));
p->multitex = p->umem;
p->ucount = p->umem + nu;
p->vectorfunc = p->ucount + nu;
p->matrixfunc = p->vectorfunc + nu;
memset(p->multitex, -1, nu);
int ntex=0;
for(int i=0; i<nu; i++){
glGetActiveUniform(p->p, i, 256, &len, p->ucount+i, &type, buf);
int j=glGetUniformLocation(p->p, buf);
if(j==-1) continue;
if(type>=GL_SAMPLER_1D && type<=GL_SAMPLER_2D_SHADOW){
p->multitex[i] = ntex++;
p->vectorfunc[i] = glUniform1fv;
p->matrixfunc[i] = NULL;
}
else{
switch(type){
case GL_FLOAT:
p->vectorfunc[i] = glUniform1fv;
p->matrixfunc[i] = NULL;
break;
case GL_FLOAT_VEC2:
p->vectorfunc[i] = glUniform2fv;
p->matrixfunc[i] = NULL;
break;
case GL_FLOAT_VEC3:
p->vectorfunc[i] = glUniform3fv;
p->matrixfunc[i] = NULL;
break;
case GL_FLOAT_VEC4:
p->vectorfunc[i] = glUniform4fv;
p->matrixfunc[i] = NULL;
break;
case GL_FLOAT_MAT2:
p->vectorfunc[i] = NULL;
p->matrixfunc[i] = glUniformMatrix2fv;
break;
case GL_FLOAT_MAT3:
p->vectorfunc[i] = NULL;
p->matrixfunc[i] = glUniformMatrix3fv;
break;
case GL_FLOAT_MAT4:
p->vectorfunc[i] = NULL;
p->matrixfunc[i] = glUniformMatrix4fv;
break;
case GL_FLOAT_MAT2x3:
p->vectorfunc[i] = NULL;
p->matrixfunc[i] = glUniformMatrix2x3fv;
break;
case GL_FLOAT_MAT2x4:
p->vectorfunc[i] = NULL;
p->matrixfunc[i] = glUniformMatrix2x4fv;
break;
case GL_FLOAT_MAT3x2:
p->vectorfunc[i] = NULL;
p->matrixfunc[i] = glUniformMatrix3x2fv;
break;
case GL_FLOAT_MAT3x4:
p->vectorfunc[i] = NULL;
p->matrixfunc[i] = glUniformMatrix3x4fv;
break;
case GL_FLOAT_MAT4x2:
p->vectorfunc[i] = NULL;
p->matrixfunc[i] = glUniformMatrix4x2fv;
break;
case GL_FLOAT_MAT4x3:
p->vectorfunc[i] = NULL;
p->matrixfunc[i] = glUniformMatrix4x3fv;
break;
}
}
}
p->ntex=ntex;
// finally, store it in svar
if(oldp){
return oldp->id;
}
else{
int id=id1k_alloc(G.vfs_idmngr);
if(id==-1){ // TODO:
}
if(!G.vfs[id]) G.vfs[id] = malloc(sizeof(vfs_t));
cvar_setp__(nam, G.vfs[id], VFS_CKSUM);
p->id = id;
*G.vfs[id] = *p;
return id;
}
}
static int vfs_isprog(int id)
{
return id1k_allocated(G.vfs_idmngr, id);
}
#define BUFFER_OFFSET(i) ((char *)NULL + (i))
/*------------------------------------------
Use OpenGL shader program
-----------------------------------------*/
void vfs_use(int id)
{
if(id<0){
if(G.vfs_cur){
glUseProgram(0);
for(int i=0; i<G.vfs_cur->narray; i++)
glDisableVertexAttribArray(i);
G.vfs_cur = NULL;
}
return;
}
if(!vfs_isprog(id)){ // error
cs_printf("Shader error\n");
return;
}
vfs_t *p = G.vfs[id];
if (p==G.vfs_cur) return;
glUseProgram(p->p);
// disable unused/enable useful vertex attribs
vfs_t *old = G.vfs_cur;
if(!old){
for(int i=0; i<p->narray; i++)
glEnableVertexAttribArray(i);
}
else{
if(old->narray > p->narray) // disable unused attrib arrays
for(int i=old->narray-1; i>= p->narray; i--)
glDisableVertexAttribArray(i);
else if (old->narray < p->narray)
for(int i=old->narray; i<p->narray; i++)
glEnableVertexAttribArray(i);
}
G.vfs_cur = p;
}
void vfs_reload(const char *nam)
{
vfs_t *p = cvar_getp__(nam, VFS_CKSUM);
if(!p) return;
vfs_load(nam);
}
/*--------------------------------------
GLSL uniforms
-------------------------------------*/
/*---------------------------------------
Handy uniform setup routines. Alternatively, you can use unifv() instead.
--------------------------------------*/
void uni1f(const char *nam, float v0)
{
if (!G.vfs_cur->p) return;
int loc = glGetUniformLocation(G.vfs_cur->p, nam);
glUniform1f(loc, v0);
}
void uni2f(const char *nam, float v0, float v1)
{
if (!G.vfs_cur->p) return;
int loc = glGetUniformLocation(G.vfs_cur->p, nam);
glUniform2f(loc, v0, v1);
}
void uni3f(const char *nam, float v0, float v1, float v2)
{
if (!G.vfs_cur->p) return;
int loc = glGetUniformLocation(G.vfs_cur->p, nam);
glUniform3f(loc, v0, v1, v2);
}
void uni4f(const char *nam, float v0, float v1, float v2, float v3)
{
if (!G.vfs_cur->p) return;
int loc = glGetUniformLocation(G.vfs_cur->p, nam);
glUniform4f(loc, v0, v1, v2, v3);
}
/*------------------------------------------------
Can process all kind of uniforms -- vector, array of vector, matrix, array of matrix, without specifing data types and sizes.
All info are parsed at shader loading time.
-----------------------------------------------*/
void unifv(const char *nam, const float *dat)
{
if (!dat) return;
vfs_t *p = G.vfs_cur;
if (!p) return;
int i = glGetUniformLocation(p->p, nam);
if(p->vectorfunc[i])
p->vectorfunc[i](i, p->ucount[i], dat);
else
p->matrixfunc[i](i, p->ucount[i], 0, dat);
}
/*-----------------------------------------------
You don't have to specify which channel the texture is bound to -- the info is parsed at shader loading time.
----------------------------------------------*/
void samp2d(const char *nam, uint tex)
{
vfs_t *p = G.vfs_cur;
if (!p) return;
int i = glGetUniformLocation(p->p, nam);
if(i<0){
// cs_printf("Cannot find sampler2D \"%s\"\n", nam);
return;
}
glUniform1i(i, p->multitex[i]);
glActiveTexture(GL_TEXTURE0 + p->multitex[i]);
glBindTexture(GL_TEXTURE_2D, tex);
glActiveTexture(GL_TEXTURE0);
}
/*
An object can be:
On disk; -- in-core = 0
In RAM; -- in-core = 1; cached = 0
In VRAM; -- cached = 1
Object can be modified only in RAM. If it's modified, its instance on disk and in VRAM should be updated.
Hash table should be used to manage objects.
Object should be stored in binary format on disk. Some tool should be used to translate between binary and text.
*/
/*--------------------------------------------------
Several vertex buffers are allocated at startup, and then controlled by a binary buddy system.
Each object has a timestamp. Everytime the object is updated (deformed/translated/rotated etc.), the timestamp is updated too.
If an object isn't used, its VB is released (put into something like "trash bin"). When the object is used again and the trash bin
isn't clearred, then the VB can be "recoverred".
Multi-stream attributes can be stored in the same or different VBs. Just let the engine determine automatically.
-------------------------------------------------*/
/*-----------------------------------------------------------------------
Vertex buffer
The minimum block size is 2k. Total vertex mem is 64m == 32k blocks
Each vertex buffer object is 4m => at most 16 VBOs.
Each VBO 2k blocks.
=> address / 2k = VBO index
(address % 2k) * 2k = VBO offset
------------------------------------------------------------
Element buffer
EB is managed by another buddy system, too.
You have to store the number of elements in each EB
4m element buffer is enough.
The minimum element buffer can be 128 bytes => 4m == 32k *128
-----------------------------------------------------------------------*/
#define BLKS_PER_VBO (2*1024)
#define VB_BLK_SIZE (2*1024)
#define EB_BLK_SIZE 128
#define MAX_NUM_BLKS (32*1024)
#define VBO_SIZE (4*1024*1024)
#define EBO_SIZE (4*1024*1024)
static void vb_init()
{
// vertex buffer
bd_gen(&G.vb_bdsys, 1, MAX_NUM_BLKS); // the memory "allocated" by the bdsys is useless; only the "address" is useful.
glGenBuffers(1, G.vb_vbo);
glBindBuffer(GL_ARRAY_BUFFER, G.vb_vbo[0]);
glBufferData(GL_ARRAY_BUFFER, VBO_SIZE, NULL, GL_STATIC_DRAW);
G.vb_nvbos = 1;
// element buffer
bd_gen(&G.eb_bdsys, 1, MAX_NUM_BLKS);
glGenBuffers(1, &G.eb_ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, G.eb_ebo);
glBufferData(GL_ARRAY_BUFFER, EBO_SIZE, NULL, GL_STATIC_DRAW);
}
static void vb_shutdown()
{
glDeleteBuffers(G.vb_nvbos, G.vb_vbo);
glDeleteBuffers(1, &G.eb_ebo);
bd_del(&G.vb_bdsys);
bd_del(&G.eb_bdsys);
}
/*-------------------------------------------
Return: some kind of "pointer", can only be used with vb_*() functions.
-------------------------------------------*/
int vb_alloc(int n, int sz, void *dat)
{
int realsize;
int size = n*sz/VB_BLK_SIZE;
if(n*sz%VB_BLK_SIZE) ++size;
int addr = bd_alloc(G.vb_bdsys, size, &realsize);
int vb = addr / BLKS_PER_VBO;
if(vb>=G.vb_nvbos){
glGenBuffers(1, G.vb_vbo+vb);
glBindBuffer(GL_ARRAY_BUFFER, G.vb_vbo[vb]);
glBufferData(GL_ARRAY_BUFFER, VBO_SIZE, GL_STATIC_DRAW, dat);
G.vb_nvbos = vb;
}
else {
glBindBuffer(GL_ARRAY_BUFFER, G.vb_vbo[vb]);
int ofs = addr % BLKS_PER_VBO * VB_BLK_SIZE;
glBufferSubData(GL_ARRAY_BUFFER, ofs, n*sz, dat);
}
// G.vb_numverts[addr] = n;
G.vb_cap[addr]=realsize*VB_BLK_SIZE;
G.vb_nv[addr]=n;
return addr;
}
/*-------------------------------
To allocate a element buffer,
Element buffers don't have something like glElementArrayPointer, but they source
their indices from that buffer object, using their <indices>
parameters as offsets into the buffer object
------------------------------*/
int eb_alloc(int nelems, int elemsz, void *dat)
{
int realsize;
int addr = bd_alloc(G.eb_bdsys, nelems * elemsz, &realsize);
G.eb_numelements[addr] = nelems;
}
void vb_free(int vb)
{
bd_free(G.vb_bdsys, vb);
}
void eb_free(int eb)
{
bd_free(G.eb_bdsys, eb);
}
void vb_update(int addr, int n, int sz, void *dat)
{
int vb=addr / BLKS_PER_VBO;
int ofs= addr % BLKS_PER_VBO * VB_BLK_SIZE;
glBindBuffer(GL_ARRAY_BUFFER, G.vb_vbo[vb]);
glBufferSubData(GL_ARRAY_BUFFER, ofs, n*sz, dat);
G.vb_nv[addr]=n;
}
void eb_update(int addr, int nbytes, void *dat)
{
int ofs = addr * EB_BLK_SIZE;
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, G.eb_ebo);
glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, ofs, nbytes, dat);
}
int vb_getcap(int addr)
{
return G.vb_cap[addr];
}
/*----------------------------------------
An object may have multiple streams.
Multiple VBOs, each VBO may have multiple interleaved attributes.
rend("vertex {T B N} texcoord", vert, TBN, texcoord);
Group interleaved attribs with {}.
Grammar:
<vb_desc> -> <attrib> {<vb_desc>} |
<attrib_group> {<vb_desc>} |
$
<attrib> -> identifier
<attrib_group> -> "{" <attrib_list> "}"
<attrib_list> -> <attrib_interleaved> {<attrib_list>}
<attrib_interleaved> -> identifier
---------------------------------------*/
static void ps_vb_desc(const char *desc)
{
char *c=desc;
char buf[256];
vfs_t *p = G.vfs_cur;
if(!p) return;
memset(p->ofs, 0, p->narray*sizeof(p->ofs[0]));
memset(p->stride, 0, p->narray*sizeof(p->stride[0]));
int nstreams=0;
int *attr = G.vb_streams;
while(*c){
if(isspace(*c)){
++c;
continue;
}
if(*c == '{'){
++c;
int ns=0;
short *strides[256];
int ofs=0;
G.vb_stream_nattr[nstreams] = 0;
while(*c){
if(isspace(*c)){
++c;
continue;
}
if(*c=='}') break;
char *b=buf;
while(*c=='_' || isalnum(*c)) *b++=*c++;
*b = '\0';
int a = glGetAttribLocation(p->p, buf);
if(a==-1){ // TODO: error processing
}
p->ofs[a] = ofs;
ofs += p->dim[a]*p->acount[a]*sizeof(float);
strides[ns++] = p->stride + a;
G.vb_stream_nattr[nstreams]++;
*attr++ = a;
}
++nstreams;
if(ns>1){
for(int i=0; i<ns; i++)
*strides[i] = ofs;
}
++c; // '}'
continue;
}
while(*c){
if(isspace(*c++)) continue;
char *b=buf;
while(*c=='_' || isalnum(*c)) *b++=*c++;
*b = '\0';
int a = glGetAttribLocation(p->p, b);
p->ofs[a] = p->stride[0] = 0;
G.vb_stream_nattr[nstreams++]++;
*attr++ = a;
}
}
G.vb_nstreams = nstreams;
}
void vb_setnv(int addr, int nv)
{
// G.vb_numverts[addr]=nv;
G.vb_nv[addr]=nv;
}
/*
"fmt" is vertex attribute description
*/
void rend(const char *fmt, int eb, ...)
{
va_list va;
if((G.vb_curvfs != G.vfs_cur || (G.vb_curfmt != fmt && strcmp(G.vb_curfmt, fmt)) ))
{
G.vb_curvfs = G.vfs_cur;
G.vb_curfmt = fmt;
ps_vb_desc(fmt);
}
vfs_t *p = G.vfs_cur;
int *attr=G.vb_streams;
int addr;
va_start(va, eb);
for(int s=0; s<G.vb_nstreams; s++){
addr = va_arg(va, int);
int vb = addr / BLKS_PER_VBO;
int ofs = addr % BLKS_PER_VBO * VB_BLK_SIZE;
int vbo=G.vb_vbo[vb];
if(vbo != G.vbo_cur){
G.vbo_cur=vbo;
glBindBuffer(GL_ARRAY_BUFFER, G.vb_vbo[vb]);
}
for(int i=0; i<G.vb_stream_nattr[s]; i++)
{
int a = *attr++;
for(int j=0; j<p->acount[a]; j++){
glVertexAttribPointer(a+j, p->dim[a], GL_FLOAT, 0, p->stride[a], ofs+p->ofs[a]);
}
}
}
va_end(va);
int nv = G.vb_nv[addr]; //G.vb_numverts[addr];
if(eb!=-1){
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, G.eb_ebo);
int type = nv<=0xff ? GL_UNSIGNED_BYTE : nv<=0xffff ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT; // TODO
int ofs = eb * EB_BLK_SIZE;
glDrawRangeElements(GL_TRIANGLES, 0, nv-1, G.eb_numelements[eb], type, ofs);
}
else{ // you can render without element buffer.
glDrawArrays(GL_TRIANGLES, 0, nv);
}
++G.rnd_counter;
}
void rendq(const char *fmt, int eb, ...)
{
va_list va;
if((G.vb_curvfs != G.vfs_cur || (G.vb_curfmt != fmt && strcmp(G.vb_curfmt, fmt)) ))
{
G.vb_curvfs = G.vfs_cur;
G.vb_curfmt = fmt;
ps_vb_desc(fmt);
}
vfs_t *p = G.vfs_cur;
int *attr=G.vb_streams;
int addr;
va_start(va, eb);
for(int s=0; s<G.vb_nstreams; s++){
addr = va_arg(va, int);
int vb = addr / BLKS_PER_VBO;
int ofs = addr % BLKS_PER_VBO * VB_BLK_SIZE;
int vbo=G.vb_vbo[vb];
if(vbo != G.vbo_cur){
G.vbo_cur=vbo;
glBindBuffer(GL_ARRAY_BUFFER, vbo);
}
for(int i=0; i<G.vb_stream_nattr[s]; i++)
{
int a = *attr++;
for(int j=0; j<p->acount[a]; j++){
glVertexAttribPointer(a+j, p->dim[a], GL_FLOAT, 0, p->stride[a], ofs+p->ofs[a]); // DEBUGGED: p->ofs[a] => ofs+p->ofs[a]
}
}
}
va_end(va);
int nv = G.vb_nv[addr]; //G.vb_numverts[addr];
if(eb!=-1){
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, G.eb_ebo);
int type = nv<=0xff ? GL_UNSIGNED_BYTE : nv<=0xffff ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT; // TODO
int ofs = eb * EB_BLK_SIZE;
glDrawRangeElements(GL_QUADS, 0, nv-1, G.eb_numelements[eb], type, ofs);
}
else{ // you can render without element buffer.
glDrawArrays(GL_QUADS, 0, nv);
}
++G.rnd_counter;
}
/*
Immediate mode
No multi-streams: just interleaved (four vertices)
=> The vertex attrib description is much simpler:
just write down the names of the attributes, in the same order as in the vertex struct
rendrect("co texco", co[4], texco[4])
co[]={x1,y1,x2,y2}
*/
void rendrect(const char *desc, ...)
{
va_list va;
vfs_t *p=G.vfs_cur;
if (!p) return;
// parse vertex description
char *c=desc;
char buf[128];
int attr[128];
int na=0;
int stride=0;
float *dat[128];
va_start(va,desc);
while(1){
// skip space
while(isspace(*c)) ++c;
// *c could be 0
if(!*c) break;
// now *c != 0 and isn't space neither
char *b=buf;
do{
*b++=*c++;
}while(isalnum(*c) || *c=='_');
*b=0;
int a=glGetAttribLocation(p->p, buf);
if(a==-1){ // error
}
attr[na]=a;
dat[na++]=va_arg(va,float*);
stride+=p->dim[a]*p->acount[a]*sizeof(float);
}
va_end(va);
glBindBuffer(GL_ARRAY_BUFFER,0);
for(int i=0; i<na; i++){
int a=attr[i];
int dim=p->dim[a];
int sz=4*dim*p->acount[a]*sizeof(float);
float *vert=alloca(sz);
memset(vert,0,sz);
float *v=vert;
float *d=dat[i];
for(int j=0; j<p->acount[a]; j++){
float *p=v;
v[0]=d[0];
v[1]=d[1];
v+=dim;
v[0]=d[2];
v[1]=d[1];
v+=dim;
v[0]=d[2];
v[1]=d[3];
v+=dim;
v[0]=d[0];
v[1]=d[3];
v+=dim;
glVertexAttribPointer(a+j, dim, GL_FLOAT, 0, 0, p);
d+=4;
}
}
// plain vertex array (not VBO)
glDrawArrays(GL_QUADS, 0, 4);
}
uint rnd_getcounter()
{
return G.rnd_counter;
}
/*------------------------------------------
Parse render target description
Grammar:
<rtdesc> -> <type>{<rtdesc>} // no white space between types
<type> -> t | d | D | S | x | X | y | Y | z | Z
T|t TEXTURE_2D
D DEPTH_COMPONENT16, texture
d DEPTH_COMPONENT24, renderbuffer
S|s STENCIL_INDEX, renderbuffer
x|y|z TEXTURE_CUBE_MAP_NEGATIVE_X|Y|Z
X|Y|Z TEXTURE_CUBE_MAP_POSITIVE_X|Y|Z
-----------------------------------------*/
static void CHECK_FRAMEBUFFER_STATUS(){
GLenum status;
status=(GLenum)glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
switch(status) {
case GL_FRAMEBUFFER_COMPLETE_EXT:
// cs_printf("Fine!\n");
return;
case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT:
cs_printf("Framebuffer incomplete,incomplete attachment\n");
return;
case GL_FRAMEBUFFER_UNSUPPORTED_EXT:
cs_printf("Unsupported framebuffer format\n");
return;
case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT:
cs_printf("Framebuffer incomplete,missing attachment\n");
return;
case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT:
{
int tex=-1;
glGetFramebufferAttachmentParameterivEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT,
GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT, &tex);
cs_printf("Framebuffer incomplete,attached images must have same dimensions\n");
cs_printf("depth attachment=%i",tex);
}
return;
case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT:
cs_printf("Framebuffer incomplete,attached images must have same format\n");
return;
case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT:
cs_printf("Framebuffer incomplete,missing draw buffer\n");
return;
case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT:
cs_printf("Framebuffer incomplete,missing read buffer\n");
return;
}
return;
}
/*------------------------------------------
Use render target
e.g.
rnd_tg("ttds", nam1, nam2, nam3, nam4);
rnd_tg(0); // Render to frame buffer
rnd_tg("td", color, depth);
-----------------------------------------*/
int frm=0;
void rnd_tg(const char *format, ...)
{
va_list ap;
if(!format) { // "Real" frame buffer
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT,0);
return;
}
if(!G.rndtg_fbo){
glGenFramebuffersEXT(1, &G.rndtg_fbo);
}
#if 0
// TESTING
glBindTexture(GL_TEXTURE_2D, 0);
// ~TESTING
#endif
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, G.rndtg_fbo);
int n=strlen(format);
int clrattach=GL_COLOR_ATTACHMENT0_EXT;
int depthattach=0;
va_start(ap, format);
for(int i=0; i<n; i++){
int rndtg = va_arg(ap, int);
switch(format[i]){
case 't':
case 'T':
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,
clrattach++, GL_TEXTURE_2D, rndtg, 0);
assert(!glGetError()+0);
break;
case 'd':
case 'D':
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,
GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, rndtg, 0); // DEBUGGED: GL_DEPTH_COMPONENT=>GL_TEXTURE_2D
assert(!glGetError()+00);
depthattach=1;
break;
case 's':
case 'S':
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,
GL_STENCIL_ATTACHMENT_EXT,GL_TEXTURE_2D, rndtg, 0);
break;
default:
assert(0);
break;
}
}
va_end(ap);
// MRT
int nrt=clrattach-GL_COLOR_ATTACHMENT0_EXT;
#if 1
if (G.rndtg_nca>nrt) {
for (int i=nrt; i<G.rndtg_nca; ++i ){
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,
GL_COLOR_ATTACHMENT0_EXT+i, GL_TEXTURE_2D, 0,0);
}
}
G.rndtg_nca=nrt;
if (!depthattach){
if (G.rndtg_nda) {
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,
GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0); // DEBUGGED: GL_DEPTH_COMPONENT=>GL_TEXTURE_2D
G.rndtg_nda=0;
}
}
else {
G.rndtg_nda=1;
}
#endif
if(nrt==1){
glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
glReadBuffer(GL_COLOR_ATTACHMENT0_EXT);
}
else if(nrt>1){
uint *mrt=alloca(sizeof(uint)*nrt);
for(int i=0; i<nrt; i++){
mrt[i]=GL_COLOR_ATTACHMENT0_EXT+i;
}
glDrawBuffers(nrt, mrt);
}
else{ // No color attachment, only render to depth buffer
if(format[0]=='d' || format[0]=='D'){
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
}
}
CHECK_FRAMEBUFFER_STATUS();
}
static void rnd_tgn(const char *format, uint *rndtg)
{
if(!format) { // "Real" frame buffer
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT,0);
return;
}
if(!G.rndtg_fbo){
glGenFramebuffersEXT(1, &G.rndtg_fbo);
}
#if 0
// TESTING
glBindTexture(GL_TEXTURE_2D, 0);
// ~TESTING
#endif
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, G.rndtg_fbo);
int n=strlen(format);
int clrattach=GL_COLOR_ATTACHMENT0_EXT;
int depthattach=0;
for(int i=0; i<n; i++){
switch(format[i]){
case 't':
case 'T':
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,
clrattach++, GL_TEXTURE_2D, rndtg[i], 0);
assert(!glGetError()+1*0);
break;
case 'd':
case 'D':
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,
GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, rndtg[i], 0); // DEBUGGED: GL_DEPTH_COMPONENT=>GL_TEXTURE_2D
depthattach=1;
assert(!glGetError()+11*0);
break;
case 's':
case 'S':
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,
GL_STENCIL_ATTACHMENT_EXT,GL_TEXTURE_2D, rndtg[i], 0);
assert(!glGetError()+111*0);
break;
default:
assert(0);
break;
}
}
// MRT
int nrt=clrattach-GL_COLOR_ATTACHMENT0_EXT;
#if 1
if (G.rndtg_nca>nrt) {
for (int i=nrt; i<G.rndtg_nca; ++i ){
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,
GL_COLOR_ATTACHMENT0_EXT+i, GL_TEXTURE_2D, 0,0);
}
}
G.rndtg_nca=nrt;
if (!depthattach){
if (G.rndtg_nda) {
glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT,
GL_DEPTH_ATTACHMENT_EXT, GL_TEXTURE_2D, 0, 0); // DEBUGGED: GL_DEPTH_COMPONENT=>GL_TEXTURE_2D
G.rndtg_nda=0;
}
}
else {
G.rndtg_nda=1;
}
#endif
if(nrt==1){
glDrawBuffer(GL_COLOR_ATTACHMENT0_EXT);
glReadBuffer(GL_COLOR_ATTACHMENT0_EXT);
}
else if(nrt>1){
uint *mrt=alloca(sizeof(uint)*nrt);
for(int i=0; i<nrt; i++){
mrt[i]=GL_COLOR_ATTACHMENT0_EXT+i;
}
glDrawBuffers(nrt, mrt);
}
else{ // No color attachment, only render to depth buffer
if(format[0]=='d' || format[0]=='D'){
glDrawBuffer(GL_NONE);
glReadBuffer(GL_NONE);
}
}
CHECK_FRAMEBUFFER_STATUS();
}
/*------------------------------------
Common texture filters:
mipminmag[0][1][1]
Usage:
uint tex=tex3b(512,512,000,data);
-----------------------------------*/
static void fltrtyp_nomip(int f, int *minf, int *magf)
{
static int init=0;
static char m[212]={[000]=0, [001]=1, [010]=2, [011]=3,
[100]=0, [101]=1, [110]=2, [111]=3,
[200]=0, [201]=1, [210]=2, [211]=3}; // mipminmag[]
static int minfltrtb[6]={GL_NEAREST,
GL_LINEAR,
GL_NEAREST_MIPMAP_NEAREST,
GL_LINEAR_MIPMAP_NEAREST,
GL_NEAREST_MIPMAP_LINEAR,
GL_LINEAR_MIPMAP_LINEAR };
static int magfltrtb[2]={GL_NEAREST, GL_LINEAR};
int typ=m[f % 212]; // So that m[] won't overflow. And all unknown filter types are treated
*minf=minfltrtb[typ/2];
*magf=magfltrtb[typ%2];
}
static void fltrtyp(int f, int *minf, int *magf)
{
static int init=0;
static char m[212]={[000]=0, [001]=1, [010]=2, [011]=3,
[100]=4, [101]=5, [110]=6, [111]=7,
[200]=8, [201]=9, [210]=10, [211]=11}; // mipminmag[]
static int minfltrtb[6]={GL_NEAREST,
GL_LINEAR,
GL_NEAREST_MIPMAP_NEAREST,
GL_LINEAR_MIPMAP_NEAREST,
GL_NEAREST_MIPMAP_LINEAR,
GL_LINEAR_MIPMAP_LINEAR };
static int magfltrtb[2]={GL_NEAREST, GL_LINEAR};
int typ=m[f % 212];
*minf=minfltrtb[typ/2];
*magf=magfltrtb[typ%2];
}
uint tex1b(int w, int h, int filter, void *data)
{
uint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
#if 0
glTexImage2D(GL_TEXTURE_2D, 0/*level*/, GL_LUMINANCE8_ALPHA8, w, h, 0/*border*/,
GL_LUMINANCE_ALPHA,GL_UNSIGNED_BYTE, data);
#endif
glTexImage2D(GL_TEXTURE_2D, 0/*level*/, GL_ALPHA8, w, h, 0/*border*/,
GL_ALPHA, GL_UNSIGNED_BYTE, data);
int minf,magf;
fltrtyp(filter, &minf, &magf);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minf);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magf);
return tex;
}
uint tex3b(int w, int h, int filter, void *data)
{
uint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0/*level*/, GL_RGB8, w, h, 0/*border*/,
GL_RGB, GL_UNSIGNED_BYTE, data);
int minf,magf;
fltrtyp(filter, &minf, &magf);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minf);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magf);
return tex;
}
uint tex4b(int w, int h, int filter, void *data)
{
uint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_RGB,
GL_UNSIGNED_BYTE, data);
int minf,magf;
fltrtyp(filter, &minf, &magf);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minf);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magf);
return tex;
}
uint tex1h(int w, int h, int filter, void *data)
{
uint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA16F_ARB, w, h, 0, GL_ALPHA,
GL_FLOAT, data);
int minf, magf;
fltrtyp_nomip(filter, &minf, &magf);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minf);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magf);
return tex;
}
uint tex3h(int w, int h, int filter, void *data)
{
uint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F_ARB, w,h,0, GL_RGB,
GL_FLOAT, data);
int minf, magf;
fltrtyp_nomip(filter, &minf, &magf);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minf);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magf);
return tex;
}
uint tex4h(int w, int h, int filter, void *data)
{
uint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F_ARB, w,h,0, GL_RGBA,
GL_FLOAT, data);
int minf, magf;
fltrtyp_nomip(filter, &minf, &magf);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minf);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magf);
return tex;
}
uint tex1f(int w, int h, int filter, void *data)
{
uint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA32F_ARB, w, h, 0, GL_ALPHA,
GL_FLOAT, data);
int minf, magf;
fltrtyp_nomip(filter, &minf, &magf);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minf);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magf);
return tex;
}
uint tex3f(int w, int h, int filter, void *data)
{
uint tex;
glGenTextures(1, &tex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F_ARB, w,h,0, GL_RGB,
GL_FLOAT, data);
int minf, magf;
fltrtyp_nomip(filter, &minf, &magf);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minf);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magf);
return tex;
}
uint tex3bdxt1(int w, int h, int filter, void *data)
{
uint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
if (data) {
int sz=8*(w/4)*(h/4);
glCompressedTexImage2D(GL_TEXTURE_2D, 0,
GL_COMPRESSED_RGB_S3TC_DXT1_EXT,
w, h, 0, sz, data);
}
else { // DEBUGGED: should use glTexImage2D() to reserve space for texture
glTexImage2D(GL_TEXTURE_2D, 0,
GL_COMPRESSED_RGB_S3TC_DXT1_EXT,
w,h,0,GL_RGB,GL_UNSIGNED_BYTE, NULL);
}
int minf, magf;
fltrtyp_nomip(filter, &minf, &magf);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minf);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magf);
return tex;
}
uint tex4f(int w, int h, int filter, void *data)
{
uint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F_ARB, w,h,0, GL_RGBA,
GL_FLOAT, data);
int minf, magf;
fltrtyp_nomip(filter, &minf, &magf);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minf);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magf);
return tex;
}
uint dtex(int w, int h, int filter, void *data)
{
uint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, w,h,0,
GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, data);
int minf, magf;
fltrtyp_nomip(filter, &minf, &magf);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minf);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magf);
return tex;
}
uint dtex2b(int w, int h, int filter, void *data)
{
uint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, w,h,0,
GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, data);
int minf, magf;
fltrtyp_nomip(filter, &minf, &magf);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minf);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magf);
return tex;
}
#if 0
uint dtex3b(int w, int h, int filter, void *data)
{
uint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, w,h,0,
GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, data);
int minf, magf;
fltrtyp_nomip(filter, &minf, &magf);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minf);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magf);
return tex;
}
#endif
uint dtex3b(int w, int h, int filter, void *data)
{
uint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT24, w,h,0,
GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, data);
// GL_LUMINANCE, GL_FLOAT, data);
int minf, magf;
fltrtyp_nomip(filter, &minf, &magf);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minf);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magf);
#if 0
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_NONE);
glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_LUMINANCE);
#endif
return tex;
}
uint dstex(int w, int h, int filter, void *data)
{
uint tex;
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8_EXT, w,h,0,
GL_DEPTH_STENCIL_EXT, GL_UNSIGNED_INT_24_8_EXT, data);
int minf, magf;
fltrtyp_nomip(filter, &minf, &magf);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minf);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magf);
return tex;
}
const uint (*texfunc[RT_MAX])(int,int,int,void*)={[RT_4B]=tex4b, [RT_4H]=tex4h, [RT_DEPTH]=dtex};
void rt_init()
{
int nlevels=lg2(min(G.screenw,G.screenh))+1;
for (int level=0; level<nlevels; ++level) {
int w=G.screenw>>level;
int h=G.screenh>>level;
const int nrts[RT_MAX]={[RT_4B]=4, [RT_4H]=2, [RT_DEPTH]=2};
for (int type=0; type<RT_MAX; ++type) {
int bit=1;
for (int i=0; i<nrts[type]; ++i) {
// texture
uint t=texfunc[type](w,h,011,0);
arr_push(G.rt_tex[type][level], t);
// arr_pushn(G.rt_tex[type][level], &t, 1);
// bitmap
G.rt_bm[type][level] |= bit<<i;
// info
int n=arr_len(G.rt_info); // rt_info[tex_name]
if (t>=n) {
rtinfo_t info[t-n+1];
for (int k=0; k<t-n+1; ++k) {
info[k].type=-1;
}
arr_pushn(G.rt_info, info, t-n+1);
}
rtinfo_t info={.type=type, .level=level, .index=i};
if (type==0 && level==0) {
printf("texture=%u\n", t);
}
assert(t<1000); /////////////////////////// dddddddddddddddddddddddd
G.rt_info[t]=info;
}
}
}
}
void rt_shutdown()
{
}
/*
gets garbage collected every frame
*/
uint rt_alloca(int type, int level)
{
}
/*
*/
void rt_lock(uint tex)
{
}
void rt_unlock(uint tex)
{
}
uint rt_alloc(int type, int level)
{
type %= RT_MAX;
if (G.rt_bm[type][level]) {
int n=arr_len(G.rt_tex[type][level]);
for (int i=0; i<n; i++) {
if (G.rt_bm[type][level] & (1<<i) ) {
G.rt_bm[type][level] &= (~(1<<i));
uint t=G.rt_tex[type][level][i];
rtinfo_t info={.type=type, .level=level, .index=i};
if (t>1000) {
printf("type=%i, level=%i\n", type, level);
assert(t<1000); ////////////////////// dddddddddddddddddddd
}
G.rt_info[t]=info;
return t;
}
}
}
else {
int sz=arr_len(G.rt_tex[type][level]);
if (sz>10) return 0; // TODO:
uint t=texfunc[type](G.screenw>>level, G.screenh>>level, 011, 0);
arr_push(G.rt_tex[type][level], t);
// arr_pushn(G.rt_tex[type][level], &t, 1);
if (t>=sz) {
rtinfo_t info[t-sz+1];
for (int k=0; k<t-sz+1; ++k) {
info[k].type=-1;
}
arr_pushn(G.rt_info, info, t-sz+1);
}
rtinfo_t info={.type=type, .level=level, .index=arr_len(G.rt_tex[type][level])-1};
G.rt_info[t]=info;
return t;
}
}
static int rt_valid(uint tex)
{
if (tex>=arr_len(G.rt_info)) return 0; // access violation
rtinfo_t *info=G.rt_info+tex; // not a (known) RT texture
if (info->type==-1) return 0;
return 1;
}
int rt_fmt(uint tex)
{
if (rt_valid(tex)) {
return G.rt_info[tex].type;
}
return -1;
}
int rt_getinfo(uint tex, rtinfo_t *info)
{
if (rt_valid(tex)) {
*info=G.rt_info[tex];
return 0;
}
return 1;
}
void rt_free(uint tex)
{
if (rt_valid(tex)) {
rtinfo_t *info=G.rt_info+tex;
G.rt_bm[info->type][info->level] |= (1<<info->index);
}
}
| 22.82315 | 132 | 0.609103 | [
"render",
"object",
"vector"
] |
c93204ea3cd9688e18dfb296c3e5c57b758d7793 | 21,354 | h | C | src/platform/gba/draw.h | krupitskas/OpenLara | f8cd4cd10067462e6efd89ce048873159678a5ce | [
"BSD-2-Clause"
] | 3,999 | 2016-09-07T15:36:25.000Z | 2022-03-31T14:54:44.000Z | src/platform/gba/draw.h | krupitskas/OpenLara | f8cd4cd10067462e6efd89ce048873159678a5ce | [
"BSD-2-Clause"
] | 333 | 2016-08-23T10:03:40.000Z | 2022-03-31T13:25:19.000Z | src/platform/gba/draw.h | krupitskas/OpenLara | f8cd4cd10067462e6efd89ce048873159678a5ce | [
"BSD-2-Clause"
] | 403 | 2016-10-31T15:11:02.000Z | 2022-03-31T15:03:52.000Z | #ifndef H_DRAW
#define H_DRAW
#include "common.h"
#include "item.h"
int32 lightAmbient;
int32 randTable[MAX_RAND_TABLE];
int32 caustics[MAX_CAUSTICS];
int32 causticsFrame;
void drawInit()
{
for (int32 i = 0; i < MAX_RAND_TABLE; i++)
{
randTable[i] = (rand_draw() >> 5) - 511;
}
for (int32 i = 0; i < MAX_CAUSTICS; i++)
{
int16 rot = i * (ANGLE_90 * 4) / MAX_CAUSTICS;
caustics[i] = phd_sin(rot) * 768 >> FIXED_SHIFT;
}
}
void drawFree()
{
//
}
void calcLightingDynamic(const Room* room, const vec3i &point)
{
const RoomInfo* info = room->info;
lightAmbient = (info->ambient << 5);
if (!info->lightsCount)
return;
lightAmbient = 8191 - lightAmbient;
int32 maxLum = 0;
for (int i = 0; i < info->lightsCount; i++)
{
const Light* light = room->data.lights + i;
vec3i pos;
pos.x = light->pos.x + (info->x << 8);
pos.y = light->pos.y;
pos.z = light->pos.z + (info->z << 8);
int32 radius = light->radius << 8;
int32 intensity = light->intensity << 5;
vec3i d = point - pos;
int32 dist = dot(d, d) >> 12;
int32 att = X_SQR(radius) >> 12;
int32 lum = (intensity * att) / (dist + att) + lightAmbient;
if (lum > maxLum) {
maxLum = lum;
}
}
lightAmbient = 8191 - ((maxLum + lightAmbient) >> 1);
Matrix &m = matrixGet();
int32 fogZ = m[2].w >> FIXED_SHIFT;
if (fogZ > FOG_MIN) {
lightAmbient += (fogZ - FOG_MIN) << FOG_SHIFT;
lightAmbient = X_MIN(lightAmbient, 8191);
}
}
void calcLightingStatic(int32 intensity)
{
lightAmbient = intensity - 4096;
Matrix &m = matrixGet();
int32 fogZ = m[2].w >> FIXED_SHIFT;
if (fogZ > FOG_MIN) {
lightAmbient += (fogZ - FOG_MIN) << FOG_SHIFT;
}
}
void drawNumber(int32 number, int32 x, int32 y)
{
static const int32 widths[] = {
12, 8, 10, 10, 10, 10, 10, 10, 10, 10
};
const Sprite* glyphSprites = level.sprites + models[ITEM_GLYPHS].start;
while (number > 0)
{
x -= widths[number % 10];
drawGlyph(glyphSprites + 52 + (number % 10), x, y);
number /= 10;
}
}
void drawMesh(int32 meshIndex)
{
const uint8* ptr = (uint8*)meshes[meshIndex] + sizeof(Mesh);
int16 vCount = *(int16*)ptr; ptr += 2;
const vec3s* vertices = (vec3s*)ptr;
ptr += vCount * 3 * sizeof(int16);
const uint16* vIntensity = NULL;
const vec3s* vNormal = NULL;
int16 nCount = *(int16*)ptr; ptr += 2;
//const int16* normals = (int16*)ptr;
if (nCount > 0) { // normals
vNormal = (vec3s*)ptr;
ptr += nCount * 3 * sizeof(int16);
} else { // intensity
vIntensity = (uint16*)ptr;
ptr += vCount * sizeof(uint16);
}
int16 rCount = *(int16*)ptr; ptr += 2;
Quad* rFaces = (Quad*)ptr; ptr += rCount * sizeof(Quad);
int16 tCount = *(int16*)ptr; ptr += 2;
Triangle* tFaces = (Triangle*)ptr; ptr += tCount * sizeof(Triangle);
int16 crCount = *(int16*)ptr; ptr += 2;
Quad* crFaces = (Quad*)ptr; ptr += crCount * sizeof(Quad);
int16 ctCount = *(int16*)ptr; ptr += 2;
Triangle* ctFaces = (Triangle*)ptr; ptr += ctCount * sizeof(Triangle);
int32 startVertex = gVerticesCount;
{
PROFILE(CNT_TRANSFORM);
transformMesh(vertices, vCount, vIntensity, vNormal);
}
{
PROFILE(CNT_ADD);
faceAddMesh(rFaces, crFaces, tFaces, ctFaces, rCount, crCount, tCount, ctCount, startVertex);
}
}
void drawShadow(const Item* item, int32 size)
{
const Sector* sector = item->room->getSector(item->pos.x, item->pos.z);
int32 floor = sector->getFloor(item->pos.x, item->pos.y, item->pos.z);
if (floor == WALL)
return;
enableClipping = true;
const Bounds& box = item->getBoundingBox(true);
int32 x = (box.maxX + box.minX) >> 1;
int32 z = (box.maxZ + box.minZ) >> 1;
int32 sx = (box.maxX - box.minX) * size >> 10;
int32 sz = (box.maxZ - box.minZ) * size >> 10;
int32 sx2 = sx << 1;
int32 sz2 = sz << 1;
int32 startVertex = gVerticesCount;
int32 y = floor - item->pos.y;
matrixPush();
matrixTranslateAbs(item->pos.x, item->pos.y, item->pos.z);
matrixRotateY(item->angle.y);
transform(x - sx, y, z + sz2, 4096);
transform(x + sx, y, z + sz2, 4096);
transform(x + sx2, y, z + sz, 4096);
transform(x + sx2, y, z - sz, 4096);
transform(x + sx, y, z - sz2, 4096);
transform(x - sx, y, z - sz2, 4096);
transform(x - sx2, y, z - sz, 4096);
transform(x - sx2, y, z + sz, 4096);
static const Index indices[] = {
0, 1, 2, 7,
7, 2, 3, 6,
6, 3, 4, 5
};
faceAddQuad(FACE_SHADOW, indices + 0, startVertex);
faceAddQuad(FACE_SHADOW, indices + 4, startVertex);
faceAddQuad(FACE_SHADOW, indices + 8, startVertex);
matrixPop();
}
void drawSprite(const Item* item)
{
vec3i d = item->pos - cameraViewPos;
faceAddSprite(d.x, d.y, d.z, item->intensity << 5, models[item->type].start + item->frameIndex);
}
void drawFlash(const ExtraInfoLara::Arm::Flash &flash)
{
matrixPush();
matrixTranslate(0, flash.offset, 55);
matrixRotateYXZ(-ANGLE_90, 0, flash.angle);
int32 tmp = lightAmbient;
calcLightingStatic(flash.intensity);
drawMesh(models[ITEM_MUZZLE_FLASH].start);
lightAmbient = tmp;
matrixPop();
}
void drawNodes(const Item* item, const AnimFrame* frameA)
{
const Model* model = models + item->type;
const Node* node = level.nodes + model->nodeIndex;
int32 meshIndex = model->start;
int32 meshCount = model->count;
uint32 visibleMask = item->visibleMask;
const uint32* angles = (uint32*)(frameA->angles + 1);
const int16* extraAngles = (int16*)item->extra;
matrixFrame(frameA->pos, angles);
if (visibleMask & 1) {
drawMesh(meshIndex);
}
while (meshCount > 1)
{
meshIndex++;
visibleMask >>= 1;
angles++;
if (node->flags & NODE_FLAG_POP) matrixPop();
if (node->flags & NODE_FLAG_PUSH) matrixPush();
matrixFrame(node->pos, angles);
if (extraAngles)
{
if (node->flags & NODE_FLAG_ROTY) matrixRotateY(*extraAngles++);
if (node->flags & NODE_FLAG_ROTX) matrixRotateX(*extraAngles++);
if (node->flags & NODE_FLAG_ROTZ) matrixRotateZ(*extraAngles++);
}
if (visibleMask & 1) {
drawMesh(meshIndex);
}
meshCount--;
node++;
}
}
void drawNodesLerp(const Item* item, const AnimFrame* frameA, const AnimFrame* frameB, int32 frameDelta, int32 frameRate)
{
if (frameDelta == 0)
{
drawNodes(item, frameA);
return;
}
const Model* model = models + item->type;
const Node* node = level.nodes + model->nodeIndex;
int32 meshIndex = model->start;
int32 meshCount = model->count;
uint32 visibleMask = item->visibleMask;
const uint32* anglesA = (uint32*)(frameA->angles + 1);
const uint32* anglesB = (uint32*)(frameB->angles + 1);
const int16* extraAngles = (int16*)item->extra;
int32 t = FixedInvU(frameRate) * frameDelta;
vec3s posLerp;
posLerp.x = frameA->pos.x + ((frameB->pos.x - frameA->pos.x) * t >> 16);
posLerp.y = frameA->pos.y + ((frameB->pos.y - frameA->pos.y) * t >> 16);
posLerp.z = frameA->pos.z + ((frameB->pos.z - frameA->pos.z) * t >> 16);
matrixFrameLerp(posLerp, anglesA, anglesB, frameDelta, frameRate);
if (visibleMask & 1) {
drawMesh(meshIndex);
}
while (meshCount > 1)
{
meshIndex++;
visibleMask >>= 1;
anglesA++;
anglesB++;
if (node->flags & NODE_FLAG_POP) matrixPop();
if (node->flags & NODE_FLAG_PUSH) matrixPush();
matrixFrameLerp(node->pos, anglesA, anglesB, frameDelta, frameRate);
if (extraAngles)
{
if (node->flags & NODE_FLAG_ROTY) matrixRotateY(*extraAngles++);
if (node->flags & NODE_FLAG_ROTX) matrixRotateX(*extraAngles++);
if (node->flags & NODE_FLAG_ROTZ) matrixRotateZ(*extraAngles++);
}
if (visibleMask & 1) {
drawMesh(meshIndex);
}
meshCount--;
node++;
}
}
#define DEF_TORSO_ANGLE vec3s(1216, -832, -192)
void drawLaraNodes(const Item* lara, const AnimFrame* frameA)
{
const Model* model = models + lara->type;
const Node* node = level.nodes + model->nodeIndex;
const ExtraInfoLara* extraL = lara->extraL;
const uint16* mesh = extraL->meshes;
const uint32* anglesArm[LARA_ARM_MAX];
const uint32* angles = anglesArm[LARA_ARM_R] = anglesArm[LARA_ARM_L] = (uint32*)(frameA->angles + 1);
int32 frameSize = (sizeof(AnimFrame) >> 1) + (model->count << 1);
vec3s torsoAngle = extraL->torso.angle;
for (int32 i = 0; i < LARA_ARM_MAX; i++)
{
const ExtraInfoLara::Arm* arm = &extraL->armR + i;
if (arm->animIndex)
{
const Anim* anim = level.anims + arm->animIndex;
const AnimFrame* frame = (AnimFrame*)(level.animFrames + (anim->frameOffset >> 1) + arm->frameIndex * frameSize);
anglesArm[i] = (uint32*)(frame->angles + 1);
// additional torso animation for shotgun
if (extraL->weapon == WEAPON_SHOTGUN && i == LARA_ARM_R)
{
vec3s ang;
DECODE_ANGLES((uint32*)(frame->angles + 1) + JOINT_TORSO, ang.x, ang.y, ang.z);
torsoAngle += ang - DEF_TORSO_ANGLE;
}
}
}
anglesArm[LARA_ARM_R] += JOINT_ARM_R1;
anglesArm[LARA_ARM_L] += JOINT_ARM_L1;
const Matrix& basis = matrixGet();
matrixPush();
{ // JOINT_HIPS
matrixFrame(frameA->pos, angles++);
drawMesh(*mesh++);
for (int32 i = 0; i < 2; i++) // draw Left & Right legs
{
matrixPush();
{ // JOINT_LEG_1
matrixFrame((node++)->pos, angles++);
drawMesh(*mesh++);
{ // JOINT_LEG_2
matrixFrame((node++)->pos, angles++);
drawMesh(*mesh++);
{ // JOINT_LEG_3
matrixFrame((node++)->pos, angles++);
drawMesh(*mesh++);
}
}
}
matrixPop();
}
{ // JOINT_TORSO
matrixFrame((node++)->pos, angles++);
matrixRotateYXZ(torsoAngle.x, torsoAngle.y, torsoAngle.z);
drawMesh(*mesh++);
for (int32 i = 0; i < LARA_ARM_MAX; i++) // draw Right & Left arms
{
const ExtraInfoLara::Arm* arm = &extraL->armR + i;
matrixPush();
// JOINT_ARM_1
matrixTranslate(node->pos.x, node->pos.y, node->pos.z);
node++;
if (arm->useBasis) { // hands are rotated relative to the basis
matrixSetBasis(matrixGet(), basis);
matrixRotateYXZ(arm->angle.x, arm->angle.y, arm->angle.z);
}
matrixFrame(vec3s(0, 0, 0), anglesArm[i]++);
drawMesh(*mesh++);
{ // JOINT_ARM_2
matrixFrame((node++)->pos, anglesArm[i]++);
drawMesh(*mesh++);
{ // JOINT_ARM_3
matrixFrame((node++)->pos, anglesArm[i]);
drawMesh(*mesh++);
if (arm->flash.timer) { // muzzle flash
drawFlash(arm->flash);
}
}
}
matrixPop();
}
{ // JOINT_HEAD
matrixFrame((node++)->pos, angles + 3 * LARA_ARM_MAX);
matrixRotateYXZ(extraL->head.angle.x, extraL->head.angle.y, extraL->head.angle.z);
drawMesh(*mesh++);
}
}
}
matrixPop();
}
void drawLaraNodesLerp(const Item* lara, const AnimFrame* frameA, const AnimFrame* frameB, int32 frameDelta, int32 frameRate)
{
if (frameDelta == 0)
{
drawLaraNodes(lara, frameA);
return;
}
const Model* model = models + lara->type;
const Node* node = level.nodes + model->nodeIndex;
const ExtraInfoLara* extraL = lara->extraL;
const uint16* mesh = extraL->meshes;
const uint32* anglesArmA[LARA_ARM_MAX];
const uint32* anglesArmB[LARA_ARM_MAX];
const uint32* anglesA = anglesArmA[LARA_ARM_R] = anglesArmA[LARA_ARM_L] = (uint32*)(frameA->angles + 1);
const uint32* anglesB = anglesArmB[LARA_ARM_R] = anglesArmB[LARA_ARM_L] = (uint32*)(frameB->angles + 1);
int32 frameRateArm[2];
frameRateArm[0] = frameRateArm[1] = frameRate;
int32 frameSize = (sizeof(AnimFrame) >> 1) + (model->count << 1);
vec3s torsoAngle = extraL->torso.angle;
for (int32 i = 0; i < LARA_ARM_MAX; i++)
{
const ExtraInfoLara::Arm* arm = &extraL->armR + i;
if (arm->animIndex)
{
const Anim* anim = level.anims + arm->animIndex;
const AnimFrame* frame = (AnimFrame*)(level.animFrames + (anim->frameOffset >> 1) + arm->frameIndex * frameSize);
anglesArmA[i] = anglesArmB[i] = (uint32*)(frame->angles + 1); // no lerp for armed hands (frameRate == 1)
ASSERT(anim->frameRate == 1);
frameRateArm[i] = anim->frameRate;
// additional torso animation for shotgun
if (extraL->weapon == WEAPON_SHOTGUN && i == LARA_ARM_R)
{
vec3s ang;
DECODE_ANGLES((uint32*)(frame->angles + 1) + JOINT_TORSO, ang.x, ang.y, ang.z);
torsoAngle += ang - DEF_TORSO_ANGLE;
}
}
}
anglesArmA[LARA_ARM_R] += JOINT_ARM_R1;
anglesArmB[LARA_ARM_R] += JOINT_ARM_R1;
anglesArmA[LARA_ARM_L] += JOINT_ARM_L1;
anglesArmB[LARA_ARM_L] += JOINT_ARM_L1;
const Matrix& basis = matrixGet();
matrixPush();
{ // JOINT_HIPS
int32 t = FixedInvU(frameRate) * frameDelta;
vec3s posLerp;
posLerp.x = frameA->pos.x + ((frameB->pos.x - frameA->pos.x) * t >> 16);
posLerp.y = frameA->pos.y + ((frameB->pos.y - frameA->pos.y) * t >> 16);
posLerp.z = frameA->pos.z + ((frameB->pos.z - frameA->pos.z) * t >> 16);
matrixFrameLerp(posLerp, anglesA++, anglesB++, frameDelta, frameRate);
drawMesh(*mesh++);
for (int32 i = 0; i < 2; i++) // draw Left & Right legs
{
matrixPush();
{ // JOINT_LEG_1
matrixFrameLerp((node++)->pos, anglesA++, anglesB++, frameDelta, frameRate);
drawMesh(*mesh++);
{ // JOINT_LEG_2
matrixFrameLerp((node++)->pos, anglesA++, anglesB++, frameDelta, frameRate);
drawMesh(*mesh++);
{ // JOINT_LEG_3
matrixFrameLerp((node++)->pos, anglesA++, anglesB++, frameDelta, frameRate);
drawMesh(*mesh++);
}
}
}
matrixPop();
}
{ // JOINT_TORSO
matrixFrameLerp((node++)->pos, anglesA++, anglesB++, frameDelta, frameRate);
matrixRotateYXZ(torsoAngle.x, torsoAngle.y, torsoAngle.z);
drawMesh(*mesh++);
for (int32 i = 0; i < LARA_ARM_MAX; i++) // draw Right & Left arms
{
const ExtraInfoLara::Arm* arm = &extraL->armR + i;
matrixPush();
// JOINT_ARM_1
matrixTranslate(node->pos.x, node->pos.y, node->pos.z);
node++;
if (arm->useBasis) { // hands are rotated relative to the basis
matrixSetBasis(matrixGet(), basis);
matrixRotateYXZ(arm->angle.x, arm->angle.y, arm->angle.z);
}
bool useLerp = frameRateArm[i] > 1; // armed hands always use frameRate == 1 (i.e. useLerp == false)
if (useLerp) {
matrixFrameLerp(vec3s(0, 0, 0), anglesArmA[i]++, anglesArmB[i]++, frameDelta, frameRate);
} else {
matrixFrame(vec3s(0, 0, 0), anglesArmA[i]++);
}
drawMesh(*mesh++);
{ // JOINT_ARM_2
if (useLerp) {
matrixFrameLerp((node++)->pos, anglesArmA[i]++, anglesArmB[i]++, frameDelta, frameRate);
} else {
matrixFrame((node++)->pos, anglesArmA[i]++);
}
drawMesh(*mesh++);
{ // JOINT_ARM_3
if (useLerp) {
matrixFrameLerp((node++)->pos, anglesArmA[i], anglesArmB[i], frameDelta, frameRate);
} else {
matrixFrame((node++)->pos, anglesArmA[i]);
}
drawMesh(*mesh++);
if (arm->flash.timer) { // muzzle flash
drawFlash(arm->flash);
}
}
}
matrixPop();
}
{ // JOINT_HEAD
matrixFrameLerp((node++)->pos, anglesA + 3 * LARA_ARM_MAX, anglesB + 3 * LARA_ARM_MAX, frameDelta, frameRate);
matrixRotateYXZ(extraL->head.angle.x, extraL->head.angle.y, extraL->head.angle.z);
drawMesh(*mesh++);
}
}
}
matrixPop();
}
void drawModel(const Item* item)
{
const AnimFrame *frameA, *frameB;
int32 frameRate;
int32 frameDelta = item->getFrames(frameA, frameB, frameRate); // TODO lerp
matrixPush();
matrixTranslateAbs(item->pos.x, item->pos.y, item->pos.z);
matrixRotateYXZ(item->angle.x, item->angle.y, item->angle.z);
int32 vis = boxIsVisible(&frameA->box);
if (vis != 0)
{
enableClipping = vis < 0;
int32 intensity = item->intensity << 5;
if (intensity == 0) {
vec3i point = item->getRelative(frameA->box.getCenter());
calcLightingDynamic(item->room, point);
} else {
calcLightingStatic(intensity);
}
// skip rooms portal clipping for objects
Rect oldViewport = viewport;
viewport = Rect( 0, 0, FRAME_WIDTH, FRAME_HEIGHT );
if (item->type == ITEM_LARA) {
drawLaraNodesLerp(item, frameA, frameB, frameDelta, frameRate);
} else {
drawNodesLerp(item, frameA, frameB, frameDelta, frameRate);
}
viewport = oldViewport;
}
matrixPop();
// shadow
if (vis != 0 && item->flags.shadow) {
drawShadow(item, 160); // TODO per item shadow size
}
}
void drawItem(const Item* item)
{
if (models[item->type].count > 0) {
drawModel(item);
} else {
drawSprite(item);
}
}
void drawRoom(const Room* room)
{
viewport = room->clip;
int32 startVertex = gVerticesCount;
const RoomInfo* info = room->info;
const RoomData& data = room->data;
matrixPush();
matrixTranslateAbs(info->x << 8, 0, info->z << 8);
gCamera->updateFrustum(info->x << 8, 0, info->z << 8);
enableClipping = true;
{
PROFILE(CNT_TRANSFORM);
transformRoom(data.vertices, info->verticesCount, info->flags.water);
}
{
PROFILE(CNT_ADD);
faceAddRoom(data.quads, info->quadsCount, data.triangles, info->trianglesCount, startVertex);
}
for (int32 i = 0; i < info->spritesCount; i++)
{
const RoomSprite* sprite = data.sprites + i;
faceAddSprite(sprite->pos.x, sprite->pos.y, sprite->pos.z, sprite->g << 5, sprite->index);
}
matrixPop();
for (int32 i = 0; i < info->meshesCount; i++)
{
const RoomMesh* mesh = data.meshes + i;
#ifdef NO_STATIC_MESH_PLANTS
if (mesh->id < 10) continue;
#endif
const StaticMesh* staticMesh = staticMeshes + mesh->id;
if (!(staticMesh->flags & STATIC_MESH_FLAG_VISIBLE)) continue; // invisible
vec3i pos;
pos.x = mesh->pos.x + (info->x << 8);
pos.y = mesh->pos.y;
pos.z = mesh->pos.z + (info->z << 8);
matrixPush();
matrixTranslateAbs(pos.x, pos.y, pos.z);
matrixRotateY((mesh->rot - 2) * ANGLE_90);
int32 vis = boxIsVisible(&staticMesh->vbox);
if (vis != 0) {
enableClipping = true;//vis < 0; // TODO wrong visibility BBox?
calcLightingStatic(mesh->intensity << 5);
drawMesh(staticMesh->meshIndex);
}
matrixPop();
}
Item* item = room->firstItem;
while (item)
{
if (item->flags.status != ITEM_FLAGS_STATUS_INVISIBLE) {
item->draw();
}
item = item->nextItem;
}
}
void drawRooms()
{
gCamera->view.room->clip = Rect( 0, 0, FRAME_WIDTH, FRAME_HEIGHT );
Room** visRoom = gCamera->view.room->getVisibleRooms();
while (*visRoom)
{
Room* room = *visRoom++;
drawRoom(room);
room->reset();
}
flush();
}
#endif
| 29.172131 | 126 | 0.538728 | [
"mesh",
"model",
"transform"
] |
c94a5c4cf3f4f10932799d3cbf066e480813c437 | 7,785 | h | C | include/small/small.h | locker/small | 770b7cf0f1133b3ff88900f6cbdd8d856e4c4409 | [
"BSD-2-Clause"
] | 85 | 2015-10-21T19:48:17.000Z | 2022-02-25T08:27:58.000Z | include/small/small.h | locker/small | 770b7cf0f1133b3ff88900f6cbdd8d856e4c4409 | [
"BSD-2-Clause"
] | 37 | 2015-10-22T20:50:34.000Z | 2021-12-16T16:18:49.000Z | include/small/small.h | locker/small | 770b7cf0f1133b3ff88900f6cbdd8d856e4c4409 | [
"BSD-2-Clause"
] | 14 | 2015-11-02T10:01:19.000Z | 2022-01-17T14:19:51.000Z | #ifndef INCLUDES_TARANTOOL_SMALL_SMALL_H
#define INCLUDES_TARANTOOL_SMALL_SMALL_H
/*
* Copyright 2010-2016, Tarantool AUTHORS, please see AUTHORS file.
*
* 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 <COPYRIGHT HOLDER> ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <stdint.h>
#include "mempool.h"
#include "slab_arena.h"
#include "lifo.h"
#include "small_class.h"
#if defined(__cplusplus)
extern "C" {
#endif /* defined(__cplusplus) */
/**
* Small object allocator.
*
* The allocator consists of a collection of mempools.
*
* There is one array which contained all pools.
* The array size limits the maximum possible number of mempools.
* All mempools are created when creating an allocator. Their sizes and
* count are calculated depending on alloc_factor and granularity, using
* small_class (see small_class.h for more details).
* When requesting a memory allocation, we can find pool with the most
* appropriate size in time O(1), using small_class.
*/
/** Basic constants of small object allocator. */
enum {
/** How many small mempools there can be. */
SMALL_MEMPOOL_MAX = 1024,
};
struct small_mempool_group;
/**
* A mempool to store objects sized from objsize_min to pool->objsize.
* Is a member of small_mempool_cache array which contains all such pools.
* All this pools are created when creating an allocator. Their sizes and
* count are calculated depending on alloc_factor and granularity, using
* small_class.
*/
struct small_mempool {
/** the pool itself. */
struct mempool pool;
/**
* Objects starting from this size and up to
* pool->objsize are stored in this factored
* pool.
*/
size_t objsize_min;
/** Small mempool group that this pool belongs to. */
struct small_mempool_group *group;
/**
* Currently used pool for memory allocation. In case waste is
* less than @waste_max of corresponding mempool_group, @used_pool
* points to this structure itself.
*/
struct small_mempool *used_pool;
/**
* Mask of appropriate pools. It is calculated once pool is created.
* Values of mask for:
* Pool 0: 0x0001 (0000 0000 0000 0001)
* Pool 1: 0x0003 (0000 0000 0000 0011)
* Pool 2: 0x0007 (0000 0000 0000 0111)
* And so forth.
*/
uint32_t appropriate_pool_mask;
/**
* Currently memory waste for a given mempool. Waste is calculated as
* amount of excess memory spent for storing small object in pools
* with large object size. For instance, if we store object with size
* of 15 bytes in a 64-byte pool having inactive 32-byte pool, the loss
* will be: 64 bytes - 32 bytes = 32 bytes.
*/
size_t waste;
};
struct small_mempool_group {
/** The first pool in the group. */
struct small_mempool *first;
/** The last pool in the group. */
struct small_mempool *last;
/**
* Raised bit on position n means that the pool with index n can be
* used for allocations. At the start only one pool (the last one)
* is available. Also note that once pool become active, it can't
* become
*/
uint32_t active_pool_mask;
/**
* Pre-calculated waste threshold reaching which small_mempool becomes
* activated. It is equal to slab_order_size / 4.
*/
size_t waste_max;
};
/** A slab allocator for a wide range of object sizes. */
struct small_alloc {
struct slab_cache *cache;
/** Array of all small mempools of a given allocator */
struct small_mempool small_mempool_cache[SMALL_MEMPOOL_MAX];
/* small_mempool_cache array real size */
uint32_t small_mempool_cache_size;
/** Array of all small mempool groups of a given allocator */
struct small_mempool_group small_mempool_groups[SMALL_MEMPOOL_MAX];
/*
* small_mempool_groups array real size. In the worst case each
* group will contain only one pool, so the number of groups is
* also limited by SMALL_MEMPOOL_MAX.
*/
uint32_t small_mempool_groups_size;
/**
* The factor used for factored pools. Must be > 1.
* Is provided during initialization.
*/
float factor;
/** Small class for this allocator */
struct small_class small_class;
uint32_t objsize_max;
};
/**
* Initialize a small memory allocator.
* @param alloc - instance to create.
* @param cache - pointer to used slab cache.
* @param objsize_min - minimal object size.
* @param granularity - alignment of objects in pools
* @param alloc_factor - desired factor of growth object size.
* Must be in (1, 2] range.
* @param actual_alloc_factor real allocation factor calculated the basis of
* desired alloc_factor
*/
void
small_alloc_create(struct small_alloc *alloc, struct slab_cache *cache,
uint32_t objsize_min, unsigned granularity,
float alloc_factor, float *actual_alloc_factor);
/** Destroy the allocator and all allocated memory. */
void
small_alloc_destroy(struct small_alloc *alloc);
/** Allocate a piece of memory in the small allocator.
*
* @retval NULL the requested size is beyond objsize_max
* or out of memory
*/
void *
smalloc(struct small_alloc *alloc, size_t size);
/** Free memory chunk allocated by the small allocator. */
/**
* Free a small objects.
*
* This boils down to finding the object's mempool and delegating
* to mempool_free().
*/
void
smfree(struct small_alloc *alloc, void *ptr, size_t size);
/**
* @brief Return an unique index associated with a chunk allocated
* by the allocator.
*
* This index space is more dense than the pointers space,
* especially in the least significant bits. This number is
* needed because some types of box's indexes (e.g. BITSET) have
* better performance then they operate on sequential offsets
* (i.e. dense space) instead of memory pointers (sparse space).
*
* The calculation is based on SLAB number and the position of an
* item within it. Current implementation only guarantees that
* adjacent chunks from one SLAB will have consecutive indexes.
* That is, if two chunks were sequentially allocated from one
* chunk they will have sequential ids. If a second chunk was
* allocated from another SLAB thеn the difference between indexes
* may be more than one.
*
* @param ptr pointer to memory allocated in small_alloc
* @return unique index
*/
size_t
small_ptr_compress(struct small_alloc *alloc, void *ptr);
/**
* Perform the opposite action of small_ptr_compress().
*/
void *
small_ptr_decompress(struct small_alloc *alloc, size_t val);
void
small_stats(struct small_alloc *alloc,
struct small_stats *totals,
int (*cb)(const void *, void *), void *cb_ctx);
#if defined(__cplusplus)
} /* extern "C" */
#endif /* defined(__cplusplus) */
#endif /* INCLUDES_TARANTOOL_SMALL_SMALL_H */
| 33.847826 | 76 | 0.737572 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.