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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
815842ae505e871705972ae7974894b29fda0eaa | 4,166 | h | C | Eagle/src/Eagle/UI/UI.h | IceLuna/Eagle | 3b0d5f014697c97138f160ddd535b1afd6d0c141 | [
"Apache-2.0"
] | 1 | 2021-12-10T19:15:25.000Z | 2021-12-10T19:15:25.000Z | Eagle/src/Eagle/UI/UI.h | IceLuna/Eagle | 3b0d5f014697c97138f160ddd535b1afd6d0c141 | [
"Apache-2.0"
] | 41 | 2021-08-18T21:32:14.000Z | 2022-02-20T11:44:06.000Z | Eagle/src/Eagle/UI/UI.h | IceLuna/Eagle | 3b0d5f014697c97138f160ddd535b1afd6d0c141 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "Eagle/Renderer/Texture.h"
#include "imgui.h"
namespace Eagle
{
class StaticMesh;
}
namespace Eagle::UI
{
enum ButtonType : int
{
None = 0,
OK = 0b00000001,
Cancel = 0b00000010,
OKCancel = 0b00000011,
Yes = 0b00000100,
No = 0b00001000,
YesNo = 0b00001100,
YesNoCancel = 0b00001110
};
bool DrawTextureSelection(const std::string& label, Ref<Texture>& modifyingTexture, bool bLoadAsSRGB);
bool DrawStaticMeshSelection(const std::string& label, Ref<StaticMesh>& staticMesh, const std::string& helpMessage = "");
bool DrawSoundSelection(const std::string& label, std::filesystem::path& selectedSoundPath);
bool DrawVec3Control(const std::string& label, glm::vec3& values, const glm::vec3 resetValues = glm::vec3{ 0.f }, float columnWidth = 100.f);
//Grid Name needs to be unique
void BeginPropertyGrid(const std::string& gridName);
void EndPropertyGrid();
bool Property(const std::string& label, std::string& value, const std::string& helpMessage = "");
bool Property(const std::string& label, bool& value, const std::string& helpMessage = "");
bool Property(const std::string& label, const std::vector<std::string>& customLabels, bool* values, const std::string& helpMessage = "");
bool PropertyText(const std::string& label, const std::string& text);
bool PropertyDrag(const std::string& label, int& value, float speed = 1.f, int min = 0, int max = 0, const std::string& helpMessage = "");
bool PropertyDrag(const std::string& label, float& value, float speed = 1.f, float min = 0.f, float max = 0.f, const std::string& helpMessage = "");
bool PropertyDrag(const std::string& label, glm::vec2& value, float speed = 1.f, float min = 0.f, float max = 0.f, const std::string& helpMessage = "");
bool PropertyDrag(const std::string& label, glm::vec3& value, float speed = 1.f, float min = 0.f, float max = 0.f, const std::string& helpMessage = "");
bool PropertyDrag(const std::string& label, glm::vec4& value, float speed = 1.f, float min = 0.f, float max = 0.f, const std::string& helpMessage = "");
bool PropertySlider(const std::string& label, int& value, int min, int max, const std::string& helpMessage = "");
bool PropertySlider(const std::string& label, float& value, float min, float max, const std::string& helpMessage = "");
bool PropertySlider(const std::string& label, glm::vec2& value, float min, float max, const std::string& helpMessage = "");
bool PropertySlider(const std::string& label, glm::vec3& value, float min, float max, const std::string& helpMessage = "");
bool PropertySlider(const std::string& label, glm::vec4& value, float min, float max, const std::string& helpMessage = "");
bool PropertyColor(const std::string& label, glm::vec3& value, const std::string& helpMessage = "");
bool PropertyColor(const std::string& label, glm::vec4& value, const std::string& helpMessage = "");
bool InputFloat(const std::string& label, float& value, float step = 0.f, float stepFast = 0.f, const std::string& helpMessage = "");
//Returns true if selection changed.
//outSelectedIndex - index of the selected option
bool Combo(const std::string& label, uint32_t currentSelection, const std::vector<std::string>& options, int& outSelectedIndex, const std::vector<std::string>& tooltips = {}, const std::string& helpMessage = "");
bool Button(const std::string& label, const std::string& buttonText, const ImVec2& size = ImVec2(0, 0));
void Tooltip(const std::string& tooltip, float treshHold = EG_HOVER_THRESHOLD);
void PushItemDisabled();
void PopItemDisabled();
void PushFrameBGColor(const glm::vec4& color);
void PopFrameBGColor();
void HelpMarker(const std::string& text);
ButtonType ShowMessage(const std::string& title, const std::string& message, ButtonType buttons);
ButtonType InputPopup(const std::string& title, const std::string& hint, std::string& input);
}
namespace Eagle::UI::TextureViewer
{
// outWindowOpened - In case X button will be clicked, this flag will be set to false.
// outWindowOpened - if nullptr set, windows will not have X button
void OpenTextureViewer(const Ref<Texture>& textureToView, bool* outWindowOpened = nullptr);
}
| 50.804878 | 213 | 0.721555 | [
"vector"
] |
8168ae110c6bec4d7680b21525afbbeaee5617e3 | 1,819 | h | C | Dependencies/include/HFL/vector.h | salmoncatt/HGE | 8ae471de46589df54cacd1bd0261989633f1e5ef | [
"BSD-3-Clause"
] | 2 | 2020-11-12T14:42:56.000Z | 2021-01-27T18:04:42.000Z | Dependencies/include/HFL/vector.h | salmoncatt/Hydrogen-Game-Engine | 8ae471de46589df54cacd1bd0261989633f1e5ef | [
"BSD-3-Clause"
] | 1 | 2021-01-27T17:39:21.000Z | 2021-01-28T01:42:36.000Z | Dependencies/include/HFL/vector.h | salmoncatt/Hydrogen-Game-Engine | 8ae471de46589df54cacd1bd0261989633f1e5ef | [
"BSD-3-Clause"
] | null | null | null |
#ifndef HFL_VECTOR_HEADER_INCLUDE
#define HFL_VECTOR_HEADER_INCLUDE
namespace HGE {
template <typename T> class vector {
private:
T* data;
size_t capacity;
size_t currentSize;
void __cleanup__() {
if (data != nullptr)
delete[] data;
capacity = 0;
currentSize = 0;
}
public:
vector() {
data = new T[1];
capacity = 1;
currentSize = 0;
}
vector(const vector& source) {
data = new T[source.capacity];
capacity = source.capacity;
currentSize = source.currentSize;
//copy over data
for (size_t i = 0; i < capacity; ++i) {
data[i] = source.data[i];
}
}
vector& operator=(const vector& source) {
__cleanup__();
data = new T[source.capacity];
capacity = source.capacity;
currentSize = source.currentSize;
//copy over data
for (size_t i = 0; i < capacity; ++i) {
data[i] = source.data[i];
}
return *this;
}
void reserve(const size_t& size) {
if (size > capacity) {
//create temp array with new size
T* temp = new T[size];
//copy over data
for (size_t i = 0; i < capacity; ++i) {
temp[i] = data[i];
}
//delete current data
delete[] data;
//set the data with the new memory adress
data = temp;
capacity = size;
}
}
void resize(const size_t& size) {
if (size > capacity)
reserve(size);
if (size > currentSize) {
for (size_t i = currentSize; i < size; ++i) {
data[i] = T();
}
}
currentSize = size;
}
void push_back(const T& value) {
if (currentSize + 1 > capacity)
reserve(capacity * 2);
data[currentSize] = value;
currentSize += 1;
}
T& operator[](const size_t& index) {
return data[index];
}
size_t size() {
return currentSize;
}
~vector() {
__cleanup__();
}
};
}
#endif
| 15.547009 | 49 | 0.583837 | [
"vector"
] |
816d6d3701ec2decb5c0a80430a246b8ca8dc636 | 10,618 | c | C | src/graphics/text.c | Df458/dfgame | 3e0312d6d027ff617c1be7c0d72309fcdfc461e2 | [
"Zlib"
] | 4 | 2017-06-26T16:52:34.000Z | 2021-11-14T20:37:19.000Z | src/graphics/text.c | Df458/dfgame | 3e0312d6d027ff617c1be7c0d72309fcdfc461e2 | [
"Zlib"
] | null | null | null | src/graphics/text.c | Df458/dfgame | 3e0312d6d027ff617c1be7c0d72309fcdfc461e2 | [
"Zlib"
] | null | null | null | // Log category, used to filter logs
#define LOG_CATEGORY "Graphics"
#include "graphics/text.h"
#include "core/check.h"
#include "core/container/array.h"
#include "core/log/log.h"
#include "core/memory/alloc.h"
#include "core/stringutil.h"
#include "math/matrix.h"
#include "graphics/font.h"
#include "graphics/mesh.h"
#include "graphics/texture_atlas.h"
#include "graphics/vertex.hd"
/** @brief Represents a piece of text to be rendered
*
* @see text.h
* @see text_new()
*/
typedef struct text {
font fnt;
char* str;
mesh msh;
alignment_2d align;
text_wrap wrap;
float max_width;
vec2 bounding_size;
}* text;
typedef struct text_line_data {
aabb_2d box;
uint16 start;
uint16 end;
} text_line_data;
glyph* glyph_to_verts(text t, vt_pt* buffer, int index, vec2 offset, float line_height) {
float atlas_size = font_get_texture(t->fnt).width;
glyph* gp = font_get_glyph(t->fnt, (uint16)t->str[index]);
if(gp && gp->advance != 0) {
aabb_2d box = font_get_glyph_bounds(t->fnt, gp->texture_index);
// Top-left
buffer[0].position.xy = vec2_add(offset, (vec2){.x = gp->bearing.x, .y = line_height-gp->bearing.y});
buffer[0].position.z = 0;
buffer[0].uv = vec2_mul((vec2){.x = box.position.x, .y = (box.position.y + box.dimensions.y)}, 1 / atlas_size);
// Bottom-left
buffer[1].position.xy = vec2_add(offset, (vec2){.x = gp->bearing.x, .y = line_height + box.dimensions.y - gp->bearing.y});
buffer[1].position.z = 0;
buffer[1].uv = vec2_mul((vec2){.x = box.position.x, .y = box.position.y}, 1 / atlas_size);
// Bottom-right
buffer[2].position.xy = vec2_add(offset, (vec2){.x = box.dimensions.x + gp->bearing.x, .y = line_height + box.dimensions.y - gp->bearing.y});
buffer[2].position.z = 0;
buffer[2].uv = vec2_mul((vec2){.x = (box.position.x + box.dimensions.x), .y = box.position.y}, 1 / atlas_size);
// Top-left
buffer[3].position.xy = vec2_add(offset, (vec2){.x = gp->bearing.x, .y = line_height-gp->bearing.y});
buffer[3].position.z = 0;
buffer[3].uv = vec2_mul((vec2){.x = box.position.x, .y = (box.position.y + box.dimensions.y)}, 1 / atlas_size);
// Bottom-right
buffer[4].position.xy = vec2_add(offset, (vec2){.x = box.dimensions.x + gp->bearing.x, .y = line_height+box.dimensions.y - gp->bearing.y});
buffer[4].position.z = 0;
buffer[4].uv = vec2_mul((vec2){.x = (box.position.x + box.dimensions.x), .y = box.position.y}, 1 / atlas_size);
// Top-right
buffer[5].position.xy = vec2_add(offset, (vec2){.x = box.dimensions.x + gp->bearing.x, .y = line_height-gp->bearing.y});
buffer[5].position.z = 0;
buffer[5].uv = vec2_mul((vec2){.x = (box.position.x + box.dimensions.x), .y = (box.position.y + box.dimensions.y)}, 1 / atlas_size);
return gp;
}
return NULL;
}
void iter_arrange_lines(text_line_data* line, text t) {
vt_pt* verts = mesh_get_data(t->msh);
vec3 offset_value = vec3_zero;
aabb_2d box = {
.position = vec2_zero,
.dimensions = { .x = line->box.dimensions.x, .y = t->bounding_size.y }
};
offset_value.xy = vec2_mul(aabb_get_origin_2d(box, t->align), -1);
for(int i = line->start * 6; i < line->end * 6; ++i) {
verts[i].position = vec_add(verts[i].position, offset_value);
}
mesh_update(t->msh);
}
text_line_data update_add_line(text t, array lines, text_line_data old, uint16 cursor, vec2* offset) {
float height = font_get_height(t->fnt);
offset->x = 0;
offset->y += height;
old.end = cursor;
array_add(lines, old);
if(old.box.dimensions.x > t->bounding_size.x) {
t->bounding_size.x = old.box.dimensions.x;
}
text_line_data new_line = (text_line_data){ .box=aabb_2d_zero, .start=0, .end=0 };
new_line.box.position.y = offset->y;
new_line.start = cursor + 1;
t->bounding_size.y += height;
return new_line;
}
void text_update_mesh(text t) {
uint16 len = strlen(t->str);
if(!len)
return;
vt_pt* buf = mscalloc(len * 6, vt_pt);
array line_data = array_mnew_ordered(text_line_data, 4);
float height = font_get_height(t->fnt);
t->bounding_size.x = 0;
t->bounding_size.y = height;
vec2 offset = vec2_zero;
text_line_data current_data = (text_line_data){ .box=aabb_2d_zero, .start=0, .end=0 };
bool line_has_space = false;
uint16 i = 0;
for(; i < len; ++i) {
float width = 0;
float advance = 0;
// Calculate width/advance for the new character
if(t->str[i] == ' ' || t->str[i] == '\t') { // Spaces
if(eq0(current_data.box.dimensions.x))
continue;
line_has_space = true;
advance = height * (t->str[i] == ' ' ? 0.5f : 2.0f);
} else if(t->str[i] == '\n') { // Newline
current_data = update_add_line(t, line_data, current_data, i, &offset);
line_has_space = false;
continue;
} else { // Regular text
glyph* gp = glyph_to_verts(t, &buf[i * 6], i, offset, height);
if(gp) {
width = font_get_glyph_bounds(t->fnt, gp->texture_index).dimensions.x;
advance = gp->advance;
}
}
// Wrapping
if(!eq0(t->max_width) && !eq0(current_data.box.dimensions.x) && current_data.box.dimensions.x + width > t->max_width && (line_has_space || t->wrap != TEXT_WRAP_WORD)) {
current_data = update_add_line(t, line_data, current_data, i, &offset);
line_has_space = false;
if(!eq0(width)) {
if(t->wrap == TEXT_WRAP_CHARACTER) {
current_data.start--;
// Shift last character
glyph_to_verts(t, &buf[i * 6], i, offset, height);
offset.x += advance;
current_data.box.dimensions.x = offset.x;
} else {
// Find the satrt of the last word so that we can work from there
int j = i;
for(; j >= 0 && t->str[j] != ' ' && t->str[j] != '\n' && t->str[j] != '\t'; --j);
text_line_data* prev_data = array_get(line_data, array_get_length(line_data) - 1);
prev_data->end -= i - j;
current_data.start -= i - j;
// Shift last word
for(j++; j <= i; j++) {
glyph* gp = glyph_to_verts(t, &buf[j * 6], j, offset, height);
if(gp) {
offset.x += gp->advance;
current_data.box.dimensions.x = offset.x;
}
}
prev_data->box.dimensions.x -= offset.x;
}
}
} else {
offset.x += advance;
current_data.box.dimensions.x = offset.x;
}
t->bounding_size.x = max(t->bounding_size.x, current_data.box.dimensions.x);
}
current_data.end = i;
if(current_data.start < current_data.end)
array_add(line_data, current_data);
mesh_free(t->msh);
t->msh = mesh_new(len * 6, buf, NULL);
sfree(buf);
array_foreach(line_data, i) {
iter_arrange_lines(i.data, t);
}
array_free(line_data);
}
void text_set_str_va(text t, const char* s, va_list args) {
if(t->str)
sfree(t->str);
char* new_str = vsaprintf(s, args);
if(!new_str)
return;
t->str = new_str;
text_update_mesh(t);
}
// ---------------------------------------------------------------------------------
text text_new(font f, const char* s, ...) {
text t = mscalloc(1, struct text);
t->fnt = f;
t->msh = NULL;
t->str = NULL;
t->align = ALIGN_DEFAULT;
t->wrap = TEXT_WRAP_DEFAULT;
t->max_width = 0;
t->bounding_size = vec2_zero;
va_list args;
va_start(args, s);
text_set_str_va(t, s, args);
va_end(args);
return t;
}
void _text_free(text t, bool free_src) {
check_return(t, "Text is NULL", );
sfree(t->str)
if(t->msh)
mesh_free(t->msh);
if(free_src)
font_free(t->fnt);
sfree(t);
}
void text_set_str(text t, const char* s, ...) {
check_return(t, "Text is NULL", );
va_list args;
va_start(args, s);
text_set_str_va(t, s, args);
va_end(args);
}
char* text_get_str(const text t) {
check_return(t, "Text is NULL", NULL);
return nstrdup(t->str);
}
mesh text_get_mesh(const text t) {
check_return(t, "Text is NULL", NULL);
return t->msh;
}
void text_set_align(text t, alignment_2d align) {
check_return(t, "Text is NULL", );
check_return(align <= ALIGN_LAST, "Invalid text alignment 0x%x", , align);
t->align = align;
text_update_mesh(t);
}
alignment_2d text_get_align(const text t) {
check_return(t, "Text is NULL", ALIGN_DEFAULT);
return t->align;
}
void text_set_wrap(text t, text_wrap wrap) {
check_return(t, "Text is NULL", );
check_return(wrap <= TEXT_WRAP_LAST, "Invalid text wrap 0x%x", , wrap);
t->wrap = wrap;
text_update_mesh(t);
}
text_wrap text_get_wrap(const text t) {
check_return(t, "Text is NULL", TEXT_WRAP_DEFAULT);
return t->wrap;
}
vec2 text_get_bounds(const text t) {
check_return(t, "Text is NULL", vec2_zero);
return t->bounding_size;
}
void text_set_max_width(text t, float width) {
check_return(t, "Text is NULL", );
t->max_width = width;
text_update_mesh(t);
}
float text_get_max_width(const text t) {
check_return(t, "Text is NULL", 0);
return t->max_width;
}
font text_get_font(const text t) {
check_return(t, "Text is NULL", NULL);
return t->fnt;
}
void text_set_font(text t, font f) {
check_return(t, "Text is NULL", );
check_return(f, "Font is NULL", );
t->fnt = f;
text_update_mesh(t);
}
void text_draw(const text t, shader s, mat4 m) {
check_return(t, "Text is NULL", );
check_return(t->fnt, "Text has no font", );
if(t->msh) {
glUseProgram(s.id);
shader_bind_uniform_name(s, "u_transform", m);
shader_bind_uniform_texture_name(s, "u_texture", font_get_texture(t->fnt), GL_TEXTURE0);
vec2 v0 = (vec2){.x=0,.y=0};
vec2 v1 = (vec2){.x=1,.y=1};
shader_bind_uniform_name(s, "uv_offset", v0);
shader_bind_uniform_name(s, "uv_scale", v1);
mesh_render(s, t->msh, GL_TRIANGLES, "i_pos", VT_POSITION, "i_uv", VT_TEXTURE);
}
}
| 30.07932 | 176 | 0.576474 | [
"mesh"
] |
817d3d54be46a0b2ec534165802b4415819f7927 | 78,668 | h | C | src/globals.h | q4a/TheXTech | 574a4ad6723cce804732337073db9d093cb700b1 | [
"MIT"
] | null | null | null | src/globals.h | q4a/TheXTech | 574a4ad6723cce804732337073db9d093cb700b1 | [
"MIT"
] | null | null | null | src/globals.h | q4a/TheXTech | 574a4ad6723cce804732337073db9d093cb700b1 | [
"MIT"
] | null | null | null | /*
* TheXTech - A platform game engine ported from old source code for VB6
*
* Copyright (c) 2009-2011 Andrew Spinks, original VB6 code
* Copyright (c) 2020-2021 Vitaly Novichkov <admin@wohlnet.ru>
*
* 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 GLOBALS_H
#define GLOBALS_H
#include <SDL2/SDL_scancode.h>
#include <string>
#include <vector>
#include <cstdlib>
#include "frm_main.h"
#include "std_picture.h"
#include "gfx.h"
#include "location.h"
#include "range_arr.hpp"
#include "rand.h"
#include "floats.h"
#include "control/con_control.h"
#include "global_constants.h"
#include "controls.h"
//Option Explicit
//Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
//Public Declare Function BitBlt Lib "gdi32" (ByVal hDestDC As Long, ByVal X As Long, ByVal Y As Long, ByVal nWidth As Long, ByVal nHeight As Long, ByVal hSrcDC As Long, ByVal xSrc As Long, ByVal ySrc As Long, ByVal dwRop As Long) As Long
//Public Declare Function StretchBlt Lib "gdi32" (ByVal hdc As Long, ByVal X As Long, ByVal Y As Long, ByVal nWidth As Long, ByVal nHeight As Long, ByVal hSrcDC As Long, ByVal xSrc As Long, ByVal ySrc As Long, ByVal nSrcWidth As Long, ByVal nSrcHeight As Long, ByVal dwRop As Long) As Long
//Public Declare Function CreateCompatibleBitmap Lib "gdi32" (ByVal hdc As Long, ByVal nWidth As Long, ByVal nHeight As Long) As Long
//Public Declare Function CreateCompatibleDC Lib "gdi32" (ByVal hdc As Long) As Long
//Public Declare Function GetDC Lib "user32" (ByVal hWnd As Long) As Long
//Public Declare Function SelectObject Lib "gdi32" (ByVal hdc As Long, ByVal hObject As Long) As Long
//Public Declare Function DeleteObject Lib "gdi32" (ByVal hObject As Long) As Long
//Public Declare Function DeleteDC Lib "gdi32" (ByVal hdc As Long) As Long
//Public Declare Function GetKeyState Lib "user32" (ByVal nVirtKey As Long) As Integer
//'Public Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA" (ByVal lpstrCommand As String, ByVal lpstrReturnString As String, ByVal uReturnLength As Integer, ByVal hwndCallback As Integer) As Integer
//Public Declare Function SetCursorPos Lib "user32" (ByVal X As Long, ByVal Y As Long) As Long
//Public Declare Function SetWindowPos Lib "user32" (ByVal hWnd As Long, ByVal hWndInsertAfter As Long, ByVal X As Long, ByVal Y As Long, ByVal cx As Long, ByVal cy As Long, ByVal wFlags As Long) As Long
//Private Declare Function GetSystemDirectory Lib "kernel32" Alias "GetSystemDirectoryA" (ByVal lpBuffer As String, ByVal nSize As Long) As Long
//Public Declare Function GetDesktopWindow Lib "user32.dll" () As Long
//Public Declare Function GetWindowDC Lib "user32.dll" (ByVal hWnd As Long) As Long
//Declare Function GetActiveWindow Lib "user32" () As Integer
//Public Declare Function GetTickCount& Lib "kernel32" ()
//Public OnlineDisc As Boolean
#define UNUSED(x) (void)x
#define IF_OUTRANGE(x, l, r) ((x) < (l) || (x) > (r))
#define IF_INRANGE(x, l, r) ((x) >= (l) && (x) <= (r))
//! Main window
extern FrmMain frmMain;
//! Container of "hardcoded" (no more) graphics
extern GFX_t GFX;
//! Showing that game is works. It gets false when closing a window or exiting a game by menu. To mean that application must be closed.
extern bool GameIsActive;
//! Path to game resources assets (by default it's ~/.PGE_Project/thextech/)
extern std::string AppPath;
/**
* @brief Process internal events (mouse, keyboard, joysticks, window's update, OS communications, etc.)
*/
extern void DoEvents();
/**
* \brief Toggle whether or not the cursor is shown.
*
* \param toggle 1 to show the cursor, 0 to hide it, -1 to query the current
* state.
*
* \return 1 if the cursor is shown, or 0 if the cursor is hidden.
*/
extern int showCursor(int show);
extern Uint8 getKeyState(SDL_Scancode key);
extern Uint8 getKeyStateI(int key);
//Public Const KEY_PRESSED As Integer = &H1000 'For control information
const int KEY_PRESSED = 1;
/**
* @brief Get name of key from a keycode
* @param key Key code
* @return Human-readable key name
*/
const char *getKeyName(int key);
struct KM_Key;
std::string getJoyKeyName(bool isController, const KM_Key &key);
/**
* @brief Rounding function that works same as in VB6
* @param x Floating point value to round
* @return rounded result
*/
extern int vb6Round(double x);
/**
* @brief Rounding function that works same as in VB6
* @param x Floating point value to round
* @param decimals Round to a specific number of decimals
* @return rounded result
*/
extern double vb6Round(double x, int decimals);
//'Saved Events
//Public numSavedEvents As Integer
extern int numSavedEvents;
//Public SavedEvents(1 To MaxSavedEvents) As String
extern RangeArr<std::string, 1, MaxSavedEvents> SavedEvents;
//Public BlockSwitch(1 To 4) As Boolean
extern RangeArrI<bool, 1, 4, false> BlockSwitch;
//'Public PowerUpUnlock(2 To 7) As Boolean
extern RangeArrI<bool, 2, 7, false> PowerUpUnlock;
//Public Const SWP_SHOWWINDOW = &H40
//const int SWP_SHOWWINDOW = 0x40;
//Public Const SWP_NOMOVE As Long = 2
//const long SWP_NOMOVE = 2;
//Public Const SWP_NOSIZE As Long = 1
//const long SWP_NOSIZE = 1;
//Public Const FLAGS = SWP_NOMOVE Or SWP_NOSIZE
//const long FLAGS = SWP_NOMOVE | SWP_NOSIZE;
//Public Const HWND_TOPMOST As Long = -1
//const long HWND_TOPMOST = -1;
//Public Const HWND_NOTOPMOST As Long = -2
//const long HWND_NOTOPMOST = -2;
//Public myBackBuffer As Long 'Backbuffer
extern long myBackBuffer;
//Public myBufferBMP As Long 'Backbuffer
extern long myBufferBMP;
//Public AllCharBlock As Integer
extern int AllCharBlock;
//Public Const KEY_TOGGLED As Integer = &H1 'For control information
//const int KEY_TOGGLED = 0x01;
//Public LocalNick As String 'Online Nickname
//Public LocalCursor As Integer 'Online Cursor color
//Public ClientPassword As String 'Password client is connecting with
//Public ServerPassword As String 'Password game server wants the client to use
//Public ServerClear As Boolean
//Public StartMenu As Boolean
extern bool StartMenu;
//Public BlockFlash As Integer
extern int BlockFlash;
//Public ScrollRelease As Boolean
extern bool ScrollRelease;
//Public TakeScreen As Boolean
extern bool TakeScreen;
//Public LB As String ' Line Break
extern std::string LB;
//Public EoT As String ' End of Transmission for WINSOCK
extern std::string EoT;
//Public Type Controls 'Controls for the player
//moved into "controls.h"
//Public Type nPlayer 'online player type
// Controls As Controls 'online players controls
// Cursor As Integer
// IsMe As Boolean 'True if this player is the local player
// Nick As String
// Active As Boolean 'True if a player is using this variable
// ECurserX As Double 'Cursor X position
// ECurserY As Double 'Cursor Y position
//End Type
//Public Type nPlay 'Netplay data type
// Allow As Boolean
// Mode As Integer 'Server or client
// ServerIP As String 'Server's IP
// ServerCon As Boolean 'Server is connected
// ServerStr As String
// ServerLocked As Boolean
// ServerLoad1 As Double
// ServerLoad As Boolean
// ClientLocked(0 To 15) As Boolean
// ClientIP(0 To 15) As String
// ClientCon(0 To 15) As Boolean
// ClientName(0 To 15) As String
// ClientStr(0 To 15) As String
// ClientRelease(0 To 15) As Integer
// ClientPassword(0 To 15) As Boolean
// ClientLoad1(0 To 15) As Double
// Online As Boolean 'online or local
// MySlot As Integer
// MyControls As Controls
// Player(0 To 15) As nPlayer
// PlayerWaitCount As Integer
// NPCWaitCount As Single
//End Type
//Public Type Location 'Holds location information for objects
// X As Double
// Y As Double
// Height As Double
// Width As Double
// SpeedX As Double
// SpeedY As Double
//End Type
//Public Type EditorControls 'Controls for the editor
struct EditorControls_t
{
// Up As Boolean
bool Up = false;
// Down As Boolean
bool Down = false;
// Left As Boolean
bool Left = false;
// Right As Boolean
bool Right = false;
// Mouse1 As Boolean
bool Mouse1 = false;
//End Type
};
// Structures moved into con_control.h
//Public conKeyboard(1 To 2) As conKeyboard 'player 1 and 2's controls
extern RangeArr<ConKeyboard_t, 1, maxLocalPlayers> conKeyboard;
//Public conJoystick(1 To 2) As conJoystick
extern RangeArr<ConJoystick_t, 1, maxLocalPlayers> conJoystick;
//Public useJoystick(1 To 2) As Integer
extern RangeArrI<int, 1, maxLocalPlayers, 0> useJoystick;
extern RangeArrI<bool, 1, maxLocalPlayers, false> wantedKeyboard;
//Public Type NPC 'The NPC Type
struct NPC_t
{
// AttLayer As String
std::string AttLayer;
// Quicksand As Integer
int Quicksand = 0;
// RespawnDelay As Integeri
int RespawnDelay = 0;
// Bouce As Boolean
bool Bouce = false;
// Pinched1 As Integer 'getting smashed by a block
int Pinched1 = 0;
// Pinched2 As Integer
int Pinched2 = 0;
// Pinched3 As Integer
int Pinched3 = 0;
// Pinched4 As Integer
int Pinched4 = 0;
// MovingPinched As Integer 'required to be smashed
int MovingPinched = 0;
// NetTimeout As Integer 'for online
int NetTimeout = 0;
// RealSpeedX As Single 'the real speed of the NPC
float RealSpeedX = 0.0f;
// Wet As Integer ' greater then 0 of the NPC is in water
int Wet = 0;
// Settings As Integer
int Settings = 0;
// NoLavaSplash As Boolean 'true for no lava splash
bool NoLavaSplash = false;
// Slope As Integer 'the block that the NPC is on a slope with
int Slope = 0;
// Multiplier As Integer 'for upping the points the player recieves
int Multiplier = 0;
// TailCD As Integer 'if greater then 0 the player can't hit with it's tail
int TailCD = 0;
// Shadow As Boolean 'if true turn the NPC black and allow it to pass through walls. only used for a cheat code
bool Shadow = false;
// TriggerActivate As String 'for events - triggers when NPC gets activated
std::string TriggerActivate;
// TriggerDeath As String 'triggers when NPC dies
std::string TriggerDeath;
// TriggerTalk As String 'triggers when you talk to the NPC
std::string TriggerTalk;
// TriggerLast As String 'trigger when this is the last NPC in a layer to die
std::string TriggerLast;
// Layer As String 'the layer name that the NPC is in
std::string Layer;
// Hidden As Boolean 'if the layer is hidden or not
bool Hidden = false;
// Legacy As Boolean 'Legacy Boss
bool Legacy = false;
// Chat As Boolean 'for talking to the NPC
bool Chat = false;
// Inert As Boolean 'the friendly toggle. makes the NPC not do anything
bool Inert = false;
// Stuck As Boolean 'the 'don't move' toggle. forces the NPC not to move
bool Stuck = false;
// DefaultStuck As Boolean
bool DefaultStuck = false;
// Text As String 'the text that is displayed when you talk to the NPC
std::string Text;
// oldAddBelt As Single
float oldAddBelt = 0.0f;
// PinchCount As Integer 'obsolete
int PinchCount = 0;
// Pinched As Boolean 'obsolete
bool Pinched = false;
// PinchedDirection As Integer 'obsolete
int PinchedDirection = 0;
// BeltSpeed As Single 'The speed of the object this NPC is standing on
float BeltSpeed = 0.0f;
// standingOnPlayer As Integer 'If this NPC is standing on a player in the clown car
int standingOnPlayer = 0;
// standingOnPlayerY As Integer
int standingOnPlayerY = 0;
// Generator As Boolean 'for spawning new NPCs
bool Generator = false;
// GeneratorTimeMax As Single
float GeneratorTimeMax = 0.0f;
// GeneratorTime As Single
float GeneratorTime = 0.0f;
// GeneratorDirection As Integer
int GeneratorDirection = 0;
// GeneratorEffect As Integer
int GeneratorEffect = 0;
// GeneratorActive As Boolean
bool GeneratorActive = false;
// playerTemp As Boolean
bool playerTemp = false;
// Location As Location 'collsion detection information
Location_t Location;
//'the default values are used when De-Activating an NPC when it goes on screen
// DefaultLocation As Location
Location_t DefaultLocation;
// DefaultDirection As Single
float DefaultDirection = 0.0f;
// DefaultType As Integer
int DefaultType = 0;
// DefaultSpecial As Integer
int DefaultSpecial = 0;
// DefaultSpecial2 As Integer
int DefaultSpecial2 = 0;
// Type As Integer 'Defines what NPC this is. 1 for goomba, 2 for red goomba, etc.
int Type = 0;
// Frame As Integer 'The graphic to be shown
int Frame = 0;
// FrameCount As Single 'The counter for incrementing the frames
float FrameCount = 0.0f;
// Direction As Single 'The direction the NPC is walking
float Direction = 0.0f;
//'Secial - misc variables used for NPC AI
// Special As Double
double Special = 0.0;
// Special2 As Double
double Special2 = 0.0;
// Special3 As Double
double Special3 = 0.0;
// Special4 As Double
double Special4 = 0.0;
// Special5 As Double
double Special5 = 0.0;
// Special6 As Double
double Special6 = 0.0;
// EXTRA: Special7 As Double
double Special7 = 0.0;
// TurnAround As Boolean 'if the NPC needs to turn around
bool TurnAround = false;
// Killed As Integer 'Flags the NPC to die a specific way.
int Killed = 0;
// Active As Boolean 'If on screen
bool Active = false;
// Reset(1 To 2) As Boolean 'If it can display the NPC
RangeArrI<bool, 1, 2, false> Reset;
// TimeLeft As Integer 'Time left before reset when not on screen
int TimeLeft = 0;
// HoldingPlayer As Integer 'Who is holding it
int HoldingPlayer = 0;
// CantHurt As Integer 'Won't hurt the player
int CantHurt = 0;
// CantHurtPlayer As Integer
int CantHurtPlayer = 0;
// BattleOwner As Integer 'Owner of the projectile
int BattleOwner = 0;
// WallDeath As Integer
int WallDeath = 0;
// Projectile As Boolean 'If the NPC is a projectile
int Projectile = 0;
// Effect As Integer 'For starting / stopping effects
int Effect = 0;
// Effect2 As Double
double Effect2 = 0.0; // When Effect 4, Used to store a destination position, must be in double!
// Effect3 As Integer
int Effect3 = 0;
// Section As Integer 'what section of the level the NPC is in
int Section = 0;
// Damage As Single
float Damage = 0.0f;
// JustActivated As Integer 'The player that activated the NPC
int JustActivated = 0;
// Block As Integer 'Used when a P-Switch turns a block into a coint
int Block = 0;
// tempBlock As Integer
int tempBlock = 0;
// onWall As Boolean
bool onWall = false;
// TurnBackWipe As Boolean
bool TurnBackWipe = false;
// Immune As Integer 'time that the NPC is immune
int Immune = 0;
//End Type
};
//Public Type Player 'The player data type.
struct Player_t
{
// DoubleJump As Boolean
bool DoubleJump = false;
// FlySparks As Boolean
bool FlySparks = false;
// Driving As Boolean
bool Driving = false;
// Quicksand As Integer
int Quicksand = 0;
// Bombs As Integer
int Bombs = 0;
// Slippy As Boolean
bool Slippy = false;
// Fairy As Boolean
bool Fairy = false;
// FairyCD As Integer
int FairyCD = 0;
// FairyTime As Integer
int FairyTime = 0;
// HasKey As Boolean
bool HasKey = false;
// SwordPoke As Integer
int SwordPoke = 0;
// Hearts As Integer
int Hearts = 0;
// CanFloat As Boolean
bool CanFloat = false;
// FloatRelease As Boolean
bool FloatRelease = false;
// FloatTime As Integer
int FloatTime = 0;
// FloatSpeed As Single
float FloatSpeed = 0.0f;
// FloatDir As Integer
int FloatDir = 0;
// GrabTime As Integer 'how long the player has been trying to grab an npc from above
int GrabTime = 0;
// GrabSpeed As Single
float GrabSpeed = 0.0f;
// VineNPC As Double 'the NPC that the player is climbing
double VineNPC = 0.0;
// EXTRA: Fence BGO
double VineBGO = 0.0;
// Wet As Integer 'weather or not the player is under water
int Wet = 0;
// WetFrame As Boolean 'true if the play should be swimming
bool WetFrame = false;
// SwimCount As Integer 'cool down between swim strokes
int SwimCount = 0;
// NoGravity As Integer
int NoGravity = 0;
// Slide As Boolean 'true if the player is sliding
bool Slide = false;
// SlideKill As Boolean 'true if the player is sliding fast enough to kill an NPC
bool SlideKill = false;
// Vine As Integer 'greater then 0 if the player is climbing
int Vine = 0;
// NoShellKick As Integer 'dont kick a shell
int NoShellKick = 0;
// ShellSurf As Boolean 'true if surfing a shell
bool ShellSurf = false;
// StateNPC As Integer
int StateNPC = 0;
// Slope As Integer 'the block that the player is standing on when on a slope
int Slope = 0;
// Stoned As Boolean 'true of a statue form (tanooki suit)
bool Stoned = false;
// StonedCD As Integer 'delay before going back in to stone form
int StonedCD = 0;
// StonedTime As Integer 'how long the player can remain as a statue
int StonedTime = 0;
// SpinJump As Boolean 'true if spin jumping
bool SpinJump = false;
// SpinFrame As Integer 'frame for spinning
int SpinFrame = 0;
// SpinFireDir As Integer 'for shooting fireballs while spin jumping
int SpinFireDir = 0;
// Multiplier As Integer 'for score increase for multiple hops
int Multiplier = 0;
// SlideCounter As Integer 'for creating the dust effect when sliding
int SlideCounter = 0;
// ShowWarp As Integer
int ShowWarp = 0;
// GroundPound As Boolean 'for purple yoshi pound
bool GroundPound = false;
// GroundPound2 As Boolean 'for purple yoshi pound
bool GroundPound2 = false;
// CanPound As Boolean 'for purple yoshi pound
bool CanPound = false;
// ForceHold As Integer 'force the player to hold an item for a specific amount of time
int ForceHold = 0;
//'yoshi powers
// YoshiYellow As Boolean
bool YoshiYellow = false;
// YoshiBlue As Boolean
bool YoshiBlue = false;
// YoshiRed As Boolean
bool YoshiRed = false;
// YoshiWingsFrame As Integer
int YoshiWingsFrame = 0;
// YoshiWingsFrameCount As Integer
int YoshiWingsFrameCount = 0;
//'yoshi graphic display
// YoshiTX As Integer
int YoshiTX = 0;
// YoshiTY As Integer
int YoshiTY = 0;
// YoshiTFrame As Integer
int YoshiTFrame = 0;
// YoshiTFrameCount As Integer
int YoshiTFrameCount = 0;
// YoshiBX As Integer
int YoshiBX = 0;
// YoshiBY As Integer
int YoshiBY = 0;
// YoshiBFrame As Integer
int YoshiBFrame = 0;
// YoshiBFrameCount As Integer
int YoshiBFrameCount = 0;
// YoshiTongue As Location
Location_t YoshiTongue;
// YoshiTongueX As Single
float YoshiTongueX = 0.0f;
// YoshiTongueLength As Integer 'length of yoshi's tongue
int YoshiTongueLength = 0;
// YoshiTonugeBool As Boolean
bool YoshiTonugeBool = false;
// YoshiNPC As Integer 'the NPC that is in yoshi's mouth
int YoshiNPC = 0;
// YoshiPlayer As Integer 'the player that is in yoshi's mouth
int YoshiPlayer = 0;
// Dismount As Integer 'delay before you can remount
int Dismount = 0;
// NoPlayerCol As Integer
int NoPlayerCol = 0;
// Location As Location 'collision detection info
Location_t Location;
// Character As Integer 'luigi or mario
int Character = 0;
// Controls As Controls 'players controls
Controls_t Controls;
// Direction As Integer 'the way the player is facing
int Direction = 0;
// Mount As Integer '1 for boot, 2 for clown car, 3 for yoshi
int Mount = 0;
// MountType As Integer 'for different types of mounts. blue yoshi, red yoshi, etc
int MountType = 0;
// MountSpecial As Integer
int MountSpecial = 0;
// MountOffsetY As Integer
int MountOffsetY = 0;
// MountFrame As Integer 'GFX frame for the player's mount
int MountFrame = 0;
// State As Integer '1 for small mario, 2 for super, 3 for fire, 4 for racoon, 5 for tanooki, 6 for hammer
int State = 0;
// Frame As Integer
int Frame = 0;
// FrameCount As Single
int FrameCount = 0;
// Jump As Integer 'how long the player can jump for
int Jump = 0;
// CanJump As Boolean 'true if the player can jump
bool CanJump = false;
// CanAltJump As Boolean 'true if the player can alt jump
bool CanAltJump = false;
// Effect As Integer 'for various effects like shrinking/growing/warping
int Effect = 0;
// Effect2 As Double 'counter for the effects
double Effect2 = 0.0;
// DuckRelease As Boolean
bool DuckRelease = false;
// Duck As Boolean 'true if ducking
bool Duck = false;
// DropRelease As Boolean
bool DropRelease = false;
// StandUp As Boolean 'aid with collision detection after ducking
bool StandUp = false;
// StandUp2 As Boolean
bool StandUp2 = false;
// Bumped As Boolean 'true if hit by another player
bool Bumped = false;
// Bumped2 As Single
float Bumped2 = 0.0f;
// Dead As Boolean 'true if dead
bool Dead = false;
// TimeToLive As Integer 'for returning to the other play after dying
int TimeToLive = 0;
// Immune As Integer 'greater then 0 if immune, this is a counter
int Immune = 0;
// Immune2 As Boolean 'makes the player blink
bool Immune2 = false;
// ForceHitSpot3 As Boolean 'force hitspot 3 for collision detection
bool ForceHitSpot3 = false;
//'for getting smashed by a block
// Pinched1 As Integer
int Pinched1 = 0;
// Pinched2 As Integer
int Pinched2 = 0;
// Pinched3 As Integer
int Pinched3 = 0;
// Pinched4 As Integer
int Pinched4 = 0;
// NPCPinched As Integer 'must be > 0 for the player to get crushed
int NPCPinched = 0;
// m2Speed As Single
float m2Speed = 0.0f;
// HoldingNPC As Integer 'What NPC is being held
int HoldingNPC = 0;
// CanGrabNPCs As Boolean 'If the player can grab NPCs
bool CanGrabNPCs = false;
// HeldBonus As Integer 'the NPC that is in the player's container
int HeldBonus = 0;
// Section As Integer 'What section of the level the player is in
int Section = 0;
// WarpCD As Integer 'delay before allowing the player to warp again
int WarpCD = 0;
// Warp As Integer 'the warp the player is using
int Warp = 0;
// FireBallCD As Integer 'How long the player has to wait before he can shoot again
int FireBallCD = 0;
// FireBallCD2 As Integer 'How long the player has to wait before he can shoot again
int FireBallCD2 = 0;
// TailCount As Integer 'Used for the tail swipe
int TailCount = 0;
// RunCount As Single 'To find how long the player has ran for
float RunCount = 0.0f;
// CanFly As Boolean 'If the player can fly
bool CanFly = false;
// CanFly2 As Boolean
bool CanFly2 = false;
// FlyCount As Integer 'length of time the player can fly
int FlyCount = 0;
// RunRelease As Boolean 'The player let go of run and pressed again
bool RunRelease = false;
// JumpRelease As Boolean 'The player let go of run and pressed again
bool JumpRelease = false;
// StandingOnNPC As Integer 'The NPC the player is standing on
int StandingOnNPC = 0;
// StandingOnTempNPC As Integer 'The NPC the player is standing on
int StandingOnTempNPC = 0;
// UnStart As Boolean 'Player let go of the start button
bool UnStart = false;
// mountBump As Single 'Player hit something while in a mount
float mountBump = 0.0f;
// SpeedFixY As Single
float SpeedFixY = 0.0f;
//End Type
};
//Public Type Background 'Background objects
struct Background_t
{
// Layer As String
std::string Layer;
// Hidden As Boolean
bool Hidden = false;
// Type As Integer
int Type = 0;
// Location As Location
Location_t Location;
//EXTRA: make a custom sorting priority
int SortPriority = -1;
//EXTRA: sub-priority
double zOffset = 0.0;
//EXTRA: UID
int uid = 0;
//End Type
};
//Public Type Water
struct Water_t
{
// Layer As String
std::string Layer;
// Hidden As Boolean
bool Hidden = false;
// Buoy As Single 'not used
float Buoy = 0.0f;
// Quicksand As Boolean
bool Quicksand = false;
// Location As Location
Location_t Location;
//End Type
};
//Public Type Block 'Blocks
struct Block_t
{
// Slippy As Boolean
bool Slippy = false;
// RespawnDelay As Integer
int RespawnDelay = 0;
// RapidHit As Integer
int RapidHit = 0;
// DefaultType As Integer
int DefaultType = 0;
// DefaultSpecial As Integer
int DefaultSpecial = 0;
//'for event triggers
// TriggerHit As String
std::string TriggerHit;
// TriggerDeath As String
std::string TriggerDeath;
// TriggerLast As String
std::string TriggerLast;
// Layer As String
std::string Layer;
// Hidden As Boolean
bool Hidden = false;
// Type As Integer 'the block's type
int Type = 0;
// Location As Location
Location_t Location;
// Special As Integer 'what is in the block?
int Special = 0;
//'for the shake effect after hitting ablock
// ShakeY As Integer
int ShakeY = 0;
// ShakeY2 As Integer
int ShakeY2 = 0;
// ShakeY3 As Integer
int ShakeY3 = 0;
// Kill As Boolean 'if true the game will destroy the block
bool Kill = false;
// Invis As Boolean 'for invisible blocks
bool Invis = false;
// NPC As Integer 'when a coin is turned into a block after the p switch is hit
int NPC = 0;
// IsPlayer As Integer 'for the clown car
int IsPlayer = 0;
// IsNPC As Integer 'the type of NPC the block is
int IsNPC = 0;
// standingOnPlayerY As Integer 'when standing on a player in the clown car
int standingOnPlayerY = 0;
// noProjClipping As Boolean
bool noProjClipping = false;
// EXTRA: Indicate the fact that block was resized by a hit
bool wasShrinkResized = false;
// IsReally As Integer 'the NPC that is this block
int IsReally = 0;
//End Type
};
//Public Type Effect 'Special effects
struct Effect_t
{
// Type As Integer
int Type = 0;
// Location As Location
Location_t Location;
// Frame As Integer
int Frame = 0;
// FrameCount As Single
int FrameCount = 0;
// Life As Integer 'timer before the effect disappears
int Life = 0;
// NewNpc As Integer 'when an effect should create and NPC, such as Yoshi
int NewNpc = 0;
// Shadow As Boolean 'for a black effect set to true
bool Shadow = false;
//End Type
};
//Public Type vScreen 'Screen controls
struct vScreen_t
{
// Left As Double
double Left = 0.0;
// Top As Double
double Top = 0.0;
// Width As Double
double Width = 0.0;
// Height As Double
double Height = 0.0;
// Visible As Boolean
bool Visible = false;
// tempX As Double
double tempX = 0.0;
// TempY As Double
double TempY = 0.0;
// TempDelay As Integer
int TempDelay = 0;
//End Type
};
//Public Type WorldLevel 'the type for levels on the world map
struct WorldLevel_t
{
// Location As Location
Location_t Location;
// Type As Integer
int Type = 0;
// FileName As String 'level's file
std::string FileName;
// LevelExit(1 To 4) As Integer ' For the direction each type of exit opens the path
RangeArrI<int, 1, 4, 0> LevelExit;
// Active As Boolean
bool Active = false;
// LevelName As String 'The name of the level
std::string LevelName;
// StartWarp As Integer 'If the level should start with a player exiting a warp
int StartWarp = 0;
// WarpX As Double 'for warping to another location on the world map
double WarpX = 0.0;
// WarpY As Double
double WarpY = 0.0;
// Path As Boolean 'for drawing a small path background
bool Path = false;
// Path2 As Boolean 'big path background
bool Path2 = false;
// Start As Boolean 'true if the game starts here
bool Start = false;
// Visible As Boolean 'true if it should be shown on the map
bool Visible = false;
//End Type
int64_t Z = 0;
int index = 0;
};
//Public Type Warp 'warps such as pipes and doors
struct Warp_t
{
// Locked As Boolean 'requires a key NPC
bool Locked = false;
// WarpNPC As Boolean 'allows NPC through the warp
bool WarpNPC = false;
// NoYoshi As Boolean 'don't allow yoshi
bool NoYoshi = false;
// Layer As String 'the name of the layer
std::string Layer;
// Hidden As Boolean 'if the layer is hidden
bool Hidden = false;
// PlacedEnt As Boolean 'for the editor, flags the entranced as placed
bool PlacedEnt = false;
// PlacedExit As Boolean
bool PlacedExit = false;
// Stars As Integer 'number of stars required to enter
int Stars = 0;
// Entrance As Location 'location of warp entrance
Location_t Entrance;
// Exit As Location 'location of warp exit
Location_t Exit;
// Effect As Integer 'style of warp. door/
int Effect = 0;
// level As String 'filename of the level it should warp to
std::string level;
// LevelWarp As Integer
int LevelWarp = 0;
// LevelEnt As Boolean 'this warp can't be used if set to true (this is for level entrances)
bool LevelEnt = false;
// Direction As Integer 'direction of the entrance for pipe style warps
int Direction = 0;
// Direction2 As Integer 'direction of the exit
int Direction2 = 0;
// MapWarp As Boolean
bool MapWarp = false;
// MapX As Integer
int MapX = 0;
// MapY As Integer
int MapY = 0;
// curStars As Integer
int curStars = 0;
// maxStars As Integer
int maxStars = 0;
//EXTRA:
bool noPrintStars = false;
bool noEntranceScene = false;
bool cannonExit = false;
double cannonExitSpeed = 10.0;
std::string eventEnter;
std::string StarsMsg;
//End Type
};
//Public Type Tile 'Tiles for the World
struct Tile_t
{
// Location As Location
Location_t Location;
// Type As Integer
int Type = 0;
//End Type
int64_t Z = 0;
bool Active = true;
};
//Public Type Scene 'World Scenery
struct Scene_t
{
// Location As Location
Location_t Location;
// Type As Integer
int Type = 0;
// Active As Boolean 'if false this won't be shown. used for paths that become available on a scene
bool Active = false;
//End Type
int64_t Z = 0;
};
//Public Type WorldPath 'World Paths
struct WorldPath_t
{
// Location As Location
Location_t Location;
// Active As Boolean
bool Active = false;
// Type As Integer
int Type = 0;
//End Type
int64_t Z = 0;
int index = 0;
};
//Public Type WorldMusic 'World Music
struct WorldMusic_t
{
// Location As Location
Location_t Location;
// Type As Integer
int Type = 0;
// EXTRA: Custom Music
std::string MusicFile;
//End Type
int64_t Z = 0;
bool Active = true;
};
//Public Type EditorCursor 'The editor's cursor
struct EditorCursor_t
{
// X As Single
float X = -50.0f;
// Y As Single
float Y = -50.0f;
// SelectedMode As Integer 'cursor mode. eraser/npc/block/background
int SelectedMode = 0;
// Selected As Integer
int Selected = 0;
// Location As Location
Location_t Location;
// Layer As String 'current layer
std::string Layer;
// Mode As Integer
int Mode = 0;
// Block As Block
Block_t Block;
// Water As Water
Water_t Water;
// Background As Background
Background_t Background;
// NPC As NPC
NPC_t NPC;
// Warp As Warp
Warp_t Warp;
// Tile As Tile
Tile_t Tile;
// Scene As Scene
Scene_t Scene;
// WorldLevel As WorldLevel
WorldLevel_t WorldLevel;
// WorldPath As WorldPath
WorldPath_t WorldPath;
// WorldMusic As WorldMusic
WorldMusic_t WorldMusic;
//End Type
};
//Public Type WorldPlayer 'the players variables on the world map
struct WorldPlayer_t
{
// Location As Location
Location_t Location;
// Type As Integer
int Type = 0;
// Frame As Integer
int Frame = 0;
// Frame2 As Integer
int Frame2 = 0;
// Move As Integer
int Move = 0;
// Move2 As Integer
int Move2 = 0;
// Move3 As Boolean
int Move3 = 0;
// LevelName As String
std::string LevelName;
//End Type
};
//Public Type Layer
//moved into layers.h
//Public Type CreditLine
struct CreditLine_t
{
// Location As Location
Location_t Location;
// Text As String
std::string Text;
//End Type
};
//Public ScreenShake As Integer
//extern int ScreenShake; // REPLACED with static variables at the update_gfx.cpp
// TODO: Make it have multiple checkpoints and assign each one with different NPCs,
// last one should resume player at given position
//Public Checkpoint As String 'the filename of the level the player has a checkpoint in
extern std::string Checkpoint;
struct Checkpoint_t
{
int id = 0;
};
// List of taken checkpoints, spawn player at last of them
extern std::vector<Checkpoint_t> CheckpointsList;
//Public MagicHand As Boolean 'true if playing a level in the editor while not in fullscreen mode
extern bool MagicHand;
//Public testPlayer(1 To 2) As Player 'test level player settings
extern RangeArr<Player_t, 1, 2> testPlayer;
//Public ClearBuffer As Boolean 'true to black the backbuffer
extern bool ClearBuffer;
//Public numLocked As Integer
extern int numLocked;
//Public resChanged As Boolean 'true if in fullscreen mode
extern bool resChanged;
//Public inputKey As Integer 'for setting the players controls
extern int inputKey;
//Public getNewKeyboard As Boolean 'true if setting keyboard controls
extern bool getNewKeyboard;
//Public getNewJoystick As Boolean
extern bool getNewJoystick;
//Public lastJoyButton As Integer
extern KM_Key lastJoyButton;
//Public GamePaused As Boolean 'true if the game is paused
extern bool GamePaused;
//Public MessageText As String 'when talking to an npc
extern std::string MessageText;
//Public NumSelectWorld As Integer
extern int NumSelectWorld;
//Public SelectWorld(1 To 100) As SelectWorld
struct SelectWorld_t;
//extern RangeArr<SelectWorld_t, 1, maxSelectWorlds> SelectWorld;
extern std::vector<SelectWorld_t> SelectWorld;
//Public ShowFPS As Boolean
extern bool ShowFPS;
//Public PrintFPS As Double
extern double PrintFPS;
// Do ground-point by alt-run key instead of down
extern bool GameplayPoundByAltRun;
// Shake screen on thwomp falling
extern bool GameplayShakeScreenThwomp;
// Shake screen on Bowser III'rd ground pound
extern bool GameplayShakeScreenBowserIIIrd;
// Shake screen on Yoshi ground pount
extern bool GameplayShakeScreenPound;
// Enable usage of the rumble control
extern bool JoystickEnableRumble;
// Show the battery status for wireless gamepads
extern bool JoystickEnableBatteryStatus;
//Public vScreen(0 To 2) As vScreen 'Sets up the players screens
extern RangeArr<vScreen_t, 0, 2> vScreen;
//Public ScreenType As Integer 'The screen/view type
extern int ScreenType;
//Public DScreenType As Integer 'The dynamic screen setup
extern int DScreenType;
//Public LevelEditor As Boolean 'if true, load the editor
extern bool LevelEditor;
//Public WorldEditor As Boolean
extern bool WorldEditor;
//Public PlayerStart(1 To 2) As Location
extern RangeArr<Location_t, 1, 2> PlayerStart;
//Public blockCharacter(0 To 20) As Boolean
extern RangeArrI<bool, 0, 20, false> blockCharacter;
//Public Type SelectWorld
struct SelectWorld_t
{
// WorldName As String
std::string WorldName;
// WorldPath As String
std::string WorldPath;
// WorldFile As String
std::string WorldFile;
// blockChar(1 To numCharacters) As Boolean
RangeArrI<bool, 1, numCharacters, false> blockChar;
//End Type
};
//Public OwedMount(0 To maxPlayers) As Integer 'when a yoshi/boot is taken from the player this returns after going back to the world map
extern RangeArrI<int, 0, maxPlayers, 0> OwedMount;
//Public OwedMountType(0 To maxPlayers) As Integer
extern RangeArrI<int, 0, maxPlayers, 0> OwedMountType;
//Public AutoX(0 To maxSections) As Single 'for autoscroll
extern RangeArr<float, 0, maxSections> AutoX;
//Public AutoY(0 To maxSections) As Single 'for autoscroll
extern RangeArr<float, 0, maxSections> AutoY;
//Public numStars As Integer 'the number of stars the player has
extern int numStars;
//Public Type Star 'keeps track of where there player got the stars from
struct Star_t
{
// level As String
std::string level;
// Section As Integer
int Section = 0;
//End Type
};
//Public nPlay As nPlay ' for online stuff
//Public Water(0 To maxWater) As Water
extern RangeArr<Water_t, 0, maxWater> Water;
//Public numWater As Integer 'number of water
extern int numWater;
//Public Star(1 To 1000) As Star
extern RangeArr<Star_t, 1, maxStarsNum> Star;
//Public GoToLevel As String
extern std::string GoToLevel;
//! EXTRA: Hide entrance screen
extern bool GoToLevelNoGameThing;
//Public StartLevel As String 'start level for an episode
extern std::string StartLevel;
//Public NoMap As Boolean 'episode has no world map
extern bool NoMap;
//Public RestartLevel As Boolean 'restart the level on death
extern bool RestartLevel;
//Public LevelChop(0 To maxSections) As Single 'for drawing backgrounds when the level has been shrunk
extern float LevelChop[maxSections + 1];
//'collision detection optimization. creates a table of contents for blocks
//Public Const FLBlocks As Long = 8000
const long FLBlocks = 10000;
//Public FirstBlock(-FLBlocks To FLBlocks) As Integer
extern RangeArr<int, -FLBlocks, FLBlocks> FirstBlock;
//Public LastBlock(-FLBlocks To FLBlocks) As Integer
extern RangeArr<int, -FLBlocks, FLBlocks> LastBlock;
//Public MidBackground As Integer 'for drawing backgrounds
extern int MidBackground;
//Public LastBackground As Integer 'last backgrounds to be drawn
extern int LastBackground;
//Public iBlocks As Integer 'blocks that are doing something. this keeps the number of interesting blocks
extern int iBlocks;
//Public iBlock(0 To maxBlocks) As Integer 'references a block #
extern RangeArrI<int, 0, maxBlocks, 0> iBlock;
//Public numTiles As Integer 'number of map tiles
extern int numTiles;
//Public numScenes As Integer 'number of scense
extern int numScenes;
//Public CustomMusic(0 To maxSections) As String 'section's custom music
extern RangeArr<std::string, 0, maxSections> CustomMusic;
//EXTRA: Max count of used sections
extern int numSections;
//Public level(0 To maxSections) As Location 'sections
extern RangeArr<Location_t, 0, maxSections> level;
//Public LevelWrap(0 To maxSections) As Boolean 'Wrap around the level
extern RangeArrI<bool, 0, maxSections, false> LevelWrap;
//EXTRA: Wrap vertically around the level
extern RangeArrI<bool, 0, maxSections, false> LevelVWrap;
//Public OffScreenExit(0 To maxSections) As Boolean 'walk offscreen to end the level
extern RangeArrI<bool, 0, maxSections, false> OffScreenExit;
//Public bgMusic(0 To maxSections) As Integer 'music
extern RangeArrI<int, 0, maxSections, 0> bgMusic;
//Public bgMusicREAL(0 To maxSections) As Integer 'default music
extern RangeArrI<int, 0, maxSections, 0> bgMusicREAL;
//Public Background2REAL(0 To maxSections) As Integer 'background
extern RangeArrI<int, 0, maxSections, 0> Background2REAL;
//Public LevelREAL(0 To maxSections) As Location 'default background
extern RangeArr<Location_t, 0, maxSections> LevelREAL;
//Public curMusic As Integer 'current music playing
extern int curMusic;
//Public bgColor(0 To maxSections) As Long 'obsolete
extern RangeArrI<long, 0, maxSections, 0> bgColor;
//Public Background2(0 To maxSections) As Integer 'level background
extern RangeArrI<int, 0, maxSections, 0> Background2;
//Public WorldPath(1 To maxWorldPaths) As WorldPath
extern RangeArr<WorldPath_t, 1, maxWorldPaths> WorldPath;
//Public numWorldPaths As Integer
extern int numWorldPaths;
//Public numWarps As Integer 'number of warps in a level
extern int numWarps;
//Public Warp(1 To maxWarps) As Warp 'define the warps
extern RangeArr<Warp_t, 1, maxWarps> Warp;
//Public Tile(1 To maxTiles) As Tile
extern RangeArr<Tile_t, 1, maxTiles> Tile;
//Public Scene(1 To maxScenes) As Scene
extern RangeArr<Scene_t, 1, maxScenes> Scene;
//Public Credit(1 To 200) As CreditLine 'for end game credits
extern RangeArr<CreditLine_t, 1, maxCreditsLines> Credit;
extern double CreditOffsetY;
extern double CreditTotalHeight;
//Public numCredits As Integer 'number of credits
extern int numCredits;
//Public numBlock As Integer 'number of blocks
extern int numBlock;
//Public numBackground As Integer 'number of background objects
extern int numBackground;
//Public numNPCs As Integer
extern int numNPCs;
//Public numEffects As Integer
extern int numEffects;
//Public numPlayers As Integer
extern int numPlayers;
//Public numWorldLevels As Integer
extern int numWorldLevels;
//Public WorldMusic(1 To maxWorldMusic) As WorldMusic
extern RangeArr<WorldMusic_t, 1, maxWorldMusic> WorldMusic;
//Public numWorldMusic As Integer
extern int numWorldMusic;
//Public WorldLevel(1 To maxWorldLevels) As WorldLevel
extern RangeArr<WorldLevel_t, 1, maxWorldLevels> WorldLevel;
//Public Background(1 To maxBackgrounds) As Background
extern RangeArr<Background_t, 1, (maxBackgrounds + maxWarps)> Background;
//Public Effect(1 To maxEffects) As Effect
extern RangeArr<Effect_t, 1, maxEffects> Effect;
//Public NPC(-128 To maxNPCs) As NPC
extern RangeArr<NPC_t, -128, maxNPCs> NPC;
//Public Block(0 To maxBlocks) As Block
extern RangeArr<Block_t, 0, maxBlocks> Block;
//Public Player(0 To maxPlayers) As Player
extern RangeArr<Player_t, 0, maxPlayers> Player;
//Public MarioFrameX(0 To maxPlayerFrames) As Integer 'Player frame offset X
extern RangeArrI<int, 0, maxPlayerFrames, 0> MarioFrameX;
//Public MarioFrameY(0 To maxPlayerFrames) As Integer 'Player frame offset Y
extern RangeArrI<int, 0, maxPlayerFrames, 0> MarioFrameY;
//Public LuigiFrameX(0 To maxPlayerFrames) As Integer 'Player frame offset X
extern RangeArrI<int, 0, maxPlayerFrames, 0> LuigiFrameX;
//Public LuigiFrameY(0 To maxPlayerFrames) As Integer 'Player frame offset Y
extern RangeArrI<int, 0, maxPlayerFrames, 0> LuigiFrameY;
//Public PeachFrameX(0 To maxPlayerFrames) As Integer 'Player frame offset X
extern RangeArrI<int, 0, maxPlayerFrames, 0> PeachFrameX;
//Public PeachFrameY(0 To maxPlayerFrames) As Integer 'Player frame offset Y
extern RangeArrI<int, 0, maxPlayerFrames, 0> PeachFrameY;
//Public ToadFrameX(0 To maxPlayerFrames) As Integer 'Player frame offset X
extern RangeArrI<int, 0, maxPlayerFrames, 0> ToadFrameX;
//Public ToadFrameY(0 To maxPlayerFrames) As Integer 'Player frame offset Y
extern RangeArrI<int, 0, maxPlayerFrames, 0> ToadFrameY;
//Public LinkFrameX(0 To maxPlayerFrames) As Integer 'Player frame offset X
extern RangeArrI<int, 0, maxPlayerFrames, 0> LinkFrameX;
//Public LinkFrameY(0 To maxPlayerFrames) As Integer 'Player frame offset Y
extern RangeArrI<int, 0, maxPlayerFrames, 0> LinkFrameY;
//Public BackgroundFence(0 To maxBackgroundType) As Boolean
extern RangeArrI<bool, 0, maxBackgroundType, false> BackgroundFence;
//Public NPCFrameOffsetX(0 To maxNPCType) As Integer 'NPC frame offset X
extern RangeArrI<int, 0, maxNPCType, 0> NPCFrameOffsetX;
//Public NPCFrameOffsetY(0 To maxNPCType) As Integer 'NPC frame offset Y
extern RangeArrI<int, 0, maxNPCType, 0> NPCFrameOffsetY;
//Public NPCWidth(0 To maxNPCType) As Integer 'NPC width
extern RangeArrI<int, 0, maxNPCType, 0> NPCWidth;
//Public NPCHeight(0 To maxNPCType) As Integer 'NPC height
extern RangeArrI<int, 0, maxNPCType, 0> NPCHeight;
//Public NPCWidthGFX(0 To maxNPCType) As Integer 'NPC gfx width
extern RangeArrI<int, 0, maxNPCType, 0> NPCWidthGFX;
//Public NPCHeightGFX(0 To maxNPCType) As Integer 'NPC gfx height
extern RangeArrI<int, 0, maxNPCType, 0> NPCHeightGFX;
//Public NPCSpeedvar(0 To maxNPCType) As Single 'NPC Speed Change
extern RangeArr<float, 0, maxNPCType> NPCSpeedvar;
//Public NPCIsAShell(0 To maxNPCType) As Boolean 'Flags the NPC type if it is a shell
extern RangeArrI<bool, 0, maxNPCType, false> NPCIsAShell;
//Public NPCIsABlock(0 To maxNPCType) As Boolean 'Flag NPC as a block
extern RangeArrI<bool, 0, maxNPCType, false> NPCIsABlock;
//Public NPCIsAHit1Block(0 To maxNPCType) As Boolean 'Flag NPC as a hit1 block
extern RangeArrI<bool, 0, maxNPCType, false> NPCIsAHit1Block;
//Public NPCIsABonus(0 To maxNPCType) As Boolean 'Flags the NPC type if it is a bonus
extern RangeArrI<bool, 0, maxNPCType, false> NPCIsABonus;
//Public NPCIsACoin(0 To maxNPCType) As Boolean 'Flags the NPC type if it is a coin
extern RangeArrI<bool, 0, maxNPCType, false> NPCIsACoin;
//Public NPCIsAVine(0 To maxNPCType) As Boolean 'Flags the NPC type if it is a vine
extern RangeArrI<bool, 0, maxNPCType, false> NPCIsAVine;
//Public NPCIsAnExit(0 To maxNPCType) As Boolean 'Flags the NPC type if it is a level exit
extern RangeArrI<bool, 0, maxNPCType, false> NPCIsAnExit;
//Public NPCIsAParaTroopa(0 To maxNPCType) As Boolean 'Flags the NPC type as a para-troopa
extern RangeArrI<bool, 0, maxNPCType, false> NPCIsAParaTroopa;
//Public NPCIsCheep(0 To maxNPCType) As Boolean 'Flags the NPC type as a cheep cheep
extern RangeArrI<bool, 0, maxNPCType, false> NPCIsCheep;
//Public NPCJumpHurt(0 To maxNPCType) As Boolean 'Hurts the player even if it jumps on the NPC
extern RangeArrI<bool, 0, maxNPCType, false> NPCJumpHurt;
//Public NPCNoClipping(0 To maxNPCType) As Boolean 'NPC can go through blocks
extern RangeArrI<bool, 0, maxNPCType, false> NPCNoClipping;
//Public NPCScore(0 To maxNPCType) As Integer 'NPC score value
extern RangeArrI<int, 0, maxNPCType, 0> NPCScore;
//Public NPCCanWalkOn(0 To maxNPCType) As Boolean 'NPC can be walked on
extern RangeArrI<bool, 0, maxNPCType, false> NPCCanWalkOn;
//Public NPCGrabFromTop(0 To maxNPCType) As Boolean 'NPC can be grabbed from the top
extern RangeArrI<bool, 0, maxNPCType, false> NPCGrabFromTop;
//Public NPCTurnsAtCliffs(0 To maxNPCType) As Boolean 'NPC turns around at cliffs
extern RangeArrI<bool, 0, maxNPCType, false> NPCTurnsAtCliffs;
//Public NPCWontHurt(0 To maxNPCType) As Boolean 'NPC wont hurt the player
extern RangeArrI<bool, 0, maxNPCType, false> NPCWontHurt;
//Public NPCMovesPlayer(0 To maxNPCType) As Boolean 'Player can not walk through the NPC
extern RangeArrI<bool, 0, maxNPCType, false> NPCMovesPlayer;
//Public NPCStandsOnPlayer(0 To maxNPCType) As Boolean 'for the clown car
extern RangeArrI<bool, 0, maxNPCType, false> NPCStandsOnPlayer;
//Public NPCIsGrabbable(0 To maxNPCType) As Boolean 'Player can grab the NPC
extern RangeArrI<bool, 0, maxNPCType, false> NPCIsGrabbable;
//Public NPCIsBoot(0 To maxNPCType) As Boolean 'npc is a kurbo's shoe
extern RangeArrI<bool, 0, maxNPCType, false> NPCIsBoot;
//Public NPCIsYoshi(0 To maxNPCType) As Boolean 'npc is a yoshi
extern RangeArrI<bool, 0, maxNPCType, false> NPCIsYoshi;
//Public NPCIsToad(0 To maxNPCType) As Boolean 'npc is a toad
extern RangeArrI<bool, 0, maxNPCType, false> NPCIsToad;
//Public NPCNoYoshi(0 To maxNPCType) As Boolean 'Player can't eat the NPC
extern RangeArrI<bool, 0, maxNPCType, false> NPCNoYoshi;
//Public NPCForeground(0 To maxNPCType) As Boolean 'draw the npc in front
extern RangeArrI<bool, 0, maxNPCType, false> NPCForeground;
//Public NPCIsABot(0 To maxNPCType) As Boolean 'Zelda 2 Bot monster
extern RangeArrI<bool, 0, maxNPCType, false> NPCIsABot;
//Public NPCDefaultMovement(0 To maxNPCType) As Boolean 'default NPC movement
extern RangeArrI<bool, 0, maxNPCType, false> NPCDefaultMovement;
//Public NPCIsVeggie(0 To maxNPCType) As Boolean 'turnips
extern RangeArrI<bool, 0, maxNPCType, false> NPCIsVeggie;
//Public NPCNoFireBall(0 To maxNPCType) As Boolean 'not hurt by fireball
extern RangeArrI<bool, 0, maxNPCType, false> NPCNoFireBall;
//Public NPCNoIceBall(0 To maxNPCType) As Boolean 'not hurt by fireball
extern RangeArrI<bool, 0, maxNPCType, false> NPCNoIceBall;
//Public NPCNoGravity(0 To maxNPCType) As Boolean 'not affected by gravity
extern RangeArrI<bool, 0, maxNPCType, false> NPCNoGravity;
//Public NPCFrame(0 To maxNPCType) As Integer
extern RangeArrI<int, 0, maxNPCType, 0> NPCFrame;
//Public NPCFrameSpeed(0 To maxNPCType) As Integer
extern RangeArrI<int, 0, maxNPCType, 0> NPCFrameSpeed;
//Public NPCFrameStyle(0 To maxNPCType) As Integer
extern RangeArrI<int, 0, maxNPCType, 0> NPCFrameStyle;
//Public Type NPCDefaults 'Default NPC Settings
// Moved into custom.cpp as local-private
//Public BlockIsSizable(0 To maxBlockType) As Boolean 'Flags block if it is sizable
extern RangeArrI<bool, 0, maxBlockType, false> BlockIsSizable;
enum
{
SLOPE_FLOOR = 0,
SLOPE_FLOOR_LEFT = -1,
SLOPE_FLOOR_RIGHT = +1,
SLOPE_CEILING = 0,
SLOPE_CEILING_LEFT = -1,
SLOPE_CEILING_RIGHT = +1,
};
//Public BlockSlope(0 To maxBlockType) As Integer 'block is sloped on top. -1 of block has an upward slope, 1 for downward
extern RangeArrI<int, 0, maxBlockType, 0> BlockSlope;
//Public BlockSlope2(0 To maxBlockType) As Integer 'block is sloped on the bottom.
extern RangeArrI<int, 0, maxBlockType, 0> BlockSlope2;
//Public vScreenX(0 To maxPlayers) As Double 'vScreen offset
extern RangeArr<double, 0, maxPlayers> vScreenX;
//Public vScreenY(0 To maxPlayers) As Double 'vScreen offset
extern RangeArr<double, 0, maxPlayers> vScreenY;
//Public qScreenX(1 To maxPlayers) As Double 'vScreen offset adjust
extern RangeArr<double, 0, maxPlayers> qScreenX;
//Public qScreenY(1 To maxPlayers) As Double 'vScreen offset adjust
extern RangeArr<double, 0, maxPlayers> qScreenY;
//Public qScreen As Boolean 'Weather or not the screen needs adjusting
extern bool qScreen;
//Public BlockWidth(0 To maxBlockType) As Integer 'Block type width
extern RangeArrI<int, 0, maxBlockType, 0> BlockWidth;
//Public BlockHeight(0 To maxBlockType) As Integer 'Block type height
extern RangeArrI<int, 0, maxBlockType, 0> BlockHeight;
//Public BonusWidth(1 To 100) As Integer 'Bonus type width
extern RangeArrI<int, 0, maxBlockType, 0> BonusWidth;
//Public BonusHeight(1 To 100) As Integer 'Bonus type height
extern RangeArrI<int, 0, maxBlockType, 0> BonusHeight;
//Public EffectWidth(1 To maxEffectType) As Integer 'Effect width
extern RangeArrI<int, 0, maxBlockType, 0> EffectWidth;
//Public EffectHeight(1 To maxEffectType) As Integer 'Effect height
extern RangeArrI<int, 0, maxBlockType, 0> EffectHeight;
//Public Type EffectDefaults
struct EffectDefaults_t
{
// EffectWidth(1 To maxEffectType) As Integer
RangeArrI<int, 1, maxEffectType, 0> EffectWidth;
// EffectHeight(1 To maxEffectType) As Integer
RangeArrI<int, 1, maxEffectType, 0> EffectHeight;
//EXTRA: count of frames (compute from the GFX height)
RangeArrI<int, 1, maxEffectType, 0> EffectFrames;
//End Type
};
//Public EffectDefaults As EffectDefaults
extern EffectDefaults_t EffectDefaults;
//Public SceneWidth(1 To 100) As Integer 'Scene width
extern RangeArrI<int, 1, maxSceneType, 0> SceneWidth;
//Public SceneHeight(1 To 100) As Integer 'Scene height
extern RangeArrI<int, 1, maxSceneType, 0> SceneHeight;
//Public BackgroundHasNoMask(1 To maxBackgroundType) As Boolean
extern RangeArrI<bool, 1, maxBackgroundType, false> BackgroundHasNoMask;
//Public Foreground(0 To maxBackgroundType) As Boolean 'flags the background object to be drawn in front of everything else
extern RangeArrI<bool, 0, maxBackgroundType, false> Foreground;
//Public BackgroundWidth(1 To maxBackgroundType) As Integer
extern RangeArrI<int, 1, maxBackgroundType, 0> BackgroundWidth;
//Public BackgroundHeight(1 To maxBackgroundType) As Integer
extern RangeArrI<int, 1, maxBackgroundType, 0> BackgroundHeight;
//Public BackgroundFrame(1 To maxBackgroundType) As Integer
extern RangeArrI<int, 1, maxBackgroundType, 0> BackgroundFrame;
//Public BackgroundFrameCount(1 To maxBackgroundType) As Integer
extern RangeArrI<int, 1, maxBackgroundType, 0> BackgroundFrameCount;
//Public BlockFrame(1 To maxBlockType) As Integer 'What frame the block is on
extern RangeArrI<int, 1, maxBlockType, 0> BlockFrame;
//Public BlockFrame2(1 To maxBlockType) As Integer 'Counter to update the blocks frame
extern RangeArrI<int, 1, maxBlockType, 0> BlockFrame2;
//Public sBlockArray(1 To 1000) As Integer 'sizable block array
extern RangeArrI<int, 1, 1000, 0> sBlockArray;
//Public sBlockNum As Integer
extern int sBlockNum;
//Public SceneFrame(1 To maxSceneType) As Integer 'What frame the scene is on
extern RangeArrI<int, 1, maxSceneType, 0> SceneFrame;
//Public SceneFrame2(1 To maxSceneType) As Integer 'Counter to update the scene frames
extern RangeArrI<int, 1, maxSceneType, 0> SceneFrame2;
//Public SpecialFrame(100) As Integer 'misc frames for things like coins and the kurbi shoe
extern RangeArrI<int, 0, 100, 0> SpecialFrame;
//Public SpecialFrameCount(100) As Single
extern RangeArr<float, 0, 100> SpecialFrameCount;
//Public TileWidth(1 To maxTileType) As Integer
extern RangeArrI<int, 1, maxTileType, 0> TileWidth;
//Public TileHeight(1 To maxTileType) As Integer
extern RangeArrI<int, 1, maxTileType, 0> TileHeight;
//Public TileFrame(1 To maxTileType) As Integer
extern RangeArrI<int, 1, maxTileType, 0> TileFrame;
//Public TileFrame2(1 To maxTileType) As Integer
extern RangeArrI<int, 1, maxTileType, 0> TileFrame2;
//Public LevelFrame(1 To 100) As Integer 'What frame the scene is on
extern RangeArrI<int, 1, 100, 0> LevelFrame;
//Public LevelFrame2(1 To 100) As Integer 'Counter to update the scene frames
extern RangeArrI<int, 1, 100, 0> LevelFrame2;
//Public BlockHasNoMask(1 To maxBlockType) As Boolean
extern RangeArrI<bool, 1, maxBlockType, false> BlockHasNoMask;
//Public LevelHasNoMask(1 To 100) As Boolean
extern RangeArrI<bool, 1, 100, false> LevelHasNoMask;
//Public BlockOnlyHitspot1(0 To maxBlockType) As Boolean
extern RangeArrI<bool, 0, maxBlockType, false> BlockOnlyHitspot1;
//Public BlockKills(0 To maxBlockType) As Boolean 'block is lava
extern RangeArrI<bool, 0, maxBlockType, false> BlockKills;
//Public BlockKills2(0 To maxBlockType) As Boolean
extern RangeArrI<bool, 0, maxBlockType, false> BlockKills2;
//Public BlockHurts(0 To maxBlockType) As Boolean 'block hurts the player
extern RangeArrI<bool, 0, maxBlockType, false> BlockHurts;
//Public BlockPSwitch(0 To maxBlockType) As Boolean 'block is affected by the p switch
extern RangeArrI<bool, 0, maxBlockType, false> BlockPSwitch;
//Public BlockNoClipping(0 To maxBlockType) As Boolean 'player/npcs can walk throught the block
extern RangeArrI<bool, 0, maxBlockType, false> BlockNoClipping;
//Public CoinFrame(1 To 10) As Integer 'What frame the coin is on
extern RangeArrI<int, 1, 10, 0> CoinFrame;
//Public CoinFrame2(1 To 10) As Integer 'Counter to update the coin frames
extern RangeArrI<int, 1, 10, 0> CoinFrame2;
//Public EditorCursor As EditorCursor
extern EditorCursor_t EditorCursor;
//Public EditorControls As EditorControls
extern EditorControls_t EditorControls;
//Public Sound(1 To numSounds) As Integer
extern RangeArrI<int, 1, numSounds, 0> Sound;
//Public SoundPause(1 To numSounds) As Integer
extern RangeArrI<int, 1, numSounds, 0> SoundPause;
//EXTRA: Immediately quit level because of a fatal error
extern bool ErrorQuit;
//Public EndLevel As Boolean 'End the level and move to the next
extern bool EndLevel;
enum LevelMacro_t
{
LEVELMACRO_OFF = 0,
LEVELMACRO_CARD_ROULETTE_EXIT = 1,
LEVELMACRO_QUESTION_SPHERE_EXIT = 2,
LEVELMACRO_KEYHOLE_EXIT = 3,
LEVELMACRO_CRYSTAL_BALL_EXIT = 4,
LEVELMACRO_GAME_COMPLETE_EXIT = 5,
LEVELMACRO_STAR_EXIT = 6,
LEVELMACRO_GOAL_TAPE_EXIT = 7,
};
//Public LevelMacro As Integer 'Shows a level outro when beat
extern int LevelMacro;
//Public LevelMacroCounter As Integer
extern int LevelMacroCounter;
//Public numJoysticks As Integer
extern int numJoysticks;
//Public FileName As String
extern std::string FileName;
//! EXTRA: A full filename (the "FileName" is now has the "base name" sense)
extern std::string FileNameFull;
//! EXTRA: Identify that episode is an intro level
extern bool IsEpisodeIntro;
//Public Coins As Integer 'number of coins
extern int Coins;
//Public Lives As Single 'number of lives
extern float Lives;
//Public EndIntro As Boolean
extern bool EndIntro;
//Public ExitMenu As Boolean
extern bool ExitMenu;
//Public LevelSelect As Boolean 'true if game should load the world map
extern bool LevelSelect;
extern bool LevelRestartRequested;
//Public WorldPlayer(1) As WorldPlayer
extern RangeArr<WorldPlayer_t, 0, 1> WorldPlayer;
//Public LevelBeatCode As Integer ' code for the way the plauer beat the level
extern int LevelBeatCode;
//Public curWorldLevel As Integer
extern int curWorldLevel;
//Public curWorldMusic As Integer
extern int curWorldMusic;
//EXTRA: Custom world music
extern std::string curWorldMusicFile;
//Public NoTurnBack(0 To maxSections) As Boolean
extern RangeArrI<bool, 0, maxSections, false> NoTurnBack;
//Public UnderWater(0 To maxSections) As Boolean
extern RangeArrI<bool, 0, maxSections, false> UnderWater;
//Public TestLevel As Boolean
extern bool TestLevel;
//Public FullFileName As String
extern std::string FullFileName;
//Public FileNamePath As String
extern std::string FileNamePath;
//Public GameMenu As Boolean
extern bool GameMenu;
//Public WorldName As String
extern std::string WorldName;
//Public selWorld As Integer
extern int selWorld;
//Public selSave As Integer
extern int selSave;
//Public PSwitchTime As Integer
extern int PSwitchTime;
//Public PSwitchStop As Integer
extern int PSwitchStop;
//Public PSwitchPlayer As Integer
extern int PSwitchPlayer;
//Public SaveSlot(1 To 3) As Integer
extern RangeArrI<int, 1, maxSaveSlots, 0> SaveSlot;
//Public SaveStars(1 To 3) As Integer
extern RangeArrI<int, 1, maxSaveSlots, 0> SaveStars;
//Public BeltDirection As Integer 'direction of the converyer belt blocks
extern int BeltDirection;
//Public BeatTheGame As Boolean 'true if the game has been beaten
extern bool BeatTheGame;
// 'for frameskip
//Public cycleCount As Integer
//extern int cycleCount;
//Public fpsTime As Double
//extern double fpsTime;
//Public fpsCount As Double
//extern double fpsCount;
//Public FrameSkip As Boolean
extern bool FrameSkip;
//Public GoalTime As Double
//extern double GoalTime;
//Public overTime As Double
//extern double overTime;
//'------------------
//Public worldCurs As Integer
extern int worldCurs;
//Public minShow As Integer
extern int minShow;
//Public maxShow As Integer
extern int maxShow;
//Public Type Physics
struct Physics_t
{
// PlayerJumpHeight As Integer
int PlayerJumpHeight = 0;
// PlayerBlockJumpHeight As Integer
int PlayerBlockJumpHeight = 0;
// PlayerHeadJumpHeight As Integer
int PlayerHeadJumpHeight = 0;
// PlayerNPCJumpHeight As Integer
int PlayerNPCJumpHeight = 0;
// PlayerSpringJumpHeight As Integer
int PlayerSpringJumpHeight = 0;
// PlayerJumpVelocity As Single
float PlayerJumpVelocity = 0.0f;
// PlayerRunSpeed As Single
float PlayerRunSpeed = 0.0f;
// PlayerWalkSpeed As Single
float PlayerWalkSpeed = 0.0f;
// PlayerTerminalVelocity As Integer
int PlayerTerminalVelocity = 0;
// PlayerGravity As Single
float PlayerGravity = 0.0f;
// PlayerHeight(1 To numCharacters, 1 To numStates) As Integer
RangeArr<RangeArrI<int, 1, numStates, 0>, 1, numCharacters> PlayerHeight;
// PlayerDuckHeight(1 To numCharacters, 1 To numStates) As Integer
RangeArr<RangeArrI<int, 1, numStates, 0>, 1, numCharacters> PlayerDuckHeight;
// PlayerWidth(1 To numCharacters, 1 To numStates) As Integer
RangeArr<RangeArrI<int, 1, numStates, 0>, 1, numCharacters> PlayerWidth;
// PlayerGrabSpotX(1 To numCharacters, 1 To numStates) As Integer
RangeArr<RangeArrI<int, 1, numStates, 0>, 1, numCharacters> PlayerGrabSpotX;
// PlayerGrabSpotY(1 To numCharacters, 1 To numStates) As Integer
RangeArr<RangeArrI<int, 1, numStates, 0>, 1, numCharacters> PlayerGrabSpotY;
// NPCTimeOffScreen As Integer
int NPCTimeOffScreen = 0;
// NPCCanHurtWait As Integer
int NPCCanHurtWait = 0;
// NPCShellSpeed As Single
float NPCShellSpeed = 0.0f;
// NPCShellSpeedY As Single
float NPCShellSpeedY = 0.0f;
// NPCWalkingSpeed As Single
float NPCWalkingSpeed = 0.0f;
// NPCWalkingOnSpeed As Single
float NPCWalkingOnSpeed = 0.0f;
// NPCMushroomSpeed As Single
float NPCMushroomSpeed = 0.0f;
// NPCGravity As Single
float NPCGravity = 0.0f;
// NPCGravityReal As Single
float NPCGravityReal = 0.0f;
// NPCPSwitch As Integer
int NPCPSwitch = 0;
//End Type
};
//Public Type Events
//moved into "layers.h"
//Public ReturnWarp As Integer 'for when the player returns from a warp
extern int ReturnWarp;
//! EXTRA: Used to be captured into game save
extern int ReturnWarpSaved;
//Public StartWarp As Integer
extern int StartWarp;
//Public Physics As Physics
extern Physics_t Physics;
//Public MenuCursor As Integer
extern int MenuCursor;
//Public MenuMode As Integer
extern int MenuMode;
//Public MenuCursorCanMove As Boolean
extern bool MenuCursorCanMove;
//Public MenuCursorCanMove2 As Boolean 'Joystick
extern bool MenuCursorCanMove2;
//Public NextFrame As Boolean
extern bool NextFrame;
//Public StopHit As Integer
extern int StopHit;
//Public MouseRelease As Boolean
extern bool MouseRelease;
//Public TestFullscreen As Boolean
extern bool TestFullscreen;
////Public keyDownAlt As Boolean 'for alt/enter fullscreen
//extern bool keyDownAlt;
////Public keyDownEnter As Boolean
//extern bool keyDownEnter;
//Public BlocksSorted As Boolean 'if using block optimization it requires the locks to be sorted
extern bool BlocksSorted;
//Public SingleCoop As Integer 'cheat code
extern int SingleCoop;
//Public CheatString As String 'logs keys for cheats
extern std::string CheatString;
//Public GameOutro As Boolean 'true if showing credits
extern bool GameOutro;
extern bool GameOutroDoQuit;
//Public CreditChop As Single
extern float CreditChop;
//Public EndCredits As Integer
extern int EndCredits;
//Public curStars As Integer 'number of stars
extern int curStars;
//Public maxStars As Integer 'max number of stars in the game
extern int maxStars;
//'cheat codes --------------
//Public ShadowMode As Boolean 'cheat code
extern bool ShadowMode;
//Public MultiHop As Boolean
extern bool MultiHop;
//Public SuperSpeed As Boolean
extern bool SuperSpeed;
//Public WalkAnywhere As Boolean
extern bool WalkAnywhere;
//Public FlyForever As Boolean
extern bool FlyForever;
//Public FreezeNPCs As Boolean
extern bool FreezeNPCs;
//Public CaptainN As Boolean
extern bool CaptainN;
//Public FlameThrower As Boolean
extern bool FlameThrower;
//Public CoinMode As Boolean 'cheat code
extern bool CoinMode;
//Public WorldUnlock As Boolean
extern bool WorldUnlock;
//Public MaxFPS As Boolean
extern bool MaxFPS;
//Public GodMode As Boolean
extern bool GodMode;
//Public GrabAll As Boolean
extern bool GrabAll;
//Public Cheater As Boolean 'if the player is a cheater
extern bool Cheater;
//EXTRA
extern Uint32 RenderMode;
//'--------------------------------
//Public WorldCredits(1 To 5) As String
extern RangeArr<std::string, 1, maxWorldCredits> WorldCredits;
//Public Score As Long 'player's score
extern int Score;
//Public Points(1 To 13) As Integer
extern RangeArrI<int, 1, 13, 0> Points;
//Public oldJumpJoy As Integer
extern KM_Key oldJumpJoy;
//Public MaxWorldStars As Integer 'maximum number of world stars
extern int MaxWorldStars;
//Public Debugger As Boolean 'if the debugger window is open
extern bool Debugger;
//Public SavedChar(0 To 10) As Player 'Saves the Player's Status
extern RangeArr<Player_t, 0, 10> SavedChar;
extern bool LoadingInProcess;
//Public LoadCoins As Integer
extern int LoadCoins;
//Public LoadCoinsT As Single
extern float LoadCoinsT;
//'Game Graphics
//Public GFXBlockCustom(1 To maxBlockType) As Boolean
extern RangeArrI<bool, 1, maxBlockType, false> GFXBlockCustom;
//Public GFXBlock(1 To maxBlockType) As Long
//extern RangeArrI<long, 1, maxBlockType, 0> GFXBlock;
#define GFXBlock GFXBlockBMP
//Public GFXBlockMask(1 To maxBlockType) As Long
extern RangeArrI<long, 1, maxBlockType, 0> GFXBlockMask;
//Public GFXBlockBMP(1 To maxBlockType) As StdPicture
extern RangeArr<StdPicture, 1, maxBlockType> GFXBlockBMP;
//Public GFXBlockMaskBMP(1 To maxBlockType) As StdPicture
extern RangeArr<StdPicture, 1, maxBlockType> GFXBlockMaskBMP;
//Public GFXBackground2Custom(1 To numBackground2) As Boolean
extern RangeArrI<bool, 1, numBackground2, false> GFXBackground2Custom;
//Public GFXBackground2(1 To numBackground2) As Long
//extern RangeArrI<long, 1, numBackground2, 0> GFXBackground2;
#define GFXBackground2 GFXBackground2BMP
//Public GFXBackground2BMP(1 To numBackground2) As StdPicture
extern RangeArr<StdPicture, 1, numBackground2> GFXBackground2BMP;
//Public GFXBackground2Height(1 To numBackground2) As Integer
extern RangeArrI<int, 1, numBackground2, 0> GFXBackground2Height;
//Public GFXBackground2Width(1 To numBackground2) As Integer
extern RangeArrI<int, 1, numBackground2, 0> GFXBackground2Width;
//Public GFXNPCCustom(1 To maxNPCType) As Boolean
extern RangeArrI<bool, 1, maxNPCType, false> GFXNPCCustom;
//Public GFXNPC(1 To maxNPCType) As Long
//extern RangeArrI<long, 1, maxNPCType, 0> GFXNPC;
#define GFXNPC GFXNPCBMP
//Public GFXNPCMask(1 To maxNPCType) As Long
extern RangeArrI<long, 1, maxNPCType, 0> GFXNPCMask;
//Public GFXNPCBMP(1 To maxNPCType) As StdPicture
extern RangeArr<StdPicture, 0, maxNPCType> GFXNPCBMP;
//Public GFXNPCMaskBMP(1 To maxNPCType) As StdPicture
extern RangeArr<StdPicture, 0, maxNPCType> GFXNPCMaskBMP;
//Public GFXNPCHeight(1 To maxNPCType) As Integer
extern RangeArrI<int, 1, maxNPCType, 0> GFXNPCHeight;
//Public GFXNPCWidth(1 To maxNPCType) As Integer
extern RangeArrI<int, 1, maxNPCType, 0> GFXNPCWidth;
//Public GFXEffectCustom(1 To maxEffectType) As Boolean
extern RangeArrI<bool, 1, maxEffectType, false> GFXEffectCustom;
//Public GFXEffect(1 To maxEffectType) As Long
//extern RangeArrI<long, 1, maxEffectType, 0> GFXEffect;
#define GFXEffect GFXEffectBMP
//Public GFXEffectMask(1 To maxEffectType) As Long
extern RangeArrI<long, 1, maxEffectType, 0> GFXEffectMask;
//Public GFXEffectBMP(1 To maxEffectType) As StdPicture
extern RangeArr<StdPicture, 1, maxEffectType> GFXEffectBMP;
//Public GFXEffectMaskBMP(1 To maxEffectType) As StdPicture
extern RangeArr<StdPicture, 1, maxEffectType> GFXEffectMaskBMP;
//Public GFXEffectHeight(1 To maxEffectType) As Integer
extern RangeArrI<int, 1, maxEffectType, 0> GFXEffectHeight;
//Public GFXEffectWidth(1 To maxEffectType) As Integer
extern RangeArrI<int, 1, maxEffectType, 0> GFXEffectWidth;
//Public GFXBackgroundCustom(1 To maxBackgroundType) As Boolean
extern RangeArrI<bool, 1, maxBackgroundType, false> GFXBackgroundCustom;
//Public GFXBackground(1 To maxBackgroundType) As Long
//extern RangeArrI<long, 1, maxBackgroundType, 0> GFXBackground;
#define GFXBackground GFXBackgroundBMP
//Public GFXBackgroundMask(1 To maxBackgroundType) As Long
extern RangeArrI<long, 1, maxBackgroundType, 0> GFXBackgroundMask;
//Public GFXBackgroundBMP(1 To maxBackgroundType) As StdPicture
extern RangeArr<StdPicture, 1, maxBackgroundType> GFXBackgroundBMP;
//Public GFXBackgroundMaskBMP(1 To maxBackgroundType) As StdPicture
extern RangeArr<StdPicture, 1, maxBackgroundType> GFXBackgroundMaskBMP;
//Public GFXBackgroundHeight(1 To maxBackgroundType) As Integer
extern RangeArrI<int, 1, maxBackgroundType, 0> GFXBackgroundHeight;
//Public GFXBackgroundWidth(1 To maxBackgroundType) As Integer
extern RangeArrI<int, 1, maxBackgroundType, 0> GFXBackgroundWidth;
extern const char *GFXPlayerNames[numCharacters];
extern RangeArr<StdPicture, 1, 10> *GFXCharacterBMP[numCharacters];
extern RangeArrI<int, 1, 10, 0> *GFXCharacterWidth[numCharacters];
extern RangeArrI<int, 1, 10, 0> *GFXCharacterHeight[numCharacters];
extern RangeArrI<bool, 1, 10, false> *GFXCharacterCustom[numCharacters];
//Public GFXMarioCustom(1 To 10) As Boolean
extern RangeArrI<bool, 1, 10, false> GFXMarioCustom;
//Public GFXMario(1 To 10) As Long
//extern RangeArrI<long, 1, 10, 0> GFXMario;
#define GFXMario GFXMarioBMP
//Public GFXMarioMask(1 To 10) As Long
extern RangeArrI<long, 1, 10, 0> GFXMarioMask;
//Public GFXMarioBMP(1 To 10) As StdPicture
extern RangeArr<StdPicture, 1, 10> GFXMarioBMP;
//Public GFXMarioMaskBMP(1 To 10) As StdPicture
extern RangeArr<StdPicture, 1, 10> GFXMarioMaskBMP;
//Public GFXMarioHeight(1 To 10) As Integer
extern RangeArrI<int, 1, 10, 0> GFXMarioHeight;
//Public GFXMarioWidth(1 To 10) As Integer
extern RangeArrI<int, 1, 10, 0> GFXMarioWidth;
//Public GFXLuigiCustom(1 To 10) As Boolean
extern RangeArrI<bool, 1, 10, false> GFXLuigiCustom;
//Public GFXLuigi(1 To 10) As Long
//extern RangeArrI<long, 1, 10, 0> GFXLuigi;
#define GFXLuigi GFXLuigiBMP
//Public GFXLuigiMask(1 To 10) As Long
extern RangeArrI<long, 1, 10, 0> GFXLuigiMask;
//Public GFXLuigiBMP(1 To 10) As StdPicture
extern RangeArr<StdPicture, 1, 10> GFXLuigiBMP;
//Public GFXLuigiMaskBMP(1 To 10) As StdPicture
extern RangeArr<StdPicture, 1, 10> GFXLuigiMaskBMP;
//Public GFXLuigiHeight(1 To 10) As Integer
extern RangeArrI<int, 1, 10, 0> GFXLuigiHeight;
//Public GFXLuigiWidth(1 To 10) As Integer
extern RangeArrI<int, 1, 10, 0> GFXLuigiWidth;
//Public GFXPeachCustom(1 To 10) As Boolean
extern RangeArrI<bool, 1, 10, false> GFXPeachCustom;
//Public GFXPeach(1 To 10) As Long
//extern RangeArrI<long, 1, 10, 0> GFXPeach;
#define GFXPeach GFXPeachBMP
//Public GFXPeachMask(1 To 10) As Long
extern RangeArrI<long, 1, 10, 0> GFXPeachMask;
//Public GFXPeachBMP(1 To 10) As StdPicture
extern RangeArr<StdPicture, 1, 10> GFXPeachBMP;
//Public GFXPeachMaskBMP(1 To 10) As StdPicture
extern RangeArr<StdPicture, 1, 10> GFXPeachMaskBMP;
//Public GFXPeachHeight(1 To 10) As Integer
extern RangeArrI<int, 1, 10, 0> GFXPeachHeight;
//Public GFXPeachWidth(1 To 10) As Integer
extern RangeArrI<int, 1, 10, 0> GFXPeachWidth;
//Public GFXToadCustom(1 To 10) As Boolean
extern RangeArrI<bool, 1, 10, false> GFXToadCustom;
//Public GFXToad(1 To 10) As Long
//extern RangeArrI<long, 1, 10, 0> GFXToad;
#define GFXToad GFXToadBMP
//Public GFXToadMask(1 To 10) As Long
extern RangeArrI<long, 1, 10, 0> GFXToadMask;
//Public GFXToadBMP(1 To 10) As StdPicture
extern RangeArr<StdPicture, 1, 10> GFXToadBMP;
//Public GFXToadMaskBMP(1 To 10) As StdPicture
extern RangeArr<StdPicture, 1, 10> GFXToadMaskBMP;
//Public GFXToadHeight(1 To 10) As Integer
extern RangeArrI<int, 1, 10, 0> GFXToadHeight;
//Public GFXToadWidth(1 To 10) As Integer
extern RangeArrI<int, 1, 10, 0> GFXToadWidth;
//Public GFXLinkCustom(1 To 10) As Boolean
extern RangeArrI<bool, 1, 10, false> GFXLinkCustom;
//Public GFXLink(1 To 10) As Long
//extern RangeArrI<long, 1, 10, 0> GFXLink;
#define GFXLink GFXLinkBMP
//Public GFXLinkMask(1 To 10) As Long
extern RangeArrI<long, 1, 10, 0> GFXLinkMask;
//Public GFXLinkBMP(1 To 10) As StdPicture
extern RangeArr<StdPicture, 1, 10> GFXLinkBMP;
//Public GFXLinkMaskBMP(1 To 10) As StdPicture
extern RangeArr<StdPicture, 1, 10> GFXLinkMaskBMP;
//Public GFXLinkHeight(1 To 10) As Integer
extern RangeArrI<int, 1, 10, 0> GFXLinkHeight;
//Public GFXLinkWidth(1 To 10) As Integer
extern RangeArrI<int, 1, 10, 0> GFXLinkWidth;
//Public GFXYoshiBCustom(1 To 10) As Boolean
extern RangeArrI<bool, 1, maxYoshiGfx, false> GFXYoshiBCustom;
//Public GFXYoshiB(1 To 10) As Long
//extern RangeArrI<long, 1, maxYoshiGfx, 0> GFXYoshiB;
#define GFXYoshiB GFXYoshiBBMP
//Public GFXYoshiBMask(1 To 10) As Long
extern RangeArrI<long, 1, maxYoshiGfx, 0> GFXYoshiBMask;
//Public GFXYoshiBBMP(1 To 10) As StdPicture
extern RangeArr<StdPicture, 1, maxYoshiGfx> GFXYoshiBBMP;
//Public GFXYoshiBMaskBMP(1 To 10) As StdPicture
extern RangeArr<StdPicture, 1, maxYoshiGfx> GFXYoshiBMaskBMP;
//Public GFXYoshiTCustom(1 To 10) As Boolean
extern RangeArrI<bool, 1, maxYoshiGfx, false> GFXYoshiTCustom;
//Public GFXYoshiT(1 To 10) As Long
//extern RangeArrI<long, 1, maxYoshiGfx, 0> GFXYoshiT;
#define GFXYoshiT GFXYoshiTBMP
//Public GFXYoshiTMask(1 To 10) As Long
extern RangeArrI<long, 1, maxYoshiGfx, 0> GFXYoshiTMask;
//Public GFXYoshiTBMP(1 To 10) As StdPicture
extern RangeArr<StdPicture, 1, maxYoshiGfx> GFXYoshiTBMP;
//Public GFXYoshiTMaskBMP(1 To 10) As StdPicture
extern RangeArr<StdPicture, 1, maxYoshiGfx> GFXYoshiTMaskBMP;
//'World Map Graphics
//Public GFXTileCustom(1 To maxTileType) As Long
extern RangeArrI<bool, 1, maxTileType, false> GFXTileCustom;
//Public GFXTile(1 To maxTileType) As Long
//extern RangeArrI<long, 1, maxTileType, 0> GFXTile;
#define GFXTile GFXTileBMP
//Public GFXTileBMP(1 To maxTileType) As StdPicture
extern RangeArr<StdPicture, 1, maxTileType> GFXTileBMP;
//Public GFXTileHeight(1 To maxTileType) As Integer
extern RangeArrI<int, 1, maxTileType, 0> GFXTileHeight;
//Public GFXTileWidth(1 To maxTileType) As Integer
extern RangeArrI<int, 1, maxTileType, 0> GFXTileWidth;
//Public GFXLevelCustom(0 To maxLevelType) As Long
extern RangeArrI<bool, 0, maxLevelType, false> GFXLevelCustom;
//Public GFXLevel(0 To maxLevelType) As Long
//extern RangeArrI<long, 0, maxLevelType, 0> GFXLevel;
#define GFXLevel GFXLevelBMP
//Public GFXLevelMask(0 To maxLevelType) As Long
extern RangeArrI<long, 0, maxLevelType, 0> GFXLevelMask;
//Public GFXLevelBMP(0 To maxLevelType) As StdPicture
extern RangeArr<StdPicture, 0, maxLevelType> GFXLevelBMP;
//Public GFXLevelMaskBMP(0 To maxLevelType) As StdPicture
extern RangeArr<StdPicture, 0, maxLevelType> GFXLevelMaskBMP;
//Public GFXLevelHeight(0 To maxLevelType) As Integer
extern RangeArrI<int, 0, maxLevelType, 0> GFXLevelHeight;
//Public GFXLevelWidth(0 To maxLevelType) As Integer
extern RangeArrI<int, 0, maxLevelType, 0> GFXLevelWidth;
//Public GFXLevelBig(0 To maxLevelType) As Boolean
extern RangeArrI<bool, 0, maxLevelType, false> GFXLevelBig;
//Public GFXSceneCustom(1 To maxSceneType) As Long
extern RangeArrI<bool, 1, maxSceneType, false> GFXSceneCustom;
//Public GFXScene(1 To maxSceneType) As Long
//extern RangeArrI<long, 1, maxSceneType, 0> GFXScene;
#define GFXScene GFXSceneBMP
//Public GFXSceneMask(1 To maxSceneType) As Long
extern RangeArrI<long, 1, maxSceneType, 0> GFXSceneMask;
//Public GFXSceneBMP(1 To maxSceneType) As StdPicture
extern RangeArr<StdPicture, 1, maxSceneType> GFXSceneBMP;
//Public GFXSceneMaskBMP(1 To maxSceneType) As StdPicture
extern RangeArr<StdPicture, 1, maxSceneType> GFXSceneMaskBMP;
//Public GFXSceneHeight(1 To maxSceneType) As Integer
extern RangeArrI<int, 1, maxSceneType, 0> GFXSceneHeight;
//Public GFXSceneWidth(1 To maxSceneType) As Integer
extern RangeArrI<int, 1, maxSceneType, 0> GFXSceneWidth;
//Public GFXPathCustom(1 To maxPathType) As Long
extern RangeArrI<bool, 1, maxPathType, false> GFXPathCustom;
//Public GFXPath(1 To maxPathType) As Long
//extern RangeArrI<long, 1, maxPathType, 0> GFXPath;
#define GFXPath GFXPathBMP
//Public GFXPathMask(1 To maxPathType) As Long
extern RangeArrI<long, 1, maxPathType, 0> GFXPathMask;
//Public GFXPathBMP(1 To maxPathType) As StdPicture
extern RangeArr<StdPicture, 1, maxPathType> GFXPathBMP;
//Public GFXPathMaskBMP(1 To maxPathType) As StdPicture
extern RangeArr<StdPicture, 1, maxPathType> GFXPathMaskBMP;
//Public GFXPathHeight(1 To maxPathType) As Integer
extern RangeArrI<int, 1, maxPathType, 0> GFXPathHeight;
//Public GFXPathWidth(1 To maxPathType) As Integer
extern RangeArrI<int, 1, maxPathType, 0> GFXPathWidth;
//Public GFXPlayerCustom(1 To numCharacters) As Long
extern RangeArrI<bool, 1, numCharacters, false> GFXPlayerCustom;
//Public GFXPlayer(1 To numCharacters) As Long
//extern RangeArrI<long, 1, numCharacters, 0> GFXPlayer;
#define GFXPlayer GFXPlayerBMP
//Public GFXPlayerMask(1 To numCharacters) As Long
extern RangeArrI<long, 1, numCharacters, 0> GFXPlayerMask;
//Public GFXPlayerBMP(1 To numCharacters) As StdPicture
extern RangeArr<StdPicture, 1, numCharacters> GFXPlayerBMP;
//Public GFXPlayerMaskBMP(1 To numCharacters) As StdPicture
extern RangeArr<StdPicture, 1, numCharacters> GFXPlayerMaskBMP;
//Public GFXPlayerHeight(1 To numCharacters) As Integer
extern RangeArrI<int, 1, numCharacters, 0> GFXPlayerHeight;
//Public GFXPlayerWidth(1 To numCharacters) As Integer
extern RangeArrI<int, 1, numCharacters, 0> GFXPlayerWidth;
//Public PlayerCharacter As Integer
extern int PlayerCharacter;
//Public PlayerCharacter2 As Integer
extern int PlayerCharacter2;
//Public MenuMouseX As Double
extern double MenuMouseX;
//Public MenuMouseY As Double
extern double MenuMouseY;
//Public MenuMouseDown As Boolean
extern bool MenuMouseDown;
//Public MenuMouseBack As Boolean
extern bool MenuMouseBack;
//Public MenuMouseRelease As Boolean
extern bool MenuMouseRelease;
//Public MenuMouseMove As Boolean
extern bool MenuMouseMove;
//Public MenuMouseClick As Boolean
extern bool MenuMouseClick;
//' event stuff
// Moved into "layers.h"
//Public ForcedControls As Boolean
extern bool ForcedControls;
//Public ForcedControl As Controls
extern Controls_t ForcedControl;
//Public SyncCount As Integer
extern int SyncCount;
//Public noUpdate As Boolean
extern bool noUpdate;
//Public gameTime As Double
//extern double gameTime;
//Public noSound As Boolean
extern bool noSound;
extern bool neverPause;
//Public tempTime As Double
//extern double tempTime;
//Dim ScrollDelay As Integer [in main.cpp]
//'battlemode stuff
//Public BattleMode As Boolean
extern bool BattleMode;
//Public BattleWinner As Integer
extern int BattleWinner;
//Public BattleLives(1 To maxPlayers) As Integer
extern RangeArrI<int, 1, maxPlayers, 0> BattleLives;
//Public BattleIntro As Integer
extern int BattleIntro;
//Public BattleOutro As Integer
extern int BattleOutro;
//Public LevelName As String
extern std::string LevelName;
//Public Const curRelease As Integer = 64
const int curRelease = 64;
#endif // GLOBALS_H
| 38.337232 | 289 | 0.744534 | [
"object",
"vector"
] |
8180e8e7b3d7400d4cbbdcc58bd9788870c8b01d | 597 | h | C | LIMoSim/mobility/routing/routingnode.h | inet-framework/LIMoSim | d9bdcefe82d41d4c8fd665a268843763fce59363 | [
"MIT"
] | 7 | 2017-07-17T07:13:03.000Z | 2021-10-12T08:39:17.000Z | LIMoSim/mobility/routing/routingnode.h | tudo-cni/LIMoSim | f0e4c8d964da18dffecea040775f07da3f5a5d46 | [
"MIT"
] | 1 | 2018-03-08T10:28:01.000Z | 2018-03-08T10:28:01.000Z | LIMoSim/mobility/routing/routingnode.h | tudo-cni/LIMoSim | f0e4c8d964da18dffecea040775f07da3f5a5d46 | [
"MIT"
] | 7 | 2017-09-13T09:05:20.000Z | 2022-01-04T17:20:20.000Z | #ifndef LIMOSIM_ROUTINGNODE_H
#define LIMOSIM_ROUTINGNODE_H
#include <map>
#include <string>
#include <vector>
#include "LIMoSim/map/node.h"
namespace LIMoSim
{
class RoutingNode
{
public:
RoutingNode(Node *_node = 0);
void addConnection(RoutingNode *_destination, double _cost);
bool hasConnection(RoutingNode *_destination);
double getCost(RoutingNode *_destination);
std::vector<RoutingNode*> getConnections();
// property accessors
Node* getNode();
public:
Node *p_node;
std::map<RoutingNode*, double> m_costs;
};
}
#endif // LIMOSIM_ROUTINGNODE_H
| 17.558824 | 64 | 0.723618 | [
"vector"
] |
818d1f027c38e79e7016a5d6af94b22ed7bc2a10 | 18,200 | c | C | sys/kern/exec_macho.c | TheSledgeHammer/2.11BSD_X44 | 4d931b88699e1409c35587915608dba6a461d020 | [
"BSD-3-Clause"
] | 3 | 2021-05-04T17:09:06.000Z | 2021-10-04T07:19:26.000Z | sys/kern/exec_macho.c | TheSledgeHammer/2.11BSD_X44 | 4d931b88699e1409c35587915608dba6a461d020 | [
"BSD-3-Clause"
] | null | null | null | sys/kern/exec_macho.c | TheSledgeHammer/2.11BSD_X44 | 4d931b88699e1409c35587915608dba6a461d020 | [
"BSD-3-Clause"
] | null | null | null | /* $NetBSD: exec_macho.c,v 1.38 2006/07/23 22:06:10 ad Exp $ */
/*-
* Copyright (c) 2001 The NetBSD Foundation, Inc.
* All rights reserved.
*
* This code is derived from software contributed to The NetBSD Foundation
* by Christos Zoulas.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the NetBSD
* Foundation, Inc. and its contributors.
* 4. Neither the name of The NetBSD Foundation 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 NETBSD FOUNDATION, 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 <sys/cdefs.h>
#include <sys/param.h>
#include <sys/proc.h>
#include <sys/malloc.h>
#include <sys/namei.h>
#include <sys/vnode.h>
#include <sys/exec.h>
#include <sys/exec_linker.h>
#include <sys/exec_macho.h>
#include <sys/syscall.h>
#include <sys/signalvar.h>
#include <sys/resourcevar.h>
#include <sys/mount.h>
#include <sys/stat.h>
#include <vm/include/vm.h>
#ifdef DEBUG_MACHO
static void
exec_macho_print_segment_command(struct exec_macho_segment_command *ls)
{
printf("ls.cmd 0x%lx\n", ls->cmd);
printf("ls.cmdsize 0x%ld\n", ls->cmdsize);
printf("ls.segname %s\n", ls->segname);
printf("ls.vmaddr 0x%lx\n", ls->vmaddr);
printf("ls.vmsize %ld\n", ls->vmsize);
printf("ls.fileoff 0x%lx\n", ls->fileoff);
printf("ls.filesize %ld\n", ls->filesize);
printf("ls.maxprot 0x%x\n", ls->maxprot);
printf("ls.initprot 0x%x\n", ls->initprot);
printf("ls.nsects %ld\n", ls->nsects);
printf("ls.flags 0x%lx\n", ls->flags);
}
static void
exec_macho_print_fat_header(struct exec_macho_fat_header *fat)
{
printf("fat.magic 0x%x\n", be32toh(fat->magic));
printf("fat.nfat_arch %d\n", be32toh(fat->nfat_arch));
}
static void
exec_macho_print_fat_arch(struct exec_macho_fat_arch *arch)
{
printf("arch.cputype %x\n", be32toh(arch->cputype));
printf("arch.cpusubtype %d\n", be32toh(arch->cpusubtype));
printf("arch.offset 0x%x\n", (int32_t)be32toh(arch->offset));
printf("arch.size %d\n", (int32_t)be32toh(arch->size));
printf("arch.align 0x%x\n", (int32_t)be32toh(arch->align));
}
static void
exec_macho_print_object_header(struct exec_macho_object_header *hdr)
{
printf("hdr.magic 0x%lx\n", hdr->magic);
printf("hdr.cputype %x\n", hdr->cputype);
printf("hdr.cpusubtype %d\n", hdr->cpusubtype);
printf("hdr.filetype 0x%lx\n", hdr->filetype);
printf("hdr.ncmds %ld\n", hdr->ncmds);
printf("hdr.sizeofcmds %ld\n", hdr->sizeofcmds);
printf("hdr.flags 0x%lx\n", hdr->flags);
}
static void
exec_macho_print_load_command(struct exec_macho_load_command *lc)
{
printf("lc.cmd %lx\n", lc->cmd);
printf("lc.cmdsize %ld\n", lc->cmdsize);
}
static void
exec_macho_print_dylinker_command(struct exec_macho_dylinker_command *dy)
{
printf("dy.cmd %lx\n", dy->cmd);
printf("dy.cmdsize %ld\n", dy->cmdsize);
printf("dy.name.offset 0x%lx\n", dy->name.offset);
printf("dy.name %s\n", ((char *)dy) + dy->name.offset);
}
static void
exec_macho_print_dylib_command(struct exec_macho_dylib_command *dy)
{
printf("dy.cmd %lx\n", dy->cmd);
printf("dy.cmdsize %ld\n", dy->cmdsize);
printf("dy.dylib.name.offset 0x%lx\n", dy->dylib.name.offset);
printf("dy.dylib.name %s\n", ((char *)dy) + dy->dylib.name.offset);
printf("dy.dylib.timestamp %ld\n", dy->dylib.timestamp);
printf("dy.dylib.current_version %ld\n", dy->dylib.current_version);
printf("dy.dylib.compatibility_version %ld\n",
dy->dylib.compatibility_version);
}
static void
exec_macho_print_thread_command(struct exec_macho_thread_command *th)
{
printf("th.cmd %lx\n", th->cmd);
printf("th.cmdsize %ld\n", th->cmdsize);
printf("th.flavor %ld\n", th->flavor);
printf("th.count %ld\n", th->count);
}
#endif /* DEBUG_MACHO */
static int
exec_macho_load_segment(elp, vp, foff, ls, type)
struct exec_linker *elp;
struct vnode *vp;
u_long foff;
struct exec_macho_segment_command *ls;
int type;
{
int flags;
struct exec_macho_emul_arg *emea;
u_long addr = trunc_page(ls->vmaddr), size = round_page(ls->filesize);
emea = (struct exec_macho_emul_arg *)elp->el_emul_arg;
flags = VMCMD_BASE;
#ifdef DEBUG_MACHO
exec_macho_print_segment_command(ls);
#endif
if (strcmp(ls->segname, "__PAGEZERO") == 0)
return 0;
if (strcmp(ls->segname, "__TEXT") != 0 &&
strcmp(ls->segname, "__DATA") != 0 &&
strcmp(ls->segname, "__LOCK") != 0 &&
strcmp(ls->segname, "__OBJC") != 0 &&
strcmp(ls->segname, "__CGSERVER") != 0 &&
strcmp(ls->segname, "__IMAGE") != 0 &&
strcmp(ls->segname, "__LINKEDIT") != 0) {
DPRINTF(("Unknown exec_macho segment %s\n", ls->segname));
return ENOEXEC;
}
if (type == MACHO_MOH_EXECUTE) {
if (strcmp(ls->segname, "__TEXT") == 0) {
elp->el_taddr = addr;
elp->el_tsize = round_page(ls->vmsize);
emea->macho_hdr =
(struct exec_macho_object_header *)addr;
}
if ((strcmp(ls->segname, "__DATA") == 0) ||
(strcmp(ls->segname, "__OBJC") == 0) ||
(strcmp(ls->segname, "__IMAGE") == 0) ||
(strcmp(ls->segname, "__CGSERVER") == 0)) {
elp->el_daddr = addr;
elp->el_dsize = round_page(ls->vmsize);
}
}
/*
* Some libraries do not have a load base address. The Darwin
* kernel seems to skip them, and dyld will do the job.
*/
if (addr == 0)
return ENOMEM;
if (ls->filesize > 0) {
NEW_VMCMD2(&elp->el_vmcmds, vmcmd_map_pagedvn, size,
addr, vp, (off_t)(ls->fileoff + foff),
ls->initprot, flags);
DPRINTF(("map(0x%lx, 0x%lx, %o, fd@ 0x%lx)\n",
addr, size, ls->initprot,
ls->fileoff + foff));
}
if (ls->vmsize > size) {
addr += size;
size = round_page(ls->vmsize - size);
NEW_VMCMD2(&elp->el_vmcmds, vmcmd_map_zero, size,
addr, vp, (off_t)(ls->fileoff + foff),
ls->initprot, flags);
DPRINTF(("mmap(0x%lx, 0x%lx, %o, zero)\n",
ls->vmaddr + ls->filesize, ls->vmsize - ls->filesize,
ls->initprot));
}
return 0;
}
static int
exec_macho_load_dylinker(elp, dy, entry, depth)
struct exec_package *elp;
struct exec_macho_dylib_command *dy;
u_long *entry;
int depth;
{
struct exec_macho_emul_arg *emea;
const char *name = ((const char *)dy) + dy->name.offset;
char path[MAXPATHLEN];
int error;
#ifdef DEBUG_MACHO
exec_macho_print_dylinker_command(dy);
#endif
emea = (struct exec_macho_emul_arg *)elp->el_emul_arg;
(void)snprintf(path, sizeof(path), "%s%s", emea->path, name);
DPRINTF(("loading linker %s\n", path));
if ((error = exec_macho_load_file(elp, path, entry,
MACHO_MOH_DYLINKER, 1, depth)) != 0)
return error;
return 0;
}
static int
exec_macho_load_dylib(elp, dy, depth)
struct exec_package *elp;
struct exec_macho_dylib_command *dy;
int depth;
{
struct exec_macho_emul_arg *emea;
const char *name = ((const char *)dy) + dy->dylib.name.offset;
char path[MAXPATHLEN];
int error;
u_long entry;
#ifdef DEBUG_MACHO
exec_macho_print_dylib_command(dy);
#endif
emea = (struct exec_macho_emul_arg *)elp->el_emul_arg;
(void)snprintf(path, sizeof(path), "%s%s", emea->path, name);
DPRINTF(("loading library %s\n", path));
if ((error = exec_macho_load_file(elp, path, &entry,
MACHO_MOH_DYLIB, 0, depth)) != 0)
return error;
return 0;
}
static u_long
exec_macho_load_thread(struct exec_macho_thread_command *th)
{
#ifdef DEBUG_MACHO
exec_macho_print_thread_command(th);
#endif
return exec_macho_thread_entry(th);
}
/*
* exec_macho_load_file(): Load a macho-binary. This is used
* for the dynamic linker and library recursive loading.
*/
static int
exec_macho_load_file(elp, path, entry, type, recursive, depth)
struct exec_linker *elp;
const char *path;
u_long *entry;
int type, recursive, depth;
{
struct proc *p = elp->el_proc;
int error;
struct nameidata nd;
struct vnode *vp;
struct vattr attr;
struct exec_macho_fat_header fat;
/*
* Check for excessive rercursive loading
*/
if (depth++ > 6)
return E2BIG;
/*
* 1. open file
* 2. read filehdr
* 3. map text, data, and bss out of it using VM_*
*/
NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, path, p);
if ((error = namei(&nd)) != 0)
return error;
vp = nd.ni_vp;
/*
* Similarly, if it's not marked as executable, or it's not a regular
* file, we don't allow it to be used.
*/
if (vp->v_type != VREG) {
error = EACCES;
goto badunlock;
}
error = vn_marktext(vp);
if (error)
return (error);
if ((error = VOP_ACCESS(vp, VEXEC, p->p_cred, p)) != 0)
goto badunlock;
/* get attributes */
if ((error = VOP_GETATTR(vp, &attr,p->p_cred, p)) != 0)
goto badunlock;
#ifdef notyet /* XXX cgd 960926 */
XXX cgd 960926: (maybe) VOP_OPEN it (and VOP_CLOSE in copyargs?)
#endif
VOP_UNLOCK(vp, 0, p);
if ((error = exec_read_from(p, vp, 0, &fat, sizeof(fat))) != 0)
goto bad;
if ((error = exec_macho_load_vnode(elp, vp, &fat, entry, type, recursive, depth)) != 0)
goto bad;
vrele(vp);
return 0;
badunlock:
VOP_UNLOCK(vp, 0, p);
bad:
#ifdef notyet /* XXX cgd 960926 */
(maybe) VOP_CLOSE it
#endif
vrele(vp);
return error;
}
/*
* exec_macho_load_vnode(): Map a file from the given vnode.
* The fat signature is checked,
* and it will return the address of the entry point in entry.
* The type determines what we are loading, a dynamic linker,
* a dynamic library, or a binary. We use that to guess at
* the entry point.
*/
static int
exec_macho_load_vnode(elp, vp, fat, entry, type, recursive, depth)
struct exec_linker *elp;
struct vnode *vp;
struct exec_macho_fat_header *fat;
u_long *entry;
int type, recursive, depth;
{
struct proc *p = elp->el_proc;
u_long aoffs, offs;
struct exec_macho_fat_arch arch;
struct exec_macho_object_header hdr;
struct exec_macho_load_command lc;
struct exec_macho_emul_arg *emea;
int error = ENOEXEC, i;
size_t size;
void *bf = &lc;
uint32_t *sc = NULL;
#ifdef DEBUG_MACHO
exec_macho_print_fat_header(fat);
#endif
switch (fat->magic) {
case MACHO_FAT_MAGIC:
for (i = 0; i < be32toh(fat->nfat_arch); i++, arch) {
if ((error = exec_read_from(p, vp, sizeof(*fat) +
sizeof(arch) * i, &arch, sizeof(arch))) != 0)
goto bad;
#ifdef DEBUG_MACHO
exec_macho_print_fat_arch(&arch);
#endif
for (sc = exec_macho_supported_cpu; *sc; sc++)
if (*sc == be32toh(arch.cputype))
break;
if (sc != NULL)
break;
}
if (sc == NULL || *sc == 0) {
DPRINTF(("CPU %d not supported by this binary",
be32toh(arch.cputype)));
goto bad;
}
break;
case MACHO_MOH_MAGIC:
/*
* This is not a FAT Mach-O binary, the file starts
* with the object header.
*/
arch.offset = 0;
break;
default:
DPRINTF(("bad exec_macho magic %x\n", fat->magic));
goto bad;
break;
}
if ((error = exec_read_from(p, vp, be32toh(arch.offset), &hdr,
sizeof(hdr))) != 0)
goto bad;
if (hdr.magic != MACHO_MOH_MAGIC) {
DPRINTF(("bad exec_macho header magic %lx\n", hdr.magic));
goto bad;
}
#ifdef DEBUG_MACHO
exec_macho_print_object_header(&hdr);
#endif
switch (hdr.filetype) {
case MACHO_MOH_PRELOAD:
case MACHO_MOH_EXECUTE:
case MACHO_MOH_DYLINKER:
case MACHO_MOH_DYLIB:
case MACHO_MOH_BUNDLE:
break;
default:
DPRINTF(("Unsupported exec_macho filetype 0x%lx\n",
hdr.filetype));
goto bad;
}
aoffs = be32toh(arch.offset);
offs = aoffs + sizeof(hdr);
size = sizeof(lc);
for (i = 0; i < hdr.ncmds; i++) {
if ((error = exec_read_from(p, vp, offs, &lc, sizeof(lc))) != 0)
goto bad;
#ifdef DEBUG_MACHO
exec_macho_print_load_command(&lc);
#endif
if (size < lc.cmdsize) {
if (lc.cmdsize > 4096) {
DPRINTF(("Bad command size %ld\n", lc.cmdsize));
goto bad;
}
if (bf != &lc)
free(bf, M_TEMP);
bf = malloc(size = lc.cmdsize, M_TEMP, M_WAITOK);
}
if ((error = exec_read_from(p, vp, offs, bf, lc.cmdsize)) != 0)
goto bad;
switch (lc.cmd) {
case MACHO_LC_SEGMENT:
error = exec_macho_load_segment(elp, vp, aoffs,
(struct exec_macho_segment_command *)bf, type);
switch(error) {
case ENOMEM: /* Just skip, dyld will load it */
DPRINTF(("load segment failed, skipping\n"));
i = hdr.ncmds;
break;
case 0: /* No error, carry on loading file */
break;
default: /* Abort file load */
DPRINTF(("load segment failed, aborting\n"));
goto bad;
break;
}
break;
case MACHO_LC_LOAD_DYLINKER:
if ((error = exec_macho_load_dylinker(elp,
(struct exec_macho_dylinker_command *)bf,
entry, depth)) != 0) {
DPRINTF(("load linker failed\n"));
goto bad;
}
emea = (struct exec_macho_emul_arg *)elp->el_emul_arg;
emea->dynamic = 1;
break;
case MACHO_LC_LOAD_DYLIB:
/*
* We should only load libraries required by the
* binary we want to load, not libraries required
* by theses libraries.
*/
if (recursive == 0)
break;
if ((error = exec_macho_load_dylib(elp,
(struct exec_macho_dylib_command *)bf,
depth)) != 0) {
DPRINTF(("load dylib failed\n"));
goto bad;
}
break;
case MACHO_LC_THREAD:
case MACHO_LC_UNIXTHREAD:
if (type == MACHO_MOH_DYLINKER || *entry == 0) {
*entry = exec_macho_load_thread(
(struct exec_macho_thread_command *)bf);
} else {
(void)exec_macho_load_thread(
(struct exec_macho_thread_command *)bf);
}
break;
case MACHO_LC_ID_DYLINKER:
case MACHO_LC_ID_DYLIB:
case MACHO_LC_SYMTAB:
case MACHO_LC_DYSYMTAB:
break;
default:
DPRINTF(("Unhandled exec_macho command 0x%lx\n",
lc.cmd));
break;
}
offs += lc.cmdsize;
}
error = 0;
bad:
if (bf != &lc)
free(bf, M_TEMP);
return error;
}
/*
* exec_macho_linker(): Prepare an Mach-O binary's exec package
*
* First, set of the various offsets/lengths in the exec package.
*
* Then, mark the text image busy (so it can be demand paged) or error
* out if this is not possible. Finally, set up vmcmds for the
* text, data, bss, and stack segments.
*/
int
exec_macho_linker(elp)
struct exec_linker *elp;
{
struct proc *p = elp->el_proc;
struct exec_macho_fat_header *fat = elp->el_image_hdr;
struct exec_macho_emul_arg *emea;
int error;
if (elp->el_hdrvalid < sizeof(*fat))
return ENOEXEC;
/*
* Check mount point. Though we're not trying to exec this binary,
* we will be executing code from it, so if the mount point
* disallows execution or set-id-ness, we punt or kill the set-id.
*/
if (elp->el_vnodep->v_mount->mnt_flag & MNT_NOEXEC)
return EACCES;
if (elp->el_vnodep->v_mount->mnt_flag & MNT_NOSUID)
elp->el_attr->va_mode &= ~(S_ISUID | S_ISGID);
error = vn_marktext(elp->el_vnodep);
if (error)
return (error);
emea = malloc(sizeof(struct exec_macho_emul_arg), M_EXEC, M_WAITOK);
elp->el_emul_arg = (void *)emea;
emea->dynamic = 0;
if (!exec_macho_probe(elp, &emea->path))
emea->path = "/";
else {
if ((error = exec_macho_probe(elp, &emea->path)) != 0)
goto bad2;
}
/*
* Make sure the underlying functions will not get
* a random value here. 0 means that no entry point
* has been found yet.
*/
elp->el_entry = 0;
if ((error = exec_macho_load_vnode(elp, elp->el_vnodep, fat,
&elp->el_entry, MACHO_MOH_EXECUTE, 1, 0)) != 0)
goto bad;
/*
* stash a copy of the program name in epp->ep_emul_arg because
* we will need it later.
*/
if ((error = copyinstr(elp->el_name, emea->filename, MAXPATHLEN, NULL)) != 0) {
DPRINTF(("Copyinstr %p failed\n", elp->el_name));
goto bad;
}
return (*elp->el_esch->ex_setup_stack)(elp);
bad:
kill_vmcmds(&elp->el_vmcmds);
bad2:
free(emea, M_EXEC);
return error;
}
int
exec_macho_probe(struct exec_linker *elp, const char **path)
{
struct emul *emul = elp->el_esch->ex_emul;
*path = emul->e_path;
return (0);
}
int
macho_copyargs(struct exec_linker *elp, struct ps_strings *arginfo, char **stackp, void *argp)
{
struct exec_macho_emul_arg *emea;
struct exec_macho_object_header *macho_hdr;
size_t len;
size_t zero = 0;
int error;
*stackp = (char *)(((unsigned long)*stackp - 1) & ~0xfUL);
emea = (struct exec_macho_emul_arg*) elp->el_emul_arg;
macho_hdr = (struct exec_macho_object_header*) emea->macho_hdr;
if ((error = copyout(&macho_hdr, *stackp, sizeof(macho_hdr))) != 0)
return error;
*stackp += sizeof(macho_hdr);
if ((error = copyargs(elp, arginfo, stackp, argp)) != 0) {
DPRINTF(("mach: copyargs failed\n"));
return error;
}
if ((error = copyout(&zero, *stackp, sizeof(zero))) != 0)
return error;
*stackp += sizeof(zero);
if ((error = copyoutstr(emea->filename, *stackp, MAXPATHLEN, &len)) != 0) {
DPRINTF(("mach: copyout path failed\n"));
return error;
}
*stackp += len + 1;
/* We don't need this anymore */
free(elp->el_emul_arg, M_TEMP);
elp->el_emul_arg = NULL;
len = len % sizeof(zero);
if (len) {
if ((error = copyout(&zero, *stackp, len)) != 0)
return error;
*stackp += len;
}
if ((error = copyout(&zero, *stackp, sizeof(zero))) != 0)
return error;
*stackp += sizeof(zero);
return 0;
}
| 26.804124 | 94 | 0.679231 | [
"object"
] |
819f87db9892e008b7fb94b3c95da08f576dbeb6 | 271 | h | C | include/geo/polygon.h | motis-project/geo | 669e6b5b15782ef547507183db2fc8f4ab005a1b | [
"MIT"
] | null | null | null | include/geo/polygon.h | motis-project/geo | 669e6b5b15782ef547507183db2fc8f4ab005a1b | [
"MIT"
] | null | null | null | include/geo/polygon.h | motis-project/geo | 669e6b5b15782ef547507183db2fc8f4ab005a1b | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include <vector>
#include "geo/latlng.h"
namespace geo {
using simple_polygon = std::vector<latlng>;
simple_polygon read_poly_file(std::string const& filename);
bool within(latlng const&, simple_polygon const&);
} // namespace geo
| 15.941176 | 59 | 0.741697 | [
"vector"
] |
81a1e94e30b3faff09debff90807fa9176883c2d | 7,564 | h | C | tests/UnitTests/ICoreStub.h | cycere/quid | 889b5bd36339d4e632c07a037db9ba38bf89ea30 | [
"MIT"
] | 1 | 2020-11-19T19:40:05.000Z | 2020-11-19T19:40:05.000Z | tests/UnitTests/ICoreStub.h | cycere/quid | 889b5bd36339d4e632c07a037db9ba38bf89ea30 | [
"MIT"
] | null | null | null | tests/UnitTests/ICoreStub.h | cycere/quid | 889b5bd36339d4e632c07a037db9ba38bf89ea30 | [
"MIT"
] | null | null | null | // Copyright (c) 2011-2016 The Cryptonote developers
// Copyright (c) 2017-2021 The Cycere developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#pragma once
#include <cstdint>
#include <unordered_map>
#include "QuidCore/QuidBasic.h"
#include "QuidCore/ICore.h"
#include "QuidCore/ICoreObserver.h"
#include "QuidProtocol/QuidProtocolDefinitions.h"
#include "Rpc/CoreRpcServerCommandsDefinitions.h"
class ICoreStub: public Quid::ICore {
public:
ICoreStub();
ICoreStub(const Quid::Block& genesisBlock);
virtual bool addObserver(Quid::ICoreObserver* observer) override;
virtual bool removeObserver(Quid::ICoreObserver* observer) override;
virtual void get_blockchain_top(uint32_t& height, Crypto::Hash& top_id) override;
virtual std::vector<Crypto::Hash> findBlockchainSupplement(const std::vector<Crypto::Hash>& remoteBlockIds, size_t maxCount,
uint32_t& totalBlockCount, uint32_t& startBlockIndex) override;
virtual bool get_random_outs_for_amounts(const Quid::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_request& req,
Quid::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_response& res) override;
virtual bool get_tx_outputs_gindexs(const Crypto::Hash& tx_id, std::vector<uint32_t>& indexs) override;
virtual Quid::i_cryptonote_protocol* get_protocol() override;
virtual bool handle_incoming_tx(Quid::BinaryArray const& tx_blob, Quid::tx_verification_context& tvc, bool keeped_by_block) override;
virtual std::vector<Quid::Transaction> getPoolTransactions() override;
virtual bool getPoolChanges(const Crypto::Hash& tailBlockId, const std::vector<Crypto::Hash>& knownTxsIds,
std::vector<Quid::Transaction>& addedTxs, std::vector<Crypto::Hash>& deletedTxsIds) override;
virtual bool getPoolChangesLite(const Crypto::Hash& tailBlockId, const std::vector<Crypto::Hash>& knownTxsIds,
std::vector<Quid::TransactionPrefixInfo>& addedTxs, std::vector<Crypto::Hash>& deletedTxsIds) override;
virtual void getPoolChanges(const std::vector<Crypto::Hash>& knownTxsIds, std::vector<Quid::Transaction>& addedTxs,
std::vector<Crypto::Hash>& deletedTxsIds) override;
virtual bool queryBlocks(const std::vector<Crypto::Hash>& block_ids, uint64_t timestamp,
uint32_t& start_height, uint32_t& current_height, uint32_t& full_offset, std::vector<Quid::BlockFullInfo>& entries) override;
virtual bool queryBlocksLite(const std::vector<Crypto::Hash>& block_ids, uint64_t timestamp,
uint32_t& start_height, uint32_t& current_height, uint32_t& full_offset, std::vector<Quid::BlockShortInfo>& entries) override;
virtual bool have_block(const Crypto::Hash& id) override;
std::vector<Crypto::Hash> buildSparseChain() override;
std::vector<Crypto::Hash> buildSparseChain(const Crypto::Hash& startBlockId) override;
virtual bool get_stat_info(Quid::core_stat_info& st_inf) override { return false; }
virtual bool on_idle() override { return false; }
virtual void pause_mining() override {}
virtual void update_block_template_and_resume_mining() override {}
virtual bool handle_incoming_block_blob(const Quid::BinaryArray& block_blob, Quid::block_verification_context& bvc, bool control_miner, bool relay_block) override { return false; }
virtual bool handle_get_objects(Quid::NOTIFY_REQUEST_GET_OBJECTS::request& arg, Quid::NOTIFY_RESPONSE_GET_OBJECTS::request& rsp) override { return false; }
virtual void on_synchronized() override {}
virtual bool getOutByMSigGIndex(uint64_t amount, uint64_t gindex, Quid::MultisignatureOutput& out) override { return true; }
virtual size_t addChain(const std::vector<const Quid::IBlock*>& chain) override;
virtual Crypto::Hash getBlockIdByHeight(uint32_t height) override;
virtual bool getBlockByHash(const Crypto::Hash &h, Quid::Block &blk) override;
virtual bool getBlockHeight(const Crypto::Hash& blockId, uint32_t& blockHeight) override;
virtual void getTransactions(const std::vector<Crypto::Hash>& txs_ids, std::list<Quid::Transaction>& txs, std::list<Crypto::Hash>& missed_txs, bool checkTxPool = false) override;
virtual bool getBackwardBlocksSizes(uint32_t fromHeight, std::vector<size_t>& sizes, size_t count) override;
virtual bool getBlockSize(const Crypto::Hash& hash, size_t& size) override;
virtual bool getAlreadyGeneratedCoins(const Crypto::Hash& hash, uint64_t& generatedCoins) override;
virtual bool getBlockReward(size_t medianSize, size_t currentBlockSize, uint64_t alreadyGeneratedCoins, uint64_t fee,
uint64_t& reward, int64_t& emissionChange) override;
virtual bool scanOutputkeysForIndices(const Quid::KeyInput& txInToKey, std::list<std::pair<Crypto::Hash, size_t>>& outputReferences) override;
virtual bool getBlockDifficulty(uint32_t height, Quid::difficulty_type& difficulty) override;
virtual bool getBlockContainingTx(const Crypto::Hash& txId, Crypto::Hash& blockId, uint32_t& blockHeight) override;
virtual bool getMultisigOutputReference(const Quid::MultisignatureInput& txInMultisig, std::pair<Crypto::Hash, size_t>& outputReference) override;
virtual bool getGeneratedTransactionsNumber(uint32_t height, uint64_t& generatedTransactions) override;
virtual bool getOrphanBlocksByHeight(uint32_t height, std::vector<Quid::Block>& blocks) override;
virtual bool getBlocksByTimestamp(uint64_t timestampBegin, uint64_t timestampEnd, uint32_t blocksNumberLimit, std::vector<Quid::Block>& blocks, uint32_t& blocksNumberWithinTimestamps) override;
virtual bool getPoolTransactionsByTimestamp(uint64_t timestampBegin, uint64_t timestampEnd, uint32_t transactionsNumberLimit, std::vector<Quid::Transaction>& transactions, uint64_t& transactionsNumberWithinTimestamps) override;
virtual bool getTransactionsByPaymentId(const Crypto::Hash& paymentId, std::vector<Quid::Transaction>& transactions) override;
virtual std::unique_ptr<Quid::IBlock> getBlock(const Crypto::Hash& blockId) override;
virtual bool handleIncomingTransaction(const Quid::Transaction& tx, const Crypto::Hash& txHash, size_t blobSize, Quid::tx_verification_context& tvc, bool keptByBlock) override;
virtual std::error_code executeLocked(const std::function<std::error_code()>& func) override;
virtual bool addMessageQueue(Quid::MessageQueue<Quid::BlockchainMessage>& messageQueuePtr) override;
virtual bool removeMessageQueue(Quid::MessageQueue<Quid::BlockchainMessage>& messageQueuePtr) override;
void set_blockchain_top(uint32_t height, const Crypto::Hash& top_id);
void set_outputs_gindexs(const std::vector<uint32_t>& indexs, bool result);
void set_random_outs(const Quid::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_response& resp, bool result);
void addBlock(const Quid::Block& block);
void addTransaction(const Quid::Transaction& tx);
void setPoolTxVerificationResult(bool result);
void setPoolChangesResult(bool result);
private:
uint32_t topHeight;
Crypto::Hash topId;
std::vector<uint32_t> globalIndices;
bool globalIndicesResult;
Quid::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS_response randomOuts;
bool randomOutsResult;
std::unordered_map<Crypto::Hash, Quid::Block> blocks;
std::unordered_map<uint32_t, Crypto::Hash> blockHashByHeightIndex;
std::unordered_map<Crypto::Hash, Crypto::Hash> blockHashByTxHashIndex;
std::unordered_map<Crypto::Hash, Quid::Transaction> transactions;
std::unordered_map<Crypto::Hash, Quid::Transaction> transactionPool;
bool poolTxVerificationResult;
bool poolChangesResult;
};
| 66.938053 | 229 | 0.793628 | [
"vector"
] |
81b0af218161896130bf65e3bdc9ac817902149b | 505 | h | C | PYJsonViewManager/Classes/Views/Search/Views/BaseJsonViewSearchResultTableViewHeaderView.h | LiPengYue/PYJsonHandler | 292194818f8f53f3c326bb4755ed529049f1a191 | [
"MIT"
] | 1 | 2019-12-10T16:32:29.000Z | 2019-12-10T16:32:29.000Z | PYJsonViewManager/Classes/Views/Search/Views/BaseJsonViewSearchResultTableViewHeaderView.h | LiPengYue/PYJsonHandler | 292194818f8f53f3c326bb4755ed529049f1a191 | [
"MIT"
] | null | null | null | PYJsonViewManager/Classes/Views/Search/Views/BaseJsonViewSearchResultTableViewHeaderView.h | LiPengYue/PYJsonHandler | 292194818f8f53f3c326bb4755ed529049f1a191 | [
"MIT"
] | null | null | null | //
// BaseJsonViewManager.h
// PYKit
//
// Created by 李鹏跃 on 2019/9/11.
// Copyright © 2019年 13lipengyue. All rights reserved.
//
#import "PYBaseTableHeaderFooterView.h"
#import "BaseJsonViewStepModel.h"
NS_ASSUME_NONNULL_BEGIN
@interface BaseJsonViewSearchResultTableViewHeaderView : PYBaseTableHeaderFooterView
@property (nonatomic,copy) NSString *title;
+ (NSString *) getTitleWithModel: (BaseJsonViewStepModel *)model;
+ (CGFloat) getHWithString: (NSString *)str;
@end
NS_ASSUME_NONNULL_END
| 21.956522 | 84 | 0.778218 | [
"model"
] |
81b0e82015950e4f4c30d61a0ba3bb32f83154e1 | 12,611 | c | C | php_gearman_task.c | MysteryDragon/pecl-networking-gearman | f220f8035c0757d689232ba17d3d9f2d7230a104 | [
"PHP-3.01"
] | 28 | 2017-07-01T06:28:58.000Z | 2021-08-22T16:50:11.000Z | php_gearman_task.c | MysteryDragon/pecl-networking-gearman | f220f8035c0757d689232ba17d3d9f2d7230a104 | [
"PHP-3.01"
] | 10 | 2020-02-28T07:53:58.000Z | 2022-01-12T08:26:40.000Z | php_gearman_task.c | MysteryDragon/pecl-networking-gearman | f220f8035c0757d689232ba17d3d9f2d7230a104 | [
"PHP-3.01"
] | 15 | 2020-02-20T22:55:44.000Z | 2021-12-10T13:09:52.000Z | /*
* Gearman PHP Extension
*
* Copyright (C) 2008 James M. Luedke <contact@jamesluedke.com>,
* Eric Day <eday@oddments.org>
* All rights reserved.
*
* Use and distribution licensed under the PHP license. See
* the LICENSE file in this directory for full text.
*/
#include "php_gearman_task.h"
inline gearman_task_obj *gearman_task_fetch_object(zend_object *obj) {
return (gearman_task_obj *)((char*)(obj) - XtOffsetOf(gearman_task_obj, std));
}
inline zend_object *gearman_task_obj_new(zend_class_entry *ce) {
gearman_task_obj *intern = ecalloc(1,
sizeof(gearman_task_obj) +
zend_object_properties_size(ce));
zend_object_std_init(&(intern->std), ce);
object_properties_init(&intern->std, ce);
intern->task_id = 0;
intern->std.handlers = &gearman_task_obj_handlers;
return &intern->std;
}
/* this function will be used to call our user defined task callbacks */
gearman_return_t _php_task_cb_fn(gearman_task_obj *task, gearman_client_obj *client, zval zcall) {
gearman_return_t ret;
zval ztask, argv[2], retval;
uint32_t param_count;
ZVAL_OBJ(&ztask, &task->std);
ZVAL_COPY_VALUE(&argv[0], &ztask);
if (Z_ISUNDEF(task->zdata)) {
param_count = 1;
} else {
ZVAL_COPY_VALUE(&argv[1], &task->zdata);
param_count = 2;
}
if (call_user_function(EG(function_table), NULL, &zcall, &retval, param_count, argv) != SUCCESS) {
php_error_docref(NULL,
E_WARNING,
"Could not call the function %s",
( Z_ISUNDEF(zcall) || Z_TYPE(zcall) != IS_STRING) ? "[undefined]" : Z_STRVAL(zcall)
);
ret = 0;
} else {
if (Z_ISUNDEF(retval)) {
ret = 0;
} else {
if (Z_TYPE(retval) != IS_LONG) {
convert_to_long(&retval);
}
ret = Z_LVAL(retval);
}
}
return ret;
}
void _php_task_free(gearman_task_st *task, void *context) {
gearman_task_obj *task_obj= (gearman_task_obj *) context;
gearman_client_obj *cli_obj = Z_GEARMAN_CLIENT_P(&task_obj->zclient);
task_obj->flags &= ~GEARMAN_TASK_OBJ_CREATED;
zend_hash_index_del(Z_ARRVAL(cli_obj->task_list), task_obj->task_id);
}
/* TODO: clean this up a bit, Macro? */
gearman_return_t _php_task_workload_fn(gearman_task_st *task) {
gearman_task_obj *task_obj = (gearman_task_obj *) gearman_task_context(task);
gearman_client_obj *client_obj = Z_GEARMAN_CLIENT_P(&task_obj->zclient);
return _php_task_cb_fn(task_obj, client_obj, client_obj->zworkload_fn);
}
gearman_return_t _php_task_created_fn(gearman_task_st *task) {
gearman_task_obj *task_obj = (gearman_task_obj *) gearman_task_context(task);
gearman_client_obj *client_obj = Z_GEARMAN_CLIENT_P(&task_obj->zclient);
return _php_task_cb_fn(task_obj, client_obj, client_obj->zcreated_fn);
}
gearman_return_t _php_task_data_fn(gearman_task_st *task) {
gearman_task_obj *task_obj = (gearman_task_obj *) gearman_task_context(task);
gearman_client_obj *client_obj = Z_GEARMAN_CLIENT_P(&task_obj->zclient);
return _php_task_cb_fn(task_obj, client_obj, client_obj->zdata_fn);
}
gearman_return_t _php_task_warning_fn(gearman_task_st *task) {
gearman_task_obj *task_obj = (gearman_task_obj *) gearman_task_context(task);
gearman_client_obj *client_obj = Z_GEARMAN_CLIENT_P(&task_obj->zclient);
return _php_task_cb_fn(task_obj, client_obj, client_obj->zwarning_fn);
}
gearman_return_t _php_task_status_fn(gearman_task_st *task) {
gearman_task_obj *task_obj = (gearman_task_obj *) gearman_task_context(task);
gearman_client_obj *client_obj = Z_GEARMAN_CLIENT_P(&task_obj->zclient);
return _php_task_cb_fn(task_obj, client_obj, client_obj->zstatus_fn);
}
gearman_return_t _php_task_complete_fn(gearman_task_st *task) {
gearman_task_obj *task_obj = (gearman_task_obj *) gearman_task_context(task);
gearman_client_obj *client_obj = Z_GEARMAN_CLIENT_P(&task_obj->zclient);
return _php_task_cb_fn(task_obj, client_obj, client_obj->zcomplete_fn);
}
gearman_return_t _php_task_exception_fn(gearman_task_st *task) {
gearman_task_obj *task_obj = (gearman_task_obj *) gearman_task_context(task);
gearman_client_obj *client_obj = Z_GEARMAN_CLIENT_P(&task_obj->zclient);
return _php_task_cb_fn(task_obj, client_obj, client_obj->zexception_fn);
}
gearman_return_t _php_task_fail_fn(gearman_task_st *task) {
gearman_task_obj *task_obj = (gearman_task_obj *) gearman_task_context(task);
gearman_client_obj *client_obj = Z_GEARMAN_CLIENT_P(&task_obj->zclient);
return _php_task_cb_fn(task_obj, client_obj, client_obj->zfail_fn);
}
/* {{{ proto object GearmanTask::__construct()
Returns a task object */
PHP_METHOD(GearmanTask, __construct) {
}
void gearman_task_free_obj(zend_object *object) {
gearman_task_obj *intern = gearman_task_fetch_object(object);
if (!intern) {
return;
}
zval_dtor(&intern->zworkload);
zval_dtor(&intern->zdata);
zval_dtor(&intern->zclient);
zend_object_std_dtor(&intern->std);
}
/* {{{ proto ?int gearman_task_return_code()
get last gearman_return_t */
PHP_FUNCTION(gearman_task_return_code) {
zval *zobj;
gearman_task_obj *obj;
if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "O", &zobj, gearman_task_ce) == FAILURE) {
RETURN_NULL();
}
obj = Z_GEARMAN_TASK_P(zobj);
RETURN_LONG(obj->ret);
}
/* }}} */
/* {{{ proto ?bool|string gearman_task_function_name(object task)
Returns function name associated with a task. */
PHP_FUNCTION(gearman_task_function_name) {
zval *zobj;
gearman_task_obj *obj;
if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "O", &zobj, gearman_task_ce) == FAILURE) {
RETURN_NULL();
}
obj = Z_GEARMAN_TASK_P(zobj);
if (obj->flags & GEARMAN_TASK_OBJ_CREATED) {
RETURN_STRING((char *)gearman_task_function_name(obj->task));
}
RETURN_FALSE;
}
/* }}} */
/* {{{ proto ?bool|string gearman_task_unique(object task)
Returns unique identifier for a task. */
PHP_FUNCTION(gearman_task_unique) {
zval *zobj;
gearman_task_obj *obj;
if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "O", &zobj, gearman_task_ce) == FAILURE) {
RETURN_NULL();
}
obj = Z_GEARMAN_TASK_P(zobj);
if (obj->flags & GEARMAN_TASK_OBJ_CREATED) {
RETURN_STRING((char *)gearman_task_unique(obj->task));
}
RETURN_FALSE;
}
/* }}} */
/* {{{ proto string gearman_task_job_handle(object task)
Returns job handle for a task. */
PHP_FUNCTION(gearman_task_job_handle) {
zval *zobj;
gearman_task_obj *obj;
if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "O", &zobj, gearman_task_ce) == FAILURE) {
RETURN_NULL();
}
obj = Z_GEARMAN_TASK_P(zobj);
if (obj->flags & GEARMAN_TASK_OBJ_CREATED) {
RETURN_STRING((char *)gearman_task_job_handle(obj->task));
}
RETURN_FALSE;
}
/* }}} */
/* {{{ proto bool gearman_task_is_known(object task)
Get status on whether a task is known or not */
PHP_FUNCTION(gearman_task_is_known) {
zval *zobj;
gearman_task_obj *obj;
if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "O", &zobj, gearman_task_ce) == FAILURE) {
RETURN_NULL();
}
obj = Z_GEARMAN_TASK_P(zobj);
if (obj->flags & GEARMAN_TASK_OBJ_CREATED) {
RETURN_BOOL(gearman_task_is_known(obj->task));
}
RETURN_FALSE;
}
/* }}} */
/* {{{ proto bool gearman_task_is_running(object task)
Get status on whether a task is running or not */
PHP_FUNCTION(gearman_task_is_running) {
zval *zobj;
gearman_task_obj *obj;
if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "O", &zobj, gearman_task_ce) == FAILURE) {
RETURN_NULL();
}
obj = Z_GEARMAN_TASK_P(zobj);
if (obj->flags & GEARMAN_TASK_OBJ_CREATED) {
RETURN_BOOL(gearman_task_is_running(obj->task));
}
RETURN_FALSE;
}
/* }}} */
/* {{{ proto int gearman_task_numerator(object task)
Returns the numerator of percentage complete for a task. */
PHP_FUNCTION(gearman_task_numerator) {
zval *zobj;
gearman_task_obj *obj;
if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "O", &zobj, gearman_task_ce) == FAILURE) {
RETURN_NULL();
}
obj = Z_GEARMAN_TASK_P(zobj);
if (obj->flags & GEARMAN_TASK_OBJ_CREATED) {
RETURN_LONG(gearman_task_numerator(obj->task));
}
RETURN_FALSE;
}
/* }}} */
/* {{{ proto int gearman_task_denominator(object task)
Returns the denominator of percentage complete for a task. */
PHP_FUNCTION(gearman_task_denominator) {
zval *zobj;
gearman_task_obj *obj;
if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "O", &zobj, gearman_task_ce) == FAILURE) {
RETURN_NULL();
}
obj = Z_GEARMAN_TASK_P(zobj);
if (obj->flags & GEARMAN_TASK_OBJ_CREATED) {
RETURN_LONG(gearman_task_denominator(obj->task));
}
RETURN_FALSE;
}
/* }}} */
/* {{{ proto string gearman_task_data(object task)
Get data being returned for a task. */
PHP_FUNCTION(gearman_task_data) {
zval *zobj;
gearman_task_obj *obj;
const uint8_t *data;
size_t data_len;
if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "O", &zobj, gearman_task_ce) == FAILURE) {
RETURN_NULL();
}
obj = Z_GEARMAN_TASK_P(zobj);
if (obj->flags & GEARMAN_TASK_OBJ_CREATED &&
!gearman_client_has_option(&Z_GEARMAN_CLIENT_P(&obj->zclient)->client, GEARMAN_CLIENT_UNBUFFERED_RESULT)) {
data = gearman_task_data(obj->task);
data_len = gearman_task_data_size(obj->task);
RETURN_STRINGL((char *)data, (long) data_len);
}
RETURN_FALSE;
}
/* }}} */
/* {{{ proto int gearman_task_data_size(object task)
Get data size being returned for a task. */
PHP_FUNCTION(gearman_task_data_size) {
zval *zobj;
gearman_task_obj *obj;
if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "O", &zobj, gearman_task_ce) == FAILURE) {
RETURN_FALSE;
}
obj = Z_GEARMAN_TASK_P(zobj);
if (obj->flags & GEARMAN_TASK_OBJ_CREATED) {
RETURN_LONG(gearman_task_data_size(obj->task));
}
RETURN_FALSE;
}
/* }}} */
/* {{{ proto int gearman_task_send_workload(object task, string data)
NOT-TESTED Send packet data for a task. */
PHP_FUNCTION(gearman_task_send_workload) {
zval *zobj;
gearman_task_obj *obj;
char *data;
size_t data_len;
if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "Os", &zobj, gearman_task_ce,
&data, &data_len) == FAILURE) {
RETURN_FALSE;
}
obj = Z_GEARMAN_TASK_P(zobj);
if (!(obj->flags & GEARMAN_TASK_OBJ_CREATED)) {
RETURN_FALSE;
}
/* XXX verify that i am doing this correctly */
data_len = gearman_task_send_workload(obj->task, data, data_len, &obj->ret);
if (obj->ret != GEARMAN_SUCCESS)
{
php_error_docref(NULL, E_WARNING, "%s",
gearman_client_error(&Z_GEARMAN_CLIENT_P(&obj->zclient)->client));
RETURN_FALSE;
}
RETURN_LONG(data_len);
}
/* }}} */
/* {{{ proto array gearman_task_recv_data(object task, long buffer_size)
NOT-TESTED Read work or result data into a buffer for a task. */
PHP_FUNCTION(gearman_task_recv_data) {
zval *zobj;
gearman_task_obj *obj;
char *data_buffer;
zend_long data_buffer_size;
size_t data_len;
if (zend_parse_method_parameters(ZEND_NUM_ARGS(), getThis(), "Ol", &zobj, gearman_task_ce,
&data_buffer_size) == FAILURE) {
RETURN_NULL();
}
obj = Z_GEARMAN_TASK_P(zobj);
if (!(obj->flags & GEARMAN_TASK_OBJ_CREATED)) {
RETURN_FALSE;
}
data_buffer= (char *) emalloc(data_buffer_size);
data_len= gearman_task_recv_data(obj->task, data_buffer, data_buffer_size,
&obj->ret);
if (obj->ret != GEARMAN_SUCCESS &&
!gearman_client_has_option(&Z_GEARMAN_CLIENT_P(&obj->zclient)->client, GEARMAN_CLIENT_UNBUFFERED_RESULT)) {
php_error_docref(NULL, E_WARNING, "%s",
gearman_client_error(&Z_GEARMAN_CLIENT_P(&obj->zclient)->client));
RETURN_FALSE;
}
array_init(return_value);
add_next_index_long(return_value, (long)data_len);
add_next_index_stringl(return_value, (char *)data_buffer,
(long)data_len);
}
/* }}} */
| 32.335897 | 116 | 0.67901 | [
"object"
] |
81b3d9f5cf29a2f28c8c5ce73e9d58927b0dfb95 | 741 | c | C | nitan/d/dragon/spirit6.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | 1 | 2019-03-27T07:25:16.000Z | 2019-03-27T07:25:16.000Z | nitan/d/dragon/spirit6.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null | nitan/d/dragon/spirit6.c | cantona/NT6 | 073f4d491b3cfe6bfbe02fbad12db8983c1b9201 | [
"MIT"
] | null | null | null | inherit ROOM;
#include <ansi.h>
void create()
{
set("short", "龍潭入口");
set("long",
"[1;32m前方就是龍潭,進去前請三思。如果到此止步,還來得及。\n"
"如要回頭,請鍵入back。在西面,有一個向下的通道,看來似乎相當深。\n"
);
set("exits", ([
"north" : __DIR__"dragoncave",
"westdown" : __DIR__"spirit7",
]));
set("no_magic", 1);
setup();
}
void init()
{
add_action("do_back", "back");
}
int do_back(object me)
{
me=this_player();
message_vision(HIC"$N的身影消失在一陣光芒中。\n"NOR,me);
set_temp("mark/diary", 0, me);
set_temp("m_success/初級", 0, me);
set_temp("m_success/幻影", 0, me);
set_temp("m_success/孽龍", 0, me);
me->move("/d/city/wumiao");
return 1;
}
| 20.583333 | 53 | 0.516869 | [
"object"
] |
eda47e4bebe7177b9227141d3adc3a720f60752e | 1,021 | h | C | Chapter18/Activity18.01/Project/MultiplayerFPS/Source/MultiplayerFPS/Pickup.h | PacktPublishing/Elevating-Game-Experiences-with-Unreal-Engine-5-Second-Edition | f17a52b8e310c981b4750fb7716cc039517b2a38 | [
"MIT"
] | 41 | 2020-11-14T07:18:27.000Z | 2022-03-28T13:42:02.000Z | Chapter18/Activity18.01/Project/MultiplayerFPS/Source/MultiplayerFPS/Pickup.h | fghaddar/Game-Development-Projects-with-Unreal-Engine | 79a987c01dd672b6e8b95bdd15f1d17380044bf8 | [
"MIT"
] | null | null | null | Chapter18/Activity18.01/Project/MultiplayerFPS/Source/MultiplayerFPS/Pickup.h | fghaddar/Game-Development-Projects-with-Unreal-Engine | 79a987c01dd672b6e8b95bdd15f1d17380044bf8 | [
"MIT"
] | 23 | 2021-01-20T07:05:38.000Z | 2022-03-15T05:25:54.000Z | #pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Pickup.generated.h"
UCLASS()
class MULTIPLAYERFPS_API APickup : public AActor
{
GENERATED_BODY()
protected:
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Pickup")
UStaticMeshComponent* Mesh;
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Pickup")
class URotatingMovementComponent* RotatingMovement;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Pickup")
float RespawnTime = 30.0f;
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Pickup")
USoundBase* PickupSound;
FTimerHandle RespawnTimer;
bool bIsEnabled = true;
APickup();
virtual void BeginPlay() override;
virtual void OnPickedUp(class AFPSCharacter* Character);
void SetIsEnabled(bool NewbIsEnabled);
void Respawn();
UFUNCTION()
void OnBeginOverlap(UPrimitiveComponent* OverlappedComp, AActor* OtherActor, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& Hit);
};
| 23.744186 | 172 | 0.790402 | [
"mesh"
] |
edbed0886994c8074a9b3a2e5a4059c9c1755e98 | 964 | h | C | marss-cpu/marss.dramsim/qemu/hw/msix.h | ARCANA-Research/RACER-Artifacts | 95a7550e510e5e26bc632ed5b14f31ba8d621b82 | [
"MIT"
] | null | null | null | marss-cpu/marss.dramsim/qemu/hw/msix.h | ARCANA-Research/RACER-Artifacts | 95a7550e510e5e26bc632ed5b14f31ba8d621b82 | [
"MIT"
] | 1 | 2021-11-05T16:18:22.000Z | 2021-11-05T16:18:22.000Z | marss-emram/marss.dramsim/qemu/hw/msix.h | ARCANA-Research/RACER-Artifacts | 95a7550e510e5e26bc632ed5b14f31ba8d621b82 | [
"MIT"
] | null | null | null | #ifndef QEMU_MSIX_H
#define QEMU_MSIX_H
#include "qemu-common.h"
#include "pci.h"
int msix_init(PCIDevice *pdev, unsigned short nentries,
unsigned bar_nr, unsigned bar_size);
void msix_write_config(PCIDevice *pci_dev, uint32_t address,
uint32_t val, int len);
void msix_mmio_map(PCIDevice *pci_dev, int region_num,
pcibus_t addr, pcibus_t size, int type);
int msix_uninit(PCIDevice *d);
void msix_save(PCIDevice *dev, QEMUFile *f);
void msix_load(PCIDevice *dev, QEMUFile *f);
int msix_enabled(PCIDevice *dev);
int msix_present(PCIDevice *dev);
uint32_t msix_bar_size(PCIDevice *dev);
int msix_vector_use(PCIDevice *dev, unsigned vector);
void msix_vector_unuse(PCIDevice *dev, unsigned vector);
void msix_unuse_all_vectors(PCIDevice *dev);
void msix_notify(PCIDevice *dev, unsigned vector);
void msix_reset(PCIDevice *dev);
extern int msix_supported;
#endif
| 26.054054 | 61 | 0.713693 | [
"vector"
] |
edc9540068eef945e7ea320f908f5bea12838909 | 1,364 | h | C | src/problems/texturedquads.h | michaelmarks/apitest | d252e949f82cc005d2cb443de9d08bb8d984cabc | [
"Unlicense"
] | 172 | 2015-01-05T15:36:14.000Z | 2022-03-11T10:57:23.000Z | src/problems/texturedquads.h | michaelmarks/apitest | d252e949f82cc005d2cb443de9d08bb8d984cabc | [
"Unlicense"
] | 19 | 2015-02-19T00:48:36.000Z | 2020-02-21T01:23:26.000Z | src/problems/texturedquads.h | michaelmarks/apitest | d252e949f82cc005d2cb443de9d08bb8d984cabc | [
"Unlicense"
] | 28 | 2015-01-08T12:16:18.000Z | 2020-05-30T18:07:36.000Z | #pragma once
#include "problems/problem.h"
// --------------------------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------
// --------------------------------------------------------------------------------------------------------------------
class TexturedQuadsProblem : public Problem
{
public:
TexturedQuadsProblem();
virtual ~TexturedQuadsProblem() override;
inline virtual void GetClearValues(Vec4* _outCol, GLfloat* _outDepth) const override
{
Vec4 clearCol = { 0.0f, 0.0f, 0.1f, 1.0f };
(*_outCol) = clearCol;
(*_outDepth) = 1.0f;
}
virtual bool Init() override;
virtual void Render() override;
virtual void Shutdown() override;
inline virtual std::string GetName() override { return "TexturedQuadsProblem"; }
virtual bool SetSolution(Solution* _solution) override;
struct Vertex
{
Vec3 pos;
Vec2 tex;
};
typedef uint16_t Index;
protected:
void Update();
std::vector<Matrix> mTransforms;
std::vector<Vertex> mVertices;
std::vector<Index> mIndices;
std::vector<TextureDetails*> mTextures;
unsigned int mIteration;
void genUnitQuad();
bool loadTextures();
};
| 27.28 | 119 | 0.483871 | [
"render",
"vector"
] |
edd1012c08c7d180ef2a5f9e20f952095e868cb5 | 1,970 | h | C | Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DisplayMapper/DisplayMapperFeatureProcessorInterface.h | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-09-13T00:01:12.000Z | 2021-09-13T00:01:12.000Z | Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DisplayMapper/DisplayMapperFeatureProcessorInterface.h | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/Atom/Feature/Common/Code/Include/Atom/Feature/DisplayMapper/DisplayMapperFeatureProcessorInterface.h | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-20T11:07:25.000Z | 2021-07-20T11:07:25.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 <Atom/RPI.Public/FeatureProcessor.h>
#include <Atom/Feature/DisplayMapper/DisplayMapperConfigurationDescriptor.h>
#include <Atom/RHI/ImagePool.h>
#include <Atom/RHI/ImageView.h>
#include <Atom/RPI.Public/Image/StreamingImage.h>
namespace AZ
{
namespace Render
{
struct DisplayMapperLut
{
RHI::Ptr<RHI::Image> m_lutImage;
RHI::Ptr<RHI::ImageView> m_lutImageView;
RHI::ImageViewDescriptor m_lutImageViewDescriptor = {};
};
struct DisplayMapperAssetLut
{
Data::Instance<RPI::StreamingImage> m_lutStreamingImage;
};
//! The display mapper feature processor interface for setting and retreiving tonemapping settings, and handing LUTs.
class DisplayMapperFeatureProcessorInterface
: public RPI::FeatureProcessor
{
public:
AZ_RTTI(AZ::Render::DisplayMapperFeatureProcessorInterface, "{FA57793A-1C7B-4B44-88C4-02AA431C468F}", FeatureProcessor);
virtual void GetOwnedLut(DisplayMapperLut& displayMapperLut, const AZ::Name& lutName) = 0;
virtual void GetDisplayMapperLut(DisplayMapperLut& displayMapperLut) = 0;
virtual void GetLutFromAssetLocation(DisplayMapperAssetLut& displayMapperAssetLut, const AZStd::string& assetPath) = 0;
virtual void GetLutFromAssetId(DisplayMapperAssetLut& displayMapperAssetLut, const AZ::Data::AssetId) = 0;
virtual void RegisterDisplayMapperConfiguration(const DisplayMapperConfigurationDescriptor& config) = 0;
virtual DisplayMapperConfigurationDescriptor GetDisplayMapperConfiguration() = 0;
};
} // namespace Render
} // namespace AZ
| 38.627451 | 158 | 0.700508 | [
"render",
"3d"
] |
edd47cf52db8fee940ed66be93301aa84ede68ff | 3,182 | h | C | src/ifmap/client/config_amqp_client.h | sagarc-contrail/contrail-controller | 834302367f3ff81f1ce93f4036b6b3788dfd6994 | [
"Apache-2.0"
] | null | null | null | src/ifmap/client/config_amqp_client.h | sagarc-contrail/contrail-controller | 834302367f3ff81f1ce93f4036b6b3788dfd6994 | [
"Apache-2.0"
] | null | null | null | src/ifmap/client/config_amqp_client.h | sagarc-contrail/contrail-controller | 834302367f3ff81f1ce93f4036b6b3788dfd6994 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017 Juniper Networks, Inc. All rights reserved.
*/
#ifndef ctrlplane_config_amqp_client_h
#define ctrlplane_config_amqp_client_h
#include <string>
#include <vector>
#include <boost/asio/ip/tcp.hpp>
#include <tbb/atomic.h>
struct IFMapConfigOptions;
class ConfigClientManager;
struct ConfigAmqpConnInfo;
/*
* This is class interacts with RabbitMQ
*/
class ConfigAmqpClient {
public:
ConfigAmqpClient(ConfigClientManager *mgr, std::string hostname,
std::string module_name, const IFMapConfigOptions &options);
virtual ~ConfigAmqpClient();
std::string rabbitmq_ip() const {
if (current_server_index_ >= rabbitmq_ips_.size())
return "";
return rabbitmq_ips_[current_server_index_];
}
std::string rabbitmq_port() const {
if (current_server_index_ >= rabbitmq_ips_.size())
return "";
return rabbitmq_ports_[current_server_index_];
}
std::string rabbitmq_user() const {
return rabbitmq_user_;
}
std::string rabbitmq_password() const {
return rabbitmq_password_;
}
std::string rabbitmq_vhost() const {
return rabbitmq_vhost_;
}
bool rabbitmq_use_ssl() const {
return rabbitmq_use_ssl_;
}
std::string rabbitmq_ssl_version() const {
return rabbitmq_ssl_version_;
}
std::string rabbitmq_ssl_keyfile() const {
return rabbitmq_ssl_keyfile_;
}
std::string rabbitmq_ssl_certfile() const {
return rabbitmq_ssl_certfile_;
}
std::string rabbitmq_ssl_ca_certs() const {
return rabbitmq_ssl_ca_certs_;
}
int reader_task_id() const;
std::string FormAmqpUri() const;
std::string hostname() const;
std::string module_name() const;
void EnqueueUUIDRequest(std::string oper, std::string obj_type,
std::string uuid_str);
bool ProcessMessage(const std::string &json_message);
static void set_disable(bool disable) { disable_ = disable; }
ConfigClientManager *config_manager() const {
return mgr_;
}
ConfigClientManager *config_manager() {
return mgr_;
}
boost::asio::ip::tcp::endpoint endpoint() const {
return endpoint_;
}
void set_connected(bool connected);
void GetConnectionInfo(ConfigAmqpConnInfo &info) const;
private:
// A Job for reading the rabbitmq
class RabbitMQReader;
ConfigClientManager *mgr_;
std::string hostname_;
std::string module_name_;
int reader_task_id_;
size_t current_server_index_;
std::vector<std::string> rabbitmq_ips_;
std::vector<std::string> rabbitmq_ports_;
std::string rabbitmq_user_;
std::string rabbitmq_password_;
std::string rabbitmq_vhost_;
bool rabbitmq_use_ssl_;
std::string rabbitmq_ssl_version_;
std::string rabbitmq_ssl_keyfile_;
std::string rabbitmq_ssl_certfile_;
std::string rabbitmq_ssl_ca_certs_;
static bool disable_;
boost::asio::ip::tcp::endpoint endpoint_;
tbb::atomic<bool> connection_status_;
tbb::atomic<uint64_t> connection_status_change_at_;
};
#endif // ctrlplane_config_amqp_client_h
| 25.66129 | 77 | 0.688875 | [
"vector"
] |
545694323dba593512313c64311db5bea8715a2c | 959 | h | C | Engine/source/gfx/gl/gfxGLVertexDecl.h | vbillet/Torque3D | ece8823599424ea675e5f79d9bcb44e42cba8cae | [
"MIT"
] | 2,113 | 2015-01-01T11:23:01.000Z | 2022-03-28T04:51:46.000Z | Engine/source/gfx/gl/gfxGLVertexDecl.h | vbillet/Torque3D | ece8823599424ea675e5f79d9bcb44e42cba8cae | [
"MIT"
] | 948 | 2015-01-02T01:50:00.000Z | 2022-02-27T05:56:40.000Z | Engine/source/gfx/gl/gfxGLVertexDecl.h | vbillet/Torque3D | ece8823599424ea675e5f79d9bcb44e42cba8cae | [
"MIT"
] | 944 | 2015-01-01T09:33:53.000Z | 2022-03-15T22:23:03.000Z | #ifndef GFX_GL_VERTEX_DECL
#define GFX_GL_VERTEX_DECL
class GFXVertexFormat;
class GFXGLDevice;
class GFXGLVertexDecl : public GFXVertexDecl
{
public:
GFXGLVertexDecl() : mFormat(NULL), mVertexAttribActiveMask(0) {}
void init(const GFXVertexFormat *format);
void prepareVertexFormat() const;
void prepareBuffer_old(U32 stream, GLint mBuffer, GLint mDivisor) const;
void updateActiveVertexAttrib(U32 lastActiveMask) const;
struct glVertexAttribData
{
U32 stream;
GLint attrIndex;
GLint elementCount; // 1 - 4
GLenum type; // GL_FLOAT...
GLboolean normalized;
GLsizei stride;
GLvoid *pointerFirst;
};
protected:
friend class GFXGLDevice;
const GFXVertexFormat *mFormat;
GLuint mVertexSize[4];
U32 mVertexAttribActiveMask;
Vector<glVertexAttribData> glVerticesFormat;
void _initVerticesFormat(U32 stream);
void _initVerticesFormat2();
};
#endif //GFX_GL_VERTEX_DECL | 24.589744 | 75 | 0.736184 | [
"vector"
] |
545cf2caa004e808487f7eef399704067a6f595c | 3,218 | h | C | sources/Engine/Modules/Physics/BulletBackend/BulletPhysicsSystemBackend.h | n-paukov/swengine | ca7441f238e8834efff5d2b61b079627824bf3e4 | [
"MIT"
] | 22 | 2017-07-26T17:42:56.000Z | 2022-03-21T22:12:52.000Z | sources/Engine/Modules/Physics/BulletBackend/BulletPhysicsSystemBackend.h | n-paukov/swengine | ca7441f238e8834efff5d2b61b079627824bf3e4 | [
"MIT"
] | 50 | 2017-08-02T19:37:48.000Z | 2020-07-24T21:10:38.000Z | sources/Engine/Modules/Physics/BulletBackend/BulletPhysicsSystemBackend.h | n-paukov/swengine | ca7441f238e8834efff5d2b61b079627824bf3e4 | [
"MIT"
] | 4 | 2018-08-20T08:12:48.000Z | 2020-07-19T14:10:05.000Z | #pragma once
#include <glm/vec3.hpp>
#include <btBulletDynamicsCommon.h>
#include "Modules/ECS/ECS.h"
#include "Modules/ECS/OnlineManagementSystem.h"
#include "Modules/Physics/BaseBackend/PhysicsSystemBackend.h"
#include "Modules/Physics/RigidBodyComponent.h"
#include "Modules/Physics/KinematicCharacterComponent.h"
#include "Modules/Physics/PhysicsCollisions.h"
#include "BulletCollisionDispatcher.h"
#include "BulletDebugPainter.h"
#include "BulletKinematicCharacterComponent.h"
// TODO: fix possible circular dependency here, replace shared_ptr to GameWorld with weak_ptr
class BulletPhysicsSystemBackend :
public PhysicsSystemBackend,
public std::enable_shared_from_this<BulletPhysicsSystemBackend>,
public EventsListener<GameObjectAddComponentEvent<RigidBodyComponent>>,
public EventsListener<GameObjectRemoveComponentEvent<RigidBodyComponent>>,
public EventsListener<GameObjectAddComponentEvent<KinematicCharacterComponent>>,
public EventsListener<GameObjectRemoveComponentEvent<KinematicCharacterComponent>>,
public EventsListener<GameObjectOnlineStatusChangeEvent> {
public:
explicit BulletPhysicsSystemBackend(GameWorld* gameWorld);
~BulletPhysicsSystemBackend() override;
void configure() override;
void unconfigure() override;
void setGravity(const glm::vec3& gravity) override;
glm::vec3 getGravity() const override;
void update(float delta) override;
void render() override;
EventProcessStatus receiveEvent(
const GameObjectAddComponentEvent<RigidBodyComponent>& event) override;
EventProcessStatus receiveEvent(
const GameObjectRemoveComponentEvent<RigidBodyComponent>& event) override;
EventProcessStatus receiveEvent(
const GameObjectAddComponentEvent<KinematicCharacterComponent>& event) override;
EventProcessStatus receiveEvent(
const GameObjectRemoveComponentEvent<KinematicCharacterComponent>& event) override;
EventProcessStatus receiveEvent(const GameObjectOnlineStatusChangeEvent& event) override;
void enableDebugDrawing(bool enable) override;
bool isDebugDrawingEnabled() override;
void setUpdateStepCallback(std::function<void(float)> callback) override;
private:
bool isConfigured() const;
void nearCallback(btBroadphasePair& collisionPair,
btCollisionDispatcher& dispatcher, btDispatcherInfo& dispatchInfo);
static CollisionCallback getCollisionsCallback(GameObject& object);
static void synchronizeTransforms(GameObject& object, const btTransform& transform);
private:
static void physicsNearCallback(btBroadphasePair& collisionPair,
btCollisionDispatcher& dispatcher, btDispatcherInfo& dispatchInfo);
static void physicsTickCallback(btDynamicsWorld* world, btScalar timeStep);
private:
GameWorld* m_gameWorld;
btDefaultCollisionConfiguration* m_collisionConfiguration = nullptr;
BulletCollisionDispatcher* m_collisionDispatcher = nullptr;
btBroadphaseInterface* m_broadphaseInterface = nullptr;
btSequentialImpulseConstraintSolver* m_constraintSolver = nullptr;
btDiscreteDynamicsWorld* m_dynamicsWorld = nullptr;
BulletDebugPainter* m_physicsDebugPainter = nullptr;
bool m_isDebugDrawingEnabled = false;
std::function<void(float)> m_updateStepCallback;
};
| 36.157303 | 93 | 0.82629 | [
"render",
"object",
"transform"
] |
545e0a170bafa39d860dc01bb6c9a349b7c1a44b | 3,096 | h | C | Desktop/Tools/CCore/inc/video/PrintDDL.h | SergeyStrukov/CCore-3-xx | 820507e78f8aa35ca05761e00e060c8f64c59af5 | [
"BSL-1.0"
] | 8 | 2017-12-21T07:00:16.000Z | 2020-04-02T09:05:55.000Z | Desktop/Tools/CCore/inc/video/PrintDDL.h | SergeyStrukov/CCore-3-xx | 820507e78f8aa35ca05761e00e060c8f64c59af5 | [
"BSL-1.0"
] | null | null | null | Desktop/Tools/CCore/inc/video/PrintDDL.h | SergeyStrukov/CCore-3-xx | 820507e78f8aa35ca05761e00e060c8f64c59af5 | [
"BSL-1.0"
] | 1 | 2020-03-30T09:54:18.000Z | 2020-03-30T09:54:18.000Z | /* PrintDDL.h */
//----------------------------------------------------------------------------------------
//
// Project: CCore 3.00
//
// Tag: Desktop
//
// License: Boost Software License - Version 1.0 - August 17th, 2003
//
// see http://www.boost.org/LICENSE_1_0.txt or the local copy
//
// Copyright (c) 2016 Sergey Strukov. All rights reserved.
//
//----------------------------------------------------------------------------------------
#ifndef CCore_inc_video_PrintDDL_h
#define CCore_inc_video_PrintDDL_h
#include <CCore/inc/CharProp.h>
#include <CCore/inc/video/Point.h>
namespace CCore {
namespace Video {
/* DDLBool() */
inline StrLen DDLBool(bool val) { return val?"True"_c:"False"_c; }
/* classes */
struct DDLPoint;
struct DDLPane;
struct DDLString;
struct DDLPrintableString;
/* struct DDLPoint */
struct DDLPoint
{
Point point;
explicit DDLPoint(const Point &point_) : point(point_) {}
// print object
void print(PrinterType &out) const
{
Printf(out,"{ #; , #; }",point.x,point.y);
}
};
/* struct DDLPane */
struct DDLPane
{
Pane pane;
explicit DDLPane(const Pane &pane_) : pane(pane_) {}
// print object
void print(PrinterType &out) const
{
Printf(out,"{ #; , #; , #; , #; }",pane.x,pane.y,pane.dx,pane.dy);
}
};
/* struct DDLString */
struct DDLString
{
StrLen str;
explicit DDLString(StrLen str_) : str(str_) {}
explicit DDLString(const ConstTypeRangeableType<char> &obj) : str(Range_const(obj)) {}
// print object
static void PrintChar(PrinterType &out,char ch)
{
switch( ch )
{
case '\b' : out.put('\\'); out.put('b'); break;
case '\t' : out.put('\\'); out.put('t'); break;
case '\n' : out.put('\\'); out.put('n'); break;
case '\v' : out.put('\\'); out.put('v'); break;
case '\f' : out.put('\\'); out.put('f'); break;
case '\r' : out.put('\\'); out.put('r'); break;
case '"' : out.put('\\'); out.put('"'); break;
case '\\' : out.put('\\'); out.put('\\'); break;
default:
{
if( CharIsPrintable(ch) ) out.put(ch); else out.put(' ');
}
}
}
void print(PrinterType &out) const
{
out.put('"');
for(char ch : str ) PrintChar(out,ch);
out.put('"');
}
};
/* struct DDLPrintableString */
struct DDLPrintableString
{
StrLen str;
explicit DDLPrintableString(StrLen str_) : str(str_) {}
explicit DDLPrintableString(const ConstTypeRangeableType<char> &obj) : str(Range_const(obj)) {}
// print object
static void GuardNotPrintable();
static void PrintChar(PrinterType &out,char ch)
{
switch( ch )
{
case '"' : out.put('\\'); out.put('"'); break;
case '\\' : out.put('\\'); out.put('\\'); break;
default:
{
if( CharIsPrintable(ch) ) out.put(ch); else GuardNotPrintable();
}
}
}
void print(PrinterType &out) const
{
out.put('"');
for(char ch : str ) PrintChar(out,ch);
out.put('"');
}
};
} // namespace Video
} // namespace CCore
#endif
| 18.763636 | 97 | 0.540698 | [
"object"
] |
545e1345e340eb485836cd33ed980348c9bb9b60 | 3,074 | h | C | KoalaRunBot/Steamhammer/Source/ProductionManager.h | koalarun/KoalaRunBot | 2c2093d26b1ca87a08731727a189f32297e9c6cd | [
"MIT"
] | null | null | null | KoalaRunBot/Steamhammer/Source/ProductionManager.h | koalarun/KoalaRunBot | 2c2093d26b1ca87a08731727a189f32297e9c6cd | [
"MIT"
] | null | null | null | KoalaRunBot/Steamhammer/Source/ProductionManager.h | koalarun/KoalaRunBot | 2c2093d26b1ca87a08731727a189f32297e9c6cd | [
"MIT"
] | null | null | null | #pragma once
#include <forward_list>
#include "Common.h"
#include "BOSSManager.h"
#include "BuildOrder.h"
#include "BuildOrderQueue.h"
#include "BuildingManager.h"
#include "ProductionGoal.h"
#include "StrategyManager.h"
namespace KoalaRunBot {
enum class ExtractorTrick { None, Start, ExtractorOrdered, UnitOrdered, MakeUnitBypass };
class ProductionManager {
ProductionManager();
BuildOrderQueue _queue;
std::forward_list<ProductionGoal> _goals;
int _lastProductionFrame; // for detecting jams
BWAPI::TilePosition _predictedTilePosition;
BWAPI::Unit _assignedWorkerForThisBuilding;
bool _haveLocationForThisBuilding;
int _delayBuildingPredictionUntilFrame;
bool _outOfBook; // production queue is beyond the opening book
int _targetGasAmount; // for "go gas until <n>"; set to 0 if no target
ExtractorTrick _extractorTrickState;
BWAPI::UnitType _extractorTrickUnitType; // drone or zergling
Building* _extractorTrickBuilding; // set depending on the extractor trick state
BWAPI::Unit getClosestUnitToPosition(const std::vector<BWAPI::Unit>& units, BWAPI::Position closestTo) const;
BWAPI::Unit getFarthestUnitFromPosition(const std::vector<BWAPI::Unit>& units, BWAPI::Position farthest) const;
BWAPI::Unit getClosestLarvaToPosition(BWAPI::Position closestTo) const;
void executeCommand(MacroCommand command);
void updateGoals();
bool meetsReservedResources(MacroAct type);
void create(BWAPI::Unit producer, const BuildOrderItem& item);
void dropJammedItemsFromQueue();
bool itemCanBeProduced(const MacroAct& act) const;
void manageBuildOrderQueue();
void maybeReorderQueue();
bool canMakeNow(BWAPI::Unit producer, MacroAct t);
void predictWorkerMovement(const Building& b);
int getFreeMinerals() const;
int getFreeGas() const;
void doExtractorTrick();
BWAPI::Unit getProducer(MacroAct t, BWAPI::Position closestTo = BWAPI::Positions::None) const;
public:
static ProductionManager& Instance();
void drawQueueInformation(std::map<BWAPI::UnitType, int>& numUnits, int x, int y, int index);
void setBuildOrder(const BuildOrder& buildOrder);
void update();
void onUnitMorph(BWAPI::Unit unit);
void onUnitDestroy(BWAPI::Unit unit);
void drawProductionInformation(int x, int y);
void startExtractorTrick(BWAPI::UnitType type);
void queueGasSteal();
bool isGasStealInQueue() const;
bool nextIsBuilding() const;
void goOutOfBookAndClearQueue();
void goOutOfBook();
bool isOutOfBook() const { return _outOfBook; };
};
class CompareWhenStarted {
public:
CompareWhenStarted() {}
// For sorting the display of items under construction.
// Some redundant code removed here thanks to Andrey Kurdiumov.
bool operator()(BWAPI::Unit u1, BWAPI::Unit u2) {
int startedU1 = u1->getType().buildTime() - u1->getRemainingBuildTime();
int startedU2 = u2->getType().buildTime() - u2->getRemainingBuildTime();
return startedU1 > startedU2;
}
};
}
| 32.357895 | 115 | 0.732271 | [
"vector"
] |
547d81baaf9f755fd6f1d00b4b89d11b19c0920d | 804 | h | C | libs/MelonFrontend/MelonFrontend/VertexShader.h | HeBomou/Melon | a5a4b7dad296d6d9b1e6bd90427af2fd7bcdf2ef | [
"BSD-3-Clause"
] | 13 | 2020-10-10T01:32:57.000Z | 2021-04-03T06:23:20.000Z | libs/MelonFrontend/MelonFrontend/VertexShader.h | paakmau/Melon | a5a4b7dad296d6d9b1e6bd90427af2fd7bcdf2ef | [
"BSD-3-Clause"
] | 2 | 2021-04-02T12:52:50.000Z | 2021-04-08T03:35:30.000Z | libs/MelonFrontend/MelonFrontend/VertexShader.h | paakmau/Melon | a5a4b7dad296d6d9b1e6bd90427af2fd7bcdf2ef | [
"BSD-3-Clause"
] | null | null | null | #include <cstdint>
#include <vector>
constexpr const char* k_VertexShader =
"#version 450\n"
"\n"
"layout(set = 0, binding = 0) uniform CameraUniformObject {\n"
" mat4 vp;\n"
"}\n"
"cameraUniformObject;\n"
"\n"
"layout(set = 1, binding = 0) uniform EntityUniformObject {\n"
" mat4 model;\n"
"}\n"
"entityUniformObbject;\n"
"\n"
"layout(location = 0) in vec3 inPosition;\n"
"layout(location = 1) in vec3 inNormal;\n"
"\n"
"layout(location = 0) out vec3 fragColor;\n"
"layout(location = 1) out vec3 normal;\n"
"\n"
"void main() {\n"
" gl_Position = cameraUniformObject.vp * entityUniformObbject.model * vec4(inPosition, 1.0);\n"
" fragColor = vec3(1.0, 1.0, 1.0);\n"
" normal = inNormal;\n"
"}\n";
| 28.714286 | 102 | 0.580846 | [
"vector",
"model"
] |
547efd93c5f3f2d90d034943d537d00ff67b88a2 | 482 | h | C | Graph.h | ksenull/CoffmanGrahamGraphVis | ddc2034374c12939d24c8b9f6a39505fabb0f8fd | [
"MIT"
] | null | null | null | Graph.h | ksenull/CoffmanGrahamGraphVis | ddc2034374c12939d24c8b9f6a39505fabb0f8fd | [
"MIT"
] | null | null | null | Graph.h | ksenull/CoffmanGrahamGraphVis | ddc2034374c12939d24c8b9f6a39505fabb0f8fd | [
"MIT"
] | null | null | null | #pragma once
#include <iostream>
#include <vector>
#include <NamedType.h>
using namespace std;
struct VertexParameter {};
struct EdgesParameter {};
struct GraphParameter {};
using Vertex = NamedType<int, VertexParameter>;
using Edges = NamedType<vector<Vertex>, EdgesParameter>;
using Graph = NamedType<vector<Edges>, GraphParameter>;
//using Vertex = int;
//using Edges = vector<Vertex>;
//using Graph = vector<Edges>;
void PrintGraph(const Graph& g);
| 20.956522 | 57 | 0.709544 | [
"vector"
] |
547ffe60b396dd8c8c04253472673d3e7ed87b8c | 368 | h | C | WeatherStation/timezone.h | notpavlov/Weather-Station | 3ac18096ee95e8ea280a7fa3f4c1249d0afbbdc1 | [
"MIT"
] | null | null | null | WeatherStation/timezone.h | notpavlov/Weather-Station | 3ac18096ee95e8ea280a7fa3f4c1249d0afbbdc1 | [
"MIT"
] | null | null | null | WeatherStation/timezone.h | notpavlov/Weather-Station | 3ac18096ee95e8ea280a7fa3f4c1249d0afbbdc1 | [
"MIT"
] | null | null | null | #include <vector>
#include <string>
/*!
* \brief Class that retrieves and sets the system's timezone.
* \copyright MIT License
* \author notpavlov
*/
class timezone {
public:
static void timezoneGet(std::string& timezone);
static void timezoneSet(const std::string& timezone);
static void timezoneListGet(std::vector<std::string>* vec);
static int init();
};
| 23 | 62 | 0.725543 | [
"vector"
] |
54830181e131672f7404907b90aa54ad789c84ed | 2,816 | h | C | firmware/rotary_encoder/RotaryEncOverMCP.h | klintan/ros2_rotary_encoder | 80f32bba170e1df01f36b3bf10ae0bab47835c01 | [
"MIT"
] | null | null | null | firmware/rotary_encoder/RotaryEncOverMCP.h | klintan/ros2_rotary_encoder | 80f32bba170e1df01f36b3bf10ae0bab47835c01 | [
"MIT"
] | null | null | null | firmware/rotary_encoder/RotaryEncOverMCP.h | klintan/ros2_rotary_encoder | 80f32bba170e1df01f36b3bf10ae0bab47835c01 | [
"MIT"
] | null | null | null | /*
* RotaryEncOverMCP.h
*
* Created on: 21.05.2018
* Author: Maxi
*/
#ifndef SRC_ROTARYENCOVERMCP_H_
#define SRC_ROTARYENCOVERMCP_H_
/* Describes new objects based on the Rotary and Adafruit MCP23017 library */
#include <Adafruit_MCP23017.h>
#include <Rotary.h>
/* function pointer definition */
typedef void (*rotaryActionFunc)(bool clockwise, int id);
/* We describe an object in which we instantiate a rotary encoder
* over an I2C expander.
* It holds the information:
* * to which MCP object it's connected
* * which pin it is connected to
* * what function to call when there is a change
* */
class RotaryEncOverMCP {
public:
RotaryEncOverMCP(Adafruit_MCP23017* mcp, byte pinA, byte pinB, rotaryActionFunc actionFunc = nullptr, int id = 0)
: rot(pinA, pinB), mcp(mcp),
pinA(pinA), pinB(pinB),
actionFunc(actionFunc), id(id) {
}
/* Initialize object in the MCP */
void init() {
if(mcp != nullptr) {
mcp->pinMode(pinA, INPUT);
mcp->pullUp(pinA, HIGH); //disable pullup on this pin
mcp->setupInterruptPin(pinA,FALLING);
mcp->pinMode(pinB, INPUT);
mcp->pullUp(pinB, HIGH); //disable pullup on this pin
mcp->setupInterruptPin(pinB,FALLING);
}
}
/* On an interrupt, can be called with the value of the GPIOAB register (or INTCAP) */
void feedInput(uint16_t gpioAB) {
uint8_t pinValA = bitRead(gpioAB, pinA);
uint8_t pinValB = bitRead(gpioAB, pinB);
//uint8_t event = rot.process(pinValA, pinValB);
Serial.println("pinValA: " + String(pinValA));
Serial.println("pinValB: " + String(pinValB));
if(actionFunc) {
actionFunc(true, id);
}
/*if(event == DIR_CW || event == DIR_CCW) {
//clock wise or counter-clock wise
bool clockwise = event == DIR_CW;
//Call into action function if registered
if(actionFunc) {
actionFunc(clockwise, id);
}
}*/
}
/* Poll the encoder. Will cause an I2C transfer. */
void poll() {
if(mcp != nullptr) {
feedInput(mcp->readGPIOAB());
}
}
Adafruit_MCP23017* getMCP() {
return mcp;
}
private:
Rotary rot; /* the rotary object which will be created*/
Adafruit_MCP23017* mcp = nullptr; /* pointer the I2C GPIO expander it's connected to */
uint8_t pinA = 0;
uint8_t pinB = 0; /* the pin numbers for output A and output B */
rotaryActionFunc actionFunc = nullptr; /* function pointer, will be called when there is an action happening */
int id = 0; /* optional ID for identification */
};
#endif /* SRC_ROTARYENCOVERMCP_H_ */
| 32 | 117 | 0.604403 | [
"object"
] |
5495e17160900e29800c6ed12e4224cc1c3c37b7 | 2,328 | h | C | csv/csv.h | KondoA9/a9_cpp_library | 36bf0371e778cc995c347246b8699eb459da66a7 | [
"MIT"
] | null | null | null | csv/csv.h | KondoA9/a9_cpp_library | 36bf0371e778cc995c347246b8699eb459da66a7 | [
"MIT"
] | null | null | null | csv/csv.h | KondoA9/a9_cpp_library | 36bf0371e778cc995c347246b8699eb459da66a7 | [
"MIT"
] | null | null | null | #pragma once
#include "../util/util.h"
#include <fstream>
#include <vector>
#include <string>
namespace a9 {
class csv {
std::vector<std::vector<std::string>> cells_;
size_t row_ = 0, column_ = 0;
char delimiter_ = ',';
std::string path_;
bool is_open_ = false;
public:
csv() {}
csv(const std::string& _path, size_t _header_rows = 0) {
open(_path, _header_rows);
}
~csv() {}
bool open(const std::string& _path, size_t _header_rows = 0) {
path_ = _path;
is_open_ = parse_csv(_header_rows);
return is_open_;
}
bool save(const std::string& _path) {
std::ofstream file(_path);
if (!file.is_open()) {
return false;
}
for (const auto& row : cells_) {
for (const auto& cell : row) {
file << cell << ',';
}
file << '\n';
}
file.close();
return true;
}
void clear() {
std::vector<std::vector<std::string>>().swap(cells_);
}
size_t rows()const {
return cells_.size();
}
size_t columns(size_t _row)const {
return cells_[_row].size();
}
void write(const std::string& _val) {
if (cells_.size() <= row_) {
cells_.push_back(std::vector<std::string>());
}
cells_[row_].push_back(_val);
}
void write(int _val) {
write(std::to_string(_val));
}
void write(double _val) {
write(std::to_string(_val));
}
template <typename T, class... Args>
void write_line(T _val, Args ..._line) {
write(_val);
write_line(std::forward<Args>(_line)...);
}
void write_new_line() {
cells_.push_back(std::vector<std::string>());
row_ += 1;
}
std::vector<std::vector<std::string>> as_vector()const {
return cells_;
}
void set_delimiter(char c) {
delimiter_ = c;
}
operator bool()const {
return is_open_;
}
std::vector<std::string> operator[] (int _i) const {
return cells_[_i];
}
private:
bool parse_csv(size_t _header_rows) {
std::ifstream file(path_);
if (!file.is_open()) {
return false;
}
size_t header_count = 0;
std::string buf;
while (std::getline(file, buf)) {
header_count++;
if (header_count <= _header_rows) {
continue;
}
const auto values = util::split(buf, delimiter_, true, true);
cells_.push_back(values);
}
file.close();
return true;
}
void write_line() {
write("\n");
}
};
} | 18.046512 | 65 | 0.601375 | [
"vector"
] |
54a1c2cfc3909a472b82893480a92466278d2fbb | 453 | h | C | Physics/Controller.h | lkstc112233/CSCI-6555-Labs | 17114a8433c028532c5a2cb8a540be507b9f268c | [
"MIT"
] | 3 | 2018-09-25T02:17:05.000Z | 2018-09-26T15:59:58.000Z | Physics/Controller.h | lkstc112233/CSCI-6555-Labs | 17114a8433c028532c5a2cb8a540be507b9f268c | [
"MIT"
] | null | null | null | Physics/Controller.h | lkstc112233/CSCI-6555-Labs | 17114a8433c028532c5a2cb8a540be507b9f268c | [
"MIT"
] | 1 | 2019-11-11T18:18:50.000Z | 2019-11-11T18:18:50.000Z | #ifndef PHYSICS_CONTROLLER_H
#define PHYSICS_CONTROLLER_H
#include <glm/glm.hpp>
#include <memory>
#include "../Graphics/Object/Object.h"
class Controller {
private:
std::weak_ptr<Object3D> handlingObject;
public:
Controller(std::shared_ptr<Object3D> object);
glm::vec3 speed;
glm::vec3 position;
float mass = 1;
void applyChange(float timeSpan);
bool valid() { return !handlingObject.expired(); }
};
#endif // PHYSICS_CONTROLLER_H | 20.590909 | 52 | 0.735099 | [
"object"
] |
54ab6c60ed6eb1214196bdcd6d22a7f2d0bc3425 | 6,614 | h | C | parsers/action_expression/generated/ActionExpressionParser.h | trgswe/fs2open.github.com | a159eba0cebca911ad14a118412fddfe5be8e9f8 | [
"Unlicense"
] | 307 | 2015-04-10T13:27:32.000Z | 2022-03-21T03:30:38.000Z | parsers/action_expression/generated/ActionExpressionParser.h | trgswe/fs2open.github.com | a159eba0cebca911ad14a118412fddfe5be8e9f8 | [
"Unlicense"
] | 2,231 | 2015-04-27T10:47:35.000Z | 2022-03-31T19:22:37.000Z | parsers/action_expression/generated/ActionExpressionParser.h | trgswe/fs2open.github.com | a159eba0cebca911ad14a118412fddfe5be8e9f8 | [
"Unlicense"
] | 282 | 2015-01-05T12:16:57.000Z | 2022-03-28T04:45:11.000Z |
// Generated from /media/cache/code/asarium/fs2open.github.com/parsers/action_expression/ActionExpression.g4 by ANTLR 4.8
#pragma once
#include "antlr4-runtime.h"
class ActionExpressionParser : public antlr4::Parser {
public:
enum {
PLUS = 1, MINUS = 2, FLOAT = 3, INT = 4, RAND_L_PAREN = 5, L_PAREN = 6,
R_PAREN = 7, IDENTIFIER = 8, DOT = 9, STRING = 10, SPACE = 11, OTHER = 12
};
enum {
RuleExpression_main = 0, RuleExpression = 1, RuleParenthesis_expression = 2,
RuleValue_expression = 3, RuleLiteral_expression = 4, RuleVariable_reference_expression = 5,
RuleRandom_range_expression = 6, RuleVec3d_constructor = 7
};
ActionExpressionParser(antlr4::TokenStream *input);
~ActionExpressionParser();
virtual std::string getGrammarFileName() const override;
virtual const antlr4::atn::ATN& getATN() const override { return _atn; };
virtual const std::vector<std::string>& getTokenNames() const override { return _tokenNames; }; // deprecated: use vocabulary instead.
virtual const std::vector<std::string>& getRuleNames() const override;
virtual antlr4::dfa::Vocabulary& getVocabulary() const override;
class Expression_mainContext;
class ExpressionContext;
class Parenthesis_expressionContext;
class Value_expressionContext;
class Literal_expressionContext;
class Variable_reference_expressionContext;
class Random_range_expressionContext;
class Vec3d_constructorContext;
class Expression_mainContext : public antlr4::ParserRuleContext {
public:
Expression_mainContext(antlr4::ParserRuleContext *parent, size_t invokingState);
virtual size_t getRuleIndex() const override;
ExpressionContext *expression();
antlr4::tree::TerminalNode *EOF();
virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override;
};
Expression_mainContext* expression_main();
class ExpressionContext : public antlr4::ParserRuleContext {
public:
ExpressionContext(antlr4::ParserRuleContext *parent, size_t invokingState);
virtual size_t getRuleIndex() const override;
Value_expressionContext *value_expression();
Random_range_expressionContext *random_range_expression();
Parenthesis_expressionContext *parenthesis_expression();
Variable_reference_expressionContext *variable_reference_expression();
std::vector<ExpressionContext *> expression();
ExpressionContext* expression(size_t i);
antlr4::tree::TerminalNode *PLUS();
antlr4::tree::TerminalNode *MINUS();
virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override;
};
ExpressionContext* expression();
ExpressionContext* expression(int precedence);
class Parenthesis_expressionContext : public antlr4::ParserRuleContext {
public:
Parenthesis_expressionContext(antlr4::ParserRuleContext *parent, size_t invokingState);
virtual size_t getRuleIndex() const override;
antlr4::tree::TerminalNode *L_PAREN();
ExpressionContext *expression();
antlr4::tree::TerminalNode *R_PAREN();
virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override;
};
Parenthesis_expressionContext* parenthesis_expression();
class Value_expressionContext : public antlr4::ParserRuleContext {
public:
Value_expressionContext(antlr4::ParserRuleContext *parent, size_t invokingState);
virtual size_t getRuleIndex() const override;
Literal_expressionContext *literal_expression();
Vec3d_constructorContext *vec3d_constructor();
virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override;
};
Value_expressionContext* value_expression();
class Literal_expressionContext : public antlr4::ParserRuleContext {
public:
Literal_expressionContext(antlr4::ParserRuleContext *parent, size_t invokingState);
virtual size_t getRuleIndex() const override;
antlr4::tree::TerminalNode *FLOAT();
antlr4::tree::TerminalNode *INT();
antlr4::tree::TerminalNode *STRING();
virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override;
};
Literal_expressionContext* literal_expression();
class Variable_reference_expressionContext : public antlr4::ParserRuleContext {
public:
Variable_reference_expressionContext(antlr4::ParserRuleContext *parent, size_t invokingState);
virtual size_t getRuleIndex() const override;
std::vector<antlr4::tree::TerminalNode *> IDENTIFIER();
antlr4::tree::TerminalNode* IDENTIFIER(size_t i);
std::vector<antlr4::tree::TerminalNode *> DOT();
antlr4::tree::TerminalNode* DOT(size_t i);
virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override;
};
Variable_reference_expressionContext* variable_reference_expression();
class Random_range_expressionContext : public antlr4::ParserRuleContext {
public:
Random_range_expressionContext(antlr4::ParserRuleContext *parent, size_t invokingState);
virtual size_t getRuleIndex() const override;
antlr4::tree::TerminalNode *RAND_L_PAREN();
std::vector<ExpressionContext *> expression();
ExpressionContext* expression(size_t i);
antlr4::tree::TerminalNode *R_PAREN();
virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override;
};
Random_range_expressionContext* random_range_expression();
class Vec3d_constructorContext : public antlr4::ParserRuleContext {
public:
Vec3d_constructorContext(antlr4::ParserRuleContext *parent, size_t invokingState);
virtual size_t getRuleIndex() const override;
antlr4::tree::TerminalNode *L_PAREN();
std::vector<ExpressionContext *> expression();
ExpressionContext* expression(size_t i);
antlr4::tree::TerminalNode *R_PAREN();
virtual antlrcpp::Any accept(antlr4::tree::ParseTreeVisitor *visitor) override;
};
Vec3d_constructorContext* vec3d_constructor();
virtual bool sempred(antlr4::RuleContext *_localctx, size_t ruleIndex, size_t predicateIndex) override;
bool expressionSempred(ExpressionContext *_localctx, size_t predicateIndex);
private:
static std::vector<antlr4::dfa::DFA> _decisionToDFA;
static antlr4::atn::PredictionContextCache _sharedContextCache;
static std::vector<std::string> _ruleNames;
static std::vector<std::string> _tokenNames;
static std::vector<std::string> _literalNames;
static std::vector<std::string> _symbolicNames;
static antlr4::dfa::Vocabulary _vocabulary;
static antlr4::atn::ATN _atn;
static std::vector<uint16_t> _serializedATN;
struct Initializer {
Initializer();
};
static Initializer _init;
};
| 34.26943 | 136 | 0.757787 | [
"vector"
] |
54b6f036c21766d80ae18ad1d889d5811c6631ee | 4,462 | h | C | printscan/wia/core/server/lockmgr.h | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | printscan/wia/core/server/lockmgr.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | printscan/wia/core/server/lockmgr.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | /******************************************************************************
*
* (C) COPYRIGHT MICROSOFT CORP., 1999
*
* TITLE: LockMgr.h
*
* VERSION: 1.0
*
* AUTHOR: ByronC
*
* DATE: 15 November, 1999
*
* DESCRIPTION:
* Definition of Lock Manager Class.
*
******************************************************************************/
#pragma once
#ifndef _LOCKMGR_H_
#define _LOCKMGR_H_
#define WIA_LOCK_WAIT_TIME 60000
class StiLockMgr; // defined later in this file
//
// Lock information stored per device
//
typedef struct _LockInfo {
HANDLE hDeviceIsFree; // Auto-Reset event object used to signal
// when device is free.
BOOL bDeviceIsLocked; // Indicates whether device is currently
// locked.
LONG lInUse; // Indicates whether the device is actually
// in use i.e. we are in the middle of a
// request (e.g. a data transfer).
DWORD dwThreadId; // The Id of the Thread which has device
// locked.
LONG lHoldingTime; // The amount of idle time (milliseconds)
// to keep hold of lock.
LONG lTimeLeft; // The amount of idle time remaining.
} LockInfo, *PLockInfo;
//
// Info struct used during enumeration callbacks
//
typedef struct _EnumContext {
StiLockMgr *This; // Pointer to the Lock Manager that
// requested the enumeration
LONG lShortestWaitTime; // Value indicating the shortest wait time
// till next unlock.
BOOL bMustSchedule; // Indicates whether the unlock callback
// must be scheduled.
} EnumContext, *PEnumContext;
//
// Class definition for the lock manager. It is used by both STI and WIA.
//
class StiLockMgr : IUnknown {
public:
//
// Constructor, Initialize, Destructor
//
StiLockMgr();
HRESULT Initialize();
~StiLockMgr();
//
// IUnknown methods
//
HRESULT _stdcall QueryInterface(const IID& iid, void** ppv);
ULONG _stdcall AddRef(void);
ULONG _stdcall Release(void);
//
// Lock/Unlock Request methods
//
HRESULT _stdcall RequestLock(BSTR pszDeviceName, ULONG ulTimeout, BOOL bInServerProcess, DWORD dwClientThreadId);
HRESULT _stdcall RequestLock(ACTIVE_DEVICE *pDevice, ULONG ulTimeOut, BOOL bOpenPort = TRUE);
HRESULT _stdcall RequestUnlock(BSTR pszDeviceName, BOOL bInServerProcess, DWORD dwClientThreadId);
HRESULT _stdcall RequestUnlock(ACTIVE_DEVICE *pDevice, BOOL bClosePort = TRUE);
HRESULT _stdcall LockDevice(ACTIVE_DEVICE *pDevice);
HRESULT _stdcall UnlockDevice(ACTIVE_DEVICE *pDevice);
VOID AutoUnlock();
VOID UpdateLockInfoStatus(ACTIVE_DEVICE *pDevice, LONG *pWaitTime, BOOL *pbMustSchedule);
HRESULT ClearLockInfo(LockInfo *pLockInfo);
private:
//
// Private helpers
//
HRESULT RequestLockHelper(ACTIVE_DEVICE *pDevice, ULONG ulTimeOut, BOOL bInServerProcess, DWORD dwClientThreadId);
HRESULT RequestUnlockHelper(ACTIVE_DEVICE *pDevice, BOOL bInServerProcess, DWORD dwClientThreadId);
HRESULT CreateLockInfo(ACTIVE_DEVICE *pDevice);
HRESULT CheckDeviceInfo(ACTIVE_DEVICE *pDevice);
#ifdef USE_ROT
HRESULT WriteCookieNameToRegistry(CHAR *szCookieName);
VOID DeleteCookieFromRegistry();
#endif
//
// Private Data
//
LONG m_cRef; // Ref count
DWORD m_dwCookie; // Cookie identifying location in ROT
BOOL m_bSched; // Indicates whether the UnlockCallback has
// been scheduled
LONG m_lSchedWaitTime; // Amount of time we told Scheduler to wait
// before calling us back
};
#ifdef DECLARE_LOCKMGR
StiLockMgr *g_pStiLockMgr;
#else
extern StiLockMgr *g_pStiLockMgr;
#endif
//
// Callback functions
//
VOID WINAPI UnlockTimedCallback(VOID *pCallbackInfo);
VOID WINAPI EnumDeviceCallback(ACTIVE_DEVICE *pDevice, VOID *pContext);
#endif
| 31.422535 | 119 | 0.579337 | [
"object"
] |
54c1b4bc026e33c82977246368e3b2763693818f | 828 | h | C | src/dataStructures.h | phil-ludewig/SensorFusionND_Camera_2D_Feature_Tracking | a6907ea1f8c0d7558af31eb60ebecd7a428f74c8 | [
"MIT"
] | null | null | null | src/dataStructures.h | phil-ludewig/SensorFusionND_Camera_2D_Feature_Tracking | a6907ea1f8c0d7558af31eb60ebecd7a428f74c8 | [
"MIT"
] | null | null | null | src/dataStructures.h | phil-ludewig/SensorFusionND_Camera_2D_Feature_Tracking | a6907ea1f8c0d7558af31eb60ebecd7a428f74c8 | [
"MIT"
] | null | null | null | #ifndef dataStructures_h
#define dataStructures_h
#include <vector>
#include <opencv2/core.hpp>
struct DataFrame { // represents the available sensor information at the same time instance
cv::Mat cameraImg; // camera image
std::vector<cv::KeyPoint> keypoints; // 2D keypoints within camera image
cv::Mat descriptors; // keypoint descriptors
std::vector<cv::DMatch> kptMatches; // keypoint matches between previous and current frame
};
struct PerformanceStatistic {
int keypointsTotal[10];
int keypointsROI[10];
int keypointsMatched[10]; // for project, use BF matching and descriptor distance ratio 0.8
std::string detectorType;
std::string descriptorType;
double detectionTime[10];
double descriptionTime[10];
double combinedTime[10];
};
#endif /* dataStructures_h */
| 25.090909 | 95 | 0.729469 | [
"vector"
] |
54c33929530817cadc58ded61f5b4c68e92777c5 | 1,964 | h | C | src/Game/GHHeightFieldOMeshLoader.h | GoldenHammerSoftware/GH | 757213f479c0fc80ed1a0f59972bf3e9d92b7526 | [
"MIT"
] | null | null | null | src/Game/GHHeightFieldOMeshLoader.h | GoldenHammerSoftware/GH | 757213f479c0fc80ed1a0f59972bf3e9d92b7526 | [
"MIT"
] | null | null | null | src/Game/GHHeightFieldOMeshLoader.h | GoldenHammerSoftware/GH | 757213f479c0fc80ed1a0f59972bf3e9d92b7526 | [
"MIT"
] | null | null | null | // Copyright Golden Hammer Software
#pragma once
#include "GHMath/GHPoint.h"
#include <vector>
#include "GHHeightFieldMeshDesc.h"
#include "GHString/GHIdentifierMap.h"
class GHModel;
class GHHeightField;
class GHXMLNode;
class GHXMLObjFactory;
class GHStringIdFactory;
class GHVBFactory;
class GHHeightFieldOMeshBucket;
class GHThreadFactory;
class GHResourceFactory;
class GHTextureWorldMap;
// looks at a heightfield and creates an optimized set of meshes.
class GHHeightFieldOMeshLoader
{
public:
GHHeightFieldOMeshLoader(GHXMLObjFactory& objFactory, const GHStringIdFactory& hashTable,
GHVBFactory& vbFactory, const GHThreadFactory& threadFactory,
const GHIdentifierMap<int>& enumMap,
GHResourceFactory& resFactory);
void createRenderable(GHModel& ret, const GHHeightField& hf, const GHXMLNode& node) const;
private:
// create minimum mesh buckets containing only the corner nodes.
void createStarterBuckets(std::vector<GHHeightFieldOMeshBucket*>& buckets,
GHModel& ret,
const GHHeightField& hf,
const GHXMLNode& node,
GHTextureWorldMap* weightMap) const;
// remove unimportant nodes to the mesh until we're as complex as we care to be.
void simplifyMesh(std::vector<GHHeightFieldOMeshBucket*>& buckets,
const GHHeightField& hf) const;
// create something that can draw all of our mesh buckets.
void createMeshRenderable(std::vector<GHHeightFieldOMeshBucket*>& buckets,
GHModel& ret,
const GHHeightField& hf,
const float* uv) const;
private:
GHXMLObjFactory& mObjFactory;
const GHStringIdFactory& mIdFactory;
GHVBFactory& mVBFactory;
const GHThreadFactory& mThreadFactory;
const GHIdentifierMap<int>& mEnumMap;
GHResourceFactory& mResourceFactory;
};
| 34.45614 | 94 | 0.692974 | [
"mesh",
"vector"
] |
54cb1433e84db3be218ae36f7a2668ec1fe2daed | 3,785 | h | C | src/qt/qtwebkit/Source/WebCore/Modules/indexeddb/IDBObjectStoreBackendImpl.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/Modules/indexeddb/IDBObjectStoreBackendImpl.h | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtwebkit/Source/WebCore/Modules/indexeddb/IDBObjectStoreBackendImpl.h | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | 1 | 2022-02-18T10:41:38.000Z | 2022-02-18T10:41:38.000Z | /*
* Copyright (C) 2011 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:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef IDBObjectStoreBackendImpl_h
#define IDBObjectStoreBackendImpl_h
#include "IDBBackingStore.h"
#include "IDBDatabaseBackendImpl.h"
#include "IDBKeyPath.h"
#include "IDBMetadata.h"
#include <wtf/HashMap.h>
#include <wtf/text/StringHash.h>
#if ENABLE(INDEXED_DATABASE)
namespace WebCore {
class IDBDatabaseBackendImpl;
class IDBTransactionBackendImpl;
struct IDBObjectStoreMetadata;
// FIXME: this namespace is temporary until we move its contents out to their own home.
namespace IDBObjectStoreBackendImpl {
class IndexWriter {
public:
explicit IndexWriter(const IDBIndexMetadata& indexMetadata)
: m_indexMetadata(indexMetadata)
{ }
IndexWriter(const IDBIndexMetadata& indexMetadata, const IDBDatabaseBackendInterface::IndexKeys& indexKeys)
: m_indexMetadata(indexMetadata)
, m_indexKeys(indexKeys)
{ }
bool verifyIndexKeys(IDBBackingStore&, IDBBackingStore::Transaction*, int64_t databaseId, int64_t objectStoreId, int64_t indexId, bool& canAddKeys, const IDBKey* primaryKey = 0, String* errorMessage = 0) const WARN_UNUSED_RETURN;
void writeIndexKeys(const IDBBackingStore::RecordIdentifier&, IDBBackingStore&, IDBBackingStore::Transaction*, int64_t databaseId, int64_t objectStoreId) const;
private:
bool addingKeyAllowed(IDBBackingStore&, IDBBackingStore::Transaction*, int64_t databaseId, int64_t objectStoreId, int64_t indexId, const IDBKey* indexKey, const IDBKey* primaryKey, bool& allowed) const WARN_UNUSED_RETURN;
const IDBIndexMetadata m_indexMetadata;
IDBDatabaseBackendInterface::IndexKeys m_indexKeys;
};
bool makeIndexWriters(PassRefPtr<IDBTransactionBackendImpl>, IDBBackingStore*, int64_t databaseId, const IDBObjectStoreMetadata&, PassRefPtr<IDBKey> primaryKey, bool keyWasGenerated, const Vector<int64_t>& indexIds, const Vector<IDBDatabaseBackendInterface::IndexKeys>&, Vector<OwnPtr<IndexWriter> >* indexWriters, String* errorMessage, bool& completed) WARN_UNUSED_RETURN;
PassRefPtr<IDBKey> generateKey(PassRefPtr<IDBBackingStore>, PassRefPtr<IDBTransactionBackendImpl>, int64_t databaseId, int64_t objectStoreId);
bool updateKeyGenerator(PassRefPtr<IDBBackingStore>, PassRefPtr<IDBTransactionBackendImpl>, int64_t databaseId, int64_t objectStoreId, const IDBKey*, bool checkCurrent);
};
} // namespace WebCore
#endif
#endif // IDBObjectStoreBackendImpl_h
| 47.3125 | 377 | 0.777807 | [
"vector"
] |
54d16e27b42ec4802b4143abdf60a59a72419796 | 81,721 | c | C | drivers/misc/vchiq/slots.c | christopherco/rpi-iotcore | 2cf15e428e743dd7f7742f7511725741640c5be3 | [
"MIT"
] | 89 | 2018-12-22T15:34:45.000Z | 2021-12-16T20:07:29.000Z | drivers/misc/vchiq/slots.c | christopherco/rpi-iotcore | 2cf15e428e743dd7f7742f7511725741640c5be3 | [
"MIT"
] | 22 | 2016-01-23T04:03:56.000Z | 2018-11-16T21:45:10.000Z | drivers/misc/vchiq/slots.c | christopherco/rpi-iotcore | 2cf15e428e743dd7f7742f7511725741640c5be3 | [
"MIT"
] | 42 | 2016-02-18T21:55:54.000Z | 2018-11-27T07:12:01.000Z | //
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Module Name:
//
// slots.c
//
// Abstract:
//
// Vchiq slots operation implementation.
//
#include "precomp.h"
#include "trace.h"
#include "slots.tmh"
#include "slotscommon.h"
#include "device.h"
#include "file.h"
#include "memory.h"
#include "transfer.h"
#include "slots.h"
VCHIQ_PAGED_SEGMENT_BEGIN
/*++
Routine Description:
Initialize VCHIQ, setup master and slave slot
Arguments:
DeviceContextPtr - A pointer to the device context.
Return Value:
NTSTATUS
--*/
_Use_decl_annotations_
NTSTATUS VchiqInit (
DEVICE_CONTEXT* DeviceContextPtr
)
{
NTSTATUS status;
OBJECT_ATTRIBUTES objectAttributes;
ULONG slotMemorySize = (VCHIQ_DEFAULT_TOTAL_SLOTS * VCHIQ_SLOT_SIZE);
// 2 * (cache line size) * (max fragments)
// cache line is based on cache-line-size = <32> at bcm2835-rpi.dtsi
ULONG fragMemorySize = 2 * 32 * VCHIQ_MAX_FRAGMENTS;
ULONG totalMemorySize = slotMemorySize + fragMemorySize;
PAGED_CODE();
// Allocated slot memory
status = VchiqAllocPhyContiguous(
DeviceContextPtr,
totalMemorySize,
&DeviceContextPtr->SlotZeroPtr);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR("Fail to allocate slot memory");
status = STATUS_INSUFFICIENT_RESOURCES;
goto End;
}
RtlZeroMemory(DeviceContextPtr->SlotZeroPtr, totalMemorySize);
// Get the slot physical memory
DeviceContextPtr->SlotMemoryPhy =
MmGetPhysicalAddress(DeviceContextPtr->SlotZeroPtr);
ULONG slotMemoryPhy = DeviceContextPtr->SlotMemoryPhy.LowPart
+ OFFSET_DIRECT_SDRAM;
// Initialize slot
ULONG memAlign =
(VCHIQ_SLOT_SIZE - (ULONG)DeviceContextPtr->SlotZeroPtr)
& VCHIQ_SLOT_MASK;
VCHIQ_SLOT_ZERO* slotZeroPtr = (VCHIQ_SLOT_ZERO*)
((UCHAR*)DeviceContextPtr->SlotZeroPtr + memAlign);
ULONG numSlots = (totalMemorySize - memAlign) / VCHIQ_SLOT_SIZE;
ULONG firstDataSlot = VCHIQ_SLOT_ZERO_SLOTS;
numSlots -= firstDataSlot;
slotZeroPtr->Magic = VCHIQ_MAGIC;
slotZeroPtr->Version = VCHIQ_VERSION;
slotZeroPtr->VersionMin = VCHIQ_VERSION_MIN;
slotZeroPtr->SlotZeroSize = sizeof(VCHIQ_SLOT_ZERO);
slotZeroPtr->SlotSize = VCHIQ_SLOT_SIZE;
slotZeroPtr->MaxSlots = VCHIQ_MAX_SLOTS;
slotZeroPtr->MaxSlotsPerSide = VCHIQ_MAX_SLOTS_PER_SIDE;
slotZeroPtr->Master.SlotSync = firstDataSlot;
slotZeroPtr->Master.SlotFirst = firstDataSlot + 1;
slotZeroPtr->Master.SlotLast = firstDataSlot + (numSlots / 2) - 1;
slotZeroPtr->Slave.SlotSync = firstDataSlot + (numSlots / 2);
slotZeroPtr->Slave.SlotFirst = firstDataSlot + (numSlots / 2) + 1;
slotZeroPtr->Slave.SlotLast = firstDataSlot + numSlots - 1;
// Enable trigger and recycle event
VCHIQ_ENABLE_EVENT_INTERRUPT(&slotZeroPtr->Slave.Trigger);
VCHIQ_ENABLE_EVENT_INTERRUPT(&slotZeroPtr->Slave.Recycle);
// Currently do not support synchronous message operation with the firmware
#ifdef SUPPORT_SYNC_OPERATION
VCHIQ_ENABLE_EVENT_INTERRUPT(&slotZeroPtr->Slave.SyncTrigger);
VCHIQ_ENABLE_EVENT_INTERRUPT(&slotZeroPtr->Slave.SyncRelease);
#endif
// Now that we have setup the slave slot we can mark it as initialized
slotZeroPtr->Slave.Initialised = 1;
// Initialize the circular buffer slot queue
{
ULONG i = 0;
for (ULONG slotCount = slotZeroPtr->Slave.SlotFirst;
slotCount <= slotZeroPtr->Slave.SlotLast;
++slotCount, ++i) {
slotZeroPtr->Slave.SlotQueue[i] = slotCount;
}
ULONG totalTxSlot = i - 1;
KeInitializeSemaphore(
&DeviceContextPtr->AvailableTxSlot,
totalTxSlot,
totalTxSlot);
DeviceContextPtr->RecycleTxSlotIndex = totalTxSlot;
slotZeroPtr->Slave.SlotQueueRecycle = totalTxSlot;
InterlockedExchange(
&DeviceContextPtr->AvailableTxSlotCount,
totalTxSlot);
}
DeviceContextPtr->SlotZeroPtr = slotZeroPtr;
// Setup fragment
slotZeroPtr->PlatformData[VCHIQ_PLATFORM_FRAGMENTS_OFFSET_IDX] =
slotMemoryPhy + slotMemorySize;
slotZeroPtr->PlatformData[VCHIQ_PLATFORM_FRAGMENTS_COUNT_IDX] =
VCHIQ_MAX_FRAGMENTS;
{
UCHAR* fragmentBasePtr =
((UCHAR*)DeviceContextPtr->SlotZeroPtr + slotMemorySize);
ULONG i;
for (i = 0; i < (VCHIQ_MAX_FRAGMENTS - 1); ++i) {
*(UCHAR **)&fragmentBasePtr[i * 2 * 32] =
&fragmentBasePtr[(i + 1) * (2 * 32)];
}
*(char **)&fragmentBasePtr[i * (2 * 32)] = NULL;
}
// Initialize all the slot processing threads and locks
ExInitializeFastMutex(&DeviceContextPtr->TxSlotMutex);
ExInitializeFastMutex(&DeviceContextPtr->RecycleSlotMutex);
// Initialize event and thread objects
KeInitializeEvent(
&DeviceContextPtr->VchiqThreadEventStop,
NotificationEvent,
FALSE);
InitializeObjectAttributes(
&objectAttributes,
NULL,
OBJ_KERNEL_HANDLE,
NULL,
NULL);
PKSTART_ROUTINE startRoutine[] =
{
VchiqTriggerThreadRoutine,
VchiqRecycleThreadRoutine,
VchiqSyncThreadRoutine,
VchiqSyncReleaseThreadRoutine,
};
for (ULONG threadCount = 0;
threadCount < THREAD_MAX_SUPPORTED;
++threadCount) {
KeInitializeEvent(
&DeviceContextPtr->VchiqThreadEvent[threadCount],
SynchronizationEvent,
FALSE);
status = PsCreateSystemThread(
&DeviceContextPtr->VchiqThreadHandle[threadCount],
THREAD_ALL_ACCESS,
&objectAttributes,
NULL,
NULL,
startRoutine[threadCount],
(VOID*)DeviceContextPtr);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"Failed to start PsCreateSystemThread (%d) %!STATUS!",
threadCount,
status);
goto End;
}
status = ObReferenceObjectByHandleWithTag (
DeviceContextPtr->VchiqThreadHandle[threadCount],
THREAD_ALL_ACCESS,
*PsThreadType,
KernelMode,
VCHIQ_ALLOC_TAG_GLOBAL_OBJ,
&DeviceContextPtr->VchiqThreadObj[threadCount],
NULL);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"ObReferenceObjectByHandle (%d) failed %!STATUS!",
threadCount,
status);
goto End;
}
ZwClose(DeviceContextPtr->VchiqThreadHandle[threadCount]);
DeviceContextPtr->VchiqThreadHandle[threadCount] = NULL;
}
End:
return status;
}
/*++
Routine Description:
Release VCHIQ related resource.
Arguments:
DeviceContextPtr - A pointer to the device context.
Return Value:
NTSTATUS
--*/
_Use_decl_annotations_
NTSTATUS VchiqRelease (
DEVICE_CONTEXT* DeviceContextPtr
)
{
PAGED_CODE();
VchiqFreePhyContiguous(
DeviceContextPtr,
&DeviceContextPtr->SlotZeroPtr);
for (ULONG threadCount = 0;
threadCount < THREAD_MAX_SUPPORTED;
++threadCount) {
if (DeviceContextPtr->VchiqThreadObj[threadCount]) {
NTSTATUS status;
LARGE_INTEGER timeout;
(void)KeSetEvent(&DeviceContextPtr->VchiqThreadEventStop, 0, FALSE);
timeout.QuadPart = WDF_REL_TIMEOUT_IN_MS(1000);
status = KeWaitForSingleObject(
DeviceContextPtr->VchiqThreadObj[threadCount],
Executive,
KernelMode,
FALSE,
&timeout);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"KeWaitForSingleObject for thread (%d) failed %!STATUS!",
threadCount,
status);
}
ObDereferenceObject(DeviceContextPtr->VchiqThreadObj[threadCount]);
DeviceContextPtr->VchiqThreadObj[threadCount] = NULL;
}
if (DeviceContextPtr->VchiqThreadHandle[threadCount]) {
ZwClose(DeviceContextPtr->VchiqThreadHandle[threadCount]);
DeviceContextPtr->VchiqThreadHandle[threadCount] = NULL;
}
}
return STATUS_SUCCESS;
}
/*++
Routine Description:
Signals VC that there is a pending slot to be processed.
Arguments:
DeviceContextPtr - A pointer to the device context.
EventPtr - Pointer to the event to be signalled
Return Value:
NTSTATUS
--*/
_Use_decl_annotations_
NTSTATUS VchiqSignalVC (
DEVICE_CONTEXT* DeviceContextPtr,
VCHIQ_REMOTE_EVENT* EventPtr
)
{
PAGED_CODE();
// Indicate that we to VC side that the event has been triggered
EventPtr->Fired = 1;
if (EventPtr->Armed) {
WRITE_REGISTER_NOFENCE_ULONG(
(ULONG*)(DeviceContextPtr->VchiqRegisterPtr + BELL2), 0);
}
return STATUS_SUCCESS;
}
/*++
Routine Description:
Acquire next location to insert a new message. Depending on size
and current location a new slot maybe used. This function should
be called within TxSlotMutex.
Arguments:
DeviceContextPtr - A pointer to the device context.
VchiqFileContextPtr - File context pointer returned to caller
RequestSize - Message Suze
SyncAcquire - Determine if the message would be sent synchronously
HeaderPPtr - Pointer that would assigned to the next available slot
location within the transfer slot.
Return Value:
NTSTATUS
--*/
_Use_decl_annotations_
NTSTATUS VchiqAcquireTxSpace (
DEVICE_CONTEXT* DeviceContextPtr,
VCHIQ_FILE_CONTEXT* VchiqFileContextPtr,
ULONG RequestSize,
BOOLEAN SyncAcquire,
VCHIQ_HEADER** HeaderPPtr
)
{
ULONG availSlotSpace;
ULONG actualBufferSize;
NTSTATUS status;
PAGED_CODE();
actualBufferSize = VCHIQ_GET_SLOT_ALIGN_SIZE(RequestSize);
availSlotSpace =
VCHIQ_SLOT_SIZE - (DeviceContextPtr->CurrentTxPos & VCHIQ_SLOT_MASK);
// Slot messages are expected to be 8 byte align so there should always be
// enough space to fit a header information
NT_ASSERT(availSlotSpace >= sizeof(VCHIQ_HEADER));
// If the current slot does not have sufficient space fill it up with
// padding and proceed to the next slot
if (actualBufferSize > availSlotSpace) {
VCHIQ_HEADER* tempHeaderPtr =
VCHIQ_GET_CURRENT_TX_HEADER(DeviceContextPtr);
tempHeaderPtr->MsgId = VCHIQ_MSGID_PADDING;
tempHeaderPtr->Size = availSlotSpace - sizeof(VCHIQ_HEADER);
DeviceContextPtr->CurrentTxPos += availSlotSpace;
}
// Process the next available slot if previous slot is all fill up
if ((DeviceContextPtr->CurrentTxPos & VCHIQ_SLOT_MASK) == 0) {
LARGE_INTEGER waitAvailableTxSlotTimeout;
waitAvailableTxSlotTimeout.QuadPart = -1 * 1000000;
status = VchiqWaitForEvents(
(VOID*)&DeviceContextPtr->AvailableTxSlot,
&VchiqFileContextPtr->FileEventStop,
(SyncAcquire) ? NULL : &waitAvailableTxSlotTimeout);
switch (status)
{
case STATUS_TIMEOUT:
*HeaderPPtr = NULL;
status = STATUS_INSUFFICIENT_RESOURCES;
VCHIQ_LOG_WARNING(
"No slot available size %d. Slot count %d",
RequestSize,
DeviceContextPtr->AvailableTxSlotCount);
goto End;
case STATUS_WAIT_1:
*HeaderPPtr = NULL;
status = STATUS_UNSUCCESSFUL;
VCHIQ_LOG_WARNING(
"File handle not active anymore %d",
RequestSize);
goto End;
}
InterlockedDecrement(&DeviceContextPtr->AvailableTxSlotCount);
ULONG slotIndex = VCHIQ_GET_NEXT_TX_SLOT_INDEX(
DeviceContextPtr);
DeviceContextPtr->SlaveCurrentSlot =
(UCHAR*)VCHIQ_GET_HEADER_BY_GLOBAL_INDEX(
DeviceContextPtr,
slotIndex);
}
*HeaderPPtr = VCHIQ_GET_CURRENT_TX_HEADER(DeviceContextPtr);
DeviceContextPtr->CurrentTxPos += actualBufferSize;
status = STATUS_SUCCESS;
End:
return status;
}
/*++
Routine Description:
Process the slot when VC fires a trigger interrupt
Arguments:
DeviceContextPtr - A pointer to the device context.
Return Value:
NTSTATUS
--*/
_Use_decl_annotations_
NTSTATUS VchiqProcessRxSlot (
DEVICE_CONTEXT* DeviceContextPtr
)
{
NTSTATUS status;
VCHIQ_SLOT_ZERO* slotZeroPtr;
VCHIQ_FILE_CONTEXT* vchiqFileContextPtr;
PAGED_CODE();
slotZeroPtr = DeviceContextPtr->SlotZeroPtr;
// Attempt to parse updated received messages
while (DeviceContextPtr->CurrentRxPos < slotZeroPtr->Master.TxPos) {
if (DeviceContextPtr->MasterCurrentSlot == NULL) {
DeviceContextPtr->MasterCurrentSlotIndex =
VCHIQ_GET_NEXT_RX_SLOT_INDEX(
DeviceContextPtr);
DeviceContextPtr->MasterCurrentSlot =
(UCHAR*)VCHIQ_GET_HEADER_BY_GLOBAL_INDEX(
DeviceContextPtr,
DeviceContextPtr->MasterCurrentSlotIndex);
SLOT_INFO* currentSlotPtr = &DeviceContextPtr->RxSlotInfo[
DeviceContextPtr->MasterCurrentSlotIndex];
currentSlotPtr->SlotInUse = TRUE;
}
VCHIQ_HEADER* rxHeader =
VCHIQ_GET_CURRENT_RX_HEADER(DeviceContextPtr);
ULONG armPortNum = VCHIQ_MSG_DSTPORT(rxHeader->MsgId);
vchiqFileContextPtr = DeviceContextPtr->ArmPortHandles[armPortNum];
switch (VCHIQ_MSG_TYPE(rxHeader->MsgId))
{
case VCHIQ_MSG_OPEN:
{
VCHIQ_LOG_WARNING(
"Unsupported message 0x%08x (%S) size 0x%08x",
rxHeader->MsgId,
VCHIQ_MESSAGE_NAME(rxHeader->MsgId),
rxHeader->Size);
}
break;
case VCHIQ_MSG_OPENACK:
{
if (vchiqFileContextPtr == NULL) {
VCHIQ_LOG_ERROR(
"Unknown VCHIQ_MSG_OPENACK 0x%08x (%S) size 0x%08x",
rxHeader->MsgId,
VCHIQ_MESSAGE_NAME(rxHeader->MsgId),
rxHeader->Size);
break;
}
vchiqFileContextPtr->VCHIQPortNumber =
VCHIQ_MSG_SRCPORT(rxHeader->MsgId);
{
WDFREQUEST nextRequest;
status = WdfIoQueueRetrieveNextRequest(
vchiqFileContextPtr->FileQueue[FILE_QUEUE_CREATE_SERVICE],
&nextRequest);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_WARNING(
"WdfIoQueueRetrieveNextRequest failed %!STATUS!",
status);
break;
}
InterlockedExchange(
&vchiqFileContextPtr->State,
SERVICE_STATE_OPEN);
WdfRequestComplete(nextRequest, STATUS_SUCCESS);
}
}
break;
case VCHIQ_MSG_CLOSE:
{
if (vchiqFileContextPtr == NULL) {
VCHIQ_LOG_WARNING(
"Unknown VCHIQ_MSG_CLOSE 0x%08x (%S) size 0x%08x",
rxHeader->MsgId,
VCHIQ_MESSAGE_NAME(rxHeader->MsgId),
rxHeader->Size);
break;
}
WDFREQUEST nextRequest;
status = WdfIoQueueRetrieveNextRequest(
vchiqFileContextPtr->FileQueue[FILE_QUEUE_CLOSE_SERVICE],
&nextRequest);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_WARNING(
"WdfIoQueueRetrieveNextRequest failed %!STATUS!",
status);
} else {
InterlockedExchange(
&vchiqFileContextPtr->State,
SERVICE_STATE_CLOSE);
WdfRequestComplete(nextRequest, STATUS_SUCCESS);
}
}
break;
case VCHIQ_MSG_DATA:
{
if (vchiqFileContextPtr == NULL) {
VCHIQ_LOG_ERROR(
"Unknown VCHIQ_MSG_DATA 0x%08x (%S) size 0x%08x",
rxHeader->MsgId,
VCHIQ_MESSAGE_NAME(rxHeader->MsgId),
rxHeader->Size);
break;
}
// Ignore zero length data
if (rxHeader->Size == 0) {
break;
}
status = VchiqProcessNewRxMsg(
DeviceContextPtr,
vchiqFileContextPtr,
rxHeader);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"VchiqProcessNewRxMsg failed %!STATUS!",
status);
break;
}
}
break;
case VCHIQ_MSG_CONNECT:
{
DeviceContextPtr->VCConnected = TRUE;
// Now that the we are connected with the firmware, go ahead
// and enable the device interface if it isnt already enabled
if (DeviceContextPtr->DeviceInterfaceEnabled == FALSE) {
status = WdfDeviceCreateDeviceInterface(
DeviceContextPtr->Device,
&VCHIQ_INTERFACE_GUID,
NULL);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"Fail to register device interface %!STATUS!",
status);
break;
}
WdfDeviceSetDeviceInterfaceState(
DeviceContextPtr->Device,
&VCHIQ_INTERFACE_GUID,
NULL,
TRUE);
DeviceContextPtr->DeviceInterfaceEnabled = TRUE;
}
}
break;
case VCHIQ_MSG_BULK_RX:
{
VCHIQ_LOG_WARNING(
"Unsupported message 0x%08x (%S) size 0x%08x",
rxHeader->MsgId,
VCHIQ_MESSAGE_NAME(rxHeader->MsgId),
rxHeader->Size);
}
break;
case VCHIQ_MSG_BULK_TX:
{
VCHIQ_LOG_WARNING(
"Unsupported message 0x%08x (%S) size 0x%08x",
rxHeader->MsgId,
VCHIQ_MESSAGE_NAME(rxHeader->MsgId),
rxHeader->Size);
}
break;
case VCHIQ_MSG_BULK_RX_DONE:
{
if (vchiqFileContextPtr == NULL) {
VCHIQ_LOG_ERROR(
"Unknown VCHIQ_MSG_BULK_RX_DONE 0x%08x (%S) size 0x%08x",
rxHeader->MsgId,
VCHIQ_MESSAGE_NAME(rxHeader->MsgId),
rxHeader->Size);
break;
}
{
WDFREQUEST nextRequest;
status = WdfIoQueueRetrieveNextRequest(
vchiqFileContextPtr->FileQueue[FILE_QUEUE_RX_DATA],
&nextRequest);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_WARNING(
"WdfIoQueueRetrieveNextRequest failed %!STATUS!",
status);
break;
}
ULONG* respondMsg = (ULONG*)(rxHeader + 1);
if (*respondMsg == 0xFFFFFFFF) {
WdfRequestComplete(nextRequest, STATUS_UNSUCCESSFUL);
} else {
VCHIQ_TX_REQUEST_CONTEXT* vchiqTxRequestContextPtr =
VchiqGetTxRequestContext(nextRequest);
if (vchiqTxRequestContextPtr != NULL) {
DMA_ADAPTER* dmaAdapterPtr =
vchiqFileContextPtr->DmaAdapterPtr;
dmaAdapterPtr->DmaOperations->FreeAdapterObject(
vchiqFileContextPtr->DmaAdapterPtr,
DeallocateObjectKeepRegisters);
dmaAdapterPtr->DmaOperations->PutScatterGatherList(
vchiqFileContextPtr->DmaAdapterPtr,
vchiqTxRequestContextPtr->ScatterGatherListPtr,
FALSE);
vchiqTxRequestContextPtr->ScatterGatherListPtr = NULL;
WdfRequestCompleteWithInformation(
nextRequest,
STATUS_SUCCESS,
MmGetMdlByteCount(vchiqTxRequestContextPtr->BufferMdlPtr));
} else {
WdfRequestComplete(nextRequest, STATUS_UNSUCCESSFUL);
}
}
}
status = VchiqProcessNewRxMsg(
DeviceContextPtr,
vchiqFileContextPtr,
rxHeader);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"VchiqProcessNewRxMsg failed %!STATUS!",
status);
break;
}
}
break;
case VCHIQ_MSG_BULK_TX_DONE:
{
if (vchiqFileContextPtr == NULL) {
VCHIQ_LOG_ERROR(
"Unknown VCHIQ_MSG_BULK_TX_DONE 0x%08x (%S) size 0x%08x",
rxHeader->MsgId,
VCHIQ_MESSAGE_NAME(rxHeader->MsgId),
rxHeader->Size);
break;
}
{
WDFREQUEST nextRequest;
status = WdfIoQueueRetrieveNextRequest(
vchiqFileContextPtr->FileQueue[FILE_QUEUE_TX_DATA],
&nextRequest);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_WARNING(
"WdfIoQueueRetrieveNextRequest failed %!STATUS!",
status);
break;
}
ULONG* respondMsg = (ULONG*)(rxHeader + 1);
if (*respondMsg == 0xFFFFFFFF) {
WdfRequestComplete(nextRequest, STATUS_UNSUCCESSFUL);
} else {
VCHIQ_TX_REQUEST_CONTEXT* vchiqTxRequestContextPtr =
VchiqGetTxRequestContext(nextRequest);
if (vchiqTxRequestContextPtr != NULL) {
DMA_ADAPTER* dmaAdapterPtr =
vchiqFileContextPtr->DmaAdapterPtr;
dmaAdapterPtr->DmaOperations->FreeAdapterObject(
vchiqFileContextPtr->DmaAdapterPtr,
DeallocateObjectKeepRegisters);
dmaAdapterPtr->DmaOperations->PutScatterGatherList(
vchiqFileContextPtr->DmaAdapterPtr,
vchiqTxRequestContextPtr->ScatterGatherListPtr,
TRUE);
vchiqTxRequestContextPtr->ScatterGatherListPtr = NULL;
WdfRequestCompleteWithInformation(
nextRequest,
STATUS_SUCCESS,
MmGetMdlByteCount(vchiqTxRequestContextPtr->BufferMdlPtr));
} else {
WdfRequestComplete(nextRequest, STATUS_UNSUCCESSFUL);
}
}
}
status = VchiqProcessNewRxMsg(
DeviceContextPtr,
vchiqFileContextPtr,
rxHeader);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"VchiqProcessNewRxMsg failed %!STATUS!",
status);
break;
}
}
break;
case VCHIQ_MSG_PADDING:
break;
case VCHIQ_MSG_PAUSE:
break;
case VCHIQ_MSG_RESUME:
break;
case VCHIQ_MSG_REMOTE_USE:
break;
case VCHIQ_MSG_REMOTE_RELEASE:
break;
case VCHIQ_MSG_REMOTE_USE_ACTIVE:
break;
default:
VCHIQ_LOG_WARNING(
"Invalid RX message 0x%08x (%S) size 0x%08x",
rxHeader->MsgId,
VCHIQ_MESSAGE_NAME(rxHeader->MsgId),
rxHeader->Size);
}
VCHIQ_LOG_INFORMATION(
"Process RX message 0x%08x (%S) size 0x%08x",
rxHeader->MsgId,
VCHIQ_MESSAGE_NAME(rxHeader->MsgId),
rxHeader->Size);
DeviceContextPtr->CurrentRxPos +=
VCHIQ_GET_SLOT_ALIGN_SIZE(rxHeader->Size + sizeof(VCHIQ_HEADER));
// Attempt to release the slot once we process the last message
if ((DeviceContextPtr->CurrentRxPos & VCHIQ_SLOT_MASK) == 0) {
ULONG slotNumber = DeviceContextPtr->MasterCurrentSlotIndex;
VchiqRecycleSlot(
DeviceContextPtr,
slotZeroPtr,
slotNumber,
TRUE);
DeviceContextPtr->MasterCurrentSlot = NULL;
}
VCHIQ_RESET_EVENT_SIGNAL(&slotZeroPtr->Slave.Trigger);
}
VCHIQ_ENABLE_EVENT_INTERRUPT(&slotZeroPtr->Slave.Trigger);
return STATUS_SUCCESS;
}
/*++
Routine Description:
Process queue that is freed by VC gpu. A recycle interrupt would be
generated when a queue becomes available
Arguments:
DeviceContextPtr - A pointer to the device context.
Return Value:
NTSTATUS
--*/
_Use_decl_annotations_
NTSTATUS VchiqProcessRecycleTxSlot (
DEVICE_CONTEXT* DeviceContextPtr
)
{
VCHIQ_SLOT_ZERO* slotZeroPtr;
ULONG currentAvailableSlot;
PAGED_CODE();
currentAvailableSlot = DeviceContextPtr->RecycleTxSlotIndex;
slotZeroPtr = DeviceContextPtr->SlotZeroPtr;
// Make available slots that is being recycle. We keep a local counter
// so we can figure the total slot to be recycled
while (currentAvailableSlot != slotZeroPtr->Slave.SlotQueueRecycle) {
// If required slot quota update can be implemented here
ULONG semaphoreSignal = KeReleaseSemaphore(
&DeviceContextPtr->AvailableTxSlot,
0,
1,
FALSE);
if (!semaphoreSignal) {
VCHIQ_LOG_INFORMATION("Tx slot now available");
}
++currentAvailableSlot;
InterlockedIncrement(&DeviceContextPtr->AvailableTxSlotCount);
VCHIQ_RESET_EVENT_SIGNAL(&slotZeroPtr->Slave.Recycle);
}
DeviceContextPtr->RecycleTxSlotIndex = currentAvailableSlot;
VCHIQ_ENABLE_EVENT_INTERRUPT(&slotZeroPtr->Slave.Recycle);
return STATUS_SUCCESS;
}
/*++
Routine Description:
Attempt to send message to VC asynchronously
Arguments:
DeviceContextPtr - A pointer to the device context.
VchiqFileContextPtr - File context pointer returned to caller
MessageId - Slot message id
BufferPtr - Pointer to message that would be dispatch to VC GPU
BufferSize - The buffer size of BufferPtr
Return Value:
NTSTATUS
--*/
_Use_decl_annotations_
NTSTATUS VchiqQueueMessageAsync (
DEVICE_CONTEXT* DeviceContextPtr,
VCHIQ_FILE_CONTEXT* VchiqFileContextPtr,
ULONG MessageId,
VOID* BufferPtr,
ULONG BufferSize
)
{
NTSTATUS status;
VCHIQ_HEADER* msgHeaderPtr;
PAGED_CODE();
ExAcquireFastMutex(&DeviceContextPtr->TxSlotMutex);
status = VchiqAcquireTxSpace(
DeviceContextPtr,
VchiqFileContextPtr,
sizeof(*msgHeaderPtr) + BufferSize,
FALSE,
&msgHeaderPtr);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"Fail to acquire a transfer slot %!STATUS!",
status);
goto End;
}
msgHeaderPtr->MsgId = MessageId;
msgHeaderPtr->Size = BufferSize;
VCHIQ_LOG_INFORMATION(
"Queue message id 0x%08x (%S) size 0x%08x",
msgHeaderPtr->MsgId,
VCHIQ_MESSAGE_NAME(msgHeaderPtr->MsgId),
msgHeaderPtr->Size);
if (BufferPtr != NULL && BufferSize != 0) {
++msgHeaderPtr;
RtlCopyMemory(msgHeaderPtr, BufferPtr, BufferSize);
}
// Safe to release mutex once we copied all the data over
ExReleaseFastMutex(&DeviceContextPtr->TxSlotMutex);
// Update transfer position and signal VC
{
VCHIQ_SLOT_ZERO* slotZeroPtr = DeviceContextPtr->SlotZeroPtr;
slotZeroPtr->Slave.TxPos = DeviceContextPtr->CurrentTxPos;
status = VchiqSignalVC(
DeviceContextPtr,
&slotZeroPtr->Master.Trigger);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"Fail to signal VC %!STATUS!",
status);
}
}
return status;
End:
ExReleaseFastMutex(&DeviceContextPtr->TxSlotMutex);
return status;
}
/*++
Routine Description:
Attempt to send multi element messate to VC asynchronously
Arguments:
DeviceContextPtr - A pointer to the device context.
VchiqFileContextPtr - File context pointer returned to caller
MessageId - Slot message id
ElementsPtr - Pointer to the multi element that would be
dispatch to VC GPU
Count - Total element to be sent
Return Value:
NTSTATUS
--*/
_Use_decl_annotations_
NTSTATUS VchiqQueueMultiElementAsync (
DEVICE_CONTEXT* DeviceContextPtr,
VCHIQ_FILE_CONTEXT* VchiqFileContextPtr,
ULONG MessageId,
VCHIQ_ELEMENT* ElementsPtr,
ULONG Count
)
{
NTSTATUS status;
ULONG totalMsgSize = 0;
VCHIQ_HEADER* msgHeaderPtr;
PAGED_CODE();
for (ULONG elementIndex = 0; elementIndex < Count; ++elementIndex) {
if (ElementsPtr[elementIndex].Size) {
ElementsPtr[elementIndex].Data = WdfMemoryGetBuffer(
ElementsPtr[elementIndex].WdfMemoryData,
NULL);
if (ElementsPtr[elementIndex].Data == NULL) {
VCHIQ_LOG_ERROR("Invalid element data pointer");
status = STATUS_INVALID_PARAMETER;
goto EndNoMutexLock;
}
totalMsgSize += ElementsPtr[elementIndex].Size;
}
}
ExAcquireFastMutex(&DeviceContextPtr->TxSlotMutex);
status = VchiqAcquireTxSpace(
DeviceContextPtr,
VchiqFileContextPtr,
sizeof(*msgHeaderPtr) + totalMsgSize,
FALSE,
&msgHeaderPtr);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"Fail to acquire a transfer slot %!STATUS!",
status);
goto End;
}
msgHeaderPtr->MsgId = MessageId;
msgHeaderPtr->Size = totalMsgSize;
VCHIQ_LOG_INFORMATION(
"Queue message id 0x%08x (%S) size 0x%08x",
msgHeaderPtr->MsgId,
VCHIQ_MESSAGE_NAME(msgHeaderPtr->MsgId),
msgHeaderPtr->Size);
++msgHeaderPtr;
for (ULONG elementIndex = 0; elementIndex < Count; ++elementIndex) {
if (ElementsPtr[elementIndex].Size) {
RtlCopyMemory(
msgHeaderPtr,
ElementsPtr[elementIndex].Data,
ElementsPtr[elementIndex].Size);
msgHeaderPtr += ElementsPtr[elementIndex].Size;
}
}
// Safe to release mutex once we copied all the data over
ExReleaseFastMutex(&DeviceContextPtr->TxSlotMutex);
// Update transfer position and signal VC
{
VCHIQ_SLOT_ZERO* slotZeroPtr = DeviceContextPtr->SlotZeroPtr;
slotZeroPtr->Slave.TxPos = DeviceContextPtr->CurrentTxPos;
status = VchiqSignalVC(
DeviceContextPtr,
&slotZeroPtr->Master.Trigger);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"Fail to signal VC %!STATUS!",
status);
}
}
EndNoMutexLock:
return status;
End:
ExReleaseFastMutex(&DeviceContextPtr->TxSlotMutex);
return status;
}
/*++
Routine Description:
VchiqProcessBulkTransfer would setup the necassary intermediate
state and memory and proceeds to perform the bulk transaction
Arguments:
DeviceContextPtr - A pointer to the device context.
VchiqFileContextPtr - File context pointer returned to caller
WdfRequest - Request framework object tied to this bulk transfer
BulkTransferPtr - Pointer to the current bulk transfer info
MsgDirection - Specify the direction of the bulk transfer
BufferMdl - Mdl pointer structer of the buffer
BufferSize - Size of data that would be transfered
Return Value:
NTSTATUS
--*/
_Use_decl_annotations_
NTSTATUS VchiqProcessBulkTransfer (
DEVICE_CONTEXT* DeviceContextPtr,
VCHIQ_FILE_CONTEXT* VchiqFileContextPtr,
WDFREQUEST WdfRequest,
VCHIQ_QUEUE_BULK_TRANSFER* BulkTransferPtr,
ULONG MsgDirection,
MDL* BufferMdl,
ULONG BufferSize
)
{
NTSTATUS status;
MSG_BULK_TYPE bulkType =
(MsgDirection == VCHIQ_MSG_BULK_TX) ?
MSG_BULK_TX : MSG_BULK_RX;
ULONG transactionType =
(MsgDirection == VCHIQ_MSG_BULK_TX) ?
FILE_QUEUE_TX_DATA : FILE_QUEUE_RX_DATA;
PAGED_CODE();
// Acquire a mutex here so we can serialize tracking of bulk transfer.
// On the firmware side it is gurantee to process all bulk in a serialize
// FIFO fashion. As long as we track the order correctly here we would not
// be out of sync.
ExAcquireFastMutex(&VchiqFileContextPtr->PendingBulkMsgMutex[bulkType]);
status = VchiqAddPendingBulkMsg(
VchiqFileContextPtr,
BulkTransferPtr,
(MsgDirection == VCHIQ_MSG_BULK_TX) ?
MSG_BULK_TX : MSG_BULK_RX);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"VchiqAddPendingBulkMsg failed (%!STATUS!)",
status);
goto End;
}
// Request needs to remain valid until memory has been succesfully DMA
// over to or from the firmware. Forward to a queue to be completed later
// so memory remains lock in physical memory. Premature completing the
// request could result in corruption (ie:jpeg decode).
status = WdfRequestForwardToIoQueue(
WdfRequest,
VchiqFileContextPtr->FileQueue[transactionType]);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"WdfRequestForwardToIoQueue failed (%!STATUS!)",
status);
NTSTATUS tempStatus;
tempStatus = VchiqRemovePendingBulkMsg(
VchiqFileContextPtr,
NULL,
bulkType,
FALSE,
NULL);
if (!NT_SUCCESS(tempStatus)) {
VCHIQ_LOG_ERROR(
"VchiqRemovePendingBulkMsg failed (%!STATUS!)",
tempStatus);
}
NT_ASSERT(NT_SUCCESS(tempStatus));
goto End;
}
status = VchiqBulkTransfer(
DeviceContextPtr,
VchiqFileContextPtr,
WdfRequest,
MsgDirection,
BufferMdl,
BufferSize,
VchiqFileContextPtr->ArmPortNumber,
VchiqFileContextPtr->VCHIQPortNumber);
if (!NT_SUCCESS(status)) {
NTSTATUS tempStatus;
WDFREQUEST removeRequest;
VCHIQ_LOG_ERROR(
"VchiqBulkTransfer failed (%!STATUS!)",
status);
tempStatus = VchiqRemovePendingBulkMsg(
VchiqFileContextPtr,
NULL,
bulkType,
FALSE,
NULL);
if (!NT_SUCCESS(tempStatus)) {
VCHIQ_LOG_ERROR(
"VchiqRemovePendingBulkMsg failed (%!STATUS!)",
tempStatus);
NT_ASSERT(NT_SUCCESS(tempStatus));
}
// Remove the request that was just inserted
tempStatus = WdfIoQueueRetrieveFoundRequest(
VchiqFileContextPtr->FileQueue[transactionType],
WdfRequest,
&removeRequest);
if (tempStatus == STATUS_NOT_FOUND) {
// Request not found, framework has has cancel the request just
// return success and request would not be completed
status = STATUS_SUCCESS;
} else if (!NT_SUCCESS(tempStatus)) {
VCHIQ_LOG_ERROR(
"WdfIoQueueRetrieveFoundRequest failed (%!STATUS!)",
tempStatus);
NT_ASSERT(NT_SUCCESS(tempStatus));
}
}
End:
ExReleaseFastMutex(&VchiqFileContextPtr->PendingBulkMsgMutex[bulkType]);
return status;
}
/*++
Routine Description:
Implementation of bulk transaction for both transmit and receive
Arguments:
DeviceContextPtr - A pointer to the device context.
VchiqFileContextPtr - File context pointer returned to caller
WdfRequest - Request framework object tied to this bulk transfer
MsgDirection - Specify the direction of the bulk transfer
BufferMdl - Mdl pointer structer of the buffer
BufferSize - Size of data that would be transfered
ArmPortNumber - Slave port number of the transfer
VchiqPortNumber - Master port number of the transfer
Return Value:
NTSTATUS
--*/
_Use_decl_annotations_
NTSTATUS VchiqBulkTransfer (
DEVICE_CONTEXT* DeviceContextPtr,
VCHIQ_FILE_CONTEXT* VchiqFileContextPtr,
WDFREQUEST WdfRequest,
ULONG MsgDirection,
MDL* BufferMdl,
ULONG BufferSize,
ULONG ArmPortNumber,
ULONG VchiqPortNumber
)
{
NTSTATUS status;
VCHIQ_PAGELIST* pageListPtr = NULL;
VCHIQ_TX_REQUEST_CONTEXT* vchiqTxRequestContextPtr;
DMA_ADAPTER* dmaAdapterPtr = VchiqFileContextPtr->DmaAdapterPtr;
ULONG scatterGatherListSize, numberOfMapRegisters;
WDFMEMORY scatterGatherWdfMemory = NULL;
WDFMEMORY dmaTransferContextPtr = NULL;
VOID* scatterGatherBufferPtr = NULL;
VOID* dmaTransferContextBufferPtr;
ULONG pageListSize = 0;
PHYSICAL_ADDRESS pageListPhyAddress = { 0 };
PAGED_CODE();
// Use the DMA api to get the right buffer list for DMA transfer as the
// recommended approach.
status = dmaAdapterPtr->DmaOperations->CalculateScatterGatherList(
dmaAdapterPtr,
BufferMdl,
MmGetMdlVirtualAddress(BufferMdl),
BufferSize,
&scatterGatherListSize,
&numberOfMapRegisters);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"CalculateScatterGatherList failed (%!STATUS!)",
status);
goto End;
}
// Allocate memory to hold the scatter gather list and transfer context
{
WDF_OBJECT_ATTRIBUTES attributes;
WDF_OBJECT_ATTRIBUTES_INIT(&attributes);
// Let the framework release the memory when request is completed
attributes.ParentObject = WdfRequest;
status = WdfMemoryCreate(
&attributes,
PagedPool,
VCHIQ_ALLOC_TAG_WDF,
scatterGatherListSize,
&scatterGatherWdfMemory,
&scatterGatherBufferPtr);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"WdfMemoryCreate (scatter gather list) failed (%!STATUS!)",
status);
goto End;
}
status = WdfMemoryCreate(
&attributes,
PagedPool,
VCHIQ_ALLOC_TAG_WDF,
DMA_TRANSFER_CONTEXT_SIZE_V1,
&dmaTransferContextPtr,
&dmaTransferContextBufferPtr);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"WdfMemoryCreate for transfer context failed (%!STATUS!)",
status);
goto End;
}
status = dmaAdapterPtr->DmaOperations->InitializeDmaTransferContext(
dmaAdapterPtr,
dmaTransferContextBufferPtr);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"InitializeDmaTransferContext failed (%!STATUS!)",
status);
goto End;
}
}
SCATTER_GATHER_LIST* scatterGatherListOutPtr;
status = dmaAdapterPtr->DmaOperations->BuildScatterGatherListEx(
dmaAdapterPtr,
DeviceContextPtr->PhyDeviceObjectPtr,
dmaTransferContextBufferPtr,
BufferMdl,
0,
BufferSize,
DMA_SYNCHRONOUS_CALLBACK,
NULL,
NULL,
(MsgDirection == VCHIQ_MSG_BULK_TX) ? TRUE : FALSE,
scatterGatherBufferPtr,
scatterGatherListSize,
NULL,
NULL,
&scatterGatherListOutPtr); // API requirement
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"BuildScatterGatherListEx failed (%!STATUS!)",
status);
goto End;
}
// Now allocate and setup a page list for buffer transmission
{
SCATTER_GATHER_LIST* scatterGatherListPtr = scatterGatherBufferPtr;
ULONG numPages = scatterGatherListPtr->NumberOfElements;
pageListSize = (numPages * sizeof(ULONG)) + sizeof(VCHIQ_PAGELIST);
status = VchiqAllocateCommonBuffer(
VchiqFileContextPtr,
pageListSize,
&pageListPtr,
&pageListPhyAddress);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR("Fail to alloc page list memory");
status = STATUS_INSUFFICIENT_RESOURCES;
goto End;
}
pageListPtr->Length = BufferSize;
pageListPtr->Type =
(MsgDirection == VCHIQ_MSG_BULK_TX) ?
PAGELIST_WRITE : PAGELIST_READ;
pageListPtr->Offset =
(USHORT)(scatterGatherListPtr->Elements[0].Address.LowPart
& (PAGE_SIZE - 1));
// Fill up page information for transfer with page address as required
// by the firmware. Firmware does not expect actual physical address.
// Running continuous pages is determined from individual element
// length value.
ULONG* pageListAddrPtr = pageListPtr->Addrs;
ULONG i;
for ( i = 0; i < scatterGatherListPtr->NumberOfElements; ++i) {
// Firmware does not support DMA transaction more than 16MB in
// running pages. This is an unlikely path so adding an assert
// to catch this
ASSERT(scatterGatherListPtr->Elements[i].Length <= 0x1000000);
*pageListAddrPtr =
(scatterGatherListPtr->Elements[i].Address.LowPart &
~(PAGE_SIZE - 1)) |
OFFSET_DIRECT_SDRAM |
BYTES_TO_PAGES(scatterGatherListPtr->Elements[i].Length) - 1;
++pageListAddrPtr;
}
}
status = VchiqAllocateTransferRequestObjContext(
DeviceContextPtr,
VchiqFileContextPtr,
WdfRequest,
BufferMdl,
pageListPtr,
pageListSize,
pageListPhyAddress,
(SCATTER_GATHER_LIST* )scatterGatherBufferPtr,
&vchiqTxRequestContextPtr);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"VchiqAllocateTransferRequestObjContext failed (%!STATUS!)",
status);
goto End;
}
// Buffer will be free when request object is released
pageListPtr = NULL;
// Dispatch message
{
ULONG bulkData[2];
bulkData[0] = pageListPhyAddress.LowPart | OFFSET_DIRECT_SDRAM;
bulkData[1] = BufferSize;
status = VchiqQueueMessageAsync(
DeviceContextPtr,
VchiqFileContextPtr,
VCHIQ_MAKE_MSG(MsgDirection, ArmPortNumber, VchiqPortNumber),
&bulkData,
sizeof(bulkData));
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"VchiqQueueMessageAsync failed with status %!STATUS!",
status);
goto End;
}
}
End:
if (!NT_SUCCESS(status)) {
if (pageListPtr) {
VchiqFreeCommonBuffer(
VchiqFileContextPtr,
pageListSize,
pageListPhyAddress,
pageListPtr);
}
}
return status;
}
/*++
Routine Description:
Process pending message when pending message request is sent from the client
Arguments:
DeviceContextPtr - Pointer to device context
VchiqFileContextPtr - File context pointer returned to caller
Return Value:
NTSTATUS
--*/
_Use_decl_annotations_
NTSTATUS VchiqProcessPendingMsg (
DEVICE_CONTEXT* DeviceContextPtr,
VCHIQ_FILE_CONTEXT* VchiqFileContextPtr
)
{
NTSTATUS status;
WDFREQUEST nextRequest;
PAGED_CODE();
if (IsListEmpty(&VchiqFileContextPtr->PendingDataMsgList)) {
status = STATUS_SUCCESS;
goto End;
}
status = WdfIoQueueRetrieveNextRequest(
VchiqFileContextPtr->FileQueue[FILE_QUEUE_PENDING_MSG],
&nextRequest);
if (status == STATUS_NO_MORE_ENTRIES) {
// Ok to return success here as userland might not have
// have a chance to request for more completion msg yet.
status = STATUS_SUCCESS;
goto End;
} else if (!NT_SUCCESS(status)) {
VCHIQ_LOG_WARNING(
"WdfIoQueueRetrieveNextRequest failed %!STATUS!",
status);
goto End;
}
status = VchiqRemovePendingMsg(
DeviceContextPtr,
VchiqFileContextPtr,
nextRequest);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_WARNING(
"VchiqRemovePendingMsg failed %!STATUS!",
status);
goto End;
}
End:
return status;
}
/*++
Routine Description:
Process pending vchi message when a dequeue request from client
is received
Arguments:
DeviceContextPtr - Pointer to device context
VchiqFileContextPtr - File context pointer returned to caller
Return Value:
NTSTATUS
--*/
_Use_decl_annotations_
NTSTATUS VchiqProcessPendingVchiMsg (
DEVICE_CONTEXT* DeviceContextPtr,
VCHIQ_FILE_CONTEXT* VchiqFileContextPtr
)
{
NTSTATUS status;
WDFREQUEST nextRequest;
PAGED_CODE();
if (IsListEmpty(&VchiqFileContextPtr->PendingVchiMsgList)) {
status = STATUS_SUCCESS;
goto End;
}
do {
status = WdfIoQueueRetrieveNextRequest(
VchiqFileContextPtr->FileQueue[FILE_QUEUE_PENDING_VCHI_MSG],
&nextRequest);
if (status == STATUS_NO_MORE_ENTRIES) {
// Ok to return success here as userland might not have
// have a chance to request to dequeue any msg yet.
status = STATUS_SUCCESS;
break;
} else if (!NT_SUCCESS(status)) {
VCHIQ_LOG_WARNING(
"WdfIoQueueRetrieveNextRequest failed %!STATUS!",
status);
break;
}
status = VchiqRemovePendingVchiMsg(
DeviceContextPtr,
VchiqFileContextPtr,
nextRequest);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_WARNING(
"VchiqRemovePendingVchiMsg failed %!STATUS!",
status);
break;
}
if (IsListEmpty(&VchiqFileContextPtr->PendingVchiMsgList)) {
status = STATUS_SUCCESS;
break;
}
} while (nextRequest != NULL);
End:
return status;
}
/*++
Routine Description:
VchiqAddRefMsg adds the ref count to a slot.
Arguments:
DeviceContextPtr - Pointer to device context
SlotNumber - Increment msg ref count for this slot number
Return Value:
NTSTATUS
--*/
_Use_decl_annotations_
NTSTATUS VchiqAddRefMsg (
DEVICE_CONTEXT* DeviceContextPtr,
ULONG SlotNumber
)
{
SLOT_INFO* slotPtr = &DeviceContextPtr->RxSlotInfo[SlotNumber];
PAGED_CODE();
InterlockedIncrement(&slotPtr->RefCount);
return STATUS_SUCCESS;
}
/*++
Routine Description:
VchiqReleaseMsg decrease the ref count to a slot and attempt
to recycle the slot.
Arguments:
DeviceContextPtr - Pointer to device context
SlotNumber - Decrrease msg ref count for this slot number
Return Value:
NTSTATUS
--*/
_Use_decl_annotations_
NTSTATUS VchiqReleaseMsg (
DEVICE_CONTEXT* DeviceContextPtr,
ULONG SlotNumber
)
{
SLOT_INFO* slotPtr = &DeviceContextPtr->RxSlotInfo[SlotNumber];
PAGED_CODE();
InterlockedDecrement(&slotPtr->RefCount);
// Check to see if the slot is available to be recycled
VchiqRecycleSlot(
DeviceContextPtr,
DeviceContextPtr->SlotZeroPtr,
SlotNumber,
FALSE);
return STATUS_SUCCESS;
}
/*++
Routine Description:
VchiqProcessNewRxMsg would take the latest rx message and add it
to the queue. It would then attempt to dispatch the message if
the client is waiting for a message completion.
Arguments:
DeviceContextPtr - Pointer to device context
VchiqFileContextPtr - File context pointer returned to caller
Msg - Pointer to the message from master
SlotNumber - Slot number that would be attempted to be recycled
Return Value:
NTSTATUS
--*/
_Use_decl_annotations_
NTSTATUS VchiqProcessNewRxMsg (
DEVICE_CONTEXT* DeviceContextPtr,
VCHIQ_FILE_CONTEXT* VchiqFileContextPtr,
VCHIQ_HEADER* RxMsg
)
{
NTSTATUS status;
PAGED_CODE();
ExAcquireFastMutex(&VchiqFileContextPtr->PendingDataMsgMutex);
status = VchiqAddPendingMsg(
DeviceContextPtr,
VchiqFileContextPtr,
RxMsg,
DeviceContextPtr->MasterCurrentSlotIndex);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"VchiqAddPendingMsg failed %!STATUS!",
status);
goto End;
}
status = VchiqProcessPendingMsg(
DeviceContextPtr,
VchiqFileContextPtr);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"VchiqAddPendingMsg failed %!STATUS!",
status);
goto End;
}
End:
ExReleaseFastMutex(&VchiqFileContextPtr->PendingDataMsgMutex);
return status;
}
/*++
Routine Description:
VchiqAddPendingMsg keeps track of pending message to a port number
and also adds a reference to the current slot.
Arguments:
DeviceContextPtr - Pointer to device context
VchiqFileContextPtr - File context pointer returned to caller
Msg - Pointer to the message from master
SlotNumber - Slot number of the current message
Return Value:
NTSTATUS
--*/
_Use_decl_annotations_
NTSTATUS VchiqAddPendingMsg (
DEVICE_CONTEXT* DeviceContextPtr,
VCHIQ_FILE_CONTEXT* VchiqFileContextPtr,
VCHIQ_HEADER* Msg,
ULONG SlotNumber
)
{
NTSTATUS status;
WDFMEMORY wdfMemoryNewPendingMsg = NULL;
PAGED_CODE();
NT_ASSERT(VchiqFileContextPtr->PendingMsgLookAsideMemory != NULL);
status = WdfMemoryCreateFromLookaside(
VchiqFileContextPtr->PendingMsgLookAsideMemory,
&wdfMemoryNewPendingMsg);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"WdfMemoryCreateFromLookaside failed %!STATUS!)",
status);
goto End;
}
size_t bufferSize;
VCHIQ_PENDING_MSG* newPendingMsgPtr;
newPendingMsgPtr = WdfMemoryGetBuffer(wdfMemoryNewPendingMsg, &bufferSize);
if (!NT_SUCCESS(status) || (bufferSize != sizeof(*newPendingMsgPtr))) {
VCHIQ_LOG_ERROR(
"WdfMemoryGetBuffer failed %!STATUS! size %d)",
status,
bufferSize);
goto End;
}
newPendingMsgPtr->Msg = Msg;
newPendingMsgPtr->SlotNumber = SlotNumber;
newPendingMsgPtr->WdfMemory = wdfMemoryNewPendingMsg;
InsertTailList(
&VchiqFileContextPtr->PendingDataMsgList,
&newPendingMsgPtr->ListEntry);
VchiqAddRefMsg(DeviceContextPtr, SlotNumber);
End:
if (!NT_SUCCESS(status)) {
if (wdfMemoryNewPendingMsg != NULL) {
WdfObjectDelete(wdfMemoryNewPendingMsg);
}
}
return status;
}
/*++
Routine Description:
VchiqRemovePendingMsg - Will remove pending message for a port number
and completes the request if a request object is provided.
Arguments:
DeviceContextPtr - Pointer to device context
VchiqFileContextPtr - File context pointer returned to caller
WdfRequest - Optional wdf request object. If provided pending messages
woudl be copied over to the output buffer.
Return Value:
NTSTATUS
--*/
_Use_decl_annotations_
NTSTATUS VchiqRemovePendingMsg (
DEVICE_CONTEXT* DeviceContextPtr,
VCHIQ_FILE_CONTEXT* VchiqFileContextPtr,
WDFREQUEST WdfRequest
)
{
NTSTATUS status;
LIST_ENTRY *nextListEntryPtr;
PAGED_CODE();
// Remove all pending message if a request object is not provided
if (WdfRequest == NULL) {
do {
nextListEntryPtr = RemoveTailList(
&VchiqFileContextPtr->PendingDataMsgList);
if (nextListEntryPtr ==
&VchiqFileContextPtr->PendingDataMsgList) {
break;
}
ULONG nextMsgSlotNumber =
CONTAINING_RECORD(
nextListEntryPtr, VCHIQ_PENDING_MSG, ListEntry)->SlotNumber;
VchiqReleaseMsg(DeviceContextPtr, nextMsgSlotNumber);
WdfObjectDelete(CONTAINING_RECORD(
nextListEntryPtr, VCHIQ_PENDING_MSG, ListEntry)->WdfMemory);
} while (nextListEntryPtr != NULL);
status = STATUS_SUCCESS;
goto End;
}
ULONG* totalMsgPtr;
size_t bufSize;
status = WdfRequestRetrieveOutputBuffer(
WdfRequest,
sizeof(*totalMsgPtr),
&totalMsgPtr,
&bufSize);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"WdfRequestRetrieveOutputBuffer failed %!STATUS! \
bufSize(%d)",
status,
bufSize);
goto CompleteRequest;
}
VCHIQ_AWAIT_COMPLETION* awaitCompletionPtr;
status = WdfRequestRetrieveInputBuffer(
WdfRequest,
sizeof(*awaitCompletionPtr),
&awaitCompletionPtr,
&bufSize);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"WdfRequestRetrieveInputBuffer failed %!STATUS! \
bufSize(%d)",
status,
bufSize);
goto CompleteRequest;
}
*totalMsgPtr = 0;
VCHIQ_COMPLETION_DATA* completionDataPtr =
WdfMemoryGetBuffer(
awaitCompletionPtr->WdfMemoryCompletion,
NULL);
do {
nextListEntryPtr = RemoveHeadList(
&VchiqFileContextPtr->PendingDataMsgList);
if (nextListEntryPtr ==
&VchiqFileContextPtr->PendingDataMsgList) {
break;
}
// Only copy over the message header is we have sufficient output buffer
VCHIQ_HEADER* nextMsgHeaderPtr =
CONTAINING_RECORD(
nextListEntryPtr, VCHIQ_PENDING_MSG, ListEntry)->Msg;
ULONG pendingMsgSize = nextMsgHeaderPtr->Size + sizeof(*nextMsgHeaderPtr);
if (pendingMsgSize > awaitCompletionPtr->MsgBufSize) {
InsertHeadList(
&VchiqFileContextPtr->PendingDataMsgList,
nextListEntryPtr);
break;
}
ULONG nextMsgSlotNumber =
CONTAINING_RECORD(
nextListEntryPtr, VCHIQ_PENDING_MSG, ListEntry)->SlotNumber;
// Return the reason we receive the message. This is redundant but
// userland expects this information. We return VCHIQ defined reason
// even for vchi service as userland would be responsible to translate
// it to equivalent vchi defined reason.
NTSTATUS tempStatus;
VCHIQ_BULK_MODE_T bulkMode;
BOOLEAN trackMsgForVchiService = FALSE;
BOOLEAN returnMsgToVchiService = TRUE;
switch (VCHIQ_MSG_TYPE(nextMsgHeaderPtr->MsgId))
{
case VCHIQ_MSG_DATA:
{
completionDataPtr[*totalMsgPtr].Reason =
VCHIQ_MESSAGE_AVAILABLE;
trackMsgForVchiService = TRUE;
}
break;
case VCHIQ_MSG_BULK_TX_DONE:
{
completionDataPtr[*totalMsgPtr].Reason =
VCHIQ_BULK_TRANSMIT_DONE;
ExAcquireFastMutex(
&VchiqFileContextPtr->PendingBulkMsgMutex[MSG_BULK_TX]);
// Suppress warning as OACR seem confused. Lock is acquired
// above but OACR still flags a warning. Warning does not occur
// in a Visual Studio build.
#pragma warning(suppress: 26110)
tempStatus = VchiqRemovePendingBulkMsg(
VchiqFileContextPtr,
&completionDataPtr[*totalMsgPtr],
MSG_BULK_TX,
FALSE,
&bulkMode);
ExReleaseFastMutex(
&VchiqFileContextPtr->PendingBulkMsgMutex[MSG_BULK_TX]);
if (!NT_SUCCESS(tempStatus)) {
VCHIQ_LOG_ERROR(
"VchiqRemovePendingBulkMsg failed %!STATUS!",
tempStatus);
returnMsgToVchiService = FALSE;
break;
}
// Do not return message if bulk transfer mode is blocking
// or no callback
if ((bulkMode == VCHIQ_BULK_MODE_BLOCKING) ||
(bulkMode == VCHIQ_BULK_MODE_NOCALLBACK)) {
returnMsgToVchiService = FALSE;
}
}
break;
case VCHIQ_MSG_BULK_RX_DONE:
{
completionDataPtr[*totalMsgPtr].Reason =
VCHIQ_BULK_RECEIVE_DONE;
ExAcquireFastMutex(
&VchiqFileContextPtr->PendingBulkMsgMutex[MSG_BULK_RX]);
tempStatus = VchiqRemovePendingBulkMsg(
VchiqFileContextPtr,
&completionDataPtr[*totalMsgPtr],
MSG_BULK_RX,
FALSE,
&bulkMode);
ExReleaseFastMutex(
&VchiqFileContextPtr->PendingBulkMsgMutex[MSG_BULK_RX]);
if (!NT_SUCCESS(tempStatus)) {
VCHIQ_LOG_ERROR(
"VchiqRemovePendingBulkMsg failed %!STATUS!",
tempStatus);
returnMsgToVchiService = FALSE;
break;
}
// Do not return message if bulk transfer mode is blocking
// or no callback
if ((bulkMode == VCHIQ_BULK_MODE_BLOCKING) ||
(bulkMode == VCHIQ_BULK_MODE_NOCALLBACK)) {
returnMsgToVchiService = FALSE;
}
}
break;
default:
VCHIQ_LOG_WARNING("Processing unknown message back to user");
break;
}
if (returnMsgToVchiService == TRUE) {
// Return the service pointer back to userland
VOID* msgBufferPtr =
WdfMemoryGetBuffer(
completionDataPtr[*totalMsgPtr].WdfMemoryBuffer,
NULL);
RtlCopyMemory(
msgBufferPtr,
nextMsgHeaderPtr,
pendingMsgSize);
completionDataPtr[*totalMsgPtr].ServiceUserData =
VchiqFileContextPtr->ServiceUserData;
++*totalMsgPtr;
}
if ((VchiqFileContextPtr->IsVchi) && (trackMsgForVchiService == TRUE)) {
ExAcquireFastMutex(&VchiqFileContextPtr->PendingVchiMsgMutex);
// For vchi based service we need to keep track of all message so it could
// be dequeue by the service in a separate IOCTL
status = VchiqAddPendingVchiMsg(
DeviceContextPtr,
VchiqFileContextPtr,
nextMsgHeaderPtr,
nextMsgSlotNumber);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"VchiqAddPendingVchiMsg failed %!STATUS!)",
status);
}
ExReleaseFastMutex(&VchiqFileContextPtr->PendingVchiMsgMutex);
}
WdfObjectDelete(CONTAINING_RECORD(
nextListEntryPtr, VCHIQ_PENDING_MSG, ListEntry)->WdfMemory);
VchiqReleaseMsg(DeviceContextPtr, nextMsgSlotNumber);
} while (*totalMsgPtr < awaitCompletionPtr->MsgBufCount);
if (*totalMsgPtr == 0) {
// Requeue the request if no completion msg to return back to caller
status = WdfRequestRequeue(WdfRequest);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"WdfRequestRequeue failed %!STATUS!",
status);
}
} else {
WdfRequestCompleteWithInformation(
WdfRequest,
STATUS_SUCCESS,
sizeof(ULONG));
ExAcquireFastMutex(&VchiqFileContextPtr->PendingVchiMsgMutex);
status = VchiqProcessPendingVchiMsg(
DeviceContextPtr,
VchiqFileContextPtr);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"VchiqProcessPendingVchiMsg failed %!STATUS!",
status);
}
ExReleaseFastMutex(&VchiqFileContextPtr->PendingVchiMsgMutex);
}
End:
return status;
CompleteRequest:
WdfRequestComplete(
WdfRequest,
status);
return status;
}
/*++
Routine Description:
VchiqAddPendingBulkMsg keeps track of bulk message. This function
needs to be lock so the order of bulk transmit is maintain.
Arguments:
VchiqFileContextPtr - File context pointer returned to caller
BulkTransferPtr - Pointer to the next pending bulk message to be added
to the list.
BulkType - Specify the type of bulk transfer
Return Value:
NTSTATUS
--*/
_Use_decl_annotations_
NTSTATUS VchiqAddPendingBulkMsg (
VCHIQ_FILE_CONTEXT* VchiqFileContextPtr,
VCHIQ_QUEUE_BULK_TRANSFER* BulkTransferPtr,
MSG_BULK_TYPE BulkType
)
{
NTSTATUS status;
WDFMEMORY wdfMemoryNewPendingMsg = NULL;
PAGED_CODE();
NT_ASSERT(VchiqFileContextPtr->PendingBulkMsgLookAsideMemory != NULL);
status = WdfMemoryCreateFromLookaside(
VchiqFileContextPtr->PendingBulkMsgLookAsideMemory,
&wdfMemoryNewPendingMsg);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"WdfMemoryCreateFromLookaside failed %!STATUS!)",
status);
goto End;
}
size_t bufferSize;
VCHIQ_PENDING_BULK_MSG* newPendingBulkTransferPtr;
newPendingBulkTransferPtr =
WdfMemoryGetBuffer(wdfMemoryNewPendingMsg, &bufferSize);
if (!NT_SUCCESS(status) || (bufferSize != sizeof(*newPendingBulkTransferPtr))) {
VCHIQ_LOG_ERROR(
"WdfMemoryGetBuffer failed %!STATUS! size %d)",
status,
bufferSize);
goto End;
}
newPendingBulkTransferPtr->WdfMemory = wdfMemoryNewPendingMsg;
newPendingBulkTransferPtr->Mode = BulkTransferPtr->Mode;
newPendingBulkTransferPtr->BulkUserData =
BulkTransferPtr->UserData;
InsertTailList(
&VchiqFileContextPtr->PendingBulkMsgList[BulkType],
&newPendingBulkTransferPtr->ListEntry);
End:
if (!NT_SUCCESS(status)) {
if (wdfMemoryNewPendingMsg != NULL) {
WdfObjectDelete(wdfMemoryNewPendingMsg);
}
}
return status;
}
/*++
Routine Description:
VchiqARemovePendingBulkMsg remove pending bulk message from the list.
Caller should acquire the appropriate PendingBulkMsgMutex resource.
Arguments:
VchiqFileContextPtr - File context pointer returned to caller
CompletionDataPtr - Pointer to a completion ddata structure which would be
populated with the next pending bulk transaction information. If this
pointer is NULL then the caller is requesting that one or all entry
would need to be remove based on RemoveAll value.
BulkType - Specify the type of bulk transfer
RemoveAll - A zero value means remove the last entry in tail. A non-zero
value means remove all entries.
Mode - Returns the bulk transder back to the caller if a pointer is provided
Return Value:
NTSTATUS
--*/
_Use_decl_annotations_
NTSTATUS VchiqRemovePendingBulkMsg (
VCHIQ_FILE_CONTEXT* VchiqFileContextPtr,
VCHIQ_COMPLETION_DATA* CompletionDataPtr,
MSG_BULK_TYPE BulkType,
ULONG RemoveAll,
VCHIQ_BULK_MODE_T* BulkMode
)
{
NTSTATUS status = STATUS_SUCCESS;
LIST_ENTRY* nextListEntryPtr;
PAGED_CODE();
if (BulkMode) {
*BulkMode = VCHIQ_BULK_MODE_WAITING;
}
// Remove the last inserted bulk list
if (CompletionDataPtr == NULL) {
do {
nextListEntryPtr = RemoveTailList(
&VchiqFileContextPtr->PendingBulkMsgList[BulkType]);
if (nextListEntryPtr ==
&VchiqFileContextPtr->PendingBulkMsgList[BulkType]) {
break;
}
WdfObjectDelete(CONTAINING_RECORD(
nextListEntryPtr, VCHIQ_PENDING_BULK_MSG, ListEntry)->WdfMemory);
} while (nextListEntryPtr != NULL && RemoveAll);
status = STATUS_SUCCESS;
goto End;
}
nextListEntryPtr = RemoveHeadList(
&VchiqFileContextPtr->PendingBulkMsgList[BulkType]);
if (nextListEntryPtr ==
&VchiqFileContextPtr->PendingBulkMsgList[BulkType]) {
status = STATUS_NOT_FOUND;
VCHIQ_LOG_WARNING("No pending bulk transfer available");
goto End;
}
// Userland expects the bulk user data pointer to be returned. I
CompletionDataPtr->BulkUserData = CONTAINING_RECORD(
nextListEntryPtr, VCHIQ_PENDING_BULK_MSG, ListEntry)->BulkUserData;
if (BulkMode) {
*BulkMode = CONTAINING_RECORD(
nextListEntryPtr, VCHIQ_PENDING_BULK_MSG, ListEntry)->Mode;
}
End:
return status;
}
/*++
Routine Description:
VchiqAddPendingVchiMsg keeps track of pending message for vchi serice.
Arguments:
DeviceContextPtr - Pointer to device context
VchiqFileContextPtr - File context pointer returned to caller
Msg - Pointer to the message from master
SlotNumber - Slot number that would be attempted to be recycled
Return Value:
NTSTATUS
--*/
_Use_decl_annotations_
NTSTATUS VchiqAddPendingVchiMsg (
DEVICE_CONTEXT* DeviceContextPtr,
VCHIQ_FILE_CONTEXT* VchiqFileContextPtr,
VCHIQ_HEADER* Msg,
ULONG SlotNumber
)
{
NTSTATUS status;
WDFMEMORY wdfMemoryNewPendingMsg = NULL;
PAGED_CODE();
// Reuse the same look aside for pending message
status = WdfMemoryCreateFromLookaside(
VchiqFileContextPtr->PendingMsgLookAsideMemory,
&wdfMemoryNewPendingMsg);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"WdfMemoryCreateFromLookaside failed %!STATUS!)",
status);
goto End;
}
size_t bufferSize;
VCHIQ_PENDING_MSG* newPendingMsgPtr;
newPendingMsgPtr = WdfMemoryGetBuffer(wdfMemoryNewPendingMsg, &bufferSize);
if (!NT_SUCCESS(status) || (bufferSize != sizeof(*newPendingMsgPtr))) {
VCHIQ_LOG_ERROR(
"WdfMemoryGetBuffer failed %!STATUS! size %d)",
status,
bufferSize);
goto End;
}
newPendingMsgPtr->Msg = Msg;
newPendingMsgPtr->SlotNumber = SlotNumber;
newPendingMsgPtr->WdfMemory = wdfMemoryNewPendingMsg;
InsertTailList(
&VchiqFileContextPtr->PendingVchiMsgList,
&newPendingMsgPtr->ListEntry);
VchiqAddRefMsg(DeviceContextPtr, SlotNumber);
End:
if (!NT_SUCCESS(status)) {
if (wdfMemoryNewPendingMsg != NULL) {
WdfObjectDelete(wdfMemoryNewPendingMsg);
}
}
return status;
}
/*++
Routine Description:
VchiqRemovePendingVchiMsg - Will remove pending message for vchi service.
Arguments:
DeviceContextPtr - Pointer to device context
VchiqFileContextPtr - File context pointer returned to caller
WdfRequest - Optional wdf request object. If provided pending messages
woudl be copied over to the output buffer.
Return Value:
NTSTATUS
--*/
_Use_decl_annotations_
NTSTATUS VchiqRemovePendingVchiMsg (
DEVICE_CONTEXT* DeviceContextPtr,
VCHIQ_FILE_CONTEXT* VchiqFileContextPtr,
WDFREQUEST WdfRequest
)
{
NTSTATUS status;
LIST_ENTRY *nextListEntryPtr;
PAGED_CODE();
// Just like pending data message remove all pending vchi message if a
// request WDF object is not provided
if (WdfRequest == NULL) {
do {
nextListEntryPtr = RemoveTailList(
&VchiqFileContextPtr->PendingVchiMsgList);
if (nextListEntryPtr ==
&VchiqFileContextPtr->PendingVchiMsgList) {
break;
}
ULONG nextMsgSlotNumber =
CONTAINING_RECORD(
nextListEntryPtr, VCHIQ_PENDING_MSG, ListEntry)->SlotNumber;
VchiqReleaseMsg(DeviceContextPtr, nextMsgSlotNumber);
WdfObjectDelete(CONTAINING_RECORD(
nextListEntryPtr, VCHIQ_PENDING_MSG, ListEntry)->WdfMemory);
} while (nextListEntryPtr != NULL);
status = STATUS_SUCCESS;
goto End;
}
VCHIQ_DEQUEUE_MESSAGE* dequeueMsgPtr;
size_t bufSize;
status = WdfRequestRetrieveInputBuffer(
WdfRequest,
sizeof(*dequeueMsgPtr),
&dequeueMsgPtr,
&bufSize);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"WdfRequestRetrieveInputBuffer failed %!STATUS! \
bufSize(%d)",
status,
bufSize);
goto CompleteRequest;
}
ULONG* totalMsgSizePtr;
status = WdfRequestRetrieveOutputBuffer(
WdfRequest,
sizeof(*totalMsgSizePtr),
&totalMsgSizePtr,
&bufSize);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"WdfRequestRetrieveOutputBuffer failed %!STATUS! \
bufSize(%d)",
status,
bufSize);
goto CompleteRequest;
}
nextListEntryPtr = RemoveHeadList(
&VchiqFileContextPtr->PendingVchiMsgList);
if (nextListEntryPtr ==
&VchiqFileContextPtr->PendingVchiMsgList) {
VCHIQ_LOG_ERROR(
"No more vchi message available!");
status = STATUS_UNSUCCESSFUL;
goto CompleteRequest;
}
// Only copy over the message header is we have sufficient output buffer
VCHIQ_HEADER* nextMsgHeaderPtr =
CONTAINING_RECORD(
nextListEntryPtr, VCHIQ_PENDING_MSG, ListEntry)->Msg;
ULONG pendingVchiMsgSize = nextMsgHeaderPtr->Size + sizeof(*nextMsgHeaderPtr);
if (pendingVchiMsgSize > dequeueMsgPtr->BufSize) {
InsertHeadList(
&VchiqFileContextPtr->PendingVchiMsgList,
nextListEntryPtr);
status = STATUS_INSUFFICIENT_RESOURCES;
goto CompleteRequest;
}
ULONG nextMsgSlotNumber =
CONTAINING_RECORD(
nextListEntryPtr, VCHIQ_PENDING_MSG, ListEntry)->SlotNumber;
VOID* msgBufferPtr =
WdfMemoryGetBuffer(
dequeueMsgPtr->WdfMemoryBuffer,
NULL);
RtlCopyMemory(
msgBufferPtr,
nextMsgHeaderPtr,
pendingVchiMsgSize);
WdfObjectDelete(CONTAINING_RECORD(
nextListEntryPtr, VCHIQ_PENDING_MSG, ListEntry)->WdfMemory);
*totalMsgSizePtr = pendingVchiMsgSize;
VchiqReleaseMsg(DeviceContextPtr, nextMsgSlotNumber);
WdfRequestCompleteWithInformation(
WdfRequest,
status,
sizeof(*totalMsgSizePtr));
return status;
CompleteRequest:
WdfRequestComplete(WdfRequest, status);
End:
return status;
}
/*++
Routine Description:
VchiqRecycleSlot attempt to recycle slot back to vchiq if
all messages within the slot are not needed anymore and the
caller has already specify slot is ready to be recyled.
Arguments:
DeviceContextPtr - Pointer to device context
SlotZeroPtr - Pointer to slot zero
SlotNumber - Slot number that would be attempted to be recycled
ReleaseSlot - Caller would specify if slot can be release for recycle
Return Value:
VOID
--*/
_Use_decl_annotations_
VOID VchiqRecycleSlot (
DEVICE_CONTEXT* DeviceContextPtr,
VCHIQ_SLOT_ZERO* SlotZeroPtr,
ULONG SlotNumber,
BOOLEAN ReleaseSlot
)
{
ULONG curSlotRefCount;
SLOT_INFO* currentSlotPtr = &DeviceContextPtr->RxSlotInfo[SlotNumber];
PAGED_CODE();
// Only release slot when caller specifies it isnt used anymore
if (ReleaseSlot) {
currentSlotPtr->SlotInUse = FALSE;
}
curSlotRefCount = InterlockedExchange(
(volatile LONG *)¤tSlotPtr->RefCount,
currentSlotPtr->RefCount);
// Only recycle the slot if there is no more reference to the slot
if ((curSlotRefCount == 0) && (currentSlotPtr->SlotInUse == FALSE)) {
NTSTATUS status;
// Lock here because we want to serialize recycle notification
ExAcquireFastMutex(&DeviceContextPtr->RecycleSlotMutex);
SlotZeroPtr->Master.SlotQueue[SlotZeroPtr->Master.SlotQueueRecycle
& VCHIQ_SLOT_QUEUE_MASK] =
SlotNumber;
++SlotZeroPtr->Master.SlotQueueRecycle;
status = VchiqSignalVC(
DeviceContextPtr,
&SlotZeroPtr->Master.Recycle);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"Fail to signal VC %!STATUS!",
status);
}
ExReleaseFastMutex(&DeviceContextPtr->RecycleSlotMutex);
}
return;
}
/*++
Routine Description:
Running thread that process the trigger interrupt
Arguments:
Param - A caller-supplied pointer to driver-defined context information
where in our case it is the device context
Return Value:
VOID
--*/
_Use_decl_annotations_
VOID VchiqTriggerThreadRoutine (
VOID* Param
)
{
NTSTATUS status;
ULONG threadActive = 1;
DEVICE_CONTEXT* deviceContextPtr = Param;
PAGED_CODE();
while (threadActive) {
if (VCHIQ_IS_EVENT_SIGNAL(
&deviceContextPtr->SlotZeroPtr->Slave.Trigger)) {
status = STATUS_WAIT_0;
} else {
status = VchiqWaitForEvents(
&deviceContextPtr->VchiqThreadEvent[THREAD_TRIGGER],
&deviceContextPtr->VchiqThreadEventStop,
NULL);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"Unexpected failure on trigger thread %!STATUS!",
status);
continue;
}
}
switch (status)
{
case STATUS_WAIT_0:
VchiqProcessRxSlot(deviceContextPtr);
break;
case STATUS_WAIT_1:
threadActive = 0;
break;
default:
VCHIQ_LOG_ERROR(
"Unexpected response for trigger thread %!STATUS!",
status);
break;
}
}
(void)PsTerminateSystemThread(STATUS_SUCCESS);
return;
}
/*++
Routine Description:
Running thread that process the recyle interrupt
Arguments:
Param - A caller-supplied pointer to driver-defined context information
where in our case it is the device context
Return Value:
VOID
--*/
_Use_decl_annotations_
VOID VchiqRecycleThreadRoutine (
VOID* Param
)
{
NTSTATUS status;
ULONG threadActive = 1;
DEVICE_CONTEXT* deviceContextPtr = Param;
PAGED_CODE();
while (threadActive) {
if (VCHIQ_IS_EVENT_SIGNAL(
&deviceContextPtr->SlotZeroPtr->Slave.Recycle)) {
status = STATUS_WAIT_0;
} else {
status = VchiqWaitForEvents(
&deviceContextPtr->VchiqThreadEvent[THREAD_RECYCLE],
&deviceContextPtr->VchiqThreadEventStop,
NULL);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"Unexpected failure on recycle thread %!STATUS!",
status);
continue;
}
}
switch (status)
{
case STATUS_WAIT_0:
VchiqProcessRecycleTxSlot(deviceContextPtr);
break;
case STATUS_WAIT_1:
threadActive = 0;
break;
default:
VCHIQ_LOG_ERROR(
"Unexpected response for recycle thread %!STATUS!",
status);
break;
}
}
(void)PsTerminateSystemThread(STATUS_SUCCESS);
return;
}
/*++
Routine Description:
Running thread that handles sync trigger
Arguments:
Param - A caller-supplied pointer to driver-defined context information
where in our case it is the device context
Return Value:
VOID
--*/
_Use_decl_annotations_
VOID VchiqSyncThreadRoutine (
VOID* Param
)
{
NTSTATUS status;
ULONG threadActive = 1;
DEVICE_CONTEXT* deviceContextPtr = Param;
PAGED_CODE();
while (threadActive) {
if (VCHIQ_IS_EVENT_SIGNAL(
&deviceContextPtr->SlotZeroPtr->Slave.SyncTrigger)) {
status = STATUS_WAIT_0;
} else {
status = VchiqWaitForEvents(
&deviceContextPtr->VchiqThreadEvent[THREAD_SYNC],
&deviceContextPtr->VchiqThreadEventStop,
NULL);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"Unexpected failure on trigger sync thread %!STATUS!",
status);
continue;
}
}
switch (status)
{
case STATUS_WAIT_0:
// Currently unsupported
break;
case STATUS_WAIT_1:
threadActive = 0;
break;
default:
VCHIQ_LOG_ERROR(
"Unexpected response for trigger sync thread %!STATUS!",
status);
break;
}
}
(void)PsTerminateSystemThread(STATUS_SUCCESS);
return;
}
/*++
Routine Description:
Running thread that handles sync release
Arguments:
Param - A caller-supplied pointer to driver-defined context information
where in our case it is the device context
Return Value:
VOID
--*/
_Use_decl_annotations_
VOID VchiqSyncReleaseThreadRoutine (
VOID* Param
)
{
NTSTATUS status;
ULONG threadActive = 1;
DEVICE_CONTEXT* deviceContextPtr = Param;
PAGED_CODE();
while (threadActive) {
if (VCHIQ_IS_EVENT_SIGNAL(
&deviceContextPtr->SlotZeroPtr->Slave.SyncRelease)) {
status = STATUS_WAIT_0;
} else {
status = VchiqWaitForEvents(
&deviceContextPtr->VchiqThreadEvent[THREAD_SYNC_RELEASE],
&deviceContextPtr->VchiqThreadEventStop,
NULL);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"Unexpected failure on sync release thread %!STATUS!",
status);
continue;
}
}
switch (status)
{
case STATUS_WAIT_0:
// Currently unsupported
break;
case STATUS_WAIT_1:
threadActive = 0;
break;
default:
VCHIQ_LOG_ERROR(
"Unexpected response for sync release thread %!STATUS!",
status);
break;
}
}
(void)PsTerminateSystemThread(STATUS_SUCCESS);
return;
}
VCHIQ_PAGED_SEGMENT_END
VCHIQ_NONPAGED_SEGMENT_BEGIN
/*++
Routine Description:
Utility function to wait for dispatcher object to be signalled or stop
event. This funtion is in nonpaged as the array of events needs to be
in nonpaged system memory.
Arguments:
MainEventPtr - Pointer to main dispatcher object
StopEventPtr - Pointer to stop event object
Timeout - Optional timeout value for wait events
Return Value:
NTSTATUS
--*/
_Use_decl_annotations_
NTSTATUS VchiqWaitForEvents (
VOID* MainEventPtr,
KEVENT* StopEventPtr,
LARGE_INTEGER* TimeoutPtr
)
{
NTSTATUS status;
VOID* waitEvents[2];
NT_ASSERT(KeGetCurrentIrql() <= APC_LEVEL);
waitEvents[0] = MainEventPtr;
waitEvents[1] = (VOID*)StopEventPtr;
status = KeWaitForMultipleObjects(
ARRAYSIZE(waitEvents),
waitEvents,
WaitAny,
Executive,
KernelMode,
FALSE,
TimeoutPtr,
NULL);
if (!NT_SUCCESS(status)) {
VCHIQ_LOG_ERROR(
"Unexpected failure on trigger thread %!STATUS!",
status);
}
return status;
}
VCHIQ_NONPAGED_SEGMENT_END | 28.150534 | 91 | 0.602624 | [
"object"
] |
54da7c6463ff1f236e24265150ddbb407ee02569 | 2,803 | h | C | panda/src/putil/uniqueIdAllocator.h | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/putil/uniqueIdAllocator.h | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/putil/uniqueIdAllocator.h | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | /**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file uniqueIdAllocator.h
* @author schuyler
* @date 2003-03-13
*/
#ifndef _UNIQUEIDALLOCATOR_H //[
#define _UNIQUEIDALLOCATOR_H
#include "pandabase.h"
#include "numeric_types.h"
/**
* Manage a set of ID values from min to max inclusive. The ID numbers that
* are freed will be allocated (reused) in the same order. I.e. the oldest
* ID numbers will be allocated.
*
* This implementation will use 4 bytes per id number, plus a few bytes of
* management data. e.g. 10,000 ID numbers will use 40KB.
*
* Also be advised that ID -1 and -2 are used internally by the allocator. If
* allocate returns IndexEnd (-1) then the allocator is out of free ID
* numbers.
*
* There are other implementations that can better leverage runs of used or
* unused IDs or use bit arrays for the IDs. But, it takes extra work to
* track the age of freed IDs, which is required for what we wanted. If you
* would like to kick around other implementation ideas, please contact
* Schuyler.
*/
class EXPCL_PANDA_PUTIL UniqueIdAllocator {
PUBLISHED:
explicit UniqueIdAllocator(uint32_t min=0, uint32_t max=20);
~UniqueIdAllocator();
uint32_t allocate();
void initial_reserve_id(uint32_t id);
void free(uint32_t index);
PN_stdfloat fraction_used() const;
void output(ostream &out) const;
void write(ostream &out) const;
public:
static const uint32_t IndexEnd;
static const uint32_t IndexAllocated;
protected:
// _table stores an array of _size words, corresponding to each allocatable
// id.
// For each free id, the table entry at the corresponding index contains the
// index number of the next free id, thus defining a chain of free id's.
// The last element of the chain contains IndexEnd.
// For an allocated id, the table entry at the corresponding index contains
// IndexAllocated.
uint32_t *_table;
// The minimum and maximum as passed to the constructor.
uint32_t _min;
uint32_t _max;
// This is the head of the free chain: as elements are allocated, they are
// taken from _table[_next_free]. If the free chain is empty, _next_free ==
// IndexEnd.
uint32_t _next_free;
// This is the tail of the free chain: as elements are freed, they are
// stored in _table[_last_free]. Normally, _table[_last_free] is the end of
// the free chain, unless the free chain is empty.
uint32_t _last_free;
// The total number of elements in _table.
uint32_t _size;
// The number of free elements in _table.
uint32_t _free;
};
#endif //]
| 31.144444 | 78 | 0.727078 | [
"3d"
] |
54ea53eaf1c76aceb416610cde14806c4265ba54 | 1,651 | h | C | model/v1beta1_local_subject_access_review.h | ityuhui/client-c | 1d30380d7ba0fe9b5e97626e0f7507be4ce8f96d | [
"curl",
"Apache-2.0"
] | null | null | null | model/v1beta1_local_subject_access_review.h | ityuhui/client-c | 1d30380d7ba0fe9b5e97626e0f7507be4ce8f96d | [
"curl",
"Apache-2.0"
] | null | null | null | model/v1beta1_local_subject_access_review.h | ityuhui/client-c | 1d30380d7ba0fe9b5e97626e0f7507be4ce8f96d | [
"curl",
"Apache-2.0"
] | null | null | null | /*
* v1beta1_local_subject_access_review.h
*
* LocalSubjectAccessReview checks whether or not_ a user or group can perform an action in a given namespace. Having a namespace scoped resource makes it much easier to grant namespace scoped policy that includes permissions checking.
*/
#ifndef _v1beta1_local_subject_access_review_H_
#define _v1beta1_local_subject_access_review_H_
#include <string.h>
#include "../external/cJSON.h"
#include "../include/list.h"
#include "../include/keyValuePair.h"
#include "v1_object_meta.h"
#include "v1beta1_subject_access_review_spec.h"
#include "v1beta1_subject_access_review_status.h"
typedef struct v1beta1_local_subject_access_review_t {
char *apiVersion; // string
char *kind; // string
v1_object_meta_t *metadata; //model
v1beta1_subject_access_review_spec_t *spec; //model
v1beta1_subject_access_review_status_t *status; //model
} v1beta1_local_subject_access_review_t;
v1beta1_local_subject_access_review_t *v1beta1_local_subject_access_review_create(
char *apiVersion,
char *kind,
v1_object_meta_t *metadata,
v1beta1_subject_access_review_spec_t *spec,
v1beta1_subject_access_review_status_t *status
);
void v1beta1_local_subject_access_review_free(v1beta1_local_subject_access_review_t *v1beta1_local_subject_access_review);
v1beta1_local_subject_access_review_t *v1beta1_local_subject_access_review_parseFromJSON(cJSON *v1beta1_local_subject_access_reviewJSON);
cJSON *v1beta1_local_subject_access_review_convertToJSON(v1beta1_local_subject_access_review_t *v1beta1_local_subject_access_review);
#endif /* _v1beta1_local_subject_access_review_H_ */
| 36.688889 | 235 | 0.835857 | [
"model"
] |
54fafe6846835aeb22afb9f68db705ef6895818c | 2,234 | h | C | ace/tao/tests/Collocation/Diamond_i.h | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 46 | 2015-12-04T17:12:58.000Z | 2022-03-11T04:30:49.000Z | ace/tao/tests/Collocation/Diamond_i.h | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | null | null | null | ace/tao/tests/Collocation/Diamond_i.h | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 23 | 2016-10-24T09:18:14.000Z | 2022-02-25T02:11:35.000Z | // Diamond_i.h,v 1.5 2001/02/25 16:03:37 bala Exp
#if !defined (TAO_DIAMOND_I_H)
#define TAO_DIAMOND_I_H
#include "DiamondS.h"
#if !defined (ACE_LACKS_PRAGMA_ONCE)
# pragma once
#endif /* ACE_LACKS_PRAGMA_ONCE */
class Diamond_Export Top_i : public POA_Diamond::Top
{
public:
Top_i (void);
~Top_i (void);
// Ctor and dtor.
virtual char * shape (CORBA::Environment &)
ACE_THROW_SPEC ((CORBA::SystemException));
// Return the shape of this object (interface.)
};
class Diamond_Export Left_i : public POA_Diamond::Left
{
public:
Left_i (void);
~Left_i (void);
// Ctor, dtor.
virtual char * shape (CORBA::Environment &)
ACE_THROW_SPEC ((CORBA::SystemException));
// Return the shape of this object (interface.)
virtual char * color (CORBA::Environment &)
ACE_THROW_SPEC ((CORBA::SystemException));
// Return the color of this object (interface.)
};
class Diamond_Export Right_i : public POA_Diamond::Right
{
public:
Right_i (void);
~Right_i (void);
// Ctor, dtor.
virtual char * shape (CORBA::Environment &)
ACE_THROW_SPEC ((CORBA::SystemException));
// Return the shape of this object (interface.)
virtual char * color (CORBA::Environment &)
ACE_THROW_SPEC ((CORBA::SystemException));
// Return the color of this object (interface.)
virtual CORBA::Long width (CORBA::Environment &)
ACE_THROW_SPEC ((CORBA::SystemException));
// Return the width of the stuff.
};
class Diamond_Export Buttom_i : public POA_Diamond::Buttom
{
public:
Buttom_i (void);
~Buttom_i (void);
// Ctor, dtor.
virtual char * shape (CORBA::Environment &)
ACE_THROW_SPEC ((CORBA::SystemException));
// Return the shape of this object (interface.)
virtual char * color (CORBA::Environment &)
ACE_THROW_SPEC ((CORBA::SystemException));
// Return the color of this object (interface.)
virtual CORBA::Long width (CORBA::Environment &)
ACE_THROW_SPEC ((CORBA::SystemException));
// Return the width of the stuff.
virtual char * name (CORBA::Environment &)
ACE_THROW_SPEC ((CORBA::SystemException));
// Return the name of the object.
};
#endif /* TAO_DIAMOND_I_H */
| 25.976744 | 59 | 0.670546 | [
"object",
"shape"
] |
54fd912e94ae36bebfba2e5bc05c0911473126f5 | 9,305 | h | C | src/module/inc/ConfigManager.h | chisuhua/comodel | 39370d2ac666fb04d182b8a56f45d81e06bac972 | [
"Apache-2.0"
] | null | null | null | src/module/inc/ConfigManager.h | chisuhua/comodel | 39370d2ac666fb04d182b8a56f45d81e06bac972 | [
"Apache-2.0"
] | null | null | null | src/module/inc/ConfigManager.h | chisuhua/comodel | 39370d2ac666fb04d182b8a56f45d81e06bac972 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <list>
#include <map>
#include <set>
#include <string>
#include <vector>
#include "base/inc/cprintf.h"
#include "ConfigIniFile.h"
#include <tvm/runtime/module.h>
// class CheckpointIn;
/**
* Base class to wrap object resolving functionality.
*
* This can be provided to the serialization framework to allow it to
* map object names onto C++ objects.
*/
class ModuleResolver
{
public:
virtual ~ModuleResolver() { }
/**
* Find a SimObject given a full path name
*
* @ingroup api_serialize
*/
virtual CoModule resolveModule(const std::string &name) = 0;
};
/** This class allows a config file to be read into gem5 (generating the
* appropriate SimObjects) from C++ */
class ConfigManager
{
protected:
/** Configuration file being read */
ConfigIniFile &configFile;
/** Flags to pass to affect param setting */
// ModuleParams::Flags flags;
public:
/** Exception for instantiate/post-instantiate errors */
class Exception : public std::exception
{
public:
std::string name;
std::string message;
public:
Exception(const std::string &name_, const std::string &message_) :
name(name_), message(message_)
{ }
const char *what() const throw() { return message.c_str(); }
~Exception() throw() { }
};
/** Name substitution when instantiating any object whose name starts
* with fromPrefix. Where both renamed and unrenamed names are used
* in the code, `object' as part of a name usually refers to the
* unrenamed name (the name as it appears in the config file) and
* `instance' is part of the renamed name */
struct Renaming
{
std::string fromPrefix;
std::string toPrefix;
Renaming(const std::string &from_prefix,
const std::string &to_prefix) :
fromPrefix(from_prefix),
toPrefix(to_prefix)
{ }
};
public:
/** SimObject indexed by name */
std::map<std::string, CoModule> objectsByName;
std::map<std::string, tvm::runtime::Module> ModuleByName;
/** ...Params objects created by this manager */
std::map<std::string, ModuleParams> objectParamsByName;
/** SimObjects in order. This is populated by findAllObjects */
std::list<CoModule> objectsInOrder;
protected:
/** While configuring, inVisit contains names of SimObjects visited in
* this recursive configuration walk */
std::set<std::string> inVisit;
/** All the renamings applicable when instantiating objects */
std::list<Renaming> renamings;
/** Bind a single connection between two objects' ports */
void bindPort(CoModule masterObject, const std::string &masterPort,
PortID masterPortIndex, CoModule slaveObject,
const std::string &slavePort, PortID slavePortIndex);
/** Bind a single (possibly vectored) master port to peers from the
* unparsed list peers with elements in the .ini connection format:
* path(.path)*.port[index] */
void bindMasterPort(CoModule object, const Port &port,
const std::vector<std::string> &peers);
/** Apply the first matching renaming in renamings to the given name */
std::string rename(const std::string &from_name);
public:
/** Apply the first matching renaming in reverse (toPrefix -> fromPrefix
* for the given name */
std::string unRename(const std::string &to_name);
protected:
/** Bind the ports of all the objects in objectInOrder order.
* Also */
void bindAllPorts();
public:
ConfigManager(ConfigIniFile &configFile_);
/** Find the type field for a named object and return both the
* name of the type to object_type and the object's directory
* entry as the return value */
void findObjectType(const std::string &object_name, std::string &object_type);
/** Add a name prefix renaming to those currently applied. Call this
* before trying to instantiate any object as the name mappings are
* not applied to the config tree read from the config file but are
* applied while processing instantiations */
void addRenaming(const Renaming &renaming);
public:
/** Bind the ports of a single SimObject */
void bindObjectPorts(CoModule object);
/** Walk the configuration starting with object object_name and fill
* in all the elements of this object on the way. This involves:
* <ul>
* <li>Calling findObjectParams to make the ...Params object
* If findObjectParams has already been called for this object,
* the ...Params object generated by that called (stored in
* (objectParamsByName[object_name] will be used)</li>
* <li>Populating the ...Params object references to other
* SimObjects by recursively descending into the trees formed
* by SimObject references</li>
* <li>Building the final SimObject and adding it to
* objectsByName</li>
* <li>If visit_children is true, recursively visit all this
* object's children and build/find them too</li>
* </ul>
* After the first call, this function will return
* objectsByName[object_name] */
CoModule findObject(const std::string &object_name, bool visit_children = false);
/** Find the parameters for the named object. Returns NULL if the
* object isn't in the configuration. For the first call with a
* particular object name, a new CxxModuleParams descended object
* is made with the configuration file contents for this object.
* This involves populating that ...Params object with:
* <ul>
* <li>parameter values from the configuration file</li>
* <li>port connection connection counts from the connection counts
* indicated by the number of peer ports in the configuration
* file</li>
* <li>nulled (or vector<>::clear'ed) SimObject references for
* SimObject-values parameters</li>
* </ul>
* The ...Params object is then added to objectParamsByName
* After the first call, this function will return
* objectParamsByName[object_name] */
ModuleParams findObjectParams(const std::string &object_name);
/** Populate objectsInOrder with a preorder, depth first traversal from
* the given object name down through all its children */
void findTraversalOrder(const std::string &object_name);
/** Find an object from objectsByName with a type-checking cast.
* This function is provided for manipulating objects after
* instantiate as it assumes the named object exists. */
template<typename ModuleType>
ModuleType & getObject(const std::string &object_name)
{
if (objectsByName.find(object_name) == objectsByName.end()) {
throw Exception("", GetFormatString("No sim object named: %s", object_name));
}
// ModuleType object = dynamic_cast<ModuleType>(objectsByName[object_name]);
ModuleType& object = objectsByName[object_name];
if (not object.defined()) {
throw Exception("", GetFormatString("Sim object: %s has the wrong type", object_name));
}
return object;
}
/** Perform mem_func on each SimObject */
void forEachObject(void (CoModuleNode::*mem_func)());
/** Find all objects by iterating over the object names in the config
* file with findObject. Also populate the traversal order */
void findAllObjects();
/** Parse a port string of the form 'path(.path)*.port[index]' into
* path, port and index */
static void parsePort(const std::string &inp,
std::string &path, std::string &port, unsigned int &index);
/** Build all objects (if build_all is true, otherwise objects must
* have been individually findObject-ed and added to the traversal
* order) and perform all the configuration specific actions up to,
* but not including initState.
*
* If you want to set some parameters before completing instantiation,
* call findObjectParams on the objects you want to modify, then call
* instantiate */
void instantiate(bool build_all = true);
/** Call initState on all objects */
void initState();
/** Call startup on all objects */
void startup();
/** Drain all objects */
// unsigned int drain();
/** Resume from drain */
// void drainResume();
/** Serialize (checkpoint) all objects to the given stream */
// void serialize(std::ostream &os);
/** Load all objects' state from the given Checkpoint */
// void loadState(CheckpointIn &checkpoint);
/** Delete all objects and clear objectsByName and objectsByOrder */
void deleteObjects();
/** Convenience functions for calling set... member functions on a
* CxxModuleParams for an object. These functions throw Exception
* rather than return a bool on failure */
void setParam(const std::string &object_name,
const std::string ¶m_name, const std::string ¶m_value);
void setParamVector(const std::string &object_name,
const std::string ¶m_name,
const std::vector<std::string> ¶m_values);
};
| 36.347656 | 100 | 0.667598 | [
"object",
"vector"
] |
0700836d125cd09d2dd66de3ab67fa298394ccea | 706 | h | C | NemoKit/NemoKit/NMUtility/Foundation/Data Structure/NMDataStack.h | wenghengcong/NemoK | bea608f7d7413de8984440cfde3c0f0231596b44 | [
"MIT"
] | null | null | null | NemoKit/NemoKit/NMUtility/Foundation/Data Structure/NMDataStack.h | wenghengcong/NemoK | bea608f7d7413de8984440cfde3c0f0231596b44 | [
"MIT"
] | null | null | null | NemoKit/NemoKit/NMUtility/Foundation/Data Structure/NMDataStack.h | wenghengcong/NemoK | bea608f7d7413de8984440cfde3c0f0231596b44 | [
"MIT"
] | 1 | 2020-05-20T17:03:08.000Z | 2020-05-20T17:03:08.000Z | //
// NMDataStack.h
// NemoMoney
//
// Created by Hunt on 2020/1/4.
// Copyright © 2020 Hunt <wenghengcong@icloud.com>. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@interface NMDataStack : NSObject <NSFastEnumeration> {
NSMutableArray* array;
}
// Removes and returns the element at the top of the stack
-(id)pop;
// Adds the element to the top of the stack
-(void)push:(id)element;
// Removes all elements
-(void)pushElementsFromArray:(NSArray*)arr;
-(void)clear;
// Returns the object at the top of the stack
-(id)peek;
// Returns the size of the stack
-(NSInteger)size;
// Returns YES if the stack is empty
-(BOOL)isEmpty;
@end
NS_ASSUME_NONNULL_END
| 20.171429 | 73 | 0.723796 | [
"object"
] |
0701af4979c6678b81aea82cd9acd91c2b2314d9 | 3,428 | h | C | src/sgl/public/hal/runnable_pthread.h | sneppy/rds | 69facd24bebd7e5f76d5c2ea696fed65b946ef9a | [
"MIT"
] | null | null | null | src/sgl/public/hal/runnable_pthread.h | sneppy/rds | 69facd24bebd7e5f76d5c2ea696fed65b946ef9a | [
"MIT"
] | null | null | null | src/sgl/public/hal/runnable_pthread.h | sneppy/rds | 69facd24bebd7e5f76d5c2ea696fed65b946ef9a | [
"MIT"
] | null | null | null | #pragma once
#include "core_types.h"
#include "hal/platform_memory.h"
#include "hal/runnable_thread.h"
#include "hal/thread_manager.h"
#if PLATFORM_USE_PTHREADS
/**
* @class RunnablePThread hal/runnable_pthread.h
* @brief Base implementation that uses pthreads
*/
class RunnablePThread : public RunnableThread
{
protected:
/// @brief Entry point function type
///
/// The pthread_create interface allows passing
/// a single parameter via reference, and returns
/// its exit value as a void pointer
typedef void * (*PThreadEntryPoint)(void * arg);
protected:
/// @brief Underlying pthread resource
pthread_t id;
/// @brief If true the thread has started and not yet finished
bool bStarted;
public:
/// @brief Default-constructor
FORCE_INLINE RunnablePThread() {}
/// @brief Virtual-destructor
FORCE_INLINE ~RunnablePThread() { destroy(); }
/// @copydoc RunnableThread::kill
virtual void kill(bool bShouldWait = true) override;
/// @copydoc RunnableThread::join
virtual FORCE_INLINE void join() override
{
if (bStarted)
{
pthread_join(id, nullptr);
bStarted = false;
}
}
protected:
/// @brief Wrapper for pthread_create
virtual FORCE_INLINE int32 createThread(pthread_t * handle, pthread_attr_t * attributes, PThreadEntryPoint func, void * arg, const ansichar * name)
{
return pthread_create(handle, attributes, func, arg);
}
/// @brief Platform dependant default stack size
virtual FORCE_INLINE int32 getDefaultStackSize()
{
// Some information on default stack sizes, selected when given 0:
// - On Windows, all threads get 1MB: http://msdn.microsoft.com/en-us/library/windows/desktop/ms686774(v=vs.85).aspx
// - On Mac, main thread gets 8MB,
// - all other threads get 512 kB when created through pthread or NSThread, and only 4kB when through MPTask()
// ( http://developer.apple.com/library/mac/#qa/qa1419/_index.html )
// I'm not gonna mess with this
return 0;
}
/// @brief Fixed thread entry points
///
/// Forwards to appropriate methods
static FORCE_INLINE void * entryPoint(void * _self)
{
assert(_self);
// Add to thread manager
RunnablePThread * self = reinterpret_cast<RunnablePThread*>(_self);
ThreadManager::getPtr()->add(self->getThreadId(), self);
// Thread life-cycle
self->preRun(), self->run(), self->postRun();
// Exit silently
pthread_exit(nullptr);
return nullptr;
}
/// @brief Called before running the thread (virtual, can be modified)
virtual FORCE_INLINE void preRun() {};
/// @brief Called before thread exits (virtual, can be modified)
virtual FORCE_INLINE void postRun() {};
/**
* @brief Thread run routine, the real entry point of the thread
*/
uint32 run();
/// @brief Performs object destruction
///
/// Why here? Some weird stuff about virtualization,
/// go ask those madman at Epic
void FORCE_INLINE destroy()
{
// Kill running thread
if (bStarted) kill();
}
protected:
/// @copydoc RunnableThread::create_internal()
virtual bool create_internal(Runnable * _runnable, const ansichar * _name, uint32 stackSize) override
{
// No runnable? No thread!
if (_runnable == nullptr) return false;
runnable = _runnable;
// Set thread name
name = _name ? _name : "unnamed";
// Create the thread
const int32 status = createThread(&id, nullptr, entryPoint, this, nullptr);
bStarted = status == 0;
return bStarted;
}
};
#endif // PLATFORM_USE_PTHREADS
| 25.969697 | 148 | 0.713536 | [
"object"
] |
070fc0b1e3097e4e8d97e5b45e0901bf6b5ded9b | 3,037 | h | C | src/Image.h | tcvdijk/lineman | d0095425390c6c19757a8d21f604d97ead5331cb | [
"Apache-2.0"
] | 1 | 2020-09-02T22:06:29.000Z | 2020-09-02T22:06:29.000Z | src/Image.h | tcvdijk/lineman | d0095425390c6c19757a8d21f604d97ead5331cb | [
"Apache-2.0"
] | null | null | null | src/Image.h | tcvdijk/lineman | d0095425390c6c19757a8d21f604d97ead5331cb | [
"Apache-2.0"
] | null | null | null | #pragma once
#ifndef INCLUDED_IMAGE
#define INCLUDED_IMAGE
#include <vector>
#include <string>
#include <functional>
#include "Point.h"
#include "lodepng.h"
class Image {
public:
struct Stroke {
Stroke() {}
Stroke(Segment seg, unsigned char r, unsigned char g, unsigned char b) : seg(seg), r(r), g(g), b(b) {}
Segment seg;
unsigned char r, g, b;
};
std::vector<Stroke> strokes;
Image(int W, int H, const unsigned char *srcpixel);
~Image();
std::vector<double> pixel;
int W, H;
double &get(int x, int y) {
return pixel[W*y + x];
}
void flip_y();
std::function<void(double*, double*)> to_pixel_coords = nullptr;
std::function<void(double*, double*)> from_pixel_coords = nullptr;
std::function<void()> cleanup = nullptr;
// This just adds the polyline to a buffer.
// Polylines are only rendered on ::save.
void addPolyline(const std::vector<Point<Space::World>> &polyline, unsigned char r, unsigned char g, unsigned char b);
double avg(Point<Space::World> a, Point<Space::World> b);
void save(const std::string &fname);
// Drawing visitors.
// visit(x,y,val) gets called for every pixel with
// x, y the pixel coordinates in global space
// val the original value at that pixel (double)
struct Draw {
Draw(double val) : myValue(val) {}
double myValue;
void visit(int, int, double &value);
};
struct DrawRGBA {
DrawRGBA(std::vector<unsigned char> &rgba, int W, unsigned char r, unsigned char g, unsigned char b, unsigned char a)
: rgba(rgba), W(W), r(r), g(g), b(b), a(a) {}
std::vector<unsigned char> &rgba;
int W;
unsigned char r, g, b, a;
void visit(int x, int y, double&);
};
struct SegmentStat {
int count = 0;
double sum = 0;
SegmentStat() = default;
void visit(int, int, double &value);
};
// Bresenham implementation with visitor template
template< class Visitor >
void bresenham(Visitor &v, Point<Space::World> a, Point<Space::World> b) {
if (abs(b.y - a.y) < abs(b.x - a.x)) {
if (a.x > b.x) {
return bresenhamLow(v, b, a);
}
else {
return bresenhamLow(v, a, b);
}
}
else {
if (a.y > b.y) {
return bresenhamHigh(v, b, a);
}
else {
return bresenhamHigh(v, a, b);
}
}
}
template< class Visitor >
void bresenhamLow(Visitor &v, Point<Space::World> a, Point<Space::World> b) {
int dx = b.x - a.x;
int dy = b.y - a.y;
int yi = 1;
if (dy < 0) {
yi = -1;
dy = -dy;
}
int D = 2 * dy - dx;
int y = a.y;
for (int x = a.x; x <= b.x; ++x) {
v.visit(x, y, get(x, y));
if (D > 0) {
y = y + yi;
D = D - 2 * dx;
}
D = D + 2 * dy;
}
}
template< class Visitor >
void bresenhamHigh(Visitor &v, Point<Space::World> a, Point<Space::World> b) {
int dx = b.x - a.x;
int dy = b.y - a.y;
int xi = 1;
if (dx < 0) {
xi = -1;
dx = -dx;
}
int D = 2 * dx - dy;
int x = a.x;
for (int y = a.y; y <= b.y; ++y) {
v.visit(x, y, get(x, y));
if (D > 0) {
x = x + xi;
D = D - 2 * dy;
}
D = D + 2 * dx;
}
}
};
#endif //ndef INCLUDED_IMAGE
| 22.496296 | 119 | 0.592032 | [
"vector"
] |
0718e8493cc6d0f7246e9a39920b711afe1dbd4e | 5,972 | h | C | crawl-ref/source/clua.h | MJSeaton/Crawl4x | a344f09bdaa866b15f21d92922a7183e59214b4f | [
"CC0-1.0"
] | 44 | 2020-04-06T08:56:09.000Z | 2021-03-17T18:05:18.000Z | crawl-ref/source/clua.h | MJSeaton/Crawl4x | a344f09bdaa866b15f21d92922a7183e59214b4f | [
"CC0-1.0"
] | 501 | 2020-04-06T07:19:01.000Z | 2022-02-23T13:04:40.000Z | crawl-ref/source/clua.h | MJSeaton/Crawl4x | a344f09bdaa866b15f21d92922a7183e59214b4f | [
"CC0-1.0"
] | 74 | 2020-04-06T07:40:50.000Z | 2021-05-21T00:13:36.000Z | #pragma once
extern "C" {
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
}
#include <cstdarg>
#include <cstdio>
#include <map>
#include <set>
#include <string>
#include "maybe-bool.h"
class CLua;
class lua_stack_cleaner
{
public:
lua_stack_cleaner(lua_State *_ls) : ls(_ls), top(lua_gettop(_ls)) { }
~lua_stack_cleaner() { lua_settop(ls, top); }
private:
lua_State *ls;
int top;
};
class lua_call_throttle
{
public:
lua_call_throttle(CLua *handle);
~lua_call_throttle();
static CLua *find_clua(lua_State *ls);
private:
CLua *lua;
typedef map<lua_State *, CLua *> lua_clua_map;
static lua_clua_map lua_map;
};
class lua_shutdown_listener
{
public:
virtual ~lua_shutdown_listener();
virtual void shutdown(CLua &lua) = 0;
};
// A convenience class to keep a reference to a lua object on the stack.
// This is useful to hang on to things that cannot be directly retrieved by
// C++ code, such as Lua function references.
class lua_datum : public lua_shutdown_listener
{
public:
lua_datum(CLua &lua, int stackpos = -1, bool pop = true);
lua_datum(const lua_datum &other);
const lua_datum &operator = (const lua_datum &other);
void shutdown(CLua &lua) override;
~lua_datum();
// Push the datum onto the Lua stack.
void push() const;
bool is_table() const;
bool is_function() const;
bool is_number() const;
bool is_string() const;
bool is_udata() const;
public:
CLua &lua;
private:
bool need_cleanup;
private:
void set_from(const lua_datum &o);
void cleanup();
};
class CLua
{
public:
CLua(bool managed = true);
~CLua();
static CLua &get_vm(lua_State *);
lua_State *state();
operator lua_State * ()
{
return state();
}
void save(writer &outf);
void save_persist();
void load_persist();
void gc();
void setglobal(const char *name);
void getglobal(const char *name);
// Assigns the value on top of the stack to a unique name in the registry
// and returns the name.
string setuniqregistry();
void setregistry(const char *name);
void getregistry(const char *name);
int loadbuffer(const char *buf, size_t size, const char *context);
int loadstring(const char *str, const char *context);
int execstring(const char *str, const char *context = "init.txt",
int nresults = 0);
int execfile(const char *filename,
bool trusted = false,
bool die_on_fail = false,
bool force = false);
void pushglobal(const string &name);
maybe_bool callmbooleanfn(const char *fn, const char *params, ...);
maybe_bool callmaybefn(const char *fn, const char *params, ...);
bool callbooleanfn(bool defval, const char *fn, const char *params, ...);
bool callfn(const char *fn, int nargs, int nret = 1);
bool callfn(const char *fn, const char *params, ...);
void fnreturns(const char *params, ...);
bool runhook(const char *hook, const char *params, ...);
void add_shutdown_listener(lua_shutdown_listener *);
void remove_shutdown_listener(lua_shutdown_listener *);
static int file_write(lua_State *ls);
static int loadfile(lua_State *ls, const char *file,
bool trusted = false, bool die_on_fail = false);
static bool is_path_safe(string file, bool trusted = false);
static bool is_managed_vm(lua_State *ls);
void print_stack();
public:
string error;
// If managed_vm is set, we have to take steps to control badly-behaved
// scripts.
bool managed_vm;
bool shutting_down;
int throttle_unit_lines;
int throttle_sleep_ms;
int throttle_sleep_start, throttle_sleep_end;
int n_throttle_sleeps;
int mixed_call_depth;
int lua_call_depth;
int max_mixed_call_depth;
int max_lua_call_depth;
long memory_used;
static const int MAX_THROTTLE_SLEEPS = 100;
private:
lua_State *_state;
typedef set<string> sfset;
sfset sourced_files;
unsigned int uniqindex;
vector<lua_shutdown_listener*> shutdown_listeners;
private:
void init_lua();
void set_error(int err, lua_State *ls = nullptr);
void load_cmacro();
void load_chooks();
void init_throttle();
static void _getregistry(lua_State *, const char *name);
void vfnreturns(const char *par, va_list va);
bool proc_returns(const char *par) const;
bool calltopfn(lua_State *ls, const char *format, va_list args,
int retc = -1, va_list *fnr = nullptr);
maybe_bool callmbooleanfn(const char *fn, const char *params,
va_list args);
maybe_bool callmaybefn(const char *fn, const char *params,
va_list args);
int push_args(lua_State *ls, const char *format, va_list args,
va_list *cpto = nullptr);
int return_count(lua_State *ls, const char *format);
struct CLuaSave
{
const char *filename;
FILE *handle;
FILE *get_file();
};
friend class lua_call_throttle;
};
class lua_text_pattern : public base_pattern
{
public:
lua_text_pattern(const string &pattern);
~lua_text_pattern();
bool valid() const override;
bool matches(const string &s) const override;
pattern_match match_location(const string &s) const override;
const string &tostring() const override { return pattern; }
static bool is_lua_pattern(const string &s);
private:
bool translated;
bool isvalid;
string pattern;
string lua_fn_name;
static unsigned int lfndx;
bool translate() const;
void pre_pattern(string &pat, string &fn) const;
void post_pattern(string &pat, string &fn) const;
static string new_fn_name();
};
// Defined in main.cc
#ifdef DEBUG_GLOBALS
#define clua (*real_clua)
#endif
extern CLua clua;
string quote_lua_string(const string &s);
| 24.37551 | 77 | 0.66276 | [
"object",
"vector"
] |
0719afd27abf5b289725951ab9c6f33fc25d605f | 778 | h | C | twi.h | KerryL/rpi | 0c34b0b933c125ce27c7e58627c14092f3b72d44 | [
"MIT"
] | null | null | null | twi.h | KerryL/rpi | 0c34b0b933c125ce27c7e58627c14092f3b72d44 | [
"MIT"
] | null | null | null | twi.h | KerryL/rpi | 0c34b0b933c125ce27c7e58627c14092f3b72d44 | [
"MIT"
] | null | null | null | // File: twi.h
// Date: 2/15/2016
// Auth: K. Loux
// Desc: Object for handling TWI communication with a slave device.
#ifndef TWI_H_
#define TWI_H_
// Standard C++ headers
#include <string>
#include <vector>
#include <iostream>
class TWI
{
public:
TWI(const std::string& deviceFileName, const unsigned char& address,
std::ostream& outStream = std::cout);
virtual ~TWI();
bool Write(const std::vector<unsigned char>& data) const;
bool Read(std::vector<unsigned char>& data,
const unsigned short& size) const;
bool ConnectionOK() const;
std::string GetErrorString() const;
private:
const unsigned char address;
int busFileDescriptor;
static const unsigned int bufferSize;
unsigned char *buffer;
protected:
std::ostream& outStream;
};
#endif// TWI_H_
| 18.97561 | 69 | 0.719794 | [
"object",
"vector"
] |
071c9a7073fdbef80f8bb8ca969153576af91557 | 1,164 | h | C | src/compiler.h | dannyvankooten/pepper-lang | 55e1f3d64a1cc210928f3ff1aed4d45d068e21af | [
"MIT"
] | 34 | 2021-04-22T13:06:23.000Z | 2022-01-13T18:08:46.000Z | src/compiler.h | dannyvankooten/pepper-lang | 55e1f3d64a1cc210928f3ff1aed4d45d068e21af | [
"MIT"
] | 3 | 2021-04-22T15:44:04.000Z | 2021-04-28T08:07:46.000Z | src/compiler.h | dannyvankooten/monkey-c-monkey-do | 17d5d2973be67ae982ee4a80c76f42ab50ad9604 | [
"MIT"
] | 6 | 2020-06-01T01:53:52.000Z | 2021-09-13T01:37:56.000Z | #pragma once
#include "opcode.h"
#include "object.h"
#include "symbol_table.h"
struct emitted_instruction {
enum opcode opcode;
uint32_t position;
};
struct compiler_scope {
struct instruction *instructions;
struct emitted_instruction last_instruction;
struct emitted_instruction previous_instruction;
};
struct compiler {
struct object_list *constants;
struct symbol_table *symbol_table;
uint32_t scope_index;
struct compiler_scope scopes[64];
};
struct compiler *compiler_new();
struct compiler *compiler_new_with_state(struct symbol_table *t, struct object_list *constants);
void compiler_free(struct compiler *c);
int compile_program(struct compiler *compiler, const struct program *program);
struct bytecode *get_bytecode(struct compiler *c);
void concat_instructions(struct instruction *ins1, struct instruction *ins2);
const char *compiler_error_str(const int err);
uint32_t compiler_emit(struct compiler *c, const enum opcode opcode, ...);
void compiler_enter_scope(struct compiler *c);
struct instruction *compiler_leave_scope(struct compiler *c);
struct compiler_scope compiler_current_scope(struct compiler *c); | 33.257143 | 96 | 0.791237 | [
"object"
] |
0721018f82beee702451803e3490ff7fed992697 | 2,958 | h | C | smtk/bridge/discrete/operation/vtkCMBModelReadOperator.h | yumin/SMTK | d280f10c5b70953b2a0196f71832955c7fc75e7f | [
"BSD-3-Clause-Clear"
] | null | null | null | smtk/bridge/discrete/operation/vtkCMBModelReadOperator.h | yumin/SMTK | d280f10c5b70953b2a0196f71832955c7fc75e7f | [
"BSD-3-Clause-Clear"
] | 4 | 2016-11-10T15:49:51.000Z | 2017-02-06T23:24:16.000Z | smtk/bridge/discrete/operation/vtkCMBModelReadOperator.h | yumin/SMTK | d280f10c5b70953b2a0196f71832955c7fc75e7f | [
"BSD-3-Clause-Clear"
] | null | null | null | //=========================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//=========================================================================
// .NAME vtkCMBModelReadOperator -
// .SECTION Description
// Front end for the readers. Reads in a vtkPolyData and then figures
// out how to parse that vtkPolyData.
#ifndef __smtkdiscrete_vtkCMBModelReadOperator_h
#define __smtkdiscrete_vtkCMBModelReadOperator_h
#include "smtk/bridge/discrete/Exports.h" // For export macro
#include "vtkObject.h"
class vtkCMBParserBase;
class vtkDiscreteModelWrapper;
class vtkPolyData;
class vtkDiscreteModel;
namespace smtk {
namespace bridge {
namespace discrete {
class Session;
}
}
}
class SMTKDISCRETESESSION_EXPORT vtkCMBModelReadOperator : public vtkObject
{
public:
static vtkCMBModelReadOperator * New();
vtkTypeMacro(vtkCMBModelReadOperator,vtkObject);
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// Load the file into Model.
// The \a session will be used to assign UUIDs to entities if there are field arrays
// for entity UUIDs; if there is no UUID array for certain entities, the session will create
// and assign new UUIDs for them. This way cmb models will have consistent UUIDs across
// different runs so that entity-attribute associations, which is recorded with UUIDs, will
// be consistent, so is color-by entity UUIDs.
// If the session is NULL, the UUIDs will be different everytime we load a cmb model.
void Operate(vtkDiscreteModelWrapper* ModelWrapper,
smtk::bridge::discrete::Session* session);
//BTX
// Description:
// Load the file into Model.
void Read(vtkDiscreteModel* model,
smtk::bridge::discrete::Session* session);
//ETX
// Description:
// Get/Set the name of the input file.
vtkSetStringMacro(FileName);
vtkGetStringMacro(FileName);
// Description:
// Returns success (1) or failue (0) for Operation.
vtkGetMacro(OperateSucceeded, int);
// Description:
// Get the string used to reference the field data array that the
// file version is stored in.
static const char* GetCMBFileVersionString();
protected:
vtkCMBModelReadOperator();
virtual ~vtkCMBModelReadOperator();
vtkCMBParserBase* NewParser(vtkPolyData* MasterPoly);
private:
// Description:
// The name of the file to be read in.
char* FileName;
vtkCMBModelReadOperator(const vtkCMBModelReadOperator&); // Not implemented.
void operator=(const vtkCMBModelReadOperator&); // Not implemented.
// Description:
// Flag to indicate that the operation on the model succeeded (1) or not (0).
int OperateSucceeded;
};
#endif
| 31.806452 | 94 | 0.704192 | [
"model"
] |
07242bd0b9106eede3ca7174a2281abdaaae16e9 | 1,926 | h | C | Library/Mapping/NWSMappingContext.h | noodlewerk/Spaghe | 5f91b61c2a812f5fa7027b68202b35365714043c | [
"BSD-2-Clause"
] | 2 | 2015-01-16T05:30:29.000Z | 2015-02-22T23:37:56.000Z | Library/Mapping/NWSMappingContext.h | noodlewerk/Spaghe | 5f91b61c2a812f5fa7027b68202b35365714043c | [
"BSD-2-Clause"
] | null | null | null | Library/Mapping/NWSMappingContext.h | noodlewerk/Spaghe | 5f91b61c2a812f5fa7027b68202b35365714043c | [
"BSD-2-Clause"
] | 2 | 2015-04-29T15:15:44.000Z | 2021-02-09T05:03:43.000Z | //
// NWSMappingContext.h
// Spaghetti
//
// Copyright (c) 2012 noodlewerk. All rights reserved.
//
#import <Foundation/Foundation.h>
@class NWSStore, NWSPath;
// path stack is only available in debug
#if DEBUG
#define DEBUG_CONTEXT_PUSH(__context,__path) [(__context) pushPath:(__path)]
#define DEBUG_CONTEXT_POP(__context) [(__context) popPath]
#else
#define DEBUG_CONTEXT_PUSH(__context,__path)
#define DEBUG_CONTEXT_POP(__context)
#endif
/**
* The mapping context is a set of objects that are available during the mapping process.
*
* The mapping context is provided to mappings and transforms to allow access to for example the object store.
*
* @see NWSMapping
* @see NWSStore
*/
@interface NWSMappingContext : NSObject
/**
* The store this context is based on.
*/
@property (nonatomic, strong) NWSStore *store;
/**
* The index of currently mapped object in the element array above. For example, we map the array:
*
* [
* {"name":"a"},
* {"name":"b","child":{"name":"c"}}
* ]
*
* When mapping object with name 'a', the indexInArray == 0, and when mapping object 'b' and 'c', the indexInArray == 1.
*
* This is primarily used for setting the order key.
*/
@property (nonatomic, readonly) NSUInteger indexInArray;
- (id)initWithStore:(NWSStore *)store;
/**
* Marks the value as 'done'.
* @param value Subject
*/
- (void)doing:(id)value;
/**
* Returns true if the value was marked 'done'.
* @param value Subject
*/
- (BOOL)did:(id)value;
/**
* Push the current index on the stack and set to zero.
* @see indexInArray
*/
- (void)pushIndexInArray;
/**
* Increment the current index by one.
* @see indexInArray
*/
- (void)incIndexInArray;
/**
* Pop the current index from the stack.
* @see indexInArray
*/
- (void)popIndexInArray;
#if DEBUG
- (void)pushPath:(NWSPath *)path;
- (void)popPath;
- (NWSPath *)pathStack;
#endif
- (NSString *)path;
@end
| 21.164835 | 120 | 0.683281 | [
"object"
] |
072d37d4631575c440a54750aea0056f8e53650e | 1,914 | h | C | arch/arm/src/rtl8720c/chip.h | alvin1991/incubator-nuttx | b4fe0422624cfdc5a1925696f6ca7191a6d45326 | [
"Apache-2.0"
] | 1,006 | 2019-12-17T23:45:41.000Z | 2022-03-31T19:42:44.000Z | arch/arm/src/rtl8720c/chip.h | alvin1991/incubator-nuttx | b4fe0422624cfdc5a1925696f6ca7191a6d45326 | [
"Apache-2.0"
] | 2,661 | 2019-12-21T15:16:09.000Z | 2022-03-31T22:30:04.000Z | arch/arm/src/rtl8720c/chip.h | alvin1991/incubator-nuttx | b4fe0422624cfdc5a1925696f6ca7191a6d45326 | [
"Apache-2.0"
] | 613 | 2019-12-21T10:17:37.000Z | 2022-03-28T09:42:20.000Z | /****************************************************************************
* arch/arm/src/rtl8720c/chip.h
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
#ifndef __ARCH_ARM_SRC_AMEBA_CHIP_H
#define __ARCH_ARM_SRC_AMEBA_CHIP_H
/****************************************************************************
* Included Files
****************************************************************************/
#ifndef __ASSEMBLY__
# include <stdint.h>
# include <sys/types.h>
#endif
#include <arch/chip/chip.h>
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
#ifndef ARRAY_SIZE
# define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))
#endif
/* If the common ARMv7-M vector handling logic is used,
* then it expects the following
* definition in this file that provides the number of
* supported external interrupts.
*/
#define ARMV8M_PERIPHERAL_INTERRUPTS (CONFIG_AMEBA_NR_IRQS - 16)
#endif /* __ARCH_ARM_SRC_AMEBA_CHIP_H */
| 39.061224 | 78 | 0.565831 | [
"vector"
] |
0743c5ac2def0c89d8d18b55af221407c2e6a7c1 | 8,731 | h | C | stlsoft/winstl_clipboard_format_sequence.h | masscry/dmc | c7638f7c524a65bc2af0876c76621d8a11da42bb | [
"BSL-1.0"
] | 86 | 2018-05-24T12:03:44.000Z | 2022-03-13T03:01:25.000Z | stlsoft/winstl_clipboard_format_sequence.h | masscry/dmc | c7638f7c524a65bc2af0876c76621d8a11da42bb | [
"BSL-1.0"
] | 1 | 2019-05-30T01:38:40.000Z | 2019-10-26T07:15:01.000Z | stlsoft/winstl_clipboard_format_sequence.h | masscry/dmc | c7638f7c524a65bc2af0876c76621d8a11da42bb | [
"BSL-1.0"
] | 14 | 2018-07-16T08:29:12.000Z | 2021-08-23T06:21:30.000Z | /* /////////////////////////////////////////////////////////////////////////////
* File: winstl_clipboard_format_sequence.h
*
* Purpose: Enumerates clipboard formats.
*
* Created: 11th May 2003
* Updated: 11th September 2004
*
* Home: http://stlsoft.org/
*
* Copyright (c) 2003-2004, Matthew Wilson and Synesis Software
* 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(s) of Matthew Wilson and Synesis Software nor the names of
* any contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* ////////////////////////////////////////////////////////////////////////// */
/// \file winstl_clipboard_format_sequence.h
///
/// Enumerates clipboard formats.
#ifndef WINSTL_INCL_H_WINSTL_CLIPBOARD_FORMAT_SEQUENCE
#define WINSTL_INCL_H_WINSTL_CLIPBOARD_FORMAT_SEQUENCE
#ifndef __STLSOFT_DOCUMENTATION_SKIP_SECTION
# define WINSTL_VER_H_WINSTL_CLIPBOARD_FORMAT_SEQUENCE_MAJOR 2
# define WINSTL_VER_H_WINSTL_CLIPBOARD_FORMAT_SEQUENCE_MINOR 0
# define WINSTL_VER_H_WINSTL_CLIPBOARD_FORMAT_SEQUENCE_REVISION 1
# define WINSTL_VER_H_WINSTL_CLIPBOARD_FORMAT_SEQUENCE_EDIT 10
#endif /* !__STLSOFT_DOCUMENTATION_SKIP_SECTION */
/* /////////////////////////////////////////////////////////////////////////////
* Includes
*/
#ifndef WINSTL_INCL_H_WINSTL
# include "winstl.h" // Include the WinSTL root header
#endif /* !WINSTL_INCL_H_WINSTL */
/* /////////////////////////////////////////////////////////////////////////////
* Namespace
*/
#ifndef _WINSTL_NO_NAMESPACE
# if defined(_STLSOFT_NO_NAMESPACE) || \
defined(__STLSOFT_DOCUMENTATION_SKIP_SECTION)
/* There is no stlsoft namespace, so must define ::winstl */
namespace winstl
{
# else
/* Define stlsoft::winstl_project */
namespace stlsoft
{
namespace winstl_project
{
# endif /* _STLSOFT_NO_NAMESPACE */
#endif /* !_WINSTL_NO_NAMESPACE */
/* /////////////////////////////////////////////////////////////////////////////
* Classes
*/
// class clipboard_format_sequence
/// This class provides an STL-like sequence for iterating the clipboard formats for the current process
class clipboard_format_sequence
{
public:
/// The type
typedef clipboard_format_sequence class_type;
/// The value type
typedef UINT value_type;
/// The size type
typedef ws_size_t size_type;
/// The difference type
typedef ws_ptrdiff_t difference_type;
/// \name Construction
/// @{
public:
/// Constructs a sequence object, attempting to open the clipboard
clipboard_format_sequence()
: m_bOpen(::OpenClipboard(NULL) != FALSE)
{}
/// Release any resources aquired
~clipboard_format_sequence()
{
if(m_bOpen)
{
::CloseClipboard();
}
}
/// @}
/// \name Iteration
/// @{
public:
/// Non-mutating iterator class
class const_iterator
{
friend class clipboard_format_sequence;
public:
/// The type
typedef const_iterator class_type;
/// The container type
typedef clipboard_format_sequence container_type;
/// \name Construction
/// @{
private:
/// Constructs an iterator from the given format
const_iterator(UINT nextFmt)
: m_nextFmt(nextFmt)
{}
public:
/// Constructs an iterator
const_iterator()
: m_nextFmt(0)
{}
/// Copy constructor
const_iterator(class_type const &rhs)
: m_nextFmt(rhs.m_nextFmt)
{}
/// Copy assignment operator
class_type &operator =(class_type const &rhs)
{
m_nextFmt = rhs.m_nextFmt;
return *this;
}
/// @}
public:
/// Pre-increment operator
class_type &operator ++()
{
winstl_message_assert("Incrementing an invalid iterator!", m_nextFmt != 0);
m_nextFmt = ::EnumClipboardFormats(m_nextFmt);
return *this;
}
/// Post-increment operator
class_type operator ++(int)
{
class_type ret(*this);
operator ++();
return ret;
}
value_type operator *() const
{
winstl_message_assert("Dereferencing an invalid iterator!", m_nextFmt != 0);
return m_nextFmt;
}
/// Evaluates whether \c this and \c rhs are equivalent
///
/// \param rhs The instance against which to compare
/// \retval true If \c this and \c rhs are equivalent
/// \retval false If \c this and \c rhs are not equivalent
ws_bool_t operator ==(class_type const &rhs) const
{
return m_nextFmt == rhs.m_nextFmt;
}
/// Evaluates whether \c this and \c rhs are not equivalent
///
/// \param rhs The instance against which to compare
/// \retval true If \c this and \c rhs are not equivalent
/// \retval false If \c this and \c rhs are equivalent
ws_bool_t operator !=(class_type const &rhs) const
{
return !operator ==(rhs);
}
/// Members
private:
UINT m_nextFmt;
};
/// Begins the iteration
///
/// \return An iterator representing the start of the sequence
const_iterator begin() const
{
return const_iterator(::EnumClipboardFormats(0));
}
/// Ends the iteration
///
/// \return An iterator representing the end of the sequence
const_iterator end() const
{
return const_iterator(0);
}
/// Indicates whether the search sequence is empty
ws_bool_t empty() const
{
return begin() != end();
}
/// Returns the number of elements in the sequence
size_type size() const
{
return static_cast<size_type>(::CountClipboardFormats());
}
/// Indicates whether the search sequence is valid
///
/// \note The sequence may not be able to access the clipboard formats if another window is currently holding the clipboard via a call to <b>OpenClipboard()</b>
ws_bool_t inaccessible() const
{
return !m_bOpen;
}
/// @}
/// Members
private:
ws_bool_t m_bOpen;
/// Not to be implemented
private:
clipboard_format_sequence(clipboard_format_sequence const &);
clipboard_format_sequence &operator =(clipboard_format_sequence const &);
};
/* ////////////////////////////////////////////////////////////////////////// */
#ifndef _WINSTL_NO_NAMESPACE
# if defined(_STLSOFT_NO_NAMESPACE) || \
defined(__STLSOFT_DOCUMENTATION_SKIP_SECTION)
} // namespace winstl
# else
} // namespace winstl_project
} // namespace stlsoft
# endif /* _STLSOFT_NO_NAMESPACE */
#endif /* !_WINSTL_NO_NAMESPACE */
/* ////////////////////////////////////////////////////////////////////////// */
#endif /* WINSTL_INCL_H_WINSTL_CLIPBOARD_FORMAT_SEQUENCE */
/* ////////////////////////////////////////////////////////////////////////// */
| 31.293907 | 165 | 0.588592 | [
"object"
] |
07490da5d61407dba7724a5de08ae7bbe6a98e1a | 990 | h | C | Engine/Rendering/Renderer.h | GreatIndieDeveloper/StrawEngine-Core | 4f4a89e1fb970b6a2963371b90fbfab64f45bba8 | [
"Apache-2.0"
] | 2 | 2019-05-07T06:50:33.000Z | 2019-05-07T14:25:50.000Z | Engine/Rendering/Renderer.h | GreatIndieDeveloper/StrawEngine-Core | 4f4a89e1fb970b6a2963371b90fbfab64f45bba8 | [
"Apache-2.0"
] | null | null | null | Engine/Rendering/Renderer.h | GreatIndieDeveloper/StrawEngine-Core | 4f4a89e1fb970b6a2963371b90fbfab64f45bba8 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "../Addons/Sprite.h"
#include <GL/glew.h>
#include "../Math/Math.h"
#include <vector>
#include <algorithm>
#include <deque>
#include <map>
#include <unordered_map>
#define SPRITESIZE sizeof(Vertex) * 4
#define MAXSPRITES 190000
#define BUFFERSIZE SPRITESIZE * MAXSPRITES
#define INDICESBUFFERSIZE MAXSPRITES * 6
struct RenderBatch{
public:
RenderBatch(){
sprites.reserve(100000);
};
public:
unsigned int TextureID;
std::vector<Sprite*> sprites;
};
class Renderer
{
public:
Renderer();
~Renderer();
void Init();
void Begin();
//Submit a Sprite to the Renderer remember to end it after
void Submit(Sprite* input);
void End();
void Looper();
unsigned int m_VAO, m_VBO, m_IBO;
private:
void InnerSubmit(Sprite* input);
int IndNum(int vecnum);
int IndNumMap(int mapnum);
int m_IndexCounter;
Vertex* m_Buffer;
std::vector<RenderBatch*> renderBatches;
std::map<int,std::vector<Sprite*>> RQ;
};
| 20.204082 | 60 | 0.684848 | [
"vector"
] |
725f6df0dc15943fbed3e75c540a33f4f212c7fa | 2,275 | h | C | components/subresource_filter/content/browser/ruleset_publisher.h | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | components/subresource_filter/content/browser/ruleset_publisher.h | Ron423c/chromium | 2edf7b980065b648f8b2a6e52193d83832fe36b7 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | components/subresource_filter/content/browser/ruleset_publisher.h | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2018 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 COMPONENTS_SUBRESOURCE_FILTER_CONTENT_BROWSER_RULESET_PUBLISHER_H_
#define COMPONENTS_SUBRESOURCE_FILTER_CONTENT_BROWSER_RULESET_PUBLISHER_H_
#include "base/callback.h"
#include "base/files/file.h"
#include "base/files/file_path.h"
#include "base/memory/scoped_refptr.h"
#include "base/single_thread_task_runner.h"
#include "components/subresource_filter/content/browser/verified_ruleset_dealer.h"
namespace subresource_filter {
// Interface for a RulesetService that defines operations that distribute the
// ruleset to the renderer processes via the RulesetDealer.
class RulesetPublisher {
public:
virtual ~RulesetPublisher() = default;
// Schedules file open and use it as ruleset file. In the case of success,
// the new and valid |base::File| is passed to |callback|. In the case of
// error an invalid |base::File| is passed to |callback|. The previous
// ruleset file will be used (if any). In either case, the supplied
// unique_ptr always contains a non-null |base::File|.
virtual void TryOpenAndSetRulesetFile(
const base::FilePath& file_path,
int expected_checksum,
base::OnceCallback<void(RulesetFilePtr)> callback) = 0;
// Redistributes the new version of the |ruleset| to all existing consumers,
// and sets up |ruleset| to be distributed to all future consumers.
virtual void PublishNewRulesetVersion(RulesetFilePtr ruleset_data) = 0;
// Task queue for best effort tasks in the thread the object was created in.
// Used for tasks triggered on RulesetService instantiation so it doesn't
// interfere with startup. Runs in the UI thread.
virtual scoped_refptr<base::SingleThreadTaskRunner>
BestEffortTaskRunner() = 0;
// Gets the ruleset dealer associated with the RulesetPublisher.
virtual VerifiedRulesetDealer::Handle* GetRulesetDealer() = 0;
// Set the callback on publish associated with the RulesetPublisher.
virtual void SetRulesetPublishedCallbackForTesting(
base::OnceClosure callback) = 0;
};
} // namespace subresource_filter
#endif // COMPONENTS_SUBRESOURCE_FILTER_CONTENT_BROWSER_RULESET_SERVICE_H_
| 42.12963 | 82 | 0.777582 | [
"object"
] |
726a55d22968840a1871c511a41594ddad57b592 | 840 | h | C | SymbolTable/ClassStruct.h | IKholopov/shishkin_forest | d6812ecc305ad35373384fb5a3abdf14502bc148 | [
"Apache-2.0"
] | 4 | 2018-02-15T20:54:18.000Z | 2018-06-20T16:22:31.000Z | SymbolTable/ClassStruct.h | IKholopov/shishkin_forest | d6812ecc305ad35373384fb5a3abdf14502bc148 | [
"Apache-2.0"
] | 1 | 2018-02-13T10:04:06.000Z | 2018-02-20T07:30:07.000Z | SymbolTable/ClassStruct.h | IKholopov/shishkin_forest | d6812ecc305ad35373384fb5a3abdf14502bc148 | [
"Apache-2.0"
] | 2 | 2017-12-17T01:22:19.000Z | 2018-08-05T16:45:31.000Z | #pragma once
#include <vector>
#include <map>
#include "MethodInfo.h"
namespace SymbolTable {
interface IClassStruct {
virtual ~IClassStruct() {}
virtual void AddClassName(const StringSymbol* className) = 0;
virtual void AddToVtable(const MethodInfo* info) = 0;
virtual void AddField(const VariableInfo* info) = 0;
virtual const std::vector<const MethodInfo*>& GetVTable() const = 0;
virtual const StringSymbol* GetTableName() const = 0;
virtual IR::IExp* GetFieldFrom(const StringSymbol* fieldName, IR::IExp* base, const Position& position) const = 0;
virtual IR::IExp* GetVirtualMethodAddress(const StringSymbol* methodName,
IR::IExp* base, const Position& position) const = 0;
virtual IR::IExp* AllocateNew(const Position& position) const = 0;
};
}
| 31.111111 | 118 | 0.685714 | [
"vector"
] |
726f0d42004312c2d400a7518daf1a5589ffdcab | 158,973 | c | C | orc/orcrules-neon.c | stb-tester/orc | 8d32f2d9f4a803e8e27c2f26ab54233d03efd023 | [
"BSD-3-Clause"
] | 45 | 2015-12-03T12:07:49.000Z | 2022-03-11T20:17:36.000Z | orc/orcrules-neon.c | stb-tester/orc | 8d32f2d9f4a803e8e27c2f26ab54233d03efd023 | [
"BSD-3-Clause"
] | null | null | null | orc/orcrules-neon.c | stb-tester/orc | 8d32f2d9f4a803e8e27c2f26ab54233d03efd023 | [
"BSD-3-Clause"
] | 15 | 2016-03-20T15:15:45.000Z | 2022-01-06T10:42:31.000Z |
#include "config.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <orc/orcprogram.h>
#include <orc/orcarm.h>
#include <orc/orcdebug.h>
#include <orc/orcneon.h>
static void orc_neon_emit_loadib (OrcCompiler *compiler, OrcVariable *dest, int param);
static void orc_neon_emit_loadiw (OrcCompiler *compiler, OrcVariable *dest, int param);
static void orc_neon_emit_loadiq (OrcCompiler *compiler, OrcVariable *dest, long long param);
static void orc_neon_emit_loadpq (OrcCompiler *compiler, int dest, int param);
const char *orc_neon_reg_name (int reg)
{
static const char *vec_regs[] = {
"d0", "d1", "d2", "d3",
"d4", "d5", "d6", "d7",
"d8", "d9", "d10", "d11",
"d12", "d13", "d14", "d15",
"d16", "d17", "d18", "d19",
"d20", "d21", "d22", "d23",
"d24", "d25", "d26", "d27",
"d28", "d29", "d30", "d31",
};
if (reg < ORC_VEC_REG_BASE || reg >= ORC_VEC_REG_BASE+32) {
return "ERROR";
}
return vec_regs[reg&0x1f];
}
const char *orc_neon_reg_name_quad (int reg)
{
static const char *vec_regs[] = {
"q0", "ERROR", "q1", "ERROR",
"q2", "ERROR", "q3", "ERROR",
"q4", "ERROR", "q5", "ERROR",
"q6", "ERROR", "q7", "ERROR",
"q8", "ERROR", "q9", "ERROR",
"q10", "ERROR", "q11", "ERROR",
"q12", "ERROR", "q13", "ERROR",
"q14", "ERROR", "q15", "ERROR",
};
if (reg < ORC_VEC_REG_BASE || reg >= ORC_VEC_REG_BASE+32) {
return "ERROR";
}
return vec_regs[reg&0x1f];
}
/** the names of the SIMD registers when used in a scalar way */
const char *orc_neon64_reg_name_scalar (int reg, int size)
{
static const char *vec_regs[5][32] = {
{ /** 8-bit */
"b0", "b1", "b2", "b3",
"b4", "b5", "b6", "b7",
"b8", "b9", "b10", "b11",
"b12", "b13", "b14", "b15",
"b16", "b17", "b18", "b19",
"b20", "b21", "b22", "b23",
"b24", "b25", "b26", "b27",
"b28", "b29", "b30", "b31"
},
{ /** 16-bit */
"h0", "h1", "h2", "h3",
"h4", "h5", "h6", "h7",
"h8", "h9", "h10", "h11",
"h12", "h13", "h14", "h15",
"h16", "h17", "h18", "h19",
"h20", "h21", "h22", "h23",
"h24", "h25", "h26", "h27",
"h28", "h29", "h30", "h31"
},
{ /** 32-bit */
"s0", "s1", "s2", "s3",
"s4", "s5", "s6", "s7",
"s8", "s9", "s10", "s11",
"s12", "s13", "s14", "s15",
"s16", "s17", "s18", "s19",
"s20", "s21", "s22", "s23",
"s24", "s25", "s26", "s27",
"s28", "s29", "s30", "s31"
},
{ /** 64-bit */
"d0", "d1", "d2", "d3",
"d4", "d5", "d6", "d7",
"d8", "d9", "d10", "d11",
"d12", "d13", "d14", "d15",
"d16", "d17", "d18", "d19",
"d20", "d21", "d22", "d23",
"d24", "d25", "d26", "d27",
"d28", "d29", "d30", "d31"
},
{ /** 128-bit */
"q0", "q1", "q2", "q3",
"q4", "q5", "q6", "q7",
"q8", "q9", "q10", "q11",
"q12", "q13", "q14", "q15",
"q16", "q17", "q18", "q19",
"q20", "q21", "q22", "q23",
"q24", "q25", "q26", "q27",
"q28", "q29", "q30", "q31"
}
};
int size_idx;
if (reg < ORC_VEC_REG_BASE || reg >= ORC_VEC_REG_BASE+32) {
return "ERROR";
}
size_idx = -1;
while (size) {
size_idx++;
size >>= 1;
}
if (size_idx < 0 || size_idx >= 5) {
return "ERROR";
}
return vec_regs[size_idx][reg&0x1f];
}
/** the names of the SIMD vector registers when used for vectorization */
const char *orc_neon64_reg_name_vector (int reg, int size, int quad)
{
static const char *vec_regs[8][32] = {
{
"v0.8b", "v1.8b", "v2.8b", "v3.8b",
"v4.8b", "v5.8b", "v6.8b", "v7.8b",
"v8.8b", "v9.8b", "v10.8b", "v11.8b",
"v12.8b", "v13.8b", "v14.8b", "v15.8b",
"v16.8b", "v17.8b", "v18.8b", "v19.8b",
"v20.8b", "v21.8b", "v22.8b", "v23.8b",
"v24.8b", "v25.8b", "v26.8b", "v27.8b",
"v28.8b", "v29.8b", "v30.8b", "v31.8b"
},
{
"v0.16b", "v1.16b", "v2.16b", "v3.16b",
"v4.16b", "v5.16b", "v6.16b", "v7.16b",
"v8.16b", "v9.16b", "v10.16b", "v11.16b",
"v12.16b", "v13.16b", "v14.16b", "v15.16b",
"v16.16b", "v17.16b", "v18.16b", "v19.16b",
"v20.16b", "v21.16b", "v22.16b", "v23.16b",
"v24.16b", "v25.16b", "v26.16b", "v27.16b",
"v28.16b", "v29.16b", "v30.16b", "v31.16b"
},
{
"v0.4h", "v1.4h", "v2.4h", "v3.4h",
"v4.4h", "v5.4h", "v6.4h", "v7.4h",
"v8.4h", "v9.4h", "v10.4h", "v11.4h",
"v12.4h", "v13.4h", "v14.4h", "v15.4h",
"v16.4h", "v17.4h", "v18.4h", "v19.4h",
"v20.4h", "v21.4h", "v22.4h", "v23.4h",
"v24.4h", "v25.4h", "v26.4h", "v27.4h",
"v28.4h", "v29.4h", "v30.4h", "v31.4h"
},
{
"v0.8h", "v1.8h", "v2.8h", "v3.8h",
"v4.8h", "v5.8h", "v6.8h", "v7.8h",
"v8.8h", "v9.8h", "v10.8h", "v11.8h",
"v12.8h", "v13.8h", "v14.8h", "v15.8h",
"v16.8h", "v17.8h", "v18.8h", "v19.8h",
"v20.8h", "v21.8h", "v22.8h", "v23.8h",
"v24.8h", "v25.8h", "v26.8h", "v27.8h",
"v28.8h", "v29.8h", "v30.8h", "v31.8h"
},
{
"v0.2s", "v1.2s", "v2.2s", "v3.2s",
"v4.2s", "v5.2s", "v6.2s", "v7.2s",
"v8.2s", "v9.2s", "v10.2s", "v11.2s",
"v12.2s", "v13.2s", "v14.2s", "v15.2s",
"v16.2s", "v17.2s", "v18.2s", "v19.2s",
"v20.2s", "v21.2s", "v22.2s", "v23.2s",
"v24.2s", "v25.2s", "v26.2s", "v27.2s",
"v28.2s", "v29.2s", "v30.2s", "v31.2s"
},
{
"v0.4s", "v1.4s", "v2.4s", "v3.4s",
"v4.4s", "v5.4s", "v6.4s", "v7.4s",
"v8.4s", "v9.4s", "v10.4s", "v11.4s",
"v12.4s", "v13.4s", "v14.4s", "v15.4s",
"v16.4s", "v17.4s", "v18.4s", "v19.4s",
"v20.4s", "v21.4s", "v22.4s", "v23.4s",
"v24.4s", "v25.4s", "v26.4s", "v27.4s",
"v28.4s", "v29.4s", "v30.4s", "v31.4s"
},
{
"v0.1d", "v1.1d", "v2.1d", "v3.1d",
"v4.1d", "v5.1d", "v6.1d", "v7.1d",
"v8.1d", "v9.1d", "v10.1d", "v11.1d",
"v12.1d", "v13.1d", "v14.1d", "v15.1d",
"v16.1d", "v17.1d", "v18.1d", "v19.1d",
"v20.1d", "v21.1d", "v22.1d", "v23.1d",
"v24.1d", "v25.1d", "v26.1d", "v27.1d",
"v28.1d", "v29.1d", "v30.1d", "v31.1d"
},
{
"v0.2d", "v1.2d", "v2.2d", "v3.2d",
"v4.2d", "v5.2d", "v6.2d", "v7.2d",
"v8.2d", "v9.2d", "v10.2d", "v11.2d",
"v12.2d", "v13.2d", "v14.2d", "v15.2d",
"v16.2d", "v17.2d", "v18.2d", "v19.2d",
"v20.2d", "v21.2d", "v22.2d", "v23.2d",
"v24.2d", "v25.2d", "v26.2d", "v27.2d",
"v28.2d", "v29.2d", "v30.2d", "v31.2d"
}
};
int size_idx;
if (reg < ORC_VEC_REG_BASE || reg >= ORC_VEC_REG_BASE+32) {
return "ERROR";
}
size_idx = -1;
while (size) {
size_idx++;
size >>= 1;
}
if (size_idx < 0 || size_idx >= 4) {
return "ERROR";
}
if (quad != 0 && quad != 1) {
return "ERROR";
}
return vec_regs[size_idx*2+quad][reg&0x1f];
}
/** a single element from a SIMD vector register as a scalar operand */
const char *orc_neon64_reg_name_vector_single (int reg, int size)
{
static const char *vec_regs[4][32] = {
{
"v0.b", "v1.b", "v2.b", "v3.b",
"v4.b", "v5.b", "v6.b", "v7.b",
"v8.b", "v9.b", "v10.b", "v11.b",
"v12.b", "v13.b", "v14.b", "v15.b",
"v16.b", "v17.b", "v18.b", "v19.b",
"v20.b", "v21.b", "v22.b", "v23.b",
"v24.b", "v25.b", "v26.b", "v27.b",
"v28.b", "v29.b", "v30.b", "v31.b"
},
{
"v0.h", "v1.h", "v2.h", "v3.h",
"v4.h", "v5.h", "v6.h", "v7.h",
"v8.h", "v9.h", "v10.h", "v11.h",
"v12.h", "v13.h", "v14.h", "v15.h",
"v16.h", "v17.h", "v18.h", "v19.h",
"v20.h", "v21.h", "v22.h", "v23.h",
"v24.h", "v25.h", "v26.h", "v27.h",
"v28.h", "v29.h", "v30.h", "v31.h"
},
{
"v0.s", "v1.s", "v2.s", "v3.s",
"v4.s", "v5.s", "v6.s", "v7.s",
"v8.s", "v9.s", "v10.s", "v11.s",
"v12.s", "v13.s", "v14.s", "v15.s",
"v16.s", "v17.s", "v18.s", "v19.s",
"v20.s", "v21.s", "v22.s", "v23.s",
"v24.s", "v25.s", "v26.s", "v27.s",
"v28.s", "v29.s", "v30.s", "v31.s"
},
{
"v0.d", "v1.d", "v2.d", "v3.d",
"v4.d", "v5.d", "v6.d", "v7.d",
"v8.d", "v9.d", "v10.d", "v11.d",
"v12.d", "v13.d", "v14.d", "v15.d",
"v16.d", "v17.d", "v18.d", "v19.d",
"v20.d", "v21.d", "v22.d", "v23.d",
"v24.d", "v25.d", "v26.d", "v27.d",
"v28.d", "v29.d", "v30.d", "v31.d"
},
};
int size_idx;
if (reg < ORC_VEC_REG_BASE || reg >= ORC_VEC_REG_BASE+32) {
return "ERROR";
}
size_idx = -1;
while (size) {
size_idx++;
size >>= 1;
}
if (size_idx < 0 || size_idx >= 4) {
return "ERROR";
}
return vec_regs[size_idx][reg&0x1f];
}
static void
orc_neon_emit_binary (OrcCompiler *p, const char *name, unsigned int code,
int dest, int src1, int src2)
{
ORC_ASSERT((code & 0x004ff0af) == 0);
ORC_ASM_CODE(p," %s %s, %s, %s\n", name,
orc_neon_reg_name (dest), orc_neon_reg_name (src1),
orc_neon_reg_name (src2));
code |= (dest&0xf)<<12;
code |= ((dest>>4)&0x1)<<22;
code |= (src1&0xf)<<16;
code |= ((src1>>4)&0x1)<<7;
code |= (src2&0xf)<<0;
code |= ((src2>>4)&0x1)<<5;
orc_arm_emit (p, code);
}
static void
orc_neon64_emit_binary (OrcCompiler *p, const char *name, unsigned int code,
OrcVariable dest, OrcVariable src1, OrcVariable src2, int vec_shift)
{
int is_quad = 0;
if (p->insn_shift == vec_shift + 1) {
is_quad = 1;
} else if (p->insn_shift > vec_shift + 1) {
ORC_COMPILER_ERROR(p, "out-of-shift");
return;
}
ORC_ASM_CODE(p," %s %s, %s, %s\n", name,
orc_neon64_reg_name_vector (dest.alloc, dest.size, is_quad),
orc_neon64_reg_name_vector (src1.alloc, src1.size, is_quad),
orc_neon64_reg_name_vector (src2.alloc, src2.size, is_quad));
code |= (is_quad&0x1)<<30;
code |= (src2.alloc&0x1f)<<16;
code |= (src1.alloc&0x1f)<<5;
code |= (dest.alloc&0x1f);
orc_arm_emit (p, code);
}
#define NEON_BINARY(code,a,b,c) \
((code) | \
(((a)&0xf)<<12) | \
((((a)>>4)&0x1)<<22) | \
(((b)&0xf)<<16) | \
((((b)>>4)&0x1)<<7) | \
(((c)&0xf)<<0) | \
((((c)>>4)&0x1)<<5))
static void
orc_neon_emit_binary_long (OrcCompiler *p, const char *name, unsigned int code,
int dest, int src1, int src2)
{
ORC_ASSERT((code & 0x004ff0af) == 0);
ORC_ASM_CODE(p," %s %s, %s, %s\n", name,
orc_neon_reg_name_quad (dest), orc_neon_reg_name (src1),
orc_neon_reg_name (src2));
code |= (dest&0xf)<<12;
code |= ((dest>>4)&0x1)<<22;
code |= (src1&0xf)<<16;
code |= ((src1>>4)&0x1)<<7;
code |= (src2&0xf)<<0;
code |= ((src2>>4)&0x1)<<5;
orc_arm_emit (p, code);
}
#if 0
static void
orc_neon_emit_binary_narrow (OrcCompiler *p, const char *name, unsigned int code,
int dest, int src1, int src2)
{
ORC_ASSERT((code & 0x004ff0af) == 0);
ORC_ASM_CODE(p," %s %s, %s, %s\n", name,
orc_neon_reg_name (dest), orc_neon_reg_name_quad (src1),
orc_neon_reg_name_quad (src2));
code |= (dest&0xf)<<12;
code |= ((dest>>4)&0x1)<<22;
code |= (src1&0xf)<<16;
code |= ((src1>>4)&0x1)<<7;
code |= (src2&0xf)<<0;
code |= ((src2>>4)&0x1)<<5;
orc_arm_emit (p, code);
}
#endif
static void
orc_neon_emit_binary_quad (OrcCompiler *p, const char *name, unsigned int code,
int dest, int src1, int src2)
{
ORC_ASSERT((code & 0x004ff0af) == 0);
ORC_ASM_CODE(p," %s %s, %s, %s\n", name,
orc_neon_reg_name_quad (dest), orc_neon_reg_name_quad (src1),
orc_neon_reg_name_quad (src2));
code |= (dest&0xf)<<12;
code |= ((dest>>4)&0x1)<<22;
code |= (src1&0xf)<<16;
code |= ((src1>>4)&0x1)<<7;
code |= (src2&0xf)<<0;
code |= ((src2>>4)&0x1)<<5;
code |= 0x40;
orc_arm_emit (p, code);
}
static void
orc_neon_emit_unary (OrcCompiler *p, const char *name, unsigned int code,
int dest, int src1)
{
ORC_ASSERT((code & 0x0040f02f) == 0);
ORC_ASM_CODE(p," %s %s, %s\n", name,
orc_neon_reg_name (dest), orc_neon_reg_name (src1));
code |= (dest&0xf)<<12;
code |= ((dest>>4)&0x1)<<22;
code |= (src1&0xf)<<0;
code |= ((src1>>4)&0x1)<<5;
orc_arm_emit (p, code);
}
static void
orc_neon64_emit_unary (OrcCompiler *p, const char *name, unsigned int code,
OrcVariable dest, OrcVariable src1, int vec_shift)
{
int is_quad = 0;
if (p->insn_shift == vec_shift + 1) {
is_quad = 1;
} else if (p->insn_shift > vec_shift + 1) {
ORC_COMPILER_ERROR(p, "out-of-shift");
return;
}
ORC_ASM_CODE(p," %s %s, %s\n", name,
orc_neon64_reg_name_vector (dest.alloc, dest.size, is_quad),
orc_neon64_reg_name_vector (src1.alloc, src1.size, is_quad));
code |= (is_quad&0x1)<<30;
code |= (src1.alloc&0x1f)<<5;
code |= (dest.alloc&0x1f);
orc_arm_emit (p, code);
}
static void
orc_neon_emit_unary_long (OrcCompiler *p, const char *name, unsigned int code,
int dest, int src1)
{
ORC_ASSERT((code & 0x0040f02f) == 0);
ORC_ASM_CODE(p," %s %s, %s\n", name,
orc_neon_reg_name_quad (dest), orc_neon_reg_name (src1));
code |= (dest&0xf)<<12;
code |= ((dest>>4)&0x1)<<22;
code |= (src1&0xf)<<0;
code |= ((src1>>4)&0x1)<<5;
orc_arm_emit (p, code);
}
static void
orc_neon_emit_unary_narrow (OrcCompiler *p, const char *name, unsigned int code,
int dest, int src1)
{
ORC_ASSERT((code & 0x0040f02f) == 0);
ORC_ASM_CODE(p," %s %s, %s\n", name,
orc_neon_reg_name (dest), orc_neon_reg_name_quad (src1));
code |= (dest&0xf)<<12;
code |= ((dest>>4)&0x1)<<22;
code |= (src1&0xf)<<0;
code |= ((src1>>4)&0x1)<<5;
orc_arm_emit (p, code);
}
static void
orc_neon_emit_unary_quad (OrcCompiler *p, const char *name, unsigned int code,
int dest, int src1)
{
ORC_ASSERT((code & 0x0040f02f) == 0);
ORC_ASM_CODE(p," %s %s, %s\n", name,
orc_neon_reg_name_quad (dest), orc_neon_reg_name_quad (src1));
code |= (dest&0xf)<<12;
code |= ((dest>>4)&0x1)<<22;
code |= (src1&0xf)<<0;
code |= ((src1>>4)&0x1)<<5;
code |= 0x40;
orc_arm_emit (p, code);
}
static void
orc_neon_emit_mov (OrcCompiler *compiler, OrcVariable dest, OrcVariable src)
{
if (compiler->is_64bit) {
orc_neon64_emit_binary (compiler, "orr", 0x0ea01c00,
dest, src, src, compiler->insn_shift);
} else {
orc_neon_emit_binary (compiler, "vorr", 0xf2200110,
dest.alloc, src.alloc, src.alloc);
}
}
static void
orc_neon_emit_mov_quad (OrcCompiler *compiler, OrcVariable dest, OrcVariable src)
{
if (compiler->is_64bit) {
orc_neon64_emit_binary (compiler, "orr", 0x0ea01c00,
dest, src, src, compiler->insn_shift - 1);
} else {
orc_neon_emit_binary_quad (compiler, "vorr", 0xf2200110,
dest.alloc, src.alloc, src.alloc);
}
}
void
orc_neon_preload (OrcCompiler *compiler, OrcVariable *var, int write,
int offset)
{
orc_uint32 code;
/* Don't use multiprocessing extensions */
write = FALSE;
ORC_ASM_CODE(compiler," pld%s [%s, #%d]\n",
write ? "w" : "",
orc_arm_reg_name (var->ptr_register), offset);
code = 0xf510f000;
if (!write) code |= (1<<22);
code |= (var->ptr_register&0xf) << 16;
if (offset < 0) {
code |= ((-offset)&0xfff) << 0;
} else {
code |= (offset&0xfff) << 0;
code |= (1<<23);
}
orc_arm_emit (compiler, code);
}
#if 0
void
orc_neon_load_halfvec_aligned (OrcCompiler *compiler, OrcVariable *var, int update)
{
orc_uint32 code;
ORC_ASM_CODE(compiler," vld1.32 %s[0], [%s]%s\n",
orc_neon_reg_name (var->alloc),
orc_arm_reg_name (var->ptr_register),
update ? "!" : "");
code = 0xf4a0080d;
code |= (var->ptr_register&0xf) << 16;
code |= (var->alloc&0xf) << 12;
code |= ((var->alloc>>4)&0x1) << 22;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
}
void
orc_neon_load_vec_aligned (OrcCompiler *compiler, OrcVariable *var, int update)
{
orc_uint32 code;
ORC_ASM_CODE(compiler," vld1.64 %s, [%s]%s\n",
orc_neon_reg_name (var->alloc),
orc_arm_reg_name (var->ptr_register),
update ? "!" : "");
code = 0xf42007cd;
code |= (var->ptr_register&0xf) << 16;
code |= (var->alloc&0xf) << 12;
code |= ((var->alloc>>4)&0x1) << 22;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
}
void
orc_neon_load_vec_unaligned (OrcCompiler *compiler, OrcVariable *var,
int update)
{
orc_uint32 code;
ORC_ASM_CODE(compiler," vld1.8 %s, [%s]%s\n",
orc_neon_reg_name (var->alloc),
orc_arm_reg_name (var->ptr_register),
update ? "!" : "");
code = 0xf420070d;
code |= (var->ptr_register&0xf) << 16;
code |= ((var->alloc)&0xf) << 12;
code |= (((var->alloc)>>4)&0x1) << 22;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
#if 0
/* used with need_mask_regs */
ORC_ASM_CODE(compiler," vld1.64 %s, [%s]%s\n",
orc_neon_reg_name (var->aligned_data + 1),
orc_arm_reg_name (var->ptr_register),
update ? "!" : "");
code = 0xf42007cd;
code |= (var->ptr_register&0xf) << 16;
code |= ((var->aligned_data+1)&0xf) << 12;
code |= (((var->aligned_data+1)>>4)&0x1) << 22;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
ORC_ASM_CODE(compiler," vtbl.8 %s, {%s,%s}, %s\n",
orc_neon_reg_name (var->alloc),
orc_neon_reg_name (var->aligned_data),
orc_neon_reg_name (var->aligned_data+1),
orc_neon_reg_name (var->mask_alloc));
code = NEON_BINARY(0xf3b00900, var->alloc, var->aligned_data,
var->mask_alloc);
orc_arm_emit (compiler, code);
/* orc_neon_emit_mov (compiler, var->alloc, var->mask_alloc); */
orc_neon_emit_mov (compiler, var->aligned_data, var->aligned_data + 1);
#endif
}
void
orc_neon_load_halfvec_unaligned (OrcCompiler *compiler, OrcVariable *var,
int update)
{
orc_uint32 code;
ORC_ASM_CODE(compiler," vld1.8 %s, [%s]\n",
orc_neon_reg_name (var->alloc),
orc_arm_reg_name (var->ptr_register));
code = 0xf420070d;
code |= (var->ptr_register&0xf) << 16;
code |= ((var->alloc)&0xf) << 12;
code |= (((var->alloc)>>4)&0x1) << 22;
/* code |= (!update) << 1; */
code |= (1) << 1;
orc_arm_emit (compiler, code);
if (update) {
orc_arm_emit_add_imm (compiler, var->ptr_register,
var->ptr_register, 4);
}
#if 0
/* used with need_mask_regs */
ORC_ASM_CODE(compiler," vld1.32 %s[1], [%s]%s\n",
orc_neon_reg_name (var->aligned_data),
orc_arm_reg_name (var->ptr_register),
update ? "!" : "");
code = 0xf4a0088d;
code |= (var->ptr_register&0xf) << 16;
code |= ((var->aligned_data)&0xf) << 12;
code |= (((var->aligned_data)>>4)&0x1) << 22;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
ORC_ASM_CODE(compiler," vtbl.8 %s, {%s,%s}, %s\n",
orc_neon_reg_name (var->alloc),
orc_neon_reg_name (var->aligned_data),
orc_neon_reg_name (var->aligned_data + 1),
orc_neon_reg_name (var->mask_alloc));
code = NEON_BINARY(0xf3b00900, var->alloc, var->aligned_data, var->mask_alloc);
orc_arm_emit (compiler, code);
orc_neon_emit_unary (compiler, "vrev64.i32", 0xf3b80000,
var->aligned_data, var->aligned_data);
#endif
}
void
orc_neon_load_fourvec_aligned (OrcCompiler *compiler, OrcVariable *var, int update)
{
orc_uint32 code;
ORC_ASM_CODE(compiler," vld1.64 { %s, %s, %s, %s }, [%s,:256]%s\n",
orc_neon_reg_name (var->alloc),
orc_neon_reg_name (var->alloc + 1),
orc_neon_reg_name (var->alloc + 2),
orc_neon_reg_name (var->alloc + 3),
orc_arm_reg_name (var->ptr_register),
update ? "!" : "");
code = 0xf42002dd;
code |= (var->ptr_register&0xf) << 16;
code |= (var->alloc&0xf) << 12;
code |= ((var->alloc>>4)&0x1) << 22;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
}
void
orc_neon_load_fourvec_unaligned (OrcCompiler *compiler, OrcVariable *var,
int update)
{
orc_uint32 code;
ORC_ASM_CODE(compiler," vld1.8 { %s, %s, %s, %s }, [%s]%s\n",
orc_neon_reg_name (var->alloc),
orc_neon_reg_name (var->alloc + 1),
orc_neon_reg_name (var->alloc + 2),
orc_neon_reg_name (var->alloc + 3),
orc_arm_reg_name (var->ptr_register),
update ? "!" : "");
code = 0xf420020d;
code |= (var->ptr_register&0xf) << 16;
code |= ((var->alloc)&0xf) << 12;
code |= (((var->alloc)>>4)&0x1) << 22;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
}
void
orc_neon_load_twovec_aligned (OrcCompiler *compiler, OrcVariable *var, int update)
{
orc_uint32 code;
ORC_ASM_CODE(compiler," vld1.64 { %s, %s }, [%s,:128]%s\n",
orc_neon_reg_name (var->alloc),
orc_neon_reg_name (var->alloc + 1),
orc_arm_reg_name (var->ptr_register),
update ? "!" : "");
code = 0xf4200aed;
code |= (var->ptr_register&0xf) << 16;
code |= (var->alloc&0xf) << 12;
code |= ((var->alloc>>4)&0x1) << 22;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
}
void
orc_neon_load_twovec_unaligned (OrcCompiler *compiler, OrcVariable *var,
int update)
{
orc_uint32 code;
ORC_ASM_CODE(compiler," vld1.8 { %s, %s }, [%s]%s\n",
orc_neon_reg_name (var->alloc),
orc_neon_reg_name (var->alloc + 1),
orc_arm_reg_name (var->ptr_register),
update ? "!" : "");
code = 0xf4200a0d;
code |= (var->ptr_register&0xf) << 16;
code |= ((var->alloc)&0xf) << 12;
code |= (((var->alloc)>>4)&0x1) << 22;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
}
void
orc_neon_loadb (OrcCompiler *compiler, OrcVariable *var, int update)
{
orc_uint32 code;
int i;
if (var->is_aligned && compiler->insn_shift == 5) {
orc_neon_load_fourvec_aligned (compiler, var, update);
} else if (var->is_aligned && compiler->insn_shift == 4) {
orc_neon_load_twovec_aligned (compiler, var, update);
} else if (var->is_aligned && compiler->insn_shift == 3) {
orc_neon_load_vec_aligned (compiler, var, update);
} else if (var->is_aligned && compiler->insn_shift == 2) {
orc_neon_load_halfvec_aligned (compiler, var, update);
} else if (compiler->insn_shift == 5) {
orc_neon_load_fourvec_unaligned (compiler, var, update);
} else if (compiler->insn_shift == 4) {
orc_neon_load_twovec_unaligned (compiler, var, update);
} else if (compiler->insn_shift == 3) {
orc_neon_load_vec_unaligned (compiler, var, update);
} else if (compiler->insn_shift == 2) {
orc_neon_load_halfvec_unaligned (compiler, var, update);
} else {
if (compiler->insn_shift > 1) {
ORC_ERROR("slow load");
}
for(i=0;i<(1<<compiler->insn_shift);i++){
ORC_ASM_CODE(compiler," vld1.8 %s[%d], [%s]%s\n",
orc_neon_reg_name (var->alloc + (i>>3)), i&7,
orc_arm_reg_name (var->ptr_register),
update ? "!" : "");
code = NEON_BINARY(0xf4a0000d, var->alloc + (i>>3),
var->ptr_register, 0);
code |= (i&7) << 5;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
}
}
}
void
orc_neon_loadw (OrcCompiler *compiler, OrcVariable *var, int update)
{
if (var->is_aligned && compiler->insn_shift == 3) {
orc_neon_load_twovec_aligned (compiler, var, update);
} else if (var->is_aligned && compiler->insn_shift == 2) {
orc_neon_load_vec_aligned (compiler, var, update);
} else if (var->is_aligned && compiler->insn_shift == 1) {
orc_neon_load_halfvec_aligned (compiler, var, update);
} else if (compiler->insn_shift == 3) {
orc_neon_load_twovec_unaligned (compiler, var, update);
} else if (compiler->insn_shift == 2) {
orc_neon_load_vec_unaligned (compiler, var, update);
} else if (compiler->insn_shift == 1) {
orc_neon_load_halfvec_unaligned (compiler, var, update);
} else {
orc_uint32 code;
int i;
if (compiler->insn_shift == 2) {
orc_neon_load_vec_aligned (compiler, var, update);
return;
} else if (compiler->insn_shift == 1) {
orc_neon_load_halfvec_aligned (compiler, var, update);
return;
}
if (compiler->insn_shift > 1) {
ORC_ERROR("slow load");
}
for(i=0;i<(1<<compiler->insn_shift);i++){
ORC_ASM_CODE(compiler," vld1.16 %s[%d], [%s]%s\n",
orc_neon_reg_name (var->alloc + (i>>2)), i&3,
orc_arm_reg_name (var->ptr_register),
update ? "!" : "");
code = NEON_BINARY(0xf4a0040d, var->alloc + (i>>2),
var->ptr_register, 0);
code |= (i&3) << 6;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
}
}
}
void
orc_neon_loadl (OrcCompiler *compiler, OrcVariable *var, int update)
{
orc_uint32 code;
int i;
if (var->is_aligned && compiler->insn_shift == 2) {
orc_neon_load_twovec_aligned (compiler, var, update);
} else if (var->is_aligned && compiler->insn_shift == 1) {
orc_neon_load_vec_aligned (compiler, var, update);
} else if (compiler->insn_shift == 2) {
orc_neon_load_twovec_unaligned (compiler, var, update);
} else if (compiler->insn_shift == 1) {
orc_neon_load_vec_unaligned (compiler, var, update);
} else {
if (compiler->insn_shift > 0) {
/* ORC_ERROR("slow load"); */
}
for(i=0;i<(1<<compiler->insn_shift);i++){
ORC_ASM_CODE(compiler," vld1.32 %s[%d], [%s]%s\n",
orc_neon_reg_name (var->alloc + (i>>1)), i & 1,
orc_arm_reg_name (var->ptr_register),
update ? "!" : "");
code = NEON_BINARY(0xf4a0080d, var->alloc + (i>>1),
var->ptr_register, 0);
code |= (i&1)<<7;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
}
}
}
void
orc_neon_loadq (OrcCompiler *compiler, int dest, int src1, int update, int is_aligned)
{
orc_uint32 code;
ORC_ASM_CODE(compiler," vld1.64 %s, [%s]%s\n",
orc_neon_reg_name (dest),
orc_arm_reg_name (src1),
update ? "!" : "");
code = 0xf42007cd;
code |= (src1&0xf) << 16;
code |= (dest&0xf) << 12;
code |= ((dest>>4)&0x1) << 22;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
}
void
orc_neon_storeb (OrcCompiler *compiler, int dest, int update, int src1, int is_aligned)
{
orc_uint32 code;
int i;
if (is_aligned && compiler->insn_shift == 5) {
ORC_ASM_CODE(compiler," vst1.8 { %s, %s, %s, %s }, [%s,:256]%s\n",
orc_neon_reg_name (src1),
orc_neon_reg_name (src1+1),
orc_neon_reg_name (src1+2),
orc_neon_reg_name (src1+3),
orc_arm_reg_name (dest),
update ? "!" : "");
code = 0xf400023d;
code |= (dest&0xf) << 16;
code |= (src1&0xf) << 12;
code |= ((src1>>4)&0x1) << 22;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
} else if (compiler->insn_shift == 5) {
ORC_ASM_CODE(compiler," vst1.8 { %s, %s, %s, %s }, [%s]%s\n",
orc_neon_reg_name (src1),
orc_neon_reg_name (src1+1),
orc_neon_reg_name (src1+2),
orc_neon_reg_name (src1+3),
orc_arm_reg_name (dest),
update ? "!" : "");
code = 0xf400020d;
code |= (dest&0xf) << 16;
code |= (src1&0xf) << 12;
code |= ((src1>>4)&0x1) << 22;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
} else if (is_aligned && compiler->insn_shift == 4) {
ORC_ASM_CODE(compiler," vst1.8 { %s, %s }, [%s,:128]%s\n",
orc_neon_reg_name (src1),
orc_neon_reg_name (src1+1),
orc_arm_reg_name (dest),
update ? "!" : "");
code = 0xf4000a2d;
code |= (dest&0xf) << 16;
code |= (src1&0xf) << 12;
code |= ((src1>>4)&0x1) << 22;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
} else if (compiler->insn_shift == 4) {
ORC_ASM_CODE(compiler," vst1.8 { %s, %s }, [%s]%s\n",
orc_neon_reg_name (src1),
orc_neon_reg_name (src1+1),
orc_arm_reg_name (dest),
update ? "!" : "");
code = 0xf4000a0d;
code |= (dest&0xf) << 16;
code |= (src1&0xf) << 12;
code |= ((src1>>4)&0x1) << 22;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
} else if (is_aligned && compiler->insn_shift == 3) {
ORC_ASM_CODE(compiler," vst1.8 %s, [%s,:64]%s\n",
orc_neon_reg_name (src1),
orc_arm_reg_name (dest),
update ? "!" : "");
code = 0xf400071d;
code |= (dest&0xf) << 16;
code |= (src1&0xf) << 12;
code |= ((src1>>4)&0x1) << 22;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
} else {
for(i=0;i<(1<<compiler->insn_shift);i++){
ORC_ASM_CODE(compiler," vst1.8 %s[%d], [%s]%s\n",
orc_neon_reg_name (src1 + (i>>3)), i&7,
orc_arm_reg_name (dest),
update ? "!" : "");
code = 0xf480000d;
code |= (dest&0xf) << 16;
code |= ((src1 + (i>>3))&0xf) << 12;
code |= ((src1>>4)&0x1) << 22;
code |= (i&7)<<5;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
}
}
}
void
orc_neon_storew (OrcCompiler *compiler, int dest, int update, int src1, int is_aligned)
{
orc_uint32 code;
int i;
if (is_aligned && compiler->insn_shift == 3) {
ORC_ASM_CODE(compiler," vst1.16 { %s, %s }, [%s,:128]%s\n",
orc_neon_reg_name (src1),
orc_neon_reg_name (src1 + 1),
orc_arm_reg_name (dest),
update ? "!" : "");
code = 0xf4000a6d;
code |= (dest&0xf) << 16;
code |= (src1&0xf) << 12;
code |= ((src1>>4)&0x1) << 22;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
} else if (is_aligned && compiler->insn_shift == 2) {
ORC_ASM_CODE(compiler," vst1.16 %s, [%s,:64]%s\n",
orc_neon_reg_name (src1),
orc_arm_reg_name (dest),
update ? "!" : "");
code = 0xf400075d;
code |= (dest&0xf) << 16;
code |= (src1&0xf) << 12;
code |= ((src1>>4)&0x1) << 22;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
} else {
for(i=0;i<(1<<compiler->insn_shift);i++){
ORC_ASM_CODE(compiler," vst1.16 %s[%d], [%s]%s\n",
orc_neon_reg_name (src1 + (i>>2)), i&3,
orc_arm_reg_name (dest),
update ? "!" : "");
code = 0xf480040d;
code |= (dest&0xf) << 16;
code |= ((src1 + (i>>2))&0xf) << 12;
code |= ((src1>>4)&0x1) << 22;
code |= (i&3)<<6;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
}
}
}
void
orc_neon_storel (OrcCompiler *compiler, int dest, int update, int src1, int is_aligned)
{
orc_uint32 code;
int i;
if (is_aligned && compiler->insn_shift == 2) {
ORC_ASM_CODE(compiler," vst1.32 { %s, %s }, [%s,:128]%s\n",
orc_neon_reg_name (src1),
orc_neon_reg_name (src1 + 1),
orc_arm_reg_name (dest),
update ? "!" : "");
code = 0xf4000aad;
code |= (dest&0xf) << 16;
code |= (src1&0xf) << 12;
code |= ((src1>>4)&0x1) << 22;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
} else if (is_aligned && compiler->insn_shift == 1) {
ORC_ASM_CODE(compiler," vst1.32 %s, [%s,:64]%s\n",
orc_neon_reg_name (src1),
orc_arm_reg_name (dest),
update ? "!" : "");
code = 0xf400079d;
code |= (dest&0xf) << 16;
code |= (src1&0xf) << 12;
code |= ((src1>>4)&0x1) << 22;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
} else {
for(i=0;i<(1<<compiler->insn_shift);i++){
ORC_ASM_CODE(compiler," vst1.32 %s[%d], [%s]%s\n",
orc_neon_reg_name (src1 + (i>>1)), i&1,
orc_arm_reg_name (dest),
update ? "!" : "");
code = 0xf480080d;
code |= (dest&0xf) << 16;
code |= ((src1 + (i>>1))&0xf) << 12;
code |= ((src1>>4)&0x1) << 22;
code |= (i&1)<<7;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
}
}
}
void
orc_neon_storeq (OrcCompiler *compiler, int dest, int update, int src1, int is_aligned)
{
orc_uint32 code;
ORC_ASM_CODE(compiler," vst1.64 %s, [%s]%s\n",
orc_neon_reg_name (src1),
orc_arm_reg_name (dest),
update ? "!" : "");
code = 0xf40007cd;
code |= (dest&0xf) << 16;
code |= (src1&0xf) << 12;
code |= ((src1>>4)&0x1) << 22;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
}
#endif
static void
neon_rule_loadupdb (OrcCompiler *compiler, void *user, OrcInstruction *insn)
{
OrcVariable *src = compiler->vars + insn->src_args[0];
OrcVariable *dest = compiler->vars + insn->dest_args[0];
unsigned int code = 0;
int size = src->size << compiler->insn_shift;
ORC_ASSERT(src->ptr_register); /* can ptr_register be 0 ? */
int ptr_reg;
/* FIXME this should be fixed at a higher level */
if (src->vartype != ORC_VAR_TYPE_SRC && src->vartype != ORC_VAR_TYPE_DEST) {
ORC_COMPILER_ERROR(compiler, "loadX used with non src/dest");
return;
}
if (compiler->is_64bit) {
if (src->ptr_offset) {
ptr_reg = compiler->gp_tmpreg;
orc_arm64_emit_add_lsr(compiler, 64, ptr_reg, src->ptr_register, src->ptr_offset, 1);
} else {
ptr_reg = src->ptr_register;
}
int opcode, flag;
if (size > 16) {
/** load multiple single-element structures to one, two, three, or four registers */
char vt_str[64];
memset(vt_str, '\x00', 64);
if (size == 64) {
snprintf(vt_str, 64, "%s, %s, %s, %s",
orc_neon64_reg_name_vector (compiler->tmpreg, 1, 1),
orc_neon64_reg_name_vector (compiler->tmpreg + 1, 1, 1),
orc_neon64_reg_name_vector (compiler->tmpreg + 2, 1, 1),
orc_neon64_reg_name_vector (compiler->tmpreg + 3, 1, 1));
opcode = 0x2;
} else if (size == 32) {
snprintf(vt_str, 64, "%s, %s",
orc_neon64_reg_name_vector (compiler->tmpreg, 1, 1),
orc_neon64_reg_name_vector (compiler->tmpreg + 1, 1, 1));
opcode = 0xa;
} else if (size == 16) {
snprintf(vt_str, 64, "%s",
orc_neon64_reg_name_vector (compiler->tmpreg, 1, 1));
opcode = 0x7;
} else {
ORC_COMPILER_ERROR(compiler,"bad aligned load size %d",
src->size << compiler->insn_shift);
return;
}
flag = 0; /* Bytes */
ORC_ASM_CODE(compiler," ld1 { %s }, [%s]\n",
vt_str, orc_arm64_reg_name (ptr_reg, 64));
code = 0x0c400000;
code |= 0 << 30; /* Q-bit */
code |= (flag&0x3) << 10;
code |= (opcode&0xf) << 12;
} else {
/** load one single-element structure to one lane of one register */
flag = 0;
if (size == 8) {
opcode = 4;
flag = 1; /* size==01 */
} else if (size == 4) {
opcode = 4;
} else if (size == 2) {
opcode = 2;
} else if (size == 1) {
opcode = 0;
} else {
ORC_COMPILER_ERROR(compiler,"bad unaligned load size %d",
src->size << compiler->insn_shift);
return;
}
ORC_ASM_CODE(compiler," ld1 { %s }[0], [%s]\n",
orc_neon64_reg_name_vector_single (compiler->tmpreg, size),
orc_arm64_reg_name (ptr_reg, 64));
code = 0x0d400000;
code |= (opcode&0x7) << 13;
code |= (flag&0x3) << 10;
}
code |= (ptr_reg&0x1f) << 5;
code |= (compiler->tmpreg&0x1f);
orc_arm_emit (compiler, code);
OrcVariable tmpreg = { .alloc = compiler->tmpreg, .size = compiler->vars[insn->src_args[0]].size };
switch (src->size) {
case 1:
orc_neon64_emit_binary (compiler, "zip1", 0x0e003800,
compiler->vars[insn->dest_args[0]],
tmpreg,
tmpreg, compiler->insn_shift - 1);
break;
case 2:
orc_neon64_emit_binary (compiler, "zip1", 0x0e403800,
compiler->vars[insn->dest_args[0]],
tmpreg,
tmpreg, compiler->insn_shift - 1);
break;
case 4:
orc_neon64_emit_binary (compiler, "zip1", 0x0e803800,
compiler->vars[insn->dest_args[0]],
tmpreg,
tmpreg, compiler->insn_shift - 1);
break;
}
} else {
if (src->ptr_offset) {
ptr_reg = compiler->gp_tmpreg;
orc_arm_emit_add_rsi(compiler, ORC_ARM_COND_AL, 0,
ptr_reg, src->ptr_register,
src->ptr_offset, ORC_ARM_LSR, 1);
} else {
ptr_reg = src->ptr_register;
}
if (size > 8) {
if (src->is_aligned) {
if (size == 32) {
ORC_ASM_CODE(compiler," vld1.64 { %s, %s, %s, %s }, [%s,:256]\n",
orc_neon_reg_name (dest->alloc),
orc_neon_reg_name (dest->alloc + 1),
orc_neon_reg_name (dest->alloc + 2),
orc_neon_reg_name (dest->alloc + 3),
orc_arm_reg_name (ptr_reg));
code = 0xf42002dd;
} else if (size == 16) {
ORC_ASM_CODE(compiler," vld1.64 { %s, %s }, [%s,:128]\n",
orc_neon_reg_name (dest->alloc),
orc_neon_reg_name (dest->alloc + 1),
orc_arm_reg_name (ptr_reg));
code = 0xf4200aed;
} else if (size == 8) {
ORC_ASM_CODE(compiler," vld1.64 %s, [%s]\n",
orc_neon_reg_name (dest->alloc),
orc_arm_reg_name (ptr_reg));
code = 0xf42007cd;
} else {
ORC_COMPILER_ERROR(compiler,"bad aligned load size %d",
src->size << compiler->insn_shift);
}
} else {
if (size == 32) {
ORC_ASM_CODE(compiler," vld1.8 { %s, %s, %s, %s }, [%s]\n",
orc_neon_reg_name (dest->alloc),
orc_neon_reg_name (dest->alloc + 1),
orc_neon_reg_name (dest->alloc + 2),
orc_neon_reg_name (dest->alloc + 3),
orc_arm_reg_name (ptr_reg));
code = 0xf420020d;
} else if (size == 16) {
ORC_ASM_CODE(compiler," vld1.8 { %s, %s }, [%s]\n",
orc_neon_reg_name (dest->alloc),
orc_neon_reg_name (dest->alloc + 1),
orc_arm_reg_name (ptr_reg));
code = 0xf4200a0d;
} else if (size == 8) {
ORC_ASM_CODE(compiler," vld1.8 %s, [%s]\n",
orc_neon_reg_name (dest->alloc),
orc_arm_reg_name (ptr_reg));
code = 0xf420070d;
} else {
ORC_COMPILER_ERROR(compiler,"bad unaligned load size %d",
src->size << compiler->insn_shift);
}
}
} else {
int shift;
if (size == 4) {
shift = 2;
} else if (size == 2) {
shift = 1;
} else {
shift = 0;
}
ORC_ASM_CODE(compiler," vld1.%d %s[0], [%s]\n",
8<<shift,
orc_neon_reg_name (dest->alloc),
orc_arm_reg_name (ptr_reg));
code = 0xf4a0000d;
code |= shift<<10;
code |= (0&7)<<5;
}
code |= (ptr_reg&0xf) << 16;
code |= (dest->alloc&0xf) << 12;
code |= ((dest->alloc>>4)&0x1) << 22;
code |= 1 << 1;
orc_arm_emit (compiler, code);
switch (src->size) {
case 1:
orc_neon_emit_binary (compiler, "vorr", 0xf2200110,
compiler->vars[insn->dest_args[0]].alloc + 1,
compiler->vars[insn->dest_args[0]].alloc,
compiler->vars[insn->dest_args[0]].alloc);
orc_neon_emit_unary (compiler, "vzip.8", 0xf3b20180,
compiler->vars[insn->dest_args[0]].alloc,
compiler->vars[insn->dest_args[0]].alloc + 1);
break;
case 2:
orc_neon_emit_binary (compiler, "vorr", 0xf2200110,
compiler->vars[insn->dest_args[0]].alloc + 1,
compiler->vars[insn->dest_args[0]].alloc,
compiler->vars[insn->dest_args[0]].alloc);
orc_neon_emit_unary (compiler, "vzip.16", 0xf3b60180,
compiler->vars[insn->dest_args[0]].alloc,
compiler->vars[insn->dest_args[0]].alloc + 1);
break;
case 4:
orc_neon_emit_binary (compiler, "vorr", 0xf2200110,
compiler->vars[insn->dest_args[0]].alloc + 1,
compiler->vars[insn->dest_args[0]].alloc,
compiler->vars[insn->dest_args[0]].alloc);
orc_neon_emit_unary_quad (compiler, "vzip.32", 0xf3ba0180,
compiler->vars[insn->dest_args[0]].alloc,
compiler->vars[insn->dest_args[0]].alloc + 1);
break;
}
}
src->update_type = 1;
}
static void
neon_rule_loadpX (OrcCompiler *compiler, void *user, OrcInstruction *insn)
{
OrcVariable *src = compiler->vars + insn->src_args[0];
OrcVariable *dest = compiler->vars + insn->dest_args[0];
int size = ORC_PTR_TO_INT (user);
if (src->vartype == ORC_VAR_TYPE_CONST) {
if (size == 1) {
orc_neon_emit_loadib (compiler, dest, src->value.i);
} else if (size == 2) {
orc_neon_emit_loadiw (compiler, dest, src->value.i);
} else if (size == 4) {
orc_neon_emit_loadil (compiler, dest, src->value.i);
} else if (size == 8) {
if (src->size == 8 && !compiler->is_64bit) {
ORC_COMPILER_ERROR(compiler,"64-bit constants not implemented");
}
orc_neon_emit_loadiq (compiler, dest, src->value.i);
} else {
ORC_PROGRAM_ERROR(compiler,"unimplemented");
}
} else {
if (size == 1) {
orc_neon_emit_loadpb (compiler, dest->alloc, insn->src_args[0]);
} else if (size == 2) {
orc_neon_emit_loadpw (compiler, dest->alloc, insn->src_args[0]);
} else if (size == 4) {
orc_neon_emit_loadpl (compiler, dest->alloc, insn->src_args[0]);
} else if (size == 8) {
orc_neon_emit_loadpq (compiler, dest->alloc, insn->src_args[0]);
} else {
ORC_PROGRAM_ERROR(compiler,"unimplemented");
}
}
}
static void
neon_rule_loadX (OrcCompiler *compiler, void *user, OrcInstruction *insn)
{
OrcVariable *src = compiler->vars + insn->src_args[0];
OrcVariable *dest = compiler->vars + insn->dest_args[0];
int update = FALSE;
unsigned int code = 0;
int size = src->size << compiler->insn_shift;
int type = ORC_PTR_TO_INT(user);
int ptr_register;
int is_aligned = src->is_aligned;
/* FIXME this should be fixed at a higher level */
if (src->vartype != ORC_VAR_TYPE_SRC && src->vartype != ORC_VAR_TYPE_DEST) {
ORC_COMPILER_ERROR(compiler, "loadX used with non src/dest");
return;
}
if (src->vartype == ORC_VAR_TYPE_DEST) update = FALSE;
if (type == 1) {
if (compiler->vars[insn->src_args[1]].vartype != ORC_VAR_TYPE_CONST) {
ORC_PROGRAM_ERROR(compiler,"unimplemented");
return;
}
ptr_register = compiler->gp_tmpreg;
if (compiler->is_64bit) {
orc_arm64_emit_add_imm (compiler, 64, ptr_register,
src->ptr_register,
compiler->vars[insn->src_args[1]].value.i * src->size);
} else {
orc_arm_emit_add_imm (compiler, ptr_register,
src->ptr_register,
compiler->vars[insn->src_args[1]].value.i * src->size);
}
update = FALSE;
is_aligned = FALSE;
} else {
ptr_register = src->ptr_register;
}
if (compiler->is_64bit) {
int opcode, flag;
if (size >= 16) {
/** load multiple single-element structures to one, two, three, or four registers */
char vt_str[64];
memset(vt_str, '\x00', 64);
if (is_aligned) {
if (size == 64) {
snprintf(vt_str, 64, "%s, %s, %s, %s",
orc_neon64_reg_name_vector (dest->alloc, 8, 1),
orc_neon64_reg_name_vector (dest->alloc + 1, 8, 1),
orc_neon64_reg_name_vector (dest->alloc + 2, 8, 1),
orc_neon64_reg_name_vector (dest->alloc + 3, 8, 1));
opcode = 2;
} else if (size == 32) {
snprintf(vt_str, 64, "%s, %s",
orc_neon64_reg_name_vector (dest->alloc, 8, 1),
orc_neon64_reg_name_vector (dest->alloc + 1, 8, 1));
opcode = 10;
} else if (size == 16) {
snprintf(vt_str, 64, "%s",
orc_neon64_reg_name_vector (dest->alloc, 8, 1));
opcode = 7;
} else {
ORC_COMPILER_ERROR(compiler,"bad aligned load size %d",
src->size << compiler->insn_shift);
return;
}
flag = 7;
} else {
if (size == 64) {
snprintf(vt_str, 64, "%s, %s, %s, %s",
orc_neon64_reg_name_vector (dest->alloc, 1, 1),
orc_neon64_reg_name_vector (dest->alloc + 1, 1, 1),
orc_neon64_reg_name_vector (dest->alloc + 2, 1, 1),
orc_neon64_reg_name_vector (dest->alloc + 3, 1, 1));
opcode = 2;
} else if (size == 32) {
snprintf(vt_str, 64, "%s, %s",
orc_neon64_reg_name_vector (dest->alloc, 1, 1),
orc_neon64_reg_name_vector (dest->alloc + 1, 1, 1));
opcode = 10;
} else if (size == 16) {
snprintf(vt_str, 64, "%s",
orc_neon64_reg_name_vector (dest->alloc, 1, 1));
opcode = 7;
} else {
ORC_COMPILER_ERROR(compiler,"bad aligned load size %d",
src->size << compiler->insn_shift);
return;
}
flag = 1;
}
ORC_ASM_CODE(compiler," ld1 { %s }, [%s]\n",
vt_str, orc_arm64_reg_name (ptr_register, 64));
code = 0x0c400000;
code |= (flag&0x1) << 30;
code |= (flag&0x3) << 10;
code |= (opcode&0xf) << 12;
} else {
/** load one single-element structure to one lane of one register */
flag = 0;
if (size == 8) {
opcode = 4;
flag = 1;
} else if (size == 4) {
opcode = 4;
} else if (size == 2) {
opcode = 2;
} else if (size == 1) {
opcode = 0;
} else {
ORC_COMPILER_ERROR(compiler,"bad unaligned load size %d",
src->size << compiler->insn_shift);
return;
}
ORC_ASM_CODE(compiler," ld1 { %s }[0], [%s]\n",
orc_neon64_reg_name_vector_single (dest->alloc, size),
orc_arm64_reg_name (ptr_register, 64));
code = 0x0d400000;
code |= (opcode&0x7) << 13;
code |= (flag&0x3) << 10;
}
code |= (ptr_register&0x1f) << 5;
code |= (dest->alloc&0x1f);
orc_arm_emit (compiler, code);
} else {
if (size >= 8) {
if (is_aligned) {
if (size == 32) {
ORC_ASM_CODE(compiler," vld1.64 { %s, %s, %s, %s }, [%s,:256]%s\n",
orc_neon_reg_name (dest->alloc),
orc_neon_reg_name (dest->alloc + 1),
orc_neon_reg_name (dest->alloc + 2),
orc_neon_reg_name (dest->alloc + 3),
orc_arm_reg_name (ptr_register),
update ? "!" : "");
code = 0xf42002dd;
} else if (size == 16) {
ORC_ASM_CODE(compiler," vld1.64 { %s, %s }, [%s,:128]%s\n",
orc_neon_reg_name (dest->alloc),
orc_neon_reg_name (dest->alloc + 1),
orc_arm_reg_name (ptr_register),
update ? "!" : "");
code = 0xf4200aed;
} else if (size == 8) {
ORC_ASM_CODE(compiler," vld1.64 %s, [%s]%s\n",
orc_neon_reg_name (dest->alloc),
orc_arm_reg_name (ptr_register),
update ? "!" : "");
code = 0xf42007cd;
} else {
ORC_COMPILER_ERROR(compiler,"bad aligned load size %d",
src->size << compiler->insn_shift);
}
} else {
if (size == 32) {
ORC_ASM_CODE(compiler," vld1.8 { %s, %s, %s, %s }, [%s]%s\n",
orc_neon_reg_name (dest->alloc),
orc_neon_reg_name (dest->alloc + 1),
orc_neon_reg_name (dest->alloc + 2),
orc_neon_reg_name (dest->alloc + 3),
orc_arm_reg_name (ptr_register),
update ? "!" : "");
code = 0xf420020d;
} else if (size == 16) {
ORC_ASM_CODE(compiler," vld1.8 { %s, %s }, [%s]%s\n",
orc_neon_reg_name (dest->alloc),
orc_neon_reg_name (dest->alloc + 1),
orc_arm_reg_name (ptr_register),
update ? "!" : "");
code = 0xf4200a0d;
} else if (size == 8) {
ORC_ASM_CODE(compiler," vld1.8 %s, [%s]%s\n",
orc_neon_reg_name (dest->alloc),
orc_arm_reg_name (ptr_register),
update ? "!" : "");
code = 0xf420070d;
} else {
ORC_COMPILER_ERROR(compiler,"bad unaligned load size %d",
src->size << compiler->insn_shift);
}
}
} else {
int shift;
if (size == 4) {
shift = 2;
} else if (size == 2) {
shift = 1;
} else {
shift = 0;
}
ORC_ASM_CODE(compiler," vld1.%d %s[0], [%s]%s\n",
8<<shift,
orc_neon_reg_name (dest->alloc),
orc_arm_reg_name (ptr_register),
update ? "!" : "");
code = 0xf4a0000d;
code |= shift<<10;
code |= (0&7)<<5;
}
code |= (ptr_register&0xf) << 16;
code |= (dest->alloc&0xf) << 12;
code |= ((dest->alloc>>4)&0x1) << 22;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
}
}
static void
neon_rule_storeX (OrcCompiler *compiler, void *user, OrcInstruction *insn)
{
OrcVariable *src = compiler->vars + insn->src_args[0];
OrcVariable *dest = compiler->vars + insn->dest_args[0];
int update = FALSE;
unsigned int code = 0;
int size = dest->size << compiler->insn_shift;
if (compiler->is_64bit) {
int opcode, flag;
if (size >= 16) {
/** store multiple single-element structures to one, two, three, or four registers */
char vt_str[64];
memset(vt_str, '\x00', 64);
if (dest->is_aligned) {
if (size == 64) {
snprintf(vt_str, 64, "%s, %s, %s, %s",
orc_neon64_reg_name_vector (src->alloc, 8, 1),
orc_neon64_reg_name_vector (src->alloc + 1, 8, 1),
orc_neon64_reg_name_vector (src->alloc + 2, 8, 1),
orc_neon64_reg_name_vector (src->alloc + 3, 8, 1));
opcode = 0x2;
} else if (size == 32) {
snprintf(vt_str, 64, "%s, %s",
orc_neon64_reg_name_vector (src->alloc, 8, 1),
orc_neon64_reg_name_vector (src->alloc + 1, 8, 1));
opcode = 0xa;
} else if (size == 16) {
snprintf(vt_str, 64, "%s",
orc_neon64_reg_name_vector (src->alloc, 8, 1));
opcode = 0x7;
} else {
ORC_COMPILER_ERROR(compiler,"bad aligned load size %d",
src->size << compiler->insn_shift);
return;
}
} else {
if (size == 64) {
snprintf(vt_str, 64, "%s, %s, %s, %s",
orc_neon64_reg_name_vector (src->alloc, 1, 1),
orc_neon64_reg_name_vector (src->alloc + 1, 1, 1),
orc_neon64_reg_name_vector (src->alloc + 2, 1, 1),
orc_neon64_reg_name_vector (src->alloc + 3, 1, 1));
opcode = 0x2;
} else if (size == 32) {
snprintf(vt_str, 64, "%s, %s",
orc_neon64_reg_name_vector (src->alloc, 1, 1),
orc_neon64_reg_name_vector (src->alloc + 1, 1, 1));
opcode = 0xa;
} else if (size == 16) {
snprintf(vt_str, 64, "%s",
orc_neon64_reg_name_vector (src->alloc, 1, 1));
opcode = 0x7;
} else {
ORC_COMPILER_ERROR(compiler,"bad aligned load size %d",
src->size << compiler->insn_shift);
return;
}
}
ORC_ASM_CODE(compiler," st1 { %s }, [%s]\n",
vt_str, orc_arm64_reg_name (dest->ptr_register, 64));
code = 0x0c000000;
code |= 1 << 30;
code |= (opcode&0xf) << 12;
} else {
/** store one single-element structure to one lane of one register */
flag = 0;
if (size == 8) {
opcode = 4;
flag = 1;
} else if (size == 4) {
opcode = 4;
} else if (size == 2) {
opcode = 2;
} else if (size == 1) {
opcode = 0;
} else {
ORC_COMPILER_ERROR(compiler,"bad unaligned load size %d",
src->size << compiler->insn_shift);
return;
}
ORC_ASM_CODE(compiler," st1 { %s }[0], [%s]\n",
orc_neon64_reg_name_vector_single (src->alloc, size),
orc_arm64_reg_name (dest->ptr_register, 64));
code = 0x0d000000;
code |= (opcode&0x7) << 13;
code |= (flag&0x3) << 10;
}
code |= (dest->ptr_register&0x1f) << 5;
code |= (src->alloc&0x1f);
orc_arm_emit (compiler, code);
} else {
if (size >= 8) {
if (dest->is_aligned) {
if (size == 32) {
ORC_ASM_CODE(compiler," vst1.64 { %s, %s, %s, %s }, [%s,:256]%s\n",
orc_neon_reg_name (src->alloc),
orc_neon_reg_name (src->alloc + 1),
orc_neon_reg_name (src->alloc + 2),
orc_neon_reg_name (src->alloc + 3),
orc_arm_reg_name (dest->ptr_register),
update ? "!" : "");
code = 0xf40002dd;
} else if (size == 16) {
ORC_ASM_CODE(compiler," vst1.64 { %s, %s }, [%s,:128]%s\n",
orc_neon_reg_name (src->alloc),
orc_neon_reg_name (src->alloc + 1),
orc_arm_reg_name (dest->ptr_register),
update ? "!" : "");
code = 0xf4000aed;
} else if (size == 8) {
ORC_ASM_CODE(compiler," vst1.64 %s, [%s]%s\n",
orc_neon_reg_name (src->alloc),
orc_arm_reg_name (dest->ptr_register),
update ? "!" : "");
code = 0xf40007cd;
} else {
ORC_COMPILER_ERROR(compiler,"bad aligned store size %d", size);
}
} else {
if (size == 32) {
ORC_ASM_CODE(compiler," vst1.8 { %s, %s, %s, %s }, [%s]%s\n",
orc_neon_reg_name (src->alloc),
orc_neon_reg_name (src->alloc + 1),
orc_neon_reg_name (src->alloc + 2),
orc_neon_reg_name (src->alloc + 3),
orc_arm_reg_name (dest->ptr_register),
update ? "!" : "");
code = 0xf400020d;
} else if (size == 16) {
ORC_ASM_CODE(compiler," vst1.8 { %s, %s }, [%s]%s\n",
orc_neon_reg_name (src->alloc),
orc_neon_reg_name (src->alloc + 1),
orc_arm_reg_name (dest->ptr_register),
update ? "!" : "");
code = 0xf4000a0d;
} else if (size == 8) {
ORC_ASM_CODE(compiler," vst1.8 %s, [%s]%s\n",
orc_neon_reg_name (src->alloc),
orc_arm_reg_name (dest->ptr_register),
update ? "!" : "");
code = 0xf400070d;
} else {
ORC_COMPILER_ERROR(compiler,"bad aligned store size %d", size);
}
}
} else {
int shift;
if (size == 4) {
shift = 2;
} else if (size == 2) {
shift = 1;
} else {
shift = 0;
}
ORC_ASM_CODE(compiler," vst1.%d %s[0], [%s]%s\n",
8<<shift,
orc_neon_reg_name (src->alloc),
orc_arm_reg_name (dest->ptr_register),
update ? "!" : "");
code = 0xf480000d;
code |= shift<<10;
code |= (0&7)<<5;
}
code |= (dest->ptr_register&0xf) << 16;
code |= (src->alloc&0xf) << 12;
code |= ((src->alloc>>4)&0x1) << 22;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
}
}
#if 0
static int
orc_neon_get_const_shift (unsigned int value)
{
int shift = 0;
while((value & 0xff) != value) {
shift++;
value >>= 1;
}
return shift;
}
#endif
void
orc_neon_emit_loadib (OrcCompiler *compiler, OrcVariable *dest, int value)
{
int reg = dest->alloc;
orc_uint32 code;
if (compiler->is_64bit) {
if (value == 0) {
orc_neon64_emit_binary (compiler, "eor", 0x2e201c00,
*dest, *dest, *dest, compiler->insn_shift - 1);
return;
}
value &= 0xff;
ORC_ASM_CODE(compiler," movi %s, #%d\n",
orc_neon64_reg_name_vector (reg, 16, 0), value);
code = 0x0f00e400; /* 8-bit (op==0 && cmode==1110) */
code |= (reg&0x1f) << 0;
code |= (value&0x1f) << 5;
code |= (value&0xe0) << 11;
code |= 1 << 30;
orc_arm_emit (compiler, code);
} else {
if (value == 0) {
orc_neon_emit_binary_quad (compiler, "veor", 0xf3000110, reg, reg, reg);
return;
}
value &= 0xff;
ORC_ASM_CODE(compiler," vmov.i8 %s, #%d\n",
orc_neon_reg_name_quad (reg), value);
code = 0xf2800e10;
code |= (reg&0xf) << 12;
code |= ((reg>>4)&0x1) << 22;
code |= (value&0xf) << 0;
code |= (value&0x70) << 12;
code |= (value&0x80) << 17;
code |= 0x40;
orc_arm_emit (compiler, code);
}
}
void
orc_neon_emit_loadiw (OrcCompiler *compiler, OrcVariable *dest, int value)
{
int reg = dest->alloc;
orc_uint32 code;
if (compiler->is_64bit) {
if (value == 0) {
orc_neon64_emit_binary (compiler, "eor", 0x2e201c00,
*dest, *dest, *dest, compiler->insn_shift - 1);
return;
}
ORC_ASM_CODE(compiler," movi %s, #0x%02x\n",
orc_neon64_reg_name_vector (reg, 16, 0), value & 0xff);
code = 0x0f008400; /* 16-bit (op==0 && cmode==10x0), x=0 is LSL #0 */
code |= (reg&0x1f) << 0;
code |= (value&0x1f) << 5;
code |= (value&0xe0) << 11;
code |= 1 << 30;
orc_arm_emit (compiler, code);
value >>= 8;
if (value) {
ORC_ASM_CODE(compiler," orr %s, #0x%02x, lsl #8\n",
orc_neon64_reg_name_vector (reg, 16, 0), value & 0xff);
code = 0x0f00b400; /* 16-bit (cmode==10x1), x=1 is LSL #8 */
code |= (reg&0x1f) << 0;
code |= (value&0x1f) << 5;
code |= (value&0xe0) << 11;
code |= 1 << 30;
orc_arm_emit (compiler, code);
}
} else {
if (value == 0) {
orc_neon_emit_binary_quad (compiler, "veor", 0xf3000110, reg, reg, reg);
return;
}
ORC_ASM_CODE(compiler," vmov.i16 %s, #0x%04x\n",
orc_neon_reg_name_quad (reg), value & 0xff);
code = 0xf2800810;
code |= (reg&0xf) << 12;
code |= ((reg>>4)&0x1) << 22;
code |= (value&0xf) << 0;
code |= (value&0x70) << 12;
code |= (value&0x80) << 17;
code |= 0x40;
orc_arm_emit (compiler, code);
value >>= 8;
if (value) {
ORC_ASM_CODE(compiler," vorr.i16 %s, #0x%04x\n",
orc_neon_reg_name_quad (reg), (value & 0xff) << 8);
code = 0xf2800b10;
code |= (reg&0xf) << 12;
code |= ((reg>>4)&0x1) << 22;
code |= (value&0xf) << 0;
code |= (value&0x70) << 12;
code |= (value&0x80) << 17;
code |= 0x40;
orc_arm_emit (compiler, code);
}
}
}
void
orc_neon_emit_loadil (OrcCompiler *compiler, OrcVariable *dest, int value)
{
int reg = dest->alloc;
orc_uint32 code;
if (compiler->is_64bit) {
if (value == 0) {
orc_neon64_emit_binary (compiler, "eor", 0x2e201c00,
*dest, *dest, *dest, compiler->insn_shift - 1);
return;
}
ORC_ASM_CODE(compiler," movi %s, #0x%02x\n",
orc_neon64_reg_name_vector (reg, 16, 0), value & 0xff);
code = 0x0f000400; /* 32-bit (op==0 && cmode==0xx0), xx=0 is LSL #0 */
code |= (reg&0x1f) << 0;
code |= (value&0x1f) << 5;
code |= (value&0xe0) << 11;
code |= 1 << 30;
orc_arm_emit (compiler, code);
value >>= 8;
if (value) {
ORC_ASM_CODE(compiler," orr %s, #0x%02x, lsl #8\n",
orc_neon64_reg_name_vector (reg, 16, 0), value & 0xff);
code = 0x0f003400; /* 32-bit (cmode==0xx1), xx=01 is LSL #8 */
code |= (reg&0x1f) << 0;
code |= (value&0x1f) << 5;
code |= (value&0xe0) << 11;
code |= 1 << 30;
orc_arm_emit (compiler, code);
}
value >>= 8;
if (value) {
ORC_ASM_CODE(compiler," orr %s, #0x%02x, lsl #16\n",
orc_neon64_reg_name_vector (reg, 16, 0), value & 0xff);
code = 0x0f005400; /* 32-bit (cmode==0xx1), xx=10 is LSL #16 */
code |= (reg&0x1f) << 0;
code |= (value&0x1f) << 5;
code |= (value&0xe0) << 11;
code |= 1 << 30;
orc_arm_emit (compiler, code);
}
value >>= 8;
if (value) {
ORC_ASM_CODE(compiler," orr %s, #0x%02x, lsl #8\n",
orc_neon64_reg_name_vector (reg, 16, 0), value & 0xff);
code = 0x0f007400; /* 32-bit (cmode==0xx1), xx=11 is LSL #24 */
code |= (reg&0x1f) << 0;
code |= (value&0x1f) << 5;
code |= (value&0xe0) << 11;
code |= 1 << 30;
orc_arm_emit (compiler, code);
}
} else {
if (value == 0) {
orc_neon_emit_binary_quad (compiler, "veor", 0xf3000110, reg, reg, reg);
return;
}
ORC_ASM_CODE(compiler," vmov.i32 %s, #0x%08x\n",
orc_neon_reg_name_quad (reg), value & 0xff);
code = 0xf2800010;
code |= (reg&0xf) << 12;
code |= ((reg>>4)&0x1) << 22;
code |= (value&0xf) << 0;
code |= (value&0x70) << 12;
code |= (value&0x80) << 17;
code |= 0x40;
orc_arm_emit (compiler, code);
value >>= 8;
if (value & 0xff) {
ORC_ASM_CODE(compiler," vorr.i32 %s, #0x%08x\n",
orc_neon_reg_name_quad (reg), (value & 0xff) << 8);
code = 0xf2800310;
code |= (reg&0xf) << 12;
code |= ((reg>>4)&0x1) << 22;
code |= (value&0xf) << 0;
code |= (value&0x70) << 12;
code |= (value&0x80) << 17;
code |= 0x40;
orc_arm_emit (compiler, code);
}
value >>= 8;
if (value & 0xff) {
ORC_ASM_CODE(compiler," vorr.i32 %s, #0x%08x\n",
orc_neon_reg_name_quad (reg), (value & 0xff) << 16);
code = 0xf2800510;
code |= (reg&0xf) << 12;
code |= ((reg>>4)&0x1) << 22;
code |= (value&0xf) << 0;
code |= (value&0x70) << 12;
code |= (value&0x80) << 17;
code |= 0x40;
orc_arm_emit (compiler, code);
}
value >>= 8;
if (value & 0xff) {
ORC_ASM_CODE(compiler," vorr.i32 %s, #0x%08x\n",
orc_neon_reg_name_quad (reg), (value & 0xff) << 24);
code = 0xf2800710;
code |= (reg&0xf) << 12;
code |= ((reg>>4)&0x1) << 22;
code |= (value&0xf) << 0;
code |= (value&0x70) << 12;
code |= (value&0x80) << 17;
code |= 0x40;
orc_arm_emit (compiler, code);
}
}
}
static void
orc_neon_emit_loadiq (OrcCompiler *compiler, OrcVariable *dest, long long value)
{
int reg = dest->alloc;
/* orc_uint32 code; */
/* int shift; */
/* int neg = FALSE; */
if (compiler->is_64bit) {
if (value == 0) {
orc_neon64_emit_binary (compiler, "eor", 0x2e201c00,
*dest, *dest, *dest, compiler->insn_shift - 1);
return;
}
/*
* NOTE: This could be optimized further. The code below is 5 instructions
* long. By locating 8-bit "islands" of bits in the value itself (8-bit is
* the limit of IMM field in MOVI/ORR opcode), it may be possible for some
* sparse constants (with fewer than 5 such islands) to generate far more
* optimal (shorter than 5 instructions) load using MOVI and ORR opcodes
* instead. However, such optimization might also be premature, since the
* constant is usually loaded only once when the program starts, hence it
* is not implemented below for now.
*/
ORC_ASM_CODE(compiler," ldr %s, L30\n",
orc_neon64_reg_name_vector (reg, 8, 0));
orc_arm_emit (compiler, 0x5c000040 | (reg & 0x1f));
orc_arm_emit_branch (compiler, ORC_ARM_COND_AL, 30);
orc_arm_emit (compiler, value & 0xffffffffULL);
orc_arm_emit (compiler, value >> 32ULL);
orc_arm_emit_label (compiler, 30);
orc_neon64_emit_binary (compiler, "trn1", 0x0ec02800,
*dest, *dest, *dest, compiler->insn_shift - 1);
return;
} else {
if (value == 0) {
orc_neon_emit_binary_quad (compiler, "veor", 0xf3000110, reg, reg, reg);
return;
}
if (value < 0) {
/* neg = TRUE; */
value = ~value;
}
#if 0
shift = orc_neon_get_const_shift (value);
if ((value & (0xff<<shift)) == value) {
value >>= shift;
if (neg) {
ORC_ASM_CODE(compiler," vmvn.i64 %s, #%d\n",
orc_neon_reg_name_quad (reg), value);
code = 0xf2800030;
} else {
ORC_ASM_CODE(compiler," vmov.i64 %s, #%d\n",
orc_neon_reg_name_quad (reg), value);
code = 0xf2800010;
}
code |= (reg&0xf) << 12;
code |= ((reg>>4)&0x1) << 22;
code |= (value&0xf) << 0;
code |= (value&0x70) << 12;
code |= (value&0x80) << 17;
code |= 0x40;
orc_arm_emit (compiler, code);
if (shift > 0) {
ORC_ASM_CODE(compiler," vshl.i64 %s, %s, #%d\n",
orc_neon_reg_name_quad (reg), orc_neon_reg_name_quad (reg), shift);
code = 0xf2a00510;
code |= (reg&0xf) << 12;
code |= ((reg>>4)&0x1) << 22;
code |= (reg&0xf) << 0;
code |= ((reg>>4)&0x1) << 5;
code |= (shift&0xf) << 16;
code |= 0x40;
orc_arm_emit (compiler, code);
}
return;
}
#endif
}
ORC_COMPILER_ERROR(compiler, "unimplemented load of constant %d", value);
}
void
orc_neon_emit_loadpb (OrcCompiler *compiler, int dest, int param)
{
orc_uint32 code;
if (compiler->is_64bit) {
orc_arm64_emit_add_imm (compiler, 64, compiler->gp_tmpreg,
compiler->exec_reg, ORC_STRUCT_OFFSET(OrcExecutor, params[param]));
ORC_ASM_CODE(compiler," ld1r {%s, %s}, [%s]\n",
orc_neon64_reg_name_vector (dest, 1, 0),
orc_neon64_reg_name_vector (dest+1, 1, 0),
orc_arm64_reg_name (compiler->gp_tmpreg, 64));
code = 0x0d40c000;
code |= 1 << 30; /* Q-bit */
code |= (compiler->gp_tmpreg&0x1f) << 5;
code |= (dest&0x1f) << 0;
} else {
orc_arm_emit_add_imm (compiler, compiler->gp_tmpreg,
compiler->exec_reg, ORC_STRUCT_OFFSET(OrcExecutor, params[param]));
ORC_ASM_CODE(compiler," vld1.8 {%s[],%s[]}, [%s]\n",
orc_neon_reg_name (dest), orc_neon_reg_name (dest+1),
orc_arm_reg_name (compiler->gp_tmpreg));
code = 0xf4a00c2f;
code |= (compiler->gp_tmpreg&0xf) << 16;
code |= (dest&0xf) << 12;
code |= ((dest>>4)&0x1) << 22;
}
orc_arm_emit (compiler, code);
}
void
orc_neon_emit_loadpw (OrcCompiler *compiler, int dest, int param)
{
orc_uint32 code;
if (compiler->is_64bit) {
orc_arm64_emit_add_imm (compiler, 64, compiler->gp_tmpreg,
compiler->exec_reg, ORC_STRUCT_OFFSET(OrcExecutor, params[param]));
ORC_ASM_CODE(compiler," ld1r {%s, %s}, [%s]\n",
orc_neon64_reg_name_vector (dest, 2, 0),
orc_neon64_reg_name_vector (dest+1, 2, 0),
orc_arm64_reg_name (compiler->gp_tmpreg, 64));
code = 0x0d40c400;
code |= 1 << 30; /* Q-bit */
code |= (compiler->gp_tmpreg&0x1f) << 5;
code |= (dest&0x1f) << 0;
} else {
orc_arm_emit_add_imm (compiler, compiler->gp_tmpreg,
compiler->exec_reg, ORC_STRUCT_OFFSET(OrcExecutor, params[param]));
ORC_ASM_CODE(compiler," vld1.16 {%s[],%s[]}, [%s]\n",
orc_neon_reg_name (dest), orc_neon_reg_name (dest+1),
orc_arm_reg_name (compiler->gp_tmpreg));
code = 0xf4a00c6f;
code |= (compiler->gp_tmpreg&0xf) << 16;
code |= (dest&0xf) << 12;
code |= ((dest>>4)&0x1) << 22;
}
orc_arm_emit (compiler, code);
}
void
orc_neon_emit_loadpl (OrcCompiler *compiler, int dest, int param)
{
orc_uint32 code;
if (compiler->is_64bit) {
orc_arm64_emit_add_imm (compiler, 64, compiler->gp_tmpreg,
compiler->exec_reg, ORC_STRUCT_OFFSET(OrcExecutor, params[param]));
ORC_ASM_CODE(compiler," ld1r {%s, %s}, [%s]\n",
orc_neon64_reg_name_vector (dest, 4, 0),
orc_neon64_reg_name_vector (dest+1, 4, 0),
orc_arm64_reg_name (compiler->gp_tmpreg, 64));
code = 0x0d40c800;
code |= 1 << 30; /* Q-bit */
code |= (compiler->gp_tmpreg&0x1f) << 5;
code |= (dest&0x1f) << 0;
} else {
orc_arm_emit_add_imm (compiler, compiler->gp_tmpreg,
compiler->exec_reg, ORC_STRUCT_OFFSET(OrcExecutor, params[param]));
ORC_ASM_CODE(compiler," vld1.32 {%s[],%s[]}, [%s]\n",
orc_neon_reg_name (dest), orc_neon_reg_name (dest+1),
orc_arm_reg_name (compiler->gp_tmpreg));
code = 0xf4a00caf;
code |= (compiler->gp_tmpreg&0xf) << 16;
code |= (dest&0xf) << 12;
code |= ((dest>>4)&0x1) << 22;
}
orc_arm_emit (compiler, code);
}
static void
orc_neon_emit_loadpq (OrcCompiler *compiler, int dest, int param)
{
orc_uint32 code;
int update = FALSE;
if (compiler->is_64bit) {
orc_arm64_emit_add_imm (compiler, 64, compiler->gp_tmpreg,
compiler->exec_reg, ORC_STRUCT_OFFSET(OrcExecutor, params[param]));
/*
* This here is a bit more complex, as the top 32 bits of the Tx are
* stored at an offset sizeof(params) * (ORC_VAR_T1-ORC_VAR_P1) from
* bottom 32 bits Px, so we do interleaved load using LD3, where the
* (v0.4s)[0] is Px and (v2.4s)[2] is Tx, because they are exactly
* 256 bits apart = 32 bytes = sizeof(params)*(ORC_VAR_T1-ORC_VAR_P1).
*
* The way all the LD1..LD4R opcodes work may be inobvious from the
* ARM A64 ISA documentation. See the following article:
* https://community.arm.com/developer/ip-products/processors/b/processors-ip-blog/posts/coding-for-neon---part-1-load-and-stores
*
* Specifically, LD3.32 with Q-bit set (128-bit operation) works this
* way. Assume array of 32bit types with 12 entries:
*
* uint32_t x0[12];
* ld3 {v0.4s, v1.4d, v2.4s}, [x0] .--- LSB (address 0)
* results in: v
* v0.4s[127:0] = { x0[9], x0[6], x0[3], x0[0] };
* v1.4s[127:0] = { x0[10], x0[7], x0[4], x0[1] };
* v2.4s[127:0] = { x0[11], x0[8], x0[5], x0[2] };
*
* To obtain the correct final result of loadpq, two MOV instructions
* are necessary to generate v0.4s = { x0[8], x0[0], x0[8], x0[0] };
* Note that there might be a better way to perform the mixing with
* some TRN/ZIP/UZP instruction.
*/
ORC_ASSERT((ORC_VAR_T1-ORC_VAR_P1) == 8);
ORC_ASM_CODE(compiler," ld3 {%s - %s}, [%s]\n",
orc_neon64_reg_name_vector (dest, 8, 0),
orc_neon64_reg_name_vector (dest+2, 8, 0),
orc_arm64_reg_name (compiler->gp_tmpreg, 64));
code = 0x0c404800;
code |= 1 << 30; /* Q-bit */
code |= (compiler->gp_tmpreg&0x1f) << 5;
code |= (dest&0x1f) << 0;
orc_arm_emit (compiler, code);
ORC_ASM_CODE(compiler," mov %s[1], %s[2]\n",
orc_neon64_reg_name_vector (dest, 4, 0),
orc_neon64_reg_name_vector (dest+2, 4, 0));
code = 0x6e0c4400;
code |= ((dest+2)&0x1f) << 5;
code |= (dest&0x1f) << 0;
orc_arm_emit (compiler, code);
ORC_ASM_CODE(compiler," mov %s[1], %s[0]\n",
orc_neon64_reg_name_vector (dest, 8, 0),
orc_neon64_reg_name_vector (dest, 8, 0));
code = 0x6e180400;
code |= (dest&0x1f) << 5;
code |= (dest&0x1f) << 0;
orc_arm_emit (compiler, code);
} else {
orc_arm_emit_add_imm (compiler, compiler->gp_tmpreg,
compiler->exec_reg, ORC_STRUCT_OFFSET(OrcExecutor, params[param]));
ORC_ASM_CODE(compiler," vld1.32 %s[0], [%s]%s\n",
orc_neon_reg_name (dest),
orc_arm_reg_name (compiler->gp_tmpreg),
update ? "!" : "");
code = 0xf4a0000d;
code |= 2<<10;
code |= (0)<<7;
code |= (compiler->gp_tmpreg&0xf) << 16;
code |= (dest&0xf) << 12;
code |= ((dest>>4)&0x1) << 22;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
ORC_ASM_CODE(compiler," vld1.32 %s[0], [%s]%s\n",
orc_neon_reg_name (dest+1),
orc_arm_reg_name (compiler->gp_tmpreg),
update ? "!" : "");
code = 0xf4a0000d;
code |= 2<<10;
code |= (0)<<7;
code |= (compiler->gp_tmpreg&0xf) << 16;
code |= ((dest+1)&0xf) << 12;
code |= (((dest+1)>>4)&0x1) << 22;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
orc_arm_emit_add_imm (compiler, compiler->gp_tmpreg,
compiler->exec_reg, ORC_STRUCT_OFFSET(OrcExecutor,
params[param + (ORC_VAR_T1-ORC_VAR_P1)]));
ORC_ASM_CODE(compiler," vld1.32 %s[1], [%s]%s\n",
orc_neon_reg_name (dest),
orc_arm_reg_name (compiler->gp_tmpreg),
update ? "!" : "");
code = 0xf4a0000d;
code |= 2<<10;
code |= (1)<<7;
code |= (compiler->gp_tmpreg&0xf) << 16;
code |= (dest&0xf) << 12;
code |= ((dest>>4)&0x1) << 22;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
ORC_ASM_CODE(compiler," vld1.32 %s[1], [%s]%s\n",
orc_neon_reg_name (dest+1),
orc_arm_reg_name (compiler->gp_tmpreg),
update ? "!" : "");
code = 0xf4a0000d;
code |= 2<<10;
code |= (1)<<7;
code |= (compiler->gp_tmpreg&0xf) << 16;
code |= ((dest+1)&0xf) << 12;
code |= (((dest+1)>>4)&0x1) << 22;
code |= (!update) << 1;
orc_arm_emit (compiler, code);
}
}
#define UNARY(opcode,insn_name,code,insn_name64,code64,vec_shift) \
static void \
orc_neon_rule_ ## opcode (OrcCompiler *p, void *user, OrcInstruction *insn) \
{ \
if (p->is_64bit) { \
if (insn_name64) { \
orc_neon64_emit_unary (p, insn_name64, code64, \
p->vars[insn->dest_args[0]], \
p->vars[insn->src_args[0]], vec_shift); \
} else { \
ORC_COMPILER_ERROR(p, "not supported in AArch64 yet [%s %x]", (insn_name64), (code64)); \
} \
} else { \
if (p->insn_shift <= vec_shift) { \
orc_neon_emit_unary (p, insn_name, code, \
p->vars[insn->dest_args[0]].alloc, \
p->vars[insn->src_args[0]].alloc); \
} else if (p->insn_shift == vec_shift + 1) { \
orc_neon_emit_unary_quad (p, insn_name, code, \
p->vars[insn->dest_args[0]].alloc, \
p->vars[insn->src_args[0]].alloc); \
} else { \
ORC_COMPILER_ERROR(p, "shift too large"); \
} \
} \
}
#define UNARY_LONG(opcode,insn_name,code,insn_name64,code64,vec_shift) \
static void \
orc_neon_rule_ ## opcode (OrcCompiler *p, void *user, OrcInstruction *insn) \
{ \
if (p->is_64bit) { \
if (insn_name64) { \
orc_neon64_emit_unary (p, insn_name64, code64, \
p->vars[insn->dest_args[0]], \
p->vars[insn->src_args[0]], vec_shift); \
} else { \
ORC_COMPILER_ERROR(p, "not supported in AArch64 yet [%s %x]", (insn_name64), (code64)); \
} \
} else { \
if (p->insn_shift <= vec_shift) { \
orc_neon_emit_unary_long (p, insn_name, code, \
p->vars[insn->dest_args[0]].alloc, \
p->vars[insn->src_args[0]].alloc); \
} else { \
ORC_COMPILER_ERROR(p, "shift too large"); \
} \
} \
}
#define UNARY_NARROW(opcode,insn_name,code,insn_name64,code64,vec_shift) \
static void \
orc_neon_rule_ ## opcode (OrcCompiler *p, void *user, OrcInstruction *insn) \
{ \
if (p->is_64bit) { \
if (insn_name64) { \
orc_neon64_emit_unary (p, insn_name64, code64, \
p->vars[insn->dest_args[0]], \
p->vars[insn->src_args[0]], vec_shift); \
} else { \
ORC_COMPILER_ERROR(p, "not supported in AArch64 yet [%s %x]", (insn_name64), (code64)); \
} \
} else { \
if (p->insn_shift <= vec_shift) { \
orc_neon_emit_unary_narrow (p, insn_name, code, \
p->vars[insn->dest_args[0]].alloc, \
p->vars[insn->src_args[0]].alloc); \
} else { \
ORC_COMPILER_ERROR(p, "shift too large"); \
} \
} \
}
#define BINARY(opcode,insn_name,code,insn_name64,code64,vec_shift) \
static void \
orc_neon_rule_ ## opcode (OrcCompiler *p, void *user, OrcInstruction *insn) \
{ \
if (p->is_64bit) { \
if (insn_name64) { \
orc_neon64_emit_binary (p, insn_name64, code64, \
p->vars[insn->dest_args[0]], \
p->vars[insn->src_args[0]], \
p->vars[insn->src_args[1]], vec_shift); \
} else { \
ORC_COMPILER_ERROR(p, "not supported in AArch64 yet"); \
} \
} else { \
if (p->insn_shift <= vec_shift) { \
orc_neon_emit_binary (p, insn_name, code, \
p->vars[insn->dest_args[0]].alloc, \
p->vars[insn->src_args[0]].alloc, \
p->vars[insn->src_args[1]].alloc); \
} else if (p->insn_shift == vec_shift + 1) { \
orc_neon_emit_binary_quad (p, insn_name, code, \
p->vars[insn->dest_args[0]].alloc, \
p->vars[insn->src_args[0]].alloc, \
p->vars[insn->src_args[1]].alloc); \
} else { \
ORC_COMPILER_ERROR(p, "shift too large"); \
} \
} \
}
#define BINARY_LONG(opcode,insn_name,code,insn_name64,code64,vec_shift) \
static void \
orc_neon_rule_ ## opcode (OrcCompiler *p, void *user, OrcInstruction *insn) \
{ \
if (p->is_64bit) { \
if (insn_name64) { \
orc_neon64_emit_binary (p, insn_name64, code64, \
p->vars[insn->dest_args[0]], \
p->vars[insn->src_args[0]], \
p->vars[insn->src_args[1]], vec_shift); \
} else { \
ORC_COMPILER_ERROR(p, "not supported in AArch64 yet [%s %x]", (insn_name64), (code64)); \
} \
} else { \
if (p->insn_shift <= vec_shift) { \
orc_neon_emit_binary_long (p, insn_name, code, \
p->vars[insn->dest_args[0]].alloc, \
p->vars[insn->src_args[0]].alloc, \
p->vars[insn->src_args[1]].alloc); \
} else { \
ORC_COMPILER_ERROR(p, "shift too large"); \
} \
} \
}
#define BINARY_NARROW(opcode,insn_name,code,insn_name64,code64,vec_shift) \
static void \
orc_neon_rule_ ## opcode (OrcCompiler *p, void *user, OrcInstruction *insn) \
{ \
if (p->is_64bit) { \
if (insn_name64) { \
orc_neon64_emit_binary (p, insn_name64, code64, \
p->vars[insn->dest_args[0]], \
p->vars[insn->src_args[0]], \
p->vars[insn->src_args[1]], vec_shift); \
} else { \
ORC_COMPILER_ERROR(p, "not supported in AArch64 yet [%s %x]", (insn_name64), (code64)); \
} \
} else { \
if (p->insn_shift <= vec_shift) { \
orc_neon_emit_binary_narrow (p, insn_name, code, \
p->vars[insn->dest_args[0]].alloc, \
p->vars[insn->src_args[0]].alloc, \
p->vars[insn->src_args[1]].alloc); \
} else { \
ORC_COMPILER_ERROR(p, "shift too large"); \
} \
} \
}
#define MOVE(opcode,insn_name,code,insn_name64,code64,vec_shift) \
static void \
orc_neon_rule_ ## opcode (OrcCompiler *p, void *user, OrcInstruction *insn) \
{ \
if (p->vars[insn->dest_args[0]].alloc == p->vars[insn->src_args[0]].alloc) { \
return; \
} \
if (p->is_64bit) { \
if (insn_name64) { \
orc_neon64_emit_binary (p, insn_name64, code64, \
p->vars[insn->dest_args[0]], \
p->vars[insn->src_args[0]], \
p->vars[insn->src_args[0]], vec_shift); \
} else { \
ORC_COMPILER_ERROR(p, "not supported in AArch64 yet [%s %x]", (insn_name64), (code64)); \
} \
} else { \
if (p->insn_shift <= vec_shift) { \
orc_neon_emit_binary (p, "vorr", 0xf2200110, \
p->vars[insn->dest_args[0]].alloc, \
p->vars[insn->src_args[0]].alloc, \
p->vars[insn->src_args[0]].alloc); \
} else if (p->insn_shift == vec_shift + 1) { \
orc_neon_emit_binary_quad (p, "vorr", 0xf2200110, \
p->vars[insn->dest_args[0]].alloc, \
p->vars[insn->src_args[0]].alloc, \
p->vars[insn->src_args[0]].alloc); \
} else { \
ORC_COMPILER_ERROR(p, "shift too large"); \
} \
} \
}
typedef struct {
orc_uint32 code;
char *name;
orc_uint32 code64;
char *name64;
int negate;
int bits;
int vec_shift;
} ShiftInfo;
ShiftInfo immshift_info[] = {
{ 0xf2880510, "vshl.i8", 0x0f085400, "shl", FALSE, 8, 3 }, /* shlb */
{ 0xf2880010, "vshr.s8", 0x0f080400, "sshr", TRUE, 8, 3 }, /* shrsb */
{ 0xf3880010, "vshr.u8", 0x2f080400, "ushr", TRUE, 8, 3 }, /* shrub */
{ 0xf2900510, "vshl.i16", 0x0f105400, "shl", FALSE, 16, 2 },
{ 0xf2900010, "vshr.s16", 0x0f100400, "sshr", TRUE, 16, 2 },
{ 0xf3900010, "vshr.u16", 0x2f100400, "ushr", TRUE, 16, 2 },
{ 0xf2a00510, "vshl.i32", 0x0f205400, "shl", FALSE, 32, 1 },
{ 0xf2a00010, "vshr.s32", 0x0f200400, "sshr", TRUE, 32, 1 },
{ 0xf3a00010, "vshr.u32", 0x2f200400, "ushr", TRUE, 32, 1 }
};
ShiftInfo regshift_info[] = {
{ 0xf3000400, "vshl.u8", 0x2e204400, "ushl", FALSE, 0, 3 }, /* shlb */
{ 0xf2000400, "vshl.s8", 0x0e204400, "sshl", TRUE, 0, 3 }, /* shrsb */
{ 0xf3000400, "vshl.u8", 0x2e204400, "ushl", TRUE, 0, 3 }, /* shrub */
{ 0xf3100400, "vshl.u16", 0x2e604400, "ushl", FALSE, 0, 2 },
{ 0xf2100400, "vshl.s16", 0x0e604400, "sshl", TRUE, 0, 2 },
{ 0xf3100400, "vshl.u16", 0x2e604400, "ushl", TRUE, 0, 2 },
{ 0xf3200400, "vshl.u32", 0x2ea04400, "ushl", FALSE, 0, 1 },
{ 0xf2200400, "vshl.s32", 0x0ea04400, "sshl", TRUE, 0, 1 },
{ 0xf3200400, "vshl.u32", 0x2ea04400, "ushl", TRUE, 0, 1 }
};
static void
orc_neon_rule_shift (OrcCompiler *p, void *user, OrcInstruction *insn)
{
int type = ORC_PTR_TO_INT(user);
orc_uint32 code;
if (p->vars[insn->src_args[1]].vartype == ORC_VAR_TYPE_CONST) {
int shift = p->vars[insn->src_args[1]].value.i;
if (shift < 0) {
ORC_COMPILER_ERROR(p, "shift negative");
return;
}
if (shift >= immshift_info[type].bits) {
ORC_COMPILER_ERROR(p, "shift too large");
return;
}
if (p->is_64bit) {
code = immshift_info[type].code64;
if (p->insn_shift <= immshift_info[type].vec_shift) {
ORC_ASM_CODE(p," %s %s, %s, #%d\n",
immshift_info[type].name64,
orc_neon64_reg_name_vector (p->vars[insn->dest_args[0]].alloc, 1, 0),
orc_neon64_reg_name_vector (p->vars[insn->src_args[0]].alloc, 1, 0),
(int)p->vars[insn->src_args[1]].value.i);
} else {
ORC_ASM_CODE(p," %s %s, %s, #%d\n",
immshift_info[type].name64,
orc_neon64_reg_name_vector (p->vars[insn->dest_args[0]].alloc, 1, 1),
orc_neon64_reg_name_vector (p->vars[insn->src_args[0]].alloc, 1, 1),
(int)p->vars[insn->src_args[1]].value.i);
code |= 1 << 30;
}
code |= (p->vars[insn->dest_args[0]].alloc&0x1f)<<0;
code |= (p->vars[insn->src_args[0]].alloc&0x1f)<<5;
} else {
code = immshift_info[type].code;
if (p->insn_shift <= immshift_info[type].vec_shift) {
ORC_ASM_CODE(p," %s %s, %s, #%d\n",
immshift_info[type].name,
orc_neon_reg_name (p->vars[insn->dest_args[0]].alloc),
orc_neon_reg_name (p->vars[insn->src_args[0]].alloc),
(int)p->vars[insn->src_args[1]].value.i);
} else {
ORC_ASM_CODE(p," %s %s, %s, #%d\n",
immshift_info[type].name,
orc_neon_reg_name_quad (p->vars[insn->dest_args[0]].alloc),
orc_neon_reg_name_quad (p->vars[insn->src_args[0]].alloc),
(int)p->vars[insn->src_args[1]].value.i);
code |= 0x40;
}
code |= (p->vars[insn->dest_args[0]].alloc&0xf)<<12;
code |= ((p->vars[insn->dest_args[0]].alloc>>4)&0x1)<<22;
code |= (p->vars[insn->src_args[0]].alloc&0xf)<<0;
code |= ((p->vars[insn->src_args[0]].alloc>>4)&0x1)<<5;
}
if (immshift_info[type].negate) {
shift = immshift_info[type].bits - shift;
}
code |= shift<<16;
orc_arm_emit (p, code);
} else if (p->vars[insn->src_args[1]].vartype == ORC_VAR_TYPE_PARAM) {
OrcVariable tmpreg = { .alloc = p->tmpreg, .size = p->vars[insn->src_args[0]].size };
orc_neon_emit_loadpb (p, p->tmpreg, insn->src_args[1]);
if (regshift_info[type].negate) {
if (p->is_64bit)
orc_neon64_emit_unary (p, "neg", 0x2e20b800, tmpreg, tmpreg, p->insn_shift - 1);
else
orc_neon_emit_unary_quad (p, "vneg.s8", 0xf3b10380, p->tmpreg, p->tmpreg);
}
if (p->is_64bit) {
orc_neon64_emit_binary (p, regshift_info[type].name64,
regshift_info[type].code64,
p->vars[insn->dest_args[0]],
p->vars[insn->src_args[0]],
tmpreg,
p->insn_shift - !!(p->insn_shift > regshift_info[type].vec_shift));
} else {
code = regshift_info[type].code;
if (p->insn_shift <= regshift_info[type].vec_shift) {
ORC_ASM_CODE(p," %s %s, %s, %s\n",
regshift_info[type].name,
orc_neon_reg_name (p->vars[insn->dest_args[0]].alloc),
orc_neon_reg_name (p->vars[insn->src_args[0]].alloc),
orc_neon_reg_name (p->tmpreg));
} else {
ORC_ASM_CODE(p," %s %s, %s, %s\n",
regshift_info[type].name,
orc_neon_reg_name_quad (p->vars[insn->dest_args[0]].alloc),
orc_neon_reg_name_quad (p->vars[insn->src_args[0]].alloc),
orc_neon_reg_name_quad (p->tmpreg));
code |= 0x40;
}
code |= (p->vars[insn->dest_args[0]].alloc&0xf)<<12;
code |= ((p->vars[insn->dest_args[0]].alloc>>4)&0x1)<<22;
code |= (p->vars[insn->src_args[0]].alloc&0xf)<<0;
code |= ((p->vars[insn->src_args[0]].alloc>>4)&0x1)<<5;
code |= (p->tmpreg&0xf)<<16;
code |= ((p->tmpreg>>4)&0x1)<<7;
orc_arm_emit (p, code);
}
} else {
ORC_PROGRAM_ERROR(p,"shift rule only works with constants and params");
}
}
#if 0
static void
orc_neon_rule_shrsw (OrcCompiler *p, void *user, OrcInstruction *insn)
{
orc_uint32 code;
if (p->vars[insn->src_args[1]].vartype == ORC_VAR_TYPE_CONST) {
code = 0xf2900010;
ORC_ASM_CODE(p," vshr.s16 %s, %s, #%d\n",
orc_neon_reg_name (p->vars[insn->dest_args[0]].alloc),
orc_neon_reg_name (p->vars[insn->src_args[0]].alloc),
p->vars[insn->src_args[1]].value);
code |= (p->vars[insn->dest_args[0]].alloc&0xf)<<12;
code |= ((p->vars[insn->dest_args[0]].alloc>>4)&0x1)<<22;
code |= (p->vars[insn->src_args[0]].alloc&0xf)<<0;
code |= ((p->vars[insn->src_args[0]].alloc>>4)&0x1)<<5;
code |= ((16 - p->vars[insn->src_args[1]].value)&0xf)<<16;
orc_arm_emit (p, code);
} else if (p->vars[insn->src_args[1]].vartype == ORC_VAR_TYPE_PARAM) {
code = 0xf2100400;
ORC_ASM_CODE(p," vshl.s16 %s, %s, %s\n",
orc_neon_reg_name (p->vars[insn->dest_args[0]].alloc),
orc_neon_reg_name (p->vars[insn->src_args[0]].alloc),
orc_neon_reg_name (p->vars[insn->src_args[1]].alloc));
code |= (p->vars[insn->dest_args[0]].alloc&0xf)<<12;
code |= ((p->vars[insn->dest_args[0]].alloc>>4)&0x1)<<22;
code |= (p->vars[insn->src_args[0]].alloc&0xf)<<0;
code |= ((p->vars[insn->src_args[0]].alloc>>4)&0x1)<<5;
code |= (p->vars[insn->src_args[1]].alloc&0xf)<<16;
code |= ((p->vars[insn->src_args[1]].alloc>>4)&0x1)<<7;
orc_arm_emit (p, code);
} else {
ORC_PROGRAM_ERROR(p,"shift rule only works with constants and params");
}
}
static void
orc_neon_rule_shrsl (OrcCompiler *p, void *user, OrcInstruction *insn)
{
orc_uint32 code;
if (p->vars[insn->src_args[1]].vartype == ORC_VAR_TYPE_CONST) {
code = 0xf2900010;
ORC_ASM_CODE(p," vshr.s32 %s, %s, #%d\n",
orc_neon_reg_name (p->vars[insn->dest_args[0]].alloc),
orc_neon_reg_name (p->vars[insn->src_args[0]].alloc),
p->vars[insn->src_args[1]].value);
code |= (p->vars[insn->dest_args[0]].alloc&0xf)<<12;
code |= ((p->vars[insn->dest_args[0]].alloc>>4)&0x1)<<22;
code |= (p->vars[insn->src_args[0]].alloc&0xf)<<0;
code |= ((p->vars[insn->src_args[0]].alloc>>4)&0x1)<<5;
code |= ((16 - p->vars[insn->src_args[1]].value)&0xf)<<16;
orc_arm_emit (p, code);
} else if (p->vars[insn->src_args[1]].vartype == ORC_VAR_TYPE_PARAM) {
code = 0xf2100400;
ORC_ASM_CODE(p," vshl.s32 %s, %s, %s\n",
orc_neon_reg_name (p->vars[insn->dest_args[0]].alloc),
orc_neon_reg_name (p->vars[insn->src_args[0]].alloc),
orc_neon_reg_name (p->vars[insn->src_args[1]].alloc));
code |= (p->vars[insn->dest_args[0]].alloc&0xf)<<12;
code |= ((p->vars[insn->dest_args[0]].alloc>>4)&0x1)<<22;
code |= (p->vars[insn->src_args[0]].alloc&0xf)<<0;
code |= ((p->vars[insn->src_args[0]].alloc>>4)&0x1)<<5;
code |= (p->vars[insn->src_args[1]].alloc&0xf)<<16;
code |= ((p->vars[insn->src_args[1]].alloc>>4)&0x1)<<7;
orc_arm_emit (p, code);
} else {
ORC_PROGRAM_ERROR(p,"shift rule only works with constants and params");
}
}
#endif
static void
orc_neon_rule_andn (OrcCompiler *p, void *user, OrcInstruction *insn)
{
int max_shift = ORC_PTR_TO_INT(user);
if (p->is_64bit) {
orc_neon64_emit_binary (p, "bic", 0x0e601c00,
p->vars[insn->dest_args[0]],
p->vars[insn->src_args[1]],
p->vars[insn->src_args[0]],
p->insn_shift - (p->insn_shift > max_shift));
} else {
/* this is special because the operand order is reversed */
if (p->insn_shift <= max_shift) {
orc_neon_emit_binary (p, "vbic", 0xf2100110,
p->vars[insn->dest_args[0]].alloc,
p->vars[insn->src_args[1]].alloc,
p->vars[insn->src_args[0]].alloc);
} else {
orc_neon_emit_binary_quad (p, "vbic", 0xf2100110,
p->vars[insn->dest_args[0]].alloc,
p->vars[insn->src_args[1]].alloc,
p->vars[insn->src_args[0]].alloc);
}
}
}
UNARY(absb,"vabs.s8",0xf3b10300, "abs", 0x0e20b800, 3)
BINARY(addb,"vadd.i8",0xf2000800, "add", 0x0e208400, 3)
BINARY(addssb,"vqadd.s8",0xf2000010, "sqadd", 0x0e200c00, 3)
BINARY(addusb,"vqadd.u8",0xf3000010, "uqadd", 0x2e200c00, 3)
BINARY(andb,"vand",0xf2000110, "and", 0x0e201c00, 3)
/* BINARY(andnb,"vbic",0xf2100110, NULL, 0, 3) */
BINARY(avgsb,"vrhadd.s8",0xf2000100, "srhadd", 0x0e201400, 3)
BINARY(avgub,"vrhadd.u8",0xf3000100, "urhadd", 0x2e201400, 3)
BINARY(cmpeqb,"vceq.i8",0xf3000810, "cmeq", 0x2e208c00, 3)
BINARY(cmpgtsb,"vcgt.s8",0xf2000300, "cmgt", 0x0e203400, 3)
MOVE(copyb,"vmov",0xf2200110, "mov", 0x0ea01c00, 3)
BINARY(maxsb,"vmax.s8",0xf2000600, "smax", 0x0e206400, 3)
BINARY(maxub,"vmax.u8",0xf3000600, "umax", 0x2e206400, 3)
BINARY(minsb,"vmin.s8",0xf2000610, "smin", 0x0e206c00, 3)
BINARY(minub,"vmin.u8",0xf3000610, "umin", 0x2e206c00, 3)
BINARY(mullb,"vmul.i8",0xf2000910, "mul", 0x0e209c00, 3)
BINARY(orb,"vorr",0xf2200110, "orr", 0x0ea01c00, 3)
/* LSHIFT(shlb,"vshl.i8",0xf2880510, NULL, 0, 3) */
/* RSHIFT(shrsb,"vshr.s8",0xf2880010,8, NULL, 0, 3) */
/* RSHIFT(shrub,"vshr.u8",0xf3880010,8, NULL, 0, 3) */
BINARY(subb,"vsub.i8",0xf3000800, "sub", 0x2e208400, 3)
BINARY(subssb,"vqsub.s8",0xf2000210, "sqsub", 0x0e202c00, 3)
BINARY(subusb,"vqsub.u8",0xf3000210, "uqsub", 0x2e202c00, 3)
BINARY(xorb,"veor",0xf3000110, "eor", 0x2e201c00, 3)
UNARY(absw,"vabs.s16",0xf3b50300, "abs", 0x0e60b800, 2)
BINARY(addw,"vadd.i16",0xf2100800, "add", 0x0e608400, 2)
BINARY(addssw,"vqadd.s16",0xf2100010, "sqadd", 0x0e600c00, 2)
BINARY(addusw,"vqadd.u16",0xf3100010, "uqadd", 0x2e600c00, 2)
BINARY(andw,"vand",0xf2000110, "and", 0x0e201c00, 2)
/* BINARY(andnw,"vbic",0xf2100110, NULL, 0, 2) */
BINARY(avgsw,"vrhadd.s16",0xf2100100, "srhadd", 0x0e601400, 2)
BINARY(avguw,"vrhadd.u16",0xf3100100, "urhadd", 0x2e601400, 2)
BINARY(cmpeqw,"vceq.i16",0xf3100810, "cmeq", 0x2e608c00, 2)
BINARY(cmpgtsw,"vcgt.s16",0xf2100300, "cmgt", 0x0e603400, 2)
MOVE(copyw,"vmov",0xf2200110, "mov", 0x0ea01c00, 2)
BINARY(maxsw,"vmax.s16",0xf2100600, "smax", 0x0e606400, 2)
BINARY(maxuw,"vmax.u16",0xf3100600, "umax", 0x2e606400, 2)
BINARY(minsw,"vmin.s16",0xf2100610, "smin", 0x0e606c00, 2)
BINARY(minuw,"vmin.u16",0xf3100610, "umin", 0x2e606c00, 2)
BINARY(mullw,"vmul.i16",0xf2100910, "mul", 0x0e609c00, 2)
BINARY(orw,"vorr",0xf2200110, "orr", 0x0ea01c00, 2)
/* LSHIFT(shlw,"vshl.i16",0xf2900510, NULL, 0, 2) */
/* RSHIFT(shrsw,"vshr.s16",0xf2900010,16, NULL, 0, 2) */
/* RSHIFT(shruw,"vshr.u16",0xf3900010,16, NULL, 0, 2) */
BINARY(subw,"vsub.i16",0xf3100800, "sub", 0x2e608400, 2)
BINARY(subssw,"vqsub.s16",0xf2100210, "sqsub", 0x0e602c00, 2)
BINARY(subusw,"vqsub.u16",0xf3100210, "uqsub", 0x2e602c00, 2)
BINARY(xorw,"veor",0xf3000110, "eor", 0x2e201c00, 2)
UNARY(absl,"vabs.s32",0xf3b90300, "abs", 0x0ea0b800, 1)
BINARY(addl,"vadd.i32",0xf2200800, "add", 0x0ea08400, 1)
BINARY(addssl,"vqadd.s32",0xf2200010, "sqadd", 0x0ea00c00, 1)
BINARY(addusl,"vqadd.u32",0xf3200010, "uqadd", 0x2ea00c00, 1)
BINARY(andl,"vand",0xf2000110, "and", 0x0e201c00, 1)
/* BINARY(andnl,"vbic",0xf2100110, NULL, 0, 1) */
BINARY(avgsl,"vrhadd.s32",0xf2200100, "srhadd", 0x0ea01400, 1)
BINARY(avgul,"vrhadd.u32",0xf3200100, "urhadd", 0x2ea01400, 1)
BINARY(cmpeql,"vceq.i32",0xf3200810, "cmeq", 0x2ea08c00, 1)
BINARY(cmpgtsl,"vcgt.s32",0xf2200300, "cmgt", 0x0ea03400, 1)
MOVE(copyl,"vmov",0xf2200110, "mov", 0x0ea01c00, 1)
BINARY(maxsl,"vmax.s32",0xf2200600, "smax", 0x0ea06400, 1)
BINARY(maxul,"vmax.u32",0xf3200600, "umax", 0x2ea06400, 1)
BINARY(minsl,"vmin.s32",0xf2200610, "smin", 0x0ea06c00, 1)
BINARY(minul,"vmin.u32",0xf3200610, "umin", 0x2ea06c00, 1)
BINARY(mulll,"vmul.i32",0xf2200910, "mul", 0x0ea09c00, 1)
BINARY(orl,"vorr",0xf2200110, "orr", 0x0ea01c00, 1)
/* LSHIFT(shll,"vshl.i32",0xf2a00510, NULL, 0, 1) */
/* RSHIFT(shrsl,"vshr.s32",0xf2a00010,32, NULL, 0, 1) */
/* RSHIFT(shrul,"vshr.u32",0xf3a00010,32, NULL, 0, 1) */
BINARY(subl,"vsub.i32",0xf3200800, "sub", 0x2ea08400, 1)
BINARY(subssl,"vqsub.s32",0xf2200210, "sqsub", 0x0ea02c00, 1)
BINARY(subusl,"vqsub.u32",0xf3200210, "uqsub", 0x2ea02c00, 1)
BINARY(xorl,"veor",0xf3000110, "eor", 0x2e201c00, 1)
/* UNARY(absq,"vabs.s64",0xf3b10300, "abs", 0xee0b800, 0) */
BINARY(addq,"vadd.i64",0xf2300800, "add", 0x4ee08400, 0)
/* BINARY(addssq,"vqadd.s64",0xf2000010, "sqadd", 0x0ee00c00, 0) */
/* BINARY(addusq,"vqadd.u64",0xf3000010, "uqadd", 0x2ee00c00, 0) */
BINARY(andq,"vand",0xf2000110, "and", 0x0e201c00, 0)
/* BINARY(avgsq,"vrhadd.s64",0xf2000100, "srhadd", 0x0ee01400, 0) */
/* BINARY(avguq,"vrhadd.u64",0xf3000100, "urhadd", 0x2ee01400, 0) */
/* BINARY(cmpeqq,"vceq.i64",0xf3000810, "cmeq", 0x2ee08c00, 0) */
/* BINARY(cmpgtsq,"vcgt.s64",0xf2000300, "cmgt", 0x0ee03400, 0) */
MOVE(copyq,"vmov",0xf2200110, "mov", 0x0ea01c00, 0)
/* BINARY(maxsq,"vmax.s64",0xf2000600, "smax", 0x0ee06400, 0) */
/* BINARY(maxuq,"vmax.u64",0xf3000600, "umax", 0x2ee06400, 0) */
/* BINARY(minsq,"vmin.s64",0xf2000610, "smin", 0x0ee06c00, 0) */
/* BINARY(minuq,"vmin.u64",0xf3000610, "umin", 0x2ee06c00, 0) */
/* BINARY(mullq,"vmul.i64",0xf2000910, "mul", 0x0ee09c00, 0) */
BINARY(orq,"vorr",0xf2200110, "orr", 0x0ea01c00, 0)
BINARY(subq,"vsub.i64",0xf3300800, "sub", 0x6ee08400, 0)
/* BINARY(subssq,"vqsub.s64",0xf2000210, "sqsub", 0x0ee00c00, 0) */
/* BINARY(subusq,"vqsub.u64",0xf3000210, "uqsub", 0x2ee00c00, 0) */
BINARY(xorq,"veor",0xf3000110, "eor", 0x2e201c00, 0)
UNARY_LONG(convsbw,"vmovl.s8",0xf2880a10, "sshll", 0x0f08a400, 3)
UNARY_LONG(convubw,"vmovl.u8",0xf3880a10, "ushll", 0x2f08a400, 3)
UNARY_LONG(convswl,"vmovl.s16",0xf2900a10, "sshll", 0x0f10a400, 2)
UNARY_LONG(convuwl,"vmovl.u16",0xf3900a10, "ushll", 0x2f10a400, 2)
UNARY_LONG(convslq,"vmovl.s32",0xf2a00a10, "sshll", 0x0f20a400, 1)
UNARY_LONG(convulq,"vmovl.u32",0xf3a00a10, "ushll", 0x2f20a400, 1)
UNARY_NARROW(convwb,"vmovn.i16",0xf3b20200, "xtn", 0x0e212800, 3)
UNARY_NARROW(convssswb,"vqmovn.s16",0xf3b20280, "sqxtn", 0x0e214800, 3)
UNARY_NARROW(convsuswb,"vqmovun.s16",0xf3b20240, "sqxtun", 0x2e212800, 3)
UNARY_NARROW(convuuswb,"vqmovn.u16",0xf3b202c0, "uqxtn", 0x2e214800, 3)
UNARY_NARROW(convlw,"vmovn.i32",0xf3b60200, "xtn", 0x0e612800, 2)
UNARY_NARROW(convql,"vmovn.i64",0xf3ba0200, "xtn", 0x0ea12800, 1)
UNARY_NARROW(convssslw,"vqmovn.s32",0xf3b60280, "sqxtn", 0x0e614800, 2)
UNARY_NARROW(convsuslw,"vqmovun.s32",0xf3b60240, "sqxtun", 0x2e612800, 2)
UNARY_NARROW(convuuslw,"vqmovn.u32",0xf3b602c0, "uqxtn", 0x2e614800, 2)
UNARY_NARROW(convsssql,"vqmovn.s64",0xf3ba0280, "sqxtn", 0x0ea14800, 1)
UNARY_NARROW(convsusql,"vqmovun.s64",0xf3ba0240, "sqxtun", 0x2ea12800, 1)
UNARY_NARROW(convuusql,"vqmovn.u64",0xf3ba02c0, "uqxtn", 0x2ea14800, 1)
BINARY_LONG(mulsbw,"vmull.s8",0xf2800c00, "smull", 0x0e20c000, 3)
BINARY_LONG(mulubw,"vmull.u8",0xf3800c00, "umull", 0x2e20c000, 3)
BINARY_LONG(mulswl,"vmull.s16",0xf2900c00, "smull", 0x0e60c000, 2)
BINARY_LONG(muluwl,"vmull.u16",0xf3900c00, "umull", 0x2e60c000, 2)
UNARY(swapw,"vrev16.i8",0xf3b00100, "rev16", 0x0e201800, 2)
UNARY(swapl,"vrev32.i8",0xf3b00080, "rev32", 0x2e200800, 1)
UNARY(swapq,"vrev64.i8",0xf3b00000, "rev64", 0x0e200800, 0)
UNARY(swapwl,"vrev32.i16",0xf3b40080, "rev32", 0x2e600800, 1)
UNARY(swaplq,"vrev64.i32",0xf3b80000, "rev64", 0x0ea00800, 0)
UNARY_NARROW(select0ql,"vmovn.i64",0xf3ba0200, "xtn", 0x0ea12800, 1)
UNARY_NARROW(select0lw,"vmovn.i32",0xf3b60200, "xtn", 0x0e612800, 2)
UNARY_NARROW(select0wb,"vmovn.i16",0xf3b20200, "xtn", 0x0e212800, 3)
BINARY(addf,"vadd.f32",0xf2000d00, "fadd", 0x0e20d400, 0)
BINARY(subf,"vsub.f32",0xf2200d00, "fsub", 0x0ea0d400, 0)
BINARY(mulf,"vmul.f32",0xf3000d10, "fmul", 0x2e20dc00, 0)
BINARY(maxf,"vmax.f32",0xf2000f00, "fmax", 0x0e20f400, 0)
BINARY(minf,"vmin.f32",0xf2200f00, "fmin", 0x0ea0f400, 0)
BINARY(cmpeqf,"vceq.f32",0xf2000e00, "fcmeq", 0x5e20e400, 0)
/* BINARY_R(cmpltf,"vclt.f32",0xf3200e00, "fcmlt", 0x5ef8e800, 1) */
/* BINARY_R(cmplef,"vcle.f32",0xf3000e00, "fcmle", 0x7ef8d800, 1) */
UNARY(convfl,"vcvt.s32.f32",0xf3bb0700, "fcvtzs", 0x0ea1b800, 0)
UNARY(convlf,"vcvt.f32.s32",0xf3bb0600, "scvtf", 0x0e21d800, 0)
#define UNARY_VFP(opcode,insn_name,code,insn_name64,code64,vec_shift) \
static void \
orc_neon_rule_ ## opcode (OrcCompiler *p, void *user, OrcInstruction *insn) \
{ \
if (p->is_64bit) { \
if (insn_name64) { \
orc_neon64_emit_unary (p, insn_name64, code64, \
p->vars[insn->dest_args[0]], \
p->vars[insn->src_args[0]], vec_shift - 1); \
} else { \
ORC_COMPILER_ERROR(p, "not supported in AArch64 yet [%s %x]", (insn_name64), (code64)); \
} \
} else { \
orc_neon_emit_unary (p, insn_name, code, \
p->vars[insn->dest_args[0]].alloc, \
p->vars[insn->src_args[0]].alloc); \
if (p->insn_shift == vec_shift + 1) { \
orc_neon_emit_unary (p, insn_name, code, \
p->vars[insn->dest_args[0]].alloc + 1, \
p->vars[insn->src_args[0]].alloc + 1); \
} else { \
ORC_COMPILER_ERROR(p, "shift too large"); \
} \
} \
}
#define BINARY_VFP(opcode,insn_name,code,insn_name64,code64,vec_shift) \
static void \
orc_neon_rule_ ## opcode (OrcCompiler *p, void *user, OrcInstruction *insn) \
{ \
if (p->is_64bit) { \
if (insn_name64) { \
orc_neon64_emit_binary (p, insn_name64, code64, \
p->vars[insn->dest_args[0]], \
p->vars[insn->src_args[0]], \
p->vars[insn->src_args[1]], vec_shift - 1); \
} else { \
ORC_COMPILER_ERROR(p, "not supported in AArch64 yet [%s %x]", (insn_name64), (code64)); \
} \
} else { \
orc_neon_emit_binary (p, insn_name, code, \
p->vars[insn->dest_args[0]].alloc, \
p->vars[insn->src_args[0]].alloc, \
p->vars[insn->src_args[1]].alloc); \
if (p->insn_shift == vec_shift + 1) { \
orc_neon_emit_binary (p, insn_name, code, \
p->vars[insn->dest_args[0]].alloc+1, \
p->vars[insn->src_args[0]].alloc+1, \
p->vars[insn->src_args[1]].alloc+1); \
} else if (p->insn_shift > vec_shift + 1) { \
ORC_COMPILER_ERROR(p, "shift too large"); \
} \
} \
}
BINARY_VFP(addd,"vadd.f64",0xee300b00, "fadd", 0x4e60d400, 0)
BINARY_VFP(subd,"vsub.f64",0xee300b40, "fsub", 0x4ee0d400, 0)
BINARY_VFP(muld,"vmul.f64",0xee200b00, "fmul", 0x6e60dc00, 0)
BINARY_VFP(divd,"vdiv.f64",0xee800b00, "fdiv", 0x6e60fc00, 0)
UNARY_VFP(sqrtd,"vsqrt.f64",0xeeb10b00, "fsqrt", 0x6ee1f800, 0)
/* BINARY_VFP(cmpeqd,"vcmpe.f64",0xee000000, NULL, 0, 0) */
UNARY_VFP(convdf,"vcvt.f64.f32",0xee200b00, "fcvtzs", 0x4ee1b800, 0)
UNARY_VFP(convfd,"vcvt.f32.f64",0xee200b00, "scvtf", 0x4e61d800, 0)
#if 1
#define NUM_ITERS_DIVF 2
static void
orc_neon_rule_divf (OrcCompiler *p, void *user, OrcInstruction *insn)
{
int vec_shift = 1;
if (p->is_64bit) {
OrcVariable tmpreg = { .alloc = p->tmpreg, .size = p->vars[insn->src_args[1]].size };
OrcVariable tmpreg2 = { .alloc = p->tmpreg2, .size = p->vars[insn->src_args[1]].size };
int i;
orc_neon64_emit_unary (p, "frecpe", 0x0ea1d800,
tmpreg, p->vars[insn->src_args[1]],
p->insn_shift);
for(i = 0; i < NUM_ITERS_DIVF; i++) {
orc_neon64_emit_binary (p, "frecps", 0x0e20fc00,
tmpreg2, /* correction factor */
tmpreg, /* the last estimate */
p->vars[insn->src_args[1]], /* the original number */
p->insn_shift);
orc_neon64_emit_binary (p, "fmul", 0x2e20dc00,
tmpreg, /* revised estimate */
tmpreg, /* last estimate */
tmpreg2, /* correction factor */
p->insn_shift);
}
orc_neon64_emit_binary (p, "fmul", 0x2e20dc00,
p->vars[insn->dest_args[0]],
p->vars[insn->src_args[0]],
tmpreg, p->insn_shift);
} else {
if (p->insn_shift <= vec_shift) {
int i;
orc_neon_emit_unary (p, "vrecpe.f32", 0xf3bb0500,
p->tmpreg,
p->vars[insn->src_args[1]].alloc);
for(i = 0; i < NUM_ITERS_DIVF; i++) {
orc_neon_emit_binary (p, "vrecps.f32", 0xf2000f10,
p->tmpreg2, /* correction factor */
p->tmpreg, /* the last estimate */
p->vars[insn->src_args[1]].alloc); /* the original number */
orc_neon_emit_binary (p, "vmul.f32", 0xf3000d10,
p->tmpreg, /* revised estimate */
p->tmpreg, /* last estimate */
p->tmpreg2); /* correction factor */
}
orc_neon_emit_binary (p, "vmul.f32", 0xf3000d10,
p->vars[insn->dest_args[0]].alloc,
p->vars[insn->src_args[0]].alloc,
p->tmpreg);
} else if (p->insn_shift == vec_shift + 1) {
int i;
orc_neon_emit_unary_quad (p, "vrecpe.f32", 0xf3bb0500,
p->tmpreg,
p->vars[insn->src_args[1]].alloc);
for(i = 0; i < NUM_ITERS_DIVF; i++) {
orc_neon_emit_binary_quad (p, "vrecps.f32", 0xf2000f10,
p->tmpreg2, /* correction factor */
p->tmpreg, /* the last estimate */
p->vars[insn->src_args[1]].alloc); /* the original number */
orc_neon_emit_binary_quad (p, "vmul.f32", 0xf3000d10,
p->tmpreg, /* revised estimate */
p->tmpreg, /* last estimate */
p->tmpreg2); /* correction factor */
}
orc_neon_emit_binary_quad (p, "vmul.f32", 0xf3000d10,
p->vars[insn->dest_args[0]].alloc,
p->vars[insn->src_args[0]].alloc,
p->tmpreg);
} else {
ORC_COMPILER_ERROR(p, "shift too large");
}
}
}
#endif
#if 1
#define NUM_ITERS_SQRTF 2
static void
orc_neon_rule_sqrtf (OrcCompiler *p, void *user, OrcInstruction *insn)
{
int vec_shift = 1;
if (p->is_64bit) {
OrcVariable tmpreg = { .alloc = p->tmpreg, .size = p->vars[insn->src_args[0]].size };
OrcVariable tmpreg2 = { .alloc = p->tmpreg2, .size = p->vars[insn->src_args[0]].size };
int i;
orc_neon64_emit_unary (p, "frsqrte", 0x2ea1d800,
tmpreg, p->vars[insn->src_args[0]],
p->insn_shift);
for(i = 0; i < NUM_ITERS_SQRTF; i++) {
orc_neon64_emit_binary (p, "fmul", 0x2e20dc00,
tmpreg2, tmpreg, p->vars[insn->src_args[0]],
p->insn_shift);
orc_neon64_emit_binary (p, "frsqrts", 0x0ea0fc00,
tmpreg2, tmpreg, tmpreg2, p->insn_shift);
orc_neon64_emit_binary (p, "fmul", 0x2e20dc00,
tmpreg, tmpreg, tmpreg2,
p->insn_shift);
}
orc_neon64_emit_unary (p, "frecpe", 0x0ea1d800,
p->vars[insn->dest_args[0]], tmpreg,
p->insn_shift);
for(i = 0; i < NUM_ITERS_DIVF; i++) {
orc_neon64_emit_binary (p, "frecps", 0x0e20fc00,
tmpreg2, /* correction factor */
p->vars[insn->dest_args[0]], /* the last estimate */
tmpreg, /* the original number */
p->insn_shift);
orc_neon64_emit_binary (p, "fmul", 0x2e20dc00,
p->vars[insn->dest_args[0]], /* revised estimate */
p->vars[insn->dest_args[0]], /* last estimate */
tmpreg2, /* correction factor */
p->insn_shift);
}
} else {
if (p->insn_shift <= vec_shift) {
int i;
orc_neon_emit_unary (p, "vrsqrte.f32", 0xf3bb0580,
p->tmpreg,
p->vars[insn->src_args[0]].alloc);
for(i = 0; i < NUM_ITERS_SQRTF; i++) {
orc_neon_emit_binary (p, "vmul.f32", 0xf3000d10,
p->tmpreg2,
p->tmpreg,
p->vars[insn->src_args[0]].alloc);
orc_neon_emit_binary (p, "vrsqrts.f32", 0xf2200f10,
p->tmpreg2,
p->tmpreg,
p->tmpreg2);
orc_neon_emit_binary (p, "vmul.f32", 0xf3000d10,
p->tmpreg,
p->tmpreg,
p->tmpreg2);
}
orc_neon_emit_unary(p, "vrecpe.f32", 0xf3bb0500,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg);
for(i=0; i < NUM_ITERS_DIVF; i++) {
orc_neon_emit_binary (p, "vrecps.f32", 0xf2000f10,
p->tmpreg2, /* correction factor */
p->vars[insn->dest_args[0]].alloc, /* the last estimate */
p->tmpreg); /* the original number */
orc_neon_emit_binary (p, "vmul.f32", 0xf3000d10,
p->vars[insn->dest_args[0]].alloc, /* revised estimate */
p->vars[insn->dest_args[0]].alloc, /* last estimate */
p->tmpreg2); /* correction factor */
}
} else if (p->insn_shift == vec_shift + 1) {
int i;
orc_neon_emit_unary_quad (p, "vrsqrte.f32", 0xf3bb0580,
p->tmpreg,
p->vars[insn->src_args[0]].alloc);
for(i = 0; i < NUM_ITERS_SQRTF; i++) {
orc_neon_emit_binary_quad (p, "vmul.f32", 0xf3000d10,
p->tmpreg2,
p->tmpreg,
p->vars[insn->src_args[0]].alloc);
orc_neon_emit_binary_quad (p, "vrsqrts.f32", 0xf2200f10,
p->tmpreg2,
p->tmpreg,
p->tmpreg2);
orc_neon_emit_binary_quad (p, "vmul.f32", 0xf3000d10,
p->tmpreg,
p->tmpreg,
p->tmpreg2);
}
orc_neon_emit_unary_quad(p, "vrecpe.f32", 0xf3bb0500,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg);
for(i=0; i < NUM_ITERS_DIVF; i++) {
orc_neon_emit_binary_quad (p, "vrecps.f32", 0xf2000f10,
p->tmpreg2, /* correction factor */
p->vars[insn->dest_args[0]].alloc, /* the last estimate */
p->tmpreg); /* the original number */
orc_neon_emit_binary_quad (p, "vmul.f32", 0xf3000d10,
p->vars[insn->dest_args[0]].alloc, /* revised estimate */
p->vars[insn->dest_args[0]].alloc, /* last estimate */
p->tmpreg2); /* correction factor */
}
} else {
ORC_COMPILER_ERROR(p, "shift too large");
}
}
}
#endif
static void
orc_neon_rule_accw (OrcCompiler *p, void *user, OrcInstruction *insn)
{
OrcVariable tmpreg = { .alloc = p->tmpreg, .size = p->vars[insn->src_args[0]].size };
unsigned int code;
if (p->insn_shift < 2) {
if (p->is_64bit) {
orc_neon64_emit_unary (p, "shl",
0x0f405400 | (48 << 16),
tmpreg, p->vars[insn->src_args[0]],
p->insn_shift - 1);
orc_neon64_emit_binary (p, "add", 0x0ee08400,
p->vars[insn->dest_args[0]],
p->vars[insn->dest_args[0]],
tmpreg, p->insn_shift - 1);
} else {
ORC_ASM_CODE(p," vshl.i64 %s, %s, #%d\n",
orc_neon_reg_name (p->tmpreg),
orc_neon_reg_name (p->vars[insn->src_args[0]].alloc), 48);
code = NEON_BINARY(0xf2a00590, p->tmpreg, 0,
p->vars[insn->src_args[0]].alloc);
code |= (48) << 16;
orc_arm_emit (p, code);
orc_neon_emit_binary (p, "vadd.i16", 0xf2100800,
p->vars[insn->dest_args[0]].alloc,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg);
}
} else {
if (p->is_64bit) {
orc_neon64_emit_binary (p, "add", 0x0e608400,
p->vars[insn->dest_args[0]],
p->vars[insn->dest_args[0]],
p->vars[insn->src_args[0]], p->insn_shift);
} else {
orc_neon_emit_binary (p, "vadd.i16", 0xf2100800,
p->vars[insn->dest_args[0]].alloc,
p->vars[insn->dest_args[0]].alloc,
p->vars[insn->src_args[0]].alloc);
}
}
}
static void
orc_neon_rule_accl (OrcCompiler *p, void *user, OrcInstruction *insn)
{
OrcVariable tmpreg = { .alloc = p->tmpreg, .size = p->vars[insn->src_args[0]].size };
unsigned int code;
if (p->insn_shift < 1) {
if (p->is_64bit) {
orc_neon64_emit_unary (p, "shl",
0x0f405400 | (32 << 16),
tmpreg, p->vars[insn->src_args[0]],
p->insn_shift - 1);
orc_neon64_emit_binary (p, "add", 0x0ee08400,
p->vars[insn->dest_args[0]],
p->vars[insn->dest_args[0]],
tmpreg, p->insn_shift - 1);
} else {
ORC_ASM_CODE(p," vshl.i64 %s, %s, #%d\n",
orc_neon_reg_name (p->tmpreg),
orc_neon_reg_name (p->vars[insn->src_args[0]].alloc), 32);
code = NEON_BINARY(0xf2a00590, p->tmpreg, 0,
p->vars[insn->src_args[0]].alloc);
code |= (32) << 16;
orc_arm_emit (p, code);
orc_neon_emit_binary (p, "vadd.i32", 0xf2200800,
p->vars[insn->dest_args[0]].alloc,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg);
}
} else {
if (p->is_64bit) {
orc_neon64_emit_binary (p, "add", 0x0ea08400,
p->vars[insn->dest_args[0]],
p->vars[insn->dest_args[0]],
p->vars[insn->src_args[0]], p->insn_shift);
} else {
orc_neon_emit_binary (p, "vadd.i32", 0xf2200800,
p->vars[insn->dest_args[0]].alloc,
p->vars[insn->dest_args[0]].alloc,
p->vars[insn->src_args[0]].alloc);
}
}
}
static void
orc_neon_rule_select1wb (OrcCompiler *p, void *user, OrcInstruction *insn)
{
unsigned int code;
if (p->is_64bit) {
ORC_ASM_CODE(p," shrn %s, %s, #%d\n",
orc_neon64_reg_name_vector (p->vars[insn->dest_args[0]].alloc, 8, 0),
orc_neon64_reg_name_vector (p->vars[insn->src_args[0]].alloc, 8, 1), 8);
orc_neon64_emit_unary (p, "shrn", 0x0f088400,
p->vars[insn->dest_args[0]],
p->vars[insn->src_args[0]], p->insn_shift);
} else {
ORC_ASM_CODE(p," vshrn.i16 %s, %s, #%d\n",
orc_neon_reg_name (p->vars[insn->dest_args[0]].alloc),
orc_neon_reg_name_quad (p->vars[insn->src_args[0]].alloc), 8);
code = NEON_BINARY (0xf2880810,
p->vars[insn->dest_args[0]].alloc,
0, p->vars[insn->src_args[0]].alloc);
orc_arm_emit (p, code);
}
}
static void
orc_neon_rule_select1lw (OrcCompiler *p, void *user, OrcInstruction *insn)
{
unsigned int code;
if (p->is_64bit) {
ORC_ASM_CODE(p," shrn %s, %s, #%d\n",
orc_neon64_reg_name_vector (p->vars[insn->dest_args[0]].alloc, 8, 0),
orc_neon64_reg_name_vector (p->vars[insn->src_args[0]].alloc, 8, 1), 16);
orc_neon64_emit_unary (p, "shrn", 0x0f108400,
p->vars[insn->dest_args[0]],
p->vars[insn->src_args[0]], p->insn_shift);
} else {
ORC_ASM_CODE(p," vshrn.i32 %s, %s, #%d\n",
orc_neon_reg_name (p->vars[insn->dest_args[0]].alloc),
orc_neon_reg_name_quad (p->vars[insn->src_args[0]].alloc), 16);
code = NEON_BINARY (0xf2900810,
p->vars[insn->dest_args[0]].alloc,
0, p->vars[insn->src_args[0]].alloc);
orc_arm_emit (p, code);
}
}
static void
orc_neon_rule_select1ql (OrcCompiler *p, void *user, OrcInstruction *insn)
{
unsigned int code;
if (p->is_64bit) {
ORC_ASM_CODE(p," shrn %s, %s, #%d\n",
orc_neon64_reg_name_vector (p->vars[insn->dest_args[0]].alloc, 8, 0),
orc_neon64_reg_name_vector (p->vars[insn->src_args[0]].alloc, 8, 1), 32);
orc_neon64_emit_unary (p, "shrn", 0x0f208400,
p->vars[insn->dest_args[0]],
p->vars[insn->src_args[0]], p->insn_shift);
} else {
ORC_ASM_CODE(p," vtrn.32 %s, %s\n",
orc_neon_reg_name (p->vars[insn->dest_args[0]].alloc),
orc_neon_reg_name_quad (p->vars[insn->src_args[0]].alloc));
code = NEON_BINARY (0xf2a00810,
p->vars[insn->dest_args[0]].alloc,
0, p->vars[insn->src_args[0]].alloc);
orc_arm_emit (p, code);
}
}
static void
orc_neon_rule_convhwb (OrcCompiler *p, void *user, OrcInstruction *insn)
{
unsigned int code;
if (p->is_64bit) {
ORC_ASM_CODE(p," shrn %s, %s, #%d\n",
orc_neon64_reg_name_vector (p->vars[insn->dest_args[0]].alloc, 8, 0),
orc_neon64_reg_name_vector (p->vars[insn->src_args[0]].alloc, 8, 1), 8);
orc_neon64_emit_unary (p, "shrn", 0x0f088400,
p->vars[insn->dest_args[0]],
p->vars[insn->src_args[0]], p->insn_shift);
} else {
ORC_ASM_CODE(p," vshrn.i16 %s, %s, #%d\n",
orc_neon_reg_name (p->vars[insn->dest_args[0]].alloc),
orc_neon_reg_name_quad (p->vars[insn->src_args[0]].alloc), 8);
code = NEON_BINARY (0xf2880810,
p->vars[insn->dest_args[0]].alloc,
0, p->vars[insn->src_args[0]].alloc);
orc_arm_emit (p, code);
}
}
static void
orc_neon_rule_convhlw (OrcCompiler *p, void *user, OrcInstruction *insn)
{
unsigned int code;
if (p->is_64bit) {
ORC_ASM_CODE(p," shrn %s, %s\n",
orc_neon64_reg_name_vector (p->vars[insn->dest_args[0]].alloc, 8, 0),
orc_neon64_reg_name_vector (p->vars[insn->src_args[0]].alloc, 8, 1));
orc_neon64_emit_unary (p, "shrn", 0x0f108400,
p->vars[insn->dest_args[0]],
p->vars[insn->src_args[0]], p->insn_shift);
} else {
ORC_ASM_CODE(p," vshrn.i32 %s, %s, #%d\n",
orc_neon_reg_name (p->vars[insn->dest_args[0]].alloc),
orc_neon_reg_name_quad (p->vars[insn->src_args[0]].alloc), 16);
code = NEON_BINARY (0xf2900810,
p->vars[insn->dest_args[0]].alloc,
0, p->vars[insn->src_args[0]].alloc);
orc_arm_emit (p, code);
}
}
static void
orc_neon_rule_mergebw (OrcCompiler *p, void *user, OrcInstruction *insn)
{
OrcVariable tmpreg = { .alloc = p->tmpreg, .size = p->vars[insn->src_args[1]].size };
if (p->insn_shift <= 2) {
if (p->is_64bit) {
orc_neon64_emit_binary (p, "zip1", 0x0e003800,
p->vars[insn->dest_args[0]],
p->vars[insn->src_args[0]],
p->vars[insn->src_args[1]], p->insn_shift);
} else {
if (p->vars[insn->dest_args[0]].alloc != p->vars[insn->src_args[0]].alloc) {
orc_neon_emit_mov (p, p->vars[insn->dest_args[0]],
p->vars[insn->src_args[0]]);
}
if (p->vars[insn->src_args[1]].last_use != p->insn_index ||
p->vars[insn->src_args[1]].alloc == p->vars[insn->dest_args[0]].alloc) {
orc_neon_emit_mov (p, tmpreg, p->vars[insn->src_args[1]]);
orc_neon_emit_unary (p, "vzip.8", 0xf3b20180,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg);
} else {
orc_neon_emit_unary (p, "vzip.8", 0xf3b20180,
p->vars[insn->dest_args[0]].alloc,
p->vars[insn->src_args[1]].alloc);
}
}
} else {
if (p->is_64bit) {
orc_neon64_emit_binary (p, "zip1", 0x0e003800,
p->vars[insn->dest_args[0]],
p->vars[insn->src_args[0]],
p->vars[insn->src_args[1]], p->insn_shift - 1);
} else {
if (p->vars[insn->dest_args[0]].alloc != p->vars[insn->src_args[0]].alloc) {
orc_neon_emit_mov_quad (p, p->vars[insn->dest_args[0]],
p->vars[insn->src_args[0]]);
}
orc_neon_emit_mov_quad (p, tmpreg, p->vars[insn->src_args[1]]);
orc_neon_emit_unary_quad (p, "vzip.8", 0xf3b20180,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg);
}
}
}
static void
orc_neon_rule_mergewl (OrcCompiler *p, void *user, OrcInstruction *insn)
{
OrcVariable tmpreg = { .alloc = p->tmpreg, .size = p->vars[insn->src_args[1]].size };
if (p->insn_shift <= 1) {
if (p->is_64bit) {
orc_neon64_emit_binary (p, "zip1", 0x0e403800,
p->vars[insn->dest_args[0]],
p->vars[insn->src_args[0]],
p->vars[insn->src_args[1]], p->insn_shift);
} else {
if (p->vars[insn->dest_args[0]].alloc != p->vars[insn->src_args[0]].alloc) {
orc_neon_emit_mov (p, p->vars[insn->dest_args[0]],
p->vars[insn->src_args[0]]);
}
if (p->vars[insn->src_args[1]].last_use != p->insn_index ||
p->vars[insn->src_args[1]].alloc == p->vars[insn->dest_args[0]].alloc) {
orc_neon_emit_mov (p, tmpreg, p->vars[insn->src_args[1]]);
orc_neon_emit_unary (p, "vzip.16", 0xf3b60180,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg);
} else {
orc_neon_emit_unary (p, "vzip.16", 0xf3b60180,
p->vars[insn->dest_args[0]].alloc,
p->vars[insn->src_args[1]].alloc);
}
}
} else {
if (p->is_64bit) {
orc_neon64_emit_binary (p, "zip1", 0x0e403800,
p->vars[insn->dest_args[0]],
p->vars[insn->src_args[0]],
p->vars[insn->src_args[1]], p->insn_shift - 1);
} else {
if (p->vars[insn->dest_args[0]].alloc != p->vars[insn->src_args[0]].alloc) {
orc_neon_emit_mov_quad (p, p->vars[insn->dest_args[0]],
p->vars[insn->src_args[0]]);
}
if (p->vars[insn->src_args[1]].last_use != p->insn_index ||
p->vars[insn->src_args[1]].alloc == p->vars[insn->dest_args[0]].alloc) {
orc_neon_emit_mov_quad (p, tmpreg, p->vars[insn->src_args[1]]);
orc_neon_emit_unary_quad (p, "vzip.16", 0xf3b60180,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg);
} else {
orc_neon_emit_unary_quad (p, "vzip.16", 0xf3b60180,
p->vars[insn->dest_args[0]].alloc,
p->vars[insn->src_args[1]].alloc);
}
}
}
}
static void
orc_neon_rule_mergelq (OrcCompiler *p, void *user, OrcInstruction *insn)
{
OrcVariable tmpreg = { .alloc = p->tmpreg, .size = p->vars[insn->src_args[1]].size };
if (p->insn_shift <= 0) {
if (p->is_64bit) {
orc_neon64_emit_binary (p, "trn1", 0x0e802800,
p->vars[insn->dest_args[0]],
p->vars[insn->src_args[0]],
p->vars[insn->src_args[1]], p->insn_shift);
} else {
if (p->vars[insn->dest_args[0]].alloc != p->vars[insn->src_args[0]].alloc) {
orc_neon_emit_mov (p, p->vars[insn->dest_args[0]],
p->vars[insn->src_args[0]]);
}
if (p->vars[insn->src_args[1]].last_use != p->insn_index ||
p->vars[insn->src_args[1]].alloc == p->vars[insn->dest_args[0]].alloc) {
orc_neon_emit_mov (p, tmpreg, p->vars[insn->src_args[1]]);
orc_neon_emit_unary (p, "vtrn.32", 0xf3ba0080,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg);
} else {
orc_neon_emit_unary (p, "vtrn.32", 0xf3ba0080,
p->vars[insn->dest_args[0]].alloc,
p->vars[insn->src_args[1]].alloc);
}
}
} else {
if (p->is_64bit) {
orc_neon64_emit_binary (p, "zip1", 0x0e803800,
p->vars[insn->dest_args[0]],
p->vars[insn->src_args[0]],
p->vars[insn->src_args[1]], p->insn_shift - 1);
} else {
if (p->vars[insn->dest_args[0]].alloc != p->vars[insn->src_args[0]].alloc) {
orc_neon_emit_mov_quad (p, p->vars[insn->dest_args[0]],
p->vars[insn->src_args[0]]);
}
if (p->vars[insn->src_args[1]].last_use != p->insn_index ||
p->vars[insn->src_args[1]].alloc == p->vars[insn->dest_args[0]].alloc) {
orc_neon_emit_mov_quad (p, tmpreg, p->vars[insn->src_args[1]]);
orc_neon_emit_unary_quad (p, "vzip.32", 0xf3ba0180,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg);
} else {
orc_neon_emit_unary_quad (p, "vzip.32", 0xf3ba0180,
p->vars[insn->dest_args[0]].alloc,
p->vars[insn->src_args[1]].alloc);
}
}
}
}
static void
orc_neon_rule_splatbw (OrcCompiler *p, void *user, OrcInstruction *insn)
{
OrcVariable tmpreg = { .alloc = p->tmpreg, .size = p->vars[insn->dest_args[0]].size };
if (p->is_64bit) {
orc_neon64_emit_binary (p, "zip1", 0x0e003800,
p->vars[insn->dest_args[0]],
p->vars[insn->src_args[0]],
p->vars[insn->src_args[0]], p->insn_shift - (p->insn_shift > 2));
} else {
if (p->insn_shift <= 2) {
if (p->vars[insn->dest_args[0]].alloc != p->vars[insn->src_args[0]].alloc) {
orc_neon_emit_mov (p, p->vars[insn->dest_args[0]],
p->vars[insn->src_args[0]]);
}
orc_neon_emit_mov (p, tmpreg, p->vars[insn->dest_args[0]]);
orc_neon_emit_unary (p, "vzip.8", 0xf3b20180,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg);
} else {
if (p->vars[insn->dest_args[0]].alloc != p->vars[insn->src_args[0]].alloc) {
orc_neon_emit_mov_quad (p, p->vars[insn->dest_args[0]],
p->vars[insn->src_args[0]]);
}
orc_neon_emit_mov_quad (p, tmpreg, p->vars[insn->dest_args[0]]);
orc_neon_emit_unary_quad (p, "vzip.8", 0xf3b20180,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg);
}
}
}
static void
orc_neon_rule_splatbl (OrcCompiler *p, void *user, OrcInstruction *insn)
{
OrcVariable tmpreg = { .alloc = p->tmpreg, .size = p->vars[insn->dest_args[0]].size };
if (p->is_64bit) {
orc_neon64_emit_binary (p, "zip1", 0x0e003800,
tmpreg,
p->vars[insn->src_args[0]],
p->vars[insn->src_args[0]], p->insn_shift - (p->insn_shift > 1));
orc_neon64_emit_binary (p, "zip1", 0x0e403800,
p->vars[insn->dest_args[0]],
tmpreg,
tmpreg, p->insn_shift - (p->insn_shift > 1));
} else {
if (p->insn_shift <= 1) {
if (p->vars[insn->dest_args[0]].alloc != p->vars[insn->src_args[0]].alloc) {
orc_neon_emit_mov (p, p->vars[insn->dest_args[0]],
p->vars[insn->src_args[0]]);
}
orc_neon_emit_mov (p, tmpreg, p->vars[insn->dest_args[0]]);
orc_neon_emit_unary (p, "vzip.8", 0xf3b20180,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg);
orc_neon_emit_mov (p, tmpreg, p->vars[insn->dest_args[0]]);
orc_neon_emit_unary (p, "vzip.16", 0xf3b60180,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg);
} else {
if (p->vars[insn->dest_args[0]].alloc != p->vars[insn->src_args[0]].alloc) {
orc_neon_emit_mov_quad (p, p->vars[insn->dest_args[0]],
p->vars[insn->src_args[0]]);
}
orc_neon_emit_mov (p, tmpreg, p->vars[insn->dest_args[0]]);
orc_neon_emit_unary_quad (p, "vzip.8", 0xf3b20180,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg);
orc_neon_emit_mov (p, tmpreg, p->vars[insn->dest_args[0]]);
orc_neon_emit_unary_quad (p, "vzip.16", 0xf3b60180,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg);
}
}
}
static void
orc_neon_rule_splatw3q (OrcCompiler *p, void *user, OrcInstruction *insn)
{
orc_uint32 code;
int offset = 0;
int label = 20;
if (p->is_64bit) {
OrcVariable tmpreg = { .alloc = p->tmpreg, .size = p->vars[insn->dest_args[0]].size };
orc_neon64_emit_binary (p, "trn2", 0x0e406800,
tmpreg,
p->vars[insn->src_args[0]],
p->vars[insn->src_args[0]], p->insn_shift - (p->insn_shift > 0));
orc_neon64_emit_binary (p, "trn2", 0x0e806800,
p->vars[insn->dest_args[0]],
tmpreg,
tmpreg, p->insn_shift - (p->insn_shift > 0));
} else {
orc_arm_add_fixup (p, label, 1);
ORC_ASM_CODE(p," vldr %s, .L%d+%d\n",
orc_neon_reg_name (p->tmpreg), label, offset);
code = 0xed9f0b00;
code |= (p->tmpreg&0xf) << 12;
code |= ((p->tmpreg>>4)&0x1) << 22;
code |= ((offset - 8) >> 2)&0xff;
orc_arm_emit (p, code);
ORC_ASM_CODE(p," vtbl.8 %s, { %s, %s }, %s\n",
orc_neon_reg_name (p->vars[insn->dest_args[0]].alloc),
orc_neon_reg_name (p->vars[insn->src_args[0]].alloc),
orc_neon_reg_name (p->vars[insn->src_args[0]].alloc + 1),
orc_neon_reg_name (p->tmpreg));
code = NEON_BINARY(0xf3b00900,
p->vars[insn->dest_args[0]].alloc,
p->vars[insn->src_args[0]].alloc,
p->tmpreg);
orc_arm_emit (p, code);
if (p->insn_shift > 0) {
ORC_ASM_CODE(p," vtbl.8 %s, { %s }, %s\n",
orc_neon_reg_name (p->vars[insn->dest_args[0]].alloc+1),
orc_neon_reg_name (p->vars[insn->src_args[0]].alloc+1),
orc_neon_reg_name (p->tmpreg));
code = NEON_BINARY(0xf3b00800,
p->vars[insn->dest_args[0]].alloc+1,
p->vars[insn->src_args[0]].alloc+1,
p->tmpreg);
orc_arm_emit (p, code);
}
}
}
static void
orc_neon_rule_accsadubl (OrcCompiler *p, void *user, OrcInstruction *insn)
{
OrcVariable tmpreg = { .alloc = p->tmpreg, .size = p->vars[insn->src_args[0]].size };
orc_uint32 x;
unsigned int code;
if (p->insn_shift < 2) {
if (p->is_64bit) {
orc_neon64_emit_binary (p, "uabdl", 0x2e207000,
tmpreg,
p->vars[insn->src_args[0]],
p->vars[insn->src_args[1]], p->insn_shift);
orc_neon64_emit_unary (p, "shl",
0x0f405400 | ((64 - (16<<p->insn_shift)) << 16),
tmpreg, tmpreg,
p->insn_shift - 1);
orc_neon64_emit_unary (p, "uadalp", 0x2e606800,
p->vars[insn->dest_args[0]],
tmpreg, p->insn_shift);
} else {
x = 0xf3800700;
ORC_ASM_CODE(p," vabdl.u8 %s, %s, %s\n",
orc_neon_reg_name_quad (p->tmpreg),
orc_neon_reg_name (p->vars[insn->src_args[0]].alloc),
orc_neon_reg_name (p->vars[insn->src_args[1]].alloc));
x |= (p->tmpreg&0xf)<<12;
x |= ((p->tmpreg>>4)&0x1)<<22;
x |= (p->vars[insn->src_args[0]].alloc&0xf)<<16;
x |= ((p->vars[insn->src_args[0]].alloc>>4)&0x1)<<7;
x |= (p->vars[insn->src_args[1]].alloc&0xf)<<0;
x |= ((p->vars[insn->src_args[1]].alloc>>4)&0x1)<<5;
orc_arm_emit (p, x);
ORC_ASM_CODE(p," vshl.i64 %s, %s, #%d\n",
orc_neon_reg_name (p->tmpreg),
orc_neon_reg_name (p->tmpreg), 64 - (16<<p->insn_shift));
code = NEON_BINARY(0xf2a00590, p->tmpreg, 0, p->tmpreg);
code |= (64 - (16<<p->insn_shift)) << 16;
orc_arm_emit (p, code);
orc_neon_emit_unary (p, "vpadal.u16", 0xf3b40680,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg);
}
} else {
if (p->is_64bit) {
orc_neon64_emit_binary (p, "uabdl", 0x2e207000,
tmpreg,
p->vars[insn->src_args[0]],
p->vars[insn->src_args[1]], p->insn_shift);
orc_neon64_emit_unary (p, "uadalp", 0x2e606800,
p->vars[insn->dest_args[0]],
tmpreg, p->insn_shift);
} else {
x = 0xf3800700;
ORC_ASM_CODE(p," vabdl.u8 %s, %s, %s\n",
orc_neon_reg_name_quad (p->tmpreg),
orc_neon_reg_name (p->vars[insn->src_args[0]].alloc),
orc_neon_reg_name (p->vars[insn->src_args[1]].alloc));
x |= (p->tmpreg&0xf)<<12;
x |= ((p->tmpreg>>4)&0x1)<<22;
x |= (p->vars[insn->src_args[0]].alloc&0xf)<<16;
x |= ((p->vars[insn->src_args[0]].alloc>>4)&0x1)<<7;
x |= (p->vars[insn->src_args[1]].alloc&0xf)<<0;
x |= ((p->vars[insn->src_args[1]].alloc>>4)&0x1)<<5;
orc_arm_emit (p, x);
orc_neon_emit_unary (p, "vpadal.u16", 0xf3b40680,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg);
}
}
}
static void
orc_neon_rule_signw (OrcCompiler *p, void *user, OrcInstruction *insn)
{
OrcVariable tmpreg = { .alloc = p->tmpreg, .size = p->vars[insn->src_args[0]].size };
/* slow */
orc_neon_emit_loadiw (p, &tmpreg, 1);
if (p->insn_shift < 3) {
if (p->is_64bit)
orc_neon64_emit_binary (p, "smin", 0x0e606c00,
p->vars[insn->dest_args[0]],
tmpreg,
p->vars[insn->src_args[0]], p->insn_shift);
else
orc_neon_emit_binary (p, "vmin.s16", 0xf2100610,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg,
p->vars[insn->src_args[0]].alloc);
} else {
if (p->is_64bit)
orc_neon64_emit_binary (p, "smin", 0x0e606c00,
p->vars[insn->dest_args[0]],
tmpreg,
p->vars[insn->src_args[0]], p->insn_shift - 1);
else
orc_neon_emit_binary_quad (p, "vmin.s16", 0xf2100610,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg,
p->vars[insn->src_args[0]].alloc);
}
orc_neon_emit_loadiw (p, &tmpreg, -1);
if (p->insn_shift < 3) {
if (p->is_64bit)
orc_neon64_emit_binary (p, "smax", 0x0e606400,
p->vars[insn->dest_args[0]],
tmpreg,
p->vars[insn->dest_args[0]], p->insn_shift);
else
orc_neon_emit_binary (p, "vmax.s16", 0xf2100600,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg,
p->vars[insn->dest_args[0]].alloc);
} else {
if (p->is_64bit)
orc_neon64_emit_binary (p, "smax", 0x0e606400,
p->vars[insn->dest_args[0]],
tmpreg,
p->vars[insn->dest_args[0]], p->insn_shift - 1);
else
orc_neon_emit_binary_quad (p, "vmax.s16", 0xf2100600,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg,
p->vars[insn->dest_args[0]].alloc);
}
}
static void
orc_neon_rule_signb (OrcCompiler *p, void *user, OrcInstruction *insn)
{
OrcVariable tmpreg = { .alloc = p->tmpreg, .size = p->vars[insn->src_args[0]].size };
/* slow */
orc_neon_emit_loadib (p, &tmpreg, 1);
if (p->insn_shift < 4) {
if (p->is_64bit)
orc_neon64_emit_binary (p, "smin", 0x0e206c00,
p->vars[insn->dest_args[0]],
tmpreg,
p->vars[insn->src_args[0]], p->insn_shift);
else
orc_neon_emit_binary (p, "vmin.s8", 0xf2000610,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg,
p->vars[insn->src_args[0]].alloc);
} else {
if (p->is_64bit)
orc_neon64_emit_binary (p, "smin", 0x0e206c00,
p->vars[insn->dest_args[0]],
tmpreg,
p->vars[insn->src_args[0]], p->insn_shift - 1);
else
orc_neon_emit_binary_quad (p, "vmin.s8", 0xf2000610,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg,
p->vars[insn->src_args[0]].alloc);
}
orc_neon_emit_loadib (p, &tmpreg, -1);
if (p->insn_shift < 4) {
if (p->is_64bit)
orc_neon64_emit_binary (p, "smax", 0x0e206400,
p->vars[insn->dest_args[0]],
tmpreg,
p->vars[insn->dest_args[0]], p->insn_shift);
else
orc_neon_emit_binary (p, "vmax.s8", 0xf2000600,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg,
p->vars[insn->dest_args[0]].alloc);
} else {
if (p->is_64bit)
orc_neon64_emit_binary (p, "smax", 0x0e206400,
p->vars[insn->dest_args[0]],
tmpreg,
p->vars[insn->dest_args[0]], p->insn_shift - 1);
else
orc_neon_emit_binary_quad (p, "vmax.s8", 0xf2000600,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg,
p->vars[insn->dest_args[0]].alloc);
}
}
static void
orc_neon_rule_signl (OrcCompiler *p, void *user, OrcInstruction *insn)
{
OrcVariable tmpreg = { .alloc = p->tmpreg, .size = p->vars[insn->src_args[0]].size };
/* slow */
orc_neon_emit_loadil (p, &tmpreg, 1);
if (p->insn_shift < 2) {
if (p->is_64bit)
orc_neon64_emit_binary (p, "smin", 0x0ea06c00,
p->vars[insn->dest_args[0]],
tmpreg,
p->vars[insn->src_args[0]], p->insn_shift);
else
orc_neon_emit_binary (p, "vmin.s32", 0xf2200610,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg,
p->vars[insn->src_args[0]].alloc);
} else {
if (p->is_64bit)
orc_neon64_emit_binary (p, "smin", 0x0ea06c00,
p->vars[insn->dest_args[0]],
tmpreg,
p->vars[insn->src_args[0]], p->insn_shift - 1);
else
orc_neon_emit_binary_quad (p, "vmin.s32", 0xf2200610,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg,
p->vars[insn->src_args[0]].alloc);
}
orc_neon_emit_loadil (p, &tmpreg, -1);
if (p->insn_shift < 2) {
if (p->is_64bit)
orc_neon64_emit_binary (p, "smax", 0x0ea06400,
p->vars[insn->dest_args[0]],
tmpreg,
p->vars[insn->dest_args[0]], p->insn_shift);
else
orc_neon_emit_binary (p, "vmax.s32", 0xf2200600,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg,
p->vars[insn->dest_args[0]].alloc);
} else {
if (p->is_64bit)
orc_neon64_emit_binary (p, "smax", 0x0ea06400,
p->vars[insn->dest_args[0]],
tmpreg,
p->vars[insn->dest_args[0]], p->insn_shift - 1);
else
orc_neon_emit_binary_quad (p, "vmax.s32", 0xf2200600,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg,
p->vars[insn->dest_args[0]].alloc);
}
}
static void
orc_neon_rule_mulhub (OrcCompiler *p, void *user, OrcInstruction *insn)
{
unsigned int code;
if (p->is_64bit) {
OrcVariable tmpreg1 = { .alloc = p->tmpreg, .size = p->vars[insn->dest_args[0]].size };
OrcVariable tmpreg2 = { .alloc = p->tmpreg2, .size = p->vars[insn->dest_args[0]].size };
orc_neon64_emit_binary (p, "umull", 0x2e20c000,
tmpreg1,
p->vars[insn->src_args[0]],
p->vars[insn->src_args[1]],
p->insn_shift);
if (p->insn_shift == 4) {
orc_neon64_emit_binary (p, "umull", 0x2e20c000,
tmpreg2,
p->vars[insn->src_args[0]],
p->vars[insn->src_args[1]],
p->insn_shift - 1);
}
/*
* WARNING:
* Be careful here, SHRN (without Q-bit set) will write bottom 64 bits
* of the $dest register with data and top 64 bits with zeroes! SHRN2
* (with Q-bit set) will write top 64 bits of $dest register with data
* and will retain bottom 64 bits content. If $dest==$src{1 or 2}, then
* using SHRN will lead to corruption of source data!
*/
orc_neon64_emit_unary (p, "shrn", 0x0f088400,
p->vars[insn->dest_args[0]],
tmpreg1, p->insn_shift);
if (p->insn_shift == 4) {
orc_neon64_emit_unary (p, "shrn", 0x0f088400,
p->vars[insn->dest_args[0]],
tmpreg2, p->insn_shift - 1);
}
} else {
orc_neon_emit_binary_long (p, "vmull.u8",0xf3800c00,
p->tmpreg,
p->vars[insn->src_args[0]].alloc,
p->vars[insn->src_args[1]].alloc);
ORC_ASM_CODE(p," vshrn.i16 %s, %s, #%d\n",
orc_neon_reg_name (p->vars[insn->dest_args[0]].alloc),
orc_neon_reg_name_quad (p->tmpreg), 8);
code = NEON_BINARY (0xf2880810,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg, 0);
orc_arm_emit (p, code);
if (p->insn_shift == 4) {
orc_neon_emit_binary_long (p, "vmull.u8",0xf3800c00,
p->tmpreg,
p->vars[insn->src_args[0]].alloc + 1,
p->vars[insn->src_args[1]].alloc + 1);
ORC_ASM_CODE(p," vshrn.i16 %s, %s, #%d\n",
orc_neon_reg_name (p->vars[insn->dest_args[0]].alloc + 1),
orc_neon_reg_name_quad (p->tmpreg), 8);
code = NEON_BINARY (0xf2880810,
p->vars[insn->dest_args[0]].alloc + 1,
p->tmpreg, 0);
orc_arm_emit (p, code);
}
}
}
static void
orc_neon_rule_mulhsb (OrcCompiler *p, void *user, OrcInstruction *insn)
{
unsigned int code;
if (p->is_64bit) {
OrcVariable tmpreg1 = { .alloc = p->tmpreg, .size = p->vars[insn->dest_args[0]].size };
OrcVariable tmpreg2 = { .alloc = p->tmpreg2, .size = p->vars[insn->dest_args[0]].size };
orc_neon64_emit_binary (p, "smull", 0x0e20c000,
tmpreg1,
p->vars[insn->src_args[0]],
p->vars[insn->src_args[1]],
p->insn_shift);
if (p->insn_shift == 4) {
orc_neon64_emit_binary (p, "smull", 0x0e20c000,
tmpreg2,
p->vars[insn->src_args[0]],
p->vars[insn->src_args[1]],
p->insn_shift - 1);
}
/*
* WARNING:
* Be careful here, SHRN (without Q-bit set) will write bottom 64 bits
* of the $dest register with data and top 64 bits with zeroes! SHRN2
* (with Q-bit set) will write top 64 bits of $dest register with data
* and will retain bottom 64 bits content. If $dest==$src{1 or 2}, then
* using SHRN will lead to corruption of source data!
*/
orc_neon64_emit_unary (p, "shrn", 0x0f088400,
p->vars[insn->dest_args[0]],
tmpreg1, p->insn_shift);
if (p->insn_shift == 4) {
orc_neon64_emit_unary (p, "shrn", 0x0f088400,
p->vars[insn->dest_args[0]],
tmpreg2, p->insn_shift - 1);
}
} else {
orc_neon_emit_binary_long (p, "vmull.s8",0xf2800c00,
p->tmpreg,
p->vars[insn->src_args[0]].alloc,
p->vars[insn->src_args[1]].alloc);
ORC_ASM_CODE(p," vshrn.i16 %s, %s, #%d\n",
orc_neon_reg_name (p->vars[insn->dest_args[0]].alloc),
orc_neon_reg_name_quad (p->tmpreg), 8);
code = NEON_BINARY (0xf2880810,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg, 0);
orc_arm_emit (p, code);
if (p->insn_shift == 4) {
orc_neon_emit_binary_long (p, "vmull.s8",0xf2800c00,
p->tmpreg,
p->vars[insn->src_args[0]].alloc + 1,
p->vars[insn->src_args[1]].alloc + 1);
ORC_ASM_CODE(p," vshrn.i16 %s, %s, #%d\n",
orc_neon_reg_name (p->vars[insn->dest_args[0]].alloc + 1),
orc_neon_reg_name_quad (p->tmpreg), 8);
code = NEON_BINARY (0xf2880810,
p->vars[insn->dest_args[0]].alloc + 1,
p->tmpreg, 0);
orc_arm_emit (p, code);
}
}
}
static void
orc_neon_rule_mulhuw (OrcCompiler *p, void *user, OrcInstruction *insn)
{
unsigned int code;
if (p->is_64bit) {
OrcVariable tmpreg1 = { .alloc = p->tmpreg, .size = p->vars[insn->dest_args[0]].size };
OrcVariable tmpreg2 = { .alloc = p->tmpreg2, .size = p->vars[insn->dest_args[0]].size };
orc_neon64_emit_binary (p, "umull", 0x2e60c000,
tmpreg1,
p->vars[insn->src_args[0]],
p->vars[insn->src_args[1]],
p->insn_shift);
if (p->insn_shift == 3) {
orc_neon64_emit_binary (p, "umull", 0x2e60c000,
tmpreg2,
p->vars[insn->src_args[0]],
p->vars[insn->src_args[1]],
p->insn_shift - 1);
}
/*
* WARNING:
* Be careful here, SHRN (without Q-bit set) will write bottom 64 bits
* of the $dest register with data and top 64 bits with zeroes! SHRN2
* (with Q-bit set) will write top 64 bits of $dest register with data
* and will retain bottom 64 bits content. If $dest==$src{1 or 2}, then
* using SHRN will lead to corruption of source data!
*/
orc_neon64_emit_unary (p, "shrn", 0x0f108400,
p->vars[insn->dest_args[0]],
tmpreg1, p->insn_shift);
if (p->insn_shift == 3) {
orc_neon64_emit_unary (p, "shrn", 0x0f108400,
p->vars[insn->dest_args[0]],
tmpreg2, p->insn_shift - 1);
}
} else {
orc_neon_emit_binary_long (p, "vmull.u16",0xf3900c00,
p->tmpreg,
p->vars[insn->src_args[0]].alloc,
p->vars[insn->src_args[1]].alloc);
ORC_ASM_CODE(p," vshrn.i32 %s, %s, #%d\n",
orc_neon_reg_name (p->vars[insn->dest_args[0]].alloc),
orc_neon_reg_name_quad (p->tmpreg), 16);
code = NEON_BINARY (0xf2900810,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg, 0);
orc_arm_emit (p, code);
if (p->insn_shift == 3) {
orc_neon_emit_binary_long (p, "vmull.u16",0xf3900c00,
p->tmpreg,
p->vars[insn->src_args[0]].alloc + 1,
p->vars[insn->src_args[1]].alloc + 1);
ORC_ASM_CODE(p," vshrn.i32 %s, %s, #%d\n",
orc_neon_reg_name (p->vars[insn->dest_args[0]].alloc + 1),
orc_neon_reg_name_quad (p->tmpreg), 16);
code = NEON_BINARY (0xf2900810,
p->vars[insn->dest_args[0]].alloc + 1,
p->tmpreg, 0);
orc_arm_emit (p, code);
}
}
}
static void
orc_neon_rule_mulhsw (OrcCompiler *p, void *user, OrcInstruction *insn)
{
unsigned int code;
if (p->is_64bit) {
OrcVariable tmpreg1 = { .alloc = p->tmpreg, .size = p->vars[insn->dest_args[0]].size };
OrcVariable tmpreg2 = { .alloc = p->tmpreg2, .size = p->vars[insn->dest_args[0]].size };
orc_neon64_emit_binary (p, "smull", 0x0e60c000,
tmpreg1,
p->vars[insn->src_args[0]],
p->vars[insn->src_args[1]],
p->insn_shift);
if (p->insn_shift == 3) {
orc_neon64_emit_binary (p, "smull", 0x0e60c000,
tmpreg2,
p->vars[insn->src_args[0]],
p->vars[insn->src_args[1]],
p->insn_shift - 1);
}
/*
* WARNING:
* Be careful here, SHRN (without Q-bit set) will write bottom 64 bits
* of the $dest register with data and top 64 bits with zeroes! SHRN2
* (with Q-bit set) will write top 64 bits of $dest register with data
* and will retain bottom 64 bits content. If $dest==$src{1 or 2}, then
* using SHRN will lead to corruption of source data!
*/
orc_neon64_emit_unary (p, "shrn", 0x0f108400,
p->vars[insn->dest_args[0]],
tmpreg1, p->insn_shift);
if (p->insn_shift == 3) {
orc_neon64_emit_unary (p, "shrn", 0x0f108400,
p->vars[insn->dest_args[0]],
tmpreg2, p->insn_shift - 1);
}
} else {
orc_neon_emit_binary_long (p, "vmull.s16",0xf2900c00,
p->tmpreg,
p->vars[insn->src_args[0]].alloc,
p->vars[insn->src_args[1]].alloc);
ORC_ASM_CODE(p," vshrn.i32 %s, %s, #%d\n",
orc_neon_reg_name (p->vars[insn->dest_args[0]].alloc),
orc_neon_reg_name_quad (p->tmpreg), 16);
code = NEON_BINARY (0xf2900810,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg, 0);
orc_arm_emit (p, code);
if (p->insn_shift == 3) {
orc_neon_emit_binary_long (p, "vmull.s16",0xf2900c00,
p->tmpreg,
p->vars[insn->src_args[0]].alloc + 1,
p->vars[insn->src_args[1]].alloc + 1);
ORC_ASM_CODE(p," vshrn.i32 %s, %s, #%d\n",
orc_neon_reg_name (p->vars[insn->dest_args[0]].alloc + 1),
orc_neon_reg_name_quad (p->tmpreg), 16);
code = NEON_BINARY (0xf2900810,
p->vars[insn->dest_args[0]].alloc + 1,
p->tmpreg, 0);
orc_arm_emit (p, code);
}
}
}
static void
orc_neon_rule_mulhul (OrcCompiler *p, void *user, OrcInstruction *insn)
{
unsigned int code;
if (p->is_64bit) {
OrcVariable tmpreg1 = { .alloc = p->tmpreg, .size = p->vars[insn->dest_args[0]].size };
OrcVariable tmpreg2 = { .alloc = p->tmpreg2, .size = p->vars[insn->dest_args[0]].size };
orc_neon64_emit_binary (p, "umull", 0x2ea0c000,
tmpreg1,
p->vars[insn->src_args[0]],
p->vars[insn->src_args[1]],
p->insn_shift);
if (p->insn_shift == 2) {
orc_neon64_emit_binary (p, "umull", 0x2ea0c000,
tmpreg2,
p->vars[insn->src_args[0]],
p->vars[insn->src_args[1]],
p->insn_shift - 1);
}
/*
* WARNING:
* Be careful here, SHRN (without Q-bit set) will write bottom 64 bits
* of the $dest register with data and top 64 bits with zeroes! SHRN2
* (with Q-bit set) will write top 64 bits of $dest register with data
* and will retain bottom 64 bits content. If $dest==$src{1 or 2}, then
* using SHRN will lead to corruption of source data!
*/
orc_neon64_emit_unary (p, "shrn", 0x0f208400,
p->vars[insn->dest_args[0]],
tmpreg1, p->insn_shift);
if (p->insn_shift == 2) {
orc_neon64_emit_unary (p, "shrn", 0x0f208400,
p->vars[insn->dest_args[0]],
tmpreg2, p->insn_shift - 1);
}
} else {
orc_neon_emit_binary_long (p, "vmull.u32",0xf3a00c00,
p->tmpreg,
p->vars[insn->src_args[0]].alloc,
p->vars[insn->src_args[1]].alloc);
ORC_ASM_CODE(p," vshrn.i64 %s, %s, #%d\n",
orc_neon_reg_name (p->vars[insn->dest_args[0]].alloc),
orc_neon_reg_name_quad (p->tmpreg), 32);
code = NEON_BINARY (0xf2a00810,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg, 0);
orc_arm_emit (p, code);
if (p->insn_shift == 2) {
orc_neon_emit_binary_long (p, "vmull.u32",0xf3a00c00,
p->tmpreg,
p->vars[insn->src_args[0]].alloc + 1,
p->vars[insn->src_args[1]].alloc + 1);
ORC_ASM_CODE(p," vshrn.i64 %s, %s, #%d\n",
orc_neon_reg_name (p->vars[insn->dest_args[0]].alloc + 1),
orc_neon_reg_name_quad (p->tmpreg), 32);
code = NEON_BINARY (0xf2a00810,
p->vars[insn->dest_args[0]].alloc + 1,
p->tmpreg, 0);
orc_arm_emit (p, code);
}
}
}
static void
orc_neon_rule_mulhsl (OrcCompiler *p, void *user, OrcInstruction *insn)
{
unsigned int code;
if (p->is_64bit) {
OrcVariable tmpreg1 = { .alloc = p->tmpreg, .size = p->vars[insn->dest_args[0]].size };
OrcVariable tmpreg2 = { .alloc = p->tmpreg2, .size = p->vars[insn->dest_args[0]].size };
orc_neon64_emit_binary (p, "smull", 0x0ea0c000,
tmpreg1,
p->vars[insn->src_args[0]],
p->vars[insn->src_args[1]],
p->insn_shift);
if (p->insn_shift == 2) {
orc_neon64_emit_binary (p, "smull", 0x0ea0c000,
tmpreg2,
p->vars[insn->src_args[0]],
p->vars[insn->src_args[1]],
p->insn_shift - 1);
}
/*
* WARNING:
* Be careful here, SHRN (without Q-bit set) will write bottom 64 bits
* of the $dest register with data and top 64 bits with zeroes! SHRN2
* (with Q-bit set) will write top 64 bits of $dest register with data
* and will retain bottom 64 bits content. If $dest==$src{1 or 2}, then
* using SHRN will lead to corruption of source data!
*/
orc_neon64_emit_unary (p, "shrn", 0x0f208400,
p->vars[insn->dest_args[0]],
tmpreg1, p->insn_shift);
if (p->insn_shift == 2) {
orc_neon64_emit_unary (p, "shrn", 0x0f208400,
p->vars[insn->dest_args[0]],
tmpreg2, p->insn_shift - 1);
}
} else {
orc_neon_emit_binary_long (p, "vmull.s32",0xf2a00c00,
p->tmpreg,
p->vars[insn->src_args[0]].alloc,
p->vars[insn->src_args[1]].alloc);
ORC_ASM_CODE(p," vshrn.i64 %s, %s, #%d\n",
orc_neon_reg_name (p->vars[insn->dest_args[0]].alloc),
orc_neon_reg_name_quad (p->tmpreg), 32);
code = NEON_BINARY (0xf2a00810,
p->vars[insn->dest_args[0]].alloc,
p->tmpreg, 0);
orc_arm_emit (p, code);
if (p->insn_shift == 2) {
orc_neon_emit_binary_long (p, "vmull.s32",0xf2a00c00,
p->tmpreg,
p->vars[insn->src_args[0]].alloc + 1,
p->vars[insn->src_args[1]].alloc + 1);
ORC_ASM_CODE(p," vshrn.i64 %s, %s, #%d\n",
orc_neon_reg_name (p->vars[insn->dest_args[0]].alloc + 1),
orc_neon_reg_name_quad (p->tmpreg), 32);
code = NEON_BINARY (0xf2a00810,
p->vars[insn->dest_args[0]].alloc + 1,
p->tmpreg, 0);
orc_arm_emit (p, code);
}
}
}
static void
orc_neon_rule_splitql (OrcCompiler *p, void *user, OrcInstruction *insn)
{
int dest0 = p->vars[insn->dest_args[0]].alloc;
int dest1 = p->vars[insn->dest_args[1]].alloc;
int src = p->vars[insn->src_args[0]].alloc;
if (p->is_64bit) {
if (src != dest0) {
orc_neon64_emit_binary (p, "uzp2", 0x0e805800,
p->vars[insn->dest_args[0]], p->vars[insn->src_args[0]],
p->vars[insn->src_args[0]], p->insn_shift - (p->insn_shift >= 1));
orc_neon64_emit_binary (p, "uzp1", 0x0e801800,
p->vars[insn->dest_args[1]], p->vars[insn->src_args[0]],
p->vars[insn->src_args[0]], p->insn_shift - (p->insn_shift >= 1));
} else {
orc_neon64_emit_binary (p, "uzp1", 0x0e801800,
p->vars[insn->dest_args[1]], p->vars[insn->src_args[0]],
p->vars[insn->src_args[0]], p->insn_shift - (p->insn_shift >= 1));
orc_neon64_emit_binary (p, "uzp2", 0x0e805800,
p->vars[insn->dest_args[0]], p->vars[insn->src_args[0]],
p->vars[insn->src_args[0]], p->insn_shift - (p->insn_shift >= 1));
}
} else {
if (p->insn_shift < 1) {
if (src != dest0) {
orc_neon_emit_mov (p, p->vars[insn->dest_args[0]], p->vars[insn->src_args[0]]);
}
if (src != dest1) {
orc_neon_emit_mov (p, p->vars[insn->dest_args[1]], p->vars[insn->src_args[0]]);
}
orc_neon_emit_unary (p, "vtrn.32", 0xf3ba0080, dest1, dest0);
} else {
if (src != dest0) {
orc_neon_emit_mov_quad (p, p->vars[insn->dest_args[0]], p->vars[insn->src_args[0]]);
}
if (src != dest1) {
orc_neon_emit_mov_quad (p, p->vars[insn->dest_args[1]], p->vars[insn->src_args[0]]);
}
orc_neon_emit_unary_quad (p, "vuzp.32", 0xf3ba0140, dest1, dest0);
}
}
}
static void
orc_neon_rule_splitlw (OrcCompiler *p, void *user, OrcInstruction *insn)
{
int dest0 = p->vars[insn->dest_args[0]].alloc;
int dest1 = p->vars[insn->dest_args[1]].alloc;
int src = p->vars[insn->src_args[0]].alloc;
if (p->is_64bit) {
if (src != dest0) {
orc_neon64_emit_binary (p, "uzp2", 0x0e405800,
p->vars[insn->dest_args[0]], p->vars[insn->src_args[0]],
p->vars[insn->src_args[0]], p->insn_shift - (p->insn_shift >= 2));
orc_neon64_emit_binary (p, "uzp1", 0x0e401800,
p->vars[insn->dest_args[1]], p->vars[insn->src_args[0]],
p->vars[insn->src_args[0]], p->insn_shift - (p->insn_shift >= 2));
} else {
orc_neon64_emit_binary (p, "uzp1", 0x0e401800,
p->vars[insn->dest_args[1]], p->vars[insn->src_args[0]],
p->vars[insn->src_args[0]], p->insn_shift - (p->insn_shift >= 2));
orc_neon64_emit_binary (p, "uzp2", 0x0e405800,
p->vars[insn->dest_args[0]], p->vars[insn->src_args[0]],
p->vars[insn->src_args[0]], p->insn_shift - (p->insn_shift >= 2));
}
} else {
if (p->insn_shift < 2) {
if (src != dest0) {
orc_neon_emit_mov (p, p->vars[insn->dest_args[0]], p->vars[insn->src_args[0]]);
}
if (src != dest1) {
orc_neon_emit_mov (p, p->vars[insn->dest_args[1]], p->vars[insn->src_args[0]]);
}
orc_neon_emit_unary (p, "vuzp.16", 0xf3b60100, dest1, dest0);
} else {
if (src != dest0) {
orc_neon_emit_mov_quad (p, p->vars[insn->dest_args[0]], p->vars[insn->src_args[0]]);
}
if (src != dest1) {
orc_neon_emit_mov_quad (p, p->vars[insn->dest_args[1]], p->vars[insn->src_args[0]]);
}
orc_neon_emit_unary_quad (p, "vuzp.16", 0xf3b60140, dest1, dest0);
}
}
}
static void
orc_neon_rule_splitwb (OrcCompiler *p, void *user, OrcInstruction *insn)
{
int dest0 = p->vars[insn->dest_args[0]].alloc;
int dest1 = p->vars[insn->dest_args[1]].alloc;
int src = p->vars[insn->src_args[0]].alloc;
if (p->is_64bit) {
if (src != dest0) {
orc_neon64_emit_binary (p, "uzp2", 0x0e005800,
p->vars[insn->dest_args[0]], p->vars[insn->src_args[0]],
p->vars[insn->src_args[0]], p->insn_shift - (p->insn_shift >= 2));
orc_neon64_emit_binary (p, "uzp1", 0x0e001800,
p->vars[insn->dest_args[1]], p->vars[insn->src_args[0]],
p->vars[insn->src_args[0]], p->insn_shift - (p->insn_shift >= 2));
} else {
orc_neon64_emit_binary (p, "uzp1", 0x0e001800,
p->vars[insn->dest_args[1]], p->vars[insn->src_args[0]],
p->vars[insn->src_args[0]], p->insn_shift - (p->insn_shift >= 2));
orc_neon64_emit_binary (p, "uzp2", 0x0e005800,
p->vars[insn->dest_args[0]], p->vars[insn->src_args[0]],
p->vars[insn->src_args[0]], p->insn_shift - (p->insn_shift >= 2));
}
} else {
if (p->insn_shift < 2) {
if (src != dest0) {
orc_neon_emit_mov (p, p->vars[insn->dest_args[0]], p->vars[insn->src_args[0]]);
}
if (src != dest1) {
orc_neon_emit_mov (p, p->vars[insn->dest_args[1]], p->vars[insn->src_args[0]]);
}
orc_neon_emit_unary (p, "vuzp.8", 0xf3b20100, dest1, dest0);
} else {
if (src != dest0) {
orc_neon_emit_mov_quad (p, p->vars[insn->dest_args[0]], p->vars[insn->src_args[0]]);
}
if (src != dest1) {
orc_neon_emit_mov_quad (p, p->vars[insn->dest_args[1]], p->vars[insn->src_args[0]]);
}
orc_neon_emit_unary_quad (p, "vuzp.8", 0xf3b20140, dest1, dest0);
}
}
}
static void
orc_neon_rule_div255w (OrcCompiler *p, void *user, OrcInstruction *insn)
{
OrcVariable tmpreg = { .alloc = p->tmpreg, .size = p->vars[insn->src_args[0]].size };
int dest = p->vars[insn->dest_args[0]].alloc;
int src = p->vars[insn->src_args[0]].alloc;
int tmp = p->tmpreg;
if (p->is_64bit) {
orc_neon64_emit_unary (p, "rshrn", 0x0f088c00,
tmpreg,
p->vars[insn->src_args[0]], p->insn_shift - !!(p->insn_shift >= 3));
orc_neon64_emit_unary (p, "ushll", 0x2f08a400,
tmpreg,
tmpreg, p->insn_shift - !!(p->insn_shift >= 3));
orc_neon64_emit_binary (p, "add", 0x0e608400,
tmpreg,
tmpreg,
p->vars[insn->src_args[0]], p->insn_shift - !!(p->insn_shift >= 3));
orc_neon64_emit_unary (p, "rshrn", 0x0f088c00,
p->vars[insn->dest_args[0]],
tmpreg, p->insn_shift - !!(p->insn_shift >= 3));
orc_neon64_emit_unary (p, "ushll", 0x2f08a400,
p->vars[insn->dest_args[0]],
p->vars[insn->dest_args[0]], p->insn_shift - !!(p->insn_shift >= 3));
} else {
if (p->insn_shift < 3) {
ORC_ASM_CODE(p," vrshrn.u16 %s, %s, #%d\n", orc_neon_reg_name(tmp),
orc_neon_reg_name_quad(src), 8);
orc_arm_emit (p, NEON_BINARY (0xf2880850, tmp, 0, src));
orc_neon_emit_unary_long (p, "vmovl.u8",0xf3880a10, tmp, tmp);
orc_neon_emit_binary (p, "vadd.i16", 0xf2100800, tmp, tmp, src);
ORC_ASM_CODE(p," vrshrn.u16 %s, %s, #%d\n", orc_neon_reg_name(dest),
orc_neon_reg_name_quad(tmp), 8);
orc_arm_emit (p, NEON_BINARY (0xf2880850, dest, 0, tmp));
orc_neon_emit_unary_long (p, "vmovl.u8",0xf3880a10, dest, dest);
} else {
ORC_ASM_CODE(p," vrshrn.u16 %s, %s, #%d\n", orc_neon_reg_name(tmp),
orc_neon_reg_name_quad(src), 8);
orc_arm_emit (p, NEON_BINARY (0xf2880850, tmp, 0, src));
orc_neon_emit_unary_long (p, "vmovl.u8",0xf3880a10, tmp, tmp);
orc_neon_emit_binary_quad (p, "vadd.i16", 0xf2100800, tmp, tmp, src);
ORC_ASM_CODE(p," vrshrn.u16 %s, %s, #%d\n", orc_neon_reg_name(dest),
orc_neon_reg_name_quad(tmp), 8);
orc_arm_emit (p, NEON_BINARY (0xf2880850, dest, 0, tmp));
orc_neon_emit_unary_long (p, "vmovl.u8",0xf3880a10, dest, dest);
}
}
}
void
orc_compiler_neon_register_rules (OrcTarget *target)
{
OrcRuleSet *rule_set;
rule_set = orc_rule_set_new (orc_opcode_set_get("sys"), target, 0);
#define REG(x) \
orc_rule_register (rule_set, #x , orc_neon_rule_ ## x, NULL)
REG(absb);
REG(addb);
REG(addssb);
REG(addusb);
REG(andb);
/* REG(andnb); */
REG(avgsb);
REG(avgub);
REG(cmpeqb);
REG(cmpgtsb);
REG(copyb);
REG(maxsb);
REG(maxub);
REG(minsb);
REG(minub);
REG(mullb);
REG(mulhsb);
REG(mulhub);
REG(orb);
/* REG(shlb); */
/* REG(shrsb); */
/* REG(shrub); */
REG(signb);
REG(subb);
REG(subssb);
REG(subusb);
REG(xorb);
REG(absw);
REG(addw);
REG(addssw);
REG(addusw);
REG(andw);
/* REG(andnw); */
REG(avgsw);
REG(avguw);
REG(cmpeqw);
REG(cmpgtsw);
REG(copyw);
REG(maxsw);
REG(maxuw);
REG(minsw);
REG(minuw);
REG(mullw);
REG(mulhsw);
REG(mulhuw);
REG(orw);
/* REG(shlw); */
/* REG(shrsw); */
/* REG(shruw); */
REG(signw);
REG(subw);
REG(subssw);
REG(subusw);
REG(xorw);
REG(absl);
REG(addl);
REG(addssl);
REG(addusl);
REG(andl);
/* REG(andnl); */
REG(avgsl);
REG(avgul);
REG(cmpeql);
REG(cmpgtsl);
REG(copyl);
REG(maxsl);
REG(maxul);
REG(minsl);
REG(minul);
REG(mulll);
REG(mulhsl);
REG(mulhul);
REG(orl);
/* REG(shll); */
/* REG(shrsl); */
/* REG(shrul); */
REG(signl);
REG(subl);
REG(subssl);
REG(subusl);
REG(xorl);
REG(addq);
REG(andq);
REG(orq);
REG(copyq);
REG(subq);
REG(xorq);
REG(convsbw);
REG(convubw);
REG(convswl);
REG(convuwl);
REG(convslq);
REG(convulq);
REG(convlw);
REG(convql);
REG(convssslw);
REG(convsuslw);
REG(convuuslw);
REG(convsssql);
REG(convsusql);
REG(convuusql);
REG(convwb);
REG(convhwb);
REG(convhlw);
REG(convssswb);
REG(convsuswb);
REG(convuuswb);
REG(mulsbw);
REG(mulubw);
REG(mulswl);
REG(muluwl);
REG(accw);
REG(accl);
REG(accsadubl);
REG(swapw);
REG(swapl);
REG(swapq);
REG(swapwl);
REG(swaplq);
REG(select0wb);
REG(select1wb);
REG(select0lw);
REG(select1lw);
REG(select0ql);
REG(select1ql);
REG(mergebw);
REG(mergewl);
REG(mergelq);
REG(splitql);
REG(splitlw);
REG(splitwb);
REG(addf);
REG(subf);
REG(mulf);
REG(divf);
REG(sqrtf);
REG(maxf);
REG(minf);
REG(cmpeqf);
/* REG(cmpltf); */
/* REG(cmplef); */
REG(convfl);
REG(convlf);
REG(addd);
REG(subd);
REG(muld);
REG(divd);
REG(sqrtd);
/* REG(cmpeqd); */
REG(convdf);
REG(convfd);
REG(splatbw);
REG(splatbl);
REG(splatw3q);
REG(div255w);
orc_rule_register (rule_set, "loadpb", neon_rule_loadpX, (void *)1);
orc_rule_register (rule_set, "loadpw", neon_rule_loadpX, (void *)2);
orc_rule_register (rule_set, "loadpl", neon_rule_loadpX, (void *)4);
orc_rule_register (rule_set, "loadpq", neon_rule_loadpX, (void *)8);
orc_rule_register (rule_set, "loadupdb", neon_rule_loadupdb, (void *)0);
orc_rule_register (rule_set, "loadb", neon_rule_loadX, (void *)0);
orc_rule_register (rule_set, "loadw", neon_rule_loadX, (void *)0);
orc_rule_register (rule_set, "loadl", neon_rule_loadX, (void *)0);
orc_rule_register (rule_set, "loadq", neon_rule_loadX, (void *)0);
orc_rule_register (rule_set, "loadoffb", neon_rule_loadX, (void *)1);
orc_rule_register (rule_set, "loadoffw", neon_rule_loadX, (void *)1);
orc_rule_register (rule_set, "loadoffl", neon_rule_loadX, (void *)1);
orc_rule_register (rule_set, "storeb", neon_rule_storeX, (void *)0);
orc_rule_register (rule_set, "storew", neon_rule_storeX, (void *)0);
orc_rule_register (rule_set, "storel", neon_rule_storeX, (void *)0);
orc_rule_register (rule_set, "storeq", neon_rule_storeX, (void *)0);
orc_rule_register (rule_set, "shlb", orc_neon_rule_shift, (void *)0);
orc_rule_register (rule_set, "shrsb", orc_neon_rule_shift, (void *)1);
orc_rule_register (rule_set, "shrub", orc_neon_rule_shift, (void *)2);
orc_rule_register (rule_set, "shlw", orc_neon_rule_shift, (void *)3);
orc_rule_register (rule_set, "shrsw", orc_neon_rule_shift, (void *)4);
orc_rule_register (rule_set, "shruw", orc_neon_rule_shift, (void *)5);
orc_rule_register (rule_set, "shll", orc_neon_rule_shift, (void *)6);
orc_rule_register (rule_set, "shrsl", orc_neon_rule_shift, (void *)7);
orc_rule_register (rule_set, "shrul", orc_neon_rule_shift, (void *)8);
orc_rule_register (rule_set, "andnb", orc_neon_rule_andn, (void *)3);
orc_rule_register (rule_set, "andnw", orc_neon_rule_andn, (void *)2);
orc_rule_register (rule_set, "andnl", orc_neon_rule_andn, (void *)1);
orc_rule_register (rule_set, "andnq", orc_neon_rule_andn, (void *)0);
}
| 34.195096 | 135 | 0.573638 | [
"vector"
] |
72709c8f73f38c40f14917932e7b3ea3107bd86c | 919 | h | C | SOLVER/src/preloop/graph/DualGraph.h | kuangdai/AxiSEM3D | fd9da14e9107783e3b07b936c67af2412146e099 | [
"MIT"
] | 17 | 2016-12-16T03:13:57.000Z | 2021-12-15T01:56:45.000Z | SOLVER/src/preloop/graph/DualGraph.h | syzeng-duduxi/AxiSEM3D | fd9da14e9107783e3b07b936c67af2412146e099 | [
"MIT"
] | 6 | 2018-01-15T17:17:20.000Z | 2020-03-18T09:53:58.000Z | SOLVER/src/preloop/graph/DualGraph.h | syzeng-duduxi/AxiSEM3D | fd9da14e9107783e3b07b936c67af2412146e099 | [
"MIT"
] | 19 | 2016-12-28T16:55:00.000Z | 2021-06-23T01:02:16.000Z | // DualGraph.h
// created by Kuangdai on 18-Jun-2016
// metis dual graph
#pragma once
#include "eigenp.h"
// domain decomposition option
struct DecomposeOption {
RDColX mElemWeights = RDColX::Zero(0);
double mImbalance = 0.01;
int mProcInterval = 1;
int mNCutsPerProc = 1;
};
class DualGraph {
public:
// form neighbourhood of connectivity
static void formNeighbourhood(const IMatX4 &connectivity, int ncommon,
std::vector<IColX> &neighbours);
// domain decomposition
static void decompose(const IMatX4 &connectivity, const DecomposeOption &option,
IColX &elemToProc);
private:
static void formAdjacency(const IMatX4 &connectivity, int ncommon, int *&xadj, int *&adjncy);
static void freeAdjacency(int *&xadj, int *&adjncy);
static void metisError(const int retval, const std::string &func_name);
static void check_idx_t();
};
| 25.527778 | 97 | 0.693145 | [
"vector"
] |
727610a83685afa47d93aaa14f2ee2511e4f3c7e | 13,030 | h | C | Pinocchio/vector.h | criminalking/character_animation | 2eb0362d8021779aad12f216f788b84799070338 | [
"MIT"
] | null | null | null | Pinocchio/vector.h | criminalking/character_animation | 2eb0362d8021779aad12f216f788b84799070338 | [
"MIT"
] | null | null | null | Pinocchio/vector.h | criminalking/character_animation | 2eb0362d8021779aad12f216f788b84799070338 | [
"MIT"
] | null | null | null | /* This file is part of the Pinocchio automatic rigging library.
Copyright (C) 2007 Ilya Baran (ibaran@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
*/
#ifndef VECTOR_H_INCLUDED
#define VECTOR_H_INCLUDED
#include <iostream>
#include <functional>
#include <vector>
#include <numeric>
#include "hashutils.h"
#include "mathutils.h"
using namespace std;
namespace _VectorPrivate {
template <int Dim> class VecOp;
}
template <class Real, int Dim>
class Vector
{
public:
typedef Vector<Real, Dim> Self;
typedef _VectorPrivate::VecOp<Dim> VO;
Vector() { VO::assign(Real(), *this); }
Vector(const Self &other) { VO::assign(other, *this); }
explicit Vector(const Real &m) { VO::assign(m, *this); }
Vector(const Real &m1, const Real &m2) { m[0] = m1; m[1] = m2; checkDim<2>(VO()); }
Vector(const Real &m1, const Real &m2, const Real &m3) { m[0] = m1; m[1] = m2; m[2] = m3; checkDim<3>(VO()); }
template<class R> Vector(const Vector<R, Dim> &other) { VO::assign(other, *this); }
Real &operator[](int n) { return m[n]; }
const Real &operator[](int n) const { return m[n]; }
//basic recursive functions
template<class F> Vector<typename F::result_type, Dim> apply(const F &func) const
{ return VO::apply(func, *this); }
template<class F> Vector<typename F::result_type, Dim> apply(const F &func, const Self &other) const
{ return VO::apply(func, *this, other); }
template<class Op, class Accum>
typename Accum::result_type accumulate(const Op &op, const Accum &accum) const
{ return VO::accumulate(op, accum, *this); }
template<class Op, class Accum>
typename Accum::result_type accumulate(const Op &op, const Accum &accum, const Self &other) const
{ return VO::accumulate(op, accum, *this, other); }
//operators
Real operator*(const Self &other) const { return accumulate(multiplies<Real>(), plus<Real>(), other); }
Self operator+(const Self &other) const { return apply(plus<Real>(), other); }
Self operator-(const Self &other) const { return apply(minus<Real>(), other); }
Self operator*(const Real &scalar) const { return apply(bind2nd(multiplies<Real>(), scalar)); }
Self operator/(const Real &scalar) const { return apply(bind2nd(divides<Real>(), scalar)); }
Self operator-() const { return apply(negate<Real>()); }
bool operator==(const Self &other) const { return accumulate(equal_to<Real>(), logical_and<Real>(), other); }
#define OPAS(op, typ) Self &operator op##=(const typ &x) { (*this) = (*this) op x; return *this; }
OPAS(+, Self)
OPAS(-, Self)
OPAS(*, Real)
OPAS(/, Real)
#undef OPAS
Real lengthsq() const { return (*this) * (*this); }
Real length() const { return sqrt(lengthsq()); }
Self normalize() const { return (*this) / length(); }
int size() const { return Dim; }
private:
template<class R, int D> friend class Vector;
template<int WantedDim> void checkDim(const _VectorPrivate::VecOp<WantedDim> &) const {}
Real m[Dim];
};
template <class Real>
class Vector<Real, -1>
{
public:
typedef Vector<Real, -1> Self;
Vector() { }
Vector(const Self &other) : m(other.m) { }
Vector(const vector<Real> &inM) : m(inM) { }
explicit Vector(const Real &inM) { m.push_back(inM); }
Real &operator[](int n) { if((int)m.size() <= n) m.resize(n + 1); return m[n]; }
const Real &operator[](int n) const { if((int)m.size() <= n) const_cast<Vector<Real, -1> *>(this)->m.resize(n + 1); return m[n]; }
//basic recursive functions
template<class F> Vector<typename F::result_type, -1> apply(const F &func) const
{
vector<typename F::result_type> out(m.size());
transform(m.begin(), m.end(), out.begin(), func);
return Vector<typename F::result_type, -1>(out);
}
template<class F> Vector<typename F::result_type, -1> apply(const F &func, const Self &other) const
{
vector<typename F::result_type> out(max(m.size(), other.m.size()));
if(m.size() == other.m.size())
transform(m.begin(), m.end(), other.m.begin(), out.begin(), func);
else if(m.size() < other.m.size()) {
transform(m.begin(), m.end(), other.m.begin(), out.begin(), func);
for(int i = m.size(); i < (int)other.m.size(); ++i) out[i] = func(Real(), other.m[i]);
} else {
transform(m.begin(), m.begin() + (other.m.end() - other.m.begin()), other.m.begin(), out.begin(), func);
for(int i = other.m.size(); i < (int)m.size(); ++i) out[i] = func(m[i], Real());
}
return Vector<typename F::result_type, -1>(out);
}
template<class Op, class Accum>
typename Accum::result_type accumulate(const Op &op, const Accum &accum) const
{
if(m.empty())
return typename Accum::result_type();
typename Accum::result_type out = op(m[0]);
for(int i = 1; i < (int)m.size(); ++i) out = accum(out, op(m[i]));
return out;
}
template<class Op, class Accum>
typename Accum::result_type accumulate(const Op &op, const Accum &accum, const Self &other) const
{
typename Accum::result_type out;
if(m.empty() || other.m.empty()) {
if(m.empty() && other.m.empty()) return typename Accum::result_type();
if(m.empty()) out = op(Real(), other.m[0]);
else out = op(m[0], Real());
}
else out = op(m[0], other.m[0]);
if(m.size() == other.m.size())
for(int i = 1; i < (int)m.size(); ++i) out = accum(out, op(m[i], other.m[i]));
else if(m.size() < other.m.size()) {
for(int i = 1; i < (int)m.size(); ++i) out = accum(out, op(m[i], other.m[i]));
for(int i = m.size(); i < (int)other.m.size(); ++i) out = accum(out, op(Real(), other.m[i]));
} else {
for(int i = 1; i < (int)other.m.size(); ++i) out = accum(out, op(m[i], other.m[i]));
for(int i = other.m.size(); i < (int)m.size(); ++i) out = accum(out, op(m[i], Real()));
}
return out;
}
//operators
Real operator*(const Self &other) const { return accumulate(multiplies<Real>(), plus<Real>(), other); }
Self operator+(const Self &other) const { return apply(plus<Real>(), other); }
Self operator-(const Self &other) const { return apply(minus<Real>(), other); }
Self operator*(const Real &scalar) const { return apply(bind2nd(multiplies<Real>(), scalar)); }
Self operator/(const Real &scalar) const { return apply(bind2nd(divides<Real>(), scalar)); }
Self operator-() const { return apply(negate<Real>()); }
#define OPAS(op, typ) Self &operator op##=(const typ &x) { (*this) = (*this) op x; return *this; }
OPAS(+, Self)
OPAS(-, Self)
OPAS(*, Real)
OPAS(/, Real)
#undef OPAS
Real lengthsq() const { return (*this) * (*this); } // length^2
Real length() const { return sqrt(lengthsq()); }
Self normalize() const { return (*this) / length(); }
int size() const { return m.size(); }
private:
vector<Real> m;
};
template <class Real, int Dim>
Vector<Real, Dim> operator*(const Real &scalar, const Vector<Real, Dim> &vec)
{
return vec * scalar; //multiplication commutes around here
}
//cross product
template <class Real>
Vector<Real, 3> operator%(const Vector<Real, 3> &v1, const Vector<Real, 3> &v2)
{
return Vector<Real, 3>(v1[1] * v2[2] - v1[2] * v2[1],
v1[2] * v2[0] - v1[0] * v2[2],
v1[0] * v2[1] - v1[1] * v2[0]);
}
typedef Vector<double, 3> Vector3;
typedef Vector<double, 2> Vector2;
template <class charT, class traits, class Real, int Dim>
basic_ostream<charT,traits>& operator<<(basic_ostream<charT,traits>& os, const Vector<Real, Dim> &v)
{
os << "[";
int ms = Dim;
if(ms == -1)
ms = v.size();
for(int i = 0; i < ms; ++i) {
os << v[i];
if(i < ms - 1)
os << ", ";
}
os << "]";
return os;
}
namespace _VectorPrivate {
#define VRD Vector<R, D>
#define VRD1 Vector<R1, D>
template <int Dim>
class VecOp
{
public: // TODO: private to public
static const int last = Dim - 1;
typedef VecOp<Dim - 1> Next;
template<int D> friend class VecOp;
template<class R, int D> friend class Vector;
template<class R, class R1, int D>
static void assign(const VRD1 &from, VRD &to) { to[last] = from[last]; Next::assign(from, to); }
template<class R, class R1, int D>
static void assign(const R1 &from, VRD &to) { to[last] = from; Next::assign(from, to); }
template<class R, int D, class F>
static Vector<typename F::result_type, D> apply(const F &func, const VRD &v)
{ Vector<typename F::result_type, D> out; _apply(func, v, out); return out; }
template<class R, int D, class F>
static Vector<typename F::result_type, D> apply(const F &func, const VRD &v, const VRD &other)
{ Vector<typename F::result_type, D> out; _apply(func, v, other, out); return out; }
template<class R, int D, class Op, class Accum>
static typename Accum::result_type accumulate(const Op &op, const Accum &accum, const VRD &v)
{ return accum(op(v[last]), Next::accumulate(op, accum, v)); }
template<class R, int D, class Op, class Accum>
static typename Accum::result_type accumulate(const Op &op, const Accum &accum, const VRD &v, const VRD &other)
{ return accum(op(v[last], other[last]), Next::accumulate(op, accum, v, other)); }
template<class R, int D, class F>
static void _apply(const F &func, const VRD &v, Vector<typename F::result_type, D> &out)
{ out[last] = func(v[last]); Next::_apply(func, v, out); }
template<class R, int D, class F>
static void _apply(const F &func, const VRD &v, const VRD &other, Vector<typename F::result_type, D> &out)
{ out[last] = func(v[last], other[last]); Next::_apply(func, v, other, out); }
};
template <>
class VecOp<1>
{
public: // TODO: private to public
template<int D> friend class VecOp;
template<class R, class R1, int D> static void assign(const VRD1 &from, VRD &to) { to[0] = from[0]; }
template<class R, class R1, int D> static void assign(const R1 &from, VRD &to) { to[0] = from; }
template<class R, int D, class F>
static Vector<typename F::result_type, D> apply(const F &func, const VRD &v)
{ Vector<typename F::result_type, D> out; _apply(func, v, out); return out; }
template<class R, int D, class F>
static Vector<typename F::result_type, D> apply(const F &func, const VRD &v, const VRD &other)
{ Vector<typename F::result_type, D> out; _apply(func, v, other, out); return out; }
template<class R, int D, class Op, class Accum>
static typename Accum::result_type accumulate(const Op &op, const Accum &, const VRD &v)
{ return op(v[0]); }
template<class R, int D, class Op, class Accum>
static typename Accum::result_type accumulate(const Op &op, const Accum &, const VRD &v, const VRD &other)
{ return op(v[0], other[0]); }
template<class R, int D, class F>
static void _apply(const F &func, const VRD &v, Vector<typename F::result_type, D> &out)
{ out[0] = func(v[0]); }
template<class R, int D, class F>
static void _apply(const F &func, const VRD &v, const VRD &other, Vector<typename F::result_type, D> &out)
{ out[0] = func(v[0], other[0]); }
};
} //namespace _VectorPrivate
//BitComparator is a utility class that helps with rectangle and dtree indices
template<int Dim> class BitComparator
{
public:
static const int last = Dim - 1;
typedef BitComparator<Dim - 1> Next;
template<class R, int D> static unsigned int less(const VRD &v1, const VRD &v2)
{ return ((v1[last] < v2[last]) ? (1 << last) : 0) + Next::less(v1, v2); }
template<class R, int D> static void assignCorner(int idx, const VRD &v1, const VRD &v2, VRD &out)
{ out[last] = (idx & (1 << last)) ? v1[last] : v2[last]; Next::assignCorner(idx, v1, v2, out); }
};
template<> class BitComparator<1>
{
public:
template<class R, int D> static unsigned int less(const VRD &v1, const VRD &v2)
{ return (v1[0] < v2[0]) ? 1 : 0; }
template<class R, int D> static void assignCorner(int idx, const VRD &v1, const VRD &v2, VRD &out)
{ out[0] = (idx & 1) ? v1[0] : v2[0];}
};
#undef VRD
#undef VRD1
#endif //VECTOR_H_INCLUDED
| 39.129129 | 134 | 0.621719 | [
"vector",
"transform"
] |
727b557578b667f15899e4ca0356f6e8b4be93fd | 1,450 | h | C | AirFloat/NotificationCenter.h | davhelm/AirFloat | 460a97d57f9adf3372093e1e62a38b726ab08737 | [
"Unlicense"
] | 2 | 2015-07-20T17:09:11.000Z | 2017-02-05T11:08:34.000Z | AirFloat/NotificationCenter.h | davhelm/AirFloat | 460a97d57f9adf3372093e1e62a38b726ab08737 | [
"Unlicense"
] | null | null | null | AirFloat/NotificationCenter.h | davhelm/AirFloat | 460a97d57f9adf3372093e1e62a38b726ab08737 | [
"Unlicense"
] | null | null | null | //
// NotificationCenter.h
// AirFloat
//
// Created by Kristian Trenskow on 2/8/12.
// Copyright (c) 2012 The Famous Software Company. All rights reserved.
//
#ifndef AirFloat_NotificationCenter_h
#define AirFloat_NotificationCenter_h
#include <stdlib.h>
#include <stdint.h>
#include "Mutex.h"
#include "Notification.h"
#include "NotificationObserver.h"
typedef void(*notificationClbk)(void* sender, const char* name, void* notificationInfo, void* callbackContext);
typedef struct {
NotificationObserver* observer;
notificationClbk callback;
void* callbackContext;
char* name;
void* object;
} NotificationCenterObserver;
class NotificationCenter {
public:
static NotificationCenter* defaultCenter();
void addObserver(NotificationObserver* observer, const char* name, void* object);
void addObserver(notificationClbk callback, void* callbackContext, const char* name, void* object);
void removeObserver(notificationClbk callback, void* callbackContext);
void removeObserver(void* callbackContext);
void postNotification(const char* name, void* sender, void* notificationInfo);
private:
NotificationCenter();
void _addObserver(NotificationObserver* observer, notificationClbk callback, void* context, const char* name, void* object);
Mutex _mutex;
NotificationCenterObserver* _observers;
uint32_t _observerCount;
};
#endif
| 25.892857 | 128 | 0.733793 | [
"object"
] |
72827b803de74087e26a7eb751d886368d8b4038 | 2,739 | h | C | include/Test.h | Matthiaas/RankAndSelectBasedQuotientFilter | 5e64cf6248d8ec4e5686bf7d818006349282db3b | [
"Apache-2.0"
] | null | null | null | include/Test.h | Matthiaas/RankAndSelectBasedQuotientFilter | 5e64cf6248d8ec4e5686bf7d818006349282db3b | [
"Apache-2.0"
] | null | null | null | include/Test.h | Matthiaas/RankAndSelectBasedQuotientFilter | 5e64cf6248d8ec4e5686bf7d818006349282db3b | [
"Apache-2.0"
] | null | null | null | #ifndef TEST_H
#define TEST_H
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include "AQM.h"
#include "RSQF.h"
#include "CQF.h"
#include "RSQF_WITHOUT_BLOCKING.h"
#include "RSQF_WITHOUT_OFFSETS.h"
#include "BloomFilter.h"
#include "CountingBloomFilter.h"
// If true this may increas runtime!
#define ENABLE_WAITING_PRINTS true
#define print(x) std::cout<<x<<std::flush
#define NEW_LINE std::cout<<std::endl
#define NEW_TEST std::cout<<"-----------------------------------------------"<<std::endl
void createDistinctTestData(int n, std::vector<Element> &insert , std::vector<Element> &lookUps);
void createCountingTestData(int n, std::vector<Element> &insert , std::vector<Element> &lookUps , std::vector<int> &count , int maxCount);
//Can not be defined in another sourec file
//Make sure T is an AMQ
template<class T,typename = std::enable_if<std::is_base_of<AQM, T>::value>>
int speedTest(double falsePositiveRate , int n , std::vector<Element> &insert
, std::vector<Element> &lookUps , std::vector<Element> &randomlookUps ,std::vector<int> &count ){
print("inti: \t\t\t" );
clock_t start = clock();
T qf(falsePositiveRate , n );
clock_t end = clock();
double time = (double) (end-start) / CLOCKS_PER_SEC ;
print( time << "s" );
NEW_LINE;
//Random Inserts:
print("Random inserts: \t");
start = clock();
for(int i = 0; i < insert.size(); i++){
for(int j = 0; j <= count[i]; j++)
qf.insert(insert[i]);
#if ENABLE_WAITING_PRINTS
if(!(i % ( insert.size()/10))) {
print(".");
}
#endif
}
end = clock();
time = (double) (end-start) / CLOCKS_PER_SEC ;
print(" " << time << "s" );
NEW_LINE;
//Lookups:
print("Lookups:\t\t");
start = clock();
int res = 0;
for(int i = 0; i < lookUps.size() ; i++){
res+= qf.query(lookUps[i]);
#if ENABLE_WAITING_PRINTS
if(!(i % (lookUps.size()/10))) {
print(".");
}
#endif
}
end = clock();
time = (double) (end-start) / CLOCKS_PER_SEC ;
print(" " << time << "s" << "\t \t" << res << " elements found (should be:" << n << ")");
NEW_LINE;
//Random lookups:
print("Random lookups: \t");
start = clock();
res = 0;
for(int i = 0; i < randomlookUps.size() ; i++){
qf.query(randomlookUps[i]);
#if ENABLE_WAITING_PRINTS
if(!(i % (randomlookUps.size()/10))) {
print(".");
}
#endif
}
end = clock();
time = (double) (end-start) / CLOCKS_PER_SEC ;
print(" " << time << "s" );
NEW_LINE;
NEW_LINE;
}
#endif | 21.398438 | 138 | 0.556042 | [
"vector"
] |
72828d968d5def96e5bcc9957fb0a5e12df92fd3 | 2,762 | h | C | panda/src/chan/animChannelScalarDynamic.h | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | 3 | 2020-01-02T08:43:36.000Z | 2020-07-05T08:59:02.000Z | panda/src/chan/animChannelScalarDynamic.h | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | null | null | null | panda/src/chan/animChannelScalarDynamic.h | sean5470/panda3d | ea2d4fecd4af1d4064c5fe2ae2a902ef4c9b903d | [
"PHP-3.0",
"PHP-3.01"
] | 1 | 2020-03-11T17:38:45.000Z | 2020-03-11T17:38:45.000Z | /**
* PANDA 3D SOFTWARE
* Copyright (c) Carnegie Mellon University. All rights reserved.
*
* All use of this software is subject to the terms of the revised BSD
* license. You should have received a copy of this license along
* with this source code in a file named "LICENSE."
*
* @file animChannelScalarDynamic.h
* @author drose
* @date 2003-10-20
*/
#ifndef ANIMCHANNELSCALARDYNAMIC_H
#define ANIMCHANNELSCALARDYNAMIC_H
#include "pandabase.h"
#include "animChannel.h"
class PandaNode;
class TransformState;
/**
* An animation channel that accepts a scalar each frame from some dynamic
* input provided by code.
*
* This object operates in two modes: in explicit mode, the programmer should
* call set_value() each frame to indicate the new value; in implicit mode,
* the programmer should call set_value_node() to indicate the node whose X
* component will be copied to the scalar each frame.
*/
class EXPCL_PANDA_CHAN AnimChannelScalarDynamic : public AnimChannelScalar {
protected:
AnimChannelScalarDynamic();
AnimChannelScalarDynamic(AnimGroup *parent, const AnimChannelScalarDynamic ©);
public:
AnimChannelScalarDynamic(const string &name);
virtual bool has_changed(int last_frame, double last_frac,
int this_frame, double this_frac);
virtual void get_value(int frame, PN_stdfloat &value);
PUBLISHED:
void set_value(PN_stdfloat value);
void set_value_node(PandaNode *node);
protected:
virtual AnimGroup *make_copy(AnimGroup *parent) const;
private:
// This is filled in only if we are using the set_value_node() interface to
// get an implicit value from the transform on the indicated node each
// frame.
PT(PandaNode) _value_node;
CPT(TransformState) _value;
CPT(TransformState) _last_value;
// This is used only if we are using the explicit set_value() interface.
bool _value_changed;
PN_stdfloat _float_value;
public:
static void register_with_read_factory();
virtual void write_datagram(BamWriter *manager, Datagram &dg);
virtual int complete_pointers(TypedWritable **plist, BamReader *manager);
void fillin(DatagramIterator &scan, BamReader *manager);
static TypedWritable *make_AnimChannelScalarDynamic(const FactoryParams ¶ms);
public:
virtual TypeHandle get_type() const {
return get_class_type();
}
virtual TypeHandle force_init_type() {init_type(); return get_class_type();}
static TypeHandle get_class_type() {
return _type_handle;
}
static void init_type() {
AnimChannelScalar::init_type();
register_type(_type_handle, "AnimChannelScalarDynamic",
AnimChannelScalar::get_class_type());
}
private:
static TypeHandle _type_handle;
};
#include "animChannelScalarDynamic.I"
#endif
| 29.698925 | 84 | 0.754164 | [
"object",
"transform",
"3d"
] |
72835fbac9c9c2f0cceef82c6da0f5c5c8c7fbbb | 1,787 | h | C | SRC/analysis/analysis_cutline.h | shikc/wotan | e6962ed5b3e14033f49666b2fc210ea8c3f77290 | [
"MIT"
] | 6 | 2018-12-15T03:31:41.000Z | 2020-11-09T12:50:03.000Z | SRC/analysis/analysis_cutline.h | shikc/wotan | e6962ed5b3e14033f49666b2fc210ea8c3f77290 | [
"MIT"
] | null | null | null | SRC/analysis/analysis_cutline.h | shikc/wotan | e6962ed5b3e14033f49666b2fc210ea8c3f77290 | [
"MIT"
] | 5 | 2019-04-22T12:47:58.000Z | 2021-03-04T06:34:20.000Z | #ifndef ANALYSIS_CUTLINE_H
#define ANALYSIS_CUTLINE_H
#include <vector>
#include "wotan_types.h"
/**** Typedefs ****/
/* used to store node indices for each level of the subgraph */
typedef std::vector< std::vector< int > > t_cutline_prob_struct;
/**** Classes ****/
/* A class used to lump together all data structures specific to the cutline analysis method that
need to be passed around during topological traversal */
class Cutline_Structs{
public:
t_cutline_prob_struct cutline_prob_struct;
float prob_routable;
/* the physical type descriptor for the 'fill' type block (i.e. the CLB) */
Physical_Type_Descriptor *fill_type;
};
/**** Function Declarations ****/
/* Called when node is popped from expansion queue during topological traversal */
void cutline_node_popped_func(int popped_node, int from_node_ind, int to_node_ind, t_rr_node &rr_node, t_ss_distances &ss_distances, t_node_topo_inf &node_topo_inf,
e_traversal_dir traversal_dir, int max_path_weight, User_Options *user_opts, void *user_data);
/* Called when topological traversal is iterateing over a node's children */
bool cutline_child_iterated_func(int parent_ind, int parent_edge_ind, int node_ind, t_rr_node &rr_node, t_ss_distances &ss_distances, t_node_topo_inf &node_topo_inf,
e_traversal_dir traversal_dir, int max_path_weight, int from_node_ind, int to_node_ind, User_Options *user_opts, void *user_data);
/* Called once topological traversal is complete */
void cutline_traversal_done_func(int from_node_ind, int to_node_ind, t_rr_node &rr_node, t_ss_distances &ss_distances, t_node_topo_inf &node_topo_inf,
e_traversal_dir traversal_dir, int max_path_weight, User_Options *user_opts, void *user_data);
#endif
| 44.675 | 165 | 0.762171 | [
"vector"
] |
7290c6bbf644adc3e7652fac17b869ebc4d11387 | 3,556 | h | C | annotations.h | cs50isdt/SuperCalc | 6319a3c2c41b97c3ff446068aa1f3adbb0f4b480 | [
"MIT"
] | 7 | 2019-11-04T06:06:54.000Z | 2021-09-29T11:18:09.000Z | annotations.h | cs50isdt/SuperCalc | 6319a3c2c41b97c3ff446068aa1f3adbb0f4b480 | [
"MIT"
] | 4 | 2015-08-31T07:15:28.000Z | 2020-12-02T13:59:23.000Z | annotations.h | cs50isdt/SuperCalc | 6319a3c2c41b97c3ff446068aa1f3adbb0f4b480 | [
"MIT"
] | 5 | 2015-09-06T16:56:56.000Z | 2021-11-23T01:24:48.000Z | /*
annotations.h
SuperCalc
Created by C0deH4cker on 6/19/20.
Copyright (c) 2020 C0deH4cker. All rights reserved.
*/
#ifndef SC_ANNOTATIONS_H
#define SC_ANNOTATIONS_H
#include <stdlib.h>
#ifndef __has_attribute
# define __has_attribute(x) 0
#endif
#ifndef __has_feature
# define __has_feature(x) 0
#endif
#ifndef __has_builtin
# define __has_builtin(x) 0
#endif
#if __has_attribute(__warn_unused_result__)
# define WARN_UNUSED_RESULT __attribute__((__warn_unused_result__))
#else
# define WARN_UNUSED_RESULT
#endif
#if __has_attribute(__noreturn__)
# define NORETURN __attribute__((__noreturn__))
#elif defined(_MSC_VER)
# define NORETURN __declspec("noreturn")
#else
# define NORETURN
#endif
#if __has_attribute(__format__)
# define ATTR_FORMAT(...) __attribute__((__format__(__VA_ARGS__)))
#else
# define ATTR_FORMAT(...)
#endif
#if __has_attribute(__fallthrough__)
# define FALLTHROUGH __attribute__((__fallthrough__))
#else
# define FALLTHROUGH
#endif
#if __has_attribute(__noescape__)
# define NOESCAPE __attribute__((__noescape__))
#else
# define NOESCAPE
#endif
#if __has_attribute(__cf_consumed__)
# define ATTR_CF_CONSUMED __attribute__((__cf_consumed__))
#else
# define ATTR_CF_CONSUMED
#endif
#if __has_attribute(__cf_returns_retained__)
# define ATTR_CF_RETURNS_RETAINED __attribute__((__cf_returns_retained__))
#else
# define ATTR_CF_RETURNS_RETAINED
#endif
#if __has_attribute(__cf_returns_not_retained__)
# define ATTR_CF_RETURNS_NOT_RETAINED __attribute__((__cf_returns_not_retained__))
#else
# define ATTR_CF_RETURNS_NOT_RETAINED
#endif
#if __has_builtin(__builtin_assume)
# define ASSUME(...) __builtin_assume(__VA_ARGS__)
#elif defined(_MSC_VER)
# define ASSUME(...) __assume(__VA_ARGS__)
#else
# define ASSUME(...)
#endif
#if __has_builtin(__builtin_unreachable)
# define UNREACHABLE __builtin_unreachable()
#else
# define UNREACHABLE ASSUME(false)
#endif
#if __has_feature(nullability)
# define ASSUME_NONNULL_BEGIN _Pragma("clang assume_nonnull begin")
# define ASSUME_NONNULL_END _Pragma("clang assume_nonnull end")
#else /* nullability */
# define _Nullable
# define _Nonnull
# define ASSUME_NONNULL_BEGIN
# define ASSUME_NONNULL_END
#endif /* nullability */
/* Used in a function body to signify that the named parameter is intentionally unused */
#ifndef UNREFERENCED_PARAMETER
# define UNREFERENCED_PARAMETER(param) do { param = param; } while(0)
#endif
/* Attributes purely for documentation purposes */
#define IN
#define OUT
#define INOUT
#define OWNED
#define UNOWNED
#define PRINTFLIKE(fmtstr, va) ATTR_FORMAT(__printf__, fmtstr, va)
#define ESCAPING
#define CONSUMED ATTR_CF_CONSUMED
#define RETURNS_OWNED ATTR_CF_RETURNS_RETAINED
#define RETURNS_UNOWNED ATTR_CF_RETURNS_NOT_RETAINED
/* These aren't possible to implement with current attributes, so they serve as documentation only */
#define INVARIANT(...)
#define _Nonnull_unless(...) _Nonnull
#define _Nullable_unless(...) _Nullable
#define OWNED_WHEN(...)
#define UNOWNED_WHEN(...)
/* Convenience macro telling the clang static analyzer that this pointer is nonnull at this point */
#define CAST_NONNULL(ptr) ((__typeof__(*ptr) * _Nonnull)(ptr))
/* Convenience typedefs */
typedef const char* _Nonnull * _Nonnull istring;
#ifdef __clang_analyzer__
/* Tell the analyzer that this object has been consumed. This "function" has no body */
void analyzer_consume(void* _Nullable CONSUMED arg);
#else /* __clang_analyzer__ */
# define analyzer_consume(...) (void)(__VA_ARGS__)
#endif /* __clang_analzer__ */
#endif /* SC_ANNOTATIONS_H */
| 24.867133 | 101 | 0.791339 | [
"object"
] |
729346d9bb56c36d8ce461c5d2a79d27aec37d38 | 796 | h | C | preparer/src/AMGPreparer/amgpreparer.h | agancsos/cpp | 08ad758f71d899027d6891dca5bed24bf02bbc81 | [
"MIT"
] | null | null | null | preparer/src/AMGPreparer/amgpreparer.h | agancsos/cpp | 08ad758f71d899027d6891dca5bed24bf02bbc81 | [
"MIT"
] | null | null | null | preparer/src/AMGPreparer/amgpreparer.h | agancsos/cpp | 08ad758f71d899027d6891dca5bed24bf02bbc81 | [
"MIT"
] | null | null | null | #ifndef __AMGPREPARER_H_INCLUDED__
#define __AMGPREPARER_H_INCLUDED__
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include "../AMGSystem/amgsystem.h"
using namespace std;
/**
This class helps prepare the needed directories for DVD files
*/
class AMGPreparer{
private:
string maxSeasons;
string startingSeason;
string diskCount;
bool silent;
void dumpConfig();
public:
AMGPreparer();
~AMGPreparer();
AMGPreparer(string max);
AMGPreparer(string max,string ss);
AMGPreparer(string max,string ss,string disks);
void prepare();
void setMax(string a);
void setSeason(string a);
void setDisks(string a);
void setSilent(bool a);
bool getSilent();
string getMax();
string getSeason();
string getDisks();
};
#endif
| 20.410256 | 62 | 0.717337 | [
"vector"
] |
72a156b75842045dc211fe393a524299777e6533 | 543 | h | C | cpp/plsomlib/util/DiameterBuffer.h | erikjber/plsomlib | 076d9d1e87a336c7a928e983b7313718aeef8688 | [
"Unlicense"
] | null | null | null | cpp/plsomlib/util/DiameterBuffer.h | erikjber/plsomlib | 076d9d1e87a336c7a928e983b7313718aeef8688 | [
"Unlicense"
] | null | null | null | cpp/plsomlib/util/DiameterBuffer.h | erikjber/plsomlib | 076d9d1e87a336c7a928e983b7313718aeef8688 | [
"Unlicense"
] | null | null | null | /**
* Created by Erik Berglund on 2018-04-18.
*/
#ifndef CPP_DIAMETERBUFFER_H
#define CPP_DIAMETERBUFFER_H
#include <vector>
#include "../metrics/EuclideanMetric.h"
using namespace std;
class DiameterBuffer
{
private:
vector<vector<double>> buffer;
EuclideanMetric bufferMetric;
double maxDiameter = -1;
public:
double getMaxDiameter()
{
return maxDiameter;
}
void setMaxDiameter(double newDiameter)
{
maxDiameter = newDiameter;
}
void updateBuffer(vector<double>& data);
};
#endif //CPP_DIAMETERBUFFER_H
| 15.514286 | 42 | 0.72744 | [
"vector"
] |
72a86ad7d4992e542306ef47a7eb0ecd14b081c8 | 6,475 | c | C | src/gst-plugins/webrtcendpoint/kmswebrtcbaseconnection.c | prlanzarin/kms-elements | 6664f325e176a7922536d7638e873e947d5b0766 | [
"Apache-2.0"
] | 1 | 2019-11-25T05:57:28.000Z | 2019-11-25T05:57:28.000Z | src/gst-plugins/webrtcendpoint/kmswebrtcbaseconnection.c | prlanzarin/kms-elements | 6664f325e176a7922536d7638e873e947d5b0766 | [
"Apache-2.0"
] | 2 | 2019-01-16T05:00:57.000Z | 2019-04-17T19:25:05.000Z | src/gst-plugins/webrtcendpoint/kmswebrtcbaseconnection.c | prlanzarin/kms-elements | 6664f325e176a7922536d7638e873e947d5b0766 | [
"Apache-2.0"
] | 2 | 2019-10-20T22:09:00.000Z | 2019-10-21T01:12:00.000Z | /*
* (C) Copyright 2014 Kurento (http://kurento.org/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "kmswebrtcbaseconnection.h"
#include <commons/kmsstats.h>
#include "kmsiceniceagent.h"
#define GST_CAT_DEFAULT kmswebrtcbaseconnection
GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT);
#define GST_DEFAULT_NAME "kmswebrtcbaseconnection"
G_DEFINE_TYPE (KmsWebRtcBaseConnection, kms_webrtc_base_connection,
G_TYPE_OBJECT);
enum
{
PROP_0,
PROP_ICE_AGENT,
PROP_STREAM_ID
};
gboolean
kms_webrtc_base_connection_configure (KmsWebRtcBaseConnection * self,
KmsIceBaseAgent * agent, const gchar * name)
{
self->agent = g_object_ref (agent);
self->name = g_strdup (name);
self->stream_id =
kms_ice_base_agent_add_stream (agent, self->name, self->min_port,
self->max_port);
if (g_strcmp0 (self->stream_id, "0") == 0) {
GST_ERROR_OBJECT (self, "Cannot add stream for %s.", name);
return FALSE;
}
return TRUE;
}
static gchar *kms_webrtc_base_connection_get_certificate_pem_default
(KmsWebRtcBaseConnection * self)
{
KmsWebRtcBaseConnectionClass *klass =
KMS_WEBRTC_BASE_CONNECTION_CLASS (G_OBJECT_GET_CLASS (self));
if (klass->get_certificate_pem ==
kms_webrtc_base_connection_get_certificate_pem_default) {
GST_WARNING_OBJECT (self,
"%s does not reimplement 'get_certificate_pem'",
G_OBJECT_CLASS_NAME (klass));
}
return NULL;
}
static void
kms_webrtc_base_connection_finalize (GObject * object)
{
KmsWebRtcBaseConnection *self = KMS_WEBRTC_BASE_CONNECTION (object);
GST_DEBUG_OBJECT (self, "finalize");
kms_ice_base_agent_remove_stream (self->agent, self->stream_id);
g_free (self->name);
g_free (self->stream_id);
g_clear_object (&self->agent);
g_rec_mutex_clear (&self->mutex);
/* chain up */
G_OBJECT_CLASS (kms_webrtc_base_connection_parent_class)->finalize (object);
}
static void
kms_webrtc_base_connection_init (KmsWebRtcBaseConnection * self)
{
g_rec_mutex_init (&self->mutex);
self->stats_enabled = FALSE;
}
static void
kms_webrtc_base_connection_set_latency_callback_default (KmsIRtpConnection *
obj, BufferLatencyCallback cb, gpointer user_data)
{
KmsWebRtcBaseConnection *self = KMS_WEBRTC_BASE_CONNECTION (obj);
self->cb = cb;
self->user_data = user_data;
}
static void
kms_webrtc_base_connection_collect_latency_stats_default (KmsIRtpConnection *
obj, gboolean enable)
{
KmsWebRtcBaseConnection *self = KMS_WEBRTC_BASE_CONNECTION (obj);
self->stats_enabled = enable;
}
static void
kms_webrtc_base_connection_get_property (GObject * object,
guint prop_id, GValue * value, GParamSpec * pspec)
{
KmsWebRtcBaseConnection *self = KMS_WEBRTC_BASE_CONNECTION (object);
KMS_WEBRTC_BASE_CONNECTION_LOCK (self);
switch (prop_id) {
case PROP_ICE_AGENT:
g_value_set_object (value, self->agent);
break;
case PROP_STREAM_ID:
g_value_set_string (value, self->stream_id);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
break;
}
KMS_WEBRTC_BASE_CONNECTION_UNLOCK (self);
}
static void
kms_webrtc_base_connection_class_init (KmsWebRtcBaseConnectionClass * klass)
{
GObjectClass *gobject_class;
gobject_class = G_OBJECT_CLASS (klass);
gobject_class->finalize = kms_webrtc_base_connection_finalize;
gobject_class->get_property = kms_webrtc_base_connection_get_property;
klass->get_certificate_pem =
kms_webrtc_base_connection_get_certificate_pem_default;
klass->set_latency_callback =
kms_webrtc_base_connection_set_latency_callback_default;
klass->collect_latency_stats =
kms_webrtc_base_connection_collect_latency_stats_default;
g_object_class_install_property (gobject_class, PROP_ICE_AGENT,
g_param_spec_object ("ice-agent", "Ice agent",
"The Ice agent.", KMS_TYPE_ICE_BASE_AGENT,
G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
g_object_class_install_property (gobject_class, PROP_STREAM_ID,
g_param_spec_string ("stream-id", "Stream identifier",
"The stream identifier.", NULL,
G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
GST_DEFAULT_NAME);
}
gchar *
kms_webrtc_base_connection_get_certificate_pem (KmsWebRtcBaseConnection * self)
{
KmsWebRtcBaseConnectionClass *klass =
KMS_WEBRTC_BASE_CONNECTION_CLASS (G_OBJECT_GET_CLASS (self));
return klass->get_certificate_pem (self);
}
void
kms_webrtc_base_connection_set_stun_server_info (KmsWebRtcBaseConnection * self,
const gchar * ip, guint port)
{
// TODO: This code should be independent of the type of ice agent
if (KMS_IS_ICE_NICE_AGENT (self->agent)) {
KmsIceNiceAgent *nice_agent = KMS_ICE_NICE_AGENT (self->agent);
g_object_set (kms_ice_nice_agent_get_agent (nice_agent),
"stun-server", ip, "stun-server-port", port, NULL);
}
}
void
kms_webrtc_base_connection_set_relay_info (KmsWebRtcBaseConnection * self,
const gchar * server_ip,
guint server_port,
const gchar * username, const gchar * password, TurnProtocol type)
{
KmsIceRelayServerInfo info;
info.server_ip = server_ip;
info.server_port = server_port;
info.username = username;
info.password = password;
info.type = type;
info.stream_id = self->stream_id;
kms_ice_base_agent_add_relay_server (self->agent, info);
}
void
kms_webrtc_base_connection_set_latency_callback (KmsIRtpConnection * self,
BufferLatencyCallback cb, gpointer user_data)
{
KmsWebRtcBaseConnectionClass *klass =
KMS_WEBRTC_BASE_CONNECTION_CLASS (G_OBJECT_GET_CLASS (self));
klass->set_latency_callback (self, cb, user_data);
}
void
kms_webrtc_base_connection_collect_latency_stats (KmsIRtpConnection * self,
gboolean enable)
{
KmsWebRtcBaseConnectionClass *klass =
KMS_WEBRTC_BASE_CONNECTION_CLASS (G_OBJECT_GET_CLASS (self));
klass->collect_latency_stats (self, enable);
}
| 28.524229 | 80 | 0.763243 | [
"object"
] |
72abcd82554bf66860643ba0132deffb10432b57 | 21,229 | h | C | src/utils/paddle_gserver_neural_network.h | pengdu/bubblefs | 9b27e191a287b3a1d012adfd3bab6a30629a5f33 | [
"BSD-3-Clause"
] | 1 | 2021-01-11T14:19:51.000Z | 2021-01-11T14:19:51.000Z | src/utils/paddle_gserver_neural_network.h | pengdu/bubblefs | 9b27e191a287b3a1d012adfd3bab6a30629a5f33 | [
"BSD-3-Clause"
] | null | null | null | src/utils/paddle_gserver_neural_network.h | pengdu/bubblefs | 9b27e191a287b3a1d012adfd3bab6a30629a5f33 | [
"BSD-3-Clause"
] | null | null | null | /* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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. */
// Paddle/paddle/gserver/gradientmachines/NeuralNetwork.h
// Paddle/paddle/gserver/gradientmachines/NeuralNetwork.cpp
#pragma once
#include <functional>
#include <map>
#include <memory>
#include "utils/paddle_proto.h"
#include "utils/paddle_gserver_dataproviders.h"
#include "utils/paddle_gserver_gradientmachines.h"
#include "utils/paddle_layer.h"
#include "utils/paddle_parameter.h"
namespace bubblefs {
namespace mypaddle {
/*
* @brief Init function for the parameters.
* @param paramId: the id of the parameter to init.
* @param para: the pointer to the parameter to init.
* @param sharedParams: the pointer to an array of the parameter to be shared.
* If it is null, no parameter sharing is used.
* Only CPU paramters can be shared.
* It handles CPU, CPU sparse, CPU sparse remote,
* and GPU parameters differently. If the type
* of a parameter is NORMAL. Basically nothing need to be done.
* CPU value: NORMAL.
* CPU param: NORMAL.
*
* CPU sparse value: NORMAL.
* CPU sparse gradient: MAT_SPARSE_ROW_AUTO_GROW.
*
* CPU sparse remote value: MAT_SPARSE_ROW_PREFETCH(_FULL_SIZE).
* CPU sparse remote gradient: MAT_SPARSE_ROW (!sharedParams)
* MAT_SPARSE_ROW_AUTO_GROW (sharedParams)
*
* GPU value: NORMAL
* GPU param: NORMAL
*/
void parameterInitNN(int paramId,
Parameter* para,
std::vector<ParameterPtr>* sharedParams);
class NeuralNetwork : public GradientMachine {
public:
virtual void init(const ModelConfig& config,
ParamInitCallback callback = nullptr,
const std::vector<ParameterType>& parameterTypes =
std::vector<ParameterType>{PARAMETER_VALUE,
PARAMETER_GRADIENT,
PARAMETER_MOMENTUM},
bool useGpu = FLAGS_use_gpu);
/**
* Connect two submodels and
* down-submodel's output become up-submodel's input.
* By default, connection is one by one,
* If the agent height is smaller than real layer, *height* has to be filled.
*
* @param realLayer The down-submodel's output layer.
* @param agentLayer The up-submodel's input agent layer.
*/
static void connect(LayerPtr agentLayer, LayerPtr realLayer, int height = 0);
void connect(std::string agentLayerName,
NeuralNetwork* srcNN,
std::string realLayerName);
virtual void prefetch(const std::vector<Argument>& inArgs);
virtual void forward(const std::vector<Argument>& inArgs,
std::vector<Argument>* outArgs,
PassType passType);
virtual void backward(const UpdateCallback& callback = nullptr);
virtual Argument getLayerOutput(const std::string& layerName);
const LayerPtr& getLayer(const std::string& layerName) const {
auto it = layerMap_.find(layerName);
CHECK(it != layerMap_.end()) << "Unknown layer " << layerName;
return it->second;
}
virtual void onPassEnd();
#ifndef PADDLE_MOBILE_INFERENCE
virtual Evaluator* makeEvaluator() const;
virtual void eval(Evaluator* evaluator) const;
#endif
virtual void resetState();
virtual void setOutputGrad(const std::vector<Argument>& args);
/// set machine state
virtual void setState(const MachineState& machineState);
/// get machine state
virtual void getState(MachineState& machineState);
static NeuralNetwork* create(const ModelConfig& config);
ParameterMap* getParameterMap() { return ¶meterMap_; }
/**
* @brief Access each layer as a for each loop.
* @param callback invoke with each layer.
*/
template <typename T>
void forEachLayer(T callback) {
for (auto& l : layers_) {
if (callback(l)) {
break;
}
}
}
static NeuralNetwork* newNeuralNetwork(const std::string& name = "",
NeuralNetwork* rootNetwork = nullptr);
const std::string& getName() const { return subModelName_; }
/// some finish work, like convert the weight format of MKLDNNLayers
void finish();
protected:
/**
* The constructor of NeuralNetwork.
* The sub networks can get parameters_ and parameterMap_
* from base NeuralNetwork.
*
* @param subModelName The name of sub-model.
* @param rootNetwork It used in MultiNetwork.
*/
NeuralNetwork(std::string subModelName = "",
NeuralNetwork* rootNetwork = nullptr)
: subModelName_(subModelName), rootNetwork_(rootNetwork) {}
std::string subModelName_;
ModelConfig config_;
std::vector<LayerPtr> layers_;
ParameterMap parameterMap_;
LayerMap layerMap_;
std::vector<DataLayerPtr> dataLayers_;
std::vector<LayerPtr> outputLayers_;
static std::map<std::string, bool> dllInitMap;
NeuralNetwork* rootNetwork_;
/// Whether parameter of this NN is initialized by its own
/// (i.e., not by callback supplied with the caller)
bool paramSelfInited_;
};
void parameterInitNN(int paramId,
Parameter* para,
std::vector<ParameterPtr>* sharedParams) {
// Create parameters values.
if (!para->useGpu() && sharedParams) {
para->enableSharedType(PARAMETER_VALUE,
(*sharedParams)[paramId]->getBuf(PARAMETER_VALUE),
(*sharedParams)[paramId]->getMat(PARAMETER_VALUE));
} else {
if (para->isSparseRemoteUpdate()) {
para->enableType(PARAMETER_VALUE,
FLAGS_loadsave_parameters_in_pserver
? Parameter::MAT_SPARSE_ROW_PREFETCH
: Parameter::MAT_SPARSE_ROW_PREFETCH_FULL_SIZE);
} else {
para->enableType(PARAMETER_VALUE);
}
}
// Create parameter gradients.
if (para->isSparseRemoteUpdate() && !sharedParams) {
para->enableType(PARAMETER_GRADIENT, Parameter::MAT_SPARSE_ROW);
} else if (para->isGradSparseUpdate()) {
para->enableType(PARAMETER_GRADIENT, Parameter::MAT_SPARSE_ROW_AUTO_GROW);
} else if (!para->isStatic()) {
para->enableType(PARAMETER_GRADIENT);
}
}
NeuralNetwork* NeuralNetwork::create(const ModelConfig& config) {
#ifndef PADDLE_MOBILE_INFERENCE
if (config.type() == "recurrent_nn") {
return newNeuralNetwork("root");
} else if (config.type() == "multi_nn") {
return new MultiNetwork("root");
} else {
return newNeuralNetwork();
}
#else
return new NeuralNetwork();
#endif
}
std::map<std::string, bool> NeuralNetwork::dllInitMap;
void NeuralNetwork::init(const ModelConfig& config,
ParamInitCallback callback,
const std::vector<ParameterType>& parameterTypes,
bool useGpu) {
using std::placeholders::_1;
using std::placeholders::_2;
ParamInitCallback paramCallback = nullptr;
if (callback != nullptr) {
paramSelfInited_ = false;
paramCallback = callback;
} else {
paramSelfInited_ = true;
paramCallback = std::bind(parameterInitNN, _1, _2, nullptr);
}
config_ = config;
if (rootNetwork_ != nullptr) {
// direct use parameters_ and parameterMap_ from base network
CHECK_EQ((size_t)config.parameters_size(),
rootNetwork_->getParameters().size());
parameters_ = rootNetwork_->getParameters();
parameterMap_ = *(rootNetwork_->getParameterMap());
} else {
parameters_.reserve(config.parameters_size());
for (const auto& para_config : config.parameters()) {
auto parameter = std::make_shared<Parameter>(para_config,
useGpu,
/*initialize=*/false);
paramCallback(parameters_.size(), parameter.get());
if (!callback) {
for (ParameterType type :
(parameter->isStatic()
? std::vector<ParameterType>{PARAMETER_VALUE}
: parameterTypes)) {
if (type != PARAMETER_VALUE && type != PARAMETER_GRADIENT) {
parameter->enableType(type);
}
}
}
parameter->setID(parameters_.size());
parameters_.push_back(parameter);
CHECK(!parameterMap_.count(parameter->getName()));
parameterMap_[parameter->getName()] = parameter;
}
}
auto layerCreate = [&](const LayerConfig& layer_config) {
auto layer = Layer::create(layer_config);
CHECK(layer) << "Create layer failed. Layer name:" << layer->getName();
layers_.push_back(layer);
CHECK(!layerMap_.count(layer->getName()));
layerMap_[layer->getName()] = layer;
};
auto subModelConfig = std::find_if(config.sub_models().begin(),
config.sub_models().end(),
[=](const SubModelConfig& sub_model) {
return sub_model.name() == subModelName_;
});
bool useSubModel = (subModelConfig != config.sub_models().end());
CHECK_EQ(useSubModel, !subModelName_.empty());
if (useSubModel) {
layers_.reserve(subModelConfig->layer_names_size());
for (const auto& layer_name : subModelConfig->layer_names()) {
auto layer_config =
std::find_if(config.layers().begin(),
config.layers().end(),
[=](const LayerConfig& layer_config) {
return layer_config.name() == layer_name;
});
CHECK(layer_config != config.layers().end());
layerCreate(*layer_config);
}
} else {
layers_.reserve(config.layers_size());
for (const auto& layer_config : config.layers()) {
bool useLayer = true;
if (config.has_external_config()) {
useLayer = true;
for (const auto& name : config.external_config().layer_names()) {
if (layer_config.name() == name) {
useLayer = false;
break;
}
}
}
if (useLayer) {
layerCreate(layer_config);
}
}
}
for (const auto& layer : layers_) {
layer->init(layerMap_, parameterMap_);
layer->initSubNetwork(this /*root*/, config_, parameterTypes, useGpu);
}
for (const auto& layer_name :
(useSubModel ? subModelConfig->input_layer_names()
: config.input_layer_names())) {
auto it = layerMap_.find(layer_name);
CHECK(it != layerMap_.end());
dataLayers_.push_back(std::dynamic_pointer_cast<DataLayer>(it->second));
}
for (const auto& layer_name :
(useSubModel ? subModelConfig->output_layer_names()
: config.output_layer_names())) {
auto it = layerMap_.find(layer_name);
CHECK(it != layerMap_.end());
outputLayers_.push_back(it->second);
}
}
void NeuralNetwork::connect(LayerPtr agentLayer,
LayerPtr realLayer,
int height) {
#ifndef PADDLE_MOBILE_INFERENCE
AgentLayer* agent = dynamic_cast<AgentLayer*>(agentLayer.get());
CHECK_NOTNULL(agent);
agent->setRealLayer(realLayer, height);
#endif
}
void NeuralNetwork::connect(std::string agentLayerName,
NeuralNetwork* srcNN,
std::string realLayerName) {
connect(this->getLayer(agentLayerName), srcNN->getLayer(realLayerName));
}
void NeuralNetwork::prefetch(const std::vector<Argument>& inArgs) {
CHECK_EQ(inArgs.size(), dataLayers_.size());
if (paramSelfInited_) {
for (auto& para : parameters_) {
if (para->isSparseRemoteUpdate()) {
auto mat = dynamic_cast<SparsePrefetchRowCpuMatrix*>(
para->getMat(PARAMETER_VALUE).get());
para->clearGradient();
if (mat) mat->clearIndices();
}
}
}
for (size_t i = 0; i != dataLayers_.size(); ++i) {
if (FLAGS_parallel_nn) {
const_cast<Argument&>(inArgs[i]).deviceId = -1;
}
dataLayers_[i]->setData(inArgs[i]);
}
for (auto& layer : layers_) {
layer->prefetch();
}
if (paramSelfInited_) {
for (auto& para : parameters_) {
if (para->isSparseRemoteUpdate()) {
auto mat = dynamic_cast<SparsePrefetchRowCpuMatrix*>(
para->getMat(PARAMETER_VALUE).get());
mat->setupIndices();
auto matGrad = dynamic_cast<SparseRowCpuMatrix*>(
para->getMat(PARAMETER_GRADIENT).get());
matGrad->reserveStore();
}
}
}
}
void NeuralNetwork::forward(const std::vector<Argument>& inArgs,
std::vector<Argument>* outArgs,
PassType passType) {
CHECK_EQ(inArgs.size(), dataLayers_.size());
outArgs->resize(outputLayers_.size());
for (size_t i = 0; i != dataLayers_.size(); ++i) {
dataLayers_[i]->setData(inArgs[i]);
}
gLayerStackTrace.set_stage(true);
{
for (auto& layer : layers_) {
REGISTER_TIMER_INFO("ForwardTimer", layer->getName().c_str());
gLayerStackTrace.push(layer->getName());
layer->forward(passType);
gLayerStackTrace.pop(layer->getName());
}
}
outArgs->clear();
outArgs->reserve(outputLayers_.size());
for (auto& layer : outputLayers_) {
outArgs->push_back(layer->getOutput());
}
}
void NeuralNetwork::resetState() {
for (auto& layer : layers_) {
layer->resetState();
}
}
void NeuralNetwork::setState(const MachineState& machineState) {
for (size_t i = 0; i < layers_.size(); i++) {
if (machineState[i] != nullptr) {
layers_[i]->setState(machineState[i]);
}
}
}
void NeuralNetwork::getState(MachineState& machineState) {
machineState.clear();
machineState.reserve(layers_.size());
for (auto& layer : layers_) {
LayerStatePtr p = layer->getState();
machineState.push_back(p);
}
}
void NeuralNetwork::backward(const UpdateCallback& callback) {
gLayerStackTrace.set_stage(false);
FOR_EACH_R(layer, layers_) {
REGISTER_TIMER_INFO("BackwardTimer", (*layer)->getName().c_str());
gLayerStackTrace.push((*layer)->getName());
if ((*layer)->needGradient()) {
(*layer)->backward(callback);
}
gLayerStackTrace.pop((*layer)->getName());
}
}
void NeuralNetwork::finish() {
#ifdef PADDLE_WITH_MKLDNN
FOR_EACH_R(layer, layers_) {
MKLDNNLayerPtr dnnLayer = std::dynamic_pointer_cast<MKLDNNLayer>(*layer);
if (dnnLayer) {
dnnLayer->convertWeightsToPaddle();
}
}
#endif
}
Argument NeuralNetwork::getLayerOutput(const std::string& layerName) {
return getLayer(layerName)->getOutput();
}
void NeuralNetwork::onPassEnd() {
for (auto& layer : layers_) {
layer->onPassEnd();
}
}
#ifndef PADDLE_MOBILE_INFERENCE
class CombinedEvaluator : public Evaluator {
public:
void addEvaluator(std::unique_ptr<Evaluator>&& evaluator) {
evaluators_.emplace_back(std::move(evaluator));
}
void start() override {
for (auto& evaluator : evaluators_) {
evaluator->start();
}
}
void finish() override {
for (auto& evaluator : evaluators_) {
evaluator->finish();
}
}
void eval(const NeuralNetwork& nn) override {
for (auto& evaluator : evaluators_) {
evaluator->eval(nn);
}
}
real evalImp(std::vector<Argument>& arguments) override {
(void)arguments;
return -1;
}
void printStats(std::ostream& os) const override {
for (auto& evaluator : evaluators_) {
evaluator->printStats(os);
os << ' ';
}
}
void distributeEval(ParameterClient2* client) override {
for (auto& evaluator : evaluators_) {
evaluator->distributeEval(client);
}
}
protected:
std::vector<std::unique_ptr<Evaluator>> evaluators_;
// Evaluator interface
public:
/**
* @brief getNames will return all inside evaluators' names.
* @param names [out]: return names.
*/
void getNames(std::vector<std::string>* names) override {
for (auto& eval : evaluators_) {
eval->getNames(names);
}
}
/**
* @brief getValue could get all inside evaluators' value.
*/
real getValue(const std::string& name, Error* err) const override {
return this->getMethodHelper<real>(
name, err, [&name, err](const std::unique_ptr<Evaluator>& eval) {
return eval->getValue(name, err);
});
}
/**
* @brief getType could get all inside evaluators' type.
*/
std::string getType(const std::string& name, Error* err) const override {
return this->getMethodHelper<std::string>(
name, err, [&name, err](const std::unique_ptr<Evaluator>& eval) {
return eval->getType(name, err);
});
}
private:
template <typename T>
T getMethodHelper(const std::string& name,
Error* err,
const std::function<T(const std::unique_ptr<Evaluator>&)>&
callback) const {
for (auto& eval : evaluators_) {
std::vector<std::string> names;
eval->getNames(&names);
if (std::find(names.begin(), names.end(), name) != names.end()) {
return callback(eval);
}
}
*err = Error("No such key %s", name.c_str());
return T();
}
};
class SubnetEvaluator : public CombinedEvaluator {
public:
SubnetEvaluator(const std::string& layerName,
std::unique_ptr<Evaluator>&& evaluator)
: layerName_(layerName) {
addEvaluator(std::move(evaluator));
}
void eval(const NeuralNetwork& nn) override {
const LayerPtr& layer = nn.getLayer(layerName_);
CHECK(layer) << "Nonexisted layer: " << layerName_ << " in submodel "
<< nn.getName();
bool accessed = false;
layer->accessSubNetwork([this, &accessed](NeuralNetwork& subnet) {
subnet.eval(evaluators_[0].get());
accessed = true;
});
CHECK(accessed) << "There is no subnetwork for layer " << layerName_
<< " in submodel " << nn.getName();
}
protected:
std::string layerName_;
};
Evaluator* NeuralNetwork::makeEvaluator() const {
CombinedEvaluator* combinedEvaluator = new CombinedEvaluator();
auto subModelConfig = std::find_if(config_.sub_models().begin(),
config_.sub_models().end(),
[=](const SubModelConfig& sub_model) {
return sub_model.name() == subModelName_;
});
bool useSubModel = (subModelConfig != config_.sub_models().end());
CHECK_EQ(useSubModel, !subModelName_.empty());
if (useSubModel) {
// create the evaluators that belong to CURRENT submodel
for (int i = 0; i < subModelConfig->evaluator_names_size(); ++i) {
// find evaluator by name
auto thisEvalConfig = std::find_if(
config_.evaluators().begin(),
config_.evaluators().end(),
[=](const EvaluatorConfig& ecfg) {
return ecfg.name() == subModelConfig->evaluator_names(i);
});
bool validConfig = (thisEvalConfig != config_.evaluators().end());
if (validConfig) {
std::unique_ptr<Evaluator> evaluator(
Evaluator::create(*thisEvalConfig));
combinedEvaluator->addEvaluator(std::move(evaluator));
}
}
for (auto& layer : layers_) {
layer->accessSubNetwork(
[layer, combinedEvaluator](NeuralNetwork& subnet) {
std::unique_ptr<Evaluator> subEvaluator(new SubnetEvaluator(
layer->getName(),
std::unique_ptr<Evaluator>(subnet.makeEvaluator())));
combinedEvaluator->addEvaluator(std::move(subEvaluator));
});
}
} else {
for (const EvaluatorConfig& evalConfig : config_.evaluators()) {
std::unique_ptr<Evaluator> evaluator(Evaluator::create(evalConfig));
combinedEvaluator->addEvaluator(std::move(evaluator));
}
}
return combinedEvaluator;
}
void NeuralNetwork::eval(Evaluator* evaluator) const { evaluator->eval(*this); }
#endif
void NeuralNetwork::setOutputGrad(const std::vector<Argument>& args) {
CHECK_GE(outputLayers_.size(), args.size());
for (size_t i = 0; i < args.size(); ++i) {
outputLayers_[i]->getOutput().grad = args[i].grad;
}
}
extern NeuralNetwork* newCustomNerualNetwork(const std::string& name,
NeuralNetwork* network)
__attribute__((weak));
NeuralNetwork* NeuralNetwork::newNeuralNetwork(const std::string& name,
NeuralNetwork* rootNetwork) {
if (newCustomNerualNetwork) {
return newCustomNerualNetwork(name, rootNetwork);
} else {
return new NeuralNetwork(name, rootNetwork);
}
}
} // namespace mypaddle
} // namespace bubblefs | 32.559816 | 80 | 0.630223 | [
"vector",
"model"
] |
6066936383b546ed037f947c548f34b4c1856dc7 | 18,618 | h | C | PooToolsSource/UniTool/PMacros.h | crazypoo/PTools | a286c29e02eaddb5df1dc66e54054c9bdd4f9ff3 | [
"MIT"
] | 9 | 2018-10-19T09:49:33.000Z | 2021-08-14T13:11:49.000Z | PooToolsSource/UniTool/PMacros.h | crazypoo/PTools | a286c29e02eaddb5df1dc66e54054c9bdd4f9ff3 | [
"MIT"
] | 1 | 2019-08-06T01:19:00.000Z | 2019-08-06T01:19:00.000Z | PooToolsSource/UniTool/PMacros.h | crazypoo/PTools | a286c29e02eaddb5df1dc66e54054c9bdd4f9ff3 | [
"MIT"
] | 3 | 2019-08-05T15:53:35.000Z | 2020-11-30T00:40:09.000Z | //
// PHong.h
// PTools
//
// Created by crazypoo on 14/9/14.
// Copyright (c) 2014年 crazypoo. All rights reserved.
//
#import "Utils.h"
#ifndef PTools_PMacros_h
#define PTools_PMacros_h
#define kDevLikeFont @"HelveticaNeue-Light"
#define kDevLikeFont_Bold @"HelveticaNeue-Medium"
#define kDevAlpha 0.45
#define kDevMaskBackgroundColor kRGBAColorDecimals(0, 0, 0, kDevAlpha)
#define kDevButtonHighlightedColor kRGBAColor(242, 242, 242, 1)
#pragma mark ---------------> 判断当前的iPhone设备/系统版本
/*! @brief 当前系统版本与系统v是否匹配
*/
#define SYSTEM_VERSION_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
/*! @brief 当前系统版本是否大于v系统
*/
#define SYSTEM_VERSION_GREATER_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
/*! @brief 当前系统版本是否大于等于v系统
*/
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
/*! @brief 当前系统版本是否小于v系统
*/
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
/*! @brief 当前系统版本是否小于等于v系统
*/
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)
/*! @brief 判断是否iOS8之前的系统版本
*/
#define IOS8before [[[UIDevice currentDevice] systemVersion] floatValue] < 8
/*! @brief 判断是否为iPhone
*/
#define IS_IPHONE (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone)
/*! @brief 判断是否为iPad
*/
#define IS_IPAD (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
/*! @brief 判断是否为ipod
*/
#define IS_IPOD ([[[UIDevice currentDevice] model] isEqualToString:@"iPod touch"])
/*! @brief 判断 iOS 8 或更高的系统版本
*/
#define IOS_VERSION_8_OR_LATER (([[[UIDevice currentDevice] systemVersion] floatValue] >=8.0)? (YES):(NO))
#pragma mark ---------------> 屏幕
/*! @brief 屏幕为类似iPhone4的机型
*/
#define iPhone4 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 960), [[UIScreen mainScreen] currentMode].size) : NO)
/*! @brief 屏幕为类似iPhone5的机型
*/
#define iPhone5 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640, 1136), [[UIScreen mainScreen] currentMode].size) : NO)
/*! @brief 屏幕为类似iPhone6的机型
*/
#define iPhone6 ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(750, 1334), [[UIScreen mainScreen] currentMode].size) : NO)
/*! @brief 屏幕为类似iPhone6P的机型
*/
#define iPhone6P ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2208), [[UIScreen mainScreen] currentMode].size) : NO)
/*! @brief 屏幕为类似iPadAir的机型
*/
#define iPad_Air ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(768, 1024), [[UIScreen mainScreen] currentMode].size) : NO)
/*! @brief 屏幕为类似iPhoneX的机型
*/
#define kDevice_Is_iPhoneX ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1125, 2436), [[UIScreen mainScreen] currentMode].size) : NO)
/*! @brief 屏幕为类似iPhoneXR的机型
*/
#define kDevice_Is_iPhoneXR ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(828, 1792), [[UIScreen mainScreen] currentMode].size) : NO)
/*! @brief 屏幕为类似iPhoneXS MAX的机型
*/
#define kDevice_Is_iPhoneXS_MAX ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(1242, 2688), [[UIScreen mainScreen] currentMode].size) : NO)
/*! @brief 当前屏幕宽度
*/
#define kSCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
/*! @brief 当前屏幕高度
*/
#define kSCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
/*! @brief 当前屏幕Size
*/
#define kSCREEN_SIZE [UIScreen mainScreen].bounds.size
/*! @brief 当前屏幕比例
*/
#define kSCREEN_SCALE ([UIScreen mainScreen].scale)
/*! @brief 获取KeyWindow
*/
#define kKEYWINDOW [UIApplication sharedApplication].keyWindow
/*! @brief 电池栏菊花转动
*/
#define kShowNetworkActivityIndicator() [UIApplication sharedApplication].networkActivityIndicatorVisible = YES
/*! @brief 电池栏菊花停止转动
*/
#define kHideNetworkActivityIndicator() [UIApplication sharedApplication].networkActivityIndicatorVisible = NO
/*! @brief 电池栏菊花设置是否转动
*/
#define NetworkActivityIndicatorVisible(x) [UIApplication sharedApplication].networkActivityIndicatorVisible = x
/*! @brief 获取view的宽度
*/
#define kGetViewWidth(view) view.frame.size.width
/*! @brief 获取view的高度
*/
#define kGetViewHeight(view) view.frame.size.height
/*! @brief 获取view的x坐标
*/
#define kGetViewX(view) view.frame.origin.x
/*! @brief 获取view的y坐标
*/
#define kGetViewY(view) view.frame.origin.y
/*! @brief 获取垂直居中的x(parent的高度/2-child的高度/2)
*/
#define CENTER_VERTICALLY(parent,child) floor((parent.frame.size.height - child.frame.size.height) / 2)
/*! @brief 获取水平居中的y(parent的宽度/2-child的宽度/2)
*/
#define CENTER_HORIZONTALLY(parent,child) floor((parent.frame.size.width - child.frame.size.width) / 2)
/*! @brief 创建的view居中于parentView
* @see [[UIView alloc] initWithFrame:(CGRect){CENTER_IN_PARENT(parentView,500,500),CGSizeMake(500,500)}];
*/
#define CENTER_IN_PARENT(parent,childWidth,childHeight) CGPointMake(floor((parent.frame.size.width - childWidth) / 2),floor((parent.frame.size.height - childHeight) / 2))
/*! @brief 创建的view,x坐标居中于parentView
*/
#define CENTER_IN_PARENT_X(parent,childWidth) floor((parent.frame.size.width - childWidth) / 2)
/*! @brief 创建的view,y坐标居中于parentView
*/
#define CENTER_IN_PARENT_Y(parent,childHeight) floor((parent.frame.size.height - childHeight) / 2)
/*! @brief view的底部坐标y
*/
#define BOTTOM(view) (view.frame.origin.y + view.frame.size.height)
/*! @brief view的右边坐标x
*/
#define RIGHT(view) (view.frame.origin.x + view.frame.size.width)
/*! @brief 状态栏的底部坐标y
*/
#define kScreenStatusBottom ([UIApplication sharedApplication].statusBarFrame.origin.y + [UIApplication sharedApplication].statusBarFrame.size.height)
/*! @brief nav高度
*/
#define HEIGHT_NAV 44.f
/*! @brief 横屏nav高度
*/
#define HEIGHT_NAV_LandSpaceLeftOrRight 32.f
/*! @brief status高度 (iPhoneX除外)
*/
#define HEIGHT_STATUS (isIPhoneXSeries() ? 44.f : 20.f)
/*! @brief 普通导航栏高度 (nav高度+status高度)
*/
#define HEIGHT_NAVBAR HEIGHT_NAV + HEIGHT_STATUS
/*! @brief tabbara安全区域高度
*/
#define HEIGHT_TABBAR_SAFEAREA (isIPhoneXSeries() ? 34.f : 0.f)
/*! @brief tabbar高度
*/
#define HEIGHT_TABBAR 49.0f
/*! @brief tabbar总高度
*/
#define HEIGHT_TABBAR_TOTAL (HEIGHT_TABBAR + HEIGHT_TABBAR_SAFEAREA)
/*! @brief NAV+TAB总高度
*/
#define HEIGHT_NAVPLUSTABBAR_TOTAL (HEIGHT_TABBAR_TOTAL + HEIGHT_NAVBAR)
/*! @brief 大标题高度
*/
#define HEIGHT_LARGETITLE 52.f
/*! @brief iPhone带大标题高度
*/
#define HEIGHT_IPHONESTATUSBARXNAVXLARGETITLE HEIGHT_STATUS + HEIGHT_NAV + HEIGHT_LARGETITLE
/*! @brief Picker一般高度
*/
#define HEIGHT_PICKER 216.f
/*! @brief PickerToolBar一般高度
*/
#define HEIGHT_PICKERTOOLBAR 44.f
/*! @brief Button一般高度
*/
#define HEIGHT_BUTTON 44.f
/*! @brief 当前屏幕的宽与320的比例
*/
#define SCREEN_POINT (float)SCREEN_WIDTH/320.f
/*! @brief 当前屏幕的高度与480的比例
*/
#define SCREEN_H_POINT (float)SCREEN_HEIGHT/480.f
/*! @brief PS字号转换成iOS字号
*/
#define kPSFontToiOSFont(pixel) (pixel*3/4)
/*! @brief 设置View的tag属性
*/
#define kVIEWWITHTAG(_OBJECT, _TAG) [_OBJECT viewWithTag : _TAG]
/*! @brief R屏
*/
#define isRetina ([UIScreen instancesRespondToSelector:@selector(currentMode)] ? CGSizeEqualToSize(CGSizeMake(640.f, 960.f), [[UIScreen mainScreen] currentMode].size) : NO)
/*! @brief SaveArea适配
*/
#define adjustsScrollViewInsets(scrollView)\
do {\
_Pragma("clang diagnostic push")\
_Pragma("clang diagnostic ignored \"-Warc-performSelector-leaks\"")\
if ([scrollView respondsToSelector:NSSelectorFromString(@"setContentInsetAdjustmentBehavior:")]) {\
NSMethodSignature *signature = [UIScrollView instanceMethodSignatureForSelector:@selector(setContentInsetAdjustmentBehavior:)];\
NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];\
NSInteger argument = 2;\
invocation.target = scrollView;\
invocation.selector = @selector(setContentInsetAdjustmentBehavior:);\
[invocation setArgument:&argument atIndex:2];\
[invocation retainArguments];\
[invocation invoke];\
}\
_Pragma("clang diagnostic pop")\
} while (0)
/*! @brief AppDelegateWindow
*/
#define kAppDelegateWindow [[[UIApplication sharedApplication] delegate] window]
#pragma mark ---------------> 通知中心
/*! @brief [NSNotificationCenter defaultCenter]
*/
#define kNotificationCenter [NSNotificationCenter defaultCenter]
#pragma mark ---------------> 颜色
/*! @brief 随机颜色
*/
#define kRandomColor [UIColor colorWithRed:arc4random_uniform(256)/255.0 green:arc4random_uniform(256)/255.0 blue:arc4random_uniform(256)/255.0 alpha:1.0]
/*! @brief 随机颜色 (带Alpha值)
*/
#define kRandomColorWithAlpha(s) [UIColor colorWithRed:arc4random_uniform(256)/255.0 green:arc4random_uniform(256)/255.0 blue:arc4random_uniform(256)/255.0 alpha:s]
/*! @brief 设置RGB颜色
*/
#define kRGBColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]
/*! @brief 设置RGB颜色 (带Alpha值)
*/
#define kRGBAColor(r, g, b, a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:a]
/*! @brief 设置RGB颜色小数形式
*/
#define kRGBColorDecimals(r, g, b) [UIColor colorWithRed:(r) green:(g) blue:(b) alpha:1.0]
/*! @brief 设置RGB颜色小数形式(带Alpha值)
*/
#define kRGBAColorDecimals(r, g, b, a) [UIColor colorWithRed:(r) green:(g) blue:(b) alpha:a]
/*! @brief clear背景颜色
*/
#define kClearColor [UIColor clearColor]
/*! @brief 16进制RGB的颜色转换
*/
#define kColorFromHex(rgbValue) [UIColor \
colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 \
green:((float)((rgbValue & 0xFF00) >> 8))/255.0 \
blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
#pragma mark ---------------> judge the simulator or hardware device 判断是真机还是模拟器
/*! @brief 如果是真机
*/
#if TARGET_OS_IPHONE
//iPhone Device
#endif
/*! @brief 如果是模拟器
*/
#if TARGET_IPHONE_SIMULATOR
//iPhone Simulator
#endif
#pragma mark ---------------> 弱引用/强引用
/*! @brief 弱引用
*/
#define kWeakSelf(type) __weak typeof(type) weak##type = type;
/*! @brief 强引用
*/
#define kStrongSelf(type) __strong typeof(type) type = weak##type;
#pragma mark ---------------> 设置 view 圆角和边框
/*! @brief 设置 view 圆角和边框
*/
#define kViewBorderRadius(View, Radius, Width, Color)\
\
[View.layer setCornerRadius:(Radius)];\
[View.layer setMasksToBounds:YES];\
[View.layer setBorderWidth:(Width)];\
[View.layer setBorderColor:[Color CGColor]]
#pragma mark ---------------> 使用 ARC 和 MRC
/*! @brief 判断ARC或者MRC
*/
#if __has_feature(objc_arc)
// ARC
#else
// MRC
#endif
#pragma mark ---------------> 沙盒目录文件
/*! @brief 获取temp
*/
#define kPathTemp NSTemporaryDirectory()
/*! @brief 获取沙盒 Document
*/
#define kPathDocument [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]
/*! @brief 获取沙盒 Cache
*/
#define kPathCache [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject]
#pragma mark ---------------> NAV返回方法
/*! @brief nav返回上一层
*/
#define kReturnsToTheUpperLayer [self.navigationController popViewControllerAnimated:YES];
#pragma mark ---------------> 获取当前语言
/*! @brief 获取当前语言
*/
#define kCurrentLanguage ([[NSLocale preferredLanguages] objectAtIndex:0])
#pragma mark ---------------> ----------------------ABOUT IMAGE 图片 ----------------------------
/*! @brief 读取本地图片 (ContentsOfFile形式读取,带格式)
*/
#define kLOADIMAGE(file,ext) [UIImage imageWithContentsOfFile:[[NSBundle mainBundle]pathForResource:file ofType:ext]]
/*! @brief 定义UIImage对象 (ContentsOfFile形式读取,不带格式)
*/
#define kIMAGE(A) [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:A ofType:nil]]
/*! @brief 定义UIImage对象 (Name形式读取)
* @attention 优先使用前两种宏定义(kLOADIMAGE(file,ext),kIMAGE(A)),性能高于后面.
*/
#define kImageNamed(_pointer) [UIImage imageNamed:_pointer]
#pragma mark ---------------> 打印
/*! @brief 强化NSLog
*/
#define PNSLog(format, ...) do {fprintf(stderr, "%s:%d\t%s\n", [[[NSString stringWithUTF8String: __FILE__] lastPathComponent] UTF8String], __LINE__, [[NSString stringWithFormat: format, ## __VA_ARGS__] UTF8String]);fprintf(stderr, "我这里是打印,不要慌,我路过的😂😂😂😂😂😂😂😂😂😂😂😂\n");}while (0)
#pragma mark ---------------> NSUserDefaults 实例化
/*! @brief NSUserDefaults 实例化
*/
#define USER_DEFAULT [NSUserDefaults standardUserDefaults]
#pragma mark ---------------> 存储对象
/*! @brief 储存数据NSUserDefaults
*/
#define kUserDefaultSetObjectForKey(__VALUE__,__KEY__) \
{\
[USER_DEFAULT setObject:__VALUE__ forKey:__KEY__];\
[USER_DEFAULT synchronize];\
}
/*! @brief 获得存储的对象NSUserDefaults
*/
#define kUserDefaultObjectForKey(__KEY__) [USER_DEFAULT objectForKey:__KEY__]
/*! @brief 删除对象NSUserDefaults
*/
#define kUserDefaultRemoveObjectForKey(__KEY__) \
{\
[USER_DEFAULT removeObjectForKey:__KEY__];\
[USER_DEFAULT synchronize];\
}
/*! @brief 修改data.plist文件
*/
#define PLIST_TICKET_INFO_EDIT [NSHomeDirectory() stringByAppendingString:@"/Documents/data.plist"]
#pragma mark ---------------> TABLEVIEW
/*! @brief 初始化某TableViewCell
*/
#define kTableViewCellAlloc(__CLASS__,__INDETIFIER__) [[__CLASS__ alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:(__INDETIFIER__)]
/*! @brief 初始化某TableViewCell的Dequeue
*/
#define kTableViewCellDequeueInit(__INDETIFIER__) [tableView dequeueReusableCellWithIdentifier:(__INDETIFIER__)];
/*! @brief 当某TableViewCell为空时初始化cell
*/
#define kTableViewCellDequeue(__CELL__,__CELLCLASS__,__INDETIFIER__) \
{\
if (__CELL__ == nil) {\
__CELL__ = [[__CELLCLASS__ alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:__INDETIFIER__];\
}\
}
/*! @brief 当某TableViewCell为空时初始化cell (自定义Style)
*/
#define kTableViewCellDequeueWithStyle(__CELL__,__CELLCLASS__,__STYLE__,__INDETIFIER__) \
{\
if (__CELL__ == nil) {\
__CELL__ = [[__CELLCLASS__ alloc]initWithStyle:__STYLE__ reuseIdentifier:__INDETIFIER__];\
}\
}
/*! @brief 初始化TableViewCell
*/
#define kTableCellFullInit(__CELLNAME__,__CELLCLASSNAME__,__STYLE__,__INDETIFIER__) \
__CELLCLASSNAME__ *__CELLNAME__ = nil; \
if (__CELLNAME__ == nil) \
{ \
__CELLNAME__ = [[__CELLCLASSNAME__ alloc]initWithStyle:__STYLE__ reuseIdentifier:__INDETIFIER__]; \
} \
else \
{ \
while ([__CELLNAME__.contentView.subviews lastObject] != nil) { \
[(UIView *)[__CELLNAME__.contentView.subviews lastObject] removeFromSuperview]; \
} \
}
#pragma mark ---------------> Show Alert, brackets is the parameters. 宏定义一个弹窗方法,括号里面是方法的参数
/*! @brief 定义一个简单的取消弹出框
*/
#define ShowAlert(s) [[[UIAlertView alloc] initWithTitle:@"OPPS!" message:s delegate:self cancelButtonTitle:@"cancel" otherButtonTitles: @"OK"]show];
#endif
#pragma mark ---------------> GCD
/*! @brief GCDGlobal
*/
#define GCDWithGlobal(block) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{block})
/*! @brief GCDMain
*/
#define GCDWithMain(block) dispatch_async(dispatch_get_main_queue(),block)
/* @brief GCD延时执行
*/
#define GCDAfter(time,block) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(time * NSEC_PER_SEC)), dispatch_get_main_queue(), block);
/*! @brief GCD (一次性执行)
*/
#define kDISPATCH_ONCE_BLOCK(onceBlock) static dispatch_once_t onceToken; dispatch_once(&onceToken, onceBlock);
/*! @brief GCD (在Main线程上运行)
*/
#define kDISPATCH_MAIN_THREAD(mainQueueBlock) dispatch_async(dispatch_get_main_queue(), ^{mainQueueBlock});
/*! @brief GCD (开启异步线程)
*/
#define kDISPATCH_GLOBAL_QUEUE_DEFAULT(globalQueueBlock) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{globalQueueBlock});
#pragma mark ---------------> 单例化 一个类
/*! @brief 创建单例
*/
#define SYNTHESIZE_SINGLETON_FOR_CLASS(classname) \
\
static classname *shared##classname = nil; \
\
+ (classname *)shared##classname \
{ \
@synchronized(self) \
{ \
if (shared##classname == nil) \
{ \
shared##classname = [[self alloc] init]; \
} \
} \
\
return shared##classname; \
} \
\
+ (id)allocWithZone:(NSZone *)zone \
{ \
@synchronized(self) \
{ \
if (shared##classname == nil) \
{ \
shared##classname = [super allocWithZone:zone]; \
return shared##classname; \
} \
} \
\
return nil; \
} \
\
- (id)copyWithZone:(NSZone *)zone \
{ \
return self; \
}
#pragma mark ---------------> 快速查询一段代码的执行时间
/*! @brief 快速查询一段代码的执行时间 (TICK)
* @see 用法TICK(do your work here)TOCK
*/
#define TICK NSDate *startTime = [NSDate date];
/*! @brief 快速查询一段代码的执行时间 (TOCK)
* @see 用法TICK(do your work here)TOCK
*/
#define TOCK NSLog(@"Time:%f", -[startTime timeIntervalSinceNow]);
#pragma mark ---------------> 设置默认字体&字体大小
/*! @brief 设置默认字体&字体大小
*/
#define kDEFAULT_FONT(n,s) [UIFont fontWithName:n size:s]
/*! @brief 屏幕宽比例 (6SP为对比)
*/
#define kScreenWidthRatio (UIScreen.mainScreen.bounds.size.width / 375.0)
/*! @brief 屏幕高比例 (6SP为对比)
*/
#define kScreenHeightRatio (UIScreen.mainScreen.bounds.size.height / 667.0)
/*! @brief 实际x宽 (6SP为对比)
*/
#define kAdaptedWidth(x) ceilf((x) * kScreenWidthRatio)
/*! @brief 实际x高 (6SP为对比)
*/
#define kAdaptedHeight(x) ceilf((x) * kScreenHeightRatio)
/*! @brief 实际系统字体字号R的大小 (6SP为对比)
*/
#define kAdaptedFontSize(R) [UIFont systemFontOfSize:kAdaptedWidth(R)]
/*! @brief 实际自定义字体字号R的大小 (6SP为对比)
*/
#define kAdaptedOtherFontSize(n,R) kDEFAULT_FONT(n,kAdaptedWidth(R))
#pragma mark ---------------> 创建返回按钮
/*! @brief 创建返回按钮 (可以自定义图片)
*/
#define kCreatReturnButton(imageName,acttion) UIButton *leftNavBtn = [UIButton buttonWithType:UIButtonTypeCustom];leftNavBtn.frame = CGRectMake(0, 0, 44, 44);[leftNavBtn setImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];[leftNavBtn addTarget:self action:@selector(acttion) forControlEvents:UIControlEventTouchUpInside];[self.navigationItem setLeftBarButtonItem:[[UIBarButtonItem alloc] initWithCustomView:leftNavBtn]];
#pragma mark ---------------> 由角度转换弧度 由弧度转换角度
/*! @brief 角度转弧度
*/
#define PDegreesToRadian(x) (M_PI * (x) / 180.0)
/*! @brief 弧度转角度
*/
#define PRadianToDegrees(radian) (radian*180.0)/(M_PI)
#pragma mark ---------------> 判断是否为空
/*! @brief 字符串是否为空
*/
#define kStringIsEmpty(str) ([str isKindOfClass:[NSNull class]] || str == nil || [str length] < 1 ? YES : NO )
/*! @brief 数组是否为空
*/
#define kArrayIsEmpty(array) (array == nil || [array isKindOfClass:[NSNull class]] || array.count == 0)
/*! @brief 字典是否为空
*/
#define kDictIsEmpty(dic) (dic == nil || [dic isKindOfClass:[NSNull class]] || dic.allKeys == 0)
/*! @brief 是否是空对象
*/
#define kObjectIsEmpty(_object) (_object == nil \
|| [_object isKindOfClass:[NSNull class]] \
|| ([_object respondsToSelector:@selector(length)] && [(NSData *)_object length] == 0) \
|| ([_object respondsToSelector:@selector(count)] && [(NSArray *)_object count] == 0))
| 34.670391 | 440 | 0.731228 | [
"model"
] |
6072563d4a5ee5856ae6942fbbb07863c663d446 | 55,717 | h | C | google/cloud/ml/v1beta1/model_service.grpc.pb.h | allquixotic/kynnaugh-cc | 8b4d0cdb7e6e3cae76aba43507bb56cee225c36f | [
"Apache-2.0"
] | 3 | 2017-01-09T10:45:00.000Z | 2018-12-18T19:57:13.000Z | google/cloud/ml/v1beta1/model_service.grpc.pb.h | allquixotic/kynnaugh-cc | 8b4d0cdb7e6e3cae76aba43507bb56cee225c36f | [
"Apache-2.0"
] | null | null | null | google/cloud/ml/v1beta1/model_service.grpc.pb.h | allquixotic/kynnaugh-cc | 8b4d0cdb7e6e3cae76aba43507bb56cee225c36f | [
"Apache-2.0"
] | null | null | null | // Generated by the gRPC protobuf plugin.
// If you make any local change, they will be lost.
// source: google/cloud/ml/v1beta1/model_service.proto
// Original file comments:
// Copyright 2016 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef GRPC_google_2fcloud_2fml_2fv1beta1_2fmodel_5fservice_2eproto__INCLUDED
#define GRPC_google_2fcloud_2fml_2fv1beta1_2fmodel_5fservice_2eproto__INCLUDED
#include "google/cloud/ml/v1beta1/model_service.pb.h"
#include <grpc++/impl/codegen/async_stream.h>
#include <grpc++/impl/codegen/async_unary_call.h>
#include <grpc++/impl/codegen/method_handler_impl.h>
#include <grpc++/impl/codegen/proto_utils.h>
#include <grpc++/impl/codegen/rpc_method.h>
#include <grpc++/impl/codegen/service_type.h>
#include <grpc++/impl/codegen/status.h>
#include <grpc++/impl/codegen/stub_options.h>
#include <grpc++/impl/codegen/sync_stream.h>
namespace grpc {
class CompletionQueue;
class Channel;
class RpcService;
class ServerCompletionQueue;
class ServerContext;
} // namespace grpc
namespace google {
namespace cloud {
namespace ml {
namespace v1beta1 {
// Copyright 2016 Google Inc. All Rights Reserved.
//
// Proto file for the Machine Learning Service
// Describes the 'models service' to work with the 'model' and 'version'
// resources.
//
// Provides methods that create and manage machine learning models and their
// versions.
//
// A model in this context is a container for versions. The model can't provide
// predictions without first having a version created for it.
//
// Each version is a trained machine learning model, and each is assumed to be
// an iteration of the same machine learning problem as the other versions of
// the same model.
//
// Your project can define multiple models, each with multiple versions.
//
// The basic life cycle of a model is:
//
// * Create and train the machine learning model and save it to a
// Google Cloud Storage location.
// * Use
// [projects.models.create](/ml/reference/rest/v1beta1/projects.models/create)
// to make a new model in your project.
// * Use
// [projects.models.versions.create](/ml/reference/rest/v1beta1/projects.models.versions/create)
// to deploy your saved model.
// * Use [projects.predict](/ml/reference/rest/v1beta1/projects/predict to
// request predictions of a version of your model, or use
// [projects.jobs.create](/ml/reference/rest/v1beta1/projects.jobs/create)
// to start a batch prediction job.
class ModelService final {
public:
class StubInterface {
public:
virtual ~StubInterface() {}
// Creates a model which will later contain one or more versions.
//
// You must add at least one version before you can request predictions from
// the model. Add versions by calling
// [projects.models.versions.create](/ml/reference/rest/v1beta1/projects.models.versions/create).
virtual ::grpc::Status CreateModel(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::CreateModelRequest& request, ::google::cloud::ml::v1beta1::Model* response) = 0;
std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::ml::v1beta1::Model>> AsyncCreateModel(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::CreateModelRequest& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::ml::v1beta1::Model>>(AsyncCreateModelRaw(context, request, cq));
}
// Lists the models in a project.
//
// Each project can contain multiple models, and each model can have multiple
// versions.
virtual ::grpc::Status ListModels(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::ListModelsRequest& request, ::google::cloud::ml::v1beta1::ListModelsResponse* response) = 0;
std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::ml::v1beta1::ListModelsResponse>> AsyncListModels(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::ListModelsRequest& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::ml::v1beta1::ListModelsResponse>>(AsyncListModelsRaw(context, request, cq));
}
// Gets information about a model, including its name, the description (if
// set), and the default version (if at least one version of the model has
// been deployed).
virtual ::grpc::Status GetModel(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::GetModelRequest& request, ::google::cloud::ml::v1beta1::Model* response) = 0;
std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::ml::v1beta1::Model>> AsyncGetModel(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::GetModelRequest& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::ml::v1beta1::Model>>(AsyncGetModelRaw(context, request, cq));
}
// Deletes a model.
//
// You can only delete a model if there are no versions in it. You can delete
// versions by calling
// [projects.models.versions.delete](/ml/reference/rest/v1beta1/projects.models.versions/delete).
virtual ::grpc::Status DeleteModel(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::DeleteModelRequest& request, ::google::longrunning::Operation* response) = 0;
std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::longrunning::Operation>> AsyncDeleteModel(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::DeleteModelRequest& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::longrunning::Operation>>(AsyncDeleteModelRaw(context, request, cq));
}
// Creates a new version of a model from a trained TensorFlow model.
//
// If the version created in the cloud by this call is the first deployed
// version of the specified model, it will be made the default version of the
// model. When you add a version to a model that already has one or more
// versions, the default version does not automatically change. If you want a
// new version to be the default, you must call
// [projects.models.versions.setDefault](/ml/reference/rest/v1beta1/projects.models.versions/setDefault).
virtual ::grpc::Status CreateVersion(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::CreateVersionRequest& request, ::google::longrunning::Operation* response) = 0;
std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::longrunning::Operation>> AsyncCreateVersion(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::CreateVersionRequest& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::longrunning::Operation>>(AsyncCreateVersionRaw(context, request, cq));
}
// Gets basic information about all the versions of a model.
//
// If you expect that a model has a lot of versions, or if you need to handle
// only a limited number of results at a time, you can request that the list
// be retrieved in batches (called pages):
virtual ::grpc::Status ListVersions(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::ListVersionsRequest& request, ::google::cloud::ml::v1beta1::ListVersionsResponse* response) = 0;
std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::ml::v1beta1::ListVersionsResponse>> AsyncListVersions(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::ListVersionsRequest& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::ml::v1beta1::ListVersionsResponse>>(AsyncListVersionsRaw(context, request, cq));
}
// Gets information about a model version.
//
// Models can have multiple versions. You can call
// [projects.models.versions.list](/ml/reference/rest/v1beta1/projects.models.versions/list)
// to get the same information that this method returns for all of the
// versions of a model.
virtual ::grpc::Status GetVersion(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::GetVersionRequest& request, ::google::cloud::ml::v1beta1::Version* response) = 0;
std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::ml::v1beta1::Version>> AsyncGetVersion(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::GetVersionRequest& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::ml::v1beta1::Version>>(AsyncGetVersionRaw(context, request, cq));
}
// Deletes a model version.
//
// Each model can have multiple versions deployed and in use at any given
// time. Use this method to remove a single version.
//
// Note: You cannot delete the version that is set as the default version
// of the model unless it is the only remaining version.
virtual ::grpc::Status DeleteVersion(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::DeleteVersionRequest& request, ::google::longrunning::Operation* response) = 0;
std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::longrunning::Operation>> AsyncDeleteVersion(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::DeleteVersionRequest& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::longrunning::Operation>>(AsyncDeleteVersionRaw(context, request, cq));
}
// Designates a version to be the default for the model.
//
// The default version is used for prediction requests made against the model
// that don't specify a version.
//
// The first version to be created for a model is automatically set as the
// default. You must make any subsequent changes to the default version
// setting manually using this method.
virtual ::grpc::Status SetDefaultVersion(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::SetDefaultVersionRequest& request, ::google::cloud::ml::v1beta1::Version* response) = 0;
std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::ml::v1beta1::Version>> AsyncSetDefaultVersion(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::SetDefaultVersionRequest& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::ml::v1beta1::Version>>(AsyncSetDefaultVersionRaw(context, request, cq));
}
private:
virtual ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::ml::v1beta1::Model>* AsyncCreateModelRaw(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::CreateModelRequest& request, ::grpc::CompletionQueue* cq) = 0;
virtual ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::ml::v1beta1::ListModelsResponse>* AsyncListModelsRaw(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::ListModelsRequest& request, ::grpc::CompletionQueue* cq) = 0;
virtual ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::ml::v1beta1::Model>* AsyncGetModelRaw(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::GetModelRequest& request, ::grpc::CompletionQueue* cq) = 0;
virtual ::grpc::ClientAsyncResponseReaderInterface< ::google::longrunning::Operation>* AsyncDeleteModelRaw(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::DeleteModelRequest& request, ::grpc::CompletionQueue* cq) = 0;
virtual ::grpc::ClientAsyncResponseReaderInterface< ::google::longrunning::Operation>* AsyncCreateVersionRaw(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::CreateVersionRequest& request, ::grpc::CompletionQueue* cq) = 0;
virtual ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::ml::v1beta1::ListVersionsResponse>* AsyncListVersionsRaw(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::ListVersionsRequest& request, ::grpc::CompletionQueue* cq) = 0;
virtual ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::ml::v1beta1::Version>* AsyncGetVersionRaw(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::GetVersionRequest& request, ::grpc::CompletionQueue* cq) = 0;
virtual ::grpc::ClientAsyncResponseReaderInterface< ::google::longrunning::Operation>* AsyncDeleteVersionRaw(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::DeleteVersionRequest& request, ::grpc::CompletionQueue* cq) = 0;
virtual ::grpc::ClientAsyncResponseReaderInterface< ::google::cloud::ml::v1beta1::Version>* AsyncSetDefaultVersionRaw(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::SetDefaultVersionRequest& request, ::grpc::CompletionQueue* cq) = 0;
};
class Stub final : public StubInterface {
public:
Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel);
::grpc::Status CreateModel(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::CreateModelRequest& request, ::google::cloud::ml::v1beta1::Model* response) override;
std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::cloud::ml::v1beta1::Model>> AsyncCreateModel(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::CreateModelRequest& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::cloud::ml::v1beta1::Model>>(AsyncCreateModelRaw(context, request, cq));
}
::grpc::Status ListModels(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::ListModelsRequest& request, ::google::cloud::ml::v1beta1::ListModelsResponse* response) override;
std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::cloud::ml::v1beta1::ListModelsResponse>> AsyncListModels(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::ListModelsRequest& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::cloud::ml::v1beta1::ListModelsResponse>>(AsyncListModelsRaw(context, request, cq));
}
::grpc::Status GetModel(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::GetModelRequest& request, ::google::cloud::ml::v1beta1::Model* response) override;
std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::cloud::ml::v1beta1::Model>> AsyncGetModel(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::GetModelRequest& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::cloud::ml::v1beta1::Model>>(AsyncGetModelRaw(context, request, cq));
}
::grpc::Status DeleteModel(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::DeleteModelRequest& request, ::google::longrunning::Operation* response) override;
std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::longrunning::Operation>> AsyncDeleteModel(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::DeleteModelRequest& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::longrunning::Operation>>(AsyncDeleteModelRaw(context, request, cq));
}
::grpc::Status CreateVersion(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::CreateVersionRequest& request, ::google::longrunning::Operation* response) override;
std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::longrunning::Operation>> AsyncCreateVersion(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::CreateVersionRequest& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::longrunning::Operation>>(AsyncCreateVersionRaw(context, request, cq));
}
::grpc::Status ListVersions(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::ListVersionsRequest& request, ::google::cloud::ml::v1beta1::ListVersionsResponse* response) override;
std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::cloud::ml::v1beta1::ListVersionsResponse>> AsyncListVersions(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::ListVersionsRequest& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::cloud::ml::v1beta1::ListVersionsResponse>>(AsyncListVersionsRaw(context, request, cq));
}
::grpc::Status GetVersion(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::GetVersionRequest& request, ::google::cloud::ml::v1beta1::Version* response) override;
std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::cloud::ml::v1beta1::Version>> AsyncGetVersion(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::GetVersionRequest& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::cloud::ml::v1beta1::Version>>(AsyncGetVersionRaw(context, request, cq));
}
::grpc::Status DeleteVersion(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::DeleteVersionRequest& request, ::google::longrunning::Operation* response) override;
std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::longrunning::Operation>> AsyncDeleteVersion(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::DeleteVersionRequest& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::longrunning::Operation>>(AsyncDeleteVersionRaw(context, request, cq));
}
::grpc::Status SetDefaultVersion(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::SetDefaultVersionRequest& request, ::google::cloud::ml::v1beta1::Version* response) override;
std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::cloud::ml::v1beta1::Version>> AsyncSetDefaultVersion(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::SetDefaultVersionRequest& request, ::grpc::CompletionQueue* cq) {
return std::unique_ptr< ::grpc::ClientAsyncResponseReader< ::google::cloud::ml::v1beta1::Version>>(AsyncSetDefaultVersionRaw(context, request, cq));
}
private:
std::shared_ptr< ::grpc::ChannelInterface> channel_;
::grpc::ClientAsyncResponseReader< ::google::cloud::ml::v1beta1::Model>* AsyncCreateModelRaw(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::CreateModelRequest& request, ::grpc::CompletionQueue* cq) override;
::grpc::ClientAsyncResponseReader< ::google::cloud::ml::v1beta1::ListModelsResponse>* AsyncListModelsRaw(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::ListModelsRequest& request, ::grpc::CompletionQueue* cq) override;
::grpc::ClientAsyncResponseReader< ::google::cloud::ml::v1beta1::Model>* AsyncGetModelRaw(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::GetModelRequest& request, ::grpc::CompletionQueue* cq) override;
::grpc::ClientAsyncResponseReader< ::google::longrunning::Operation>* AsyncDeleteModelRaw(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::DeleteModelRequest& request, ::grpc::CompletionQueue* cq) override;
::grpc::ClientAsyncResponseReader< ::google::longrunning::Operation>* AsyncCreateVersionRaw(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::CreateVersionRequest& request, ::grpc::CompletionQueue* cq) override;
::grpc::ClientAsyncResponseReader< ::google::cloud::ml::v1beta1::ListVersionsResponse>* AsyncListVersionsRaw(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::ListVersionsRequest& request, ::grpc::CompletionQueue* cq) override;
::grpc::ClientAsyncResponseReader< ::google::cloud::ml::v1beta1::Version>* AsyncGetVersionRaw(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::GetVersionRequest& request, ::grpc::CompletionQueue* cq) override;
::grpc::ClientAsyncResponseReader< ::google::longrunning::Operation>* AsyncDeleteVersionRaw(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::DeleteVersionRequest& request, ::grpc::CompletionQueue* cq) override;
::grpc::ClientAsyncResponseReader< ::google::cloud::ml::v1beta1::Version>* AsyncSetDefaultVersionRaw(::grpc::ClientContext* context, const ::google::cloud::ml::v1beta1::SetDefaultVersionRequest& request, ::grpc::CompletionQueue* cq) override;
const ::grpc::RpcMethod rpcmethod_CreateModel_;
const ::grpc::RpcMethod rpcmethod_ListModels_;
const ::grpc::RpcMethod rpcmethod_GetModel_;
const ::grpc::RpcMethod rpcmethod_DeleteModel_;
const ::grpc::RpcMethod rpcmethod_CreateVersion_;
const ::grpc::RpcMethod rpcmethod_ListVersions_;
const ::grpc::RpcMethod rpcmethod_GetVersion_;
const ::grpc::RpcMethod rpcmethod_DeleteVersion_;
const ::grpc::RpcMethod rpcmethod_SetDefaultVersion_;
};
static std::unique_ptr<Stub> NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options = ::grpc::StubOptions());
class Service : public ::grpc::Service {
public:
Service();
virtual ~Service();
// Creates a model which will later contain one or more versions.
//
// You must add at least one version before you can request predictions from
// the model. Add versions by calling
// [projects.models.versions.create](/ml/reference/rest/v1beta1/projects.models.versions/create).
virtual ::grpc::Status CreateModel(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::CreateModelRequest* request, ::google::cloud::ml::v1beta1::Model* response);
// Lists the models in a project.
//
// Each project can contain multiple models, and each model can have multiple
// versions.
virtual ::grpc::Status ListModels(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::ListModelsRequest* request, ::google::cloud::ml::v1beta1::ListModelsResponse* response);
// Gets information about a model, including its name, the description (if
// set), and the default version (if at least one version of the model has
// been deployed).
virtual ::grpc::Status GetModel(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::GetModelRequest* request, ::google::cloud::ml::v1beta1::Model* response);
// Deletes a model.
//
// You can only delete a model if there are no versions in it. You can delete
// versions by calling
// [projects.models.versions.delete](/ml/reference/rest/v1beta1/projects.models.versions/delete).
virtual ::grpc::Status DeleteModel(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::DeleteModelRequest* request, ::google::longrunning::Operation* response);
// Creates a new version of a model from a trained TensorFlow model.
//
// If the version created in the cloud by this call is the first deployed
// version of the specified model, it will be made the default version of the
// model. When you add a version to a model that already has one or more
// versions, the default version does not automatically change. If you want a
// new version to be the default, you must call
// [projects.models.versions.setDefault](/ml/reference/rest/v1beta1/projects.models.versions/setDefault).
virtual ::grpc::Status CreateVersion(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::CreateVersionRequest* request, ::google::longrunning::Operation* response);
// Gets basic information about all the versions of a model.
//
// If you expect that a model has a lot of versions, or if you need to handle
// only a limited number of results at a time, you can request that the list
// be retrieved in batches (called pages):
virtual ::grpc::Status ListVersions(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::ListVersionsRequest* request, ::google::cloud::ml::v1beta1::ListVersionsResponse* response);
// Gets information about a model version.
//
// Models can have multiple versions. You can call
// [projects.models.versions.list](/ml/reference/rest/v1beta1/projects.models.versions/list)
// to get the same information that this method returns for all of the
// versions of a model.
virtual ::grpc::Status GetVersion(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::GetVersionRequest* request, ::google::cloud::ml::v1beta1::Version* response);
// Deletes a model version.
//
// Each model can have multiple versions deployed and in use at any given
// time. Use this method to remove a single version.
//
// Note: You cannot delete the version that is set as the default version
// of the model unless it is the only remaining version.
virtual ::grpc::Status DeleteVersion(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::DeleteVersionRequest* request, ::google::longrunning::Operation* response);
// Designates a version to be the default for the model.
//
// The default version is used for prediction requests made against the model
// that don't specify a version.
//
// The first version to be created for a model is automatically set as the
// default. You must make any subsequent changes to the default version
// setting manually using this method.
virtual ::grpc::Status SetDefaultVersion(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::SetDefaultVersionRequest* request, ::google::cloud::ml::v1beta1::Version* response);
};
template <class BaseClass>
class WithAsyncMethod_CreateModel : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithAsyncMethod_CreateModel() {
::grpc::Service::MarkMethodAsync(0);
}
~WithAsyncMethod_CreateModel() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status CreateModel(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::CreateModelRequest* request, ::google::cloud::ml::v1beta1::Model* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
void RequestCreateModel(::grpc::ServerContext* context, ::google::cloud::ml::v1beta1::CreateModelRequest* request, ::grpc::ServerAsyncResponseWriter< ::google::cloud::ml::v1beta1::Model>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
::grpc::Service::RequestAsyncUnary(0, context, request, response, new_call_cq, notification_cq, tag);
}
};
template <class BaseClass>
class WithAsyncMethod_ListModels : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithAsyncMethod_ListModels() {
::grpc::Service::MarkMethodAsync(1);
}
~WithAsyncMethod_ListModels() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status ListModels(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::ListModelsRequest* request, ::google::cloud::ml::v1beta1::ListModelsResponse* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
void RequestListModels(::grpc::ServerContext* context, ::google::cloud::ml::v1beta1::ListModelsRequest* request, ::grpc::ServerAsyncResponseWriter< ::google::cloud::ml::v1beta1::ListModelsResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
::grpc::Service::RequestAsyncUnary(1, context, request, response, new_call_cq, notification_cq, tag);
}
};
template <class BaseClass>
class WithAsyncMethod_GetModel : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithAsyncMethod_GetModel() {
::grpc::Service::MarkMethodAsync(2);
}
~WithAsyncMethod_GetModel() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status GetModel(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::GetModelRequest* request, ::google::cloud::ml::v1beta1::Model* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
void RequestGetModel(::grpc::ServerContext* context, ::google::cloud::ml::v1beta1::GetModelRequest* request, ::grpc::ServerAsyncResponseWriter< ::google::cloud::ml::v1beta1::Model>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
::grpc::Service::RequestAsyncUnary(2, context, request, response, new_call_cq, notification_cq, tag);
}
};
template <class BaseClass>
class WithAsyncMethod_DeleteModel : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithAsyncMethod_DeleteModel() {
::grpc::Service::MarkMethodAsync(3);
}
~WithAsyncMethod_DeleteModel() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status DeleteModel(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::DeleteModelRequest* request, ::google::longrunning::Operation* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
void RequestDeleteModel(::grpc::ServerContext* context, ::google::cloud::ml::v1beta1::DeleteModelRequest* request, ::grpc::ServerAsyncResponseWriter< ::google::longrunning::Operation>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
::grpc::Service::RequestAsyncUnary(3, context, request, response, new_call_cq, notification_cq, tag);
}
};
template <class BaseClass>
class WithAsyncMethod_CreateVersion : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithAsyncMethod_CreateVersion() {
::grpc::Service::MarkMethodAsync(4);
}
~WithAsyncMethod_CreateVersion() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status CreateVersion(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::CreateVersionRequest* request, ::google::longrunning::Operation* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
void RequestCreateVersion(::grpc::ServerContext* context, ::google::cloud::ml::v1beta1::CreateVersionRequest* request, ::grpc::ServerAsyncResponseWriter< ::google::longrunning::Operation>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
::grpc::Service::RequestAsyncUnary(4, context, request, response, new_call_cq, notification_cq, tag);
}
};
template <class BaseClass>
class WithAsyncMethod_ListVersions : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithAsyncMethod_ListVersions() {
::grpc::Service::MarkMethodAsync(5);
}
~WithAsyncMethod_ListVersions() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status ListVersions(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::ListVersionsRequest* request, ::google::cloud::ml::v1beta1::ListVersionsResponse* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
void RequestListVersions(::grpc::ServerContext* context, ::google::cloud::ml::v1beta1::ListVersionsRequest* request, ::grpc::ServerAsyncResponseWriter< ::google::cloud::ml::v1beta1::ListVersionsResponse>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
::grpc::Service::RequestAsyncUnary(5, context, request, response, new_call_cq, notification_cq, tag);
}
};
template <class BaseClass>
class WithAsyncMethod_GetVersion : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithAsyncMethod_GetVersion() {
::grpc::Service::MarkMethodAsync(6);
}
~WithAsyncMethod_GetVersion() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status GetVersion(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::GetVersionRequest* request, ::google::cloud::ml::v1beta1::Version* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
void RequestGetVersion(::grpc::ServerContext* context, ::google::cloud::ml::v1beta1::GetVersionRequest* request, ::grpc::ServerAsyncResponseWriter< ::google::cloud::ml::v1beta1::Version>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
::grpc::Service::RequestAsyncUnary(6, context, request, response, new_call_cq, notification_cq, tag);
}
};
template <class BaseClass>
class WithAsyncMethod_DeleteVersion : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithAsyncMethod_DeleteVersion() {
::grpc::Service::MarkMethodAsync(7);
}
~WithAsyncMethod_DeleteVersion() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status DeleteVersion(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::DeleteVersionRequest* request, ::google::longrunning::Operation* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
void RequestDeleteVersion(::grpc::ServerContext* context, ::google::cloud::ml::v1beta1::DeleteVersionRequest* request, ::grpc::ServerAsyncResponseWriter< ::google::longrunning::Operation>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
::grpc::Service::RequestAsyncUnary(7, context, request, response, new_call_cq, notification_cq, tag);
}
};
template <class BaseClass>
class WithAsyncMethod_SetDefaultVersion : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithAsyncMethod_SetDefaultVersion() {
::grpc::Service::MarkMethodAsync(8);
}
~WithAsyncMethod_SetDefaultVersion() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status SetDefaultVersion(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::SetDefaultVersionRequest* request, ::google::cloud::ml::v1beta1::Version* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
void RequestSetDefaultVersion(::grpc::ServerContext* context, ::google::cloud::ml::v1beta1::SetDefaultVersionRequest* request, ::grpc::ServerAsyncResponseWriter< ::google::cloud::ml::v1beta1::Version>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) {
::grpc::Service::RequestAsyncUnary(8, context, request, response, new_call_cq, notification_cq, tag);
}
};
typedef WithAsyncMethod_CreateModel<WithAsyncMethod_ListModels<WithAsyncMethod_GetModel<WithAsyncMethod_DeleteModel<WithAsyncMethod_CreateVersion<WithAsyncMethod_ListVersions<WithAsyncMethod_GetVersion<WithAsyncMethod_DeleteVersion<WithAsyncMethod_SetDefaultVersion<Service > > > > > > > > > AsyncService;
template <class BaseClass>
class WithGenericMethod_CreateModel : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithGenericMethod_CreateModel() {
::grpc::Service::MarkMethodGeneric(0);
}
~WithGenericMethod_CreateModel() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status CreateModel(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::CreateModelRequest* request, ::google::cloud::ml::v1beta1::Model* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
};
template <class BaseClass>
class WithGenericMethod_ListModels : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithGenericMethod_ListModels() {
::grpc::Service::MarkMethodGeneric(1);
}
~WithGenericMethod_ListModels() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status ListModels(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::ListModelsRequest* request, ::google::cloud::ml::v1beta1::ListModelsResponse* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
};
template <class BaseClass>
class WithGenericMethod_GetModel : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithGenericMethod_GetModel() {
::grpc::Service::MarkMethodGeneric(2);
}
~WithGenericMethod_GetModel() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status GetModel(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::GetModelRequest* request, ::google::cloud::ml::v1beta1::Model* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
};
template <class BaseClass>
class WithGenericMethod_DeleteModel : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithGenericMethod_DeleteModel() {
::grpc::Service::MarkMethodGeneric(3);
}
~WithGenericMethod_DeleteModel() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status DeleteModel(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::DeleteModelRequest* request, ::google::longrunning::Operation* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
};
template <class BaseClass>
class WithGenericMethod_CreateVersion : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithGenericMethod_CreateVersion() {
::grpc::Service::MarkMethodGeneric(4);
}
~WithGenericMethod_CreateVersion() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status CreateVersion(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::CreateVersionRequest* request, ::google::longrunning::Operation* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
};
template <class BaseClass>
class WithGenericMethod_ListVersions : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithGenericMethod_ListVersions() {
::grpc::Service::MarkMethodGeneric(5);
}
~WithGenericMethod_ListVersions() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status ListVersions(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::ListVersionsRequest* request, ::google::cloud::ml::v1beta1::ListVersionsResponse* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
};
template <class BaseClass>
class WithGenericMethod_GetVersion : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithGenericMethod_GetVersion() {
::grpc::Service::MarkMethodGeneric(6);
}
~WithGenericMethod_GetVersion() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status GetVersion(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::GetVersionRequest* request, ::google::cloud::ml::v1beta1::Version* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
};
template <class BaseClass>
class WithGenericMethod_DeleteVersion : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithGenericMethod_DeleteVersion() {
::grpc::Service::MarkMethodGeneric(7);
}
~WithGenericMethod_DeleteVersion() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status DeleteVersion(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::DeleteVersionRequest* request, ::google::longrunning::Operation* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
};
template <class BaseClass>
class WithGenericMethod_SetDefaultVersion : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithGenericMethod_SetDefaultVersion() {
::grpc::Service::MarkMethodGeneric(8);
}
~WithGenericMethod_SetDefaultVersion() override {
BaseClassMustBeDerivedFromService(this);
}
// disable synchronous version of this method
::grpc::Status SetDefaultVersion(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::SetDefaultVersionRequest* request, ::google::cloud::ml::v1beta1::Version* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
};
template <class BaseClass>
class WithStreamedUnaryMethod_CreateModel : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithStreamedUnaryMethod_CreateModel() {
::grpc::Service::MarkMethodStreamed(0,
new ::grpc::StreamedUnaryHandler< ::google::cloud::ml::v1beta1::CreateModelRequest, ::google::cloud::ml::v1beta1::Model>(std::bind(&WithStreamedUnaryMethod_CreateModel<BaseClass>::StreamedCreateModel, this, std::placeholders::_1, std::placeholders::_2)));
}
~WithStreamedUnaryMethod_CreateModel() override {
BaseClassMustBeDerivedFromService(this);
}
// disable regular version of this method
::grpc::Status CreateModel(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::CreateModelRequest* request, ::google::cloud::ml::v1beta1::Model* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
// replace default version of method with streamed unary
virtual ::grpc::Status StreamedCreateModel(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::google::cloud::ml::v1beta1::CreateModelRequest,::google::cloud::ml::v1beta1::Model>* server_unary_streamer) = 0;
};
template <class BaseClass>
class WithStreamedUnaryMethod_ListModels : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithStreamedUnaryMethod_ListModels() {
::grpc::Service::MarkMethodStreamed(1,
new ::grpc::StreamedUnaryHandler< ::google::cloud::ml::v1beta1::ListModelsRequest, ::google::cloud::ml::v1beta1::ListModelsResponse>(std::bind(&WithStreamedUnaryMethod_ListModels<BaseClass>::StreamedListModels, this, std::placeholders::_1, std::placeholders::_2)));
}
~WithStreamedUnaryMethod_ListModels() override {
BaseClassMustBeDerivedFromService(this);
}
// disable regular version of this method
::grpc::Status ListModels(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::ListModelsRequest* request, ::google::cloud::ml::v1beta1::ListModelsResponse* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
// replace default version of method with streamed unary
virtual ::grpc::Status StreamedListModels(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::google::cloud::ml::v1beta1::ListModelsRequest,::google::cloud::ml::v1beta1::ListModelsResponse>* server_unary_streamer) = 0;
};
template <class BaseClass>
class WithStreamedUnaryMethod_GetModel : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithStreamedUnaryMethod_GetModel() {
::grpc::Service::MarkMethodStreamed(2,
new ::grpc::StreamedUnaryHandler< ::google::cloud::ml::v1beta1::GetModelRequest, ::google::cloud::ml::v1beta1::Model>(std::bind(&WithStreamedUnaryMethod_GetModel<BaseClass>::StreamedGetModel, this, std::placeholders::_1, std::placeholders::_2)));
}
~WithStreamedUnaryMethod_GetModel() override {
BaseClassMustBeDerivedFromService(this);
}
// disable regular version of this method
::grpc::Status GetModel(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::GetModelRequest* request, ::google::cloud::ml::v1beta1::Model* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
// replace default version of method with streamed unary
virtual ::grpc::Status StreamedGetModel(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::google::cloud::ml::v1beta1::GetModelRequest,::google::cloud::ml::v1beta1::Model>* server_unary_streamer) = 0;
};
template <class BaseClass>
class WithStreamedUnaryMethod_DeleteModel : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithStreamedUnaryMethod_DeleteModel() {
::grpc::Service::MarkMethodStreamed(3,
new ::grpc::StreamedUnaryHandler< ::google::cloud::ml::v1beta1::DeleteModelRequest, ::google::longrunning::Operation>(std::bind(&WithStreamedUnaryMethod_DeleteModel<BaseClass>::StreamedDeleteModel, this, std::placeholders::_1, std::placeholders::_2)));
}
~WithStreamedUnaryMethod_DeleteModel() override {
BaseClassMustBeDerivedFromService(this);
}
// disable regular version of this method
::grpc::Status DeleteModel(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::DeleteModelRequest* request, ::google::longrunning::Operation* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
// replace default version of method with streamed unary
virtual ::grpc::Status StreamedDeleteModel(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::google::cloud::ml::v1beta1::DeleteModelRequest,::google::longrunning::Operation>* server_unary_streamer) = 0;
};
template <class BaseClass>
class WithStreamedUnaryMethod_CreateVersion : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithStreamedUnaryMethod_CreateVersion() {
::grpc::Service::MarkMethodStreamed(4,
new ::grpc::StreamedUnaryHandler< ::google::cloud::ml::v1beta1::CreateVersionRequest, ::google::longrunning::Operation>(std::bind(&WithStreamedUnaryMethod_CreateVersion<BaseClass>::StreamedCreateVersion, this, std::placeholders::_1, std::placeholders::_2)));
}
~WithStreamedUnaryMethod_CreateVersion() override {
BaseClassMustBeDerivedFromService(this);
}
// disable regular version of this method
::grpc::Status CreateVersion(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::CreateVersionRequest* request, ::google::longrunning::Operation* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
// replace default version of method with streamed unary
virtual ::grpc::Status StreamedCreateVersion(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::google::cloud::ml::v1beta1::CreateVersionRequest,::google::longrunning::Operation>* server_unary_streamer) = 0;
};
template <class BaseClass>
class WithStreamedUnaryMethod_ListVersions : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithStreamedUnaryMethod_ListVersions() {
::grpc::Service::MarkMethodStreamed(5,
new ::grpc::StreamedUnaryHandler< ::google::cloud::ml::v1beta1::ListVersionsRequest, ::google::cloud::ml::v1beta1::ListVersionsResponse>(std::bind(&WithStreamedUnaryMethod_ListVersions<BaseClass>::StreamedListVersions, this, std::placeholders::_1, std::placeholders::_2)));
}
~WithStreamedUnaryMethod_ListVersions() override {
BaseClassMustBeDerivedFromService(this);
}
// disable regular version of this method
::grpc::Status ListVersions(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::ListVersionsRequest* request, ::google::cloud::ml::v1beta1::ListVersionsResponse* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
// replace default version of method with streamed unary
virtual ::grpc::Status StreamedListVersions(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::google::cloud::ml::v1beta1::ListVersionsRequest,::google::cloud::ml::v1beta1::ListVersionsResponse>* server_unary_streamer) = 0;
};
template <class BaseClass>
class WithStreamedUnaryMethod_GetVersion : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithStreamedUnaryMethod_GetVersion() {
::grpc::Service::MarkMethodStreamed(6,
new ::grpc::StreamedUnaryHandler< ::google::cloud::ml::v1beta1::GetVersionRequest, ::google::cloud::ml::v1beta1::Version>(std::bind(&WithStreamedUnaryMethod_GetVersion<BaseClass>::StreamedGetVersion, this, std::placeholders::_1, std::placeholders::_2)));
}
~WithStreamedUnaryMethod_GetVersion() override {
BaseClassMustBeDerivedFromService(this);
}
// disable regular version of this method
::grpc::Status GetVersion(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::GetVersionRequest* request, ::google::cloud::ml::v1beta1::Version* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
// replace default version of method with streamed unary
virtual ::grpc::Status StreamedGetVersion(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::google::cloud::ml::v1beta1::GetVersionRequest,::google::cloud::ml::v1beta1::Version>* server_unary_streamer) = 0;
};
template <class BaseClass>
class WithStreamedUnaryMethod_DeleteVersion : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithStreamedUnaryMethod_DeleteVersion() {
::grpc::Service::MarkMethodStreamed(7,
new ::grpc::StreamedUnaryHandler< ::google::cloud::ml::v1beta1::DeleteVersionRequest, ::google::longrunning::Operation>(std::bind(&WithStreamedUnaryMethod_DeleteVersion<BaseClass>::StreamedDeleteVersion, this, std::placeholders::_1, std::placeholders::_2)));
}
~WithStreamedUnaryMethod_DeleteVersion() override {
BaseClassMustBeDerivedFromService(this);
}
// disable regular version of this method
::grpc::Status DeleteVersion(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::DeleteVersionRequest* request, ::google::longrunning::Operation* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
// replace default version of method with streamed unary
virtual ::grpc::Status StreamedDeleteVersion(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::google::cloud::ml::v1beta1::DeleteVersionRequest,::google::longrunning::Operation>* server_unary_streamer) = 0;
};
template <class BaseClass>
class WithStreamedUnaryMethod_SetDefaultVersion : public BaseClass {
private:
void BaseClassMustBeDerivedFromService(const Service *service) {}
public:
WithStreamedUnaryMethod_SetDefaultVersion() {
::grpc::Service::MarkMethodStreamed(8,
new ::grpc::StreamedUnaryHandler< ::google::cloud::ml::v1beta1::SetDefaultVersionRequest, ::google::cloud::ml::v1beta1::Version>(std::bind(&WithStreamedUnaryMethod_SetDefaultVersion<BaseClass>::StreamedSetDefaultVersion, this, std::placeholders::_1, std::placeholders::_2)));
}
~WithStreamedUnaryMethod_SetDefaultVersion() override {
BaseClassMustBeDerivedFromService(this);
}
// disable regular version of this method
::grpc::Status SetDefaultVersion(::grpc::ServerContext* context, const ::google::cloud::ml::v1beta1::SetDefaultVersionRequest* request, ::google::cloud::ml::v1beta1::Version* response) final override {
abort();
return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, "");
}
// replace default version of method with streamed unary
virtual ::grpc::Status StreamedSetDefaultVersion(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< ::google::cloud::ml::v1beta1::SetDefaultVersionRequest,::google::cloud::ml::v1beta1::Version>* server_unary_streamer) = 0;
};
typedef WithStreamedUnaryMethod_CreateModel<WithStreamedUnaryMethod_ListModels<WithStreamedUnaryMethod_GetModel<WithStreamedUnaryMethod_DeleteModel<WithStreamedUnaryMethod_CreateVersion<WithStreamedUnaryMethod_ListVersions<WithStreamedUnaryMethod_GetVersion<WithStreamedUnaryMethod_DeleteVersion<WithStreamedUnaryMethod_SetDefaultVersion<Service > > > > > > > > > StreamedUnaryService;
typedef Service SplitStreamedService;
typedef WithStreamedUnaryMethod_CreateModel<WithStreamedUnaryMethod_ListModels<WithStreamedUnaryMethod_GetModel<WithStreamedUnaryMethod_DeleteModel<WithStreamedUnaryMethod_CreateVersion<WithStreamedUnaryMethod_ListVersions<WithStreamedUnaryMethod_GetVersion<WithStreamedUnaryMethod_DeleteVersion<WithStreamedUnaryMethod_SetDefaultVersion<Service > > > > > > > > > StreamedService;
};
} // namespace v1beta1
} // namespace ml
} // namespace cloud
} // namespace google
#endif // GRPC_google_2fcloud_2fml_2fv1beta1_2fmodel_5fservice_2eproto__INCLUDED
| 66.647129 | 387 | 0.734982 | [
"model"
] |
609628f774bde18d9a86e67be4862d3e1bc6ecdb | 909 | c | C | d/islands/common/eldebaro/mon/oasis_guard.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-07-19T05:24:44.000Z | 2021-11-18T04:08:19.000Z | d/islands/common/eldebaro/mon/oasis_guard.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 4 | 2021-03-15T18:56:39.000Z | 2021-08-17T17:08:22.000Z | d/islands/common/eldebaro/mon/oasis_guard.c | Dbevan/SunderingShadows | 6c15ec56cef43c36361899bae6dc08d0ee907304 | [
"MIT"
] | 13 | 2019-09-12T06:22:38.000Z | 2022-01-31T01:15:12.000Z | #include <std.h>
#include "../area_stuff.h"
inherit GUARDSMAN;
void create()
{
::create();
NPCCRE->build_me(TO);
add_id(({"oasis guard"}));
set_nogo(({ELROOMSE+"14"}));
set_speed(20);
}
int is_eldebaro_monster(object ob)
{
if(!objectp(ob)) return 0;
if(ob->id("eldebarocreature")) return 1;
return 0;
}
void check_my_environment()
{
object *vics;
int x;
if(!objectp(TO)) return;
if(!objectp(ETO)) return;
vics = filter_array(all_living(ETO), "is_eldebaro_monster", TO);
vics -= TO->query_attackers();
if(!sizeof(vics)) return;
for(x = 0;x < sizeof(vics);x++)
{
TO->force_me("kill "+vics[x]->query_name());
continue;
}
return;
}
void init()
{
::init();
check_my_environment();
return;
}
void heart_beat()
{
::heart_beat();
if(!objectp(TO)) return;
check_my_environment();
return;
} | 17.823529 | 68 | 0.586359 | [
"object"
] |
60a59159c72047106509e4af0a10f39b7d16c59a | 1,438 | h | C | OpenGL/Light.h | CyberPlaton/OpenGL | 79afbb1356a2bdebfa4b3f11197c6fe7dd568a19 | [
"MIT"
] | null | null | null | OpenGL/Light.h | CyberPlaton/OpenGL | 79afbb1356a2bdebfa4b3f11197c6fe7dd568a19 | [
"MIT"
] | null | null | null | OpenGL/Light.h | CyberPlaton/OpenGL | 79afbb1356a2bdebfa4b3f11197c6fe7dd568a19 | [
"MIT"
] | null | null | null | #pragma once
#include"Mesh.h"
#include"ShaderProgram.h"
#include<glm/glm.hpp>
#include<glm/gtx/transform.hpp>
class Light{
public:
void SetShader(const std::string& vsname, const std::string& fsname);
void Use();
// Special method for drawing light source.
// We use a standard vertex, fragment shader.
void Draw(glm::mat4 projection, glm::mat4 view, glm::vec3 viewPos);
glm::vec3 GetColor()const { return m_Color; }
glm::vec3 GetPosition()const { return m_Position; }
glm::vec3 GetScale()const { return m_Scale; }
float GetBrightness()const { return m_Brightness; }
void SetPosition(glm::vec3 pos);
void SetColor(glm::vec3 color);
void SetScale(glm::vec3 scale);
void SetBrightness(float b);
ShaderProgram* GetLightShader() const { return m_LightShader; }
private:
ShaderProgram* m_DefaultShader = nullptr;
ShaderProgram* m_LightShader = nullptr;
Mesh* m_LightMesh = nullptr;
glm::vec3 m_Position;
glm::vec3 m_Scale;
glm::vec3 m_Color;
float m_Brightness = 1.0f;
protected:
Light() {
m_LightMesh = new Mesh();
m_LightMesh->LoadOBJ("Sphere.obj");
m_LightShader = new ShaderProgram();
m_DefaultShader = new ShaderProgram();
m_DefaultShader->LoadShaders("basic.vert", "basic.frag");
}
};
class DirectionalLight : public Light {
public:
DirectionalLight(){}
};
class PointLight : public Light {
public:
PointLight(){}
};
class SpotLight : public Light {
public:
SpotLight(){}
};
| 18.675325 | 70 | 0.717663 | [
"mesh",
"transform"
] |
60a7e74e86725742a3d7b850172f84c2297a237f | 527 | h | C | SDK/IJSEditSDK/Model/IJSIPath.h | wangjinshan/IJSPhotoSDK | b1c696641f85793e5146f49a86aa3246f33d8a5b | [
"MIT"
] | 142 | 2017-07-11T01:56:46.000Z | 2022-02-10T07:05:18.000Z | AssetsSelect/Lib/QSAssetsSelect/SDK/IJSImageEditSDK/Model/IJSIPath.h | Qson8/QSAssetsSelect | 5cbd7a45c1a93b6e79662f74f173d386ca4e33dd | [
"MIT"
] | 12 | 2017-09-16T08:39:36.000Z | 2020-07-08T08:52:01.000Z | IJSPhotoSDKProject/SDK/Core/IJSEditSDK/Model/IJSIPath.h | wangjinshan/IJSPhotoSDK | b1c696641f85793e5146f49a86aa3246f33d8a5b | [
"MIT"
] | 17 | 2017-10-22T15:03:32.000Z | 2021-02-08T03:27:45.000Z | //
// IJSIPath.h
// IJSImageEditSDK
//
// Created by shan on 2017/7/26.
// Copyright © 2017年 shanshen. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
/*
* 画线类
*/
@interface IJSIPath : NSObject
@property (nonatomic, strong) CAShapeLayer *shape;
@property (nonatomic, strong) UIColor *pathColor; //画笔颜色
+ (instancetype)pathToPoint:(CGPoint)beginPoint pathWidth:(CGFloat)pathWidth;
- (void)pathLineToPoint:(CGPoint)movePoint; //加点
- (void)drawPath; //绘制
@end
| 21.958333 | 77 | 0.681214 | [
"shape"
] |
60aba6197adb205347e61249379ceef6e6456958 | 41,817 | c | C | openbsd/sys/arch/mvme88k/dev/vx.c | MarginC/kame | 2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30 | [
"BSD-3-Clause"
] | 91 | 2015-01-05T15:18:31.000Z | 2022-03-11T16:43:28.000Z | openbsd/sys/arch/mvme88k/dev/vx.c | MarginC/kame | 2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30 | [
"BSD-3-Clause"
] | 1 | 2016-02-25T15:57:55.000Z | 2016-02-25T16:01:02.000Z | openbsd/sys/arch/mvme88k/dev/vx.c | MarginC/kame | 2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30 | [
"BSD-3-Clause"
] | 21 | 2015-02-07T08:23:07.000Z | 2021-12-14T06:01:49.000Z | /* $OpenBSD: vx.c,v 1.1 1999/05/29 04:41:45 smurph Exp $ */
/*
* Copyright (c) 1999 Steve Murphree, Jr.
* All rights reserved.
*
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Dale Rahn.
* 4. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/param.h>
#include <sys/callout.h>
#include <sys/conf.h>
#include <sys/ioctl.h>
#include <sys/proc.h>
#include <sys/tty.h>
#include <sys/uio.h>
#include <sys/systm.h>
#include <sys/time.h>
#include <sys/device.h>
#include <machine/cpu.h>
#include <machine/autoconf.h>
#include <dev/cons.h>
#include <mvme88k/dev/vxreg.h>
#include <sys/syslog.h>
#include "pcctwo.h"
#if NPCCTWO > 0
#include <mvme88k/dev/pcctworeg.h>
#include <mvme88k/dev/vme.h>
#endif
#include <machine/psl.h>
#define splvx() spltty()
#ifdef DEBUG
#undef DEBUG
#endif
#define DEBUG_KERN 1
struct vx_info {
struct tty *tty;
u_char vx_swflags;
int vx_linestatus;
int open;
int waiting;
u_char vx_consio;
u_char vx_speed;
u_char read_pending;
struct wring *wringp;
struct rring *rringp;
};
struct vxsoftc {
struct device sc_dev;
struct evcnt sc_intrcnt;
struct evcnt sc_sintrcnt;
struct vx_info sc_info[9];
struct vxreg *vx_reg;
unsigned int board_addr;
struct channel *channel;
char channel_number;
struct packet sc_bppwait_pkt;
void *sc_bppwait_pktp;
struct intrhand sc_ih_c;
struct intrhand sc_ih_s;
struct vme2reg *sc_vme2;
int sc_ipl;
int sc_vec;
int sc_flags;
struct envelope *elist_head, *elist_tail;
struct packet *plist_head, *plist_tail;
};
extern int cold; /* var in autoconf.c that is set in machdep.c when booting */
/* prototypes */
void *get_next_envelope __P((struct envelope *thisenv));
struct envelope *get_status_head __P((struct vxsoftc *sc));
void set_status_head __P((struct vxsoftc *sc, void *envp));
struct packet *get_packet __P((struct vxsoftc *sc, struct envelope *thisenv));
struct envelope *find_status_packet __P((struct vxsoftc *sc, struct packet * pktp));
void read_wakeup __P((struct vxsoftc *sc, int port));
int bpp_send __P((struct vxsoftc *sc, void *pkt, int wait_flag));
int create_channels __P((struct vxsoftc *sc));
void *memcpy2 __P((void *dest, const void *src, size_t size));
void *get_free_envelope __P((struct vxsoftc *sc));
void put_free_envelope __P((struct vxsoftc *sc, void *envp));
void *get_free_packet __P((struct vxsoftc *sc));
void put_free_packet __P((struct vxsoftc *sc, void *pktp));
int vx_init __P((struct vxsoftc *sc));
int vx_event __P((struct vxsoftc *sc, struct packet *evntp));
void vx_unblock __P((struct tty *tp));
int vx_ccparam __P((struct vxsoftc *sc, struct termios *par, int port));
int vx_param __P((struct tty *tp, struct termios *t));
int vx_intr __P((struct vxsoftc *sc));
int vx_sintr __P((struct vxsoftc *sc));
int vx_poll __P((struct vxsoftc *sc, struct packet *wpktp));
void vx_overflow __P((struct vxsoftc *sc, int port, long *ptime, u_char *msg));
void vx_frame __P((struct vxsoftc *sc, int port));
void vx_break __P(( struct vxsoftc *sc, int port));
int vx_mctl __P((dev_t dev, int bits, int how));
int vxmatch __P((struct device *parent, void *self, void *aux));
void vxattach __P((struct device *parent, struct device *self, void *aux));
int vxopen __P((dev_t dev, int flag, int mode, struct proc *p));
int vxclose __P((dev_t dev, int flag, int mode, struct proc *p));
int vxread __P((dev_t dev, struct uio *uio, int flag));
int vxwrite __P((dev_t dev, struct uio *uio, int flag));
int vxioctl __P((dev_t dev, int cmd, caddr_t data, int flag, struct proc *p));
void vxstart __P((struct tty *tp));
int vxstop __P((struct tty *tp, int flag));
static void vxputc __P((struct vxsoftc *sc, int port, u_char c));
static u_char vxgetc __P((struct vxsoftc *sc, int *port));
struct cfattach vx_ca = {
sizeof(struct vxsoftc), vxmatch, vxattach
};
struct cfdriver vx_cd = {
NULL, "vx", DV_TTY, 0
};
#define VX_UNIT(x) (int)(minor(x) / 9)
#define VX_PORT(x) (int)(minor(x) % 9)
extern int cputyp;
struct envelope *bpp_wait;
unsigned int board_addr;
struct tty * vxtty(dev)
dev_t dev;
{
int unit, port;
struct vxsoftc *sc;
unit = VX_UNIT(dev);
if (unit >= vx_cd.cd_ndevs ||
(sc = (struct vxsoftc *) vx_cd.cd_devs[unit]) == NULL) {
return (NULL);
}
port = VX_PORT(dev);
return sc->sc_info[port].tty;
}
int
vxmatch(parent, self, aux)
struct device *parent;
void *self;
void *aux;
{
struct vxreg *vx_reg;
struct vxsoftc *sc = self;
struct confargs *ca = aux;
int ret;
if (cputyp != CPU_187)
return 0;
#ifdef OLD_MAPPINGS
ca->ca_vaddr = ca->ca_paddr;
#endif
ca->ca_len = 0x10000; /* we know this. */
ca->ca_ipl = 3; /* we need interrupts for this board to work */
vx_reg = (struct vxreg *)ca->ca_vaddr;
board_addr = (unsigned int)ca->ca_vaddr;
if (!badvaddr(&vx_reg->ipc_cr, 1)){
if (ca->ca_vec & 0x03) {
printf("xvt: bad vector 0x%x\n", ca->ca_vec);
return (0);
}
return (1);
} else {
return (0);
}
}
void
vxattach(parent, self, aux)
struct device *parent;
struct device *self;
void *aux;
{
struct vxsoftc *sc = (struct vxsoftc *)self;
struct confargs *ca = aux;
int i;
/* set up dual port memory and registers and init*/
sc->vx_reg = (struct vxreg *)ca->ca_vaddr;
sc->channel = (struct channel *)(ca->ca_vaddr + 0x0100);
sc->sc_vme2 = ca->ca_master;
sc->sc_ipl = ca->ca_ipl;
sc->sc_vec = ca->ca_vec;
sc->board_addr = (unsigned int)ca->ca_vaddr;
printf("\n");
if (create_channels(sc)) {
printf("%s: failed to create channel %d\n", sc->sc_dev.dv_xname,
sc->channel->channel_number);
return;
}
if (vx_init(sc)){
printf("%s: failed to initialize\n", sc->sc_dev.dv_xname);
return;
}
/* enable interrupts */
sc->sc_ih_c.ih_fn = vx_intr;
sc->sc_ih_c.ih_arg = sc;
sc->sc_ih_c.ih_ipl = ca->ca_ipl;
sc->sc_ih_c.ih_wantframe = 0;
vmeintr_establish(ca->ca_vec, &sc->sc_ih_c);
evcnt_attach(&sc->sc_dev, "intr", &sc->sc_intrcnt);
}
int vxtdefaultrate = TTYDEF_SPEED;
dtr_ctl(sc, port, on)
struct vxsoftc *sc;
int port;
int on;
{
struct packet pkt;
bzero(&pkt, sizeof(struct packet));
pkt.command = CMD_IOCTL;
pkt.ioctl_cmd_l = IOCTL_TCXONC;
pkt.command_pipe_number = sc->channel_number;
pkt.status_pipe_number = sc->channel_number;
pkt.device_number = port;
if (on) {
pkt.ioctl_arg_l = 6; /* assert DTR */
} else {
pkt.ioctl_arg_l = 7; /* negate DTR */
}
bpp_send(sc, &pkt, NOWAIT);
return (pkt.error_l);
}
rts_ctl(sc, port, on)
struct vxsoftc *sc;
int port;
int on;
{
struct packet pkt;
bzero(&pkt, sizeof(struct packet));
pkt.command = CMD_IOCTL;
pkt.ioctl_cmd_l = IOCTL_TCXONC;
pkt.command_pipe_number = sc->channel_number;
pkt.status_pipe_number = sc->channel_number;
pkt.device_number = port;
if (on) {
pkt.ioctl_arg_l = 4; /* assert RTS */
} else {
pkt.ioctl_arg_l = 5; /* negate RTS */
}
bpp_send(sc, &pkt, NOWAIT);
return (pkt.error_l);
}
flush_ctl(sc, port, which)
struct vxsoftc *sc;
int port;
int which;
{
struct packet pkt;
bzero(&pkt, sizeof(struct packet));
pkt.command = CMD_IOCTL;
pkt.ioctl_cmd_l = IOCTL_TCFLSH;
pkt.command_pipe_number = sc->channel_number;
pkt.status_pipe_number = sc->channel_number;
pkt.device_number = port;
pkt.ioctl_arg_l = which; /* 0=input, 1=output, 2=both */
bpp_send(sc, &pkt, NOWAIT);
return (pkt.error_l);
}
int vx_mctl (dev, bits, how)
dev_t dev;
int bits;
int how;
{
int s, unit, port;
int vxbits;
struct vxsoftc *sc;
struct vx_info *vxt;
u_char msvr;
unit = VX_UNIT(dev);
port = VX_PORT(dev);
sc = (struct vxsoftc *) vx_cd.cd_devs[unit];
vxt = &sc->sc_info[port];
s = splvx();
switch (how) {
case DMSET:
if( bits & TIOCM_RTS) {
rts_ctl(sc, port, 1);
vxt->vx_linestatus |= TIOCM_RTS;
} else {
rts_ctl(sc, port, 0);
vxt->vx_linestatus &= ~TIOCM_RTS;
}
if( bits & TIOCM_DTR) {
dtr_ctl(sc, port, 1);
vxt->vx_linestatus |= TIOCM_DTR;
} else {
dtr_ctl(sc, port, 0);
vxt->vx_linestatus &= ~TIOCM_DTR;
}
break;
case DMBIC:
if ( bits & TIOCM_RTS) {
rts_ctl(sc, port, 0);
vxt->vx_linestatus &= ~TIOCM_RTS;
}
if ( bits & TIOCM_DTR) {
dtr_ctl(sc, port, 0);
vxt->vx_linestatus &= ~TIOCM_DTR;
}
break;
case DMBIS:
if ( bits & TIOCM_RTS) {
rts_ctl(sc, port, 1);
vxt->vx_linestatus |= TIOCM_RTS;
}
if ( bits & TIOCM_DTR) {
dtr_ctl(sc, port, 1);
vxt->vx_linestatus |= TIOCM_DTR;
}
break;
case DMGET:
bits = 0;
msvr = vxt->vx_linestatus;
if( msvr & TIOCM_DSR) {
bits |= TIOCM_DSR;
}
if( msvr & TIOCM_CD) {
bits |= TIOCM_CD;
}
if( msvr & TIOCM_CTS) {
bits |= TIOCM_CTS;
}
if( msvr & TIOCM_DTR) {
bits |= TIOCM_DTR;
}
if( msvr & TIOCM_RTS) {
bits |= TIOCM_RTS;
}
break;
}
splx(s);
bits = 0;
bits |= TIOCM_DTR;
bits |= TIOCM_RTS;
bits |= TIOCM_CTS;
bits |= TIOCM_CD;
bits |= TIOCM_DSR;
return (bits);
}
int vxopen (dev, flag, mode, p)
dev_t dev;
int flag;
int mode;
struct proc *p;
{
int s, unit, port;
struct vx_info *vxt;
struct vxsoftc *sc;
struct tty *tp;
struct open_packet opkt;
u_short code;
unit = VX_UNIT(dev);
port = VX_PORT(dev);
if (unit >= vx_cd.cd_ndevs ||
(sc = (struct vxsoftc *) vx_cd.cd_devs[unit]) == NULL) {
return (ENODEV);
}
/*flush_ctl(sc, port, 2);*/
bzero(&opkt, sizeof(struct packet));
opkt.eye_catcher[0] = 0x33;
opkt.eye_catcher[1] = 0x33;
opkt.eye_catcher[2] = 0x33;
opkt.eye_catcher[3] = 0x33;
opkt.command_pipe_number = sc->channel_number;
opkt.status_pipe_number = sc->channel_number;
opkt.command = CMD_OPEN;
opkt.device_number = port;
bpp_send(sc, &opkt, WAIT_POLL);
if (opkt.error_l) {
#ifdef DEBUG_VXT
printf("unit %d, port %d, ", unit, port);
printf("error = %d\n", opkt.error_l);
#endif
return (ENODEV);
}
code = opkt.event_code;
s = splvx();
vxt = &sc->sc_info[port];
if (vxt->tty) {
tp = vxt->tty;
} else {
tp = vxt->tty = ttymalloc();
}
/* set line status */
tp->t_state |= TS_CARR_ON;
if (code & E_DCD) {
tp->t_state |= TS_CARR_ON;
vxt->vx_linestatus |= TIOCM_CD;
}
if (code & E_DSR) {
vxt->vx_linestatus |= TIOCM_DSR;
}
if (code & E_CTS) {
vxt->vx_linestatus |= TIOCM_CTS;
}
tp->t_oproc = vxstart;
tp->t_param = vx_param;
tp->t_dev = dev;
if ((tp->t_state & TS_ISOPEN) == 0) {
tp->t_state |= TS_WOPEN;
ttychars(tp);
if (tp->t_ispeed == 0) {
/*
* only when cleared do we reset to defaults.
*/
tp->t_iflag = TTYDEF_IFLAG;
tp->t_oflag = TTYDEF_OFLAG;
tp->t_lflag = TTYDEF_LFLAG;
tp->t_ispeed = tp->t_ospeed = vxtdefaultrate;
tp->t_cflag = TTYDEF_CFLAG;
}
/*
* do these all the time
*/
if (vxt->vx_swflags & TIOCFLAG_CLOCAL)
tp->t_cflag |= CLOCAL;
if (vxt->vx_swflags & TIOCFLAG_CRTSCTS)
tp->t_cflag |= CRTSCTS;
if (vxt->vx_swflags & TIOCFLAG_MDMBUF)
tp->t_cflag |= MDMBUF;
vx_param(tp, &tp->t_termios);
ttsetwater(tp);
(void)vx_mctl(dev, TIOCM_DTR | TIOCM_RTS, DMSET);
tp->t_state |= TS_CARR_ON;
} else if (tp->t_state & TS_XCLUDE && p->p_ucred->cr_uid != 0) {
splx(s);
return (EBUSY);
}
/*
* Reset the tty pointer, as there could have been a dialout
* use of the tty with a dialin open waiting.
*/
tp->t_dev = dev;
sc->sc_info[port].open = 1;
read_wakeup(sc, port);
splx(s);
return ((*linesw[tp->t_line].l_open)(dev, tp));
}
int
vx_param(tp, t)
struct tty *tp;
struct termios *t;
{
int unit, port;
struct vxsoftc *sc;
int s;
dev_t dev;
dev = tp->t_dev;
unit = VX_UNIT(dev);
if (unit >= vx_cd.cd_ndevs ||
(sc = (struct vxsoftc *) vx_cd.cd_devs[unit]) == NULL) {
return (ENODEV);
}
port = VX_PORT(dev);
tp->t_ispeed = t->c_ispeed;
tp->t_ospeed = t->c_ospeed;
tp->t_cflag = t->c_cflag;
vx_ccparam(sc, t, port);
vx_unblock(tp);
return 0;
}
int
vxclose (dev, flag, mode, p)
dev_t dev;
int flag;
int mode;
struct proc *p;
{
int unit, port;
struct tty *tp;
struct vx_info *vxt;
struct vxsoftc *sc;
int s;
struct close_packet cpkt;
unit = VX_UNIT(dev);
if (unit >= vx_cd.cd_ndevs ||
(sc = (struct vxsoftc *) vx_cd.cd_devs[unit]) == NULL) {
return (ENODEV);
}
port = VX_PORT(dev);
/* flush_ctl(sc, port, 2); flush both input and output */
vxt = &sc->sc_info[port];
tp = vxt->tty;
(*linesw[tp->t_line].l_close)(tp, flag);
if((tp->t_cflag & HUPCL) != 0) {
rts_ctl(sc, port, 0);
dtr_ctl(sc, port, 0);
}
s = splvx();
bzero(&cpkt, sizeof(struct packet));
cpkt.eye_catcher[0] = 0x55;
cpkt.eye_catcher[1] = 0x55;
cpkt.eye_catcher[2] = 0x55;
cpkt.eye_catcher[3] = 0x55;
cpkt.command_pipe_number = sc->channel_number;
cpkt.status_pipe_number = sc->channel_number;
cpkt.command = CMD_CLOSE;
cpkt.device_number = port;
bpp_send(sc, &cpkt, NOWAIT);
splx(s);
ttyclose(tp);
sc->sc_info[port].open = 0;
return (0);
}
void
read_wakeup(sc, port)
struct vxsoftc *sc;
int port;
{
struct rring *rp;
struct read_wakeup_packet rwp;
volatile struct vx_info *vxt;
vxt = &sc->sc_info[port];
/*
* If we already have a read_wakeup paket
* for this port, do nothing.
*/
if (vxt->read_pending) {
return;
} else {
vxt->read_pending = 1;
}
bzero(&rwp, sizeof(struct packet));
rwp.eye_catcher[0] = 0x11;
rwp.eye_catcher[1] = 0x11;
rwp.eye_catcher[2] = 0x11;
rwp.eye_catcher[3] = 0x11;
rwp.command_pipe_number = sc->channel_number;
rwp.status_pipe_number = sc->channel_number;
rwp.command = CMD_READW;
rwp.device_number = port;
/*
* Do not wait. Characters will be transfered
* to (*linesw[tp->t_line].l_rint)(c,tp); by
* vx_intr() (IPC will notify via interrupt)
*/
bpp_send(sc, &rwp, NOWAIT);
}
int
vxread (dev, uio, flag)
dev_t dev;
struct uio *uio;
int flag;
{
int unit, port;
struct tty *tp;
volatile struct vx_info *vxt;
volatile struct vxsoftc *sc;
unit = VX_UNIT(dev);
if (unit >= vx_cd.cd_ndevs ||
(sc = (struct vxsoftc *) vx_cd.cd_devs[unit]) == NULL) {
return (ENODEV);
}
port = VX_PORT(dev);
vxt = &sc->sc_info[port];
tp = vxt->tty;
if (!tp) return ENXIO;
return ((*linesw[tp->t_line].l_read)(tp, uio, flag));
}
int
vxwrite (dev, uio, flag)
dev_t dev;
struct uio *uio;
int flag;
{
int unit, port;
struct tty *tp;
struct vx_info *vxt;
struct vxsoftc *sc;
struct wring *wp;
struct write_wakeup_packet wwp;
u_short get, put;
int i, cnt, s;
unit = VX_UNIT(dev);
if (unit >= vx_cd.cd_ndevs ||
(sc = (struct vxsoftc *) vx_cd.cd_devs[unit]) == NULL) {
return (ENODEV);
}
port = VX_PORT(dev);
vxt = &sc->sc_info[port];
tp = vxt->tty;
if (!tp) return ENXIO;
wp = sc->sc_info[port].wringp;
get = wp->get;
put = wp->put;
if ((put + 1) == get) {
bzero(&wwp, sizeof(struct packet));
wwp.eye_catcher[0] = 0x22;
wwp.eye_catcher[1] = 0x22;
wwp.eye_catcher[2] = 0x22;
wwp.eye_catcher[3] = 0x22;
wwp.command_pipe_number = sc->channel_number;
wwp.status_pipe_number = sc->channel_number;
wwp.command = CMD_WRITEW;
wwp.device_number = port;
bpp_send(sc, &wwp, WAIT_POLL);
if (wwp.error_l) {
return (ENXIO);
}
}
return ((*linesw[tp->t_line].l_write)(tp, uio, flag));
}
int
vxioctl (dev, cmd, data, flag, p)
dev_t dev;
int cmd;
caddr_t data;
int flag;
struct proc *p;
{
int error;
int unit, port;
struct tty *tp;
struct vx_info *vxt;
struct vxsoftc *sc;
unit = VX_UNIT(dev);
if (unit >= vx_cd.cd_ndevs ||
(sc = (struct vxsoftc *) vx_cd.cd_devs[unit]) == NULL) {
return (ENODEV);
}
port = VX_PORT(dev);
vxt = &sc->sc_info[port];
tp = vxt->tty;
if (!tp)
return ENXIO;
error = (*linesw[tp->t_line].l_ioctl)(tp, cmd, data, flag, p);
if (error >= 0)
return (error);
error = ttioctl(tp, cmd, data, flag, p);
if (error >= 0)
return (error);
switch (cmd) {
case TIOCSBRK:
/* */
break;
case TIOCCBRK:
/* */
break;
case TIOCSDTR:
(void) vx_mctl(dev, TIOCM_DTR | TIOCM_RTS, DMBIS);
break;
case TIOCCDTR:
(void) vx_mctl(dev, TIOCM_DTR | TIOCM_RTS, DMBIC);
break;
case TIOCMSET:
(void) vx_mctl(dev, *(int *) data, DMSET);
break;
case TIOCMBIS:
(void) vx_mctl(dev, *(int *) data, DMBIS);
break;
case TIOCMBIC:
(void) vx_mctl(dev, *(int *) data, DMBIC);
break;
case TIOCMGET:
*(int *)data = vx_mctl(dev, 0, DMGET);
break;
case TIOCGFLAGS:
*(int *)data = vxt->vx_swflags;
break;
case TIOCSFLAGS:
error = suser(p->p_ucred, &p->p_acflag);
if (error != 0)
return(EPERM);
vxt->vx_swflags = *(int *)data;
vxt->vx_swflags &= /* only allow valid flags */
(TIOCFLAG_SOFTCAR | TIOCFLAG_CLOCAL | TIOCFLAG_CRTSCTS);
break;
default:
return (ENOTTY);
}
return 0;
}
int
vxstop(tp, flag)
struct tty *tp;
int flag;
{
int s;
s = splvx();
if (tp->t_state & TS_BUSY) {
if ((tp->t_state & TS_TTSTOP) == 0)
tp->t_state |= TS_FLUSH;
}
splx(s);
return 0;
}
static u_char
vxgetc(sc, port)
struct vxsoftc *sc;
int *port;
{
return 0;
}
static void
vxputc(sc, port, c)
struct vxsoftc *sc;
int port;
u_char c;
{
struct wring *wp;
wp = sc->sc_info[port].wringp;
wp->data[wp->put++ & (WRING_BUF_SIZE-1)] = c;
wp->put &= (WRING_BUF_SIZE-1);
return;
}
u_short vxtspeed(speed)
int speed;
{
switch (speed) {
case B0:
return VB0;
break;
case B50:
return VB50;
break;
case B75:
return VB75;
break;
case B110:
return VB110;
break;
case B134:
return VB134;
break;
case B150:
return VB150;
break;
case B200:
return VB200;
break;
case B300:
return VB300;
break;
case B600:
return VB600;
break;
case B1200:
return VB1200;
break;
case B1800:
return VB1800;
break;
case B2400:
return VB2400;
break;
case B4800:
return VB4800;
break;
case B9600:
return VB9600;
break;
case B19200:
return VB19200;
break;
case B38400:
return VB38400;
break;
default:
return VB9600;
break;
}
}
int
vx_ccparam(sc, par, port)
struct vxsoftc *sc;
struct termios *par;
int port;
{
struct termio tio;
int imask=0, ints, s;
int cflag, iflag, oflag, lflag;
struct ioctl_a_packet pkt;
bzero(&pkt, sizeof(struct packet));
if (par->c_ospeed == 0) {
s = splvx();
/* dont kill the console */
if(sc->sc_info[port].vx_consio == 0) {
/* disconnect, drop RTS DTR stop reciever */
rts_ctl(sc, port, 0);
dtr_ctl(sc, port, 0);
}
splx(s);
return (0xff);
}
pkt.command = CMD_IOCTL;
pkt.ioctl_cmd_l = IOCTL_TCGETA;
pkt.command_pipe_number = sc->channel_number;
pkt.status_pipe_number = sc->channel_number;
pkt.device_number = port;
bpp_send(sc, &pkt, WAIT_POLL);
cflag = pkt.c_cflag;
cflag |= vxtspeed(par->c_ospeed);
switch (par->c_cflag & CSIZE) {
case CS5:
cflag |= VCS5;
imask = 0x1F;
break;
case CS6:
cflag |= VCS6;
imask = 0x3F;
break;
case CS7:
cflag |= VCS7;
imask = 0x7F;
break;
default:
cflag |= VCS8;
imask = 0xFF;
}
if (par->c_cflag & PARENB) cflag |= VPARENB; else cflag &= ~VPARENB;
if (par->c_cflag & PARODD) cflag |= VPARODD; else cflag &= ~VPARODD;
if (par->c_cflag & CREAD) cflag |= VCREAD; else cflag &= ~VCREAD;
if (par->c_cflag & CLOCAL) cflag |= VCLOCAL; else cflag &= ~VCLOCAL;
if (par->c_cflag & HUPCL) cflag |= VHUPCL; else cflag &= ~VHUPCL;
/*
if (par->c_iflag & BRKINT) iflag |= VBRKINT; else iflag &= ~VBRKINT;
if (par->c_iflag & ISTRIP) iflag |= VISTRIP; else iflag &= ~VISTRIP;
if (par->c_iflag & ICRNL) iflag |= VICRNL; else iflag &= ~VICRNL;
if (par->c_iflag & IXON) iflag |= VIXON; else iflag &= ~VIXON;
if (par->c_iflag & IXANY) iflag |= VIXANY; else iflag &= ~VIXANY;
if (par->c_oflag & OPOST) oflag |= VOPOST; else oflag &= ~VOPOST;
if (par->c_oflag & ONLCR) oflag |= VONLCR; else oflag &= ~VONLCR;
if (par->c_oflag & OXTABS) oflag |= VOXTABS; else oflag &= ~VOXTABS;
if (par->c_lflag & ECHO) lflag |= VECHO; else lflag &= ~VECHO;
if (par->c_lflag & ECHOE) lflag |= VECHOE; else lflag &= ~VECHOE;
if (par->c_lflag & ICANON) lflag |= VICANON; else lflag &= ~VICANON;
if (par->c_lflag & ISIG) lflag |= VISIG; else lflag &= ~VISIG;
*/
pkt.command = CMD_IOCTL;
pkt.ioctl_cmd_l = IOCTL_TCSETA;
pkt.command_pipe_number = sc->channel_number;
pkt.status_pipe_number = sc->channel_number;
pkt.device_number = port;
pkt.c_cflag = cflag;
/*
pkt.c_iflag = iflag;
pkt.c_oflag = oflag;
pkt.c_lflag = lflag;
*/
bpp_send(sc, &pkt, WAIT_POLL);
return imask;
}
void
vx_unblock(tp)
struct tty *tp;
{
tp->t_state &= ~TS_FLUSH;
if (tp->t_outq.c_cc != 0)
vxstart(tp);
}
void
vxstart(tp)
struct tty *tp;
{
dev_t dev;
u_char cbuf;
struct vxsoftc *sc;
struct wring *wp;
int cc, port, unit, s, cnt, i;
u_short get, put;
char buffer[WRING_BUF_SIZE];
char *wrdp;
dev = tp->t_dev;
port = VX_PORT(dev);
unit = VX_UNIT(dev);
if (unit >= vx_cd.cd_ndevs ||
(sc = (struct vxsoftc *) vx_cd.cd_devs[unit]) == NULL) {
return;
}
if ((tp->t_state & TS_ISOPEN) == 0)
return;
s = splvx();
if ((tp->t_state & (TS_TIMEOUT | TS_BUSY | TS_TTSTOP | TS_FLUSH)) == 0) {
tp->t_state |= TS_BUSY;
wp = sc->sc_info[port].wringp;
get = wp->get;
put = wp->put;
cc = tp->t_outq.c_cc;
while (cc > 0) {
cnt = min(WRING_BUF_SIZE, cc);
cnt = q_to_b(&tp->t_outq, buffer, cnt);
buffer[cnt] = 0;
for (i=0; i<cnt; i++) {
vxputc(sc, port, buffer[i]);
}
cc -= cnt;
}
tp->t_state &= ~TS_BUSY;
}
splx(s);
return;
}
void
read_chars(sc, port)
struct vxsoftc *sc;
int port;
{
/*
* This routine is called by vx_intr() when there are
* characters in the read ring. It will process one
* cooked line, put the chars in the line disipline ring,
* and then return. The characters may then
* be read by vxread.
*/
struct vx_info *vxt;
struct rring *rp;
struct read_wakeup_packet rwp;
struct tty *tp;
u_short get, put;
int frame_count, i, pc = 0, open;
char c;
vxt = &sc->sc_info[port];
tp = vxt->tty;
rp = vxt->rringp;
open = vxt->open;
get = rp->get;
put = rp->put;
#ifdef DEBUG_VXT
printf("read_chars() get=%d, put=%d ", get, put);
printf("open = %d ring at 0x%x\n", open, rp);
#endif
while (get != put) {
frame_count = rp->data[rp->get++ & (RRING_BUF_SIZE - 1)];
rp->get &= (RRING_BUF_SIZE - 1);
for (i=0; i<frame_count; i++) {
c = rp->data[rp->get++ & (RRING_BUF_SIZE - 1)];
rp->get &= (RRING_BUF_SIZE - 1);
if (open)
(*linesw[tp->t_line].l_rint)(c,tp);
}
c = rp->data[rp->get++ & (RRING_BUF_SIZE - 1)];
rp->get &= (RRING_BUF_SIZE - 1);
if (!(c & DELIMITER)) {
vx_frame (sc, port);
break;
} else {
break;
}
get = rp->get;
put = rp->put;
}
vxt->read_pending = 0;
read_wakeup(sc, port);
return;
}
ccode(sc, port, c)
struct vxsoftc *sc;
int port;
char c;
{
struct vx_info *vxt;
struct tty *tp;
tp = vxt->tty;
vxt = &sc->sc_info[port];
tp = vxt->tty;
(*linesw[tp->t_line].l_rint)(c,tp);
}
int
vx_intr(sc)
struct vxsoftc *sc;
{
struct envelope *envp, *next_envp;
struct envelope env;
struct packet *pktp, pkt;
int valid, i;
short cmd;
u_char port;
struct vme2reg *vme2 = (struct vme2reg *)sc->sc_vme2;
if (vme2->vme2_vbr & VME2_SYSFAIL){
/* do something... print_dump(sc); */
}
if (!cold) sc->sc_intrcnt.ev_count++;
while (env_isvalid(get_status_head(sc))) {
pktp = get_packet(sc, get_status_head(sc));
valid = env_isvalid(get_status_head(sc));
cmd = pktp->command;
port = pktp->device_number;
/* if we are waiting on this packet, strore the info so bpp_send
can process the packet */
if (sc->sc_bppwait_pktp == pktp)
memcpy2(&sc->sc_bppwait_pkt, pktp, sizeof(struct packet));
memcpy2(&pkt, pktp, sizeof(struct packet));
next_envp = get_next_envelope(get_status_head(sc));
envp = get_status_head(sc);
/* return envelope and packet to the free queues */
put_free_envelope(sc, envp);
put_free_packet(sc, pktp);
/* mark new status pipe head pointer */
set_status_head(sc, next_envp);
/* if it was valid, process packet */
switch (cmd) {
case CMD_READW:
#ifdef DEBUG_VXT
printf("READW Packet\n");
#endif
read_chars(sc, port);
return 1;
break;
case CMD_WRITEW:
#ifdef DEBUG_VXT
printf("WRITEW Packet\n"); /* Still don't know XXXsmurph */
#endif
return 1;
break;
case CMD_EVENT:
#ifdef DEBUG_VXT
printf("EVENT Packet\n");
#endif
vx_event(sc, &pkt);
return 1;
break;
case CMD_PROCCESED:
#ifdef DEBUG_VXT
printf("CMD_PROCCESED Packet\n");
#endif
return 1;
break;
default:
#ifdef DEBUG_VXT
printf("Other packet 0x%x\n", cmd);
#endif
return 1;
break;
}
}
return 1;
}
int
vx_event(sc, evntp)
struct vxsoftc *sc;
struct packet *evntp;
{
u_short code = evntp->event_code;
struct event_packet evnt;
struct vx_info *vxt;
vxt = &sc->sc_info[evntp->device_number];
if (code & E_INTR) {
ccode(sc, evntp->device_number, CINTR);
}
if (code & E_QUIT) {
ccode(sc, evntp->device_number, CQUIT);
}
if (code & E_HUP) {
rts_ctl(sc, evntp->device_number, 0);
dtr_ctl(sc, evntp->device_number, 0);
}
if (code & E_DCD) {
vxt->vx_linestatus |= TIOCM_CD;
}
if (code & E_DSR) {
vxt->vx_linestatus |= TIOCM_DSR;
}
if (code & E_CTS) {
vxt->vx_linestatus |= TIOCM_CTS;
}
if (code & E_LOST_DCD) {
vxt->vx_linestatus &= ~TIOCM_CD;
}
if (code & E_LOST_DSR) {
vxt->vx_linestatus &= ~TIOCM_DSR;
}
if (code & E_LOST_CTS) {
vxt->vx_linestatus &= ~TIOCM_CTS;
}
if (code & E_PR_FAULT) {
/* do something... */
}
if (code & E_PR_POUT) {
/* do something... */
}
if (code & E_PR_SELECT) {
/* do something... */
}
if (code & E_SWITCH) {
/* do something... */
}
if (code & E_BREAK) {
vx_break (sc, evntp->device_number);
}
/* send and event packet backe to the device */
bzero(&evnt, sizeof(struct event_packet));
evnt.command = CMD_EVENT;
evnt.device_number = evntp->device_number;
evnt.command_pipe_number = sc->channel_number;
/* return status on same channel */
evnt.status_pipe_number = sc->channel_number;
/* send packet to the firmware */
bpp_send(sc, &evnt, NOWAIT);
return 1;
}
void
vx_overflow (sc, port, ptime, msg)
struct vxsoftc *sc;
int port;
long *ptime;
u_char *msg;
{
log(LOG_WARNING, "%s port %d: overrun\n", sc->sc_dev.dv_xname, port);
return;
}
void
vx_frame (sc, port)
struct vxsoftc *sc;
int port;
{
log(LOG_WARNING, "%s port %d: frame error\n", sc->sc_dev.dv_xname, port);
return;
}
void
vx_break (sc, port)
struct vxsoftc *sc;
int port;
{
#ifdef DEBUG_KERN
Debugger();
#else
log(LOG_WARNING, "%s port %d: break detected\n", sc->sc_dev.dv_xname, port);
#endif
return;
}
/*
* Initialization and Buffered Pipe Protocol (BPP) code
*/
/* special function for 16 bit data transfer */
/* Not needed now that I figured out VME bus */
/* mappings and address modifiers, but I don't */
/* want to change them :) */
void *
memcpy2(void *dest, const void *src, size_t size)
{
int i;
short *d, *s;
d = (short*) dest;
s = (short*) src;
for (i=0; i<(size/2); i++) {
*d = *s;
d++;
s++;
}
}
void
wzero(void *addr, size_t size)
{
int i;
short *d;
d = (short*) addr;
for (i=0; i<(size/2); i++) {
*d = 0;
d++;
}
}
int
create_free_queue(sc)
struct vxsoftc *sc;
{
int i;
struct envelope *envp;
struct envelope env;
struct packet *pktp;
struct packet pkt;
envp = (struct envelope *)ENVELOPE_AREA;
sc->elist_head = envp;
for (i=0; i < NENVELOPES; i++) {
bzero(envp, sizeof(struct envelope));
if (i==(NENVELOPES - 1)) {
envp->link = NULL;
} else {
envp->link = (u_long)envp + sizeof(struct envelope);
}
envp->packet_ptr = NULL;
envp->valid_flag = 0;
envp++;
}
sc->elist_tail = --envp;
pktp = (struct packet *)PACKET_AREA;
sc->plist_head = pktp;
for (i=0; i < NPACKETS; i++) {
bzero(pktp, sizeof(struct packet));
if (i==(NPACKETS - 1)) {
pktp->link = NULL;
} else {
pktp->link = (u_long)pktp + sizeof(struct packet);
}
pktp++;
}
sc->plist_tail = --pktp;
return 0; /* no error */
}
void *
get_free_envelope(sc)
struct vxsoftc *sc;
{
void *envp;
envp = sc->elist_head;
sc->elist_head = (struct envelope *)sc->elist_head->link;
bzero(envp, sizeof(struct envelope));
return envp;
}
void
put_free_envelope(sc, ep)
struct vxsoftc *sc;
void * ep;
{
struct envelope *envp = (struct envelope *)ep;
bzero(envp, sizeof(struct envelope));
sc->elist_tail->link = (ulong)envp;
envp->link = NULL;
sc->elist_tail = envp;
}
void*
get_free_packet(sc)
struct vxsoftc *sc;
{
struct packet *pktp;
pktp = sc->plist_head;
sc->plist_head = (struct packet *)sc->plist_head->link;
bzero(pktp, sizeof(struct packet));
return pktp;
}
void
put_free_packet(sc, pp)
struct vxsoftc *sc;
void *pp;
{
struct packet *pktp = (struct packet *)pp;
/*bzero(pktp, sizeof(struct packet));*/
pktp->command = CMD_PROCCESED;
sc->plist_tail->link = (u_long)pktp;
pktp->link = NULL;
sc->plist_tail = pktp;
}
/*
* This is the nitty gritty. All the rest if this code
* was hell to come by. Getting this right from the
* Moto manual took *time*!
*/
int
create_channels(sc)
struct vxsoftc *sc;
{
struct envelope *envp;
struct envelope env;
struct packet *pktp;
u_char valid;
u_short status;
u_short tas, csr;
struct vxreg *ipc_csr;
ipc_csr = sc->vx_reg;
/* wait for busy bit to clear */
while ((ipc_csr->ipc_cr & IPC_CR_BUSY));
create_free_queue(sc);
/* set up channel header. we only want one */
tas = ipc_csr->ipc_tas;
while (!(tas & IPC_TAS_VALID_STATUS)) {
envp = get_free_envelope(sc);
sc->channel->command_pipe_head_ptr_h = HI(envp);
sc->channel->command_pipe_head_ptr_l = LO(envp);
sc->channel->command_pipe_tail_ptr_h = sc->channel->command_pipe_head_ptr_h;
sc->channel->command_pipe_tail_ptr_l = sc->channel->command_pipe_head_ptr_l;
envp = get_free_envelope(sc);
sc->channel->status_pipe_head_ptr_h = HI(envp);
sc->channel->status_pipe_head_ptr_l = LO(envp);
sc->channel->status_pipe_tail_ptr_h = sc->channel->status_pipe_head_ptr_h;
sc->channel->status_pipe_tail_ptr_l = sc->channel->status_pipe_head_ptr_l;
sc->channel->interrupt_level = sc->sc_ipl;
sc->channel->interrupt_vec = sc->sc_vec;
sc->channel->channel_priority = 0;
sc->channel->channel_number = 0;
sc->channel->valid = 1;
sc->channel->address_modifier = 0x8D; /* A32/D16 supervisor data access */
sc->channel->datasize = 0; /* 32 bit data mode */
/* loop until TAS bit is zero */
while ((ipc_csr->ipc_tas & IPC_TAS_TAS));
ipc_csr->ipc_tas |= IPC_TAS_TAS;
/* load address of channel header */
ipc_csr->ipc_addrh = HI(sc->channel);
ipc_csr->ipc_addrl = LO(sc->channel);
/* load address modifier reg (supervisor data access) */
ipc_csr->ipc_amr = 0x8D;
/* load tas with create channel command */
ipc_csr->ipc_tas |= IPC_CSR_CREATE;
/* set vaild command bit */
ipc_csr->ipc_tas |= IPC_TAS_VALID_CMD;
/* notify IPC of the CSR command */
ipc_csr->ipc_cr |= IPC_CR_ATTEN;
/* loop until IPC sets vaild status bit */
delay(5000);
tas = ipc_csr->ipc_tas;
}
/* save the status */
status = ipc_csr->ipc_sr;
/* set COMMAND COMPLETE bit */
ipc_csr->ipc_tas |= IPC_TAS_COMPLETE;
/* notify IPC that we are through */
ipc_csr->ipc_cr |= IPC_CR_ATTEN;
/* check and see if the channel was created */
if (!status && sc->channel->valid) {
sc->channel_number = sc->channel->channel_number;
printf("%s: created channel %d\n", sc->sc_dev.dv_xname,
sc->channel->channel_number);
return 0;
} else {
switch (status) {
case 0x0000:
printf("%s: channel not valid\n",
sc->sc_dev.dv_xname);
break;
case 0xFFFF:
printf("%s: invalid CSR command\n",
sc->sc_dev.dv_xname);
break;
case 0xC000:
printf("%s: could not read channel structure\n",
sc->sc_dev.dv_xname);
break;
case 0x8000:
printf("%s: could not write channel structure\n",
sc->sc_dev.dv_xname);
break;
default:
printf("%s: unknown IPC CSR command error 0x%x\n",
sc->sc_dev.dv_xname, status);
break;
}
return status; /* error */
}
}
void
print_dump(sc)
struct vxsoftc *sc;
{
char *dump_area, *end_dump, *dumpp;
char dump[209];
char dump2[209];
bzero(&dump, 209);
dump_area = (char *)0xff780030;
memcpy2(&dump, dump_area, 208);
printf("%s", dump);
}
void *
get_next_envelope(thisenv)
struct envelope *thisenv;
{
return ((void *)thisenv->link);
}
int
env_isvalid(thisenv)
struct envelope *thisenv;
{
return thisenv->valid_flag;
}
struct envelope *
get_cmd_tail(sc)
struct vxsoftc *sc;
{
unsigned long retaddr;
retaddr = (unsigned long)sc->vx_reg;
retaddr += sc->channel->command_pipe_tail_ptr_l;
return ((struct envelope *)retaddr);
}
struct envelope *
get_status_head(sc)
struct vxsoftc *sc;
{
unsigned long retaddr;
retaddr = (unsigned long)sc->vx_reg;
retaddr += sc->channel->status_pipe_head_ptr_l;
return ((struct envelope *)retaddr);
}
void
set_status_head(sc, envp)
struct vxsoftc *sc;
void *envp;
{
sc->channel->status_pipe_head_ptr_h = HI(envp);
sc->channel->status_pipe_head_ptr_l = LO(envp);
return;
}
struct packet *
get_packet(sc, thisenv)
struct vxsoftc *sc;
struct envelope *thisenv;
{
struct envelope env;
unsigned long baseaddr;
if (thisenv == NULL) return NULL;
baseaddr = (unsigned long)sc->vx_reg;
/*
* packet ptr returned on status pipe is only last two bytes
* so we must supply the full address based on the board address.
* This also works for all envelopes because every address is an
* offset to the board address
*/
baseaddr |= thisenv->packet_ptr;
return ((void*)baseaddr);
}
/*
* Send a command via BPP
*/
int
bpp_send(struct vxsoftc *sc, void *pkt, int wait_flag)
{
struct envelope *envp;
struct init_packet init, *initp;
struct packet *wpktp, *pktp, *testpktp;
struct vme2reg *vme2 = (struct vme2reg *)sc->sc_vme2;
unsigned long newenv;
int i, s;
/* load up packet in dual port mem */
pktp = get_free_packet(sc);
memcpy2(pktp, pkt, sizeof(struct packet));
envp = get_cmd_tail(sc);
newenv = (unsigned long)get_free_envelope(sc); /* put a NULL env on the tail */
envp->link = newenv;
sc->channel->command_pipe_tail_ptr_h = HI(newenv);
sc->channel->command_pipe_tail_ptr_l = LO(newenv);
envp->packet_ptr = (u_long)pktp; /* add the command packet */
envp->valid_flag = 1; /* set valid command flag */
sc->vx_reg->ipc_cr |= IPC_CR_ATTEN;
if (wait_flag) { /* wait for a packet to return */
while (pktp->command != CMD_PROCCESED) {
#ifdef DEBUG_VXT
printf("Polling for packet 0x%x in envelope 0x%x...\n", pktp, envp);
#endif
vx_intr(sc);
delay(5000);
}
memcpy2(pkt, pktp, sizeof(struct packet));
return 0;
}
return 0; /* no error */
}
/*
* BPP commands
*/
int
vx_init(sc)
struct vxsoftc *sc;
{
int i;
struct init_info *infp, inf;
struct wring *wringp;
struct rring *rringp;
struct termio def_termio;
struct init_packet init;
struct event_packet evnt;
bzero(&def_termio, sizeof(struct termio));
/* init wait queue */
bzero(&sc->sc_bppwait_pkt, sizeof(struct packet));
sc->sc_bppwait_pktp = NULL;
/* set up init_info array */
wringp = (struct wring *)WRING_AREA;
rringp = (struct rring *)RRING_AREA;
infp = (struct init_info *)INIT_INFO_AREA;
for (i=0; i<9; i++) {
bzero(&inf, sizeof(struct init_info));
infp->write_ring_ptr_h = HI(wringp);
infp->write_ring_ptr_l = LO(wringp);
sc->sc_info[i].wringp = wringp;
infp->read_ring_ptr_h = HI(rringp);
infp->read_ring_ptr_l = LO(rringp);
sc->sc_info[i].rringp = rringp;
#ifdef DEBUG_VXT
printf("write at 0x%8x, read at 0x%8x\n", wringp, rringp);
#endif
infp->write_ring_size = WRING_DATA_SIZE;
infp->read_ring_size = RRING_DATA_SIZE;
infp->def_termio.c_iflag = VBRKINT;
infp->def_termio.c_oflag = 0;
infp->def_termio.c_cflag = (VB9600 | VCS8);
infp->def_termio.c_lflag = VISIG; /* enable signal processing */
infp->def_termio.c_line = 1; /* raw line disipline, we want to control it! */
infp->def_termio.c_cc[0] = CINTR;
infp->def_termio.c_cc[1] = CQUIT;
infp->def_termio.c_cc[2] = CERASE;
infp->def_termio.c_cc[3] = CKILL;
infp->def_termio.c_cc[4] = 20;
infp->def_termio.c_cc[5] = 2;
infp->reserved1 = 0; /* Must be Zero */
infp->reserved2 = 0;
infp->reserved3 = 0;
infp->reserved4 = 0;
wringp++; rringp++; infp++;
}
/* set up init_packet */
bzero(&init, sizeof(struct init_packet));
init.eye_catcher[0] = 0x12;
init.eye_catcher[1] = 0x34;
init.eye_catcher[2] = 0x56;
init.eye_catcher[3] = 0x78;
init.command = CMD_INIT;
init.command_pipe_number = sc->channel_number;
/* return status on the same channel */
init.status_pipe_number = sc->channel_number;
init.interrupt_level = sc->sc_ipl;
init.interrupt_vec = sc->sc_vec;
init.init_info_ptr_h = HI(INIT_INFO_AREA);
init.init_info_ptr_l = LO(INIT_INFO_AREA);
/* send packet to the firmware and wait for completion */
bpp_send(sc, &init, WAIT_POLL);
/* check for error */
if (init.error_l !=0) {
return init.error_l;
} else {
/* send one event packet to each device; */
for (i=0; i<9; i++) {
bzero(&evnt, sizeof(struct event_packet));
evnt.command = CMD_EVENT;
evnt.device_number = i;
evnt.command_pipe_number = sc->channel_number;
/* return status on same channel */
evnt.status_pipe_number = sc->channel_number;
/* send packet to the firmware */
bpp_send(sc, &evnt, NOWAIT);
}
return 0;
}
}
| 24.714539 | 84 | 0.609465 | [
"vector"
] |
60aec12e7628000dcbeae14e4987fa635fb3f18c | 4,547 | h | C | models/lnd/clm/src/iac/giac/gcam/cvs/objects/sectors/include/tran_subsector.h | E3SM-Project/iESM | 2a1013a3d85a11d935f1b2a8187a8bbcd75d115d | [
"BSD-3-Clause-LBNL"
] | 9 | 2018-05-15T02:10:40.000Z | 2020-01-10T18:27:31.000Z | models/lnd/clm/src/iac/giac/gcam/cvs/objects/sectors/include/tran_subsector.h | zhangyue292/iESM | 2a1013a3d85a11d935f1b2a8187a8bbcd75d115d | [
"BSD-3-Clause-LBNL"
] | 3 | 2018-10-12T18:41:56.000Z | 2019-11-12T15:18:49.000Z | models/lnd/clm/src/iac/giac/gcam/cvs/objects/sectors/include/tran_subsector.h | zhangyue292/iESM | 2a1013a3d85a11d935f1b2a8187a8bbcd75d115d | [
"BSD-3-Clause-LBNL"
] | 3 | 2018-05-15T02:10:33.000Z | 2021-04-06T17:45:49.000Z | #ifndef _TRAN_SUBSECTOR_H_
#define _TRAN_SUBSECTOR_H_
#if defined(_MSC_VER)
#pragma once
#endif
/*
* LEGAL NOTICE
* This computer software was prepared by Battelle Memorial Institute,
* hereinafter the Contractor, under Contract No. DE-AC05-76RL0 1830
* with the Department of Energy (DOE). NEITHER THE GOVERNMENT NOR THE
* CONTRACTOR MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY
* LIABILITY FOR THE USE OF THIS SOFTWARE. This notice including this
* sentence must appear on any copies of this computer software.
*
* EXPORT CONTROL
* User agrees that the Software will not be shipped, transferred or
* exported into any country or used in any manner prohibited by the
* United States Export Administration Act or any other applicable
* export laws, restrictions or regulations (collectively the "Export Laws").
* Export of the Software may require some form of license or other
* authority from the U.S. Government, and failure to obtain such
* export control license may result in criminal liability under
* U.S. laws. In addition, if the Software is identified as export controlled
* items under the Export Laws, User represents and warrants that User
* is not a citizen, or otherwise located within, an embargoed nation
* (including without limitation Iran, Syria, Sudan, Cuba, and North Korea)
* and that User is not otherwise prohibited
* under the Export Laws from receiving the Software.
*
* Copyright 2011 Battelle Memorial Institute. All Rights Reserved.
* Distributed as open-source under the terms of the Educational Community
* License version 2.0 (ECL 2.0). http://www.opensource.org/licenses/ecl2.php
*
* For further details, see: http://www.globalchange.umd.edu/models/gcam/
*
*/
/*!
* \file tran_subsector.h
* \ingroup Objects
* \brief The TranSubsector header file.
* \author Marshall Wise, Sonny Kim, Josh Lurz
*/
#include <vector>
#include <string>
#include <xercesc/dom/DOMNode.hpp>
#include "sectors/include/subsector.h"
// Forward declarations
class GDP;
class MoreSectorInfo;
class Demographic;
class IInfo;
/*!
* \ingroup Objects
* \brief A derived subsector representing a mode of transportation.
* \author Sonny Kim, Josh Lurz, Steve Smith, Marshall Wise
*/
class TranSubsector: public Subsector{
public:
TranSubsector( const std::string& regionName, const std::string& sectorName );
static const std::string& getXMLNameStatic();
virtual void completeInit( const IInfo* aSectorInfo,
DependencyFinder* aDependencyFinder,
ILandAllocator* aLandAllocator );
virtual void initCalc( NationalAccount* aNationalAccount,
const Demographic* aDemographics,
const MoreSectorInfo* aMoreSectorInfo,
const int aPeriod );
double getPrice( const GDP* aGDP, const int aPeriod ) const;
virtual void setOutput( const double aVariableSubsectorDemand,
const double aFixedOutputScaleFactor,
const GDP* aGDP,
const int aPeriod );
protected:
std::vector<double> speed; // Speed of Mode in Miles/hour
std::vector<double> mPopulation; // copy of population from demographics
std::vector<double> popDenseElasticity; // Population Density Elasticity of mode
std::vector<double> mServiceOutputs; //!< Service output by period.
double popDensity; // population density per land area
virtual void MCoutputSupplySector( const GDP* aGDP ) const;
virtual void MCoutputAllSectors( const GDP* aGDP,
const IndirectEmissionsCalculator* aIndirectEmissionsCalc,
const std::vector<double> aSectorOutput ) const;
bool XMLDerivedClassParse( const std::string& nodeName, const xercesc::DOMNode* curr );
void toInputXMLDerived( std::ostream& out, Tabs* tabs ) const;
void toDebugXMLDerived( const int period, std::ostream& out, Tabs* tabs ) const;
const std::string& getXMLName() const;
double getTimeValue( const GDP* aGDP, const int aPeriod ) const;
double getTimeInTransit( const int aPeriod ) const;
double getServicePerCapita( const int aPeriod ) const;
double getGeneralizedPrice( const GDP* aGDP, const int aPeriod ) const;
private:
static const std::string XML_NAME; //!< XML name of this object.
bool mAddTimeValue; //!< add value of time to price term
//! Save time value for debugging purposes.
mutable double mTimeValue;
};
#endif // _TRAN_SUBSECTOR_H_
| 39.53913 | 95 | 0.717616 | [
"object",
"vector"
] |
60b040e64e3b4a6c7b048e38f7ae9f431007e5d1 | 7,692 | h | C | sdk_k64f/middleware/multicore/erpc/erpc_c/transports/erpc_mu_transport.h | Sir-Branch/k64f-starter-template | f8959fd185f090363d180d69f84c2727e37cbeeb | [
"MIT"
] | 1 | 2020-08-23T20:24:19.000Z | 2020-08-23T20:24:19.000Z | sdk_k64f/middleware/multicore/erpc/erpc_c/transports/erpc_mu_transport.h | Sir-Branch/xxxx-starter-template | f8959fd185f090363d180d69f84c2727e37cbeeb | [
"MIT"
] | 1 | 2020-08-24T00:41:48.000Z | 2020-08-24T02:17:44.000Z | sdk_k64f/middleware/multicore/erpc/erpc_c/transports/erpc_mu_transport.h | Sir-Branch/xxxx-starter-template | f8959fd185f090363d180d69f84c2727e37cbeeb | [
"MIT"
] | null | null | null | /*
* Copyright 2017 NXP
* All rights reserved.
*
*
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef _EMBEDDED_RPC__MU_TRANSPORT_H_
#define _EMBEDDED_RPC__MU_TRANSPORT_H_
#include "erpc_config_internal.h"
#if ERPC_THREADS
#include "erpc_threading.h"
#endif
#include "erpc_message_buffer.h"
#include "erpc_transport.h"
#include "fsl_device_registers.h"
#include "fsl_mu.h"
/*!
* @addtogroup mu_transport
* @{
* @file
*/
////////////////////////////////////////////////////////////////////////////////
// Definitions
////////////////////////////////////////////////////////////////////////////////
#if ERPC_TRANSPORT_MU_USE_MCMGR
/*!< Count of MU tx/rx registers to be used by this transport layer.
Keep one MU channel for MCMGR operations. */
#define MU_REG_COUNT (MU_RR_COUNT - 1U)
#define MU_LAST_REG_IDX 2
#define MU_RX_Interrupt_Handler(x) MU_RX_Interrupt(x)
#define MU_RX_Interrupt(number) MU_Rx##number##FullFlagISR
#define MU_RxFullFlagISRCallback MU_RX_Interrupt_Handler(MU_LAST_REG_IDX)
#define MU_TX_Interrupt_Handler(x) MU_TX_Interrupt(x)
#define MU_TX_Interrupt(number) MU_Tx##number##EmptyFlagISR
#define MU_TxEmptyFlagISRCallback MU_TX_Interrupt_Handler(MU_LAST_REG_IDX)
#else
#define MU_REG_COUNT (MU_RR_COUNT) /*!< Count of MU tx/rx registers to be used by this transport layer */
#endif /* ERPC_TRANSPORT_MU_USE_MCMGR */
////////////////////////////////////////////////////////////////////////////////
// Classes
////////////////////////////////////////////////////////////////////////////////
namespace erpc {
/*!
* @brief Transport that uses Messaging Unit (MU) for interprocessor messaging.
*
* This transport layer use the Messaging Unit (MU), which enables two processors within
* the SoC to communicate and coordinate by passing messages (e.g. data, status and control)
* through the MU interface.
* The MU has four transmit and four receive registers used for communication between cores,
* the transport layer use count of registers defined by macro MU_REG_COUNT (default setting
* is use all MU registers).
* The communication uses the interrupt from the MU, to be possible use this transport
* layer on different platform must be specified this macros:
* MU_IRQ_HANDLER - name of the MU irq handler
* MU_IRQ - name of MU irq to be possible enable it by passing it as argument to function EnableIRQ()
* MU_IRQ_PRIORITY - number of priority passed as argument to function NVIC_SetPriority()
*
* @ingroup mu_transport
*/
class MUTransport : public Transport
{
public:
/*!
* @brief Constructor of MU transport
*
* This function initializes object attributes.
*/
MUTransport(void);
/*!
* @brief Destructor of MU transport
*/
virtual ~MUTransport(void);
/*!
* @brief Initialization of MU transport layer
*
* Initialize MU peripheral and enable MU interrupt in NVIC.
*
* @param[in] Base address of MU peripheral
*
* @retval kErpcStatus_Success When init function was executed successfully.
* @retval kErpcStatus_InitFailed When init function wasn't executed successfully.
*/
virtual erpc_status_t init(MU_Type *muBase);
/*!
* @brief Start receiving data and stores it to passed message buffer
*
* Initialize receiving of message, it is blocking until doesn't receive complete message.
*
* @param[in] message Message buffer, which will be filled by incoming message.
*
* @return kErpcStatus_Success
*/
virtual erpc_status_t receive(MessageBuffer *message);
/*!
* @brief Function to send prepared message.
*
* @param[in] message Pass message buffer to send.
*
* @retval kErpcStatus_SendFailed Failed to send message buffer.
* @retval kErpcStatus_Success Successfully sent all data.
*/
virtual erpc_status_t send(MessageBuffer *message);
/*!
* @brief Function to check if is new message to receive.
*
* This function should be called before blocking function receive() to avoid waiting for new message.
*
* @return True if exist new message, else false.
*/
virtual bool hasMessage() { return m_newMessage; }
#if ERPC_TRANSPORT_MU_USE_MCMGR
/*!
* @brief Callback function called from MU IRQ when TxEmptyFlag is set
*
* This function calls tx_cb() to handle tx empty irq for the particular instance of the MUTransport.
* MU interrupts are managed by the MCMGR component and the mu_transport overloads the weak handler
* defined in MCMGR MU ISR table.
*/
static void mu_tx_empty_irq_callback(void);
/*!
* @brief Callback function called from MU IRQ when RxFullFlag is set
*
* This function calls rx_cb() to handle rx full irq for the particular instance of the MUTransport.
* MU interrupts are managed by the MCMGR component and the mu_transport overloads the weak handler
* defined in MCMGR MU ISR table.
*/
static void mu_rx_full_irq_callback(void);
#else
/*!
* @brief Callback function called from MU IRQ
*
* This function reads status flags of MU and base on the evnet which cause the irq
* calls function rx_cb() to handle rx full irq or tx_cb() to handle tx empty irq
* for the particular instance of the MUTransport
*/
static void mu_irq_callback(void);
#endif /* ERPC_TRANSPORT_MU_USE_MCMGR */
protected:
/*!
* @brief Function called from MU IRQ when the MU RX full flag is asserted and the IRQ is enabled
*
* When is this function invoked prior receive function (bare metal case) the m_newMessage
* flag is set and the MU rx full interrupt is disabled.
* When is this function invoked after receive function the data from MU registers
* is copied to this receiving buffer passed in receive function.
* When is received whole message unblock the receive function.
*/
void rx_cb(void);
/*!
* @brief Function called from MU IRQ when the MU TX empty flag is asserted and the IRQ is enabled
*
* Write data from the buffer passed in send function to MU registers.
* When is sent whole message unblock the send function.
*/
void tx_cb(void);
volatile bool m_newMessage; /*!< Flag used in function hasMessage() to inform server by polling function that
message is ready for receiving */
uint32_t m_rxMsgSize; /*!< Size of received message - count of bytes to must be received to complete currently
received message */
uint32_t m_rxCntBytes; /*!< Count of currently received bytes of message */
uint32_t *volatile m_rxBuffer; /*!< Pointer to buffer to which is copied data from MU registers during receiving */
uint32_t m_txMsgSize; /*!< Size of transmitted message - count of bytes to must be transmitted to send complete
message */
uint32_t m_txCntBytes; /*!< Count of currently received bytes of message */
uint32_t *volatile m_txBuffer; /*!< Pointer to buffer from which is copied data to MU registers during sending */
#if ERPC_THREADS
Semaphore m_rxSemaphore; /*!< Semaphore used by RTOS to block task until the receiving is not complete */
Semaphore m_txSemaphore; /*!< Semaphore used by RTOS to block task until the sending is not complete */
Mutex m_sendLock; /*!< Mutex protecting send. */
Mutex m_receiveLock; /*!< Mutex protecting receive. */
#endif
MU_Type *m_muBase; /*!< Base address of MU peripheral */
};
} // namespace erpc
/*! @} */
#endif // _EMBEDDED_RPC__MU_TRANSPORT_H_
| 37.891626 | 120 | 0.673687 | [
"object"
] |
60b1882bbecde987cd9e6f8977a4c1c07734eb53 | 1,177 | h | C | packager/media/base/test/rsa_test_data.h | Acidburn0zzz/shaka-packager | c540e5afa0a649285dc5a2c2a1ce68cc76ab1bd5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2016-07-26T04:05:06.000Z | 2016-07-26T04:05:06.000Z | packager/media/base/test/rsa_test_data.h | Acidburn0zzz/shaka-packager | c540e5afa0a649285dc5a2c2a1ce68cc76ab1bd5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | packager/media/base/test/rsa_test_data.h | Acidburn0zzz/shaka-packager | c540e5afa0a649285dc5a2c2a1ce68cc76ab1bd5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 Google Inc. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
//
// RSA test data generated using fake_prng for purposes of testing.
#ifndef MEDIA_BASE_RSA_TEST_DATA_H_
#define MEDIA_BASE_RSA_TEST_DATA_H_
#include <string>
#include "packager/base/macros.h"
namespace shaka {
namespace media {
/// Self generated test vector to verify algorithm stability.
struct RsaTestSet {
RsaTestSet();
~RsaTestSet();
std::string public_key;
std::string private_key;
std::string test_message;
std::string encrypted_message;
std::string signature;
};
/// Collection of test sets.
class RsaTestData {
public:
RsaTestData();
~RsaTestData();
const RsaTestSet& test_set_3072_bits() const { return test_set_3072_bits_; }
const RsaTestSet& test_set_2048_bits() const { return test_set_2048_bits_; }
private:
RsaTestSet test_set_3072_bits_;
RsaTestSet test_set_2048_bits_;
DISALLOW_COPY_AND_ASSIGN(RsaTestData);
};
} // namespace media
} // namespace shaka
#endif // MEDIA_BASE_RSA_TEST_DATA_H_
| 23.078431 | 78 | 0.757009 | [
"vector"
] |
60b4f90af04e34faa20d4daef18fb73ceea1bf3c | 2,711 | h | C | header.h | EVILBEAN-cmd/RSA | e90687b7bcd1591fbe30641d2c57fb77f930914d | [
"MIT"
] | 1 | 2021-08-05T14:19:34.000Z | 2021-08-05T14:19:34.000Z | header.h | EVILBEAN-cmd/RSA-encryption-decryption | e90687b7bcd1591fbe30641d2c57fb77f930914d | [
"MIT"
] | 4 | 2021-08-12T22:04:34.000Z | 2021-08-12T22:07:32.000Z | header.h | EVILBEAN-cmd/RSA | e90687b7bcd1591fbe30641d2c57fb77f930914d | [
"MIT"
] | null | null | null | #ifndef HEADER_H
#define HEADER_H
#include <stdio.h>
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <unistd.h>
#include <vector>
// obviously
using namespace std;
// Checks if number is prime
// @param n integer to be checked
// @return true or false
bool isPrime(long long n);
// Finds the greatest common divisor of two integers a and b \n
// source: https://www.inf.hs-flensburg.de/lang/krypto/algo/euklid.htm#section3 12.08.2021
// @param a first integer
// @param b second integer
// @returns u (only variable that is needed in this code)
unsigned long long extgcd(unsigned long long a, unsigned long long b);
// source: https://www.inf.hs-flensburg.de/lang/krypto/grund/inverses-element.htm 12.08.2021
// @param a inverse to be calculated
// @param n modulo number
// @returns the modinverse
unsigned long long modinverse(unsigned long long a, unsigned long long n);
// simple struct to return three results
struct result{
unsigned long long e; // first public key part
unsigned long long d; // first private key part
unsigned long long n; // second private and public key part
};
// Creates the public and private key pairs
// @returns results as a struct with the key pairs
result createKeys();
// Modular exponentiation (b^e mod m) \n
// source: https://en.wikipedia.org/wiki/Modular_exponentiation 12.08.2021
// @param base integer b
// @param exponent exponent of integer b
// @param modulus divided by integer m
// @return c the remainder
unsigned long long modular_pow(unsigned long long base, unsigned long long exponent, unsigned long long modulus);
// encrypts numbers with c = m^e mod n
// @param m number to be ciphered
// @param e first part of public key
// @param n second part if public key
// @return c the ciphered number
unsigned long long encryption(unsigned long long m, unsigned long long e, unsigned long long n);
// decrypts numbers with m = c^d mod n
// @param c ciphered number
// @param d first part of private key
// @param n second part if private key
// @return m the decrypted number
unsigned long long decryption(unsigned long long c, unsigned long long d, unsigned long long n);
// source: https://www.geeksforgeeks.org/print-all-prime-factors-of-a-given-number/ 12.08.2021
// @param factors vector of factors of n
// @param n integer for prime factorization
void primeFactors(vector<unsigned long long>& factors, long long n);
// finds the private key form the public key with help of prime factorization
// @param e first part of public key
// @param n second part of public key
// @returns d the first part of the private key
unsigned long long rsaFactoring(unsigned long long e, unsigned long long n);
#endif | 30.806818 | 113 | 0.739579 | [
"vector"
] |
60c1cbeba6496ca2248e78059c59d133ed92e11c | 38,885 | c | C | dlls/ntdll/file.c | roytam1/wine-win31look | 2c8284c53a46c1309fbf62a3998538c44fcbf207 | [
"MIT"
] | 1 | 2019-10-23T04:07:16.000Z | 2019-10-23T04:07:16.000Z | dlls/ntdll/file.c | roytam1/wine-win31look | 2c8284c53a46c1309fbf62a3998538c44fcbf207 | [
"MIT"
] | null | null | null | dlls/ntdll/file.c | roytam1/wine-win31look | 2c8284c53a46c1309fbf62a3998538c44fcbf207 | [
"MIT"
] | null | null | null | /*
* Copyright 1999, 2000 Juergen Schmied
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "config.h"
#include "wine/port.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <assert.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef HAVE_SYS_ERRNO_H
#include <sys/errno.h>
#endif
#define NONAMELESSUNION
#define NONAMELESSSTRUCT
#include "wine/unicode.h"
#include "wine/debug.h"
#include "wine/server.h"
#include "async.h"
#include "ntdll_misc.h"
#include "winternl.h"
#include "winioctl.h"
WINE_DEFAULT_DEBUG_CHANNEL(ntdll);
/**************************************************************************
* NtOpenFile [NTDLL.@]
* ZwOpenFile [NTDLL.@]
*
* Open a file.
*
* PARAMS
* FileHandle [O] Variable that receives the file handle on return
* DesiredAccess [I] Access desired by the caller to the file
* ObjectAttributes [I] Structue describing the file to be opened
* IoStatusBlock [O] Receives details about the result of the operation
* ShareAccess [I] Type of shared access the caller requires
* OpenOptions [I] Options for the file open
*
* RETURNS
* Success: 0. FileHandle and IoStatusBlock are updated.
* Failure: An NTSTATUS error code describing the error.
*/
NTSTATUS WINAPI NtOpenFile(
OUT PHANDLE FileHandle,
ACCESS_MASK DesiredAccess,
POBJECT_ATTRIBUTES ObjectAttributes,
OUT PIO_STATUS_BLOCK IoStatusBlock,
ULONG ShareAccess,
ULONG OpenOptions)
{
LPWSTR filename;
static const WCHAR szDosDevices[] = {'\\','D','o','s','D','e','v','i','c','e','s','\\',0};
FIXME("(%p,0x%08lx,%p,%p,0x%08lx,0x%08lx) partial stub\n",
FileHandle, DesiredAccess, ObjectAttributes,
IoStatusBlock, ShareAccess, OpenOptions);
dump_ObjectAttributes (ObjectAttributes);
if(ObjectAttributes->RootDirectory)
{
FIXME("Object root directory unknown %p\n",
ObjectAttributes->RootDirectory);
return STATUS_OBJECT_NAME_NOT_FOUND;
}
filename = ObjectAttributes->ObjectName->Buffer;
/* FIXME: DOSFS stuff should call here, not vice-versa */
if(strncmpW(filename, szDosDevices, strlenW(szDosDevices)))
return STATUS_OBJECT_NAME_NOT_FOUND;
/* FIXME: this calls SetLastError() -> bad */
*FileHandle = pCreateFileW( &filename[strlenW(szDosDevices)], DesiredAccess, ShareAccess,
NULL, OPEN_EXISTING, 0, 0 );
if (*FileHandle == INVALID_HANDLE_VALUE) return STATUS_OBJECT_NAME_NOT_FOUND;
return STATUS_SUCCESS;
}
/**************************************************************************
* NtCreateFile [NTDLL.@]
* ZwCreateFile [NTDLL.@]
*
* Either create a new file or directory, or open an existing file, device,
* directory or volume.
*
* PARAMS
* FileHandle [O] Points to a variable which receives the file handle on return
* DesiredAccess [I] Desired access to the file
* ObjectAttributes [I] Structure describing the file
* IoStatusBlock [O] Receives information about the operation on return
* AllocationSize [I] Initial size of the file in bytes
* FileAttributes [I] Attributes to create the file with
* ShareAccess [I] Type of shared access the caller would like to the file
* CreateDisposition [I] Specifies what to do, depending on whether the file already exists
* CreateOptions [I] Options for creating a new file
* EaBuffer [I] Undocumented
* EaLength [I] Undocumented
*
* RETURNS
* Success: 0. FileHandle and IoStatusBlock are updated.
* Failure: An NTSTATUS error code describing the error.
*/
NTSTATUS WINAPI NtCreateFile(
OUT PHANDLE FileHandle,
ACCESS_MASK DesiredAccess,
POBJECT_ATTRIBUTES ObjectAttributes,
OUT PIO_STATUS_BLOCK IoStatusBlock,
PLARGE_INTEGER AllocateSize,
ULONG FileAttributes,
ULONG ShareAccess,
ULONG CreateDisposition,
ULONG CreateOptions,
PVOID EaBuffer,
ULONG EaLength)
{
FIXME("(%p,0x%08lx,%p,%p,%p,0x%08lx,0x%08lx,0x%08lx,0x%08lx,%p,0x%08lx) stub\n",
FileHandle,DesiredAccess,ObjectAttributes,
IoStatusBlock,AllocateSize,FileAttributes,
ShareAccess,CreateDisposition,CreateOptions,EaBuffer,EaLength);
dump_ObjectAttributes (ObjectAttributes);
return 0;
}
/***********************************************************************
* Asynchronous file I/O *
*/
static DWORD fileio_get_async_count(const async_private *ovp);
static void CALLBACK fileio_call_completion_func(ULONG_PTR data);
static void fileio_async_cleanup(async_private *ovp);
static async_ops fileio_async_ops =
{
fileio_get_async_count, /* get_count */
fileio_call_completion_func, /* call_completion */
fileio_async_cleanup /* cleanup */
};
static async_ops fileio_nocomp_async_ops =
{
fileio_get_async_count, /* get_count */
NULL, /* call_completion */
fileio_async_cleanup /* cleanup */
};
typedef struct async_fileio
{
struct async_private async;
PIO_APC_ROUTINE apc;
void* apc_user;
char *buffer;
unsigned int count;
unsigned long offset;
enum fd_type fd_type;
} async_fileio;
static DWORD fileio_get_async_count(const struct async_private *ovp)
{
async_fileio *fileio = (async_fileio*) ovp;
if (fileio->count < fileio->async.iosb->Information)
return 0;
return fileio->count - fileio->async.iosb->Information;
}
static void CALLBACK fileio_call_completion_func(ULONG_PTR data)
{
async_fileio *ovp = (async_fileio*) data;
TRACE("data: %p\n", ovp);
ovp->apc( ovp->apc_user, ovp->async.iosb, ovp->async.iosb->Information );
fileio_async_cleanup( &ovp->async );
}
static void fileio_async_cleanup( struct async_private *ovp )
{
RtlFreeHeap( GetProcessHeap(), 0, ovp );
}
/***********************************************************************
* FILE_GetNtStatus(void)
*
* Retrieve the Nt Status code from errno.
* Try to be consistent with FILE_SetDosError().
*/
NTSTATUS FILE_GetNtStatus(void)
{
int err = errno;
DWORD nt;
TRACE( "errno = %d\n", errno );
switch (err)
{
case EAGAIN: nt = STATUS_SHARING_VIOLATION; break;
case EBADF: nt = STATUS_INVALID_HANDLE; break;
case ENOSPC: nt = STATUS_DISK_FULL; break;
case EPERM:
case EROFS:
case EACCES: nt = STATUS_ACCESS_DENIED; break;
case ENOENT: nt = STATUS_SHARING_VIOLATION; break;
case EISDIR: nt = STATUS_FILE_IS_A_DIRECTORY; break;
case EMFILE:
case ENFILE: nt = STATUS_NO_MORE_FILES; break;
case EINVAL:
case ENOTEMPTY: nt = STATUS_DIRECTORY_NOT_EMPTY; break;
case EPIPE: nt = STATUS_PIPE_BROKEN; break;
case EIO: nt = STATUS_DEVICE_NOT_READY; break;
case ENOEXEC: /* ?? */
case ESPIPE: /* ?? */
case EEXIST: /* ?? */
default:
FIXME( "Converting errno %d to STATUS_UNSUCCESSFUL\n", err );
nt = STATUS_UNSUCCESSFUL;
}
return nt;
}
/***********************************************************************
* FILE_AsyncReadService (INTERNAL)
*
* This function is called while the client is waiting on the
* server, so we can't make any server calls here.
*/
static void FILE_AsyncReadService(async_private *ovp)
{
async_fileio *fileio = (async_fileio*) ovp;
IO_STATUS_BLOCK* io_status = fileio->async.iosb;
int result;
int already = io_status->Information;
TRACE("%p %p\n", io_status, fileio->buffer );
/* check to see if the data is ready (non-blocking) */
if ( fileio->fd_type == FD_TYPE_SOCKET )
result = read(ovp->fd, &fileio->buffer[already], fileio->count - already);
else
{
result = pread(ovp->fd, &fileio->buffer[already], fileio->count - already,
fileio->offset + already);
if ((result < 0) && (errno == ESPIPE))
result = read(ovp->fd, &fileio->buffer[already], fileio->count - already);
}
if ((result < 0) && ((errno == EAGAIN) || (errno == EINTR)))
{
TRACE("Deferred read %d\n",errno);
io_status->u.Status = STATUS_PENDING;
return;
}
/* check to see if the transfer is complete */
if (result < 0)
{
io_status->u.Status = FILE_GetNtStatus();
return;
}
else if (result == 0)
{
io_status->u.Status = io_status->Information ? STATUS_SUCCESS : STATUS_END_OF_FILE;
return;
}
io_status->Information += result;
if (io_status->Information >= fileio->count || fileio->fd_type == FD_TYPE_SOCKET )
io_status->u.Status = STATUS_SUCCESS;
else
io_status->u.Status = STATUS_PENDING;
TRACE("read %d more bytes %ld/%d so far\n",
result, io_status->Information, fileio->count);
}
/******************************************************************************
* NtReadFile [NTDLL.@]
* ZwReadFile [NTDLL.@]
*
* Read from an open file handle.
*
* PARAMS
* FileHandle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
* Event [I] Event to signal upon completion (or NULL)
* ApcRoutine [I] Callback to call upon completion (or NULL)
* ApcContext [I] Context for ApcRoutine (or NULL)
* IoStatusBlock [O] Receives information about the operation on return
* Buffer [O] Destination for the data read
* Length [I] Size of Buffer
* ByteOffset [O] Destination for the new file pointer position (or NULL)
* Key [O] Function unknown (may be NULL)
*
* RETURNS
* Success: 0. IoStatusBlock is updated, and the Information member contains
* The number of bytes read.
* Failure: An NTSTATUS error code describing the error.
*/
NTSTATUS WINAPI NtReadFile(HANDLE hFile, HANDLE hEvent,
PIO_APC_ROUTINE apc, void* apc_user,
PIO_STATUS_BLOCK io_status, void* buffer, ULONG length,
PLARGE_INTEGER offset, PULONG key)
{
int unix_handle, flags;
enum fd_type type;
TRACE("(%p,%p,%p,%p,%p,%p,0x%08lx,%p,%p),partial stub!\n",
hFile,hEvent,apc,apc_user,io_status,buffer,length,offset,key);
io_status->Information = 0;
io_status->u.Status = wine_server_handle_to_fd( hFile, GENERIC_READ, &unix_handle, &type, &flags );
if (io_status->u.Status) return io_status->u.Status;
if (flags & FD_FLAG_RECV_SHUTDOWN)
{
wine_server_release_fd( hFile, unix_handle );
return STATUS_PIPE_DISCONNECTED;
}
if (flags & FD_FLAG_TIMEOUT)
{
if (hEvent)
{
/* this shouldn't happen, but check it */
FIXME("NIY-hEvent\n");
wine_server_release_fd( hFile, unix_handle );
return STATUS_NOT_IMPLEMENTED;
}
io_status->u.Status = NtCreateEvent(&hEvent, SYNCHRONIZE, NULL, 0, 0);
if (io_status->u.Status)
{
wine_server_release_fd( hFile, unix_handle );
return io_status->u.Status;
}
}
if (flags & (FD_FLAG_OVERLAPPED|FD_FLAG_TIMEOUT))
{
async_fileio* ovp;
NTSTATUS ret;
if (!(ovp = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(async_fileio))))
{
wine_server_release_fd( hFile, unix_handle );
return STATUS_NO_MEMORY;
}
ovp->async.ops = (apc ? &fileio_async_ops : &fileio_nocomp_async_ops );
ovp->async.handle = hFile;
ovp->async.fd = unix_handle; /* FIXME */
ovp->async.type = ASYNC_TYPE_READ;
ovp->async.func = FILE_AsyncReadService;
ovp->async.event = hEvent;
ovp->async.iosb = io_status;
ovp->count = length;
if ( offset == NULL )
ovp->offset = 0;
else
{
ovp->offset = offset->u.LowPart;
if (offset->u.HighPart) FIXME("NIY-high part\n");
}
ovp->apc = apc;
ovp->apc_user = apc_user;
ovp->buffer = buffer;
ovp->fd_type = type;
io_status->Information = 0;
ret = register_new_async(&ovp->async);
if (ret != STATUS_SUCCESS)
return ret;
if (flags & FD_FLAG_TIMEOUT)
{
NtWaitForSingleObject(hEvent, TRUE, NULL);
NtClose(hEvent);
}
else
{
LARGE_INTEGER timeout;
/* let some APC be run, this will read some already pending data */
timeout.u.LowPart = timeout.u.HighPart = 0;
NtDelayExecution( TRUE, &timeout );
}
return io_status->u.Status;
}
switch (type)
{
case FD_TYPE_SMB:
FIXME("NIY-SMB\n");
/* FIXME */
/* return SMB_ReadFile(hFile, unix_handle, buffer, length, io_status); */
wine_server_release_fd( hFile, unix_handle );
return STATUS_INVALID_HANDLE;
case FD_TYPE_DEFAULT:
/* normal unix file */
break;
default:
FIXME("Unsupported type of fd %d\n", type);
wine_server_release_fd( hFile, unix_handle );
return STATUS_INVALID_HANDLE;
}
if (offset)
{
FILE_POSITION_INFORMATION fpi;
fpi.CurrentByteOffset = *offset;
io_status->u.Status = NtSetInformationFile(hFile, io_status, &fpi, sizeof(fpi),
FilePositionInformation);
if (io_status->u.Status)
{
wine_server_release_fd( hFile, unix_handle );
return io_status->u.Status;
}
}
/* code for synchronous reads */
while ((io_status->Information = read( unix_handle, buffer, length )) == -1)
{
if ((errno == EAGAIN) || (errno == EINTR)) continue;
if (errno == EFAULT) FIXME( "EFAULT handling broken for now\n" );
io_status->u.Status = FILE_GetNtStatus();
break;
}
wine_server_release_fd( hFile, unix_handle );
return io_status->u.Status;
}
/***********************************************************************
* FILE_AsyncWriteService (INTERNAL)
*
* This function is called while the client is waiting on the
* server, so we can't make any server calls here.
*/
static void FILE_AsyncWriteService(struct async_private *ovp)
{
async_fileio *fileio = (async_fileio *) ovp;
PIO_STATUS_BLOCK io_status = fileio->async.iosb;
int result;
int already = io_status->Information;
TRACE("(%p %p)\n",io_status,fileio->buffer);
/* write some data (non-blocking) */
if ( fileio->fd_type == FD_TYPE_SOCKET )
result = write(ovp->fd, &fileio->buffer[already], fileio->count - already);
else
{
result = pwrite(ovp->fd, &fileio->buffer[already], fileio->count - already,
fileio->offset + already);
if ((result < 0) && (errno == ESPIPE))
result = write(ovp->fd, &fileio->buffer[already], fileio->count - already);
}
if ((result < 0) && ((errno == EAGAIN) || (errno == EINTR)))
{
io_status->u.Status = STATUS_PENDING;
return;
}
/* check to see if the transfer is complete */
if (result < 0)
{
io_status->u.Status = FILE_GetNtStatus();
return;
}
io_status->Information += result;
io_status->u.Status = (io_status->Information < fileio->count) ? STATUS_PENDING : STATUS_SUCCESS;
TRACE("wrote %d more bytes %ld/%d so far\n",result,io_status->Information,fileio->count);
}
/******************************************************************************
* NtWriteFile [NTDLL.@]
* ZwWriteFile [NTDLL.@]
*
* Write to an open file handle.
*
* PARAMS
* FileHandle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
* Event [I] Event to signal upon completion (or NULL)
* ApcRoutine [I] Callback to call upon completion (or NULL)
* ApcContext [I] Context for ApcRoutine (or NULL)
* IoStatusBlock [O] Receives information about the operation on return
* Buffer [I] Source for the data to write
* Length [I] Size of Buffer
* ByteOffset [O] Destination for the new file pointer position (or NULL)
* Key [O] Function unknown (may be NULL)
*
* RETURNS
* Success: 0. IoStatusBlock is updated, and the Information member contains
* The number of bytes written.
* Failure: An NTSTATUS error code describing the error.
*/
NTSTATUS WINAPI NtWriteFile(HANDLE hFile, HANDLE hEvent,
PIO_APC_ROUTINE apc, void* apc_user,
PIO_STATUS_BLOCK io_status,
const void* buffer, ULONG length,
PLARGE_INTEGER offset, PULONG key)
{
int unix_handle, flags;
enum fd_type type;
TRACE("(%p,%p,%p,%p,%p,%p,0x%08lx,%p,%p)!\n",
hFile,hEvent,apc,apc_user,io_status,buffer,length,offset,key);
TRACE("(%p,%p,%p,%p,%p,%p,0x%08lx,%p,%p),partial stub!\n",
hFile,hEvent,apc,apc_user,io_status,buffer,length,offset,key);
io_status->Information = 0;
io_status->u.Status = wine_server_handle_to_fd( hFile, GENERIC_WRITE, &unix_handle, &type, &flags );
if (io_status->u.Status) return io_status->u.Status;
if (flags & FD_FLAG_SEND_SHUTDOWN)
{
wine_server_release_fd( hFile, unix_handle );
return STATUS_PIPE_DISCONNECTED;
}
if (flags & (FD_FLAG_OVERLAPPED|FD_FLAG_TIMEOUT))
{
async_fileio* ovp;
NTSTATUS ret;
if (!(ovp = RtlAllocateHeap(GetProcessHeap(), 0, sizeof(async_fileio))))
{
wine_server_release_fd( hFile, unix_handle );
return STATUS_NO_MEMORY;
}
ovp->async.ops = (apc ? &fileio_async_ops : &fileio_nocomp_async_ops );
ovp->async.handle = hFile;
ovp->async.fd = unix_handle; /* FIXME */
ovp->async.type = ASYNC_TYPE_WRITE;
ovp->async.func = FILE_AsyncWriteService;
ovp->async.event = hEvent;
ovp->async.iosb = io_status;
ovp->count = length;
if (offset) {
ovp->offset = offset->u.LowPart;
if (offset->u.HighPart) FIXME("NIY-high part\n");
} else {
ovp->offset = 0;
}
ovp->apc = apc;
ovp->apc_user = apc_user;
ovp->buffer = (void*)buffer;
ovp->fd_type = type;
io_status->Information = 0;
ret = register_new_async(&ovp->async);
if (ret != STATUS_SUCCESS)
return ret;
if (flags & FD_FLAG_TIMEOUT)
{
NtWaitForSingleObject(hEvent, TRUE, NULL);
NtClose(hEvent);
}
else
{
LARGE_INTEGER timeout;
/* let some APC be run, this will write as much data as possible */
timeout.u.LowPart = timeout.u.HighPart = 0;
NtDelayExecution( TRUE, &timeout );
}
return io_status->u.Status;
}
switch (type)
{
case FD_TYPE_SMB:
FIXME("NIY-SMB\n");
wine_server_release_fd( hFile, unix_handle );
return STATUS_NOT_IMPLEMENTED;
case FD_TYPE_DEFAULT:
/* normal unix files */
if (unix_handle == -1) return STATUS_INVALID_HANDLE;
break;
default:
FIXME("Unsupported type of fd %d\n", type);
wine_server_release_fd( hFile, unix_handle );
return STATUS_INVALID_HANDLE;
}
if (offset)
{
FILE_POSITION_INFORMATION fpi;
fpi.CurrentByteOffset = *offset;
io_status->u.Status = NtSetInformationFile(hFile, io_status, &fpi, sizeof(fpi),
FilePositionInformation);
if (io_status->u.Status)
{
wine_server_release_fd( hFile, unix_handle );
return io_status->u.Status;
}
}
/* synchronous file write */
while ((io_status->Information = write( unix_handle, buffer, length )) == -1)
{
if ((errno == EAGAIN) || (errno == EINTR)) continue;
if (errno == EFAULT) FIXME( "EFAULT handling broken for now\n" );
if (errno == ENOSPC) io_status->u.Status = STATUS_DISK_FULL;
else io_status->u.Status = FILE_GetNtStatus();
break;
}
wine_server_release_fd( hFile, unix_handle );
return io_status->u.Status;
}
/**************************************************************************
* NtDeviceIoControlFile [NTDLL.@]
* ZwDeviceIoControlFile [NTDLL.@]
*
* Perform an I/O control operation on an open file handle.
*
* PARAMS
* DeviceHandle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
* Event [I] Event to signal upon completion (or NULL)
* ApcRoutine [I] Callback to call upon completion (or NULL)
* ApcContext [I] Context for ApcRoutine (or NULL)
* IoStatusBlock [O] Receives information about the operation on return
* IoControlCode [I] Control code for the operation to perform
* InputBuffer [I] Source for any input data required (or NULL)
* InputBufferSize [I] Size of InputBuffer
* OutputBuffer [O] Source for any output data returned (or NULL)
* OutputBufferSize [I] Size of OutputBuffer
*
* RETURNS
* Success: 0. IoStatusBlock is updated.
* Failure: An NTSTATUS error code describing the error.
*/
NTSTATUS WINAPI NtDeviceIoControlFile(HANDLE DeviceHandle, HANDLE hEvent,
PIO_APC_ROUTINE UserApcRoutine,
PVOID UserApcContext,
PIO_STATUS_BLOCK IoStatusBlock,
ULONG IoControlCode,
PVOID InputBuffer,
ULONG InputBufferSize,
PVOID OutputBuffer,
ULONG OutputBufferSize)
{
TRACE("(%p,%p,%p,%p,%p,0x%08lx,%p,0x%08lx,%p,0x%08lx)\n",
DeviceHandle, hEvent, UserApcRoutine, UserApcContext,
IoStatusBlock, IoControlCode,
InputBuffer, InputBufferSize, OutputBuffer, OutputBufferSize);
if (CDROM_DeviceIoControl(DeviceHandle, hEvent,
UserApcRoutine, UserApcContext,
IoStatusBlock, IoControlCode,
InputBuffer, InputBufferSize,
OutputBuffer, OutputBufferSize) == STATUS_NO_SUCH_DEVICE)
{
/* it wasn't a CDROM */
FIXME("Unimplemented dwIoControlCode=%08lx\n", IoControlCode);
IoStatusBlock->u.Status = STATUS_NOT_IMPLEMENTED;
IoStatusBlock->Information = 0;
if (hEvent) NtSetEvent(hEvent, NULL);
}
return IoStatusBlock->u.Status;
}
/******************************************************************************
* NtFsControlFile [NTDLL.@]
* ZwFsControlFile [NTDLL.@]
*/
NTSTATUS WINAPI NtFsControlFile(
IN HANDLE DeviceHandle,
IN HANDLE Event OPTIONAL,
IN PIO_APC_ROUTINE ApcRoutine OPTIONAL,
IN PVOID ApcContext OPTIONAL,
OUT PIO_STATUS_BLOCK IoStatusBlock,
IN ULONG IoControlCode,
IN PVOID InputBuffer,
IN ULONG InputBufferSize,
OUT PVOID OutputBuffer,
IN ULONG OutputBufferSize)
{
FIXME("(%p,%p,%p,%p,%p,0x%08lx,%p,0x%08lx,%p,0x%08lx): stub\n",
DeviceHandle,Event,ApcRoutine,ApcContext,IoStatusBlock,IoControlCode,
InputBuffer,InputBufferSize,OutputBuffer,OutputBufferSize);
return 0;
}
/******************************************************************************
* NtSetVolumeInformationFile [NTDLL.@]
* ZwSetVolumeInformationFile [NTDLL.@]
*
* Set volume information for an open file handle.
*
* PARAMS
* FileHandle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
* IoStatusBlock [O] Receives information about the operation on return
* FsInformation [I] Source for volume information
* Length [I] Size of FsInformation
* FsInformationClass [I] Type of volume information to set
*
* RETURNS
* Success: 0. IoStatusBlock is updated.
* Failure: An NTSTATUS error code describing the error.
*/
NTSTATUS WINAPI NtSetVolumeInformationFile(
IN HANDLE FileHandle,
PIO_STATUS_BLOCK IoStatusBlock,
PVOID FsInformation,
ULONG Length,
FS_INFORMATION_CLASS FsInformationClass)
{
FIXME("(%p,%p,%p,0x%08lx,0x%08x) stub\n",
FileHandle,IoStatusBlock,FsInformation,Length,FsInformationClass);
return 0;
}
/******************************************************************************
* NtQueryInformationFile [NTDLL.@]
* ZwQueryInformationFile [NTDLL.@]
*
* Get information about an open file handle.
*
* PARAMS
* FileHandle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
* IoStatusBlock [O] Receives information about the operation on return
* FileInformation [O] Destination for file information
* Length [I] Size of FileInformation
* FileInformationClass [I] Type of file information to get
*
* RETURNS
* Success: 0. IoStatusBlock and FileInformation are updated.
* Failure: An NTSTATUS error code describing the error.
*/
NTSTATUS WINAPI NtQueryInformationFile(HANDLE hFile, PIO_STATUS_BLOCK io_status,
PVOID ptr, LONG len,
FILE_INFORMATION_CLASS class)
{
NTSTATUS status;
LONG used = 0;
BYTE answer[256];
time_t ct = 0, wt = 0, at = 0;
TRACE("(%p,%p,%p,0x%08lx,0x%08x)\n", hFile, io_status, ptr, len, class);
switch (class)
{
case FileBasicInformation:
{
FILE_BASIC_INFORMATION* fbi = (FILE_BASIC_INFORMATION*)answer;
if (sizeof(answer) < sizeof(*fbi)) goto too_small;
SERVER_START_REQ( get_file_info )
{
req->handle = hFile;
if (!(status = wine_server_call( req )))
{
/* FIXME: which file types are supported ?
* Serial ports (FILE_TYPE_CHAR) are not,
* and MSDN also says that pipes are not supported.
* FILE_TYPE_REMOTE seems to be supported according to
* MSDN q234741.txt */
if ((reply->type == FILE_TYPE_DISK) ||
(reply->type == FILE_TYPE_REMOTE))
{
at = reply->access_time;
wt = reply->write_time;
ct = reply->change_time;
fbi->FileAttributes = reply->attr;
used = sizeof(*fbi);
}
else status = STATUS_INVALID_HANDLE; /* FIXME ??? */
}
}
SERVER_END_REQ;
if (used)
{
RtlSecondsSince1970ToTime(wt, &fbi->CreationTime);
RtlSecondsSince1970ToTime(wt, &fbi->LastWriteTime);
RtlSecondsSince1970ToTime(ct, &fbi->ChangeTime);
RtlSecondsSince1970ToTime(at, &fbi->LastAccessTime);
}
}
break;
case FileStandardInformation:
{
FILE_STANDARD_INFORMATION* fsi = (FILE_STANDARD_INFORMATION*)answer;
if (sizeof(answer) < sizeof(*fsi)) goto too_small;
SERVER_START_REQ( get_file_info )
{
req->handle = hFile;
if (!(status = wine_server_call( req )))
{
/* FIXME: which file types are supported ?
* Serial ports (FILE_TYPE_CHAR) are not,
* and MSDN also says that pipes are not supported.
* FILE_TYPE_REMOTE seems to be supported according to
* MSDN q234741.txt */
if ((reply->type == FILE_TYPE_DISK) ||
(reply->type == FILE_TYPE_REMOTE))
{
fsi->AllocationSize.u.HighPart = reply->alloc_high;
fsi->AllocationSize.u.LowPart = reply->alloc_low;
fsi->EndOfFile.u.HighPart = reply->size_high;
fsi->EndOfFile.u.LowPart = reply->size_low;
fsi->NumberOfLinks = reply->links;
fsi->DeletePending = FALSE; /* FIXME */
fsi->Directory = (reply->attr & FILE_ATTRIBUTE_DIRECTORY);
used = sizeof(*fsi);
}
else status = STATUS_INVALID_HANDLE; /* FIXME ??? */
}
}
SERVER_END_REQ;
}
break;
case FilePositionInformation:
{
FILE_POSITION_INFORMATION* fpi = (FILE_POSITION_INFORMATION*)answer;
if (sizeof(answer) < sizeof(*fpi)) goto too_small;
SERVER_START_REQ( set_file_pointer )
{
req->handle = hFile;
req->low = 0;
req->high = 0;
req->whence = SEEK_CUR;
if (!(status = wine_server_call( req )))
{
fpi->CurrentByteOffset.u.HighPart = reply->new_high;
fpi->CurrentByteOffset.u.LowPart = reply->new_low;
used = sizeof(*fpi);
}
}
SERVER_END_REQ;
}
break;
default:
FIXME("Unsupported class (%d)\n", class);
return io_status->u.Status = STATUS_NOT_IMPLEMENTED;
}
if (used) memcpy(ptr, answer, min(used, len));
io_status->u.Status = status;
io_status->Information = len;
return status;
too_small:
io_status->Information = 0;
return io_status->u.Status = STATUS_BUFFER_TOO_SMALL;
}
/******************************************************************************
* NtSetInformationFile [NTDLL.@]
* ZwSetInformationFile [NTDLL.@]
*
* Set information about an open file handle.
*
* PARAMS
* FileHandle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
* IoStatusBlock [O] Receives information about the operation on return
* FileInformation [I] Source for file information
* Length [I] Size of FileInformation
* FileInformationClass [I] Type of file information to set
*
* RETURNS
* Success: 0. IoStatusBlock is updated.
* Failure: An NTSTATUS error code describing the error.
*/
NTSTATUS WINAPI NtSetInformationFile(HANDLE hFile, PIO_STATUS_BLOCK io_status,
PVOID ptr, ULONG len,
FILE_INFORMATION_CLASS class)
{
NTSTATUS status = STATUS_INVALID_PARAMETER_3;
TRACE("(%p,%p,%p,0x%08lx,0x%08x)\n", hFile, io_status, ptr, len, class);
switch (class)
{
case FilePositionInformation:
if (len >= sizeof(FILE_POSITION_INFORMATION))
{
FILE_POSITION_INFORMATION* fpi = (FILE_POSITION_INFORMATION*)ptr;
SERVER_START_REQ( set_file_pointer )
{
req->handle = hFile;
req->low = fpi->CurrentByteOffset.u.LowPart;
req->high = fpi->CurrentByteOffset.u.HighPart;
req->whence = SEEK_SET;
status = wine_server_call( req );
}
SERVER_END_REQ;
status = STATUS_SUCCESS;
}
break;
default:
FIXME("Unsupported class (%d)\n", class);
return STATUS_NOT_IMPLEMENTED;
}
io_status->u.Status = status;
io_status->Information = 0;
return status;
}
/******************************************************************************
* NtQueryVolumeInformationFile [NTDLL.@]
* ZwQueryVolumeInformationFile [NTDLL.@]
*
* Get volume information for an open file handle.
*
* PARAMS
* FileHandle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
* IoStatusBlock [O] Receives information about the operation on return
* FsInformation [O] Destination for volume information
* Length [I] Size of FsInformation
* FsInformationClass [I] Type of volume information to set
*
* RETURNS
* Success: 0. IoStatusBlock and FsInformation are updated.
* Failure: An NTSTATUS error code describing the error.
*/
NTSTATUS WINAPI NtQueryVolumeInformationFile (
IN HANDLE FileHandle,
OUT PIO_STATUS_BLOCK IoStatusBlock,
OUT PVOID FSInformation,
IN ULONG Length,
IN FS_INFORMATION_CLASS FSInformationClass)
{
ULONG len = 0;
FIXME("(%p %p %p 0x%08lx 0x%08x) stub!\n",
FileHandle, IoStatusBlock, FSInformation, Length, FSInformationClass);
switch ( FSInformationClass )
{
case FileFsVolumeInformation:
len = sizeof( FILE_FS_VOLUME_INFORMATION );
break;
case FileFsLabelInformation:
len = 0;
break;
case FileFsSizeInformation:
len = sizeof( FILE_FS_SIZE_INFORMATION );
break;
case FileFsDeviceInformation:
len = sizeof( FILE_FS_DEVICE_INFORMATION );
break;
case FileFsAttributeInformation:
len = sizeof( FILE_FS_ATTRIBUTE_INFORMATION );
break;
case FileFsControlInformation:
len = 0;
break;
case FileFsFullSizeInformation:
len = 0;
break;
case FileFsObjectIdInformation:
len = 0;
break;
case FileFsMaximumInformation:
len = 0;
break;
}
if (Length < len)
return STATUS_BUFFER_TOO_SMALL;
switch ( FSInformationClass )
{
case FileFsVolumeInformation:
break;
case FileFsLabelInformation:
break;
case FileFsSizeInformation:
break;
case FileFsDeviceInformation:
if (FSInformation)
{
FILE_FS_DEVICE_INFORMATION * DeviceInfo = FSInformation;
DeviceInfo->DeviceType = FILE_DEVICE_DISK;
DeviceInfo->Characteristics = 0;
break;
};
case FileFsAttributeInformation:
break;
case FileFsControlInformation:
break;
case FileFsFullSizeInformation:
break;
case FileFsObjectIdInformation:
break;
case FileFsMaximumInformation:
break;
}
IoStatusBlock->u.Status = STATUS_SUCCESS;
IoStatusBlock->Information = len;
return STATUS_SUCCESS;
}
/******************************************************************
* NtFlushBuffersFile (NTDLL.@)
*
* Flush any buffered data on an open file handle.
*
* PARAMS
* FileHandle [I] Handle returned from ZwOpenFile() or ZwCreateFile()
* IoStatusBlock [O] Receives information about the operation on return
*
* RETURNS
* Success: 0. IoStatusBlock is updated.
* Failure: An NTSTATUS error code describing the error.
*/
NTSTATUS WINAPI NtFlushBuffersFile( HANDLE hFile, IO_STATUS_BLOCK* IoStatusBlock )
{
NTSTATUS ret;
HANDLE hEvent = NULL;
SERVER_START_REQ( flush_file )
{
req->handle = hFile;
ret = wine_server_call( req );
hEvent = reply->event;
}
SERVER_END_REQ;
if (!ret && hEvent)
{
ret = NtWaitForSingleObject( hEvent, FALSE, NULL );
NtClose( hEvent );
}
return ret;
}
/******************************************************************
* NtLockFile (NTDLL.@)
*
*
*/
NTSTATUS WINAPI NtLockFile( HANDLE hFile, HANDLE lock_granted_event,
PIO_APC_ROUTINE apc, void* apc_user,
PIO_STATUS_BLOCK io_status, PLARGE_INTEGER offset,
PLARGE_INTEGER count, ULONG* key, BOOLEAN dont_wait,
BOOLEAN exclusive )
{
NTSTATUS ret;
HANDLE handle;
BOOLEAN async;
if (apc || io_status || key)
{
FIXME("Unimplemented yet parameter\n");
return STATUS_NOT_IMPLEMENTED;
}
for (;;)
{
SERVER_START_REQ( lock_file )
{
req->handle = hFile;
req->offset_low = offset->u.LowPart;
req->offset_high = offset->u.HighPart;
req->count_low = count->u.LowPart;
req->count_high = count->u.HighPart;
req->shared = !exclusive;
req->wait = !dont_wait;
ret = wine_server_call( req );
handle = reply->handle;
async = reply->overlapped;
}
SERVER_END_REQ;
if (ret != STATUS_PENDING)
{
if (!ret && lock_granted_event) NtSetEvent(lock_granted_event, NULL);
return ret;
}
if (async)
{
FIXME( "Async I/O lock wait not implemented, might deadlock\n" );
if (handle) NtClose( handle );
return STATUS_PENDING;
}
if (handle)
{
NtWaitForSingleObject( handle, FALSE, NULL );
NtClose( handle );
}
else
{
LARGE_INTEGER time;
/* Unix lock conflict, sleep a bit and retry */
time.QuadPart = 100 * (ULONGLONG)10000;
time.QuadPart = -time.QuadPart;
NtDelayExecution( FALSE, &time );
}
}
}
/******************************************************************
* NtUnlockFile (NTDLL.@)
*
*
*/
NTSTATUS WINAPI NtUnlockFile( HANDLE hFile, PIO_STATUS_BLOCK io_status,
PLARGE_INTEGER offset, PLARGE_INTEGER count,
PULONG key )
{
NTSTATUS status;
TRACE( "%p %lx%08lx %lx%08lx\n",
hFile, offset->u.HighPart, offset->u.LowPart, count->u.HighPart, count->u.LowPart );
if (io_status || key)
{
FIXME("Unimplemented yet parameter\n");
return STATUS_NOT_IMPLEMENTED;
}
SERVER_START_REQ( unlock_file )
{
req->handle = hFile;
req->offset_low = offset->u.LowPart;
req->offset_high = offset->u.HighPart;
req->count_low = count->u.LowPart;
req->count_high = count->u.HighPart;
status = wine_server_call( req );
}
SERVER_END_REQ;
return status;
}
| 33.377682 | 104 | 0.583927 | [
"object"
] |
60d90063b336d50cf5ea27576c4cfad8b5609d54 | 3,697 | h | C | uuv_gazebo_plugins/uuv_gazebo_ros_plugins/include/uuv_gazebo_ros_plugins/FinROSPlugin.h | oKermorgant/Plankton | ce21579792122b05d27f147ab66f515001ccb733 | [
"Apache-2.0",
"BSD-3-Clause"
] | 79 | 2020-09-30T22:19:07.000Z | 2022-03-27T12:30:58.000Z | uuv_gazebo_plugins/uuv_gazebo_ros_plugins/include/uuv_gazebo_ros_plugins/FinROSPlugin.h | oKermorgant/Plankton | ce21579792122b05d27f147ab66f515001ccb733 | [
"Apache-2.0",
"BSD-3-Clause"
] | 17 | 2020-10-05T01:01:49.000Z | 2022-03-04T13:58:53.000Z | uuv_gazebo_plugins/uuv_gazebo_ros_plugins/include/uuv_gazebo_ros_plugins/FinROSPlugin.h | oKermorgant/Plankton | ce21579792122b05d27f147ab66f515001ccb733 | [
"Apache-2.0",
"BSD-3-Clause"
] | 22 | 2020-10-27T14:42:48.000Z | 2022-03-25T10:41:51.000Z | // Copyright (c) 2020 The Plankton Authors.
// All rights reserved.
//
// This source code is derived from UUV Simulator
// (https://github.com/uuvsimulator/uuv_simulator)
// Copyright (c) 2016-2019 The UUV Simulator Authors
// licensed under the Apache license, Version 2.0
// cf. 3rd-party-licenses.txt file in the root directory of this source tree.
//
// 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 __FIN_ROS_PLUGIN_HH__
#define __FIN_ROS_PLUGIN_HH__
#include <uuv_gazebo_plugins/FinPlugin.h>
#include <uuv_gazebo_ros_plugins_msgs/msg/float_stamped.hpp>
#include <uuv_gazebo_ros_plugins_msgs/srv/get_list_param.hpp>
#include <gazebo/common/Plugin.hh>
#include <gazebo_ros/node.hpp>
#include <rclcpp/rclcpp.hpp>
#include <geometry_msgs/msg/wrench_stamped.hpp>
#include <map>
#include <memory>
namespace uuv_simulator_ros
{
class FinROSPlugin : public gazebo::FinPlugin
{
using GetListParam = uuv_gazebo_ros_plugins_msgs::srv::GetListParam;
using FloatStamped = uuv_gazebo_ros_plugins_msgs::msg::FloatStamped;
/// \brief Constrcutor.
public: FinROSPlugin();
/// \brief Destructor.
public: ~FinROSPlugin();
/// \brief Load module and read parameters from SDF.
public: void Load(gazebo::physics::ModelPtr _parent, sdf::ElementPtr _sdf);
/// \brief Publish state via ROS.
public: void RosPublishStates();
/// \brief Set new set point.
public: void SetReference(
const uuv_gazebo_ros_plugins_msgs::msg::FloatStamped::SharedPtr _msg);
/// \brief Return the list of paramaters of the lift and drag model
public: void GetLiftDragParams(
const GetListParam::Request::SharedPtr _req,
GetListParam::Response::SharedPtr _res);
/// \brief Return the ROS publish period.
public: gazebo::common::Time GetRosPublishPeriod();
/// \brief Set the ROS publish frequency (Hz).
public: void SetRosPublishRate(double _hz);
/// \brief Initialize Module.
public: virtual void Init();
/// \brief Reset Module.
public: virtual void Reset();
/// \brief Pointer to this ROS node's handle.
protected: gazebo_ros::Node::SharedPtr myRosNode;
/// \brief Subscriber reacting to new reference set points.
private: rclcpp::Subscription<uuv_gazebo_ros_plugins_msgs::msg::FloatStamped>::SharedPtr mySubReference;
/// \brief Publisher for current state.
private: rclcpp::Publisher<uuv_gazebo_ros_plugins_msgs::msg::FloatStamped>::SharedPtr myPubState;
/// \brief Publisher for current actual thrust.
private: rclcpp::Publisher<geometry_msgs::msg::WrenchStamped>::SharedPtr myPubFinForce;
/// \brief Connection for callbacks on update world.
private: gazebo::event::ConnectionPtr rosPublishConnection;
/// \brief Period after which we should publish a message via ROS.
private: gazebo::common::Time rosPublishPeriod;
/// \brief Map of services
private: std::map<std::string,
rclcpp::Service<uuv_gazebo_ros_plugins_msgs::srv::GetListParam>::SharedPtr> myServicesById;
/// \brief Last time we published a message via ROS.
private: gazebo::common::Time lastRosPublishTime;
};
}
#endif
| 34.551402 | 113 | 0.727076 | [
"model"
] |
60e8c45460b494362099f4ce21300ab13925db03 | 4,352 | h | C | Code/Framework/AzToolsFramework/Tests/Prefab/SpawnableRemoveEditorInfoTestFixture.h | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-09-13T00:01:12.000Z | 2021-09-13T00:01:12.000Z | Code/Framework/AzToolsFramework/Tests/Prefab/SpawnableRemoveEditorInfoTestFixture.h | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | null | null | null | Code/Framework/AzToolsFramework/Tests/Prefab/SpawnableRemoveEditorInfoTestFixture.h | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-20T11:07:25.000Z | 2021-07-20T11:07:25.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 <AzCore/Component/Entity.h>
#include <AzToolsFramework/ToolsComponents/EditorComponentBase.h>
#include <AzToolsFramework/UnitTest/AzToolsFrameworkTestHelpers.h>
#include <Prefab/Spawnable/EditorInfoRemover.h>
#include <Prefab/Spawnable/PrefabProcessorContext.h>
#include <Prefab/PrefabSystemComponent.h>
#include <Prefab/PrefabDomTypes.h>
namespace UnitTest
{
using namespace AzToolsFramework::Prefab;
class TestExportRuntimeComponentWithCallback
: public AZ::Component
{
public:
AZ_COMPONENT(TestExportRuntimeComponentWithCallback, "{BD30EBBB-74DA-473C-9C68-7077AAE8C0B1}", AZ::Component);
TestExportRuntimeComponentWithCallback() = default;
TestExportRuntimeComponentWithCallback(bool returnPointerToSelf, bool exportHandled);
void Activate() override {}
void Deactivate() override {}
static void Reflect(AZ::ReflectContext* context);
AZ::ExportedComponent ExportComponent(AZ::Component* thisComponent, const AZ::PlatformTagSet& /*platformTags*/);
const bool m_exportHandled{ false };
const bool m_returnPointerToSelf{ false };
};
class TestExportRuntimeComponentWithoutCallback
: public AZ::Component
{
public:
AZ_COMPONENT(TestExportRuntimeComponentWithoutCallback, "{44216269-2BAB-48E4-864F-F8D4CCFF60BB}", AZ::Component);
void Activate() override {}
void Deactivate() override {}
static void Reflect(AZ::ReflectContext* context);
};
class TestExportEditorComponent
: public AzToolsFramework::Components::EditorComponentBase
{
public:
AZ_COMPONENT(TestExportEditorComponent, "{60EE7F0E-1C89-433A-AA7C-20F64BA1F470}", AzToolsFramework::Components::EditorComponentBase);
enum class ExportComponentType
{
ExportEditorComponent,
ExportRuntimeComponentWithCallBack,
ExportRuntimeComponentWithoutCallBack,
ExportNullComponent,
};
TestExportEditorComponent() = default;
TestExportEditorComponent(ExportComponentType exportType, bool exportHandled);
void Activate() override {}
void Deactivate() override {}
static void Reflect(AZ::ReflectContext* context);
AZ::ExportedComponent ExportComponent(AZ::Component* thisComponent, const AZ::PlatformTagSet& /*platformTags*/);
void BuildGameEntity(AZ::Entity* gameEntity) override;
ExportComponentType m_exportType{ ExportComponentType::ExportNullComponent };
bool m_exportHandled{ false };
};
class SpawnableRemoveEditorInfoTestFixture
: public ToolsApplicationFixture
{
protected:
void SetUpEditorFixtureImpl() override;
void TearDownEditorFixtureImpl() override;
// create entity containing the EditorOnly component to be processed
void CreateSourceEntity(const char* name, bool editorOnly);
// create entity containing the non editor-only component to be processed
void CreateSourceTestExportRuntimeEntity(const char* name, bool returnPointerToSelf, bool exportHandled);
// create entity containing the editor-only component to be processed
void CreateSourceTestExportEditorEntity(
const char* name,
TestExportEditorComponent::ExportComponentType exportType,
bool exportHandled);
// Locate and return an entity from the exported entities
AZ::Entity* GetRuntimeEntity(const char* entityName);
void ConvertSourceEntitiesToPrefab();
void ConvertRuntimePrefab(bool expectedResult = true);
AZStd::vector<AZ::Entity*> m_sourceEntities;
AZStd::vector<AZ::Entity*> m_runtimeEntities;
AZ::SerializeContext* m_serializeContext{ nullptr };
PrefabSystemComponent* m_prefabSystemComponent{ nullptr };
PrefabConversionUtils::EditorInfoRemover m_editorInfoRemover;
PrefabConversionUtils::PrefabProcessorContext m_prefabProcessorContext{ AZ::Uuid::CreateRandom() };
PrefabDom m_prefabDom;
};
}
| 36.571429 | 158 | 0.716912 | [
"vector",
"3d"
] |
60f07dfad970740fec77225e461963f34d4132ca | 22,685 | c | C | grdemo.c | mooseman/pdutils | 824cef963c7f64d0f93acf62409962b56dad9436 | [
"Unlicense"
] | 7 | 2015-10-20T05:42:53.000Z | 2021-11-19T13:13:05.000Z | grdemo.c | mooseman/pdutils | 824cef963c7f64d0f93acf62409962b56dad9436 | [
"Unlicense"
] | null | null | null | grdemo.c | mooseman/pdutils | 824cef963c7f64d0f93acf62409962b56dad9436 | [
"Unlicense"
] | null | null | null |
/*****************************************************************************
VGA graphics demo
Chris Giese <geezer@execpc.com> http://my.execpc.com/~geezer
Release date: ?
This code is public domain (no copyright).
You can do whatever you want with it.
This code uses the BIOS to set graphics mode, and uses the BIOS font.
Should compile cleanly with Turbo C++ 1.0, Turbo C++ 3.0, 16- or 32-bit
Watcom C, or DJGPP. DJGPP version will not work in Windows NT/2000/XP
DOS box.
Some additional things you could do with this:
- Write a function tblit1(), similar to blit1(), that uses an on-off
transparency mask. Use this function to blit non-rectangular objects
such as a mouse cursor.
- Write blit_plane(): a fast function to blit from monochrome to monochrome
or 4-plane bitmaps. Use an external shift() function, written in asm
- Support VBE 1.x banked framebuffer
- Support VBE 2.x linear framebuffer (pmode only, not at A000h:0000)
- Support greater color depths: 15 bpp, 16 bpp, 24 bpp, 32 bpp
- Color reduction, e.g. Heckbert (median-cut) algorithm
- Clipping engine that lets you draw a window that is partially
obscured by "closer" windows
- Mouse, keyboard, and timer events
- Widgets: push button, checkbox, radio buttons, listbox, dialog, etc.
*****************************************************************************/
#include <string.h> /* [_f]memset() */
/********************************* TURBO C **********************************/
#if defined(__TURBOC__)
#include <dos.h> /* struct REGPACK, intr() */
/* The framebuffer is far outside the 16-bit data segment. The only way to
make the framebuffer work like in-memory bitmaps is to use far pointers.
We still use the SMALL memory model. */
#define FAR far
#define FARPTR(S, O) MK_FP(S, O)
#define outportw(P,V) outport(P,V)
#define R_AX r_ax
#define R_BX r_bx
#define R_BP r_bp
#define R_ES r_es
#define trap(N,R) intr(N,R)
typedef struct REGPACK regs_t;
#if __TURBOC__<0x300
void vmemset(unsigned char FAR *s, unsigned c, unsigned n)
{
for(; n != 0; n--)
{
*s = c;
s++;
}
}
#else
void vmemset(unsigned char FAR *s, unsigned c, unsigned n)
{
_fmemset(s, c, n);
}
#endif
/********************************* DJGPP ************************************/
#elif defined(__DJGPP__)
#include <dpmi.h> /* __dpmi_... */
#include <dos.h> /* inportb(), outportb() */
#define FAR /* nothing */
#define FARPTR(S, O) (unsigned char *)((S) * 16L + (O) + \
__djgpp_conventional_base)
/* near pointers; not supported in Windows NT/2k/XP DOS box */
#include <sys/nearptr.h> /* __djgpp_conventional_base, __djgpp_nearptr_enable() */
#include <stdio.h> /* printf() */
#include <crt0.h> /* _CRT0_FLAG_NEARPTR, _crt0_startup_flags */
#define R_AX x.ax
#define R_BX x.bx
#define R_BP x.bp
#define R_ES x.es
#define trap(N,R) __dpmi_int(N,R)
typedef __dpmi_regs regs_t;
void vmemset(unsigned char FAR *s, unsigned c, unsigned n)
{
memset(s, c, n);
}
/******************************** WATCOM C **********************************/
#elif defined(__WATCOMC__)
#include <dos.h> /* union REGPACK, MK_FP(), intr() */
#if defined(__386__)
#define FAR /* nothing */
#define FARPTR(S, O) (unsigned char *)((S) * 16L + (O))
void vmemset(unsigned char FAR *s, unsigned c, unsigned n)
{
memset(s, c, n);
}
#else
#define FAR far
#define FARPTR(S, O) MK_FP(S, O)
void vmemset(unsigned char FAR *s, unsigned c, unsigned n)
{
_fmemset(s, c, n);
}
#endif
#define inportb(P) inp(P)
#define outportb(P,V) outp(P,V)
#define outportw(P,V) outpw(P,V)
#define R_AX w.ax
#define R_BX w.bx
#define R_BP w.bp
#define R_ES w.es
/* WARNING: for 32-bit code, unused fields of regs_t
must be zeroed before using this macro */
#define trap(N,R) intr(N,R)
typedef union REGPACK regs_t;
#else
#error Not Turbo C, not DJGPP, not Watcom C. Sorry.
#endif
#include <conio.h> /* getch() */
/* need direct access to some VGA registers to select plane,
enable Mode X, and fix screwy CGA addressing */
#define VGA_SEQ_INDEX 0x3C4
#define VGA_SEQ_DATA 0x3C5
#define VGA_GC_INDEX 0x3CE
#define VGA_GC_DATA 0x3CF
#define VGA_CRTC_INDEX 0x3D4
#define VGA_CRTC_DATA 0x3D5
/* bitmap "class" */
typedef struct
{
unsigned wd, ht;
unsigned char FAR *raster;
unsigned fore_color, back_color;
/* "member functions" */
const struct _driver *ops;
} bmp_t;
typedef struct _driver
{
/* "pure virtual functions": color drivers MUST implement these */
void (*write_pixel)(bmp_t *bmp, unsigned x, unsigned y, unsigned c);
unsigned (*read_pixel)(bmp_t *bmp, unsigned x, unsigned y);
/* "virtual functions": drivers MAY implement these, for speed
fill rectangular area with solid color */
void (*fill_rect)(bmp_t *bmp, int x, int y, int wd, int ht);
/* copy monochrome bitmap to this bitmap (used to display text) */
void (*blit1)(bmp_t *src, bmp_t *dst, unsigned dst_x, unsigned dst_y);
/* copy all or part of one bitmap to another (both of the same depth) */
void (*blit)(bmp_t *src, bmp_t *dst, unsigned dst_x, unsigned dst_y);
} ops_t;
/*============================================================================
helper functions
============================================================================*/
/*****************************************************************************
*****************************************************************************/
void set_plane(unsigned p)
{
static unsigned curr_p = -1u;
/**/
unsigned char pmask;
p &= 3;
if(p == curr_p)
return;
curr_p = p;
pmask = 1 << p;
#if 0
outportb(VGA_GC_INDEX, 4);
outportb(VGA_GC_DATA, p);
outportb(VGA_SEQ_INDEX, 2);
outportb(VGA_SEQ_DATA, pmask);
#else
/* this is a little faster... */
outportw(VGA_GC_INDEX, (p << 8) | 4);
outportw(VGA_SEQ_INDEX, (pmask << 8) | 2);
#endif
}
/*****************************************************************************
fast planar (monochrome or 16-color) rectangle fill
*****************************************************************************/
void fill_plane(bmp_t *bmp, int x, int y, int wd, int ht, unsigned c)
{
unsigned w, wd_in_bytes, off;
unsigned char lmask, rmask;
int x2, y2;
x2 = x + wd - 1;
w = (x2 >> 3) - (x >> 3) + 1;
lmask = 0x00FF >> (x & 7); /* FF 7F 3F 1F 0F 07 03 01 */
rmask = 0xFF80 >> (x2 & 7);/* 80 C0 E0 F0 F8 FC FE FF */
if(w == 1)
lmask &= rmask;
wd_in_bytes = bmp->wd / 8;
off = wd_in_bytes * y + x / 8;
if(c)
/* for each row... */
for(y2 = y; y2 < y + ht; y2++)
{
/* do partial byte on left */
bmp->raster[off] |= lmask;
/* do solid bytes in middle */
if(w > 2)
vmemset(bmp->raster + off + 1, 0xFF, w - 2);
/* do partial byte on right */
if(w > 1)
bmp->raster[off + w - 1] |= rmask;
/* next row */
off += wd_in_bytes;
}
else
{
lmask = ~lmask;
rmask = ~rmask;
for(y2 = y; y2 < y + ht; y2++)
{
bmp->raster[off] &= lmask;
if(w > 2)
vmemset(bmp->raster + off + 1, 0, w - 2);
if(w > 1)
bmp->raster[off + w - 1] &= rmask;
off += wd_in_bytes;
}
}
}
/*****************************************************************************
fast planar blit
*****************************************************************************/
void blit_plane(bmp_t *src, bmp_t *dst, unsigned dst_x, unsigned dst_y)
{
/* left as an exercise for the reader :)
You may need an external, assembly-language function to shift (left or
right) a long string of bytes. No need to shift by more than 7 bits. */
}
/*============================================================================
driver for monochrome (1-bit) graphics
============================================================================*/
/*****************************************************************************
*****************************************************************************/
static void write_pixel1(bmp_t *bmp, unsigned x, unsigned y, unsigned c)
{
unsigned wd_in_bytes;
unsigned off, mask;
c = (c & 1) * 0xFF;
wd_in_bytes = bmp->wd / 8;
off = wd_in_bytes * y + x / 8;
x = (x & 7) * 1;
mask = 0x80 >> x;
bmp->raster[off] = (bmp->raster[off] & ~mask) | (c & mask);
}
/*****************************************************************************
*****************************************************************************/
static unsigned read_pixel1(bmp_t *bmp, unsigned x, unsigned y)
{
unsigned wd_in_bytes;
unsigned off, mask;
wd_in_bytes = bmp->wd / 8;
off = wd_in_bytes * y + x / 8;
x = (x & 7) * 1;
mask = 0x80 >> x;
return (bmp->raster[off] & mask) != 0;
}
/*****************************************************************************
*****************************************************************************/
static void fill_rect1(bmp_t *bmp, int x, int y, int wd, int ht)
{
fill_plane(bmp, x, y, wd, ht, bmp->fore_color & 1);
}
/*****************************************************************************
*****************************************************************************/
const ops_t g_ops1 =
{
write_pixel1,
read_pixel1,
fill_rect1,
NULL, /* blit1 */
NULL /* blit */
};
/*============================================================================
driver for 2-bit packed pixel (4-color CGA) graphics
============================================================================*/
/*****************************************************************************
*****************************************************************************/
static void write_pixel2(bmp_t *bmp, unsigned x, unsigned y, unsigned c)
{
unsigned wd_in_bytes, off, mask;
c = (c & 3) * 0x55;
wd_in_bytes = bmp->wd / 4;
off = wd_in_bytes * y + x / 4;
x = (x & 3) * 2;
mask = 0xC0 >> x;
bmp->raster[off] = (bmp->raster[off] & ~mask) | (c & mask);
}
/*****************************************************************************
*****************************************************************************/
const ops_t g_ops2 =
{
write_pixel2,
NULL, /* read_pixel */
NULL, /* fill_rect */
NULL, /* blit1 */
NULL /* blit */
};
/*============================================================================
driver for 4-plane 16-color graphics
============================================================================*/
/*****************************************************************************
*****************************************************************************/
static void write_pixel4p(bmp_t *bmp, unsigned x, unsigned y, unsigned c)
{
unsigned wd_in_bytes, off, mask, p, pmask;
wd_in_bytes = bmp->wd / 8;
off = wd_in_bytes * y + x / 8;
x = (x & 7) * 1;
mask = 0x80 >> x;
pmask = 1;
for(p = 0; p < 4; p++)
{
set_plane(p);
if(pmask & c)
bmp->raster[off] |= mask;
else
bmp->raster[off] &= ~mask;
pmask <<= 1;
}
}
/*****************************************************************************
pixel-by-pixel fill is too slow, so use this optimized function:
*****************************************************************************/
static void fill_rect4p(bmp_t *bmp, int x, int y, int wd, int ht)
{
unsigned char p, pmask;
pmask = 1;
for(p = 0; p < 4; p++)
{
set_plane(p);
fill_plane(bmp, x, y, wd, ht, bmp->fore_color & pmask);
pmask <<= 1;
}
}
/*****************************************************************************
*****************************************************************************/
const ops_t g_ops4p =
{
write_pixel4p,
NULL, /* read_pixel */
fill_rect4p,
NULL, /* blit1 */
NULL /* blit */
};
/*============================================================================
driver for 8-bit 256-color graphics
============================================================================*/
/*****************************************************************************
*****************************************************************************/
static void write_pixel8(bmp_t *bmp, unsigned x, unsigned y, unsigned c)
{
unsigned wd_in_bytes;
unsigned off;
wd_in_bytes = bmp->wd;
off = wd_in_bytes * y + x;
bmp->raster[off] = c;
}
/*****************************************************************************
*****************************************************************************/
static void fill_rect8(bmp_t *bmp, int x, int y, int wd, int ht)
{
unsigned wd_in_bytes, off, y2;
wd_in_bytes = bmp->wd;
off = wd_in_bytes * y + x;
for(y2 = y; y2 < y + ht; y2++)
{
vmemset(bmp->raster + off, bmp->fore_color, wd);
off += wd_in_bytes;
}
}
/*****************************************************************************
*****************************************************************************/
const ops_t g_ops8 =
{
write_pixel8,
NULL, /* read_pixel */
fill_rect8,
NULL, /* blit1 */
NULL /* blit */
};
/*============================================================================
driver for 8-bit 256-color Mode-X graphics
============================================================================*/
/*****************************************************************************
*****************************************************************************/
static void write_pixel8x(bmp_t *bmp, unsigned x, unsigned y, unsigned c)
{
unsigned wd_in_bytes;
unsigned off;
wd_in_bytes = bmp->wd / 4;
off = wd_in_bytes * y + x / 4;
set_plane(x & 3);
bmp->raster[off] = c;
}
/*****************************************************************************
*****************************************************************************/
const ops_t g_ops8x =
{
write_pixel8x,
NULL, /* read_pixel */
NULL, /* fill_rect */
NULL, /* blit1 */
NULL /* blit */
};
/*============================================================================
depth-independent routines, which call the depth-dependent routines
============================================================================*/
/*****************************************************************************
*****************************************************************************/
unsigned read_pixel(bmp_t *bmp, unsigned x, unsigned y)
{
if(x >= bmp->wd || y >= bmp->ht)
return 0;
if(bmp->ops->read_pixel == NULL)
return 0; /* uh-oh */
return bmp->ops->read_pixel(bmp, x, y);
}
/*****************************************************************************
*****************************************************************************/
void write_pixel(bmp_t *bmp, unsigned x, unsigned y, unsigned c)
{
if(x >= bmp->wd || y >= bmp->ht)
return;
if(bmp->ops->write_pixel == NULL)
return; /* uh-oh */
bmp->ops->write_pixel(bmp, x, y, c);
}
/*****************************************************************************
*****************************************************************************/
void fill_rect(bmp_t *bmp, int x, int y, int wd, int ht)
{
int x2, y2;
/* clip */
if(x < 0)
{
if(wd + x < 0)
return;
wd += x;
x = 0;
}
if(x + wd >= (int)bmp->wd)
{
if(x >= (int)bmp->wd)
return;
wd = bmp->wd - x;
}
if(y < 0)
{
if(ht + y < 0)
return;
ht += y;
y = 0;
}
if(y + ht >= (int)bmp->ht)
{
if(y >= (int)bmp->ht)
return;
ht = bmp->ht - y;
}
/* use fast routine if available */
if(bmp->ops->fill_rect != NULL)
{
bmp->ops->fill_rect(bmp, x, y, wd, ht);
return;
}
for(y2 = y; y2 < y + ht; y2++)
for(x2 = x; x2 < x + wd; x2++)
write_pixel(bmp, x2, y2, bmp->fore_color);
}
/*****************************************************************************
*****************************************************************************/
void hline(bmp_t *bmp, int x, int y, unsigned wd)
{
fill_rect(bmp, x, y, wd, 1);
}
/*****************************************************************************
*****************************************************************************/
void vline(bmp_t *bmp, int x, int y, unsigned ht)
{
fill_rect(bmp, x, y, 1, ht);
}
/*****************************************************************************
blit1 = blit from monochrome bitmap to bitmap of any color depth
*****************************************************************************/
void blit1(bmp_t *src, bmp_t *dst, unsigned dst_x, unsigned dst_y)
{
unsigned x, y, c;
/* source bitmap _must_ be monochrome */
if(src->ops != &g_ops1)
return;
/* use fast routine if available */
if(src->ops->blit1 != NULL)
{
src->ops->blit1(src, dst, dst_x, dst_y);
return;
}
for(y = 0; y < src->ht; y++)
for(x = 0; x < src->wd; x++)
{
c = read_pixel(src, x, y);
/* xxx - on-off transparency?
if(c == 0)
continue; */
if(c != 0)
c = dst->fore_color;
else
c = dst->back_color;
write_pixel(dst, dst_x + x, dst_y + y, c);
}
}
/*****************************************************************************
blit = copy from one bitmap to another, both of the same color depth
*****************************************************************************/
void blit(bmp_t *src, bmp_t *dst, unsigned dst_x, unsigned dst_y)
{
unsigned x, y, c;
/* they must be the same depth */
if(src->ops != dst->ops)
return;
/* use fast routine if available */
if(src->ops->blit != NULL)
{
src->ops->blit(src, dst, dst_x, dst_y);
return;
}
for(y = 0; y < src->ht; y++)
for(x = 0; x < src->wd; x++)
{
c = read_pixel(src, x, y);
write_pixel(dst, dst_x + x, dst_y + y, c);
}
}
/*****************************************************************************
find 8x8 font in VGA BIOS ROM
*****************************************************************************/
unsigned char FAR *bios_8x8_font(void)
{
unsigned char FAR *font;
regs_t regs;
/* use BIOS INT 10h AX=1130h to find font #3 (8x8) in ROM */
memset(®s, 0, sizeof(regs)); /* for Watcom C */
regs.R_AX = 0x1130;
regs.R_BX = 0x0300;
trap(0x10, ®s);
/* CauseWay DOS extender seems to return a selector in ES,
instead of real-mode segment value (usu. 0xC000) */
#if defined(__WATCOMC__)&&defined(__386__)
font = FARPTR(0xC000, regs.R_BP);
#else
font = FARPTR(regs.R_ES, regs.R_BP);
#endif
return font;
}
/*****************************************************************************
*****************************************************************************/
void bputs(bmp_t *bmp, unsigned x, unsigned y, const char *s)
{
unsigned char FAR *font;
bmp_t src;
font = bios_8x8_font();
src.wd = 8;
src.ht = 8;
src.ops = &g_ops1;
for(; *s != '\0'; s++)
{
src.raster = font + 8 * (*s);
blit1(&src, bmp, x, y);
x += 8;
}
}
/*============================================================================
DEMO
============================================================================*/
/*****************************************************************************
*****************************************************************************/
static void border3d(bmp_t *bmp, int x, int y, unsigned wd, unsigned ht,
char down)
{
if(down)
{
bmp->fore_color = 8;
hline(bmp, x + 0, y + 0, wd - 1);
vline(bmp, x + 0, y + 0, ht - 1);
bmp->fore_color = 0;
hline(bmp, x + 1, y + 1, wd - 3);
vline(bmp, x + 1, y + 1, ht - 3);
bmp->fore_color = 7;
hline(bmp, x + 1, y + ht - 2, wd - 2);
vline(bmp, x + wd - 2, y + 1, ht - 2);
bmp->fore_color = 15;
hline(bmp, x + 0, y + ht - 1, wd);
vline(bmp, x + wd - 1, y + 0, ht);
}
else
{
bmp->fore_color = 7;
hline(bmp, x + 0, y + 0, wd - 1);
vline(bmp, x + 0, y + 0, ht - 1);
bmp->fore_color = 15;
hline(bmp, x + 1, y + 1, wd - 3);
vline(bmp, x + 1, y + 1, ht - 3);
bmp->fore_color = 8;
hline(bmp, x + 1, y + ht - 2, wd - 2);
vline(bmp, x + wd - 2, y + 1, ht - 2);
bmp->fore_color = 0;
hline(bmp, x + 0, y + ht - 1, wd);
vline(bmp, x + wd - 1, y + 0, ht);
}
}
/*****************************************************************************
*****************************************************************************/
static void demo(bmp_t *bmp, const char *title)
{
unsigned x = 10, y = 10, wd = 180, ht = 50;
/* erase screen to blue */
bmp->fore_color = 1;
fill_rect(bmp, 0, 0, bmp->wd, bmp->ht);
/* draw gray window with 3D border */
bmp->fore_color = 7;
fill_rect(bmp, x, y, wd, ht);
border3d(bmp, x, y, wd, ht, 0);
/* draw white-on-green title bar */
bmp->fore_color = 2;
fill_rect(bmp, x + 2, y + 2, wd - 4, 10);
bmp->back_color = 2;
bmp->fore_color = 15;
bputs(bmp, x + 3, y + 3, title);
/* draw menu bar on existing gray background */
bmp->back_color = 7;
bmp->fore_color = 0;
bputs(bmp, x + 3, y + 13, "File Edit");
/* draw white inner area with 3D border */
bmp->fore_color = 15;
fill_rect(bmp, x + 3, y + 21, wd - 6, ht - 24);
border3d(bmp, x + 3, y + 21, wd - 6, ht - 24, 1);
/* await key pressed */
getch();
}
/*****************************************************************************
*****************************************************************************/
int main(void)
{
static const unsigned wd[] =
{
640, 320, 640, 320, 320
};
static const unsigned ht[] =
{
480, 200, 480, 200, 200
};
static const ops_t *ops[] =
{
&g_ops1, &g_ops2, &g_ops4p, &g_ops8, &g_ops8x
};
static const unsigned mode[] =
{
0x11, 5, 0x12, 0x13, 0x13
};
static const char *title[] =
{
"640x480x2", "320x200x4", "640x480x16", "320x200x256",
"320x200x256 ModeX"
};
/**/
regs_t regs;
unsigned i;
bmp_t bmp;
#if defined(__DJGPP__)
if(!(_crt0_startup_flags & _CRT0_FLAG_NEARPTR))
{
if(!__djgpp_nearptr_enable())
{
printf("Could not enable nearptr access "
"(Windows NT/2000/XP?)\n");
}
}
#endif
for(i = 0; i < sizeof(wd) / sizeof(wd[0]); i++)
{
bmp.raster = FARPTR(0xA000, 0);
bmp.wd = wd[i];
bmp.ht = ht[i];
bmp.ops = ops[i];
memset(®s, 0, sizeof(regs)); /* for Watcom C */
regs.R_AX = mode[i];
trap(0x10, ®s);
/* to make CGA graphics work like other graphics modes... */
if(mode[i] == 0x05)
{
/* 1) turn off screwy CGA addressing */
outportb(VGA_CRTC_INDEX, 0x17);
outportb(VGA_CRTC_DATA, inportb(VGA_CRTC_DATA) | 1);
/* 2) turn off doublescan */
outportb(VGA_CRTC_INDEX, 9);
outportb(VGA_CRTC_DATA, inportb(VGA_CRTC_DATA) & ~0x80);
/* 3) move the framebuffer from B800:0000 to A000:0000 */
outportb(VGA_GC_INDEX, 6);
outportb(VGA_GC_DATA, inportb(VGA_GC_INDEX) & ~0x0C);
}
/* to convert mode 13h to Mode X... */
else if(i == 4)
{
/* 1) turn off Chain-4 addressing */
outportb(VGA_SEQ_INDEX, 0x04);
outportb(VGA_SEQ_DATA, inportb(VGA_SEQ_DATA) & ~0x08);
/* 2) turn off doubleword clocking */
outportb(VGA_CRTC_INDEX, 0x14);
outportb(VGA_CRTC_DATA, inportb(VGA_CRTC_DATA) & ~0x40);
/* 3) turn off word clocking in case it's on */
outportb(VGA_CRTC_INDEX, 0x17);
outportb(VGA_CRTC_DATA, inportb(VGA_CRTC_DATA) | 0x40);
}
demo(&bmp, title[i]);
}
/* return to text mode */
memset(®s, 0, sizeof(regs)); /* for Watcom C */
regs.R_AX = 0x03;
trap(0x10, ®s);
return 0;
}
| 29.576271 | 82 | 0.458673 | [
"model",
"3d",
"solid"
] |
60f47265dead8673b3c8bfba01b469f220c35feb | 2,600 | h | C | contrib/mcutils/include/MCUtils/Clustering.h | aaronvincent/gambit_aaron | a38bd6fc10d781e71f2adafd401c76e1e3476b05 | [
"Unlicense"
] | 2 | 2020-09-08T20:05:27.000Z | 2021-04-26T07:57:56.000Z | contrib/mcutils/include/MCUtils/Clustering.h | aaronvincent/gambit_aaron | a38bd6fc10d781e71f2adafd401c76e1e3476b05 | [
"Unlicense"
] | 9 | 2020-10-19T09:56:17.000Z | 2021-05-28T06:12:03.000Z | contrib/mcutils/include/MCUtils/Clustering.h | aaronvincent/gambit_aaron | a38bd6fc10d781e71f2adafd401c76e1e3476b05 | [
"Unlicense"
] | 5 | 2020-09-08T02:23:34.000Z | 2021-03-23T08:48:04.000Z | // -*- C++ -*-
//
// This file is part of MCUtils -- https://bitbucket.org/andybuckley/mcutils
// Copyright (C) 2013-2016 Andy Buckley <andy.buckley@cern.ch>
//
// Embedding of MCUtils code in other projects is permitted provided this
// notice is retained and the MCUtils namespace and include path are changed.
//
#pragma once
#if __cplusplus <= 199711L
#error "This library needs at least a C++11 compliant compiler: are you using -std=c++11?"
#endif
/// @file FastJet clustering on HepMC events
/// @author Andy Buckley <andy.buckley@cern.ch>
#include "HEPUtils/FastJet.h"
#include "MCUtils/HepMCEventUtils.h"
namespace MCUtils {
/// @name Converters between HepMC and FastJet momentum types
//@{
/// Convert a HepMC FourVector to a FastJet PseudoJet
inline fastjet::PseudoJet mk_pseudojet(const HepMC::FourVector& p4) {
return fastjet::PseudoJet(p4.px(), p4.py(), p4.pz(), p4.e());
}
/// Convert a HepMC GenParticle to a FastJet PseudoJet
inline fastjet::PseudoJet mk_pseudojet(const HepMC::GenParticle* gp) {
fastjet::PseudoJet pj = mk_pseudojet(gp->momentum());
//pj.set_user_info(new HepMCInfo(p));
return pj;
}
/// Convert a vector of HepMC GenParticles to a vector of FastJet PseudoJets
inline std::vector<fastjet::PseudoJet> mk_pseudojets(const GenParticlesC& gps) {
std::vector<fastjet::PseudoJet> pjs;
for (const HepMC::GenParticle* gp : gps) {
pjs.push_back( mk_pseudojet(gp) );
}
return pjs;
}
//@}
/// @name Jet builders from HepMC input types
//@{
/// Construct pT-sorted jets using the @a alg measure with jet @a R parameter, and min pT @a ptmin (in MeV)
inline std::vector<fastjet::PseudoJet> get_jets(const GenParticlesC& particles, double R, double ptmin,
fastjet::JetAlgorithm alg=fastjet::antikt_algorithm) {
/// @todo Convert to use filter_jet_inputs
return HEPUtils::get_jets(mk_pseudojets(filter_stable(particles)), R, ptmin, alg);
}
/// Construct pT-sorted jets using the @a alg measure with jet @a R parameter, and min pT @a ptmin (in MeV)
inline std::vector<fastjet::PseudoJet> get_jets(const HepMC::GenEvent* evt, double R, double ptmin,
fastjet::JetAlgorithm alg=fastjet::antikt_algorithm) {
/// @todo Convert to use get_jet_inputs
return HEPUtils::get_jets(mk_pseudojets(get_stable(evt)), R, ptmin, alg);
}
//@}
/// @todo Make safe photon clustering for charged leptons
/// @todo Make tau, B, top and W/Z finders (both safe and direct versions)
}
| 33.333333 | 109 | 0.679231 | [
"vector"
] |
60f65c25192dc6f319b95b44c0762b8ea4b1fe72 | 1,639 | h | C | source/reserve.h | dos-games/vanilla-shadow_warrior | bf781c586c7e9cda0cfb0b3bc56983f535cb75c4 | [
"Unlicense"
] | 18 | 2015-07-21T03:53:29.000Z | 2021-12-20T18:42:56.000Z | source/reserve.h | Azarien/shadow-warrior | bf781c586c7e9cda0cfb0b3bc56983f535cb75c4 | [
"Unlicense"
] | null | null | null | source/reserve.h | Azarien/shadow-warrior | bf781c586c7e9cda0cfb0b3bc56983f535cb75c4 | [
"Unlicense"
] | 6 | 2016-10-17T09:06:22.000Z | 2022-02-11T10:02:17.000Z | //-------------------------------------------------------------------------
/*
Copyright (C) 1997, 2005 - 3D Realms Entertainment
This file is part of Shadow Warrior version 1.2
Shadow Warrior is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
Original Source: 1997 - Frank Maddin and Jim Norwood
Prepared for public release: 03/28/2005 - Charlie Wiederhold, 3D Realms
*/
//-------------------------------------------------------------------------
#ifndef RESERVE_H
#define RESERVE_H
// This header is used for reserving tile space for programatic purposes
// MAXTILES is currently at 6144 in size - anything under this is ok
#define MAXMIRRORS 8
// This is just some, high, blank tile number not used
// by real graphics to put the MAXMIRRORS mirrors in
#define MIRRORLABEL 6000
#define TILT_TILE 6016
// save screen and tilt tile stuff
#define SAVE_SCREEN_TILE 6017
#define SAVE_SCREEN_XSIZE 160L
#define SAVE_SCREEN_YSIZE 100L
#endif
| 35.630435 | 76 | 0.674802 | [
"3d"
] |
60f8390542051a9953f3b73450db990c3823a6aa | 34,450 | h | C | src/elements/basis/TACSElementBasis.h | tchin-divergent/tacs | 34743b370da4ab6ea16d24de7c574c3fec9d333a | [
"Apache-2.0"
] | null | null | null | src/elements/basis/TACSElementBasis.h | tchin-divergent/tacs | 34743b370da4ab6ea16d24de7c574c3fec9d333a | [
"Apache-2.0"
] | null | null | null | src/elements/basis/TACSElementBasis.h | tchin-divergent/tacs | 34743b370da4ab6ea16d24de7c574c3fec9d333a | [
"Apache-2.0"
] | null | null | null | /*
This file is part of TACS: The Toolkit for the Analysis of Composite
Structures, a parallel finite-element code for structural and
multidisciplinary design optimization.
Copyright (C) 2014 Georgia Tech Research Corporation
TACS is licensed under the Apache License, Version 2.0 (the
"License"); you may not use this software except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
*/
#ifndef TACS_ELEMENT_BASIS_H
#define TACS_ELEMENT_BASIS_H
#include "TACSObject.h"
#include "TACSElementTypes.h"
/*
This virtual base class defines the interface for the basis functions
and quadrature schemes used in most TACS elements.
These are designed to provide common quadrature, interpolation, and
transformation computations needed for finite element computations.
This is also designed to capture
*/
class TACSElementBasis : public TACSObject {
public:
/**
Get the layout type
@return The element layout type
*/
virtual ElementLayout getLayoutType();
/**
Get the parametric point visualization point
Note that the number of visualization points must be consistent with
the number of points defined by the call to TacsGetNumVisNodes()
with the corresponding element layout type.
@param n Index for the parametric point for visualization
@param pt Parametric point location within the element
*/
virtual void getVisPoint( int n, double pt[] );
/**
Get the number of basis functions
*/
virtual int getNumNodes() = 0;
/**
Get the spatial dimension of parameter input space = 1, 2, or 3
*/
virtual int getNumParameters() = 0;
/**
Get the number of quadrature points for the volume/area of the element
*/
virtual int getNumQuadraturePoints() = 0;
/**
Get the quadrature weight for the n-th quadrature point
@param n The quadrature point index
@return The quadrature weight value
*/
virtual double getQuadratureWeight( int n ) = 0;
/**
Get the parametric location of the n-th quadrature point
@param n The quadrature point index
@param pt The parametric location of the quadrature point
@return The quadrature weight value
*/
virtual double getQuadraturePoint( int n, double pt[] ) = 0;
/**
Get the number of faces or edges for the element
@return The number of faces/edges for the basis
*/
virtual int getNumElementFaces() = 0;
/**
Get the number of quadrature points for the given face
@param face The face/edge index
@return The number of quadrature points for the face
*/
virtual int getNumFaceQuadraturePoints( int face ) = 0;
/**
Get the quadrature point for the given face/edge
The quadrature point and weight are in the original parameter space
(not parametrized along an edge or face). The tangent parameter
direction(s) correspond to the directions in parameter space along
the specified surface. In the case when the parameter space is
of dimention 1, 2, or 3, there are respectively 0, 1 and 2 tagents
stored in row major order so that for the 3D case:
tangent = [d1[0], d1[1], d1[2], d2[0], d2[1], d2[2]]
Note that the tangents obey the right-hand rule so that
crossProduct(Xd*d1, Xd*d2) gives an outward-facing normal direction.
@param face The face/edge index
@param n The quadrautre point index
@param pt The quadrature point
@param tangent Parametric direction(s) parallel to the face
@return The quadrature weight for the face
*/
virtual double getFaceQuadraturePoint( int face, int n, double pt[],
double tangent[] ) = 0;
/**
Get the face normal at a specified face quadrature point.
This function returns a 2 or 3-vector depending on the dimension
of the problem. Note that this function can only be used to evaluate
the face normal at locations defined by the basis function class.
@param face The face/edge index
@param n The quadrautre point index
@param Xpts The node locations
@param Xd The derivative of the physical node location w.r.t. parameters
@param normal The face (or edge) normal
@return The area contribution
*/
TacsScalar getFaceNormal( int face, int n,
const TacsScalar Xpts[],
TacsScalar X[],
TacsScalar Xd[],
TacsScalar normal[] );
/**
Add the derivative of the face normal into the nodal sensitivities
@param face The face/edge index
@param n The quadrautre point index
@param Xpts The node locations
@param A The area contribution (computed from forward code)
@param normal The face normal
@param dfdA The input derivative of the function w.r.t. area
@param dfdXd The derivative of the function w.r.t. Xd
@param dfdn The derivative of the function w.r.t. surface normal
@param dfdXpts The output derivative w.r.t. the node locations
*/
void addFaceNormalXptSens( int face, int n,
const TacsScalar A,
const TacsScalar Xd[],
const TacsScalar normal[],
const TacsScalar dfdA,
const TacsScalar dfdX[],
const TacsScalar dfdXd[],
const TacsScalar dfdn[],
TacsScalar dfdXpts[] );
/**
Get the Jacobian transformation from computational to physical
coordinates.
This code returns the determinant of the transformation and
returns both the Xd, the derivative of physical coordinates
w.r.t. the parameters, and J, the inverse of Xd. This code can be
used for computing the volume/area quadratures.
@param n The index of the quadrature point
@param pt The quadrature point
@param Xpts The node locations
@param Xd The derivative of the physical node location w.r.t. parameters
@param J The Jacobian transformation (inverse of Xd)
@return The determinant of Xd
*/
TacsScalar getJacobianTransform( int n,
const double pt[],
const TacsScalar Xpts[],
TacsScalar Xd[],
TacsScalar J[] );
/**
Compute the derivative of the Jacobian transformation
This code adds the contribution to the derivative of the Jacobian
transformation to the output dfdXpts. Note that the inputs here
should be generated by a call to getJacobianTransform first. Note
that dfdXd and dfdJ may be passed as NULL.
@param n The index of the quadrature point
@param pt The quadrature point
@param Xpts The node locations
@param Xd The derivative of the physical node location w.r.t. parameters
@param J The Jacobian transformation (inverse of Xd)
@param dfddetJ The derivative of the function w.r.t. detJ
@param dfdXd The derivative of the function w.r.t. Xd
@param dfdJ The derivative of the function w.r.t. J
@param dfdXpts The output derivative of the function w.r.t. Xpts
*/
void addJacobianTransformXptSens( int n,
const double pt[],
const TacsScalar Xd[],
const TacsScalar J[],
TacsScalar dfddetJ,
const TacsScalar dfXd[],
const TacsScalar dfdJ[],
TacsScalar dfdXpts[] );
/**
Get the field values at the specified quadrature point
@param n The index of the quadrature point
@param pt The quadrature point
@param Xpts The element node locations
@param vars The element variable values
@param X The computed coordinate location at quadrature point n
@param U The computed field values at quadrature point n
*/
void getFieldValues( int n, const double pt[],
const TacsScalar Xpts[],
const int vars_per_node,
const TacsScalar vars[],
TacsScalar X[],
TacsScalar U[] );
/**
Get the gradient of the field at the quadrature point.
Note that all matrices are row-major order.
The arguments Xd and Ud are often only intermediate values, but are returned
here so that they can be passed in to the differentiated code.
@param n The index of the quadrature point
@param pt The parametric location
@param Xpts The element node locations
@param vars_per_node The number of degrees of freedom per node
@param vars The element state variables
@param dvars The first time derivative of the element state vars
@param ddvars The second time derivative of the element state vars
@param X The physical quadrature point
@param Xd The derivative of the physical node location w.r.t. parameters
@param J The Jacobian transformation (inverse of Xd)
@param Ut The variables and time derivatives at the quadrature point
@param Ud The derivative of the variables w.r.t. the parametric coords
@param Ux The derivative of the variables w.r.t. the spatial coords
@return The determinant of the matrix Xd
*/
TacsScalar getFieldGradient( int n,
const double pt[],
const TacsScalar Xpts[],
const int vars_per_node,
const TacsScalar vars[],
const TacsScalar dvars[],
const TacsScalar ddvars[],
TacsScalar X[],
TacsScalar Xd[],
TacsScalar J[],
TacsScalar Ut[],
TacsScalar Ud[],
TacsScalar Ux[] );
/**
Add the derivative of the field gradient terms with respect to
the state variable values.
@param n The index of the quadrature point
@param pt The parametric location
@param Xpts The element node locations
@param vars_per_node The number of degrees of freedom per node
@param Xd The derivative of the physical node location w.r.t. parameters
@param J The Jacobian transformation (inverse of Xd)
@param Ud The derivative of the variables w.r.t. the parametric coords
@param dfdUt The derivative of the function w.r.t. Ut
@param dfdUx The derivative of the function w.r.t. Ux
@param dfdu The output derivative of the function w.r.t. state variables
*/
void addFieldGradientSVSens( int n,
const double pt[],
const TacsScalar Xpts[],
const int vars_per_node,
const TacsScalar Xd[],
const TacsScalar J[],
const TacsScalar Ud[],
const TacsScalar dfdUt[],
TacsScalar dfdUx[],
TacsScalar dfdu[] );
/**
Add the contributions to the derivative of the node locations from
the computation of the field gradient.
This member function adds the contribution to the gradient from derivatives
of a function with respect to the determinant, the node location, the
derivatives of the nodes with respect to the parametric coordinates, and
the terms in the Jacobian transformation, and the derivatives of the
field quantities.
The terms dfdX, dfdXd, dfdJ and dfdUx may be passed in as NULL if they
are zero.
@param n The index of the quadrature point
@param pt The parametric location
@param Xpts The element node locations
@param vars_per_node The number of degrees of freedom per node
@param Xd The derivative of the physical node location w.r.t. parameters
@param J The Jacobian transformation (inverse of Xd)
@param Ud The derivative of the variables w.r.t. the parametric coords
@param dfddetJ The derivative of the determinant
@param dfdX The derivative w.r.t. node location
@param dfdXd The derivative w.r.t. the components of Xd
@param dfdJ The derivative w.r.t. the components of J
@param dfdUx The derivative w.r.t. the components of Ux
@param dfdXpts The output derivative of the function w.r.t. node locations
*/
void addFieldGradientXptSens( int n,
const double pt[],
const TacsScalar Xpts[],
const int vars_per_node,
const TacsScalar Xd[],
const TacsScalar J[],
const TacsScalar Ud[],
const TacsScalar dfddetJ,
const TacsScalar dfdX[],
const TacsScalar dfdXd[],
const TacsScalar dfdJ[],
const TacsScalar dfdUx[],
TacsScalar dfdXpts[] );
/**
Get the gradient of the field at the quadrature point.
This function returns the values and derivatives of the state variables,
and a corresponding adjoint vector. This is used in computing the
derivative of the adjoint-residual product.
Note that the adjoint variable vector Psi is of length vars_per_node,
(not 3*var_per_node), since it only contains the adjoint values, and
not their first and second time derivatives.
@param n The index of the quadrature point
@param pt The parametric location
@param Xpts The element node locations
@param vars_per_node The number of degrees of freedom per node
@param vars The element state variables
@param dvars The first time derivative of the element state vars
@param ddvars The second time derivative of the element state vars
@param X The physical quadrature point
@param Xd The derivative of the physical node location w.r.t. parameters
@param J The Jacobian transformation (inverse of Xd)
@param Ut The variables and time derivatives at the quadrature point
@param Ud The derivative of the variables w.r.t. the parametric coords
@param Ux The derivative of the variables w.r.t. the spatial coords
@param Psi The adjoint variable values (no time derivatives!)
@param Psid The derivatives of the adjoint variables w.r.t. parameters
@param Psix The spatial derivatives of the adjoint variables
@return The determinant of the matrix Xd
*/
TacsScalar getFieldGradient( int n,
const double pt[],
const TacsScalar Xpts[],
const int vars_per_node,
const TacsScalar vars[],
const TacsScalar dvars[],
const TacsScalar ddvars[],
const TacsScalar psi[],
TacsScalar X[],
TacsScalar Xd[],
TacsScalar J[],
TacsScalar Ut[],
TacsScalar Ud[],
TacsScalar Ux[],
TacsScalar Psi[],
TacsScalar Psid[],
TacsScalar Psix[] );
/**
Add the contributions to the derivative of the node locations from
the computation of the field and adjoint gradients.
The terms dfdX, dfdXd, dfdJ, dfdPsix or dfdUx may be passed in as NULL if they
are zero. Note that if either dfdPsix or dfdUx is NULL, then the other must
be as well. (If not you should use the other version of this code.)
@param n The index of the quadrature point
@param pt The parametric location
@param Xpts The element node locations
@param vars_per_node The number of degrees of freedom per node
@param Xd The derivative of the physical node location w.r.t. parameters
@param J The Jacobian transformation (inverse of Xd)
@param Ud The derivative of the variables w.r.t. the parametric coords
@param Psid The derivatives of the adjoint variables w.r.t. parameters
@param dfddetJ The derivative of the determinant
@param dfdX The derivative w.r.t. node location
@param dfdXd The derivative w.r.t. the components of Xd
@param dfdJ The derivative w.r.t. the components of J
@param dfdUx The derivative w.r.t. the components of Ux
@param dfdPsix The derivative w.r.t. the components of Psix
@param dfdXpts The output derivative of the function w.r.t. node locations
*/
void addFieldGradientXptSens( int n,
const double pt[],
const TacsScalar Xpts[],
const int vars_per_node,
const TacsScalar Xd[],
const TacsScalar J[],
const TacsScalar Ud[],
const TacsScalar Psid[],
const TacsScalar dfddetJ,
const TacsScalar dfdX[],
const TacsScalar dfdXd[],
const TacsScalar dfdJ[],
const TacsScalar dfdUx[],
const TacsScalar dfdPsix[],
TacsScalar dfdXpts[] );
/**
Add the weak form of the governing equations to the residual.
This code adds the residual contributions from a quadrature point
to the residual. The coefficients DUt and DUx are obtained from
the physical domain so the Jacobian transformation is applied to
bring these derivatives back to the computational space.
In this call, the values of DUt and DUx are modified in applying
the Jacobian transformation.
@param n The quadrautre point index
@param pt The quadrature point value
@param weight The quadrature weight
@param J The Jacobian coordinate transformation
@param vars_per_node The number of variables per node
@param DUt The coefficients of the temporal part of the weak form
@param DUx The coefficients of the spatial part of the weak form
@param res The residual
*/
void addWeakResidual( int n, const double pt[],
TacsScalar weight,
const TacsScalar J[],
const int vars_per_node,
TacsScalar DUt[],
TacsScalar DUx[],
TacsScalar res[] );
/**
Scale the terms in the Jacobian matrix
@param weight The quadrature weight
@param alpha Coefficient for the Jacobian w.r.t. states
@param beta Coefficient for the Jacobian w.r.t. first time deriv states
@param gamma Coefficient for the Jacobian w.r.t. second time deriv states
@param Jac_nnz Number of non-zero Jacobian entries
@param Jac_paris The (i,j) locations of the Jacobian entries
@param Jac The Jacobian values
*/
void scaleWeakMatrix( const TacsScalar weight,
const TacsScalar alpha,
const TacsScalar beta,
const TacsScalar gamma,
const int Jac_nnz,
const int *Jac_pairs,
TacsScalar *Jac );
/**
Add the entries from the matrix of the weak form residual to a matrix
@param n The quadrautre point index
@param pt The quadrature point value
@param J The Jacobian coordinate transformation
@param vars_per_node The number of variables per node
@param Jac_nnz Number of non-zero Jacobian entries
@param Jac_paris The (i,j) locations of the Jacobian entries
@param Jac The Jacobian values
@param mat The Jacobian matrix
*/
void addWeakMatrix( int n, const double pt[],
const TacsScalar J[],
const int vars_per_node,
const int Jac_nnz,
const int *Jac_pairs,
const TacsScalar *Jac,
TacsScalar *mat );
/**
Compute the matrix-vector product using thd data computed from a weak
The data array consists of both the Jacobian transformation and the
entries that contain the element matrix data obtained from a call to
evalWeakMatrix at a given quadrature point. The data is repeated for each
quadrature point in the element. For the case when num_params = 3, the
data array will contain the following entries:
data = [ J[0], J[1], ... , J[8], Jac[0], Jac[1], ... , Jac[Jac_nnz-1],
J[0], J[1], ... , J[8], Jac[0], Jac[1], ... , Jac[Jac_nnz-1],
.... ]
This data repeats for each quadrature point in element. It is assumed
that the non-zero pattern for each quadrature point is the same.
The overall size of the data array is therefore:
num_quadrature_points*(num_params*num_params + Jac_nnz)
The temp array is used to store intermediate values needed for the
computation of the matrix-vector product. The size of the temporary array
must be at least:
(num_quadrature_points+1)*vars_per_node*(num_params+1)
@param vars_per_node The number of variables per node
@param Jac_nnz Number of non-zero Jacobian entries
@param Jac_paris The (i,j) locations of the Jacobian entries
@param data The element data
@param temp A temporary array
@param px The input vector
@param py The output vector
*/
void addMatVecProduct( const int vars_per_node,
const int Jac_nnz,
const int *Jac_pairs,
const TacsScalar *data,
TacsScalar temp[],
const TacsScalar *px,
TacsScalar *py );
/**
Interpolate the specified number of fields
This function computes the following for i = 0, vars_per_node-1
field[incr*i] = sum_{j} N[j]*values[vars_per_node*j + i]
@param n The quadrature point index
@param pt The parametric point
@param vars_per_node The number of variables to interpolate
@param values The values of the field at the nodes
@param incr The increment between locations in the field array
@param field The field values
*/
virtual void interpFields( const int n,
const double pt[],
const int vars_per_node,
const TacsScalar values[],
const int incr,
TacsScalar field[] );
/**
Compute the interpolation field for three different interpolants
simultaneously. This is common when assemblying the temporal derivatives
This function computes the following for i = 0, vars_per_node-1
field[3*i] = sum_{j} N[j]*vals1[vars_per_node*j + i]
field[3*i+1] = sum_{j} N[j]*vals2[vars_per_node*j + i]
field[3*i+2] = sum_{j} N[j]*vals3[vars_per_node*j + i]
@param n The quadrature point index
@param pt The parametric point
@param vars_per_node The number of variables to interpolate
@param vals1 The first array of values at the nodes
@param vals2 The second array of values at the nodes
@param vals3 The third array of values at the nodes
@param field The field values
*/
virtual void interpFields( const int n,
const double pt[],
const int vars_per_node,
const TacsScalar val1[],
const TacsScalar val2[],
const TacsScalar val3[],
TacsScalar field[] );
/**
Add the transpose of the interpolation operation to the vector
This function computes the following for i = 0, vars_per_node-1,
and j = 0, num_nodes-1
values[vars_per_node*j + i] += N[j]*field[incr*i]
@param n The quadrature point index
@param pt The parametric point
@param incr The increment between locations in the field array
@param field The field values
@param vars_per_node The number of fields to interpolate
@param values The values of the variables at the nodes
*/
virtual void addInterpFieldsTranspose( const int n,
const double pt[],
const int incr,
const TacsScalar field[],
const int vars_per_node,
TacsScalar values[] );
/**
Compute the gradient of the fields in the computational space
This function must compute
grad[num_params*i + j] = sum_{k} N_{k,j}*values[vars_per_node*k + i]
@param n The quadrature point index
@param pt The parametric location of the quadrature point
@param vars_per_node The number of fields to interpolate
@param values The values of the field at the nodes
@param grad The gradient of the field in the computational space
*/
virtual void interpFieldsGrad( const int n,
const double pt[],
const int vars_per_node,
const TacsScalar values[],
TacsScalar grad[] );
/**
Add the transpose of the gradient interpolation to the vector
This function computes the following for i = 0, vars_per_node-1,
j = 1, num_params-1, and j = 0, num_nodes-1
values[vars_per_node*k + i] += N_{k,j}*grad[incr*i + j]
@param n The quadrature point index
@param pt The parametric location of the quadrature point
@param vars_per_node The number of fields to interpolate
@param grad The gradient of the field in the computational space
@param values The array to add values
*/
virtual void addInterpFieldsGradTranspose( int n,
const double pt[],
const int vars_per_node,
const TacsScalar grad[],
TacsScalar values[] );
/**
Interpolate the fields and gradients at every quadrature point and
store them in the array out.
The values are stored by values and gradients, so the total size of
the output array "out" is:
vars_per_node*(num_params + 1)*num_quadrature_points
*/
virtual void interpAllFieldsGrad( const int vars_per_node,
const TacsScalar values[],
TacsScalar out[] );
/*
*/
virtual void addInterpAllFieldsGradTranspose( const int vars_per_node,
const TacsScalar in[],
TacsScalar values[] );
/**
Add the outer-product of the shape functions to the matrix
mat[row_incr*i + col_incr*j] += scale*N[i]*N[j]
@param n The quadrature point index
@param pt The parametric location of the quadrature point
@param weight The weight factor added to the matrix
@param row_incr The row increment applied to the matrix
@param col_incr The column increment applied to the matrix
@param mat The element matrix
*/
virtual void addInterpOuterProduct( const int n,
const double pt[],
const TacsScalar weight,
const int row_incr,
const int col_incr,
TacsScalar *mat );
/**
Add the outer-product of the shape functions to the matrix
mat[row_incr*i + col_incr*j] += scale*N[i]*N[j]
@param n The quadrature point index
@param pt The parametric location of the quadrature point
@param weight The weight factor added to the matrix
@param row_incr The row increment applied to the matrix
@param col_incr The column increment applied to the matrix
@param mat The element matrix
*/
virtual void addInterpGradOuterProduct( const int n,
const double pt[],
const int transpose,
const TacsScalar weight,
const TacsScalar scale[],
const int row_incr,
const int col_incr,
TacsScalar *mat );
/**
Add the outer-product of the shape functions to the matrix
mat[row_incr*i + col_incr*j] += scale*N,x[i]*N,x[j]
@param n The quadrature point index
@param pt The parametric location of the quadrature point
@param weight The weight factor added to the matrix
@param row_incr The row increment applied to the matrix
@param col_incr The column increment applied to the matrix
@param mat The element matrix
*/
virtual void addInterpGradGradOuterProduct( const int n,
const double pt[],
const TacsScalar weight,
const TacsScalar iscale[],
const TacsScalar jscale[],
const int row_incr,
const int col_incr,
TacsScalar *mat );
/**
Compute the interpolate to a quadrature point on the face
By default, this evaluates the interpFields function, but if you have
a specific shape function implementation, indexed on the quadrature
point, this will not work.
@param face The face index
@param n The quadrature point index on this face
@param vars_per_node The number of variables per node
@param values The values to interpolate
@param incr The increment between locations in the field array
@param field The field values
*/
virtual void interpFaceFields( const int face,
const int n,
const double pt[],
const int vars_per_node,
const TacsScalar values[],
const int incr,
TacsScalar field[] );
/**
Add the transpose of the interpolation operation to the vector
on the face quadrature points.
@param n The quadrature point index
@param pt The parametric point
@param vars_per_node The number of variables per node
@param values The values of the interpolant at the nodes
@param incr The increment between locations in the field array
@param field The field values
*/
virtual void addInterpFaceFieldsTranspose( const int face,
const int n,
const double pt[],
const int incr,
const TacsScalar field[],
const int vars_per_node,
TacsScalar values[] );
/**
Compute the interpolate to a quadrature point on the face
By default, this evaluates the interpFields function, but if you have
a specific shape function implementation, indexed on the quadrature
point, this will not work.
@param face The face index
@param n The quadrature point index on this face
@param vars_per_node The number of fields to interpolate
@param values The values to interpolate
@param grad The gradient of the field in the computational space
*/
virtual void interpFaceFieldsGrad( const int face,
const int n,
const double pt[],
const int vars_per_node,
const TacsScalar values[],
TacsScalar grad[] );
/**
Add the transpose of the gradient interpolation to the vector
at quadrature points on the specified face
@param face The face index
@param n The quadrature point index
@param pt The parametric location of the quadrature point
@param vars_per_node The number of fields to interpolate
@param values The values of the interpolant at the nodes
@param grad The gradient of the field in the computational space
*/
virtual void addInterpFaceFieldsGradTranspose( const int face,
int n,
const double pt[],
const int vars_per_node,
const TacsScalar grad[],
TacsScalar values[] );
/**
Evaluate the basis functions at the quadrature points
This provides direct access to the shape functions, but should
not be used by any external code.
@param pt The quadrature point
@param N The shape function values
*/
virtual void computeBasis( const double pt[], double N[] ) = 0;
/**
Evaluate the basis functions and their derivatives at each
node.
@param pt The quadrature point
@param N The shape function values
@param Nxi The derivatives of the shape functions
*/
virtual void computeBasisGradient( const double pt[], double N[], double Nxi[] ) = 0;
private:
// This is the maximum number of nodes (basis functions). This
// is only used in the default implementation of the interpolatant
// functions above and should not be accessed by any external class.
static const int MAX_NUM_NODES = 216; // = 6**3
};
#endif // TACS_ELEMENT_BASIS_H
| 41.506024 | 87 | 0.601538 | [
"shape",
"vector",
"3d"
] |
e6698b3fa9c243a87527fe4b61a5a2d1a7eef265 | 2,241 | h | C | include/avalanche/CLBufferPool.h | kpot/avalanche | 4bfa6f66a5610d3619414e374d77eae2edcb8b20 | [
"MIT"
] | 6 | 2019-02-02T22:35:03.000Z | 2022-02-28T20:15:48.000Z | include/avalanche/CLBufferPool.h | kpot/avalanche | 4bfa6f66a5610d3619414e374d77eae2edcb8b20 | [
"MIT"
] | null | null | null | include/avalanche/CLBufferPool.h | kpot/avalanche | 4bfa6f66a5610d3619414e374d77eae2edcb8b20 | [
"MIT"
] | 1 | 2020-08-04T21:32:35.000Z | 2020-08-04T21:32:35.000Z | #ifndef AVALANCHE_CLBUFFERPOOL_H
#define AVALANCHE_CLBUFFERPOOL_H
#include <memory>
#include <mutex>
#include <array>
#include "CL_cust/cl2.hpp"
#include "avalanche/ArrayType.h"
#include "avalanche/Shape.h"
namespace avalanche {
class CLBuffer;
class MultiArray;
class CLMemoryManager;
/** A pool of OpenCL buffers, strictly associated with a particular device */
// TODO: Check if the pool has been destroyed
class CLBufferPool {
public:
// Enough for up to 1 TB of buffers
static constexpr std::uint8_t MaxBuckets = 40;
static constexpr std::size_t MaxBufferSize = (
static_cast<std::size_t>(1) << MaxBuckets);
CLBufferPool(CLMemoryManager* memory_manager,
std::size_t device_index,
const cl::Context &context,
const cl::CommandQueue &device_queue);
~CLBufferPool();
bool is_linked_with_device(const cl::Device &device) const;
std::shared_ptr<MultiArray> make_array(
Shape shape, ArrayType dtype=ArrayType::float32);
std::shared_ptr<CLBuffer> reserve_buffer(std::size_t size_in_bytes);
template <typename Vector>
std::shared_ptr<CLBuffer> reserve_buffer_for_vector(Vector v) {
return reserve_buffer(sizeof(typename Vector::value_type) * v.size());
}
static long find_mem_slot(size_t size);
std::size_t num_available_blocks() const;
std::size_t num_buckets() const;
std::size_t device_index() { return _device_index; }
cl::CommandQueue& cl_queue() { return _device_queue; }
const cl::CommandQueue& cl_queue() const { return _device_queue; }
cl::Context& cl_context() { return _cl_context; }
std::shared_ptr<CLBufferPool> own_reference();
bool queue_support_ooo_execution() const;
private:
CLMemoryManager *_memory_manager;
std::size_t _device_index;
cl::Context _cl_context;
cl::CommandQueue _device_queue;
const cl::Device _cl_device;
std::array<std::vector<cl::Buffer>, MaxBuckets> _buckets;
std::array<std::mutex, MaxBuckets> _buckets_mutex;
friend class CLBuffer;
void return_buffer(cl::Buffer &&cl_buffer, long bucket_idx);
};
using BufferPoolRef = std::shared_ptr<CLBufferPool>;
} // namespace
#endif //AVALANCHE_CLBUFFERPOOL_H
| 31.125 | 78 | 0.716644 | [
"shape",
"vector"
] |
e66ff43c72cbb9b57d530e51a3b8d6c7cba0308d | 1,246 | h | C | HelloWorld/Classes/ChipmunkLayer.h | authorly/interapptive | c0e564695af649087d329bc519f04e5f85b47035 | [
"Zlib",
"Apache-2.0",
"MIT",
"Libpng",
"curl",
"BSD-3-Clause"
] | 1 | 2020-08-21T02:36:16.000Z | 2020-08-21T02:36:16.000Z | HelloWorld/Classes/ChipmunkLayer.h | authorly/interapptive | c0e564695af649087d329bc519f04e5f85b47035 | [
"Zlib",
"Apache-2.0",
"MIT",
"Libpng",
"curl",
"BSD-3-Clause"
] | null | null | null | HelloWorld/Classes/ChipmunkLayer.h | authorly/interapptive | c0e564695af649087d329bc519f04e5f85b47035 | [
"Zlib",
"Apache-2.0",
"MIT",
"Libpng",
"curl",
"BSD-3-Clause"
] | null | null | null | #ifndef interapptive_ChipmunkLayer_h
#define interapptive_ChipmunkLayer_h
#include "SharedGlobalData.h"
#include "CCLayer.h"
#include "chipmunk.h"
#include <vector>
class ChipmunkLayer : public cocos2d::CCLayer
{
public:
static ChipmunkLayer* layerWithPage(FallingObjectSetting *fallingObjectSetting, StaticObjectSetting *staticObjectSetting);
~ChipmunkLayer();
ChipmunkLayer();
void newFallingObject(float dt);
virtual void update(float dt);
virtual void onEnter();
virtual void onExit();
virtual void didAccelerate(cocos2d::CCAcceleration* pAccelerationValue);
std::vector<cpBody*>& getBodysToBeFreeArray();
private:
bool init(FallingObjectSetting *fallingObjectSetting, StaticObjectSetting *staticObjectSetting);
void setupSpace();
void addFloor();
void addWalls();
void createStaticPhysicObject();
void freeBodies();
private:
cpSpace *space;
int totalFallingObjects;
float accX;
float accY;
bool isFallingObjectTouched;
std::vector<cpBody*> staticBodyArray;
std::vector<cpBody*> bodyTobeFreeArray;
// weak ref
FallingObjectSetting *fallingObjectSetting;
StaticObjectSetting *staticObjectSetting;
};
#endif
| 24.431373 | 126 | 0.73114 | [
"vector"
] |
e6748a6adcd21d1d3b25b0eaee583f4c5451bbba | 848 | h | C | SimpleRPG-Text/Inventory.h | utilForever/SimpleRPG-Text | 546c130f93505984dc77c51a872254c52ef99470 | [
"MIT"
] | 33 | 2015-10-01T05:38:05.000Z | 2021-09-25T01:43:30.000Z | SimpleRPG-Text/Inventory.h | mudaliaraditya/SimpleRPG-Text | 546c130f93505984dc77c51a872254c52ef99470 | [
"MIT"
] | 1 | 2015-10-02T15:20:22.000Z | 2015-10-02T15:20:22.000Z | SimpleRPG-Text/Inventory.h | mudaliaraditya/SimpleRPG-Text | 546c130f93505984dc77c51a872254c52ef99470 | [
"MIT"
] | 10 | 2015-09-30T14:54:59.000Z | 2020-05-20T19:26:42.000Z | #ifndef INVENTORY_H
#define INVENTORY_H
#include <list>
#include <utility>
#include "JsonBox.h"
#include "EntityManager.h"
class Item;
class Weapon;
class Armor;
class Inventory
{
private:
std::list<std::pair<Item*, int>> items;
template <typename T>
void Load(JsonBox::Value& v, EntityManager* manager);
template <typename T>
JsonBox::Array JSONArray();
public:
Inventory();
Inventory(JsonBox::Value& _v, EntityManager* _manager);
void Add(Item* itemToAdd, int count);
void Remove(Item* itemToRemove, int count);
int Count(Item* itemToCount);
template <typename T>
int Count(unsigned int pos);
template <typename T>
T* Get(unsigned int pos);
int Print(bool label = false);
template <typename T>
int Print(bool label = false);
void Clear();
void Merge(Inventory* inventory);
JsonBox::Object GetJSON();
};
#endif | 16.627451 | 56 | 0.716981 | [
"object"
] |
e6775b68b4149ed08427dedd568286860e76267e | 16,916 | h | C | src/MagnumPlugins/GlslangShaderConverter/GlslangConverter.h | jlaxson/magnum-plugins | 17561c8c2397b210f768c5843267a67e8179ce33 | [
"MIT"
] | null | null | null | src/MagnumPlugins/GlslangShaderConverter/GlslangConverter.h | jlaxson/magnum-plugins | 17561c8c2397b210f768c5843267a67e8179ce33 | [
"MIT"
] | null | null | null | src/MagnumPlugins/GlslangShaderConverter/GlslangConverter.h | jlaxson/magnum-plugins | 17561c8c2397b210f768c5843267a67e8179ce33 | [
"MIT"
] | null | null | null | #ifndef Magnum_ShaderTools_GlslangConverter_h
#define Magnum_ShaderTools_GlslangConverter_h
/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019,
2020 Vladimír Vondruš <mosra@centrum.cz>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/** @file
* @brief Class @ref Magnum::ShaderTools::GlslangConverter
* @m_since_latest_{plugins}
*/
#include <Magnum/ShaderTools/AbstractConverter.h>
#include "MagnumPlugins/GlslangShaderConverter/configure.h"
#ifndef DOXYGEN_GENERATING_OUTPUT
#ifndef MAGNUM_GLSLANGSHADERCONVERTER_BUILD_STATIC
#ifdef GlslangShaderConverter_EXPORTS
#define MAGNUM_GLSLANGSHADERCONVERTER_EXPORT CORRADE_VISIBILITY_EXPORT
#else
#define MAGNUM_GLSLANGSHADERCONVERTER_EXPORT CORRADE_VISIBILITY_IMPORT
#endif
#else
#define MAGNUM_GLSLANGSHADERCONVERTER_EXPORT CORRADE_VISIBILITY_STATIC
#endif
#define MAGNUM_GLSLANGSHADERCONVERTER_LOCAL CORRADE_VISIBILITY_LOCAL
#else
#define MAGNUM_GLSLANGSHADERCONVERTER_EXPORT
#define MAGNUM_GLSLANGSHADERCONVERTER_LOCAL
#endif
namespace Magnum { namespace ShaderTools {
/**
@brief Glslang shader converter plugin
@m_since_latest_{plugins}
@m_keywords{GlslangShaderConverter GlslToSpirvShaderConverter}
@m_keywords{GlslShaderConverter}
Uses [Glslang](https://github.com/KhronosGroup/glslang) for GLSL validation and
GLSL to SPIR-V compilation (@ref Format::Glsl, @ref Format::Spirv).
This plugin provides the `GlslShaderConverter` and `GlslToSpirvShaderConverter`
plugins.
@m_class{m-block m-danger}
@thirdparty This library makes use of [Glslang](https://github.com/KhronosGroup/glslang),
licensed under a mixture of @m_class{m-label m-success} **BSD 3-clause**,
@m_class{m-label m-success} **BSD 2-clause**,
@m_class{m-label m-success} **MIT**, @m_class{m-label m-success} **Apache**,
@m_class{m-label m-danger} **modified GPLv3** and
@m_class{m-label m-warning} **NVidia Software** licenses
([license text](https://github.com/KhronosGroup/glslang/blob/master/LICENSE.txt)).
Please consult the license before use.
@section ShaderTools-GlslangConverter-usage Usage
This plugin depends on the @ref ShaderTools and [Glslang](https://github.com/KhronosGroup/glslang)
libraries and is built if `WITH_GLSLANGSHADERCONVERTER` is enabled when
building Magnum Plugins. To use as a dynamic plugin, load
@cpp "GlslangShaderConverter" @ce via @ref Corrade::PluginManager::Manager.
Additionally, if you're using Magnum as a CMake subproject, bundle the
[magnum-plugins](https://github.com/mosra/magnum-plugins) and
[glslang](https://github.com/KhronosGroup/glslang) repositories and do the
following. If you want to use system-installed Glslang, omit the first part and
point `CMAKE_PREFIX_PATH` to their installation dir if necessary.
@code{.cmake}
# Skip tests, external dependencies, glslangValidator executable, SPIR-V Tools
# integration and HLSL support, which Magnum doesn't use
set(BUILD_TESTING OFF CACHE BOOL "" FORCE)
set(BUILD_EXTERNAL OFF CACHE BOOL "" FORCE)
set(ENABLE_CTEST OFF CACHE BOOL "" FORCE)
set(ENABLE_GLSLANG_BINARIES OFF CACHE BOOL "" FORCE)
set(ENABLE_OPT OFF CACHE BOOL "" FORCE)
set(ENABLE_HLSL OFF CACHE BOOL "" FORCE)
set(ENABLE_SPVREMAPPER OFF CACHE BOOL "" FORCE)
add_subdirectory(glslang EXCLUDE_FROM_ALL)
set(WITH_GLSLANGSHADERCONVERTER ON CACHE BOOL "" FORCE)
add_subdirectory(magnum-plugins EXCLUDE_FROM_ALL)
# So the dynamically loaded plugin gets built implicitly
add_dependencies(your-app MagnumPlugins::GlslangShaderConverter)
@endcode
To use as a static plugin or as a dependency of another plugin with CMake, put
[FindMagnumPlugins.cmake](https://github.com/mosra/magnum-plugins/blob/master/modules/FindMagnumPlugins.cmake)
and [FindGlslang.cmake](https://github.com/mosra/magnum-plugins/blob/master/modules/FindGlslang.cmake)
into your `modules/` directory, request the `GlslangShaderConverter` component
of the `MagnumPlugins` package and link to the
`MagnumPlugins::GlslangShaderConverter` target:
@code{.cmake}
find_package(MagnumPlugins REQUIRED GlslangShaderConverter)
# ...
target_link_libraries(your-app PRIVATE MagnumPlugins::GlslangShaderConverter)
@endcode
See @ref building-plugins, @ref cmake-plugins and @ref plugins for more
information.
@section ShaderTools-GlslangConverter-conversion Compiling GLSL to SPIR-V
Use one of the @ref convertDataToData(), @ref convertDataToFile(),
@ref convertFileToData() or @ref convertFileToFile() APIs to compile a GLSL
source for a particular stage to SPIR-V. Only GLSL 1.40 (OpenGL 3.2) and higher
is accepted by Glslang for compilation to SPIR-V, earlier versions can be only
validated. See @ref ShaderTools-GlslangConverter-stages and
@ref ShaderTools-GlslangConverter-format below for details on how to specify a
shader stage, input/output format version and target environment.
@section ShaderTools-GlslangConverter-validation GLSL validation
Use @ref validateData() or @ref validateFile() to validate a GLSL file. Unlike
SPIR-V compilation, all versions starting from GLSL 1.10 (OpenGL 2.0) can be
validated. Note that in some cases, such as opening an inaccessible file or an
assembly error the validation function can return @cpp {false, ""} @ce and
print a message to the error output instead.
Validation results are highly dependent on the target format and version set
using @ref setOutputFormat(), see @ref ShaderTools-GlslangConverter-format
below for details. Additional validation options can be set through the
@ref ShaderTools-GlslangConverter-configuration "plugin-specific config".
@section ShaderTools-GlslangConverter-includes Processing #include directives
If the `GL_GOOGLE_include_directive` extension is enabled (which, crazily
enough, isn't listed in any registry nor has any public specification), it's
possible to @cpp #include @ce other source files. You can also use the
extension directive to distinguish between offline compilation and runtime
compilation by a GL driver (in which case you'd add the extra sources for
example with a sequence of @ref GL::Shader::addSource() calls):
@code{.glsl}
#ifdef GL_GOOGLE_include_directive
#extension GL_GOOGLE_include_directive: require
#include "fullScreenTriangle.glsl"
#include "constants.glsl"
#endif
@endcode
Currently, only @cpp #include "file" @ce directives are implemented in the
plugin, system includes using @cpp #include <file> @ce are reserved for future
use.
@m_class{m-note m-warning}
@par
The @gl_extension{ARB,shading_language_include} extension isn't supported
due to subtle sematical differences --- the [offical reasoning](https://github.com/KhronosGroup/glslang/issues/249)
is that this extension relies on shader sources being supplied at runtime
which makes it impossible to validate the shader offline.
If you validate or convert using @ref validateFile(), @ref convertFileToFile()
or @ref convertFileToData(), this will work automatically, with includes being
searched for relative to the top-level file. If you are validating/converting
data or when need more flexibility such as custom include paths, you also
supply an @ref ShaderTools-AbstractConverter-usage-callbacks "input file callback",
which will then get called for all encountered files.
While it's possible that the callback gets called multiple times for a single
file due to common files being included from multiple places, a
@ref InputFileCallbackPolicy::LoadTemporary is guaranteed to be followed by a
matching @ref InputFileCallbackPolicy::Close before a
@ref InputFileCallbackPolicy::LoadTemporary happens again --- or, in other
words, @ref InputFileCallbackPolicy::Close is never called twice for the same
file without a corresponding @ref InputFileCallbackPolicy::LoadTemporary in
between. This means the user callbacks don't need to implement any kind of
reference counting, that's handled on the plugin side.
@section ShaderTools-GlslangConverter-stages Shader stages
When validating or converting files using @ref validateFile(),
@ref convertFileToFile() or @ref convertFileToData() and passing
@ref Stage::Unspecified, shader stage is detected based on filename extension
suffix:
- `*.vert` for @ref Stage::Vertex
- `*.frag` for @ref Stage::Fragment
- `*.geom` for @ref Stage::Geometry
- `*.tesc` for @ref Stage::TessellationControl
- `*.tese` for @ref Stage::TessellationEvaluation
- `*.comp` for @ref Stage::Compute
- `*.rgen` for @ref Stage::RayGeneration
- `*.rahit` for @ref Stage::RayAnyHit
- `*.rchit` for @ref Stage::RayClosestHit
- `*.rmiss` for @ref Stage::RayMiss
- `*.rint` for @ref Stage::RayIntersection
- `*.rcall` for @ref Stage::RayCallable
- `*.task` for @ref Stage::MeshTask
- `*.mesh` for @ref Stage::Mesh
Similarly is done for filenames ending with `*.<stage>.glsl`. If none of above
matches or if validating/converting data instead of a file,
@ref Stage::Unspecified is treated the same as @ref Stage::Vertex.
@section ShaderTools-GlslangConverter-format Input and output format and version
The @p format passed to @ref setInputFormat() has to be either
@ref Format::Unspecified or @ref Format::Glsl. The GLSL version is taken from
the @cpp #version @ce directive, if present in the source, and defaults to
@cpp 110 @ce (GLSL 1.10, OpenGL 2.0) if not specified. It can be forcibly
overriden with the @p version parameter to one of the following values,
equivalently to allowed @cpp #version @ce directives:
- `110` for GLSL 1.10 (OpenGL 2.0)
- `120` for GLSL 1.20 (OpenGL 2.1)
- `130` for GLSL 1.30 (OpenGL 3.0)
- `140` for GLSL 1.40 (OpenGL 3.1)
- `150` for GLSL 1.50 compatibility profile (OpenGL 3.2)
- `150 core` for GLSL 1.50 core profile (OpenGL 3.2)
- `330` for GLSL 3.30 compatibility profile (OpenGL 3.3)
- `330 core` for GLSL 3.30 core profile (OpenGL 3.3)
- `400` for GLSL 4.00 compatibility profile (OpenGL 4.0)
- `400 core` for GLSL 4.00 core profile (OpenGL 4.0)
- `410` for GLSL 4.10 compatibility profile (OpenGL 4.1)
- `410 core` for GLSL 4.10 core profile (OpenGL 4.1)
- `420` for GLSL 4.20 compatibility profile (OpenGL 4.2)
- `420 core` for GLSL 4.20 core profile (OpenGL 4.2)
- `430` for GLSL 4.30 compatibility profile (OpenGL 4.3)
- `430 core` for GLSL 4.30 core profile (OpenGL 4.3)
- `440` for GLSL 4.40 compatibility profile (OpenGL 4.4)
- `440 core` for GLSL 4.40 core profile (OpenGL 4.4)
- `450` for GLSL 4.50 compatibility profile (OpenGL 4.5)
- `450 core` for GLSL 4.50 core profile (OpenGL 4.5)
- `460` for GLSL 4.60 compatibility profile (OpenGL 4.6)
- `460 core` for GLSL 4.60 core profile (OpenGL 4.6)
- `100 es` for GLSL ES 1.00 (OpenGL ES 2.0)
- `300 es` for GLSL ES 3.00 (OpenGL ES 3.0)
- `310 es` for GLSL ES 3.10 (OpenGL ES 3.1)
- `320 es` for GLSL ES 3.20 (OpenGL ES 3.2)
The @p format passed to @ref setOutputFormat() has to be either
@ref Format::Unspecified or @ref Format::Spirv. The @p version is divided
between target and SPIR-V version, and by default targets Vulkan 1.0 and SPIR-V
1.0. You can override using the second parameter passed to
@ref setOutputFormat() either by specifying just the target, having the SPIR-V
version implicit:
- `opengl` for generic OpenGL without any SPIR-V rules applied (validation
only)
- `opengl4.5` for OpenGL 4.5, implicitly with SPIR-V 1.0
- `vulkan1.0` for Vulkan 1.0, implicitly with SPIR-V 1.0
- `vulkan1.1` for Vulkan 1.1, implicitly with SPIR-V 1.3
- `vulkan1.2` for Vulkan 1.2, implicitly with SPIR-V 1.5
Or by specifying a `<target> spv<major>.<minor>` version, where `<target>` is
one of the above and the `<major>`/`<minor>` is from the range of 1.0 to 1.5.
So for example `vulkan1.1 spv1.4` will target Vulkan 1.1 with SPIR-V 1.4
(instead of the default SPIR-V 1.3).
In case of validation and @p version set to `opengl` or `opengl4.5`, the
implicit @ref Format::Unspecified means no SPIR-V specific rules will be
enforced (like explicit uniform locations) in order to make it possible to
validate non-SPIR-V shaders such as GLSL ES or WebGL ones. In case of
`opengl4.5` you can set @ref Format::Spirv to enforce SPIR-V rules as well, and
thus behave the same as when doing a SPIR-V conversion. Using a @p version in
the `opengl4.5 spv<major>.<minor>` form will also imply @ref Format::Spirv. For
Vulkan validation and SPIR-V conversion, @ref Format::Unspecified is treated
the same way as @ref Format::Spirv.
Apart from imposing various target-specific restrictions on the GLSL source,
the `openglX.Y` target implicitly adds @cpp #define GL_SPIRV @ce (as specified
by @gl_extension{ARB,gl_spirv}), while `vulkanX.Y` adds @cpp #define VULKAN @ce
(as specified by @m_class{m-doc-external} [GL_KHR_vulkan_glsl](https://github.com/KhronosGroup/GLSL/blob/master/extensions/khr/GL_KHR_vulkan_glsl.txt)).
Either of those macros is always defined for conversion, for validation it's
defined only if SPIR-V validation is included, as defined in the paragraph
above.
@section ShaderTools-GlslangConverter-debug-info-level Debug info level
By default, the converter outputs SPIR-V without any debug information. You
can control this using @ref setDebugInfoLevel():
- `0` or the empty default generates no debug info
- `1` makes the input GLSL source embedded in the `OpSource` instruction
(including the filename, if converting from a file), together with `OpLine`
providing line info for the instructions and `OpModuleProcessed` describing
what all processing steps were taken by Glslang
@section ShaderTools-GlslangConverter-configuration Plugin-specific config
It's possible to tune various compiler and validator options through
@ref configuration(). There's also a configurable set of builtins and limits,
affecting validation and compilation results. See below for all options and
their default values.
@snippet MagnumPlugins/GlslangShaderConverter/GlslangShaderConverter.conf config
*/
class MAGNUM_GLSLANGSHADERCONVERTER_EXPORT GlslangConverter: public AbstractConverter {
public:
/** @brief Initialize the Glslang library */
static void initialize();
/** @brief Finalize the Glslang library */
static void finalize();
/** @brief Plugin manager constructor */
explicit GlslangConverter(PluginManager::AbstractManager& manager, const std::string& plugin);
private:
MAGNUM_GLSLANGSHADERCONVERTER_LOCAL ConverterFeatures doFeatures() const override;
MAGNUM_GLSLANGSHADERCONVERTER_LOCAL void doSetInputFormat(Format format, Containers::StringView version) override;
MAGNUM_GLSLANGSHADERCONVERTER_LOCAL void doSetOutputFormat(Format format, Containers::StringView version) override;
MAGNUM_GLSLANGSHADERCONVERTER_LOCAL void doSetDefinitions(Containers::ArrayView<const std::pair<Containers::StringView, Containers::StringView>> definitions) override;
MAGNUM_GLSLANGSHADERCONVERTER_LOCAL void doSetDebugInfoLevel(Containers::StringView level) override;
MAGNUM_GLSLANGSHADERCONVERTER_LOCAL std::pair<bool, Containers::String> doValidateFile(Stage stage, Containers::StringView filename) override;
MAGNUM_GLSLANGSHADERCONVERTER_LOCAL std::pair<bool, Containers::String> doValidateData(Stage stage, Containers::ArrayView<const char> data) override;
MAGNUM_GLSLANGSHADERCONVERTER_LOCAL bool doConvertFileToFile(Magnum::ShaderTools::Stage stage, Containers::StringView from, Containers::StringView to) override;
MAGNUM_GLSLANGSHADERCONVERTER_LOCAL Containers::Array<char> doConvertFileToData(Magnum::ShaderTools::Stage stage, Containers::StringView from) override;
MAGNUM_GLSLANGSHADERCONVERTER_LOCAL Containers::Array<char> doConvertDataToData(Magnum::ShaderTools::Stage stage, Containers::ArrayView<const char> data) override;
struct State;
Containers::Pointer<State> _state;
};
}}
#endif
| 48.469914 | 175 | 0.771577 | [
"mesh",
"geometry"
] |
e6846167c8d26467ac797198ecfa18a14f2cd1b9 | 8,246 | c | C | iOS/buildlibs/armv7/allegro-4.4.2/addons/allegrogl/examp/exext.c | jonreyno/AGS | 6922847542401f451a26c6cc31b9d51b5889a008 | [
"Artistic-2.0"
] | 21 | 2019-05-08T23:50:29.000Z | 2021-04-28T07:59:17.000Z | iOS/buildlibs/armv7/allegro-4.4.2/addons/allegrogl/examp/exext.c | jonreyno/AGS | 6922847542401f451a26c6cc31b9d51b5889a008 | [
"Artistic-2.0"
] | null | null | null | iOS/buildlibs/armv7/allegro-4.4.2/addons/allegrogl/examp/exext.c | jonreyno/AGS | 6922847542401f451a26c6cc31b9d51b5889a008 | [
"Artistic-2.0"
] | 6 | 2019-05-19T04:30:15.000Z | 2022-01-29T05:26:46.000Z | /* This examples demonstrates how to use the AllegroGL extension mechanism.
*/
#include <math.h>
#include <string.h>
#include <allegro.h>
#include "alleggl.h"
#ifdef ALLEGRO_MACOSX
#include <OpenGL/glu.h>
#else
#include <GL/glu.h>
#endif
#ifndef M_PI
#define M_PI 3.1415926535897932384626433832795
#endif
#define WINDOW_W 640
#define WINDOW_H 480
#define MESH_SIZE 64
GLfloat mesh[MESH_SIZE][MESH_SIZE][3];
GLfloat wave_movement = 0.0f;
/* Define our vertex program.
* It basically does:
* pos = vertex.position;
* pos.y = (sin(wave.x + pos.x / 5) + sin(wave.x + pos.z / 4)) * 2.5;
* result.position = modelview * projection * pos;
*/
/* Plain ARBvp doesn't have a SIN opcode, so we provide one, built on a taylor
* expansion, with some fugding.
*
* First, we convert the operand to the [-pi..+pi] period by:
* - Dividing by 2pi, adding 1/2
* - Taking the fraction of the result
* - Multiplying by 2pi, then subtracting pi.
* x' = frac((x / 2pi) + 0.5) * 2pi - pi
*
* Then, we compute the sine using a 7th order Taylor series centered at 0:
* x' = x - x^3/3! + x^5/5! - x^7/7!
*
* Note that we begin by multiplying x by 0.98 as a fugding factor to
* compensate for the fact that our Taylor series is just an approximation.
* The error is then reduced to < 0.5% from the ideal sine function.
*/
#define SIN(d, s, t) \
/* Convert to [-pi..+pi] period */ \
"MAD "d", "s", one_over_pi, 0.5;\n" \
"FRC "d","d";\n" \
"MAD "d","d", two_pi, -pi;\n" \
"MUL "d","d", 0.98;\n" /* Scale input to compensate for prec error */\
/* Compute SIN(d), using a Taylor series */ \
"MUL "t".x, "d", "d";\n" /* x^2 */ \
"MUL "t".y, "t".x, "d";\n" /* x^3 */ \
"MUL "t".z, "t".y, "t".x;\n" /* x^5 */ \
"MUL "t".w, "t".z, "t".x;\n" /* x^7 */ \
"MAD "d", "t".y,-inv_3_fact, "d";\n" /* x - x^3/3! */ \
"MAD "d", "t".z, inv_5_fact, "d";\n" /* x - x^3/3! + x^5/5! */ \
"MAD "d", "t".w,-inv_7_fact, "d";\n" /* x - x^3/3! + x^5/5! - x^7/7!*/
/* This is the actual vertex program.
* It computes sin(wave.x + pos.x / 5) and sin(wave.x + pos.z), adds them up,
* scales the result by 2.5 and stores that as the vertex's y component.
*
* Then, it does the modelview-projection transform on the vertex.
*
* XXX<rohannessian> Broken ATI drivers need a \n after each "line"
*/
const char *program =
"!!ARBvp1.0\n"
"ATTRIB pos = vertex.position;\n"
"ATTRIB wave = vertex.attrib[1];\n"
"PARAM modelview[4] = { state.matrix.mvp };\n"
"PARAM one_over_pi = 0.1591549;\n"
"PARAM pi = 3.1415926;\n"
"PARAM two_pi = 6.2831853;\n"
"PARAM inv_3_fact = 0.1666666;\n"
"PARAM inv_5_fact = 0.00833333333;\n"
"PARAM inv_7_fact = 0.00019841269841269;\n"
"TEMP temp, temp2;\n"
/* temp.y = sin(wave.x + pos.x / 5) */
"MAD temp.y, pos.x, 0.2, wave.x;\n"
SIN("temp.y", "temp.y", "temp2")
/* temp.y += sin(wave.x + pos.z / 4) */
"MAD temp.x, pos.z, 0.25, wave.x;\n"
SIN("temp.x", "temp.x", "temp2")
"ADD temp.y, temp.x, temp.y;\n"
/* pos.y = temp.y * 2.5 */
"MOV temp2, pos;\n"
"MUL temp2.y, temp.y, 2.5;\n"
/* Transform the position by the modelview matrix */
"DP4 result.position.w, temp2, modelview[3];\n"
"DP4 result.position.x, temp2, modelview[0];\n"
"DP4 result.position.y, temp2, modelview[1];\n"
"DP4 result.position.z, temp2, modelview[2];\n"
"MOV result.color, vertex.color;\n"
"END";
/* NVIDIA drivers do a better job; let's use a simpler program if we can.
*/
const char *program_nv =
"!!ARBvp1.0"
"OPTION NV_vertex_program2;"
"ATTRIB wave = vertex.attrib[1];"
"PARAM modelview[4] = { state.matrix.mvp };"
"TEMP temp;"
"TEMP pos;"
"MOV pos, vertex.position;"
/* temp.x = sin(wave.x + pos.x / 5) */
/* temp.z = sin(wave.x + pos.z / 4) */
"MAD temp.xz, pos, {0.2, 1.0, 0.25, 1.0}, wave.x;"
"SIN temp.x, temp.x;"
"SIN temp.z, temp.z;"
/* temp.y = temp.x + temp.z */
"ADD temp.y, temp.x, temp.z;"
/* pos.y = temp.y * 2.5 */
"MUL pos.y, temp.y, 2.5;"
/* Transform the position by the modelview matrix */
"DP4 result.position.w, pos, modelview[3];"
"DP4 result.position.x, pos, modelview[0];"
"DP4 result.position.y, pos, modelview[1];"
"DP4 result.position.z, pos, modelview[2];"
"MOV result.color, vertex.color;"
"END";
void create_mesh() {
int x, z;
/* Create our mesh */
for (x = 0; x < MESH_SIZE; x++) {
for (z = 0; z < MESH_SIZE; z++) {
mesh[x][z][0] = (float) (MESH_SIZE / 2) - x;
mesh[x][z][1] = 0.0f;
mesh[x][z][2] = (float) (MESH_SIZE / 2) - z;
}
}
}
void draw_mesh() {
int x, z;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glColor4f(0.5f, 1.0f, 0.5f, 1.0f);
for (x = 0; x < MESH_SIZE - 1; x++) {
glBegin(GL_TRIANGLE_STRIP);
for (z = 0; z < MESH_SIZE - 1; z++) {
glVertexAttrib1fARB(1, wave_movement);
glVertex3fv(&mesh[x][z][0]);
glVertex3fv(&mesh[x+1][z][0]);
wave_movement += 0.00001f;
if (wave_movement > 2 * M_PI) {
wave_movement = 0.0f;
}
}
glEnd();
}
glFlush();
}
int main() {
GLuint pid;
allegro_init();
install_allegro_gl();
install_keyboard();
allegro_gl_clear_settings();
allegro_gl_set(AGL_COLOR_DEPTH, 32);
allegro_gl_set(AGL_DOUBLEBUFFER, 1);
allegro_gl_set(AGL_Z_DEPTH, 32);
allegro_gl_set(AGL_WINDOWED, TRUE);
allegro_gl_set(AGL_RENDERMETHOD, 1);
allegro_gl_set(AGL_SAMPLES, 4);
allegro_gl_set(AGL_SAMPLE_BUFFERS, 1);
allegro_gl_set(AGL_SUGGEST, AGL_COLOR_DEPTH | AGL_DOUBLEBUFFER
| AGL_RENDERMETHOD | AGL_Z_DEPTH | AGL_WINDOWED
| AGL_SAMPLES | AGL_SAMPLE_BUFFERS);
if (set_gfx_mode(GFX_OPENGL, WINDOW_W, WINDOW_H, 0, 0)) {
allegro_message("Error setting OpenGL graphics mode:\n%s\n"
"Allegro GL error : %s\n",
allegro_error, allegro_gl_error);
return -1;
}
if (allegro_gl_extensions_GL.ARB_multisample) {
glEnable(GL_MULTISAMPLE_ARB);
}
if (!allegro_gl_extensions_GL.ARB_vertex_program) {
allegro_message("This example requires a video card that supports "
" the ARB_vertex_program extension.\n");
return -1;
}
glEnable(GL_DEPTH_TEST);
glShadeModel(GL_SMOOTH);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glDisable(GL_CULL_FACE);
/* Setup projection and modelview matrices */
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0, WINDOW_W/(float)WINDOW_H, 0.1, 100.0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
/* Position the camera to look at our mesh from a distance */
gluLookAt(0.0f, 20.0f, -45.0f, 0.0f, 0.0f, 0.0f, 0, 1, 0);
create_mesh();
/* Define the vertex program */
glEnable(GL_VERTEX_PROGRAM_ARB);
glGenProgramsARB(1, &pid);
glBindProgramARB(GL_VERTEX_PROGRAM_ARB, pid);
glGetError();
if (allegro_gl_extensions_GL.NV_vertex_program2_option) {
glProgramStringARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
strlen(program_nv), program_nv);
}
else {
glProgramStringARB(GL_VERTEX_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB,
strlen(program), program);
}
/* Check for errors */
if (glGetError()) {
const char *pgm =
allegro_gl_extensions_GL.NV_vertex_program2_option
? program_nv : program;
GLint error_pos;
const GLubyte *error_str = glGetString(GL_PROGRAM_ERROR_STRING_ARB);
glGetIntegerv(GL_PROGRAM_ERROR_POSITION_ARB, &error_pos);
allegro_message("Error compiling the vertex program:\n%s\n\nat "
"character: %i\n%s\n", error_str, (int)error_pos,
pgm + error_pos);
TRACE("Error compiling the vertex program:\n%s\n\nat "
"character: %i\n%s\n", error_str, (int)error_pos,
pgm + error_pos);
return -1;
}
while (!key[KEY_ESC]) {
draw_mesh();
allegro_gl_flip();
}
glDeleteProgramsARB(1, &pid);
return 0;
}
END_OF_MAIN()
| 28.239726 | 78 | 0.604172 | [
"mesh",
"transform"
] |
e690293c1d0afa4d59ce8b0625f68ad982cff65b | 831 | h | C | ios-admin-application/LocalStorage/LSBookingStatus+CoreDataProperties.h | simplybookme-ltd/appointment-scheduling-app | fef0d023f61098259661427454b40dab0247094c | [
"Apache-2.0"
] | 15 | 2016-07-15T02:10:21.000Z | 2021-04-13T12:33:20.000Z | ios-admin-application/LocalStorage/LSBookingStatus+CoreDataProperties.h | simplybookme-ltd/appointment-scheduling-app | fef0d023f61098259661427454b40dab0247094c | [
"Apache-2.0"
] | null | null | null | ios-admin-application/LocalStorage/LSBookingStatus+CoreDataProperties.h | simplybookme-ltd/appointment-scheduling-app | fef0d023f61098259661427454b40dab0247094c | [
"Apache-2.0"
] | 3 | 2016-12-19T12:16:37.000Z | 2021-03-02T16:44:26.000Z | //
// LSBookingStatus+CoreDataProperties.h
// ios-admin-application
//
// Created by Michail Grebionkin on 24.03.16.
// Copyright © 2016 Michail Grebionkin. All rights reserved.
//
// Choose "Create NSManagedObject Subclass…" from the Core Data editor menu
// to delete and recreate this implementation file for your updated model.
//
#import "LSBookingStatus.h"
NS_ASSUME_NONNULL_BEGIN
@interface LSBookingStatus (CoreDataProperties)
@property (nullable, nonatomic, retain) NSString *statusID;
@property (nullable, nonatomic, retain) NSString *name;
@property (nullable, nonatomic, retain) NSNumber *isDefault;
@property (nullable, nonatomic, retain) NSString *hexColor;
@property (nullable, nonatomic, retain) NSNumber *searchID;
@property (nullable, nonatomic, retain) NSDate *lastUpdate;
@end
NS_ASSUME_NONNULL_END
| 29.678571 | 76 | 0.77497 | [
"model"
] |
e692793b8659b1458753e9bfade21b943b856b5e | 4,479 | h | C | display_info.h | doj/few | cdaa53b08f73a901cd07022b92e20f02e9b7b91b | [
"MIT"
] | 2 | 2015-04-05T20:15:31.000Z | 2021-07-14T19:36:03.000Z | display_info.h | doj/few | cdaa53b08f73a901cd07022b92e20f02e9b7b91b | [
"MIT"
] | null | null | null | display_info.h | doj/few | cdaa53b08f73a901cd07022b92e20f02e9b7b91b | [
"MIT"
] | null | null | null | /* -*- mode: C++; c-basic-offset: 4; tab-width: 8; -*-
* vi: set shiftwidth=4 tabstop=8:
* :indentSize=4:tabSize=8:
*/
#pragma once
#include "types.h"
#include <vector>
#include <string>
#include <memory>
class file_index;
class DisplayInfo
{
typedef lineNum_vector_t displayedLineNum_t;
displayedLineNum_t displayedLineNum;
displayedLineNum_t::iterator topLineIt;
displayedLineNum_t::iterator bottomLineIt;
public:
typedef std::shared_ptr<DisplayInfo> ptr_t;
DisplayInfo();
void assign(lineNum_vector_t&& v);
/// @return the number of lines managed by this object.
unsigned size() const { return displayedLineNum.size(); }
/**
* start an iteration over the lines.
* This function can only be called after assign() has been called.
* @return true if there are lines to display; false if there is nothing to display.
*/
bool start();
/**
* get the current line number.
* This function can only be called after start() has been called.
* @return the current line number; 0 if the current line number is not valid.
*/
line_number_t current() const;
/**
* advance to the next line.
* This function can only be called after start() has been called.
* @return true if there is a next line; false if the current line is the last line and nothing was advanced.
*/
bool next();
/**
* advance to the previous line.
* This function can only be called after start() has been called.
* @return true if there is a previous line; false if the current line is the first line and nothing was advanced.
*/
bool prev();
/**
* This function can only be called after start() has been called.
* @return the line number of the top line on the display; 0 if nothing is displayed.
*/
line_number_t topLineNum() const;
/**
* This function can only be called after start() has been called.
* @return the line number of the bottom line on the display; 0 if nothing is displayed.
*/
line_number_t bottomLineNum() const;
/**
* This function can only be called after assign() has been called.
* @return the line number of the last line managed by this object; 0 if nothing is managed.
*/
line_number_t lastLineNum() const;
/**
* position the object onto a line number.
* This function can only be called after assign() has been called.
* @return true if the line number is managed by this object; false if the line was not found.
*/
bool go_to(const line_number_t lineNum);
/**
* position the object on line_num.
* This function can only be called after assign() has been called.
* If line_num is not included in the object, position on the previous line.
*/
void go_to_approx(const line_number_t line_num);
/**
* position the object onto a line number approximately p percent into the lines.
* @param p percentage, between [0..100].
*/
void go_to_perc(unsigned p);
/**
* check if the first line is displayed.
* This function can only be called after start() has been called.
* @return true if the first line of the file is displayed.
*/
bool isFirstLineDisplayed() const;
/**
* check if the last line is displayed.
* This function can only be called after start() has been called.
* @return true if the first line of the file is displayed.
*/
bool isLastLineDisplayed() const;
/**
* move the display down one line.
* This function can only be called after start() has been called.
*/
void down();
/**
* move the display up one line.
* This function can only be called after start() has been called.
*/
void up();
/// move the display to the first line.
void top();
/**
* move the display down one page.
* The old bottom line becomes the new top line.
* This function can only be called after start() has been called.
*/
void page_down();
std::string info() const;
/**
* save the lines from fi to filename.
* @param filename a file name. The file is created if it does not exist.
* @return true if filename could be created and all lines could be written;
* false if a file error happened or fi does not contain all lines handled by this.
*/
bool save(const std::string& filename, file_index& fi);
};
| 30.889655 | 118 | 0.653494 | [
"object",
"vector"
] |
e698e661b4c9b51a0f38ae4fc212db0911e6920c | 4,367 | h | C | Engine/Interface/UIQuiz.h | openlastchaos/lastchaos-source-client | 3d88594dba7347b1bb45378136605e31f73a8555 | [
"Apache-2.0"
] | 1 | 2022-02-14T15:46:44.000Z | 2022-02-14T15:46:44.000Z | Engine/Interface/UIQuiz.h | openlastchaos/lastchaos-source-client | 3d88594dba7347b1bb45378136605e31f73a8555 | [
"Apache-2.0"
] | null | null | null | Engine/Interface/UIQuiz.h | openlastchaos/lastchaos-source-client | 3d88594dba7347b1bb45378136605e31f73a8555 | [
"Apache-2.0"
] | 2 | 2022-01-10T22:17:06.000Z | 2022-01-17T09:34:08.000Z | // ----------------------------------------------------------------------------
// File : UIQuiz.h
// Desc : Created by dongmin
// ----------------------------------------------------------------------------
#ifndef UIQUIZ_H_
#define UIQUIZ_H_
#ifdef PRAGMA_ONCE
#pragma once
#endif
// Define item slot
#define QUIZ_QUIZ_WIDTH 216
#define QUIZ_QUIZ_HEIGHT 151
#define QUIZ_TRADE_HEIGHT 75 // 98 - 23 = 75
// Column & Row
#define QUIZ_USER_SLOT_COL 5
#define QUIZ_USER_SLOT_ROW 4
#define QUIZ_USER_SLOT_ROW_TOTAL 20
#define QUIZ_USER_SLOT_MAX (QUIZ_USER_SLOT_ROW_TOTAL * QUIZ_USER_SLOT_COL)
#define QUIZ_QUIZ_SLOT_COL 5
#define QUIZ_QUIZ_SLOT_TOTAL 10
// Define text position
#define QUIZ_TITLE_TEXT_OFFSETX 25
#define QUIZ_TITLE_TEXT_OFFSETY 5
// Define size of shop
#define QUIZ_MAIN_WIDTH 216
#define QUIZ_MAIN_HEIGHT 290 // 305 - 23 = 282
// ----------------------------------------------------------------------------
// Name : CUIQuiz
// Desc :
// ----------------------------------------------------------------------------
class CUIQuiz : public CUIWindow
{
protected:
int m_nCurRow;
int m_nSelUserItemID;
int m_nSelQuizItemID;
int m_nNumOfItem;
// Region
UIRect m_rcMainTitle;
UIRect m_rcTop; // Quiz
UIRect m_rcBottom; // Trade
// Background
UIRectUV m_rtBackTop;
UIRectUV m_rtBackMiddle;
UIRectUV m_rtBackBottom;
UIRectUV m_rtBlank;
// Inventory
UIRectUV m_rtUserInven;
UIRectUV m_rtQuizInven;
UIRectUV m_rtSeperatorInven;
// Item Info
UIRectUV m_rtInfoUL; // UV of upper left region of information
UIRectUV m_rtInfoUM; // UV of upper middle region of information
UIRectUV m_rtInfoUR; // UV of upper right region of information
UIRectUV m_rtInfoML; // UV of middle left region of information
UIRectUV m_rtInfoMM; // UV of middle middle region of information
UIRectUV m_rtInfoMR; // UV of middle right region of information
UIRectUV m_rtInfoLL; // UV of lower left region of information
UIRectUV m_rtInfoLM; // UV of lower middle region of information
UIRectUV m_rtInfoLR; // UV of lower right region of information
UIRectUV m_rtUnmovableOutline; // UV of outline of unmovable items
UIRectUV m_rtSelectOutline; // UV of outline of selected items
BOOL m_bShowItemInfo; // If item tool tip is shown or not
BOOL m_bDetailItemInfo; // If item informaion is shown in detail or not
int m_nCurInfoLines; // Count of current item information lines
CTString m_strItemInfo[MAX_ITEMINFO_LINE]; // Item information string
COLOR m_colItemInfo[MAX_ITEMINFO_LINE]; // Color of item information string
UIRect m_rcItemInfo; // Item information region
// Buttons
CUIButton m_btnClose; // Close button of Quiz
CUIButton m_btnOK; // Sell button of Quiz
CUIButton m_btnCancel; // Cancel button of Quiz
CUIScrollBar m_sbScrollBar; // Scroll bar of inventory
public:
// Items
CUIButtonEx m_abtnQuizItems[QUIZ_QUIZ_SLOT_TOTAL]; // Trade Slot items
CUIButtonEx m_abtnUserItems[QUIZ_USER_SLOT_MAX]; // Quiz Slot items
public:
CUIQuiz();
~CUIQuiz();
// Create
void Create( CUIWindow *pParentWnd, int nX, int nY, int nWidth, int nHeight );
void OpenQuiz( );
// Render
void Render();
// Adjust position
void ResetPosition( PIX pixMinI, PIX pixMinJ, PIX pixMaxI, PIX pixMaxJ );
void AdjustPosition( PIX pixMinI, PIX pixMinJ, PIX pixMaxI, PIX pixMaxJ );
// Clear
void ClearItems();
void RefreshPlayerItem();
void ResetQuiz();
// Messages
WMSG_RESULT MouseMessage( MSG *pMsg );
protected:
// Internal functions
void AddItemInfoString( CTString &strItemInfo, COLOR colItemInfo = 0xF2F2F2FF );
BOOL GetItemInfo( int nWhichSlot, int &nInfoWidth, int &nInfoHeight,
int nTradeItem = -1, int inven_idx = -1 );
void ShowItemInfo( BOOL bShowInfo, BOOL bRenew = FALSE, int nTradeItem = -1, int inven_idx = -1 );
void RenderItems();
void QuizToUser( SQUAD llCount );
void UserToQuiz( SQUAD llCount );
void PrepareUserItems();
// Command functions
void AddQuizItem( int nIdx, int nUniIndex, SQUAD llCount );
void DelQuizItem( int nIdx, int nUniIndex, SQUAD llCount, int nTradeItemID );
void SendBingo();
};
#endif // UIQUIZ_H_
| 32.348148 | 99 | 0.660408 | [
"render"
] |
e6a4627e3ded5fe0203fb372d685b4d6c10d48bf | 726 | h | C | src/context.h | XujieSi/fse18-artifact-183 | 29cf14b5072fdfb1786eaaf60e9ac6e75f932d74 | [
"MIT"
] | 6 | 2018-11-01T23:15:38.000Z | 2022-02-17T09:37:44.000Z | src/context.h | XujieSi/fse18-artifact-183 | 29cf14b5072fdfb1786eaaf60e9ac6e75f932d74 | [
"MIT"
] | null | null | null | src/context.h | XujieSi/fse18-artifact-183 | 29cf14b5072fdfb1786eaaf60e9ac6e75f932d74 | [
"MIT"
] | 1 | 2018-11-01T23:15:41.000Z | 2018-11-01T23:15:41.000Z | #ifndef CONTEXT_H
#define CONTEXT_H
#include "template.h"
#include <vector>
#include <set>
#include <map>
#include <z3++.h>
namespace ALPS {
struct EDBValue {
};
struct ContextManager{
z3::context C;
int MaxBits;
std::map<TypeInfo, z3::sort> sortMap;
std::map<Relation, z3::func_decl> funcMap;
std::map<Relation, std::set<std::vector<unsigned int>>> EDBFacts;
void buildSorts(TypeInfo* TArr, int N);
void buildFuncDecls(Relation* RArr, int N);
void updateFuncDecls(Relation r);
void loadEDBFacts(Relation* RArr, int N);
void appendEDBConstr(Z3_fixedpoint& fp) ;
void expandEDBWithKnownFacts(std::map<Relation, std::set<std::vector<unsigned int>>>&);
};
} // end of namepsace ALPS
#endif
| 14.235294 | 89 | 0.703857 | [
"vector"
] |
e6b2102657b784174c063c118d5f4cb4e0d16fe8 | 3,616 | h | C | TongueQT/TongueQT/src/Vega/libraries/isotropicHyperelasticFEM/isotropicHyperelasticFEMMT.h | lrkk1234/TongueSimulation | 347cf38452aa62d1173da1c4935f691456255e46 | [
"MIT"
] | 2 | 2020-03-28T03:15:49.000Z | 2020-09-09T02:54:33.000Z | TongueQT/TongueQT/src/Vega/libraries/isotropicHyperelasticFEM/isotropicHyperelasticFEMMT.h | lrkk1234/TongueSimulation | 347cf38452aa62d1173da1c4935f691456255e46 | [
"MIT"
] | null | null | null | TongueQT/TongueQT/src/Vega/libraries/isotropicHyperelasticFEM/isotropicHyperelasticFEMMT.h | lrkk1234/TongueSimulation | 347cf38452aa62d1173da1c4935f691456255e46 | [
"MIT"
] | 2 | 2020-09-08T19:28:19.000Z | 2021-07-25T00:35:26.000Z | /*************************************************************************
* *
* Vega FEM Simulation Library Version 2.2 *
* *
* "isotropic hyperelastic FEM" library , Copyright (C) 2015 USC *
* All rights reserved. *
* *
* Code authors: Jernej Barbic, Fun Shing Sin *
* http://www.jernejbarbic.com/code *
* *
* Research: Jernej Barbic, Fun Shing Sin, Daniel Schroeder, *
* Doug L. James, Jovan Popovic *
* *
* Funding: National Science Foundation, Link Foundation, *
* Singapore-MIT GAMBIT Game Lab, *
* Zumberge Research and Innovation Fund at USC *
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the BSD-style license that is *
* included with this library in the file LICENSE.txt *
* *
* 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 file *
* LICENSE.TXT for more details. *
* *
*************************************************************************/
#ifndef _ISOTROPICHYPERELASTICFEMMT_H_
#define _ISOTROPICHYPERELASTICFEMMT_H_
#include "isotropicHyperelasticFEM.h"
/*
This class is a multi-threaded version of the class "IsotropicHyperelasticFEM".
It uses POSIX threads ("pthreads") as the threading API.
Each thread assembles the internal force with respect to a subset of all the mesh elements.
At the end, the individual results are added into a global internal force vector.
See also "isotropicHyperelasticFEM.h".
*/
class IsotropicHyperelasticFEMMT : public IsotropicHyperelasticFEM
{
public:
// see "isotropicHyperelasticFEM.h" for usage
// numThreads is the number of threads to use for the computation
IsotropicHyperelasticFEMMT(TetMesh * tetMesh, IsotropicMaterial * isotropicMaterial, double principalStretchThreshold=-DBL_MAX, bool addGravity=false, double g=9.81, int numThreads=1);
virtual ~IsotropicHyperelasticFEMMT();
// Computes strain energy, internal forces, and/or tangent stiffness matrix, as requested by computationMode. It returns 0 on success, and non-zero on failure.
// this is an advanced function; you normally do not need to use it
virtual int GetEnergyAndForceAndTangentStiffnessMatrixHelper(double * u, double * energy, double * internalForces, SparseMatrix * tangentStiffnessMatrix, int computationMode);
int GetStartElement(int rank);
int GetEndElement(int rank);
protected:
int numThreads;
int * startElement, * endElement;
double * energyBuffer;
double * internalForceBuffer;
SparseMatrix ** tangentStiffnessMatrixBuffer;
void Initialize();
};
#endif
| 51.657143 | 186 | 0.527931 | [
"mesh",
"vector"
] |
e6ba244379d1da9b64173cfeb1cfb0010ab73dff | 1,891 | h | C | include/roman.h | MarkKoz/cs-236 | 341f3c2d4d1f88ae95e6276982d899822626d2c7 | [
"MIT"
] | null | null | null | include/roman.h | MarkKoz/cs-236 | 341f3c2d4d1f88ae95e6276982d899822626d2c7 | [
"MIT"
] | null | null | null | include/roman.h | MarkKoz/cs-236 | 341f3c2d4d1f88ae95e6276982d899822626d2c7 | [
"MIT"
] | null | null | null | #ifndef CS_236_ROMAN_H
#define CS_236_ROMAN_H
#include <string>
#include <unordered_map>
/**
* @brief Represents a Roman numeral value.
*
* Roman numerals have 7 digits, which have the following values:
* - M: 1000
* - D: 500
* - C: 100
* - L: 50
* - X: 10
* - V: 5
* - I: 1
*
* A larger numeral preceding a smaller numeral means addition.
* A smaller numeral preceding a larger numeral means subtraction.
*/
class romanType
{
public:
/**
* @brief Construct a @c romanType from a string.
*
* Copy the string into the new object and then convert it to an integer.
*
* @param value The string representing the Roman numeral value.
*
* @throw std::invalid_argument The roman numeral is empty or contains an invalid character.
*/
explicit romanType(const std::string& value);
/**
* @brief Construct a @c romanType from a string.
*
* Move the string into the new object and then convert it to an integer.
*
* @param value The string representing the Roman numeral value.
*
* @throw std::invalid_argument The roman numeral is empty or contains an invalid character.
*/
explicit romanType(std::string&& value);
/**
* @brief Print the underlying value using Arabic numerals.
*/
void print_arabic() const;
/**
* @brief Print the underlying value using Roman numerals.
*/
void print_roman() const;
private:
/**
* @brief Convert the Roman numeral to an integer.
*
* @throw std::invalid_argument The roman numeral is empty or contains an invalid character.
* @return The integer representation of the Roman numeral.
*/
[[nodiscard]] unsigned int to_integer() const;
std::string roman_numeral_;
unsigned int arabic_numeral_;
static const std::unordered_map<char, unsigned int> ROMAN_TO_ARABIC;
};
#endif
| 25.90411 | 96 | 0.662084 | [
"object"
] |
e4b77b671f1a0067081d23c81e49bf626468b7d4 | 8,722 | h | C | numpy/core/src/common/simd/sse/math.h | sukritingupta/numpy | 2c44c93164c274a5865799eefd3e401effa948a9 | [
"BSD-3-Clause"
] | 2 | 2022-01-20T18:13:17.000Z | 2022-03-25T04:30:01.000Z | numpy/core/src/common/simd/sse/math.h | sukritingupta/numpy | 2c44c93164c274a5865799eefd3e401effa948a9 | [
"BSD-3-Clause"
] | 8 | 2021-10-07T10:59:49.000Z | 2021-11-22T20:06:49.000Z | numpy/core/src/common/simd/sse/math.h | sukritingupta/numpy | 2c44c93164c274a5865799eefd3e401effa948a9 | [
"BSD-3-Clause"
] | 1 | 2022-03-22T11:47:01.000Z | 2022-03-22T11:47:01.000Z | #ifndef NPY_SIMD
#error "Not a standalone header"
#endif
#ifndef _NPY_SIMD_SSE_MATH_H
#define _NPY_SIMD_SSE_MATH_H
/***************************
* Elementary
***************************/
// Square root
#define npyv_sqrt_f32 _mm_sqrt_ps
#define npyv_sqrt_f64 _mm_sqrt_pd
// Reciprocal
NPY_FINLINE npyv_f32 npyv_recip_f32(npyv_f32 a)
{ return _mm_div_ps(_mm_set1_ps(1.0f), a); }
NPY_FINLINE npyv_f64 npyv_recip_f64(npyv_f64 a)
{ return _mm_div_pd(_mm_set1_pd(1.0), a); }
// Absolute
NPY_FINLINE npyv_f32 npyv_abs_f32(npyv_f32 a)
{
return _mm_and_ps(
a, _mm_castsi128_ps(_mm_set1_epi32(0x7fffffff))
);
}
NPY_FINLINE npyv_f64 npyv_abs_f64(npyv_f64 a)
{
return _mm_and_pd(
a, _mm_castsi128_pd(npyv_setall_s64(0x7fffffffffffffffLL))
);
}
// Square
NPY_FINLINE npyv_f32 npyv_square_f32(npyv_f32 a)
{ return _mm_mul_ps(a, a); }
NPY_FINLINE npyv_f64 npyv_square_f64(npyv_f64 a)
{ return _mm_mul_pd(a, a); }
// Maximum, natively mapping with no guarantees to handle NaN.
#define npyv_max_f32 _mm_max_ps
#define npyv_max_f64 _mm_max_pd
// Maximum, supports IEEE floating-point arithmetic (IEC 60559),
// - If one of the two vectors contains NaN, the equivalent element of the other vector is set
// - Only if both corresponded elements are NaN, NaN is set.
NPY_FINLINE npyv_f32 npyv_maxp_f32(npyv_f32 a, npyv_f32 b)
{
__m128 nn = _mm_cmpord_ps(b, b);
__m128 max = _mm_max_ps(a, b);
return npyv_select_f32(_mm_castps_si128(nn), max, a);
}
NPY_FINLINE npyv_f64 npyv_maxp_f64(npyv_f64 a, npyv_f64 b)
{
__m128d nn = _mm_cmpord_pd(b, b);
__m128d max = _mm_max_pd(a, b);
return npyv_select_f64(_mm_castpd_si128(nn), max, a);
}
// Maximum, integer operations
#ifdef NPY_HAVE_SSE41
#define npyv_max_s8 _mm_max_epi8
#define npyv_max_u16 _mm_max_epu16
#define npyv_max_u32 _mm_max_epu32
#define npyv_max_s32 _mm_max_epi32
#else
NPY_FINLINE npyv_s8 npyv_max_s8(npyv_s8 a, npyv_s8 b)
{
return npyv_select_s8(npyv_cmpgt_s8(a, b), a, b);
}
NPY_FINLINE npyv_u16 npyv_max_u16(npyv_u16 a, npyv_u16 b)
{
return npyv_select_u16(npyv_cmpgt_u16(a, b), a, b);
}
NPY_FINLINE npyv_u32 npyv_max_u32(npyv_u32 a, npyv_u32 b)
{
return npyv_select_u32(npyv_cmpgt_u32(a, b), a, b);
}
NPY_FINLINE npyv_s32 npyv_max_s32(npyv_s32 a, npyv_s32 b)
{
return npyv_select_s32(npyv_cmpgt_s32(a, b), a, b);
}
#endif
#define npyv_max_u8 _mm_max_epu8
#define npyv_max_s16 _mm_max_epi16
NPY_FINLINE npyv_u64 npyv_max_u64(npyv_u64 a, npyv_u64 b)
{
return npyv_select_u64(npyv_cmpgt_u64(a, b), a, b);
}
NPY_FINLINE npyv_s64 npyv_max_s64(npyv_s64 a, npyv_s64 b)
{
return npyv_select_s64(npyv_cmpgt_s64(a, b), a, b);
}
// Minimum, natively mapping with no guarantees to handle NaN.
#define npyv_min_f32 _mm_min_ps
#define npyv_min_f64 _mm_min_pd
// Minimum, supports IEEE floating-point arithmetic (IEC 60559),
// - If one of the two vectors contains NaN, the equivalent element of the other vector is set
// - Only if both corresponded elements are NaN, NaN is set.
NPY_FINLINE npyv_f32 npyv_minp_f32(npyv_f32 a, npyv_f32 b)
{
__m128 nn = _mm_cmpord_ps(b, b);
__m128 min = _mm_min_ps(a, b);
return npyv_select_f32(_mm_castps_si128(nn), min, a);
}
NPY_FINLINE npyv_f64 npyv_minp_f64(npyv_f64 a, npyv_f64 b)
{
__m128d nn = _mm_cmpord_pd(b, b);
__m128d min = _mm_min_pd(a, b);
return npyv_select_f64(_mm_castpd_si128(nn), min, a);
}
// Minimum, integer operations
#ifdef NPY_HAVE_SSE41
#define npyv_min_s8 _mm_min_epi8
#define npyv_min_u16 _mm_min_epu16
#define npyv_min_u32 _mm_min_epu32
#define npyv_min_s32 _mm_min_epi32
#else
NPY_FINLINE npyv_s8 npyv_min_s8(npyv_s8 a, npyv_s8 b)
{
return npyv_select_s8(npyv_cmplt_s8(a, b), a, b);
}
NPY_FINLINE npyv_u16 npyv_min_u16(npyv_u16 a, npyv_u16 b)
{
return npyv_select_u16(npyv_cmplt_u16(a, b), a, b);
}
NPY_FINLINE npyv_u32 npyv_min_u32(npyv_u32 a, npyv_u32 b)
{
return npyv_select_u32(npyv_cmplt_u32(a, b), a, b);
}
NPY_FINLINE npyv_s32 npyv_min_s32(npyv_s32 a, npyv_s32 b)
{
return npyv_select_s32(npyv_cmplt_s32(a, b), a, b);
}
#endif
#define npyv_min_u8 _mm_min_epu8
#define npyv_min_s16 _mm_min_epi16
NPY_FINLINE npyv_u64 npyv_min_u64(npyv_u64 a, npyv_u64 b)
{
return npyv_select_u64(npyv_cmplt_u64(a, b), a, b);
}
NPY_FINLINE npyv_s64 npyv_min_s64(npyv_s64 a, npyv_s64 b)
{
return npyv_select_s64(npyv_cmplt_s64(a, b), a, b);
}
// round to nearest integer even
NPY_FINLINE npyv_f32 npyv_rint_f32(npyv_f32 a)
{
#ifdef NPY_HAVE_SSE41
return _mm_round_ps(a, _MM_FROUND_TO_NEAREST_INT);
#else
const npyv_f32 szero = _mm_set1_ps(-0.0f);
__m128i roundi = _mm_cvtps_epi32(a);
__m128i overflow = _mm_cmpeq_epi32(roundi, _mm_castps_si128(szero));
__m128 r = _mm_cvtepi32_ps(roundi);
// respect sign of zero
r = _mm_or_ps(r, _mm_and_ps(a, szero));
return npyv_select_f32(overflow, a, r);
#endif
}
// round to nearest integer even
NPY_FINLINE npyv_f64 npyv_rint_f64(npyv_f64 a)
{
#ifdef NPY_HAVE_SSE41
return _mm_round_pd(a, _MM_FROUND_TO_NEAREST_INT);
#else
const npyv_f64 szero = _mm_set1_pd(-0.0);
const npyv_f64 two_power_52 = _mm_set1_pd(0x10000000000000);
npyv_f64 sign_two52 = _mm_or_pd(two_power_52, _mm_and_pd(a, szero));
// round by add magic number 2^52
npyv_f64 round = _mm_sub_pd(_mm_add_pd(a, sign_two52), sign_two52);
// respect signed zero, e.g. -0.5 -> -0.0
return _mm_or_pd(round, _mm_and_pd(a, szero));
#endif
}
// ceil
#ifdef NPY_HAVE_SSE41
#define npyv_ceil_f32 _mm_ceil_ps
#define npyv_ceil_f64 _mm_ceil_pd
#else
NPY_FINLINE npyv_f32 npyv_ceil_f32(npyv_f32 a)
{
const npyv_f32 szero = _mm_set1_ps(-0.0f);
const npyv_f32 one = _mm_set1_ps(1.0f);
npyv_s32 roundi = _mm_cvttps_epi32(a);
npyv_f32 round = _mm_cvtepi32_ps(roundi);
npyv_f32 ceil = _mm_add_ps(round, _mm_and_ps(_mm_cmplt_ps(round, a), one));
// respect signed zero, e.g. -0.5 -> -0.0
npyv_f32 rzero = _mm_or_ps(ceil, _mm_and_ps(a, szero));
// if overflow return a
return npyv_select_f32(_mm_cmpeq_epi32(roundi, _mm_castps_si128(szero)), a, rzero);
}
NPY_FINLINE npyv_f64 npyv_ceil_f64(npyv_f64 a)
{
const npyv_f64 szero = _mm_set1_pd(-0.0);
const npyv_f64 one = _mm_set1_pd(1.0);
const npyv_f64 two_power_52 = _mm_set1_pd(0x10000000000000);
npyv_f64 sign_two52 = _mm_or_pd(two_power_52, _mm_and_pd(a, szero));
// round by add magic number 2^52
npyv_f64 round = _mm_sub_pd(_mm_add_pd(a, sign_two52), sign_two52);
npyv_f64 ceil = _mm_add_pd(round, _mm_and_pd(_mm_cmplt_pd(round, a), one));
// respect signed zero, e.g. -0.5 -> -0.0
return _mm_or_pd(ceil, _mm_and_pd(a, szero));
}
#endif
// trunc
#ifdef NPY_HAVE_SSE41
#define npyv_trunc_f32(A) _mm_round_ps(A, _MM_FROUND_TO_ZERO)
#define npyv_trunc_f64(A) _mm_round_pd(A, _MM_FROUND_TO_ZERO)
#else
NPY_FINLINE npyv_f32 npyv_trunc_f32(npyv_f32 a)
{
const npyv_f32 szero = _mm_set1_ps(-0.0f);
npyv_s32 roundi = _mm_cvttps_epi32(a);
npyv_f32 trunc = _mm_cvtepi32_ps(roundi);
// respect signed zero, e.g. -0.5 -> -0.0
npyv_f32 rzero = _mm_or_ps(trunc, _mm_and_ps(a, szero));
// if overflow return a
return npyv_select_f32(_mm_cmpeq_epi32(roundi, _mm_castps_si128(szero)), a, rzero);
}
NPY_FINLINE npyv_f64 npyv_trunc_f64(npyv_f64 a)
{
const npyv_f64 szero = _mm_set1_pd(-0.0);
const npyv_f64 one = _mm_set1_pd(1.0);
const npyv_f64 two_power_52 = _mm_set1_pd(0x10000000000000);
npyv_f64 abs_a = npyv_abs_f64(a);
// round by add magic number 2^52
npyv_f64 abs_round = _mm_sub_pd(_mm_add_pd(abs_a, two_power_52), two_power_52);
npyv_f64 subtrahend = _mm_and_pd(_mm_cmpgt_pd(abs_round, abs_a), one);
return _mm_or_pd(_mm_sub_pd(abs_round, subtrahend), _mm_and_pd(a, szero));
}
#endif
// floor
#ifdef NPY_HAVE_SSE41
#define npyv_floor_f32 _mm_floor_ps
#define npyv_floor_f64 _mm_floor_pd
#else
NPY_FINLINE npyv_f32 npyv_floor_f32(npyv_f32 a)
{
const npyv_f32 one = _mm_set1_ps(1.0f);
npyv_f32 round = npyv_rint_f32(a);
return _mm_sub_ps(round, _mm_and_ps(_mm_cmpgt_ps(round, a), one));
}
NPY_FINLINE npyv_f64 npyv_floor_f64(npyv_f64 a)
{
const npyv_f64 one = _mm_set1_pd(1.0);
npyv_f64 round = npyv_rint_f64(a);
return _mm_sub_pd(round, _mm_and_pd(_mm_cmpgt_pd(round, a), one));
}
#endif // NPY_HAVE_SSE41
#endif // _NPY_SIMD_SSE_MATH_H
| 33.937743 | 94 | 0.707751 | [
"vector"
] |
e4bd63a5790e405d097b9c0b9d6a08f44d145a38 | 4,469 | c | C | examples/nonlocaldiffusion.c | ikaroruan/FastTransforms | 3e32663b814bfa789a9e25aab180e31c36df0d5e | [
"MIT"
] | 36 | 2018-05-05T04:01:23.000Z | 2022-01-01T00:27:31.000Z | examples/nonlocaldiffusion.c | ikaroruan/FastTransforms | 3e32663b814bfa789a9e25aab180e31c36df0d5e | [
"MIT"
] | 51 | 2018-06-28T15:01:52.000Z | 2021-09-09T15:53:04.000Z | examples/nonlocaldiffusion.c | ikaroruan/FastTransforms | 3e32663b814bfa789a9e25aab180e31c36df0d5e | [
"MIT"
] | 9 | 2018-06-11T15:21:32.000Z | 2022-01-28T21:29:14.000Z | #include <fasttransforms.h>
#include <ftutilities.h>
void oprec(const int n, double * v, const double alpha, const double delta2) {
if (n > 0)
v[0] = 1;
if (n > 1)
v[1] = (4*alpha+8-(alpha+4)*delta2)/4;
for (int i = 1; i < n-1; i++)
v[i+1] = (((2*i+alpha+2)*(2*i+alpha+4)+alpha*(alpha+2))/(2*(i+1)*(2*i+alpha+2))*(2*i+alpha+3)/(i+alpha+3) - delta2/4*(2*i+alpha+3)/(i+1)*(2*i+alpha+4)/(i+alpha+3))*v[i] - (i+alpha+1)/(i+alpha+3)*(2*i+alpha+4)/(2*i+alpha+2)*v[i-1];
}
/*!
\example nonlocaldiffusion.c
This example calculates the spectrum of the nonlocal diffusion operator:
\f[
\mathcal{L}_\delta u = \int_{\mathbb{S}^2} \rho_\delta(|\mathbf{x}-\mathbf{y}|)\left[u(\mathbf{x}) - u(\mathbf{y})\right] \,\mathrm{d}\Omega(\mathbf{y}),
\f]
defined in Eq. (2) of
R. M. Slevinsky, H. Montanelli, and Q. Du, [A spectral method for nonlocal diffusion operators on the sphere](https://doi.org/10.1016/j.jcp.2018.06.024), *J. Comp. Phys.*, **372**:893--911, 2018.
In the above, \f$0<\delta<2\f$, \f$-1<\alpha<1\f$, and the kernel:
\f[
\rho_\delta(|\mathbf{x}-\mathbf{y}|) = \frac{4(1+\alpha)}{\pi \delta^{2+2\alpha}} \frac{\chi_{[0,\delta]}(|\mathbf{x}-\mathbf{y}|)}{|\mathbf{x}-\mathbf{y}|^{2-2\alpha}},
\f]
where \f$\chi_I(\cdot)\f$ is the indicator function on the set \f$I\f$.
This nonlocal operator is diagonalized by spherical harmonics:
\f[
\mathcal{L}_\delta Y_\ell^m(\mathbf{x}) = \lambda_\ell(\alpha, \delta) Y_\ell^m(\mathbf{x}),
\f]
and its eigenfunctions are given by the generalized Funk--Hecke formula:
\f[
\lambda_\ell(\alpha, \delta) = \frac{(1+\alpha) 2^{2+\alpha}}{\delta^{2+2\alpha}}\int_{1-\delta^2/2}^1 \left[P_\ell(t)-1\right] (1-t)^{\alpha-1} \,\mathrm{d} t.
\f]
In the paper, the authors use Clenshaw--Curtis quadrature and asymptotic evaluation of Legendre polynomials to achieve \f$\mathcal{O}(n^2\log n)\f$ complexity for the evaluation of the first \f$n\f$ eigenvalues. With a change of basis, this complexity can be reduced to \f$\mathcal{O}(n\log n)\f$.
First, we represent:
\f[
P_n(t) - 1 = \sum_{j=0}^{n-1} \left[P_{j+1}(t) - P_j(t)\right] = -\sum_{j=0}^{n-1} (1-t) P_j^{(1,0)}(t).
\f]
Then, we represent \f$P_j^{(1,0)}(t)\f$ with Jacobi polynomials \f$P_i^{(\alpha,0)}(t)\f$ and we integrate using [DLMF 18.9.16](https://dlmf.nist.gov/18.9.16):
\f[
\int_x^1 P_i^{(\alpha,0)}(t)(1-t)^\alpha\,\mathrm{d}t = \left\{ \begin{array}{cc} \frac{(1-x)^{\alpha+1}}{\alpha+1} & \mathrm{for~}i=0,\\ \frac{1}{2i}(1-x)^{\alpha+1}(1+x)P_{i-1}^{(\alpha+1,1)}(x), & \mathrm{for~}i>0.\end{array}\right.
\f]
The code below implements this algorithm, making use of the Jacobi--Jacobi transform \ref ft_plan_jacobi_to_jacobi.
For numerical stability, the conversion from Jacobi polynomials \f$P_j^{(1,0)}(t)\f$ to \f$P_i^{(\alpha,0)}(t)\f$ is divided into conversion from \f$P_j^{(1,0)}(t)\f$ to \f$P_k^{(0,0)}(t)\f$, before conversion from \f$P_k^{(0,0)}(t)\f$ to \f$P_i^{(\alpha,0)}(t)\f$.
*/
int main(void) {
printf("This example calculates the spectrum of the nonlocal diffusion\n");
printf("operator defined in Eq. (2) of\n");
printf("\t"MAGENTA("R. M. Slevinsky, H. Montanelli, and Q. Du, A spectral method for")"\n");
printf("\t"MAGENTA("nonlocal diffusion operators on the sphere, J. Comp. Phys.,")"\n");
printf("\t"MAGENTA("372:893--911, 2018.")"\n");
printf("Please see "CYAN("https://doi.org/10.1016/j.jcp.2018.06.024")" and\n");
printf("the online documentation for further details.\n");
char * FMT = "%17.16e";
int n = 11;
double alpha = -0.5, delta = 0.025;
double delta2 = delta*delta;
double scl = (1+alpha)*(2-delta2/2);
printf("\n"MAGENTA("n = %i")", "MAGENTA("α = %1.3f")", and "MAGENTA("δ = %1.3f")".\n", n, alpha, delta);
double lambda[n];
if (n > 0)
lambda[0] = 0;
if (n > 1)
lambda[1] = -2;
oprec(n-2, lambda+2, alpha, delta2);
for (int i = 2; i < n; i++)
lambda[i] *= -scl/(i-1);
ft_tb_eigen_FMM * P = ft_plan_jacobi_to_jacobi(0, 0, n-1, 0, 0, alpha, 0);
ft_bfmv('T', P, lambda+1);
for (int i = 2; i < n; i++)
lambda[i] = ((2*i-1)*lambda[i] + (i-1)*lambda[i-1])/i;
for (int i = 2; i < n; i++)
lambda[i] += lambda[i-1];
printf("The spectrum, "MAGENTA("0 ≤ ℓ < %i")", ", n);
printmat(MAGENTA("λ_ℓ(α,δ)"), FMT, lambda, n, 1);
printf("\n");
ft_destroy_tb_eigen_FMM(P);
return 0;
}
| 46.072165 | 299 | 0.593198 | [
"transform"
] |
e4ce94a403ef84a38fab3bcc904054e9c52a1433 | 1,168 | h | C | shape.h | somyungoh/volume-modeling-rendering | 1d0f0009eec4cf6cf3d69b74289b08076a58eaef | [
"MIT"
] | 1 | 2018-11-16T16:20:59.000Z | 2018-11-16T16:20:59.000Z | shape.h | somyungoh/volume-modeling-rendering | 1d0f0009eec4cf6cf3d69b74289b08076a58eaef | [
"MIT"
] | null | null | null | shape.h | somyungoh/volume-modeling-rendering | 1d0f0009eec4cf6cf3d69b74289b08076a58eaef | [
"MIT"
] | null | null | null | #ifndef _SM_FIELD_OBJECT_H_
#define _SM_FIELD_OBJECT_H_
/*********************************************************************
*
* shape.h
*
* This class plays as an 'Obeject', which contains
* ALL FIELDS one each. It will be used when building shapes
*
*********************************************************************/
#include "field.h"
#include "grid.h"
#include "transform.h"
class shape{
public:
// constructors
shape();
shape(const color &baseColor);
~shape();
// getter, setters
void setScalarField(fieldScalarPtr sf);
///void setVectorField(fieldVectorPtr vf);
///void setMatrixField(fieldMatrixPtr mf);
fieldScalarPtr getScalarField() const;
fieldVectorPtr getVectorField() const;
fieldMatrixPtr getMatrixField() const;
fieldScalarPtr getScalarGrid() const;
color Color() const;
// transforms
void translate(const vec3 &dx);
void scale(const vec3 &s);
void rotate(const vec3 &axis, float angle);
private:
// vectors of fields
fieldScalarPtr scalarField;
///fieldVectorPtr vectorField;
///fieldMatrixPtr matrixField;
color baseColor;
};
#endif // !_SM_FIELD_OBJECT_H_
| 23.836735 | 71 | 0.621575 | [
"shape",
"transform"
] |
e4d2938a174ec28544a402e707e9259b39920a3a | 84,642 | c | C | minix/drivers/storage/ahci/ahci.c | calmsacibis995/minix | dfba95598f553b6560131d35a76658f1f8c9cf38 | [
"Unlicense"
] | null | null | null | minix/drivers/storage/ahci/ahci.c | calmsacibis995/minix | dfba95598f553b6560131d35a76658f1f8c9cf38 | [
"Unlicense"
] | null | null | null | minix/drivers/storage/ahci/ahci.c | calmsacibis995/minix | dfba95598f553b6560131d35a76658f1f8c9cf38 | [
"Unlicense"
] | null | null | null | /* Advanced Host Controller Interface (AHCI) driver, by D.C. van Moolenbroek
* - Multithreading support by Arne Welzel
* - Native Command Queuing support by Raja Appuswamy
*/
/*
* This driver is based on the following specifications:
* - Serial ATA Advanced Host Controller Interface (AHCI) 1.3
* - Serial ATA Revision 2.6
* - AT Attachment with Packet Interface 7 (ATA/ATAPI-7)
* - ATAPI Removable Rewritable Media Devices 1.3 (SFF-8070)
*
* The driver supports device hot-plug, active device status tracking,
* nonremovable ATA and removable ATAPI devices, custom logical sector sizes,
* sector-unaligned reads, native command queuing and parallel requests to
* different devices.
*
* It does not implement transparent failure recovery, power management, or
* port multiplier support.
*/
/*
* An AHCI controller exposes a number of ports (up to 32), each of which may
* or may not have one device attached (port multipliers are not supported).
* Each port is maintained independently.
*
* The following figure depicts the possible transitions between port states.
* The NO_PORT state is not included; no transitions can be made from or to it.
*
* +----------+ +----------+
* | SPIN_UP | ------+ +-----> | BAD_DEV | ------------------+
* +----------+ | | +----------+ |
* | | | ^ |
* v v | | |
* +----------+ +----------+ +----------+ +----------+ |
* | NO_DEV | --> | WAIT_DEV | --> | WAIT_ID | --> | GOOD_DEV | |
* +----------+ +----------+ +----------+ +----------+ |
* ^ | | | |
* +----------------+----------------+----------------+--------+
*
* At driver startup, all physically present ports are put in SPIN_UP state.
* This state differs from NO_DEV in that BDEV_OPEN calls will be deferred
* until either the spin-up timer expires, or a device has been identified on
* that port. This prevents early BDEV_OPEN calls from failing erroneously at
* startup time if the device has not yet been able to announce its presence.
*
* If a device is detected, either at startup time or after hot-plug, its
* signature is checked and it is identified, after which it may be determined
* to be a usable ("good") device, which means that the device is considered to
* be in a working state. If these steps fail, the device is marked as unusable
* ("bad"). At any point in time, the device may be disconnected; the port is
* then put back into NO_DEV state.
*
* A device in working state (GOOD_DEV) may or may not have a medium. All ATA
* devices are assumed to be fixed; all ATAPI devices are assumed to have
* removable media. To prevent erroneous access to switched devices and media,
* the driver makes devices inaccessible until they are fully closed (the open
* count is zero) when a device (hot-plug) or medium change is detected.
* For hot-plug changes, access is prevented by setting the BARRIER flag until
* the device is fully closed and then reopened. For medium changes, access is
* prevented by not acknowledging the medium change until the device is fully
* closed and reopened. Removable media are not locked in the drive while
* opened, because the driver author is uncomfortable with that concept.
*
* Ports may leave the group of states where a device is connected (that is,
* WAIT_ID, GOOD_DEV, and BAD_DEV) in two ways: either due to a hot-unplug
* event, or due to a hard reset after a serious failure. For simplicity, we
* we perform a hard reset after a hot-unplug event as well, so that the link
* to the device is broken. Thus, in both cases, a transition to NO_DEV is
* made, after which the link to the device may or may not be reestablished.
* In both cases, ongoing requests are cancelled and the BARRIER flag is set.
*
* The following table lists for each state, whether the port is started
* (PxCMD.ST is set), whether a timer is running, what the PxIE mask is to be
* set to, and what BDEV_OPEN calls on this port should return.
*
* State Started Timer PxIE BDEV_OPEN
* --------- --------- --------- --------- ---------
* NO_PORT no no (none) ENXIO
* SPIN_UP no yes PCE (wait)
* NO_DEV no no PCE ENXIO
* WAIT_DEV no yes PCE (wait)
* BAD_DEV no no PRCE ENXIO
* WAIT_ID yes yes PRCE+ (wait)
* GOOD_DEV yes per-command PRCE+ OK
*
* In order to continue deferred BDEV_OPEN calls, the BUSY flag must be unset
* when changing from SPIN_UP to any state but WAIT_DEV, and when changing from
* WAIT_DEV to any state but WAIT_ID, and when changing from WAIT_ID to any
* other state.
*/
/*
* The maximum byte size of a single transfer (MAX_TRANSFER) is currently set
* to 4MB. This limit has been chosen for a number of reasons:
* - The size that can be specified in a Physical Region Descriptor (PRD) is
* limited to 4MB for AHCI. Limiting the total transfer size to at most this
* size implies that no I/O vector element needs to be split up across PRDs.
* This means that the maximum number of needed PRDs can be predetermined.
* - The limit is below what can be transferred in a single ATA request, namely
* 64k sectors (i.e., at least 32MB). This means that transfer requests need
* never be split up into smaller chunks, reducing implementation complexity.
* - A single, static timeout can be used for transfers. Very large transfers
* can legitimately take up to several minutes -- well beyond the appropriate
* timeout range for small transfers. The limit obviates the need for a
* timeout scheme that takes into account the transfer size.
* - Similarly, the transfer limit reduces the opportunity for buggy/malicious
* clients to keep the driver busy for a long time with a single request.
* - The limit is high enough for all practical purposes. The transfer setup
* overhead is already relatively negligible at this size, and even larger
* requests will not help maximize throughput. As NR_IOREQS is currently set
* to 64, the limit still allows file systems to perform I/O requests with
* vectors completely filled with 64KB-blocks.
*/
#include <minix/drivers.h>
#include <minix/blockdriver_mt.h>
#include <minix/drvlib.h>
#include <machine/pci.h>
#include <sys/ioc_disk.h>
#include <sys/mman.h>
#include <assert.h>
#include "ahci.h"
/* Host Bus Adapter (HBA) state. */
static struct {
volatile u32_t *base; /* base address of memory-mapped registers */
size_t size; /* size of memory-mapped register area */
int nr_ports; /* addressable number of ports (1..NR_PORTS) */
int nr_cmds; /* maximum number of commands per port */
int has_ncq; /* NCQ support flag */
int has_clo; /* CLO support flag */
int irq; /* IRQ number */
int hook_id; /* IRQ hook ID */
} hba_state;
#define hba_read(r) (hba_state.base[r])
#define hba_write(r, v) (hba_state.base[r] = (v))
/* Port state. */
static struct port_state {
int state; /* port state */
unsigned int flags; /* port flags */
volatile u32_t *reg; /* memory-mapped port registers */
u8_t *mem_base; /* primary memory buffer virtual address */
phys_bytes mem_phys; /* primary memory buffer physical address */
vir_bytes mem_size; /* primary memory buffer size */
/* the FIS, CL, CT[0] and TMP buffers are all in the primary buffer */
u32_t *fis_base; /* FIS receive buffer virtual address */
phys_bytes fis_phys; /* FIS receive buffer physical address */
u32_t *cl_base; /* command list buffer virtual address */
phys_bytes cl_phys; /* command list buffer physical address */
u8_t *ct_base[NR_CMDS]; /* command table virtual address */
phys_bytes ct_phys[NR_CMDS]; /* command table physical address */
u8_t *tmp_base; /* temporary storage buffer virtual address */
phys_bytes tmp_phys; /* temporary storage buffer physical address */
u8_t *pad_base; /* sector padding buffer virtual address */
phys_bytes pad_phys; /* sector padding buffer physical address */
vir_bytes pad_size; /* sector padding buffer size */
u64_t lba_count; /* number of valid Logical Block Addresses */
u32_t sector_size; /* medium sector size in bytes */
int open_count; /* number of times this port is opened */
int device; /* associated device number, or NO_DEVICE */
struct device part[DEV_PER_DRIVE]; /* partition bases and sizes */
struct device subpart[SUB_PER_DRIVE]; /* same for subpartitions */
minix_timer_t timer; /* port-specific timeout timer */
int left; /* number of tries left before giving up */
/* (only used for signature probing) */
int queue_depth; /* NCQ queue depth */
u32_t pend_mask; /* commands not yet complete */
struct {
thread_id_t tid;/* ID of the worker thread */
minix_timer_t timer; /* timer associated with each request */
int result; /* success/failure result of the commands */
} cmd_info[NR_CMDS];
} port_state[NR_PORTS];
#define port_read(ps, r) ((ps)->reg[r])
#define port_write(ps, r, v) ((ps)->reg[r] = (v))
static int ahci_instance; /* driver instance number */
static int ahci_verbose; /* verbosity level (0..4) */
/* Timeout-related values. */
static clock_t ahci_spinup_timeout;
static clock_t ahci_device_timeout;
static clock_t ahci_device_delay;
static unsigned int ahci_device_checks;
static clock_t ahci_command_timeout;
static clock_t ahci_transfer_timeout;
static clock_t ahci_flush_timeout;
/* Timeout environment variable names and default values. */
static struct {
char *name; /* environment variable name */
u32_t default_ms; /* default in milliseconds */
clock_t *ptr; /* clock ticks value pointer */
} ahci_timevar[] = {
{ "ahci_init_timeout", SPINUP_TIMEOUT, &ahci_spinup_timeout },
{ "ahci_device_timeout", DEVICE_TIMEOUT, &ahci_device_timeout },
{ "ahci_cmd_timeout", COMMAND_TIMEOUT, &ahci_command_timeout },
{ "ahci_io_timeout", TRANSFER_TIMEOUT, &ahci_transfer_timeout },
{ "ahci_flush_timeout", FLUSH_TIMEOUT, &ahci_flush_timeout }
};
static int ahci_map[MAX_DRIVES]; /* device-to-port mapping */
static int ahci_exiting = FALSE; /* exit after last close? */
#define BUILD_ARG(port, tag) (((port) << 8) | (tag))
#define GET_PORT(arg) ((arg) >> 8)
#define GET_TAG(arg) ((arg) & 0xFF)
#define dprintf(v,s) do { \
if (ahci_verbose >= (v)) \
printf s; \
} while (0)
/* Convert milliseconds to clock ticks. Round up. */
#define millis_to_hz(ms) (((ms) * sys_hz() + 999) / 1000)
static void port_set_cmd(struct port_state *ps, int cmd, cmd_fis_t *fis,
u8_t packet[ATAPI_PACKET_SIZE], prd_t *prdt, int nr_prds, int write);
static void port_issue(struct port_state *ps, int cmd, clock_t timeout);
static int port_exec(struct port_state *ps, int cmd, clock_t timeout);
static void port_timeout(int arg);
static void port_disconnect(struct port_state *ps);
static char *ahci_portname(struct port_state *ps);
static int ahci_open(devminor_t minor, int access);
static int ahci_close(devminor_t minor);
static ssize_t ahci_transfer(devminor_t minor, int do_write, u64_t position,
endpoint_t endpt, iovec_t *iovec, unsigned int count, int flags);
static struct device *ahci_part(devminor_t minor);
static void ahci_alarm(clock_t stamp);
static int ahci_ioctl(devminor_t minor, unsigned long request,
endpoint_t endpt, cp_grant_id_t grant, endpoint_t user_endpt);
static void ahci_intr(unsigned int mask);
static int ahci_device(devminor_t minor, device_id_t *id);
static struct port_state *ahci_get_port(devminor_t minor);
/* AHCI driver table. */
static struct blockdriver ahci_dtab = {
.bdr_type = BLOCKDRIVER_TYPE_DISK,
.bdr_open = ahci_open,
.bdr_close = ahci_close,
.bdr_transfer = ahci_transfer,
.bdr_ioctl = ahci_ioctl,
.bdr_part = ahci_part,
.bdr_intr = ahci_intr,
.bdr_alarm = ahci_alarm,
.bdr_device = ahci_device
};
/*===========================================================================*
* atapi_exec *
*===========================================================================*/
static int atapi_exec(struct port_state *ps, int cmd,
u8_t packet[ATAPI_PACKET_SIZE], size_t size, int write)
{
/* Execute an ATAPI command. Return OK or error.
*/
cmd_fis_t fis;
prd_t prd[1];
int nr_prds = 0;
assert(size <= AHCI_TMP_SIZE);
/* Fill in the command table with a FIS, a packet, and if a data
* transfer is requested, also a PRD.
*/
memset(&fis, 0, sizeof(fis));
fis.cf_cmd = ATA_CMD_PACKET;
if (size > 0) {
fis.cf_feat = ATA_FEAT_PACKET_DMA;
if (!write && (ps->flags & FLAG_USE_DMADIR))
fis.cf_feat |= ATA_FEAT_PACKET_DMADIR;
prd[0].vp_addr = ps->tmp_phys;
prd[0].vp_size = size;
nr_prds++;
}
/* Start the command, and wait for it to complete or fail. */
port_set_cmd(ps, cmd, &fis, packet, prd, nr_prds, write);
return port_exec(ps, cmd, ahci_command_timeout);
}
/*===========================================================================*
* atapi_test_unit *
*===========================================================================*/
static int atapi_test_unit(struct port_state *ps, int cmd)
{
/* Test whether the ATAPI device and medium are ready.
*/
u8_t packet[ATAPI_PACKET_SIZE];
memset(packet, 0, sizeof(packet));
packet[0] = ATAPI_CMD_TEST_UNIT;
return atapi_exec(ps, cmd, packet, 0, FALSE);
}
/*===========================================================================*
* atapi_request_sense *
*===========================================================================*/
static int atapi_request_sense(struct port_state *ps, int cmd, int *sense)
{
/* Request error (sense) information from an ATAPI device, and return
* the sense key. The additional sense codes are not used at this time.
*/
u8_t packet[ATAPI_PACKET_SIZE];
int r;
memset(packet, 0, sizeof(packet));
packet[0] = ATAPI_CMD_REQUEST_SENSE;
packet[4] = ATAPI_REQUEST_SENSE_LEN;
r = atapi_exec(ps, cmd, packet, ATAPI_REQUEST_SENSE_LEN, FALSE);
if (r != OK)
return r;
dprintf(V_REQ, ("%s: ATAPI SENSE: sense %x ASC %x ASCQ %x\n",
ahci_portname(ps), ps->tmp_base[2] & 0xF, ps->tmp_base[12],
ps->tmp_base[13]));
*sense = ps->tmp_base[2] & 0xF;
return OK;
}
/*===========================================================================*
* atapi_load_eject *
*===========================================================================*/
static int atapi_load_eject(struct port_state *ps, int cmd, int load)
{
/* Load or eject a medium in an ATAPI device.
*/
u8_t packet[ATAPI_PACKET_SIZE];
memset(packet, 0, sizeof(packet));
packet[0] = ATAPI_CMD_START_STOP;
packet[4] = load ? ATAPI_START_STOP_LOAD : ATAPI_START_STOP_EJECT;
return atapi_exec(ps, cmd, packet, 0, FALSE);
}
/*===========================================================================*
* atapi_read_capacity *
*===========================================================================*/
static int atapi_read_capacity(struct port_state *ps, int cmd)
{
/* Retrieve the LBA count and sector size of an ATAPI medium.
*/
u8_t packet[ATAPI_PACKET_SIZE], *buf;
int r;
memset(packet, 0, sizeof(packet));
packet[0] = ATAPI_CMD_READ_CAPACITY;
r = atapi_exec(ps, cmd, packet, ATAPI_READ_CAPACITY_LEN, FALSE);
if (r != OK)
return r;
/* Store the number of LBA blocks and sector size. */
buf = ps->tmp_base;
ps->lba_count = (u64_t) ((buf[0] << 24) | (buf[1] << 16) |
(buf[2] << 8) | buf[3]) + 1;
ps->sector_size =
(buf[4] << 24) | (buf[5] << 16) | (buf[6] << 8) | buf[7];
if (ps->sector_size == 0 || (ps->sector_size & 1)) {
dprintf(V_ERR, ("%s: invalid medium sector size %u\n",
ahci_portname(ps), ps->sector_size));
return EINVAL;
}
dprintf(V_INFO,
("%s: medium detected (%u byte sectors, %llu MB size)\n",
ahci_portname(ps), ps->sector_size,
ps->lba_count * ps->sector_size / (1024*1024)));
return OK;
}
/*===========================================================================*
* atapi_check_medium *
*===========================================================================*/
static int atapi_check_medium(struct port_state *ps, int cmd)
{
/* Check whether a medium is present in a removable-media ATAPI device.
* If a new medium is detected, get its total and sector size. Return
* OK only if a usable medium is present, and an error otherwise.
*/
int sense;
/* Perform a readiness check. */
if (atapi_test_unit(ps, cmd) != OK) {
ps->flags &= ~FLAG_HAS_MEDIUM;
/* If the check failed due to a unit attention condition, retry
* reading the medium capacity. Otherwise, assume that there is
* no medium available.
*/
if (atapi_request_sense(ps, cmd, &sense) != OK ||
sense != ATAPI_SENSE_UNIT_ATT)
return ENXIO;
}
/* If a medium is newly detected, try reading its capacity now. */
if (!(ps->flags & FLAG_HAS_MEDIUM)) {
if (atapi_read_capacity(ps, cmd) != OK)
return EIO;
ps->flags |= FLAG_HAS_MEDIUM;
}
return OK;
}
/*===========================================================================*
* atapi_id_check *
*===========================================================================*/
static int atapi_id_check(struct port_state *ps, u16_t *buf)
{
/* Determine whether we support this ATAPI device based on the
* identification data it returned, and store some of its properties.
*/
/* The device must be an ATAPI device; it must have removable media;
* it must support DMA without DMADIR, or DMADIR for DMA.
*/
if ((buf[ATA_ID_GCAP] & (ATA_ID_GCAP_ATAPI_MASK |
ATA_ID_GCAP_REMOVABLE | ATA_ID_GCAP_INCOMPLETE)) !=
(ATA_ID_GCAP_ATAPI | ATA_ID_GCAP_REMOVABLE) ||
((buf[ATA_ID_CAP] & ATA_ID_CAP_DMA) != ATA_ID_CAP_DMA &&
(buf[ATA_ID_DMADIR] & (ATA_ID_DMADIR_DMADIR |
ATA_ID_DMADIR_DMA)) != (ATA_ID_DMADIR_DMADIR |
ATA_ID_DMADIR_DMA))) {
dprintf(V_ERR, ("%s: unsupported ATAPI device\n",
ahci_portname(ps)));
dprintf(V_DEV, ("%s: GCAP %04x CAP %04x DMADIR %04x\n",
ahci_portname(ps), buf[ATA_ID_GCAP], buf[ATA_ID_CAP],
buf[ATA_ID_DMADIR]));
return FALSE;
}
/* Remember whether to use the DMADIR flag when appropriate. */
if (buf[ATA_ID_DMADIR] & ATA_ID_DMADIR_DMADIR)
ps->flags |= FLAG_USE_DMADIR;
/* ATAPI CD-ROM devices are considered read-only. */
if (((buf[ATA_ID_GCAP] & ATA_ID_GCAP_TYPE_MASK) >>
ATA_ID_GCAP_TYPE_SHIFT) == ATAPI_TYPE_CDROM)
ps->flags |= FLAG_READONLY;
if ((buf[ATA_ID_SUP1] & ATA_ID_SUP1_VALID_MASK) == ATA_ID_SUP1_VALID &&
!(ps->flags & FLAG_READONLY)) {
/* Save write cache related capabilities of the device. It is
* possible, although unlikely, that a device has support for
* either of these but not both.
*/
if (buf[ATA_ID_SUP0] & ATA_ID_SUP0_WCACHE)
ps->flags |= FLAG_HAS_WCACHE;
if (buf[ATA_ID_SUP1] & ATA_ID_SUP1_FLUSH)
ps->flags |= FLAG_HAS_FLUSH;
}
return TRUE;
}
/*===========================================================================*
* atapi_transfer *
*===========================================================================*/
static int atapi_transfer(struct port_state *ps, int cmd, u64_t start_lba,
unsigned int count, int write, prd_t *prdt, int nr_prds)
{
/* Perform data transfer from or to an ATAPI device.
*/
cmd_fis_t fis;
u8_t packet[ATAPI_PACKET_SIZE];
/* Fill in a Register Host to Device FIS. */
memset(&fis, 0, sizeof(fis));
fis.cf_cmd = ATA_CMD_PACKET;
fis.cf_feat = ATA_FEAT_PACKET_DMA;
if (!write && (ps->flags & FLAG_USE_DMADIR))
fis.cf_feat |= ATA_FEAT_PACKET_DMADIR;
/* Fill in a packet. */
memset(packet, 0, sizeof(packet));
packet[0] = write ? ATAPI_CMD_WRITE : ATAPI_CMD_READ;
packet[2] = (start_lba >> 24) & 0xFF;
packet[3] = (start_lba >> 16) & 0xFF;
packet[4] = (start_lba >> 8) & 0xFF;
packet[5] = start_lba & 0xFF;
packet[6] = (count >> 24) & 0xFF;
packet[7] = (count >> 16) & 0xFF;
packet[8] = (count >> 8) & 0xFF;
packet[9] = count & 0xFF;
/* Start the command, and wait for it to complete or fail. */
port_set_cmd(ps, cmd, &fis, packet, prdt, nr_prds, write);
return port_exec(ps, cmd, ahci_transfer_timeout);
}
/*===========================================================================*
* ata_id_check *
*===========================================================================*/
static int ata_id_check(struct port_state *ps, u16_t *buf)
{
/* Determine whether we support this ATA device based on the
* identification data it returned, and store some of its properties.
*/
/* This must be an ATA device; it must not have removable media;
* it must support LBA and DMA; it must support the FLUSH CACHE
* command; it must support 48-bit addressing.
*/
if ((buf[ATA_ID_GCAP] & (ATA_ID_GCAP_ATA_MASK | ATA_ID_GCAP_REMOVABLE |
ATA_ID_GCAP_INCOMPLETE)) != ATA_ID_GCAP_ATA ||
(buf[ATA_ID_CAP] & (ATA_ID_CAP_LBA | ATA_ID_CAP_DMA)) !=
(ATA_ID_CAP_LBA | ATA_ID_CAP_DMA) ||
(buf[ATA_ID_SUP1] & (ATA_ID_SUP1_VALID_MASK |
ATA_ID_SUP1_FLUSH | ATA_ID_SUP1_LBA48)) !=
(ATA_ID_SUP1_VALID | ATA_ID_SUP1_FLUSH | ATA_ID_SUP1_LBA48)) {
dprintf(V_ERR, ("%s: unsupported ATA device\n",
ahci_portname(ps)));
dprintf(V_DEV, ("%s: GCAP %04x CAP %04x SUP1 %04x\n",
ahci_portname(ps), buf[ATA_ID_GCAP], buf[ATA_ID_CAP],
buf[ATA_ID_SUP1]));
return FALSE;
}
/* Get number of LBA blocks, and sector size. */
ps->lba_count = ((u64_t) buf[ATA_ID_LBA3] << 48) |
((u64_t) buf[ATA_ID_LBA2] << 32) |
((u64_t) buf[ATA_ID_LBA1] << 16) |
(u64_t) buf[ATA_ID_LBA0];
/* Determine the queue depth of the device. */
if (hba_state.has_ncq &&
(buf[ATA_ID_SATA_CAP] & ATA_ID_SATA_CAP_NCQ)) {
ps->flags |= FLAG_HAS_NCQ;
ps->queue_depth =
(buf[ATA_ID_QDEPTH] & ATA_ID_QDEPTH_MASK) + 1;
if (ps->queue_depth > hba_state.nr_cmds)
ps->queue_depth = hba_state.nr_cmds;
}
/* For now, we only support long logical sectors. Long physical sector
* support may be added later. Note that the given value is in words.
*/
if ((buf[ATA_ID_PLSS] & (ATA_ID_PLSS_VALID_MASK | ATA_ID_PLSS_LLS)) ==
(ATA_ID_PLSS_VALID | ATA_ID_PLSS_LLS))
ps->sector_size =
((buf[ATA_ID_LSS1] << 16) | buf[ATA_ID_LSS0]) << 1;
else
ps->sector_size = ATA_SECTOR_SIZE;
if (ps->sector_size < ATA_SECTOR_SIZE) {
dprintf(V_ERR, ("%s: invalid sector size %u\n",
ahci_portname(ps), ps->sector_size));
return FALSE;
}
ps->flags |= FLAG_HAS_MEDIUM | FLAG_HAS_FLUSH;
/* FLUSH CACHE is mandatory for ATA devices; write caches are not. */
if (buf[ATA_ID_SUP0] & ATA_ID_SUP0_WCACHE)
ps->flags |= FLAG_HAS_WCACHE;
/* Check Force Unit Access capability of the device. */
if ((buf[ATA_ID_ENA2] & (ATA_ID_ENA2_VALID_MASK | ATA_ID_ENA2_FUA)) ==
(ATA_ID_ENA2_VALID | ATA_ID_ENA2_FUA))
ps->flags |= FLAG_HAS_FUA;
return TRUE;
}
/*===========================================================================*
* ata_transfer *
*===========================================================================*/
static int ata_transfer(struct port_state *ps, int cmd, u64_t start_lba,
unsigned int count, int write, int force, prd_t *prdt, int nr_prds)
{
/* Perform data transfer from or to an ATA device.
*/
cmd_fis_t fis;
assert(count <= ATA_MAX_SECTORS);
/* Special case for sector counts: 65536 is specified as 0. */
if (count == ATA_MAX_SECTORS)
count = 0;
memset(&fis, 0, sizeof(fis));
fis.cf_dev = ATA_DEV_LBA;
if (ps->flags & FLAG_HAS_NCQ) {
if (write) {
if (force && (ps->flags & FLAG_HAS_FUA))
fis.cf_dev |= ATA_DEV_FUA;
fis.cf_cmd = ATA_CMD_WRITE_FPDMA_QUEUED;
} else {
fis.cf_cmd = ATA_CMD_READ_FPDMA_QUEUED;
}
}
else {
if (write) {
if (force && (ps->flags & FLAG_HAS_FUA))
fis.cf_cmd = ATA_CMD_WRITE_DMA_FUA_EXT;
else
fis.cf_cmd = ATA_CMD_WRITE_DMA_EXT;
}
else {
fis.cf_cmd = ATA_CMD_READ_DMA_EXT;
}
}
fis.cf_lba = start_lba & 0x00FFFFFFUL;
fis.cf_lba_exp = (start_lba >> 24) & 0x00FFFFFFUL;
fis.cf_sec = count & 0xFF;
fis.cf_sec_exp = (count >> 8) & 0xFF;
/* Start the command, and wait for it to complete or fail. */
port_set_cmd(ps, cmd, &fis, NULL /*packet*/, prdt, nr_prds, write);
return port_exec(ps, cmd, ahci_transfer_timeout);
}
/*===========================================================================*
* gen_identify *
*===========================================================================*/
static int gen_identify(struct port_state *ps, int blocking)
{
/* Identify an ATA or ATAPI device. If the blocking flag is set, block
* until the command has completed; otherwise return immediately.
*/
cmd_fis_t fis;
prd_t prd;
/* Set up a command, and a single PRD for the result. */
memset(&fis, 0, sizeof(fis));
if (ps->flags & FLAG_ATAPI)
fis.cf_cmd = ATA_CMD_IDENTIFY_PACKET;
else
fis.cf_cmd = ATA_CMD_IDENTIFY;
prd.vp_addr = ps->tmp_phys;
prd.vp_size = ATA_ID_SIZE;
/* Start the command, and possibly wait for the result. */
port_set_cmd(ps, 0, &fis, NULL /*packet*/, &prd, 1, FALSE /*write*/);
if (blocking)
return port_exec(ps, 0, ahci_command_timeout);
port_issue(ps, 0, ahci_command_timeout);
return OK;
}
/*===========================================================================*
* gen_flush_wcache *
*===========================================================================*/
static int gen_flush_wcache(struct port_state *ps)
{
/* Flush the device's write cache.
*/
cmd_fis_t fis;
/* The FLUSH CACHE command may not be supported by all (writable ATAPI)
* devices.
*/
if (!(ps->flags & FLAG_HAS_FLUSH))
return EINVAL;
/* Use the FLUSH CACHE command for both ATA and ATAPI. We are not
* interested in the disk location of a failure, so there is no reason
* to use the ATA-only FLUSH CACHE EXT command. Either way, the command
* may indeed fail due to a disk error, in which case it should be
* repeated. For now, we shift this responsibility onto the caller.
*/
memset(&fis, 0, sizeof(fis));
fis.cf_cmd = ATA_CMD_FLUSH_CACHE;
/* Start the command, and wait for it to complete or fail.
* The flush command may take longer than regular I/O commands.
*/
port_set_cmd(ps, 0, &fis, NULL /*packet*/, NULL /*prdt*/, 0,
FALSE /*write*/);
return port_exec(ps, 0, ahci_flush_timeout);
}
/*===========================================================================*
* gen_get_wcache *
*===========================================================================*/
static int gen_get_wcache(struct port_state *ps, int *val)
{
/* Retrieve the status of the device's write cache.
*/
int r;
/* Write caches are not mandatory. */
if (!(ps->flags & FLAG_HAS_WCACHE))
return EINVAL;
/* Retrieve information about the device. */
if ((r = gen_identify(ps, TRUE /*blocking*/)) != OK)
return r;
/* Return the current setting. */
*val = !!(((u16_t *) ps->tmp_base)[ATA_ID_ENA0] & ATA_ID_ENA0_WCACHE);
return OK;
}
/*===========================================================================*
* gen_set_wcache *
*===========================================================================*/
static int gen_set_wcache(struct port_state *ps, int enable)
{
/* Enable or disable the device's write cache.
*/
cmd_fis_t fis;
clock_t timeout;
/* Write caches are not mandatory. */
if (!(ps->flags & FLAG_HAS_WCACHE))
return EINVAL;
/* Disabling the write cache causes a (blocking) cache flush. Cache
* flushes may take much longer than regular commands.
*/
timeout = enable ? ahci_command_timeout : ahci_flush_timeout;
/* Set up a command. */
memset(&fis, 0, sizeof(fis));
fis.cf_cmd = ATA_CMD_SET_FEATURES;
fis.cf_feat = enable ? ATA_SF_EN_WCACHE : ATA_SF_DI_WCACHE;
/* Start the command, and wait for it to complete or fail. */
port_set_cmd(ps, 0, &fis, NULL /*packet*/, NULL /*prdt*/, 0,
FALSE /*write*/);
return port_exec(ps, 0, timeout);
}
/*===========================================================================*
* ct_set_fis *
*===========================================================================*/
static vir_bytes ct_set_fis(u8_t *ct, cmd_fis_t *fis, unsigned int tag)
{
/* Fill in the Frame Information Structure part of a command table,
* and return the resulting FIS size (in bytes). We only support the
* command Register - Host to Device FIS type.
*/
memset(ct, 0, ATA_H2D_SIZE);
ct[ATA_FIS_TYPE] = ATA_FIS_TYPE_H2D;
ct[ATA_H2D_FLAGS] = ATA_H2D_FLAGS_C;
ct[ATA_H2D_CMD] = fis->cf_cmd;
ct[ATA_H2D_LBA_LOW] = fis->cf_lba & 0xFF;
ct[ATA_H2D_LBA_MID] = (fis->cf_lba >> 8) & 0xFF;
ct[ATA_H2D_LBA_HIGH] = (fis->cf_lba >> 16) & 0xFF;
ct[ATA_H2D_DEV] = fis->cf_dev;
ct[ATA_H2D_LBA_LOW_EXP] = fis->cf_lba_exp & 0xFF;
ct[ATA_H2D_LBA_MID_EXP] = (fis->cf_lba_exp >> 8) & 0xFF;
ct[ATA_H2D_LBA_HIGH_EXP] = (fis->cf_lba_exp >> 16) & 0xFF;
ct[ATA_H2D_CTL] = fis->cf_ctl;
if (ATA_IS_FPDMA_CMD(fis->cf_cmd)) {
ct[ATA_H2D_FEAT] = fis->cf_sec;
ct[ATA_H2D_FEAT_EXP] = fis->cf_sec_exp;
ct[ATA_H2D_SEC] = tag << ATA_SEC_TAG_SHIFT;
ct[ATA_H2D_SEC_EXP] = 0;
} else {
ct[ATA_H2D_FEAT] = fis->cf_feat;
ct[ATA_H2D_FEAT_EXP] = fis->cf_feat_exp;
ct[ATA_H2D_SEC] = fis->cf_sec;
ct[ATA_H2D_SEC_EXP] = fis->cf_sec_exp;
}
return ATA_H2D_SIZE;
}
/*===========================================================================*
* ct_set_packet *
*===========================================================================*/
static void ct_set_packet(u8_t *ct, u8_t packet[ATAPI_PACKET_SIZE])
{
/* Fill in the packet part of a command table.
*/
memcpy(&ct[AHCI_CT_PACKET_OFF], packet, ATAPI_PACKET_SIZE);
}
/*===========================================================================*
* ct_set_prdt *
*===========================================================================*/
static void ct_set_prdt(u8_t *ct, prd_t *prdt, int nr_prds)
{
/* Fill in the PRDT part of a command table.
*/
u32_t *p;
int i;
p = (u32_t *) &ct[AHCI_CT_PRDT_OFF];
for (i = 0; i < nr_prds; i++, prdt++) {
*p++ = prdt->vp_addr;
*p++ = 0;
*p++ = 0;
*p++ = prdt->vp_size - 1;
}
}
/*===========================================================================*
* port_set_cmd *
*===========================================================================*/
static void port_set_cmd(struct port_state *ps, int cmd, cmd_fis_t *fis,
u8_t packet[ATAPI_PACKET_SIZE], prd_t *prdt, int nr_prds, int write)
{
/* Prepare the given command for execution, by constructing a command
* table and setting up a command list entry pointing to the table.
*/
u8_t *ct;
u32_t *cl;
vir_bytes size;
/* Set a port-specific flag that tells us if the command being
* processed is a NCQ command or not.
*/
if (ATA_IS_FPDMA_CMD(fis->cf_cmd)) {
ps->flags |= FLAG_NCQ_MODE;
} else {
assert(!ps->pend_mask);
ps->flags &= ~FLAG_NCQ_MODE;
}
/* Construct a command table, consisting of a command FIS, optionally
* a packet, and optionally a number of PRDs (making up the actual PRD
* table).
*/
ct = ps->ct_base[cmd];
assert(ct != NULL);
assert(nr_prds <= NR_PRDS);
size = ct_set_fis(ct, fis, cmd);
if (packet != NULL)
ct_set_packet(ct, packet);
ct_set_prdt(ct, prdt, nr_prds);
/* Construct a command list entry, pointing to the command's table.
* Current assumptions: callers always provide a Register - Host to
* Device type FIS, and all non-NCQ commands are prefetchable.
*/
cl = &ps->cl_base[cmd * AHCI_CL_ENTRY_DWORDS];
memset(cl, 0, AHCI_CL_ENTRY_SIZE);
cl[0] = (nr_prds << AHCI_CL_PRDTL_SHIFT) |
((!ATA_IS_FPDMA_CMD(fis->cf_cmd) &&
(nr_prds > 0 || packet != NULL)) ? AHCI_CL_PREFETCHABLE : 0) |
(write ? AHCI_CL_WRITE : 0) |
((packet != NULL) ? AHCI_CL_ATAPI : 0) |
((size / sizeof(u32_t)) << AHCI_CL_CFL_SHIFT);
cl[2] = ps->ct_phys[cmd];
}
/*===========================================================================*
* port_finish_cmd *
*===========================================================================*/
static void port_finish_cmd(struct port_state *ps, int cmd, int result)
{
/* Finish a command that has either succeeded or failed.
*/
assert(cmd < ps->queue_depth);
dprintf(V_REQ, ("%s: command %d %s\n", ahci_portname(ps),
cmd, (result == RESULT_SUCCESS) ? "succeeded" : "failed"));
/* Update the command result, and clear it from the pending list. */
ps->cmd_info[cmd].result = result;
assert(ps->pend_mask & (1 << cmd));
ps->pend_mask &= ~(1 << cmd);
/* Wake up the thread, unless it is the main thread. This can happen
* during initialization, as the gen_identify function is called by the
* main thread itself.
*/
if (ps->state != STATE_WAIT_ID)
blockdriver_mt_wakeup(ps->cmd_info[cmd].tid);
}
/*===========================================================================*
* port_fail_cmds *
*===========================================================================*/
static void port_fail_cmds(struct port_state *ps)
{
/* Fail all ongoing commands for a device.
*/
int i;
for (i = 0; ps->pend_mask != 0 && i < ps->queue_depth; i++)
if (ps->pend_mask & (1 << i))
port_finish_cmd(ps, i, RESULT_FAILURE);
}
/*===========================================================================*
* port_check_cmds *
*===========================================================================*/
static void port_check_cmds(struct port_state *ps)
{
/* Check what commands have completed, and finish them.
*/
u32_t mask, done;
int i;
/* See which commands have completed. */
if (ps->flags & FLAG_NCQ_MODE)
mask = port_read(ps, AHCI_PORT_SACT);
else
mask = port_read(ps, AHCI_PORT_CI);
/* Wake up threads corresponding to completed commands. */
done = ps->pend_mask & ~mask;
for (i = 0; i < ps->queue_depth; i++)
if (done & (1 << i))
port_finish_cmd(ps, i, RESULT_SUCCESS);
}
/*===========================================================================*
* port_find_cmd *
*===========================================================================*/
static int port_find_cmd(struct port_state *ps)
{
/* Find a free command tag to queue the current request.
*/
int i;
for (i = 0; i < ps->queue_depth; i++)
if (!(ps->pend_mask & (1 << i)))
break;
/* We should always be able to find a free slot, since a thread runs
* only when it is free, and thus, only because a slot is available.
*/
assert(i < ps->queue_depth);
return i;
}
/*===========================================================================*
* port_get_padbuf *
*===========================================================================*/
static int port_get_padbuf(struct port_state *ps, size_t size)
{
/* Make available a temporary buffer for use by this port. Enlarge the
* previous buffer if applicable and necessary, potentially changing
* its physical address.
*/
if (ps->pad_base != NULL && ps->pad_size >= size)
return OK;
if (ps->pad_base != NULL)
free_contig(ps->pad_base, ps->pad_size);
ps->pad_size = size;
ps->pad_base = alloc_contig(ps->pad_size, 0, &ps->pad_phys);
if (ps->pad_base == NULL) {
dprintf(V_ERR, ("%s: unable to allocate a padding buffer of "
"size %lu\n", ahci_portname(ps),
(unsigned long) size));
return ENOMEM;
}
dprintf(V_INFO, ("%s: allocated padding buffer of size %lu\n",
ahci_portname(ps), (unsigned long) size));
return OK;
}
/*===========================================================================*
* sum_iovec *
*===========================================================================*/
static int sum_iovec(struct port_state *ps, endpoint_t endpt,
iovec_s_t *iovec, int nr_req, vir_bytes *total)
{
/* Retrieve the total size of the given I/O vector. Check for alignment
* requirements along the way. Return OK (and the total request size)
* or an error.
*/
vir_bytes size, bytes;
int i;
bytes = 0;
for (i = 0; i < nr_req; i++) {
size = iovec[i].iov_size;
if (size == 0 || (size & 1) || size > LONG_MAX) {
dprintf(V_ERR, ("%s: bad size %lu in iovec from %d\n",
ahci_portname(ps), size, endpt));
return EINVAL;
}
bytes += size;
if (bytes > LONG_MAX) {
dprintf(V_ERR, ("%s: iovec size overflow from %d\n",
ahci_portname(ps), endpt));
return EINVAL;
}
}
*total = bytes;
return OK;
}
/*===========================================================================*
* setup_prdt *
*===========================================================================*/
static int setup_prdt(struct port_state *ps, endpoint_t endpt,
iovec_s_t *iovec, int nr_req, vir_bytes size, vir_bytes lead,
int write, prd_t *prdt)
{
/* Convert (the first part of) an I/O vector to a Physical Region
* Descriptor Table describing array that can later be used to set the
* command's real PRDT. The resulting table as a whole should be
* sector-aligned; leading and trailing local buffers may have to be
* used for padding as appropriate. Return the number of PRD entries,
* or a negative error code.
*/
struct vumap_vir vvec[NR_PRDS];
size_t bytes, trail;
int i, r, pcount, nr_prds = 0;
if (lead > 0) {
/* Allocate a buffer for the data we don't want. */
if ((r = port_get_padbuf(ps, ps->sector_size)) != OK)
return r;
prdt[nr_prds].vp_addr = ps->pad_phys;
prdt[nr_prds].vp_size = lead;
nr_prds++;
}
/* The sum of lead, size, trail has to be sector-aligned. */
trail = (ps->sector_size - (lead + size)) % ps->sector_size;
/* Get the physical addresses of the given buffers. */
for (i = 0; i < nr_req && size > 0; i++) {
bytes = MIN(iovec[i].iov_size, size);
if (endpt == SELF)
vvec[i].vv_addr = (vir_bytes) iovec[i].iov_grant;
else
vvec[i].vv_grant = iovec[i].iov_grant;
vvec[i].vv_size = bytes;
size -= bytes;
}
pcount = i;
if ((r = sys_vumap(endpt, vvec, i, 0, write ? VUA_READ : VUA_WRITE,
&prdt[nr_prds], &pcount)) != OK) {
dprintf(V_ERR, ("%s: unable to map memory from %d (%d)\n",
ahci_portname(ps), endpt, r));
return r;
}
assert(pcount > 0 && pcount <= i);
/* Make sure all buffers are physically contiguous and word-aligned. */
for (i = 0; i < pcount; i++) {
if (vvec[i].vv_size != prdt[nr_prds].vp_size) {
dprintf(V_ERR, ("%s: non-contiguous memory from %d\n",
ahci_portname(ps), endpt));
return EINVAL;
}
if (prdt[nr_prds].vp_addr & 1) {
dprintf(V_ERR, ("%s: bad physical address from %d\n",
ahci_portname(ps), endpt));
return EINVAL;
}
nr_prds++;
}
if (trail > 0) {
assert(nr_prds < NR_PRDS);
prdt[nr_prds].vp_addr = ps->pad_phys + lead;
prdt[nr_prds].vp_size = trail;
nr_prds++;
}
return nr_prds;
}
/*===========================================================================*
* port_transfer *
*===========================================================================*/
static ssize_t port_transfer(struct port_state *ps, u64_t pos, u64_t eof,
endpoint_t endpt, iovec_s_t *iovec, int nr_req, int write, int flags)
{
/* Perform an I/O transfer on a port.
*/
prd_t prdt[NR_PRDS];
vir_bytes size, lead;
unsigned int count, nr_prds;
u64_t start_lba;
int r, cmd;
/* Get the total request size from the I/O vector. */
if ((r = sum_iovec(ps, endpt, iovec, nr_req, &size)) != OK)
return r;
dprintf(V_REQ, ("%s: %s for %lu bytes at pos %llx\n",
ahci_portname(ps), write ? "write" : "read", size, pos));
assert(ps->state == STATE_GOOD_DEV);
assert(ps->flags & FLAG_HAS_MEDIUM);
assert(ps->sector_size > 0);
/* Limit the maximum size of a single transfer.
* See the comments at the top of this file for details.
*/
if (size > MAX_TRANSFER)
size = MAX_TRANSFER;
/* If necessary, reduce the request size so that the request does not
* extend beyond the end of the partition. The caller already
* guarantees that the starting position lies within the partition.
*/
if (pos + size > eof)
size = (vir_bytes) (eof - pos);
start_lba = pos / ps->sector_size;
lead = (vir_bytes) (pos % ps->sector_size);
count = (lead + size + ps->sector_size - 1) / ps->sector_size;
/* Position must be word-aligned for read requests, and sector-aligned
* for write requests. We do not support read-modify-write for writes.
*/
if ((lead & 1) || (write && lead != 0)) {
dprintf(V_ERR, ("%s: unaligned position from %d\n",
ahci_portname(ps), endpt));
return EINVAL;
}
/* Write requests must be sector-aligned. Word alignment of the size is
* already guaranteed by sum_iovec().
*/
if (write && (size % ps->sector_size) != 0) {
dprintf(V_ERR, ("%s: unaligned size %lu from %d\n",
ahci_portname(ps), size, endpt));
return EINVAL;
}
/* Create a vector of physical addresses and sizes for the transfer. */
nr_prds = r = setup_prdt(ps, endpt, iovec, nr_req, size, lead, write,
prdt);
if (r < 0) return r;
/* Perform the actual transfer. */
cmd = port_find_cmd(ps);
if (ps->flags & FLAG_ATAPI)
r = atapi_transfer(ps, cmd, start_lba, count, write, prdt,
nr_prds);
else
r = ata_transfer(ps, cmd, start_lba, count, write,
!!(flags & BDEV_FORCEWRITE), prdt, nr_prds);
if (r != OK) return r;
return size;
}
/*===========================================================================*
* port_hardreset *
*===========================================================================*/
static void port_hardreset(struct port_state *ps)
{
/* Perform a port-level (hard) reset on the given port.
*/
port_write(ps, AHCI_PORT_SCTL, AHCI_PORT_SCTL_DET_INIT);
micro_delay(COMRESET_DELAY * 1000); /* COMRESET_DELAY is in ms */
port_write(ps, AHCI_PORT_SCTL, AHCI_PORT_SCTL_DET_NONE);
}
/*===========================================================================*
* port_override *
*===========================================================================*/
static void port_override(struct port_state *ps)
{
/* Override the port's BSY and/or DRQ flags. This may only be done
* prior to starting the port.
*/
u32_t cmd;
cmd = port_read(ps, AHCI_PORT_CMD);
port_write(ps, AHCI_PORT_CMD, cmd | AHCI_PORT_CMD_CLO);
SPIN_UNTIL(!(port_read(ps, AHCI_PORT_CMD) & AHCI_PORT_CMD_CLO),
PORTREG_DELAY);
dprintf(V_INFO, ("%s: overridden\n", ahci_portname(ps)));
}
/*===========================================================================*
* port_start *
*===========================================================================*/
static void port_start(struct port_state *ps)
{
/* Start the given port, allowing for the execution of commands and the
* transfer of data on that port.
*/
u32_t cmd;
/* Reset status registers. */
port_write(ps, AHCI_PORT_SERR, ~0);
port_write(ps, AHCI_PORT_IS, ~0);
/* Start the port. */
cmd = port_read(ps, AHCI_PORT_CMD);
port_write(ps, AHCI_PORT_CMD, cmd | AHCI_PORT_CMD_ST);
dprintf(V_INFO, ("%s: started\n", ahci_portname(ps)));
}
/*===========================================================================*
* port_stop *
*===========================================================================*/
static void port_stop(struct port_state *ps)
{
/* Stop the given port, if not already stopped.
*/
u32_t cmd;
cmd = port_read(ps, AHCI_PORT_CMD);
if (cmd & (AHCI_PORT_CMD_CR | AHCI_PORT_CMD_ST)) {
port_write(ps, AHCI_PORT_CMD, cmd & ~AHCI_PORT_CMD_ST);
SPIN_UNTIL(!(port_read(ps, AHCI_PORT_CMD) & AHCI_PORT_CMD_CR),
PORTREG_DELAY);
dprintf(V_INFO, ("%s: stopped\n", ahci_portname(ps)));
}
}
/*===========================================================================*
* port_restart *
*===========================================================================*/
static void port_restart(struct port_state *ps)
{
/* Restart a port after a fatal error has occurred.
*/
/* Fail all outstanding commands. */
port_fail_cmds(ps);
/* Stop the port. */
port_stop(ps);
/* If the BSY and/or DRQ flags are set, reset the port. */
if (port_read(ps, AHCI_PORT_TFD) &
(AHCI_PORT_TFD_STS_BSY | AHCI_PORT_TFD_STS_DRQ)) {
dprintf(V_ERR, ("%s: port reset\n", ahci_portname(ps)));
/* To keep this driver simple, we do not transparently recover
* ongoing requests. Instead, we mark the failing device as
* disconnected, and reset it. If the reset succeeds, the
* device (or, perhaps, eventually, another device) will come
* back up. Any current and future requests to this port will
* be failed until the port is fully closed and reopened.
*/
port_disconnect(ps);
/* Trigger a port reset. */
port_hardreset(ps);
return;
}
/* Start the port. */
port_start(ps);
}
/*===========================================================================*
* print_string *
*===========================================================================*/
static void print_string(u16_t *buf, int start, int end)
{
/* Print a string that is stored as little-endian words and padded with
* trailing spaces.
*/
int i, last = 0;
while (end >= start && buf[end] == 0x2020) end--;
if (end >= start && (buf[end] & 0xFF) == 0x20) end--, last++;
for (i = start; i <= end; i++)
printf("%c%c", buf[i] >> 8, buf[i] & 0xFF);
if (last)
printf("%c", buf[i] >> 8);
}
/*===========================================================================*
* port_id_check *
*===========================================================================*/
static void port_id_check(struct port_state *ps, int success)
{
/* The device identification command has either completed or timed out.
* Decide whether this device is usable or not, and store some of its
* properties.
*/
u16_t *buf;
assert(ps->state == STATE_WAIT_ID);
ps->flags &= ~FLAG_BUSY;
cancel_timer(&ps->cmd_info[0].timer);
if (!success) {
if (!(ps->flags & FLAG_ATAPI) &&
port_read(ps, AHCI_PORT_SIG) != ATA_SIG_ATA) {
dprintf(V_INFO, ("%s: may not be ATA, trying ATAPI\n",
ahci_portname(ps)));
ps->flags |= FLAG_ATAPI;
(void) gen_identify(ps, FALSE /*blocking*/);
return;
}
dprintf(V_ERR,
("%s: unable to identify\n", ahci_portname(ps)));
}
/* If the identify command itself succeeded, check the results and
* store some properties.
*/
if (success) {
buf = (u16_t *) ps->tmp_base;
if (ps->flags & FLAG_ATAPI)
success = atapi_id_check(ps, buf);
else
success = ata_id_check(ps, buf);
}
/* If the device has not been identified successfully, mark it as an
* unusable device.
*/
if (!success) {
port_stop(ps);
ps->state = STATE_BAD_DEV;
port_write(ps, AHCI_PORT_IE, AHCI_PORT_IE_PRCE);
return;
}
/* The device has been identified successfully, and hence usable. */
ps->state = STATE_GOOD_DEV;
/* Print some information about the device. */
if (ahci_verbose >= V_INFO) {
printf("%s: ATA%s, ", ahci_portname(ps),
(ps->flags & FLAG_ATAPI) ? "PI" : "");
print_string(buf, 27, 46);
if (ahci_verbose >= V_DEV) {
printf(" (");
print_string(buf, 10, 19);
printf(", ");
print_string(buf, 23, 26);
printf(")");
}
if (ps->flags & FLAG_HAS_MEDIUM)
printf(", %u byte sectors, %llu MB size",
ps->sector_size,
ps->lba_count * ps->sector_size / (1024*1024));
printf("\n");
}
}
/*===========================================================================*
* port_connect *
*===========================================================================*/
static void port_connect(struct port_state *ps)
{
/* A device has been found to be attached to this port. Start the port,
* and do timed polling for its signature to become available.
*/
u32_t status, sig;
dprintf(V_INFO, ("%s: device connected\n", ahci_portname(ps)));
port_start(ps);
/* The next check covers a purely hypothetical race condition, where
* the device would disappear right before we try to start it. This is
* possible because we have to clear PxSERR, and with that, the DIAG.N
* bit. Double-check the port status, and if it is not as we expect,
* infer a disconnection.
*/
status = port_read(ps, AHCI_PORT_SSTS) & AHCI_PORT_SSTS_DET_MASK;
if (status != AHCI_PORT_SSTS_DET_PHY) {
dprintf(V_ERR, ("%s: device vanished!\n", ahci_portname(ps)));
port_stop(ps);
ps->state = STATE_NO_DEV;
ps->flags &= ~FLAG_BUSY;
return;
}
/* Clear all state flags except the busy flag, which may be relevant if
* a BDEV_OPEN call is waiting for the device to become ready; the
* barrier flag, which prevents access to the device until it is
* completely closed and (re)opened; and, the thread suspension flag.
*/
ps->flags &= (FLAG_BUSY | FLAG_BARRIER | FLAG_SUSPENDED);
/* Check the port's signature. We only use the signature to speed up
* identification; we will try both ATA and ATAPI if the signature is
* neither ATA nor ATAPI.
*/
sig = port_read(ps, AHCI_PORT_SIG);
if (sig == ATA_SIG_ATAPI)
ps->flags |= FLAG_ATAPI;
/* Attempt to identify the device. Do this using continuation, because
* we may already be called from port_wait() here, and could end up
* confusing the timer expiration procedure.
*/
ps->state = STATE_WAIT_ID;
port_write(ps, AHCI_PORT_IE, AHCI_PORT_IE_MASK);
(void) gen_identify(ps, FALSE /*blocking*/);
}
/*===========================================================================*
* port_disconnect *
*===========================================================================*/
static void port_disconnect(struct port_state *ps)
{
/* The device has detached from this port. It has already been stopped.
*/
dprintf(V_INFO, ("%s: device disconnected\n", ahci_portname(ps)));
ps->state = STATE_NO_DEV;
port_write(ps, AHCI_PORT_IE, AHCI_PORT_IE_PCE);
ps->flags &= ~FLAG_BUSY;
/* Fail any ongoing request. The caller may already have done this. */
port_fail_cmds(ps);
/* Block any further access until the device is completely closed and
* reopened. This prevents arbitrary I/O to a newly plugged-in device
* without upper layers noticing.
*/
ps->flags |= FLAG_BARRIER;
/* Inform the blockdriver library to reduce the number of threads. */
blockdriver_mt_set_workers(ps->device, 1);
}
/*===========================================================================*
* port_dev_check *
*===========================================================================*/
static void port_dev_check(struct port_state *ps)
{
/* Perform device detection by means of polling.
*/
u32_t status, tfd;
assert(ps->state == STATE_WAIT_DEV);
status = port_read(ps, AHCI_PORT_SSTS) & AHCI_PORT_SSTS_DET_MASK;
dprintf(V_DEV, ("%s: polled status %u\n", ahci_portname(ps), status));
switch (status) {
case AHCI_PORT_SSTS_DET_PHY:
tfd = port_read(ps, AHCI_PORT_TFD);
/* If a Phy connection has been established, and the BSY and
* DRQ flags are cleared, the device is ready.
*/
if (!(tfd & (AHCI_PORT_TFD_STS_BSY | AHCI_PORT_TFD_STS_DRQ))) {
port_connect(ps);
return;
}
/* fall-through */
case AHCI_PORT_SSTS_DET_DET:
/* A device has been detected, but it is not ready yet. Try for
* a while before giving up. This may take seconds.
*/
if (ps->left > 0) {
ps->left--;
set_timer(&ps->cmd_info[0].timer, ahci_device_delay,
port_timeout, BUILD_ARG(ps - port_state, 0));
return;
}
}
dprintf(V_INFO, ("%s: device not ready\n", ahci_portname(ps)));
/* We get here on timeout, and if the HBA reports that there is no
* device present at all. In all cases, we change to another state.
*/
if (status == AHCI_PORT_SSTS_DET_PHY) {
/* Some devices may not correctly clear BSY/DRQ. Upon timeout,
* if we can override these flags, do so and start the
* identification process anyway.
*/
if (hba_state.has_clo) {
port_override(ps);
port_connect(ps);
return;
}
/* A device is present and initialized, but not ready. */
ps->state = STATE_BAD_DEV;
port_write(ps, AHCI_PORT_IE, AHCI_PORT_IE_PRCE);
} else {
/* A device may or may not be present, but it does not appear
* to be ready in any case. Ignore it until the next device
* initialization event.
*/
ps->state = STATE_NO_DEV;
ps->flags &= ~FLAG_BUSY;
}
}
/*===========================================================================*
* port_intr *
*===========================================================================*/
static void port_intr(struct port_state *ps)
{
/* Process an interrupt on this port.
*/
u32_t smask, emask;
int success;
if (ps->state == STATE_NO_PORT) {
dprintf(V_ERR, ("%s: interrupt for invalid port!\n",
ahci_portname(ps)));
return;
}
smask = port_read(ps, AHCI_PORT_IS);
emask = smask & port_read(ps, AHCI_PORT_IE);
/* Clear the interrupt flags that we saw were set. */
port_write(ps, AHCI_PORT_IS, smask);
dprintf(V_REQ, ("%s: interrupt (%08x)\n", ahci_portname(ps), smask));
/* Check if any commands have completed. */
port_check_cmds(ps);
if (emask & AHCI_PORT_IS_PCS) {
/* Clear the X diagnostics bit to clear this interrupt. */
port_write(ps, AHCI_PORT_SERR, AHCI_PORT_SERR_DIAG_X);
dprintf(V_DEV, ("%s: device attached\n", ahci_portname(ps)));
switch (ps->state) {
case STATE_SPIN_UP:
case STATE_NO_DEV:
/* Reportedly, a device has shown up. Start polling its
* status until it has become ready.
*/
if (ps->state == STATE_SPIN_UP)
cancel_timer(&ps->cmd_info[0].timer);
ps->state = STATE_WAIT_DEV;
ps->left = ahci_device_checks;
port_dev_check(ps);
break;
case STATE_WAIT_DEV:
/* Nothing else to do. */
break;
default:
/* Impossible. */
assert(0);
}
} else if (emask & AHCI_PORT_IS_PRCS) {
/* Clear the N diagnostics bit to clear this interrupt. */
port_write(ps, AHCI_PORT_SERR, AHCI_PORT_SERR_DIAG_N);
dprintf(V_DEV, ("%s: device detached\n", ahci_portname(ps)));
switch (ps->state) {
case STATE_WAIT_ID:
case STATE_GOOD_DEV:
/* The device is no longer ready. Stop the port, cancel
* ongoing requests, and disconnect the device.
*/
port_stop(ps);
/* fall-through */
case STATE_BAD_DEV:
port_disconnect(ps);
/* The device has become unusable to us at this point.
* Reset the port to make sure that once the device (or
* another device) becomes usable again, we will get a
* PCS interrupt as well.
*/
port_hardreset(ps);
break;
default:
/* Impossible. */
assert(0);
}
} else if (smask & AHCI_PORT_IS_MASK) {
/* We assume that any other interrupt indicates command
* completion or (command or device) failure. Unfortunately, if
* an NCQ command failed, we cannot easily determine which one
* it was. For that reason, after completing all successfully
* finished commands (above), we fail all other outstanding
* commands and restart the port. This can possibly be improved
* later by obtaining per-command status results from the HBA.
*/
success = !(port_read(ps, AHCI_PORT_TFD) &
(AHCI_PORT_TFD_STS_ERR | AHCI_PORT_TFD_STS_DF));
/* Check now for failure. There are fatal failures, and there
* are failures that set the TFD.STS.ERR field using a D2H
* FIS. In both cases, we just restart the port, failing all
* commands in the process.
*/
if ((port_read(ps, AHCI_PORT_TFD) &
(AHCI_PORT_TFD_STS_ERR | AHCI_PORT_TFD_STS_DF)) ||
(smask & AHCI_PORT_IS_RESTART)) {
port_restart(ps);
}
/* If we were waiting for ID verification, check now. */
if (ps->state == STATE_WAIT_ID)
port_id_check(ps, success);
}
}
/*===========================================================================*
* port_timeout *
*===========================================================================*/
static void port_timeout(int arg)
{
/* A timeout has occurred on this port. Figure out what the timeout is
* for, and take appropriate action.
*/
struct port_state *ps;
int port, cmd;
port = GET_PORT(arg);
cmd = GET_TAG(arg);
assert(port >= 0 && port < hba_state.nr_ports);
ps = &port_state[port];
/* Regardless of the outcome of this timeout, wake up the thread if it
* is suspended. This applies only during the initialization.
*/
if (ps->flags & FLAG_SUSPENDED) {
assert(cmd == 0);
blockdriver_mt_wakeup(ps->cmd_info[0].tid);
}
/* If detection of a device after startup timed out, give up on initial
* detection and only look for hot plug events from now on.
*/
if (ps->state == STATE_SPIN_UP) {
/* One exception: if the PCS interrupt bit is set here, then we
* are probably running on VirtualBox, which is currently not
* always raising interrupts when setting interrupt bits (!).
*/
if (port_read(ps, AHCI_PORT_IS) & AHCI_PORT_IS_PCS) {
dprintf(V_INFO, ("%s: bad controller, no interrupt\n",
ahci_portname(ps)));
ps->state = STATE_WAIT_DEV;
ps->left = ahci_device_checks;
port_dev_check(ps);
return;
} else {
dprintf(V_INFO, ("%s: spin-up timeout\n",
ahci_portname(ps)));
/* If the busy flag is set, a BDEV_OPEN request is
* waiting for the detection to finish; clear the busy
* flag to return an error to the caller.
*/
ps->state = STATE_NO_DEV;
ps->flags &= ~FLAG_BUSY;
}
return;
}
/* If we are waiting for a device to become connected and initialized,
* check now.
*/
if (ps->state == STATE_WAIT_DEV) {
port_dev_check(ps);
return;
}
dprintf(V_ERR, ("%s: timeout\n", ahci_portname(ps)));
/* Restart the port, failing all current commands. */
port_restart(ps);
/* Finish up the identify operation. */
if (ps->state == STATE_WAIT_ID)
port_id_check(ps, FALSE);
}
/*===========================================================================*
* port_wait *
*===========================================================================*/
static void port_wait(struct port_state *ps)
{
/* Suspend the current thread until the given port is no longer busy,
* due to either command completion or timeout.
*/
ps->flags |= FLAG_SUSPENDED;
while (ps->flags & FLAG_BUSY)
blockdriver_mt_sleep();
ps->flags &= ~FLAG_SUSPENDED;
}
/*===========================================================================*
* port_issue *
*===========================================================================*/
static void port_issue(struct port_state *ps, int cmd, clock_t timeout)
{
/* Issue a command to the port, and set a timer to trigger a timeout
* if the command takes too long to complete.
*/
/* Set the corresponding NCQ command bit, if applicable. */
if (ps->flags & FLAG_HAS_NCQ)
port_write(ps, AHCI_PORT_SACT, 1 << cmd);
/* Make sure that the compiler does not delay any previous write
* operations until after the write to the command issue register.
*/
__insn_barrier();
/* Tell the controller that a new command is ready. */
port_write(ps, AHCI_PORT_CI, 1 << cmd);
/* Update pending commands. */
ps->pend_mask |= 1 << cmd;
/* Set a timer in case the command does not complete at all. */
set_timer(&ps->cmd_info[cmd].timer, timeout, port_timeout,
BUILD_ARG(ps - port_state, cmd));
}
/*===========================================================================*
* port_exec *
*===========================================================================*/
static int port_exec(struct port_state *ps, int cmd, clock_t timeout)
{
/* Execute a command on a port, wait for the command to complete or for
* a timeout, and return whether the command succeeded or not.
*/
port_issue(ps, cmd, timeout);
/* Put the thread to sleep until a timeout or a command completion
* happens. Earlier, we used to call port_wait which set the suspended
* flag. We now abandon it since the flag has to work on a per-thread,
* and hence per-tag basis and not on a per-port basis. Instead, we
* retain that call only to defer open calls during device/driver
* initialization. Instead, we call sleep here directly. Before
* sleeping, we register the thread.
*/
ps->cmd_info[cmd].tid = blockdriver_mt_get_tid();
blockdriver_mt_sleep();
/* Cancelling a timer that just triggered, does no harm. */
cancel_timer(&ps->cmd_info[cmd].timer);
assert(!(ps->flags & FLAG_BUSY));
dprintf(V_REQ, ("%s: end of command -- %s\n", ahci_portname(ps),
(ps->cmd_info[cmd].result == RESULT_FAILURE) ?
"failure" : "success"));
if (ps->cmd_info[cmd].result == RESULT_FAILURE)
return EIO;
return OK;
}
/*===========================================================================*
* port_alloc *
*===========================================================================*/
static void port_alloc(struct port_state *ps)
{
/* Allocate memory for the given port, and enable FIS receipt. We try
* to cram everything into one 4K-page in order to limit memory usage
* as much as possible. More memory may be allocated on demand later,
* but allocation failure should be fatal only here. Note that we do
* not allocate memory for sector padding here, because we do not know
* the device's sector size yet.
*/
size_t fis_off, tmp_off, ct_off; int i;
size_t ct_offs[NR_CMDS];
u32_t cmd;
fis_off = AHCI_CL_SIZE + AHCI_FIS_SIZE - 1;
fis_off -= fis_off % AHCI_FIS_SIZE;
tmp_off = fis_off + AHCI_FIS_SIZE + AHCI_TMP_ALIGN - 1;
tmp_off -= tmp_off % AHCI_TMP_ALIGN;
/* Allocate memory for all the commands. */
ct_off = tmp_off + AHCI_TMP_SIZE;
for (i = 0; i < NR_CMDS; i++) {
ct_off += AHCI_CT_ALIGN - 1;
ct_off -= ct_off % AHCI_CT_ALIGN;
ct_offs[i] = ct_off;
ps->mem_size = ct_off + AHCI_CT_SIZE;
ct_off = ps->mem_size;
}
ps->mem_base = alloc_contig(ps->mem_size, AC_ALIGN4K, &ps->mem_phys);
if (ps->mem_base == NULL)
panic("unable to allocate port memory");
memset(ps->mem_base, 0, ps->mem_size);
ps->cl_base = (u32_t *) ps->mem_base;
ps->cl_phys = ps->mem_phys;
assert(ps->cl_phys % AHCI_CL_SIZE == 0);
ps->fis_base = (u32_t *) (ps->mem_base + fis_off);
ps->fis_phys = ps->mem_phys + fis_off;
assert(ps->fis_phys % AHCI_FIS_SIZE == 0);
ps->tmp_base = (u8_t *) (ps->mem_base + tmp_off);
ps->tmp_phys = ps->mem_phys + tmp_off;
assert(ps->tmp_phys % AHCI_TMP_ALIGN == 0);
for (i = 0; i < NR_CMDS; i++) {
ps->ct_base[i] = ps->mem_base + ct_offs[i];
ps->ct_phys[i] = ps->mem_phys + ct_offs[i];
assert(ps->ct_phys[i] % AHCI_CT_ALIGN == 0);
}
/* Tell the controller about some of the physical addresses. */
port_write(ps, AHCI_PORT_FBU, 0);
port_write(ps, AHCI_PORT_FB, ps->fis_phys);
port_write(ps, AHCI_PORT_CLBU, 0);
port_write(ps, AHCI_PORT_CLB, ps->cl_phys);
/* Enable FIS receive. */
cmd = port_read(ps, AHCI_PORT_CMD);
port_write(ps, AHCI_PORT_CMD, cmd | AHCI_PORT_CMD_FRE);
ps->pad_base = NULL;
ps->pad_size = 0;
}
/*===========================================================================*
* port_free *
*===========================================================================*/
static void port_free(struct port_state *ps)
{
/* Disable FIS receipt for the given port, and free previously
* allocated memory.
*/
u32_t cmd;
/* Disable FIS receive. */
cmd = port_read(ps, AHCI_PORT_CMD);
if (cmd & (AHCI_PORT_CMD_FR | AHCI_PORT_CMD_FRE)) {
port_write(ps, AHCI_PORT_CMD, cmd & ~AHCI_PORT_CMD_FRE);
SPIN_UNTIL(!(port_read(ps, AHCI_PORT_CMD) & AHCI_PORT_CMD_FR),
PORTREG_DELAY);
}
if (ps->pad_base != NULL)
free_contig(ps->pad_base, ps->pad_size);
free_contig(ps->mem_base, ps->mem_size);
}
/*===========================================================================*
* port_init *
*===========================================================================*/
static void port_init(struct port_state *ps)
{
/* Initialize the given port.
*/
u32_t cmd;
int i;
/* Initialize the port state structure. */
ps->queue_depth = 1;
ps->state = STATE_SPIN_UP;
ps->flags = FLAG_BUSY;
ps->sector_size = 0;
ps->open_count = 0;
ps->pend_mask = 0;
for (i = 0; i < NR_CMDS; i++)
init_timer(&ps->cmd_info[i].timer);
ps->reg = (u32_t *) ((u8_t *) hba_state.base +
AHCI_MEM_BASE_SIZE + AHCI_MEM_PORT_SIZE * (ps - port_state));
/* Allocate memory for the port. */
port_alloc(ps);
/* Just listen for device connection events for now. */
port_write(ps, AHCI_PORT_IE, AHCI_PORT_IE_PCE);
/* Enable device spin-up for HBAs that support staggered spin-up.
* This is a no-op for HBAs that do not support it.
*/
cmd = port_read(ps, AHCI_PORT_CMD);
port_write(ps, AHCI_PORT_CMD, cmd | AHCI_PORT_CMD_SUD);
/* Trigger a port reset. */
port_hardreset(ps);
set_timer(&ps->cmd_info[0].timer, ahci_spinup_timeout,
port_timeout, BUILD_ARG(ps - port_state, 0));
}
/*===========================================================================*
* ahci_probe *
*===========================================================================*/
static int ahci_probe(int skip)
{
/* Find a matching PCI device.
*/
int r, devind;
u16_t vid, did;
pci_init();
r = pci_first_dev(&devind, &vid, &did);
if (r <= 0)
return -1;
while (skip--) {
r = pci_next_dev(&devind, &vid, &did);
if (r <= 0)
return -1;
}
pci_reserve(devind);
return devind;
}
/*===========================================================================*
* ahci_reset *
*===========================================================================*/
static void ahci_reset(void)
{
/* Reset the HBA. Do not enable AHCI mode afterwards.
*/
u32_t ghc;
ghc = hba_read(AHCI_HBA_GHC);
hba_write(AHCI_HBA_GHC, ghc | AHCI_HBA_GHC_AE);
hba_write(AHCI_HBA_GHC, ghc | AHCI_HBA_GHC_AE | AHCI_HBA_GHC_HR);
SPIN_UNTIL(!(hba_read(AHCI_HBA_GHC) & AHCI_HBA_GHC_HR), RESET_DELAY);
if (hba_read(AHCI_HBA_GHC) & AHCI_HBA_GHC_HR)
panic("unable to reset HBA");
}
/*===========================================================================*
* ahci_init *
*===========================================================================*/
static void ahci_init(int devind)
{
/* Initialize the device.
*/
u32_t base, size, cap, ghc, mask;
int r, port, ioflag;
if ((r = pci_get_bar(devind, PCI_BAR_6, &base, &size, &ioflag)) != OK)
panic("unable to retrieve BAR: %d", r);
if (ioflag)
panic("invalid BAR type");
/* There must be at least one port, and at most NR_PORTS ports. Limit
* the actual total number of ports to the size of the exposed area.
*/
if (size < AHCI_MEM_BASE_SIZE + AHCI_MEM_PORT_SIZE)
panic("HBA memory size too small: %u", size);
size = MIN(size, AHCI_MEM_BASE_SIZE + AHCI_MEM_PORT_SIZE * NR_PORTS);
hba_state.nr_ports = (size - AHCI_MEM_BASE_SIZE) / AHCI_MEM_PORT_SIZE;
/* Map the register area into local memory. */
hba_state.base = (u32_t *) vm_map_phys(SELF, (void *) base, size);
hba_state.size = size;
if (hba_state.base == MAP_FAILED)
panic("unable to map HBA memory");
/* Retrieve, allocate and enable the controller's IRQ. */
hba_state.irq = pci_attr_r8(devind, PCI_ILR);
hba_state.hook_id = 0;
if ((r = sys_irqsetpolicy(hba_state.irq, 0, &hba_state.hook_id)) != OK)
panic("unable to register IRQ: %d", r);
if ((r = sys_irqenable(&hba_state.hook_id)) != OK)
panic("unable to enable IRQ: %d", r);
/* Reset the HBA. */
ahci_reset();
/* Enable AHCI and interrupts. */
ghc = hba_read(AHCI_HBA_GHC);
hba_write(AHCI_HBA_GHC, ghc | AHCI_HBA_GHC_AE | AHCI_HBA_GHC_IE);
/* Limit the maximum number of commands to the controller's value. */
/* Note that we currently use only one command anyway. */
cap = hba_read(AHCI_HBA_CAP);
hba_state.has_ncq = !!(cap & AHCI_HBA_CAP_SNCQ);
hba_state.has_clo = !!(cap & AHCI_HBA_CAP_SCLO);
hba_state.nr_cmds = MIN(NR_CMDS,
((cap >> AHCI_HBA_CAP_NCS_SHIFT) & AHCI_HBA_CAP_NCS_MASK) + 1);
dprintf(V_INFO, ("AHCI%u: HBA v%d.%d%d, %ld ports, %ld commands, "
"%s queuing, IRQ %d\n",
ahci_instance,
(int) (hba_read(AHCI_HBA_VS) >> 16),
(int) ((hba_read(AHCI_HBA_VS) >> 8) & 0xFF),
(int) (hba_read(AHCI_HBA_VS) & 0xFF),
((cap >> AHCI_HBA_CAP_NP_SHIFT) & AHCI_HBA_CAP_NP_MASK) + 1,
((cap >> AHCI_HBA_CAP_NCS_SHIFT) & AHCI_HBA_CAP_NCS_MASK) + 1,
hba_state.has_ncq ? "supports" : "no", hba_state.irq));
dprintf(V_INFO, ("AHCI%u: CAP %08x, CAP2 %08x, PI %08x\n",
ahci_instance, cap, hba_read(AHCI_HBA_CAP2),
hba_read(AHCI_HBA_PI)));
/* Initialize each of the implemented ports. We ignore CAP.NP. */
mask = hba_read(AHCI_HBA_PI);
for (port = 0; port < hba_state.nr_ports; port++) {
port_state[port].device = NO_DEVICE;
port_state[port].state = STATE_NO_PORT;
if (mask & (1 << port))
port_init(&port_state[port]);
}
}
/*===========================================================================*
* ahci_stop *
*===========================================================================*/
static void ahci_stop(void)
{
/* Disable AHCI, and clean up resources to the extent possible.
*/
struct port_state *ps;
int r, port;
for (port = 0; port < hba_state.nr_ports; port++) {
ps = &port_state[port];
if (ps->state != STATE_NO_PORT) {
port_stop(ps);
port_free(ps);
}
}
ahci_reset();
if ((r = vm_unmap_phys(SELF, (void *) hba_state.base,
hba_state.size)) != OK)
panic("unable to unmap HBA memory: %d", r);
if ((r = sys_irqrmpolicy(&hba_state.hook_id)) != OK)
panic("unable to deregister IRQ: %d", r);
}
/*===========================================================================*
* ahci_alarm *
*===========================================================================*/
static void ahci_alarm(clock_t stamp)
{
/* Process an alarm.
*/
/* Call the port-specific handler for each port that timed out. */
expire_timers(stamp);
}
/*===========================================================================*
* ahci_intr *
*===========================================================================*/
static void ahci_intr(unsigned int UNUSED(mask))
{
/* Process an interrupt.
*/
struct port_state *ps;
u32_t mask;
int r, port;
/* Handle an interrupt for each port that has the interrupt bit set. */
mask = hba_read(AHCI_HBA_IS);
for (port = 0; port < hba_state.nr_ports; port++) {
if (mask & (1 << port)) {
ps = &port_state[port];
port_intr(ps);
/* After processing an interrupt, wake up the device
* thread if it is suspended and now no longer busy.
*/
if ((ps->flags & (FLAG_SUSPENDED | FLAG_BUSY)) ==
FLAG_SUSPENDED)
blockdriver_mt_wakeup(ps->cmd_info[0].tid);
}
}
/* Clear the bits that we processed. */
hba_write(AHCI_HBA_IS, mask);
/* Reenable the interrupt. */
if ((r = sys_irqenable(&hba_state.hook_id)) != OK)
panic("unable to enable IRQ: %d", r);
}
/*===========================================================================*
* ahci_get_params *
*===========================================================================*/
static void ahci_get_params(void)
{
/* Retrieve and parse parameters passed to this driver, except the
* device-to-port mapping, which has to be parsed later.
*/
long v;
unsigned int i;
/* Find out which driver instance we are. */
v = 0;
(void) env_parse("instance", "d", 0, &v, 0, 255);
ahci_instance = (int) v;
/* Initialize the verbosity level. */
v = V_ERR;
(void) env_parse("ahci_verbose", "d", 0, &v, V_NONE, V_REQ);
ahci_verbose = (int) v;
/* Initialize timeout-related values. */
for (i = 0; i < sizeof(ahci_timevar) / sizeof(ahci_timevar[0]); i++) {
v = ahci_timevar[i].default_ms;
(void) env_parse(ahci_timevar[i].name, "d", 0, &v, 1,
LONG_MAX);
*ahci_timevar[i].ptr = millis_to_hz(v);
}
ahci_device_delay = millis_to_hz(DEVICE_DELAY);
ahci_device_checks = (ahci_device_timeout + ahci_device_delay - 1) /
ahci_device_delay;
}
/*===========================================================================*
* ahci_set_mapping *
*===========================================================================*/
static void ahci_set_mapping(void)
{
/* Construct a mapping from device nodes to port numbers.
*/
char key[16], val[32], *p;
unsigned int port;
int i, j;
/* Start off with a mapping that includes implemented ports only, in
* order. We choose this mapping over an identity mapping to maximize
* the chance that the user will be able to access the first MAX_DRIVES
* devices. Note that we can only do this after initializing the HBA.
*/
for (i = j = 0; i < NR_PORTS && j < MAX_DRIVES; i++)
if (port_state[i].state != STATE_NO_PORT)
ahci_map[j++] = i;
for ( ; j < MAX_DRIVES; j++)
ahci_map[j] = NO_PORT;
/* See if the user specified a custom mapping. Unlike all other
* configuration options, this is a per-instance setting.
*/
strlcpy(key, "ahci0_map", sizeof(key));
key[4] += ahci_instance;
if (env_get_param(key, val, sizeof(val)) == OK) {
/* Parse the mapping, which is assumed to be a comma-separated
* list of zero-based port numbers.
*/
p = val;
for (i = 0; i < MAX_DRIVES; i++) {
if (*p) {
port = (unsigned int) strtoul(p, &p, 0);
if (*p) p++;
ahci_map[i] = port % NR_PORTS;
}
else ahci_map[i] = NO_PORT;
}
}
/* Create a reverse mapping. */
for (i = 0; i < MAX_DRIVES; i++)
if ((j = ahci_map[i]) != NO_PORT)
port_state[j].device = i;
}
/*===========================================================================*
* sef_cb_init_fresh *
*===========================================================================*/
static int sef_cb_init_fresh(int type, sef_init_info_t *UNUSED(info))
{
/* Initialize the driver.
*/
int devind;
/* Get command line parameters. */
ahci_get_params();
/* Probe for recognized devices, skipping matches as appropriate. */
devind = ahci_probe(ahci_instance);
if (devind < 0)
panic("no matching device found");
/* Initialize the device we found. */
ahci_init(devind);
/* Create a mapping from device nodes to port numbers. */
ahci_set_mapping();
/* Announce that we are up. */
blockdriver_announce(type);
return OK;
}
/*===========================================================================*
* sef_cb_signal_handler *
*===========================================================================*/
static void sef_cb_signal_handler(int signo)
{
/* In case of a termination signal, shut down this driver.
*/
int port;
if (signo != SIGTERM) return;
/* If any ports are still opened, assume that the system is being shut
* down, and stay up until the last device has been closed.
*/
ahci_exiting = TRUE;
for (port = 0; port < hba_state.nr_ports; port++)
if (port_state[port].open_count > 0)
return;
/* If not, stop the driver and exit immediately. */
ahci_stop();
exit(0);
}
/*===========================================================================*
* sef_local_startup *
*===========================================================================*/
static void sef_local_startup(void)
{
/* Set callbacks and initialize the System Event Framework (SEF).
*/
/* Register init callbacks. */
sef_setcb_init_fresh(sef_cb_init_fresh);
/* Register signal callbacks. */
sef_setcb_signal_handler(sef_cb_signal_handler);
/* Enable support for live update. */
blockdriver_mt_support_lu();
/* Let SEF perform startup. */
sef_startup();
}
/*===========================================================================*
* ahci_portname *
*===========================================================================*/
static char *ahci_portname(struct port_state *ps)
{
/* Return a printable name for the given port. Whenever we can, print a
* "Dx" device number rather than a "Pxx" port number, because the user
* may not be aware of the mapping currently in use.
*/
static char name[] = "AHCI0-P00";
name[4] = '0' + ahci_instance;
if (ps->device == NO_DEVICE) {
name[6] = 'P';
name[7] = '0' + (ps - port_state) / 10;
name[8] = '0' + (ps - port_state) % 10;
}
else {
name[6] = 'D';
name[7] = '0' + ps->device;
name[8] = 0;
}
return name;
}
/*===========================================================================*
* ahci_map_minor *
*===========================================================================*/
static struct port_state *ahci_map_minor(devminor_t minor, struct device **dvp)
{
/* Map a minor device number to a port and a pointer to the partition's
* device structure. Return NULL if this minor device number does not
* identify an actual device.
*/
struct port_state *ps;
int port;
ps = NULL;
if (minor >= 0 && minor < NR_MINORS) {
port = ahci_map[minor / DEV_PER_DRIVE];
if (port == NO_PORT)
return NULL;
ps = &port_state[port];
*dvp = &ps->part[minor % DEV_PER_DRIVE];
}
else if ((unsigned) (minor -= MINOR_d0p0s0) < NR_SUBDEVS) {
port = ahci_map[minor / SUB_PER_DRIVE];
if (port == NO_PORT)
return NULL;
ps = &port_state[port];
*dvp = &ps->subpart[minor % SUB_PER_DRIVE];
}
return ps;
}
/*===========================================================================*
* ahci_part *
*===========================================================================*/
static struct device *ahci_part(devminor_t minor)
{
/* Return a pointer to the partition information structure of the given
* minor device.
*/
struct device *dv;
if (ahci_map_minor(minor, &dv) == NULL)
return NULL;
return dv;
}
/*===========================================================================*
* ahci_open *
*===========================================================================*/
static int ahci_open(devminor_t minor, int access)
{
/* Open a device.
*/
struct port_state *ps;
int r;
ps = ahci_get_port(minor);
/* Only one open request can be processed at a time, due to the fact
* that it is an exclusive operation. The thread that handles this call
* can therefore freely register itself at slot zero.
*/
ps->cmd_info[0].tid = blockdriver_mt_get_tid();
/* If we are still in the process of initializing this port or device,
* wait for completion of that phase first.
*/
if (ps->flags & FLAG_BUSY)
port_wait(ps);
/* The device may only be opened if it is now properly functioning. */
if (ps->state != STATE_GOOD_DEV)
return ENXIO;
/* Some devices may only be opened in read-only mode. */
if ((ps->flags & FLAG_READONLY) && (access & BDEV_W_BIT))
return EACCES;
if (ps->open_count == 0) {
/* The first open request. Clear the barrier flag, if set. */
ps->flags &= ~FLAG_BARRIER;
/* Recheck media only when nobody is using the device. */
if ((ps->flags & FLAG_ATAPI) &&
(r = atapi_check_medium(ps, 0)) != OK)
return r;
/* After rechecking the media, the partition table must always
* be read. This is also a convenient time to do it for
* nonremovable devices. Start by resetting the partition
* tables and setting the working size of the entire device.
*/
memset(ps->part, 0, sizeof(ps->part));
memset(ps->subpart, 0, sizeof(ps->subpart));
ps->part[0].dv_size = ps->lba_count * ps->sector_size;
partition(&ahci_dtab, ps->device * DEV_PER_DRIVE, P_PRIMARY,
!!(ps->flags & FLAG_ATAPI));
blockdriver_mt_set_workers(ps->device, ps->queue_depth);
}
else {
/* If the barrier flag is set, deny new open requests until the
* device is fully closed first.
*/
if (ps->flags & FLAG_BARRIER)
return ENXIO;
}
ps->open_count++;
return OK;
}
/*===========================================================================*
* ahci_close *
*===========================================================================*/
static int ahci_close(devminor_t minor)
{
/* Close a device.
*/
struct port_state *ps;
int port;
ps = ahci_get_port(minor);
/* Decrease the open count. */
if (ps->open_count <= 0) {
dprintf(V_ERR, ("%s: closing already-closed port\n",
ahci_portname(ps)));
return EINVAL;
}
ps->open_count--;
if (ps->open_count > 0)
return OK;
/* The device is now fully closed. That also means that the threads for
* this device are not needed anymore, so we reduce the count to one.
*/
blockdriver_mt_set_workers(ps->device, 1);
if (ps->state == STATE_GOOD_DEV && !(ps->flags & FLAG_BARRIER)) {
dprintf(V_INFO, ("%s: flushing write cache\n",
ahci_portname(ps)));
(void) gen_flush_wcache(ps);
}
/* If the entire driver has been told to terminate, check whether all
* devices are now closed. If so, tell libblockdriver to quit after
* replying to the close request.
*/
if (ahci_exiting) {
for (port = 0; port < hba_state.nr_ports; port++)
if (port_state[port].open_count > 0)
break;
if (port == hba_state.nr_ports) {
ahci_stop();
blockdriver_mt_terminate();
}
}
return OK;
}
/*===========================================================================*
* ahci_transfer *
*===========================================================================*/
static ssize_t ahci_transfer(devminor_t minor, int do_write, u64_t position,
endpoint_t endpt, iovec_t *iovec, unsigned int count, int flags)
{
/* Perform data transfer on the selected device.
*/
struct port_state *ps;
struct device *dv;
u64_t pos, eof;
ps = ahci_get_port(minor);
dv = ahci_part(minor);
if (ps->state != STATE_GOOD_DEV || (ps->flags & FLAG_BARRIER))
return EIO;
if (count > NR_IOREQS)
return EINVAL;
/* Check for basic end-of-partition condition: if the start position of
* the request is outside the partition, return success immediately.
* The size of the request is obtained, and possibly reduced, later.
*/
if (position >= dv->dv_size)
return OK;
pos = dv->dv_base + position;
eof = dv->dv_base + dv->dv_size;
return port_transfer(ps, pos, eof, endpt, (iovec_s_t *) iovec, count,
do_write, flags);
}
/*===========================================================================*
* ahci_ioctl *
*===========================================================================*/
static int ahci_ioctl(devminor_t minor, unsigned long request,
endpoint_t endpt, cp_grant_id_t grant, endpoint_t UNUSED(user_endpt))
{
/* Process I/O control requests.
*/
struct port_state *ps;
int r, val;
ps = ahci_get_port(minor);
switch (request) {
case DIOCEJECT:
if (ps->state != STATE_GOOD_DEV || (ps->flags & FLAG_BARRIER))
return EIO;
if (!(ps->flags & FLAG_ATAPI))
return EINVAL;
return atapi_load_eject(ps, 0, FALSE /*load*/);
case DIOCOPENCT:
return sys_safecopyto(endpt, grant, 0,
(vir_bytes) &ps->open_count, sizeof(ps->open_count));
case DIOCFLUSH:
if (ps->state != STATE_GOOD_DEV || (ps->flags & FLAG_BARRIER))
return EIO;
return gen_flush_wcache(ps);
case DIOCSETWC:
if (ps->state != STATE_GOOD_DEV || (ps->flags & FLAG_BARRIER))
return EIO;
if ((r = sys_safecopyfrom(endpt, grant, 0, (vir_bytes) &val,
sizeof(val))) != OK)
return r;
return gen_set_wcache(ps, val);
case DIOCGETWC:
if (ps->state != STATE_GOOD_DEV || (ps->flags & FLAG_BARRIER))
return EIO;
if ((r = gen_get_wcache(ps, &val)) != OK)
return r;
return sys_safecopyto(endpt, grant, 0, (vir_bytes) &val,
sizeof(val));
}
return ENOTTY;
}
/*===========================================================================*
* ahci_device *
*===========================================================================*/
static int ahci_device(devminor_t minor, device_id_t *id)
{
/* Map a minor device number to a device ID.
*/
struct port_state *ps;
struct device *dv;
if ((ps = ahci_map_minor(minor, &dv)) == NULL)
return ENXIO;
*id = ps->device;
return OK;
}
/*===========================================================================*
* ahci_get_port *
*===========================================================================*/
static struct port_state *ahci_get_port(devminor_t minor)
{
/* Get the port structure associated with the given minor device.
* Called only from worker threads, so the minor device is already
* guaranteed to map to a port.
*/
struct port_state *ps;
struct device *dv;
if ((ps = ahci_map_minor(minor, &dv)) == NULL)
panic("device mapping for minor %d disappeared", minor);
return ps;
}
/*===========================================================================*
* main *
*===========================================================================*/
int main(int argc, char **argv)
{
/* Driver task.
*/
env_setargs(argc, argv);
sef_local_startup();
blockdriver_mt_task(&ahci_dtab);
return 0;
}
| 30.947715 | 79 | 0.591491 | [
"vector"
] |
e4d34e1f0f543a4b80435541750e449feed8290b | 5,554 | h | C | hrwros_ws/devel/.private/hrwros_msgs/include/hrwros_msgs/CounterWithDelayResult.h | AshfakYeafi/ros | 7895302251088b7945e359f60a9c617e5170a72e | [
"MIT"
] | null | null | null | hrwros_ws/devel/.private/hrwros_msgs/include/hrwros_msgs/CounterWithDelayResult.h | AshfakYeafi/ros | 7895302251088b7945e359f60a9c617e5170a72e | [
"MIT"
] | null | null | null | hrwros_ws/devel/.private/hrwros_msgs/include/hrwros_msgs/CounterWithDelayResult.h | AshfakYeafi/ros | 7895302251088b7945e359f60a9c617e5170a72e | [
"MIT"
] | null | null | null | // Generated by gencpp from file hrwros_msgs/CounterWithDelayResult.msg
// DO NOT EDIT!
#ifndef HRWROS_MSGS_MESSAGE_COUNTERWITHDELAYRESULT_H
#define HRWROS_MSGS_MESSAGE_COUNTERWITHDELAYRESULT_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace hrwros_msgs
{
template <class ContainerAllocator>
struct CounterWithDelayResult_
{
typedef CounterWithDelayResult_<ContainerAllocator> Type;
CounterWithDelayResult_()
: result_message() {
}
CounterWithDelayResult_(const ContainerAllocator& _alloc)
: result_message(_alloc) {
(void)_alloc;
}
typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _result_message_type;
_result_message_type result_message;
typedef boost::shared_ptr< ::hrwros_msgs::CounterWithDelayResult_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::hrwros_msgs::CounterWithDelayResult_<ContainerAllocator> const> ConstPtr;
}; // struct CounterWithDelayResult_
typedef ::hrwros_msgs::CounterWithDelayResult_<std::allocator<void> > CounterWithDelayResult;
typedef boost::shared_ptr< ::hrwros_msgs::CounterWithDelayResult > CounterWithDelayResultPtr;
typedef boost::shared_ptr< ::hrwros_msgs::CounterWithDelayResult const> CounterWithDelayResultConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::hrwros_msgs::CounterWithDelayResult_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::hrwros_msgs::CounterWithDelayResult_<ContainerAllocator> >::stream(s, "", v);
return s;
}
template<typename ContainerAllocator1, typename ContainerAllocator2>
bool operator==(const ::hrwros_msgs::CounterWithDelayResult_<ContainerAllocator1> & lhs, const ::hrwros_msgs::CounterWithDelayResult_<ContainerAllocator2> & rhs)
{
return lhs.result_message == rhs.result_message;
}
template<typename ContainerAllocator1, typename ContainerAllocator2>
bool operator!=(const ::hrwros_msgs::CounterWithDelayResult_<ContainerAllocator1> & lhs, const ::hrwros_msgs::CounterWithDelayResult_<ContainerAllocator2> & rhs)
{
return !(lhs == rhs);
}
} // namespace hrwros_msgs
namespace ros
{
namespace message_traits
{
template <class ContainerAllocator>
struct IsFixedSize< ::hrwros_msgs::CounterWithDelayResult_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::hrwros_msgs::CounterWithDelayResult_<ContainerAllocator> const>
: FalseType
{ };
template <class ContainerAllocator>
struct IsMessage< ::hrwros_msgs::CounterWithDelayResult_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::hrwros_msgs::CounterWithDelayResult_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::hrwros_msgs::CounterWithDelayResult_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::hrwros_msgs::CounterWithDelayResult_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::hrwros_msgs::CounterWithDelayResult_<ContainerAllocator> >
{
static const char* value()
{
return "be8a5eb8699d93f379b287dcfc6e376c";
}
static const char* value(const ::hrwros_msgs::CounterWithDelayResult_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0xbe8a5eb8699d93f3ULL;
static const uint64_t static_value2 = 0x79b287dcfc6e376cULL;
};
template<class ContainerAllocator>
struct DataType< ::hrwros_msgs::CounterWithDelayResult_<ContainerAllocator> >
{
static const char* value()
{
return "hrwros_msgs/CounterWithDelayResult";
}
static const char* value(const ::hrwros_msgs::CounterWithDelayResult_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::hrwros_msgs::CounterWithDelayResult_<ContainerAllocator> >
{
static const char* value()
{
return "# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n"
"string result_message # Result message: simple string message for the result.\n"
;
}
static const char* value(const ::hrwros_msgs::CounterWithDelayResult_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::hrwros_msgs::CounterWithDelayResult_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.result_message);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct CounterWithDelayResult_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::hrwros_msgs::CounterWithDelayResult_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::hrwros_msgs::CounterWithDelayResult_<ContainerAllocator>& v)
{
s << indent << "result_message: ";
Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.result_message);
}
};
} // namespace message_operations
} // namespace ros
#endif // HRWROS_MSGS_MESSAGE_COUNTERWITHDELAYRESULT_H
| 28.192893 | 166 | 0.777638 | [
"vector"
] |
e4d52e19bcc4039369365ad27be55747c972c909 | 18,987 | c | C | util/Cache.c | SirWumpus/libsnert | 087968a94df77bf0685749b678258e7987b889c6 | [
"BSD-2-Clause"
] | null | null | null | util/Cache.c | SirWumpus/libsnert | 087968a94df77bf0685749b678258e7987b889c6 | [
"BSD-2-Clause"
] | null | null | null | util/Cache.c | SirWumpus/libsnert | 087968a94df77bf0685749b678258e7987b889c6 | [
"BSD-2-Clause"
] | null | null | null | /*
* Cache.h
*
* Cache API
*
* An object that maps keys to values. A Cache cannot contain
* duplicate keys; each non-null key can map to at most one non-null
* value. Similar to Java's abstract Dictionary class.
*
* Copyright 2001, 2006 by Anthony Howe. All rights reserved.
*/
#include <com/snert/lib/version.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <com/snert/lib/io/posix.h>
#include <com/snert/lib/type/Data.h>
#include <com/snert/lib/type/Hash.h>
#include <com/snert/lib/util/Cache.h>
#include <com/snert/lib/util/Properties.h>
#include <com/snert/lib/util/Text.h>
#if defined(HAVE_SYSLOG_H) && ! defined(__MINGW32__)
# include <syslog.h>
#else
# include <com/snert/lib/io/Log.h>
#endif
#ifdef DEBUG_MALLOC
# include <com/snert/lib/util/DebugMalloc.h>
#endif
#define REF_CACHE(v) ((Cache)(v))
/***********************************************************************
*** Class variables.
***********************************************************************/
static int debug = 0;
/***********************************************************************
*** Hash instance methods
***********************************************************************/
static void
CacheHashDestroy(void *self)
{
HashDestroy(REF_CACHE(self)->_cache);
free(REF_CACHE(self)->_name);
free(self);
}
static Data
CacheHashGet(Cache self, Data key)
{
Object value = HashGet(self->_cache, key);
if (value == NULL)
return NULL;
return value->clone(value);
}
static long
CacheHashSize(Cache self)
{
return HashSize(self->_cache);
}
static int
CacheHashIsEmpty(Cache self)
{
return CacheHashSize(self) == 0;
}
static int
CacheHashPut(Cache self, Data key, Data value)
{
if ((key = key->clone(key)) == NULL)
goto error0;
if ((value = value->clone(value)) == NULL)
goto error1;
if (HashPut(self->_cache, key, value))
goto error2;
return 0;
error2:
value->destroy(value);
error1:
key->destroy(key);
error0:
return -1;
}
static int
CacheHashRemove(Cache self, Data key)
{
return HashRemove(self->_cache, key);
}
static int
CacheHashRemoveAll(Cache self)
{
HashRemoveAll(self->_cache);
return 0;
}
static int
CacheHashSync(Cache self)
{
/* Do nothing. */
return 0;
}
static int
CacheHashWalk(Cache self, int (*function)(void *key, void *value, void *data), void *data)
{
return HashWalk(self->_cache, function, data);
}
/***********************************************************************
*** Properties instance methods
***********************************************************************/
static Data
CachePropGet(Cache self, Data key)
{
Data value = PropertiesGetData(self->_cache, key);
if (value == NULL)
return NULL;
return value->clone(value);
}
static long
CachePropSize(Cache self)
{
return PropertiesSize(self->_cache);
}
static int
CachePropIsEmpty(Cache self)
{
return PropertiesSize(self->_cache) == 0;
}
static int
CachePropPut(Cache self, Data key, Data value)
{
return PropertiesSetData(self->_cache, key, value);
}
static int
CachePropRemove(Cache self, Data key)
{
return PropertiesRemoveData(self->_cache, key);
}
static int
CachePropRemoveAll(Cache self)
{
PropertiesRemoveAll(self->_cache);
return 0;
}
static int
CachePropSync(Cache self)
{
return PropertiesSave(self->_cache, self->_name);
}
static int
CachePropWalk(Cache self, int (*function)(void *key, void *value, void *data), void *data)
{
return PropertiesWalk(self->_cache, function, data);
}
static void
CachePropDestroy(void *self)
{
(void) CachePropSync(self);
PropertiesDestroy(REF_CACHE(self)->_cache);
free(REF_CACHE(self)->_name);
free(self);
}
/***********************************************************************
*** Berkeley DB instance methods
***********************************************************************/
#include <com/snert/lib/berkeley_db.h>
#if defined(HAVE_DB_H)
# define DEFAULT_HANDLER "bdb"
#else
# define DEFAULT_HANDLER "flatfile"
#endif
#ifdef HAVE_DB_H
#ifdef ENABLE_FILE_LOCKING
static int
CacheBdbLock(Cache self, int mode)
{
mode = mode == 0 ? LOCK_SH : LOCK_EX;
/* Wait until we get the file lock. */
do
errno = 0;
while (flock(self->_lockfd, mode) && errno == EINTR);
return -(errno != 0);
}
static int
CacheBdbUnlock(Cache self)
{
return flock(self->_lockfd, LOCK_UN);
}
#else
# define CacheBdbLock(c, l)
# define CacheBdbUnlock(c)
#endif
static int
CacheBdbOpen(Cache self, const char *name)
{
#if DB_VERSION_MAJOR == 1
# ifdef IGNORE_CORRUPT_CACHE_ISSUE_WITH_DB_185
DB *db;
if ((db = dbopen(name, O_CREAT|O_RDWR, 0660, DB_HASH, NULL)) == (DB *) 0) {
syslog(LOG_ERR, "failed to open \"%s\": %s (%d)", name, strerror(errno), errno);
return -1;
}
if ((self->_lockfd = db->fd(db)) == -1) {
syslog(LOG_ERR, "get lock fd error \"%s\": %s (%d)", name, strerror(errno), errno);
db->close(db);
return -1;
}
self->_cache = db;
# else
syslog(LOG_ERR, "LibSnert Cache API no longer supports Berkeley DB 1.85");
return -1;
# endif
#else
{
int rc;
DB *db;
#ifdef THIS_CODE_PROBLEMATIC
{
rc = db_create(&db, NULL, 0);
if (rc != 0) {
syslog(LOG_ERR, "db_create() error: %s", db_strerror(rc));
return -1;
}
struct stat sb;
if (stat(name, &sb) == 0) {
rc = db->verify(db, name, NULL, NULL, 0);
if (rc == DB_VERIFY_BAD) {
syslog(LOG_ERR, "database \"%s\" corrupted, starting from zero", name);
if (unlink(name)) {
syslog(LOG_ERR, "failed to remove \"%s\"", name);
return -1;
}
}
/* BDB 4.2.52 documentation:
*
* The DB handle may not be accessed again after
* DB->verify is called, regardless of its return.
*
* In previous releases, applications calling the DB->verify
* method had to explicitly discard the DB handle by calling
* the DB->close method. Further, using the DB handle in other
* ways after calling the DB->verify method was not prohibited
* by the documentation, although such use was likely to lead
* to problems.
*
* For consistency with other Berkeley DB methods, DB->verify
* method has been documented in the current release as a DB
* handle destructor. Applications using the DB handle in any
* way (including calling the DB->close method) after calling
* DB->verify should be updated to make no further use of any
* kind of the DB handle after DB->verify returns.
*/
# if DB_VERSION_MAJOR < 4 || DB_VERSION_MINOR < 2
(void) db->close(db, 0);
# endif
}
}
#endif
rc = db_create(&db, (DB_ENV *) 0, 0);
if (rc != 0) {
syslog(LOG_ERR, "db_create() error: %s", db_strerror(rc));
return -1;
}
/*
* Specify the hash bucket density. The suggested rule given by the
* Berkely DB documentation is:
*
* pagesize - 32
* ---------------------------------------- = density
* average_key_size + average_data_size + 8
*
* So pagesize is typically the disk block size, which for Linux
* appears to be 4096 bytes. The average_data_size is sizeof CacheEntry
* and average_key_size is the average email address length, which we'll
* guess is 50 bytes. So...
*
* (4096 - 32) / (50 + 8 + 8) = 61.57...
*
* This seems rather conservative. Now from observation of db_stat
* snapshot from 3 different mail servers (slow, moderate, heavy)
* running at least a week:
*
* keys / buckets = keys_per_bucket (density)
*
* slow: 2526 / 25 = 101,04
* moderate: 49357 / 432 = 114,2523148...
* heavy: 204599 / 2500 = 81,8396
*
* So reworking the above rule to get average_key_size:
*
* (pagesize - 32) - (average_data_size + 8) * keys_per_bucket
* ----------------------------------------------------------- = average_key_size
* keys_per_bucket
*
* slow: 24,237623762376237623762376237624
* moderate: 19,649122807017543859649122807018
* heavy: 34,172839506172839506172839506173
*
* Now if we consider an average_key_size of 38, that is slightly larger
* than the value from the heavy use mail server, then we get a density of:
*
* 75,259259259259259259259259259259
*
* This looks good to me.
*/
(void) db->set_h_ffactor(db, 75);
rc = db->open(db, DBTXN_ROAR name, NULL, DB_HASH, DB_CREATE|DB_NOMMAP, 0);
if (rc != 0) {
syslog(LOG_ERR, "failed to create or open \"%s\": %s", name, db_strerror(rc));
return -1;
}
if (db->fd(db, &self->_lockfd)) {
syslog(LOG_ERR, "get lock fd error \"%s\": %s", name, db_strerror(rc));
(void) db->close(db, 0);
return -1;;
}
self->_cache = db;
}
#endif
return 0;
}
static void
CacheBdbDestroy(void *selfless)
{
Cache self = (Cache) selfless;
if (self != NULL) {
DB *db = (DB *) self->_cache;
if (db != NULL)
#if DB_VERSION_MAJOR == 1
db->close(db);
#else
db->close(db, 0);
#endif
free(self->_name);
free(self);
}
}
static Data
CacheBdbGet(Cache self, Data key)
{
Data value = NULL;
DBT dkey, dvalue;
DB *db = (DB *) self->_cache;
if (db == NULL || key == NULL) {
errno = EFAULT;
goto error0;
}
memset(&dkey, 0, sizeof (dkey));
memset(&dvalue, 0, sizeof (dvalue));
dkey.data = key->base(key);
dkey.size = key->length(key);
CacheBdbLock(self, 0);
#if DB_VERSION_MAJOR == 1
if (db->get(db, &dkey, &dvalue, 0) != 0)
goto error1;
/* Because BDB 1.85 manages the memory assignment of returned
* values, we have to create Data object which is a copy of
* the value returned, as it will change on the next call.
*/
if ((value = DataCreateCopyBytes(dvalue.data, dvalue.size)) == NULL)
goto error1;
#else
dvalue.flags = DB_DBT_MALLOC;
if (db->get(db, NULL, &dkey, &dvalue, 0) != 0)
goto error1;
/* BDB 3.2 or better can be told to allocate the memory for us,
* but it then becomes our responsiblity, so here we create a
* Data object and simply assign the value return from db->get().
* When we destroy the Data object, it will be released.
*/
if ((value = DataCreateWithBytes(dvalue.data, dvalue.size)) == NULL)
free(dvalue.data);
#endif
error1:
CacheBdbUnlock(self);
error0:
return value;
}
static int
CacheBdbPut(Cache self, Data key, Data value)
{
int rc = -1;
DBT dkey, dvalue;
DB *db = (DB *) self->_cache;
if (db == NULL || key == NULL || value == NULL) {
errno = EFAULT;
goto error0;
}
memset(&dkey, 0, sizeof (dkey));
memset(&dvalue, 0, sizeof (dvalue));
dkey.data = key->base(key);
dkey.size = key->length(key);
dvalue.data = value->base(value);
dvalue.size = value->length(value);
CacheBdbLock(self, 1);
#if DB_VERSION_MAJOR == 1
if (db->put(db, &dkey, &dvalue, 0) != 0)
goto error1;
#else
if (db->put(db, (DB_TXN *) 0, &dkey, &dvalue, 0) != 0)
goto error1;
#endif
#ifdef ALWAYS_SYNC
/* We must ALWAYS sync the database to disk, because there
* is no clean way to shutdown a milter (quickly) such that
* the atexit() handler is called in order to properly close
* the database. The alternative is to use Berkely DB
* transactions only available in 4.1.
*/
rc = db->sync(db, 0);
#else
rc = 0;
#endif
error1:
CacheBdbUnlock(self);
error0:
return rc;
}
static int
CacheBdbRemove(Cache self, Data key)
{
int rc = -1;
DBT dkey;
DB *db = (DB *) self->_cache;
if (db == NULL || key == NULL) {
errno = EFAULT;
goto error0;
}
memset(&dkey, 0, sizeof (dkey));
dkey.data = key->base(key);
dkey.size = key->length(key);
CacheBdbLock(self, 1);
#if DB_VERSION_MAJOR == 1
if (db->del(db, &dkey, 0) != 0)
goto error1;
#else
if (db->del(db, NULL, &dkey, 0) != 0)
goto error1;
#endif
rc = 0;
error1:
CacheBdbUnlock(self);
error0:
return rc;
}
static int
CacheBdbSync(Cache self)
{
int rc;
DB *db = (DB *) self->_cache;
if (db == NULL) {
errno = EFAULT;
return -1;
}
CacheBdbLock(self, 1);
rc = db->sync(db, 0);
CacheBdbUnlock(self);
return rc;
}
static int
CacheBdbWalk(Cache self, int (*function)(void *key, void *value, void *data), void *data)
{
int rc = -1;
DBT dkey, dvalue;
struct data key, value;
DB *db = (DB *) self->_cache;
#if DB_VERSION_MAJOR == 1
unsigned next;
#else
DBC *cursor;
#endif
if (db == NULL || function == NULL) {
errno = EFAULT;
goto error0;
}
DataInit(&key);
DataInit(&value);
memset(&dkey, 0, sizeof (dkey));
memset(&dvalue, 0, sizeof (dvalue));
#ifndef NDEBUG
if (debug)
syslog(LOG_DEBUG, "CacheBdbWalk(): get first cursor entry");
#endif
#if DB_VERSION_MAJOR == 1
next = R_FIRST;
while (db->seq(db, &dkey, &dvalue, next) == 0) {
next = R_NEXT;
#else
dkey.flags = DB_DBT_REALLOC;
dvalue.flags = DB_DBT_REALLOC;
{
int err;
if ((err = db->cursor(db, NULL, &cursor, 0)) != 0) {
syslog(LOG_ERR, "CacheBdbWalk(): failed to setup cursor: %s", db_strerror(err));
goto error0;
}
}
CacheBdbLock(self, 1);
while (cursor->c_get(cursor, &dkey, &dvalue, DB_NEXT) == 0) {
#endif
if (dkey.data == NULL) {
syslog(LOG_ERR, "CacheBdbWalk(): c_get returned a NULL key");
goto error1;
}
/* Convert from DBT to Data object. */
key._base = dkey.data;
key._length = dkey.size;
if (dvalue.data == NULL) {
syslog(LOG_ERR, "CacheBdbWalk(): c_get returned a NULL value");
goto error1;
}
/* Convert from DBT to Data object. */
value._base = dvalue.data;
value._length = dvalue.size;
#ifndef NDEBUG
if (debug)
syslog(LOG_DEBUG, "CacheBdbWalk(): call-back walk function");
#endif
switch ((*function)(&key, &value, data)) {
case 0:
#ifndef NDEBUG
if (debug)
syslog(LOG_DEBUG, "CacheBdbWalk(): stop walking");
#endif
goto stop;
case -1:
#ifndef NDEBUG
if (debug)
syslog(LOG_DEBUG, "CacheBdbWalk(): delete entry at cursor");
#endif
#if DB_VERSION_MAJOR == 1
# ifdef TRIED_THIS_ALREADY
if (db->del(db, &dkey, 0) != 0)
# else
if (db->del(db, NULL, R_CURSOR) != 0)
# endif
#else
if (cursor->c_del(cursor, 0) != 0)
#endif
goto error1;
break;
}
#ifndef NDEBUG
if (debug)
syslog(LOG_DEBUG, "CacheBdbWalk(): get next cursor entry");
#endif
}
stop:
rc = 0;
error1:
CacheBdbUnlock(self);
#if DB_VERSION_MAJOR > 1
free(dkey.data);
free(dvalue.data);
(void) cursor->c_close(cursor);
#endif
error0:
return rc;
}
static int
CacheBdbRemoveAnyEntry(void *key, void *value, void *data)
{
return -1;
}
static int
CacheBdbRemoveAll(Cache self)
{
return CacheBdbWalk(self, CacheBdbRemoveAnyEntry, NULL);
}
static int
CacheBdbCount(void *key, void *value, void *data)
{
if (key != NULL && data != NULL)
(*(long *) data)++;
return 1;
}
static long
CacheBdbSize(Cache self)
{
long count = 0;
(void) CacheBdbWalk(self, CacheBdbCount, &count);
return count;
}
static int
CacheBdbIsEmpty(Cache self)
{
return CacheBdbSize(self) == 0;
}
#endif /* HAVE_DB_H */
/***********************************************************************
*** Class methods
***********************************************************************/
void
CacheSetDebug(int flag)
{
debug = flag;
}
Cache
CacheCreate(const char *handler, const char *name)
{
Cache cache;
if (handler == NULL || *handler == '\0')
goto error0;
if ((cache = malloc(sizeof (*cache))) == NULL)
goto error0;
if ((cache->_name = strdup(name)) == NULL)
goto error1;
ObjectInit(cache);
cache->objectName = "Cache";
cache->objectMethodCount += 9;
cache->objectSize = sizeof (*cache);
cache->setDebug = CacheSetDebug;
if (TextInsensitiveCompare(handler, "bdb") == 0) {
#if defined(HAVE_DB_H)
CacheBdbOpen(cache, name);
cache->destroy = CacheBdbDestroy;
cache->get = CacheBdbGet;
cache->isEmpty = CacheBdbIsEmpty;
cache->put = CacheBdbPut;
cache->remove = CacheBdbRemove;
cache->removeAll = CacheBdbRemoveAll;
cache->size = CacheBdbSize;
cache->sync = CacheBdbSync;
cache->walk = CacheBdbWalk;
#else
goto error2;
#endif
} else if (TextInsensitiveCompare(handler, "flatfile") == 0) {
cache->_cache = PropertiesCreate();
if (PropertiesLoad(cache->_cache, name)) {
FILE *fp;
if (errno != ENOENT)
goto error3;
if ((fp = fopen(name, "a")) == NULL)
goto error3;
(void) fclose(fp);
}
cache->destroy = CachePropDestroy;
cache->get = CachePropGet;
cache->isEmpty = CachePropIsEmpty;
cache->put = CachePropPut;
cache->remove = CachePropRemove;
cache->removeAll = CachePropRemoveAll;
cache->size = CachePropSize;
cache->sync = CachePropSync;
cache->walk = CachePropWalk;
} else if (TextInsensitiveCompare(handler, "hash") == 0) {
cache->_cache = HashCreate();
cache->destroy = CacheHashDestroy;
cache->get = CacheHashGet;
cache->isEmpty = CacheHashIsEmpty;
cache->put = CacheHashPut;
cache->remove = CacheHashRemove;
cache->removeAll = CacheHashRemoveAll;
cache->size = CacheHashSize;
cache->sync = CacheHashSync;
cache->walk = CacheHashWalk;
}
if (cache->_cache == NULL)
goto error2;
return cache;
error3:
cache->destroy(cache);
error2:
free(cache->_name);
error1:
free(cache);
error0:
return NULL;
}
/***********************************************************************
*** Test
***********************************************************************/
#ifdef TEST
#include <stdio.h>
#include <com/snert/lib/version.h>
#ifdef USE_DEBUG_MALLOC
# define WITHOUT_SYSLOG 1
# include <com/snert/lib/io/Log.h>
# include <com/snert/lib/util/DebugMalloc.h>
#endif
void
isNotNull(void *ptr)
{
if (ptr == NULL) {
printf("NULL\n");
exit(1);
}
printf("OK\n");
}
int
printKeyValue(void *key, void *value, void *data)
{
(*(long *) data)++;
printf("count=%ld %s=%s\n", *(long *) data, ((Data) key)->_base, ((Data) value)->_base);
return 1;
}
void
TestCache(Cache cache)
{
long count;
Data k, v, x;
char key[40], value[40];
printf("size=%ld\n", count = cache->size(cache));
snprintf(key, sizeof (key), "key%ld", count);
printf("new key=%s...", key);
isNotNull(k = DataCreateCopyString(key));
snprintf(value, sizeof (value), "value%ld", count);
printf("new value=%s...", value);
isNotNull(v = DataCreateCopyString(value));
printf("put...%s\n", cache->put(cache, k, v) ? "FAIL" : "OK");
printf("get...");
isNotNull(x = cache->get(cache, k));
printf("x->length=%ld v->length=%ld\n", x->length(x), v->length(v));
printf("equals...%s\n", x->equals(x, v) ? "OK" : "FAIL");
k->destroy(k);
v->destroy(v);
count = 0;
printf("walk...\n");
cache->walk(cache, printKeyValue, &count);
printf("count equals size...%s\n", count != cache->size(cache) ? "FAIL" : "OK");
printf("sync...%s\n", cache->sync(cache) ? "FAIL" : "OK");
printf("destroy\n");
cache->destroy(cache);
}
int
main(int argc, char **argv)
{
Cache a;
printf("\n--Cache--\n");
printf("create default cache...");
isNotNull((a = CacheCreate(NULL, "cache.default")));
TestCache(a);
printf("\ncreate flat file cache...");
isNotNull(a = CacheCreate("flatfile", "cache.properties"));
TestCache(a);
printf("\ncreate hash cache...");
isNotNull(a = CacheCreate("hash", "cache.hash"));
TestCache(a);
printf("\ncreate bdb cache...");
if ((a = CacheCreate("bdb", "cache.bdb")) == NULL) {
printf("FAIL (no BDB support maybe)\n");
} else {
printf("OK\n");
TestCache(a);
}
printf("\n--DONE--\n");
return 0;
}
#endif /* TEST */
| 21.333708 | 90 | 0.62843 | [
"object"
] |
e4d89da930f1267edfa8a499168f8387c71984ff | 5,439 | h | C | CalibCalorimetry/HcalPlugins/src/HcalHardcodeCalibrations.h | NTrevisani/cmssw | a212a27526f34eb9507cf8b875c93896e6544781 | [
"Apache-2.0"
] | 1 | 2021-01-04T10:25:39.000Z | 2021-01-04T10:25:39.000Z | CalibCalorimetry/HcalPlugins/src/HcalHardcodeCalibrations.h | NTrevisani/cmssw | a212a27526f34eb9507cf8b875c93896e6544781 | [
"Apache-2.0"
] | 7 | 2016-07-17T02:34:54.000Z | 2019-08-13T07:58:37.000Z | CalibCalorimetry/HcalPlugins/src/HcalHardcodeCalibrations.h | NTrevisani/cmssw | a212a27526f34eb9507cf8b875c93896e6544781 | [
"Apache-2.0"
] | 2 | 2019-09-27T08:33:22.000Z | 2019-11-14T10:52:30.000Z | //
// Original Author: Fedor Ratnikov Oct 21, 2005
//
// ESSource to generate default HCAL calibration objects
//
#include <map>
#include <string>
#include "FWCore/Framework/interface/ESProducer.h"
#include "FWCore/Framework/interface/EventSetupRecordIntervalFinder.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/ParameterSet/interface/ParameterSetDescription.h"
#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h"
#include "Geometry/CaloTopology/interface/HcalTopology.h"
#include "CondFormats/HcalObjects/interface/AllObjects.h"
#include "CalibCalorimetry/HcalAlgos/interface/HBHERecalibration.h"
#include "CondFormats/DataRecord/interface/HcalTPParametersRcd.h"
#include "DataFormats/HcalCalibObjects/interface/HFRecalibration.h"
#include "CalibCalorimetry/HcalAlgos/interface/HcalDbHardcode.h"
class ParameterSet;
class HcalPedestalsRcd;
class HcalPedestalWidthsRcd;
class HcalGainsRcd;
class HcalGainWidthsRcd;
class HcalQIEDataRcd;
class HcalQIETypesRcd;
class HcalChannelQualityRcd;
class HcalElectronicsMapRcd;
class HcalRespCorrsRcd;
class HcalZSThresholdsRcd;
class HcalL1TriggerObjectsRcd;
class HcalTimeCorrsRcd;
class HcalLUTCorrsRcd;
class HcalPFCorrsRcd;
class HcalValidationCorrsRcd;
class HcalLutMetadataRcd;
class HcalDcsRcd;
class HcalDcsMapRcd;
class HcalRecoParamsRcd;
class HcalLongRecoParamsRcd;
class HcalZDCLowGainFractionsRcd;
class HcalMCParamsRcd;
class HcalFlagHFDigiTimeParamsRcd;
class HcalTimingParamsRcd;
class HcalFrontEndMapRcd;
class HcalSiPMParametersRcd;
class HcalSiPMCharacteristicsRcd;
class HcalTPChannelParametersRcd;
class HcalTPParaamersRcd;
class HcalHardcodeCalibrations : public edm::ESProducer, public edm::EventSetupRecordIntervalFinder {
public:
HcalHardcodeCalibrations(const edm::ParameterSet&);
~HcalHardcodeCalibrations() override;
void produce(){};
static void fillDescriptions(edm::ConfigurationDescriptions& descriptions);
protected:
void setIntervalFor(const edm::eventsetup::EventSetupRecordKey&,
const edm::IOVSyncValue&,
edm::ValidityInterval&) override;
std::unique_ptr<HcalPedestals> producePedestals_(const HcalPedestalsRcd& rcd, bool eff);
std::unique_ptr<HcalPedestalWidths> producePedestalWidths_(const HcalPedestalWidthsRcd& rcd, bool eff);
std::unique_ptr<HcalPedestals> producePedestals(const HcalPedestalsRcd& rcd);
std::unique_ptr<HcalPedestalWidths> producePedestalWidths(const HcalPedestalWidthsRcd& rcd);
std::unique_ptr<HcalPedestals> produceEffectivePedestals(const HcalPedestalsRcd& rcd);
std::unique_ptr<HcalPedestalWidths> produceEffectivePedestalWidths(const HcalPedestalWidthsRcd& rcd);
std::unique_ptr<HcalGains> produceGains(const HcalGainsRcd& rcd);
std::unique_ptr<HcalGainWidths> produceGainWidths(const HcalGainWidthsRcd& rcd);
std::unique_ptr<HcalQIEData> produceQIEData(const HcalQIEDataRcd& rcd);
std::unique_ptr<HcalQIETypes> produceQIETypes(const HcalQIETypesRcd& rcd);
std::unique_ptr<HcalChannelQuality> produceChannelQuality(const HcalChannelQualityRcd& rcd);
std::unique_ptr<HcalElectronicsMap> produceElectronicsMap(const HcalElectronicsMapRcd& rcd);
std::unique_ptr<HcalRespCorrs> produceRespCorrs(const HcalRespCorrsRcd& rcd);
std::unique_ptr<HcalZSThresholds> produceZSThresholds(const HcalZSThresholdsRcd& rcd);
std::unique_ptr<HcalL1TriggerObjects> produceL1TriggerObjects(const HcalL1TriggerObjectsRcd& rcd);
std::unique_ptr<HcalTimeCorrs> produceTimeCorrs(const HcalTimeCorrsRcd& rcd);
std::unique_ptr<HcalLUTCorrs> produceLUTCorrs(const HcalLUTCorrsRcd& rcd);
std::unique_ptr<HcalPFCorrs> producePFCorrs(const HcalPFCorrsRcd& rcd);
std::unique_ptr<HcalValidationCorrs> produceValidationCorrs(const HcalValidationCorrsRcd& rcd);
std::unique_ptr<HcalLutMetadata> produceLutMetadata(const HcalLutMetadataRcd& rcd);
std::unique_ptr<HcalDcsValues> produceDcsValues(const HcalDcsRcd& rcd);
std::unique_ptr<HcalDcsMap> produceDcsMap(const HcalDcsMapRcd& rcd);
std::unique_ptr<HcalRecoParams> produceRecoParams(const HcalRecoParamsRcd& rcd);
std::unique_ptr<HcalTimingParams> produceTimingParams(const HcalTimingParamsRcd& rcd);
std::unique_ptr<HcalLongRecoParams> produceLongRecoParams(const HcalLongRecoParamsRcd& rcd);
std::unique_ptr<HcalZDCLowGainFractions> produceZDCLowGainFractions(const HcalZDCLowGainFractionsRcd& rcd);
std::unique_ptr<HcalMCParams> produceMCParams(const HcalMCParamsRcd& rcd);
std::unique_ptr<HcalFlagHFDigiTimeParams> produceFlagHFDigiTimeParams(const HcalFlagHFDigiTimeParamsRcd& rcd);
std::unique_ptr<HcalFrontEndMap> produceFrontEndMap(const HcalFrontEndMapRcd& rcd);
std::unique_ptr<HcalSiPMParameters> produceSiPMParameters(const HcalSiPMParametersRcd& rcd);
std::unique_ptr<HcalSiPMCharacteristics> produceSiPMCharacteristics(const HcalSiPMCharacteristicsRcd& rcd);
std::unique_ptr<HcalTPChannelParameters> produceTPChannelParameters(const HcalTPChannelParametersRcd& rcd);
std::unique_ptr<HcalTPParameters> produceTPParameters(const HcalTPParametersRcd& rcd);
private:
HcalDbHardcode dbHardcode;
double iLumi;
std::unique_ptr<HBHERecalibration> hb_recalibration;
std::unique_ptr<HBHERecalibration> he_recalibration;
std::unique_ptr<HFRecalibration> hf_recalibration;
bool switchGainWidthsForTrigPrims;
bool setHEdsegm;
bool setHBdsegm;
bool useLayer0Weight;
bool useIeta18depth1;
bool testHEPlan1;
};
| 45.705882 | 112 | 0.832322 | [
"geometry"
] |
e4d941d59bc9c714eb69562685561ce89aec3640 | 279 | h | C | common/geometry/d3/utils/intersection_line_plane.h | Loks-/competitions | 3bb231ba9dd62447048832f45b09141454a51926 | [
"MIT"
] | 4 | 2018-06-05T14:15:52.000Z | 2022-02-08T05:14:23.000Z | common/geometry/d3/utils/intersection_line_plane.h | Loks-/competitions | 3bb231ba9dd62447048832f45b09141454a51926 | [
"MIT"
] | null | null | null | common/geometry/d3/utils/intersection_line_plane.h | Loks-/competitions | 3bb231ba9dd62447048832f45b09141454a51926 | [
"MIT"
] | 1 | 2018-10-21T11:01:35.000Z | 2018-10-21T11:01:35.000Z | #pragma once
#include "common/geometry/d3/line.h"
#include "common/geometry/d3/plane.h"
template <class T>
inline T Intersection(const geometry::d3::Line<T>& l,
const geometry::d3::Plane<T>& p) {
T x0 = p(l(0)), x1 = p(l(1));
return x0 / (x0 - x1);
}
| 23.25 | 56 | 0.594982 | [
"geometry"
] |
e4dfc94799b06e7ac50af74debce11dea3d24308 | 1,783 | h | C | payload/Payload/common.h | eblair2/webkitexploit-poc | 08516b5e51adf3d41d5e84b927248824421c3113 | [
"MIT"
] | 1 | 2021-11-08T17:59:43.000Z | 2021-11-08T17:59:43.000Z | payload/Payload/common.h | eblair2/webkitexploit-poc | 08516b5e51adf3d41d5e84b927248824421c3113 | [
"MIT"
] | null | null | null | payload/Payload/common.h | eblair2/webkitexploit-poc | 08516b5e51adf3d41d5e84b927248824421c3113 | [
"MIT"
] | null | null | null | #ifndef COMMON_H
#define COMMON_H
#include <stdint.h>
#include <mach/mach.h>
#import <Foundation/Foundation.h>
#include "offsets.h"
#define MAGIC 0xdeadbeefdeadbeefull
#ifdef RELEASE
# define LOG(str, args...) do { } while(0)
#else
# define LOG(str, args...) do { NSLog(@"[%s] " str, __func__, ##args); } while(0)
#endif
extern kern_return_t bootstrap_look_up(mach_port_t bp, char *name, mach_port_t *sp);
extern mach_port_t mach_reply_port(void);
extern kern_return_t mach_vm_allocate(task_t task, mach_vm_address_t *addr, mach_vm_size_t size, int flags);
extern kern_return_t mach_vm_deallocate(task_t task, mach_vm_address_t address, mach_vm_size_t size);
extern kern_return_t mach_vm_read(vm_map_t target_task, mach_vm_address_t address, mach_vm_size_t size, vm_offset_t *data, mach_msg_type_number_t *dataCnt);
extern kern_return_t mach_vm_write(vm_map_t target_task, mach_vm_address_t address, vm_offset_t data, mach_msg_type_number_t dataCnt);
extern kern_return_t mach_vm_read_overwrite(vm_map_t target_task, mach_vm_address_t address, mach_vm_size_t size, mach_vm_address_t data, mach_vm_size_t *outsize);
extern kern_return_t mach_vm_protect(task_t task, mach_vm_address_t addr, mach_vm_size_t size, boolean_t set_max, vm_prot_t new_prot);
extern kern_return_t mach_vm_map(task_t task, mach_vm_address_t *addr, mach_vm_size_t size, mach_vm_offset_t mask, int flags, mem_entry_name_port_t object, memory_object_offset_t offset, boolean_t copy, vm_prot_t cur, vm_prot_t max, vm_inherit_t inheritance);
extern kern_return_t mach_vm_remap(vm_map_t dst, mach_vm_address_t *dst_addr, mach_vm_size_t size, mach_vm_offset_t mask, int flags, vm_map_t src, mach_vm_address_t src_addr, boolean_t copy, vm_prot_t *cur_prot, vm_prot_t *max_prot, vm_inherit_t inherit);
#endif
| 59.433333 | 259 | 0.822771 | [
"object"
] |
e4e954bd384ce1510dd12ede52fc1c6b47c27217 | 2,950 | h | C | td/telegram/BotCommand.h | lccxz/td | 6cdda6a2f3be4d0379f00a07fcd49f330da731fb | [
"BSL-1.0"
] | 4,829 | 2017-12-31T21:15:19.000Z | 2022-03-31T14:58:07.000Z | td/telegram/BotCommand.h | lccxz/td | 6cdda6a2f3be4d0379f00a07fcd49f330da731fb | [
"BSL-1.0"
] | 1,872 | 2018-01-01T18:35:37.000Z | 2022-03-31T15:46:00.000Z | td/telegram/BotCommand.h | lccxz/td | 6cdda6a2f3be4d0379f00a07fcd49f330da731fb | [
"BSL-1.0"
] | 1,117 | 2018-01-01T15:02:49.000Z | 2022-03-30T12:40:11.000Z | //
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2021
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#pragma once
#include "td/telegram/td_api.h"
#include "td/telegram/telegram_api.h"
#include "td/telegram/UserId.h"
#include "td/actor/PromiseFuture.h"
#include "td/utils/common.h"
#include "td/utils/tl_helpers.h"
namespace td {
class Td;
class BotCommand {
string command_;
string description_;
friend bool operator==(const BotCommand &lhs, const BotCommand &rhs);
public:
BotCommand() = default;
BotCommand(string command, string description) : command_(std::move(command)), description_(std::move(description)) {
}
explicit BotCommand(telegram_api::object_ptr<telegram_api::botCommand> &&bot_command);
td_api::object_ptr<td_api::botCommand> get_bot_command_object() const;
telegram_api::object_ptr<telegram_api::botCommand> get_input_bot_command() const;
template <class StorerT>
void store(StorerT &storer) const {
td::store(command_, storer);
td::store(description_, storer);
}
template <class ParserT>
void parse(ParserT &parser) {
td::parse(command_, parser);
td::parse(description_, parser);
}
};
bool operator==(const BotCommand &lhs, const BotCommand &rhs);
inline bool operator!=(const BotCommand &lhs, const BotCommand &rhs) {
return !(lhs == rhs);
}
class BotCommands {
UserId bot_user_id_;
vector<BotCommand> commands_;
friend bool operator==(const BotCommands &lhs, const BotCommands &rhs);
public:
BotCommands() = default;
BotCommands(UserId bot_user_id, vector<telegram_api::object_ptr<telegram_api::botCommand>> &&bot_commands);
td_api::object_ptr<td_api::botCommands> get_bot_commands_object(Td *td) const;
UserId get_bot_user_id() const {
return bot_user_id_;
}
template <class StorerT>
void store(StorerT &storer) const {
td::store(bot_user_id_, storer);
td::store(commands_, storer);
}
template <class ParserT>
void parse(ParserT &parser) {
td::parse(bot_user_id_, parser);
td::parse(commands_, parser);
}
};
bool operator==(const BotCommands &lhs, const BotCommands &rhs);
inline bool operator!=(const BotCommands &lhs, const BotCommands &rhs) {
return !(lhs == rhs);
}
void set_commands(Td *td, td_api::object_ptr<td_api::BotCommandScope> &&scope_ptr, string &&language_code,
vector<td_api::object_ptr<td_api::botCommand>> &&commands, Promise<Unit> &&promise);
void delete_commands(Td *td, td_api::object_ptr<td_api::BotCommandScope> &&scope_ptr, string &&language_code,
Promise<Unit> &&promise);
void get_commands(Td *td, td_api::object_ptr<td_api::BotCommandScope> &&scope_ptr, string &&language_code,
Promise<td_api::object_ptr<td_api::botCommands>> &&promise);
} // namespace td
| 28.921569 | 119 | 0.72 | [
"vector"
] |
e4edf2ce85cc6046068eb24fa35585dcc05bd68c | 4,936 | h | C | Adjust/ADJConfig.h | scelis/ios_sdk | 7fe5b724e761f4cbd479de173afa2144252a172a | [
"MIT"
] | 1 | 2021-07-07T11:16:33.000Z | 2021-07-07T11:16:33.000Z | Adjust/ADJConfig.h | scelis/ios_sdk | 7fe5b724e761f4cbd479de173afa2144252a172a | [
"MIT"
] | null | null | null | Adjust/ADJConfig.h | scelis/ios_sdk | 7fe5b724e761f4cbd479de173afa2144252a172a | [
"MIT"
] | 1 | 2021-07-20T19:11:26.000Z | 2021-07-20T19:11:26.000Z | //
// ADJConfig.h
// adjust
//
// Created by Pedro Filipe on 30/10/14.
// Copyright (c) 2014 adjust GmbH. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "ADJLogger.h"
#import "ADJAttribution.h"
#import "ADJSessionSuccess.h"
#import "ADJSessionFailure.h"
#import "ADJEventSuccess.h"
#import "ADJEventFailure.h"
/**
* Optional delegate that will get informed about tracking results
*/
@protocol AdjustDelegate
@optional
/**
* Optional delegate method that gets called when the attribution information changed
*
* @param attribution The attribution information. See ADJAttribution for details.
*/
- (void)adjustAttributionChanged:(ADJAttribution *)attribution;
/**
* Optional delegate method that gets called when an event is tracked with success
*
* @param eventSuccessResponseData The response information from tracking with success. See ADJEventSuccess for details.
*/
- (void)adjustEventTrackingSucceeded:(ADJEventSuccess *)eventSuccessResponseData;
/**
* Optional delegate method that gets called when an event is tracked with failure
*
* @param eventFailureResponseData The response information from tracking with failure. See ADJEventFailure for details.
*/
- (void)adjustEventTrackingFailed:(ADJEventFailure *)eventFailureResponseData;
/**
* Optional delegate method that gets called when an session is tracked with success
*
* @param sessionSuccessResponseData The response information from tracking with success. See ADJSessionSuccess for details.
*/
- (void)adjustSessionTrackingSucceeded:(ADJSessionSuccess *)sessionSuccessResponseData;
/**
* Optional delegate method that gets called when an session is tracked with failure
*
* @param sessionFailureResponseData The response information from tracking with failure. See ADJSessionFailure for details.
*/
- (void)adjustSessionTrackingFailed:(ADJSessionFailure *)sessionFailureResponseData;
/**
* Optional delegate method that gets called when a deeplink is about to be opened by the adjust SDK
*
* @param deeplink The deeplink url that was received by the adjust SDK to be opened
* @return boolean value that indicates whether the deeplink should be opened by the adjust SDK
*/
- (BOOL)adjustDeeplinkResponse:(NSURL *)deeplink;
@end
@interface ADJConfig : NSObject<NSCopying>
@property (nonatomic, copy, readonly) NSString *appToken;
@property (nonatomic, copy, readonly) NSString *environment;
@property (nonatomic, copy) NSString *sdkPrefix;
@property (nonatomic, copy) NSString *defaultTracker;
/**
* Configuration object for the initialization of the Adjust SDK.
*
* @param appToken The App Token of your app. This unique identifier can
* be found it in your dashboard at http://adjust.com and should always
* be 12 characters long.
* @param environment The current environment your app. We use this environment to
* distinguish between real traffic and artificial traffic from test devices.
* It is very important that you keep this value meaningful at all times!
* Especially if you are tracking revenue.
*/
+ (ADJConfig*)configWithAppToken:(NSString *)appToken environment:(NSString *)environment;
- (id)initWithAppToken:(NSString *)appToken environment:(NSString *)environment;
/**
* Change the verbosity of Adjust's logs.
*
* You can increase or reduce the amount of logs from Adjust by passing
* one of the following parameters. Use Log.ASSERT to disable all logging.
*
* @var logLevel The desired minimum log level (default: info)
* Must be one of the following:
* - ADJLogLevelVerbose (enable all logging)
* - ADJLogLevelDebug (enable more logging)
* - ADJLogLevelInfo (the default)
* - ADJLogLevelWarn (disable info logging)
* - ADJLogLevelError (disable warnings as well)
* - ADJLogLevelAssert (disable errors as well)
*/
@property (nonatomic, assign) ADJLogLevel logLevel;
/**
* Enable event buffering if your app triggers a lot of events.
* When enabled, events get buffered and only get tracked each
* minute. Buffered events are still persisted, of course.
*
* @var eventBufferingEnabled Enable or disable event buffering
*/
@property (nonatomic, assign) BOOL eventBufferingEnabled;
/**
* Set the optional delegate that will inform you about attribution or events
*
* See the AdjustDelegate declaration above for details
*
* @var delegate The delegate that might implement the optional delegate
* methods like adjustAttributionChanged, adjustTrackingSucceeded or adjustTrackingFailed:
*/
@property (nonatomic, weak) NSObject<AdjustDelegate> *delegate;
/**
* Enables sending in the background
*
* @var sendInBackground Enable or disable sending in the background
*/
@property (nonatomic, assign) BOOL sendInBackground;
@property (nonatomic, assign, readonly) BOOL hasResponseDelegate;
@property (nonatomic, assign, readonly) BOOL hasAttributionChangedDelegate;
- (BOOL) isValid;
@end
| 36.294118 | 124 | 0.763169 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.