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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ac3da8efb2ed5c07d36359b82fcec627fb4099a5 | 1,964 | h | C | TapPointSDK/TapPointSDK.framework/Versions/A/Headers/PRXTapPointManager.h | proxama/ios-tappoint-sdk | c248b5a50c6b7d1f575480f8f7aa7afca0376e93 | [
"MIT"
] | null | null | null | TapPointSDK/TapPointSDK.framework/Versions/A/Headers/PRXTapPointManager.h | proxama/ios-tappoint-sdk | c248b5a50c6b7d1f575480f8f7aa7afca0376e93 | [
"MIT"
] | null | null | null | TapPointSDK/TapPointSDK.framework/Versions/A/Headers/PRXTapPointManager.h | proxama/ios-tappoint-sdk | c248b5a50c6b7d1f575480f8f7aa7afca0376e93 | [
"MIT"
] | null | null | null | //
// PRXTapPointManager.h
// TapPointSDK
//
// Created by Sarah Fuke on 25/07/2017.
// Copyright © 2017 Proxama Solutions Ltd. All rights reserved.
//
/**
* A block called by the TapPoint manager when initialisation fails.
*
* @param error An NSError describing why initialisation failed.
*/
typedef void (^PRXTapPointFailureBlock)(NSError *error);
/**
* The PRXTapPointManager protocol is adopted by the shared TapPoint manager.
*/
@protocol PRXTapPointManager <NSObject>
/**
* Initialises the TapPoint SDK.
*
* You should call this method as soon as possible after application launch,
* or when the network connection first becomes available. You should call this method every time
* the application launches in the app delegate's didFinishLaunchingWithOptions: method.
*
* Initialisation can fail for several reasons, for example the provided application name is invalid, or
* if the network connection is not functioning. Your application should inspect the NSError object that
* is returned in the failure block of this method and decide whether it is possible to recover. This might
* mean listening for when the network connection status changes so that the application can attempt to
* register again.
*
* @param key The application key provided by TapPoint. This is case sensitive.
* @param failureBlock Block called when initialisation fails. This block contains an NSError
* argument describing the cause of the error.
*/
- (void)initialiseWithKey:(NSString *)key
failure:(PRXTapPointFailureBlock)failureBlock
__attribute((nonnull(1)));
@end
/**
* An object used to retrieve the shared TapPoint manager.
*
* The TapPoint manager is able to initialise the TapPoint SDK.
*/
@interface PRXTapPoint : NSObject
/**
* Returns the shared TapPoint manager.
*
* A TapPoint manager is able to initialise the TapPoint SDK.
*
* @return The shared TapPoint manager.
*/
+ (id <PRXTapPointManager>)sharedManager;
@end
| 32.196721 | 107 | 0.759165 | [
"object"
] |
ac3fe05d7f9279abd6199070dd6fd2e030e76593 | 10,750 | h | C | TKPEmu/include/display.h | OFFTKP/TKPEmu | 7cf22d8263ae8431721006af7c3156564607b490 | [
"MIT"
] | 8 | 2021-12-20T22:57:54.000Z | 2022-03-23T04:21:33.000Z | TKPEmu/include/display.h | OFFTKP/TKPEmu | 7cf22d8263ae8431721006af7c3156564607b490 | [
"MIT"
] | 21 | 2021-10-31T00:05:45.000Z | 2022-03-24T12:50:56.000Z | TKPEmu/include/display.h | OFFTKP/TKPEmu | 7cf22d8263ae8431721006af7c3156564607b490 | [
"MIT"
] | 1 | 2022-03-22T23:25:07.000Z | 2022-03-22T23:25:07.000Z | #pragma once
#ifndef TKP_GB_DISPLAY_H
#define TKP_GB_DISPLAY_H
#include <SDL2/SDL.h>
#include <string>
#include <mutex>
#include <deque>
#include <atomic>
#include <GL/glew.h>
#include <lib/imgui_impl_sdl.h>
#include <lib/imgui_impl_opengl3.h>
#include <imgui/imgui_internal.h>
#include <lib/widget_keyselector.h>
#include <lib/imfilebrowser.h>
#include <include/generic_drawable.h>
#include "emulator_types.hxx"
#include "TKPImage.h"
#include "settings_manager.h"
#include "base_application.h"
#include "emulator_factory.h"
// Helper Macros - IM_FMTARGS, IM_FMTLIST: Apply printf-style warnings to our formatting functions.
#if !defined(IMGUI_USE_STB_SPRINTF) && defined(__MINGW32__) && !defined(__clang__)
#define IM_FMTARGS(FMT) __attribute__((format(gnu_printf, FMT, FMT+1)))
#define IM_FMTLIST(FMT) __attribute__((format(gnu_printf, FMT, 0)))
#elif !defined(IMGUI_USE_STB_SPRINTF) && (defined(__clang__) || defined(__GNUC__))
#define IM_FMTARGS(FMT) __attribute__((format(printf, FMT, FMT+1)))
#define IM_FMTLIST(FMT) __attribute__((format(printf, FMT, 0)))
#else
#define IM_FMTARGS(FMT)
#define IM_FMTLIST(FMT)
#endif
// runs a function that may throw - to be used inside display member functions
#define TKP_MAY_THROW(func) do { \
try { \
func; \
} catch (const std::runtime_error& ex) { \
throw_error(ex); \
} \
} while(0)
// runs a function that may throw - to be used inside display member functions
// and runs an action after throwing
#define TKP_MAY_THROW_ACTION(func, action) do { \
try { \
func; \
} catch (const std::runtime_error& ex) { \
throw_error(ex); \
action; \
} \
} while(0)
namespace TKPEmu::Graphics {
constexpr auto GameboyWidth = 160;
constexpr auto GameboyHeight = 144;
constexpr auto MenuBarHeight = 19;
constexpr auto RecentRomsMaxSize = 5;
struct WindowSettings {
int window_width = 640;
int window_height = 480;
int minimum_width = GameboyWidth;
int minimum_height = GameboyHeight + MenuBarHeight;
// TODO: replace these magic numbers with screen height / width / -1
int maximum_width = 1920;
int maximum_height = 1080;
};
class Display {
private:
using TKPShortcut = TKPEmu::Applications::TKPShortcut;
using TKPImage = TKPEmu::Tools::TKPImage;
using KeySelector = TKPEmu::Tools::KeySelector;
using EmuStartOptions = TKPEmu::EmuStartOptions;
using SDL_GLContextType = std::remove_pointer_t<SDL_GLContext>;
using IMApplication = TKPEmu::Applications::IMApplication;
using Drawable = TKPEmu::Applications::Drawable;
using SettingsManager = TKPEmu::Tools::SettingsManager;
using DisInstr = TKPEmu::Tools::DisInstr;
using GameboyPalettes = std::array<std::array<float, 3>,4>;
using GameboyKeys = std::array<SDL_Keycode, 4>;
using Chip8Keys = std::array<SDL_Keycode, 16>;
const std::string GLSLVersion = "#version 130";
std::vector<std::string> SupportedRoms = { ".gb", ".gbc", ".n64", ".N64", ".z64", ".ch8" };
#ifdef _WIN32
wchar_t exe_dir[MAX_PATH];
#endif
std::string ImGuiSettingsFile = "imgui.ini";
private:
// RAII class for the initialization functions
class DisplayInitializer {
public:
DisplayInitializer();
~DisplayInitializer();
};
public:
Display();
~Display();
Display(const Display&) = delete;
Display& operator=(const Display&) = delete;
void EnterMainLoop();
void WS_SetActionFlag(int* action_ptr);
void WS_LoadRom(std::string path);
private:
// This member being first means that it gets constructed first and gets destructed last
// which is what we want to happen with the SDL_Init and the destroy functions
DisplayInitializer display_initializer_;
std::deque<std::filesystem::path> recent_paths_;
// To be used with settings_manager, these are the settings keys with their default values
TKPEmu::Tools::SettingsMap settings_ =
{
{"General.debug_mode", "1"},
{"General.skip_boot", "0"},
{"General.fast_mode", "0"},
{"General.last_dir", ""},
{"General.recent0", ""},
{"General.recent1", ""},
{"General.recent2", ""},
{"General.recent3", ""},
{"General.recent4", ""},
{"Video.limit_fps", "1"},
{"Video.max_fps", "60"},
{"Gameboy.color0", "d0d058"},
{"Gameboy.color1", "a0a840"},
{"Gameboy.color2", "708028"},
{"Gameboy.color3", "405010"},
{"Gameboy.key_right", std::to_string(SDLK_RIGHT)},
{"Gameboy.key_left", std::to_string(SDLK_LEFT)},
{"Gameboy.key_down", std::to_string(SDLK_DOWN)},
{"Gameboy.key_up", std::to_string(SDLK_UP)},
{"Gameboy.key_a", std::to_string(SDLK_z)},
{"Gameboy.key_b", std::to_string(SDLK_x)},
{"Gameboy.key_start", std::to_string(SDLK_RETURN)},
{"Gameboy.key_select", std::to_string(SDLK_SPACE)},
{"Chip8.key_0", std::to_string(SDLK_1)},
{"Chip8.key_1", std::to_string(SDLK_2)},
{"Chip8.key_2", std::to_string(SDLK_3)},
{"Chip8.key_3", std::to_string(SDLK_4)},
{"Chip8.key_4", std::to_string(SDLK_q)},
{"Chip8.key_5", std::to_string(SDLK_w)},
{"Chip8.key_6", std::to_string(SDLK_e)},
{"Chip8.key_7", std::to_string(SDLK_a)},
{"Chip8.key_8", std::to_string(SDLK_s)},
{"Chip8.key_9", std::to_string(SDLK_d)},
{"Chip8.key_a", std::to_string(SDLK_z)},
{"Chip8.key_b", std::to_string(SDLK_x)},
{"Chip8.key_c", std::to_string(SDLK_4)},
{"Chip8.key_d", std::to_string(SDLK_r)},
{"Chip8.key_e", std::to_string(SDLK_f)},
{"Chip8.key_f", std::to_string(SDLK_v)},
{"N64.ipl_loc", "not set"},
};
SettingsManager settings_manager_;
// Emulation specific settings
GameboyPalettes gb_palettes_{};
GameboyKeys gb_keys_direction_{};
GameboyKeys gb_keys_action_{};
Chip8Keys chip8_keys_{};
std::filesystem::path n64_ipl_loc_{};
bool limit_fps_ = true;
int max_fps_ = 60;
int* action_ptr_ = nullptr;
bool debug_mode_ = true;
bool skip_boot_ = false;
bool fast_mode_ = false;
WindowSettings window_settings_;
GLuint frame_buffer_;
ImGui::FileBrowser file_browser_;
using file_browser_callback_fncptr = void (Display::*)(std::filesystem::path);
file_browser_callback_fncptr file_browser_callback_;
EmuType emulator_type_ = EmuType::None;
std::shared_ptr<Emulator> emulator_;
// Applications loaded according to the emulator (such as disassembler, tracelogger, other plugins etc)
std::vector<std::unique_ptr<IMApplication>> emulator_tools_;
// Generic tools that work across emulators
std::vector<std::unique_ptr<Drawable>> generic_tools_;
std::unique_ptr<SDL_Window, decltype(&SDL_DestroyWindow)> window_ptr_;
std::unique_ptr<SDL_GLContextType, decltype(&SDL_GL_DeleteContext)> gl_context_ptr_;
std::chrono::system_clock::time_point a = std::chrono::system_clock::now();
std::chrono::system_clock::time_point b = std::chrono::system_clock::now();
// This variable helps for setting up the controls
SDL_Keycode last_key_pressed_ = 0;
float sleep_time_ = 16.75f;
// These bools determine whether certain windows are open
// We aren't allowed to use static member variables so we use static functions that
// return static members
bool rom_loaded_ = false;
bool rom_paused_ = false;
bool menu_bar_open_ = true;
bool window_fpscounter_open_ = false;
bool window_disassembly_open_ = false;
bool window_settings_open_ = false;
bool window_file_browser_open_ = false;
bool window_about_open_ = false;
bool window_messagebox_open_ = false;
bool ipl_changed_ = false;
std::string messagebox_body_;
std::string WS_path_;
TKPShortcut last_shortcut_ = TKPShortcut::NONE;
// Window drawing functions for ImGui
void draw_settings(bool* draw);
void draw_fps_counter(bool* draw);
void draw_disassembly(bool* draw);
void draw_file_browser(bool* draw);
void draw_about(bool* draw);
void draw_game_background(bool* draw);
void draw_menu_bar(bool* draw);
void draw_messagebox(bool* draw);
void draw_menu_bar_file();
void draw_menu_bar_file_recent();
void draw_menu_bar_tools();
void draw_menu_bar_view();
void draw_menu_bar_help();
void draw_tools();
void open_file_browser(std::string title, std::vector<std::string>& extensions);
void open_file_browser_rom();
void handle_shortcuts();
void save_recent_files();
// Helper functions
bool load_image_from_file(const char* filename, TKPImage& out);
void limit_fps();
void init_settings_values();
void init_gameboy_values();
void init_n64_values();
bool is_rom_loaded();
bool is_rom_loaded_and_debugmode();
// This function deals with scaling the gameboy screen texture without stretching it
void image_scale(ImVec2& topleft, ImVec2& bottomright, float wi, float hi);
void load_rom(std::filesystem::path path);
void load_ipl(std::filesystem::path path);
std::any get_emu_specific_args(EmuType type);
void setup_emulator_specific();
void setup_gameboy_palette();
void load_loop();
void load_theme();
void main_loop();
void throw_error(const std::runtime_error& ex);
std::runtime_error generate_exception(std::string func_name, int line_num, std::string description);
};
}
#endif
| 43.522267 | 111 | 0.606791 | [
"vector"
] |
ac475a3b418210c2e3cc47d0d74dfb871fdd5be1 | 6,181 | h | C | Tools/Tools/DumpRenderTree/chromium/EventSender.h | VincentWei/mdolphin-core | 48ffdcf587a48a7bb4345ae469a45c5b64ffad0e | [
"Apache-2.0"
] | 6 | 2017-05-31T01:46:45.000Z | 2018-06-12T10:53:30.000Z | Tools/Tools/DumpRenderTree/chromium/EventSender.h | FMSoftCN/mdolphin-core | 48ffdcf587a48a7bb4345ae469a45c5b64ffad0e | [
"Apache-2.0"
] | null | null | null | Tools/Tools/DumpRenderTree/chromium/EventSender.h | FMSoftCN/mdolphin-core | 48ffdcf587a48a7bb4345ae469a45c5b64ffad0e | [
"Apache-2.0"
] | 2 | 2017-07-17T06:02:42.000Z | 2018-09-19T10:08:38.000Z | /*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
EventSender class:
Bound to a JavaScript window.eventSender object using
CppBoundClass::bindToJavascript(), this allows layout tests to fire DOM events.
*/
#ifndef EventSender_h
#define EventSender_h
#include "CppBoundClass.h"
#include "base/task.h"
#include "public/WebDragOperation.h"
#include "public/WebInputEvent.h"
#include "public/WebPoint.h"
class TestShell;
namespace WebKit {
class WebDragData;
class WebView;
}
class EventSender : public CppBoundClass {
public:
// Builds the property and method lists needed to bind this class to a JS
// object.
EventSender(TestShell*);
// Resets some static variable state.
void reset();
// Simulate drag&drop system call.
void doDragDrop(const WebKit::WebDragData&, WebKit::WebDragOperationsMask);
// JS callback methods.
void mouseDown(const CppArgumentList&, CppVariant*);
void mouseUp(const CppArgumentList&, CppVariant*);
void mouseMoveTo(const CppArgumentList&, CppVariant*);
void mouseWheelTo(const CppArgumentList&, CppVariant*);
void leapForward(const CppArgumentList&, CppVariant*);
void keyDown(const CppArgumentList&, CppVariant*);
void dispatchMessage(const CppArgumentList&, CppVariant*);
void textZoomIn(const CppArgumentList&, CppVariant*);
void textZoomOut(const CppArgumentList&, CppVariant*);
void zoomPageIn(const CppArgumentList&, CppVariant*);
void zoomPageOut(const CppArgumentList&, CppVariant*);
void scheduleAsynchronousClick(const CppArgumentList&, CppVariant*);
void beginDragWithFiles(const CppArgumentList&, CppVariant*);
CppVariant dragMode;
void addTouchPoint(const CppArgumentList&, CppVariant*);
void cancelTouchPoint(const CppArgumentList&, CppVariant*);
void clearTouchPoints(const CppArgumentList&, CppVariant*);
void releaseTouchPoint(const CppArgumentList&, CppVariant*);
void setTouchModifier(const CppArgumentList&, CppVariant*);
void touchCancel(const CppArgumentList&, CppVariant*);
void touchEnd(const CppArgumentList&, CppVariant*);
void touchMove(const CppArgumentList&, CppVariant*);
void touchStart(const CppArgumentList&, CppVariant*);
void updateTouchPoint(const CppArgumentList&, CppVariant*);
// Unimplemented stubs
void contextClick(const CppArgumentList&, CppVariant*);
void enableDOMUIEventLogging(const CppArgumentList&, CppVariant*);
void fireKeyboardEventsToElement(const CppArgumentList&, CppVariant*);
void clearKillRing(const CppArgumentList&, CppVariant*);
// Properties used in layout tests.
#if defined(OS_WIN)
CppVariant wmKeyDown;
CppVariant wmKeyUp;
CppVariant wmChar;
CppVariant wmDeadChar;
CppVariant wmSysKeyDown;
CppVariant wmSysKeyUp;
CppVariant wmSysChar;
CppVariant wmSysDeadChar;
#endif
private:
// Returns the test shell's webview.
WebKit::WebView* webview();
// Returns true if dragMode is true.
bool isDragMode() { return dragMode.isBool() && dragMode.toBoolean(); }
// Sometimes we queue up mouse move and mouse up events for drag drop
// handling purposes. These methods dispatch the event.
void doMouseMove(const WebKit::WebMouseEvent&);
void doMouseUp(const WebKit::WebMouseEvent&);
static void doLeapForward(int milliseconds);
void replaySavedEvents();
// Helper to return the button type given a button code
static WebKit::WebMouseEvent::Button getButtonTypeFromButtonNumber(int);
// Helper to extract the button number from the optional argument in
// mouseDown and mouseUp
static int getButtonNumberFromSingleArg(const CppArgumentList&);
// Returns true if the specified key code passed in needs a shift key
// modifier to be passed into the generated event.
bool needsShiftModifier(int);
void updateClickCountForButton(WebKit::WebMouseEvent::Button);
// Compose a touch event from the current touch points and send it.
void sendCurrentTouchEvent(const WebKit::WebInputEvent::Type);
ScopedRunnableMethodFactory<EventSender> m_methodFactory;
// Non-owning pointer. The EventSender is owned by the TestShell.
TestShell* m_shell;
// Location of last mouseMoveTo event.
static WebKit::WebPoint lastMousePos;
// Currently pressed mouse button (Left/Right/Middle or None)
static WebKit::WebMouseEvent::Button pressedButton;
// The last button number passed to mouseDown and mouseUp.
// Used to determine whether the click count continues to
// increment or not.
static WebKit::WebMouseEvent::Button lastButtonType;
};
#endif // EventSender_h
| 39.120253 | 81 | 0.751658 | [
"object"
] |
ac4d59b91d8b19d2cd632af7ee92c01cee35788c | 6,787 | h | C | deps/ccommon/include/time/cc_wheel.h | wonism/pelikan | 08800930ee81e67abc5a3b89d596951121314bc1 | [
"Apache-2.0"
] | 1,080 | 2016-04-04T22:53:48.000Z | 2022-03-30T00:00:14.000Z | deps/ccommon/include/time/cc_wheel.h | wonism/pelikan | 08800930ee81e67abc5a3b89d596951121314bc1 | [
"Apache-2.0"
] | 149 | 2016-04-06T08:54:12.000Z | 2022-03-15T21:51:34.000Z | deps/ccommon/include/time/cc_wheel.h | wonism/pelikan | 08800930ee81e67abc5a3b89d596951121314bc1 | [
"Apache-2.0"
] | 103 | 2016-04-04T22:42:56.000Z | 2022-03-27T17:09:40.000Z | /*
* ccommon - a cache common library.
* Copyright (C) 2013 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#ifdef __cplusplus
extern "C" {
#endif
#include <cc_event.h>
#include <cc_queue.h>
#include <time/cc_timer.h>
/* TODO(yao): we need to ask the question of whether we want to expose
* `struct timeout_event` and its related functions at all, given the
* difficulty of managing the resource lifecycle in combination with
* the arbitrary nature of callback functions.
*
* Keeping the existing interfaces untouched for now to minimize changes
* introduced at once. Will revisit very soon.
*/
/* name type description */
#define TIMING_WHEEL_METRIC(ACTION) \
ACTION( timeout_event_curr, METRIC_GAUGE, "# timeout events allocated" )\
ACTION( timeout_event_active, METRIC_GAUGE, "# timeout events in use" )\
ACTION( timeout_event_borrow, METRIC_COUNTER, "# timeout events borrowed" )\
ACTION( timeout_event_borrow_ex,METRIC_COUNTER, "# tevents borrow errors" )\
ACTION( timeout_event_return, METRIC_COUNTER, "# timeout events returned" )\
ACTION( timing_wheel_insert, METRIC_COUNTER, "# tevent insertions" )\
ACTION( timing_wheel_remove, METRIC_COUNTER, "# tevent removal" )\
ACTION( timing_wheel_event, METRIC_GAUGE, "# tevents in timing wheels" )\
ACTION( timing_wheel_process, METRIC_COUNTER, "# tevents processed" )\
ACTION( timing_wheel_tick, METRIC_COUNTER, "# ticks processed" )\
ACTION( timing_wheel_exec, METRIC_COUNTER, "# timing wheel executions " )
typedef struct {
TIMING_WHEEL_METRIC(METRIC_DECLARE)
} timing_wheel_metrics_st;
typedef void (*timeout_cb_fn)(void *); /* timeout callback */
/**
* We use TAILQ because for request timeouts it is very important to have
* low overhead removing entries, as most requests will *not* time out.
* For background maintenance tasks, the situation is the opposite- everything
* times out. However, the volume of such events are so low that performance
* or storage efficiency is not a consideration when choosing data structures.
*/
/**
* timing wheel shouldn't use very fine grain timeouts due to both scheduling
* overhead and the batching nature of processing.
*/
/**
* For timing wheel, we hide the definition of `struct timeout_event', a
* practice we do not usually adopt in this project unless there is a good
* reason to.
* Here, the reason lies in the life-cycle management of timeout events. The
* caller of `timing_wheel_insert' by nature cannot determine whether or when
* the timeout event will eventually be triggered beforehand. As a result,
* the caller has to keep reference and free up resources associated with the
* timeout event in the callback if the timeout event is triggerred.
*
* Hence if the caller to create and pass in a timeout event object, it is on
* the hook to manage the life cycle of that object. On the other hand, the
* sole purpose of such an event is to be used with timing wheel. So if we can
* take over the burden of managing these objects, it will simplify usage and
* prevent memory leak caused by not freeing up timeout event objects.
* Therefore, by hiding `struct timeout_event's definition, caller can only get
* a reference to it, which can be used to delete the timeout if desired. Other
* than that, caller need not worry about the life cycle of these objects. If
* the caller is confident that the timeout event will be triggered, it can even
* ignore the reference returned at insertion.
*
* For insertions that may or may not be removed before due, the caller is
* expected to clear the pointer returned in the callback, but _not_ attempt to
* remove it (since it is already removed).
*/
/**
* Recurring events, by definition, are never removed unless the service is
* being shut down. In this case, the teardown logic of timing wheel will
* properly clean up all resources tied to such events.
*/
struct timeout_event;
struct timing_wheel {
/* basic properties of the timing wheel */
struct timeout tick; /* tick interval */
size_t cap; /* capacity as # ticks in the time wheel */
size_t max_ntick; /* max # ticks to cover in one execution */
/* the following is used internally */
uint64_t tick_ns; /* tick in nanoseconds */
/* state of the wheel */
bool active; /* is the wheel supposed to be turning? */
struct timeout due; /* next trigger time */
size_t curr; /* index of current tick */
uint64_t nevent; /* # of timeout_event objects in wheel */
struct tevent_tqh *table; /* an array of header each points to a list
* of timeouts expiring in the same tick.
* table should contain exactly cap entries,
* each corresponding to a TALQ for the
* corresponding tick
*/
/* some metrics of the most important aspects */
uint64_t nprocess; /* total # timeout events processed */
uint64_t nexec; /* total # executions */
uint64_t ntick; /* total # ticks processed */
};
struct timing_wheel *timing_wheel_create(struct timeout *tick, size_t cap, size_t ntick);
void timing_wheel_destroy(struct timing_wheel **tw);
struct timeout_event * timing_wheel_insert(struct timing_wheel *tw, struct timeout *delay, bool recur, timeout_cb_fn cb, void *arg);
void timing_wheel_remove(struct timing_wheel *tw, struct timeout_event **tev);
void timing_wheel_start(struct timing_wheel *tw);
void timing_wheel_stop(struct timing_wheel *tw);
void timing_wheel_execute(struct timing_wheel *tw);
void timing_wheel_flush(struct timing_wheel *tw); /* triggering all, useful for teardown */
void timing_wheel_setup(timing_wheel_metrics_st *metrics);
void timing_wheel_teardown(void);
#ifdef __cplusplus
}
#endif
| 46.806897 | 132 | 0.682334 | [
"object"
] |
ac4fa04ae988b045510b14375837c3a43b0c784f | 1,957 | h | C | include/DriveSingularity/Math/Segment.h | 737363395/DriveSingularity | 51a7ce61c2263b662f669cd8bc01faa88ad4b771 | [
"Apache-2.0"
] | null | null | null | include/DriveSingularity/Math/Segment.h | 737363395/DriveSingularity | 51a7ce61c2263b662f669cd8bc01faa88ad4b771 | [
"Apache-2.0"
] | null | null | null | include/DriveSingularity/Math/Segment.h | 737363395/DriveSingularity | 51a7ce61c2263b662f669cd8bc01faa88ad4b771 | [
"Apache-2.0"
] | null | null | null | #ifndef DRIVE_SINGULARITY_MATH_SEGMENT_H
#define DRIVE_SINGULARITY_MATH_SEGMENT_H
#include "DriveSingularity/Math/Constants.h"
#include "DriveSingularity/Math/Vector.h"
namespace ds {
class Segment {
public:
Segment(const VectorD &start, const VectorD &end) : start(start), end(end) {}
const VectorD &getStart() const { return start; }
const VectorD &getEnd() const { return end; }
private:
VectorD start, end;
};
inline double signedDistance(const Segment &seg, const VectorD &point) {
// TODO(ming): refactor distance
auto segVec = normalize(seg.getEnd() - seg.getEnd());
auto vec = point - seg.getStart();
int sign = cross(segVec, normalize(vec)) > -eps ? 1 : -1;
assert(dot(segVec, normalize(vec)) > -eps); // TODO
double proj = dot(vec, segVec);
return sign * std::sqrt(vec.getLength() * vec.getLength() - proj * proj);
}
inline bool isIntersect(const Segment &seg1, const Segment &seg2) {
auto segVec = seg1.getEnd() - seg1.getStart();
auto vec1 = seg2.getStart() - seg1.getStart(), vec2 = seg2.getEnd() - seg1.getStart();
double cross1 = cross(vec1, segVec), cross2 = cross(vec2, segVec);
if (fabs(cross1) < eps) {
return fabs(segVec.getLength() - (segVec - vec1).getLength() - vec1.getLength()) < eps;
}
if (fabs(cross2) < eps) {
return fabs(segVec.getLength() - (segVec - vec2).getLength() - vec2.getLength()) < eps;
}
if (cross1 * cross2 > 0) return false;
segVec = seg2.getEnd() - seg2.getStart();
vec1 = seg1.getStart() - seg2.getStart();
vec2 = seg1.getEnd() - seg2.getStart();
cross1 = cross(vec1, segVec);
cross2 = cross(vec2, segVec);
if (fabs(cross1) < eps) {
return fabs(segVec.getLength() - (segVec - vec1).getLength() - vec1.getLength()) < eps;
}
if (fabs(cross2) < eps) {
return fabs(segVec.getLength() - (segVec - vec2).getLength() - vec2.getLength()) < eps;
}
return cross1 * cross2 < 0;
}
} // namespace ds
#endif // DRIVE_SINGULARITY_MATH_SEGMENT_H
| 32.616667 | 91 | 0.669903 | [
"vector"
] |
ac6c23a875f8873ba8e99607f4d991b33767dcf4 | 1,130 | h | C | src/mapper.h | evenleo/simple-mapreduce | e4ea504c2028743cea9636646ba4c7103e54adeb | [
"MIT"
] | 1 | 2020-08-10T14:16:42.000Z | 2020-08-10T14:16:42.000Z | src/mapper.h | evenleo/simple-mapreduce | e4ea504c2028743cea9636646ba4c7103e54adeb | [
"MIT"
] | null | null | null | src/mapper.h | evenleo/simple-mapreduce | e4ea504c2028743cea9636646ba4c7103e54adeb | [
"MIT"
] | null | null | null | #ifndef LMR_MAPPER_H
#define LMR_MAPPER_H
#include <string>
#include <vector>
#include <set>
#include <chrono>
#include <fstream>
#include <algorithm>
#include "mapinput.h"
#include "hash.h"
#include "reflector.h"
namespace lmr {
using namespace std;
class Mapper {
public:
virtual void init() {}
virtual void Map(const string& key, const string& value) = 0;
virtual void combine() {}
virtual ~Mapper() {}
void set_mapinput(MapInput* mapinput) { mapinput_ = mapinput; }
void set_hashfunc(HashFunction hashfunc) { hashfunc_ = hashfunc; }
void set_outputfile(const string& outputfile) { outputfile_ = outputfile; }
void set_numreducer(int num);
void mapwork();
protected:
void emit(string key, string value);
private:
void output();
HashFunction hashfunc_ = JSHash;
int num_reducer_ = 0;
string outputfile_;
MapInput* mapinput_ = nullptr;
vector<multiset<pair<string, string>>> out_;
};
#define MAPPER_CREATE(name) reinterpret_cast<Mapper*>(Reflector::Instance().CreateObject(name))
}
#endif //LMR_MAPPER_H
| 22.6 | 96 | 0.673451 | [
"vector"
] |
ac76c61b1ea30e4c063393fed1ffbf634bd0f8d5 | 1,567 | h | C | src/ctx/gen_ctx.h | Zx55/c0-cli | e17d1f682c00937884e52b81bc4e160f61dc69a1 | [
"MIT"
] | null | null | null | src/ctx/gen_ctx.h | Zx55/c0-cli | e17d1f682c00937884e52b81bc4e160f61dc69a1 | [
"MIT"
] | null | null | null | src/ctx/gen_ctx.h | Zx55/c0-cli | e17d1f682c00937884e52b81bc4e160f61dc69a1 | [
"MIT"
] | null | null | null | /*
* Created by zx5 on 2019/12/4.
* Copyright (c) zx5. All rights reserved.
*/
#ifndef C0_GEN_CTX_H
#define C0_GEN_CTX_H
#include "tools/error.h"
#include "symtbl/symtbl.h"
#include "ist/instruction.h"
namespace cc0 {
class GeneratorContext final {
private:
static SymTbl _tbl;
static std::vector<C0Err> _fatal;
static std::vector<C0Err> _wrns;
static std::vector<Instruction> _ist;
public:
GeneratorContext() = delete;
GeneratorContext(const GeneratorContext&) = delete;
GeneratorContext(GeneratorContext&&) = delete;
GeneratorContext& operator=(GeneratorContext ctx) = delete;
inline static void init_tbl() { _tbl.init(); }
inline static SymTbl& get_tbl() { return _tbl; }
[[nodiscard]] inline static auto&& get_fatals() { return std::move(_fatal); }
[[nodiscard]] inline static auto&& get_wrns() { return std::move(_wrns); }
[[nodiscard]] inline static auto&& get_ist() { return std::move(_ist); }
inline static void put_fatal(C0Err err) { _fatal.push_back(std::move(err)); }
inline static void put_wrn(C0Err wrn) { _wrns.push_back(std::move(wrn)); }
inline static void put_ist(Instruction ist) { _ist.push_back(std::move(ist)); }
[[nodiscard]] inline static Instruction& get_ist(uint32_t offset) { return _ist.at(offset); }
inline static void pop_ist() { _ist.pop_back(); }
inline static void pop_ist(uint32_t n) { _ist.erase(_ist.end() - n, _ist.end()); }
};
}
#endif //C0_GEN_CTX_H
| 35.613636 | 101 | 0.650925 | [
"vector"
] |
ac7742241f39694b40cd9e1ff74afabdffc3cced | 8,056 | c | C | marks.c | muflax-scholars/zathura | 6b0bd56842358a97ba3feba38dc48066ffc3a024 | [
"Zlib"
] | null | null | null | marks.c | muflax-scholars/zathura | 6b0bd56842358a97ba3feba38dc48066ffc3a024 | [
"Zlib"
] | null | null | null | marks.c | muflax-scholars/zathura | 6b0bd56842358a97ba3feba38dc48066ffc3a024 | [
"Zlib"
] | null | null | null | /* See LICENSE file for license and copyright information */
#include <stdlib.h>
#include <string.h>
#include <girara/session.h>
#include <girara/callbacks.h>
#include <girara/datastructures.h>
#include "callbacks.h"
#include "marks.h"
#include "document.h"
#include "render.h"
#include "utils.h"
static void mark_add(zathura_t* zathura, int key);
static void mark_evaluate(zathura_t* zathura, int key);
static bool cb_marks_view_key_press_event_add(GtkWidget* widget, GdkEventKey*
event, girara_session_t* session);
static bool cb_marks_view_key_press_event_evaluate(GtkWidget* widget,
GdkEventKey* event, girara_session_t* session);
struct zathura_mark_s {
int key; /**> Marks key */
double position_x; /**> Horizontal adjustment */
double position_y; /**> Vertical adjustment */
unsigned int page; /**> Page number */
double scale; /**> Zoom level */
};
bool
sc_mark_add(girara_session_t* session, girara_argument_t* UNUSED(argument),
girara_event_t* UNUSED(event), unsigned int UNUSED(t))
{
g_return_val_if_fail(session != NULL, FALSE);
g_return_val_if_fail(session->gtk.view != NULL, FALSE);
/* redirect signal handler */
g_signal_handler_disconnect(G_OBJECT(session->gtk.view), session->signals.view_key_pressed);
session->signals.view_key_pressed = g_signal_connect(G_OBJECT(session->gtk.view), "key-press-event",
G_CALLBACK(cb_marks_view_key_press_event_add), session);
return true;
}
bool
sc_mark_evaluate(girara_session_t* session, girara_argument_t* UNUSED(argument),
girara_event_t* UNUSED(event), unsigned int UNUSED(t))
{
g_return_val_if_fail(session != NULL, FALSE);
g_return_val_if_fail(session->gtk.view != NULL, FALSE);
/* redirect signal handler */
g_signal_handler_disconnect(G_OBJECT(session->gtk.view), session->signals.view_key_pressed);
session->signals.view_key_pressed = g_signal_connect(G_OBJECT(session->gtk.view), "key-press-event",
G_CALLBACK(cb_marks_view_key_press_event_evaluate), session);
return true;
}
bool
cb_marks_view_key_press_event_add(GtkWidget* UNUSED(widget), GdkEventKey* event,
girara_session_t* session)
{
g_return_val_if_fail(session != NULL, FALSE);
g_return_val_if_fail(session->gtk.view != NULL, FALSE);
g_return_val_if_fail(session->global.data != NULL, FALSE);
zathura_t* zathura = (zathura_t*) session->global.data;
/* reset signal handler */
g_signal_handler_disconnect(G_OBJECT(session->gtk.view), session->signals.view_key_pressed);
session->signals.view_key_pressed = g_signal_connect(G_OBJECT(session->gtk.view), "key-press-event",
G_CALLBACK(girara_callback_view_key_press_event), session);
/* evaluate key */
if (((event->keyval >= '0' && event->keyval <= '9') ||
(event->keyval >= 'a' && event->keyval <= 'z') ||
(event->keyval >= 'A' && event->keyval <= 'Z')
) == false) {
return false;
}
mark_add(zathura, event->keyval);
return true;
}
bool cb_marks_view_key_press_event_evaluate(GtkWidget* UNUSED(widget), GdkEventKey*
event, girara_session_t* session)
{
g_return_val_if_fail(session != NULL, FALSE);
g_return_val_if_fail(session->gtk.view != NULL, FALSE);
g_return_val_if_fail(session->global.data != NULL, FALSE);
zathura_t* zathura = (zathura_t*) session->global.data;
/* reset signal handler */
g_signal_handler_disconnect(G_OBJECT(session->gtk.view), session->signals.view_key_pressed);
session->signals.view_key_pressed = g_signal_connect(G_OBJECT(session->gtk.view), "key-press-event",
G_CALLBACK(girara_callback_view_key_press_event), session);
/* evaluate key */
if (((event->keyval >= '0' && event->keyval <= '9') ||
(event->keyval >= 'a' && event->keyval <= 'z') ||
(event->keyval >= 'A' && event->keyval <= 'Z')
) == false) {
return true;
}
mark_evaluate(zathura, event->keyval);
return true;
}
bool
cmd_marks_add(girara_session_t* session, girara_list_t* argument_list)
{
g_return_val_if_fail(session != NULL, false);
g_return_val_if_fail(session->global.data != NULL, false);
zathura_t* zathura = (zathura_t*) session->global.data;
if (girara_list_size(argument_list) < 1) {
return false;
}
char* key_string = girara_list_nth(argument_list, 0);
if (key_string == NULL) {
return false;
}
if (strlen(key_string) < 1 || strlen(key_string) > 1) {
return false;
}
char key = key_string[0];
if (((key >= 0x41 && key <= 0x5A) || (key >=
0x61 && key <= 0x7A)) == false) {
return false;
}
mark_add(zathura, key);
return false;
}
bool
cmd_marks_delete(girara_session_t* session, girara_list_t* argument_list)
{
g_return_val_if_fail(session != NULL, false);
g_return_val_if_fail(session->global.data != NULL, false);
zathura_t* zathura = (zathura_t*) session->global.data;
if (girara_list_size(argument_list) < 1) {
return false;
}
if (girara_list_size(zathura->global.marks) == 0) {
return false;
}
GIRARA_LIST_FOREACH(argument_list, char*, iter, key_string)
if (key_string == NULL) {
continue;
}
for (unsigned int i = 0; i < strlen(key_string); i++) {
char key = key_string[i];
if (((key >= 0x41 && key <= 0x5A) || (key >=
0x61 && key <= 0x7A)) == false) {
continue;
}
/* search for existing mark */
girara_list_iterator_t* mark_iter = girara_list_iterator(zathura->global.marks);
do {
zathura_mark_t* mark = (zathura_mark_t*) girara_list_iterator_data(mark_iter);
if (mark == NULL) {
continue;
}
if (mark->key == key) {
girara_list_remove(zathura->global.marks, mark);
continue;
}
} while (girara_list_iterator_next(mark_iter) != NULL);
girara_list_iterator_free(mark_iter);
}
GIRARA_LIST_FOREACH_END(argument_list, char*, iter, key_string);
return true;
}
void
mark_add(zathura_t* zathura, int key)
{
if (zathura == NULL || zathura->document == NULL || zathura->global.marks == NULL) {
return;
}
unsigned int page_id = zathura_document_get_current_page_number(zathura->document);
double position_x = zathura_document_get_position_x(zathura->document);
double position_y = zathura_document_get_position_y(zathura->document);
double scale = zathura_document_get_scale(zathura->document);
/* search for existing mark */
GIRARA_LIST_FOREACH(zathura->global.marks, zathura_mark_t*, iter, mark)
if (mark->key == key) {
mark->page = page_id;
mark->position_x = position_x;
mark->position_y = position_y;
mark->scale = scale;
return;
}
GIRARA_LIST_FOREACH_END(zathura->global.marks, zathura_mark_t*, iter, mark);
/* add new mark */
zathura_mark_t* mark = g_try_malloc0(sizeof(zathura_mark_t));
if (mark == NULL) {
return;
}
mark->key = key;
mark->page = page_id;
mark->position_x = position_x;
mark->position_y = position_y;
mark->scale = scale;
girara_list_append(zathura->global.marks, mark);
}
void
mark_evaluate(zathura_t* zathura, int key)
{
if (zathura == NULL || zathura->global.marks == NULL) {
return;
}
/* search for existing mark */
GIRARA_LIST_FOREACH(zathura->global.marks, zathura_mark_t*, iter, mark)
if (mark != NULL && mark->key == key) {
zathura_document_set_scale(zathura->document, mark->scale);
render_all(zathura);
zathura_jumplist_add(zathura);
page_set(zathura, mark->page);
position_set(zathura, mark->position_x, mark->position_y);
zathura_jumplist_add(zathura);
return;
}
GIRARA_LIST_FOREACH_END(zathura->global.marks, zathura_mark_t*, iter, mark);
}
void
mark_free(void* data)
{
if (data == NULL) {
return;
}
zathura_mark_t* mark = (zathura_mark_t*) data;
g_free(mark);
}
| 30.285714 | 102 | 0.667949 | [
"render"
] |
ac782606ff706a554a10d76fbc113985660db40a | 1,289 | h | C | src/utils/SkMultiPictureDocument.h | henry-luo/skia | 2f2187b66dca1761f590668d3cbdf07453df7b6f | [
"BSD-3-Clause"
] | 1 | 2019-10-29T14:36:32.000Z | 2019-10-29T14:36:32.000Z | src/utils/SkMultiPictureDocument.h | henry-luo/skia | 2f2187b66dca1761f590668d3cbdf07453df7b6f | [
"BSD-3-Clause"
] | 1 | 2017-06-18T00:25:03.000Z | 2017-11-29T16:01:48.000Z | src/utils/SkMultiPictureDocument.h | henry-luo/skia | 2f2187b66dca1761f590668d3cbdf07453df7b6f | [
"BSD-3-Clause"
] | 5 | 2017-11-30T06:06:50.000Z | 2022-03-31T21:48:49.000Z | /*
* Copyright 2016 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#ifndef SkMultiPictureDocument_DEFINED
#define SkMultiPictureDocument_DEFINED
/*
This format is not intended to be used in production.
For clients looking for a way to represent a document in memory,
struct Doc {
std::vector<sk_sp<SkPicture>> fPages;
std::vector<SkSize> fPageSizes;
};
or
struct Page {
sk_sp<SkPicture> fPage;
SkSize fPageSize;
};
std::vector<Page> pages;
would work much better.
Multi-SkPicture (MSKP) files are still useful for debugging and
testing.
The downsides of this format are currently:
- no way to extract a single page; must read the entire file at once.
- must use `dm` to convert to another format before passing into
standard skp tools.
- `dm` can extract the first page to skp, but no others.
TODO(halcanary): replace with somthing that addresses these issues.
*/
#include "SkDocument.h"
/** Writes into an experimental, undocumented file format that is
useful for debugging documents printed via Skia. */
SK_API sk_sp<SkDocument> SkMakeMultiPictureDocument(SkWStream* dst);
#endif // SkMultiPictureDocument_DEFINED
| 26.306122 | 73 | 0.718386 | [
"vector"
] |
ac7b20f4beea1f53c608a0f2207017006db93420 | 1,347 | h | C | FrekisSDKSample/Pods/Frekis/Frekis/FrekisFramework.framework/PrivateHeaders/FMBLEModel.h | frekisSDK/ios-sdk-sample | 57c7ad2e0e3c0689755d7a42f1952f472aaf08e6 | [
"MIT"
] | 1 | 2020-08-02T04:12:35.000Z | 2020-08-02T04:12:35.000Z | FrekisSDKSample/Pods/Frekis/Frekis/FrekisFramework.framework/PrivateHeaders/FMBLEModel.h | frekisSDK/ios-sdk-sample | 57c7ad2e0e3c0689755d7a42f1952f472aaf08e6 | [
"MIT"
] | 2 | 2020-08-17T11:50:37.000Z | 2021-09-19T11:21:23.000Z | FrekisSDKSample/Pods/Frekis/Frekis/FrekisFramework.framework/PrivateHeaders/FMBLEModel.h | frekisSDK/ios-sdk-sample | 57c7ad2e0e3c0689755d7a42f1952f472aaf08e6 | [
"MIT"
] | null | null | null | //
// FMBLEModel.h
// SolebeiSmartLock
//
// Created by Andy on 2018/5/31.
// Copyright © 2018年 FL SMART. All rights reserved.
//
#import "BaseModel.h"
#import <CoreBluetooth/CoreBluetooth.h>
@interface FMBLEModel : BaseModel
/** ble id */
@property (strong, nonatomic) NSString *identifier_ID;
/** name */
@property (strong, nonatomic) NSString *bleName;
/** password */
@property (strong, nonatomic) NSString *password;
/** battery */
@property (assign, nonatomic) NSInteger battery;
/** lock state: unlocked 0/ 1 locked/ */
@property (assign, nonatomic) NSInteger lockState;
/** auto unlock switch */
@property (assign, nonatomic) BOOL isAutoUnlock;
/** Vibration alert switch */
@property (assign, nonatomic) BOOL isVibrationAlert;
/** notification switch */
@property (assign, nonatomic) BOOL isNotification;
/** consign model switch 托运模式 */
@property (assign, nonatomic) BOOL isConsignModel;
/** mac string */
@property (strong, nonatomic) NSString *mac;
/** connection state */
@property (assign, nonatomic) BOOL isConnected;
/** Read */
@property (strong, nonatomic) CBCharacteristic *readCharacteristic;
/** Write */
@property (strong, nonatomic) CBCharacteristic *writeCharacteristic;
@property (strong, nonatomic) NSData *tokenData;
/** ble device object */
@property (strong, nonatomic) CBPeripheral *peripheral;
@end
| 26.411765 | 68 | 0.723831 | [
"object",
"model"
] |
ac82a6678e559fcaf98b65196410a822bd53d52b | 1,805 | h | C | RecoTracker/ConversionSeedGenerators/plugins/CombinedHitQuadrupletGeneratorForPhotonConversion.h | Purva-Chaudhari/cmssw | 32e5cbfe54c4d809d60022586cf200b7c3020bcf | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | RecoTracker/ConversionSeedGenerators/plugins/CombinedHitQuadrupletGeneratorForPhotonConversion.h | Purva-Chaudhari/cmssw | 32e5cbfe54c4d809d60022586cf200b7c3020bcf | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | RecoTracker/ConversionSeedGenerators/plugins/CombinedHitQuadrupletGeneratorForPhotonConversion.h | Purva-Chaudhari/cmssw | 32e5cbfe54c4d809d60022586cf200b7c3020bcf | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #ifndef CombinedHitQuadrupletGeneratorForPhotonConversion_H
#define CombinedHitQuadrupletGeneratorForPhotonConversion_H
#include <vector>
#include <memory>
#include "RecoTracker/TkHitPairs/interface/OrderedHitPairs.h"
#include "RecoTracker/TkHitPairs/interface/LayerHitMapCache.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "FWCore/Utilities/interface/EDGetToken.h"
class TrackingRegion;
class OrderedHitPairs;
class HitQuadrupletGeneratorFromLayerPairForPhotonConversion;
class SeedingLayerSetsHits;
namespace edm {
class Event;
class EventSetup;
class ParameterSet;
class ConsumesCollector;
} // namespace edm
#include "ConversionRegion.h"
/** \class CombinedHitQuadrupletGeneratorForPhotonConversion
* Hides set of HitQuadrupletGeneratorFromLayerPairForPhotonConversion generators.
*/
class CombinedHitQuadrupletGeneratorForPhotonConversion {
public:
typedef LayerHitMapCache LayerCacheType;
public:
CombinedHitQuadrupletGeneratorForPhotonConversion(const edm::ParameterSet& cfg, edm::ConsumesCollector& iC);
CombinedHitQuadrupletGeneratorForPhotonConversion(const CombinedHitQuadrupletGeneratorForPhotonConversion& cb) =
delete;
~CombinedHitQuadrupletGeneratorForPhotonConversion();
void hitPairs(const TrackingRegion&, OrderedHitPairs&, const edm::Event&, const edm::EventSetup&);
const OrderedHitPairs& run(const TrackingRegion& region, const edm::Event& ev, const edm::EventSetup& es);
void clearLayerCache() { theLayerCache.clear(); }
/*------------------------*/
private:
edm::EDGetTokenT<SeedingLayerSetsHits> theSeedingLayerToken;
const unsigned int theMaxElement;
LayerCacheType theLayerCache;
std::unique_ptr<HitQuadrupletGeneratorFromLayerPairForPhotonConversion> theGenerator;
OrderedHitPairs thePairs;
};
#endif
| 32.818182 | 114 | 0.818283 | [
"vector"
] |
ac83d2871349ec82d002bb710045eddc32da8dc7 | 948 | h | C | DiligentSamples/playground/pg_module/engine/src/DX11/SceneDX11.h | raptoravis/defpr | 7335474b09dde91710d7bb2725c06e88d95b86f3 | [
"Apache-2.0"
] | 3 | 2019-08-04T08:24:36.000Z | 2021-11-18T19:27:10.000Z | DiligentSamples/playground/pg_module/engine/src/DX11/SceneDX11.h | raptoravis/defpr | 7335474b09dde91710d7bb2725c06e88d95b86f3 | [
"Apache-2.0"
] | null | null | null | DiligentSamples/playground/pg_module/engine/src/DX11/SceneDX11.h | raptoravis/defpr | 7335474b09dde91710d7bb2725c06e88d95b86f3 | [
"Apache-2.0"
] | 1 | 2020-08-16T00:04:45.000Z | 2020-08-16T00:04:45.000Z | #pragma once
#include "../SceneBase.h"
class RenderDeviceDX11;
class SceneDX11 : public SceneBase
{
public:
SceneDX11( RenderDeviceDX11& pDevice );
virtual ~SceneDX11();
protected:
virtual std::shared_ptr<Buffer> CreateFloatVertexBuffer( const float* data, unsigned int count, unsigned int stride ) const;
virtual std::shared_ptr<Buffer> CreateUIntIndexBuffer( const unsigned int* data, unsigned int count ) const;
virtual std::shared_ptr<Mesh> CreateMesh() const;
virtual std::shared_ptr<Material> CreateMaterial() const;
virtual std::shared_ptr<Texture> CreateTexture( const std::wstring& fileName ) const;
virtual std::shared_ptr<Texture> CreateTexture2D( uint16_t width, uint16_t height );
virtual std::shared_ptr<Texture> GetDefaultTexture();
private:
RenderDeviceDX11& m_Device;
Microsoft::WRL::ComPtr<ID3D11Device2> m_pDevice;
Microsoft::WRL::ComPtr<ID3D11DeviceContext2> m_pContext;
}; | 33.857143 | 128 | 0.754219 | [
"mesh"
] |
fed9dbad56467547a0b295a96faa9a16150ce86b | 57,386 | c | C | base_station/app/Application/ble_remote_display/remote_display.c | Michael-Hollister/ti-diy-sub1-robot | f3fec3bd2f7ea59645f611095a7646c8d218cd9e | [
"MIT"
] | null | null | null | base_station/app/Application/ble_remote_display/remote_display.c | Michael-Hollister/ti-diy-sub1-robot | f3fec3bd2f7ea59645f611095a7646c8d218cd9e | [
"MIT"
] | null | null | null | base_station/app/Application/ble_remote_display/remote_display.c | Michael-Hollister/ti-diy-sub1-robot | f3fec3bd2f7ea59645f611095a7646c8d218cd9e | [
"MIT"
] | null | null | null | /******************************************************************************
@file remote_display.c
@brief This file contains the Remote Display sample application for use
with the CC2650 Bluetooth Low Energy Protocol Stack.
Group: WCS, BTS
Target Device: CC13xx
******************************************************************************
Copyright (c) 2013-2018, Texas Instruments Incorporated
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of Texas Instruments Incorporated nor the names of
its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************
Release Name: simplelink_cc13x2_sdk_2_20_00_
Release Date: 2018-07-02 19:40:58
*****************************************************************************/
/*********************************************************************
* INCLUDES
*/
#include <string.h>
#include <ti/sysbios/knl/Task.h>
#include <ti/sysbios/knl/Clock.h>
#include <ti/sysbios/knl/Event.h>
#include <ti/sysbios/knl/Queue.h>
#include <ti/display/Display.h>
#if !(defined __TI_COMPILER_VERSION__)
#include <intrinsics.h>
#endif
#include <ti/drivers/utils/List.h>
#include <icall.h>
#include "util.h"
#include <bcomdef.h>
/* This Header file contains all BLE API and icall structure definition */
#include <icall_ble_api.h>
#include <devinfoservice.h>
#include <remote_display_gatt_profile.h>
#ifdef USE_RCOSC
#include <rcosc_calibration.h>
#endif //USE_RCOSC
#include <board.h>
#include <board_key.h>
#include "remote_display.h"
#include <dmm/dmm_policy_blesp_wsnnode.h>
#ifdef RF_PROFILING
#include <ti/drivers/PIN.h>
#include <ti/drivers/pin/PINCC26XX.h>
#include "Board.h"
#endif
/*********************************************************************
* MACROS
*/
/*********************************************************************
* CONSTANTS
*/
// Address mode of the local device
#define DEFAULT_ADDRESS_MODE ADDRMODE_PUBLIC
// General discoverable mode: advertise indefinitely
#define DEFAULT_DISCOVERABLE_MODE GAP_ADTYPE_FLAGS_GENERAL
// Advertising interval when device is discoverable (units of 625us, 160=100ms)
#define DEFAULT_ADVERTISING_INTERVAL 160
// Minimum connection interval (units of 1.25ms, 80=100ms) for parameter update request
#define DEFAULT_DESIRED_MIN_CONN_INTERVAL 80
// Maximum connection interval (units of 1.25ms, 88=110ms) for parameter update request
#define DEFAULT_DESIRED_MAX_CONN_INTERVAL 88
// Slave latency to use for parameter update request
#define DEFAULT_DESIRED_SLAVE_LATENCY 0
// Supervision timeout value (units of 10ms, 300=3s) for parameter update request
#define DEFAULT_DESIRED_CONN_TIMEOUT 300
// Pass parameter updates to the app for it to decide.
#define DEFAULT_PARAM_UPDATE_REQ_DECISION GAP_UPDATE_REQ_PASS_TO_APP
// How often to perform periodic event (in ms)
#define RD_PERIODIC_EVT_PERIOD 5000
// How often to read current current RPA (in ms)
#define RD_READ_RPA_EVT_PERIOD 3000
// Delay (in ms) after connection establishment before sending a parameter update request
#define RD_SEND_PARAM_UPDATE_DELAY 1000
// Number of times to attempt to configure params, some apps will reject the
// update request if they are still discovering the attributes
#define MAX_PARAM_UPDATE_ATTEMPTS 3
// Task configuration
#define RD_TASK_PRIORITY 1
#ifndef RD_TASK_STACK_SIZE
#define RD_TASK_STACK_SIZE 1024
#endif
// Application events
#define RD_STATE_CHANGE_EVT 0
#define RD_CHAR_CHANGE_EVT 1
#define RD_KEY_CHANGE_EVT 2
#define RD_ADV_EVT 3
#define RD_PAIR_STATE_EVT 4
#define RD_PASSCODE_EVT 5
#define RD_READ_RPA_EVT 6
#define RD_SEND_PARAM_UPDATE_EVT 7
#define RD_UPDATE_NODE_ADDR_EVT 8
#define RD_UPDATE_CONC_LED_EVT 9
#define RD_UPDATE_NODE_DATA_EVT 10
#define RD_UPDATE_NODE_STATS_EVT 11
// Internal Events for RTOS application
#define RD_ICALL_EVT ICALL_MSG_EVENT_ID // Event_Id_31
#define RD_QUEUE_EVT UTIL_QUEUE_EVENT_ID // Event_Id_30
// Bitwise OR of all RTOS events to pend on
#define RD_ALL_EVENTS (RD_ICALL_EVT | \
RD_QUEUE_EVT)
// Size of string-converted device address ("0xXXXXXXXXXXXX")
#define RD_ADDR_STR_SIZE 15
// Row numbers for display
#define RD_ROW_TITLE 0
#define RD_ROW_SEPARATOR_1 1
#define RD_ROW_STATUS_1 2
#define RD_ROW_STATUS_2 3
#define RD_ROW_CONNECTION 4
#define RD_ROW_ADVSTATE 5
#define RD_ROW_IDA 6
#define RD_ROW_RPA 7
#define RD_ROW_WSN_DATA 8
#define RD_ROW_WSN_STATS_1 9
#define RD_ROW_WSN_STATS_2 10
#define RD_ROW_WSN_STATS_3 11
#define RD_ROW_DEBUG 12
// For storing the active connections
#define RD_RSSI_TRACK_CHNLS 1 // Max possible channels can be GAP_BONDINGS_MAX
#define RD_MAX_RSSI_STORE_DEPTH 5
#define RD_INVALID_HANDLE 0xFFFF
#define RSSI_2M_THRSHLD -30 // -80 dB rssi
#define RSSI_1M_THRSHLD -40 // -90 dB rssi
#define RSSI_S2_THRSHLD -50 // -100 dB rssi
#define RSSI_S8_THRSHLD -60 // -120 dB rssi
#define RD_PHY_NONE LL_PHY_NONE // No PHY set
#define AUTO_PHY_UPDATE 0xFF
// Spin if the expression is not true
#define REMOTEDISPLAY_ASSERT(expr) if (!(expr)) HAL_ASSERT_SPINLOCK;
/*********************************************************************
* TYPEDEFS
*/
// App event passed from stack modules. This type is defined by the application
// since it can queue events to itself however it wants.
typedef struct
{
uint8_t event; // event type
void *pData; // pointer to message
} rdEvt_t;
// Container to store passcode data when passing from gapbondmgr callback
// to app event. See the pfnPairStateCB_t documentation from the gapbondmgr.h
// header file for more information on each parameter.
typedef struct
{
uint8_t state;
uint16_t connHandle;
uint8_t status;
} rdPairStateData_t;
// Container to store passcode data when passing from gapbondmgr callback
// to app event. See the pfnPasscodeCB_t documentation from the gapbondmgr.h
// header file for more information on each parameter.
typedef struct
{
uint8_t deviceAddr[B_ADDR_LEN];
uint16_t connHandle;
uint8_t uiInputs;
uint8_t uiOutputs;
uint32_t numComparison;
} rdPasscodeData_t;
// Container to store advertising event data when passing from advertising
// callback to app event. See the respective event in GapAdvScan_Event_IDs
// in gap_advertiser.h for the type that pBuf should be cast to.
typedef struct
{
uint32_t event;
void *pBuf;
} rdGapAdvEventData_t;
// Container to store information from clock expiration using a flexible array
// since data is not always needed
typedef struct
{
uint8_t event; //
uint8_t data[];
} rdClockEventData_t;
// List element for parameter update and PHY command status lists
typedef struct
{
List_Elem elem;
uint16_t connHandle;
} rdConnHandleEntry_t;
// Connected device information
typedef struct
{
uint16_t connHandle; // Connection Handle
Clock_Struct* pUpdateClock; // pointer to clock struct
} rdConnRec_t;
/*********************************************************************
* GLOBAL VARIABLES
*/
// Display Interface
Display_Handle dispHandle = NULL;
// Task configuration
Task_Struct rdTask;
#if defined __TI_COMPILER_VERSION__
#pragma DATA_ALIGN(rdTaskStack, 8)
#else
#pragma data_alignment=8
#endif
uint8_t rdTaskStack[RD_TASK_STACK_SIZE];
/*********************************************************************
* LOCAL VARIABLES
*/
// Entity ID globally used to check for source and/or destination of messages
static ICall_EntityID selfEntity;
// Event globally used to post local events and pend on system and
// local events.
static ICall_SyncHandle syncEvent;
// Queue object used for app messages
static Queue_Struct appMsgQueue;
static Queue_Handle appMsgQueueHandle;
// Clock instance for internal periodic events. Only one is needed since
// GattServApp will handle notifying all connected GATT clients
static Clock_Struct clkPeriodic;
// Clock instance for RPA read events.
static Clock_Struct clkRpaRead;
// Memory to pass RPA read event ID to clock handler
rdClockEventData_t argRpaRead =
{ .event = RD_READ_RPA_EVT };
// Per-handle connection info
static rdConnRec_t connList[MAX_NUM_BLE_CONNS];
// List to store connection handles for queued param updates
static List_List paramUpdateList;
// GAP GATT Attributes
static uint8_t attDeviceName[GAP_DEVICE_NAME_LEN] = "Node Remote Display";
// Advertisement data
static uint8_t advertData[] =
{
0x02, // length of this data
GAP_ADTYPE_FLAGS,
DEFAULT_DISCOVERABLE_MODE | GAP_ADTYPE_FLAGS_BREDR_NOT_SUPPORTED,
// service UUID, to notify central devices what services are included
// in this peripheral
0x03, // length of this data
GAP_ADTYPE_16BIT_MORE, // some of the UUID's, but not all
LO_UINT16(RDPROFILE_SERV_UUID),
HI_UINT16(RDPROFILE_SERV_UUID)
};
// Scan Response Data
static uint8_t scanRspData[] =
{
// complete name
15, // length of this data
GAP_ADTYPE_LOCAL_NAME_COMPLETE,
'D',
'M',
'M',
' ',
'W',
's',
'n',
'N',
'o',
'd',
'e',
' ',
'R',
'D',
// connection interval range
5, // length of this data
GAP_ADTYPE_SLAVE_CONN_INTERVAL_RANGE,
LO_UINT16(DEFAULT_DESIRED_MIN_CONN_INTERVAL), // 100ms
HI_UINT16(DEFAULT_DESIRED_MIN_CONN_INTERVAL),
LO_UINT16(DEFAULT_DESIRED_MAX_CONN_INTERVAL), // 1s
HI_UINT16(DEFAULT_DESIRED_MAX_CONN_INTERVAL),
// Tx power level
2, // length of this data
GAP_ADTYPE_POWER_LEVEL,
0 // 0dBm
};
// Advertising handles
static uint8 advHandleLegacy;
// Address mode
static GAP_Addr_Modes_t addrMode = DEFAULT_ADDRESS_MODE;
// Current Random Private Address
static uint8 rpa[B_ADDR_LEN] = {0};
#ifdef RF_PROFILING
/* Pin driver handle */
static PIN_Handle rfBleProfilingPinHandle;
static PIN_State rfBleProfilingPinState;
#define BLE_CONNECTED_GPIO Board_DIO22
/*
* Application LED pin configuration table:
* - All LEDs board LEDs are off.
*/
PIN_Config rfBleProfilingPinTable[] =
{
BLE_CONNECTED_GPIO | PIN_GPIO_OUTPUT_EN | PIN_GPIO_LOW | PIN_PUSHPULL | PIN_DRVSTR_MAX,
PIN_TERMINATE
};
#endif
static RemoteDisplay_nodeCbs_t nodeCallbacks;
/*********************************************************************
* LOCAL FUNCTIONS
*/
static void RemoteDisplay_init( void );
static void RemoteDisplay_taskFxn(UArg a0, UArg a1);
static uint8_t RemoteDisplay_processStackMsg(ICall_Hdr *pMsg);
static uint8_t RemoteDisplay_processGATTMsg(gattMsgEvent_t *pMsg);
static void RemoteDisplay_processGapMessage(gapEventHdr_t *pMsg);
static void RemoteDisplay_advCallback(uint32_t event, void *pBuf, uintptr_t arg);
static void RemoteDisplay_processAdvEvent(rdGapAdvEventData_t *pEventData);
static void RemoteDisplay_processAppMsg(rdEvt_t *pMsg);
static void RemoteDisplay_processCharValueChangeEvt(uint8_t paramId);
static void RemoteDisplay_updateRPA(void);
static void RemoteDisplay_clockHandler(UArg arg);
static void RemoteDisplay_passcodeCb(uint8_t *pDeviceAddr, uint16_t connHandle,
uint8_t uiInputs, uint8_t uiOutputs,
uint32_t numComparison);
static void RemoteDisplay_pairStateCb(uint16_t connHandle, uint8_t state,
uint8_t status);
static void RemoteDisplay_processPairState(rdPairStateData_t *pPairState);
static void RemoteDisplay_processPasscode(rdPasscodeData_t *pPasscodeData);
static void RemoteDisplay_charValueChangeCB(uint8_t paramId);
static status_t RemoteDisplay_enqueueMsg(uint8_t event, void *pData);
static void RemoteDisplay_keyChangeHandler(uint8 keys);
static void RemoteDisplay_handleKeys(uint8_t keys);
static uint8_t RemoteDisplay_addConn(uint16_t connHandle);
static uint8_t RemoteDisplay_getConnIndex(uint16_t connHandle);
static uint8_t RemoteDisplay_removeConn(uint16_t connHandle);
static void RemoteDisplay_processParamUpdate(uint16_t connHandle);
static uint8_t RemoteDisplay_clearConnListEntry(uint16_t connHandle);
/*********************************************************************
* EXTERN FUNCTIONS
*/
extern void AssertHandler(uint8 assertCause, uint8 assertSubcause);
/*********************************************************************
* PROFILE CALLBACKS
*/
// GAP Bond Manager Callbacks
static gapBondCBs_t RemoteDisplay_BondMgrCBs =
{
RemoteDisplay_passcodeCb, // Passcode callback
RemoteDisplay_pairStateCb // Pairing/Bonding state Callback
};
// Remote Display GATT Profile Callbacks
static remoteDisplayProfileCBs_t RemoteDisplay_ProfileCBs =
{
RemoteDisplay_charValueChangeCB // Remote Display GATT Characteristic value change callback
};
/*********************************************************************
* PUBLIC FUNCTIONS
*/
/*********************************************************************
* @fn RemoteDisplay_registerNodeCbs
*
* @brief Register the wsn node callbacks
*/
void RemoteDisplay_registerNodeCbs(RemoteDisplay_nodeCbs_t nodeCbs)
{
nodeCallbacks = nodeCbs;
}
/*********************************************************************
* @fn RemoteDisplay_createTask
*
* @brief Task creation function for the Remote Display.
*/
void RemoteDisplay_createTask(void)
{
Task_Params taskParams;
// Configure task
Task_Params_init(&taskParams);
taskParams.stack = rdTaskStack;
taskParams.stackSize = RD_TASK_STACK_SIZE;
taskParams.priority = RD_TASK_PRIORITY;
Task_construct(&rdTask, RemoteDisplay_taskFxn, &taskParams, NULL);
}
/*********************************************************************
* @fn RemoteDisplay_setNodeAddress
*
* @brief Sets the nodes address characteristic
*/
void RemoteDisplay_setNodeAddress(uint8_t nodeAddress)
{
uint8_t *pValue = ICall_malloc(sizeof(uint8_t));
if (pValue)
{
*pValue = nodeAddress;
RemoteDisplay_enqueueMsg(RD_UPDATE_NODE_ADDR_EVT, pValue);
}
}
/*********************************************************************
* @fn RemoteDisplay_setNodeAddress
*
* @brief Sets the nodes address characteristic
*/
void RemoteDisplay_setConcLed(uint8_t concLed)
{
uint8_t *pValue = ICall_malloc(sizeof(uint8_t));
if (pValue)
{
*pValue = concLed;
RemoteDisplay_enqueueMsg(RD_UPDATE_CONC_LED_EVT, pValue);
}
}
/*********************************************************************
* @fn RemoteDisplay_updateNodeData
*
* @brief Sets the nodes data reading characteristic
*/
void RemoteDisplay_updateNodeData(uint8_t sensorData)
{
uint8_t *pValue = ICall_malloc(sizeof(uint8_t));
if (pValue)
{
*pValue = sensorData;
RemoteDisplay_enqueueMsg(RD_UPDATE_NODE_DATA_EVT, pValue);
}
}
/*********************************************************************
* @fn RemoteDisplay_updateNodeData
*
* @brief Sets the nodes data reading characteristic
*/
void RemoteDisplay_updateNodeWsnStats(RemoteDisplay_nodeWsnStats_t stats)
{
#ifdef RD_DISPLAY_WSN_STATS
RemoteDisplay_nodeWsnStats_t *pValue = ICall_malloc(sizeof(RemoteDisplay_nodeWsnStats_t));
if (pValue)
{
*pValue = stats;
RemoteDisplay_enqueueMsg(RD_UPDATE_NODE_STATS_EVT, pValue);
}
#endif //RD_DISPLAY_WSN_STATS
}
/*********************************************************************
* @fn RemoteDisplay_init
*
* @brief Called during initialization and contains application
* specific initialization (ie. hardware initialization/setup,
* table initialization, power up notification, etc), and
* profile initialization/setup.
*/
static void RemoteDisplay_init(void)
{
#ifdef RF_PROFILING
/* Open LED pins */
rfBleProfilingPinHandle = PIN_open(&rfBleProfilingPinState, rfBleProfilingPinTable);
/* Clear Debug pins */
PIN_setOutputValue(rfBleProfilingPinHandle, BLE_CONNECTED_GPIO, 0);
#endif
// ******************************************************************
// N0 STACK API CALLS CAN OCCUR BEFORE THIS CALL TO ICall_registerApp
// ******************************************************************
// Register the current thread as an ICall dispatcher application
// so that the application can send and receive messages.
ICall_registerApp(&selfEntity, &syncEvent);
#ifdef USE_RCOSC
RCOSC_enableCalibration();
#endif // USE_RCOSC
// Create an RTOS queue for message from profile to be sent to app.
appMsgQueueHandle = Util_constructQueue(&appMsgQueue);
// Set the Device Name characteristic in the GAP GATT Service
// For more information, see the section in the User's Guide:
// http://software-dl.ti.com/lprf/ble5stack-latest/
GGS_SetParameter(GGS_DEVICE_NAME_ATT, GAP_DEVICE_NAME_LEN, attDeviceName);
// Configure GAP
{
uint16_t paramUpdateDecision = DEFAULT_PARAM_UPDATE_REQ_DECISION;
// Pass all parameter update requests to the app for it to decide
GAP_SetParamValue(GAP_PARAM_LINK_UPDATE_DECISION, paramUpdateDecision);
}
// Setup the GAP Bond Manager. For more information see the GAP Bond Manager
// section in the User's Guide:
// http://software-dl.ti.com/lprf/ble5stack-latest/
{
// Don't send a pairing request after connecting; the peer device must
// initiate pairing
uint8_t pairMode = GAPBOND_PAIRING_MODE_WAIT_FOR_REQ;
// Use authenticated pairing: require passcode.
uint8_t mitm = TRUE;
// This device only has display capabilities. Therefore, it will display the
// passcode during pairing. However, since the default passcode is being
// used, there is no need to display anything.
uint8_t ioCap = GAPBOND_IO_CAP_DISPLAY_ONLY;
// Request bonding (storing long-term keys for re-encryption upon subsequent
// connections without repairing)
uint8_t bonding = TRUE;
GAPBondMgr_SetParameter(GAPBOND_PAIRING_MODE, sizeof(uint8_t), &pairMode);
GAPBondMgr_SetParameter(GAPBOND_MITM_PROTECTION, sizeof(uint8_t), &mitm);
GAPBondMgr_SetParameter(GAPBOND_IO_CAPABILITIES, sizeof(uint8_t), &ioCap);
GAPBondMgr_SetParameter(GAPBOND_BONDING_ENABLED, sizeof(uint8_t), &bonding);
}
// Initialize GATT attributes
GGS_AddService(GATT_ALL_SERVICES); // GAP GATT Service
GATTServApp_AddService(GATT_ALL_SERVICES); // GATT Service
DevInfo_AddService(); // Device Information Service
RemoteDisplay_AddService(GATT_ALL_SERVICES); // Remote Display GATT Profile
// Setup the Remote Display Characteristic Values
// For more information, see the GATT and GATTServApp sections in the User's Guide:
// http://software-dl.ti.com/lprf/ble5stack-latest/
{
uint8_t nodeReportIntervalDefaultValue = 1;
uint8_t concLedDefaultValue = 0;
uint8_t nodeDataDefaultValue = 1;
uint8_t nodeAdressDefaultValue[RDPROFILE_NODE_ADDR_CHAR_LEN] = { 0 };
RemoteDisplay_SetParameter(RDPROFILE_NODE_REPORT_INTERVAL_CHAR, sizeof(uint8_t),
&nodeReportIntervalDefaultValue);
RemoteDisplay_SetParameter(RDPROFILE_CONC_LED_CHAR, sizeof(uint8_t),
&concLedDefaultValue);
RemoteDisplay_SetParameter(RDPROFILE_NODE_DATA_CHAR, sizeof(uint8_t),
&nodeDataDefaultValue);
RemoteDisplay_SetParameter(RDPROFILE_NODE_ADDR_CHAR, RDPROFILE_NODE_ADDR_CHAR_LEN,
nodeAdressDefaultValue);
}
// Register callback with Remote Display GATT profile
RemoteDisplay_RegisterAppCBs(&RemoteDisplay_ProfileCBs);
// Start Bond Manager and register callback
VOID GAPBondMgr_Register(&RemoteDisplay_BondMgrCBs);
// Register with GAP for HCI/Host messages. This is needed to receive HCI
// events. For more information, see the HCI section in the User's Guide:
// http://software-dl.ti.com/lprf/ble5stack-latest/
GAP_RegisterForMsgs(selfEntity);
// Register for GATT local events and ATT Responses pending for transmission
GATT_RegisterForMsgs(selfEntity);
// Set default values for Data Length Extension
// Extended Data Length Feature is already enabled by default
{
// Set initial values to maximum, RX is set to max. by default(251 octets, 2120us)
// Some brand smartphone is essentially needing 251/2120, so we set them here.
#define APP_SUGGESTED_PDU_SIZE 251 //default is 27 octets(TX)
#define APP_SUGGESTED_TX_TIME 2120 //default is 328us(TX)
// This API is documented in hci.h
// See the LE Data Length Extension section in the BLE5-Stack User's Guide for information on using this command:
// http://software-dl.ti.com/lprf/ble5stack-latest/
HCI_LE_WriteSuggestedDefaultDataLenCmd(APP_SUGGESTED_PDU_SIZE, APP_SUGGESTED_TX_TIME);
}
// Initialize GATT Client
GATT_InitClient();
// Init key debouncer
Board_initKeys(RemoteDisplay_keyChangeHandler);
// Initialize Connection List
RemoteDisplay_clearConnListEntry(LL_CONNHANDLE_ALL);
//Initialize GAP layer for Peripheral role and register to receive GAP events
GAP_DeviceInit(GAP_PROFILE_PERIPHERAL, selfEntity, addrMode, NULL);
// The type of display is configured based on the BOARD_DISPLAY_USE...
// preprocessor definitions
dispHandle = Display_open(Display_Type_ANY, NULL);
// update display
Display_printf(dispHandle, RD_ROW_TITLE, 0, "Wsn Node Remote Display");
Display_printf(dispHandle, RD_ROW_SEPARATOR_1, 0, "====================");
}
/*********************************************************************
* @fn RemoteDisplay_taskFxn
*
* @brief Application task entry point for the Remote Display.
*
* @param a0, a1 - not used.
*/
static void RemoteDisplay_taskFxn(UArg a0, UArg a1)
{
// Initialize application
RemoteDisplay_init();
// Application main loop
for (;;)
{
uint32_t events;
// Waits for an event to be posted associated with the calling thread.
// Note that an event associated with a thread is posted when a
// message is queued to the message receive queue of the thread
events = Event_pend(syncEvent, Event_Id_NONE, RD_ALL_EVENTS,
ICALL_TIMEOUT_FOREVER);
if (events)
{
ICall_EntityID dest;
ICall_ServiceEnum src;
ICall_HciExtEvt *pMsg = NULL;
// Fetch any available messages that might have been sent from the stack
if (ICall_fetchServiceMsg(&src, &dest,
(void **)&pMsg) == ICALL_ERRNO_SUCCESS)
{
uint8 safeToDealloc = TRUE;
if ((src == ICALL_SERVICE_CLASS_BLE) && (dest == selfEntity))
{
ICall_Stack_Event *pEvt = (ICall_Stack_Event *)pMsg;
// Check for non-BLE stack events
if (pEvt->signature != 0xffff)
{
// Process inter-task message
safeToDealloc = RemoteDisplay_processStackMsg((ICall_Hdr *)pMsg);
}
}
if (pMsg && safeToDealloc)
{
ICall_freeMsg(pMsg);
}
}
// If RTOS queue is not empty, process app message.
if (events & RD_QUEUE_EVT)
{
while (!Queue_empty(appMsgQueueHandle))
{
rdEvt_t *pMsg = (rdEvt_t *)Util_dequeueMsg(appMsgQueueHandle);
if (pMsg)
{
// Process message.
RemoteDisplay_processAppMsg(pMsg);
// Free the space from the message.
ICall_free(pMsg);
}
}
}
}
}
}
/*********************************************************************
* @fn RemoteDisplay_processStackMsg
*
* @brief Process an incoming stack message.
*
* @param pMsg - message to process
*
* @return TRUE if safe to deallocate incoming message, FALSE otherwise.
*/
static uint8_t RemoteDisplay_processStackMsg(ICall_Hdr *pMsg)
{
// Always dealloc pMsg unless set otherwise
uint8_t safeToDealloc = TRUE;
switch (pMsg->event)
{
case GAP_MSG_EVENT:
RemoteDisplay_processGapMessage((gapEventHdr_t*) pMsg);
break;
case GATT_MSG_EVENT:
// Process GATT message
safeToDealloc = RemoteDisplay_processGATTMsg((gattMsgEvent_t *)pMsg);
break;
case HCI_GAP_EVENT_EVENT:
{
// Process HCI message
switch(pMsg->status)
{
case HCI_BLE_HARDWARE_ERROR_EVENT_CODE:
AssertHandler(HAL_ASSERT_CAUSE_HARDWARE_ERROR,0);
break;
default:
break;
}
break;
}
default:
// do nothing
break;
}
return (safeToDealloc);
}
/*********************************************************************
* @fn RemoteDisplay_processGATTMsg
*
* @brief Process GATT messages and events.
*
* @return TRUE if safe to deallocate incoming message, FALSE otherwise.
*/
static uint8_t RemoteDisplay_processGATTMsg(gattMsgEvent_t *pMsg)
{
if (pMsg->method == ATT_FLOW_CTRL_VIOLATED_EVENT)
{
// ATT request-response or indication-confirmation flow control is
// violated. All subsequent ATT requests or indications will be dropped.
// The app is informed in case it wants to drop the connection.
// Display the opcode of the message that caused the violation.
Display_printf(dispHandle, RD_ROW_STATUS_1, 0, "FC Violated: %d", pMsg->msg.flowCtrlEvt.opcode);
}
else if (pMsg->method == ATT_MTU_UPDATED_EVENT)
{
// MTU size updated
Display_printf(dispHandle, RD_ROW_STATUS_1, 0, "MTU Size: %d", pMsg->msg.mtuEvt.MTU);
}
// Free message payload. Needed only for ATT Protocol messages
GATT_bm_free(&pMsg->msg, pMsg->method);
// It's safe to free the incoming message
return (TRUE);
}
/*********************************************************************
* @fn RemoteDisplay_processAppMsg
*
* @brief Process an incoming callback from a profile.
*
* @param pMsg - message to process
*
* @return None.
*/
static void RemoteDisplay_processAppMsg(rdEvt_t *pMsg)
{
bool dealloc = TRUE;
switch (pMsg->event)
{
case RD_CHAR_CHANGE_EVT:
RemoteDisplay_processCharValueChangeEvt(*(uint8_t*)(pMsg->pData));
break;
case RD_KEY_CHANGE_EVT:
RemoteDisplay_handleKeys(*(uint8_t*)(pMsg->pData));
break;
case RD_ADV_EVT:
RemoteDisplay_processAdvEvent((rdGapAdvEventData_t*)(pMsg->pData));
break;
case RD_PAIR_STATE_EVT:
RemoteDisplay_processPairState((rdPairStateData_t*)(pMsg->pData));
break;
case RD_PASSCODE_EVT:
RemoteDisplay_processPasscode((rdPasscodeData_t*)(pMsg->pData));
break;
case RD_READ_RPA_EVT:
RemoteDisplay_updateRPA();
break;
case RD_SEND_PARAM_UPDATE_EVT:
{
// Extract connection handle from data
uint16_t connHandle = *(uint16_t *)(((rdClockEventData_t *)pMsg->pData)->data);
RemoteDisplay_processParamUpdate(connHandle);
// This data is not dynamically allocated
dealloc = FALSE;
break;
}
case RD_UPDATE_NODE_ADDR_EVT:
{
RemoteDisplay_SetParameter( RDPROFILE_NODE_ADDR_CHAR, RDPROFILE_NODE_ADDR_CHAR_LEN, (uint8_t*)(pMsg->pData) );
break;
}
case RD_UPDATE_CONC_LED_EVT:
{
RemoteDisplay_SetParameter( RDPROFILE_CONC_LED_CHAR, 1, (uint8_t*)(pMsg->pData) );
break;
}
case RD_UPDATE_NODE_DATA_EVT:
{
Display_printf(dispHandle, RD_ROW_WSN_DATA, 0, "WSN Node Data: %02x", *((uint8_t*)(pMsg->pData)));
// Note that if notifications of the fourth characteristic have been
// enabled by a GATT client device, then a notification will be sent
// every time this function is called.
RemoteDisplay_SetParameter(RDPROFILE_NODE_DATA_CHAR, sizeof(uint8_t),
(uint8_t*)(pMsg->pData));
break;
}
#ifdef RD_DISPLAY_WSN_STATS
case RD_UPDATE_NODE_STATS_EVT:
{
Display_printf(dispHandle, RD_ROW_WSN_STATS_1, 0, "WSN Node Statistics:");
Display_printf(dispHandle, RD_ROW_WSN_STATS_2, 0, "dataSendSuccess:%d, dataSendFail:%d dataTxSchError:%d, ",
((RemoteDisplay_nodeWsnStats_t*)(pMsg->pData))->dataSendSuccess,
((RemoteDisplay_nodeWsnStats_t*)(pMsg->pData))->dataSendFail,
((RemoteDisplay_nodeWsnStats_t*)(pMsg->pData))->dataTxSchError);
Display_printf(dispHandle, RD_ROW_WSN_STATS_3, 0, "ackRxTimeout:%d, ackRxSchError:%d, ackRxAbort:%d ",
((RemoteDisplay_nodeWsnStats_t*)(pMsg->pData))->ackRxTimeout,
((RemoteDisplay_nodeWsnStats_t*)(pMsg->pData))->ackRxSchError,
((RemoteDisplay_nodeWsnStats_t*)(pMsg->pData))->ackRxAbort);
break;
}
#endif //RD_DISPLAY_WSN_STATS
default:
// Do nothing.
break;
}
// Free message data if it exists and we are to dealloc
if ((dealloc == TRUE) && (pMsg->pData != NULL))
{
ICall_free(pMsg->pData);
}
}
/*********************************************************************
* @fn RemoteDisplay_processGapMessage
*
* @brief Process an incoming GAP event.
*
* @param pMsg - message to process
*/
static void RemoteDisplay_processGapMessage(gapEventHdr_t *pMsg)
{
switch(pMsg->opcode)
{
case GAP_DEVICE_INIT_DONE_EVENT:
{
bStatus_t status = FAILURE;
gapDeviceInitDoneEvent_t *pPkt = (gapDeviceInitDoneEvent_t *)pMsg;
if(pPkt->hdr.status == SUCCESS)
{
// Store the system ID
uint8_t systemId[DEVINFO_SYSTEM_ID_LEN];
// use 6 bytes of device address for 8 bytes of system ID value
systemId[0] = pPkt->devAddr[0];
systemId[1] = pPkt->devAddr[1];
systemId[2] = pPkt->devAddr[2];
// set middle bytes to zero
systemId[4] = 0x00;
systemId[3] = 0x00;
// shift three bytes up
systemId[7] = pPkt->devAddr[5];
systemId[6] = pPkt->devAddr[4];
systemId[5] = pPkt->devAddr[3];
// Set Device Info Service Parameter
DevInfo_SetParameter(DEVINFO_SYSTEM_ID, DEVINFO_SYSTEM_ID_LEN, systemId);
Display_printf(dispHandle, RD_ROW_STATUS_1, 0, "Initialized");
// Setup and start Advertising
// For more information, see the GAP section in the User's Guide:
// http://software-dl.ti.com/lprf/ble5stack-latest/
// Temporary memory for advertising parameters for set #1. These will be copied
// by the GapAdv module
GapAdv_params_t advParamLegacy = GAPADV_PARAMS_LEGACY_SCANN_CONN;
advParamLegacy.primIntMin = DEFAULT_ADVERTISING_INTERVAL;
advParamLegacy.primIntMax = DEFAULT_ADVERTISING_INTERVAL;
// Create Advertisement set #1 and assign handle
status = GapAdv_create(&RemoteDisplay_advCallback, &advParamLegacy,
&advHandleLegacy);
REMOTEDISPLAY_ASSERT(status == SUCCESS);
// Load advertising data for set #1 that is statically allocated by the app
status = GapAdv_loadByHandle(advHandleLegacy, GAP_ADV_DATA_TYPE_ADV,
sizeof(advertData), advertData);
REMOTEDISPLAY_ASSERT(status == SUCCESS);
// Load scan response data for set #1 that is statically allocated by the app
status = GapAdv_loadByHandle(advHandleLegacy, GAP_ADV_DATA_TYPE_SCAN_RSP,
sizeof(scanRspData), scanRspData);
REMOTEDISPLAY_ASSERT(status == SUCCESS);
// Set event mask for set #1
status = GapAdv_setEventMask(advHandleLegacy,
GAP_ADV_EVT_MASK_START_AFTER_ENABLE |
GAP_ADV_EVT_MASK_END_AFTER_DISABLE |
GAP_ADV_EVT_MASK_SET_TERMINATED);
// Enable legacy advertising for set #1
status = GapAdv_enable(advHandleLegacy, GAP_ADV_ENABLE_OPTIONS_USE_MAX , 0);
REMOTEDISPLAY_ASSERT(status == SUCCESS);
// Display device address
Display_printf(dispHandle, RD_ROW_IDA, 0, "%s Addr: %s",
(addrMode <= ADDRMODE_RANDOM) ? "Dev" : "ID",
Util_convertBdAddr2Str(pPkt->devAddr));
if (addrMode > ADDRMODE_RANDOM)
{
RemoteDisplay_updateRPA();
// Create one-shot clock for RPA check event.
Util_constructClock(&clkRpaRead, RemoteDisplay_clockHandler,
RD_READ_RPA_EVT_PERIOD, 0, true,
(UArg) &argRpaRead);
}
}
break;
}
case GAP_LINK_ESTABLISHED_EVENT:
{
gapEstLinkReqEvent_t *pPkt = (gapEstLinkReqEvent_t *)pMsg;
// Display the amount of current connections
uint8_t numActive = linkDB_NumActive();
Display_printf(dispHandle, RD_ROW_STATUS_2, 0, "Num Conns: %d",
(uint16_t)numActive);
if (pPkt->hdr.status == SUCCESS)
{
// Add connection to list and start RSSI
RemoteDisplay_addConn(pPkt->connectionHandle);
// Display the address of this connection
Display_printf(dispHandle, RD_ROW_STATUS_1, 0, "Connected to %s",
Util_convertBdAddr2Str(pPkt->devAddr));
// Start Periodic Clock.
Util_startClock(&clkPeriodic);
}
if (numActive < MAX_NUM_BLE_CONNS)
{
// Start advertising since there is room for more connections
GapAdv_enable(advHandleLegacy, GAP_ADV_ENABLE_OPTIONS_USE_MAX , 0);
}
else
{
// Stop advertising since there is no room for more connections
GapAdv_disable(advHandleLegacy, GAP_ADV_ENABLE_OPTIONS_USE_MAX , 0);
}
break;
}
case GAP_LINK_TERMINATED_EVENT:
{
gapTerminateLinkEvent_t *pPkt = (gapTerminateLinkEvent_t *)pMsg;
// Display the amount of current connections
uint8_t numActive = linkDB_NumActive();
Display_printf(dispHandle, RD_ROW_STATUS_1, 0, "Device Disconnected!");
Display_printf(dispHandle, RD_ROW_STATUS_2, 0, "Num Conns: %d",
(uint16_t)numActive);
// Remove the connection from the list and disable RSSI if needed
RemoteDisplay_removeConn(pPkt->connectionHandle);
// If no active connections
if (numActive == 0)
{
// Stop periodic clock
Util_stopClock(&clkPeriodic);
}
// Start advertising since there is room for more connections
GapAdv_enable(advHandleLegacy, GAP_ADV_ENABLE_OPTIONS_USE_MAX , 0);
// Clear remaining lines
Display_clearLine(dispHandle, RD_ROW_CONNECTION);
break;
}
case GAP_UPDATE_LINK_PARAM_REQ_EVENT:
{
gapUpdateLinkParamReqReply_t rsp;
gapUpdateLinkParamReqEvent_t *pReq = (gapUpdateLinkParamReqEvent_t *)pMsg;
rsp.connectionHandle = pReq->req.connectionHandle;
rsp.signalIdentifier = pReq->req.signalIdentifier;
// Only accept connection intervals with slave latency of 0
// This is just an example of how the application can send a response
if(pReq->req.connLatency == 0)
{
rsp.intervalMin = pReq->req.intervalMin;
rsp.intervalMax = pReq->req.intervalMax;
rsp.connLatency = pReq->req.connLatency;
rsp.connTimeout = pReq->req.connTimeout;
rsp.accepted = TRUE;
}
else
{
rsp.accepted = FALSE;
}
// Send Reply
VOID GAP_UpdateLinkParamReqReply(&rsp);
break;
}
case GAP_LINK_PARAM_UPDATE_EVENT:
{
gapLinkUpdateEvent_t *pPkt = (gapLinkUpdateEvent_t *)pMsg;
static uint8_t paramUpdateFailCnt = 0;
// Get the address from the connection handle
linkDBInfo_t linkInfo;
linkDB_GetInfo(pPkt->connectionHandle, &linkInfo);
if(pPkt->status == SUCCESS)
{
paramUpdateFailCnt = 0;
// Display the address of the connection update
Display_printf(dispHandle, RD_ROW_STATUS_2, 0, "Link Param Updated: %s",
Util_convertBdAddr2Str(linkInfo.addr));
}
else
{
paramUpdateFailCnt++;
// Display the address of the connection update failure
Display_printf(dispHandle, RD_ROW_STATUS_2, 0,
"Link Param Update Failed 0x%x: %s", pPkt->opcode,
Util_convertBdAddr2Str(linkInfo.addr));
if(paramUpdateFailCnt < MAX_PARAM_UPDATE_ATTEMPTS)
{
uint8_t connIndex = RemoteDisplay_getConnIndex(pPkt->connectionHandle);
rdClockEventData_t *paramUpdateEventData;
// Allocate data to send through clock handler
paramUpdateEventData = ICall_malloc(sizeof(rdClockEventData_t) +
sizeof (uint16_t));
if(paramUpdateEventData)
{
paramUpdateEventData->event = RD_SEND_PARAM_UPDATE_EVT;
*((uint16_t *)paramUpdateEventData->data) = pPkt->connectionHandle;
// Create a clock object and start
connList[connIndex].pUpdateClock
= (Clock_Struct*) ICall_malloc(sizeof(Clock_Struct));
if (connList[connIndex].pUpdateClock)
{
Util_constructClock(connList[connIndex].pUpdateClock,
RemoteDisplay_clockHandler,
(RD_SEND_PARAM_UPDATE_DELAY*paramUpdateFailCnt),
0, true, (UArg) paramUpdateEventData);
}
}
}
}
// Check if there are any queued parameter updates
rdConnHandleEntry_t *connHandleEntry = (rdConnHandleEntry_t *)List_get(¶mUpdateList);
if (connHandleEntry != NULL)
{
// Attempt to send queued update now
RemoteDisplay_processParamUpdate(connHandleEntry->connHandle);
// Free list element
ICall_free(connHandleEntry);
}
break;
}
default:
Display_clearLines(dispHandle, RD_ROW_STATUS_1, RD_ROW_STATUS_2);
break;
}
}
/*********************************************************************
* @fn RemoteDisplay_bleFastStateUpdateCb
*
* @brief Callback from BLE link layer to indicate a state change
*/
void RemoteDisplay_bleFastStateUpdateCb(uint32_t stackType, uint32_t stackState)
{
if(stackType == DMMPolicy_StackType_BlePeripheral)
{
static uint32_t prevStackState = 0;
if( !(prevStackState & LL_TASK_ID_SLAVE) && (stackState & LL_TASK_ID_SLAVE))
{
//We just connected
#ifdef RF_PROFILING
PIN_setOutputValue(rfBleProfilingPinHandle, BLE_CONNECTED_GPIO, 1);
#endif
/* update DMM policy */
DMMPolicy_updateStackState(DMMPolicy_StackType_BlePeripheral, DMMPOLICY_STACKSTATE_BLEPERIPH_CONNECTED);
}
else if( (prevStackState & LL_TASK_ID_SLAVE) && !(stackState & LL_TASK_ID_SLAVE))
{
//We just disconnected
#ifdef RF_PROFILING
PIN_setOutputValue(rfBleProfilingPinHandle, BLE_CONNECTED_GPIO, 0);
#endif
/* update DMM policy */
DMMPolicy_updateStackState(DMMPolicy_StackType_BlePeripheral, DMMPOLICY_STACKSTATE_BLEPERIPH_ADV);
}
prevStackState = stackState;
}
}
/*********************************************************************
* @fn RemoteDisplay_charValueChangeCB
*
* @brief Callback from REmote Display Profile indicating a characteristic
* value change.
*
* @param paramId - parameter Id of the value that was changed.
*
* @return None.
*/
static void RemoteDisplay_charValueChangeCB(uint8_t paramId)
{
uint8_t *pValue = ICall_malloc(sizeof(uint8_t));
if (pValue)
{
*pValue = paramId;
if (RemoteDisplay_enqueueMsg(RD_CHAR_CHANGE_EVT, pValue) != SUCCESS)
{
ICall_freeMsg(pValue);
}
}
}
/*********************************************************************
* @fn RemoteDisplay_processCharValueChangeEvt
*
* @brief Process a pending Remote Display Profile characteristic value change
* event.
*
* @param paramID - parameter ID of the value that was changed.
*/
static void RemoteDisplay_processCharValueChangeEvt(uint8_t paramId)
{
uint8_t newReportIntreval;
uint8_t newConLed;
uint8_t newNodeAddr[RDPROFILE_NODE_ADDR_CHAR_LEN];
switch(paramId)
{
case RDPROFILE_NODE_REPORT_INTERVAL_CHAR:
RemoteDisplay_GetParameter(RDPROFILE_NODE_REPORT_INTERVAL_CHAR, &newReportIntreval);
Display_printf(dispHandle, RD_ROW_STATUS_1, 0, "Report Interval Char: %d", (uint16_t)newReportIntreval);
if(nodeCallbacks.setReportIntervalCb != NULL)
{
nodeCallbacks.setReportIntervalCb(newReportIntreval);
}
break;
case RDPROFILE_CONC_LED_CHAR:
RemoteDisplay_GetParameter(RDPROFILE_CONC_LED_CHAR, &newConLed);
Display_printf(dispHandle, RD_ROW_STATUS_1, 0, "Conc LED Toggle Char: %d", (uint16_t)newConLed);
if(nodeCallbacks.setConcLedCb != NULL)
{
nodeCallbacks.setConcLedCb(newConLed);
}
break;
case RDPROFILE_NODE_ADDR_CHAR:
RemoteDisplay_GetParameter(RDPROFILE_NODE_ADDR_CHAR, newNodeAddr);
if(nodeCallbacks.setNodeAddressCb != NULL)
{
nodeCallbacks.setNodeAddressCb(newNodeAddr[0]);
}
break;
default:
// should not reach here!
break;
}
}
/*********************************************************************
* @fn RemoteDisplay_updateRPA
*
* @brief Read the current RPA from the stack and update display
* if the RPA has changed.
*
* @param None.
*
* @return None.
*/
static void RemoteDisplay_updateRPA(void)
{
uint8_t* pRpaNew;
// Read the current RPA.
pRpaNew = GAP_GetDevAddress(FALSE);
if (memcmp(pRpaNew, rpa, B_ADDR_LEN))
{
// If the RPA has changed, update the display
Display_printf(dispHandle, RD_ROW_RPA, 0, "RP Addr: %s",
Util_convertBdAddr2Str(pRpaNew));
memcpy(rpa, pRpaNew, B_ADDR_LEN);
}
}
/*********************************************************************
* @fn RemoteDisplay_clockHandler
*
* @brief Handler function for clock timeouts.
*
* @param arg - event type
*
* @return None.
*/
static void RemoteDisplay_clockHandler(UArg arg)
{
rdClockEventData_t *pData = (rdClockEventData_t *)arg;
if (pData->event == RD_READ_RPA_EVT)
{
// Start the next period
Util_startClock(&clkRpaRead);
// Post event to read the current RPA
RemoteDisplay_enqueueMsg(RD_READ_RPA_EVT, NULL);
}
else if (pData->event == RD_SEND_PARAM_UPDATE_EVT)
{
// Send message to app
RemoteDisplay_enqueueMsg(RD_SEND_PARAM_UPDATE_EVT, pData);
}
}
/*********************************************************************
* @fn RemoteDisplay_keyChangeHandler
*
* @brief Key event handler function
*
* @param keys - bitmap of pressed keys
*
* @return none
*/
static void RemoteDisplay_keyChangeHandler(uint8_t keys)
{
uint8_t *pValue = ICall_malloc(sizeof(uint8_t));
if (pValue)
{
*pValue = keys;
if(RemoteDisplay_enqueueMsg(RD_KEY_CHANGE_EVT, pValue) != SUCCESS)
{
ICall_freeMsg(pValue);
}
}
}
/*********************************************************************
* @fn RemoteDisplay_handleKeys
*
* @brief Handles all key events for this device.
*
* @param keys - bit field for key events. Valid entries:
* KEY_LEFT
* KEY_RIGHT
*/
static void RemoteDisplay_handleKeys(uint8_t keys)
{
/* add button precessing here
*/
}
/*********************************************************************
* @fn RemoteDisplay_advCallback
*
* @brief GapAdv module callback
*
* @param pMsg - message to process
*/
static void RemoteDisplay_advCallback(uint32_t event, void *pBuf, uintptr_t arg)
{
rdGapAdvEventData_t *pData = ICall_malloc(sizeof(rdGapAdvEventData_t));
if (pData)
{
pData->event = event;
pData->pBuf = pBuf;
if(RemoteDisplay_enqueueMsg(RD_ADV_EVT, pData) != SUCCESS)
{
ICall_freeMsg(pData);
}
}
}
/*********************************************************************
* @fn RemoteDisplay_processAdvEvent
*
* @brief Process advertising event in app context
*
* @param pEventData
*/
static void RemoteDisplay_processAdvEvent(rdGapAdvEventData_t *pEventData)
{
switch (pEventData->event)
{
case GAP_EVT_ADV_START_AFTER_ENABLE:
Display_printf(dispHandle, RD_ROW_ADVSTATE, 0, "Adv Set %d Enabled",
*(uint8_t *)(pEventData->pBuf));
break;
case GAP_EVT_ADV_END_AFTER_DISABLE:
Display_printf(dispHandle, RD_ROW_ADVSTATE, 0, "Adv Set %d Disabled",
*(uint8_t *)(pEventData->pBuf));
break;
case GAP_EVT_ADV_START:
break;
case GAP_EVT_ADV_END:
break;
case GAP_EVT_ADV_SET_TERMINATED:
{
GapAdv_setTerm_t *advSetTerm = (GapAdv_setTerm_t *)(pEventData->pBuf);
Display_printf(dispHandle, RD_ROW_ADVSTATE, 0, "Adv Set %d disabled after conn %d",
advSetTerm->handle, advSetTerm->connHandle );
}
break;
case GAP_EVT_SCAN_REQ_RECEIVED:
break;
case GAP_EVT_INSUFFICIENT_MEMORY:
break;
default:
break;
}
// All events have associated memory to free except the insufficient memory
// event
if (pEventData->event != GAP_EVT_INSUFFICIENT_MEMORY)
{
ICall_free(pEventData->pBuf);
}
}
/*********************************************************************
* @fn RemoteDisplay_pairStateCb
*
* @brief Pairing state callback.
*
* @return none
*/
static void RemoteDisplay_pairStateCb(uint16_t connHandle, uint8_t state,
uint8_t status)
{
rdPairStateData_t *pData = ICall_malloc(sizeof(rdPairStateData_t));
// Allocate space for the event data.
if (pData)
{
pData->state = state;
pData->connHandle = connHandle;
pData->status = status;
// Queue the event.
if(RemoteDisplay_enqueueMsg(RD_PAIR_STATE_EVT, pData) != SUCCESS)
{
ICall_freeMsg(pData);
}
}
}
/*********************************************************************
* @fn RemoteDisplay_passcodeCb
*
* @brief Passcode callback.
*
* @return none
*/
static void RemoteDisplay_passcodeCb(uint8_t *pDeviceAddr,
uint16_t connHandle,
uint8_t uiInputs,
uint8_t uiOutputs,
uint32_t numComparison)
{
rdPasscodeData_t *pData = ICall_malloc(sizeof(rdPasscodeData_t));
// Allocate space for the passcode event.
if (pData )
{
pData->connHandle = connHandle;
memcpy(pData->deviceAddr, pDeviceAddr, B_ADDR_LEN);
pData->uiInputs = uiInputs;
pData->uiOutputs = uiOutputs;
pData->numComparison = numComparison;
// Enqueue the event.
if(RemoteDisplay_enqueueMsg(RD_PASSCODE_EVT, pData) != SUCCESS)
{
ICall_freeMsg(pData);
}
}
}
/*********************************************************************
* @fn RemoteDisplay_processPairState
*
* @brief Process the new paring state.
*
* @return none
*/
static void RemoteDisplay_processPairState(rdPairStateData_t *pPairData)
{
uint8_t state = pPairData->state;
uint8_t status = pPairData->status;
switch (state)
{
case GAPBOND_PAIRING_STATE_STARTED:
Display_printf(dispHandle, RD_ROW_CONNECTION, 0, "Pairing started");
break;
case GAPBOND_PAIRING_STATE_COMPLETE:
if (status == SUCCESS)
{
Display_printf(dispHandle, RD_ROW_CONNECTION, 0, "Pairing success");
}
else
{
Display_printf(dispHandle, RD_ROW_CONNECTION, 0, "Pairing fail: %d", status);
}
break;
case GAPBOND_PAIRING_STATE_ENCRYPTED:
if (status == SUCCESS)
{
Display_printf(dispHandle, RD_ROW_CONNECTION, 0, "Encryption success");
}
else
{
Display_printf(dispHandle, RD_ROW_CONNECTION, 0, "Encryption failed: %d", status);
}
break;
case GAPBOND_PAIRING_STATE_BOND_SAVED:
if (status == SUCCESS)
{
Display_printf(dispHandle, RD_ROW_CONNECTION, 0, "Bond save success");
}
else
{
Display_printf(dispHandle, RD_ROW_CONNECTION, 0, "Bond save failed: %d", status);
}
break;
default:
break;
}
}
/*********************************************************************
* @fn RemoteDisplay_processPasscode
*
* @brief Process the Passcode request.
*
* @return none
*/
static void RemoteDisplay_processPasscode(rdPasscodeData_t *pPasscodeData)
{
// Display passcode to user
if (pPasscodeData->uiOutputs != 0)
{
Display_printf(dispHandle, RD_ROW_CONNECTION, 0, "Passcode: %d",
B_APP_DEFAULT_PASSCODE);
}
// Send passcode response
GAPBondMgr_PasscodeRsp(pPasscodeData->connHandle , SUCCESS,
B_APP_DEFAULT_PASSCODE);
}
/*********************************************************************
* @fn RemoteDisplay_enqueueMsg
*
* @brief Creates a message and puts the message in RTOS queue.
*
* @param event - message event.
* @param state - message state.
*/
static status_t RemoteDisplay_enqueueMsg(uint8_t event, void *pData)
{
uint8_t success;
rdEvt_t *pMsg = ICall_malloc(sizeof(rdEvt_t));
// Create dynamic pointer to message.
if(pMsg)
{
pMsg->event = event;
pMsg->pData = pData;
// Enqueue the message.
success = Util_enqueueMsg(appMsgQueueHandle, syncEvent, (uint8_t *)pMsg);
return (success) ? SUCCESS : FAILURE;
}
return(bleMemAllocError);
}
/*********************************************************************
* @fn RemoteDisplay_addConn
*
* @brief Add a device to the connected device list
*
* @return index of the connected device list entry where the new connection
* info is put in.
* if there is no room, MAX_NUM_BLE_CONNS will be returned.
*/
static uint8_t RemoteDisplay_addConn(uint16_t connHandle)
{
uint8_t i;
uint8_t status = bleNoResources;
rdClockEventData_t *paramUpdateEventData;
// Try to find an available entry
for (i = 0; i < MAX_NUM_BLE_CONNS; i++)
{
if (connList[i].connHandle == LL_CONNHANDLE_INVALID)
{
// Found available entry to put a new connection info in
connList[i].connHandle = connHandle;
// Allocate data to send through clock handler
paramUpdateEventData = ICall_malloc(sizeof(rdClockEventData_t) +
sizeof (uint16_t));
if(paramUpdateEventData)
{
paramUpdateEventData->event = RD_SEND_PARAM_UPDATE_EVT;
*((uint16_t *)paramUpdateEventData->data) = connHandle;
// Create a clock object and start
connList[i].pUpdateClock
= (Clock_Struct*) ICall_malloc(sizeof(Clock_Struct));
if (connList[i].pUpdateClock)
{
Util_constructClock(connList[i].pUpdateClock,
RemoteDisplay_clockHandler,
RD_SEND_PARAM_UPDATE_DELAY, 0, true,
(UArg) paramUpdateEventData);
}
}
else
{
status = bleMemAllocError;
}
break;
}
}
return status;
}
/*********************************************************************
* @fn RemoteDisplay_getConnIndex
*
* @brief Find index in the connected device list by connHandle
*
* @return the index of the entry that has the given connection handle.
* if there is no match, MAX_NUM_BLE_CONNS will be returned.
*/
static uint8_t RemoteDisplay_getConnIndex(uint16_t connHandle)
{
uint8_t i;
for (i = 0; i < MAX_NUM_BLE_CONNS; i++)
{
if (connList[i].connHandle == connHandle)
{
return i;
}
}
return(MAX_NUM_BLE_CONNS);
}
/*********************************************************************
* @fn RemoteDisplay_clearConnListEntry
*
* @brief Find index in the connected device list by connHandle
*
* @return the index of the entry that has the given connection handle.
* if there is no match, MAX_NUM_BLE_CONNS will be returned.
*/
static uint8_t RemoteDisplay_clearConnListEntry(uint16_t connHandle)
{
uint8_t i;
// Set to invalid connection index initially
uint8_t connIndex = MAX_NUM_BLE_CONNS;
if(connHandle != LL_CONNHANDLE_ALL)
{
// Get connection index from handle
connIndex = RemoteDisplay_getConnIndex(connHandle);
if(connIndex >= MAX_NUM_BLE_CONNS)
{
return(bleInvalidRange);
}
}
// Clear specific handle or all handles
for(i = 0; i < MAX_NUM_BLE_CONNS; i++)
{
if((connIndex == i) || (connHandle == LL_CONNHANDLE_ALL))
{
connList[i].connHandle = LL_CONNHANDLE_INVALID;
}
}
return(SUCCESS);
}
/*********************************************************************
* @fn RemoteDisplay_removeConn
*
* @brief Remove a device from the connected device list
*
* @return index of the connected device list entry where the new connection
* info is removed from.
* if connHandle is not found, MAX_NUM_BLE_CONNS will be returned.
*/
static uint8_t RemoteDisplay_removeConn(uint16_t connHandle)
{
uint8_t connIndex = RemoteDisplay_getConnIndex(connHandle);
if(connIndex != MAX_NUM_BLE_CONNS)
{
Clock_Struct* pUpdateClock = connList[connIndex].pUpdateClock;
if (pUpdateClock != NULL)
{
// Stop and destruct the RTOS clock if it's still alive
if (Util_isActive(pUpdateClock))
{
Util_stopClock(pUpdateClock);
}
// Destruct the clock object
Clock_destruct(pUpdateClock);
// Free clock struct
ICall_free(pUpdateClock);
}
// Clear Connection List Entry
RemoteDisplay_clearConnListEntry(connHandle);
}
return connIndex;
}
/*********************************************************************
* @fn RemoteDisplay_processParamUpdate
*
* @brief Remove a device from the connected device list
*
* @return index of the connected device list entry where the new connection
* info is removed from.
* if connHandle is not found, MAX_NUM_BLE_CONNS will be returned.
*/
static void RemoteDisplay_processParamUpdate(uint16_t connHandle)
{
gapUpdateLinkParamReq_t req;
uint8_t connIndex;
req.connectionHandle = connHandle;
req.connLatency = DEFAULT_DESIRED_SLAVE_LATENCY;
req.connTimeout = DEFAULT_DESIRED_CONN_TIMEOUT;
req.intervalMin = DEFAULT_DESIRED_MIN_CONN_INTERVAL;
req.intervalMax = DEFAULT_DESIRED_MAX_CONN_INTERVAL;
connIndex = RemoteDisplay_getConnIndex(connHandle);
REMOTEDISPLAY_ASSERT(connIndex < MAX_NUM_BLE_CONNS);
// Deconstruct the clock object
Clock_destruct(connList[connIndex].pUpdateClock);
// Free clock struct
ICall_free(connList[connIndex].pUpdateClock);
connList[connIndex].pUpdateClock = NULL;
// Send parameter update
bStatus_t status = GAP_UpdateLinkParamReq(&req);
// If there is an ongoing update, queue this for when the udpate completes
if (status == bleAlreadyInRequestedMode)
{
rdConnHandleEntry_t *connHandleEntry = ICall_malloc(sizeof(rdConnHandleEntry_t));
if (connHandleEntry)
{
connHandleEntry->connHandle = connHandle;
List_put(¶mUpdateList, (List_Elem *)&connHandleEntry);
}
}
}
/*********************************************************************
*********************************************************************/
| 30.985961 | 117 | 0.64514 | [
"object"
] |
fedb44f3875913671b11c8e7812b3b30a3462a21 | 464 | h | C | include/il2cpp/JumpCalculator.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | 1 | 2022-01-15T20:20:27.000Z | 2022-01-15T20:20:27.000Z | include/il2cpp/JumpCalculator.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | null | null | null | include/il2cpp/JumpCalculator.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | null | null | null | #pragma once
#include "il2cpp.h"
void JumpCalculator__Startup (JumpCalculator_o* __this, UnityEngine_Transform_o* transform, float moveDistance, float relativeHeight, float relativeLower, float duration, const MethodInfo* method_info);
UnityEngine_Vector3_o JumpCalculator__Process (JumpCalculator_o* __this, float deltaTime, bool* isFinished, const MethodInfo* method_info);
void JumpCalculator___ctor (JumpCalculator_o* __this, const MethodInfo* method_info);
| 58 | 202 | 0.842672 | [
"transform"
] |
fedc11ae4091d966d09a0f475f6a159e3a4c2b33 | 5,672 | h | C | src/aimp_dotnet/SDK/AimpCore.h | F8ER/aimp_dotnet | 2e93b9eda44cd77337b45f008d29eec574774064 | [
"Apache-2.0"
] | null | null | null | src/aimp_dotnet/SDK/AimpCore.h | F8ER/aimp_dotnet | 2e93b9eda44cd77337b45f008d29eec574774064 | [
"Apache-2.0"
] | null | null | null | src/aimp_dotnet/SDK/AimpCore.h | F8ER/aimp_dotnet | 2e93b9eda44cd77337b45f008d29eec574774064 | [
"Apache-2.0"
] | null | null | null | // ----------------------------------------------------
// AIMP DotNet SDK
// Copyright (c) 2014 - 2020 Evgeniy Bogdan
// https://github.com/martin211/aimp_dotnet
// Mail: mail4evgeniy@gmail.com
// ----------------------------------------------------
#pragma once
#include "SDK/AimpExtensionBase.h"
#include "AimpStream.h"
#include "Action/AimpAction.h"
#include "Lyrics/AimpLyrics.h"
#include "Menu/AimpMenuItem.h"
namespace AIMP {
namespace SDK {
using namespace System;
using namespace SDK;
[System::Serializable]
public ref class AimpCore : public IAimpCore {
private:
ManagedAimpCore^ _aimpCore;
bool _disposed;
public:
AimpCore(ManagedAimpCore^ core) {
_aimpCore = core;
}
~AimpCore() {
Diagnostics::Trace::TraceInformation("Dispose AimpCore");
Diagnostics::Trace::Flush();
if (_disposed) {
return;
}
this->!AimpCore();
_disposed = true;
}
!AimpCore() {
}
virtual String^ GetPath(MessageDispatcher::AimpCorePathType pathType) {
String^ path;
if (_aimpCore->GetPath(pathType, path) == ActionResultType::OK) {
return path;
}
return String::Empty;
}
virtual AimpActionResult^ SendMessage(MessageDispatcher::AimpCoreMessageType message, int value,
Object^ obj) {
return ACTION_RESULT(Utils::CheckResult(_aimpCore->SendMessage(message, value, obj)));
}
virtual AimpActionResult^ RegisterExtension(IAimpExtension^ extension) {
return ACTION_RESULT(
Utils::CheckResult(_aimpCore->RegisterExtension(IID_IAIMPOptionsDialogFrame, extension)));
}
virtual AimpActionResult^ UnregisterExtension(IAimpExtension^ extension) {
return ACTION_RESULT(Utils::CheckResult(_aimpCore->UnregisterExtension(extension)));
}
virtual StreamResult CreateStream() {
IAIMPStream* stream = nullptr;
const auto result = _aimpCore->CreateStream(&stream);
if (result == ActionResultType::OK && stream != nullptr) {
return gcnew AimpActionResult<IAimpStream^>(result, gcnew AimpStream(stream));
}
return gcnew AimpActionResult<IAimpStream^>(result, nullptr);
}
generic <class TAimpObject>
virtual AimpActionResult<IAimpObject^>^ CreateObject() {
const auto t = TAimpObject::typeid;
const auto core = _aimpCore->GetAimpCore();
if (t == IAimpStream::typeid) {
IAIMPStream* obj = nullptr;
IAimpStream^ managed = nullptr;
const auto result = Utils::CheckResult(
core->CreateObject(IID_IAIMPMemoryStream, reinterpret_cast<void**>(&obj)));
if (result == ActionResultType::OK) {
managed = gcnew AimpStream(obj);
}
return gcnew AimpActionResult<IAimpObject^>(result, managed);
}
if (t == IAimpAction::typeid) {
IAIMPAction* obj = nullptr;
IAimpAction^ managed = nullptr;
const auto result = Utils::CheckResult(
core->CreateObject(IID_IAIMPAction, reinterpret_cast<void**>(&obj)));
if (result == ActionResultType::OK) {
managed = gcnew AimpAction(obj);
}
return gcnew AimpActionResult<IAimpObject^>(result, managed);
}
if (t == IAimpFileInfo::typeid) {
IAIMPFileInfo* obj = nullptr;
IAimpFileInfo^ managed = nullptr;
const auto result = Utils::CheckResult(
core->CreateObject(IID_IAIMPFileInfo, reinterpret_cast<void**>(&obj)));
if (result == ActionResultType::OK) {
managed = gcnew AimpFileInfo(obj);
}
return gcnew AimpActionResult<IAimpObject^>(result, managed);
}
if (t == IAimpLyrics::typeid) {
IAIMPLyrics* obj = nullptr;
IAimpLyrics^ managed = nullptr;
const auto result = Utils::CheckResult(
core->CreateObject(IID_IAIMPLyrics, reinterpret_cast<void**>(&obj)));
if (result == ActionResultType::OK) {
managed = gcnew AimpLyrics(obj);
}
return gcnew AimpActionResult<IAimpObject^>(result, managed);
}
if (t == IAimpMenuItem::typeid) {
IAIMPMenuItem* obj = nullptr;
IAimpMenuItem^ managed = nullptr;
const auto result = Utils::CheckResult(
core->CreateObject(IID_IAIMPMenuItem, reinterpret_cast<void**>(&obj)));
if (result == ActionResultType::OK) {
managed = gcnew AimpMenuItem(obj);
}
return gcnew AimpActionResult<IAimpObject^>(result, managed);
}
return nullptr;
}
};
}
}
| 36.831169 | 110 | 0.50335 | [
"object"
] |
fee3a8b9423f9f8498fb48240f53739373fb3f5c | 17,762 | h | C | src/g_statusbar/sbar.h | Erick194/gzdoom | dcb7755716b7f4f6edce6f28b9e316d6de7eda15 | [
"RSA-MD"
] | 2 | 2020-04-19T13:37:34.000Z | 2021-06-09T04:26:25.000Z | src/g_statusbar/sbar.h | Erick194/gzdoom | dcb7755716b7f4f6edce6f28b9e316d6de7eda15 | [
"RSA-MD"
] | null | null | null | src/g_statusbar/sbar.h | Erick194/gzdoom | dcb7755716b7f4f6edce6f28b9e316d6de7eda15 | [
"RSA-MD"
] | null | null | null | /*
** sbar.h
** Base status bar definition
**
**---------------------------------------------------------------------------
** Copyright 1998-2006 Randy Heit
** 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. 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.
**---------------------------------------------------------------------------
**
*/
#ifndef __SBAR_H__
#define __SBAR_H__
#include "dobject.h"
#include "v_collection.h"
#include "v_text.h"
#include "r_data/renderstyle.h"
class player_t;
struct FRemapTable;
enum EHudState
{
HUD_StatusBar,
HUD_Fullscreen,
HUD_None,
HUD_AltHud // Used for passing through popups to the alt hud
};
enum EMonospacing : int;
// HUD Message base object --------------------------------------------------
// This is a mo-op base class to allow derived ZScript message types that can be managed by the status bar.
class DHUDMessageBase : public DObject
{
DECLARE_CLASS(DHUDMessageBase, DObject)
HAS_OBJECT_POINTERS
public:
virtual void Serialize(FSerializer &arc);
virtual bool Tick() { return true; } // Returns true to indicate time for removal
virtual void ScreenSizeChanged() {}
virtual void Draw(int bottom, int visibility) {}
bool CallTick(); // Returns true to indicate time for removal
void CallScreenSizeChanged();
void CallDraw(int bottom, int visibility);
private:
TObjPtr<DHUDMessageBase*> Next = nullptr;
uint32_t SBarID = 0;
friend class DBaseStatusBar;
};
// HUD Message --------------------------------------------------
class DHUDMessage : public DHUDMessageBase
{
DECLARE_CLASS (DHUDMessage, DHUDMessageBase)
public:
DHUDMessage (FFont *font, const char *text, float x, float y, int hudwidth, int hudheight,
EColorRange textColor, float holdTime);
virtual void OnDestroy () override;
virtual void Serialize(FSerializer &arc);
virtual void Draw (int bottom, int visibility) override;
virtual void ResetText (const char *text);
virtual void DrawSetup ();
virtual void DoDraw (int linenum, int x, int y, bool clean, int hudheight);
virtual bool Tick () override;
virtual void ScreenSizeChanged () override;
void SetVisibility(int vis)
{
VisibilityFlags = vis;
}
void SetRenderStyle(ERenderStyle style)
{
Style = style;
}
void SetAlpha(float alpha)
{
Alpha = alpha;
}
void SetNoWrap(bool nowrap)
{
NoWrap = nowrap;
ResetText(SourceText);
}
void SetClipRect(int x, int y, int width, int height, bool aspect)
{
ClipX = x;
ClipY = y;
ClipWidth = width;
ClipHeight = height;
HandleAspect = aspect;
}
void SetWrapWidth(int wrap)
{
WrapWidth = wrap;
ResetText(SourceText);
}
protected:
TArray<FBrokenLines> Lines;
int Width, Height, NumLines;
float Left, Top;
bool CenterX, NoWrap;
int HoldTics;
int Tics;
int State;
int VisibilityFlags;
int HUDWidth, HUDHeight;
int ClipX, ClipY, ClipWidth, ClipHeight, WrapWidth; // in HUD coords
int ClipLeft, ClipTop, ClipRight, ClipBot; // in screen coords
bool HandleAspect;
EColorRange TextColor;
FFont *Font;
FRenderStyle Style;
double Alpha;
void CalcClipCoords(int hudheight);
DHUDMessage () : SourceText(NULL) {}
private:
char *SourceText;
};
// HUD message visibility flags
enum
{
HUDMSG_NotWith3DView = 1,
HUDMSG_NotWithFullMap = 2,
HUDMSG_NotWithOverlayMap = 4,
};
// HUD Message; appear instantly, then fade out type ------------------------
class DHUDMessageFadeOut : public DHUDMessage
{
DECLARE_CLASS (DHUDMessageFadeOut, DHUDMessage)
public:
DHUDMessageFadeOut (FFont *font, const char *text, float x, float y, int hudwidth, int hudheight,
EColorRange textColor, float holdTime, float fadeOutTime);
virtual void Serialize(FSerializer &arc);
virtual void DoDraw (int linenum, int x, int y, bool clean, int hudheight);
virtual bool Tick ();
protected:
int FadeOutTics;
DHUDMessageFadeOut() {}
};
// HUD Message; fade in, then fade out type ---------------------------------
class DHUDMessageFadeInOut : public DHUDMessageFadeOut
{
DECLARE_CLASS (DHUDMessageFadeInOut, DHUDMessageFadeOut)
public:
DHUDMessageFadeInOut (FFont *font, const char *text, float x, float y, int hudwidth, int hudheight,
EColorRange textColor, float holdTime, float fadeInTime, float fadeOutTime);
virtual void Serialize(FSerializer &arc);
virtual void DoDraw (int linenum, int x, int y, bool clean, int hudheight);
virtual bool Tick ();
protected:
int FadeInTics;
DHUDMessageFadeInOut() {}
};
// HUD Message; type on, then fade out type ---------------------------------
class DHUDMessageTypeOnFadeOut : public DHUDMessageFadeOut
{
DECLARE_CLASS (DHUDMessageTypeOnFadeOut, DHUDMessageFadeOut)
public:
DHUDMessageTypeOnFadeOut (FFont *font, const char *text, float x, float y, int hudwidth, int hudheight,
EColorRange textColor, float typeTime, float holdTime, float fadeOutTime);
virtual void Serialize(FSerializer &arc);
virtual void DoDraw (int linenum, int x, int y, bool clean, int hudheight);
virtual bool Tick ();
virtual void ScreenSizeChanged ();
protected:
float TypeOnTime;
int CurrLine;
int LineVisible;
int LineLen;
DHUDMessageTypeOnFadeOut() {}
};
// Mug shots ----------------------------------------------------------------
struct FMugShotFrame
{
TArray<FString> Graphic;
int Delay;
FMugShotFrame();
~FMugShotFrame();
FTexture *GetTexture(const char *default_face, const char *skin_face, int random, int level=0,
int direction=0, bool usesLevels=false, bool health2=false, bool healthspecial=false,
bool directional=false);
};
struct FMugShotState
{
uint8_t bUsesLevels:1;
uint8_t bHealth2:1; // Health level is the 2nd character from the end.
uint8_t bHealthSpecial:1; // Like health2 only the 2nd frame gets the normal health type.
uint8_t bDirectional:1; // Faces direction of damage.
uint8_t bFinished:1;
unsigned int Position;
int Time;
int Random;
FName State = NAME_None;
TArray<FMugShotFrame> Frames;
FMugShotState(FName name);
~FMugShotState();
void Tick();
void Reset();
FMugShotFrame &GetCurrentFrame() { return Frames[Position]; }
FTexture *GetCurrentFrameTexture(const char *default_face, const char *skin_face, int level=0, int direction=0)
{
return GetCurrentFrame().GetTexture(default_face, skin_face, Random, level, direction, bUsesLevels, bHealth2, bHealthSpecial, bDirectional);
}
private:
FMugShotState();
};
class player_t;
class FMugShot
{
public:
enum StateFlags
{
STANDARD = 0x0,
XDEATHFACE = 0x1,
ANIMATEDGODMODE = 0x2,
DISABLEGRIN = 0x4,
DISABLEOUCH = 0x8,
DISABLEPAIN = 0x10,
DISABLERAMPAGE = 0x20,
CUSTOM = 0x40,
};
FMugShot();
void Grin(bool grin=true) { bEvilGrin = grin; }
void Reset();
void Tick(player_t *player);
bool SetState(const char *state_name, bool wait_till_done=false, bool reset=false);
int UpdateState(player_t *player, StateFlags stateflags=STANDARD);
FTexture *GetFace(player_t *player, const char *default_face, int accuracy, StateFlags stateflags=STANDARD);
private:
FMugShotState *CurrentState;
int RampageTimer;
int LastDamageAngle;
int FaceHealthNow;
int FaceHealthLast;
bool bEvilGrin;
bool bDamageFaceActive;
bool bNormal;
bool bOuchActive;
};
extern TArray<FMugShotState> MugShotStates;
FMugShotState *FindMugShotState(FName state);
int FindMugShotStateIndex(FName state);
// Base Status Bar ----------------------------------------------------------
class FTexture;
enum
{
HUDMSGLayer_OverHUD,
HUDMSGLayer_UnderHUD,
HUDMSGLayer_OverMap,
NUM_HUDMSGLAYERS,
HUDMSGLayer_Default = HUDMSGLayer_OverHUD,
};
//============================================================================
//
// encapsulates all settings a HUD font may need
//
//============================================================================
class DHUDFont : public DObject
{
// this blocks CreateNew on this class which is the intent here.
DECLARE_ABSTRACT_CLASS(DHUDFont, DObject);
public:
FFont *mFont;
int mSpacing;
EMonospacing mMonospacing;
int mShadowX;
int mShadowY;
DHUDFont(FFont *f, int sp, EMonospacing ms, int sx, int sy)
: mFont(f), mSpacing(sp), mMonospacing(ms), mShadowX(sx), mShadowY(sy)
{}
};
class DBaseStatusBar : public DObject
{
friend class DSBarInfo;
DECLARE_CLASS (DBaseStatusBar, DObject)
HAS_OBJECT_POINTERS
public:
// Popup screens for Strife's status bar
enum
{
POP_NoChange = -1,
POP_None,
POP_Log,
POP_Keys,
POP_Status
};
// Status face stuff
enum
{
ST_NUMPAINFACES = 5,
ST_NUMSTRAIGHTFACES = 3,
ST_NUMTURNFACES = 2,
ST_NUMSPECIALFACES = 3,
ST_NUMEXTRAFACES = 2,
ST_FACESTRIDE = ST_NUMSTRAIGHTFACES+ST_NUMTURNFACES+ST_NUMSPECIALFACES,
ST_NUMFACES = ST_FACESTRIDE*ST_NUMPAINFACES+ST_NUMEXTRAFACES,
ST_TURNOFFSET = ST_NUMSTRAIGHTFACES,
ST_OUCHOFFSET = ST_TURNOFFSET + ST_NUMTURNFACES,
ST_EVILGRINOFFSET = ST_OUCHOFFSET + 1,
ST_RAMPAGEOFFSET = ST_EVILGRINOFFSET + 1,
ST_GODFACE = ST_NUMPAINFACES*ST_FACESTRIDE,
ST_DEADFACE = ST_GODFACE + 1
};
enum EAlign
{
TOP = 0,
VCENTER = 1,
BOTTOM = 2,
VOFFSET = 3,
VMASK = 3,
LEFT = 0,
HCENTER = 4,
RIGHT = 8,
HOFFSET = 12,
HMASK = 12,
CENTER = VCENTER | HCENTER,
CENTER_BOTTOM = BOTTOM | HCENTER
};
DBaseStatusBar ();
void SetSize(int reltop = 32, int hres = 320, int vres = 200, int hhres = -1, int hvres = -1);
void OnDestroy() override;
void AttachMessage (DHUDMessageBase *msg, uint32_t id=0, int layer=HUDMSGLayer_Default);
DHUDMessageBase *DetachMessage (DHUDMessageBase *msg);
DHUDMessageBase *DetachMessage (uint32_t id);
void DetachAllMessages ();
void ShowPlayerName ();
double GetDisplacement() { return Displacement; }
int GetPlayer ();
static void AddBlend (float r, float g, float b, float a, float v_blend[4]);
// do not make this a DObject Serialize function because it's not used like one!
void SerializeMessages(FSerializer &arc);
void SetScale();
virtual void Tick ();
void CallTick();
virtual void Draw (EHudState state, double ticFrac);
void CallDraw(EHudState state, double ticFrac);
void DrawBottomStuff (EHudState state);
void DrawTopStuff (EHudState state);
void AttachToPlayer(player_t *player);
DVector2 GetHUDScale() const;
virtual void FlashCrosshair ();
virtual void BlendView (float blend[4]);
void NewGame ();
virtual void ScreenSizeChanged ();
void CallScreenSizeChanged();
void ShowPop (int popnum);
virtual bool MustDrawLog(EHudState state);
virtual void SetMugShotState (const char *state_name, bool wait_till_done=false, bool reset=false);
void DrawLog();
uint32_t GetTranslation() const;
void CreateAltHUD();
void DrawAltHUD();
void DrawGraphic(FTextureID texture, double x, double y, int flags, double Alpha, double boxwidth, double boxheight, double scaleX, double scaleY);
void DrawString(FFont *font, const FString &cstring, double x, double y, int flags, double Alpha, int translation, int spacing, EMonospacing monospacing, int shadowX, int shadowY, double scaleX, double scaleY);
void TransformRect(double &x, double &y, double &w, double &h, int flags = 0);
void Fill(PalEntry color, double x, double y, double w, double h, int flags = 0);
void SetClipRect(double x, double y, double w, double h, int flags = 0);
void BeginStatusBar(int resW, int resH, int relTop, bool forceScaled);
void BeginHUD(int resW, int resH, double Alpha, bool forceScaled = false);
bool ForceHUDScale(bool on) { std::swap(ForcedScale, on); return on; } // This is for SBARINFO which should not use BeginStatusBar or BeginHUD.
void StatusbarToRealCoords(double &x, double &y, double &w, double &h) const;
int GetTopOfStatusbar() const
{
return SBarTop;
}
//protected:
void DrawPowerups ();
void RefreshBackground () const;
private:
DObject *AltHud = nullptr;
public:
AActor *ValidateInvFirst (int numVisible) const;
void DrawCrosshair ();
// Sizing info for ths status bar.
int ST_X;
int ST_Y;
int SBarTop;
DVector2 SBarScale;
int RelTop;
int HorizontalResolution, VerticalResolution;
bool Scaled; // This needs to go away.
DVector2 defaultScale; // factor for fully scaled fullscreen display.
bool ForcedScale = false;
bool Centering;
bool FixedOrigin;
bool CompleteBorder;
double CrosshairSize;
double Displacement;
bool ShowLog;
int artiflashTick = 0;
double itemflashFade = 0.75;
player_t *CPlayer;
double Alpha = 1.;
DVector2 drawOffset = { 0,0 }; // can be set by subclasses to offset drawing operations
double drawClip[4] = { 0,0,0,0 }; // defines a clipping rectangle (not used yet)
bool fullscreenOffsets = false; // current screen is displayed with fullscreen behavior.
FMugShot mugshot;
private:
bool RepositionCoords (int &x, int &y, int xo, int yo, const int w, const int h) const;
void DrawMessages (int layer, int bottom);
void DrawConsistancy () const;
void DrawWaiting () const;
void SetDrawSize(int reltop, int hres, int vres);
TObjPtr<DHUDMessageBase*> Messages[NUM_HUDMSGLAYERS];
int BaseRelTop;
int BaseSBarHorizontalResolution;
int BaseSBarVerticalResolution;
int BaseHUDHorizontalResolution;
int BaseHUDVerticalResolution;
};
extern DBaseStatusBar *StatusBar;
// Status bar factories -----------------------------------------------------
DBaseStatusBar *CreateCustomStatusBar(int script=0);
// Crosshair stuff ----------------------------------------------------------
void ST_FormatMapName(FString &mapname, const char *mapnamecolor = "");
void ST_LoadCrosshair(bool alwaysload=false);
void ST_Clear();
void ST_CreateStatusBar(bool bTitleLevel);
extern FTexture *CrosshairImage;
int GetInventoryIcon(AActor *item, uint32_t flags, int *applyscale = nullptr);
enum DI_Flags
{
DI_SKIPICON = 0x1,
DI_SKIPALTICON = 0x2,
DI_SKIPSPAWN = 0x4,
DI_SKIPREADY = 0x8,
DI_ALTICONFIRST = 0x10,
DI_TRANSLATABLE = 0x20,
DI_FORCESCALE = 0x40,
DI_DIM = 0x80,
DI_DRAWCURSORFIRST = 0x100, // only for DrawInventoryBar.
DI_ALWAYSSHOWCOUNT = 0x200, // only for DrawInventoryBar.
DI_DIMDEPLETED = 0x400,
DI_DONTANIMATE = 0x800, // do not animate the texture
DI_MIRROR = 0x1000, // flip the texture horizontally, like a mirror
DI_SCREEN_AUTO = 0, // decide based on given offsets.
DI_SCREEN_MANUAL_ALIGN = 0x4000, // If this is on, the following flags will have an effect
DI_SCREEN_TOP = DI_SCREEN_MANUAL_ALIGN,
DI_SCREEN_VCENTER = 0x8000 | DI_SCREEN_MANUAL_ALIGN,
DI_SCREEN_BOTTOM = 0x10000 | DI_SCREEN_MANUAL_ALIGN,
DI_SCREEN_VOFFSET = 0x18000 | DI_SCREEN_MANUAL_ALIGN,
DI_SCREEN_VMASK = 0x18000 | DI_SCREEN_MANUAL_ALIGN,
DI_SCREEN_LEFT = DI_SCREEN_MANUAL_ALIGN,
DI_SCREEN_HCENTER = 0x20000 | DI_SCREEN_MANUAL_ALIGN,
DI_SCREEN_RIGHT = 0x40000 | DI_SCREEN_MANUAL_ALIGN,
DI_SCREEN_HOFFSET = 0x60000 | DI_SCREEN_MANUAL_ALIGN,
DI_SCREEN_HMASK = 0x60000 | DI_SCREEN_MANUAL_ALIGN,
DI_SCREEN_LEFT_TOP = DI_SCREEN_TOP|DI_SCREEN_LEFT,
DI_SCREEN_RIGHT_TOP = DI_SCREEN_TOP|DI_SCREEN_RIGHT,
DI_SCREEN_LEFT_BOTTOM = DI_SCREEN_BOTTOM|DI_SCREEN_LEFT,
DI_SCREEN_RIGHT_BOTTOM = DI_SCREEN_BOTTOM|DI_SCREEN_RIGHT,
DI_SCREEN_CENTER = DI_SCREEN_VCENTER|DI_SCREEN_HCENTER,
DI_SCREEN_CENTER_BOTTOM = DI_SCREEN_BOTTOM|DI_SCREEN_HCENTER,
DI_SCREEN_OFFSETS = DI_SCREEN_HOFFSET|DI_SCREEN_VOFFSET,
DI_ITEM_AUTO = 0, // equivalent with bottom center, which is the default alignment.
DI_ITEM_TOP = 0x80000,
DI_ITEM_VCENTER = 0x100000,
DI_ITEM_BOTTOM = 0, // this is the default vertical alignment
DI_ITEM_VOFFSET = 0x180000,
DI_ITEM_VMASK = 0x180000,
DI_ITEM_LEFT = 0x200000,
DI_ITEM_HCENTER = 0, // this is the deafault horizontal alignment
DI_ITEM_RIGHT = 0x400000,
DI_ITEM_HOFFSET = 0x600000,
DI_ITEM_HMASK = 0x600000,
DI_ITEM_LEFT_TOP = DI_ITEM_TOP|DI_ITEM_LEFT,
DI_ITEM_RIGHT_TOP = DI_ITEM_TOP|DI_ITEM_RIGHT,
DI_ITEM_LEFT_BOTTOM = DI_ITEM_BOTTOM|DI_ITEM_LEFT,
DI_ITEM_RIGHT_BOTTOM = DI_ITEM_BOTTOM|DI_ITEM_RIGHT,
DI_ITEM_CENTER = DI_ITEM_VCENTER|DI_ITEM_HCENTER,
DI_ITEM_CENTER_BOTTOM = DI_ITEM_BOTTOM|DI_ITEM_HCENTER,
DI_ITEM_OFFSETS = DI_ITEM_HOFFSET|DI_ITEM_VOFFSET,
DI_TEXT_ALIGN_LEFT = 0,
DI_TEXT_ALIGN_RIGHT = 0x800000,
DI_TEXT_ALIGN_CENTER = 0x1000000,
DI_TEXT_ALIGN = 0x1800000,
DI_ALPHAMAPPED = 0x2000000,
DI_NOSHADOW = 0x4000000,
DI_ALWAYSSHOWCOUNTERS = 0x8000000,
DI_ARTIFLASH = 0x10000000,
DI_FORCEFILL = 0x20000000,
// These 2 flags are only used by SBARINFO so these duplicate other flags not used by SBARINFO
DI_DRAWINBOX = DI_TEXT_ALIGN_RIGHT,
DI_ALTERNATEONFAIL = DI_TEXT_ALIGN_CENTER,
};
#endif /* __SBAR_H__ */
| 28.97553 | 211 | 0.724243 | [
"object"
] |
fee5117e84bfe0fdfbbc0f09b9ded2785ec2b057 | 72,245 | h | C | src/xtd.core/include/xtd/io/directory_info.h | BaderEddineOuaich/xtd | 6f28634c7949a541d183879d2de18d824ec3c8b1 | [
"MIT"
] | 1 | 2022-02-25T16:53:06.000Z | 2022-02-25T16:53:06.000Z | src/xtd.core/include/xtd/io/directory_info.h | leanid/xtd | 2e1ea6537218788ca08901faf8915d4100990b53 | [
"MIT"
] | null | null | null | src/xtd.core/include/xtd/io/directory_info.h | leanid/xtd | 2e1ea6537218788ca08901faf8915d4100990b53 | [
"MIT"
] | null | null | null | /// @file
/// @brief Contains xtd::io::directory_info class.
/// @copyright Copyright (c) 2022 Gammasoft. All rights reserved.
#pragma once
#include <iterator>
#include <memory>
#include "file_system_info.h"
/// @brief The xtd namespace contains all fundamental classes to access Hardware, Os, System, and more.
namespace xtd {
/// @brief The xtd::io namespace contains types that allow reading and writing to files and data streams, and types that provide basic file and directory support.
namespace io {
/// @cond
class directory;
class file_info;
/// @endcond
/// @brief Exposes instance methods for creating, moving, and enumerating through directories and subdirectories. This class cannot be inherited.
/// @code
/// class core_export_ directory_info final : public xtd::io::file_system_info
/// @endcode
/// @par Inheritance
/// xtd::io::file_system_info → xtd::io::directory_info
/// @par Namespace
/// xtd::io
/// @par Library
/// xtd.core
/// @ingroup xtd_core io
/// @par Examples
/// The following example demonstrates some of the main members of the xtd::io::directory_info class.
/// @code
/// #include <xtd/xtd>
///
/// using namespace xtd;
/// using namespace xtd::io;
///
/// class program {
/// public:
/// static void main() {
/// // Specify the directories you want to manipulate.
/// directory_info di("c:\\MyDir");
/// try {
/// // Determine whether the directory exists.
/// if (di.exists()) {
/// // Indicate that the directory already exists.
/// console::write_line("That path exists already.");
/// return;
/// }
///
/// // Try to create the directory.
/// di.create();
/// console::write_line("The directory was created successfully.");
///
/// // Delete the directory.
/// di.remove();
/// console::write_line("The directory was deleted successfully.");
/// }
/// catch (const system_exception& e) {
/// console::write_line("The process failed: {0}", e.to_string());
/// }
/// }
/// };
///
/// startup_(program);
/// @endcode
/// @par Examples
/// The following example demonstrates how to copy a directory and its contents.
/// @code
/// #include <xtd/xtd>
///
/// using namespace xtd;
/// using namespace xtd::io;
///
/// class copy_dir {
/// public:
/// static void copy_all(const directory_info& source, const directory_info& target) {
/// if (source.full_name().to_lower() == target.full_name().to_lower()) {
/// return;
/// }
///
/// // Check if the target directory exists, if not, create it.
/// if (directory::exists(target.full_name()) == false) {
/// directory::create_directory(target.full_name());
/// }
///
/// // Copy each file into it's new directory.
/// for (file_info fi : source.get_files()) {
/// console::write_line("Copying {0}\\{1}", target.full_name(), fi.name());
/// fi.copy_to(path::combine(target.to_string(), fi.name()), true);
/// }
///
/// // Copy each subdirectory using recursion.
/// for (directory_info di_source_sub_dir : source.get_directories()) {
/// directory_info next_target_sub_dir = target.create_subdirectory(di_source_sub_dir.name());
/// copy_all(di_source_sub_dir, next_target_sub_dir);
/// }
/// }
///
/// static void main() {
/// ustring source_directory = "c:\\source_directory";
/// ustring target_directory = "c:\\target_directory";
///
/// directory_info di_source(source_directory);
/// directory_info di_target(target_directory);
///
/// copy_all(di_source, di_target);
/// }
/// };
///
/// startup_(copy_dir);
///
/// // Output will vary based on the contents of the source directory.
/// @endcode
/// @remarks Use the xtd::io::directory_info class for typical operations such as copying, moving, renaming, creating, and deleting directories.
/// @remarks If you are going to reuse an object several times, consider using the instance method of xtd::io::directory_info instead of the corresponding static methods of the xtd::io::directory class, because a security check will not always be necessary.
/// @note In members that accept a path as an input string, that path must be well-formed or an exception is raised. For example, if a path is fully qualified but begins with a space, the path is not trimmed in methods of the class. Therefore, the path is malformed and an exception is raised. Similarly, a path or a combination of paths cannot be fully qualified twice. For example, "c:\temp c:\windows" also raises an exception in most cases. Ensure that your paths are well-formed when using methods that accept a path string.
/// @remarks In members that accept a path, the path can refer to a file or just a directory. The specified path can also refer to a relative path or a Universal Naming Convention (UNC) path for a server and share name. For example, all the following are acceptable paths:
/// * "c:\\MyDir\\MyFile.txt".
/// * "c:\\MyDir".
/// * "MyDir\\MySubdir".
/// * "\\\\MyServer\\MyShare".
/// @remarks By default, full read/write access to new directories is granted to all users.
/// @remarks For a list of common I/O tasks, see <a href="https://github.com/gammasoft71/xtd/blob/master/docs/tutorial_common_io_tasks.md">Common I/O Tasks</a>.
class core_export_ directory_info final : public xtd::io::file_system_info {
public:
/// @brief Represent directory iterator used by xtd::io::directory_info.
class directory_iterator : public std::iterator<std::input_iterator_tag, xtd::io::directory_info> {
explicit directory_iterator(const xtd::ustring& path, const xtd::ustring& pattern);
public:
/// @cond
directory_iterator();
directory_iterator(const directory_iterator&) = default;
directory_iterator(directory_iterator&&) = default;
directory_iterator& operator++();
directory_iterator operator++(int);
bool operator==(directory_iterator other) const;
bool operator!=(directory_iterator other) const {return !operator==(other);}
value_type operator*() const;
/// @endcond
private:
friend xtd::io::directory;
friend xtd::io::directory_info;
struct data;
std::shared_ptr<data> data_;
};
/// @brief Represent file iterator used by xtd::io::directory_info.
class file_iterator : public std::iterator<std::input_iterator_tag, xtd::io::file_info> {
explicit file_iterator(const std::string& path, const std::string& pattern);
public:
/// @cond
file_iterator();
file_iterator(const file_iterator&) = default;
file_iterator(file_iterator&&) = default;
file_iterator& operator++();
file_iterator operator++(int);
bool operator==(file_iterator other) const;
bool operator!=(file_iterator other) const {return !operator==(other);}
value_type operator*() const;
/// @endcond
private:
friend xtd::io::directory;
friend xtd::io::directory_info;
struct data;
std::shared_ptr<data> data_;
};
/// @brief Represent file system iterator used by xtd::io::directory_info.
class file_system_info_iterator : public std::iterator<std::input_iterator_tag, std::shared_ptr<xtd::io::file_system_info>> {
explicit file_system_info_iterator(const std::string& path, const std::string& pattern);
public:
/// @cond
file_system_info_iterator();
file_system_info_iterator(const file_system_info_iterator&) = default;
file_system_info_iterator(file_system_info_iterator&&) = default;
file_system_info_iterator& operator++();
file_system_info_iterator operator++(int);
bool operator==(file_system_info_iterator other) const;
bool operator!=(file_system_info_iterator other) const {return !operator==(other);}
value_type operator*() const;
/// @endcond
private:
friend xtd::io::directory;
friend xtd::io::directory_info;
struct data;
std::shared_ptr<data> data_;
};
/// @name Fields
/// @{
/// @brief Represents the uninitialized xtd::io::directory_info object. This field is constant.
static const directory_info empty;
/// @}
/// @name Constructors
/// @{
/// @brief Initializes a new instance of the xtd::io::directory_info class on the specified path.
/// @param path A string specifying the path on which to create the xtd::io::directory_info.
/// @exception xtd::security::security_exception The caller does not have the required permission.
/// @exception xtd::argument_exception path contains invalid characters such as ", <, >, or |.
/// @exception xtd::io::path_too_long_exception The specified path, file name, or both exceed the system-defined maximum length.
/// @par Examples
/// The following example uses this constructor to create the specified directory and subdirectory, and demonstrates that a directory that contains subdirectories cannot be deleted.
/// @code
/// #include <xtd/xtd>
///
/// using namespace xtd;
/// using namespace xtd::io;
///
/// class program {
/// public:
/// static void main() {
/// // Specify the directories you want to manipulate.
/// directory_info di1(R"(c:\MyDir)");
/// directory_info di2(R"(c:\MyDir\temp)");
///
/// try {
/// // Create the directories.
/// di1.create();
/// di2.create();
///
/// // This operation will not be allowed because there are subdirectories.
/// console::write_line("I am about to attempt to delete {0}.", di1.name());
/// di1.remove();
/// console::write_line("The delete operation was successful, which was unexpected.");
/// } catch (const system_exception&) {
/// console::write_line("The delete operation failed as expected.");
/// }
/// }
/// };
///
/// startup_(program);
/// @endcode
/// @remarks This constructor does not check if a directory exists. This constructor is a placeholder for a string that is used to access the disk in subsequent operations.
/// @remarks For a list of common I/O tasks, see <a href="https://github.com/gammasoft71/xtd/blob/master/docs/tutorial_common_io_tasks.md">Common I/O Tasks</a>.
explicit directory_info(const xtd::ustring& path);
/// @}
/// @name Properrties
/// @{
/// @brief Gets a value indicating whether the directory exists.
/// @return true if the directory exists; otherwise, false.
/// @par Examples
/// The following example demonstrates a use of the Exists property in the context of copying a source directory to a target directory.
/// @code
/// #include <xtd/xtd>
///
/// using namespace std;
/// using namespace xtd;
/// using namespace xtd::io;
///
/// class program {
/// public:
/// // Copy a source directory to a target directory.
/// static void copy_directory(const ustring& source_directory, const ustring& target_directory) {
/// directory_info source(source_directory);
/// directory_info target(target_directory);
///
/// //Determine whether the source directory exists.
/// if(!source.exists())
/// return;
/// if(!target.exists())
/// target.create();
///
/// //Copy files.
/// vector<file_info> source_files = source.get_files();
/// for(size_t i = 0; i < source_files.size(); ++i)
/// file::copy(source_files[i].full_name(), target.full_name() +"\\" + source_files[i].name(), true);
///
/// //Copy directories.
/// vector<directory_info> source_directories = source.get_directories();
/// for(size_t j = 0; j < source_directories.size(); ++j)
/// copy_directory(source_directories[j].full_name(), target.full_name() + "\\" + source_directories[j].name());
/// }
///
/// static void main() {
/// // Specify the directories you want to manipulate.
/// copy_directory("D:\\Tools","D:\\NewTools");
/// }
/// };
///
/// startup_(program);
/// @endcode
/// @remarks The xtd::io::directory_info::exists property returns false if any error occurs while trying to determine if the specified file exists. This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, a failing or missing disk, or if the caller does not have permission to read the file.
bool exists() const override;
/// @brief Gets the name of this xtd::io::directory_info instance.
/// @return The directory name.
/// @par Examples
/// The following example displays the name of the current xtd::io::directory_info instance only.
/// @code
/// #include <xtd/xtd>
///
/// using namespace xtd;
/// using namespace xtd::io;
///
/// class program {
/// public:
/// static void main() {
/// directory_info dir(".");
/// ustring dir_name = dir.name();
/// console::write_line("directory_info name is {0}.", dir_name);
/// }
/// };
///
/// startup_(program);
/// @endcode
/// @remarks This xtd::io::directory_info::name property returns only the name of the directory, such as "Bin". To get the full path, such as "c:\public\Bin", use the xtd::io::directory_info::full_name property.
/// @remarks The xtd::io::directory_info::name property of a xtd::io::directory_info requires no permission (beyond the read permission to the directory necessary to construct the Exists) but can give out the directory name. If it is necessary to hand out a xtd::io::directory_info to a protected directory with a cryptographically secure name, create a dummy directory for the untrusted code's use.
/// @remarks For a list of common I/O tasks, see <a href="https://github.com/gammasoft71/xtd/blob/master/docs/tutorial_common_io_tasks.md">Common I/O Tasks</a>.
xtd::ustring name() const override;
/// @brief Gets the parent directory of a specified subdirectory.
/// @return The parent directory, or null if the path is null or if the file path denotes a root (such as \, C:\, or \\server\share).
/// @exception xtd::security::security_exception The caller does not have the required permission.
/// @par Examples
/// The following example refers to the parent directory of a specified directory.
/// @code
/// #include <xtd/xtd>
///
/// using namespace xtd;
/// using namespace xtd::io;
///
/// class program {
/// public:
/// static void main() {
/// // Make a reference to a directory.
/// directory_info di("TempDir");
///
/// // Create the directory only if it does not already exist.
/// if (di.exists() == false)
/// di.create();
///
/// // Create a subdirectory in the directory just created.
/// directory_info dis = di.create_subdirectory("SubDir");
///
/// // Get a reference to the parent directory of the subdirectory you just made.
/// directory_info parent_dir = dis.parent();
/// console::write_line("The parent directory of '{0}' is '{1}'", dis.name(), parent_dir.name());
///
/// // Delete the parent directory.
/// di.remove(true);
/// }
/// };
/// ///
/// startup_(program);
/// @endcode
/// @remarks To ensure consistent behavior across versions and to make your intent explicit, retrieve the value of one of the following properties on the xtd::io::directory_info instance returned by xtd::io::directory_info::parent.
/// * xtd::io::directory_info::name, which returns the simple name of the directory (such as bin).
/// * xtd::io::directory_info::full_name, which returns the absolute path of the directory.
/// @remarks For a list of common I/O tasks, see <a href="https://github.com/gammasoft71/xtd/blob/master/docs/tutorial_common_io_tasks.md">Common I/O Tasks</a>.
xtd::io::directory_info parent() const;
/// @brief Gets the root portion of the directory.
/// @return An object that represents the root of the directory.
/// @exception xtd::security::security_exception The caller does not have the required permission.
/// @par Examples
/// The following example displays root locations for specified directories.
/// @code
/// #include <xtd/xtd>
///
/// using namespace xtd;
/// using namespace xtd::io;
///
/// class program {
/// public:
/// static void main() {
/// directory_info di1(R"(\\tempshare\tempdir)");
/// directory_info di2("tempdir");
/// directory_info di3(R"(x:\tempdir)");
/// directory_info di4(R"(c:\)");
///
/// console::write_line("The root path of '{0}' is '{1}'", di1.full_name(), di1.root());
/// console::write_line("The root path of '{0}' is '{1}'", di2.full_name(), di2.root());
/// console::write_line("The root path of '{0}' is '{1}'", di3.full_name(), di3.root());
/// console::write_line("The root path of '{0}' is '{1}'", di4.full_name(), di4.root());
/// }
/// };
///
/// startup_(program);
///
/// /*
/// This code produces output similar to the following:
///
/// The root path of '\\tempshare\tempdir' is '\\tempshare\tempdir'
/// The root path of 'c:\Projects\ConsoleApplication1\ConsoleApplication1\bin\Debug\tempdir' is 'c:\'
/// The root path of 'x:\tempdir' is 'x:\'
/// The root path of 'c:\' is 'c:\'
/// */
/// @endcode
xtd::io::directory_info root() const;
/// @}
/// @name Methods
/// @{
/// @brief Creates a directory.
/// @exception xtd::io::io_exception The directory cannot be created.
/// @par Examples
/// The following example checks whether a specified directory exists, creates the directory if it does not exist, and deletes the directory.
/// @code
/// #include <xtd/xtd>
///
/// using namespace xtd;
/// using namespace xtd::io;
///
/// class program {
/// public:
/// static void main() {
/// // Specify the directories you want to manipulate.
/// directory_info di("c:\\MyDir");
/// try {
/// // Determine whether the directory exists.
/// if (di.exists()) {
/// // Indicate that the directory already exists.
/// console::write_line("That path exists already.");
/// return;
/// }
///
/// // Try to create the directory.
/// di.create();
/// console::write_line("The directory was created successfully.");
///
/// // Delete the directory.
/// di.remove();
/// console::write_line("The directory was deleted successfully.");
/// }
/// catch (const system_exception& e) {
/// console::write_line("The process failed: {0}", e.to_string());
/// }
/// }
/// };
///
/// startup_(program);
/// @endcode
/// @remarks If the directory already exists, this method does nothing.
/// @remarks If the directory did not exist before calling this method, then any cached attribute information about the directory will be flushed if the creation is successful.
/// @remarks For a list of common I/O tasks, see <a href="https://github.com/gammasoft71/xtd/blob/master/docs/tutorial_common_io_tasks.md">Common I/O Tasks</a>.
void create();
/// @brief Creates a subdirectory or subdirectories on the specified path. The specified path can be relative to this instance of the xtd::io::directory_info class.
/// @param path The specified path. This cannot be a different disk volume or Universal Naming Convention (UNC) name.
/// @return The last directory specified in path.
/// @exception xtd::argument_exception path does not specify a valid file path or contains invalid xtd::io::directory_info characters.
/// @exception xtd::io::directory_not_found_exception The specified path is invalid, such as being on an unmapped drive.
/// @exception xtd::io::io_exception The subdirectory cannot be created.<br>-or-<br>A file or directory already has the name specified by path.
/// @exception xtd::io::path_too_long_exception The specified path, file name, or both exceed the system-defined maximum length.
/// @exception xtd::security::security_exception The caller does not have code access permission to create the directory.
/// @exception xtd::not_supported_exception path contains a colon character (:) that is not part of a drive label ("C:\").
/// @par Examples
/// The following example demonstrates creating a subdirectory. In this example, the created directories are removed once created. Therefore, to test this sample, comment out the delete lines in the code.
/// @code
/// #include <xtd/xtd>
///
/// using namespace xtd;
/// using namespace xtd::io;
///
/// class program {
/// public:
/// static void main() {
/// // Create a reference to a directory.
/// directory_info di("TempDir");
///
/// // Create the directory only if it does not already exist.
/// if (di.exists() == false)
/// di.create();
///
/// // Create a subdirectory in the directory just created.
/// directory_info dis = di.create_subdirectory("SubDir");
///
/// // Process that directory as required.
/// // ...
///
/// // Delete the subdirectory.
/// dis.remove(true);
///
/// // Delete the directory.
/// di.remove(true);
/// }
/// };
///
/// startup_(program);
/// @endcode
/// @remarks Any and all directories specified in path are created, unless some part of path is invalid. The path parameter specifies a directory path, not a file path. If the subdirectory already exists, this method does nothing.
/// @remarks For a list of common I/O tasks, see <a href="https://github.com/gammasoft71/xtd/blob/master/docs/tutorial_common_io_tasks.md">Common I/O Tasks</a>.
xtd::io::directory_info create_subdirectory(const xtd::ustring& path) const;
/// @brief Returns an enumerable collection of directory information in the current directory.
/// @return An xtd::io::directory_info::directory_iterator of directories in the current directory.
/// @exception xtd::io::directory_not_found_exception The specified path is invalid, such as being on an unmapped drive.
/// @exception xtd::security::security_exception The caller does not have code access permission to create the directory.
/// @par Examples
/// The following example enumerates the subdirectories under the "My Documents" directory.
/// @code
/// #include <xtd/xtd>
///
/// using namespace xtd;
/// using namespace xtd::io;
///
/// class program {
/// public:
/// static void main() {
/// // Set a variable to the Documents path.
/// ustring doc_path = environment::get_folder_path(environment::special_folder::my_documents);
///
/// directory_info dirs(doc_path);
///
/// for (auto di : dirs.enumerate_directories()) {
/// console::write_line("{}", di.name());
/// }
/// }
/// };
///
/// startup_(program);
/// @endcode
/// @remarks The xtd::io::directory_info::enumerate_directories and xtd::io::directory_info::get_directories methods differ as follows:
/// @remarks * When you use xtd::io::directory_info::enumerate_directories, you can start enumerating the collection of xtd::io::directory_info objects before the whole collection is returned.
/// @remarks * When you use xtd::io::directory_info::get_directories, you must wait for the whole array of xtd::io::directory_info objects to be returned before you can access the array.
/// @remarks Therefore, when you are working with many files and directories, xtd::io::directory_info::enumerate_directories can be more efficient.
/// @remarks This method pre-populates the values of the following xtd::io::directory_info properties:
/// * xtd::io::file_system_info::attributes
/// * xtd::io::file_system_info::creation_time
/// * xtd::io::file_system_info::last_access_time
/// * xtd::io::file_system_info::last_write_time
xtd::io::directory_info::directory_iterator enumerate_directories() const;
/// @brief Returns an enumerable collection of directory information that matches a specified search pattern.
/// @param search_pattern The search string to match against the names of directories. This parameter can contain a combination of valid literal path and wildcard (* and ?) characters, but it doesn't support regular expressions.
/// @return An xtd::io::directory_info::directory_iterator of directories that matches search_pattern.
/// @exception xtd::io::directory_not_found_exception The specified path is invalid, such as being on an unmapped drive.
/// @exception xtd::security::security_exception The caller does not have code access permission to create the directory.
/// @remarks searchPattern can be a combination of literal and wildcard characters, but it doesn't support regular expressions. The following wildcard specifiers are permitted in searchPattern.
/// | Wildcard specifier | Matches |
/// |--------------------|-------------------------------------------|
/// | * (asterisk) | Zero or more characters in that position. |
/// | ? (question mark) | Zero or one character in that position. |
/// @remarks Characters other than the wildcard are literal characters. For example, the string "*t" searches for all names in ending with the letter "t". ". The searchPattern string "s*" searches for all names in path beginning with the letter "s".
/// @remarks The xtd::io::directory_info::enumerate_directories and xtd::io::directory_info::get_directories methods differ as follows:
/// @remarks * When you use xtd::io::directory_info::enumerate_directories, you can start enumerating the collection of xtd::io::directory_info objects before the whole collection is returned.
/// @remarks * When you use xtd::io::directory_info::get_directories, you must wait for the whole array of xtd::io::directory_info objects to be returned before you can access the array.
/// @remarks Therefore, when you are working with many files and directories, xtd::io::directory_info::enumerate_directories can be more efficient.
/// @remarks This method pre-populates the values of the following xtd::io::directory_info properties:
/// * xtd::io::file_system_info::attributes
/// * xtd::io::file_system_info::creation_time
/// * xtd::io::file_system_info::last_access_time
/// * xtd::io::file_system_info::last_write_time
xtd::io::directory_info::directory_iterator enumerate_directories(const xtd::ustring& search_pattern) const;
/// @brief Returns an enumerable collection of file information in the current directory.
/// @return An xtd::io::directory_info::file_iterator of the files in the current directory.
/// @exception xtd::io::directory_not_found_exception The specified path is invalid, such as being on an unmapped drive.
/// @exception xtd::security::security_exception The caller does not have code access permission to create the directory.
/// @par Examples
/// The following example enumerates the files under a specified directory.
///
/// If you only need the names of the files, use the static xtd::io::directory class for better performance. For an example, see the xtd::io::directory::enumerate_files method.
/// @code
/// #include <xtd/xtd>
///
/// using namespace xtd;
/// using namespace xtd::io;
///
/// class program {
/// public:
/// static void main() {
/// // Create a directory_info of the directory of the files to enumerate.
/// directory_info dir_info(R"(\\archives1\library\)");
///
/// // Get the files iteror.
/// auto files = dir_info.enumerate_files();
///
/// // Show results.
/// for (auto f : files) {
/// console::write_line("{0}", f.name());
/// }
/// }
/// };
///
/// startup_(program);
/// @endcode
/// @par Examples
/// The following example shows how to enumerate files in a directory by using different search options. The example assumes a directory that has files named log1.txt, log2.txt, test1.txt, test2.txt, test3.txt.
/// @code
/// #include <xtd/xtd>
///
/// using namespace xtd;
/// using namespace xtd::io;
///
/// class program {
/// public:
/// static void main() {
/// directory_info di(R"(C:\ExampleDir)");
/// console::write_line("No search pattern returns:");
/// for (auto fi : di.enumerate_files()) {
/// console::write_line(fi.name());
/// }
///
/// console::write_line();
///
/// console::write_line("Search pattern *2* returns:");
/// for (auto fi : di.enumerate_files("*2*")) {
/// console::write_line(fi.name());
/// }
///
/// console::write_line();
///
/// console::write_line("Search pattern test?.txt returns:");
/// for (auto fi : di.enumerate_files("test?.txt")) {
/// console::write_line(fi.name());
/// }
/// }
/// };
///
/// startup_(program);
///
/// /*
/// This code produces output similar to the following:
///
/// No search pattern returns:
/// log1.txt
/// log2.txt
/// test1.txt
/// test2.txt
/// test3.txt
///
/// Search pattern *2* returns:
/// log2.txt
/// test2.txt
///
/// Search pattern test?.txt returns:
/// test1.txt
/// test2.txt
/// test3.txt
/// */
/// @endcode
/// @remarks The xtd::io::directory_info::enumerate_files and xtd::io::directory_info::get_files methods differ as follows:
/// * When you use xtd::io::directory_info::enumerate_files, you can start enumerating the collection of xtd::io::directory_info objects before the whole collection is returned.
/// * When you use xtd::io::directory_info::get_files, you must wait for the whole array of xtd::io::directory_info objects to be returned before you can access the array.
/// @remarks Therefore, when you are working with many files and directories, xtd::io::directory_info::enumerate_files can be more efficient.
/// @remarks This method pre-populates the values of the following xtd::io::directory_info properties:
/// * xtd::io::file_system_info::attributes
/// * xtd::io::file_system_info::creation_time
/// * xtd::io::file_system_info::last_access_time
/// * xtd::io::file_system_info::last_write_time
/// * xtd::io::file_system_info::size
xtd::io::directory_info::file_iterator enumerate_files() const;
/// @brief Returns an enumerable collection of file information that matches a search pattern.
/// @param search_pattern The search string to match against the names of files. This parameter can contain a combination of valid literal path and wildcard (* and ?) characters, but it doesn't support regular expressions.
/// @return An xtd::io::directory_info::file_iterator of files that matches search_pattern.
/// @exception xtd::io::directory_not_found_exception The specified path is invalid, such as being on an unmapped drive.
/// @exception xtd::security::security_exception The caller does not have code access permission to create the directory.
/// @par Examples
/// The following example shows how to enumerate files in a directory by using different search options. The example assumes a directory that has files named log1.txt, log2.txt, test1.txt, test2.txt, test3.txt.
/// @code
/// #include <xtd/xtd>
///
/// using namespace xtd;
/// using namespace xtd::io;
///
/// class program {
/// public:
/// static void main() {
/// directory_info di(R"(C:\ExampleDir)");
/// console::write_line("No search pattern returns:");
/// for (auto fi : di.enumerate_files()) {
/// console::write_line(fi.name());
/// }
///
/// console::write_line();
///
/// console::write_line("Search pattern *2* returns:");
/// for (auto fi : di.enumerate_files("*2*")) {
/// console::write_line(fi.name());
/// }
///
/// console::write_line();
///
/// console::write_line("Search pattern test?.txt returns:");
/// for (auto fi : di.enumerate_files("test?.txt")) {
/// console::write_line(fi.name());
/// }
/// }
/// };
///
/// startup_(program);
///
/// /*
/// This code produces output similar to the following:
///
/// No search pattern returns:
/// log1.txt
/// log2.txt
/// test1.txt
/// test2.txt
/// test3.txt
///
/// Search pattern *2* returns:
/// log2.txt
/// test2.txt
///
/// Search pattern test?.txt returns:
/// test1.txt
/// test2.txt
/// test3.txt
/// */
/// @endcode
/// @remarks search_pattern can be a combination of literal and wildcard characters, but it doesn't support regular expressions. The following wildcard specifiers are permitted in search_pattern.
/// | Wildcard specifier | Matches |
/// |--------------------|-------------------------------------------|
/// | * (asterisk) | Zero or more characters in that position. |
/// | ? (question mark) | Zero or one character in that position. |
/// @remarks Characters other than the wildcard are literal characters. For example, the string "*t" searches for all names in ending with the letter "t". ". The search_pattern string "s*" searches for all names in path beginning with the letter "s".
/// @remarks The xtd::io::directory_info::enumerate_files and xtd::io::directory_info::get_files methods differ as follows:
/// * When you use xtd::io::directory_info::enumerate_files, you can start enumerating the collection of xtd::io::directory_info objects before the whole collection is returned.
/// * When you use xtd::io::directory_info::get_files, you must wait for the whole array of xtd::io::directory_info objects to be returned before you can access the array.
/// @remarks Therefore, when you are working with many files and directories, xtd::io::directory_info::enumerate_files can be more efficient.
/// @remarks This method pre-populates the values of the following xtd::io::directory_info properties:
/// * xtd::io::file_system_info::attributes
/// * xtd::io::file_system_info::creation_time
/// * xtd::io::file_system_info::last_access_time
/// * xtd::io::file_system_info::last_write_time
/// * xtd::io::file_system_info::size
xtd::io::directory_info::file_iterator enumerate_files(const xtd::ustring& search_pattern) const;
/// @brief Returns an enumerable collection of file system information in the current directory.
/// @return An xtd::io::directory_info::file_system_info_iterator of file system information in the current directory.
/// @exception xtd::io::directory_not_found_exception The specified path is invalid, such as being on an unmapped drive.
/// @exception xtd::security::security_exception The caller does not have code access permission to create the directory.
/// @remarks The xtd::io::directory_info::enumerate_file_system_infos and xtd::io::directory_info::get_file_system_infos methods differ as follows:
/// * When you use xtd::io::directory_info::enumerate_file_system_infos, you can start enumerating the collection of xtd::io::directory_info objects before the whole collection is returned.
/// * When you use xtd::io::directory_info::get_file_system_infos, you must wait for the whole array of xtd::io::directory_info objects to be returned before you can access the array.
/// @remarks Therefore, when you are working with many files and directories, xtd::io::directory_info::enumerate_file_system_infos can be more efficient.
/// @remarks This method pre-populates the values of the following xtd::io::directory_info properties:
/// * xtd::io::file_system_info::attributes
/// * xtd::io::file_system_info::creation_time
/// * xtd::io::file_system_info::last_access_time
/// * xtd::io::file_system_info::last_write_time
/// * xtd::io::file_system_info::size
xtd::io::directory_info::file_system_info_iterator enumerate_file_system_infos() const;
/// @brief Returns an enumerable collection of file system information that matches a specified search pattern.
/// @param search_pattern The search string to match against the names of directories. This parameter can contain a combination of valid literal path and wildcard (* and ?) characters, but it doesn't support regular expressions.
/// @return An xtd::io::directory_info::file_system_info_iterator of file system information objects that matches search_pattern.
/// @exception xtd::io::directory_not_found_exception The specified path is invalid, such as being on an unmapped drive.
/// @exception xtd::security::security_exception The caller does not have code access permission to create the directory.
/// @remarks search_pattern can be a combination of literal and wildcard characters, but it doesn't support regular expressions. The following wildcard specifiers are permitted in search_pattern.
/// | Wildcard specifier | Matches |
/// |--------------------|-------------------------------------------|
/// | * (asterisk) | Zero or more characters in that position. |
/// | ? (question mark) | Zero or one character in that position. |
/// @remarks Characters other than the wildcard are literal characters. For example, the string "*t" searches for all names in ending with the letter "t". ". The search_pattern string "s*" searches for all names in path beginning with the letter "s".
/// @remarks The xtd::io::directory_info::enumerate_file_system_infos and xtd::io::directory_info::get_file_system_infos methods differ as follows:
/// * When you use xtd::io::directory_info::enumerate_file_system_infos, you can start enumerating the collection of xtd::io::directory_info objects before the whole collection is returned.
/// * When you use xtd::io::directory_info::get_file_system_infos, you must wait for the whole array of xtd::io::directory_info objects to be returned before you can access the array.
/// @remarks Therefore, when you are working with many files and directories, xtd::io::directory_info::enumerate_file_system_infos can be more efficient.
/// @remarks This method pre-populates the values of the following xtd::io::directory_info properties:
/// * xtd::io::file_system_info::attributes
/// * xtd::io::file_system_info::creation_time
/// * xtd::io::file_system_info::last_access_time
/// * xtd::io::file_system_info::last_write_time
/// * xtd::io::file_system_info::size
xtd::io::directory_info::file_system_info_iterator enumerate_file_system_infos(const xtd::ustring& search_pattern) const;
/// @brief Returns the subdirectories of the current directory.
/// @return An array of xtd::io::directory_info objects.
/// @exception xtd::io::directory_not_found_exception The specified path is invalid, such as being on an unmapped drive.
/// @exception xtd::security::security_exception The caller does not have code access permission to create the directory.
/// @par Examples
/// The following example retrieves all the directories in the root directory and displays the directory names.
/// @code
/// #include <xtd/xtd>
///
/// using namespace std;
/// using namespace xtd;
/// using namespace xtd::io;
///
/// class program {
/// public:
/// static void main() {
/// // Make a reference to a directory.
/// directory_info di("c:\\");
///
/// // Get a reference to each directory in that directory.
/// vector<directory_info> di_arr = di.get_directories();
///
/// // Display the names of the directories.
/// for (directory_info dri : di_arr)
/// console::write_line(dri.name());
/// }
/// };
///
/// startup_(program);
/// @endcode
/// @remarks If there are no subdirectories, this method returns an empty array. This method is not recursive.
/// @remarks This method pre-populates the values of the following xtd::io::directory_info properties:
/// * xtd::io::file_system_info::attributes
/// * xtd::io::file_system_info::creation_time
/// * xtd::io::file_system_info::last_access_time
/// * xtd::io::file_system_info::last_write_time
/// * xtd::io::file_system_info::size
std::vector<xtd::io::directory_info> get_directories() const;
/// @brief Returns an array of directories in the current DirectoryInfo matching the given search criteria.
/// @param search_pattern The search string to match against the names of directories. This parameter can contain a combination of valid literal path and wildcard (* and ?) characters, but it doesn't support regular expressions.
/// @return An array of type xtd::io::directory_info matching search_pattern.
/// @exception xtd::io::directory_not_found_exception The specified path is invalid, such as being on an unmapped drive.
/// @exception xtd::security::security_exception The caller does not have code access permission to create the directory.
/// @par Examples
/// TThe following example counts the directories in a path that contain the specified letter.
/// @code
/// #include <xtd/xtd>
///
/// using namespace std;
/// using namespace xtd;
/// using namespace xtd::io;
///
/// class program {
/// public:
/// static void main() {
/// try {
/// directory_info di(R"(c:\)");
///
/// // Get only subdirectories that contain the letter "p."
/// vector<directory_info> dirs = di.get_directories("*p*");
/// console::write_line("The number of directories containing the letter p is {0}.", dirs.size());
///
/// for (directory_info di_next : dirs) {
/// console::write_line("The number of files in {0} is {1}", di_next, di_next.get_files().size());
/// }
/// } catch (const system_exception& e) {
/// console::write_line("The process failed: {0}", e.to_string());
/// }
/// }
/// };
///
/// startup_(program);
///@endcode
/// @remarks search_pattern can be a combination of literal and wildcard characters, but it doesn't support regular expressions. The following wildcard specifiers are permitted in search_pattern.
/// | Wildcard specifier | Matches |
/// |--------------------|-------------------------------------------|
/// | * (asterisk) | Zero or more characters in that position. |
/// | ? (question mark) | Zero or one character in that position. |
/// @remarks Characters other than the wildcard are literal characters. For example, the string "*t" searches for all names in ending with the letter "t". ". The search_pattern string "s*" searches for all names in path beginning with the letter "s".
/// @remarks This method pre-populates the values of the following xtd::io::directory_info properties:
/// * xtd::io::file_system_info::attributes
/// * xtd::io::file_system_info::creation_time
/// * xtd::io::file_system_info::last_access_time
/// * xtd::io::file_system_info::last_write_time
/// * xtd::io::file_system_info::size
std::vector<xtd::io::directory_info> get_directories(const xtd::ustring& search_pattern) const;
/// @brief Returns a file list from the current directory.
/// @return An array of type xtd::io::file_info.
/// @exception xtd::io::directory_not_found_exception The specified path is invalid, such as being on an unmapped drive.
/// @exception xtd::security::security_exception The caller does not have code access permission to create the directory.
/// @par Examples
/// The following example shows how to get a list of files from a directory by using different search options. The example assumes a directory that has files named log1.txt, log2.txt, test1.txt, test2.txt, test3.tx
/// @code
/// #include <xtd/xtd>
///
/// using namespace xtd;
/// using namespace xtd::io;
///
/// class program {
/// public:
/// static void main() {
/// directory_info di(R"(C:\ExampleDir)");
/// console::write_line("No search pattern returns:");
/// for (auto fi : di.get_files()) {
/// console::write_line(fi.name());
/// }
///
/// console::write_line();
///
/// console::write_line("Search pattern *2* returns:");
/// for (auto fi : di.get_files("*2*")) {
/// console::write_line(fi.name());
/// }
///
/// console::write_line();
///
/// console::write_line("Search pattern test?.txt returns:");
/// for (auto fi : di.get_files("test?.txt")) {
/// console::write_line(fi.name());
/// }
/// }
/// };
///
/// startup_(program);
///
/// /*
/// This code produces output similar to the following:
///
/// No search pattern returns:
/// log1.txt
/// log2.txt
/// test1.txt
/// test2.txt
/// test3.txt
///
/// Search pattern *2* returns:
/// log2.txt
/// test2.txt
///
/// Search pattern test?.txt returns:
/// test1.txt
/// test2.txt
/// test3.txt
/// */
/// @endcode
/// @remarks The xtd::io::directory_info::enumerate_files and xtd::io::directory_info::get_files methods differ as follows:
/// * When you use xtd::io::directory_info::enumerate_files, you can start enumerating the collection of xtd::io::directory_info objects before the whole collection is returned.
/// * When you use xtd::io::directory_info::get_files, you must wait for the whole array of xtd::io::directory_info objects to be returned before you can access the array.
/// @remarks Therefore, when you are working with many files and directories, xtd::io::directory_info::enumerate_files can be more efficient.
/// @remarks This method pre-populates the values of the following xtd::io::directory_info properties:
/// * xtd::io::file_system_info::attributes
/// * xtd::io::file_system_info::creation_time
/// * xtd::io::file_system_info::last_access_time
/// * xtd::io::file_system_info::last_write_time
/// * xtd::io::file_system_info::size
std::vector<xtd::io::file_info> get_files() const;
/// @brief Returns a file list from the current directory matching the given search pattern.
/// @param search_pattern The search string to match against the names of files. This parameter can contain a combination of valid literal path and wildcard (* and ?) characters, but it doesn't support regular expressions.
/// @return An array of type xtd::io::file_info.
/// @exception xtd::io::directory_not_found_exception The specified path is invalid, such as being on an unmapped drive.
/// @exception xtd::security::security_exception The caller does not have code access permission to create the directory.
/// @par Examples
/// The following example shows how to get a list of files from a directory by using different search options. The example assumes a directory that has files named log1.txt, log2.txt, test1.txt, test2.txt, test3.tx
/// @code
/// #include <xtd/xtd>
///
/// using namespace xtd;
/// using namespace xtd::io;
///
/// class program {
/// public:
/// static void main() {
/// directory_info di(R"(C:\ExampleDir)");
/// console::write_line("No search pattern returns:");
/// for (auto fi : di.get_files()) {
/// console::write_line(fi.name());
/// }
///
/// console::write_line();
///
/// console::write_line("Search pattern *2* returns:");
/// for (auto fi : di.get_files("*2*")) {
/// console::write_line(fi.name());
/// }
///
/// console::write_line();
///
/// console::write_line("Search pattern test?.txt returns:");
/// for (auto fi : di.get_files("test?.txt")) {
/// console::write_line(fi.name());
/// }
/// }
/// };
///
/// startup_(program);
///
/// /*
/// This code produces output similar to the following:
///
/// No search pattern returns:
/// log1.txt
/// log2.txt
/// test1.txt
/// test2.txt
/// test3.txt
///
/// Search pattern *2* returns:
/// log2.txt
/// test2.txt
///
/// Search pattern test?.txt returns:
/// test1.txt
/// test2.txt
/// test3.txt
/// */
/// @endcode
/// @remarks search_pattern can be a combination of literal and wildcard characters, but it doesn't support regular expressions. The following wildcard specifiers are permitted in search_pattern.
/// | Wildcard specifier | Matches |
/// |--------------------|-------------------------------------------|
/// | * (asterisk) | Zero or more characters in that position. |
/// | ? (question mark) | Zero or one character in that position. |
/// @remarks Characters other than the wildcard are literal characters. For example, the string "*t" searches for all names in ending with the letter "t". ". The search_pattern string "s*" searches for all names in path beginning with the letter "s".
/// @remarks The xtd::io::directory_info::enumerate_files and xtd::io::directory_info::get_files methods differ as follows:
/// * When you use xtd::io::directory_info::enumerate_files, you can start enumerating the collection of xtd::io::directory_info objects before the whole collection is returned.
/// * When you use xtd::io::directory_info::get_files, you must wait for the whole array of xtd::io::directory_info objects to be returned before you can access the array.
/// @remarks Therefore, when you are working with many files and directories, xtd::io::directory_info::enumerate_files can be more efficient.
/// @remarks This method pre-populates the values of the following xtd::io::directory_info properties:
/// * xtd::io::file_system_info::attributes
/// * xtd::io::file_system_info::creation_time
/// * xtd::io::file_system_info::last_access_time
/// * xtd::io::file_system_info::last_write_time
/// * xtd::io::file_system_info::size
std::vector<xtd::io::file_info> get_files(const xtd::ustring& search_pattern) const;
/// @brief Returns an array of strongly typed xtd::io::file_system_info entries representing all the files and subdirectories in a directory.
/// @return An array of strongly typed xtd::io::file_system_info entries.
/// @exception xtd::io::directory_not_found_exception The specified path is invalid, such as being on an unmapped drive.
/// @exception xtd::security::security_exception The caller does not have code access permission to create the directory.
/// @par Examples
/// The following example counts the files and directories under the specified directory.
/// @code
/// #include <xtd/xtd>
///
/// using namespace xtd;
/// using namespace xtd::io;
///
/// class program {
/// public:
/// static void main() {
/// try {
/// console::write_line("Enter the path to a directory:");
///
/// ustring directory = console::read_line();
///
/// // Create a new directory_info object.
/// directory_info dir(directory);
///
/// if (!dir.exists()) {
/// throw directory_not_found_exception("The directory does not exist.", csf_);
/// }
///
/// // Call the GetFileSystemInfos method.
/// std::vector<std::shared_ptr<file_system_info>> infos = dir.get_file_system_infos();
///
/// console::write_line("Working...");
///
/// // Pass the result to the list_directories_and_files
/// // method defined below.
/// list_directories_and_files(infos);
///
/// // Display the results to the console.
/// console::write_line("Directories: {0}", directories);
/// console::write_line("Files: {0}", files);
/// } catch (const system_exception& e) {
/// console::write_line(e.message());
/// }
/// }
///
/// private:
/// static void list_directories_and_files(std::vector<std::shared_ptr<file_system_info>> fs_info) {
/// // Iterate through each item.
/// for (std::shared_ptr<file_system_info> i : fs_info) {
/// // Check to see if this is a directory_info object.
/// if (is<directory_info>(i)) {
/// // Add one to the directory count.
/// directories++;
///
/// // Cast the object to a directory_info object.
/// std::shared_ptr<directory_info> d_info = as<directory_info>(i);
///
/// // Iterate through all sub-directories.
/// list_directories_and_files(d_info->get_file_system_infos());
/// }
/// // Check to see if this is a FileInfo object.
/// else if (is<file_info>(i)) {
/// // Add one to the file count.
/// files++;
/// }
/// }
/// }
///
/// inline static long files = 0;
/// inline static long directories = 0;
/// };
///
/// startup_(program);
/// @endcode
/// @remarks The xtd::io::directory_info::enumerate_file_system_infos and xtd::io::directory_info::get_file_system_infos methods differ as follows:
/// * When you use xtd::io::directory_info::enumerate_file_system_infos, you can start enumerating the collection of xtd::io::file_system_info objects before the whole collection is returned.
/// * When you use xtd::io::directory_info::get_file_system_infos, you must wait for the whole array of xtd::io::file_system_info objects to be returned before you can access the array.
/// @remarks Therefore, when you are working with many files and directories, xtd::io::directory_info::enumerate_file_system_infos can be more efficient.
/// @remarks This method pre-populates the values of the following xtd::io::file_system_info properties:
/// * xtd::io::file_system_info::attributes
/// * xtd::io::file_system_info::creation_time
/// * xtd::io::file_system_info::last_access_time
/// * xtd::io::file_system_info::last_write_time
/// * xtd::io::file_system_info::size
std::vector<std::shared_ptr<xtd::io::file_system_info>> get_file_system_infos() const;
/// @brief Retrieves an array of strongly typed FileSystemInfo objects representing the files and subdirectories that match the specified search criteria.
/// @param search_pattern The search string to match against the names of directories and files. This parameter can contain a combination of valid literal path and wildcard (* and ?) characters, but it doesn't support regular expressions.
/// @return An array of strongly typed xtd::io::file_system_info entries.
/// @exception xtd::io::directory_not_found_exception The specified path is invalid, such as being on an unmapped drive.
/// @exception xtd::security::security_exception The caller does not have code access permission to create the directory.
/// @par Examples
/// The following example counts the files and directories that match the specified search pattern.
/// @code
/// #include <xtd/xtd>
///
/// using namespace xtd;
/// using namespace xtd::io;
///
/// class program {
/// public:
/// static void main() {
/// try {
/// console::write_line("Enter the path to a directory:");
///
/// ustring directory = console::read_line();
///
/// console::write_line("Enter a search string (for example *p*):");
///
/// ustring search_string = console::read_line();
///
/// // Create a new directory_info object.
/// directory_info dir(directory);
///
/// if (!dir.exists()) {
/// throw directory_not_found_exception("The directory does not exist.", csf_);
/// }
///
/// // Call the GetFileSystemInfos method.
/// std::vector<std::shared_ptr<file_system_info>> infos = dir.get_file_system_infos(search_string);
///
/// console::write_line("Working...");
///
/// // Pass the result to the list_directories_and_files
/// // method defined below.
/// list_directories_and_files(infos, search_string);
///
/// // Display the results to the console.
/// console::write_line("Directories: {0}", directories);
/// console::write_line("Files: {0}", files);
/// } catch (const system_exception& e) {
/// console::write_line(e.message());
/// }
/// }
///
/// private:
/// static void list_directories_and_files(std::vector<std::shared_ptr<file_system_info>> fs_info, const ustring& search_string) {
/// // Iterate through each item.
/// for (std::shared_ptr<file_system_info> i : fs_info) {
/// // Check to see if this is a directory_info object.
/// if (is<directory_info>(i)) {
/// // Add one to the directory count.
/// directories++;
///
/// // Cast the object to a directory_info object.
/// std::shared_ptr<directory_info> d_info = as<directory_info>(i);
///
/// // Iterate through all sub-directories.
/// list_directories_and_files(d_info->get_file_system_infos(search_string), search_string);
/// }
/// // Check to see if this is a FileInfo object.
/// else if (is<file_info>(i)) {
/// // Add one to the file count.
/// files++;
/// }
/// }
/// }
///
/// inline static long files = 0;
/// inline static long directories = 0;
/// };
///
/// startup_(program);
/// @endcode
/// @remarks search_pattern can be a combination of literal and wildcard characters, but it doesn't support regular expressions. The following wildcard specifiers are permitted in search_pattern.
/// | Wildcard specifier | Matches |
/// |--------------------|-------------------------------------------|
/// | * (asterisk) | Zero or more characters in that position. |
/// | ? (question mark) | Zero or one character in that position. |
/// @remarks Characters other than the wildcard are literal characters. For example, the string "*t" searches for all names in ending with the letter "t". ". The search_pattern string "s*" searches for all names in path beginning with the letter "s".
/// @remarks The xtd::io::directory_info::enumerate_file_system_infos and xtd::io::directory_info::get_file_system_infos methods differ as follows:
/// * When you use xtd::io::directory_info::enumerate_file_system_infos, you can start enumerating the collection of xtd::io::file_system_info objects before the whole collection is returned.
/// * When you use xtd::io::directory_info::get_file_system_infos, you must wait for the whole array of xtd::io::file_system_info objects to be returned before you can access the array.
/// @remarks Therefore, when you are working with many files and directories, xtd::io::directory_info::enumerate_file_system_infos can be more efficient.
/// @remarks This method pre-populates the values of the following xtd::io::file_system_info properties:
/// * xtd::io::file_system_info::attributes
/// * xtd::io::file_system_info::creation_time
/// * xtd::io::file_system_info::last_access_time
/// * xtd::io::file_system_info::last_write_time
/// * xtd::io::file_system_info::size
std::vector<std::shared_ptr<xtd::io::file_system_info>> get_file_system_infos(const xtd::ustring& search_pattern) const;
/// @brief Moves a DirectoryInfo instance and its contents to a new path.
/// @param dest_dir_name The name and path to which to move this directory. The destination cannot be another disk volume or a directory with the identical name. It can be an existing directory to which you want to add this directory as a subdirectory.
/// @exception xtd::io::directory_not_found_exception The specified path is invalid, such as being on an unmapped drive.
/// @exception xtd::io::io_exception The directory is not empty.<br>-or-<br>The directory is the application's current working directory.<br>-or-<br>There is an open handle on the directory.
/// @exception xtd::security::security_exception The caller does not have code access permission to create the directory.
/// @par Examples
/// The following example demonstrates moving a directory.
/// @code
/// #include <xtd/xtd>
///
/// using namespace xtd;
/// using namespace xtd::io;
///
/// class program {
/// public:
/// static void main() {
/// // Make a reference to a directory.
/// directory_info di("TempDir");
///
/// // Create the directory only if it does not already exist.
/// if (di.exists() == false)
/// di.create();
///
/// // Create a subdirectory in the directory just created.
/// directory_info dis = di.create_subdirectory("SubDir");
///
/// // Move the main directory. Note that the contents move with the directory.
/// if (directory::exists("NewTempDir") == false)
/// di.move_to("NewTempDir");
///
/// try {
/// // Attempt to delete the subdirectory. Note that because it has been
/// // moved, an exception is thrown.
/// dis.remove(true);
/// } catch (const system_exception&) {
/// // Handle this exception in some way, such as with the following code:
/// // console::write_line("That directory does not exist.");
/// }
///
/// // Point the directory_info reference to the new directory.
/// //di = directory_info("NewTempDir");
///
/// // Delete the directory.
/// //di.remove(true);
/// }
/// };
///
/// startup_(program);
/// @endcode
/// @remarks This method throws an IOException if, for example, you try to move c:\mydir to c:\public, and c:\public already exists. You must specify "c:\\public\\mydir" as the destDirName parameter, or specify a new directory name such as "c:\\newdir".
/// @remarks This method permits moving a directory to a read-only directory. The read/write attribute of neither directory is affected.
/// @remarks For a list of common I/O tasks, see <a href="https://github.com/gammasoft71/xtd/blob/master/docs/tutorial_common_io_tasks.md">Common I/O Tasks</a>.
void move_to(const xtd::ustring& dest_dir_name);
/// @brief Deletes this xtd::io::directory_info if it is empty.
/// @exception xtd::unauthorized_access_exception The directory contains a read-only file.
/// @exception xtd::io::directory_not_found_exception The directory described by this xtd::io::directory_info object does not exist or could not be found.
/// @exception xtd::io::io_exception The directory is not empty.<br>-or-<br>The directory is the application's current working directory.<br>-or-<br>There is an open handle on the directory.
/// @exception xtd::security::security_exception The caller does not have the required permission.
/// @par Examples
/// The following example throws an exception if you attempt to delete a directory that is not empty.
/// @code
/// #include <xtd/xtd>
///
/// using namespace xtd;
/// using namespace xtd::io;
///
/// class program {
/// public:
/// static void main() {
/// // Specify the directories you want to manipulate.
/// directory_info di1(R"(c:\MyDir)");
///
/// try {
/// // Create the directories.
/// di1.create();
/// di1.create_subdirectory("temp");
///
/// //This operation will not be allowed because there are subdirectories.
/// console::write_line("I am about to attempt to delete {0}", di1.name());
/// di1.remove();
/// console::write_line("The Delete operation was successful, which was unexpected.");
/// } catch (const system_exception&) {
/// console::write_line("The Delete operation failed as expected.");
/// }
/// }
/// };
///
/// startup_(program);
/// @endcode
/// @remarks For a list of common I/O tasks, see <a href="https://github.com/gammasoft71/xtd/blob/master/docs/tutorial_common_io_tasks.md">Common I/O Tasks</a>.
void remove() const override;
/// @brief Deletes this instance of a DirectoryInfo, specifying whether to delete subdirectories and files.
/// @param recursive true to delete this directory, its subdirectories, and all files; otherwise, false.
/// @exception xtd::unauthorized_access_exception The directory contains a read-only file.
/// @exception xtd::io::directory_not_found_exception The directory described by this xtd::io::directory_info object does not exist or could not be found.
/// @exception xtd::io::io_exception The directory is not empty.<br>-or-<br>The directory is the application's current working directory.<br>-or-<br>There is an open handle on the directory.
/// @exception xtd::security::security_exception The caller does not have the required permission.
/// @par Examples
/// The following example demonstrates deleting a directory. Because the directory is removed, first comment out the Delete line to test that the directory exists. Then uncomment the same line of code to test that the directory was removed successfully.
/// @code
/// #include <xtd/xtd>
///
/// using namespace xtd;
/// using namespace xtd::io;
///
/// class program {
/// public:
/// static void main() {
/// // Make a reference to a directory.
/// directory_info di("TempDir");
///
/// // Create the directory only if it does not already exist.
/// if (di.exists() == false)
/// di.create();
///
/// // Create a subdirectory in the directory just created.
/// directory_info dis = di.create_subdirectory("SubDir");
///
/// // Process that directory as required.
/// // ...
///
/// // Delete the subdirectory. The true indicates that if subdirectories
/// // or files are in this directory, they are to be deleted as well.
/// dis.remove(true);
///
/// // Delete the directory.
/// di.remove(true);
/// }
/// };
///
/// startup_(program);
/// @endcode
/// @remarks If the xtd::io::directory_info has no files or subdirectories, this method deletes the xtd::io::directory_info even if recursive is false. Attempting to delete a xtd::io::directory_info that is not empty when recursive is false throws an xtd::io::io_exception.
/// @remarks For a list of common I/O tasks, see <a href="https://github.com/gammasoft71/xtd/blob/master/docs/tutorial_common_io_tasks.md">Common I/O Tasks</a>.
void remove(bool recursive) const;
/// @}
private:
directory_info() = default;
};
}
}
/// @cond
namespace std {
inline xtd::io::directory_info::directory_iterator begin(xtd::io::directory_info::directory_iterator it) {return it;}
inline xtd::io::directory_info::directory_iterator end(xtd::io::directory_info::directory_iterator it) {return xtd::io::directory_info::directory_iterator();}
inline xtd::io::directory_info::file_iterator begin(xtd::io::directory_info::file_iterator it) {return it;}
inline xtd::io::directory_info::file_iterator end(xtd::io::directory_info::file_iterator it) {return xtd::io::directory_info::file_iterator();}
inline xtd::io::directory_info::file_system_info_iterator begin(xtd::io::directory_info::file_system_info_iterator it) {return it;}
inline xtd::io::directory_info::file_system_info_iterator end(xtd::io::directory_info::file_system_info_iterator it) {return xtd::io::directory_info::file_system_info_iterator();}
}
/// @endcond
| 53.83383 | 533 | 0.615918 | [
"object",
"vector"
] |
fee92c1b5ff1b4e440b26743b9990f9308037cfe | 5,585 | h | C | algorithms/visappfeats.h | JohnStranzl/GRIME2 | 087a67055890b884ed701cc3d57c78978ad20ff2 | [
"Apache-2.0"
] | 3 | 2021-02-16T05:46:20.000Z | 2021-03-08T08:38:21.000Z | algorithms/visappfeats.h | JohnStranzl/GRIME2 | 087a67055890b884ed701cc3d57c78978ad20ff2 | [
"Apache-2.0"
] | 6 | 2021-04-10T14:55:24.000Z | 2021-08-28T17:54:24.000Z | algorithms/visappfeats.h | JohnStranzl/GRIME2 | 087a67055890b884ed701cc3d57c78978ad20ff2 | [
"Apache-2.0"
] | 1 | 2021-04-15T02:20:19.000Z | 2021-04-15T02:20:19.000Z | /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Copyright 2021 Kenneth W. Chapman
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 VISAPPFEATS_H
#define VISAPPFEATS_H
#include "labelroi.h"
#include "featuredata.h"
#include "findanchor.h"
namespace gc
{
class FeatCalcItem
{
public:
FeatCalcItem() :
datetimeOriginal( std::string( "1955-09-24T12:05:00" ) ),
datetimeProcessing( std::string( "1955-09-24T12:05:01" ) )
{}
FeatCalcItem( const std::string timeStampOriginal,
const std::string timeStampProcessing,
const std::string imageFilepath,
const std::string resultImageFilepath = "",
const std::string resultCSVFilepath = "" ) :
datetimeOriginal( timeStampOriginal ),
datetimeProcessing( timeStampProcessing ),
imagePath( imageFilepath ),
resultImagePath( resultImageFilepath ),
resultCSVPath( resultCSVFilepath )
{
}
void clear()
{
datetimeOriginal = std::string( "1955-09-24T12:05:00" );
datetimeProcessing = std::string( "1955-09-24T12:05:01" );
imagePath.clear();
resultImagePath.clear();
resultCSVPath.clear();
}
std::string datetimeOriginal; ///< Datetime stamp when the image to be search was created
std::string datetimeProcessing; ///< Datetime stamp when the findline was performed
std::string imagePath; ///< Input image filepath of the image to be searched
std::string resultImagePath; ///< Optional result image created from input image with found line and move detection overlays
std::string resultCSVPath; ///< Optional result csv file path to hold timestamps and stage measurements
};
class FeatCalcParams
{
public:
FeatCalcParams() :
timeStampType( FROM_EXIF ),
timeStampStartPos( -1 ),
timeStampLength( -1 )
{}
// TODO -- Correct this documentation
/**
* @brief Constructor to set the object to a valid state
* @param timeStampOriginal Datetime stamp when the image to be search was created
* @param timeStampProcessing Datetime stamp when the findline was performed
* @param imageFilepath Input image filepath of the image to be searched
* @param resultImageFilepath Optional result image created from input image with found line and move detection overlays
* @param resultCSVFilepath Optional result CSV file to build a table of features for a set of images
*/
FeatCalcParams( const GC_TIMESTAMP_TYPE tmStampType,
const int tmStampStartPos,
const int tmStampLength,
const std::string tmStampFormat,
const std::vector< LabelROIItem > rois ) :
timeStampType( tmStampType ),
timeStampStartPos( tmStampStartPos ),
timeStampLength( tmStampLength ),
timeStampFormat( tmStampFormat )
{
areaROIs.clear();
for ( size_t i = 0; i < rois.size(); ++i )
areaROIs.push_back( rois[ i ] );
}
void clear()
{
timeStampType = FROM_EXIF;
timeStampStartPos = -1;
timeStampLength = -1;
timeStampFormat.clear();
areaROIs.clear();
}
// timestamp in ISO 8601 DateTime format
// e.g. 1955-09-24T12:05:00Z00:00
GC_TIMESTAMP_TYPE timeStampType; ///< Specifies where to get timestamp (filename, exif, or dateTimeOriginal)
int timeStampStartPos; ///< start position of timestamp string in filename (not whole path)
int timeStampLength; ///< length of timestamp string in filename
std::string timeStampFormat; ///< Format of the timestamp string, e.g. YYYY-MM-DDThh:mm::ss
vector< LabelROIItem > areaROIs; ///< Vector of regions of interest for area feature calculation
};
class VisAppFeats
{
public:
VisAppFeats();
GC_STATUS ReadSettings( const std::string jsonFilepath );
GC_STATUS WriteSettings( const std::string jsonFilepath );
GC_STATUS CalcMovement( const cv::Mat img, Point &ptOrig, cv::Point &ptMove, double &angle );
cv::Rect GetAnchorROI() { return anchor.ModelRect(); }
GC_STATUS SetAnchorRef( const string imgRefFilepath, const cv::Rect rect );
GC_STATUS SetFeatROIs( const std::vector< LabelROIItem > &items );
void SetCalcParams( const FeatCalcParams ¶ms ) { featCalcParams = params; }
GC_STATUS CreateCSVFileAndHeader( const std::string filepath, const FeatureSet &featSet );
GC_STATUS WriteFeatSetToCSV( const std::string filepath, const FeatureSet &featSet );
GC_STATUS ReadCSV( const std::string filepath, std::vector< FeatureSet > &featSets );
private:
FindAnchor anchor;
FeatCalcParams featCalcParams;
GC_STATUS ParseRow( const std::vector< std::string > data, FeatureSet &feat );
};
} // namespace gc
#endif // VISAPPFEATS_H
| 39.609929 | 135 | 0.64906 | [
"object",
"vector"
] |
fef716dac4300586de9ebcb0cdeb95fcfb0602e9 | 375 | h | C | Friendly/Controllers/MenuWorkflow/EventsWorkflow/EventPreview Module/Cell/TextCell/FREventPreviewTextCell.h | vikingdr/Friendly | ea690b061fc1dae59345f24d361dc032713e16de | [
"MIT"
] | null | null | null | Friendly/Controllers/MenuWorkflow/EventsWorkflow/EventPreview Module/Cell/TextCell/FREventPreviewTextCell.h | vikingdr/Friendly | ea690b061fc1dae59345f24d361dc032713e16de | [
"MIT"
] | null | null | null | Friendly/Controllers/MenuWorkflow/EventsWorkflow/EventPreview Module/Cell/TextCell/FREventPreviewTextCell.h | vikingdr/Friendly | ea690b061fc1dae59345f24d361dc032713e16de | [
"MIT"
] | null | null | null | //
// FRTextTableViewCell.h
// Friendly
//
// Created by Zaslavskaya Yevheniya on 10.03.16.
// Copyright © 2016 Accucode Inc. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "FREventModel.h"
#import "FREventPreviewTextCellViewModel.h"
@interface FREventPreviewTextCell : UITableViewCell
- (void) updateWithModel:(FREventPreviewTextCellViewModel*)model;
@end
| 19.736842 | 65 | 0.757333 | [
"model"
] |
fefc8579ddf44abbc8fae3d118aa0ad265f94c81 | 2,495 | h | C | src/avt/Pipeline/AbstractFilters/avtStructuredChunkDataTreeIterator.h | visit-dav/vis | c08bc6e538ecd7d30ddc6399ec3022b9e062127e | [
"BSD-3-Clause"
] | 226 | 2018-12-29T01:13:49.000Z | 2022-03-30T19:16:31.000Z | src/avt/Pipeline/AbstractFilters/avtStructuredChunkDataTreeIterator.h | visit-dav/vis | c08bc6e538ecd7d30ddc6399ec3022b9e062127e | [
"BSD-3-Clause"
] | 5,100 | 2019-01-14T18:19:25.000Z | 2022-03-31T23:08:36.000Z | src/avt/Pipeline/AbstractFilters/avtStructuredChunkDataTreeIterator.h | visit-dav/vis | c08bc6e538ecd7d30ddc6399ec3022b9e062127e | [
"BSD-3-Clause"
] | 84 | 2019-01-24T17:41:50.000Z | 2022-03-10T10:01:46.000Z | // Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
// Project developers. See the top-level LICENSE file for dates and other
// details. No copyright assignment is required to contribute to VisIt.
// ************************************************************************* //
// avtStructuredChunkDataTreeIterator.h //
// ************************************************************************* //
#ifndef AVT_STRUCTURED_CHUNK_DATA_TREE_ITERATOR_H
#define AVT_STRUCTURED_CHUNK_DATA_TREE_ITERATOR_H
#include <pipeline_exports.h>
#include <avtSIMODataTreeIterator.h>
#include <avtGhostData.h>
#include <avtStructuredMeshChunker.h>
// ****************************************************************************
// Class: avtStructuredChunkDataTreeIterator
//
// Purpose:
// This is an abstract type that prepares a filter to interact with
// the structured mesh chunker module. It is possible to use the
// structured mesh chunker without the help of this class -- it's sole
// purpose is to do bookkeeping to ease the burden for derived types,
// as well as remove redundant code.
//
// Programmer: Hank Childs
// Creation: March 27, 2005
//
// Modifications:
// Eric Brugger, Wed Aug 20 16:31:44 PDT 2014
// Modified the class to work with avtDataRepresentation.
//
// ****************************************************************************
class PIPELINE_API avtStructuredChunkDataTreeIterator : public avtSIMODataTreeIterator
{
public:
avtStructuredChunkDataTreeIterator();
virtual ~avtStructuredChunkDataTreeIterator();
protected:
bool downstreamRectilinearMeshOptimizations;
bool downstreamCurvilinearMeshOptimizations;
avtGhostDataType downstreamGhostType;
bool chunkedStructuredMeshes;
virtual avtDataTree_p ExecuteDataTree(avtDataRepresentation *);
virtual avtDataRepresentation *ProcessOneChunk(avtDataRepresentation *,
bool) = 0;
virtual void GetAssignments(vtkDataSet *, const int *,
std::vector<avtStructuredMeshChunker::ZoneDesignation>&)=0;
virtual avtContract_p ModifyContract(avtContract_p);
virtual void PreExecute(void);
virtual void PostExecute(void);
};
#endif
| 38.384615 | 86 | 0.58517 | [
"mesh",
"vector"
] |
fefd16b5a9d3116939f171ce077f1d20c67debef | 2,161 | h | C | ni/src/lib/hlu/CoordArrTableP.h | tenomoto/ncl | a87114a689a1566e9aa03d85bcf6dc7325b47633 | [
"Apache-2.0"
] | 210 | 2016-11-24T09:05:08.000Z | 2022-03-24T19:15:32.000Z | ni/src/lib/hlu/CoordArrTableP.h | tenomoto/ncl | a87114a689a1566e9aa03d85bcf6dc7325b47633 | [
"Apache-2.0"
] | 156 | 2017-09-22T09:56:48.000Z | 2022-03-30T07:02:21.000Z | ni/src/lib/hlu/CoordArrTableP.h | tenomoto/ncl | a87114a689a1566e9aa03d85bcf6dc7325b47633 | [
"Apache-2.0"
] | 58 | 2016-12-14T00:15:22.000Z | 2022-03-15T09:13:00.000Z | /*
* $Id: CoordArrTableP.h,v 1.4 1995-04-07 10:41:18 boote Exp $
*/
/************************************************************************
* *
* Copyright (C) 1993 *
* University Corporation for Atmospheric Research *
* All Rights Reserved *
* *
************************************************************************/
/*
* File: CoordArrTableP.h
*
* Author: Jeff W. Boote
* National Center for Atmospheric Research
* PO 3000, Boulder, Colorado
*
* Date: Wed Jul 28 11:34:08 MDT 1993
*
* Description: Private declarations for CoordArrTable object.
*/
#ifndef _NCoordArrTableP_h
#define _NCoordArrTableP_h
#include <ncarg/hlu/DataItemP.h>
#include <ncarg/hlu/CoordArrTable.h>
#include <ncarg/hlu/CoordArrTableFloatP.h>
typedef struct _NhlCoordArrTableLayerPart{
NhlString xtype;
NhlString ytype;
int xsize;
int ysize;
NhlGenArray xtable;
NhlGenArray ytable;
NhlGenArray xtable_lens;
NhlGenArray ytable_lens;
NhlBoolean copy_tables;
NhlGenArray missing_x;
NhlGenArray missing_y;
NhlGenArray max_x;
NhlGenArray max_y;
NhlGenArray min_x;
NhlGenArray min_y;
/*
* Private Fields
*/
NrmQuark xtypeQ;
NrmQuark ytypeQ;
NhlGenArray own_x;
NhlGenArray own_y;
_NhlConvertContext conv_x;
_NhlConvertContext conv_y;
NhlGenArray own_miss_x;
NhlGenArray own_miss_y;
NhlBoolean sticky_max_x;
NhlBoolean sticky_min_x;
NhlBoolean sticky_max_y;
NhlBoolean sticky_min_y;
} NhlCoordArrTableLayerPart;
typedef struct _NhlCoordArrTableLayerRec{
NhlBaseLayerPart base;
NhlDataItemLayerPart dataitem;
NhlCoordArrTableLayerPart cat;
} NhlCoordArrTableLayerRec;
typedef struct _NhlCoordArrTableClassPart{
int foo;
} NhlCoordArrTableClassPart;
typedef struct _NhlCoordArrTableClassRec{
NhlBaseClassPart base_class;
NhlDataItemClassPart dataitem_class;
NhlCoordArrTableClassPart cat_class;
} NhlCoordArrTableClassRec;
typedef struct _NhlCoordArrTableClassRec *NhlCoordArrTableClass;
typedef struct _NhlCoordArrTableLayerRec *NhlCoordArrTableLayer;
extern NhlCoordArrTableClassRec NhlcoordArrTableClassRec;
#endif /* _NCoordArrTableP_h */
| 24.011111 | 73 | 0.714021 | [
"object"
] |
3a00a4b2b4c06aedc548c61d55f3ef274d52c310 | 58,873 | c | C | src/sound/votrax.c | automation-club/pinmame | c44c0503a6516f79259bf5d1dbbfcdeadada1d1a | [
"BSD-3-Clause"
] | 46 | 2016-09-10T15:43:48.000Z | 2022-03-30T13:50:11.000Z | src/sound/votrax.c | Kissarmynh/pinmame | c552e469d60400602f62f7cdc3c4e93d81c3b720 | [
"BSD-3-Clause"
] | 13 | 2021-01-20T18:36:26.000Z | 2021-12-31T06:49:42.000Z | src/sound/votrax.c | Kissarmynh/pinmame | c552e469d60400602f62f7cdc3c4e93d81c3b720 | [
"BSD-3-Clause"
] | 25 | 2017-11-13T07:20:39.000Z | 2022-03-30T09:17:23.000Z | // license:BSD-3-Clause
/**************************************************************************
Votrax SC-01 Emulator/Simulation
Mike@Dissfulfils.co.uk (old simulation core)
Tom.Haukap@t-online.de (dto.)
Olivier Galibert (new simulation core)
**************************************************************************
VOTRAXSC01_sh_start - Start emulation, load samples from Votrax subdirectory
VOTRAXSC01_sh_stop - End emulation, free memory used for samples
votraxsc01_w - Write data to votrax port
votraxsc01_status_r - Return busy status (1 = busy)
If you need to alter the base frequency (i.e. Qbert) then just alter
the variable VotraxBaseFrequency, this is defaulted to 8000
**************************************************************************/
// #define OLD_VOTRAX
// Define to use old sample based emulation, also adapt gts80s.c and taitos.c then accordingly (search for the OLD_VOTRAX)
//!! marks all spots where the new emulation might be still shaky due to the manual port from MAME
// #define REAL_DEVICE
// Uncomment the above line if you like to use a real SC-01 chip connected to
// the printer port 1. Connect the data lines P0-P5 to D1-D6, I0-I1 to D7-D6,
// ACK to ACK and STROBE to STROBE.
/*
tp3 stb i1 i2 tp2
1 1 o o white noise
1 0 - 1 phone timing clock
1 0 1 0 closure tick
1 0 0 0 sram write pulse
0 - - - sram write pulse
i1.o = glottal impulse
i2.o = white noise
tp1 = phi clock (tied to f2q rom access)
*/
#include "driver.h"
#include "votrax.h"
#ifdef REAL_DEVICE
#include "dlportio.h"
#endif
#include "math.h"
#include <stdbool.h>
typedef unsigned char byte;
#define VERBOSE 0
#if VERBOSE
#define LOG(x) logerror x
#else
#define LOG(x)
#endif
static struct {
#ifdef OLD_VOTRAX
int baseFrequency;
int busy;
int channels[4];
int actPhoneme;
int actIntonation;
#endif
struct VOTRAXSC01interface *intf;
#ifdef OLD_VOTRAX
INT16* pActPos;
int iRemainingSamples;
#endif
mame_timer* timer;
#ifdef OLD_VOTRAX
INT16 *lpBuffer;
INT16* pBufferPos;
int iSamplesInBuffer;
int iDelay;
#endif
#ifdef REAL_DEVICE
unsigned char strobe;
#endif
#ifndef OLD_VOTRAX
UINT32 mainclock; // Current main clock
double sclock; // Stream sample clock (40KHz, main/18)
double cclock; // 20KHz capacitor switching clock (main/36)
UINT32 sample_count; // Sample counter, to cadence chip updates
// Inputs
UINT8 inflection; // 2-bit inflection value
UINT8 phone; // 6-bit phone value
// Outputs
//!! devcb_write_line m_ar_cb; // Callback for ar
bool ar_state; // Current ar state
// "Unpacked" current rom values
UINT8 rom_duration; // Duration in 5KHz units (main/144) of one tick, 16 ticks per phone, 7 bits
UINT8 rom_vd, rom_cld; // Duration in ticks of the "voice" and "closure" delays, 4 bits
UINT8 rom_fa, rom_fc, rom_va; // Analog parameters, noise volume, noise freq cutoff and voice volume, 4 bits each
UINT8 rom_f1, rom_f2, rom_f2q, rom_f3; // Analog parameters, formant frequencies and Q, 4 bits each
bool rom_closure; // Closure bit, true = silence at cld
bool rom_pause; // Pause bit
// Current interpolated values (8 bits each)
UINT8 cur_fa, cur_fc, cur_va;
UINT8 cur_f1, cur_f2, cur_f2q, cur_f3;
// Current committed values
UINT8 filt_fa, filt_fc, filt_va; // Analog parameters, noise volume, noise freq cutoff and voice volume, 4 bits each
UINT8 filt_f1, filt_f2, filt_f2q, filt_f3; // Analog parameters, formant frequencies/Q on 4 bits except f2 on 5 bits
// Internal counters
UINT16 phonetick; // 9-bits phone tick duration counter
UINT8 ticks; // 5-bits tick counter
UINT8 pitch; // 7-bits pitch counter
UINT8 closure; // 5-bits glottal closure counter
UINT8 update_counter; // 6-bits counter for the 625Hz (main/1152) and 208Hz (main/3456) update timing generators
// Internal state
bool cur_closure; // Current internal closure state
UINT16 noise; // 15-bit noise shift register
bool cur_noise; // Current noise output
// Filter coefficients and level histories
double voice_1[4];
double voice_2[4];
double voice_3[4];
double noise_1[3];
double noise_2[3];
double noise_3[2];
double noise_4[2];
double vn_1[4];
double vn_2[4];
double vn_3[4];
double vn_4[4];
double vn_5[2];
double vn_6[2];
double f1_a[4], f1_b[4]; // F1 filtering
double f2v_a[4], f2v_b[4]; // F2 voice filtering
double f2n_a[2], f2n_b[2]; // F2 noise filtering
double f3_a[4], f3_b[4]; // F3 filtering
double f4_a[4], f4_b[4]; // F4 filtering
double fx_a[1], fx_b[2]; // Final filtering
double fn_a[3], fn_b[3]; // Noise shaping
int stream;
#endif
} votraxsc01_locals;
#ifdef OLD_VOTRAX
#include "vtxsmpls.inc"
const int _dataOutAdr = 0x378;
const int _statusInAdr = 0x379;
const int _ctrlOutAdr = 0x37a;
const byte _bitmaskAck = 0x40;
const byte _pitchMask = 0x40;
#endif
#if VERBOSE
static const char *PhonemeNames[65] =
{
"EH3", "EH2", "EH1", "PA0", "DT", "A1", "A2", "ZH",
"AH2", "I3", "I2", "I1", "M", "N", "B", "V",
"CH", "SH", "Z", "AW1", "NG", "AH1", "OO1", "OO",
"L", "K", "J", "H", "G", "F", "D", "S",
"A", "AY", "Y1", "UH3", "AH", "P", "O", "I",
"U", "Y", "T", "R", "E", "W", "AE", "AE1",
"AW2", "UH2", "UH1", "UH", "O2", "O1", "IU", "U1",
"THV", "TH", "ER", "EH", "E1", "AW", "PA1", "STOP",
0
};
#endif
/*static const int PhonemeLengths[65] =
{
59, 71, 121, 47, 47, 71, 103, 90,
71, 55, 80, 121, 103, 80, 71, 71,
71, 121, 71, 146, 121, 146, 103, 185,
103, 80, 47, 71, 71, 103, 55, 90,
185, 65, 80, 47, 250, 103, 185, 185,
185, 103, 71, 90, 185, 80, 185, 103,
90, 71, 103, 185, 80, 121, 59, 90,
80, 71, 146, 185, 121, 250, 185, 47,
0
};*/
#ifndef OLD_VOTRAX
// This waveform is built using a series of transistors as a resistor
// ladder. There is first a transistor to ground, then a series of
// seven transistors one quarter the size of the first one, then it
// finishes by an active resistor to +9V.
//
// The terminal of the transistor to ground is used as a middle value.
// Index 0 is at that value. Index 1 is at 0V. Index 2 to 8 start at
// just after the resistor down the latter. Indices 9+ are the middle
// value again.
//
// For simplicity, we rescale the values to get the middle at 0 and
// the top at 1. The final wave is very similar to the patent
// drawing.
// Possible timer parameters
enum {
T_COMMIT_PHONE,
T_END_OF_PHONE
};
static const double s_glottal_wave[9] =
{
0,
-4/7.0,
7/7.0,
6/7.0,
5/7.0,
4/7.0,
3/7.0,
2/7.0,
1/7.0
};
// ROM definition for the Votrax phone ROM
static const UINT8 sc01a_bin[512] = {
0xA4, 0x50, 0xA0, 0xF0, 0xE0, 0x00, 0x00, 0x03, 0xA4, 0x50, 0xA0, 0x00,
0x23, 0x0A, 0x00, 0x3E, 0xA4, 0x58, 0xA0, 0x30, 0xF0, 0x00, 0x00, 0x3F,
0xA3, 0x80, 0x69, 0xB0, 0xC1, 0x0C, 0x00, 0x3D, 0x26, 0xD3, 0x49, 0x90,
0xA1, 0x09, 0x00, 0x3C, 0x27, 0x81, 0x68, 0x94, 0x21, 0x0A, 0x00, 0x3B,
0x82, 0xC3, 0x48, 0x24, 0xA1, 0x08, 0x00, 0x3A, 0xA4, 0x00, 0x38, 0x18,
0x68, 0x01, 0x00, 0x39, 0x20, 0x52, 0xE1, 0x88, 0x63, 0x0A, 0x00, 0x38,
0x22, 0xC1, 0xE8, 0x90, 0x61, 0x04, 0x00, 0x37, 0xA2, 0x83, 0x60, 0x10,
0x66, 0x03, 0x00, 0x36, 0xA2, 0xC1, 0xE8, 0x80, 0xA1, 0x09, 0x00, 0x35,
0xA2, 0xC1, 0xE8, 0x34, 0x61, 0x0A, 0x00, 0x34, 0xA3, 0x81, 0x89, 0xB4,
0x21, 0x0A, 0x00, 0x33, 0xA3, 0x81, 0x89, 0xE4, 0xA1, 0x07, 0x00, 0x32,
0xA3, 0x81, 0x89, 0x54, 0x63, 0x01, 0x00, 0x31, 0xA3, 0x80, 0x69, 0x60,
0x61, 0x04, 0x00, 0x30, 0xA7, 0x80, 0xE8, 0x74, 0xA0, 0x07, 0x00, 0x2F,
0xA7, 0x80, 0xE8, 0x74, 0x20, 0x0A, 0x00, 0x2E, 0x22, 0xC1, 0x60, 0x14,
0x66, 0x0A, 0x00, 0x2D, 0x26, 0xD3, 0x49, 0x70, 0x20, 0x0A, 0x00, 0x2C,
0x82, 0x43, 0x08, 0x54, 0x63, 0x04, 0x00, 0x2B, 0xE0, 0x32, 0x11, 0xE8,
0x72, 0x01, 0x00, 0x2A, 0x26, 0x53, 0x01, 0x64, 0xA1, 0x07, 0x00, 0x29,
0x22, 0xC1, 0xE8, 0x80, 0x21, 0x0A, 0x00, 0x28, 0xA6, 0x91, 0x61, 0x80,
0x21, 0x0A, 0x00, 0x27, 0xA2, 0xC1, 0xE8, 0x84, 0x21, 0x0A, 0x00, 0x26,
0xA8, 0x24, 0x13, 0x63, 0xB2, 0x07, 0x00, 0x25, 0xA3, 0x40, 0xE9, 0x84,
0xC1, 0x0C, 0x00, 0x24, 0xA3, 0x81, 0x89, 0x54, 0xE3, 0x00, 0x00, 0x23,
0x26, 0x12, 0xA0, 0x64, 0x61, 0x0A, 0x00, 0x22, 0x26, 0xD3, 0x69, 0x70,
0x61, 0x05, 0x00, 0x21, 0xA6, 0xC1, 0xC9, 0x84, 0x21, 0x0A, 0x00, 0x20,
0xE0, 0x32, 0x91, 0x48, 0x68, 0x04, 0x00, 0x1F, 0x26, 0x91, 0xE8, 0x00,
0x7C, 0x0B, 0x00, 0x1E, 0xA8, 0x2C, 0x83, 0x65, 0xA2, 0x07, 0x00, 0x1D,
0x26, 0xC1, 0x41, 0xE0, 0x73, 0x01, 0x00, 0x1C, 0xAC, 0x04, 0x22, 0xFD,
0x62, 0x01, 0x00, 0x1B, 0x2C, 0x34, 0x7B, 0xDB, 0xE8, 0x00, 0x00, 0x1A,
0x2C, 0x64, 0x23, 0x11, 0x72, 0x0A, 0x00, 0x19, 0xA2, 0xD0, 0x09, 0xF4,
0xA1, 0x07, 0x00, 0x18, 0x23, 0x81, 0x49, 0x20, 0x21, 0x0A, 0x00, 0x17,
0x23, 0x81, 0x49, 0x30, 0xA1, 0x07, 0x00, 0x16, 0xA3, 0x40, 0xE9, 0x84,
0xA1, 0x08, 0x00, 0x15, 0x36, 0x4B, 0x08, 0xD4, 0xA0, 0x09, 0x00, 0x14,
0xA3, 0x80, 0x69, 0x70, 0xA0, 0x08, 0x00, 0x13, 0x60, 0x58, 0xD1, 0x9C,
0x63, 0x01, 0x00, 0x12, 0x6C, 0x54, 0x8B, 0xFB, 0xA2, 0x09, 0x00, 0x11,
0x6C, 0x54, 0x8B, 0xFB, 0x63, 0x01, 0x00, 0x10, 0x28, 0x64, 0xD3, 0xF7,
0x63, 0x01, 0x00, 0x0F, 0x22, 0x91, 0xE1, 0x90, 0x73, 0x01, 0x00, 0x0E,
0x36, 0x19, 0x24, 0xE6, 0x61, 0x0A, 0x00, 0x0D, 0x32, 0x88, 0xA5, 0x66,
0xA3, 0x07, 0x00, 0x0C, 0xA6, 0x91, 0x61, 0x90, 0xA1, 0x09, 0x00, 0x0B,
0xA6, 0x91, 0x61, 0x90, 0x61, 0x0A, 0x00, 0x0A, 0xA6, 0x91, 0x61, 0x80,
0x61, 0x0B, 0x00, 0x09, 0xA3, 0x40, 0xE9, 0xC4, 0x61, 0x01, 0x00, 0x08,
0x6C, 0x54, 0xCB, 0xF3, 0x63, 0x04, 0x00, 0x07, 0xA6, 0xC1, 0xC9, 0x34,
0xA1, 0x07, 0x00, 0x06, 0xA6, 0xC1, 0xC9, 0x64, 0x61, 0x01, 0x00, 0x05,
0xE8, 0x16, 0x03, 0x61, 0xFB, 0x00, 0x00, 0x04, 0x27, 0x81, 0x68, 0xC4,
0xA1, 0x09, 0x00, 0x02, 0x27, 0x81, 0x68, 0xD4, 0x61, 0x01, 0x00, 0x01,
0x27, 0x81, 0x68, 0x74, 0x61, 0x03, 0x00, 0x00
};
void filters_commit(int force);
void votraxsc01_set_clock(UINT32 newfreq)
{
// update if changed
if(newfreq != votraxsc01_locals.mainclock) {
stream_update(votraxsc01_locals.stream,0);
if (timer_expire(votraxsc01_locals.timer) != TIME_NEVER) {
// determine how many clock ticks remained on the timer
double remaining = timer_timeleft(votraxsc01_locals.timer)*votraxsc01_locals.mainclock; //!! was: remaining().as_ticks(votraxsc01_locals.mainclock)
// adjust the timer to the same number of ticks based on the new frequency
timer_adjust(votraxsc01_locals.timer, remaining/(double)newfreq/*attotime::from_ticks(remaining, newfreq)*/, 0, TIME_NEVER); //!! correct like this?
}
votraxsc01_locals.mainclock = newfreq;
votraxsc01_locals.sclock = votraxsc01_locals.mainclock / 18.0;
votraxsc01_locals.cclock = votraxsc01_locals.mainclock / 36.0;
stream_set_sample_rate(votraxsc01_locals.stream, votraxsc01_locals.sclock);
filters_commit(1);
}
}
// useful macros to deal with bit shuffling encryptions
#define BITSWAP4(val,B3,B2,B1,B0) \
((BIT(val,B3) << 3) | (BIT(val,B2) << 2) | (BIT(val,B1) << 1) | (BIT(val,B0) << 0))
#define BITSWAP7(val,B6,B5,B4,B3,B2,B1,B0) \
((BIT(val,B6) << 6) | (BIT(val,B5) << 5) | (BIT(val,B4) << 4) | \
(BIT(val,B3) << 3) | (BIT(val,B2) << 2) | (BIT(val,B1) << 1) | (BIT(val,B0) << 0))
static void phone_commit()
{
int i;
// Only these two counters are reset on phone change, the rest is
// free-running.
votraxsc01_locals.phonetick = 0;
votraxsc01_locals.ticks = 0;
// In the real chip, the rom is re-read all the time. Since it's
// internal and immutable, no point in not caching it though.
for (i = 0; i<64; i++) {
const UINT64 val = ((UINT64 *)sc01a_bin)/*(m_rom->base())*/[i];
if (votraxsc01_locals.phone == ((val >> 56) & 0x3f)) {
votraxsc01_locals.rom_f1 = BITSWAP4(val, 0, 7, 14, 21);
votraxsc01_locals.rom_va = BITSWAP4(val, 1, 8, 15, 22);
votraxsc01_locals.rom_f2 = BITSWAP4(val, 2, 9, 16, 23);
votraxsc01_locals.rom_fc = BITSWAP4(val, 3, 10, 17, 24);
votraxsc01_locals.rom_f2q = BITSWAP4(val, 4, 11, 18, 25);
votraxsc01_locals.rom_f3 = BITSWAP4(val, 5, 12, 19, 26);
votraxsc01_locals.rom_fa = BITSWAP4(val, 6, 13, 20, 27);
// These two values have their bit orders inverted
// compared to everything else due to a bug in the
// prototype (miswiring of the comparator with the ticks
// count) they compensated in the rom.
votraxsc01_locals.rom_cld = BITSWAP4(val, 34, 32, 30, 28);
votraxsc01_locals.rom_vd = BITSWAP4(val, 35, 33, 31, 29);
votraxsc01_locals.rom_closure = BIT(val, 36);
votraxsc01_locals.rom_duration = BITSWAP7(~val, 37, 38, 39, 40, 41, 42, 43);
// Hard-wired on the die, not an actual part of the rom.
votraxsc01_locals.rom_pause = (votraxsc01_locals.phone == 0x03) || (votraxsc01_locals.phone == 0x3e);
#if VERBOSE
LOG(("commit fa=%x va=%x fc=%x f1=%x f2=%x f2q=%x f3=%x dur=%02x cld=%x vd=%d cl=%d pause=%d\n", votraxsc01_locals.rom_fa, votraxsc01_locals.rom_va, votraxsc01_locals.rom_fc, votraxsc01_locals.rom_f1, votraxsc01_locals.rom_f2, votraxsc01_locals.rom_f2q, votraxsc01_locals.rom_f3, votraxsc01_locals.rom_duration, votraxsc01_locals.rom_cld, votraxsc01_locals.rom_vd, votraxsc01_locals.rom_closure, votraxsc01_locals.rom_pause));
#endif
// That does not happen in the sc01(a) rom, but let's
// cover our behind.
if (votraxsc01_locals.rom_cld == 0)
votraxsc01_locals.cur_closure = votraxsc01_locals.rom_closure;
return;
}
}
}
static void interpolate(UINT8 * const reg, const UINT8 target)
{
// One step of interpolation, adds one eight of the distance
// between the current value and the target.
*reg = *reg - (*reg >> 3) + (target << 1);
}
static void chip_update()
{
int tick_625,tick_208;
int inp;
// Phone tick counter update. Stopped when ticks reach 16.
// Technically the counter keeps updating, but the comparator is
// disabled.
if (votraxsc01_locals.ticks != 0x10) {
votraxsc01_locals.phonetick++;
// Comparator is with duration << 2, but there's a one-tick
// delay in the path.
if (votraxsc01_locals.phonetick == ((votraxsc01_locals.rom_duration << 2) | 1)) {
votraxsc01_locals.phonetick = 0;
votraxsc01_locals.ticks++;
if (votraxsc01_locals.ticks == votraxsc01_locals.rom_cld)
votraxsc01_locals.cur_closure = votraxsc01_locals.rom_closure;
}
}
// The two update timing counters. One divides by 16, the other
// by 48, and they're phased so that the 208Hz counter ticks
// exactly between two 625Hz ticks.
votraxsc01_locals.update_counter++;
if (votraxsc01_locals.update_counter == 0x30)
votraxsc01_locals.update_counter = 0;
tick_625 = !(votraxsc01_locals.update_counter & 0xf);
tick_208 = (votraxsc01_locals.update_counter == 0x28);
// Formant update. Die bug there: fc should be updated, not va.
// The formants are frozen on a pause phone unless both voice and
// noise volumes are zero.
if (tick_208 && (!votraxsc01_locals.rom_pause || !(votraxsc01_locals.filt_fa || votraxsc01_locals.filt_va))) {
// interpolate(&votraxsc01_locals.cur_va, votraxsc01_locals.rom_va);
interpolate(&votraxsc01_locals.cur_fc, votraxsc01_locals.rom_fc);
interpolate(&votraxsc01_locals.cur_f1, votraxsc01_locals.rom_f1);
interpolate(&votraxsc01_locals.cur_f2, votraxsc01_locals.rom_f2);
interpolate(&votraxsc01_locals.cur_f2q, votraxsc01_locals.rom_f2q);
interpolate(&votraxsc01_locals.cur_f3, votraxsc01_locals.rom_f3);
#if VERBOSE
LOG(("int fa=%x va=%x fc=%x f1=%x f2=%02x f2q=%02x f3=%x\n", votraxsc01_locals.cur_fa >> 4, votraxsc01_locals.cur_va >> 4, votraxsc01_locals.cur_fc >> 4, votraxsc01_locals.cur_f1 >> 4, votraxsc01_locals.cur_f2 >> 3, votraxsc01_locals.cur_f2q >> 4, votraxsc01_locals.cur_f3 >> 4));
#endif
}
// Non-formant update. Same bug there, va should be updated, not fc.
if(tick_625) {
if (votraxsc01_locals.ticks >= votraxsc01_locals.rom_vd)
interpolate(&votraxsc01_locals.cur_fa, votraxsc01_locals.rom_fa);
if (votraxsc01_locals.ticks >= votraxsc01_locals.rom_cld)
// interpolate(&votraxsc01_locals.cur_fc, votraxsc01_locals.rom_fc);
interpolate(&votraxsc01_locals.cur_va, votraxsc01_locals.rom_va);
#if VERBOSE
LOG(("int fa=%x va=%x fc=%x f1=%x f2=%02x f2q=%02x f3=%x\n", votraxsc01_locals.cur_fa >> 4, votraxsc01_locals.cur_va >> 4, votraxsc01_locals.cur_fc >> 4, votraxsc01_locals.cur_f1 >> 4, votraxsc01_locals.cur_f2 >> 3, votraxsc01_locals.cur_f2q >> 4, votraxsc01_locals.cur_f3 >> 4));
#endif
}
// Closure counter, reset every other tick in theory when not
// active (on the extra rom cycle).
//
// The closure level is immediatly used in the analog path,
// there's no pitch synchronization.
if (!votraxsc01_locals.cur_closure && (votraxsc01_locals.filt_fa || votraxsc01_locals.filt_va))
votraxsc01_locals.closure = 0;
else if (votraxsc01_locals.closure != (7 << 2))
votraxsc01_locals.closure++;
// Pitch counter. Equality comparison, so it's possible to make
// it miss by manipulating the inflection inputs, but it'll wrap.
// There's a delay, hence the +2.
// Intrinsically pre-divides by two, so we added one bit on the 7
votraxsc01_locals.pitch = (votraxsc01_locals.pitch + 1) & 0xff;
if(votraxsc01_locals.pitch == (0xe0 ^ (votraxsc01_locals.inflection << 5) ^ (votraxsc01_locals.filt_f1 << 1)) + 2)
votraxsc01_locals.pitch = 0;
// Filters are updated in index 1 of the pitch wave, which does
// indeed mean four times in a row.
if ((votraxsc01_locals.pitch & 0xf9) == 0x08)
filters_commit(0);
// Noise shift register. 15 bits, with a nxor on the last two
// bits for the loop.
inp = (1 || votraxsc01_locals.filt_fa) && votraxsc01_locals.cur_noise && (votraxsc01_locals.noise != 0x7fff);
votraxsc01_locals.noise = ((votraxsc01_locals.noise << 1) & 0x7ffe) | inp;
votraxsc01_locals.cur_noise = !(((votraxsc01_locals.noise >> 14) ^ (votraxsc01_locals.noise >> 13)) & 1);
#if VERBOSE
LOG(("tick %02x.%03x 625=%d 208=%d pitch=%02x.%x ns=%04x ni=%d noise=%d cl=%x.%x clf=%d/%d\n", votraxsc01_locals.ticks, votraxsc01_locals.phonetick, tick_625, tick_208, votraxsc01_locals.pitch >> 3, votraxsc01_locals.pitch & 7, votraxsc01_locals.noise, inp, votraxsc01_locals.cur_noise, votraxsc01_locals.closure >> 2, votraxsc01_locals.closure & 3, votraxsc01_locals.rom_closure, votraxsc01_locals.cur_closure));
#endif
}
/*
Playing with analog filters, or where all the magic filter formulas are coming from.
First you start with an analog circuit, for instance this one:
| +--[R2]--+
| | |
| +--|C2|--+<V1 +--|C3|--+
| | | | |
| Vi +--[R1]--+ | |\ | | |\ |
| -----+ +----+--+-\ | +--+-\ |
| +--|C1|--+ | >--+--[Rx]--+ | >--+----- Vo
| | 0-++/ 0-++/ |
| | |/ +--[R0]--+ |/ |
| | | | |
| | | /| | |
| | | /-+--+--[R0]--+
| +--[R4]-------+--< |
| V2^ \++-0
| \|
It happens to be what most of the filters in the sc01a look like.
You need to determine the transfer function H(s) of the circuit, which is
defined as the ratio Vo/Vi. To do that, you use some properties:
- The intensity through an element is equal to the voltage
difference through the element divided by the impedence
- The impedence of a resistance is equal to its resistance
- The impedence of a capacitor is 1/(s*C) where C is its capacitance
- The impedence of elements in series is the sum of the impedences
- The impedence of elements in parallel is the inverse of the sum of
the inverses
- The sum of all intensities flowing into a node is 0 (there's no
charge accumulation in a wire)
- An operational amplifier in looped mode is an interesting beast:
the intensity at its two inputs is always 0, and the voltage is
forced identical between the inputs. In our case, since the '+'
inputs are all tied to ground, that means that the '-' inputs are at
voltage 0, intensity 0.
From here we can build some equations. Noting:
X1 = 1/(1/R1 + s*C1)
X2 = 1/(1/R2 + s*C2)
X3 = 1/(s*C3)
Then computing the intensity flow at each '-' input we have:
Vi/X1 + V2/R4 + V1/X2 = 0
V2/R0 + Vo/R0 = 0
V1/Rx + Vo/X3 = 0
Wrangling the equations, one eventually gets:
| 1 + s * C1*R1
| Vo/Vi = H(s) = (R4/R1) * -------------------------------------------
| 1 + s * C3*Rx*R4/R2 + s^2 * C2*C3*Rx*R4
To check the mathematics between the 's' stuff, check "Laplace
transform". In short, it's a nice way of manipulating derivatives
and integrals without having to manipulate derivatives and
integrals.
With that transfer function, we first can compute what happens to
every frequency in the input signal. You just compute H(2i*pi*f)
where f is the frequency, which will give you a complex number
representing the amplitude and phase effect. To get the usual dB
curves, compute 20*log10(abs(v))).
Now, once you have an analog transfer function, you can build a
digital filter from it using what is called the bilinear transform.
In our case, we have an analog filter with the transfer function:
| 1 + k[0]*s
| H(s) = -------------------------
| 1 + k[1]*s + k[2]*s^2
We can always reintroduce the global multipler later, and it's 1 in
most of our cases anyway.
The we pose:
| z-1
| s(z) = zc * ---
| z+1
where zc = 2*pi*fr/tan(pi*fr/fs)
with fs = sampling frequency
and fr = most interesting frequency
Then we rewrite H in function of negative integer powers of z.
Noting m0 = zc*k[0], m1 = zc*k[1], m2=zc*zc*k[2],
a little equation wrangling then gives:
| (1+m0) + (3+m0) *z^-1 + (3-m0) *z^-2 + (1-m0)*z^-3
| H(z) = ----------------------------------------------------------------
| (1+m1+m2) + (3+m1-m2)*z^-1 + (3-m1-m2)*z^-2 + (1-m1+m2)*z^-3
That beast in the digital transfer function, of which you can
extract response curves by posing z = exp(2*i*pi*f/fs).
Note that the bilinear transform is an approximation, and H(z(f)) =
H(s(f)) only at frequency fr. And the shape of the filter will be
better respected around fr. If you look at the curves of the
filters we're interested in, the frequency:
fr = sqrt(abs(k[0]*k[1]-k[2]))/(2*pi*k[2])
which is a (good) approximation of the filter peak position is a
good choice.
Note that terminology wise, the "standard" bilinear transform is
with fr = fs/2, and using a different fr is called "pre-warping".
So now we have a digital transfer function of the generic form:
| a[0] + a[1]*z^-1 + a[2]*z^-2 + a[3]*z^-3
| H(z) = --------------------------------------------
| b[0] + b[1]*z^-1 + b[2]*z^-2 + b[3]*z^-3
The magic then is that the powers of z represent time in samples.
Noting x the input stream and y the output stream, you have:
H(z) = y(z)/x(z)
or in other words:
y*b[0]*z^0 + y*b[1]*z^-1 + y*b[2]*z^-2 + y*b[3]*z^-3 = x*a[0]*z^0 + x*a[1]*z^-1 + x*a[2]*z^-2 + x*a[3]*z^-3
i.e.
y*z^0 = (x*a[0]*z^0 + x*a[1]*z^-1 + x*a[2]*z^-2 + x*a[3]*z^-3 - y*b[1]*z^-1 - y*b[2]*z^-2 - y*b[3]*z^-3) / b[0]
and powers of z being time in samples,
y[0] = (x[0]*a[0] + x[-1]*a[1] + x[-2]*a[2] + x[-3]*a[3] - y[-1]*b[1] - y[-2]*b[2] - y[-3]*b[3]) / b[0]
So you have a filter you can apply. Note that this is why you want
negative powers of z. Positive powers would mean looking into the
future (which is possible in some cases, in particular with x, and
has some very interesting properties, but is not very useful in
analog circuit simulation).
Note that if you have multiple inputs, all this stuff is linear.
Or, in other words, you just have to split it in multiple circuits
with only one input connected each time and sum the results. It
will be correct.
Also, since we're in practice in a dynamic system, for an amplifying
filter (i.e. where things like r4/r1 is not 1), it's better to
proceed in two steps:
- amplify the input by the current value of the coefficient, and
historize it
- apply the now non-amplifying filter to the historized amplified
input
That way reduces the probability of the output bouncing all over the
place.
Except, we're not done yet. Doing resistors precisely in an IC is
very hard and/or expensive (you may have heard of "laser cut
resistors" in DACs of the time). Doing capacitors is easier, and
their value is proportional to their surface. So there are no
resistors on the sc01 die (which is a lie, there are three, but not
in the filter path. They are used to scale the voltage in the pitch
wave and to generate +5V from the +9V), but a magic thing called a
switched capacitor. Lookup patent 4,433,210 for details. Using
high frequency switching a capacitor can be turned into a resistor
of value 1/(C*f) where f is the switching frequency (20Khz,
main/36). And the circuit is such that the absolute value of the
capacitors is irrelevant, only their ratio is useful, which factors
out the intrinsic capacity-per-surface-area of the IC which may be
hard to keep stable from one die to another. As a result all the
capacitor values we use are actually surfaces in square micrometers.
For the curious, it looks like the actual capacitance was around 25
femtofarad per square micrometer.
*/
static void build_standard_filter(double * const a, double * const b,
const double c1t, // Unswitched cap, input, top
const double c1b, // Switched cap, input, bottom
const double c2t, // Unswitched cap, over first amp-op, top
const double c2b, // Switched cap, over first amp-op, bottom
const double c3, // Cap between the two op-amps
const double c4) // Cap over second op-amp
{
// First compute the three coefficients of H(s). One can note
// that there is as many capacitor values on both sides of the
// division, which confirms that the capacity-per-surface-area
// is not needed.
const double k0 = c1t / (votraxsc01_locals.cclock * c1b);
const double k1 = c4 * c2t / (votraxsc01_locals.cclock * c1b * c3);
const double k2 = c4 * c2b / (votraxsc01_locals.cclock * votraxsc01_locals.cclock * c1b * c3);
// Estimate the filter cutoff frequency
const double fpeak = sqrt(fabs(k0*k1 - k2))/((2.*M_PI)*k2);
// figure radians from frequency
double w0 = fpeak * (2.0 * M_PI);
#if !defined(_MSC_VER) || (_MSC_VER > 1500)
// keep it in -PI/T .. PI/T
const double wdMax = M_PI * votraxsc01_locals.sclock;
if (w0 > wdMax)
w0 -= 2.0 * wdMax;
#endif
// Turn that into a warp multiplier
const double zc = w0/tan(w0 / (2.0*votraxsc01_locals.sclock));
// Finally compute the result of the z-transform
const double m0 = zc*k0;
const double m1 = zc*k1;
const double m2 = zc*zc*k2;
a[0] = 1.+m0;
a[1] = 3.+m0;
a[2] = 3.-m0;
a[3] = 1.-m0;
b[0] = 1.+m1+m2;
b[1] = 3.+m1-m2;
b[2] = 3.-m1-m2;
b[3] = 1.-m1+m2;
}
/*
Second filter type used once at the end, much simpler:
| +--[R1]--+
| | |
| +--|C1|--+
| | |
| Vi | |\ |
| ---[R0]--+--+-\ |
| | >--+------ Vo
| 0-++/
| |/
Vi/R0 = Vo / (1/(1/R1 + s.C1)) = Vo (1/R1 + s.C1)
H(s) = Vo/Vi = (R1/R0) * (1 / (1 + s.R1.C1))
*/
static void build_lowpass_filter(double * const a, double * const b,
const double c1t, // Unswitched cap, over amp-op, top
const double c1b) // Switched cap, over amp-op, bottom
{
// The caps values puts the cutoff at around 150Hz, put that's no good.
// Recordings shows we want it around 4K, so fuzz it.
// Compute the only coefficient we care about
const double k = c1b / (votraxsc01_locals.cclock * c1t) * (150.0/4000.0);
// Compute the filter cutoff frequency
const double fpeak = 1./((2.*M_PI)*k);
// figure radians from frequency
double w0 = fpeak * (2.0 * M_PI);
#if !defined(_MSC_VER) || (_MSC_VER > 1500)
// keep it in -PI/T .. PI/T
const double wdMax = M_PI * votraxsc01_locals.sclock;
if (w0 > wdMax)
w0 -= 2.0 * wdMax;
#endif
// Turn that into a warp multiplier
const double zc = w0/tan(w0 / (2.0*votraxsc01_locals.sclock));
// Finally compute the result of the z-transform
const double m = zc*k;
a[0] = 1.;
b[0] = 1.+m;
b[1] = 1.-m;
}
/*
Used to shape the white noise
+-------------------------------------------------------------------+
| |
+--|C1|--+---------|C3|----------+--|C4|--+ |
| | + + | | |
Vi | |\ | (1) (1) | | + + |
-|R0|-+--+-\ | | | | |\ | (1) (1) |
| >--+--(2)-+--|C2|--+---(2)-+--+-\ | | | |
0-++/ | | >--+--(2)--+--|C5|--+---(2)--+
|/ Vo 0-++/
|/
Equivalent:
+------------------|R5|-------------------+
| |
+--|C1|--+---------|C3|----------+--|C4|--+
| | | |
Vi | |\ | | |
-|R0|-+--+-\ | | |\ |
| >--+---------|R2|----------+--+-\ |
0-++/ | | >--+
|/ Vo 0-++/
|/
We assume r0 = r2
*/
static void build_noise_shaper_filter(double * const a, double * const b,
const double c1, // Cap over first amp-op
const double c2t, // Unswitched cap between amp-ops, input, top
const double c2b, // Switched cap between amp-ops, input, bottom
const double c3, // Cap over second amp-op
const double c4) // Switched cap after second amp-op
{
// Coefficients of H(s) = k1*s / (1 + k2*s + k3*s^2)
const double k0 = c2t*c3*c2b/c4;
const double k1 = c2t*(votraxsc01_locals.cclock * c2b);
const double k2 = c1*c2t*c3/(votraxsc01_locals.cclock * c4);
// Estimate the filter cutoff frequency
const double fpeak = sqrt(1./k2)/(2.*M_PI);
// figure radians from frequency
double w0 = fpeak * (2.0 * M_PI);
#if !defined(_MSC_VER) || (_MSC_VER > 1500)
// keep it in -PI/T .. PI/T
const double wdMax = M_PI * votraxsc01_locals.sclock;
if (w0 > wdMax)
w0 -= 2.0 * wdMax;
#endif
// Turn that into a warp multiplier
const double zc = w0/tan(w0 / (2.0*votraxsc01_locals.sclock));
// Finally compute the result of the z-transform
const double m0 = zc*k0;
const double m1 = zc*k1;
const double m2 = zc*zc*k2;
a[0] = m0;
a[1] = 0;
a[2] = -m0;
b[0] = 1.+m1+m2;
b[1] = 2.-2.*m2;
b[2] = 1.-m1+m2;
}
/*
Noise injection in f2
| +--[R2]--+ +--[R1]-------- Vi
| | | |
| +--|C2|--+<V1 +--|C3|--+
| | | | |
| | |\ | | |\ |
| +----+--+-\ | +--+-\ |
| | | >--+--[Rx]--+ | >--+----- Vo
| | 0-++/ 0-++/ |
| | |/ +--[R0]--+ |/ |
| | | | |
| | | /| | |
| | | /-+--+--[R0]--+
| +--[R4]-------+--< |
| V2^ \++-0
| \|
We drop r0/r1 out of the equation (it factorizes), and we rescale so
that H(infinity)=1.
*/
static void build_injection_filter(double * const a, double * const b,
const double c1b, // Switched cap, input, bottom
const double c2t, // Unswitched cap, over first amp-op, top
const double c2b, // Switched cap, over first amp-op, bottom
const double c3, // Cap between the two op-amps
const double c4) // Cap over second op-amp
{
// First compute the three coefficients of H(s) = (k0 + k2*s)/(k1 - k2*s)
const double k0 = votraxsc01_locals.cclock * c2t;
const double k1 = votraxsc01_locals.cclock * (c1b * c3 / c2t - c2t);
const double k2 = c2b;
// Don't pre-warp
const double zc = 2.*votraxsc01_locals.sclock;
// Finally compute the result of the z-transform
const double m = zc*k2;
a[0] = k0 + m;
a[1] = k0 - m;
b[0] = k1 - m;
b[1] = k1 + m;
// That ends up in a numerically unstable filter. Neutralize it for now.
a[0] = 0;
a[1] = 0;
b[0] = 1.;
b[1] = 0;
}
// Compute a total capacitor value based on which bits are currently active
static unsigned int bits_to_caps(unsigned int value, const unsigned int * const caps_values, const size_t N) {
size_t i;
unsigned int total = 0;
for(i = 0; i < N; ++i) {
if(value & 1)
total += caps_values[i];
value >>= 1;
}
return total;
}
static const unsigned int f1_caps[4] = { 2546, 4973, 9861, 19724 };
static const unsigned int f2v1_caps[4] = { 1390, 2965, 5875, 11297 };
static const unsigned int f2v2_caps[5] = { 833, 1663, 3164, 6327, 12654 };
static const unsigned int f2n1_caps[4] = { 1390, 2965, 5875, 11297 };
static const unsigned int f2n2_caps[5] = { 833, 1663, 3164, 6327, 12654 };
static const unsigned int f3_caps[4] = { 2226, 4485, 9056, 18111 };
void filters_commit(int force)
{
votraxsc01_locals.filt_fa = votraxsc01_locals.cur_fa >> 4;
votraxsc01_locals.filt_fc = votraxsc01_locals.cur_fc >> 4;
votraxsc01_locals.filt_va = votraxsc01_locals.cur_va >> 4;
if (force || votraxsc01_locals.filt_f1 != votraxsc01_locals.cur_f1 >> 4) {
votraxsc01_locals.filt_f1 = votraxsc01_locals.cur_f1 >> 4;
build_standard_filter(votraxsc01_locals.f1_a, votraxsc01_locals.f1_b,
11247,
11797,
949,
52067,
2280 + bits_to_caps(votraxsc01_locals.filt_f1, f1_caps, 4),
166272);
}
if (force || votraxsc01_locals.filt_f2 != votraxsc01_locals.cur_f2 >> 3 || votraxsc01_locals.filt_f2q != votraxsc01_locals.cur_f2q >> 4) {
votraxsc01_locals.filt_f2 = votraxsc01_locals.cur_f2 >> 3;
votraxsc01_locals.filt_f2q = votraxsc01_locals.cur_f2q >> 4;
build_standard_filter(votraxsc01_locals.f2v_a, votraxsc01_locals.f2v_b,
24840,
29154,
829 + bits_to_caps(votraxsc01_locals.filt_f2q, f2v1_caps, 4),
38180,
2352 + bits_to_caps(votraxsc01_locals.filt_f2, f2v2_caps, 5),
34270);
build_injection_filter(votraxsc01_locals.f2n_a, votraxsc01_locals.f2n_b,
29154,
829 + bits_to_caps(votraxsc01_locals.filt_f2q, f2n1_caps, 4),
38180,
2352 + bits_to_caps(votraxsc01_locals.filt_f2, f2n2_caps, 5),
34270);
}
if (force || votraxsc01_locals.filt_f3 != votraxsc01_locals.cur_f3 >> 4) {
votraxsc01_locals.filt_f3 = votraxsc01_locals.cur_f3 >> 4;
build_standard_filter(votraxsc01_locals.f3_a, votraxsc01_locals.f3_b,
0,
17594,
868,
18828,
8480 + bits_to_caps(votraxsc01_locals.filt_f3, f3_caps, 4),
50019);
}
if(force) {
build_standard_filter(votraxsc01_locals.f4_a, votraxsc01_locals.f4_b,
0,
28810,
1165,
21457,
8558,
7289);
build_lowpass_filter(votraxsc01_locals.fx_a, votraxsc01_locals.fx_b,
1122,
23131);
build_noise_shaper_filter(votraxsc01_locals.fn_a, votraxsc01_locals.fn_b,
15500,
14854,
8450,
9523,
14083);
}
#if VERBOSE
if(votraxsc01_locals.filt_fa || votraxsc01_locals.filt_va || votraxsc01_locals.filt_fc || votraxsc01_locals.filt_f1 || votraxsc01_locals.filt_f2 || votraxsc01_locals.filt_f2q || votraxsc01_locals.filt_f3)
LOG(("filter fa=%x va=%x fc=%x f1=%x f2=%02x f2q=%x f3=%x\n",
votraxsc01_locals.filt_fa, votraxsc01_locals.filt_va, votraxsc01_locals.filt_fc, votraxsc01_locals.filt_f1, votraxsc01_locals.filt_f2, votraxsc01_locals.filt_f2q, votraxsc01_locals.filt_f3));
#endif
}
// Shift a history of values by one and insert the new value at the front
static void shift_hist(const double val, double * const hist_array, const size_t N) {
size_t i;
for(i=N-1; i>0; i--)
hist_array[i] = hist_array[i-1];
hist_array[0] = val;
}
// Apply a filter and compute the result. 'a' is applied to x (inputs) and 'b' to y (outputs)
static double apply_filter(const double * const x, const double * const y, const double * const a, const size_t Na, const double * const b, const size_t Nb) {
size_t i;
double total = 0;
for(i=0; i<Na; i++)
total += x[i] * a[i];
for(i=1; i<Nb; i++)
total -= y[i-1] * b[i];
return total / b[0];
}
static float analog_calc()
{
double v,n,n2,vn;
// Voice-only path.
// 1. Pick up the pitch wave
v = votraxsc01_locals.pitch >= (9 << 3) ? 0 : s_glottal_wave[votraxsc01_locals.pitch >> 3];
// 2. Multiply by the initial amplifier. It's linear on the die,
// even if it's not in the patent.
v = v * votraxsc01_locals.filt_va * (1.0/15.0);
shift_hist(v, votraxsc01_locals.voice_1, 4);
// 3. Apply the f1 filter
v = apply_filter(votraxsc01_locals.voice_1, votraxsc01_locals.voice_2, votraxsc01_locals.f1_a, 4, votraxsc01_locals.f1_b, 4);
shift_hist(v, votraxsc01_locals.voice_2, 4);
// 4. Apply the f2 filter, voice half
v = apply_filter(votraxsc01_locals.voice_2, votraxsc01_locals.voice_3, votraxsc01_locals.f2v_a, 4, votraxsc01_locals.f2v_b, 4);
shift_hist(v, votraxsc01_locals.voice_3, 4);
// Noise-only path
// 5. Pick up the noise pitch. Amplitude is linear. Base
// intensity should be checked w.r.t the voice.
n = 1e4 * ((votraxsc01_locals.pitch & 0x40 ? votraxsc01_locals.cur_noise : 0) ? 1 : -1);
n = n * votraxsc01_locals.filt_fa * (1.0/15.0);
shift_hist(n, votraxsc01_locals.noise_1, 3);
// 6. Apply the noise shaper
n = apply_filter(votraxsc01_locals.noise_1, votraxsc01_locals.noise_2, votraxsc01_locals.fn_a, 3, votraxsc01_locals.fn_b, 3);
shift_hist(n, votraxsc01_locals.noise_2, 3);
// 7. Scale with the f2 noise input
n2 = n * votraxsc01_locals.filt_fc * (1.0/15.0);
shift_hist(n2, votraxsc01_locals.noise_3, 2);
// 8. Apply the f2 filter, noise half,
n2 = apply_filter(votraxsc01_locals.noise_3, votraxsc01_locals.noise_4, votraxsc01_locals.f2n_a, 2, votraxsc01_locals.f2n_b, 2);
shift_hist(n2, votraxsc01_locals.noise_4, 2);
// Mixed path
// 9. Add the f2 voice and f2 noise outputs
vn = v + n2;
shift_hist(vn, votraxsc01_locals.vn_1, 4);
// 10. Apply the f3 filter
vn = apply_filter(votraxsc01_locals.vn_1, votraxsc01_locals.vn_2, votraxsc01_locals.f3_a, 4, votraxsc01_locals.f3_b, 4);
shift_hist(vn, votraxsc01_locals.vn_2, 4);
// 11. Second noise insertion
vn += n * (5 + (15 ^ votraxsc01_locals.filt_fc)) * (1.0/20.0);
shift_hist(vn, votraxsc01_locals.vn_3, 4);
// 12. Apply the f4 filter
vn = apply_filter(votraxsc01_locals.vn_3, votraxsc01_locals.vn_4, votraxsc01_locals.f4_a, 4, votraxsc01_locals.f4_b, 4);
shift_hist(vn, votraxsc01_locals.vn_4, 4);
// 13. Apply the glottal closure amplitude, also linear
vn = vn * (7 ^ (votraxsc01_locals.closure >> 2)) * (1.0/7.0);
shift_hist(vn, votraxsc01_locals.vn_5, 2);
// 13. Apply the final fixed filter
vn = apply_filter(votraxsc01_locals.vn_5, votraxsc01_locals.vn_6, votraxsc01_locals.fx_a, 1, votraxsc01_locals.fx_b, 2);
shift_hist(vn, votraxsc01_locals.vn_6, 2);
return (float)vn * (float)(1.0/2.4); // prevent excessive clipping //!! MAME had a similar magic of * 1.5 here, which is way too loud though
}
#else
#define PT_NS 0
#define PT_V 1
#define PT_VF 2
#define PT_F 3
#define PT_N 4
#define PT_VS 5
#define PT_FS 6
// int sample_rate[4] = {22050, 22550, 23050, 23550};
long sample_rate[4] = {22050, 22050, 22050, 22050};
INLINE int time_to_samples(int ms)
{
return sample_rate[votraxsc01_locals.actIntonation]*ms/1000;
}
void PrepareVoiceData(int nextPhoneme, int nextIntonation)
{
int iNextRemainingSamples;
INT16 *pNextPos, *lpHelp;
int iFadeOutSamples;
int iFadeOutPos;
int iFadeInSamples;
int iFadeInPos;
int doMix;
int AdditionalSamples;
int dwCount, i;
INT16 data;
if ( votraxsc01_locals.lpBuffer )
free(votraxsc01_locals.lpBuffer);
votraxsc01_locals.lpBuffer = NULL;
AdditionalSamples = 0;
if ( PhonemeData[votraxsc01_locals.actPhoneme].iType>=PT_VS && votraxsc01_locals.actPhoneme!=nextPhoneme ) {
AdditionalSamples = PhonemeData[votraxsc01_locals.actPhoneme].iSecondStart;
}
if ( PhonemeData[nextPhoneme].iType>=PT_VS ) {
// 'stop phonemes' will stop playing until the next phoneme is send
votraxsc01_locals.iRemainingSamples = 0;
return;
}
// length of samples to produce
dwCount = time_to_samples(PhonemeData[nextPhoneme].iLengthms);
votraxsc01_locals.iSamplesInBuffer = dwCount+AdditionalSamples;
votraxsc01_locals.lpBuffer = (INT16*) malloc(votraxsc01_locals.iSamplesInBuffer*sizeof(INT16));
if ( AdditionalSamples )
memcpy(votraxsc01_locals.lpBuffer, PhonemeData[votraxsc01_locals.actPhoneme].lpStart[votraxsc01_locals.actIntonation], AdditionalSamples*sizeof(INT16));
lpHelp = votraxsc01_locals.lpBuffer + AdditionalSamples;
iNextRemainingSamples = 0;
pNextPos = NULL;
iFadeOutSamples = 0;
iFadeOutPos = 0;
iFadeInSamples = 0;
iFadeInPos = 0;
doMix = 0;
// set up processing
if ( PhonemeData[votraxsc01_locals.actPhoneme].sameAs!=PhonemeData[nextPhoneme].sameAs ) {
// do something, if they are the same all FadeIn/Out values are 0,
// the buffer is simply filled with the samples of the new phoneme
switch ( PhonemeData[votraxsc01_locals.actPhoneme].iType ) {
case PT_NS:
// "fade" out NS:
iFadeOutSamples = time_to_samples(30);
iFadeOutPos = 0;
// fade in new phoneme
iFadeInPos = -time_to_samples(30);
iFadeInSamples = time_to_samples(30);
break;
case PT_V:
case PT_VF:
switch ( PhonemeData[nextPhoneme].iType ){
case PT_F:
case PT_VF:
// V-->F, V-->VF: fade out 30 ms fade in from 30 ms to 60 ms without mixing
iFadeOutPos = 0;
iFadeOutSamples = time_to_samples(30);
iFadeInPos = -time_to_samples(30);
iFadeInSamples = time_to_samples(30);
break;
case PT_N:
// V-->N: fade out 40 ms fade from 0 ms to 40 ms without mixing
iFadeOutPos = 0;
iFadeOutSamples = time_to_samples(40);
iFadeInPos = -time_to_samples(10);
iFadeInSamples = time_to_samples(10);
break;
default:
// fade out 20 ms, no fade in from 10 ms to 30 ms
iFadeOutPos = 0;
iFadeOutSamples = time_to_samples(20);
iFadeInPos = -time_to_samples(0);
iFadeInSamples = time_to_samples(20);
break;
}
break;
case PT_N:
switch ( PhonemeData[nextPhoneme].iType ){
case PT_V:
case PT_VF:
// N-->V, N-->VF: fade out 30 ms fade in from 10 ms to 50 ms without mixing
iFadeOutPos = 0;
iFadeOutSamples = time_to_samples(30);
iFadeInPos = -time_to_samples(10);
iFadeInSamples = time_to_samples(40);
break;
default:
break;
}
break;
case PT_VS:
case PT_FS:
iFadeOutPos = 0;
iFadeOutSamples = PhonemeData[votraxsc01_locals.actPhoneme].iLength[votraxsc01_locals.actIntonation] - PhonemeData[votraxsc01_locals.actPhoneme].iSecondStart;
votraxsc01_locals.pActPos = PhonemeData[votraxsc01_locals.actPhoneme].lpStart[votraxsc01_locals.actIntonation] + PhonemeData[votraxsc01_locals.actPhoneme].iSecondStart;
votraxsc01_locals.iRemainingSamples = iFadeOutSamples;
doMix = 1;
iFadeInPos = -time_to_samples(0);
iFadeInSamples = time_to_samples(0);
break;
default:
// fade out 30 ms, no fade in
iFadeOutPos = 0;
iFadeOutSamples = time_to_samples(20);
iFadeInPos = -time_to_samples(20);
break;
}
if ( !votraxsc01_locals.iDelay ) {
// this is true if after a stop and a phoneme was send a second phoneme is send
// during the delay time of the chip. Ignore the first phoneme data
iFadeOutPos = 0;
iFadeOutSamples = 0;
}
}
else {
// the next one is of the same type as the previous one; continue to use the samples of the last phoneme
iNextRemainingSamples = votraxsc01_locals.iRemainingSamples;
pNextPos = votraxsc01_locals.pActPos;
}
for (i=0; i<dwCount; i++)
{
data = 0x00;
// fade out
if ( iFadeOutPos<iFadeOutSamples )
{
double dFadeOut = 1.0;
if ( !doMix )
dFadeOut = 1.0-sin((double)iFadeOutPos/(double)iFadeOutSamples * (M_PI/2.));
if ( !votraxsc01_locals.iRemainingSamples ) {
votraxsc01_locals.iRemainingSamples = PhonemeData[votraxsc01_locals.actPhoneme].iLength[votraxsc01_locals.actIntonation];
votraxsc01_locals.pActPos = PhonemeData[votraxsc01_locals.actPhoneme].lpStart[votraxsc01_locals.actIntonation];
}
data = (INT16) (*votraxsc01_locals.pActPos++ * dFadeOut);
votraxsc01_locals.iRemainingSamples--;
iFadeOutPos++;
}
// fade in or copy
if ( iFadeInPos>=0 )
{
double dFadeIn = 1.0;
if ( iFadeInPos<iFadeInSamples ) {
dFadeIn = sin((double)iFadeInPos/(double)iFadeInSamples * (M_PI/2.));
iFadeInPos++;
}
if ( !iNextRemainingSamples ) {
iNextRemainingSamples = PhonemeData[nextPhoneme].iLength[nextIntonation];
pNextPos = PhonemeData[nextPhoneme].lpStart[nextIntonation];
}
data += (INT16) (*pNextPos++ * dFadeIn);
iNextRemainingSamples--;
}
iFadeInPos++;
*lpHelp++ = data;
}
votraxsc01_locals.pBufferPos = votraxsc01_locals.lpBuffer;
votraxsc01_locals.pActPos = pNextPos;
votraxsc01_locals.iRemainingSamples = iNextRemainingSamples;
}
#endif
WRITE_HANDLER(votraxsc01_w)
{
#if !defined(OLD_VOTRAX) && !defined(REAL_DEVICE)
UINT8 prev;
// only 2 bits matter
int inflection = (data >> 6) & 0x03; //!! MAME astrocde also uses: (data & 0x80) ? 0 : 2;
//if (votraxsc01_locals.inflection == inflection) //!! original code, due to separate w for inflection in MAME -> does not matter, astrocde has inflection, then -directly- phone write after it
// return;
stream_update(votraxsc01_locals.stream, 0);
votraxsc01_locals.inflection = inflection;
//!! in the original code this was the separate phone write from here on:
// flush out anything currently processing
//stream_update(votraxsc01_locals.stream,0);
prev = votraxsc01_locals.phone;
// only 6 bits matter
votraxsc01_locals.phone = data & 0x3f;
#if VERBOSE
if (votraxsc01_locals.phone != prev || votraxsc01_locals.phone != 0x3f)
LOG(("phone %02x.%d %s\n", votraxsc01_locals.phone, votraxsc01_locals.inflection, PhonemeNames[votraxsc01_locals.phone]));
#endif
votraxsc01_locals.ar_state = CLEAR_LINE;
// Schedule a commit/ar reset at roughly 0.1ms in the future (one
// phi1 transition followed by the rom extra state in practice),
// but only if there isn't already one on the fly. It will
// override an end-of-phone timeout if there's one pending, but
// that's not a problem since stb does that anyway.
if (timer_expire(votraxsc01_locals.timer) == TIME_NEVER || timer_param(votraxsc01_locals.timer) != T_COMMIT_PHONE)
timer_adjust(votraxsc01_locals.timer, 72./(double)votraxsc01_locals.mainclock/*attotime::from_ticks(72, votraxsc01_locals.mainclock)*/, T_COMMIT_PHONE, TIME_NEVER); //!! correct?
#else
int Phoneme, Intonation;
Phoneme = data & 0x3F;
Intonation = (data >> 6)&0x03;
#if VERBOSE
LOG(("Votrax SC-01: %s at intonation %d\n", PhonemeNames[Phoneme], Intonation));
#endif
#ifndef REAL_DEVICE
// votraxsc01_locals.pActPos = PhonemeData[votraxsc01_locals.actPhoneme].lpStart;
// votraxsc01_locals.iRemainingSamples = PhonemeData[votraxsc01_locals.actPhoneme].iLength;
// timer_reset(votraxsc01_locals.timer, PhonemeLengths[votraxsc01_locals.actPhoneme]/1000.0);
// timer_enable(votraxsc01_locals.timer,1);
PrepareVoiceData(Phoneme, Intonation);
if ( votraxsc01_locals.actPhoneme==0x3f )
votraxsc01_locals.iDelay = time_to_samples(20);
if ( !votraxsc01_locals.busy )
{
votraxsc01_locals.busy = -1;
if ( votraxsc01_locals.intf->BusyCallback[0] )
(*votraxsc01_locals.intf->BusyCallback[0])(votraxsc01_locals.busy);
}
#else
DlPortWritePortUshort(_dataOutAdr, data);
votraxsc01_locals.strobe = 0x00;
DlPortWritePortUshort(_ctrlOutAdr, votraxsc01_locals.strobe);
#endif
votraxsc01_locals.actPhoneme = Phoneme;
votraxsc01_locals.actIntonation = Intonation;
#endif
}
#ifdef REAL_DEVICE
int get_busy()
{
if ( !((DlPortReadPortUchar(_statusInAdr)&_bitmaskAck)>0) )
return -1;
else
return 0;
}
#endif
READ_HANDLER(votraxsc01_status_r)
{
#ifdef REAL_DEVICE
return get_busy();
#else
#ifdef OLD_VOTRAX
return votraxsc01_locals.busy;
#else
return !votraxsc01_locals.ar_state; //!! inverted behavior from MAME
#endif
#endif
}
#ifdef OLD_VOTRAX
void votraxsc01_set_base_frequency(double baseFrequency)
{
int i;
if ( baseFrequency>=0 )
{
votraxsc01_locals.baseFrequency = baseFrequency;
for (i=0; i < 4; i++)
stream_set_sample_rate(votraxsc01_locals.channels[i], baseFrequency);
}
}
#endif
void votraxsc01_set_volume(int volume) // currently just (ab)used to en/disable the output (e.g. volume = 0 or 100 only)
{
#ifdef OLD_VOTRAX
int i;
if (volume >= 0)
{
for (i = 0; i < 4; i++)
mixer_set_volume(votraxsc01_locals.channels[i], volume);
}
#else
if (volume >= 0)
mixer_set_volume(votraxsc01_locals.stream, volume);
#endif
}
static void Votrax_Update(int num, INT16 *buffer, int length)
{
#ifndef REAL_DEVICE
float* const __restrict buffer_f = (float*)buffer;
#if VERBOSE
LOG(("Votrax SC-01: update %d\n", length));
#endif
#ifndef OLD_VOTRAX
int i;
for (i = 0; i<length; i++) {
votraxsc01_locals.sample_count++;
if (votraxsc01_locals.sample_count & 1)
chip_update();
buffer_f[i] = analog_calc();
//LOG(("Votrax SC-01: buffer %d\n", ac));
}
#else
int samplesToCopy;
if ( num!=votraxsc01_locals.actIntonation ) {
memset(buffer_f, 0x00, length*sizeof(float));
return;
}
while ( length ) {
int i;
// if ( votraxsc01_locals.iRemainingSamples==0 ) {
// votraxsc01_locals.pActPos = PhonemeData[votraxsc01_locals.actPhoneme].lpStart;
// votraxsc01_locals.iRemainingSamples = PhonemeData[votraxsc01_locals.actPhoneme].iLength;
// }
// samplesToCopy = (length<=votraxsc01_locals.iRemainingSamples)?length:votraxsc01_locals.iRemainingSamples;
// for(i = 0; i < samplesToCopy; ++i)
// buffer_f[i] = (float)votraxsc01_locals.pActPos[i] * (float)(1./32768.);
// buffer_f += samplesToCopy;
// votraxsc01_locals.pActPos += samplesToCopy;
// votraxsc01_locals.iRemainingSamples -= samplesToCopy;
// length -= samplesToCopy;
if ( votraxsc01_locals.iDelay ) {
samplesToCopy = (length<=votraxsc01_locals.iDelay)?length:votraxsc01_locals.iDelay;
memset(buffer_f, 0x00, samplesToCopy*sizeof(float));
buffer_f += samplesToCopy;
votraxsc01_locals.iDelay -= samplesToCopy;
length -= samplesToCopy;
}
else if ( votraxsc01_locals.iSamplesInBuffer==0 ) {
if ( votraxsc01_locals.busy ) {
votraxsc01_locals.busy = 0;
if ( votraxsc01_locals.intf->BusyCallback[0] )
(*votraxsc01_locals.intf->BusyCallback[0])(votraxsc01_locals.busy);
}
if ( votraxsc01_locals.iRemainingSamples==0 ) {
if ( PhonemeData[votraxsc01_locals.actPhoneme].iType>=PT_VS ) {
votraxsc01_locals.pActPos = PhonemeData[0x3f].lpStart[0];
votraxsc01_locals.iRemainingSamples = PhonemeData[0x3f].iLength[0];
}
else {
votraxsc01_locals.pActPos = PhonemeData[votraxsc01_locals.actPhoneme].lpStart[votraxsc01_locals.actIntonation];
votraxsc01_locals.iRemainingSamples = PhonemeData[votraxsc01_locals.actPhoneme].iLength[votraxsc01_locals.actIntonation];
}
}
samplesToCopy = (length<=votraxsc01_locals.iRemainingSamples)?length:votraxsc01_locals.iRemainingSamples;
for(i = 0; i < samplesToCopy; ++i)
buffer_f[i] = (float)votraxsc01_locals.pActPos[i] * (float)(1./32768.);
buffer_f += samplesToCopy;
votraxsc01_locals.pActPos += samplesToCopy;
votraxsc01_locals.iRemainingSamples -= samplesToCopy;
length -= samplesToCopy;
}
else {
samplesToCopy = (length<=votraxsc01_locals.iSamplesInBuffer)?length:votraxsc01_locals.iSamplesInBuffer;
for(i = 0; i < samplesToCopy; ++i)
buffer_f[i] = (float)votraxsc01_locals.pBufferPos[i] * (float)(1./32768.);
buffer_f += samplesToCopy;
votraxsc01_locals.pBufferPos += samplesToCopy;
votraxsc01_locals.iSamplesInBuffer -= samplesToCopy;
length -= samplesToCopy;
}
}
#endif
#endif
}
#if !defined(OLD_VOTRAX) && !defined(REAL_DEVICE)
static void VOTRAXSC01_sh_start_timeout(int which)
{
#ifdef REAL_DEVICE
int help;
if ( !votraxsc01_locals.strobe ) {
votraxsc01_locals.strobe = 0x01;
DlPortWritePortUshort(_ctrlOutAdr, votraxsc01_locals.strobe);
}
help = get_busy();
if ( votraxsc01_locals.busy!=help ) {
votraxsc01_locals.busy = help;
if ( votraxsc01_locals.intf->BusyCallback[0] )
(*votraxsc01_locals.intf->BusyCallback[0])(votraxsc01_locals.busy);
}
#endif
#ifndef OLD_VOTRAX
stream_update(votraxsc01_locals.stream, 0);
switch (which) {
case T_COMMIT_PHONE:
// strobe -> commit transition,
phone_commit();
timer_adjust(votraxsc01_locals.timer, (double)(16 * (votraxsc01_locals.rom_duration * 4u + 1) * 4 * 9 + 2)/(double)votraxsc01_locals.mainclock/*attotime::from_ticks(16 * (votraxsc01_locals.rom_duration * 4 + 1) * 4 * 9 + 2, votraxsc01_locals.mainclock)*/, T_END_OF_PHONE, TIME_NEVER);
break;
case T_END_OF_PHONE:
// end of phone
votraxsc01_locals.ar_state = ASSERT_LINE;
break;
}
//!! m_ar_cb(votraxsc01_locals.ar_state);
if (votraxsc01_locals.intf->BusyCallback[0])
(*votraxsc01_locals.intf->BusyCallback[0])(!votraxsc01_locals.ar_state); //!! inverted behavior from MAME
#endif
}
#endif
int VOTRAXSC01_sh_start(const struct MachineSound *msound)
{
#if defined(OLD_VOTRAX) && !defined(REAL_DEVICE)
static char s[32];
int i;
#endif
memset(&votraxsc01_locals, 0x00, sizeof(votraxsc01_locals));
votraxsc01_locals.intf = msound->sound_interface;
#if !defined(OLD_VOTRAX) && !defined(REAL_DEVICE)
// initialize internal state
votraxsc01_locals.mainclock = votraxsc01_locals.intf->baseFrequency[0]; //!! clock();
votraxsc01_locals.sclock = votraxsc01_locals.mainclock / 18.0;
votraxsc01_locals.cclock = votraxsc01_locals.mainclock / 36.0;
votraxsc01_locals.stream = stream_init_float("Votrax - SC01", votraxsc01_locals.intf->mixing_level[0], votraxsc01_locals.sclock, 0, Votrax_Update, 1);
votraxsc01_locals.timer = timer_alloc(VOTRAXSC01_sh_start_timeout);
// reset outputs
//!! m_ar_cb.resolve_safe();
votraxsc01_locals.ar_state = ASSERT_LINE;
//!! was the separate reset code from here on:
// Technically, there's no reset in this chip, and initial state
// is random. Still, it's a good idea to start it with something
// sane.
votraxsc01_locals.phone = 0x3f;
votraxsc01_locals.inflection = 0;
votraxsc01_locals.ar_state = ASSERT_LINE;
//!! m_ar_cb(votraxsc01_locals.ar_state);
votraxsc01_locals.sample_count = 0;
// Initialize the m_rom* values
phone_commit();
// Clear the interpolation sram
votraxsc01_locals.cur_fa = votraxsc01_locals.cur_fc = votraxsc01_locals.cur_va = 0;
votraxsc01_locals.cur_f1 = votraxsc01_locals.cur_f2 = votraxsc01_locals.cur_f2q = votraxsc01_locals.cur_f3 = 0;
// Initialize the m_filt* values and the filter coefficients
filters_commit(1);
// Clear the rest of the internal digital state
votraxsc01_locals.pitch = 0;
votraxsc01_locals.closure = 0;
votraxsc01_locals.update_counter = 0;
votraxsc01_locals.cur_closure = 1;
votraxsc01_locals.noise = 0;
votraxsc01_locals.cur_noise = 0;
#else
votraxsc01_locals.baseFrequency = votraxsc01_locals.intf->baseFrequency[0];
if ( votraxsc01_locals.baseFrequency<=0 )
votraxsc01_locals.baseFrequency = 8000;
// votraxsc01_locals.busy = -1;
// votraxsc01_locals.baseFrequency = 8000;
votraxsc01_locals.actPhoneme = 0x3f;
#ifndef REAL_DEVICE
// votraxsc01_locals.pActPos = PhonemeData[votraxsc01_locals.actPhoneme].lpStart;
// votraxsc01_locals.iRemainingSamples = PhonemeData[votraxsc01_locals.actPhoneme].iLength;
// votraxsc01_locals.timer = timer_alloc(VOTRAXSC01_sh_start_timeout);
// timer_adjust(votraxsc01_locals.timer, PhonemeLengths[votraxsc01_locals.actPhoneme]/1000.0, 0, 0);
// timer_enable(votraxsc01_locals.timer,0);
PrepareVoiceData(votraxsc01_locals.actPhoneme, votraxsc01_locals.actIntonation);
for (i=0; i<=3; i++) {
sprintf(s, "Votrax-SC01 #%d Int %d", 0, i);
votraxsc01_locals.channels[i] = stream_init(s, votraxsc01_locals.intf->mixing_level[0], sample_rate[i], i, Votrax_Update);
// set_RC_filter(votraxsc01_locals.channels[i], 270000, 15000, 0, 10000); // if reactivated, replace with filter.c
}
// if ( votraxsc01_locals.intf->BusyCallback[0] )
// (*votraxsc01_locals.intf->BusyCallback[0])(votraxsc01_locals.busy);
#else
DlPortWritePortUshort(_dataOutAdr, 0x3f);
votraxsc01_locals.strobe = 0x00;
DlPortWritePortUshort(_ctrlOutAdr, votraxsc01_locals.strobe);
votraxsc01_locals.timer = timer_alloc(VOTRAXSC01_sh_start_timeout);
timer_adjust(votraxsc01_locals.timer, 0, 0, 0.00001);
timer_enable(votraxsc01_locals.timer, 1);
#endif
#endif
return 0;
}
void VOTRAXSC01_sh_stop(void)
{
if ( votraxsc01_locals.timer )
timer_remove(votraxsc01_locals.timer);
votraxsc01_locals.timer = 0;
#ifdef OLD_VOTRAX
if (votraxsc01_locals.lpBuffer) {
free(votraxsc01_locals.lpBuffer);
votraxsc01_locals.lpBuffer = NULL;
}
#endif
#ifdef REAL_DEVICE
DlPortWritePortUshort(_ctrlOutAdr, 0x01);
#endif
}
| 35.211124 | 429 | 0.650604 | [
"shape",
"transform"
] |
3a0758703f05329db0a39cae1fec78efeb2061ca | 2,951 | h | C | src/qpid/broker/SelectorToken.h | irinabov/debian-qpid-cpp-1.35.0 | 98b0597071c0a5f0cc407a35d5a4690d9189065e | [
"Apache-2.0"
] | 1 | 2017-11-29T09:19:02.000Z | 2017-11-29T09:19:02.000Z | src/qpid/broker/SelectorToken.h | irinabov/debian-qpid-cpp-1.35.0 | 98b0597071c0a5f0cc407a35d5a4690d9189065e | [
"Apache-2.0"
] | null | null | null | src/qpid/broker/SelectorToken.h | irinabov/debian-qpid-cpp-1.35.0 | 98b0597071c0a5f0cc407a35d5a4690d9189065e | [
"Apache-2.0"
] | null | null | null | #ifndef QPID_BROKER_SELECTORTOKEN_H
#define QPID_BROKER_SELECTORTOKEN_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.
*
*/
#include "qpid/broker/BrokerImportExport.h"
#include <iosfwd>
#include <string>
#include <stdexcept>
#include <vector>
namespace qpid {
namespace broker {
typedef enum {
T_EOS,
T_NULL,
T_TRUE,
T_FALSE,
T_NOT,
T_AND,
T_OR,
T_IN,
T_IS,
T_BETWEEN,
T_LIKE,
T_ESCAPE,
T_IDENTIFIER,
T_STRING,
T_NUMERIC_EXACT,
T_NUMERIC_APPROX,
T_LPAREN,
T_RPAREN,
T_COMMA,
T_PLUS,
T_MINUS,
T_MULT,
T_DIV,
T_EQUAL,
T_NEQ,
T_LESS,
T_GRT,
T_LSEQ,
T_GREQ
} TokenType;
struct Token {
TokenType type;
std::string val;
std::string::const_iterator tokenStart;
Token() :
type(T_EOS)
{}
Token(TokenType t, const std::string& v) :
type(t),
val(v)
{}
Token(TokenType t, const std::string::const_iterator& s, const std::string& v) :
type(t),
val(v),
tokenStart(s)
{}
Token(TokenType t, const std::string::const_iterator& s, const std::string::const_iterator& e) :
type(t),
val(std::string(s,e)),
tokenStart(s)
{}
bool operator==(const Token& r) const
{
return
(type == T_EOS && r.type == T_EOS) ||
(type == r.type && val == r.val);
}
};
QPID_BROKER_EXTERN std::ostream& operator<<(std::ostream& os, const Token& t);
class TokenException : public std::range_error {
public:
TokenException(const std::string&);
};
QPID_BROKER_EXTERN bool tokenise(std::string::const_iterator& s, std::string::const_iterator& e, Token& tok);
class Tokeniser {
std::vector<Token> tokens;
unsigned int tokp;
std::string::const_iterator inStart;
std::string::const_iterator inp;
std::string::const_iterator inEnd;
public:
QPID_BROKER_EXTERN Tokeniser(const std::string::const_iterator& s, const std::string::const_iterator& e);
QPID_BROKER_EXTERN void returnTokens(unsigned int n = 1);
QPID_BROKER_EXTERN const Token& nextToken();
QPID_BROKER_EXTERN std::string remaining();
};
}}
#endif
| 23.054688 | 109 | 0.662148 | [
"vector"
] |
3a107dbd4dae9bc85ffe3bb389484ae383f36097 | 6,071 | h | C | HAL/Camera/Drivers/Epiphan/SDK/slib/include/s_lib.h | vhanded/HAL | 56819df45a1d3edf118282b644449c9d1e395286 | [
"Apache-2.0"
] | 34 | 2015-07-19T06:34:09.000Z | 2022-03-15T13:34:38.000Z | HAL/Camera/Drivers/Epiphan/SDK/slib/include/s_lib.h | vhanded/HAL | 56819df45a1d3edf118282b644449c9d1e395286 | [
"Apache-2.0"
] | 43 | 2015-02-08T17:06:28.000Z | 2020-06-09T15:22:16.000Z | HAL/Camera/Drivers/Epiphan/SDK/slib/include/s_lib.h | vhanded/HAL | 56819df45a1d3edf118282b644449c9d1e395286 | [
"Apache-2.0"
] | 36 | 2015-04-18T15:41:49.000Z | 2021-05-28T15:55:28.000Z | /*
* $Id: s_lib.h,v 1.26 2009/11/17 00:14:24 slava Exp $
*
* Copyright (C) 2000-2009 by Slava Monich
*
* 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 ``AS IS'' AND ANY EXPRESSED 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 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) ARISING
* IN ANY WAY OUT OF THE USE OR INABILITY TO USE THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation
* are those of the authors and should not be interpreted as representing
* any official policies, either expressed or implied.
*/
#ifndef _SLAVA_LIB_H_
#define _SLAVA_LIB_H_
#include "s_base32.h"
#include "s_base64.h"
#include "s_bitset.h"
#include "s_buf.h"
#include "s_cs.h"
#include "s_dom.h"
#include "s_event.h"
#include "s_file.h"
#include "s_futil.h"
#include "s_hash.h"
#include "s_hist.h"
#include "s_itr.h"
#include "s_lib.h"
#include "s_lock.h"
#include "s_math.h"
#include "s_md.h"
#include "s_mem.h"
#include "s_mutex.h"
#include "s_opt.h"
#include "s_prop.h"
#include "s_queue.h"
#include "s_random.h"
#include "s_ring.h"
#include "s_rwlock.h"
#include "s_stack.h"
#include "s_strbuf.h"
#include "s_thread.h"
#include "s_util.h"
#include "s_vector.h"
#include "s_ver.h"
#include "s_wkq.h"
#include "s_xml.h"
#ifdef __cplusplus
extern "C" {
#endif /* __cplusplus */
/*
* SLIB_InitModules() and SLIB_Init() do the same thing, the only
* difference is that Win32 version of SLIB_Init() initializes
* Winsock, while SLIB_InitModules() does not. On any other platform
* these two functions are absolutely equivalent.
*/
extern void SLIB_Init P_((void));
extern void SLIB_InitModules P_((void));
extern void SLIB_Shutdown P_((void));
#ifdef __cplusplus
} /* end of extern "C" */
#endif /* __cplusplus */
#endif /* _SLAVA_LIB_H_ */
/*
* HISTORY:
*
* $Log: s_lib.h,v $
* Revision 1.26 2009/11/17 00:14:24 slava
* o introducing generic synchronization API. This is a pretty destructive
* checkin, it's not 100% backward compatible. The Lock type is now a
* generic lock. What used to be called Lock is now RWLock. Sorry.
*
* Revision 1.25 2008/09/03 09:24:35 slava
* o added ring buffer object
*
* Revision 1.24 2006/10/20 04:56:44 slava
* o cleanup. moved file related utilities (most if not all of them implemented
* in s_futil.c) into a separate header file, s_futil.h. This may break
* compilation of the sources that include individual slib header files
* instead of including s_lib.h
*
* Revision 1.23 2004/08/18 02:52:01 slava
* o added support for BASE32 encoding
*
* Revision 1.22 2004/07/29 17:09:37 slava
* o message digest framework
*
* Revision 1.21 2004/07/19 22:55:11 slava
* o moved BASE64 encoding functions from s_util to s_base64 module
*
* Revision 1.20 2004/03/25 04:01:51 slava
* o added SLIB_VERSION macro
*
* Revision 1.19 2003/12/04 04:48:55 slava
* o replaced _LINUX_KERNEL_ with _LINUX_KERNEL for consistency with other
* platform defines such as _UNIX, _WIN32, _NT_KERNEL etc.
*
* Revision 1.18 2003/11/30 02:49:57 slava
* o port to Linux kernel mode environment
*
* Revision 1.17 2003/11/08 20:47:43 slava
* o added iterators
*
* Revision 1.16 2003/05/21 17:36:34 slava
* o added extern "C" block for C++ compilers
*
* Revision 1.15 2003/05/21 00:17:25 slava
* o include s_mem.h
*
* Revision 1.14 2003/01/29 07:33:20 slava
* o include s_dom.h
*
* Revision 1.13 2002/08/12 05:13:27 slava
* o use (void) rather than () to declare functions that have
* no arguments. The problem with () is that compilers interpret
* it as an *unspecified* argument list, but (void) clearly
* indicates that function takes no arguments. Improves compile
* time error checking
*
* Revision 1.12 2002/05/29 06:49:42 slava
* o parser for command line options
*
* Revision 1.11 2002/05/22 04:24:42 slava
* o include s_strbuf.h
*
* Revision 1.10 2001/12/28 00:41:16 slava
* o added BitSet functions
*
* Revision 1.9 2001/11/27 06:06:58 slava
* o added "work queue" module
*
* Revision 1.8 2001/11/26 07:59:55 slava
* o added s_math module
*
* Revision 1.7 2001/11/25 01:29:02 slava
* o added SLIB_Init(), SLIB_InitModules() and SLIB_Shutdown() functions
*
* Revision 1.6 2001/10/08 08:25:36 slava
* o support for parsing XML files
*
* Revision 1.5 2001/05/30 04:42:13 slava
* o from now on this code is distributed under BSD-style license which
* permits unlimited redistribution and use in source and binary forms
*
* Revision 1.4 2001/01/12 06:52:53 slava
* o support for histogramming
*
* Revision 1.3 2001/01/03 09:18:23 slava
* o new file I/O support for transparent access to plain or compressed
* files, sockets, etc.
*
* Revision 1.2 2000/12/31 02:55:47 oleg
* o added Stack to slib
*
* Revision 1.1 2000/08/19 04:48:58 slava
* o initial checkin
*
* Local Variables:
* mode: C
* c-basic-offset: 4
* indent-tabs-mode: nil
* End:
*/
| 32.292553 | 80 | 0.686543 | [
"object"
] |
3a12b1e018d8552b53650fef108e6f41b3a48c80 | 3,235 | h | C | inc/C_H/errno.h | FlashSoft/GPSTracker | d5135c6b11c0ae022b212d4517cc18c33a038bc4 | [
"BSD-2-Clause"
] | 3 | 2020-11-03T03:43:41.000Z | 2022-03-18T07:38:47.000Z | inc/C_H/errno.h | copslock/RecorderGPSTracker | fc2c1f72327a1b7d8483427f588eaeca7985a6c7 | [
"BSD-2-Clause"
] | null | null | null | inc/C_H/errno.h | copslock/RecorderGPSTracker | fc2c1f72327a1b7d8483427f588eaeca7985a6c7 | [
"BSD-2-Clause"
] | 5 | 2020-10-04T14:59:29.000Z | 2022-03-22T16:31:31.000Z | /* errno.h: ANSI 'C' (X3J11 Oct 88) library header, section 4.1.3 */
/* Copyright (C) Codemist Ltd., 1988 */
/* Copyright 1991 ARM Limited. All rights reserved. */
/* version 1 */
/*
* RCS $Revision: 1.11.2.1 $
* Checkin $Date: 2001/02/22 16:23:35 $
* Revising $Author: cadeniyi $
*/
#ifndef __errno_h
#define __errno_h
#ifndef __ERRNO_DECLS
#define __ERRNO_DECLS
#undef __CLIBNS
#ifdef __cplusplus
#ifdef __EDG_RUNTIME_USES_NAMESPACES
namespace std {
#define __CLIBNS std::
#else
#define __CLIBNS ::
#endif /* ifdef __EDG_RUNTIME_USES_NAMESPACES */
extern "C" {
#else
#define __CLIBNS
#endif /* __cplusplus */
extern __pure volatile int *__rt_errno_addr(void);
#ifdef __cplusplus
} /* extern "C" */
#endif
#ifdef __EDG_RUNTIME_USES_NAMESPACES
} /* namespace std */
#endif
#endif /* __ERRNO_DECLS */
#ifdef __EDG_RUNTIME_USES_NAMESPACES
#ifndef __ERRNO_NO_EXPORTS
using std::__rt_errno_addr;
#endif
#endif
#define errno (*__CLIBNS __rt_errno_addr())
/*
* expands to a modifiable lvalue that has type volatile int, the value of
* which is set to a positive error code by several library functions. It is
* initialised to zero at program startup, but is never set to zero by any
* library function. The value of errno may be set to nonzero by a library
* function call whether or not there is an error, provided the use of errno
* is not documented in the description of the function in the Standard.
*/
#define EDOM 1
/*
* if a domain error occurs (an input argument is outside the
* domain over which the mathematical function is defined) the
* integer expression errno acquires the value of the macro EDOM
* and HUGE_VAL is returned. EDOM may be used by non-mathematical
* functions.
*/
#define ERANGE 2
/*
* a range error occurs if the result of a function can not be
* represented as a double value. If the result overflows (the
* magnitude of the result is so large that it cannot be
* represented in an object of the specified type), the function
* returns the value of the macro HUGE_VAL, with the same sign as
* the correct value of the function; the integer expression errno
* acquires the value of the macro ERANGE. If the result underflows
* (the magnitude of the result is so small that it cannot be
* represented in an object of the specified type), the function
* returns zero; the integer expression errno acquires the value of
* the macro ERANGE. ERANGE may be used by non-mathematical
* functions.
*/
#define ESIGNUM 3
/*
* ESIGNUM is generated by signal() if the user attempts to change
* the handling of a nonexistent signal. ESIGNUM is not part of the
* ANSI C standard.
*/
#define EILSEQ 4
/*
* EILSEQ is notionally generated by multi-byte character
* processing routines (mbtowc et al), and must be defined for this
* reason. ARM's libraries do not generate it.
*
* EILSEQ is not mentioned in the ANSI C standard itself, but in
* Normative Addendum 1.
*/
#endif
/* end of errno.h */
| 30.809524 | 77 | 0.676662 | [
"object"
] |
3a158c823cb35a46020f7039950b537402b7f41d | 2,127 | h | C | include/commands/CommandGroup.h | NoMod-Programming/PROSIterativeRobot | 6417d328db3de1b901422e99aa82fac0cac7566e | [
"MIT"
] | null | null | null | include/commands/CommandGroup.h | NoMod-Programming/PROSIterativeRobot | 6417d328db3de1b901422e99aa82fac0cac7566e | [
"MIT"
] | null | null | null | include/commands/CommandGroup.h | NoMod-Programming/PROSIterativeRobot | 6417d328db3de1b901422e99aa82fac0cac7566e | [
"MIT"
] | null | null | null | #ifndef _COMMANDS_COMMANDGROUP_H_
#define _COMMANDS_COMMANDGROUP_H_
#include "commands/Command.h"
#include "main.h"
#include <vector>
class CommandGroup : public Command {
private:
std::vector<std::vector<Command*>> commands; // 2d vector keeping track of all commands and command groups. Each vector in the 2d vector represents a sequential step. All the commands and command groups in each sequential step are run in parallel
std::vector<std::vector<Subsystem*>> requirements; // 2d vector storing the requirements of each command and command group
std::vector<std::vector<int>> added; // 2d vector keeping track of which commands and command groups have been added to the event scheduler
size_t sequentialIndex = 0; // Keeps track of the current sequential step the command group is running
public:
std::vector<Subsystem*>& getRequirements(); // Returns a vector containing the subsystem requirements of all of the commands and command groups in the current sequential step
bool canRun(); // Checks if all the commands and command groups in the command group can run
void initialize(); // Set up the command for running
void execute(); // Run the command
bool isFinished(); // Returns whether or not the command group is finished. The execute function is called continuously until this is true or the command group is interrupted
void end(); // Run when command group is finished
void interrupted(); // Run when command group was interrupted
void addSequentialCommand(Command* aCommand); // Adds a command or command group to a new sequential step. Sequential steps are run in the order they are added
void addParallelCommand(Command* aCommand); // Adds a command or command group to be run in parallel with the commands and command groups in the current sequential steps
void run(); // Runs this command group. May be called anywhere.
void stop(); // Stops this command group while it is running. May be called anywhere.
// ...and finally, the constructor!
CommandGroup();
};
#endif // _COMMANDS_COMMANDGROUP_H_
| 62.558824 | 251 | 0.74236 | [
"vector"
] |
3a16c6445ffdddbc0e745b78a75fa65890c39884 | 1,392 | h | C | jcc/_jcc3/java/lang/Short.h | IreneZhou0129/PyLucene-assignment | 70916f1c8451c5dce5c5205915b25f214ffed2e4 | [
"Apache-2.0"
] | null | null | null | jcc/_jcc3/java/lang/Short.h | IreneZhou0129/PyLucene-assignment | 70916f1c8451c5dce5c5205915b25f214ffed2e4 | [
"Apache-2.0"
] | null | null | null | jcc/_jcc3/java/lang/Short.h | IreneZhou0129/PyLucene-assignment | 70916f1c8451c5dce5c5205915b25f214ffed2e4 | [
"Apache-2.0"
] | null | null | null | /*
* 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 _Short_H
#define _Short_H
#include <Python.h>
#include "java/lang/Object.h"
#include "java/lang/Class.h"
namespace java {
namespace lang {
class Short : public Object {
public:
static Class *class$;
static jmethodID *_mids;
static jclass initializeClass(bool);
explicit Short(jobject obj) : Object(obj) {
initializeClass(false);
}
Short(jshort);
jshort shortValue() const;
};
DECLARE_TYPE(Short);
class t_Short {
public:
PyObject_HEAD
Short object;
static PyObject *wrap_Object(const Short& object);
static PyObject *wrap_jobject(const jobject& object);
};
}
}
#endif /* _Short_H */
| 26.769231 | 77 | 0.619971 | [
"object"
] |
3a1ad575ed609d497a7e20738787d64b9fe737ba | 22,583 | h | C | source/file/min/md5_anim.h | Aaron-SP/mgl | cb2555c4d4149b02ec40dd9c057336345a09df99 | [
"Apache-2.0"
] | 36 | 2018-05-11T22:59:10.000Z | 2021-04-09T00:13:10.000Z | source/file/min/md5_anim.h | Aaron-SP/mgl | cb2555c4d4149b02ec40dd9c057336345a09df99 | [
"Apache-2.0"
] | 3 | 2018-05-08T00:42:55.000Z | 2018-07-10T16:14:28.000Z | source/file/min/md5_anim.h | Aaron-SP/mgl | cb2555c4d4149b02ec40dd9c057336345a09df99 | [
"Apache-2.0"
] | 2 | 2018-06-21T13:17:43.000Z | 2018-07-10T15:30:00.000Z | /* Copyright [2013-2018] [Aaron Springstroh, Minimal Graphics Library]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef _MGL_MD5_ANIM_MGL_
#define _MGL_MD5_ANIM_MGL_
#include <fstream>
#include <min/aabbox.h>
#include <min/mat4.h>
#include <min/mem_chunk.h>
#include <min/quat.h>
#include <min/strtoken.h>
#include <min/vec3.h>
#include <sstream>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
// A node is the same thing as a joint
// A transform is a base frame
// An animated node is an animated joint
// A bound is stored into an aabb
namespace min
{
class md5_node
{
private:
std::string _name;
int _parent;
int _flag;
unsigned _start;
public:
md5_node(const std::string &name, const int parent, const int flag, const unsigned start)
: _name(name), _parent(parent), _flag(flag), _start(start) {}
inline const std::string &get_name() const
{
return _name;
}
inline int get_parent() const
{
return _parent;
}
inline int get_flag() const
{
return _flag;
}
inline unsigned get_start() const
{
return _start;
}
};
template <typename T>
class md5_transform
{
private:
vec3<T> _position;
quat<T> _rotation;
public:
md5_transform(const vec3<T> &t, const quat<T> &r)
: _position(t), _rotation(r)
{
_rotation.calculate_w();
}
inline const vec3<T> &get_position() const
{
return _position;
}
inline const quat<T> &get_rotation() const
{
return _rotation;
}
};
template <class T>
class md5_animated_node
{
private:
vec3<T> _position;
quat<T> _rotation;
int _parent;
public:
md5_animated_node(const md5_transform<T> ©, const int parent)
: _position(copy.get_position()), _rotation(copy.get_rotation()), _parent(parent) {}
inline int get_parent() const
{
return _parent;
}
inline vec3<T> &get_position()
{
return _position;
}
inline const vec3<T> &get_position() const
{
return _position;
}
inline quat<T> &get_rotation()
{
return _rotation;
}
inline const quat<T> &get_rotation() const
{
return _rotation;
}
};
template <typename T>
class md5_frame_data
{
private:
std::vector<T> _data;
unsigned _id;
public:
md5_frame_data(const unsigned id)
: _id(id) {}
inline void add(const T data)
{
_data.push_back(data);
}
inline const std::vector<T> &get_data() const
{
return _data;
}
inline void reserve(size_t n)
{
_data.reserve(n);
}
};
template <class T>
class md5_frame
{
private:
std::vector<mat4<T>> _bones;
std::vector<md5_animated_node<T>> _nodes;
public:
inline void add_node(const md5_animated_node<T> &node, const mat4<T> &bone)
{
_nodes.push_back(node);
_bones.push_back(bone);
}
inline const md5_animated_node<T> &get_node(const int parent_id) const
{
return _nodes[parent_id];
}
inline const std::vector<mat4<T>> &get_bones() const
{
return _bones;
}
inline void reserve(size_t n)
{
_bones.reserve(n);
_nodes.reserve(n);
}
};
template <typename T>
class md5_anim
{
private:
std::vector<md5_node> _nodes;
std::vector<aabbox<T, vec3>> _bounds;
std::vector<md5_transform<T>> _transforms;
std::vector<md5_frame_data<T>> _frame_data;
std::vector<md5_frame<T>> _frames;
mutable std::vector<mat4<T>> _current_frame;
T _animation_length;
mutable T _time;
unsigned _frame_rate;
mutable unsigned _loops;
inline void load_file(const std::string &_file)
{
std::ifstream file(_file, std::ios::in | std::ios::binary | std::ios::ate);
if (file.is_open())
{
// Get the size of the file
const size_t size = static_cast<size_t>(file.tellg());
// Adjust file pointer to beginning
file.seekg(0, std::ios::beg);
// Allocate space for new file
std::string data(size, 0);
// Read bytes and close the file
file.read(&data[0], size);
// Close the file
file.close();
// Process the DDS file
load(data);
}
else
{
throw std::runtime_error("md5_anim: Could not load file '" + _file + "'");
}
}
inline void load(const std::string &data)
{
// Get locations of all lines in string buffer
const auto lines = min::read_lines(data);
// Read line by line
unsigned frames, nodes, components;
frames = nodes = components = 0;
// Allocate field buffer
std::string field;
field.reserve(16);
const size_t size = lines.size();
for (size_t i = 0; i < size; i++)
{
// read line and trim the line whitespace
const auto &position = lines[i];
std::string line = data.substr(position.first, position.second);
min::trim(line);
// skip empty line size in bytes
if (line.size() == 0)
{
continue;
}
// Read the property of this line
field.clear();
std::istringstream s(line);
s >> field;
// Execute action based on property
if (min::to_lower(field).compare("md5version") == 0)
{
// Parse the version number and check against target
int version;
s >> version;
// Expected version 10
if (version != 10)
{
throw std::runtime_error("md5_anim: Version number unsupported, got '" + std::to_string(version) + "' expected '10'");
}
}
else if (min::to_lower(field).compare("commandline") == 0)
{
// Skip these command parameters, as they are unused
continue;
}
else if (min::to_lower(field).compare("numframes") == 0)
{
s >> frames;
}
else if (min::to_lower(field).compare("numjoints") == 0)
{
s >> nodes;
}
else if (min::to_lower(field).compare("framerate") == 0)
{
s >> _frame_rate;
}
else if (min::to_lower(field).compare("numanimatedcomponents") == 0)
{
s >> components;
}
else if (min::to_lower(field).compare("hierarchy") == 0)
{
// Parse the next 'nodes' lines in the file
const std::vector<std::string> h_lines = min::get_lines(data, lines, nodes, i);
// process the hierarchy data
process_hierarchy(h_lines);
}
else if (min::to_lower(field).compare("bounds") == 0)
{
// Parse the next 'frames' lines in the file
const std::vector<std::string> b_lines = min::get_lines(data, lines, frames, i);
// process the bounds data
process_bounds(b_lines);
}
else if (min::to_lower(field).compare("baseframe") == 0)
{
// Parse the next 'nodes' lines in the file
const std::vector<std::string> bf_lines = min::get_lines(data, lines, nodes, i);
// process the baseframe data
process_baseframe(bf_lines);
}
else if (min::to_lower(field).compare("frame") == 0)
{
// Get the frame ID
unsigned id;
s >> id;
// Parse the next 'nodes' lines in the file
const std::vector<std::string> f_lines = min::get_lines(data, lines, nodes, i);
// process the frame data
process_frame_data(f_lines, id, components);
}
else if (field.compare("}") != 0)
{
// There is another command that we do not know about
throw std::runtime_error("md5_anim: unknown property '" + field + "'");
}
// Check for errors
if (s.fail())
{
throw std::runtime_error("md5_anim: Invalid line in file '" + line + "'");
}
}
}
inline void interpolate_current_frame(const md5_frame<T> &frame0, const md5_frame<T> &frame1, T ratio) const
{
const size_t size = _nodes.size();
for (size_t i = 0; i < size; i++)
{
// lerp interpolation for position
const vec3<T> &from_position = frame0.get_node(i).get_position();
const vec3<T> &to_position = frame1.get_node(i).get_position();
const vec3<T> position = vec3<T>::lerp(from_position, to_position, ratio);
// slerp interpolation for rotation
const quat<T> &from_rotation = frame0.get_node(i).get_rotation();
const quat<T> &to_rotation = frame1.get_node(i).get_rotation();
const quat<T> rotation = quat<T>::slerp(from_rotation, to_rotation, ratio);
// Set the interpolate position and rotation
_current_frame[i] = mat4<T>(position, rotation);
}
}
inline void process_hierarchy(const std::vector<std::string> &lines)
{
if (lines.size() > 0)
{
// Create name buffer
std::string name;
name.reserve(16);
// For all lines
_nodes.reserve(lines.size());
for (const auto &line : lines)
{
// Clear the name buffer
name.clear();
// Local variables
int parent, flag;
unsigned start;
// Parse the items on the line
std::istringstream s(line);
s >> name;
s >> parent;
s >> flag;
s >> start;
// Remove quotes from string name
name.erase(std::remove(name.begin(), name.end(), '\"'), name.end());
// Add the node to the hierarchy
_nodes.emplace_back(name, parent, flag, start);
// Check for errors
if (s.fail())
{
throw std::runtime_error("md5_anim: invalid hierarchy line: '" + line + "'");
}
}
}
else
{
throw std::runtime_error("md5_anim: no md5_nodes specified in animation file");
}
}
inline void process_bounds(const std::vector<std::string> &lines)
{
if (lines.size() > 0)
{
// Create junk buffer
std::string junk;
junk.reserve(16);
// For all lines
_bounds.reserve(lines.size());
for (const auto &line : lines)
{
// Clear the junk buffer
junk.clear();
// Local variables
T minx, miny, minz;
T maxx, maxy, maxz;
// Parse the items on the line
std::istringstream s(line);
// Skip the '('
s >> junk;
// Read the min bounds
s >> minx;
s >> miny;
s >> minz;
// Skip the ')' and '('
s >> junk;
s >> junk;
// Read the max bounds
s >> maxx;
s >> maxy;
s >> maxz;
// Add the bound to the bounds list
_bounds.emplace_back(vec3<T>(minx, miny, minz), vec3<T>(maxx, maxy, maxz));
// Check for errors
if (s.fail())
{
throw std::runtime_error("md5_anim: invalid bound line: '" + line + "'");
}
}
}
else
{
throw std::runtime_error("md5_anim: no bounds specified in animation file");
}
}
inline void process_baseframe(const std::vector<std::string> &lines)
{
if (lines.size() > 0)
{
// Create junk buffer
std::string junk;
junk.reserve(16);
// For all lines
_transforms.reserve(lines.size());
for (const auto &line : lines)
{
// Clear the junk buffer
junk.clear();
// Local variables
T x, y, z;
T qx, qy, qz;
// Parse the items on the line
std::istringstream s(line);
// Skip the '('
s >> junk;
// Read the translation
s >> x;
s >> y;
s >> z;
// Skip the ')' and '('
s >> junk;
s >> junk;
// Read the rotation
s >> qx;
s >> qy;
s >> qz;
// Add the transform to the base frame transform buffer, we are not normalizing here!
_transforms.emplace_back(vec3<T>(x, y, z), quat<T>(0.0, qx, qy, qz));
// Check for errors
if (s.fail())
{
throw std::runtime_error("md5_anim: invalid baseframe line: '" + line + "'");
}
}
}
else
{
throw std::runtime_error("md5_anim: no baseframe transforms specified in animation file");
}
}
inline void process_frame_data(const std::vector<std::string> &lines, const unsigned frame_id, const unsigned components)
{
if (lines.size() > 0)
{
// Check that the number of components divides evenly, and the ratio is 6
if (components % lines.size() != 0 && components / lines.size() == 6)
{
throw std::runtime_error("md5_anim: unexpected component count");
}
// Create the frame for this id and reserve space
md5_frame_data<T> frame_data(frame_id);
frame_data.reserve(components);
unsigned count = 0;
for (const auto &line : lines)
{
std::istringstream s(line);
T data;
// Read all of the components on this line
for (size_t i = 0; i < 6; i++)
{
s >> data;
frame_data.add(data);
count++;
}
// Check for errors
if (s.fail())
{
throw std::runtime_error("md5_anim: invalid frame_data line: '" + line + "'");
}
}
// Check that the component count matches expected
if (count != components)
{
throw std::runtime_error("md5_anim: invalid frame component count, expected '" + std::to_string(components) + "' got '" + std::to_string(count));
}
// Add this frame to the frame list
_frame_data.push_back(frame_data);
// Create a frame from the frame data
process_frame(frame_data);
}
else
{
throw std::runtime_error("md5_anim: no frame data specified in animation file");
}
}
inline void process_frame(const md5_frame_data<T> &frame_data)
{
if (_nodes.size() != _transforms.size())
{
throw std::runtime_error("md5_anim: node-transform mismatch");
}
// Create frame from input data and reserve space
md5_frame<T> frame;
frame.reserve(_nodes.size());
// Transform all the nodes in the hierarchy
const size_t size = _nodes.size();
for (size_t i = 0; i < size; i++)
{
const md5_node &node = _nodes[i];
const md5_transform<T> &transform = _transforms[i];
const std::vector<T> &data = frame_data.get_data();
// Transform the node, down the parent tree
md5_animated_node<T> child(transform, node.get_parent());
size_t j = 0;
const int flag = node.get_flag();
// Check for start overflow
const unsigned start = node.get_start();
if (start >= data.size())
{
throw std::runtime_error("md5_anim: frame data overflow");
}
// Set the position for this frame
vec3<T> &position = child.get_position();
if (flag & 1)
{
position.x(data[start + j++]);
}
if (flag & 2)
{
position.y(data[start + j++]);
}
if (flag & 4)
{
position.z(data[start + j++]);
}
// Set the animated rotation
quat<T> &rotation = child.get_rotation();
if (flag & 8)
{
rotation.x(data[start + j++]);
}
if (flag & 16)
{
rotation.y(data[start + j++]);
}
if (flag & 32)
{
rotation.z(data[start + j++]);
}
// Calculate W since we changed components, this normalizes the quaternion
// We need to negate rotation angle here since we use left-handed coordinates
rotation = rotation.conjugate();
rotation.calculate_w();
// If this node has a parent and is valid
const int parent = child.get_parent();
if (parent >= (int)size)
{
throw std::runtime_error("md5_anim: parent overflow '" + std::to_string(parent) + " is greater than '" + std::to_string(size) + "'");
}
else if (parent >= 0)
{
// Transform the child position based off parent rotation
const md5_animated_node<T> &parent_node = frame.get_node(parent);
const vec3<T> rotated = parent_node.get_rotation().transform(position);
// Translate position by parent position
position = parent_node.get_position() + rotated;
// Rotate rotation by parent rotation
rotation = parent_node.get_rotation() * rotation;
}
// Create matrix bone for this node
const mat4<T> bone(position, rotation);
// Add this node to the frame
frame.add_node(child, bone);
}
// Add this frame to the frame list
_frames.push_back(frame);
}
public:
md5_anim(const std::string &file) : _time(0.0), _frame_rate(0), _loops(0)
{
load_file(file);
// Set the length of the animation
_animation_length = static_cast<T>(_frames.size()) / _frame_rate;
if (_frames.size() == 0)
{
throw std::runtime_error("md5_anim: no frames in animation");
}
// Set the current frame
_current_frame = _frames[0].get_bones();
}
md5_anim(const mem_file &mem) : _time(0.0), _frame_rate(0), _loops(0)
{
load(mem.to_string());
// Set the length of the animation
_animation_length = static_cast<T>(_frames.size()) / _frame_rate;
if (_frames.size() == 0)
{
throw std::runtime_error("md5_anim: no frames in animation");
}
// Set the current frame
_current_frame = _frames[0].get_bones();
}
inline const std::vector<aabbox<T, vec3>> &get_bounds() const
{
return _bounds;
}
inline const std::vector<mat4<T>> &get_current_frame() const
{
return _current_frame;
}
inline unsigned get_frame_rate() const
{
return _frame_rate;
}
inline const std::vector<md5_frame_data<T>> &get_frame_data() const
{
return _frame_data;
}
inline const std::vector<md5_frame<T>> &get_frames() const
{
return _frames;
}
inline const std::vector<md5_node> &get_nodes() const
{
return _nodes;
}
inline const std::vector<md5_transform<T>> &get_transforms() const
{
return _transforms;
}
inline unsigned get_loop_count() const
{
return _loops;
}
inline void set_loop_count(const unsigned count) const
{
// Reset loop count
_loops = count;
}
inline void set_time(const T time) const
{
// Reset the animation time
_time = time;
}
inline void step(const T step) const
{
// Accumulate the time
_time += step;
// If time exceeds the animation length, loop
if (_time >= _animation_length && _loops > 0)
{
// Decriment loop count
_loops--;
// Calculate time in next loop
_time = std::fmod(_time, _animation_length);
}
// If we ran out of loops, exit
if (_loops == 0)
{
return;
}
// Calculate the two frames to interpolate between
const T frame_time = _time * _frame_rate;
const unsigned frame_low = static_cast<unsigned>(std::floor(frame_time));
const unsigned frame_high = frame_low + 1;
// Calculate position between the two frames for interpolation
const T ratio = frame_time - frame_low;
const size_t frames = _frames.size();
const unsigned frame0 = frame_low % frames;
const unsigned frame1 = frame_high % frames;
// Interpolate between the two frames
interpolate_current_frame(_frames[frame0], _frames[frame1], ratio);
}
};
}
#endif
| 29.404948 | 161 | 0.51769 | [
"vector",
"transform"
] |
3a20f75deb84d1c33d3dd2b84d9a8825f1419e41 | 500 | h | C | Sources/Renderer.h | badcast/night-fear-game | efc548a06a6c690b32cff47acfb1906e7dfdaf3c | [
"MIT"
] | null | null | null | Sources/Renderer.h | badcast/night-fear-game | efc548a06a6c690b32cff47acfb1906e7dfdaf3c | [
"MIT"
] | null | null | null | Sources/Renderer.h | badcast/night-fear-game | efc548a06a6c690b32cff47acfb1906e7dfdaf3c | [
"MIT"
] | null | null | null | #pragma once
#include "framework.h"
#include "Component.h"
namespace RoninEngine::Runtime
{
struct Render_info
{
Rect_t src;
Rectf_t dst;
SDL_Renderer* renderer;
Texture* texture;
};
class Renderer : public Component
{
public:
Renderer();
Renderer(const string& name);
Renderer(const Renderer&) = delete;
virtual Vec2 GetSize() = 0;
virtual void Render(Render_info* render_info) = 0;
uint8_t zOrder;
};
}
| 16.666667 | 53 | 0.61 | [
"render"
] |
3a235c993fe62d4b3bf87a21e419313fc540ad7a | 1,399 | c | C | tests/legacy/kernel/test_obj_tracing/nanokernel/src/phil_task.c | garciavb/zephyr | a3db0d1313e9e8609f03abe5d87eb5eaf2f1a15c | [
"Apache-2.0"
] | 2 | 2018-12-12T19:03:07.000Z | 2019-06-29T13:41:34.000Z | tests/legacy/kernel/test_obj_tracing/nanokernel/src/phil_task.c | wingel/zephyr | 012b9d4453caabe7e55af93883792405e57dade4 | [
"Apache-2.0"
] | null | null | null | tests/legacy/kernel/test_obj_tracing/nanokernel/src/phil_task.c | wingel/zephyr | 012b9d4453caabe7e55af93883792405e57dade4 | [
"Apache-2.0"
] | null | null | null | /* phil_task.c - dining philosophers */
/*
* Copyright (c) 2011-2016 Wind River Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <zephyr.h>
#include "phil.h"
#define STSIZE 1024
extern void phil_entry(void);
extern void object_monitor(void);
char __stack phil_stack[N_PHILOSOPHERS][STSIZE];
char __stack mon_stack[STSIZE];
struct nano_sem forks[N_PHILOSOPHERS];
/**
*
* @brief Nanokernel entry point
*
*/
int main(void)
{
int i;
for (i = 0; i < N_PHILOSOPHERS; i++) {
nano_sem_init(&forks[i]);
nano_task_sem_give(&forks[i]);
}
/* create philosopher fibers */
for (i = 0; i < N_PHILOSOPHERS; i++) {
task_fiber_start(&phil_stack[i][0], STSIZE,
(nano_fiber_entry_t) phil_entry, 0, 0, 6, 0);
}
/* create object counter monitor */
task_fiber_start(mon_stack, STSIZE,
(nano_fiber_entry_t) object_monitor, 0, 0, 7, 0);
return 0;
}
| 24.12069 | 75 | 0.706934 | [
"object"
] |
3a254ddebe9e68fb0e68c1e7a0c29efc184bbed5 | 1,831 | h | C | src/steam_event.h | FLSoz/greenworks | bd3fabcc7fcaefaa54f34ba7197e5016af034134 | [
"MIT"
] | null | null | null | src/steam_event.h | FLSoz/greenworks | bd3fabcc7fcaefaa54f34ba7197e5016af034134 | [
"MIT"
] | null | null | null | src/steam_event.h | FLSoz/greenworks | bd3fabcc7fcaefaa54f34ba7197e5016af034134 | [
"MIT"
] | null | null | null | // Copyright (c) 2016 Greenheart Games Pty. Ltd. All rights reserved.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#ifndef SRC_STEAM_EVENT_H_
#define SRC_STEAM_EVENT_H_
#include "nan.h"
#include "steam_client.h"
#include "v8.h"
namespace greenworks {
class SteamEvent : public greenworks::SteamClient::Observer {
public:
explicit SteamEvent(const Nan::Persistent<v8::Object> &persistent_steam_events) : persistent_steam_events_(persistent_steam_events) {}
void OnGameOverlayActivated(bool is_active) override;
void OnSteamServersConnected() override;
void OnSteamServersDisconnected() override;
void OnSteamServerConnectFailure(int status_code) override;
void OnSteamShutdown() override;
void OnPersonaStateChange(uint64 raw_steam_id, int persona_change_flag) override;
void OnAvatarImageLoaded(uint64 raw_steam_id, int image_handle, int height, int width) override;
void OnGameConnectedFriendChatMessage(uint64 raw_steam_id, int message_id) override;
void OnDLCInstalled(AppId_t dlc_app_id) override;
void OnMicroTxnAuthorizationResponse(uint32 AppID, uint64 OrderID, bool Autorized) override;
void OnLobbyCreated(int status_code, uint64 SteamIdLobby);
void OnLobbyDataUpdate(uint64 SteamIdLobby, uint64 SteamIdMember, bool Success);
void OnLobbyEnter(uint64 SteamIdLobby, int ChatPermissions, bool Locked, int ChatRoomEnterResponse);
void OnLobbyInvite(uint64 SteamIdUser, uint64 SteamIdLobby, uint64 GameId);
void OnGameLobbyJoinRequested(uint64 SteamIdLobby, uint64 SteamIdUser);
void OnGameRichPresenceJoinRequested(uint64 steamIDFriend, std::string rgchConnect);
void OnNewUrlLaunchParameters();
private:
const Nan::Persistent<v8::Object> &persistent_steam_events_;
};
} // namespace greenworks
#endif // SRC_STEAM_EVENT_H_
| 42.581395 | 136 | 0.812671 | [
"object"
] |
3a3b6fd6fdfe5ffabb676e79c7e5af6655948ead | 1,368 | h | C | Engine/Source/Editor/UnrealEd/Public/ApexClothingUtils.h | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Editor/UnrealEd/Public/ApexClothingUtils.h | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Editor/UnrealEd/Public/ApexClothingUtils.h | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "EngineDefines.h"
class USkeletalMesh;
namespace nvidia
{
namespace apex
{
class ClothingAsset;
}
}
// Define interface for importing apex clothing asset
namespace ApexClothingUtils
{
UNREALED_API FString PromptForClothingFile();
// Prompt the user to select an APEX file that will be imported to the new UClothingAsset format
UNREALED_API void PromptAndImportClothing(USkeletalMesh* SkelMesh);
// Given a buffer, build an apex clothing asset
UNREALED_API nvidia::apex::ClothingAsset* CreateApexClothingAssetFromBuffer(const uint8* Buffer, int32 BufferSize);
// Functions below remain from previous clothing system and only remain to remove the bound
// data from a skeletal mesh. This is done when postloading USkeletalMesh when upgrading the assets
// Function to restore all clothing section to original mesh section related to specified asset index
UNREALED_API void RemoveAssetFromSkeletalMesh(USkeletalMesh* SkelMesh, uint32 AssetIndex, bool bReleaseAsset = true, bool bRecreateSkelMeshComponent = false);
// Function to restore clothing section to original mesh section
UNREALED_API void RestoreOriginalClothingSection(USkeletalMesh* SkelMesh, uint32 LODIndex, uint32 SectionIndex, bool bReregisterSkelMeshComponent = true);
}
| 36 | 159 | 0.80848 | [
"mesh"
] |
3a438e3cebd0d5b8d36dc1342391f9a912300396 | 1,713 | h | C | src/examples/testbed_control/structs_main.h | amartsop/PixhawkDevel | 85a89ccaf090cf450fc8f4dd9726bdcfb00470c9 | [
"BSD-3-Clause"
] | null | null | null | src/examples/testbed_control/structs_main.h | amartsop/PixhawkDevel | 85a89ccaf090cf450fc8f4dd9726bdcfb00470c9 | [
"BSD-3-Clause"
] | null | null | null | src/examples/testbed_control/structs_main.h | amartsop/PixhawkDevel | 85a89ccaf090cf450fc8f4dd9726bdcfb00470c9 | [
"BSD-3-Clause"
] | null | null | null | #ifndef STRUCTS_MAIN_H
#define STRUCTS_MAIN_H
// Measurements struct
struct measurements_vec_s{
// Translational velocity in body frame
float u; float v; float w;
// Rotational velocity in body frame
float p; float q; float r;
// Euler angles
float phi_; float theta_; float psi_;
// Translational acceleration in body frame
float axb; float ayb; float azb;
// Previous translational velocity in body frame
float up; float vp; float wp;
// Previous rotational velocity in body frame
float pp; float qp; float rp;
// Previous euler angles
float phi_p; float theta_p; float psi_p;
// Previous translational acceleration in body frame
float axb_p; float ayb_p; float azb_p;
// time (ms)
uint64_t t;
// time previous (ms)
uint64_t t_p;
};
// State vector struct
struct state_vec_s{
// Translational velocity
float w;
// Rotational velocity
float q;
// z displacement
float z;
// theta angle
float theta;
};
// Setpoint struct
struct setpoint_vec_s{
// Desired translation velocity
float w;
//Desired rotational velocity
float theta;
};
struct control_vec_s{
// Rotational velocity of the left motor
float wl_t;
// Rotational velocity of the right motor
float wr_t;
};
struct testbed_control_subscription_data_s {
struct battery_status_s bat_status;
struct vehicle_attitude_s att;
struct sensor_bias_s sen_bias;
struct input_rc_s input_rc_signal;
int battery_status_sub;
int sensor_bias_sub;
int att_sub;
int input_rc_sub;
};
struct covariance_mat_s{
// Covariance in w estimation
float w;
// Covariance in q estimation
float q;
// Covariance in z estimation
float z;
// Covariance in theta estimation
float theta;
};
#endif
| 16.471154 | 53 | 0.737303 | [
"vector"
] |
3a48476916800a207c40202901ffeda943184aa9 | 1,673 | h | C | modules/drivers/camera/camera.h | BaiduXLab/apollo | 2764e934b6d0da1342be781447348288ac84c5e9 | [
"Apache-2.0"
] | 3 | 2019-01-30T11:58:40.000Z | 2019-05-22T02:43:03.000Z | modules/drivers/camera/camera.h | BaiduXLab/apollo | 2764e934b6d0da1342be781447348288ac84c5e9 | [
"Apache-2.0"
] | 3 | 2020-02-24T14:19:55.000Z | 2022-02-10T19:49:29.000Z | modules/drivers/camera/camera.h | BaiduXLab/apollo | 2764e934b6d0da1342be781447348288ac84c5e9 | [
"Apache-2.0"
] | 3 | 2019-02-20T00:24:05.000Z | 2022-01-04T05:58:51.000Z | /******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#ifndef MODULES_DRIVERS_CAMERA_CAMERA_H_
#define MODULES_DRIVERS_CAMERA_CAMERA_H_
#include <memory>
#include <string>
#include <thread>
#include <vector>
#include "modules/common/apollo_app.h"
#include "modules/common/util/util.h"
#include "modules/drivers/camera/nodes/camera_nodelet.h"
namespace apollo {
namespace drivers {
namespace camera {
class Camera : public apollo::common::ApolloApp {
public:
Camera() = default;
virtual ~Camera();
std::string Name() const override;
apollo::common::Status Init() override;
apollo::common::Status Start() override;
void Stop() override;
void RunOnce();
void OnTimer(const ros::TimerEvent&);
private:
bool running_ = true;
std::vector<std::shared_ptr<std::thread> > threads_;
CameraNodelet camera_nodelet_;
};
} // namespace camera
} // namespace drivers
} // namespace apollo
#endif // MODULES_DRIVERS_CAMERA_CAMERA_H_
| 29.875 | 79 | 0.674836 | [
"vector"
] |
3a4ca8591c01bdd587513cbf38736bd7c2f4b70b | 40,094 | h | C | Include/xy.h | Gaztin/xy | 39206be8a283445e0527cec648049625acf4f2ef | [
"Zlib"
] | 2 | 2021-10-17T00:41:54.000Z | 2022-03-07T14:59:22.000Z | Include/xy.h | Gaztin/xy | 39206be8a283445e0527cec648049625acf4f2ef | [
"Zlib"
] | null | null | null | Include/xy.h | Gaztin/xy | 39206be8a283445e0527cec648049625acf4f2ef | [
"Zlib"
] | 1 | 2022-03-06T17:59:32.000Z | 2022-03-06T17:59:32.000Z | /*
* Copyright (c) 2021 Sebastian Kylander https://gaztin.com/
*
* This software is provided 'as-is', without any express or implied warranty. In no event will
* the authors be held liable for any damages arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose, including commercial
* applications, and to alter it and redistribute it freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not claim that you wrote the
* original software. If you use this software in a product, an acknowledgment in the product
* documentation would be appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be misrepresented as
* being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#pragma once
//////////////////////////////////////////////////////////////////////////
/// Includes
#include <memory>
#include <span>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
//////////////////////////////////////////////////////////////////////////
/// Pre-processor defines
#define XY_UI_MODE_DESKTOP 0x01
#define XY_UI_MODE_PHONE 0x02
#define XY_UI_MODE_WATCH 0x04
#define XY_UI_MODE_TV 0x08
#define XY_UI_MODE_VR 0x10
#define XY_UI_MODE_CAR 0x20
#define XY_UI_MODE_HEADLESS 0x40
#if defined( _WIN32 )
/// Windows
#define XY_OS_WINDOWS
#define XY_UI_MODES ( XY_UI_MODE_DESKTOP )
#elif defined( __APPLE__ ) // _WIN32
/// Apple
#include <TargetConditionals.h>
#if TARGET_OS_OSX
#define XY_OS_MACOS
#define XY_UI_MODES ( XY_UI_MODE_DESKTOP )
#elif TARGET_OS_IOS // TARGET_OS_OSX
#define XY_OS_IOS
#define XY_UI_MODES ( XY_UI_MODE_PHONE )
#elif TARGET_OS_WATCH // TARGET_OS_IOS
#define XY_OS_WATCHOS
#define XY_UI_MODES ( XY_UI_MODE_WATCH )
#elif TARGET_OS_TV // TARGET_OS_WATCH
#define XY_OS_TVOS
#define XY_UI_MODES ( XY_UI_MODE_TV )
#endif // TARGET_OS_TV
#elif defined( __ANDROID__ ) // __APPLE__
/// Android
#define XY_OS_ANDROID
// Since there is no way to detect at compile time what UI mode we are targeting, we have to define all possible environments
// List of UI modes can be found at https://developer.android.google.cn/guide/topics/resources/providing-resources.html#UiModeQualifier
// (Appliance corresponds to Headless)
#define XY_UI_MODES ( XY_UI_MODE_PHONE | XY_UI_MODE_WATCH | XY_UI_MODE_TV | XY_UI_MODE_VR | XY_UI_MODE_CAR | XY_UI_MODE_HEADLESS )
#elif defined( __linux__ ) // __ANDROID__
/// Linux
#define XY_OS_LINUX
#define XY_UI_MODES ( XY_UI_MODE_DESKTOP | XY_UI_MODE_HEADLESS )
#endif // __linux__
//////////////////////////////////////////////////////////////////////////
/// Enumerators
enum class xyTheme
{
Light,
Dark,
}; // xyTheme
enum class xyMessageButtons
{
Ok,
OkCancel,
YesNo,
YesNoCancel,
AbortRetryIgnore,
CancelTryagainContinue,
RetryCancel,
}; // xyMessageButtons
enum class xyMessageResult
{
Ok,
Cancel,
Yes,
No,
Abort,
Retry,
Ignore,
Tryagain,
Continue,
}; // xyMessageResult
//////////////////////////////////////////////////////////////////////////
/// Data structures
struct xyPlatformImpl;
struct xyContext
{
std::span< char* > CommandLineArgs;
std::unique_ptr< xyPlatformImpl > pPlatformImpl;
uint32_t UIMode = 0x0;
}; // xyContext
struct xyRect
{
int32_t Left = 0;
int32_t Top = 0;
int32_t Right = 0;
int32_t Bottom = 0;
}; // xyRect
struct xyDevice
{
std::string Name;
}; // xyDevice
struct xyDisplayAdapter
{
std::string Name;
xyRect FullRect;
xyRect WorkRect;
}; // xyDisplayAdapter
struct xyLanguage
{
std::string LocaleName;
}; // xyLanguage
struct xyBatteryState
{
operator bool( void ) const { return Valid; }
uint8_t CapacityPercentage = 100;
bool Charging = false;
bool Valid = false;
}; // xyPowerStatus
//////////////////////////////////////////////////////////////////////////
/// Functions
/**
* Obtains the internal xy context where all the global data is stored
*
* @return A reference to the context data.
*/
extern xyContext& xyGetContext( void );
/**
* Convert a unicode string to UTF-8.
*
* @return A UTF-8 string.
*/
extern std::string xyUTF( std::wstring_view String );
/**
* Convert a UTF-8 to Unicode.
*
* @return A Unicode string.
*/
extern std::wstring xyUnicode( std::string_view String );
/**
* Prompts a system message box containing a user-defined message and a set of options in the form of buttons.
* The current thread is blocked until a selection has been made.
*
* @param Title The title of the message box window.
* @param Message The content of the message text box.
* @param Buttons The range of button options to present.
* @return The result that was selected.
*/
extern xyMessageResult xyMessageBox( std::string_view Title, std::string_view Message, xyMessageButtons Buttons );
/**
* Prompts a system message box containing a user-defined message and an 'OK' button.
* The current thread is blocked until the message box is closed.
*
* @param Title The title of the message box window.
* @param Message The content of the message text box.
*/
extern void xyMessageBox( std::string_view Title, std::string_view Message );
/**
* Obtains information about the current device.
*
* @return The device data.
*/
extern xyDevice xyGetDevice( void );
/**
* Obtains the preferred theme of this device.
*
* @return The theme enumerator.
*/
extern xyTheme xyGetPreferredTheme( void );
/**
* Obtains the system language.
*
* @return The language code.
*/
extern xyLanguage xyGetLanguage( void );
/**
* Obtains the state of the battery power source on this device.
*
* Note: The battery state has a Valid field that is set to true if battery information was successfully obtained.
* If it is false, that either means that the device is only using electric power, or that an error occurred.
* Either way, the battery state provides a boolean operator that allows you to write code like this:
*
* if( xyBatteryState State = xyGetBatteryState() )
* {
* // Successfully obtained the battery state!
* }
*
* @return The battery state.
*/
extern xyBatteryState xyGetBatteryState( void );
/**
* Obtains the display adapters connected to the device.
*
* @return A vector of display adapters.
*/
extern std::vector< xyDisplayAdapter > xyGetDisplayAdapters( void );
//////////////////////////////////////////////////////////////////////////
/*
██╗███╗ ███╗██████╗ ██╗ ███████╗███╗ ███╗███████╗███╗ ██╗████████╗ █████╗ ████████╗██╗ ██████╗ ███╗ ██╗
██║████╗ ████║██╔══██╗██║ ██╔════╝████╗ ████║██╔════╝████╗ ██║╚══██╔══╝██╔══██╗╚══██╔══╝██║██╔═══██╗████╗ ██║
██║██╔████╔██║██████╔╝██║ █████╗ ██╔████╔██║█████╗ ██╔██╗ ██║ ██║ ███████║ ██║ ██║██║ ██║██╔██╗ ██║
██║██║╚██╔╝██║██╔═══╝ ██║ ██╔══╝ ██║╚██╔╝██║██╔══╝ ██║╚██╗██║ ██║ ██╔══██║ ██║ ██║██║ ██║██║╚██╗██║
██║██║ ╚═╝ ██║██║ ███████╗███████╗██║ ╚═╝ ██║███████╗██║ ╚████║ ██║ ██║ ██║ ██║ ██║╚██████╔╝██║ ╚████║
╚═╝╚═╝ ╚═╝╚═╝ ╚══════╝╚══════╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝
*/
#if defined( XY_IMPLEMENT )
//////////////////////////////////////////////////////////////////////////
/// Includes
#include "xy-platforms/xy-android.h"
#include "xy-platforms/xy-desktop.h"
#include "xy-platforms/xy-ios.h"
#include "xy-platforms/xy-macos.h"
#include "xy-platforms/xy-tvos.h"
#include "xy-platforms/xy-watchos.h"
#include "xy-platforms/xy-windows.h"
#if defined( XY_OS_WINDOWS )
#include <windows.h>
#include <lmcons.h>
#elif defined( XY_OS_MACOS ) // XY_OS_WINDOWS
#include <Cocoa/Cocoa.h>
#include <Foundation/Foundation.h>
#elif defined( XY_OS_ANDROID ) // XY_OS_MACOS
#include <android/configuration.h>
#include <android/native_activity.h>
#include <uchar.h>
#include <unistd.h>
#elif defined( XY_OS_IOS ) // XY_OS_ANDROID
#include <UIKit/UIKit.h>
#endif // XY_OS_IOS
//////////////////////////////////////////////////////////////////////////
/// Functions
xyContext& xyGetContext( void )
{
static xyContext Context;
return Context;
} // xyGetContext
//////////////////////////////////////////////////////////////////////////
std::string xyUTF( std::wstring_view String )
{
std::string UTFString;
size_t Size;
const wchar_t* pSrc = String.data();
mbstate_t State{};
#if defined( XY_OS_WINDOWS )
if( wcsrtombs_s( &Size, nullptr, 0, &pSrc, String.size(), &State ) == 0 )
{
UTFString.resize( Size );
wcsrtombs_s( &Size, &UTFString[ 0 ], Size, &pSrc, String.size(), &State );
}
#else // XY_OS_WINDOWS
if( ( Size = wcsrtombs( nullptr, &pSrc, String.size(), &State ) ) > 0 )
{
UTFString.resize( Size );
wcsrtombs( &UTFString[ 0 ], &pSrc, String.size(), &State );
}
#endif // !XY_OS_WINDOWS
return UTFString;
} // xyUTF
//////////////////////////////////////////////////////////////////////////
std::wstring xyUnicode( std::string_view String )
{
std::wstring Result;
size_t Size;
const char* pSrc = String.data();
mbstate_t MultiByteState{ };
#if defined( XY_OS_WINDOWS )
if( mbsrtowcs_s( &Size, nullptr, 0, &pSrc, String.size(), &MultiByteState ) == 0 )
{
Result.resize( Size );
mbsrtowcs_s( &Size, &Result[ 0 ], Size, &pSrc, String.size(), &MultiByteState );
}
#else // XY_OS_WINDOWS
if( ( Size = mbsrtowcs( nullptr, &pSrc, String.size(), &MultiByteState ) ) > 0 )
{
Result.resize( Size );
mbsrtowcs( &Result[ 0 ], &pSrc, String.size(), &MultiByteState );
}
#endif // !XY_OS_WINDOWS
return Result;
} // xyUnicode
//////////////////////////////////////////////////////////////////////////
xyMessageResult xyMessageBox( std::string_view Title, std::string_view Message, xyMessageButtons Buttons )
{
#if defined( XY_OS_WINDOWS )
const UINT MessageType = [ Buttons ]
{
switch( Buttons )
{
default:
case xyMessageButtons::Ok: return MB_OK;
case xyMessageButtons::OkCancel: return MB_OKCANCEL;
case xyMessageButtons::YesNo: return MB_YESNO;
case xyMessageButtons::YesNoCancel: return MB_YESNOCANCEL;
case xyMessageButtons::AbortRetryIgnore: return MB_ABORTRETRYIGNORE;
case xyMessageButtons::CancelTryagainContinue: return MB_CANCELTRYCONTINUE;
case xyMessageButtons::RetryCancel: return MB_RETRYCANCEL;
}
}();
// The ANSI version of MessageBox doesn't support UTF-8 strings so we convert it into Unicode and use the Unicode version instead
const std::wstring UnicodeTitle = xyUnicode( Title );
const std::wstring UnicodeMessage = xyUnicode( Message );
int Result;
if( !UnicodeMessage.empty() ) Result = MessageBoxW( NULL, UnicodeMessage.data(), UnicodeTitle.data(), MessageType | MB_ICONINFORMATION | MB_TASKMODAL );
else Result = MessageBoxA( NULL, Message .data(), Title .data(), MessageType | MB_ICONINFORMATION | MB_TASKMODAL );
switch( Result )
{
default:
case IDOK: return xyMessageResult::Ok;
case IDCANCEL: return xyMessageResult::Cancel;
case IDABORT: return xyMessageResult::Abort;
case IDRETRY: return xyMessageResult::Retry;
case IDIGNORE: return xyMessageResult::Ignore;
case IDYES: return xyMessageResult::Yes;
case IDNO: return xyMessageResult::No;
case IDTRYAGAIN: return xyMessageResult::Tryagain;
case IDCONTINUE: return xyMessageResult::Continue;
}
#elif defined( XY_OS_MACOS ) // XY_OS_WINDOWS
NSAlert* pAlert = [ [ NSAlert alloc ] init ];
NSString* pMessageText = [ NSString stringWithUTF8String:Title.data() ];
NSString* pInformativeText = [ NSString stringWithUTF8String:Message.data() ];
[ pAlert setMessageText:pMessageText ];
[ pAlert setInformativeText:pInformativeText ];
[ pAlert setAlertStyle:NSAlertStyleInformational ];
// Note: Trailing space in "Cancel " is intended
// NSAlert has special layouts for common titles (such as "Cancel") that we would like to avoid
switch( Buttons )
{
case xyMessageButtons::Ok:
[ pAlert addButtonWithTitle:@"OK" ].tag = ( NSInteger )xyMessageResult::Ok;
break;
case xyMessageButtons::OkCancel:
[ pAlert addButtonWithTitle:@"OK" ].tag = ( NSInteger )xyMessageResult::Ok;
[ pAlert addButtonWithTitle:@"Cancel" ].tag = ( NSInteger )xyMessageResult::Cancel;
break;
case xyMessageButtons::YesNo:
[ pAlert addButtonWithTitle:@"Yes" ].tag = ( NSInteger )xyMessageResult::Yes;
[ pAlert addButtonWithTitle:@"No" ].tag = ( NSInteger )xyMessageResult::No;
break;
case xyMessageButtons::YesNoCancel:
[ pAlert addButtonWithTitle:@"Yes" ].tag = ( NSInteger )xyMessageResult::Yes;
[ pAlert addButtonWithTitle:@"No" ].tag = ( NSInteger )xyMessageResult::No;
[ pAlert addButtonWithTitle:@"Cancel " ].tag = ( NSInteger )xyMessageResult::Cancel;
break;
case xyMessageButtons::AbortRetryIgnore:
[ pAlert addButtonWithTitle:@"Abort" ].tag = ( NSInteger )xyMessageResult::Abort;
[ pAlert addButtonWithTitle:@"Retry" ].tag = ( NSInteger )xyMessageResult::Retry;
[ pAlert addButtonWithTitle:@"Ignore" ].tag = ( NSInteger )xyMessageResult::Ignore;
break;
case xyMessageButtons::CancelTryagainContinue:
[ pAlert addButtonWithTitle:@"Cancel " ].tag = ( NSInteger )xyMessageResult::Cancel;
[ pAlert addButtonWithTitle:@"Try Again" ].tag = ( NSInteger )xyMessageResult::Tryagain;
[ pAlert addButtonWithTitle:@"Continue" ].tag = ( NSInteger )xyMessageResult::Continue;
break;
case xyMessageButtons::RetryCancel:
[ pAlert addButtonWithTitle:@"Retry" ].tag = ( NSInteger )xyMessageResult::Retry;
[ pAlert addButtonWithTitle:@"Cancel " ].tag = ( NSInteger )xyMessageResult::Cancel;
break;
}
xyMessageResult Result = ( xyMessageResult )[ pAlert runModal ];
[ pInformativeText release ];
[ pMessageText release ];
[ pAlert release ];
return Result;
#elif defined( XY_OS_ANDROID ) // XY_OS_MACOS
jobject Spinner = xyRunOnJavaThread( []( std::string Title, std::string Message, int Buttons )
{
xyContext& rContext = xyGetContext();
JNIEnv* pJNI = rContext.pPlatformImpl->pNativeActivity->env;
// Easy way to tidy up all our local references when we're done
pJNI->PushLocalFrame( 16 );
// Obtain all necessary classes and method IDs
jclass ClassBuilder = pJNI->FindClass( "android/app/AlertDialog$Builder" );
jmethodID CtorBuilder = pJNI->GetMethodID( ClassBuilder, "<init>", "(Landroid/content/Context;)V" );
jmethodID MethodSetTitle = pJNI->GetMethodID( ClassBuilder, "setTitle", "(Ljava/lang/CharSequence;)Landroid/app/AlertDialog$Builder;" );
jmethodID MethodSetMessage = pJNI->GetMethodID( ClassBuilder, "setMessage", "(Ljava/lang/CharSequence;)Landroid/app/AlertDialog$Builder;" );
jmethodID MethodSetNeutralButton = pJNI->GetMethodID( ClassBuilder, "setNeutralButton", "(Ljava/lang/CharSequence;Landroid/content/DialogInterface$OnClickListener;)Landroid/app/AlertDialog$Builder;" );
jmethodID MethodSetNegativeButton = pJNI->GetMethodID( ClassBuilder, "setNegativeButton", "(Ljava/lang/CharSequence;Landroid/content/DialogInterface$OnClickListener;)Landroid/app/AlertDialog$Builder;" );
jmethodID MethodSetPositiveButton = pJNI->GetMethodID( ClassBuilder, "setPositiveButton", "(Ljava/lang/CharSequence;Landroid/content/DialogInterface$OnClickListener;)Landroid/app/AlertDialog$Builder;" );
jmethodID MethodSetCancelable = pJNI->GetMethodID( ClassBuilder, "setCancelable", "(Z)Landroid/app/AlertDialog$Builder;" );
jmethodID MethodShow = pJNI->GetMethodID( ClassBuilder, "show", "()Landroid/app/AlertDialog;" );
// Create a dummy spinner that will keep track of which button was clicked.
// This is done because we need a built-in class that implements DialogInterface.OnClickListener and has an easy way to query which button was clicked
jclass ClassSpinner = pJNI->FindClass( "android/widget/Spinner" );
jmethodID CtorSpinner = pJNI->GetMethodID( ClassSpinner, "<init>", "(Landroid/content/Context;)V" );
jmethodID MethodSetSelection = pJNI->GetMethodID( ClassSpinner, "setSelection", "(I)V" );
jobject Spinner = pJNI->NewObject( ClassSpinner, CtorSpinner, rContext.pPlatformImpl->pNativeActivity->clazz );
Spinner = pJNI->NewGlobalRef( Spinner );
pJNI->CallVoidMethod( Spinner, MethodSetSelection, 0 );
// Create the alert dialog
jobject Builder = pJNI->NewObject( ClassBuilder, CtorBuilder, rContext.pPlatformImpl->pNativeActivity->clazz );
pJNI->CallObjectMethod( Builder, MethodSetTitle, pJNI->NewStringUTF( Title.data() ) );
pJNI->CallObjectMethod( Builder, MethodSetMessage, pJNI->NewStringUTF( Message.data() ) );
pJNI->CallObjectMethod( Builder, MethodSetCancelable, false );
switch( ( xyMessageButtons )Buttons )
{
case xyMessageButtons::Ok:
pJNI->CallObjectMethod( Builder, MethodSetPositiveButton, pJNI->NewStringUTF( "OK" ), Spinner );
break;
case xyMessageButtons::OkCancel:
pJNI->CallObjectMethod( Builder, MethodSetNeutralButton, pJNI->NewStringUTF( "OK" ), Spinner );
pJNI->CallObjectMethod( Builder, MethodSetPositiveButton, pJNI->NewStringUTF( "Cancel" ), Spinner );
break;
case xyMessageButtons::YesNo:
pJNI->CallObjectMethod( Builder, MethodSetNeutralButton, pJNI->NewStringUTF( "Yes" ), Spinner );
pJNI->CallObjectMethod( Builder, MethodSetPositiveButton, pJNI->NewStringUTF( "No" ), Spinner );
break;
case xyMessageButtons::YesNoCancel:
pJNI->CallObjectMethod( Builder, MethodSetNeutralButton, pJNI->NewStringUTF( "Yes" ), Spinner );
pJNI->CallObjectMethod( Builder, MethodSetNegativeButton, pJNI->NewStringUTF( "No" ), Spinner );
pJNI->CallObjectMethod( Builder, MethodSetPositiveButton, pJNI->NewStringUTF( "Cancel" ), Spinner );
break;
case xyMessageButtons::AbortRetryIgnore:
pJNI->CallObjectMethod( Builder, MethodSetNeutralButton, pJNI->NewStringUTF( "Abort" ), Spinner );
pJNI->CallObjectMethod( Builder, MethodSetNegativeButton, pJNI->NewStringUTF( "Retry" ), Spinner );
pJNI->CallObjectMethod( Builder, MethodSetPositiveButton, pJNI->NewStringUTF( "Ignore" ), Spinner );
break;
case xyMessageButtons::CancelTryagainContinue:
pJNI->CallObjectMethod( Builder, MethodSetNeutralButton, pJNI->NewStringUTF( "Cancel" ), Spinner );
pJNI->CallObjectMethod( Builder, MethodSetNegativeButton, pJNI->NewStringUTF( "Try Again" ), Spinner );
pJNI->CallObjectMethod( Builder, MethodSetPositiveButton, pJNI->NewStringUTF( "Continue" ), Spinner );
break;
case xyMessageButtons::RetryCancel:
pJNI->CallObjectMethod( Builder, MethodSetNeutralButton, pJNI->NewStringUTF( "Retry" ), Spinner );
pJNI->CallObjectMethod( Builder, MethodSetPositiveButton, pJNI->NewStringUTF( "Cancel" ), Spinner );
break;
}
// Show the alert
pJNI->CallObjectMethod( Builder, MethodShow );
pJNI->PopLocalFrame( nullptr );
return Spinner;
}, std::string( Title ), std::string( Message ), ( int )Buttons );
xyContext& rContext = xyGetContext();
JavaVM* pJVM = rContext.pPlatformImpl->pNativeActivity->vm;
JNIEnv* pJNI;
pJVM->AttachCurrentThread( &pJNI, nullptr );
// Sleep until the alert is closed
jclass ClassSpinner = pJNI->GetObjectClass( Spinner );
jmethodID MethodGetSelectedItemPosition = pJNI->GetMethodID( ClassSpinner, "getSelectedItemPosition", "()I" );
int Result;
while( ( Result = pJNI->CallIntMethod( Spinner, MethodGetSelectedItemPosition ) ) == 0 )
std::this_thread::sleep_for( std::chrono::milliseconds( 1 ) );
pJNI->DeleteGlobalRef( Spinner );
pJVM->DetachCurrentThread();
std::array< xyMessageResult, 3 > ResultTable;
switch( Buttons )
{
default:
case xyMessageButtons::Ok: ResultTable = { xyMessageResult::Ok, { }, { } }; break;
case xyMessageButtons::OkCancel: ResultTable = { xyMessageResult::Cancel, { }, xyMessageResult::Ok }; break;
case xyMessageButtons::YesNo: ResultTable = { xyMessageResult::No, { }, xyMessageResult::Yes }; break;
case xyMessageButtons::YesNoCancel: ResultTable = { xyMessageResult::Cancel, xyMessageResult::No, xyMessageResult::Yes }; break;
case xyMessageButtons::AbortRetryIgnore: ResultTable = { xyMessageResult::Ignore, xyMessageResult::Retry, xyMessageResult::Abort }; break;
case xyMessageButtons::CancelTryagainContinue: ResultTable = { xyMessageResult::Continue, xyMessageResult::Tryagain, xyMessageResult::Cancel }; break;
case xyMessageButtons::RetryCancel: ResultTable = { xyMessageResult::Cancel, { }, xyMessageResult::Retry }; break;
}
// Results ranges from -1 to -3
return ResultTable[ -( Result + 1 ) ];
#elif defined( XY_OS_IOS ) // XY_OS_ANDROID
__block int Result = -1;
dispatch_async_and_wait( dispatch_get_main_queue(), ^
{
UIApplication* pApplication = [ UIApplication sharedApplication ];
UIScene* pScene = [ [ [ pApplication connectedScenes ] allObjects ] firstObject ];
UIViewController* pViewController = [ [ [ ( UIWindowScene* )pScene windows ] firstObject ] rootViewController ];
NSString* pTitle = [ NSString stringWithUTF8String:Title.data() ];
NSString* pMessage = [ NSString stringWithUTF8String:Message.data() ];
UIAlertController* pAlertController = [ UIAlertController alertControllerWithTitle:pTitle message:pMessage preferredStyle:UIAlertControllerStyleAlert ];
switch( Buttons )
{
case xyMessageButtons::Ok:
[ pAlertController addAction:[ UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^( UIAlertAction* pAction ) { Result = ( int )xyMessageResult::Ok; } ] ];
break;
case xyMessageButtons::OkCancel:
[ pAlertController addAction:[ UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^( UIAlertAction* pAction ) { Result = ( int )xyMessageResult::Ok; } ] ];
[ pAlertController addAction:[ UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^( UIAlertAction* pAction ) { Result = ( int )xyMessageResult::Cancel; } ] ];
break;
case xyMessageButtons::YesNo:
[ pAlertController addAction:[ UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:^( UIAlertAction* pAction ) { Result = ( int )xyMessageResult::Yes; } ] ];
[ pAlertController addAction:[ UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleDefault handler:^( UIAlertAction* pAction ) { Result = ( int )xyMessageResult::No; } ] ];
break;
case xyMessageButtons::YesNoCancel:
[ pAlertController addAction:[ UIAlertAction actionWithTitle:@"Yes" style:UIAlertActionStyleDefault handler:^( UIAlertAction* pAction ) { Result = ( int )xyMessageResult::Yes; } ] ];
[ pAlertController addAction:[ UIAlertAction actionWithTitle:@"No" style:UIAlertActionStyleDefault handler:^( UIAlertAction* pAction ) { Result = ( int )xyMessageResult::No; } ] ];
[ pAlertController addAction:[ UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^( UIAlertAction* pAction ) { Result = ( int )xyMessageResult::Cancel; } ] ];
break;
case xyMessageButtons::AbortRetryIgnore:
[ pAlertController addAction:[ UIAlertAction actionWithTitle:@"Abort" style:UIAlertActionStyleDefault handler:^( UIAlertAction* pAction ) { Result = ( int )xyMessageResult::Abort; } ] ];
[ pAlertController addAction:[ UIAlertAction actionWithTitle:@"Retry" style:UIAlertActionStyleDefault handler:^( UIAlertAction* pAction ) { Result = ( int )xyMessageResult::Retry; } ] ];
[ pAlertController addAction:[ UIAlertAction actionWithTitle:@"Ignore" style:UIAlertActionStyleDefault handler:^( UIAlertAction* pAction ) { Result = ( int )xyMessageResult::Ignore; } ] ];
break;
case xyMessageButtons::CancelTryagainContinue:
[ pAlertController addAction:[ UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^( UIAlertAction* pAction ) { Result = ( int )xyMessageResult::Cancel; } ] ];
[ pAlertController addAction:[ UIAlertAction actionWithTitle:@"Try Again" style:UIAlertActionStyleDefault handler:^( UIAlertAction* pAction ) { Result = ( int )xyMessageResult::Tryagain; } ] ];
[ pAlertController addAction:[ UIAlertAction actionWithTitle:@"Continue" style:UIAlertActionStyleDefault handler:^( UIAlertAction* pAction ) { Result = ( int )xyMessageResult::Continue; } ] ];
break;
case xyMessageButtons::RetryCancel:
[ pAlertController addAction:[ UIAlertAction actionWithTitle:@"Retry" style:UIAlertActionStyleDefault handler:^( UIAlertAction* pAction ) { Result = ( int )xyMessageResult::Retry; } ] ];
[ pAlertController addAction:[ UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleDefault handler:^( UIAlertAction* pAction ) { Result = ( int )xyMessageResult::Cancel; } ] ];
break;
}
[ pViewController presentViewController:pAlertController animated:NO completion:^{ } ];
} );
// Sleep until selection has been made
while( Result < 0 )
std::this_thread::sleep_for( std::chrono::milliseconds( 1 ) );
return ( xyMessageResult )Result;
#endif // XY_OS_IOS
} // xyMessageBox
//////////////////////////////////////////////////////////////////////////
void xyMessageBox( std::string_view Title, std::string_view Message )
{
( void )xyMessageBox( Title, Message, xyMessageButtons::Ok );
} // xyMessageBox
//////////////////////////////////////////////////////////////////////////
xyDevice xyGetDevice( void )
{
#if defined( XY_OS_WINDOWS )
CHAR Buffer[ CNLEN + 1 ];
DWORD Size = static_cast< DWORD >( std::size( Buffer ) );
if( GetComputerNameA( Buffer, &Size ) )
{
return { .Name={ Buffer, Size } };
}
return { };
#elif defined( XY_OS_MACOS ) // XY_OS_WINDOWS
NSString* pName = [ [ NSHost currentHost ] name ];
return { .Name=[ pName UTF8String ] };
#elif defined( XY_OS_ANDROID ) // XY_OS_MACOS
xyContext& rContext = xyGetContext();
JNIEnv* pJNI;
rContext.pPlatformImpl->pNativeActivity->vm->AttachCurrentThread( &pJNI, nullptr );
jclass BuildClass = pJNI->FindClass( "android/os/Build" );
jfieldID ManufacturerField = pJNI->GetStaticFieldID( BuildClass, "MANUFACTURER", "Ljava/lang/String;" );
jfieldID ModelField = pJNI->GetStaticFieldID( BuildClass, "MODEL", "Ljava/lang/String;" );
jstring ManufacturerName = static_cast< jstring >( pJNI->GetStaticObjectField( BuildClass, ManufacturerField ) );
jstring ModelName = static_cast< jstring >( pJNI->GetStaticObjectField( BuildClass, ModelField ) );
const char* pManufacturerNameUTF = pJNI->GetStringUTFChars( ManufacturerName, nullptr );
const char* pModelNameUTF = pJNI->GetStringUTFChars( ModelName, nullptr );
std::string DeviceName = std::string( pManufacturerNameUTF ) + ' ' + pModelNameUTF;
pJNI->ReleaseStringUTFChars( ModelName, pModelNameUTF );
pJNI->ReleaseStringUTFChars( ManufacturerName, pManufacturerNameUTF );
rContext.pPlatformImpl->pNativeActivity->vm->DetachCurrentThread();
return { .Name=std::move( DeviceName ) };
#elif defined( XY_OS_IOS ) // XY_OS_ANDROID
NSString* pDeviceName = [ [ UIDevice currentDevice ] name ];
return { .Name=[ pDeviceName UTF8String ] };
#endif // XY_OS_IOS
} // xyGetDevice
//////////////////////////////////////////////////////////////////////////
xyTheme xyGetPreferredTheme( void )
{
// Default to light theme
xyTheme Theme = xyTheme::Light;
#if defined( XY_OS_WINDOWS )
DWORD AppsUseLightTheme;
DWORD DataSize = sizeof( AppsUseLightTheme );
if( RegGetValueA( HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", "AppsUseLightTheme", RRF_RT_REG_DWORD, NULL, &AppsUseLightTheme, &DataSize ) == ERROR_SUCCESS )
Theme = AppsUseLightTheme ? xyTheme::Light : xyTheme::Dark;
#elif defined( XY_OS_MACOS ) // XY_OS_WINDOWS
NSString* pStyle = [ [ NSUserDefaults standardUserDefaults ] stringForKey:@"AppleInterfaceStyle" ];
if( [ pStyle isEqualToString:@"Dark" ] )
Theme = xyTheme::Dark;
#elif defined( XY_OS_ANDROID ) // XY_OS_MACOS
xyContext& rContext = xyGetContext();
switch( AConfiguration_getUiModeNight( rContext.pPlatformImpl->pConfiguration ) )
{
case ACONFIGURATION_UI_MODE_NIGHT_NO: { Theme = xyTheme::Light; } break;
case ACONFIGURATION_UI_MODE_NIGHT_YES: { Theme = xyTheme::Dark; } break;
default: break;
}
#elif defined( XY_OS_IOS ) // XY_OS_ANDROID
UITraitCollection* pTraitCollection = [ UITraitCollection currentTraitCollection ];
switch( [ pTraitCollection userInterfaceStyle ] )
{
case UIUserInterfaceStyleLight: { Theme = xyTheme::Light; } break;
case UIUserInterfaceStyleDark: { Theme = xyTheme::Dark; } break;
default: break;
}
#endif // XY_OS_IOS
return Theme;
} // xyGetPreferredTheme
//////////////////////////////////////////////////////////////////////////
xyLanguage xyGetLanguage( void )
{
#if defined( XY_OS_WINDOWS )
xyLanguage Language;
WCHAR Buffer[ LOCALE_NAME_MAX_LENGTH ];
GetUserDefaultLocaleName( Buffer, static_cast< int >( std::size( Buffer ) ) );
return { .LocaleName=xyUTF( Buffer ) };
#elif defined( XY_OS_MACOS ) // XY_OS_WINDOWS
NSString* pLanguageCode = [ [ NSLocale currentLocale ] languageCode ];
return { .LocaleName=[ pLanguageCode UTF8String ] };
#elif defined( XY_OS_ANDROID ) // XY_OS_MACOS
xyContext& rContext = xyGetContext();
char LanguageCode[ 2 ];
AConfiguration_getLanguage( rContext.pPlatformImpl->pConfiguration, LanguageCode );
return { .LocaleName=std::string( LanguageCode, 2 ) };
#elif defined( XY_OS_IOS ) // XY_OS_ANDROID
NSString* pLanguage = [ [ NSLocale preferredLanguages ] firstObject ];
return { .LocaleName=[ pLanguage UTF8String ] };
#endif // XY_OS_IOS
} // xyGetLanguage
//////////////////////////////////////////////////////////////////////////
xyBatteryState xyGetBatteryState( void )
{
xyBatteryState BatteryState;
#if defined( XY_OS_WINDOWS )
SYSTEM_POWER_STATUS SystemPowerStatus;
if( GetSystemPowerStatus( &SystemPowerStatus ) && SystemPowerStatus.BatteryFlag ^ 128 )
{
BatteryState.CapacityPercentage = SystemPowerStatus.BatteryLifePercent;
BatteryState.Charging = SystemPowerStatus.BatteryFlag & 8;
BatteryState.Valid = true;
}
#elif defined( XY_OS_MACOS ) // XY_OS_WINDOWS
CFMutableDictionaryRef Service = IOServiceMatching( "IOPMPowerSource" );
if( io_registry_entry_t Entry = IOServiceGetMatchingService( kIOMasterPortDefault, Service ) )
{
CFMutableDictionaryRef Properties = nullptr;
if( IORegistryEntryCreateCFProperties( Entry, &Properties, nullptr, 0 ) == kIOReturnSuccess )
{
NSDictionary* pRawProperties = ( NSDictionary* )Properties;
bool IsCharging = [ [ pRawProperties objectForKey:@"IsCharging" ] boolValue ];
double Capacity = [ [ pRawProperties objectForKey:@"CurrentCapacity" ] doubleValue ];
double MaxCapacity = [ [ pRawProperties objectForKey:@"MaxCapacity" ] doubleValue ];
BatteryState.CapacityPercentage = static_cast< uint8_t >( 100.0 * Capacity / MaxCapacity );
BatteryState.Charging = IsCharging;
BatteryState.Valid = true;
}
IOObjectRelease( Entry );
}
#elif defined( XY_OS_ANDROID ) // XY_OS_MACOS
xyContext& rContext = xyGetContext();
JNIEnv* pEnv;
rContext.pPlatformImpl->pNativeActivity->vm->AttachCurrentThread( &pEnv, nullptr );
jobject Activity = rContext.pPlatformImpl->pNativeActivity->clazz;
jclass ActivityClass = pEnv->GetObjectClass( Activity );
jstring BatteryService = ( jstring )pEnv->GetStaticObjectField( ActivityClass, pEnv->GetStaticFieldID( ActivityClass, "BATTERY_SERVICE", "Ljava/lang/String;" ) );
jobject BatteryManager = pEnv->CallObjectMethod( Activity, pEnv->GetMethodID( ActivityClass, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;" ), BatteryService );
jclass BatteryManagerClass = pEnv->GetObjectClass( BatteryManager );
jint PropertyCapacity = pEnv->GetStaticIntField( BatteryManagerClass, pEnv->GetStaticFieldID( BatteryManagerClass, "BATTERY_PROPERTY_CAPACITY", "I" ) );
jint PropertyStatus = pEnv->GetStaticIntField( BatteryManagerClass, pEnv->GetStaticFieldID( BatteryManagerClass, "BATTERY_PROPERTY_STATUS", "I" ) );
jint StatusCharging = pEnv->GetStaticIntField( BatteryManagerClass, pEnv->GetStaticFieldID( BatteryManagerClass, "BATTERY_STATUS_CHARGING", "I" ) );
jmethodID GetIntProperty = pEnv->GetMethodID( BatteryManagerClass, "getIntProperty", "(I)I" );
jint Capacity = pEnv->CallIntMethod( BatteryManager, GetIntProperty, PropertyCapacity );
jint Status = pEnv->CallIntMethod( BatteryManager, GetIntProperty, PropertyStatus );
BatteryState.CapacityPercentage = static_cast< uint8_t >( Capacity );
BatteryState.Charging = Status == StatusCharging;
BatteryState.Valid = true;
rContext.pPlatformImpl->pNativeActivity->vm->DetachCurrentThread();
#elif defined( XY_OS_IOS ) // XY_OS_ANDROID
UIDevice* pDevice = [ UIDevice currentDevice ];
const float Level = [ pDevice batteryLevel ];
if( BatteryState.Valid = ( Level >= 0.0f ) )
{
BatteryState.CapacityPercentage = static_cast< uint8_t >( 100.0f * Level );
BatteryState.Charging = [ pDevice batteryState ] == UIDeviceBatteryStateCharging;
}
#endif // XY_OS_IOS
return BatteryState;
} // xyGetBatteryState
//////////////////////////////////////////////////////////////////////////
std::vector< xyDisplayAdapter > xyGetDisplayAdapters( void )
{
std::vector< xyDisplayAdapter > DisplayAdapters;
#if defined( XY_OS_WINDOWS )
auto EnumProc = []( HMONITOR MonitorHandle, HDC /*DeviceContextHandle*/, LPRECT /*pRect*/, LPARAM UserData ) -> BOOL
{
auto& rMonitors = *reinterpret_cast< std::vector< xyDisplayAdapter >* >( UserData );
MONITORINFOEXA Info = { sizeof( MONITORINFOEXA ) };
if( GetMonitorInfoA( MonitorHandle, &Info ) )
{
xyDisplayAdapter Adapter = { .Name = Info.szDevice,
.FullRect = { .Left=Info.rcMonitor.left, .Top=Info.rcMonitor.top, .Right=Info.rcMonitor.right, .Bottom=Info.rcMonitor.bottom },
.WorkRect = { .Left=Info.rcWork .left, .Top=Info.rcWork .top, .Right=Info.rcWork .right, .Bottom=Info.rcWork .bottom } };
DISPLAY_DEVICEA DisplayDevice = { .cb=sizeof( DISPLAY_DEVICEA ) };
if( EnumDisplayDevicesA( Adapter.Name.c_str(), 0, &DisplayDevice, 0 ) )
Adapter.Name = DisplayDevice.DeviceString;
rMonitors.emplace_back( std::move( Adapter ) );
}
// Always continue
return TRUE;
};
EnumDisplayMonitors( NULL, NULL, EnumProc, reinterpret_cast< LPARAM >( &DisplayAdapters ) );
#elif defined( XY_OS_MACOS ) // XY_OS_WINDOWS
for( NSScreen* pScreen in [ NSScreen screens ] )
{
xyDisplayAdapter Adapter = { .Name = [ [ pScreen localizedName ] UTF8String ],
.FullRect = { .Left=NSMinX( pScreen.frame ), .Top=NSMinY( pScreen.frame ), .Right=NSMaxX( pScreen.frame ), .Bottom=NSMaxY( pScreen.frame ) },
.WorkRect = { .Left=NSMinX( pScreen.visibleFrame ), .Top=NSMinY( pScreen.visibleFrame ), .Right=NSMaxX( pScreen.visibleFrame ), .Bottom=NSMaxY( pScreen.visibleFrame ) } };
DisplayAdapters.emplace_back( std::move( Adapter ) );
}
#elif defined( XY_OS_ANDROID ) // XY_OS_MACOS
xyContext& rContext = xyGetContext();
JNIEnv* pJNI;
rContext.pPlatformImpl->pNativeActivity->vm->AttachCurrentThread( &pJNI, nullptr );
jobject Activity = rContext.pPlatformImpl->pNativeActivity->clazz;
jclass ActivityClass = pJNI->GetObjectClass( Activity );
jstring DisplayService = ( jstring )pJNI->GetStaticObjectField( ActivityClass, pJNI->GetStaticFieldID( ActivityClass, "DISPLAY_SERVICE", "Ljava/lang/String;" ) );
jobject DisplayManager = pJNI->CallObjectMethod( Activity, pJNI->GetMethodID( ActivityClass, "getSystemService", "(Ljava/lang/String;)Ljava/lang/Object;" ), DisplayService );
jobjectArray Displays = ( jobjectArray )pJNI->CallObjectMethod( DisplayManager, pJNI->GetMethodID( pJNI->GetObjectClass( DisplayManager ), "getDisplays", "()[Landroid/view/Display;" ) );
jsize DisplayCount = pJNI->GetArrayLength( Displays );
for( jsize i = 0; i < DisplayCount; ++i )
{
jobject Display = pJNI->GetObjectArrayElement( Displays, i );
jclass DisplayClass = pJNI->GetObjectClass( Display );
jstring Name = ( jstring )pJNI->CallObjectMethod( Display, pJNI->GetMethodID( DisplayClass, "getName", "()Ljava/lang/String;" ) );
const char* pNameUTF = pJNI->GetStringUTFChars( Name, nullptr );
jclass RectClass = pJNI->FindClass( "android/graphics/Rect" );
jobject Bounds = pJNI->AllocObject( RectClass );
xyDisplayAdapter Adapter = { .Name=pNameUTF };
// NOTE: "getRectSize" is deprecated as of SDK v30.
// The documentation suggests using WindowMetric#getBounds(), but there seems to be no way of obtaining the bounds of a specific Display object.
pJNI->CallVoidMethod( Display, pJNI->GetMethodID( DisplayClass, "getRectSize", "(Landroid/graphics/Rect;)V" ), Bounds );
Adapter.FullRect.Left = pJNI->GetIntField( Bounds, pJNI->GetFieldID( RectClass, "left", "I" ) );
Adapter.FullRect.Top = pJNI->GetIntField( Bounds, pJNI->GetFieldID( RectClass, "top", "I" ) );
Adapter.FullRect.Right = pJNI->GetIntField( Bounds, pJNI->GetFieldID( RectClass, "right", "I" ) );
Adapter.FullRect.Bottom = pJNI->GetIntField( Bounds, pJNI->GetFieldID( RectClass, "bottom", "I" ) );
if( jobject DisplayCutout = pJNI->CallObjectMethod( Display, pJNI->GetMethodID( DisplayClass, "getCutout", "()Landroid/view/DisplayCutout;" ) ) )
{
jclass DisplayCutoutClass = pJNI->GetObjectClass( DisplayCutout );
Adapter.WorkRect.Left = pJNI->CallIntMethod( DisplayCutout, pJNI->GetMethodID( DisplayCutoutClass, "getSafeInsetLeft", "()I" ) );
Adapter.WorkRect.Top = pJNI->CallIntMethod( DisplayCutout, pJNI->GetMethodID( DisplayCutoutClass, "getSafeInsetTop", "()I" ) );
Adapter.WorkRect.Right = pJNI->CallIntMethod( DisplayCutout, pJNI->GetMethodID( DisplayCutoutClass, "getSafeInsetRight", "()I" ) );
Adapter.WorkRect.Bottom = pJNI->CallIntMethod( DisplayCutout, pJNI->GetMethodID( DisplayCutoutClass, "getSafeInsetBottom", "()I" ) );
}
else
{
// TODO: There are other ways to obtain the safe area
Adapter.WorkRect = Adapter.FullRect;
}
DisplayAdapters.emplace_back( std::move( Adapter ) );
pJNI->ReleaseStringUTFChars( Name, pNameUTF );
}
rContext.pPlatformImpl->pNativeActivity->vm->DetachCurrentThread();
#elif defined( XY_OS_IOS ) // XY_OS_ANDROID
NSArray< UIScreen* >* pScreens = [ UIScreen screens ];
for( UIScreen* pScreen in pScreens )
{
NSString* pScreenName = ( pScreen == [ UIScreen mainScreen ] ) ? @"Main Display" : [ NSString stringWithFormat:@"External Display #%d", [ pScreens indexOfObject:pScreen ] ];
CGRect Bounds = [ pScreen bounds ];
xyDisplayAdapter MainDisplay = { .Name = [ pScreenName UTF8String ],
.FullRect = { .Left=CGRectGetMinX( Bounds ), .Top=CGRectGetMinY( Bounds ), .Right=CGRectGetMaxX( Bounds ), .Bottom=CGRectGetMaxY( Bounds ) } };
// TODO: Obtain the safe area
DisplayAdapters.emplace_back( std::move( MainDisplay ) );
}
#endif // XY_OS_IOS
return DisplayAdapters;
} // xyGetDisplayAdapters
#endif // XY_IMPLEMENT
| 40.053946 | 205 | 0.675363 | [
"object",
"vector",
"model"
] |
3a54ff3c69346e2c342d9c834eb80bbaa75ba417 | 1,363 | h | C | pool/pthreadpool.h | tallsong/LinuxNetwork | a41a9c4ae11cda44485abd6e95368aacae7cc59a | [
"MIT"
] | 3 | 2019-03-27T06:02:54.000Z | 2021-01-25T00:57:19.000Z | pool/pthreadpool.h | tallsong/LinuxNetwork | a41a9c4ae11cda44485abd6e95368aacae7cc59a | [
"MIT"
] | null | null | null | pool/pthreadpool.h | tallsong/LinuxNetwork | a41a9c4ae11cda44485abd6e95368aacae7cc59a | [
"MIT"
] | null | null | null | #ifndef __THREADPOOL_H_
#define __THREADPOOL_H_
typedef struct threadpool_t threadpool_t;
/**
* @function threadpool_create
* @descCreates a threadpool_t object.
* @param thr_num thread num
* @param max_thr_num max thread size
* @param queue_max_size size of the queue.
* @return a newly created thread pool or NULL
*/
threadpool_t *threadpool_create(int min_thr_num, int max_thr_num, int queue_max_size);
/**
* @function threadpool_add
* @desc add a new task in the queue of a thread pool
* @param pool Thread pool to which add the task.
* @param function Pointer to the function that will perform the task.
* @param argument Argument to be passed to the function.
* @return 0 if all goes well,else -1
*/
int threadpool_add(threadpool_t *pool, void*(*function)(void *arg), void *arg);
/**
* @function threadpool_destroy
* @desc Stops and destroys a thread pool.
* @param pool Thread pool to destroy.
* @return 0 if destory success else -1
*/
int threadpool_destroy(threadpool_t *pool);
/**
* @desc get the thread num
* @pool pool threadpool
* @return # of the thread
*/
int threadpool_all_threadnum(threadpool_t *pool);
/**
* desc get the busy thread num
* @param pool threadpool
* return # of the busy thread
*/
int threadpool_busy_threadnum(threadpool_t *pool);
#endif
| 27.816327 | 87 | 0.707263 | [
"object"
] |
3a64157546d0e44b823513fdf02eb317eb130e2a | 1,003 | h | C | Source/Quarrel/Effects.h | rachelnertia/Quarrel | 69616179fc71305757549c7fcaccc22707a91ba4 | [
"MIT"
] | null | null | null | Source/Quarrel/Effects.h | rachelnertia/Quarrel | 69616179fc71305757549c7fcaccc22707a91ba4 | [
"MIT"
] | null | null | null | Source/Quarrel/Effects.h | rachelnertia/Quarrel | 69616179fc71305757549c7fcaccc22707a91ba4 | [
"MIT"
] | 1 | 2019-06-02T17:43:22.000Z | 2019-06-02T17:43:22.000Z | #pragma once
#include <chrono>
#include <vector>
#include "External/enum.h"
namespace qvr
{
class RenderComponent;
}
struct DamageCount;
class MovementSpeed;
BETTER_ENUM(
ActiveEffectType, int,
None,
Burning,
Poisoned,
Chilled,
Frozen
);
struct ActiveEffect
{
ActiveEffectType type;
std::chrono::duration<float> remainingDuration;
std::chrono::duration<float> runningDuration;
};
struct ActiveEffectSet
{
std::vector<ActiveEffect> container;
};
void AddActiveEffect(
const ActiveEffectType effectType,
ActiveEffectSet& activeEffects);
void RemoveExpiredEffects(ActiveEffectSet& activeEffects);
// Returns true if the damage effect should be applied this frame.
bool UpdateEffect(ActiveEffect& activeEffect, const std::chrono::duration<float> deltaTime);
void ApplyEffect(const ActiveEffect& activeEffect, DamageCount& damage);
void ApplyEffect(const ActiveEffect& effect, MovementSpeed& speed);
void ApplyEffect(const ActiveEffect& effect, qvr::RenderComponent& renderComponent); | 20.469388 | 92 | 0.793619 | [
"vector"
] |
3a655d5ff9daba0044b1ed64331075901a21f125 | 933 | h | C | System/Library/PrivateFrameworks/PhotosUICore.framework/_PXDisplayLinkWeakReference.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | 1 | 2020-11-04T15:43:01.000Z | 2020-11-04T15:43:01.000Z | System/Library/PrivateFrameworks/PhotosUICore.framework/_PXDisplayLinkWeakReference.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/PhotosUICore.framework/_PXDisplayLinkWeakReference.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | null | null | null | /*
* This header is generated by classdump-dyld 1.0
* on Monday, September 28, 2020 at 5:54:58 PM Mountain Standard Time
* Operating System: Version 14.0 (Build 18A373)
* Image Source: /System/Library/PrivateFrameworks/PhotosUICore.framework/PhotosUICore
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
@interface _PXDisplayLinkWeakReference : NSObject {
id _object;
SEL _selector;
}
@property (nonatomic,__weak,readonly) id object; //@synthesize object=_object - In the implementation block
@property (nonatomic,readonly) SEL selector; //@synthesize selector=_selector - In the implementation block
-(void)handleDisplayLink:(id)arg1 ;
-(SEL)selector;
-(id)initWithObject:(id)arg1 selector:(SEL)arg2 ;
-(id)object;
@end
| 37.32 | 124 | 0.630225 | [
"object"
] |
3a67f85b5928f78fccb16982eaffb60cdbb4eeb6 | 14,583 | h | C | B2G/gecko/layout/tables/celldata.h | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-08-31T15:24:31.000Z | 2020-04-24T20:31:29.000Z | B2G/gecko/layout/tables/celldata.h | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | null | null | null | B2G/gecko/layout/tables/celldata.h | wilebeast/FireFox-OS | 43067f28711d78c429a1d6d58c77130f6899135f | [
"Apache-2.0"
] | 3 | 2015-07-29T07:17:15.000Z | 2020-11-04T06:55:37.000Z | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef CellData_h__
#define CellData_h__
#include "nsISupports.h"
#include "nsCoord.h"
#include "mozilla/gfx/Types.h"
class nsTableCellFrame;
class nsCellMap;
class BCCellData;
#define MAX_ROWSPAN 65534 // the cellmap can not handle more.
#define MAX_COLSPAN 1000 // limit as IE and opera do. If this ever changes,
// change COL_SPAN_OFFSET/COL_SPAN_SHIFT accordingly.
/**
* Data stored by nsCellMap to rationalize rowspan and colspan cells.
*/
class CellData
{
public:
/** Initialize the mOrigCell pointer
* @param aOrigCell the table cell frame which will be stored in mOrigCell.
*/
void Init(nsTableCellFrame* aCellFrame);
/** does a cell originate from here
* @return is true if a cell corresponds to this cellmap entry
*/
bool IsOrig() const;
/** is the celldata valid
* @return is true if no cell originates and the cell is not spanned by
* a row- or colspan. mBits are 0 in this case and mOrigCell is
* nullptr
*/
bool IsDead() const;
/** is the entry spanned by row- or a colspan
* @return is true if the entry is spanned by a row- or colspan
*/
bool IsSpan() const;
/** is the entry spanned by rowspan
* @return is true if the entry is spanned by a rowspan
*/
bool IsRowSpan() const;
/** is the entry spanned by a zero rowspan
* zero rowspans span all cells starting from the originating cell down to
* the end of the rowgroup or a cell originating in the same column
* @return is true if the entry is spanned by a zero rowspan
*/
bool IsZeroRowSpan() const;
/** mark the current entry as spanned by a zero rowspan
* @param aIsZero if true mark the entry as covered by a zero rowspan
*/
void SetZeroRowSpan(bool aIsZero);
/** get the distance from the current entry to the corresponding origin of the rowspan
* @return containing the distance in the column to the originating cell
*/
uint32_t GetRowSpanOffset() const;
/** set the distance from the current entry to the corresponding origin of the rowspan
* @param the distance in the column to the originating cell
*/
void SetRowSpanOffset(uint32_t aSpan);
/** is the entry spanned by colspan
* @return is true if the entry is spanned by a colspan
*/
bool IsColSpan() const;
/** is the entry spanned by a zero colspan
* zero colspans span all cells starting from the originating cell towards
* the end of the colgroup or a cell originating in the same row
* or a rowspanned entry
* @return is true if the entry is spanned by a zero colspan
*/
bool IsZeroColSpan() const;
/** mark the current entry as spanned by a zero colspan
* @param aIsZero if true mark the entry as covered by a zero colspan
*/
void SetZeroColSpan(bool aIsZero);
/** get the distance from the current entry to the corresponding origin of the colspan
* @return containing the distance in the row to the originating cell
*/
uint32_t GetColSpanOffset() const;
/** set the distance from the current entry to the corresponding origin of the colspan
* @param the distance in the column to the originating cell
*/
void SetColSpanOffset(uint32_t aSpan);
/** is the entry spanned by a row- and a colspan
* @return is true if the entry is spanned by a row- and a colspan
*/
bool IsOverlap() const;
/** mark the current entry as spanned by a row- and a colspan
* @param aOverlap if true mark the entry as covered by a row- and a colspan
*/
void SetOverlap(bool aOverlap);
/** get the table cell frame for this entry
* @return a pointer to the cellframe, this will be nullptr when the entry
* is only a spanned entry
*/
nsTableCellFrame* GetCellFrame() const;
private:
friend class nsCellMap;
friend class BCCellData;
/** constructor.
* @param aOrigCell the table cell frame which will be stored in mOrigCell.
*/
CellData(nsTableCellFrame* aOrigCell); // implemented in nsCellMap.cpp
/** destructor */
~CellData(); // implemented in nsCellMap.cpp
protected:
// this union relies on the assumption that an object (not primitive type) does
// not start on an odd bit boundary. If mSpan is 0 then mOrigCell is in effect
// and the data does not represent a span. If mSpan is 1, then mBits is in
// effect and the data represents a span.
// mBits must be an unsigned long because it must match the size of
// mOrigCell on both 32- and 64-bit platforms.
union {
nsTableCellFrame* mOrigCell;
unsigned long mBits;
};
};
// Border Collapsing Cell Data
enum BCBorderOwner
{
eTableOwner = 0,
eColGroupOwner = 1,
eAjaColGroupOwner = 2, // col group to the left
eColOwner = 3,
eAjaColOwner = 4, // col to the left
eRowGroupOwner = 5,
eAjaRowGroupOwner = 6, // row group above
eRowOwner = 7,
eAjaRowOwner = 8, // row above
eCellOwner = 9,
eAjaCellOwner = 10 // cell to the top or to the left
};
typedef uint16_t BCPixelSize;
// These are the max sizes that are stored. If they are exceeded, then the max is stored and
// the actual value is computed when needed.
#define MAX_BORDER_WIDTH nscoord(PR_BITMASK(sizeof(BCPixelSize) * 8))
static inline nscoord
BC_BORDER_TOP_HALF_COORD(int32_t p2t, uint16_t px) { return (px - px / 2) * p2t; }
static inline nscoord
BC_BORDER_RIGHT_HALF_COORD(int32_t p2t, uint16_t px) { return ( px / 2) * p2t; }
static inline nscoord
BC_BORDER_BOTTOM_HALF_COORD(int32_t p2t, uint16_t px) { return ( px / 2) * p2t; }
static inline nscoord
BC_BORDER_LEFT_HALF_COORD(int32_t p2t, uint16_t px) { return (px - px / 2) * p2t; }
#define BC_BORDER_TOP_HALF(px) ((px) - (px) / 2)
#define BC_BORDER_RIGHT_HALF(px) ((px) / 2)
#define BC_BORDER_BOTTOM_HALF(px) ((px) / 2)
#define BC_BORDER_LEFT_HALF(px) ((px) - (px) / 2)
// BCData stores the top and left border info and the corner connecting the two.
class BCData
{
public:
BCData();
~BCData();
nscoord GetLeftEdge(BCBorderOwner& aOwner,
bool& aStart) const;
void SetLeftEdge(BCBorderOwner aOwner,
nscoord aSize,
bool aStart);
nscoord GetTopEdge(BCBorderOwner& aOwner,
bool& aStart) const;
void SetTopEdge(BCBorderOwner aOwner,
nscoord aSize,
bool aStart);
BCPixelSize GetCorner(mozilla::css::Side& aCornerOwner,
bool& aBevel) const;
void SetCorner(BCPixelSize aSubSize,
mozilla::css::Side aOwner,
bool aBevel);
bool IsLeftStart() const;
void SetLeftStart(bool aValue);
bool IsTopStart() const;
void SetTopStart(bool aValue);
protected:
BCPixelSize mLeftSize; // size in pixels of left border
BCPixelSize mTopSize; // size in pixels of top border
BCPixelSize mCornerSubSize; // size of the largest border not in the
// dominant plane (for example, if corner is
// owned by the segment to its top or bottom,
// then the size is the max of the border
// sizes of the segments to its left or right.
unsigned mLeftOwner: 4; // owner of left border
unsigned mTopOwner: 4; // owner of top border
unsigned mLeftStart: 1; // set if this is the start of a vertical border segment
unsigned mTopStart: 1; // set if this is the start of a horizontal border segment
unsigned mCornerSide: 2; // mozilla::css::Side of the owner of the upper left corner relative to the corner
unsigned mCornerBevel: 1; // is the corner beveled (only two segments, perpendicular, not dashed or dotted).
};
// BCCellData entries replace CellData entries in the cell map if the border collapsing model is in
// effect. BCData for a row and col entry contains the left and top borders of cell at that row and
// col and the corner connecting the two. The right borders of the cells in the last col and the bottom
// borders of the last row are stored in separate BCData entries in the cell map.
class BCCellData : public CellData
{
public:
BCCellData(nsTableCellFrame* aOrigCell);
~BCCellData();
BCData mData;
};
// The layout of a celldata is as follows. The top 10 bits are the colspan
// offset (which is enough to represent our allowed values 1-1000 for colspan).
// Then there are three bits of flags. Then 16 bits of rowspan offset (which
// lets us represent numbers up to 65535. Then another 3 bits of flags.
// num bits to shift right to get right aligned col span
#define COL_SPAN_SHIFT 22
// num bits to shift right to get right aligned row span
#define ROW_SPAN_SHIFT 3
// the col offset to the data containing the original cell.
#define COL_SPAN_OFFSET (0x3FF << COL_SPAN_SHIFT)
// the row offset to the data containing the original cell
#define ROW_SPAN_OFFSET (0xFFFF << ROW_SPAN_SHIFT)
// And the flags
#define SPAN 0x00000001 // there a row or col span
#define ROW_SPAN 0x00000002 // there is a row span
#define ROW_SPAN_0 0x00000004 // the row span is 0
#define COL_SPAN (1 << (COL_SPAN_SHIFT - 3)) // there is a col span
#define COL_SPAN_0 (1 << (COL_SPAN_SHIFT - 2)) // the col span is 0
#define OVERLAP (1 << (COL_SPAN_SHIFT - 1)) // there is a row span and
// col span but not by
// same cell
inline nsTableCellFrame* CellData::GetCellFrame() const
{
if (SPAN != (SPAN & mBits)) {
return mOrigCell;
}
return nullptr;
}
inline void CellData::Init(nsTableCellFrame* aCellFrame)
{
mOrigCell = aCellFrame;
}
inline bool CellData::IsOrig() const
{
return ((nullptr != mOrigCell) && (SPAN != (SPAN & mBits)));
}
inline bool CellData::IsDead() const
{
return (0 == mBits);
}
inline bool CellData::IsSpan() const
{
return (SPAN == (SPAN & mBits));
}
inline bool CellData::IsRowSpan() const
{
return (SPAN == (SPAN & mBits)) &&
(ROW_SPAN == (ROW_SPAN & mBits));
}
inline bool CellData::IsZeroRowSpan() const
{
return (SPAN == (SPAN & mBits)) &&
(ROW_SPAN == (ROW_SPAN & mBits)) &&
(ROW_SPAN_0 == (ROW_SPAN_0 & mBits));
}
inline void CellData::SetZeroRowSpan(bool aIsZeroSpan)
{
if (SPAN == (SPAN & mBits)) {
if (aIsZeroSpan) {
mBits |= ROW_SPAN_0;
}
else {
mBits &= ~ROW_SPAN_0;
}
}
}
inline uint32_t CellData::GetRowSpanOffset() const
{
if ((SPAN == (SPAN & mBits)) && ((ROW_SPAN == (ROW_SPAN & mBits)))) {
return (uint32_t)((mBits & ROW_SPAN_OFFSET) >> ROW_SPAN_SHIFT);
}
return 0;
}
inline void CellData::SetRowSpanOffset(uint32_t aSpan)
{
mBits &= ~ROW_SPAN_OFFSET;
mBits |= (aSpan << ROW_SPAN_SHIFT);
mBits |= SPAN;
mBits |= ROW_SPAN;
}
inline bool CellData::IsColSpan() const
{
return (SPAN == (SPAN & mBits)) &&
(COL_SPAN == (COL_SPAN & mBits));
}
inline bool CellData::IsZeroColSpan() const
{
return (SPAN == (SPAN & mBits)) &&
(COL_SPAN == (COL_SPAN & mBits)) &&
(COL_SPAN_0 == (COL_SPAN_0 & mBits));
}
inline void CellData::SetZeroColSpan(bool aIsZeroSpan)
{
if (SPAN == (SPAN & mBits)) {
if (aIsZeroSpan) {
mBits |= COL_SPAN_0;
}
else {
mBits &= ~COL_SPAN_0;
}
}
}
inline uint32_t CellData::GetColSpanOffset() const
{
if ((SPAN == (SPAN & mBits)) && ((COL_SPAN == (COL_SPAN & mBits)))) {
return (uint32_t)((mBits & COL_SPAN_OFFSET) >> COL_SPAN_SHIFT);
}
return 0;
}
inline void CellData::SetColSpanOffset(uint32_t aSpan)
{
mBits &= ~COL_SPAN_OFFSET;
mBits |= (aSpan << COL_SPAN_SHIFT);
mBits |= SPAN;
mBits |= COL_SPAN;
}
inline bool CellData::IsOverlap() const
{
return (SPAN == (SPAN & mBits)) && (OVERLAP == (OVERLAP & mBits));
}
inline void CellData::SetOverlap(bool aOverlap)
{
if (SPAN == (SPAN & mBits)) {
if (aOverlap) {
mBits |= OVERLAP;
}
else {
mBits &= ~OVERLAP;
}
}
}
inline BCData::BCData()
{
mLeftOwner = mTopOwner = eCellOwner;
mLeftStart = mTopStart = 1;
mLeftSize = mCornerSubSize = mTopSize = 0;
mCornerSide = NS_SIDE_TOP;
mCornerBevel = false;
}
inline BCData::~BCData()
{
}
inline nscoord BCData::GetLeftEdge(BCBorderOwner& aOwner,
bool& aStart) const
{
aOwner = (BCBorderOwner)mLeftOwner;
aStart = (bool)mLeftStart;
return (nscoord)mLeftSize;
}
inline void BCData::SetLeftEdge(BCBorderOwner aOwner,
nscoord aSize,
bool aStart)
{
mLeftOwner = aOwner;
mLeftSize = (aSize > MAX_BORDER_WIDTH) ? MAX_BORDER_WIDTH : aSize;
mLeftStart = aStart;
}
inline nscoord BCData::GetTopEdge(BCBorderOwner& aOwner,
bool& aStart) const
{
aOwner = (BCBorderOwner)mTopOwner;
aStart = (bool)mTopStart;
return (nscoord)mTopSize;
}
inline void BCData::SetTopEdge(BCBorderOwner aOwner,
nscoord aSize,
bool aStart)
{
mTopOwner = aOwner;
mTopSize = (aSize > MAX_BORDER_WIDTH) ? MAX_BORDER_WIDTH : aSize;
mTopStart = aStart;
}
inline BCPixelSize BCData::GetCorner(mozilla::css::Side& aOwnerSide,
bool& aBevel) const
{
aOwnerSide = mozilla::css::Side(mCornerSide);
aBevel = (bool)mCornerBevel;
return mCornerSubSize;
}
inline void BCData::SetCorner(BCPixelSize aSubSize,
mozilla::css::Side aOwnerSide,
bool aBevel)
{
mCornerSubSize = aSubSize;
mCornerSide = aOwnerSide;
mCornerBevel = aBevel;
}
inline bool BCData::IsLeftStart() const
{
return (bool)mLeftStart;
}
inline void BCData::SetLeftStart(bool aValue)
{
mLeftStart = aValue;
}
inline bool BCData::IsTopStart() const
{
return (bool)mTopStart;
}
inline void BCData::SetTopStart(bool aValue)
{
mTopStart = aValue;
}
#endif
| 29.761224 | 112 | 0.645066 | [
"object",
"model"
] |
3a68734c592ae907e27bf58554f1d8b5330d4e27 | 1,171 | h | C | include/car_calculator.h | R41fK/kuehmayer_project_2 | 19fbe26500312c576e7c4958fa160c931211e2fd | [
"BSL-1.0"
] | null | null | null | include/car_calculator.h | R41fK/kuehmayer_project_2 | 19fbe26500312c576e7c4958fa160c931211e2fd | [
"BSL-1.0"
] | null | null | null | include/car_calculator.h | R41fK/kuehmayer_project_2 | 19fbe26500312c576e7c4958fa160c931211e2fd | [
"BSL-1.0"
] | null | null | null | #pragma once
#include <climits>
#include <cfloat>
#include <optional>
#include <string>
#include "message.pb.h"
#include "car.h"
#include "car_builder.h"
class Car_Calculator {
private:
Car car{0, 0, 0, Car_Types::NONE, Car_Brands::NONE, Fuel_Type::NONE};
short unsigned int leasing_duration{0};
short unsigned int insurance_class{USHRT_MAX};
double rest_value{DBL_MAX};
double deposit{DBL_MAX};
double annual_interest_rate{0.0201};
bool _is_over_24{true};
public:
void set_car(Car);
void set_leasing_duration(short unsigned int);
void set_insurance_class(short unsigned int);
void set_rest_value(double);
void set_deposit(double);
void is_under_24();
void is_over_24();
std::optional<double> calculate_leasing_rate();
std::optional<double> calculate_insurance_rate();
std::string to_string();
// get the protomessage. If the second parameter ist true it is a reply,
// else it is a request
std::string get_proto_message(std::string, std::string, bool);
// updates the object from a proto-message
void update_car_calculator_from_proto_message(Message_Car_Calculator);
}; | 26.022222 | 77 | 0.719044 | [
"object"
] |
3a71b242598400a63acc9dce3152c1aeb38e335c | 452 | h | C | core/UnlockBytes.h | DronMDF/doors | 4e2069159c5edf1d55933480307c127b853255e0 | [
"MIT"
] | null | null | null | core/UnlockBytes.h | DronMDF/doors | 4e2069159c5edf1d55933480307c127b853255e0 | [
"MIT"
] | 205 | 2019-02-22T15:37:26.000Z | 2019-07-21T21:20:00.000Z | core/UnlockBytes.h | DronMDF/doors | 4e2069159c5edf1d55933480307c127b853255e0 | [
"MIT"
] | null | null | null | // Copyright (c) 2019 Andrey Valyaev <dron.valyaev@gmail.com>
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
#pragma once
#include "Bytes.h"
class UnlockBytes final : public Bytes {
public:
UnlockBytes(uint32_t id, uint32_t lock_no, uint64_t key);
std::vector<uint8_t> raw() const override;
private:
const uint32_t id;
const uint32_t lock_no;
const uint64_t key;
};
| 25.111111 | 64 | 0.747788 | [
"vector"
] |
3a72976c76a38cdc884eb7aaa8b98f25c1dfb5ac | 5,885 | h | C | tesseract_state_solver/include/tesseract_state_solver/mutable_state_solver.h | daoran/tesseract | 2c593d12a0a470bd2672fdf6ff86843dd69b6e4a | [
"BSD-3-Clause",
"BSD-2-Clause",
"Apache-2.0"
] | 25 | 2021-11-08T05:41:28.000Z | 2022-03-29T12:17:30.000Z | tesseract_state_solver/include/tesseract_state_solver/mutable_state_solver.h | daoran/tesseract | 2c593d12a0a470bd2672fdf6ff86843dd69b6e4a | [
"BSD-3-Clause",
"BSD-2-Clause",
"Apache-2.0"
] | 79 | 2021-10-30T19:53:38.000Z | 2022-03-31T21:37:43.000Z | tesseract_state_solver/include/tesseract_state_solver/mutable_state_solver.h | daoran/tesseract | 2c593d12a0a470bd2672fdf6ff86843dd69b6e4a | [
"BSD-3-Clause",
"BSD-2-Clause",
"Apache-2.0"
] | 10 | 2021-11-09T03:02:08.000Z | 2022-03-23T02:24:33.000Z | /**
* @file mutable_state_solver.h
* @brief Tesseract Scene Graph Mutable State Solver Interface .
*
* @author Levi Armstrong
* @date Dec 18, 2017
* @version TODO
* @bug No known bugs
*
* @copyright Copyright (c) 2017, Southwest Research Institute
*
* @par License
* Software License Agreement (Apache License)
* @par
* 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
* @par
* 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 TESSERACT_STATE_SOLVER_MUTABLE_STATE_SOLVER_H
#define TESSERACT_STATE_SOLVER_MUTABLE_STATE_SOLVER_H
#include <tesseract_state_solver/state_solver.h>
#ifdef SWIG
%shared_ptr(tesseract_scene_graph::MutableStateSolver)
%wrap_unique_ptr(MutableStateSolverUPtr,tesseract_scene_graph::MutableStateSolver)
#endif // SWIG
namespace tesseract_scene_graph
{
/**
* @brief A mutable state solver allows you to reconfigure the solver's links and joints
*/
class MutableStateSolver : public StateSolver
{
public:
using Ptr = std::shared_ptr<MutableStateSolver>;
using ConstPtr = std::shared_ptr<const MutableStateSolver>;
using UPtr = std::unique_ptr<MutableStateSolver>;
using ConstUPtr = std::unique_ptr<const MutableStateSolver>;
MutableStateSolver() = default;
~MutableStateSolver() override = default;
MutableStateSolver(const MutableStateSolver&) = default;
MutableStateSolver& operator=(const MutableStateSolver&) = default;
MutableStateSolver(MutableStateSolver&&) = default;
MutableStateSolver& operator=(MutableStateSolver&&) = default;
/**
* @brief Set the state solver revision number
* @param revision The revision number to assign
*/
virtual void setRevision(int revision) = 0;
/**
* @brief Get the state solver revision number
* @return revision number
*/
virtual int getRevision() const = 0;
/**
* @brief Adds a link/joint to the solver
* @param link The link to be added to the graph
* @param joint The associated joint to be added to the graph
* @return Return False if a link with the same name allready exists, otherwise true
*/
virtual bool addLink(const Link& link, const Joint& joint) = 0;
/**
* @brief Move a link
* @param joint The associated joint that defines the move
* @return Return False if link does not exist or if joint name already exists, otherwise true
*/
virtual bool moveLink(const Joint& joint) = 0;
/**
* @brief Removes a link from the graph
*
* Note: this will remove all inbound and outbound edges
*
* @param name Name of the link to be removed
* @return Return False if a link does not exists, otherwise true
*/
virtual bool removeLink(const std::string& name) = 0;
/**
* @brief Replace and existing joint with the provided one
* @param joint The replacement joint
* @return Return False if a joint does not exists, otherwise true
*/
virtual bool replaceJoint(const Joint& joint) = 0;
/**
* @brief Removes a joint from the graph
* @param name Name of the joint to be removed
* @return Return False if a joint does not exists, otherwise true
*/
virtual bool removeJoint(const std::string& name) = 0;
/**
* @brief Move joint to new parent link
* @param name Name of the joint to move
* @param parent_link Name of parent link to move to
* @return Returns true if successful, otherwise false.
*/
virtual bool moveJoint(const std::string& name, const std::string& parent_link) = 0;
/**
* @brief Changes the "origin" transform of the joint and recomputes the associated edge
* @param name Name of the joint to be changed
* @param new_origin The new transform associated with the joint
* @return True if successful.
*/
virtual bool changeJointOrigin(const std::string& name, const Eigen::Isometry3d& new_origin) = 0;
/**
* @brief Changes the position limits associated with a joint
* @param joint_name Name of the joint to be updated
* @param limits New position limits to be set as the joint limits
* @returnTrue if successful.
*/
virtual bool changeJointPositionLimits(const std::string& name, double lower, double upper) = 0;
/**
* @brief Changes the velocity limits associated with a joint
* @param joint_name Name of the joint to be updated
* @param limits New velocity limits to be set as the joint limits
* @return
*/
virtual bool changeJointVelocityLimits(const std::string& name, double limit) = 0;
/**
* @brief Changes the acceleration limits associated with a joint
* @param joint_name Name of the joint to be updated
* @param limits New acceleration limits to be set as the joint limits
* @return
*/
virtual bool changeJointAccelerationLimits(const std::string& name, double limit) = 0;
/**
* @brief Merge a scene into the current solver
* @param scene_graph Const ref to the graph to be merged
* @param joint The joint that connects current scene with the inserted scene
* @param prefix string Will be prepended to every link and joint of the merged scene
* @return Return False if any link or joint name collides with current solver, otherwise True
* The prefix argument is meant to allow adding multiple copies of the same subgraph with different names
*/
virtual bool insertSceneGraph(const SceneGraph& scene_graph, const Joint& joint, const std::string& prefix = "") = 0;
};
} // namespace tesseract_scene_graph
#endif // TESSERACT_STATE_SOLVER_MUTABLE_STATE_SOLVER_H
| 36.78125 | 119 | 0.729652 | [
"transform"
] |
3a73eb89b77786b07fc0a4df7da815cb6181cc97 | 478 | h | C | DirectX11-ModelViewer/SubMesh.h | Ym39/DirectX11-ModelViewer | 7772df37e6dddf49f0e49856336c9fdb50ff1d68 | [
"MIT"
] | null | null | null | DirectX11-ModelViewer/SubMesh.h | Ym39/DirectX11-ModelViewer | 7772df37e6dddf49f0e49856336c9fdb50ff1d68 | [
"MIT"
] | null | null | null | DirectX11-ModelViewer/SubMesh.h | Ym39/DirectX11-ModelViewer | 7772df37e6dddf49f0e49856336c9fdb50ff1d68 | [
"MIT"
] | null | null | null | #pragma once
#include <d3d11.h>
#include "Utility.h"
class SubMesh
{
public:
SubMesh(const SaveSubMesh& subMesh);
bool Initalize(ID3D11Device* device);
void Render(ID3D11DeviceContext* deviceContext);
void Shutdown();
unsigned int GetIndexCount() const { return indices.size(); }
const vector<InputVertex>& GetVertices() const { return vertices; }
private:
ID3D11Buffer* mVertexBuffer, * mIndexBuffer;
vector<InputVertex> vertices;
vector<unsigned int> indices;
};
| 21.727273 | 68 | 0.757322 | [
"render",
"vector"
] |
3a75342c0a47e06bc7431ef2f6b6d6778f8094aa | 286 | h | C | include/slt_runtime/render.h | FrancoisChabot/slt_engine | 7b84c842456c93b1062caa82b4f13d56a892aa8c | [
"BSL-1.0"
] | null | null | null | include/slt_runtime/render.h | FrancoisChabot/slt_engine | 7b84c842456c93b1062caa82b4f13d56a892aa8c | [
"BSL-1.0"
] | null | null | null | include/slt_runtime/render.h | FrancoisChabot/slt_engine | 7b84c842456c93b1062caa82b4f13d56a892aa8c | [
"BSL-1.0"
] | null | null | null | #ifndef SLT_RUNTIME_RENDER_H
#define SLT_RUNTIME_RENDER_H
#include "slt/color.h"
#include "slt_runtime/drawing/model.h"
namespace slt {
namespace render {
struct FrameScope {
FrameScope();
~FrameScope();
};
void clearFrame(Color const&);
void draw(ModelRef const&);
}
}
#endif
| 13.619048 | 38 | 0.741259 | [
"render",
"model"
] |
3a7648214db36800d9d7ffab3b3242d68459f724 | 28,565 | h | C | include/engine/table.h | zxjcarrot/spitfire | dc598eef8a3865ef3edc94ea07e60d326b2f83e0 | [
"MIT"
] | 20 | 2021-04-10T11:48:30.000Z | 2022-03-23T03:07:01.000Z | include/engine/table.h | zxjcarrot/spitfire | dc598eef8a3865ef3edc94ea07e60d326b2f83e0 | [
"MIT"
] | null | null | null | include/engine/table.h | zxjcarrot/spitfire | dc598eef8a3865ef3edc94ea07e60d326b2f83e0 | [
"MIT"
] | 8 | 2021-08-09T06:34:35.000Z | 2022-03-23T03:07:03.000Z | //
// Created by zxjcarrot on 2020-02-03.
//
#ifndef SPITFIRE_TABLE_H
#define SPITFIRE_TABLE_H
#include "buf/buf_mgr.h"
#include "engine/btreeolc.h"
namespace spitfire {
struct TuplePointer {
pid_t pid;
uint32_t off;
bool IsNull() const {
return (pid == kInvalidPID && off == std::numeric_limits<uint32_t>::max());
}
bool operator==(const TuplePointer &rhs) const {
return pid == rhs.pid && off == rhs.off;
}
bool operator!=(const TuplePointer &rhs) const {
return !operator==(rhs);
}
};
static const TuplePointer kInvalidTuplePointer = {kInvalidPID, std::numeric_limits<uint32_t>::max()};
template<class Key,
class T>
class ClusteredIndex {
public:
ClusteredIndex(ConcurrentBufferManager *mgr) : mgr(mgr), btree(mgr) {}
Status Init(pid_t root_page_pid) {
return btree.Init(root_page_pid);
}
bool Lookup(const Key &k, T &tuple) {
return btree.Lookup(k, tuple);
}
bool Lookup(const Key &k, std::function<BTreeOPResult (const T &)> processor) {
return btree.Lookup(k, processor);
}
pid_t GetRootPid() {
return btree.GetRootPageId();
}
BTreeOPResult
Insert(const T &tuple, std::function<bool(const void *)> predicate = [](const void *) { return false; },
bool upsert = true) {
return btree.Insert(tuple.Key(), tuple, predicate, upsert);
}
BTreeOPResult
Update(const T &tuple, std::function<bool(const void *)> predicate = [](const void *) { return false; }) {
return Insert(tuple.Key(), tuple, predicate);
}
void Delete(const Key &k) {
btree.Erase(k);
}
void Scan(const Key &start_key, std::function<BTreeOPResult(const T &tuple)> scan_processor) {
btree.Scan(start_key, scan_processor);
}
void ScanForUpdate(const Key &start_key, std::function<void(T &, bool &, bool &)> scan_processor) {
btree.ScanForUpdate(start_key, scan_processor);
}
BTreeOPResult LookupForUpdate(const Key &start_key, std::function<bool(T &tuple)> updater) {
return btree.LookupForUpdate(start_key, updater);
}
typename BTree<Key, T>::BTreeStats GetStats() {
return btree.GetStats();
}
private:
ConcurrentBufferManager *mgr;
BTree<Key, T> btree;
};
template<class Key,
class T>
class HeapTable {
public:
struct HeapTablePage {
T tuples[(kPageSize - sizeof(uint16_t) - sizeof(pid_t)) / sizeof(T)];
pid_t next_page_pid;
uint16_t num_tuples_in_page;
char ___padding___[kPageSize - sizeof(tuples) - sizeof(num_tuples_in_page) - sizeof(next_page_pid)];
constexpr static HeapTablePage *dummy = static_cast<HeapTablePage *>(nullptr);
constexpr static size_t kMaxNumTuples = sizeof(tuples) / sizeof(T);
static pid_t *RefNextPagePid(ConcurrentBufferManager::PageAccessor &accessor) {
auto offset = static_cast<uint32_t>(reinterpret_cast<char *>(&dummy->next_page_pid) -
reinterpret_cast<char *>(dummy));
auto size = sizeof(pid_t);
auto slice = accessor.PrepareForWrite(offset, size);
return reinterpret_cast<pid_t *>(slice.data());
}
static pid_t GetNextPagePid(ConcurrentBufferManager::PageAccessor &accessor) {
auto offset = static_cast<uint32_t>(reinterpret_cast<char *>(&dummy->next_page_pid) -
reinterpret_cast<char *>(dummy));
auto size = sizeof(pid_t);
auto slice = accessor.PrepareForRead(offset, size);
return *reinterpret_cast<pid_t *>(slice.data());
}
static uint16_t *RefNumTuples(ConcurrentBufferManager::PageAccessor &accessor) {
auto offset = static_cast<uint32_t>(reinterpret_cast<char *>(&dummy->num_tuples_in_page) -
reinterpret_cast<char *>(dummy));
auto size = sizeof(uint16_t);
auto slice = accessor.PrepareForWrite(offset, size);
return reinterpret_cast<uint16_t *>(slice.data());
}
static uint16_t GetNumTuples(ConcurrentBufferManager::PageAccessor &accessor) {
auto offset = static_cast<uint32_t>(reinterpret_cast<char *>(&dummy->num_tuples_in_page) -
reinterpret_cast<char *>(dummy));
auto size = sizeof(uint16_t);
auto slice = accessor.PrepareForRead(offset, size);
return *reinterpret_cast<uint16_t *>(slice.data());
}
static const T *GetTuples(ConcurrentBufferManager::PageAccessor &accessor, int pos, int num) {
assert(pos + num <= kMaxNumTuples);
auto offset = static_cast<uint32_t>(reinterpret_cast<char *>(&dummy->tuples[pos]) -
reinterpret_cast<char *>(dummy));
auto size = sizeof(T) * num;
auto slice = accessor.PrepareForRead(offset, size);
return reinterpret_cast<T *>(slice.data());
}
static T GetTuple(ConcurrentBufferManager::PageAccessor &accessor, int pos) {
return *GetTuples(accessor, pos, 1);
}
static uint32_t ComputeTuplePosition(int pos) {
return static_cast<uint32_t>(reinterpret_cast<char *>(&dummy->tuples[pos]) -
reinterpret_cast<char *>(dummy));
}
static T *RefTuples(ConcurrentBufferManager::PageAccessor &accessor, int pos, int num) {
assert(pos + num <= kMaxNumTuples);
auto offset = static_cast<uint32_t>(reinterpret_cast<char *>(&dummy->tuples[pos]) -
reinterpret_cast<char *>(dummy));
auto size = sizeof(T) * num;
auto slice = accessor.PrepareForWrite(offset, size);
return reinterpret_cast<T *>(slice.data());
}
static T *RefTuple(ConcurrentBufferManager::PageAccessor &accessor, int pos) {
return RefTuples(accessor, pos, 1);
}
};
static_assert(sizeof(HeapTablePage) == kPageSize, "sizeof(HeapTablePage) != kPageSize");
HeapTable() : mgr(nullptr), meta_page_pid(kInvalidPID) {}
Status Init(const pid_t meta_page_pid, ConcurrentBufferManager *mgr, bool new_table) {
this->meta_page_pid = meta_page_pid;
this->mgr = mgr;
PageDesc *meta_page_desc;
if (this->meta_page_pid == kInvalidPID) {
Status s = mgr->NewPage(this->meta_page_pid);
if (!s.ok())
return s;
}
Status s = mgr->Get(this->meta_page_pid, meta_page_desc, ConcurrentBufferManager::PageOPIntent::INTENT_READ);
if (!s.ok())
return s;
DeferCode c([meta_page_desc, mgr]() { mgr->Put(meta_page_desc); });
if (new_table) {
pid_t head_page_pid;
s = mgr->NewPage(head_page_pid);
if (!s.ok())
return s;
PageDesc *new_page_desc;
s = mgr->Get(head_page_pid, new_page_desc, ConcurrentBufferManager::PageOPIntent::INTENT_WRITE);
if (!s.ok())
return s;
// Initialize a head page
InitializeHeapTablePage(new_page_desc, kInvalidPID);
// Link the meta page with the head page
meta_page_desc->LatchExclusive();
InitializeHeapTablePage(meta_page_desc, head_page_pid);
meta_page_desc->UnlatchExclusive();
mgr->Put(new_page_desc);
}
return Status::OK();
}
bool Lookup(const Key &k, T &tuple) {
bool found = false;
Scan([&, this](TuplePointer pointer, const T &t) -> bool {
if (tuple.Key() == k) {
tuple = t;
found = true;
return true;
}
return false;
});
return found;
}
void Insert(const T &tuple) {
TuplePointer dummy;
Insert(tuple, dummy);
}
void CreateNewHeadPage() {
PageDesc *meta_page_desc = nullptr;
Status s = mgr->Get(meta_page_pid, meta_page_desc, ConcurrentBufferManager::PageOPIntent::INTENT_READ);
assert(s.ok());
meta_page_desc->LatchExclusive();
auto accessor = mgr->GetPageAccessorFromDesc(meta_page_desc);
HeapTablePage *meta_page = nullptr;
auto head_page_pid = meta_page->GetNextPagePid(accessor);
if (head_page_pid == kInvalidPID) {
pid_t head_page_pid;
s = mgr->NewPage(head_page_pid);
assert(s.ok());
PageDesc *new_page_desc;
s = mgr->Get(head_page_pid, new_page_desc, ConcurrentBufferManager::PageOPIntent::INTENT_WRITE);
assert(s.ok());
// Initialize the head page
InitializeHeapTablePage(new_page_desc, kInvalidPID);
// Link the meta page with the head page
InitializeHeapTablePage(meta_page_desc, head_page_pid);
mgr->Put(new_page_desc);
}
meta_page_desc->UnlatchExclusive();
mgr->Put(meta_page_desc);
}
void Insert(const T &tuple, TuplePointer &result_holder) {
start:
{
auto head_page_pid = GetHeadPagePid();
if (head_page_pid == kInvalidPID) {
// Empty page list.
// Try to create a head page by grabing the latch on the meta page.
CreateNewHeadPage();
goto start;
}
PageDesc *pd = nullptr;
Status s = mgr->Get(head_page_pid, pd);
if (!s.ok()) {
goto start;
}
pd->LatchExclusive();
auto accessor = mgr->GetPageAccessorFromDesc(pd);
HeapTablePage *hp = nullptr;
int n_tuples = hp->GetNumTuples(accessor);
if (n_tuples >= hp->kMaxNumTuples) {
pd->UnlatchExclusive();
mgr->Put(pd);
PageDesc *meta_page_desc = nullptr;
Status s = mgr->Get(meta_page_pid, meta_page_desc, ConcurrentBufferManager::PageOPIntent::INTENT_WRITE);
assert(s.ok());
meta_page_desc->LatchExclusive();
auto meta_page_accessor = mgr->GetPageAccessorFromDesc(meta_page_desc);
HeapTablePage *meta_page = nullptr;
auto latest_head_page_pid = meta_page->GetNextPagePid(meta_page_accessor);
if (latest_head_page_pid != head_page_pid) {
meta_page_desc->UnlatchExclusive();
mgr->Put(meta_page_desc);
// New head page has been installed, retry the insertion.
goto retry;
}
// Create a new head page
pid_t new_head_page_pid = kInvalidPID;
PageDesc *new_head_page_desc = nullptr;
s = mgr->NewPage(new_head_page_pid);
assert(s.ok());
s = mgr->Get(new_head_page_pid, new_head_page_desc,
ConcurrentBufferManager::PageOPIntent::INTENT_WRITE);
assert(s.ok());
InitializeHeapTablePage(new_head_page_desc, head_page_pid);
mgr->Put(new_head_page_desc);
*meta_page->RefNextPagePid(meta_page_accessor) = new_head_page_pid;
meta_page_desc->UnlatchExclusive();
mgr->Put(meta_page_desc);
goto retry; // Installed the new head page, retry the insertion.
} else {
result_holder = {head_page_pid, hp->ComputeTuplePosition(n_tuples)};
*hp->RefTuple(accessor, n_tuples) = tuple;
(*hp->RefNumTuples(accessor))++;
}
pd->UnlatchExclusive();
mgr->Put(pd);
return;
}
retry:
Insert(tuple, result_holder);
}
void Update(const T &tuple) {
auto target_key = tuple.Key();
std::vector<TuplePointer> ptrs;
Scan([&, this](TuplePointer pointer, const T &t) -> bool {
if (t.Key() == target_key) {
ptrs.push_back(pointer);
}
return false;
});
for (auto ptr : ptrs) {
PageDesc *pd = nullptr;
Status s = mgr->Get(ptr.pid, pd, ConcurrentBufferManager::PageOPIntent::INTENT_WRITE);
assert(s.ok());
pd->LatchExclusive();
auto accessor = mgr->GetPageAccessorFromDesc(pd);
HeapTablePage *hp = nullptr;
*hp->RefTuple(accessor, ptr.off) = tuple;
pd->UnlatchExclusive();
mgr->Put(pd);
}
}
void Delete(const Key &k) {
throw std::runtime_error("Not implemented yet");
}
void Scan(const Key &start_key, std::function<bool(TuplePointer pointer, const T &tuple)> scan_processor) {
Scan([&, this](TuplePointer pointer, const T &tuple) -> bool {
if (tuple.Key() >= start_key) {
return scan_processor(pointer, tuple);
}
return false;
});
}
void Scan(std::function<bool(TuplePointer pointer, const T &tuple)> scan_processor) {
// Walk the list of pages using classic latch-coupling protocol:
// Release the latch of the previous page only
// after the current page is properly latched.
auto prev_page_pid = GetMetaPagePid();
pid_t cur_page_pid = kInvalidPID;
HeapTablePage *prev_page = nullptr;
HeapTablePage *cur_page = nullptr;
PageDesc *prev_page_desc = nullptr;
PageDesc *cur_page_desc = nullptr;
Status s = mgr->Get(prev_page_pid, prev_page_desc, ConcurrentBufferManager::PageOPIntent::INTENT_READ);
assert(s.ok());
prev_page_desc->LatchShared();
{
auto prev_page_accessor = mgr->GetPageAccessorFromDesc(prev_page_desc);
cur_page_pid = prev_page->GetNextPagePid(prev_page_accessor);
}
bool early_exit = false;
while (cur_page_pid != kInvalidPID) {
s = mgr->Get(cur_page_pid, cur_page_desc, ConcurrentBufferManager::PageOPIntent::INTENT_READ);
assert(s.ok());
cur_page_desc->LatchShared();
auto cur_page_accessor = mgr->GetPageAccessorFromDesc(cur_page_desc);
pid_t next_page_pid = cur_page->GetNextPagePid(cur_page_accessor);
// Release the latch of the previous page
// only after the current page is latched.
prev_page_desc->UnlatchShared();
mgr->Put(prev_page_desc);
HeapTablePage *hp = nullptr;
int n_tuples = hp->GetNumTuples(cur_page_accessor);
const T *tuples = nullptr;
if (n_tuples) {
tuples = hp->GetTuples(cur_page_accessor, 0, n_tuples);
} else {
n_tuples = 0;
}
for (int i = 0; i < n_tuples && early_exit == false; ++i) {
early_exit = scan_processor(TuplePointer{cur_page_pid, hp->ComputeTuplePosition(i)}, tuples[i]);
}
prev_page_desc = cur_page_desc;
cur_page_pid = next_page_pid;
if (early_exit == true) {
break;
}
}
prev_page_desc->UnlatchShared();
mgr->Put(prev_page_desc);
}
void Scan(std::function<bool(TuplePointer pointer, const T &tuple, bool & skip_this_page)> scan_processor) {
// Walk the list of pages using classic latch-coupling protocol:
// Release the latch of the previous page only
// after the current page is properly latched.
auto prev_page_pid = GetMetaPagePid();
pid_t cur_page_pid = kInvalidPID;
HeapTablePage *prev_page = nullptr;
HeapTablePage *cur_page = nullptr;
PageDesc *prev_page_desc = nullptr;
PageDesc *cur_page_desc = nullptr;
Status s = mgr->Get(prev_page_pid, prev_page_desc, ConcurrentBufferManager::PageOPIntent::INTENT_READ);
assert(s.ok());
prev_page_desc->LatchShared();
{
auto prev_page_accessor = mgr->GetPageAccessorFromDesc(prev_page_desc);
cur_page_pid = prev_page->GetNextPagePid(prev_page_accessor);
}
bool early_exit = false;
while (cur_page_pid != kInvalidPID) {
s = mgr->Get(cur_page_pid, cur_page_desc, ConcurrentBufferManager::PageOPIntent::INTENT_READ);
assert(s.ok());
cur_page_desc->LatchShared();
auto cur_page_accessor = mgr->GetPageAccessorFromDesc(cur_page_desc);
pid_t next_page_pid = cur_page->GetNextPagePid(cur_page_accessor);
// Release the latch of the previous page
// only after the current page is latched.
prev_page_desc->UnlatchShared();
mgr->Put(prev_page_desc);
HeapTablePage *hp = nullptr;
int n_tuples = hp->GetNumTuples(cur_page_accessor);
const T *tuples = nullptr;
if (n_tuples) {
tuples = hp->GetTuples(cur_page_accessor, 0, n_tuples);
} else {
n_tuples = 0;
}
for (int i = 0; i < n_tuples && early_exit == false; ++i) {
bool skip_this_page = false;
early_exit = scan_processor(TuplePointer{cur_page_pid, hp->ComputeTuplePosition(i)}, tuples[i], skip_this_page);
if (skip_this_page == true) {
break;
}
}
prev_page_desc = cur_page_desc;
cur_page_pid = next_page_pid;
if (early_exit == true) {
break;
}
}
prev_page_desc->UnlatchShared();
mgr->Put(prev_page_desc);
}
pid_t GetHeadPagePid() {
PageDesc *meta_page_desc = nullptr;
Status s = mgr->Get(meta_page_pid, meta_page_desc, ConcurrentBufferManager::PageOPIntent::INTENT_READ);
assert(s.ok());
meta_page_desc->LatchShared();
auto accessor = mgr->GetPageAccessorFromDesc(meta_page_desc);
HeapTablePage *meta_page = nullptr;
auto head_page_pid = meta_page->GetNextPagePid(accessor);
meta_page_desc->UnlatchShared();
mgr->Put(meta_page_desc);
return head_page_pid;
}
pid_t GetMetaPagePid() {
return meta_page_pid;
}
void PurgePages(const std::unordered_set<pid_t> & purge_set) {
// Walk the list of pages using classic latch-coupling protocol:
// Release the latch of the previous page only
// after the current page is properly latched.
auto prev_page_pid = GetMetaPagePid();
pid_t cur_page_pid = kInvalidPID;
HeapTablePage *prev_page = nullptr;
HeapTablePage *cur_page = nullptr;
PageDesc *prev_page_desc = nullptr;
PageDesc *cur_page_desc = nullptr;
Status s = mgr->Get(prev_page_pid, prev_page_desc, ConcurrentBufferManager::PageOPIntent::INTENT_READ);
assert(s.ok());
prev_page_desc->LatchExclusive();
{
auto prev_page_accessor = mgr->GetPageAccessorFromDesc(prev_page_desc);
cur_page_pid = prev_page->GetNextPagePid(prev_page_accessor);
}
// Unlink the pages from the list so that future readers won't access these pages.
std::unordered_set<pid_t> unlinked_pages;
while (cur_page_pid != kInvalidPID) {
s = mgr->Get(cur_page_pid, cur_page_desc, ConcurrentBufferManager::PageOPIntent::INTENT_READ);
assert(s.ok());
cur_page_desc->LatchExclusive();
auto cur_page_accessor = mgr->GetPageAccessorFromDesc(cur_page_desc);
pid_t next_page_pid = cur_page->GetNextPagePid(cur_page_accessor);
if (purge_set.find(cur_page_pid) != purge_set.end()) {
auto prev_page_accessor = mgr->GetPageAccessorFromDesc(prev_page_desc);
*prev_page->RefNextPagePid(prev_page_accessor) = next_page_pid;
unlinked_pages.insert(cur_page_pid);
cur_page_desc->UnlatchExclusive();
mgr->Put(cur_page_desc);
} else {
prev_page_desc->UnlatchExclusive();
mgr->Put(prev_page_desc);
prev_page_desc = cur_page_desc;
prev_page = cur_page;
prev_page_pid = cur_page_pid;
}
cur_page_pid = next_page_pid;
}
prev_page_desc->UnlatchExclusive();
mgr->Put(prev_page_desc);
mgr->EvictPurgablePages(unlinked_pages);
// Do final purging on the unlinked pages
for (auto pid : unlinked_pages) {
mgr->Flush(pid, false, false);
mgr->Flush(pid, false, false);
}
for (auto pid : unlinked_pages) {
mgr->FreePage(pid);
}
}
private:
void InitializeHeapTablePage(PageDesc *new_page_desc, pid_t next_page_pid) {
auto page_accessor = mgr->GetPageAccessorFromDesc(new_page_desc);
HeapTablePage *heap_page = nullptr;
*heap_page->RefNextPagePid(page_accessor) = next_page_pid;
*heap_page->RefNumTuples(page_accessor) = 0;
page_accessor.FinishAccess();
}
ConcurrentBufferManager *mgr;
pid_t meta_page_pid;
};
template<class Key,
class T,
int kNumParts = 16>
class PartitionedHeapTable{
public:
struct PartitionedHeapTablePage {
lsn_t lsn;
pid_t part_ptrs[(kPageSize - sizeof(uint16_t) - sizeof(lsn_t)) / sizeof(pid_t)];
uint16_t num_parts;
char ___padding___[kPageSize - sizeof(part_ptrs) - sizeof(lsn_t) - sizeof(num_parts)];
constexpr static PartitionedHeapTablePage *dummy = static_cast<PartitionedHeapTablePage *>(nullptr);
constexpr static size_t kMaxNumTuples = sizeof(part_ptrs) / sizeof(pid_t);
static uint16_t *RefNumParts(ConcurrentBufferManager::PageAccessor &accessor) {
auto offset = static_cast<uint32_t>(reinterpret_cast<char *>(&dummy->num_parts) -
reinterpret_cast<char *>(dummy));
auto size = sizeof(uint16_t);
auto slice = accessor.PrepareForWrite(offset, size);
return reinterpret_cast<uint16_t *>(slice.data());
}
static uint16_t GetNumParts(ConcurrentBufferManager::PageAccessor &accessor) {
auto offset = static_cast<uint32_t>(reinterpret_cast<char *>(&dummy->num_parts) -
reinterpret_cast<char *>(dummy));
auto size = sizeof(uint16_t);
auto slice = accessor.PrepareForRead(offset, size);
return *reinterpret_cast<uint16_t *>(slice.data());
}
static const pid_t *GetPartPtrs(ConcurrentBufferManager::PageAccessor &accessor, int pos, int num) {
assert(pos + num <= kMaxNumTuples);
auto offset = static_cast<uint32_t>(reinterpret_cast<char *>(&dummy->part_ptrs[pos]) -
reinterpret_cast<char *>(dummy));
auto size = sizeof(pid_t) * num;
auto slice = accessor.PrepareForRead(offset, size);
return reinterpret_cast<pid_t *>(slice.data());
}
static pid_t GetPartPtr(ConcurrentBufferManager::PageAccessor &accessor, int pos) {
return *GetPartPtrs(accessor, pos, 1);
}
static pid_t *RefPartPtrs(ConcurrentBufferManager::PageAccessor &accessor, int pos, int num) {
assert(pos + num <= kMaxNumTuples);
auto offset = static_cast<uint32_t>(reinterpret_cast<char *>(&dummy->part_ptrs[pos]) -
reinterpret_cast<char *>(dummy));
auto size = sizeof(pid_t) * num;
auto slice = accessor.PrepareForWrite(offset, size);
return reinterpret_cast<pid_t *>(slice.data());
}
static pid_t *RefPartPtr(ConcurrentBufferManager::PageAccessor &accessor, int pos) {
return RefPartPtrs(accessor, pos, 1);
}
};
static_assert(sizeof(PartitionedHeapTablePage) == kPageSize, "sizeof(PartitionedHeapTablePage) != kPageSize");
PartitionedHeapTable(int num_parts = kNumParts) : mgr(nullptr), num_parts(num_parts), parts(nullptr) {}
~PartitionedHeapTable() {
delete[] parts;
}
Status Init(const pid_t meta_page_pid, ConcurrentBufferManager *mgr, bool new_table) {
this->meta_page_pid = meta_page_pid;
this->mgr = mgr;
PageDesc *meta_page_desc;
if (this->meta_page_pid == kInvalidPID) {
Status s = mgr->NewPage(this->meta_page_pid);
if (!s.ok())
return s;
}
Status s = mgr->Get(this->meta_page_pid, meta_page_desc, ConcurrentBufferManager::PageOPIntent::INTENT_READ);
if (!s.ok())
return s;
DeferCode c([meta_page_desc, mgr]() { mgr->Put(meta_page_desc); });
parts = new HeapTable<Key, T>[num_parts];
if (new_table) {
PartitionedHeapTablePage * meta_page = nullptr;
for (int i = 0; i < num_parts; ++i) {
pid_t part_meta_page_pid = kInvalidPID;
s = parts[i].Init(part_meta_page_pid, mgr, new_table);
if (!s.ok())
return s;
part_meta_page_pid = parts[i].GetMetaPagePid();
assert(part_meta_page_pid != kInvalidPID);
auto accessor = mgr->GetPageAccessorFromDesc(meta_page_desc);
meta_page_desc->LatchExclusive();
*meta_page->RefPartPtr(accessor, i) = part_meta_page_pid;
*meta_page->RefNumParts(accessor) = num_parts;
meta_page_desc->UnlatchExclusive();
}
} else {
PartitionedHeapTablePage * meta_page = nullptr;
auto accessor = mgr->GetPageAccessorFromDesc(meta_page_desc);
num_parts = meta_page->GetNumParts(accessor);
for (int i = 0; i < num_parts; ++i) {
pid_t part_meta_page_pid = meta_page->GetPartPtr(accessor, i);
assert(part_meta_page_pid != kInvalidPID);
s = parts[i].Init(part_meta_page_pid, mgr, new_table);
if (!s.ok())
return s;
}
}
return Status::OK();
}
bool Lookup(const Key &k, T &tuple) {
auto target_key = tuple.Key();
return parts[GetPartitionNum(target_key)].Lookup(k, tuple);
}
void Insert(const T &tuple) {
TuplePointer dummy;
Insert(tuple, dummy);
}
void Insert(const T &tuple, TuplePointer &result_holder) {
auto target_key = tuple.Key();
auto part_idx = GetPartitionNum(target_key);
parts[part_idx].Insert(tuple, result_holder);
}
inline int GetPartitionNum(const Key & key) {
return std::hash<Key>()(key) % num_parts;
}
void Update(const T &tuple) {
auto target_key = tuple.Key();
parts[GetPartitionNum(target_key)].Update(tuple);
}
void Delete(const Key &k) {
throw std::runtime_error("Not implemented yet");
}
void Scan(const Key &start_key, std::function<bool(TuplePointer pointer, const T &tuple)> scan_processor) {
Scan([&, this](TuplePointer pointer, const T &tuple) -> bool {
if (tuple.Key() >= start_key) {
return scan_processor(pointer, tuple);
}
return false;
});
}
void Scan(std::function<bool(TuplePointer pointer, const T &tuple)> scan_processor) {
for (int i = 0; i < num_parts; ++i) {
parts[i].Scan(scan_processor);
}
}
void Scan(std::function<bool(TuplePointer pointer, const T &tuple, bool & skip_this_page)> scan_processor) {
for (int i = 0; i < num_parts; ++i) {
parts[i].Scan(scan_processor);
}
}
pid_t GetMetaPagePid() {
return meta_page_pid;
}
void PurgePages(const std::unordered_set<pid_t> &purge_set) {
for (int i = 0; i < num_parts; ++i) {
parts[i].PurgePages(purge_set);
}
}
private:
ConcurrentBufferManager *mgr;
pid_t meta_page_pid;
int num_parts;
HeapTable<Key, T> *parts;
};
}
#endif //SPITFIRE_TABLE_H
| 38.445491 | 128 | 0.591493 | [
"vector"
] |
3a790817ebe1a4fd6a93641a7021e23ba62ba850 | 3,870 | h | C | src/storage/orm_users.h | Telecominfraproject/wlan-cloud-ucentralsec | b14eba63c3366f01a5cda3122002857598919088 | [
"BSD-3-Clause"
] | 2 | 2021-08-04T02:31:23.000Z | 2022-01-06T02:04:45.000Z | src/storage/orm_users.h | Telecominfraproject/wlan-cloud-ucentralsec | b14eba63c3366f01a5cda3122002857598919088 | [
"BSD-3-Clause"
] | 3 | 2021-08-23T14:39:10.000Z | 2022-01-06T02:04:16.000Z | src/storage/orm_users.h | Telecominfraproject/wlan-cloud-ucentralsec | b14eba63c3366f01a5cda3122002857598919088 | [
"BSD-3-Clause"
] | 2 | 2022-01-03T16:16:44.000Z | 2022-03-16T07:18:06.000Z | //
// Created by stephane bourque on 2021-12-27.
//
#pragma once
#include "framework/orm.h"
#include "RESTObjects/RESTAPI_SecurityObjects.h"
namespace OpenWifi {
typedef Poco::Tuple<
std::string, // Id = 0;
std::string, // name;
std::string, // description;
std::string, // avatar;
std::string, // email;
bool, // bool validated = false;
std::string, // validationEmail;
uint64_t, // validationDate = 0;
uint64_t, // creationDate = 0;
std::string, // validationURI;
bool, // bool changePassword = true;
uint64_t, // lastLogin = 0;
std::string, // currentLoginURI;
uint64_t, // lastPasswordChange = 0;
uint64_t, // lastEmailCheck = 0;
bool, // bool waitingForEmailCheck = false;
std::string, // locale;
std::string, // notes;
std::string, // location;
std::string, // owner;
bool, // bool suspended = false;
bool, // bool blackListed = false;
std::string, // userRole;
std::string, // userTypeProprietaryInfo;
std::string, // securityPolicy;
uint64_t, // securityPolicyChange;
std::string, // currentPassword;
std::string, // lastPasswords;
std::string, // oauthType;
std::string, // oauthUserInfo;
uint64_t // modified
> UserInfoRecordTuple;
typedef std::vector <UserInfoRecordTuple> UserInfoRecordTupleList;
class UserCache : public ORM::DBCache<SecurityObjects::UserInfo> {
public:
UserCache(unsigned Size, unsigned TimeOut, bool Users);
void UpdateCache(const SecurityObjects::UserInfo &R) override;
void Create(const SecurityObjects::UserInfo &R) override;
bool GetFromCache(const std::string &FieldName, const std::string &Value, SecurityObjects::UserInfo &R) override;
void Delete(const std::string &FieldName, const std::string &Value) override;
private:
std::mutex Mutex_;
bool UsersOnly_;
std::unique_ptr<Poco::ExpireLRUCache<std::string,SecurityObjects::UserInfo>> CacheById_;
std::unique_ptr<Poco::ExpireLRUCache<std::string,std::string>> CacheByEMail_;
};
class BaseUserDB : public ORM::DB<UserInfoRecordTuple, SecurityObjects::UserInfo> {
public:
const uint32_t CurrentVersion = 1;
BaseUserDB( const std::string &name, const std::string &shortname, OpenWifi::DBType T, Poco::Data::SessionPool & P, Poco::Logger &L, UserCache * Cache, bool users);
bool CreateUser(const std::string & Admin, SecurityObjects::UserInfo & NewUser, bool PasswordHashedAlready = false );
bool GetUserByEmail(const std::string & email, SecurityObjects::UserInfo & User);
bool GetUserById(const std::string &Id, SecurityObjects::UserInfo &User);
bool GetUsers( uint64_t Offset, uint64_t HowMany, SecurityObjects::UserInfoVec & Users, const std::string & WhereClause="");
bool UpdateUserInfo(const std::string & Admin, SecurityObjects::USER_ID_TYPE & Id, const SecurityObjects::UserInfo &UInfo);
bool DeleteUser(const std::string & Admin, const SecurityObjects::USER_ID_TYPE & Id);
bool DeleteUsers(const std::string & Admin, const std::string & owner);
bool SetLastLogin(const std::string &Id);
bool SetAvatar(const std::string &Id, const std::string &Value);
inline uint32_t Version() override { return CurrentVersion;}
bool Upgrade(uint32_t from, uint32_t &to) override;
bool UsersOnly_;
};
}
| 45 | 172 | 0.599742 | [
"vector"
] |
3a7a5ec71eabb00490c8b89adb9ac90048ddfee2 | 7,287 | c | C | c2drox-perl6/c/GLib/gio/gdbusobjectmanager.c | andydude/droxtools | d608ceb715908fb00398c0d28eee74286fef3750 | [
"MIT"
] | 118 | 2015-01-09T03:36:48.000Z | 2021-11-09T10:40:01.000Z | c2drox-perl6/c/GLib/gio/gdbusobjectmanager.c | andydude/droxtools | d608ceb715908fb00398c0d28eee74286fef3750 | [
"MIT"
] | 2 | 2015-07-14T06:18:29.000Z | 2016-03-14T04:00:45.000Z | c2drox-perl6/c/GLib/gio/gdbusobjectmanager.c | andydude/droxtools | d608ceb715908fb00398c0d28eee74286fef3750 | [
"MIT"
] | 56 | 2015-01-06T01:43:58.000Z | 2019-06-22T13:52:20.000Z | /* GDBus - GLib D-Bus Library
*
* Copyright (C) 2008-2010 Red Hat, Inc.
*
* 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 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.
*
* Author: David Zeuthen <davidz@redhat.com>
*/
#include "config.h"
#include "gdbusobject.h"
#include "gdbusobjectmanager.h"
#include "gdbusinterface.h"
#include "gdbusutils.h"
#include "glibintl.h"
/**
* SECTION:gdbusobjectmanager
* @short_description: Base type for D-Bus object managers
* @include: gio/gio.h
*
* The #GDBusObjectManager type is the base type for service- and
* client-side implementations of the standardized <ulink
* url="http://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-objectmanager">org.freedesktop.DBus.ObjectManager</ulink>
* interface.
*
* See #GDBusObjectManagerClient for the client-side implementation
* and #GDBusObjectManagerServer for the service-side implementation.
*/
typedef GDBusObjectManagerIface GDBusObjectManagerInterface;
G_DEFINE_INTERFACE (GDBusObjectManager, g_dbus_object_manager, G_TYPE_OBJECT)
static void
g_dbus_object_manager_default_init (GDBusObjectManagerIface *iface)
{
/**
* GDBusObjectManager::object-added:
* @manager: The #GDBusObjectManager emitting the signal.
* @object: The #GDBusObject that was added.
*
* Emitted when @object is added to @manager.
*
* Since: 2.30
*/
g_signal_new ("object-added",
G_TYPE_FROM_INTERFACE (iface),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GDBusObjectManagerIface, object_added),
NULL,
NULL,
g_cclosure_marshal_VOID__OBJECT,
G_TYPE_NONE,
1,
G_TYPE_DBUS_OBJECT);
/**
* GDBusObjectManager::object-removed:
* @manager: The #GDBusObjectManager emitting the signal.
* @object: The #GDBusObject that was removed.
*
* Emitted when @object is removed from @manager.
*
* Since: 2.30
*/
g_signal_new ("object-removed",
G_TYPE_FROM_INTERFACE (iface),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GDBusObjectManagerIface, object_removed),
NULL,
NULL,
g_cclosure_marshal_VOID__OBJECT,
G_TYPE_NONE,
1,
G_TYPE_DBUS_OBJECT);
/**
* GDBusObjectManager::interface-added:
* @manager: The #GDBusObjectManager emitting the signal.
* @object: The #GDBusObject on which an interface was added.
* @interface: The #GDBusInterface that was added.
*
* Emitted when @interface is added to @object.
*
* This signal exists purely as a convenience to avoid having to
* connect signals to all objects managed by @manager.
*
* Since: 2.30
*/
g_signal_new ("interface-added",
G_TYPE_FROM_INTERFACE (iface),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GDBusObjectManagerIface, interface_added),
NULL,
NULL,
NULL,
G_TYPE_NONE,
2,
G_TYPE_DBUS_OBJECT,
G_TYPE_DBUS_INTERFACE);
/**
* GDBusObjectManager::interface-removed:
* @manager: The #GDBusObjectManager emitting the signal.
* @object: The #GDBusObject on which an interface was removed.
* @interface: The #GDBusInterface that was removed.
*
* Emitted when @interface has been removed from @object.
*
* This signal exists purely as a convenience to avoid having to
* connect signals to all objects managed by @manager.
*
* Since: 2.30
*/
g_signal_new ("interface-removed",
G_TYPE_FROM_INTERFACE (iface),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (GDBusObjectManagerIface, interface_removed),
NULL,
NULL,
NULL,
G_TYPE_NONE,
2,
G_TYPE_DBUS_OBJECT,
G_TYPE_DBUS_INTERFACE);
}
/* ---------------------------------------------------------------------------------------------------- */
/**
* g_dbus_object_manager_get_object_path:
* @manager: A #GDBusObjectManager.
*
* Gets the object path that @manager is for.
*
* Returns: A string owned by @manager. Do not free.
*
* Since: 2.30
*/
const gchar *
g_dbus_object_manager_get_object_path (GDBusObjectManager *manager)
{
GDBusObjectManagerIface *iface = G_DBUS_OBJECT_MANAGER_GET_IFACE (manager);
return iface->get_object_path (manager);
}
/**
* g_dbus_object_manager_get_objects:
* @manager: A #GDBusObjectManager.
*
* Gets all #GDBusObject objects known to @manager.
*
* Returns: (transfer full) (element-type GDBusObject): A list of
* #GDBusObject objects. The returned list should be freed with
* g_list_free() after each element has been freed with
* g_object_unref().
*
* Since: 2.30
*/
GList *
g_dbus_object_manager_get_objects (GDBusObjectManager *manager)
{
GDBusObjectManagerIface *iface = G_DBUS_OBJECT_MANAGER_GET_IFACE (manager);
return iface->get_objects (manager);
}
/**
* g_dbus_object_manager_get_object:
* @manager: A #GDBusObjectManager.
* @object_path: Object path to lookup.
*
* Gets the #GDBusObjectProxy at @object_path, if any.
*
* Returns: (transfer full): A #GDBusObject or %NULL. Free with
* g_object_unref().
*
* Since: 2.30
*/
GDBusObject *
g_dbus_object_manager_get_object (GDBusObjectManager *manager,
const gchar *object_path)
{
GDBusObjectManagerIface *iface = G_DBUS_OBJECT_MANAGER_GET_IFACE (manager);
g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
return iface->get_object (manager, object_path);
}
/**
* g_dbus_object_manager_get_interface:
* @manager: A #GDBusObjectManager.
* @object_path: Object path to lookup.
* @interface_name: D-Bus interface name to lookup.
*
* Gets the interface proxy for @interface_name at @object_path, if
* any.
*
* Returns: (transfer full): A #GDBusInterface instance or %NULL. Free
* with g_object_unref().
*
* Since: 2.30
*/
GDBusInterface *
g_dbus_object_manager_get_interface (GDBusObjectManager *manager,
const gchar *object_path,
const gchar *interface_name)
{
GDBusObjectManagerIface *iface = G_DBUS_OBJECT_MANAGER_GET_IFACE (manager);
g_return_val_if_fail (g_variant_is_object_path (object_path), NULL);
g_return_val_if_fail (g_dbus_is_interface_name (interface_name), NULL);
return iface->get_interface (manager, object_path, interface_name);
}
| 31.960526 | 141 | 0.663648 | [
"object"
] |
3a85fc041069091a59843e806c5a049a360ba81e | 6,375 | c | C | ext/phalcon/mvc/model/validator/ip.zep.c | nhawa/phalcontest | 711e971d02af20b46d8f130f1d80fa7a7f01732f | [
"BSD-3-Clause"
] | null | null | null | ext/phalcon/mvc/model/validator/ip.zep.c | nhawa/phalcontest | 711e971d02af20b46d8f130f1d80fa7a7f01732f | [
"BSD-3-Clause"
] | null | null | null | ext/phalcon/mvc/model/validator/ip.zep.c | nhawa/phalcontest | 711e971d02af20b46d8f130f1d80fa7a7f01732f | [
"BSD-3-Clause"
] | null | null | null |
#ifdef HAVE_CONFIG_H
#include "../../../../ext_config.h"
#endif
#include <php.h>
#include "../../../../php_ext.h"
#include "../../../../ext.h"
#include <Zend/zend_operators.h>
#include <Zend/zend_exceptions.h>
#include <Zend/zend_interfaces.h>
#include "kernel/main.h"
#include "kernel/fcall.h"
#include "kernel/memory.h"
#include "kernel/exception.h"
#include "kernel/operators.h"
#include "kernel/array.h"
/**
* Phalcon\Mvc\Model\Validator\IP
*
* Validates that a value is ipv4 address in valid range
*
*<code>
*use Phalcon\Mvc\Model\Validator\Ip;
*
*class Data extends Phalcon\Mvc\Model
*{
*
* public function validation()
* {
* // Any pubic IP
* $this->validate(new IP(array(
* 'field' => 'server_ip',
* 'version' => IP::VERSION_4 | IP::VERSION_6, // v6 and v4. The same if not specified
* 'allowReserved' => false, // False if not specified. Ignored for v6
* 'allowPrivate' => false, // False if not specified
* 'message' => 'IP address has to be correct'
* )));
*
* // Any public v4 address
* $this->validate(new IP(array(
* 'field' => 'ip_4',
* 'version' => IP::VERSION_4,
* 'message' => 'IP address has to be correct'
* )));
*
* // Any v6 address
* $this->validate(new IP(array(
* 'field' => 'ip6',
* 'version' => IP::VERSION_6,
* 'allowPrivate' => true,
* 'message' => 'IP address has to be correct'
* )));
*
* if ($this->validationHasFailed() == true) {
* return false;
* }
* }
*
*}
*</code>
*/
ZEPHIR_INIT_CLASS(Phalcon_Mvc_Model_Validator_Ip) {
ZEPHIR_REGISTER_CLASS_EX(Phalcon\\Mvc\\Model\\Validator, Ip, phalcon, mvc_model_validator_ip, phalcon_mvc_model_validator_ce, phalcon_mvc_model_validator_ip_method_entry, 0);
zend_declare_class_constant_long(phalcon_mvc_model_validator_ip_ce, SL("VERSION_4"), 1048576 TSRMLS_CC);
zend_declare_class_constant_long(phalcon_mvc_model_validator_ip_ce, SL("VERSION_6"), 2097152 TSRMLS_CC);
zend_class_implements(phalcon_mvc_model_validator_ip_ce TSRMLS_CC, 1, phalcon_mvc_model_validatorinterface_ce);
return SUCCESS;
}
/**
* Executes the validator
*/
PHP_METHOD(Phalcon_Mvc_Model_Validator_Ip, validate) {
zval *_6, *_12$$5;
zend_bool _5;
int ZEPHIR_LAST_CALL_STATUS;
zval *record, *field = NULL, *value = NULL, *message = NULL, *version = NULL, *allowPrivate = NULL, *allowReserved = NULL, *options = NULL, *_0 = NULL, *_1 = NULL, *_2 = NULL, *_3 = NULL, *_4 = NULL, _7 = zval_used_for_init, *_8, *_9 = NULL, *_10$$5 = NULL, *_11$$5, *_13$$5 = NULL;
ZEPHIR_MM_GROW();
zephir_fetch_params(1, 1, 0, &record);
ZEPHIR_INIT_VAR(_0);
ZVAL_STRING(_0, "field", ZEPHIR_TEMP_PARAM_COPY);
ZEPHIR_CALL_METHOD(&field, this_ptr, "getoption", NULL, 0, _0);
zephir_check_temp_parameter(_0);
zephir_check_call_status();
if (Z_TYPE_P(field) != IS_STRING) {
ZEPHIR_THROW_EXCEPTION_DEBUG_STR(phalcon_mvc_model_exception_ce, "Field name must be a string", "phalcon/mvc/model/validator/ip.zep", 87);
return;
}
ZEPHIR_CALL_METHOD(&value, record, "readattribute", NULL, 0, field);
zephir_check_call_status();
ZEPHIR_INIT_NVAR(_0);
ZVAL_STRING(_0, "version", ZEPHIR_TEMP_PARAM_COPY);
ZEPHIR_INIT_VAR(_1);
ZVAL_LONG(_1, (1048576 | 2097152));
ZEPHIR_CALL_METHOD(&version, this_ptr, "getoption", NULL, 0, _0, _1);
zephir_check_temp_parameter(_0);
zephir_check_call_status();
ZEPHIR_INIT_NVAR(_0);
ZVAL_STRING(_0, "allowPrivate", ZEPHIR_TEMP_PARAM_COPY);
ZEPHIR_CALL_METHOD(&_2, this_ptr, "getoption", NULL, 0, _0);
zephir_check_temp_parameter(_0);
zephir_check_call_status();
if (zephir_is_true(_2)) {
ZEPHIR_INIT_VAR(allowPrivate);
ZVAL_LONG(allowPrivate, 0);
} else {
ZEPHIR_INIT_NVAR(allowPrivate);
ZVAL_LONG(allowPrivate, 8388608);
}
ZEPHIR_INIT_NVAR(_0);
ZVAL_STRING(_0, "allowReserved", ZEPHIR_TEMP_PARAM_COPY);
ZEPHIR_CALL_METHOD(&_3, this_ptr, "getoption", NULL, 0, _0);
zephir_check_temp_parameter(_0);
zephir_check_call_status();
if (zephir_is_true(_3)) {
ZEPHIR_INIT_VAR(allowReserved);
ZVAL_LONG(allowReserved, 0);
} else {
ZEPHIR_INIT_NVAR(allowReserved);
ZVAL_LONG(allowReserved, 4194304);
}
ZEPHIR_INIT_NVAR(_0);
ZVAL_STRING(_0, "allowEmpty", ZEPHIR_TEMP_PARAM_COPY);
ZEPHIR_INIT_NVAR(_1);
ZVAL_BOOL(_1, 0);
ZEPHIR_CALL_METHOD(&_4, this_ptr, "getoption", NULL, 0, _0, _1);
zephir_check_temp_parameter(_0);
zephir_check_call_status();
_5 = zephir_is_true(_4);
if (_5) {
_5 = ZEPHIR_IS_EMPTY(value);
}
if (_5) {
RETURN_MM_BOOL(1);
}
ZEPHIR_INIT_VAR(options);
zephir_create_array(options, 2, 0 TSRMLS_CC);
ZEPHIR_INIT_VAR(_6);
zephir_create_array(_6, 1, 0 TSRMLS_CC);
zephir_array_update_string(&_6, SL("default"), &ZEPHIR_GLOBAL(global_false), PH_COPY | PH_SEPARATE);
zephir_array_update_string(&options, SL("options"), &_6, PH_COPY | PH_SEPARATE);
ZEPHIR_SINIT_VAR(_7);
zephir_bitwise_or_function(&_7, version, allowPrivate TSRMLS_CC);
ZEPHIR_INIT_VAR(_8);
zephir_bitwise_or_function(_8, &_7, allowReserved TSRMLS_CC);
zephir_array_update_string(&options, SL("flags"), &_8, PH_COPY | PH_SEPARATE);
ZEPHIR_SINIT_NVAR(_7);
ZVAL_LONG(&_7, 275);
ZEPHIR_CALL_FUNCTION(&_9, "filter_var", NULL, 197, value, &_7, options);
zephir_check_call_status();
if (!(zephir_is_true(_9))) {
ZEPHIR_INIT_VAR(_10$$5);
ZVAL_STRING(_10$$5, "message", ZEPHIR_TEMP_PARAM_COPY);
ZEPHIR_INIT_VAR(_11$$5);
ZVAL_STRING(_11$$5, "IP address is incorrect", ZEPHIR_TEMP_PARAM_COPY);
ZEPHIR_CALL_METHOD(&message, this_ptr, "getoption", NULL, 0, _10$$5, _11$$5);
zephir_check_temp_parameter(_10$$5);
zephir_check_temp_parameter(_11$$5);
zephir_check_call_status();
ZEPHIR_INIT_VAR(_12$$5);
zephir_create_array(_12$$5, 1, 0 TSRMLS_CC);
zephir_array_update_string(&_12$$5, SL(":field"), &field, PH_COPY | PH_SEPARATE);
ZEPHIR_CALL_FUNCTION(&_13$$5, "strtr", NULL, 26, message, _12$$5);
zephir_check_call_status();
ZEPHIR_INIT_NVAR(_10$$5);
ZVAL_STRING(_10$$5, "IP", ZEPHIR_TEMP_PARAM_COPY);
ZEPHIR_CALL_METHOD(NULL, this_ptr, "appendmessage", NULL, 0, _13$$5, field, _10$$5);
zephir_check_temp_parameter(_10$$5);
zephir_check_call_status();
RETURN_MM_BOOL(0);
}
RETURN_MM_BOOL(1);
}
| 33.376963 | 283 | 0.690667 | [
"model"
] |
3a9a37b0fcdb8f68fe0c0a172ce7486707e827f2 | 484 | h | C | systems/plants/joints/drakeJointUtil.h | jacob-izr/drake | d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9 | [
"BSD-3-Clause"
] | null | null | null | systems/plants/joints/drakeJointUtil.h | jacob-izr/drake | d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9 | [
"BSD-3-Clause"
] | null | null | null | systems/plants/joints/drakeJointUtil.h | jacob-izr/drake | d8f0f1f231ecba83ed53b1a1c2f9f43da50396b9 | [
"BSD-3-Clause"
] | 1 | 2021-09-29T19:37:28.000Z | 2021-09-29T19:37:28.000Z | #ifndef DRAKEJOINTUTIL_H_
#define DRAKEJOINTUTIL_H_
#include "DrakeJoint.h"
#include <string>
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <memory>
// FIXME: delete this interface. it's not needed anymore by the new parser
DLLEXPORT_DRAKEJOINT std::unique_ptr<DrakeJoint> createJoint(
const std::string& joint_name, const Eigen::Isometry3d& transform_to_parent_body, int floating, const Eigen::Vector3d& joint_axis, double pitch);
#endif /* DRAKEJOINTUTIL_H_ */
| 28.470588 | 149 | 0.778926 | [
"geometry"
] |
3a9abe875b54dfb390f6629acb048dfde70e3962 | 11,331 | c | C | kernel/nortos/startup/startup_msp432_iar.c | ArakniD/simplelink_msp432p4_sdk | 002fd4866284891e0b9b1a8d917a74334d39a997 | [
"BSD-3-Clause"
] | 2 | 2022-02-28T01:38:24.000Z | 2022-02-28T01:38:31.000Z | kernel/nortos/startup/startup_msp432_iar.c | ArakniD/simplelink_msp432p4_sdk | 002fd4866284891e0b9b1a8d917a74334d39a997 | [
"BSD-3-Clause"
] | 3 | 2019-05-10T04:24:45.000Z | 2019-05-10T05:53:34.000Z | kernel/nortos/startup/startup_msp432_iar.c | ArakniD/simplelink_msp432p4_sdk | 002fd4866284891e0b9b1a8d917a74334d39a997 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2017, Texas Instruments Incorporated
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
//*****************************************************************************
//
// MSP432 Family Interrupt Vector Table for GCC
//
//****************************************************************************
#if !(defined(__IAR_SYSTEMS_ICC__))
#error "startup_msp432_iar.c: Unsupported compiler!"
#endif
#include <stdint.h>
#include <ti/devices/DeviceFamily.h>
#include <ti/devices/msp432p4xx/driverlib/driverlib.h>
#include <ti/devices/msp432p4xx/driverlib/interrupt.h>
//*****************************************************************************
//
// External declaration for the reset handler that is to be called when the
// processor is started
//
//*****************************************************************************
static void nmiISR(void);
static void faultISR(void);
static void defaultHandler(void);
static void busFaultHandler(void);
//*****************************************************************************
//
// The entry point for the application startup code.
//
//*****************************************************************************
extern void __iar_program_start(void);
//*****************************************************************************
//
//! Get stack start (highest address) symbol from linker file.
//
//*****************************************************************************
extern const void* STACK_TOP;
// It is required to place something in the CSTACK segment to get the stack
// check feature in IAR to work as expected
__root static void* dummy_stack @ ".stack";
//*****************************************************************************
//
// A union that describes the entries of the vector table. The union is needed
// since the first entry is the stack pointer and the remainder are function
// pointers.
//
//*****************************************************************************
typedef union
{
void (*pfnHandler)(void);
unsigned long ulPtr;
}
uVectorEntry;
//*****************************************************************************
//
// The vector table. Note that the proper constructs must be placed on this to
// ensure that it ends up at physical address 0x0000.0000.
//
//*****************************************************************************
#pragma location = ".intvec"
const uVectorEntry __vector_table[] =
{
(void (*)(void))&STACK_TOP, // The initial stack pointer
__iar_program_start, // The reset handler
nmiISR, // The NMI handler
faultISR, // The hard fault handler
defaultHandler, // The MPU fault handler
busFaultHandler, // The bus fault handler
defaultHandler, // The usage fault handler
0, /* Reserved */
0, /* Reserved */
0, /* Reserved */
0, /* Reserved */
defaultHandler, /* SVCall handler */
defaultHandler, // Debug monitor handler
0, /* Reserved */
defaultHandler, /* The PendSV handler */
defaultHandler, /* The SysTick handler */
defaultHandler, /* PSS ISR */
defaultHandler, /* CS ISR */
defaultHandler, /* PCM ISR */
defaultHandler, /* WDT ISR */
defaultHandler, /* FPU ISR */
defaultHandler, /* FLCTL ISR */
defaultHandler, /* COMP0 ISR */
defaultHandler, /* COMP1 ISR */
defaultHandler, /* TA0_0 ISR */
defaultHandler, /* TA0_N ISR */
defaultHandler, /* TA1_0 ISR */
defaultHandler, /* TA1_N ISR */
defaultHandler, /* TA2_0 ISR */
defaultHandler, /* TA2_N ISR */
defaultHandler, /* TA3_0 ISR */
defaultHandler, /* TA3_N ISR */
defaultHandler, /* EUSCIA0 ISR */
defaultHandler, /* EUSCIA1 ISR */
defaultHandler, /* EUSCIA2 ISR */
defaultHandler, /* EUSCIA3 ISR */
defaultHandler, /* EUSCIB0 ISR */
defaultHandler, /* EUSCIB1 ISR */
defaultHandler, /* EUSCIB2 ISR */
defaultHandler, /* EUSCIB3 ISR */
defaultHandler, /* ADC14 ISR */
defaultHandler, /* T32_INT1 ISR */
defaultHandler, /* T32_INT2 ISR */
defaultHandler, /* T32_INTC ISR */
defaultHandler, /* AES ISR */
defaultHandler, /* RTC ISR */
defaultHandler, /* DMA_ERR ISR */
defaultHandler, /* DMA_INT3 ISR */
defaultHandler, /* DMA_INT2 ISR */
defaultHandler, /* DMA_INT1 ISR */
defaultHandler, /* DMA_INT0 ISR */
defaultHandler, /* PORT1 ISR */
defaultHandler, /* PORT2 ISR */
defaultHandler, /* PORT3 ISR */
defaultHandler, /* PORT4 ISR */
defaultHandler, /* PORT5 ISR */
defaultHandler, /* PORT6 ISR */
defaultHandler, /* Reserved 41 */
defaultHandler, /* Reserved 42 */
defaultHandler, /* Reserved 43 */
defaultHandler, /* Reserved 44 */
defaultHandler, /* Reserved 45 */
defaultHandler, /* Reserved 46 */
defaultHandler, /* Reserved 47 */
defaultHandler, /* Reserved 48 */
defaultHandler, /* Reserved 49 */
defaultHandler, /* Reserved 50 */
defaultHandler, /* Reserved 51 */
defaultHandler, /* Reserved 52 */
defaultHandler, /* Reserved 53 */
defaultHandler, /* Reserved 54 */
defaultHandler, /* Reserved 55 */
defaultHandler, /* Reserved 56 */
defaultHandler, /* Reserved 57 */
defaultHandler, /* Reserved 58 */
defaultHandler, /* Reserved 59 */
defaultHandler, /* Reserved 60 */
defaultHandler, /* Reserved 61 */
defaultHandler, /* Reserved 62 */
defaultHandler, /* Reserved 63 */
};
/*
* This function is called by __iar_program_start() early in the boot sequence.
*/
int __low_level_init(void)
{
Interrupt_disableMaster();
/* disable the watchdog timer */
MAP_WDT_A_holdTimer();
/*==================================*/
/* Choose if segment initialization */
/* should be done or not. */
/* Return: 0 to omit seg_init */
/* 1 to run seg_init */
/*==================================*/
return 1;
}
/* This is the code that gets called when the processor receives a NMI. This */
/* simply enters an infinite loop, preserving the system state for examination */
static void
nmiISR(void)
{
while(1)
{
}
}
/* by a debugger. */
static void
faultISR(void)
{
/* Enter an infinite loop. */
while(1)
{
}
}
/* This is the code that gets called when the processor receives a fault */
/* interrupt. This simply enters an infinite loop, preserving the system state */
/* for examination by a debugger. */
static void
busFaultHandler(void)
{
/* Enter an infinite loop. */
while(1)
{
}
}
/* This is the code that gets called when the processor receives an unexpected */
/* interrupt. This simply enters an infinite loop, preserving the system state */
/* for examination by a debugger. */
static void defaultHandler(void)
{
/* Enter an infinite loop. */
while(1)
{
}
}
| 45.143426 | 82 | 0.439944 | [
"vector"
] |
3a9bef784845ae5bbe7392b316e6c36d8353dc07 | 8,324 | h | C | ir/vector.h | DTharun/p4lang | d83d078f95ae2eaf054955fb645fa4d4a7e54847 | [
"Apache-2.0"
] | 27 | 2018-06-30T13:01:40.000Z | 2022-01-28T09:07:21.000Z | ir/vector.h | DTharun/p4lang | d83d078f95ae2eaf054955fb645fa4d4a7e54847 | [
"Apache-2.0"
] | 8 | 2018-06-01T11:19:02.000Z | 2018-06-09T13:09:15.000Z | ir/vector.h | DTharun/p4lang | d83d078f95ae2eaf054955fb645fa4d4a7e54847 | [
"Apache-2.0"
] | 6 | 2019-02-24T11:20:22.000Z | 2021-05-25T17:21:07.000Z | /*
Copyright 2013-present Barefoot Networks, 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 _IR_VECTOR_H_
#define _IR_VECTOR_H_
#include "dbprint.h"
#include "lib/enumerator.h"
#include "lib/null.h"
#include "lib/safe_vector.h"
class JSONLoader;
namespace IR {
// Specialization of vector which
// - only stores const IR::Node* objects inside (T should derive from Node)
// - inherits from IR::Node itself
class VectorBase : public Node {
public:
typedef const Node * const *iterator;
virtual iterator VectorBase_begin() const = 0;
virtual iterator VectorBase_end() const = 0;
virtual size_t size() const = 0;
virtual bool empty() const = 0;
iterator begin() const { return VectorBase_begin(); }
iterator end() const { return VectorBase_end(); }
VectorBase() = default;
VectorBase(const VectorBase &) = default;
VectorBase(VectorBase &&) = default;
VectorBase &operator=(const VectorBase &) = default;
VectorBase &operator=(VectorBase &&) = default;
protected:
explicit VectorBase(JSONLoader &json) : Node(json) {}
};
// This class should only be used in the IR.
// User-level code should use regular std::vector
template<class T>
class Vector : public VectorBase {
safe_vector<const T *> vec;
public:
typedef const T* value_type;
Vector() = default;
Vector(const Vector &) = default;
Vector(Vector &&) = default;
explicit Vector(JSONLoader &json);
Vector &operator=(const Vector &) = default;
Vector &operator=(Vector &&) = default;
explicit Vector(const T *a) {
vec.emplace_back(std::move(a)); }
explicit Vector(const safe_vector<const T *> &a) {
vec.insert(vec.end(), a.begin(), a.end()); }
Vector(const std::initializer_list<const T *> &a) : vec(a) {}
static Vector<T>* fromJSON(JSONLoader &json);
typedef typename safe_vector<const T *>::iterator iterator;
typedef typename safe_vector<const T *>::const_iterator const_iterator;
iterator begin() { return vec.begin(); }
const_iterator begin() const { return vec.begin(); }
VectorBase::iterator VectorBase_begin() const override {
/* DANGER -- works as long as IR::Node is the first ultimate base class of T */
return reinterpret_cast<VectorBase::iterator>(&vec[0]); }
iterator end() { return vec.end(); }
const_iterator end() const { return vec.end(); }
VectorBase::iterator VectorBase_end() const override {
/* DANGER -- works as long as IR::Node is the first ultimate base class of T */
return reinterpret_cast<VectorBase::iterator>(&vec[0] + vec.size()); }
std::reverse_iterator<iterator> rbegin() { return vec.rbegin(); }
std::reverse_iterator<const_iterator> rbegin() const { return vec.rbegin(); }
std::reverse_iterator<iterator> rend() { return vec.rend(); }
std::reverse_iterator<const_iterator> rend() const { return vec.rend(); }
size_t size() const override { return vec.size(); }
void resize(size_t sz) { vec.resize(sz); }
bool empty() const override { return vec.empty(); }
const T* const & front() const { return vec.front(); }
const T*& front() { return vec.front(); }
void clear() { vec.clear(); }
iterator erase(iterator i) { return vec.erase(i); }
iterator erase(iterator s, iterator e) { return vec.erase(s, e); }
template<typename ForwardIter>
iterator insert(iterator i, ForwardIter b, ForwardIter e) {
/* FIXME -- gcc prior to 4.9 is broken and the insert routine returns void
* FIXME -- rather than an iterator. So we recalculate it from an index */
int index = i - vec.begin();
vec.insert(i, b, e);
return vec.begin() + index; }
template<typename Container>
iterator append(const Container &toAppend)
{ return insert(end(), toAppend.begin(), toAppend.end()); }
/**
* Appends the provided node or vector of nodes to the end of this Vector.
*
* @param item A node to append; if this is a Vector, its contents will be
* appended.
*/
void pushBackOrAppend(const IR::Node* item) {
if (item == nullptr) return;
if (auto* itemAsVector = item->to<IR::Vector<T>>()) {
append(*itemAsVector);
return;
}
BUG_CHECK(item->is<T>(), "Unexpected vector element: %1%", item);
push_back(item->to<T>());
}
iterator insert(iterator i, const T* v) {
/* FIXME -- gcc prior to 4.9 is broken and the insert routine returns void
* FIXME -- rather than an iterator. So we recalculate it from an index */
int index = i - vec.begin();
vec.insert(i, v);
return vec.begin() + index; }
iterator insert(iterator i, size_t n, const T* v) {
/* FIXME -- gcc prior to 4.9 is broken and the insert routine returns void
* FIXME -- rather than an iterator. So we recalculate it from an index */
int index = i - vec.begin();
vec.insert(i, n, v);
return vec.begin() + index; }
const T *const &operator[](size_t idx) const { return vec[idx]; }
const T *&operator[](size_t idx) { return vec[idx]; }
const T *const &at(size_t idx) const { return vec.at(idx); }
const T *&at(size_t idx) { return vec.at(idx); }
template <class... Args> void emplace_back(Args&&... args) {
vec.emplace_back(new T(std::forward<Args>(args)...)); }
void push_back(T *a) { vec.push_back(a); }
void push_back(const T *a) { vec.push_back(a); }
void pop_back() { vec.pop_back(); }
const T* const & back() const { return vec.back(); }
const T*& back() { return vec.back(); }
template<class U> void push_back(U &a) { vec.push_back(a); }
void check_null() const { for (auto e : vec) CHECK_NULL(e); }
IRNODE_SUBCLASS(Vector)
IRNODE_DECLARE_APPLY_OVERLOAD(Vector)
bool operator==(const Node &a) const override { return a == *this; }
// If you get an error about this method not being overridden
// you are probably using a Vector where you should be using an std::vector.
bool operator==(const Vector &a) const override { return vec == a.vec; }
cstring node_type_name() const override {
return "Vector<" + T::static_type_name() + ">"; }
static cstring static_type_name() {
return "Vector<" + T::static_type_name() + ">"; }
void visit_children(Visitor &v) override;
void visit_children(Visitor &v) const override;
virtual void parallel_visit_children(Visitor &v);
virtual void parallel_visit_children(Visitor &v) const;
void toJSON(JSONGenerator &json) const override;
Util::Enumerator<const T*>* getEnumerator() const {
return Util::Enumerator<const T*>::createEnumerator(vec); }
template <typename S>
Util::Enumerator<const S*>* only() const {
std::function<bool(const T*)> filter = [](const T* d) { return d->template is<S>(); };
return getEnumerator()->where(filter)->template as<const S*>(); }
};
} // namespace IR
// XXX(seth): We use this namespace to hide our get() overloads from ADL. GCC
// 4.8 has a bug which causes these overloads to be considered when get() is
// called on a type in the global namespace, even if the number of arguments
// doesn't match up, which can trigger template instantiations that cause
// errors.
namespace GetImpl {
template<class T, class U> const T *get(const IR::Vector<T> &vec, U name) {
for (auto el : vec)
if (el->name == name)
return el;
return nullptr; }
template<class T, class U> const T *get(const IR::Vector<T> *vec, U name) {
if (vec)
for (auto el : *vec)
if (el->name == name)
return el;
return nullptr; }
} // namespace GetImpl
using namespace GetImpl; // NOLINT(build/namespaces)
#endif /* _IR_VECTOR_H_ */
| 42.040404 | 94 | 0.65197 | [
"vector"
] |
3aa0212f44436d905cc4c667219b386853bbfa5d | 5,514 | h | C | crankvisual/crankvertexstruct.h | WSID/crank-system | 7c94f829050815392259c227e38b34f97886f7fc | [
"MIT"
] | null | null | null | crankvisual/crankvertexstruct.h | WSID/crank-system | 7c94f829050815392259c227e38b34f97886f7fc | [
"MIT"
] | null | null | null | crankvisual/crankvertexstruct.h | WSID/crank-system | 7c94f829050815392259c227e38b34f97886f7fc | [
"MIT"
] | null | null | null | #ifndef CRANKVERTEXSTRUCT_H
#define CRANKVERTEXSTRUCT_H
/* Copyright (C) 2015, WSID */
/* 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 _CRANKVISUAL_INSIDE
#error crankrendermodule.h cannot be included directly: include crankvisual.h
#endif
#include <glib.h>
#include <glib-object.h>
#include <cogl/cogl2-experimental.h>
#include "crankbase.h"
//////// Type Declaration //////////////////////////////////////////////////////
/**
* CrankVertexP3N3
* @x: X component of position attribute.
* @y: Y component of position attribute.
* @z: Z component of position attribute.
* @nx: X component of normal attribute.
* @ny: Y component of normal attribute.
* @nz: Z component of normal attribute.
*
* A structure to hold position and normal information.
*/
typedef struct _CrankVertexP3N3 {
gfloat x;
gfloat y;
gfloat z;
gfloat nx;
gfloat ny;
gfloat nz;
} CrankVertexP3N3;
/**
* CrankVertexP3N3C4
* @x: X component of position attribute.
* @y: Y component of position attribute.
* @z: Z component of position attribute.
* @nx: X component of normal attribute.
* @ny: Y component of normal attribute.
* @nz: Z component of normal attribute.
* @r: Red component of color attribute.
* @g: Green component of color attribute.
* @b: Blue component of color attribute.
* @a: Alpha component of color attribute.
*
* A structure to hold position and normal, and color information.
*/
typedef struct _CrankVertexP3N3C4 {
gfloat x;
gfloat y;
gfloat z;
gfloat nx;
gfloat ny;
gfloat nz;
guint8 r;
guint8 g;
guint8 b;
guint8 a;
} CrankVertexP3N3C4;
/**
* CrankVertexP3N3T2
* @x: X component of position attribute.
* @y: Y component of position attribute.
* @z: Z component of position attribute.
* @nx: X component of normal attribute.
* @ny: Y component of normal attribute.
* @nz: Z component of normal attribute.
* @s: S component of texture coordinate attribute.
* @t: T component of texture coordinate attribute.
*
* A structure to hold position and normal, and texture coordinate information.
*/
typedef struct _CrankVertexP3N3T2 {
gfloat x;
gfloat y;
gfloat z;
gfloat nx;
gfloat ny;
gfloat nz;
gfloat s;
gfloat t;
} CrankVertexP3N3T2;
//////// Alternative Type Declarations /////////////////////////////////////////
/**
* CrankVertexP3N3V:
* @position: Position attribute.
* @normal: Normal attribute.
*
* Alternative struct declaration of #CrankVertexP3N3
*/
typedef struct _CrankVertexP3N3V {
CrankVecFloat3 position;
CrankVecFloat3 normal;
} CrankVertexP3N3V;
/**
* CrankVertexP3N3C4V:
* @position: Position attribute.
* @normal: Normal attribute.
* @r: Red component of color attribute.
* @g: Green component of color attribute.
* @b: Blue component of color attribute.
* @a: Alpha component of color attribute.
*
* Alternative struct declaration of #CrankVertexP3N3C4
*/
typedef struct _CrankVertexP3N3C4V {
CrankVecFloat3 position;
CrankVecFloat3 normal;
guint8 r;
guint8 g;
guint8 b;
guint8 a;
} CrankVertexP3N3C4V;
/**
* CrankVertexP3N3T2V:
* @position: Position attribute.
* @normal: Normal attribute.
* @texcoord: Texture coordinate attribute.
*
* Alternative struct declaration of #CrankVertexP3N3T2
*/
typedef struct _CrankVertexP3N3T2V {
CrankVecFloat3 position;
CrankVecFloat3 normal;
CrankVecFloat2 texcoord;
} CrankVertexP3N3T2V;
//////// Public Functions //////////////////////////////////////////////////////
CoglPrimitive *crank_cogl_primitive_new_p3n3 (CoglContext *context,
CoglVerticesMode mode,
gint n_vertices,
const CrankVertexP3N3 *data);
CoglPrimitive *crank_cogl_primitive_new_p3n3c4 (CoglContext *context,
CoglVerticesMode mode,
gint n_vertices,
const CrankVertexP3N3C4 *data);
CoglPrimitive *crank_cogl_primitive_new_p3n3t2 (CoglContext *context,
CoglVerticesMode mode,
gint n_vertices,
const CrankVertexP3N3T2 *data);
#endif
| 30.296703 | 85 | 0.644178 | [
"object"
] |
3aa1a7ca566bff138eaf396e42f005ae59760223 | 2,722 | h | C | include/cppsl/threading/delegate_base.h | alexcvc/cppsl | a3c033561630fe170bd84fdefa2863bcf88920d9 | [
"MIT"
] | null | null | null | include/cppsl/threading/delegate_base.h | alexcvc/cppsl | a3c033561630fe170bd84fdefa2863bcf88920d9 | [
"MIT"
] | null | null | null | include/cppsl/threading/delegate_base.h | alexcvc/cppsl | a3c033561630fe170bd84fdefa2863bcf88920d9 | [
"MIT"
] | null | null | null | /*
Thread Wrapper v.2.0
Delegates
Copyright (C) 2017 by Sergey A Kryukov
The article, along with any associated source code and files, is licensed under
The Code Project Open License (CPOL)
http://www.SAKryukov.org
http://www.codeproject.com/Members/SAKryukov
Original publications:
https://www.codeproject.com/Articles/1177478/Thread-Wrapper-CPP
https://www.codeproject.com/Articles/1177869/Conveyor-Thread-Wrapper-CPP
*/
/*************************************************************************//**
* \file DelegateBase.hpp
* \brief The Delegate base type is used to store in the queue, and reflects
* the profile of the synchronization object and its thread.
* \ingroup Thread Wrapper for Modern C++
* \date 2021-10-24
*****************************************************************************/
#ifndef __INCLUDE_CPPSL_THREADING_DELEGATE_BASE_H__
#define __INCLUDE_CPPSL_THREADING_DELEGATE_BASE_H__
//-----------------------------------------------------------------------------
// includes <...>
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// includes "..."
//-----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// Defines and macros
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// Typedefs, structs, enums, unions and variables
//----------------------------------------------------------------------------
namespace cppsl::threading {
template<typename T>
class DelegateBase;
template<typename RET, typename ...PARAMS>
class DelegateBase<RET(PARAMS...)> {
protected:
using stub_type = RET(*)(void *this_ptr, PARAMS...);
struct InvocationElement {
InvocationElement() = default;
InvocationElement(void *this_ptr, stub_type aStub) : object(this_ptr), stub(aStub) {}
void Clone(InvocationElement &target) const {
target.stub = stub;
target.object = object;
} //Clone
bool operator==(const InvocationElement &another) const {
return another.stub == stub && another.object == object;
} //==
bool operator!=(const InvocationElement &another) const {
return another.stub != stub || another.object != object;
} //!=
void *object = nullptr;
stub_type stub = nullptr;
}; //InvocationElement
}; //class DelegateBase
} /* namespace cppsl::threading */
#endif /* __INCLUDE_CPPSL_THREADING_DELEGATE_BASE_H__ */
| 34.897436 | 91 | 0.490448 | [
"object"
] |
3ab214383771c2e6a8d77a7aa294a3d9723d0eb3 | 591 | h | C | GTInjectingDemo/GTInjectingDemo/Class_responder_key/UIResponder+GTResponderKey.h | GUTHome/GTInjectingDemo | d82899199852af03b775e2f2c386f86eb7137468 | [
"MIT"
] | null | null | null | GTInjectingDemo/GTInjectingDemo/Class_responder_key/UIResponder+GTResponderKey.h | GUTHome/GTInjectingDemo | d82899199852af03b775e2f2c386f86eb7137468 | [
"MIT"
] | null | null | null | GTInjectingDemo/GTInjectingDemo/Class_responder_key/UIResponder+GTResponderKey.h | GUTHome/GTInjectingDemo | d82899199852af03b775e2f2c386f86eb7137468 | [
"MIT"
] | null | null | null | //
// UIResponder+GTResponderKey.h
// GTInjectingDemo
//
// Created by tanxl on 2019/12/23.
// Copyright © 2019 tanxl. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIResponder (GTResponderKey)
#pragma mark -
/**
* (Casa的思想框架实践)
* 走KEY转响应,最终在控制器里要实现的是【routerEventWithSelectorKey:msgSource:objects】由此方法分发事件统一管理
* KEY非方法名字
*/
// 转发单参数
- (void)routerEventWithSelectorKey:(NSString *)selectorKey msgSource:(id)msgSource object:(id)object;
// 转发多参数
- (void)routerEventWithSelectorKey:(NSString *)selectorKey msgSource:(id)msgSource objects:(NSArray *)objects;
@end
| 21.107143 | 110 | 0.742809 | [
"object"
] |
3ac0bdb05587c0454b6518456bdfc079b40660a4 | 2,403 | c | C | clicks/irthermo3/example/main.c | dMajoIT/mikrosdk_click_v2 | f425fd85054961b4f600d1708cf18ac952a6bdb8 | [
"MIT"
] | 31 | 2020-10-02T14:15:14.000Z | 2022-03-24T08:33:21.000Z | clicks/irthermo3/example/main.c | dMajoIT/mikrosdk_click_v2 | f425fd85054961b4f600d1708cf18ac952a6bdb8 | [
"MIT"
] | 4 | 2020-10-27T14:05:00.000Z | 2022-03-10T09:38:57.000Z | clicks/irthermo3/example/main.c | dMajoIT/mikrosdk_click_v2 | f425fd85054961b4f600d1708cf18ac952a6bdb8 | [
"MIT"
] | 32 | 2020-11-28T07:56:42.000Z | 2022-03-14T19:42:29.000Z | /*!
* \file
* \brief IrThermo3 Click example
*
* # Description
* The demo application displays ambient and object temperature measurementss
* using IrThermo 3 click.
*
* The demo application is composed of two sections :
*
* ## Application Init
* Initializes Driver ,resets the devic and performs calibration.
*
* ## Application Task
* The device measures ambient and object temperatures and displays data in
* degree centigrade every second.
*
* \author Jovan Stajkovic
*
*/
// ------------------------------------------------------------------- INCLUDES
#include "board.h"
#include "log.h"
#include "irthermo3.h"
// ------------------------------------------------------------------ VARIABLES
static irthermo3_t irthermo3;
static log_t logger;
static float amb_temp;
static float obj_temp;
uint8_t adr_rst[ 4 ] = { 0x30, 0x05, 0x00, 0x06 };
uint8_t eeprom_unlock[ 4 ] = { 0x30, 0x05, 0x55, 0x4C };
// ------------------------------------------------------ APPLICATION FUNCTIONS
void application_init ( void )
{
log_cfg_t log_cfg;
irthermo3_cfg_t cfg;
/**
* Logger initialization.
* Default baud rate: 115200
* Default log level: LOG_LEVEL_DEBUG
* @note If USB_UART_RX and USB_UART_TX
* are defined as HAL_PIN_NC, you will
* need to define them manually for log to work.
* See @b LOG_MAP_USB_UART macro definition for detailed explanation.
*/
LOG_MAP_USB_UART( log_cfg );
log_init( &logger, &log_cfg );
log_info( &logger, "---- Application Init ----" );
// Click initialization.
irthermo3_cfg_setup( &cfg );
IRTHERMO3_MAP_MIKROBUS( cfg, MIKROBUS_1 );
irthermo3_init( &irthermo3, &cfg );
irthermo3_global_write ( &irthermo3, adr_rst, 4 );
irthermo3_cal ( &irthermo3 );
Delay_ms( 500 );
}
void application_task ( void )
{
amb_temp = irthermo3_get_ambient_temperature( &irthermo3 );
log_printf( &logger, "Ambient temperature: %.2f °C \r\n", amb_temp );
obj_temp = irthermo3_get_object_temperature( &irthermo3 );
log_printf( &logger, "Object temperature: %.2f °C \r\n", obj_temp );
log_printf( &logger, "----------------------------\r\n" );
Delay_ms( 1000 );
}
void main ( void )
{
application_init( );
for ( ; ; )
{
application_task( );
}
}
// ------------------------------------------------------------------------ END
| 26.119565 | 79 | 0.587183 | [
"object"
] |
3ac15b37874278b2cf04d340df9b701a9d36c91a | 36,287 | h | C | PCD_main/Supp_Func.h | Decclo/Project_ChickenDoor | 723cdcaeff2a14dadac0be077fd725a4a587588f | [
"MIT"
] | 1 | 2019-01-06T23:20:05.000Z | 2019-01-06T23:20:05.000Z | PCD_main/Supp_Func.h | Decclo/Project_ChickenDoor | 723cdcaeff2a14dadac0be077fd725a4a587588f | [
"MIT"
] | null | null | null | PCD_main/Supp_Func.h | Decclo/Project_ChickenDoor | 723cdcaeff2a14dadac0be077fd725a4a587588f | [
"MIT"
] | null | null | null | #ifndef Supp_Func
#define Supp_Func
/*
* Supp_Func.h
* Author: Hans V. Rasmussen
* Created: 13/06-2017 18:47
* Modified: 30/07-2017 16:32
* Version: 1.2
*
* Description:
* This library includes some extra functionality for the DS3231.
*/
//Change log
/*
Version: 1.2
Added:
Changed:
- Minor changes to relay functions and UI.
- Optimized timer1.
- Wrote comments for everything besides UIupdate.
Removed:
Notes:
- Running initial tests, preparing for a full scale test. UI will be finished before PCD v1.0
Version: 1.1
Added:
- UIupdate in Human_Machine_Interface
- EEPROM functionality
- Alarm1 and 2 are stored in EEPROM simultaneously with being written to the DS3231
- LCD functionality
- UI functionality (Work In Progress)
- Added timer1 to make interrupt ever 1 ms
- Added counter for relayArray to make relays turn off after x seconds
- Added timer for UI to make a 300ms delay as a safety against the user
- Added the button read function to the timer, so that the UI is more smooth. Hopefully this will not make any complications.
- class relayArray to control the relays
Changed:
Removed:
Notes:
Version: 1.0
Added:
- classes 'Human_Machine_Interface' and 'DS3231RTC_Alarms'
Changed:
Removed:
Notes:
- First working version
*/
#include <avr/eeprom.h>
#include <DS3232RTC.h> //http://github.com/JChristensen/DS3232RTC
#include <Streaming.h> //http://arduiniana.org/libraries/streaming/
#include <TimeLib.h> //http://playground.arduino.cc/Code/Time
#include <Wire.h> //http://arduino.cc/en/Reference/Wire
#include <LiquidCrystal.h> // Arduino library for LCD
#include <avr/interrupt.h>
// Define Buttons for LCD
#define btnPIN A0
#define btnRESET 0
#define btnSELECT 1
#define btnRIGHT 2
#define btnUP 3
#define btnDOWN 4
#define btnLEFT 5
// Define time to wait between buttons presses (change this time to tune the button handling)
#define UIbtnHold 500
// Define commands for Relay Array
#define liftSTOP 0 // Stops the lift
#define liftCW 1 // Opens the door - Retracts in the cable
#define liftCCW 2 // Closes the door - Extends the cable
// define pins of Relay Array
#define RAControl1 DDD4
#define RAControl2 DDD5
#define RAControl3 DDD6
#define RAControl4 DDD7
// Define time for Relay Array to stop lift again (ms)
#define RAHold 4000
// Declare external global lcd
extern LiquidCrystal lcd;
extern DS3232RTC RTC;
// Global variables:
volatile boolean alarmIsrWasCalled = false; // Variable to check if the interrupt has happened.
// UI:
volatile uint8_t btnStat = 0; // variable for testing button state every 1 ms.
volatile uint16_t UIdelay = 0;
volatile boolean UIdelayStat = 0;
// relayArray:
volatile uint16_t RACounter1 = 0;
volatile boolean RACounter1Status = 0;
// Debugging:
// volatile uint16_t T1Timer = 0;
// volatile uint8_t test = 0;
// addresses of the alarms on the EEPROM (one time_t object takes 7 bytes)
uint8_t alarm1_addr = 0;
uint8_t alarm2_addr = 10;
// Functions:
void alarmIsr() // INT0 triggered function.
{
alarmIsrWasCalled = true;
}
// Classes
class Human_Machine_Interface
{
public:
Human_Machine_Interface();
/**
* \brief Takes in variable of type time_t and prints contents to serial or LCD.
* Text is 20 characters long.
*
* \param t
*
* \return void
*/
void printDateTime(time_t t);
/**
* \brief Takes in variable of type tmElements_t and prints contents to serial or LCD.
* Does not print year, text is 15 characters long.
*
* \param TM
*
* \return void
*/
void printDateTime(tmElements_t TM);
/**
* \brief Checks LCD buttons and returns value corresponding to button.
*
* \param void
*
* \return uint8_t
*/
uint8_t read_LCD_buttons(void);
/**
* \brief handles user input/output, should be called regurlarly
*
* \param void
*
* \return void
*/
void UIupdate(void);
protected:
private:
uint8_t UIstate;
tmElements_t tid;
};
class DS3231RTC_Alarms
{
public:
DS3231RTC_Alarms(); // Constructor
/**
* \brief Initializes the alarms and the interrupt.
*
* \param
*
* \return void
*/
void init_alarms(void);
/**
* \brief Takes in pointer, checks whether alarm1 or alarm2 have been triggered.
*
* \param uint8_t *
*
* \return void
*/
void alarm_Check(uint8_t *stat);
/**
* \brief returns the time when alarm1 is expected
*
* \param void
*
* \return time_t
*/
time_t alarm1_get(void);
/**
* \brief returns the time when alarm2 is expected
*
* \param void
*
* \return time_t
*/
time_t alarm2_get(void);
/**
* \brief Takes in tmElements_t and sets timer1 to trigger once a day.
* Only uses seconds, minutes and hours.
*
* \param TM
*
* \return boolean
*/
void alarm1_set(tmElements_t TM);
/**
* \brief Takes in tmElements_t and sets timer2 to trigger once a day.
* Only uses seconds, minutes and hours.
*
* \param TM
*
* \return boolean
*/
void alarm2_set(tmElements_t TM);
/************************************************************************
To change alarms do the following:
RTC.setAlarm(ALM1_MATCH_SECONDS, 0, 0, 0, 1); //daydate parameter should be between 1 and 7
RTC.alarm(ALARM_1); //ensure RTC interrupt flag is cleared
RTC.alarmInterrupt(ALARM_1, true);
RTC.setAlarm syntax for alarm1 is
void setAlarm(ALARM_TYPES_t alarmType, byte seconds, byte minutes, byte hours, byte daydate);
RTC.setAlarm syntax for alarm2 is
void setAlarm(ALARM_TYPES_t alarmType, byte minutes, byte hours, byte daydate);
Values for Alarm 1
ALM1_EVERY_SECOND -- causes an alarm once per second.
ALM1_MATCH_SECONDS -- causes an alarm when the seconds match (i.e. once per minute).
ALM1_MATCH_MINUTES -- causes an alarm when the minutes and seconds match.
ALM1_MATCH_HOURS -- causes an alarm when the hours and minutes and seconds match.
ALM1_MATCH_DATE -- causes an alarm when the date of the month and hours and minutes and seconds match.
ALM1_MATCH_DAY -- causes an alarm when the day of the week and hours and minutes and seconds match.
Values for Alarm 2
ALM2_EVERY_MINUTE -- causes an alarm once per minute.
ALM2_MATCH_MINUTES -- causes an alarm when the minutes match (i.e. once per hour).
ALM2_MATCH_HOURS -- causes an alarm when the hours and minutes match.
ALM2_MATCH_DATE -- causes an alarm when the date of the month and hours and minutes match.
ALM2_MATCH_DAY -- causes an alarm when the day of the week and hours and minutes match.
************************************************************************/
protected:
private:
// union: make a variable that can be interpreted multiple ways, ex as a long int or as an array of 8 bytes.
// This will be used when writing time_t to the EEPROM, as the EEPROM with current libraries only takes chars to store.
// By using union one can easily split the unsigned long int time_t into 8 bytes of data and then write them, example:
// union_name.long_variable = makeTime(TM);
// for (int i = 0; i < 7; i++)
// {
// eeprom_write_byte((uint8_t *)alarm1_addr+i, u.byte_array[0+i]);
// }
union {
unsigned long int long_time;
byte byte_array[7];
} alarm1_time;
union {
unsigned long int long_time;
byte byte_array[7];
} alarm2_time;
};
class liftRelayArray
{
public:
liftRelayArray(); // Constructor
/**
* \brief Initializes the pins required
*
* \param void
*
* \return void
*/
void relayArrayInit(void);
/**
* \brief Executes a command for the lift
*
* \param cmd - liftCW, liftCCW, liftSTOP
*
* \return void
*/
void relayArrayCommand(uint8_t cmd);
/**
* \brief Function that controls what actually should happen when alarm happens.
*
* \param uint8_t alarmtrig
*
* \return void
*/
void relayAutoCommand(uint8_t alarmtrig);
protected:
private:
};
// make objects of the classes:
Human_Machine_Interface HMI;// Make a object of the 'class Human_Machine_Interface' named 'HMI'
DS3231RTC_Alarms RTC_alarm; // Make a object of the 'class DS3231RTC_Alarms' named 'RTC_alarm'
liftRelayArray relayArray; // Make a object of the 'class liftRelayArray' named 'relayArray'
Human_Machine_Interface::Human_Machine_Interface() : UIstate(0)
{
breakTime(0, tid);
// Standard constructor procedure:
// give variables values by constructor : var_name(var_val) {}
// old constructor code
// UIstate = 0;
// time_t temp = 0;
// tid = HMI.ConvTotm(temp);
// tid.Hour = 8;
// tid.Minute = 30;
}
void Human_Machine_Interface::printDateTime(time_t t)
{
// Print the current time to serial with time_t as input.
Serial << ((day(t)<10) ? "0" : "") << _DEC(day(t)) << ' ';
Serial << (month(t)) << " " << _DEC(year(t)) << ' ';
Serial << ((hour(t)<10) ? "0" : "") << _DEC(hour(t)) << ':';
Serial << ((minute(t)<10) ? "0" : "") << _DEC(minute(t)) << ':';
Serial << ((second(t)<10) ? "0" : "") << _DEC(second(t));
}
void Human_Machine_Interface::printDateTime(tmElements_t TM)
{
// Print the current time to serial with tmElements_t as input.
Serial << ((TM.Day<10) ? "0" : "") << TM.Day << ' ';
Serial << (TM.Month) << ' ';
Serial << ((TM.Hour<10) ? "0" : "") << TM.Hour << ':';
Serial << ((TM.Minute<10) ? "0" : "") << TM.Minute << ':';
Serial << ((TM.Second<10) ? "0" : "") << TM.Second << endl;
}
uint8_t Human_Machine_Interface::read_LCD_buttons(void)
{
// read the value from the sensor
int adc_key_in = analogRead(btnPIN);
if (adc_key_in > 1050) return btnRESET;
if (adc_key_in < 50) return btnRIGHT;
if (adc_key_in < 250) return btnUP;
if (adc_key_in < 450) return btnDOWN;
if (adc_key_in < 650) return btnLEFT;
if (adc_key_in < 850) return btnSELECT;
return 0; // when all others fail, return 0.
}
void Human_Machine_Interface::UIupdate(void)
{
uint8_t userState = 0;
if (UIdelay >= UIbtnHold)
{
UIdelay = 0;
UIdelayStat = 0;
userState = btnStat; // insert user input here.
btnStat = 0;
}
else
{
UIdelayStat = 1;
}
// userState = HMI.read_LCD_buttons();
switch (UIstate)
{
case 0:
// Update tid with time from DS3231
breakTime(RTC.get(), tid);
// Print time here on LCD
lcd.noBlink();
lcd.clear();
lcd.setCursor(0,0);
lcd << "Klokkeslaet";
lcd.setCursor(0,1);
lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << "";
// user input
switch (userState)
{
case btnSELECT:
/* Your code here */ // Go to UIstate 1, To change C1
UIstate = 1;
break;
case btnRESET:
/* Your code here */ //Nothing happens
break;
case btnUP:
/* Your code here */ //nothing happens
break;
case btnDOWN:
/* Your code here */ //nothing happens
break;
case btnLEFT:
/* Your code here */ //Go to UIstate 20, we go to alarm 2
UIstate = 20;
break;
case btnRIGHT:
/* Your code here */ //Go to UIstate 10, we go to alarm 1
UIstate = 10;
break;
default:
/* Your code here */
break;
}
break;
case 1:
// Show time, blink C1
lcd.clear();
lcd.setCursor(0,0);
lcd << "Skift Klokkeslet";
lcd.setCursor(0,1);
lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << "";
lcd.setCursor(0,1);
lcd.blink();
switch (userState)
{
case btnSELECT:
/* Your code here */ //Do nothing
break;
case btnRESET:
/* Your code here */ //Do nothing
break;
case btnUP:
/* Your code here */ //Add 10 to variable hours
//If variable hours is 23< then subtract 20
if ((0 <= tid.Hour) & (tid.Hour < 14))
{
tid.Hour += 10;
}
else if((14 <= tid.Hour) & (tid.Hour < 20))
{
tid.Hour -= 10;
}
else
{
tid.Hour -= 20;
}
break;
case btnDOWN:
/* Your code here */ //subtract 10 to variable hours
// If variable hours is <0 then add 20
if ((0 <= tid.Hour) & (tid.Hour < 4))
{
tid.Hour += 20;
}
else if((4 <= tid.Hour) & (tid.Hour < 10))
{
tid.Hour += 10;
}
else
{
tid.Hour -= 10;
}
break;
case btnLEFT:
/* Your code here */ //Go to UIstate 0, revert changes, see time
UIstate = 0;
break;
case btnRIGHT:
/* Your code here */ //Go to UIstate 2, To change C2
UIstate = 2;
break;
default:
/* Your code here */
break;
}
break;
case 2:
// Show time, blink C2
lcd.clear();
lcd.setCursor(0,0);
lcd << "Skift Klokkeslet";
lcd.setCursor(0,1);
lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << "";
lcd.setCursor(1,1);
lcd.blink();
switch (userState)
{
case btnSELECT:
/* Your code here */ //Do nothing
break;
case btnRESET:
/* Your code here */ //Do nothing
break;
case btnUP:
/* Your code here */ //Add 1 to variable hours
//If variable hours is 23< then subtract 3
if ((9 == tid.Hour) | (19 == tid.Hour))
{
tid.Hour -= 9;
}
else if(23 == tid.Hour)
{
tid.Hour -= 3;
}
else
{
tid.Hour += 1;
}
break;
case btnDOWN:
/* Your code here */ //subtract 1 to variable hours
// If variable hours is <0 then add 9
if ((0 == tid.Hour) | (10 == tid.Hour))
{
tid.Hour += 9;
}
else if(20 == tid.Hour)
{
tid.Hour += 3;
}
else
{
tid.Hour -= 1;
}
break;
case btnLEFT:
/* Your code here */ //Go to UIstate 1, to change C1
UIstate = 1;
break;
case btnRIGHT:
/* Your code here */ // Go to UIstate 3, To change C3
UIstate = 3;
break;
default:
/* Your code here */
break;
}
break;
case 3:
// Show time, blink C3
lcd.clear();
lcd.setCursor(0,0);
lcd << "Skift Klokkeslet";
lcd.setCursor(0,1);
lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << "";
lcd.setCursor(3,1);
lcd.blink();
switch (userState)
{
case btnSELECT:
/* Your code here */ // Do nothing
break;
case btnRESET:
/* Your code here */ //Do nothing
break;
case btnUP:
/* Your code here */ //Add 10 to variable minutes
//If variable minutes is 59< then subtract 50
if ((50 <= tid.Minute))
{
tid.Minute -= 50;
}
else
{
tid.Minute += 10;
}
break;
case btnDOWN:
/* Your code here */ //subtract 10 to variable minutes
// If variable minutes is <0 then add 50
if((0 <= tid.Minute) & (tid.Minute < 10))
{
tid.Minute += 50;
}
else
{
tid.Minute -= 10;
}
break;
case btnLEFT:
/* Your code here */ //Go to UIstate 2, to change C2
UIstate = 2;
break;
case btnRIGHT:
/* Your code here */ //Go to UIstate 4, To change C4
UIstate = 4;
break;
default:
/* Your code here */
break;
}
break;
case 4:
// Show time, blink C4
lcd.clear();
lcd.setCursor(0,0);
lcd << "Skift Klokkeslet";
lcd.setCursor(0,1);
lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << "";
lcd.setCursor(4,1);
lcd.blink();
switch (userState)
{
case btnSELECT:
/* Your code here */ // Go to UIstate 0, write time to timer module,
UIstate = 0;
RTC.set(makeTime(tid));
break;
case btnRESET:
/* Your code here */ //Do nothing
break;
case btnUP:
/* Your code here */ //Add 1 to variable minutes
//If variable minutes is 59< then subtract 9
if ((tid.Minute == 9) | (tid.Minute == 19) | (tid.Minute == 29) | (tid.Minute == 39) | (tid.Minute == 49) | (tid.Minute == 59))
{
tid.Minute -= 9;
}
else
{
tid.Minute += 1;
}
break;
case btnDOWN:
/* Your code here */ //subtract 1 to variable minutes
// If variable minutes is >0 then add 9
if ((tid.Minute == 0) | (tid.Minute == 10) | (tid.Minute == 20) | (tid.Minute == 30) | (tid.Minute == 40) | (tid.Minute == 50))
{
tid.Minute += 9;
}
else
{
tid.Minute -= 1;
}
break;
case btnLEFT:
/* Your code here */ //Go to UIstate 3, to change C3
UIstate = 3;
break;
case btnRIGHT:
/* Your code here */ //Do nothing
break;
default:
/* Your code here */
break;
}
break;
case 10:
// Show Alarm1
breakTime(RTC_alarm.alarm1_get(), tid);
lcd.noBlink();
lcd.clear();
lcd.setCursor(0,0);
lcd << "Doeren aabner:";
lcd.setCursor(0,1);
lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << "";
switch (userState)
{
case btnSELECT:
/* Your code here */ // Go to UIstate 11, to change C1
UIstate = 11;
break;
case btnRESET:
/* Your code here */ //Do nothing
break;
case btnUP:
/* Your code here */ //Do nothing
break;
case btnDOWN:
/* Your code here */ //Do nothing
break;
case btnLEFT:
/* Your code here */ //Go to UIstate 0, we go to Time
UIstate = 0;
break;
case btnRIGHT:
/* Your code here */ //Go to UIstate 20, we go to Alarm2
UIstate = 20;
break;
default:
/* Your code here */
break;
}
break;
case 11:
// Show Alarm1, blink C1
lcd.clear();
lcd.setCursor(0,0);
lcd << "Skift aabning:";
lcd.setCursor(0,1);
lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << "";
lcd.setCursor(0,1);
lcd.blink();
switch (userState)
{
case btnSELECT:
/* Your code here */ //Do nothing
break;
case btnRESET:
/* Your code here */ //Do nothing
break;
case btnUP:
/* Your code here */ //Add 10 to variable hours
//If variable hours is 23< then subtract 20
if ((0 <= tid.Hour) & (tid.Hour < 14))
{
tid.Hour += 10;
}
else if((14 <= tid.Hour) & (tid.Hour < 20))
{
tid.Hour -= 10;
}
else
{
tid.Hour -= 20;
}
break;
case btnDOWN:
/* Your code here */ //subtract 10 to variable hours
// If variable hours is <0 then add 20
if ((0 <= tid.Hour) & (tid.Hour < 4))
{
tid.Hour += 20;
}
else if((4 <= tid.Hour) & (tid.Hour < 10))
{
tid.Hour += 10;
}
else
{
tid.Hour -= 10;
}
break;
case btnLEFT:
/* Your code here */ //Go to UIstate 10, revert changes, see alarm1
UIstate = 10;
break;
case btnRIGHT:
/* Your code here */ // Go to UIstate 12, To change C2
UIstate = 12;
break;
default:
/* Your code here */
break;
}
break;
case 12:
// Show Alarm1, blink C2
lcd.clear();
lcd.setCursor(0,0);
lcd << "Skift aabning:";
lcd.setCursor(0,1);
lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << "";
lcd.setCursor(1,1);
lcd.blink();
switch (userState)
{
case btnSELECT:
/* Your code here */ //Do nothing
break;
case btnRESET:
/* Your code here */ //Do nothing
break;
case btnUP:
/* Your code here */ //Add 1 to variable hours
//If variable hours is 23< then subtract 3
if ((9 == tid.Hour) | (19 == tid.Hour))
{
tid.Hour -= 9;
}
else if(23 == tid.Hour)
{
tid.Hour -= 3;
}
else
{
tid.Hour += 1;
}
break;
case btnDOWN:
/* Your code here */ //subtract 1 to variable hours
// If variable hours is <0 then add 9
if ((0 == tid.Hour) | (10 == tid.Hour))
{
tid.Hour += 9;
}
else if(20 == tid.Hour)
{
tid.Hour += 3;
}
else
{
tid.Hour -= 1;
}
break;
case btnLEFT:
/* Your code here */ //Go to UIstate 11, To change C1
UIstate = 11;
break;
case btnRIGHT:
/* Your code here */ // Go to UIstate 13, To change C3
UIstate = 13;
break;
default:
/* Your code here */
break;
}
break;
case 13:
// Show Alarm1, blink C3
lcd.clear();
lcd.setCursor(0,0);
lcd << "Skift aabning:";
lcd.setCursor(0,1);
lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << "";
lcd.setCursor(3,1);
lcd.blink();
switch (userState)
{
case btnSELECT:
/* Your code here */ // Go to UIstate 14, To change C4
break;
case btnRESET:
/* Your code here */ //Go to UIstate 12, To change C2
break;
case btnUP:
/* Your code here */ //Add 10 to variable minutes
//If variable minutes is 59< then subtract 50
if ((50 <= tid.Minute))
{
tid.Minute -= 50;
}
else
{
tid.Minute += 10;
}
break;
case btnDOWN:
/* Your code here */ //subtract 10 to variable minutes
// If variable minutes is <0 then add 50
if((0 <= tid.Minute) & (tid.Minute < 10))
{
tid.Minute += 50;
}
else
{
tid.Minute -= 10;
}
break;
case btnLEFT:
/* Your code here */ //Do nothing
UIstate = 12;
break;
case btnRIGHT:
/* Your code here */ //Do nothing
UIstate = 14;
break;
default:
/* Your code here */
break;
}
break;
case 14:
// Show Alarm1, blink C4
lcd.clear();
lcd.setCursor(0,0);
lcd << "Skift aabning:";
lcd.setCursor(0,1);
lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << "";
lcd.setCursor(4,1);
lcd.blink();
switch (userState)
{
case btnSELECT:
/* Your code here */ // Go to UIstate 10, Write Alarm1 to timer module
UIstate = 10;
RTC_alarm.alarm1_set(tid);
break;
case btnRESET:
/* Your code here */ //Go to UIstate 13, To change C3
break;
case btnUP:
/* Your code here */ //Add 1 to variable minutes
//If variable minutes is 59< then subtract 9
if ((tid.Minute == 9) | (tid.Minute == 19) | (tid.Minute == 29) | (tid.Minute == 39) | (tid.Minute == 49) | (tid.Minute == 59))
{
tid.Minute -= 9;
}
else
{
tid.Minute += 1;
}
break;
case btnDOWN:
/* Your code here */ //subtract 1 to variable minutes
// If variable minutes is >0 then add 9
if ((tid.Minute == 0) | (tid.Minute == 10) | (tid.Minute == 20) | (tid.Minute == 30) | (tid.Minute == 40) | (tid.Minute == 50))
{
tid.Minute += 9;
}
else
{
tid.Minute -= 1;
}
break;
case btnLEFT:
/* Your code here */ //Go to UIstate 3, to change C3
UIstate = 13;
break;
case btnRIGHT:
/* Your code here */ //Do nothing
break;
default:
/* Your code here */
break;
}
break;
case 20:
// Show Alarm2
breakTime(RTC_alarm.alarm2_get(), tid);
lcd.noBlink();
lcd.clear();
lcd.setCursor(0,0);
lcd << "Doeren Lukker:";
lcd.setCursor(0,1);
lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << "";
switch (userState)
{
case btnSELECT:
/* Your code here */ // Go to UIstate 21, To change C1
UIstate = 21;
break;
case btnRESET:
/* Your code here */ //Do nothing
break;
case btnUP:
/* Your code here */ //Do nothing
break;
case btnDOWN:
/* Your code here */ //Do nothing
break;
case btnLEFT:
/* Your code here */ //Go to UIstate 10, we go to Alarm1
UIstate = 10;
break;
case btnRIGHT:
/* Your code here */ //Go to UIstate 0, we go to Time
UIstate = 0;
break;
default:
/* Your code here */
break;
}
break;
case 21:
// Show Alarm2, blink C1
lcd.clear();
lcd.setCursor(0,0);
lcd << "Skift lukketid:";
lcd.setCursor(0,1);
lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << "";
lcd.setCursor(0,1);
lcd.blink();
switch (userState)
{
case btnSELECT:
/* Your code here */ // Do nothing
break;
case btnRESET:
/* Your code here */ // Do nothing
break;
case btnUP:
/* Your code here */ //Add 10 to variable hours
//If variable hours is 23< then subtract 20
if ((0 <= tid.Hour) & (tid.Hour < 14))
{
tid.Hour += 10;
}
else if((14 <= tid.Hour) & (tid.Hour < 20))
{
tid.Hour -= 10;
}
else
{
tid.Hour -= 20;
}
break;
case btnDOWN:
/* Your code here */ //subtract 10 to variable hours
// If variable hours is <0 then add 20
if ((0 <= tid.Hour) & (tid.Hour < 4))
{
tid.Hour += 20;
}
else if((4 <= tid.Hour) & (tid.Hour < 10))
{
tid.Hour += 10;
}
else
{
tid.Hour -= 10;
}
break;
case btnLEFT:
/* Your code here */ //Go to UIstate 20, revert changes, see Alarm2
UIstate = 20;
break;
case btnRIGHT:
/* Your code here */ //Go to UIstate 22
UIstate = 22;
break;
default:
/* Your code here */
break;
}
break;
case 22:
// Show Alarm2, blink C2
lcd.clear();
lcd.setCursor(0,0);
lcd << "Skift lukketid:";
lcd.setCursor(0,1);
lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << "";
lcd.setCursor(1,1);
lcd.blink();
switch (userState)
{
case btnSELECT:
/* Your code here */ // Do nothing
break;
case btnRESET:
/* Your code here */ // Do nothing
break;
case btnUP:
/* Your code here */ //Add 1 to variable hours
//If variable hours is 23< then subtract 3
if ((9 == tid.Hour) | (19 == tid.Hour))
{
tid.Hour -= 9;
}
else if(23 == tid.Hour)
{
tid.Hour -= 3;
}
else
{
tid.Hour += 1;
}
break;
case btnDOWN:
/* Your code here */ //subtract 1 to variable hours
// If variable hours is <0 then add 9
if ((0 == tid.Hour) | (10 == tid.Hour))
{
tid.Hour += 9;
}
else if(20 == tid.Hour)
{
tid.Hour += 3;
}
else
{
tid.Hour -= 1;
}
break;
case btnLEFT:
/* Your code here */ //Go to UIstate 21 to change C1
UIstate = 21;
break;
case btnRIGHT:
/* Your code here */ //Go to UIstate 23 to change C3
UIstate = 23;
break;
default:
/* Your code here */
break;
}
break;
case 23:
// Show Alarm2, blink C3
lcd.clear();
lcd.setCursor(0,0);
lcd << "Skift lukketid:";
lcd.setCursor(0,1);
lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << "";
lcd.setCursor(3,1);
lcd.blink();
switch (userState)
{
case btnSELECT:
/* Your code here */ // Do nothing
break;
case btnRESET:
/* Your code here */ // Do nothing
break;
case btnUP:
/* Your code here */ //Add 10 to variable minutes
//If variable minutes is 59< then subtract 50
if ((50 <= tid.Minute))
{
tid.Minute -= 50;
}
else
{
tid.Minute += 10;
}
break;
case btnDOWN:
/* Your code here */ //subtract 10 to variable minutes
// If variable minutes is <0 then add 50
if((0 <= tid.Minute) & (tid.Minute < 10))
{
tid.Minute += 50;
}
else
{
tid.Minute -= 10;
}
break;
case btnLEFT:
/* Your code here */ // Go to UIstate 22 to change C2
UIstate = 22;
break;
case btnRIGHT:
/* Your code here */ // Go to UIstate 24 to change C4
UIstate = 24;
break;
default:
/* Your code here */
break;
}
break;
case 24:
// Show Alarm2, blink C4
lcd.clear();
lcd.setCursor(0,0);
lcd << "Skift lukketid:";
lcd.setCursor(0,1);
lcd << ((tid.Hour<10) ? "0" : "") << tid.Hour << ":" << ((tid.Minute<10) ? "0" : "") << tid.Minute << "";
lcd.setCursor(4,1);
lcd.blink();
switch (userState)
{
case btnSELECT:
/* Your code here */ // Go to UIstate 20, Write Alarm2 to timer module
UIstate = 20;
RTC_alarm.alarm2_set(tid);
break;
case btnRESET:
/* Your code here */ // Do nothing
break;
case btnUP:
/* Your code here */ //Add 1 to variable minutes
//If variable minutes is 59< then subtract 9
if ((tid.Minute == 9) | (tid.Minute == 19) | (tid.Minute == 29) | (tid.Minute == 39) | (tid.Minute == 49) | (tid.Minute == 59))
{
tid.Minute -= 9;
}
else
{
tid.Minute += 1;
}
break;
case btnDOWN:
/* Your code here */ //subtract 1 to variable minutes
// If variable minutes is >0 then add 9
if ((tid.Minute == 0) | (tid.Minute == 10) | (tid.Minute == 20) | (tid.Minute == 30) | (tid.Minute == 40) | (tid.Minute == 50))
{
tid.Minute += 9;
}
else
{
tid.Minute -= 1;
}
break;
case btnLEFT:
/* Your code here */ // Go to UIstate 23 to change C3
UIstate = 23;
break;
case btnRIGHT:
/* Your code here */ // Do nothing
break;
default:
/* Your code here */
break;
}
break;
default: // default state, aka state 0.
// user input
break;
}
}
DS3231RTC_Alarms::DS3231RTC_Alarms()
{
// Constructor for the alarms class.
alarm1_time.long_time = 0;
alarm2_time.long_time = 0;
}
void DS3231RTC_Alarms::init_alarms(void)
{
// Setup the SQW interrupt:
DDRD &= ~(1 << DDD2); // make INT0 an input.
PORTD |= (1 << DDD2); // enable pull-up on INT0.
attachInterrupt(INT0, alarmIsr, FALLING); // Initializing the INT0 interrupt in the Arduino way.
//Disable the default square wave of the SQW pin.
RTC.squareWave(SQWAVE_NONE);
//Prepare alarm1 for the interrupt.
RTC.alarm(ALARM_1); //ensure RTC interrupt flag is cleared
RTC.alarmInterrupt(ALARM_1, true);
//Prepare alarm1 for the interrupt.
RTC.alarm(ALARM_2); //ensure RTC interrupt flag is cleared
RTC.alarmInterrupt(ALARM_2, true);
// Read the alarm time from the EEPROM for UI use
for (int i = 0; i < 7; i++)
{
DS3231RTC_Alarms::alarm1_time.byte_array[0+i] = eeprom_read_byte((uint8_t *)alarm1_addr+i);
}
for (int i = 0; i < 7; i++)
{
DS3231RTC_Alarms::alarm2_time.byte_array[0+i] = eeprom_read_byte((uint8_t *)alarm2_addr+i);
}
}
void DS3231RTC_Alarms::alarm_Check(uint8_t *stat)
{
if (alarmIsrWasCalled) // if the interrupt has happened
{
if (RTC.alarm(ALARM_1)) // check if alarm1 has happened and reset it.
{
*stat = 1;
}
else if (RTC.alarm(ALARM_2)) // or else check if alarm2 has happened and reset it.
{
*stat = 2;
}
alarmIsrWasCalled = false;
}
else // else return 0
{
*stat = 0;
}
}
time_t DS3231RTC_Alarms::alarm1_get(void)
{
// returns the value from alarm1 read from the EEPROM during setup
return alarm1_time.long_time;
}
time_t DS3231RTC_Alarms::alarm2_get(void)
{
// returns the value from alarm2 read from the EEPROM during setup
return alarm2_time.long_time;
}
void DS3231RTC_Alarms::alarm1_set(tmElements_t TM)
{
// Overwrites the current alarm1 both in the DS3231 clock module and in the EEPROM.
// Overwrite the alarm1 time in the DS3231 clock module.
RTC.setAlarm(ALM1_MATCH_HOURS, TM.Second, TM.Minute, TM.Hour, 1); //daydate parameter should be between 1 and 7
RTC.alarm(ALARM_1); //ensure RTC interrupt flag is cleared
RTC.alarmInterrupt(ALARM_1, true);
// Overwrite the alarm1 time in the EEPROM.
alarm1_time.long_time = makeTime(TM);
for (int i = 0; i < 7; i++)
{
eeprom_write_byte((uint8_t *)alarm1_addr+i, alarm1_time.byte_array[0+i]);
}
// Writing debug message to serial
Serial << "Alarm1 set to " << alarm1_time.long_time << " or ";
Serial << TM.Hour << ":" << TM.Minute << ":" << TM.Second << endl;
}
void DS3231RTC_Alarms::alarm2_set(tmElements_t TM)
{
// Overwrites the current alarm2 both in the DS3231 clock module and in the EEPROM.
// Overwrite the alarm2 time in the DS3231 clock module.
RTC.setAlarm(ALM2_MATCH_HOURS, TM.Second, TM.Minute, TM.Hour, 1); //daydate parameter should be between 1 and 7
RTC.alarm(ALARM_2); //ensure RTC interrupt flag is cleared
RTC.alarmInterrupt(ALARM_2, true);
// Overwrite the alarm2 time in the EEPROM.
alarm2_time.long_time = makeTime(TM);
for (int i = 0; i < 7; i++)
{
eeprom_write_byte((uint8_t *)alarm2_addr+i, alarm2_time.byte_array[0+i]);
}
// Writing debug message to serial
Serial << "Alarm2 set to " << alarm2_time.long_time << " or ";
Serial << TM.Hour << ":" << TM.Minute << ":" << TM.Second << endl;
}
liftRelayArray::liftRelayArray()
{
// Constructor for the relay class
}
void liftRelayArray::relayArrayInit(void)
{
// Initialize Buttons
DDRD |= (1 << RAControl1) | (1 << RAControl2) | (1 << RAControl3) | (1 << RAControl4); // Marks pins as output.
//PORTD &= ~(1 << RAControl1) & ~(1 << RAControl2) & ~(1 << RAControl3) & ~(1 << RAControl4); // Puts pins into off state.
PORTD |= (1 << RAControl1) | (1 << RAControl2) | (1 << RAControl3) | (1 << RAControl4);
/*
Use ports:
PORTD |= (1 << DDC1); // Make PD1 = 1 (on)
PORTD &= ~(1 << DDC1); // Puts PD1 = 0 (off).
*/
// setup timer1 to make an interrupt every 1 ms
noInterrupts(); // disable all interrupts
TCCR1A = 0;
TCCR1B = 0;
TCNT1 = 0;
OCR1A = 16000; // compare match register 16MHz/1000
TCCR1B |= (1 << WGM12); // CTC mode
TCCR1B |= (1 << CS10); // No prescaler
TIMSK1 |= (1 << OCIE1A); // enable timer compare interrupt
interrupts(); // enable all interrupts
}
void liftRelayArray::relayArrayCommand(uint8_t cmd)
{
// Using the lift made easy.
switch (cmd)
{
case liftCW: // Make the cable retract - Open door
/*
PORTD &= ~(1 << RAControl1); // Turn off all relays
PORTD &= ~(1 << RAControl2);
PORTD &= ~(1 << RAControl3);
PORTD &= ~(1 << RAControl4);
delay(10);
PORTD |= (1 << RAControl1); // Turn on lift
PORTD |= (1 << RAControl4);
*/
PORTD |= (1 << RAControl1); // Turn off all relays
PORTD |= (1 << RAControl2);
PORTD |= (1 << RAControl3);
PORTD |= (1 << RAControl4);
_delay_ms(10);
PORTD &= ~(1 << RAControl1); // Turn on lift
PORTD &= ~(1 << RAControl4);
break;
case liftCCW: // Make the cable extend - Close door
/*
PORTD &= ~(1 << RAControl1); // Turn off all relays
PORTD &= ~(1 << RAControl2);
PORTD &= ~(1 << RAControl3);
PORTD &= ~(1 << RAControl4);
delay(10);
PORTD |= (1 << RAControl2); // Turn on lift
PORTD |= (1 << RAControl3);
*/
PORTD |= (1 << RAControl1); // Turn off all relays
PORTD |= (1 << RAControl2);
PORTD |= (1 << RAControl3);
PORTD |= (1 << RAControl4);
_delay_ms(10);
PORTD &= ~(1 << RAControl2); // Turn on lift
PORTD &= ~(1 << RAControl3);
break;
default: // default, aka. liftSTOP
PORTD |= (1 << RAControl1); // Turn off all relays
PORTD |= (1 << RAControl2);
PORTD |= (1 << RAControl3);
PORTD |= (1 << RAControl4);
break;
}
}
void liftRelayArray::relayAutoCommand(uint8_t alarmtrig)
{
switch(alarmtrig) // switch statement to automatically handle what should happen if alarm has happened.
{
case 1: // alarm1:
if(!RACounter1Status)
{
relayArrayCommand(liftCW);
RACounter1Status = 1; // start timer and stop after x seconds (see defines)
}
break;
case 2: // alarm2:
if(!RACounter1Status)
{
relayArrayCommand(liftCCW);
RACounter1Status = 1; // start timer and stop after x seconds (see defines)
}
break;
default: // if there was no alarm:
if (RACounter1 >= RAHold)
{
relayArrayCommand(liftSTOP);
RACounter1Status = 0;
RACounter1 = 0; // Reset RACounter1.
}
break;
}
}
ISR(TIMER1_COMPA_vect) // timer compare interrupt service routine
{
// // Debugging
// if (T1Timer >= 1000)
// {
// test++;
// T1Timer = 0;
//
// Serial << "Test is: " << test << " and RACounter is: " << RACounter1 << endl;
// }
// else
// {
// T1Timer++;
// }
// HMI interface timers:
if (!btnStat)
{
btnStat = HMI.read_LCD_buttons();
}
if (UIdelayStat == 1)
{
UIdelay++;
}
// RelayArray:
if (RACounter1Status == 1)
{
RACounter1++;
}
}
#endif
| 22.344212 | 131 | 0.580676 | [
"object"
] |
3ac82edcc1fba81a90fdde57b74904ac15261c98 | 41,319 | c | C | mame/src/emu/sound/disc_flt.c | clobber/MAME-OS-X | ca11d0e946636bda042b6db55c82113e5722fc08 | [
"MIT"
] | 15 | 2015-03-03T23:15:57.000Z | 2021-11-12T07:09:24.000Z | mame/src/emu/sound/disc_flt.c | clobber/MAME-OS-X | ca11d0e946636bda042b6db55c82113e5722fc08 | [
"MIT"
] | null | null | null | mame/src/emu/sound/disc_flt.c | clobber/MAME-OS-X | ca11d0e946636bda042b6db55c82113e5722fc08 | [
"MIT"
] | 8 | 2015-07-07T16:40:44.000Z | 2020-08-18T06:57:29.000Z | /************************************************************************
*
* MAME - Discrete sound system emulation library
*
* Written by Keith Wilkins (mame@esplexo.co.uk)
*
* (c) K.Wilkins 2000
*
***********************************************************************
*
* DST_CRFILTER - Simple CR filter & also highpass filter
* DST_FILTER1 - Generic 1st order filter
* DST_FILTER2 - Generic 2nd order filter
* DST_OP_AMP_FILT - Op Amp filter circuits
* DST_RC_CIRCUIT_1 - RC charge/discharge circuit
* DST_RCDISC - Simple discharging RC
* DST_RCDISC2 - Simple charge R1/C, discharge R0/C
* DST_RCDISC3 - Simple charge R1/c, discharge R0*R1/(R0+R1)/C
* DST_RCDISC4 - Various charge/discharge circuits
* DST_RCDISC5 - Diode in series with R//C
* DST_RCDISC_MOD - RC triggered by logic and modulated
* DST_RCFILTER - Simple RC filter & also lowpass filter
* DST_RCFILTER_SW - Usage of node_description values for switchable RC filter
* DST_RCINTEGRATE - Two diode inputs, transistor and a R/C charge
* discharge network
* DST_SALLEN_KEY - Sallen-Key filter circuit
*
************************************************************************/
/************************************************************************
*
* DST_CRFILTER - Usage of node_description values for CR filter
*
* input[0] - Enable input value
* input[1] - input value
* input[2] - Resistor value (initialization only)
* input[3] - Capacitor Value (initialization only)
* input[4] - Voltage reference. Usually 0V.
*
************************************************************************/
#define DST_CRFILTER__IN DISCRETE_INPUT(0)
#define DST_CRFILTER__R DISCRETE_INPUT(1)
#define DST_CRFILTER__C DISCRETE_INPUT(2)
#define DST_CRFILTER__VREF DISCRETE_INPUT(3)
DISCRETE_STEP(dst_crfilter)
{
if (UNEXPECTED(m_has_rc_nodes))
{
double rc = DST_CRFILTER__R * DST_CRFILTER__C;
if (rc != m_rc)
{
m_rc = rc;
m_exponent = RC_CHARGE_EXP(rc);
}
}
double v_out = DST_CRFILTER__IN - m_vCap;
double v_diff = v_out - DST_CRFILTER__VREF;
set_output(0, v_out);
m_vCap += v_diff * m_exponent;
}
DISCRETE_RESET(dst_crfilter)
{
m_has_rc_nodes = this->input_is_node() & 0x6;
m_rc = DST_CRFILTER__R * DST_CRFILTER__C;
m_exponent = RC_CHARGE_EXP(m_rc);
m_vCap = 0;
set_output(0, DST_CRFILTER__IN);
}
/************************************************************************
*
* DST_FILTER1 - Generic 1st order filter
*
* input[0] - Enable input value
* input[1] - input value
* input[2] - Frequency value (initialization only)
* input[3] - Filter type (initialization only)
*
************************************************************************/
#define DST_FILTER1__ENABLE DISCRETE_INPUT(0)
#define DST_FILTER1__IN DISCRETE_INPUT(1)
#define DST_FILTER1__FREQ DISCRETE_INPUT(2)
#define DST_FILTER1__TYPE DISCRETE_INPUT(3)
static void calculate_filter1_coefficients(discrete_base_node *node, double fc, double type,
struct discrete_filter_coeff &coeff)
{
double den, w, two_over_T;
/* calculate digital filter coefficents */
/*w = 2.0*M_PI*fc; no pre-warping */
w = node->sample_rate()*2.0*tan(M_PI*fc/node->sample_rate()); /* pre-warping */
two_over_T = 2.0*node->sample_rate();
den = w + two_over_T;
coeff.a1 = (w - two_over_T)/den;
if (type == DISC_FILTER_LOWPASS)
{
coeff.b0 = coeff.b1 = w/den;
}
else if (type == DISC_FILTER_HIGHPASS)
{
coeff.b0 = two_over_T/den;
coeff.b1 = -(coeff.b0);
}
else
{
/* FIXME: reenable */
//node->m_device->discrete_log("calculate_filter1_coefficients() - Invalid filter type for 1st order filter.");
}
}
DISCRETE_STEP(dst_filter1)
{
double gain = 1.0;
double v_out;
if (DST_FILTER1__ENABLE == 0.0)
{
gain = 0.0;
}
v_out = -m_fc.a1*m_fc.y1 + m_fc.b0*gain*DST_FILTER1__IN + m_fc.b1*m_fc.x1;
m_fc.x1 = gain*DST_FILTER1__IN;
m_fc.y1 = v_out;
set_output(0, v_out);
}
DISCRETE_RESET(dst_filter1)
{
calculate_filter1_coefficients(this, DST_FILTER1__FREQ, DST_FILTER1__TYPE, m_fc);
set_output(0, 0);
}
/************************************************************************
*
* DST_FILTER2 - Generic 2nd order filter
*
* input[0] - Enable input value
* input[1] - input value
* input[2] - Frequency value (initialization only)
* input[3] - Damping value (initialization only)
* input[4] - Filter type (initialization only)
*
************************************************************************/
#define DST_FILTER2__ENABLE DISCRETE_INPUT(0)
#define DST_FILTER2__IN DISCRETE_INPUT(1)
#define DST_FILTER2__FREQ DISCRETE_INPUT(2)
#define DST_FILTER2__DAMP DISCRETE_INPUT(3)
#define DST_FILTER2__TYPE DISCRETE_INPUT(4)
static void calculate_filter2_coefficients(discrete_base_node *node,
double fc, double d, double type,
struct discrete_filter_coeff &coeff)
{
double w; /* cutoff freq, in radians/sec */
double w_squared;
double den; /* temp variable */
double two_over_T = 2 * node->sample_rate();
double two_over_T_squared = two_over_T * two_over_T;
/* calculate digital filter coefficents */
/*w = 2.0*M_PI*fc; no pre-warping */
w = node->sample_rate() * 2.0 * tan(M_PI * fc / node->sample_rate()); /* pre-warping */
w_squared = w * w;
den = two_over_T_squared + d*w*two_over_T + w_squared;
coeff.a1 = 2.0 * (-two_over_T_squared + w_squared) / den;
coeff.a2 = (two_over_T_squared - d * w * two_over_T + w_squared) / den;
if (type == DISC_FILTER_LOWPASS)
{
coeff.b0 = coeff.b2 = w_squared/den;
coeff.b1 = 2.0 * (coeff.b0);
}
else if (type == DISC_FILTER_BANDPASS)
{
coeff.b0 = d * w * two_over_T / den;
coeff.b1 = 0.0;
coeff.b2 = -(coeff.b0);
}
else if (type == DISC_FILTER_HIGHPASS)
{
coeff.b0 = coeff.b2 = two_over_T_squared / den;
coeff.b1 = -2.0 * (coeff.b0);
}
else
{
/* FIXME: reenable */
//node->device->discrete_log("calculate_filter2_coefficients() - Invalid filter type for 2nd order filter.");
}
}
DISCRETE_STEP(dst_filter2)
{
double gain = 1.0;
double v_out;
if (DST_FILTER2__ENABLE == 0.0)
{
gain = 0.0;
}
v_out = -m_fc.a1 * m_fc.y1 - m_fc.a2 * m_fc.y2 +
m_fc.b0 * gain * DST_FILTER2__IN + m_fc.b1 * m_fc.x1 + m_fc.b2 * m_fc.x2;
m_fc.x2 = m_fc.x1;
m_fc.x1 = gain * DST_FILTER2__IN;
m_fc.y2 = m_fc.y1;
m_fc.y1 = v_out;
set_output(0, v_out);
}
DISCRETE_RESET(dst_filter2)
{
calculate_filter2_coefficients(this, DST_FILTER2__FREQ, DST_FILTER2__DAMP, DST_FILTER2__TYPE,
m_fc);
set_output(0, 0);
}
/************************************************************************
*
* DST_OP_AMP_FILT - Op Amp filter circuit RC filter
*
* input[0] - Enable input value
* input[1] - IN0 node
* input[2] - IN1 node
* input[3] - Filter Type
*
* also passed discrete_op_amp_filt_info structure
*
* Mar 2004, D Renaud.
************************************************************************/
#define DST_OP_AMP_FILT__ENABLE DISCRETE_INPUT(0)
#define DST_OP_AMP_FILT__INP1 DISCRETE_INPUT(1)
#define DST_OP_AMP_FILT__INP2 DISCRETE_INPUT(2)
#define DST_OP_AMP_FILT__TYPE DISCRETE_INPUT(3)
DISCRETE_STEP(dst_op_amp_filt)
{
DISCRETE_DECLARE_INFO(discrete_op_amp_filt_info)
double v_out = 0;
double i, v = 0;
if (DST_OP_AMP_FILT__ENABLE)
{
if (m_is_norton)
{
v = DST_OP_AMP_FILT__INP1 - OP_AMP_NORTON_VBE;
if (v < 0) v = 0;
}
else
{
/* Millman the input voltages. */
i = m_iFixed;
switch (m_type)
{
case DISC_OP_AMP_FILTER_IS_LOW_PASS_1_A:
i += (DST_OP_AMP_FILT__INP1 - DST_OP_AMP_FILT__INP2) / info->r1;
if (info->r2 != 0)
i += (m_vP - DST_OP_AMP_FILT__INP2) / info->r2;
if (info->r3 != 0)
i += (m_vN - DST_OP_AMP_FILT__INP2) / info->r3;
break;
default:
i += (DST_OP_AMP_FILT__INP1 - m_vRef) / info->r1;
if (info->r2 != 0)
i += (DST_OP_AMP_FILT__INP2 - m_vRef) / info->r2;
break;
}
v = i * m_rTotal;
}
switch (m_type)
{
case DISC_OP_AMP_FILTER_IS_LOW_PASS_1:
m_vC1 += (v - m_vC1) * m_exponentC1;
v_out = m_vC1 * m_gain + info->vRef;
break;
case DISC_OP_AMP_FILTER_IS_LOW_PASS_1_A:
m_vC1 += (v - m_vC1) * m_exponentC1;
v_out = m_vC1 * m_gain + DST_OP_AMP_FILT__INP2;
break;
case DISC_OP_AMP_FILTER_IS_HIGH_PASS_1:
v_out = (v - m_vC1) * m_gain + info->vRef;
m_vC1 += (v - m_vC1) * m_exponentC1;
break;
case DISC_OP_AMP_FILTER_IS_BAND_PASS_1:
v_out = (v - m_vC2);
m_vC2 += (v - m_vC2) * m_exponentC2;
m_vC1 += (v_out - m_vC1) * m_exponentC1;
v_out = m_vC1 * m_gain + info->vRef;
break;
case DISC_OP_AMP_FILTER_IS_BAND_PASS_0 | DISC_OP_AMP_IS_NORTON:
m_vC1 += (v - m_vC1) * m_exponentC1;
m_vC2 += (m_vC1 - m_vC2) * m_exponentC2;
v = m_vC2;
v_out = v - m_vC3;
m_vC3 += (v - m_vC3) * m_exponentC3;
i = v_out / m_rTotal;
v_out = (m_iFixed - i) * info->rF;
break;
case DISC_OP_AMP_FILTER_IS_HIGH_PASS_0 | DISC_OP_AMP_IS_NORTON:
v_out = v - m_vC1;
m_vC1 += (v - m_vC1) * m_exponentC1;
i = v_out / m_rTotal;
v_out = (m_iFixed - i) * info->rF;
break;
case DISC_OP_AMP_FILTER_IS_BAND_PASS_1M:
case DISC_OP_AMP_FILTER_IS_BAND_PASS_1M | DISC_OP_AMP_IS_NORTON:
v_out = -m_fc.a1 * m_fc.y1 - m_fc.a2 * m_fc.y2 +
m_fc.b0 * v + m_fc.b1 * m_fc.x1 + m_fc.b2 * m_fc.x2 +
m_vRef;
m_fc.x2 = m_fc.x1;
m_fc.x1 = v;
m_fc.y2 = m_fc.y1;
break;
}
/* Clip the output to the voltage rails.
* This way we get the original distortion in all it's glory.
*/
if (v_out > m_vP) v_out = m_vP;
if (v_out < m_vN) v_out = m_vN;
m_fc.y1 = v_out - m_vRef;
set_output(0, v_out);
}
else
set_output(0, 0);
}
DISCRETE_RESET(dst_op_amp_filt)
{
DISCRETE_DECLARE_INFO(discrete_op_amp_filt_info)
/* Convert the passed filter type into an int for easy use. */
m_type = (int)DST_OP_AMP_FILT__TYPE & DISC_OP_AMP_FILTER_TYPE_MASK;
m_is_norton = (int)DST_OP_AMP_FILT__TYPE & DISC_OP_AMP_IS_NORTON;
if (m_is_norton)
{
m_vRef = 0;
m_rTotal = info->r1;
if (m_type == (DISC_OP_AMP_FILTER_IS_BAND_PASS_0 | DISC_OP_AMP_IS_NORTON))
m_rTotal += info->r2 + info->r3;
/* Setup the current to the + input. */
m_iFixed = (info->vP - OP_AMP_NORTON_VBE) / info->r4;
/* Set the output max. */
m_vP = info->vP - OP_AMP_NORTON_VBE;
m_vN = info->vN;
}
else
{
m_vRef = info->vRef;
/* Set the output max. */
m_vP = info->vP - OP_AMP_VP_RAIL_OFFSET;
m_vN = info->vN;
/* Work out the input resistance. It is all input and bias resistors in parallel. */
m_rTotal = 1.0 / info->r1; /* There has to be an R1. Otherwise the table is wrong. */
if (info->r2 != 0) m_rTotal += 1.0 / info->r2;
if (info->r3 != 0) m_rTotal += 1.0 / info->r3;
m_rTotal = 1.0 / m_rTotal;
m_iFixed = 0;
m_rRatio = info->rF / (m_rTotal + info->rF);
m_gain = -info->rF / m_rTotal;
}
switch (m_type)
{
case DISC_OP_AMP_FILTER_IS_LOW_PASS_1:
case DISC_OP_AMP_FILTER_IS_LOW_PASS_1_A:
m_exponentC1 = RC_CHARGE_EXP(info->rF * info->c1);
m_exponentC2 = 0;
break;
case DISC_OP_AMP_FILTER_IS_HIGH_PASS_1:
m_exponentC1 = RC_CHARGE_EXP(m_rTotal * info->c1);
m_exponentC2 = 0;
break;
case DISC_OP_AMP_FILTER_IS_BAND_PASS_1:
m_exponentC1 = RC_CHARGE_EXP(info->rF * info->c1);
m_exponentC2 = RC_CHARGE_EXP(m_rTotal * info->c2);
break;
case DISC_OP_AMP_FILTER_IS_BAND_PASS_1M | DISC_OP_AMP_IS_NORTON:
if (info->r2 == 0)
m_rTotal = info->r1;
else
m_rTotal = RES_2_PARALLEL(info->r1, info->r2);
case DISC_OP_AMP_FILTER_IS_BAND_PASS_1M:
{
double fc = 1.0 / (2 * M_PI * sqrt(m_rTotal * info->rF * info->c1 * info->c2));
double d = (info->c1 + info->c2) / sqrt(info->rF / m_rTotal * info->c1 * info->c2);
double gain = -info->rF / m_rTotal * info->c2 / (info->c1 + info->c2);
calculate_filter2_coefficients(this, fc, d, DISC_FILTER_BANDPASS, m_fc);
m_fc.b0 *= gain;
m_fc.b1 *= gain;
m_fc.b2 *= gain;
if (m_is_norton)
m_vRef = (info->vP - OP_AMP_NORTON_VBE) / info->r3 * info->rF;
else
m_vRef = info->vRef;
break;
}
case DISC_OP_AMP_FILTER_IS_BAND_PASS_0 | DISC_OP_AMP_IS_NORTON:
m_exponentC1 = RC_CHARGE_EXP(RES_2_PARALLEL(info->r1, info->r2 + info->r3 + info->r4) * info->c1);
m_exponentC2 = RC_CHARGE_EXP(RES_2_PARALLEL(info->r1 + info->r2, info->r3 + info->r4) * info->c2);
m_exponentC3 = RC_CHARGE_EXP((info->r1 + info->r2 + info->r3 + info->r4) * info->c3);
break;
case DISC_OP_AMP_FILTER_IS_HIGH_PASS_0 | DISC_OP_AMP_IS_NORTON:
m_exponentC1 = RC_CHARGE_EXP(info->r1 * info->c1);
break;
}
/* At startup there is no charge on the caps and output is 0V in relation to vRef. */
m_vC1 = 0;
m_vC1b = 0;
m_vC2 = 0;
m_vC3 = 0;
set_output(0, info->vRef);
}
/************************************************************************
*
* DST_RC_CIRCUIT_1 - RC charge/discharge circuit
*
************************************************************************/
#define DST_RC_CIRCUIT_1__IN0 DISCRETE_INPUT(0)
#define DST_RC_CIRCUIT_1__IN1 DISCRETE_INPUT(1)
#define DST_RC_CIRCUIT_1__R DISCRETE_INPUT(2)
#define DST_RC_CIRCUIT_1__C DISCRETE_INPUT(3)
#define CD4066_R_ON 270
DISCRETE_STEP( dst_rc_circuit_1 )
{
if (DST_RC_CIRCUIT_1__IN0 == 0)
if (DST_RC_CIRCUIT_1__IN1 == 0)
/* cap is floating and does not change charge */
/* output is pulled to ground */
set_output(0, 0);
else
{
/* cap is discharged */
m_v_cap -= m_v_cap * m_exp_2;
set_output(0, m_v_cap * m_v_drop);
}
else
if (DST_RC_CIRCUIT_1__IN1 == 0)
{
/* cap is charged */
m_v_cap += (5.0 - m_v_cap) * m_exp_1;
/* output is pulled to ground */
set_output(0, 0);
}
else
{
/* cap is charged slightly less */
m_v_cap += (m_v_charge_1_2 - m_v_cap) * m_exp_1_2;
set_output(0, m_v_cap * m_v_drop);
}
}
DISCRETE_RESET( dst_rc_circuit_1 )
{
/* the charging voltage across the cap based on in2*/
m_v_drop = RES_VOLTAGE_DIVIDER(CD4066_R_ON, CD4066_R_ON + DST_RC_CIRCUIT_1__R);
m_v_charge_1_2 = 5.0 * m_v_drop;
m_v_cap = 0;
/* precalculate charging exponents */
/* discharge cap - in1 = 0, in2 = 1*/
m_exp_2 = RC_CHARGE_EXP((CD4066_R_ON + DST_RC_CIRCUIT_1__R) * DST_RC_CIRCUIT_1__C);
/* charge cap - in1 = 1, in2 = 0 */
m_exp_1 = RC_CHARGE_EXP(CD4066_R_ON * DST_RC_CIRCUIT_1__C);
/* charge cap - in1 = 1, in2 = 1 */
m_exp_1_2 = RC_CHARGE_EXP(RES_2_PARALLEL(CD4066_R_ON, CD4066_R_ON + DST_RC_CIRCUIT_1__R) * DST_RC_CIRCUIT_1__C);
/* starts at 0 until cap starts charging */
set_output(0, 0);
}
/************************************************************************
*
* DST_RCDISC - Usage of node_description values for RC discharge
* (inverse slope of DST_RCFILTER)
*
* input[0] - Enable input value
* input[1] - input value
* input[2] - Resistor value (initialization only)
* input[3] - Capacitor Value (initialization only)
*
************************************************************************/
#define DST_RCDISC__ENABLE DISCRETE_INPUT(0)
#define DST_RCDISC__IN DISCRETE_INPUT(1)
#define DST_RCDISC__R DISCRETE_INPUT(2)
#define DST_RCDISC__C DISCRETE_INPUT(3)
DISCRETE_STEP(dst_rcdisc)
{
switch (m_state)
{
case 0: /* waiting for trigger */
if(DST_RCDISC__ENABLE)
{
m_state = 1;
m_t = 0;
}
set_output(0, 0);
break;
case 1:
if (DST_RCDISC__ENABLE)
{
set_output(0, DST_RCDISC__IN * exp(m_t / m_exponent0));
m_t += this->sample_time();
} else
{
m_state = 0;
}
}
}
DISCRETE_RESET(dst_rcdisc)
{
set_output(0, 0);
m_state = 0;
m_t = 0;
m_exponent0=-1.0 * DST_RCDISC__R * DST_RCDISC__C;
}
/************************************************************************
*
* DST_RCDISC2 - Usage of node_description values for RC discharge
* Has switchable charge resistor/input
*
* input[0] - Switch input value
* input[1] - input[0] value
* input[2] - Resistor0 value (initialization only)
* input[3] - input[1] value
* input[4] - Resistor1 value (initialization only)
* input[5] - Capacitor Value (initialization only)
*
************************************************************************/
#define DST_RCDISC2__ENABLE DISCRETE_INPUT(0)
#define DST_RCDISC2__IN0 DISCRETE_INPUT(1)
#define DST_RCDISC2__R0 DISCRETE_INPUT(2)
#define DST_RCDISC2__IN1 DISCRETE_INPUT(3)
#define DST_RCDISC2__R1 DISCRETE_INPUT(4)
#define DST_RCDISC2__C DISCRETE_INPUT(5)
DISCRETE_STEP(dst_rcdisc2)
{
double diff;
/* Works differently to other as we are always on, no enable */
/* exponential based in difference between input/output */
diff = ((DST_RCDISC2__ENABLE == 0) ? DST_RCDISC2__IN0 : DST_RCDISC2__IN1) - m_v_out;
diff = diff - (diff * ((DST_RCDISC2__ENABLE == 0) ? m_exponent0 : m_exponent1));
m_v_out += diff;
set_output(0, m_v_out);
}
DISCRETE_RESET(dst_rcdisc2)
{
m_v_out = 0;
m_state = 0;
m_t = 0;
m_exponent0 = RC_DISCHARGE_EXP(DST_RCDISC2__R0 * DST_RCDISC2__C);
m_exponent1 = RC_DISCHARGE_EXP(DST_RCDISC2__R1 * DST_RCDISC2__C);
}
/************************************************************************
*
* DST_RCDISC3 - Usage of node_description values for RC discharge
*
*
* input[0] - Enable
* input[1] - input value
* input[2] - Resistor0 value (initialization only)
* input[4] - Resistor1 value (initialization only)
* input[5] - Capacitor Value (initialization only)
* input[6] - Diode Junction voltage (initialization only)
*
************************************************************************/
#define DST_RCDISC3__ENABLE DISCRETE_INPUT(0)
#define DST_RCDISC3__IN DISCRETE_INPUT(1)
#define DST_RCDISC3__R1 DISCRETE_INPUT(2)
#define DST_RCDISC3__R2 DISCRETE_INPUT(3)
#define DST_RCDISC3__C DISCRETE_INPUT(4)
#define DST_RCDISC3__DJV DISCRETE_INPUT(5)
DISCRETE_STEP(dst_rcdisc3)
{
double diff;
/* Exponential based in difference between input/output */
if(DST_RCDISC3__ENABLE)
{
diff = DST_RCDISC3__IN - m_v_out;
if (m_v_diode > 0)
{
if (diff > 0)
{
diff = diff * m_exponent0;
}
else if (diff < -m_v_diode)
{
diff = diff * m_exponent1;
}
else
{
diff = diff * m_exponent0;
}
}
else
{
if (diff < 0)
{
diff = diff * m_exponent0;
}
else if (diff > -m_v_diode)
{
diff = diff * m_exponent1;
}
else
{
diff = diff * m_exponent0;
}
}
m_v_out += diff;
set_output(0, m_v_out);
}
else
{
set_output(0, 0);
}
}
DISCRETE_RESET(dst_rcdisc3)
{
m_v_out = 0;
m_state = 0;
m_t = 0;
m_v_diode = DST_RCDISC3__DJV;
m_exponent0 = RC_CHARGE_EXP(DST_RCDISC3__R1 * DST_RCDISC3__C);
m_exponent1 = RC_CHARGE_EXP(RES_2_PARALLEL(DST_RCDISC3__R1, DST_RCDISC3__R2) * DST_RCDISC3__C);
}
/************************************************************************
*
* DST_RCDISC4 - Various charge/discharge circuits
*
* input[0] - Enable input value
* input[1] - input value
* input[2] - R1 Resistor value (initialization only)
* input[2] - R2 Resistor value (initialization only)
* input[4] - C1 Capacitor Value (initialization only)
* input[4] - vP power source (initialization only)
* input[4] - circuit type (initialization only)
*
************************************************************************/
#define DST_RCDISC4__ENABLE DISCRETE_INPUT(0)
#define DST_RCDISC4__IN DISCRETE_INPUT(1)
#define DST_RCDISC4__R1 DISCRETE_INPUT(2)
#define DST_RCDISC4__R2 DISCRETE_INPUT(3)
#define DST_RCDISC4__R3 DISCRETE_INPUT(4)
#define DST_RCDISC4__C1 DISCRETE_INPUT(5)
#define DST_RCDISC4__VP DISCRETE_INPUT(6)
#define DST_RCDISC4__TYPE DISCRETE_INPUT(7)
DISCRETE_STEP(dst_rcdisc4)
{
int inp1 = (DST_RCDISC4__IN == 0) ? 0 : 1;
double v_out = 0;
if (DST_RCDISC4__ENABLE == 0)
{
set_output(0, 0);
return;
}
switch (m_type)
{
case 1:
case 3:
m_vC1 += ((m_v[inp1] - m_vC1) * m_exp[inp1]);
v_out = m_vC1;
break;
}
/* clip output */
if (v_out > m_max_out) v_out = m_max_out;
if (v_out < 0) v_out = 0;
set_output(0, v_out);
}
DISCRETE_RESET( dst_rcdisc4)
{
double v, i, r, rT;
m_type = 0;
/* some error checking. */
if (DST_RCDISC4__R1 <= 0 || DST_RCDISC4__R2 <= 0 || DST_RCDISC4__C1 <= 0 || (DST_RCDISC4__R3 <= 0 && m_type == 1))
{
m_device->discrete_log("Invalid component values in NODE_%d.\n", this->index());
return;
}
if (DST_RCDISC4__VP < 3)
{
m_device->discrete_log("vP must be >= 3V in NODE_%d.\n", this->index());
return;
}
if (DST_RCDISC4__TYPE < 1 || DST_RCDISC4__TYPE > 3)
{
m_device->discrete_log("Invalid circuit type in NODE_%d.\n", this->index());
return;
}
m_vC1 = 0;
/* store type as integer */
m_type = (int)DST_RCDISC4__TYPE;
/* setup the maximum op-amp output. */
m_max_out = DST_RCDISC4__VP - OP_AMP_VP_RAIL_OFFSET;
switch (m_type)
{
case 1:
/* We will simulate this as a voltage divider with 2 states depending
* on the input. But we have to take the diodes into account.
*/
v = DST_RCDISC4__VP - .5; /* diode drop */
/* When the input is 1, both R1 & R3 are basically in parallel. */
r = RES_2_PARALLEL(DST_RCDISC4__R1, DST_RCDISC4__R3);
rT = DST_RCDISC4__R2 + r;
i = v / rT;
m_v[1] = i * r + .5;
rT = RES_2_PARALLEL(DST_RCDISC4__R2, r);
m_exp[1] = RC_CHARGE_EXP(rT * DST_RCDISC4__C1);
/* When the input is 0, R1 is out of circuit. */
rT = DST_RCDISC4__R2 + DST_RCDISC4__R3;
i = v / rT;
m_v[0] = i * DST_RCDISC4__R3 + .5;
rT = RES_2_PARALLEL(DST_RCDISC4__R2, DST_RCDISC4__R3);
m_exp[0] = RC_CHARGE_EXP(rT * DST_RCDISC4__C1);
break;
case 3:
/* We will simulate this as a voltage divider with 2 states depending
* on the input. The 1k pullup is in parallel with the internal TTL
* resistance, so we will just use .5k in series with R1.
*/
r = 500.0 + DST_RCDISC4__R1;
m_v[1] = RES_VOLTAGE_DIVIDER(r, DST_RCDISC4__R2) * (5.0 - 0.5);
rT = RES_2_PARALLEL(r, DST_RCDISC4__R2);
m_exp[1] = RC_CHARGE_EXP(rT * DST_RCDISC4__C1);
/* When the input is 0, R1 is out of circuit. */
m_v[0] = 0;
m_exp[0] = RC_CHARGE_EXP(DST_RCDISC4__R2 * DST_RCDISC4__C1);
break;
}
}
/************************************************************************
*
* DST_RCDISC5 - Diode in series with R//C
*
* input[0] - Enable input value
* input[1] - input value
* input[2] - Resistor value (initialization only)
* input[3] - Capacitor Value (initialization only)
*
************************************************************************/
#define DST_RCDISC5__ENABLE DISCRETE_INPUT(0)
#define DST_RCDISC5__IN DISCRETE_INPUT(1)
#define DST_RCDISC5__R DISCRETE_INPUT(2)
#define DST_RCDISC5__C DISCRETE_INPUT(3)
DISCRETE_STEP( dst_rcdisc5)
{
double diff,u;
/* Exponential based in difference between input/output */
u = DST_RCDISC5__IN - 0.7; /* Diode drop */
if( u < 0)
u = 0;
diff = u - m_v_cap;
if(DST_RCDISC5__ENABLE)
{
if(diff < 0)
diff = diff * m_exponent0;
m_v_cap += diff;
set_output(0, m_v_cap);
}
else
{
if(diff > 0)
m_v_cap = u;
set_output(0, 0);
}
}
DISCRETE_RESET( dst_rcdisc5)
{
set_output(0, 0);
m_state = 0;
m_t = 0;
m_v_cap = 0;
m_exponent0 = RC_CHARGE_EXP(DST_RCDISC5__R * DST_RCDISC5__C);
}
/************************************************************************
*
* DST_RCDISC_MOD - RC triggered by logic and modulated
*
* input[0] - Enable input value
* input[1] - input value 1
* input[2] - input value 2
* input[3] - Resistor 1 value (initialization only)
* input[4] - Resistor 2 value (initialization only)
* input[5] - Resistor 3 value (initialization only)
* input[6] - Resistor 4 value (initialization only)
* input[7] - Capacitor Value (initialization only)
* input[8] - Voltage Value (initialization only)
*
************************************************************************/
#define DST_RCDISC_MOD__IN1 DISCRETE_INPUT(0)
#define DST_RCDISC_MOD__IN2 DISCRETE_INPUT(1)
#define DST_RCDISC_MOD__R1 DISCRETE_INPUT(2)
#define DST_RCDISC_MOD__R2 DISCRETE_INPUT(3)
#define DST_RCDISC_MOD__R3 DISCRETE_INPUT(4)
#define DST_RCDISC_MOD__R4 DISCRETE_INPUT(5)
#define DST_RCDISC_MOD__C DISCRETE_INPUT(6)
#define DST_RCDISC_MOD__VP DISCRETE_INPUT(7)
DISCRETE_STEP(dst_rcdisc_mod)
{
double diff, v_cap, u, vD;
int mod_state, mod1_state, mod2_state;
/* Exponential based in difference between input/output */
v_cap = m_v_cap;
mod1_state = DST_RCDISC_MOD__IN1 > 0.5;
mod2_state = DST_RCDISC_MOD__IN2 > 0.6;
mod_state = (mod2_state << 1) + mod1_state;
u = mod1_state ? 0 : DST_RCDISC_MOD__VP;
/* Clamp */
diff = u - v_cap;
vD = diff * m_vd_gain[mod_state];
if (vD < -0.6)
{
diff = u + 0.6 - v_cap;
diff -= diff * m_exp_low[mod1_state];
v_cap += diff;
set_output(0, mod2_state ? 0 : -0.6);
}
else
{
diff -= diff * m_exp_high[mod_state];
v_cap += diff;
/* neglecting current through R3 drawn by next8 node */
set_output(0, mod2_state ? 0: (u - v_cap) * m_gain[mod1_state]);
}
m_v_cap = v_cap;
}
DISCRETE_RESET(dst_rcdisc_mod)
{
double rc[2], rc2[2];
/* pre-calculate fixed values */
/* DST_RCDISC_MOD__IN1 <= 0.5 */
rc[0] = DST_RCDISC_MOD__R1 + DST_RCDISC_MOD__R2;
if (rc[0] < 1) rc[0] = 1;
m_exp_low[0] = RC_DISCHARGE_EXP(DST_RCDISC_MOD__C * rc[0]);
m_gain[0] = RES_VOLTAGE_DIVIDER(rc[0], DST_RCDISC_MOD__R4);
/* DST_RCDISC_MOD__IN1 > 0.5 */
rc[1] = DST_RCDISC_MOD__R2;
if (rc[1] < 1) rc[1] = 1;
m_exp_low[1] = RC_DISCHARGE_EXP(DST_RCDISC_MOD__C * rc[1]);
m_gain[1] = RES_VOLTAGE_DIVIDER(rc[1], DST_RCDISC_MOD__R4);
/* DST_RCDISC_MOD__IN2 <= 0.6 */
rc2[0] = DST_RCDISC_MOD__R4;
/* DST_RCDISC_MOD__IN2 > 0.6 */
rc2[1] = RES_2_PARALLEL(DST_RCDISC_MOD__R3, DST_RCDISC_MOD__R4);
/* DST_RCDISC_MOD__IN1 <= 0.5 && DST_RCDISC_MOD__IN2 <= 0.6 */
m_exp_high[0] = RC_DISCHARGE_EXP(DST_RCDISC_MOD__C * (rc[0] + rc2[0]));
m_vd_gain[0] = RES_VOLTAGE_DIVIDER(rc[0], rc2[0]);
/* DST_RCDISC_MOD__IN1 > 0.5 && DST_RCDISC_MOD__IN2 <= 0.6 */
m_exp_high[1] = RC_DISCHARGE_EXP(DST_RCDISC_MOD__C * (rc[1] + rc2[0]));
m_vd_gain[1] = RES_VOLTAGE_DIVIDER(rc[1], rc2[0]);
/* DST_RCDISC_MOD__IN1 <= 0.5 && DST_RCDISC_MOD__IN2 > 0.6 */
m_exp_high[2] = RC_DISCHARGE_EXP(DST_RCDISC_MOD__C * (rc[0] + rc2[1]));
m_vd_gain[2] = RES_VOLTAGE_DIVIDER(rc[0], rc2[1]);
/* DST_RCDISC_MOD__IN1 > 0.5 && DST_RCDISC_MOD__IN2 > 0.6 */
m_exp_high[3] = RC_DISCHARGE_EXP(DST_RCDISC_MOD__C * (rc[1] + rc2[1]));
m_vd_gain[3] = RES_VOLTAGE_DIVIDER(rc[1], rc2[1]);
m_v_cap = 0;
set_output(0, 0);
}
/************************************************************************
*
* DST_RCFILTER - Usage of node_description values for RC filter
*
* input[0] - Enable input value
* input[1] - input value
* input[2] - Resistor value (initialization only)
* input[3] - Capacitor Value (initialization only)
* input[4] - Voltage reference. Usually 0V.
*
************************************************************************/
#define DST_RCFILTER__VIN DISCRETE_INPUT(0)
#define DST_RCFILTER__R DISCRETE_INPUT(1)
#define DST_RCFILTER__C DISCRETE_INPUT(2)
#define DST_RCFILTER__VREF DISCRETE_INPUT(3)
DISCRETE_STEP(dst_rcfilter)
{
if (EXPECTED(m_is_fast))
m_v_out += ((DST_RCFILTER__VIN - m_v_out) * m_exponent);
else
{
if (UNEXPECTED(m_has_rc_nodes))
{
double rc = DST_RCFILTER__R * DST_RCFILTER__C;
if (rc != m_rc)
{
m_rc = rc;
m_exponent = RC_CHARGE_EXP(rc);
}
}
/************************************************************************/
/* Next Value = PREV + (INPUT_VALUE - PREV)*(1-(EXP(-TIMEDELTA/RC))) */
/************************************************************************/
m_vCap += ((DST_RCFILTER__VIN - m_v_out) * m_exponent);
m_v_out = m_vCap + DST_RCFILTER__VREF;
}
set_output(0, m_v_out);
}
DISCRETE_RESET(dst_rcfilter)
{
m_has_rc_nodes = this->input_is_node() & 0x6;
m_rc = DST_RCFILTER__R * DST_RCFILTER__C;
m_exponent = RC_CHARGE_EXP(m_rc);
m_vCap = 0;
m_v_out = 0;
/* FIXME --> we really need another class here */
if (!m_has_rc_nodes && DST_RCFILTER__VREF == 0)
m_is_fast = 1;
else
m_is_fast = 0;
}
/************************************************************************
*
* DST_RCFILTER_SW - Usage of node_description values for switchable RC filter
*
* input[0] - Enable input value
* input[1] - input value
* input[2] - Resistor value (initialization only)
* input[3] - Capacitor Value (initialization only)
* input[4] - Voltage reference. Usually 0V.
*
************************************************************************/
#define DST_RCFILTER_SW__ENABLE DISCRETE_INPUT(0)
#define DST_RCFILTER_SW__VIN DISCRETE_INPUT(1)
#define DST_RCFILTER_SW__SWITCH DISCRETE_INPUT(2)
#define DST_RCFILTER_SW__R DISCRETE_INPUT(3)
#define DST_RCFILTER_SW__C(x) DISCRETE_INPUT(4+x)
/* 74HC4066 : 15
* 74VHC4066 : 15
* UTC4066 : 270 @ 5VCC, 80 @ 15VCC
* CD4066BC : 270 (Fairchild)
*
* The choice below makes scramble sound about "right". For future error reports,
* we need the exact type of switch and at which voltage (5, 12?) it is operated.
*/
#define CD4066_ON_RES (40)
// FIXME: This needs optimization !
DISCRETE_STEP(dst_rcfilter_sw)
{
int i;
int bits = (int)DST_RCFILTER_SW__SWITCH;
double us = 0;
double vIn = DST_RCFILTER_SW__VIN;
double v_out;
if (EXPECTED(DST_RCFILTER_SW__ENABLE))
{
switch (bits)
{
case 0:
v_out = vIn;
break;
case 1:
m_vCap[0] += (vIn - m_vCap[0]) * m_exp0;
v_out = m_vCap[0] + (vIn - m_vCap[0]) * m_factor;
break;
case 2:
m_vCap[1] += (vIn - m_vCap[1]) * m_exp1;
v_out = m_vCap[1] + (vIn - m_vCap[1]) * m_factor;
break;
default:
for (i = 0; i < 4; i++)
{
if (( bits & (1 << i)) != 0)
us += m_vCap[i];
}
v_out = m_f1[bits] * vIn + m_f2[bits] * us;
for (i = 0; i < 4; i++)
{
if (( bits & (1 << i)) != 0)
m_vCap[i] += (v_out - m_vCap[i]) * m_exp[i];
}
}
set_output(0, v_out);
}
else
{
set_output(0, 0);
}
}
DISCRETE_RESET(dst_rcfilter_sw)
{
int i, bits;
for (i = 0; i < 4; i++)
{
m_vCap[i] = 0;
m_exp[i] = RC_CHARGE_EXP( CD4066_ON_RES * DST_RCFILTER_SW__C(i));
}
for (bits=0; bits < 15; bits++)
{
double rs = 0;
for (i = 0; i < 4; i++)
{
if (( bits & (1 << i)) != 0)
rs += DST_RCFILTER_SW__R;
}
m_f1[bits] = RES_VOLTAGE_DIVIDER(rs, CD4066_ON_RES);
m_f2[bits] = DST_RCFILTER_SW__R / (CD4066_ON_RES + rs);
}
/* fast cases */
m_exp0 = RC_CHARGE_EXP((CD4066_ON_RES + DST_RCFILTER_SW__R) * DST_RCFILTER_SW__C(0));
m_exp1 = RC_CHARGE_EXP((CD4066_ON_RES + DST_RCFILTER_SW__R) * DST_RCFILTER_SW__C(1));
m_factor = RES_VOLTAGE_DIVIDER(DST_RCFILTER_SW__R, CD4066_ON_RES);
set_output(0, 0);
}
/************************************************************************
*
* DST_RCINTEGRATE - Two diode inputs, transistor and a R/C charge
* discharge network
*
* input[0] - Enable input value
* input[1] - input value 1
* input[2] - input value 2
* input[3] - Resistor 1 value (initialization only)
* input[4] - Resistor 2 value (initialization only)
* input[5] - Capacitor Value (initialization only)
*
************************************************************************/
#define DST_RCINTEGRATE__IN1 DISCRETE_INPUT(0)
#define DST_RCINTEGRATE__R1 DISCRETE_INPUT(1)
#define DST_RCINTEGRATE__R2 DISCRETE_INPUT(2)
#define DST_RCINTEGRATE__R3 DISCRETE_INPUT(3)
#define DST_RCINTEGRATE__C DISCRETE_INPUT(4)
#define DST_RCINTEGRATE__VP DISCRETE_INPUT(5)
#define DST_RCINTEGRATE__TYPE DISCRETE_INPUT(6)
/* Ebers-Moll large signal model
* Couriersud:
* The implementation avoids all iterative approaches in order not to burn cycles
* We will calculate Ic from vBE and use this as an indication where to go.
* The implementation may oscillate if you change the weighting factors at the
* end.
*
* This implementation is not perfect, but does it's job in dkong'
*/
/* reverse saturation current */
#define IES 7e-15
#define ALPHAT 0.99
#define KT 0.026
#define EM_IC(x) (ALPHAT * IES * exp( (x) / KT - 1.0 ))
DISCRETE_STEP( dst_rcintegrate)
{
double diff, u, iQ, iQc, iC, RG, vE;
double vP;
u = DST_RCINTEGRATE__IN1;
vP = DST_RCINTEGRATE__VP;
if ( u - 0.7 < m_vCap * m_gain_r1_r2)
{
/* discharge .... */
diff = 0.0 - m_vCap;
iC = m_c_exp1 * diff; /* iC */
diff -= diff * m_exp_exponent1;
m_vCap += diff;
iQ = 0;
vE = m_vCap * m_gain_r1_r2;
RG = vE / iC;
}
else
{
/* charging */
diff = (vP - m_vCE) * m_f - m_vCap;
iC = 0.0 - m_c_exp0 * diff; /* iC */
diff -= diff * m_exp_exponent0;
m_vCap += diff;
iQ = iC + (iC * DST_RCINTEGRATE__R1 + m_vCap) / DST_RCINTEGRATE__R2;
RG = (vP - m_vCE) / iQ;
vE = (RG - DST_RCINTEGRATE__R3) / RG * (vP - m_vCE);
}
u = DST_RCINTEGRATE__IN1;
if (u > 0.7 + vE)
{
vE = u - 0.7;
//iQc = EM_IC(u - vE);
iQc = m_EM_IC_0_7;
}
else
iQc = EM_IC(u - vE);
m_vCE = MIN(vP - 0.1, vP - RG * iQc);
/* Avoid oscillations
* The method tends to largely overshoot - no wonder without
* iterative solution approximation
*/
m_vCE = MAX(m_vCE, 0.1 );
m_vCE = 0.1 * m_vCE + 0.9 * (vP - vE - iQ * DST_RCINTEGRATE__R3);
switch (m_type)
{
case DISC_RC_INTEGRATE_TYPE1:
set_output(0, m_vCap);
break;
case DISC_RC_INTEGRATE_TYPE2:
set_output(0, vE);
break;
case DISC_RC_INTEGRATE_TYPE3:
set_output(0, MAX(0, vP - iQ * DST_RCINTEGRATE__R3));
break;
}
}
DISCRETE_RESET(dst_rcintegrate)
{
double r;
double dt = this->sample_time();
m_type = DST_RCINTEGRATE__TYPE;
m_vCap = 0;
m_vCE = 0;
/* pre-calculate fixed values */
m_gain_r1_r2 = RES_VOLTAGE_DIVIDER(DST_RCINTEGRATE__R1, DST_RCINTEGRATE__R2);
r = DST_RCINTEGRATE__R1 / DST_RCINTEGRATE__R2 * DST_RCINTEGRATE__R3 + DST_RCINTEGRATE__R1 + DST_RCINTEGRATE__R3;
m_f = RES_VOLTAGE_DIVIDER(DST_RCINTEGRATE__R3, DST_RCINTEGRATE__R2);
m_exponent0 = -1.0 * r * m_f * DST_RCINTEGRATE__C;
m_exponent1 = -1.0 * (DST_RCINTEGRATE__R1 + DST_RCINTEGRATE__R2) * DST_RCINTEGRATE__C;
m_exp_exponent0 = exp(dt / m_exponent0);
m_exp_exponent1 = exp(dt / m_exponent1);
m_c_exp0 = DST_RCINTEGRATE__C / m_exponent0 * m_exp_exponent0;
m_c_exp1 = DST_RCINTEGRATE__C / m_exponent1 * m_exp_exponent1;
m_EM_IC_0_7 = EM_IC(0.7);
set_output(0, 0);
}
/************************************************************************
*
* DST_SALLEN_KEY - Sallen-Key filter circuit
*
* input[0] - Enable input value
* input[1] - IN0 node
* input[3] - Filter Type
*
* also passed discrete_op_amp_filt_info structure
*
* 2008, couriersud
************************************************************************/
#define DST_SALLEN_KEY__ENABLE DISCRETE_INPUT(0)
#define DST_SALLEN_KEY__INP0 DISCRETE_INPUT(1)
#define DST_SALLEN_KEY__TYPE DISCRETE_INPUT(2)
DISCRETE_STEP(dst_sallen_key)
{
double gain = 1.0;
double v_out;
if (DST_SALLEN_KEY__ENABLE == 0.0)
{
gain = 0.0;
}
v_out = -m_fc.a1 * m_fc.y1 - m_fc.a2 * m_fc.y2 +
m_fc.b0 * gain * DST_SALLEN_KEY__INP0 + m_fc.b1 * m_fc.x1 + m_fc.b2 * m_fc.x2;
m_fc.x2 = m_fc.x1;
m_fc.x1 = gain * DST_SALLEN_KEY__INP0;
m_fc.y2 = m_fc.y1;
m_fc.y1 = v_out;
set_output(0, v_out);
}
DISCRETE_RESET(dst_sallen_key)
{
DISCRETE_DECLARE_INFO(discrete_op_amp_filt_info)
double freq, q;
switch ((int) DST_SALLEN_KEY__TYPE)
{
case DISC_SALLEN_KEY_LOW_PASS:
freq = 1.0 / ( 2.0 * M_PI * sqrt(info->c1 * info->c2 * info->r1 * info->r2));
q = sqrt(info->c1 * info->c2 * info->r1 * info->r2) / (info->c2 * (info->r1 + info->r2));
break;
default:
fatalerror("Unknown sallen key filter type");
}
calculate_filter2_coefficients(this, freq, 1.0 / q, DISC_FILTER_LOWPASS, m_fc);
set_output(0, 0);
}
/* !!!!!!!!!!! NEW FILTERS for testing !!!!!!!!!!!!!!!!!!!!! */
/************************************************************************
*
* DST_RCFILTERN - Usage of node_description values for RC filter
*
* input[0] - Enable input value
* input[1] - input value
* input[2] - Resistor value (initialization only)
* input[3] - Capacitor Value (initialization only)
*
************************************************************************/
#define DST_RCFILTERN__ENABLE DISCRETE_INPUT(0)
#define DST_RCFILTERN__IN DISCRETE_INPUT(1)
#define DST_RCFILTERN__R DISCRETE_INPUT(2)
#define DST_RCFILTERN__C DISCRETE_INPUT(3)
#if 0
DISCRETE_RESET(dst_rcfilterN)
{
#if 0
double f=1.0/(2*M_PI* DST_RCFILTERN__R * DST_RCFILTERN__C);
/* !!!!!!!!!!!!!! CAN'T CHEAT LIKE THIS !!!!!!!!!!!!!!!! */
/* Put this stuff in a context */
this->m_input[2] = f;
this->m_input[3] = DISC_FILTER_LOWPASS;
/* Use first order filter */
dst_filter1_reset(node);
#endif
}
#endif
/************************************************************************
*
* DST_RCDISCN - Usage of node_description values for RC discharge
* (inverse slope of DST_RCFILTER)
*
* input[0] - Enable input value
* input[1] - input value
* input[2] - Resistor value (initialization only)
* input[3] - Capacitor Value (initialization only)
*
************************************************************************/
#define DST_RCDISCN__ENABLE DISCRETE_INPUT(0)
#define DST_RCDISCN__IN DISCRETE_INPUT(1)
#define DST_RCDISCN__R DISCRETE_INPUT(2)
#define DST_RCDISCN__C DISCRETE_INPUT(3)
DISCRETE_RESET(dst_rcdiscN)
{
#if 0
double f = 1.0 / (2 * M_PI * DST_RCDISCN__R * DST_RCDISCN__C);
/* !!!!!!!!!!!!!! CAN'T CHEAT LIKE THIS !!!!!!!!!!!!!!!! */
/* Put this stuff in a context */
this->m_input[2] = f;
this->m_input[3] = DISC_FILTER_LOWPASS;
/* Use first order filter */
dst_filter1_reset(node);
#endif
}
DISCRETE_STEP(dst_rcdiscN)
{
double gain = 1.0;
double v_out;
if (DST_RCDISCN__ENABLE == 0.0)
{
gain = 0.0;
}
/* A rise in the input signal results in an instant charge, */
/* else discharge through the RC to zero */
if (gain* DST_RCDISCN__IN > m_x1)
v_out = gain* DST_RCDISCN__IN;
else
v_out = -m_a1*m_y1;
m_x1 = gain* DST_RCDISCN__IN;
m_y1 = v_out;
set_output(0, v_out);
}
/************************************************************************
*
* DST_RCDISC2N - Usage of node_description values for RC discharge
* Has switchable charge resistor/input
*
* input[0] - Switch input value
* input[1] - input[0] value
* input[2] - Resistor0 value (initialization only)
* input[3] - input[1] value
* input[4] - Resistor1 value (initialization only)
* input[5] - Capacitor Value (initialization only)
*
************************************************************************/
#define DST_RCDISC2N__ENABLE DISCRETE_INPUT(0)
#define DST_RCDISC2N__IN0 DISCRETE_INPUT(1)
#define DST_RCDISC2N__R0 DISCRETE_INPUT(2)
#define DST_RCDISC2N__IN1 DISCRETE_INPUT(3)
#define DST_RCDISC2N__R1 DISCRETE_INPUT(4)
#define DST_RCDISC2N__C DISCRETE_INPUT(5)
DISCRETE_STEP(dst_rcdisc2N)
{
double inp = ((DST_RCDISC2N__ENABLE == 0) ? DST_RCDISC2N__IN0 : DST_RCDISC2N__IN1);
double v_out;
if (DST_RCDISC2N__ENABLE == 0)
v_out = -m_fc0.a1*m_y1 + m_fc0.b0*inp + m_fc0.b1 * m_x1;
else
v_out = -m_fc1.a1*m_y1 + m_fc1.b0*inp + m_fc1.b1*m_x1;
m_x1 = inp;
m_y1 = v_out;
set_output(0, v_out);
}
DISCRETE_RESET(dst_rcdisc2N)
{
double f1,f2;
f1 = 1.0 / (2 * M_PI * DST_RCDISC2N__R0 * DST_RCDISC2N__C);
f2 = 1.0 / (2 * M_PI * DST_RCDISC2N__R1 * DST_RCDISC2N__C);
calculate_filter1_coefficients(this, f1, DISC_FILTER_LOWPASS, m_fc0);
calculate_filter1_coefficients(this, f2, DISC_FILTER_LOWPASS, m_fc1);
/* Initialize the object */
set_output(0, 0);
}
| 28.753653 | 117 | 0.599216 | [
"object",
"model"
] |
3ac942b32da51c6713238acd044a940d9f3508bf | 6,803 | h | C | GlpkSharp/include/glpfhv.h | lionelberton/GlpkSharp | 067c2c79b033db76eb33df68cf3265032839aaae | [
"MIT"
] | 22 | 2016-10-05T12:19:01.000Z | 2022-01-23T09:14:41.000Z | GlpkSharp/include/glpfhv.h | lionelberton/GlpkSharp | 067c2c79b033db76eb33df68cf3265032839aaae | [
"MIT"
] | 23 | 2017-05-08T15:02:39.000Z | 2021-11-03T16:43:39.000Z | GlpkSharp/include/glpfhv.h | lionelberton/GlpkSharp | 067c2c79b033db76eb33df68cf3265032839aaae | [
"MIT"
] | 12 | 2017-06-07T23:51:09.000Z | 2022-01-04T13:06:21.000Z | /* glpfhv.h (LP basis factorization, FHV eta file version) */
/***********************************************************************
* This code is part of GLPK (GNU Linear Programming Kit).
*
* Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008,
* 2009, 2010 Andrew Makhorin, Department for Applied Informatics,
* Moscow Aviation Institute, Moscow, Russia. All rights reserved.
* E-mail: <mao@gnu.org>.
*
* GLPK 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 3 of the License, or
* (at your option) any later version.
*
* GLPK 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 GLPK. If not, see <http://www.gnu.org/licenses/>.
***********************************************************************/
#ifndef GLPFHV_H
#define GLPFHV_H
#include "glpluf.h"
/***********************************************************************
* The structure FHV defines the factorization of the basis mxm-matrix
* B, where m is the number of rows in corresponding problem instance.
*
* This factorization is the following sextet:
*
* [B] = (F, H, V, P0, P, Q), (1)
*
* where F, H, and V are such matrices that
*
* B = F * H * V, (2)
*
* and P0, P, and Q are such permutation matrices that the matrix
*
* L = P0 * F * inv(P0) (3)
*
* is lower triangular with unity diagonal, and the matrix
*
* U = P * V * Q (4)
*
* is upper triangular. All the matrices have the same order m, which
* is the order of the basis matrix B.
*
* The matrices F, V, P, and Q are stored in the structure LUF (see the
* module GLPLUF), which is a member of the structure FHV.
*
* The matrix H is stored in the form of eta file using row-like format
* as follows:
*
* H = H[1] * H[2] * ... * H[nfs], (5)
*
* where H[k], k = 1, 2, ..., nfs, is a row-like factor, which differs
* from the unity matrix only by one row, nfs is current number of row-
* like factors. After the factorization has been built for some given
* basis matrix B the matrix H has no factors and thus it is the unity
* matrix. Then each time when the factorization is recomputed for an
* adjacent basis matrix, the next factor H[k], k = 1, 2, ... is built
* and added to the end of the eta file H.
*
* Being sparse vectors non-trivial rows of the factors H[k] are stored
* in the right part of the sparse vector area (SVA) in the same manner
* as rows and columns of the matrix F.
*
* For more details see the program documentation. */
typedef struct FHV FHV;
struct FHV
{ /* LP basis factorization */
int m_max;
/* maximal value of m (increased automatically, if necessary) */
int m;
/* the order of matrices B, F, H, V, P0, P, Q */
int valid;
/* the factorization is valid only if this flag is set */
LUF *luf;
/* LU-factorization (contains the matrices F, V, P, Q) */
/*--------------------------------------------------------------*/
/* matrix H in the form of eta file */
int hh_max;
/* maximal number of row-like factors (which limits the number of
updates of the factorization) */
int hh_nfs;
/* current number of row-like factors (0 <= hh_nfs <= hh_max) */
int *hh_ind; /* int hh_ind[1+hh_max]; */
/* hh_ind[k], k = 1, ..., nfs, is the number of a non-trivial row
of factor H[k] */
int *hh_ptr; /* int hh_ptr[1+hh_max]; */
/* hh_ptr[k], k = 1, ..., nfs, is a pointer to the first element
of the non-trivial row of factor H[k] in the SVA */
int *hh_len; /* int hh_len[1+hh_max]; */
/* hh_len[k], k = 1, ..., nfs, is the number of non-zero elements
in the non-trivial row of factor H[k] */
/*--------------------------------------------------------------*/
/* matrix P0 */
int *p0_row; /* int p0_row[1+m_max]; */
/* p0_row[i] = j means that p0[i,j] = 1 */
int *p0_col; /* int p0_col[1+m_max]; */
/* p0_col[j] = i means that p0[i,j] = 1 */
/* if i-th row or column of the matrix F corresponds to i'-th row
or column of the matrix L = P0*F*inv(P0), then p0_row[i'] = i
and p0_col[i] = i' */
/*--------------------------------------------------------------*/
/* working arrays */
int *cc_ind; /* int cc_ind[1+m_max]; */
/* integer working array */
double *cc_val; /* double cc_val[1+m_max]; */
/* floating-point working array */
/*--------------------------------------------------------------*/
/* control parameters */
double upd_tol;
/* update tolerance; if after updating the factorization absolute
value of some diagonal element u[k,k] of matrix U = P*V*Q is
less than upd_tol * max(|u[k,*]|, |u[*,k]|), the factorization
is considered as inaccurate */
/*--------------------------------------------------------------*/
/* some statistics */
int nnz_h;
/* current number of non-zeros in all factors of matrix H */
};
/* return codes: */
#define FHV_ESING 1 /* singular matrix */
#define FHV_ECOND 2 /* ill-conditioned matrix */
#define FHV_ECHECK 3 /* insufficient accuracy */
#define FHV_ELIMIT 4 /* update limit reached */
#define FHV_EROOM 5 /* SVA overflow */
#define fhv_create_it _glp_fhv_create_it
FHV *fhv_create_it(void);
/* create LP basis factorization */
#define fhv_factorize _glp_fhv_factorize
int fhv_factorize(FHV *fhv, int m, int (*col)(void *info, int j,
int ind[], double val[]), void *info);
/* compute LP basis factorization */
#define fhv_h_solve _glp_fhv_h_solve
void fhv_h_solve(FHV *fhv, int tr, double x[]);
/* solve system H*x = b or H'*x = b */
#define fhv_ftran _glp_fhv_ftran
void fhv_ftran(FHV *fhv, double x[]);
/* perform forward transformation (solve system B*x = b) */
#define fhv_btran _glp_fhv_btran
void fhv_btran(FHV *fhv, double x[]);
/* perform backward transformation (solve system B'*x = b) */
#define fhv_update_it _glp_fhv_update_it
int fhv_update_it(FHV *fhv, int j, int len, const int ind[],
const double val[]);
/* update LP basis factorization */
#define fhv_delete_it _glp_fhv_delete_it
void fhv_delete_it(FHV *fhv);
/* delete LP basis factorization */
#endif
/* eof */
| 39.783626 | 72 | 0.575922 | [
"vector"
] |
6b2921e687b638df7c33f535abd59f96be0db385 | 44,486 | h | C | model_tools/src/tensorflow/tensorflow_adaptee.h | ishine/bolt | ea734231f7085898ba5ca10da6d02da38058a705 | [
"MIT"
] | 722 | 2019-12-02T13:07:19.000Z | 2022-03-24T08:55:38.000Z | model_tools/src/tensorflow/tensorflow_adaptee.h | ishine/bolt | ea734231f7085898ba5ca10da6d02da38058a705 | [
"MIT"
] | 89 | 2019-12-04T13:46:25.000Z | 2022-03-28T02:52:27.000Z | model_tools/src/tensorflow/tensorflow_adaptee.h | ishine/bolt | ea734231f7085898ba5ca10da6d02da38058a705 | [
"MIT"
] | 137 | 2019-12-03T08:41:58.000Z | 2022-03-18T19:54:59.000Z | // Copyright (C) 2019. Huawei Technologies Co., Ltd. All rights reserved.
// 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 _H_TENSORFLOWADAPTEE
#define _H_TENSORFLOWADAPTEE
#include <json/json.h>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <math.h>
#include "model_adaptee.h"
class TensorflowAdaptee : public ModelAdaptee {
public:
TensorflowAdaptee()
{
this->modelInputLayerNum = 0;
this->entityOpCount = 0;
this->weightOpNum = 0;
this->curInDegree = 0;
this->curNodeIndex = 0;
}
~TensorflowAdaptee()
{}
protected:
std::string cleanRedundantC(std::string str)
{
std::string result = "";
for (int i = 1; i < (int)(str.length() - 1); i++) {
if (str.at(i) == '\\') {
continue;
} else {
result += str.at(i);
}
}
return result;
}
OperatorType convert_tensorflow_type(std::string tfType)
{
if (tfType.compare("Mul") == 0 || tfType.compare("Sub") == 0 ||
tfType.compare("Add") == 0 || tfType.compare("RealDiv") == 0) {
if (curInDegree == 1) {
return OT_Power;
} else {
return OT_Eltwise;
}
} else if (tfType.compare("FusedBatchNorm") == 0) {
return OT_BatchNorm;
} else if (tfType.compare("Relu6") == 0) {
return OT_Relu6;
} else if (tfType.compare("DepthwiseConv2dNative") == 0) {
return OT_Conv;
} else if (tfType.compare("MaxPool") == 0) {
return OT_Pooling;
} else if (tfType.compare("ConcatV2") == 0) {
return OT_Concat;
} else if (tfType.compare("Relu") == 0) {
return OT_Relu;
} else if (tfType.compare("ResizeBilinear") == 0) {
return OT_Resize;
} else if (tfType.compare("ArgMax") == 0) {
return OT_ArgMax;
} else if (tfType.compare("ExpandDims") == 0) {
return OT_Unsqueeze;
} else if (tfType.compare("Pad") == 0 || tfType.compare("PadV2") == 0) {
return OT_Pad;
} else if (tfType.compare("Transpose") == 0) {
return OT_Transpose;
} else if (tfType.compare("BiasAdd") == 0) {
return OT_FC;
} else if (tfType.compare("Conv2DBackpropInput") == 0 || tfType.compare("Conv2D") == 0) {
return OT_Conv;
} else if (tfType.compare("Cast") == 0) {
return OT_Cast;
} else if (tfType.compare("Reshape") == 0) {
return OT_Reshape;
} else if (tfType.compare("Rsqrt") == 0) {
return OT_Power;
} else if (tfType.compare("Squeeze") == 0) {
return OT_Squeeze;
} else if (tfType.compare("Sigmoid") == 0) {
return OT_Sigmoid;
} else if (tfType.compare("MatMul") == 0) {
if (this->curInDegree == 1) {
return OT_FC;
} else {
return OT_MatMul;
}
} else if (tfType.compare("Softmax") == 0) {
return OT_Softmax;
} else if (tfType.compare("AvgPool") == 0) {
return OT_Pooling;
} else if (tfType.compare("Mean") == 0) {
return OT_Reduction;
} else if (tfType.compare("Shape") == 0) {
return OT_Shape;
} else {
UNI_ERROR_LOG("operator name:%s type:%s not supported.\n", this->layerName.c_str(),
tfType.c_str());
return OT_None;
}
}
EE parse_file(std::string dir, std::string mfn) override
{
EE ret;
std::string tfSuffix = ".json";
this->modelName = mfn;
std::string modelAbsPath = dir + "/" + mfn + tfSuffix;
std::string::size_type idx;
std::ifstream inFile;
inFile.open(modelAbsPath);
if (!inFile.is_open()) {
UNI_ERROR_LOG("can not open tensorflow model file %s.\n", modelAbsPath.c_str());
}
std::stringstream strStream;
strStream << inFile.rdbuf();
std::string strValueFromPy = strStream.str();
std::string strValue = cleanRedundantC(strValueFromPy);
std::string tailStr = strValue.substr(strValue.length() - 18, 18);
newStrValue = "";
idx = tailStr.find("library");
if (idx == std::string::npos) {
newStrValue = strValue;
} else {
newStrValue = strValue.substr(0, strValue.length() - 16) + "}";
}
Json::Reader reader;
Json::Value value;
if (reader.parse(newStrValue, value)) {
this->entityOpCount = value["node"].size();
for (int i = 0; i < (int)(value["node"].size()); i++) {
if ((value["node"][i]["op"].asString()).compare("Const") == 0) {
constId[value["node"][i]["name"].asString()] = i;
this->entityOpCount = this->entityOpCount - 1;
} else if ((value["node"][i]["op"].asString()).compare("Identity") == 0) {
idenConst[value["node"][i]["name"].asString()] =
value["node"][i]["input"][0].asString();
this->entityOpCount = this->entityOpCount - 1;
} else if ((value["node"][i]["op"].asString()).compare("Placeholder") == 0) {
this->modelInputLayerNum = this->modelInputLayerNum + 1;
this->entityOpCount = this->entityOpCount - 1;
}
}
ret = SUCCESS;
} else {
ret = FILE_ERROR;
}
return ret;
}
template <typename T>
void shiftRight(T *array, int length, int left, int right)
{
// only transpose 4-dim parameter
if (length >= 4) {
T data = array[right];
for (int i = right; i > left; i--) {
array[i] = array[i - 1];
}
array[left] = data;
}
}
EE adapt_operators(ModelSpec *ms) override
{
EE ret = SUCCESS;
ms->dt = DT_F32;
str_copy(ms->model_name, modelName.c_str(), modelName.length());
ms->num_inputs = this->modelInputLayerNum;
ms->input_names = (I8 **)mt_new_storage(ms->num_inputs * sizeof(I8 *));
ms->input_dims = (TensorDesc *)mt_new_storage(sizeof(TensorDesc) * ms->num_inputs);
int traverseInputLayerIndex = 0;
ms->num_operator_specs = this->entityOpCount;
OperatorSpec *opsPtr =
(OperatorSpec *)mt_new_storage(sizeof(OperatorSpec) * ms->num_operator_specs);
ms->ops = opsPtr;
int traverseEntityOpIndex = 0;
std::map<std::string, int> unmapOps;
Json::Reader reader;
Json::Value value;
if (reader.parse(newStrValue, value)) {
this->ttValue = value;
for (int i = 0; i < (int)(value["node"].size()); i++) {
layerName = value["node"][i]["name"].asString();
UNI_DEBUG_LOG("process operator name:%s parameter.\n", layerName.c_str());
this->opType = value["node"][i]["op"].asString();
if (opType.compare("Placeholder") == 0) {
ms->input_names[traverseInputLayerIndex] =
(I8 *)mt_new_storage(NAME_LEN * sizeof(I8));
str_copy(ms->input_names[traverseInputLayerIndex], layerName.c_str(),
layerName.length());
int placeholder_shape_size =
value["node"][i]["attr"]["shape"]["shape"]["dim"].size();
if (placeholder_shape_size == 0) {
UNI_ERROR_LOG("model input %s dimensions are not specific.\n",
ms->input_names[traverseInputLayerIndex]);
}
std::vector<int> inputShape(placeholder_shape_size);
for (int j = 0; j < placeholder_shape_size; j++) {
inputShape[j] = std::stoi(
value["node"][i]["attr"]["shape"]["shape"]["dim"][j]["size"].asString());
}
shiftRight<int>(inputShape.data(), inputShape.size(), 1, inputShape.size() - 1);
ms->input_dims[traverseInputLayerIndex].nDims = inputShape.size();
ms->input_dims[traverseInputLayerIndex].dt = DT_F32;
ms->input_dims[traverseInputLayerIndex].df =
getTensorDefaultDataFormat(ms->input_dims[traverseInputLayerIndex].nDims);
for (U32 j = 0; j < ms->input_dims[traverseInputLayerIndex].nDims; j++) {
ms->input_dims[traverseInputLayerIndex]
.dims[ms->input_dims[traverseInputLayerIndex].nDims - 1 - j] =
inputShape[j];
}
traverseInputLayerIndex++;
} else if (opType.compare("Const") == 0) {
int tensorDimSize =
value["node"][i]["attr"]["value"]["tensor"]["tensorShape"]["dim"].size();
std::vector<int> tensorDims;
int tensorDimsNum = 1;
for (int j = 0; j < tensorDimSize; j++) {
tensorDims.push_back(std::stoi(
value["node"][i]["attr"]["value"]["tensor"]["tensorShape"]["dim"][j]["s"
"i"
"z"
"e"]
.asString()));
tensorDimsNum *= tensorDims[j];
}
} else if (opType.compare("Identity") != 0) {
std::vector<std::string> inList;
std::vector<std::string> constList;
this->nodeV = value["node"][i];
ParameterSpec tmpPs;
str_copy(
opsPtr[traverseEntityOpIndex].name, layerName.c_str(), layerName.length());
if (opType.compare("Conv2DBackpropInput") == 0) {
UNI_WARNING_LOG("Filter the input0_size\n");
} else if (opType.compare("FusedBatchNorm") == 0 &&
value["node"][i]["input"].size() != 5) { // To collect more special cases
constList.push_back(value["node"][i]["input"][0].asString());
} else {
inList.push_back(value["node"][i]["input"][0].asString());
}
for (int k = 1; k < (int)(value["node"][i]["input"].size()); k++) {
std::string curIn = value["node"][i]["input"][k].asString();
if (idenConst.find(curIn) == idenConst.end() &&
constId.find(curIn) == constId.end()) {
inList.push_back(curIn);
} else {
if (constId.find(idenConst[curIn]) == constId.end() &&
constId.find(curIn) == constId.end()) {
inList.push_back(curIn);
} else {
constList.push_back(curIn);
}
}
}
if (constList.size() > 0) {
weightConstInput[layerName] = constList;
if (opType != "Mul" && opType != "Sub" && opType != "Add" &&
opType != "RealDiv" && opType != "ConcatV2" && opType != "PadV2" &&
opType != "ArgMax" && opType != "Transpose" && opType != "Pad" &&
opType != "ExpandDims" && opType != "ResizeBilinear" &&
opType != "Reshape" && opType != "Mean") { // TODO: expand more cases
weightIds.push_back(i);
this->weightOpNum = this->weightOpNum + 1;
}
}
opsPtr[traverseEntityOpIndex].num_inputs = inList.size();
opsPtr[traverseEntityOpIndex].input_tensors_name = (I8 **)mt_new_storage(
opsPtr[traverseEntityOpIndex].num_inputs * sizeof(I8 *));
for (int k = 0; k < (int)(opsPtr[traverseEntityOpIndex].num_inputs); k++) {
opsPtr[traverseEntityOpIndex].input_tensors_name[k] =
(I8 *)mt_new_storage(NAME_LEN * sizeof(I8));
str_copy(opsPtr[traverseEntityOpIndex].input_tensors_name[k],
inList[k].c_str(), inList[k].length());
}
opsPtr[traverseEntityOpIndex].num_outputs = 1;
opsPtr[traverseEntityOpIndex].output_tensors_name = (I8 **)mt_new_storage(
opsPtr[traverseEntityOpIndex].num_outputs * sizeof(I8 *));
for (int k = 0; k < (int)(opsPtr[traverseEntityOpIndex].num_outputs); k++) {
opsPtr[traverseEntityOpIndex].output_tensors_name[k] =
(I8 *)mt_new_storage(NAME_LEN * sizeof(I8));
str_copy(opsPtr[traverseEntityOpIndex].output_tensors_name[k],
layerName.c_str(), layerName.length());
}
opsPtr[traverseEntityOpIndex].tensor_positions = nullptr;
opsPtr[traverseEntityOpIndex].num_quant_feature = 0;
opsPtr[traverseEntityOpIndex].feature_scale = nullptr;
this->curInDegree = inList.size();
OperatorType curOpType = convert_tensorflow_type(opType);
opsPtr[traverseEntityOpIndex].type = curOpType;
CHECK_STATUS(adapt_operator(curOpType, &tmpPs));
opsPtr[traverseEntityOpIndex].ps = tmpPs;
traverseEntityOpIndex++;
}
}
} else {
UNI_ERROR_LOG("can not read tensorflow model.\n");
}
return ret;
}
EE adapt_weights(ModelSpec *ms) override
{
ms->num_weight_specs = weightOpNum;
WeightSpec *wsPtr = (WeightSpec *)mt_new_storage(sizeof(WeightSpec) * ms->num_weight_specs);
for (int j = 0; j < ms->num_weight_specs; j++) {
wsPtr[j].num_quant_scale = 0;
wsPtr[j].weight_scale = nullptr;
}
ms->ws = wsPtr;
Json::Reader reader;
Json::Value value;
if (reader.parse(newStrValue, value)) {
for (int j = 0; j < ms->num_weight_specs; j++) {
int curWeightIndex = weightIds[j];
std::string weightOpType = value["node"][curWeightIndex]["op"].asString();
std::string weightOpName = value["node"][curWeightIndex]["name"].asString();
str_copy(wsPtr[j].op_name, weightOpName.c_str(), weightOpName.length());
std::vector<std::string> constList = weightConstInput[weightOpName];
UNI_DEBUG_LOG("process operator name:%s weight.\n", weightOpName.c_str());
if (weightOpType.compare("Conv2D") == 0 ||
weightOpType.compare("Conv2DBackpropInput") == 0 ||
weightOpType.compare("MatMul") == 0 ||
weightOpType.compare("DepthwiseConv2dNative") == 0) { // To collect more op
if (constList.size() == 1) {
std::string curIdenStr = constList[0];
std::string curConstStr = idenConst[curIdenStr];
int curConstIndex = constId[curConstStr];
if (constId.find(curIdenStr) != constId.end()) {
curConstIndex = constId[curIdenStr];
}
int tensorContentSize =
value["node"][curConstIndex]["attr"]["value"]["tensor"]["tensorContent"]
.size();
wsPtr[j].mdt = DT_F32;
wsPtr[j].bytes_of_weight = tensorContentSize * sizeof(float);
float *fp32Ptr = (float *)mt_new_storage(wsPtr[j].bytes_of_weight);
for (int k = 0; k < tensorContentSize; k++) {
fp32Ptr[k] = std::stof(
value["node"][curConstIndex]["attr"]["value"]["tensor"]["tensorCont"
"ent"][k]
.asString());
}
wsPtr[j].weight = (U8 *)fp32Ptr;
wsPtr[j].bytes_of_vec = 0;
wsPtr[j].vec = nullptr;
} else {
CHECK_STATUS(NOT_IMPLEMENTED);
}
} else if (weightOpType.compare("BiasAdd") == 0) {
if (constList.size() == 1) {
std::string curIdenStr = constList[0];
std::string curConstStr = idenConst[curIdenStr];
int curConstIndex = constId[curConstStr];
int tensorContentSize =
value["node"][curConstIndex]["attr"]["value"]["tensor"]["tensorContent"]
.size();
wsPtr[j].mdt = DT_F32;
wsPtr[j].bytes_of_weight = 0;
wsPtr[j].weight = nullptr;
wsPtr[j].bytes_of_vec = tensorContentSize * sizeof(float);
float *fp32Ptr = (float *)mt_new_storage(wsPtr[j].bytes_of_vec);
for (int k = 0; k < tensorContentSize; k++) {
fp32Ptr[k] = std::stof(
value["node"][curConstIndex]["attr"]["value"]["tensor"]["tensorCont"
"ent"][k]
.asString());
}
wsPtr[j].vec = (U8 *)fp32Ptr;
} else {
CHECK_STATUS(NOT_IMPLEMENTED);
}
} else if (weightOpType.compare("FusedBatchNorm") == 0) {
if (constList.size() == 4) {
std::string curScaleIdenStr = constList[0];
std::string curScaleConstStr = idenConst[curScaleIdenStr];
int curScaleConstIndex = constId[curScaleConstStr];
if (constId.find(curScaleIdenStr) != constId.end()) {
curScaleConstIndex = constId[curScaleIdenStr];
}
std::string curOffsetIdenStr = constList[1];
std::string curOffsetConstStr = idenConst[curOffsetIdenStr];
int curOffsetConstIndex = constId[curOffsetConstStr];
if (constId.find(curOffsetIdenStr) != constId.end()) {
curOffsetConstIndex = constId[curOffsetIdenStr];
}
std::string curMeanIdenStr = constList[2];
std::string curMeanConstStr = idenConst[curMeanIdenStr];
int curMeanConstIndex = constId[curMeanConstStr];
if (constId.find(curMeanIdenStr) != constId.end()) {
curMeanConstIndex = constId[curMeanIdenStr];
}
std::string curVarianceIdenStr = constList[3];
std::string curVarianceConstStr = idenConst[curVarianceIdenStr];
int curVarianceConstIndex = constId[curVarianceConstStr];
if (constId.find(curVarianceIdenStr) != constId.end()) {
curVarianceConstIndex = constId[curVarianceIdenStr];
}
int iterSize =
value["node"][curScaleConstIndex]["attr"]["value"]["tensor"]["tensorCon"
"tent"]
.size();
wsPtr[j].mdt = DT_F32;
wsPtr[j].bytes_of_weight = iterSize * sizeof(float);
float *fp32FirPtr = (float *)mt_new_storage(wsPtr[j].bytes_of_weight);
wsPtr[j].weight = (U8 *)fp32FirPtr;
wsPtr[j].bytes_of_vec = iterSize * sizeof(float);
float *fp32SecPtr = (float *)mt_new_storage(wsPtr[j].bytes_of_vec);
wsPtr[j].vec = (U8 *)fp32SecPtr;
for (int k = 0; k < iterSize; k++) {
float tmpScale = std::stof(
value["node"][curScaleConstIndex]["attr"]["value"]["tensor"]["tenso"
"rCont"
"ent"][0]
.asString());
float tmpOffset = std::stof(
value["node"][curOffsetConstIndex]["attr"]["value"]["tensor"]["tens"
"orCo"
"nten"
"t"][0]
.asString());
float tmpMean = std::stof(
value["node"][curMeanConstIndex]["attr"]["value"]["tensor"]["tensor"
"Conten"
"t"][0]
.asString());
float tmpVariance = std::stof(
value["node"][curVarianceConstIndex]["attr"]["value"]["tensor"]["te"
"ns"
"or"
"Co"
"nt"
"en"
"t"][0]
.asString());
float tmpNewMean =
tmpMean - tmpOffset * sqrt(tmpVariance / powf(tmpScale, 2));
float tmpNewVariance = tmpVariance / (powf(tmpScale, 2));
fp32FirPtr[k] = tmpNewMean;
fp32SecPtr[k] = tmpNewVariance;
}
} else {
CHECK_STATUS(NOT_IMPLEMENTED);
}
}
}
}
return SUCCESS;
}
ParameterSpec adapt_Eltwise() override
{
ParameterSpec curPs;
memset(&curPs, 0, sizeof(curPs));
EltwiseParamSpec eps;
memset(&eps, 0, sizeof(eps));
if (opType == "Add") {
eps.elt_mode = ELTWISE_SUM;
eps.activation_type = ACTIVATION_NULL;
} else if (opType == "Sub") {
eps.elt_mode = ELTWISE_SUB;
eps.activation_type = ACTIVATION_NULL;
}
curPs.eltwise_spec = eps;
return curPs;
}
ParameterSpec adapt_ArgMax() override
{
ParameterSpec curPs;
memset(&curPs, 0, sizeof(curPs));
ArgMaxParamSpec aps;
memset(&aps, 0, sizeof(aps));
aps.axis = 1; // TODO
curPs.argmax_spec = aps;
return curPs;
}
ParameterSpec adapt_Conv() override
{
ParameterSpec curPs;
memset(&curPs, 0, sizeof(curPs));
ConvolutionParamSpec convPs;
memset(&convPs, 0, sizeof(convPs));
convPs.kernel_t = 1;
convPs.stride_t = 1;
convPs.padding_before = 0;
convPs.padding_after = 0;
convPs.dilatedRate_t = 1;
std::string conv_op = nodeV["name"].asString();
int dilationsInfo[4] = {0, 0, 0, 0};
int stridesInfo[4] = {0, 0, 0, 0};
if (opType.compare("DepthwiseConv2dNative") == 0) {
for (int i = 0; i < (int)(nodeV["attr"]["dilations"]["list"]["i"].size()); i++) {
dilationsInfo[i] = 1;
}
} else {
dilationsInfo[0] = 1;
dilationsInfo[1] = 1;
}
for (int i = 0; i < (int)(nodeV["attr"]["strides"]["list"]["i"].size()); i++) {
stridesInfo[i] = std::stoi(
nodeV["attr"]["strides"]["list"]["i"][i].asString()); // TODO extract real data
}
convPs.dilatedRate_h = dilationsInfo[1]; // atten
convPs.dilatedRate_w = dilationsInfo[2];
convPs.stride_h = stridesInfo[1];
convPs.stride_w = stridesInfo[2];
std::vector<std::string> curConvIdens = this->weightConstInput[conv_op];
int curConstId = -1;
if (constId.find(curConvIdens[0]) != constId.end()) {
curConstId = constId[curConvIdens[0]];
} else {
curConstId = constId[idenConst[curConvIdens[0]]];
}
std::string constOpName = this->ttValue["node"][curConstId]["name"].asString();
std::vector<int> convWeightKernels;
for (int k = 0; k <
(int)(this->ttValue["node"][curConstId]["attr"]["value"]["tensor"]["tensorShape"]["di"
"m"]
.size());
k++) {
convWeightKernels.push_back(
std::stoi(this->ttValue["node"][curConstId]["attr"]["value"]["tensor"]
["tensorShape"]["dim"][k]["size"]
.asString()));
}
if (convWeightKernels.size() < 4) {
UNI_ERROR_LOG("can not process operator name:%s kernel.\n", this->layerName.c_str());
}
if (opType.compare("DepthwiseConv2dNative") == 0) {
convPs.num_outputs = convWeightKernels[2];
} else {
convPs.num_outputs = convWeightKernels[3];
}
convPs.kernel_h = convWeightKernels[0];
convPs.kernel_w = convWeightKernels[1];
std::string tfPaddingMode =
nodeV["attr"]["padding"]["s"].asString(); // choose one of VALID/SAME
if (tfPaddingMode.at(0) == 'V') {
tfPaddingMode = "VALID";
convPs.padding_top = 0;
convPs.padding_bottom = 0;
convPs.padding_left = 0;
convPs.padding_right = 0;
} else {
tfPaddingMode = "SAME";
convPs.padding_top = (U32)INT_MAX;
convPs.padding_bottom = (U32)INT_MAX;
convPs.padding_left = (U32)INT_MAX;
convPs.padding_right = (U32)INT_MAX;
}
convPs.group = 1;
convPs.dw_activation_type = ACTIVATION_NULL;
convPs.pw_activation_type = ACTIVATION_NULL;
if (convPs.group != 1 && convPs.group == convPs.num_outputs) {
convPs.convolution_type = Convolution_Depthwise;
} else {
if (convPs.dilatedRate_h > 1 || convPs.dilatedRate_w > 1) {
convPs.convolution_type = Convolution_Dilation;
} else {
convPs.convolution_type = Convolution_Pointwise;
}
}
if (opType.compare("DepthwiseConv2dNative") == 0) {
convPs.convolution_type = Convolution_Depthwise;
}
curPs.conv_spec = convPs;
return curPs;
}
ParameterSpec adapt_BatchNorm() override
{
ParameterSpec curPs;
memset(&curPs, 0, sizeof(curPs));
BatchNormParamSpec bps;
memset(&bps, 0, sizeof(bps));
bps.axis = 0;
bps.eps = nodeV["attr"]["epsilon"]["f"].asFloat();
bps.gama = 0;
bps.momentum = 0;
curPs.bn_spec = bps;
return curPs;
}
ParameterSpec adapt_Fc() override
{
ParameterSpec curPs;
memset(&curPs, 0, sizeof(curPs));
FullyConnectedParamSpec fps;
memset(&fps, 0, sizeof(fps));
// to locate the const weight op
std::string curOpName = nodeV["name"].asString();
std::vector<std::string> curConvIdens = this->weightConstInput[curOpName];
int curConstId = -1;
if (constId.find(curConvIdens[0]) != constId.end()) {
curConstId = constId[curConvIdens[0]];
} else {
curConstId = constId[idenConst[curConvIdens[0]]];
}
int dimLengthIndex =
this->ttValue["node"][curConstId]["attr"]["value"]["tensor"]["tensorShape"].size() - 1;
fps.num_outputs =
std::stoi(this->ttValue["node"][curConstId]["attr"]["value"]["tensor"]["tensorShape"]
["dim"][dimLengthIndex]["size"]
.asString()); // fc_dimSize is static two-dimension
fps.num_slices = 1;
curPs.fc_spec = fps;
return curPs;
}
ParameterSpec adapt_Pooling() override
{
ParameterSpec curPs;
memset(&curPs, 0, sizeof(curPs));
PoolingParamSpec pps;
memset(&pps, 0, sizeof(pps));
std::vector<int> kernelSize; // ihwo
std::vector<int> stridesInfo;
for (int i = 0; i < (int)(nodeV["attr"]["ksize"]["list"]["i"].size()); i++) {
kernelSize.push_back(std::stoi(nodeV["attr"]["ksize"]["list"]["i"][i].asString()));
}
for (int i = 0; i < (int)(nodeV["attr"]["strides"]["list"]["i"].size()); i++) {
stridesInfo.push_back(std::stoi(nodeV["attr"]["strides"]["list"]["i"][i].asString()));
}
pps.kernel_t = 1;
pps.kernel_h = kernelSize[1];
pps.kernel_w = kernelSize[2];
pps.stride_t = 1;
pps.stride_h = 1;
pps.stride_w = 1;
pps.padding_before = 0;
pps.padding_after = 0;
pps.padding_top = 0;
pps.padding_bottom = 0;
pps.padding_left = 0;
pps.padding_right = 0;
pps.rm = CEIL;
if (opType.compare("MaxPool") == 0) {
pps.mode = POOLING_MAX;
} else { // refer to "AvgPool"
pps.mode = POOLING_MEAN;
}
curPs.pooling_spec = pps;
return curPs;
}
ParameterSpec adapt_Reduction() override
{
// Mapping to <Mean>
ParameterSpec curPs;
memset(&curPs, 0, sizeof(curPs));
ReductionParamSpec reductionPs;
memset(&reductionPs, 0, sizeof(reductionPs));
if (opType.compare("Mean") == 0) {
reductionPs.reduction_mode = REDUCTION_MEAN;
} else {
UNI_ERROR_LOG("can not map operator name:%s type:%s to Reduction.\n",
this->layerName.c_str(), opType.c_str());
}
std::string reductionOpName = nodeV["name"].asString();
std::vector<std::string> constInputs = weightConstInput[reductionOpName];
int constReductionOpIndex = -1;
if (constId.find(constInputs[0]) != constId.end()) {
constReductionOpIndex = constId[constInputs[0]];
} else {
constReductionOpIndex = constId[idenConst[constInputs[0]]];
}
reductionPs.axes_num =
this->ttValue["node"][constReductionOpIndex]["attr"]["value"]["tensor"]["tensorContent"]
.size();
for (int i = 0; i < reductionPs.axes_num; i++) {
reductionPs.axes[i] = std::stoi(
this->ttValue["node"][constReductionOpIndex]["attr"]["value"]["tensor"]["tensorCont"
"ent"][i]
.asString());
}
curPs.reduction_spec = reductionPs;
return curPs;
}
ParameterSpec adapt_Pad() override
{
ParameterSpec curPs;
memset(&curPs, 0, sizeof(curPs));
PadParamSpec padPs;
memset(&padPs, 0, sizeof(padPs));
std::string curOpName = nodeV["name"].asString();
std::vector<std::string> curConvIdens = this->weightConstInput[curOpName];
int curConstId = -1;
if (constId.find(curConvIdens[0]) != constId.end()) {
curConstId = constId[curConvIdens[0]];
} else {
curConstId = constId[idenConst[curConvIdens[0]]];
}
std::vector<int> padInfos;
for (int i = 0; i < (int)(this->ttValue["node"][curConstId]["attr"]["value"]["tensor"]["ten"
"sor"
"Con"
"ten"
"t"]
.size());
i++) {
padInfos.push_back(
std::stoi(this->ttValue["node"][curConstId]["attr"]["value"]["tensor"]["tensorConte"
"nt"][i]
.asString()));
}
padPs.before = 0;
padPs.after = 0;
padPs.top = padInfos[2];
padPs.bottom = padInfos[3];
padPs.left = padInfos[4];
padPs.right = padInfos[5];
padPs.constant_value = 0; // TODO: for PadV2
padPs.pad_mode = Pad_Constant;
curPs.pad_spec = padPs;
return curPs;
}
ParameterSpec adapt_Concat() override
{
ParameterSpec curPs;
memset(&curPs, 0, sizeof(curPs));
ConcatParamSpec concatPs;
memset(&concatPs, 0, sizeof(concatPs));
concatPs.axis = std::stoi(nodeV["attr"]["N"]["i"].asString());
curPs.concat_spec = concatPs;
return curPs;
}
ParameterSpec adapt_Resize() override
{
ParameterSpec curPs;
memset(&curPs, 0, sizeof(curPs));
ResizeParamSpec resizePs;
memset(&resizePs, 0, sizeof(resizePs));
std::string curOpName = nodeV["name"].asString();
std::vector<std::string> curConvIdens = this->weightConstInput[curOpName];
int curConstId = -1;
if (constId.find(curConvIdens[0]) != constId.end()) {
curConstId = constId[curConvIdens[0]];
} else {
curConstId = constId[idenConst[curConvIdens[0]]];
}
resizePs.num_sizes = 2;
resizePs.num_scales = 0;
for (int k = 0; k < (int)(this->ttValue["node"][curConstId]["attr"]["value"]["tensor"]["ten"
"sor"
"Con"
"ten"
"t"]
.size());
k++) {
resizePs.sizes[k] =
std::stoi(this->ttValue["node"][curConstId]["attr"]["value"]["tensor"]["tensorConte"
"nt"][k]
.asString());
}
curPs.resize_spec = resizePs;
return curPs;
}
ParameterSpec adapt_Power() override
{
ParameterSpec curPs;
memset(&curPs, 0, sizeof(curPs));
PowerParamSpec powerPs;
memset(&curPs, 0, sizeof(powerPs));
float curScale = 1.0;
float curShift = 0.0;
if (opType.compare("Rsqrt") == 0) {
powerPs.power = 0.5;
curPs.power_spec = powerPs;
return curPs;
}
std::string curOpName = nodeV["name"].asString();
std::vector<std::string> curConvIdens = this->weightConstInput[curOpName];
int curConstId = -1;
if (constId.find(curConvIdens[0]) != constId.end()) {
curConstId = constId[curConvIdens[0]];
} else {
curConstId = constId[idenConst[curConvIdens[0]]];
}
if (opType.compare("Mul") == 0) {
curScale = std::stof(this->ttValue["node"][curConstId]["attr"]["value"]["tensor"]["tens"
"orCo"
"nten"
"t"][0]
.asString());
} else if (opType.compare("Sub") == 0) {
curShift = -1 *
std::stof(this->ttValue["node"][curConstId]["attr"]["value"]["tensor"]["tensorConte"
"nt"][0]
.asString());
} else if (opType.compare("RealDiv") == 0) {
curScale = 1.0 /
std::stof(this->ttValue["node"][curConstId]["attr"]["value"]["tensor"]["tensorConte"
"nt"][0]
.asString());
}
powerPs.scale = curScale;
powerPs.shift = curShift;
powerPs.power = 1;
curPs.power_spec = powerPs;
return curPs;
}
ParameterSpec adapt_Transpose() override
{
ParameterSpec curPs;
memset(&curPs, 0, sizeof(curPs));
TransposeParamSpec transPs;
memset(&transPs, 0, sizeof(transPs));
// extract the perm info from the const input
std::string curOpName = nodeV["name"].asString();
std::vector<std::string> curConvIdens = this->weightConstInput[curOpName];
int curConstId = -1;
if (constId.find(curConvIdens[0]) != constId.end()) {
curConstId = constId[curConvIdens[0]];
} else {
curConstId = constId[idenConst[curConvIdens[0]]];
}
transPs.trans_size =
this->ttValue["node"][curConstId]["attr"]["value"]["tensor"]["tensorContent"].size();
for (int i = 0; i < (int)(transPs.trans_size); i++) {
transPs.trans_dims[i] =
std::stoi(this->ttValue["node"][curConstId]["attr"]["value"]["tensor"]["tensorConte"
"nt"][i]
.asString());
;
}
curPs.transpose_spec = transPs;
return curPs;
}
ParameterSpec adapt_Reshape() override
{
ParameterSpec curPs;
memset(&curPs, 0, sizeof(curPs));
ReshapeParamSpec reshapePs;
memset(&reshapePs, 0, sizeof(reshapePs));
std::string curOpName = nodeV["name"].asString();
std::vector<std::string> curConvIdens = this->weightConstInput[curOpName];
if (curConvIdens.size() == 0) {
return curPs;
}
int curConstId = -1;
if (constId.find(curConvIdens[0]) != constId.end()) {
curConstId = constId[curConvIdens[0]];
} else {
curConstId = constId[idenConst[curConvIdens[0]]];
}
reshapePs.shape_size =
this->ttValue["node"][curConstId]["attr"]["value"]["tensor"]["tensorContent"].size();
for (int k = 0; k < reshapePs.shape_size; k++) {
reshapePs.shape_dims[k] =
std::stoi(this->ttValue["node"][curConstId]["attr"]["value"]["tensor"]["tensorConte"
"nt"][k]
.asString());
}
reshapePs.axis = 8;
reshapePs.num_axes = -1;
curPs.reshape_spec = reshapePs;
return curPs;
}
ParameterSpec adapt_Squeeze() override
{
ParameterSpec curPs;
memset(&curPs, 0, sizeof(curPs));
SqueezeParamSpec squeezePs;
memset(&squeezePs, 0, sizeof(squeezePs));
std::vector<int> squeezeDimsInfo;
squeezePs.axes_num = nodeV["attr"]["squeeze_dims"]["list"]["i"].size();
for (int i = 0; i < (int)(nodeV["attr"]["squeeze_dims"]["list"]["i"].size()); i++) {
squeezePs.axes[i] = std::stoi(nodeV["attr"]["squeeze_dims"]["list"]["i"][i].asString());
}
curPs.squeeze_spec = squeezePs;
return curPs;
}
ParameterSpec adapt_Unsqueeze() override
{
ParameterSpec curPs;
memset(&curPs, 0, sizeof(curPs));
UnsqueezeParamSpec unsqueezePs;
memset(&unsqueezePs, 0, sizeof(unsqueezePs));
std::string unsqueeze_op = nodeV["name"].asString();
int expandDimIndex = constId[idenConst[weightConstInput[unsqueeze_op][0]]];
unsqueezePs.axes_num =
this->ttValue["node"][expandDimIndex]["attr"]["value"]["tensor"]["tensorContent"].size();
for (int k = 0; k < unsqueezePs.axes_num; k++) {
unsqueezePs.axes[k] = std::stoi(
this->ttValue["node"][expandDimIndex]["attr"]["value"]["tensor"]["tensorContent"][k]
.asString());
}
curPs.unsqueeze_spec = unsqueezePs;
return curPs;
}
ParameterSpec adapt_Cast() override
{
ParameterSpec curPs;
memset(&curPs, 0, sizeof(curPs));
CastParamSpec castPs;
memset(&castPs, 0, sizeof(castPs));
castPs.targetDt = DT_F32;
curPs.cast_spec = castPs;
return curPs;
}
private:
int modelInputLayerNum;
int entityOpCount;
std::string modelName;
std::string newStrValue;
Json::Value nodeV;
int curNodeIndex;
std::string opType;
std::string layerName;
Json::Value ttValue;
std::map<std::string, int> constId;
std::map<std::string, std::string> idenConst;
std::map<std::string, std::vector<std::string>> weightConstInput;
std::vector<int> weightIds;
int weightOpNum;
int curInDegree;
};
#endif
| 45.071935 | 149 | 0.471969 | [
"shape",
"vector",
"model"
] |
6b2ab7b2107ba003c48c920d14b3005742236844 | 895 | h | C | cppcs/StudentTextEditor.h | aidenszeto/cppcs | 1c8c960cd77cd586085c6fed6b6ec796be2f576e | [
"MIT"
] | 5 | 2021-03-15T22:17:46.000Z | 2021-07-16T00:19:55.000Z | cppcs/StudentTextEditor.h | aidenszeto/cppcs | 1c8c960cd77cd586085c6fed6b6ec796be2f576e | [
"MIT"
] | 2 | 2021-03-17T18:46:26.000Z | 2021-03-23T18:13:48.000Z | cppcs/StudentTextEditor.h | aidenszeto/cppcs | 1c8c960cd77cd586085c6fed6b6ec796be2f576e | [
"MIT"
] | null | null | null | #ifndef STUDENTTEXTEDITOR_H_
#define STUDENTTEXTEDITOR_H_
#include "TextEditor.h"
#include <list>
#include <unordered_set>
class Undo;
class StudentTextEditor : public TextEditor {
public:
StudentTextEditor(Undo* undo);
~StudentTextEditor();
bool load(std::string file);
bool save(std::string file);
void reset();
void move(Dir dir);
void del();
void backspace();
void insert(char ch);
void enter();
void getPos(int& row, int& col) const;
int getLines(int startRow, int numRows, std::vector<std::string>& lines) const;
void undo();
private:
void writeError(std::string error);
void writeOutput(std::string out);
int m_row;
int m_col;
std::list<std::string> m_editor;
std::list<std::string> m_compile;
std::list<std::string>::iterator m_currRow;
std::list<std::string>::iterator m_upDown;
std::unordered_set<std::string> m_includes;
};
#endif // STUDENTTEXTEDITOR_H_
| 21.829268 | 80 | 0.729609 | [
"vector"
] |
6b2fcce86b774ce7d6123c7137eee1e1bcb10068 | 3,552 | h | C | coupling/datastructures/Molecule.h | HSU-HPC/MaMiCo | d6f8597bd41ac3a5d3929c5eb4f7ecbc1b80e2ee | [
"BSD-4-Clause"
] | 6 | 2021-02-06T17:21:10.000Z | 2022-01-27T21:36:55.000Z | coupling/datastructures/Molecule.h | HSU-HPC/MaMiCo | d6f8597bd41ac3a5d3929c5eb4f7ecbc1b80e2ee | [
"BSD-4-Clause"
] | 1 | 2021-06-24T15:17:46.000Z | 2021-06-25T11:54:52.000Z | coupling/datastructures/Molecule.h | HSU-HPC/MaMiCo | d6f8597bd41ac3a5d3929c5eb4f7ecbc1b80e2ee | [
"BSD-4-Clause"
] | 6 | 2021-12-16T11:39:24.000Z | 2022-03-28T07:00:30.000Z | // Copyright (C) 2015 Technische Universitaet Muenchen
// This file is part of the Mamico project. For conditions of distribution
// and use, please see the copyright notice in Mamico's main folder, or at
// www5.in.tum.de/mamico
#ifndef _MOLECULARDYNAMICS_COUPLING_DATASTRUCTURES_MOLECULE_H_
#define _MOLECULARDYNAMICS_COUPLING_DATASTRUCTURES_MOLECULE_H_
#include "tarch/la/Vector.h"
#include "coupling/interface/Molecule.h"
namespace coupling {
namespace datastructures {
template<unsigned int dim>
class Molecule;
}
}
/**
* @brief molecule representation for coupling component. Dericed from the class coupling::interface::Molecule
* @tparam dim Number of dimensions; it can be 1, 2 or 3
* @author Philipp Neumann
*/
template<unsigned int dim>
class coupling::datastructures::Molecule: public coupling::interface::Molecule<dim> {
public:
/** Constructor: initialises the molecule;
* @param position
* @param velocity
* @param force
* @param potentialEnergy
*/
Molecule(
const tarch::la::Vector<dim,double>& position,
const tarch::la::Vector<dim,double>& velocity,
const tarch::la::Vector<dim,double>& force,
const double & potentialEnergy
): coupling::interface::Molecule<dim>(),
_position(position),_velocity(velocity),_force(force),_potentialEnergy(potentialEnergy){}
Molecule(): coupling::interface::Molecule<dim>(),
_position(tarch::la::Vector<dim,double>(0.0)),_velocity(tarch::la::Vector<dim,double>(0.0)),
_force(tarch::la::Vector<dim,double>(0.0)),_potentialEnergy(0.0){}
/** Destructor */
virtual ~Molecule(){}
/** returns the velocity of the molecule
* @return _velocity Velocity*/
tarch::la::Vector<dim,double> getVelocity() const{ return _velocity;}
/** sets the velocity of the molecule
* @param velocity Velocity*/
void setVelocity(const tarch::la::Vector<dim,double>& velocity){_velocity = velocity;}
/** returns the velocity of the molecule
* @return _position Position*/
tarch::la::Vector<dim,double> getPosition() const {return _position;}
/** sets the velocity of the molecule
* @param position Position*/
void setPosition(const tarch::la::Vector<dim,double>& position){_position=position;}
/** sets the force acting on this molecule. This function is called in the USHER
* scheme so far only if the force of a newly created molecule should be set
* @param force Force
* @todo Philipp When the force should be set? when not? you need to implement this function.
*/
void setForce(const tarch::la::Vector<dim,double>& force){_force = force;}
/** returns the force of the molecule
* @return _force Force*/
tarch::la::Vector<dim,double> getForce() const{ return _force;}
/** returns potential energy of the molecule
* @return _potentialEnergy Potential energy of the molecule */
double getPotentialEnergy() const {return _potentialEnergy;}
/** sets potential energy of the molecule
* @param _potentialEnergy Potential energy of the molecule */
void setPotentialEnergy(const double& potentialEnergy){_potentialEnergy = potentialEnergy;}
private:
/** Position of the molecule */
tarch::la::Vector<dim,double> _position;
/** Velocity vector of the molecule */
tarch::la::Vector<dim,double> _velocity;
/** Force vector of the molecule */
tarch::la::Vector<dim,double> _force;
/** Potential energy of the molecule */
double _potentialEnergy;
};
#endif // _MOLECULARDYNAMICS_COUPLING_DATASTRUCTURES_MOLECULE_H_
| 38.608696 | 110 | 0.717905 | [
"vector"
] |
6b38c2a59656fe629bfdf10b89b05c6d8199833f | 10,509 | h | C | ccnxlibs/libccnx-transport-rta/ccnx/transport/common/transport_Stack.h | cherouvim/cicn-nrs | 440d6a7f56e7240f179205ed5ce1fe8000d03b83 | [
"Apache-2.0"
] | 10 | 2018-11-04T06:37:14.000Z | 2022-02-18T00:26:34.000Z | ccnxlibs/libccnx-transport-rta/ccnx/transport/common/transport_Stack.h | cherouvim/cicn-nrs | 440d6a7f56e7240f179205ed5ce1fe8000d03b83 | [
"Apache-2.0"
] | null | null | null | ccnxlibs/libccnx-transport-rta/ccnx/transport/common/transport_Stack.h | cherouvim/cicn-nrs | 440d6a7f56e7240f179205ed5ce1fe8000d03b83 | [
"Apache-2.0"
] | 3 | 2019-01-17T19:47:55.000Z | 2022-02-18T00:28:18.000Z | /*
* Copyright (c) 2017 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file transport_Stack.h
* @brief <#Brief Description#>
*
* <#Detailed Description#>
*
*/
#ifndef libccnx_ccnx_transport_Stack
#define libccnx_ccnx_transport_Stack
#include <stdbool.h>
#include <parc/algol/parc_JSON.h>
#include <parc/algol/parc_HashCode.h>
struct TransportStack;
typedef struct TransportStack TransportStack;
/**
* Increase the number of references to a `TransportStack` instance.
*
* Note that new `TransportStack` is not created,
* only that the given `TransportStack` reference count is incremented.
* Discard the reference by invoking `transportStack_Release`.
*
* @param [in] instance A pointer to a valid TransportStack instance.
*
* @return The same value as @p instance.
*
* Example:
* @code
* {
* TransportStack *a = transportStack_Create();
*
* TransportStack *b = transportStack_Acquire();
*
* transportStack_Release(&a);
* transportStack_Release(&b);
* }
* @endcode
*/
TransportStack *transportStack_Acquire(const TransportStack *instance);
#ifdef LIBRTA_DISABLE_VALIDATION
# define transportStack_OptionalAssertValid(_instance_)
#else
# define transportStack_OptionalAssertValid(_instance_) transportStack_AssertValid(_instance_)
#endif
/**
* Assert that the given `TransportStack` instance is valid.
*
* @param [in] instance A pointer to a valid TransportStack instance.
*
* Example:
* @code
* {
* TransportStack *a = transportStack_Create();
*
* transportStack_AssertValid(a);
*
* printf("Instance is valid.\n");
*
* transportStack_Release(&b);
* }
* @endcode
*/
void transportStack_AssertValid(const TransportStack *instance);
/**
* Create an instance of TransportStack
*
* <#Paragraphs Of Explanation#>
*
* @return non-NULL A pointer to a valid TransportStack instance.
* @return NULL An error occurred.
*
* Example:
* @code
* {
* TransportStack *a = transportStack_Create();
*
* transportStack_Release(&a);
* }
* @endcode
*/
TransportStack *transportStack_Create(void);
/**
* Compares @p instance with @p other for order.
*
* Returns a negative integer, zero, or a positive integer as @p instance
* is less than, equal to, or greater than @p other.
*
* @param [in] instance A pointer to a valid TransportStack instance.
* @param [in] other A pointer to a valid TransportStack instance.
*
* @return <0 Instance is less than @p other.
* @return 0 Instance a and instance b compare the same.
* @return >0 Instance a is greater than instance b.
*
* Example:
* @code
* {
* TransportStack *a = transportStack_Create();
* TransportStack *b = transportStack_Create();
*
* if (transportStack_Compare(a, b) == 0) {
* printf("Instances are equal.\n");
* }
*
* transportStack_Release(&a);
* transportStack_Release(&b);
* }
* @endcode
*
* @see transportStack_Equals
*/
int transportStack_Compare(const TransportStack *instance, const TransportStack *other);
/**
* Create an independent copy the given `PARCBuffer`
*
* A new buffer is created as a complete copy of the original.
*
* @param [in] original A pointer to a valid TransportStack instance.
*
* @return NULL Memory could not be allocated.
* @return non-NULL A pointer to a new `TransportStack` instance.
*
* Example:
* @code
* {
* TransportStack *a = transportStack_Create();
*
* TransportStack *copy = transportStack_Copy(&b);
*
* transportStack_Release(&b);
* transportStack_Release(©);
* }
* @endcode
*/
TransportStack *transportStack_Copy(const TransportStack *original);
/**
* Print a human readable representation of the given `TransportStack`.
*
* @param [in] instance A pointer to a valid TransportStack instance.
* @param [in] indentation The indentation level to use for printing.
*
* Example:
* @code
* {
* TransportStack *a = transportStack_Create();
*
* transportStack_Display(a, 0);
*
* transportStack_Release(&a);
* }
* @endcode
*/
void transportStack_Display(const TransportStack *instance, int indentation);
/**
* Determine if two `TransportStack` instances are equal.
*
* The following equivalence relations on non-null `TransportStack` instances are maintained: *
* * It is reflexive: for any non-null reference value x, `transportStack_Equals(x, x)` must return true.
*
* * It is symmetric: for any non-null reference values x and y, `transportStack_Equals(x, y)` must return true if and only if
* `transportStack_Equals(y x)` returns true.
*
* * It is transitive: for any non-null reference values x, y, and z, if
* `transportStack_Equals(x, y)` returns true and
* `transportStack_Equals(y, z)` returns true,
* then `transportStack_Equals(x, z)` must return true.
*
* * It is consistent: for any non-null reference values x and y, multiple invocations of `transportStack_Equals(x, y)`
* consistently return true or consistently return false.
*
* * For any non-null reference value x, `transportStack_Equals(x, NULL)` must return false.
*
* @param [in] x A pointer to a valid TransportStack instance.
* @param [in] y A pointer to a valid TransportStack instance.
*
* @return true The instances x and y are equal.
*
* Example:
* @code
* {
* TransportStack *a = transportStack_Create();
* TransportStack *b = transportStack_Create();
*
* if (transportStack_Equals(a, b)) {
* printf("Instances are equal.\n");
* }
*
* transportStack_Release(&a);
* transportStack_Release(&b);
* }
* @endcode
* @see transportStack_HashCode
*/
bool transportStack_Equals(const TransportStack *x, const TransportStack *y);
/**
* Returns a hash code value for the given instance.
*
* The general contract of `HashCode` is:
*
* Whenever it is invoked on the same instance more than once during an execution of an application,
* the `HashCode` function must consistently return the same value,
* provided no information used in a corresponding comparisons on the instance is modified.
*
* This value need not remain consistent from one execution of an application to another execution of the same application.
* If two instances are equal according to the {@link transportStack_Equals} method,
* then calling the {@link transportStack_HashCode} method on each of the two instances must produce the same integer result.
*
* It is not required that if two instances are unequal according to the
* {@link transportStack_Equals} function,
* then calling the `transportStack_HashCode`
* method on each of the two objects must produce distinct integer results.
*
* @param [in] instance A pointer to a valid TransportStack instance.
*
* @return The hashcode for the given instance.
*
* Example:
* @code
* {
* TransportStack *a = transportStack_Create();
*
* PARCHashCode hashValue = transportStack_HashCode(buffer);
* transportStack_Release(&a);
* }
* @endcode
*/
PARCHashCode transportStack_HashCode(const TransportStack *instance);
/**
* Determine if an instance of `TransportStack` is valid.
*
* Valid means the internal state of the type is consistent with its required current or future behaviour.
* This may include the validation of internal instances of types.
*
* @param [in] instance A pointer to a valid TransportStack instance.
*
* @return true The instance is valid.
* @return false The instance is not valid.
*
* Example:
* @code
* {
* TransportStack *a = transportStack_Create();
*
* if (transportStack_IsValid(a)) {
* printf("Instance is valid.\n");
* }
*
* transportStack_Release(&a);
* }
* @endcode
*
*/
bool transportStack_IsValid(const TransportStack *instance);
/**
* Release a previously acquired reference to the given `TransportStack` instance,
* decrementing the reference count for the instance.
*
* The pointer to the instance is set to NULL as a side-effect of this function.
*
* If the invocation causes the last reference to the instance to be released,
* the instance is deallocated and the instance's implementation will perform
* additional cleanup and release other privately held references.
*
* @param [in,out] instancePtr A pointer to a pointer to the instance to release.
*
* Example:
* @code
* {
* TransportStack *a = transportStack_Create();
*
* transportStack_Release(&a);
* }
* @endcode
*/
void transportStack_Release(TransportStack **instancePtr);
/**
* Create a `PARCJSON` instance (representation) of the given object.
*
* @param [in] instance A pointer to a valid TransportStack instance.
*
* @return NULL Memory could not be allocated to contain the `PARCJSON` instance.
* @return non-NULL An allocated C string that must be deallocated via parcMemory_Deallocate().
*
* Example:
* @code
* {
* TransportStack *a = transportStack_Create();
*
* PARCJSON *json = transportStack_ToJSON(a);
*
* printf("JSON representation: %s\n", parcJSON_ToString(json));
* parcJSON_Release(&json);
*
* transportStack_Release(&a);
* }
* @endcode
*/
PARCJSON *transportStack_ToJSON(const TransportStack *instance);
/**
* Produce a null-terminated string representation of the specified `TransportStack`.
*
* The result must be freed by the caller via {@link parcMemory_Deallocate}.
*
* @param [in] instance A pointer to a valid TransportStack instance.
*
* @return NULL Cannot allocate memory.
* @return non-NULL A pointer to an allocated, null-terminated C string that must be deallocated via {@link parcMemory_Deallocate}.
*
* Example:
* @code
* {
* TransportStack *a = transportStack_Create();
*
* char *string = transportStack_ToString(a);
*
* transportStack_Release(&a);
*
* parcMemory_Deallocate(&string);
* }
* @endcode
*
* @see transportStack_Display
*/
char *transportStack_ToString(const TransportStack *instance);
#endif
| 29.602817 | 131 | 0.706728 | [
"object"
] |
6b413e7b2acdf288a0181330af3aa9f10e9e9d69 | 2,181 | h | C | gl_vk_chopper/RenderContext.h | yangtzehina/VulkanStudy | 76af12e46ecbba0a2d22812ebec3faa7383b0328 | [
"MIT"
] | 1 | 2021-11-11T13:33:54.000Z | 2021-11-11T13:33:54.000Z | gl_vk_chopper/RenderContext.h | yangtzehina/VulkanStudy | 76af12e46ecbba0a2d22812ebec3faa7383b0328 | [
"MIT"
] | null | null | null | gl_vk_chopper/RenderContext.h | yangtzehina/VulkanStudy | 76af12e46ecbba0a2d22812ebec3faa7383b0328 | [
"MIT"
] | null | null | null | /*-----------------------------------------------------------------------
Copyright (c) 2014-2016, NVIDIA. 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.
* Neither the name of its contributors may be used to endorse
or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``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.
-----------------------------------------------------------------------*/
/* Contact chebert@nvidia.com (Chris Hebert) for feedback */
#ifndef __H_RENDERCONTEXT_
#define __H_RENDERCONTEXT_
#pragma once
#include<map>
#include "Scene.h"
#include"Mesh.h"
#include"WMath.h"
#include"Types.h"
#include "MeshUtils.h"
class RenderContext
{
public:
~RenderContext();
static RenderContext* Get();
Scene *newScene(const Scene::ID &inID);
Scene *getScene(const Scene::ID &inID);
void deleteScene(const Scene::ID &inID);
Mesh *newMesh(const Mesh::ID &inID, const meshimport::MeshDataf &inData);
Mesh *newMesh(const Mesh::ID &inID);
Mesh *getMesh(const Mesh::ID &inID);
void deleteMesh(const Mesh::ID &inID);
void getRenderTriangles(const Scene::ID &inID, render::TriangleList &outTriangles);
private:
RenderContext();
Scene::Map m_scene_map;
Mesh::Map m_mesh_map;
};
#endif | 32.552239 | 84 | 0.726272 | [
"mesh",
"render"
] |
6b46252adfbdcd556d4f8a296846fe4cf65eda48 | 1,307 | h | C | cmfe/lib/Driver/ToolChains/Arch/GenX.h | dmitryryintel/cm-compiler | 1ef7651dc1c33d3e4853f8779d6a720e45e20e19 | [
"Intel",
"MIT"
] | 115 | 2018-02-01T18:56:44.000Z | 2022-03-21T13:23:00.000Z | cmfe/lib/Driver/ToolChains/Arch/GenX.h | dmitryryintel/cm-compiler | 1ef7651dc1c33d3e4853f8779d6a720e45e20e19 | [
"Intel",
"MIT"
] | 27 | 2018-09-17T17:49:49.000Z | 2021-11-03T04:31:51.000Z | cmfe/lib/Driver/ToolChains/Arch/GenX.h | dmitryryintel/cm-compiler | 1ef7651dc1c33d3e4853f8779d6a720e45e20e19 | [
"Intel",
"MIT"
] | 55 | 2018-02-01T07:11:49.000Z | 2022-03-04T01:20:23.000Z | //===--- GenX.h - GenX-specific Tool Helpers --------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_ARCH_GENX_H
#define LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_ARCH_GENX_H
#include "clang/Driver/Driver.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/Option.h"
#include <string>
#include <vector>
namespace clang {
namespace driver {
namespace tools {
namespace GenX {
// get CPU from args
std::string getGenXTargetCPU(const llvm::opt::ArgList &Args);
// get features from args and triple
void getGenXTargetFeatures(const Driver &D, const llvm::Triple &Triple,
const llvm::opt::ArgList &Args,
std::vector<llvm::StringRef> &Features);
// binary format for CMRT is required according to options
bool isCMBinaryFormat(const llvm::opt::ArgList &Args);
} // end namespace GenX
} // namespace tools
} // end namespace driver
} // end namespace clang
#endif // LLVM_CLANG_LIB_DRIVER_TOOLCHAINS_ARCH_GENX_H
| 29.704545 | 80 | 0.65264 | [
"vector"
] |
6b506703c41737821d6a45338a48ddca9c7237a3 | 82,594 | c | C | source/ak_asn1_cert.c | kovdan01/libakrypt-0.x | 2f855c0c9cf0cf7591052d4ace43ed427d744812 | [
"MIT"
] | null | null | null | source/ak_asn1_cert.c | kovdan01/libakrypt-0.x | 2f855c0c9cf0cf7591052d4ace43ed427d744812 | [
"MIT"
] | null | null | null | source/ak_asn1_cert.c | kovdan01/libakrypt-0.x | 2f855c0c9cf0cf7591052d4ace43ed427d744812 | [
"MIT"
] | null | null | null | /* ----------------------------------------------------------------------------------------------- */
/* Copyright (c) 2021 by Axel Kenzo, axelkenzo@mail.ru */
/* */
/* Файл ak_asn1_cert.c */
/* - содержит реализацию функций, предназначенных для экспорта/импорта открытых ключей */
/* ----------------------------------------------------------------------------------------------- */
#include <libakrypt-internal.h>
/* ----------------------------------------------------------------------------------------------- */
#ifdef AK_HAVE_STRING_H
#include <string.h>
#endif
#ifdef AK_HAVE_TIME_H
#include <time.h>
#endif
/* ----------------------------------------------------------------------------------------------- */
/* Функции экспорта открытых ключей в запрос на сертификат */
/* ----------------------------------------------------------------------------------------------- */
/*! \brief Функция формирует фрагмент asn1 дерева, содержащий параметры открытого ключа.
\param vk контекст открытого ключа
\return Функция возвращает указатель на tlv узел, содержащий сформированную структуру.
В случае ошибки возвращается `NULL`. */
/* ----------------------------------------------------------------------------------------------- */
static ak_tlv ak_verifykey_export_to_asn1_value( ak_verifykey vk )
{
ak_oid ec = NULL;
struct bit_string bs;
int error = ak_error_ok;
ak_tlv tlv = NULL, os = NULL;
ak_asn1 asn = NULL, basn = NULL;
size_t val64 = sizeof( ak_uint64 )*vk->wc->size; /* количество октетов в одном вычете */
ak_uint8 data[ 2*sizeof(ak_uint64)*ak_mpznmax_size ]; /* asn1 представление открытого ключа */
ak_uint8 encode[ 4 + sizeof( data )]; /* кодированная octet string */
size_t sz = sizeof( encode );
if(( error = ak_asn1_add_oid( asn = ak_asn1_new(), vk->oid->id[0] )) != ak_error_ok ) goto labex;
if(( error = ak_asn1_add_asn1( asn, TSEQUENCE, ak_asn1_new( ))) != ak_error_ok ) goto labex;
if(( ec = ak_oid_find_by_data( vk->wc )) == NULL ) {
ak_error_message( ak_error_wrong_oid, __func__,
"public key has incorrect pointer to elliptic curve parameters" );
goto labex;
}
ak_asn1_add_oid( asn->current->data.constructed, ec->id[0] );
ak_asn1_add_oid( asn->current->data.constructed, vk->ctx.oid->id[0] );
if(( basn = ak_asn1_new()) == NULL ) goto labex;
if(( error = ak_asn1_add_asn1( basn, TSEQUENCE, asn )) != ak_error_ok ) {
if( basn != NULL ) ak_asn1_delete( basn );
goto labex;
}
/* кодируем открытый ключ => готовим octet string */
memset( data, 0, sizeof( data ));
if(( os = ak_tlv_new_primitive( TOCTET_STRING, ( val64<<1 ), data, ak_false )) == NULL ){
ak_error_message( ak_error_get_value(), __func__,
"incorrect creation of temporary tlv context" );
if( basn != NULL ) ak_asn1_delete( basn );
goto labex;
}
/* помещаем в нее данные */
ak_wpoint_reduce( &vk->qpoint, vk->wc );
ak_mpzn_to_little_endian( vk->qpoint.x, vk->wc->size, data, val64, ak_false );
ak_mpzn_to_little_endian( vk->qpoint.y, vk->wc->size, data+val64, val64, ak_false );
if(( error = ak_tlv_encode( os, encode, &sz )) != ak_error_ok ) {
ak_error_message( error, __func__, "incorrect encoding of temporary tlv context" );
if( os != NULL ) ak_tlv_delete( os );
if( basn != NULL ) ak_asn1_delete( basn );
goto labex;
}
bs.value = encode;
bs.len = sz;
bs.unused = 0;
ak_asn1_add_bit_string( basn, &bs );
if(( tlv = ak_tlv_new_constructed( TSEQUENCE^CONSTRUCTED, basn )) == NULL ) {
ak_asn1_delete( basn );
ak_error_message( ak_error_get_value(), __func__,
"incorrect addition the bit sting with public key value" );
}
ak_tlv_delete( os );
return tlv;
labex:
if( asn != NULL ) ak_asn1_delete( asn );
ak_error_message( ak_error_get_value(), __func__,
"incorrect export of public key into request asn1 tree" );
return NULL;
}
/* ----------------------------------------------------------------------------------------------- */
/*! \brief Функция формирует asn1 дерево с запросом на сертификат открытого ключа.
Выполняются следующие действия:
- формируется tlv элемент, содержащий имя владельца, параметры алгоритма и значение ключа,
- tlv элемент кодируется в der-последовательность,
- вырабатывается подпись под der-последовательностью,
- идентификатор алгоритма выработки подписи и значение подписи также помещаются в asn1 дерево.
\param vk контекст открытого ключа
\param sk контекст секретного ключа
\param a уровень asn1 дерева, в который помещается запрос на сертификат.
\return Функция возвращает \ref ak_error_ok (ноль) в случае успеха, в случае неудачи
возвращается код ошибки. */
/* ----------------------------------------------------------------------------------------------- */
static int ak_verifykey_export_to_asn1_request( ak_verifykey vk, ak_signkey sk,
ak_random generator, ak_asn1 a )
{
ak_asn1 asn = NULL;
struct bit_string bs;
int error = ak_error_ok;
ak_uint8 data[4096], s[128];
size_t size = sizeof( data );
ak_tlv tlv = NULL, pkey = NULL;
if( a == NULL ) return ak_error_message( ak_error_null_pointer, __func__,
"using null pointer to asn1 context" );
if( !ak_ptr_is_equal( vk->number, sk->verifykey_number, sizeof( vk->number )))
return ak_error_message( ak_error_not_equal_data, __func__,
"secret key not correspondig to public key" );
if( ak_signkey_get_tag_size( sk ) > sizeof( s ))
ak_error_message( ak_error_wrong_length, __func__,
"using digital signature algorithm with very large signature" );
/* 1. Создаем последовательность, которая будет содержать данные запроса */
if(( error = ak_asn1_add_asn1( a, TSEQUENCE^CONSTRUCTED, asn = ak_asn1_new())) != ak_error_ok ) {
if( asn != NULL ) ak_asn1_delete( asn );
return ak_error_message( error, __func__, "incorrect creation of first level sequence");
}
/* 2. Создаем tlv элемент, для которого, потом, будет вычисляться электронная подпись */
tlv = ak_tlv_new_constructed( TSEQUENCE^CONSTRUCTED, asn = ak_asn1_new( ));
/* добавляем ноль */
ak_asn1_add_uint32( asn, 0 );
/* копируем asn1 дерево с расширенным именем из структуры открытого ключа
в asn1 дерево формируемого запроса */
ak_asn1_add_tlv( asn, ak_tlv_duplicate_global_name( vk->name ));
/* помещаем информацию об алгоритме и открытом ключе */
ak_asn1_add_tlv( asn, pkey = ak_verifykey_export_to_asn1_value( vk ));
if( pkey == NULL ) {
if( tlv != NULL ) tlv = ak_tlv_delete( tlv );
return ak_error_message( ak_error_get_value(), __func__,
"incorrect export of public key into tlv context" );
}
/* 0x00 это помещаемое в CONTEXT_SPECIFIC значение */
ak_asn1_add_asn1( asn, CONTEXT_SPECIFIC^0x00, ak_asn1_new( ));
/* 3. Помещаем tlv элемент в основное дерево */
ak_asn1_add_tlv( a->current->data.constructed, tlv );
/* 4. Помещаем идентификатор алгоритма выработки подписи */
ak_asn1_add_asn1( a->current->data.constructed, TSEQUENCE^CONSTRUCTED, asn = ak_asn1_new());
ak_asn1_add_oid( asn, sk->key.oid->id[0] );
/* 4. Помещаем bit-string со значением подписи */
if(( error = ak_tlv_encode( tlv, data, &size )) != ak_error_ok )
return ak_error_message( error, __func__, "incorrect encoding of asn1 context");
memset( s, 0, sizeof( s ));
if(( error = ak_signkey_sign_ptr( sk, generator, data, size, s, sizeof( s ))) != ak_error_ok )
return ak_error_message( error, __func__, "incorrect signing internal data" );
bs.value = s;
bs.len = ak_signkey_get_tag_size( sk );
bs.unused = 0;
if(( error = ak_asn1_add_bit_string( a->current->data.constructed, &bs )) != ak_error_ok )
ak_error_message( error, __func__, "incorrect adding a digital signature value" );
return error;
}
/* ----------------------------------------------------------------------------------------------- */
/*! Функция помещает информацию об открытом ключе в asn1 дерево, подписывает эту информацию
и сохраняет созданное дерево в файл, который называется "запросом на сертификат".
\note Контекст секретного ключа `sk` должен соответствовать контексту открытого ключа `vk`.
В противном случае нельзя будет проверить электронную подпись под открытым ключом, поскольку
запрос на сертификат, по сути, является урезанной версией самоподписанного сертификата.
Отсюда следует, что нельзя создать запрос на сертификат ключа, который не поддерживает
определенный библиотекой алгоритм подписи (например ключ на кривой в 640 бит).
Такие ключи должны сразу помещаться в сертификат.
\param vk Контекст открытого ключа
\param sk Контекст секретного ключа, соответствующий открытому ключу
\param generator Генератор псевдослучайных последовательностей, используемый для выработки
электронной подписи под запросом на сертификат
\param filename Указатель на строку, содержащую имя файла, в который будет экспортирован ключ;
Если параметр `size` отличен от нуля,
то указатель должен указывать на область памяти, в которую будет помещено сформированное имя файла.
\param size Размер области памяти, в которую будет помещено имя файла.
Если размер области недостаточен, то будет возбуждена ошибка.
Данный параметр должен принимать значение 0 (ноль), если указатель `filename` указывает
на константную строку.
\param format Формат, в котором сохраняются данные - der или pem.
\return Функция возвращает \ref ak_error_ok (ноль) в случае успеха, в случае неудачи
возвращается код ошибки. */
/* ----------------------------------------------------------------------------------------------- */
int ak_verifykey_export_to_request( ak_verifykey vk, ak_signkey sk, ak_random generator,
char *filename, const size_t size, export_format_t format )
{
ak_asn1 asn = NULL;
int error = ak_error_ok;
if( vk == NULL ) return ak_error_message( ak_error_null_pointer, __func__,
"using null pointer to public key context" );
if( sk == NULL ) return ak_error_message( ak_error_null_pointer, __func__,
"using null pointer to secret key context" );
if( filename == NULL ) return ak_error_message( ak_error_null_pointer, __func__,
"using null pointer to file name" );
/* 1. При необходимости, формируем имя файла для экспорта открытого ключа
Формируемое имя совпадает с номером ключа и однозначно зависит от его значения */
if( size != 0 ) {
memset( filename, 0, size );
if( size < 12 ) return ak_error_message( ak_error_wrong_length, __func__,
"using small buffer to storing request file name" );
else ak_snprintf( filename, size, "%s.csr",
ak_ptr_to_hexstr( vk->number, sizeof( vk->number ), ak_false ));
}
/* 2. Создаем asn1 дерево */
if(( error = ak_verifykey_export_to_asn1_request( vk, sk, generator,
asn = ak_asn1_new( ))) != ak_error_ok ) {
ak_error_message( error, __func__, "incorrect creation af asn1 context" );
goto labexit;
}
/* 3. Сохраняем созданное дерево в файл */
if(( error = ak_asn1_export_to_file( asn,
filename, format, public_key_request_content )) != ak_error_ok ) {
ak_error_message_fmt( error, __func__, "incorrect export asn1 context to file %s", filename );
goto labexit;
}
labexit:
if( asn != NULL ) asn = ak_asn1_delete( asn );
return error;
}
/* ----------------------------------------------------------------------------------------------- */
/* Функции импорта открытых ключей из запроса на сертификат */
/* ----------------------------------------------------------------------------------------------- */
static int ak_verifykey_import_from_asn1_value( ak_verifykey vkey, ak_asn1 asnkey,
ak_function_file_output verbose )
{
size_t size = 0;
char message[256];
ak_oid oid = NULL;
struct bit_string bs;
ak_pointer ptr = NULL;
int error = ak_error_ok;
ak_asn1 asn = asnkey, asnl1;
ak_uint32 val = 0, val64 = 0;
/* проверяем наличие последовательности верхнего уровня */
ak_asn1_first( asn );
if(( DATA_STRUCTURE( asn->current->tag ) != CONSTRUCTED ) ||
( TAG_NUMBER( asn->current->tag ) != TSEQUENCE ))
return ak_error_message( ak_error_invalid_asn1_tag, __func__ ,
"the first next level element must be a sequence" );
/* получаем алгоритм электронной подписи */
ak_asn1_first( asnl1 = asn->current->data.constructed );
if(( DATA_STRUCTURE( asnl1->current->tag ) != PRIMITIVE ) ||
( TAG_NUMBER( asnl1->current->tag ) != TOBJECT_IDENTIFIER ))
return ak_error_message( ak_error_invalid_asn1_tag, __func__ ,
"the first element of child asn1 context must be an object identifier" );
if(( error = ak_tlv_get_oid( asnl1->current, &ptr )) != ak_error_ok )
return ak_error_message( error, __func__, "incorrect reading an object identifier" );
if(( oid = ak_oid_find_by_id( ptr )) == NULL )
return ak_error_message_fmt( ak_error_oid_id, __func__,
"using unsupported object identifier %s", ptr );
if(( oid->engine != verify_function ) || ( oid->mode != algorithm ))
return ak_error_message( ak_error_oid_engine, __func__, "using wrong object identifier" );
/* получаем параметры элиптической кривой */
ak_asn1_next( asnl1 );
if(( DATA_STRUCTURE( asnl1->current->tag ) != CONSTRUCTED ) ||
( TAG_NUMBER( asnl1->current->tag ) != TSEQUENCE ))
return ak_error_message( ak_error_invalid_asn1_tag, __func__ ,
"the second element of child asn1 context must be a sequence of object identifiers" );
asnl1 = asnl1->current->data.constructed;
ak_asn1_first( asnl1 );
if(( DATA_STRUCTURE( asnl1->current->tag ) != PRIMITIVE ) ||
( TAG_NUMBER( asnl1->current->tag ) != TOBJECT_IDENTIFIER ))
return ak_error_message( ak_error_invalid_asn1_tag, __func__ ,
"the first element of last child asn1 context must be an object identifier" );
if(( error = ak_tlv_get_oid( asnl1->current, &ptr )) != ak_error_ok )
return ak_error_message( error, __func__, "incorrect reading an object identifier" );
if(( oid = ak_oid_find_by_id( ptr )) == NULL )
return ak_error_message_fmt( ak_error_oid_id, __func__,
"import an unsupported object identifier %s for elliptic curve", ptr );
if(( oid->engine != identifier ) || ( oid->mode != wcurve_params ))
return ak_error_message( ak_error_oid_engine, __func__, "using wrong object identifier" );
/* создаем контекст */
asnl1 = NULL;
if(( error = ak_verifykey_create( vkey, (const ak_wcurve )oid->data )) != ak_error_ok )
return ak_error_message( error, __func__, "incorrect creation of verify key context" );
/* получаем значение открытого ключа */
ak_asn1_last( asn );
if(( DATA_STRUCTURE( asn->current->tag ) != PRIMITIVE ) ||
( TAG_NUMBER( asn->current->tag ) != TBIT_STRING )) {
ak_error_message( error = ak_error_invalid_asn1_tag, __func__ ,
"the second element of child asn1 context must be a bit string" );
goto lab1;
}
if(( error = ak_tlv_get_bit_string( asn->current, &bs )) != ak_error_ok ) {
ak_error_message( error, __func__, "incorrect reading a bit string" );
goto lab1;
}
/* считали битовую строку, проверяем что это der-кодировка некоторого целого числа */
if(( error = ak_asn1_decode( asnl1 = ak_asn1_new(),
bs.value, bs.len, ak_false )) != ak_error_ok ) {
ak_error_message( error, __func__, "incorrect decoding a value of public key" );
goto lab1;
}
if(( DATA_STRUCTURE( asnl1->current->tag ) != PRIMITIVE ) ||
( TAG_NUMBER( asnl1->current->tag ) != TOCTET_STRING )) {
ak_error_message( error = ak_error_invalid_asn1_tag, __func__ ,
"the public key must be an octet string" );
goto lab1;
}
/* считываем строку и разбиваем ее на две половинки */
val = ( ak_uint32 )vkey->wc->size;
val64 = sizeof( ak_uint64 )*val;
ak_tlv_get_octet_string( asnl1->current, &ptr, &size );
if( size != 2*val64 ) {
ak_error_message_fmt( error = ak_error_wrong_length, __func__ ,
"the size of public key is equal to %u (must be %u octets)", (unsigned int)size, 2*val64 );
goto lab1;
}
/* копируем данные и проверям, что точка действительно принадлежит кривой */
ak_mpzn_set_little_endian( vkey->qpoint.x, val, ptr, val64, ak_false );
ak_mpzn_set_little_endian( vkey->qpoint.y, val, ((ak_uint8*)ptr)+val64, val64, ak_false );
ak_mpzn_set_ui( vkey->qpoint.z, val, 1 );
if( ak_wpoint_is_ok( &vkey->qpoint, vkey->wc ) != ak_true ) {
ak_error_message_fmt( error = ak_error_curve_point, __func__ ,
"the public key isn't on given elliptic curve" );
goto lab1;
}
/* устанавливаем флаг */
vkey->flags = ak_key_flag_set_key;
/* выводим считанное */
if( verbose ) {
verbose(" Public Key:\n");
ak_snprintf( message, sizeof( message ), " x: %s\n",
ak_mpzn_to_hexstr( vkey->qpoint.x, vkey->wc->size )); verbose( message );
ak_snprintf( message, sizeof( message ), " y: %s\n",
ak_mpzn_to_hexstr( vkey->qpoint.y, vkey->wc->size )); verbose( message );
ak_snprintf( message, sizeof( message ), " curve: %s (%u bits)\n",
oid->name[0], 64*vkey->wc->size ); verbose( message );
}
lab1:
if( asnl1 != NULL ) ak_asn1_delete( asnl1 );
if( error != ak_error_ok ) ak_verifykey_destroy( vkey );
return error;
}
/* ----------------------------------------------------------------------------------------------- */
/*! \brief Функция получает значение открытого ключа из запроса на сертификат,
разобранного в ASN.1 дерево, и создает контекст открытого ключа.
Функция считывает oid алгоритма подписи и проверяет, что он соответствует ГОСТ Р 34.12-2012,
потом функция считывает параметры эллиптической кривой и проверяет, что библиотека поддерживает
данные параметры. В заключение функция считывает открытый ключ и проверяет,
что он принадлежит кривой со считанными ранее параметрами.
После выполнения всех проверок, функция создает (действие `create`) контекст открытого ключа,
а также присваивает (действие `set_key`) ему считанное из asn1 дерева значение.
\param vkey контекст создаваемого открытого ключа асимметричного криптографического алгоритма
\param asnkey считанное из файла asn1 дерево
\return Функция возвращает \ref ak_error_ok (ноль) в случае успеха, в случае неудачи
возвращается код ошибки. */
/* ----------------------------------------------------------------------------------------------- */
static int ak_verifykey_import_from_asn1_request( ak_verifykey vkey, ak_asn1 asnkey,
ak_function_file_output verbose )
{
char message[512];
ak_uint32 val = 0;
ak_asn1 asn = asnkey; /* копируем адрес */
/* проверяем, что первым элементом содержится ноль */
ak_asn1_first( asn );
if(( DATA_STRUCTURE( asn->current->tag ) != PRIMITIVE ) ||
( TAG_NUMBER( asn->current->tag ) != TINTEGER ))
return ak_error_message( ak_error_invalid_asn1_tag, __func__ ,
"the first element of root asn1 context be an integer" );
ak_tlv_get_uint32( asn->current, &val );
if( val != 0 ) return ak_error_message( ak_error_invalid_asn1_content, __func__ ,
"the first element of asn1 context must be a zero" );
if( verbose ) {
verbose(" Type:\n Public Key Certificate's Request\n");
ak_snprintf( message, sizeof( message ), " Version: v%d\n", val+1 );
verbose( message );
}
/* второй элемент содержит имя владельца ключа.
этот элемент должен быть позднее перенесен в контекст открытого ключа */
ak_asn1_next( asn );
if( verbose ) {
verbose(" Subject:\n");
ak_tlv_snprintf_global_name( asn->current, message, sizeof( message ));
verbose( message ); verbose( "\n" );
}
/* третий элемент должен быть SEQUENCE с набором oid и значением ключа */
if( ak_asn1_next( asn ) != ak_true )
return ak_error_message( ak_error_invalid_asn1_count, __func__, "unexpected end of asn1 tree" );
/* проверяем наличие последовательности верхнего уровня */
if(( DATA_STRUCTURE( asn->current->tag ) != CONSTRUCTED ) ||
( TAG_NUMBER( asn->current->tag ) != TSEQUENCE ))
return ak_error_message( ak_error_invalid_asn1_tag, __func__ ,
"the element of root asn1 tree must be a sequence with object identifiers" );
asn = asn->current->data.constructed;
return ak_verifykey_import_from_asn1_value( vkey, asn, verbose );
}
/* ----------------------------------------------------------------------------------------------- */
/*! Функция считывает из заданного файла запрос на получение сертификата. Запрос хранится в виде
asn1 дерева, определяемого Р 1323565.1.023-2018.
Собственно asn1 дерево может быть храниться в файле в виде обычной der-последовательности,
либо в виде der-последовательности, дополнительно закодированной в `base64` (формат `pem`).
\note Функция является конструктором контекста ak_verifykey.
После считывания asn1 дерева функция проверяет подпись под открытым ключом и,
в случае успешной проверки, создает контекст `vkey` и инициирует его необходимыми значениями.
\param vkey контекст создаваемого открытого ключа асимметричного криптографического алгоритма
\param filename имя файла
\return Функция возвращает \ref ak_error_ok (ноль) в случае успеха, в случае неудачи
возвращается код ошибки. */
/* ----------------------------------------------------------------------------------------------- */
int ak_verifykey_import_from_request( ak_verifykey vkey, const char *filename,
ak_function_file_output verbose )
{
size_t size = 0;
ak_tlv tlv = NULL;
struct bit_string bs;
ak_uint8 buffer[4096];
int error = ak_error_ok;
ak_asn1 root = NULL, asn = NULL, asnkey = NULL;
/* стандартные проверки */
if( vkey == NULL ) return ak_error_message( ak_error_null_pointer, __func__,
"using null pointer to secret key context" );
if( filename == NULL ) return ak_error_message( ak_error_null_pointer, __func__,
"using null pointer to filename" );
/* считываем ключ и преобразуем его в ASN.1 дерево */
if(( error = ak_asn1_import_from_file( root = ak_asn1_new(), filename )) != ak_error_ok ) {
ak_error_message_fmt( error, __func__,
"incorrect reading of ASN.1 context from %s file", filename );
goto lab1;
}
/* здесь мы считали asn1, декодировали и должны убедиться, что это то самое дерево */
ak_asn1_first( root );
tlv = root->current;
if( DATA_STRUCTURE( tlv->tag ) != CONSTRUCTED ) {
ak_error_message( error = ak_error_invalid_asn1_tag,
__func__, "incorrect structure of asn1 context" );
goto lab1;
}
/* проверяем количество узлов */
if(( asn = tlv->data.constructed )->count != 3 ) {
ak_error_message_fmt( error = ak_error_invalid_asn1_count, __func__,
"root asn1 context contains incorrect count of leaves" );
goto lab1;
}
/* первый узел позволит нам получить значение открытого ключа
(мы считываем параметры эллиптической кривой, инициализируем контекст значением
открытого ключа и проверяем, что ключ принадлежит указанной кривой ) */
ak_asn1_first( asn );
if( DATA_STRUCTURE( asn->current->tag ) != CONSTRUCTED ) {
ak_error_message( error = ak_error_invalid_asn1_tag, __func__,
"incorrect structure of asn1 context" );
goto lab1;
}
if(( error = ak_verifykey_import_from_asn1_request( vkey,
asnkey = asn->current->data.constructed, verbose )) != ak_error_ok ) {
ak_error_message( error, __func__, "incorrect structure of request" );
goto lab1;
}
/* 4. На основе считанных данных формируем номер ключа */
if(( error = ak_verifykey_set_number( vkey )) != ak_error_ok ) {
ak_error_message( error, __func__, "incorrect creation on public key number" );
goto lab1;
}
/* второй узел, в нашей терминологии, содержит идентификатор секретного ключа
и бесполезен, поскольку вся информация об открытом ключе проверки подписи,
эллиптической кривой и ее параметрах уже считана. остается только проверить подпись,
расположенную в последнем, третьем узле запроса. */
/* 1. Начинаем с того, что готовим данные, под которыми должна быть проверена подпись */
memset( buffer, 0, size = sizeof( buffer ));
ak_asn1_first( asn );
if(( error = ak_tlv_encode( asn->current, buffer, &size )) != ak_error_ok ) {
ak_error_message_fmt( error, __func__,
"incorrect encoding of tlv context contains of %u octets", (unsigned int) size );
goto lab1;
}
/* 2. Теперь получаем значение подписи из asn1 дерева и сравниваем его с вычисленным значением */
ak_asn1_last( asn );
if(( DATA_STRUCTURE( asn->current->tag ) != PRIMITIVE ) ||
( TAG_NUMBER( asn->current->tag ) != TBIT_STRING )) {
ak_error_message( error = ak_error_invalid_asn1_tag, __func__ ,
"the second element of child asn1 context must be a bit string" );
goto lab1;
}
if(( error = ak_tlv_get_bit_string( asn->current, &bs )) != ak_error_ok ) {
ak_error_message( error , __func__ , "incorrect value of bit string in root asn1 context" );
goto lab1;
}
/* 3. Только сейчас проверяем подпись под данными */
if( ak_verifykey_verify_ptr( vkey, buffer, size, bs.value ) != ak_true ) {
ak_error_message( error = ak_error_not_equal_data, __func__, "digital signature isn't valid" );
goto lab1;
}
/* 5. В самом конце, после проверки подписи,
изымаем узел, содержащий имя владельца открытого ключа -- далее этот узел будет перемещен
в сертификат открытого ключа.
Все проверки пройдены ранее и нам точно известна структура asn1 дерева. */
ak_asn1_first( asn );
asn = asn->current->data.constructed;
ak_asn1_first( asn );
ak_asn1_next( asn ); /* нужен второй узел */
vkey->name = ak_asn1_exclude( asn );
lab1: if( root != NULL ) ak_asn1_delete( root );
return error;
}
/* ----------------------------------------------------------------------------------------------- */
/* Служебные функции для работы с сертификатами */
/* ----------------------------------------------------------------------------------------------- */
/*! Данный номер (serialNumber) зависит от номера секретного ключа, подписывающего открытый ключ и,
тем самым, может принимать различные значения для каждого из подписывающих ключей.
Серийный номер сертификата образуют младшие 32 байта результата хеширования
последовательной конкатенации номеров открытого и секретного ключей.
Для хеширования используется функция, определенная в контексте `секретного` ключа,
т.е. Стрибог512 для длинной подписи и Стрибог256 для короткой.
\code
result[0..31] = Hash( vk->number || sk->number )
\endcode
Вычисленное значение не помещается в контекст открытого ключа, а возвращается как
большое целое число. Это позволяет использовать данную функцию как при экспорте,
так и при импорте сертификатов открытых ключей (в момент разбора цепочек сертификации).
\param vk контекст открытого ключа, помещаемого в asn1 дерево сертификата
\param sk контекст ключа подписи, содержащий параметры центра сертификации
\param serialNumber переменная, в которую помещается серийный номер.
\return Функция возвращает указатель на созданный объект.
В случае ошибки возвращается NULL. */
/* ----------------------------------------------------------------------------------------------- */
int ak_verifykey_generate_certificate_serial_number( ak_verifykey vk,
ak_signkey sk, ak_mpzn256 serialNumber )
{
ak_uint8 result[64];
/* используем для хеширования контекст секретного ключа */
if( ak_hash_get_tag_size( &sk->ctx ) > sizeof( result ))
return ak_error_message( ak_error_wrong_length, __func__,
"using secret key with huge signature tag" );
memset( result, 0, sizeof( result ));
ak_hash_clean( &sk->ctx );
ak_hash_update( &sk->ctx, vk->number, sizeof( vk->number ));
ak_hash_finalize( &sk->ctx, sk->key.number, sizeof( sk->key.number ), result, sizeof( result ));
ak_mpzn_set_little_endian( serialNumber, ak_mpzn256_size, result, 32, ak_true );
return ak_error_ok;
}
/* ----------------------------------------------------------------------------------------------- */
/*! \param opts указатель на структуру, в которой передаются параметры сертификата
\return В случае успеха функция возвращает \ref ak_error_ok (ноль), в противном случае,
возвращается код ошибки. */
/* ----------------------------------------------------------------------------------------------- */
int ak_certificate_opts_create( ak_certificate_opts opts )
{
if( opts == NULL ) return ak_error_message( ak_error_null_pointer, __func__,
"initializing null pointer to certificate options" );
memset( opts, 0, sizeof( struct certificate_opts ));
/* значения по умолчанию */
opts->ca.is_present = ak_false;
opts->key_usage.is_present = ak_false;
opts->subjkey.is_present = ak_false;
opts->authoritykey.is_present = ak_false;
return ak_error_ok;
}
/* ----------------------------------------------------------------------------------------------- */
/*! \param opts указатель на структуру, в которой передаются параметры сертификата
\return В случае успеха функция возвращает \ref ak_error_ok (ноль), в противном случае,
возвращается код ошибки. */
/* ----------------------------------------------------------------------------------------------- */
int ak_certificate_opts_destroy( ak_certificate_opts opts )
{
if( opts == NULL ) return ak_error_message( ak_error_null_pointer, __func__,
"destroying null pointer to certificate options" );
memset( opts, 0, sizeof( struct certificate_opts ));
return ak_error_ok;
}
/* ----------------------------------------------------------------------------------------------- */
/* Функции экспорта открытых ключей в сертификат */
/* ----------------------------------------------------------------------------------------------- */
/*! \brief Создание tlv узла, содержащего структуру TBSCertificate версии 3
в соответствии с Р 1323565.1.023-2018.
Структура `tbsCertificate` определяется следующим образом
\code
TBSCertificate ::= SEQUENCE {
version [0] Version DEFAULT v1,
serialNumber CertificateSerialNumber,
signature AlgorithmIdentifier,
issuer Name,
validity Validity,
subject Name,
subjectPublicKeyInfo SubjectPublicKeyInfo,
issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL,
-- If present, version MUST be v2 or v3
subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL,
-- If present, version MUST be v2 or v3
extensions [3] Extensions OPTIONAL
-- If present, version MUST be v3 -- }
\endcode
Перечень добавляемых расширений определяется значениями аргумента `opts`.
\param subject_vkey контекст открытого ключа, помещаемого в asn1 дерево сертификата
\param issuer_skey контекст ключа подписи
\param issuer_vkey контект ключа проверки подписи, содержащий параметры центра сертификации
\param opts набор опций, формирующих помещаемые в сертификат расширения
\return Функция возвращает указатель на созданный объект.
В случае ошибки возвращается NULL. */
/* ----------------------------------------------------------------------------------------------- */
static ak_tlv ak_verifykey_export_to_tbs( ak_verifykey subject_vkey, ak_signkey issuer_skey,
ak_verifykey issuer_vkey, ak_certificate_opts opts )
{
ak_mpzn256 serialNumber;
ak_tlv tbs = NULL, tlv = NULL;
ak_asn1 asn = NULL, tbasn = NULL;
if(( tbs = ak_tlv_new_sequence()) == NULL ) {
ak_error_message( ak_error_get_value(), __func__, "incorrect creation of tlv context" );
return NULL;
}
else tbasn = tbs->data.constructed;
/* теперь создаем дерево сертификата в соответствии с Р 1323565.1.023-2018
version: начинаем с размещения версии сертификата, т.е. ветки следующего вида
┐
├[0]┐
│ └INTEGER 2 (величина 2 является максимально возможным значением ) */
ak_asn1_add_asn1( tbasn, CONTEXT_SPECIFIC^0x00, asn = ak_asn1_new( ));
if( asn != NULL ) ak_asn1_add_uint32( asn, 2 );
else {
ak_error_message( ak_error_get_value(), __func__,
"incorrect creation of certificate version context");
goto labex;
}
/* serialNumber: вырабатываем и добавляем номер сертификата */
ak_verifykey_generate_certificate_serial_number( subject_vkey, issuer_skey, serialNumber );
ak_asn1_add_mpzn( tbasn, TINTEGER, serialNumber, ak_mpzn256_size );
/* signature: указываем алгоритм подписи (это будет повторено еще раз при выработке подписи) */
ak_asn1_add_algorithm_identifier( tbasn, issuer_skey->key.oid, NULL );
/* issuer: вставляем информацию о расширенном имени лица, подписывающего ключ
(эмитента, выдающего сертификат) */
ak_asn1_add_tlv( tbasn, ak_tlv_duplicate_global_name( issuer_vkey->name ));
/* validity: вставляем информацию в времени действия ключа */
ak_asn1_add_validity( tbasn, issuer_skey->key.resource.time.not_before,
issuer_skey->key.resource.time.not_after );
/* subject: вставляем информацию о расширенном имени владельца ключа */
ak_asn1_add_tlv( tbasn, ak_tlv_duplicate_global_name( subject_vkey->name ));
/* subjectPublicKeyInfo: вставляем информацию об открытом ключе */
ak_asn1_add_tlv( tbasn, tlv = ak_verifykey_export_to_asn1_value( subject_vkey ));
if( tlv == NULL ) {
ak_error_message( ak_error_get_value(), __func__,
"incorrect generation of subject public key info" );
goto labex;
}
/* теперь мы принимаем решение - сертификат самоподписанный или нет
выполняется проверка на совпадение subjectKeyIdentifier (номера открытого ключа) */
if( ak_ptr_is_equal( subject_vkey->number, issuer_vkey->number, 32 )) {
opts->ca.is_present = ak_true;
opts->ca.value = ak_true;
if( !opts->key_usage.is_present ) opts->key_usage.is_present = ak_true;
if( !(opts->key_usage.bits&bit_keyCertSign )) opts->key_usage.bits ^= bit_keyCertSign;
}
/* далее мы реализуем возможности сертификатов третьей версии, а именно
вставляем перечень расширений
0x03 это помещаемое в CONTEXT_SPECIFIC значение */
ak_asn1_add_asn1( tbasn, CONTEXT_SPECIFIC^0x03, asn = ak_asn1_new( ));
if( asn == NULL ) {
ak_error_message( ak_error_get_value(), __func__,
"incorrect creation of certificate extensions asn1 context");
goto labex;
}
ak_asn1_add_tlv( asn, ak_tlv_new_sequence( ));
asn = asn->current->data.constructed;
/* 1. В обязательном порядке добавляем номер открытого ключа */
ak_asn1_add_tlv( asn, tlv = ak_tlv_new_subject_key_identifier( subject_vkey->number, 32 ));
if( tlv == NULL ) {
ak_error_message( ak_error_get_value(), __func__,
"incorrect generation of SubjectKeyIdentifier extension" );
goto labex;
}
/* 2. Если определено расширение BasicConstraints, то добавляем его
(расширение может добавляться не только в самоподписаные сертификаты) */
if( opts->ca.is_present ) {
ak_asn1_add_tlv( asn,
tlv = ak_tlv_new_basic_constraints( opts->ca.value , opts->ca.pathlenConstraint ));
if( tlv == NULL ) {
ak_error_message( ak_error_get_value(), __func__,
"incorrect generation of SubjectKeyIdentifier extension" );
goto labex;
}
}
/* 3. Если определены флаги keyUsage, то мы добавляем соответствующее расширение */
if( opts->key_usage.is_present ) {
ak_asn1_add_tlv( asn, tlv = ak_tlv_new_key_usage( opts->key_usage.bits ));
if( tlv == NULL ) {
ak_error_message( ak_error_get_value(), __func__,
"incorrect generation of SubjectKeyIdentifier extension" );
goto labex;
}
}
/* 4. Добавляем имена для поиска ключа проверки подписи (Authority Key Identifier)
данное расширение будет добавляться всегда */
ak_asn1_add_tlv( asn, tlv = ak_tlv_new_authority_key_identifier( issuer_skey,
issuer_vkey, opts->authoritykey.include_name ));
if( tlv == NULL ) {
ak_error_message( ak_error_get_value(), __func__,
"incorrect generation of Authority Key Identifier extension" );
goto labex;
}
return tbs;
labex: if( tbs != NULL ) ak_tlv_delete( tbs );
return NULL;
}
/* ----------------------------------------------------------------------------------------------- */
/*! \brief Функция создает asn1 дерево, содержащее сертификат открытого ключа.
\param subject_vkey контекст открытого ключа, помещаемого в asn1 дерево сертификата
\param issuer_skey контекст ключа подписи
\param issuer_vkey контект ключа проверки подписи, содержащий параметры центра сертификации
\param generator геератор случайных последовательностей, используемый для подписи сертификата
\param opts набор опций, формирующих помещаемые в сертификат расширения
\return Функция возвращает указатель на созданный объект.
В случае ошибки возвращается NULL. */
/* ----------------------------------------------------------------------------------------------- */
static ak_asn1 ak_verifykey_export_to_asn1_certificate( ak_verifykey subject_vkey,
ak_signkey issuer_skey, ak_verifykey issuer_vkey, ak_random generator, ak_certificate_opts opts )
{
size_t len = 0;
struct bit_string bs;
int error = ak_error_ok;
ak_asn1 certificate = NULL;
ak_uint8 encode[4096], out[128];
ak_tlv tlv = NULL, ta = NULL, tbs = NULL;
/* создаем контейнер для сертификата */
if(( error = ak_asn1_add_tlv( certificate = ak_asn1_new(),
tlv = ak_tlv_new_sequence( ))) != ak_error_ok ) {
ak_error_message( error, __func__, "incorrect addition of tlv context" );
goto labex;
}
if( tlv == NULL ) {
ak_error_message( ak_error_null_pointer, __func__, "incorrect creation of tlv context" );
goto labex;
}
/* создаем поле tbsCertificate */
if(( tbs = ak_verifykey_export_to_tbs( subject_vkey, issuer_skey, issuer_vkey, opts )) == NULL ) {
ak_error_message( ak_error_get_value(), __func__,
"incorrect creation of tbsCertificate element" );
goto labex;
}
/* вставляем в основное дерево созданный элемент */
ak_asn1_add_tlv( tlv->data.constructed, tbs );
/* добавляем информацию о алгоритме подписи */
ak_asn1_add_tlv( tlv->data.constructed, ta = ak_tlv_new_sequence( ));
if( ta == NULL ) {
ak_error_message( ak_error_get_value(), __func__,
"incorrect generation of digital signature identifier" );
goto labex;
}
ak_asn1_add_oid( ta->data.constructed, issuer_skey->key.oid->id[0] );
/* вырабатываем подпись */
len = sizeof( encode );
if(( error = ak_tlv_encode( tbs, encode, &len )) != ak_error_ok ) {
ak_error_message( error, __func__, "incorrect encoding of tbsCertificate element" );
goto labex;
}
if(( error = ak_signkey_sign_ptr( issuer_skey, generator, encode,
len, out, sizeof( out ))) != ak_error_ok ) {
ak_error_message( error, __func__, "incorrect generation of digital signature" );
goto labex;
}
/* добавляем подпись в основное дерево */
bs.value = out;
bs.len = ak_signkey_get_tag_size( issuer_skey );
bs.unused = 0;
if(( error = ak_asn1_add_bit_string( tlv->data.constructed, &bs )) != ak_error_ok ) {
ak_error_message( error, __func__, "incorrect adding a digital signature value" );
goto labex;
}
return certificate;
labex: if( certificate != NULL ) certificate = ak_asn1_delete( certificate );
return NULL;
}
/* ----------------------------------------------------------------------------------------------- */
/*! Функция помещает информацию об открытом ключе в asn1 дерево, подписывает эту информацию,
помещает в это же asn1 дерево информацию о подписывающем лице и правилах применения ключа.
После этого сформированное дерево сохраняется в файл (сертификат открытого ключа)
в заданном пользователем формате.
\param subject_vkey контекст открытого ключа, который помещается в сертификат; контекст должен
содержать расширенное имя лица (subject), владеющего открытым ключом.
\param issuer_skey контекст секретного ключа, с помощью которого подписывается создаваемый сертификат;
\param issuer_vkey контекст открытого ключа, соответствующий секретному ключу подписи;
данный контекст используется для получения расширенного имени лица,
подписывающего сертификат (issuer), а также для проверки разрешений на использование сертификата.
\param generator генератор слечайных последовательностей, используемый для подписи сертификата.
\param opts набор опций, формирующих помещаемые в сертификат расширения
\param filename указатель на строку, содержащую имя файла, в который будет экспортирован ключ;
Если параметр `filename_size` отличен от нуля,
то указатель должен указывать на область памяти, в которую будет помещено сформированное имя файла.
\param size размер области памяти, в которую будет помещено имя файла.
Если размер области недостаточен, то будет возбуждена ошибка.
Данный параметр должен принимать значение 0 (ноль), если указатель `filename` указывает
на константную строку.
\param format формат, в котором сохраняются данные, допутимые значения
\ref asn1_der_format или \ref asn1_pem_format.
\return Функция возвращает \ref ak_error_ok (ноль) в случае успеха, в случае неудачи
возвращается код ошибки. */
/* ----------------------------------------------------------------------------------------------- */
int ak_verifykey_export_to_certificate( ak_verifykey subject_vkey,
ak_signkey issuer_skey, ak_verifykey issuer_vkey, ak_random generator,
ak_certificate_opts opts, char *filename, const size_t size, export_format_t format )
{
ak_mpzn256 serialNumber;
int error = ak_error_ok;
ak_asn1 certificate = NULL;
const char *file_extensions[] = { /* имена параметризуются значениями типа export_format_t */
"cer",
"crt"
};
/* необходимые проверки */
if( subject_vkey == NULL ) return ak_error_message( ak_error_null_pointer, __func__,
"using null pointer to subject's public key context" );
if( issuer_skey == NULL ) return ak_error_message( ak_error_null_pointer, __func__,
"using null pointer to issuer's secret key context" );
if( issuer_vkey == NULL ) return ak_error_message( ak_error_null_pointer, __func__,
"using null pointer to issuer's public key context" );
/* проверяем, что секретный ключ соответствует открытому */
if( memcmp( issuer_skey->verifykey_number, issuer_vkey->number, 32 ) != 0 )
return ak_error_message( ak_error_not_equal_data, __func__,
"the issuer's secret key does not correspond to the given public key" );
/* вырабатываем asn1 дерево */
if(( certificate = ak_verifykey_export_to_asn1_certificate(
subject_vkey, issuer_skey, issuer_vkey, generator, opts )) == NULL )
return ak_error_message( ak_error_get_value(), __func__,
"incorrect creation of asn1 context for certificate" );
/* формируем имя файла для хранения ключа
(данное имя в точности совпадает с номером ключа) */
if( size ) {
if( size < ( 5 + 2*sizeof( subject_vkey->number )) ) {
ak_error_message( error = ak_error_out_of_memory, __func__,
"insufficent buffer size for certificate filename" );
goto labex;
}
memset( filename, 0, size );
ak_verifykey_generate_certificate_serial_number( subject_vkey, issuer_skey, serialNumber );
ak_snprintf( filename, size, "%s.%s",
ak_mpzn_to_hexstr( serialNumber, ak_mpzn256_size ), file_extensions[format] );
}
/* сохраняем созданное дерево в файл */
if(( error = ak_asn1_export_to_file( certificate, filename,
format, public_key_certificate_content )) != ak_error_ok )
ak_error_message_fmt( error, __func__,
"incorrect export asn1 context to file %s in pem format", filename );
labex: if( certificate != NULL ) ak_asn1_delete( certificate );
return error;
}
/* ----------------------------------------------------------------------------------------------- */
/* Функции импорта открытых ключей из сертификата */
/* ----------------------------------------------------------------------------------------------- */
/*! \brief Функция импортирует базовую часть сертификата */
/* ----------------------------------------------------------------------------------------------- */
static int ak_verifykey_import_from_asn1_tbs_base( ak_verifykey subject_vkey,
ak_verifykey *issuer_vkey, ak_asn1 sequence , ak_certificate_opts opts,
ak_function_file_output verbose )
{
char message[512];
ak_pointer ptr = NULL;
int error = ak_error_ok;
time_t not_before, not_after;
ak_oid algoid = NULL, paroid = NULL;
ak_tlv subject_name = NULL;
/* 1. получаем версию сертификата */
ak_asn1_first( sequence );
if(( DATA_STRUCTURE( sequence->current->tag ) != CONSTRUCTED ) ||
( DATA_CLASS( sequence->current->tag ) != ( CONTEXT_SPECIFIC^0x00 ))) {
ak_error_message_fmt( error = ak_error_invalid_asn1_tag, __func__,
"incorrect tag value for certificate's version (tag: %x)", sequence->current->tag );
goto lab1;
}
else
if(( error = ak_tlv_get_uint32(
sequence->current->data.constructed->current, &opts->version )) != ak_error_ok ) {
ak_error_message( error, __func__, "incorrect reading of certificate's version" );
goto lab1;
}
if( verbose ) {
ak_snprintf( message, sizeof( message ), " Version: v%d\n", opts->version+1 );
verbose( message );
}
/* 2. определяем серийный номер сертификата (вырабатывается при подписи сертификата)
и помещаем его в структуру с опциями */
ak_asn1_next( sequence );
if(( DATA_STRUCTURE( sequence->current->tag ) != PRIMITIVE ) ||
( TAG_NUMBER( sequence->current->tag ) != TINTEGER )) {
ak_error_message_fmt( error = ak_error_invalid_asn1_tag, __func__,
"incorrect tag value for certificate's serial number (tag: %x)", sequence->current->tag );
goto lab1;
}
if(( ak_tlv_get_octet_string( sequence->current,
&ptr, &opts->serialnumlen ) != ak_error_ok ) || ( ptr == NULL )) {
ak_error_message( error, __func__, "incorrect reading of certificate's serial number" );
goto lab1;
} else {
memset( opts->serialnum, 0, sizeof( opts->serialnum ));
memcpy( opts->serialnum, ptr,
opts->serialnumlen = ak_min( opts->serialnumlen, sizeof( opts->serialnum )));
}
if( verbose ) {
ak_snprintf( message, sizeof( message ), " Serial number:\n %s\n",
ak_ptr_to_hexstr( opts->serialnum, opts->serialnumlen, ak_false ));
verbose( message );
}
/* 3. Получаем алгоритм подписи (oid секретного ключа) */
ak_asn1_next( sequence );
if(( error = ak_tlv_get_algorithm_identifier( sequence->current,
&algoid, &paroid )) != ak_error_ok ) {
ak_error_message( error, __func__, "incorrect reading of signature algorithm" );
goto lab1;
}
if( algoid->engine != sign_function ) {
ak_error_message( error = ak_error_oid_engine, __func__,
"the certificate has incorrect or unsupported signature algorithm identifier" );
goto lab1;
}
if( verbose ) {
ak_snprintf( message, sizeof( message ), " Algorithm:\n %s", algoid->name[0] );
verbose( message );
if( paroid != NULL ) {
ak_snprintf( message, sizeof( message ), " (params: %s)\n", paroid->name[0] );
verbose( message );
}
else verbose( "\n" );
}
/* 4. Получаем имя эмитента (лица подписавшего сертификат)
и сравниваем с тем, что у нас есть (если сертификат был создан ранее)
иначе просто присваиваем имя в контекст */
ak_asn1_next( sequence );
if(( DATA_STRUCTURE( sequence->current->tag ) != CONSTRUCTED ) ||
( TAG_NUMBER( sequence->current->tag ) != TSEQUENCE )) {
ak_error_message_fmt( error = ak_error_invalid_asn1_tag, __func__,
"unexpected tag value for generalized name of certificate's issuer (tag: %x)",
sequence->current->tag );
goto lab1;
}
if( *issuer_vkey != NULL ) { /* в функцию передан созданный ранее открытый ключ проверки подписи,
поэтому мы должны проверить совпадение имен, т.е. то,
что переданный ключ совпадает с тем, что был использован
при подписи сертификата */
if( ak_tlv_compare_global_names( sequence->current, (*issuer_vkey)->name ) != ak_error_ok ) {
error = ak_error_certificate_verify_names;
goto lab1;
}
}
if( verbose ) {
verbose(" Issuer:\n");
ak_tlv_snprintf_global_name( sequence->current, message, sizeof( message ));
verbose( message ); verbose( "\n" );
}
// opts->issuer_name = ak_tlv_duplicate_global_name( sequence->current );
/* 5. Получаем интервал времени действия */
ak_asn1_next( sequence );
if(( error = ak_tlv_get_validity( sequence->current,
¬_before, ¬_after )) != ak_error_ok ) {
ak_error_message( error, __func__, "incorrect reading a validity value from asn1 context" );
goto lab1;
}
if( verbose ) {
#ifdef AK_HAVE_WINDOWS_H
ak_snprintf( message, sizeof( message ), " Validity:\n from: %s\n", ctime( ¬_before ));
verbose( message );
ak_snprintf( message, sizeof( message ), " to: %s\n", ctime( ¬_after ));
verbose( message );
#else
char output_buffer[128];
strftime( output_buffer, sizeof( output_buffer ), /* локализованный вывод */
"%e %b %Y %H:%M:%S (%A) %Z", localtime( ¬_before ));
ak_snprintf( message, sizeof( message ), " Validity:\n from: %s\n", output_buffer );
verbose( message );
strftime( output_buffer, sizeof( output_buffer ), /* локализованный вывод */
"%e %b %Y %H:%M:%S (%A) %Z", localtime( ¬_after ));
ak_snprintf( message, sizeof( message ), " to: %s\n", output_buffer );
verbose( message );
#endif
}
/* 6. Получаем имя владельца импортируемого ключа */
ak_asn1_next( sequence );
if(( DATA_STRUCTURE( sequence->current->tag ) != CONSTRUCTED ) ||
( TAG_NUMBER( sequence->current->tag ) != TSEQUENCE )) {
ak_error_message_fmt( error = ak_error_invalid_asn1_tag, __func__,
"unexpected tag value for generalized name of certificate's subject (tag: %x)",
sequence->current->tag );
goto lab1;
}
subject_name = ak_tlv_duplicate_global_name( sequence->current );
if( verbose ) {
verbose(" Subject:\n");
ak_tlv_snprintf_global_name( sequence->current, message, sizeof( message ));
verbose( message ); verbose( "\n" );
}
/* 7. Получаем значение открытого ключа */
if( ak_asn1_next( sequence ) != ak_true ) {
ak_error_message( ak_error_invalid_asn1_count, __func__, "unexpected end of asn1 tree" );
goto lab1;
}
/* проверяем наличие последовательности верхнего уровня */
if(( DATA_STRUCTURE( sequence->current->tag ) != CONSTRUCTED ) ||
( TAG_NUMBER( sequence->current->tag ) != TSEQUENCE ))
return ak_error_message( ak_error_invalid_asn1_tag, __func__ ,
"the element of root asn1 tree must be a sequence with object identifiers" );
if(( error = ak_verifykey_import_from_asn1_value( subject_vkey,
sequence->current->data.constructed, verbose )) != ak_error_ok ) {
ak_error_message( error, __func__, "incorrect import of public key value" );
goto lab1;
}
/* присваиваем значения полей */
subject_vkey->name = subject_name;
subject_vkey->time.not_after = not_after;
subject_vkey->time.not_before = not_before;
opts->created = ak_true;
lab1:
if( !opts->created ) {
if( subject_vkey != NULL ) ak_tlv_delete( subject_name );
}
return error;
}
/* ----------------------------------------------------------------------------------------------- */
/*! \brief Функция импортирует в секретный ключ расширения сертификата и определяет открытый ключ
для проверки */
/* ----------------------------------------------------------------------------------------------- */
static int ak_verifykey_import_from_asn1_extensions( ak_verifykey subject_vkey,
ak_verifykey *issuer_vkey, ak_asn1 sequence, ak_certificate_opts opts,
ak_function_file_output verbose )
{
size_t size = 0;
char message[256];
ak_oid oid = NULL;
ak_pointer ptr = NULL;
int error = ak_error_ok;
if(( DATA_STRUCTURE( sequence->current->tag ) != CONSTRUCTED ) ||
( TAG_NUMBER( sequence->current->tag ) != TSEQUENCE ))
return ak_error_message( ak_error_invalid_asn1_tag, __func__,
"incorrect asn1 tree for certificate's extensions" );
else ak_asn1_first( sequence = sequence->current->data.constructed ); /* все расширения здесь */
if( sequence->count == 0 ) goto lab1;
if( verbose ) verbose(" Extensions:\n");
/* -- часть кода, отвечающая за разбор расширений сертификата */
do{
ak_asn1 ext = NULL, vasn = NULL;
if(( DATA_STRUCTURE( sequence->current->tag ) != CONSTRUCTED ) ||
( TAG_NUMBER( sequence->current->tag ) != TSEQUENCE )) continue;
ak_asn1_first( ext = sequence->current->data.constructed ); /* текущее расширение */
if(( DATA_STRUCTURE( ext->current->tag ) != PRIMITIVE ) ||
( TAG_NUMBER( ext->current->tag ) != TOBJECT_IDENTIFIER )) continue;
if( ak_tlv_get_oid( ext->current, &ptr ) != ak_error_ok ) continue;
if(( oid = ak_oid_find_by_id( ptr )) == NULL ) continue;
ak_asn1_last( ext ); /* перемещаемся к данным */
/* теперь мы разбираем поступившие расширения */
/* ----------------------------------------------------------------------------------------- */
if( strcmp( oid->id[0], "2.5.29.14" ) == 0 ) { /* это subjectKeyIdentifier,
т.е. номер считываемого открытого ключа */
if(( DATA_STRUCTURE( ext->current->tag ) != PRIMITIVE ) ||
( TAG_NUMBER( ext->current->tag ) != TOCTET_STRING )) continue;
/* декодируем номер ключа */
opts->subjkey.is_present = ak_true;
ak_tlv_get_octet_string( ext->current, &ptr, &size );
memcpy( subject_vkey->number, ((ak_uint8 *)ptr)+2,
opts->subjkey.length = ak_min( 32, size-2 ));
if( verbose ) {
ak_snprintf( message, sizeof( message ), " x509v3 Subject Key Identifier:\n %s\n",
ak_ptr_to_hexstr( subject_vkey->number, opts->subjkey.length, ak_false ));
verbose( message );
}
}
/* ----------------------------------------------------------------------------------------- */
if( strcmp( oid->id[0], "2.5.29.19" ) == 0 ) { /* это basicConstraints
т.е. принадлежность центрам сертификации */
opts->ca.is_present = ak_true;
if(( DATA_STRUCTURE( ext->current->tag ) != PRIMITIVE ) ||
( TAG_NUMBER( ext->current->tag ) != TOCTET_STRING )) continue;
ak_tlv_get_octet_string( ext->current, &ptr, &size );
/* теперь разбираем поля */
if( ak_asn1_decode( vasn = ak_asn1_new(), ptr, size, ak_false ) == ak_error_ok ) {
if(( DATA_STRUCTURE( vasn->current->tag ) == CONSTRUCTED ) ||
( TAG_NUMBER( vasn->current->tag ) != TSEQUENCE )) {
ak_asn1 vasn2 = vasn->current->data.constructed;
if( vasn2->current != NULL ) {
ak_asn1_first( vasn2 );
if(( DATA_STRUCTURE( vasn2->current->tag ) == PRIMITIVE ) &&
( TAG_NUMBER( vasn2->current->tag ) == TBOOLEAN )) {
ak_tlv_get_bool( vasn2->current, &opts->ca.value );
}
if( ak_asn1_next( vasn2 ) ) {
if(( DATA_STRUCTURE( vasn2->current->tag ) != PRIMITIVE ) &&
( TAG_NUMBER( vasn2->current->tag ) != TINTEGER ))
ak_tlv_get_uint32( vasn2->current, &opts->ca.pathlenConstraint );
}
}
}
if( verbose ) {
ak_snprintf( message, sizeof( message ),
" x509v3 Basic Constraints:\n ca: %s, pathlen: %d\n",
( opts->ca.value ? "true" : "false" ), opts->ca.pathlenConstraint );
verbose( message );
}
}
if( vasn ) ak_asn1_delete( vasn );
}
/* ----------------------------------------------------------------------------------------- */
if( strcmp( oid->id[0], "2.5.29.15" ) == 0 ) { /* это keyUsage
т.е. область применения сертификата */
opts->key_usage.is_present = ak_true;
if(( DATA_STRUCTURE( ext->current->tag ) != PRIMITIVE ) ||
( TAG_NUMBER( ext->current->tag ) != TOCTET_STRING )) continue;
/* декодируем битовую последовательность */
ak_tlv_get_octet_string( ext->current, &ptr, &size );
if( ak_asn1_decode( vasn = ak_asn1_new(), ptr, size, ak_false ) == ak_error_ok ) {
if(( DATA_STRUCTURE( vasn->current->tag ) == PRIMITIVE ) &&
( TAG_NUMBER( vasn->current->tag ) == TBIT_STRING )) {
struct bit_string bs;
ak_tlv_get_bit_string( vasn->current, &bs );
opts->key_usage.bits = bs.value[0]; /* TODO: это фрагмент необходимо оттестировать */
opts->key_usage.bits <<= 1;
if( bs.len > 1 ) {
opts->key_usage.bits <<= 8-bs.unused;
opts->key_usage.bits ^= bs.value[1];
}
}
if( verbose ) {
verbose(" x509v3 Basic Usage:\n " );
if( opts->key_usage.bits&bit_decipherOnly) verbose( "Decipher " );
if( opts->key_usage.bits&bit_encipherOnly) verbose("Encipher ");
if( opts->key_usage.bits&bit_cRLSign) verbose("CRL sign ");
if( opts->key_usage.bits&bit_keyCertSign) verbose("Certificate sign, ");
if( opts->key_usage.bits&bit_keyAgreement) verbose("Key agreement ");
if( opts->key_usage.bits&bit_dataEncipherment) verbose("Data encipherment ");
if( opts->key_usage.bits&bit_keyEncipherment) verbose("Key encipherment ");
if( opts->key_usage.bits&bit_contentCommitment) verbose("Content commitment ");
if( opts->key_usage.bits&bit_digitalSignature) verbose("Digital signature");
verbose("\n");
}
}
else opts->key_usage.bits = 0;
if( vasn ) ak_asn1_delete( vasn );
}
/* ----------------------------------------------------------------------------------------- */
if( strcmp( oid->id[0], "2.5.29.35" ) == 0 ) { /* это authorityKeyIdentifier
т.е. номера ключа проверки */
if(( DATA_STRUCTURE( ext->current->tag ) != PRIMITIVE ) ||
( TAG_NUMBER( ext->current->tag ) != TOCTET_STRING )) continue;
ak_tlv_get_octet_string( ext->current, &ptr, &size );
if( ak_asn1_decode( vasn = ak_asn1_new(), ptr, size, ak_false ) == ak_error_ok ) {
/* здесь мы должны иметь последовательность, примерно, такого вида
└SEQUENCE┐
├[0] 8b983b891851e8ef9c0278b8eac8d420b255c95d
├[1]┐
│ └[4]┐
│ └SEQUENCE┐
│ ├SET┐
│ │ └SEQUENCE┐
│ │ ├OBJECT IDENTIFIER 1.2.840.113549.1.9.1 (email-address)
│ │ └IA5 STRING dit@minsvyaz.ru
└[2] 34681e40cb41ef33a9a0b7c876929a29
где
- [0] - номер открытого ключа, используемого для проверки подписи
(в openssl для самоподписанных сертификатов совпадает с SubjectKeyIdentifer (vkey->number)
- [1] - расширенное имя владельца
- [2] - номер сертификата открытого ключа, используемого для проверки подписи
может быть конечно не все, например, у корневого сертификата ГУЦ нет этого расширения */
ak_asn1 lasn = NULL;
if(( DATA_STRUCTURE( vasn->current->tag ) != CONSTRUCTED ) ||
( TAG_NUMBER( vasn->current->tag ) != TSEQUENCE )) {
ak_error_message( ak_error_invalid_asn1_tag, __func__,
"incorrect asn1 tree for authorithyKeyIdentifier extension" );
goto labstop;
}
lasn = vasn->current->data.constructed;
opts->authoritykey.is_present = ak_true;
if( verbose ) verbose(" x509v3 Authority Key Identifier:\n" );
ak_asn1_first( lasn );
do{
if(( DATA_STRUCTURE( lasn->current->tag ) == CONSTRUCTED ) ||
(( DATA_CLASS( lasn->current->tag )) == CONTEXT_SPECIFIC )) {
switch( TAG_NUMBER( lasn->current->tag )) {
case 0x00:
if( verbose ) {
ak_snprintf( message, sizeof( message ), " %s (unique key number)\n",
ak_ptr_to_hexstr( lasn->current->data.primitive, lasn->current->len, ak_false ));
verbose( message );
}
if( *issuer_vkey == NULL ) {
/* в данной ситуации ключ проверки подписи не известен.
поскольку мы можем считывать из файла и искать только ключи по серийным номерам,
то использовать данный номер мы можем только для проверки того, что сертификат
является самоподписанным т.е. subject_key.number =? lasn->current->data.primitive */
if( memcmp( lasn->current->data.primitive,
subject_vkey->number, lasn->current->len ) == 0 ) {
*issuer_vkey = subject_vkey; /* ключ проверки совпадает с ключом в сертификате */
}
}
break;
case 0x01:
break;
case 0x02:
if( verbose ) {
ak_snprintf( message, sizeof( message ), " %s (serial number)\n",
ak_ptr_to_hexstr( lasn->current->data.primitive, lasn->current->len, ak_false ));
verbose( message );
}
break;
default:
break;
}
}
} while( ak_asn1_next( lasn ));
labstop:;
}
if( vasn ) ak_asn1_delete( vasn );
}
/* ----------------------------------------------------------------------------------------- */
} while( ak_asn1_next( sequence )); /* конец цикла перебора расширений */
lab1:
return error;
}
/* ----------------------------------------------------------------------------------------------- */
/*! \brief Функция импортирует в секретный ключ значения, содержащиеся
в последовательности TBSCerfificate */
/* ----------------------------------------------------------------------------------------------- */
static int ak_verifykey_import_from_asn1_tbs( ak_verifykey subject_vkey,
ak_verifykey *issuer_vkey, ak_tlv tbs , ak_certificate_opts opts,
ak_function_file_output verbose )
{
ak_asn1 sequence = NULL;
int error = ak_error_ok;
if( verbose ) verbose(" Type:\n Public Key Certificate\n");
/* считываем основные поля сертификата, определеные для версий 1 или 2. */
if(( error = ak_verifykey_import_from_asn1_tbs_base( subject_vkey,
issuer_vkey, sequence = tbs->data.constructed, opts, verbose )) != ak_error_ok ) {
return ak_error_message( error, __func__, "incorrect loading a base part of certificate" );
}
/* пропускаем поля второй версии и переходим к третьей версии, а именно, к расширениям.
поля расширений должны нам разъяснить, является ли данный ключ самоподписанным или нет.
если нет, и issuer_vkey не определен, то мы должны считать его с диска */
ak_asn1_last( sequence );
if( opts->version != 2 ) return error; /* нам достался сертификат версии один или два */
/* проверяекм узел */
if(( DATA_STRUCTURE( sequence->current->tag ) != CONSTRUCTED ) ||
(( DATA_CLASS( sequence->current->tag )) != CONTEXT_SPECIFIC ) ||
( TAG_NUMBER( sequence->current->tag ) != 0x3 )) {
return ak_error_message_fmt( ak_error_invalid_asn1_tag, __func__,
"incorrect tag value for certificate extensions (tag: %x)", sequence->current->tag );
}
/* считываем доступные расширения сертификата */
if(( error = ak_verifykey_import_from_asn1_extensions( subject_vkey,
issuer_vkey, sequence->current->data.constructed, opts, verbose )) != ak_error_ok )
ak_error_message( error, __func__, "incorrect loading a certificate's extensions" );
return error;
}
/* ----------------------------------------------------------------------------------------------- */
/*! \brief Считывание открытого ключа из сертификата, представленного в виде ASN.1 дерева.
Функция выполняет основные действия по проверке электронной подписи
под импортируемым сертификатом.
\param subject_vkey контекст создаваемого открытого ключа асимметричного криптографического
алгоритма
\param issuer_vkey открытый ключ, с помощью которого можно проверить подпись под сертификатом;
может принимать значение `NULL`
\param root asn1 дерево, содержащее сертификат создаваемого открытого ключа
\param opts структура, в которую помещаются параметры созданного открытого ключа
\return Функция возвращает \ref ak_error_ok (ноль) в случае успеха, в случае неудачи
возвращается код ошибки. */
/* ----------------------------------------------------------------------------------------------- */
static int ak_verifykey_import_from_asn1_certificate( ak_verifykey subject_vkey,
ak_verifykey issuer_vkey, ak_asn1 root, ak_certificate_opts opts,
ak_function_file_output verbose )
{
size_t size = 0;
ak_tlv tbs = NULL;
ak_asn1 lvs = NULL;
struct bit_string bs;
ak_uint8 buffer[4096];
int error = ak_error_ok;
time_t now = time( NULL );
ak_verifykey vkey = issuer_vkey;
if( subject_vkey == NULL ) return ak_error_message( ak_error_null_pointer, __func__,
"using null pointer to secret key context" );
/* 1. проверяем устройство asn1 дерева */
if( root->count != 1 ) {
/* здесь мы проверяем, что это сертификат, а не коллекция сертификатов, т.е.
asn1 дерево содержит только 1 элемент верхнего уровня */
ak_error_message( error = ak_error_invalid_asn1_count, __func__,
"unexpected count of top level elements (certificates)" );
goto lab1;
}
if(( DATA_STRUCTURE( root->current->tag ) != CONSTRUCTED ) ||
( TAG_NUMBER( root->current->tag ) != TSEQUENCE )) {
/* здесь мы проверили, что внутри находится sequence */
ak_error_message_fmt( error = ak_error_invalid_asn1_tag, __func__ ,
"unexpected type of certificate's container (tag: %x)", root->current->tag );
goto lab1;
} else lvs = root->current->data.constructed;
if( lvs->count != 3 ) {
/* здесь мы проверяем, что это последовательность из трех элементов
- tbs
- параметры подписи
- собственно сама подпись */
ak_error_message_fmt( error = ak_error_invalid_asn1_count, __func__,
"incorrect count of top level certificate elements (value: %u, must be: 3)",
(unsigned int) lvs->count );
goto lab1;
}
/* 2. считываем информацию о ключе из tbsCertificate */
ak_asn1_first( lvs );
tbs = lvs->current;
if(( DATA_STRUCTURE( tbs->tag ) != CONSTRUCTED ) ||
( TAG_NUMBER( tbs->tag ) != TSEQUENCE )) {
/* здесь мы проверили, что внутри находится sequence */
ak_error_message_fmt( error = ak_error_invalid_asn1_tag, __func__ ,
"unexpected type of TBSCertificate's container (tag: %x)", root->current->tag );
goto lab1;
}
/* устанавливаем флаг, что ключ не создан, и переходим к его созданию */
opts->created = ak_false;
if(( error = ak_verifykey_import_from_asn1_tbs( subject_vkey,
&vkey, tbs, opts, verbose )) != ak_error_ok ) {
if( opts->created )
ak_error_message( error, __func__, "incorrect validating of TBSCertificate's parameters");
else ak_error_message( error, __func__ ,
"incorrect decoding of TBSCertificate's asn1 container" );
goto lab1;
}
if( !opts->created ) {
ak_error_message( error = ak_error_undefined_function, __func__ ,
"incorrect import TBSCertificate from asn1 container" );
goto lab1;
}
/* 3. проверяем валидность сертификата */
/* 3.1 - наличие ключа проверки */
if( vkey == NULL ) {
ak_error_message( error = ak_error_certificate_verify_key, __func__,
"using an undefined public key to verify a given certificate" );
goto lab1;
}
/* 3.2 - проверяем срок действия сертификата */
if(( subject_vkey->time.not_before > now ) || ( subject_vkey->time.not_after < now )) {
ak_error_message( ak_error_certificate_validity, __func__,
"the certificate has expired (the current time is not within the specified bounds)" );
goto lab1;
}
/* 3.3 - теперь ничего не остается, как проверять подпись под сертификатом
3.3.1 - начинаем с того, что готовим данные, под которыми должна быть проверена подпись */
memset( buffer, 0, size = sizeof( buffer ));
ak_asn1_first( lvs );
if(( error = ak_tlv_encode( lvs->current, buffer, &size )) != ak_error_ok ) {
ak_error_message_fmt( error, __func__,
"incorrect encoding of tlv context contains of %u octets", (unsigned int) size );
goto lab1;
}
/* 3.3.2 - теперь получаем значение подписи из asn1 дерева и сравниваем его с вычисленным значением */
ak_asn1_last( lvs );
if(( DATA_STRUCTURE( lvs->current->tag ) != PRIMITIVE ) ||
( TAG_NUMBER( lvs->current->tag ) != TBIT_STRING )) {
ak_error_message( error = ak_error_invalid_asn1_tag, __func__ ,
"the second element of child asn1 context must be a bit string" );
goto lab1;
}
if(( error = ak_tlv_get_bit_string( lvs->current, &bs )) != ak_error_ok ) {
ak_error_message( error , __func__ , "incorrect value of bit string in root asn1 context" );
goto lab1;
}
/* 3.3.3 - только сейчас проверяем подпись под данными */
if( ak_verifykey_verify_ptr( vkey, buffer, size, bs.value ) != ak_true ) {
ak_error_message( error = ak_error_not_equal_data, __func__, "digital signature isn't valid" );
goto lab1;
}
/* 4. если открытый ключ проверки подписи был создан в ходе работы функции, его надо удалить */
lab1:
if( vkey != NULL ) {
if(( vkey != issuer_vkey ) && ( vkey != subject_vkey ))
ak_oid_delete_object( vkey->oid, vkey ); /* здесь мы ожидаем, что ключ, созданный
в процессе выполнения функции, был размещен в куче */
}
return error;
}
/* ----------------------------------------------------------------------------------------------- */
/*! Функция считывает из заданного файла `filename` сертификат открытого ключа,
хранящийся в виде asn1 дерева, определяемого Р 1323565.1.023-2018.
Собственно asn1 дерево может быть храниться в файле в виде обычной der-последовательности,
либо в виде der-последовательности, дополнительно закодированной в `base64` (формат `pem`).
Функция является конструктором контекста `subject_vkey`.
После считывания asn1 дерева функция проверяет подпись под сертификатом открытого ключа и,
в случае успешной проверки, создает контекст `subject_vkey` и инициирует его необходимыми
значениями.
Ключ проверки сертификата должен быть предварительно создан и передаватьсяс помощью
указателя `issuer_vkey` (если номер сертификата проверки подписи или расширенное имя владельца
не совпадают с тем, что содержится в issuer_vkey, то возбуждается ошибка)
Если указатель `issuer_vkey` равен `NULL`, то функция ищет сертифкат с соответствующим серийным
номером в устанавливаемом библиотекой `libakrypt` каталоге; данный каталог указывается при сборке
библотеки из исходных текстов в параметре `AK_CA_PATH`; для unix-like систем значением по
умолчанию является каталог `\usr\share\ca-certificates\libakrypt`.
\note В случае если проверка валидности сертификата не выполнена и функция возвращает ошибку,
значение флага `opts.created` позволят определить, создан ли контекст открытого ключа и
нужно ли в дальнейшем производить его удаление.
\param vkey контекст создаваемого открытого ключа асимметричного криптографического алгоритма,
параметры которого считываются из файла `filename`
\param issuer_vkey открытый ключ, с помощью которого можно проверить подпись под сертификатом;
может принимать значение `NULL`
\param filename имя файла, из которого считываются значения параметров открытого ключа
\param opts структура, в которую помещаются параметры созданного открытого ключа
\return Функция возвращает \ref ak_error_ok (ноль) в случае успеха, в случае неудачи
возвращается код ошибки. */
/* ----------------------------------------------------------------------------------------------- */
int ak_verifykey_import_from_certificate( ak_verifykey subject_vkey, ak_verifykey issuer_vkey,
const char *filename, ak_certificate_opts opts, ak_function_file_output verbose )
{
ak_asn1 root = NULL;
int error = ak_error_ok;
/* стандартные проверки */
if( filename == NULL ) return ak_error_message( ak_error_null_pointer, __func__,
"using null pointer to filename" );
if( ak_certificate_opts_create( opts ) != ak_error_ok )
return ak_error_message( ak_error_null_pointer, __func__,
"using null pointer to context with subject's public key options" );
/* считываем ключ и преобразуем его в ASN.1 дерево */
if(( error = ak_asn1_import_from_file( root = ak_asn1_new(), filename )) != ak_error_ok ) {
ak_error_message_fmt( error, __func__,
"incorrect reading of ASN.1 context from %s file", filename );
goto lab1;
}
/* собственно выполняем считывающее преобразование */
if(( error = ak_verifykey_import_from_asn1_certificate( subject_vkey,
issuer_vkey, root, opts, verbose )) != ak_error_ok ) {
ak_error_message( error, __func__, "wrong import of public key from asn.1 context" );
}
lab1: if( root != NULL ) ak_asn1_delete( root );
return error;
}
/* ----------------------------------------------------------------------------------------------- */
/*! Функция предполагает, что в области памяти `ptr` располагается сертификат открытого ключа,
записанныей в der-кодировке.
Причина использования даной фукции заключается в раскодировании сертификатов,
передаваемых в ходе выполнения криптографических протоколов, и считываемых, вместе с
другими данными, в оперативную память.
Поведение и возвращаетмые значения функции аналогичны поведению и возвращаемым
значениям функции ak_verifykey_import_from_certificate().
\param vkey контекст создаваемого открытого ключа асимметричного криптографического алгоритма,
параметры которого считываются из файла `filename`
\param issuer_vkey открытый ключ, с помощью которого можно проверить подпись под сертификатом;
может принимать значение `NULL`
\param указатель на область памяти, в которой распологается сертификат открытого ключа
\param size размер сертификата (в октетах)
\return Функция возвращает \ref ak_error_ok (ноль) в случае успеха, в случае неудачи
возвращается код ошибки. */
/* ----------------------------------------------------------------------------------------------- */
int ak_verifykey_import_from_ptr_as_certificate( ak_verifykey subject_vkey,
ak_verifykey issuer_vkey, const ak_pointer ptr, const size_t size,
ak_certificate_opts opts, ak_function_file_output verbose )
{
ak_asn1 root = NULL;
int error = ak_error_ok;
/* стандартные проверки */
if(( ptr == NULL ) || ( size == 0 ))
return ak_error_message( ak_error_null_pointer, __func__,
"using null pointer or zero length data with certificate" );
if( ak_certificate_opts_create( opts ) != ak_error_ok )
return ak_error_message( ak_error_null_pointer, __func__,
"using null pointer to context with subject's public key options" );
/* считываем ключ и преобразуем его в ASN.1 дерево */
if(( error = ak_asn1_decode( root = ak_asn1_new(), ptr, size, ak_false )) != ak_error_ok ) {
ak_error_message_fmt( error, __func__, "incorrect decoding of ASN.1 context from data buffer");
goto lab1;
}
/* собственно выполняем считывающее преобразование */
if(( error = ak_verifykey_import_from_asn1_certificate( subject_vkey,
issuer_vkey, root, opts, verbose )) != ak_error_ok ) {
ak_error_message( error, __func__, "wrong import of public key from asn.1 context" );
}
lab1: if( root != NULL ) ak_asn1_delete( root );
return error;
}
/* ----------------------------------------------------------------------------------------------- */
/* ak_asn1_cert.c */
/* ----------------------------------------------------------------------------------------------- */
| 50.300853 | 108 | 0.599475 | [
"object"
] |
6b5217a661951aeb6150ccefb031bee056f3b725 | 2,224 | h | C | MUON/MUONcalib/AliMUONCalibParamNF.h | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | MUON/MUONcalib/AliMUONCalibParamNF.h | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | MUON/MUONcalib/AliMUONCalibParamNF.h | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | /* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* See cxx source for full Copyright notice */
// $Id$
/// \ingroup calib
/// \class AliMUONCalibParamNF
/// \brief Implementation of AliMUONVCalibParam for tuples of floats
///
// Author Laurent Aphecetche
#ifndef ALIMUONCALIBPARAMNF_H
#define ALIMUONCALIBPARAMNF_H
#ifndef ALIMUONVCALIBPARAM_H
# include "AliMUONVCalibParam.h"
#endif
class AliMUONCalibParamNF : public AliMUONVCalibParam
{
public:
AliMUONCalibParamNF();
AliMUONCalibParamNF(Int_t dimension, Int_t theSize, Int_t id0, Int_t id1, Float_t fillWithValue=0);
AliMUONCalibParamNF(const AliMUONCalibParamNF& other);
AliMUONCalibParamNF& operator=(const AliMUONCalibParamNF& other);
virtual ~AliMUONCalibParamNF();
/// Own clone methods (as the default TObject::Clone turned out to be pretty slow !)
virtual TObject* Clone(const char* = "") const { return new AliMUONCalibParamNF(*this); }
/// Return dimension
virtual Int_t Dimension() const { return fDimension; }
virtual void Print(Option_t* opt="") const;
virtual void SetValueAsFloat(Int_t i, Int_t j, Float_t value);
virtual void SetValueAsFloatFast(Int_t i, Int_t j, Float_t value);
virtual void SetValueAsInt(Int_t i, Int_t j, Int_t value);
virtual void SetValueAsIntFast(Int_t i, Int_t j, Int_t value);
/// Return size - the number of float pair we hold
virtual Int_t Size() const { return fSize; }
virtual Float_t ValueAsFloat(Int_t i, Int_t j=0) const;
virtual Float_t ValueAsFloatFast(Int_t i, Int_t j=0) const;
virtual Int_t ValueAsInt(Int_t i, Int_t j=0) const;
virtual Int_t ValueAsIntFast(Int_t i, Int_t j=0) const;
private:
void CopyTo(AliMUONCalibParamNF& destination) const;
Int_t Index(Int_t i, Int_t j) const;
Int_t IndexFast(Int_t i, Int_t j) const;
private:
Int_t fDimension; ///< dimension of this object
Int_t fSize; ///< The number of float pair we hold
Int_t fN; ///< The total number of floats we hold (fDimension*fSize)
/// The values array
Float_t* fValues; //[fN] The values array
ClassDef(AliMUONCalibParamNF,3) // Container for calibration parameters
};
#endif
| 31.771429 | 101 | 0.72482 | [
"object"
] |
6b681f366fa898f0c413787fa98a8da004f5dc5b | 5,707 | h | C | src/ext/cvc4-1.6-build/include/cvc4/printer/sygus_print_callback.h | bchurchill/pldi19-equivalence-checker | 2e7707be99c10828970f1d96c2bcbb058936cbdc | [
"ECL-2.0",
"Apache-2.0"
] | 30 | 2019-03-14T04:17:34.000Z | 2022-03-29T21:54:21.000Z | src/ext/cvc4-1.6-build/include/cvc4/printer/sygus_print_callback.h | bchurchill/pldi19-equivalence-checker | 2e7707be99c10828970f1d96c2bcbb058936cbdc | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | src/ext/cvc4-1.6-build/include/cvc4/printer/sygus_print_callback.h | bchurchill/pldi19-equivalence-checker | 2e7707be99c10828970f1d96c2bcbb058936cbdc | [
"ECL-2.0",
"Apache-2.0"
] | 7 | 2019-07-26T17:43:39.000Z | 2020-04-28T16:16:10.000Z | /********************* */
/*! \file sygus_print_callback.h
** \verbatim
** Top contributors (to current version):
** Andrew Reynolds, Haniel Barbosa
** This file is part of the CVC4 project.
** Copyright (c) 2009-2018 by the authors listed in the file AUTHORS
** in the top-level source directory) and their institutional affiliations.
** All rights reserved. See the file COPYING in the top-level source
** directory for licensing information.\endverbatim
**
** \brief sygus print callback functions
**/
#include <cvc4/cvc4_public.h>
#ifndef __CVC4__PRINTER__SYGUS_PRINT_CALLBACK_H
#define __CVC4__PRINTER__SYGUS_PRINT_CALLBACK_H
#include <vector>
#include <cvc4/expr/datatype.h>
#include <cvc4/expr/expr.h>
namespace CVC4 {
namespace printer {
/** sygus expression constructor printer
*
* This class is used for printing sygus datatype constructor terms whose top
* symbol is an expression, such as a custom defined lambda. For example, for
* sygus grammar:
* A -> (+ x A B) | x | y
* B -> 0 | 1
* The first constructor, call it C_f for A takes two arguments (A, B) and has
* sygus operator
* (lambda ((z Int) (w Int)) (+ x z w))
* For this operator, we set a print callback that prints, e.g. the term
* C_f( t1, t2 )
* is printed as:
* "(+ x [out1] [out2])"
* where out1 is the result of p->toStreamSygus(out,t1) and
* out2 is the result of p->toStreamSygus(out,t2).
*/
class CVC4_PUBLIC SygusExprPrintCallback : public SygusPrintCallback
{
public:
SygusExprPrintCallback(Expr body, std::vector<Expr>& args);
~SygusExprPrintCallback() {}
/** print sygus term e on output out using printer p */
virtual void toStreamSygus(const Printer* p,
std::ostream& out,
Expr e) const override;
protected:
/** body of the sygus term */
Expr d_body;
/** arguments */
std::vector<Expr> d_args;
/** body argument */
int d_body_argument;
/** do string replace
*
* Replaces all occurrences of oldStr with newStr in str.
*/
void doStrReplace(std::string& str,
const std::string& oldStr,
const std::string& newStr) const;
};
/** sygus let expression constructor printer
*
* This class is used for printing sygus
* datatype constructor terms whose top symbol
* is a let expression.
* For example, for grammar:
* A -> (let ((x B)) (+ A 1)) | x | (+ A A) | 0
* B -> 0 | 1
* the first constructor for A takes as arguments
* (B,A) and has sygus operator
* (lambda ((y Int) (z Int)) (+ z 1))
* CVC4's support for let expressions in grammars
* is highly limited, since notice that the
* argument y : B is unused.
*
* For the above constructor, we have that
* d_let_body is (+ z 1),
* d_sygus_let_args is { y, z },
* d_sygus_num_let_input_args is 1, since
* y is an original input argument of the
* let expression, but z is not.
*/
class CVC4_PUBLIC SygusLetExprPrintCallback : public SygusExprPrintCallback
{
public:
SygusLetExprPrintCallback(Expr let_body,
std::vector<Expr>& let_args,
unsigned ninput_args);
~SygusLetExprPrintCallback() {}
/** print sygus term e on output out using printer p */
virtual void toStreamSygus(const Printer* p,
std::ostream& out,
Expr e) const override;
private:
/** number of arguments that are interpreted as input arguments */
unsigned d_num_let_input_args;
};
/** sygus named constructor printer
*
* This callback is used for explicitly naming
* the builtin term that a sygus datatype constructor
* should be printed as. This is used for printing
* terms in sygus grammars that involve defined
* functions. For example, for grammar :
* A -> f( A ) | 0
* where f is defined as:
* (define-fun ((x Int)) Int (+ x 1))
* this class can be used as a callback for printing
* the first sygus datatype constructor f, where we use
* analog operator (lambda (x) (+ x 1)).
*/
class CVC4_PUBLIC SygusNamedPrintCallback : public SygusPrintCallback
{
public:
SygusNamedPrintCallback(std::string name);
~SygusNamedPrintCallback() {}
/** print sygus term e on output out using printer p */
virtual void toStreamSygus(const Printer* p,
std::ostream& out,
Expr e) const override;
private:
/** the defined function name */
std::string d_name;
};
/** sygus empty printer
*
* This callback is used for printing constructors whose operators are
* implicit, such as identity functions. For example, for grammar :
* A -> B
* B -> x | 0 | 1
* The first constructor of A, call it cons, has sygus operator (lambda (x) x).
* Call toStreamSygus on cons( t ) should call toStreamSygus on t directly.
*/
class CVC4_PUBLIC SygusEmptyPrintCallback : public SygusPrintCallback
{
public:
SygusEmptyPrintCallback() {}
~SygusEmptyPrintCallback() {}
/** print sygus term e on output out using printer p */
virtual void toStreamSygus(const Printer* p,
std::ostream& out,
Expr e) const override;
/* Retrieves empty callback pointer */
static inline std::shared_ptr<SygusEmptyPrintCallback> getEmptyPC()
{
if (!d_empty_pc)
{
d_empty_pc = std::make_shared<SygusEmptyPrintCallback>();
}
return d_empty_pc;
}
private:
/* empty callback object */
static std::shared_ptr<SygusEmptyPrintCallback> d_empty_pc;
};
} /* CVC4::printer namespace */
} /* CVC4 namespace */
#endif /* __CVC4__PRINTER__SYGUS_PRINT_CALLBACK_H */
| 32.426136 | 80 | 0.652357 | [
"object",
"vector"
] |
6b73ad2123c2fa2a9b1740ea368dacb40d3956ae | 990 | h | C | macOS/10.13/CoreFoundation.framework/_CFXNotificationObjectRegistration.h | onmyway133/Runtime-Headers | e9b80e7ab9103f37ad421ad6b8b58ee06369d21f | [
"MIT"
] | 30 | 2016-10-09T20:13:00.000Z | 2022-01-24T04:14:57.000Z | macOS/10.13/CoreFoundation.framework/_CFXNotificationObjectRegistration.h | onmyway133/Runtime-Headers | e9b80e7ab9103f37ad421ad6b8b58ee06369d21f | [
"MIT"
] | null | null | null | macOS/10.13/CoreFoundation.framework/_CFXNotificationObjectRegistration.h | onmyway133/Runtime-Headers | e9b80e7ab9103f37ad421ad6b8b58ee06369d21f | [
"MIT"
] | 7 | 2017-08-29T14:41:25.000Z | 2022-01-19T17:14:54.000Z | /* Generated by RuntimeBrowser
Image: /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation
*/
@interface _CFXNotificationObjectRegistration : _CFXNotificationRegistrationContainer {
void * _object;
}
@property (atomic, readonly) void*object;
+ (Class)childClass;
+ (const struct { long long x1; int (*x2)(); int (*x3)(); int (*x4)(); int (*x5)(); int (*x6)(); }*)stringKeyCallbacks;
- (id)acquireObserver:(void*)arg1 options:(unsigned long long)arg2;
- (BOOL)enumerate:(id)arg1;
- (void)find:(void*)arg1 matching:(struct { struct { id *x_1_1_1; unsigned long long x_1_1_2; BOOL x_1_1_3; } x1; struct { id *x_2_1_1; unsigned long long x_2_1_2; BOOL x_2_1_3; } x2; }*)arg2;
- (id)initWithObject:(void*)arg1 parent:(id)arg2;
- (void*)key;
- (void)match:(void*)arg1 matching:(struct { struct { id *x_1_1_1; unsigned long long x_1_1_2; BOOL x_1_1_3; } x1; struct { id *x_2_1_1; unsigned long long x_2_1_2; BOOL x_2_1_3; } x2; }*)arg2;
- (void*)object;
@end
| 43.043478 | 193 | 0.708081 | [
"object"
] |
6b815e7edc1590a3975883b781329758ac1c6c58 | 14,098 | h | C | source/glbinding-aux/include/glbinding-aux/Meta.h | dutow/glbinding | ac12883c4387650c29dbbf01278b7198083750d9 | [
"MIT"
] | null | null | null | source/glbinding-aux/include/glbinding-aux/Meta.h | dutow/glbinding | ac12883c4387650c29dbbf01278b7198083750d9 | [
"MIT"
] | null | null | null | source/glbinding-aux/include/glbinding-aux/Meta.h | dutow/glbinding | ac12883c4387650c29dbbf01278b7198083750d9 | [
"MIT"
] | null | null | null |
#pragma once
#include <string>
#include <utility>
#include <vector>
#include <set>
#include <cstdint>
#include <glbinding-aux/glbinding-aux_api.h>
#include <glbinding-aux/glbinding-aux_features.h>
#include <glbinding/gl/types.h>
#include <glbinding/AbstractFunction.h>
namespace glbinding
{
class Version;
namespace aux
{
/**
* @brief
* Provisioning of meta information about OpenGL extensions, functions and conversion of strings and symbols of the OpenGL API
*/
class GLBINDING_AUX_API Meta
{
public:
/**
* @brief
* Deleted Constructor as all functions are static
*/
Meta() = delete;
/**
* @brief
* Returns the revision of the parsed gl.xml file
*
* @deprecated
*
* @return
* The revision of the parsed gl.xml file
*/
static int glRevision();
/**
* @brief
* Converts a string into a bitfield symbol
*
* @param[in] bitfield
* The string representation of the bitfield
*
* @return
* The symbol identified through the bitfield string, 0 if failed
*/
static gl::GLbitfield getBitfield(const std::string & bitfield);
/**
* @brief
* Returns the list of all bitfields known by the gl.xml
*
* @return
* The list of all bitfields known by the gl.xml
*/
static std::vector<gl::GLbitfield> bitfields();
/**
* @brief
* Converts a GLenum to a string
*
* @param[in] glenum
* The enum to convert
*
* @return
* A string representation of the GLenum symbol name
*
* @remark
* Beware, that some enums in the OpenGL API have different symbol names but identical enum values and that this function cannot differentiate between them
*/
static const std::string & getString(gl::GLenum glenum);
/**
* @brief
* Converts a string to an enum symbol
*
* @param[in] glenum
* The string representation of the enum
*
* @return
* The symbol identified through the enum string, 0 if failed
*/
static gl::GLenum getEnum(const std::string & glenum);
/**
* @brief
* Returns the list of all enums known by the gl.xml
*
* @return
* The list of all enums known by the gl.xml
*/
static std::vector<gl::GLenum> enums();
/**
* @brief
* Converts a GLboolean to a string
*
* @param[in] boolean
* The boolean to convert
*
* @return
* A string representation of the GLboolean symbol name
*
* @remark
* Can either be '`GL_TRUE`' or '`GL_FALSE`'
*/
static const std::string & getString(const gl::GLboolean & boolean);
/**
* @brief
* Converts a string to a GLboolean symbol
*
* @param[in] boolean
* The string representation of the GLboolean
*
* @return
* The symbol identified through the boolean string, '`GL_FALSE`' if failed
*/
static gl::GLboolean getBoolean(const std::string & boolean);
/**
* @brief
* Converts a GLextension to its string representation
*
* @param[in] extension
* The extension to convert
*
* @return
* The string representation of the extension
*/
static const std::string & getString(gl::GLextension extension);
/**
* @brief
* Converts a string to an extension
*
* @param[in] extension
* The string representation of the extension
*
* @return
* The symbol identified through the extension string, '`UNKNOWN`' if failed
*/
static gl::GLextension getExtension(const std::string & extension);
/**
* @brief
* Returns the set of all extensions known by the gl.xml
*
* @return
* The set of all extensions known by the gl.xml
*/
static std::set<gl::GLextension> extensions();
/**
* @brief
* Returns the set of extensions that are required for by the given version
*
* @param[in] version
* The version/feature to return the required extensions for.
* If an null version is given, all extensions that have no
* version/feature associated are returned instead
*
* @return
* The set of extensions that should be supported for the given version.
* All non-versioned extensions can be queried by providing the null version
*/
static const std::set<gl::GLextension> extensions(const Version & version);
/**
* @brief
* Returns the list of extensions that are requiring an OpenGL function
*
* @param[in] glfunction
* The name of the function, including the 'gl' prefix
*
* @return
* The set of extensions that are requiring an OpenGL function
*/
static const std::set<gl::GLextension> extensions(const std::string & glfunction);
/**
* @brief
* Returns the list of features that are requiring an OpenGL function
*
* @param[in] glfunction
* The name of the function, including the 'gl' prefix
*
* @return
* The set of features that are requiring an OpenGL function
*/
static const std::set<Version> versions(const std::string & glfunction);
/**
* @brief
* Returns the set of functions that are required for the version
*
* @param[in] version
* The version to return the required functions for
*
* @return
* The set of functions that are required for the version
*
* @remark
* This is exclusive (preceeding versions are ignored)
*/
static const std::set<AbstractFunction *> functions(const Version & version);
/**
* @brief
* Returns the set of functions that are required for the extension
*
* @param[in] extension
* The extension to return the required functions for
*
* @return
* The set of functions that are required for the extension
*/
static const std::set<AbstractFunction *> functions(gl::GLextension extension);
/**
* @brief
* Returns the first OpenGL Version (Feature) that required the extension
*
* @param[in] glextension
* The extension
*
* @return
* The first GL Version (Feature) that required the extension
*/
static const Version & version(gl::GLextension glextension);
/**
* @brief
* Returns the list of all Versions (Features) known by the gl.xml
*
* @return
* The list of all Versions (Features) known by the gl.xml
*/
static const std::set<Version> & versions();
/**
* @brief
* Convert bitfield to symbol name string representation
*
* @param[in] bitfield
* The bitfield value
*
* @return
* The string representation of the value
*/
static const std::string & getString(gl::AttribMask bitfield);
/**
* @brief
* Convert bitfield to symbol name string representation
*
* @param[in] bitfield
* The bitfield value
*
* @return
* The string representation of the value
*/
static const std::string & getString(gl::BufferAccessMask bitfield);
/**
* @brief
* Convert bitfield to symbol name string representation
*
* @param[in] bitfield
* The bitfield value
*
* @return
* The string representation of the value
*/
static const std::string & getString(gl::BufferStorageMask bitfield);
/**
* @brief
* Convert bitfield to symbol name string representation
*
* @param[in] bitfield
* The bitfield value
*
* @return
* The string representation of the value
*/
static const std::string & getString(gl::ClearBufferMask bitfield);
/**
* @brief
* Convert bitfield to symbol name string representation
*
* @param[in] bitfield
* The bitfield value
*
* @return
* The string representation of the value
*/
static const std::string & getString(gl::ClientAttribMask bitfield);
/**
* @brief
* Convert bitfield to symbol name string representation
*
* @param[in] bitfield
* The bitfield value
*
* @return
* The string representation of the value
*/
static const std::string & getString(gl::ContextFlagMask bitfield);
/**
* @brief
* Convert bitfield to symbol name string representation
*
* @param[in] bitfield
* The bitfield value
*
* @return
* The string representation of the value
*/
static const std::string & getString(gl::ContextProfileMask bitfield);
/**
* @brief
* Convert bitfield to symbol name string representation
*
* @param[in] bitfield
* The bitfield value
*
* @return
* The string representation of the value
*/
static const std::string & getString(gl::FfdMaskSGIX bitfield);
/**
* @brief
* Convert bitfield to symbol name string representation
*
* @param[in] bitfield
* The bitfield value
*
* @return
* The string representation of the value
*/
static const std::string & getString(gl::FragmentShaderColorModMaskATI bitfield);
/**
* @brief
* Convert bitfield to symbol name string representation
*
* @param[in] bitfield
* The bitfield value
*
* @return
* The string representation of the value
*/
static const std::string & getString(gl::FragmentShaderDestMaskATI bitfield);
/**
* @brief
* Convert bitfield to symbol name string representation
*
* @param[in] bitfield
* The bitfield value
*
* @return
* The string representation of the value
*/
static const std::string & getString(gl::FragmentShaderDestModMaskATI bitfield);
/**
* @brief
* Convert bitfield to symbol name string representation
*
* @param[in] bitfield
* The bitfield value
*
* @return
* The string representation of the value
*/
static const std::string & getString(gl::MapBufferAccessMask bitfield);
/**
* @brief
* Convert bitfield to symbol name string representation
*
* @param[in] bitfield
* The bitfield value
*
* @return
* The string representation of the value
*/
static const std::string & getString(gl::MemoryBarrierMask bitfield);
/**
* @brief
* Convert bitfield to symbol name string representation
*
* @param[in] bitfield
* The bitfield value
*
* @return
* The string representation of the value
*/
static const std::string & getString(gl::OcclusionQueryEventMaskAMD bitfield);
/**
* @brief
* Convert bitfield to symbol name string representation
*
* @param[in] bitfield
* The bitfield value
*
* @return
* The string representation of the value
*/
static const std::string & getString(gl::PathFontStyle bitfield);
/**
* @brief
* Convert bitfield to symbol name string representation
*
* @param[in] bitfield
* The bitfield value
*
* @return
* The string representation of the value
*/
static const std::string & getString(gl::PathMetricMask bitfield);
/**
* @brief
* Convert bitfield to symbol name string representation
*
* @param[in] bitfield
* The bitfield value
*
* @return
* The string representation of the value
*/
static const std::string & getString(gl::PathRenderingMaskNV bitfield);
/**
* @brief
* Convert bitfield to symbol name string representation
*
* @param[in] bitfield
* The bitfield value
*
* @return
* The string representation of the value
*/
static const std::string & getString(gl::PerformanceQueryCapsMaskINTEL bitfield);
/**
* @brief
* Convert bitfield to symbol name string representation
*
* @param[in] bitfield
* The bitfield value
*
* @return
* The string representation of the value
*/
static const std::string & getString(gl::SyncObjectMask bitfield);
/**
* @brief
* Convert bitfield to symbol name string representation
*
* @param[in] bitfield
* The bitfield value
*
* @return
* The string representation of the value
*/
static const std::string & getString(gl::TextureStorageMaskAMD bitfield);
/**
* @brief
* Convert bitfield to symbol name string representation
*
* @param[in] bitfield
* The bitfield value
*
* @return
* The string representation of the value
*/
static const std::string & getString(gl::UnusedMask bitfield);
/**
* @brief
* Convert bitfield to symbol name string representation
*
* @param[in] bitfield
* The bitfield value
*
* @return
* The string representation of the value
*/
static const std::string & getString(gl::UseProgramStageMask bitfield);
/**
* @brief
* Convert bitfield to symbol name string representation
*
* @param[in] bitfield
* The bitfield value
*
* @return
* The string representation of the value
*/
static const std::string & getString(gl::VertexHintsMaskPGI bitfield);
private:
/**
* @brief
* Returns the bucket index of an OpenGL identifier used for the actual lookup into the compile-time maps
*
* @param[in] identifier
* The identifier for the bucket lookup
*
* @param[in] prefixLength
* The length of the prefix (e.g., 'gl' or 'GL_') to omit to get the actual first character of the identifier
*
* @return
* The bucket index of an OpenGL identifier
*/
static size_t alphabeticalGroupIndex(const std::string & identifier, std::uint8_t prefixLength);
};
} } // namespace glbinding::aux
| 25.493671 | 161 | 0.608313 | [
"vector"
] |
6b81771b349e152afb7b15e0d82c8fe5ce47bb21 | 2,824 | h | C | platform/switch/include/polyline/polyline.h | henlo-birb/lovepotion | 3b7128f0683252915cd0178a3e028a553b01fdc1 | [
"0BSD"
] | 303 | 2016-06-20T01:07:44.000Z | 2021-04-02T09:54:51.000Z | platform/switch/include/polyline/polyline.h | henlo-birb/lovepotion | 3b7128f0683252915cd0178a3e028a553b01fdc1 | [
"0BSD"
] | 95 | 2017-09-26T19:17:58.000Z | 2021-04-06T00:53:02.000Z | platform/switch/include/polyline/polyline.h | henlo-birb/lovepotion | 3b7128f0683252915cd0178a3e028a553b01fdc1 | [
"0BSD"
] | 50 | 2017-07-14T06:06:46.000Z | 2020-12-25T18:19:11.000Z | #pragma once
#include "deko3d/vertex.h"
#include <span>
namespace love
{
class Graphics;
/*
** Abstract base class
** for a chain of segments.
*/
class Polyline
{
public:
Polyline(vertex::TriangleIndexMode mode = vertex::TriangleIndexMode::STRIP) :
vertices(nullptr),
overdraw(nullptr),
vertexCount(0),
overdrawVertexCount(0),
triangleIndexMode(mode),
overdrawVertexStart(0)
{}
virtual ~Polyline();
/**
* @param coords Vertices defining the core line segments
* @param count Number of vertices
* @param size_hint Expected number of vertices of the rendering sleeve around the core
* line.
* @param halfwidth linewidth / 2.
* @param pixel_size Dimension of one pixel on the screen in world coordinates.
* @param draw_overdraw Fake antialias the line.
*/
void Render(const Vector2* coords, size_t count, size_t sizeHint, float halfWidth,
float pixelSize, bool drawOverdraw);
void Draw(Graphics* graphics);
protected:
virtual void CalculateOverdrawVertexCount(bool isLooping);
virtual void RenderOverdraw(const std::vector<Vector2>& normals, float pixelSize,
bool isLooping);
/* Enables a "fake" anti-aliasing line border */
virtual void FillColorArray(Colorf constant, Colorf* colors, int count);
/** Calculate line boundary points.
*
* @param[out] anchors Anchor points defining the core line.
* @param[out] normals Normals defining the edge of the sleeve.
* @param[in,out] s Direction of segment pq (updated to the segment qr).
* @param[in,out] len_s Length of segment pq (updated to the segment qr).
* @param[in,out] ns Normal on the segment pq (updated to the segment qr).
* @param[in] q Current point on the line.
* @param[in] r Next point on the line.
* @param[in] hw Half line width (see Polyline.render()).
*/
virtual void RenderEdge(std::vector<Vector2>& anchors, std::vector<Vector2>& normals,
Vector2& s, float& len_s, Vector2& ns, const Vector2& q,
const Vector2& r, float hw) = 0;
static constexpr float LINES_PARALLEL_EPS = 0.05f;
Vector2* vertices;
Vector2* overdraw;
size_t vertexCount;
size_t overdrawVertexCount;
vertex::TriangleIndexMode triangleIndexMode;
size_t overdrawVertexStart;
DkPrimitive triangleMode = DkPrimitive_TriangleStrip;
};
} // namespace love
| 35.3 | 99 | 0.591714 | [
"render",
"vector"
] |
6b9340b7718be74a28c078957a10b83088141952 | 14,019 | c | C | interfaces/dia/app/navigation.c | krattai/monoflow | d777b8f345c5f2910114af7a186dc3bb6fe14aaf | [
"BSD-2-Clause"
] | 1 | 2021-05-04T16:35:42.000Z | 2021-05-04T16:35:42.000Z | interfaces/dia/app/navigation.c | krattai/monoflow | d777b8f345c5f2910114af7a186dc3bb6fe14aaf | [
"BSD-2-Clause"
] | null | null | null | interfaces/dia/app/navigation.c | krattai/monoflow | d777b8f345c5f2910114af7a186dc3bb6fe14aaf | [
"BSD-2-Clause"
] | 1 | 2021-05-04T16:35:35.000Z | 2021-05-04T16:35:35.000Z | /* Dia -- a diagram creation/manipulation program
* Copyright (C) 1998 Alexander Larsson
*
* $Id$
*
* navigation.c : a navigation popup window to browse large diagrams.
* Copyright (C) 2003 Luc Pionchon
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
#include <gtk/gtk.h>
#include "diagram.h"
#include "display.h"
#include "diagdkrenderer.h"
#include "navigation.h"
#define THUMBNAIL_MAX_SIZE 150 /*(pixels) this may be a preference*/
struct _NavigationWindow
{
GtkWidget * popup_window;
/*popup size (drawing_area)*/
int width;
int height;
int max_size;
gboolean is_first_expose;
/*miniframe*/
int frame_w;
int frame_h;
GdkGC * gc;
GdkCursor * cursor;
/*factors to translate thumbnail coordinates to adjustement values*/
gdouble hadj_coef;
gdouble vadj_coef;
/*diagram thumbnail's buffer*/
GdkPixmap * buffer;
/*display to navigate*/
DDisplay * ddisp;
};
typedef struct _NavigationWindow NavigationWindow;
static NavigationWindow _nav;
static NavigationWindow * nav = &_nav;
#define DIAGRAM_OFFSET 1 /*(diagram's unit) so we can see the little green boxes :)*/
#define FRAME_THICKNESS 2 /*(pixels)*/
#define STD_CURSOR_MIN 16 /*(pixels)*/
static void on_button_navigation_popup_pressed (GtkButton * button, gpointer _ddisp);
static void on_button_navigation_popup_released (GtkButton * button, gpointer unused);
static void reset_sc_adj (GtkAdjustment * adj, gdouble lower, gdouble upper, gdouble page);
static gboolean on_da_expose_event (GtkWidget * widget, GdkEventExpose * event, gpointer unused);
static gboolean on_da_motion_notify_event (GtkWidget * widget, GdkEventMotion * event, gpointer unused);
static gboolean on_da_button_release_event (GtkWidget * widget, GdkEventButton * event, gpointer popup_window);
static char * nav_xpm[] = {
"10 10 2 1",
" c None",
". c #000000",
" .. ",
" .... ",
" .. ",
" . .. . ",
"..........",
"..........",
" . .. . ",
" .. ",
" .... ",
" .. "
};
GtkWidget *
navigation_popup_new (DDisplay *ddisp)
{
GtkWidget * button;
GtkWidget * image;
GdkPixmap * pixmap;
GdkBitmap * mask = NULL;
button = gtk_button_new ();
gtk_container_set_border_width (GTK_CONTAINER (button), 0);
gtk_button_set_relief (GTK_BUTTON(button), GTK_RELIEF_NONE);
g_signal_connect (G_OBJECT (button), "pressed",
G_CALLBACK (on_button_navigation_popup_pressed), ddisp);
/*if you are fast, the button catches it before the drawing_area:*/
g_signal_connect (G_OBJECT (button), "released",
G_CALLBACK (on_button_navigation_popup_released), NULL);
pixmap = gdk_pixmap_colormap_create_from_xpm_d(NULL,
gtk_widget_get_colormap(button),
&mask,
&(button->style->bg[GTK_STATE_NORMAL]),
nav_xpm);
image = gtk_image_new_from_pixmap (pixmap, mask);
g_object_unref(pixmap);
g_object_unref(mask);
gtk_container_add (GTK_CONTAINER (button), image);
gtk_widget_show(image);
return button;
}
static void
on_button_navigation_popup_pressed (GtkButton * button, gpointer _ddisp)
{
GtkWidget * popup_window;
GtkWidget * frame;
GtkWidget * drawing_area;
DiagramData * data;
Rectangle rect;/*diagram's extents*/
real zoom;/*zoom factor for thumbnail rendering*/
memset (nav, 0, sizeof(NavigationWindow));
/*--Retrieve the diagram's data*/
nav->ddisp = (DDisplay *) _ddisp;
data = nav->ddisp->diagram->data;
/*--Calculate sizes*/
{
int canvas_width, canvas_height;/*pixels*/
int diagram_width, diagram_height;/*pixels*/
GtkAdjustment * adj;
nav->max_size = THUMBNAIL_MAX_SIZE;
/*size: Diagram <--> thumbnail*/
rect.top = data->extents.top - DIAGRAM_OFFSET;
rect.left = data->extents.left - DIAGRAM_OFFSET;
rect.bottom = data->extents.bottom + DIAGRAM_OFFSET + 1;
rect.right = data->extents.right + DIAGRAM_OFFSET + 1;
zoom = nav->max_size / MAX( (rect.right - rect.left) , (rect.bottom - rect.top) );
nav->width = MIN( nav->max_size, (rect.right - rect.left) * zoom);
nav->height = MIN( nav->max_size, (rect.bottom - rect.top) * zoom);
/*size: display canvas <--> frame cursor*/
diagram_width = (int) ddisplay_transform_length (nav->ddisp, (rect.right - rect.left));
diagram_height = (int) ddisplay_transform_length (nav->ddisp, (rect.bottom - rect.top));
if (diagram_width * diagram_height == 0)
return; /* don't crash with no size, i.e. empty diagram */
canvas_width = nav->ddisp->canvas->allocation.width;
canvas_height = nav->ddisp->canvas->allocation.height;
nav->frame_w = nav->width * canvas_width / diagram_width;
nav->frame_h = nav->height * canvas_height / diagram_height;
/*reset adjustements to diagram size,*/
/*(dia allows to grow the canvas bigger than the diagram's actual size) */
/*and store the ratio thumbnail/adjustement(speedup on motion)*/
adj = nav->ddisp->hsbdata;
reset_sc_adj (adj, rect.left, rect.right, canvas_width / nav->ddisp->zoom_factor);
nav->hadj_coef = (adj->upper - adj->page_size - adj->lower) / (nav->width - nav->frame_w);
adj = nav->ddisp->vsbdata;
reset_sc_adj (adj, rect.top, rect.bottom, canvas_height / nav->ddisp->zoom_factor);
nav->vadj_coef = (adj->upper - adj->page_size - adj->lower) / (nav->height - nav->frame_h);
}
/*--GUI*/
/*popup window, and cute frame*/
popup_window = gtk_window_new (GTK_WINDOW_POPUP);
nav->popup_window = popup_window;
gtk_window_set_position (GTK_WINDOW (popup_window), GTK_WIN_POS_MOUSE);
frame = gtk_frame_new (NULL);
gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_ETCHED_OUT);
/*drawing area*/
drawing_area = gtk_drawing_area_new ();
gtk_widget_set_size_request (drawing_area, nav->width, nav->height);
gtk_widget_set_events (drawing_area, 0
| GDK_EXPOSURE_MASK
| GDK_POINTER_MOTION_MASK
| GDK_BUTTON_RELEASE_MASK
);
g_signal_connect (G_OBJECT (drawing_area), "expose_event",
G_CALLBACK (on_da_expose_event), NULL);
g_signal_connect (G_OBJECT (drawing_area), "motion_notify_event",
G_CALLBACK (on_da_motion_notify_event), NULL);
g_signal_connect (G_OBJECT (drawing_area), "button_release_event",
G_CALLBACK (on_da_button_release_event), NULL);
/*packing*/
gtk_container_add (GTK_CONTAINER (frame), drawing_area);
gtk_container_add (GTK_CONTAINER (popup_window), frame);
gtk_widget_show (drawing_area);
gtk_widget_show (frame);
gtk_widget_show (popup_window);
/*miniframe style*/
nav->gc = gdk_gc_new (drawing_area->window);
gdk_gc_set_line_attributes (nav->gc,
FRAME_THICKNESS,
GDK_LINE_SOLID, GDK_CAP_BUTT, GDK_JOIN_MITER);
/*cursor*/
if(MIN(nav->frame_h, nav->frame_w) > STD_CURSOR_MIN){
nav->cursor = gdk_cursor_new (GDK_FLEUR);
}
else{/*the miniframe is very small, so we use a minimalist cursor*/
unsigned char cursor_none_data[] = { 0x00 };
GdkBitmap * bitmap;
GdkColor fg = { 0, 65535, 65535, 65535};
GdkColor bg = { 0, 0, 0, 0 };
bitmap = gdk_bitmap_create_from_data(NULL, cursor_none_data, 1, 1);
nav->cursor = gdk_cursor_new_from_pixmap(bitmap, bitmap, &fg, &bg, 1, 1);
g_object_unref(bitmap);
}
/*grab the pointer*/
gdk_pointer_grab (drawing_area->window, TRUE,
GDK_BUTTON_RELEASE_MASK | GDK_BUTTON_MOTION_MASK,
drawing_area->window,
nav->cursor,
GDK_CURRENT_TIME);
/*buffer to draw the thumbnail on*/
nav->buffer = gdk_pixmap_new (drawing_area->window,
nav->width, nav->height, -1);
gdk_draw_rectangle (nav->buffer,
drawing_area->style->black_gc, TRUE,
0, 0, nav->width, nav->height);
{/*--Render the thumbnail*/
DiaGdkRenderer *renderer;
GdkColor color;
renderer = g_object_new (DIA_TYPE_GDK_RENDERER, NULL);
renderer->transform = dia_transform_new (&rect, &zoom);
renderer->pixmap = nav->buffer;/*render on the thumbnail buffer*/
renderer->gc = gdk_gc_new (nav->buffer);
/*Background color*/
color_convert (&data->bg_color, &color);
gdk_gc_set_foreground (renderer->gc, &color);
gdk_draw_rectangle (renderer->pixmap, renderer->gc, 1, 0, 0, nav->width, nav->height);
/*render the data*/
data_render (data, DIA_RENDERER (renderer), NULL, NULL, NULL);
g_object_ref (renderer->pixmap);
g_object_unref (renderer);
}
nav->is_first_expose = TRUE;/*set to request to draw the miniframe*/
}
/* resets adjustement to diagram size */
static void
reset_sc_adj (GtkAdjustment * adj, gdouble lower, gdouble upper, gdouble page)
{
adj->page_size = page;
adj->lower = lower;
adj->upper = upper;
if (adj->value < lower) adj->value = lower;
if (adj->value > (upper - page)) adj->value = upper - page;
gtk_adjustment_changed(adj);
}
static gboolean
on_da_expose_event (GtkWidget * widget, GdkEventExpose * event, gpointer unused)
{
/*refresh the part outdated by the event*/
gdk_draw_pixmap (widget->window,
widget->style->fg_gc[GTK_WIDGET_STATE (widget)],
GDK_PIXMAP(nav->buffer),
event->area.x, event->area.y,
event->area.x, event->area.y,
event->area.width, event->area.height);
/*the first time, display the current display's state*/
if(nav->is_first_expose){
GtkAdjustment * adj;
int x, y;
adj = nav->ddisp->hsbdata;
x = (adj->value - adj->lower) / (adj->upper - adj->lower) * (nav->width) +1;
adj = nav->ddisp->vsbdata;
y = (adj->value - adj->lower) / (adj->upper - adj->lower) * (nav->height) +1;
/*draw directly on the window, do not buffer the miniframe*/
gdk_draw_rectangle (widget->window,
nav->gc, FALSE,
x, y, nav->frame_w, nav->frame_h);
nav->is_first_expose = FALSE;
}
return FALSE;
}
static gboolean
on_da_motion_notify_event (GtkWidget * drawing_area, GdkEventMotion * event, gpointer unused)
{
GtkAdjustment * adj;
gboolean value_changed;
int w = nav->frame_w;
int h = nav->frame_h;
int x, y;/*top left of the miniframe*/
/* Don't try to move if there's no room for it.*/
if (w >= nav->width-1 && h >= nav->height-1) return FALSE;
x = CLAMP (event->x - w/2 , 0, nav->width - w);
y = CLAMP (event->y - h/2 , 0, nav->height - h);
adj = nav->ddisp->hsbdata;
value_changed = FALSE;
if (w/2 <= event->x && event->x <= (nav->width - w/2)){
adj->value = adj->lower + x * nav->hadj_coef;
value_changed = TRUE;
}
else if (x == 0 && adj->value != adj->lower){/*you've been too fast! :)*/
adj->value = adj->lower;
value_changed = TRUE;
}
else if (x == (nav->width - w) && adj->value != (adj->upper - adj->page_size)){/*idem*/
adj->value = adj->upper - adj->page_size;
value_changed = TRUE;
}
if (value_changed) gtk_adjustment_value_changed(adj);
adj = nav->ddisp->vsbdata;
value_changed = FALSE;
if (h/2 <= event->y && event->y <= (nav->height - h/2)){
adj->value = adj->lower + y * nav->vadj_coef;
value_changed = TRUE;
}
else if (y == 0 && adj->value != adj->lower){/*you've been too fast! :)*/
adj->value = adj->lower;
value_changed = TRUE;
}
else if (y == (nav->height - h) && adj->value != (adj->upper - adj->page_size)){/*idem*/
adj->value = adj->upper - adj->page_size;
value_changed = TRUE;
}
if (value_changed) gtk_adjustment_value_changed(adj);
/*--Draw the miniframe*/
/*refresh from the buffer*/
gdk_draw_pixmap (drawing_area->window,
drawing_area->style->fg_gc[GTK_WIDGET_STATE (drawing_area)],
GDK_PIXMAP(nav->buffer),
0, 0, 0, 0, nav->width, nav->height);
/*draw directly on the window, do not buffer the miniframe*/
gdk_draw_rectangle (drawing_area->window,
nav->gc, FALSE,
x, y, w, h);
return FALSE;
}
static gboolean
on_da_button_release_event (GtkWidget * widget, GdkEventButton * event, gpointer unused)
{
/* Apparently there are circumstances where this is run twice for one popup
* Protected calls to avoid crashing on second pass.
*/
if (nav->buffer)
g_object_unref (nav->buffer);
nav->buffer = NULL;
if (nav->gc)
g_object_unref (nav->gc);
nav->gc = NULL;
if (nav->cursor)
gdk_cursor_unref (nav->cursor);
nav->cursor = NULL;
if (nav->popup_window)
gtk_widget_destroy (nav->popup_window);
nav->popup_window = NULL;
/*returns the focus on the canvas*/
gtk_widget_grab_focus(nav->ddisp->canvas);
return FALSE;
}
static void
on_button_navigation_popup_released (GtkButton * button, gpointer z)
{
/* don't popdown before having drawn once */
if (!nav->is_first_expose) /* needed for gtk+-2.6.x, but work for 2.6 too. */
on_da_button_release_event (NULL, NULL, NULL);
}
| 31.717195 | 111 | 0.645624 | [
"render",
"transform"
] |
6b95d52a7a228615e23f113ff2d36dbaa459176a | 1,511 | h | C | entity/contents/filters/gaussian_blur_filter_contents.h | JsouLiang/impeller | 380e45d7f27c6815638287c99fbb0a0b136fd861 | [
"BSD-3-Clause"
] | null | null | null | entity/contents/filters/gaussian_blur_filter_contents.h | JsouLiang/impeller | 380e45d7f27c6815638287c99fbb0a0b136fd861 | [
"BSD-3-Clause"
] | 5 | 2022-03-02T01:43:59.000Z | 2022-03-31T01:48:46.000Z | entity/contents/filters/gaussian_blur_filter_contents.h | JsouLiang/impeller | 380e45d7f27c6815638287c99fbb0a0b136fd861 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#pragma once
#include <memory>
#include <optional>
#include "impeller/entity/contents/filters/filter_contents.h"
#include "impeller/entity/contents/filters/filter_input.h"
namespace impeller {
class DirectionalGaussianBlurFilterContents final : public FilterContents {
public:
DirectionalGaussianBlurFilterContents();
~DirectionalGaussianBlurFilterContents() override;
void SetSigma(Sigma sigma);
void SetDirection(Vector2 direction);
void SetBlurStyle(BlurStyle blur_style);
void SetSourceOverride(FilterInput::Ref alpha_mask);
// |FilterContents|
std::optional<Rect> GetFilterCoverage(const FilterInput::Vector& inputs,
const Entity& entity) const override;
private:
// |FilterContents|
bool RenderFilter(const FilterInput::Vector& input_textures,
const ContentContext& renderer,
const Entity& entity,
RenderPass& pass,
const Rect& coverage) const override;
Sigma blur_sigma_;
Vector2 blur_direction_;
BlurStyle blur_style_ = BlurStyle::kNormal;
bool src_color_factor_ = false;
bool inner_blur_factor_ = true;
bool outer_blur_factor_ = true;
FilterInput::Ref source_override_;
FML_DISALLOW_COPY_AND_ASSIGN(DirectionalGaussianBlurFilterContents);
};
} // namespace impeller
| 29.627451 | 77 | 0.726671 | [
"vector"
] |
6b9e9bb3c8cf58b29e7b305e8c54ee5bca8249d2 | 40,440 | h | C | content/browser/renderer_host/navigation_controller_impl.h | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | content/browser/renderer_host/navigation_controller_impl.h | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | content/browser/renderer_host/navigation_controller_impl.h | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CONTENT_BROWSER_RENDERER_HOST_NAVIGATION_CONTROLLER_IMPL_H_
#define CONTENT_BROWSER_RENDERER_HOST_NAVIGATION_CONTROLLER_IMPL_H_
#include <stddef.h>
#include <stdint.h>
#include <memory>
#include <set>
#include <string>
#include <vector>
#include "base/callback.h"
#include "base/gtest_prod_util.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "content/browser/renderer_host/back_forward_cache_impl.h"
#include "content/browser/renderer_host/navigation_controller_delegate.h"
#include "content/browser/renderer_host/navigation_entry_impl.h"
#include "content/browser/ssl/ssl_manager.h"
#include "content/common/content_export.h"
#include "content/common/navigation_client.mojom-forward.h"
#include "content/public/browser/navigation_controller.h"
#include "content/public/browser/navigation_type.h"
#include "content/public/browser/reload_type.h"
#include "mojo/public/cpp/bindings/pending_associated_remote.h"
#include "services/network/public/mojom/source_location.mojom-forward.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/public/common/tokens/tokens.h"
#include "third_party/blink/public/mojom/navigation/navigation_params.mojom-forward.h"
namespace blink {
struct NavigationDownloadPolicy;
} // namespace blink
namespace content {
class FrameTree;
class FrameTreeNode;
class NavigationRequest;
class RenderFrameHostImpl;
class SiteInfo;
class SiteInstance;
struct LoadCommittedDetails;
// NavigationControllerImpl is 1:1 with FrameTree. See comments on the base
// class.
class CONTENT_EXPORT NavigationControllerImpl : public NavigationController {
public:
// This tracks one NavigationRequest navigating to a pending NavigationEntry.
// In some cases, several NavigationRequests are referencing the same pending
// NavigationEntry. For instance:
// - A reload requested while a reload is already in progress.
// - An history navigation causing several subframes to navigate.
//
// When no NavigationRequests are referencing the pending NavigationEntry
// anymore, it should be discarded to avoid a URL spoof.
//
// The deletion is not always immediate, because it is not possible to delete
// the entry while requesting a navigation to it at the same time. In this
// case, the deletion happens later, when returning from the function.
//
// If the pending NavigationEntry is discarded before the PendingEntryRef(s),
// then removing the last associated PendingEntryRef is a no-op. It is a no-op
// forever, even if the entry becomes the pending NavigationEntry again in the
// meantime. Rather than track the NavigationRequest or pending entry
// explicitly, this ref class simply goes into a set that gets cleared with
// each change to the pending entry
class PendingEntryRef {
public:
explicit PendingEntryRef(
base::WeakPtr<NavigationControllerImpl> controller);
PendingEntryRef(const PendingEntryRef&) = delete;
PendingEntryRef& operator=(const PendingEntryRef&) = delete;
~PendingEntryRef();
private:
base::WeakPtr<NavigationControllerImpl> controller_;
};
NavigationControllerImpl(BrowserContext* browser_context,
FrameTree& frame_tree,
NavigationControllerDelegate* delegate);
NavigationControllerImpl(const NavigationControllerImpl&) = delete;
NavigationControllerImpl& operator=(const NavigationControllerImpl&) = delete;
~NavigationControllerImpl() override;
// NavigationController implementation:
WebContents* DeprecatedGetWebContents() override;
BrowserContext* GetBrowserContext() override;
void Restore(int selected_navigation,
RestoreType type,
std::vector<std::unique_ptr<NavigationEntry>>* entries) override;
NavigationEntryImpl* GetActiveEntry() override;
NavigationEntryImpl* GetVisibleEntry() override;
int GetCurrentEntryIndex() override;
NavigationEntryImpl* GetLastCommittedEntry() override;
int GetLastCommittedEntryIndex() override;
bool CanViewSource() override;
int GetEntryCount() override;
NavigationEntryImpl* GetEntryAtIndex(int index) override;
NavigationEntryImpl* GetEntryAtOffset(int offset) override;
void DiscardNonCommittedEntries() override;
NavigationEntryImpl* GetPendingEntry() override;
int GetPendingEntryIndex() override;
base::WeakPtr<NavigationHandle> LoadURL(
const GURL& url,
const Referrer& referrer,
ui::PageTransition type,
const std::string& extra_headers) override;
base::WeakPtr<NavigationHandle> LoadURLWithParams(
const LoadURLParams& params) override;
void LoadIfNecessary() override;
base::WeakPtr<NavigationHandle> LoadPostCommitErrorPage(
RenderFrameHost* render_frame_host,
const GURL& url,
const std::string& error_page_html,
net::Error error) override;
bool CanGoBack() override;
bool CanGoForward() override;
bool CanGoToOffset(int offset) override;
void GoBack() override;
void GoForward() override;
void GoToIndex(int index) override;
void GoToOffset(int offset) override;
bool RemoveEntryAtIndex(int index) override;
void PruneForwardEntries() override;
const SessionStorageNamespaceMap& GetSessionStorageNamespaceMap() override;
SessionStorageNamespace* GetDefaultSessionStorageNamespace() override;
bool NeedsReload() override;
void SetNeedsReload() override;
void CancelPendingReload() override;
void ContinuePendingReload() override;
bool IsInitialNavigation() override;
bool IsInitialBlankNavigation() override;
void Reload(ReloadType reload_type, bool check_for_repost) override;
void NotifyEntryChanged(NavigationEntry* entry) override;
void CopyStateFrom(NavigationController* source, bool needs_reload) override;
void CopyStateFromAndPrune(NavigationController* source,
bool replace_entry) override;
bool CanPruneAllButLastCommitted() override;
void PruneAllButLastCommitted() override;
void DeleteNavigationEntries(
const DeletionPredicate& deletionPredicate) override;
bool IsEntryMarkedToBeSkipped(int index) override;
BackForwardCacheImpl& GetBackForwardCache() override;
// Discards the pending entry if any. If this is caused by a navigation
// committing a new entry, `commit_details` will contain the committed
// navigation's details.
void DiscardNonCommittedEntriesWithCommitDetails(
LoadCommittedDetails* commit_details);
// Creates the initial NavigationEntry for the NavigationController when its
// FrameTree is being initialized. See NavigationEntry::IsInitialEntry() on
// what this means.
void CreateInitialEntry();
// Starts a navigation in a newly created subframe as part of a history
// navigation. Returns true if the history navigation could start, false
// otherwise. If this returns false, the caller should do a regular
// navigation to the default src URL for the frame instead.
bool StartHistoryNavigationInNewSubframe(
RenderFrameHostImpl* render_frame_host,
mojo::PendingAssociatedRemote<mojom::NavigationClient>*
navigation_client);
// Reloads the |frame_tree_node| and returns true. In some rare cases, there
// is no history related to the frame, nothing happens and this returns false.
bool ReloadFrame(FrameTreeNode* frame_tree_node);
// Navigates to a specified offset from the "current entry". Currently records
// a histogram indicating whether the session history navigation would only
// affect frames within the subtree of |sandbox_frame_tree_node_id|, which
// initiated the navigation. Navigating via this function is considered
// renderer-initiated, since it is only invoked when the renderer requests a
// history traversal.
void GoToOffsetInSandboxedFrame(int offset, int sandbox_frame_tree_node_id);
// Navigates to the specified offset from the "current entry" and marks the
// navigations as initiated by the renderer.
void GoToOffsetFromRenderer(int offset);
#if defined(OS_ANDROID)
// The difference between (Can)GoToOffsetWithSkipping and
// (Can)GoToOffset/(Can)GoToOffsetInSandboxedFrame is that this respects the
// history manipulation intervention and will exclude skippable entries.
// These should only be used for browser-initiated navigaitons.
bool CanGoToOffsetWithSkipping(int offset);
void GoToOffsetWithSkipping(int offset);
#endif
// Called when a document requests a navigation through a
// RenderFrameProxyHost.
void NavigateFromFrameProxy(
RenderFrameHostImpl* render_frame_host,
const GURL& url,
const blink::LocalFrameToken* initiator_frame_token,
int initiator_process_id,
const absl::optional<url::Origin>& initiator_origin,
bool is_renderer_initiated,
SiteInstance* source_site_instance,
const Referrer& referrer,
ui::PageTransition page_transition,
bool should_replace_current_entry,
blink::NavigationDownloadPolicy download_policy,
const std::string& method,
scoped_refptr<network::ResourceRequestBody> post_body,
const std::string& extra_headers,
network::mojom::SourceLocationPtr source_location,
scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
const absl::optional<blink::Impression>& impression);
// Navigates to the history entry associated with the given app history |key|.
// Searches |entries_| for a FrameNavigationEntry associated with |node|
// that has |key| as its app history key. Searches back from the current
// index, then forward, so if there are multiple entries with the same key,
// the nearest to current should be selected. Stops searching in the current
// direction if it finds a NavigationEntry without a FrameNavigationEntry for
// |node|, or if the FrameNavigationEntry doesn't match origin or site
// instance.
//
// If no matching entry is found, the navigation is dropped. The renderer
// should only send the navigation to the browser if it believes the entry is
// in |entries_|, but it might be wrong (if the entry was dropped from
// |entries_|, or due to a race condition) or compromised.
// If a matching entry is found, navigate to that entry and proceed like any
// other history navigation.
void NavigateToAppHistoryKey(FrameTreeNode* node, const std::string& key);
// Whether this is the initial navigation in an unmodified new tab. In this
// case, we know there is no content displayed in the page.
bool IsUnmodifiedBlankTab();
// The session storage namespace that all child RenderViews associated with
// |site_info| should use.
SessionStorageNamespace* GetSessionStorageNamespace(
const SiteInfo& site_info);
// Returns the index of the specified entry, or -1 if entry is not contained
// in this NavigationController.
int GetIndexOfEntry(const NavigationEntryImpl* entry) const;
// Return the index of the entry with the given unique id, or -1 if not found.
int GetEntryIndexWithUniqueID(int nav_entry_id) const;
// Return the entry with the given unique id, or null if not found.
NavigationEntryImpl* GetEntryWithUniqueID(int nav_entry_id) const;
// Same as above method, but also includes the pending entry in the search
// space.
NavigationEntryImpl* GetEntryWithUniqueIDIncludingPending(
int nav_entry_id) const;
NavigationControllerDelegate* delegate() const { return delegate_; }
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class NeedsReloadType {
kRequestedByClient = 0,
kRestoreSession = 1,
kCopyStateFrom = 2,
kCrashedSubframe = 3,
kMaxValue = kCrashedSubframe
};
// Request a reload to happen when activated. Same as the public
// SetNeedsReload(), but takes in a |type| which specifies why the reload is
// being requested.
void SetNeedsReload(NeedsReloadType type);
// For use by WebContentsImpl ------------------------------------------------
// Visit all FrameNavigationEntries as well as all frame trees and register
// any instances of |origin| as non-isolated with their respective
// BrowsingInstances. This is important when |origin| requests isolation, so
// that we only do so in BrowsingInstances that haven't seen it before.
void RegisterExistingOriginToPreventOptInIsolation(const url::Origin& origin);
// Allow renderer-initiated navigations to create a pending entry when the
// provisional load starts.
void SetPendingEntry(std::unique_ptr<NavigationEntryImpl> entry);
// Handles updating the navigation state after the renderer has navigated.
// This is used by the WebContentsImpl.
//
// If a new entry is created, it will return true and will have filled the
// given details structure and broadcast the NOTIFY_NAV_ENTRY_COMMITTED
// notification. The caller can then use the details without worrying about
// listening for the notification.
//
// In the case that nothing has changed, the details structure is undefined
// and it will return false.
//
// |was_on_initial_empty_document| indicates whether the document being
// navigated away from was an initial empty document.
//
// |previous_document_was_activated| is true if the previous document had user
// interaction. This is used for a new renderer-initiated navigation to decide
// if the page that initiated the navigation should be skipped on
// back/forward button.
bool RendererDidNavigate(RenderFrameHostImpl* rfh,
const mojom::DidCommitProvisionalLoadParams& params,
LoadCommittedDetails* details,
bool is_same_document_navigation,
bool was_on_initial_empty_document,
bool previous_document_was_activated,
NavigationRequest* navigation_request);
// Notifies us that we just became active. This is used by the WebContentsImpl
// so that we know to load URLs that were pending as "lazy" loads.
void SetActive(bool is_active);
// Sets the SessionStorageNamespace for the given |partition_id|. This is
// used during initialization of a new NavigationController to allow
// pre-population of the SessionStorageNamespace objects. Session restore,
// prerendering, and the implementation of window.open() are the primary users
// of this API.
//
// Calling this function when a SessionStorageNamespace has already been
// associated with a |partition_id| will CHECK() fail.
void SetSessionStorageNamespace(
const StoragePartitionId& partition_id,
SessionStorageNamespace* session_storage_namespace);
// Random data ---------------------------------------------------------------
FrameTree& frame_tree() { return frame_tree_; }
SSLManager* ssl_manager() { return &ssl_manager_; }
// Maximum number of entries before we start removing entries from the front.
static void set_max_entry_count_for_testing(size_t max_entry_count) {
max_entry_count_for_testing_ = max_entry_count;
}
static size_t max_entry_count();
void SetGetTimestampCallbackForTest(
const base::RepeatingCallback<base::Time()>& get_timestamp_callback);
// Discards only the pending entry. |was_failure| should be set if the pending
// entry is being discarded because it failed to load.
void DiscardPendingEntry(bool was_failure);
// Sets a flag on the pending NavigationEntryImpl instance if any that the
// navigation failed due to an SSL error.
void SetPendingNavigationSSLError(bool error);
// Returns true if the string corresponds to a valid data URL, false
// otherwise.
#if defined(OS_ANDROID)
static bool ValidateDataURLAsString(
const scoped_refptr<const base::RefCountedString>& data_url_as_string);
#endif
// Invoked when a user activation occurs within the page, so that relevant
// entries can be updated as needed.
void NotifyUserActivation();
// Tracks a new association between the current pending entry and a
// NavigationRequest. Callers are responsible for only calling this for
// requests corresponding to the current pending entry.
std::unique_ptr<PendingEntryRef> ReferencePendingEntry();
// Another page accessed the initial empty main document, which means it
// is no longer safe to display a pending URL without risking a URL spoof.
void DidAccessInitialMainDocument();
// The state for the page changed and should be updated in session history.
void UpdateStateForFrame(RenderFrameHostImpl* render_frame_host,
const blink::PageState& page_state);
// Like NavigationController::CreateNavigationEntry, but takes an extra
// argument, |source_site_instance|.
static std::unique_ptr<NavigationEntryImpl> CreateNavigationEntry(
const GURL& url,
Referrer referrer,
absl::optional<url::Origin> initiator_origin,
SiteInstance* source_site_instance,
ui::PageTransition transition,
bool is_renderer_initiated,
const std::string& extra_headers,
BrowserContext* browser_context,
scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory);
// Called just before sending the commit to the renderer. Walks the
// session history entries for the committing FrameTreeNode, forward and
// backward from the pending entry. All contiguous and same-origin
// FrameNavigationEntries are serialized and added to |request|'s commit
// params.
void PopulateAppHistoryEntryVectors(NavigationRequest* request);
private:
friend class RestoreHelper;
FRIEND_TEST_ALL_PREFIXES(TimeSmoother, Basic);
FRIEND_TEST_ALL_PREFIXES(TimeSmoother, SingleDuplicate);
FRIEND_TEST_ALL_PREFIXES(TimeSmoother, ManyDuplicates);
FRIEND_TEST_ALL_PREFIXES(TimeSmoother, ClockBackwardsJump);
FRIEND_TEST_ALL_PREFIXES(NavigationControllerBrowserTest, PostThenReload);
FRIEND_TEST_ALL_PREFIXES(NavigationControllerBrowserTest,
PostThenReplaceStateThenReload);
FRIEND_TEST_ALL_PREFIXES(NavigationControllerBrowserTest,
PostThenPushStateThenReloadThenHistory);
FRIEND_TEST_ALL_PREFIXES(NavigationControllerBrowserTest,
PostThenFragmentNavigationThenReloadThenHistory);
FRIEND_TEST_ALL_PREFIXES(
NavigationControllerBrowserTest,
PostThenBrowserInitiatedFragmentNavigationThenReload);
FRIEND_TEST_ALL_PREFIXES(NavigationControllerBrowserTest, PostSubframe);
FRIEND_TEST_ALL_PREFIXES(NavigationControllerDisableHistoryIntervention,
GoToOffsetWithSkippingDisableHistoryIntervention);
FRIEND_TEST_ALL_PREFIXES(NavigationControllerHistoryInterventionBrowserTest,
GoToOffsetWithSkippingEnableHistoryIntervention);
FRIEND_TEST_ALL_PREFIXES(NavigationControllerHistoryInterventionBrowserTest,
SetSkipOnBackForwardDoSkipForGoToOffsetWithSkipping);
FRIEND_TEST_ALL_PREFIXES(NavigationControllerHistoryInterventionBrowserTest,
SetSkipOnBackForwardDoNotSkipForGoToOffset);
// Defines possible actions that are returned by
// DetermineActionForHistoryNavigation().
enum class HistoryNavigationAction {
kStopLooking,
kKeepLooking,
kSameDocument,
kDifferentDocument,
};
// Helper class to smooth out runs of duplicate timestamps while still
// allowing time to jump backwards.
class CONTENT_EXPORT TimeSmoother {
public:
// Returns |t| with possibly some time added on.
base::Time GetSmoothedTime(base::Time t);
private:
// |low_water_mark_| is the first time in a sequence of adjusted
// times and |high_water_mark_| is the last.
base::Time low_water_mark_;
base::Time high_water_mark_;
};
// The repost dialog is suppressed during testing. However, it should be shown
// in some tests. This allows a test to elect to allow the repost dialog to
// show for a scoped duration.
class CONTENT_EXPORT ScopedShowRepostDialogForTesting {
public:
ScopedShowRepostDialogForTesting();
~ScopedShowRepostDialogForTesting();
ScopedShowRepostDialogForTesting(const ScopedShowRepostDialogForTesting&) =
delete;
ScopedShowRepostDialogForTesting& operator=(
const ScopedShowRepostDialogForTesting&) = delete;
private:
const bool was_disallowed_;
};
// Navigates in session history to the given index. If
// |sandbox_frame_tree_node_id| is valid, then this request came
// from a sandboxed iframe with top level navigation disallowed. This
// is currently only used for tracking metrics.
void GoToIndex(int index,
int sandbox_frame_tree_node_id,
bool is_browser_initiated);
// Starts a navigation to an already existing pending NavigationEntry.
// Currently records a histogram indicating whether the session history
// navigation would only affect frames within the subtree of
// |sandbox_frame_tree_node_id|, which initiated the navigation.
void NavigateToExistingPendingEntry(ReloadType reload_type,
int sandboxed_source_frame_tree_node_id,
bool is_browser_initiated);
// Helper function used by FindFramesToNavigate to determine the appropriate
// action to take for a particular frame while navigating to
// |pending_entry_|.
HistoryNavigationAction DetermineActionForHistoryNavigation(
FrameTreeNode* frame,
ReloadType reload_type);
// Recursively identifies which frames need to be navigated for a navigation
// to |pending_entry_|, starting at |frame| and exploring its children.
// |same_document_loads| and |different_document_loads| will be filled with
// the NavigationRequests needed to navigate to |pending_entry_|.
void FindFramesToNavigate(
FrameTreeNode* frame,
ReloadType reload_type,
bool is_browser_initiated,
std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
std::vector<std::unique_ptr<NavigationRequest>>*
different_document_loads);
// Starts a new navigation based on |load_params|, that doesn't correspond to
// an existing NavigationEntry.
base::WeakPtr<NavigationHandle> NavigateWithoutEntry(
const LoadURLParams& load_params);
// Handles a navigation to a renderer-debug URL.
void HandleRendererDebugURL(FrameTreeNode* frame_tree_node, const GURL& url);
// Creates and returns a NavigationEntry based on |load_params| for a
// navigation in |node|.
// |override_user_agent|, |should_replace_current_entry| and
// |has_user_gesture| will override the values from |load_params|. The same
// values should be passed to CreateNavigationRequestFromLoadParams.
std::unique_ptr<NavigationEntryImpl> CreateNavigationEntryFromLoadParams(
FrameTreeNode* node,
const LoadURLParams& load_params,
bool override_user_agent,
bool should_replace_current_entry,
bool has_user_gesture);
// Creates and returns a NavigationRequest based on |load_params| for a
// new navigation in |node|.
// Will return nullptr if the parameters are invalid and the navigation cannot
// start.
// |override_user_agent|, |should_replace_current_entry| and
// |has_user_gesture| will override the values from |load_params|. The same
// values should be passed to CreateNavigationEntryFromLoadParams.
// TODO(clamy): Remove the dependency on NavigationEntry and
// FrameNavigationEntry.
std::unique_ptr<NavigationRequest> CreateNavigationRequestFromLoadParams(
FrameTreeNode* node,
const LoadURLParams& load_params,
bool override_user_agent,
bool should_replace_current_entry,
bool has_user_gesture,
network::mojom::SourceLocationPtr source_location,
ReloadType reload_type,
NavigationEntryImpl* entry,
FrameNavigationEntry* frame_entry);
// Creates and returns a NavigationRequest for a navigation to |entry|. Will
// return nullptr if the parameters are invalid and the navigation cannot
// start.
// TODO(clamy): Ensure this is only called for navigations to existing
// NavigationEntries.
std::unique_ptr<NavigationRequest> CreateNavigationRequestFromEntry(
FrameTreeNode* frame_tree_node,
NavigationEntryImpl* entry,
FrameNavigationEntry* frame_entry,
ReloadType reload_type,
bool is_same_document_history_load,
bool is_history_navigation_in_new_child_frame,
bool is_browser_initiated);
// Returns whether there is a pending NavigationEntry whose unique ID matches
// the given NavigationRequest's pending_nav_entry_id.
bool PendingEntryMatchesRequest(NavigationRequest* request) const;
// Classifies the given renderer navigation (see the NavigationType enum).
NavigationType ClassifyNavigation(
RenderFrameHostImpl* rfh,
const mojom::DidCommitProvisionalLoadParams& params,
NavigationRequest* navigation_request,
LoadCommittedDetails* load_committed_details);
// Handlers for the different types of navigation types. They will actually
// handle the navigations corresponding to the different NavClasses above.
// They will NOT broadcast the commit notification, that should be handled by
// the caller.
//
// RendererDidNavigateAutoSubframe is special, it may not actually change
// anything if some random subframe is loaded. It will return true if anything
// changed, or false if not.
//
// The NewEntry and NewSubframe functions take in |replace_entry| to pass to
// InsertOrReplaceEntry, in case the newly created NavigationEntry is meant to
// replace the current one (e.g., for location.replace or successful loads
// after net errors), in contrast to updating a NavigationEntry in place
// (e.g., for history.replaceState).
void RendererDidNavigateToNewEntry(
RenderFrameHostImpl* rfh,
const mojom::DidCommitProvisionalLoadParams& params,
bool is_same_document,
bool replace_entry,
bool previous_document_was_activated,
NavigationRequest* request,
LoadCommittedDetails* details);
void RendererDidNavigateToExistingEntry(
RenderFrameHostImpl* rfh,
const mojom::DidCommitProvisionalLoadParams& params,
bool is_same_document,
bool was_restored,
NavigationRequest* request,
bool keep_pending_entry,
LoadCommittedDetails* details);
void RendererDidNavigateNewSubframe(
RenderFrameHostImpl* rfh,
const mojom::DidCommitProvisionalLoadParams& params,
bool is_same_document,
bool replace_entry,
bool previous_document_was_activated,
NavigationRequest* request,
LoadCommittedDetails* details);
bool RendererDidNavigateAutoSubframe(
RenderFrameHostImpl* rfh,
const mojom::DidCommitProvisionalLoadParams& params,
bool is_same_document,
bool was_on_initial_empty_document,
NavigationRequest* request,
LoadCommittedDetails* details);
// Allows the derived class to issue notifications that a load has been
// committed. This will fill in the active entry to the details structure.
void NotifyNavigationEntryCommitted(LoadCommittedDetails* details);
// Updates the virtual URL of an entry to match a new URL, for cases where
// the real renderer URL is derived from the virtual URL, like view-source:
void UpdateVirtualURLToURL(NavigationEntryImpl* entry, const GURL& new_url);
// Invoked after session/tab restore or cloning a tab. Resets the transition
// type of the entries, updates the max page id and creates the active
// contents.
void FinishRestore(int selected_index, RestoreType type);
// Inserts a new entry or replaces the current entry with a new one, removing
// all entries after it. The new entry will become the active one.
// If |was_post_commit_error_| is set, the last committed entry will be saved,
// the new entry will replace it, and on any navigation away from the new
// entry or on reloads, the old one will replace |entry|.
void InsertOrReplaceEntry(std::unique_ptr<NavigationEntryImpl> entry,
bool replace,
bool was_post_commit_error,
bool is_in_fenced_frame_tree,
LoadCommittedDetails* details);
// Removes the entry at |index|, as long as it is not the current entry.
void RemoveEntryAtIndexInternal(int index);
// If we have the maximum number of entries, remove the oldest entry that is
// marked to be skipped on back/forward button, in preparation to add another.
// If no entry is skippable, then the oldest entry will be pruned.
void PruneOldestSkippableEntryIfFull();
// Removes all entries except the last committed entry. If there is a new
// pending navigation it is preserved. In contrast to
// PruneAllButLastCommitted() this does not update the session history of the
// RenderView. Callers must ensure that |CanPruneAllButLastCommitted| returns
// true before calling this.
void PruneAllButLastCommittedInternal();
// Inserts up to |max_index| entries from |source| into this. This does NOT
// adjust any of the members that reference entries_
// (last_committed_entry_index_ or pending_entry_index_)
void InsertEntriesFrom(NavigationControllerImpl* source, int max_index);
// Returns the navigation index that differs from the current entry by the
// specified |offset|. The index returned is not guaranteed to be valid.
// This does not account for skippable entries or the history manipulation
// intervention.
int GetIndexForOffset(int offset);
// History Manipulation intervention:
// The previous document that started this navigation needs to be skipped in
// subsequent back/forward UI navigations if it never received any user
// gesture. This is to intervene against pages that manipulate the history
// such that the user is not able to go back to the last site they interacted
// with (crbug.com/907167).
// Note that this function must be called before the new navigation entry is
// inserted in |entries_| to make sure UKM reports the URL of the document
// adding the entry.
void SetShouldSkipOnBackForwardUIIfNeeded(
bool replace_entry,
bool previous_document_was_activated,
bool is_renderer_initiated,
ukm::SourceId previous_page_load_ukm_source_id);
// This function sets all same document entries with the same value
// of skippable flag. This is to avoid back button abuse by inserting
// multiple history entries and also to help valid cases where a user gesture
// on the document should apply to all same document history entries and none
// should be skipped. All entries belonging to the same document as the entry
// at |reference_index| will get their skippable flag set to |skippable|.
void SetSkippableForSameDocumentEntries(int reference_index, bool skippable);
// Called when one PendingEntryRef is deleted. When all of the refs for the
// current pending entry have been deleted, this automatically discards the
// pending NavigationEntry.
void PendingEntryRefDeleted(PendingEntryRef* ref);
// Computes the policy container policies to be stored in the
// FrameNavigationEntry by RendererDidNavigate.
std::unique_ptr<PolicyContainerPolicies>
ComputePolicyContainerPoliciesForFrameEntry(RenderFrameHostImpl* rfh,
bool is_same_document,
const GURL& url);
// Adds details from a committed navigation to `entry` and the
// FrameNavigationEntry corresponding to `rfh`.
void UpdateNavigationEntryDetails(
NavigationEntryImpl* entry,
RenderFrameHostImpl* rfh,
const mojom::DidCommitProvisionalLoadParams& params,
NavigationRequest* request,
NavigationEntryImpl::UpdatePolicy update_policy,
bool is_new_entry,
LoadCommittedDetails* commit_details);
// Broadcasts this controller's session history offset and length to all
// renderers involved in rendering the current page. The offset is
// GetLastCommittedEntryIndex() and length is GetEntryCount().
void BroadcastHistoryOffsetAndLength();
// Helper functions used to determine if it is safe to change the internal
// representation of StoragePartitionId.
//
// Called when a new StoragePartitionId is added to
// `session_storage_namespace_map_` and adds an entry to
// `partition_config_to_id_map_`.
void OnStoragePartitionIdAdded(const StoragePartitionId& partition_id);
// Called to log a crash dump when unique string representations result in
// the same StoragePartitionConfig, or an ID used to lookup a namespace
// contains a different config than the one used when the namespace was
// added to the map. Both situations imply that there is not a 1:1 mapping
// between representations.
void LogStoragePartitionIdCrashKeys(
const StoragePartitionId& original_partition_id,
const StoragePartitionId& new_partition_id);
// Used by PopulateAppHistoryEntryVectors to initialize a single vector.
enum class Direction { kForward, kBack };
std::vector<blink::mojom::AppHistoryEntryPtr>
PopulateSingleAppHistoryEntryVector(Direction direction,
int entry_index,
const url::Origin& pending_origin,
FrameTreeNode* node,
SiteInstance* site_instance,
int64_t previous_item_sequence_number);
// Helper for NavigateToAppHistoryKey(). Ensures that we only navigate to
// |target_entry| if it matches |current_entry|'s origin and site instance, as
// well as having |app_history_key| as its key.
HistoryNavigationAction ShouldNavigateToEntryForAppHistoryKey(
FrameNavigationEntry* current_entry,
FrameNavigationEntry* target_entry,
const std::string& app_history_key);
// Whether to maintain a session history with just one entry.
//
// This returns true for a prerendering page and for fenced frames.
// `frame_tree_node` is checked to see if it belongs to a frame tree for
// prerendering or for a fenced frame.
// Explainer:
// https://github.com/jeremyroman/alternate-loading-modes/blob/main/browsing-context.md#session-history)
//
// Portals will be added to this in the future.
bool ShouldMaintainTrivialSessionHistory(
const FrameTreeNode* frame_tree_node) const;
// ---------------------------------------------------------------------------
// The FrameTree this instance belongs to. Each FrameTree gets its own
// NavigationController.
FrameTree& frame_tree_;
// The user browser context associated with this controller.
const raw_ptr<BrowserContext> browser_context_;
// List of |NavigationEntry|s for this controller.
std::vector<std::unique_ptr<NavigationEntryImpl>> entries_;
// An entry we haven't gotten a response for yet. This will be discarded
// when we navigate again. It's used only so we know what the currently
// displayed tab is.
//
// This may refer to an item in the entries_ list if the pending_entry_index_
// != -1, or it may be its own entry that should be deleted. Be careful with
// the memory management.
raw_ptr<NavigationEntryImpl> pending_entry_ = nullptr;
// This keeps track of the NavigationRequests associated with the pending
// NavigationEntry. When all of them have been deleted, or have stopped
// loading, the pending NavigationEntry can be discarded.
//
// This is meant to avoid a class of URL spoofs where the navigation is
// canceled, but the stale pending NavigationEntry is left in place.
std::set<PendingEntryRef*> pending_entry_refs_;
// If a new entry fails loading, details about it are temporarily held here
// until the error page is shown (or 0 otherwise).
//
// TODO(avi): We need a better way to handle the connection between failed
// loads and the subsequent load of the error page. This current approach has
// issues: 1. This might hang around longer than we'd like if there is no
// error page loaded, and 2. This doesn't work very well for frames.
// http://crbug.com/474261
int failed_pending_entry_id_ = 0;
// The index of the currently visible entry.
int last_committed_entry_index_ = -1;
// The index of the pending entry if it is in entries_, or -1 if
// pending_entry_ is a new entry (created by LoadURL).
int pending_entry_index_ = -1;
// The delegate associated with the controller. Possibly null during
// setup.
raw_ptr<NavigationControllerDelegate> delegate_;
// Manages the SSL security UI.
SSLManager ssl_manager_;
// Whether we need to be reloaded when made active.
bool needs_reload_ = false;
// Source of when |needs_reload_| is set. Only valid when |needs_reload_|
// is set.
NeedsReloadType needs_reload_type_ = NeedsReloadType::kRequestedByClient;
// Whether this is the initial navigation.
// Becomes false when initial navigation commits.
bool is_initial_navigation_ = true;
// Prevent unsafe re-entrant calls to NavigateToPendingEntry.
bool in_navigate_to_pending_entry_ = false;
// Used to find the appropriate SessionStorageNamespace for the storage
// partition of a NavigationEntry.
//
// A NavigationController may contain NavigationEntries that correspond to
// different StoragePartitions. Even though they are part of the same
// NavigationController, only entries in the same StoragePartition may
// share session storage state with one another.
SessionStorageNamespaceMap session_storage_namespace_map_;
// Temporary map that is being used to verify that there is a 1:1
// relationship between the string representation used as the key in
// `session_storage_namespace_map_` and the StoragePartitionConfig
// representation that we plan to migrate the map key to.
// TODO(acolwell): Remove this map once we have enough data to determine if
// it is safe to change representations or not.
std::map<StoragePartitionConfig, StoragePartitionId>
partition_config_to_id_map_;
// The maximum number of entries that a navigation controller can store.
static size_t max_entry_count_for_testing_;
// If a repost is pending, its type (RELOAD or RELOAD_BYPASSING_CACHE),
// NO_RELOAD otherwise.
ReloadType pending_reload_ = ReloadType::NONE;
// Used to get timestamps for newly-created navigation entries.
base::RepeatingCallback<base::Time()> get_timestamp_callback_;
// Used to smooth out timestamps from |get_timestamp_callback_|.
// Without this, whenever there is a run of redirects or
// code-generated navigations, those navigations may occur within
// the timer resolution, leading to things sometimes showing up in
// the wrong order in the history view.
TimeSmoother time_smoother_;
// BackForwardCache:
//
// Stores frozen RenderFrameHost. Restores them on history navigation.
// See BackForwardCache class documentation.
BackForwardCacheImpl back_forward_cache_;
// Holds the entry that was committed at the time an error page was triggered
// due to a call to LoadPostCommitErrorPage. The error entry will take its
// place until the user navigates again, at which point it will go back into
// the entry list instead of the error entry. Set to nullptr if there is no
// post commit error entry. Note that this entry must always correspond to the
// last committed entry index, and that there can be only a single post-commit
// error page entry in its place in entries_. This ensures that its spot in
// entries_ cannot go away (e.g., due to PruneForwardEntries) and that it can
// go back into place after any subsequent commit.
std::unique_ptr<NavigationEntryImpl> entry_replaced_by_post_commit_error_;
// NOTE: This must be the last member.
base::WeakPtrFactory<NavigationControllerImpl> weak_factory_{this};
};
} // namespace content
#endif // CONTENT_BROWSER_RENDERER_HOST_NAVIGATION_CONTROLLER_IMPL_H_
| 45.694915 | 106 | 0.750321 | [
"vector"
] |
6b9f4f0d98d29798cd17b07e1a7e464e7c84a76a | 10,451 | h | C | enduser/troubleshoot/tshoot/apgtsinf.h | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | enduser/troubleshoot/tshoot/apgtsinf.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | enduser/troubleshoot/tshoot/apgtsinf.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //
// MODULE: APGTSINF.H
//
// PURPOSE: Inference support header
//
// PROJECT: Generic Troubleshooter DLL for Microsoft AnswerPoint
//
// COMPANY: Saltmine Creative, Inc. (206)-284-7511 support@saltmine.com
//
// AUTHOR: Roman Mach, Joe Mabel
//
// ORIGINAL DATE: 8-2-96
//
// NOTES:
// 1. Based on Print Troubleshooter DLL
//
// Version Date By Comments
//--------------------------------------------------------------------
// V0.1 - RM Original
// V3.0 7-21-98 JM Major revision, deprecate IDH in favor of NID, use STL.
//
#if !defined(APGTSINF_H_INCLUDED)
#define APGTSINF_H_INCLUDED
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
#include "propnames.h"
#include "topic.h"
using namespace std;
#define MAXBUF 256 // length of text buffers used for filenames,
// IP adresses (this is plenty big), HTTP response ( like
// "200 OK", again, plenty big), registry keys,
// and occasionally just to format an arbitrary string.
//--------------------------------------------------------------------
// Default Values for localizable text
#define SZ_UNKNOWN _T("Unknown")
#define SZ_NEXT_BTN _T("Next")
#define SZ_START_BTN _T("StartOver")
#define SZ_BACK_BTN _T("Back")
#define SZ_PP_SNIF_BTN _T("Investigate")
//#define SZ_I_NO_RESULT_PAGE _T("<HR>Not Enough Information was available to provide a useful result\n <BR>It is also possible that the information you provided is not correct, please check your entries\n <BR>Please amend your choices\n <P><INPUT TYPE=SUBMIT VALUE=\"Continue\"><BR>")
#define SZ_I_NO_RESULT_PAGE _T("<HR>This troubleshooter can't diagnose the cause of your problem based on the information you have provided.\n <BR>Either start the troubleshooter over, change your answers in the table and continue, or search for other resources.\n <P><INPUT TYPE=SUBMIT VALUE=\"Continue\"><BR>")
#define SZ_HIST_TABLE_SNIFFED_TEXT _T("INVESTIGATED")
#define SZ_ALLOW_SNIFFING_TEXT _T("I want the troubleshooter to investigate settings on this computer")
#define SZ_SNIFF_ONE_NODE _T("Investigate")
#define SZ_SNIFF_FAILED _T("The troubleshooter was unable to investigate the necessary settings. Follow the remaining instructions on this page to complete the task manually.")
#define SZ_INPUT_TAG_NEXT _T("<INPUT tag=next TYPE=SUBMIT VALUE=\"")
#define SZ_INPUT_TAG_STARTOVER _T("<INPUT tag=startover TYPE=BUTTON VALUE=\"")
#define SZ_INPUT_TAG_BACK _T("<INPUT tag=back TYPE=BUTTON VALUE=\"")
#define SZ_INPUT_TAG_SNIFFER _T("<INPUT tag=sniffer TYPE=BUTTON VALUE=\"")
// Text forms of some special state values
#define SZ_ST_FAILED _T("0") // "failed" on fixable node is considered normal
// 101 - Go to "Bye" Page (User succeeded)
#define SZ_ST_WORKED _T("101")
// 102 - Unknown (user doesn't know the correct answer here - applies to Fixable/Unfixable and
// Info nodes only)
#define SZ_ST_UNKNOWN _T("102")
// 103 - "Anything Else?" (effectively, "retry a skiped node?"
#define SZ_ST_ANY _T("103")
//
#define SZ_ST_SNIFFED_MANUALLY_TRUE _T("true")
//
#define SZ_ST_SNIFFED_MANUALLY_FALSE _T("false")
class CSniffConnector;
class CSniff;
//
class CInfer
{
// This class is an instrument to restore m_arrInitial - like order of
// elements in array, passed to its "Restore" function
class CArrayOrderRestorer
{
vector<NID> m_arrInitial;
public:
CArrayOrderRestorer(const vector<NID>& initial) : m_arrInitial(initial) {}
public:
bool Restore(long base_length, vector<NID>& arr_to_restore);
};
public:
CInfer(CSniffConnector* pSniffConnector);
~CInfer();
int INode(LPCTSTR sz) {return m_pTopic->INode(sz);};
void SetTopic(CTopic *pTopic);
void SetNodeState(NID nid, IST ist);
void AddToSniffed(NID nid, IST ist);
void IdentifyPresumptiveCause();
void FillInHTMLFragments(CHTMLFragmentsTS &frag);
bool AppendBESRedirection(CString & str);
NID NIDFromIDH(IDH idh) const;
NID NIDSelected() const;
CSniff* GetSniff();
void SetLastSniffedManually(bool);
private:
enum ActionButtons {
k_BtnNext = 0x01,
k_BtnBack = 0x02,
k_BtnStartOver = 0x04,
k_BtnPPSniffing = 0x08, // Problem Page sniff button for expensive sniffing
// of multiple nodes
k_BtnManualSniffing = 0x10, // for manual sniffing of a single node
};
typedef UINT ActionButtonSet; // should be an OR of 0 or more ActionButtons
private:
bool IsProblemNode(NID nid) const;
void AddToBasisForInference(NID nid, IST ist);
void GetRecommendations();
void RecycleSkippedNode();
bool AllCauseNodesNormal();
bool IsInSniffedArray(NID nid) const;
bool IsPresumptiveCause(NID nid) const;
void CreateUnknownButtonText(CString & strUnknown) const;
void AppendNextButtonText(CString & str) const;
void AppendBackButtonText(CString & str) const;
void AppendPPSnifferButtonText(CString & str) const;
void AppendStartOverButtonText(CString & str) const;
void AppendManualSniffButtonText(CString & str) const;
void AppendHistTableSniffedText(CString & str) const;
void AppendAllowSniffingText(CString & str) const;
void AppendSniffFailedText(CString & str) const;
void AppendActionButtons(CString & str, ActionButtonSet btns, NID nid = -1) const;
void AppendNextButton(CString & str) const;
void AppendStartOverButton(CString & str) const;
void AppendBackButton(CString & str) const;
void AppendPPSnifferButton(CString & str) const;
void AppendManualSniffButton(CString & str, NID nid) const;
void AppendMultilineNetProp(CString & str, LPCTSTR szPropName, LPCTSTR szFormat);
void AppendMultilineNodeProp(CString & str, NID nid, LPCTSTR szPropName, LPCTSTR szFormat);
void AppendCurrentRadioButtons(NID nid, CString & str);
static void AppendRadioButtonCurrentNode(
CString &str, LPCTSTR szName, LPCTSTR szValue, LPCTSTR szLabel, bool bChecked =false);
void AppendRadioButtonVisited(CString &str, NID nid, UINT value, bool bSet,
LPCTSTR szLabel, bool bShowHistory) const;
void CreateProblemVisitedText(CString & str, NID nidProblem, bool bShowHistory);
bool AppendVisitedNodeText(CString & str, NID nid, bool bShowHistory) const;
void AppendStateText(CString & str, NID nid, UINT state, bool bSet, bool bSkipped,
bool bShowHistory, int nStateSet);
void AppendHiddenFieldSniffed(CString &str, NID nid) const;
void AddAllowAutomaticSniffingHiddenField(CString &str) const;
void AppendCurrentNodeText(CString & str);
void AppendByeMsg(CString & str);
void AppendFailMsg(CString & str);
void AppendServiceMsg(CString & str);
void AppendNIDPage(NID nid, CString & str);
void AppendImpossiblePage(CString & str);
void AppendSniffAllCausesNormalPage(CString & str);
void AppendProblemPage(CString & str);
void AppendProblemNodes(CString & str);
void AppendLinkAsButton(
CString & str,
const CString & strTarget,
const CString & strLabel) const;
// JSM V3.2 wrapper for AppendMultilineNetProp() used by FillInHTMLFragments()
CString ConvertNetProp(const CString &strNetPropName);
bool ShowFullBES();
bool TimeForBES();
void OutputBackend(CString & str);
static bool HideState(LPCTSTR szStateName);
bool SymbolicFromNID(CString & str, NID nid) const;
static bool IsCause (ESTDLBL lbl);
bool IsSkipped(NID nid) const;
bool ManuallySniffedNodeExists() const;
bool IsManuallySniffedNode(NID nid) const;
private:
CTopic *m_pTopic; // associated belief network
CSniff *m_pSniff; // associated sniffing object
// History, extracted from the query from the user.
// All this is known _before_ we seek a recommendation.
CBasisForInference m_BasisForInference; // tie together nodes & their states; excludes
// skipped nodes
CBasisForInference m_SniffedStates; // tie together successfully sniffed nodes & their states
vector<NID> m_arrnidSkipped; // nodes for which the user has been unable to give
// a yes or no answer (or, in the case of multistate,
// any useful answer at all).
vector<NID> m_arrnidVisited; // node numbers of recommendations the user has visited
// This includes skipped nodes, but excludes the selected problem
// and excludes pseudo-nodes like the FAIL node.
NID m_nidProblem; // problem node indicated by user request.
// set to nidNil if no problem node yet specified.
bool m_bDone; // TRUE ==> we got back state ST_WORKED (better be
// for the last node in the list!) so it's time to
// show the BYE page
CString m_strStartOverLink; // For Online TS, URL of Problem page
// Recommendations
CRecommendations m_Recommendations; // new recommendations. We only care about the
// first recommendation not already offered and skipped.
bool m_bRecOK; // true ==> m_Recommendations is valid. (Can be valid and
// empty if nothing to recommend).
CNodeStatePair m_SniffedRecommendation; // if a recommendation from a sniffer overrides normal;
// method of getting a recommendation, here's where we store it.
// Otherwise, nidNil.
// Because this is always a Cause node in its abnormal state,
// it is actually redundant (but harmless) to track state as
// well as node ID.
// Back End Search
bool m_bUseBackEndRedirection;// Set true when user asks for Back End Search
CString m_strEncodedForm; // URL-encoded search form (like the contents of a Get-method
// query). This is built as a side effect when we construct
// the full BES page.
// Variables related to re-offering a previously skipped node
bool m_bRecycleSkippedNode; // Set TRUE if user (responding to service node) wants
// to revisit a previously skipped node. May be set false
// if we discover there is no such node to revisit.
NID m_nidRecycled; // Node to use if m_bRecycleSkippedNode is TRUE
bool m_bRecyclingInitialized;// Protects against multiple calls to RecycleSkippedNode()
// ------------- Misc -------------
NID m_nidSelected; // once we work out what node to show the user, we keep this
// around for logging.
bool m_bLastSniffedManually; // identifies that last node was sniffed manually
};
#endif // !defined(APGTSINF_H_INCLUDED)
| 40.824219 | 313 | 0.708927 | [
"object",
"vector"
] |
6ba0ab82883ffebe2e3ea4364057bdb5f7522379 | 12,242 | c | C | Engine/actor.c | Byterset/UltraEd | e7c1556cd0a7ea5fc713c46b72e1dd4762760eea | [
"MIT"
] | null | null | null | Engine/actor.c | Byterset/UltraEd | e7c1556cd0a7ea5fc713c46b72e1dd4762760eea | [
"MIT"
] | null | null | null | Engine/actor.c | Byterset/UltraEd | e7c1556cd0a7ea5fc713c46b72e1dd4762760eea | [
"MIT"
] | null | null | null | #include <nusys.h>
#include <malloc.h>
#include <string.h>
#include <stdio.h>
#include "upng.h"
#include "actor.h"
#include "util.h"
#include "vector.h"
#include "math.h"
Actor *CActor_CreateModel(int id, const char *name, void *modelStart, void *modelEnd, double positionX, double positionY, double positionZ,
double rotX, double rotY, double rotZ, double angle, double scaleX, double scaleY, double scaleZ,
double centerX, double centerY, double centerZ, double radius,
double extentX, double extentY, double extentZ, enum ColliderType collider)
{
return CActor_CreateTexturedModel(id, name, modelStart, modelEnd,
NULL, NULL, 0, 0, positionX, positionY, positionZ, rotX, rotY, rotZ, angle, scaleX, scaleY, scaleZ,
centerX, centerY, centerZ, radius, extentX, extentY, extentZ, collider);
}
Actor *CActor_CreateTexturedModel(int id, const char *name, void *modelStart, void *modelEnd, void *textureStart, void *textureEnd,
int textureWidth, int textureHeight, double positionX, double positionY, double positionZ, double rotX,
double rotY, double rotZ, double angle, double scaleX, double scaleY, double scaleZ,
double centerX, double centerY, double centerZ, double radius,
double extentX, double extentY, double extentZ, enum ColliderType collider)
{
const int modelSize = modelEnd - modelStart;
const int textureSize = textureEnd - textureStart;
void *modelBuffer = malloc(modelSize);
void *textureBuffer = malloc(textureSize);
// Transfer from ROM the model mesh data and texture.
CUtil_Rom2Ram(modelStart, modelBuffer, modelSize);
CUtil_Rom2Ram(textureStart, textureBuffer, textureSize);
Model *model = (Model *)malloc(sizeof(Model));
model->texture = NULL;
model->textureWidth = textureWidth;
model->textureHeight = textureHeight;
Actor *actor = (Actor *)model;
CActor_Init(actor, id, name, TModel, positionX, positionY, positionZ, rotX, rotY, rotZ,
angle, scaleX, scaleY, scaleZ, centerX, centerY, centerZ, radius, extentX, extentY, extentZ, collider);
// Read how many vertices for this mesh.
int vertexCount = 0;
char *line = (char *)strtok(modelBuffer, "\n");
sscanf(line, "%i", &vertexCount);
model->mesh.vertices = (Vtx *)malloc(vertexCount * sizeof(Vtx));
model->mesh.vertexCount = vertexCount;
// Gather all of the X, Y, and Z vertex info.
for (int i = 0; i < vertexCount; i++)
{
double x, y, z, r, g, b, a, s, t;
line = (char *)strtok(NULL, "\n");
sscanf(line, "%lf %lf %lf %lf %lf %lf %lf %lf %lf", &x, &y, &z, &r, &g, &b, &a, &s, &t);
model->mesh.vertices[i].v.ob[0] = x * SCALE_FACTOR;
model->mesh.vertices[i].v.ob[1] = y * SCALE_FACTOR;
model->mesh.vertices[i].v.ob[2] = -z * SCALE_FACTOR;
model->mesh.vertices[i].v.flag = 0;
model->mesh.vertices[i].v.tc[0] = (int)(s * textureWidth) << 5;
model->mesh.vertices[i].v.tc[1] = (int)(t * textureHeight) << 5;
model->mesh.vertices[i].v.cn[0] = r * 255;
model->mesh.vertices[i].v.cn[1] = g * 255;
model->mesh.vertices[i].v.cn[2] = b * 255;
model->mesh.vertices[i].v.cn[3] = a * 255;
}
free(modelBuffer);
// Load in the png texture data.
upng_t *png = upng_new_from_bytes(textureBuffer, textureSize);
if (png != NULL)
{
upng_decode(png);
if (upng_get_error(png) == UPNG_EOK)
{
// Convert texture data from 24bpp to 16bpp in RGB5551 format.
model->texture = CUtil_Image24To16(upng_get_buffer(png), textureWidth, textureHeight);
}
upng_free(png);
}
return actor;
}
Actor *CActor_CreateCamera(int id, const char *name, double positionX, double positionY, double positionZ,
double rotX, double rotY, double rotZ, double angle,
double centerX, double centerY, double centerZ, double radius,
double extentX, double extentY, double extentZ, double fov, enum ColliderType collider)
{
Camera *camera = (Camera *)malloc(sizeof(Camera));
camera->fov = fov;
Actor *actor = (Actor *)camera;
CActor_Init(actor, id, name, TCamera, positionX, positionY, positionZ, rotX, rotY, rotZ,
angle, 1.0, 1.0, 1.0, centerX, centerY, centerZ, radius, extentX, extentY, extentZ, collider);
return actor;
}
void CActor_Init(Actor *actor, int id, const char *name, enum ActorType actorType, double positionX, double positionY,
double positionZ, double rotX, double rotY, double rotZ, double angle, double scaleX,
double scaleY, double scaleZ, double centerX, double centerY, double centerZ, double radius,
double extentX, double extentY, double extentZ, enum ColliderType colliderType)
{
actor->id = id;
actor->name = name;
actor->visible = 1;
actor->type = actorType;
actor->collider = colliderType;
actor->parent = NULL;
actor->children = NULL;
actor->start = NULL;
actor->update = NULL;
actor->input = NULL;
actor->collide = NULL;
actor->notify = NULL;
actor->destroy = NULL;
actor->dynamic = NULL;
actor->originalCenter.x = actor->center.x = centerX;
actor->originalCenter.y = actor->center.y = centerY;
actor->originalCenter.z = actor->center.z = -centerZ;
actor->originalRadius = actor->radius = radius;
actor->originalExtents.x = actor->extents.x = extentX;
actor->originalExtents.y = actor->extents.y = extentY;
actor->originalExtents.z = actor->extents.z = extentZ;
// Entire axis can't be zero or it won't render.
if (rotX == 0.0 && rotY == 0.0 && rotZ == 0.0) rotZ = 1;
const int invertScalar = (actorType == TModel ? -1 : 1);
actor->position.x = positionX;
actor->position.y = positionY;
actor->position.z = invertScalar * positionZ;
actor->scale.x = scaleX;
actor->scale.y = scaleY;
actor->scale.z = scaleZ;
actor->rotationAxis.x = rotX;
actor->rotationAxis.y = rotY;
actor->rotationAxis.z = invertScalar * rotZ;
actor->rotationAngle = invertScalar * angle;
}
void CActor_Draw(Actor *actor, Gfx **displayList)
{
if (!actor->visible) return;
const int invertScalar = actor->type == TCamera ? -1 : 1;
guTranslate(&actor->transform.translation, actor->position.x * SCALE_FACTOR, actor->position.y * SCALE_FACTOR, invertScalar * actor->position.z * SCALE_FACTOR);
guRotate(&actor->transform.rotation, actor->rotationAngle, invertScalar * actor->rotationAxis.x, invertScalar * actor->rotationAxis.y, actor->rotationAxis.z);
guScale(&actor->transform.scale, actor->scale.x, actor->scale.y, actor->scale.z);
gSPMatrix((*displayList)++, OS_K0_TO_PHYSICAL(&actor->transform.translation),
G_MTX_MODELVIEW | G_MTX_MUL | G_MTX_PUSH);
gSPMatrix((*displayList)++, OS_K0_TO_PHYSICAL(&actor->transform.rotation),
G_MTX_MODELVIEW | G_MTX_MUL | G_MTX_NOPUSH);
gSPMatrix((*displayList)++, OS_K0_TO_PHYSICAL(&actor->transform.scale),
G_MTX_MODELVIEW | G_MTX_MUL | G_MTX_NOPUSH);
gDPPipeSync((*displayList)++);
if (actor->type == TModel)
{
Model *model = (Model *)actor;
gDPSetCycleType((*displayList)++, G_CYC_1CYCLE);
gDPSetRenderMode((*displayList)++, G_RM_AA_ZB_OPA_SURF, G_RM_AA_ZB_OPA_SURF2);
gSPClearGeometryMode((*displayList)++, 0xFFFFFFFF);
gSPSetGeometryMode((*displayList)++, G_SHADE | G_SHADING_SMOOTH | G_ZBUFFER | G_CULL_FRONT);
if (model->texture != NULL)
{
gSPTexture((*displayList)++, 0xffff, 0xffff, 0, G_TX_RENDERTILE, G_ON);
gDPSetTextureFilter((*displayList)++, G_TF_BILERP);
gDPSetTexturePersp((*displayList)++, G_TP_PERSP);
gDPSetCombineMode((*displayList)++, G_CC_MODULATERGB, G_CC_MODULATERGB);
gDPLoadTextureBlock((*displayList)++, model->texture, G_IM_FMT_RGBA, G_IM_SIZ_16b,
model->textureWidth, model->textureHeight, 0,
G_TX_WRAP, G_TX_WRAP, G_TX_NOMASK, G_TX_NOMASK, G_TX_NOLOD, G_TX_NOLOD);
}
else
{
gDPSetCombineMode((*displayList)++, G_CC_SHADE, G_CC_SHADE);
}
int skip = 0;
int remainingVertices = model->mesh.vertexCount;
const int size = 30;
// Send vertex data in batches.
while (remainingVertices > 0)
{
int take = remainingVertices >= size ? size : remainingVertices;
gSPVertex((*displayList)++, &(model->mesh.vertices[skip]), take, 0);
gDPPipeSync((*displayList)++);
for (int i = 0; i < take / 3; i++)
{
gSP1Triangle((*displayList)++, i * 3, i * 3 + 1, i * 3 + 2, 0);
}
remainingVertices -= take;
skip += take;
}
}
if (actor->children != NULL)
{
for (int i = 0; i < CVector_Size(actor->children); i++)
{
CActor_Draw(CVector_Get(actor->children, i), displayList);
}
}
gSPPopMatrix((*displayList)++, G_MTX_MODELVIEW);
}
void CActor_LinkChildToParent(Vector actors, Actor *child, Actor *parent)
{
if (parent && child)
{
if (parent->children == NULL)
{
parent->children = CVector_Create();
}
CVector_Add(parent->children, child);
child->parent = parent;
}
}
Vector3 CActor_GetPosition(Actor *Actor)
{
if (Actor == NULL)
return (Vector3) { 0, 0, 0 };
if (Actor->parent == NULL)
{
const int invertScalar = Actor->type == TCamera ? -1 : 1;
return (Vector3) { Actor->position.x, Actor->position.y, invertScalar * Actor->position.z };
}
return CMath_Vec3MulMat(Actor->position, CActor_GetMatrix(Actor->parent));
}
Mtx CActor_GetMatrix(Actor *Actor)
{
if (Actor == NULL)
{
Mtx mat;
guMtxIdent(&mat);
return mat;
}
Mtx combined;
guMtxCatL(&Actor->transform.scale, &Actor->transform.rotation, &combined);
// Need to rebuild translation matrix since the actor's stored one is scaled up.
Mtx translation;
const int invertScalar = Actor->type == TCamera ? -1 : 1;
guTranslate(&translation, Actor->position.x, Actor->position.y, invertScalar * Actor->position.z);
guMtxCatL(&combined, &translation, &combined);
if (Actor->parent == NULL)
{
return combined;
}
return CMath_MatMulMat(combined, CActor_GetMatrix(Actor->parent));
}
Mtx CActor_GetRotationMatrix(Actor *Actor)
{
if (Actor == NULL)
{
Mtx mat;
guMtxIdent(&mat);
return mat;
}
if (Actor->parent == NULL)
{
return Actor->transform.rotation;
}
return CMath_MatMulMat(Actor->transform.rotation, CActor_GetRotationMatrix(Actor->parent));
}
void CActor_UpdateAABB(Actor *Actor)
{
float center[3] = { Actor->center.x, Actor->center.y, Actor->center.z };
const float originalCenter[3] = { Actor->originalCenter.x, Actor->originalCenter.y, Actor->originalCenter.z };
float extents[3] = { Actor->extents.x, Actor->extents.y, Actor->extents.z };
const float originalExtents[3] = { Actor->originalExtents.x, Actor->originalExtents.y, Actor->originalExtents.z };
float mat[4][4];
Mtx fixedMat = CActor_GetMatrix(Actor);
guMtxL2F(mat, &fixedMat);
for (int i = 0; i < 3; i++)
{
center[i] = 0.0f;
extents[i] = 0.0f;
for (int j = 0; j < 3; j++)
{
center[i] += mat[j][i] * originalCenter[j];
extents[i] += fabs(mat[j][i]) * originalExtents[j];
}
}
Actor->center = (Vector3) { center[0], center[1], center[2] };
Actor->extents = (Vector3) { extents[0], extents[1], extents[2] };
}
void CActor_UpdateSphere(Actor *Actor)
{
Actor->center = CMath_Vec3MulMat(Actor->originalCenter, Actor->transform.rotation);
// Scale the calculated radius using the largest scale value of the actor.
float scaleComps[3] = { fabs(Actor->scale.x), fabs(Actor->scale.y), fabs(Actor->scale.z) };
float largestScale = 0;
for (int i = 0; i < 3; i++)
{
if (scaleComps[i] > largestScale)
largestScale = scaleComps[i];
}
Actor->radius = largestScale * Actor->originalRadius;
}
| 34.877493 | 164 | 0.637886 | [
"mesh",
"render",
"vector",
"model",
"transform"
] |
6ba1f9ab5f6d2e0d81c8f4d907868a275e53e931 | 1,121 | h | C | components/optimization_guide/core/insertion_ordered_set.h | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-10-18T02:33:40.000Z | 2020-10-18T02:33:40.000Z | components/optimization_guide/core/insertion_ordered_set.h | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 3 | 2021-05-17T16:28:52.000Z | 2021-05-21T22:42:22.000Z | components/optimization_guide/core/insertion_ordered_set.h | DamieFC/chromium | 54ce2d3c77723697efd22cfdb02aea38f9dfa25c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_OPTIMIZATION_GUIDE_CORE_INSERTION_ORDERED_SET_H_
#define COMPONENTS_OPTIMIZATION_GUIDE_CORE_INSERTION_ORDERED_SET_H_
#include <vector>
#include "base/containers/flat_set.h"
// Keeps a set of unique element, while preserving the insertion order. vector()
// can be accessed to get the ordered elements.
template <typename T>
class InsertionOrderedSet {
public:
InsertionOrderedSet() = default;
void insert(const T& elem) {
auto ret = set_.insert(elem);
if (ret.second) {
// The element wasn't already in the container.
vector_.push_back(elem);
}
}
void clear() {
set_.clear();
vector_.clear();
}
bool empty() const { return vector_.empty(); }
const std::vector<T>& vector() { return vector_; }
const base::flat_set<T>& set() { return set_; }
private:
base::flat_set<T> set_;
std::vector<T> vector_;
};
#endif // COMPONENTS_OPTIMIZATION_GUIDE_CORE_INSERTION_ORDERED_SET_H_
| 25.477273 | 80 | 0.721677 | [
"vector"
] |
6ba8a7b67cbc2b958ea9b2304dd5f3865fbbbaff | 3,573 | c | C | model/ezsigntemplatesigner_get_object_v1_response_all_of.c | ezmaxinc/eZmax-SDK-c | 725eab79d6311127a2d5bd731b978bce94142d69 | [
"curl",
"MIT"
] | null | null | null | model/ezsigntemplatesigner_get_object_v1_response_all_of.c | ezmaxinc/eZmax-SDK-c | 725eab79d6311127a2d5bd731b978bce94142d69 | [
"curl",
"MIT"
] | null | null | null | model/ezsigntemplatesigner_get_object_v1_response_all_of.c | ezmaxinc/eZmax-SDK-c | 725eab79d6311127a2d5bd731b978bce94142d69 | [
"curl",
"MIT"
] | null | null | null | #include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "ezsigntemplatesigner_get_object_v1_response_all_of.h"
ezsigntemplatesigner_get_object_v1_response_all_of_t *ezsigntemplatesigner_get_object_v1_response_all_of_create(
ezsigntemplatesigner_get_object_v1_response_m_payload_t *m_payload
) {
ezsigntemplatesigner_get_object_v1_response_all_of_t *ezsigntemplatesigner_get_object_v1_response_all_of_local_var = malloc(sizeof(ezsigntemplatesigner_get_object_v1_response_all_of_t));
if (!ezsigntemplatesigner_get_object_v1_response_all_of_local_var) {
return NULL;
}
ezsigntemplatesigner_get_object_v1_response_all_of_local_var->m_payload = m_payload;
return ezsigntemplatesigner_get_object_v1_response_all_of_local_var;
}
void ezsigntemplatesigner_get_object_v1_response_all_of_free(ezsigntemplatesigner_get_object_v1_response_all_of_t *ezsigntemplatesigner_get_object_v1_response_all_of) {
if(NULL == ezsigntemplatesigner_get_object_v1_response_all_of){
return ;
}
listEntry_t *listEntry;
if (ezsigntemplatesigner_get_object_v1_response_all_of->m_payload) {
ezsigntemplatesigner_get_object_v1_response_m_payload_free(ezsigntemplatesigner_get_object_v1_response_all_of->m_payload);
ezsigntemplatesigner_get_object_v1_response_all_of->m_payload = NULL;
}
free(ezsigntemplatesigner_get_object_v1_response_all_of);
}
cJSON *ezsigntemplatesigner_get_object_v1_response_all_of_convertToJSON(ezsigntemplatesigner_get_object_v1_response_all_of_t *ezsigntemplatesigner_get_object_v1_response_all_of) {
cJSON *item = cJSON_CreateObject();
// ezsigntemplatesigner_get_object_v1_response_all_of->m_payload
if (!ezsigntemplatesigner_get_object_v1_response_all_of->m_payload) {
goto fail;
}
cJSON *m_payload_local_JSON = ezsigntemplatesigner_get_object_v1_response_m_payload_convertToJSON(ezsigntemplatesigner_get_object_v1_response_all_of->m_payload);
if(m_payload_local_JSON == NULL) {
goto fail; //model
}
cJSON_AddItemToObject(item, "mPayload", m_payload_local_JSON);
if(item->child == NULL) {
goto fail;
}
return item;
fail:
if (item) {
cJSON_Delete(item);
}
return NULL;
}
ezsigntemplatesigner_get_object_v1_response_all_of_t *ezsigntemplatesigner_get_object_v1_response_all_of_parseFromJSON(cJSON *ezsigntemplatesigner_get_object_v1_response_all_ofJSON){
ezsigntemplatesigner_get_object_v1_response_all_of_t *ezsigntemplatesigner_get_object_v1_response_all_of_local_var = NULL;
// define the local variable for ezsigntemplatesigner_get_object_v1_response_all_of->m_payload
ezsigntemplatesigner_get_object_v1_response_m_payload_t *m_payload_local_nonprim = NULL;
// ezsigntemplatesigner_get_object_v1_response_all_of->m_payload
cJSON *m_payload = cJSON_GetObjectItemCaseSensitive(ezsigntemplatesigner_get_object_v1_response_all_ofJSON, "mPayload");
if (!m_payload) {
goto end;
}
m_payload_local_nonprim = ezsigntemplatesigner_get_object_v1_response_m_payload_parseFromJSON(m_payload); //nonprimitive
ezsigntemplatesigner_get_object_v1_response_all_of_local_var = ezsigntemplatesigner_get_object_v1_response_all_of_create (
m_payload_local_nonprim
);
return ezsigntemplatesigner_get_object_v1_response_all_of_local_var;
end:
if (m_payload_local_nonprim) {
ezsigntemplatesigner_get_object_v1_response_m_payload_free(m_payload_local_nonprim);
m_payload_local_nonprim = NULL;
}
return NULL;
}
| 41.068966 | 190 | 0.824237 | [
"model"
] |
6bafd45eafa21f6cd652c9c08be2f3d40deb8f25 | 10,437 | h | C | io/database.h | aconstlink/natus | d2123c6e1798bd0771b8a1a05721c68392afc92f | [
"MIT"
] | null | null | null | io/database.h | aconstlink/natus | d2123c6e1798bd0771b8a1a05721c68392afc92f | [
"MIT"
] | 292 | 2020-03-19T22:38:52.000Z | 2022-03-05T22:49:34.000Z | io/database.h | aconstlink/natus | d2123c6e1798bd0771b8a1a05721c68392afc92f | [
"MIT"
] | null | null | null | #pragma once
#include "api.h"
#include "typedefs.h"
#include "handle.h"
#include "monitor.hpp"
#include "obfuscator.hpp"
#include "location.hpp"
#include <natus/concurrent/isleep.hpp>
#include <natus/concurrent/mrsw.hpp>
#include <natus/ntd/vector.hpp>
#include <natus/ntd/filesystem.hpp>
namespace natus
{
namespace io
{
class NATUS_IO_API database
{
natus_this_typedefs( database ) ;
private: // monitoring stuff
natus::concurrent::thread_t _update_thread ;
natus::concurrent::interruptable_sleep_t _isleep ;
public:
typedef std::function< void_t ( char_cptr_t, size_t const ) > load_completion_funk_t ;
private:
// this is the cache of a file record.
// it holds :
// - the load/store handles of an operation
// - the cached data
// - the owner database
// - the index into the databases' file record
struct record_cache ;
natus_res_typedef( record_cache ) ;
friend struct record_cache ;
struct file_record
{
natus::io::location_t location ;
// -1 : invalid
// -2 : external
// otherwise : stored in .natus db file
uint64_t offset = uint64_t( -1 ) ;
uint64_t sib = uint64_t( 0 ) ;
natus::io::path_t rel ;
natus::ntd::filesystem::file_time_type stamp ;
natus::ntd::vector< natus::io::monitor_res_t > monitors ;
// the handle prototype/origin which is copied to the user
record_cache_res_t cache ;
file_record( void_t ) {}
file_record( file_record const & rhv )
{
location = rhv.location ;
offset = rhv.offset ;
sib = rhv.sib ;
rel = rhv.rel ;
stamp = rhv.stamp ;
monitors = rhv.monitors ;
cache = rhv.cache ;
}
file_record( file_record && rhv )
{
location = ::std::move( rhv.location ) ;
offset = rhv.offset ;
sib = rhv.sib ;
rel = ::std::move( rhv.rel ) ;
stamp = ::std::move( rhv.stamp ) ;
monitors = ::std::move( rhv.monitors ) ;
cache = std::move( rhv.cache ) ;
}
~file_record( void_t ) {}
file_record & operator = ( file_record const& rhv ) noexcept
{
location = rhv.location ;
offset = rhv.offset ;
sib = rhv.sib ;
rel = rhv.rel ;
stamp = rhv.stamp ;
monitors = rhv.monitors ;
cache = rhv.cache;
return *this ;
}
file_record & operator = ( file_record&& rhv ) noexcept
{
location = ::std::move( rhv.location ) ;
offset = rhv.offset ;
sib = rhv.sib ;
rel = ::std::move( rhv.rel ) ;
stamp = ::std::move( rhv.stamp ) ;
monitors = ::std::move( rhv.monitors ) ;
cache = std::move( rhv.cache ) ;
return *this ;
}
};
natus_typedef( file_record ) ;
private:
struct file_header
{
// encryption method
// some infos
// start of file records
// number of file records
char_t padding[ 20 ] ;
};
struct db
{
natus::io::path_t base ;
natus::io::path_t working ;
natus::io::path_t name ;
natus::ntd::vector< file_record > records ;
natus::ntd::vector< natus::io::monitor_res_t > monitors ;
size_t offset = 0 ;
db( void_t ) {}
db( db const& rhv ) { *this = rhv ; }
db( db && rhv ) { *this = ::std::move( rhv ) ; }
~db( void_t ) {}
db & operator = ( db const& rhv )
{
base = rhv.base ;
records = rhv.records ;
monitors = rhv.monitors ;
working = rhv.working ;
name = rhv.name ;
offset = rhv.offset ;
return *this ;
}
db & operator = ( db && rhv )
{
base = ::std::move( rhv.base ) ;
records = ::std::move( rhv.records ) ;
monitors = ::std::move( rhv.monitors ) ;
working = ::std::move( rhv.working ) ;
name = ::std::move( rhv.name ) ;
offset = rhv.offset ;
return *this ;
}
};
natus_typedef( db ) ;
db_t _db ;
mutable natus::concurrent::mrsw_t _ac ;
static natus::io::obfuscator_t obfuscator( void_t ) noexcept
{
return natus::io::obfuscator_t::variant_1() ;
}
public:
enum class encryption
{
none
};
// user access for file record
class NATUS_IO_API cache_access
{
natus_this_typedefs( cache_access ) ;
friend class database ;
private:
record_cache_res_t _res ;
cache_access( record_cache_res_t res ) : _res( std::move( res ) ) {}
public:
cache_access( this_cref_t rhv ) noexcept : _res( rhv._res ) {}
cache_access( this_rref_t rhv ) noexcept : _res( std::move( rhv._res ) ) {}
~cache_access( void_t ) noexcept {}
this_ref_t operator = ( this_cref_t rhv ) noexcept { _res = rhv._res ; return *this ; }
this_ref_t operator = ( this_rref_t rhv ) noexcept { _res = std::move(rhv._res) ; return *this ; }
// wait for io operation to be finished or taken from data cache
// if cache exists, it will be preferred. Data cache should be updated
// automatically on file change which will be notified by the monitor.
bool_t wait_for_operation( natus::io::database::load_completion_funk_t funk ) ;
// load the same location.
this_t load( bool_t const reload = false ) noexcept ;
// changes the location of this record cache access.
this_t load( natus::io::location_cref_t loc, bool_t const reload = false ) noexcept ;
};
natus_res_typedef( cache_access ) ;
public:
database( void_t ) ;
database( natus::io::path_cref_t base, natus::io::path_cref_t working_rel = "./",
natus::io::path_cref_t name = "db" ) ;
database( this_cref_t ) = delete ;
database( this_rref_t rhv ) ;
~database( void_t ) ;
this_ref_t operator = ( this_rref_t rhv ) noexcept ;
public:
// gives access to some file system structure
// or to a natus database file.
//
// @param base the base path to the database file
// @param working_rel where the data should be look for/stored at relative to base
// @param name the db file/folder name
//
// Filesystem: /base/name
// Natus File: /base/name.natus
bool_t init( natus::io::path_cref_t base, natus::io::path_cref_t working_rel = "./",
natus::io::path_cref_t name = "db" ) ;
// pack the initialized resource into a natus file
bool_t pack( this_t::encryption const = this_t::encryption::none ) ;
// unpack the initialized resource to a file system
bool_t unpack( void_t ) ;
// store from memory
natus::io::store_handle_t store( natus::ntd::string_cref_t location , char_cptr_t, size_t const ) ;
// load to memory
// @param loc the file location
// @param reload force reload from database( filesystem/ndb file )
this_t::cache_access_t load( natus::io::location_cref_t loc, bool_t const reload = false ) ;
void_t dump_to_std( void_t ) const noexcept ;
public: // monitor
void_t attach( natus::ntd::string_cref_t, natus::io::monitor_res_t ) noexcept ;
void_t detach( natus::ntd::string_cref_t, natus::io::monitor_res_t ) noexcept ;
void_t attach( natus::io::monitor_res_t ) noexcept ;
void_t detach( natus::io::monitor_res_t mon ) noexcept ;
public:
bool_t lookup_extension( natus::ntd::string_cref_t loc, natus::ntd::string_out_t ) const noexcept ;
private:
file_record_t create_file_record( this_t::db_ref_t, natus::io::path_cref_t ) const noexcept;
bool_t lookup( natus::io::location_cref_t loc, file_record_out_t ) const noexcept ;
bool_t lookup( db const & db_, natus::io::location_cref_t loc, file_record_out_t ) const noexcept ;
void_t file_change_stamp( this_t::file_record_cref_t ) noexcept ;
void_t file_remove( this_t::file_record_cref_t ) noexcept ;
void_t file_change_external( this_t::file_record_cref_t ) noexcept ;
static void_t file_change_external( db & db_, this_t::file_record_cref_t ) noexcept ;
natus::io::location_t location_for_index( size_t const ) const ;
private: // monitor
void_t spawn_update( void_t ) noexcept ;
void_t join_update( void_t ) noexcept ;
private:
void_t load_db_file( db & db_, natus::io::path_cref_t ) ;
};
natus_res_typedef( database ) ;
}
}
| 35.743151 | 114 | 0.49497 | [
"vector"
] |
6bb4d4419849a1a364f10d72384ae75b1ff49356 | 2,472 | c | C | student-distrib/exception.c | TaKeTube/TLEOS | b0cd42edecae5103cacb4e6f66506e05f212a25e | [
"AFL-1.1"
] | null | null | null | student-distrib/exception.c | TaKeTube/TLEOS | b0cd42edecae5103cacb4e6f66506e05f212a25e | [
"AFL-1.1"
] | null | null | null | student-distrib/exception.c | TaKeTube/TLEOS | b0cd42edecae5103cacb4e6f66506e05f212a25e | [
"AFL-1.1"
] | null | null | null | #include "lib.h"
#include "exception.h"
#include "syscall.h"
void exc_handler(unsigned int vec);
/* string array contains exception message */
static char* exception_info[EXC_NUM] = {
"Division by zero",
"Single-step interrupt",
"NMI",
"Breakpoint",
"Overflow",
"Bounds",
"Invalid Opcode",
"Coprocessor not available",
"Double fault",
"Coprocessor Segment Overrun",
"Invalid Task State Segment",
"Segment not present",
"Stack Fault",
"General protection fault",
"Page fault",
"reserved",
"Math Fault",
"Alignment Check",
"Machine Check",
"SIMD Floating-Point Exception"
};
/*
* exc_handler
* DESCRIPTION: exception handler, print out the exception info
* INPUTS: vec -- corresponding exception
* OUTPUTS: none
* RETURN VALUE: none
* SIDE EFFECTS: none
*/
void exc_handler(unsigned int vec){
if(vec >= EXC_NUM)
return;
cli();
printf("EXCEPTION %d:\n", vec);
printf("%s\n", exception_info[vec]);
/* halt the current program if there is */
if(cur_fd_array != NULL)
halt(HALT_EXCEPTION);
/* end with infinite loop according to the document */
while(1);
}
/* handler for exceptions in Linux */
/* just print out the exception corresponding to the interrupt vector */
void exc_divide_error() {exc_handler(0x00);}
void exc_single_step() {exc_handler(0x01);}
void exc_nmi() {exc_handler(0x02);}
void exc_breakpoint() {exc_handler(0x03);}
void exc_overflow() {exc_handler(0x04);}
void exc_bounds() {exc_handler(0x05);}
void exc_invalid_opcode() {exc_handler(0x06);}
void exc_coprocessor_not_avaliable() {exc_handler(0x07);}
void exc_double_fault() {exc_handler(0x08);}
void exc_coprocessor_segment_fault() {exc_handler(0x09);}
void exc_invalid_tss() {exc_handler(0x0A);}
void exc_segment_not_present() {exc_handler(0x0B);}
void exc_stack_fault() {exc_handler(0x0C);}
void exc_general_protection_fault() {exc_handler(0x0D);}
void exc_page_fault() {exc_handler(0x0E);}
void exc_reserved() {exc_handler(0x0F);}
void exc_math_fault() {exc_handler(0x10);}
void exc_alignment_check() {exc_handler(0x11);}
void exc_machine_check() {exc_handler(0x12);}
void exc_simd_floating_point() {exc_handler(0x13);}
| 33.405405 | 72 | 0.635922 | [
"vector"
] |
6bb98cbf3dfe6e86425918bc9dcb55c7d46be36a | 3,838 | h | C | include/openthread/openthread.h | jjlee3/openthread | abba21bca6e1b07ca76b0241dfaf045e57396818 | [
"BSD-3-Clause"
] | 3 | 2018-06-20T11:13:33.000Z | 2020-12-08T15:15:10.000Z | include/openthread/openthread.h | jjlee3/openthread | abba21bca6e1b07ca76b0241dfaf045e57396818 | [
"BSD-3-Clause"
] | null | null | null | include/openthread/openthread.h | jjlee3/openthread | abba21bca6e1b07ca76b0241dfaf045e57396818 | [
"BSD-3-Clause"
] | 3 | 2017-08-29T01:31:57.000Z | 2020-05-07T22:56:52.000Z | /*
* Copyright (c) 2016, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* @brief
* This file defines the top-level functions for the OpenThread library.
*/
#ifndef OPENTHREAD_H_
#define OPENTHREAD_H_
#include "openthread/types.h"
#include "openthread/crypto.h"
#include "openthread/dataset.h"
#include "openthread/instance.h"
#include "openthread/ip6.h"
#include "openthread/link.h"
#include "openthread/message.h"
#include "openthread/netdata.h"
#include "openthread/tasklet.h"
#include "openthread/thread.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @defgroup api API
* @brief
* This module includes the application programming interface to the OpenThread stack.
*
* @{
*
* @defgroup execution Execution
* @defgroup commands Commands
* @defgroup config Configuration
* @defgroup diags Diagnostics
* @defgroup messages Message Buffers
* @defgroup ip6 IPv6
* @defgroup udp UDP
* @defgroup coap CoAP
*
* @}
*
*/
/**
* @defgroup platform Platform Abstraction
* @brief
* This module includes the platform abstraction used by the OpenThread stack.
*
* @{
* @}
*
*/
/**
* @defgroup core Core
* @brief
* This module includes the core OpenThread stack.
*
* @{
*
* @defgroup core-6lowpan 6LoWPAN
* @defgroup core-coap CoAP
* @defgroup core-global-address Global IPv6 Address
* @defgroup core-ipv6 IPv6
* @defgroup core-mac MAC
* @defgroup core-mesh-forwarding Mesh Forwarding
* @defgroup core-message Message
* @defgroup core-mle MLE
* @defgroup core-netdata Network Data
* @defgroup core-netif Network Interface
* @defgroup core-arp RLOC Mapping
* @defgroup core-security Security
* @defgroup core-tasklet Tasklet
* @defgroup core-timer Timer
* @defgroup core-udp UDP
* @defgroup core-tcp TCP
* @defgroup core-link-quality Link Quality
*
* @}
*
*/
/**
* Get the OpenThread version string.
*
* @returns A pointer to the OpenThread version.
*
*/
OTAPI const char *OTCALL otGetVersionString(void);
/**
* This function converts a ThreadError enum into a string.
*
* @param[in] aError A ThreadError enum.
*
* @returns A string representation of a ThreadError.
*
*/
OTAPI const char *OTCALL otThreadErrorToString(ThreadError aError);
#ifdef __cplusplus
} // extern "C"
#endif
#endif // OPENTHREAD_H_
| 28.014599 | 88 | 0.729807 | [
"mesh"
] |
6bb996378979edd63bcf64bc8e6ed4df8f4d22c8 | 5,221 | h | C | include/libcotask/core/standard_new_allocator.h | xiaoweiChen/libcopp | 73efa089bab674c7858308c93803d40ff4cbb66e | [
"BSL-1.0",
"MIT"
] | 1 | 2021-02-10T15:29:46.000Z | 2021-02-10T15:29:46.000Z | include/libcotask/core/standard_new_allocator.h | xiaoweiChen/libcopp | 73efa089bab674c7858308c93803d40ff4cbb66e | [
"BSL-1.0",
"MIT"
] | null | null | null | include/libcotask/core/standard_new_allocator.h | xiaoweiChen/libcopp | 73efa089bab674c7858308c93803d40ff4cbb66e | [
"BSL-1.0",
"MIT"
] | null | null | null | /**
* standard_new_allocator.h
*
* Created on: 2014年4月1日
* Author: owent
* @date 2017-05-10
* Released under the MIT license
*/
#ifndef COTASK_CORE_STANDARD_NEW_ALLOCATOR_H
#define COTASK_CORE_STANDARD_NEW_ALLOCATOR_H
#pragma once
#include <libcopp/utils/features.h>
#include <libcopp/utils/std/smart_ptr.h>
namespace cotask {
namespace core {
class standard_new_allocator {
public:
#if defined(COPP_MACRO_ENABLE_VARIADIC_TEMPLATE) && COPP_MACRO_ENABLE_VARIADIC_TEMPLATE
/**
* @brief allocate a object
* @param args construct parameters
* @return pointer of new object
*/
template <typename Ty, typename... TARGS>
static std::shared_ptr<Ty> allocate(Ty *, TARGS COPP_MACRO_RV_REF... args) {
return COPP_MACRO_STD_MOVE(std::make_shared<Ty>(COPP_MACRO_STD_FORWARD(TARGS, args)...));
}
#else
/**
* @brief allocate a object with 0 parameter(s).
* @return pointer of new object
*/
template <typename Ty>
static std::shared_ptr<Ty> allocate(Ty *) {
return COPP_MACRO_STD_MOVE(std::make_shared<Ty>());
}
/**
* @brief allocate a object with 1 parameter(s).
* @param arg0 parameter 0
* @return pointer of new object
*/
template <typename Ty, typename TARG0>
static std::shared_ptr<Ty> allocate(Ty *, TARG0 COPP_MACRO_RV_REF arg0) {
return COPP_MACRO_STD_MOVE(std::make_shared<Ty>(COPP_MACRO_STD_FORWARD(TARG0, arg0)));
}
/**
* @brief allocate a object with 2 parameter(s).
* @param arg0 parameter 0
* @param arg1 parameter 1
* @return pointer of new object
*/
template <typename Ty, typename TARG0, typename TARG1>
static std::shared_ptr<Ty> allocate(Ty *, TARG0 COPP_MACRO_RV_REF arg0, TARG1 COPP_MACRO_RV_REF arg1) {
return COPP_MACRO_STD_MOVE(std::make_shared<Ty>(COPP_MACRO_STD_FORWARD(TARG0, arg0), COPP_MACRO_STD_FORWARD(TARG1, arg1)));
}
/**
* @brief allocate a object with 3 parameter(s).
* @param arg0 parameter 0
* @param arg1 parameter 1
* @param arg2 parameter 2
* @return pointer of new object
*/
template <typename Ty, typename TARG0, typename TARG1, typename TARG2>
static std::shared_ptr<Ty> allocate(Ty *, TARG0 COPP_MACRO_RV_REF arg0, TARG1 COPP_MACRO_RV_REF arg1,
TARG2 COPP_MACRO_RV_REF arg2) {
return COPP_MACRO_STD_MOVE(std::make_shared<Ty>(COPP_MACRO_STD_FORWARD(TARG0, arg0), COPP_MACRO_STD_FORWARD(TARG1, arg1),
COPP_MACRO_STD_FORWARD(TARG2, arg2)));
}
/**
* @brief allocate a object with 4 parameter(s).
* @param arg0 parameter 0
* @param arg1 parameter 1
* @param arg2 parameter 2
* @param arg3 parameter 3
* @return pointer of new object
*/
template <typename Ty, typename TARG0, typename TARG1, typename TARG2, typename TARG3>
static std::shared_ptr<Ty> allocate(Ty *, TARG0 COPP_MACRO_RV_REF arg0, TARG1 COPP_MACRO_RV_REF arg1,
TARG2 COPP_MACRO_RV_REF arg2, TARG3 COPP_MACRO_RV_REF arg3) {
return COPP_MACRO_STD_MOVE(std::make_shared<Ty>(COPP_MACRO_STD_FORWARD(TARG0, arg0), COPP_MACRO_STD_FORWARD(TARG1, arg1),
COPP_MACRO_STD_FORWARD(TARG2, arg2), COPP_MACRO_STD_FORWARD(TARG3, arg3)));
}
/**
* @brief allocate a object with 5 parameter(s).
* @param arg0 parameter 0
* @param arg1 parameter 1
* @param arg2 parameter 2
* @param arg3 parameter 3
* @param arg4 parameter 4
* @return pointer of new object
*/
template <typename Ty, typename TARG0, typename TARG1, typename TARG2, typename TARG3, typename TARG4>
static std::shared_ptr<Ty> allocate(Ty *, TARG0 COPP_MACRO_RV_REF arg0, TARG1 COPP_MACRO_RV_REF arg1,
TARG2 COPP_MACRO_RV_REF arg2, TARG3 COPP_MACRO_RV_REF arg3, TARG4 COPP_MACRO_RV_REF arg4) {
return COPP_MACRO_STD_MOVE(std::make_shared<Ty>(COPP_MACRO_STD_FORWARD(TARG0, arg0), COPP_MACRO_STD_FORWARD(TARG1, arg1),
COPP_MACRO_STD_FORWARD(TARG2, arg2), COPP_MACRO_STD_FORWARD(TARG3, arg3),
COPP_MACRO_STD_FORWARD(TARG4, arg4)));
}
#endif
template <typename Ty>
static void deallocate(std::shared_ptr<Ty> &pt) {}
};
}
}
#endif /* STANDARD_NEW_ALLOCATOR_H_ */
| 43.87395 | 139 | 0.562919 | [
"object"
] |
6bba08e5077144201aade4dfb33a6879ece74947 | 6,439 | h | C | Pods/XLsn0wKit_objc/XLsn0wKit/XLsn0wComponents/XLsn0wSegmentedBar/XLsn0wSegmentedBar.h | XLsn0w/XLsn0wMapKit | 78fbee844a0f61c0e557e5d98a7e80d3be26ec1d | [
"MIT"
] | 4 | 2019-04-03T08:04:53.000Z | 2021-07-08T07:48:48.000Z | Pods/XLsn0wKit_objc/XLsn0wKit/XLsn0wComponents/XLsn0wSegmentedBar/XLsn0wSegmentedBar.h | XLsn0w/XLsn0wMapKit | 78fbee844a0f61c0e557e5d98a7e80d3be26ec1d | [
"MIT"
] | null | null | null | Pods/XLsn0wKit_objc/XLsn0wKit/XLsn0wComponents/XLsn0wSegmentedBar/XLsn0wSegmentedBar.h | XLsn0w/XLsn0wMapKit | 78fbee844a0f61c0e557e5d98a7e80d3be26ec1d | [
"MIT"
] | 2 | 2019-12-27T06:53:38.000Z | 2020-01-29T07:32:55.000Z | /*********************************************************************************************
* __ __ _ _________ _ _ _ _________ __ _ __ *
* \ \ / / | | | _______| | | \ | | | ______ | \ \ / \ / / *
* \ \ / / | | | | | |\ \ | | | | | | \ \ / \ \ / / *
* \ \/ / | | | |______ | | \ \ | | | | | | \ \ / / \ \ / / *
* /\/\/\ | | |_______ | | | \ \| | | | | | \ \ / / \ \ / / *
* / / \ \ | |______ ______| | | | \ \ | | |_____| | \ \ / \ \ / *
* /_/ \_\ |________| |________| |_| \__| |_________| \_/ \_/ *
* *
*********************************************************************************************/
#import <UIKit/UIKit.h>
@class XLsn0wSegmentedView;
@class XLsn0wSegmentedBar;
@protocol XLsn0wSegmentedBarDelegate <NSObject>
- (void)segmentedBar:(XLsn0wSegmentedBar *)segmentedBar didSelectAtIndex:(NSInteger)index;
@end
@interface XLsn0wSegmentedBar : UIView
@property (nonatomic, weak) id<XLsn0wSegmentedBarDelegate> xlsn0wDelegate;
@property (strong, nonatomic) XLsn0wSegmentedView *xlsn0wSegmentedView;
@property (strong, nonatomic) UIScrollView *bottomScrollView;
/*! 初始化前必须添加此行代码 self.automaticallyAdjustsScrollViewInsets = NO;//自动滚动调整,默认为YES */
- (instancetype)initWithFrame:(CGRect)frame titleArray:(NSArray *)titleArray subviewArray:(NSArray *)subviewArray;
@end
/*********************************************************************************************
* __ __ _ _________ _ _ _ _________ __ _ __ *
* \ \ / / | | | _______| | | \ | | | ______ | \ \ / \ / / *
* \ \ / / | | | | | |\ \ | | | | | | \ \ / \ \ / / *
* \ \/ / | | | |______ | | \ \ | | | | | | \ \ / / \ \ / / *
* /\/\/\ | | |_______ | | | \ \| | | | | | \ \ / / \ \ / / *
* / / \ \ | |______ ______| | | | \ \ | | |_____| | \ \ / \ \ / *
* /_/ \_\ |________| |________| |_| \__| |_________| \_/ \_/ *
* *
*********************************************************************************************/
#import <QuartzCore/QuartzCore.h>
typedef void(^btnClickBlock)(NSInteger index);
@interface XLsn0wSegmentedView : UIView
/**
* 是否开启下划线动画 默认开启
*/
@property (nonatomic, assign) BOOL isLoadAnimation;
/**
* 未选中时的文字颜色,默认黑色
*/
@property (nonatomic,strong) UIColor *titleNomalColor;
/**
* 选中时的文字颜色,默认红色
*/
@property (nonatomic,strong) UIColor *titleSelectColor;
/**
* 字体大小,默认15
*/
@property (nonatomic,strong) UIFont *titleFont;
/**
* 默认选中的index=1,即第一个
*/
@property (nonatomic,assign) NSInteger defaultIndex;
/**
* 点击后的block
*/
@property (nonatomic,copy)btnClickBlock block;
/**
* 初始化方法
*
* @param frame frame
* @param titleArray 传入数组
* @param block 点击后的回调
*/
-(instancetype)initWithFrame:(CGRect)frame titles:(NSArray *)titleArray clickBlick:(btnClickBlock)block;
-(void)updateselectLineFrameWithoffset:(CGFloat)offsetx;
@end
/**************************************************************************************************/
@interface CALayer (XLsn0wSegmentedBar)
@property (nonatomic) CGFloat left; ///< Shortcut for frame.origin.x.
@property (nonatomic) CGFloat top; ///< Shortcut for frame.origin.y
@property (nonatomic) CGFloat right; ///< Shortcut for frame.origin.x + frame.size.width
@property (nonatomic) CGFloat bottom; ///< Shortcut for frame.origin.y + frame.size.height
@property (nonatomic) CGFloat width; ///< Shortcut for frame.size.width.
@property (nonatomic) CGFloat height; ///< Shortcut for frame.size.height.
@property (nonatomic) CGPoint center; ///< Shortcut for center.
@property (nonatomic) CGFloat centerX; ///< Shortcut for center.x
@property (nonatomic) CGFloat centerY; ///< Shortcut for center.y
@property (nonatomic) CGPoint origin; ///< Shortcut for frame.origin.
@property (nonatomic, getter=frameSize, setter=setFrameSize:) CGSize size; ///< Shortcut for frame.size.
/**
* 旋转
*/
@property (nonatomic) CGFloat transformRotation; ///< key path "transform.rotation"
@property (nonatomic) CGFloat transformRotationX; ///< key path "transform.rotation.x"
@property (nonatomic) CGFloat transformRotationY; ///< key path "transform.rotation.y"
@property (nonatomic) CGFloat transformRotationZ; ///< key path "transform.rotation.z"
/**
* 缩放
*/
@property (nonatomic) CGFloat transformScale; ///< key path "transform.scale"
@property (nonatomic) CGFloat transformScaleX; ///< key path "transform.scale.x"
@property (nonatomic) CGFloat transformScaleY; ///< key path "transform.scale.y"
@property (nonatomic) CGFloat transformScaleZ; ///< key path "transform.scale.z"
/**
* 平移
*/
@property (nonatomic) CGFloat transformTranslationX; ///< key path "transform.translation.x"
@property (nonatomic) CGFloat transformTranslationY; ///< key path "transform.translation.y"
@property (nonatomic) CGFloat transformTranslationZ; ///< key path "transform.translation.z"
@end
/**************************************************************************************************/
@interface NSString (XLsn0wSegmentedBar)
/**
* @brief 计算文字的高度
*
* @param font 字体(默认为系统字体)
* @param width 约束宽度
*/
- (CGFloat)heightWithFont:(UIFont *)font constrainedToWidth:(CGFloat)width;
/**
* @brief 计算文字的宽度
*
* @param font 字体(默认为系统字体)
* @param height 约束高度
*/
- (CGFloat)widthWithFont:(UIFont *)font constrainedToHeight:(CGFloat)height;
/**
* @brief 计算文字的大小
*
* @param font 字体(默认为系统字体)
* @param width 约束宽度
*/
- (CGSize)sizeWithFont:(UIFont *)font constrainedToWidth:(CGFloat)width;
/**
* @brief 计算文字的大小
*
* @param font 字体(默认为系统字体)
* @param height 约束高度
*/
- (CGSize)sizeWithFont:(UIFont *)font constrainedToHeight:(CGFloat)height;
/**
* @brief 反转字符串
*
* @param strSrc 被反转字符串
*
* @return 反转后字符串
*/
+ (NSString *)reverseString:(NSString *)strSrc;
@end
| 35.574586 | 114 | 0.513744 | [
"transform"
] |
6bbd63fe6f70c67496cb938b2e3b5386eedc5287 | 849 | h | C | BlackVision/LibBlackVision/Source/Engine/Models/Plugins/Channels/Geometry/IndexChannelDescriptor.h | black-vision-engine/bv-engine | 85089d41bb22afeaa9de070646e12aa1777ecedf | [
"MIT"
] | 1 | 2022-01-28T11:43:47.000Z | 2022-01-28T11:43:47.000Z | BlackVision/LibBlackVision/Source/Engine/Models/Plugins/Channels/Geometry/IndexChannelDescriptor.h | black-vision-engine/bv-engine | 85089d41bb22afeaa9de070646e12aa1777ecedf | [
"MIT"
] | null | null | null | BlackVision/LibBlackVision/Source/Engine/Models/Plugins/Channels/Geometry/IndexChannelDescriptor.h | black-vision-engine/bv-engine | 85089d41bb22afeaa9de070646e12aa1777ecedf | [
"MIT"
] | null | null | null | #pragma once
#include <string>
#include "Engine/Models/Plugins/Interfaces/IIndexChannelDescriptor.h"
namespace bv { namespace model
{
class IndexChannelDescriptor : public IIndexChannelDescriptor
{
private:
static const int m_sIdxSizes[ (int) IndexType::IT_TOTAL ];
IndexType m_indexType;
public:
IndexChannelDescriptor ( IndexType type );
virtual ~IndexChannelDescriptor ();
virtual IndexType GetType () const;
virtual int GetIndexSize () const;
std::string SuggestedDefaultName () const;
static int IndexSize ( IndexType type );
static std::string DefaultName ( IndexType type );
};
} //model
} //bv
| 22.945946 | 72 | 0.555948 | [
"model"
] |
6bbdd65dc6006172c68b59f30d8002bf226545e8 | 2,665 | h | C | code/components/voip-mumble/include/MumbleAudioInput.h | coverxit/wl-fivem | 9ad4559106c0ef17c5a53c198ceae662eb264455 | [
"MIT"
] | 2 | 2021-01-26T01:56:40.000Z | 2021-10-10T15:30:39.000Z | code/components/voip-mumble/include/MumbleAudioInput.h | coverxit/wl-fivem | 9ad4559106c0ef17c5a53c198ceae662eb264455 | [
"MIT"
] | 1 | 2021-09-10T21:44:58.000Z | 2021-09-10T21:44:58.000Z | code/components/voip-mumble/include/MumbleAudioInput.h | coverxit/wl-fivem | 9ad4559106c0ef17c5a53c198ceae662eb264455 | [
"MIT"
] | 22 | 2018-11-17T17:19:01.000Z | 2021-05-22T09:51:07.000Z | /*
* This file is part of the CitizenFX project - http://citizen.re/
*
* See LICENSE and MENTIONS in the root of the source tree for information
* regarding licensing.
*/
#pragma once
#include <thread>
#include <wrl.h>
#include <audioclient.h>
#include <mmdeviceapi.h>
extern "C"
{
#include <libswresample/swresample.h>
#include <libavutil/mem.h>
#include <libavutil/opt.h>
#include <libavutil/mathematics.h>
#include <libavutil/samplefmt.h>
};
#include <webrtc/modules/audio_processing/include/audio_processing.h>
#include <webrtc/modules/interface/module_common_types.h>
#include <webrtc/system_wrappers/include/trace.h>
#include <opus.h>
#include <queue>
#include "MumbleClient.h"
using namespace Microsoft::WRL;
class MumbleClient;
class MumbleAudioInput
{
private:
std::thread m_thread;
ComPtr<IMMDeviceEnumerator> m_mmDeviceEnumerator;
ComPtr<IAudioClient> m_audioClient;
ComPtr<IAudioCaptureClient> m_audioCaptureClient;
WAVEFORMATEX m_waveFormat;
HANDLE m_startEvent;
SwrContext* m_avr;
webrtc::AudioProcessing* m_apm;
uint8_t* m_resampledBytes;
uint32_t m_cachedLen;
uint8_t m_cachedBytes[512 * 1024];
uint8_t m_encodedBytes[65536];
OpusEncoder* m_opus;
std::queue<std::string> m_opusPackets;
uint64_t m_sequence;
MumbleClient* m_client;
MumbleActivationMode m_mode;
MumbleVoiceLikelihood m_likelihood;
bool m_isTalking;
bool m_ptt;
std::string m_deviceId;
float m_positionX;
float m_positionY;
float m_positionZ;
float m_audioLevel;
std::vector<uint8_t> m_audioBuffer;
private:
static void ThreadStart(MumbleAudioInput* instance);
void ThreadFunc();
void InitializeAudioDevice();
HRESULT HandleIncomingAudio();
void HandleData(const uint8_t* buffer, size_t numBytes);
void EnqueueOpusPacket(std::string packet);
void SendQueuedOpusPackets();
inline void SetInputFormat(WAVEFORMATEX* waveFormat) { m_waveFormat = *waveFormat; }
public:
MumbleAudioInput();
void Initialize();
void Enable();
void SetActivationMode(MumbleActivationMode mode);
void SetActivationLikelihood(MumbleVoiceLikelihood likelihood);
void SetPTTButtonState(bool pressed);
void SetAudioDevice(const std::string& dsoundDeviceId);
inline bool IsTalking()
{
return m_isTalking;
}
inline float GetAudioLevel()
{
return m_audioLevel;
}
inline void SetPosition(float position[3])
{
m_positionX = position[0];
m_positionY = position[1];
m_positionZ = position[2];
}
inline void SetClient(MumbleClient* client) { m_client = client; }
};
| 18.900709 | 86 | 0.725704 | [
"vector"
] |
5f957a7f0b15233243456aed53ffeb7cc72fa383 | 982 | h | C | examples/CBuilder/Compound/ModelEvolution/Version1/dModel.h | LenakeTech/BoldForDelphi | 3ef25517d5c92ebccc097c6bc2f2af62fc506c71 | [
"MIT"
] | 121 | 2020-09-22T10:46:20.000Z | 2021-11-17T12:33:35.000Z | examples/CBuilder/Compound/ModelEvolution/Version1/dModel.h | LenakeTech/BoldForDelphi | 3ef25517d5c92ebccc097c6bc2f2af62fc506c71 | [
"MIT"
] | 8 | 2020-09-23T12:32:23.000Z | 2021-07-28T07:01:26.000Z | examples/CBuilder/Compound/ModelEvolution/Version1/dModel.h | LenakeTech/BoldForDelphi | 3ef25517d5c92ebccc097c6bc2f2af62fc506c71 | [
"MIT"
] | 42 | 2020-09-22T14:37:20.000Z | 2021-10-04T10:24:12.000Z | //---------------------------------------------------------------------------
#ifndef dModelH
#define dModelH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include "BoldAbstractModel.hpp"
#include "BoldHandle.hpp"
#include "BoldModel.hpp"
#include "BoldSubscription.hpp"
#include "BoldUMLModelLink.hpp"
#include "BoldUMLRose98Link.hpp"
//---------------------------------------------------------------------------
class TdmModel : public TDataModule
{
__published: // IDE-managed Components
TBoldModel *Model;
TBoldUMLRose98Link *BoldUMLRose98Link1;
private: // User declarations
public: // User declarations
__fastcall TdmModel(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TdmModel *dmModel;
//---------------------------------------------------------------------------
#endif
| 32.733333 | 77 | 0.470468 | [
"model"
] |
5f96e4f601e2fcbbfbb4feca8df9b4d065e1eb15 | 7,784 | h | C | include/circuits/GarbledBooleanCircuitFixedKey.h | cryptobiu/libscapi | 49eee7aee9eb3544a7facb199d0a6e98097b058a | [
"MIT"
] | 160 | 2016-05-11T09:45:56.000Z | 2022-03-06T09:32:19.000Z | include/circuits/GarbledBooleanCircuitFixedKey.h | cryptobiu/libscapi | 49eee7aee9eb3544a7facb199d0a6e98097b058a | [
"MIT"
] | 57 | 2016-12-26T07:02:12.000Z | 2022-03-06T16:34:31.000Z | include/circuits/GarbledBooleanCircuitFixedKey.h | cryptobiu/libscapi | 49eee7aee9eb3544a7facb199d0a6e98097b058a | [
"MIT"
] | 67 | 2016-10-10T17:56:22.000Z | 2022-03-15T22:56:39.000Z | /**
* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*
* Copyright (c) 2016 LIBSCAPI (http://crypto.biu.ac.il/SCAPI)
* This file is part of the SCAPI project.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* 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.
*
* We request that any publication and/or code referring to and/or based on SCAPI contain an appropriate citation to SCAPI, including a reference to
* http://crypto.biu.ac.il/SCAPI.
*
* Libscapi uses several open source libraries. Please see these projects for any further licensing issues.
* For more information , See https://github.com/cryptobiu/libscapi/blob/master/LICENSE.MD
*
* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
*
*/
#pragma once
#include "Config.h"
#include "TedKrovetzAesNiWrapperC.h"
#include "GarbledBooleanCircuit.h"
struct GarbledGate;
/*
* GarbledBooleanCircuit is a general abstract class for garbled circuits with fixed key.
* All garbled circuits have four main operations:
* 1. The garble function that creates the garbled table
* 2. The compute function that computes a result on a garbled circuit on the input which is the keys that were chosen for each input wire.
* 3. The verify method is used in the case of a malicious adversary to verify that the garbled circuit
* created is an honest garbling of the agreed upon non garbled circuit.
* 4. The translate method that translates the garbled output which usually is generated by the compute() function into meaningful output (a 0/1 result, rather
* than the keys outputed by compute)
*
* author: Cryptography and Computer Security Research Group Department of Computer Science Bar-Ilan University (Meital Levy)
*
*/
class GarbledBooleanCircuitFixedKey :
public GarbledBooleanCircuit
{
public:
/**
* This method computes the circuit for the given input singleWiresInputKeys.
* It returns a the garbled values keys for the output wires. This output can be translated via the translate() method
* if the translation table is set.
*/
void compute(block *singleWiresInputKeys,block * Output) override;
/**
* This is a virtual function that is implemented in the derived classes due to many changes in each derived class.
* This function behaves exactly as the verify method except the last phase.
* The verify function verifies that the translation table matches the resulted output garbled values, while this function does not, rather,
* it returns the resulted output garbled values.
*
* bothWiresInputKeys : both keys for each input wire. This array must be filled with both input keys
* emptyBothWireOutputKeys :T his array will be filled with both output keys during the process of the function. It must be empty.
*
* returns : true if this GarbledBooleanCircuit is a garbling the given keys, false otherwise.
*/
//virtual bool internalVerify(block *bothWiresInputKeys, block *emptyBothWireOutputKeys) = 0;
protected:
bool isFreeXor;//A flag indicating if the user wants to use the optimization of FreeXor.
block fixedKey;//fixed-key AES used for the garbling process. This will be hardcoded unless the user changes it. The fixed key
//optimization reduses the number of the costly setKey function of the AES prp and thus optimize the performance.
AES_KEY aesFixedKey;//We use a pointer since new with 32 bit does not 16-align the variable by default
int numOfRows;//number of rows
public:
GarbledBooleanCircuitFixedKey(void);
virtual ~GarbledBooleanCircuitFixedKey(void) {};
bool getIsNonXorOutputsRequired() const{ return isNonXorOutputsRequired; };
int getNumOfRows() const { return numOfRows; };
virtual int getGarbledTableSize() override;
protected:
/**
* Reads a file and fill the gates, number of parties, input indices, output indices and so on.
* In addition initializes the member variables such as isFreeXor, isRowReduction and other variables that are set to nullptr.
* It uses a fixed pre-defined fixed key and initializes the object accordingly.
* It also allocates memory according to the circuit it creates, such as computedWires, garbledWires and so on. This
* is done in the construction, rather than in the relevant function to reduce cache misses.
*/
void createCircuit(const char * fileName, bool isFreeXor, bool isNonXorOutputsRequired) override;
/*
* In some cases it is important that the output keys of each wire will not all have the same fixed delta xor
* between the 0-wire and the 1-wire (for example when the (constructor of the circuit) garbler needs to send both outputs
* to the party that computes the circuit, if the delta is the same it breaks the security since the delta of the
* the entire circuit is revealed.
*
* This function garbles the output keys using identity gates, the computing party will need to use the version
* that decrypts these identity gates by turning the flag isNonXorOutputsRequired to true.
* Garble calls this function only when this flag is true.
*/
void garbleOutputWiresToNoFixedDelta(block *deltaFreeXor, int nonXorIndex, block *emptyBothOutputKeys);
/*
* In some cases it is important that the output keys of each wire will not all have the same fixed delta xor
* between the 0-wire and the 1-wire (for example when the (constructor of the circuit) garbler needs to send the both outputs
* to the party that computes the circuit, if the delta is the same it breaks the security since the delta of the
* the entire circuit is revealed.
*
* This function computes the identity gates that the garbeler had created.
*/
void computeOutputWiresToNoFixedDelta(int nonXorIndex, block * Output);
/*
* In some cases it is important that the output keys of each wire will not all have the same fixed delta xor
* between the 0-wire and the 1-wire (for example when the (constructor of the circuit) garbler needs to send the both outputs
* to the party that computes the circuit, if the delta is the same it breaks the security since the delta of the
* the entire circuit is revealed.
*
* This function just turns the keys with fixed delta between them to the keys without delta using the seed in the same way that
* the garble function does. It does not create a garbled table for thes identity gates since there is no use.
* The last verification will be done in verifyTranslationTable that makes sure that the new outputs with no fixed delta
* have signal bits matching the corresponding bit in the translation table.
*/
void verifyOutputWiresToNoFixedDelta(block *bothOutputsKeys);
}; | 51.893333 | 161 | 0.741264 | [
"object"
] |
5f9abb8a7303a44302b9c50c2dc7a75e41ca1b2f | 1,989 | h | C | plugins/robots/generators/trik/trikGeneratorBase/include/trikGeneratorBase/trikGeneratorPluginBase.h | ladaegorova18/trik-studio | f8d9ce50301fd93c948ac774e85c0e6bfff820bc | [
"Apache-2.0"
] | 17 | 2019-06-04T06:22:47.000Z | 2022-02-11T18:27:25.000Z | plugins/robots/generators/trik/trikGeneratorBase/include/trikGeneratorBase/trikGeneratorPluginBase.h | ladaegorova18/trik-studio | f8d9ce50301fd93c948ac774e85c0e6bfff820bc | [
"Apache-2.0"
] | 1,248 | 2019-02-21T19:32:09.000Z | 2022-03-29T16:50:04.000Z | plugins/robots/generators/trik/trikGeneratorBase/include/trikGeneratorBase/trikGeneratorPluginBase.h | khodand/trik-studio | 3d2de6809d38b621433c7ccb1cd98da8868d022d | [
"Apache-2.0"
] | 17 | 2019-02-12T07:58:23.000Z | 2022-03-10T11:39:21.000Z | /* Copyright 2007-2015 QReal Research Group
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. */
#pragma once
#include <QtCore/QScopedPointer>
#include <generatorBase/robotsGeneratorPluginBase.h>
#include "trikGeneratorBase/trikGeneratorBaseDeclSpec.h"
namespace trik {
namespace robotModel {
class TrikGeneratorRobotModel;
}
/// A base class for every generator from the TRIK kit.
class ROBOTS_TRIK_GENERATOR_BASE_EXPORT TrikGeneratorPluginBase : public generatorBase::RobotsGeneratorPluginBase
{
Q_OBJECT
public:
TrikGeneratorPluginBase(kitBase::robotModel::RobotModelInterface * const robotModel
, const QSharedPointer<kitBase::blocksBase::BlocksFactoryInterface> &blocksFactory
);
~TrikGeneratorPluginBase() override;
QList<kitBase::robotModel::RobotModelInterface *> robotModels() override;
QSharedPointer<kitBase::blocksBase::BlocksFactoryInterface> blocksFactoryFor(
const kitBase::robotModel::RobotModelInterface *model) override;
QList<kitBase::AdditionalPreferences *> settingsWidgets() override;
protected:
void regenerateExtraFiles(const QFileInfo &newFileInfo) override;
/// Provides access to robot model to descendant classes.
kitBase::robotModel::RobotModelInterface &robotModel() const;
private:
/// Robot model that is used to query information about various robot devices.
QScopedPointer<kitBase::robotModel::RobotModelInterface> mRobotModel;
QSharedPointer<kitBase::blocksBase::BlocksFactoryInterface> mBlocksFactory;
};
}
| 32.080645 | 113 | 0.793363 | [
"model"
] |
5f9f90aee8c79d83afb73d47bfc030cb915a466e | 7,046 | h | C | cvpp_contrib/projects/temporal3d/src/cnn_hilbert/aux_loads.h | nicolasrosa/Sparse-to-Continuous | 8664de17d6b6c6cc39bf8fcebfcb829249367f2f | [
"BSD-2-Clause"
] | 19 | 2018-09-25T01:58:13.000Z | 2021-07-27T09:54:36.000Z | cvpp_contrib/projects/temporal3d/src/cnn_hilbert/aux_loads.h | nicolasrosa/Sparse-to-Continuous | 8664de17d6b6c6cc39bf8fcebfcb829249367f2f | [
"BSD-2-Clause"
] | 18 | 2020-03-24T18:18:56.000Z | 2022-02-10T00:35:13.000Z | cvpp_contrib/projects/temporal3d/src/cnn_hilbert/aux_loads.h | nicolasrosa/Sparse-to-Continuous | 8664de17d6b6c6cc39bf8fcebfcb829249367f2f | [
"BSD-2-Clause"
] | 4 | 2019-11-14T02:35:34.000Z | 2020-08-27T11:36:02.000Z |
#include <dirent.h>
#include <sys/types.h>
#include <cvpp/containers/matrix.h>
#include <cvpp/containers/vector.h>
#include <cvpp/containers/image.h>
#include <cvpp/properties/pose.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
using namespace cvpp;
Seq<String>
get_files( const String& dir , const int& n = 0 )
{
DIR *dp;
struct dirent *dirp;
Seq<String> files;
if( ( dp = opendir( dir.c_str() ) ) == NULL )
disp( "Error Opening" , dir );
while( ( dirp = readdir( dp ) ) != NULL)
{
String file( dirp->d_name );
if( file[ file.size() - 4 ] == '.' )
files.push_back( dir + file );
}
closedir( dp );
std::sort( files.begin() , files.end() );
if( n > 0 ) files.resize( n );
return files;
}
Matf
load_vel2cam( const String& file )
{
String line;
std::ifstream infile( file + "/calib_velo_to_cam.txt" );
float R[9] , t[3];
while( std::getline( infile , line ) )
{
if( line[0] == 'R' && line[1] == ':' )
tokenFloat( line.c_str() , R , ' ' );
if( line[0] == 'T' && line[1] == ':' )
tokenFloat( line.c_str() , t , ' ' );
}
Matf T( 4 , 4 );
T.eig() << R[0] , R[1] , R[2] , t[0] ,
R[3] , R[4] , R[5] , t[1] ,
R[6] , R[7] , R[8] , t[2] ,
0.0 , 0.0 , 0.0 , 1.0 ;
return T.t();
}
Matf
load_imu2vel( const String& file )
{
String line;
std::ifstream infile( file + "/calib_imu_to_velo.txt" );
float R[9] , t[3];
while( std::getline( infile , line ) )
{
if( line[0] == 'R' && line[1] == ':' )
tokenFloat( line.c_str() , R , ' ' );
if( line[0] == 'T' && line[1] == ':' )
tokenFloat( line.c_str() , t , ' ' );
}
Matf T( 4 , 4 );
T.eig() << R[0] , R[1] , R[2] , t[0] ,
R[3] , R[4] , R[5] , t[1] ,
R[6] , R[7] , R[8] , t[2] ,
0.0 , 0.0 , 0.0 , 1.0 ;
return T.t();
}
void
load_cam2cam( const String& dir , Matf& K , Matf& D , Matf& R , Matf& P )
{
String file = dir + "/calib_cam_to_cam.txt";
String line;
std::ifstream infile( file );
float k[9] , d[5] , r[9] , p[12];
while( std::getline( infile , line ) )
{
if( line.substr(0,4).compare( "K_02" ) == 0 )
tokenFloat( line.substr(5).c_str() , k , ' ' );
if( line.substr(0,4).compare( "D_02" ) == 0 )
tokenFloat( line.substr(5).c_str() , d , ' ' );
if( line.substr(0,9).compare( "R_rect_00" ) == 0 )
tokenFloat( line.substr(10).c_str() , r , ' ' );
if( line.substr(0,9).compare( "P_rect_02" ) == 0 )
tokenFloat( line.substr(10).c_str() , p , ' ' );
}
K.reset( 3 , 3 );
forLOOPij( K.r() , K.c() )
K(i,j) = k[ i * K.c() + j ];
D.reset( 5 );
forLOOPi( D.r() )
D(i) = d[ i ];
R.reset( 4 , 4 ).setIdentity();
forLOOPij( 3 , 3 )
R(i,j) = r[ i * 3 + j ];
R.blu(3) = R.blu(3).t();
P.reset( 3 , 4 );
forLOOPij( P.r() , P.c() )
P(i,j) = p[ i * P.c() + j ];
P = P.t();
}
SeqMatd
load_vel( const Seq<String>& files )
{
int n = files.size();
SeqMatd vels( n );
int base = 1000000;
float *data = (float*)malloc( base * sizeof(float) );
forLOOPi( n )
{
float *px = data + 0 , *py = data + 1;
float *pz = data + 2 , *pr = data + 3;
FILE *stream;
stream = fopen( files[i].c_str() , "rb" );
int num = fread( data , sizeof(float) , base , stream ) / 4;
vels[i].reset( num , 4 );
forLOOPj( num )
{
vels[i].row(j) << *px , *py , *pz , *pr ;
px += 4 ; py += 4 ; pz += 4 ; pr += 4 ;
}
fclose( stream );
}
return vels;
}
Matd load_vel( const String& file )
{
Seq<String> files;
files.push_back( file );
SeqMatd vels = load_vel( files );
return vels[0];
}
SeqImg3c
load_img( const Seq<String>& files )
{
int n = files.size();
SeqImg3c imgs( n );
#pragma omp parallel for
forLOOPi( n )
{
imgs[i].load( files[i] );
}
return imgs;
}
Img3c load_img( const String& file )
{
Seq<String> files;
files.push_back( file );
SeqImg3c imgs = load_img( files );
return imgs[0];
}
SeqPosef
load_pos( const Seq<String>& files )
{
int n = files.size();
Matf data( n , 30 );
forLOOPi( n )
{
float vals[30];
std::ifstream infile( files[i] );
String line;
while( std::getline( infile , line ) )
tokenFloat( ( ' ' + line ).c_str() , vals , ' ' );
forLOOPj( data.c() )
data(i,j) = vals[j];
}
float lat0 = data(0,0);
float r = 6378137 , s = std::cos( lat0 * PI / 180.0 );
float sr = s * r;
Matf xyz( n , 6 );
forLOOPi( xyz.r() )
{
float lat = data(i,0) , lon = data(i,1);
float z = data(i,2) , r = data(i,3) , p = data(i,4) , w = data(i,5);
float x = sr * PI * lon / 180.0;
float y = sr * std::log( std::tan( PI * ( 90.0 + lat ) / 360.0 ) );
xyz.row(i) << x , y , z , r , p , w;
}
Matf off = xyz.cl(3).r(0).clone();
xyz.cl(3) -= off;
SeqPosef poses( n );
forLOOPi( poses.size() )
poses[i].setPose( xyz.r(i) );
return poses;
}
Posef load_pos( const String& file )
{
Seq<String> files;
files.push_back( file );
SeqPosef poses = load_pos( files );
return poses[0];
}
void prep_dirs( const String& dir )
{
String path;
struct stat st = {0};
path = dir ; if( stat( path.c_str() , &st ) == -1 ) mkdir( path.c_str() , 0700 );
path = dir + "/imgs"; if( stat( path.c_str() , &st ) == -1 ) mkdir( path.c_str() , 0700 );
path = dir + "/disp1"; if( stat( path.c_str() , &st ) == -1 ) mkdir( path.c_str() , 0700 );
path = dir + "/disp2"; if( stat( path.c_str() , &st ) == -1 ) mkdir( path.c_str() , 0700 );
path = dir + "/xyz"; if( stat( path.c_str() , &st ) == -1 ) mkdir( path.c_str() , 0700 );
path = dir + "/all"; if( stat( path.c_str() , &st ) == -1 ) mkdir( path.c_str() , 0700 );
path = dir + "/uvxyz"; if( stat( path.c_str() , &st ) == -1 ) mkdir( path.c_str() , 0700 );
}
void save_data( const String& suf , const String& dir , const String& path ,
const Img3c& img , const Img1c& dsp1 , const Img1c& dsp2 ,
const Matf& xyz , const Matf& uvxyz , const Matf& all )
{
int nn = path.length() , n = 0;
while( path[ nn - n ] != '/' ) n++; n--;
String name = path.substr( nn - n , n -4 );
String sufname = suf + name;
disp( sufname );
img.saveIMG( dir + "/imgs/" + sufname + ".png" );
dsp1.saveIMG( dir + "/disp1/" + sufname + ".png" );
dsp2.saveIMG( dir + "/disp2/" + sufname + ".png" );
xyz.saveBIN( dir + "/xyz/" + sufname + ".bin" );
all.saveBIN( dir + "/all/" + sufname + ".bin" );
uvxyz.saveBIN( dir + "/uvxyz/" + sufname + ".bin" );
}
| 24.897527 | 95 | 0.478144 | [
"vector"
] |
5fb3a7ae2728c71c4d16969027c2d6ca4e3639d9 | 2,206 | h | C | CsPlugin/Source/CsCore/Public/Skin/Data/Visual/CsData_Skin_VisualStaticMeshAndMaterial.h | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | 2 | 2019-03-17T10:43:53.000Z | 2021-04-20T21:24:19.000Z | CsPlugin/Source/CsCore/Public/Skin/Data/Visual/CsData_Skin_VisualStaticMeshAndMaterial.h | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | null | null | null | CsPlugin/Source/CsCore/Public/Skin/Data/Visual/CsData_Skin_VisualStaticMeshAndMaterial.h | closedsum/core | c3cae44a177b9684585043a275130f9c7b67fef0 | [
"Unlicense"
] | null | null | null | // Copyright 2017-2021 Closed Sum Games, LLC. All Rights Reserved.
#pragma once
#include "UObject/Object.h"
// Interfaces
#include "Data/CsData.h"
#include "Skin/Data/Visual/CsData_Skin_Visual.h"
#include "Skin/Data/Visual/StaticMesh/CsData_Skin_VisualStaticMesh.h"
#include "Skin/Data/Visual/Material/CsData_Skin_VisualMaterial.h"
// Types
#include "Types/CsTypes_StaticMesh.h"
#include "Material/CsTypes_Material.h"
#include "CsData_Skin_VisualStaticMeshAndMaterial.generated.h"
struct FCsInterfaceMap;
class USkeletalMesh;
class UMaterialInterface;
/**
*
*/
UCLASS(BlueprintType, Blueprintable)
class CSCORE_API UCsData_Skin_VisualStaticMeshAndMaterial : public UObject,
public ICsData,
public ICsData_Skin_Visual,
public ICsData_Skin_VisualStaticMesh,
public ICsData_Skin_VisualMaterial
{
GENERATED_UCLASS_BODY()
public:
static const FName Name;
#define DataType NCsData::IData
private:
DataType* DataProxy;
// UObject Interface
#pragma region
public:
virtual void PostLoad() override;
virtual void BeginDestroy() override;
#pragma endregion UObject Interface
private:
void Init();
void Reset();
FCsInterfaceMap* InterfaceMap;
// ICsGetInterfaceMap
#pragma region
public:
FCsInterfaceMap* GetInterfaceMap() const { return InterfaceMap; }
#pragma endregion ICsGetInterfaceMap
protected:
bool bLoaded;
// ICsData
#pragma region
public:
FORCEINLINE DataType* _getIData() const { return DataProxy; }
bool IsValid(const int32& LoadFlags);
void Load(const int32& LoadFlags);
void Unload();
bool IsLoaded() const;
#pragma endregion ICsData
public:
UPROPERTY(EditAnywhere, BlueprintReadOnly)
FCsStaticMesh Mesh;
// ICsData_Skin_VisualStaticMesh
#pragma region
public:
FORCEINLINE UStaticMesh* GetStaticMesh() const { return Mesh.Get(); }
#pragma endregion ICsData_Skin_VisualStaticMesh
public:
UPROPERTY(EditAnywhere, BlueprintReadOnly)
FCsTArrayMaterialInterface Materials;
// ICsData_Skin_VisualMaterial
#pragma region
public:
FORCEINLINE const TArray<UMaterialInterface*>& GetMaterials() const { return Materials.Get(); }
#pragma endregion ICsData_Skin_VisualMaterial
#undef DataType
}; | 19.522124 | 96 | 0.774705 | [
"mesh",
"object"
] |
5fb5e81d730d281bc1d849915410f788c55b688f | 10,768 | c | C | src/map/lapack2flamec/f2c/c/claqr1.c | vallejos/libflame | 65cc6f2a1ad6baedeb1d801e19c4e4d80cc854c7 | [
"BSD-3-Clause"
] | null | null | null | src/map/lapack2flamec/f2c/c/claqr1.c | vallejos/libflame | 65cc6f2a1ad6baedeb1d801e19c4e4d80cc854c7 | [
"BSD-3-Clause"
] | null | null | null | src/map/lapack2flamec/f2c/c/claqr1.c | vallejos/libflame | 65cc6f2a1ad6baedeb1d801e19c4e4d80cc854c7 | [
"BSD-3-Clause"
] | null | null | null | /* ../netlib/claqr1.f -- translated by f2c (version 20100827). You must link the resulting object file with libf2c: on Microsoft Windows system, link with libf2c.lib;
on Linux or Unix systems, link with .../path/to/libf2c.a -lm or, if you install libf2c.a in a standard place, with -lf2c -lm -- in that order, at the end of the command line, as in cc *.o -lf2c -lm Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., http://www.netlib.org/f2c/libf2c.zip */
#include "FLA_f2c.h" /* > \brief \b CLAQR1 sets a scalar multiple of the first column of the product of 2-by-2 or 3-by-3 matrix H a nd specified shifts. */
/* =========== DOCUMENTATION =========== */
/* Online html documentation available at */
/* http://www.netlib.org/lapack/explore-html/ */
/* > \htmlonly */
/* > Download CLAQR1 + dependencies */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/claqr1. f"> */
/* > [TGZ]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/claqr1. f"> */
/* > [ZIP]</a> */
/* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/claqr1. f"> */
/* > [TXT]</a> */
/* > \endhtmlonly */
/* Definition: */
/* =========== */
/* SUBROUTINE CLAQR1( N, H, LDH, S1, S2, V ) */
/* .. Scalar Arguments .. */
/* COMPLEX S1, S2 */
/* INTEGER LDH, N */
/* .. */
/* .. Array Arguments .. */
/* COMPLEX H( LDH, * ), V( * ) */
/* .. */
/* > \par Purpose: */
/* ============= */
/* > */
/* > \verbatim */
/* > */
/* > Given a 2-by-2 or 3-by-3 matrix H, CLAQR1 sets v to a */
/* > scalar multiple of the first column of the product */
/* > */
/* > (*) K = (H - s1*I)*(H - s2*I) */
/* > */
/* > scaling to avoid overflows and most underflows. */
/* > */
/* > This is useful for starting double implicit shift bulges */
/* > in the QR algorithm. */
/* > \endverbatim */
/* Arguments: */
/* ========== */
/* > \param[in] N */
/* > \verbatim */
/* > N is integer */
/* > Order of the matrix H. N must be either 2 or 3. */
/* > \endverbatim */
/* > */
/* > \param[in] H */
/* > \verbatim */
/* > H is COMPLEX array of dimension (LDH,N) */
/* > The 2-by-2 or 3-by-3 matrix H in (*). */
/* > \endverbatim */
/* > */
/* > \param[in] LDH */
/* > \verbatim */
/* > LDH is integer */
/* > The leading dimension of H as declared in */
/* > the calling procedure. LDH.GE.N */
/* > \endverbatim */
/* > */
/* > \param[in] S1 */
/* > \verbatim */
/* > S1 is COMPLEX */
/* > \endverbatim */
/* > */
/* > \param[in] S2 */
/* > \verbatim */
/* > S2 is COMPLEX */
/* > */
/* > S1 and S2 are the shifts defining K in (*) above. */
/* > \endverbatim */
/* > */
/* > \param[out] V */
/* > \verbatim */
/* > V is COMPLEX array of dimension N */
/* > A scalar multiple of the first column of the */
/* > matrix K in (*). */
/* > \endverbatim */
/* Authors: */
/* ======== */
/* > \author Univ. of Tennessee */
/* > \author Univ. of California Berkeley */
/* > \author Univ. of Colorado Denver */
/* > \author NAG Ltd. */
/* > \date September 2012 */
/* > \ingroup complexOTHERauxiliary */
/* > \par Contributors: */
/* ================== */
/* > */
/* > Karen Braman and Ralph Byers, Department of Mathematics, */
/* > University of Kansas, USA */
/* > */
/* ===================================================================== */
/* Subroutine */
int claqr1_(integer *n, complex *h__, integer *ldh, complex * s1, complex *s2, complex *v)
{
/* System generated locals */
integer h_dim1, h_offset, i__1, i__2, i__3, i__4;
real r__1, r__2, r__3, r__4, r__5, r__6;
complex q__1, q__2, q__3, q__4, q__5, q__6, q__7, q__8;
/* Builtin functions */
double r_imag(complex *);
/* Local variables */
real s;
complex h21s, h31s;
/* -- LAPACK auxiliary routine (version 3.4.2) -- */
/* -- LAPACK is a software package provided by Univ. of Tennessee, -- */
/* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */
/* September 2012 */
/* .. Scalar Arguments .. */
/* .. */
/* .. Array Arguments .. */
/* .. */
/* ================================================================ */
/* .. Parameters .. */
/* .. */
/* .. Local Scalars .. */
/* .. */
/* .. Intrinsic Functions .. */
/* .. */
/* .. Statement Functions .. */
/* .. */
/* .. Statement Function definitions .. */
/* .. */
/* .. Executable Statements .. */
/* Parameter adjustments */
h_dim1 = *ldh;
h_offset = 1 + h_dim1;
h__ -= h_offset;
--v;
/* Function Body */
if (*n == 2)
{
i__1 = h_dim1 + 1;
q__2.r = h__[i__1].r - s2->r;
q__2.i = h__[i__1].i - s2->i; // , expr subst
q__1.r = q__2.r;
q__1.i = q__2.i; // , expr subst
i__2 = h_dim1 + 2;
s = (r__1 = q__1.r, abs(r__1)) + (r__2 = r_imag(&q__1), abs(r__2)) + ( (r__3 = h__[i__2].r, abs(r__3)) + (r__4 = r_imag(&h__[h_dim1 + 2]), abs(r__4)));
if (s == 0.f)
{
v[1].r = 0.f;
v[1].i = 0.f; // , expr subst
v[2].r = 0.f;
v[2].i = 0.f; // , expr subst
}
else
{
i__1 = h_dim1 + 2;
q__1.r = h__[i__1].r / s;
q__1.i = h__[i__1].i / s; // , expr subst
h21s.r = q__1.r;
h21s.i = q__1.i; // , expr subst
i__1 = (h_dim1 << 1) + 1;
q__2.r = h21s.r * h__[i__1].r - h21s.i * h__[i__1].i;
q__2.i = h21s.r * h__[i__1].i + h21s.i * h__[i__1].r; // , expr subst
i__2 = h_dim1 + 1;
q__4.r = h__[i__2].r - s1->r;
q__4.i = h__[i__2].i - s1->i; // , expr subst
i__3 = h_dim1 + 1;
q__6.r = h__[i__3].r - s2->r;
q__6.i = h__[i__3].i - s2->i; // , expr subst
q__5.r = q__6.r / s;
q__5.i = q__6.i / s; // , expr subst
q__3.r = q__4.r * q__5.r - q__4.i * q__5.i;
q__3.i = q__4.r * q__5.i + q__4.i * q__5.r; // , expr subst
q__1.r = q__2.r + q__3.r;
q__1.i = q__2.i + q__3.i; // , expr subst
v[1].r = q__1.r;
v[1].i = q__1.i; // , expr subst
i__1 = h_dim1 + 1;
i__2 = (h_dim1 << 1) + 2;
q__4.r = h__[i__1].r + h__[i__2].r;
q__4.i = h__[i__1].i + h__[ i__2].i; // , expr subst
q__3.r = q__4.r - s1->r;
q__3.i = q__4.i - s1->i; // , expr subst
q__2.r = q__3.r - s2->r;
q__2.i = q__3.i - s2->i; // , expr subst
q__1.r = h21s.r * q__2.r - h21s.i * q__2.i;
q__1.i = h21s.r * q__2.i + h21s.i * q__2.r; // , expr subst
v[2].r = q__1.r;
v[2].i = q__1.i; // , expr subst
}
}
else
{
i__1 = h_dim1 + 1;
q__2.r = h__[i__1].r - s2->r;
q__2.i = h__[i__1].i - s2->i; // , expr subst
q__1.r = q__2.r;
q__1.i = q__2.i; // , expr subst
i__2 = h_dim1 + 2;
i__3 = h_dim1 + 3;
s = (r__1 = q__1.r, abs(r__1)) + (r__2 = r_imag(&q__1), abs(r__2)) + ( (r__3 = h__[i__2].r, abs(r__3)) + (r__4 = r_imag(&h__[h_dim1 + 2]), abs(r__4))) + ((r__5 = h__[i__3].r, abs(r__5)) + (r__6 = r_imag(&h__[h_dim1 + 3]), abs(r__6)));
if (s == 0.f)
{
v[1].r = 0.f;
v[1].i = 0.f; // , expr subst
v[2].r = 0.f;
v[2].i = 0.f; // , expr subst
v[3].r = 0.f;
v[3].i = 0.f; // , expr subst
}
else
{
i__1 = h_dim1 + 2;
q__1.r = h__[i__1].r / s;
q__1.i = h__[i__1].i / s; // , expr subst
h21s.r = q__1.r;
h21s.i = q__1.i; // , expr subst
i__1 = h_dim1 + 3;
q__1.r = h__[i__1].r / s;
q__1.i = h__[i__1].i / s; // , expr subst
h31s.r = q__1.r;
h31s.i = q__1.i; // , expr subst
i__1 = h_dim1 + 1;
q__4.r = h__[i__1].r - s1->r;
q__4.i = h__[i__1].i - s1->i; // , expr subst
i__2 = h_dim1 + 1;
q__6.r = h__[i__2].r - s2->r;
q__6.i = h__[i__2].i - s2->i; // , expr subst
q__5.r = q__6.r / s;
q__5.i = q__6.i / s; // , expr subst
q__3.r = q__4.r * q__5.r - q__4.i * q__5.i;
q__3.i = q__4.r * q__5.i + q__4.i * q__5.r; // , expr subst
i__3 = (h_dim1 << 1) + 1;
q__7.r = h__[i__3].r * h21s.r - h__[i__3].i * h21s.i;
q__7.i = h__[i__3].r * h21s.i + h__[i__3].i * h21s.r; // , expr subst
q__2.r = q__3.r + q__7.r;
q__2.i = q__3.i + q__7.i; // , expr subst
i__4 = h_dim1 * 3 + 1;
q__8.r = h__[i__4].r * h31s.r - h__[i__4].i * h31s.i;
q__8.i = h__[i__4].r * h31s.i + h__[i__4].i * h31s.r; // , expr subst
q__1.r = q__2.r + q__8.r;
q__1.i = q__2.i + q__8.i; // , expr subst
v[1].r = q__1.r;
v[1].i = q__1.i; // , expr subst
i__1 = h_dim1 + 1;
i__2 = (h_dim1 << 1) + 2;
q__5.r = h__[i__1].r + h__[i__2].r;
q__5.i = h__[i__1].i + h__[ i__2].i; // , expr subst
q__4.r = q__5.r - s1->r;
q__4.i = q__5.i - s1->i; // , expr subst
q__3.r = q__4.r - s2->r;
q__3.i = q__4.i - s2->i; // , expr subst
q__2.r = h21s.r * q__3.r - h21s.i * q__3.i;
q__2.i = h21s.r * q__3.i + h21s.i * q__3.r; // , expr subst
i__3 = h_dim1 * 3 + 2;
q__6.r = h__[i__3].r * h31s.r - h__[i__3].i * h31s.i;
q__6.i = h__[i__3].r * h31s.i + h__[i__3].i * h31s.r; // , expr subst
q__1.r = q__2.r + q__6.r;
q__1.i = q__2.i + q__6.i; // , expr subst
v[2].r = q__1.r;
v[2].i = q__1.i; // , expr subst
i__1 = h_dim1 + 1;
i__2 = h_dim1 * 3 + 3;
q__5.r = h__[i__1].r + h__[i__2].r;
q__5.i = h__[i__1].i + h__[ i__2].i; // , expr subst
q__4.r = q__5.r - s1->r;
q__4.i = q__5.i - s1->i; // , expr subst
q__3.r = q__4.r - s2->r;
q__3.i = q__4.i - s2->i; // , expr subst
q__2.r = h31s.r * q__3.r - h31s.i * q__3.i;
q__2.i = h31s.r * q__3.i + h31s.i * q__3.r; // , expr subst
i__3 = (h_dim1 << 1) + 3;
q__6.r = h21s.r * h__[i__3].r - h21s.i * h__[i__3].i;
q__6.i = h21s.r * h__[i__3].i + h21s.i * h__[i__3].r; // , expr subst
q__1.r = q__2.r + q__6.r;
q__1.i = q__2.i + q__6.i; // , expr subst
v[3].r = q__1.r;
v[3].i = q__1.i; // , expr subst
}
}
return 0;
}
/* claqr1_ */
| 38.594982 | 292 | 0.46211 | [
"object"
] |
5fb9bab3c514d9910d923d748f8b9a186ff29da8 | 1,779 | h | C | oneflow/xrt/xla/xla_executable.h | wangyuyue/oneflow | 0a71c22fe8355392acc8dc0e301589faee4c4832 | [
"Apache-2.0"
] | 3,285 | 2020-07-31T05:51:22.000Z | 2022-03-31T15:20:16.000Z | oneflow/xrt/xla/xla_executable.h | wangyuyue/oneflow | 0a71c22fe8355392acc8dc0e301589faee4c4832 | [
"Apache-2.0"
] | 2,417 | 2020-07-31T06:28:58.000Z | 2022-03-31T23:04:14.000Z | oneflow/xrt/xla/xla_executable.h | wangyuyue/oneflow | 0a71c22fe8355392acc8dc0e301589faee4c4832 | [
"Apache-2.0"
] | 520 | 2020-07-31T05:52:42.000Z | 2022-03-29T02:38:11.000Z | /*
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef ONEFLOW_XRT_XLA_XLA_EXECUTABLE_H_
#define ONEFLOW_XRT_XLA_XLA_EXECUTABLE_H_
#include "oneflow/xrt/executable.h"
#include "tensorflow/compiler/xla/client/local_client.h"
namespace oneflow {
namespace xrt {
namespace mola {
class XlaExecutable : public Executable {
public:
XlaExecutable(const std::string& name, const XrtDevice& device,
const std::vector<xla::Shape>& input_shapes, const xla::Shape& output_shape,
std::unique_ptr<xla::LocalExecutable>&& executable)
: Executable(name, XrtEngine::XLA),
device_(device),
input_shapes_(input_shapes),
output_shape_(output_shape),
executable_(std::move(executable)) {}
virtual ~XlaExecutable() = default;
bool Run(const std::vector<Parameter>& inputs, const ExecutableRunOptions& run_options,
bool block_until_done = true) override;
private:
XrtDevice device_;
std::vector<xla::Shape> input_shapes_;
// The output shape is always a tuple.
xla::Shape output_shape_;
std::unique_ptr<xla::LocalExecutable> executable_;
};
} // namespace mola
} // namespace xrt
} // namespace oneflow
#endif // ONEFLOW_XRT_XLA_XLA_EXECUTABLE_H_
| 31.210526 | 92 | 0.741428 | [
"shape",
"vector"
] |
5fbd0adaf5c39aedff439f20d297518d7da8b0d2 | 5,653 | h | C | components/data_reduction_proxy/core/browser/data_reduction_proxy_io_data.h | hefen1/chromium | 52f0b6830e000ca7c5e9aa19488af85be792cc88 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/data_reduction_proxy/core/browser/data_reduction_proxy_io_data.h | hefen1/chromium | 52f0b6830e000ca7c5e9aa19488af85be792cc88 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/data_reduction_proxy/core/browser/data_reduction_proxy_io_data.h | hefen1/chromium | 52f0b6830e000ca7c5e9aa19488af85be792cc88 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2020-04-04T13:34:56.000Z | 2020-11-04T07:17:52.000Z | // Copyright 2015 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_DATA_REDUCTION_PROXY_CORE_BROWSER_DATA_REDUCTION_PROXY_IO_DATA_H_
#define COMPONENTS_DATA_REDUCTION_PROXY_CORE_BROWSER_DATA_REDUCTION_PROXY_IO_DATA_H_
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/prefs/pref_member.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_debug_ui_service.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_delegate.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_network_delegate.h"
#include "components/data_reduction_proxy/core/browser/data_reduction_proxy_request_options.h"
namespace net {
class NetLog;
class URLRequestInterceptor;
}
namespace data_reduction_proxy {
class DataReductionProxyConfig;
class DataReductionProxyConfigurator;
class DataReductionProxyEventStore;
class DataReductionProxyService;
class DataReductionProxyStatisticsPrefs;
class DataReductionProxyUsageStats;
// Contains and initializes all Data Reduction Proxy objects that operate on
// the IO thread.
class DataReductionProxyIOData {
public:
// Constructs a DataReductionProxyIOData object. |param_flags| is used to
// set information about the DNS names used by the proxy, and allowable
// configurations.
DataReductionProxyIOData(
const Client& client,
int param_flags,
net::NetLog* net_log,
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner,
scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner,
bool enable_quic);
virtual ~DataReductionProxyIOData();
// Initializes preferences, including a preference to track whether the
// Data Reduction Proxy is enabled.
void InitOnUIThread(PrefService* pref_service);
// Destroys the statistics preferences.
void ShutdownOnUIThread();
// Sets the Data Reduction Proxy service after it has been created.
void SetDataReductionProxyService(
base::WeakPtr<DataReductionProxyService> data_reduction_proxy_service);
// Creates an interceptor suitable for following the Data Reduction Proxy
// bypass protocol.
scoped_ptr<net::URLRequestInterceptor> CreateInterceptor();
// Creates a NetworkDelegate suitable for carrying out the Data Reduction
// Proxy protocol, including authenticating, establishing a handler to
// override the current proxy configuration, and
// gathering statistics for UMA.
scoped_ptr<DataReductionProxyNetworkDelegate> CreateNetworkDelegate(
scoped_ptr<net::NetworkDelegate> wrapped_network_delegate,
bool track_proxy_bypass_statistics);
// Returns true if the Data Reduction Proxy is enabled and false otherwise.
bool IsEnabled() const;
DataReductionProxyConfigurator* configurator() const {
return configurator_.get();
}
DataReductionProxyConfig* config() const {
return config_.get();
}
DataReductionProxyEventStore* event_store() const {
return event_store_.get();
}
DataReductionProxyRequestOptions* request_options() const {
return request_options_.get();
}
net::ProxyDelegate* proxy_delegate() const {
return proxy_delegate_.get();
}
net::NetLog* net_log() {
return net_log_;
}
base::WeakPtr<DataReductionProxyService> service() const {
return service_;
}
// Used for testing.
DataReductionProxyUsageStats* usage_stats() const {
return usage_stats_.get();
}
DataReductionProxyDebugUIService* debug_ui_service() const {
return debug_ui_service_.get();
}
void set_debug_ui_service(
scoped_ptr<DataReductionProxyDebugUIService> ui_service) const {
debug_ui_service_= ui_service.Pass();
}
private:
friend class TestDataReductionProxyIOData;
// Used for testing.
DataReductionProxyIOData();
// The type of Data Reduction Proxy client.
Client client_;
// Parameters including DNS names and allowable configurations.
scoped_ptr<DataReductionProxyConfig> config_;
// Holds the DataReductionProxyDebugUIManager for Data Reduction Proxy bypass
// interstitials.
mutable scoped_ptr<DataReductionProxyDebugUIService> debug_ui_service_;
// Tracker of Data Reduction Proxy-related events, e.g., for logging.
scoped_ptr<DataReductionProxyEventStore> event_store_;
// Setter of the Data Reduction Proxy-specific proxy configuration.
scoped_ptr<DataReductionProxyConfigurator> configurator_;
// A proxy delegate. Used, for example, to add authentication to HTTP CONNECT
// request.
scoped_ptr<DataReductionProxyDelegate> proxy_delegate_;
// Data Reduction Proxy objects with a UI based lifetime.
base::WeakPtr<DataReductionProxyService> service_;
// Tracker of various metrics to be reported in UMA.
scoped_ptr<DataReductionProxyUsageStats> usage_stats_;
// Constructs credentials suitable for authenticating the client.
scoped_ptr<DataReductionProxyRequestOptions> request_options_;
// A net log.
net::NetLog* net_log_;
// IO and UI task runners, respectively.
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_;
scoped_refptr<base::SingleThreadTaskRunner> ui_task_runner_;
// Used
bool shutdown_on_ui_;
// Preference that determines if the Data Reduction Proxy has been enabled
// by the user. In practice, this can be overridden by the command line.
BooleanPrefMember enabled_;
DISALLOW_COPY_AND_ASSIGN(DataReductionProxyIOData);
};
} // namespace data_reduction_proxy
#endif // COMPONENTS_DATA_REDUCTION_PROXY_CORE_BROWSER_DATA_REDUCTION_PROXY_IO_DATA_H_
| 33.252941 | 95 | 0.790023 | [
"object"
] |
5fcbe351338620d05e8ad7e27b9be694c3fe07cd | 1,015 | h | C | src/integrators/delayed/delayed.h | joeylitalien/drmlt-dpt | a12baa5d50ff6e6337e5cbb0433b1baa6fd498d7 | [
"MIT"
] | 3 | 2020-08-24T06:56:14.000Z | 2021-08-25T16:26:41.000Z | src/integrators/delayed/delayed.h | joeylitalien/drmlt-dpt | a12baa5d50ff6e6337e5cbb0433b1baa6fd498d7 | [
"MIT"
] | null | null | null | src/integrators/delayed/delayed.h | joeylitalien/drmlt-dpt | a12baa5d50ff6e6337e5cbb0433b1baa6fd498d7 | [
"MIT"
] | null | null | null | #pragma once
#include "commondef.h"
#include "gaussian.h"
#include "alignedallocator.h"
#include "utils.h"
#include "integrator.h"
#include <vector>
#include "mltstats.h"
#include "drsmallstep.h"
/**
* Delayed rejection (DR)
* Isotropic 1st-stage, mixture of iso and H2MC 2nd-stage
*/
class DRIntegrator : public Integrator {
public:
/**
* Specifies the sampling algorithm that is internally used
*/
enum EType {
EGreen, // uses Green & Mira (2001) algorithm
EMira // uses Tierney & Mira (1999) algorithm
};
/// Constructor
DRIntegrator(const Scene *scene, std::shared_ptr<const PathFuncLib> pathFuncLib);
/// Prepass for MLT bootstrap
Float PrePass(const MLTState &mltState,
const int64_t numInitSamples,
const int numChains,
MarkovStates &initStates,
std::shared_ptr<PiecewiseConstant1D> &lengthDist) override;
/// Main rendering loop
void Render() override;
}; | 23.604651 | 85 | 0.64335 | [
"render",
"vector"
] |
5fce5c7c8080e5cfa3825fa3ae7f78a3709bf9fa | 3,246 | c | C | MidTerm_Assignment/resultant.c | davidemelu/C-Style-Programming | eb8c956a319ebbd3ae66b479611ad153446dad65 | [
"MIT"
] | null | null | null | MidTerm_Assignment/resultant.c | davidemelu/C-Style-Programming | eb8c956a319ebbd3ae66b479611ad153446dad65 | [
"MIT"
] | null | null | null | MidTerm_Assignment/resultant.c | davidemelu/C-Style-Programming | eb8c956a319ebbd3ae66b479611ad153446dad65 | [
"MIT"
] | null | null | null | /*
File: resultant.c
This program prompt the user for the number of vectors.
b. prompt the user to enter the vector(s) in polar form (magnitude and angle in degrees), then
c. output the x and y components of the resultant and
d. output in polar form the resultant.
*/
#include<stdio.h>
#include<math.h>
double x_Component(double magnitude, double angle);
double y_Component(double magnitude, double angle);
double magnitude(double xComponent, double yComponent);
double angle(double xComponent, double yComponent);
int main(){
//initializing count
int count = 0;
// individual varuiable for the x and y resultant component
double resultantX = 0;
double resultantY = 0;
// declaring number of vector, angle, magnitude, x any y values
double mag, angle, xValue, yValue;
int noOfVecetor;
// prompt user, asking number of vector
printf("How many vectors? ");
scanf("%d", &noOfVecetor);
while (count < noOfVecetor){
// prompt user, asking for the magnitude and
printf("Enter vector %d (mag, angle):", count+1);
scanf("%lf %lf", &mag, &angle);
//resultant x component
xValue = x_Component(mag, angle);
resultantX = resultantX + xValue;
//resultant y component
yValue = y_Component(mag, angle);
resultantY = resultantY + yValue;
count++;
}
double PolarFormMagnitude = magnitude(resultantX, resultantY);
printf("\nThe resultant in rectangular form is:");
printf("\nx-component = %lf", resultantX);
printf("\ny-component = %lf", resultantY);
printf("\nThe polar form of the resultant is:");
printf("\nMagnitude = %lf", PolarFormMagnitude);
printf("\nAngle with positive x-axis = degrees");
return 0;
}
// return function to calculate x component
double x_Component(double magnitude, double angle){
angle = angle * (M_PI / 180);
double x_Value = magnitude * cos(angle);
return x_Value;
}
// return function to calculate y component
double y_Component(double magnitude, double angle){
angle = angle * (M_PI / 180);
double y_Value = magnitude * sin(angle);
return y_Value;
}
// return function to calculate the magnitude
double magnitude(double xComponent, double yComponent){
double insideSqrt = (pow(xComponent, 2) + pow(yComponent, 2));
double pythagoras = sqrt(insideSqrt);
return pythagoras;
}
/*
//return function for the angle with positive x-axis
double angle(double xComponent, double yComponent){
//declare
double angleX;
// quadrant 1
if ((y_Component / xComponent) > 0){
angleX = atan(y_Component / xComponent);
return angleX;
}
//quadrant 2
else if((y_Component / xComponent) < 0){
angleX = M_PI + atan(y_Component / xComponent);
return angleX;
}
// quadrant 3
else if((y_Component / xComponent)){
angleX = M_PI + atan(y_Component / xComponent);
return angleX;
}
// quadrant 4
else if((y_Component / xComponent)){
angleX = (2 * M_PI) + atan(y_Component / xComponent);
return angleX;
}
} */
| 29.243243 | 94 | 0.636784 | [
"vector"
] |
5fd1ee2131b3d2f19a9ceffc790c6f2d02557923 | 2,779 | h | C | tensorflow/lite/delegates/nnapi/quant_lstm_sup.h | uve/tensorflow | e08079463bf43e5963acc41da1f57e95603f8080 | [
"Apache-2.0"
] | null | null | null | tensorflow/lite/delegates/nnapi/quant_lstm_sup.h | uve/tensorflow | e08079463bf43e5963acc41da1f57e95603f8080 | [
"Apache-2.0"
] | null | null | null | tensorflow/lite/delegates/nnapi/quant_lstm_sup.h | uve/tensorflow | e08079463bf43e5963acc41da1f57e95603f8080 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2019 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_LITE_DELEGATES_NNAPI_QUANT_LSTM_SUP_H_
#define TENSORFLOW_LITE_DELEGATES_NNAPI_QUANT_LSTM_SUP_H_
#include <vector>
#include "tensorflow/lite/c/c_api_internal.h"
namespace tflite {
namespace delegate {
namespace nnapi {
void ExtractQuantLstmWeightsSubmatrix(const TfLiteIntArray* submatrix_dims,
const int32_t offset_row,
const int32_t offset_column,
const TfLiteIntArray* weight_dims,
const uint8_t* weights,
std::vector<uint8_t>* submatrix);
void DecomposeQuantLstmWeightsTensor(const uint8_t* concat_weights,
const TfLiteIntArray* weight_dims,
std::vector<uint8_t>* recurrent_to_input,
std::vector<uint8_t>* input_to_input,
std::vector<uint8_t>* recurrent_to_cell,
std::vector<uint8_t>* input_to_cell,
std::vector<uint8_t>* recurrent_to_forget,
std::vector<uint8_t>* input_to_forget,
std::vector<uint8_t>* recurrent_to_output,
std::vector<uint8_t>* input_to_output);
void SetWeightSubmatrixDims(const TfLiteIntArray* weight_dims,
TfLiteIntArray* recurrent_submatrix_dims,
TfLiteIntArray* input_submatrix_dims);
void DecomposeBiasTensor(const int32_t* biases, int bias_size,
std::vector<int32_t>* input_bias,
std::vector<int32_t>* cell_bias,
std::vector<int32_t>* forget_bias,
std::vector<int32_t>* output_bias);
} // namespace nnapi
} // namespace delegate
} // namespace tflite
#endif // TENSORFLOW_LITE_DELEGATES_NNAPI_QUANT_LSTM_SUP_H_
| 47.101695 | 81 | 0.574667 | [
"vector"
] |
5ff7c37da42e11a1c698f2c6582b1428dd5c32ac | 656 | h | C | system/debuff.h | dnartz/PvZ-Emulator | 3954f36f4e0f22cee07d6a86003d3892f0938b8b | [
"BSD-2-Clause"
] | 1 | 2022-03-29T23:49:55.000Z | 2022-03-29T23:49:55.000Z | system/debuff.h | dnartz/PvZ-Emulator | 3954f36f4e0f22cee07d6a86003d3892f0938b8b | [
"BSD-2-Clause"
] | 2 | 2021-03-10T18:17:07.000Z | 2021-05-11T13:59:22.000Z | system/debuff.h | dnartz/PvZ-Emulator | 3954f36f4e0f22cee07d6a86003d3892f0938b8b | [
"BSD-2-Clause"
] | 1 | 2021-10-18T18:29:47.000Z | 2021-10-18T18:29:47.000Z | #pragma once
#include "object/scene.h"
#include "object/zombie.h"
#include "system/reanim.h"
namespace pvz_emulator::system {
class debuff {
private:
object::scene& scene;
system::reanim reanim;
public:
void set_slowed(object::zombie& z, unsigned int countdown);
void set_butter(object::zombie& z);
void remove_freeze(object::zombie& z) {
z.countdown.freeze = 0;
reanim.update_fps(z);
}
void remove_slow(object::zombie& z) {
z.countdown.slow = 0;
reanim.update_fps(z);
}
void remove_by_fire_pea(object::zombie& z);
debuff(object::scene& s) : scene(s), reanim(s) { }
};
}
| 19.294118 | 63 | 0.637195 | [
"object"
] |
5ff8ab00889731f7175e862da4d44d34ed8fc873 | 7,381 | h | C | engine/src/liquid/scripting/LuaScope.h | GasimGasimzada/liquid-engine | 0d6c8b6b6ec508dc63b970dc23698caf1578147a | [
"MIT"
] | null | null | null | engine/src/liquid/scripting/LuaScope.h | GasimGasimzada/liquid-engine | 0d6c8b6b6ec508dc63b970dc23698caf1578147a | [
"MIT"
] | null | null | null | engine/src/liquid/scripting/LuaScope.h | GasimGasimzada/liquid-engine | 0d6c8b6b6ec508dc63b970dc23698caf1578147a | [
"MIT"
] | null | null | null | #pragma once
struct lua_State;
#include "LuaTable.h"
namespace liquid {
/**
* @brief Lua user data object
*/
struct LuaUserData {
/**
* @brief User data pointer
*/
void *pointer = nullptr;
};
/**
* @brief Wrapper around Lua scope
*
* Encapsulates Lua functionality
* with a simple API
*/
class LuaScope {
public:
/**
* @brief Default constructor
*
* Does not set the Lua scope
*/
LuaScope() = default;
/**
* @brief Create lua scope wrapper
*
* @param scope Lua scope
*/
LuaScope(void *scope);
/**
* @brief Get variable value from stack
*
* Assertion fails if a type is not
* implemented
*
* @tparam T Variable type
* @param index Stack index
* @return Variable value
*/
template <class T> T get(int32_t index = -1) {
LIQUID_ASSERT(false, "Not implemented");
}
/**
* @brief Check if variable is not a correct type
*
* Assertion fails if a type is not
* implemented
*
* @tparam T Variable type to check for
* @param index Stack index
* @retval true Type matches
* @retval false Type does not match
*/
template <class T> bool is(int32_t index = -1) {
LIQUID_ASSERT(false, "Not implemented");
return false;
}
/**
* @brief Generic variable setter
*
* Assertion fails if a type is not
* implemented
*
* @tparam T Variable type
* @param value Variable value
*/
template <class T> void set(const T &value) {
LIQUID_ASSERT(false, "Not implemented");
}
/**
* @brief Pops last value from stack
*
* @tparam T Variable type
* @return Variable value
*/
template <class T> T popLast() {
const auto &value = get<T>(-1);
pop(-1);
return value;
}
/**
* @brief Get global variable
*
* @tparam T Variable type
* @param name Variable global name
* @return Variable value
*/
template <class T> T getGlobal(const String &name) {
luaGetGlobal(name);
return popLast<T>();
}
/**
* @brief Set global variable
*
* @tparam T Variable type
* @param name Variable global name
* @param value Variable value
*/
template <class T> void setGlobal(const String &name, const T &value) {
set(value);
setPreviousValueAsGlobal(name);
}
/**
* @brief Set previously stored value as global
*
* @param name Global variable name
*/
void setPreviousValueAsGlobal(const String &name);
/**
* @brief Check if global function exists i
*
* @param name Function name
* @retval true Function exists
* @retval false Function does not exist
*/
bool hasFunction(const String &name);
/**
* @brief Call global function
*
* @param numArgs Number of arguments
*/
void call(uint32_t numArgs);
/**
* @brief Create table
*
* @param size Table size
* @return Lua table
*/
LuaTable createTable(uint32_t size);
/**
* @brief Get Lua state
*
* @return Lua state
*/
inline lua_State *getLuaState() { return mScope; }
/**
* @brief Get global variable and add it to stack
*
* @param name Variable name
* @return Lua result
*/
int luaGetGlobal(const String &name);
/**
* @brief Pop items from the stack
*
* @param count Number of elements to pop
*/
void pop(int count);
private:
/**
* @brief Convert stack value to integer
*
* @param index Stack index
* @return Integer value
*/
int32_t luaGetInteger(int index);
/**
* @brief Convert stack value to decimal
*
* @param index Stack index
* @return Decimal
*/
float luaGetNumber(int index);
/**
* @brief Convert stack value to string
*
* @param index Stack index
* @return String value
*/
StringView luaGetString(int index);
/**
* @brief Convert stack value to user data
*
* @param index Stack index
* @return User data value
*/
void *luaGetUserData(int index);
/**
* @brief Check if stack value is a number
*
* @param index Stack index
* @retval true Value is number
* @retval false Value is not a number
*/
bool luaIsNumber(int index);
/**
* @brief Check if stack value is a string
*
* @param index Stack index
* @retval true Value is string
* @retval false Value is not a string
*/
bool luaIsString(int index);
/**
* @brief Push floating point to stack
*
* @param value Floating point value
*/
void luaSetNumber(float value);
/**
* @brief Push string to stack
*
* @param value String value
*/
void luaSetString(const String &value);
/**
* @brief Push user data to the stack
*
* @param value User data value
*/
void luaSetUserData(void *value);
private:
lua_State *mScope = nullptr;
};
/**
* @brief Get integer
*
* @param index Stack index
* @return Integer value
*/
template <> inline int32_t LuaScope::get<int32_t>(int32_t index) {
return luaGetInteger(index);
}
/**
* @brief Get unsigned integer
*
* @param index Stack index
* @return Unsigned integer
*/
template <> inline uint32_t LuaScope::get<uint32_t>(int32_t index) {
return static_cast<uint32_t>(luaGetInteger(index));
}
/**
* @brief Get floating point
*
* @param index Stack index
* @return Floating point value
*/
template <> inline float LuaScope::get<float>(int32_t index) {
return luaGetNumber(index);
}
/**
* @brief Get string view
*
* @param index Stack index
* @return String view
*/
template <> inline StringView LuaScope::get<StringView>(int32_t index) {
return luaGetString(index);
}
/**
* @brief Get string
*
* @param index Stack index
* @return String
*/
template <> inline String LuaScope::get<String>(int32_t index) {
return String(luaGetString(index));
}
/**
* @brief Get table
*
* @param index Stack index
* @return Lua table
*/
template <> inline LuaTable LuaScope::get<LuaTable>(int32_t index) {
return LuaTable(static_cast<void *>(mScope));
}
/**
* @brief Get user data
*
* @param index Stack index
* @return User data
*/
template <> inline LuaUserData LuaScope::get<LuaUserData>(int32_t index) {
return {luaGetUserData(index)};
}
/**
* @brief Check if variable is a string
*
* @param index Stack index
* @retval true Type matches
* @retval false Type does not match
*/
template <> inline bool LuaScope::is<String>(int32_t index) {
return luaIsString(index);
}
/**
* @brief Check if variable is a floating point
*
* @param index Stack index
* @retval true Type matches
* @retval false Type does not match
*/
template <> inline bool LuaScope::is<float>(int32_t index) {
return luaIsNumber(index);
}
/**
* @brief Set floating point
*
* @param value Floating point value
*/
template <> inline void LuaScope::set<float>(const float &value) {
luaSetNumber(value);
}
/**
* @brief Set string
*
* @param value String value
*/
template <> inline void LuaScope::set<String>(const String &value) {
luaSetString(value);
}
/**
* @brief Set user data
*
* @param value User data value
*/
template <> inline void LuaScope::set<LuaUserData>(const LuaUserData &value) {
luaSetUserData(value.pointer);
}
/**
* @brief Get global table variable
*
* @param name Variable global name
* @return Table value
*/
template <> inline LuaTable LuaScope::getGlobal<LuaTable>(const String &name) {
luaGetGlobal(name);
return get<LuaTable>();
}
} // namespace liquid
| 19.423684 | 79 | 0.644086 | [
"object"
] |
27003c9cbb2d9710528070affe33c907b9980af3 | 899 | h | C | include/stack.h | proglanguage/anal_ex | 83b6cadbb325638185169b59ab955b8349f22c84 | [
"MIT"
] | 4 | 2019-04-23T00:33:29.000Z | 2021-12-27T21:29:26.000Z | include/stack.h | proglanguage/anal_ex | 83b6cadbb325638185169b59ab955b8349f22c84 | [
"MIT"
] | null | null | null | include/stack.h | proglanguage/anal_ex | 83b6cadbb325638185169b59ab955b8349f22c84 | [
"MIT"
] | 1 | 2019-05-21T01:22:42.000Z | 2019-05-21T01:22:42.000Z | //> addapted from https://www.techiedelight.com/stack-implementation/
#ifndef __STACK_H__
#define __STACK_H__
#include <stdlib.h>
#include <stdio.h>
typedef struct stack{
int max; // the max siz of the stack
int top; // The element in top of the stack
char** items; // vector of elements in the stack
}stack;
// Utility function to initialize stack
stack* newStack(int capacity);
// Utility function to return the size of the stack
int size(stack *pt);
// Utility function to check if the stack is empty or not
int isEmpty(stack *pt);
// Utility function to check if the stack is full or not
int isFull(stack *pt);
// Utility function to add an element x in the stack
void push(stack *pt, char* x);
// Utility function to return top element in a stack
char* top(stack *pt);
// Utility function to pop top element from the stack
char* pop(stack *pt);
#endif /** __STACK_H__ **/
| 24.972222 | 69 | 0.719689 | [
"vector"
] |
271c86c0b7c7fa3c629fe73a752ca5c810895f49 | 3,057 | h | C | include/RPN.h | Park-ma/Learn-Algorithms | b9f6c1c663a3d1c29d913e7a90f3031075c2b7b9 | [
"MIT"
] | 1 | 2021-01-12T14:27:33.000Z | 2021-01-12T14:27:33.000Z | include/RPN.h | Park-ma/Learn-Algorithms | b9f6c1c663a3d1c29d913e7a90f3031075c2b7b9 | [
"MIT"
] | null | null | null | include/RPN.h | Park-ma/Learn-Algorithms | b9f6c1c663a3d1c29d913e7a90f3031075c2b7b9 | [
"MIT"
] | null | null | null |
#ifndef LEARN_ALGORITHMS_RPN_H
#define LEARN_ALGORITHMS_RPN_H
#include <string>
#include <vector>
#include <stack>
#include <cctype>
namespace learn_al{
const char pri[9][9] = { //运算符优先等级 [栈顶] [当前]
/* |-------------------- 当 前 运 算 符 --------------------| */
/* + - * / ^ ! ( ) \0 */
/* -- + */ '>', '>', '<', '<', '<', '<', '<', '>', '>',
/* | - */ '>', '>', '<', '<', '<', '<', '<', '>', '>',
/* 栈 * */ '>', '>', '>', '>', '<', '<', '<', '>', '>',
/* 顶 / */ '>', '>', '>', '>', '<', '<', '<', '>', '>',
/* 运 ^ */ '>', '>', '>', '>', '>', '<', '<', '>', '>',
/* 算 ! */ '>', '>', '>', '>', '>', '>', ' ', '>', '>',
/* 符 ( */ '<', '<', '<', '<', '<', '<', '<', '=', ' ',
/* | ) */ ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
/* -- \0 */ '<', '<', '<', '<', '<', '<', '<', ' ', '='
};
using std::vector;
using std::string;
using std::stack;
char orderBetween(char c1,char c2);
int optr2int ( char op );
vector<string> inToPost(vector<string> const &infix){
vector<string> postfix;
stack<char> optr;
optr.push('\0');
int i = 0;
while (!optr.empty()&&i<infix.size()){
if(infix[i].size() > 1 || (infix[i].size() == 1) && std::isdigit(infix[i][0])){
postfix.push_back(infix[i]);
i++;
}else{
char c = static_cast<char>(infix[i][0]);
switch (orderBetween(optr.top(),c)) {
case '<':
optr.push(c);
i++;
break;
case '=':
optr.pop();
i++;
break;
case '>':{
char op = optr.top();
postfix.emplace_back(1, op);
optr.pop();
break;
}
default:
exit(-1);
}
}
}
return postfix;
}
char orderBetween(char c1,char c2){
int i1 = optr2int(c1);
int i2 = optr2int(c2);
return pri[i1][i2];
}
int optr2int ( char op ) { //由运算符转译出编号
switch ( op ) {
case '+' : return 0; //加
case '-' : return 1; //减
case '*' : return 2; //乘
case '/' : return 3; //除
case '^' : return 4; //乘方
case '!' : return 5; //阶乘
case '(' : return 6; //左括号
case ')' : return 7; //右括号
case '\0': return 8; //起始符与终止符
default : exit ( -1 ); //未知运算符
}
}
}
#endif //LEARN_ALGORITHMS_RPN_H
| 36.392857 | 91 | 0.281976 | [
"vector"
] |
271f1b96bca35cfc8f43c60f39a067d8fba9bde9 | 2,248 | h | C | Graphics/ColorRGBA.h | PremiumGraphicsCodes/CGLib | eecd73c5af1a9e0c044e7d675318dbb496aec6b5 | [
"MIT"
] | null | null | null | Graphics/ColorRGBA.h | PremiumGraphicsCodes/CGLib | eecd73c5af1a9e0c044e7d675318dbb496aec6b5 | [
"MIT"
] | null | null | null | Graphics/ColorRGBA.h | PremiumGraphicsCodes/CGLib | eecd73c5af1a9e0c044e7d675318dbb496aec6b5 | [
"MIT"
] | 1 | 2022-02-03T08:09:03.000Z | 2022-02-03T08:09:03.000Z | #ifndef __CRYSTAL_GRAPHICS_COLOR_RGBA_H__
#define __CRYSTAL_GRAPHICS_COLOR_RGBA_H__
#include <vector>
#include <array>
namespace Crystal {
namespace Graphics {
class ColorHSV;
template< typename T >
class ColorRGBA {
public:
ColorRGBA();
ColorRGBA(const T red, const T green, const T blue, const T alpha = 255);
void setRed( const T r ) { this->red = r; }
T getRed() const { return red; }
void setGreen( const T g ) { this->green = g; }
T getGreen() const { return this->green; }
void setBlue(const T b) { this->blue = b; }
T getBlue() const { return blue; }
void setAlpha(const T a) { this->alpha = a; }
T getAlpha() const { return alpha; }
static ColorRGBA White() { return ColorRGBA( 255, 255, 255 ); }
static ColorRGBA Black() { return ColorRGBA( 0, 0, 0); }
static ColorRGBA Red() { return ColorRGBA( 255, 0, 0); }
static ColorRGBA Green() { return ColorRGBA( 0, 255, 0 ); }
static ColorRGBA Blue() { return ColorRGBA( 0, 0, 255 ); }
static ColorRGBA Yellow() { return ColorRGBA( 255, 255, 0 ); }
static ColorRGBA Cyan() { return ColorRGBA( 0, 255, 255 ); }
static ColorRGBA Magenta() { return ColorRGBA( 255, 0, 255 ); }
std::array<T, 3> toArray3() const;
std::vector<T> toArray4() const;
bool equals(const ColorRGBA& rhs) const;
bool operator==( const ColorRGBA& rhs ) const { return equals( rhs ); }
bool operator!=(const ColorRGBA& rhs) const { return !equals( rhs ); }
ColorRGBA<T> getScaled( const T f ) const { return ColorRGBA<T>( getRed() * f, getGreen() * f, getBlue() * f ); }
void add( const ColorRGBA& rhs ) {
this->red += rhs.red;
this->green += rhs.green;
this->blue += rhs.blue;
}
ColorRGBA<T> getAdded( const ColorRGBA<T>& rhs ) const {
return ColorRGBA<T>( this->red + rhs.red, this->green + rhs.green, this->blue + rhs.blue );
}
void operator+=( const ColorRGBA& rhs ) { add( rhs ); }
ColorRGBA<T> operator+( const ColorRGBA& rhs ) const { return getAdded( rhs ); }
T toGrayScale() const {
const auto g = 77 * red + 150 * green + 29 * blue;
return g / T{ 255 };
}
ColorHSV toHSV() const;
public:
T red;
T green;
T blue;
T alpha;
};
}
}
#endif | 24.172043 | 115 | 0.622776 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.