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
733a812a4a3154b3b4e0bdefe97a0241f165afa7
1,197
h
C
test_Text/src/ofApp.h
Bentleyj/Textsplosion
d410be2340f850ff0a19fedaaa52c062807bf5ff
[ "MIT" ]
null
null
null
test_Text/src/ofApp.h
Bentleyj/Textsplosion
d410be2340f850ff0a19fedaaa52c062807bf5ff
[ "MIT" ]
null
null
null
test_Text/src/ofApp.h
Bentleyj/Textsplosion
d410be2340f850ff0a19fedaaa52c062807bf5ff
[ "MIT" ]
null
null
null
#pragma once #include "ofMain.h" #include "ofxFontStash.h" #include "ofxGui.h" #include "Textsplosion.h" class ofApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void keyPressed(int key); void keyReleased(int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void mouseEntered(int x, int y); void mouseExited(int x, int y); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); void drawSquares(); ofVec3f drawText(string text, ofVec3f viewPositionNorm); vector<Textsplosion> texts; ofxPanel gui; ofParameter<float> xScale; ofParameter<float> yScale; vector<ofVec2f> positions; ofVec3f cameraPosTarget; ofVec3f camUpVectorTarget; float noiseOffset1; float noiseOffset2; float noiseOffset3; float noiseOffset4; float noise; int textIndex; bool animating = false; ofTrueTypeFont* font; ofLight light; ofEasyCam cam; };
20.288136
64
0.657477
[ "vector" ]
734143dee2404de4142c0c50dc3231958eff2ac2
850
h
C
src/notebookpage.h
jslick/PepperNote
47f73a3c3ec13362f9576f04c3c10aca4a1f9db6
[ "MIT" ]
2
2016-03-02T13:13:17.000Z
2019-12-04T01:57:59.000Z
src/notebookpage.h
jslick/PepperNote
47f73a3c3ec13362f9576f04c3c10aca4a1f9db6
[ "MIT" ]
null
null
null
src/notebookpage.h
jslick/PepperNote
47f73a3c3ec13362f9576f04c3c10aca4a1f9db6
[ "MIT" ]
null
null
null
/* * Copyright (c) 2012 PepperNote developers * * See the file license.txt for copying permission. */ #ifndef NOTEBOOKPAGE_H #define NOTEBOOKPAGE_H #include <QObject> class Notebook; class NotebookPage : public QObject { Q_OBJECT public: explicit NotebookPage(const QString& pageId = "", const QString& pageName = ""); QString getId() const; QString createId(); QString getName() const; /** * @param pageName * @note Emits pageNameChanged */ void setName(const QString& pageName); signals: /** * @brief Emitted when the pageName changes, but not when the object is * created * * @param pageName The new pageName */ void pageNameChanged(QString pageName); public slots: private: QString pageId; QString pageName; }; #endif // NOTEBOOKPAGE_H
17
84
0.655294
[ "object" ]
7344b161f85dd680162aad959658c249d2faabf3
449
h
C
toonz/sources/include/tlin/tlin_vector.h
ss23/opentoonz
b42e43d4b8d9fedc26022d145218b9a147a30985
[ "BSD-3-Clause" ]
null
null
null
toonz/sources/include/tlin/tlin_vector.h
ss23/opentoonz
b42e43d4b8d9fedc26022d145218b9a147a30985
[ "BSD-3-Clause" ]
null
null
null
toonz/sources/include/tlin/tlin_vector.h
ss23/opentoonz
b42e43d4b8d9fedc26022d145218b9a147a30985
[ "BSD-3-Clause" ]
1
2019-10-07T17:12:30.000Z
2019-10-07T17:12:30.000Z
#ifndef TLIN_VECTOR_H #define TLIN_VECTOR_H //---------------------------------------------------------------------------- /*! The Vector class represents a vector in tlin-compatible algorithms. */ template <typename T> class vector { public: vector(int size); ~vector(); vector(const vector &); vector &operator=(const vector &); int size() const; T &operator[](int i); const T &operator[](int i) const; }; #endif //TLIN_MATRIX_H
15.482759
78
0.570156
[ "vector" ]
73473ab10f9fd63b1d2ab38ed2a14ec8863fe5d4
4,519
h
C
GraphicsEngine.h
nghiattran/KittiViz
fa3ac5edb1f5efbfef7a9ef2926042f32045b7c0
[ "MIT" ]
19
2017-12-29T14:34:58.000Z
2021-12-22T07:46:32.000Z
GraphicsEngine.h
dj-boy/KittiViz
fa3ac5edb1f5efbfef7a9ef2926042f32045b7c0
[ "MIT" ]
1
2017-12-29T14:34:53.000Z
2018-08-05T20:09:56.000Z
GraphicsEngine.h
dj-boy/KittiViz
fa3ac5edb1f5efbfef7a9ef2926042f32045b7c0
[ "MIT" ]
3
2018-01-25T00:17:24.000Z
2021-07-03T15:36:58.000Z
#ifndef GRAPHICSENGINE_H_INCLUDED #define GRAPHICSENGINE_H_INCLUDED #include <GL/glew.h> #include <SFML/Graphics.hpp> #include <SFML/OpenGL.hpp> #include <SFML/System.hpp> #include <iostream> #include <string> #include <stdio.h> #define GLM_SWIZZLE #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include "lib/objects/Axes.h" #include "lib/loaders/PointsLoader.h" #include "lib/loaders/DataLoader.h" #include "lib/loaders/BoxLoader.h" #include "lib/loaders/ConfigLoader.h" #include "lib/cameras/SphericalCamera.h" #include "lib/cameras/YPRCamera.h" #include "lib/objects/Models.h" #include "lib/objects/MainCar.h" #include "lib/objects/Speedometer.h" #include "lib/layouts/SubWindow.h" #include "lib/utils/Screen.h" /** \file GraphicsEngine.h \brief Header file for GraphicsEngine.cpp \author Don Spickler, Nghia Tran \version 1.2 \date Written: 4/5/2016 <BR> Revised: 4/6/2016 */ /** \class GraphicsEngine \brief The GraphicsEngine class is an extension of sf::RenderWindow which handles all of the graphics rendering in the program. */ class GraphicsEngine : public sf::RenderWindow { private: GLenum mode; ///< Mode, either point, line or fill. int sscount; ///< Screenshot count to be appended to the screenshot filename. bool isDrawCloudpoints = true; const int NUM_LIGHT = 3; Axes coords; ///< Axes Object PointsLoader* pointsLoader; ///< Object to load velodyne cloud points. DataLoader* dataLoader; ///< Object to control all data processing. BoxLoader* boxLoader; ///< Object to control all bouding boxes. SubWindow* subwindow; ///< SubWindow Objects ConfigLoader* confLoader; Screen* screen; GLuint ModelLoc; ///< Location ID of the Model matrix in the shader. GLuint NormalLoc; ///< Location ID of the Normal matrix in the shader. GLuint PVMLoc; ///< Location ID of the PVM matrix in the shader. GLuint program; ///< ID of the shader program. GLuint CMprogram; ///< ID of the cube map shader program. GLuint texTransLoc; ///< Location ID of the texture transformation SphericalCamera sphcamera; ///< Spherical Camera YPRCamera yprcamera; ///< Yaw-Pitch-Roll Camera int CameraNumber; ///< Camera number 1 = spherical, 2 = yaw-pitch-roll. SphericalCamera LtPos[10]; ///< Spherical "Camera" to control position of the light. Speedometer speedometer; Material mat; ///< Material of the current object. Light lt[10]; ///< Light object. Models lightobj; ///< Used for sphere at light source. MainCar mainCar; ///< Object wrapper for Wavefront obj file data. GLuint CubeMapTexId; ///< Cube Map Texture ID. Models CMSphere; ///< Sphere Object for Cube Map glm::mat4 projection; ///< Projection Matrix glm::mat4 model; ///< Model Matrix GLboolean isDrawAxes; ///< Boolean for axes being drawn. GLboolean isPlaying; ///< Boolean for playing vidoes. sf::Image texture; ///< Cube map texture. void screenshot(std::string ext); void printOpenGLErrors(); void print_GLM_Matrix(glm::mat4 m); void print_GLM_Matrix(glm::mat3 m); public: GraphicsEngine(std::string, GLint, GLint); ~GraphicsEngine(); int fps; void display(); void changeMode(); void screenshotPNG(); void screenshotJPG(); void resize(); void setSize(unsigned int, unsigned int); GLfloat* getScreenBounds(); GLboolean isSphericalCameraOn(); void setSphericalCameraOn(); GLboolean isYPRCameraOn(); void setYPRCameraOn(); void setDrawAxes(GLboolean b); void toggleDrawAxes(); void setPlayingVideo(GLboolean b); void togglePlayingVideo(); void toggleBoxes(); void toggleDrawCloudpoints(); void toggleSpeedUnit(); void setFrameRate(int frameRate); int getFrameRate() const; void increaseFrameRate(int diff); void setupSideWindows(); void drawSideWindows(); SphericalCamera* getLtPos(); SphericalCamera* getSphericalCamera(); YPRCamera* getYPRCamera(); }; #endif // GRAPHICSENGINE_H_INCLUDED
32.746377
94
0.639965
[ "object", "model" ]
734ce8f02361fcbb546407a3198b4ef5cc6600d3
5,878
h
C
CBP/CBP/SimObject.h
clayne/CBPSSE
c2bd6470efe3e0dcb3df606fb693f5c66e66e4e5
[ "MIT" ]
3
2020-06-21T18:10:19.000Z
2021-02-05T21:33:18.000Z
CBP/CBP/SimObject.h
clayne/CBPSSE
c2bd6470efe3e0dcb3df606fb693f5c66e66e4e5
[ "MIT" ]
2
2020-08-29T14:29:19.000Z
2020-09-10T18:40:52.000Z
CBP/CBP/SimObject.h
clayne/CBPSSE
c2bd6470efe3e0dcb3df606fb693f5c66e66e4e5
[ "MIT" ]
4
2020-08-25T17:56:35.000Z
2021-11-25T09:39:47.000Z
#pragma once #include "Config.h" #include "Common/BulletExtensions.h" #include "SimComponent.h" namespace CBP { struct nodeDesc_t { nodeDesc_t( const stl::fixed_string& a_nodeName, const stl::fixed_string& a_confGroup, NiAVObject* a_node, NiNode* a_parent, bool a_collisions, bool a_movement, const configComponent_t& a_physConf, const configNode_t& a_nodeConf) : nodeName(a_nodeName), object(a_node), parent(a_parent), confGroup(a_confGroup), collision(a_collisions), movement(a_movement), physConf(a_physConf), nodeConf(a_nodeConf) { } const stl::fixed_string &nodeName; const stl::fixed_string &confGroup; NiAVObject* object; NiNode* parent; bool collision; bool movement; const configComponent_t& physConf; const configNode_t& nodeConf; }; typedef std::vector<nodeDesc_t> nodeDescList_t; class SimObject { using nodeList_t = std::vector<std::unique_ptr<SimComponent>>; public: SimObject( Game::VMHandle a_handle, Actor* actor, NiNode* a_rootNode, ConfigGender a_sex, const nodeDescList_t& a_desc); virtual ~SimObject() noexcept; SimObject() = delete; SimObject(const SimObject& a_rhs) = delete; SimObject(SimObject&& a_rhs) = delete; SimObject& operator=(const SimObject&) = delete; SimObject& operator=(SimObject&&) = delete; void UpdateMotion(float a_timeStep); void ReadTransforms(float a_timeStep); //void ReadWorldData(); void WriteTransforms(); void UpdateConfig(Actor* a_actor, bool a_collisions, const configComponents_t& a_config); bool HasNewNode(Actor* a_actor, const nodeMap_t& a_nodeMap); void RemoveInvalidNodes(Actor* a_actor); void Reset(); void InvalidateHandle(); //bool ValidateNodes(Actor* a_actor); void ApplyForce(std::uint32_t a_steps, const stl::fixed_string& a_component, const btVector3& a_force); #ifdef _CBP_ENABLE_DEBUG void UpdateDebugInfo(); #endif [[nodiscard]] static nodeDescList_t::size_type CreateNodeDescriptorList( Game::VMHandle a_handle, Actor* a_actor, NiNode* a_rootNode, ConfigGender a_sex, const configComponents_t& a_config, const nodeMap_t& a_nodeMap, bool a_collisions, nodeDescList_t& a_out); #ifdef _CBP_ENABLE_DEBUG [[nodiscard]] SKMP_FORCEINLINE const std::string& GetActorName() const noexcept { return m_actorName; } #endif [[nodiscard]] SKMP_FORCEINLINE const NiTransform* GetHeadTransform() const { return m_objHead ? std::addressof(m_objHead->m_worldTransform) : nullptr; } [[nodiscard]] SKMP_FORCEINLINE bool GetHeadTransform(Bullet::btTransformEx& a_out) const { if (m_objHead) { a_out = m_objHead->m_worldTransform; return true; } return false; } void SetSuspended(bool a_switch); [[nodiscard]] SKMP_FORCEINLINE bool IsSuspended() const { return m_suspended; } [[nodiscard]] SKMP_FORCEINLINE const auto& GetNodeList() const { return m_nodes; } [[nodiscard]] SKMP_FORCEINLINE auto GetActorHandle() const { return m_handle.get(); } SKMP_FORCEINLINE void MarkForDelete() { m_markedForDelete = true; } [[nodiscard]] SKMP_FORCEINLINE auto IsMarkedForDelete() const { return m_markedForDelete; } [[nodiscard]] SKMP_FORCEINLINE bool Empty() const { return m_nodes.empty(); } #if 0 SKMP_FORCEINLINE void SetTimeStep(float a_timeStep) { m_currentTimeStep = a_timeStep; } SKMP_FORCEINLINE float GetTimeStep() const { return m_currentTimeStep; } [[nodiscard]] SKMP_FORCEINLINE auto& GetTask() { return m_task; } #endif [[nodiscard]] SKMP_FORCEINLINE auto GetActor() const { return m_actor.get(); } private: [[nodiscard]] static NiNode* GetParentNode( NiAVObject* a_root, const configNode_t& a_nodeConfig); static NiNode* CreateNode( NiNode* a_parent, const BSFixedString& a_name); [[nodiscard]] static NiNode* GetNPCRoot( Actor* a_actor, bool a_firstPerson = false); void ClearSimComponentParent(SimComponent* a_sc); nodeList_t m_nodes; Game::VMHandleRef m_handle; NiPointer<Actor> m_actor; NiPointer<NiAVObject> m_objHead; ConfigGender m_sex; bool m_suspended; bool m_markedForDelete; #if 0 float m_currentTimeStep; struct task_t { task_t(SimObject* a_ptr) : m_ptr(a_ptr) {} void operator()() const { auto daz = _MM_GET_DENORMALS_ZERO_MODE(); auto ftz = _MM_GET_FLUSH_ZERO_MODE(); _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); m_ptr->UpdateMotion(m_ptr->GetTimeStep()); _MM_SET_DENORMALS_ZERO_MODE(daz); _MM_SET_FLUSH_ZERO_MODE(ftz); } SimObject* m_ptr; }; concurrency::task_handle<task_t> m_task; #endif #ifdef _CBP_ENABLE_DEBUG std::string m_actorName; #endif }; }
27.339535
111
0.590507
[ "object", "vector" ]
734fb562da5d03199217b4b07f886ed3d5961369
1,171
h
C
source/scene/prCube.h
pmac1965/proteus
53f366be90739f456c64f09cbec565a0e97b2629
[ "Apache-2.0" ]
1
2019-01-27T14:47:10.000Z
2019-01-27T14:47:10.000Z
source/scene/prCube.h
pmac1965/proteus
53f366be90739f456c64f09cbec565a0e97b2629
[ "Apache-2.0" ]
null
null
null
source/scene/prCube.h
pmac1965/proteus
53f366be90739f456c64f09cbec565a0e97b2629
[ "Apache-2.0" ]
null
null
null
// File: prCube.h /** * Copyright 2014 Paul Michael McNab * * 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 "prSceneObject.h" #include "../core/prGameObject.h" // Class: prCube // A simple geometric primitive for use by the *game editor* // // Notes: // This class is a game object, and therefore inherits a great deal // of functionality from the game object // // See Also // <prGameObject> class prCube : public Proteus::Core::prGameObject //: public prSceneObject { public: // Method: prCube // Ctor prCube(); // Method: Draw // Draws this primitive void Draw(); };
25.456522
75
0.682323
[ "object" ]
7351b9b2f3112fdc8b65e04f412eb969373f042d
3,337
h
C
integrators/igi.h
cathook/rendering_final_proj
d0c147b563d6949839983bf38317c81367e2ed4c
[ "BSD-2-Clause" ]
3
2020-12-09T00:03:29.000Z
2021-07-03T13:31:41.000Z
integrators/igi.h
piwell/CS348B-pbrt
147a9a3ef55cfcb0a1ad0132c63d1ac2f928418f
[ "BSD-2-Clause" ]
null
null
null
integrators/igi.h
piwell/CS348B-pbrt
147a9a3ef55cfcb0a1ad0132c63d1ac2f928418f
[ "BSD-2-Clause" ]
1
2020-11-28T12:33:24.000Z
2020-11-28T12:33:24.000Z
/* pbrt source code Copyright(c) 1998-2012 Matt Pharr and Greg Humphreys. This file is part of pbrt. 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. 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. */ #if defined(_MSC_VER) #pragma once #endif #ifndef PBRT_INTEGRATORS_IGI_H #define PBRT_INTEGRATORS_IGI_H // integrators/igi.h* #include "pbrt.h" #include "integrator.h" // IGIIntegrator Local Structures struct VirtualLight { VirtualLight() { } VirtualLight(const Point &pp, const Normal &nn, const Spectrum &c, float reps) : p(pp), n(nn), pathContrib(c), rayEpsilon(reps) { } Point p; Normal n; Spectrum pathContrib; float rayEpsilon; }; // IGIIntegrator Declarations class IGIIntegrator : public SurfaceIntegrator { public: // IGIIntegrator Public Methods ~IGIIntegrator(); Spectrum Li(const Scene *scene, const Renderer *renderer, const RayDifferential &ray, const Intersection &isect, const Sample *sample, RNG &rng, MemoryArena &arena) const; void RequestSamples(Sampler *sampler, Sample *sample, const Scene *scene); void Preprocess(const Scene *, const Camera *, const Renderer *); IGIIntegrator(uint32_t nl, uint32_t ns, float rrt, int maxd, float gl, int ng) { nLightPaths = RoundUpPow2(nl); nLightSets = RoundUpPow2(ns); rrThreshold = rrt; maxSpecularDepth = maxd; virtualLights.resize(nLightSets); gLimit = gl; nGatherSamples = ng; lightSampleOffsets = NULL; bsdfSampleOffsets = NULL; } private: // IGIIntegrator Private Data // Declare sample parameters for light source sampling LightSampleOffsets *lightSampleOffsets; BSDFSampleOffsets *bsdfSampleOffsets; uint32_t nLightPaths, nLightSets; float gLimit; int nGatherSamples; float rrThreshold; int maxSpecularDepth; int vlSetOffset; BSDFSampleOffsets gatherSampleOffset; vector<vector<VirtualLight> > virtualLights; }; IGIIntegrator *CreateIGISurfaceIntegrator(const ParamSet &params); #endif // PBRT_INTEGRATORS_IGI_H
34.05102
84
0.724004
[ "vector" ]
7354cfc3890126b4b2b79ac2619156cd4d5ea4a4
7,888
c
C
netbsd/sys/arch/alpha/pci/pci_a12.c
shisa/kame-shisa
25dfcf220c0cd8192e475a602501206ccbd9263e
[ "BSD-3-Clause" ]
1
2019-10-15T06:29:32.000Z
2019-10-15T06:29:32.000Z
netbsd/sys/arch/alpha/pci/pci_a12.c
shisa/kame-shisa
25dfcf220c0cd8192e475a602501206ccbd9263e
[ "BSD-3-Clause" ]
null
null
null
netbsd/sys/arch/alpha/pci/pci_a12.c
shisa/kame-shisa
25dfcf220c0cd8192e475a602501206ccbd9263e
[ "BSD-3-Clause" ]
3
2017-01-09T02:15:36.000Z
2019-10-15T06:30:25.000Z
/* $NetBSD: pci_a12.c,v 1.7 2000/06/29 08:58:48 mrg Exp $ */ /* [Notice revision 2.0] * Copyright (c) 1997, 1998 Avalon Computer Systems, Inc. * All rights reserved. * * Author: Ross Harvey * * 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 and * author 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 Avalon Computer Systems, Inc. nor the names of * its contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * 4. This copyright will be assigned to The NetBSD Foundation on * 1/1/2000 unless these terms (including possibly the assignment * date) are updated in writing by Avalon prior to the latest specified * assignment date. * * THIS SOFTWARE IS PROVIDED BY AVALON COMPUTER SYSTEMS, INC. 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 FOUNDATION 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 "opt_avalon_a12.h" /* Config options headers */ #include <sys/cdefs.h> /* RCS ID & Copyright macro defns */ __KERNEL_RCSID(0, "$NetBSD: pci_a12.c,v 1.7 2000/06/29 08:58:48 mrg Exp $"); #include <sys/types.h> #include <sys/param.h> #include <sys/time.h> #include <sys/systm.h> #include <sys/errno.h> #include <sys/malloc.h> #include <sys/device.h> #include <sys/syslog.h> #include <uvm/uvm_extern.h> #include <machine/autoconf.h> #include <dev/pci/pcireg.h> #include <dev/pci/pcivar.h> #include <alpha/pci/a12creg.h> #include <alpha/pci/a12cvar.h> #include <alpha/pci/pci_a12.h> #define PCI_A12() /* Generate ctags(1) key */ #define LOADGSR() (REGVAL(A12_GSR) & 0x7fc0) static int pci_serr __P((void *)); static int a12_xbar_flag __P((void *)); struct a12_intr_vect_t { int on; int (*f) __P((void *)); void *a; } a12_intr_pci = { 0 }, a12_intr_serr = { 1, pci_serr }, a12_intr_flag = { 1, a12_xbar_flag }, a12_intr_iei = { 0 }, a12_intr_dc = { 0 }, a12_intr_xb = { 0 }; static struct gintcall { char flag; char needsclear; char intr_index; /* XXX implicit crossref */ struct a12_intr_vect_t *f; char *msg; } gintcall[] = { { 6, 0, 2, &a12_intr_pci, "PCI Device" }, { 7, 1, 3, &a12_intr_serr, "PCI SERR#" }, { 8, 1, 4, &a12_intr_flag, "XB Frame MCE" }, { 9, 1, 5, &a12_intr_flag, "XB Frame ECE" }, /* skip 10, gsr.TEI */ { 11, 1, 6, &a12_intr_iei, "Interval Timer"}, { 12, 1, 7, &a12_intr_flag, "XB FIFO Overrun"}, { 13, 1, 8, &a12_intr_flag, "XB FIFO Underrun"}, { 14, 1, 9, &a12_intr_dc, "DC Control Word"}, { 0 } }; struct evcnt a12_intr_evcnt; int avalon_a12_intr_map __P((void *, pcitag_t, int, int, pci_intr_handle_t *)); const char *avalon_a12_intr_string __P((void *, pci_intr_handle_t)); const struct evcnt *avalon_a12_intr_evcnt __P((void *, pci_intr_handle_t)); void *avalon_a12_intr_establish __P((void *, pci_intr_handle_t, int, int (*func)(void *), void *)); void avalon_a12_intr_disestablish __P((void *, void *)); static void clear_gsr_interrupt __P((long)); static void a12_GInt(void); void a12_iointr __P((void *framep, unsigned long vec)); void pci_a12_pickintr(ccp) struct a12c_config *ccp; { pci_chipset_tag_t pc = &ccp->ac_pc; pc->pc_intr_v = ccp; pc->pc_intr_map = avalon_a12_intr_map; pc->pc_intr_string = avalon_a12_intr_string; pc->pc_intr_evcnt = avalon_a12_intr_evcnt; pc->pc_intr_establish = avalon_a12_intr_establish; pc->pc_intr_disestablish = avalon_a12_intr_disestablish; /* Not supported on A12. */ pc->pc_pciide_compat_intr_establish = NULL; evcnt_attach_dynamic(&a12_intr_evcnt, EVCNT_TYPE_INTR, NULL, "a12", "pci irq"); set_iointr(a12_iointr); } int avalon_a12_intr_map(ccv, bustag, buspin, line, ihp) void *ccv; pcitag_t bustag; int buspin, line; pci_intr_handle_t *ihp; { /* only one PCI slot (per CPU, that is, but there are 12 CPU's!) */ *ihp = 0; return 0; } const char * avalon_a12_intr_string(ccv, ih) void *ccv; pci_intr_handle_t ih; { return "a12 pci irq"; /* see "only one" note above */ } const struct evcnt * avalon_a12_intr_evcnt(ccv, ih) void *ccv; pci_intr_handle_t ih; { return (&a12_intr_evcnt); } void * avalon_a12_intr_establish(ccv, ih, level, func, arg) void *ccv, *arg; pci_intr_handle_t ih; int level; int (*func) __P((void *)); { a12_intr_pci.f = func; a12_intr_pci.a = arg; a12_intr_pci.on= 1; alpha_wmb(); REGVAL(A12_OMR) |= A12_OMR_PCI_ENABLE; alpha_mb(); return (void *)func; } void avalon_a12_intr_disestablish(ccv, cookie) void *ccv, *cookie; { if(cookie == a12_intr_pci.f) { alpha_wmb(); REGVAL(A12_OMR) &= ~A12_OMR_PCI_ENABLE; alpha_mb(); a12_intr_pci.f = 0; a12_intr_pci.on= 0; } else What(); } void a12_intr_register_xb(f) int (*f) __P((void *)); { a12_intr_xb.f = f; a12_intr_xb.on = 1; } void a12_intr_register_icw(f) int (*f) __P((void *)); { long t; t = REGVAL(A12_OMR) & ~A12_OMR_ICW_ENABLE; if ((a12_intr_dc.on = (f != NULL)) != 0) t |= A12_OMR_ICW_ENABLE; a12_intr_dc.f = f; alpha_wmb(); REGVAL(A12_OMR) = t; alpha_mb(); } long a12_nothing; static void clear_gsr_interrupt(write_1_to_clear) long write_1_to_clear; { REGVAL(A12_GSR) = write_1_to_clear; alpha_mb(); a12_nothing = REGVAL(A12_GSR); } static int pci_serr(p) void *p; { panic("pci_serr"); } static int a12_xbar_flag(p) void *p; { panic("a12_xbar_flag: %s", p); } static void a12_GInt(void) { struct gintcall *gic; long gsrsource, gsrvalue = LOADGSR(); void *s; /* * Switch interrupts do not go through this function */ for(gic=gintcall; gic->f; ++gic) { gsrsource = gsrvalue & 1L<<gic->flag; if (gsrsource && gic->f->on) { if(gic->needsclear) clear_gsr_interrupt(1L<<gic->flag); s = gic->f->a; if (s == NULL) s = gic->msg; if (gic->f->f == NULL) printf("Stray interrupt: %s OMR=%lx\n", gic->msg, REGVAL(A12_OMR) & 0xffc0); else gic->f->f(s); alpha_wmb(); } } } /* * IRQ_H 3 2 1 0 * EV5(10) 23 22 21 20 * EV5(16) 17 16 15 14 * OSF IPL 6 5 4 3 * VECTOR(16) 940 930 920 900 note: no 910 or 940 * f(VECTOR) 4 3 2 0 note: no 1 or 4 * EVENT Never Clk Misc Xbar */ void a12_iointr(framep, vec) void *framep; unsigned long vec; { unsigned irq = (vec-0x900) >> 4; /* this is the f(vector) above */ /* * Xbar device is in the A12 CPU core logic, so its interrupts * might as well be hardwired. */ a12_intr_evcnt.ev_count++; switch(irq) { case 0: if (a12_intr_xb.f == NULL) panic("no switch interrupt registered"); else a12_intr_xb.f(NULL); return; case 2: a12_GInt(); return; default: panic("a12_iointr"); } }
25.61039
78
0.6643
[ "vector" ]
735aadfc4f465e4e5cfd60bfabbdcc84505f3571
1,826
h
C
applications/physbam/physbam-lib/Public_Library/PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL/OPENGL_OCTREE_FACE_SCALAR_FIELD.h
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
20
2017-07-03T19:09:09.000Z
2021-09-10T02:53:56.000Z
applications/physbam/physbam-lib/Public_Library/PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL/OPENGL_OCTREE_FACE_SCALAR_FIELD.h
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
null
null
null
applications/physbam/physbam-lib/Public_Library/PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL/OPENGL_OCTREE_FACE_SCALAR_FIELD.h
schinmayee/nimbus
170cd15e24a7a88243a6ea80aabadc0fc0e6e177
[ "BSD-3-Clause" ]
9
2017-09-17T02:05:06.000Z
2020-01-31T00:12:01.000Z
#ifndef COMPILE_WITHOUT_DYADIC_SUPPORT //##################################################################### // Copyright 2004, Eran Guendelman. // This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt. //##################################################################### // Class OPENGL_OCTREE_FACE_SCALAR_FIELD //##################################################################### #ifndef __OPENGL_OCTREE_FACE_SCALAR_FIELD__ #define __OPENGL_OCTREE_FACE_SCALAR_FIELD__ #include <PhysBAM_Tools/Arrays/ARRAYS_FORWARD.h> #include <PhysBAM_Rendering/PhysBAM_OpenGL/OpenGL/OPENGL_OBJECT.h> namespace PhysBAM{ template<class T> class OCTREE_GRID; template<class T> class OPENGL_COLOR_MAP; template<class T,class T2=T> class OPENGL_OCTREE_FACE_SCALAR_FIELD:public OPENGL_OBJECT { public: OCTREE_GRID<T>& grid; ARRAY<T2>& value; OPENGL_COLOR_MAP<T2>* color_map; int point_size; T line_size; bool draw_points; OPENGL_OCTREE_FACE_SCALAR_FIELD(OCTREE_GRID<T>& grid_input,ARRAY<T2>& value_input,OPENGL_COLOR_MAP<T2>* color_map_input,bool draw_points_input): grid(grid_input),value(value_input),color_map(color_map_input),point_size(5),line_size((T).025),draw_points(draw_points_input) {} void Scale_Vector_Size(const T scale) {line_size*=scale;} //##################################################################### void Display(const int in_color=1) const PHYSBAM_OVERRIDE; virtual void Update(){} virtual RANGE<VECTOR<float,3> > Bounding_Box() const PHYSBAM_OVERRIDE; void Print_Selection_Info(std::ostream& output_stream,OPENGL_SELECTION* current_selection) const PHYSBAM_OVERRIDE; //##################################################################### }; } #endif #endif
39.695652
148
0.635268
[ "vector" ]
735aea0195487efd8553332ce53287d42f787b0f
23,144
h
C
src/vw/Math/Functors.h
tkeemon/visionworkbench
df59fcb31191e1fc4fecfe1901963da1614a52b1
[ "NASA-1.3" ]
1
2020-06-02T04:06:43.000Z
2020-06-02T04:06:43.000Z
src/vw/Math/Functors.h
tkeemon/visionworkbench
df59fcb31191e1fc4fecfe1901963da1614a52b1
[ "NASA-1.3" ]
null
null
null
src/vw/Math/Functors.h
tkeemon/visionworkbench
df59fcb31191e1fc4fecfe1901963da1614a52b1
[ "NASA-1.3" ]
null
null
null
// __BEGIN_LICENSE__ // Copyright (C) 2006-2010 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ /// \file Math/Functors.h /// /// Mathematical functors. /// /// This file provides polymorphic functor versions of the standard /// mathematical functions defined in e.g. math.h. /// #ifndef __VW_MATH_FUNCTORS_H__ #define __VW_MATH_FUNCTORS_H__ #include <cstdlib> #include <limits> #include <complex> #include <vector> #include <algorithm> #include <vw/config.h> #include <vw/Core/CompoundTypes.h> #include <vw/Core/TypeDeduction.h> #include <vw/Core/Functors.h> #include <vw/Core/Exception.h> #include <vw/config.h> // The math.h header in FreeBSD (and possibly other platforms) does not // include routines for manipulating long doubles. We disable long // double VW math routines here for certain platforms. #if defined(__FreeBSD__) || defined(_WIN32) #define __VW_MATH_DISABLE_LONG_DOUBLE_ARITHMETIC #endif namespace vw { namespace math { template <class T> struct StdMathType { typedef double type; }; template <> struct StdMathType<float> { typedef float type; }; template <> struct StdMathType<long double> { typedef long double type; }; template <class T1, class T2> struct StdMathType2 { typedef typename StdMathType<typename PromoteType<T1,T2>::type>::type type; }; template <class FuncT, class ArgT, bool ArgIsCompound> struct ArgUnaryFunctorTypeHelper : public StdMathType<ArgT> {}; template <class FuncT, class ArgT> struct ArgUnaryFunctorTypeHelper<FuncT,ArgT,true> { typedef typename CompoundChannelType<ArgT>::type channel_type; typedef typename ArgUnaryFunctorTypeHelper<FuncT,channel_type,IsCompound<channel_type>::value>::type result_channel_type; typedef typename CompoundChannelCast<ArgT,result_channel_type>::type type; }; template <class F, class T> struct ArgUnaryFunctorType : public ArgUnaryFunctorTypeHelper<F,T,IsCompound<T>::value> {}; template <class FuncT, class Arg1T, class Arg2T, bool Arg1IsCompound, bool Arg2IsCompound> struct BinaryFunctorTypeHelper : public StdMathType2<Arg1T,Arg2T> {}; template <class FuncT, class Arg1T, class Arg2T> struct BinaryFunctorTypeHelper<FuncT,Arg1T,Arg2T,true,false> { typedef typename CompoundChannelType<Arg1T>::type channel_type; typedef typename BinaryFunctorTypeHelper<FuncT,channel_type,Arg2T,IsCompound<channel_type>::value,false>::type result_channel_type; typedef typename CompoundChannelCast<Arg1T,result_channel_type>::type type; }; template <class FuncT, class Arg1T, class Arg2T> struct BinaryFunctorTypeHelper<FuncT,Arg1T,Arg2T,false,true> { typedef typename CompoundChannelType<Arg2T>::type channel_type; typedef typename BinaryFunctorTypeHelper<FuncT,Arg1T,channel_type,false,IsCompound<channel_type>::value>::type result_channel_type; typedef typename CompoundChannelCast<Arg2T,result_channel_type>::type type; }; template <class FuncT, class Arg1T, class Arg2T> struct BinaryFunctorTypeHelper<FuncT,Arg1T,Arg2T,true,true> { typedef typename CompoundChannelType<Arg1T>::type channel1_type; typedef typename CompoundChannelType<Arg2T>::type channel2_type; typedef typename BinaryFunctorTypeHelper<FuncT,channel1_type,channel2_type,IsCompound<channel1_type>::value,IsCompound<channel2_type>::value>::type result_channel_type; typedef typename boost::mpl::if_<CompoundIsCompatible<Arg1T,Arg2T>, typename CompoundChannelCast<Arg1T,result_channel_type>::type, TypeDeductionError<BinaryFunctorTypeHelper> >::type type; }; template <class FuncT, class Arg1T, class Arg2T> struct BinaryFunctorType : public BinaryFunctorTypeHelper<FuncT,Arg1T,Arg2T,IsCompound<Arg1T>::value,IsCompound<Arg2T>::value> {}; // ******************************************************************** // Standard Mathematical Functors // ******************************************************************** #if !defined(__VW_MATH_DISABLE_LONG_DOUBLE_ARITHMETIC) // This will actually create a specialization for long doubles #define __VW_MATH_UNARY_LONG_DOUBLE_IMPL(func) \ long double operator()( long double arg ) const { \ return func##l(arg); \ } #define __VW_MATH_BINARY_LONG_DOUBLE_IMPL(func) \ long double operator()( long double arg1, long double arg2 ) const { \ return func##l(arg1,arg2); \ } #else // This is basically a no-op #define __VW_MATH_UNARY_LONG_DOUBLE_IMPL(func) #define __VW_MATH_BINARY_LONG_DOUBLE_IMPL(func) #endif #define __VW_UNARY_MATH_FUNCTOR(name,func) \ struct Arg##name##Functor \ : UnaryReturnBinaryTemplateBind1st<ArgUnaryFunctorType,Arg##name##Functor> { \ template <class ValT> \ typename ArgUnaryFunctorType<Arg##name##Functor,ValT>::type \ operator()( ValT arg ) const { \ return func(arg); \ } \ float operator()( float arg ) const { \ return func##f(arg); \ } \ __VW_MATH_UNARY_LONG_DOUBLE_IMPL(func) \ }; \ using ::func; #define __VW_BINARY_MATH_FUNCTOR(name,func) \ struct ArgArg##name##Functor \ : BinaryReturnTernaryTemplateBind1st<BinaryFunctorType,ArgArg##name##Functor> { \ float operator()( float arg1, float arg2 ) const { \ return func##f(arg1,arg2); \ } \ __VW_MATH_BINARY_LONG_DOUBLE_IMPL(func) \ template <class Arg1T, class Arg2T> \ typename BinaryFunctorType<ArgArg##name##Functor,Arg1T,Arg2T>::type \ inline operator()( Arg1T const& arg1, Arg2T const& arg2 ) const { \ return func( arg1, arg2 ); \ } \ }; \ template <class ValT> \ struct ArgVal##name##Functor \ : UnaryReturnTernaryTemplateBind1st3rd<BinaryFunctorType,ArgArg##name##Functor,ValT> { \ ValT m_val; \ ArgVal##name##Functor(ValT val) : m_val(val) {} \ template <class ArgT> \ typename BinaryFunctorType<ArgArg##name##Functor,ArgT,ValT>::type \ inline operator()( ArgT const& arg ) const { \ return ArgArg##name##Functor()( arg, m_val ); \ } \ }; \ template <class ValT> \ struct ValArg##name##Functor \ : UnaryReturnTernaryTemplateBind1st2nd<BinaryFunctorType,ArgArg##name##Functor,ValT> { \ ValT m_val; \ ValArg##name##Functor(ValT val) : m_val(val) {} \ template <class ArgT> \ typename BinaryFunctorType<ArgArg##name##Functor,ValT,ArgT>::type \ inline operator()( ArgT const& arg ) const { \ return ArgArg##name##Functor()( m_val, arg ); \ } \ }; \ using ::func; __VW_UNARY_MATH_FUNCTOR( Fabs, fabs ) __VW_UNARY_MATH_FUNCTOR( Acos, acos ) __VW_UNARY_MATH_FUNCTOR( Asin, asin ) __VW_UNARY_MATH_FUNCTOR( Atan, atan ) __VW_UNARY_MATH_FUNCTOR( Cos, cos ) __VW_UNARY_MATH_FUNCTOR( Sin, sin ) __VW_UNARY_MATH_FUNCTOR( Tan, tan ) __VW_UNARY_MATH_FUNCTOR( Cosh, cosh ) __VW_UNARY_MATH_FUNCTOR( Sinh, sinh ) __VW_UNARY_MATH_FUNCTOR( Tanh, tanh ) __VW_UNARY_MATH_FUNCTOR( Exp, exp ) __VW_UNARY_MATH_FUNCTOR( Log, log ) __VW_UNARY_MATH_FUNCTOR( Log10, log10 ) __VW_UNARY_MATH_FUNCTOR( Sqrt, sqrt ) __VW_UNARY_MATH_FUNCTOR( Ceil, ceil ) __VW_UNARY_MATH_FUNCTOR( Floor, floor ) __VW_BINARY_MATH_FUNCTOR( Atan2, atan2 ) __VW_BINARY_MATH_FUNCTOR( Pow, pow ) __VW_BINARY_MATH_FUNCTOR( Hypot, hypot ) #ifndef WIN32 __VW_UNARY_MATH_FUNCTOR( Acosh, acosh ) __VW_UNARY_MATH_FUNCTOR( Asinh, asinh ) __VW_UNARY_MATH_FUNCTOR( Atanh, atanh ) #ifdef VW_HAVE_EXP2 __VW_UNARY_MATH_FUNCTOR( Exp2, exp2 ) #endif #ifdef VW_HAVE_LOG2 __VW_UNARY_MATH_FUNCTOR( Log2, log2 ) #endif #ifdef VW_HAVE_TGAMMA __VW_UNARY_MATH_FUNCTOR( Tgamma, tgamma ) #endif __VW_UNARY_MATH_FUNCTOR( Lgamma, lgamma ) __VW_UNARY_MATH_FUNCTOR( Expm1, expm1 ) __VW_UNARY_MATH_FUNCTOR( Log1p, log1p ) __VW_UNARY_MATH_FUNCTOR( Cbrt, cbrt ) __VW_UNARY_MATH_FUNCTOR( Erf, erf ) __VW_UNARY_MATH_FUNCTOR( Erfc, erfc ) __VW_UNARY_MATH_FUNCTOR( Round, round ) __VW_UNARY_MATH_FUNCTOR( Trunc, trunc ) __VW_BINARY_MATH_FUNCTOR( Copysign, copysign ) __VW_BINARY_MATH_FUNCTOR( Fdim, fdim ) #endif #undef __VW_UNARY_MATH_FUNCTOR #undef __VW_BINARY_MATH_FUNCTOR // Real part functor struct ArgRealFunctor : UnaryReturnTemplateType<MakeReal> { template <class ValT> ValT operator()( ValT const& val ) const { return val; } template <class ValT> ValT operator()( std::complex<ValT> const& val ) const { return std::real(val); } }; // Imaginary part functor struct ArgImagFunctor : UnaryReturnTemplateType<MakeReal> { template <class ValT> ValT operator()( ValT const& /*val*/ ) const { return ValT(); } template <class ValT> ValT operator()( std::complex<ValT> const& val ) const { return std::imag(val); } }; // Absolute value functor // This one's tricky because we have a bunch of distinct cases // for integer types, floating-point types, and complex types. /// \cond INTERNAL // This is outside ArgAbsFunctor because explicit template // specialization doesn't work at class scope. template <bool IntegralN> struct DefaultAbsBehavior { template <class ValT> static inline int apply( ValT val ) { return std::abs(val); } }; template <> struct DefaultAbsBehavior<false> { template <class ValT> static inline double apply( ValT val ) { return fabs(val); } }; /// \endcond struct ArgAbsFunctor { template <class Args> struct result; template <class FuncT, class ValT> struct result<FuncT(ValT)> { typedef typename boost::mpl::if_c<std::numeric_limits<ValT>::is_integer, int, double>::type type; }; template <class FuncT> struct result<FuncT(float)> { typedef float type; }; template <class FuncT> struct result<FuncT(long double)> { typedef long double type; }; template <class FuncT> struct result<FuncT(long)> { typedef long type; }; template <class FuncT> struct result<FuncT(long long)> { typedef long long type; }; template <class FuncT, class ValT> struct result<FuncT(std::complex<ValT>)> { typedef ValT type; }; template <class ValT> typename result<ArgAbsFunctor(ValT)>::type inline operator()( ValT val ) const { return DefaultAbsBehavior<std::numeric_limits<ValT>::is_integer>::apply(val); } inline float operator()( float val ) const { return ::fabsf(val); } inline long operator()( long val ) const { return std::labs(val); } #ifdef VW_HAVE_FABSL inline long double operator()( long double val ) const { return ::fabsl(val); } #endif #ifdef VW_HAVE_LLABS inline long long operator()( long long val ) const { return ::llabs(val); } #endif template <class ValT> inline ValT operator()( std::complex<ValT> const& val ) const { return std::abs(val); } }; // Complex conjugation functor struct ArgConjFunctor : UnaryReturnSameType { template <class ValT> ValT operator()( ValT const& val ) const { return val; } template <class ValT> std::complex<ValT> operator()( std::complex<ValT> const& val ) const { return std::conj(val); } }; // General-purpose accumulation functor template <class AccumT, class FuncT = ArgArgInPlaceSumFunctor> struct Accumulator : ReturnFixedType<AccumT const&> { private: AccumT m_accum; FuncT m_func; public: typedef AccumT value_type; Accumulator() : m_accum(), m_func() {} Accumulator( FuncT const& func ) : m_accum(), m_func(func) {} Accumulator( AccumT const& accum ) : m_accum(accum), m_func() {} Accumulator( AccumT const& accum, FuncT const& func ) : m_accum(accum), m_func(func) {} template <class ArgT> inline AccumT const& operator()( ArgT const& arg ) { m_func(m_accum, arg); return m_accum; } inline AccumT const& value() const { return m_accum; } void reset( AccumT const& accum = AccumT() ) { m_accum = accum; } }; // Computes minimum and maximum values template <class ValT> class MinMaxAccumulator : public ReturnFixedType<void> { ValT m_minval, m_maxval; bool m_valid; public: typedef std::pair<ValT,ValT> value_type; MinMaxAccumulator() : m_minval(0), m_maxval(0), m_valid(false) {} void operator()( ValT const& arg ) { if ( ! m_valid ) { m_minval = m_maxval = arg; m_valid = true; } else { if( arg < m_minval ) m_minval = arg; if( m_maxval < arg ) m_maxval = arg; } } ValT minimum() const { VW_ASSERT(m_valid, ArgumentErr() << "MinMaxAccumulator: no valid samples"); return m_minval; } ValT maximum() const { VW_ASSERT(m_valid, ArgumentErr() << "MinMaxAccumulator: no valid samples"); return m_maxval; } std::pair<ValT,ValT> value() const { VW_ASSERT(m_valid, ArgumentErr() << "MinMaxAccumulator: no valid samples"); return std::make_pair(m_minval,m_maxval); } }; // Computes the median of the values to which it is applied. template <class ValT> class MedianAccumulator : public ReturnFixedType<void> { std::vector<ValT> m_values; public: typedef ValT value_type; void operator()( ValT const& value ) { m_values.push_back( value ); } ValT const& value() { VW_ASSERT(m_values.size(), ArgumentErr() << "MedianAccumulator: no valid samples"); sort(m_values.begin(), m_values.end()); return m_values[m_values.size()/2]; } }; // Computes the mean of the values to which it is applied. template <class ValT> class MeanAccumulator : public ReturnFixedType<void> { typedef typename CompoundChannelCast<ValT,double>::type accum_type; accum_type m_accum; double m_count; public: typedef accum_type value_type; MeanAccumulator() : m_accum(), m_count() {} void operator()( ValT const& value ) { m_accum += value; m_count += 1.0; } value_type value() const { VW_ASSERT(m_count, ArgumentErr() << "MeanAccumulator: no valid samples"); return m_accum / m_count; } }; // Computes the standard deviation of the values to which it is applied. template <class ValT> class StdDevAccumulator : public ReturnFixedType<void> { typedef typename CompoundChannelCast<ValT,double>::type accum_type; accum_type mom1_accum, mom2_accum; double num_samples; public: typedef accum_type value_type; StdDevAccumulator() : mom1_accum(), mom2_accum(), num_samples() {} void operator()( ValT const& arg ) { mom1_accum += arg; mom2_accum += (accum_type) arg * arg; num_samples += 1.0; } value_type value() const { VW_ASSERT(num_samples, ArgumentErr() << "StdDevAccumulator(): no valid samples."); return sqrt(mom2_accum/num_samples - (mom1_accum/num_samples)*(mom1_accum/num_samples)); } }; // CDF (Cumulative Distribution Function) Accumulator // Actually it's an approximation. It allows for a more memory efficient // calculation of any quantile. Probably most importantly the median. // // Taken from Numerical Recipes (3rd E) pg 435 template <class ValT> class CDFAccumulator : public ReturnFixedType<void> { size_t m_buffersize, m_num_quantiles, m_buffer_idx; size_t m_num_samples; // nq, nd, nt std::vector<double> m_cdf, m_sample_buf, m_quantile; double m_q0, m_qm; // quantile min and max; public: CDFAccumulator( size_t buffersize = 1000, size_t quantiles = 251) { this->resize( buffersize, quantiles ); } // Allow user to change post constructor (see ChannelAccumulator) void resize( size_t buffersize, size_t quantiles ) { VW_ASSERT(quantiles > 0, LogicErr() << "Cannot have 0 quantiles"); m_buffersize = buffersize; m_buffer_idx = m_num_samples = 0; m_sample_buf.resize( m_buffersize ); m_q0 = std::numeric_limits<double>::max(); m_qm = -std::numeric_limits<double>::max(); m_num_quantiles = quantiles; if ( !(quantiles%2) ) m_num_quantiles++; m_quantile.resize(m_num_quantiles); m_cdf.resize(m_num_quantiles); // Setting a generic cdf to start things off, where 80% of the // distribution is in the middle third. size_t third = m_num_quantiles/3; size_t third2 = third*2; double slope = 10.0 / double(third); double first_tertile_gain = 1.0 - slope; // Filling middle for ( size_t j = third; j <= third2; j++ ) m_cdf[j] = 0.8*(double(j-third)/double(third2-third))+0.1; // Filling first tertile for ( ssize_t j = third-1; j >= 0; j-- ) m_cdf[j] = first_tertile_gain*m_cdf[j+1]; // Filling third tertile for ( size_t j = third2+1; j < m_num_quantiles; j++ ) m_cdf[j] = 1.0 - first_tertile_gain*(1.0-m_cdf[j-1]); } // Merge in Bundles void update() { size_t jd=0, jq=1; double target, told=0, tnew=0, qold, qnew; std::vector<double> m_new_quantile(m_num_quantiles); std::sort( m_sample_buf.begin(), m_sample_buf.begin()+m_buffer_idx ); // For partial updates // Setting to global min and max; qold = qnew = m_quantile[0] = m_new_quantile[0] = m_q0; m_quantile.back() = m_new_quantile.back() = m_qm; // .. then setting comparable probabilities m_cdf[0] = std::min(0.5/(m_buffer_idx+m_num_samples), 0.5*m_cdf[1]); m_cdf.back() = std::max(1-0.5/(m_buffer_idx+m_num_samples), 0.5*(1+m_cdf[m_num_quantiles-2])); // Looping over target probability values for interpolation for ( size_t iq = 1; iq < m_num_quantiles-1; iq++ ) { target = (m_num_samples+m_buffer_idx)*m_cdf[iq]; if ( tnew < target ) while (1) { // Locating a succession of abscissa-ordinate pairs // (qnew,tnew) that are the discontinuities of value or // slope, breaking to perform an interpolation as we cross // each target. if ( jq < m_num_quantiles && ( jd >= m_buffer_idx || m_quantile[jq] < m_sample_buf[jd] ) ) { // Found slope discontinuity from old CDF. qnew = m_quantile[jq]; tnew = jd + m_num_samples*m_cdf[jq++]; if ( tnew >= target ) break; } else { // Found value discontinuity from batch data CDF. qnew = m_sample_buf[jd]; tnew = told; if ( m_quantile[jq] > m_quantile[jq-1] ) tnew += m_num_samples*(m_cdf[jq]-m_cdf[jq-1])* (qnew-qold)/(m_quantile[jq]-m_quantile[jq-1]); jd++; if ( tnew >= target ) break; told = tnew++; qold = qnew; if ( tnew >= target ) break; } told = tnew; qold = qnew; } // Performing new interpolation if ( tnew == told ) m_new_quantile[iq] = 0.5*(qold+qnew); else m_new_quantile[iq] = qold + (qnew-qold)*(target-told)/(tnew-told); told = tnew; qold = qnew; } // Reset'n m_quantile = m_new_quantile; m_num_samples += m_buffer_idx; m_buffer_idx = 0; } // User update function. (Bundles Data) void operator()( ValT const& arg ) { // Assimilate, We are the Borg, your data is my data! m_sample_buf[m_buffer_idx++] = arg; if ( arg < m_q0 ) { m_q0 = arg; } // stretch cdf? if ( arg > m_qm ) { m_qm = arg; } if ( m_buffer_idx == m_buffersize ) update(); // merge cdf? } // Extract a percentile ValT quantile( double const& arg ) const { double q; // if ( m_buffer_idx > 0 ) update(); size_t jl=0,jh=m_num_quantiles-1,j; while ( jh - jl > 1 ) { j = (jh+jl)>>1; if ( arg > m_cdf[j] ) jl=j; else jh=j; } j = jl; q = m_quantile[j]+(m_quantile[j+1]-m_quantile[j])*(arg-m_cdf[j])/(m_cdf[j+1]-m_cdf[j]); // Keeping estimate in CDF return std::max(m_quantile[0],std::min(m_quantile.back(),q)); } // Predefine functions ValT median() const { return quantile(0.5); } ValT first_quartile() const { return quantile(0.25); } ValT third_quartile() const { return quantile(0.75); } ValT approximate_mean( float const& stepping = 0.1 ) const { ValT mean = 0; size_t count = 0; for ( float i = stepping; i < 1+stepping; i+=stepping ) { count++; mean += ( quantile(i) + quantile(i-stepping) ) / 2.0; } return mean / ValT(count); } ValT approximate_stddev( float const& stepping = 0.1 ) const { ValT mean = approximate_mean(stepping); ValT stddev = 0; size_t count = 0; for ( float i = stepping; i < 1+stepping; i+=stepping ) { count++; stddev += pow((quantile(i) + quantile(i-stepping))/2-mean,2); } return sqrt(stddev/ValT(count)); } }; } // namespace math // I'm not even really sure why the math namespace exists anymore.... -MDH using math::Accumulator; using math::MinMaxAccumulator; using math::MedianAccumulator; using math::MeanAccumulator; using math::StdDevAccumulator; } // namespace vw #endif // __VW_MATH_FUNCTORS_H__
37.878887
192
0.608495
[ "vector" ]
736253a269f8062e1f353f09e13a264ca76ae57d
5,523
h
C
src/machine/cpu/Moira/MoiraDataflow.h
elmerucr/E64-II
47115cba99630cd0890768e8657e1fabba6c2c3b
[ "MIT" ]
2
2021-02-02T19:28:02.000Z
2021-11-28T20:14:28.000Z
src/machine/cpu/Moira/MoiraDataflow.h
elmerucr/E64-II
47115cba99630cd0890768e8657e1fabba6c2c3b
[ "MIT" ]
null
null
null
src/machine/cpu/Moira/MoiraDataflow.h
elmerucr/E64-II
47115cba99630cd0890768e8657e1fabba6c2c3b
[ "MIT" ]
null
null
null
// ----------------------------------------------------------------------------- // This file is part of Moira - A Motorola 68k emulator // // Copyright (C) Dirk W. Hoffmann. www.dirkwhoffmann.de // Licensed under the GNU General Public License v3 // // See https://www.gnu.org for license information // ----------------------------------------------------------------------------- /* Moira utilizes a three layer design to model dataflow inside the processor. * * Layer 1: Main entry points. Most instruction execution handlers call a * layer 1 function to read or write their operands. * * Layer 2: Data providers. This layer provides functions for moving data back * and forth between various locations. * * Layer 3: Memory interface. The functions from this layer perform the actual * memory access. * * The following picture depicts the interplay between the different layers: * * | * - - - - - - - - - - - - - - - - - - -|- - - - - - - - - - - - - - - - - - - - * Layer 1: V * readOp * (writeOp) * | * Addressing Mode M = 0---1---2---3---4---5---6---7---8---9---A---B * / | | | | | | | | | | \ * / | --------------------------------- \ * / | | \ * / | V \ * / | computeEA ----------- \ * / | | | \ * - - - - - - - -|- - - - -|- - - - - -|- - - - - - - -|- - - - - - - - -|- - - * Layer 2: | | | V | * | | | readExt | * V V V V * readD readA readM -----> addressError readI * (writeD) (writeA) (writeM) * | * updateAn() * | * - - - - - - - - - - - - - - - - - - -|- - - - - - - - - - - - - - - - - - - - * Layer 3: | * Size S = B-----------W-----------L * | | | * V V V * read8 read16 2 x read16 * (write8) (write8) (2 x write16) * */ /* Reads an operand * * The source of the operand is determined by the addressing mode M. If the * operand is read from memory, the effective address is stored in variable ea. * If the source is a register or an immediate value, variable ea remains * untouched. */ template<Mode M, Size S, Flags F = 0> bool readOp(int n, u32 &ea, u32 &result); /* Writes an operand * * If parameter ea is omitted, the destination of the operand is determined * by the addressing mode M. Parameter 'last' indicates if this function is * initiates the last memory bus cycle of an instruction. */ template<Mode M, Size S, Flags F = 0> bool writeOp(int n, u32 val); template<Mode M, Size S, Flags F = 0> void writeOp(int n, u32 ea, u32 val); // Computes an effective address template<Mode M, Size S, Flags F = 0> u32 computeEA(u32 n); // Emulates the address register modification for modes (An)+, (An)- template<Mode M, Size S> void updateAn(int n); template<Mode M, Size S> void updateAnPD(int n); template<Mode M, Size S> void undoAnPD(int n); template<Mode M, Size S> void updateAnPI(int n); // Reads a value from a specific memory space template<MemSpace M, Size S, Flags F = 0> u32 readM(u32 addr); template<MemSpace M, Size S, Flags F = 0> u32 readM(u32 addr, bool &error); // Reads a value from program or data space, depending on the addressing mode template<Mode M, Size S, Flags F = 0> u32 readM(u32 addr); template<Mode M, Size S, Flags F = 0> u32 readM(u32 addr, bool &error); // Writes a value to a specific memory space template<MemSpace M, Size S, Flags F = 0> void writeM(u32 addr, u32 val); template<MemSpace M, Size S, Flags F = 0> void writeM(u32 addr, u32 val, bool &error); // Writes an operand to memory (without or with address error checking) template<Mode M, Size S, Flags F = 0> void writeM(u32 addr, u32 val); template<Mode M, Size S, Flags F = 0> void writeM(u32 addr, u32 val, bool &error); // Reads an immediate value from memory template<Size S> u32 readI(); // Pushes a value onto the stack template<Size S, Flags F = 0> void push(u32 value); template<Size S, Flags F = 0> void push(u32 value, bool &error); // Checks whether the provided address should trigger an address error template<Size S = Word> bool misaligned(u32 addr); // Creates an address error stack frame template<Flags F = 0> AEStackFrame makeFrame(u32 addr, u32 pc, u16 sr, u16 ird); template<Flags F = 0> AEStackFrame makeFrame(u32 addr, u32 pc); template<Flags F = 0> AEStackFrame makeFrame(u32 addr); // Prefetches the next instruction template<Flags F = 0> void prefetch(); // Performs a full prefetch cycle template<Flags F = 0, int delay = 0> void fullPrefetch(); // Reads an extension word from memory void readExt(); // Jumps to an exception vector template<Flags F = 0> void jumpToVector(int nr);
44.540323
86
0.502082
[ "vector", "model" ]
736e201cfd50131691f8a1e7145ed82bb5f893c1
2,010
h
C
src/Triangle.h
Stibius/RayTracer
d71e6de6d5607cf705db56c095e9381ad26c62d0
[ "Unlicense" ]
null
null
null
src/Triangle.h
Stibius/RayTracer
d71e6de6d5607cf705db56c095e9381ad26c62d0
[ "Unlicense" ]
null
null
null
src/Triangle.h
Stibius/RayTracer
d71e6de6d5607cf705db56c095e9381ad26c62d0
[ "Unlicense" ]
null
null
null
#pragma once #include "LeafShape.h" class Triangle : public LeafShape { private: Vector m_v1, m_v2, m_v3; Vector m_n1, m_n2, m_n3; public: static std::string DESCRIPTION_LABEL; Triangle() = default; Triangle(const Vector& v1, const Vector& v2, const Vector& v3, ComponentShape* parent, const Material* material, const std::string& name = ""); Triangle(const Vector& v1, const Vector& v2, const Vector& v3, const Vector& n1, const Vector& n2, const Vector& n3, ComponentShape* parent, const Material* material, const std::string& name = ""); Triangle(const std::string& description, const std::vector<Material*>& materials); Triangle(const Triangle& other) = default; Triangle(Triangle&& other) = default; Triangle& operator=(const Triangle& other) = default; Triangle& operator=(Triangle&& other) = default; ~Triangle() override = default; Intersection getIntersection(const Ray& ray) const override; Intersection getIntersectionSmooth(const Ray& ray) const; std::vector<Intersection> getIntersections(const Ray& ray) const override; std::vector<Intersection> getIntersectionsSmooth(const Ray& ray) const; bool clipsPoint(const Vector& point) const override; const Vector& getV1() const; const Vector& getV2() const; const Vector& getV3() const; const Vector& getN1() const; const Vector& getN2() const; const Vector& getN3() const; std::unique_ptr<ComponentShape> clone() const override; std::string toDescription() const override; void setV1(const Vector& v1); void setV2(const Vector& v2); void setV3(const Vector& v3); void setN1(const Vector& n1); void setN2(const Vector& n2); void setN3(const Vector& n3); void fromDescription(const std::string& description, const std::vector<Material*>& materials) override; void translate(const Vector& translation) override; void rotate(double degrees, const Vector& axis) override; void scale(const Vector& scaleFactors) override; };
24.814815
201
0.716418
[ "vector" ]
73883668b1ad1ea9ab474241a5e8437ff0fe690c
963
h
C
Brio/src/Brio.h
Ckyre/brio
77a41a2a9d16c20542b60b2425e44525d3f4eef8
[ "Apache-2.0" ]
null
null
null
Brio/src/Brio.h
Ckyre/brio
77a41a2a9d16c20542b60b2425e44525d3f4eef8
[ "Apache-2.0" ]
null
null
null
Brio/src/Brio.h
Ckyre/brio
77a41a2a9d16c20542b60b2425e44525d3f4eef8
[ "Apache-2.0" ]
null
null
null
#pragma once #include "Brio/Core/Core.h" #include "Brio/Core/Application.h" #include "Brio/Core/Layer.h" #include "Brio/Core/Log.h" #include "Brio/Core/Timestep.h" // ---- Input ------------------------------- #include "Brio/Core/Input.h" #include "Brio/Core/KeyCodes.h" #include "Brio/Core/MouseCodes.h" // --------------------------------------------- #include "Brio/Renderer/Camera/CameraController.h" #include "Brio/ImGui/ImGuiLayer.h" #include "Brio/Scene/Scene.h" #include "Brio/Scene/Entity.h" #include "Brio/Scene/Component.h" // ---- Renderer ------------------------------- #include "Brio/Renderer/Renderer.h" #include "Brio/Renderer/RenderCommand.h" #include "Brio/Renderer/Buffer.h" #include "Brio/Renderer/Shader.h" #include "Brio/Renderer/FrameBuffer.h" #include "Brio/Renderer/Texture.h" #include "Brio/Renderer/Material.h" #include "Brio/Renderer/Mesh.h" #include "Brio/Renderer/Skybox.h" // ---------------------------------------------
26.027027
50
0.616822
[ "mesh" ]
4cd1da46a7967c753364e9589c2afef652ad7133
4,568
h
C
stage5/02-installqtlibs/qt5.15/include/QtQuick3D/5.15.1/QtQuick3D/private/qquick3dcustommaterial_p.h
damir1996iz/tabletos
bfc2f650e3291ce63f083bcf36e81392341fbc40
[ "BSD-3-Clause" ]
null
null
null
stage5/02-installqtlibs/qt5.15/include/QtQuick3D/5.15.1/QtQuick3D/private/qquick3dcustommaterial_p.h
damir1996iz/tabletos
bfc2f650e3291ce63f083bcf36e81392341fbc40
[ "BSD-3-Clause" ]
null
null
null
stage5/02-installqtlibs/qt5.15/include/QtQuick3D/5.15.1/QtQuick3D/private/qquick3dcustommaterial_p.h
damir1996iz/tabletos
bfc2f650e3291ce63f083bcf36e81392341fbc40
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2019 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qt Quick 3D. ** ** $QT_BEGIN_LICENSE:GPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 or (at your option) any later version ** approved by the KDE Free Qt Foundation. The licenses are as published by ** the Free Software Foundation and appearing in the file LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QSSGCUSTOMMATERIAL_H #define QSSGCUSTOMMATERIAL_H // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // We mean it. // #include <QtQuick3D/private/qquick3dmaterial_p.h> #include <QtCore/qvector.h> #include <QtQuick3DRender/private/qssgrenderbasetypes_p.h> #include <QtQuick3DRuntimeRender/private/qssgrendergraphobject_p.h> #include <QtQuick3DRuntimeRender/private/qssgrenderdynamicobjectsystemcommands_p.h> #include <QtQuick3D/private/qquick3dshaderutils_p.h> QT_BEGIN_NAMESPACE class Q_QUICK3D_EXPORT QQuick3DCustomMaterial : public QQuick3DMaterial { Q_OBJECT Q_PROPERTY(bool hasTransparency READ hasTransparency WRITE setHasTransparency NOTIFY hasTransparencyChanged) Q_PROPERTY(bool hasRefraction READ hasRefraction WRITE setHasRefraction NOTIFY hasRefractionChanged) Q_PROPERTY(bool alwaysDirty READ alwaysDirty WRITE setAlwaysDirty NOTIFY alwaysDirtyChanged) Q_PROPERTY(QQuick3DShaderUtilsShaderInfo *shaderInfo READ shaderInfo WRITE setShaderInfo) Q_PROPERTY(QQmlListProperty<QQuick3DShaderUtilsRenderPass> passes READ passes) public: explicit QQuick3DCustomMaterial(QQuick3DObject *parent = nullptr); ~QQuick3DCustomMaterial() override; bool hasTransparency() const; bool hasRefraction() const; bool alwaysDirty() const; QQuick3DShaderUtilsShaderInfo *shaderInfo() const; QQmlListProperty<QQuick3DShaderUtilsRenderPass> passes(); public Q_SLOTS: void setHasTransparency(bool hasTransparency); void setHasRefraction(bool hasRefraction); void setShaderInfo(QQuick3DShaderUtilsShaderInfo *shaderInfo); void setAlwaysDirty(bool alwaysDirty); Q_SIGNALS: void hasTransparencyChanged(bool hasTransparency); void hasRefractionChanged(bool hasRefraction); void alwaysDirtyChanged(bool alwaysDirty); protected: QSSGRenderGraphObject *updateSpatialNode(QSSGRenderGraphObject *node) override; void markAllDirty() override; private Q_SLOTS: void onPropertyDirty(); void onTextureDirty(QQuick3DShaderUtilsTextureInput *texture); private: enum Dirty { TextureDirty = 0x1, PropertyDirty = 0x2 }; // Passes static void qmlAppendPass(QQmlListProperty<QQuick3DShaderUtilsRenderPass> *list, QQuick3DShaderUtilsRenderPass *pass); static QQuick3DShaderUtilsRenderPass *qmlPassAt(QQmlListProperty<QQuick3DShaderUtilsRenderPass> *list, int index); static int qmlPassCount(QQmlListProperty<QQuick3DShaderUtilsRenderPass> *list); static void qmlPassClear(QQmlListProperty<QQuick3DShaderUtilsRenderPass> *list); void markDirty(QQuick3DCustomMaterial::Dirty type) { if (!(m_dirtyAttributes & quint32(type))) { m_dirtyAttributes |= quint32(type); update(); } } quint32 m_dirtyAttributes = 0xffffffff; bool m_hasTransparency = false; bool m_hasRefraction = false; QQuick3DShaderUtilsShaderInfo *m_shaderInfo = nullptr; QVector<QQuick3DShaderUtilsRenderPass *> m_passes; bool m_alwaysDirty = false; }; QT_END_NAMESPACE #endif // QSSGCUSTOMMATERIAL_H
36.253968
122
0.74387
[ "3d" ]
4cdea5020402a46ecf846dda6e1b2c78a35a7b18
3,474
h
C
includes/encryptedMessage.h
gshimabuko/cryptopals1_3
9183b377b22c13e81abacde4cdcf6e32a81d7231
[ "Unlicense" ]
null
null
null
includes/encryptedMessage.h
gshimabuko/cryptopals1_3
9183b377b22c13e81abacde4cdcf6e32a81d7231
[ "Unlicense" ]
null
null
null
includes/encryptedMessage.h
gshimabuko/cryptopals1_3
9183b377b22c13e81abacde4cdcf6e32a81d7231
[ "Unlicense" ]
null
null
null
/********************************************************************************* * @copyright Copyright (c) 2021 by Guilherme Shimabuko - Shima's Digital Hardware * * 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 Shima's DIgital Hardware 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 PARTI- * CULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SHIMA'S DIGITAL HARDWARE * 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 encryptedMessage.h * @brief Implementation of class abstraction for encrypted messages. * * @details This file implements a Encrypted message class that holds the original * encrypted message, a decrypted message, and two scores that define the likelyhood * of a decoded string being a real message in the English language. * This class will also include functions to decode the message and to calculate * said scores, to set the encoded message and to get the scores. * * The implemented functions are as followed: * * @author Guilherme Shimabuko * * date of last update in yy-mm-dd format * * @date 2021-09-10 * * @version 1.00 * * Version History * * Version Date Author Changes * * 1.00 2021-09-10 GSHIMABUKO Class implementation * ********************************************************************************* */ #ifndef __ENCRYPTEDMESSAGE__ #define __ENCRYPTEDMESSAGE__ #include <vector> class encryptedMessage { private: std::vector <unsigned char> encodedMessage; std::vector <unsigned char> decodedMessage; // float charScore; // float statScore; public: void setEncodedMessage(std::string message); void decodeMessage(std::vector<unsigned char> keyVector); // void computeCharScore(); // void computeStatScore(); // std::string getEncodedMessage(); std::string getDecodedMessage(); // float getCharScore(); // float getStatScore(); // float getTotalScore(); }; #endif /* __ENCRYPTEDMESSAGE__ */
40.870588
84
0.645653
[ "vector" ]
4ceff2ca3310ef3de5af7e7d1d559556818eba7a
2,890
h
C
include/s2mIMUs.h
ValentinAllard/biorbd
fd9a39eb624a56966a76d9d77cf951c09db79d31
[ "MIT" ]
null
null
null
include/s2mIMUs.h
ValentinAllard/biorbd
fd9a39eb624a56966a76d9d77cf951c09db79d31
[ "MIT" ]
1
2019-08-02T08:46:38.000Z
2019-08-02T08:46:38.000Z
include/s2mIMUs.h
ValentinAllard/biorbd
fd9a39eb624a56966a76d9d77cf951c09db79d31
[ "MIT" ]
null
null
null
#ifndef S2M_IMUS_H #define S2M_IMUS_H #include <vector> #include "biorbdConfig.h" #include "s2mAttitude.h" #include "s2mString.h" #include "s2mNode.h" #include "s2mPatch.h" class s2mJoints; class s2mIMU; class s2mGenCoord; class s2mMatrix; class BIORBD_API s2mIMUs { public: s2mIMUs(); virtual ~s2mIMUs(); // Set and get void addIMU(const s2mAttitude &pos = s2mAttitude(), const s2mString &name = "", const s2mString &parentName = "", const bool &technical = true, const bool &anatomical = false, const int &id = -1); // Ajouter un nouveau marker unsigned int nIMUs() const; // Retourne le nombre de marqueurs std::vector<s2mString> IMUsNames(); std::vector<s2mString> technicalIMUsNames(); std::vector<s2mString> anatomicalIMUsNames(); std::vector<s2mIMU> IMU(); // Retour d'un STL vector de tous les IMU std::vector<s2mIMU> IMU(s2mJoints& m, unsigned int idx); // Retour d'un STL vector de tous les IMU d'un segment idx const s2mIMU& IMU(const unsigned int&); // Retour d'un IMU ind idx std::vector<s2mIMU> IMU(s2mJoints& model, const s2mGenCoord &Q, const bool &updateKin = true); // Retour d'un STL vector de tous les IMUs s2mIMU IMU(s2mJoints& model, const s2mGenCoord&, const unsigned int&, const bool &updateKin = true); // Retour d'un IMU ind idx std::vector<s2mIMU> segmentIMU(s2mJoints& model, const s2mGenCoord&, const unsigned int&, const bool &updateKin = true); // Retour d'un STL vector de tous les IMUs d'un segment unsigned int nTechIMUs(); // Retourne le nombre de marqueurs techniques unsigned int nAnatIMUs(); // Retourne le nombre de marqueurs anatomiques std::vector<s2mIMU> technicalIMU(s2mJoints& model, const s2mGenCoord &Q, bool updateKin = true); // Retour d'un STL vector de tous les IMUs std::vector<s2mIMU> technicalIMU(); // Retour d'un STL vector de tous les IMUs std::vector<s2mIMU> anatomicalIMU(s2mJoints& model, const s2mGenCoord &Q, bool updateKin = true); // Retour d'un STL vector de tous les IMUs std::vector<s2mIMU> anatomicalIMU(); // Retour d'un STL vector de tous les IMUs std::vector<s2mMatrix> IMUJacobian(s2mJoints& model, const s2mGenCoord &Q, const bool &updateKin = true); // Retourne la jacobienne des Tags std::vector<s2mMatrix> TechnicalIMUJacobian(s2mJoints& model, const s2mGenCoord &Q, const bool &updateKin = true); // Retourne la jacobienne des Tags pour les marqueurs techniques protected: std::vector<s2mMatrix> IMUJacobian(s2mJoints& model, const s2mGenCoord &Q, const bool &updateKin, bool lookForTechnical); // Retourne la jacobienne des Tags std::vector <s2mIMU> m_IMUs; }; #endif // S2M_IMUS_H
45.15625
187
0.669204
[ "vector", "model" ]
4cfb4050efd5315b19a95c41fd195c72d204a340
2,738
h
C
GlkView/GlkHub.h
Logicalshift/CocoaGlk
e8f21057ba6f5beb9a8a17149c224f9593821af6
[ "MIT" ]
null
null
null
GlkView/GlkHub.h
Logicalshift/CocoaGlk
e8f21057ba6f5beb9a8a17149c224f9593821af6
[ "MIT" ]
null
null
null
GlkView/GlkHub.h
Logicalshift/CocoaGlk
e8f21057ba6f5beb9a8a17149c224f9593821af6
[ "MIT" ]
2
2017-05-25T19:24:49.000Z
2018-03-03T18:53:32.000Z
// // GlkHub.h // CocoaGlk // // Created by Andrew Hunter on 16/03/2005. // Copyright 2005 Andrew Hunter. All rights reserved. // #import <Cocoa/Cocoa.h> #import <GlkView/GlkHubProtocol.h> // // The hub is the first point that a client connects to the Glk server application. // // The hub should be named, unless you want any random Glk application connecting. No hubs are available until a name has been // set. // Setting a hub cookie increases security, but you must communicate it to the client tasks somehow. Using a keychain cookie is // one way around this. // Always set the hub name after the cookie if you are using cookies. // // Client tasks by default connect to the hub named CocoaGlk. // @interface GlkHub : NSObject<GlkHub> { // Hub data NSString* hubName; // Name of the hub NSString* cookie; // Hub cookie (clients must know this to connect) id delegate; // The delegate (used to create anonymous sessions) NSMutableDictionary* waitingSessions; // Sessions waiting for a connection (maps cookies to sessions) // The connection NSConnection* connection; // The point at which the clients can connect to us } // The shared hub + (GlkHub*) sharedGlkHub; // Creating your own hub is liable to be hairy and unsupported. You only need one per task anyway. // Naming - (void) setHubName: (NSString*) hubName; // The name of this GlkHub. Calls resetConnection. - (void) useProcessHubName; // Auto-generates a name based on the process name - (NSString*) hubName; // Security - (void) setHubCookie: (NSString*) hubCookie; // Clients must know this in order to connect to the hub. nil by default. - (void) setRandomHubCookie; // Auto-generates a cookie. Not cryptographically secure (yet). - (void) setKeychainHubCookie; // Auto-generates (if no cookie exists yet) and stores the hub cookie in the keychain. - (NSString*) hubCookie; // The connection - (void) resetConnection; // Starts listening for connections if we're not already // Registering sessions for later consumption - (void) registerSession: (NSObject<GlkSession>*) session // Registers a session with the given cookie. A client can request this specific session object (exactly one, though) withCookie: (NSString*) sessionCookie; - (void) unregisterSession: (NSObject<GlkSession>*)session; // Unregisters a session previously registered with registerSession // The delegate - (void) setDelegate: (id) hubDelegate; - (id) delegate; @end // Hub delegate functions @interface NSObject(GlkHubDelegate) - (NSObject<GlkSession>*) createAnonymousSession; // Usually should return a GlkView. Called when a task starts with no session cookie @end
38.56338
175
0.719869
[ "object" ]
9805970485b983b860f502df668a306d0c963a8e
3,424
h
C
cryptohome/bootlockbox/tpm_nvspace_impl.h
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
cryptohome/bootlockbox/tpm_nvspace_impl.h
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
cryptohome/bootlockbox/tpm_nvspace_impl.h
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CRYPTOHOME_BOOTLOCKBOX_TPM_NVSPACE_IMPL_H_ #define CRYPTOHOME_BOOTLOCKBOX_TPM_NVSPACE_IMPL_H_ #include <memory> #include <string> #include <openssl/sha.h> #include <brillo/dbus/dbus_connection.h> #include <tpm_manager/proto_bindings/tpm_manager.pb.h> #include <tpm_manager-client/tpm_manager/dbus-proxies.h> #include "cryptohome/bootlockbox/tpm_nvspace.h" namespace cryptohome { struct BootLockboxNVSpace { uint16_t version; uint16_t flags; uint8_t digest[SHA256_DIGEST_LENGTH]; } __attribute__((packed)); constexpr uint8_t kNVSpaceVersion = 1; constexpr uint32_t kNVSpaceSize = sizeof(BootLockboxNVSpace); // Empty password is used for bootlockbox nvspace. Confidentiality // is not required and the nvspace is write locked after user logs in. constexpr char kWellKnownPassword[] = ""; // This class handles tpm operations to read, write, lock and define nv spaces. // Usage: // auto nvspace_utility = TPMNVSpaceImpl(); // nvspace_utility.Initialize(); // nvspace_utility.WriteNVSpace(...); class TPMNVSpaceImpl : public TPMNVSpace { public: TPMNVSpaceImpl() = default; // Constructor that does not take ownership of tpm_nvram. TPMNVSpaceImpl(org::chromium::TpmNvramProxyInterface* tpm_nvram, org::chromium::TpmManagerProxyInterface* tpm_owner); TPMNVSpaceImpl(const TPMNVSpaceImpl&) = delete; TPMNVSpaceImpl& operator=(const TPMNVSpaceImpl&) = delete; ~TPMNVSpaceImpl() {} // Initializes tpm_nvram if necessary. // Must be called before issuing and calls to this utility. bool Initialize() override; // This method defines a non-volatile storage area in TPM for bootlockboxd // via tpm_managerd. NVSpaceState DefineNVSpace() override; // This method writes |digest| to nvram space for bootlockboxd. bool WriteNVSpace(const std::string& digest) override; // Reads nvspace and extract |digest|. bool ReadNVSpace(std::string* digest, NVSpaceState* state) override; // Locks the bootlockbox nvspace for writing. bool LockNVSpace() override; // Register the callback that would be called when TPM ownership had been // taken. void RegisterOwnershipTakenCallback( const base::RepeatingClosure& callback) override; private: // Get the TPM status from tpm_manager. bool GetTPMStatus(bool* owned, bool* owner_password_present); // This method removes owner dependency from tpm_manager. bool RemoveNVSpaceOwnerDependency(); // This method would be called when the ownership had been taken. void OnOwnershipTaken(const base::RepeatingClosure& callback, const tpm_manager::OwnershipTakenSignal& signal); brillo::DBusConnection connection_; // Tpm manager interfaces that relays relays tpm request to tpm_managerd over // DBus. It is used for defining nvspace on the first boot. This object is // created in Initialize and should only be used in the same thread. std::unique_ptr<org::chromium::TpmNvramProxyInterface> default_tpm_nvram_; org::chromium::TpmNvramProxyInterface* tpm_nvram_; std::unique_ptr<org::chromium::TpmManagerProxyInterface> default_tpm_owner_; org::chromium::TpmManagerProxyInterface* tpm_owner_; }; } // namespace cryptohome #endif // CRYPTOHOME_BOOTLOCKBOX_TPM_NVSPACE_IMPL_H_
34.938776
79
0.765771
[ "object" ]
98094c5362a097d886a42f5d8e2353e852b85ddb
1,287
h
C
PyCommon/modules/Simulator/hpUJoint.h
hpgit/HumanFoot
f9a1a341b7c43747bddcd5584b8c98a0d1ac2973
[ "Apache-2.0" ]
null
null
null
PyCommon/modules/Simulator/hpUJoint.h
hpgit/HumanFoot
f9a1a341b7c43747bddcd5584b8c98a0d1ac2973
[ "Apache-2.0" ]
null
null
null
PyCommon/modules/Simulator/hpUJoint.h
hpgit/HumanFoot
f9a1a341b7c43747bddcd5584b8c98a0d1ac2973
[ "Apache-2.0" ]
null
null
null
#ifndef HP_UJOINT #define HP_UJOINT #include <VP/vpDataType.h> #include <VP/vpUJoint.h> class hpUJoint : public vpUJoint { public: hpUJoint():vpUJoint(){backup = false;} scalar GetDisplacement(int i){return m_rQ[i];} scalar GetFirstDeriv(int i){return m_rDq[i];} scalar GetSecondDeriv(int i){return m_rDdq[i];} scalar GetGenTorque(int i){return m_rActuationTau[i];} void SetSecondDeriv(int i, const scalar &a){m_rDdq[i] = a;} void SetGenTorque(int i, const scalar &a){m_rActuationTau[i] = a;} SE3 GetTransform(){return Transform();} void BackupAccTau(); void RestoreAccTau(); boolean backup; scalar backupAcc[2]; scalar backupTau[2]; }; void hpUJoint::BackupAccTau() { backup = true; for(int i=0; i<2; i++) { backupAcc[i] = GetAngle(i); backupTau[i] = GetTorque(i); } } void hpUJoint::RestoreAccTau() { if (backup) { backup = false; for(int i=0; i<2; i++) { SetAngle(backupAcc[i]); SetTorque(backupTau[i]); } } } #endif
25.235294
87
0.512821
[ "transform" ]
9809b367c2bfd1789cee8f1b3c4eabb48d7271a8
1,225
h
C
src/defs.h
Pand9/planty-db
1e8b46e6dbc3e36c7aaa084c1387165d89af68aa
[ "Apache-2.0" ]
null
null
null
src/defs.h
Pand9/planty-db
1e8b46e6dbc3e36c7aaa084c1387165d89af68aa
[ "Apache-2.0" ]
null
null
null
src/defs.h
Pand9/planty-db
1e8b46e6dbc3e36c7aaa084c1387165d89af68aa
[ "Apache-2.0" ]
null
null
null
#pragma once #include <bits/stdc++.h> #include "basic.h" using index_t = i64; using value_t = i64; using vstr = std::vector<std::string>; using indices_t = std::vector<index_t>; using vi64 = std::vector<i64>; using cname = std::string; using cnames = std::vector<std::string>; using std::vector; using std::string; using std::string_view; using std::move; #ifdef INFO_PRINTS auto log_info = [](auto const& ...ts) { lprintln("info:", ts...); }; #else #define log_info(...) #endif #ifdef PLAN_PRINTS auto log_plan = [](auto const& ...ts) { lprintln("plan:", ts...); }; #else #define log_plan(...) #endif auto log_debug = [](auto const& ...ts) { lprintln("debug:", ts...); }; #ifdef PERF_PRINTS auto log_perf = [](auto const& ...ts) { lprintln("perf:", ts...); }; #else #define log_perf(...) #endif #define bound_assert(INDEX, CONTAINER) massert(INDEX >= 0 && INDEX < isize(CONTAINER), \ "Index '" #INDEX "' = " + std::to_string(INDEX) + " out of bounds of container '" #CONTAINER \ "' with size " + std::to_string(isize(CONTAINER))) #define unreachable_assert(msg) do { std::cerr << "Fatal error: unreachable code was reached in line " << __LINE__ << ", message: " << msg << std::endl; exit(42); } while(0)
31.410256
173
0.645714
[ "vector" ]
980bdb0f97982e08f3bd0293873d31d1c89927fb
1,554
h
C
src/software/ai/evaluation/shot.h
jonl112/Software
61a028a98d5c0dd5e79bf055b231633290ddbf9f
[ "MIT" ]
null
null
null
src/software/ai/evaluation/shot.h
jonl112/Software
61a028a98d5c0dd5e79bf055b231633290ddbf9f
[ "MIT" ]
null
null
null
src/software/ai/evaluation/shot.h
jonl112/Software
61a028a98d5c0dd5e79bf055b231633290ddbf9f
[ "MIT" ]
null
null
null
#pragma once #include "software/geom/point.h" class Shot { public: Shot() = delete; /** * Creates a shot with the given target and angle * * @param point The target to shoot at * @param angle The angle formed by the shot origin, and the edges of the two * obstacles closest to the shot path * */ explicit Shot(Point point, Angle angle); /** * Returns a point, the target to shoot at. * * @return a point, representing the target to shoot at. */ const Point &getPointToShootAt() const; /** * Returns the angle formed by the shot origin, and the edges of the two obstacles * closest to the shot path * * @return the angle formed by the shot origin, and the edges of the two obstacles * closest to the shot path */ const Angle &getOpenAngle() const; private: /** * The target of the shot * */ Point point; /** * The angle formed by the shot origin, and the edges of the two obstacles closest to the shot path * XXXXO - Obstacle XXXX | XXXX | XXXX | Robot - R ============== T - Target XXXX | XXXX | XXXX | XXXXO - Obstacle The angle formed by '|' in between the obstacles '=' represents the shot vector * */ Angle angle; };
24.666667
89
0.507722
[ "vector" ]
9810ea40232daf635cf2f982a86012784e26b806
2,138
h
C
base/module/include/motis/module/registry.h
alexandersinkovic/motis
e4a0af04b4c934b8361401b1164db81bec5f1e6b
[ "MIT" ]
null
null
null
base/module/include/motis/module/registry.h
alexandersinkovic/motis
e4a0af04b4c934b8361401b1164db81bec5f1e6b
[ "MIT" ]
58
2021-11-22T13:43:39.000Z
2022-03-18T21:49:04.000Z
base/module/include/motis/module/registry.h
Kingforce01/motis
e4a0af04b4c934b8361401b1164db81bec5f1e6b
[ "MIT" ]
null
null
null
#pragma once #include <map> #include <mutex> #include <optional> #include "ctx/access_request.h" #include "motis/module/client.h" #include "motis/module/global_res_ids.h" #include "motis/module/message.h" #include "motis/module/receiver.h" namespace motis::module { using void_op_fn_t = std::function<void()>; using op_fn_t = std::function<msg_ptr(msg_ptr const&)>; using remote_op_fn_t = std::function<void(msg_ptr, callback)>; struct op { op(std::function<msg_ptr(msg_ptr const&)> fn, std::vector<ctx::access_request> access) : fn_{std::move(fn)}, access_{std::move(access)} {} op_fn_t fn_; ctx::accesses_t access_; }; struct registry { void register_op(std::string const& name, op_fn_t, ctx::accesses_t&& = std::vector<ctx::access_request>{ {to_res_id(global_res_id::SCHEDULE), ctx::access_t::READ}}); void register_client_handler(std::string&& target, std::function<void(client_hdl)>&&); void subscribe(std::string const& topic, op_fn_t, ctx::accesses_t&& = std::vector<ctx::access_request>{ {to_res_id(global_res_id::SCHEDULE), ctx::access_t::READ}}); void subscribe(std::string const& topic, void_op_fn_t, ctx::accesses_t&& = std::vector<ctx::access_request>{ {to_res_id(global_res_id::SCHEDULE), ctx::access_t::READ}}); std::vector<std::string> register_remote_ops( std::vector<std::string> const& names, remote_op_fn_t const& fn); void unregister_remote_op(std::vector<std::string> const& names); std::optional<remote_op_fn_t> get_remote_op(std::string const& prefix); std::optional<op> get_operation(std::string const& prefix); void reset(); std::map<std::string, op> operations_; std::map<std::string, std::vector<op>> topic_subscriptions_; std::map<std::string, std::function<void(client_hdl)>> client_handlers_; std::mutex mutable remote_op_mutex_; std::map<std::string, remote_op_fn_t> remote_operations_; }; } // namespace motis::module
31.910448
74
0.653414
[ "vector" ]
9814d3f9afd2e853b30ba229d5482de0b451ba78
2,017
h
C
Libraries/RobsJuceModules/rosic/transforms/rosic_WaveletTransforms.h
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
34
2017-04-19T18:26:02.000Z
2022-02-15T17:47:26.000Z
Libraries/RobsJuceModules/rosic/transforms/rosic_WaveletTransforms.h
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
307
2017-05-04T21:45:01.000Z
2022-02-03T00:59:01.000Z
Libraries/RobsJuceModules/rosic/transforms/rosic_WaveletTransforms.h
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
4
2017-09-05T17:04:31.000Z
2021-12-15T21:24:28.000Z
#ifndef rosic_WaveletTransforms_h #define rosic_WaveletTransforms_h //// rosic includes: //#include "../basics/rosic_HelperFunctions.h" //#include <algorithm> namespace rosic { /** Performs a 1D Haar-transform on the passed buffer. The number of levels should be at most the number of times, which the length is divisible by 2 (without remainder). */ template <class T> void trafoHaar1D(T *buffer, int length, int numLevels); /** Performs a 1D inverse Haar-transform on the passed buffer. The number of levels should be at most the number of times, which the length is divisible by 2 (without remainder). */ template <class T> void trafoInverseHaar1D(T *buffer, int length, int numLevels); //=============================================================================================== // implementation: template <class T> void trafoHaar1D(T *buffer, int length, int numLevels) { const double c = SQRT2_INV; //T *tmp = (T*) alloca(length*sizeof(T)); T* tmp = new T[length]; // todo: get ird - let client pass workspace pointer int w = length; for(int level=1; level<=numLevels; level++) { int j = w/2; for(int i=0; i<j; i++) { tmp[i] = c * (buffer[2*i] + buffer[2*i+1]); tmp[i+j] = c * (buffer[2*i] - buffer[2*i+1]); } memcpy(buffer, tmp, w*sizeof(T)); w /= 2; } delete[] tmp; } template <class T> void trafoInverseHaar1D(T *buffer, int length, int numLevels) { const double c = SQRT2_INV; //T *tmp = (T*) alloca(length*sizeof(T)); T* tmp = new T[length]; // get rid int w = length/numLevels; for(int level=1; level<=numLevels; level++) { int j = w/2; for(int i=0; i<j; i++) { tmp[2*i] = c * (buffer[i] + buffer[i+j]); tmp[2*i+1] = c * (buffer[i] - buffer[i+j]); } memcpy(buffer, tmp, w*sizeof(T)); w *= 2; } delete[] tmp; } } // end namespace rosic #endif // #ifndef rosic_WaveletTransforms_h
29.231884
99
0.577095
[ "transform" ]
981ad6231af3f55af7a5d0e4d4d9e65a5d591719
4,066
c
C
src/rnn.c
PandoraLS/PercepNet
cf3394e806280abef9823c0f889a32efc7ac6f7c
[ "BSD-3-Clause" ]
null
null
null
src/rnn.c
PandoraLS/PercepNet
cf3394e806280abef9823c0f889a32efc7ac6f7c
[ "BSD-3-Clause" ]
null
null
null
src/rnn.c
PandoraLS/PercepNet
cf3394e806280abef9823c0f889a32efc7ac6f7c
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2008-2011 Octasic Inc. 2012-2017 Jean-Marc Valin */ /* 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. 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 FOUNDATION 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <math.h> #include "opus_types.h" #include "common.h" #include "arch.h" #include "tansig_table.h" #include "nnet.h" #include "nnet_data.h" #include <stdio.h> void compute_rnn(RNNState *rnn, float *gains, float *strengths, const float *input) { int i; float dense_out[MAX_NEURONS]; float first_conv1d_out[CONV_DIM]; float second_conv1d_out[CONV_DIM]; float noise_input[MAX_NEURONS*3]; float denoise_input[MAX_NEURONS*3]; compute_dense(rnn->model->input_dense, dense_out, input); compute_conv1d(rnn->model->first_conv1d, first_conv1d_out/*512*/, rnn->first_conv1d_state, dense_out); compute_conv1d(rnn->model->second_conv1d, second_conv1d_out/*512*/, rnn->second_conv1d_state, first_conv1d_out); //align 3 conv data RNN_MOVE(rnn->convout_buf, &rnn->convout_buf[CONV_DIM], CONVOUT_BUF_SIZE-CONV_DIM); RNN_COPY(&rnn->convout_buf[CONVOUT_BUF_SIZE-CONV_DIM], rnn->second_conv1d_state, CONV_DIM); //T-3 convout input for gru1 compute_gru(rnn->model->gru1, rnn->gru1_state, rnn->convout_buf); compute_gru(rnn->model->gru2, rnn->gru2_state, rnn->gru1_state); compute_gru(rnn->model->gru3, rnn->gru3_state, rnn->gru2_state); //for temporary input for gb_gru and rb_gru is gru3_state //but it might be need concat convout_buf through gru1,2,3_state compute_gru(rnn->model->gb_gru, rnn->gb_gru_state, rnn->gru3_state); compute_gru(rnn->model->rb_gru, rnn->rb_gru_state, rnn->gru3_state); compute_dense(rnn->model->gb_output, gains, rnn->gb_gru_state); compute_dense(rnn->model->rb_output, strengths, rnn->rb_gru_state); /* compute_gru(rnn->model->vad_gru, rnn->vad_gru_state, dense_out); compute_dense(rnn->model->vad_output, vad, rnn->vad_gru_state); for (i=0;i<rnn->model->input_dense_size;i++) noise_input[i] = dense_out[i]; for (i=0;i<rnn->model->vad_gru_size;i++) noise_input[i+rnn->model->input_dense_size] = rnn->vad_gru_state[i]; for (i=0;i<INPUT_SIZE;i++) noise_input[i+rnn->model->input_dense_size+rnn->model->vad_gru_size] = input[i]; compute_gru(rnn->model->noise_gru, rnn->noise_gru_state, noise_input); for (i=0;i<rnn->model->vad_gru_size;i++) denoise_input[i] = rnn->vad_gru_state[i]; for (i=0;i<rnn->model->noise_gru_size;i++) denoise_input[i+rnn->model->vad_gru_size] = rnn->noise_gru_state[i]; for (i=0;i<INPUT_SIZE;i++) denoise_input[i+rnn->model->vad_gru_size+rnn->model->noise_gru_size] = input[i]; compute_gru(rnn->model->denoise_gru, rnn->denoise_gru_state, denoise_input); compute_dense(rnn->model->denoise_output, gains, rnn->denoise_gru_state); */ }
48.987952
115
0.735366
[ "model" ]
485e1c18164084d04167b458b76e6733c23d073a
8,170
h
C
src/utils.h
FMSoftCN/hibox
cbcd560dbbaf30885bcd6570454f3a3f4e312ba6
[ "MIT" ]
3
2020-11-03T01:45:17.000Z
2022-01-18T01:37:05.000Z
src/utils.h
FMSoftCN/hibox
cbcd560dbbaf30885bcd6570454f3a3f4e312ba6
[ "MIT" ]
1
2020-11-03T07:50:54.000Z
2020-11-03T07:50:54.000Z
src/utils.h
FMSoftCN/hibox
cbcd560dbbaf30885bcd6570454f3a3f4e312ba6
[ "MIT" ]
4
2020-11-03T06:15:25.000Z
2022-01-27T09:23:18.000Z
/* * utils - misc libubox utility functions * * Copyright (C) 2012 Felix Fietkau <nbd@openwrt.org> * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef __LIBHIBOX_UTILS_H #define __LIBHIBOX_UTILS_H #include <sys/types.h> #include <sys/time.h> #include <stdint.h> #include <stdbool.h> #include <unistd.h> #include <time.h> /* * calloc_a(size_t len, [void **addr, size_t len,...], NULL) * * allocate a block of memory big enough to hold multiple aligned objects. * the pointer to the full object (starting with the first chunk) is returned, * all other pointers are stored in the locations behind extra addr arguments. * the last argument needs to be a NULL pointer */ #define calloc_a(len, ...) __calloc_a(len, ##__VA_ARGS__, NULL) #ifdef __cplusplus extern "C" { #endif void *__calloc_a(size_t len, ...); #ifdef __cplusplus } #endif #ifndef ARRAY_SIZE #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0])) #endif #define __BUILD_BUG_ON(condition) ((void)sizeof(char[1 - 2*!!(condition)])) #ifdef __OPTIMIZE__ extern int __BUILD_BUG_ON_CONDITION_FAILED; #define BUILD_BUG_ON(condition) \ do { \ __BUILD_BUG_ON(condition); \ if (condition) \ __BUILD_BUG_ON_CONDITION_FAILED = 1; \ } while(0) #else #define BUILD_BUG_ON __BUILD_BUG_ON #endif #if defined(__APPLE__) && !defined(CLOCK_MONOTONIC) #define LIBHIBOX_COMPAT_CLOCK_GETTIME #include <mach/clock_types.h> #define CLOCK_REALTIME CALENDAR_CLOCK #define CLOCK_MONOTONIC SYSTEM_CLOCK #ifdef __cplusplus extern "C" { #endif int clock_gettime(int type, struct timespec *tv); #ifdef __cplusplus } #endif #endif #ifdef __GNUC__ #define _GNUC_MIN_VER(maj, min) (((__GNUC__ << 8) + __GNUC_MINOR__) >= (((maj) << 8) + (min))) #else #define _GNUC_MIN_VER(maj, min) 0 #endif #if defined(__linux__) || defined(__CYGWIN__) #include <byteswap.h> #include <endian.h> #elif defined(__APPLE__) #include <machine/endian.h> #include <machine/byte_order.h> #elif defined(__FreeBSD__) #include <sys/endian.h> #else #include <machine/endian.h> #endif #ifndef __BYTE_ORDER #define __BYTE_ORDER BYTE_ORDER #endif #ifndef __BIG_ENDIAN #define __BIG_ENDIAN BIG_ENDIAN #endif #ifndef __LITTLE_ENDIAN #define __LITTLE_ENDIAN LITTLE_ENDIAN #endif #define __constant_swap16(x) ((uint16_t)( \ (((uint16_t)(x) & (uint16_t)0x00ffU) << 8) | \ (((uint16_t)(x) & (uint16_t)0xff00U) >> 8))) #define __constant_swap32(x) ((uint32_t)( \ (((uint32_t)(x) & (uint32_t)0x000000ffUL) << 24) | \ (((uint32_t)(x) & (uint32_t)0x0000ff00UL) << 8) | \ (((uint32_t)(x) & (uint32_t)0x00ff0000UL) >> 8) | \ (((uint32_t)(x) & (uint32_t)0xff000000UL) >> 24))) #define __constant_swap64(x) ((uint64_t)( \ (((uint64_t)(x) & (uint64_t)0x00000000000000ffULL) << 56) | \ (((uint64_t)(x) & (uint64_t)0x000000000000ff00ULL) << 40) | \ (((uint64_t)(x) & (uint64_t)0x0000000000ff0000ULL) << 24) | \ (((uint64_t)(x) & (uint64_t)0x00000000ff000000ULL) << 8) | \ (((uint64_t)(x) & (uint64_t)0x000000ff00000000ULL) >> 8) | \ (((uint64_t)(x) & (uint64_t)0x0000ff0000000000ULL) >> 24) | \ (((uint64_t)(x) & (uint64_t)0x00ff000000000000ULL) >> 40) | \ (((uint64_t)(x) & (uint64_t)0xff00000000000000ULL) >> 56))) /* * This returns a constant expression while determining if an argument is * a constant expression, most importantly without evaluating the argument. */ #define __is_constant(x) \ (sizeof(int) == sizeof(*(1 ? ((void*)((long)(x) * 0l)) : (int*)1))) #define __eval_once(func, x) \ ({ __typeof__(x) __x = x; func(__x); }) #ifdef __cplusplus /* * g++ does not support __builtin_choose_expr, so always use __eval_once. * Unfortunately this means that the byte order functions can't be used * as a constant expression anymore */ #define __eval_safe(func, x) __eval_once(func, x) #else #define __eval_safe(func, x) \ __builtin_choose_expr(__is_constant(x), \ func(x), __eval_once(func, x)) #endif #if __BYTE_ORDER == __LITTLE_ENDIAN #define const_cpu_to_be64(x) __constant_swap64(x) #define const_cpu_to_be32(x) __constant_swap32(x) #define const_cpu_to_be16(x) __constant_swap16(x) #define const_be64_to_cpu(x) __constant_swap64(x) #define const_be32_to_cpu(x) __constant_swap32(x) #define const_be16_to_cpu(x) __constant_swap16(x) #define const_cpu_to_le64(x) (x) #define const_cpu_to_le32(x) (x) #define const_cpu_to_le16(x) (x) #define const_le64_to_cpu(x) (x) #define const_le32_to_cpu(x) (x) #define const_le16_to_cpu(x) (x) #define cpu_to_be64(x) __eval_safe(__constant_swap64, x) #define cpu_to_be32(x) __eval_safe(__constant_swap32, x) #define cpu_to_be16(x) __eval_safe(__constant_swap16, x) #define be64_to_cpu(x) __eval_safe(__constant_swap64, x) #define be32_to_cpu(x) __eval_safe(__constant_swap32, x) #define be16_to_cpu(x) __eval_safe(__constant_swap16, x) #define cpu_to_le64(x) (x) #define cpu_to_le32(x) (x) #define cpu_to_le16(x) (x) #define le64_to_cpu(x) (x) #define le32_to_cpu(x) (x) #define le16_to_cpu(x) (x) #else /* __BYTE_ORDER == __LITTLE_ENDIAN */ #define const_cpu_to_le64(x) __constant_swap64(x) #define const_cpu_to_le32(x) __constant_swap32(x) #define const_cpu_to_le16(x) __constant_swap16(x) #define const_le64_to_cpu(x) __constant_swap64(x) #define const_le32_to_cpu(x) __constant_swap32(x) #define const_le16_to_cpu(x) __constant_swap16(x) #define const_cpu_to_be64(x) (x) #define const_cpu_to_be32(x) (x) #define const_cpu_to_be16(x) (x) #define const_be64_to_cpu(x) (x) #define const_be32_to_cpu(x) (x) #define const_be16_to_cpu(x) (x) #define cpu_to_le64(x) __eval_safe(__constant_swap64, x) #define cpu_to_le32(x) __eval_safe(__constant_swap32, x) #define cpu_to_le16(x) __eval_safe(__constant_swap16, x) #define le64_to_cpu(x) __eval_safe(__constant_swap64, x) #define le32_to_cpu(x) __eval_safe(__constant_swap32, x) #define le16_to_cpu(x) __eval_safe(__constant_swap16, x) #define cpu_to_be64(x) (x) #define cpu_to_be32(x) (x) #define cpu_to_be16(x) (x) #define be64_to_cpu(x) (x) #define be32_to_cpu(x) (x) #define be16_to_cpu(x) (x) #endif #ifndef __packed #define __packed __attribute__((packed)) #endif #ifndef __constructor #define __constructor __attribute__((constructor)) #endif #ifndef __destructor #define __destructor __attribute__((destructor)) #endif #ifndef __hidden #define __hidden __attribute__((visibility("hidden"))) #endif #ifdef __cplusplus extern "C" { #endif char * b64_encode_alloc (const void *buf, size_t size); int b64_encode(const void *src, size_t src_len, void *dest, size_t dest_len); int b64_decode(const void *src, void *dest, size_t dest_len); #ifdef __cplusplus } #endif #define B64_ENCODE_LEN(_len) ((((_len) + 2) / 3) * 4 + 1) #define B64_DECODE_LEN(_len) (((_len) / 4) * 3 + 1) static inline unsigned int cbuf_order(unsigned int x) { return 32 - __builtin_clz(x - 1); } static inline unsigned long cbuf_size(int order) { unsigned long page_size = sysconf(_SC_PAGESIZE); unsigned long ret = 1ULL << order; if (ret < page_size) ret = page_size; return ret; } #ifdef __cplusplus extern "C" { #endif void *cbuf_alloc(unsigned int order); void cbuf_free(void *ptr, unsigned int order); /* hex must be long enough to hold the heximal characters */ void bin2hex (const unsigned char *bin, int len, char *hex); /* bin must be long enough to hold the bytes. return the number of bytes converted, <= 0 for error */ int hex2bin (const char *hex, unsigned char *bin); #ifdef __cplusplus } #endif #endif /* __LIBHIBOX_UTILS_H */
27.416107
94
0.731946
[ "object" ]
485e298b145b2f70ce5682a4c6a73726d68456c9
1,780
h
C
cusanalytic_sc_online/include/alibabacloud/cusanalytic_sc_online/model/DescribeActionDataRequest.h
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
cusanalytic_sc_online/include/alibabacloud/cusanalytic_sc_online/model/DescribeActionDataRequest.h
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
cusanalytic_sc_online/include/alibabacloud/cusanalytic_sc_online/model/DescribeActionDataRequest.h
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud 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 ALIBABACLOUD_CUSANALYTIC_SC_ONLINE_MODEL_DESCRIBEACTIONDATAREQUEST_H_ #define ALIBABACLOUD_CUSANALYTIC_SC_ONLINE_MODEL_DESCRIBEACTIONDATAREQUEST_H_ #include <string> #include <vector> #include <alibabacloud/core/RpcServiceRequest.h> #include <alibabacloud/cusanalytic_sc_online/Cusanalytic_sc_onlineExport.h> namespace AlibabaCloud { namespace Cusanalytic_sc_online { namespace Model { class ALIBABACLOUD_CUSANALYTIC_SC_ONLINE_EXPORT DescribeActionDataRequest : public RpcServiceRequest { public: DescribeActionDataRequest(); ~DescribeActionDataRequest(); long getTsEnd()const; void setTsEnd(long tsEnd); std::string getStoreId()const; void setStoreId(const std::string& storeId); int getPageLimit()const; void setPageLimit(int pageLimit); int getPageNo()const; void setPageNo(int pageNo); long getTsStart()const; void setTsStart(long tsStart); private: long tsEnd_; std::string storeId_; int pageLimit_; int pageNo_; long tsStart_; }; } } } #endif // !ALIBABACLOUD_CUSANALYTIC_SC_ONLINE_MODEL_DESCRIBEACTIONDATAREQUEST_H_
29.666667
103
0.748876
[ "vector", "model" ]
48724c617e357d22cf828d01c2bd9a77f20d6f0d
1,337
h
C
src/services/pcn-firewall/src/base/SessionTableBase.h
francescomessina/polycube
38f2fb4ffa13cf51313b3cab9994be738ba367be
[ "ECL-2.0", "Apache-2.0" ]
337
2018-12-12T11:50:15.000Z
2022-03-15T00:24:35.000Z
src/services/pcn-firewall/src/base/SessionTableBase.h
l1b0k/polycube
7af919245c131fa9fe24c5d39d10039cbb81e825
[ "ECL-2.0", "Apache-2.0" ]
253
2018-12-17T21:36:15.000Z
2022-01-17T09:30:42.000Z
src/services/pcn-firewall/src/base/SessionTableBase.h
l1b0k/polycube
7af919245c131fa9fe24c5d39d10039cbb81e825
[ "ECL-2.0", "Apache-2.0" ]
90
2018-12-19T15:49:38.000Z
2022-03-27T03:56:07.000Z
/** * firewall API generated from firewall.yang * * NOTE: This file is auto generated by polycube-codegen * https://github.com/polycube-network/polycube-codegen */ /* Do not edit this file manually */ /* * SessionTableBase.h * * */ #pragma once #include "../serializer/SessionTableJsonObject.h" #include <spdlog/spdlog.h> using namespace polycube::service::model; class Firewall; class SessionTableBase { public: SessionTableBase(Firewall &parent); virtual ~SessionTableBase(); virtual void update(const SessionTableJsonObject &conf); virtual SessionTableJsonObject toJsonObject(); /// <summary> /// Source IP /// </summary> virtual std::string getSrc() = 0; /// <summary> /// Destination IP /// </summary> virtual std::string getDst() = 0; /// <summary> /// Level 4 Protocol. /// </summary> virtual std::string getL4proto() = 0; /// <summary> /// Source Port /// </summary> virtual uint16_t getSport() = 0; /// <summary> /// Destination /// </summary> virtual uint16_t getDport() = 0; /// <summary> /// Connection state. /// </summary> virtual std::string getState() = 0; /// <summary> /// Last packet matching the connection /// </summary> virtual uint32_t getEta() = 0; std::shared_ptr<spdlog::logger> logger(); protected: Firewall &parent_; };
17.826667
58
0.65445
[ "model" ]
4877d451290351f004d937ba6d6675f5828492b8
2,240
c
C
nitan/kungfu/skill/yingxiong-sanzhao/yingxiong.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
1
2019-03-27T07:25:16.000Z
2019-03-27T07:25:16.000Z
nitan/kungfu/skill/yingxiong-sanzhao/yingxiong.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
nitan/kungfu/skill/yingxiong-sanzhao/yingxiong.c
cantona/NT6
073f4d491b3cfe6bfbe02fbad12db8983c1b9201
[ "MIT" ]
null
null
null
// yingxiong.c #include <ansi.h> inherit F_SSERVER; string name() { return "蓋世英雄"; } int perform(object me, object target) { int level; string msg; int ap, dp; if( !objectp(target) ) { target = offensive_target(me);} if( !target || !target->is_character() || target == me || !me->is_fighting(target) || !living(target) || query_temp("no_living", target) ) return notify_fail(name() + "只能對戰鬥中的對手使用。\n"); if( query("gender", me) != "男性" && !wizardp(me) ) return notify_fail("象你這副娘娘腔,也許練“絕世風姿”恐怕更合適點吧。\n"); if( (int)me->query_skill("yingxiong-sanzhao", 1) < 150 ) return notify_fail("你的英雄三招不夠嫻熟,不會使用"+name()+"。\n"); if( (int)me->query_skill("force", 1) < 160 ) return notify_fail("你的基本內功不夠嫻熟,不會使用"+name()+"。\n"); if( query("neili", me)<300 ) return notify_fail("你的內力不足,恐怕沒法逞英雄了。\n"); if( query_temp("shenlong/yingxiong", me) ) return notify_fail("你已經在大擺英雄的譜了,還不夠啊?\n"); level = me->query_skill("yingxiong-sanzhao", 1); addn("neili", -200, me); me->start_busy(1); ap = attack_power(me, "strike"); dp = defense_power(target, "force"); if( ap / 2 + random(ap) > dp ) { message_combatd(HIY"$N"HIY"越鬥越是兇猛,激鬥中仰天大吼一聲:“蓋世英雄!!”,一股豪氣自$N心中升起,頓時更是兇悍起來。\n" NOR, me, target); set_temp("shenlong/yingxiong", 1, me); addn_temp("apply/attack", level, me); addn_temp("apply/unarmed_damage", level, me); if( !target->is_busy() ) target->start_busy(random(3)+1); me->start_call_out( (: call_other, __FILE__, "remove_effect", me, level:), 30); } else { message_combatd(HIG"激鬥中的$N衝着$n大喊:“蓋世。。。”,語意未了,就被$n迫得手忙腳亂。\n" NOR, me, target); } return 1; } void remove_effect(object me, int level) { delete_temp("shenlong/yingxiong", me); addn_temp("apply/attack", -level, me); addn_temp("apply/unarmed_damage", -level, me); message_combatd(HIY"$N突然感到心底一陣失落:“歷代英雄,都歸孤冢。”一念及此,頓時意興蕭然。\n" NOR, me); }
33.939394
111
0.541964
[ "object" ]
488970be4d8c395bd78b5efd03b5c0db1b6afe34
56,604
c
C
src/deemon/objects/filetypes.c
GrieferAtWork/deemon
16a4899303390c93d6e7b3910aa4d20e7a55d80b
[ "Zlib" ]
5
2019-09-27T01:33:53.000Z
2021-11-29T16:31:39.000Z
src/deemon/objects/filetypes.c
GrieferAtWork/deemon
16a4899303390c93d6e7b3910aa4d20e7a55d80b
[ "Zlib" ]
null
null
null
src/deemon/objects/filetypes.c
GrieferAtWork/deemon
16a4899303390c93d6e7b3910aa4d20e7a55d80b
[ "Zlib" ]
1
2019-10-04T09:42:30.000Z
2019-10-04T09:42:30.000Z
/* Copyright (c) 2018-2021 Griefer@Work * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement (see the following) in the product * * documentation is required: * * Portions Copyright (c) 2018-2021 Griefer@Work * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * */ #ifndef GUARD_DEEMON_OBJECTS_FILETYPES_C #define GUARD_DEEMON_OBJECTS_FILETYPES_C 1 #include <deemon/alloc.h> #include <deemon/api.h> #include <deemon/arg.h> #include <deemon/bool.h> #include <deemon/error.h> #include <deemon/file.h> #include <deemon/filetypes.h> #include <deemon/int.h> #include <deemon/none.h> #include <deemon/object.h> #include <deemon/string.h> #include <deemon/stringutils.h> #include <deemon/system-features.h> /* memcpy(), ... */ #include <hybrid/atomic.h> #include "../runtime/runtime_error.h" #include "../runtime/strings.h" #include "gc_inspect.h" DECL_BEGIN typedef DeeMemoryFileObject MemoryFile; typedef DeeFileReaderObject Reader; typedef DeeFileWriterObject Writer; PRIVATE WUNUSED NONNULL((1)) int DCALL mf_init(MemoryFile *__restrict self) { self->mf_begin = NULL; self->mf_ptr = NULL; self->mf_end = NULL; return 0; } PRIVATE NONNULL((1)) void DCALL mf_fini(MemoryFile *__restrict self) { /* We only get here if `DeeFile_ReleaseMemory()' * was used to duplicate the memory block! */ Dee_Free((void *)self->mf_begin); } PRIVATE WUNUSED NONNULL((1, 2)) size_t DCALL mf_read(MemoryFile *__restrict self, void *__restrict buffer, size_t bufsize, dioflag_t UNUSED(flags)) { size_t result; DeeFile_LockWrite(self); ASSERT(self->mf_ptr >= self->mf_begin); if (self->mf_ptr >= self->mf_end) { result = 0; } else { result = (size_t)(self->mf_end - self->mf_ptr) * sizeof(char); if (result > bufsize) result = bufsize; /* Copy data into the given buffer. */ memcpy(buffer, self->mf_ptr, result); *(uintptr_t *)&self->mf_ptr += result; } DeeFile_LockEndWrite(self); return result; } PRIVATE WUNUSED NONNULL((1, 2)) size_t DCALL mf_pread(MemoryFile *__restrict self, void *__restrict buffer, size_t bufsize, dpos_t pos, dioflag_t UNUSED(flags)) { size_t result; DeeFile_LockRead(self); ASSERT(self->mf_ptr >= self->mf_begin); result = (size_t)(self->mf_end - self->mf_begin) * sizeof(char); if unlikely(pos >= (dpos_t)result) { result = 0; } else { result = result - (size_t)pos; if (result > bufsize) result = bufsize; /* Copy data into the given buffer. */ memcpy(buffer, self->mf_begin + (size_t)pos, result); } DeeFile_LockEndRead(self); return result; } PRIVATE WUNUSED NONNULL((1)) dpos_t DCALL mf_seek(MemoryFile *__restrict self, doff_t off, int whence) { dpos_t result; char *new_pointer; DeeFile_LockWrite(self); ASSERT(self->mf_ptr >= self->mf_begin); switch (whence) { case SEEK_SET: if unlikely(off < 0) goto err_invalid; if unlikely(self->mf_begin + (size_t)off < self->mf_begin) goto err_overflow; self->mf_ptr = self->mf_begin + (size_t)off; result = (dpos_t)off; break; case SEEK_CUR: result = (size_t)(self->mf_ptr - self->mf_begin); result += (dssize_t)off; if unlikely((doff_t)result < 0) goto err_invalid; new_pointer = self->mf_ptr + (dssize_t)off; if unlikely(off > 0 && new_pointer < self->mf_ptr) goto err_overflow; self->mf_ptr = new_pointer; break; case SEEK_END: result = (size_t)(self->mf_end - self->mf_begin); result += (dssize_t)off; if unlikely((doff_t)result < 0) goto err_invalid; new_pointer = self->mf_begin + result; if unlikely(new_pointer < self->mf_begin) goto err_overflow; self->mf_ptr = new_pointer; break; default: DeeFile_LockEndWrite(self); DeeError_Throwf(&DeeError_ValueError, "Invalid seek mode %d", whence); goto err; } DeeFile_LockEndWrite(self); return result; err_invalid: DeeFile_LockEndWrite(self); DeeError_Throwf(&DeeError_ValueError, "Invalid seek pointer"); goto err; err_overflow: DeeFile_LockEndWrite(self); DeeError_Throwf(&DeeError_IntegerOverflow, "Seek pointer is overflowing"); err: return (dpos_t)-1; } PRIVATE WUNUSED NONNULL((1)) int DCALL mf_close(MemoryFile *__restrict self) { DeeFile_LockWrite(self); self->mf_end = self->mf_begin; DeeFile_LockEndWrite(self); return 0; } PRIVATE WUNUSED NONNULL((1)) int DCALL mf_getc(MemoryFile *__restrict self, dioflag_t UNUSED(flags)) { int result; DeeFile_LockWrite(self); ASSERT(self->mf_ptr >= self->mf_begin); if unlikely(self->mf_ptr >= self->mf_end) { result = GETC_EOF; } else { result = *self->mf_ptr++; } DeeFile_LockEndWrite(self); return result; } PRIVATE WUNUSED NONNULL((1)) int DCALL mf_ungetc(MemoryFile *__restrict self, int ch) { int result; DeeFile_LockWrite(self); ASSERT(self->mf_ptr >= self->mf_begin); if unlikely(self->mf_ptr == self->mf_begin) { result = GETC_EOF; } else { #if 0 if (self->mf_ptr[-1] != (char)ch) { DeeFile_LockEndWrite(self); DeeError_Throwf(&DeeError_ValueError, "Incorrect character for ungetc()"); return GETC_ERR; } #endif (void)ch; /* Rewind the file pointer. */ --self->mf_ptr; result = 0; } DeeFile_LockEndWrite(self); return result; } PUBLIC DeeFileTypeObject DeeMemoryFile_Type = { /* .ft_base = */ { OBJECT_HEAD_INIT(&DeeFileType_Type), /* .tp_name = */ "_MemoryFile", /* .tp_doc = */ NULL, /* .tp_flags = */ TP_FNORMAL, /* .tp_weakrefs = */ 0, /* .tp_features = */ TF_HASFILEOPS, /* .tp_base = */ (DeeTypeObject *)&DeeFile_Type, /* .tp_init = */ { { /* .tp_alloc = */ { /* .tp_ctor = */ (dfunptr_t)&mf_init, /* .tp_copy_ctor = */ (dfunptr_t)NULL, /* .tp_deep_ctor = */ (dfunptr_t)NULL, /* .tp_any_ctor = */ (dfunptr_t)NULL, TYPE_FIXED_ALLOCATOR(MemoryFile) } }, /* .tp_dtor = */ (void (DCALL *)(DeeObject *__restrict))&mf_fini, /* .tp_assign = */ NULL, /* .tp_move_assign = */ NULL }, /* .tp_cast = */ { /* .tp_str = */ NULL, /* .tp_repr = */ NULL, /* .tp_bool = */ NULL }, /* .tp_call = */ NULL, /* .tp_visit = */ NULL, /* .tp_gc = */ NULL, /* .tp_math = */ NULL, /* .tp_cmp = */ NULL, /* .tp_seq = */ NULL, /* .tp_iter_next = */ NULL, /* .tp_attr = */ NULL, /* .tp_with = */ NULL, /* .tp_buffer = */ NULL, /* .tp_methods = */ NULL, /* .tp_getsets = */ NULL, /* .tp_members = */ NULL, /* .tp_class_methods = */ NULL, /* .tp_class_getsets = */ NULL, /* .tp_class_members = */ NULL }, /* .ft_read = */ (size_t (DCALL *)(DeeFileObject *__restrict, void *__restrict, size_t, dioflag_t))&mf_read, /* .ft_write = */ NULL, /* .ft_seek = */ (dpos_t (DCALL *)(DeeFileObject *__restrict, doff_t, int))&mf_seek, /* .ft_sync = */ NULL, /* .ft_trunc = */ NULL, /* .ft_close = */ (int (DCALL *)(DeeFileObject *__restrict))&mf_close, /* .ft_pread = */ (size_t (DCALL *)(DeeFileObject *__restrict, void *__restrict, size_t, dpos_t, dioflag_t))&mf_pread, /* .ft_pwrite = */ NULL, /* .ft_getc = */ (int (DCALL *)(DeeFileObject *__restrict, dioflag_t))&mf_getc, /* .ft_ungetc = */ (int (DCALL *)(DeeFileObject *__restrict, int))&mf_ungetc, /* .ft_putc = */ NULL }; /* Open a read-only view for raw memory contained within the given data-block. * The returned file can be used to access said data in a read-only fashion, * however since the data isn't copied, before that data gets freed, you must * call `DeeFile_ReleaseMemory()' to inform the view of this happened, while * simultaneously decrementing its reference counter by ONE. * `DeeFile_ReleaseMemory()' will automatically determine the proper course * of action, dependent on whether the file is being shared with some other * part of deemon. If it is, it will replace the view's data with a heap-allocated * copy of that data, and if that isn't possible, modify the view to represent * an empty data set. * The main use of this functionality is to allow the use of `DeeModule_LoadSourceStream()' * with a stream backed by source code located in memory. */ PUBLIC WUNUSED NONNULL((1)) DREF /*File*/ DeeObject *DCALL DeeFile_OpenRoMemory(void const *data, size_t data_size) { DREF MemoryFile *result; result = DeeObject_MALLOC(MemoryFile); if unlikely(!result) goto done; result->mf_begin = (char *)data; result->mf_end = (char *)data + data_size; result->mf_ptr = result->mf_begin; DeeLFileObject_Init(result, &DeeMemoryFile_Type); done: return (DREF DeeObject *)result; } PUBLIC NONNULL((1)) void DCALL DeeFile_ReleaseMemory(DREF /*File*/ DeeObject *__restrict self) { MemoryFile *me = (MemoryFile *)self; ASSERT_OBJECT_TYPE_EXACT(self, (DeeTypeObject *)&DeeMemoryFile_Type); if (!DeeObject_IsShared(me)) { /* The file also went away, so we can simply not free its data! */ Dee_DecrefNokill((DeeObject *)&DeeMemoryFile_Type); DeeObject_FreeTracker(me); DeeObject_Free(me); } else { /* Try to copy the data of the file in question. */ void *data_copy; size_t size; DeeFile_LockRead(me); size = (size_t)(me->mf_end - me->mf_begin); DeeFile_LockEndRead(me); data_copy = size ? Dee_TryMalloc(size) : NULL; COMPILER_READ_BARRIER(); DeeFile_LockWrite(me); if likely(data_copy || !size) { /* Copy the stream's data */ memcpy(data_copy, me->mf_begin, (size_t)(me->mf_end - me->mf_begin)); me->mf_end = (char *)data_copy + (me->mf_end - me->mf_begin); me->mf_ptr = (char *)data_copy + (me->mf_ptr - me->mf_begin); me->mf_begin = (char *)data_copy; } else { /* Failed to copy data. - Fallback by deleting the * stream's data so it becomes weak undefined behavior... */ me->mf_begin = NULL; me->mf_end = NULL; me->mf_ptr = NULL; } DeeFile_LockEndWrite(me); } } PRIVATE ATTR_COLD int DCALL err_file_closed(void) { return DeeError_Throwf(&DeeError_FileClosed, "File was closed"); } PRIVATE WUNUSED NONNULL((1, 2)) size_t DCALL reader_read(Reader *__restrict self, void *__restrict buffer, size_t bufsize, dioflag_t UNUSED(flags)) { size_t result; DeeFile_LockWrite(self); ASSERT(self->r_ptr >= self->r_begin); if unlikely(!self->r_owner) { DeeFile_LockEndWrite(self); return (size_t)err_file_closed(); } if (self->r_ptr >= self->r_end) { result = 0; } else { result = (size_t)(self->r_end - self->r_ptr) * sizeof(char); if (result > bufsize) result = bufsize; /* Copy data into the given buffer. */ memcpy(buffer, self->r_ptr, result); *(uintptr_t *)&self->r_ptr += result; } DeeFile_LockEndWrite(self); return result; } PRIVATE WUNUSED NONNULL((1, 2)) size_t DCALL reader_pread(Reader *__restrict self, void *__restrict buffer, size_t bufsize, dpos_t pos, dioflag_t UNUSED(flags)) { size_t result; DeeFile_LockRead(self); ASSERT(self->r_ptr >= self->r_begin); if unlikely(!self->r_owner) { DeeFile_LockEndRead(self); return (size_t)err_file_closed(); } result = (size_t)(self->r_end - self->r_begin) * sizeof(char); if unlikely(pos >= (dpos_t)result) { result = 0; } else { result = result - (size_t)pos; if (result > bufsize) result = bufsize; /* Copy data into the given buffer. */ memcpy(buffer, self->r_begin + (size_t)pos, result); } DeeFile_LockEndRead(self); return result; } PRIVATE WUNUSED NONNULL((1)) dpos_t DCALL reader_seek(Reader *__restrict self, doff_t off, int whence) { dpos_t result; char *new_pointer; DeeFile_LockWrite(self); ASSERT(self->r_ptr >= self->r_begin); if unlikely(!self->r_owner) { DeeFile_LockEndWrite(self); return (dpos_t)err_file_closed(); } switch (whence) { case SEEK_SET: if unlikely(off < 0) goto err_invalid; if unlikely(self->r_begin + (size_t)off < self->r_begin) goto err_overflow; self->r_ptr = self->r_begin + (size_t)off; result = (dpos_t)off; break; case SEEK_CUR: result = (size_t)(self->r_ptr - self->r_begin); result += (dssize_t)off; if unlikely((doff_t)result < 0) goto err_invalid; new_pointer = self->r_ptr + (dssize_t)off; if unlikely(off > 0 && new_pointer < self->r_ptr) goto err_overflow; self->r_ptr = new_pointer; break; case SEEK_END: result = (size_t)(self->r_end - self->r_begin); result += (dssize_t)off; if unlikely((doff_t)result < 0) goto err_invalid; new_pointer = self->r_begin + result; if unlikely(new_pointer < self->r_begin) goto err_overflow; self->r_ptr = new_pointer; break; default: DeeFile_LockEndWrite(self); DeeError_Throwf(&DeeError_ValueError, "Invalid seek mode %d", whence); goto err; } DeeFile_LockEndWrite(self); return result; err_invalid: DeeFile_LockEndWrite(self); DeeError_Throwf(&DeeError_ValueError, "Invalid seek pointer"); goto err; err_overflow: DeeFile_LockEndWrite(self); DeeError_Throwf(&DeeError_IntegerOverflow, "Seek pointer is overflowing"); err: return (dpos_t)-1; } PRIVATE WUNUSED NONNULL((1)) int DCALL reader_sync(Reader *__restrict self) { #ifdef CONFIG_NO_THREADS if unlikely(!self->r_owner) #else /* CONFIG_NO_THREADS */ if unlikely(!ATOMIC_READ(self->r_owner)) #endif /* !CONFIG_NO_THREADS */ { return err_file_closed(); } return 0; } PRIVATE WUNUSED NONNULL((1)) int DCALL reader_close(Reader *__restrict self) { DREF DeeObject *owner; DeeFile_LockWrite(self); ASSERT(self->r_ptr >= self->r_begin); /* Extract the string from which data was being read. */ owner = self->r_owner; /* Clear all fields to NULL. */ self->r_owner = NULL; self->r_begin = NULL; self->r_ptr = NULL; self->r_end = NULL; DeeFile_LockEndWrite(self); /* If the string was already deleted, throw an error. */ if unlikely(!owner) return err_file_closed(); /* Decref() the string. */ DeeObject_PutBuf(owner, &self->r_buffer, Dee_BUFFER_FREADONLY); Dee_Decref(owner); return 0; } PRIVATE WUNUSED NONNULL((1)) DREF DeeObject *DCALL reader_getowner(Reader *__restrict self) { DREF DeeObject *result; DeeFile_LockRead(self); result = self->r_owner; Dee_XIncref(result); DeeFile_LockEndRead(self); if (!result) err_file_closed(); return result; } PRIVATE WUNUSED NONNULL((1, 2)) int DCALL reader_setowner(Reader *__restrict self, DeeObject *__restrict value) { DeeObject *old_value; DeeBuffer new_buffer, old_buffer; if (DeeGC_IsReachable((DeeObject *)self, value)) return err_reference_loop((DeeObject *)self, value); if (DeeObject_GetBuf(value, &new_buffer, Dee_BUFFER_FREADONLY)) goto err; Dee_Incref(value); DeeFile_LockRead(self); old_value = self->r_owner; self->r_owner = value; /* Setup pointers to read from the entire string. */ self->r_begin = (char *)new_buffer.bb_base; self->r_ptr = (char *)new_buffer.bb_base; self->r_end = (char *)new_buffer.bb_base + new_buffer.bb_size; memcpy(&old_buffer, &self->r_buffer, sizeof(DeeBuffer)); memcpy(&self->r_buffer, &new_buffer, sizeof(DeeBuffer)); DeeFile_LockEndRead(self); if (old_value) { DeeObject_PutBuf(old_value, &old_buffer, Dee_BUFFER_FREADONLY); Dee_Decref(old_value); } return 0; err: return -1; } PRIVATE WUNUSED NONNULL((1)) int DCALL reader_getc(Reader *__restrict self, dioflag_t UNUSED(flags)) { int result; DeeFile_LockWrite(self); ASSERT(self->r_ptr >= self->r_begin); if unlikely(!self->r_owner) { DeeFile_LockEndWrite(self); err_file_closed(); return GETC_ERR; } if unlikely(self->r_ptr >= self->r_end) { result = GETC_EOF; } else { result = *self->r_ptr++; } DeeFile_LockEndWrite(self); return result; } PRIVATE WUNUSED NONNULL((1)) int DCALL reader_ungetc(Reader *__restrict self, int ch) { int result; DeeFile_LockWrite(self); ASSERT(self->r_ptr >= self->r_begin); if unlikely(!self->r_owner) { DeeFile_LockEndWrite(self); err_file_closed(); return GETC_ERR; } if unlikely(self->r_ptr == self->r_begin) { result = GETC_EOF; } else { #if 0 if (self->r_ptr[-1] != (char)ch) { DeeFile_LockEndWrite(self); DeeError_Throwf(&DeeError_ValueError, "Incorrect character for ungetc()"); return GETC_ERR; } #endif (void)ch; /* Rewind the file pointer. */ --self->r_ptr; result = 0; } DeeFile_LockEndWrite(self); return result; } PRIVATE NONNULL((1)) void DCALL reader_fini(Reader *__restrict self) { if (self->r_owner) { DeeObject_PutBuf(self->r_owner, &self->r_buffer, Dee_BUFFER_FREADONLY); Dee_Decref(self->r_owner); } } PRIVATE NONNULL((1, 2)) void DCALL reader_visit(Reader *__restrict self, dvisit_t proc, void *arg) { Dee_XVisit(self->r_owner); } PRIVATE WUNUSED NONNULL((1)) int DCALL reader_ctor(Reader *__restrict self) { rwlock_init(&self->fo_lock); self->r_owner = NULL; self->r_begin = NULL; self->r_ptr = NULL; self->r_end = NULL; return 0; } PRIVATE WUNUSED NONNULL((1)) int DCALL reader_init(Reader *__restrict self, size_t argc, DeeObject *const *argv) { size_t begin = 0, end = (size_t)-1; if (DeeArg_Unpack(argc, argv, "o|IdId:_FileReader", &self->r_owner, &begin, &end)) goto err; if (DeeObject_GetBuf(self->r_owner, &self->r_buffer, Dee_BUFFER_FREADONLY)) goto err; /* Truncate the end-pointer. */ if (end > self->r_buffer.bb_size) end = self->r_buffer.bb_size; /* Handle empty read. */ if unlikely(begin >= end) begin = end = 0; /* Fill in members. */ Dee_Incref(self->r_owner); rwlock_init(&self->fo_lock); self->r_begin = (char *)self->r_buffer.bb_base + begin; self->r_end = (char *)self->r_buffer.bb_base + end; self->r_ptr = self->r_begin; return 0; err: return -1; } PRIVATE struct type_getset tpconst reader_getsets[] = { { "owner", (DREF DeeObject *(DCALL *)(DeeObject *__restrict))&reader_getowner, (int (DCALL *)(DeeObject *__restrict))&reader_close, (int (DCALL *)(DeeObject *, DeeObject *))&reader_setowner, DOC("Assign the object from which data is being read") }, { NULL } }; PUBLIC DeeFileTypeObject DeeFileReader_Type = { /* .ft_base = */ { OBJECT_HEAD_INIT(&DeeFileType_Type), /* .tp_name = */ "_FileReader", /* .tp_doc = */ DOC("()\n" "(s:?DBytes,start=!0,end=!-1)\n" "Create a file stream for reading data of the given @s as a buffer, " "starting at its byte-offset @start and ending at @end\n" "Note that the given indices @start and @end refer to byte " "offsets, and not character offsets, not its preferred encoding"), /* .tp_flags = */ TP_FNORMAL, /* .tp_weakrefs = */ 0, /* .tp_features = */ TF_HASFILEOPS | TF_NONLOOPING, /* .tp_base = */ (DeeTypeObject *)&DeeFile_Type, /* .tp_init = */ { { /* .tp_alloc = */ { /* .tp_ctor = */ (dfunptr_t)&reader_ctor, /* .tp_copy_ctor = */ (dfunptr_t)NULL, /* .tp_deep_ctor = */ (dfunptr_t)NULL, /* .tp_any_ctor = */ (dfunptr_t)&reader_init, TYPE_FIXED_ALLOCATOR(Reader) } }, /* .tp_dtor = */ (void (DCALL *)(DeeObject *__restrict))&reader_fini, /* .tp_assign = */ NULL, /* .tp_move_assign = */ NULL }, /* .tp_cast = */ { /* .tp_str = */ NULL, /* .tp_repr = */ NULL, /* .tp_bool = */ NULL }, /* .tp_call = */ NULL, /* .tp_visit = */ (void (DCALL *)(DeeObject *__restrict, dvisit_t, void *))&reader_visit, /* .tp_gc = */ NULL, /* .tp_math = */ NULL, /* .tp_cmp = */ NULL, /* .tp_seq = */ NULL, /* .tp_iter_next = */ NULL, /* .tp_attr = */ NULL, /* .tp_with = */ NULL, /* .tp_buffer = */ NULL, /* .tp_methods = */ NULL, /* .tp_getsets = */ reader_getsets, /* .tp_members = */ NULL, /* .tp_class_methods = */ NULL, /* .tp_class_getsets = */ NULL, /* .tp_class_members = */ NULL }, /* .ft_read = */ (size_t (DCALL *)(DeeFileObject *__restrict, void *__restrict, size_t, dioflag_t))&reader_read, /* .ft_write = */ NULL, /* .ft_seek = */ (dpos_t (DCALL *)(DeeFileObject *__restrict, doff_t, int))&reader_seek, /* .ft_sync = */ (int (DCALL *)(DeeFileObject *__restrict))&reader_sync, /* .ft_trunc = */ NULL, /* .ft_close = */ (int (DCALL *)(DeeFileObject *__restrict))&reader_close, /* .ft_pread = */ (size_t (DCALL *)(DeeFileObject *__restrict, void *__restrict, size_t, dpos_t, dioflag_t))&reader_pread, /* .ft_pwrite = */ NULL, /* .ft_getc = */ (int (DCALL *)(DeeFileObject *__restrict, dioflag_t))&reader_getc, /* .ft_ungetc = */ (int (DCALL *)(DeeFileObject *__restrict, int))&reader_ungetc, /* .ft_putc = */ NULL }; /* Open a new file stream for reading memory from `data...+=data_size' * This stream assumes that data is immutable, and owned by `data_owner'. * The best example for a type that fits these requirements is `string' * This function greatly differs from `DeeFile_OpenRoMemory()', in that * the referenced data is shared with an explicit object, rather that * being held using a ticket-system, where the caller must manually * inform the memory stream when data is supposed to get released. * However, the end result of both mechanisms is the same, in that * the stream indirectly referenced a given data-block, rather than * having to keep its own copy of some potentially humongous memory block. */ PUBLIC WUNUSED NONNULL((1, 2)) DREF /*File*/ DeeObject *DCALL DeeFile_OpenObjectMemory(DeeObject *__restrict data_owner, void const *data, size_t data_size) { DREF Reader *result; result = DeeObject_MALLOC(Reader); if unlikely(!result) goto done; Dee_Incref(data_owner); result->r_owner = data_owner; result->r_begin = (char *)data; result->r_end = (char *)data + data_size; result->r_ptr = (char *)data; #ifndef __INTELLISENSE__ result->r_buffer.bb_put = NULL; /* Hide the buffer interface component. */ #endif /* !__INTELLISENSE__ */ DeeLFileObject_Init(result, &DeeFileReader_Type); done: return (DREF DeeObject *)result; } /* Similar to `DeeFile_OpenObjectMemory()', but used * to open a generic object using the buffer-interface. */ PUBLIC WUNUSED NONNULL((1)) DREF /*File*/ DeeObject *DCALL DeeFile_OpenObjectBuffer(DeeObject *__restrict data, size_t begin, size_t end) { DREF Reader *result; result = DeeObject_MALLOC(Reader); if unlikely(!result) goto done; if (DeeObject_GetBuf(data, &result->r_buffer, Dee_BUFFER_FREADONLY)) goto err_r; /* Truncate the end-pointer. */ if (end > result->r_buffer.bb_size) end = result->r_buffer.bb_size; /* Handle empty read. */ if unlikely(begin > end) begin = end; /* Fill in members. */ Dee_Incref(data); result->r_owner = data; result->r_begin = (char *)result->r_buffer.bb_base + begin; result->r_end = (char *)result->r_buffer.bb_base + end; result->r_ptr = result->r_begin; DeeLFileObject_Init(result, &DeeFileReader_Type); done: return (DREF DeeObject *)result; err_r: DeeObject_FREE(result); return NULL; } PRIVATE /*WUNUSED*/ NONNULL((1)) int DCALL writer_ctor(Writer *__restrict self) { rwlock_init(&self->fo_lock); unicode_printer_init(&self->w_printer); self->w_string = NULL; return 0; } PRIVATE WUNUSED NONNULL((1)) int DCALL writer_init(Writer *__restrict self, size_t argc, DeeObject *const *argv) { DeeStringObject *init_string; if (DeeArg_Unpack(argc, argv, "o:_FileWriter", &init_string)) goto err; if (DeeObject_AssertTypeExact(init_string, &DeeString_Type)) goto err; rwlock_init(&self->fo_lock); self->w_printer.up_flags = (uint8_t)DeeString_WIDTH(init_string); if (self->w_printer.up_flags == STRING_WIDTH_1BYTE) { self->w_string = NULL; self->w_printer.up_buffer = DeeString_STR(init_string); self->w_printer.up_length = DeeString_SIZE(init_string); } else { self->w_string = init_string; self->w_printer.up_buffer = DeeString_WSTR(init_string); self->w_printer.up_length = WSTR_LENGTH(self->w_printer.up_buffer); } Dee_Incref(init_string); return 0; err: return -1; } PRIVATE NONNULL((1)) void DCALL writer_fini(Writer *__restrict self) { if (self->w_string) { Dee_Decref(self->w_string); } else if (!self->w_printer.up_buffer) { } else if ((self->w_printer.up_flags & UNICODE_PRINTER_FWIDTH) == STRING_WIDTH_1BYTE) { Dee_Decref(COMPILER_CONTAINER_OF(self->w_printer.up_buffer, DeeStringObject, s_str)); } else { unicode_printer_fini(&self->w_printer); } } PRIVATE NONNULL((1, 2)) void DCALL writer_visit(Writer *__restrict self, dvisit_t proc, void *arg) { DeeFile_LockRead(self); if (self->w_string) { Dee_Visit(self->w_string); } else if (!self->w_printer.up_buffer) { } else if ((self->w_printer.up_flags & UNICODE_PRINTER_FWIDTH) == STRING_WIDTH_1BYTE) { Dee_Visit(COMPILER_CONTAINER_OF(self->w_printer.up_buffer, DeeStringObject, s_str)); } else { } DeeFile_LockEndRead(self); } /* Returns the current string written by the writer. (decoded) */ PUBLIC WUNUSED NONNULL((1)) /*string*/ DREF DeeObject *DCALL DeeFileWriter_GetString(DeeObject *__restrict self) { Writer *me = (Writer *)self; DREF DeeStringObject *result; ASSERT_OBJECT_TYPE_EXACT(me, &DeeFileWriter_Type); again: DeeFile_LockRead(me); if ((me->w_printer.up_flags & UNICODE_PRINTER_FWIDTH) == STRING_WIDTH_1BYTE) { /* Special case for 1-byte strings. */ ASSERT(!me->w_string); if (!me->w_printer.up_buffer) { DeeFile_LockEndRead(me); return_empty_string; } result = COMPILER_CONTAINER_OF(me->w_printer.up_buffer, DeeStringObject, s_str); if (!DeeObject_IsShared(result)) { if (me->w_printer.up_length != result->s_len) { /* Flush the string buffer and deallocated unused memory. */ if (result->s_data) { Dee_string_utf_fini(result->s_data, result); Dee_string_utf_free(result->s_data); result->s_data = NULL; } result->s_hash = DEE_STRING_HASH_UNSET; result->s_len = me->w_printer.up_length; result = (DREF DeeStringObject *)DeeObject_TryRealloc(result, offsetof(DeeStringObject, s_str) + (me->w_printer.up_length + 1) * sizeof(char)); if unlikely(!result) { result = COMPILER_CONTAINER_OF(me->w_printer.up_buffer, DeeStringObject, s_str); } me->w_printer.up_buffer = result->s_str; } result->s_str[result->s_len] = 0; } else { /* The string is already being shared, meaning that the must have already been flushed. */ ASSERT(me->w_printer.up_length == result->s_len); } } else if (me->w_string) { /* A cached multi-byte string has already been set. */ result = me->w_string; } else { #ifndef CONFIG_NO_THREADS if (!atomic_rwlock_upgrade(&me->fo_lock) && (result = me->w_string) != NULL) ; else #endif /* !CONFIG_NO_THREADS */ { /* Must pack together a multi-byte string. */ result = (DREF DeeStringObject *)unicode_printer_trypack(&me->w_printer); if unlikely(!result) goto err_collect; me->w_string = result; me->w_printer.up_flags = (uint8_t)DeeString_WIDTH(result); if (me->w_printer.up_flags == STRING_WIDTH_1BYTE) { me->w_string = NULL; me->w_printer.up_buffer = DeeString_STR(result); me->w_printer.up_length = DeeString_SIZE(result); } else { me->w_string = result; me->w_printer.up_buffer = DeeString_WSTR(result); me->w_printer.up_length = WSTR_LENGTH(me->w_printer.up_buffer); } atomic_rwlock_downgrade(&me->fo_lock); } } Dee_Incref(result); DeeFile_LockEndRead(me); ASSERT(DeeString_STR(result)[DeeString_SIZE(result)] == 0); return (DREF DeeObject *)result; err_collect: DeeFile_LockEndRead(me); if (Dee_CollectMemory((size_t)-1)) goto again; return NULL; } PRIVATE WUNUSED NONNULL((1)) int DCALL writer_delstring(Writer *__restrict self) { DeeFile_LockWrite(self); if (self->w_string) { DeeStringObject *old_string; old_string = self->w_string; self->w_string = NULL; unicode_printer_init(&self->w_printer); DeeFile_LockEndWrite(self); Dee_Decref(old_string); } else if (!self->w_printer.up_buffer) { ASSERT(self->w_printer.up_length == 0); ASSERT((self->w_printer.up_flags & UNICODE_PRINTER_FWIDTH) == STRING_WIDTH_1BYTE); DeeFile_LockEndWrite(self); } else if ((self->w_printer.up_flags & UNICODE_PRINTER_FWIDTH) == STRING_WIDTH_1BYTE) { Dee_Decref(COMPILER_CONTAINER_OF(self->w_printer.up_buffer, DeeStringObject, s_str)); unicode_printer_init(&self->w_printer); DeeFile_LockEndWrite(self); } else { unicode_printer_fini(&self->w_printer); unicode_printer_init(&self->w_printer); DeeFile_LockEndWrite(self); } return 0; } PRIVATE WUNUSED NONNULL((1, 2)) int DCALL writer_setstring(Writer *__restrict self, DeeStringObject *__restrict value) { DREF DeeStringObject *old_string; struct unicode_printer old_printer; if (DeeNone_Check(value)) goto do_del_string; if (DeeObject_AssertTypeExact(value, &DeeString_Type)) goto err; if (DeeString_IsEmpty(value)) goto do_del_string; Dee_Incref(value); DeeFile_LockWrite(self); memcpy(&old_printer, &self->w_printer, sizeof(struct unicode_printer)); old_string = self->w_string; self->w_printer.up_flags = (uint8_t)DeeString_WIDTH(value); if (self->w_printer.up_flags == STRING_WIDTH_1BYTE) { self->w_string = NULL; self->w_printer.up_buffer = DeeString_STR(value); self->w_printer.up_length = DeeString_SIZE(value); } else { self->w_string = value; self->w_printer.up_buffer = DeeString_WSTR(value); self->w_printer.up_length = WSTR_LENGTH(self->w_printer.up_buffer); } DeeFile_LockEndWrite(self); if (old_string) { Dee_Decref(old_string); } else if (!old_printer.up_buffer) { ASSERT(old_printer.up_length == 0); ASSERT((old_printer.up_flags & UNICODE_PRINTER_FWIDTH) == STRING_WIDTH_1BYTE); } else if ((old_printer.up_flags & UNICODE_PRINTER_FWIDTH) == STRING_WIDTH_1BYTE) { Dee_Decref(COMPILER_CONTAINER_OF(old_printer.up_buffer, DeeStringObject, s_str)); } else { unicode_printer_fini(&old_printer); } return 0; do_del_string: return writer_delstring(self); err: return -1; } PRIVATE struct type_getset tpconst writer_getsets[] = { { DeeString_STR(&str_string), (DREF DeeObject *(DCALL *)(DeeObject *__restrict))&DeeFileWriter_GetString, (int (DCALL *)(DeeObject *__restrict))&writer_delstring, (int (DCALL *)(DeeObject *, DeeObject *))&writer_setstring, DOC("->?Dstring\n" "Get/set the currently written text string") }, { NULL } }; PRIVATE WUNUSED NONNULL((1)) DREF DeeStringObject *DCALL writer_get(Writer *self, size_t argc, DeeObject *const *argv) { if (DeeArg_Unpack(argc, argv, ":get")) goto err; return (DREF DeeStringObject *)DeeFileWriter_GetString((DeeObject *)self); err: return NULL; } PRIVATE WUNUSED NONNULL((1)) DREF DeeObject *DCALL writer_size(Writer *self, size_t argc, DeeObject *const *argv) { size_t result; if (DeeArg_Unpack(argc, argv, ":size")) goto err; #ifdef CONFIG_NO_THREADS result = self->w_printer.up_length; #else /* CONFIG_NO_THREADS */ result = ATOMIC_READ(self->w_printer.up_length); #endif /* !CONFIG_NO_THREADS */ return DeeInt_NewSize(result); err: return NULL; } PRIVATE WUNUSED NONNULL((1)) DREF DeeObject *DCALL writer_allocated(Writer *self, size_t argc, DeeObject *const *argv) { size_t result; if (DeeArg_Unpack(argc, argv, ":allocated")) goto err; DeeFile_LockRead(self); result = self->w_printer.up_buffer ? WSTR_LENGTH(self->w_printer.up_buffer) : 0; DeeFile_LockEndRead(self); return DeeInt_NewSize(result); err: return NULL; } PRIVATE WUNUSED NONNULL((1)) DREF DeeObject *DCALL writer_sizeof(Writer *self, size_t argc, DeeObject *const *argv) { size_t result; if (DeeArg_Unpack(argc, argv, ":__sizeof__")) goto err; DeeFile_LockRead(self); result = sizeof(Writer) + (self->w_printer.up_buffer ? ((WSTR_LENGTH(self->w_printer.up_buffer) + 1) * STRING_SIZEOF_WIDTH(self->w_printer.up_flags & UNICODE_PRINTER_FWIDTH)) : 0); DeeFile_LockEndRead(self); return DeeInt_NewSize(result); err: return NULL; } PRIVATE struct type_method tpconst writer_methods[] = { { DeeString_STR(&str_get), (DREF DeeObject *(DCALL *)(DeeObject *, size_t, DeeObject *const *))&writer_get, DOC("->?Dstring\n" "Synchronize and retrieve all data that has already been written") }, { "pack", (DREF DeeObject *(DCALL *)(DeeObject *, size_t, DeeObject *const *))&writer_get, DOC("->?Dstring\n" "Deprecated alias for reading from ?#string") }, { DeeString_STR(&str_size), (DREF DeeObject *(DCALL *)(DeeObject *, size_t, DeeObject *const *))&writer_size, DOC("->?Dint\n" "Return the total amount of written bytes") }, { "allocated", (DREF DeeObject *(DCALL *)(DeeObject *, size_t, DeeObject *const *))&writer_allocated, DOC("->?Dint\n" "Returns the currently allocated buffer size (in bytes)") }, { "__sizeof__", (DREF DeeObject *(DCALL *)(DeeObject *, size_t, DeeObject *const *))&writer_sizeof, DOC("->?Dint") }, { NULL } }; #define UNICODE_PRINTER_INITIAL_BUFSIZE 64 PRIVATE WUNUSED NONNULL((1, 2)) bool DCALL writer_tryappend8(Writer *__restrict self, uint8_t const *__restrict buffer, size_t bufsize) { size_t i, written, avail; if (!self->w_printer.up_buffer) { /* Allocate the initial buffer. */ size_t init_size = bufsize; DeeStringObject *init_buffer; if (init_size < UNICODE_PRINTER_INITIAL_BUFSIZE) init_size = UNICODE_PRINTER_INITIAL_BUFSIZE; init_buffer = (DeeStringObject *)DeeObject_TryMalloc(offsetof(DeeStringObject, s_str) + (init_size + 1) * sizeof(char)); if unlikely(!init_buffer) { init_size = bufsize; init_buffer = (DeeStringObject *)DeeObject_TryMalloc(offsetof(DeeStringObject, s_str) + (init_size + 1) * sizeof(char)); if unlikely(!init_buffer) goto err; } DeeObject_Init(init_buffer, &DeeString_Type); init_buffer->s_data = NULL; init_buffer->s_hash = DEE_STRING_HASH_UNSET; init_buffer->s_len = init_size; memcpy(init_buffer->s_str, buffer, bufsize); self->w_printer.up_buffer = init_buffer->s_str; self->w_printer.up_length = bufsize; goto ok; } avail = WSTR_LENGTH(self->w_printer.up_buffer); written = self->w_printer.up_length; ASSERT(avail >= written); SWITCH_SIZEOF_WIDTH(self->w_printer.up_flags & UNICODE_PRINTER_FWIDTH) { CASE_WIDTH_1BYTE: if (written + bufsize > avail) { /* Must allocate more memory. */ DeeStringObject *new_buffer; size_t new_size = avail; do { new_size *= 2; } while (new_size < written + bufsize); new_buffer = (DeeStringObject *)DeeObject_TryRealloc(COMPILER_CONTAINER_OF(self->w_printer.up_buffer, DeeStringObject, s_str), offsetof(DeeStringObject, s_str) + (new_size + 1) * sizeof(char)); if unlikely(!new_buffer) { new_size = written + bufsize; new_buffer = (DeeStringObject *)DeeObject_TryRealloc(COMPILER_CONTAINER_OF(self->w_printer.up_buffer, DeeStringObject, s_str), offsetof(DeeStringObject, s_str) + (new_size + 1) * sizeof(char)); if unlikely(!new_buffer) goto err; } new_buffer->s_len = new_size; self->w_printer.up_buffer = new_buffer->s_str; } memcpy((uint8_t *)self->w_printer.up_buffer + self->w_printer.up_length, buffer, bufsize); self->w_printer.up_length += bufsize; break; CASE_WIDTH_2BYTE: { uint16_t *dst; if (written + bufsize > avail) { /* Must allocate more memory. */ uint16_t *new_buffer; size_t new_size = avail; do { new_size *= 2; } while (new_size < written + bufsize); new_buffer = DeeString_TryResize2ByteBuffer((uint16_t *)self->w_printer.up_buffer, new_size); if unlikely(!new_buffer) { new_buffer = DeeString_TryResize2ByteBuffer((uint16_t *)self->w_printer.up_buffer, written + bufsize); if unlikely(!new_buffer) goto err; } self->w_printer.up_buffer = new_buffer; } dst = (uint16_t *)self->w_printer.up_buffer; dst += self->w_printer.up_length; self->w_printer.up_length += bufsize; for (i = 0; i < bufsize; ++i) *dst++ = buffer[i]; } break; CASE_WIDTH_4BYTE: { uint32_t *dst; if (written + bufsize > avail) { /* Must allocate more memory. */ uint32_t *new_buffer; size_t new_size = avail; do { new_size *= 2; } while (new_size < written + bufsize); new_buffer = DeeString_TryResize4ByteBuffer((uint32_t *)self->w_printer.up_buffer, new_size); if unlikely(!new_buffer) { new_buffer = DeeString_TryResize4ByteBuffer((uint32_t *)self->w_printer.up_buffer, written + bufsize); if unlikely(!new_buffer) goto err; } self->w_printer.up_buffer = new_buffer; } dst = (uint32_t *)self->w_printer.up_buffer; dst += self->w_printer.up_length; self->w_printer.up_length += bufsize; for (i = 0; i < bufsize; ++i) *dst++ = buffer[i]; } break; } ok: return true; err: return false; } PRIVATE WUNUSED NONNULL((1)) bool DCALL writer_tryappendch(Writer *__restrict self, uint32_t ch) { size_t written, avail; if (!self->w_printer.up_buffer) { /* Allocate the initial buffer. */ if (ch <= 0xff) { size_t init_size = UNICODE_PRINTER_INITIAL_BUFSIZE; DeeStringObject *init_buffer; init_buffer = (DeeStringObject *)DeeObject_TryMalloc(offsetof(DeeStringObject, s_str) + (init_size + 1) * sizeof(char)); if unlikely(!init_buffer) { init_size = 1; init_buffer = (DeeStringObject *)DeeObject_TryMalloc(offsetof(DeeStringObject, s_str) + (init_size + 1) * sizeof(char)); if unlikely(!init_buffer) goto err; } DeeObject_Init(init_buffer, &DeeString_Type); init_buffer->s_data = NULL; init_buffer->s_hash = DEE_STRING_HASH_UNSET; init_buffer->s_len = init_size; init_buffer->s_str[0] = (char)(uint8_t)ch; ASSERT((self->w_printer.up_flags & UNICODE_PRINTER_FWIDTH) == STRING_WIDTH_1BYTE); self->w_printer.up_buffer = init_buffer->s_str; self->w_printer.up_length = 1; } else if (ch <= 0xffff) { uint16_t *init_buffer; init_buffer = DeeString_TryNew2ByteBuffer(UNICODE_PRINTER_INITIAL_BUFSIZE); if unlikely(!init_buffer) { init_buffer = DeeString_TryNew2ByteBuffer(1); if unlikely(!init_buffer) goto err; } init_buffer[0] = (uint16_t)ch; self->w_printer.up_buffer = init_buffer; self->w_printer.up_length = 1; ASSERT((self->w_printer.up_flags & UNICODE_PRINTER_FWIDTH) == STRING_WIDTH_1BYTE); self->w_printer.up_flags |= STRING_WIDTH_2BYTE; } else { uint32_t *init_buffer; init_buffer = DeeString_TryNew4ByteBuffer(UNICODE_PRINTER_INITIAL_BUFSIZE); if unlikely(!init_buffer) { init_buffer = DeeString_TryNew4ByteBuffer(1); if unlikely(!init_buffer) goto err; } init_buffer[0] = ch; self->w_printer.up_buffer = init_buffer; self->w_printer.up_length = 1; ASSERT((self->w_printer.up_flags & UNICODE_PRINTER_FWIDTH) == STRING_WIDTH_1BYTE); self->w_printer.up_flags |= STRING_WIDTH_4BYTE; } goto ok; } /* Append to an existing buffer, possibly up-casting that buffer to a greater magnitude. */ avail = WSTR_LENGTH(self->w_printer.up_buffer); written = self->w_printer.up_length; ASSERT(avail >= written); SWITCH_SIZEOF_WIDTH(self->w_printer.up_flags & UNICODE_PRINTER_FWIDTH) { CASE_WIDTH_1BYTE: if (ch <= 0xff) { if (written >= avail) { /* Must allocate more memory. */ DeeStringObject *new_buffer; size_t new_size = avail; do { new_size *= 2; } while (new_size <= written); new_buffer = (DeeStringObject *)DeeObject_TryRealloc(COMPILER_CONTAINER_OF(self->w_printer.up_buffer, DeeStringObject, s_str), offsetof(DeeStringObject, s_str) + (new_size + 1) * sizeof(char)); if unlikely(!new_buffer) { new_size = written + 1; new_buffer = (DeeStringObject *)DeeObject_TryRealloc(COMPILER_CONTAINER_OF(self->w_printer.up_buffer, DeeStringObject, s_str), offsetof(DeeStringObject, s_str) + (new_size + 1) * sizeof(char)); if unlikely(!new_buffer) goto err; } new_buffer->s_len = new_size; self->w_printer.up_buffer = new_buffer->s_str; } ((uint8_t *)self->w_printer.up_buffer)[self->w_printer.up_length] = (uint8_t)ch; ++self->w_printer.up_length; break; } if (ch <= 0xffff) { /* Must up-cast to 16-bit */ uint16_t *new_buffer; size_t i, length; length = self->w_printer.up_length; new_buffer = DeeString_TryNew2ByteBuffer(length + 1); if unlikely(!new_buffer) goto err; for (i = 0; i < length; ++i) new_buffer[i] = ((uint8_t *)self->w_printer.up_buffer)[i]; new_buffer[length] = (uint16_t)ch; DeeObject_Free(COMPILER_CONTAINER_OF(self->w_printer.up_buffer, DeeStringObject, s_str)); Dee_DecrefNokill(&DeeString_Type); self->w_printer.up_buffer = new_buffer; #if STRING_WIDTH_1BYTE != 0 self->w_printer.up_flags &= ~UNICODE_PRINTER_FWIDTH; #endif /* STRING_WIDTH_1BYTE != 0 */ self->w_printer.up_flags |= STRING_WIDTH_2BYTE; ++self->w_printer.up_length; } else { /* Must up-cast to 32-bit */ uint32_t *new_buffer; size_t i, length; length = self->w_printer.up_length; new_buffer = DeeString_TryNew4ByteBuffer(length + 1); if unlikely(!new_buffer) goto err; for (i = 0; i < length; ++i) new_buffer[i] = ((uint8_t *)self->w_printer.up_buffer)[i]; new_buffer[length] = (uint32_t)ch; DeeObject_Free(COMPILER_CONTAINER_OF(self->w_printer.up_buffer, DeeStringObject, s_str)); Dee_DecrefNokill(&DeeString_Type); self->w_printer.up_buffer = new_buffer; #if STRING_WIDTH_1BYTE != 0 self->w_printer.up_flags &= ~UNICODE_PRINTER_FWIDTH; #endif /* STRING_WIDTH_1BYTE != 0 */ self->w_printer.up_flags |= STRING_WIDTH_4BYTE; ++self->w_printer.up_length; } break; CASE_WIDTH_2BYTE: if (ch > 0xffff) { /* Must up-cast to 32-bit. */ uint32_t *new_buffer; size_t i, length; uint16_t *src; length = self->w_printer.up_length; new_buffer = DeeString_TryNew4ByteBuffer(length + 1); if unlikely(!new_buffer) goto err; src = (uint16_t *)self->w_printer.up_buffer; for (i = 0; i < length; ++i) new_buffer[i] = src[i]; new_buffer[length] = ch; self->w_printer.up_buffer = new_buffer; self->w_printer.up_flags &= ~UNICODE_PRINTER_FWIDTH; self->w_printer.up_flags |= STRING_WIDTH_4BYTE; ++self->w_printer.up_length; Dee_Free((size_t *)src - 1); break; } if (written >= avail) { /* Must allocate more memory. */ uint16_t *new_buffer; size_t new_size = avail; do { new_size *= 2; } while (new_size <= written); new_buffer = DeeString_TryResize2ByteBuffer((uint16_t *)self->w_printer.up_buffer, new_size); if unlikely(!new_buffer) { new_buffer = DeeString_TryResize2ByteBuffer((uint16_t *)self->w_printer.up_buffer, written + 1); if unlikely(!new_buffer) goto err; } self->w_printer.up_buffer = new_buffer; } ((uint16_t *)self->w_printer.up_buffer)[self->w_printer.up_length] = (uint16_t)ch; ++self->w_printer.up_length; break; CASE_WIDTH_4BYTE: if (written >= avail) { /* Must allocate more memory. */ uint32_t *new_buffer; size_t new_size = avail; do { new_size *= 2; } while (new_size <= written); new_buffer = DeeString_TryResize4ByteBuffer((uint32_t *)self->w_printer.up_buffer, new_size); if unlikely(!new_buffer) { new_buffer = DeeString_TryResize4ByteBuffer((uint32_t *)self->w_printer.up_buffer, written + 1); if unlikely(!new_buffer) goto err; } self->w_printer.up_buffer = new_buffer; } ((uint32_t *)self->w_printer.up_buffer)[self->w_printer.up_length] = ch; ++self->w_printer.up_length; break; } ok: return true; err: return false; } INTDEF WUNUSED NONNULL((1)) uint32_t DCALL utf8_getchar(uint8_t const *__restrict base, uint8_t seqlen); PRIVATE WUNUSED NONNULL((1, 2)) size_t DCALL writer_write(Writer *__restrict self, uint8_t const *__restrict buffer, size_t bufsize, dioflag_t UNUSED(flags)) { size_t result = bufsize; again: DeeFile_LockWrite(self); if (self->w_string) { DeeStringObject *wstr = self->w_string; unsigned int width = self->w_printer.up_flags & UNICODE_PRINTER_FWIDTH; ASSERT(DeeString_WIDTH(wstr) != STRING_WIDTH_1BYTE); ASSERT(DeeString_WIDTH(wstr) == width); ASSERT(self->w_printer.up_buffer == DeeString_WSTR(wstr)); ASSERT(self->w_printer.up_length == DeeString_WLEN(wstr)); if (DeeObject_IsShared(wstr)) { /* Unshare the pre-written multi-byte buffer. */ if (width == STRING_WIDTH_2BYTE) { uint16_t *buffer_copy; size_t length; length = self->w_printer.up_length; buffer_copy = DeeString_TryNew2ByteBuffer(length + bufsize); if unlikely(!buffer_copy) { DeeFile_LockEndWrite(self); if (Dee_CollectMemory(sizeof(size_t) + (length + bufsize + 1) * 2)) goto again; goto err; } memcpyw(buffer_copy, self->w_printer.up_buffer, length); self->w_printer.up_buffer = buffer_copy; /* Inherit data */ } else { uint32_t *buffer_copy; size_t length; length = self->w_printer.up_length; buffer_copy = DeeString_TryNew4ByteBuffer(length + bufsize); if unlikely(!buffer_copy) { DeeFile_LockEndWrite(self); if (Dee_CollectMemory(sizeof(size_t) + (length + bufsize + 1) * 4)) goto again; goto err; } memcpyl(buffer_copy, self->w_printer.up_buffer, length); self->w_printer.up_buffer = buffer_copy; /* Inherit data */ } /* Drop our reference to the pre-packed string. */ self->w_string = NULL; DeeFile_LockEndWrite(self); Dee_Decref_unlikely(wstr); goto again; } else { /* The string isn't being shared, so we can just discard all unused data, * and keep on appending to the pre-generated multi-byte buffer. */ struct string_utf *utf = wstr->s_data; ASSERT(utf != NULL); /* WARNING: Just string UTF finalizer that doesn't free width data for `width' */ if (width == STRING_WIDTH_2BYTE && utf->u_data[STRING_WIDTH_4BYTE]) { Dee_Free((size_t *)utf->u_data[STRING_WIDTH_4BYTE] - 1); } else if (width == STRING_WIDTH_4BYTE && utf->u_data[STRING_WIDTH_2BYTE]) { Dee_Free((size_t *)utf->u_data[STRING_WIDTH_2BYTE] - 1); if (utf->u_utf16 && (uint16_t *)utf->u_utf16 != (uint16_t *)utf->u_data[STRING_WIDTH_2BYTE]) Dee_Free((size_t *)utf->u_utf16 - 1); } if (utf->u_utf8 && utf->u_utf8 != wstr->s_str) Dee_Free((size_t *)utf->u_utf8 - 1); Dee_string_utf_free(utf); DeeObject_Free(wstr); Dee_DecrefNokill(&DeeString_Type); } self->w_string = NULL; } else if (self->w_printer.up_buffer && (self->w_printer.up_flags & UNICODE_PRINTER_FWIDTH) == STRING_WIDTH_1BYTE) { DeeStringObject *written_buffer; written_buffer = COMPILER_CONTAINER_OF(self->w_printer.up_buffer, DeeStringObject, s_str); ASSERT(DeeString_WIDTH(written_buffer) == STRING_WIDTH_1BYTE); if unlikely(DeeObject_IsShared(written_buffer)) { /* Unshare the already written portion of the buffer. */ DeeStringObject *buffer_copy; size_t buffer_length = self->w_printer.up_length; ASSERT(buffer_length == DeeString_SIZE(written_buffer)); buffer_copy = (DeeStringObject *)DeeObject_TryMalloc(offsetof(DeeStringObject, s_str) + (buffer_length + bufsize + 1) * sizeof(char)); if unlikely(!buffer_copy) { DeeFile_LockEndWrite(self); if (Dee_CollectMemory(offsetof(DeeStringObject, s_str) + (buffer_length + bufsize + 1) * sizeof(char))) goto again; goto err; } DeeObject_Init(buffer_copy, &DeeString_Type); buffer_copy->s_len = buffer_length; buffer_copy->s_data = NULL; buffer_copy->s_hash = DEE_STRING_HASH_UNSET; memcpyc(buffer_copy->s_str, written_buffer->s_str, self->w_printer.up_length, sizeof(char)); self->w_printer.up_buffer = buffer_copy->s_str; DeeFile_LockEndWrite(self); Dee_Decref_unlikely(written_buffer); goto again; } } /* At this point, we know that the buffer has been locked, and that * the pre-written string has been unshared. - Now we can actually * get to work and start appending the new content! */ if (self->w_printer.up_flags & UNICODE_PRINTER_FPENDING) { /* Complete a UTF-8 sequence. */ uint8_t seqlen = utf8_sequence_len[self->w_printer.up_pend[0]]; uint8_t gotlen = (self->w_printer.up_flags & UNICODE_PRINTER_FPENDING) >> UNICODE_PRINTER_FPENDING_SHFT; uint8_t missing, full_sequence[UTF8_MAX_MBLEN]; ASSERT(gotlen < seqlen); missing = seqlen - gotlen; if (missing > bufsize) { /* Append what we got, but that won't be all of it... */ memcpy(self->w_printer.up_pend + gotlen, buffer, bufsize); self->w_printer.up_flags += (uint8_t)bufsize << UNICODE_PRINTER_FPENDING_SHFT; goto done_unlock; } /* Complete the sequence, and append the character. */ memcpy(full_sequence, self->w_printer.up_pend, gotlen); memcpy(full_sequence + gotlen, buffer, missing); if (!writer_tryappendch(self, utf8_getchar(full_sequence, seqlen))) { DeeFile_LockEndWrite(self); if (Dee_CollectMemory(4)) goto again; } self->w_printer.up_flags &= ~UNICODE_PRINTER_FPENDING; buffer += missing; bufsize -= missing; } { uint8_t *flush_start, *iter, *end; end = (flush_start = iter = (uint8_t *)buffer) + bufsize; while (iter < end) { uint8_t seqlen; /* Search for UTF-8 byte sequences */ if (*iter < 0xc0) { ++iter; continue; } if (flush_start < iter && !writer_tryappend8(self, flush_start, (size_t)(iter - flush_start))) { DeeFile_LockEndWrite(self); buffer = flush_start; bufsize = (size_t)(end - flush_start); if (Dee_CollectMemory((size_t)(iter - flush_start))) goto again; goto err; } /* Goto a multi-byte sequence. */ seqlen = utf8_sequence_len[*iter]; if (seqlen > (size_t)(end - iter)) { /* Incomplete sequence (remember the portion already given) */ seqlen = (uint8_t)(end - iter); self->w_printer.up_flags |= seqlen << UNICODE_PRINTER_FPENDING_SHFT; memcpy(self->w_printer.up_pend, iter, seqlen); goto done_unlock; } /* The full sequence has been given! */ if (!writer_tryappendch(self, utf8_getchar(iter, seqlen))) { DeeFile_LockEndWrite(self); if (!Dee_CollectMemory(4)) goto err; buffer = iter; bufsize = (size_t)(end - iter); goto again; } iter += seqlen; flush_start = iter; } /* Flush the remainder. */ if (flush_start < end && !writer_tryappend8(self, flush_start, (size_t)(end - flush_start))) { DeeFile_LockEndWrite(self); buffer = flush_start; bufsize = (size_t)(end - flush_start); if (Dee_CollectMemory(bufsize)) goto again; goto err; } } done_unlock: DeeFile_LockEndWrite(self); return result; err: return (size_t)-1; } PUBLIC DeeFileTypeObject DeeFileWriter_Type = { /* .ft_base = */ { OBJECT_HEAD_INIT(&DeeFileType_Type), /* .tp_name = */ "_FileWriter", /* .tp_doc = */ NULL, /* .tp_flags = */ TP_FNORMAL, /* .tp_weakrefs = */ 0, /* .tp_features = */ TF_HASFILEOPS | TF_NONLOOPING, /* .tp_base = */ (DeeTypeObject *)&DeeFile_Type, /* .tp_init = */ { { /* .tp_alloc = */ { /* .tp_ctor = */ (dfunptr_t)&writer_ctor, /* .tp_copy_ctor = */ (dfunptr_t)NULL, /* .tp_deep_ctor = */ (dfunptr_t)NULL, /* .tp_any_ctor = */ (dfunptr_t)&writer_init, TYPE_FIXED_ALLOCATOR(Writer) } }, /* .tp_dtor = */ (void (DCALL *)(DeeObject *__restrict))&writer_fini, /* .tp_assign = */ NULL, /* .tp_move_assign = */ NULL }, /* .tp_cast = */ { /* .tp_str = */ NULL, /* .tp_repr = */ NULL, /* .tp_bool = */ NULL }, /* .tp_call = */ NULL, /* .tp_visit = */ (void (DCALL *)(DeeObject *__restrict, dvisit_t, void *))&writer_visit, /* .tp_gc = */ NULL, /* .tp_math = */ NULL, /* .tp_cmp = */ NULL, /* .tp_seq = */ NULL, /* .tp_iter_next = */ NULL, /* .tp_attr = */ NULL, /* .tp_with = */ NULL, /* .tp_buffer = */ NULL, /* .tp_methods = */ writer_methods, /* .tp_getsets = */ writer_getsets, /* .tp_members = */ NULL, /* .tp_class_methods = */ NULL, /* .tp_class_getsets = */ NULL, /* .tp_class_members = */ NULL }, /* .ft_read = */ NULL, /* .ft_write = */ (size_t (DCALL *)(DeeFileObject *__restrict, void const *__restrict, size_t, dioflag_t))&writer_write, /* .ft_seek = */ NULL, /* .ft_sync = */ NULL, /* .ft_trunc = */ NULL, /* .ft_close = */ (int (DCALL *)(DeeFileObject *__restrict))&writer_delstring, /* .ft_pread = */ NULL, /* .ft_pwrite = */ NULL, /* .ft_getc = */ NULL, /* .ft_ungetc = */ NULL, /* .ft_putc = */ NULL }; /* Open a new file stream that writes all written data into a string. */ PUBLIC WUNUSED DREF /*File*/ DeeObject *DCALL DeeFile_OpenWriter(void) { DREF Writer *result; result = DeeObject_MALLOC(Writer); if unlikely(!result) goto done; writer_ctor(result); DeeLFileObject_Init(result, &DeeFileWriter_Type); done: return (DREF DeeObject *)result; } DECL_END #endif /* !GUARD_DEEMON_OBJECTS_FILETYPES_C */
33.935252
124
0.646845
[ "object" ]
489498f4fe890c1f7493898a6b0941a950566049
1,891
h
C
x509ls/cli/certificate_view_layout.h
skip2/x509ls
cc825523b001d244f8338341f1c39bd0cf5bda80
[ "MIT" ]
8
2015-03-13T23:37:40.000Z
2022-01-22T20:53:50.000Z
x509ls/cli/certificate_view_layout.h
skip2/x509ls
cc825523b001d244f8338341f1c39bd0cf5bda80
[ "MIT" ]
null
null
null
x509ls/cli/certificate_view_layout.h
skip2/x509ls
cc825523b001d244f8338341f1c39bd0cf5bda80
[ "MIT" ]
3
2015-03-14T19:52:25.000Z
2019-06-10T09:06:47.000Z
// X509LS // Copyright 2013 Tom Harwood #ifndef X509LS_CLI_CERTIFICATE_VIEW_LAYOUT_H_ #define X509LS_CLI_CERTIFICATE_VIEW_LAYOUT_H_ #include <string> #include "x509ls/base/types.h" #include "x509ls/certificate/certificate.h" #include "x509ls/cli/base/cli_control.h" using std::string; namespace x509ls { class CliApplication; class CommandLine; class MenuBar; class StatusBar; class TextControl; // Screen layout for displaying a single scrollable certificate. // // The screen layout consists of a menu bar, scrollable text representation of // the certificate (the majority of space), spacer rows, and a command line row // for text entry. // // There are two menu options: // - index: Close layout, go back to previous layout, i.e. certificate list. // - save: Save certificate in PEM format. class CertificateViewLayout : public CliControl { public: // Construct a CertificateViewLayout. |certificate| should exist for the // lifetime of the object. CertificateViewLayout(CliApplication* application, const Certificate& certificate); virtual ~CertificateViewLayout(); protected: virtual bool KeyPressEvent(int keypress); virtual void OnEvent(const BaseObject* source, int event_code); private: NO_COPY_AND_ASSIGN(CertificateViewLayout) const Certificate& certificate_; MenuBar* menu_bar_; TextControl* text_control_; StatusBar* status_bar_; CommandLine* command_line_; static const char* kMenuText; // Display the save certificate (as filename) prompt. void StartSaveCertificate(); // Save the certificate to |filename| in PEM format, and set |result_message| // to a short string indicating success or failure. Returns true iif the // certificate was saved successfully. bool SaveCertificate(const string& filename, string* result_message) const; }; } // namespace x509ls #endif // X509LS_CLI_CERTIFICATE_VIEW_LAYOUT_H_
28.223881
79
0.770492
[ "object" ]
489a922f35040b106c227f61ef346c64bf579158
826
h
C
titan-infinite/src/pch.h
KyleKaiWang/titan-infinite
d2905e050501fc076589bb8e1578d3285ec5aab0
[ "Apache-2.0" ]
null
null
null
titan-infinite/src/pch.h
KyleKaiWang/titan-infinite
d2905e050501fc076589bb8e1578d3285ec5aab0
[ "Apache-2.0" ]
null
null
null
titan-infinite/src/pch.h
KyleKaiWang/titan-infinite
d2905e050501fc076589bb8e1578d3285ec5aab0
[ "Apache-2.0" ]
null
null
null
/* * Vulkan Renderer Program * * Copyright (C) 2020 Kyle Wang */ #pragma once #include <vulkan/vulkan.hpp> #include <optional> #include <iostream> #include <fstream> #include <cstdint> #include <string> #include <memory> #include <vector> #include <set> #include <chrono> #include <assert.h> #include <unordered_map> #include <stb_image.h> #include <stb_image_write.h> #include <tiny_gltf.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> #include <glm/gtx/euler_angles.hpp> #include <glm/gtx/quaternion.hpp> #include "transform.h" #include "timer.h" #include "vkHelpers.h" #include "renderer.h" #include "device.h" #include "camera.h" #include "memory.h" #include "buffer.h" #include "texture.h" #include "inverse_kinematics.h" #include "model.h" #include "skybox.h"
18.355556
39
0.725182
[ "vector", "model", "transform" ]
489e75e4a7205fd299fcb9cdb20045abce42b7ef
1,021
h
C
storage/src/vespa/storage/persistence/apply_bucket_diff_state.h
sagiyaho/vespa
5865b9bb80b540f6d252312fa6002300b2f1c9ee
[ "Apache-2.0" ]
4,054
2017-08-11T07:58:38.000Z
2022-03-31T22:32:15.000Z
storage/src/vespa/storage/persistence/apply_bucket_diff_state.h
sagiyaho/vespa
5865b9bb80b540f6d252312fa6002300b2f1c9ee
[ "Apache-2.0" ]
4,854
2017-08-10T20:19:25.000Z
2022-03-31T19:04:23.000Z
storage/src/vespa/storage/persistence/apply_bucket_diff_state.h
sagiyaho/vespa
5865b9bb80b540f6d252312fa6002300b2f1c9ee
[ "Apache-2.0" ]
541
2017-08-10T18:51:18.000Z
2022-03-11T03:18:56.000Z
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include <vespa/persistence/spi/bucket.h> #include <vector> namespace storage { class ApplyBucketDiffEntryResult; class MergeBucketInfoSyncer; /* * State of all bucket diff entry spi operation (putAsync or removeAsync) * for one or more ApplyBucketDiffCommand / ApplyBucketDiffReply. */ class ApplyBucketDiffState { std::vector<ApplyBucketDiffEntryResult> _async_results; const MergeBucketInfoSyncer& _merge_bucket_info_syncer; spi::Bucket _bucket; bool _stale_bucket_info; public: ApplyBucketDiffState(const MergeBucketInfoSyncer &merge_bucket_info_syncer, const spi::Bucket& bucket); ~ApplyBucketDiffState(); void push_back(ApplyBucketDiffEntryResult&& result); bool empty() const; void wait(); void check(); void mark_stale_bucket_info(); void sync_bucket_info(); }; }
30.029412
107
0.708129
[ "vector" ]
48b3661426ebadc1c8c438b316172203e9ede903
15,330
h
C
source/util_api/http/include/http_psover2_interface.h
lgirdk/ccsp-common-library
8d912984e96f960df6dadb4b0e6bc76c76376776
[ "Apache-2.0" ]
4
2018-02-26T05:41:14.000Z
2019-12-20T07:31:39.000Z
source/util_api/http/include/http_psover2_interface.h
rdkcmf/rdkb-CcspCommonLibrary
3eba76685bbf5eb6656f45eb4b57fdb5c269c2a1
[ "Apache-2.0" ]
null
null
null
source/util_api/http/include/http_psover2_interface.h
rdkcmf/rdkb-CcspCommonLibrary
3eba76685bbf5eb6656f45eb4b57fdb5c269c2a1
[ "Apache-2.0" ]
3
2017-07-30T15:35:16.000Z
2020-08-18T20:44:08.000Z
/* * If not stated otherwise in this file or this component's Licenses.txt file the * following copyright and licenses apply: * * Copyright 2015 RDK Management * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /********************************************************************** Copyright [2014] [Cisco Systems, 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. **********************************************************************/ /********************************************************************** module: http_psover2_interface.h For HyperText Transfer Protocol Implementation (HTTP), BroadWay Service Delivery System --------------------------------------------------------------- description: This wrapper file defines all the platform-independent functions and macros for the Http Pso Ver2 Object. --------------------------------------------------------------- environment: platform independent --------------------------------------------------------------- author: Xuechen Yang --------------------------------------------------------------- revision: 03/04/02 initial revision. **********************************************************************/ #ifndef _HTTP_PSOVER2_INTERFACE_ #define _HTTP_PSOVER2_INTERFACE_ /* * This object is derived a virtual base object defined by the underlying framework. We include the * interface header files of the base object here to shield other objects from knowing the derived * relationship between this object and its base class. */ #include "ansc_co_interface.h" #include "ansc_co_external_api.h" #include "http_properties.h" /*********************************************************** PLATFORM INDEPENDENT HTTP PSO VER2 OBJECT DEFINITION ***********************************************************/ /* * Define some const values that will be used in the object mapper object definition. */ #define HTTP_PSOVER2_STATE_INITIALIZED 0 #define HTTP_PSOVER2_STATE_CLIENT_CONNECTED 1 #define HTTP_PSOVER2_STATE_FINISHED 2 #define HTTP_PSOVER2_QMODE_COLLECT 1 #define HTTP_PSOVER2_QMODE_PROCESS 2 #define HTTP_PSOVER2_SFLAG_HEADERS 0x00000001 #define HTTP_PSOVER2_SFLAG_BODY 0x00000002 /* * Since we write all kernel modules in C (due to better performance and lack of compiler support), * we have to simulate the C++ object by encapsulating a set of functions inside a data structure. */ typedef ANSC_HANDLE (*PFN_HTTPPSOVER2_GET_CONTEXT) ( ANSC_HANDLE hThisObject ); typedef ANSC_STATUS (*PFN_HTTPPSOVER2_SET_CONTEXT) ( ANSC_HANDLE hThisObject, ANSC_HANDLE hContext ); typedef ANSC_HANDLE (*PFN_HTTPPSOVER2_GET_IF) ( ANSC_HANDLE hThisObject ); typedef ANSC_STATUS (*PFN_HTTPPSOVER2_SET_IF) ( ANSC_HANDLE hThisObject, ANSC_HANDLE hInterface ); typedef ULONG (*PFN_HTTPPSOVER2_GET_MODE) ( ANSC_HANDLE hThisObject ); typedef ANSC_STATUS (*PFN_HTTPPSOVER2_SET_MODE) ( ANSC_HANDLE hThisObject, ULONG ulMode ); typedef ULONG (*PFN_HTTPPSOVER2_GET_STATE) ( ANSC_HANDLE hThisObject ); typedef ANSC_STATUS (*PFN_HTTPPSOVER2_SET_STATE) ( ANSC_HANDLE hThisObject, ULONG ulState ); typedef ANSC_STATUS (*PFN_HTTPPSOVER2_GET_PROPERTY) ( ANSC_HANDLE hThisObject, ANSC_HANDLE hProperty ); typedef ANSC_STATUS (*PFN_HTTPPSOVER2_SET_PROPERTY) ( ANSC_HANDLE hThisObject, ANSC_HANDLE hProperty ); typedef ANSC_STATUS (*PFN_HTTPPSOVER2_RETURN) ( ANSC_HANDLE hThisObject ); typedef ANSC_STATUS (*PFN_HTTPPSOVER2_RESET) ( ANSC_HANDLE hThisObject ); typedef ANSC_STATUS (*PFN_HTTPPSOVER2_OPEN) ( ANSC_HANDLE hThisObject ); typedef ANSC_STATUS (*PFN_HTTPPSOVER2_CLOSE) ( ANSC_HANDLE hThisObject ); typedef ANSC_STATUS (*PFN_HTTPPSOVER2_ENGAGE) ( ANSC_HANDLE hThisObject ); typedef ANSC_STATUS (*PFN_HTTPPSOVER2_CANCEL) ( ANSC_HANDLE hThisObject ); typedef ANSC_STATUS (*PFN_HTTPPSOVER2_ACQUIRE) ( ANSC_HANDLE hThisObject ); typedef ANSC_STATUS (*PFN_HTTPPSOVER2_RELEASE) ( ANSC_HANDLE hThisObject ); typedef ANSC_HANDLE (*PFN_HTTPPSOVER2_ASK_TRO) ( ANSC_HANDLE hThisObject, ANSC_HANDLE hSocket ); typedef ANSC_HANDLE (*PFN_HTTPPSOVER2_POP_TRO) ( ANSC_HANDLE hThisObject, ANSC_HANDLE hSocket ); typedef ANSC_HANDLE (*PFN_HTTPPSOVER2_GET_TRO) ( ANSC_HANDLE hThisObject ); typedef ANSC_HANDLE (*PFN_HTTPPSOVER2_ADD_TRO) ( ANSC_HANDLE hThisObject ); typedef ANSC_STATUS (*PFN_HTTPPSOVER2_DEL_ALL) ( ANSC_HANDLE hThisObject ); typedef ULONG (*PFN_HTTPPSOVER2_QUERY) ( ANSC_HANDLE hThisObject, PVOID buffer, ULONG ulSize, ANSC_HANDLE hBufferContext ); typedef ANSC_STATUS (*PFN_HTTPPSOVER2_RECV) ( ANSC_HANDLE hThisObject, PVOID buffer, ULONG ulSize, ANSC_HANDLE hBufferContext ); typedef ANSC_STATUS (*PFN_HTTPPSOVER2_FINISH) ( ANSC_HANDLE hThisObject, PVOID buffer, ULONG ulSize, ANSC_HANDLE hBufferContext ); typedef ANSC_STATUS (*PFN_HTTPPSOVER2_SEND) ( ANSC_HANDLE hThisObject, ANSC_HANDLE hMessage, ULONG ulSendFlags ); typedef BOOL (*PFN_HTTPPSOVER2_ACCEPT) ( ANSC_HANDLE hThisObject, ANSC_HANDLE hReserved ); typedef ANSC_STATUS (*PFN_HTTPPSOVER2_AUTH) ( ANSC_HANDLE hThisObject, ANSC_HANDLE hReserved ); /* * A significant difference between HTTP/1.1 and earlier versions of HTTP is that persistent co- * nnetions are the default behavior of any HTTP connection. That is, unless otherwise indicated, * the client SHOULD assme that the server will maintain a persistent connection, even after error * responses from the server. * * The HTTP Simple Proxy Object creates a unique outbound session for each inbound HTTP session: * the closing of either session will bring down the other. The proxy itself does NOT contribute * to the maintainence of the persistent connection. Note that more sophisticated HTTP proxies MAY * employ different session management to cope with following requirements: * * $ providing cached response directly to the clients * $ enable outbound session sharing if multiple clients is requesting the same URL * $ maintain inbound and outbound sessions separately for better efficiency */ #define HTTP_PSO_VER2_CLASS_CONTENT \ /* duplication of the base object class content */ \ ANSCCO_CLASS_CONTENT \ /* start of object class content */ \ ANSC_HANDLE hWamIf; \ ANSC_HANDLE hSbcIf; \ ANSC_HANDLE hCbcIf; \ ANSC_HANDLE hPbcIf; \ ANSC_HANDLE hHfpIf; \ ANSC_HANDLE hClientSocket; \ ANSC_HANDLE hSbcContext; \ ANSC_HANDLE hCbcContext; \ ULONG HashIndex; \ ULONG SbcPmode; \ ULONG CbcPmode; \ ULONG SessionState; \ ANSC_LOCK AccessLock; \ \ SLIST_HEADER TroSList; \ ANSC_LOCK TroSListLock; \ \ PFN_HTTPPSOVER2_GET_IF GetWamIf; \ PFN_HTTPPSOVER2_SET_IF SetWamIf; \ PFN_HTTPPSOVER2_GET_IF GetSbcIf; \ PFN_HTTPPSOVER2_SET_IF SetSbcIf; \ PFN_HTTPPSOVER2_GET_IF GetCbcIf; \ PFN_HTTPPSOVER2_SET_IF SetCbcIf; \ PFN_HTTPPSOVER2_GET_IF GetPbcIf; \ PFN_HTTPPSOVER2_SET_IF SetPbcIf; \ PFN_HTTPPSOVER2_GET_IF GetHfpIf; \ PFN_HTTPPSOVER2_SET_IF SetHfpIf; \ \ PFN_HTTPPSOVER2_GET_CONTEXT GetClientSocket; \ PFN_HTTPPSOVER2_SET_CONTEXT SetClientSocket; \ PFN_HTTPPSOVER2_GET_CONTEXT GetSbcContext; \ PFN_HTTPPSOVER2_SET_CONTEXT SetSbcContext; \ PFN_HTTPPSOVER2_GET_CONTEXT GetCbcContext; \ PFN_HTTPPSOVER2_SET_CONTEXT SetCbcContext; \ \ PFN_HTTPPSOVER2_GET_MODE GetSbcPmode; \ PFN_HTTPPSOVER2_SET_MODE SetSbcPmode; \ PFN_HTTPPSOVER2_GET_MODE GetCbcPmode; \ PFN_HTTPPSOVER2_SET_MODE SetCbcPmode; \ PFN_HTTPPSOVER2_GET_STATE GetSessionState; \ PFN_HTTPPSOVER2_SET_STATE SetSessionState; \ \ PFN_HTTPPSOVER2_RETURN Return; \ PFN_HTTPPSOVER2_RESET Reset; \ \ PFN_HTTPPSOVER2_OPEN Open; \ PFN_HTTPPSOVER2_CLOSE Close; \ \ PFN_HTTPPSOVER2_ACQUIRE AcquireAccess; \ PFN_HTTPPSOVER2_RELEASE ReleaseAccess; \ \ PFN_HTTPPSOVER2_ASK_TRO AskTroBySocket; \ PFN_HTTPPSOVER2_POP_TRO PopTroBySocket; \ PFN_HTTPPSOVER2_GET_TRO GetLastTro; \ PFN_HTTPPSOVER2_GET_TRO GetCurTro; \ PFN_HTTPPSOVER2_ADD_TRO AddNewTro; \ PFN_HTTPPSOVER2_DEL_ALL DelAllTros; \ \ PFN_HTTPPSOVER2_QUERY QueryForClient; \ PFN_HTTPPSOVER2_RECV RecvFromClient; \ PFN_HTTPPSOVER2_FINISH FinishedByClient; \ PFN_HTTPPSOVER2_ACCEPT AcceptClient; \ PFN_HTTPPSOVER2_AUTH Authenticate; \ /* end of object class content */ \ typedef struct _HTTP_PSO_VER2_OBJECT { HTTP_PSO_VER2_CLASS_CONTENT } HTTP_PSO_VER2_OBJECT, *PHTTP_PSO_VER2_OBJECT; #define ACCESS_HTTP_PSO_VER2_OBJECT(p) \ ACCESS_CONTAINER(p, HTTP_PSO_VER2_OBJECT, Linkage) #endif
38.517588
99
0.451794
[ "object" ]
48b44c43a6443bf09c5469b08d7a8092a590eb52
2,621
h
C
renderer/shader.h
Jerrody/ionengine_ops
8327e1d067e0be1a57464e365bc103365c2f0e3d
[ "MIT" ]
null
null
null
renderer/shader.h
Jerrody/ionengine_ops
8327e1d067e0be1a57464e365bc103365c2f0e3d
[ "MIT" ]
null
null
null
renderer/shader.h
Jerrody/ionengine_ops
8327e1d067e0be1a57464e365bc103365c2f0e3d
[ "MIT" ]
null
null
null
// Copyright © 2020-2021 Dmitriy Lukovenko. All rights reserved. #pragma once #include <renderer/backend.h> #include <renderer/data.h> #include <lib/math/vector.h> namespace ionengine::renderer { template<class Type> struct ShaderBinding { uint32_t index; std::u8string name; }; template<> struct ShaderBinding<Sampler> { uint32_t index; std::u8string name; }; template<> struct ShaderBinding<Buffer> { uint32_t index; std::u8string name; }; template<> struct ShaderBinding<Texture> { uint32_t index; std::u8string name; }; using ShaderBindingDesc = std::variant<ShaderBinding<Sampler>, ShaderBinding<Buffer>,ShaderBinding<Texture>>; using ShaderEffectId = uint32_t; using ShaderBindingId = uint32_t; struct ShaderEffectDesc { std::map<std::u8string, ShaderPackageData::ShaderInfo const*> shader_infos; std::unordered_map<ShaderBindingId, ShaderBindingDesc> shader_bindings; ShaderEffectDesc& set_shader_code(std::u8string const& name, ShaderPackageData::ShaderInfo const& shader_info, ShaderFlags const flags) { shader_infos[name] = &shader_info; return *this; } ShaderEffectDesc& set_binding(ShaderBindingId const id, ShaderBindingDesc const& shader_binding_desc) { shader_bindings[id] = shader_binding_desc; return *this; } }; class ShaderEffect { public: ShaderEffect() = default; std::span<Handle<Shader> const> shaders() const; ShaderBindingDesc const& bindings(ShaderBindingId const id) const; private: friend class ShaderEffectBinder; friend class ShaderCache; std::unordered_map<ShaderBindingId, ShaderBindingDesc> _bindings; std::vector<Handle<Shader>> _shaders; }; class ShaderEffectBinder { public: ShaderEffectBinder(ShaderEffect& shader_effect); ShaderEffectBinder& bind(ShaderBindingId const id, std::variant<Handle<Texture>, Handle<Buffer>, Handle<Sampler>> const& target); void update(Backend& backend, Handle<DescriptorSet> const& descriptor_set); private: ShaderEffect* _shader_effect; std::array<DescriptorWriteDesc, 64> _descriptor_updates; uint32_t _update_count{0}; }; class ShaderCache { public: ShaderCache() = default; void create_shader_effect(Backend& backend, ShaderEffectId const id, ShaderEffectDesc const& shader_effect_desc); ShaderEffect const& shader_effect(ShaderEffectId const id) const; ShaderEffect& shader_effect(ShaderEffectId const id); private: std::unordered_map<ShaderEffectId, ShaderEffect> _shader_effects; std::map<std::u8string, Handle<Shader>> _shader_cache; }; }
23.19469
141
0.741702
[ "vector" ]
1edad38c689aea82d5837cdb23fde617f5a08811
1,262
h
C
Source/video.h
matanui159/8-Bee
431cd2e405fe29e8dadb8b0c5e59c307348cef4f
[ "Apache-2.0" ]
null
null
null
Source/video.h
matanui159/8-Bee
431cd2e405fe29e8dadb8b0c5e59c307348cef4f
[ "Apache-2.0" ]
null
null
null
Source/video.h
matanui159/8-Bee
431cd2e405fe29e8dadb8b0c5e59c307348cef4f
[ "Apache-2.0" ]
null
null
null
/* * video.h * * Copyright 2018 Joshua Michael Minter * * 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 VIDEO_H_ #define VIDEO_H_ #include <8bee.h> #include "transform.h" void bee__video_init_native(void* window); void bee__video_update_native(); void bee__video_clear(); void* bee__video_texture_create(int width, int height, unsigned short* data); void bee__video_texture_update(void* texture, const bee_sprite_t* sprite, unsigned short* data); void bee__video_texture_target(void* texture); void bee__video_texture_draw(void* texture, const bee_sprite_t* sprite, const bee__matrix_t* matrix); void bee__video_init(); void bee__video_data(unsigned short* data); void bee__video_update(); #endif
33.210526
102
0.748019
[ "transform" ]
1eddaa214139d4a55036d38fb71965196b501d7f
20,969
h
C
src/AzslcTypes.h
aws-lumberyard-dev/o3de-azslc
bafacbe822da625da22ceba09e8fcdcf18d8d09b
[ "Apache-2.0", "MIT" ]
13
2021-07-23T00:11:20.000Z
2022-02-09T07:59:20.000Z
src/AzslcTypes.h
aws-lumberyard-dev/o3de-azslc
bafacbe822da625da22ceba09e8fcdcf18d8d09b
[ "Apache-2.0", "MIT" ]
10
2021-09-14T12:12:22.000Z
2022-03-30T21:27:10.000Z
src/AzslcTypes.h
aws-lumberyard-dev/o3de-azslc
bafacbe822da625da22ceba09e8fcdcf18d8d09b
[ "Apache-2.0", "MIT" ]
5
2021-07-19T23:49:51.000Z
2021-12-02T05:13:35.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #pragma once #include "AzslcUtils.h" namespace AZ::ShaderCompiler { // type classes before canonicalization. // post canonicalization, you can't have generic arithmetic nor typeof. MAKE_REFLECTABLE_ENUM (TypeClass, // Error case IsNotType, // The void type Void, // Predefined Scalar, Vector, GenericVector, // vector<t,d> Matrix, GenericMatrix, // matrix<t,d1,d2> Texture, GenericTexture, MultisampledTexture, Sampler, StructuredBuffer, Buffer, ByteAddressBuffer, ConstantBuffer, StreamOutput, LibrarySubobject, OtherViewBufferType, OtherPredefined, // IO patch // Not predefined Struct, Class, Interface, Enum, TypeofExpression, Alias ); // == category queries == inline bool IsUserDefined(TypeClass typeClass) { return typeClass.IsOneOf(TypeClass::Struct, TypeClass::Class, TypeClass::Interface, TypeClass::Enum); } //! a product type is a (non-union) 'structured' type. (Cartesian product in type theory) inline bool IsProductType(TypeClass typeClass) { return typeClass.IsOneOf(TypeClass::Struct, TypeClass::Class, TypeClass::Interface); } // predefined types are all HLSL base types (void included) inline bool IsPredefinedType(TypeClass typeClass) { return !typeClass.IsOneOf(TypeClass::IsNotType, TypeClass::TypeofExpression, TypeClass::Alias) && !IsUserDefined(typeClass); } // an arithmetic type, but not non-generic inline bool IsNonGenericArithmetic(TypeClass typeClass) { return typeClass.IsOneOf(TypeClass::Scalar, TypeClass::Vector, TypeClass::Matrix); } // has a generic to canonicalize inline bool IsGenericArithmetic(TypeClass typeClass) { return typeClass.IsOneOf(TypeClass::GenericVector, TypeClass::GenericMatrix); } inline bool IsArithmetic(TypeClass typeClass) { return IsGenericArithmetic(typeClass) || IsNonGenericArithmetic(typeClass); } // a fundamental is void or arithmetic inline bool IsFundamental(TypeClass typeClass) { return typeClass == TypeClass::Void || IsArithmetic(typeClass); } // type that behaves like its generic parameter inline bool IsChameleon(TypeClass typeClass) { // IO patch are not strict chameleon because they behave like an array. if we consider array collapsing then maybe they are. return typeClass.IsOneOf(TypeClass::StructuredBuffer, TypeClass::Buffer, TypeClass::StreamOutput, TypeClass::ConstantBuffer); } inline bool HasGenericParameter(TypeClass typeClass) { // TODO: to add InputPath/OutputPatch because it has a generic parameter. (when you do it, update ExtractGenericTypeParameterNameFromAstContext) return IsChameleon(typeClass) || IsGenericArithmetic(typeClass) || typeClass.IsOneOf(TypeClass::GenericTexture, TypeClass::MultisampledTexture); } inline bool IsViewTypeBuffer(TypeClass typeClass) { return typeClass.IsOneOf(TypeClass::ConstantBuffer, TypeClass::StructuredBuffer, TypeClass::Buffer, TypeClass::ByteAddressBuffer, TypeClass::OtherViewBufferType); } inline bool IsViewType(TypeClass typeClass) { // note that a constant buffer is not a view type return IsViewTypeBuffer(typeClass) || typeClass.IsOneOf(TypeClass::Texture, TypeClass::GenericTexture, TypeClass::MultisampledTexture, TypeClass::Sampler); } //Example Texture2D m_myTex[]; is supported. inline bool CanBeDeclaredAsUnboundedArray(TypeClass typeClass) { return IsViewType(typeClass); } // Get TypeClass for type inside a predefined context inline TypeClass AnalyzeTypeClass(azslParser::PredefinedTypeContext* predefinedNode) { TypeClass toReturn = TypeClass::OtherPredefined; // default value if nothing of the under was non null. using PredefinedNodeT = std::remove_pointer_t<decltype(predefinedNode)>; // DRY // map TypeClasses to the same indexes than the context functions list array<TypeClass, 16> contextClasses = { TypeClass::Scalar, TypeClass::Vector, TypeClass::GenericVector, TypeClass::Matrix, TypeClass::GenericMatrix, TypeClass::Texture, TypeClass::MultisampledTexture, TypeClass::GenericTexture, TypeClass::Sampler, TypeClass::StructuredBuffer, TypeClass::Buffer, TypeClass::ByteAddressBuffer, TypeClass::ConstantBuffer, TypeClass::StreamOutput, TypeClass::OtherViewBufferType, TypeClass::LibrarySubobject}; // create a constexpr valuelist of member function pointers using FunctionList = ValueTplList< &PredefinedNodeT::scalarType, &PredefinedNodeT::vectorType, &PredefinedNodeT::genericVectorType, &PredefinedNodeT::matrixType, &PredefinedNodeT::genericMatrixPredefinedType, &PredefinedNodeT::texturePredefinedType, &PredefinedNodeT::msTexturePredefinedType, &PredefinedNodeT::genericTexturePredefinedType, &PredefinedNodeT::samplerStatePredefinedType, &PredefinedNodeT::structuredBufferPredefinedType, &PredefinedNodeT::bufferPredefinedType, &PredefinedNodeT::byteAddressBufferTypes, &PredefinedNodeT::constantBufferTemplated, &PredefinedNodeT::streamOutputPredefinedType, &PredefinedNodeT::otherViewResourceType, &PredefinedNodeT::subobjectType >; static_assert( countTemplateParameters_v<FunctionList> == contextClasses.size() ); // This meta-loop will be unfolded at build time, therefore the generic lambda will be instantiated individually (by each type) ForEachValue<FunctionList>([&toReturn, &predefinedNode, &contextClasses](auto ctxMemFn, auto index) { if ((predefinedNode->*ctxMemFn)()) // pointer-to-member-function call. { toReturn = contextClasses[index]; } }); return toReturn; } // Get TypeClass for type inside a type context inline TypeClass AnalyzeTypeClass(AstType* typeNode) { TypeClass toReturn = TypeClass::IsNotType; if (typeNode != nullptr) { if (typeNode->predefinedType()) { toReturn = AnalyzeTypeClass(typeNode->predefinedType()); } else if (typeNode->userDefinedType() && typeNode->userDefinedType()->anyStructuredTypeDefinition()) { if (typeNode->userDefinedType()->anyStructuredTypeDefinition()->classDefinition()) { toReturn = TypeClass::Class; } else if (typeNode->userDefinedType()->anyStructuredTypeDefinition()->interfaceDefinition()) { toReturn = TypeClass::Interface; } else if (typeNode->userDefinedType()->anyStructuredTypeDefinition()->structDefinition()) { toReturn = TypeClass::Struct; } else if (typeNode->userDefinedType()->anyStructuredTypeDefinition()->enumDefinition()) { toReturn = TypeClass::Enum; } } else if (typeNode->typeofExpression()) { toReturn = TypeClass::TypeofExpression; } } return toReturn; } // Get TypeClass for type inside a functype context inline TypeClass AnalyzeTypeClass(AstFuncType* funcTypeNode) { TypeClass toReturn = TypeClass::IsNotType; if (funcTypeNode != nullptr) { if (funcTypeNode->Void()) { toReturn = TypeClass::Void; } else { AstType* typeNode = funcTypeNode->type(); toReturn = AnalyzeTypeClass(typeNode); } } return toReturn; } // Analyze a type (by parsing it) and return what class it belongs to. // Don't let too wild uncontrolled input sneak in there, there may be vectors of attack. inline TypeClass AnalyzeTypeClass(string_view typeName) { assert(typeName.find("/") == string::npos); // forgot to unmangle ? use the TentativeName overload in these cases // Construct a mini program of the form "type a();" and check the AST. // Deduce the type class from the node. string miniprogram { typeName }; miniprogram += " a();"; ANTLRInputStream input(miniprogram); azslLexer lexer(&input); lexer.removeErrorListeners(); CommonTokenStream tokens(&lexer); azslParser parser(&tokens); parser.removeErrorListeners(); azslParser::CompilationUnitContext* unit = parser.compilationUnit(); bool failCondition = parser.getNumberOfSyntaxErrors() > 0 || unit->Declarations.empty() || unit->Declarations[0]->attributedFunctionDeclaration() == nullptr || unit->Declarations[0]->attributedFunctionDeclaration()->functionDeclaration() == nullptr || unit->Declarations[0]->attributedFunctionDeclaration()->functionDeclaration()->hlslFunctionDeclaration() == nullptr; AstFuncType* funcTypeNode = nullptr; if (!failCondition) { funcTypeNode = unit->Declarations[0]-> attributedFunctionDeclaration()-> functionDeclaration()-> hlslFunctionDeclaration()-> leadingTypeFunctionSignature()-> functionType(); } return AnalyzeTypeClass(funcTypeNode); } struct TentativeName { string mangled; }; // try to analyze a type with a few iterations to remove mangling while the result is NotAType inline TypeClass AnalyzeTypeClass(TentativeName typeName) { string try1 = UnMangle(typeName.mangled); TypeClass result = AnalyzeTypeClass(try1); if (result == TypeClass::IsNotType) { // this version does not preserve the global one, this can help for fundamentals string try2 = ReplaceSeparators(typeName.mangled, "::"); result = AnalyzeTypeClass(try2); } return result; } /// Rows and Cols (this is specific to shader languages to identify vector and matrix types) struct ArithmeticTypeInfo { void ResolveSize() { m_size = Packing::PackedSizeof(m_underlyingScalar); } /// Get the size of a single base element const uint32_t GetBaseSize() const { return m_size; } /// Get the size of a the element with regard to dimensions as well const uint32_t GetTotalSize() const { return m_size * (m_cols > 0 ? m_cols : 1) * (m_rows > 0 ? m_rows : 1); } /// True if the type is a vector type. If it's a vector type it cannot be a matrix as well. const bool IsVector() const { // This treats special cases like 2x1, 3x1 and 4x1 as vectors // The behavior is consistent with dxc packing rules return (m_cols == 1 && m_rows > 1) || (m_cols > 1 && m_rows == 0); } /// True if the type is a matrix type. If it's a matrix type it cannot be a vector as well. const bool IsMatrix() const { // This fails special cases like 2x1, 3x1 and 4x1, // but allows cases like 1x2, 1x3 and 1x4. // The behavior is consistent with dxc packing rules return m_rows > 0 && m_cols > 1; } /// If initialized as a fundamental -> not empty. const bool IsEmpty() const { return m_underlyingScalar == -1; } // for pretty print string UnderlyingScalarToStr() const { return m_underlyingScalar >= 0 && m_underlyingScalar < AZ::ShaderCompiler::Predefined::Scalar.size() ? AZ::ShaderCompiler::Predefined::Scalar[m_underlyingScalar] : "<NA>"; } uint32_t m_size = 0; // In bytes. Size of 0 indicates TypeRefInfo which hasn't been resolved or is a struct uint32_t m_rows = 0; // 0 means it's not a matrix (effective Rows = 1). 1 or more means a Matrix uint32_t m_cols = 0; // 0 means it's not a vector (effective Cols = 1). 1 or more means a Vector or Matrix int m_underlyingScalar = -1; // index into AZ::ShaderCompiler::Predefined::Scalar, all fundamentals end up in a scalar at its leaf. }; //! TypeRefInfo holds resolved immutable information of a core type (the `matrix2x2` in `column_major matrix2x2 a[3];`) //! Its own id (containing mangled core name) //! A type class (scalar, matrix, buffer, UDT...) //! Information around the fundamental if applicable (not UDT). struct TypeRefInfo { TypeRefInfo() = default; TypeRefInfo(IdentifierUID typeId, const ArithmeticTypeInfo& fundamentalInfo, TypeClass typeClass) : m_arithmeticInfo{fundamentalInfo}, m_typeClass{typeClass}, m_typeId{typeId} {} //! is plain data: sum type or fundamental. but not enum; because we don't know what underlying they have. const bool IsPackable() const { return m_typeClass.IsOneOf(TypeClass::Struct, TypeClass::Class) || !m_arithmeticInfo.IsEmpty(); } //! non assigned TypeRefInfo bool IsEmpty() const { return m_typeId.m_name.empty(); } //! if the type is a SubpassInput, it's an input attachment bool IsInputAttachment(const azslLexer* lexer) const { return IsViewType(m_typeClass) && ( m_typeId.GetNameLeaf() == Trim(lexer->getVocabulary().getLiteralName(azslLexer::SubpassInput), "\'") || m_typeId.GetNameLeaf() == Trim(lexer->getVocabulary().getLiteralName(azslLexer::SubpassInputMS), "\'")); } friend bool operator == (const TypeRefInfo& lhs, const TypeRefInfo& rhs) { return lhs.m_typeId == rhs.m_typeId; } friend bool operator != (const TypeRefInfo& lhs, const TypeRefInfo& rhs) { return !operator==(lhs,rhs); } IdentifierUID m_typeId; TypeClass m_typeClass; ArithmeticTypeInfo m_arithmeticInfo; }; //! Run a syntactic analysis of an arithmetic type name and extract info on its composition inline ArithmeticTypeInfo CreateArithmeticTypeInfo(QualifiedName a_typeName) { assert(IsArithmetic( /*slow*/AnalyzeTypeClass(TentativeName{a_typeName}) )); // no need to call this function if you don't have a fundamental (non void) assert(!IsGenericArithmetic( /*slow*/AnalyzeTypeClass(TentativeName{a_typeName}) )); // ↑ fatal aspect. The input needs to be canonicalized earlier to minimize this function's complexity. ArithmeticTypeInfo toReturn; string typeName = UnMangle(a_typeName); size_t baseTypeLen = typeName.length(); // In shading languages we have vector and matrix types which use number of columns and possibly rows (for matrices) // The digits always appear at the end of the type, so we can count back to resolve them auto& colsChar = typeName.at(baseTypeLen - 1); if (isdigit(colsChar)) { // Fundamental types ending with a digit are either vectors (1, 2, 3, 4) or matrices (1x1, 2x2, 3x3, 4x4, etc) // Vectors' sizes are defined in components, we opt to put those in Columns for consistency with the Matrix type below. // A float3x4 matrix in DXC is represented as class.matrix.float.3.4 = type { [3 x <4 x float>] } toReturn.m_cols = colsChar - '0'; baseTypeLen--; assert(toReturn.m_cols >= 1 && toReturn.m_cols <= 4); // We should not be hitting asserts with any shader input, this is a bug in the tool if (baseTypeLen >= 2) { // It's possible we are in a matrix type so let's check for rows too! // Documentation: https://docs.microsoft.com/en-us/windows/desktop/direct3dhlsl/dx-graphics-hlsl-per-component-math // A matrix is a data structure that contains rows and columns of data.The data can be any of the scalar data types, // however, every element of a matrix is the same data type.The number of rows and columns is specified with the // row-by-column string that is appended to the data type. auto& rowsChar = typeName.at(baseTypeLen - 2); if (isdigit(rowsChar)) { assert(typeName.at(baseTypeLen - 1) == 'x'); // We should not be hitting asserts with any shader input, this is a bug in the tool toReturn.m_rows = rowsChar - '0'; baseTypeLen -= 2; assert(toReturn.m_rows >= 1 && toReturn.m_rows <= 4); // We should not be hitting asserts with any shader input, this is a bug in the tool } } } // In any case baseTypeLen gives us our base type without vector or matrix information string baseType = typeName.substr(0, baseTypeLen); // 2 special cases: generic vector and matrix with no generic parameter -> they default to float, 4, 4. // https://github.com/Microsoft/DirectXShaderCompiler/issues/2034 // temporarily support them, but when we canonicalize generics it will be supported earlier. if (baseType == "vector" || baseType == "matrix") { baseType = "float"; } auto it = ::std::find(AZ::ShaderCompiler::Predefined::Scalar.begin(), AZ::ShaderCompiler::Predefined::Scalar.end(), baseType); assert(it != AZ::ShaderCompiler::Predefined::Scalar.end()); // baseType must exist in the Scalar bag by program invariant. toReturn.m_underlyingScalar = static_cast<int>( std::distance(AZ::ShaderCompiler::Predefined::Scalar.begin(), it) ); toReturn.ResolveSize(); return toReturn; } MAKE_REFLECTABLE_ENUM(RootParamType, SRV, // t UAV, // u Sampler, // s CBV, // b, bound under an SrgTable as a View. Used for external buffers SrgConstantCB, // b, bound through a root descriptor. Used for SRG Constants. RootConstantCB // b, bound through a CB under root signature. Used for root constants. ); MAKE_REFLECTABLE_ENUM(BindingType, T, U, S, B); //!< as HLSL register type. (please keep in the same order as RootParamType for simple mapping) //! map SRV->T | UAV->U | Sampler->S | CBV,SrgConsant,RootConstant->B BindingType RootParamTypeToBindingType(RootParamType paramType); }
45.884026
170
0.584959
[ "vector", "3d" ]
1ef8dbc62ec531258977193dc0cfd9cc9db265dc
4,380
h
C
deps/leveldb/leveldb-basho/util/expiry_os.h
andris9/leveldown-basho-andris
611673f94e517f02ac15567a48fcc18c61cb46d2
[ "MIT" ]
null
null
null
deps/leveldb/leveldb-basho/util/expiry_os.h
andris9/leveldown-basho-andris
611673f94e517f02ac15567a48fcc18c61cb46d2
[ "MIT" ]
null
null
null
deps/leveldb/leveldb-basho/util/expiry_os.h
andris9/leveldown-basho-andris
611673f94e517f02ac15567a48fcc18c61cb46d2
[ "MIT" ]
null
null
null
// ------------------------------------------------------------------- // // expiry_os.h // // Copyright (c) 2016 Basho Technologies, Inc. All Rights Reserved. // // This file is provided to you under the Apache License, // Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain // a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // // ------------------------------------------------------------------- #ifndef EXPIRY_OS_H #define EXPIRY_OS_H #include <vector> #include "leveldb/options.h" #include "leveldb/expiry.h" #include "leveldb/perf_count.h" #include "db/dbformat.h" #include "db/version_edit.h" namespace leveldb { class ExpiryModuleOS : public ExpiryModule { public: ExpiryModuleOS() : expiry_enabled(false), expiry_minutes(0), whole_file_expiry(false) {}; ~ExpiryModuleOS() {}; // Print expiry options to LOG file virtual void Dump(Logger * log) const; // Quick test to allow manifest logic and such know if // extra expiry logic should be checked virtual bool ExpiryActivated() const {return(expiry_enabled);}; // db/write_batch.cc MemTableInserter::Put() calls this. // returns false on internal error virtual bool MemTableInserterCallback( const Slice & Key, // input: user's key about to be written const Slice & Value, // input: user's value object ValueType & ValType, // input/output: key type. call might change ExpiryTime & Expiry) const; // input/output: 0 or specific expiry. call might change // db/dbformat.cc KeyRetirement::operator() calls this. // db/version_set.cc SaveValue() calls this too. // returns true if key is expired, returns false if key not expired virtual bool KeyRetirementCallback( const ParsedInternalKey & Ikey) const; // input: key to examine for retirement // table/table_builder.cc TableBuilder::Add() calls this. // returns false on internal error virtual bool TableBuilderCallback( const Slice & key, // input: internal key SstCounters & counters) const; // input/output: counters for new sst table // db/memtable.cc MemTable::Get() calls this. // returns true if type/expiry is expired, returns false if not expired virtual bool MemTableCallback( const Slice & Key) const; // input: leveldb internal key // db/version_set.cc VersionSet::Finalize() calls this if no // other compaction selected for a level // returns true if there is an expiry compaction eligible virtual bool CompactionFinalizeCallback( bool WantAll, // input: true - examine all expired files const Version & Ver, // input: database state for examination int Level, // input: level to review for expiry VersionEdit * Edit) const; // output: NULL or destination of delete list public: // NOTE: option names below are intentionally public and lowercase with underscores. // This is to match style of options within include/leveldb/options.h. // Riak specific option to enable/disable expiry features globally // true: expiry enabled // false: disabled (some expired keys may reappear) bool expiry_enabled; // Riak specific option giving number of minutes a stored key/value // may stay within the database before automatic deletion. Zero // disables expiry by age feature. uint64_t expiry_minutes; // configuration values // Riak specific option authorizing leveldb to eliminate entire // files that contain expired data (delete files instead of // removing expired data during compactions). bool whole_file_expiry; protected: // When "creating" write time, chose its source based upon // open source versus enterprise edition virtual uint64_t GenerateWriteTime(const Slice & Key, const Slice & Value) const; }; // ExpiryModuleOS } // namespace leveldb #endif // ifndef
37.435897
93
0.674201
[ "object", "vector" ]
1efbaa1acda74ff53d759dd496f527734c1c4797
12,607
h
C
gazebo/models.h
PositronicsLab/wild-robot
e3d2612075c349f9d446d8804ce4151cb8e16126
[ "MIT" ]
1
2018-06-24T00:05:32.000Z
2018-06-24T00:05:32.000Z
gazebo/models.h
PositronicsLab/wild-robot
e3d2612075c349f9d446d8804ce4151cb8e16126
[ "MIT" ]
null
null
null
gazebo/models.h
PositronicsLab/wild-robot
e3d2612075c349f9d446d8804ce4151cb8e16126
[ "MIT" ]
null
null
null
#ifndef _WEAZELBALL_MODELS_H_ #define _WEAZELBALL_MODELS_H_ //----------------------------------------------------------------------------- #include <gazebo/gazebo.hh> #include <gazebo/common/Plugin.hh> #include <gazebo/common/common.hh> #include <gazebo/common/Events.hh> #include <gazebo/physics/physics.hh> #include "vicon.h" #include "weazelball.h" //----------------------------------------------------------------------------- using namespace gazebo; //----------------------------------------------------------------------------- class model_c; typedef boost::shared_ptr< model_c > model_ptr; class weazelball_c; typedef boost::shared_ptr< weazelball_c > weazelball_ptr; class world_c; typedef boost::shared_ptr< world_c > world_ptr; //----------------------------------------------------------------------------- class model_c { protected: physics::WorldPtr _world; physics::ModelPtr _model; physics::ModelPtr model( std::string name ) { return _world->GetModel( name ); } physics::LinkPtr link( std::string name ) { return _model->GetLink( name ); } physics::JointPtr joint( std::string name ) { return _model->GetJoint( name ); } physics::ModelPtr model( std::string name, std::string& errors ) { physics::ModelPtr m = model( name ); if( !m ) errors += "Unable to find model: " + name + "\n"; return m; } physics::LinkPtr link( std::string name, std::string& errors ) { physics::LinkPtr l = link( name ); if( !l ) errors += "Unable to find link: " + name + "\n"; return l; } physics::JointPtr joint( std::string name, std::string& errors ) { physics::JointPtr j = joint( name ); if( !j ) errors += "Unable to find joint: " + name + "\n"; return j; } public: model_c( physics::WorldPtr world ) : _world( world ) { } model_c( physics::ModelPtr model ) : _model( model ) { _world = _model->GetWorld(); } virtual ~model_c( void ) { } physics::Link_V links( void ) { return _model->GetLinks(); } physics::Joint_V joints( void ) { return _model->GetJoints(); } physics::ModelPtr model( void ) { return _model; } std::string name( void ) { return _model->GetName(); } }; //----------------------------------------------------------------------------- class weazelball_c : public model_c { private: physics::LinkPtr _shell; physics::LinkPtr _motor; physics::JointPtr _actuator; math::Vector3 center_offset; math::Quaternion rotation_offset; std::vector<math::Vector3> marker_positions; public: physics::LinkPtr shell( void ) { return _shell; } physics::LinkPtr motor( void ) { return _motor; } physics::JointPtr actuator( void ) { return _actuator; } public: weazelball_c( physics::WorldPtr world ) : model_c( world ) { read_vsk(); } weazelball_c( physics::ModelPtr model ) : model_c( model ) { } virtual ~weazelball_c( void ) { } math::Vector3 get_center_offset( void ) { // unadjusted offset center //return math::Vector3(0, 0, 0) / 1000; // offset center computed by perturbation return math::Vector3(-1.066979004925168, 3.498590099946762, 2.312719577988714) / 1000; // offset center computed by minimization //return math::Vector3(-1.266714124699, 3.365409558160, 1.907292996249) / 1000; } math::Quaternion get_rotation_offset( void ) { //return gazebo::math::Quaternion( -PI/2.0, 0.0, 0 ) * gazebo::math::Quaternion( 0, 0, PI ); return gazebo::math::Quaternion( -PI/2.0, 0.0, 0 ); } bool validate( std::string& errors ) { std::string id; if( _model ) { _world = _model->GetWorld(); } else if( _world ) { _model = model_c::model( "weazelball", errors ); if( !_model ) return false; } else { errors += "No world or model provided to weazelball_c instance\n"; return false; } _shell = link( "shell", errors ); _motor = link( "motor", errors ); _actuator = joint( "motor_actuator", errors ); if( !( _world && _model && _shell && _motor && _actuator ) ) return false; return true; } void pose( wb_vicon_state_ptr state ) { // extract the position vector from the state gazebo::math::Vector3 pos = gazebo::math::Vector3( state->val(0), state->val(1), state->val(2) ); //pos.z = 0.041; //pos += center_offset; // extract the rotation quaternion from the state gazebo::math::Quaternion rot = gazebo::math::Quaternion( state->val(6), state->val(3), state->val(4), state->val(5) ); center_offset = rot.RotateVector( get_center_offset() ); // the world frame. Rotate the model frame back to a frame aligned with // the world. //rot = rot * gazebo::math::Quaternion( -PI/2.0, 0.0, 0.0 ); rot = rot * get_rotation_offset(); //gazebo::math::Quaternion q( 0, 0, PI); //center_offset = rot.RotateVector( q.RotateVector(math::Vector3(-1.0671, 3.4986, 2.3128) / 1000) ); //gazebo::math::Quaternion q( 0, 0, PI); //center_offset = rot.RotateVector( math::Vector3(-1.0671, 3.4986, 2.3128) / 1000); //math::Vector3 co = rot.RotateVector( center_offset ); pos += center_offset; // update the pose of the shell only. Have no reference for motor in vicon _model->SetLinkWorldPose( gazebo::math::Pose( pos, rot ), _shell ); state->val(0) = pos.x; state->val(1) = pos.y; state->val(2) = pos.z; state->val(3) = rot.x; state->val(4) = rot.y; state->val(5) = rot.z; state->val(6) = rot.w; } void pose( wb_shell_state_ptr state ) { // extract the position vector from the state gazebo::math::Vector3 pos = gazebo::math::Vector3( state->val(0), state->val(1), state->val(2) ); //pos.z = 0.041; //pos += center_offset; // extract the rotation quaternion from the state gazebo::math::Quaternion rot = gazebo::math::Quaternion( state->val(6), state->val(3), state->val(4), state->val(5) ); //math::Vector3 co = rot.RotateVector( math::Vector3(-1.0671, 3.4986, 2.3128) / 1000 ); //math::Vector3 co = rot.RotateVector( center_offset ); //center_offset = rot.RotateVector( math::Vector3(-1.0671, 3.4986, 2.3128) / 1000 ); // the vicon data is recorded with a model frame rotated by 90 degrees to center_offset = rot.RotateVector( get_center_offset() ); // the world frame. Rotate the model frame back to a frame aligned with // the world. //rot = rot * gazebo::math::Quaternion( -PI/2.0, 0.0, 0.0 ); rot = rot * get_rotation_offset(); //gazebo::math::Quaternion q( 0, 0, PI); //center_offset = rot.RotateVector( q.RotateVector(math::Vector3(-1.0671, 3.4986, 2.3128) / 1000) ); //center_offset = rot.RotateVector( math::Vector3(-1.0671, 3.4986, 2.3128) / 1000 ); //math::Vector3 co = rot.RotateVector( center_offset ); pos += center_offset; // pos -= co; // update the pose of the shell only. Have no reference for motor in vicon _model->SetLinkWorldPose( gazebo::math::Pose( pos, rot ), _shell ); state->val(0) = pos.x; state->val(1) = pos.y; state->val(2) = pos.z; state->val(3) = rot.x; state->val(4) = rot.y; state->val(5) = rot.z; state->val(6) = rot.w; } bool read_vsk( void ) { TiXmlDocument doc; std::string path = MOCAP_DATA_PATH; std::stringstream ssfile; ssfile << path << "wb.vsk"; printf( "reading file: %s\n", ssfile.str().c_str() ); if( !doc.LoadFile( ssfile.str() ) ) return false; TiXmlElement *modelxml = doc.FirstChildElement( "KinematicModel" ); if (!modelxml) { std::cout << "ERROR: No <KinematicModel> element. Cannot parse vsk file[" << path << "]. Markers will not be visualized.\n"; return false; } TiXmlElement *markersetxml = modelxml->FirstChildElement( "MarkerSet" ); if (!markersetxml) { std::cout << "ERROR: No <MarkerSet> element. Cannot parse vsk file[" << path << "]. Markers will not be visualized.\n"; return false; } TiXmlElement *markersxml = markersetxml->FirstChildElement( "Markers" ); if (!markersxml) { std::cout << "ERROR: No <Markers> element. Cannot parse vsk file[" << path << "]. Markers will not be visualized.\n"; return false; } TiXmlElement *markerxml, *prevmarkerxml; markerxml = markersxml->FirstChildElement( "Marker" ); if (!markerxml) { std::cout << "ERROR: No <Marker> element. Cannot parse vsk file[" << path << "]. Markers will not be visualized.\n"; return false; } while( markerxml ) { std::string positionxml = markerxml->Attribute( "POSITION" ); if ( !positionxml.size() ) { std::cout << "ERROR: No \"POSITION\" attribute in <Marker>. Ignoring element. Malformed marker will not be visualized.\n"; } else { math::Vector3 pos; std::stringstream ss( positionxml ); std::istream_iterator<std::string> begin( ss ); std::istream_iterator<std::string> end; std::vector<std::string> vstrings( begin, end ); if( vstrings.size() == 3 ) { pos.x = atof( vstrings[0].c_str() ); pos.y = atof( vstrings[1].c_str() ); pos.z = atof( vstrings[2].c_str() ); pos /= 1000; std::cout << "position: " << pos << std::endl; marker_positions.push_back(pos); } } prevmarkerxml = markerxml; markerxml = prevmarkerxml->NextSiblingElement( "Marker" ); } return true; } }; //----------------------------------------------------------------------------- class led_c; typedef boost::shared_ptr< led_c > led_ptr; class led_c : protected model_c { private: physics::ModelPtr _led_off; physics::ModelPtr _led_on; bool _on; public: led_c( physics::WorldPtr world ) : model_c( world ) { _on = false; } bool validate( std::string& errors ) { std::string id; if( _world ) { _led_off = model_c::model( "weazelsignaloff", errors ); if( !_led_off ) return false; _led_on = model_c::model( "weazelsignalon", errors ); if( !_led_on ) return false; } else { errors += "No world or model provided to led_c instance\n"; return false; } /* _shell = link( "shell", errors ); _motor = link( "motor", errors ); _actuator = joint( "motor_actuator", errors ); */ if( !( _world && _led_off && _led_on ) ) return false; return true; } void switch_on( void ) { gazebo::math::Vector3 on_pos( 0, 0, 0.25 ); gazebo::math::Vector3 off_pos( 0, 0, -0.25 ); gazebo::math::Quaternion rot( 1, 0, 0, 0 ); _led_on->SetLinkWorldPose( gazebo::math::Pose( on_pos, rot ), "geom" ); _led_off->SetLinkWorldPose( gazebo::math::Pose( off_pos, rot ), "geom" ); } void switch_off( void ) { gazebo::math::Vector3 on_pos( 0, 0, -0.25 ); gazebo::math::Vector3 off_pos( 0, 0, 0.25 ); gazebo::math::Quaternion rot( 1, 0, 0, 0 ); _led_on->SetLinkWorldPose( gazebo::math::Pose( on_pos, rot ), "geom" ); _led_off->SetLinkWorldPose( gazebo::math::Pose( off_pos, rot ), "geom" ); } }; //----------------------------------------------------------------------------- class world_c { private: physics::WorldPtr _world; weazelball_ptr _weazelball; led_ptr _led; unsigned trial_index; bool _has_led; public: world_c( physics::WorldPtr world ) : _world( world ) { _has_led = false; } virtual ~world_c( void ) { } physics::WorldPtr gzworld( void ) { return _world; } weazelball_ptr weazelball( void ) { return _weazelball; } led_ptr led( void ) { return _led; } bool validate( std::string& errors ) { std::string validation_errors; bool weazelball_validated, led_validated; errors = ""; // create the weazelball model encapsulation structure and validate it _weazelball = weazelball_ptr( new weazelball_c( _world ) ); weazelball_validated = _weazelball->validate( validation_errors ); if( !( weazelball_validated ) ) return false; _led = led_ptr( new led_c( _world ) ); led_validated = _led->validate( validation_errors ); if( !( led_validated ) ) _has_led = true; return true; } void reset( void ) { _world->Reset(); } double sim_time( void ) { return _world->GetSimTime().Double(); } void sim_time( double t ) { _world->SetSimTime( common::Time( t ) ); } double step_size( void ) { return _world->GetPhysicsEngine()->GetMaxStepSize(); } double real_time( void ) { return _world->GetRealTime().Double(); } }; //----------------------------------------------------------------------------- #endif // _WEAZELBALL_MODELS_H_
31.205446
132
0.59935
[ "vector", "model" ]
48113920a1ad2be4e18876112d18746f7eab80fc
58,578
h
C
src/qt/qtwebkit/Source/WebCore/rendering/RenderLayer.h
viewdy/phantomjs
eddb0db1d253fd0c546060a4555554c8ee08c13c
[ "BSD-3-Clause" ]
1
2015-05-27T13:52:20.000Z
2015-05-27T13:52:20.000Z
src/qt/qtwebkit/Source/WebCore/rendering/RenderLayer.h
mrampersad/phantomjs
dca6f77a36699eb4e1c46f7600cca618f01b0ac3
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtwebkit/Source/WebCore/rendering/RenderLayer.h
mrampersad/phantomjs
dca6f77a36699eb4e1c46f7600cca618f01b0ac3
[ "BSD-3-Clause" ]
1
2017-03-19T13:03:23.000Z
2017-03-19T13:03:23.000Z
/* * Copyright (C) 2003, 2009, 2012 Apple Inc. All rights reserved. * * Portions are Copyright (C) 1998 Netscape Communications Corporation. * * Other contributors: * Robert O'Callahan <roc+@cs.cmu.edu> * David Baron <dbaron@fas.harvard.edu> * Christian Biesinger <cbiesinger@web.de> * Randall Jesup <rjesup@wgate.com> * Roland Mainz <roland.mainz@informatik.med.uni-giessen.de> * Josh Soref <timeless@mac.com> * Boris Zbarsky <bzbarsky@mit.edu> * * 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 * * Alternatively, the contents of this file may be used under the terms * of either the Mozilla Public License Version 1.1, found at * http://www.mozilla.org/MPL/ (the "MPL") or the GNU General Public * License Version 2.0, found at http://www.fsf.org/copyleft/gpl.html * (the "GPL"), in which case the provisions of the MPL or the GPL are * applicable instead of those above. If you wish to allow use of your * version of this file only under the terms of one of those two * licenses (the MPL or the GPL) and not to allow others to use your * version of this file under the LGPL, indicate your decision by * deletingthe provisions above and replace them with the notice and * other provisions required by the MPL or the GPL, as the case may be. * If you do not delete the provisions above, a recipient may use your * version of this file under any of the LGPL, the MPL or the GPL. */ #ifndef RenderLayer_h #define RenderLayer_h #include "PaintInfo.h" #include "RenderBox.h" #include "ScrollableArea.h" #include <wtf/OwnPtr.h> namespace WebCore { #if ENABLE(CSS_FILTERS) class FilterEffectRenderer; class FilterEffectRendererHelper; class FilterOperations; class RenderLayerFilterInfo; #endif class HitTestRequest; class HitTestResult; class HitTestingTransformState; class RenderFlowThread; class RenderGeometryMap; class RenderMarquee; class RenderReplica; class RenderScrollbarPart; class RenderStyle; class RenderView; class Scrollbar; class TransformationMatrix; #if USE(ACCELERATED_COMPOSITING) class RenderLayerBacking; class RenderLayerCompositor; #endif enum BorderRadiusClippingRule { IncludeSelfForBorderRadius, DoNotIncludeSelfForBorderRadius }; enum IncludeSelfOrNot { IncludeSelf, ExcludeSelf }; enum RepaintStatus { NeedsNormalRepaint, NeedsFullRepaint, NeedsFullRepaintForPositionedMovementLayout }; class ClipRect { public: ClipRect() : m_hasRadius(false) { } ClipRect(const LayoutRect& rect) : m_rect(rect) , m_hasRadius(false) { } const LayoutRect& rect() const { return m_rect; } void setRect(const LayoutRect& rect) { m_rect = rect; } bool hasRadius() const { return m_hasRadius; } void setHasRadius(bool hasRadius) { m_hasRadius = hasRadius; } bool operator==(const ClipRect& other) const { return rect() == other.rect() && hasRadius() == other.hasRadius(); } bool operator!=(const ClipRect& other) const { return rect() != other.rect() || hasRadius() != other.hasRadius(); } bool operator!=(const LayoutRect& otherRect) const { return rect() != otherRect; } void intersect(const LayoutRect& other) { m_rect.intersect(other); } void intersect(const ClipRect& other) { m_rect.intersect(other.rect()); if (other.hasRadius()) m_hasRadius = true; } void move(LayoutUnit x, LayoutUnit y) { m_rect.move(x, y); } void move(const LayoutSize& size) { m_rect.move(size); } void moveBy(const LayoutPoint& point) { m_rect.moveBy(point); } bool isEmpty() const { return m_rect.isEmpty(); } bool intersects(const LayoutRect& rect) const { return m_rect.intersects(rect); } bool intersects(const HitTestLocation&) const; private: LayoutRect m_rect; bool m_hasRadius; }; inline ClipRect intersection(const ClipRect& a, const ClipRect& b) { ClipRect c = a; c.intersect(b); return c; } class ClipRects { WTF_MAKE_FAST_ALLOCATED; public: static PassRefPtr<ClipRects> create() { return adoptRef(new ClipRects); } static PassRefPtr<ClipRects> create(const ClipRects& other) { return adoptRef(new ClipRects(other)); } ClipRects() : m_refCnt(1) , m_fixed(false) { } void reset(const LayoutRect& r) { m_overflowClipRect = r; m_fixedClipRect = r; m_posClipRect = r; m_fixed = false; } const ClipRect& overflowClipRect() const { return m_overflowClipRect; } void setOverflowClipRect(const ClipRect& r) { m_overflowClipRect = r; } const ClipRect& fixedClipRect() const { return m_fixedClipRect; } void setFixedClipRect(const ClipRect&r) { m_fixedClipRect = r; } const ClipRect& posClipRect() const { return m_posClipRect; } void setPosClipRect(const ClipRect& r) { m_posClipRect = r; } bool fixed() const { return m_fixed; } void setFixed(bool fixed) { m_fixed = fixed; } void ref() { m_refCnt++; } void deref() { if (!--m_refCnt) delete this; } bool operator==(const ClipRects& other) const { return m_overflowClipRect == other.overflowClipRect() && m_fixedClipRect == other.fixedClipRect() && m_posClipRect == other.posClipRect() && m_fixed == other.fixed(); } ClipRects& operator=(const ClipRects& other) { m_overflowClipRect = other.overflowClipRect(); m_fixedClipRect = other.fixedClipRect(); m_posClipRect = other.posClipRect(); m_fixed = other.fixed(); return *this; } private: ClipRects(const LayoutRect& r) : m_overflowClipRect(r) , m_fixedClipRect(r) , m_posClipRect(r) , m_refCnt(1) , m_fixed(false) { } ClipRects(const ClipRects& other) : m_overflowClipRect(other.overflowClipRect()) , m_fixedClipRect(other.fixedClipRect()) , m_posClipRect(other.posClipRect()) , m_refCnt(1) , m_fixed(other.fixed()) { } ClipRect m_overflowClipRect; ClipRect m_fixedClipRect; ClipRect m_posClipRect; unsigned m_refCnt : 31; bool m_fixed : 1; }; enum ClipRectsType { PaintingClipRects, // Relative to painting ancestor. Used for painting. RootRelativeClipRects, // Relative to the ancestor treated as the root (e.g. transformed layer). Used for hit testing. AbsoluteClipRects, // Relative to the RenderView's layer. Used for compositing overlap testing. NumCachedClipRectsTypes, AllClipRectTypes, TemporaryClipRects }; enum ShouldRespectOverflowClip { IgnoreOverflowClip, RespectOverflowClip }; struct ClipRectsCache { WTF_MAKE_FAST_ALLOCATED; public: ClipRectsCache() { #ifndef NDEBUG for (int i = 0; i < NumCachedClipRectsTypes; ++i) { m_clipRectsRoot[i] = 0; m_scrollbarRelevancy[i] = IgnoreOverlayScrollbarSize; } #endif } PassRefPtr<ClipRects> getClipRects(ClipRectsType clipRectsType, ShouldRespectOverflowClip respectOverflow) { return m_clipRects[getIndex(clipRectsType, respectOverflow)]; } void setClipRects(ClipRectsType clipRectsType, ShouldRespectOverflowClip respectOverflow, PassRefPtr<ClipRects> clipRects) { m_clipRects[getIndex(clipRectsType, respectOverflow)] = clipRects; } #ifndef NDEBUG const RenderLayer* m_clipRectsRoot[NumCachedClipRectsTypes]; OverlayScrollbarSizeRelevancy m_scrollbarRelevancy[NumCachedClipRectsTypes]; #endif private: int getIndex(ClipRectsType clipRectsType, ShouldRespectOverflowClip respectOverflow) { int index = static_cast<int>(clipRectsType); if (respectOverflow == RespectOverflowClip) index += static_cast<int>(NumCachedClipRectsTypes); return index; } RefPtr<ClipRects> m_clipRects[NumCachedClipRectsTypes * 2]; }; struct LayerFragment { public: LayerFragment() : shouldPaintContent(false) { } void setRects(const LayoutRect& bounds, const ClipRect& background, const ClipRect& foreground, const ClipRect& outline) { layerBounds = bounds; backgroundRect = background; foregroundRect = foreground; outlineRect = outline; } void moveBy(const LayoutPoint& offset) { layerBounds.moveBy(offset); backgroundRect.moveBy(offset); foregroundRect.moveBy(offset); outlineRect.moveBy(offset); paginationClip.moveBy(offset); } void intersect(const LayoutRect& rect) { backgroundRect.intersect(rect); foregroundRect.intersect(rect); outlineRect.intersect(rect); } bool shouldPaintContent; LayoutRect layerBounds; ClipRect backgroundRect; ClipRect foregroundRect; ClipRect outlineRect; // Unique to paginated fragments. The physical translation to apply to shift the layer when painting/hit-testing. LayoutPoint paginationOffset; // Also unique to paginated fragments. An additional clip that applies to the layer. It is in layer-local // (physical) coordinates. LayoutRect paginationClip; }; typedef Vector<LayerFragment, 1> LayerFragments; class RenderLayer : public ScrollableArea { public: friend class RenderReplica; RenderLayer(RenderLayerModelObject*); ~RenderLayer(); String name() const; RenderLayerModelObject* renderer() const { return m_renderer; } RenderBox* renderBox() const { return m_renderer && m_renderer->isBox() ? toRenderBox(m_renderer) : 0; } RenderLayer* parent() const { return m_parent; } RenderLayer* previousSibling() const { return m_previous; } RenderLayer* nextSibling() const { return m_next; } RenderLayer* firstChild() const { return m_first; } RenderLayer* lastChild() const { return m_last; } void addChild(RenderLayer* newChild, RenderLayer* beforeChild = 0); RenderLayer* removeChild(RenderLayer*); void removeOnlyThisLayer(); void insertOnlyThisLayer(); void repaintIncludingDescendants(); #if USE(ACCELERATED_COMPOSITING) // Indicate that the layer contents need to be repainted. Only has an effect // if layer compositing is being used, void setBackingNeedsRepaint(); void setBackingNeedsRepaintInRect(const LayoutRect&); // r is in the coordinate space of the layer's render object void repaintIncludingNonCompositingDescendants(RenderLayerModelObject* repaintContainer); #endif void styleChanged(StyleDifference, const RenderStyle* oldStyle); RenderMarquee* marquee() const { return m_marquee.get(); } bool isNormalFlowOnly() const { return m_isNormalFlowOnly; } bool isSelfPaintingLayer() const { return m_isSelfPaintingLayer; } bool cannotBlitToWindow() const; bool isTransparent() const; RenderLayer* transparentPaintingAncestor(); void beginTransparencyLayers(GraphicsContext*, const RenderLayer* rootLayer, const LayoutRect& paintDirtyRect, PaintBehavior); bool hasReflection() const { return renderer()->hasReflection(); } bool isReflection() const { return renderer()->isReplica(); } RenderReplica* reflection() const { return m_reflection; } RenderLayer* reflectionLayer() const; const RenderLayer* root() const { const RenderLayer* curr = this; while (curr->parent()) curr = curr->parent(); return curr; } const LayoutPoint& location() const { return m_topLeft; } void setLocation(const LayoutPoint& p) { m_topLeft = p; } const IntSize& size() const { return m_layerSize; } void setSize(const IntSize& size) { m_layerSize = size; } LayoutRect rect() const { return LayoutRect(location(), size()); } int scrollWidth() const; int scrollHeight() const; void panScrollFromPoint(const IntPoint&); enum ScrollOffsetClamping { ScrollOffsetUnclamped, ScrollOffsetClamped }; // Scrolling methods for layers that can scroll their overflow. void scrollByRecursively(const IntSize&, ScrollOffsetClamping = ScrollOffsetUnclamped); void scrollToOffset(const IntSize&, ScrollOffsetClamping = ScrollOffsetUnclamped); void scrollToXOffset(int x, ScrollOffsetClamping clamp = ScrollOffsetUnclamped) { scrollToOffset(IntSize(x, scrollYOffset()), clamp); } void scrollToYOffset(int y, ScrollOffsetClamping clamp = ScrollOffsetUnclamped) { scrollToOffset(IntSize(scrollXOffset(), y), clamp); } int scrollXOffset() const { return m_scrollOffset.width() + scrollOrigin().x(); } int scrollYOffset() const { return m_scrollOffset.height() + scrollOrigin().y(); } IntSize scrollOffset() const { return IntSize(scrollXOffset(), scrollYOffset()); } void scrollRectToVisible(const LayoutRect&, const ScrollAlignment& alignX, const ScrollAlignment& alignY); LayoutRect getRectToExpose(const LayoutRect& visibleRect, const LayoutRect& visibleRectRelativeToDocument, const LayoutRect& exposeRect, const ScrollAlignment& alignX, const ScrollAlignment& alignY); bool scrollsOverflow() const; bool hasScrollbars() const { return m_hBar || m_vBar; } void setHasHorizontalScrollbar(bool); void setHasVerticalScrollbar(bool); PassRefPtr<Scrollbar> createScrollbar(ScrollbarOrientation); void destroyScrollbar(ScrollbarOrientation); bool hasHorizontalScrollbar() const { return horizontalScrollbar(); } bool hasVerticalScrollbar() const { return verticalScrollbar(); } // ScrollableArea overrides virtual Scrollbar* horizontalScrollbar() const { return m_hBar.get(); } virtual Scrollbar* verticalScrollbar() const { return m_vBar.get(); } virtual ScrollableArea* enclosingScrollableArea() const; int verticalScrollbarWidth(OverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize) const; int horizontalScrollbarHeight(OverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize) const; bool hasOverflowControls() const; bool isPointInResizeControl(const IntPoint& absolutePoint) const; bool hitTestOverflowControls(HitTestResult&, const IntPoint& localPoint); IntSize offsetFromResizeCorner(const IntPoint& absolutePoint) const; void paintOverflowControls(GraphicsContext*, const IntPoint&, const IntRect& damageRect, bool paintingOverlayControls = false); void paintScrollCorner(GraphicsContext*, const IntPoint&, const IntRect& damageRect); void paintResizer(GraphicsContext*, const IntPoint&, const IntRect& damageRect); void updateScrollInfoAfterLayout(); bool scroll(ScrollDirection, ScrollGranularity, float multiplier = 1); void autoscroll(const IntPoint&); bool canResize() const; void resize(const PlatformMouseEvent&, const LayoutSize&); bool inResizeMode() const { return m_inResizeMode; } void setInResizeMode(bool b) { m_inResizeMode = b; } bool isRootLayer() const { return m_isRootLayer; } #if USE(ACCELERATED_COMPOSITING) RenderLayerCompositor* compositor() const; // Notification from the renderer that its content changed (e.g. current frame of image changed). // Allows updates of layer content without repainting. void contentChanged(ContentChangeType); #endif bool canRender3DTransforms() const; enum UpdateLayerPositionsFlag { CheckForRepaint = 1 << 0, NeedsFullRepaintInBacking = 1 << 1, IsCompositingUpdateRoot = 1 << 2, UpdateCompositingLayers = 1 << 3, UpdatePagination = 1 << 4 }; typedef unsigned UpdateLayerPositionsFlags; static const UpdateLayerPositionsFlags defaultFlags = CheckForRepaint | IsCompositingUpdateRoot | UpdateCompositingLayers; void updateLayerPositionsAfterLayout(const RenderLayer* rootLayer, UpdateLayerPositionsFlags); void updateLayerPositionsAfterOverflowScroll(); void updateLayerPositionsAfterDocumentScroll(); #if USE(ACCELERATED_COMPOSITING) void positionNewlyCreatedOverflowControls(); #endif bool isPaginated() const { return m_isPaginated; } RenderLayer* enclosingPaginationLayer() const { return m_enclosingPaginationLayer; } void updateTransform(); #if ENABLE(CSS_COMPOSITING) void updateBlendMode(); #endif const LayoutSize& offsetForInFlowPosition() const { return m_offsetForInFlowPosition; } void clearClipRectsIncludingDescendants(ClipRectsType typeToClear = AllClipRectTypes); void clearClipRects(ClipRectsType typeToClear = AllClipRectTypes); void addBlockSelectionGapsBounds(const LayoutRect&); void clearBlockSelectionGapsBounds(); void repaintBlockSelectionGaps(); // A stacking context is a layer that has a non-auto z-index. bool isStackingContext() const { return isStackingContext(renderer()->style()); } // A stacking container can have z-order lists. All stacking contexts are // stacking containers, but the converse is not true. Layers that use // composited scrolling are stacking containers, but they may not // necessarily be stacking contexts. bool isStackingContainer() const { return isStackingContext() || needsCompositedScrolling(); } // Gets the enclosing stacking container for this layer, excluding this // layer itself. RenderLayer* stackingContainer() const; // Gets the enclosing stacking container for this layer, possibly the layer // itself, if it is a stacking container. RenderLayer* enclosingStackingContainer() { return isStackingContainer() ? this : stackingContainer(); } void dirtyZOrderLists(); void dirtyStackingContainerZOrderLists(); Vector<RenderLayer*>* posZOrderList() const { ASSERT(!m_zOrderListsDirty); ASSERT(isStackingContainer() || !m_posZOrderList); return m_posZOrderList.get(); } bool hasNegativeZOrderList() const { return negZOrderList() && negZOrderList()->size(); } Vector<RenderLayer*>* negZOrderList() const { ASSERT(!m_zOrderListsDirty); ASSERT(isStackingContainer() || !m_negZOrderList); return m_negZOrderList.get(); } void dirtyNormalFlowList(); Vector<RenderLayer*>* normalFlowList() const { ASSERT(!m_normalFlowListDirty); return m_normalFlowList.get(); } // Update our normal and z-index lists. void updateLayerListsIfNeeded(); // FIXME: We should ASSERT(!m_visibleContentStatusDirty) here, but see https://bugs.webkit.org/show_bug.cgi?id=71044 // ditto for hasVisibleDescendant(), see https://bugs.webkit.org/show_bug.cgi?id=71277 bool hasVisibleContent() const { return m_hasVisibleContent; } bool hasVisibleDescendant() const { return m_hasVisibleDescendant; } void setHasVisibleContent(); void dirtyVisibleContentStatus(); bool hasBoxDecorationsOrBackground() const; bool hasVisibleBoxDecorations() const; // Returns true if this layer has visible content (ignoring any child layers). bool isVisuallyNonEmpty() const; // True if this layer container renderers that paint. bool hasNonEmptyChildRenderers() const; // FIXME: We should ASSERT(!m_hasSelfPaintingLayerDescendantDirty); here but we hit the same bugs as visible content above. // Part of the issue is with subtree relayout: we don't check if our ancestors have some descendant flags dirty, missing some updates. bool hasSelfPaintingLayerDescendant() const { return m_hasSelfPaintingLayerDescendant; } // This returns true if we have an out of flow positioned descendant whose // containing block is not a descendant of ours. If this is true, we cannot // automatically opt into composited scrolling since this out of flow // positioned descendant would become clipped by us, possibly altering the // rendering of the page. // FIXME: We should ASSERT(!m_hasOutOfFlowPositionedDescendantDirty); here but we may hit the same bugs as visible content above. bool hasOutOfFlowPositionedDescendant() const { return m_hasOutOfFlowPositionedDescendant; } // Gets the nearest enclosing positioned ancestor layer (also includes // the <html> layer and the root layer). RenderLayer* enclosingPositionedAncestor() const; // Returns the nearest enclosing layer that is scrollable. RenderLayer* enclosingScrollableLayer() const; // The layer relative to which clipping rects for this layer are computed. RenderLayer* clippingRootForPainting() const; RenderLayer* enclosingOverflowClipLayer(IncludeSelfOrNot) const; #if USE(ACCELERATED_COMPOSITING) // Enclosing compositing layer; if includeSelf is true, may return this. RenderLayer* enclosingCompositingLayer(IncludeSelfOrNot = IncludeSelf) const; RenderLayer* enclosingCompositingLayerForRepaint(IncludeSelfOrNot = IncludeSelf) const; // Ancestor compositing layer, excluding this. RenderLayer* ancestorCompositingLayer() const { return enclosingCompositingLayer(ExcludeSelf); } #endif #if ENABLE(CSS_FILTERS) RenderLayer* enclosingFilterLayer(IncludeSelfOrNot = IncludeSelf) const; RenderLayer* enclosingFilterRepaintLayer() const; void setFilterBackendNeedsRepaintingInRect(const LayoutRect&, bool immediate); bool hasAncestorWithFilterOutsets() const; #endif bool canUseConvertToLayerCoords() const { // These RenderObject have an impact on their layers' without them knowing about it. return !renderer()->hasColumns() && !renderer()->hasTransform() #if ENABLE(SVG) && !renderer()->isSVGRoot() #endif ; } // FIXME: adjustForColumns allows us to position compositing layers in columns correctly, but eventually they need to be split across columns too. enum ColumnOffsetAdjustment { DontAdjustForColumns, AdjustForColumns }; void convertToPixelSnappedLayerCoords(const RenderLayer* ancestorLayer, IntPoint& location, ColumnOffsetAdjustment adjustForColumns = DontAdjustForColumns) const; void convertToPixelSnappedLayerCoords(const RenderLayer* ancestorLayer, IntRect&, ColumnOffsetAdjustment adjustForColumns = DontAdjustForColumns) const; void convertToLayerCoords(const RenderLayer* ancestorLayer, LayoutPoint&, ColumnOffsetAdjustment adjustForColumns = DontAdjustForColumns) const; void convertToLayerCoords(const RenderLayer* ancestorLayer, LayoutRect&, ColumnOffsetAdjustment adjustForColumns = DontAdjustForColumns) const; int zIndex() const { return renderer()->style()->zIndex(); } enum PaintLayerFlag { PaintLayerHaveTransparency = 1, PaintLayerAppliedTransform = 1 << 1, PaintLayerTemporaryClipRects = 1 << 2, PaintLayerPaintingReflection = 1 << 3, PaintLayerPaintingOverlayScrollbars = 1 << 4, PaintLayerPaintingCompositingBackgroundPhase = 1 << 5, PaintLayerPaintingCompositingForegroundPhase = 1 << 6, PaintLayerPaintingCompositingMaskPhase = 1 << 7, PaintLayerPaintingCompositingScrollingPhase = 1 << 8, PaintLayerPaintingOverflowContents = 1 << 9, PaintLayerPaintingRootBackgroundOnly = 1 << 10, PaintLayerPaintingSkipRootBackground = 1 << 11, PaintLayerPaintingCompositingAllPhases = (PaintLayerPaintingCompositingBackgroundPhase | PaintLayerPaintingCompositingForegroundPhase | PaintLayerPaintingCompositingMaskPhase) }; typedef unsigned PaintLayerFlags; // The two main functions that use the layer system. The paint method // paints the layers that intersect the damage rect from back to // front. The hitTest method looks for mouse events by walking // layers that intersect the point from front to back. void paint(GraphicsContext*, const LayoutRect& damageRect, PaintBehavior = PaintBehaviorNormal, RenderObject* subtreePaintRoot = 0, RenderRegion* = 0, PaintLayerFlags = 0); bool hitTest(const HitTestRequest&, HitTestResult&); bool hitTest(const HitTestRequest&, const HitTestLocation&, HitTestResult&); void paintOverlayScrollbars(GraphicsContext*, const LayoutRect& damageRect, PaintBehavior, RenderObject* subtreePaintRoot = 0); struct ClipRectsContext { ClipRectsContext(const RenderLayer* inRootLayer, RenderRegion* inRegion, ClipRectsType inClipRectsType, OverlayScrollbarSizeRelevancy inOverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize, ShouldRespectOverflowClip inRespectOverflowClip = RespectOverflowClip) : rootLayer(inRootLayer) , region(inRegion) , clipRectsType(inClipRectsType) , overlayScrollbarSizeRelevancy(inOverlayScrollbarSizeRelevancy) , respectOverflowClip(inRespectOverflowClip) { } const RenderLayer* rootLayer; RenderRegion* region; ClipRectsType clipRectsType; OverlayScrollbarSizeRelevancy overlayScrollbarSizeRelevancy; ShouldRespectOverflowClip respectOverflowClip; }; // This method figures out our layerBounds in coordinates relative to // |rootLayer}. It also computes our background and foreground clip rects // for painting/event handling. // Pass offsetFromRoot if known. void calculateRects(const ClipRectsContext&, const LayoutRect& paintDirtyRect, LayoutRect& layerBounds, ClipRect& backgroundRect, ClipRect& foregroundRect, ClipRect& outlineRect, const LayoutPoint* offsetFromRoot = 0) const; // Compute and cache clip rects computed with the given layer as the root void updateClipRects(const ClipRectsContext&); // Compute and return the clip rects. If useCached is true, will used previously computed clip rects on ancestors // (rather than computing them all from scratch up the parent chain). void calculateClipRects(const ClipRectsContext&, ClipRects&) const; ClipRects* clipRects(const ClipRectsContext& context) const { ASSERT(context.clipRectsType < NumCachedClipRectsTypes); return m_clipRectsCache ? m_clipRectsCache->getClipRects(context.clipRectsType, context.respectOverflowClip).get() : 0; } LayoutRect childrenClipRect() const; // Returns the foreground clip rect of the layer in the document's coordinate space. LayoutRect selfClipRect() const; // Returns the background clip rect of the layer in the document's coordinate space. LayoutRect localClipRect() const; // Returns the background clip rect of the layer in the local coordinate space. // Pass offsetFromRoot if known. bool intersectsDamageRect(const LayoutRect& layerBounds, const LayoutRect& damageRect, const RenderLayer* rootLayer, const LayoutPoint* offsetFromRoot = 0) const; enum CalculateLayerBoundsFlag { IncludeSelfTransform = 1 << 0, UseLocalClipRectIfPossible = 1 << 1, IncludeLayerFilterOutsets = 1 << 2, ExcludeHiddenDescendants = 1 << 3, DontConstrainForMask = 1 << 4, IncludeCompositedDescendants = 1 << 5, UseFragmentBoxes = 1 << 6, DefaultCalculateLayerBoundsFlags = IncludeSelfTransform | UseLocalClipRectIfPossible | IncludeLayerFilterOutsets | UseFragmentBoxes }; typedef unsigned CalculateLayerBoundsFlags; // Bounding box relative to some ancestor layer. Pass offsetFromRoot if known. LayoutRect boundingBox(const RenderLayer* rootLayer, CalculateLayerBoundsFlags = 0, const LayoutPoint* offsetFromRoot = 0) const; // Bounding box in the coordinates of this layer. LayoutRect localBoundingBox(CalculateLayerBoundsFlags = 0) const; // Pixel snapped bounding box relative to the root. IntRect absoluteBoundingBox() const; // Bounds used for layer overlap testing in RenderLayerCompositor. LayoutRect overlapBounds() const { return overlapBoundsIncludeChildren() ? calculateLayerBounds(this) : localBoundingBox(); } #if ENABLE(CSS_FILTERS) // If true, this layer's children are included in its bounds for overlap testing. // We can't rely on the children's positions if this layer has a filter that could have moved the children's pixels around. bool overlapBoundsIncludeChildren() const { return hasFilter() && renderer()->style()->filter().hasFilterThatMovesPixels(); } #else bool overlapBoundsIncludeChildren() const { return false; } #endif // Can pass offsetFromRoot if known. LayoutRect calculateLayerBounds(const RenderLayer* ancestorLayer, const LayoutPoint* offsetFromRoot = 0, CalculateLayerBoundsFlags = DefaultCalculateLayerBoundsFlags) const; // WARNING: This method returns the offset for the parent as this is what updateLayerPositions expects. LayoutPoint computeOffsetFromRoot(bool& hasLayerOffset) const; // Return a cached repaint rect, computed relative to the layer renderer's containerForRepaint. LayoutRect repaintRect() const { return m_repaintRect; } LayoutRect repaintRectIncludingNonCompositingDescendants() const; void setRepaintStatus(RepaintStatus status) { m_repaintStatus = status; } LayoutUnit staticInlinePosition() const { return m_staticInlinePosition; } LayoutUnit staticBlockPosition() const { return m_staticBlockPosition; } void setStaticInlinePosition(LayoutUnit position) { m_staticInlinePosition = position; } void setStaticBlockPosition(LayoutUnit position) { m_staticBlockPosition = position; } bool hasTransform() const { return renderer()->hasTransform(); } // Note that this transform has the transform-origin baked in. TransformationMatrix* transform() const { return m_transform.get(); } // currentTransform computes a transform which takes accelerated animations into account. The // resulting transform has transform-origin baked in. If the layer does not have a transform, // returns the identity matrix. TransformationMatrix currentTransform(RenderStyle::ApplyTransformOrigin = RenderStyle::IncludeTransformOrigin) const; TransformationMatrix renderableTransform(PaintBehavior) const; // Get the perspective transform, which is applied to transformed sublayers. // Returns true if the layer has a -webkit-perspective. // Note that this transform has the perspective-origin baked in. TransformationMatrix perspectiveTransform() const; FloatPoint perspectiveOrigin() const; bool preserves3D() const { return renderer()->style()->transformStyle3D() == TransformStyle3DPreserve3D; } bool has3DTransform() const { return m_transform && !m_transform->isAffine(); } #if ENABLE(CSS_FILTERS) virtual void filterNeedsRepaint(); bool hasFilter() const { return renderer()->hasFilter(); } #else bool hasFilter() const { return false; } #endif #if ENABLE(CSS_COMPOSITING) bool hasBlendMode() const { return renderer()->hasBlendMode(); } #else bool hasBlendMode() const { return false; } #endif // Overloaded new operator. Derived classes must override operator new // in order to allocate out of the RenderArena. void* operator new(size_t, RenderArena*); // Overridden to prevent the normal delete from being called. void operator delete(void*, size_t); #if USE(ACCELERATED_COMPOSITING) bool isComposited() const { return m_backing != 0; } bool hasCompositedMask() const; RenderLayerBacking* backing() const { return m_backing.get(); } RenderLayerBacking* ensureBacking(); void clearBacking(bool layerBeingDestroyed = false); virtual GraphicsLayer* layerForScrolling() const; virtual GraphicsLayer* layerForHorizontalScrollbar() const; virtual GraphicsLayer* layerForVerticalScrollbar() const; virtual GraphicsLayer* layerForScrollCorner() const; virtual bool usesCompositedScrolling() const OVERRIDE; bool needsCompositedScrolling() const; bool needsCompositingLayersRebuiltForClip(const RenderStyle* oldStyle, const RenderStyle* newStyle) const; bool needsCompositingLayersRebuiltForOverflow(const RenderStyle* oldStyle, const RenderStyle* newStyle) const; #else bool isComposited() const { return false; } bool hasCompositedMask() const { return false; } bool usesCompositedScrolling() const { return false; } bool needsCompositedScrolling() const { return false; } #endif bool paintsWithTransparency(PaintBehavior paintBehavior) const { return isTransparent() && ((paintBehavior & PaintBehaviorFlattenCompositingLayers) || !isComposited()); } bool paintsWithTransform(PaintBehavior) const; // Returns true if background phase is painted opaque in the given rect. // The query rect is given in local coordinates. bool backgroundIsKnownToBeOpaqueInRect(const LayoutRect&) const; bool containsDirtyOverlayScrollbars() const { return m_containsDirtyOverlayScrollbars; } void setContainsDirtyOverlayScrollbars(bool dirtyScrollbars) { m_containsDirtyOverlayScrollbars = dirtyScrollbars; } #if ENABLE(CSS_SHADERS) bool isCSSCustomFilterEnabled() const; #endif #if ENABLE(CSS_FILTERS) FilterOperations computeFilterOperations(const RenderStyle*); bool paintsWithFilters() const; bool requiresFullLayerImageForFilters() const; FilterEffectRenderer* filterRenderer() const; RenderLayerFilterInfo* filterInfo() const; RenderLayerFilterInfo* ensureFilterInfo(); void removeFilterInfoIfNeeded(); bool hasFilterInfo() const { return m_hasFilterInfo; } void setHasFilterInfo(bool hasFilterInfo) { m_hasFilterInfo = hasFilterInfo; } #endif #if !ASSERT_DISABLED bool layerListMutationAllowed() const { return m_layerListMutationAllowed; } void setLayerListMutationAllowed(bool flag) { m_layerListMutationAllowed = flag; } #endif Node* enclosingElement() const; #if ENABLE(DIALOG_ELEMENT) bool isInTopLayer() const; bool isInTopLayerSubtree() const; #endif #if USE(ACCELERATED_COMPOSITING) enum ViewportConstrainedNotCompositedReason { NoNotCompositedReason, NotCompositedForBoundsOutOfView, NotCompositedForNonViewContainer, NotCompositedForNoVisibleContent, }; void setViewportConstrainedNotCompositedReason(ViewportConstrainedNotCompositedReason reason) { m_viewportConstrainedNotCompositedReason = reason; } ViewportConstrainedNotCompositedReason viewportConstrainedNotCompositedReason() const { return static_cast<ViewportConstrainedNotCompositedReason>(m_viewportConstrainedNotCompositedReason); } #endif bool isOutOfFlowRenderFlowThread() const { return renderer()->isOutOfFlowRenderFlowThread(); } private: enum CollectLayersBehavior { StopAtStackingContexts, StopAtStackingContainers }; void updateZOrderLists(); void rebuildZOrderLists(); void rebuildZOrderLists(CollectLayersBehavior, OwnPtr<Vector<RenderLayer*> >&, OwnPtr<Vector<RenderLayer*> >&); void clearZOrderLists(); void updateNormalFlowList(); // Non-auto z-index always implies stacking context here, because StyleResolver::adjustRenderStyle already adjusts z-index // based on positioning and other criteria. bool isStackingContext(const RenderStyle* style) const { return !style->hasAutoZIndex() || isRootLayer(); } bool isDirtyStackingContainer() const { return m_zOrderListsDirty && isStackingContainer(); } void setAncestorChainHasSelfPaintingLayerDescendant(); void dirtyAncestorChainHasSelfPaintingLayerDescendantStatus(); bool acceleratedCompositingForOverflowScrollEnabled() const; void updateDescendantsAreContiguousInStackingOrder(); void updateDescendantsAreContiguousInStackingOrderRecursive(const HashMap<const RenderLayer*, int>&, int& minIndex, int& maxIndex, int& count, bool firstIteration); void computeRepaintRects(const RenderLayerModelObject* repaintContainer, const RenderGeometryMap* = 0); void computeRepaintRectsIncludingDescendants(); void clearRepaintRects(); void clipToRect(RenderLayer* rootLayer, GraphicsContext*, const LayoutRect& paintDirtyRect, const ClipRect&, BorderRadiusClippingRule = IncludeSelfForBorderRadius); void restoreClip(GraphicsContext*, const LayoutRect& paintDirtyRect, const ClipRect&); bool shouldRepaintAfterLayout() const; void updateSelfPaintingLayer(); void updateStackingContextsAfterStyleChange(const RenderStyle* oldStyle); void updateScrollbarsAfterStyleChange(const RenderStyle* oldStyle); void updateScrollbarsAfterLayout(); void setAncestorChainHasOutOfFlowPositionedDescendant(RenderObject* containingBlock); void dirtyAncestorChainHasOutOfFlowPositionedDescendantStatus(); void updateOutOfFlowPositioned(const RenderStyle* oldStyle); void updateNeedsCompositedScrolling(); // Returns true if the position changed. bool updateLayerPosition(); void updateLayerPositions(RenderGeometryMap* = 0, UpdateLayerPositionsFlags = defaultFlags); enum UpdateLayerPositionsAfterScrollFlag { NoFlag = 0, IsOverflowScroll = 1 << 0, HasSeenViewportConstrainedAncestor = 1 << 1, HasSeenAncestorWithOverflowClip = 1 << 2, HasChangedAncestor = 1 << 3 }; typedef unsigned UpdateLayerPositionsAfterScrollFlags; void updateLayerPositionsAfterScroll(RenderGeometryMap*, UpdateLayerPositionsAfterScrollFlags = NoFlag); friend IntSize RenderBox::scrolledContentOffset() const; IntSize scrolledContentOffset() const { return m_scrollOffset; } IntSize clampScrollOffset(const IntSize&) const; // The normal operator new is disallowed on all render objects. void* operator new(size_t) throw(); void setNextSibling(RenderLayer* next) { m_next = next; } void setPreviousSibling(RenderLayer* prev) { m_previous = prev; } void setParent(RenderLayer* parent); void setFirstChild(RenderLayer* first) { m_first = first; } void setLastChild(RenderLayer* last) { m_last = last; } LayoutPoint renderBoxLocation() const { return renderer()->isBox() ? toRenderBox(renderer())->location() : LayoutPoint(); } void collectLayers(bool includeHiddenLayers, CollectLayersBehavior, OwnPtr<Vector<RenderLayer*> >&, OwnPtr<Vector<RenderLayer*> >&); void updateCompositingAndLayerListsIfNeeded(); struct LayerPaintingInfo { LayerPaintingInfo(RenderLayer* inRootLayer, const LayoutRect& inDirtyRect, PaintBehavior inPaintBehavior, const LayoutSize& inSubPixelAccumulation, RenderObject* inSubtreePaintRoot = 0, RenderRegion*inRegion = 0, OverlapTestRequestMap* inOverlapTestRequests = 0) : rootLayer(inRootLayer) , subtreePaintRoot(inSubtreePaintRoot) , paintDirtyRect(inDirtyRect) , subPixelAccumulation(inSubPixelAccumulation) , region(inRegion) , overlapTestRequests(inOverlapTestRequests) , paintBehavior(inPaintBehavior) , clipToDirtyRect(true) { } RenderLayer* rootLayer; RenderObject* subtreePaintRoot; // only paint descendants of this object LayoutRect paintDirtyRect; // relative to rootLayer; LayoutSize subPixelAccumulation; RenderRegion* region; // May be null. OverlapTestRequestMap* overlapTestRequests; // May be null. PaintBehavior paintBehavior; bool clipToDirtyRect; }; bool setupFontSubpixelQuantization(GraphicsContext*, bool& didQuantizeFonts); bool setupClipPath(GraphicsContext*, const LayerPaintingInfo&, const LayoutPoint& offsetFromRoot, LayoutRect& rootRelativeBounds, bool& rootRelativeBoundsComputed); #if ENABLE(CSS_FILTERS) PassOwnPtr<FilterEffectRendererHelper> setupFilters(GraphicsContext*, LayerPaintingInfo&, PaintLayerFlags, const LayoutPoint& offsetFromRoot, LayoutRect& rootRelativeBounds, bool& rootRelativeBoundsComputed); GraphicsContext* applyFilters(FilterEffectRendererHelper*, GraphicsContext* originalContext, LayerPaintingInfo&, LayerFragments&); #endif void paintLayer(GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags); void paintLayerContentsAndReflection(GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags); void paintLayerByApplyingTransform(GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags, const LayoutPoint& translationOffset = LayoutPoint()); void paintLayerContents(GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags); void paintList(Vector<RenderLayer*>*, GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags); void paintPaginatedChildLayer(RenderLayer* childLayer, GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags); void paintChildLayerIntoColumns(RenderLayer* childLayer, GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags, const Vector<RenderLayer*>& columnLayers, size_t columnIndex); void collectFragments(LayerFragments&, const RenderLayer* rootLayer, RenderRegion*, const LayoutRect& dirtyRect, ClipRectsType, OverlayScrollbarSizeRelevancy inOverlayScrollbarSizeRelevancy = IgnoreOverlayScrollbarSize, ShouldRespectOverflowClip = RespectOverflowClip, const LayoutPoint* offsetFromRoot = 0, const LayoutRect* layerBoundingBox = 0); void updatePaintingInfoForFragments(LayerFragments&, const LayerPaintingInfo&, PaintLayerFlags, bool shouldPaintContent, const LayoutPoint* offsetFromRoot); void paintBackgroundForFragments(const LayerFragments&, GraphicsContext*, GraphicsContext* transparencyLayerContext, const LayoutRect& transparencyPaintDirtyRect, bool haveTransparency, const LayerPaintingInfo&, PaintBehavior, RenderObject* paintingRootForRenderer); void paintForegroundForFragments(const LayerFragments&, GraphicsContext*, GraphicsContext* transparencyLayerContext, const LayoutRect& transparencyPaintDirtyRect, bool haveTransparency, const LayerPaintingInfo&, PaintBehavior, RenderObject* paintingRootForRenderer, bool selectionOnly, bool forceBlackText); void paintForegroundForFragmentsWithPhase(PaintPhase, const LayerFragments&, GraphicsContext*, const LayerPaintingInfo&, PaintBehavior, RenderObject* paintingRootForRenderer); void paintOutlineForFragments(const LayerFragments&, GraphicsContext*, const LayerPaintingInfo&, PaintBehavior, RenderObject* paintingRootForRenderer); void paintOverflowControlsForFragments(const LayerFragments&, GraphicsContext*, const LayerPaintingInfo&); void paintMaskForFragments(const LayerFragments&, GraphicsContext*, const LayerPaintingInfo&, RenderObject* paintingRootForRenderer); void paintTransformedLayerIntoFragments(GraphicsContext*, const LayerPaintingInfo&, PaintLayerFlags); RenderLayer* hitTestLayer(RenderLayer* rootLayer, RenderLayer* containerLayer, const HitTestRequest& request, HitTestResult& result, const LayoutRect& hitTestRect, const HitTestLocation&, bool appliedTransform, const HitTestingTransformState* transformState = 0, double* zOffset = 0); RenderLayer* hitTestLayerByApplyingTransform(RenderLayer* rootLayer, RenderLayer* containerLayer, const HitTestRequest&, HitTestResult&, const LayoutRect& hitTestRect, const HitTestLocation&, const HitTestingTransformState* = 0, double* zOffset = 0, const LayoutPoint& translationOffset = LayoutPoint()); RenderLayer* hitTestList(Vector<RenderLayer*>*, RenderLayer* rootLayer, const HitTestRequest& request, HitTestResult& result, const LayoutRect& hitTestRect, const HitTestLocation&, const HitTestingTransformState* transformState, double* zOffsetForDescendants, double* zOffset, const HitTestingTransformState* unflattenedTransformState, bool depthSortDescendants); RenderLayer* hitTestPaginatedChildLayer(RenderLayer* childLayer, RenderLayer* rootLayer, const HitTestRequest& request, HitTestResult& result, const LayoutRect& hitTestRect, const HitTestLocation&, const HitTestingTransformState* transformState, double* zOffset); RenderLayer* hitTestChildLayerColumns(RenderLayer* childLayer, RenderLayer* rootLayer, const HitTestRequest& request, HitTestResult& result, const LayoutRect& hitTestRect, const HitTestLocation&, const HitTestingTransformState* transformState, double* zOffset, const Vector<RenderLayer*>& columnLayers, size_t columnIndex); PassRefPtr<HitTestingTransformState> createLocalTransformState(RenderLayer* rootLayer, RenderLayer* containerLayer, const LayoutRect& hitTestRect, const HitTestLocation&, const HitTestingTransformState* containerTransformState, const LayoutPoint& translationOffset = LayoutPoint()) const; bool hitTestContents(const HitTestRequest&, HitTestResult&, const LayoutRect& layerBounds, const HitTestLocation&, HitTestFilter) const; bool hitTestContentsForFragments(const LayerFragments&, const HitTestRequest&, HitTestResult&, const HitTestLocation&, HitTestFilter, bool& insideClipRect) const; bool hitTestResizerInFragments(const LayerFragments&, const HitTestLocation&) const; RenderLayer* hitTestTransformedLayerInFragments(RenderLayer* rootLayer, RenderLayer* containerLayer, const HitTestRequest&, HitTestResult&, const LayoutRect& hitTestRect, const HitTestLocation&, const HitTestingTransformState* = 0, double* zOffset = 0); bool listBackgroundIsKnownToBeOpaqueInRect(const Vector<RenderLayer*>*, const LayoutRect&) const; void computeScrollDimensions(); bool hasHorizontalOverflow() const; bool hasVerticalOverflow() const; bool hasScrollableHorizontalOverflow() const; bool hasScrollableVerticalOverflow() const; bool shouldBeNormalFlowOnly() const; bool shouldBeSelfPaintingLayer() const; int scrollPosition(Scrollbar*) const; // ScrollableArea interface virtual void invalidateScrollbarRect(Scrollbar*, const IntRect&); virtual void invalidateScrollCornerRect(const IntRect&); virtual bool isActive() const; virtual bool isScrollCornerVisible() const; virtual IntRect scrollCornerRect() const; virtual IntRect convertFromScrollbarToContainingView(const Scrollbar*, const IntRect&) const; virtual IntRect convertFromContainingViewToScrollbar(const Scrollbar*, const IntRect&) const; virtual IntPoint convertFromScrollbarToContainingView(const Scrollbar*, const IntPoint&) const; virtual IntPoint convertFromContainingViewToScrollbar(const Scrollbar*, const IntPoint&) const; virtual int scrollSize(ScrollbarOrientation) const; virtual void setScrollOffset(const IntPoint&); virtual IntPoint scrollPosition() const; virtual IntPoint minimumScrollPosition() const; virtual IntPoint maximumScrollPosition() const; virtual IntRect visibleContentRect(VisibleContentRectIncludesScrollbars) const; virtual int visibleHeight() const; virtual int visibleWidth() const; virtual IntSize contentsSize() const; virtual IntSize overhangAmount() const; virtual IntPoint lastKnownMousePosition() const; virtual bool isHandlingWheelEvent() const OVERRIDE; virtual bool shouldSuspendScrollAnimations() const; virtual bool scrollbarsCanBeActive() const; virtual IntRect scrollableAreaBoundingBox() const OVERRIDE; virtual bool scrollbarAnimationsAreSuppressed() const OVERRIDE; // Rectangle encompassing the scroll corner and resizer rect. IntRect scrollCornerAndResizerRect() const; // NOTE: This should only be called by the overriden setScrollOffset from ScrollableArea. void scrollTo(int, int); void updateCompositingLayersAfterScroll(); IntSize scrollbarOffset(const Scrollbar*) const; void updateScrollableAreaSet(bool hasOverflow); void dirtyAncestorChainVisibleDescendantStatus(); void setAncestorChainHasVisibleDescendant(); void updateDescendantDependentFlags(HashSet<const RenderObject*>* outOfFlowDescendantContainingBlocks = 0); // This flag is computed by RenderLayerCompositor, which knows more about 3d hierarchies than we do. void setHas3DTransformedDescendant(bool b) { m_has3DTransformedDescendant = b; } bool has3DTransformedDescendant() const { return m_has3DTransformedDescendant; } void dirty3DTransformedDescendantStatus(); // Both updates the status, and returns true if descendants of this have 3d. bool update3DTransformedDescendantStatus(); void createReflection(); void removeReflection(); void updateReflectionStyle(); bool paintingInsideReflection() const { return m_paintingInsideReflection; } void setPaintingInsideReflection(bool b) { m_paintingInsideReflection = b; } #if ENABLE(CSS_FILTERS) void updateOrRemoveFilterClients(); void updateOrRemoveFilterEffectRenderer(); #endif void parentClipRects(const ClipRectsContext&, ClipRects&) const; ClipRect backgroundClipRect(const ClipRectsContext&) const; LayoutRect paintingExtent(const RenderLayer* rootLayer, const LayoutRect& paintDirtyRect, PaintBehavior); RenderLayer* enclosingTransformedAncestor() const; // Convert a point in absolute coords into layer coords, taking transforms into account LayoutPoint absoluteToContents(const LayoutPoint&) const; void positionOverflowControls(const IntSize&); void updateScrollCornerStyle(); void updateResizerStyle(); void drawPlatformResizerImage(GraphicsContext*, IntRect resizerCornerRect); void updatePagination(); // FIXME: Temporary. Remove when new columns come online. bool useRegionBasedColumns() const; #if USE(ACCELERATED_COMPOSITING) bool hasCompositingDescendant() const { return m_hasCompositingDescendant; } void setHasCompositingDescendant(bool b) { m_hasCompositingDescendant = b; } enum IndirectCompositingReason { NoIndirectCompositingReason, IndirectCompositingForStacking, IndirectCompositingForOverlap, IndirectCompositingForBackgroundLayer, IndirectCompositingForGraphicalEffect, // opacity, mask, filter, transform etc. IndirectCompositingForPerspective, IndirectCompositingForPreserve3D }; void setIndirectCompositingReason(IndirectCompositingReason reason) { m_indirectCompositingReason = reason; } IndirectCompositingReason indirectCompositingReason() const { return static_cast<IndirectCompositingReason>(m_indirectCompositingReason); } bool mustCompositeForIndirectReasons() const { return m_indirectCompositingReason; } #endif // Returns true if z ordering would not change if this layer were a stacking container. bool canBeStackingContainer() const; friend class RenderLayerBacking; friend class RenderLayerCompositor; friend class RenderLayerModelObject; // Only safe to call from RenderBoxModelObject::destroyLayer(RenderArena*) void destroy(RenderArena*); LayoutUnit overflowTop() const; LayoutUnit overflowBottom() const; LayoutUnit overflowLeft() const; LayoutUnit overflowRight() const; IntRect rectForHorizontalScrollbar(const IntRect& borderBoxRect) const; IntRect rectForVerticalScrollbar(const IntRect& borderBoxRect) const; LayoutUnit verticalScrollbarStart(int minX, int maxX) const; LayoutUnit horizontalScrollbarStart(int minX) const; bool overflowControlsIntersectRect(const IntRect& localRect) const; protected: // The bitfields are up here so they will fall into the padding from ScrollableArea on 64-bit. // Keeps track of whether the layer is currently resizing, so events can cause resizing to start and stop. bool m_inResizeMode : 1; bool m_scrollDimensionsDirty : 1; bool m_zOrderListsDirty : 1; bool m_normalFlowListDirty: 1; bool m_isNormalFlowOnly : 1; bool m_isSelfPaintingLayer : 1; // If have no self-painting descendants, we don't have to walk our children during painting. This can lead to // significant savings, especially if the tree has lots of non-self-painting layers grouped together (e.g. table cells). bool m_hasSelfPaintingLayerDescendant : 1; bool m_hasSelfPaintingLayerDescendantDirty : 1; // If we have no out of flow positioned descendants and no non-descendant // appears between our descendants in stacking order, then we may become a // stacking context. bool m_hasOutOfFlowPositionedDescendant : 1; bool m_hasOutOfFlowPositionedDescendantDirty : 1; bool m_needsCompositedScrolling : 1; // If this is true, then no non-descendant appears between any of our // descendants in stacking order. This is one of the requirements of being // able to safely become a stacking context. bool m_descendantsAreContiguousInStackingOrder : 1; const bool m_isRootLayer : 1; bool m_usedTransparency : 1; // Tracks whether we need to close a transparent layer, i.e., whether // we ended up painting this layer or any descendants (and therefore need to // blend). bool m_paintingInsideReflection : 1; // A state bit tracking if we are painting inside a replica. bool m_inOverflowRelayout : 1; unsigned m_repaintStatus : 2; // RepaintStatus bool m_visibleContentStatusDirty : 1; bool m_hasVisibleContent : 1; bool m_visibleDescendantStatusDirty : 1; bool m_hasVisibleDescendant : 1; bool m_isPaginated : 1; // If we think this layer is split by a multi-column ancestor, then this bit will be set. bool m_3DTransformedDescendantStatusDirty : 1; bool m_has3DTransformedDescendant : 1; // Set on a stacking context layer that has 3D descendants anywhere // in a preserves3D hierarchy. Hint to do 3D-aware hit testing. #if USE(ACCELERATED_COMPOSITING) bool m_hasCompositingDescendant : 1; // In the z-order tree. unsigned m_indirectCompositingReason : 3; unsigned m_viewportConstrainedNotCompositedReason : 2; #endif bool m_containsDirtyOverlayScrollbars : 1; bool m_updatingMarqueePosition : 1; #if !ASSERT_DISABLED bool m_layerListMutationAllowed : 1; #endif #if ENABLE(CSS_FILTERS) bool m_hasFilterInfo : 1; #endif #if ENABLE(CSS_COMPOSITING) BlendMode m_blendMode; #endif RenderLayerModelObject* m_renderer; RenderLayer* m_parent; RenderLayer* m_previous; RenderLayer* m_next; RenderLayer* m_first; RenderLayer* m_last; LayoutRect m_repaintRect; // Cached repaint rects. Used by layout. LayoutRect m_outlineBox; // Our current relative position offset. LayoutSize m_offsetForInFlowPosition; // Our (x,y) coordinates are in our parent layer's coordinate space. LayoutPoint m_topLeft; // The layer's width/height IntSize m_layerSize; // This is the (scroll) offset from scrollOrigin(). IntSize m_scrollOffset; // The width/height of our scrolled area. LayoutSize m_scrollSize; // For layers with overflow, we have a pair of scrollbars. RefPtr<Scrollbar> m_hBar; RefPtr<Scrollbar> m_vBar; // For layers that establish stacking contexts, m_posZOrderList holds a sorted list of all the // descendant layers within the stacking context that have z-indices of 0 or greater // (auto will count as 0). m_negZOrderList holds descendants within our stacking context with negative // z-indices. OwnPtr<Vector<RenderLayer*> > m_posZOrderList; OwnPtr<Vector<RenderLayer*> > m_negZOrderList; // This list contains child layers that cannot create stacking contexts. For now it is just // overflow layers, but that may change in the future. OwnPtr<Vector<RenderLayer*> > m_normalFlowList; OwnPtr<ClipRectsCache> m_clipRectsCache; IntPoint m_cachedOverlayScrollbarOffset; OwnPtr<RenderMarquee> m_marquee; // Used by layers with overflow:marquee // Cached normal flow values for absolute positioned elements with static left/top values. LayoutUnit m_staticInlinePosition; LayoutUnit m_staticBlockPosition; OwnPtr<TransformationMatrix> m_transform; // May ultimately be extended to many replicas (with their own paint order). RenderReplica* m_reflection; // Renderers to hold our custom scroll corner and resizer. RenderScrollbarPart* m_scrollCorner; RenderScrollbarPart* m_resizer; // Pointer to the enclosing RenderLayer that caused us to be paginated. It is 0 if we are not paginated. RenderLayer* m_enclosingPaginationLayer; private: IntRect m_blockSelectionGapsBounds; #if USE(ACCELERATED_COMPOSITING) OwnPtr<RenderLayerBacking> m_backing; #endif }; inline void RenderLayer::clearZOrderLists() { ASSERT(!isStackingContainer()); m_posZOrderList.clear(); m_negZOrderList.clear(); } inline void RenderLayer::updateZOrderLists() { if (!m_zOrderListsDirty) return; if (!isStackingContainer()) { clearZOrderLists(); m_zOrderListsDirty = false; return; } rebuildZOrderLists(); } #if !ASSERT_DISABLED class LayerListMutationDetector { public: LayerListMutationDetector(RenderLayer* layer) : m_layer(layer) , m_previousMutationAllowedState(layer->layerListMutationAllowed()) { m_layer->setLayerListMutationAllowed(false); } ~LayerListMutationDetector() { m_layer->setLayerListMutationAllowed(m_previousMutationAllowedState); } private: RenderLayer* m_layer; bool m_previousMutationAllowedState; }; #endif void makeMatrixRenderable(TransformationMatrix&, bool has3DRendering); } // namespace WebCore #ifndef NDEBUG // Outside the WebCore namespace for ease of invocation from gdb. void showLayerTree(const WebCore::RenderLayer*); void showLayerTree(const WebCore::RenderObject*); #endif #endif // RenderLayer_h
43.747573
274
0.744358
[ "render", "object", "vector", "transform", "3d" ]
4832726b1b1665173a0b4d295f56938c52cff754
3,783
h
C
MfgToolLib/StApiFactory.h
Bobe-Wang/mfgtools
2aedf0e3c0ef104a32669df2a80193a600e8357e
[ "BSD-3-Clause" ]
1
2019-08-10T01:21:21.000Z
2019-08-10T01:21:21.000Z
MfgToolLib/StApiFactory.h
Bobe-Wang/mfgtools
2aedf0e3c0ef104a32669df2a80193a600e8357e
[ "BSD-3-Clause" ]
null
null
null
MfgToolLib/StApiFactory.h
Bobe-Wang/mfgtools
2aedf0e3c0ef104a32669df2a80193a600e8357e
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2009-2013, 2016 Freescale Semiconductor, Inc. * * 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 Freescale Semiconductor 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. * */ // StApiFactory.h // ////////////////////////////////////////////////////////////////////// #if !defined(STAPIFACTORY_H__INCLUDED) #define STAPIFACTORY_H__INCLUDED //#include "Common/StdString.h" #include "StDdiApi.h" #include "StHidApi.h" namespace api { class StApiFactory { public: typedef StApi* (*CreateApiCallback)(CStdString paramStr); private: typedef std::map<CStdString, CreateApiCallback> CallbackMap; public: StApiFactory() { RegisterApi(L"HidInquiry", HidInquiry::Create); RegisterApi(L"HidDownloadFw", HidDownloadFw::Create); RegisterApi(L"HidBltcRequestSense", HidBltcRequestSense::Create); RegisterApi(L"HidDeviceReset", HidDeviceReset::Create); RegisterApi(L"HidDevicePowerDown", HidDevicePowerDown::Create); RegisterApi(L"HidTestUnitReady", HidTestUnitReady::Create); RegisterApi(L"HidPitcRequestSense", HidPitcRequestSense::Create); /* RegisterApi(L"HidInquiry", HidInquiry::Create); RegisterApi(L"HidInquiry", HidInquiry::Create); RegisterApi(L"HidInquiry", HidInquiry::Create); RegisterApi(L"HidInquiry", HidInquiry::Create); RegisterApi(L"HidInquiry", HidInquiry::Create); RegisterApi(L"HidInquiry", HidInquiry::Create); RegisterApi(L"HidInquiry", HidInquiry::Create); RegisterApi(L"HidInquiry", HidInquiry::Create); RegisterApi(L"HidInquiry", HidInquiry::Create); RegisterApi(L"HidInquiry", HidInquiry::Create); */ }; bool RegisterApi(CStdString name, CreateApiCallback createFn) { return _callbacks.insert(CallbackMap::value_type(name, createFn)).second; }; bool UnregisterApi(CStdString name) { return _callbacks.erase(name) == 1; }; StApi* CreateApi(CStdString name, CStdString paramStr="") { CallbackMap::const_iterator i = _callbacks.find(name); if ( i == _callbacks.end() ) { // not found throw std::runtime_error("Unknown API name."); } // Invoke the creation function return (i->second)(paramStr); }; private: CallbackMap _callbacks; }; } // namespace api // The one and only StApiFactory object StApiFactory& gStApiFactory() { static StApiFactory factory; return factory; }; using namespace api; #endif // !defined(STAPIFACTORY_H__INCLUDED)
33.184211
83
0.736717
[ "object" ]
48376d0d6e87a197405738dd3d28c63be3184d88
675
h
C
core/includes/core/events/EventArgs.h
toeb/cpp.core
84c782b1e0919dd598c3c19c8e5c71f27453ebf2
[ "MIT" ]
2
2016-10-25T19:42:49.000Z
2017-03-25T22:26:03.000Z
core/includes/core/events/EventArgs.h
toeb/cpp.core
84c782b1e0919dd598c3c19c8e5c71f27453ebf2
[ "MIT" ]
null
null
null
core/includes/core/events/EventArgs.h
toeb/cpp.core
84c782b1e0919dd598c3c19c8e5c71f27453ebf2
[ "MIT" ]
null
null
null
#pragma once #include <core/core.h> #include <core/any.h> #include <core/events/events.h> #include <iostream> NS_BEGIN(CORE_EVENTS_NAMESPACE) /// a simple data transfer object cotnaining the sender of the event as well a an arbitrary argument class EventArgs{ public: typedef any sender_type; typedef any value_type; EventArgs(sender_type sender, value_type arg) :_sender(sender), _arg(arg){} sender_type event(){ return _sender; } value_type arg(){ return _arg; } private: sender_type _sender; value_type _arg; }; inline std::ostream & operator << (std::ostream & out, const EventArgs &){ return out; } NS_END(CORE_EVENTS_NAMESPACE)
28.125
100
0.721481
[ "object" ]
4845920aa672ee0e0cd156a16779f6f2762447e6
2,031
h
C
src/qif191/QIFDocument/type_t.CThreadedFeatureConstructionMethodType.h
QualityInformationFramework/QIFResourcesEditor
4ff1de9d1dd20d9c43eaa9cc320caeff1c57760e
[ "BSL-1.0" ]
null
null
null
src/qif191/QIFDocument/type_t.CThreadedFeatureConstructionMethodType.h
QualityInformationFramework/QIFResourcesEditor
4ff1de9d1dd20d9c43eaa9cc320caeff1c57760e
[ "BSL-1.0" ]
null
null
null
src/qif191/QIFDocument/type_t.CThreadedFeatureConstructionMethodType.h
QualityInformationFramework/QIFResourcesEditor
4ff1de9d1dd20d9c43eaa9cc320caeff1c57760e
[ "BSL-1.0" ]
null
null
null
#pragma once namespace qif191 { namespace t { class CThreadedFeatureConstructionMethodType : public TypeBase { public: QIF191_EXPORT CThreadedFeatureConstructionMethodType(xercesc::DOMNode* const& init); QIF191_EXPORT CThreadedFeatureConstructionMethodType(CThreadedFeatureConstructionMethodType const& init); void operator=(CThreadedFeatureConstructionMethodType const& other) { m_node = other.m_node; } static altova::meta::ComplexType StaticInfo() { return altova::meta::ComplexType(types + _altova_ti_t_altova_CThreadedFeatureConstructionMethodType); } MemberElement<t::CThreadedFeatureBestFitType, _altova_mi_t_altova_CThreadedFeatureConstructionMethodType_altova_BestFit> BestFit; struct BestFit { typedef Iterator<t::CThreadedFeatureBestFitType> iterator; }; MemberElement<t::CThreadedFeatureRecompType, _altova_mi_t_altova_CThreadedFeatureConstructionMethodType_altova_Recompensated> Recompensated; struct Recompensated { typedef Iterator<t::CThreadedFeatureRecompType> iterator; }; MemberElement<t::CThreadedFeatureCopyType, _altova_mi_t_altova_CThreadedFeatureConstructionMethodType_altova_Copy> Copy; struct Copy { typedef Iterator<t::CThreadedFeatureCopyType> iterator; }; MemberElement<t::CThreadedFeatureCastType, _altova_mi_t_altova_CThreadedFeatureConstructionMethodType_altova_Cast> Cast; struct Cast { typedef Iterator<t::CThreadedFeatureCastType> iterator; }; MemberElement<t::CThreadedFeatureTransformType, _altova_mi_t_altova_CThreadedFeatureConstructionMethodType_altova_Transform> Transform; struct Transform { typedef Iterator<t::CThreadedFeatureTransformType> iterator; }; MemberElement<t::CThreadedFeatureFromCylinderType, _altova_mi_t_altova_CThreadedFeatureConstructionMethodType_altova_FromCylinder> FromCylinder; struct FromCylinder { typedef Iterator<t::CThreadedFeatureFromCylinderType> iterator; }; QIF191_EXPORT void SetXsiType(); }; } // namespace t } // namespace qif191 //#endif // _ALTOVA_INCLUDED_QIFDocument_ALTOVA_t_ALTOVA_CThreadedFeatureConstructionMethodType
50.775
152
0.859183
[ "transform" ]
484c30ba240735a93a0a6d2093c95128b305eecf
808
h
C
L1Trigger/L1THGCal/interface/concentrator/HGCalConcentratorTrigSumImpl.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
13
2015-11-30T15:49:45.000Z
2022-02-08T16:11:30.000Z
L1Trigger/L1THGCal/interface/concentrator/HGCalConcentratorTrigSumImpl.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
640
2015-02-11T18:55:47.000Z
2022-03-31T14:12:23.000Z
L1Trigger/L1THGCal/interface/concentrator/HGCalConcentratorTrigSumImpl.h
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
51
2015-08-11T21:01:40.000Z
2022-03-30T07:31:34.000Z
#ifndef __L1Trigger_L1THGCal_HGCalConcentratorTrigSumImpl_h__ #define __L1Trigger_L1THGCal_HGCalConcentratorTrigSumImpl_h__ #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "DataFormats/L1THGCal/interface/HGCalTriggerCell.h" #include "DataFormats/L1THGCal/interface/HGCalTriggerSums.h" #include "L1Trigger/L1THGCal/interface/HGCalTriggerTools.h" #include <vector> class HGCalConcentratorTrigSumImpl { public: HGCalConcentratorTrigSumImpl(const edm::ParameterSet& conf); void doSum(uint32_t module_id, const std::vector<l1t::HGCalTriggerCell>& trigCellVecInput, std::vector<l1t::HGCalTriggerSums>& trigSumsVecOutput) const; void eventSetup(const edm::EventSetup& es) { triggerTools_.eventSetup(es); } private: HGCalTriggerTools triggerTools_; }; #endif
32.32
78
0.804455
[ "vector" ]
484ef58e74f08f28cd3c50cb265a273abdcff179
676
h
C
artag-try/Marker.h
MaverickPeter/Copter_mavlink_campanion_control
90c5846b9b68792fd5c4d0080adf236d0a6c47ea
[ "MIT" ]
1
2018-04-27T03:35:11.000Z
2018-04-27T03:35:11.000Z
detect/Marker.h
MaverickPeter/Copter_mavlink_campanion_control
90c5846b9b68792fd5c4d0080adf236d0a6c47ea
[ "MIT" ]
null
null
null
detect/Marker.h
MaverickPeter/Copter_mavlink_campanion_control
90c5846b9b68792fd5c4d0080adf236d0a6c47ea
[ "MIT" ]
1
2020-12-24T01:53:44.000Z
2020-12-24T01:53:44.000Z
// // Created by 崔瑜翔 on 2018/3/20. // #include <vector> #include <iostream> #include <opencv2/opencv.hpp> #include "GeometryTypes.h" using namespace cv; using namespace std; class Marker { public: Marker(); friend bool operator<(const Marker& M1,const Marker& M2); friend ostream & operator << (ostream &str,const Marker &M); static Mat rotate(Mat in); static int hammDistMarker(Mat bits); static int mat2id(const cv::Mat &bits); static int getMarkerId(Mat &in,int &nRotations); public: int id; Transformation transformation; vector<Point2f> points; void drawContour(Mat& image,Scalar color = CV_RGB(0,250,0)) const; };
17.789474
70
0.681953
[ "vector" ]
4855696e95edf5705993dd8b8ccd9725ccb83303
12,363
h
C
libsafedart/builder.h
nasa/SAFE-DART
41d75c1c116c29d68455942df74a4a9205a0e444
[ "NASA-1.3" ]
8
2017-11-03T09:39:20.000Z
2021-09-26T14:01:31.000Z
libsafedart/builder.h
nasa/SAFE-DART
41d75c1c116c29d68455942df74a4a9205a0e444
[ "NASA-1.3" ]
null
null
null
libsafedart/builder.h
nasa/SAFE-DART
41d75c1c116c29d68455942df74a4a9205a0e444
[ "NASA-1.3" ]
5
2018-10-18T08:32:58.000Z
2019-11-13T17:11:46.000Z
/* ********************************************************************** ** ** Developed for NASA Glenn Research Center ** By: Flight Software Branch (LSS) ** ** Project: Flow Boiling and Condensation Experiment (FBCE) ** Candidate for GOTS reuse once FBCE has completed V&V testing ** ** Filename: builder.h ** File Date: 20160928 ** ** Authors ** ** Author: Jordan R. Higgins (JRH) ** ** Version and Traceability ** ** Subversion: @version $Id$ ** ** Revision History: ** <Date> <Name of Change Agent> ** Description: ** - Bulleted list of changes. ** ** 17 Nov 2016 Jordan Higgins ** Description: ** - Added createdObject(QSharedPointer<QObject>) and ** destroyingObject(QObject *) signals, to allow extension of the ** instantiation process. ** ** Copyright © 2017 United States Government as represented by NASA Glenn Research Center. ** No copyright is claimed in the United States under Title 17, U.S.Code. All Other Rights Reserved. ** See LICENSE.txt in the root of the repository for more details. ** ********************************************************************** */ #pragma once #include <QByteArray> #include <QException> #include <QHash> #include <QMutex> #include <QObject> #include <QSharedPointer> #include <configuration.h> /*! * \brief An exception thrown when creation of a class fails. * * \ingroup SAFE-DART-Framework */ class BuilderException : public QException { public: /*! * \brief Creates an exception from a null-terminated C string. * * \param message A message describing what caused the exception. */ BuilderException(const char *message) : _message(message) {} /*! * \brief Creates an exception from a byte array. * * \param message A message describing what caused the exception. */ BuilderException(const QByteArray &message) : _message(message) {} /*! * \brief Creates an exception from a QString. * * \param message A message describing what caused the exception. */ BuilderException(const QString &message) : _message(message.toUtf8()) {} /*! * \brief Creates a copy of another BuilderException. * * \param copy The BuilderException whose message to copy. */ BuilderException(const BuilderException &copy) : _message(copy._message) {} ~BuilderException() throw() {} /*! * \brief Creates a copy of this BuilderException. * * \return A pointer to a BuilderException with the same message as this. */ BuilderException *clone() const { return new BuilderException(*this); } /*! * \brief Throws this BuilderException. */ void raise() const { throw *this; } /*! * \brief Gets a description of what caused this BuilderException. * * \return A raw string containing a description of the cause of this * BuilderException. */ const char *what() const throw() { return _message.data(); } protected: /*! * \brief A byte array containing a string describing the cause of the exception. */ const QByteArray _message; }; /*! * \brief Builds and caches objects created through reflection. * * Builder is the foundation of the SAFE-DART architecture. It provides an * interface through which software can instantiate objects using reflection. * Instantiating objects this way allows the implementation types to be changed * without needing to recompile the software. * * Builder uses a configuration file which specifies which types to instantiate. * This allows the objects that are instantiated to be configured at run-time * without any additional effort required by the caller, allowing the * application to be reconfigured at run-time with minimal effort. With the use * of shared libraries, this can also allow functionality to be added or changed * without the need to recompile the entire software. * * Builder also keeps track of the instances it creates, reusing them when the * type is requested again. When an instance of Builder is used by multiple * libraries, this also means that any objects instantiated by the Builder may * be shared between those libraries. * * \ingroup SAFE-DART-Framework */ class Builder : public QObject { Q_OBJECT public: /*! * \brief Creates a Builder. * * \param parent The parent QObject of this Builder. */ explicit Builder(QObject *parent = 0); ~Builder(); /*! * \brief Gets an instance of a generic object by name. * * The given name is looked up in the Builder's Configuration, if any, in * the \c safedart section. If a match is found, its value is used as the * name of the type to instantiate; otherwise, the given name is used. * Configuration file mappings are not recursive. For instance, if the * configuration file has Foo=Bar and Bar=Baz, get("Foo") will attempt to * create an instance of the class named Bar. * * If the given type has been instantiated before, the existing object will * be returned if it still exists. This is true <i>even if the given name is * different</i>; for instance, if the configuration file has Foo=Baz and * Bar=Baz, get("Foo") and get("Bar") may return the same object. * * Once found, the QObject in question will be instantiated; T(Builder *) is * used if it is available, else T() is used. * * \param name The name of the type to instantiate. * * \return An instance of the object type associated with the given name. * * \throw BuilderException No QObject could be found with the given name. * \throw BuilderException The QObject with the given name could not be * created. * * \note The constructor used to instantiate the QObject must be marked * Q_INVOKABLE, or it will not be usable via reflection. */ virtual QSharedPointer<QObject> get(const char *name); /*! * \brief Gets an instance of a specific type by name. * * Functions very similarly to get(const char *), but additionally casts the * object (safely) to the given type. * * \see get(const char *) * \throw LocatorException The object could not be casted to type T. */ template<typename T> QSharedPointer<T> get(const char *name); /*! * \brief Gets an instance of a specific type. * * Functions very similarly to get<T>(const char *), but uses the name of * the interface T. * * \see get<T>(const char *) * * \note T must have been declared as an interface using Q_DECLARE_INTERFACE * for this to work correctly. */ template<typename T> QSharedPointer<T> get(); /*! * \brief Provides an instance of QObject to be associated with the given * name. * * This allows a custom object to be provided, which will be returned when * the object with the given name is requested. * * \param name The name to associate the given object with. * \param object The object to associate with the given name. * * \note Builder holds only a weak pointer to \c object; it must be kept * alive by the caller, or it will be freed and default rules will be used * to instantiate the object when requested. */ virtual void provide(const char *name, QSharedPointer<QObject> object); /*! * \brief Gets the Configuration used by this Builder. * * \return A pointer to the Configuration used by this Builder. May be null * if none was set. */ QSharedPointer<Configuration> configuration(); /*! * \brief Gets the configuration section used by this Builder. * * \return The configuration section used by this builder. */ QString section(); /*! * \brief Sets the Configuration used by this Builder. * * \param configuration The Configuration to be used by this Builder. * \param section The section within the configuration file to use. */ void setConfiguration(QSharedPointer<Configuration> configuration, const QString &section = "safedart"); signals: /*! * \brief Emitted when an object is created by the Builder. * * This signal is provided so that the application may perform additional * logic for newly-created objects. This signal is emitted after the object * is instantiated, but before get() returns the object to the caller. * * \param object A pointer to the object that was created. */ void createdObject(QSharedPointer<QObject> object); /*! * \brief Emitted when an object is about to be destroyed by the Builder. * * This signal is provided so that the application may perform additional * logic for an object immediately before it is destroyed. This signal is * emitted immediately before the object is deleted, so the pointer that is * passed in should not be kept. * * \param object A pointer to the object that will be destroyed. * * \warning If this signal is connected in a queued non-blocking fashion, * the object pointer may be invalid by the time the slot is executed. Be * aware that <b>this can happen if automatic connection is used</b>. */ void destroyingObject(QObject *object); protected: /*! * \brief A previously-created instance of an object. * * The Instance struct contains the necessary information to maintain a * reference to a shared object while it exists, without preventing it from * being deleted. It also allows creation of the object to be synchronized * to ensure that only one instance of the object exists at a time. * * \note QWeakPointer itself is thread-safe, so exclusive access is not * required to be able to access an existing instance of the object. If * there is no existing instance of the object, however, only one should be * created. In this case, a lock is used, so that only one thread will * attempt to create an object. This ensures that only one instance of the * object will exist at any given time. */ struct Instance { /*! * \brief A mutex which synchronizes the creation of the instance stored * in \c _reference. * * No lock is needed be used when reading the value of the pointer, but * a lock should be held when creating the object. To ensure proper * synchronization, \c _reference should be checked again after locking * the mutex and before creating an instance of the object. */ QMutex _referenceMutex; /*! * \brief A weak pointer to the existing instance of the object, if any. */ QWeakPointer<QObject> _reference; /*! * \brief Creates an Instance containing no value. */ Instance() = default; /*! * \brief Creates a copy of the given Instance. * * \param copy The Instance whose reference to copy. */ Instance(const Instance &copy); }; /*! * \brief A pointer to the Configuration used by this Builder. */ QSharedPointer<Configuration> _configuration; /*! * \brief A mapping of object name to the existing instance (if any). */ QHash<QByteArray, Instance> _instances; /*! * \brief A mutex used to ensure that access to \c _instances is exclusive. * * Because it is not known whether an object exists in the map prior to * looking it up, an exclusive lock is used. This allows the index operator * to be used, which will add the key if it does not already exist in a * single operation. */ QMutex _instancesMutex; /*! * \brief A string containing the name of the configuration section to use. */ QString _section; }; template<typename T> QSharedPointer<T> Builder::get(const char *name) { QSharedPointer<T> object = get(name).objectCast<T>(); if (!object) { QString message = QString("Type does not implement the requested service."); throw BuilderException(message); } return object; } template<typename T> QSharedPointer<T> Builder::get() { const char *name = qobject_interface_iid<T *>(); return get<T>(name); }
34.341667
108
0.660762
[ "object" ]
f09bb1b6d63f570a7359c80bd4341ba06dff35a1
248
h
C
include/Utopia/Core/Systems/LocalToParentSystem.h
Ubpa/DustEngine
4fc32d4011ce21ab5ab2a8149e398d9baa3cbdc0
[ "MIT" ]
9
2020-08-03T02:11:07.000Z
2020-09-29T09:12:45.000Z
include/Utopia/Core/Systems/LocalToParentSystem.h
Ubpa/DustEngine
4fc32d4011ce21ab5ab2a8149e398d9baa3cbdc0
[ "MIT" ]
null
null
null
include/Utopia/Core/Systems/LocalToParentSystem.h
Ubpa/DustEngine
4fc32d4011ce21ab5ab2a8149e398d9baa3cbdc0
[ "MIT" ]
1
2020-08-10T03:34:52.000Z
2020-08-10T03:34:52.000Z
#pragma once #include <UECS/UECS.hpp> #include <UGM/transform.hpp> namespace Ubpa::Utopia { struct LocalToParentSystem { static constexpr char SystemFuncName[] = "LocalToParentSystem"; static void OnUpdate(UECS::Schedule& schedule); }; }
17.714286
65
0.741935
[ "transform" ]
f09ee21953a69b0cf93af7425721c2963357a6e5
27,084
c
C
gempak/source/programs/gui/nmap2/nmap_pgfilterw.c
oxelson/gempak
e7c477814d7084c87d3313c94e192d13d8341fa1
[ "BSD-3-Clause" ]
42
2015-06-03T15:26:21.000Z
2022-02-28T22:36:03.000Z
gempak/source/programs/gui/nmap2/nmap_pgfilterw.c
oxelson/gempak
e7c477814d7084c87d3313c94e192d13d8341fa1
[ "BSD-3-Clause" ]
60
2015-05-11T21:36:08.000Z
2022-03-29T16:22:42.000Z
gempak/source/programs/gui/nmap2/nmap_pgfilterw.c
oxelson/gempak
e7c477814d7084c87d3313c94e192d13d8341fa1
[ "BSD-3-Clause" ]
27
2016-06-06T21:55:14.000Z
2022-03-18T18:23:28.000Z
#include "geminc.h" #include "gemprm.h" #include "nmap_data.h" #include "pgprm.h" #include "vgstruct.h" #include "drwids.h" #include "hints.h" #include "Nxm.h" #include "proto_xw.h" #define ACTV_FILTER "NONE" /* Filter window up but no filters checked */ #define CANCEL_FILTER "ALL" /* Filter window down */ #define MAX_FILTYPES 10 /* Max. number of filter types */ #define TIME_FILTER 0 /* Time filter */ #define ALL_ON "All On" #define ALL_OFF "All Off" static int _nFilTime[MAX_FILTYPES]; static char _filTime[MAX_FILTYPES][MAX_FILTER_NUM][DSPLY_FILTER_SZ]; static Boolean _filterStatus[MAX_FILTER_NUM]; static Widget _filterForm; static WidgetList _filterChkBtn; static WidgetList _cntlBtn; static char _curFilter[512]; static Boolean _allOn = True; /* Toggle between ALL_ON & ALL_OFF */ static Boolean _offByHotkey = False; /* Button turned off by hotkey */ static Boolean _fromGfa = False; /* * private callback functions */ static void pgfilterw_ctlBtnCb ( Widget, long, XtPointer ); static void pgfilterw_toggleCb ( Widget, long, XtPointer ); /* * private functions */ static void pgfilterw_updateFilter ( void ); static void pgfilterw_refresh ( void ); static void pgfilterw_getLastTime ( char *selectedTime ); /************************************************************************ * nmap_pgfilterw.c * * * * This module controls the display filter functions. * * * * CONTENTS: * * pgfilterw_create() creates filter control window * * pgfilterw_popup() pops up filter control window * * pgfilterw_popdown() pops down filter control window * * pgfilterw_isUp() Queries if filter control window is up * * pgfilterw_stepOneUp() Moves one up from the current filter * * pgfilterw_stepOneDown() Moves one down from the current filter * * * * private callback functions: * * pgfilterw_toggleCb() callback for filter toggle buttons * * pgfilterw_ctlBtnCb() callback for filter control buttons * * * * private functions: * * pgfilterw_updateFilter() updates current filter and redisplay * * pgfilterw_refresh() updates display * * pgfilterw_turnOnTime turns on a given filter time * * pgfilterw_getLastTime gets the name of the last selected time * * * ***********************************************************************/ /*=====================================================================*/ void pgfilterw_create ( Widget parent ) /************************************************************************ * pgfilterw_create * * * * This function creates the display filter control window. * * * * void pgfilterw_create ( parent ) * * * * Input parameters: * * parent Widget Parent widget * * * * Output parameters: * * * ** * * Log: * * J. Wu/SAIC 07/04 initial coding * * E. Safford/SAIC 08/04 make filter times horizontal layout & * * use ALL_ON/ALL_OFF definitions * * T. Piper/SAIC 10/05 declared ii & nn long * * J. Wu/SAIC 06/06 load table from CVG lib & adjust layout * * M. Li/SAIC 02/07 Change callback type for filter hour * ***********************************************************************/ { int ier; long ii, nn; char *ctlstrs[] = { ALL_ON, "Close" }; Widget pane, optform, cntl_form; XmString xmstr; /*---------------------------------------------------------------------*/ /* * Load the filter table. */ cvg_rdfilter ( &ier ); /* * Initialize filter selections in CVG library */ strcpy ( _curFilter, CANCEL_FILTER ); cvg_setfilter ( _curFilter, &ier ); /* * Retrieve all valid filter entries */ cvg_gettblfilter ( &_nFilTime[TIME_FILTER], _filTime[TIME_FILTER], &ier ); for ( ii = 0; ii < _nFilTime[TIME_FILTER]; ii++ ) { _filterStatus[ii] = False; } /* * Create main dialog window. */ _filterForm = XmCreateFormDialog ( parent, "pgfilterw_popup", NULL, 0 ); xmstr = XmStringCreateLocalized("Filter Control"); XtVaSetValues ( _filterForm, XmNnoResize, TRUE, XmNautoUnmanage, FALSE, XmNdialogTitle, xmstr, NULL ); XmStringFree(xmstr); /* * Create pane area. */ pane = XtVaCreateManagedWidget ( "filterw_pane", xmPanedWindowWidgetClass, _filterForm, XmNsashWidth, 1, XmNsashHeight, 1, XmNleftAttachment, XmATTACH_FORM, XmNrightAttachment, XmATTACH_FORM, NULL ); /* * Create check buttons */ optform = XtVaCreateManagedWidget ( "filterw_optform", xmRowColumnWidgetClass, pane, XmNpacking, XmPACK_TIGHT, XmNorientation, XmHORIZONTAL, NULL ); nn = _nFilTime[0]; _filterChkBtn = (WidgetList) XtMalloc( (size_t)nn * sizeof(Widget) ); for ( ii = 0; ii < nn; ii++ ) { _filterChkBtn[ii] = XtVaCreateManagedWidget ( _filTime[0][ii], xmToggleButtonWidgetClass, optform, NULL ); XtAddCallback ( _filterChkBtn[ii], XmNvalueChangedCallback, (XtCallbackProc)pgfilterw_toggleCb, (XtPointer) ii ); } /* * Create control buttons */ nn = XtNumber ( ctlstrs ); _cntlBtn = (WidgetList) XtMalloc( (size_t)nn * sizeof(Widget) ); cntl_form = XtVaCreateManagedWidget ( "filter_cntl_form", xmFormWidgetClass, pane, XmNfractionBase, nn * 100, NULL ); for ( ii = 0; ii < nn; ii++ ) { _cntlBtn[ii] = XtVaCreateManagedWidget ( ctlstrs[ii], xmPushButtonWidgetClass, cntl_form, XmNleftAttachment, XmATTACH_POSITION, XmNleftPosition, ((ii * 100) + 10 ), XmNrightAttachment, XmATTACH_POSITION, XmNrightPosition, (((ii + 1) * 100) - 10), NULL ); XtAddCallback ( _cntlBtn[ii], XmNactivateCallback, (XtCallbackProc)pgfilterw_ctlBtnCb, (XtPointer) ii ); } /* * Make the "ALL ON/ALL OFF" button insensetive if no valid filters * found from the filter table. */ if ( _nFilTime[TIME_FILTER] <= 0 ) { XtSetSensitive ( _cntlBtn[0], False ); } } /*=====================================================================*/ void pgfilterw_popup ( void ) /************************************************************************ * pgfilterw_popup * * * * This function manages the display filter window. * * * * void pgfilterw_popup ( void ) * * * * Input parameters: * * Output parameters: * * NONE * * * ** * * Log: * * J. Wu/SAIC 07/04 initial coding * * E. Safford/SAIC 08/04 use ALL_ON/ALL_OFF definitions * ***********************************************************************/ { XmString xmstr; /*---------------------------------------------------------------------*/ if ( !XtIsManaged ( _filterForm ) ) { XtManageChild ( _filterForm ); } /* * At the beginning, set to ALL_OFF status, none of the elements * with time stamp should be displayed. */ _allOn = False; xmstr = XmStringCreateLtoR ( ALL_ON, XmFONTLIST_DEFAULT_TAG ); XtVaSetValues ( _cntlBtn[0], XmNlabelString, xmstr, NULL ); XmStringFree ( xmstr ); pgfilterw_updateFilter (); } /*=====================================================================*/ void pgfilterw_popdown ( void ) /************************************************************************ * pgfilterw_popdown * * * * This function unmanages the display filter window. * * * * void pgfilterw_popdown ( void ) * * * * Input parameters: * * Output parameters: * * NONE * * * ** * * Log: * * J. Wu/SAIC 07/04 initial coding * ***********************************************************************/ { int ii; /*---------------------------------------------------------------------*/ if ( XtIsManaged ( _filterForm ) ) { XtUnmanageChild ( _filterForm ); } /* * Deactivate filter, so all elements could be displayed. */ _allOn = False; for ( ii = 0; ii < _nFilTime[TIME_FILTER]; ii++ ) { _filterStatus[ii] = False; XmToggleButtonSetState ( _filterChkBtn[ii], False, False ); } pgfilterw_updateFilter (); } /*=====================================================================*/ Boolean pgfilterw_isUp ( void ) /************************************************************************ * pgfilterw_isUp * * * * Query whether the filter control dialog is managed or not. * * * * Boolean pgfilterw_isUp ( void ) * * * * Input parameters: * * Output parameters: * * NONE * * * * Return parameters: * * pgfilterw_isUp Boolean Is/is not managed * * * ** * * Log: * * J. Wu/SAIC 07/04 initial coding * ***********************************************************************/ { return ( XtIsManaged (_filterForm) ); } /*=====================================================================*/ /* ARGSUSED */ static void pgfilterw_ctlBtnCb ( Widget wid, long which, XtPointer call ) /************************************************************************ * pgfilterw_cntlBtnCb * * * * Callback function for the control buttons in filter window. * * * * static void pgfilterw_ctlBtnCb ( wid, which, call ) * * * * Input parameters: * * wid Widget widget ID * * which long which button * * call XtPointer callback struct * * * * Output parameters: * * Return parameters: * * NONE * * * ** * * Log: * * J. Wu/SAIC 07/04 initial coding * * E. Safford/SAIC 08/04 use ALL_ON/ALL_OFF definitions * ***********************************************************************/ { int ii; XmString xmstr; /*---------------------------------------------------------------------*/ switch ( which ) { case 0: /* All On/Off - toggle on/off all filters in window */ if ( _allOn ) { _allOn = False; xmstr = XmStringCreateLtoR ( ALL_ON, XmFONTLIST_DEFAULT_TAG ); } else { _allOn = True; xmstr = XmStringCreateLtoR ( ALL_OFF, XmFONTLIST_DEFAULT_TAG ); } XtVaSetValues ( _cntlBtn[0], XmNlabelString, xmstr, NULL ); XmStringFree ( xmstr ); for ( ii = 0; ii < _nFilTime[TIME_FILTER]; ii++ ) { _filterStatus[ii] = _allOn; XmToggleButtonSetState ( _filterChkBtn[ii], _allOn, False ); } pgfilterw_updateFilter (); break; case 1: /* Close - close window and display all elements */ pgfilterw_popdown (); break; } } /*=====================================================================*/ /* ARGSUSED */ static void pgfilterw_toggleCb ( Widget wid, long which, XtPointer call ) /************************************************************************ * pgfilterw_toggleCb * * * * Callback function for filter check buttons. * * * * static void pgfilterw_toggleCb ( wid, which, call ) * * * * Input parameters: * * wid Widget widget ID * * which long button index * * call XtPointer not used * * * * Output parameters: * * Return parameters: * * NONE * * * ** * * Log: * * J. Wu/SAIC 07/04 initial coding * ***********************************************************************/ { if ( _filterStatus[which] ) { _filterStatus[which] = False; } else { _filterStatus[which] = True; } pgfilterw_updateFilter (); } /*=====================================================================*/ static void pgfilterw_updateFilter ( void ) /************************************************************************ * pgfilterw_updateFilter * * * * Updates the current filter string and then refreshes the display. * * * * static void pgfilterw_updateFilter ( void ) * * * * Input parameters: * * Output parameters: * * none * * * ** * * Log: * * J. Wu/SAIC 07/04 initial coding * * J. Wu/SAIC 08/04 link filter change with GFA window * * J. Wu/SAIC 09/04 Restart GFA for any filter changes * * J. Wu/SAIC 10/04 Access GFA attr with cvg_getFld() * * E. Safford/SAIC 07/05 rm sequence # from cvg_scangfa() call * * M. Li/SAIC 03/07 Not reset fcst hour if change from GFA * * E. Safford/SAIC 05/07 fix gfa' connection * * E. Safford/SAIC 06/07 fix bug in preFilterOn determination * * B. Yin/SAIC 12/07 set GFA hr to last selected filter time * * J. Wu/SGT 06/14 Unset operation for a new selection * ***********************************************************************/ { int ii, filternum, ier, cur_obj, cur_loc, newel_loc, num; int subtyp, areatyp, len; char lastTime[8], value[32], tag[32], timeCmp[10]; Boolean gfaIsUp = False, gfaInAdd = False, preFilterOn = False; Boolean gfaPrimeIsUp = False; VG_DBStruct cur_el, newel; /*---------------------------------------------------------------------*/ cur_el.elem.gfa.info.nblocks = 0; _curFilter[0] = '\0'; filternum = 0; for ( ii = 0; ii < _nFilTime[TIME_FILTER]; ii++ ) { if ( _filterStatus[ii] ) { filternum++; strcat ( _curFilter, _filTime[TIME_FILTER][ii] ); if ( ii < (_nFilTime[TIME_FILTER] - 1) ) { strcat ( _curFilter, ";" ); } } } /* * If no filter is provided but the filter window is up - none * of the elements with time stamp will be displayed. If the * filter window is down, all elements should be displayed. */ if ( filternum == 0 ) { if ( pgfilterw_isUp() ) { strcpy ( _curFilter, ACTV_FILTER ); } else { strcpy ( _curFilter, CANCEL_FILTER ); } } /* * Check if gfaw is up and its mode. */ gfaIsUp = pggfaw_isUp(); gfaPrimeIsUp = pggfawp_isUp(); if( gfaIsUp ) { gfaInAdd = pggfaw_isAddMode(); } else if( gfaPrimeIsUp ) { gfaInAdd = pggfawp_isAddMode(); } cur_obj = pgpalw_getCurObjId (); /* * If gfaw is up, retrieve the current GFA attributes and check * if the previous forecast hour is still "ON" in filter window. * * If it is still on, then take no action. If it is not, and there * is another time selected, set the GFA/GFA' window forecast hour to * the first selected time. * * Note that the GFA/GFA' will ignore the Airmet and Outlook filter * settings. */ cur_loc = -1; preFilterOn = False; if ( gfaIsUp || gfaPrimeIsUp ) { if ( gfaInAdd ) { if( gfaIsUp ) { pggfaw_getAttr ( &cur_el ); ier = 0; } else { pggfawp_getAttr ( &cur_el ); ier = 0; } } else { cur_loc = pgactv_getElmLoc (); cvg_rdrec ( cvg_getworkfile(), cur_loc, &cur_el, &ier ); } cvg_getFld ( &cur_el, TAG_GFA_FCSTHR, value, &ier ); if ( filternum > 0 && ier == 0 ) { for ( ii = 0; ii < _nFilTime[TIME_FILTER]; ii++ ) { if ( _filterStatus[ii] ) { strcpy( timeCmp, _filTime[TIME_FILTER][ii] ); len = strlen( timeCmp ); if( timeCmp[ len-1 ] == '+' ) { timeCmp[ len-1 ] = '\0'; } if ( strcmp ( value, timeCmp ) == 0 ) { preFilterOn = True; break; } } } } } /* * Update filter setting in CVG library. */ cvg_setfilter ( _curFilter, &ier ); /* * Refresh the display. */ pgfilterw_refresh (); /* * Adjust GFA window, if necessary. */ if ( gfaIsUp || gfaPrimeIsUp ) { /* * If previously in "Add" mode, keep drawing. */ if ( gfaInAdd ) { /* * Set the GFA hour to the last selected filter time. * */ pgfilterw_getLastTime ( lastTime ); if ( strlen ( lastTime ) > (size_t)0 ) { if (!_fromGfa) { if( gfaIsUp ) { pggfaw_setHour ( lastTime ); } else { pggfawp_setHour ( lastTime ); } } } } else { /* Previously in "Edit" mode */ /* * The filter matching the active element's forecast hour * is still ON, keep editing it. */ if ( preFilterOn ) { cvg_freeElPtr( &cur_el ); pghdlb_select ( &cur_el, cur_loc ); } else { /* * The filter matching the active element's forecast * hour is OFF, terminate all pending actions. * However, if it is turned off by pressing hotkeys, * and a GFA element matching the same subtype, * and area type number could be found, * set to edit that element. */ if ( _offByHotkey ) { cvg_getFld ( &cur_el, TAG_GFA_SUBTYPE, value, &ier ); subtyp = atoi ( value ); cvg_getFld ( &cur_el, TAG_GFA_AREATYPE, value, &ier ); areatyp = atoi ( value ); cvg_getFld ( &cur_el, TAG_GFA_TAG, tag, &ier ); cvg_scangfa ( NULL, pglayer_getCurLayer(), subtyp, areatyp, tag, &newel, &newel_loc, &ier ); if ( ier == 0 ) { crg_getinx ( cur_loc, &num, &ier); pghdlb_deselectEl ( num, TRUE ); pgactv_setActvElm ( &newel, newel_loc ); pghdlb_select ( &newel, newel_loc ); if( gfaIsUp ) { pggfaw_setAttr ( &newel ); } else { pggfawp_setAttr ( &newel ); } } else { pgevt_unsetOper ( TRUE ); } } else { pgevt_unsetOper ( TRUE ); } _offByHotkey = False; } } /* End "if" in edit mode */ } // Need to reset the operation to allow a new selection. else { pgevt_unsetOper ( FALSE ); } cvg_freeElPtr( &cur_el ); _fromGfa = False; } /*=====================================================================*/ void pgfilterw_stepOneUp ( void ) /************************************************************************ * pgfilterw_stepOneUp * * * * Moves up one filter from the highest one currently selected. * * * * void pgfilterw_stepOneUp ( ) * * * * Input parameters: * * Output parameters: * * none * * * ** * * Log: * * J. Wu/SAIC 07/04 initial coding * * J. Wu/SAIC 08/04 set _offByHotkey to True * * J. Wu/SAIC 12/04 disable if the filter window is not up * ***********************************************************************/ { int ii, highest; /*---------------------------------------------------------------------*/ if ( !pgfilterw_isUp() ) return; highest = 0; for ( ii = 0; ii < _nFilTime[TIME_FILTER]; ii++ ) { if ( _filterStatus[ii] && ii >= highest ) { highest = ii + 1; } _filterStatus[ii] = False; XmToggleButtonSetState ( _filterChkBtn[ii], False, False ); } if ( highest >= (_nFilTime[TIME_FILTER]) ) { highest = _nFilTime[TIME_FILTER] - 1; } _filterStatus[highest] = True; XmToggleButtonSetState ( _filterChkBtn[highest], True, False ); _offByHotkey = True; pgfilterw_updateFilter ( ); } /*=====================================================================*/ void pgfilterw_stepOneDown ( void ) /************************************************************************ * pgfilterw_stepOneDown * * * * Moves down one filter from the lowest one currently selected. * * * * void pgfilterw_stepOnDown ( void ) * * * * Input parameters: * * Output parameters: * * none * * * ** * * Log: * * J. Wu/SAIC 07/04 initial coding * * J. Wu/SAIC 08/04 set _offByHotkey to True * * J. Wu/SAIC 12/04 disable if the filter window is not up * ***********************************************************************/ { int ii, lowest; /*---------------------------------------------------------------------*/ if ( !pgfilterw_isUp() ) return; lowest = _nFilTime[TIME_FILTER] - 1; for ( ii = (_nFilTime[TIME_FILTER]-1); ii >= 0; ii-- ) { if ( _filterStatus[ii] && ii <= lowest ) { lowest = ii - 1; } _filterStatus[ii] = False; XmToggleButtonSetState ( _filterChkBtn[ii], False, False ); } if ( lowest <= 0 ) { lowest = 0; } _filterStatus[lowest] = True; XmToggleButtonSetState ( _filterChkBtn[lowest], True, False ); _offByHotkey = True; pgfilterw_updateFilter (); } /*=====================================================================*/ static void pgfilterw_refresh ( void ) /************************************************************************ * pgpalw_refresh * * * * This function refeshes the drawn pgen elements and signals for a * * reload of all frames in the loop. The current pixmap is cleared and * * restored from the master copy, then cvg_redraw is called to redraw * * pgen elements. The xw driver will then reload the pgen elements for * * all the remaining pixmaps in the loop. This reload will take place * * the next time they are displayed. * * * * static void pgfilterw_refresh ( ) * * * * Input parameters: * * Output parameters: * * Return value: * * NONE * ** * * Log: * * J. Wu/SAIC 07/04 copy from pgpalw_refresh() * * S. Danz/AWC 07/06 cvg_redraw before crg_rebuild so * * autoplacement is ready * * J. Wu/SAIC 02/08 refresh under user's projection * ***********************************************************************/ { Widget canvas; Cardinal width, height; int ier; Boolean compWinIsUp = False; /*---------------------------------------------------------------------*/ /* * Check if the comptational window is up or not. The refresh should be * done on the user's projection */ if ( ncw_isup() ) { compWinIsUp = True; ncw_unset(); } /* * Clear current display */ canvas = (Widget)mcanvw_getDrawingW(); XtVaGetValues ( canvas, XmNwidth, &width, XmNheight, &height, NULL ); XClearArea ( XtDisplay(canvas), XtWindow(canvas), 0, 0, width, height, False ); /* * For each frame, copy from master pixmap to displayable * pixmaps in gemwindow. */ xpgrestlp (); /* * Tell xw driver to refresh the vector graphics * for all pixmaps in the loop. */ xpgrfrsh (); /* * Load and plot the vg elements in current frame. */ cvg_redraw( cvg_getworkfile(), &ier ); /* * Now that we have everything loaded, rebuild the range * records */ crg_rebuild (); geplot ( &ier ); /* * Reset the comptational window if necessary. */ if ( compWinIsUp ) { ncw_set (); ncw_sproj ( "PREFS" ); } } /*=====================================================================*/ void pgfilterw_turnOnTime ( const char *newTime ) /************************************************************************ * pgfilterw_turnOnTime * * * * Turns on the given new time, if it is in the menu. * * * * void pgfilterw_turnOnTime ( newTime ) * * * * Input parameters: * * *newTime char New time to be turned on * * * * Output parameters: * * none * * * ** * * Log: * * J. Wu/SAIC 08/04 initial coding * * M. Li/SAIC 03/07 add cvg_matchfilter * * M. Li/SAIC 03/07 Turn on _fromGfa - change from GFA * ***********************************************************************/ { int ii, ier; filter_t timeMatched, timecmp; Boolean matchAny = True, filter_match; /*---------------------------------------------------------------------*/ strcpy ( timecmp, newTime ); cvg_matchfilter ( timecmp, matchAny, &filter_match, timeMatched, &ier ); if ( filter_match ) { strcpy ( timecmp, timeMatched ); } for ( ii = 0; ii < _nFilTime[TIME_FILTER]; ii++ ) { if ( !(_filterStatus[ii] ) && strcasecmp ( timecmp, _filTime[TIME_FILTER][ii] ) == 0 ) { _filterStatus[ii] = True; XmToggleButtonSetState ( _filterChkBtn[ii], True, False ); _fromGfa = True; pgfilterw_updateFilter (); break; } } } /*=====================================================================*/ static void pgfilterw_getLastTime ( char *selectedTime ) /************************************************************************ * pgfilterw_getLastTime * * * * Gets the name of the last selected filter time. * * * * void pgfilterw_getLastTime ( selectedTime ) * * * * Input parameters: * * none * * * * Output parameters: * * *selectedTime char Name of the first selected filter time * * * ** * * Log: * * J. Wu/SAIC 08/04 initial coding * * B. Yin/SAIC 12/07 change first time to last time * ***********************************************************************/ { int ii; /*---------------------------------------------------------------------*/ selectedTime[0] = '\0'; for ( ii = _nFilTime[TIME_FILTER] - 1; ii >= 0; ii-- ) { if ( _filterStatus[ii] ) { strcpy ( selectedTime, _filTime[TIME_FILTER][ii] ); break; } } }
29.79538
79
0.472936
[ "vector" ]
f0a12f701bef94c53ade31d15cb2529e4d1bae96
5,469
h
C
cc/taxonomy.h
HKU-BAL/MegaPath
b81796024f864af5fd44deb5812f34704c570160
[ "BSD-3-Clause" ]
6
2021-10-06T07:47:04.000Z
2022-01-25T05:09:08.000Z
cc/taxonomy.h
edwwlui/MegaPath
b81796024f864af5fd44deb5812f34704c570160
[ "BSD-3-Clause" ]
null
null
null
cc/taxonomy.h
edwwlui/MegaPath
b81796024f864af5fd44deb5812f34704c570160
[ "BSD-3-Clause" ]
null
null
null
#ifndef TAXONOMY_H__ #define TAXONOMY_H__ #include <sstream> #include <unordered_map> #include <vector> #include <cassert> #include <cctype> #include <zlib.h> #include "kxseq.h" // ========================== HELPER FUNCTIONS ============================ inline std::string removeVersion(const std::string &accesstion) { for (int i = accesstion.length() - 1; i >= 0; --i) { if (accesstion[i] == '.') { return accesstion.substr(0, i); } else if (!isdigit(accesstion[i])) { return accesstion; } } return accesstion; } inline std::string getAccession(const std::string &ntHeader) { size_t spliterPos = ntHeader.find_first_of('|'); if (spliterPos == std::string::npos) { // new format header, see http://www.ncbi.nlm.nih.gov/news/09-17-2014-simple-FASTA-headers-genomes-FTP/ return removeVersion(ntHeader); } else if (ntHeader.substr(0, spliterPos) == "gi") { // old header, skip the GI, and then the db flag spliterPos = ntHeader.find_first_of('|', spliterPos + 1); spliterPos = ntHeader.find_first_of('|', spliterPos + 1); size_t spliterPos2 = ntHeader.find_first_of('|', spliterPos + 1); return removeVersion(ntHeader.substr(spliterPos + 1, spliterPos2 - spliterPos - 1)); } else { return removeVersion(ntHeader); } } // ========================== END OF HELPER FUNCTIONS ============================ struct TaxInfo { int parent; std::string rank; std::string name; }; struct TaxDB { static const int kInitNumTax = 2000000; std::unordered_map<std::string, int> acc2tid; std::unordered_map<std::string, int> name2tid; std::vector<TaxInfo> taxInfo; TaxDB(): taxInfo(kInitNumTax) {} void initAccToTax(const char *acc2TidFile) { gzFile fp = std::string(acc2TidFile) == "-" ? gzdopen(fileno(stdin), "r") : gzopen(acc2TidFile, "r"); kx::kxstream<gzFile> ks(fp); std::string buf, acc, tid; while (ks.get_until(kx::kSepSpace, buf) != kx::kEOF) { ks.get_until(kx::kSepSpace, acc); ks.get_until(kx::kSepSpace, tid); acc2tid[removeVersion(acc)] = atoi(tid.c_str()); ks.get_until(kx::kSepLine, buf); } gzclose(fp); } void readNode(const char *nodePath) { gzFile fpNode = std::string(nodePath) == "-" ? gzdopen(fileno(stdin), "r") : gzopen(nodePath, "r"); kx::kxstream<gzFile> ksNode(fpNode); std::string tid, buf, parent, rank; while (ksNode.get_until(kx::kSepSpace, tid) != kx::kEOF) { ksNode.get_until(kx::kSepSpace, buf); ksNode.get_until(kx::kSepSpace, parent); ksNode.get_until(kx::kSepSpace, buf); ksNode.get_until(kx::kSepSpace, rank); int id = atoi(tid.c_str()); if (id >= (int)taxInfo.size()) { taxInfo.resize((id + 1) * 1.5); } taxInfo[id].parent = atoi(parent.c_str()); taxInfo[id].rank = rank; ksNode.get_until(kx::kSepLine, buf); } gzclose(fpNode); } void readName(const char *namePath, bool alsoAddName2tid = false) { gzFile fpName = std::string(namePath) == "-" ? gzdopen(fileno(stdin), "r") : gzopen(namePath, "r"); kx::kxstream<gzFile> ksName(fpName); std::string buf; while (ksName.get_until(kx::kSepLine, buf) != kx::kEOF) { if (buf.find("scientific name") == std::string::npos) { continue; } std::stringstream is(buf); int id; char d; is >> id >> d; std::string name; std::string nextpart; is >> nextpart; while (nextpart != "|") { if (name.length() > 0) name += " "; name += nextpart; is >> nextpart; } taxInfo[id].name = name; if (alsoAddName2tid) name2tid[name] = id; } gzclose(fpName); } int popUpToSpecies(int tid) { while (tid != 1 && tid != 0 && taxInfo[tid].rank != "species") { tid = taxInfo[tid].parent; } return tid; } std::string getTaxInfo(int tid) { std::string s; while (tid != 1 && tid != 0) { if (taxInfo[tid].rank == "species" || taxInfo[tid].rank == "genus" || taxInfo[tid].rank == "family" || taxInfo[tid].rank == "superkingdom") { if (s.length()) { s += "|"; } s += taxInfo[tid].rank + "|" + taxInfo[tid].name; } tid = taxInfo[tid].parent; } return s; } int LCA(const std::vector<int> &tids) { if (tids.size() == 1) return tids[0]; std::vector<std::vector<int>> lineage(tids.size()); for (size_t i = 0; i < tids.size(); ++i) { int tid = tids[i]; while (tid != 0 && tid != 1) { lineage[i].push_back(tid); tid = taxInfo[tid].parent; } lineage[i].push_back(tid); } int lca = 0; for (size_t k = 0; ; ++k) { int lcaCandidate = *(lineage[0].rbegin() + k); for (size_t i = 1; i < tids.size(); ++i) { if (lineage[i].size() < k + 1 || *(lineage[i].rbegin() + k) != lcaCandidate) { return lca; } } lca = lcaCandidate; } return lca; } }; #endif
30.383333
111
0.522033
[ "vector" ]
f0bb423b8c2f85c3e9e9f2092125c1ce58ad8e02
1,796
h
C
sync/js/sync_js_controller.h
Fusion-Rom/android_external_chromium_org
d8b126911c6ea9753e9f526bee5654419e1d0ebd
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-01-25T10:18:18.000Z
2021-01-23T15:29:56.000Z
sync/js/sync_js_controller.h
Fusion-Rom/android_external_chromium_org
d8b126911c6ea9753e9f526bee5654419e1d0ebd
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2018-02-10T21:00:08.000Z
2018-03-20T05:09:50.000Z
sync/js/sync_js_controller.h
Fusion-Rom/android_external_chromium_org
d8b126911c6ea9753e9f526bee5654419e1d0ebd
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-04T06:34:36.000Z
2020-11-04T06:34:36.000Z
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SYNC_JS_SYNC_JS_CONTROLLER_H_ #define SYNC_JS_SYNC_JS_CONTROLLER_H_ #include <string> #include <vector> #include "base/basictypes.h" #include "base/compiler_specific.h" #include "base/memory/weak_ptr.h" #include "base/observer_list.h" #include "sync/base/sync_export.h" #include "sync/internal_api/public/util/weak_handle.h" #include "sync/js/js_controller.h" #include "sync/js/js_event_handler.h" namespace syncer { class JsBackend; // A class that mediates between the sync JsEventHandlers and the sync // JsBackend. class SYNC_EXPORT SyncJsController : public JsController, public JsEventHandler, public base::SupportsWeakPtr<SyncJsController> { public: SyncJsController(); virtual ~SyncJsController(); // Sets the backend to route all messages to (if initialized). // Sends any queued-up messages if |backend| is initialized. void AttachJsBackend(const WeakHandle<JsBackend>& js_backend); // JsController implementation. virtual void AddJsEventHandler(JsEventHandler* event_handler) OVERRIDE; virtual void RemoveJsEventHandler(JsEventHandler* event_handler) OVERRIDE; // JsEventHandler implementation. virtual void HandleJsEvent(const std::string& name, const JsEventDetails& details) OVERRIDE; private: // Sets |js_backend_|'s event handler depending on how many // underlying event handlers we have. void UpdateBackendEventHandler(); WeakHandle<JsBackend> js_backend_; ObserverList<JsEventHandler> js_event_handlers_; DISALLOW_COPY_AND_ASSIGN(SyncJsController); }; } // namespace syncer #endif // SYNC_JS_SYNC_JS_CONTROLLER_H_
29.933333
76
0.769488
[ "vector" ]
f0d0b02cd1ea60049b7e169473144ee21f911d3f
601
h
C
SDK/netvars.h
pwnedboi/csgobase
1144a6990cc08d3c7b57c3badf93b903468395d1
[ "MIT" ]
9
2018-06-28T19:40:34.000Z
2020-11-02T09:01:33.000Z
SDK/netvars.h
pwnedboi/csgobase
1144a6990cc08d3c7b57c3badf93b903468395d1
[ "MIT" ]
1
2018-09-01T20:55:55.000Z
2018-09-01T20:55:55.000Z
SDK/netvars.h
pwnedboi/csgobase
1144a6990cc08d3c7b57c3badf93b903468395d1
[ "MIT" ]
5
2018-09-01T20:53:21.000Z
2020-06-16T19:33:23.000Z
#pragma once namespace NetVar { vector<RecvTable*> GetTables(); RecvTable* GetTable(vector<RecvTable*> tables, const char* tableName); int GetOffset(vector<RecvTable*> tables, const char* tableName, const char *propName); int GetProp(vector<RecvTable*> tables, const char* tableName, const char* propName, RecvProp** prop = 0); int GetProp(vector<RecvTable*> tables, RecvTable* recvTable, const char* propName, RecvProp** prop = 0); string DumpTable(RecvTable* table, int depth); uintptr_t HookProp(const char* tableName, const char* propName, RecvVarProxyFn function); }
46.230769
109
0.735441
[ "vector" ]
f0db3f927cd9858b23f98a487980f07dde49ad6f
2,102
h
C
src/osvr/Server/JSONResolvePossibleRef.h
ccccjason/OSVR_device_plugin
6c9171265900530341cfa79357151daa39618737
[ "Apache-2.0" ]
1
2022-03-28T05:09:11.000Z
2022-03-28T05:09:11.000Z
src/osvr/Server/JSONResolvePossibleRef.h
ccccjason/my_osvr
fdb2a64cbf88211c34f8c8bd42f0f83a6b98769e
[ "Apache-2.0" ]
null
null
null
src/osvr/Server/JSONResolvePossibleRef.h
ccccjason/my_osvr
fdb2a64cbf88211c34f8c8bd42f0f83a6b98769e
[ "Apache-2.0" ]
null
null
null
/** @file @brief Header @date 2015 @author Sensics, Inc. <http://sensics.com/osvr> */ // Copyright 2015 Sensics, 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. #ifndef INCLUDED_JSONResolvePossibleRef_h_GUID_64F277A1_33F0_4986_6EEE_09E17C09AA52 #define INCLUDED_JSONResolvePossibleRef_h_GUID_64F277A1_33F0_4986_6EEE_09E17C09AA52 // Internal Includes // - none // Library/third-party includes #include <json/value.h> // Standard includes #include <vector> #include <string> namespace osvr { namespace server { /// @brief Given an input that might be a filename, might be a JSON /// Pointer-style $ref object, and might just directly be an object, return /// the object desired. /// /// If just a string (suggesting it was intended to be a reference), returns /// null. /// /// @param stringAcceptableResult Determines whether a string that we can't /// resolve to a loadable JSON reference should be returned as itself /// (valid, true), or should be signaled as an error by returning null /// (false, default) /// @param searchPath Optional list of directories to look for any mentioned /// files. Json::Value resolvePossibleRef(Json::Value const &input, bool stringAcceptableResult = false, std::vector<std::string> const &searchPath = std::vector<std::string>()); } // namespace server } // namespace osvr #endif // INCLUDED_JSONResolvePossibleRef_h_GUID_64F277A1_33F0_4986_6EEE_09E17C09AA52
33.365079
85
0.691722
[ "object", "vector" ]
f0e762cd85dba5fc1003dc066d7883dcb6c4b47e
2,456
h
C
headers/deng/renderer/renderer.h
inugami-dev64/Deng
ce7b05db57a9ee576293f3de28f9cc3a3255f5ca
[ "Apache-2.0" ]
5
2020-12-15T19:27:34.000Z
2021-12-15T17:00:36.000Z
headers/deng/renderer/renderer.h
inugami-dev64/Deng
ce7b05db57a9ee576293f3de28f9cc3a3255f5ca
[ "Apache-2.0" ]
null
null
null
headers/deng/renderer/renderer.h
inugami-dev64/Deng
ce7b05db57a9ee576293f3de28f9cc3a3255f5ca
[ "Apache-2.0" ]
null
null
null
/// DENG: dynamic engine - small but powerful 3D game engine /// licence: Apache, see LICENCE file /// file: renderer.h - abstracted renderer class header /// author: Karl-Mihkel Ott #ifndef __RENDERER_H #define __RENDERER_H #ifdef __RENDERER_CPP #include <string.h> #include <vector> #include <thread> #include <chrono> #include <mutex> #include <queue> #include <string> #include <memory> #include <array> #include <vulkan/vulkan.h> #include <common/base_types.h> #include <common/hashmap.h> #include <common/uuid.h> #include <common/err_def.h> #include <data/assets.h> #include <math/deng_math.h> #include <deng/window.h> #include <deng/cam3d.h> #include <deng/registry/registry.h> #endif #include <imgui-layer/imgui_entity.h> #include <deng/cross_api/cross_api.h> #include <deng/vulkan/renderer.h> #include <deng/opengl/renderer.h> #include <deng/renderer/asset_man.h> #include <deng/renderer/data_updater.h> #define DENG_DEFAULT_NEAR_PLANE 0.1f #define DENG_DEFAULT_FAR_PLANE 25.0f #define DENG_FRAME_INTERVAL 50 // microseconds namespace deng { // Frame renderer type class Renderer; typedef void(*PCustomRunFunc)(Renderer&); /// Main renderer class class Renderer : public __DataUpdater { private: vulkan::__vk_ConfigVars m_vk_vars; opengl::__gl_ConfigVars m_gl_vars; std::shared_ptr<vulkan::__vk_Renderer> m_vk_rend; std::shared_ptr<opengl::__gl_Renderer> m_gl_rend; dengMath::vec4<deng_vec_t> m_env_color; deng_RendererHintBits m_hints; deng_bool_t m_is_init; Window *m_p_win; Camera3D *m_p_cam; public: Renderer(deng_RendererHintBits hints, const dengMath::vec4<deng_vec_t> &env_color); /// Setup graphics api specific renderer from the hints given in the constructor void setup(Camera3D &main_cam, Window &main_win); /// Update data, before creating new frame void update(); /// Begin the rendering loop void run(); /// idle the renderer void idle(); // Render backend getter and setter methods public: void setUIDataPtr(__ImGuiData *p_data); const deng_bool_t isInit(); const std::vector<deng_Id> &getAssets(); const std::vector<deng_Id> &getTextures(); deng::Registry &getRegistry(); }; } #endif
25.061224
91
0.664495
[ "render", "vector", "3d" ]
f0e7acdbf3174c38571ab5e5c50b3b1320e82226
3,473
h
C
code/render/coregraphics/memorymeshloader.h
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
67
2015-03-30T19:56:16.000Z
2022-03-11T13:52:17.000Z
code/render/coregraphics/memorymeshloader.h
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
5
2015-04-15T17:17:33.000Z
2016-02-11T00:40:17.000Z
code/render/coregraphics/memorymeshloader.h
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
34
2015-03-30T15:08:00.000Z
2021-09-23T05:55:10.000Z
#pragma once //------------------------------------------------------------------------------ /** @class CoreGraphics::MemoryMeshLoader Setup a Mesh object from a given vertex, index buffer and primitive group. (C) 2008 Radon Labs GmbH (C) 2013-2016 Individual contributors, see AUTHORS file */ #include "resources/resourceloader.h" #include "coregraphics/base/resourcebase.h" #include "coregraphics/vertexbuffer.h" #include "coregraphics/indexbuffer.h" #include "coregraphics/primitivegroup.h" //------------------------------------------------------------------------------ namespace CoreGraphics { class MemoryMeshLoader : public Resources::ResourceLoader { __DeclareClass(MemoryMeshLoader); public: /// constructor MemoryMeshLoader(); /// set the intended resource usage (default is UsageImmutable) void SetUsage(Base::ResourceBase::Usage usage); /// get resource usage Base::ResourceBase::Usage GetUsage() const; /// set the intended resource access (default is AccessNone) void SetAccess(Base::ResourceBase::Access access); /// get the resource access Base::ResourceBase::Access GetAccess() const; /// set vertex buffer void SetVertexBuffer(const Ptr<CoreGraphics::VertexBuffer>& vBuffer); /// set index buffer void SetIndexBuffer(const Ptr<CoreGraphics::IndexBuffer>& iBuffer); /// set primitive group void SetPrimitiveGroups(const Util::Array<CoreGraphics::PrimitiveGroup>& pGroup); /// called by resource when a load is requested virtual bool OnLoadRequested(); protected: /// setup mesh resource from given memory data bool SetupMeshFromMemory(); private: Base::ResourceBase::Usage usage; Base::ResourceBase::Access access; Ptr<CoreGraphics::VertexBuffer> vertexBuffer; Ptr<CoreGraphics::IndexBuffer> indexBuffer; Util::Array<CoreGraphics::PrimitiveGroup> primitiveGroups; }; //------------------------------------------------------------------------------ /** */ inline void MemoryMeshLoader::SetUsage(Base::ResourceBase::Usage usage_) { this->usage = usage_; } //------------------------------------------------------------------------------ /** */ inline Base::ResourceBase::Usage MemoryMeshLoader::GetUsage() const { return this->usage; } //------------------------------------------------------------------------------ /** */ inline void MemoryMeshLoader::SetAccess(Base::ResourceBase::Access access_) { this->access = access_; } //------------------------------------------------------------------------------ /** */ inline Base::ResourceBase::Access MemoryMeshLoader::GetAccess() const { return this->access; } //------------------------------------------------------------------------------ /** */ inline void MemoryMeshLoader::SetVertexBuffer(const Ptr<CoreGraphics::VertexBuffer>& vBuffer) { this->vertexBuffer = vBuffer; } //------------------------------------------------------------------------------ /** */ inline void MemoryMeshLoader::SetIndexBuffer(const Ptr<CoreGraphics::IndexBuffer>& iBuffer) { this->indexBuffer = iBuffer; } //------------------------------------------------------------------------------ /** */ inline void MemoryMeshLoader::SetPrimitiveGroups(const Util::Array<CoreGraphics::PrimitiveGroup>& pGroup) { this->primitiveGroups = pGroup; } } // namespace CoreGraphics //------------------------------------------------------------------------------
28.702479
93
0.556291
[ "mesh", "object" ]
f0f3c729ac21fd70684b16ed737f427304ac3a3a
9,902
h
C
include/readSTL.h
ericpko/computer-graphics-ray-casting
5aeeff4d7bebffe0c2844ccee72ebc6180c5f481
[ "MIT" ]
null
null
null
include/readSTL.h
ericpko/computer-graphics-ray-casting
5aeeff4d7bebffe0c2844ccee72ebc6180c5f481
[ "MIT" ]
null
null
null
include/readSTL.h
ericpko/computer-graphics-ray-casting
5aeeff4d7bebffe0c2844ccee72ebc6180c5f481
[ "MIT" ]
null
null
null
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com> // // 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/. #ifndef IGL_READSTL_H #define IGL_READSTL_H # define IGL_INLINE inline #ifndef IGL_NO_EIGEN # include <Eigen/Core> #endif #include <string> #include <cstdio> #include <vector> namespace igl { // Inputs: // stl_file pointer to already opened .stl file // Outputs: // stl_file closed file template <typename TypeV, typename TypeF, typename TypeN> IGL_INLINE bool readSTL( FILE * stl_file, std::vector<std::vector<TypeV> > & V, std::vector<std::vector<TypeF> > & F, std::vector<std::vector<TypeN> > & N); template <typename TypeV, typename TypeF, typename TypeN> IGL_INLINE bool readSTL( const std::string & filename, std::vector<std::vector<TypeV> > & V, std::vector<std::vector<TypeF> > & F, std::vector<std::vector<TypeN> > & N); } #include <iostream> template <typename TypeV, typename TypeF, typename TypeN> IGL_INLINE bool igl::readSTL( const std::string & filename, std::vector<std::vector<TypeV> > & V, std::vector<std::vector<TypeF> > & F, std::vector<std::vector<TypeN> > & N) { using namespace std; // Should test for ascii // Open file, and check for error FILE * stl_file = fopen(filename.c_str(),"rb"); if(NULL==stl_file) { fprintf(stderr,"IOError: %s could not be opened...\n", filename.c_str()); return false; } return readSTL(stl_file,V,F,N); } template <typename TypeV, typename TypeF, typename TypeN> IGL_INLINE bool igl::readSTL( FILE * stl_file, std::vector<std::vector<TypeV> > & V, std::vector<std::vector<TypeF> > & F, std::vector<std::vector<TypeN> > & N) { using namespace std; //stl_file = freopen(NULL,"rb",stl_file); if(NULL==stl_file) { fprintf(stderr,"IOError: stl file could not be reopened as binary (1) ...\n"); return false; } V.clear(); F.clear(); N.clear(); // Specifically 80 character header char header[80]; char solid[80]; bool is_ascii = true; if(fread(header,1,80,stl_file) != 80) { cerr<<"IOError: too short (1)."<<endl; goto close_false; } sscanf(header,"%s",solid); if(string("solid") != solid) { // definitely **not** ascii is_ascii = false; }else { // might still be binary char buf[4]; if(fread(buf,1,4,stl_file) != 4) { cerr<<"IOError: too short (3)."<<endl; goto close_false; } size_t num_faces = *reinterpret_cast<unsigned int*>(buf); fseek(stl_file,0,SEEK_END); int file_size = ftell(stl_file); if(file_size == 80 + 4 + (4*12 + 2) * num_faces) { is_ascii = false; }else { is_ascii = true; } } if(is_ascii) { // Rewind to end of header //stl_file = fopen(filename.c_str(),"r"); //stl_file = freopen(NULL,"r",stl_file); fseek(stl_file, 0, SEEK_SET); if(NULL==stl_file) { fprintf(stderr,"IOError: stl file could not be reopened as ascii ...\n"); return false; } // Read 80 header // Eat file name #ifndef IGL_LINE_MAX # define IGL_LINE_MAX 2048 #endif char name[IGL_LINE_MAX]; if(NULL==fgets(name,IGL_LINE_MAX,stl_file)) { cerr<<"IOError: ascii too short (2)."<<endl; goto close_false; } // ascii while(true) { int ret; char facet[IGL_LINE_MAX],normal[IGL_LINE_MAX]; vector<TypeN > n(3); double nd[3]; ret = fscanf(stl_file,"%s %s %lg %lg %lg",facet,normal,nd,nd+1,nd+2); if(string("endsolid") == facet) { break; } if(ret != 5 || !(string("facet") == facet || string("faced") == facet) || string("normal") != normal) { cout<<"facet: "<<facet<<endl; cout<<"normal: "<<normal<<endl; cerr<<"IOError: bad format (1)."<<endl; goto close_false; } // copy casts to Type n[0] = nd[0]; n[1] = nd[1]; n[2] = nd[2]; N.push_back(n); char outer[IGL_LINE_MAX], loop[IGL_LINE_MAX]; ret = fscanf(stl_file,"%s %s",outer,loop); if(ret != 2 || string("outer") != outer || string("loop") != loop) { cerr<<"IOError: bad format (2)."<<endl; goto close_false; } vector<TypeF> f; while(true) { char word[IGL_LINE_MAX]; int ret = fscanf(stl_file,"%s",word); if(ret == 1 && string("endloop") == word) { break; }else if(ret == 1 && string("vertex") == word) { vector<TypeV> v(3); double vd[3]; int ret = fscanf(stl_file,"%lg %lg %lg",vd,vd+1,vd+2); if(ret != 3) { cerr<<"IOError: bad format (3)."<<endl; goto close_false; } f.push_back(V.size()); // copy casts to Type v[0] = vd[0]; v[1] = vd[1]; v[2] = vd[2]; V.push_back(v); }else { cerr<<"IOError: bad format (4)."<<endl; goto close_false; } } F.push_back(f); char endfacet[IGL_LINE_MAX]; ret = fscanf(stl_file,"%s",endfacet); if(ret != 1 || string("endfacet") != endfacet) { cerr<<"IOError: bad format (5)."<<endl; goto close_false; } } // read endfacet goto close_true; }else { // Binary //stl_file = freopen(NULL,"rb",stl_file); fseek(stl_file, 0, SEEK_SET); // Read 80 header char header[80]; if(fread(header,sizeof(char),80,stl_file)!=80) { cerr<<"IOError: bad format (6)."<<endl; goto close_false; } // Read number of triangles unsigned int num_tri; if(fread(&num_tri,sizeof(unsigned int),1,stl_file)!=1) { cerr<<"IOError: bad format (7)."<<endl; goto close_false; } V.resize(num_tri*3,vector<TypeV >(3,0)); N.resize(num_tri,vector<TypeN >(3,0)); F.resize(num_tri,vector<TypeF >(3,0)); for(int t = 0;t<(int)num_tri;t++) { // Read normal float n[3]; if(fread(n,sizeof(float),3,stl_file)!=3) { cerr<<"IOError: bad format (8)."<<endl; goto close_false; } // Read each vertex for(int c = 0;c<3;c++) { F[t][c] = 3*t+c; N[t][c] = n[c]; float v[3]; if(fread(v,sizeof(float),3,stl_file)!=3) { cerr<<"IOError: bad format (9)."<<endl; goto close_false; } V[3*t+c][0] = v[0]; V[3*t+c][1] = v[1]; V[3*t+c][2] = v[2]; } // Read attribute size unsigned short att_count; if(fread(&att_count,sizeof(unsigned short),1,stl_file)!=1) { cerr<<"IOError: bad format (10)."<<endl; goto close_false; } } goto close_true; } close_false: fclose(stl_file); return false; close_true: fclose(stl_file); return true; } #ifdef IGL_STATIC_LIBRARY // Explicit template instantiation // generated by autoexplicit.sh template bool igl::readSTL<Eigen::Matrix<double, -1, -1, 1, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 1, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&); // generated by autoexplicit.sh template bool igl::readSTL<Eigen::Matrix<float, -1, 3, 1, -1, 3>, Eigen::Matrix<unsigned int, -1, 3, 1, -1, 3>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, Eigen::PlainObjectBase<Eigen::Matrix<float, -1, 3, 1, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<unsigned int, -1, 3, 1, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&); // generated by autoexplicit.sh template bool igl::readSTL<Eigen::Matrix<double, -1, 3, 0, -1, 3>, Eigen::Matrix<int, -1, 3, 0, -1, 3>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 0, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&); // generated by autoexplicit.sh template bool igl::readSTL<Eigen::Matrix<double, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&); template bool igl::readSTL<Eigen::Matrix<float, -1, -1, 0, -1, -1>, Eigen::Matrix<int, -1, -1, 0, -1, -1>, Eigen::Matrix<float, -1, -1, 0, -1, -1> >(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, Eigen::PlainObjectBase<Eigen::Matrix<float, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> >&, Eigen::PlainObjectBase<Eigen::Matrix<float, -1, -1, 0, -1, -1> >&); template bool igl::readSTL<Eigen::Matrix<double, -1, 3, 1, -1, 3>, Eigen::Matrix<int, -1, 3, 1, -1, 3>, Eigen::Matrix<double, -1, -1, 0, -1, -1> >(std::basic_string<char, std::char_traits<char>, std::allocator<char> > const&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, 3, 1, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<int, -1, 3, 1, -1, 3> >&, Eigen::PlainObjectBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> >&); #endif #endif
33.910959
439
0.5816
[ "geometry", "vector", "solid" ]
0b08b5e621885a9709b532fbeec0a0e6c83a7b63
4,823
h
C
IndieLib/common/include/IND_AnimationManager.h
DarthMike/indielib-crossplatform
473a589ae050b6d1c274cf58adf08731e63ae870
[ "Zlib" ]
29
2015-03-05T08:11:23.000Z
2020-11-11T08:27:22.000Z
IndieLib/common/include/IND_AnimationManager.h
PowerOlive/indielib-crossplatform
473a589ae050b6d1c274cf58adf08731e63ae870
[ "Zlib" ]
1
2019-04-03T18:59:01.000Z
2019-04-14T11:46:45.000Z
IndieLib/common/include/IND_AnimationManager.h
PowerOlive/indielib-crossplatform
473a589ae050b6d1c274cf58adf08731e63ae870
[ "Zlib" ]
9
2015-03-05T08:17:10.000Z
2021-08-09T07:15:37.000Z
/***************************************************************************************** * File: IND_AnimationManager.h * Desc: Animation manager *****************************************************************************************/ /*********************************** The zlib License ************************************ * * Copyright (c) 2013 Indielib-crossplatform Development Team * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source * distribution. * *****************************************************************************************/ #ifndef _IND_ANIMATIONMANAGER_ #define _IND_ANIMATIONMANAGER_ // ----- Includes ----- #include <list> #include <vector> // ----- Forward declarations ----- class IND_SurfaceManager; class IND_ImageManager; class IND_Image; class IND_Timer; class CollisionParser; class IND_Animation; // -------------------------------------------------------------------------------- // IND_AnimationManager // -------------------------------------------------------------------------------- /** @defgroup IND_AnimationManager IND_AnimationManager @ingroup Managers Manager of ::IND_Animation objects. Click in ::IND_AnimationManager to see all the methods of this class. */ /**@{*/ /** Manager of ::IND_Animation objects. Used for storing these type of objects. */ class LIB_EXP IND_AnimationManager { public: // ----- Init/End ----- IND_AnimationManager(): _ok(false) { } ~IND_AnimationManager() { end(); } bool init(IND_ImageManager *pImageManager, IND_SurfaceManager *pSurfaceManager); void end(); bool isOK(); // ----- Public methods ----- bool addToImage(IND_Animation *pNewAnimation, const char *pAnimation); // ----- Not specifying block size ----- bool addToSurface(IND_Animation *pNewAnimation, const char *pAnimation, IND_Type pType, IND_Quality pQuality); bool addToSurface(IND_Animation *pNewAnimation, const char *pAnimation, IND_Type pType, IND_Quality pQuality, unsigned char pR, unsigned char pG, unsigned char pB); // ----- Specifying block size ----- bool addToSurface(IND_Animation *pNewAnimation, const char *pAnimation, int pBlockSize, IND_Type pType, IND_Quality pQuality); bool addToSurface(IND_Animation *pNewAnimation, const char *pAnimation, int pBlockSize, IND_Type pType, IND_Quality pQuality, unsigned char pR, unsigned char pG, unsigned char pB); bool remove(IND_Animation *pAn); private: /** @cond DOCUMENT_PRIVATEAPI */ // ----- Private ----- bool _ok; // ----- Enums ----- enum { FRAMES, FRAME_, PATH, NAME, FILE, OFFSET_X, OFFSET_Y, SEQUENCES, TIME, OBRACKET, CBRACKET, KW_UNKNOWN }; // ----- Objects ----- IND_ImageManager *_imageManager; IND_SurfaceManager *_surfaceManager; CollisionParser *_collisionParser; // ----- Containers ----- list <IND_Animation *> *_listAnimations; // ----- Private methods ----- bool calculateAxis(IND_Animation *pAn, int pSequence, float pAxisX, float pAxisY, int *pAxisCalX, int *pAxisCalY); void addToList(IND_Animation *pNewAnimation); void delFromlist(IND_Animation *pAn); IND_Image *loadImage(const char *pName); bool remove(IND_Animation *pAn, bool pType); bool parseAnimation(IND_Animation *pNewAnimation, const char *pAnimationName); bool isDeclaredFrame(const char *pFrameName, IND_Animation *pNewAnimation, int *pPos); void writeMessage(); void initVars(); void freeVars(); /** @endcond */ }; /**@}*/ #endif // _IND_ANIMATIONMANAGER_
26.944134
105
0.567489
[ "vector" ]
0b0c26e9b9fa945badc7c7cf641f7a0cedb758fa
2,724
h
C
inipp/utility/filesystem.h
ac-custom-shaders-patch/inipp
112fbb1bcf55ecbfc17db4614335728d29f17c5b
[ "MIT" ]
3
2019-08-25T09:33:51.000Z
2021-10-07T19:51:50.000Z
inipp/utility/filesystem.h
ac-custom-shaders-patch/inipp
112fbb1bcf55ecbfc17db4614335728d29f17c5b
[ "MIT" ]
null
null
null
inipp/utility/filesystem.h
ac-custom-shaders-patch/inipp
112fbb1bcf55ecbfc17db4614335728d29f17c5b
[ "MIT" ]
null
null
null
/** * Copyright (C) 2014 Patrick Mours. All rights reserved. * License: https://github.com/crosire/reshade#license */ #pragma once #include <string> #include <vector> #include <ostream> #include <functional> #include "string_codecvt.h" #ifndef USE_SIMPLE #include "blob.h" #include "special_folder.h" #endif typedef unsigned char byte; namespace utils { enum class special_folder : unsigned; struct path { path() {} path(const char* data) : data_(data) {} path(const wchar_t* data) : data_(utf16_to_utf8(data)) {} path(std::string data) : data_(std::move(data)) {} path(const std::wstring& data) : data_(utf16_to_utf8(data)) {} bool operator==(const path& other) const; bool operator!=(const path& other) const; std::string& string() { return data_; } const std::string& string() const { return data_; } std::wstring wstring() const; friend std::ostream& operator<<(std::ostream& stream, const path& path); bool empty() const { return data_.empty(); } size_t length() const { return data_.length(); } bool is_absolute() const; path parent_path() const; path filename() const; path filename_without_extension() const; std::string extension() const; bool extension_matches(const std::vector<std::string>& extensions) const; path replace_extension(const std::string& extension) const; bool is_child_of(const path& parent) const; path operator/(const path& more) const; path operator+(char c) const { return data_ + c; } path operator+(const path& more) const { return data_ + more.data_; } private: std::string data_; }; bool exists(const path& path); bool create_dir(const path& path); long long get_file_size(const path& path); path resolve(const path& filename, const std::vector<path>& paths); path absolute(const path& filename, const path& parent_path); path get_module_path(void* handle); void set_special_folders_path(const path& ac_root); const path& get_special_folder_path(special_folder id); #ifndef USE_SIMPLE path scan_dir(const path& dir, const char* mask, const std::function<bool(const WIN32_FIND_DATAW& data)>& callback); path scan_dir_recursive(const path& dir, const char* mask, const std::function<bool(const WIN32_FIND_DATAW& data, const path& parent)>& callback, const std::function<bool(const WIN32_FIND_DATAW& data, const path& parent)>& filter_dir = {}); std::vector<path> list_files(const path& path_val, const char* mask = "*", bool recursive = false); bool try_read_file(const path& filename, blob& result); void write_file(const path& filename, const blob_view& data); blob read_file(const path& filename); #endif std::string read_file_str(const path& filename); }
26.446602
100
0.714758
[ "vector" ]
0b0cc1bc8cfe80108f44e6e02120f2701b0fb4a7
8,167
c
C
kernel/arch/arm/src/stmp3770/stmp3770_boot.c
Repeerc/ExistOS_Kernel
0eeb245f6eb5d594dd601fe95b3cab9311758114
[ "Apache-2.0" ]
4
2021-08-14T04:39:55.000Z
2021-08-17T13:07:39.000Z
kernel/arch/arm/src/stmp3770/stmp3770_boot.c
Repeerc/ExistOS_Kernel
0eeb245f6eb5d594dd601fe95b3cab9311758114
[ "Apache-2.0" ]
null
null
null
kernel/arch/arm/src/stmp3770/stmp3770_boot.c
Repeerc/ExistOS_Kernel
0eeb245f6eb5d594dd601fe95b3cab9311758114
[ "Apache-2.0" ]
1
2021-09-02T11:57:11.000Z
2021-09-02T11:57:11.000Z
/**************************************************************************** * arch/arm/src/stmp3770/stmp3770_boot.c * * 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 <stdint.h> #include <stdio.h> #include "chip.h" #include "arm.h" #include "arm_internal.h" #include "arm_arch.h" #include "stmp3770_clkctrl.h" #include "registers/regspower.h" #include "registers/regsdigctl.h" #include "registers/regsapbx.h" #include "registers/regsapbh.h" #ifdef CONFIG_PAGING # include <nuttx/page.h> # include "pg_macros.h" #endif /**************************************************************************** * Private Types ****************************************************************************/ struct section_mapping_s { uint32_t physbase; /* Physical address of the region to be mapped */ uint32_t virtbase; /* Virtual address of the region to be mapped */ uint32_t mmuflags; /* MMU settings for the region (e.g., cache-able) */ uint32_t nsections; /* Number of mappings in the region */ }; /**************************************************************************** * Public Data ****************************************************************************/ extern uint32_t _vector_start; /* Beginning of vector block */ extern uint32_t _vector_end; /* End+1 of vector block */ /**************************************************************************** * Private Data ****************************************************************************/ #ifndef CONFIG_ARCH_ROMPGTABLE static const struct section_mapping_s g_section_mapping[] = { {STMP3770_PERIPHERAL_PSECTION, STMP3770_PERIPHERAL_VSECTION, STMP3770_PERIPHERAL_MMUFLAG, STMP3770_PERIPHERAL_NSECTIONS} , {0, 0, STMP3770_PERIPHERAL_MMUFLAG, STMP3770_PERIPHERAL_NSECTIONS} }; #define NMAPPINGS (sizeof(g_section_mapping) / sizeof(struct section_mapping_s)) #endif /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Name: up_setlevel1entry ****************************************************************************/ #ifndef CONFIG_ARCH_ROMPGTABLE static inline void up_setlevel1entry(uint32_t paddr, uint32_t vaddr, uint32_t mmuflags) { uint32_t *pgtable = (uint32_t *)PGTABLE_BASE_VADDR; uint32_t index = vaddr >> 20; /* Save the page table entry */ pgtable[index] = (paddr | mmuflags); } #endif /**************************************************************************** * Name: up_setlevel2coarseentry ****************************************************************************/ static inline void up_setlevel2coarseentry(uint32_t ctabvaddr, uint32_t paddr, uint32_t vaddr, uint32_t mmuflags) { uint32_t *ctable = (uint32_t *)ctabvaddr; uint32_t index; /* The coarse table divides a 1Mb address space up into 256 entries, each * corresponding to 4Kb of address space. The coarse page table index is * related to the offset from the beginning of 1Mb region. */ index = (vaddr & 0x000ff000) >> 12; /* Save the coarse table entry */ ctable[index] = (paddr | mmuflags); } /**************************************************************************** * Name: up_setupmappings ****************************************************************************/ #ifndef CONFIG_ARCH_ROMPGTABLE static void up_setupmappings(void) { int i; int j; for (i = 0; i < NMAPPINGS; i++) { uint32_t sect_paddr = g_section_mapping[i].physbase; uint32_t sect_vaddr = g_section_mapping[i].virtbase; uint32_t mmuflags = g_section_mapping[i].mmuflags; for (j = 0; j < g_section_mapping[i].nsections; j++) { up_setlevel1entry(sect_paddr, sect_vaddr, mmuflags); sect_paddr += SECTION_SIZE; sect_vaddr += SECTION_SIZE; } } tlb_invalidate(); } #endif /**************************************************************************** * Name: up_vectorpermissions * * Description: * Set permissions on the vector mapping. * ****************************************************************************/ #if !defined(CONFIG_ARCH_ROMPGTABLE) && defined(CONFIG_ARCH_LOWVECTORS) && defined(CONFIG_PAGING) static void up_vectorpermissions(uint32_t mmuflags) { /* The PTE for the beginning of ISRAM is at the base of the L2 page table */ uint32_t *ptr = (uint32_t *)PG_L2_VECT_VADDR; uint32_t pte; /* The pte might be zero the first time this function is called. */ pte = *ptr; if (pte == 0) { pte = PG_VECT_PBASE; } else { pte &= PG_L1_PADDRMASK; } /* Update the MMU flags and save */ *ptr = pte | mmuflags; /* Invalid the TLB for this address */ tlb_invalidate_single(PG_L2_VECT_VADDR); } #endif /**************************************************************************** * Name: up_copyvectorblock * * Description: * Copy the interrupt block to its final destination. * ****************************************************************************/ static volatile void up_copyvectorblock(void) { uint32_t *src; uint32_t *end; uint32_t *dest; /* If we are using vectors in low memory but RAM in that area has been * marked read only, then temporarily mark the mapping write-able * (non-buffered). */ #if !defined(CONFIG_ARCH_ROMPGTABLE) && defined(CONFIG_ARCH_LOWVECTORS) && \ defined(CONFIG_PAGING) up_vectorpermissions(MMU_L2_VECTRWFLAGS); #endif src = (uint32_t *)&_vector_start; end = (uint32_t *)&_vector_end; dest = (uint32_t *)0x4; src++; while (src < end) { *dest++ = *src++; } /* src = (uint32_t *) 0x20; *src = 0x40; */ /* __asm volatile ("mov r0,#4"); __asm volatile ("mov r1,#0"); __asm volatile ("ldr r0,[r0]"); __asm volatile ("str r0,[r1]"); */ /* Make the vectors read-only, cacheable again */ #if !defined(CONFIG_ARCH_ROMPGTABLE) && defined(CONFIG_ARCH_LOWVECTORS) && defined(CONFIG_PAGING) up_vectorpermissions(MMU_L2_VECTROFLAGS); #endif } /**************************************************************************** * Public Functions ****************************************************************************/ void arm_boot(void) { /* __start provided the basic MMU mappings for SRAM. * Now provide mappings for all IO regions * (Including the vector region). */ #ifndef CONFIG_ARCH_ROMPGTABLE up_setupmappings(); #endif /* CONFIG_ARCH_ROMPGTABLE */ up_copyvectorblock(); BF_SETV(POWER_VDDDCTRL,TRG,26); // Set voltage = 1.45 V pll_enable(); HCLK_set_div(0, 4); //120 MHz CPUCLK_set_div(0, 2); //240 MHz CPUCLK_set_gating(0); CPUCLK_set_bypass(0); BF_CS2(APBX_CTRL0, SFTRST, 0, CLKGATE, 0); //Enable APBX DMA BF_CS2(APBH_CTRL0, SFTRST, 0, CLKGATE, 0); //Enable APBH DMA }
27.969178
97
0.52553
[ "vector" ]
0b0fc3bcc7510122ece6008825a31a2d7d4bd0ce
1,923
h
C
schoolwork/particle-system/code/FullEngine/header/ext/simple-xml.h
Benjins/CCSPage
af301acbf78c7f94c5afbe0604b59fa08f8fd259
[ "MIT" ]
null
null
null
schoolwork/particle-system/code/FullEngine/header/ext/simple-xml.h
Benjins/CCSPage
af301acbf78c7f94c5afbe0604b59fa08f8fd259
[ "MIT" ]
null
null
null
schoolwork/particle-system/code/FullEngine/header/ext/simple-xml.h
Benjins/CCSPage
af301acbf78c7f94c5afbe0604b59fa08f8fd259
[ "MIT" ]
null
null
null
/* Author: Benji Smith Licensed under MIT License. See License.txt for details */ #ifndef SIMPLE_XML_H #define SIMPLE_XML_H #include <vector> #include <string> #include <fstream> #include <iostream> #include <map> using std::string; using std::vector; using std::ifstream; using std::cout; using std::endl; using std::ofstream; using std::map; #define MAX_STACK_SIZE 8192 template<typename T> struct Stack{ T* values;//[MAX_STACK_SIZE]; int count; Stack(){ count = 0; values = new T[MAX_STACK_SIZE]; } void Push(const T& newValue){ values[count] = newValue; count++; } T Pop(){ count--; return values[count]; } T& Top(){ return values[count-1]; } ~Stack(){ delete[] values; } }; struct XMLAttribute{ string name; string data; XMLAttribute() : name(), data(){ } XMLAttribute(const string& _name, const string& _data) : name(_name), data(_data){ } XMLAttribute(const string&& _name, const string&& _data) : name(_name), data(_data){ } void Print() const{ cout << name << ":" << data; } string ToString(){ return name + "='" + data + "'"; } }; struct XMLElement{ string name; vector<XMLAttribute> attributes; map<string, string> attributeMap; vector<XMLElement> children; void AddAttribute(const string& name, const string& data){ attributes.emplace_back(name, data); attributeMap.insert(std::make_pair(name, data)); } void AddAttribute(const string&& name, const string&& data){ attributes.emplace_back(name, data); attributeMap.insert(std::make_pair(name, data)); } void Print() const; string SaveElement(string tabbing = ""); }; struct XMLDocument{ string name; vector<XMLElement> contents; void Print() const; }; vector<string> Tokenize(const string& document); XMLDocument ParseTokens(vector<string>& tokens); void SaveXMLDoc(XMLDocument& doc, string fileName); void LoadXMLDoc(XMLDocument& doc, string fileName); #endif
17.169643
61
0.692148
[ "vector" ]
0b1a8828f45860685cb2838e89194bd304b736bd
2,437
h
C
modules/spaint/include/spaint/segmentation/Segmenter.h
torrvision/spaint
9cac8100323ea42fe439f66407b832b88f72d2fd
[ "Unlicense" ]
197
2015-10-01T07:23:01.000Z
2022-03-23T03:02:31.000Z
modules/spaint/include/spaint/segmentation/Segmenter.h
torrvision/spaint
9cac8100323ea42fe439f66407b832b88f72d2fd
[ "Unlicense" ]
16
2016-03-26T13:01:08.000Z
2020-09-02T09:13:49.000Z
modules/spaint/include/spaint/segmentation/Segmenter.h
torrvision/spaint
9cac8100323ea42fe439f66407b832b88f72d2fd
[ "Unlicense" ]
62
2015-10-03T07:14:59.000Z
2021-08-31T08:58:18.000Z
/** * spaint: Segmenter.h * Copyright (c) Torr Vision Group, University of Oxford, 2016. All rights reserved. */ #ifndef H_SPAINT_SEGMENTER #define H_SPAINT_SEGMENTER #include <ITMLib/Objects/RenderStates/ITMRenderState.h> #include <ITMLib/Objects/Views/ITMView.h> #include <ORUtils/SE3Pose.h> #include <orx/base/ORImagePtrTypes.h> namespace spaint { /** * \brief An instance of a class deriving from this one can be used to segment a target from the current view of the scene. */ class Segmenter { //#################### TYPEDEFS #################### protected: typedef boost::shared_ptr<const ITMLib::ITMRenderState> RenderState_CPtr; typedef boost::shared_ptr<const ITMLib::ITMView> View_CPtr; //#################### PROTECTED VARIABLES #################### protected: /** The most recent target mask produced by the segmentation process. */ ORUCharImage_Ptr m_targetMask; /** The current view of the scene. */ View_CPtr m_view; //#################### CONSTRUCTORS #################### public: /** * \brief Constructs a segmenter. * * \param view The current view of the scene. */ explicit Segmenter(const View_CPtr& view); //#################### DESTRUCTOR #################### public: /** * \brief Destroys the segmenter. */ virtual ~Segmenter(); //#################### PUBLIC ABSTRACT MEMBER FUNCTIONS #################### public: /** * \brief Resets the segmenter. */ virtual void reset() = 0; /** * \brief Segments the target from the current view of the scene. * * \param pose The camera pose from which the scene is being viewed. * \param renderState The render state corresponding to the camera. * \return The target mask produced by the segmentation process. */ virtual ORUCharImage_CPtr segment(const ORUtils::SE3Pose& pose, const RenderState_CPtr& renderState) const = 0; /** * \brief Trains the segmenter. * * \param pose The camera pose from which the scene is being viewed. * \param renderState The render state corresponding to the camera. * \return A visualisation of the training process to enable the user to see what's going on. */ virtual ORUChar4Image_CPtr train(const ORUtils::SE3Pose& pose, const RenderState_CPtr& renderState) = 0; }; //#################### TYPEDEFS #################### typedef boost::shared_ptr<Segmenter> Segmenter_Ptr; } #endif
28.670588
123
0.635207
[ "render" ]
0b24d1dc4554c13fe015596ec9c89f199bc1a50f
2,568
h
C
engine/gfx/gles2/include/aeon/gfx/gles2/gfx_gles2_device.h
aeon-engine/aeon-engine
9efcf83985110c36ebf0964bd4f76b261f2f6717
[ "MIT" ]
12
2017-02-25T17:14:15.000Z
2021-08-02T13:39:18.000Z
engine/gfx/gles2/include/aeon/gfx/gles2/gfx_gles2_device.h
aeon-engine/aeon-engine
9efcf83985110c36ebf0964bd4f76b261f2f6717
[ "MIT" ]
31
2017-02-23T06:59:44.000Z
2017-05-21T11:49:10.000Z
engine/gfx/gles2/include/aeon/gfx/gles2/gfx_gles2_device.h
aeon-engine/aeon-engine
9efcf83985110c36ebf0964bd4f76b261f2f6717
[ "MIT" ]
5
2017-05-02T05:34:53.000Z
2020-05-19T06:57:50.000Z
/* * Copyright (c) 2012-2018 Robin Degen * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #include <aeon/gfx/gfx_device.h> #include <aeon/gfx/gfx_render_target.h> #include <aeon/input/input_handler.h> #include <aeon/common/exception.h> #include <aeon/common/logger.h> namespace aeon { namespace gfx { namespace gles2 { DEFINE_EXCEPTION_OBJECT(gles2_initialized_exception, aeon::common::exception, "OpenGL ES 2.0 Device already initialized."); DEFINE_EXCEPTION_OBJECT(gles2_device_exception, aeon::common::exception, "OpenGL ES 2.0 Device Exception"); class gfx_gles2_device : public gfx::device { public: using render_targets = std::vector<std::shared_ptr<render_target>>; explicit gfx_gles2_device(io::io_interface &io); virtual ~gfx_gles2_device(); void __initialize_impl() override; void set_clear_color(const common::types::color &c) override; void set_viewport(render_target &rt, viewport &vp) override; void clear_buffer(int buffer_flag) override; auto create_mesh(std::shared_ptr<material> material) -> std::unique_ptr<mesh> override; void add_render_target(std::shared_ptr<render_target> target) override; auto render(float dt) -> bool override; void set_scissor(const common::types::rectangle<float> &scissor) const; private: void __create_managers(); void __setup_opengl() const; aeon::logger::logger logger_; render_targets render_targets_; }; } // namespace gles2 } // namespace gfx } // namespace aeon
32.506329
107
0.745717
[ "mesh", "render", "vector" ]
7151aad2ec480ed032d5a6127acff81059f5c268
77,610
c
C
libloragw/src/loragw_hal.c
glmoritz/lora_gateway
d5abd361332154330616d7124b0f0711ac0c143b
[ "MIT" ]
null
null
null
libloragw/src/loragw_hal.c
glmoritz/lora_gateway
d5abd361332154330616d7124b0f0711ac0c143b
[ "MIT" ]
null
null
null
libloragw/src/loragw_hal.c
glmoritz/lora_gateway
d5abd361332154330616d7124b0f0711ac0c143b
[ "MIT" ]
null
null
null
/* / _____) _ | | ( (____ _____ ____ _| |_ _____ ____| |__ \____ \| ___ | (_ _) ___ |/ ___) _ \ _____) ) ____| | | || |_| ____( (___| | | | (______/|_____)_|_|_| \__)_____)\____)_| |_| (C)2013 Semtech-Cycleo Description: LoRa concentrator Hardware Abstraction Layer License: Revised BSD License, see LICENSE.TXT file include in the project Maintainer: Sylvain Miermont */ /* -------------------------------------------------------------------------- */ /* --- DEPENDANCIES --------------------------------------------------------- */ #include <stdint.h> /* C99 types */ #include <stdbool.h> /* bool type */ #include <stdio.h> /* printf fprintf */ #include <string.h> /* memcpy */ #include <sys/time.h> #include <math.h> /* pow, cell */ #include <stdarg.h> #include "loragw_reg.h" #include "loragw_hal.h" #include "loragw_aux.h" #include "loragw_spi.h" #include "loragw_radio.h" #include "loragw_fpga.h" #include "loragw_lbt.h" #include "sx126x_labscim.h" /*---------------- LABSCIM -----------------*/ #include "labscim_linked_list.h" #include "labscim_protocol.h" #include "labscim_socket.h" #include "labscim_platform_socket.h" #include "labscim-lora-radio-protocol.h" #include "base64.h" #include "parson.h" #include "labscim_helper.h" extern uint64_t gLabscimTime; extern uint64_t gCommandLabscimLog; extern uint8_t mac_addr[]; /*LabSCim MQTT result collector*/ #include "MQTTAsync.h" void mqtt_onSubscribeFailure(void* context, MQTTAsync_failureData* response); void mqtt_onSubscribe(void* context, MQTTAsync_successData* response); void mqtt_onDisconnect(void* context, MQTTAsync_successData* response); void mqtt_onConnectFailure(void* context, MQTTAsync_failureData* response); void mqtt_connlost(void *context, char *cause); int mqtt_msgarrvd(void *context, char *topicName, int topicLen, MQTTAsync_message *message); void mqtt_onSend(void* context, MQTTAsync_successData* response); void mqtt_onConnect(void* context, MQTTAsync_successData* response); extern uint8_t gMQTTAddress[48]; extern uint8_t gMQTTTopic[128]; #define CLIENTID "LabSCim gateway" #define QOS 1 #define TIMEOUT 10000L uint64_t gPacketGeneratedSignal; uint64_t gPacketLatencySignal; uint64_t gPacketErrorSignal; pthread_mutex_t gEmitListMutex = PTHREAD_MUTEX_INITIALIZER; struct labscim_ll gEmitSignalList; volatile bool lib_exit_sig = false; /* 1 -> application terminates cleanly (shut down hardware, close open files, etc) */ volatile bool lib_quit_sig = false; /* -------------------------------------------------------------------------- */ /* --- PRIVATE MACROS ------------------------------------------------------- */ #define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) #if DEBUG_HAL == 1 #define DEBUG_MSG(str) fprintf(stderr, str) #define DEBUG_PRINTF(fmt, args...) fprintf(stderr, "%s:%d: " fmt, __FUNCTION__, __LINE__, args) #define DEBUG_ARRAY(a, b, c) \ for (a = 0; a < b; ++a) \ fprintf(stderr, "%x.", c[a]); \ fprintf(stderr, "end\n") #define CHECK_NULL(a) \ if (a == NULL) \ { \ fprintf(stderr, "%s:%d: ERROR: NULL POINTER AS ARGUMENT\n", __FUNCTION__, __LINE__); \ return LGW_HAL_ERROR; \ } #else #define DEBUG_MSG(str) #define DEBUG_PRINTF(fmt, args...) #define DEBUG_ARRAY(a, b, c) \ for (a = 0; a != 0;) \ { \ } #define CHECK_NULL(a) \ if (a == NULL) \ { \ return LGW_HAL_ERROR; \ } #endif #define IF_HZ_TO_REG(f) (f << 5) / 15625 #define SET_PPM_ON(bw, dr) (((bw == BW_125KHZ) && ((dr == DR_LORA_SF11) || (dr == DR_LORA_SF12))) || ((bw == BW_250KHZ) && (dr == DR_LORA_SF12))) #define TRACE() fprintf(stderr, "@ %s %d\n", __FUNCTION__, __LINE__); /* -------------------------------------------------------------------------- */ /* --- PRIVATE CONSTANTS & TYPES -------------------------------------------- */ #define MCU_ARB 0 #define MCU_AGC 1 #define MCU_ARB_FW_BYTE 8192 /* size of the firmware IN BYTES (= twice the number of 14b words) */ #define MCU_AGC_FW_BYTE 8192 /* size of the firmware IN BYTES (= twice the number of 14b words) */ #define FW_VERSION_ADDR 0x20 /* Address of firmware version in data memory */ #define FW_VERSION_CAL 2 /* Expected version of calibration firmware */ #define FW_VERSION_AGC 4 /* Expected version of AGC firmware */ #define FW_VERSION_ARB 1 /* Expected version of arbiter firmware */ #define TX_METADATA_NB 16 #define RX_METADATA_NB 16 #define AGC_CMD_WAIT 16 #define AGC_CMD_ABORT 17 #define MIN_LORA_PREAMBLE 6 #define STD_LORA_PREAMBLE 8 #define MIN_FSK_PREAMBLE 3 #define STD_FSK_PREAMBLE 5 #define RSSI_MULTI_BIAS -35 /* difference between "multi" modem RSSI offset and "stand-alone" modem RSSI offset */ #define RSSI_FSK_POLY_0 60 /* polynomiam coefficients to linearize FSK RSSI */ #define RSSI_FSK_POLY_1 1.5351 #define RSSI_FSK_POLY_2 0.003 /* Useful bandwidth of SX125x radios to consider depending on channel bandwidth */ /* Note: the below values come from lab measurements. For any question, please contact Semtech support */ #define LGW_RF_RX_BANDWIDTH_125KHZ 925000 /* for 125KHz channels */ #define LGW_RF_RX_BANDWIDTH_250KHZ 1000000 /* for 250KHz channels */ #define LGW_RF_RX_BANDWIDTH_500KHZ 1100000 /* for 500KHz channels */ #define TX_START_DELAY_DEFAULT 1497 /* Calibrated value for 500KHz BW and notch filter disabled */ /* constant arrays defining hardware capability */ const uint8_t ifmod_config[LGW_IF_CHAIN_NB] = LGW_IFMODEM_CONFIG; /* Version string, used to identify the library version/options once compiled */ const char lgw_version_string[] = "Version: " LIBLORAGW_VERSION ";"; /* -------------------------------------------------------------------------- */ /* --- PRIVATE VARIABLES ---------------------------------------------------- */ #include "arb_fw.var" /* external definition of the variable */ #include "agc_fw.var" /* external definition of the variable */ #include "cal_fw.var" /* external definition of the variable */ /* The following static variables are the configuration set that the user can modify using rxrf_setconf, rxif_setconf and txgain_setconf functions. The functions _start and _send then use that set to configure the hardware. Parameters validity and coherency is verified by the _setconf functions and the _start and _send functions assume they are valid. */ static bool lgw_is_started; static bool rf_enable[LGW_RF_CHAIN_NB]; static uint32_t rf_rx_freq[LGW_RF_CHAIN_NB]; /* absolute, in Hz */ static float rf_rssi_offset[LGW_RF_CHAIN_NB]; static bool rf_tx_enable[LGW_RF_CHAIN_NB]; static uint32_t rf_tx_notch_freq[LGW_RF_CHAIN_NB]; static enum lgw_radio_type_e rf_radio_type[LGW_RF_CHAIN_NB]; static bool if_enable[LGW_IF_CHAIN_NB]; static bool if_rf_chain[LGW_IF_CHAIN_NB]; /* for each IF, 0 -> radio A, 1 -> radio B */ static int32_t if_freq[LGW_IF_CHAIN_NB]; /* relative to radio frequency, +/- in Hz */ static uint8_t lora_multi_sfmask[LGW_MULTI_NB]; /* enables SF for LoRa 'multi' modems */ static uint8_t lora_rx_bw; /* bandwidth setting for LoRa standalone modem */ static uint8_t lora_rx_sf; /* spreading factor setting for LoRa standalone modem */ static bool lora_rx_ppm_offset; static uint8_t fsk_rx_bw; /* bandwidth setting of FSK modem */ static uint32_t fsk_rx_dr; /* FSK modem datarate in bauds */ static uint8_t fsk_sync_word_size = 3; /* default number of bytes for FSK sync word */ static uint64_t fsk_sync_word = 0xC194C1; /* default FSK sync word (ALIGNED RIGHT, MSbit first) */ static bool lorawan_public = false; static uint8_t rf_clkout = 0; static struct lgw_tx_gain_lut_s txgain_lut = { .size = 2, .lut[0] = { .dig_gain = 0, .pa_gain = 2, .dac_gain = 3, .mix_gain = 10, .rf_power = 14}, .lut[1] = {.dig_gain = 0, .pa_gain = 3, .dac_gain = 3, .mix_gain = 14, .rf_power = 27}}; /* TX I/Q imbalance coefficients for mixer gain = 8 to 15 */ static int8_t cal_offset_a_i[8]; /* TX I offset for radio A */ static int8_t cal_offset_a_q[8]; /* TX Q offset for radio A */ static int8_t cal_offset_b_i[8]; /* TX I offset for radio B */ static int8_t cal_offset_b_q[8]; /* TX Q offset for radio B */ /* -------------------------------------------------------------------------- */ /* --- PRIVATE FUNCTIONS DECLARATION ---------------------------------------- */ int load_firmware(uint8_t target, uint8_t *firmware, uint16_t size); void lgw_constant_adjust(void); int32_t lgw_sf_getval(int x); int32_t lgw_bw_getval(int x); /* -------------------------------------------------------------------------- */ /* --- PRIVATE FUNCTIONS DEFINITION ----------------------------------------- */ void EmitAndYield() { struct signal_emit* em; pthread_mutex_lock(&gEmitListMutex); em = labscim_ll_pop_front(&gEmitSignalList); while(em!=NULL) { LabscimSignalEmit(em->id,em->value); free(em); em = labscim_ll_pop_front(&gEmitSignalList); } pthread_mutex_unlock(&gEmitListMutex); protocol_yield(gNodeOutputBuffer); } /* size is the firmware size in bytes (not 14b words) */ int load_firmware(uint8_t target, uint8_t *firmware, uint16_t size) { int reg_rst; int reg_sel; uint8_t fw_check[8192]; int32_t dummy; /* check parameters */ CHECK_NULL(firmware); if (target == MCU_ARB) { if (size != MCU_ARB_FW_BYTE) { DEBUG_MSG("ERROR: NOT A VALID SIZE FOR MCU ARG FIRMWARE\n"); return -1; } reg_rst = LGW_MCU_RST_0; reg_sel = LGW_MCU_SELECT_MUX_0; } else if (target == MCU_AGC) { if (size != MCU_AGC_FW_BYTE) { DEBUG_MSG("ERROR: NOT A VALID SIZE FOR MCU AGC FIRMWARE\n"); return -1; } reg_rst = LGW_MCU_RST_1; reg_sel = LGW_MCU_SELECT_MUX_1; } else { DEBUG_MSG("ERROR: NOT A VALID TARGET FOR LOADING FIRMWARE\n"); return -1; } /* reset the targeted MCU */ lgw_reg_w(reg_rst, 1); /* set mux to access MCU program RAM and set address to 0 */ lgw_reg_w(reg_sel, 0); lgw_reg_w(LGW_MCU_PROM_ADDR, 0); /* write the program in one burst */ lgw_reg_wb(LGW_MCU_PROM_DATA, firmware, size); /* Read back firmware code for check */ lgw_reg_r(LGW_MCU_PROM_DATA, &dummy); /* bug workaround */ lgw_reg_rb(LGW_MCU_PROM_DATA, fw_check, size); if (memcmp(firmware, fw_check, size) != 0) { printf("ERROR: Failed to load fw %d\n", (int)target); return -1; } /* give back control of the MCU program ram to the MCU */ lgw_reg_w(reg_sel, 1); return 0; } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ void lgw_constant_adjust(void) { /* I/Q path setup */ // lgw_reg_w(LGW_RX_INVERT_IQ,0); /* default 0 */ // lgw_reg_w(LGW_MODEM_INVERT_IQ,1); /* default 1 */ // lgw_reg_w(LGW_CHIRP_INVERT_RX,1); /* default 1 */ // lgw_reg_w(LGW_RX_EDGE_SELECT,0); /* default 0 */ // lgw_reg_w(LGW_MBWSSF_MODEM_INVERT_IQ,0); /* default 0 */ // lgw_reg_w(LGW_DC_NOTCH_EN,1); /* default 1 */ lgw_reg_w(LGW_RSSI_BB_FILTER_ALPHA, 6); /* default 7 */ lgw_reg_w(LGW_RSSI_DEC_FILTER_ALPHA, 7); /* default 5 */ lgw_reg_w(LGW_RSSI_CHANN_FILTER_ALPHA, 7); /* default 8 */ lgw_reg_w(LGW_RSSI_BB_DEFAULT_VALUE, 23); /* default 32 */ lgw_reg_w(LGW_RSSI_CHANN_DEFAULT_VALUE, 85); /* default 100 */ lgw_reg_w(LGW_RSSI_DEC_DEFAULT_VALUE, 66); /* default 100 */ lgw_reg_w(LGW_DEC_GAIN_OFFSET, 7); /* default 8 */ lgw_reg_w(LGW_CHAN_GAIN_OFFSET, 6); /* default 7 */ /* Correlator setup */ // lgw_reg_w(LGW_CORR_DETECT_EN,126); /* default 126 */ // lgw_reg_w(LGW_CORR_NUM_SAME_PEAK,4); /* default 4 */ // lgw_reg_w(LGW_CORR_MAC_GAIN,5); /* default 5 */ // lgw_reg_w(LGW_CORR_SAME_PEAKS_OPTION_SF6,0); /* default 0 */ // lgw_reg_w(LGW_CORR_SAME_PEAKS_OPTION_SF7,1); /* default 1 */ // lgw_reg_w(LGW_CORR_SAME_PEAKS_OPTION_SF8,1); /* default 1 */ // lgw_reg_w(LGW_CORR_SAME_PEAKS_OPTION_SF9,1); /* default 1 */ // lgw_reg_w(LGW_CORR_SAME_PEAKS_OPTION_SF10,1); /* default 1 */ // lgw_reg_w(LGW_CORR_SAME_PEAKS_OPTION_SF11,1); /* default 1 */ // lgw_reg_w(LGW_CORR_SAME_PEAKS_OPTION_SF12,1); /* default 1 */ // lgw_reg_w(LGW_CORR_SIG_NOISE_RATIO_SF6,4); /* default 4 */ // lgw_reg_w(LGW_CORR_SIG_NOISE_RATIO_SF7,4); /* default 4 */ // lgw_reg_w(LGW_CORR_SIG_NOISE_RATIO_SF8,4); /* default 4 */ // lgw_reg_w(LGW_CORR_SIG_NOISE_RATIO_SF9,4); /* default 4 */ // lgw_reg_w(LGW_CORR_SIG_NOISE_RATIO_SF10,4); /* default 4 */ // lgw_reg_w(LGW_CORR_SIG_NOISE_RATIO_SF11,4); /* default 4 */ // lgw_reg_w(LGW_CORR_SIG_NOISE_RATIO_SF12,4); /* default 4 */ /* LoRa 'multi' demodulators setup */ // lgw_reg_w(LGW_PREAMBLE_SYMB1_NB,10); /* default 10 */ // lgw_reg_w(LGW_FREQ_TO_TIME_INVERT,29); /* default 29 */ // lgw_reg_w(LGW_FRAME_SYNCH_GAIN,1); /* default 1 */ // lgw_reg_w(LGW_SYNCH_DETECT_TH,1); /* default 1 */ // lgw_reg_w(LGW_ZERO_PAD,0); /* default 0 */ lgw_reg_w(LGW_SNR_AVG_CST, 3); /* default 2 */ if (lorawan_public) { /* LoRa network */ lgw_reg_w(LGW_FRAME_SYNCH_PEAK1_POS, 3); /* default 1 */ lgw_reg_w(LGW_FRAME_SYNCH_PEAK2_POS, 4); /* default 2 */ } else { /* private network */ lgw_reg_w(LGW_FRAME_SYNCH_PEAK1_POS, 1); /* default 1 */ lgw_reg_w(LGW_FRAME_SYNCH_PEAK2_POS, 2); /* default 2 */ } // lgw_reg_w(LGW_PREAMBLE_FINE_TIMING_GAIN,1); /* default 1 */ // lgw_reg_w(LGW_ONLY_CRC_EN,1); /* default 1 */ // lgw_reg_w(LGW_PAYLOAD_FINE_TIMING_GAIN,2); /* default 2 */ // lgw_reg_w(LGW_TRACKING_INTEGRAL,0); /* default 0 */ // lgw_reg_w(LGW_ADJUST_MODEM_START_OFFSET_RDX8,0); /* default 0 */ // lgw_reg_w(LGW_ADJUST_MODEM_START_OFFSET_SF12_RDX4,4092); /* default 4092 */ // lgw_reg_w(LGW_MAX_PAYLOAD_LEN,255); /* default 255 */ /* LoRa standalone 'MBWSSF' demodulator setup */ // lgw_reg_w(LGW_MBWSSF_PREAMBLE_SYMB1_NB,10); /* default 10 */ // lgw_reg_w(LGW_MBWSSF_FREQ_TO_TIME_INVERT,29); /* default 29 */ // lgw_reg_w(LGW_MBWSSF_FRAME_SYNCH_GAIN,1); /* default 1 */ // lgw_reg_w(LGW_MBWSSF_SYNCH_DETECT_TH,1); /* default 1 */ // lgw_reg_w(LGW_MBWSSF_ZERO_PAD,0); /* default 0 */ if (lorawan_public) { /* LoRa network */ lgw_reg_w(LGW_MBWSSF_FRAME_SYNCH_PEAK1_POS, 3); /* default 1 */ lgw_reg_w(LGW_MBWSSF_FRAME_SYNCH_PEAK2_POS, 4); /* default 2 */ } else { lgw_reg_w(LGW_MBWSSF_FRAME_SYNCH_PEAK1_POS, 1); /* default 1 */ lgw_reg_w(LGW_MBWSSF_FRAME_SYNCH_PEAK2_POS, 2); /* default 2 */ } // lgw_reg_w(LGW_MBWSSF_ONLY_CRC_EN,1); /* default 1 */ // lgw_reg_w(LGW_MBWSSF_PAYLOAD_FINE_TIMING_GAIN,2); /* default 2 */ // lgw_reg_w(LGW_MBWSSF_PREAMBLE_FINE_TIMING_GAIN,1); /* default 1 */ // lgw_reg_w(LGW_MBWSSF_TRACKING_INTEGRAL,0); /* default 0 */ // lgw_reg_w(LGW_MBWSSF_AGC_FREEZE_ON_DETECT,1); /* default 1 */ /* Improvement of reference clock frequency error tolerance */ lgw_reg_w(LGW_ADJUST_MODEM_START_OFFSET_RDX4, 1); /* default 0 */ lgw_reg_w(LGW_ADJUST_MODEM_START_OFFSET_SF12_RDX4, 4094); /* default 4092 */ lgw_reg_w(LGW_CORR_MAC_GAIN, 7); /* default 5 */ /* FSK datapath setup */ lgw_reg_w(LGW_FSK_RX_INVERT, 1); /* default 0 */ lgw_reg_w(LGW_FSK_MODEM_INVERT_IQ, 1); /* default 0 */ /* FSK demodulator setup */ lgw_reg_w(LGW_FSK_RSSI_LENGTH, 4); /* default 0 */ lgw_reg_w(LGW_FSK_PKT_MODE, 1); /* variable length, default 0 */ lgw_reg_w(LGW_FSK_CRC_EN, 1); /* default 0 */ lgw_reg_w(LGW_FSK_DCFREE_ENC, 2); /* default 0 */ // lgw_reg_w(LGW_FSK_CRC_IBM,0); /* default 0 */ lgw_reg_w(LGW_FSK_ERROR_OSR_TOL, 10); /* default 0 */ lgw_reg_w(LGW_FSK_PKT_LENGTH, 255); /* max packet length in variable length mode */ // lgw_reg_w(LGW_FSK_NODE_ADRS,0); /* default 0 */ // lgw_reg_w(LGW_FSK_BROADCAST,0); /* default 0 */ // lgw_reg_w(LGW_FSK_AUTO_AFC_ON,0); /* default 0 */ lgw_reg_w(LGW_FSK_PATTERN_TIMEOUT_CFG, 128); /* sync timeout (allow 8 bytes preamble + 8 bytes sync word, default 0 */ /* TX general parameters */ lgw_reg_w(LGW_TX_START_DELAY, TX_START_DELAY_DEFAULT); /* default 0 */ /* TX LoRa */ // lgw_reg_w(LGW_TX_MODE,0); /* default 0 */ lgw_reg_w(LGW_TX_SWAP_IQ, 1); /* "normal" polarity; default 0 */ if (lorawan_public) { /* LoRa network */ lgw_reg_w(LGW_TX_FRAME_SYNCH_PEAK1_POS, 3); /* default 1 */ lgw_reg_w(LGW_TX_FRAME_SYNCH_PEAK2_POS, 4); /* default 2 */ } else { /* Private network */ lgw_reg_w(LGW_TX_FRAME_SYNCH_PEAK1_POS, 1); /* default 1 */ lgw_reg_w(LGW_TX_FRAME_SYNCH_PEAK2_POS, 2); /* default 2 */ } /* TX FSK */ // lgw_reg_w(LGW_FSK_TX_GAUSSIAN_EN,1); /* default 1 */ lgw_reg_w(LGW_FSK_TX_GAUSSIAN_SELECT_BT, 2); /* Gaussian filter always on TX, default 0 */ // lgw_reg_w(LGW_FSK_TX_PATTERN_EN,1); /* default 1 */ // lgw_reg_w(LGW_FSK_TX_PREAMBLE_SEQ,0); /* default 0 */ return; } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ int32_t lgw_bw_getval(int x) { switch (x) { case BW_500KHZ: return 500000; case BW_250KHZ: return 250000; case BW_125KHZ: return 125000; case BW_62K5HZ: return 62500; case BW_31K2HZ: return 31200; case BW_15K6HZ: return 15600; case BW_7K8HZ: return 7800; default: return -1; } } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ int32_t lgw_sf_getval(int x) { switch (x) { case DR_LORA_SF7: return 7; case DR_LORA_SF8: return 8; case DR_LORA_SF9: return 9; case DR_LORA_SF10: return 10; case DR_LORA_SF11: return 11; case DR_LORA_SF12: return 12; default: return -1; } } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ uint16_t lgw_get_tx_start_delay(bool tx_notch_enable, uint8_t bw) { float notch_delay_us = 0.0; float bw_delay_us = 0.0; float tx_start_delay; /* Notch filtering performed by FPGA adds a constant delay (group delay) that we need to compensate */ if (tx_notch_enable) { notch_delay_us = lgw_fpga_get_tx_notch_delay(); } /* Calibrated delay brought by SX1301 depending on signal bandwidth */ switch (bw) { case BW_125KHZ: bw_delay_us = 1.5; break; case BW_500KHZ: /* Intended fall-through: it is the calibrated reference */ default: break; } tx_start_delay = (float)TX_START_DELAY_DEFAULT - bw_delay_us - notch_delay_us; printf("INFO: tx_start_delay=%u (%f) - (%u, bw_delay=%f, notch_delay=%f)\n", (uint16_t)tx_start_delay, tx_start_delay, TX_START_DELAY_DEFAULT, bw_delay_us, notch_delay_us); return (uint16_t)tx_start_delay; /* keep truncating instead of rounding: better behaviour measured */ } /* -------------------------------------------------------------------------- */ /* --- PUBLIC FUNCTIONS DEFINITION ------------------------------------------ */ int lgw_board_setconf(struct lgw_conf_board_s conf) { /* check if the concentrator is running */ if (lgw_is_started == true) { DEBUG_MSG("ERROR: CONCENTRATOR IS RUNNING, STOP IT BEFORE TOUCHING CONFIGURATION\n"); return LGW_HAL_ERROR; } /* set internal config according to parameters */ lorawan_public = conf.lorawan_public; rf_clkout = conf.clksrc; DEBUG_PRINTF("Note: board configuration; lorawan_public:%d, clksrc:%d\n", lorawan_public, rf_clkout); return LGW_HAL_SUCCESS; } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ int lgw_lbt_setconf(struct lgw_conf_lbt_s conf) { int x; /* check if the concentrator is running */ if (lgw_is_started == true) { DEBUG_MSG("ERROR: CONCENTRATOR IS RUNNING, STOP IT BEFORE TOUCHING CONFIGURATION\n"); return LGW_HAL_ERROR; } x = lbt_setconf(&conf); if (x != LGW_LBT_SUCCESS) { DEBUG_MSG("ERROR: Failed to configure concentrator for LBT\n"); return LGW_HAL_ERROR; } return LGW_HAL_SUCCESS; } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ int lgw_rxrf_setconf(uint8_t rf_chain, struct lgw_conf_rxrf_s conf) { /* check if the concentrator is running */ if (lgw_is_started == true) { DEBUG_MSG("ERROR: CONCENTRATOR IS RUNNING, STOP IT BEFORE TOUCHING CONFIGURATION\n"); return LGW_HAL_ERROR; } /* check input range (segfault prevention) */ if (rf_chain >= LGW_RF_CHAIN_NB) { DEBUG_MSG("ERROR: NOT A VALID RF_CHAIN NUMBER\n"); return LGW_HAL_ERROR; } /* check if radio type is supported */ if ((conf.type != LGW_RADIO_TYPE_SX1255) && (conf.type != LGW_RADIO_TYPE_SX1257)) { DEBUG_MSG("ERROR: NOT A VALID RADIO TYPE\n"); return LGW_HAL_ERROR; } /* check if TX notch filter frequency is supported */ if ((conf.tx_enable == true) && ((conf.tx_notch_freq < LGW_MIN_NOTCH_FREQ) || (conf.tx_notch_freq > LGW_MAX_NOTCH_FREQ))) { DEBUG_PRINTF("WARNING: NOT A VALID TX NOTCH FILTER FREQUENCY [%u..%u]Hz\n", LGW_MIN_NOTCH_FREQ, LGW_MAX_NOTCH_FREQ); conf.tx_notch_freq = 0; } /* set internal config according to parameters */ rf_enable[rf_chain] = conf.enable; rf_rx_freq[rf_chain] = conf.freq_hz; rf_rssi_offset[rf_chain] = conf.rssi_offset; rf_radio_type[rf_chain] = conf.type; rf_tx_enable[rf_chain] = conf.tx_enable; rf_tx_notch_freq[rf_chain] = conf.tx_notch_freq; DEBUG_PRINTF("Note: rf_chain %d configuration; en:%d freq:%d rssi_offset:%f radio_type:%d tx_enable:%d tx_notch_freq:%u\n", rf_chain, rf_enable[rf_chain], rf_rx_freq[rf_chain], rf_rssi_offset[rf_chain], rf_radio_type[rf_chain], rf_tx_enable[rf_chain], rf_tx_notch_freq[rf_chain]); return LGW_HAL_SUCCESS; } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ int lgw_rxif_setconf(uint8_t if_chain, struct lgw_conf_rxif_s conf) { int32_t bw_hz; uint32_t rf_rx_bandwidth; /* check if the concentrator is running */ if (lgw_is_started == true) { DEBUG_MSG("ERROR: CONCENTRATOR IS RUNNING, STOP IT BEFORE TOUCHING CONFIGURATION\n"); return LGW_HAL_ERROR; } /* check input range (segfault prevention) */ if (if_chain >= LGW_IF_CHAIN_NB) { DEBUG_PRINTF("ERROR: %d NOT A VALID IF_CHAIN NUMBER\n", if_chain); return LGW_HAL_ERROR; } /* if chain is disabled, don't care about most parameters */ if (conf.enable == false) { if_enable[if_chain] = false; if_freq[if_chain] = 0; DEBUG_PRINTF("Note: if_chain %d disabled\n", if_chain); return LGW_HAL_SUCCESS; } /* check 'general' parameters */ if (ifmod_config[if_chain] == IF_UNDEFINED) { DEBUG_PRINTF("ERROR: IF CHAIN %d NOT CONFIGURABLE\n", if_chain); } if (conf.rf_chain >= LGW_RF_CHAIN_NB) { DEBUG_MSG("ERROR: INVALID RF_CHAIN TO ASSOCIATE WITH A LORA_STD IF CHAIN\n"); return LGW_HAL_ERROR; } /* check if IF frequency is optimal based on channel and radio bandwidths */ switch (conf.bandwidth) { case BW_250KHZ: rf_rx_bandwidth = LGW_RF_RX_BANDWIDTH_250KHZ; /* radio bandwidth */ break; case BW_500KHZ: rf_rx_bandwidth = LGW_RF_RX_BANDWIDTH_500KHZ; /* radio bandwidth */ break; default: /* For 125KHz and below */ rf_rx_bandwidth = LGW_RF_RX_BANDWIDTH_125KHZ; /* radio bandwidth */ break; } bw_hz = lgw_bw_getval(conf.bandwidth); /* channel bandwidth */ if ((conf.freq_hz + ((bw_hz == -1) ? LGW_REF_BW : bw_hz) / 2) > ((int32_t)rf_rx_bandwidth / 2)) { DEBUG_PRINTF("ERROR: IF FREQUENCY %d TOO HIGH\n", conf.freq_hz); return LGW_HAL_ERROR; } else if ((conf.freq_hz - ((bw_hz == -1) ? LGW_REF_BW : bw_hz) / 2) < -((int32_t)rf_rx_bandwidth / 2)) { DEBUG_PRINTF("ERROR: IF FREQUENCY %d TOO LOW\n", conf.freq_hz); return LGW_HAL_ERROR; } /* check parameters according to the type of IF chain + modem, fill default if necessary, and commit configuration if everything is OK */ switch (ifmod_config[if_chain]) { case IF_LORA_STD: /* fill default parameters if needed */ if (conf.bandwidth == BW_UNDEFINED) { conf.bandwidth = BW_250KHZ; } if (conf.datarate == DR_UNDEFINED) { conf.datarate = DR_LORA_SF9; } /* check BW & DR */ if (!IS_LORA_BW(conf.bandwidth)) { DEBUG_MSG("ERROR: BANDWIDTH NOT SUPPORTED BY LORA_STD IF CHAIN\n"); return LGW_HAL_ERROR; } if (!IS_LORA_STD_DR(conf.datarate)) { DEBUG_MSG("ERROR: DATARATE NOT SUPPORTED BY LORA_STD IF CHAIN\n"); return LGW_HAL_ERROR; } /* set internal configuration */ if_enable[if_chain] = conf.enable; if_rf_chain[if_chain] = conf.rf_chain; if_freq[if_chain] = conf.freq_hz; lora_rx_bw = conf.bandwidth; lora_rx_sf = (uint8_t)(DR_LORA_MULTI & conf.datarate); /* filter SF out of the 7-12 range */ if (SET_PPM_ON(conf.bandwidth, conf.datarate)) { lora_rx_ppm_offset = true; } else { lora_rx_ppm_offset = false; } DEBUG_PRINTF("Note: LoRa 'std' if_chain %d configuration; en:%d freq:%d bw:%d dr:%d\n", if_chain, if_enable[if_chain], if_freq[if_chain], lora_rx_bw, lora_rx_sf); break; case IF_LORA_MULTI: /* fill default parameters if needed */ if (conf.bandwidth == BW_UNDEFINED) { conf.bandwidth = BW_125KHZ; } if (conf.datarate == DR_UNDEFINED) { conf.datarate = DR_LORA_MULTI; } /* check BW & DR */ if (conf.bandwidth != BW_125KHZ) { DEBUG_MSG("ERROR: BANDWIDTH NOT SUPPORTED BY LORA_MULTI IF CHAIN\n"); return LGW_HAL_ERROR; } if (!IS_LORA_MULTI_DR(conf.datarate)) { DEBUG_MSG("ERROR: DATARATE(S) NOT SUPPORTED BY LORA_MULTI IF CHAIN\n"); return LGW_HAL_ERROR; } /* set internal configuration */ if_enable[if_chain] = conf.enable; if_rf_chain[if_chain] = conf.rf_chain; if_freq[if_chain] = conf.freq_hz; lora_multi_sfmask[if_chain] = (uint8_t)(DR_LORA_MULTI & conf.datarate); /* filter SF out of the 7-12 range */ DEBUG_PRINTF("Note: LoRa 'multi' if_chain %d configuration; en:%d freq:%d SF_mask:0x%02x\n", if_chain, if_enable[if_chain], if_freq[if_chain], lora_multi_sfmask[if_chain]); break; case IF_FSK_STD: /* fill default parameters if needed */ if (conf.bandwidth == BW_UNDEFINED) { conf.bandwidth = BW_250KHZ; } if (conf.datarate == DR_UNDEFINED) { conf.datarate = 64000; /* default datarate */ } /* check BW & DR */ if (!IS_FSK_BW(conf.bandwidth)) { DEBUG_MSG("ERROR: BANDWIDTH NOT SUPPORTED BY FSK IF CHAIN\n"); return LGW_HAL_ERROR; } if (!IS_FSK_DR(conf.datarate)) { DEBUG_MSG("ERROR: DATARATE NOT SUPPORTED BY FSK IF CHAIN\n"); return LGW_HAL_ERROR; } /* set internal configuration */ if_enable[if_chain] = conf.enable; if_rf_chain[if_chain] = conf.rf_chain; if_freq[if_chain] = conf.freq_hz; fsk_rx_bw = conf.bandwidth; fsk_rx_dr = conf.datarate; if (conf.sync_word > 0) { fsk_sync_word_size = conf.sync_word_size; fsk_sync_word = conf.sync_word; } DEBUG_PRINTF("Note: FSK if_chain %d configuration; en:%d freq:%d bw:%d dr:%d (%d real dr) sync:0x%0*llX\n", if_chain, if_enable[if_chain], if_freq[if_chain], fsk_rx_bw, fsk_rx_dr, LGW_XTAL_FREQU / (LGW_XTAL_FREQU / fsk_rx_dr), 2 * fsk_sync_word_size, fsk_sync_word); break; default: DEBUG_PRINTF("ERROR: IF CHAIN %d TYPE NOT SUPPORTED\n", if_chain); return LGW_HAL_ERROR; } return LGW_HAL_SUCCESS; } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ int lgw_txgain_setconf(struct lgw_tx_gain_lut_s *conf) { int i; /* Check LUT size */ if ((conf->size < 1) || (conf->size > TX_GAIN_LUT_SIZE_MAX)) { DEBUG_PRINTF("ERROR: TX gain LUT must have at least one entry and maximum %d entries\n", TX_GAIN_LUT_SIZE_MAX); return LGW_HAL_ERROR; } txgain_lut.size = conf->size; for (i = 0; i < txgain_lut.size; i++) { /* Check gain range */ if (conf->lut[i].dig_gain > 3) { DEBUG_MSG("ERROR: TX gain LUT: SX1301 digital gain must be between 0 and 3\n"); return LGW_HAL_ERROR; } if (conf->lut[i].dac_gain != 3) { DEBUG_MSG("ERROR: TX gain LUT: SX1257 DAC gains != 3 are not supported\n"); return LGW_HAL_ERROR; } if (conf->lut[i].mix_gain > 15) { DEBUG_MSG("ERROR: TX gain LUT: SX1257 mixer gain must not exceed 15\n"); return LGW_HAL_ERROR; } else if (conf->lut[i].mix_gain < 8) { DEBUG_MSG("ERROR: TX gain LUT: SX1257 mixer gains < 8 are not supported\n"); return LGW_HAL_ERROR; } if (conf->lut[i].pa_gain > 3) { DEBUG_MSG("ERROR: TX gain LUT: External PA gain must not exceed 3\n"); return LGW_HAL_ERROR; } /* Set internal LUT */ txgain_lut.lut[i].dig_gain = conf->lut[i].dig_gain; txgain_lut.lut[i].dac_gain = conf->lut[i].dac_gain; txgain_lut.lut[i].mix_gain = conf->lut[i].mix_gain; txgain_lut.lut[i].pa_gain = conf->lut[i].pa_gain; txgain_lut.lut[i].rf_power = conf->lut[i].rf_power; } return LGW_HAL_SUCCESS; } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ pthread_t gThridIf; pthread_t gThridMQTT; pthread_mutex_t gWaitingCommandsMutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t gWaitingCommandsMore = PTHREAD_COND_INITIALIZER; struct labscim_ll gThreadCommands; struct labscim_ll gReceivedPackets; void lgw_labscim_get_command_queue(struct labscim_ll** Commands, pthread_mutex_t** Mutex, pthread_cond_t** More) { *Commands = &gCommands; *Mutex = &gWaitingCommandsMutex; *More = &gWaitingCommandsMore; } void lgw_labscim_sleep(uint64_t ms, uint64_t yield) { struct labscim_protocol_header* resp; uint8_t ctrue = 1; uint8_t waiting = 1; uint32_t cmd_seq; uint32_t seq_no = set_time_event(gNodeOutputBuffer, 0, ctrue, ms * 1000); if(yield) { EmitAndYield(); } pthread_mutex_lock(&gWaitingCommandsMutex); while (waiting) { if (gThreadCommands.count > 0) { struct labscim_ll_node *iter = gThreadCommands.head; while (iter != NULL) { if (((struct labscim_protocol_header *)iter->data)->request_sequence_number == seq_no) { free(labscim_ll_pop_node(&gThreadCommands, iter)); waiting = 0; break; } iter = iter->next; } } if(waiting) { pthread_cond_wait(&gWaitingCommandsMore, &gWaitingCommandsMutex); } } pthread_mutex_unlock(&gWaitingCommandsMutex); } /* -------------------------------------------------------------------------- */ /* --- THREAD 6: LabSCim - Send statistics back to Omnet++ --------- */ volatile MQTTAsync_token deliveredtoken; volatile uint32_t finished = 0; volatile uint32_t subscribed = 0; void mqtt_onConnect(void* context, MQTTAsync_successData* response) { MQTTAsync client = (MQTTAsync)context; MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer; int rc; printf("Successful connection\n"); printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n", gMQTTTopic, CLIENTID, QOS); opts.onSuccess = mqtt_onSubscribe; opts.onFailure = mqtt_onSubscribeFailure; opts.context = client; deliveredtoken = 0; finished = 0; subscribed = 0; if ((rc = MQTTAsync_subscribe(client, gMQTTTopic, QOS, &opts)) != MQTTASYNC_SUCCESS) { printf("Failed to start subscribe, return code %d\n", rc); exit(EXIT_FAILURE); } } void mqtt_onSend(void* context, MQTTAsync_successData* response) { printf("Message with token value %d delivery confirmed\n", response->token); } int mqtt_msgarrvd(void *context, char *topicName, int topicLen, MQTTAsync_message *message) { JSON_Value *root_val; JSON_Array *fields; JSON_Object *obj = NULL; JSON_Value *val = NULL; /* needed to detect the absence of some fields */ const char *str; /* pointer to sub-strings in the JSON data */ unsigned long long ull = 0; MQTTAsync client = (MQTTAsync)context; MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer; MQTTAsync_message pubmsg = MQTTAsync_message_initializer; int rc; /* try to parse JSON */ const char s[2] = "/"; const max_topics = 8; char *token[max_topics]; uint8_t payload[255]; uint8_t enc_payload[255]; uint8_t return_topic[255]; int8_t* data; uint32_t i; struct signal_emit* sig; struct timeval tv; gettimeofday(&tv, NULL); printf("%lu, Message arrived\n", tv.tv_sec*1000000+tv.tv_usec); printf(" topic: %s\n", topicName); printf(" message: %.*s\n", message->payloadlen, (char*)message->payload); /* walk through other tokens */ i = 0; token[0] = strtok(topicName, s); while(( token[i] != NULL )&&(i<max_topics)) { i++; token[i] = strtok(NULL, s); } if (strcmp("error", token[5])==0) { root_val = json_parse_string_with_comments(message->payload); if (root_val != NULL) { obj = json_value_get_object(root_val); data = json_object_get_string(obj, "error"); if (data != NULL) { sig = (struct signal_emit *)malloc(sizeof(struct signal_emit)); sig->id = gPacketErrorSignal; sig->value = data[0]; pthread_mutex_lock(&gEmitListMutex); labscim_ll_insert_at_back(&gEmitSignalList, (void *)sig); pthread_mutex_unlock(&gEmitListMutex); } } } if(strcmp("up",token[5])==0) { root_val = json_parse_string_with_comments(message->payload); if (root_val != NULL) { obj = json_value_get_object(root_val); data = json_object_get_string(obj, "data"); if (data != NULL) { b64_to_bin(data, strlen(data), payload, 255); uint64_t *values = (uint64_t *)payload; sig = (struct signal_emit*)malloc(sizeof(struct signal_emit)); sig->id = gPacketLatencySignal; sig->value = (gLabscimTime - values[1])/1e6; pthread_mutex_lock(&gEmitListMutex); labscim_ll_insert_at_back(&gEmitSignalList,(void*)sig); pthread_mutex_unlock(&gEmitListMutex); if (client != NULL) { values[2] = gLabscimTime; bin_to_b64(payload, sizeof(uint64_t) * 3, enc_payload, 255); sprintf(payload, "{\"confirmed\": false, \"fPort\": 2, \"data\": \"%s\"}", enc_payload); opts.onSuccess = mqtt_onSend; opts.context = client; pubmsg.payload = payload; pubmsg.payloadlen = strlen(payload); pubmsg.qos = QOS; pubmsg.retained = 0; deliveredtoken = 0; //application/[ApplicationID]/device/[DevEUI]/command/down // sprintf(return_topic, "application/%s/%s/%s/command/down", token[1], token[2], token[3]); // if ((rc = MQTTAsync_sendMessage(client, return_topic, &pubmsg, &opts)) != MQTTASYNC_SUCCESS) // { // printf("Failed to start sendMessage, return code %d\n", rc); // exit(EXIT_FAILURE); // } sig = (struct signal_emit *)malloc(sizeof(struct signal_emit)); sig->id = gPacketGeneratedSignal; sig->value = gLabscimTime / 1e6; pthread_mutex_lock(&gEmitListMutex); labscim_ll_insert_at_back(&gEmitSignalList, (void *)sig); pthread_mutex_unlock(&gEmitListMutex); } } } } MQTTAsync_freeMessage(&message); MQTTAsync_free(topicName); return 1; } void mqtt_connlost(void *context, char *cause) { MQTTAsync client = (MQTTAsync)context; MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer; int rc; printf("\nConnection lost\n"); printf(" cause: %s\n", cause); printf("Reconnecting\n"); conn_opts.keepAliveInterval = 10; conn_opts.cleansession = 1; if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS) { printf("Failed to start connect, return code %d\n", rc); finished = 1; } } void mqtt_onConnectFailure(void* context, MQTTAsync_failureData* response) { printf("Connect failed, rc %d\n", response ? response->code : 0); finished = 1; } void mqtt_onDisconnect(void* context, MQTTAsync_successData* response) { printf("Successful disconnection\n"); finished = 1; } void mqtt_onSubscribe(void* context, MQTTAsync_successData* response) { printf("Subscribe succeeded\n"); subscribed = 1; } void mqtt_onSubscribeFailure(void* context, MQTTAsync_failureData* response) { printf("Subscribe failed, rc %d\n", response ? response->code : 0); finished = 1; subscribed = 0; } void thread_labscim_mqtt(void) { MQTTAsync client; MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer; MQTTAsync_disconnectOptions disc_opts = MQTTAsync_disconnectOptions_initializer; MQTTAsync_token token; int rc; pthread_mutex_lock(&gEmitListMutex); labscim_ll_init_list(&gEmitSignalList); pthread_mutex_unlock(&gEmitListMutex); MQTTAsync_create(&client, gMQTTAddress, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL); MQTTAsync_setCallbacks(client, (void*)client, mqtt_connlost, mqtt_msgarrvd, NULL); conn_opts.keepAliveInterval = 10; conn_opts.cleansession = 1; conn_opts.onSuccess = mqtt_onConnect; conn_opts.onFailure = mqtt_onConnectFailure; conn_opts.context = client; if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS) { printf("Failed to start connect, return code %d\n", rc); exit(EXIT_FAILURE); } /* main loop task */ while (!lib_exit_sig && !lib_quit_sig) { wait_ms(500); if(finished) { mqtt_connlost(client, " reconnect"); } } disc_opts.onSuccess = mqtt_onDisconnect; if ((rc = MQTTAsync_disconnect(client, &disc_opts)) != MQTTASYNC_SUCCESS) { printf("Failed to start sendMessage, return code %d\n", rc); exit(EXIT_FAILURE); } destroy_exit: MQTTAsync_destroy(&client); exit: printf("\nINFO: End of validation thread\n"); return rc; } void labscim_interface_thread(void) { uint64_t ret; labscim_ll_init_list(&gReceivedPackets); while (!lib_exit_sig && !lib_quit_sig) { pthread_mutex_lock(gNodeInputBuffer->mutex.mutex); labscim_socket_handle_input(gNodeInputBuffer, &gCommands); while (gCommands.count == 0) { pthread_cond_wait(gNodeInputBuffer->mutex.more, gNodeInputBuffer->mutex.mutex); labscim_socket_handle_input(gNodeInputBuffer, &gCommands); } pthread_cond_signal(gNodeInputBuffer->mutex.less); pthread_mutex_unlock(gNodeInputBuffer->mutex.mutex); //socket_process_all_commands(); void *cmd; pthread_mutex_lock(&gWaitingCommandsMutex); uint64_t processed = 0; //process returned commands (if any) do { cmd = labscim_ll_pop_front(&gCommands); if (cmd != NULL) { struct labscim_protocol_header *hdr = (struct labscim_protocol_header *)cmd; ret = socket_process_command(hdr); processed++; } } while (cmd != NULL); if(gThreadCommands.count > 0) { pthread_cond_broadcast(&gWaitingCommandsMore); } else { EmitAndYield(); } pthread_mutex_unlock(&gWaitingCommandsMutex); } } void labscim_radio_incoming_response(struct labscim_radio_response *cmd) { switch (cmd->radio_response_code) { case LORA_RADIO_PACKET_RECEIVED: labscim_ll_insert_at_back(&gReceivedPackets,cmd); break; case LORA_RADIO_GET_STATE_RESULT: labscim_ll_insert_at_back(&gThreadCommands,cmd); break; default: free(cmd); break; } } void lgw_labscim_get_time(struct timeval *time) { //struct timespec utc; //lgw_gps_get(&utc, NULL, NULL, NULL); //time->tv_sec = utc.tv_sec; //time->tv_usec = utc.tv_nsec/1000; time->tv_sec = gLabscimTime/1000000; time->tv_usec = gLabscimTime%1000000; } int lgw_start(uint8_t* NodeName, uint32_t BufferSize, uint64_t* GatewayMac) { int i; if (lgw_is_started == true) { DEBUG_MSG("Note: LoRa concentrator already started, restarting it now\n"); } lib_exit_sig = false; lib_quit_sig = false; uint8_t *inbuffername, *outbuffername; inbuffername = (uint8_t *)malloc(sizeof(uint8_t) * strlen(NodeName) + 4); if (inbuffername == NULL) { perror("\nMalloc\n"); return; } memcpy(inbuffername + 1, NodeName, strlen(NodeName)); memcpy(inbuffername + strlen(NodeName) + 1, "in", 2); inbuffername[0] = '/'; inbuffername[strlen(NodeName) + 3] = 0; outbuffername = (uint8_t *)malloc(sizeof(uint8_t) * strlen(NodeName) + 5); if (outbuffername == NULL) { perror("\nMalloc\n"); return; } memcpy(outbuffername + 1, NodeName, strlen(NodeName)); memcpy(outbuffername + strlen(NodeName) + 1, "out", 3); outbuffername[0] = '/'; outbuffername[strlen(NodeName) + 4] = 0; gNodeOutputBuffer = (buffer_circ_t *)malloc(sizeof(buffer_circ_t)); if (gNodeOutputBuffer == NULL) { perror("\nMalloc\n"); return; } labscim_buffer_init(gNodeOutputBuffer, outbuffername, BufferSize, 0); labscim_ll_init_list(&gCommands); gNodeInputBuffer = (buffer_circ_t *)malloc(sizeof(buffer_circ_t)); if (gNodeInputBuffer == NULL) { perror("\nMalloc\n"); return; } labscim_buffer_init(gNodeInputBuffer, inbuffername, BufferSize, 1); node_is_ready(gNodeOutputBuffer); while (!gBootReceived) { //shared memory communication pthread_mutex_lock(gNodeInputBuffer->mutex.mutex); labscim_socket_handle_input(gNodeInputBuffer, &gCommands); while (gCommands.count == 0) { pthread_cond_wait(gNodeInputBuffer->mutex.more, gNodeInputBuffer->mutex.mutex); labscim_socket_handle_input(gNodeInputBuffer, &gCommands); } pthread_cond_signal(gNodeInputBuffer->mutex.less); pthread_mutex_unlock(gNodeInputBuffer->mutex.mutex); pthread_mutex_lock(&gWaitingCommandsMutex); void* cmd; do { cmd = labscim_ll_pop_front(&gCommands); if(cmd!=NULL) { labscim_ll_insert_at_back(&gThreadCommands, cmd); } } while (cmd!=NULL); pthread_mutex_unlock(&gWaitingCommandsMutex); lgw_process_all_commands(); } *GatewayMac = *((uint64_t*)mac_addr); i = pthread_create(&gThridIf, NULL, (void *(*)(void *))labscim_interface_thread, NULL); if (i != 0) { DEBUG_MSG("ERROR: [main] impossible to create library thread\n"); return LGW_HAL_ERROR; } lgw_is_started = true; if (gCommandLabscimLog) { gPacketGeneratedSignal = LabscimSignalRegister("LoRaDownstreamPacketGenerated"); gPacketLatencySignal = LabscimSignalRegister("LoRaUpstreamPacketLatency"); gPacketErrorSignal = LabscimSignalRegister("LoRaUpstreamPacketError"); i = pthread_create(&gThridMQTT, NULL, (void *(*)(void *))thread_labscim_mqtt, NULL); if (i != 0) { DEBUG_MSG("ERROR: [main] impossible to labscim mqtt thread\n"); exit(EXIT_FAILURE); } } // int64_t max_freq=rf_rx_freq[(uint8_t)if_rf_chain[0]] + if_freq[0]; int64_t min_freq=rf_rx_freq[(uint8_t)if_rf_chain[0]] + if_freq[0]; for (int64_t i = 0; i < LGW_IF_CHAIN_NB; i++) { if (rf_rx_freq[(uint8_t)if_rf_chain[i]] + if_freq[i] > max_freq) { max_freq = rf_rx_freq[(uint8_t)if_rf_chain[i]] + if_freq[i]; } if (rf_rx_freq[(uint8_t)if_rf_chain[i]] + if_freq[i] < min_freq) { min_freq = rf_rx_freq[(uint8_t)if_rf_chain[i]] + if_freq[i]; } } //set channel and bandwidth - this has no practical effect since gateway radio always receive all packets, but this way, spectrum plotter plots the right listening window struct lora_set_frequency frequency_setup; frequency_setup.Frequency_Hz = (max_freq-min_freq)/2 + min_freq; radio_command(gNodeOutputBuffer, LORA_RADIO_SET_CHANNEL, (void *)&frequency_setup, sizeof(struct lora_set_frequency)); struct lora_set_modulation_params mp; ModulationParams_t radio_setup; mp.TransmitPower_dBm = 27; mp.ModulationParams.Params.LoRa.CodingRate = 1; mp.ModulationParams.Params.LoRa.SpreadingFactor = 7; radio_setup.Params.LoRa.Bandwidth = (max_freq-min_freq)+200000; memcpy(&(mp.ModulationParams), &radio_setup, sizeof(ModulationParams_t)); radio_command(gNodeOutputBuffer, LORA_RADIO_SET_MODULATION_PARAMS, (void *)&mp, sizeof(struct lora_set_modulation_params)); //set gateway to RX mode struct lora_set_rx srx; srx.Timeout_us = ~((uint64_t)0); //continuous RX radio_command(gNodeOutputBuffer, LORA_RADIO_SET_RX, (void *)&srx, sizeof(struct lora_set_rx)); //then set modulation to lora struct lora_set_modem modem_type; uint32_t sequence_number; modem_type.Modem = 1;//(uint32_t)MODEM_LORA; sequence_number = radio_command(gNodeOutputBuffer, LORA_RADIO_SET_MODEM, (void *)&modem_type, sizeof(struct lora_set_modem)); return LGW_HAL_SUCCESS; } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ int lgw_stop(void) { lgw_soft_reset(); lgw_disconnect(); lib_exit_sig = true; lib_quit_sig = true; lgw_is_started = false; return LGW_HAL_SUCCESS; } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ int lgw_receive(uint8_t max_pkt, struct lgw_pkt_rx_s *pkt_data) { int nb_pkt_fetch; /* loop variable and return value */ struct lgw_pkt_rx_s *p; /* pointer to the current structure in the struct array */ uint8_t buff[255 + RX_METADATA_NB]; /* buffer to store the result of SPI read bursts */ unsigned sz; /* size of the payload, uses to address metadata */ int ifmod; /* type of if_chain/modem a packet was received by */ int stat_fifo; /* the packet status as indicated in the FIFO */ uint32_t raw_timestamp; /* timestamp when internal 'RX finished' was triggered */ uint32_t delay_x, delay_y, delay_z; /* temporary variable for timestamp offset calculation */ uint32_t timestamp_correction; /* correction to account for processing delay */ uint32_t sf, cr, bw_pow, crc_en, ppm; /* used to calculate timestamp correction */ struct labscim_radio_response *cmd; struct lora_radio_payload* payload; /* check if the concentrator is running */ if (lgw_is_started == false) { DEBUG_MSG("ERROR: CONCENTRATOR IS NOT RUNNING, START IT BEFORE RECEIVING\n"); return LGW_HAL_ERROR; } /* check input variables */ if ((max_pkt <= 0) || (max_pkt > LGW_PKT_FIFO_SIZE)) { DEBUG_PRINTF("ERROR: %d = INVALID MAX NUMBER OF PACKETS TO FETCH\n", max_pkt); return LGW_HAL_ERROR; } CHECK_NULL(pkt_data); /* Initialize buffer */ memset(buff, 0, sizeof buff); /* iterate max_pkt times at most */ nb_pkt_fetch = 0; while (nb_pkt_fetch < max_pkt) { /* point to the proper struct in the struct array */ p = &pkt_data[nb_pkt_fetch]; /* fetch all the RX FIFO data */ //lgw_reg_rb(LGW_RX_PACKET_DATA_FIFO_NUM_STORED, buff, 5); /* 0: number of packets available in RX data buffer */ /* 1,2: start address of the current packet in RX data buffer */ /* 3: CRC status of the current packet */ /* 4: size of the current packet payload in byte */ /* how many packets are in the RX buffer ? Break if zero */ //if (buff[0] == 0) //{ // break; /* no more packets to fetch, exit out of FOR loop */ //} /* sanity check */ //if (buff[0] > LGW_PKT_FIFO_SIZE) //{ // DEBUG_PRINTF("WARNING: %u = INVALID NUMBER OF PACKETS TO FETCH, ABORTING\n", buff[0]); // break; //} //DEBUG_PRINTF("FIFO content: %x %x %x %x %x\n", buff[0], buff[1], buff[2], buff[3], buff[4]); if(gReceivedPackets.count > 0) { cmd = (struct labscim_radio_response*)labscim_ll_pop_front(&gReceivedPackets); payload = (struct lora_radio_payload*)(cmd->radio_struct); p->size = payload->MessageSize_bytes; //sz = p->size; /* get payload + metadata */ //lgw_reg_rb(LGW_RX_DATA_BUF_DATA, buff, sz + RX_METADATA_NB); /* process metadata TODO: set the ifchain properly*/ p->if_chain = 0xFF; for (int64_t i = 0; i < LGW_IF_CHAIN_NB; i++) { if (rf_rx_freq[(uint8_t)if_rf_chain[i]] + if_freq[i] == payload->CenterFrequency_Hz) { p->if_chain = i; break; } } if (p->if_chain == 0xFF) { //this packet would not be received if our gateway model were more accurate - ignoring free(cmd); continue; } else { /* copy payload to result struct */ memcpy((void *)p->payload, (void *)payload->Message, payload->MessageSize_bytes); //if (p->if_chain >= LGW_IF_CHAIN_NB) //{ // DEBUG_PRINTF("WARNING: %u NOT A VALID IF_CHAIN NUMBER, ABORTING\n", p->if_chain); // break; //} ifmod = ifmod_config[p->if_chain]; //DEBUG_PRINTF("[%d %d]\n", p->if_chain, ifmod); p->rf_chain = (uint8_t)if_rf_chain[p->if_chain]; p->freq_hz = (uint32_t)((int32_t)rf_rx_freq[p->rf_chain] + if_freq[p->if_chain]); p->rssi = payload->RSSI_dbm-30; if (payload->CRCError) { p->status = STAT_CRC_BAD; } else { p->status = STAT_CRC_OK; } if ((ifmod == IF_LORA_MULTI) || (ifmod == IF_LORA_STD)) { DEBUG_MSG("Note: LoRa packet\n"); p->modulation = MOD_LORA; p->snr = payload->SNR_db; p->snr_min = payload->SNR_db; p->snr_max = payload->SNR_db; if (ifmod == IF_LORA_MULTI) { p->bandwidth = BW_125KHZ; /* fixed in hardware */ } else { p->bandwidth = lora_rx_bw; /* get the parameter from the config variable */ } switch (payload->LoRaSF) { case 7: p->datarate = DR_LORA_SF7; break; case 8: p->datarate = DR_LORA_SF8; break; case 9: p->datarate = DR_LORA_SF9; break; case 10: p->datarate = DR_LORA_SF10; break; case 11: p->datarate = DR_LORA_SF11; break; case 12: p->datarate = DR_LORA_SF12; break; default: p->datarate = DR_UNDEFINED; } switch (payload->LoRaCR) { case 1: p->coderate = CR_LORA_4_5; break; case 2: p->coderate = CR_LORA_4_6; break; case 3: p->coderate = CR_LORA_4_7; break; case 4: p->coderate = CR_LORA_4_8; break; default: p->coderate = CR_UNDEFINED; } } else if (ifmod == IF_FSK_STD) { DEBUG_MSG("Note: FSK packet\n"); p->modulation = MOD_FSK; p->snr = -128.0; p->snr_min = -128.0; p->snr_max = -128.0; p->bandwidth = fsk_rx_bw; p->datarate = fsk_rx_dr; p->coderate = CR_UNDEFINED; } else { DEBUG_MSG("ERROR: UNEXPECTED PACKET ORIGIN\n"); p->status = STAT_UNDEFINED; p->modulation = MOD_UNDEFINED; p->rssi = -128.0; p->snr = -128.0; p->snr_min = -128.0; p->snr_max = -128.0; p->bandwidth = BW_UNDEFINED; p->datarate = DR_UNDEFINED; p->coderate = CR_UNDEFINED; timestamp_correction = 0; } free(cmd); } p->count_us = payload->RX_timestamp_us; p->crc = 0; nb_pkt_fetch++; //TODO: p->crc = (uint16_t)buff[sz + 10] + ((uint16_t)buff[sz + 11] << 8); } else { break; } } return nb_pkt_fetch; } /* ~~ */ char gBuffer[256]; int labscim_printf(const char *fmt, ...) { #define LOGLEVEL_INFO (3) va_list args; va_start(args, fmt); int rc = vsnprintf(gBuffer, sizeof(gBuffer), fmt, args); if(rc>sizeof(gBuffer)) { strcpy(gBuffer+strlen(gBuffer)-4,"..."); rc = sizeof(gBuffer); } gBuffer[sizeof(gBuffer)-1]=0; printf("%s",gBuffer); print_message(gNodeOutputBuffer,LOGLEVEL_INFO,gBuffer,strlen(gBuffer)+1); va_end(args); return rc; } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ int lgw_send(struct lgw_pkt_tx_s pkt_data) { int i, x; struct lora_radio_payload* msg; uint8_t labscim_buff[FIXED_SIZEOF_LORA_RADIO_PAYLOAD + 256]; uint8_t buff[TX_METADATA_NB]; /* buffer to prepare the packet to send + metadata before SPI write burst */ uint32_t part_int = 0; /* integer part for PLL register value calculation */ uint32_t part_frac = 0; /* fractional part for PLL register value calculation */ uint16_t fsk_dr_div; /* divider to configure for target datarate */ int transfer_size = 0; /* data to transfer from host to TX databuffer */ int payload_offset = 0; /* start of the payload content in the databuffer */ uint8_t pow_index = 0; /* 4-bit value to set the firmware TX power */ uint8_t target_mix_gain = 0; /* used to select the proper I/Q offset correction */ uint32_t count_trig = 0; /* timestamp value in trigger mode corrected for TX start delay */ bool tx_allowed = false; uint16_t tx_start_delay; bool tx_notch_enable = false; msg = (struct lora_radio_payload*)labscim_buff; /* check if the concentrator is running */ if (lgw_is_started == false) { DEBUG_MSG("ERROR: CONCENTRATOR IS NOT RUNNING, START IT BEFORE SENDING\n"); return LGW_HAL_ERROR; } /* check input range (segfault prevention) */ if (pkt_data.rf_chain >= LGW_RF_CHAIN_NB) { DEBUG_MSG("ERROR: INVALID RF_CHAIN TO SEND PACKETS\n"); return LGW_HAL_ERROR; } /* check input variables */ if (rf_tx_enable[pkt_data.rf_chain] == false) { DEBUG_MSG("ERROR: SELECTED RF_CHAIN IS DISABLED FOR TX ON SELECTED BOARD\n"); return LGW_HAL_ERROR; } if (rf_enable[pkt_data.rf_chain] == false) { DEBUG_MSG("ERROR: SELECTED RF_CHAIN IS DISABLED\n"); return LGW_HAL_ERROR; } if (!IS_TX_MODE(pkt_data.tx_mode)) { DEBUG_MSG("ERROR: TX_MODE NOT SUPPORTED\n"); return LGW_HAL_ERROR; } if (pkt_data.modulation == MOD_LORA) { if (!IS_LORA_BW(pkt_data.bandwidth)) { DEBUG_MSG("ERROR: BANDWIDTH NOT SUPPORTED BY LORA TX\n"); return LGW_HAL_ERROR; } if (!IS_LORA_STD_DR(pkt_data.datarate)) { DEBUG_MSG("ERROR: DATARATE NOT SUPPORTED BY LORA TX\n"); return LGW_HAL_ERROR; } if (!IS_LORA_CR(pkt_data.coderate)) { DEBUG_MSG("ERROR: CODERATE NOT SUPPORTED BY LORA TX\n"); return LGW_HAL_ERROR; } if (pkt_data.size > 255) { DEBUG_MSG("ERROR: PAYLOAD LENGTH TOO BIG FOR LORA TX\n"); return LGW_HAL_ERROR; } } else if (pkt_data.modulation == MOD_FSK) { if ((pkt_data.f_dev < 1) || (pkt_data.f_dev > 200)) { DEBUG_MSG("ERROR: TX FREQUENCY DEVIATION OUT OF ACCEPTABLE RANGE\n"); return LGW_HAL_ERROR; } if (!IS_FSK_DR(pkt_data.datarate)) { DEBUG_MSG("ERROR: DATARATE NOT SUPPORTED BY FSK IF CHAIN\n"); return LGW_HAL_ERROR; } if (pkt_data.size > 255) { DEBUG_MSG("ERROR: PAYLOAD LENGTH TOO BIG FOR FSK TX\n"); return LGW_HAL_ERROR; } } else { DEBUG_MSG("ERROR: INVALID TX MODULATION\n"); return LGW_HAL_ERROR; } /* Enable notch filter for LoRa 125kHz */ if ((pkt_data.modulation == MOD_LORA) && (pkt_data.bandwidth == BW_125KHZ)) { tx_notch_enable = true; } /* Get the TX start delay to be applied for this TX */ tx_start_delay = lgw_get_tx_start_delay(tx_notch_enable, pkt_data.bandwidth); /* interpretation of TX power */ for (pow_index = txgain_lut.size - 1; pow_index > 0; pow_index--) { if (txgain_lut.lut[pow_index].rf_power <= pkt_data.rf_power) { break; } } msg->TxPower_dbm = pkt_data.rf_power; /* loading TX imbalance correction */ target_mix_gain = txgain_lut.lut[pow_index].mix_gain; // if (pkt_data.rf_chain == 0) // { /* use radio A calibration table */ // lgw_reg_w(LGW_TX_OFFSET_I, cal_offset_a_i[target_mix_gain - 8]); // lgw_reg_w(LGW_TX_OFFSET_Q, cal_offset_a_q[target_mix_gain - 8]); // } // else // { /* use radio B calibration table */ // lgw_reg_w(LGW_TX_OFFSET_I, cal_offset_b_i[target_mix_gain - 8]); // lgw_reg_w(LGW_TX_OFFSET_Q, cal_offset_b_q[target_mix_gain - 8]); // } /* Set digital gain from LUT */ //lgw_reg_w(LGW_TX_GAIN, txgain_lut.lut[pow_index].dig_gain); /* fixed metadata, useful payload and misc metadata compositing */ transfer_size = TX_METADATA_NB + pkt_data.size; /* */ payload_offset = TX_METADATA_NB; /* start the payload just after the metadata */ msg->MessageSize_bytes = pkt_data.size; /* metadata 0 to 2, TX PLL frequency */ switch (rf_radio_type[0]) { /* we assume that there is only one radio type on the board */ case LGW_RADIO_TYPE_SX1255: part_int = pkt_data.freq_hz / (SX125x_32MHz_FRAC << 7); /* integer part, gives the MSB */ part_frac = ((pkt_data.freq_hz % (SX125x_32MHz_FRAC << 7)) << 9) / SX125x_32MHz_FRAC; /* fractional part, gives middle part and LSB */ break; case LGW_RADIO_TYPE_SX1257: part_int = pkt_data.freq_hz / (SX125x_32MHz_FRAC << 8); /* integer part, gives the MSB */ part_frac = ((pkt_data.freq_hz % (SX125x_32MHz_FRAC << 8)) << 8) / SX125x_32MHz_FRAC; /* fractional part, gives middle part and LSB */ break; default: DEBUG_PRINTF("ERROR: UNEXPECTED VALUE %d FOR RADIO TYPE\n", rf_radio_type[0]); break; } buff[0] = 0xFF & part_int; /* Most Significant Byte */ buff[1] = 0xFF & (part_frac >> 8); /* middle byte */ buff[2] = 0xFF & part_frac; /* Least Significant Byte */ /* metadata 3 to 6, timestamp trigger value */ /* TX state machine must be triggered at (T0 - lgw_i_tx_start_delay_us) for packet to start being emitted at T0 */ if (pkt_data.tx_mode == TIMESTAMPED) { count_trig = pkt_data.count_us - (uint32_t)tx_start_delay; buff[3] = 0xFF & (count_trig >> 24); buff[4] = 0xFF & (count_trig >> 16); buff[5] = 0xFF & (count_trig >> 8); buff[6] = 0xFF & count_trig; } msg->Tx_Delay_us = pkt_data.count_us-gLabscimTime; msg->CenterFrequency_Hz = pkt_data.freq_hz; /* parameters depending on modulation */ if (pkt_data.modulation == MOD_LORA) { /* metadata 7, modulation type, radio chain selection and TX power */ buff[7] = (0x20 & (pkt_data.rf_chain << 5)) | (0x0F & pow_index); /* bit 4 is 0 -> LoRa modulation */ buff[8] = 0; /* metadata 8, not used */ /* metadata 9, CRC, LoRa CR & SF */ switch (pkt_data.datarate) { case DR_LORA_SF7: buff[9] = 7; break; case DR_LORA_SF8: buff[9] = 8; break; case DR_LORA_SF9: buff[9] = 9; break; case DR_LORA_SF10: buff[9] = 10; break; case DR_LORA_SF11: buff[9] = 11; break; case DR_LORA_SF12: buff[9] = 12; break; default: DEBUG_PRINTF("ERROR: UNEXPECTED VALUE %d IN SWITCH STATEMENT\n", pkt_data.datarate); } msg->LoRaSF = buff[9]; switch (pkt_data.coderate) { case CR_LORA_4_5: buff[9] |= 1 << 4; break; case CR_LORA_4_6: buff[9] |= 2 << 4; break; case CR_LORA_4_7: buff[9] |= 3 << 4; break; case CR_LORA_4_8: buff[9] |= 4 << 4; break; default: DEBUG_PRINTF("ERROR: UNEXPECTED VALUE %d IN SWITCH STATEMENT\n", pkt_data.coderate); } msg->LoRaCR = pkt_data.coderate; if (pkt_data.no_crc == false) { buff[9] |= 0x80; /* set 'CRC enable' bit */ } else { DEBUG_MSG("Info: packet will be sent without CRC\n"); } /* metadata 10, payload size */ buff[10] = pkt_data.size; /* metadata 11, implicit header, modulation bandwidth, PPM offset & polarity */ switch (pkt_data.bandwidth) { case BW_125KHZ: buff[11] = 0; msg->LoRaBandwidth_Hz = 125000; break; case BW_250KHZ: msg->LoRaBandwidth_Hz = 250000; buff[11] = 1; break; case BW_500KHZ: msg->LoRaBandwidth_Hz = 500000; buff[11] = 2; break; default: DEBUG_PRINTF("ERROR: UNEXPECTED VALUE %d IN SWITCH STATEMENT\n", pkt_data.bandwidth); } if (pkt_data.no_header == true) { buff[11] |= 0x04; /* set 'implicit header' bit */ } if (SET_PPM_ON(pkt_data.bandwidth, pkt_data.datarate)) { buff[11] |= 0x08; /* set 'PPM offset' bit at 1 */ } if (pkt_data.invert_pol == true) { buff[11] |= 0x10; /* set 'TX polarity' bit at 1 */ } /* metadata 12 & 13, LoRa preamble size */ if (pkt_data.preamble == 0) { /* if not explicit, use recommended LoRa preamble size */ pkt_data.preamble = STD_LORA_PREAMBLE; } else if (pkt_data.preamble < MIN_LORA_PREAMBLE) { /* enforce minimum preamble size */ pkt_data.preamble = MIN_LORA_PREAMBLE; DEBUG_MSG("Note: preamble length adjusted to respect minimum LoRa preamble size\n"); } buff[12] = 0xFF & (pkt_data.preamble >> 8); buff[13] = 0xFF & pkt_data.preamble; /* metadata 14 & 15, not used */ buff[14] = 0; buff[15] = 0; /* MSB of RF frequency is now used in AGC firmware to implement large/narrow filtering in SX1257/55 */ buff[0] &= 0x3F; /* Unset 2 MSBs of frequency code */ if (pkt_data.bandwidth == BW_500KHZ) { buff[0] |= 0x80; /* Set MSB bit to enlarge analog filter for 500kHz BW */ } /* Set MSB-1 bit to enable digital filter if required */ if (tx_notch_enable == true) { DEBUG_MSG("INFO: Enabling TX notch filter\n"); buff[0] |= 0x40; } } else if (pkt_data.modulation == MOD_FSK) { /* metadata 7, modulation type, radio chain selection and TX power */ buff[7] = (0x20 & (pkt_data.rf_chain << 5)) | 0x10 | (0x0F & pow_index); /* bit 4 is 1 -> FSK modulation */ buff[8] = 0; /* metadata 8, not used */ /* metadata 9, frequency deviation */ buff[9] = pkt_data.f_dev; /* metadata 10, payload size */ buff[10] = pkt_data.size; /* TODO: how to handle 255 bytes packets ?!? */ /* metadata 11, packet mode, CRC, encoding */ buff[11] = 0x01 | (pkt_data.no_crc ? 0 : 0x02) | (0x02 << 2); /* always in variable length packet mode, whitening, and CCITT CRC if CRC is not disabled */ /* metadata 12 & 13, FSK preamble size */ if (pkt_data.preamble == 0) { /* if not explicit, use LoRa MAC preamble size */ pkt_data.preamble = STD_FSK_PREAMBLE; } else if (pkt_data.preamble < MIN_FSK_PREAMBLE) { /* enforce minimum preamble size */ pkt_data.preamble = MIN_FSK_PREAMBLE; DEBUG_MSG("Note: preamble length adjusted to respect minimum FSK preamble size\n"); } buff[12] = 0xFF & (pkt_data.preamble >> 8); buff[13] = 0xFF & pkt_data.preamble; /* metadata 14 & 15, FSK baudrate */ fsk_dr_div = (uint16_t)((uint32_t)LGW_XTAL_FREQU / pkt_data.datarate); /* Ok for datarate between 500bps and 250kbps */ buff[14] = 0xFF & (fsk_dr_div >> 8); buff[15] = 0xFF & fsk_dr_div; /* insert payload size in the packet for variable mode */ buff[16] = pkt_data.size; ++transfer_size; /* one more byte to transfer to the TX modem */ ++payload_offset; /* start the payload with one more byte of offset */ /* MSB of RF frequency is now used in AGC firmware to implement large/narrow filtering in SX1257/55 */ buff[0] &= 0x7F; /* Always use narrow band for FSK (force MSB to 0) */ } else { DEBUG_MSG("ERROR: INVALID TX MODULATION..\n"); return LGW_HAL_ERROR; } /* Configure TX start delay based on TX notch filter */ //lgw_reg_w(LGW_TX_START_DELAY, tx_start_delay); /* copy payload from user struct to buffer containing metadata */ //memcpy((void *)(buff + payload_offset), (void *)(pkt_data.payload), pkt_data.size); /* reset TX command flags */ //lgw_abort_tx(); msg->SNR_db = -200.0; msg->RSSI_dbm = -200.0; msg->RX_timestamp_us = 0; /* put metadata + payload in the TX data buffer */ //lgw_reg_w(LGW_TX_DATA_BUF_ADDR, 0); //lgw_reg_wb(LGW_TX_DATA_BUF_DATA, buff, transfer_size); //DEBUG_ARRAY(i, transfer_size, buff); uint8_t code; x = lbt_is_channel_free(&pkt_data, tx_start_delay, &tx_allowed); //x = lgw_status(RX_STATUS , &code); if (x != LGW_HAL_SUCCESS) { DEBUG_MSG("ERROR: Failed to check channel availability for TX\n"); return LGW_HAL_ERROR; } if (tx_allowed == true) { // switch (pkt_data.tx_mode) // { // case IMMEDIATE: // lgw_reg_w(LGW_TX_TRIG_IMMEDIATE, 1); // break; // case TIMESTAMPED: // lgw_reg_w(LGW_TX_TRIG_DELAYED, 1); // break; // case ON_GPS: // lgw_reg_w(LGW_TX_TRIG_GPS, 1); // break; // default: // DEBUG_PRINTF("ERROR: UNEXPECTED VALUE %d IN SWITCH STATEMENT\n", pkt_data.tx_mode); // return LGW_HAL_ERROR; // } memcpy((void*)(msg->Message),(void *)(pkt_data.payload), pkt_data.size); radio_command(gNodeOutputBuffer, LORA_RADIO_SEND, (uint8_t *)msg, FIXED_SIZEOF_LORA_RADIO_PAYLOAD + msg->MessageSize_bytes); } else { DEBUG_MSG("ERROR: Cannot send packet, channel is busy (LBT)\n"); return LGW_LBT_ISSUE; } return LGW_HAL_SUCCESS; } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ int lgw_status(uint8_t select, uint8_t *code) { int32_t read_value; /* check input variables */ CHECK_NULL(code); uint32_t ChannelIsFree; struct labscim_radio_response *resp; struct lora_radio_status radio_status; uint32_t sequence_number; sequence_number = radio_command(gNodeOutputBuffer, LORA_RADIO_GET_STATE, (void *)&radio_status, sizeof(struct lora_radio_status)); resp = (struct labscim_radio_response *)lgw_wait_for_command(LABSCIM_RADIO_RESPONSE, sequence_number); if (select == TX_STATUS) { if (lgw_is_started == false) { *code = TX_OFF; } else { if (resp->radio_response_code == LORA_RADIO_GET_STATE_RESULT) { switch ((RadioMode)((struct lora_radio_status *)resp->radio_struct)->RadioMode) { case RADIO_MODE_TRANSMITTER: { *code = TX_EMITTING; break; } case RADIO_MODE_RECEIVER: case RADIO_MODE_OFF: case RADIO_MODE_SLEEP: { *code = TX_FREE; break; } default: //something very wrong while (1) ; } } else { //something very wrong happened while (1) ; } } } else if (select == RX_STATUS) { if (resp->radio_response_code == LORA_RADIO_GET_STATE_RESULT) { if (((RadioMode)((struct lora_radio_status *)resp->radio_struct)->RadioMode) == RADIO_MODE_RECEIVER) { if ((RadioMode)((struct lora_radio_status *)resp->radio_struct)->ChannelIsFree) { *code = RX_OFF; } else { *code = RX_ON; } } else { *code = RX_STATUS_UNKNOWN; } } else { //something very wrong happened while (1) ; } } else { DEBUG_MSG("ERROR: SELECTION INVALID, NO STATUS TO RETURN\n"); free(resp); return LGW_HAL_ERROR; } free(resp); return LGW_HAL_SUCCESS; } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ int lgw_abort_tx(void) { int i; i = lgw_reg_w(LGW_TX_TRIG_ALL, 0); if (i == LGW_REG_SUCCESS) return LGW_HAL_SUCCESS; else return LGW_HAL_ERROR; } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ int lgw_get_trigcnt(uint32_t *trig_cnt_us) { //int i; //int32_t val; //i = lgw_reg_r(LGW_TIMESTAMP, &val); //if (i == LGW_REG_SUCCESS) //{ *trig_cnt_us = (uint32_t)(gLabscimTime); return LGW_HAL_SUCCESS; //} //else //{ // return LGW_HAL_ERROR; //} } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ const char *lgw_version_info() { return lgw_version_string; } /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */ uint32_t lgw_time_on_air(struct lgw_pkt_tx_s *packet) { int32_t val; uint8_t SF, H, DE; uint16_t BW; uint32_t payloadSymbNb, Tpacket; double Tsym, Tpreamble, Tpayload, Tfsk; if (packet == NULL) { DEBUG_MSG("ERROR: Failed to compute time on air, wrong parameter\n"); return 0; } if (packet->modulation == MOD_LORA) { /* Get bandwidth */ val = lgw_bw_getval(packet->bandwidth); if (val != -1) { BW = (uint16_t)(val / 1E3); } else { DEBUG_PRINTF("ERROR: Cannot compute time on air for this packet, unsupported bandwidth (0x%02X)\n", packet->bandwidth); return 0; } /* Get datarate */ val = lgw_sf_getval(packet->datarate); if (val != -1) { SF = (uint8_t)val; } else { DEBUG_PRINTF("ERROR: Cannot compute time on air for this packet, unsupported datarate (0x%02X)\n", packet->datarate); return 0; } /* Duration of 1 symbol */ Tsym = pow(2, SF) / BW; /* Duration of preamble */ Tpreamble = ((double)(packet->preamble) + 4.25) * Tsym; /* Duration of payload */ H = (packet->no_header == false) ? 0 : 1; /* header is always enabled, except for beacons */ DE = (SF >= 11) ? 1 : 0; /* Low datarate optimization enabled for SF11 and SF12 */ payloadSymbNb = 8 + (ceil((double)(8 * packet->size - 4 * SF + 28 + 16 - 20 * H) / (double)(4 * (SF - 2 * DE))) * (packet->coderate + 4)); /* Explicitely cast to double to keep precision of the division */ Tpayload = payloadSymbNb * Tsym; /* Duration of packet */ Tpacket = Tpreamble + Tpayload; } else if (packet->modulation == MOD_FSK) { /* PREAMBLE + SYNC_WORD + PKT_LEN + PKT_PAYLOAD + CRC PREAMBLE: default 5 bytes SYNC_WORD: default 3 bytes PKT_LEN: 1 byte (variable length mode) PKT_PAYLOAD: x bytes CRC: 0 or 2 bytes */ Tfsk = (8 * (double)(packet->preamble + fsk_sync_word_size + 1 + packet->size + ((packet->no_crc == true) ? 0 : 2)) / (double)packet->datarate) * 1E3; /* Duration of packet */ Tpacket = (uint32_t)Tfsk + 1; /* add margin for rounding */ } else { Tpacket = 0; DEBUG_PRINTF("ERROR: Cannot compute time on air for this packet, unsupported modulation (0x%02X)\n", packet->modulation); } return Tpacket; } /* --- EOF ------------------------------------------------------------------ */
34.432121
284
0.579706
[ "model" ]
71524c44c5abef4a51c06f7c5b7e79495905f0de
11,131
h
C
Co-Simulation/Sumo/sumo-1.7.0/src/microsim/MSParkingArea.h
uruzahe/carla
940c2ab23cce1eda1ef66de35f66b42d40865fb1
[ "MIT" ]
null
null
null
Co-Simulation/Sumo/sumo-1.7.0/src/microsim/MSParkingArea.h
uruzahe/carla
940c2ab23cce1eda1ef66de35f66b42d40865fb1
[ "MIT" ]
null
null
null
Co-Simulation/Sumo/sumo-1.7.0/src/microsim/MSParkingArea.h
uruzahe/carla
940c2ab23cce1eda1ef66de35f66b42d40865fb1
[ "MIT" ]
null
null
null
/****************************************************************************/ // Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo // Copyright (C) 2015-2020 German Aerospace Center (DLR) and others. // This program and the accompanying materials are made available under the // terms of the Eclipse Public License 2.0 which is available at // https://www.eclipse.org/legal/epl-2.0/ // This Source Code may also be made available under the following Secondary // Licenses when the conditions for such availability set forth in the Eclipse // Public License 2.0 are satisfied: GNU General Public License, version 2 // or later which is available at // https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later /****************************************************************************/ /// @file MSParkingArea.h /// @author Mirco Sturari /// @date Tue, 19.01.2016 /// // A area where vehicles can park next to the road /****************************************************************************/ #pragma once #include <config.h> #include <vector> #include <algorithm> #include <map> #include <string> #include <utils/geom/PositionVector.h> #include <utils/common/Named.h> #include "MSStoppingPlace.h" // =========================================================================== // class declarations // =========================================================================== class MSLane; class SUMOVehicle; class MSTransportable; class Position; class Command; // =========================================================================== // class definitions // =========================================================================== /** * @class MSParkingArea * @brief A lane area vehicles can halt at * * The stop tracks the last free space a vehicle may halt at by being * informed about a vehicle's entering and depart. It keeps the information * about entered vehicles' begin and end position within an internal * container ("myEndPositions") and is so able to compute the last free space. * * Please note that using the last free space disallows vehicles to enter a * free space in between other vehicles. */ class MSParkingArea : public MSStoppingPlace { public: /** @brief Constructor * * @param[in] id The id of the stop * @param[in] net The net the stop belongs to * @param[in] lines Names of the lines that halt on this stop * @param[in] lane The lane the stop is placed on * @param[in] begPos Begin position of the stop on the lane * @param[in] endPos End position of the stop on the lane * @param[in] capacity Capacity of the stop * @param[in] width Width of the default lot rectangle * @param[in] length Length of the default lot rectangle * @param[in] angle Angle of the default lot rectangle */ MSParkingArea(const std::string& id, const std::vector<std::string>& lines, MSLane& lane, double begPos, double endPos, int capacity, double width, double length, double angle, const std::string& name, bool onRoad); /// @brief Destructor virtual ~MSParkingArea(); /** @brief Returns the area capacity * * @return The capacity */ int getCapacity() const; /// @brief whether vehicles park on the road bool parkOnRoad() const { return myOnRoad; } /** @brief Returns the area occupancy * * @return The occupancy computed as number of vehicles in myEndPositions * (reduced by 1 if at least one vehicle has finished parking but is blocked * from entering the road) */ int getOccupancy() const; /** @brief Returns the area occupancy * * @return The occupancy computed as number of vehicles in myEndPositions */ int getOccupancyIncludingBlocked() const; /** @brief Returns the area occupancy at the end of the last simulation step * * @return The occupancy computed as number of vehicles in myEndPositions */ int getLastStepOccupancy() const { return myLastStepOccupancy; } /** @brief Called if a vehicle enters this stop * * Stores the position of the entering vehicle in myEndPositions. * * Recomputes the free space using "computeLastFreePos" then. * * @param[in] what The vehicle that enters the parking area * @see computeLastFreePos */ void enter(SUMOVehicle* veh); /** @brief Called if a vehicle leaves this stop * * Removes the position of the vehicle from myEndPositions. * * Recomputes the free space using "computeLastFreePos" then. * * @param[in] what The vehicle that leaves the parking area * @see computeLastFreePos */ void leaveFrom(SUMOVehicle* what); /** @brief Called at the end of the time step * * Stores the current occupancy. * * @param[in] currentTime The current simulation time (unused) * @return Always 0 (the event is not rescheduled) */ SUMOTime updateOccupancy(SUMOTime currentTime); /** @brief Returns the last free position on this stop * * @return The last free position of this bus stop */ double getLastFreePos(const SUMOVehicle& forVehicle) const; /** @brief Returns the last free position on this stop including * reservatiosn from the current lane and time step * * @return The last free position of this bus stop */ double getLastFreePosWithReservation(SUMOTime t, const SUMOVehicle& forVehicle); /** @brief Returns the position of parked vehicle * * @return The position of parked vehicle */ Position getVehiclePosition(const SUMOVehicle& forVehicle) const; /** @brief Returns the insertion position of a parked vehicle * * @return The nsertion position of a parked vehicle along the lane */ double getInsertionPosition(const SUMOVehicle& forVehicle) const; /** @brief Returns the angle of parked vehicle * * @return The angle of parked vehicle */ double getVehicleAngle(const SUMOVehicle& forVehicle) const; /** @brief Return the angle of myLastFreeLot - the next parking lot * only expected to be called after we have established there is space in the parking area * * @return The angle of the lot in degrees */ int getLastFreeLotAngle() const; /** @brief Return the GUI angle of myLastFreeLot - the angle the GUI uses to rotate into the next parking lot * as above, only expected to be called after we have established there is space in the parking area * * @return The GUI angle, relative to the lane, in radians */ double getLastFreeLotGUIAngle() const; /** @brief Return the manoeuver angle of the lot where the vehicle is parked * * @return The manoeuver angle in degrees */ int getManoeuverAngle(const SUMOVehicle& forVehicle) const; /** @brief Return the GUI angle of the lot where the vehicle is parked * * @return The GUI angle, relative to the lane, in radians */ double getGUIAngle(const SUMOVehicle& forVehicle) const; /** @brief Add a lot entry to parking area * * @param[in] x X position of the lot center * @param[in] y Y position of the lot center * @param[in] z Z position of the lot center * @param[in] width Width of the lot rectangle * @param[in] length Length of the lot rectangle * @param[in] angle Angle of the lot rectangle * @return Whether the lot entry could be added */ virtual void addLotEntry(double x, double y, double z, double width, double length, double angle); /** @brief Returns the lot rectangle width * * @return The width */ double getWidth() const; /** @brief Returns the lot rectangle length * * @return The length */ double getLength() const; /** @brief Returns the lot rectangle angle * * @return The angle */ double getAngle() const; /// @brief update state so that vehicles wishing to enter cooperate with exiting vehicles void notifyEgressBlocked(); void setNumAlternatives(int alternatives) { myNumAlternatives = MAX2(myNumAlternatives, alternatives); } int getNumAlternatives() const { return myNumAlternatives; } protected: /** @struct LotSpaceDefinition * @brief Representation of a single lot space */ struct LotSpaceDefinition { /// @brief the running index int index; /// @brief The last parked vehicle or 0 SUMOVehicle* vehicle; /// @brief The position of the vehicle when parking in this space Position myPosition; /// @brief The rotation double myRotation; /// @brief The width double myWidth; /// @brief The length double myLength; /// @brief The position along the lane that the vehicle needs to reach for entering this lot double myEndPos; ///@brief The angle between lane and lot through which a vehicle must manoeuver to enter the lot double myManoeuverAngle; ///@brief Whether the lot is on the LHS of the lane relative to the lane direction bool mySideIsLHS; }; /** @brief Computes the last free position on this stop * * The last free position is the one, the last vehicle ends at. * It is stored in myLastFreePos. If no vehicle halts, the last free * position gets the value of myEndPos. */ void computeLastFreePos(); /// @brief Last free lot number (-1 no free lot) int myLastFreeLot; /// @brief Stop area capacity int myCapacity; /// @brief Whether vehicles stay on the road bool myOnRoad; /// @brief The default width of each parking space double myWidth; /// @brief The default length of each parking space double myLength; /// @brief The default angle of each parking space double myAngle; /// @brief All the spaces in this parking area std::vector<LotSpaceDefinition> mySpaceOccupancies; /// @brief The roadside shape of this parkingArea PositionVector myShape; /// @brief whether a vehicle wants to exit but is blocked bool myEgressBlocked; /// @brief track parking reservations from the lane for the current time step SUMOTime myReservationTime; int myReservations; double myReservationMaxLength; /// @brief the number of alternative parkingAreas that are assigned to parkingAreaRerouter int myNumAlternatives; /// @brief Changes to the occupancy in the current time step int myLastStepOccupancy; /// @brief Event for updating the occupancy Command* myUpdateEvent; private: /// @brief Invalidated copy constructor. MSParkingArea(const MSParkingArea&); /// @brief Invalidated assignment operator. MSParkingArea& operator=(const MSParkingArea&); };
32.357558
113
0.638038
[ "shape", "vector" ]
71572dd9396380800d275d24bd18e18a89884fa1
12,449
c
C
external/bsd/kyua-testers/dist/atf_list.c
calmsacibis995/minix
dfba95598f553b6560131d35a76658f1f8c9cf38
[ "Unlicense" ]
null
null
null
external/bsd/kyua-testers/dist/atf_list.c
calmsacibis995/minix
dfba95598f553b6560131d35a76658f1f8c9cf38
[ "Unlicense" ]
null
null
null
external/bsd/kyua-testers/dist/atf_list.c
calmsacibis995/minix
dfba95598f553b6560131d35a76658f1f8c9cf38
[ "Unlicense" ]
null
null
null
// Copyright 2012 Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Google Inc. nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "atf_list.h" #include <assert.h> #include <errno.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "error.h" /// Expected header in the test program list. #define TP_LIST_HEADER "Content-Type: application/X-atf-tp; version=\"1\"" /// Same as fgets, but removes any trailing newline from the output string. /// /// \param [out] str Pointer to the output buffer. /// \param size Length of the output buffer. /// \param [in,out] stream File from which to read the line. /// /// \return A pointer to the output buffer if successful; otherwise NULL. static char* fgets_no_newline(char* str, int size, FILE* stream) { char* result = fgets(str, size, stream); if (result != NULL) { const size_t length = strlen(str); if (length > 0 && str[length - 1] == '\n') str[length - 1] = '\0'; } return result; } /// Generates an error for the case where fgets() returns NULL. /// /// \param input Stream on which fgets() returned an error. /// \param message Error message. /// /// \return An error object with the error message and any relevant details. static kyua_error_t fgets_error(FILE* input, const char* message) { if (feof(input)) { return kyua_generic_error_new("%s: unexpected EOF", message); } else { assert(ferror(input)); return kyua_libc_error_new(errno, "%s", message); } } /// Reads the header of the test cases list. /// /// The header does not carry any useful information, so all this function does /// is ensure the header is valid. /// /// \param [in,out] input File from which to read the header. /// /// \return OK if the header is valid; an error if it is not. static kyua_error_t parse_header(FILE* input) { char line[80]; // It's ugly to have a limit, but it's easier this way. if (fgets_no_newline(line, sizeof(line), input) == NULL) return fgets_error(input, "fgets failed to read test cases list " "header"); if (strcmp(line, TP_LIST_HEADER) != 0) return kyua_generic_error_new("Invalid test cases list header '%s'", line); if (fgets_no_newline(line, sizeof(line), input) == NULL) return fgets_error(input, "fgets failed to read test cases list " "header"); if (strcmp(line, "") != 0) return kyua_generic_error_new("Incomplete test cases list header"); return kyua_error_ok(); } /// Looks for the first occurrence of any of the specified delimiters. /// /// \param container String in which to look for the delimiters. /// \param delimiters List of delimiters to look for. /// /// \return A pointer to the first occurrence of the delimiter, or NULL if /// there is none. static char* find_first_of(char* container, const char* delimiters) { char* ptr = container; while (*ptr != '\0') { if (strchr(delimiters, *ptr) != NULL) return ptr; ++ptr; } return NULL; } /// Prints a string within single quotes, with proper escaping. /// /// \param [in,out] line The line to be printed. This is a non-const pointer /// and the input string is modified to simplify tokenization. /// \param [in,out] output Buffer onto which to write the quoted string. /// \param surrounding If true, surround the printed value with single quotes. static void print_quoted(char* line, FILE* output, const bool surrounding) { if (surrounding) fprintf(output, "'"); char* quoteptr; while ((quoteptr = find_first_of(line, "\'\\")) != NULL) { const char quote = *quoteptr; *quoteptr = '\0'; fprintf(output, "%s\\%c", line, quote); line = quoteptr + 1; } if (surrounding) fprintf(output, "%s'", line); else fprintf(output, "%s", line); } /// Parses a property from the test cases list. /// /// The property is of the form "name: value", where the value extends to the /// end of the line without quotations. /// /// \param [in,out] line The line to be parsed. This is a non-const pointer /// and the input string is modified to simplify tokenization. /// \param [out] key The name of the property if the parsing succeeds. This /// is a pointer within the input line. /// \param [out] value The value of the property if the parsing succeeds. This /// is a pointer within the input line. /// /// \return OK if the line contains a valid property; an error otherwise. /// In case of success, both key and value are updated. static kyua_error_t parse_property(char* line, char** const key, char** const value) { char* delim = strstr(line, ": "); if (delim == NULL) return kyua_generic_error_new("Invalid property '%s'", line); *delim = '\0'; *(delim + 1) = '\0'; *key = line; *value = delim + 2; return kyua_error_ok(); } /// Static value to denote an error in the return of rewrite_property; static const char* rewrite_error = "ERROR"; /// Converts the name of an ATF property to a Kyua generic property. /// /// \param name The name of the ATF property to process. /// /// \return The name of the corresponding Kyua property if the input property is /// valid; NULL if the property has a custom name that has to be handled in the /// parent; or rewrite_error if the property is invalid. If this returns /// rewrite_error, it's OK to pointer-compare the return value to the static /// symbol for equality. static const char* rewrite_property(const char* name) { if (strcmp(name, "descr") == 0) return "description"; else if (strcmp(name, "has.cleanup") == 0) return "has_cleanup"; else if (strcmp(name, "require.arch") == 0) return "allowed_architectures"; else if (strcmp(name, "require.config") == 0) return "required_configs"; else if (strcmp(name, "require.files") == 0) return "required_files"; else if (strcmp(name, "require.machine") == 0) return "allowed_platforms"; else if (strcmp(name, "require.memory") == 0) return "required_memory"; else if (strcmp(name, "require.progs") == 0) return "required_programs"; else if (strcmp(name, "require.user") == 0) return "required_user"; else if (strcmp(name, "timeout") == 0) return "timeout"; else if (strlen(name) > 2 && name[0] == 'X' && name[1] == '-') return NULL; else return rewrite_error; } /// Parses a single test case and writes it to the output. /// /// This has to be called after the ident property has been read, and takes care /// of reading the rest of the test case and printing the parsed result. /// /// Be aware that this consumes the newline after the test case. The caller /// should not look for it. /// /// \param [in,out] input File from which to read the header. /// \param [in,out] output File to which to write the parsed test case. /// \param [in,out] name The name of the test case. This is a non-const pointer /// and the input string is modified to simplify tokenization. /// /// \return OK if the parsing succeeds; an error otherwise. static kyua_error_t parse_test_case(FILE* input, FILE* output, char* name) { kyua_error_t error; char line[1024]; // It's ugly to have a limit, but it's easier this way. fprintf(output, "test_case{name="); print_quoted(name, output, true); error = kyua_error_ok(); while (!kyua_error_is_set(error) && fgets_no_newline(line, sizeof(line), input) != NULL && strcmp(line, "") != 0) { char* key; char* value; #if defined(__minix) /* LSC: -Werror=maybe-uninitialized, with -O3 */ key = value = NULL; #endif /* defined(__minix) */ error = parse_property(line, &key, &value); if (!kyua_error_is_set(error)) { const char* out_key = rewrite_property(key); if (out_key == rewrite_error) { error = kyua_generic_error_new("Unknown ATF property %s", key); } else if (out_key == NULL) { fprintf(output, ", ['custom."); print_quoted(key, output, false); fprintf(output, "']="); print_quoted(value, output, true); } else { fprintf(output, ", %s=", out_key); print_quoted(value, output, true); } } } fprintf(output, "}\n"); return error; } /// Rewrites the test cases list from the input to the output. /// /// \param [in,out] input Stream from which to read the test program's test /// cases list. The current location must be after the header and at the /// first identifier (if any). /// \param [out] output Stream to which to write the generic list. /// /// \return An error object. static kyua_error_t parse_tests(FILE* input, FILE* output) { char line[512]; // It's ugly to have a limit, but it's easier this way. if (fgets_no_newline(line, sizeof(line), input) == NULL) { return fgets_error(input, "Empty test cases list"); } kyua_error_t error; do { char* key; char* value; #if defined(__minix) /* LSC: -Werror=maybe-uninitialized, with -O3 */ key = value = NULL; #endif /* defined(__minix) */ error = parse_property(line, &key, &value); if (kyua_error_is_set(error)) break; if (strcmp(key, "ident") == 0) { error = parse_test_case(input, output, value); } else { error = kyua_generic_error_new("Expected ident property, got %s", key); } } while (!kyua_error_is_set(error) && fgets_no_newline(line, sizeof(line), input) != NULL); if (!kyua_error_is_set(error)) { if (ferror(input)) error = kyua_libc_error_new(errno, "fgets failed"); else assert(feof(input)); } return error; } /// Reads an ATF test cases list and prints a Kyua definition. /// /// \param fd A file descriptor from which to read the test cases list of a test /// program. Should be connected to the stdout of the latter. This /// function grabs ownership of the descriptor and releases it in all cases. /// \param [in,out] output File to which to write the Kyua definition. /// /// \return OK if the parsing succeeds; an error otherwise. Note that, if there /// is an error, the output may not be consistent and should not be used. kyua_error_t atf_list_parse(const int fd, FILE* output) { kyua_error_t error; FILE* input = fdopen(fd, "r"); if (input == NULL) { error = kyua_libc_error_new(errno, "fdopen(%d) failed", fd); close(fd); } else { error = parse_header(input); if (!kyua_error_is_set(error)) { error = parse_tests(input, output); } fclose(input); } return error; }
34.200549
80
0.646478
[ "object" ]
7158e4886e9d33352df24fc5ef6531596179c94a
10,126
h
C
src/ObjVLink.h
2kranki/libCmn
4f9db4c9c8e2dff64e1c741dc1c11e9f3b5d07ce
[ "Unlicense" ]
2
2017-03-23T15:23:56.000Z
2021-03-04T09:54:54.000Z
src/ObjVLink.h
2kranki/libCmn
4f9db4c9c8e2dff64e1c741dc1c11e9f3b5d07ce
[ "Unlicense" ]
null
null
null
src/ObjVLink.h
2kranki/libCmn
4f9db4c9c8e2dff64e1c741dc1c11e9f3b5d07ce
[ "Unlicense" ]
null
null
null
// vi:nu:et:sts=4 ts=4 sw=4 //**************************************************************** // Object with a Variable Number of Integer Links (ObjVLink) //**************************************************************** /* * Program * Object with a Variable Number of Integer Links (ObjVLink) * Purpose * This object provides for adding a variable number of * external integer links to an object. There are also a * fixed number of links such as parent, left and right. * * Remarks * 1. This object uses signed indices so that the sign can be * used for something such as back pointers. It is assumed * that an index must be non-zero. * 2. The fixed indices can be accessed directly through their * property methods or via get/set using OBJVLINK_INDEX * indices. * * History * 01/14/2020 Generated */ /* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For more information, please refer to <http://unlicense.org/> */ #include <cmn_defs.h> #include <AStr.h> #ifndef OBJVLINK_H #define OBJVLINK_H #define OBJVLINK_JSON_SUPPORT 1 //#define OBJVLINK_SINGLETON 1 #ifdef __cplusplus extern "C" { #endif //**************************************************************** //* * * * * * * * * * * * Data Definitions * * * * * * * * * * * //**************************************************************** typedef struct ObjVLink_data_s OBJVLINK_DATA; // Inherits from OBJ typedef struct ObjVLink_class_data_s OBJVLINK_CLASS_DATA; // Inherits from OBJ typedef struct ObjVLink_vtbl_s { OBJ_IUNKNOWN iVtbl; // Inherited Vtbl. // Put other methods below this as pointers and add their // method names to the vtbl definition in ObjVLink_object.c. // Properties: // Methods: //bool (*pIsEnabled)(OBJVLINK_DATA *); } OBJVLINK_VTBL; typedef struct ObjVLink_class_vtbl_s { OBJ_IUNKNOWN iVtbl; // Inherited Vtbl. // Put other methods below this as pointers and add their // method names to the vtbl definition in ObjVLink_object.c. // Properties: // Methods: //bool (*pIsEnabled)(OBJVLINK_DATA *); } OBJVLINK_CLASS_VTBL; // Index values used the Get/Set which will access the fixed indices // as well as those in the optional array. typedef enum ObjVLink_Index_e { OBJVLINK_INDEX_UNKNOWN=0, // Not Allowed OBJVLINK_INDEX_INDEX, OBJVLINK_INDEX_LEFT, OBJVLINK_INDEX_MIDDLE, OBJVLINK_INDEX_MISC, OBJVLINK_INDEX_PARENT, OBJVLINK_INDEX_RIGHT, OBJVLINK_INDEX_HIGH // Beginning value to access the array. } OBJVLINK_INDEX; /**************************************************************** * * * * * * * * * * * Routine Definitions * * * * * * * * * * * ****************************************************************/ //--------------------------------------------------------------- // *** Class Methods *** //--------------------------------------------------------------- #ifdef OBJVLINK_SINGLETON OBJVLINK_DATA * ObjVLink_Shared ( void ); void ObjVLink_SharedReset ( void ); #endif /*! Allocate a new Object and partially initialize. Also, this sets an indicator that the object was alloc'd which is tested when the object is released. @return pointer to ObjVLink object if successful, otherwise OBJ_NIL. */ OBJVLINK_DATA * ObjVLink_Alloc ( void ); OBJ_ID ObjVLink_Class ( void ); OBJVLINK_DATA * ObjVLink_New ( void ); #ifdef OBJVLINK_JSON_SUPPORT OBJVLINK_DATA * ObjVLink_NewFromJsonString( ASTR_DATA *pString ); OBJVLINK_DATA * ObjVLink_NewFromJsonStringA( const char *pStringA ); #endif //--------------------------------------------------------------- // *** Properties *** //--------------------------------------------------------------- int32_t ObjVLink_getIndex ( OBJVLINK_DATA *this ); bool ObjVLink_setIndex ( OBJVLINK_DATA *this, int32_t value ); int32_t ObjVLink_getLeft ( OBJVLINK_DATA *this ); bool ObjVLink_setLeft ( OBJVLINK_DATA *this, int32_t value ); int32_t ObjVLink_getMiddle ( OBJVLINK_DATA *this ); bool ObjVLink_setMiddle ( OBJVLINK_DATA *this, int32_t value ); int32_t ObjVLink_getMisc ( OBJVLINK_DATA *this ); bool ObjVLink_setMisc ( OBJVLINK_DATA *this, int32_t value ); int32_t ObjVLink_getParent ( OBJVLINK_DATA *this ); bool ObjVLink_setParent ( OBJVLINK_DATA *this, int32_t value ); int32_t ObjVLink_getRight ( OBJVLINK_DATA *this ); bool ObjVLink_setRight ( OBJVLINK_DATA *this, int32_t value ); //--------------------------------------------------------------- // *** Methods *** //--------------------------------------------------------------- /*! Assign the contents of this object to the other object (ie this -> other). Any objects in other will be released before a copy of the object is performed. Example: @code ERESULT eRc = ObjVLink_Assign(this,pOther); @endcode @param this object pointer @param pOther a pointer to another OBJVLINK object @return If successful, ERESULT_SUCCESS otherwise an ERESULT_* error */ ERESULT ObjVLink_Assign ( OBJVLINK_DATA *this, OBJVLINK_DATA *pOther ); /*! Copy the current object creating a new object. Example: @code ObjVLink *pCopy = ObjVLink_Copy(this); @endcode @param this object pointer @return If successful, a OBJVLINK object which must be released, otherwise OBJ_NIL. @warning Remember to release the returned object. */ OBJVLINK_DATA * ObjVLink_Copy ( OBJVLINK_DATA *this ); /*! Get the index'th entry in the array. If it doesn't exist or there is an error, return zero which is not a legal index. Indices must be non-zero. @param this objArray object pointer @return If successful, an index number, otherwise 0. */ int32_t ObjVLink_Get ( OBJVLINK_DATA *this, uint32_t index // Relative to 1 ); OBJVLINK_DATA * ObjVLink_Init ( OBJVLINK_DATA *this ); uint32_t ObjVLink_NumVLinks ( OBJVLINK_DATA *this ); /*! Set the index'th entry in the array to the given index. @param this objArray object pointer @param index unsigned integer > 0 @param amt signed integer @return If successful, an old index number, otherwise 0. */ int32_t ObjVLink_Set ( OBJVLINK_DATA *this, uint32_t index, // Relative to 1 int32_t amt ); #ifdef OBJVLINK_JSON_SUPPORT /*! Create a string that describes this object and the objects within it in HJSON formt. (See hjson object for details.) Example: @code ASTR_DATA *pDesc = ObjVLink_ToJson(this); @endcode @param this object pointer @return If successful, an AStr object which must be released containing the JSON text, otherwise OBJ_NIL and LastError set to an appropriate ERESULT_* error code. @warning Remember to release the returned AStr object. */ ASTR_DATA * ObjVLink_ToJson( OBJVLINK_DATA *this ); #endif /*! Create a string that describes this object and the objects within it. Example: @code ASTR_DATA *pDesc = ObjVLink_ToDebugString(this,4); @endcode @param this object pointer @param indent number of characters to indent every line of output, can be 0 @return If successful, an AStr object which must be released containing the description, otherwise OBJ_NIL. @warning Remember to release the returned AStr object. */ ASTR_DATA * ObjVLink_ToDebugString ( OBJVLINK_DATA *this, int indent ); #ifdef __cplusplus } #endif #endif /* OBJVLINK_H */
27.895317
85
0.553822
[ "object" ]
7163d1a67e2180ded6536d191cc9a2d1456c7f7d
16,736
h
C
include/ossim/imaging/ossimImageFileWriter.h
martidi/ossim
44268fa9d7fc5a3038642e702e85ccd339a4ff9f
[ "MIT" ]
null
null
null
include/ossim/imaging/ossimImageFileWriter.h
martidi/ossim
44268fa9d7fc5a3038642e702e85ccd339a4ff9f
[ "MIT" ]
null
null
null
include/ossim/imaging/ossimImageFileWriter.h
martidi/ossim
44268fa9d7fc5a3038642e702e85ccd339a4ff9f
[ "MIT" ]
1
2018-10-11T11:36:16.000Z
2018-10-11T11:36:16.000Z
//******************************************************************* // // License: See top level LICENSE.txt file. // // Author: Frank Warmerdam (warmerdam@pobox.com) // // Description: // // Contains class declaration for ossimImageWriter //******************************************************************* // $Id: ossimImageFileWriter.h 21963 2012-12-04 16:28:12Z dburken $ #ifndef ossimImageFileWriter_HEADER #define ossimImageFileWriter_HEADER #include <fstream> #include <ossim/base/ossimIoStream.h> #include <ossim/imaging/ossimImageWriter.h> #include <ossim/base/ossimFilename.h> #include <ossim/base/ossimConnectableObjectListener.h> #include <ossim/base/ossimProcessInterface.h> #include <ossim/base/ossimObjectEvents.h> #include <ossim/base/ossimProcessProgressEvent.h> #include <ossim/base/ossimViewController.h> /** * Pure virtual base class for image file writers. * * There is normally one subclass of this class for each format supported * for writing. This class roughly corresponds to the ImageHandler class * used for reading images. Format specific ossimImageWriter's are normally * instantiated by the ossimImageWriterFactory::createWriterInstance() method. * ossimImageWriters should not be directly instantiated by application code. */ class OSSIMDLLEXPORT ossimImageFileWriter : public ossimImageWriter, public ossimProcessInterface, public ossimConnectableObjectListener { public: /** * The writer will own the sequencer. */ ossimImageFileWriter(const ossimFilename& filename = ossimFilename(), ossimImageSource* inputSource=0, ossimObject* owner=0); virtual ~ossimImageFileWriter(); virtual ossimObject* getObject(); virtual const ossimObject* getObject()const; /** * void getImageTypeList(std::vector<ossimString>& imageTypeList)const * * pure virtual * * Appends the writers image types to the "imageTypeList". * * This is the actual image type name. So for * example, ossimTiffWriter has several image types. Some of these * include TIFF_TILED, TIFF_TILED_BAND_SEPARATE ... etc. * The ossimGdalWriter * may include GDAL_IMAGINE_HFA, GDAL_RGB_NITF, GDAL_JPEG20000, ... etc. * * @param imageTypeList stl::vector<ossimString> list to append to. * * @note All writers should append to the list, not, clear it and then add * their types. */ virtual void getImageTypeList(std::vector<ossimString>& imageTypeList)const=0; /** * Returns a 3-letter extension from the image type descriptor * (theOutputImageType) that can be used for image file extensions. * * @param imageType string representing image type. * * @return the 3-letter string extension. */ virtual ossimString getExtension() const; /** * Examples of writers that always generate internal * overviews are ossim_kakadu_jp2 and ossim_kakadu_nitf_j2k. * * @return true if the output of the writer will have * internal overviews. The default is false. */ virtual bool getOutputHasInternalOverviews( void ) const; /** * bool hasImageType(const ossimString& imageType) const * * @param imageType string representing image type. * * @return true if "imageType" is supported by writer. */ virtual bool hasImageType(const ossimString& imageType) const; /** * Sets the output image tiling size if supported by the writer. If not * supported this simply sets the sequencer(input) tile size. */ virtual void setTileSize(const ossimIpt& tileSize); /** * Will write an envi header file. If "theFilename" is "foo.tif" * then this will write out "foo.hdr". */ virtual bool writeEnviHeaderFile() ; /** * Will write an ER Mapper header file. If "theFilename" is "foo.tif" * then this will write out "foo.hdr". */ virtual bool writeErsHeaderFile() ; /** * Will write an external geometry file. If "theFilename" is "foo.tif" * then this will write out "foo.geom". */ virtual bool writeExternalGeometryFile() ; /** * Will write an fgdc file. If "theFilename" is "foo.tif" * then this will write out "foo.xml". */ virtual bool writeFgdcFile() ; /** * Returns true on success, false on error. */ virtual bool writeHistogramFile() ; /** * Will write a jpeg world file. If "theFilename" is "foo.tif" * then this will write out "foo.jpw". */ virtual bool writeJpegWorldFile() ; /** * Write out an ossim overview file from the source_file. * If source file is "foo.tif", this will create a "foo.ovr" in * the same directory. * * @param source_file The file to create overview from. * * @param tiff_compress_type valid types: * - COMPRESSION_JPEG * - COMPRESSION_DEFLATE * - COMPRESSION_PACKBITS * - COMPRESSION_NONE=1 (default) * * @param jpeg_compress_quality Compression quality. Only valid with * COMPRESSION_JPEG. Range 1 to 100 with 100 being the best. * default = 75 * * @return true on success, false on error. */ virtual bool writeOverviewFile(ossim_uint16 tiff_compress_type = 1, ossim_int32 jpeg_compress_quality = 75, bool includeR0 = false ); /** * Will write a readme file. If "theFilename" is "foo.tif" * then this will write out "foo_readme.txt". */ virtual bool writeReadmeFile() ; /** * Will write a world file. If "theFilename" is "foo.tif" * then this will write out "foo.tfw". */ virtual bool writeTiffWorldFile() ; /** * Will write a world file. The extension will be derived from the * image extension. * * Currently handles the following image extentions: * * "tif" or "tiff" -> "tfw" * "jpg" of "jpeg" -> "jpw" * "png" -> "pgw" * "sid" -> "sdw" * * If extension does not match one of the above no file will be written * and false will be returned. * * @return true on success false on error. */ virtual bool writeWorldFile() ; /** * Convenience method that calls meta data write methods that are flagged * to be called. Attempts to write all files flagged to be written even * if one file writer returns false. * * Currently calls these methods if flagged: * writeEnviHeaderFile * writeExternalGeometryFile * writeFgdcFile * writeJpegWorldFile * writeReadmeFile * writeTiffWorldFile * writeOverviewFile * writeHistogramFile * * @return true if all files flagged are written, false if not. */ virtual bool writeMetaDataFiles() ; virtual void setAreaOfInterest(const ossimIrect& inputRect); /** * @brief Sets the sequencer and connects it to the input of this. * * This does not set the area of interest. Note stored as an ossimRefPtr. * * @param sequencer Pointer to a sequencer. */ virtual void changeSequencer(ossimImageSourceSequencer* sequencer); virtual ossimImageSourceSequencer* getSequencer(); /** * @brief Initialize method. * * Calls theInputConnection->initialize() then syncs area of interest(AOI) * with ossimImageWriter::theAreaOfInterest taking precedence over * ossimImageSourceSequencer::theAreaOfInterest. */ virtual void initialize(); /** * Calls: * writeFile() * writeMetaDataFiles() * * @return true on success, false on error. */ virtual bool execute(); /** * @brief Method to write the image to a stream. * * This implementation does nothing and returns false. * Derived classed should implement as needed. * * @return true on success, false on error. */ virtual bool writeStream(); /** * @brief Sets the output stream to write to. * * This implementation in this class does nothing and returns false. * Derived classed should implement as needed. * * @param stream The stream to write to. * * @return true if object can write to stream, false if not. */ virtual bool setOutputStream(ossimRefPtr<ossimOStream> stream); /** tmp drb */ virtual bool setOutputStream(std::ostream& str); /** * @brief Method to return the stream attached to output. * * This implementation in this class does nothing and returns an empty * ossimRefPtr<ossimOStream>. * Derived classed should implement as needed. * * @return The stream wrapped around a ref pointer. */ virtual ossimRefPtr<ossimOStream> getOutputStream() const; virtual void setPercentComplete(double percentComplete); virtual void setOutputImageType(ossim_int32 type); virtual void setOutputImageType(const ossimString& type); virtual ossim_int32 getOutputImageType() const; virtual ossimString getOutputImageTypeString() const; virtual void setOutputName(const ossimString& outputName); virtual void setFilename(const ossimFilename& file); virtual const ossimFilename& getFilename()const; virtual bool saveState(ossimKeywordlist& kwl, const char* prefix=0)const; virtual bool loadState(const ossimKeywordlist& kwl, const char* prefix=0); virtual bool canConnectMyInputTo(ossim_int32 inputIndex, const ossimConnectableObject* object)const; virtual void disconnectInputEvent(ossimConnectionEvent& event); virtual void connectInputEvent(ossimConnectionEvent& event); virtual void propertyEvent(ossimPropertyEvent& event); /** * Control flags... */ virtual bool getWriteImageFlag() const; virtual bool getWriteHistogramFlag() const; virtual bool getWriteOverviewFlag() const; virtual bool getScaleToEightBitFlag() const; virtual bool getWriteEnviHeaderFlag() const; virtual bool getWriteErsHeaderFlag() const; virtual bool getWriteExternalGeometryFlag() const; virtual bool getWriteFgdcFlag() const; virtual bool getWriteJpegWorldFileFlag() const; virtual bool getWriteReadmeFlag() const; virtual bool getWriteTiffWorldFileFlag() const; virtual bool getWriteWorldFileFlag() const; virtual void setWriteImageFlag(bool flag); virtual void setWriteOverviewFlag(bool flag); virtual void setWriteHistogramFlag(bool flag); virtual void setScaleToEightBitFlag(bool flag); virtual void setWriteEnviHeaderFlag(bool flag); virtual void setWriteErsHeaderFlag(bool flag); virtual void setWriteExternalGeometryFlag(bool flag); virtual void setWriteFgdcFlag(bool flag); virtual void setWriteJpegWorldFile(bool flag); virtual void setWriteReadme(bool flag); virtual void setWriteTiffWorldFile(bool flag); virtual void setWriteWorldFile(bool flag); virtual ossim_uint16 getOverviewCompressType() const; virtual ossim_int32 getOverviewJpegCompressQuality() const; virtual void setOverviewCompressType(ossim_uint16 type); virtual void setOverviewJpegCompressQuality(ossim_int32 quality); virtual void setProperty(ossimRefPtr<ossimProperty> property); virtual ossimRefPtr<ossimProperty> getProperty(const ossimString& name)const; virtual void getPropertyNames(std::vector<ossimString>& propertyNames)const; /** * Overrides base "addListener" this will capture the pointer and then call * the base class "addListener". If overview building is enabled, the * listener will be passed to the overview builder::addListener, and * subsequently removed from the overview builder after the build overview * call is complete. This it transparent to the caller of this method. * * @param listener The listener to add. * * @return Currently always returns true. * * @note Callers still should call "removeListener" after the writing * process is complete. * * @note If called more than once, theProgressListener will contain * the latest listener. */ virtual bool addListener(ossimListener* listener); /** * Overrides base "removeListener". Calls base "removeListener which will * find and removes the listener. * If "theProgressListener" pointer matches listener "theProgressListener" * will be set to NULL. * * @param listener The listener to remove. * * @return Currently always returns true. */ virtual bool removeListener(ossimListener* listener); /** * If "point" the coordinate tie points are relative to the center of the * pixel. If "area" the coordinate tie points are relative to the upper * left corner of the pixel. * * For image types that are keyed, tiff for instance, this will set the * geotiff key: GTRasterTypeGeoKey * * If meta data writers are enabled, world file writers for instance, * this will also be propagated to them. * * Default in this writer is: OSSIM_PIXEL_IS_POINT * * @param type * OSSIM_PIXEL_IS_POINT = center of pixel * OSSIM_PIXEL_IS_AREA = upper left corner of pixel */ virtual void setPixelType(ossimPixelType type); /** * If "point" the coordinate tie points are relative to the center of the * pixel. If "area" the coordinate tie points are relative to the upper * left corner of the pixel. * * For image types that are keyed, tiff for instance, this will set the * geotiff key: GTRasterTypeGeoKey * * If meta data writers are enabled, world file writers for instance, * this will also be propagated to them. * Default in this writer is: OSSIM_PIXEL_IS_POINT * * @param type * "point" = center of pixel * "area" = upper left corner of pixel * * @note If the downcased "type" is not equal to "point" or "area" pixel * type will remain unchanged. */ virtual void setPixelType(const ossimString& type); /** * @return The pixel type as either OSSIM_PIXEL_IS_POINT or * OSSIM_PIXEL_IS_AREA. */ virtual ossimPixelType getPixelType() const; /** * @param type ossimString to initialize which will either be "point" or * "area". */ virtual void getPixelTypeString(ossimString& type) const; protected: /** * Common world file writer method. * * @param file The file to write like "foo.tfw" or "foo.jpw". * * @return true on success, false on error. */ bool writeWorldFile(const ossimFilename& file); /** * Write out the file. * @return true on success, false on error. */ virtual bool writeFile() = 0; ossimRefPtr<ossimImageSourceSequencer> theInputConnection; ossimRefPtr<ossimViewController> theViewController; ossimListener* theProgressListener; ossimFilename theFilename; ossimString theOutputImageType; bool theWriteImageFlag; bool theWriteOverviewFlag; bool theWriteHistogramFlag; bool theScaleToEightBitFlag; ossim_uint16 theOverviewCompressType; ossim_int32 theOverviewJpegCompressQuality; /** * External meta data writer flags. Not really part of an image writer, put * here for convenience. If true the writer will do the connection work * for you. */ bool theWriteEnviHeaderFlag; bool theWriteErsHeaderFlag; bool theWriteExternalGeometryFlag; bool theWriteFgdcFlag; bool theWriteJpegWorldFileFlag; bool theWriteReadmeFlag; bool theWriteTiffWorldFileFlag; bool theWriteWorldFileFlag; bool theAutoCreateDirectoryFlag; /** * If not a geographic projection this allows the user to set the linear * units of the output tag to be: * * meters (default) * us_survey_feet * feet * * This will be propagated to writers that can switch types and to the * associated metadata writers. */ ossimUnitType theLinearUnits; /** OSSIM_PIXEL_IS_POINT = 0, OSSIM_PIXEL_IS_AREA = 1 */ ossimPixelType thePixelType; TYPE_DATA }; #endif
33.472
81
0.658222
[ "geometry", "object", "vector" ]
717adcb5ba48c88bd2988da0d18d6427441480e1
1,315
h
C
Code/Framework/AzQtComponents/AzQtComponents/Components/StyledLineEdit.h
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
11
2021-07-08T09:58:26.000Z
2022-03-17T17:59:26.000Z
Code/Framework/AzQtComponents/AzQtComponents/Components/StyledLineEdit.h
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
29
2021-07-06T19:33:52.000Z
2022-03-22T10:27:49.000Z
Code/Framework/AzQtComponents/AzQtComponents/Components/StyledLineEdit.h
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
4
2021-07-06T19:24:43.000Z
2022-03-31T12:42:27.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #pragma once #if !defined(Q_MOC_RUN) #include <AzQtComponents/AzQtComponentsAPI.h> #include <QLineEdit> #endif namespace AzQtComponents { class AZ_QT_COMPONENTS_API StyledLineEdit : public QLineEdit { Q_OBJECT Q_PROPERTY(Flavor flavor READ flavor WRITE setFlavor NOTIFY flavorChanged) public: enum Flavor { Plain = 0, Information, Question, Invalid, Valid, FlavorCount }; Q_ENUM(Flavor) explicit StyledLineEdit(QWidget* parent = nullptr); ~StyledLineEdit(); Flavor flavor() const; void setFlavor(Flavor); protected: void focusInEvent(QFocusEvent* event) override; void focusOutEvent(QFocusEvent* event) override; signals: void flavorChanged(); void onFocus(); // Required for focus dependent custom widgets, e.g. ConfigStringLineEditCtrl. void onFocusOut(); private: void validateEntry(); Flavor m_flavor; }; } // namespace AzQtComponents
22.672414
102
0.631939
[ "3d" ]
717b3aea0df451e99c832fa6a2d9d45411349f05
2,319
h
C
image/ExifImageHelper.h
gizmomogwai/cpplib
a09bf4d3f2a312774d3d85a5c65468099a1797b0
[ "MIT" ]
null
null
null
image/ExifImageHelper.h
gizmomogwai/cpplib
a09bf4d3f2a312774d3d85a5c65468099a1797b0
[ "MIT" ]
null
null
null
image/ExifImageHelper.h
gizmomogwai/cpplib
a09bf4d3f2a312774d3d85a5c65468099a1797b0
[ "MIT" ]
null
null
null
#ifndef ExifImageHelper_h_ #define ExifImageHelper_h_ #include <image/ImageApi.h> #include <string> #include <sstream> class IMAGE_API ExifImageHelper { public: static std::string getDescription(int id) { switch (id) { case 256: return "Image Width"; case 257: return "Image Height"; case 258: return "Bits Per Channel"; case 259: return "Compression"; case 270: return "Image Description"; case 271: return "Manufacturer Name"; case 272: return "Model Name"; case 273: return "Strip Offset"; case 274: return "Image Orientation"; case 277: return "Samples Per Pixel"; case 278: return "Rows Per Strip"; case 282: return "Pixels/resolution in x"; case 283: return "Pixels/resolution in y"; case 296: return "Units of resolution"; case 305: return "Software"; case 306: return "Creation Date"; case 513: return "JPEGIFOFFSET"; case 514: return "JPEGIFBYTECOUNT"; case 531: return "subsample positioning"; case 34665: return "EXIFIFDPOINTER"; case 33434: return "Exposuretime"; case 33437: return "FNumber"; case 34850: return "EXPOSUREPROGRAM"; case 36867: return "EXIFTAG_DATETIMEORIGINAL"; case 36868: return "EXIFTAG_DATETIMEDIGITIZED"; case 36864: return "Exif Version"; case 37121: return "COMPONENTSCONFIGURATION"; case 37122: return "Compressed Bit Per Pixel"; case 37380: return "EXPOSUREBIASVALUE"; case 37381: return "MaxApertureValue"; case 37382: return "SubjectDistance"; case 37383: return "Metering Mode"; case 37384: return "Light Source"; case 37385: return "Flash"; case 37386: return "Focallength"; case 37500: return "Makernote"; case 40960: return "FlashPixVersion"; case 40961: return "ColorSpace"; case 40962: return "PixelXDimension"; case 40963: return "PixelYDimension"; case 40965: return "EXIFINTEROPIFDPOINTER"; case 41728: return "FILESOURCE"; default: std::ostringstream s; s << "unknown " << id; return s.str(); } } }; #endif
21.672897
45
0.608452
[ "model" ]
71a6966ff03fe3670433d7a541173bc8dd62240c
5,603
h
C
Sources/Plugins/RenderSystem_GPR/SoftwareRenderer.h
jdelezenne/Sonata
fb1b1b64a78874a0ab2809995be4b6f14f9e4d56
[ "MIT" ]
null
null
null
Sources/Plugins/RenderSystem_GPR/SoftwareRenderer.h
jdelezenne/Sonata
fb1b1b64a78874a0ab2809995be4b6f14f9e4d56
[ "MIT" ]
null
null
null
Sources/Plugins/RenderSystem_GPR/SoftwareRenderer.h
jdelezenne/Sonata
fb1b1b64a78874a0ab2809995be4b6f14f9e4d56
[ "MIT" ]
null
null
null
/*============================================================================= SoftwareRenderer.h Project: Sonata Engine Copyright � 2005 Julien Delezenne =============================================================================*/ #ifndef _SOFTWARERENDERER_H_ #define _SOFTWARERENDERER_H_ #include "OGPR/OGPR.h" #include "Graphic/Renderer.h" #include "Mesh/VertexDeclaration.h" #include "Material/Shader.h" using namespace Teesside; // Default is float3 colour buffer //#define ARGB_COLOUR_BUFFER typedef Vector3 (*OGPRVertexFunction) (OGPRVertexFuncEnv* env); typedef Colour32 (*OGPRFragmentFunction) (OGPRFragmentFuncEnv* env); typedef void (*OGPRPixelFunction) (OGPRPixelFuncEnv *env); enum DeviceBufferType { DBT_ColourBuffer, DBT_DepthBuffer, DBT_StencilBuffer, DBT_Unused }; struct SoftwareCaps { uint32 MaxStreams; uint32 MaxInterpolants; uint32 MaxConstants; uint32 MaxBuffers; }; struct SoftwareLight { LightType Type; bool Enabled; Colour32 AmbientColour; Colour32 DiffuseColour; Colour32 SpecularColour; Vector3 Attenuations; Vector3 Direction; Vector3 Position; real32 Exponent; real32 CutOff; }; struct SoftwareStates { Colour32 Ambient; ScissorState ScissorState; FogState FogState; PointState PointState; FillMode FillMode; ShadeMode ShadeMode; CullMode CullMode; bool NormalizeNormals; bool Dithering; ColourFlag ColourWriteEnable; MaterialState MaterialState; bool Lighting; Array<SoftwareLight> Lights; DepthState DepthState; StencilState StencilState; AlphaState AlphaState; List<TextureState> Textures; }; /** Software implementation of the renderer. */ class SoftwareRenderer : public Renderer { public: /** Constructors / Destructor. */ //@{ SoftwareRenderer(); virtual ~SoftwareRenderer(); //@} virtual const Colour32& GetClearColour() const { return _ClearColour; } virtual void SetClearColour(const Colour32& clearColour) { _ClearColour = clearColour; } virtual real32 GetDepthValue() const { return _DepthValue; } virtual void SetDepthValue(real32 depthValue) { _DepthValue = depthValue; } virtual int32 GetStencilValue() const { return _StencilValue; } virtual void SetStencilValue(int32 stencilValue) { _StencilValue = stencilValue; } virtual const Matrix4& GetWorldTransform(); virtual void SetWorldTransform(const Matrix4& matWorld); virtual void SetAmbientColour(const Colour32& value); virtual void SetScissorState(ScissorState state); virtual void SetFogState(FogState state); virtual void SetPointState(PointState state); virtual void SetFillMode(FillMode mode); virtual void SetShadeMode(ShadeMode mode); virtual void SetCullMode(CullMode mode); virtual void SetNormalizeNormals(bool value); virtual void SetDithering(bool value); virtual void SetLighting(bool value); virtual void SetMaterialState(MaterialState state); virtual void SetLightState(LightState state); virtual void SetTextureState(int stage, TextureState state); virtual void DisableTextureState(int stage); virtual void SetColourWriteEnable(ColourFlag colourWriteEnable); virtual void SetDepthState(DepthState state); virtual void SetStencilState(StencilState state); virtual void SetAlphaState(AlphaState state); virtual void SetBlendModes(BlendMode sourceBlend, BlendMode destinationBlend); virtual bool Create(uint32 width, uint32 height); virtual void GetCaps(); virtual bool Destroy(); virtual void Clear(); virtual void BeginScene(); virtual void EndScene(); virtual void DumpColourBuffer(const String& fileName); virtual bool CreateVertexBuffer(uint32 length, uint32 components, HardwareBuffer** vertexBuffer); virtual bool CreateIndexBuffer(uint32 indexSize, uint32 indexCount, HardwareBuffer** indexBuffer); virtual bool CreateTexture(Image* image, Texture** texture); virtual void Render(Mesh* mesh); virtual void RenderGeometry(Mesh* mesh); virtual void DrawText(const String& text, uint32 x, uint32 y, const Colour32& colour); public: OGPRBuffer* GetColourBuffer() const { return _ColourBuffer; } OGPRBuffer* GetDepthBuffer() const { return _DepthBuffer; } OGPRBuffer* GetStencilBuffer() const { return _StencilBuffer; } OGPRRenderer* GetRenderer() const { return _Renderer; } VertexDeclaration* GetVertexDeclaration() const { return _VertexDeclaration; } OGPRBuffer* GetVertexBuffer() const { return _VertexBuffer; } SoftwareStates States; /** Vertices Operations. */ //@{ /// Clipping. bool Clipping(Vector4& position) { return false; } //@} /** Pixels Operations. */ //@{ /// Framebuffer operations. bool Raster(OGPRFragmentFuncEnv& env, Colour32& colour); //@} protected: bool _Init; SoftwareCaps _Caps; Colour32 _ClearColour; real32 _DepthValue; int32 _StencilValue; Matrix4 _WorldTransform; VertexDeclaration* _VertexDeclaration; OGPRBuffer* _VertexBuffer; uint32 _Width; uint32 _Height; OGPRRenderer* _Renderer; OGPRBuffer* _ColourBuffer; OGPRBuffer* _DepthBuffer; OGPRBuffer* _StencilBuffer; /** Fragments Operations. */ //@{ /// Scissor testing. bool ScissorTest(OGPRFragmentFuncEnv& env, const Vector4& position); /// Alpha testing. bool AlphaTest(OGPRFragmentFuncEnv& env, real32 alpha); /// Stencil testing. bool StencilTest(OGPRFragmentFuncEnv& env); void _StencilOperation(OGPRFragmentFuncEnv& env, StencilOperation operation, int32 current); /// Depth testing. bool DepthTest(OGPRFragmentFuncEnv& env, real32 depth); /// Blending. void Blending(const Colour32& current, Colour32& colour); /// Fog. void PixelFog(real32 depth, Colour32& colour); /// Masking. void Masking(Colour32& colour); //@} }; #endif
28.155779
99
0.759593
[ "mesh", "render" ]
71a6e9ea847ea05732a241c2d760352ad8527a96
432
h
C
simulation.h
mpdcampbell/nat-selection
1b4c7d4eeb4f262685d8a219005993bebe8f3fee
[ "MIT" ]
5
2019-09-29T21:30:18.000Z
2019-12-31T00:24:51.000Z
simulation.h
mpdcampbell/nat-selection
1b4c7d4eeb4f262685d8a219005993bebe8f3fee
[ "MIT" ]
null
null
null
simulation.h
mpdcampbell/nat-selection
1b4c7d4eeb4f262685d8a219005993bebe8f3fee
[ "MIT" ]
3
2019-08-01T16:55:55.000Z
2020-03-14T17:14:29.000Z
#ifndef SIMULATION_H #define SIMULATION_H #include <vector> #include "food.h" #include "blob.h" #include "simulationResults.h" extern int g_nameHolder; void walkAndEat(std::vector<Blob> &blobArray, std::vector<Food> &foodArray, simulationResults &stats); void naturalSelection(std::vector<Blob> &blobArray); void breed(std::vector<Blob> &blobArray); void digestAndSleep(std::vector<Blob> &blobArray); #endif
22.736842
103
0.733796
[ "vector" ]
2193a32e216c33e1bc783f002d929434c19fa687
3,671
h
C
src/RenderFarmUI/RF_DrawMap.h
rromanchuk/xptools
deff017fecd406e24f60dfa6aae296a0b30bff56
[ "X11", "MIT" ]
71
2015-12-15T19:32:27.000Z
2022-02-25T04:46:01.000Z
src/RenderFarmUI/RF_DrawMap.h
rromanchuk/xptools
deff017fecd406e24f60dfa6aae296a0b30bff56
[ "X11", "MIT" ]
19
2016-07-09T19:08:15.000Z
2021-07-29T10:30:20.000Z
src/RenderFarmUI/RF_DrawMap.h
rromanchuk/xptools
deff017fecd406e24f60dfa6aae296a0b30bff56
[ "X11", "MIT" ]
42
2015-12-14T19:13:02.000Z
2022-03-01T15:15:03.000Z
/* * Copyright (c) 2004, Laminar Research. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #ifndef DRAWMAP_H #define DRAWMAP_H #include "MapDefs.h" #include "RF_Selection.h" #include "ProgressUtils.h" #include "RTree2.h" extern int g_color_face_with_terr; extern int g_color_face_with_zone; extern int g_color_face_with_supr; extern int g_color_face_with_appr; extern int g_color_face_use_supr_tint; class GUI_GraphState; void PrecalcOGL(Pmwx& ioMap, ProgressFunc inFunc); void RecalcOGLColors(Pmwx& ioMap, ProgressFunc inFunc); struct PmwxIndex_t { PmwxIndex_t() { } typedef RTree2<Face_handle,16> FaceTree; typedef RTree2<Halfedge_handle,16> HalfedgeTree; typedef RTree2<Vertex_handle,16> VertexTree; FaceTree faces; HalfedgeTree halfedges; VertexTree vertices; void IndexPmwx(Pmwx& pmwx, PmwxIndex_t& index); private: PmwxIndex_t(const PmwxIndex_t&); PmwxIndex_t& operator=(const PmwxIndex_t&); }; void IndexPmwx(Pmwx& pmwx, PmwxIndex_t& index); void DrawMapBucketed( GUI_GraphState * inState, Pmwx& inMap, PmwxIndex_t& inIndex, double mapWest, double mapSouth, double mapEast, double mapNorth, // double screenLeft, // double screenBottom, // double screenRight, // double screenTop, const set<Pmwx::Vertex_handle>& vertexSel, const set<Pmwx::Halfedge_handle>& edgeSel, const set<Pmwx::Face_handle>& faceSel, const set<PointFeatureSelection>& pointFeatureSel); void FindFaceTouchesPt(Pmwx& inMap, PmwxIndex_t& index, const Point2&, vector<Face_handle>& outIDs); // Fully checks for pt containment void FindFaceTouchesRectFast(Pmwx& inMap, PmwxIndex_t& index, const Point2&, const Point2&, vector<Face_handle>& outIDs); // Intersects with face bbox, not face void FindFaceFullyInRect(Pmwx& inMap, PmwxIndex_t& index, const Point2&, const Point2&, vector<Face_handle>& outIDs); // Full containment void FindHalfedgeTouchesRectFast(Pmwx& inMap, PmwxIndex_t& index, const Point2&, const Point2&, vector<Halfedge_handle>& outIDs); // Intersects with half-edge bbox, not half-edge void FindHalfedgeFullyInRect(Pmwx& inMap, PmwxIndex_t& index, const Point2&, const Point2&, vector<Halfedge_handle>& outIDs); // Full containment void FindVerticesTouchesPt(Pmwx& inMap, PmwxIndex_t& index, const Point2&, vector<Vertex_handle>& outIDs); // Perfect equalty. void FindVerticesTouchesRect(Pmwx& inMap, PmwxIndex_t& index, const Point2&, const Point2&, vector<Vertex_handle>& outIDs); // Full containment (any containment is full for pts) #endif
40.340659
181
0.743667
[ "vector" ]
219ebf6971722134b1752d85734bcaa235b81d09
33,753
c
C
client-src/sendbackup.c
nikolasco/amanda
a41a213072aeb6ee715b68f3d84707110546ae9f
[ "BSD-4-Clause-UC" ]
1
2016-05-09T10:42:44.000Z
2016-05-09T10:42:44.000Z
client-src/sendbackup.c
nikolasco/amanda
a41a213072aeb6ee715b68f3d84707110546ae9f
[ "BSD-4-Clause-UC" ]
null
null
null
client-src/sendbackup.c
nikolasco/amanda
a41a213072aeb6ee715b68f3d84707110546ae9f
[ "BSD-4-Clause-UC" ]
null
null
null
/* * Amanda, The Advanced Maryland Automatic Network Disk Archiver * Copyright (c) 1991-1999 University of Maryland at College Park * All Rights Reserved. * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of U.M. not be used in advertising or * publicity pertaining to distribution of the software without specific, * written prior permission. U.M. makes no representations about the * suitability of this software for any purpose. It is provided "as is" * without express or implied warranty. * * U.M. DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL U.M. * 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. * * Authors: the Amanda Development Team. Its members are listed in a * file named AUTHORS, in the root directory of this distribution. */ /* * $Id: sendbackup.c,v 1.88 2006/07/25 18:27:56 martinea Exp $ * * common code for the sendbackup-* programs. */ #include "amanda.h" #include "sendbackup.h" #include "clock.h" #include "pipespawn.h" #include "amfeatures.h" #include "amandad.h" #include "arglist.h" #include "getfsent.h" #include "conffile.h" #include "amandates.h" #define sendbackup_debug(i, ...) do { \ if ((i) <= debug_sendbackup) { \ dbprintf(__VA_LIST__); \ } \ } while (0) #define TIMEOUT 30 pid_t comppid = (pid_t)-1; pid_t dumppid = (pid_t)-1; pid_t tarpid = (pid_t)-1; pid_t encpid = (pid_t)-1; pid_t indexpid = (pid_t)-1; pid_t application_api_pid = (pid_t)-1; char *errorstr = NULL; int datafd; int mesgfd; int indexfd; g_option_t *g_options = NULL; long dump_size = -1; backup_program_t *program = NULL; dle_t *gdle = NULL; static am_feature_t *our_features = NULL; static char *our_feature_string = NULL; static char *amandad_auth = NULL; /* local functions */ int main(int argc, char **argv); char *childstr(pid_t pid); int check_status(pid_t pid, amwait_t w, int mesgfd); pid_t pipefork(void (*func)(void), char *fname, int *stdinfd, int stdoutfd, int stderrfd); int check_result(int mesgfd); void parse_backup_messages(dle_t *dle, int mesgin); static void process_dumpline(char *str); static void save_fd(int *, int); void application_api_info_tapeheader(int mesgfd, char *prog, dle_t *dle); int fdprintf(int fd, char *format, ...) G_GNUC_PRINTF(2, 3); int fdprintf( int fd, char *format, ...) { va_list argp; char *s; int r; arglist_start(argp, format); s = g_strdup_vprintf(format, argp); arglist_end(argp); r = full_write(fd, s, strlen(s)); amfree(s); return r; } int main( int argc, char ** argv) { int interactive = 0; int level = 0; int mesgpipe[2]; dle_t *dle = NULL; char *dumpdate, *stroptions; char *qdisk = NULL; char *qamdevice = NULL; char *line = NULL; char *err_extra = NULL; char *s; int i; int ch; GSList *errlist; FILE *mesgstream; level_t *alevel; /* initialize */ /* * Configure program for internationalization: * 1) Only set the message locale for now. * 2) Set textdomain for all amanda related programs to "amanda" * We don't want to be forced to support dozens of message catalogs. */ setlocale(LC_MESSAGES, "C"); textdomain("amanda"); safe_fd(DATA_FD_OFFSET, DATA_FD_COUNT*2); openbsd_fd_inform(); safe_cd(); set_pname("sendbackup"); /* Don't die when child closes pipe */ signal(SIGPIPE, SIG_IGN); /* Don't die when interrupt received */ signal(SIGINT, SIG_IGN); if(argc > 1 && strcmp(argv[1],"-t") == 0) { interactive = 1; argc--; argv++; } else { interactive = 0; } add_amanda_log_handler(amanda_log_stderr); add_amanda_log_handler(amanda_log_syslog); dbopen(DBG_SUBDIR_CLIENT); startclock(); dbprintf(_("Version %s\n"), VERSION); if(argc > 2 && strcmp(argv[1], "amandad") == 0) { amandad_auth = stralloc(argv[2]); } our_features = am_init_feature_set(); our_feature_string = am_feature_to_string(our_features); config_init(CONFIG_INIT_CLIENT, NULL); /* (check for config errors comes later) */ check_running_as(RUNNING_AS_CLIENT_LOGIN); if(interactive) { /* * In interactive (debug) mode, the backup data is sent to * /dev/null and none of the network connections back to driver * programs on the tape host are set up. The index service is * run and goes to stdout. */ g_fprintf(stderr, _("%s: running in interactive test mode\n"), get_pname()); fflush(stderr); } qdisk = NULL; dumpdate = NULL; stroptions = NULL; for(; (line = agets(stdin)) != NULL; free(line)) { if (line[0] == '\0') continue; if(interactive) { g_fprintf(stderr, "%s> ", get_pname()); fflush(stderr); } if(strncmp_const(line, "OPTIONS ") == 0) { g_options = parse_g_options(line+8, 1); if(!g_options->hostname) { g_options->hostname = alloc(MAX_HOSTNAME_LENGTH+1); gethostname(g_options->hostname, MAX_HOSTNAME_LENGTH); g_options->hostname[MAX_HOSTNAME_LENGTH] = '\0'; } if (g_options->config) { /* overlay this configuration on the existing (nameless) configuration */ config_init(CONFIG_INIT_CLIENT | CONFIG_INIT_EXPLICIT_NAME | CONFIG_INIT_OVERLAY, g_options->config); dbrename(get_config_name(), DBG_SUBDIR_CLIENT); } /* check for any config errors now */ if (config_errors(&errlist) >= CFGERR_ERRORS) { char *errstr = config_errors_to_error_string(errlist); g_printf("%s\n", errstr); dbclose(); return 1; } if (am_has_feature(g_options->features, fe_req_xml)) { break; } continue; } if (dle && dle->program != NULL) { err_extra = _("multiple requests"); goto err; } dbprintf(_(" sendbackup req: <%s>\n"), line); dle = alloc_dle(); s = line; ch = *s++; skip_whitespace(s, ch); /* find the program name */ if(ch == '\0') { err_extra = _("no program name"); goto err; /* no program name */ } dle->program = s - 1; skip_non_whitespace(s, ch); s[-1] = '\0'; if (strcmp(dle->program, "APPLICATION")==0) { dle->program_is_application_api=1; skip_whitespace(s, ch); /* find dumper name */ if (ch == '\0') { goto err; /* no program */ } dle->program = s - 1; skip_non_whitespace(s, ch); s[-1] = '\0'; } dle->program = stralloc(dle->program); skip_whitespace(s, ch); /* find the disk name */ if(ch == '\0') { err_extra = _("no disk name"); goto err; /* no disk name */ } amfree(qdisk); qdisk = s - 1; ch = *qdisk; skip_quoted_string(s, ch); s[-1] = '\0'; qdisk = stralloc(qdisk); dle->disk = unquote_string(qdisk); skip_whitespace(s, ch); /* find the device or level */ if (ch == '\0') { err_extra = _("bad level"); goto err; } if(!isdigit((int)s[-1])) { amfree(qamdevice); qamdevice = s - 1; ch = *qamdevice; skip_quoted_string(s, ch); s[-1] = '\0'; qamdevice = stralloc(qamdevice); dle->device = unquote_string(qamdevice); skip_whitespace(s, ch); /* find level number */ } else { dle->device = stralloc(dle->disk); qamdevice = stralloc(qdisk); } /* find the level number */ if(ch == '\0' || sscanf(s - 1, "%d", &level) != 1) { err_extra = _("bad level"); goto err; /* bad level */ } skip_integer(s, ch); alevel = g_new0(level_t, 1); alevel->level = level; dle->levellist = g_slist_append(dle->levellist, alevel); skip_whitespace(s, ch); /* find the dump date */ if(ch == '\0') { err_extra = _("no dumpdate"); goto err; /* no dumpdate */ } amfree(dumpdate); dumpdate = s - 1; skip_non_whitespace(s, ch); s[-1] = '\0'; dumpdate = stralloc(dumpdate); skip_whitespace(s, ch); /* find the options keyword */ if(ch == '\0') { err_extra = _("no options"); goto err; /* no options */ } if(strncmp_const_skip(s - 1, "OPTIONS ", s, ch) != 0) { err_extra = _("no OPTIONS keyword"); goto err; /* no options */ } skip_whitespace(s, ch); /* find the options string */ if(ch == '\0') { err_extra = _("bad options string"); goto err; /* no options */ } amfree(stroptions); stroptions = stralloc(s - 1); } amfree(line); if (g_options == NULL) { g_printf(_("ERROR [Missing OPTIONS line in sendbackup input]\n")); error(_("Missing OPTIONS line in sendbackup input\n")); /*NOTREACHED*/ } if (am_has_feature(g_options->features, fe_req_xml)) { char *errmsg = NULL; dle = amxml_parse_node_FILE(stdin, &errmsg); if (errmsg) { err_extra = errmsg; goto err; } if (!dle) { err_extra = _("One DLE required"); goto err; } else if (dle->next) { err_extra = _("Only one DLE allowed"); goto err; } qdisk = quote_string(dle->disk); if (dle->device == NULL) dle->device = stralloc(dle->disk); qamdevice = quote_string(dle->device); dumpdate = stralloc("NODATE"); stroptions = stralloc(""); } else { parse_options(stroptions, dle, g_options->features, 0); } gdle = dle; if (dle->program == NULL || dle->disk == NULL || dle->device == NULL || dle->levellist == NULL || dumpdate == NULL) { err_extra = _("no valid sendbackup request"); goto err; } if (g_slist_length(dle->levellist) != 1) { err_extra = _("Too many level"); goto err; } alevel = (level_t *)dle->levellist->data; level = alevel->level; dbprintf(_(" Parsed request as: program `%s'\n"), dle->program); dbprintf(_(" disk `%s'\n"), qdisk); dbprintf(_(" device `%s'\n"), qamdevice); dbprintf(_(" level %d\n"), level); dbprintf(_(" since %s\n"), dumpdate); dbprintf(_(" options `%s'\n"), stroptions); if (dle->program_is_application_api==1) { /* check that the application_api exist */ } else { for(i = 0; programs[i]; i++) { if (strcmp(programs[i]->name, dle->program) == 0) { break; } } if (programs[i] == NULL) { dbprintf(_("ERROR [%s: unknown program %s]\n"), get_pname(), dle->program); error(_("ERROR [%s: unknown program %s]"), get_pname(), dle->program); /*NOTREACHED*/ } program = programs[i]; } if(!interactive) { datafd = DATA_FD_OFFSET + 0; mesgfd = DATA_FD_OFFSET + 2; indexfd = DATA_FD_OFFSET + 4; } if (!dle->create_index) indexfd = -1; if (dle->auth && amandad_auth) { if(strcasecmp(dle->auth, amandad_auth) != 0) { g_printf(_("ERROR [client configured for auth=%s while server requested '%s']\n"), amandad_auth, dle->auth); exit(-1); } } if (dle->kencrypt) { g_printf("KENCRYPT\n"); } g_printf(_("CONNECT DATA %d MESG %d INDEX %d\n"), DATA_FD_OFFSET, DATA_FD_OFFSET+1, indexfd == -1 ? -1 : DATA_FD_OFFSET+2); g_printf(_("OPTIONS ")); if(am_has_feature(g_options->features, fe_rep_options_features)) { g_printf("features=%s;", our_feature_string); } if(am_has_feature(g_options->features, fe_rep_options_hostname)) { g_printf("hostname=%s;", g_options->hostname); } if (!am_has_feature(g_options->features, fe_rep_options_features) && !am_has_feature(g_options->features, fe_rep_options_hostname)) { g_printf(";"); } g_printf("\n"); fflush(stdout); if (freopen("/dev/null", "w", stdout) == NULL) { dbprintf(_("Error redirecting stdout to /dev/null: %s\n"), strerror(errno)); exit(1); } if(interactive) { if((datafd = open("/dev/null", O_RDWR)) < 0) { error(_("ERROR [open of /dev/null for debug data stream: %s]\n"), strerror(errno)); /*NOTREACHED*/ } mesgfd = 2; indexfd = 1; } if(!interactive) { if(datafd == -1 || mesgfd == -1 || (dle->create_index && indexfd == -1)) { dbclose(); exit(1); } } mesgstream = fdopen(mesgfd,"w"); run_client_scripts(EXECUTE_ON_PRE_DLE_BACKUP, g_options, dle, mesgstream); fflush(mesgstream); if (dle->program_is_application_api==1) { guint j; char *cmd=NULL; GPtrArray *argv_ptr; char levelstr[20]; backup_support_option_t *bsu; char *compopt = NULL; char *encryptopt = skip_argument; int compout, dumpout; GSList *scriptlist; script_t *script; time_t cur_dumptime; int result; GPtrArray *errarray; int errfd[2]; FILE *dumperr; /* apply client-side encryption here */ if ( dle->encrypt == ENCRYPT_CUST ) { encpid = pipespawn(dle->clnt_encrypt, STDIN_PIPE, 0, &compout, &datafd, &mesgfd, dle->clnt_encrypt, encryptopt, NULL); dbprintf(_("encrypt: pid %ld: %s\n"), (long)encpid, dle->clnt_encrypt); } else { compout = datafd; encpid = -1; } /* now do the client-side compression */ if(dle->compress == COMP_FAST || dle->compress == COMP_BEST) { compopt = skip_argument; #if defined(COMPRESS_BEST_OPT) && defined(COMPRESS_FAST_OPT) if(dle->compress == COMP_BEST) { compopt = COMPRESS_BEST_OPT; } else { compopt = COMPRESS_FAST_OPT; } #endif comppid = pipespawn(COMPRESS_PATH, STDIN_PIPE, 0, &dumpout, &compout, &mesgfd, COMPRESS_PATH, compopt, NULL); if(compopt != skip_argument) { dbprintf(_("compress pid %ld: %s %s\n"), (long)comppid, COMPRESS_PATH, compopt); } else { dbprintf(_("compress pid %ld: %s\n"), (long)comppid, COMPRESS_PATH); } } else if (dle->compress == COMP_CUST) { compopt = skip_argument; comppid = pipespawn(dle->compprog, STDIN_PIPE, 0, &dumpout, &compout, &mesgfd, dle->compprog, compopt, NULL); if(compopt != skip_argument) { dbprintf(_("pid %ld: %s %s\n"), (long)comppid, dle->compprog, compopt); } else { dbprintf(_("pid %ld: %s\n"), (long)comppid, dle->compprog); } } else { dumpout = compout; comppid = -1; } cur_dumptime = time(0); bsu = backup_support_option(dle->program, g_options, dle->disk, dle->device, &errarray); if (!bsu) { char *errmsg; char *qerrmsg; guint i; for (i=0; i < errarray->len; i++) { errmsg = g_ptr_array_index(errarray, i); qerrmsg = quote_string(errmsg); fdprintf(mesgfd, _("sendbackup: error [Application '%s': %s]\n"), dle->program, errmsg); dbprintf("aa: %s\n",qerrmsg); amfree(qerrmsg); } if (i == 0) { /* no errarray */ errmsg = vstrallocf(_("Can't execute application '%s'"), dle->program); qerrmsg = quote_string(errmsg); fdprintf(mesgfd, _("sendbackup: error [%s]\n"), errmsg); dbprintf(_("ERROR %s\n"), qerrmsg); amfree(qerrmsg); amfree(errmsg); } return 0; } if (pipe(errfd) < 0) { char *errmsg; char *qerrmsg; errmsg = vstrallocf(_("Application '%s': can't create pipe"), dle->program); qerrmsg = quote_string(errmsg); fdprintf(mesgfd, _("sendbackup: error [%s]\n"), errmsg); dbprintf(_("ERROR %s\n"), qerrmsg); amfree(qerrmsg); amfree(errmsg); return 0; } switch(application_api_pid=fork()) { case 0: argv_ptr = g_ptr_array_new(); cmd = vstralloc(APPLICATION_DIR, "/", dle->program, NULL); g_ptr_array_add(argv_ptr, stralloc(dle->program)); g_ptr_array_add(argv_ptr, stralloc("backup")); if (bsu->message_line == 1) { g_ptr_array_add(argv_ptr, stralloc("--message")); g_ptr_array_add(argv_ptr, stralloc("line")); } if (g_options->config && bsu->config == 1) { g_ptr_array_add(argv_ptr, stralloc("--config")); g_ptr_array_add(argv_ptr, stralloc(g_options->config)); } if (g_options->hostname && bsu->host == 1) { g_ptr_array_add(argv_ptr, stralloc("--host")); g_ptr_array_add(argv_ptr, stralloc(g_options->hostname)); } if (dle->disk && bsu->disk == 1) { g_ptr_array_add(argv_ptr, stralloc("--disk")); g_ptr_array_add(argv_ptr, stralloc(dle->disk)); } g_ptr_array_add(argv_ptr, stralloc("--device")); g_ptr_array_add(argv_ptr, stralloc(dle->device)); if (level <= bsu->max_level) { g_ptr_array_add(argv_ptr, stralloc("--level")); g_snprintf(levelstr,19,"%d",level); g_ptr_array_add(argv_ptr, stralloc(levelstr)); } if (indexfd != -1 && bsu->index_line == 1) { g_ptr_array_add(argv_ptr, stralloc("--index")); g_ptr_array_add(argv_ptr, stralloc("line")); } if (dle->record && bsu->record == 1) { g_ptr_array_add(argv_ptr, stralloc("--record")); } application_property_add_to_argv(argv_ptr, dle, bsu); for (scriptlist = dle->scriptlist; scriptlist != NULL; scriptlist = scriptlist->next) { script = (script_t *)scriptlist->data; if (script->result && script->result->proplist) { property_add_to_argv(argv_ptr, script->result->proplist); } } g_ptr_array_add(argv_ptr, NULL); dbprintf(_("%s: running \"%s\n"), get_pname(), cmd); for (j = 1; j < argv_ptr->len - 1; j++) dbprintf(" %s\n", (char *)g_ptr_array_index(argv_ptr,j)); dbprintf(_("\"\n")); if(dup2(dumpout, 1) == -1) { error(_("Can't dup2: %s"),strerror(errno)); /*NOTREACHED*/ } if (dup2(errfd[1], 2) == -1) { error(_("Can't dup2: %s"),strerror(errno)); /*NOTREACHED*/ } if(dup2(mesgfd, 3) == -1) { error(_("Can't dup2: %s"),strerror(errno)); /*NOTREACHED*/ } if(indexfd > 0) { if(dup2(indexfd, 4) == -1) { error(_("Can't dup2: %s"),strerror(errno)); /*NOTREACHED*/ } fcntl(indexfd, F_SETFD, 0); } application_api_info_tapeheader(mesgfd, dle->program, dle); if (indexfd != 0) { safe_fd(3, 2); } else { safe_fd(3, 1); } execve(cmd, (char **)argv_ptr->pdata, safe_env()); exit(1); break; default: break; case -1: error(_("%s: fork returned: %s"), get_pname(), strerror(errno)); } close(errfd[1]); dumperr = fdopen(errfd[0],"r"); if (!dumperr) { error(_("Can't fdopen: %s"), strerror(errno)); /*NOTREACHED*/ } result = 0; while ((line = agets(dumperr)) != NULL) { if (strlen(line) > 0) { fdprintf(mesgfd, "sendbackup: error [%s]\n", line); dbprintf("error: %s\n", line); result = 1; } amfree(line); } result |= check_result(mesgfd); if (result == 0) { char *amandates_file; amandates_file = getconf_str(CNF_AMANDATES); if(start_amandates(amandates_file, 1)) { amandates_updateone(dle->disk, level, cur_dumptime); finish_amandates(); free_amandates(); } else { if (GPOINTER_TO_INT(dle->estimatelist->data) == ES_CALCSIZE && bsu->calcsize) { error(_("error [opening %s for writing: %s]"), amandates_file, strerror(errno)); } else { g_debug(_("non-fatal error opening '%s' for writing: %s]"), amandates_file, strerror(errno)); } } } amfree(bsu); } else { if(!interactive) { /* redirect stderr */ if(dup2(mesgfd, 2) == -1) { dbprintf(_("Error redirecting stderr to fd %d: %s\n"), mesgfd, strerror(errno)); dbclose(); exit(1); } } if(pipe(mesgpipe) == -1) { s = strerror(errno); dbprintf(_("error [opening mesg pipe: %s]\n"), s); error(_("error [opening mesg pipe: %s]"), s); } program->start_backup(dle, g_options->hostname, datafd, mesgpipe[1], indexfd); dbprintf(_("Started backup\n")); parse_backup_messages(dle, mesgpipe[0]); dbprintf(_("Parsed backup messages\n")); } run_client_scripts(EXECUTE_ON_POST_DLE_BACKUP, g_options, dle, mesgstream); fflush(mesgstream); amfree(qdisk); amfree(qamdevice); amfree(dumpdate); amfree(stroptions); amfree(our_feature_string); am_release_feature_set(our_features); our_features = NULL; free_g_options(g_options); dbclose(); return 0; err: if (err_extra) { g_printf(_("ERROR FORMAT ERROR IN REQUEST PACKET '%s'\n"), err_extra); dbprintf(_("REQ packet is bogus: %s\n"), err_extra); } else { g_printf(_("ERROR FORMAT ERROR IN REQUEST PACKET\n")); dbprintf(_("REQ packet is bogus\n")); } amfree(qdisk); amfree(qamdevice); amfree(dumpdate); amfree(stroptions); amfree(our_feature_string); dbclose(); return 1; } /* * Returns a string for a child process. Checks the saved dump and * compress pids to see which it is. */ char * childstr( pid_t pid) { if(pid == dumppid) return program->backup_name; if(pid == comppid) return "compress"; if(pid == encpid) return "encrypt"; if(pid == indexpid) return "index"; if(pid == application_api_pid) { if (!gdle) { dbprintf("gdle == NULL\n"); return "gdle == NULL"; } return gdle->program; } return "unknown"; } /* * Determine if the child return status really indicates an error. * If so, add the error message to the error string; more than one * child can have an error. */ int check_status( pid_t pid, amwait_t w, int mesgfd) { char *thiserr = NULL; char *str, *strX; int ret, sig, rc; str = childstr(pid); if(WIFSIGNALED(w)) { ret = 0; rc = sig = WTERMSIG(w); } else { sig = 0; rc = ret = WEXITSTATUS(w); } if(pid == indexpid) { /* * Treat an index failure (other than signal) as a "STRANGE" * rather than an error so the dump goes ahead and gets processed * but the failure is noted. */ if(ret != 0) { fdprintf(mesgfd, _("? index %s returned %d\n"), str, ret); rc = 0; } indexpid = -1; strX = "index"; } else if(pid == comppid) { /* * compress returns 2 sometimes, but it is ok. */ #ifndef HAVE_GZIP if(ret == 2) { rc = 0; } #endif comppid = -1; strX = "compress"; } else if(pid == dumppid && tarpid == -1) { /* * Ultrix dump returns 1 sometimes, but it is ok. */ #ifdef DUMP_RETURNS_1 if(ret == 1) { rc = 0; } #endif dumppid = -1; strX = "dump"; } else if(pid == tarpid) { if (ret == 1) { rc = 0; } /* * tar bitches about active filesystems, but we do not care. */ #ifdef IGNORE_TAR_ERRORS if(ret == 2) { rc = 0; } #endif dumppid = tarpid = -1; strX = "dump"; } else if(pid == application_api_pid) { strX = "Application"; } else { strX = "unknown"; } if(rc == 0) { return 0; /* normal exit */ } if(ret == 0) { thiserr = vstrallocf(_("%s (%d) %s got signal %d"), strX, (int)pid, str, sig); } else { thiserr = vstrallocf(_("%s (%d) %s returned %d"), strX, (int)pid, str, ret); } fdprintf(mesgfd, "? %s\n", thiserr); if(errorstr) { errorstr = newvstrallocf(errorstr, "%s, %s", errorstr, thiserr); amfree(thiserr); } else { errorstr = thiserr; thiserr = NULL; } return 1; } /* *Send header info to the message file. */ void info_tapeheader( dle_t *dle) { g_fprintf(stderr, "%s: info BACKUP=%s\n", get_pname(), program->backup_name); g_fprintf(stderr, "%s: info RECOVER_CMD=", get_pname()); if (dle->compress == COMP_FAST || dle->compress == COMP_BEST) g_fprintf(stderr, "%s %s |", UNCOMPRESS_PATH, #ifdef UNCOMPRESS_OPT UNCOMPRESS_OPT #else "" #endif ); g_fprintf(stderr, "%s -xpGf - ...\n", program->restore_name); if (dle->compress == COMP_FAST || dle->compress == COMP_BEST) g_fprintf(stderr, "%s: info COMPRESS_SUFFIX=%s\n", get_pname(), COMPRESS_SUFFIX); g_fprintf(stderr, "%s: info end\n", get_pname()); } void application_api_info_tapeheader( int mesgfd, char *prog, dle_t *dle) { char line[1024]; g_snprintf(line, 1024, "%s: info BACKUP=APPLICATION\n", get_pname()); if (full_write(mesgfd, line, strlen(line)) != strlen(line)) { dbprintf(_("error writing to mesgfd socket: %s"), strerror(errno)); return; } g_snprintf(line, 1024, "%s: info APPLICATION=%s\n", get_pname(), prog); if (full_write(mesgfd, line, strlen(line)) != strlen(line)) { dbprintf(_("error writing to mesgfd socket: %s"), strerror(errno)); return; } g_snprintf(line, 1024, "%s: info RECOVER_CMD=", get_pname()); if (full_write(mesgfd, line, strlen(line)) != strlen(line)) { dbprintf(_("error writing to mesgfd socket: %s"), strerror(errno)); return; } if (dle->compress == COMP_FAST || dle->compress == COMP_BEST) { g_snprintf(line, 1024, "%s %s |", UNCOMPRESS_PATH, #ifdef UNCOMPRESS_OPT UNCOMPRESS_OPT #else "" #endif ); if (full_write(mesgfd, line, strlen(line)) != strlen(line)) { dbprintf(_("error writing to mesgfd socket: %s"), strerror(errno)); return; } } g_snprintf(line, 1024, "%s/%s restore [./file-to-restore]+\n", APPLICATION_DIR, prog); if (full_write(mesgfd, line, strlen(line)) != strlen(line)) { dbprintf(_("error writing to mesgfd socket: %s"), strerror(errno)); return; } if (dle->compress) { g_snprintf(line, 1024, "%s: info COMPRESS_SUFFIX=%s\n", get_pname(), COMPRESS_SUFFIX); if (full_write(mesgfd, line, strlen(line)) != strlen(line)) { dbprintf(_("error writing to mesgfd socket: %s"), strerror(errno)); return; } } g_snprintf(line, 1024, "%s: info end\n", get_pname()); if (full_write(mesgfd, line, strlen(line)) != strlen(line)) { dbprintf(_("error writing to mesgfd socket: %s"), strerror(errno)); return; } } pid_t pipefork( void (*func)(void), char * fname, int * stdinfd, int stdoutfd, int stderrfd) { int inpipe[2]; pid_t pid; dbprintf(_("Forking function %s in pipeline\n"), fname); if(pipe(inpipe) == -1) { error(_("error [open pipe to %s: %s]"), fname, strerror(errno)); /*NOTREACHED*/ } switch(pid = fork()) { case -1: error(_("error [fork %s: %s]"), fname, strerror(errno)); /*NOTREACHED*/ default: /* parent process */ aclose(inpipe[0]); /* close input side of pipe */ *stdinfd = inpipe[1]; break; case 0: /* child process */ aclose(inpipe[1]); /* close output side of pipe */ if(dup2(inpipe[0], 0) == -1) { error(_("error [fork %s: dup2(%d, in): %s]"), fname, inpipe[0], strerror(errno)); /*NOTRACHED*/ } if(dup2(stdoutfd, 1) == -1) { error(_("error [fork %s: dup2(%d, out): %s]"), fname, stdoutfd, strerror(errno)); /*NOTRACHED*/ } if(dup2(stderrfd, 2) == -1) { error(_("error [fork %s: dup2(%d, err): %s]"), fname, stderrfd, strerror(errno)); /*NOTRACHED*/ } func(); exit(0); /*NOTREACHED*/ } return pid; } int check_result( int mesgfd) { int goterror; pid_t wpid; amwait_t retstat; goterror = 0; while((wpid = waitpid((pid_t)-1, &retstat, WNOHANG)) > 0) { if(check_status(wpid, retstat, mesgfd)) goterror = 1; } if (dumppid != -1) { sleep(5); while((wpid = waitpid((pid_t)-1, &retstat, WNOHANG)) > 0) { if(check_status(wpid, retstat, mesgfd)) goterror = 1; } } if (dumppid != -1) { dbprintf(_("Sending SIGHUP to dump process %d\n"), (int)dumppid); if(dumppid != -1) { if(kill(dumppid, SIGHUP) == -1) { dbprintf(_("Can't send SIGHUP to %d: %s\n"), (int)dumppid, strerror(errno)); } } sleep(5); while((wpid = waitpid((pid_t)-1, &retstat, WNOHANG)) > 0) { if(check_status(wpid, retstat, mesgfd)) goterror = 1; } } if (dumppid != -1) { dbprintf(_("Sending SIGKILL to dump process %d\n"), (int)dumppid); if(dumppid != -1) { if(kill(dumppid, SIGKILL) == -1) { dbprintf(_("Can't send SIGKILL to %d: %s\n"), (int)dumppid, strerror(errno)); } } sleep(5); while((wpid = waitpid((pid_t)-1, &retstat, WNOHANG)) > 0) { if(check_status(wpid, retstat, mesgfd)) goterror = 1; } } return goterror; } void parse_backup_messages( dle_t *dle, int mesgin) { int goterror; char *line; amfree(errorstr); for(; (line = areads(mesgin)) != NULL; free(line)) { process_dumpline(line); } if(errno) { error(_("error [read mesg pipe: %s]"), strerror(errno)); /*NOTREACHED*/ } goterror = check_result(mesgfd); if(errorstr) { error(_("error [%s]"), errorstr); /*NOTREACHED*/ } else if(dump_size == -1) { error(_("error [no backup size line]")); /*NOTREACHED*/ } program->end_backup(dle, goterror); fdprintf(mesgfd, _("%s: size %ld\n"), get_pname(), dump_size); fdprintf(mesgfd, _("%s: end\n"), get_pname()); } static void process_dumpline( char * str) { amregex_t *rp; char *type; char startchr; for(rp = program->re_table; rp->regex != NULL; rp++) { if(match(rp->regex, str)) { break; } } if(rp->typ == DMP_SIZE) { dump_size = (long)((the_num(str, rp->field)* rp->scale+1023.0)/1024.0); } switch(rp->typ) { case DMP_NORMAL: type = "normal"; startchr = '|'; break; case DMP_STRANGE: type = "strange"; startchr = '?'; break; case DMP_SIZE: type = "size"; startchr = '|'; break; case DMP_ERROR: type = "error"; startchr = '?'; break; default: /* * Should never get here. */ type = "unknown"; startchr = '!'; break; } dbprintf("%3d: %7s(%c): %s\n", rp->srcline, type, startchr, str); fdprintf(mesgfd, "%c %s\n", startchr, str); } /* * start_index. Creates an index file from the output of dump/tar. * It arranges that input is the fd to be written by the dump process. * If createindex is not enabled, it does nothing. If it is not, a * new process will be created that tees input both to a pipe whose * read fd is dup2'ed input and to a program that outputs an index * file to `index'. * * make sure that the chat from restore doesn't go to stderr cause * this goes back to amanda which doesn't expect to see it * (2>/dev/null should do it) * * Originally by Alan M. McIvor, 13 April 1996 * * Adapted by Alexandre Oliva, 1 May 1997 * * This program owes a lot to tee.c from GNU sh-utils and dumptee.c * from the DeeJay backup package. */ static void save_fd( int * fd, int min) { int origfd = *fd; while (*fd >= 0 && *fd < min) { int newfd = dup(*fd); if (newfd == -1) dbprintf(_("Unable to save file descriptor [%s]\n"), strerror(errno)); *fd = newfd; } if (origfd != *fd) dbprintf(_("Dupped file descriptor %i to %i\n"), origfd, *fd); } void start_index( int createindex, int input, int mesg, int index, char * cmd) { int pipefd[2]; FILE *pipe_fp; int exitcode; if (!createindex) return; if (pipe(pipefd) != 0) { error(_("creating index pipe: %s"), strerror(errno)); /*NOTREACHED*/ } switch(indexpid = fork()) { case -1: error(_("forking index tee process: %s"), strerror(errno)); /*NOTREACHED*/ default: aclose(pipefd[0]); if (dup2(pipefd[1], input) == -1) { error(_("dup'ping index tee output: %s"), strerror(errno)); /*NOTREACHED*/ } aclose(pipefd[1]); return; case 0: break; } /* now in a child process */ save_fd(&pipefd[0], 4); save_fd(&index, 4); save_fd(&mesg, 4); save_fd(&input, 4); dup2(pipefd[0], 0); dup2(index, 1); dup2(mesg, 2); dup2(input, 3); for(index = 4; index < (int)FD_SETSIZE; index++) { if (index != dbfd()) { close(index); } } if ((pipe_fp = popen(cmd, "w")) == NULL) { error(_("couldn't start index creator [%s]"), strerror(errno)); /*NOTREACHED*/ } dbprintf(_("Started index creator: \"%s\"\n"), cmd); while(1) { char buffer[BUFSIZ], *ptr; ssize_t bytes_read; size_t bytes_written; size_t just_written; do { bytes_read = read(0, buffer, SIZEOF(buffer)); } while ((bytes_read < 0) && ((errno == EINTR) || (errno == EAGAIN))); if (bytes_read < 0) { error(_("index tee cannot read [%s]"), strerror(errno)); /*NOTREACHED*/ } if (bytes_read == 0) break; /* finished */ /* write the stuff to the subprocess */ ptr = buffer; bytes_written = 0; just_written = full_write(fileno(pipe_fp), ptr, (size_t)bytes_read); if (just_written < (size_t)bytes_read) { /* * just as we waited for write() to complete. */ if (errno != EPIPE) { dbprintf(_("Index tee cannot write to index creator [%s]\n"), strerror(errno)); } } else { bytes_written += just_written; ptr += just_written; } /* write the stuff to stdout, ensuring none lost when interrupt occurs */ ptr = buffer; bytes_written = 0; just_written = full_write(3, ptr, bytes_read); if (just_written < (size_t)bytes_read) { error(_("index tee cannot write [%s]"), strerror(errno)); /*NOTREACHED*/ } else { bytes_written += just_written; ptr += just_written; } } aclose(pipefd[1]); /* finished */ /* check the exit code of the pipe and moan if not 0 */ if ((exitcode = pclose(pipe_fp)) != 0) { char *exitstr = str_exit_status("Index pipe", exitcode); dbprintf("%s\n", exitstr); amfree(exitstr); } else { dbprintf(_("Index created successfully\n")); } pipe_fp = NULL; exit(exitcode); } extern backup_program_t dump_program, gnutar_program; backup_program_t *programs[] = { &dump_program, &gnutar_program, NULL };
25.245325
87
0.607442
[ "3d" ]
21a84845bc9832151b4764c01b6ff5b686a52992
1,193
h
C
Engine/Source/Runtime/Engine/Classes/Particles/Size/ParticleModuleSizeScaleBySpeed.h
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
Engine/Source/Runtime/Engine/Classes/Particles/Size/ParticleModuleSizeScaleBySpeed.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/Particles/Size/ParticleModuleSizeScaleBySpeed.h
PopCap/GameIdea
201e1df50b2bc99afc079ce326aa0a44b178a391
[ "BSD-2-Clause" ]
null
null
null
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. /*============================================================================== ParticleModuleSizeScaleBySpeed: Scale the size of a particle by its velocity. ==============================================================================*/ #pragma once #include "Particles/Size/ParticleModuleSizeBase.h" #include "ParticleModuleSizeScaleBySpeed.generated.h" UCLASS(editinlinenew, hidecategories=Object, meta=(DisplayName = "Size By Speed")) class UParticleModuleSizeScaleBySpeed : public UParticleModuleSizeBase { GENERATED_UCLASS_BODY() /** By how much speed affects the size of the particle in each dimension. */ UPROPERTY(EditAnywhere, Category=ParticleModuleSizeScaleBySpeed) FVector2D SpeedScale; /** The maximum amount by which to scale a particle in each dimension. */ UPROPERTY(EditAnywhere, Category=ParticleModuleSizeScaleBySpeed) FVector2D MaxScale; // Begin UParticleModule Interface virtual void Update(FParticleEmitterInstance* Owner, int32 Offset, float DeltaTime) override; virtual void CompileModule(struct FParticleEmitterBuildInfo& EmitterInfo) override; // End UParticleModule Interface };
36.151515
94
0.700754
[ "object" ]
21a98fa67080fc15a2119a2f94c54ba24ddb5eeb
5,825
c
C
sdk-6.5.20/libs/sdklt/bcmlta/bcmltx/bcm56880_a0/dna_4_6_6/bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_xfrm_handler.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
sdk-6.5.20/libs/sdklt/bcmlta/bcmltx/bcm56880_a0/dna_4_6_6/bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_xfrm_handler.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
sdk-6.5.20/libs/sdklt/bcmlta/bcmltx/bcm56880_a0/dna_4_6_6/bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_xfrm_handler.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
/******************************************************************************* * * DO NOT EDIT THIS FILE! * This file is auto-generated by fltg from Logical Table mapping files. * * Tool: $SDK/INTERNAL/fltg/bin/fltg * * Edits to this file will be lost when it is regenerated. * * This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file. * * Copyright 2007-2020 Broadcom Inc. All rights reserved. */ /* Logical Table Adaptor for component bcmltx */ /* Handler: bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_xfrm_handler */ #include <bcmlrd/bcmlrd_types.h> #include <bcmltd/chip/bcmltd_id.h> #include <bcmltx/bcmltx_field_demux_wide.h> #include <bcmdrd/chip/bcm56880_a0_enum.h> #include <bcmlrd/chip/bcm56880_a0/dna_4_6_6/bcm56880_a0_dna_4_6_6_lrd_xfrm_field_desc.h> extern const bcmltd_field_desc_t bcm56880_a0_dna_4_6_6_lrd_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_src_field_desc_s0[]; static const bcmltd_field_desc_t bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_dst_field_desc[3] = { { .field_id = BCMLTD_INTERNAL_FIELD_BASE + 103, .field_idx = 0, .minbit = 305, .maxbit = 359, .entry_idx = 0, .sym = "IFTA80_E2T_03_B0_QUADm.TABLE_FIELDS_2f[116:62]", .reserved = 0 }, { .field_id = BCMLTD_INTERNAL_FIELD_BASE + 104, .field_idx = 0, .minbit = 363, .maxbit = 371, .entry_idx = 0, .sym = "IFTA80_E2T_03_B0_QUADm.TABLE_FIELDS_3f[8:0]", .reserved = 0 }, { .field_id = BCMLTD_INTERNAL_FIELD_BASE + 105, .field_idx = 0, .minbit = 158, .maxbit = 221, .entry_idx = 0, .sym = "IFTA80_E2T_03_B0_QUADm.TABLE_FIELDS_1f[98:35]", .reserved = 0 }, }; static const bcmltd_field_list_t bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_src_list_s0 = { .field_num = 3, .field_array = bcm56880_a0_dna_4_6_6_lrd_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_src_field_desc_s0 }; static const bcmltd_field_list_t bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_dst_list_d0 = { .field_num = 3, .field_array = bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_dst_field_desc }; static const uint32_t bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_transform_src_s0[1] = { BCM56880_A0_DNA_4_6_6_L3_IPV6_MULTICAST_2_TABLEt_IP_HDR_DIPf, }; static const uint32_t bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_transform_dst_d0[3] = { BCMLTD_INTERNAL_FIELD_BASE + 103, BCMLTD_INTERNAL_FIELD_BASE + 104, BCMLTD_INTERNAL_FIELD_BASE + 105, }; static const bcmltd_generic_arg_t bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_comp_data = { .sid = BCM56880_A0_DNA_4_6_6_L3_IPV6_MULTICAST_2_TABLEt, .values = 0, .value = NULL, .user_data = NULL }; static const bcmltd_transform_arg_t bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_xfrm_handler_fwd_arg_s0_d0 = { .values = 0, .value = NULL, .tables = 0, .table = NULL, .fields = 1, .field = bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_transform_src_s0, .field_list = &bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_src_list_s0, .rfields = 3, .rfield = bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_transform_dst_d0, .rfield_list = &bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_dst_list_d0, .comp_data = &bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_comp_data }; static const bcmltd_transform_arg_t bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_xfrm_handler_rev_arg_s0_d0 = { .values = 0, .value = NULL, .tables = 0, .table = NULL, .fields = 3, .field = bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_transform_dst_d0, .field_list = &bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_dst_list_d0, .rfields = 1, .rfield = bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_transform_src_s0, .rfield_list = &bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_src_list_s0, .comp_data = &bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_comp_data }; const bcmltd_xfrm_handler_t bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_xfrm_handler_fwd_s0_d0 = { .transform = bcmltx_field_demux_wide_transform, .arg = &bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_xfrm_handler_fwd_arg_s0_d0 }; const bcmltd_xfrm_handler_t bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_xfrm_handler_rev_s0_d0 = { .transform = bcmltx_field_mux_wide_transform, .arg = &bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_wide_l3_ipv6_multicast_2_tablet_ip_hdr_dipf_0_xfrm_handler_rev_arg_s0_d0 };
43.796992
139
0.778541
[ "transform" ]
21d247fac956d11a92b88ee2296f32c80ca66242
3,118
h
C
Projects/Editor/Source/Editor/Space/Assets/CListFSController.h
tsukoyumi/skylicht-engine
3b88d9718e87e552152633ef60e3f889869b71de
[ "MIT" ]
null
null
null
Projects/Editor/Source/Editor/Space/Assets/CListFSController.h
tsukoyumi/skylicht-engine
3b88d9718e87e552152633ef60e3f889869b71de
[ "MIT" ]
null
null
null
Projects/Editor/Source/Editor/Space/Assets/CListFSController.h
tsukoyumi/skylicht-engine
3b88d9718e87e552152633ef60e3f889869b71de
[ "MIT" ]
null
null
null
/* !@ MIT License Copyright (c) 2020 Skylicht Technology CO., LTD Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the Rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. This file is part of the "Skylicht Engine". https://github.com/skylicht-lab/skylicht-engine !# */ #pragma once #include "GUI/GUI.h" #include "AssetManager/CAssetManager.h" namespace Skylicht { namespace Editor { class CTreeFSController; class CSearchAssetController; class CListFSController { protected: GUI::CCanvas* m_canvas; GUI::CListBox* m_listFS; GUI::CListRowItem* m_renameItem; std::wstring m_renameRevert; CTreeFSController* m_treeController; CSearchAssetController* m_searchController; CAssetManager* m_assetManager; std::string m_currentFolder; std::string m_selectSearchPath; GUI::CMessageBox* m_msgBox; GUI::CListRowItem* m_newFolderItem; bool m_searching; public: CListFSController(GUI::CCanvas* canvas, GUI::CListBox* list); virtual ~CListFSController(); void OnPress(GUI::CBase* item); void OnSelected(GUI::CBase* item); void OnKeyPress(GUI::CBase* control, int key, bool press); void OnFileOpen(GUI::CBase* node); void refresh(); void setTreeController(CTreeFSController* treeController) { m_treeController = treeController; } void setSearchController(CSearchAssetController* searchController) { m_searchController = searchController; } void rename(GUI::CListRowItem* node); void initDragDrop(GUI::CListRowItem* item); void OnRename(GUI::CBase* control); void OnCancelRename(GUI::CBase* control); void removePath(const char* path); void scrollAndSelectPath(const char* path); void newFolder(const char* parent); void OnRenameFolder(GUI::CBase* control); void OnCancelRenameFolder(GUI::CBase* control); const std::string& getCurrentFolder() { return m_currentFolder; } void enableSearching(bool b) { m_searching = b; if (b == true) m_selectSearchPath = ""; } bool isSearching() { return m_searching; } public: void add(const std::string& currentFolder, std::vector<SFileInfo>& files); }; } }
23.984615
141
0.737332
[ "vector" ]
21d2e0d5321e1ecfb024c4a502e3cc1e37e0095c
2,332
h
C
engine/src/physics/ObjectProperties.h
targodan/gameProgramming
5c0b36bee271dca65636d0317324a2bb786613f0
[ "MIT" ]
1
2019-07-14T11:32:30.000Z
2019-07-14T11:32:30.000Z
engine/src/physics/ObjectProperties.h
targodan/gameProgramming
5c0b36bee271dca65636d0317324a2bb786613f0
[ "MIT" ]
null
null
null
engine/src/physics/ObjectProperties.h
targodan/gameProgramming
5c0b36bee271dca65636d0317324a2bb786613f0
[ "MIT" ]
null
null
null
#ifndef OBJECTPROPERTIES_H #define OBJECTPROPERTIES_H #include <eigen3/Eigen/Eigen> #include "../util/vector.h" #include "../renderer/Vertex.h" #include "../renderer/Mesh.h" #include "../IllegalArgumentException.h" namespace engine { namespace physics { using namespace Eigen; using engine::util::vector; struct ObjectProperties { ObjectProperties(const VectorXf& allVertices, const vector<size_t>& surfaceVertexIndices, const VectorXf& surfaceAreaPerVertex, const VectorXf& massPerVertex) : allVertices(allVertices), surfaceVertexIndices(surfaceVertexIndices), surfaceAreaPerVertex(surfaceAreaPerVertex), massPerVertex(massPerVertex) { if(surfaceVertexIndices.size() > static_cast<size_t>(allVertices.rows()) / 3) { throw IllegalArgumentException("You specified more vertices to be part of the surface than there are vertices."); } if(static_cast<size_t>(surfaceAreaPerVertex.rows()) != surfaceVertexIndices.size()) { throw IllegalArgumentException("There should be equal amounts of surface vertices and elements in surfaceAreaPerVertex."); } if(massPerVertex.rows() != allVertices.rows() / 3) { throw IllegalArgumentException("There should be equal amounts of all vertices and elements in massPerVertex."); } } ObjectProperties(const ObjectProperties& orig); ObjectProperties(ObjectProperties&& orig); ObjectProperties& operator=(const ObjectProperties& orig); ObjectProperties& operator=(ObjectProperties&& orig); VectorXf allVertices; vector<size_t> surfaceVertexIndices; VectorXf surfaceAreaPerVertex; VectorXf massPerVertex; VectorXf getSurfaceVertices() const; VectorXf mapSurfaceForcesToAllVertices(const VectorXf& surfaceForces) const; #include "ObjectProperties__helper.h" }; } } #endif /* OBJECTPROPERTIES_H */
38.866667
142
0.598199
[ "mesh", "vector" ]
21dcb09781572d871339284d4297b1f77d73e7ca
410
h
C
source/lib/tuple.h
IanFinlayson/tetra
10f5e6e2bf52340b5162850d32c480400d6d7521
[ "MIT" ]
5
2017-01-21T01:53:30.000Z
2021-06-20T04:25:40.000Z
source/lib/tuple.h
IanFinlayson/tetra
10f5e6e2bf52340b5162850d32c480400d6d7521
[ "MIT" ]
6
2017-02-21T13:23:06.000Z
2019-01-28T21:34:10.000Z
source/lib/tuple.h
IanFinlayson/tetra
10f5e6e2bf52340b5162850d32c480400d6d7521
[ "MIT" ]
2
2015-02-24T16:40:48.000Z
2015-04-16T22:29:48.000Z
/* tuple.h * declares the tuple class which represents a Tetra Tuple object */ #ifndef TUPLE_H #define TUPLE_H #include "list.h" /* the List class */ class Tuple : public List { private: static const String L_DELIM; static const String R_DELIM; protected: String getLDelim() const { return L_DELIM; } String getRDelim() const { return R_DELIM; } }; #endif
15.185185
68
0.643902
[ "object" ]
21df103b4e7d7a92791094a86279734625bac2a3
50,852
h
C
Sources/Sample/HelloCarDemo/Android/HelloElastosDemo/app/src/main/jni/elastos/include/elastos/utility/Arrays.h
xiaoweiruby/Elastos.RT
238e9b747f70fc129769ae7850def4362c43e443
[ "Apache-2.0" ]
1
2019-04-15T13:08:56.000Z
2019-04-15T13:08:56.000Z
Sources/Sample/RPC/Switch/RPCServer/app/src/main/cpp/elastos/inc/elastos/utility/Arrays.h
xiaoweiruby/Elastos.RT
238e9b747f70fc129769ae7850def4362c43e443
[ "Apache-2.0" ]
null
null
null
Sources/Sample/RPC/Switch/RPCServer/app/src/main/cpp/elastos/inc/elastos/utility/Arrays.h
xiaoweiruby/Elastos.RT
238e9b747f70fc129769ae7850def4362c43e443
[ "Apache-2.0" ]
null
null
null
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // 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 __ELASTOS_UTILITY_ARRAYS_H__ #define __ELASTOS_UTILITY_ARRAYS_H__ //#include "elastos/utility/AbstractList.h" #include "Elastos.CoreLibrary.Utility.h" #include "elastos/core/Object.h" #include "elastos/core/StringBuilder.h" #include "elastos/core/Math.h" #include "elastos/utility/DualPivotQuicksort.h" #include "elastos/utility/ComparableTimSort.h" #include "elastos/utility/TimSort.h" #include "elastos/utility/logging/Logger.h" using Elastos::Core::IComparator; using Elastos::Core::IComparable; using Elastos::Core::StringBuilder; using Elastos::Core::IArrayOf; using Elastos::IO::ISerializable; //using Elastos::Utility::Logging::Logger; namespace Elastos { namespace Utility { class ECO_PUBLIC Arrays { private: // class ArrayList // : public AbstractList // , public ISerializable // , public IRandomAccess // { // public: // CAR_INTERFACE_DECL() // ArrayList( // /* [in] */ ArrayOf<IInterface *> * storage); // CARAPI Contains( // /* [in] */ IInterface * object, // /* [out] */ Boolean* result); // CARAPI Get( // /* [in] */ Int32 location, // /* [out] */ IInterface ** result); // CARAPI IndexOf( // /* [in] */ IInterface * object, // /* [out] */ Int32* result); // CARAPI LastIndexOf( // /* [in] */ IInterface * object, // /* [out] */ Int32* index); // CARAPI Set( // /* [in] */ Int32 location, // /* [in] */ IInterface * object, // /* [out] */ IInterface ** result); // CARAPI GetSize( // /* [out] */ Int32* size); // CARAPI ToArray( // /* [out] */ ArrayOf<IInterface *> ** outArray); // CARAPI ToArray( // /* [in] */ ArrayOf<IInterface *> * contents, // /* [out] */ ArrayOf<IInterface *> ** outArray); // private: // AutoPtr<ArrayOf<IInterface *> > mA; // }; public: template<typename T> static CARAPI FromList( /* [in] */ IList* inList, /* [out, callee] */ ArrayOf<T*> ** array); template<typename T> static CARAPI AsList( /* [in] */ ArrayOf<T> * array, /* [out] */ IList** outList); template<typename T> static CARAPI AsList( /* [in] */ const AutoPtr<ArrayOf<T> > & array, /* [out] */ IList** outList); // Notes: there is not implementation for converting ArrayOf<Boolean> to IList. // static CARAPI AsList( /* [in] */ ArrayOf<Byte> * array, /* [out] */ IList** outList); static CARAPI AsList( /* [in] */ ArrayOf<Char32> * array, /* [out] */ IList** outList); static CARAPI AsList( /* [in] */ ArrayOf<Int16> * array, /* [out] */ IList** outList); static CARAPI AsList( /* [in] */ ArrayOf<Int32> * array, /* [out] */ IList** outList); static CARAPI AsList( /* [in] */ ArrayOf<Int64> * array, /* [out] */ IList** outList); static CARAPI AsList( /* [in] */ ArrayOf<Float> * array, /* [out] */ IList** outList); static CARAPI AsList( /* [in] */ ArrayOf<Double> * array, /* [out] */ IList** outList); static CARAPI AsList( /* [in] */ ArrayOf<String> * array, /* [out] */ IList** outList); /** * Performs a binary search for {@code value} in the ascending sorted array {@code array}, * in the range specified by fromIndex (inclusive) and toIndex (exclusive). * Searching in an unsorted array has an undefined result. It's also undefined which element * is found if there are multiple occurrences of the same element. * * @param array the sorted array to search. * @param startIndex the inclusive start index. * @param endIndex the exclusive start index. * @param value the element to find. * @return the non-negative index of the element, or a negative index which * is {@code -index - 1} where the element would be inserted. * @throws IllegalArgumentException if {@code startIndex > endIndex} * @throws ArrayIndexOutOfBoundsException if {@code startIndex < 0 || endIndex > array.length} * @since 1.6 */ static CARAPI BinarySearch( /* [in] */ ArrayOf<String>* array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ const String& value, /* [out] */ Int32* index); static CARAPI BinarySearch( /* [in] */ const AutoPtr<ArrayOf<String> > & array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ const String& value, /* [out] */ Int32* index); /** * Performs a binary search for {@code value} in the ascending sorted array {@code array}. * Searching in an unsorted array has an undefined result. It's also undefined which element * is found if there are multiple occurrences of the same element. * * @param array the sorted array to search. * @param value the element to find. * @return the non-negative index of the element, or a negative index which * is {@code -index - 1} where the element would be inserted. */ static CARAPI BinarySearch( /* [in] */ ArrayOf<String>* array, /* [in] */ const String& value, /* [out] */ Int32* index); static CARAPI BinarySearch( /* [in] */ const AutoPtr<ArrayOf<String> > & array, /* [in] */ const String& value, /* [out] */ Int32* index); /** * Performs a binary search for {@code value} in the ascending sorted array {@code array}, * in the range specified by fromIndex (inclusive) and toIndex (exclusive). * Searching in an unsorted array has an undefined result. It's also undefined which element * is found if there are multiple occurrences of the same element. * * @param array the sorted array to search. * @param startIndex the inclusive start index. * @param endIndex the exclusive start index. * @param value the element to find. * @return the non-negative index of the element, or a negative index which * is {@code -index - 1} where the element would be inserted. * @throws IllegalArgumentException if {@code startIndex > endIndex} * @throws ArrayIndexOutOfBoundsException if {@code startIndex < 0 || endIndex > array.length} * @since 1.6 */ template<typename T> static CARAPI BinarySearch( /* [in] */ ArrayOf<T>* array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ T value, /* [out] */ Int32* index); template<typename T> static CARAPI BinarySearch( /* [in] */ const AutoPtr<ArrayOf<T> > & array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ T value, /* [out] */ Int32* index); /** * Performs a binary search for {@code value} in the ascending sorted array {@code array}. * Searching in an unsorted array has an undefined result. It's also undefined which element * is found if there are multiple occurrences of the same element. * * @param array the sorted array to search. * @param value the element to find. * @return the non-negative index of the element, or a negative index which * is {@code -index - 1} where the element would be inserted. */ template<typename T> static CARAPI BinarySearch( /* [in] */ ArrayOf<T>* array, /* [in] */ T value, /* [out] */ Int32* index); template<typename T> static CARAPI BinarySearch( /* [in] */ const AutoPtr<ArrayOf<T> > & array, /* [in] */ T value, /* [out] */ Int32* index); /** * Performs a binary search for {@code value} in the ascending sorted array {@code array}, * in the range specified by fromIndex (inclusive) and toIndex (exclusive). * Searching in an unsorted array has an undefined result. It's also undefined which element * is found if there are multiple occurrences of the same element. * * @param array the sorted array to search. * @param startIndex the inclusive start index. * @param endIndex the exclusive start index. * @param value the element to find. * @return the non-negative index of the element, or a negative index which * is {@code -index - 1} where the element would be inserted. * @throws ClassCastException * if an element in the array or the search element does not * implement {@code Comparable}, or cannot be compared to each other. * @throws IllegalArgumentException if {@code startIndex > endIndex} * @throws ArrayIndexOutOfBoundsException if {@code startIndex < 0 || endIndex > array.length} * @since 1.6 */ template<typename T> static CARAPI BinarySearch( /* [in] */ ArrayOf<T *> * array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ T * value, /* [out] */ Int32* index); template<typename T> static CARAPI BinarySearch( /* [in] */ const AutoPtr<ArrayOf<T *> > & array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ T * value, /* [out] */ Int32* index); /** * Performs a binary search for {@code value} in the ascending sorted array {@code array}. * Searching in an unsorted array has an undefined result. It's also undefined which element * is found if there are multiple occurrences of the same element. * * @param array the sorted array to search. * @param value the element to find. * @return the non-negative index of the element, or a negative index which * is {@code -index - 1} where the element would be inserted. * @throws ClassCastException * if an element in the array or the search element does not * implement {@code Comparable}, or cannot be compared to each other. */ template<typename T> static CARAPI BinarySearch( /* [in] */ ArrayOf<T *> * array, /* [in] */ T * value, /* [out] */ Int32* index); template<typename T> static CARAPI BinarySearch( /* [in] */ const AutoPtr<ArrayOf<T *> > & array, /* [in] */ T * value, /* [out] */ Int32* index); /** * Performs a binary search for {@code value} in the ascending sorted array {@code array}, * in the range specified by fromIndex (inclusive) and toIndex (exclusive), * using {@code comparator} to compare elements. * Searching in an unsorted array has an undefined result. It's also undefined which element * is found if there are multiple occurrences of the same element. * * @param array the sorted array to search. * @param startIndex the inclusive start index. * @param endIndex the exclusive start index. * @param value the element to find. * @param comparator the {@code Comparator} used to compare the elements. * @return the non-negative index of the element, or a negative index which * is {@code -index - 1} where the element would be inserted. * @throws ClassCastException * if an element in the array or the search element does not * implement {@code Comparable}, or cannot be compared to each other. * @throws IllegalArgumentException if {@code startIndex > endIndex} * @throws ArrayIndexOutOfBoundsException if {@code startIndex < 0 || endIndex > array.length} * @since 1.6 */ template<typename T> static CARAPI BinarySearch( /* [in] */ ArrayOf<T *> * array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ T * value, /* [in] */ IComparator* comparator, /* [out] */ Int32* index); template<typename T> static CARAPI BinarySearch( /* [in] */ const AutoPtr<ArrayOf<T *> > & array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ T * value, /* [in] */ IComparator* comparator, /* [out] */ Int32* index); /** * Performs a binary search for {@code value} in the ascending sorted array {@code array}, * using {@code comparator} to compare elements. * Searching in an unsorted array has an undefined result. It's also undefined which element * is found if there are multiple occurrences of the same element. * * @param array the sorted array to search. * @param value the element to find. * @param comparator the {@code Comparator} used to compare the elements. * @return the non-negative index of the element, or a negative index which * is {@code -index - 1} where the element would be inserted. * @throws ClassCastException * if an element in the array or the search element does not * implement {@code Comparable}, or cannot be compared to each other. */ template<typename T> static CARAPI BinarySearch( /* [in] */ ArrayOf<T *> * array, /* [in] */ T * value, /* [in] */ IComparator* comparator, /* [out] */ Int32* index); template<typename T> static CARAPI BinarySearch( /* [in] */ const AutoPtr<ArrayOf<T *> > & array, /* [in] */ T * value, /* [in] */ IComparator* comparator, /* [out] */ Int32* index); /** * Fills the specified array with the specified element. * * @param array * the {@code byte} array to fill. * @param value * the {@code byte} element. */ template<typename T> static CARAPI Fill( /* [in] */ ArrayOf<T>* array, /* [in] */ T value); template<typename T> static CARAPI Fill( /* [in] */ const AutoPtr<ArrayOf<T> > & array, /* [in] */ T value); /** * Fills the specified range in the array with the specified element. * * @param array * the {@code byte} array to fill. * @param start * the first index to fill. * @param end * the last + 1 index to fill. * @param value * the {@code byte} element. * @throws IllegalArgumentException * if {@code start > end}. * @throws ArrayIndexOutOfBoundsException * if {@code start < 0} or {@code end > array.length}. */ template<typename T> static CARAPI Fill( /* [in] */ ArrayOf<T>* array, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [in] */ T value); template<typename T> static CARAPI Fill( /* [in] */ const AutoPtr<ArrayOf<T> > & array, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [in] */ T value); /** * Returns a hash code based on the contents of the given array. For any two * {@code boolean} arrays {@code a} and {@code b}, if * {@code Arrays.equals(a, b)} returns {@code true}, it means * that the return value of {@code Arrays.hashCode(a)} equals {@code Arrays.hashCode(b)}. * <p> * The value returned by this method is the same value as the * {@link List#hashCode()} method which is invoked on a {@link List} * containing a sequence of {@link Boolean} instances representing the * elements of array in the same order. If the array is {@code null}, the return * value is 0. * * @param array * the array whose hash code to compute. * @return the hash code for {@code array}. */ template<typename T> static CARAPI_(Int32) GetHashCode( /* [in] */ ArrayOf<T>* array); template<typename T> static CARAPI_(Int32) GetHashCode( /* [in] */ const AutoPtr<ArrayOf<T> > & array); static CARAPI_(Int32) GetHashCode( /* [in] */ ArrayOf<Boolean>* array); static CARAPI_(Int32) GetHashCode( /* [in] */ ArrayOf<Int64>* array); static CARAPI_(Int32) GetHashCode( /* [in] */ ArrayOf<Float>* array); static CARAPI_(Int32) GetHashCode( /* [in] */ ArrayOf<Double>* array); template<typename T> static CARAPI_(Int32) GetHashCode( /* [in] */ ArrayOf<T *> * array); template<typename T> static CARAPI_(Int32) GetHashCode( /* [in] */ const AutoPtr<ArrayOf<T *> > & array); template<typename T> static CARAPI_(Int32) DeepGetHashCode( /* [in] */ ArrayOf<T *> * array); template<typename T> static CARAPI_(Int32) DeepGetHashCode( /* [in] */ T * element); template<typename T> static CARAPI_(Int32) DeepGetHashCode( /* [in] */ const AutoPtr<T> & element); /** * Compares the two arrays. * * @param array1 * the first {@code byte} array. * @param array2 * the second {@code byte} array. * @return {@code true} if both arrays are {@code null} or if the arrays have the * same length and the elements at each index in the two arrays are * equal, {@code false} otherwise. */ template<typename T> static CARAPI_(Boolean) Equals( /* [in] */ ArrayOf<T>* array1, /* [in] */ ArrayOf<T>* array2); template<typename T> static CARAPI_(Boolean) Equals( /* [in] */ const AutoPtr<ArrayOf<T> > & array1, /* [in] */ const AutoPtr<ArrayOf<T> > & array2); static CARAPI_(Boolean) Equals( /* [in] */ ArrayOf<Float>* array1, /* [in] */ ArrayOf<Float>* array2); static CARAPI_(Boolean) Equals( /* [in] */ ArrayOf<Double>* array1, /* [in] */ ArrayOf<Double>* array2); template<typename T> static CARAPI_(Boolean) Equals( /* [in] */ ArrayOf<T *> * array1, /* [in] */ ArrayOf<T *> * array2); template<typename T> static CARAPI_(Boolean) Equals( /* [in] */ const AutoPtr<ArrayOf<T *> > & array1, /* [in] */ ArrayOf<T *> * array2); template<typename T> static CARAPI_(Boolean) Equals( /* [in] */ ArrayOf<T *> * array1, /* [in] */ const AutoPtr<ArrayOf<T *> > & array2); template<typename T> static CARAPI_(Boolean) Equals( /* [in] */ const AutoPtr<ArrayOf<T *> > & array1, /* [in] */ const AutoPtr<ArrayOf<T *> > & array2); template<typename T> static CARAPI_(Boolean) DeepEquals( /* [in] */ ArrayOf<T> * array1, /* [in] */ ArrayOf<T> * array2); template<typename T> static CARAPI_(Boolean) DeepEquals( /* [in] */ const AutoPtr<ArrayOf<T> > & array1, /* [in] */ const AutoPtr<ArrayOf<T> > & array2); template<typename T> static CARAPI_(Boolean) DeepEquals( /* [in] */ T * e1, /* [in] */ T * e2); template<typename T> static CARAPI_(Boolean) DeepEquals( /* [in] */ const AutoPtr<T> & e1, /* [in] */ T * e2); template<typename T> static CARAPI_(Boolean) DeepEquals( /* [in] */ T * e1, /* [in] */ const AutoPtr<T> & e2); template<typename T> static CARAPI_(Boolean) DeepEquals( /* [in] */ const AutoPtr<T> & e1, /* [in] */ const AutoPtr<T> & e2); template<typename T> static CARAPI Sort( /* [in] */ ArrayOf<T>* array); template<typename T> static CARAPI Sort( /* [in] */ const AutoPtr<ArrayOf<T> > & array); template<typename T> static CARAPI Sort( /* [in] */ ArrayOf<T>* array, /* [in] */ Int32 start, /* [in] */ Int32 end); template<typename T> static CARAPI Sort( /* [in] */ const AutoPtr<ArrayOf<T> > & array, /* [in] */ Int32 start, /* [in] */ Int32 end); template<typename T> static CARAPI Sort( /* [in] */ ArrayOf<T *> * array); template<typename T> static CARAPI Sort( /* [in] */ const AutoPtr<ArrayOf<T *> > & array); template<typename T> static CARAPI Sort( /* [in] */ ArrayOf<T *> * array, /* [in] */ Int32 start, /* [in] */ Int32 end); template<typename T> static CARAPI Sort( /* [in] */ const AutoPtr<ArrayOf<T *> > & array, /* [in] */ Int32 start, /* [in] */ Int32 end); template<typename T> static CARAPI Sort( /* [in] */ ArrayOf<T *> * array, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [in] */ IComparator* comparator); template<typename T> static CARAPI Sort( /* [in] */ const AutoPtr<ArrayOf<T *> > & array, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [in] */ IComparator* comparator); template<typename T> static CARAPI Sort( /* [in] */ ArrayOf<T *> * array, /* [in] */ IComparator* comparator); template<typename T> static CARAPI Sort( /* [in] */ const AutoPtr<ArrayOf<T *> > & array, /* [in] */ IComparator* comparator); template<typename T> static CARAPI_(String) ToString( /* [in] */ ArrayOf<T> * array); template<typename T> static CARAPI_(String) ToString( /* [in] */ const AutoPtr<ArrayOf<T> > & array); static CARAPI_(String) ToString( /* [in] */ ArrayOf<Char32> * array); template<typename T> static CARAPI_(String) DeepToString( /* [in] */ ArrayOf<T *> * array); template<typename T> static CARAPI_(String) DeepToString( /* [in] */ const AutoPtr<ArrayOf<T *> > & array); template<typename T> static CARAPI CopyOf( /* [in] */ ArrayOf<T> * original, /* [in] */ Int32 newLength, /* [out, callee] */ ArrayOf<T> ** result); template<typename T> static CARAPI CopyOf( /* [in] */ const AutoPtr<ArrayOf<T> > & original, /* [in] */ Int32 newLength, /* [out, callee] */ ArrayOf<T> ** result); template<typename T> static CARAPI CopyOfRange( /* [in] */ ArrayOf<T> * original, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [out, callee] */ ArrayOf<T> ** result); template<typename T> static CARAPI CopyOfRange( /* [in] */ const AutoPtr<ArrayOf<T> > & original, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [out, callee] */ ArrayOf<T> ** result); template<typename T, typename U> static CARAPI CopyOf( /* [in] */ ArrayOf<T> * original, /* [in] */ Int32 newLength, /* [out, callee] */ ArrayOf<U> ** result); template<typename T, typename U> static CARAPI CopyOf( /* [in] */ const AutoPtr<ArrayOf<T> > & original, /* [in] */ Int32 newLength, /* [out, callee] */ ArrayOf<U> ** result); template<typename T, typename U> static CARAPI CopyOfRange( /* [in] */ ArrayOf<T> * original, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [out, callee] */ ArrayOf<U> ** result); template<typename T, typename U> static CARAPI CopyOfRange( /* [in] */ const AutoPtr<ArrayOf<T> > & original, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [out, callee] */ ArrayOf<U> ** result); public: static CARAPI CheckStartAndEnd( /* [in] */ Int32 len, /* [in] */ Int32 start, /* [in] */ Int32 end); static CARAPI CheckOffsetAndCount( /* [in] */ Int32 arrayLength, /* [in] */ Int32 offset, /* [in] */ Int32 count); private: static CARAPI_(AutoPtr<IList>) CreateArrayList( /* [in] */ Int32 length); static CARAPI CheckBinarySearchBounds( /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ Int32 length); template<typename T> ECO_LOCAL static CARAPI DeepToString( /* [in] */ T * obj, /* [in] */ ArrayOf<T*> * origArrays, /* [in] */ StringBuilder& sb); template<typename T> ECO_LOCAL static CARAPI_(Boolean) DeepToStringContains( /* [in] */ ArrayOf<T *> * origArray, /* [in] */ T * obj); template<typename T> ECO_LOCAL static CARAPI DeepToString( /* [in] */ T * obj, /* [in] */ IArrayOf * origArrays, /* [in] */ StringBuilder& sb); template<typename T> ECO_LOCAL static CARAPI_(Boolean) DeepToStringContains( /* [in] */ IArrayOf * origArray, /* [in] */ T * obj); ECO_LOCAL static CARAPI DeepToString( /* [in] */ IInterface * obj, /* [in] */ IArrayOf * origArray, /* [in] */ StringBuilder& sb); ECO_LOCAL static CARAPI_(Boolean) DeepToStringContains( /* [in] */ IArrayOf * origArray, /* [in] */ IInterface * obj); private: ECO_LOCAL Arrays(); ECO_LOCAL Arrays(const Arrays&); }; //========================================================================= // template methods implementation //========================================================================= template<typename T> ECode Arrays::FromList( /* [in] */ IList* list, /* [out, callee] */ ArrayOf<T*> ** array) { VALIDATE_NOT_NULL(array) *array = NULL; VALIDATE_NOT_NULL(list) Int32 size; list->GetSize(&size); AutoPtr<ArrayOf<T*> > temp = ArrayOf<T*>::Alloc(size); if (size > 0) { AutoPtr<IIterator> it; list->GetIterator((IIterator**)&it); Boolean hasNext; Int32 i = 0; while (it->HasNext(&hasNext), hasNext) { AutoPtr<IInterface> obj; it->GetNext((IInterface**)&obj); temp->Set(i++, T::Probe(obj)); } } *array = temp; REFCOUNT_ADD(*array) return NOERROR; } template<typename T> ECode Arrays::AsList( /* [in] */ ArrayOf<T> * array, /* [out] */ IList** outList) { VALIDATE_NOT_NULL(outList) *outList = NULL; if (array) { AutoPtr<IList> l = CreateArrayList(array->GetLength()); for (Int32 i = 0; i < array->GetLength(); ++i) { l->Add(i, TO_IINTERFACE((*array)[i])); } *outList = l; REFCOUNT_ADD(*outList) } return NOERROR; } template<typename T> ECode Arrays::AsList( /* [in] */ const AutoPtr<ArrayOf<T> > & array, /* [out] */ IList** outList) { return AsList(array.Get(), outList); } template<typename T> ECode Arrays::BinarySearch( /* [in] */ ArrayOf<T>* array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ T value, /* [out] */ Int32* index) { VALIDATE_NOT_NULL(index) *index = -1; assert(array != NULL); VALIDATE_NOT_NULL(array) ECode ec = CheckBinarySearchBounds(startIndex, endIndex, array->GetLength()); if (FAILED(ec)) { printf("Arrays", "BinarySearch: error %08x, startIndex: %d, endIndex: %d, array length: %d", ec, startIndex, endIndex, array->GetLength()); return ec; } Int32 lo = startIndex; Int32 hi = endIndex - 1; Int32 mid; T midVal; while (lo <= hi) { mid = (UInt32(lo + hi)) >> 1; midVal = (*array)[mid]; if (midVal < value) { lo = mid + 1; } else if (midVal > value) { hi = mid - 1; } else { *index = mid; // value found return NOERROR; } } *index = ~lo; // value not present return NOERROR; } template<typename T> ECode Arrays::BinarySearch( /* [in] */ ArrayOf<T>* array, /* [in] */ T value, /* [out] */ Int32* index) { VALIDATE_NOT_NULL(index) *index = -1; assert(array != NULL); VALIDATE_NOT_NULL(array) return BinarySearch(array, 0, array->GetLength(), value, index); } template<typename T> ECode Arrays::BinarySearch( /* [in] */ const AutoPtr<ArrayOf<T> > & array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ T value, /* [out] */ Int32* index) { return BinarySearch(array.Get(), startIndex, endIndex, value, index); } template<typename T> ECode Arrays::BinarySearch( /* [in] */ const AutoPtr<ArrayOf<T> > & array, /* [in] */ T value, /* [out] */ Int32* index) { return BinarySearch(array.Get(), value, index); } template<typename T> ECode Arrays::BinarySearch( /* [in] */ ArrayOf<T *> * array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ T * value, /* [out] */ Int32* index) { VALIDATE_NOT_NULL(index) *index = -1; assert(array != NULL); VALIDATE_NOT_NULL(array) ECode ec = CheckBinarySearchBounds(startIndex, endIndex, array->GetLength()); if (FAILED(ec)) { printf("Arrays", "BinarySearch: error %08x, startIndex: %d, endIndex: %d, array length: %d", ec, startIndex, endIndex, array->GetLength()); return ec; } Int32 lo = startIndex; Int32 hi = endIndex - 1; Int32 mid, midValCmp; IComparable* comp; while (lo <= hi) { mid = (UInt32(lo + hi)) >> 1; comp = IComparable::Probe((*array)[mid]); if (comp == NULL) { printf("Arrays", "BinarySearch: object at %d does not implement IComparable.", mid); } assert(comp != NULL); comp->CompareTo(TO_IINTERFACE(value), &midValCmp); if (midValCmp < 0) { lo = mid + 1; } else if (midValCmp > 0) { hi = mid - 1; } else { *index = mid; // value found return NOERROR; } } *index = ~lo; // value not present return NOERROR; } template<typename T> ECode Arrays::BinarySearch( /* [in] */ const AutoPtr<ArrayOf<T *> > & array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ T * value, /* [out] */ Int32* index) { return BinarySearch(array.Get(), startIndex, endIndex, value, index); } template<typename T> ECode Arrays::BinarySearch( /* [in] */ ArrayOf<T *> * array, /* [in] */ T * value, /* [out] */ Int32* index) { VALIDATE_NOT_NULL(index) *index = -1; assert(array != NULL); VALIDATE_NOT_NULL(array) return BinarySearch(array, 0, array->GetLength(), value, index); } template<typename T> ECode Arrays::BinarySearch( /* [in] */ const AutoPtr<ArrayOf<T *> > & array, /* [in] */ T * value, /* [out] */ Int32* index) { VALIDATE_NOT_NULL(index) *index = -1; assert(array != NULL); VALIDATE_NOT_NULL(array) return BinarySearch(array.Get(), 0, array->GetLength(), value, index); } template<typename T> ECode Arrays::BinarySearch( /* [in] */ ArrayOf<T *> * array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ T* value, /* [in] */ IComparator* comparator, /* [out] */ Int32* index) { VALIDATE_NOT_NULL(index) *index = -1; assert(array != NULL); VALIDATE_NOT_NULL(array) if (comparator == NULL) { return BinarySearch(array, startIndex, endIndex, value, index); } FAIL_RETURN(CheckBinarySearchBounds(startIndex, endIndex, array->GetLength())); Int32 lo = startIndex; Int32 hi = endIndex - 1; Int32 mid, midValCmp; while (lo <= hi) { mid = (UInt32(lo + hi)) >> 1; comparator->Compare(TO_IINTERFACE((*array)[mid]), value, &midValCmp); if (midValCmp < 0) { lo = mid + 1; } else if (midValCmp > 0) { hi = mid - 1; } else { *index = mid; // value found return NOERROR; } } *index = ~lo; // value not present return NOERROR; } template<typename T> ECode Arrays::BinarySearch( /* [in] */ const AutoPtr<ArrayOf<T *> > & array, /* [in] */ Int32 startIndex, /* [in] */ Int32 endIndex, /* [in] */ T* value, /* [in] */ IComparator* comparator, /* [out] */ Int32* index) { return BinarySearch(array.Get(), startIndex, endIndex, value, comparator, index); } template<typename T> ECode Arrays::BinarySearch( /* [in] */ ArrayOf<T *> * array, /* [in] */ T* value, /* [in] */ IComparator* comparator, /* [out] */ Int32* index) { VALIDATE_NOT_NULL(index) *index = -1; assert(array != NULL); VALIDATE_NOT_NULL(array) return BinarySearch(array, 0, array->GetLength(), value, comparator, index); } template<typename T> ECode Arrays::BinarySearch( /* [in] */ const AutoPtr<ArrayOf<T *> > & array, /* [in] */ T* value, /* [in] */ IComparator* comparator, /* [out] */ Int32* index) { VALIDATE_NOT_NULL(index) *index = -1; assert(array != NULL); VALIDATE_NOT_NULL(array) return BinarySearch(array.Get(), 0, array->GetLength(), value, comparator, index); } template<typename T> ECode Arrays::Fill( /* [in] */ ArrayOf<T>* array, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [in] */ T value) { assert(array != NULL); VALIDATE_NOT_NULL(array); FAIL_RETURN(CheckStartAndEnd(array->GetLength(), start, end)); for (Int32 i = start; i < end; i++) { array->Set(i, value); } return NOERROR; } template<typename T> ECode Arrays::Fill( /* [in] */ ArrayOf<T>* array, /* [in] */ T value) { assert(array != NULL); VALIDATE_NOT_NULL(array); for (Int32 i = 0; i < array->GetLength(); i++) { array->Set(i, value); } return NOERROR; } template<typename T> ECode Arrays::Fill( /* [in] */ const AutoPtr<ArrayOf<T> > & array, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [in] */ T value) { return Fill(array.Get(), start, end, value); } template<typename T> ECode Arrays::Fill( /* [in] */ const AutoPtr<ArrayOf<T> > & array, /* [in] */ T value) { return Fill(array.Get(), value); } template<typename T> Int32 Arrays::GetHashCode( /* [in] */ ArrayOf<T>* array) { if (array == NULL) { return 0; } Int32 hashCode = 1; for (Int32 i = 0; i < array->GetLength(); i++) { hashCode = 31 * hashCode + (Int32)(*array)[i]; } return hashCode; } template<typename T> Int32 Arrays::GetHashCode( /* [in] */ const AutoPtr<ArrayOf<T> > & array) { return GetHashCode(array.Get()); } template<typename T> Int32 Arrays::GetHashCode( /* [in] */ ArrayOf<T *> * array) { if (array == NULL) { return 0; } Int32 hashCode = 1; T* element; for (Int32 i = 0; i < array->GetLength(); i++) { element = (*array)[i]; hashCode = 31 * hashCode + Object::GetHashCode(element); } return hashCode; } template<typename T> Int32 Arrays::GetHashCode( /* [in] */ const AutoPtr<ArrayOf<T *> > & array) { return GetHashCode(array.Get()); } template<typename T> Int32 Arrays::DeepGetHashCode( /* [in] */ ArrayOf<T *> * array) { if (array == NULL) { return 0; } Int32 hashCode = 1, elementHashCode; for (Int32 i = 0; i < array->GetLength(); i++) { elementHashCode = DeepGetHashCode((*array)[i]); hashCode = 31 * hashCode + elementHashCode; } return hashCode; } template<typename T> Int32 Arrays::DeepGetHashCode( /* [in] */ T* element) { if (element == NULL) { return 0; } if (IArrayOf::Probe(element) == NULL) { return Object::GetHashCode(element); } /* * element is an array */ Int32 length; AutoPtr<IArrayOf> array = IArrayOf::Probe(element); array->GetLength(&length); Int32 hashCode = 1, elementHashCode; for (Int32 i = 0; i < length; ++i) { AutoPtr<IInterface> object; array->Get(i, (IInterface**)&object); elementHashCode = DeepGetHashCode(object.Get()); hashCode = 31 * hashCode + elementHashCode; } return hashCode; } template<typename T> Int32 Arrays::DeepGetHashCode( /* [in] */ const AutoPtr<T> & element) { return DeepGetHashCode(element.Get()); } template<typename T> Boolean Arrays::Equals( /* [in] */ ArrayOf<T>* array1, /* [in] */ ArrayOf<T>* array2) { if (array1 == array2) { return TRUE; } if (array1 == NULL || array2 == NULL || array1->GetLength() != array2->GetLength()) { return FALSE; } for (Int32 i = 0; i < array1->GetLength(); i++) { if ((*array1)[i] != (*array2)[i]) { return FALSE; } } return TRUE; } template<typename T> Boolean Arrays::Equals( /* [in] */ const AutoPtr<ArrayOf<T> > & array1, /* [in] */ const AutoPtr<ArrayOf<T> > & array2) { return Equals(array1.Get(), array2.Get()); } template<typename T> Boolean Arrays::DeepEquals( /* [in] */ ArrayOf<T> * array1, /* [in] */ ArrayOf<T> * array2) { if (array1 == array2) { return TRUE; } if (array1 == NULL || array2 == NULL || array1->GetLength() != array2->GetLength()) { return FALSE; } for (Int32 i = 0; i < array1->GetLength(); i++) { if (!DeepEquals(TO_IINTERFACE((*array1)[i]), TO_IINTERFACE((*array2)[i]))) { return FALSE; } } return TRUE; } template<typename T> Boolean Arrays::DeepEquals( /* [in] */ const AutoPtr<ArrayOf<T> > & array1, /* [in] */ const AutoPtr<ArrayOf<T> > & array2) { return DeepEquals(array1.Get(), array2.Get()); } template<typename T> Boolean Arrays::Equals( /* [in] */ ArrayOf<T *> * array1, /* [in] */ ArrayOf<T *> * array2) { if (array1 == array2) { return TRUE; } if (array1 == NULL || array2 == NULL || array1->GetLength() != array2->GetLength()) { return FALSE; } T *e1, *e2; for (Int32 i = 0; i < array1->GetLength(); i++) { e1 = (*array1)[i]; e2 = (*array2)[i]; if (!(e1 == NULL ? e2 == NULL : Object::Equals(e1, e2))) { return FALSE; } } return TRUE; } template<typename T> Boolean Arrays::Equals( /* [in] */ const AutoPtr<ArrayOf<T *> > & array1, /* [in] */ ArrayOf<T *> * array2) { return Equals(array1.Get(), array2); } template<typename T> Boolean Arrays::Equals( /* [in] */ ArrayOf<T *> * array1, /* [in] */ const AutoPtr<ArrayOf<T *> > & array2) { return Equals(array1, array2.Get()); } template<typename T> Boolean Arrays::Equals( /* [in] */ const AutoPtr<ArrayOf<T *> > & array1, /* [in] */ const AutoPtr<ArrayOf<T *> > & array2) { return Equals(array1.Get(), array2.Get()); } template<typename T> Boolean Arrays::DeepEquals( /* [in] */ T* e1, /* [in] */ T* e2) { if (e1 == NULL && e2 == NULL) { return TRUE; } if (e1 == NULL || e2 == NULL) { return FALSE; } if (e1->Probe(EIID_IInterface) == e2->Probe(EIID_IInterface)) { return TRUE; } if (IArrayOf::Probe(e1) == NULL || IArrayOf::Probe(e2) == NULL) { return Object::Equals(e1, e2); } /* * compare as arrays */ AutoPtr<IArrayOf> a1 = IArrayOf::Probe(e1); AutoPtr<IArrayOf> a2 = IArrayOf::Probe(e2); Int32 len1, len2; a1->GetLength(&len1); a2->GetLength(&len2); if (len1 != len2) { return FALSE; } for (Int32 i = 0; i < len1; ++i) { AutoPtr<IInterface> o1, o2; a1->Get(i, (IInterface**)&o1); a2->Get(i, (IInterface**)&o2); if (DeepEquals(o1, o2) == FALSE) { return FALSE; } } return TRUE; } template<typename T> Boolean Arrays::DeepEquals( /* [in] */ const AutoPtr<T> & e1, /* [in] */ T* e2) { return Arrays::DeepEquals(e1.Get(), e2); } template<typename T> Boolean Arrays::DeepEquals( /* [in] */ T* e1, /* [in] */ const AutoPtr<T> & e2) { return Arrays::DeepEquals(e1, e2.Get()); } template<typename T> Boolean Arrays::DeepEquals( /* [in] */ const AutoPtr<T> & e1, /* [in] */ const AutoPtr<T> & e2) { return Arrays::DeepEquals(e1.Get(), e2.Get()); } template<typename T> ECode Arrays::Sort( /* [in] */ ArrayOf<T> * array) { return DualPivotQuicksort::Sort(array); } template<typename T> ECode Arrays::Sort( /* [in] */ const AutoPtr<ArrayOf<T> > & array) { return DualPivotQuicksort::Sort(array.Get()); } template<typename T> ECode Arrays::Sort( /* [in] */ ArrayOf<T> * array, /* [in] */ Int32 start, /* [in] */ Int32 end) { return DualPivotQuicksort::Sort(array, start, end); } template<typename T> ECode Arrays::Sort( /* [in] */ const AutoPtr<ArrayOf<T> > & array, /* [in] */ Int32 start, /* [in] */ Int32 end) { return DualPivotQuicksort::Sort(array.Get(), start, end); } template<typename T> ECode Arrays::Sort( /* [in] */ ArrayOf<T *> * array) { return ComparableTimSort<T>::Sort(array); } template<typename T> ECode Arrays::Sort( /* [in] */ const AutoPtr<ArrayOf<T *> >& array) { return ComparableTimSort<T>::Sort(array.Get()); } template<typename T> ECode Arrays::Sort( /* [in] */ ArrayOf<T *> * array, /* [in] */ Int32 start, /* [in] */ Int32 end) { return ComparableTimSort<T>::Sort(array, start, end); } template<typename T> ECode Arrays::Sort( /* [in] */ const AutoPtr<ArrayOf<T *> >& array, /* [in] */ Int32 start, /* [in] */ Int32 end) { return ComparableTimSort<T>::Sort(array.Get(), start, end); } template<typename T> ECode Arrays::Sort( /* [in] */ ArrayOf<T *> * array, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [in] */ IComparator* comparator) { return TimSort<T>::Sort(array, start, end, comparator); } template<typename T> ECode Arrays::Sort( /* [in] */ const AutoPtr<ArrayOf<T *> >& array, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [in] */ IComparator* comparator) { return TimSort<T>::Sort(array.Get(), start, end, comparator); } template<typename T> ECode Arrays::Sort( /* [in] */ ArrayOf<T *> * array, /* [in] */ IComparator* comparator) { return TimSort<T>::Sort(array, comparator); } template<typename T> ECode Arrays::Sort( /* [in] */ const AutoPtr<ArrayOf<T *> >& array, /* [in] */ IComparator* comparator) { return TimSort<T>::Sort(array.Get(), comparator); } template<typename T> String Arrays::ToString( /* [in] */ ArrayOf<T>* array) { if (array == NULL) { return String("NULL"); } if (array->GetLength() == 0) { return String("[]"); } StringBuilder sb(array->GetLength() * 7); sb.AppendChar('['); sb.Append((*array)[0]); for (Int32 i = 1; i < array->GetLength(); i++) { sb.Append(", "); sb.Append((*array)[i]); } sb.AppendChar(']'); return sb.ToString(); } template<typename T> String Arrays::ToString( /* [in] */ const AutoPtr<ArrayOf<T> > & array) { return ToString(array.Get()); } template<typename T> Boolean Arrays::DeepToStringContains( /* [in] */ IArrayOf * origArray, /* [in] */ T * obj) { if (origArray == NULL) { return FALSE; } IInterface * object = TO_IINTERFACE(obj); Int32 length; origArray->GetLength(&length); for (Int32 i = 0; i < length; ++i) { AutoPtr<IInterface> element; origArray->Get(i, (IInterface**)&element); if (element.Get() == object) { return TRUE; } } return FALSE; } template<typename T> ECode Arrays::DeepToString( /* [in] */ T * obj, /* [in] */ IArrayOf * origArray, /* [in] */ StringBuilder& sb) { IArrayOf* array = IArrayOf::Probe(obj); if (array == NULL) { String info = Object::ToString(obj); sb.Append(info); return NOERROR; } if (DeepToStringContains(origArray, obj)) { sb.Append("[...]"); } else { sb.AppendChar('['); Int32 length; array->GetLength(&length); for (Int32 i = 0; i < length; ++i) { if (i != 0) sb += ", "; AutoPtr<IInterface> element; array->Get(i, (IInterface**)&element); DeepToString(element.Get(), origArray, sb); } sb.AppendChar(']'); } return NOERROR; } template<typename T> Boolean Arrays::DeepToStringContains( /* [in] */ ArrayOf<T *> * origArray, /* [in] */ T* array) { if (origArray == NULL || origArray->GetLength() == 0) { return FALSE; } for (Int32 i = 0; i < origArray->GetLength(); ++i) { if (TO_IINTERFACE((*origArray)[i]) == array) { return TRUE; } } return FALSE; } template<typename T> ECode Arrays::DeepToString( /* [in] */ T * obj, /* [in] */ ArrayOf<T*> * origArray, /* [in] */ StringBuilder& sb) { IArrayOf* array = IArrayOf::Probe(obj); if (array == NULL) { String info = Object::ToString(obj); sb.Append(info); return NOERROR; } if (DeepToStringContains(origArray, obj)) { sb.Append("[...]"); } else { sb.AppendChar('['); Int32 length; array->GetLength(&length); for (Int32 i = 0; i < length; ++i) { if (i != 0) sb += ", "; AutoPtr<IInterface> element; array->Get(i, (IInterface**)&element); DeepToString(element.Get(), origArray, sb); } sb.AppendChar(']'); } return NOERROR; } template<typename T> String Arrays::DeepToString( /* [in] */ ArrayOf<T *> * array) { // Special case null to prevent NPE if (array == NULL) { return String("NULL"); } // delegate this to the recursive method StringBuilder sb(array->GetLength() * 9); sb.AppendChar('['); for (Int32 i = 0; i < array->GetLength(); ++i) { if (i != 0) sb += ", "; DeepToString((*array)[i], array, sb); } sb.AppendChar(']'); return sb.ToString(); } template<typename T> String Arrays::DeepToString( /* [in] */ const AutoPtr<ArrayOf<T *> > & array) { return DeepToString(array.Get()); } template<typename T> ECode Arrays::CopyOfRange( /* [in] */ ArrayOf<T> * original, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [out, callee] */ ArrayOf<T> ** result) { VALIDATE_NOT_NULL(result) *result = NULL; assert(original); VALIDATE_NOT_NULL(original) if (start > end) { printf("Arrays", "CopyOfRange: error, E_ILLEGAL_ARGUMENT_EXCEPTION, start %d, end %d", start, end); return E_ILLEGAL_ARGUMENT_EXCEPTION; } Int32 originalLength = original->GetLength(); if (start < 0 || start > originalLength) { printf("Arrays", "CopyOfRange: error, E_ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION, start %d, originalLength %d", start, originalLength); return E_ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION; } Int32 resultLength = end - start; Int32 copyLength = Elastos::Core::Math::Min(resultLength, originalLength - start); AutoPtr<ArrayOf<T> > array = ArrayOf<T>::Alloc(resultLength); array->Copy(original, start, copyLength); *result = array; REFCOUNT_ADD(*result) return NOERROR; } template<typename T> ECode Arrays::CopyOf( /* [in] */ ArrayOf<T> * original, /* [in] */ Int32 newLength, /* [out, callee] */ ArrayOf<T> ** result) { if (newLength < 0) { printf("Arrays", "CopyOf: error, E_NAGATIVE_ARRAY_SIZE_EXCEPTION, newLength %d", newLength); return E_NAGATIVE_ARRAY_SIZE_EXCEPTION; } return CopyOfRange(original, 0, newLength, result); } template<typename T> ECode Arrays::CopyOfRange( /* [in] */ const AutoPtr<ArrayOf<T> > & original, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [out, callee] */ ArrayOf<T> ** result) { return CopyOfRange(original.Get(), start, end, result); } template<typename T> ECode Arrays::CopyOf( /* [in] */ const AutoPtr<ArrayOf<T> > & original, /* [in] */ Int32 newLength, /* [out, callee] */ ArrayOf<T> ** result) { return CopyOf(original.Get(), newLength, result); } template<typename T, typename U> ECode Arrays::CopyOfRange( /* [in] */ ArrayOf<T> * original, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [out, callee] */ ArrayOf<U> ** result) { VALIDATE_NOT_NULL(result) *result = NULL; assert(original); VALIDATE_NOT_NULL(original) if (start > end) { printf("Arrays", "CopyOfRange: error, E_ILLEGAL_ARGUMENT_EXCEPTION, start %d, end %d", start, end); return E_ILLEGAL_ARGUMENT_EXCEPTION; } Int32 originalLength = original->GetLength(); if (start < 0 || start > originalLength) { printf("Arrays", "CopyOfRange: error, E_ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION, start %d, originalLength %d", start, originalLength); return E_ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION; } Int32 resultLength = end - start; Int32 copyLength = Elastos::Core::Math::Min(resultLength, originalLength - start); AutoPtr<ArrayOf<U> > array = ArrayOf<U>::Alloc(resultLength); for (Int32 i = 0; i < original->GetLength(); ++i) { array->Set(i, (U)(*original)[i]); // TODO: only work with primitives } *result = result; REFCOUNT_ADD(*result) return NOERROR; } template<typename T, typename U> ECode Arrays::CopyOf( /* [in] */ ArrayOf<T> * original, /* [in] */ Int32 newLength, /* [out, callee] */ ArrayOf<U> ** result) { if (newLength < 0) { printf("Arrays", "CopyOf: error, E_NAGATIVE_ARRAY_SIZE_EXCEPTION, newLength %d", newLength); return E_NAGATIVE_ARRAY_SIZE_EXCEPTION; } return CopyOfRange(original, 0, newLength, result); } template<typename T, typename U> ECode Arrays::CopyOfRange( /* [in] */ const AutoPtr<ArrayOf<T> > & original, /* [in] */ Int32 start, /* [in] */ Int32 end, /* [out, callee] */ ArrayOf<U> ** result) { return CopyOfRange(original.Get(), start, end, result); } template<typename T, typename U> ECode Arrays::CopyOf( /* [in] */ const AutoPtr<ArrayOf<T> > & original, /* [in] */ Int32 newLength, /* [out, callee] */ ArrayOf<U> ** result) { return CopyOf(original, newLength, result); } } // namespace Utility } // namespace Elastos #endif // __ELASTOS_UTILITY_ARRAYS_H__
28.568539
114
0.563655
[ "object" ]
21ea58a4fb597a93a1fab8dd217d3e7356dad76e
781
h
C
symbolic/matcher.h
lilissun/spa
d44974c51017691ff4ada29c212c54bb0ee931c2
[ "Apache-2.0" ]
null
null
null
symbolic/matcher.h
lilissun/spa
d44974c51017691ff4ada29c212c54bb0ee931c2
[ "Apache-2.0" ]
null
null
null
symbolic/matcher.h
lilissun/spa
d44974c51017691ff4ada29c212c54bb0ee931c2
[ "Apache-2.0" ]
1
2020-04-24T02:28:32.000Z
2020-04-24T02:28:32.000Z
// // matcher.h // symbolic // // Created by Li Li on 21/7/14. // Copyright (c) 2014 Lilissun. All rights reserved. // #ifndef __symbolic__matcher__ #define __symbolic__matcher__ #include <iostream> #include <map> #include <vector> #include "term.h" #include "explicit/name.h" namespace sym { class Pattern; class VariablePattern; class Matcher { protected: std::vector<Pattern *> _patterns; // owned std::map<emc::Name, Pattern *> _naming; // referred public: Matcher() {} ~Matcher(); public: void pattern(Pattern *pattern); Pattern * variable(const emc::Name &name); void map(const emc::Name &name, Pattern *pattern); }; } #endif /* defined(__symbolic__matcher__) */
20.025641
59
0.615877
[ "vector" ]
21ef2253d0adfb92f6f3b176fd4cd53da26452cf
3,177
h
C
DataCollector/mozilla/xulrunner-sdk/include/mozilla/dom/workers/bindings/WorkerFeature.h
andrasigneczi/TravelOptimiser
b08805f97f0823fd28975a36db67193386aceb22
[ "Apache-2.0" ]
1
2016-04-20T08:35:44.000Z
2016-04-20T08:35:44.000Z
DataCollector/mozilla/xulrunner-sdk/include/mozilla/dom/workers/bindings/WorkerFeature.h
andrasigneczi/TravelOptimiser
b08805f97f0823fd28975a36db67193386aceb22
[ "Apache-2.0" ]
null
null
null
DataCollector/mozilla/xulrunner-sdk/include/mozilla/dom/workers/bindings/WorkerFeature.h
andrasigneczi/TravelOptimiser
b08805f97f0823fd28975a36db67193386aceb22
[ "Apache-2.0" ]
null
null
null
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* 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/. */ #ifndef mozilla_dom_workers_workerfeature_h__ #define mozilla_dom_workers_workerfeature_h__ #include "mozilla/dom/workers/Workers.h" BEGIN_WORKERS_NAMESPACE /** * Use this chart to help figure out behavior during each of the closing * statuses. Details below. * * +==============================================================+ * | Closing Statuses | * +=============+=============+=================+================+ * | status | clear queue | abort execution | close handler | * +=============+=============+=================+================+ * | Closing | yes | no | no timeout | * +-------------+-------------+-----------------+----------------+ * | Terminating | yes | yes | no timeout | * +-------------+-------------+-----------------+----------------+ * | Canceling | yes | yes | short duration | * +-------------+-------------+-----------------+----------------+ * | Killing | yes | yes | doesn't run | * +-------------+-------------+-----------------+----------------+ */ #ifdef Status /* Xlib headers insist on this for some reason... Nuke it because it'll override our member name */ #undef Status #endif enum Status { // Not yet scheduled. Pending = 0, // This status means that the close handler has not yet been scheduled. Running, // Inner script called close() on the worker global scope. Setting this // status causes the worker to clear its queue of events but does not abort // the currently running script. The close handler is also scheduled with // no expiration time. Closing, // Outer script called terminate() on the worker or the worker object was // garbage collected in its outer script. Setting this status causes the // worker to abort immediately, clear its queue of events, and schedules the // close handler with no expiration time. Terminating, // Either the user navigated away from the owning page or the owning page fell // out of bfcache. Setting this status causes the worker to abort immediately // and schedules the close handler with a short expiration time. Since the // page has gone away the worker may not post any messages. Canceling, // The application is shutting down. Setting this status causes the worker to // abort immediately and the close handler is never scheduled. Killing, // The close handler has run and the worker is effectively dead. Dead }; class WorkerFeature { public: virtual ~WorkerFeature() { } virtual bool Suspend(JSContext* aCx) { return true; } virtual bool Resume(JSContext* aCx) { return true; } virtual bool Notify(JSContext* aCx, Status aStatus) = 0; }; END_WORKERS_NAMESPACE #endif /* mozilla_dom_workers_workerfeature_h__ */
36.94186
80
0.576959
[ "object" ]
21f25dac915fa21b954bcdc631fc12a46d711536
7,156
h
C
Chapter5/Main/hgt-qfunc.v.0.5.2/deps/simdpp/simd/float32x4.h
dunarel/dunphd-thesis
7c6286b5134024a8a67f97c4bfba8d6b94dc21c9
[ "BSD-3-Clause" ]
null
null
null
Chapter5/Main/hgt-qfunc.v.0.5.2/deps/simdpp/simd/float32x4.h
dunarel/dunphd-thesis
7c6286b5134024a8a67f97c4bfba8d6b94dc21c9
[ "BSD-3-Clause" ]
null
null
null
Chapter5/Main/hgt-qfunc.v.0.5.2/deps/simdpp/simd/float32x4.h
dunarel/dunphd-thesis
7c6286b5134024a8a67f97c4bfba8d6b94dc21c9
[ "BSD-3-Clause" ]
null
null
null
/* libsimdpp Copyright (C) 2011 Povilas Kanapickas tir5c3@yahoo.co.uk 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. 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 LIBSIMDPP_SIMD_FLOAT32X4_H #define LIBSIMDPP_SIMD_FLOAT32X4_H #ifndef LIBSIMDPP_SIMD_H #error "This file must be included through simd.h" #endif #include <simdpp/simd/int32x4.h> namespace simdpp { #ifndef DOXYGEN_SHOULD_SKIP_THIS namespace SIMDPP_ARCH_NAMESPACE { #endif class basic_int32x4; /// @defgroup simd_vec_fp Types: floating-point vectors /// @{ /// Class representing float32x4 vector class float32x4 { public: using element_type = float; using uint_element_type = uint32_t; using int_vector_type = basic_int32x4; using uint_vector_type = uint32x4; using mask_type = mask_float32x4; static constexpr unsigned length = 4; static constexpr unsigned num_bits = 32; static constexpr uint_element_type all_bits = 0xffffffff; float32x4() = default; float32x4(const float32x4&) = default; float32x4& operator=(const float32x4&) = default; /// Construct from the underlying vector type #if SIMDPP_USE_SSE2 float32x4(__m128 d) : d_(d) {} float32x4& operator=(__m128 d) { d_ = d; return *this; } #elif SIMDPP_USE_NEON float32x4(float32x4_t d) : d_(d) {} float32x4& operator=(float32x4_t d) { d_ = d; return *this; } #elif SIMDPP_USE_ALTIVEC float32x4(__vector float d) : d_(d) {} float32x4& operator=(__vector float d) { d_ = d; return *this; } #endif /// Convert to underlying vector type #if SIMDPP_USE_SSE2 operator __m128() const { return d_; } #elif SIMDPP_USE_NEON operator float32x4_t() const { return d_; } #elif SIMDPP_USE_ALTIVEC operator __vector float() const { return d_; } #endif /// @{ /// Construct from compatible int32x4 integer vector type #if SIMDPP_USE_SSE2 explicit float32x4(basic_int32x4 d) : d_(_mm_castsi128_ps(d)) {} float32x4& operator=(basic_int32x4 d) { d_ = _mm_castsi128_ps(d); return *this; } #elif SIMDPP_USE_NEON explicit float32x4(basic_int32x4 d) : d_(vreinterpretq_f32_s32(d)) {} float32x4& operator=(basic_int32x4 d) { d_ = vreinterpretq_f32_s32(d); return *this; } #elif SIMDPP_USE_ALTIVEC explicit float32x4(basic_int32x4 d) : d_((__vector float)d) {} float32x4& operator=(basic_int32x4 d) { d_ = (__vector float)d; return *this; } #elif SIMDPP_USE_NULL explicit float32x4(basic_int32x4 d) { f32_[0] = bit_cast<float>(d[0]); f32_[1] = bit_cast<float>(d[1]); f32_[2] = bit_cast<float>(d[2]); f32_[3] = bit_cast<float>(d[3]); } float32x4& operator=(basic_int32x4 d) { operator=(float32x4(d)); return *this; } #endif /// @} #ifndef DOXYGEN_SHOULD_SKIP_THIS #if SIMDPP_USE_NULL || (SIMDPP_USE_NEON && !SIMDPP_USE_NEON_FLT_SP) /// For internal use only const float& operator[](unsigned i) const { return f32_[i]; } float& operator[](unsigned i) { return f32_[i]; } #endif #endif /** Creates a float32x4 vector with the contents set to zero @code r0 = 0.0f r1 = 0.0f r2 = 0.0f r3 = 0.0f @endcode */ static float32x4 zero(); /** Creates a float32x4 vector from a value loaded from memory. @code | 0 1 2 3 | r = [ v0 v0 v0 v0 ] @endcode @icost{SSE2-SSE4.1, 2} */ static float32x4 load_broadcast(const float* v0); /** Creates a float32x4 vector from a value stored in a core register. @code | 0 1 2 3 | r = [ v0 v0 v0 v0 ] @endcode @icost{SSE2-SSE4.1, 2} @icost{NEON, 2} */ static float32x4 set_broadcast(float v0); /** Creates a float32x4 vector from a value known at compile-time @code | 0 1 2 3 | r = [ v0 v0 v0 v0 ] @endcode */ static float32x4 make_const(float v0); /** Creates a float32x4 vector from two values known at compile-time @code | 0 1 2 3 | r = [ v0 v1 v0 v1 ] @endcode */ static float32x4 make_const(float v0, float v1); /** Creates a float32x4 vector from four values known at compile-time @code | 0 1 2 3 | r = [ v0 v1 v2 v3 ] @endcode */ static float32x4 make_const(float v0, float v1, float v2, float v3); private: #if SIMDPP_USE_SSE2 __m128 d_; #elif SIMDPP_USE_NEON && !SIMDPP_USE_NEON_FLT_SP union { float f32_[4]; float32x4_t d_; }; #elif SIMDPP_USE_NEON float32x4_t d_; #elif SIMDPP_USE_ALTIVEC __vector float d_; #elif SIMDPP_USE_NULL float f32_[4]; #endif }; /// Class representing a mask for 4x 32-bit floating-point vector class mask_float32x4 { public: static constexpr unsigned length = 4; mask_float32x4() = default; mask_float32x4(const mask_float32x4 &) = default; mask_float32x4 &operator=(const mask_float32x4 &) = default; #ifndef DOXYGEN_SHOULD_SKIP_THIS #if SIMDPP_USE_SSE2 mask_float32x4(__m128 d) : d_(d) {} #elif SIMDPP_USE_NEON mask_float32x4(float32x4_t d) : d_(d) {} mask_float32x4(uint32x4_t d) : d_(d) {} #elif SIMDPP_USE_ALTIVEC mask_float32x4(__vector float d) : d_(d) {} mask_float32x4(__vector __bool int d) : d_((__vector float)d) {} #endif #if SIMDPP_USE_NULL #else mask_float32x4(float32x4 d) : d_(d) {} #endif #endif /// Access the underlying type operator float32x4() const; #ifndef DOXYGEN_SHOULD_SKIP_THIS #if SIMDPP_USE_NULL bool& operator[](unsigned id) { return b_[id]; } const bool& operator[](unsigned id) const { return b_[id]; } #endif #endif private: #if SIMDPP_USE_NULL bool b_[4]; #else float32x4 d_; #endif }; /// @} -- end defgroup #ifndef DOXYGEN_SHOULD_SKIP_THIS } // namespace SIMDPP_ARCH_NAMESPACE #endif } // namespace simdpp #endif
28.97166
90
0.676356
[ "vector" ]
21f2c3bd804554949b0dfd8e9393e69d4cf6ee8b
10,105
h
C
src/libAtoms/libatoms.h
albapa/QUIP
ecde1e332c6bd62c238d3cd90e31dba4fb390313
[ "NRL" ]
null
null
null
src/libAtoms/libatoms.h
albapa/QUIP
ecde1e332c6bd62c238d3cd90e31dba4fb390313
[ "NRL" ]
null
null
null
src/libAtoms/libatoms.h
albapa/QUIP
ecde1e332c6bd62c238d3cd90e31dba4fb390313
[ "NRL" ]
null
null
null
/* H0 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ /* H0 X */ /* H0 X libAtoms+QUIP: atomistic simulation library */ /* H0 X */ /* H0 X Portions of this code were written by */ /* H0 X Albert Bartok-Partay, Silvia Cereda, Gabor Csanyi, James Kermode, */ /* H0 X Ivan Solt, Wojciech Szlachta, Csilla Varnai, Steven Winfield. */ /* H0 X */ /* H0 X Copyright 2006-2010. */ /* H0 X */ /* H0 X These portions of the source code are released under the GNU General */ /* H0 X Public License, version 2, http://www.gnu.org/copyleft/gpl.html */ /* H0 X */ /* H0 X If you would like to license the source code under different terms, */ /* H0 X please contact Gabor Csanyi, gabor@csanyi.net */ /* H0 X */ /* H0 X Portions of this code were written by Noam Bernstein as part of */ /* H0 X his employment for the U.S. Government, and are not subject */ /* H0 X to copyright in the USA. */ /* H0 X */ /* H0 X */ /* H0 X When using this software, please cite the following reference: */ /* H0 X */ /* H0 X http://www.libatoms.org */ /* H0 X */ /* H0 X Additional contributions by */ /* H0 X Alessio Comisso, Chiara Gattinoni, and Gianpietro Moras */ /* H0 X */ /* H0 XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX */ #ifndef LIBATOMS_H #define LIBATOMS_H #define C_KEY_LEN 256 /* remove trailing underscores if compiling on BG/Q arch */ #ifdef BGQ #define register_constraint_sub_ register_constraint_sub #define call_constraint_sub_ call_constraint_sub #define fisnan_ fisnan #define ffsize_ ffsize #define fabort_ fabort #define fusleep_ fusleep #define system_command_ system_command #define c_increase_stack_ c_increase_stack #define fwc_l_ fwc_l #define fwrite_line_to_file_ fwrite_line_to_file #define fappend_file_to_file fappend_file_to_file #define frm_file_ frm_file #define pointer_to_ pointer_to #define c_mem_info_ c_mem_info #define register_callbackpot_sub_ register_callbackpot_sub #define call_callbackpot_sub_ call_callbackpot_sub // #define quippy_error_abort_ quippy_error_abort #define c_push_error_with_info_ c_push_error_with_info #define c_push_error_ c_push_error #define c_error_abort_ c_error_abort #define c_error_clear_stack_ c_error_clear_stack #define c_system_initialise_ c_system_initialise #define c_dictionary_initialise_ c_dictionary_initialise #define c_dictionary_finalise_ c_dictionary_finalise #define c_dictionary_get_n_ c_dictionary_get_n #define c_dictionary_get_key_ c_dictionary_get_key #define c_dictionary_query_key_ c_dictionary_query_key #define c_dictionary_query_index_ c_dictionary_query_index #define c_dictionary_add_key_ c_dictionary_add_key #define c_extendable_str_concat_ c_extendable_str_concat #define abc_to_xyz_ abc_to_xyz #endif /* Dictionary types */ #define T_NONE 0 #define T_INTEGER 1 #define T_REAL 2 #define T_COMPLEX 3 #define T_LOGICAL 4 #define T_INTEGER_A 5 #define T_REAL_A 6 #define T_COMPLEX_A 7 #define T_LOGICAL_A 8 #define T_CHAR 9 #define T_CHAR_A 10 #define T_DATA 11 #define T_INTEGER_A2 12 #define T_REAL_A2 13 /* Property types -- legacy for backwards compatibility */ #define PROPERTY_INT 1 #define PROPERTY_REAL 2 #define PROPERTY_STR 3 #define PROPERTY_LOGICAL 4 /* Dictionary access macros */ #define INTEGER(loc) (*(int *)loc) #define REAL(loc) (*(double *)loc) #define LOGICAL(loc) (*(int *)loc) #define COMPLEX_R(loc) (((double *)loc)[0]) #define COMPLEX_I(loc) (((double *)loc)[1]) #define CHAR(loc) ((char *)loc) #define INTEGER_A(loc,i) (((int *)loc)[i]) #define REAL_A(loc,i) (((double *)loc)[i]) #define LOGICAL_A(loc,i) (((int *)loc)[i]) #define COMPLEX_A_R(loc,i) (((double *)loc)[i*2+0]) #define COMPLEX_A_I(loc,i) (((double *)loc)[i*2+1]) #define CHAR_A(loc, shape, i, j) (((char *)loc)[j*shape[0]+i]) #define INTEGER_A2(loc, shape, i, j) (((int *)loc)[j*shape[0]+i]) #define REAL_A2(loc, shape, i, j) (((double *)loc)[j*shape[0]+i]) /* error.f95 (via libAtoms_utils_no_module.f95) */ #ifdef CDEBUG #define debug(fmt, ...) fprintf(stderr, fmt, ## __VA_ARGS__) #else #define debug(fmt, ...) #endif #define ERROR_NONE 0 #define ERROR_UNSPECIFIED -1 #define ERROR_IO -2 #define ERROR_IO_EOF -3 #define INIT_ERROR if (error != NULL) *error = ERROR_NONE #define RAISE_ERROR(info, ...) sprintf(error_h_info, info, ## __VA_ARGS__ ); error_h_line = __LINE__; error_h_kind = ERROR_UNSPECIFIED; c_push_error_with_info_(error_h_info, __FILE__, &error_h_line, &error_h_kind, strlen(error_h_info), strlen(__FILE__)); if (error != NULL) { *error = error_h_kind; return; } else c_error_abort_(error) #define RAISE_ERROR_WITH_KIND(kind, info, ...) sprintf(error_h_info, info, ## __VA_ARGS__ ); error_h_line = __LINE__; error_h_kind = kind; c_push_error_with_info_(error_h_info, __FILE__, &error_h_line, &error_h_kind, strlen(error_h_info), strlen(__FILE__)); if (error != NULL) { *error = error_h_kind; return; } else c_error_abort_(error) #define PASS_ERROR if (error != NULL && *error != ERROR_NONE) { error_h_line = __LINE__; c_push_error_(__FILE__, &error_h_line, error, strlen(__FILE__)); return; } #define CLEAR_ERROR c_error_clear_stack_(); extern void c_push_error_with_info_(char*, char*, int*, int*, size_t, size_t); extern void c_push_error_(char*, int*, int*, size_t); extern void c_error_abort_(int *); extern void c_error_clear_stack_(void); extern char error_h_info[1000]; extern int error_h_line; extern int error_h_kind; /* quippy abort handler */ #include <setjmp.h> extern jmp_buf environment_buffer; extern char abort_message[1024]; void quippy_error_abort_(char *message, int len); void quippy_error_abort_int_handler(int signum); /* System.f95 (via libAtoms_utils_no_module.f95) */ extern void c_system_initialise_(int *verbosity); #define system_initialise c_system_initialise_ /* Dictionary.f95 (via libAtoms_utils_no_module.f95) */ typedef int fortran_t; extern void c_dictionary_initialise_(fortran_t*); #define dictionary_initialise c_dictionary_initialise_ extern void c_dictionary_finalise_(fortran_t*); #define dictionary_finalise c_dictionary_finalise_ extern void c_dictionary_get_n_(fortran_t*, int*); #define dictionary_get_n c_dictionary_get_n_ extern void c_dictionary_get_key_(fortran_t*, int*, char *, int*, int*, size_t); #define dictionary_get_key c_dictionary_get_key_ extern void c_dictionary_query_key_(fortran_t*, char*, int*, int*, void*, int*, size_t); #define dictionary_query_key c_dictionary_query_key_ extern void c_dictionary_query_index_(fortran_t*, int*, char*, int*, int*, void*, int*, size_t); #define dictionary_query_index c_dictionary_query_index_ extern void c_dictionary_add_key_(fortran_t*, char*, int*, int*, void*, int*, size_t); #define dictionary_add_key c_dictionary_add_key_ /* ExtendableStr.f95 (via libAtoms_utils_no_module.f95) */ extern void c_extendable_str_concat_(fortran_t*, char*, int *, int *, size_t); #define extendable_str_concat c_extendable_str_concat_ /* Atoms.f95 (via libAtoms_utils_no_module.f95) */ void lattice_abc_to_xyz_(double cell_lengths[3], double cell_angles[3], double lattice[3][3]); void lattice_xyz_to_abc_(double lattice[3][3], double cell_lengths[3], double cell_angles[3]); #define LIBATOMS_DECLARE_CONFIG fortran_t *params, fortran_t *properties, fortran_t *selected_properties, double lattice[3][3], int *n_atom /* xyz.c */ void read_xyz (char *filename, fortran_t *params, fortran_t *properties, fortran_t *selected_properties, double lattice[3][3], int *n_atom, int compute_index, int frame, int *range, int string, int string_length, int n_index, int *indices, int *error); void write_xyz (char *filename, fortran_t *params, fortran_t *properties, fortran_t *selected_properties, double lattice[3][3], int n_atom, int append, char *prefix, char *int_format, char *real_format, char *str_format, char *logical_format, int string, fortran_t *estr, int update_index, int *error); void query_xyz (char *filename, int compute_index, int frame, int *n_frame, int *n_atom, int *error); /* netcdf.c */ void read_netcdf (char *filename, fortran_t *params, fortran_t *properties, fortran_t *selected_properties, double lattice[3][3], double cell_lengths[3], double cell_angles[3], int *cell_rotated, int *n_atom, int frame, int zero, int *range, int irep, double rrep, int *error); void write_netcdf (char *filename, fortran_t *params, fortran_t *properties, fortran_t *selected_properties, double lattice[3][3], double cell_lengths[3], double cell_angles[3], int cell_rotated, int n_atom, int n_label, int n_string, int frame, int netcdf4, int append, int shuffle, int deflate, int deflate_level, int *error); void query_netcdf (char *filename, int *n_frame, int *n_atom, int *n_label, int *n_string, int *error); /* cutil.c */ #define MAX_CALLBACKS 200 #endif
45.931818
338
0.668481
[ "shape" ]
bc26a974a02a1fc086609d94db6d386f5ad4ec4b
1,024
h
C
data-logger/include/f1_datalogger/controllers/pure_pursuit_controller.h
linklab-uva/deepracing
fc25c47658277df029e7399d295d97a75fe85216
[ "Apache-2.0" ]
11
2020-06-29T15:21:37.000Z
2021-04-12T00:42:26.000Z
data-logger/include/f1_datalogger/controllers/pure_pursuit_controller.h
linklab-uva/deepracing
fc25c47658277df029e7399d295d97a75fe85216
[ "Apache-2.0" ]
null
null
null
data-logger/include/f1_datalogger/controllers/pure_pursuit_controller.h
linklab-uva/deepracing
fc25c47658277df029e7399d295d97a75fe85216
[ "Apache-2.0" ]
4
2019-01-23T23:36:57.000Z
2021-07-02T00:18:37.000Z
#ifndef INCLUDE_CONTROLLERS_PURE_PURSUIT_CONTROLLER_H_ #define INCLUDE_CONTROLLERS_PURE_PURSUIT_CONTROLLER_H_ #include "f1_datalogger/udp_logging/common/measurement_handler_2018.h" #include "Eigen/Core" #include <vector> #include <boost/math/constants/constants.hpp> #include "f1_datalogger/controllers/f1_interface.h" #include <memory> namespace deepf1 { class F1_DATALOGGER_CONTROLS_PUBLIC PurePursuitController { public: PurePursuitController(std::shared_ptr<MeasurementHandler2018> measurement_handler, double Kv=1.0, double L = 3.7, double max_angle = 0.78539816339744830961566084581988, double velocity_setpoint = 100.0); ~PurePursuitController(); void run(const std::string& trackfile = "Australia_racingline.track", float velKp=1.0, float velKi= 0.1, float velKd = -0.1, float velocity_lookahead_gain = 1.5); private: std::shared_ptr<MeasurementHandler2018> measurement_handler_; double Kv_, L_, max_angle_, velocity_setpoint_; std::shared_ptr<deepf1::F1Interface> f1_interface_; }; } #endif
37.925926
164
0.805664
[ "vector" ]
bc279122a795caf4f4b1aa725ba5def89a8286f2
449
h
C
PipelineLayout.h
Sqazine/vksph
748356d5adfc0dadd93cf9b0a4e48fe447b63d26
[ "Apache-2.0" ]
1
2021-11-10T07:37:49.000Z
2021-11-10T07:37:49.000Z
PipelineLayout.h
Sqazine/vksph
748356d5adfc0dadd93cf9b0a4e48fe447b63d26
[ "Apache-2.0" ]
null
null
null
PipelineLayout.h
Sqazine/vksph
748356d5adfc0dadd93cf9b0a4e48fe447b63d26
[ "Apache-2.0" ]
null
null
null
#pragma once #include <vulkan/vulkan.h> #include <vector> namespace VK { class PipelineLayout { public: PipelineLayout( const std::vector<VkDescriptorSetLayout> &descriptorSetLayouts = {}, const std::vector<VkPushConstantRange> &pushConstantRange = {}); ~PipelineLayout(); const VkPipelineLayout &GetVKPipelineLayoutHandle() const; private: VkPipelineLayout m_PipelineLayoutHandle; }; }
24.944444
157
0.685969
[ "vector" ]
bc4ebd2c9c69825e348e33e48e66bf32fad5e68b
1,188
h
C
RFW/backends/VulkanRTX/src/ComputePipeline.h
MeirBon/rendering-fw
dff775c816d19cd9e11eac2c2a2b3c608216ad4c
[ "Apache-2.0" ]
77
2020-01-03T18:32:47.000Z
2021-08-08T01:06:52.000Z
RFW/backends/VulkanRTX/src/ComputePipeline.h
meirbon/rendering-fw
dff775c816d19cd9e11eac2c2a2b3c608216ad4c
[ "Apache-2.0" ]
1
2020-01-09T01:59:27.000Z
2020-01-09T08:47:28.000Z
RFW/backends/VulkanRTX/src/ComputePipeline.h
meirbon/rendering-fw
dff775c816d19cd9e11eac2c2a2b3c608216ad4c
[ "Apache-2.0" ]
2
2022-02-20T01:55:07.000Z
2022-03-30T03:02:48.000Z
// // Created by meir on 10/25/19. // #ifndef RENDERINGFW_VULKANRTX_SRC_COMPUTEPIPELINE_H #define RENDERINGFW_VULKANRTX_SRC_COMPUTEPIPELINE_H #include <vulkan/vulkan.hpp> #include "VulkanDevice.h" #include "Shader.h" #include "DescriptorSet.h" namespace vkrtx { class ComputePipeline { public: ComputePipeline(const VulkanDevice &device, const Shader &computeShader); ~ComputePipeline(); void addPushConstant(vk::PushConstantRange pushConstant); void addDescriptorSet(const DescriptorSet *set); void recordPushConstant(vk::CommandBuffer cmdBuffer, uint32_t idx, uint32_t sizeInBytes, void *data); void recordDispatchCommand(vk::CommandBuffer cmdBuffer, uint32_t width, uint32_t height = 1, uint32_t depth = 1); void finalize(); void cleanup(); private: bool m_Generated = false; VulkanDevice m_Device; vk::PipelineShaderStageCreateInfo m_ShaderStage; std::vector<const DescriptorSet *> m_DescriptorSets; std::vector<vk::DescriptorSet> m_VkDescriptorSets; std::vector<vk::PushConstantRange> m_PushConstants; vk::Pipeline m_Pipeline = nullptr; vk::PipelineLayout m_Layout = nullptr; }; } // namespace vkrtx #endif // RENDERINGFW_VULKANRTX_SRC_COMPUTEPIPELINE_H
27
114
0.792088
[ "vector" ]
bc686a7dcd93ad5718d198d915af8333d6f34314
525
h
C
Assignment2_MatthewFerreira/SDL_Project/UI0.h
adityadutta/Assignment2_GAME203
ff15cd91f0d2bea3b74433e0877569515d0f18ea
[ "MIT" ]
null
null
null
Assignment2_MatthewFerreira/SDL_Project/UI0.h
adityadutta/Assignment2_GAME203
ff15cd91f0d2bea3b74433e0877569515d0f18ea
[ "MIT" ]
null
null
null
Assignment2_MatthewFerreira/SDL_Project/UI0.h
adityadutta/Assignment2_GAME203
ff15cd91f0d2bea3b74433e0877569515d0f18ea
[ "MIT" ]
null
null
null
#ifndef UI0_H #define UI0_H #include "MMath.h" #include "UIFactory.h" #include <SDL.h> using namespace MATH; class UI0 : public UIFactory { private: SDL_Window *window; Matrix4 projectionMatrix; SDL_Surface *healthBar1Image; Vec3 healthBar1Pos; SDL_Rect healthBar1Rect; SDL_Surface *healthBar2Image; Vec3 healthBar2Pos; SDL_Rect healthBar2Rect; public: UI0(SDL_Window* sdlWindow); ~UI0(); bool OnCreate(); void OnDestroy(); void Update(const float time); void Render(SDL_Surface *screenSurface); }; #endif
16.935484
41
0.76
[ "render" ]
bc7fe03f6e662e4c273ad663e688cae151ae1751
5,525
c
C
sdk-6.5.20/libs/sdklt/bcmlta/bcmltx/bcm56880_a0/dna_4_6_6/bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_xfrm_handler.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
sdk-6.5.20/libs/sdklt/bcmlta/bcmltx/bcm56880_a0/dna_4_6_6/bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_xfrm_handler.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
sdk-6.5.20/libs/sdklt/bcmlta/bcmltx/bcm56880_a0/dna_4_6_6/bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_xfrm_handler.c
copslock/broadcom_cpri
8e2767676e26faae270cf485591902a4c50cf0c5
[ "Spencer-94" ]
null
null
null
/******************************************************************************* * * DO NOT EDIT THIS FILE! * This file is auto-generated by fltg from Logical Table mapping files. * * Tool: $SDK/INTERNAL/fltg/bin/fltg * * Edits to this file will be lost when it is regenerated. * * This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file. * * Copyright 2007-2020 Broadcom Inc. All rights reserved. */ /* Logical Table Adaptor for component bcmltx */ /* Handler: bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_xfrm_handler */ #include <bcmlrd/bcmlrd_types.h> #include <bcmltd/chip/bcmltd_id.h> #include <bcmltx/bcmltx_field_demux.h> #include <bcmdrd/chip/bcm56880_a0_enum.h> #include <bcmlrd/chip/bcm56880_a0/dna_4_6_6/bcm56880_a0_dna_4_6_6_lrd_xfrm_field_desc.h> extern const bcmltd_field_desc_t bcm56880_a0_dna_4_6_6_lrd_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_src_field_desc_s0[]; static const bcmltd_field_desc_t bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_dst_field_desc[2] = { { .field_id = BCMLTD_INTERNAL_FIELD_BASE + 86, .field_idx = 0, .minbit = 5, .maxbit = 36, .entry_idx = 0, .sym = "MEMDB_TCAM_IFTA80_MEM0_0_MEM0_1m.KEY0f.ENTRY0[34:3]", .reserved = 0 }, { .field_id = BCMLTD_INTERNAL_FIELD_BASE + 88, .field_idx = 0, .minbit = 55, .maxbit = 86, .entry_idx = 0, .sym = "MEMDB_TCAM_IFTA80_MEM0_0_MEM0_1m.KEY0f.ENTRY0[84:53]", .reserved = 0 }, }; static const bcmltd_field_list_t bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_src_list_s0 = { .field_num = 2, .field_array = bcm56880_a0_dna_4_6_6_lrd_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_src_field_desc_s0 }; static const bcmltd_field_list_t bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_dst_list_d0 = { .field_num = 2, .field_array = bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_dst_field_desc }; static const uint32_t bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_transform_src_s0[1] = { BCM56880_A0_DNA_4_6_6_L3_SRC_IPV6_UC_ROUTE_OVERRIDEt_IPV6u_LOWERf, }; static const uint32_t bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_transform_dst_d0[2] = { BCMLTD_INTERNAL_FIELD_BASE + 86, BCMLTD_INTERNAL_FIELD_BASE + 88, }; static const bcmltd_generic_arg_t bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_comp_data = { .sid = BCM56880_A0_DNA_4_6_6_L3_SRC_IPV6_UC_ROUTE_OVERRIDEt, .values = 0, .value = NULL, .user_data = NULL }; static const bcmltd_transform_arg_t bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_xfrm_handler_fwd_arg_s0_d0 = { .values = 0, .value = NULL, .tables = 0, .table = NULL, .fields = 1, .field = bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_transform_src_s0, .field_list = &bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_src_list_s0, .rfields = 2, .rfield = bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_transform_dst_d0, .rfield_list = &bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_dst_list_d0, .comp_data = &bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_comp_data }; static const bcmltd_transform_arg_t bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_xfrm_handler_rev_arg_s0_d0 = { .values = 0, .value = NULL, .tables = 0, .table = NULL, .fields = 2, .field = bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_transform_dst_d0, .field_list = &bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_dst_list_d0, .rfields = 1, .rfield = bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_transform_src_s0, .rfield_list = &bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_src_list_s0, .comp_data = &bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_comp_data }; const bcmltd_xfrm_handler_t bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_xfrm_handler_fwd_s0_d0 = { .transform = bcmltx_field_demux_transform, .arg = &bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_xfrm_handler_fwd_arg_s0_d0 }; const bcmltd_xfrm_handler_t bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_xfrm_handler_rev_s0_d0 = { .transform = bcmltx_field_mux_transform, .arg = &bcm56880_a0_dna_4_6_6_lta_bcmltx_field_demux_l3_src_ipv6_uc_route_overridet_ipv6u_lowerf_0_xfrm_handler_rev_arg_s0_d0 };
44.918699
139
0.791855
[ "transform" ]
bc81fdf70459adfc2082901e5ebd188d27c76e15
9,543
c
C
linger_router_rule.c
liubang/linger_framework
9c856754ce8f4cbf79962a6571b6a76de0fa9ba7
[ "MIT" ]
7
2017-09-30T01:46:17.000Z
2018-09-10T21:35:51.000Z
linger_router_rule.c
iliubang/linger_framework
9c856754ce8f4cbf79962a6571b6a76de0fa9ba7
[ "MIT" ]
null
null
null
linger_router_rule.c
iliubang/linger_framework
9c856754ce8f4cbf79962a6571b6a76de0fa9ba7
[ "MIT" ]
null
null
null
/* +----------------------------------------------------------------------+ | linger_framework | +----------------------------------------------------------------------+ | Copyright (c) 1997-2016 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: liubang <it.liubang@gmail.com> | +----------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ini.h" #include "php_linger_framework.h" #include "ext/standard/php_string.h" #include "linger_router_rule.h" zend_class_entry *router_rule_ce; ZEND_BEGIN_ARG_INFO_EX(linger_framework_router_rule_void_arginfo, 0, 0, 0) ZEND_END_ARG_INFO() ZEND_BEGIN_ARG_INFO_EX(linger_framework_router_rule_4_arginfo, 0, 0, 4) ZEND_ARG_INFO(0, request_method) ZEND_ARG_INFO(0, uri) ZEND_ARG_INFO(0, class) ZEND_ARG_INFO(0, class_method) ZEND_END_ARG_INFO() zend_object_handlers linger_router_rule_obj_handlers; static zend_object *linger_create_router_rule_obj(zend_class_entry *ce) /* {{{ */ { router_rule_obj *internal; internal = ecalloc(1, sizeof(router_rule_obj) + zend_object_properties_size(ce)); zend_object_std_init(&internal->std, ce); object_properties_init(&internal->std, ce); internal->std.handlers = &linger_router_rule_obj_handlers; internal->zs_uri = NULL; return &internal->std; } /* }}} */ static void linger_free_router_rule_obj(zend_object *object) /* {{{ */ { router_rule_obj *internal = (router_rule_obj *)((char *)object - XtOffsetOf(router_rule_obj, std)); zend_object_std_dtor(&internal->std); if (internal->zs_uri) { zend_string_release(internal->zs_uri); } } /* }}} */ zval *linger_router_rule_instance(zval *this, zval *request_method, zval *uri, zval *class, zval *class_method) /* {{{ */ { if (Z_ISUNDEF_P(this)) { object_init_ex(this, router_rule_ce); } char *lower_method = zend_str_tolower_dup(Z_STRVAL_P(request_method), Z_STRLEN_P(request_method)); if (!strncmp(lower_method, "get", 3) || !strncmp(lower_method, "post", 4) || !strncmp(lower_method, "put", 3) || !strncmp(lower_method, "delete", 6)) { zend_update_property_string(router_rule_ce, this, ZEND_STRL(ROUTER_RULE_PROPERTIES_REQUEST_METHOD), lower_method); } else { linger_throw_exception(NULL, 0, "invalid http request."); linger_efree(lower_method); return NULL; } if (UNEXPECTED(IS_STRING != Z_TYPE_P(uri) || IS_STRING != Z_TYPE_P(request_method) || IS_STRING != Z_TYPE_P(class) || IS_STRING != Z_TYPE_P(class_method))) { linger_throw_exception(NULL, 0, "parameters error."); linger_efree(lower_method); return NULL; } zend_update_property_string(router_rule_ce, this, ZEND_STRL(ROUTER_RULE_PROPERTIES_URI), Z_STRVAL_P(uri)); zend_update_property(router_rule_ce, this, ZEND_STRL(ROUTER_RULE_PROPERTIES_CLASS), class); zend_update_property(router_rule_ce, this, ZEND_STRL(ROUTER_RULE_PROPERTIES_CLASS_METHOD), class_method); linger_efree(lower_method); //Z_GET_ZS_URI(this) = zend_string_init(Z_STRVAL_P(uri), Z_STRLEN_P(uri), 0); return this; } /* }}} */ zval *linger_router_rule_get_request_method(zval *this) /* {{{ */ { if (!this) return NULL; return zend_read_property(router_rule_ce, this, ZEND_STRL(ROUTER_RULE_PROPERTIES_REQUEST_METHOD), 1, NULL); } /* }}} */ zval *linger_router_rule_get_uri(zval *this) /* {{{ */ { if (!this) return NULL; return zend_read_property(router_rule_ce, this, ZEND_STRL(ROUTER_RULE_PROPERTIES_URI), 1, NULL); } /* }}} */ zval *linger_router_rule_get_class(zval *this) /* {{{ */ { if (!this) return NULL; return zend_read_property(router_rule_ce, this, ZEND_STRL(ROUTER_RULE_PROPERTIES_CLASS), 1, NULL); } /* }}} */ zval *linger_router_rule_get_class_method(zval *this) /* {{{ */ { if (UNEXPECTED(!this)) return NULL; return zend_read_property(router_rule_ce, this, ZEND_STRL(ROUTER_RULE_PROPERTIES_CLASS_METHOD), 1, NULL); } /* }}} */ int linger_router_rule_set_compiled_uri(zval *this, zend_string *compiled_uri) /* {{{ */ { if (UNEXPECTED(!this || !compiled_uri)) return FAILURE; zend_string *old = Z_GET_ZS_URI(this); if (old) { zend_string_release(old); } Z_GET_ZS_URI(this) = compiled_uri; return SUCCESS; } /* }}} */ zend_string *linger_router_rule_get_compiled_uri(zval *this) /* {{{ */ { if (UNEXPECTED(!this)) return NULL; return Z_GET_ZS_URI(this); } /* }}} */ int linger_router_rule_set_params_map(zval *this, zval *params_map) /* {{{ */ { if (!this || IS_ARRAY != Z_TYPE_P(params_map)) return FAILURE; zend_update_property(router_rule_ce, this, ZEND_STRL(ROUTER_RULE_PROPERTIES_PARAMS_MAP), params_map); return SUCCESS; } /* }}} */ zval *linger_router_rule_get_params_map(zval *this) /* {{{ */ { if (!this) return NULL; return zend_read_property(router_rule_ce, this, ZEND_STRL(ROUTER_RULE_PROPERTIES_PARAMS_MAP), 1, NULL); } /* }}} */ PHP_METHOD(linger_framework_router_rule, __construct) /* {{{ */ { zval *request_method, *uri, *class, *class_method; if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "zzzz", &request_method, &uri, &class, &class_method) == FAILURE) { return; } (void)linger_router_rule_instance(getThis(), request_method, uri, class, class_method); } /* }}} */ PHP_METHOD(linger_framework_router_rule, getRequestMethod) /* {{{ */ { zval *request_method = zend_read_property(router_rule_ce, getThis(), ZEND_STRL(ROUTER_RULE_PROPERTIES_REQUEST_METHOD), 1, NULL); RETURN_ZVAL(request_method, 1, 0); } /* }}} */ PHP_METHOD(linger_framework_router_rule, getUri) /* {{{ */ { zval *uri = zend_read_property(router_rule_ce, getThis(), ZEND_STRL(ROUTER_RULE_PROPERTIES_URI), 1, NULL); RETURN_ZVAL(uri, 1, 0); } /* }}} */ PHP_METHOD(linger_framework_router_rule, getClass) /* {{{ */ { zval *class = zend_read_property(router_rule_ce, getThis(), ZEND_STRL(ROUTER_RULE_PROPERTIES_CLASS), 1, NULL); RETURN_ZVAL(class, 1, 0); } /* }}} */ PHP_METHOD(linger_framework_router_rule, getClassMethod) /* {{{ */ { zval *class_method = zend_read_property(router_rule_ce, getThis(), ZEND_STRL(ROUTER_RULE_PROPERTIES_CLASS_METHOD), 1, NULL); RETURN_ZVAL(class_method, 1, 0); } /* }}} */ PHP_METHOD(linger_framework_router_rule, dump) /* {{{ */ { zend_string *compiled_uri = Z_GET_ZS_URI(getThis()); if (NULL != compiled_uri) { php_printf("compiled_uri: %s\n", ZSTR_VAL(compiled_uri)); } else { php_printf("compiled_uri: NULL\n"); } } /* }}} */ zend_function_entry router_rule_methods[] = { /* {{{ */ PHP_ME(linger_framework_router_rule, __construct, linger_framework_router_rule_4_arginfo, ZEND_ACC_PUBLIC | ZEND_ACC_CTOR) PHP_ME(linger_framework_router_rule, getRequestMethod, linger_framework_router_rule_void_arginfo, ZEND_ACC_PUBLIC) PHP_ME(linger_framework_router_rule, getUri, linger_framework_router_rule_void_arginfo, ZEND_ACC_PUBLIC) PHP_ME(linger_framework_router_rule, getClass, linger_framework_router_rule_void_arginfo, ZEND_ACC_PUBLIC) PHP_ME(linger_framework_router_rule, getClassMethod, linger_framework_router_rule_void_arginfo, ZEND_ACC_PUBLIC) PHP_ME(linger_framework_router_rule, dump, NULL, ZEND_ACC_PUBLIC) PHP_FE_END }; /* }}} */ LINGER_MINIT_FUNCTION(router_rule) /* {{{ */ { zend_class_entry ce; INIT_CLASS_ENTRY(ce, "Linger\\Framework\\RouterRule", router_rule_methods); router_rule_ce = zend_register_internal_class_ex(&ce, NULL); router_rule_ce->ce_flags |= ZEND_ACC_FINAL; router_rule_ce->create_object = linger_create_router_rule_obj; memcpy(&linger_router_rule_obj_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers)); linger_router_rule_obj_handlers.offset = XtOffsetOf(router_rule_obj, std); linger_router_rule_obj_handlers.dtor_obj = zend_objects_destroy_object; linger_router_rule_obj_handlers.free_obj = linger_free_router_rule_obj; zend_declare_property_null(router_rule_ce, ZEND_STRL(ROUTER_RULE_PROPERTIES_REQUEST_METHOD), ZEND_ACC_PRIVATE); zend_declare_property_null(router_rule_ce, ZEND_STRL(ROUTER_RULE_PROPERTIES_URI), ZEND_ACC_PRIVATE); zend_declare_property_null(router_rule_ce, ZEND_STRL(ROUTER_RULE_PROPERTIES_PARAMS_MAP), ZEND_ACC_PRIVATE); zend_declare_property_null(router_rule_ce, ZEND_STRL(ROUTER_RULE_PROPERTIES_CLASS), ZEND_ACC_PRIVATE); zend_declare_property_null(router_rule_ce, ZEND_STRL(ROUTER_RULE_PROPERTIES_CLASS_METHOD), ZEND_ACC_PRIVATE); return SUCCESS; } /* }}} */
35.344444
132
0.677565
[ "object" ]
bc836fb56a1ddbf5a8cf3ab66c9680dc527c7c4d
3,237
h
C
include/deemon/property.h
GrieferAtWork/deemon
16a4899303390c93d6e7b3910aa4d20e7a55d80b
[ "Zlib" ]
5
2019-09-27T01:33:53.000Z
2021-11-29T16:31:39.000Z
include/deemon/property.h
GrieferAtWork/deemon
16a4899303390c93d6e7b3910aa4d20e7a55d80b
[ "Zlib" ]
null
null
null
include/deemon/property.h
GrieferAtWork/deemon
16a4899303390c93d6e7b3910aa4d20e7a55d80b
[ "Zlib" ]
1
2019-10-04T09:42:30.000Z
2019-10-04T09:42:30.000Z
/* Copyright (c) 2018-2021 Griefer@Work * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement (see the following) in the product * * documentation is required: * * Portions Copyright (c) 2018-2021 Griefer@Work * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * */ #ifndef GUARD_DEEMON_PROPERTY_H #define GUARD_DEEMON_PROPERTY_H 1 #include "api.h" #include "object.h" DECL_BEGIN #ifdef DEE_SOURCE #define Dee_property_object property_object #endif /* DEE_SOURCE */ typedef struct Dee_property_object DeePropertyObject; struct Dee_property_object { /* A wrapper object describing an instance * property when accessed through the class: * >> class MyClass { * >> private foo_value = 42; * >> * >> foo = { * >> get() { * >> print "In getter"; * >> return foo_value; * >> } * >> set(v) { * >> print "In setter"; * >> foo_value = v; * >> } * >> } * >> } * >> * >> local prop = MyClass.foo; // This is a `struct Dee_property_object' * >> print repr prop; // `property { get = @thiscall function(), set = @thiscall function(v) }' * >> local inst = MyClass(); * >> print inst.foo; // `In getter' `42' * >> print prop.get(inst); // `In getter' `42' * Note that property wrappers are always unbound and not actually * used when accessing instance members through normal means. * They are merely used as syntactical sugar to allow access to * public instance properties when only given the class that * implements that property. */ Dee_OBJECT_HEAD DREF DeeObject *p_get; /* [0..1][const] Getter callback. */ DREF DeeObject *p_del; /* [0..1][const] Delete callback. */ DREF DeeObject *p_set; /* [0..1][const] Setter callback. */ }; DDATDEF DeeTypeObject DeeProperty_Type; #define DeeProperty_Check(ob) DeeObject_InstanceOf(ob, &DeeProperty_Type) #define DeeProperty_CheckExact(ob) DeeObject_InstanceOfExact(ob, &DeeProperty_Type) DECL_END #endif /* !GUARD_DEEMON_PROPERTY_H */
42.038961
106
0.570899
[ "object" ]
bc8a66487fce6197a676f00329cd1c387869e7be
10,131
c
C
beamracer.c
pulkomandy/beamracer_btbx
10dc71e30cf756b2ff357f1b31789f488836648b
[ "MIT" ]
1
2020-05-04T10:57:32.000Z
2020-05-04T10:57:32.000Z
beamracer.c
pulkomandy/beamracer_btbx
10dc71e30cf756b2ff357f1b31789f488836648b
[ "MIT" ]
null
null
null
beamracer.c
pulkomandy/beamracer_btbx
10dc71e30cf756b2ff357f1b31789f488836648b
[ "MIT" ]
null
null
null
/* BEAM RACER * Copyright 2014, Adrien Destugues <pulkomandy@gmail.com> * This program is distributed under the terms of the MIT License */ #include "bitbox.h" #include <string.h> // COLOR PALETTES ------------------------------------------------------------- // The road uses only 4 colors, but we encode 2 pixels in one byte (with 4 // unused bits currently). Then we use these palettes to lookup 2 pixels in // only one memory access and expand them to 2 16-byte values (packed in one // uint32_t) that we then blit on screen. // Alternating between the two palettes at carefully chosen lines give the // illusion of the road moving. #define red RGB(255, 0, 0) #define white RGB(255, 255, 255) #define green RGB(0, 255, 0) #define grey RGB(63, 63, 63) static const uint32_t paletteA[16] = { red | (red << 16),white | (red << 16), green | (red << 16), grey | (red << 16), red | (white << 16), white | (white << 16), green | (white << 16), grey | (white << 16), red | (green << 16), white | (green << 16), green | (green << 16), grey | (green << 16), red | (grey << 16), white | (grey << 16), green | (grey << 16), grey | (grey << 16), }; #define red2 RGB(255, 255, 255) #define white2 RGB(63, 63, 63) #define green2 RGB(0, 127, 0) #define grey2 RGB(63, 63, 63) static const uint32_t paletteB[16] = { red2 | (red2 << 16), white2 | (red2 << 16), green2 | (red2 << 16), grey2 | (red2 << 16), red2 | (white2 << 16), white2 | (white2 << 16), green2 | (white2 << 16), grey2 | (white2 << 16), red2 | (green2 << 16), white2 | (green2 << 16), green2 | (green2 << 16), grey2 | (green2 << 16), red2 | (grey2 << 16), white2 | (grey2 << 16), green2 | (grey2 << 16), grey2 | (grey2 << 16), }; // TEXTURES ------------------------------------------------------------------- // The road texture as described above. It is wider than the screen // (180 bytes * 2 pixels per bytes = 360 pixels) so we can offset it to the // left or right without having part of the next line showing on the other edge. // // TODO: the road has a left/right symetry so we should store only half of it // TODO: each byte has a value in 0..15 only. We could halve this and pack more // at the cost of an extra shift&mask in the blit/lookup. Or we can make the // road use 16 colors instead of just 4. extern uint8_t roadtex[256][180]; // KERNEL CALLBACKS ----------------------------------------------------------- // TODO implement those to make an actual game! void game_init() {}; void game_frame() {}; void game_line() {}; // TODO some sound and music would be great too. void game_snd_buffer(uint16_t* buffer, int len) {}; // VIDEO CALLBACKS ------------------------------------------------------------ // Road steering position // Steering is done by shifting the road a tiny bit left or right at each line // // r is the "initial" position of the road. Since we draw things top to bottom, // this is actually the position of the road at the horizon. // // dr ("delta R") is the variation of r at each line ("speed" of the curve) // // ddr ("delta delta R") is the variation of dr at each line ("acceleration") // // The curves should not be very intense and we can have only at most 320 pixels // cumulated difference between the start and end of the road. We have around // 120 lines (half height of the screen, the rest is the sky) to do that. This // means dr should stay in the range 0 to about 1.5, which in turn means ddr // should be very small (as it is added to dr at each frame). // We implement this using a fixed point scheme (r >> 10 is used as the // position, and dr >> 10 is added to r at each frame). This gives an useful // ddr resolution but some rounding artifacts. static int r, dr, ddr; // Same as above for altitude (to implement hills and valleys) // horizon is the starting line on the screen where the road starts (make it // higher when the car is running down a hill, and lower when it is climbing) // q is the distorsion of the road to fake the curving. It is used in the same // way as r with 1st and 2nd derivatives using a fixed point scheme. static int horizon, q, dq, ddq; void graph_vsync() { if (vga_line != VGA_V_PIXELS) return; // Curves are controlled with the mouse currently (for testing). They should // come from the "track" data instead. // We initialize ddr with the curve value (centered mouse / 2) ddr += mouse_x; // dr starts as 0 so the road looks straight at the horizon. This isn't // correct, it should start at (dr/2)² or so so the road looks straight // under the car wheels and distorts as it gets further dr = 0; // And this should be computed so r ends up being reasonably close to 0 on // the last line of the screen. Or it can be offset a bit, to make it feel // like the car is taking the turn and being pulled towards the outside of // the curve. It depends on the feeling you want to give to the game. // Currently the math is randomly tweaked until it feels mostly correct. // More mathematical way to compute that needed // (again, this would be simpler if the road was drawn bottom to top, but // asking people to flip their monitors is something you could do only in // arcade cabinets) r = (-200 * ddr + 10 * 256) * 128; // Compute q depending on the mouse buttons. Again, ugly hand-tweaked values // here, needs a more mathematical way to do this. // More intense values (both for q, horizon and r) will give a more // "rollercoaster" feel to the game. Lower variations give a more realistic // (but also more boring) feel. q = 0; if (mouse_buttons & mousebut_left) { dq = 1 << 14; ddq = 100; horizon = 100; } else if (mouse_buttons & mousebut_right) { dq = 1<<16; ddq = -300; horizon = 128; } else { horizon = 120; dq = 1 << 15; ddq = 0; } }; void graph_line() { // 64bit access to line buffer for faster blitting uint64_t* buf = (uint64_t*)draw_buffer; // The screen is split in two parts: "above" and "below" the horizon. // "above" is the sky, and there can be a background image there too. // The background image must scroll to the left and right in curves to // make it look like the car is actually taking the turn. if (vga_line < horizon) { // Draw the sky - This is just a simple gradient. We could use several // palettes to have day and night, different weathers, and overall a // different look for each track. // There is only one palette value used for each line, so more crazy // effects are possible here (fading from one palette to another, or // a more advanced approach with color-slide math). uint64_t color = RGB(2 * vga_line + 16, 255, 255); // Once we have computed the 16-bit color, we quadruplicate (?) it in // a 64-bit number, which we then copy all over the screen. // TODO check if this is actually faster than using 32 or 16 bits. color = color | (color << 16); color = color | (color << 32); for (int word = 0; word < 80; word++) { *(buf++) = color; } // TODO add some background/Horizon image (should move on hills and // when steering, too) } else { // Draw the road // Compute stripes state // z is the Z coordinate of the world. Assuming x and y are the usual // screen coordinates, z is the "distance" behind the screen the point // is at. We compute this by using perspective projection for a more // correct look. // (don't panic, while it is "perspective", we only need to consider // the y and z axes, so this is still 2D math). int z; // This is the speed at which the car is running. It should be a // variable and the user should control it with some gamepad buttons :) const int speed = 26; // This is the height of the user eyes. Use a lower height for an F-1 // game in 1st-person, and an higher one for a 3rd-person game or // monster truck game (in both cases the eyes are higher up) // Note that the horizon and q values must be adjusted to match. const int height = (256 * 1024); // This is the width (in z-units) of the stripes on the road. We use a // multiple of 2 here so a single bit of the Z value can be used to // pick one of the two road palettes, making the strips visible. const int stripe = 512; // Compute the altitude for this line dq += ddq; q += dq; if (q >> 15 > 255) q = 255 << 15; // Compute Z by projecting the screen on the road according to the // altitude z = height / ((q >> 15) + 32); // Shift z at each frame according to the speed to make the stripes move z += vga_frame * speed; // Compute road curve dr += ddr; r += dr; // Now the blitting happens. The steps are: // Pick the correct palette depending on the z position, and current // frame. As mentionned above we do this with a single bit test. const uint32_t* p = ((z + vga_frame * speed) & stripe) ? paletteA : paletteB; // Get a 32-bit pointer to the screen uint32_t* buf = (uint32_t*)draw_buffer; // And do the blitting. We get 2 pixels from the road texture at once // according to the q (for the line) and r (offset x), look them up // (2 at once) using the current palette, then put that in the line // buffer. for (int px = 0; px < 160; px++) { buf[px] = p[roadtex[q >> 15][(r >> 15) + px]]; } } // At this point the whole sky or road is computed. We can now render // sprites, and other fun stuff on it. This is done even for lines above the // horizon because sprites far enough on the road may be visible above the // horizon. For very convincing hills, even sprites further than that ("on // the other side of the hill") should have their top part visible above the // horizon // // But for now, we draw just the player's car... if (vga_line > 240 - 56) { // The car is stored as 16-bit data for direct copy currently. // No palette lookup here, but a "magic pink" (uh white) test to make // the car sprite transparent. There are better ways to handle this, // as the sprite is (currently) convex and symetric extern uint16_t carsprite[56][75]; uint16_t* sl = carsprite[(vga_line - 184)]; for (int i = 0; i < 75; i++) { if (sl[i] != RGB(255,0,255)) draw_buffer[122 + i] = sl[i]; } } };
41.016194
97
0.661534
[ "render" ]
bc8c0b35397f070830cde46b51066ae2108d6537
8,769
h
C
kubernetes/api/RbacAuthorizationV1API.h
brendandburns/c
ea2fb243e1fd71e96a1ae470b728c3767bf0f328
[ "Apache-2.0" ]
1
2020-03-25T19:45:53.000Z
2020-03-25T19:45:53.000Z
kubernetes/api/RbacAuthorizationV1API.h
brendandburns/c
ea2fb243e1fd71e96a1ae470b728c3767bf0f328
[ "Apache-2.0" ]
null
null
null
kubernetes/api/RbacAuthorizationV1API.h
brendandburns/c
ea2fb243e1fd71e96a1ae470b728c3767bf0f328
[ "Apache-2.0" ]
null
null
null
#include <stdlib.h> #include <stdio.h> #include "../include/apiClient.h" #include "../include/list.h" #include "../external/cJSON.h" #include "../include/keyValuePair.h" #include "../model/v1_api_resource_list.h" #include "../model/v1_cluster_role.h" #include "../model/v1_cluster_role_binding.h" #include "../model/v1_cluster_role_binding_list.h" #include "../model/v1_cluster_role_list.h" #include "../model/v1_delete_options.h" #include "../model/v1_role.h" #include "../model/v1_role_binding.h" #include "../model/v1_role_binding_list.h" #include "../model/v1_role_list.h" #include "../model/v1_status.h" // create a ClusterRole // v1_cluster_role_t* RbacAuthorizationV1API_createClusterRole(apiClient_t *apiClient ,v1_cluster_role_t * body ,char * pretty ,char * dryRun ,char * fieldManager); // create a ClusterRoleBinding // v1_cluster_role_binding_t* RbacAuthorizationV1API_createClusterRoleBinding(apiClient_t *apiClient ,v1_cluster_role_binding_t * body ,char * pretty ,char * dryRun ,char * fieldManager); // create a Role // v1_role_t* RbacAuthorizationV1API_createNamespacedRole(apiClient_t *apiClient ,char * namespace ,v1_role_t * body ,char * pretty ,char * dryRun ,char * fieldManager); // create a RoleBinding // v1_role_binding_t* RbacAuthorizationV1API_createNamespacedRoleBinding(apiClient_t *apiClient ,char * namespace ,v1_role_binding_t * body ,char * pretty ,char * dryRun ,char * fieldManager); // delete a ClusterRole // v1_status_t* RbacAuthorizationV1API_deleteClusterRole(apiClient_t *apiClient ,char * name ,char * pretty ,char * dryRun ,int gracePeriodSeconds ,int orphanDependents ,char * propagationPolicy ,v1_delete_options_t * body); // delete a ClusterRoleBinding // v1_status_t* RbacAuthorizationV1API_deleteClusterRoleBinding(apiClient_t *apiClient ,char * name ,char * pretty ,char * dryRun ,int gracePeriodSeconds ,int orphanDependents ,char * propagationPolicy ,v1_delete_options_t * body); // delete collection of ClusterRole // v1_status_t* RbacAuthorizationV1API_deleteCollectionClusterRole(apiClient_t *apiClient ,char * pretty ,int allowWatchBookmarks ,char * _continue ,char * dryRun ,char * fieldSelector ,int gracePeriodSeconds ,char * labelSelector ,int limit ,int orphanDependents ,char * propagationPolicy ,char * resourceVersion ,int timeoutSeconds ,int watch ,v1_delete_options_t * body); // delete collection of ClusterRoleBinding // v1_status_t* RbacAuthorizationV1API_deleteCollectionClusterRoleBinding(apiClient_t *apiClient ,char * pretty ,int allowWatchBookmarks ,char * _continue ,char * dryRun ,char * fieldSelector ,int gracePeriodSeconds ,char * labelSelector ,int limit ,int orphanDependents ,char * propagationPolicy ,char * resourceVersion ,int timeoutSeconds ,int watch ,v1_delete_options_t * body); // delete collection of Role // v1_status_t* RbacAuthorizationV1API_deleteCollectionNamespacedRole(apiClient_t *apiClient ,char * namespace ,char * pretty ,int allowWatchBookmarks ,char * _continue ,char * dryRun ,char * fieldSelector ,int gracePeriodSeconds ,char * labelSelector ,int limit ,int orphanDependents ,char * propagationPolicy ,char * resourceVersion ,int timeoutSeconds ,int watch ,v1_delete_options_t * body); // delete collection of RoleBinding // v1_status_t* RbacAuthorizationV1API_deleteCollectionNamespacedRoleBinding(apiClient_t *apiClient ,char * namespace ,char * pretty ,int allowWatchBookmarks ,char * _continue ,char * dryRun ,char * fieldSelector ,int gracePeriodSeconds ,char * labelSelector ,int limit ,int orphanDependents ,char * propagationPolicy ,char * resourceVersion ,int timeoutSeconds ,int watch ,v1_delete_options_t * body); // delete a Role // v1_status_t* RbacAuthorizationV1API_deleteNamespacedRole(apiClient_t *apiClient ,char * name ,char * namespace ,char * pretty ,char * dryRun ,int gracePeriodSeconds ,int orphanDependents ,char * propagationPolicy ,v1_delete_options_t * body); // delete a RoleBinding // v1_status_t* RbacAuthorizationV1API_deleteNamespacedRoleBinding(apiClient_t *apiClient ,char * name ,char * namespace ,char * pretty ,char * dryRun ,int gracePeriodSeconds ,int orphanDependents ,char * propagationPolicy ,v1_delete_options_t * body); // get available resources // v1_api_resource_list_t* RbacAuthorizationV1API_getAPIResources(apiClient_t *apiClient); // list or watch objects of kind ClusterRole // v1_cluster_role_list_t* RbacAuthorizationV1API_listClusterRole(apiClient_t *apiClient ,char * pretty ,int allowWatchBookmarks ,char * _continue ,char * fieldSelector ,char * labelSelector ,int limit ,char * resourceVersion ,int timeoutSeconds ,int watch); // list or watch objects of kind ClusterRoleBinding // v1_cluster_role_binding_list_t* RbacAuthorizationV1API_listClusterRoleBinding(apiClient_t *apiClient ,char * pretty ,int allowWatchBookmarks ,char * _continue ,char * fieldSelector ,char * labelSelector ,int limit ,char * resourceVersion ,int timeoutSeconds ,int watch); // list or watch objects of kind Role // v1_role_list_t* RbacAuthorizationV1API_listNamespacedRole(apiClient_t *apiClient ,char * namespace ,char * pretty ,int allowWatchBookmarks ,char * _continue ,char * fieldSelector ,char * labelSelector ,int limit ,char * resourceVersion ,int timeoutSeconds ,int watch); // list or watch objects of kind RoleBinding // v1_role_binding_list_t* RbacAuthorizationV1API_listNamespacedRoleBinding(apiClient_t *apiClient ,char * namespace ,char * pretty ,int allowWatchBookmarks ,char * _continue ,char * fieldSelector ,char * labelSelector ,int limit ,char * resourceVersion ,int timeoutSeconds ,int watch); // list or watch objects of kind RoleBinding // v1_role_binding_list_t* RbacAuthorizationV1API_listRoleBindingForAllNamespaces(apiClient_t *apiClient ,int allowWatchBookmarks ,char * _continue ,char * fieldSelector ,char * labelSelector ,int limit ,char * pretty ,char * resourceVersion ,int timeoutSeconds ,int watch); // list or watch objects of kind Role // v1_role_list_t* RbacAuthorizationV1API_listRoleForAllNamespaces(apiClient_t *apiClient ,int allowWatchBookmarks ,char * _continue ,char * fieldSelector ,char * labelSelector ,int limit ,char * pretty ,char * resourceVersion ,int timeoutSeconds ,int watch); // partially update the specified ClusterRole // v1_cluster_role_t* RbacAuthorizationV1API_patchClusterRole(apiClient_t *apiClient ,char * name ,object_t * body ,char * pretty ,char * dryRun ,char * fieldManager ,int force); // partially update the specified ClusterRoleBinding // v1_cluster_role_binding_t* RbacAuthorizationV1API_patchClusterRoleBinding(apiClient_t *apiClient ,char * name ,object_t * body ,char * pretty ,char * dryRun ,char * fieldManager ,int force); // partially update the specified Role // v1_role_t* RbacAuthorizationV1API_patchNamespacedRole(apiClient_t *apiClient ,char * name ,char * namespace ,object_t * body ,char * pretty ,char * dryRun ,char * fieldManager ,int force); // partially update the specified RoleBinding // v1_role_binding_t* RbacAuthorizationV1API_patchNamespacedRoleBinding(apiClient_t *apiClient ,char * name ,char * namespace ,object_t * body ,char * pretty ,char * dryRun ,char * fieldManager ,int force); // read the specified ClusterRole // v1_cluster_role_t* RbacAuthorizationV1API_readClusterRole(apiClient_t *apiClient ,char * name ,char * pretty); // read the specified ClusterRoleBinding // v1_cluster_role_binding_t* RbacAuthorizationV1API_readClusterRoleBinding(apiClient_t *apiClient ,char * name ,char * pretty); // read the specified Role // v1_role_t* RbacAuthorizationV1API_readNamespacedRole(apiClient_t *apiClient ,char * name ,char * namespace ,char * pretty); // read the specified RoleBinding // v1_role_binding_t* RbacAuthorizationV1API_readNamespacedRoleBinding(apiClient_t *apiClient ,char * name ,char * namespace ,char * pretty); // replace the specified ClusterRole // v1_cluster_role_t* RbacAuthorizationV1API_replaceClusterRole(apiClient_t *apiClient ,char * name ,v1_cluster_role_t * body ,char * pretty ,char * dryRun ,char * fieldManager); // replace the specified ClusterRoleBinding // v1_cluster_role_binding_t* RbacAuthorizationV1API_replaceClusterRoleBinding(apiClient_t *apiClient ,char * name ,v1_cluster_role_binding_t * body ,char * pretty ,char * dryRun ,char * fieldManager); // replace the specified Role // v1_role_t* RbacAuthorizationV1API_replaceNamespacedRole(apiClient_t *apiClient ,char * name ,char * namespace ,v1_role_t * body ,char * pretty ,char * dryRun ,char * fieldManager); // replace the specified RoleBinding // v1_role_binding_t* RbacAuthorizationV1API_replaceNamespacedRoleBinding(apiClient_t *apiClient ,char * name ,char * namespace ,v1_role_binding_t * body ,char * pretty ,char * dryRun ,char * fieldManager);
42.567961
386
0.797354
[ "model" ]
bc95f2458143b7b97b5a1311923f9d247ca9a479
1,024
h
C
src/graphics/label.h
ArneDJ/terranova
533e9e5687d464153418f73a1d811f57e7c572b9
[ "CC0-1.0" ]
null
null
null
src/graphics/label.h
ArneDJ/terranova
533e9e5687d464153418f73a1d811f57e7c572b9
[ "CC0-1.0" ]
null
null
null
src/graphics/label.h
ArneDJ/terranova
533e9e5687d464153418f73a1d811f57e7c572b9
[ "CC0-1.0" ]
null
null
null
#pragma once #include "../extern/freetypegl/freetype-gl.h" namespace gfx { struct LabelVertex { glm::vec2 position = {}; glm::vec2 texcoord = {}; }; struct LabelBuffer { std::vector<LabelVertex> vertices; std::vector<uint32_t> indices; }; class LabelMesh { public: GLuint VAO = 0; GLuint VBO = 0; GLuint EBO = 0; LabelBuffer buffer; geom::Rectangle bounds; public: LabelMesh(); ~LabelMesh(); public: void set_text(const std::string &text, texture_font_t *font); void set_quad(const geom::Rectangle &rectangle); void display() const; }; class Label { public: std::unique_ptr<LabelMesh> text_mesh; std::unique_ptr<LabelMesh> background_mesh; public: glm::vec3 text_color = {}; glm::vec3 background_color = {}; float scale = 1.f; public: Label(); public: void format(const std::string &text, texture_font_t *font); }; class LabelFont { public: texture_atlas_t *atlas = nullptr; texture_font_t *font = nullptr; public: LabelFont(const std::string &fontpath, size_t fontsize); ~LabelFont(); }; };
18.285714
62
0.710938
[ "vector" ]
bcaa4e2e6c14c068968c770523f4f93fb70a67df
53,995
h
C
cabinets/Orange_Metamp_4x12_M930_1.h
plfiorini/GuitarAmp
5339737260e19b9ac32ef554b81d42f23ead3b53
[ "Zlib" ]
1
2021-08-12T20:04:23.000Z
2021-08-12T20:04:23.000Z
cabinets/Orange_Metamp_4x12_M930_1.h
plfiorini/GuitarAmp
5339737260e19b9ac32ef554b81d42f23ead3b53
[ "Zlib" ]
null
null
null
cabinets/Orange_Metamp_4x12_M930_1.h
plfiorini/GuitarAmp
5339737260e19b9ac32ef554b81d42f23ead3b53
[ "Zlib" ]
null
null
null
/// Impulse response header, generated by ir_wav2h.py /// Input file: 1.wav #ifndef IR_ORANGE_METAMP_4X12_M930_1_H #define IR_ORANGE_METAMP_4X12_M930_1_H #include <vector> namespace Orange_Metamp_4x12_M930_1 { static const char* name = "1"; static const char* vendor = "Orange Metamp 4x12"; static const char* mic = "M930"; static int samplerate = 44100; static std::vector<double> frames = { 0.408958435059, 0.961818933487, 0.999999880791, 0.572575688362, 0.151854157448, -0.100286722183, -0.251191496849, -0.408717751503, -0.534811735153, -0.533798694611, -0.296424984932, 0.0425794124603, 0.219777822495, 0.248165249825, 0.213616490364, 0.105803251266, 0.0379390716553, 0.0708149671555, 0.101311802864, 0.0864619016647, 0.099552989006, 0.0929361581802, -0.0449488162994, -0.177958250046, -0.164120316505, -0.0579906702042, 0.0629314184189, 0.107806444168, 0.0573532581329, -0.058633685112, -0.170356273651, -0.160244822502, -0.0526125431061, 0.0288717746735, 0.0999405384064, 0.179308056831, 0.230098843575, 0.187644720078, 0.110537052155, 0.0717235803604, 0.0620546340942, 0.0389057397842, 0.0111780166626, -0.0275763273239, -0.0467230081558, -0.0612069368362, -0.0883893966675, -0.110751867294, -0.0842512845993, -0.03797352314, 0.00267016887665, 0.0657275915146, 0.160340547562, 0.173431873322, 0.104319214821, 0.0666667222977, 0.0700232982635, 0.0268716812134, -0.0273356437683, -0.0421509742737, -0.0512651205063, -0.098380446434, -0.111822247505, -0.067539691925, -0.00727987289429, 0.0367623567581, 0.0621169805527, 0.0541836023331, 0.0226466655731, -0.0167902708054, -0.0310831069946, -0.029597401619, -0.0206736326218, -0.0159972906113, -0.00890076160431, -0.00322961807251, 0.0136460065842, 0.0247341394424, 0.0379054546356, 0.0535089969635, 0.0798476934433, 0.0914841890335, 0.0837854146957, 0.0571837425232, 0.0207780599594, -0.0373013019562, -0.0864642858505, -0.108012318611, -0.0988012552261, -0.0883005857468, -0.0726212263107, -0.0531680583954, -0.0265080928802, -0.00339841842651, 0.0264931917191, 0.0507414340973, 0.0665870904922, 0.0624706745148, 0.0512719154358, 0.025496006012, -0.00463259220123, -0.0364820957184, -0.0455515384674, -0.0358225107193, -0.0175092220306, -0.0137687921524, -0.0132763385773, -0.0124138593674, -0.000897288322449, 0.0111688375473, 0.0273531675339, 0.0370181798935, 0.0507488250732, 0.0628898143768, 0.077966094017, 0.0758074522018, 0.0590867996216, 0.0293267965317, 0.000659704208374, -0.0329047441483, -0.0553059577942, -0.0657162666321, -0.0590696334839, -0.0488996505737, -0.0299581289291, -0.0154769420624, 0.00200533866882, 0.0187830924988, 0.0405173301697, 0.0475181341171, 0.0433387756348, 0.0304597616196, 0.0250840187073, 0.018519282341, 0.0157543420792, 0.00630950927734, -0.00287652015686, -0.0152857303619, -0.0190427303314, -0.0236216783524, -0.021951675415, -0.0211985111237, -0.014121055603, -0.00799858570099, 0.00455963611603, 0.014576792717, 0.0280616283417, 0.0363386869431, 0.0460387468338, 0.0461505651474, 0.0444488525391, 0.0356016159058, 0.0288778543472, 0.015420794487, 0.00202119350433, -0.016786813736, -0.0268015861511, -0.0299260616302, -0.0210200548172, -0.0127736330032, -0.000853538513184, 0.00604772567749, 0.0160117149353, 0.0203909873962, 0.0233337879181, 0.0174543857574, 0.0155135393143, 0.0116837024689, 0.0102945566177, 0.00188076496124, -0.00609230995178, -0.0215948820114, -0.0349577665329, -0.0476143360138, -0.0483894348145, -0.0452451705933, -0.0313163995743, -0.0169132947922, -0.000340104103088, 0.00660312175751, 0.0124387741089, 0.0128527879715, 0.0168838500977, 0.0174108743668, 0.0201522111893, 0.0172522068024, 0.0159198045731, 0.00794005393982, 0.0016667842865, -0.00669836997986, -0.00735330581665, -0.00838947296143, -0.00373423099518, -0.00266122817993, -0.000359535217285, -0.00292038917542, -0.00105810165405, -0.000677824020386, 0.00613713264465, 0.0122219324112, 0.0227564573288, 0.0275520086288, 0.031476855278, 0.0259412527084, 0.0180923938751, 0.00342011451721, -0.0078581571579, -0.0208041667938, -0.0262067317963, -0.0294582843781, -0.0245231389999, -0.0202629566193, -0.0110428333282, -0.00348448753357, 0.00886571407318, 0.0174344778061, 0.0286953449249, 0.034551858902, 0.0389049053192, 0.0326704978943, 0.025158405304, 0.0134094953537, 0.0048131942749, -0.00656187534332, -0.010204911232, -0.0112442970276, -0.00544810295105, -0.00162351131439, 0.00648510456085, 0.00965929031372, 0.0136671066284, 0.0132722854614, 0.0149334669113, 0.0105531215668, 0.00743341445923, 0.00157833099365, 0.000825166702271, -0.00126135349274, 0.00151407718658, 0.000910520553589, 0.00328981876373, 0.00296223163605, 0.00595235824585, 0.00460231304169, 0.00528073310852, 0.00156688690186, 8.26120376587e-05, -0.00519335269928, -0.00762152671814, -0.0128735303879, -0.0132886171341, -0.014793753624, -0.0108554363251, -0.00844991207123, -0.00254213809967, -0.000559687614441, 0.00413942337036, 0.00443422794342, 0.00510728359222, 0.000775337219238, -0.000136256217957, -0.00331842899323, -0.00194096565247, -0.0017694234848, 0.00261247158051, 0.00386500358582, 0.00819945335388, 0.00953698158264, 0.0136650800705, 0.013995051384, 0.0168370008469, 0.0162098407745, 0.0180827379227, 0.0162572860718, 0.0175211429596, 0.0161051750183, 0.0185431241989, 0.0189478397369, 0.0227319002151, 0.0225780010223, 0.0229966640472, 0.0172237157822, 0.0118165016174, 0.00241804122925, -0.00253331661224, -0.00681054592133, -0.0039496421814, -0.00178980827332, 0.00402247905731, 0.00715804100037, 0.0132904052734, 0.0153918266296, 0.0190232992172, 0.0183261632919, 0.019676566124, 0.0172263383865, 0.016220331192, 0.0109783411026, 0.00855648517609, 0.00415921211243, 0.00387954711914, 0.00215125083923, 0.00479388237, 0.00530219078064, 0.00930941104889, 0.0103440284729, 0.0139365196228, 0.0142203569412, 0.0163683891296, 0.0145709514618, 0.0155512094498, 0.0133205652237, 0.0123794078827, 0.00753962993622, 0.00545704364777, 0.000479340553284, -0.000884413719177, -0.00332057476044, -0.00115501880646, -0.000606298446655, 0.00363266468048, 0.00582218170166, 0.0110607147217, 0.0128699541092, 0.0162209272385, 0.015169262886, 0.0150059461594, 0.0102461576462, 0.00706362724304, 0.000585794448853, -0.00303936004639, -0.00810396671295, -0.00776791572571, -0.00776517391205, -0.00378370285034, -0.00214087963104, 0.00241911411285, 0.00405919551849, 0.00826597213745, 0.00951218605042, 0.0133789777756, 0.0142936706543, 0.0173289775848, 0.016764998436, 0.0182744264603, 0.0168223381042, 0.0178020000458, 0.0157308578491, 0.0157423019409, 0.0125378370285, 0.0118961334229, 0.00933051109314, 0.0106542110443, 0.0105831623077, 0.0138773918152, 0.014689207077, 0.018383026123, 0.0191910266876, 0.0214864015579, 0.0200538635254, 0.0206922292709, 0.018346786499, 0.0181511640549, 0.0151634216309, 0.0149973630905, 0.0127201080322, 0.0131685733795, 0.0111502408981, 0.0120459794998, 0.0106427669525, 0.0115846395493, 0.00951945781708, 0.00960493087769, 0.0071839094162, 0.00792467594147, 0.00708508491516, 0.00944364070892, 0.00973987579346, 0.0129138231277, 0.0136115550995, 0.0161488056183, 0.014967083931, 0.0152626037598, 0.0125200748444, 0.0118758678436, 0.00862288475037, 0.00835001468658, 0.00649511814117, 0.00767481327057, 0.00688683986664, 0.00873100757599, 0.0079060792923, 0.00939667224884, 0.00886368751526, 0.0111147165298, 0.0109992027283, 0.012953877449, 0.0121058225632, 0.0131484270096, 0.0114370584488, 0.0117762088776, 0.0094006061554, 0.0093469619751, 0.00724148750305, 0.00773811340332, 0.00598919391632, 0.00681734085083, 0.00567758083344, 0.00698184967041, 0.00584995746613, 0.0069522857666, 0.00590324401855, 0.0072603225708, 0.0062108039856, 0.00734221935272, 0.00612998008728, 0.00709223747253, 0.00603353977203, 0.00789070129395, 0.00812256336212, 0.0106830596924, 0.0109525918961, 0.0133737325668, 0.0132172107697, 0.014709353447, 0.0136684179306, 0.0147687196732, 0.0136326551437, 0.0147552490234, 0.0137546062469, 0.0148513317108, 0.0137127637863, 0.0148475170135, 0.0139100551605, 0.0152733325958, 0.0147943496704, 0.0166401863098, 0.0165622234344, 0.0189057588577, 0.0190563201904, 0.020601272583, 0.0191097259521, 0.0188549757004, 0.0157796144485, 0.0143874883652, 0.0109915733337, 0.0101865530014, 0.00807201862335, 0.00890159606934, 0.00843238830566, 0.0104402303696, 0.0104588270187, 0.0122532844543, 0.0115749835968, 0.0128606557846, 0.0123037099838, 0.0138216018677, 0.01311814785, 0.0140870809555, 0.0125592947006, 0.0124824047089, 0.0104683637619, 0.0108897686005, 0.00974214076996, 0.0106195211411, 0.00936722755432, 0.0100438594818, 0.00884675979614, 0.00962650775909, 0.00844740867615, 0.00937604904175, 0.00879609584808, 0.0106379985809, 0.010954618454, 0.0134824514389, 0.0139527320862, 0.0156626701355, 0.0147275924683, 0.0151470899582, 0.0131547451019, 0.0124114751816, 0.00954926013947, 0.00883507728577, 0.00683176517487, 0.00726866722107, 0.0062427520752, 0.00731515884399, 0.00679588317871, 0.00837790966034, 0.00847864151001, 0.0105929374695, 0.0105677843094, 0.0116523504257, 0.0102714300156, 0.0103597640991, 0.0086190700531, 0.00892579555511, 0.00795710086823, 0.00925469398499, 0.00908267498016, 0.0107502937317, 0.0105493068695, 0.0117418766022, 0.010818362236, 0.0115785598755, 0.0107239484787, 0.0118997097015, 0.0116373300552, 0.01309466362, 0.0125961303711, 0.0137749910355, 0.0132983922958, 0.0143402814865, 0.0134938955307, 0.0143409967422, 0.0135889053345, 0.0146198272705, 0.0140733718872, 0.0151612758636, 0.0144330263138, 0.0152971744537, 0.0146182775497, 0.015687584877, 0.0150257349014, 0.015806555748, 0.0146923065186, 0.014852643013, 0.0130276679993, 0.0126233100891, 0.0106731653214, 0.0107184648514, 0.00966918468475, 0.0105216503143, 0.00972747802734, 0.0101919174194, 0.00880372524261, 0.00882875919342, 0.00731694698334, 0.00772273540497, 0.00712358951569, 0.00865280628204, 0.00907981395721, 0.0110710859299, 0.0109901428223, 0.0117089748383, 0.010435461998, 0.0106043815613, 0.0093834400177, 0.0100009441376, 0.00955045223236, 0.0108293294907, 0.0104821920395, 0.0113124847412, 0.0104421377182, 0.0110911130905, 0.01056432724, 0.0117809772491, 0.0114020109177, 0.0120489597321, 0.0108071565628, 0.0107145309448, 0.0090491771698, 0.00894844532013, 0.00776898860931, 0.00833189487457, 0.00758600234985, 0.00826871395111, 0.00760161876678, 0.00849103927612, 0.00808441638947, 0.0091564655304, 0.00893104076385, 0.0101171731949, 0.00969815254211, 0.0103178024292, 0.00930893421173, 0.00966668128967, 0.00894010066986, 0.0100021362305, 0.00998866558075, 0.011302947998, 0.0111422538757, 0.0122436285019, 0.0118803977966, 0.0126085281372, 0.0118345022202, 0.0123828649521, 0.0117317438126, 0.012547492981, 0.0122623443604, 0.0135762691498, 0.0136877298355, 0.0149359703064, 0.0146152973175, 0.0154184103012, 0.0147166252136, 0.0150654315948, 0.0142164230347, 0.0148787498474, 0.0142657756805, 0.0146261453629, 0.0133748054504, 0.0130347013474, 0.0114990472794, 0.0119148492813, 0.0119198560715, 0.0135172605515, 0.0134842395782, 0.0137825012207, 0.0120311975479, 0.0113086700439, 0.00967442989349, 0.00970685482025, 0.00910377502441, 0.0100984573364, 0.00966334342957, 0.00989091396332, 0.00864911079407, 0.00863337516785, 0.0076984167099, 0.00839829444885, 0.00819897651672, 0.00921547412872, 0.00886738300323, 0.00938725471497, 0.00857424736023, 0.00894236564636, 0.00819039344788, 0.00863993167877, 0.00801241397858, 0.00869178771973, 0.00817716121674, 0.00850999355316, 0.00756227970123, 0.00798285007477, 0.00775241851807, 0.00897693634033, 0.00903809070587, 0.00982177257538, 0.00936806201935, 0.0103105306625, 0.0102736949921, 0.0110545158386, 0.0101515054703, 0.00990307331085, 0.00842249393463, 0.00839245319366, 0.00783669948578, 0.0085117816925, 0.00779390335083, 0.00835812091827, 0.00859904289246, 0.0103785991669, 0.010953783989, 0.0119066238403, 0.0109528303146, 0.0111306905746, 0.0111615657806, 0.0124200582504, 0.0116277933121, 0.0112882852554, 0.0104817152023, 0.011628985405, 0.0118982791901, 0.0124962329865, 0.0108461380005, 0.0102052688599, 0.0098819732666, 0.0122969150543, 0.0145149230957, 0.0177048444748, 0.0184738636017, 0.0182024240494, 0.0156881809235, 0.014317035675, 0.0128412246704, 0.0132899284363, 0.0129480361938, 0.0139595270157, 0.0144982337952, 0.0152686834335, 0.0131714344025, 0.0111796855927, 0.00968897342682, 0.0120204687119, 0.015168428421, 0.0188403129578, 0.0194458961487, 0.0190047025681, 0.0167030096054, 0.0158556699753, 0.0161888599396, 0.0200581550598, 0.022669672966, 0.0230484008789, 0.019584774971, 0.0164115428925, 0.0118594169617, 0.00702774524689, 0.000871419906616, -0.00183081626892, -0.000911831855774, 0.00441253185272, 0.00817739963531, 0.00934934616089, 0.00738835334778, 0.00778698921204, 0.00984728336334, 0.0138756036758, 0.0164625644684, 0.0188897848129, 0.0183520317078, 0.0176184177399, 0.0168305635452, 0.0166647434235, 0.0134110450745, 0.00999879837036, 0.00651383399963, 0.00731575489044, 0.0117008686066, 0.0180587768555, 0.0200403928757, 0.0174430608749, 0.011035323143, 0.00885033607483, 0.0123872756958, 0.0195859670639, 0.0206887722015, 0.0139226913452, 0.00338530540466, -0.00105118751526, -0.000219106674194, 0.00214862823486, 0.000282764434814, -0.00194454193115, -0.00253117084503, 0.00126838684082, 0.00584018230438, 0.00882983207703, 0.00362741947174, -0.00553381443024, -0.0113263130188, -0.00868511199951, -0.00382196903229, 0.00165593624115, 0.00592565536499, 0.0111129283905, 0.0158801078796, 0.0203304290771, 0.0189183950424, 0.0142960548401, 0.00891065597534, 0.00589168071747, 0.00207805633545, -0.000382304191589, -0.00166773796082, 0.00110626220703, 0.00684678554535, 0.0146069526672, 0.0184731483459, 0.0196377038956, 0.0193161964417, 0.0209194421768, 0.0216175317764, 0.0224863290787, 0.0205298662186, 0.0179314613342, 0.0149105787277, 0.0137802362442, 0.0118713378906, 0.0100346803665, 0.00870442390442, 0.0109430551529, 0.0138608217239, 0.0167413949966, 0.0172933340073, 0.0183653831482, 0.0182474851608, 0.0185947418213, 0.0176272392273, 0.0173819065094, 0.0163369178772, 0.0157731771469, 0.0134323835373, 0.0103795528412, 0.00521183013916, 0.000516533851624, -0.00295996665955, -0.000904321670532, 0.00451052188873, 0.0113401412964, 0.0144513845444, 0.0156358480453, 0.0151963233948, 0.0144544839859, 0.0114357471466, 0.00981163978577, 0.00908493995667, 0.00981795787811, 0.0098865032196, 0.0111311674118, 0.0106997489929, 0.00981223583221, 0.00754606723785, 0.00629365444183, 0.00512909889221, 0.00555086135864, 0.00593566894531, 0.00776028633118, 0.00873136520386, 0.0099915266037, 0.00998985767365, 0.0109952688217, 0.0116808414459, 0.0130231380463, 0.0126655101776, 0.0126864910126, 0.0121290683746, 0.012305021286, 0.010938167572, 0.00985634326935, 0.00866568088531, 0.00970816612244, 0.010964512825, 0.012863278389, 0.0134080648422, 0.0145184993744, 0.0153609514236, 0.0174834728241, 0.0182266235352, 0.0185067653656, 0.0173684358597, 0.0173531770706, 0.0165975093842, 0.0159573554993, 0.0136387348175, 0.0119385719299, 0.0101315975189, 0.0100836753845, 0.0101790428162, 0.0119643211365, 0.0132983922958, 0.0145173072815, 0.0134875774384, 0.0120580196381, 0.00933468341827, 0.00772488117218, 0.00649631023407, 0.00700056552887, 0.00711798667908, 0.00796437263489, 0.00773370265961, 0.00805795192719, 0.00738596916199, 0.00686025619507, 0.00517094135284, 0.0046751499176, 0.00437808036804, 0.00539791584015, 0.00572049617767, 0.00671100616455, 0.00691330432892, 0.00789153575897, 0.00827527046204, 0.00941026210785, 0.00981795787811, 0.0106378793716, 0.00994753837585, 0.00918114185333, 0.00711190700531, 0.00582683086395, 0.00459885597229, 0.00497400760651, 0.00527143478394, 0.00673532485962, 0.0077075958252, 0.00947654247284, 0.0102841854095, 0.0111496448517, 0.0110869407654, 0.0120384693146, 0.0124405622482, 0.0131610631943, 0.0126197338104, 0.0122673511505, 0.0107172727585, 0.00945055484772, 0.00725936889648, 0.00621438026428, 0.00563359260559, 0.00685405731201, 0.00775599479675, 0.00919187068939, 0.00989031791687, 0.0111825466156, 0.011572599411, 0.0123138427734, 0.0121610164642, 0.0125560760498, 0.0119544267654, 0.0116701126099, 0.0108672380447, 0.0112124681473, 0.0109843015671, 0.011178612709, 0.010693192482, 0.0114017724991, 0.0119333267212, 0.0129413604736, 0.0128908157349, 0.0134102106094, 0.0134769678116, 0.0144248008728, 0.0144828557968, 0.0145170688629, 0.0133595466614, 0.0124986171722, 0.0108294487, 0.00991129875183, 0.00863409042358, 0.00807726383209, 0.0070892572403, 0.00724744796753, 0.00720834732056, 0.00817179679871, 0.00871682167053, 0.00982797145844, 0.0100243091583, 0.010359287262, 0.00964069366455, 0.0095522403717, 0.00930655002594, 0.00990200042725, 0.00964713096619, 0.00978302955627, 0.00945031642914, 0.00992345809937, 0.00984132289886, 0.0103604793549, 0.0103546380997, 0.0110825300217, 0.0111067295074, 0.0113788843155, 0.0107841491699, 0.0108419656754, 0.0106829404831, 0.0112998485565, 0.0109958648682, 0.0109285116196, 0.0103372335434, 0.0107966661453, 0.011101603508, 0.0120342969894, 0.0120278596878, 0.0123125314713, 0.0120538473129, 0.0124442577362, 0.0118205547333, 0.0111835002899, 0.00990545749664, 0.0096048116684, 0.00929391384125, 0.0100617408752, 0.0106860399246, 0.0119271278381, 0.0121690034866, 0.0124439001083, 0.0118229389191, 0.0116673707962, 0.0109932422638, 0.0106571912766, 0.00950813293457, 0.00853323936462, 0.00738263130188, 0.00768768787384, 0.00809359550476, 0.00962626934052, 0.0102081298828, 0.0102158784866, 0.00954818725586, 0.00951683521271, 0.00825881958008, 0.00714635848999, 0.00622129440308, 0.00709974765778, 0.0086590051651, 0.011620759964, 0.0145227909088, 0.0172824859619, 0.017606139183, 0.016871213913, 0.0152978897095, 0.0143164396286, 0.0129610300064, 0.0120686292648, 0.0105320215225, 0.00896847248077, 0.00688517093658, 0.00668597221375, 0.00728094577789, 0.00776922702789, 0.00649499893188, 0.00641870498657, 0.00761640071869, 0.00870680809021, 0.00773513317108, 0.00723266601562, 0.00738608837128, 0.00836789608002, 0.00778806209564, 0.00686573982239, 0.00587868690491, 0.00601804256439, 0.00521874427795, 0.00372624397278, 0.00202453136444, 0.00241756439209, 0.00404512882233, 0.00648641586304, 0.00809717178345, 0.00948095321655, 0.0103245973587, 0.0114710330963, 0.0109910964966, 0.00986564159393, 0.00847125053406, 0.00777983665466, 0.00700962543488, 0.00708711147308, 0.0075786113739, 0.00917911529541, 0.0099104642868, 0.00943231582642, 0.00746047496796, 0.00612950325012, 0.00587069988251, 0.00717997550964, 0.00786805152893, 0.00815343856812, 0.00826108455658, 0.00972211360931, 0.0114076137543, 0.0124694108963, 0.0117993354797, 0.0106327533722, 0.00921475887299, 0.0086966753006, 0.00812530517578, 0.00802826881409, 0.00759375095367, 0.00764977931976, 0.00752818584442, 0.00735902786255, 0.00651359558105, 0.00651800632477, 0.00674867630005, 0.00721275806427, 0.00720489025116, 0.00752747058868, 0.00787019729614, 0.00881886482239, 0.00927293300629, 0.00932192802429, 0.00873124599457, 0.00895392894745, 0.00990760326385, 0.011527299881, 0.0121972560883, 0.0121128559113, 0.0110148191452, 0.0100494623184, 0.00931012630463, 0.00936603546143, 0.00922155380249, 0.00899589061737, 0.00858354568481, 0.00881218910217, 0.00880110263824, 0.00885593891144, 0.00873005390167, 0.00926852226257, 0.00954639911652, 0.00931894779205, 0.00806355476379, 0.00690269470215, 0.00583648681641, 0.00503838062286, 0.00386583805084, 0.00381302833557, 0.00492799282074, 0.00714766979218, 0.00851786136627, 0.0088130235672, 0.00797533988953, 0.00696420669556, 0.00611436367035, 0.00621974468231, 0.0066522359848, 0.00759541988373, 0.0082585811615, 0.00873029232025, 0.00829076766968, 0.00754427909851, 0.00679504871368, 0.00696539878845, 0.00790441036224, 0.00938475131989, 0.00983047485352, 0.0100841522217, 0.0100164413452, 0.00970923900604, 0.00832307338715, 0.00728487968445, 0.00663375854492, 0.00684356689453, 0.00730109214783, 0.007737159729, 0.00725364685059, 0.0066249370575, 0.00605404376984, 0.00604236125946, 0.00576937198639, 0.00596070289612, 0.00614130496979, 0.00671529769897, 0.00703465938568, 0.00765132904053, 0.00821125507355, 0.00880658626556, 0.00898480415344, 0.0095009803772, 0.00952410697937, 0.00957226753235, 0.00920569896698, 0.00895524024963, 0.00794625282288, 0.00706231594086, 0.00642657279968, 0.00654304027557, 0.00679194927216, 0.00743627548218, 0.00762546062469, 0.00808537006378, 0.00846064090729, 0.00922477245331, 0.00924742221832, 0.00905525684357, 0.00847351551056, 0.00838053226471, 0.00803232192993, 0.00808072090149, 0.00785219669342, 0.00800454616547, 0.00811922550201, 0.00857055187225, 0.00858151912689, 0.00896215438843, 0.00927233695984, 0.00993740558624, 0.00998604297638, 0.00981736183167, 0.00890147686005, 0.008220911026, 0.00744259357452, 0.00736856460571, 0.00716352462769, 0.00730383396149, 0.00704562664032, 0.00713336467743, 0.00674617290497, 0.00651526451111, 0.00598108768463, 0.00599503517151, 0.00586378574371, 0.0064070224762, 0.006995677948, 0.00813829898834, 0.00843894481659, 0.00831854343414, 0.00740313529968, 0.00671720504761, 0.00565409660339, 0.00505197048187, 0.00450313091278, 0.00491297245026, 0.00557899475098, 0.00719690322876, 0.00819993019104, 0.00856137275696, 0.00763058662415, 0.00662064552307, 0.00546562671661, 0.00532698631287, 0.00522923469543, 0.00573801994324, 0.00606179237366, 0.00673758983612, 0.00660586357117, 0.00647807121277, 0.00561487674713, 0.00480890274048, 0.00383067131042, 0.00390124320984, 0.00423455238342, 0.00564193725586, 0.00707745552063, 0.00838601589203, 0.0082186460495, 0.00780034065247, 0.00727486610413, 0.00741255283356, 0.00669050216675, 0.00614857673645, 0.00580525398254, 0.0064343214035, 0.00686478614807, 0.00777065753937, 0.00841927528381, 0.00919759273529, 0.00904285907745, 0.00887525081635, 0.0082106590271, 0.00799250602722, 0.00746953487396, 0.00738573074341, 0.00701189041138, 0.00719749927521, 0.00716519355774, 0.00754737854004, 0.00737059116364, 0.00748860836029, 0.00718879699707, 0.00698041915894, 0.00627338886261, 0.00617671012878, 0.0059278011322, 0.00614941120148, 0.00616383552551, 0.00664734840393, 0.00656378269196, 0.00661385059357, 0.00627028942108, 0.00648415088654, 0.00668060779572, 0.00750291347504, 0.00789999961853, 0.00820887088776, 0.00762689113617, 0.00729465484619, 0.00664436817169, 0.00641310214996, 0.00571501255035, 0.00509536266327, 0.0041731595993, 0.00416541099548, 0.00449216365814, 0.00552380084991, 0.00608623027802, 0.00669848918915, 0.00665903091431, 0.00687623023987, 0.00680470466614, 0.0069637298584, 0.00651037693024, 0.006138920784, 0.00557446479797, 0.00558304786682, 0.00539898872375, 0.00579297542572, 0.00614035129547, 0.00678861141205, 0.0069363117218, 0.00729036331177, 0.00709509849548, 0.00697541236877, 0.0065324306488, 0.00651562213898, 0.00624859333038, 0.00633645057678, 0.00627636909485, 0.00679063796997, 0.00738954544067, 0.00847196578979, 0.00887203216553, 0.00875878334045, 0.0074383020401, 0.00615906715393, 0.00508463382721, 0.00496912002563, 0.00468838214874, 0.00466167926788, 0.00439751148224, 0.0047082901001, 0.00491881370544, 0.0055125951767, 0.00589036941528, 0.00645613670349, 0.00648438930511, 0.00661182403564, 0.00635945796967, 0.0062849521637, 0.00586915016174, 0.00579345226288, 0.00538718700409, 0.00536382198334, 0.00531649589539, 0.00565493106842, 0.00562918186188, 0.00578820705414, 0.00539708137512, 0.00518155097961, 0.00484251976013, 0.00495326519012, 0.00481712818146, 0.00493371486664, 0.00462758541107, 0.00461912155151, 0.00447976589203, 0.00467801094055, 0.00462913513184, 0.00497448444366, 0.00518596172333, 0.00571036338806, 0.00583696365356, 0.00625276565552, 0.00650763511658, 0.0068736076355, 0.00662696361542, 0.00655007362366, 0.00592052936554, 0.00541663169861, 0.00483083724976, 0.00479352474213, 0.00457608699799, 0.00472593307495, 0.00446093082428, 0.00443470478058, 0.00432860851288, 0.00475287437439, 0.00486171245575, 0.00496578216553, 0.00448036193848, 0.00429749488831, 0.00396656990051, 0.00411748886108, 0.00406587123871, 0.00427031517029, 0.00419628620148, 0.00468790531158, 0.00520527362823, 0.00594758987427, 0.0059107542038, 0.00570547580719, 0.00497221946716, 0.00456607341766, 0.00422036647797, 0.00460076332092, 0.00488412380219, 0.00535321235657, 0.00537991523743, 0.00581419467926, 0.00614726543427, 0.00686752796173, 0.00708723068237, 0.00726056098938, 0.00684070587158, 0.00654911994934, 0.00602293014526, 0.00610506534576, 0.00591385364532, 0.00579535961151, 0.00521063804626, 0.00521636009216, 0.00543928146362, 0.00639820098877, 0.00705945491791, 0.00753748416901, 0.00706326961517, 0.00662064552307, 0.00603890419006, 0.00603139400482, 0.00580012798309, 0.00576162338257, 0.00506865978241, 0.00452721118927, 0.00391256809235, 0.00414347648621, 0.00445377826691, 0.00522255897522, 0.00549936294556, 0.00571918487549, 0.00547730922699, 0.00560879707336, 0.00531339645386, 0.00505542755127, 0.00438296794891, 0.00424039363861, 0.00400495529175, 0.00409555435181, 0.00380873680115, 0.0039074420929, 0.00383532047272, 0.00405716896057, 0.00371217727661, 0.00364422798157, 0.00344347953796, 0.00375914573669, 0.00379741191864, 0.0041127204895, 0.00417768955231, 0.00453674793243, 0.0042941570282, 0.00416839122772, 0.00373923778534, 0.00364458560944, 0.00316262245178, 0.00301969051361, 0.00276720523834, 0.00326752662659, 0.00383865833282, 0.00464797019958, 0.00457167625427, 0.0042417049408, 0.00351011753082, 0.00347471237183, 0.00364053249359, 0.00406634807587, 0.00349748134613, 0.00290834903717, 0.00240349769592, 0.00284004211426, 0.0029776096344, 0.00301361083984, 0.00275659561157, 0.00302076339722, 0.00302445888519, 0.00332987308502, 0.00358152389526, 0.00397074222565, 0.00302743911743, 0.00160694122314, 0.000726819038391, 0.00190711021423, 0.00342619419098, 0.00440609455109, 0.00393843650818, 0.00306260585785, 0.0021378993988, 0.0023421049118, 0.00288259983063, 0.00393354892731, 0.00453531742096, 0.00493347644806, 0.00500762462616, 0.00605130195618, 0.00702774524689, 0.00724995136261, 0.00575125217438, 0.00411891937256, 0.00316536426544, 0.0038241147995, 0.00495004653931, 0.00612318515778, 0.00620973110199, 0.00590038299561, 0.0053414106369, 0.00532615184784, 0.00548279285431, 0.00614202022552, 0.00630176067352, 0.00615203380585, 0.00533807277679, 0.00479733943939, 0.00439167022705, 0.00461792945862, 0.00449728965759, 0.00415289402008, 0.00337505340576, 0.00307583808899, 0.00298130512238, 0.00342464447021, 0.0035707950592, 0.00363647937775, 0.003169298172, 0.00289797782898, 0.00267887115479, 0.00296580791473, 0.00299906730652, 0.00301480293274, 0.00263464450836, 0.00238251686096, 0.00208127498627, 0.00239276885986, 0.00267922878265, 0.00270891189575, 0.00178861618042, 0.00078821182251, 0.000131726264954, 0.000693321228027, 0.00174963474274, 0.00286948680878, 0.00331938266754, 0.00380301475525, 0.00421154499054, 0.00477397441864, 0.00489151477814, 0.0048930644989, 0.00456881523132, 0.00451409816742, 0.00434303283691, 0.00422084331512, 0.00373065471649, 0.00343096256256, 0.00313663482666, 0.00326299667358, 0.003422498703, 0.00382685661316, 0.00401616096497, 0.00426363945007, 0.00425624847412, 0.0045371055603, 0.00481641292572, 0.00509583950043, 0.0049079656601, 0.0047892332077, 0.00456273555756, 0.0044059753418, 0.00398254394531, 0.00374233722687, 0.00334870815277, 0.00309681892395, 0.0026752948761, 0.00244641304016, 0.00234377384186, 0.0027824640274, 0.00327098369598, 0.00371432304382, 0.00364327430725, 0.00354790687561, 0.00322079658508, 0.00288891792297, 0.00238966941833, 0.00229442119598, 0.00228714942932, 0.00236916542053, 0.00213921070099, 0.00188183784485, 0.00138604640961, 0.00100147724152, 0.000583171844482, 0.000613331794739, 0.000898480415344, 0.001460313797, 0.00165891647339, 0.00176918506622, 0.00174641609192, 0.00195205211639, 0.00192713737488, 0.00193977355957, 0.00187408924103, 0.00212705135345, 0.00242805480957, 0.00284898281097, 0.00286877155304, 0.00278854370117, 0.0026113986969, 0.00281381607056, 0.00296831130981, 0.00312614440918, 0.00285136699677, 0.00264251232147, 0.00253939628601, 0.00266849994659, 0.00240063667297, 0.00205278396606, 0.00161802768707, 0.00159430503845, 0.00172472000122, 0.00210583209991, 0.00221121311188, 0.00236582756042, 0.00241696834564, 0.002610206604, 0.00255024433136, 0.00264322757721, 0.00274908542633, 0.00317859649658, 0.00348722934723, 0.00362586975098, 0.00310122966766, 0.00242471694946, 0.00164210796356, 0.00143051147461, 0.00151121616364, 0.0018857717514, 0.0020614862442, 0.00256431102753, 0.00317537784576, 0.00395727157593, 0.00429248809814, 0.00438249111176, 0.00382244586945, 0.00308156013489, 0.00219392776489, 0.0017751455307, 0.00160133838654, 0.0019006729126, 0.00223064422607, 0.00289869308472, 0.00342786312103, 0.00393724441528, 0.00401318073273, 0.00400185585022, 0.00381600856781, 0.00374734401703, 0.00339937210083, 0.00326573848724, 0.00319576263428, 0.00355219841003, 0.00390803813934, 0.00437819957733, 0.00441861152649, 0.00436770915985, 0.00402557849884, 0.00386488437653, 0.00355350971222, 0.00341248512268, 0.00330543518066, 0.00386250019073, 0.00426697731018, 0.00415873527527, 0.00337135791779, 0.00281834602356, 0.00225102901459, 0.00199198722839, 0.00189423561096, 0.00219690799713, 0.00235044956207, 0.00262081623077, 0.00243937969208, 0.00213730335236, 0.00175225734711, 0.00180506706238, 0.00180518627167, 0.00190711021423, 0.00158727169037, 0.00119078159332, 0.000548124313354, 0.000363826751709, 0.000778198242188, 0.00211954116821, 0.00331020355225, 0.00406193733215, 0.00402247905731, 0.00348448753357, 0.00212442874908, 0.000918745994568, -4.94718551636e-05, -0.000804781913757, -0.00166356563568, -0.00168204307556, -0.000748038291931, 0.00117552280426, 0.00278675556183, 0.00359785556793, 0.00350427627563, 0.0034145116806, 0.00302958488464, 0.00259530544281, 0.00199246406555, 0.0015082359314, 0.000776886940002, 0.000377655029297, 4.33921813965e-05, 0.000187516212463, 0.000674962997437, 0.00184595584869, 0.00275754928589, 0.00288367271423, 0.00207483768463, 0.00146055221558, 0.00116670131683, 0.00139439105988, 0.00150609016418, 0.00165939331055, 0.00155258178711, 0.00149500370026, 0.000877857208252, -0.000240683555603, -0.00170850753784, -0.00288879871368, -0.00365352630615, -0.00302588939667, -0.00149536132812, 0.000548601150513, 0.0021014213562, 0.00286436080933, 0.00255405902863, 0.00197005271912, 0.00115764141083, 0.000466465950012, -0.000377893447876, -0.00107443332672, -0.00184714794159, -0.00229322910309, -0.00262439250946, -0.00245225429535, -0.0019816160202, -0.000961661338806, 0.00025200843811, 0.00165915489197, 0.00242531299591, 0.00269424915314, 0.00239038467407, 0.00208842754364, 0.00155878067017, 0.00119686126709, 0.00083315372467, 0.000834584236145, 0.000869154930115, 0.00128376483917, 0.00190830230713, 0.00268220901489, 0.00281524658203, 0.00265693664551, 0.00219225883484, 0.00183057785034, 0.00126612186432, 0.000954151153564, 0.000903606414795, 0.00151681900024, 0.00227510929108, 0.00324475765228, 0.00389409065247, 0.0042519569397, 0.00381255149841, 0.00300264358521, 0.00176179409027, 0.000824689865112, -5.12599945068e-05, -0.000724196434021, -0.00137829780579, -0.00135266780853, -0.00113070011139, -0.000504732131958, 0.000163793563843, 0.00103497505188, 0.00160038471222, 0.00220668315887, 0.00247132778168, 0.00265502929688, 0.00258803367615, 0.00267565250397, 0.00246274471283, 0.00225281715393, 0.00159192085266, 0.00121247768402, 0.00121808052063, 0.00191974639893, 0.00254952907562, 0.00317597389221, 0.00333118438721, 0.00355052947998, 0.00353395938873, 0.00354540348053, 0.00321924686432, 0.00313472747803, 0.00298142433167, 0.00309646129608, 0.00280404090881, 0.00239849090576, 0.00167918205261, 0.0012754201889, 0.00100100040436, 0.00126695632935, 0.00137972831726, 0.00149548053741, 0.0010974407196, 0.000980257987976, 0.00117623806, 0.00165772438049, 0.00130176544189, 0.00077223777771, 0.000392198562622, 0.000766396522522, 0.00107872486115, 0.00128054618835, 0.000837802886963, 0.000648498535156, 0.000582933425903, 0.000845789909363, 0.0005943775177, 0.000281810760498, -0.000148892402649, 1.76429748535e-05, 0.000118613243103, 0.000270128250122, -3.81469726562e-05, -4.43458557129e-05, 7.64131546021e-05, 0.000520586967468, 0.00062894821167, 0.00105166435242, 0.00142812728882, 0.0018630027771, 0.0016530752182, 0.00137042999268, 0.000774502754211, 0.000587582588196, 0.000391364097595, 0.000512719154358, 0.000384569168091, 0.000385522842407, 0.000155329704285, 0.000138640403748, -2.34842300415e-05, 0.000282526016235, 0.000568509101868, 0.00103044509888, 0.0010575056076, 0.00100803375244, 0.00049901008606, 0.00020706653595, -0.000218987464905, -0.000443339347839, -0.000831842422485, -0.000781655311584, -0.00068187713623, -0.000153064727783, 0.000382542610168, 0.00106608867645, 0.00109970569611, 0.00105714797974, 0.00084662437439, 0.000778198242188, 0.00031578540802, -4.41074371338e-06, -0.000324130058289, -0.000180959701538, -0.000250935554504, -0.000213146209717, -0.000245809555054, 0.00022828578949, 0.000706076622009, 0.00129759311676, 0.00145673751831, 0.00161910057068, 0.00136959552765, 0.000945806503296, 0.000237822532654, -0.00031852722168, -0.000977039337158, -0.00127112865448, -0.00145256519318, -0.00109887123108, -0.00043249130249, 0.000660419464111, 0.00145399570465, 0.00225138664246, 0.00264644622803, 0.00243270397186, 0.00132894515991, 0.000292062759399, -0.000499606132507, -0.000482797622681, 5.13792037964e-05, 0.000911116600037, 0.00136256217957, 0.00162208080292, 0.00154852867126, 0.00144362449646, 0.00124299526215, 0.00135445594788, 0.0013552904129, 0.00126910209656, 0.00110876560211, 0.00133347511292, 0.0017364025116, 0.00229156017303, 0.00246071815491, 0.00246024131775, 0.00237202644348, 0.00263857841492, 0.00277745723724, 0.00255346298218, 0.0016747713089, 0.000553250312805, -0.000482082366943, -0.000759959220886, -0.000452399253845, 0.000210523605347, 0.000848889350891, 0.00152289867401, 0.00184047222137, 0.00177526473999, 0.00136399269104, 0.00117564201355, 0.00136137008667, 0.00189602375031, 0.00223207473755, 0.00226998329163, 0.00192046165466, 0.00135540962219, 0.00054132938385, -0.000232338905334, -0.000658512115479, -0.00041127204895, 0.000229477882385, 0.00123620033264, 0.0021538734436, 0.00248312950134, 0.00206089019775, 0.00140166282654, 0.000542759895325, -0.000396370887756, -0.00108361244202, -0.000983357429504, -0.000168323516846, 0.000592112541199, 0.000724196434021, 0.000749111175537, 0.00113248825073, 0.00182688236237, 0.00220656394958, 0.0019907951355, 0.00133740901947, 0.000503897666931, -0.000325560569763, -0.000799059867859, -0.000878930091858, -0.000658273696899, -0.000279068946838, 0.000292301177979, 0.000702619552612, 0.000723481178284, 0.000522494316101, 0.000362157821655, 0.000293850898743, 0.00018048286438, 3.0517578125e-05, 2.32458114624e-05, 3.8743019104e-05, -8.8095664978e-05, -0.000190019607544, -4.70876693726e-05, 0.000292897224426, 0.000727295875549, 0.00116884708405, 0.00142431259155, 0.00145828723907, 0.0013542175293, 0.00106155872345, 0.000431418418884, -0.000335454940796, -0.000802993774414, -0.000634789466858, -1.19209289551e-05, 0.000625014305115, 0.000986456871033, 0.00111496448517, 0.000847101211548, 0.000252842903137, -0.000472784042358, -0.00113987922668, -0.00167334079742, -0.00185430049896, -0.00171256065369, -0.0012286901474, -0.000573635101318, 2.49147415161e-05, 0.000243186950684, 0.00017261505127, -3.88622283936e-05, -0.000107049942017, -0.000112295150757, -0.000193953514099, -0.000429630279541, -0.000472545623779, -0.000428676605225, -0.000322699546814, -0.000166296958923, 0.000142812728882, 0.000492811203003, 0.000852227210999, 0.000829935073853, 0.000482082366943, 4.64916229248e-06, -0.000107765197754, 0.000109791755676, 0.000449419021606, 0.000499725341797, 0.000538945198059, 0.000604510307312, 0.000674962997437, 0.000397443771362, -7.97510147095e-05, -0.00068211555481, -0.000961303710938, -0.000846028327942, -0.000258684158325, 0.000286936759949, 0.000704526901245, 0.000887870788574, 0.000975728034973, 0.00081729888916, 0.000656247138977, 0.000335574150085, 0.000165581703186, 0.000105500221252, 0.000240921974182, 0.000239014625549, 0.000285863876343, 0.000183343887329, 0.000155210494995, 9.58442687988e-05, 0.000125408172607, -5.59091567993e-05, -0.000141620635986, -0.000211238861084, -3.07559967041e-05, 0.000129222869873, 0.000444531440735, 0.000605702400208, 0.000733017921448, 0.000612020492554, 0.000609517097473, 0.000536441802979, 0.00068461894989, 0.000886797904968, 0.00122630596161, 0.00123357772827, 0.0011944770813, 0.000936269760132, 0.000691771507263, 0.000145554542542, -0.000296950340271, -0.000681638717651, -0.000676870346069, -0.000618696212769, -0.000296711921692, -8.08238983154e-05, 0.000129461288452, 4.18424606323e-05, 8.66651535034e-05, 0.0, 9.51290130615e-05, 0.000159025192261, 0.000420928001404, 0.000452399253845, 0.00057315826416, 0.000494480133057, 0.000447511672974, 0.000158905982971, 0.000108957290649, 5.88893890381e-05, 0.000302195549011, 0.000412344932556, 0.000554442405701, 0.000347852706909, 0.000239491462708, 9.76324081421e-05, 0.000316262245178, 0.000444531440735, 0.000734925270081, 0.000836610794067, 0.00103640556335, 0.000889539718628, 0.00073516368866, 0.000397562980652, 0.000369668006897, 0.000208735466003, 0.000221133232117, 0.000158429145813, 0.000398278236389, 0.000418305397034, 0.000476241111755, 0.000312209129333, 0.000305533409119, 2.02655792236e-05, -0.000178217887878, -0.00054657459259, -0.000519394874573, -0.000418543815613, -1.02519989014e-05, 0.000172734260559, 0.00043785572052, 0.000385165214539, 0.00043523311615, 0.00023365020752, 0.000162363052368, -0.000179052352905, -0.000312209129333, -0.000504970550537, -0.000341176986694, -0.000223159790039, 0.00019109249115, 0.000360012054443, 0.000600576400757, 0.000614166259766, 0.000831842422485, 0.000709652900696, 0.000542402267456, 2.24113464355e-05, -0.000211238861084, -0.000347495079041, -1.19209289551e-05, 0.000267267227173, 0.000768899917603, 0.00091552734375, 0.00104224681854, 0.00081479549408, 0.000730395317078, 0.000466108322144, 0.000385165214539, 1.23977661133e-05, -0.00022280216217, -0.000596404075623, -0.000636100769043, -0.000726461410522, -0.000438332557678, -0.000217080116272, 0.000208139419556, 0.00032365322113, 0.000491857528687, 0.000324010848999, 0.000310182571411, 6.86645507812e-05, -1.43051147461e-05, -0.000234603881836, -0.000116348266602, -0.000172257423401, -0.000112891197205, -0.000287175178528, -0.000162482261658, -0.000176906585693, -8.89301300049e-05, -0.000313997268677, -0.000255823135376, -0.000267386436462, 4.07695770264e-05, 0.000186562538147, 0.000401616096497, 0.000226259231567, 0.00030779838562, 0.000367641448975, 0.000685334205627, 0.000678896903992, 0.00064754486084, 0.00025200843811, 0.00016450881958, 7.60555267334e-05, 0.000205755233765, 1.50203704834e-05, 6.33001327515e-05, 2.76565551758e-05, 0.00020694732666, 0.000156760215759, 0.000362277030945, 0.000382542610168, 0.000570178031921, 0.00054395198822, 0.000743746757507, 0.000744223594666, 0.000945448875427, 0.000856399536133, 0.000773191452026, 0.000314950942993, 9.51290130615e-05, -0.00019359588623, -4.48226928711e-05, 0.000120520591736, 0.000501155853271, 0.000446200370789, 0.000415802001953, 0.000221371650696, 0.000284552574158, 5.47170639038e-05, 4.05311584473e-05, -0.000102877616882, -4.64916229248e-05, -0.000262260437012, -0.000295877456665, -0.000590205192566, -0.000718116760254, -0.0010176897049, -0.000951886177063, -0.000924110412598, -0.000545024871826, -0.000397086143494, -0.000169634819031, -0.000247478485107, -0.000101804733276, -0.000121712684631, 0.000127553939819, 0.000165224075317, 0.000329375267029, 0.000135540962219, 9.29832458496e-05, -0.000174283981323, -0.000258207321167, -0.000549077987671, -0.000465512275696, -0.000450015068054, -0.000195622444153, -0.000205993652344, -3.0517578125e-05, -0.000133395195007, -4.81605529785e-05, -0.000114560127258, 0.000118732452393, 9.60826873779e-05, 0.000221252441406, 5.43594360352e-05, 3.43322753906e-05, -0.000215888023376, -0.000116109848022, -0.000101804733276, 0.000168919563293, 0.000148415565491, 0.00025486946106, 0.000117897987366, 0.000251412391663, 0.000137090682983, 0.000168323516846, -7.64131546021e-05, -7.11679458618e-05, -0.000208854675293, -3.33786010742e-05, -7.5101852417e-05, 5.01871109009e-05, -0.000130414962769, -9.07182693481e-05, -0.000198125839233, -6.36577606201e-05, -0.000240921974182, -0.000282287597656, -0.000569343566895, -0.000548958778381, -0.000617384910583, -0.000325441360474, -0.000198602676392, 9.22679901123e-05, 7.0333480835e-06, -1.44243240356e-05, -0.000357270240784, -0.000359535217285, -0.000336170196533, 5.6266784668e-05, 0.00015389919281, 0.000335812568665, 0.000194668769836, 0.000261664390564, 8.83340835571e-05, 7.99894332886e-05, -0.000192642211914, -0.000205397605896, -0.00039279460907, -0.000296711921692, -0.000369906425476, -0.000190377235413, -0.000242114067078, -8.36849212646e-05, -0.000137090682983, 7.31945037842e-05, 6.89029693604e-05, 0.0002521276474, 0.000182747840881, 0.000335216522217, 0.000220060348511, 0.000234723091125, -3.62396240234e-05, -5.9962272644e-05, -0.000259876251221, -0.000151395797729, -0.000182867050171, 4.64916229248e-06, -9.0479850769e-05, 5.18560409546e-05, 3.51667404175e-05, 0.000251650810242, 0.000165343284607, 0.000187993049622, -5.84125518799e-05, -5.20944595337e-05, -0.000225186347961, -0.000156760215759, -0.000300765037537, -0.00023353099823, -0.000370740890503, -0.000217914581299, -0.000233054161072, -2.03847885132e-05, -7.37905502319e-05, 1.78813934326e-06, -0.000224471092224, -0.000220537185669, -0.000370383262634, -0.000250458717346, -0.000315070152283, -0.000144720077515, -0.000207424163818, -6.46114349365e-05, -0.000146746635437, -3.81469726562e-05, -0.000178337097168, -9.6321105957e-05, -0.000170469284058, -3.57627868652e-07, -0.000132918357849, -0.000140309333801, -0.000350713729858, -0.000274419784546, -0.000361442565918, -0.000197768211365, -0.000219225883484, -1.41859054565e-05, -5.79357147217e-05, 3.3974647522e-05, -0.000156402587891, -0.000168442726135, -0.000388503074646, -0.000355005264282, -0.000494241714478, -0.0003981590271, -0.000476598739624, -0.000298976898193, -0.000300645828247, -5.50746917725e-05, -2.86102294922e-06, 0.000213384628296, 0.000147581100464, 0.00024151802063, 0.000100493431091, 0.000102043151855, -0.000184655189514, -0.000256896018982, -0.000451922416687, -0.00039005279541, -0.000517725944519, -0.000387787818909, -0.000385761260986, -0.000109553337097, -1.63316726685e-05, 0.000223636627197, 0.000167727470398, 0.000246644020081, 8.79764556885e-05, 5.36441802979e-05, -0.000242352485657, -0.000266551971436, -0.000347375869751, -0.000122427940369, -6.5803527832e-05, 0.000115275382996, -3.34978103638e-05, -4.56571578979e-05, -0.000245571136475, -0.000239491462708, -0.000431537628174, -0.000381588935852, -0.000443339347839, -0.000229477882385, -0.00019371509552, -2.65836715698e-05, -0.000187397003174, -0.00025737285614, -0.000469446182251, -0.000320553779602, -0.000267386436462, -6.66379928589e-05, -0.000177025794983, -0.000207662582397, -0.000481009483337, -0.000545263290405, -0.000732898712158, -0.000634431838989, -0.000633597373962, -0.000406742095947, -0.000375390052795, -0.000189542770386, -0.00023090839386, -0.000118851661682, -0.000212430953979, -0.000128269195557, -0.000220060348511, -9.42945480347e-05, -9.21487808228e-05, 0.000124573707581, 0.000118613243103, 0.000218033790588, 5.88893890381e-05, 4.63724136353e-05, -0.000114440917969, -2.08616256714e-05, -7.02142715454e-05, 5.96046447754e-07, -0.000174045562744, -0.000153183937073, -0.000219225883484, -2.16960906982e-05, 3.75509262085e-05, 0.000231027603149, 0.000160694122314, 0.000204682350159, 7.02142715454e-05, 9.79900360107e-05, -0.000102639198303, -0.000180959701538, -0.000383019447327, -0.000299692153931, -0.000293970108032, -8.71419906616e-05, -8.48770141602e-05, -2.92062759399e-05, -0.00023365020752, -0.000271916389465, -0.000419735908508, -0.000362277030945, -0.000437617301941, -0.000325918197632, -0.000381231307983, -0.000283241271973, -0.000341773033142, -0.00023365020752, -0.000279903411865, -0.000164031982422, -0.000214457511902, -0.00011157989502, -0.000146865844727, 1.060962677e-05, -7.0333480835e-06, 3.57627868652e-05, -0.000146865844727, -0.000160813331604, -0.000257849693298, -0.00016725063324, -0.000265717506409, -0.000263452529907, -0.000409603118896, -0.000370860099792, -0.000453472137451, -0.000343322753906, -0.000314831733704, -0.000120639801025, -0.000103831291199, 2.49147415161e-05, -2.47955322266e-05, 3.64780426025e-05, -7.22408294678e-05, -6.06775283813e-05, -0.000207304954529, -0.000209808349609, -0.00033974647522, -0.000306010246277, -0.000383615493774, -0.000301599502563, -0.000355839729309, -0.000274062156677, -0.000337243080139, -0.000258684158325, -0.000300407409668, -0.000221490859985, -0.000327229499817, -0.000311374664307, -0.000408530235291, -0.000346660614014, -0.000375032424927, -0.000251412391663, -0.000288963317871, -0.000200033187866, -0.000205159187317, -5.90085983276e-05, -6.07967376709e-05, 2.76565551758e-05, -7.06911087036e-05, -0.000121831893921, -0.000356554985046, -0.000436186790466, -0.000556588172913, -0.000457525253296, -0.000420451164246, -0.000239968299866, -0.000203132629395, -4.86373901367e-05, -3.51667404175e-05, 2.63452529907e-05, -0.000132918357849, -0.00022304058075, -0.000410676002502, -0.000394940376282, -0.000421285629272, -0.000278949737549, -0.000248551368713, -0.00013256072998, -0.000171899795532, -0.000110626220703, -0.000197172164917, -0.00021231174469, -0.000335574150085, -0.000262975692749, -0.000230312347412, -8.55922698975e-05, -0.000122904777527, -8.27312469482e-05, -0.000120401382446, -9.17911529541e-06, -3.71932983398e-05, -3.32593917847e-05, -0.000204682350159, -0.000256061553955, -0.000350952148438, -0.000281691551208, -0.000329852104187, -0.000285387039185, -0.000328183174133, -0.000227332115173, -0.000229358673096, -0.000142812728882, -0.000182032585144, -0.000124931335449, -0.000175476074219, -0.000114679336548, -0.000127553939819, -1.59740447998e-05, -3.81469726562e-05, -2.53915786743e-05, -0.000137090682983, -0.000117301940918, -0.000167012214661, -0.00011670589447, -0.000194072723389, -0.000200510025024, -0.000304102897644, -0.000260949134827, -0.00023877620697, -6.75916671753e-05, 0.0, 0.000117421150208, 7.59363174438e-05, 6.05583190918e-05, -8.73804092407e-05, -0.000116109848022, -0.000195384025574, -0.000145554542542, -0.00014865398407, -2.77757644653e-05, 1.10864639282e-05, 0.000121593475342, 9.6321105957e-05, 0.000117301940918, 2.08616256714e-05, 1.41859054565e-05, -6.96182250977e-05, -4.58955764771e-05, -9.11951065063e-05, -4.58955764771e-05, -8.85725021362e-05, -1.66893005371e-06, 6.41345977783e-05, 0.000218510627747, 0.000213027000427, 0.000224828720093, 0.000124335289001, 0.000109672546387, 3.17096710205e-05, 5.73396682739e-05, -1.87158584595e-05, -3.94582748413e-05, -0.000126838684082, -6.8187713623e-05, -5.31673431396e-05, 2.93254852295e-05, -6.79492950439e-06, 3.57627868652e-07, -0.000123739242554, -0.000182390213013, -0.000258803367615, -0.000182390213013, -0.000187635421753, -0.000171184539795, -0.000269532203674, -0.000273942947388, -0.000308275222778, -0.000219821929932, -0.000175952911377, -3.43322753906e-05, 2.41994857788e-05, 0.000118851661682, 7.49826431274e-05, 3.20672988892e-05, -0.000149607658386, -0.000289797782898, -0.000485062599182, -0.000527620315552, -0.000540494918823, -0.000393629074097, -0.000257730484009, -2.121925354e-05, 9.56058502197e-05, 0.000173687934875, 6.96182250977e-05, -1.77621841431e-05, -0.00017261505127, -0.000217080116272, -0.000294089317322, -0.000282883644104, -0.000337362289429, -0.000308275222778, -0.000318288803101, -0.000239968299866, -0.000224590301514, -0.000154614448547, -0.000204086303711, -0.000255703926086, -0.000373244285583, -0.000369548797607, -0.000385880470276, -0.000346541404724, -0.000399351119995, -0.0003662109375, -0.000353217124939, -0.000294089317322, -0.000349760055542, -0.00036609172821, -0.000434994697571, -0.000406503677368, -0.000381112098694, -0.000257015228271, -0.000210881233215, -0.000141859054565, -0.000156044960022, -0.000136852264404, -0.000223994255066, -0.000310897827148, -0.000466704368591, -0.000491261482239, -0.000453591346741, -0.000287532806396, -0.000199317932129, -0.000110268592834, -0.00010085105896, -5.10215759277e-05, -9.14335250854e-05, -9.83476638794e-05, -0.00015664100647, -0.000149607658386, -0.000186681747437, -0.000184416770935, -0.000252604484558, -0.0002601146698, -0.000272274017334, -0.000194430351257, -0.000170350074768, -0.00012731552124, -0.000141859054565, -8.53538513184e-05, -6.00814819336e-05, -1.43051147461e-05, -8.8095664978e-05, -0.000172138214111, -0.000285029411316, -0.000288009643555, -0.000287055969238, -0.000221490859985, -0.00020444393158, -0.000158190727234, -0.000168681144714, -0.000138878822327, -0.000148177146912, -0.00011670589447, -0.000125169754028, -8.10623168945e-05, -7.14063644409e-05, -3.61204147339e-05, -7.8558921814e-05, -0.000117182731628, -0.000198125839233, -0.000212788581848, -0.000234007835388, -0.000192165374756, -0.000174880027771, -0.000113248825073, -8.5711479187e-05, -3.3974647522e-05, -4.39882278442e-05, -4.92334365845e-05, -0.000102281570435, -0.000106930732727, -0.000125527381897, -0.000107526779175, -0.000130891799927, -0.000117778778076, -0.000126361846924, -9.14335250854e-05, -8.02278518677e-05, -4.97102737427e-05, -7.55786895752e-05, -8.55922698975e-05, -0.000111699104309, -9.00030136108e-05, -0.000102519989014, -9.75131988525e-05, -0.000113844871521, -7.99894332886e-05, -6.04391098022e-05, -2.13384628296e-05, -1.87158584595e-05, 4.76837158203e-06, -6.19888305664e-06, -1.27553939819e-05, -5.93662261963e-05, -7.83205032349e-05, -0.00010359287262, -8.85725021362e-05, -8.46385955811e-05, -5.36441802979e-05, -5.47170639038e-05, -5.68628311157e-05, -9.77516174316e-05, -0.000117540359497, -0.000148296356201, -0.000152826309204, -0.000177502632141, -0.000184178352356, -0.00020432472229, -0.000190138816833, -0.00017786026001, -0.000135064125061, -0.000110745429993, -8.84532928467e-05, -0.000109434127808, -0.000123143196106, -0.000145316123962, -0.000135898590088, -0.000121831893921, -7.04526901245e-05, -2.93254852295e-05, 6.55651092529e-06, -3.81469726562e-06, -2.27689743042e-05, -5.98430633545e-05, -7.53402709961e-05, -9.77516174316e-05, -9.72747802734e-05, -9.66787338257e-05, -7.54594802856e-05, -6.71148300171e-05, -5.18560409546e-05, -4.82797622681e-05, -2.68220901489e-05, -1.65700912476e-05, -5.24520874023e-06, -1.07288360596e-05, -2.26497650146e-06, -3.09944152832e-06, -1.90734863281e-06, -2.00271606445e-05, -3.07559967041e-05, -4.63724136353e-05, -4.3511390686e-05, -4.20808792114e-05, -2.99215316772e-05, -2.96831130981e-05, -2.52723693848e-05, -3.31401824951e-05, -3.64780426025e-05, -5.1736831665e-05, -6.52074813843e-05, -8.77380371094e-05, -9.44137573242e-05, -9.22679901123e-05, -7.45058059692e-05, -6.75916671753e-05, -6.35385513306e-05, -6.98566436768e-05, -7.06911087036e-05, -7.76052474976e-05, -7.54594802856e-05, -7.36713409424e-05, -6.3419342041e-05, -5.80549240112e-05, -4.66108322144e-05, -4.00543212891e-05, -3.11136245728e-05, -2.99215316772e-05, -2.64644622803e-05, -2.77757644653e-05, -2.74181365967e-05, -3.57627868652e-05, -4.1127204895e-05, -4.41074371338e-05, -3.7670135498e-05, -3.32593917847e-05, -2.43186950684e-05, -1.6450881958e-05, -6.07967376709e-06, -4.52995300293e-06, -6.31809234619e-06, -1.33514404297e-05, -1.77621841431e-05, -2.36034393311e-05, -2.38418579102e-05, -2.19345092773e-05, -1.51395797729e-05, -1.060962677e-05, -5.36441802979e-06, -3.33786010742e-06, -2.02655792236e-06, -4.17232513428e-06, -5.72204589844e-06, -8.94069671631e-06, -1.03712081909e-05, -1.10864639282e-05, -8.82148742676e-06, -7.15255737305e-06, -5.36441802979e-06, -4.17232513428e-06, -2.02655792236e-06, -7.15255737305e-07, 0.0, 0.0 }; // frames int __init__ = add_ir(name, vendor, mic, frames, samplerate); } // Orange_Metamp_4x12_M930_1 #endif
109.080808
123
0.785313
[ "vector" ]
bcac5b290de40e24cc8c9721d867de5aeeead829
1,515
h
C
src/Renderer/RenderCommand.h
Stral9315/xsngine
4a4afe21f12483dbe266113b17a4b51ea850ee56
[ "MIT" ]
13
2015-02-05T22:44:29.000Z
2021-09-04T21:28:10.000Z
src/Renderer/RenderCommand.h
Stral9315/xsngine
4a4afe21f12483dbe266113b17a4b51ea850ee56
[ "MIT" ]
47
2015-03-23T14:11:06.000Z
2017-05-21T05:14:57.000Z
src/Renderer/RenderCommand.h
Stral9315/xsngine
4a4afe21f12483dbe266113b17a4b51ea850ee56
[ "MIT" ]
7
2015-04-29T00:48:23.000Z
2018-04-01T13:12:40.000Z
#pragma once #include "Renderer/Renderer.h" #include "Common/Matrix.h" namespace Renderer { struct Material; class Model; class ShaderProgram; extern ShaderProgram *quadProgram; //FIXME: polymorphism? enum class CommandType { DrawQuad, DrawModel, DrawParticles, Screenshot }; struct DrawQuadCommand { vector2 pos; vector2 size; vector2 st1, st2; vector4 colour; const Material *material; }; struct DrawModelCommand { const Model *model; RenderInfo info; }; struct DrawParticlesCommand { const Backend::Buffer *vbo; const Backend::Buffer *ibo; const Material *material; size_t count; }; struct ScreenshotCommand { int32_t width; int32_t height; GLuint pbo; GLsync sync; const char *name; }; struct RenderCommand { private: CommandType type; public: union { DrawQuadCommand drawQuad; DrawModelCommand drawModel; DrawParticlesCommand drawParticles; ScreenshotCommand screenshot; }; // don't allow default instantiation RenderCommand() = delete; RenderCommand( CommandType commandType ) : type( commandType ) { } // initialise render command queue // create default material, allocate GPU buffers static void Init( void ); // clean up GPU resources static void Shutdown( void ); // dispatch the render command to the associated function void Execute( void ) const; }; // ??? void DrawQuad( const DrawQuadCommand &cmd ); } // namespace Renderer
14.708738
59
0.688449
[ "render", "model" ]
2952e00e33bbc976fb3df287ddad6b2a49001f76
11,549
h
C
include/cozy/cose.h
microbuilder/cozy
ae616b3eb0e718f093d138fc82852c5d418aba5b
[ "Apache-2.0" ]
8
2020-07-01T04:48:09.000Z
2021-12-23T03:13:31.000Z
include/cozy/cose.h
motet/cozy
ae616b3eb0e718f093d138fc82852c5d418aba5b
[ "Apache-2.0" ]
1
2021-09-23T08:49:53.000Z
2021-09-23T08:49:53.000Z
include/cozy/cose.h
motet/cozy
ae616b3eb0e718f093d138fc82852c5d418aba5b
[ "Apache-2.0" ]
1
2021-09-23T08:40:03.000Z
2021-09-23T08:40:03.000Z
/* * Copyright 2020 RISE Research Institutes of Sweden * * 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 COSE_H #define COSE_H #include <zephyr.h> #include <string.h> #include "nanocbor/nanocbor.h" #ifndef CONFIG_MBEDTLS_CFG_FILE #include "mbedtls/config-tls-generic.h" #else #include CONFIG_MBEDTLS_CFG_FILE #endif #include <mbedtls/md.h> #include <mbedtls/pk.h> #include <mbedtls/gcm.h> #include <mbedtls/ecp.h> #include <mbedtls/ecdsa.h> #include <mbedtls/error.h> #define COSE_CONTEXT_SIGN "Signature" #define COSE_CONTEXT_SIGN1 "Signature1" #define COSE_CONTEXT_COUNTERSIGN "CounterSignature" #define COSE_CONTEXT_MAC "MAC" #define COSE_CONTEXT_MAC0 "MAC0" #define COSE_CONTEXT_ENCRYPT "Encrypt" #define COSE_CONTEXT_ENCRYPT0 "Encrypt0" #define COSE_CONTEXT_ENC_RECIPIENT "Enc_Recipient" #define COSE_CONTEXT_MAC_RECIPIENT "Mac_Recipient" #define COSE_CONTEXT_REC_RECIPIENT "Rec_Recipient" #define DUMPX(var) printk("%s = %x\n", #var, var); #define DUMPD(var) printk("%s = %d\n", #var, var); #define DUMPS(var) printk("%s = %s\n", #var, var); /** * @brief COSE API * @{ */ #define COSE_ERROR_NONE 0x00 #define COSE_ERROR_MBEDTLS 0x01 #define COSE_ERROR_NANOCBOR 0x02 #define COSE_ERROR_UNSUPPORTED 0x03 #define COSE_ERROR_ENCODE 0x04 #define COSE_ERROR_DECODE 0x05 #define COSE_ERROR_AUTHENTICATE 0x06 #define COSE_ERROR_MISMATCH 0x07 #define COSE_ERROR_HASH 0x08 #define COSE_ERROR_ENCRYPT 0x09 #define COSE_ERROR_DECRYPT 0x0a #define COSE_ERROR_SIGN 0x0b #define COSE_ERROR_OVERFLOW 0x0c typedef enum { cose_tag_sign = 98, cose_tag_sign1 = 18, cose_tag_encrypt = 96, cose_tag_encrypt0 = 16, cose_tag_mac = 97, cose_tag_mac0 = 17, } cose_tag_t; typedef enum { cose_alg_aes_gcm_128 = 1, cose_alg_aes_gcm_192 = 2, cose_alg_aes_gcm_256 = 3, cose_alg_hmac_256_64 = 4, cose_alg_hmac_256_256 = 5, cose_alg_hmac_384_384 = 6, cose_alg_hmac_512_512 = 7, cose_alg_cbc_mac_128_64 = 14, cose_alg_cbc_mac_256_64 = 15, cose_alg_cbc_mac_128_128 = 25, cose_alg_cbc_mac_256_128 = 26, cose_alg_aes_ccm_16_64_128 = 10, cose_alg_aes_ccm_16_64_256 = 11, cose_alg_aes_ccm_64_64_128 = 12, cose_alg_aes_ccm_64_64_256 = 13, cose_alg_aes_ccm_16_128_128 = 30, cose_alg_aes_ccm_16_128_256 = 31, cose_alg_aes_ccm_64_128_128 = 32, cose_alg_aes_ccm_64_128_256 = 33, cose_alg_ecdh_es_hkdf_256 = -25, cose_alg_ecdh_es_hkdf_512 = -26, cose_alg_ecdh_ss_hkdf_256 = -27, cose_alg_ecdh_ss_hkdf_512 = -28, cose_alg_ecdh_es_a128kw = -29, cose_alg_ecdh_es_a192kw = -30, cose_alg_ecdh_es_a256kw = -31, cose_alg_ecdh_ss_a128kw = -32, cose_alg_ecdh_ss_a192kw = -33, cose_alg_ecdh_ss_a256kw = -34, cose_alg_aes_kw_128 = -3, cose_alg_aes_kw_192 = -4, cose_alg_aes_kw_256 = -5, cose_alg_direct = -6, cose_alg_direct_hkdf_hmac_sha_256 = -10, cose_alg_direct_hkdf_hmac_sha_512 = -11, cose_alg_direct_hkdf_aes_128 = -12, cose_alg_direct_hkdf_aes_256 = -13, cose_alg_ecdsa_sha_256 = -7, cose_alg_ecdsa_sha_384 = -35, cose_alg_ecdsa_sha_512 = -36, } cose_alg_t; typedef enum { cose_header_algorithm = 1, cose_header_critical = 2, cose_header_content_type = 3, cose_header_kid = 4, cose_header_iv = 5, cose_header_partial_iv = 6, cose_header_countersign = 7, cose_header_operation_time = 8, cose_header_countersign0 = 9, cose_header_hkdf_salt = -20, cose_header_kdf_u_name = -21, cose_header_kdf_u_nonce = -22, cose_header_kdf_u_other = -23, cose_header_kdf_v_name = -24, cose_header_kdf_v_nonce = -25, cose_header_kdf_v_other = -26, cose_header_ecdh_ephemeral = -1, cose_header_ecdh_static = -2, cose_header_ecdh_epk = -1, cose_header_ecdh_spk = -2, cose_header_ecdh_spk_kid = -3, } cose_header_t; typedef enum { cose_key_label_kty = 1, cose_key_label_kid = 2, cose_key_label_alg = 3, cose_key_label_key_ops = 4, cose_key_label_base_iv = 5, } cose_key_label_t; typedef enum { cose_key_op_sign = 1, cose_key_op_verify = 2, cose_key_op_encrypt = 3, cose_key_op_decrypt = 4, cose_key_op_wrap_key = 5, cose_key_op_unwrap_key = 6, cose_key_op_derive_key = 7, cose_key_op_derive_bits = 8, cose_key_op_mac_create = 9, cose_key_op_mac_verify = 10, } cose_key_op_t; typedef enum { cose_kty_okp = 1, cose_kty_ec2 = 2, cose_kty_symmetric = 4, } cose_kty_t; typedef enum { cose_ec_param_crv = -1, cose_ec_param_x = -2, cose_ec_param_y = -3, cose_ec_param_d = -4, } cose_ec_param_t; typedef enum { cose_octet_param_crv = -1, cose_octet_param_x = -2, cose_octet_param_d = -4, } cose_octet_param_t; typedef enum { cose_symmetric_param_K = -1, } cose_symmetric_param_t; typedef enum { cose_curve_p256 = 1, cose_curve_p384 = 2, cose_curve_p251 = 3, cose_curve_x25519 = 4, cose_curve_x448 = 5, cose_curve_ed25519 = 6, cose_curve_ed448 = 7, } cose_curve_t; typedef enum { cwt_claim_iss = 1, /* Issuer */ cwt_claim_sub = 2, /* Subject */ cwt_claim_aud = 3, /* Audience */ cwt_claim_exp = 4, /* Expiration Time */ cwt_claim_nbf = 5, /* Not Before */ cwt_claim_iat = 6, /* Issued At */ cwt_claim_cti = 7, /* CWT ID */ } cwt_claim_t; typedef enum { cose_mode_r = 1, /* read */ cose_mode_w = 2, /* write */ } cose_mode_t; typedef struct { /* internal */ cose_kty_t kty; cose_alg_t alg; cose_curve_t crv; cose_key_op_t op; size_t len_key; /* api accessible */ const uint8_t * kid; size_t len_kid; const uint8_t * aad; size_t len_aad; } cose_key_t; typedef struct { cose_key_t key; /* internal */ size_t len_sig; size_t len_hash; mbedtls_pk_context pk; mbedtls_md_type_t md_alg; } cose_sign_context_t; typedef struct { cose_key_t key; /* internal */ int cipher; size_t len_mac; uint8_t * iv; size_t len_iv; mbedtls_gcm_context gcm; } cose_crypt_context_t; void cose_set_kid(cose_key_t * key, const uint8_t * kid, size_t len_kid); void cose_set_aad(cose_key_t * key, const uint8_t * aad, size_t len_aad); /** * @brief Initialize COSE signing context * * @param ctx Pointer to uninitialized signing context * @param mode 0 for signature generation, 1 for verification * @param pem PEM-formatted key string * * @retval COSE_ERROR_NONE Success * @retval COSE_ERROR_MBEDTLS Failed to parse key string * @retval COSE_ERROR_UNSUPPORTED Crypto algorithm not supported */ int cose_sign_init(cose_sign_context_t * ctx, cose_mode_t mode, const uint8_t * pem); /** * @brief Initialize COSE encryption and MAC context * * @param ctx Pointer to uninitialized encryption and MAC context * @param key Pointer to raw key bytes * @param alg Crypto algorithm allowed for use with this key * @param iv Initialization vector * @param len_iv Length of IV * * @retval COSE_ERROR_NONE Success * @retval COSE_ERROR_UNSUPPORTED Crypto algorithm not supported */ int cose_crypt_init(cose_crypt_context_t * ctx, const uint8_t * key, cose_alg_t alg, uint8_t * iv, const size_t len_iv); /* free underlying mbedTLS contexts */ void cose_sign_free(cose_sign_context_t * ctx); void cose_crypt_free(cose_crypt_context_t * ctx); /** * @brief Encode a COSE Sign1 object * * @param ctx Pointer to the COSE signing context * @param pld Pointer to the payload to be signed * @param len_pld Length of the payload * @param[out] obj Pointer to output buffer for encoded object * @param[out] len_obj Pointer to length of buffer * * @retval COSE_ERROR_NONE Success * @retval COSE_ERROR_ENCODE Failed to encode COSE object * @retval COSE_ERROR_HASH Failed to hash authenticated data * @retval COSE_ERROR_SIGN Failed to encrypt message diggest */ int cose_sign1_write(cose_sign_context_t * ctx, const uint8_t * pld, const size_t len_pld, uint8_t * obj, size_t * len_obj); /** * @brief Decode a COSE Sign1 object * * @param ctx Pointer to the COSE signing context * @param obj Pointer to the encoded COSE object * @param len_obj Length of encode COSE object * @param[out] pld Pointer to payload within COSE object * @param[out] len_pld Payload length * * @retval COSE_ERROR_NONE Success * @retval COSE_ERROR_DECODE Failed to decode COSE object * @retval COSE_ERROR_HASH Failed to hash authenticated data * @retval COSE_ERROR_AUTHENTICATE Failed to authenticate signature */ int cose_sign1_read(cose_sign_context_t * ctx, const uint8_t * obj, const size_t len_obj, const uint8_t ** pld, size_t * len_pld); /** * @brief Encode a COSE Encrypt object * * @param ctx Pointer to the COSE encryption and MAC context * @param pld Pointer to the payload to be encrypted (and MACed) * @param len_pld Length of the payload * @param[out] obj Pointer to output buffer for encoded object * @param[out] len_obj Pointer to length of buffer * * @retval COSE_ERROR_NONE Success * @retval COSE_ERROR_ENCODE Failed to encode COSE object * @retval COSE_ERROR_ENCRYPT Failed to encrypt (and MAC) data */ int cose_encrypt0_write(cose_crypt_context_t *ctx, const uint8_t * pld, const size_t len_pld, uint8_t * obj, size_t * len_obj); /** * @brief Decode a COSE Encrypt object * * @param ctx Pointer to the COSE encryption and MAC context * @param obj Pointer to the encoded COSE object * @param len_obj Length of encode COSE object * @param[out] pld Pointer to the output buffer for decoded payload * @param[out] len_pld Pointer to length of buffer * * @retval COSE_ERROR_NONE Success * @retval COSE_ERROR_ENCODE Failed to encode authenticated data structure * @retval COSE_ERROR_DECODE Failed to decode COSE object * @retval COSE_ERROR_DECRYPT Failed to decrypt/authenticate COSE object */ int cose_encrypt0_read(cose_crypt_context_t * ctx, const uint8_t * obj, const size_t len_obj, uint8_t * pld, size_t * len_pld); /** * @brief Not yet implemented */ int cose_mac0_write(cose_crypt_context_t *ctx, const uint8_t * pld, const size_t len_pld, uint8_t * obj, size_t * len_obj); /** * @brief Not yet implemented */ int cose_mac0_read(cose_crypt_context_t * ctx, const uint8_t * obj, const size_t len_obj, uint8_t * pld, size_t * len_pld); /** * @} */ #endif /* COSE_H */
30.472296
86
0.684128
[ "object", "vector" ]
296552543adbf5b53c088ec99e9434aa16a5cb64
26,779
c
C
src/Emulators/atari800/ide.c
slajerek/RetroDebugger
e761e4f9efd103a05e65ef283423b142fa4324c7
[ "Apache-2.0", "MIT" ]
34
2021-05-29T07:04:17.000Z
2022-03-10T20:16:03.000Z
src/Emulators/atari800/ide.c
slajerek/RetroDebugger
e761e4f9efd103a05e65ef283423b142fa4324c7
[ "Apache-2.0", "MIT" ]
6
2021-12-25T13:05:21.000Z
2022-01-19T17:35:17.000Z
src/Emulators/atari800/ide.c
slajerek/RetroDebugger
e761e4f9efd103a05e65ef283423b142fa4324c7
[ "Apache-2.0", "MIT" ]
6
2021-12-24T18:37:41.000Z
2022-02-06T23:06:02.000Z
/* * ide.c - Emulate IDE interface * * Copyright (C) 2010 Ivo van Poorten * * Based on QEMU IDE disk emulator (hw/ide/{core.c,microdrive.c,mmio.c}) * Copyright (C) 2003 Fabrice Bellard * Copyright (C) 2006 Openhand Ltd. * * 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. */ /* Emulate 8-bit and 16-bit IDE interface at $D500-$D50F * * Eight 16-bit IDE registers: * * LSB (bit 0..7) at 0xd500-0xd507 * MSB (bit 8..15) at 0xd508-0xd50f * * Full 16-bits are read and written when accessing the LSB (latch) * * If the MSB is ignored, the interface is compatible with MyIDE * * 16-bit operations: * * Read: read LSB (device returns 1 16-bit word), read MSB * Write: write MSB, write LSB (16-bit word is written to device) */ #define _XOPEN_SOURCE 600 #include "atari-config.h" /* allow non-ansi fseek/ftell functions */ #ifdef __STRICT_ANSI__ # undef __STRICT_ANSI__ # include <stdio.h> # define __STRICT_ANSI__ 1 #else # include <stdio.h> #endif #include "ide.h" #include "atari.h" #include "a-log.h" #include "a-util.h" #include "ide_internal.h" #include <string.h> #ifdef HAVE_INTTYPES_H # include <inttypes.h> #endif #include <stdlib.h> #include <errno.h> #ifdef HAVE_UNISTD_H # include <unistd.h> #endif #define SECTOR_SIZE 512 #define STD_HEADS 16 #define STD_SECTORS 63 /* #if defined (HAVE_WINDOWS_H) # define fseeko fseeko64 # define ftello ftello64 #elif defined (__BEOS__) # define fseeko _fseek # define ftello _ftell # define PRId64 "lld" #elif defined (__DJGPP__) # define fseeko fseek # define ftello ftell # define PRId64 "lld" #endif */ #ifndef HAVE_FSEEKO #define fseeko(a, b, c) fseek(a, b, c) #define ftello(a) ftell(a) #endif #ifdef WIN32 #include "snprintf.h" #endif int IDE_enabled = 0, IDE_debug = 0; struct ide_device device; static int count = 0; /* for debug stuff */ static void inline padstr(uint8_t *str, const char *src, int len) { int i; for(i = 0; i < len; i++) str[i^1] = *src ? *src++ : ' '; } #define LE16(x,y,z) { (x)[(y)<<1] = (z)&0xff; (x)[((y)<<1)+1] = ((uint16_t)z)>>8; } static void ide_identify(struct ide_device *s) { unsigned int oldsize; uint8_t *p = s->io_buffer; memset(p, 0, 512); LE16(p, 0, GCBI_FIXED_DRIVE); LE16(p, 1, s->cylinders); LE16(p, 3, s->heads); /* LE16(p, 4, 512 * s->sectors); // bytes per track, obsolete ATA2 LE16(p, 5, 512); // bytes per sector, obsolete ATA2 */ LE16(p, 6, s->sectors); /* sectors per track */ padstr(p+10*2, s->drive_serial_str, 20); /* LE16(p, 20, 3); // buffer type, obsolete ATA2 LE16(p, 21, 16); // cache size in sectors, obsolete ATA2 */ LE16(p, 22, 4); /* number of ECC bytes */ padstr(p+23*2, PACKAGE_VERSION, 8); padstr(p+27*2, "ATARI800 HARDDISK", 40); if (MAX_MULT_SECTORS > 1) LE16(p, 47, 0x8000 | MAX_MULT_SECTORS); LE16(p, 48, 0); /* cannot perform double word I/O */ LE16(p, 49, CAP_LBA_SUPPORTED); LE16(p, 51, 0x0200); /* PIO transfer cycle */ /* LE16(p, 52, 0x0200); // DMA transfer cycle, obsolete ATA3 */ LE16(p, 53, 1/*+2+4*/); /* words 54-58[,64-70,88] are valid */ LE16(p, 54, s->cylinders); LE16(p, 55, s->heads); LE16(p, 56, s->sectors); oldsize = s->cylinders * s->heads * s->sectors; LE16(p, 57, oldsize); LE16(p, 58, oldsize >> 16); if (s->mult_sectors) LE16(p, 59, 0x100 | s->mult_sectors); LE16(p, 60, s->nb_sectors); /* total number of LBA sectors */ LE16(p, 61, s->nb_sectors >> 16); if (s->is_cf) { LE16(p, 0, 0x848a); /* CF Storage Card signature */ padstr(p+27*2, "ATARI800 MICRODRIVE", 40); LE16(p, 49, CAP_LBA_SUPPORTED); LE16(p, 51, 2); LE16(p, 52, 1); } if (s->is_cdrom) { LE16(p, 0, GCBI_HAS_PACKET_FEAT_SET | GCBI_CDROM_DEVICE | GCBI_HAS_REMOVABLE_MEDIA | GCBI_50US_TILL_DRQ | GCBI_12BYTE_PACKETS); padstr(p+27*2, "ATARI800 DVD-ROM", 40); LE16(p, 49, CAP_LBA_SUPPORTED); } } static void ide_dummy_transfer_stop(struct ide_device *s) { s->data_ptr = s->data_end = s->io_buffer; s->io_buffer[0] = s->io_buffer[1] = s->io_buffer[2] = s->io_buffer[3] = 0xff; count = 0; } static void ide_reset(struct ide_device *s) { if (IDE_debug) fprintf(stderr, "ide: reset\n"); if (s->is_cf) s->mult_sectors = 0; else s->mult_sectors = MAX_MULT_SECTORS; /* ide regs */ s->feature = s->error = s->nsector = s->sector = s->lcyl = s->hcyl = 0; /* lba48 */ s->hob_feature = s->hob_sector = s->hob_nsector = s->hob_lcyl = s->hob_hcyl = s->lba48 = 0; s->select = 0xa0; s->status = READY_STAT | SEEK_STAT; /* ATAPI stuff skipped */ s->select &= 0xf0; /* clear head */ s->nsector = s->sector = 1; if (s->is_cdrom) { s->lcyl = 0x14; s->hcyl = 0xeb; } else { s->lcyl = s->hcyl = 0; } s->end_transfer_func = ide_dummy_transfer_stop; ide_dummy_transfer_stop(s); s->media_changed = 0; } static int ide_init_drive(struct ide_device *s, char *filename) { if (!(s->file = fopen(filename, "rb+"))) { Log_print("%s: %s", filename, strerror(errno)); return FALSE; } s->blocksize = SECTOR_SIZE; fseeko(s->file, 0, SEEK_END); s->filesize = ftello(s->file); if (IDE_debug) fprintf(stderr, "ide: filesize: %"PRId64"\n", (int64_t)s->filesize); if (!s->io_buffer) { s->io_buffer_size = SECTOR_SIZE * MAX_MULT_SECTORS; s->io_buffer = Util_malloc(s->io_buffer_size); } s->nb_sectors = s->filesize / SECTOR_SIZE; /* use standard physical disk geometry */ s->cylinders = s->nb_sectors / (STD_HEADS * STD_SECTORS); if (s->cylinders > 16383) s->cylinders = 16383; else if (s->cylinders < 2) { Log_print("%s: image file too small\n", filename); fclose(s->file); return FALSE; } s->heads = STD_HEADS; s->sectors = STD_SECTORS; if (IDE_debug) fprintf(stderr, "ide: cyls/heads/secs - %d/%d/%d\n", s->cylinders, s->heads, s->sectors); s->drive_serial = 1; snprintf(s->drive_serial_str, sizeof(s->drive_serial_str), "QM%05d", s->drive_serial); ide_reset(s); return TRUE; } static uint32_t ide_ioport_read(struct ide_device *s, uint16_t addr) { int ret = 0xff, hob = 0; addr &= 7; /* hob = s->select & (1<<7); */ /* FIXME: HOB stuff is broken/disabled in QEMU */ switch(addr) { case 0: /* bottom ide layer does nothing here */ break; case 1: ret = hob ? s->hob_feature : s->error; break; case 2: ret = hob ? s->hob_nsector : s->nsector & 0xff; break; case 3: ret = hob ? s->hob_sector : s->sector; break; case 4: ret = hob ? s->hob_lcyl : s->lcyl; break; case 5: ret = hob ? s->hob_hcyl : s->hcyl; break; case 6: ret = s->select; break; default: case 7: ret = s->status; break; } if (IDE_debug) fprintf(stderr, "ide: get: addr: %04x, ret: %02x\n", addr, ret); return ret; } static inline void not_implemented(uint8_t val) { if (IDE_debug) fprintf(stderr, "\tIDE: %02x not implemented\n", val); } static inline void ide_abort_command(struct ide_device *s) { s->status = READY_STAT | ERR_STAT; s->error = ABRT_ERR; } static void ide_cmd_lba48_transform(struct ide_device *s, int lba48) { s->lba48 = lba48; if (!s->lba48) { if (!s->nsector) s->nsector = 256; } else { if (!s->nsector && !s->hob_nsector) s->nsector = 65536; else s->nsector = (s->hob_nsector << 8) | s->nsector; } } static int64_t ide_get_sector(struct ide_device *s) { int64_t sector_num; if (s->select & 0x40) { /* lba */ if (IDE_debug) fprintf(stderr, "get_sector: lba\n"); if (!s->lba48) { sector_num = ((s->select & 0x0f) << 24) | ( s->hcyl << 16) | ( s->lcyl << 8) | s->sector; } else { sector_num = ((int64_t) s->hob_hcyl << 40) | ((int64_t) s->hob_lcyl << 32) | ((int64_t) s->hob_sector << 24) | ((int64_t) s->hcyl << 16) | ((int64_t) s->lcyl << 8) | s->sector; } } else { sector_num = ((s->hcyl << 8) | s->lcyl) * s->heads * s->sectors + (s->select & 0x0f) * s->sectors + (s->sector - 1); if (IDE_debug) fprintf(stderr, "get_sector: large: hcyl %02x lcyl %02x heads %02x sectors %02x select&f %1x sector-1 %d sector_num %"PRId64"\n", s->hcyl, s->lcyl, s->heads, s->sectors, s->select&0x0f, s->sector-1, sector_num); } return sector_num; } static void ide_transfer_start(struct ide_device *s, uint8_t *buf, int size, EndTransferFunc *end_transfer_func) { if (IDE_debug) fprintf(stderr, "transfer start\n"); s->end_transfer_func = end_transfer_func; s->data_ptr = buf; s->data_end = buf + size; s->cycle = 0; if (!(s->status & ERR_STAT)) s->status |= DRQ_STAT; } static void ide_transfer_stop(struct ide_device *s) { if (IDE_debug) fprintf(stderr, "transfer stop\n"); s->end_transfer_func = ide_transfer_stop; s->data_ptr = s->io_buffer; s->data_end = s->io_buffer; s->status &= ~DRQ_STAT; count = 0; } static void ide_set_sector(struct ide_device *s, int64_t sector_num) { unsigned int cyl, r; if (s->select & 0x40) { if (!s->lba48) { s->select = (s->select & 0xf0) | (sector_num >> 24); s->hcyl = sector_num >> 16 ; s->lcyl = sector_num >> 8 ; s->sector = sector_num ; } else { s->sector = sector_num ; s->lcyl = sector_num >> 8; s->hcyl = sector_num >> 16; s->hob_sector = sector_num >> 24; s->hob_lcyl = sector_num >> 32; s->hob_hcyl = sector_num >> 40; } } else { cyl = sector_num / (s->heads * s->sectors); r = sector_num % (s->heads * s->sectors); s->hcyl = cyl >> 8; s->lcyl = cyl ; s->select = (s->select & 0xf0) | ((r / s->sectors) & 0x0f); s->sector = (r % s->sectors) + 1; } } static void ide_sector_read(struct ide_device *s) { int64_t sector_num; int n; s->status = READY_STAT | SEEK_STAT; s->error = 0; sector_num = ide_get_sector(s); n = s->nsector; if (!n) { ide_transfer_stop(s); } else { if (IDE_debug) fprintf(stderr, "IDE: read sector=%" PRId64 "\n", sector_num); if (n > s->req_nb_sectors) n = s->req_nb_sectors; if (fseeko(s->file, sector_num * SECTOR_SIZE, SEEK_SET) < 0) goto fail; if (fread(s->io_buffer, n * SECTOR_SIZE, 1, s->file) != 1) goto fail; if (IDE_debug) fprintf(stderr, "sector read OK\n"); ide_transfer_start(s, s->io_buffer, 512*n, ide_sector_read); s->nsector -= n; ide_set_sector(s, sector_num + n + (s->nsector ? 0 : -1)); } return; fail: ide_abort_command(s); if (IDE_debug) fprintf(stderr, "sector read FAILED\n"); } static void ide_sector_write(struct ide_device *s) { int64_t sector_num; int n, n1; s->status = READY_STAT | SEEK_STAT; sector_num = ide_get_sector(s); if (IDE_debug) fprintf(stderr, "IDE: write sector=%" PRId64 "\n", sector_num); n = s->nsector; if (n > s->req_nb_sectors) n = s->req_nb_sectors; if (fseeko(s->file, sector_num * SECTOR_SIZE, SEEK_SET) < 0) { fprintf(stderr, "FSEEKO FAILED\n"); goto fail; } if (fwrite(s->io_buffer, n * SECTOR_SIZE, 1, s->file) != 1) { fprintf(stderr, "FWRITE FAILED\n"); goto fail; } fflush(s->file); s->nsector -= n; if (s->nsector == 0) { ide_transfer_stop(s); } else { n1 = s->nsector; if (n1 > s->req_nb_sectors) n1 = s->req_nb_sectors; ide_transfer_start(s, s->io_buffer, 512 * n1, ide_sector_write); } ide_set_sector(s, sector_num + n + (s->nsector ? 0 : -1)); return; fail: ide_abort_command(s); } static void ide_command(struct ide_device *s, uint8_t val) { int lba48 = 0, n; switch(val) { case WIN_IDENTIFY: ide_identify(s); s->status = READY_STAT | SEEK_STAT; ide_transfer_start(s, s->io_buffer, 512, ide_transfer_stop); break; case WIN_SPECIFY: case WIN_RECAL: s->error = 0; s->status = READY_STAT | SEEK_STAT; break; case WIN_SETMULT: if (s->is_cf && !s->nsector) { s->mult_sectors = 0; s->status = READY_STAT | SEEK_STAT; } else if ((s->nsector & 0xff) != 0 && ((s->nsector & 0xff) > MAX_MULT_SECTORS || (s->nsector & (s->nsector - 1)) != 0)) { ide_abort_command(s); } else { s->mult_sectors = s->nsector & 0xff; s->status = READY_STAT | SEEK_STAT; } break; case WIN_VERIFY_EXT: lba48 = 1; case WIN_VERIFY: case WIN_VERIFY_ONCE: /* do sector number check ? */ ide_cmd_lba48_transform(s, lba48); s->status = READY_STAT | SEEK_STAT; break; case WIN_READ_EXT: lba48 = 1; case WIN_READ: case WIN_READ_ONCE: ide_cmd_lba48_transform(s, lba48); s->req_nb_sectors = 1; ide_sector_read(s); break; case WIN_WRITE_EXT: lba48 = 1; case WIN_WRITE: case WIN_WRITE_ONCE: case CFA_WRITE_SECT_WO_ERASE: case WIN_WRITE_VERIFY: ide_cmd_lba48_transform(s, lba48); s->error = 0; s->status = SEEK_STAT | READY_STAT; s->req_nb_sectors = 1; ide_transfer_start(s, s->io_buffer, 512, ide_sector_write); s->media_changed = 1; break; case WIN_MULTREAD_EXT: lba48 = 1; case WIN_MULTREAD: if (!s->mult_sectors) goto abort_cmd; ide_cmd_lba48_transform(s, lba48); s->req_nb_sectors = s->mult_sectors; ide_sector_read(s); break; case WIN_MULTWRITE_EXT: lba48 = 1; case WIN_MULTWRITE: case CFA_WRITE_MULTI_WO_ERASE: if (!s->mult_sectors) goto abort_cmd; ide_cmd_lba48_transform(s, lba48); s->error = 0; s->status = SEEK_STAT | READY_STAT; s->req_nb_sectors = s->mult_sectors; n = s->nsector; if (n > s->req_nb_sectors) n = s->req_nb_sectors; ide_transfer_start(s, s->io_buffer, 512 * n, ide_sector_write); s->media_changed = 1; break; case WIN_READDMA_EXT: case WIN_READDMA: case WIN_READDMA_ONCE: case WIN_WRITEDMA_EXT: case WIN_WRITEDMA: case WIN_WRITEDMA_ONCE: not_implemented(val); goto abort_cmd; break; case WIN_READ_NATIVE_MAX_EXT: lba48 = 1; case WIN_READ_NATIVE_MAX: ide_cmd_lba48_transform(s, lba48); ide_set_sector(s, s->nb_sectors - 1); s->status = READY_STAT | SEEK_STAT; break; case WIN_CHECKPOWERMODE1: case WIN_CHECKPOWERMODE2: s->nsector = 0xff; /* device active or idle */ s->status = READY_STAT | SEEK_STAT; break; case WIN_SETFEATURES: switch(s->feature) { case FEAT_ENABLE_REVERTING_TO_DEFAULTS: case FEAT_DISABLE_REVERTING_TO_DEFAULTS: case FEAT_ENABLE_WRITE_CACHE: case FEAT_DISABLE_WRITE_CACHE: case FEAT_ENABLE_READ_LOOKAHEAD: case FEAT_DISABLE_READ_LOOKAHEAD: case FEAT_ENABLE_ADVANCED_PM: case FEAT_DISABLE_ADVANCED_PM: case FEAT_ENABLE_AUTO_ACOUSTIC_MNGMNT: case FEAT_DISABLE_AUTO_ACOUSTIC_MNGMNT: s->status = READY_STAT | SEEK_STAT; break; case FEAT_SET_TRANSFER_MODE: if ( (s->nsector >> 3) <= 1) { /* 0: pio default, 1: pio mode */ /* set identify_data accordingly */ } else { /* single word dma, mdma and udma mode */ goto abort_cmd; } s->status = READY_STAT | SEEK_STAT; break; case FEAT_ENABLE_8BIT_DATA_TRANSFERS: if (IDE_debug) fprintf(stderr, "ide: enable 8-bit mode\n"); s->do_8bit = 1; s->cycle = 0; s->status = READY_STAT | SEEK_STAT; break; case FEAT_DISABLE_8BIT_DATA_TRANSFERS: if (IDE_debug) fprintf(stderr, "ide: disable 8-bit mode\n"); s->do_8bit = 0; s->status = READY_STAT | SEEK_STAT; break; default: goto abort_cmd; break; } break; case WIN_FLUSH_CACHE: case WIN_FLUSH_CACHE_EXT: fflush(s->file); break; case WIN_STANDBY: case WIN_STANDBY2: case WIN_STANDBYNOW1: case WIN_STANDBYNOW2: case WIN_IDLEIMMEDIATE: case CFA_IDLEIMMEDIATE: case WIN_SETIDLE1: case WIN_SETIDLE2: case WIN_SLEEPNOW1: case WIN_SLEEPNOW2: s->status = READY_STAT; break; case WIN_SEEK: if(s->is_cdrom) goto abort_cmd; /* XXX: Check that seek is within bounds and return error if not */ s->status = READY_STAT | SEEK_STAT; break; /* ATAPI Commands SKIPPED */ /* CF-ATA commands */ case CFA_REQ_EXT_ERROR_CODE: if (!s->is_cf) goto abort_cmd; s->error = 0x09; /* miscellaneous error, MARK_ERR | MCR_ERR */ s->status = READY_STAT | SEEK_STAT; break; case CFA_ERASE_SECTORS: case CFA_WEAR_LEVEL: if (!s->is_cf) goto abort_cmd; if (val == CFA_WEAR_LEVEL) s->nsector = 0; if (val == CFA_ERASE_SECTORS) s->media_changed = 1; s->error = 0; s->status = READY_STAT | SEEK_STAT; break; case CFA_TRANSLATE_SECTOR: if (!s->is_cf) goto abort_cmd; s->error = 0; s->status = READY_STAT | SEEK_STAT; memset(s->io_buffer, 0, 0x200); s->io_buffer[0x00] = s->hcyl; /* Cyl MSB */ s->io_buffer[0x01] = s->lcyl; /* Cyl LSB */ s->io_buffer[0x02] = s->select; /* Head */ s->io_buffer[0x03] = s->sector; /* Sector */ s->io_buffer[0x04] = ide_get_sector(s) >> 16; /* LBA MSB */ s->io_buffer[0x05] = ide_get_sector(s) >> 8; /* LBA */ s->io_buffer[0x06] = ide_get_sector(s) >> 0; /* LBA LSB */ s->io_buffer[0x13] = 0x00; /* Erase flag */ s->io_buffer[0x18] = 0x00; /* Hot count */ s->io_buffer[0x19] = 0x00; /* Hot count */ s->io_buffer[0x1a] = 0x01; /* Hot count */ ide_transfer_start(s, s->io_buffer, 0x200, ide_transfer_stop); break; case CFA_ACCESS_METADATA_STORAGE: if (!s->is_cf) goto abort_cmd; not_implemented(val); /* FIXME: ... not yet */ goto abort_cmd; break; case IBM_SENSE_CONDITION: if (!s->is_cf) goto abort_cmd; switch (s->feature) { case 0x01: /* sense temperature in device */ s->nsector = 0x50; /* +20 C */ break; default: goto abort_cmd; } s->status = READY_STAT | SEEK_STAT; break; case WIN_SMART: not_implemented(val); /* FIXME: ... not yet */ goto abort_cmd; break; default: abort_cmd: ide_abort_command(s); break; } } static void ide_clear_hob(struct ide_device *s) { s->select &= ~(1<<7); } static void ide_ioport_write(struct ide_device *s, uint16_t addr, uint8_t val){ if (IDE_debug) fprintf(stderr, "ide: put: addr: %04x, byte: %02x\n", addr, val); addr &= 7; /* ignore writes to command block while busy */ if (addr != 7 && s->bus_status & (BUSY_STAT|DRQ_STAT)) return; switch(addr) { case 0: /* bottom ide layer does nothing here */ break; case 1: ide_clear_hob(s); s->hob_feature = s->feature; s->feature = val; break; case 2: ide_clear_hob(s); s->hob_nsector = s->nsector; s->nsector = val; break; case 3: ide_clear_hob(s); s->hob_sector = s->sector; s->sector = val; break; case 4: ide_clear_hob(s); s->hob_lcyl = s->lcyl; s->lcyl = val; break; case 5: ide_clear_hob(s); s->hob_hcyl = s->hcyl; s->hcyl = val; break; case 6: /* FIXME: HOB readback uses bit 7 */ s->select = (val & ~0x10) | 0xa0; s->bus_unit = (val>>4)&1; break; default: case 7: if (IDE_debug) fprintf(stderr, "\tIDE: CMD=%02x\n", val); ide_transfer_stop(s); /* if ( (s->status & (BUSY_STAT|DRQ_STAT)) && val != WIN_DEVICE_RESET) break; */ ide_command(s, val); break; } } static uint16_t ide_data_readw(struct ide_device *s, int addr) { uint8_t *p; uint16_t ret; /* PIO data access only when DRQ bit is set */ if (!(s->status & DRQ_STAT)) return 0; /* LE16 */ p = s->data_ptr; ret = p[0]; ret |= p[1] << 8; p += 2; s->data_ptr = p; if (IDE_debug) { fprintf(stderr, "data_readw: %d, %04x (count: %d)\n", addr, ret, count); count++; count &= 0xff; } if (p >= s->data_end) s->end_transfer_func(s); return ret; } static void ide_data_writew(struct ide_device *s, int addr, uint16_t val) { uint8_t *p; if (IDE_debug) fprintf(stderr, "data_writew: %d, %04x\n", addr, val); /* PIO data access only when DRQ bit is set */ if (!(s->status & DRQ_STAT)) return; /* LE16 */ p = s->data_ptr; p[0] = val & 0xff; p[1] = val >> 8; p += 2; s->data_ptr = p; if (p >= s->data_end) s->end_transfer_func(s); } static uint8_t mmio_ide_read(struct ide_device *s, int addr) { uint16_t ret; /* will be cast at return */ addr &= 15; if (addr == 0) { if (!s->do_8bit) { ret = ide_data_readw(s, 0); s->upperhalf[0] = ret & 0xff00; return ret; } if (!s->cycle) { s->data = ide_data_readw(s, 0); ret = s->data & 0xff; } else { ret = s->data >> 8; } s->cycle = !s->cycle; return ret; } else if (addr >= 8) { return s->upperhalf[addr-8] >> 8; } else { ret = ide_ioport_read(s, addr); s->upperhalf[addr] = ret & 0xff00; return ret; } } static void mmio_ide_write(struct ide_device *s, int addr, uint8_t val) { addr &= 15; if (addr == 0) { if (!s->do_8bit) { ide_data_writew(s, 0, s->upperhalf[0] | val); return; } if (!s->cycle) { s->data = val & 0xff; } else { ide_data_writew(s, 0, s->data | (val << 8)); } s->cycle = !s->cycle; } else if (addr >= 8) { s->upperhalf[addr-8] = val << 8; } else { ide_ioport_write(s, addr, s->upperhalf[addr] | val); } } void IDE_PutByte(uint16_t addr, uint8_t val) { struct ide_device *s = &device; mmio_ide_write(s, addr, val); } uint8_t IDE_GetByte(uint16_t addr, int no_side_effects) { struct ide_device *s = &device; return mmio_ide_read(s, addr); } int IDE_Initialise(int *argc, char *argv[]) { int i, j, ret = TRUE; char *filename = NULL; if (IDE_debug) fprintf(stderr, "ide: init\n"); for (i = j = 1; i < *argc; i++) { int available = i + 1 < *argc; if (!strcmp(argv[i], "-ide" )) { if (!available) { Log_print("Missing argument for '%s'", argv[i]); return FALSE; } filename = Util_strdup(argv[++i]); } else if (!strcmp(argv[i], "-ide_debug")) { IDE_debug = 1; } else if (!strcmp(argv[i], "-ide_cf")) { device.is_cf = 1; } else { if (!strcmp(argv[i], "-help")) { Log_print("\t-ide <file> Enable IDE emulation"); Log_print("\t-ide_debug Enable IDE Debug Output"); Log_print("\t-ide_cf Enable CF emulation"); } argv[j++] = argv[i]; } } *argc = j; if (filename) { IDE_enabled = ret = ide_init_drive(&device, filename); free(filename); } return ret; } void IDE_Exit(void) { if (IDE_enabled) { fclose(device.file); IDE_enabled = FALSE; } }
29.013001
229
0.544793
[ "geometry" ]
2966fa294d5e320a098c216eff6777d74b920051
10,704
h
C
src/prmplanner.h
idincern/prm_sim
9c576d200eb4576a289dae42ca9c08729aceecd7
[ "MIT" ]
3
2020-02-24T22:32:44.000Z
2021-05-06T23:13:11.000Z
src/prmplanner.h
idincern/prm_sim
9c576d200eb4576a289dae42ca9c08729aceecd7
[ "MIT" ]
null
null
null
src/prmplanner.h
idincern/prm_sim
9c576d200eb4576a289dae42ca9c08729aceecd7
[ "MIT" ]
2
2020-06-12T12:24:22.000Z
2021-10-19T11:25:46.000Z
/*! @file * * @brief A low dispersion PRM planner. * * The idea of the LD-PRM is to capture the connectivity of the * configuration space with fewer samples, which reduces the * running time of the algorithm. Different to a simple PRM planner, * the samples generated by the LD-PRM must fufil an important criterion * in order to be included inside the roadmap. Samples are forbidden to * be close to each other more than a predefined radius. This criterion * creates an almost uniform distribution of samples which helps in * narrow passageways. * For more information, please see http://cdn.intechopen.com/pdfs/45913.pdf * * @author arosspope * @date 12-10-2017 */ #ifndef PRMPLANNER_H #define PRMPLANNER_H #include <map> #include <utility> #include "localmap.h" #include "graph.h" #include "types.h" //PrmPlanner default constants const double PLANNER_DEF_MAP_SIZE = 20.0; /*!< The default ogmap size is 20x20m */ const double PLANNER_DEF_MAP_RES = 0.1; /*!< The default ogmap resolution is 0.1m per pixel */ const unsigned int PLANNER_DEF_DENSITY = 5; /*!< The default max amount of neighbours a node in the network can have */ class PrmPlanner { public: /*! @brief Default constructor for PrmPlanner. */ PrmPlanner(); /*! @brief Constructor for a PrmPlanner. * * @param mapSize The size of the OgMap in meters (square maps only). * @param mapRes The resolution of the OgMaps provided to this object. * @param density The density of the prm network (max neighbours a node can have). * * @note This will set the reference position to 0,0 by default. To change this, * call setReference(). */ PrmPlanner(double mapSize, double mapRes, unsigned int density); /*! @brief Builds a prm network between a start and end ordinate. * * @param cspace The OgMap to build the prm network within. Must be already expanded. * @param start The starting ordinate. This is usually the robot's position. * @param goal The goal ordiante to reach from start. * @return vector<TGlobalOrd> - An ordered vector of globalOrd's between start * and goal. This will be empty if no path was * discovered. */ std::vector<TGlobalOrd> build(cv::Mat &cspace, TGlobalOrd start, TGlobalOrd goal); /*! @brief Query the network for a path between start and goal within cspace. * * @param cspace The map configuration space. Must be already expanded. * @param start The starting ordinate. This is usually the robot's position. * @param goal The goal ordiante to reach from start. * @return vector<TGlobalOrd> - An ordered vector of globalOrd's between start * and goal. This will be empty if no path was * discovered. */ std::vector<TGlobalOrd> query(cv::Mat &cspace, TGlobalOrd start, TGlobalOrd goal); /*! @brief Expands the configuration space of a map. * * So that we are able to treat the robot as a point in space, * we expand the boundaries of non-free space by the diameter of * the robot. * * @param space The space (map) to expand. * @param robotDiameter The diameter of the robot in meters. */ void expandConfigSpace(cv::Mat &space, double robotDiameter); /*! @brief Overlays the current state of the PRM unto a colour OgMap. * * Not only will this overlay the prm (in blue), but if supplied with * a valid non-empty path, it will also overaly this trajectory (red). * * @param space The OgMap to overlay the PRM and path on top of. * @param path The path to also overlay. Empty if no path to display. */ void showOverlay(cv::Mat &space, std::vector<TGlobalOrd> path); /*! @brief Sets the reference position of the provided OgMaps. * * @param reference The reference to set, this is usually the robot's * global position. */ void setReference(const TGlobalOrd reference); /*! @brief Updates the size of the OgMaps provided. * * @param mapSize The size of the OgMap in meters (square maps only). */ void setMapSize(double mapSize); /*! @brief Updates the resolution of the OgMaps provided. * * @param resolution The size of the OgMap in meters. */ void setResolution(double resolution); /*! @brief Indicates if the given ordinate is acessible in cspace. * * @param cspace The space to check for the ordinate. * @param ordinate The ordiante to check. * @return TRUE - If the ordinate is within known, free space. */ bool ordinateAccessible(cv::Mat &cspace, TGlobalOrd ordinate); private: Graph graph_; /*!< A graph representation of the roadmap network */ LocalMap lmap_; /*!< An object for interacting with the ogMap provided to this object */ std::map<vertex, TGlobalOrd> network_; /*!< A look up table to convert a vertex to coordinate within map */ vertex nextVertexId_; /*!< Used for generating unique vertex ids for coordiantes */ TGlobalOrd reference_; /*!< Reference ordinate for the local map, this is usually the robot position */ unsigned int density_; /*!< The density of the prm network (max neighbours a node can have). */ /*! @brief Optimises a path between two points in a config space. * * In some cases, the shortest path in a PRM network may not be the * most direct route between a start and goal. This function aims * to remove the points in the path that can be directly accessed * by earlier points. For example, if there is a direct path between * start and goal, this function will find it. * * @param cspace The configuration space to find direct access within. * @param path An ordered representation of the path, where the first element * is the start, and the end element is the goal. */ std::vector<TGlobalOrd> optimisePath(cv::Mat &cspace, std::vector<TGlobalOrd> path); /*! @brief Embeds a node in the prm network. * * Given a node, determine the closest k neighbours and * attempt to connect to them. * * @param cspace The configuration space to embed the node in. * @param node The node to connect and embed. * @param k The amount of neighbours to attempt to connect to. * @param retry If this is TRUE, then the algorithm will ensure * that k neighbours have been connected to. However, * this assurance will depend on the density of the network * and the amount of actual nodes in the network. */ void embedNode(cv::Mat &cspace, vertex node, unsigned int k, bool retry); /*! @brief Joins node configurations to eachother within the network. * * * @param cspace The configuration space to embed the nodes in. * @param k The amount of neighbours to attempt to connect too (for each node). */ void joinNetwork(cv::Mat &cspace, unsigned int k); /*! @brief Returns a representation of the internal PRM. * * @return vector<<Point, Point>> - A vector of pairs of points. This represents * their connection to eachother. Verticies that have * no neighbours are simply paired with themselves. */ std::vector<std::pair<cv::Point, cv::Point>> composePRM(); /*! @brief Converts a path of globalOrds to OgMap points. * * @param path The path of ordiantes to convert. * @return vector<points> - The converted path of OgMap points. */ std::vector<cv::Point> toPointPath(std::vector<TGlobalOrd> path); /*! @brief Converts a path of verticies to Global ords. * * @param path The path of verticies to convert. * @return vector<TGlobalOrd> - The converted path of Verticies. */ std::vector<TGlobalOrd> toOrdPath(std::vector<vertex> path); /*! @brief Returns a list of neighbours for the node. * * This function will return a list of neighbours around the * node in the PRM. This list is ordered by its distance to * the node (first element is closest). * * @param cspace The configuration space. * @param node The node to get neighbours for. * @param shouldConnect An extra qualifier for a neighbour. TRUE if you * want to actually connect to it. * @return vector<TGlobalOrd> - A list of neighbours */ std::vector<TGlobalOrd> getNeighbours(cv::Mat &cspace, vertex node, bool shouldConnect); /*! @brief Get the vertex corresponding to a global ordiante. * * If no vertex exists for this ordinate, then add it to the graph * and return the newly generated vertex. * * @param ordinate The ordiante to find or add. * @return vertex - The vertex representation of the ordinate. */ vertex findOrAdd(TGlobalOrd ordinate); /*! @brief Determines if an ordiante exists within the graph as a vertex. * * @param ord The ordiante to find or add. * @return TRUE - If the ordiante exists. */ bool existsAsVertex(TGlobalOrd ord); /*! @brief Finds the vertex corresponding to an ordiante. * * @param ord The ordiante to find. * @param v A reference to put the found vertex into. * @return TRUE - If the ordiante was found within the network_. */ bool lookup(TGlobalOrd ord, vertex &v); /*! @brief Returns the next unique vertex id within the graph. * * @return vertex The next unique vertex id. */ vertex nextVertexId(); /*! @brief Determines if an ordinate lies within the radius of any other nodes. * * @param ord The ordinate to check for. * @param r The radius qualifier. * @return TRUE - If the ordindate is violating the space of any other nodes. */ bool violatingSpace(TGlobalOrd ord, double r); /*! @brief Calculates the euclidean distance between two ordiantes. * * @param o1 The first ordinate. * @param o2 The second ordinate. * @return double - The distance between the two ordiantes. */ static double distance(TGlobalOrd o1, TGlobalOrd o2); /*! @brief Adds ordiante to the internal graph/network. * * @return ordinate The ordiante to add. * @return vertex - The ordinate's unique vertex id. */ vertex addOrdinate(TGlobalOrd ordinate); /*! @brief Prioritises all nodes in network based on their edge count. * * Nodes (or verticies) with the least amount of edge connections appear * early in the list. * * @return vector<vertex> - Prioritised list of nodes. */ std::vector<vertex> prioritiseNodes(); }; #endif // PRMPLANNER_H
39.940299
124
0.671618
[ "object", "vector" ]
296deb358ca789ef6865033450bfefaaf7e182b6
4,854
h
C
GameEngine/GameWindow.h
MCassimus/GameEngine
c24623bf921cf39957228c30a934ec9528b9bcdb
[ "MIT" ]
null
null
null
GameEngine/GameWindow.h
MCassimus/GameEngine
c24623bf921cf39957228c30a934ec9528b9bcdb
[ "MIT" ]
null
null
null
GameEngine/GameWindow.h
MCassimus/GameEngine
c24623bf921cf39957228c30a934ec9528b9bcdb
[ "MIT" ]
null
null
null
#pragma once #include <gl\glew.h> #include <GLFW\glfw3.h> #include <glm\glm.hpp> #include "Clock.h" class GameWindow { public: GameWindow(); ~GameWindow(); void setCursorLocked(bool); void setCursorVisible(bool); void clear(); void render(); bool isOpen(); void close(); static bool keyPressed(int);//returns true on frame of press static bool keyReleased(int);//returns true on frame of release static bool keyHeld(int);//returns true when key held more than one frame static glm::dvec2 mousePos; static glm::dvec2 mouseDelta; static Clock clock; #pragma region keyDef static const int keyUnknown = -1; static const int keySpace = 32; static const int keyApostrophe = 39; static const int keyComma = 44; static const int keyMinus = 45; static const int keyPeriod = 46; static const int keyForwardslash = 47; static const int key0 = 48; static const int key1 = 49; static const int key2 = 50; static const int key3 = 51; static const int key4 = 52; static const int key5 = 53; static const int key6 = 54; static const int key7 = 55; static const int key8 = 56; static const int key9 = 57; static const int keySemicolon = 59; static const int keyEquals = 61; static const int keyA = 65; static const int keyB = 66; static const int keyC = 67; static const int keyD = 68; static const int keyE = 69; static const int keyF = 70; static const int keyG = 71; static const int keyH = 72; static const int keyI = 73; static const int keyJ = 74; static const int keyK = 75; static const int keyL = 76; static const int keyM = 77; static const int keyN = 78; static const int keyO = 79; static const int keyP = 80; static const int keyQ = 81; static const int keyR = 82; static const int keyS = 83; static const int keyT = 84; static const int keyU = 85; static const int keyV = 86; static const int keyW = 87; static const int keyX = 88; static const int keyY = 89; static const int keyZ = 90; static const int keyLBracket = 91; static const int keyBackslash = 92; static const int keyRBracket = 93; static const int keyGrave = 96; static const int keyEscape = 256; static const int keyEnter = 257; static const int keyTab = 258; static const int keyBackspace = 259; static const int keyInsert = 260; static const int keyDelete = 261; static const int keyRightArrow = 262; static const int keyLeftArrow = 263; static const int keyDownArrow = 264; static const int keyUpArrow = 265; static const int keyPageUp = 266; static const int keyPageDown = 267; static const int keyHome = 268; static const int keyEnd = 269; static const int keyCapsLock = 280; static const int keyScrollLock = 281; static const int keyNumLock = 282; static const int keyPrintScreen = 283; static const int keyPause = 284; static const int keyF1 = 290; static const int keyF2 = 291; static const int keyF3 = 292; static const int keyF4 = 293; static const int keyF5 = 294; static const int keyF6 = 295; static const int keyF7 = 296; static const int keyF8 = 297; static const int keyF9 = 298; static const int keyF10 = 299; static const int keyF11 = 300; static const int keyF12 = 301; static const int keyF13 = 302; static const int keyF14 = 303; static const int keyF15 = 304; static const int keyF16 = 305; static const int keyF17 = 306; static const int keyF18 = 307; static const int keyF19 = 308; static const int keyF20 = 309; static const int keyF21 = 310; static const int keyF22 = 311; static const int keyF23 = 312; static const int keyF24 = 313; static const int keyF25 = 314; static const int keypad0 = 320; static const int keypad1 = 321; static const int keypad2 = 322; static const int keypad3 = 323; static const int keypad4 = 324; static const int keypad5 = 325; static const int keypad6 = 326; static const int keypad7 = 327; static const int keypad8 = 328; static const int keypad9 = 329; static const int keypadPeriod = 330; static const int keypadForwardslash = 331; static const int keypadAsterisk = 332; static const int keypadSubtract = 333; static const int keypadPlus = 334; static const int keypadEnter = 335; static const int keypadEquals = 336; static const int keyLShift = 340; static const int keyLControl = 341; static const int keyLAlt = 342; static const int keyLSystem = 343; static const int keyRShift = 344; static const int keyRControl = 345; static const int keyRAlt = 346; static const int keyRSystem = 347; static const int keyMenu = 348; static const int mouseLeft = 0; static const int mouseRight = 1; static const int mouseWheel = 2; static const int mouseButton4 = 3; static const int mouseButton5 = 4; static const int mouseButton6 = 5; static const int mouseButton7 = 6; static const int mouseButton8 = 7; #pragma endregion protected: static GLFWwindow * window; bool cursorLocked = false; };
30.528302
74
0.727647
[ "render" ]
296fca13df5d1752b629d7a84eb903025aa73e2c
1,831
h
C
cpp/wechat/patcher/process_patcher.h
wjiec/packages
4ccaf8f717265a1f8a9af533f9a998b935efb32a
[ "MIT" ]
null
null
null
cpp/wechat/patcher/process_patcher.h
wjiec/packages
4ccaf8f717265a1f8a9af533f9a998b935efb32a
[ "MIT" ]
1
2016-09-15T07:06:15.000Z
2016-09-15T07:06:15.000Z
cpp/wechat/patcher/process_patcher.h
wjiec/packages
4ccaf8f717265a1f8a9af533f9a998b935efb32a
[ "MIT" ]
null
null
null
#ifndef __THANOS_CORE_WECHAT_PATCHER_PROCESS_PATCHER_INCLUDED__ #define __THANOS_CORE_WECHAT_PATCHER_PROCESS_PATCHER_INCLUDED__ #include <windows.h> // SystemInformationClass typedef enum _SYSTEM_INFORMATION_CLASS { SYSTEM_HANDLE_INFORMATION = 16, } SystemInformationClass; // ZwQuerySystemInformation signature typedef ULONG (NTAPI *ZwQuerySystemInformationFunc)( IN SystemInformationClass systemInformationClass, OUT PVOID systemInformation, IN ULONG systemInformationLength, OUT PULONG returnLength OPTIONAL ); // SystemHandleTableEntryInfo typedef struct SystemHandleTableEntryInfo_t { USHORT uniqueProcessId; USHORT creatorBackTraceIndex; UCHAR objectTypeIndex; UCHAR handleAttributes; USHORT handleValue; PVOID object; ULONG grantedAccess; } SystemHandleTableEntryInfo; // SystemHandleInformation typedef struct SystemHandleInformation_t { ULONG numberOfHandles; SystemHandleTableEntryInfo handles[]; } SystemHandleInformation; // ObjectInformationClass typedef enum _OBJECT_INFORMATION_CLASS { OBJECT_NAME_INFORMATION = 1, OBJECT_TYPE_INFORMATION = 2, } ObjectInformationClass; // ObjectNameInformation typedef struct ObjectNameInformation_t { struct { USHORT length; USHORT maxLen; USHORT *buffer; } name; } ObjectNameInformation; // NtQueryObject signature typedef ULONG (NTAPI *NtQueryObjectFunc)( _In_opt_ HANDLE handle, _In_ ObjectInformationClass objectInformationClass, _Out_opt_ PVOID objectInformation, _In_ ULONG objectInformationLength, _Out_opt_ PULONG returnLength ); namespace Thanos { namespace Core { namespace WeChat { namespace Patcher { class ProcessPatcher { public: static bool patch(); }; } } } } #endif // __THANOS_CORE_WECHAT_PATCHER_PROCESS_PATCHER_INCLUDED__
23.177215
65
0.787548
[ "object" ]
2980adbcbd6d4dce2ef4a23c1a8fecb692834e43
3,587
h
C
src/Display.h
wormyrocks/Grafici-GFX
0f1defbc769f2bd5a1ff1fa5fcaa7e2ea8f19dba
[ "Apache-2.0" ]
3
2020-12-02T22:54:38.000Z
2021-06-14T03:57:01.000Z
src/Display.h
wormyrocks/Grafici-GFX
0f1defbc769f2bd5a1ff1fa5fcaa7e2ea8f19dba
[ "Apache-2.0" ]
18
2019-09-23T16:17:49.000Z
2021-01-26T07:06:11.000Z
src/Display.h
wormyrocks/Grafici-GFX
0f1defbc769f2bd5a1ff1fa5fcaa7e2ea8f19dba
[ "Apache-2.0" ]
3
2019-12-23T00:34:35.000Z
2021-11-30T16:24:02.000Z
#ifndef GRAFICI_DISPLAY_H #define GRAFICI_DISPLAY_H #include "Adafruit_GFX.h" #include "Types.h" #include "Utils.h" #include "Vector.h" class Display { public: void begin(Adafruit_GFX &driver) { _driver = &driver; } Adafruit_GFX &driver() { return *_driver; } void line(CartesianVector<DisplayNorm> begin, CartesianVector<DisplayNorm> end, ColorGFX color) const { auto pixel_begin = project(begin); auto pixel_end = project(end); _driver->drawLine(pixel_begin.x(), pixel_begin.y(), pixel_end.x(), pixel_end.y(), color); } void fillRect(CartesianVector<DisplayNorm> bl, CartesianVector<DisplayNorm> tr, ColorGFX color) const { CartesianVector<DisplayAbd> pixel_bl = project(bl); CartesianVector<DisplayAbd> pixel_tr = project(tr); CartesianVector<DisplayAbd> pixel_delta = pixel_tr - pixel_bl; /* Use min betwee bl and tr as Adafruit GFX does not handle when top is actually bottom and viceversa */ /* This can happen when we flip our boundary */ _driver->fillRect(graficiMin(pixel_bl.x(), pixel_tr.x()), graficiMin(pixel_bl.y(), pixel_tr.y()), abs(pixel_delta.x()), abs(pixel_delta.y()), color); } void fillRect(CartesianVector<DisplayNorm> bl, CartesianVector<DisplayNorm> br,CartesianVector<DisplayNorm> tl, CartesianVector<DisplayNorm> tr, ColorGFX color) const { //TODO if this is a simple rectangle call fillRect(bl,tr,color) CartesianVector<DisplayAbd> pixel_bl = project(bl); CartesianVector<DisplayAbd> pixel_br = project(br); CartesianVector<DisplayAbd> pixel_tl = project(tl); CartesianVector<DisplayAbd> pixel_tr = project(tr); /* Draw rect as two triangles to avoid transformations */ _driver->fillTriangle(pixel_bl.x(),pixel_bl.y(),pixel_br.x(),pixel_br.y(),pixel_tl.x(),pixel_tl.y(),color); _driver->fillTriangle(pixel_tl.x(),pixel_tl.y(),pixel_tr.x(),pixel_tr.y(),pixel_br.x(),pixel_br.y(),color); } void circle(CartesianVector<DisplayNorm> center, CartesianVector<DisplayNorm> radius, ColorGFX color) const { CartesianVector<DisplayAbd> circle_center = project(center); if ((radius.x() == 0) || (radius.y() == 0)) { _driver->drawPixel(circle_center.x(), circle_center.y(), color); } else { CartesianVector<DisplayAbd> circle_radius = project(radius); _driver->drawCircle(circle_center.x(), circle_center.y(), graficiMin(circle_radius.x(), circle_radius.y()), color); } } /* TODO provide a deformable circle given a 4-point rectangle */ void fillCircle(CartesianVector<DisplayNorm> center, CartesianVector<DisplayNorm> radius, ColorGFX color) const { CartesianVector<DisplayAbd> circle_center = project(center); if ((radius.x() == 0) || (radius.y() == 0)) { _driver->drawPixel(circle_center.x(), circle_center.y(), color); } else { CartesianVector<DisplayAbd> circle_radius = project(radius); _driver->fillCircle(circle_center.x(), circle_center.y(), graficiMin(circle_radius.x(), circle_radius.y()), color); } } void point(CartesianVector<DisplayNorm> center, ColorGFX color) const { circle(center, { 0, 0 }, color); } /* from normalized display vector to absolute pixel vector */ CartesianVector<DisplayAbd> project(CartesianVector<DisplayNorm> vector) const { return CartesianVector<DisplayAbd>{ static_cast<DisplayAbd>(vector.x() * (_driver->width() - 1)), static_cast<DisplayAbd>((1 - vector.y()) * (_driver->height() - 1)) }; }; private: Adafruit_GFX *_driver; }; #endif /* GRAFICI_DISPLAY_H */
35.87
168
0.700585
[ "vector" ]
29892c092ea1bfcd788f4d773529668e831344fd
7,759
h
C
utf8.h
Llewellynvdm/id3
b6413124856b1eb170f81b2f66cecf1f13235673
[ "BSD-2-Clause" ]
108
2015-01-16T16:05:07.000Z
2022-03-31T12:13:51.000Z
utf8.h
Llewellynvdm/id3
b6413124856b1eb170f81b2f66cecf1f13235673
[ "BSD-2-Clause" ]
26
2015-05-27T00:00:51.000Z
2022-02-20T15:03:44.000Z
utf8.h
Llewellynvdm/id3
b6413124856b1eb170f81b2f66cecf1f13235673
[ "BSD-2-Clause" ]
11
2016-07-18T22:15:22.000Z
2022-03-13T00:45:31.000Z
/* UTF-8 (unicode transformation format) encoding/decoding layer copyright (c) 2003, 2004, 2005 squell <squell@alumina.nl> use, modification, copying and distribution of this software is permitted under the conditions described in the file 'COPYING'. Usage: The namespace 'utf8' defines a couple of things. utf8::length(ptr) - returns the code-points of a null-terminated utf8 string utf8::length(begin, end) - returns the number of code points in [begin, end) utf8::encode(begin, end, result) - encodes the code points in [begin, end) to UTF8, storing in result utf8::decode(begin, end, result) - decodes the code units in [begin, end) to UCS4, storing in result 'ptr', 'begin' and 'end' should be Input Iterators, 'output' should be an Output Iterator. UTF8 decoding is safe with respect to overlong sequences, surrogate pairs, and so on, and passes Markus Kuhn's UTF8 stress test: http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt Types for rolling your own; utf8::mbbuf - a buffer that is large enough to hold a single multibyte character utf8::encoder<OutputIterator> utf8::decoder<OutputIterator[, ErrorFunction]> - encoding and decoding. see class definitions below. decoder takes an optional second template argument, which is a function pointer or function object type called for illegal input sequences, as if matching this signature: template<class utfIter> wchar error(utfIter p, wchar ucs) the first argument points past the offending multibyte sequence, and ucs is a suggested resolution: wchar(-1) for stray bytes, or the decoded value for overlong or otherwise invalid sequences. The default error handler is inline and returns U+FFFD - REPLACEMENT CHARACTER for all arguments. Example: int utf8_wctomb(char* s, wchar_t wc) { if(!s) return 0; utf8::encoder<char*> enc(s); enc.put(wc); return enc.base() - s; } */ #ifndef __ZF_UTF8_HPP #define __ZF_UTF8_HPP #if __STDC_VERSION__ >= 199901L || __cplusplus >= 201103L # include <stdint.h> #endif namespace utf8 { // some definitions #if __STDC_VERSION__ >= 199901L typedef uint_fast32_t wchar; // ucs-4 symbol holder #else typedef unsigned long wchar; // ucs-4 symbol holder #endif typedef char mbbuf[6]; // maximum symbol length // common internal definitions // - made a template class to the static table can be defined in the header template<class T = void> class base { public: template<class utfIter> struct error { inline wchar operator()(utfIter, wchar) { return 0xFFFDu; } }; protected: base() { (T)void("ensure T == void"); } static inline wchar max(unsigned n); static unsigned char dectab[]; }; template<class utfIter> // invalid code handler (func) inline wchar default_error(utfIter p, wchar ucs) { return base<>::error<utfIter>()(p, ucs); } // encoding and decoding primitive classes template<class utfIter, class Error = base<>::error<utfIter> > class decoder : base<> { utfIter p, end; Error errf; public: decoder(utfIter begin, utfIter end = utfIter(), Error e = Error()) : p(begin), end(end), errf(e) { } utfIter& base() { return p; } inline bool i_get(wchar&); bool get(wchar&); }; template<class utfIter> class encoder : base<> { utfIter p; public: encoder(utfIter out) : p(out) { } utfIter& base() { return p; } inline void i_put(wchar); void put(wchar); }; // primitive functions template<class utfIter> unsigned long length(utfIter begin, utfIter end); template<class utfIter> unsigned long length(utfIter begin); template<class utfIter, class charIter> charIter decode(utfIter begin, utfIter end, charIter out); template<class utfIter, class charIter> utfIter encode(charIter begin, charIter end, utfIter out); // encode & decode definitions template<class T> inline wchar base<T>::max(unsigned n) /* max. code of seq. n */ { return 1ul << (n*5+1); /* 2 ** [ 6(n-1) + 7-n ] */ } template<class T> unsigned char base<T>::dectab[64] = { /* symbol length table */ 2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3, 3,3,3,3,3,3,3,3, 4,4,4,4,4,4,4,4, 5,5,5,5,6,6,0,0, }; template<class utfIter, class Error> inline bool decoder<utfIter,Error>::i_get(wchar& out) { wchar ucs; /* uni. code symbol */ wchar lng; /* overlong mark */ int seq; unsigned char c; if(p != end) /* seq == 0 loop */ switch((c=*p++) & 0xC0) { default: /* 0x00 .. 0x7F */ return out=c, 1; case 0xC0: /* start of sequence */ if((seq=dectab[c & 0x3F])) { ucs = c & ((1<<(8-seq))-1); /* mask off good bits */ lng = max(--seq); /* determine minimum */ lng <<= seq==1; /* fix 2 byte minimum */ goto seqloop; } case 0x80: /* stray byte */ return out=errf(p, -1), 1; } return 0; seqloop: while(p != end && (c=*p^0x80) <= 0x3F) { ++p; ucs = ucs << 6 | c; if(--seq) continue; if((ucs&~1ul ) == 0xFFFE || /* illegal unicode? */ (ucs&~0x7FFul) == 0xD800 || /* utf-16 surrogate? */ (ucs < lng ) ) /* was overlong? */ return out=errf(p, ucs), 1; else return out=ucs, 1; } return out=errf(p, -1), 1; } template<class utfIter> inline void encoder<utfIter>::i_put(wchar ucs) { if(ucs < 0x80) *p++ = ucs; else { /* determine bytes */ unsigned char c; int n; ucs &= (1ul << 31) - 1; for(n=2; max(n) <= ucs; ) ++n; /* could be faster? */ for(c = 0xFF^(0xFF >> n); n--; c = 0x80) *p++ = c | ((ucs >> n*6) & 0x3F); } } // non-inline versions. template<class utfIter, class Error> bool decoder<utfIter,Error>::get(wchar& ucs) { return i_get(ucs); } template<class utfIter> void encoder<utfIter>::put(wchar ucs) { i_put(ucs); } // sequence routines template<class utfIter> unsigned long length(utfIter begin, utfIter end) { decoder<utfIter> utf(begin, end); unsigned long cnt = 0; for(wchar wc; utf.i_get(wc); ) ++cnt; return cnt; } template<class utfIter> unsigned long length(utfIter begin) { decoder<utfIter> utf(begin); unsigned long cnt = 0; for(wchar wc; utf.i_get(wc), wc; ) ++cnt; return cnt; } template<class utfIter, class charIter> charIter decode(utfIter begin, utfIter end, charIter out) { decoder<utfIter> utf(begin, end); wchar wc; while( utf.i_get(wc) ) *out++ = wc; return out; } template<class utfIter, class charIter> utfIter encode(charIter begin, charIter end, utfIter out) { encoder<utfIter> utf(out); while(begin != end) utf.i_put(*begin++); return utf.base(); } } #endif /* UTF-8, terse Any byte with bit7 clear is that byte. Any byte with bit7 belongs to a sequence of bytes. All but the first have bit6 clear, the remaining 6bits carrying data. The starting byte consists of a number of bits (counted from msb side), which indicate the number of bytes in this sequence (at least two), followed by a zero bit, followed by a few bits of data. */
26.301695
76
0.596469
[ "object" ]