hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | 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 270 | max_issues_repo_name stringlengths 5 116 | 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 270 | max_forks_repo_name stringlengths 5 116 | 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 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a0270ba921c97b9e11884de1d7532fab07d9f679 | 25,217 | cpp | C++ | exportNF/release/windows/obj/src/flixel/input/touch/FlxTouchManager.cpp | theblobscp/NekoFreakMod-FridayNightFunkin | 232bcb08234cfe881fd6d52b13e6ae443e105fd1 | [
"BSD-3-Clause"
] | null | null | null | exportNF/release/windows/obj/src/flixel/input/touch/FlxTouchManager.cpp | theblobscp/NekoFreakMod-FridayNightFunkin | 232bcb08234cfe881fd6d52b13e6ae443e105fd1 | [
"BSD-3-Clause"
] | null | null | null | exportNF/release/windows/obj/src/flixel/input/touch/FlxTouchManager.cpp | theblobscp/NekoFreakMod-FridayNightFunkin | 232bcb08234cfe881fd6d52b13e6ae443e105fd1 | [
"BSD-3-Clause"
] | null | null | null | // Generated by Haxe 4.2.1+bf9ff69
#include <hxcpp.h>
#ifndef INCLUDED_Std
#include <Std.h>
#endif
#ifndef INCLUDED_flixel_input_FlxInput
#include <flixel/input/FlxInput.h>
#endif
#ifndef INCLUDED_flixel_input_FlxPointer
#include <flixel/input/FlxPointer.h>
#endif
#ifndef INCLUDED_flixel_input_IFlxInput
#include <flixel/input/IFlxInput.h>
#endif
#ifndef INCLUDED_flixel_input_IFlxInputManager
#include <flixel/input/IFlxInputManager.h>
#endif
#ifndef INCLUDED_flixel_input_touch_FlxTouch
#include <flixel/input/touch/FlxTouch.h>
#endif
#ifndef INCLUDED_flixel_input_touch_FlxTouchManager
#include <flixel/input/touch/FlxTouchManager.h>
#endif
#ifndef INCLUDED_flixel_util_IFlxDestroyable
#include <flixel/util/IFlxDestroyable.h>
#endif
#ifndef INCLUDED_haxe_IMap
#include <haxe/IMap.h>
#endif
#ifndef INCLUDED_haxe_ds_IntMap
#include <haxe/ds/IntMap.h>
#endif
#ifndef INCLUDED_lime_app_IModule
#include <lime/app/IModule.h>
#endif
#ifndef INCLUDED_openfl_Lib
#include <openfl/Lib.h>
#endif
#ifndef INCLUDED_openfl_display_DisplayObject
#include <openfl/display/DisplayObject.h>
#endif
#ifndef INCLUDED_openfl_display_DisplayObjectContainer
#include <openfl/display/DisplayObjectContainer.h>
#endif
#ifndef INCLUDED_openfl_display_IBitmapDrawable
#include <openfl/display/IBitmapDrawable.h>
#endif
#ifndef INCLUDED_openfl_display_InteractiveObject
#include <openfl/display/InteractiveObject.h>
#endif
#ifndef INCLUDED_openfl_display_MovieClip
#include <openfl/display/MovieClip.h>
#endif
#ifndef INCLUDED_openfl_display_Sprite
#include <openfl/display/Sprite.h>
#endif
#ifndef INCLUDED_openfl_display_Stage
#include <openfl/display/Stage.h>
#endif
#ifndef INCLUDED_openfl_events_Event
#include <openfl/events/Event.h>
#endif
#ifndef INCLUDED_openfl_events_EventDispatcher
#include <openfl/events/EventDispatcher.h>
#endif
#ifndef INCLUDED_openfl_events_IEventDispatcher
#include <openfl/events/IEventDispatcher.h>
#endif
#ifndef INCLUDED_openfl_events_TouchEvent
#include <openfl/events/TouchEvent.h>
#endif
#ifndef INCLUDED_openfl_ui_Multitouch
#include <openfl/ui/Multitouch.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_267129cd6cd94d38_160_new,"flixel.input.touch.FlxTouchManager","new",0x0e972b2d,"flixel.input.touch.FlxTouchManager.new","flixel/input/touch/FlxTouchManager.hx",160,0xc27259e6)
HX_LOCAL_STACK_FRAME(_hx_pos_267129cd6cd94d38_39_getByID,"flixel.input.touch.FlxTouchManager","getByID",0x18c2ee75,"flixel.input.touch.FlxTouchManager.getByID","flixel/input/touch/FlxTouchManager.hx",39,0xc27259e6)
HX_LOCAL_STACK_FRAME(_hx_pos_267129cd6cd94d38_47_getFirst,"flixel.input.touch.FlxTouchManager","getFirst",0xd4f3e5cd,"flixel.input.touch.FlxTouchManager.getFirst","flixel/input/touch/FlxTouchManager.hx",47,0xc27259e6)
HX_LOCAL_STACK_FRAME(_hx_pos_267129cd6cd94d38_62_destroy,"flixel.input.touch.FlxTouchManager","destroy",0x29a37247,"flixel.input.touch.FlxTouchManager.destroy","flixel/input/touch/FlxTouchManager.hx",62,0xc27259e6)
HX_LOCAL_STACK_FRAME(_hx_pos_267129cd6cd94d38_85_justStarted,"flixel.input.touch.FlxTouchManager","justStarted",0x4159d442,"flixel.input.touch.FlxTouchManager.justStarted","flixel/input/touch/FlxTouchManager.hx",85,0xc27259e6)
HX_LOCAL_STACK_FRAME(_hx_pos_267129cd6cd94d38_116_justReleased,"flixel.input.touch.FlxTouchManager","justReleased",0x217e7e9c,"flixel.input.touch.FlxTouchManager.justReleased","flixel/input/touch/FlxTouchManager.hx",116,0xc27259e6)
HX_LOCAL_STACK_FRAME(_hx_pos_267129cd6cd94d38_143_reset,"flixel.input.touch.FlxTouchManager","reset",0x90b1b1dc,"flixel.input.touch.FlxTouchManager.reset","flixel/input/touch/FlxTouchManager.hx",143,0xc27259e6)
HX_LOCAL_STACK_FRAME(_hx_pos_267129cd6cd94d38_176_handleTouchBegin,"flixel.input.touch.FlxTouchManager","handleTouchBegin",0x51a5a0c5,"flixel.input.touch.FlxTouchManager.handleTouchBegin","flixel/input/touch/FlxTouchManager.hx",176,0xc27259e6)
HX_LOCAL_STACK_FRAME(_hx_pos_267129cd6cd94d38_193_handleTouchEnd,"flixel.input.touch.FlxTouchManager","handleTouchEnd",0xa3529b77,"flixel.input.touch.FlxTouchManager.handleTouchEnd","flixel/input/touch/FlxTouchManager.hx",193,0xc27259e6)
HX_LOCAL_STACK_FRAME(_hx_pos_267129cd6cd94d38_206_handleTouchMove,"flixel.input.touch.FlxTouchManager","handleTouchMove",0x4a3ff3f5,"flixel.input.touch.FlxTouchManager.handleTouchMove","flixel/input/touch/FlxTouchManager.hx",206,0xc27259e6)
HX_LOCAL_STACK_FRAME(_hx_pos_267129cd6cd94d38_222_add,"flixel.input.touch.FlxTouchManager","add",0x0e8d4cee,"flixel.input.touch.FlxTouchManager.add","flixel/input/touch/FlxTouchManager.hx",222,0xc27259e6)
HX_LOCAL_STACK_FRAME(_hx_pos_267129cd6cd94d38_237_recycle,"flixel.input.touch.FlxTouchManager","recycle",0x3ca95560,"flixel.input.touch.FlxTouchManager.recycle","flixel/input/touch/FlxTouchManager.hx",237,0xc27259e6)
HX_LOCAL_STACK_FRAME(_hx_pos_267129cd6cd94d38_253_update,"flixel.input.touch.FlxTouchManager","update",0x8957295c,"flixel.input.touch.FlxTouchManager.update","flixel/input/touch/FlxTouchManager.hx",253,0xc27259e6)
HX_LOCAL_STACK_FRAME(_hx_pos_267129cd6cd94d38_278_onFocus,"flixel.input.touch.FlxTouchManager","onFocus",0x9fe44386,"flixel.input.touch.FlxTouchManager.onFocus","flixel/input/touch/FlxTouchManager.hx",278,0xc27259e6)
HX_LOCAL_STACK_FRAME(_hx_pos_267129cd6cd94d38_282_onFocusLost,"flixel.input.touch.FlxTouchManager","onFocusLost",0x9504548a,"flixel.input.touch.FlxTouchManager.onFocusLost","flixel/input/touch/FlxTouchManager.hx",282,0xc27259e6)
HX_LOCAL_STACK_FRAME(_hx_pos_267129cd6cd94d38_17_boot,"flixel.input.touch.FlxTouchManager","boot",0xadc79cc5,"flixel.input.touch.FlxTouchManager.boot","flixel/input/touch/FlxTouchManager.hx",17,0xc27259e6)
namespace flixel{
namespace input{
namespace touch{
void FlxTouchManager_obj::__construct(){
HX_GC_STACKFRAME(&_hx_pos_267129cd6cd94d38_160_new)
HXLINE( 161) this->list = ::Array_obj< ::Dynamic>::__new();
HXLINE( 162) this->_inactiveTouches = ::Array_obj< ::Dynamic>::__new();
HXLINE( 163) this->_touchesCache = ::haxe::ds::IntMap_obj::__alloc( HX_CTX );
HXLINE( 164) ::flixel::input::touch::FlxTouchManager_obj::maxTouchPoints = ::openfl::ui::Multitouch_obj::maxTouchPoints;
HXLINE( 165) ::openfl::ui::Multitouch_obj::inputMode = 2;
HXLINE( 167) ::openfl::Lib_obj::get_current()->stage->addEventListener(HX_("touchBegin",ea,cd,e6,a9),this->handleTouchBegin_dyn(),null(),null(),null());
HXLINE( 168) ::openfl::Lib_obj::get_current()->stage->addEventListener(HX_("touchEnd",5c,c5,09,00),this->handleTouchEnd_dyn(),null(),null(),null());
HXLINE( 169) ::openfl::Lib_obj::get_current()->stage->addEventListener(HX_("touchMove",70,72,cd,0d),this->handleTouchMove_dyn(),null(),null(),null());
}
Dynamic FlxTouchManager_obj::__CreateEmpty() { return new FlxTouchManager_obj; }
void *FlxTouchManager_obj::_hx_vtable = 0;
Dynamic FlxTouchManager_obj::__Create(::hx::DynamicArray inArgs)
{
::hx::ObjectPtr< FlxTouchManager_obj > _hx_result = new FlxTouchManager_obj();
_hx_result->__construct();
return _hx_result;
}
bool FlxTouchManager_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x3f93d6ef;
}
static ::flixel::input::IFlxInputManager_obj _hx_flixel_input_touch_FlxTouchManager__hx_flixel_input_IFlxInputManager= {
( void (::hx::Object::*)())&::flixel::input::touch::FlxTouchManager_obj::destroy,
( void (::hx::Object::*)())&::flixel::input::touch::FlxTouchManager_obj::reset,
( void (::hx::Object::*)())&::flixel::input::touch::FlxTouchManager_obj::update,
( void (::hx::Object::*)())&::flixel::input::touch::FlxTouchManager_obj::onFocus,
( void (::hx::Object::*)())&::flixel::input::touch::FlxTouchManager_obj::onFocusLost,
};
static ::flixel::util::IFlxDestroyable_obj _hx_flixel_input_touch_FlxTouchManager__hx_flixel_util_IFlxDestroyable= {
( void (::hx::Object::*)())&::flixel::input::touch::FlxTouchManager_obj::destroy,
};
void *FlxTouchManager_obj::_hx_getInterface(int inHash) {
switch(inHash) {
case (int)0x65dd217a: return &_hx_flixel_input_touch_FlxTouchManager__hx_flixel_input_IFlxInputManager;
case (int)0xd4fe2fcd: return &_hx_flixel_input_touch_FlxTouchManager__hx_flixel_util_IFlxDestroyable;
}
#ifdef HXCPP_SCRIPTABLE
return super::_hx_getInterface(inHash);
#else
return 0;
#endif
}
::flixel::input::touch::FlxTouch FlxTouchManager_obj::getByID(int TouchPointID){
HX_STACKFRAME(&_hx_pos_267129cd6cd94d38_39_getByID)
HXDLIN( 39) return ( ( ::flixel::input::touch::FlxTouch)(this->_touchesCache->get(TouchPointID)) );
}
HX_DEFINE_DYNAMIC_FUNC1(FlxTouchManager_obj,getByID,return )
::flixel::input::touch::FlxTouch FlxTouchManager_obj::getFirst(){
HX_STACKFRAME(&_hx_pos_267129cd6cd94d38_47_getFirst)
HXDLIN( 47) if (::hx::IsNotNull( this->list->__get(0).StaticCast< ::flixel::input::touch::FlxTouch >() )) {
HXLINE( 49) return this->list->__get(0).StaticCast< ::flixel::input::touch::FlxTouch >();
}
else {
HXLINE( 53) return null();
}
HXLINE( 47) return null();
}
HX_DEFINE_DYNAMIC_FUNC0(FlxTouchManager_obj,getFirst,return )
void FlxTouchManager_obj::destroy(){
HX_STACKFRAME(&_hx_pos_267129cd6cd94d38_62_destroy)
HXLINE( 63) {
HXLINE( 63) int _g = 0;
HXDLIN( 63) ::Array< ::Dynamic> _g1 = this->list;
HXDLIN( 63) while((_g < _g1->length)){
HXLINE( 63) ::flixel::input::touch::FlxTouch touch = _g1->__get(_g).StaticCast< ::flixel::input::touch::FlxTouch >();
HXDLIN( 63) _g = (_g + 1);
HXLINE( 65) touch->destroy();
}
}
HXLINE( 67) this->list = null();
HXLINE( 69) {
HXLINE( 69) int _g2 = 0;
HXDLIN( 69) ::Array< ::Dynamic> _g3 = this->_inactiveTouches;
HXDLIN( 69) while((_g2 < _g3->length)){
HXLINE( 69) ::flixel::input::touch::FlxTouch touch = _g3->__get(_g2).StaticCast< ::flixel::input::touch::FlxTouch >();
HXDLIN( 69) _g2 = (_g2 + 1);
HXLINE( 71) touch->destroy();
}
}
HXLINE( 73) this->_inactiveTouches = null();
HXLINE( 75) this->_touchesCache = null();
}
HX_DEFINE_DYNAMIC_FUNC0(FlxTouchManager_obj,destroy,(void))
::Array< ::Dynamic> FlxTouchManager_obj::justStarted(::Array< ::Dynamic> TouchArray){
HX_STACKFRAME(&_hx_pos_267129cd6cd94d38_85_justStarted)
HXLINE( 86) if (::hx::IsNull( TouchArray )) {
HXLINE( 88) TouchArray = ::Array_obj< ::Dynamic>::__new();
}
HXLINE( 91) int touchLen = TouchArray->length;
HXLINE( 93) if ((touchLen > 0)) {
HXLINE( 95) TouchArray->removeRange(0,touchLen);
}
HXLINE( 98) {
HXLINE( 98) int _g = 0;
HXDLIN( 98) ::Array< ::Dynamic> _g1 = this->list;
HXDLIN( 98) while((_g < _g1->length)){
HXLINE( 98) ::flixel::input::touch::FlxTouch touch = _g1->__get(_g).StaticCast< ::flixel::input::touch::FlxTouch >();
HXDLIN( 98) _g = (_g + 1);
HXLINE( 100) if ((touch->input->current == 2)) {
HXLINE( 102) TouchArray->push(touch);
}
}
}
HXLINE( 106) return TouchArray;
}
HX_DEFINE_DYNAMIC_FUNC1(FlxTouchManager_obj,justStarted,return )
::Array< ::Dynamic> FlxTouchManager_obj::justReleased(::Array< ::Dynamic> TouchArray){
HX_STACKFRAME(&_hx_pos_267129cd6cd94d38_116_justReleased)
HXLINE( 117) if (::hx::IsNull( TouchArray )) {
HXLINE( 119) TouchArray = ::Array_obj< ::Dynamic>::__new();
}
HXLINE( 122) int touchLen = TouchArray->length;
HXLINE( 123) if ((touchLen > 0)) {
HXLINE( 125) TouchArray->removeRange(0,touchLen);
}
HXLINE( 128) {
HXLINE( 128) int _g = 0;
HXDLIN( 128) ::Array< ::Dynamic> _g1 = this->list;
HXDLIN( 128) while((_g < _g1->length)){
HXLINE( 128) ::flixel::input::touch::FlxTouch touch = _g1->__get(_g).StaticCast< ::flixel::input::touch::FlxTouch >();
HXDLIN( 128) _g = (_g + 1);
HXLINE( 130) if ((touch->input->current == -1)) {
HXLINE( 132) TouchArray->push(touch);
}
}
}
HXLINE( 136) return TouchArray;
}
HX_DEFINE_DYNAMIC_FUNC1(FlxTouchManager_obj,justReleased,return )
void FlxTouchManager_obj::reset(){
HX_STACKFRAME(&_hx_pos_267129cd6cd94d38_143_reset)
HXLINE( 144) {
HXLINE( 144) ::Dynamic key = this->_touchesCache->keys();
HXDLIN( 144) while(( (bool)(key->__Field(HX_("hasNext",6d,a5,46,18),::hx::paccDynamic)()) )){
HXLINE( 144) int key1 = ( (int)(key->__Field(HX_("next",f3,84,02,49),::hx::paccDynamic)()) );
HXLINE( 146) this->_touchesCache->remove(key1);
}
}
HXLINE( 149) {
HXLINE( 149) int _g = 0;
HXDLIN( 149) ::Array< ::Dynamic> _g1 = this->list;
HXDLIN( 149) while((_g < _g1->length)){
HXLINE( 149) ::flixel::input::touch::FlxTouch touch = _g1->__get(_g).StaticCast< ::flixel::input::touch::FlxTouch >();
HXDLIN( 149) _g = (_g + 1);
HXLINE( 151) touch->input->reset();
HXLINE( 152) this->_inactiveTouches->push(touch);
}
}
HXLINE( 155) this->list->removeRange(0,this->list->length);
}
HX_DEFINE_DYNAMIC_FUNC0(FlxTouchManager_obj,reset,(void))
void FlxTouchManager_obj::handleTouchBegin( ::openfl::events::TouchEvent FlashEvent){
HX_STACKFRAME(&_hx_pos_267129cd6cd94d38_176_handleTouchBegin)
HXLINE( 177) ::flixel::input::touch::FlxTouch touch = ( ( ::flixel::input::touch::FlxTouch)(this->_touchesCache->get(FlashEvent->touchPointID)) );
HXLINE( 178) if (::hx::IsNotNull( touch )) {
HXLINE( 180) int _hx_tmp = ::Std_obj::_hx_int(FlashEvent->stageX);
HXDLIN( 180) touch->setXY(_hx_tmp,::Std_obj::_hx_int(FlashEvent->stageY));
}
else {
HXLINE( 184) int touch1 = ::Std_obj::_hx_int(FlashEvent->stageX);
HXDLIN( 184) int touch2 = ::Std_obj::_hx_int(FlashEvent->stageY);
HXDLIN( 184) touch = this->recycle(touch1,touch2,FlashEvent->touchPointID);
}
HXLINE( 186) touch->input->press();
}
HX_DEFINE_DYNAMIC_FUNC1(FlxTouchManager_obj,handleTouchBegin,(void))
void FlxTouchManager_obj::handleTouchEnd( ::openfl::events::TouchEvent FlashEvent){
HX_STACKFRAME(&_hx_pos_267129cd6cd94d38_193_handleTouchEnd)
HXLINE( 194) ::flixel::input::touch::FlxTouch touch = ( ( ::flixel::input::touch::FlxTouch)(this->_touchesCache->get(FlashEvent->touchPointID)) );
HXLINE( 196) if (::hx::IsNotNull( touch )) {
HXLINE( 198) touch->input->release();
}
}
HX_DEFINE_DYNAMIC_FUNC1(FlxTouchManager_obj,handleTouchEnd,(void))
void FlxTouchManager_obj::handleTouchMove( ::openfl::events::TouchEvent FlashEvent){
HX_STACKFRAME(&_hx_pos_267129cd6cd94d38_206_handleTouchMove)
HXLINE( 207) ::flixel::input::touch::FlxTouch touch = ( ( ::flixel::input::touch::FlxTouch)(this->_touchesCache->get(FlashEvent->touchPointID)) );
HXLINE( 209) if (::hx::IsNotNull( touch )) {
HXLINE( 211) int _hx_tmp = ::Std_obj::_hx_int(FlashEvent->stageX);
HXDLIN( 211) touch->setXY(_hx_tmp,::Std_obj::_hx_int(FlashEvent->stageY));
}
}
HX_DEFINE_DYNAMIC_FUNC1(FlxTouchManager_obj,handleTouchMove,(void))
::flixel::input::touch::FlxTouch FlxTouchManager_obj::add( ::flixel::input::touch::FlxTouch Touch){
HX_STACKFRAME(&_hx_pos_267129cd6cd94d38_222_add)
HXLINE( 223) this->list->push(Touch);
HXLINE( 224) this->_touchesCache->set(( (int)(Touch->input->ID) ),Touch);
HXLINE( 225) return Touch;
}
HX_DEFINE_DYNAMIC_FUNC1(FlxTouchManager_obj,add,return )
::flixel::input::touch::FlxTouch FlxTouchManager_obj::recycle(int X,int Y,int PointID){
HX_GC_STACKFRAME(&_hx_pos_267129cd6cd94d38_237_recycle)
HXLINE( 238) if ((this->_inactiveTouches->length > 0)) {
HXLINE( 240) ::flixel::input::touch::FlxTouch touch = this->_inactiveTouches->pop().StaticCast< ::flixel::input::touch::FlxTouch >();
HXLINE( 241) touch->recycle(X,Y,PointID);
HXLINE( 242) return this->add(touch);
}
HXLINE( 245) return this->add( ::flixel::input::touch::FlxTouch_obj::__alloc( HX_CTX ,X,Y,PointID));
}
HX_DEFINE_DYNAMIC_FUNC3(FlxTouchManager_obj,recycle,return )
void FlxTouchManager_obj::update(){
HX_STACKFRAME(&_hx_pos_267129cd6cd94d38_253_update)
HXLINE( 254) int i = (this->list->length - 1);
HXLINE( 255) ::flixel::input::touch::FlxTouch touch;
HXLINE( 257) while((i >= 0)){
HXLINE( 259) touch = this->list->__get(i).StaticCast< ::flixel::input::touch::FlxTouch >();
HXLINE( 262) bool _hx_tmp;
HXDLIN( 262) ::flixel::input::FlxInput _this = touch->input;
HXDLIN( 262) bool _hx_tmp1;
HXDLIN( 262) if ((_this->current != 0)) {
HXLINE( 262) _hx_tmp1 = (_this->current == -1);
}
else {
HXLINE( 262) _hx_tmp1 = true;
}
HXDLIN( 262) if (_hx_tmp1) {
HXLINE( 262) _hx_tmp = (touch->input->current != -1);
}
else {
HXLINE( 262) _hx_tmp = false;
}
HXDLIN( 262) if (_hx_tmp) {
HXLINE( 264) touch->input->reset();
HXLINE( 265) this->_touchesCache->remove(( (int)(touch->input->ID) ));
HXLINE( 266) this->list->removeRange(i,1);
HXLINE( 267) this->_inactiveTouches->push(touch);
}
else {
HXLINE( 271) touch->update();
}
HXLINE( 274) i = (i - 1);
}
}
HX_DEFINE_DYNAMIC_FUNC0(FlxTouchManager_obj,update,(void))
void FlxTouchManager_obj::onFocus(){
HX_STACKFRAME(&_hx_pos_267129cd6cd94d38_278_onFocus)
}
HX_DEFINE_DYNAMIC_FUNC0(FlxTouchManager_obj,onFocus,(void))
void FlxTouchManager_obj::onFocusLost(){
HX_STACKFRAME(&_hx_pos_267129cd6cd94d38_282_onFocusLost)
HXDLIN( 282) this->reset();
}
HX_DEFINE_DYNAMIC_FUNC0(FlxTouchManager_obj,onFocusLost,(void))
int FlxTouchManager_obj::maxTouchPoints;
::hx::ObjectPtr< FlxTouchManager_obj > FlxTouchManager_obj::__new() {
::hx::ObjectPtr< FlxTouchManager_obj > __this = new FlxTouchManager_obj();
__this->__construct();
return __this;
}
::hx::ObjectPtr< FlxTouchManager_obj > FlxTouchManager_obj::__alloc(::hx::Ctx *_hx_ctx) {
FlxTouchManager_obj *__this = (FlxTouchManager_obj*)(::hx::Ctx::alloc(_hx_ctx, sizeof(FlxTouchManager_obj), true, "flixel.input.touch.FlxTouchManager"));
*(void **)__this = FlxTouchManager_obj::_hx_vtable;
__this->__construct();
return __this;
}
FlxTouchManager_obj::FlxTouchManager_obj()
{
}
void FlxTouchManager_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(FlxTouchManager);
HX_MARK_MEMBER_NAME(list,"list");
HX_MARK_MEMBER_NAME(_inactiveTouches,"_inactiveTouches");
HX_MARK_MEMBER_NAME(_touchesCache,"_touchesCache");
HX_MARK_END_CLASS();
}
void FlxTouchManager_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(list,"list");
HX_VISIT_MEMBER_NAME(_inactiveTouches,"_inactiveTouches");
HX_VISIT_MEMBER_NAME(_touchesCache,"_touchesCache");
}
::hx::Val FlxTouchManager_obj::__Field(const ::String &inName,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 3:
if (HX_FIELD_EQ(inName,"add") ) { return ::hx::Val( add_dyn() ); }
break;
case 4:
if (HX_FIELD_EQ(inName,"list") ) { return ::hx::Val( list ); }
break;
case 5:
if (HX_FIELD_EQ(inName,"reset") ) { return ::hx::Val( reset_dyn() ); }
break;
case 6:
if (HX_FIELD_EQ(inName,"update") ) { return ::hx::Val( update_dyn() ); }
break;
case 7:
if (HX_FIELD_EQ(inName,"getByID") ) { return ::hx::Val( getByID_dyn() ); }
if (HX_FIELD_EQ(inName,"destroy") ) { return ::hx::Val( destroy_dyn() ); }
if (HX_FIELD_EQ(inName,"recycle") ) { return ::hx::Val( recycle_dyn() ); }
if (HX_FIELD_EQ(inName,"onFocus") ) { return ::hx::Val( onFocus_dyn() ); }
break;
case 8:
if (HX_FIELD_EQ(inName,"getFirst") ) { return ::hx::Val( getFirst_dyn() ); }
break;
case 11:
if (HX_FIELD_EQ(inName,"justStarted") ) { return ::hx::Val( justStarted_dyn() ); }
if (HX_FIELD_EQ(inName,"onFocusLost") ) { return ::hx::Val( onFocusLost_dyn() ); }
break;
case 12:
if (HX_FIELD_EQ(inName,"justReleased") ) { return ::hx::Val( justReleased_dyn() ); }
break;
case 13:
if (HX_FIELD_EQ(inName,"_touchesCache") ) { return ::hx::Val( _touchesCache ); }
break;
case 14:
if (HX_FIELD_EQ(inName,"handleTouchEnd") ) { return ::hx::Val( handleTouchEnd_dyn() ); }
break;
case 15:
if (HX_FIELD_EQ(inName,"handleTouchMove") ) { return ::hx::Val( handleTouchMove_dyn() ); }
break;
case 16:
if (HX_FIELD_EQ(inName,"_inactiveTouches") ) { return ::hx::Val( _inactiveTouches ); }
if (HX_FIELD_EQ(inName,"handleTouchBegin") ) { return ::hx::Val( handleTouchBegin_dyn() ); }
}
return super::__Field(inName,inCallProp);
}
bool FlxTouchManager_obj::__GetStatic(const ::String &inName, Dynamic &outValue, ::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 14:
if (HX_FIELD_EQ(inName,"maxTouchPoints") ) { outValue = ( maxTouchPoints ); return true; }
}
return false;
}
::hx::Val FlxTouchManager_obj::__SetField(const ::String &inName,const ::hx::Val &inValue,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 4:
if (HX_FIELD_EQ(inName,"list") ) { list=inValue.Cast< ::Array< ::Dynamic> >(); return inValue; }
break;
case 13:
if (HX_FIELD_EQ(inName,"_touchesCache") ) { _touchesCache=inValue.Cast< ::haxe::ds::IntMap >(); return inValue; }
break;
case 16:
if (HX_FIELD_EQ(inName,"_inactiveTouches") ) { _inactiveTouches=inValue.Cast< ::Array< ::Dynamic> >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
bool FlxTouchManager_obj::__SetStatic(const ::String &inName,Dynamic &ioValue,::hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 14:
if (HX_FIELD_EQ(inName,"maxTouchPoints") ) { maxTouchPoints=ioValue.Cast< int >(); return true; }
}
return false;
}
void FlxTouchManager_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_("list",5e,1c,b3,47));
outFields->push(HX_("_inactiveTouches",43,04,4f,3d));
outFields->push(HX_("_touchesCache",f4,e3,c3,76));
super::__GetFields(outFields);
};
#ifdef HXCPP_SCRIPTABLE
static ::hx::StorageInfo FlxTouchManager_obj_sMemberStorageInfo[] = {
{::hx::fsObject /* ::Array< ::Dynamic> */ ,(int)offsetof(FlxTouchManager_obj,list),HX_("list",5e,1c,b3,47)},
{::hx::fsObject /* ::Array< ::Dynamic> */ ,(int)offsetof(FlxTouchManager_obj,_inactiveTouches),HX_("_inactiveTouches",43,04,4f,3d)},
{::hx::fsObject /* ::haxe::ds::IntMap */ ,(int)offsetof(FlxTouchManager_obj,_touchesCache),HX_("_touchesCache",f4,e3,c3,76)},
{ ::hx::fsUnknown, 0, null()}
};
static ::hx::StaticInfo FlxTouchManager_obj_sStaticStorageInfo[] = {
{::hx::fsInt,(void *) &FlxTouchManager_obj::maxTouchPoints,HX_("maxTouchPoints",fe,7e,0e,64)},
{ ::hx::fsUnknown, 0, null()}
};
#endif
static ::String FlxTouchManager_obj_sMemberFields[] = {
HX_("list",5e,1c,b3,47),
HX_("_inactiveTouches",43,04,4f,3d),
HX_("_touchesCache",f4,e3,c3,76),
HX_("getByID",28,a9,a5,13),
HX_("getFirst",ba,87,74,60),
HX_("destroy",fa,2c,86,24),
HX_("justStarted",75,64,db,ed),
HX_("justReleased",09,1b,5b,66),
HX_("reset",cf,49,c8,e6),
HX_("handleTouchBegin",b2,77,ad,79),
HX_("handleTouchEnd",24,ed,e0,4d),
HX_("handleTouchMove",a8,19,39,dc),
HX_("add",21,f2,49,00),
HX_("recycle",13,10,8c,37),
HX_("update",09,86,05,87),
HX_("onFocus",39,fe,c6,9a),
HX_("onFocusLost",bd,e4,85,41),
::String(null()) };
static void FlxTouchManager_obj_sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(FlxTouchManager_obj::maxTouchPoints,"maxTouchPoints");
};
#ifdef HXCPP_VISIT_ALLOCS
static void FlxTouchManager_obj_sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(FlxTouchManager_obj::maxTouchPoints,"maxTouchPoints");
};
#endif
::hx::Class FlxTouchManager_obj::__mClass;
static ::String FlxTouchManager_obj_sStaticFields[] = {
HX_("maxTouchPoints",fe,7e,0e,64),
::String(null())
};
void FlxTouchManager_obj::__register()
{
FlxTouchManager_obj _hx_dummy;
FlxTouchManager_obj::_hx_vtable = *(void **)&_hx_dummy;
::hx::Static(__mClass) = new ::hx::Class_obj();
__mClass->mName = HX_("flixel.input.touch.FlxTouchManager",bb,10,25,64);
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &FlxTouchManager_obj::__GetStatic;
__mClass->mSetStaticField = &FlxTouchManager_obj::__SetStatic;
__mClass->mMarkFunc = FlxTouchManager_obj_sMarkStatics;
__mClass->mStatics = ::hx::Class_obj::dupFunctions(FlxTouchManager_obj_sStaticFields);
__mClass->mMembers = ::hx::Class_obj::dupFunctions(FlxTouchManager_obj_sMemberFields);
__mClass->mCanCast = ::hx::TCanCast< FlxTouchManager_obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = FlxTouchManager_obj_sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = FlxTouchManager_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = FlxTouchManager_obj_sStaticStorageInfo;
#endif
::hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
void FlxTouchManager_obj::__boot()
{
{
HX_STACKFRAME(&_hx_pos_267129cd6cd94d38_17_boot)
HXDLIN( 17) maxTouchPoints = 0;
}
}
} // end namespace flixel
} // end namespace input
} // end namespace touch
| 41.75 | 243 | 0.720823 | [
"object",
"3d"
] |
a02a2d8cff90fc14ace2d766f70bec8d3cbbc2de | 2,206 | cpp | C++ | lib/tTetraedr.cpp | B1Z0N/KPI-geometrylib | a83b4394f9c150c131f6533d8cd8c39886684886 | [
"MIT"
] | 2 | 2019-04-28T16:38:54.000Z | 2019-12-27T20:09:43.000Z | lib/tTetraedr.cpp | B1Z0N/KPI-geometrylib | a83b4394f9c150c131f6533d8cd8c39886684886 | [
"MIT"
] | null | null | null | lib/tTetraedr.cpp | B1Z0N/KPI-geometrylib | a83b4394f9c150c131f6533d8cd8c39886684886 | [
"MIT"
] | null | null | null | #include "../include/geometry.hpp"
tTetraedr::tTetraedr(const tPoint &V1, const tPoint &V2, const tPoint &V3, const tPoint &S, char const *NewName)
: tNamed(NewName), fT(V1, V2, V3), fS(S)
{
assert(correct());
}
tTetraedr::tTetraedr(const tTriangle &N, const tPoint &S, char const *NewName)
: tNamed(NewName), fT(N), fS(S)
{
assert(correct());
}
tTetraedr::tTetraedr(double ax, double ay, double az,
double bx, double by, double bz,
double cx, double cy, double cz,
double sx, double sy, double sz, char const *NewName)
: tNamed(NewName), fT(ax, ay, az, bx, by, bz, cx, cy, cz), fS(sx, sy, sz)
{
assert(correct());
}
tTetraedr::tTetraedr(const tTetraedr &T)
:tNamed(T)
{
fT = T.GetT();
fS = T.GetS();
}
tTetraedr::tTetraedr(const tPlane &P1, const tPlane &P2, const tPlane &P3, const tPlane &P4, char const *NewName)
:tNamed(NewName)
{
tPoint S = Cut3Planes(P1, P2, P3), A = Cut3Planes(P1, P2, P4), B = Cut3Planes(P1, P3, P4), C = Cut3Planes(P2, P3, P4);
tTriangle T(A, B, C);
fT = T;
fS = S;
assert(correct());
}
bool tTetraedr::correct() const
{
return !(Volume() < eps);
}
double tTetraedr::Volume() const
{
double Vol;
tPlane P(fT.GetA(), fT.GetB(), fT.GetC());
Vol = (1.0 / 3) * fT.Square() * P.DistToPoint(fS);
return Vol;
}
tPoint tTetraedr::GetS() const
{
return fS;
}
void tTetraedr::SetS(const tPoint &P)
{
fS = P;
assert(correct());
}
tTriangle tTetraedr::GetT() const
{
return fT;
}
void tTetraedr::SetT(const tTriangle &T)
{
fT = T;
assert(correct());
}
tTetraedr &tTetraedr::operator=(const tTetraedr &T)
{
fT = T.GetT();
fS = T.GetS();
return *this;
}
bool operator==(const tTetraedr &T1, const tTetraedr &T2)
{
return ((T1.GetT() == T2.GetT()) && (T1.GetS() == T2.GetS()));
}
ostream &operator<<(ostream &output, const tTetraedr &T)
{
output << "Tetraedr: \nBase:" << T.GetT() << "Pik: " << T.GetS();
return output;
}
istream &operator>>(istream &input, tTetraedr &Tet)
{
tPoint p;
tTriangle T;
cout << "Enter tetraedr(triangle of basis & poiunt of pik): \n";
cin >> T;
cin >> p;
tTetraedr j(T, p);
Tet = j;
} | 21.211538 | 120 | 0.602901 | [
"geometry"
] |
a02c170233ea08198798909bf336041ff22b571c | 3,064 | cpp | C++ | Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkResidualAnalysisWidget.cpp | liu3xing3long/MITK-2016.11 | 385c506f9792414f40337e106e13d5fd61aa3ccc | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkResidualAnalysisWidget.cpp | liu3xing3long/MITK-2016.11 | 385c506f9792414f40337e106e13d5fd61aa3ccc | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Plugins/org.mitk.gui.qt.diffusionimaging/src/QmitkResidualAnalysisWidget.cpp | liu3xing3long/MITK-2016.11 | 385c506f9792414f40337e106e13d5fd61aa3ccc | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*===================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "QmitkResidualAnalysisWidget.h"
#include <QPen>
#include <qwt_legend.h>
#include <qwt_plot_picker.h>
#include <qwt_picker_machine.h>
QmitkResidualAnalysisWidget::QmitkResidualAnalysisWidget( QWidget * parent )
: QmitkPlotWidget(parent)
{
m_PlotPicker = new QwtPlotPicker(m_Plot->canvas());
m_PlotPicker->setStateMachine(new QwtPickerDragPointMachine());
m_PlotPicker->setTrackerMode(QwtPicker::ActiveOnly);
}
QmitkResidualAnalysisWidget::~QmitkResidualAnalysisWidget()
{
delete m_PlotPicker;
}
void QmitkResidualAnalysisWidget::DrawMeans()
{
this->Clear();
this->SetPlotTitle("mean residual per volume");
QPen pen( Qt::SolidLine );
pen.setWidth(1);
// Create values for x-axis
std::vector<double> xAxis;
for(unsigned int i=0; i<m_Means.size(); ++i)
{
xAxis.push_back((double)i);
}
pen.setColor(Qt::black);
int curveId = this->InsertCurve( "Mean" );
this->SetCurveData( curveId, xAxis, m_Means );
this->SetCurvePen( curveId, pen );
this->SetCurveStyle( curveId, QwtPlotCurve::Dots);
pen.setColor(Qt::blue);
curveId = this->InsertCurve( "Q1" );
this->SetCurveData( curveId, xAxis, m_Q1 );
this->SetCurvePen( curveId, pen );
this->SetCurveStyle( curveId, QwtPlotCurve::Dots);
pen.setColor(Qt::red);
curveId = this->InsertCurve( "Q3" );
this->SetCurveData( curveId, xAxis, m_Q3 );
this->SetCurvePen( curveId, pen );
this->SetCurveStyle( curveId, QwtPlotCurve::Dots);
this->m_Plot->setAxisTitle(0, "Residual");
this->m_Plot->setAxisTitle(3, "DWI Volume");
auto legend = new QwtLegend;
this->SetLegend(legend, QwtPlot::RightLegend, 0.5);
this->Replot();
}
void QmitkResidualAnalysisWidget::DrawPercentagesOfOutliers()
{
this->Clear();
this->SetPlotTitle("Percentage of outliers");
QPen pen( Qt::SolidLine );
pen.setWidth(1);
// Create values for x-axis
std::vector<double> xAxis;
for(unsigned int i=0; i<m_PercentagesOfOutliers.size(); ++i)
{
xAxis.push_back((double)i);
}
pen.setColor(Qt::black);
int curveId = this->InsertCurve( "Outliers" );
this->SetCurveData( curveId, xAxis, m_PercentagesOfOutliers );
this->SetCurvePen( curveId, pen );
//this->SetCurveStyle( curveId, QwtPlotCurve::Fitted);
this->m_Plot->setAxisTitle(0, "Percentage of outliers");
this->m_Plot->setAxisTitle(3, "DWI Volume");
auto legend = new QwtLegend;
this->SetLegend(legend, QwtPlot::RightLegend, 0.5);
this->Replot();
}
| 25.966102 | 77 | 0.658616 | [
"vector"
] |
a02da65ce907a035dad53817ff807f981ce8e599 | 4,061 | cpp | C++ | src/libcore/src/libcore/util/BasicLruCache.cpp | sparkoss/ccm | 9ed67a7cbdc9c69f4182e72be8e8b6b23d7c3c8d | [
"Apache-2.0"
] | 6 | 2018-05-08T10:08:21.000Z | 2021-11-13T13:22:58.000Z | src/libcore/src/libcore/util/BasicLruCache.cpp | sparkoss/ccm | 9ed67a7cbdc9c69f4182e72be8e8b6b23d7c3c8d | [
"Apache-2.0"
] | 1 | 2018-05-08T10:20:17.000Z | 2018-07-23T05:19:19.000Z | src/libcore/src/libcore/util/BasicLruCache.cpp | sparkoss/ccm | 9ed67a7cbdc9c69f4182e72be8e8b6b23d7c3c8d | [
"Apache-2.0"
] | 4 | 2018-03-13T06:21:11.000Z | 2021-06-19T02:48:07.000Z | //=========================================================================
// Copyright (C) 2018 The C++ Component Model(CCM) Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "ccm/core/AutoLock.h"
#include "ccm/util/CLinkedHashMap.h"
#include "ccm.util.IMapEntry.h"
#include "libcore/util/BasicLruCache.h"
#include <ccmlogger.h>
using ccm::core::AutoLock;
using ccm::core::E_NULL_POINTER_EXCEPTION;
using ccm::util::CLinkedHashMap;
using ccm::util::IID_IMap;
using ccm::util::ILinkedHashMap;
using ccm::util::IMapEntry;
namespace libcore {
namespace util {
CCM_INTERFACE_IMPL_1(BasicLruCache, SyncObject, IBasicLruCache);
ECode BasicLruCache::Constructor(
/* [in] */ Integer maxSize)
{
if (maxSize <= 0) {
Logger::E("BasicLruCache", "maxSize <= 0");
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
mMaxSize = maxSize;
CLinkedHashMap::New(0, 0.75f, true, IID_IMap, (IInterface**)&mMap);
return NOERROR;
}
ECode BasicLruCache::Get(
/* [in] */ IInterface* key,
/* [out] */ IInterface** value)
{
VALIDATE_NOT_NULL(value);
if (key == nullptr) {
Logger::E("BasicLruCache", "key == null");
return E_NULL_POINTER_EXCEPTION;
}
{
AutoLock lock(this);
mMap->Get(key, value);
if (*value != nullptr) {
return NOERROR;
}
}
// Don't hold any locks while calling create.
AutoPtr<IInterface> result;
FAIL_RETURN(Create(key, &result));
{
AutoLock lock(this);
// NOTE: Another thread might have already inserted a value for |key| into the map.
// This shouldn't be an observable change as long as create creates equal values for
// equal keys. We will however attempt to trim the map twice, but that shouldn't be
// a big deal since uses of this class aren't heavily contended (and this class
// isn't design for such usage anyway).
if (result != nullptr) {
mMap->Put(key, result);
TrimToSize(mMaxSize);
}
}
result.MoveTo(value);
return NOERROR;
}
ECode BasicLruCache::Put(
/* [in] */ IInterface* key,
/* [in] */ IInterface* value,
/* [out] */ IInterface** prevValue)
{
if (key == nullptr) {
Logger::E("BasicLruCache", "key == null");
return E_NULL_POINTER_EXCEPTION;
}
else if (value == nullptr) {
Logger::E("BasicLruCache", "value == null");
return E_NULL_POINTER_EXCEPTION;
}
mMap->Put(key, value, prevValue);
TrimToSize(mMaxSize);
return NOERROR;
}
void BasicLruCache::TrimToSize(
/* [in] */ Integer maxSize)
{
Integer size;
while (mMap->GetSize(&size), size > maxSize) {
AutoPtr<IMapEntry> toEvict;
ILinkedHashMap::Probe(mMap)->GetEldest(&toEvict);
AutoPtr<IInterface> key, value;
toEvict->GetKey(&key);
toEvict->GetValue(&value);
mMap->Remove(key);
EntryEvicted(key, value);
}
}
void BasicLruCache::EntryEvicted(
/* [in] */ IInterface* key,
/* [in] */ IInterface* value)
{}
ECode BasicLruCache::Create(
/* [in] */ IInterface* key,
/* [out] */ IInterface** value)
{
*value = nullptr;
return NOERROR;
}
ECode BasicLruCache::Snapshot(
/* [out] */ IMap** snapshot)
{
return CLinkedHashMap::New(IMap::Probe(mMap), IID_IMap, (IInterface**)snapshot);
}
ECode BasicLruCache::EvictAll()
{
TrimToSize(0);
return NOERROR;
}
}
}
| 26.89404 | 92 | 0.614873 | [
"model"
] |
a034cbd8b84aa86951bbb120e0ef3e659fbbc7e4 | 1,710 | cpp | C++ | lib/random/rand.cpp | listenlink/isaac | b0a265ee45337f92f1e8e9f2fb08a057292b0240 | [
"MIT"
] | 17 | 2017-01-22T10:40:52.000Z | 2021-12-01T07:42:40.000Z | lib/random/rand.cpp | listenlink/isaac | b0a265ee45337f92f1e8e9f2fb08a057292b0240 | [
"MIT"
] | 3 | 2017-01-19T07:17:29.000Z | 2017-02-08T06:07:48.000Z | lib/random/rand.cpp | listenlink/isaac | b0a265ee45337f92f1e8e9f2fb08a057292b0240 | [
"MIT"
] | 13 | 2017-01-10T13:21:03.000Z | 2021-08-11T11:44:06.000Z | /* Copyright 2015-2017 Philippe Tillet
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files
* (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software,
* and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <vector>
#include <random>
#include "isaac/random/rand.h"
namespace isaac
{
namespace random
{
template<typename T>
array rand(tuple const & shape, driver::Context const & context)
{
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_real_distribution<> rng(0, 1);
std::vector<T> data(prod(shape));
for(size_t i = 0 ; i < data.size() ; ++i)
data[i] = rng(mt);
return array(shape, data, context);
}
#define INSTANTIATE(T) template array rand<T>(tuple const &, driver::Context const & context);
INSTANTIATE(float)
INSTANTIATE(double)
#undef INSTANTIATE
}
}
| 32.264151 | 94 | 0.740936 | [
"shape",
"vector"
] |
a03b39936a10a99206f4822fb91fd1850885f0e7 | 4,540 | cpp | C++ | ui.cpp | xanxys/construct | d0a4eaa21a02e9e4440274c1c13dbb5d8ce73ab9 | [
"BSD-2-Clause-FreeBSD"
] | 3 | 2015-01-12T05:42:02.000Z | 2018-11-30T20:02:00.000Z | ui.cpp | xanxys/construct | d0a4eaa21a02e9e4440274c1c13dbb5d8ce73ab9 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | ui.cpp | xanxys/construct | d0a4eaa21a02e9e4440274c1c13dbb5d8ce73ab9 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | #include "ui.h"
#include <boost/algorithm/string.hpp>
namespace construct {
UserMenuScript::UserMenuScript(std::function<Json::Value()> getStat,
cairo_surface_t* surface) :
getStat(getStat), surface(surface) {
}
UserMenuScript::~UserMenuScript() {
cairo_surface_destroy(surface);
}
void UserMenuScript::step(float dt, Object& object) {
const float height_px = 20;
auto c_context = cairo_create(surface);
cairo_select_font_face(c_context, "monospace", CAIRO_FONT_SLANT_NORMAL, CAIRO_FONT_WEIGHT_NORMAL);
cairo_set_source_rgb(c_context, 1, 0.9, 1);
cairo_paint(c_context);
cairo_set_font_size(c_context, height_px);
cairo_set_source_rgb(c_context, 0, 0, 0);
cairo_translate(c_context, 0, 0.8 * height_px);
const std::string stat_multiline = Json::StyledWriter().write(getStat());
std::vector<std::string> lines;
boost::algorithm::split(lines, stat_multiline, boost::is_any_of("\n"));
cairo_save(c_context);
for(const auto& line : lines) {
cairo_show_text(c_context, line.c_str());
cairo_fill(c_context);
cairo_translate(c_context, 0, height_px);
}
cairo_restore(c_context);
cairo_destroy(c_context);
object.texture->useIn();
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
cairo_image_surface_get_width(surface),
cairo_image_surface_get_height(surface),
0, GL_BGRA, GL_UNSIGNED_BYTE,
cairo_image_surface_get_data(surface));
}
LocomotionScript::LocomotionScript(
std::function<OVR::Vector3f()> getHeadDirection,
std::function<Eigen::Vector3f()> getEyePosition,
std::function<void(Eigen::Vector3f)> setMovingDirection,
cairo_surface_t* surface) :
getHeadDirection(getHeadDirection),
getEyePosition(getEyePosition),
setMovingDirection(setMovingDirection),
surface(surface) {
}
LocomotionScript::~LocomotionScript() {
cairo_surface_destroy(surface);
}
void LocomotionScript::step(float dt, Object& object) {
setMovingDirection(Eigen::Vector3f::Zero());
const auto center_u = getEyePosition() - Eigen::Vector3f(0, 0, 1.4 - 0.05);
object.setLocalToWorld(Transform3f(Eigen::Translation<float, 3>(center_u)));
auto dir_pre = getHeadDirection();
const Eigen::Vector3f org = getEyePosition();
const Eigen::Vector3f dir(dir_pre.x, dir_pre.y, dir_pre.z);
// Intersect ray with z = 0.05 (p.dot(normal) = dist)
const Eigen::Vector3f normal(0, 0, 1);
const float dist = 0.05;
const float t = (dist - normal.dot(org)) / normal.dot(dir);
if(t <= 0 || t > 10) {
return;
}
const Eigen::Vector3f isect = org + t * dir;
// Calculate position in normalized surface coord [0,1]^2.
const Eigen::Vector3f center = center_u + Eigen::Vector3f(0, 2.5, 0);
const Eigen::Vector3f size(0.9, 0.4, 0.1);
const Eigen::Vector3f nc = (isect - center + size/2).cwiseQuotient(size);
if(nc.x() < 0 || nc.y() < 0 || nc.x() > 1 || nc.y() > 1) {
return;
}
// Draw something.
auto ctx = cairo_create(surface);
cairo_set_source_rgb(ctx, 1, 1, 1);
cairo_paint(ctx);
cairo_destroy(ctx);
object.texture->useIn();
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
cairo_image_surface_get_width(surface),
cairo_image_surface_get_height(surface),
0, GL_BGRA, GL_UNSIGNED_BYTE,
cairo_image_surface_get_data(surface));
setMovingDirection((isect - Eigen::Vector3f(0, 0, 0.05)).normalized());
}
CursorScript::CursorScript(
std::function<Eigen::Vector3f()> getHeadDirection,
std::function<Eigen::Vector3f()> getEyePosition,
cairo_surface_t* surface) :
getHeadDirection(getHeadDirection),
getEyePosition(getEyePosition),
surface(surface) {
}
CursorScript::~CursorScript() {
cairo_surface_destroy(surface);
}
void CursorScript::step(float dt, Object& object) {
Ray ray(getEyePosition(), getHeadDirection());
auto isect = object.scene.intersectAny(ray);
if(!isect) {
// TODO: hide cursor
} else {
// Send message to the object.
Json::Value message;
message["type"] = "stare";
message["u"] = isect->uv[0];
message["v"] = isect->uv[1];
object.scene.sendMessage(isect->id, message);
// Move cursor.
object.setLocalToWorld(
Eigen::Translation<float, 3>(isect->position + isect->normal * 0.01) *
createBasis(isect->normal));
}
}
Eigen::Matrix3f CursorScript::createBasis(Eigen::Vector3f normal) {
auto seed_y = Eigen::Vector3f::UnitX();
auto axis_x = seed_y.cross(normal);
if(axis_x.norm() == 0) {
axis_x = Eigen::Vector3f::UnitY().cross(normal).normalized();
} else {
axis_x.normalize();
}
auto axis_y = normal.cross(axis_x).normalized();
Eigen::Matrix3f m;
m.col(0) = axis_x;
m.col(1) = axis_y;
m.col(2) = normal;
return m;
}
} // namespace
| 26.091954 | 99 | 0.720264 | [
"object",
"vector"
] |
a03d3ad95cd258291a032090fcc6a62e4bcbfdc4 | 2,975 | cc | C++ | src/Core/Algorithms/Legacy/Fields/MeshData/GetMeshQualityField.cc | benjaminlarson/SCIRunGUIPrototype | ed34ee11cda114e3761bd222a71a9f397517914d | [
"Unlicense"
] | null | null | null | src/Core/Algorithms/Legacy/Fields/MeshData/GetMeshQualityField.cc | benjaminlarson/SCIRunGUIPrototype | ed34ee11cda114e3761bd222a71a9f397517914d | [
"Unlicense"
] | null | null | null | src/Core/Algorithms/Legacy/Fields/MeshData/GetMeshQualityField.cc | benjaminlarson/SCIRunGUIPrototype | ed34ee11cda114e3761bd222a71a9f397517914d | [
"Unlicense"
] | null | null | null | /*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2009 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <Core/Algorithms/Fields/MeshData/GetMeshQualityField.h>
#include <Core/Datatypes/Field.h>
#include <Core/Datatypes/FieldInformation.h>
namespace SCIRunAlgo {
bool
GetMeshQualityFieldAlgo::run(FieldHandle input, FieldHandle& output)
{
algo_start("GetMeshQualityField");
std::string metric = get_option("metric");
if (input.get_rep() == 0)
{
error("No input field");
algo_end(); return (false);
}
FieldInformation fi(input);
fi.make_double();
fi.make_constantdata();
output = CreateField(fi,input->mesh());
if (output.get_rep() == 0)
{
error("Could not create output field");
algo_end(); return (false);
}
VField* ofield = output->vfield();
VMesh* imesh = input->vmesh();
if (metric == "scaled_jacobian")
{
VMesh::Elem::size_type num_values = imesh->num_elems();
for (VMesh::Elem::index_type j=0; j<num_values; j++)
{
ofield->set_value(imesh->scaled_jacobian_metric(j),j);
}
}
else if (metric == "jacobian")
{
VMesh::Elem::size_type num_values = imesh->num_elems();
for (VMesh::Elem::index_type j=0; j<num_values; j++)
{
ofield->set_value(imesh->jacobian_metric(j),j);
}
}
else if (metric == "volume")
{
VMesh::Elem::size_type num_values = imesh->num_elems();
for (VMesh::Elem::index_type j=0; j<num_values; j++)
{
ofield->set_value(imesh->volume_metric(j),j);
}
}
else if (metric == "insc_circ_ratio")
{
VMesh::Elem::size_type num_values = imesh->num_elems();
for (VMesh::Elem::index_type j=0; j<num_values; j++)
{
ofield->set_value(imesh->inscribed_circumscribed_radius_metric(j),j);
}
}
algo_end();
return (true);
}
}
| 29.455446 | 78 | 0.689748 | [
"mesh"
] |
a0447859cac30e6f70c397f1f4a70ad60fe9cb97 | 21,850 | hxx | C++ | include/LOCAL_itkResourceProbe.hxx | InsightSoftwareConsortium/ITKPerformanceBenchmarking | f9a8dc22b67ec63eee023c0734fc7aa5f119356a | [
"Apache-2.0"
] | 1 | 2017-12-07T21:29:59.000Z | 2017-12-07T21:29:59.000Z | include/LOCAL_itkResourceProbe.hxx | InsightSoftwareConsortium/ITKPerformanceBenchmarking | f9a8dc22b67ec63eee023c0734fc7aa5f119356a | [
"Apache-2.0"
] | 33 | 2017-06-30T19:35:06.000Z | 2021-09-22T00:07:26.000Z | include/LOCAL_itkResourceProbe.hxx | InsightSoftwareConsortium/ITKPerformanceBenchmarking | f9a8dc22b67ec63eee023c0734fc7aa5f119356a | [
"Apache-2.0"
] | 6 | 2017-06-30T18:22:47.000Z | 2020-02-19T23:10:16.000Z | /*=========================================================================
*
* Copyright NumFOCUS
*
* 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.txt
*
* 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.
*
*=========================================================================*/
/*=========================================================================
*
* Portions of this file are subject to the VTK Toolkit Version 3 copyright.
*
* Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
*
* For complete copyright, license and disclaimer of warranty information
* please refer to the NOTICE file at the top of the ITK source tree.
*
*=========================================================================*/
#ifndef itkLOCALResourceProbe_hxx
#define itkLOCALResourceProbe_hxx
#include <numeric>
#include <iomanip>
#include <sstream>
#include <algorithm>
#include <functional>
#include <utility>
#include <type_traits>
#include "itkNumericTraits.h"
#include "itksys/SystemInformation.hxx"
#include "itkMath.h"
namespace itk
{
template <typename ValueType, typename MeanType>
LOCAL_ResourceProbe<ValueType, MeanType>::LOCAL_ResourceProbe(std::string type, std::string unit)
: m_TypeString(std::move(type))
, m_UnitString(std::move(unit))
{
this->GetSystemInformation();
this->Reset();
}
template <typename ValueType, typename MeanType>
LOCAL_ResourceProbe<ValueType, MeanType>::~LOCAL_ResourceProbe() = default;
template <typename ValueType, typename MeanType>
void
LOCAL_ResourceProbe<ValueType, MeanType>::Reset()
{
this->m_TotalValue = NumericTraits<ValueType>::ZeroValue();
this->m_StartValue = NumericTraits<ValueType>::ZeroValue();
this->m_MinimumValue = NumericTraits<ValueType>::max();
this->m_MaximumValue = NumericTraits<ValueType>::min();
this->m_MeanValue = NumericTraits<MeanType>::ZeroValue();
this->m_StandardDeviation = NumericTraits<ValueType>::ZeroValue();
this->m_NumberOfStarts = NumericTraits<CountType>::ZeroValue();
this->m_NumberOfStops = NumericTraits<CountType>::ZeroValue();
this->m_NumberOfIteration = NumericTraits<CountType>::ZeroValue();
this->m_ProbeValueList.clear();
}
template <typename ValueType, typename MeanType>
std::string
LOCAL_ResourceProbe<ValueType, MeanType>::GetType() const
{
return this->m_TypeString;
}
template <typename ValueType, typename MeanType>
std::string
LOCAL_ResourceProbe<ValueType, MeanType>::GetUnit() const
{
return this->m_UnitString;
}
template <typename ValueType, typename MeanType>
void
LOCAL_ResourceProbe<ValueType, MeanType>::Start()
{
this->m_NumberOfStarts++;
this->m_StartValue = this->GetInstantValue();
}
template <typename ValueType, typename MeanType>
void
LOCAL_ResourceProbe<ValueType, MeanType>::Stop()
{
ValueType probevalue = this->GetInstantValue() - this->m_StartValue;
if (this->m_NumberOfStops == this->m_NumberOfStarts)
{
return;
}
this->UpdateMinimumMaximumMeasuredValue(probevalue);
this->m_TotalValue += probevalue;
this->m_ProbeValueList.push_back(probevalue);
this->m_NumberOfStops++;
this->m_NumberOfIteration = static_cast<CountType>(this->m_ProbeValueList.size());
}
template <typename ValueType, typename MeanType>
typename LOCAL_ResourceProbe<ValueType, MeanType>::CountType
LOCAL_ResourceProbe<ValueType, MeanType>::GetNumberOfStarts() const
{
return this->m_NumberOfStarts;
}
template <typename ValueType, typename MeanType>
typename LOCAL_ResourceProbe<ValueType, MeanType>::CountType
LOCAL_ResourceProbe<ValueType, MeanType>::GetNumberOfStops() const
{
return this->m_NumberOfStops;
}
template <typename ValueType, typename MeanType>
typename LOCAL_ResourceProbe<ValueType, MeanType>::CountType
LOCAL_ResourceProbe<ValueType, MeanType>::GetNumberOfIteration() const
{
return this->m_NumberOfIteration;
}
template <typename ValueType, typename MeanType>
ValueType
LOCAL_ResourceProbe<ValueType, MeanType>::GetTotal() const
{
return this->m_TotalValue;
}
template <typename ValueType, typename MeanType>
MeanType
LOCAL_ResourceProbe<ValueType, MeanType>::GetMean() const
{
MeanType meanValue = NumericTraits<MeanType>::ZeroValue();
if (this->m_NumberOfStops)
{
meanValue = static_cast<MeanType>(this->m_TotalValue) / static_cast<MeanType>(this->m_NumberOfStops);
}
return meanValue;
}
template <typename ValueType, typename MeanType>
ValueType
LOCAL_ResourceProbe<ValueType, MeanType>::GetMinimum() const
{
return this->m_MinimumValue;
}
template <typename ValueType, typename MeanType>
ValueType
LOCAL_ResourceProbe<ValueType, MeanType>::GetMaximum() const
{
return this->m_MaximumValue;
}
template <typename ValueType, typename MeanType>
ValueType
LOCAL_ResourceProbe<ValueType, MeanType>::GetStandardDeviation()
{
this->m_MeanValue = this->GetMean();
std::vector<ValueType> diff(this->m_ProbeValueList.size());
std::transform(this->m_ProbeValueList.begin(),
this->m_ProbeValueList.end(),
diff.begin(),
std::bind(std::minus<ValueType>(), std::placeholders::_1, static_cast<ValueType>(this->m_MeanValue)));
ValueType sqsum = std::inner_product(diff.begin(), diff.end(), diff.begin(), NumericTraits<ValueType>::ZeroValue());
int sz = static_cast<int>(this->m_ProbeValueList.size()) - 1;
if (sz <= 0)
{
this->m_StandardDeviation = NumericTraits<ValueType>::ZeroValue();
}
else
{
this->m_StandardDeviation =
static_cast<ValueType>(std::sqrt(static_cast<double>(sqsum / (static_cast<ValueType>(sz)))));
}
return this->m_StandardDeviation;
}
template <typename ValueType, typename MeanType>
ValueType
LOCAL_ResourceProbe<ValueType, MeanType>::GetStandardError()
{
const ValueType standardDeviation = this->GetStandardDeviation();
this->m_StandardError =
static_cast<ValueType>(standardDeviation / std::sqrt(static_cast<double>(this->m_ProbeValueList.size())));
return this->m_StandardError;
}
template <typename ValueType, typename MeanType>
void
LOCAL_ResourceProbe<ValueType, MeanType>::SetNameOfProbe(const char * nameOfProbe)
{
this->m_NameOfProbe = nameOfProbe;
}
template <typename ValueType, typename MeanType>
std::string
LOCAL_ResourceProbe<ValueType, MeanType>::GetNameOfProbe() const
{
return this->m_NameOfProbe;
}
template <typename ValueType, typename MeanType>
void
LOCAL_ResourceProbe<ValueType, MeanType>::PrintSystemInformation(std::ostream & os)
{
os << "System: " << m_SystemName << std::endl;
os << "Processor: " << m_ProcessorName << std::endl;
os << " Cache: " << m_ProcessorCacheSize << std::endl;
os << " Clock: " << m_ProcessorClockFrequency << std::endl;
os << " Physical CPUs: " << m_NumberOfPhysicalCPU << std::endl;
os << " Logical CPUs: " << m_NumberOfLogicalCPU << std::endl;
// Retrieve memory information in mebibytes.
os << " Virtual Memory: Total: " << std::left << std::setw(tabwidth) << m_TotalVirtualMemory
<< " Available: " << m_AvailableVirtualMemory << std::endl;
os << " Physical Memory: Total: " << std::left << std::setw(tabwidth) << m_TotalPhysicalMemory
<< " Available: " << m_AvailablePhysicalMemory << std::endl;
os << "OSName: " << m_OSName << std::endl;
os << " Release: " << m_OSRelease << std::endl;
os << " Version: " << m_OSVersion << std::endl;
os << " Platform: " << m_OSPlatform << std::endl;
os << " Operating System is " << (m_Is64Bits ? "64 bit" : "32 bit") << std::endl;
os << "ITK Version: " << m_ITKVersion << std::endl;
}
template <typename ValueType, typename MeanType>
void
LOCAL_ResourceProbe<ValueType, MeanType>::Report(std::ostream & os,
bool printSystemInfo,
bool printReportHead,
bool useTabs)
{
if (printSystemInfo)
{
this->PrintSystemInformation(os);
}
if (printReportHead)
{
this->PrintReportHead(os, useTabs);
}
std::stringstream ss;
if (useTabs)
{
ss << std::left << '\t' << this->m_NameOfProbe << std::left << '\t' << this->m_NumberOfIteration << std::left
<< '\t' << this->GetTotal() << std::left << '\t' << this->GetMinimum() << std::left << '\t' << this->GetMean()
<< std::left << '\t' << this->GetMaximum() << std::left << '\t' << this->GetStandardDeviation();
}
else
{
ss << std::left << std::setw(tabwidth * 2) << this->m_NameOfProbe << std::left << std::setw(tabwidth)
<< this->m_NumberOfIteration << std::left << std::setw(tabwidth) << this->GetTotal() << std::left
<< std::setw(tabwidth) << this->GetMinimum() << std::left << std::setw(tabwidth) << this->GetMean() << std::left
<< std::setw(tabwidth) << this->GetMaximum() << std::left << std::setw(tabwidth) << this->GetStandardDeviation();
}
os << ss.str() << std::endl;
}
template <typename ValueType, typename MeanType>
void
LOCAL_ResourceProbe<ValueType, MeanType>::ExpandedReport(std::ostream & os,
bool printSystemInfo,
bool printReportHead,
bool useTabs)
{
if (printSystemInfo)
{
this->PrintSystemInformation(os);
}
if (printReportHead)
{
this->PrintExpandedReportHead(os, useTabs);
}
std::stringstream ss;
ValueType ratioOfMeanToMinimum;
if (Math::ExactlyEquals(this->GetMinimum(), 0.0))
{
ratioOfMeanToMinimum = NumericTraits<ValueType>::ZeroValue();
}
else
{
ratioOfMeanToMinimum = static_cast<ValueType>(this->GetMean()) / this->GetMinimum();
}
ValueType ratioOfMaximumToMean;
if (Math::ExactlyEquals(this->GetMean(), 0.0))
{
ratioOfMaximumToMean = NumericTraits<ValueType>::ZeroValue();
}
else
{
ratioOfMaximumToMean = this->GetMaximum() / static_cast<ValueType>(this->GetMean());
}
if (useTabs)
{
ss << std::left << '\t' << this->m_NameOfProbe << std::left << '\t' << this->m_NumberOfIteration << std::left
<< '\t' << this->GetTotal() << std::left << '\t' << this->GetMinimum() << std::left << '\t'
<< this->GetMean() - this->GetMinimum() << std::left << '\t' << ratioOfMeanToMinimum * 100 << std::left << '\t'
<< this->GetMean() << std::left << '\t' << this->GetMaximum() - this->GetMean() << std::left << '\t'
<< ratioOfMaximumToMean * 100 << std::left << '\t' << this->GetMaximum() << std::left << '\t'
<< this->GetMaximum() - this->GetMinimum() << std::left << '\t' << this->GetStandardDeviation() << std::left
<< '\t' << this->GetStandardError();
}
else
{
ss << std::left << std::setw(tabwidth * 2) << this->m_NameOfProbe << std::left << std::setw(tabwidth)
<< this->m_NumberOfIteration << std::left << std::setw(tabwidth) << this->GetTotal() << std::left
<< std::setw(tabwidth) << this->GetMinimum() << std::left << std::setw(tabwidth)
<< this->GetMean() - this->GetMinimum() << std::left << std::setw(tabwidth) << ratioOfMeanToMinimum * 100
<< std::left << std::setw(tabwidth) << this->GetMean() << std::left << std::setw(tabwidth)
<< this->GetMaximum() - this->GetMean() << std::left << std::setw(tabwidth) << ratioOfMaximumToMean * 100
<< std::left << std::setw(tabwidth) << this->GetMaximum() << std::left << std::setw(tabwidth)
<< this->GetMaximum() - this->GetMinimum() << std::left << std::setw(tabwidth) << this->GetStandardDeviation()
<< std::left << std::setw(tabwidth) << this->GetStandardError();
}
os << ss.str() << std::endl;
}
template <typename ValueType, typename MeanType>
template <typename T>
void
LOCAL_ResourceProbe<ValueType, MeanType>::PrintJSONvar(std::ostream & os,
const char * varName,
T varValue,
unsigned indent,
bool comma)
{
bool varIsNumber = std::is_arithmetic<T>::value;
while (indent > 0)
{
os << ' ';
--indent;
}
if (varIsNumber) // no quotes around the value
{
os << '"' << varName << "\": " << varValue;
}
else // put quotes around the value
{
os << '"' << varName << "\": \"" << varValue << '"';
}
if (comma)
{
os << ',';
}
os << '\n'; // std::endl has a side-effect of flushing the stream
}
template <typename ValueType, typename MeanType>
void
LOCAL_ResourceProbe<ValueType, MeanType>::JSONReport(std::ostream & os)
{
std::stringstream ss;
ValueType ratioOfMeanToMinimum;
if (Math::ExactlyEquals(this->GetMinimum(), 0.0))
{
ratioOfMeanToMinimum = NumericTraits<ValueType>::ZeroValue();
}
else
{
ratioOfMeanToMinimum = static_cast<ValueType>(this->GetMean()) / this->GetMinimum();
}
ValueType ratioOfMaximumToMean;
if (Math::ExactlyEquals(this->GetMean(), 0.0))
{
ratioOfMaximumToMean = NumericTraits<ValueType>::ZeroValue();
}
else
{
ratioOfMaximumToMean = this->GetMaximum() / static_cast<ValueType>(this->GetMean());
}
os << " {\n";
PrintJSONvar(os, "Name", m_NameOfProbe);
PrintJSONvar(os, "Type", m_TypeString);
PrintJSONvar(os, "Iterations", m_NumberOfIteration);
PrintJSONvar(os, "Units", m_UnitString);
PrintJSONvar(os, "Mean", this->GetMean());
PrintJSONvar(os, "Minimum", this->GetMinimum());
PrintJSONvar(os, "Maximum", this->GetMaximum());
PrintJSONvar(os, "Total", this->GetTotal());
PrintJSONvar(os, "StandardDeviation", this->GetStandardDeviation());
PrintJSONvar(os, "StandardError", this->GetStandardError());
PrintJSONvar(os, "TotalDifference", this->GetMaximum() - this->GetMinimum());
PrintJSONvar(os, "MeanMinimumDifference", this->GetMean() - this->GetMinimum());
PrintJSONvar(os, "MeanMinimumDifferencePercent", ratioOfMeanToMinimum * 100);
PrintJSONvar(os, "MaximumMeanDifference", this->GetMaximum() - this->GetMean());
PrintJSONvar(os, "MaximumMeanDifferencePercent", ratioOfMaximumToMean * 100, 4);
os << " "
<< "\"Values\": [";
for (size_t ii = 0; ii < m_ProbeValueList.size() - 1; ++ii)
{
os << m_ProbeValueList[ii] << ", ";
}
os << m_ProbeValueList.at(m_ProbeValueList.size() - 1);
os << "]\n";
os << " }";
}
template <typename ValueType, typename MeanType>
void
LOCAL_ResourceProbe<ValueType, MeanType>::UpdateMinimumMaximumMeasuredValue(ValueType value)
{
if (this->m_MinimumValue > value)
{
this->m_MinimumValue = value;
}
if (this->m_MaximumValue < value)
{
this->m_MaximumValue = value;
}
}
template <typename ValueType, typename MeanType>
void
LOCAL_ResourceProbe<ValueType, MeanType>::PrintReportHead(std::ostream & os, bool useTabs)
{
std::stringstream ss;
if (useTabs)
{
ss << std::left << '\t' << std::string("Name Of Probe (") + this->m_TypeString + std::string(")") << std::left
<< '\t' << "Iterations" << std::left << '\t' << std::string("Total (") + this->m_UnitString + std::string(")")
<< std::left << '\t' << std::string("Min (") + this->m_UnitString + std::string(")") << std::left << '\t'
<< std::string("Mean (") + this->m_UnitString + std::string(")") << std::left << '\t'
<< std::string("Max (") + this->m_UnitString + std::string(")") << std::left << '\t'
<< std::string("StdDev (") + this->m_UnitString + std::string(")");
}
else
{
ss << std::left << std::setw(tabwidth * 2) << std::string("Name Of Probe (") + this->m_TypeString + std::string(")")
<< std::left << std::setw(tabwidth) << "Iterations" << std::left << std::setw(tabwidth)
<< std::string("Total (") + this->m_UnitString + std::string(")") << std::left << std::setw(tabwidth)
<< std::string("Min (") + this->m_UnitString + std::string(")") << std::left << std::setw(tabwidth)
<< std::string("Mean (") + this->m_UnitString + std::string(")") << std::left << std::setw(tabwidth)
<< std::string("Max (") + this->m_UnitString + std::string(")") << std::left << std::setw(tabwidth)
<< std::string("StdDev (") + this->m_UnitString + std::string(")");
}
os << ss.str() << std::endl;
}
template <typename ValueType, typename MeanType>
void
LOCAL_ResourceProbe<ValueType, MeanType>::PrintExpandedReportHead(std::ostream & os, bool useTabs)
{
std::stringstream ss;
if (useTabs)
{
ss << std::left << '\t' << std::string("Name Of Probe (") + this->m_TypeString + std::string(")") << std::left
<< '\t' << "Iterations" << std::left << '\t' << std::string("Total (") + this->m_UnitString + std::string(")")
<< std::left << '\t' << std::string("Min (") + this->m_UnitString + std::string(")") << std::left << '\t'
<< "Mean-Min (diff)" << std::left << '\t' << "Mean/Min (%)" << std::left << '\t'
<< std::string("Mean (") + this->m_UnitString + std::string(")") << std::left << '\t' << "Max-Mean (diff)"
<< std::left << '\t' << "Max/Mean (%)" << std::left << '\t'
<< std::string("Max (") + this->m_UnitString + std::string(")") << std::left << '\t'
<< std::string("Total Diff (") + this->m_UnitString + std::string(")") << std::left << '\t'
<< std::string("StdDev (") + this->m_UnitString + std::string(")") << std::left << '\t'
<< std::string("StdErr (") + this->m_UnitString + std::string(")");
}
else
{
ss << std::left << std::setw(tabwidth * 2) << std::string("Name Of Probe (") + this->m_TypeString + std::string(")")
<< std::left << std::setw(tabwidth) << "Iterations" << std::left << std::setw(tabwidth)
<< std::string("Total (") + this->m_UnitString + std::string(")") << std::left << std::setw(tabwidth)
<< std::string("Min (") + this->m_UnitString + std::string(")") << std::left << std::setw(tabwidth)
<< "Mean-Min (diff)" << std::left << std::setw(tabwidth) << "Mean/Min (%)" << std::left << std::setw(tabwidth)
<< std::string("Mean (") + this->m_UnitString + std::string(")") << std::left << std::setw(tabwidth)
<< "Max-Mean (diff)" << std::left << std::setw(tabwidth) << "Max/Mean (%)" << std::left << std::setw(tabwidth)
<< std::string("Max (") + this->m_UnitString + std::string(")") << std::left << std::setw(tabwidth)
<< std::string("Total Diff (") + this->m_UnitString + std::string(")") << std::left << std::setw(tabwidth)
<< std::string("StdDev (") + this->m_UnitString + std::string(")") << std::left << std::setw(tabwidth)
<< std::string("StdErr (") + this->m_UnitString + std::string(")");
}
os << ss.str() << std::endl;
}
template <typename ValueType, typename MeanType>
void
LOCAL_ResourceProbe<ValueType, MeanType>::PrintJSONSystemInformation(std::ostream & os)
{
os << "{\n";
PrintJSONvar(os, "System", m_SystemName);
os << " \"Processor\" :{\n";
PrintJSONvar(os, "Name", m_ProcessorName, 6);
PrintJSONvar(os, "Cache", m_ProcessorCacheSize, 6);
PrintJSONvar(os, "Clock", m_ProcessorClockFrequency, 6);
PrintJSONvar(os, "Physical CPUs", m_NumberOfPhysicalCPU, 6);
PrintJSONvar(os, "Logical CPUs", m_NumberOfLogicalCPU, 6);
PrintJSONvar(os, "Virtual Memory Total", m_TotalVirtualMemory, 6);
PrintJSONvar(os, "Virtual Memory Available", m_AvailableVirtualMemory, 6);
PrintJSONvar(os, "Physical Memory Total", m_TotalPhysicalMemory, 6);
PrintJSONvar(os, "Physical Memory Available", m_AvailablePhysicalMemory, 6, false);
os << " },\n";
os << " \"OperatingSystem\" :{\n";
PrintJSONvar(os, "Name", m_OSName, 6);
PrintJSONvar(os, "Release", m_OSRelease, 6);
PrintJSONvar(os, "Version", m_OSVersion, 6);
PrintJSONvar(os, "Platform", m_OSPlatform, 6);
PrintJSONvar(os, "Bitness", (m_Is64Bits ? "64 bit" : "32 bit"), 6, false);
os << " },\n";
PrintJSONvar(os, "ITKVersion", m_ITKVersion, 4, false);
os << " }";
}
template <typename ValueType, typename MeanType>
void
LOCAL_ResourceProbe<ValueType, MeanType>::GetSystemInformation()
{
itksys::SystemInformation systeminfo;
systeminfo.RunCPUCheck();
systeminfo.RunMemoryCheck();
systeminfo.RunOSCheck();
m_SystemName = systeminfo.GetHostname();
m_ProcessorName = systeminfo.GetExtendedProcessorName();
m_ProcessorCacheSize = systeminfo.GetProcessorCacheSize();
m_ProcessorClockFrequency = systeminfo.GetProcessorClockFrequency();
m_NumberOfPhysicalCPU = systeminfo.GetNumberOfPhysicalCPU();
m_NumberOfLogicalCPU = systeminfo.GetNumberOfLogicalCPU();
m_OSName = systeminfo.GetOSName();
m_OSRelease = systeminfo.GetOSRelease();
m_OSVersion = systeminfo.GetOSVersion();
m_OSPlatform = systeminfo.GetOSPlatform();
m_Is64Bits = systeminfo.Is64Bits();
std::ostringstream itkversion;
itkversion << ITK_VERSION_MAJOR << "." << ITK_VERSION_MINOR << "." << ITK_VERSION_PATCH;
m_ITKVersion = itkversion.str();
// Retrieve memory information in mebibytes.
m_TotalVirtualMemory = systeminfo.GetTotalVirtualMemory();
m_AvailableVirtualMemory = systeminfo.GetAvailableVirtualMemory();
m_TotalPhysicalMemory = systeminfo.GetTotalPhysicalMemory();
m_AvailablePhysicalMemory = systeminfo.GetAvailablePhysicalMemory();
}
} // end namespace itk
#endif
| 36.477462 | 120 | 0.635652 | [
"vector",
"transform"
] |
a049d811ea3b23b5326bb4cdf4386b2ae96b2e14 | 13,264 | cc | C++ | chrome/browser/chromeos/drive/download_handler_unittest.cc | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | chrome/browser/chromeos/drive/download_handler_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | chrome/browser/chromeos/drive/download_handler_unittest.cc | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright (c) 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.
#include "chrome/browser/chromeos/drive/download_handler.h"
#include <stdint.h>
#include "base/files/scoped_temp_dir.h"
#include "base/run_loop.h"
#include "chrome/browser/chromeos/drive/file_system_util.h"
#include "chrome/test/base/testing_profile.h"
#include "components/download/public/common/mock_download_item.h"
#include "components/drive/chromeos/dummy_file_system.h"
#include "components/drive/file_system_core_util.h"
#include "content/public/test/mock_download_manager.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "content/public/test/test_utils.h"
#include "google_apis/drive/test_util.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace drive {
namespace {
// Test file system for verifying the behavior of DownloadHandler, by simulating
// various responses from FileSystem.
class DownloadHandlerTestFileSystem : public DummyFileSystem {
public:
DownloadHandlerTestFileSystem() : error_(FILE_ERROR_FAILED) {}
void set_error(FileError error) { error_ = error; }
// FileSystemInterface overrides.
void GetResourceEntry(const base::FilePath& file_path,
const GetResourceEntryCallback& callback) override {
callback.Run(error_, std::unique_ptr<ResourceEntry>(error_ == FILE_ERROR_OK
? new ResourceEntry
: NULL));
}
void CreateDirectory(const base::FilePath& directory_path,
bool is_exclusive,
bool is_recursive,
const FileOperationCallback& callback) override {
callback.Run(error_);
}
void FreeDiskSpaceIfNeededFor(
int64_t num_bytes,
const FreeDiskSpaceCallback& callback) override {
free_disk_space_if_needed_for_num_bytes_.push_back(num_bytes);
callback.Run(true);
}
std::vector<int64_t> free_disk_space_if_needed_for_num_bytes_;
private:
FileError error_;
};
class DownloadHandlerTestDownloadManager : public content::MockDownloadManager {
public:
void GetAllDownloads(
content::DownloadManager::DownloadVector* downloads) override {
for (auto* test_download : test_downloads_) {
downloads->push_back(test_download);
}
}
content::DownloadManager::DownloadVector test_downloads_;
};
class DownloadHandlerTestDownloadItem : public download::MockDownloadItem {
public:
bool IsDone() const override { return is_done_; }
int64_t GetTotalBytes() const override { return total_bytes_; }
int64_t GetReceivedBytes() const override { return received_bytes_; }
bool is_done_ = false;
int64_t total_bytes_ = 0;
int64_t received_bytes_ = 0;
};
} // namespace
class DownloadHandlerTest : public testing::Test {
public:
DownloadHandlerTest()
: download_manager_(new DownloadHandlerTestDownloadManager) {}
void SetUp() override {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
// Set expectations for download item.
EXPECT_CALL(download_item_, GetState())
.WillRepeatedly(testing::Return(download::DownloadItem::IN_PROGRESS));
download_handler_.reset(new DownloadHandler(&test_file_system_));
download_handler_->Initialize(download_manager_.get(), temp_dir_.GetPath());
download_handler_->SetFreeDiskSpaceDelayForTesting(
base::TimeDelta::FromMilliseconds(0));
}
protected:
base::ScopedTempDir temp_dir_;
content::TestBrowserThreadBundle thread_bundle_;
TestingProfile profile_;
std::unique_ptr<DownloadHandlerTestDownloadManager> download_manager_;
std::unique_ptr<DownloadHandlerTestDownloadManager>
incognito_download_manager_;
DownloadHandlerTestFileSystem test_file_system_;
std::unique_ptr<DownloadHandler> download_handler_;
download::MockDownloadItem download_item_;
};
TEST_F(DownloadHandlerTest, SubstituteDriveDownloadPathNonDrivePath) {
const base::FilePath non_drive_path(FILE_PATH_LITERAL("/foo/bar"));
ASSERT_FALSE(util::IsUnderDriveMountPoint(non_drive_path));
// Call SubstituteDriveDownloadPath()
base::FilePath substituted_path;
download_handler_->SubstituteDriveDownloadPath(
non_drive_path,
&download_item_,
google_apis::test_util::CreateCopyResultCallback(&substituted_path));
content::RunAllTasksUntilIdle();
// Check the result.
EXPECT_EQ(non_drive_path, substituted_path);
EXPECT_FALSE(download_handler_->IsDriveDownload(&download_item_));
}
TEST_F(DownloadHandlerTest, SubstituteDriveDownloadPath) {
const base::FilePath drive_path =
util::GetDriveMountPointPath(&profile_).AppendASCII("test.dat");
// Test the case that the download target directory already exists.
test_file_system_.set_error(FILE_ERROR_OK);
// Call SubstituteDriveDownloadPath()
base::FilePath substituted_path;
download_handler_->SubstituteDriveDownloadPath(
drive_path,
&download_item_,
google_apis::test_util::CreateCopyResultCallback(&substituted_path));
content::RunAllTasksUntilIdle();
// Check the result.
EXPECT_TRUE(temp_dir_.GetPath().IsParent(substituted_path));
ASSERT_TRUE(download_handler_->IsDriveDownload(&download_item_));
EXPECT_EQ(drive_path, download_handler_->GetTargetPath(&download_item_));
}
TEST_F(DownloadHandlerTest, SubstituteDriveDownloadPathGetEntryFailure) {
const base::FilePath drive_path =
util::GetDriveMountPointPath(&profile_).AppendASCII("test.dat");
// Test the case that access to the download target directory failed for some
// reason.
test_file_system_.set_error(FILE_ERROR_FAILED);
// Call SubstituteDriveDownloadPath()
base::FilePath substituted_path;
download_handler_->SubstituteDriveDownloadPath(
drive_path,
&download_item_,
google_apis::test_util::CreateCopyResultCallback(&substituted_path));
content::RunAllTasksUntilIdle();
// Check the result.
EXPECT_TRUE(substituted_path.empty());
}
// content::SavePackage calls SubstituteDriveDownloadPath before creating
// DownloadItem.
TEST_F(DownloadHandlerTest, SubstituteDriveDownloadPathForSavePackage) {
const base::FilePath drive_path =
util::GetDriveMountPointPath(&profile_).AppendASCII("test.dat");
test_file_system_.set_error(FILE_ERROR_OK);
// Call SubstituteDriveDownloadPath()
base::FilePath substituted_path;
download_handler_->SubstituteDriveDownloadPath(
drive_path,
NULL, // DownloadItem is not available at this moment.
google_apis::test_util::CreateCopyResultCallback(&substituted_path));
content::RunAllTasksUntilIdle();
// Check the result of SubstituteDriveDownloadPath().
EXPECT_TRUE(temp_dir_.GetPath().IsParent(substituted_path));
// |download_item_| is not a drive download yet.
EXPECT_FALSE(download_handler_->IsDriveDownload(&download_item_));
// Call SetDownloadParams().
download_handler_->SetDownloadParams(drive_path, &download_item_);
// |download_item_| is a drive download now.
ASSERT_TRUE(download_handler_->IsDriveDownload(&download_item_));
EXPECT_EQ(drive_path, download_handler_->GetTargetPath(&download_item_));
}
TEST_F(DownloadHandlerTest, CheckForFileExistence) {
const base::FilePath drive_path =
util::GetDriveMountPointPath(&profile_).AppendASCII("test.dat");
// Make |download_item_| a drive download.
download_handler_->SetDownloadParams(drive_path, &download_item_);
ASSERT_TRUE(download_handler_->IsDriveDownload(&download_item_));
EXPECT_EQ(drive_path, download_handler_->GetTargetPath(&download_item_));
// Test for the case when the path exists.
test_file_system_.set_error(FILE_ERROR_OK);
// Call CheckForFileExistence.
bool file_exists = false;
download_handler_->CheckForFileExistence(
&download_item_,
google_apis::test_util::CreateCopyResultCallback(&file_exists));
content::RunAllTasksUntilIdle();
// Check the result.
EXPECT_TRUE(file_exists);
// Test for the case when the path does not exist.
test_file_system_.set_error(FILE_ERROR_NOT_FOUND);
// Call CheckForFileExistence again.
download_handler_->CheckForFileExistence(
&download_item_,
google_apis::test_util::CreateCopyResultCallback(&file_exists));
content::RunAllTasksUntilIdle();
// Check the result.
EXPECT_FALSE(file_exists);
}
TEST_F(DownloadHandlerTest, FreeDiskSpace) {
// Add a download item to download manager.
DownloadHandlerTestDownloadItem download_item_a;
download_item_a.is_done_ = false;
download_item_a.total_bytes_ = 100;
download_item_a.received_bytes_ = 10;
download_manager_->test_downloads_.push_back(&download_item_a);
// Free disk space for download_item_a.
download_handler_->FreeDiskSpaceIfNeededImmediately();
ASSERT_EQ(1u,
test_file_system_.free_disk_space_if_needed_for_num_bytes_.size());
ASSERT_EQ(download_item_a.total_bytes_ - download_item_a.received_bytes_,
test_file_system_.free_disk_space_if_needed_for_num_bytes_[0]);
// Confirm that FreeDiskSpaceIfNeeded is rate limited by calling it twice.
download_handler_->FreeDiskSpaceIfNeeded();
download_handler_->FreeDiskSpaceIfNeeded();
ASSERT_EQ(1u,
test_file_system_.free_disk_space_if_needed_for_num_bytes_.size());
download_item_a.received_bytes_ = 20;
base::RunLoop().RunUntilIdle();
ASSERT_EQ(2u,
test_file_system_.free_disk_space_if_needed_for_num_bytes_.size());
ASSERT_EQ(download_item_a.total_bytes_ - download_item_a.received_bytes_,
test_file_system_.free_disk_space_if_needed_for_num_bytes_[1]);
// Observe incognito download manager and add another download item.
// FreeDiskSpace should be called with considering both download items.
incognito_download_manager_.reset(new DownloadHandlerTestDownloadManager);
download_handler_->ObserveIncognitoDownloadManager(
incognito_download_manager_.get());
DownloadHandlerTestDownloadItem download_item_b;
download_item_b.is_done_ = false;
download_item_b.total_bytes_ = 200;
download_item_b.received_bytes_ = 0;
incognito_download_manager_->test_downloads_.push_back(&download_item_b);
download_item_a.received_bytes_ = 30;
download_handler_->FreeDiskSpaceIfNeededImmediately();
ASSERT_EQ(3u,
test_file_system_.free_disk_space_if_needed_for_num_bytes_.size());
ASSERT_EQ(download_item_a.total_bytes_ - download_item_a.received_bytes_ +
download_item_b.total_bytes_ - download_item_b.received_bytes_,
test_file_system_.free_disk_space_if_needed_for_num_bytes_[2]);
// Free disk space after making both items completed. In this case
// FreeDiskSpace should be called with 0 byte to keep
// drive::internal::kMinFreeSpaceInBytes.
download_item_a.is_done_ = true;
download_item_b.is_done_ = true;
download_handler_->FreeDiskSpaceIfNeeded();
base::RunLoop().RunUntilIdle();
ASSERT_EQ(4u,
test_file_system_.free_disk_space_if_needed_for_num_bytes_.size());
ASSERT_EQ(0, test_file_system_.free_disk_space_if_needed_for_num_bytes_[3]);
}
TEST_F(DownloadHandlerTest, CalculateRequestSpace) {
DownloadHandlerTestDownloadItem download_item_a;
download_item_a.is_done_ = false;
download_item_a.total_bytes_ = 100;
download_item_a.received_bytes_ = 0;
DownloadHandlerTestDownloadItem download_item_b;
download_item_b.is_done_ = false;
download_item_b.total_bytes_ = 200;
download_item_b.received_bytes_ = 10;
content::DownloadManager::DownloadVector downloads;
downloads.push_back(&download_item_a);
downloads.push_back(&download_item_b);
ASSERT_EQ(download_item_a.total_bytes_ - download_item_a.received_bytes_ +
download_item_b.total_bytes_ - download_item_b.received_bytes_,
download_handler_->CalculateRequestSpace(downloads));
download_item_a.received_bytes_ = 10;
ASSERT_EQ(download_item_a.total_bytes_ - download_item_a.received_bytes_ +
download_item_b.total_bytes_ - download_item_b.received_bytes_,
download_handler_->CalculateRequestSpace(downloads));
download_item_b.is_done_ = true;
// Since download_item_b is completed, it shouldn't be counted.
ASSERT_EQ(download_item_a.total_bytes_ - download_item_a.received_bytes_,
download_handler_->CalculateRequestSpace(downloads));
// Add unknown size download item.
DownloadHandlerTestDownloadItem download_item_c;
download_item_c.is_done_ = false;
download_item_c.total_bytes_ = 0;
downloads.push_back(&download_item_c);
// Unknown size download should be counted as 0 byte.
ASSERT_EQ(download_item_a.total_bytes_ - download_item_a.received_bytes_,
download_handler_->CalculateRequestSpace(downloads));
// Add another unknown size download item.
DownloadHandlerTestDownloadItem download_item_d;
download_item_d.is_done_ = false;
download_item_d.total_bytes_ = 0;
downloads.push_back(&download_item_d);
// Unknown size downloads should be counted as 0 byte.
ASSERT_EQ(download_item_a.total_bytes_ - download_item_a.received_bytes_,
download_handler_->CalculateRequestSpace(downloads));
}
} // namespace drive
| 37.050279 | 80 | 0.77111 | [
"vector"
] |
a04b28c4116abac90e4e357290622feb84ed7e8b | 2,963 | cpp | C++ | Leetcode/Coding Interviews/37_Serialize_and_Deserialize_Binary_Tree.cpp | ZR-Huang/AlgorithmPractices | 226cecde136531341ce23cdf88529345be1912fc | [
"BSD-3-Clause"
] | 1 | 2019-11-26T11:52:25.000Z | 2019-11-26T11:52:25.000Z | Leetcode/Coding Interviews/37_Serialize_and_Deserialize_Binary_Tree.cpp | ZR-Huang/AlgorithmPractices | 226cecde136531341ce23cdf88529345be1912fc | [
"BSD-3-Clause"
] | null | null | null | Leetcode/Coding Interviews/37_Serialize_and_Deserialize_Binary_Tree.cpp | ZR-Huang/AlgorithmPractices | 226cecde136531341ce23cdf88529345be1912fc | [
"BSD-3-Clause"
] | null | null | null | /*
注意:本题与主站 297 题相同:https://leetcode-cn.com/problems/serialize-and-deserialize-binary-tree/
请实现两个函数,分别用来序列化和反序列化二叉树。
示例:
你可以将以下二叉树:
1
/ \
2 3
/ \
4 5
序列化为 "[1,2,3,null,null,4,5]"
*/
#include <iostream>
#include <string>
#include <queue>
#include <sstream>
#include <algorithm>
using namespace std;
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Codec {
public:
// Encodes a tree to a single string.
string serialize(TreeNode* root) {
if (root == NULL) return "";
queue<TreeNode*> q;
vector<string> ans;
q.push(root);
while(!q.empty()){
int length = q.size();
for (int i=0; i<length ; i++){
TreeNode* node = q.front();
q.pop();
if (node == NULL) ans.push_back("null");
else {
ans.push_back(to_string(node->val));
q.push(node->left);
q.push(node->right);
}
}
}
stringstream ss;
for(int i=0; i<ans.size(); i++)
{
if(i != 0) ss << ",";
ss << ans[i];
}
return ss.str();
}
// Decodes your encoded data to tree.
TreeNode* deserialize(string data) {
if(data.empty()) return NULL;
vector<string> values;
stringstream ss(data);
while(ss.good()){
string substr;
getline(ss, substr, ',');
values.push_back(substr);
}
reverse(values.begin(), values.end());
queue<TreeNode*> q;
TreeNode* root = new TreeNode(stoi(values.at(values.size()-1)));
values.pop_back();
q.push(root);
while(!q.empty()){
int length = q.size();
for(int i=0; i<length; i++){
TreeNode* node = q.front();
q.pop();
string left = values.at(values.size()-1);
values.pop_back();
string right = values.at(values.size()-1);
values.pop_back();
if (left != "null"){
node->left = new TreeNode(stoi(left));
q.push(node->left);
}
if (right != "null"){
node->right = new TreeNode(stoi(right));
q.push(node->right);
}
}
}
return root;
}
};
int main(){
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->right->left = new TreeNode(4);
root->right->right = new TreeNode(5);
Codec c;
c.deserialize(c.serialize(root));
return 0;
}
// Your Codec object will be instantiated and called as such:
// Codec codec;
// codec.deserialize(codec.serialize(root)); | 26.221239 | 88 | 0.488356 | [
"object",
"vector"
] |
a051e8f0060f96a951c6e8754f1609e9dd4a9a50 | 8,451 | cc | C++ | src/systemc/core/sc_process_handle.cc | hyu-iot/gem5 | aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5 | [
"BSD-3-Clause"
] | 765 | 2015-01-14T16:17:04.000Z | 2022-03-28T07:46:28.000Z | src/systemc/core/sc_process_handle.cc | hyu-iot/gem5 | aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5 | [
"BSD-3-Clause"
] | 148 | 2018-07-20T00:58:36.000Z | 2021-11-16T01:52:33.000Z | src/systemc/core/sc_process_handle.cc | hyu-iot/gem5 | aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5 | [
"BSD-3-Clause"
] | 807 | 2015-01-06T09:55:38.000Z | 2022-03-30T10:23:36.000Z | /*
* Copyright 2018 Google, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "systemc/core/process.hh"
#include "systemc/core/scheduler.hh"
#include "systemc/ext/core/messages.hh"
#include "systemc/ext/core/sc_main.hh"
#include "systemc/ext/core/sc_process_handle.hh"
#include "systemc/ext/utils/sc_report_handler.hh"
namespace sc_core
{
const char *
sc_unwind_exception::what() const throw()
{
return _isReset ? "RESET" : "KILL";
}
bool
sc_unwind_exception::is_reset() const
{
return _isReset;
}
sc_unwind_exception::sc_unwind_exception() : _isReset(false) {}
sc_unwind_exception::sc_unwind_exception(const sc_unwind_exception &e) :
_isReset(e._isReset)
{}
sc_unwind_exception::~sc_unwind_exception() throw() {}
void
sc_set_location(const char *file, int lineno)
{
sc_process_b *current = ::sc_gem5::scheduler.current();
if (!current)
return;
current->file = file;
current->lineno = lineno;
}
sc_process_b *
sc_get_curr_process_handle()
{
return ::sc_gem5::scheduler.current();
}
sc_process_handle::sc_process_handle() : _gem5_process(nullptr) {}
sc_process_handle::sc_process_handle(const sc_process_handle &handle) :
_gem5_process(handle._gem5_process)
{
if (_gem5_process)
_gem5_process->incref();
}
sc_process_handle::sc_process_handle(sc_object *obj) :
_gem5_process(dynamic_cast<::sc_gem5::Process *>(obj))
{
if (_gem5_process)
_gem5_process->incref();
}
sc_process_handle::~sc_process_handle()
{
if (_gem5_process)
_gem5_process->decref();
}
bool
sc_process_handle::valid() const
{
return _gem5_process != nullptr;
}
sc_process_handle &
sc_process_handle::operator = (const sc_process_handle &handle)
{
if (_gem5_process)
_gem5_process->decref();
_gem5_process = handle._gem5_process;
if (_gem5_process)
_gem5_process->incref();
return *this;
}
bool
sc_process_handle::operator == (const sc_process_handle &handle) const
{
return _gem5_process && handle._gem5_process &&
(_gem5_process == handle._gem5_process);
}
bool
sc_process_handle::operator != (const sc_process_handle &handle) const
{
return !(handle == *this);
}
bool
sc_process_handle::operator < (const sc_process_handle &other) const
{
return _gem5_process < other._gem5_process;
}
void
sc_process_handle::swap(sc_process_handle &handle)
{
::sc_gem5::Process *temp = handle._gem5_process;
handle._gem5_process = _gem5_process;
_gem5_process = temp;
}
const char *
sc_process_handle::name() const
{
return _gem5_process ? _gem5_process->name() : "";
}
sc_curr_proc_kind
sc_process_handle::proc_kind() const
{
return _gem5_process ? _gem5_process->procKind() : SC_NO_PROC_;
}
const std::vector<sc_object *> &
sc_process_handle::get_child_objects() const
{
static const std::vector<sc_object *> empty;
return _gem5_process ? _gem5_process->get_child_objects() : empty;
}
const std::vector<sc_event *> &
sc_process_handle::get_child_events() const
{
static const std::vector<sc_event *> empty;
return _gem5_process ? _gem5_process->get_child_events() : empty;
}
sc_object *
sc_process_handle::get_parent_object() const
{
return _gem5_process ? _gem5_process->get_parent_object() : nullptr;
}
sc_object *
sc_process_handle::get_process_object() const
{
return _gem5_process;
}
bool
sc_process_handle::dynamic() const
{
return _gem5_process ? _gem5_process->dynamic() : false;
}
bool
sc_process_handle::terminated() const
{
return _gem5_process ? _gem5_process->terminated() : false;
}
const sc_event &
sc_process_handle::terminated_event() const
{
if (!_gem5_process) {
SC_REPORT_WARNING(SC_ID_EMPTY_PROCESS_HANDLE_, "terminated_event()");
static sc_gem5::InternalScEvent non_event;
return non_event;
}
return _gem5_process->terminatedEvent();
}
void
sc_process_handle::suspend(sc_descendent_inclusion_info include_descendants)
{
if (!_gem5_process) {
SC_REPORT_WARNING(SC_ID_EMPTY_PROCESS_HANDLE_, "suspend()");
return;
}
_gem5_process->suspend(include_descendants == SC_INCLUDE_DESCENDANTS);
}
void
sc_process_handle::resume(sc_descendent_inclusion_info include_descendants)
{
if (!_gem5_process) {
SC_REPORT_WARNING(SC_ID_EMPTY_PROCESS_HANDLE_, "resume()");
return;
}
_gem5_process->resume(include_descendants == SC_INCLUDE_DESCENDANTS);
}
void
sc_process_handle::disable(sc_descendent_inclusion_info include_descendants)
{
if (!_gem5_process) {
SC_REPORT_WARNING(SC_ID_EMPTY_PROCESS_HANDLE_, "disable()");
return;
}
_gem5_process->disable(include_descendants == SC_INCLUDE_DESCENDANTS);
}
void
sc_process_handle::enable(sc_descendent_inclusion_info include_descendants)
{
if (!_gem5_process) {
SC_REPORT_WARNING(SC_ID_EMPTY_PROCESS_HANDLE_, "enable()");
return;
}
_gem5_process->enable(include_descendants == SC_INCLUDE_DESCENDANTS);
}
void
sc_process_handle::kill(sc_descendent_inclusion_info include_descendants)
{
if (!_gem5_process) {
SC_REPORT_WARNING(SC_ID_EMPTY_PROCESS_HANDLE_, "kill()");
return;
}
_gem5_process->kill(include_descendants == SC_INCLUDE_DESCENDANTS);
}
void
sc_process_handle::reset(sc_descendent_inclusion_info include_descendants)
{
if (!_gem5_process) {
SC_REPORT_WARNING(SC_ID_EMPTY_PROCESS_HANDLE_, "reset()");
return;
}
_gem5_process->reset(include_descendants == SC_INCLUDE_DESCENDANTS);
}
bool
sc_process_handle::is_unwinding()
{
if (!_gem5_process) {
SC_REPORT_WARNING(SC_ID_EMPTY_PROCESS_HANDLE_, "is_unwinding()");
return false;
}
return _gem5_process->isUnwinding();
}
const sc_event &
sc_process_handle::reset_event() const
{
if (!_gem5_process) {
SC_REPORT_WARNING(SC_ID_EMPTY_PROCESS_HANDLE_, "reset()");
static sc_gem5::InternalScEvent non_event;
return non_event;
}
return _gem5_process->resetEvent();
}
void
sc_process_handle::sync_reset_on(
sc_descendent_inclusion_info include_descendants)
{
if (!_gem5_process) {
SC_REPORT_WARNING(SC_ID_EMPTY_PROCESS_HANDLE_, "sync_reset_on()");
return;
}
_gem5_process->syncResetOn(include_descendants == SC_INCLUDE_DESCENDANTS);
}
void
sc_process_handle::sync_reset_off(
sc_descendent_inclusion_info include_descendants)
{
if (!_gem5_process) {
SC_REPORT_WARNING(SC_ID_EMPTY_PROCESS_HANDLE_, "sync_reset_off()");
return;
}
_gem5_process->syncResetOff(include_descendants == SC_INCLUDE_DESCENDANTS);
}
sc_process_handle
sc_get_current_process_handle()
{
if (sc_is_running())
return sc_process_handle(::sc_gem5::scheduler.current());
else
return sc_process_handle(::sc_gem5::Process::newest());
}
bool
sc_is_unwinding()
{
return sc_get_current_process_handle().is_unwinding();
}
bool sc_allow_process_control_corners;
} // namespace sc_core
| 25.68693 | 79 | 0.738137 | [
"vector"
] |
a052605d5f6034de80b4e6890c5eddf14f35d087 | 929 | cpp | C++ | red-microdnf/red-lib/redtransaction.cpp | redpesk-labs/red-pak | bd11881f50ae627a0641448ae0b307a9a9e2877e | [
"Apache-2.0"
] | 5 | 2021-02-24T09:00:36.000Z | 2022-02-10T16:37:10.000Z | red-microdnf/red-lib/redtransaction.cpp | redpesk-labs/red-pak | bd11881f50ae627a0641448ae0b307a9a9e2877e | [
"Apache-2.0"
] | null | null | null | red-microdnf/red-lib/redtransaction.cpp | redpesk-labs/red-pak | bd11881f50ae627a0641448ae0b307a9a9e2877e | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2021 IoT.bzh
author: Clément Bénier <clement.benier@iot.bzh>
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 "redtransaction.hpp"
namespace redlib {
std::vector<libdnf::base::TransactionPackage> & RedTransaction::get_transaction_packages() {
if (transaction_packages.empty())
transaction_packages = libdnf::base::Transaction::get_transaction_packages();
return transaction_packages;
}
} //namespace redlib
| 30.966667 | 92 | 0.775027 | [
"vector"
] |
a0537ce07d9c5ef93abee4ae9ac90980d8b5c3ab | 524 | hpp | C++ | archive/native/src/knapsack.hpp | bbboll/knapsack | 9d3ad8884133a0f62eb6144b2bb705c9c2b7fa2e | [
"MIT"
] | null | null | null | archive/native/src/knapsack.hpp | bbboll/knapsack | 9d3ad8884133a0f62eb6144b2bb705c9c2b7fa2e | [
"MIT"
] | null | null | null | archive/native/src/knapsack.hpp | bbboll/knapsack | 9d3ad8884133a0f62eb6144b2bb705c9c2b7fa2e | [
"MIT"
] | null | null | null | #ifndef KNAPSACK_H
#define KNAPSACK_H
#include <vector>
// struct to hold item data
struct Item {
int weight;
int value;
};
// this data type is used when passing the solution
// of a knapsack problem to python
typedef std::vector<Item> ItemList;
// class to hold knapsack problem data and expose solver
class Knapsack
{
private:
std::vector<Item> items;
int **cache;
int capacity;
int findBest(int i, int j);
public:
void addItem(int weight, int value);
void setCapacity(int cap);
ItemList solve();
};
#endif | 16.903226 | 56 | 0.725191 | [
"vector"
] |
a05443e36dcb087e5c9b87a7378caab77ac35a84 | 3,745 | cc | C++ | third_party/blink/renderer/modules/installedapp/navigator_installed_app.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/blink/renderer/modules/installedapp/navigator_installed_app.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | third_party/blink/renderer/modules/installedapp/navigator_installed_app.cc | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 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.
#include "third_party/blink/renderer/modules/installedapp/navigator_installed_app.h"
#include <memory>
#include "third_party/blink/renderer/bindings/core/v8/callback_promise_adapter.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_related_application.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/frame/navigator.h"
#include "third_party/blink/renderer/modules/installedapp/installed_app_controller.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
namespace blink {
NavigatorInstalledApp::NavigatorInstalledApp(Navigator& navigator)
: Supplement<Navigator>(navigator) {}
NavigatorInstalledApp* NavigatorInstalledApp::From(Document& document) {
if (!document.GetFrame() || !document.GetFrame()->DomWindow())
return nullptr;
Navigator& navigator = *document.GetFrame()->DomWindow()->navigator();
return &From(navigator);
}
NavigatorInstalledApp& NavigatorInstalledApp::From(Navigator& navigator) {
NavigatorInstalledApp* supplement =
Supplement<Navigator>::From<NavigatorInstalledApp>(navigator);
if (!supplement) {
supplement = MakeGarbageCollected<NavigatorInstalledApp>(navigator);
ProvideTo(navigator, supplement);
}
return *supplement;
}
ScriptPromise NavigatorInstalledApp::getInstalledRelatedApps(
ScriptState* script_state,
Navigator& navigator) {
// [SecureContext] from the IDL ensures this.
DCHECK(ExecutionContext::From(script_state)->IsSecureContext());
return NavigatorInstalledApp::From(navigator).getInstalledRelatedApps(
script_state);
}
ScriptPromise NavigatorInstalledApp::getInstalledRelatedApps(
ScriptState* script_state) {
auto* resolver = MakeGarbageCollected<ScriptPromiseResolver>(script_state);
ScriptPromise promise = resolver->Promise();
InstalledAppController* app_controller = Controller();
if (!app_controller) { // If the associated frame is detached
auto* exception = MakeGarbageCollected<DOMException>(
DOMExceptionCode::kInvalidStateError,
"The object is no longer associated to a document.");
resolver->Reject(exception);
return promise;
}
if (!app_controller->GetSupplementable()->IsMainFrame()) {
auto* exception = MakeGarbageCollected<DOMException>(
DOMExceptionCode::kInvalidStateError,
"getInstalledRelatedApps() is only supported in "
"top-level browsing contexts.");
resolver->Reject(exception);
return promise;
}
app_controller->GetInstalledRelatedApps(
std::make_unique<
CallbackPromiseAdapter<HeapVector<Member<RelatedApplication>>, void>>(
resolver));
return promise;
}
InstalledAppController* NavigatorInstalledApp::Controller() {
if (!GetSupplementable()->GetFrame())
return nullptr;
return InstalledAppController::From(*GetSupplementable()->GetFrame());
}
const char NavigatorInstalledApp::kSupplementName[] = "NavigatorInstalledApp";
void NavigatorInstalledApp::Trace(Visitor* visitor) {
Supplement<Navigator>::Trace(visitor);
}
} // namespace blink
| 38.214286 | 85 | 0.773031 | [
"object"
] |
a055ea38dff3791b7512d17fda1c5318487dff35 | 10,523 | cpp | C++ | APEX_1.4/samples_v2/SampleBase/ApexRenderMaterial.cpp | gongyiling/PhysX-3.4 | 99bc1c62880cf626f9926781e76a528b5276c68b | [
"Unlicense"
] | 1,863 | 2018-12-03T13:06:03.000Z | 2022-03-29T07:12:37.000Z | APEX_1.4/samples_v2/SampleBase/ApexRenderMaterial.cpp | cctxx/PhysX-3.4-1 | 5e42a5f112351a223c19c17bb331e6c55037b8eb | [
"Unlicense"
] | 71 | 2018-12-03T19:48:39.000Z | 2022-01-11T09:30:52.000Z | APEX_1.4/samples_v2/SampleBase/ApexRenderMaterial.cpp | cctxx/PhysX-3.4-1 | 5e42a5f112351a223c19c17bb331e6c55037b8eb | [
"Unlicense"
] | 265 | 2018-12-03T14:30:03.000Z | 2022-03-25T20:57:01.000Z | //
// 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 NVIDIA CORPORATION 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 ``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.
//
// Copyright (c) 2018 NVIDIA Corporation. All rights reserved.
#include "ApexRenderMaterial.h"
#include <DirectXMath.h>
#include "ApexResourceCallback.h"
#include "Utils.h"
#include "PsFastXml.h"
#include "PsFileBuffer.h"
#include "PxInputDataFromPxFileBuf.h"
#include "nvparameterized/NvParamUtils.h"
const char* DEFAULT_SPRITE_PARTICLE_SHADER = "pointsprite.hlsl";
const char* DEFAULT_MESH_PARTICLE_SHADER = "pointsprite.hlsl";
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Material .xml files parser
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
class MaterialXmlParser : public nvidia::shdfnd::FastXml::Callback
{
public:
MaterialXmlParser() :
blendMode(ApexRenderMaterial::BLEND_NONE)
{
}
virtual ~MaterialXmlParser()
{
}
string textureFile;
vector<string> shaderFiles;
ApexRenderMaterial::BlendMode blendMode;
protected:
// encountered a comment in the XML
virtual bool processComment(const char* /*comment*/)
{
return true;
}
virtual bool processClose(const char* /*element*/, unsigned int /*depth*/, bool& /*isError*/)
{
return true;
}
// return true to continue processing the XML document, false to skip.
virtual bool processElement(const char* elementName, // name of the element
const char* elementData, // element data, null if none
const nvidia::shdfnd::FastXml::AttributePairs& attr,
int /*lineno*/) // line number in the source XML file
{
PX_UNUSED(attr);
if (::strcmp(elementName, "texture") == 0)
{
textureFile = elementData;
}
else if (::strcmp(elementName, "shader") == 0)
{
shaderFiles.push_back(elementData);
}
else if (::strcmp(elementName, "blending") == 0)
{
blendMode = (::stricmp(elementData, "additive") == 0) ? ApexRenderMaterial::BLEND_ADDITIVE :
ApexRenderMaterial::BLEND_ALPHA_BLENDING;
}
return true;
}
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// ApexRenderMaterial
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
ApexRenderMaterial::ApexRenderMaterial(ApexResourceCallback* resourceProvider, const char* xmlFilePath)
{
PsFileBuffer theBuffer(xmlFilePath, nvidia::general_PxIOStream2::PxFileBuf::OPEN_READ_ONLY);
PxInputDataFromPxFileBuf id(theBuffer);
MaterialXmlParser parser;
nvidia::shdfnd::FastXml* xml = nvidia::shdfnd::createFastXml(&parser);
xml->processXml(id, false);
this->initialize(resourceProvider, parser.shaderFiles, parser.textureFile.c_str(), parser.blendMode);
xml->release();
}
ApexRenderMaterial::ApexRenderMaterial(ApexResourceCallback* resourceCallback, const NvParameterized::Interface *graphicMaterialData)
{
const char* textureFileName = NULL;
NvParameterized::getParamString(*graphicMaterialData, "DiffuseTexture", textureFileName);
BlendMode blendMode = BLEND_NONE;
const char *technique = "SPRITE_ONE";
NvParameterized::getParamEnum(*graphicMaterialData, "RenderTechnique", technique);
if (technique)
{
if (::strcmp(technique, "SPRITE_ONE") == 0)
{
blendMode = BLEND_ADDITIVE;
}
else if (::strcmp(technique, "SPRITE_ALPHA") == 0)
{
blendMode = BLEND_ALPHA_BLENDING;
}
}
this->initialize(resourceCallback, blendMode == BLEND_NONE ? DEFAULT_MESH_PARTICLE_SHADER : DEFAULT_SPRITE_PARTICLE_SHADER, textureFileName, blendMode);
}
ApexRenderMaterial::ApexRenderMaterial(ApexResourceCallback* resourceCallback, const char* shaderFileName,
const char* textureFileName, BlendMode blendMode)
{
this->initialize(resourceCallback, shaderFileName, textureFileName, blendMode);
}
void ApexRenderMaterial::initialize(ApexResourceCallback* resourceCallback, const char* shaderFileName, const char* textureFileName, BlendMode blendMode)
{
vector<string> v;
v.push_back(shaderFileName);
initialize(resourceCallback, v, textureFileName, blendMode);
}
void ApexRenderMaterial::initialize(ApexResourceCallback* resourceCallback, vector<string> shaderFileNames, const char* textureFileName, BlendMode blendMode)
{
mTextureSRV = nullptr;
mTexture = nullptr;
mBlendState = nullptr;
mTextureFileName = textureFileName;
for (uint32_t i = 0; i < shaderFileNames.size(); i++)
{
string shaderFilePath = ((char*)resourceCallback->requestResourceCustom(ApexResourceCallback::eSHADER_FILE_PATH, shaderFileNames[i].c_str()));
mShaderFilePathes.push_back(shaderFilePath);
}
mShaderGroups.reserve(mShaderFilePathes.size());
if (!mTextureFileName.empty())
{
mTexture =
(TextureResource*)resourceCallback->requestResourceCustom(ApexResourceCallback::eTEXTURE_RESOURCE, mTextureFileName.c_str());
}
setBlending(blendMode);
reload();
}
void ApexRenderMaterial::releaseReloadableResources()
{
for (vector<ShaderGroup*>::iterator it = mShaderGroups.begin(); it != mShaderGroups.end(); it++)
{
delete *it;
}
mShaderGroups.clear();
SAFE_RELEASE(mTextureSRV);
}
ApexRenderMaterial::~ApexRenderMaterial()
{
releaseReloadableResources();
SAFE_RELEASE(mBlendState);
for (list<Instance*>::iterator it = mInstances.begin(); it != mInstances.end(); it++)
{
delete *it;
}
mInstances.clear();
}
void ApexRenderMaterial::setBlending(BlendMode blendMode)
{
SAFE_RELEASE(mBlendState);
D3D11_BLEND_DESC desc;
ZeroMemory(&desc, sizeof(desc));
switch (blendMode)
{
case BLEND_NONE:
desc.RenderTarget[0].BlendEnable = FALSE;
desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
break;
case BLEND_ALPHA_BLENDING:
desc.AlphaToCoverageEnable = FALSE;
desc.IndependentBlendEnable = TRUE;
desc.RenderTarget[0].BlendEnable = TRUE;
desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;
desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA;
desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
break;
case BLEND_ADDITIVE: // actually, is's additive by alpha
desc.AlphaToCoverageEnable = FALSE;
desc.IndependentBlendEnable = TRUE;
desc.RenderTarget[0].BlendEnable = TRUE;
desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
desc.RenderTarget[0].DestBlend = D3D11_BLEND_ONE;
desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ONE;
desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_SRC_ALPHA;
desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
break;
default:
PX_ALWAYS_ASSERT_MESSAGE("Unknown blend mode");
}
ID3D11Device* device = GetDeviceManager()->GetDevice();
V(device->CreateBlendState(&desc, &mBlendState));
}
void ApexRenderMaterial::reload()
{
releaseReloadableResources();
// load shaders
ID3D11Device* device = GetDeviceManager()->GetDevice();
for (vector<string>::iterator it = mShaderFilePathes.begin(); it != mShaderFilePathes.end(); it++)
{
const char* shaderFilePath = (*it).c_str();
ShaderGroup* shaderGroup = new ShaderGroup();
V(createShaderFromFile(device, shaderFilePath, "VS", &(shaderGroup->vs), shaderGroup->buffer));
V(createShaderFromFile(device, shaderFilePath, "PS", &shaderGroup->ps));
createShaderFromFile(device, shaderFilePath, "GS", &shaderGroup->gs);
mShaderGroups.push_back(shaderGroup);
}
// load texture
if (mTexture)
{
V(DirectX::CreateShaderResourceView(device, mTexture->image.GetImages(), mTexture->image.GetImageCount(),
mTexture->metaData, &mTextureSRV));
}
}
ApexRenderMaterial::Instance* ApexRenderMaterial::getMaterialInstance(const D3D11_INPUT_ELEMENT_DESC* elementDescs, uint32_t numElements)
{
ID3D11InputLayout* inputLayout = NULL;
ID3D11Device* device = GetDeviceManager()->GetDevice();
for (uint32_t i = 0; i < mShaderGroups.size(); i++)
{
if (mShaderGroups[i]->buffer == NULL)
continue;
device->CreateInputLayout(elementDescs, numElements, mShaderGroups[i]->buffer->GetBufferPointer(), mShaderGroups[i]->buffer->GetBufferSize(), &inputLayout);
if (inputLayout)
{
Instance* materialInstance = new Instance(*this, inputLayout, i);
mInstances.push_back(materialInstance);
return materialInstance;
}
}
PX_ALWAYS_ASSERT();
return NULL;
}
void ApexRenderMaterial::Instance::bind(ID3D11DeviceContext& context, uint32_t slot)
{
mMaterial.mShaderGroups[mShaderNum]->Set(&context);
context.OMSetBlendState(mMaterial.mBlendState, nullptr, 0xFFFFFFFF);
context.PSSetShaderResources(slot, 1, &(mMaterial.mTextureSRV));
context.IASetInputLayout(mInputLayout);
}
bool ApexRenderMaterial::Instance::isValid()
{
return mMaterial.mShaderGroups.size() > 0 && mMaterial.mShaderGroups[mShaderNum]->IsValid();
}
| 34.276873 | 158 | 0.726029 | [
"vector"
] |
a056e00f912f8ea9351cbe1ab2a68b05c351be51 | 25,197 | hpp | C++ | include/crab/domains/variable_domain.hpp | LinerSu/crab | 8f3516f4b4765f4a093bb3c3a94ac2daa174130c | [
"Apache-2.0"
] | null | null | null | include/crab/domains/variable_domain.hpp | LinerSu/crab | 8f3516f4b4765f4a093bb3c3a94ac2daa174130c | [
"Apache-2.0"
] | null | null | null | include/crab/domains/variable_domain.hpp | LinerSu/crab | 8f3516f4b4765f4a093bb3c3a94ac2daa174130c | [
"Apache-2.0"
] | null | null | null | #pragma once
/* Classical variable propagation domain */
#include <crab/domains/abstract_domain.hpp>
#include <crab/domains/backward_assign_operations.hpp>
#include <crab/domains/interval.hpp>
#include <crab/domains/separate_domains.hpp>
#include <crab/support/stats.hpp>
#include <boost/optional.hpp>
namespace crab {
namespace domains {
/**
* Each variable is mapped to an element in this lattice:
*
* top
* |
* ...,Var_1,Var_2,...,Var_{n-1},Var_n,...
* |
* bottom
*
* top means that it might not be a variable
**/
template <typename VariableName> class variable_domain {
boost::optional<VariableName> m_variable;
bool m_is_bottom;
using variable_t = variable_domain<VariableName>;
variable_domain(bool is_bottom)
: m_variable(boost::none), m_is_bottom(is_bottom) {}
public:
variable_domain(VariableName c) : m_variable(c), m_is_bottom(false) {}
static variable_t bottom() { return variable_domain(true); }
static variable_t top() { return variable_domain(false); }
// static variable_t singleton() { return variable_domain(VariableName(0)); }
bool is_bottom() const { return m_is_bottom; }
bool is_top() const { return (!is_bottom() && !m_variable); }
bool is_variable() const { return m_variable != boost::none; }
VariableName get_variable() const {
assert(is_variable());
return *m_variable;
}
/** Begin Lattice Operations **/
/**
Indicates either this <= v property based on lattice.
@param v a variable object has the same type as current.
@return true if <= holds; else false.
*/
bool operator<=(const variable_t &v) const {
if (is_bottom() || v.is_top()) {
return true;
} else if (v.is_bottom() || is_top()) {
return false;
} else {
assert(is_variable());
assert(v.is_variable());
return get_variable() == v.get_variable();
}
}
/**
Indicates either this == v property based on lattice.
Note top == top?
@param v a variable object has the same type as current.
@return true if == holds; else false.
*/
bool operator==(const variable_t &v) const {
return (m_is_bottom == v.m_is_bottom && m_variable == v.m_variable);
}
/**
Indicates either this | v property based on lattice.
bot | v = v; this | bot = this
if this == v then this | v = this
otherwise return top
@param v a variable object has the same type as current.
@return what we described above.
*/
variable_t operator|(const variable_t &v) const {
if (is_bottom() || v.is_top())
return v;
else if (is_top() || v.is_bottom())
return *this;
else {
assert(is_variable());
assert(v.is_variable());
if (get_variable() == v.get_variable()) {
return *this;
} else {
return variable_t::top();
}
}
}
variable_t operator||(const variable_t &v) const { return *this | v; }
template <typename Thresholds>
variable_t widening_thresholds(const variable_t &v,
const Thresholds &ts /*unused*/) const {
return *this | v;
// Q: how we handle widening with threshold
}
/**
Indicates either this & v property based on lattice.
this & top = this; top & v = v
if this == v then this & v = this
otherwise return bot
@param v a variable object has the same type as current.
@return what we described above.
*/
variable_t operator&(const variable_t &v) const {
if (is_bottom() || v.is_top())
return *this;
else if (is_top() || v.is_bottom()) {
return v;
} else {
assert(is_variable());
assert(v.is_variable());
if (get_variable() == v.get_variable()) {
return *this;
} else {
return variable_t::bottom();
}
}
}
variable_t operator&&(const variable_t &v) const { return *this & v; }
/** End Lattice Operations **/
/** Begin arithmetic operations **/
// The following operations -- op
// Var_i op Var_j = top
variable_t Add(const variable_t &v) const {
if (is_bottom() || v.is_bottom()) {
return variable_t::bottom();
} else {
return variable_t::top();
}
}
variable_t Sub(const variable_t &v) const {
if (is_bottom() || v.is_bottom()) {
return variable_t::bottom();
} else {
return variable_t::top();
}
}
variable_t Mul(const variable_t &v) const {
if (is_bottom() || v.is_bottom()) {
return variable_t::bottom();
} else {
return variable_t::top();
}
}
variable_t SDiv(const variable_t &v) const {
if (is_bottom() || v.is_bottom()) {
return variable_t::bottom();
} else {
return variable_t::top();
}
}
variable_t SRem(const variable_t &v) const {
if (is_bottom() || v.is_bottom()) {
return variable_t::bottom();
} else {
return variable_t::top();
}
}
variable_t UDiv(const variable_t &v) const {
if (is_bottom() || v.is_bottom()) {
return variable_t::bottom();
} else {
return variable_t::top();
}
}
variable_t URem(const variable_t &v) const {
if (is_bottom() || v.is_bottom()) {
return variable_t::bottom();
} else {
return variable_t::top();
}
}
variable_t Arith(crab::domains::arith_operation_t op,
const variable_t &v) const {
if (is_bottom() || v.is_bottom()) {
return variable_t::bottom();
} else {
return variable_t::top();
}
}
/** End arithmetic operations **/
/** Begin bitwise operations **/
// These operations depend on the type of Number
variable_t BitwiseAnd(const variable_t &v) const {
if (is_bottom() || v.is_bottom()) {
return variable_t::bottom();
} else {
return variable_t::top();
}
}
variable_t BitwiseOr(const variable_t &v) const {
if (is_bottom() || v.is_bottom()) {
return variable_t::bottom();
} else {
return variable_t::top();
}
}
variable_t BitwiseXor(const variable_t &v) const {
if (is_bottom() || v.is_bottom()) {
return variable_t::bottom();
} else {
return variable_t::top();
}
}
variable_t BitwiseShl(const variable_t &v) const {
if (is_bottom() || v.is_bottom()) {
return variable_t::bottom();
} else {
return variable_t::top();
}
}
variable_t BitwiseLShr(const variable_t &v) const {
if (is_bottom() || v.is_bottom()) {
return variable_t::bottom();
} else {
return variable_t::top();
}
}
variable_t BitwiseAShr(const variable_t &v) const {
if (is_bottom() || v.is_bottom()) {
return variable_t::bottom();
} else {
return variable_t::top();
}
}
variable_t BitwiseOp(const variable_t &v) const {
if (is_bottom() || v.is_bottom()) {
return variable_t::bottom();
} else {
return variable_t::top();
}
}
/** End bitwise operations **/
void write(crab::crab_os &o) const {
if (is_bottom()) {
o << "_|_";
} else if (is_top()) {
o << "top";
} else {
assert(is_variable());
o << get_variable();
}
}
// void rename(const variable_vector_t &from,
// const variable_vector_t &to) {
// if (!is_variable()) {
// return;
// }
// for (int i = 0; i < from.size(); ++i) {
// auto tmp = from[i].name();
// if (tmp == m_variable) {
// m_variable = to[i].name();
// break;
// }
// }
// }
// void forget(const variable_vector_t &variables) {
// if (is_bottom() || is_top()) {
// return;
// }
// for (auto const &var : variables) {
// auto tmp = from[i].name();
// if (m_variable == tmp) {
// m_variable = boost::none;
// m_is_bottom = true;
// break;
// }
// }
// }
friend inline crab_os &operator<<(crab_os &o, const variable_t &v) {
v.write(o);
return o;
}
};
// template <typename VariableName>
// class variable_domain final
// : public
// crab::domains::abstract_domain_api<variable_domain<VariableName>> {
// public:
// using variable_domain_t = variable_domain<VariableName>;
// using abstract_domain_t =
// crab::domains::abstract_domain_api<variable_domain_t>;
// using typename abstract_domain_t::disjunctive_linear_constraint_system_t;
// using typename abstract_domain_t::interval_t;
// using typename abstract_domain_t::linear_constraint_system_t;
// using typename abstract_domain_t::linear_constraint_t;
// using typename abstract_domain_t::linear_expression_t;
// using typename abstract_domain_t::reference_constraint_t;
// using typename abstract_domain_t::variable_or_constant_t;
// using typename abstract_domain_t::variable_or_constant_vector_t;
// using typename abstract_domain_t::variable_t;
// using typename abstract_domain_t::variable_vector_t;
// using variable_value_t = variable<VariableName>;
// using varname_t = VariableName;
// private:
// using separate_domain_t = ikos::separate_domain<variable_t,
// variable_value_t>;
// private:
// separate_domain_t m_env;
// variable_domain(separate_domain_t &&env) : m_env(std::move(env)) {}
// variable_value_t eval(const linear_expression_t &expr) const {
// assert(!is_bottom());
// variable_value_t r(expr.constant());
// for (auto const &kv : expr) {
// variable_value_t c(kv.first);
// r = r.Add(c.Mul(m_env[kv.second]));
// if (r.is_top()) {
// break;
// }
// }
// return r;
// }
// constant_t compute_residual(const linear_constraint_t &cst,
// const variable_value_t &pivot) const {
// constant_t residual(cst.constant());
// for (auto const &kv : cst) {
// constant_t c(kv.first);
// const variable_value_t &v = kv.second;
// if (!(v == pivot)) {
// residual = residual.Sub(c.Mul(m_env[v]));
// if (residual.is_top()) {
// break;
// }
// }
// }
// return residual;
// }
// void propagate(const linear_constraint_t &cst) {
// if (is_bottom()) {
// return;
// }
// if (cst.is_inequality() || cst.is_strict_inequality() ||
// cst.is_disequation()) {
// constant_t e = eval(cst.expression());
// if (e.is_constant()) {
// if (cst.is_inequality()) {
// if (!(e.get_constant() <= number_t(0))) {
// set_to_bottom();
// return;
// }
// } else if (cst.is_disequation()) {
// if (!(e.get_constant() != number_t(0))) {
// set_to_bottom();
// return;
// }
// } else if (cst.is_strict_inequality()) {
// if (!(e.get_constant() < number_t(0))) {
// set_to_bottom();
// return;
// }
// }
// }
// } else if (cst.is_equality()) {
// for (auto kv : cst) {
// number_t c = kv.first;
// const variable_t &pivot = kv.second;
// constant_t new_c = compute_residual(cst, pivot).SDiv(c);
// if (!new_c.is_top()) {
// m_env.set(pivot, m_env[pivot] & new_c);
// }
// }
// }
// }
// void solve_constraints(const linear_constraint_system_t &csts) {
// for (auto const &c : csts) {
// if (is_bottom()) {
// return;
// }
// if (c.is_inequality() && c.is_unsigned()) {
// // we don't handle unsigned constraints
// continue;
// }
// if (c.is_tautology()) {
// continue;
// }
// if (c.is_contradiction()) {
// set_to_bottom();
// return;
// }
// propagate(c);
// }
// }
// public:
// variable_domain_t make_top() const override {
// return variable_domain_t(separate_domain_t::top());
// }
// variable_domain_t make_bottom() const override {
// return variable_domain_t(separate_domain_t::bottom());
// }
// void set_to_top() override {
// variable_domain abs(separate_domain_t::top());
// std::swap(*this, abs);
// }
// void set_to_bottom() override {
// variable_domain abs(separate_domain_t::bottom());
// std::swap(*this, abs);
// }
// variable_domain() : m_env(separate_domain_t::top()) {}
// variable_domain(const variable_domain_t &e) : m_env(e.m_env) {
// crab::CrabStats::count(domain_name() + ".count.copy");
// crab::ScopedCrabStats __st__(domain_name() + ".copy");
// }
// variable_domain(variable_domain_t &&e) : m_env(std::move(e.m_env)) {}
// variable_domain_t &operator=(const variable_domain_t &v) {
// crab::CrabStats::count(domain_name() + ".count.copy");
// crab::ScopedCrabStats __st__(domain_name() + ".copy");
// if (this != &v) {
// m_env = v.m_env;
// }
// return *this;
// }
// variable_domain_t &operator=(variable_domain_t &&v) {
// if (this != &v) {
// m_env = std::move(v.m_env);
// }
// return *this;
// }
// variable_value_t get_variable_value(const variable_t &v) const {
// return m_env[v];
// }
// void set_variable_value(const variable_t &v, variable_value_t v_val) {
// m_env.set(v, v_val);
// }
// bool is_bottom() const override { return m_env.is_bottom(); }
// bool is_top() const override { return m_env.is_top(); }
// bool operator<=(const variable_domain_t &v) const override {
// crab::CrabStats::count(domain_name() + ".count.leq");
// crab::ScopedCrabStats __st__(domain_name() + ".leq");
// return (m_env <= v.m_env);
// }
// void operator|=(const variable_domain_t &v) override {
// crab::CrabStats::count(domain_name() + ".count.join");
// crab::ScopedCrabStats __st__(domain_name() + ".join");
// CRAB_LOG("constant-domain",
// crab::outs() << "Join " << m_env << " and " << v.m_env <<
// "\n";);
// m_env = m_env | v.m_env;
// CRAB_LOG("constant-domain", crab::outs() << "Res=" << m_env << "\n";);
// }
// variable_domain_t operator|(const variable_domain_t &v) const override {
// crab::CrabStats::count(domain_name() + ".count.join");
// crab::ScopedCrabStats __st__(domain_name() + ".join");
// return (m_env | v.m_env);
// }
// variable_domain_t operator&(const variable_domain_t &v) const override {
// crab::CrabStats::count(domain_name() + ".count.meet");
// crab::ScopedCrabStats __st__(domain_name() + ".meet");
// return (m_env & v.m_env);
// }
// variable_domain_t operator||(const variable_domain_t &v) const override {
// crab::CrabStats::count(domain_name() + ".count.widening");
// crab::ScopedCrabStats __st__(domain_name() + ".widening");
// return (m_env || v.m_env);
// }
// variable_domain_t widening_thresholds(
// const variable_domain_t &v,
// const crab::iterators::thresholds<number_t> &ts) const override {
// crab::CrabStats::count(domain_name() + ".count.widening");
// crab::ScopedCrabStats __st__(domain_name() + ".widening");
// return m_env.widening_thresholds(v.m_env, ts);
// }
// variable_domain_t operator&&(const variable_domain_t &v) const override {
// crab::CrabStats::count(domain_name() + ".count.narrowing");
// crab::ScopedCrabStats __st__(domain_name() + ".narrowing");
// return (m_env && v.m_env);
// }
// void operator-=(const variable_t &v) override {
// crab::CrabStats::count(domain_name() + ".count.forget");
// crab::ScopedCrabStats __st__(domain_name() + ".forget");
// m_env -= v;
// }
// interval_t operator[](const variable_t &v) override {
// variable_value_t val = m_env[v];
// if (val.is_bottom()) {
// return interval_t::bottom();
// } else if (val.is_top()) {
// return interval_t::top();
// } else {
// assert(val.is_variable());
// return interval_t(val.get_variable());
// }
// }
// // // TODO: update this
// // void operator+=(const linear_constraint_system_t &csts) override {
// // crab::CrabStats::count(domain_name() + ".count.add_constraints");
// // crab::ScopedCrabStats __st__(domain_name() + ".add_constraints");
// // solve_constraints(csts);
// // }
// // // TODO: update this
// // void assign(const variable_t &x, const linear_expression_t &e) override
// {
// // crab::CrabStats::count(domain_name() + ".count.assign");
// // crab::ScopedCrabStats __st__(domain_name() + ".assign");
// // if (boost::optional<variable_t> v = e.get_variable()) {
// // m_env.set(x, m_env[(*v)]);
// // } else {
// // m_env.set(x, eval(e));
// // }
// // }
// // void apply(crab::domains::arith_operation_t op, const variable_t &x,
// // const variable_t &y, const variable_t &z) override {
// // crab::CrabStats::count(domain_name() + ".count.apply");
// // crab::ScopedCrabStats __st__(domain_name() + ".apply");
// // if (!is_bottom()) {
// // variable_value_t yc = m_env[y];
// // variable_value_t zc = m_env[z];
// // variable_value_t xc = variable_value_t::top();
// // xc = yc.Arith(op, zc);
// // m_env.set(x, xc);
// // }
// // }
// // void apply(crab::domains::arith_operation_t op, const variable_t &x,
// // const variable_t &y, number_t k) override {
// // crab::CrabStats::count(domain_name() + ".count.apply");
// // crab::ScopedCrabStats __st__(domain_name() + ".apply");
// // // Var_i op num(k) should not be applied
// // CRAB_ERROR("Operation ", op, " not supported for variable domain");
// // if (!is_bottom()) {
// // variable_value_t xc = variable_value_t::top();
// // m_env.set(x, xc);
// // }
// // }
// // intrinsics operations
// void intrinsic(std::string name, const variable_or_constant_vector_t
// &inputs,
// const variable_vector_t &outputs) override {
// CRAB_WARN("Intrinsics ", name, " not implemented by ", domain_name());
// }
// // void backward_intrinsic(std::string name,
// // const variable_or_constant_vector_t &inputs,
// // const variable_vector_t &outputs,
// // const constant_domain_t &invariant) override {
// // CRAB_WARN("Intrinsics ", name, " not implemented by ", domain_name());
// // }
// // // backward arithmetic operations
// // void backward_assign(const variable_t &x, const linear_expression_t &e,
// // const constant_domain_t &inv) override {
// // crab::CrabStats::count(domain_name() + ".count.backward_assign");
// // crab::ScopedCrabStats __st__(domain_name() + ".backward_assign");
// // // TODO
// // }
// // void backward_apply(crab::domains::arith_operation_t op, const
// variable_t &x,
// // const variable_t &y, number_t z,
// // const constant_domain_t &inv) override {
// // crab::CrabStats::count(domain_name() + ".count.backward_apply");
// // crab::ScopedCrabStats __st__(domain_name() + ".backward_apply");
// // // TODO
// // }
// // void backward_apply(crab::domains::arith_operation_t op, const
// variable_t &x,
// // const variable_t &y, const variable_t &z,
// // const constant_domain_t &inv) override {
// // crab::CrabStats::count(domain_name() + ".count.backward_apply");
// // crab::ScopedCrabStats __st__(domain_name() + ".backward_apply");
// // // TODO
// // }
// // cast operations
// // void apply(crab::domains::int_conv_operation_t /*op*/, const variable_t
// &dst,
// // const variable_t &src) override {
// // // ignore the widths
// // assign(dst, src);
// // }
// // bitwise operations
// // void apply(crab::domains::bitwise_operation_t op, const variable_t &x,
// // const variable_t &y, const variable_t &z) override {
// // crab::CrabStats::count(domain_name() + ".count.apply");
// // crab::ScopedCrabStats __st__(domain_name() + ".apply");
// // if (!is_bottom()) {
// // variable_value_t yc = m_env[y];
// // variable_value_t zc = m_env[z];
// // variable_value_t xc = variable_value_t::top();
// // xc = yc.BitwiseOp(zc);
// // m_env.set(x, xc);
// // }
// // }
// // void apply(crab::domains::bitwise_operation_t op, const variable_t &x,
// // const variable_t &y, number_t k) override {
// // crab::CrabStats::count(domain_name() + ".count.apply");
// // crab::ScopedCrabStats __st__(domain_name() + ".apply");
// // // Var_i op num(k) should not be applied
// // CRAB_ERROR("Operation ", op, " not supported for variable domain");
// // if (!is_bottom()) {
// // variable_value_t xc = variable_value_t::top();
// // m_env.set(x, xc);
// // }
// // }
// // virtual void select(const variable_t &lhs, const linear_constraint_t
// &cond,
// // const linear_expression_t &e1,
// // const linear_expression_t &e2) override {
// // crab::CrabStats::count(domain_name() + ".count.select");
// // crab::ScopedCrabStats __st__(domain_name() + ".select");
// // if (!is_bottom()) {
// // constant_domain_t inv1(*this);
// // inv1 += cond;
// // if (inv1.is_bottom()) {
// // assign(lhs, e2);
// // return;
// // }
// // constant_domain_t inv2(*this);
// // inv2 += cond.negate();
// // if (inv2.is_bottom()) {
// // assign(lhs, e1);
// // return;
// // }
// // m_env.set(lhs, eval(e1) | eval(e2));
// // }
// // }
// /// variable_domain_t implements only standard abstract operations of
// /// a equality domain so it is intended to be used as a leaf domain
// /// in the hierarchy of domains.
// NUMERICAL_OPERATIONS_NOT_IMPLEMENTED(variable_domain_t)
// BOOL_OPERATIONS_NOT_IMPLEMENTED(variable_domain_t)
// ARRAY_OPERATIONS_NOT_IMPLEMENTED(variable_domain_t)
// REGION_AND_REFERENCE_OPERATIONS_NOT_IMPLEMENTED(variable_domain_t)
// void forget(const variable_vector_t &variables) override {
// if (is_bottom() || is_top()) {
// return;
// }
// for (auto const &var : variables) {
// this->operator-=(var);
// }
// }
// void project(const variable_vector_t &variables) override {
// crab::CrabStats::count(domain_name() + ".count.project");
// crab::ScopedCrabStats __st__(domain_name() + ".project");
// m_env.project(variables);
// }
// void rename(const variable_vector_t &from,
// const variable_vector_t &to) override {
// crab::CrabStats::count(domain_name() + ".count.rename");
// crab::ScopedCrabStats __st__(domain_name() + ".rename");
// m_env.rename(from, to);
// }
// void expand(const variable_t &x, const variable_t &new_x) override {
// crab::CrabStats::count(domain_name() + ".count.expand");
// crab::ScopedCrabStats __st__(domain_name() + ".expand");
// if (is_bottom() || is_top()) {
// return;
// }
// m_env.set(new_x, m_env[x]);
// }
// void normalize() override {}
// void minimize() override {}
// void write(crab::crab_os &o) const override {
// crab::CrabStats::count(domain_name() + ".count.write");
// crab::ScopedCrabStats __st__(domain_name() + ".write");
// m_env.write(o);
// }
// linear_constraint_system_t to_linear_constraint_system() const override {
// crab::CrabStats::count(domain_name() +
// ".count.to_linear_constraint_system");
// crab::ScopedCrabStats __st__(domain_name() +
// ".to_linear_constraint_system");
// linear_constraint_system_t csts;
// if (this->is_bottom()) {
// csts += linear_constraint_t::get_false();
// return csts;
// }
// for (auto it = m_env.begin(); it != m_env.end(); ++it) {
// const variable_t &v = it->first;
// const variable_value_t &val = it->second;
// if (val.is_variable()) {
// csts += linear_constraint_t(v == val.get_variable());
// }
// }
// return csts;
// }
// disjunctive_linear_constraint_system_t
// to_disjunctive_linear_constraint_system() const override {
// auto lin_csts = to_linear_constraint_system();
// if (lin_csts.is_false()) {
// return disjunctive_linear_constraint_system_t(true /*is_false*/);
// } else if (lin_csts.is_true()) {
// return disjunctive_linear_constraint_system_t(false /*is_false*/);
// } else {
// return disjunctive_linear_constraint_system_t(lin_csts);
// }
// }
// std::string domain_name() const override { return "VariableDomain"; }
// }; // class variable_domain
} // namespace domains
} // namespace crab
// namespace crab {
// namespace domains {
// template <typename VariableName>
// struct abstract_domain_traits<variable_domain<VariableName>> {
// using number_t = Number;
// using varname_t = VariableName;
// };
// } // namespace domains
// } // namespace crab
| 31.575188 | 80 | 0.585863 | [
"object"
] |
a058df4a35e626ec50154fd8f9b14c6d0c9a431b | 9,337 | cpp | C++ | client/UI/angelscript/Checkbox.cpp | vblanco20-1/NovusCore-Client | 662596465a1851cb87240290f34544f4edf76aa0 | [
"MIT"
] | null | null | null | client/UI/angelscript/Checkbox.cpp | vblanco20-1/NovusCore-Client | 662596465a1851cb87240290f34544f4edf76aa0 | [
"MIT"
] | null | null | null | client/UI/angelscript/Checkbox.cpp | vblanco20-1/NovusCore-Client | 662596465a1851cb87240290f34544f4edf76aa0 | [
"MIT"
] | null | null | null | #include "Checkbox.h"
#include "Panel.h"
#include "../../Scripting/ScriptEngine.h"
#include "../../Utils/ServiceLocator.h"
#include <GLFW/glfw3.h>
#include "../ECS/Components/Singletons/UILockSingleton.h"
#include "../ECS/Components/Visible.h"
#include "../ECS/Components/Renderable.h"
#include "../ECS/Components/Collidable.h"
namespace UIScripting
{
Checkbox::Checkbox() : BaseElement(UI::UIElementType::UITYPE_CHECKBOX)
{
entt::registry* registry = ServiceLocator::GetUIRegistry();
UISingleton::UILockSingleton& uiLockSingleton = registry->ctx<UISingleton::UILockSingleton>();
uiLockSingleton.mutex.lock();
{
UIComponent::Transform* transform = ®istry->emplace<UIComponent::Transform>(_entityId);
transform->sortData.entId = _entityId;
transform->sortData.type = _elementType;
transform->asObject = this;
registry->emplace<UIComponent::Visible>(_entityId);
registry->emplace<UIComponent::Visibility>(_entityId);
registry->emplace<UIComponent::Image>(_entityId);
UIComponent::Checkbox* checkBox = ®istry->emplace<UIComponent::Checkbox>(_entityId);
checkBox->asObject = this;
registry->emplace<UIComponent::Renderable>(_entityId);
registry->emplace<UIComponent::Collidable>(_entityId);
UIComponent::TransformEvents* events = ®istry->emplace<UIComponent::TransformEvents>(_entityId);
events->asObject = this;
events->SetFlag(UI::UITransformEventsFlags::UIEVENTS_FLAG_CLICKABLE);
}
uiLockSingleton.mutex.unlock();
checkPanel = Panel::CreatePanel();
checkPanel->SetFillParentSize(true);
checkPanel->SetCollisionEnabled(false);
checkPanel->SetParent(this);
checkPanel->SetDepth(500);
}
void Checkbox::RegisterType()
{
i32 r = ScriptEngine::RegisterScriptClass("Checkbox", 0, asOBJ_REF | asOBJ_NOCOUNT);
r = ScriptEngine::RegisterScriptInheritance<BaseElement, Checkbox>("BaseElement");
r = ScriptEngine::RegisterScriptFunction("Checkbox@ CreateCheckbox()", asFUNCTION(Checkbox::CreateCheckbox)); assert(r >= 0);
// TransformEvents Functions
r = ScriptEngine::RegisterScriptClassFunction("void SetEventFlag(int8 flags)", asMETHOD(Checkbox, SetEventFlag)); assert(r >= 0);
r = ScriptEngine::RegisterScriptClassFunction("void UnsetEventFlag(int8 flags)", asMETHOD(Checkbox, UnsetEventFlag)); assert(r >= 0);
r = ScriptEngine::RegisterScriptClassFunction("bool IsClickable()", asMETHOD(Checkbox, IsClickable)); assert(r >= 0);
r = ScriptEngine::RegisterScriptClassFunction("bool IsDraggable()", asMETHOD(Checkbox, IsDraggable)); assert(r >= 0);
r = ScriptEngine::RegisterScriptClassFunction("bool IsFocusable()", asMETHOD(Checkbox, IsFocusable)); assert(r >= 0);
r = ScriptEngine::RegisterScriptFunctionDef("void CheckboxEventCallback(Checkbox@ checkbox)"); assert(r >= 0);
r = ScriptEngine::RegisterScriptClassFunction("void OnClick(CheckboxEventCallback@ cb)", asMETHOD(Checkbox, SetOnClickCallback)); assert(r >= 0);
r = ScriptEngine::RegisterScriptClassFunction("void OnDragged(CheckboxEventCallback@ cb)", asMETHOD(Checkbox, SetOnDragCallback)); assert(r >= 0);
r = ScriptEngine::RegisterScriptClassFunction("void OnFocused(CheckboxEventCallback@ cb)", asMETHOD(Checkbox, SetOnFocusCallback)); assert(r >= 0);
// Rendering Functions
r = ScriptEngine::RegisterScriptClassFunction("void SetBackgroundTexture(string Texture)", asMETHOD(Checkbox, SetBackgroundTexture)); assert(r >= 0);
r = ScriptEngine::RegisterScriptClassFunction("string GetBackgroundTexture()", asMETHOD(Checkbox, GetBackgroundTexture)); assert(r >= 0);
r = ScriptEngine::RegisterScriptClassFunction("void SetBackgroundColor(Color color)", asMETHOD(Checkbox, SetBackgroundColor)); assert(r >= 0);
r = ScriptEngine::RegisterScriptClassFunction("Color GetBackgroundColor()", asMETHOD(Checkbox, GetBackgroundColor)); assert(r >= 0);
r = ScriptEngine::RegisterScriptClassFunction("void SetCheckTexture(string Texture)", asMETHOD(Checkbox, SetCheckTexture)); assert(r >= 0);
r = ScriptEngine::RegisterScriptClassFunction("string GetCheckTexture()", asMETHOD(Checkbox, GetCheckTexture)); assert(r >= 0);
r = ScriptEngine::RegisterScriptClassFunction("void SetCheckColor(Color color)", asMETHOD(Checkbox, SetCheckColor)); assert(r >= 0);
r = ScriptEngine::RegisterScriptClassFunction("Color GetCheckColor()", asMETHOD(Checkbox, GetCheckColor)); assert(r >= 0);
// Checkbox Functions
r = ScriptEngine::RegisterScriptClassFunction("void SetChecked(bool checked)", asMETHOD(Checkbox, SetChecked)); assert(r >= 0);
}
const bool Checkbox::IsClickable() const
{
const UIComponent::TransformEvents* events = &ServiceLocator::GetUIRegistry()->get<UIComponent::TransformEvents>(_entityId);
return events->IsClickable();
}
const bool Checkbox::IsDraggable() const
{
const UIComponent::TransformEvents* events = &ServiceLocator::GetUIRegistry()->get<UIComponent::TransformEvents>(_entityId);
return events->IsDraggable();
}
const bool Checkbox::IsFocusable() const
{
const UIComponent::TransformEvents* events = &ServiceLocator::GetUIRegistry()->get<UIComponent::TransformEvents>(_entityId);
return events->IsFocusable();
}
void Checkbox::SetEventFlag(const UI::UITransformEventsFlags flags)
{
UIComponent::TransformEvents* events = &ServiceLocator::GetUIRegistry()->get<UIComponent::TransformEvents>(_entityId);
events->SetFlag(flags);
}
void Checkbox::UnsetEventFlag(const UI::UITransformEventsFlags flags)
{
UIComponent::TransformEvents* events = &ServiceLocator::GetUIRegistry()->get<UIComponent::TransformEvents>(_entityId);
events->UnsetFlag(flags);
}
void Checkbox::SetOnClickCallback(asIScriptFunction* callback)
{
UIComponent::TransformEvents* events = &ServiceLocator::GetUIRegistry()->get<UIComponent::TransformEvents>(_entityId);
events->onClickCallback = callback;
events->SetFlag(UI::UITransformEventsFlags::UIEVENTS_FLAG_CLICKABLE);
}
void Checkbox::SetOnDragCallback(asIScriptFunction* callback)
{
UIComponent::TransformEvents* events = &ServiceLocator::GetUIRegistry()->get<UIComponent::TransformEvents>(_entityId);
events->onDraggedCallback = callback;
events->SetFlag(UI::UITransformEventsFlags::UIEVENTS_FLAG_DRAGGABLE);
}
void Checkbox::SetOnFocusCallback(asIScriptFunction* callback)
{
UIComponent::TransformEvents* events = &ServiceLocator::GetUIRegistry()->get<UIComponent::TransformEvents>(_entityId);
events->onFocusedCallback = callback;
events->SetFlag(UI::UITransformEventsFlags::UIEVENTS_FLAG_FOCUSABLE);
}
const std::string& Checkbox::GetBackgroundTexture() const
{
const UIComponent::Image* image = &ServiceLocator::GetUIRegistry()->get<UIComponent::Image>(_entityId);
return image->texture;
}
void Checkbox::SetBackgroundTexture(const std::string& texture)
{
entt::registry* registry = ServiceLocator::GetUIRegistry();
UIComponent::Image* image = ®istry->get<UIComponent::Image>(_entityId);
image->texture = texture;
}
const Color Checkbox::GetBackgroundColor() const
{
const UIComponent::Image* image = &ServiceLocator::GetUIRegistry()->get<UIComponent::Image>(_entityId);
return image->color;
}
void Checkbox::SetBackgroundColor(const Color& color)
{
entt::registry* registry = ServiceLocator::GetUIRegistry();
UIComponent::Image* image = ®istry->get<UIComponent::Image>(_entityId);
image->color = color;
}
const std::string& Checkbox::GetCheckTexture() const
{
return checkPanel->GetTexture();
}
void Checkbox::SetCheckTexture(const std::string& texture)
{
checkPanel->SetTexture(texture);
}
const Color Checkbox::GetCheckColor() const
{
return checkPanel->GetColor();
}
void Checkbox::SetCheckColor(const Color& color)
{
checkPanel->SetColor(color);
}
const bool Checkbox::IsChecked() const
{
const UIComponent::Checkbox* checkBox = &ServiceLocator::GetUIRegistry()->get<UIComponent::Checkbox>(_entityId);
return checkBox->checked;
}
void Checkbox::SetChecked(bool checked)
{
UIComponent::Checkbox* checkBox = &ServiceLocator::GetUIRegistry()->get<UIComponent::Checkbox>(_entityId);
checkBox->checked = checked;
checkPanel->SetVisible(checked);
if (checked)
checkBox->OnChecked();
else
checkBox->OnUnchecked();
}
void Checkbox::ToggleChecked()
{
SetChecked(!IsChecked());
}
void Checkbox::HandleKeyInput(i32 key)
{
if (key == GLFW_KEY_ENTER)
{
ToggleChecked();
}
}
Checkbox* Checkbox::CreateCheckbox()
{
Checkbox* checkbox = new Checkbox();
return checkbox;
}
} | 44.889423 | 157 | 0.686944 | [
"transform"
] |
a058fd75441724de2adb3d0d5d7fb6bf52526fc8 | 7,924 | cpp | C++ | samples/sources/sample_00/sample_00.cpp | NechukhrinN/enduro2d | 774f120395885a6f0f21418c4de024e7668ee436 | [
"MIT"
] | 92 | 2018-08-07T14:45:33.000Z | 2021-11-14T20:37:23.000Z | samples/sources/sample_00/sample_00.cpp | NechukhrinN/enduro2d | 774f120395885a6f0f21418c4de024e7668ee436 | [
"MIT"
] | 43 | 2018-09-30T20:48:03.000Z | 2020-04-20T20:05:26.000Z | samples/sources/sample_00/sample_00.cpp | NechukhrinN/enduro2d | 774f120395885a6f0f21418c4de024e7668ee436 | [
"MIT"
] | 13 | 2018-08-08T13:45:28.000Z | 2020-10-02T11:55:58.000Z | /*******************************************************************************
* This file is part of the "Enduro2D"
* For conditions of distribution and use, see copyright notice in LICENSE.md
* Copyright (C) 2018-2020, by Matvey Cherevko (blackmatov@gmail.com)
******************************************************************************/
#include "../common.hpp"
using namespace e2d;
namespace
{
const char* vs_source_cstr = R"glsl(
attribute vec3 a_position;
attribute vec2 a_uv;
attribute vec4 a_color;
uniform float u_time;
uniform mat4 u_MVP;
varying vec4 v_color;
varying vec2 v_uv;
void main(){
v_color = a_color;
v_uv = a_uv;
float s = 0.7 + 0.3 * (cos(u_time * 3.0) + 1.0);
gl_Position = vec4(a_position * s, 1.0) * u_MVP;
}
)glsl";
const char* fs_source_cstr = R"glsl(
uniform float u_time;
uniform sampler2D u_texture1;
uniform sampler2D u_texture2;
varying vec4 v_color;
varying vec2 v_uv;
void main(){
vec2 uv = vec2(v_uv.s, 1.0 - v_uv.t);
if ( u_time > 2.0 ) {
gl_FragColor = v_color * texture2D(u_texture2, uv);
} else {
gl_FragColor = v_color * texture2D(u_texture1, uv);
}
}
)glsl";
struct vertex1 {
v3f position;
v2hu uv;
static vertex_declaration decl() noexcept {
return vertex_declaration()
.add_attribute<v3f>("a_position")
.add_attribute<v2hu>("a_uv");
}
};
struct vertex2 {
color32 color;
static vertex_declaration decl() noexcept {
return vertex_declaration()
.add_attribute<color32>("a_color").normalized();
}
};
std::array<u16,6> generate_quad_indices() noexcept {
return {0, 1, 2, 2, 1, 3};
}
std::array<vertex1,4> generate_quad_vertices(const v2u& size) noexcept {
f32 hw = size.x * 0.5f;
f32 hh = size.y * 0.5f;
return {
vertex1{{-hw, hh, 0.f}, {0, 1}},
vertex1{{-hw, -hh, 0.f}, {0, 0}},
vertex1{{ hw, hh, 0.f}, {1, 1}},
vertex1{{ hw, -hh, 0.f}, {1, 0}}};
}
std::array<vertex2,4> generate_quad_colors() noexcept {
return {
vertex2{color32::red()},
vertex2{color32::green()},
vertex2{color32::blue()},
vertex2{color32::yellow()}};
}
class game final : public engine::application {
public:
bool initialize() final {
the<vfs>().register_scheme<archive_file_source>(
"piratepack",
the<vfs>().read(url("resources://bin/kenney_piratepack.zip")));
the<vfs>().register_scheme_alias(
"ships",
url("piratepack://PNG/Retina/Ships"));
image texture1_image;
if ( !images::try_load_image(texture1_image, the<vfs>().read(url("ships://ship (2).png"))) ) {
return false;
}
image texture2_image;
if ( !images::try_load_image(texture2_image, the<vfs>().read(url("ships://ship (19).png"))) ) {
return false;
}
shader_ = the<render>().create_shader(vs_source_cstr, fs_source_cstr);
texture1_ = the<render>().create_texture(texture1_image);
texture2_ = the<render>().create_texture(texture2_image);
if ( !shader_ || !texture1_ || !texture2_ ) {
return false;
}
const auto indices = generate_quad_indices();
index_buffer_ = the<render>().create_index_buffer(
indices,
index_declaration::index_type::unsigned_short,
index_buffer::usage::static_draw);
const auto vertices1 = generate_quad_vertices(texture1_->size());
vertex_buffer1_ = the<render>().create_vertex_buffer(
vertices1,
vertex1::decl(),
vertex_buffer::usage::static_draw);
const auto vertices2 = generate_quad_colors();
vertex_buffer2_ = the<render>().create_vertex_buffer(
vertices2,
vertex2::decl(),
vertex_buffer::usage::static_draw);
if ( !index_buffer_ || !vertex_buffer1_ || !vertex_buffer2_ ) {
return false;
}
material_ = render::material()
.add_pass(render::pass_state()
.states(render::state_block()
.capabilities(render::capabilities_state()
.blending(true))
.blending(render::blending_state()
.src_factor(render::blending_factor::src_alpha)
.dst_factor(render::blending_factor::one_minus_src_alpha)))
.shader(shader_)
.properties(render::property_block()
.sampler("u_texture1", render::sampler_state()
.texture(texture1_)
.min_filter(render::sampler_min_filter::linear)
.mag_filter(render::sampler_mag_filter::linear))
.sampler("u_texture2", render::sampler_state()
.texture(texture2_)
.min_filter(render::sampler_min_filter::linear)
.mag_filter(render::sampler_mag_filter::linear))));
geometry_ = render::geometry()
.indices(index_buffer_)
.add_vertices(vertex_buffer1_)
.add_vertices(vertex_buffer2_);
return true;
}
bool frame_tick() final {
const keyboard& k = the<input>().keyboard();
if ( the<window>().should_close() || k.is_key_just_released(keyboard_key::escape) ) {
return false;
}
if ( k.is_key_just_pressed(keyboard_key::f12) ) {
the<dbgui>().toggle_visible(!the<dbgui>().visible());
}
if ( k.is_key_pressed(keyboard_key::lsuper) && k.is_key_just_released(keyboard_key::enter) ) {
the<window>().toggle_fullscreen(!the<window>().fullscreen());
}
return true;
}
void frame_render() final {
const auto framebuffer_size = the<window>().real_size().cast_to<f32>();
const auto projection = math::make_orthographic_lh_matrix4(
framebuffer_size, 0.f, 1.f);
material_.properties()
.property("u_time", the<engine>().time())
.property("u_MVP", projection);
the<render>().execute(render::command_block<64>()
.add_command(render::viewport_command(
the<window>().framebuffer_size().cast_to<i32>()))
.add_command(render::clear_command()
.color_value({1.f, 0.4f, 0.f, 1.f}))
.add_command(render::draw_command(material_, geometry_)));
}
private:
shader_ptr shader_;
texture_ptr texture1_;
texture_ptr texture2_;
index_buffer_ptr index_buffer_;
vertex_buffer_ptr vertex_buffer1_;
vertex_buffer_ptr vertex_buffer2_;
render::material material_;
render::geometry geometry_;
};
}
int e2d_main(int argc, char *argv[]) {
auto params = engine::parameters("sample_00", "enduro2d")
.window_params(engine::window_parameters()
.size({1024, 768}))
.timer_params(engine::timer_parameters()
.maximal_framerate(100));
modules::initialize<engine>(argc, argv, params).start<game>();
modules::shutdown<engine>();
return 0;
}
| 35.533632 | 107 | 0.528142 | [
"geometry",
"render"
] |
a059bdd314f94f21e5b3b30aa64e478767c723f4 | 5,397 | cpp | C++ | Src/GIS/tile2/heightmap3.cpp | jjuiddong/Car-Navigation | 4b9a33f9a386d5e9355b174962d6b5b756dfc477 | [
"MIT"
] | 4 | 2019-12-08T23:10:15.000Z | 2019-12-18T11:38:27.000Z | Src/GIS/tile2/heightmap3.cpp | jjuiddong/Car-Navigation | 4b9a33f9a386d5e9355b174962d6b5b756dfc477 | [
"MIT"
] | 1 | 2020-01-17T19:00:29.000Z | 2020-01-17T19:00:29.000Z | Src/GIS/tile2/heightmap3.cpp | jjuiddong/Car-Navigation | 4b9a33f9a386d5e9355b174962d6b5b756dfc477 | [
"MIT"
] | 2 | 2019-12-11T21:12:14.000Z | 2021-12-31T09:48:41.000Z |
#include "stdafx.h"
#include "heightmap3.h"
using namespace graphic;
using namespace gis2;
const float cHeightmap3::DEFAULT_H = 2.f;
cHeightmap3::cHeightmap3()
: m_level(0)
, m_x(0)
, m_y(0)
, m_width(0)
, m_height(0)
, m_data(nullptr)
, m_maxH(1.f)
, m_minH(-1.f)
, m_texture(nullptr)
, m_isTextureUpdate(false)
{
}
cHeightmap3::cHeightmap3(graphic::cRenderer &renderer, const char *fileName)
: m_level(0)
, m_x(0)
, m_y(0)
, m_width(0)
, m_height(0)
, m_data(nullptr)
, m_texture(nullptr)
, m_isTextureUpdate(false)
{
if (!ReadAndCreateTexture(renderer, fileName))
throw std::exception();
}
cHeightmap3::cHeightmap3(graphic::cRenderer &renderer, const cHeightmap3 *src,
const char *fileName, const sHeightmapArgs2 &args)
{
if (!Create(renderer, *src, args.huvs, args.level, args.x, args.y))
throw std::exception();
m_fileName = fileName;
}
cHeightmap3::~cHeightmap3()
{
Clear();
}
// copy src heightmap
// copy src from huvs[4]
bool cHeightmap3::Create(cRenderer &renderer, const cHeightmap3 &src
, const float huvs[4]
, const int level, const int x, const int y)
{
// nothing~
return false;
}
// read heightmap custom file format
// file format
// - file type: 'dem' 3byte
// - width: unsigned short 4byte
// - height: unsigned short 4byte
// - heightmap: width * height * float(4byte)
bool cHeightmap3::ReadCustom(const char *fileName)
{
Clear();
std::ifstream ifs(fileName, std::ios::binary);
if (!ifs.is_open())
return false;
char fmt[4] = { 0, };
ifs.read(fmt, 3);
if (string("dem") != fmt)
return false;
ifs.read((char*)&m_width, sizeof(m_width));
ifs.read((char*)&m_height, sizeof(m_height));
if (m_width * m_height > 10000000)
return false; // too large
m_data = new float[m_width * m_height];
ifs.read((char*)m_data, sizeof(float) * m_width * m_height);
UpdateLocationByString(fileName);
return true;
}
// read heightmap file where directoryName, level, x, y
bool cHeightmap3::Read(const char *directoryName,
const int level, const int x, const int y)
{
const int ty = (1 << level) - y - 1;
StrPath path;
path.Format("%s\\%d\\%04d\\%04d_%04d.bil", directoryName, level, ty, ty, x);
return Read(path.c_str());
}
// read ArcGis heightmap file (lerc)
// parse level, x, y by filename
// filename format: *//level//yloc//yloc_xloc.bil
bool cHeightmap3::Read(const char *fileName)
{
using namespace std;
Clear();
cCntZImg czimg;
float *buffer = czimg.UnCompress(fileName);
if (!buffer)
return false;
m_width = czimg.m_width;
m_height = czimg.m_height;
m_data = buffer;
return true;
}
// write heightmap data custom format
// file format
// - file type: 'dem' 3byte
// - width: unsigned short 4byte
// - height: unsigned short 4byte
// - heightmap: width * height * float(4byte)
bool cHeightmap3::Write(const StrPath &directoryName)
{
if (!m_data)
return false;
const StrPath fileName = GetFileName(directoryName.c_str());
std::ofstream ofs(fileName.c_str(), std::ios::binary);
if (!ofs.is_open())
return false;
ofs.write("dem", 3);
ofs.write((char*)&m_width, sizeof(m_width));
ofs.write((char*)&m_height, sizeof(m_height));
ofs.write((char*)m_data, m_width * m_height * sizeof(float));
return true;
}
// read heightmap and then create texture buffer
bool cHeightmap3::ReadAndCreateTexture(graphic::cRenderer &renderer,
const char *fileName)
{
if (!Read(fileName))
return false;
if (m_texture = new graphic::cTexture())
{
m_texture->Create(renderer, m_width, m_height
, DXGI_FORMAT_R32_FLOAT
, m_data, m_width * sizeof(float)
, D3D11_USAGE_DYNAMIC);
m_isTextureUpdate = true;
}
return m_texture ? true : false;
}
StrPath cHeightmap3::GetFileName(const StrPath &directoryName
, const int level, const int x, const int y)
{
const int ty = (1 << level) - y - 1;
StrPath path;
path.Format("%s\\%d\\%04d\\%04d_%04d.bil", directoryName.c_str(), level, ty, ty, x);
return path;
}
StrPath cHeightmap3::GetFileName(const char *directoryName)
{
return GetFileName(directoryName, m_level, m_x, m_y);
}
float cHeightmap3::GetHeight(const Vector2 &uv)
{
RETV(!m_data, 0);
const Vector2 pos(max(0.f, min(1.f, uv.x)), max(0.f, min(1.f, uv.y)));
const int x = (int)((m_width - 1) * pos.x);
const int y = (int)((m_height - 1) * pos.y);
const float val = m_data[(m_width * y) + x];
return val * 0.05f;
}
// clac heightmap min/max boundingbox
bool cHeightmap3::CalcBoundingBox()
{
RETV(!m_data, false);
float maxH = FLT_MIN;
float minH = FLT_MAX;
const int n = m_width * m_height;
float *p = m_data;
for (int i = 0; i < n; ++i, ++p)
{
if (maxH < *p)
maxH = *p;
if (minH > *p)
minH = *p;
}
m_maxH = std::max(DEFAULT_H, maxH * 0.05f);
m_minH = minH * 0.05f;
return true;
}
// update level, x, y attribute by string
// string: maybe filename, ex) *//level//y//y_x.bil
bool cHeightmap3::UpdateLocationByString(const string &str)
{
vector<string> out;
common::tokenizer(str, "\\", {}, out);
if (out.size() < 4)
return false;
const int s = out.size();
const int level = atoi(out[s - 3].c_str());
int y = 0, x = 0;
const int cnt = sscanf(out[s - 1].c_str(), "%d_%d.bill", &y, &x);
RETV(cnt < 2, false);
m_level = level;
m_x = x;
m_y = (1 << level) - y - 1; // change arcgis space -> original space
return true;
}
void cHeightmap3::Clear()
{
SAFE_DELETEA(m_data);
SAFE_DELETE(m_texture);
m_isTextureUpdate = false;
}
| 21.501992 | 85 | 0.672966 | [
"vector"
] |
a065cdfa8b0c15f3e37f8b94528dea6dbca28fe9 | 1,677 | hh | C++ | packages/data/Material_Factory.hh | brbass/ibex | 5a4cc5b4d6d46430d9667970f8a34f37177953d4 | [
"MIT"
] | 2 | 2020-04-13T20:06:41.000Z | 2021-02-12T17:55:54.000Z | packages/data/Material_Factory.hh | brbass/ibex | 5a4cc5b4d6d46430d9667970f8a34f37177953d4 | [
"MIT"
] | 1 | 2018-10-22T21:03:35.000Z | 2018-10-22T21:03:35.000Z | packages/data/Material_Factory.hh | brbass/ibex | 5a4cc5b4d6d46430d9667970f8a34f37177953d4 | [
"MIT"
] | 3 | 2019-04-03T02:15:37.000Z | 2022-01-04T05:50:23.000Z | #ifndef Material_Factory_hh
#define Material_Factory_hh
#include <memory>
#include <vector>
class Angular_Discretization;
class Energy_Discretization;
class Material;
/*
Create a Material object standard data
*/
class Material_Factory
{
public:
// Constructor
Material_Factory(std::shared_ptr<Angular_Discretization> angular,
std::shared_ptr<Energy_Discretization> energy);
// Return Material object
std::shared_ptr<Material> get_standard_material(int index,
std::vector<double> const &sigma_t_data,
std::vector<double> const &sigma_s_data,
std::vector<double> const &nu_data,
std::vector<double> const &sigma_f_data,
std::vector<double> const &chi_data,
std::vector<double> const &internal_source_data) const;
std::shared_ptr<Material> get_full_fission_material(int index,
std::vector<double> const &sigma_t_data,
std::vector<double> const &sigma_s_data,
std::vector<double> const &sigma_f_data,
std::vector<double> const &internal_source_data) const;
private:
std::shared_ptr<Angular_Discretization> angular_;
std::shared_ptr<Energy_Discretization> energy_;
};
#endif
| 39 | 111 | 0.517591 | [
"object",
"vector"
] |
a066e191213ffaa91af6a6c382acbde5a72ba696 | 9,549 | cpp | C++ | SampleGraphics/Skinning/Skinning.cpp | wjezxujian/WildMagic4 | 249a17f8c447cf57c6283408e01009039810206a | [
"BSL-1.0"
] | 3 | 2021-08-02T04:03:03.000Z | 2022-01-04T07:31:20.000Z | SampleGraphics/Skinning/Skinning.cpp | wjezxujian/WildMagic4 | 249a17f8c447cf57c6283408e01009039810206a | [
"BSL-1.0"
] | null | null | null | SampleGraphics/Skinning/Skinning.cpp | wjezxujian/WildMagic4 | 249a17f8c447cf57c6283408e01009039810206a | [
"BSL-1.0"
] | 5 | 2019-10-13T02:44:19.000Z | 2021-08-02T04:03:10.000Z | // Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// The Wild Magic Version 4 Restricted Libraries source code is supplied
// under the terms of the license agreement
// http://www.geometrictools.com/License/Wm4RestrictedLicense.pdf
// and may not be copied or disclosed except in accordance with the terms
// of that agreement.
#include "Skinning.h"
WM4_WINDOW_APPLICATION(Skinning);
//----------------------------------------------------------------------------
Skinning::Skinning ()
:
WindowApplication3("Skinning",0,0,640,480,ColorRGBA(0.5f,0.0f,1.0f,1.0f))
{
}
//----------------------------------------------------------------------------
bool Skinning::OnInitialize ()
{
if (!WindowApplication3::OnInitialize())
{
return false;
}
m_spkCamera->SetFrustum(-0.55f,0.55f,-0.4125f,0.4125f,1.0f,1000.0f);
Vector3f kCLoc(0.0f, 0.0f, 0.0f);
Vector3f kCDir(0.0f,0.0f,1.0f);
Vector3f kCUp(0.0f,1.0f,0.0f);
Vector3f kCRight = kCDir.Cross(kCUp);
m_spkCamera->SetFrame(kCLoc,kCDir,kCUp,kCRight);
CreateScene();
// initial update of objects
m_spkScene->UpdateGS();
m_spkScene->UpdateRS();
// initial culling of scene
m_kCuller.SetCamera(m_spkCamera);
m_kCuller.ComputeVisibleSet(m_spkScene);
InitializeCameraMotion(0.1f,0.001f);
InitializeObjectMotion(m_spkMesh);
return true;
}
//----------------------------------------------------------------------------
void Skinning::OnTerminate ()
{
m_spkScene = 0;
m_spkEffect = 0;
m_spkMesh = 0;
WindowApplication3::OnTerminate();
}
//----------------------------------------------------------------------------
void Skinning::OnIdle ()
{
MeasureTime();
UpdateConstants((float)System::GetTime());
if (MoveCamera())
{
m_kCuller.ComputeVisibleSet(m_spkScene);
}
if (MoveObject())
{
m_spkScene->UpdateGS();
m_kCuller.ComputeVisibleSet(m_spkScene);
}
m_pkRenderer->ClearBuffers();
if (m_pkRenderer->BeginScene())
{
m_pkRenderer->DrawScene(m_kCuller.GetVisibleSet());
DrawFrameRate(8,GetHeight()-8,ColorRGBA::BLACK);
m_pkRenderer->EndScene();
}
m_pkRenderer->DisplayBackBuffer();
UpdateFrameCount();
}
//----------------------------------------------------------------------------
bool Skinning::OnKeyDown (unsigned char ucKey, int iX, int iY)
{
if (WindowApplication3::OnKeyDown(ucKey,iX,iY))
{
return true;
}
switch (ucKey)
{
case 's':
case 'S':
TestStreaming(m_spkScene,128,128,640,480,"Skinning.wmof");
return true;
}
return false;
}
//----------------------------------------------------------------------------
void Skinning::CreateScene ()
{
Attributes kAttr;
kAttr.SetPChannels(3);
kAttr.SetCChannels(0,3); // RGB vertex colors
kAttr.SetTChannels(0,4); // weights for skinning
// The skinned object is a cylinder.
const int iRadialSamples = 10;
const int iAxisSamples = 7;
const float fRadius = 10.0f;
const float fHeight = 80.0f;
const float fInvRS = 1.0f/(float)iRadialSamples;
const float fInvASm1 = 1.0f/(float)(iAxisSamples-1);
const float fHalfHeight = 0.5f*fHeight;
const Vector3f kCenter(0.0f,0.0f,100.0f);
const Vector3f kU(0.0f,0.0f,-1.0f);
const Vector3f kV(0.0f,1.0f,0.0f);
const Vector3f kAxis(1.0f,0.0f,0.0f);
// generate geometry
int iVQuantity = iAxisSamples*(iRadialSamples+1);
VertexBuffer* pkVB = WM4_NEW VertexBuffer(kAttr,iVQuantity);
// Generate points on the unit circle to be used in computing the mesh
// points on a cylinder slice.
int iR, iA, iAStart, i;
float* afSin = WM4_NEW float[iRadialSamples+1];
float* afCos = WM4_NEW float[iRadialSamples+1];
for (iR = 0; iR < iRadialSamples; iR++)
{
float fAngle = Mathf::TWO_PI*fInvRS*iR;
afCos[iR] = Mathf::Cos(fAngle);
afSin[iR] = Mathf::Sin(fAngle);
}
afSin[iRadialSamples] = afSin[0];
afCos[iRadialSamples] = afCos[0];
// generate the cylinder itself
for (iA = 0, i = 0; iA < iAxisSamples; iA++)
{
float fAxisFraction = iA*fInvASm1; // in [0,1]
float fZ = -fHalfHeight + fHeight*fAxisFraction;
// compute center of slice
Vector3f kSliceCenter = kCenter + fZ*kAxis;
// compute slice vertices with duplication at end point
ColorRGB kColor(fAxisFraction,1.0f-fAxisFraction,0.3f);
Vector4f kTCoord;
int iSave = i;
for (iR = 0; iR < iRadialSamples; iR++)
{
// vertex position and color
Vector3f kNormal = afCos[iR]*kU + afSin[iR]*kV;
pkVB->Position3(i) = kSliceCenter + fRadius*kNormal;
pkVB->Color3(0,i) = kColor;
// Set texture coordinates to the correct vertex weights.
if (iA == 0)
{
kTCoord[0] = 1.0f;
}
else if (iA == 1)
{
kTCoord[0] = 0.5f;
}
else
{
kTCoord[0] = 0.0f;
}
if (iA == 1 || iA == 3)
{
kTCoord[1] = 0.5f;
}
else if (iA == 2)
{
kTCoord[1] = 1.0f;
}
else
{
kTCoord[1] = 0.0f;
}
if (iA == 3 || iA == 5)
{
kTCoord[2] = 0.5f;
}
else if (iA == 4)
{
kTCoord[2] = 1.0f;
}
else
{
kTCoord[2] = 0.0f;
}
if (iA == 6)
{
kTCoord[3] = 1.0f;
}
else if (iA == 5)
{
kTCoord[3] = 0.5f;
}
else
{
kTCoord[3] = 0.0f;
}
pkVB->TCoord4(0,i) = kTCoord;
i++;
}
// vertex position and color
pkVB->Position3(i) = pkVB->Position3(iSave);
pkVB->Color3(0,i) = kColor;
// Set texture coordinates to the correct vertex weights.
if (iA == 0)
{
kTCoord[0] = 1.0f;
}
else if (iA == 1)
{
kTCoord[0] = 0.5f;
}
else
{
kTCoord[0] = 0.0f;
}
if (iA == 1 || iA == 3)
{
kTCoord[1] = 0.5f;
}
else if (iA == 2)
{
kTCoord[1] = 1.0f;
}
else
{
kTCoord[1] = 0.0f;
}
if (iA == 3 || iA == 5)
{
kTCoord[2] = 0.5f;
}
else if (iA == 4)
{
kTCoord[2] = 1.0f;
}
else
{
kTCoord[2] = 0.0f;
}
if (iA == 6)
{
kTCoord[3] = 1.0f;
}
else if (iA == 5)
{
kTCoord[3] = 0.5f;
}
else
{
kTCoord[3] = 0.0f;
}
pkVB->TCoord4(0,i) = kTCoord;
i++;
}
// generate connectivity
int iTQuantity = 2*(iAxisSamples-1)*iRadialSamples;
int iIQuantity = 3*iTQuantity;
IndexBuffer* pkIB = WM4_NEW IndexBuffer(iIQuantity);
int* aiIndex = pkIB->GetData();
int* aiLocalIndex = aiIndex;
for (iA = 0, iAStart = 0; iA < iAxisSamples-1; iA++)
{
int i0 = iAStart;
int i1 = i0 + 1;
iAStart += iRadialSamples + 1;
int i2 = iAStart;
int i3 = i2 + 1;
for (i = 0; i < iRadialSamples; i++, aiLocalIndex += 6)
{
aiLocalIndex[0] = i0;
aiLocalIndex[1] = i1;
aiLocalIndex[2] = i2;
aiLocalIndex[3] = i1;
aiLocalIndex[4] = i3;
aiLocalIndex[5] = i2;
i0++;
i1++;
i2++;
i3++;
}
}
WM4_DELETE[] afCos;
WM4_DELETE[] afSin;
m_spkMesh = WM4_NEW TriMesh(pkVB,pkIB);
m_spkScene = WM4_NEW Node;
m_spkScene->AttachChild(m_spkMesh);
m_spkEffect = WM4_NEW SkinningEffect;
m_spkMesh->AttachEffect(m_spkEffect);
}
//----------------------------------------------------------------------------
void Skinning::UpdateConstants (float fTime)
{
// create some arbitrary skinning transformations
const float fFactor = Mathf::PI/1.25f;
int iDiv = (int)(fTime/fFactor);
// the angle now ranges from -factor/4 to +factor/4
float fAngle = Mathf::FAbs(fTime-iDiv*fFactor-fFactor/2.0f)-
fFactor/4.0f;
for (int i = 0; i < 4; i++)
{
float fThisAngle;
if ((int)(fTime/fFactor+0.25f) % 2)
{
fThisAngle = Mathf::FAbs((float)i-1.5f)*fAngle;
}
else
{
fThisAngle = ((float)i-1.5f)*fAngle;
}
Matrix3f kRot(Vector3f::UNIT_Z,fThisAngle);
Vector3f kTrn(0.0f,10.0f*Mathf::Sin(fTime+0.5f*(float)i),0.0f);
// The vector-on-left convention needs to be used since this is what
// the shader system expects.
Matrix4f kMatrix(
kRot[0][0],kRot[1][0],kRot[2][0],0.0f,
kRot[0][1],kRot[1][1],kRot[2][1],0.0f,
kRot[0][2],kRot[1][2],kRot[2][2],0.0f,
kTrn[0], kTrn[1], kTrn[2], 1.0f);
m_spkEffect->SetMatrix(i,kMatrix);
}
}
//----------------------------------------------------------------------------
| 26.673184 | 78 | 0.485705 | [
"mesh",
"geometry",
"object",
"vector"
] |
a06792dfc268549e496d3146458ebb43c19971a6 | 6,594 | cc | C++ | src/main/layer.cc | hisahi/malpinx | 3fd3630073d5abc6e53aa18e6672fb3265f5da94 | [
"MIT"
] | null | null | null | src/main/layer.cc | hisahi/malpinx | 3fd3630073d5abc6e53aa18e6672fb3265f5da94 | [
"MIT"
] | null | null | null | src/main/layer.cc | hisahi/malpinx | 3fd3630073d5abc6e53aa18e6672fb3265f5da94 | [
"MIT"
] | null | null | null | /****************************************************************************/
/* */
/* MALPINX SOURCE CODE (C) 2020 SAMPO HIPPELAINEN (HISAHI). */
/* SEE THE LICENSE FILE IN THE SOURCE ROOT DIRECTORY FOR LICENSE INFO. */
/* */
/****************************************************************************/
// layer.cc: layer implementations
#include <memory>
#include <algorithm>
#include "layer.hh"
#include "sprite.hh"
#include "fix.hh"
BackgroundLayer::BackgroundLayer(std::shared_ptr<Image> bg,
int ox, int oy, Fix sx, Fix sy)
: _img(bg), _offsetX(ox), _offsetY(oy), _scrollXMul(sx), _scrollYMul(sy)
{
}
void BackgroundLayer::blit(Image &fb, LayerScroll scroll)
{
_img->blitTiled(fb, 0, 0, (scroll.x * _scrollXMul).round() - _offsetX,
(scroll.y * _scrollYMul).round() - _offsetY, S_WIDTH, S_HEIGHT);
}
void NonTiledBackgroundLayer::blit(Image &fb, LayerScroll scroll)
{
_img->blit(fb, 0, 0, (scroll.x * _scrollXMul).round() - _offsetX,
(scroll.y * _scrollYMul).round() - _offsetY, S_WIDTH, S_HEIGHT);
}
void HTiledBackgroundLayer::blit(Image &fb, LayerScroll scroll)
{
int sy = _offsetY - (scroll.y * _scrollYMul).round(), oy = 0, sh = S_HEIGHT;
if (sy < 0)
{
oy -= sy;
sh += sy;
oy = 0;
}
if (oy + sh > _img->height())
sh = _img->height() - oy;
if (sh > 0)
_img->blitTiled(fb, 0, sy,
(scroll.x * _scrollXMul).round() - _offsetX, oy, S_WIDTH, sh);
}
void AdditiveBackgroundLayer::blit(Image &fb, LayerScroll scroll)
{
_img->blitAdditiveTiled(fb, 0, 0,
(scroll.x * _scrollXMul).round() - _offsetX,
(scroll.y * _scrollYMul).round() - _offsetY, S_WIDTH, S_HEIGHT);
}
void HTiledAdditiveBackgroundLayer::blit(Image &fb, LayerScroll scroll)
{
int sy = 0, oy = (scroll.y * _scrollYMul).round() - _offsetY, sh = S_HEIGHT;
if (oy < 0)
{
sy -= oy;
sh += oy;
oy = 0;
}
if (sy + sh > _img->height())
sh = _img->height() - sy;
if (sh > 0)
_img->blitAdditiveTiled(fb, 0, sy,
(scroll.x * _scrollXMul).round() - _offsetX, oy, S_WIDTH, sh);
}
void HTiledParallaxBackgroundLayer::blit(Image &fb, LayerScroll scroll)
{
int sy = _offsetY - (scroll.y * _scrollYMul).round(), oy = 0, sh = S_HEIGHT;
if (sy < 0)
{
oy -= sy;
sh += sy;
oy = 0;
}
if (oy + sh > _img->height())
sh = _img->height() - oy;
Fix truexm = _scrollXMul;
for (int yoff = 0; yoff < sh; ++yoff)
{
_img->blitTiled(fb, 0, sy + yoff,
(scroll.x * truexm).round() - _offsetX,
oy + yoff, S_WIDTH, 1);
truexm += sign * 0.016_x;
}
}
void HTiledWavyBackgroundLayer::blit(Image &fb, LayerScroll scroll)
{
int sy = _offsetY - (scroll.y * _scrollYMul).round(), oy = 0, sh = S_HEIGHT;
if (sy < 0)
{
oy -= sy;
sh += sy;
oy = 0;
}
if (oy + sh > _img->height())
sh = _img->height() - oy;
int sinOff = phase;
for (int yoff = 0; yoff < sh; ++yoff)
{
_img->blitTiled(fb, 0, sy + yoff,
(scroll.x * _scrollXMul
+ 16 * sineTable[sinOff >> 1]).round() - _offsetX,
oy + yoff, S_WIDTH, 1);
sinOff = (sinOff + 1) % 256;
}
phase = (phase + 1) % 256;
}
ForegroundLayer::ForegroundLayer(std::shared_ptr<Image> bg,
int ox, int oy, Fix sx, Fix sy)
: _img(bg), _offsetX(ox), _offsetY(oy), _scrollXMul(sx), _scrollYMul(sy)
{
}
void ForegroundLayer::blit(Image &fb, LayerScroll scroll)
{
_img->blitTiled(fb, 0, 0, (scroll.x * _scrollXMul).round() - _offsetX,
(scroll.y * _scrollYMul).round() - _offsetY, S_WIDTH, S_HEIGHT);
}
bool ForegroundLayer::hitsSprite(Image &spriteImage, LayerScroll scroll,
const Hitbox &box, Fix spriteX, Fix spriteY) const
{
return _img->overlapsTiled(spriteImage,
(scroll.x + spriteX).round() - _offsetX,
(scroll.y + spriteY).round() - _offsetY,
box.x, box.y, box.w, box.h);
}
void NonTiledForegroundLayer::blit(Image &fb, LayerScroll scroll)
{
_img->blit(fb, 0, 0, (scroll.x * _scrollXMul).round() - _offsetX,
(scroll.y * _scrollYMul).round() - _offsetY, S_WIDTH, S_HEIGHT);
}
bool NonTiledForegroundLayer::hitsSprite(Image &spriteImage, LayerScroll scroll,
const Hitbox &box, Fix spriteX, Fix spriteY) const
{
return _img->overlaps(spriteImage,
(scroll.x + spriteX).round() - _offsetX,
(scroll.y + spriteY).round() - _offsetY,
box.x, box.y, box.w, box.h);
}
ColorWindow::ColorWindow(int x, int y, int w, int h)
: ColorWindow(Color::transparent, x, y, w, h)
{
}
ColorWindow::ColorWindow(Color clr, int x, int y, int w, int h)
: _color(clr), _x(x), _y(y), _width(w), _height(h)
{
}
void ColorWindow::blit(Image &fb)
{
Color m = _color;
if (!m) return;
int stride = fb.width();
auto dst = fb.buffer().begin() + (_y * stride + _x);
int y;
for (y = 0; y < _height; ++y)
{
std::transform(dst, dst + _width, dst,
[=](const Color &c) { return c + m; });
dst += stride;
}
}
bool ColorWindow::hasColor() const
{
return static_cast<bool>(_color);
}
bool ColorWindow::fade(int n/* = 1*/)
{
return static_cast<bool>(_color -= Color(n, n, n));
}
void ColorWindow::flash(Color clr)
{
_color += clr;
}
FadeWindow::FadeWindow(int x, int y, int w, int h)
: _x(x), _y(y), _width(w), _height(h)
{
}
void FadeWindow::blit(Image &fb)
{
Color m = _color;
if (!m) return;
int stride = fb.width();
auto dst = fb.buffer().begin() + (_y * stride + _x);
int y;
for (y = 0; y < _height; ++y)
{
std::transform(dst, dst + _width, dst,
[=](const Color &c) { return c - m; });
dst += stride;
}
}
bool FadeWindow::hasColor() const
{
return static_cast<bool>(_color);
}
bool FadeWindow::fadeOut(int n/* = 1*/)
{
return (_color += Color(n, n, n)).getR() >= S_MAXCLR;
}
bool FadeWindow::fadeIn(int n/* = 1*/)
{
return !static_cast<bool>(_color -= Color(n, n, n));
}
| 29.048458 | 81 | 0.523961 | [
"transform"
] |
a07441d434d27450233761407d26cfe30ace518f | 9,010 | cpp | C++ | src/render/opengl/shaders/sphere_shaders.cpp | nyorem/polyscope | 320b0ec454723a8df1965f6b1f37fbf361282477 | [
"MIT"
] | 1 | 2020-05-17T17:22:03.000Z | 2020-05-17T17:22:03.000Z | src/render/opengl/shaders/sphere_shaders.cpp | nyorem/polyscope | 320b0ec454723a8df1965f6b1f37fbf361282477 | [
"MIT"
] | null | null | null | src/render/opengl/shaders/sphere_shaders.cpp | nyorem/polyscope | 320b0ec454723a8df1965f6b1f37fbf361282477 | [
"MIT"
] | null | null | null | #include "polyscope/render/opengl/shaders/sphere_shaders.h"
namespace polyscope {
namespace render {
namespace backend_openGL3_glfw {
// clang-format off
const ShaderStageSpecification FLEX_SPHERE_VERT_SHADER = {
ShaderStageType::Vertex,
// uniforms
{
{"u_modelView", DataType::Matrix44Float},
},
// attributes
{
{"a_position", DataType::Vector3Float},
},
{}, // textures
// source
R"(
${ GLSL_VERSION }$
in vec3 a_position;
uniform mat4 u_modelView;
${ VERT_DECLARATIONS }$
void main()
{
gl_Position = u_modelView * vec4(a_position, 1.0);
${ VERT_ASSIGNMENTS }$
}
)"
};
const ShaderStageSpecification FLEX_SPHERE_GEOM_SHADER = {
ShaderStageType::Geometry,
// uniforms
{
{"u_projMatrix", DataType::Matrix44Float},
{"u_pointRadius", DataType::Float},
},
// attributes
{
},
{}, // textures
// source
R"(
${ GLSL_VERSION }$
layout(points) in;
layout(triangle_strip, max_vertices=4) out;
in vec4 position_tip[];
uniform mat4 u_projMatrix;
uniform float u_pointRadius;
out vec3 sphereCenterView;
${ GEOM_DECLARATIONS }$
void buildTangentBasis(vec3 unitNormal, out vec3 basisX, out vec3 basisY);
void main() {
float pointRadius = u_pointRadius;
${ SPHERE_SET_POINT_RADIUS_GEOM }$
// Construct the 4 corners of a billboard quad, facing the camera
// Quad is shifted pointRadius toward the camera, otherwise it doesn't actually necessarily
// cover the full sphere due to perspective.
vec3 dirToCam = normalize(-gl_in[0].gl_Position.xyz);
vec3 basisX;
vec3 basisY;
buildTangentBasis(dirToCam, basisX, basisY);
vec4 center = u_projMatrix * (gl_in[0].gl_Position + vec4(dirToCam, 0.) * pointRadius);
vec4 dx = u_projMatrix * (vec4(basisX, 0.) * pointRadius);
vec4 dy = u_projMatrix * (vec4(basisY, 0.) * pointRadius);
vec4 p1 = center - dx - dy;
vec4 p2 = center + dx - dy;
vec4 p3 = center - dx + dy;
vec4 p4 = center + dx + dy;
// Other data to emit
vec3 sphereCenterViewVal = gl_in[0].gl_Position.xyz / gl_in[0].gl_Position.w;
// Emit the vertices as a triangle strip
${ GEOM_PER_EMIT }$ sphereCenterView = sphereCenterViewVal; gl_Position = p1; EmitVertex();
${ GEOM_PER_EMIT }$ sphereCenterView = sphereCenterViewVal; gl_Position = p2; EmitVertex();
${ GEOM_PER_EMIT }$ sphereCenterView = sphereCenterViewVal; gl_Position = p3; EmitVertex();
${ GEOM_PER_EMIT }$ sphereCenterView = sphereCenterViewVal; gl_Position = p4; EmitVertex();
EndPrimitive();
}
)"
};
const ShaderStageSpecification FLEX_SPHERE_FRAG_SHADER = {
ShaderStageType::Fragment,
// uniforms
{
{"u_projMatrix", DataType::Matrix44Float},
{"u_invProjMatrix", DataType::Matrix44Float},
{"u_viewport", DataType::Vector4Float},
{"u_pointRadius", DataType::Float},
},
{ }, // attributes
// textures
{
},
// source
R"(
${ GLSL_VERSION }$
uniform mat4 u_projMatrix;
uniform mat4 u_invProjMatrix;
uniform vec4 u_viewport;
uniform float u_pointRadius;
in vec3 sphereCenterView;
layout(location = 0) out vec4 outputF;
float LARGE_FLOAT();
vec3 lightSurfaceMat(vec3 normal, vec3 color, sampler2D t_mat_r, sampler2D t_mat_g, sampler2D t_mat_b, sampler2D t_mat_k);
vec3 fragmentViewPosition(vec4 viewport, vec2 depthRange, mat4 invProjMat, vec4 fragCoord);
bool raySphereIntersection(vec3 rayStart, vec3 rayDir, vec3 sphereCenter, float sphereRad, out float tHit, out vec3 pHit, out vec3 nHit);
float fragDepthFromView(mat4 projMat, vec2 depthRange, vec3 viewPoint);
${ FRAG_DECLARATIONS }$
void main()
{
// Build a ray corresponding to this fragment
vec2 depthRange = vec2(gl_DepthRange.near, gl_DepthRange.far);
vec3 viewRay = fragmentViewPosition(u_viewport, depthRange, u_invProjMatrix, gl_FragCoord);
float pointRadius = u_pointRadius;
${ SPHERE_SET_POINT_RADIUS_FRAG }$
// Raycast to the sphere
float tHit;
vec3 pHit;
vec3 nHit;
bool hit = raySphereIntersection(vec3(0., 0., 0), viewRay, sphereCenterView, pointRadius, tHit, pHit, nHit);
if(tHit >= LARGE_FLOAT()) {
discard;
}
float depth = fragDepthFromView(u_projMatrix, depthRange, pHit);
${ GLOBAL_FRAGMENT_FILTER }$
// Set depth (expensive!)
gl_FragDepth = depth;
// Shading
${ GENERATE_SHADE_VALUE }$
${ GENERATE_SHADE_COLOR }$
// Lighting
vec3 shadeNormal = nHit;
${ GENERATE_LIT_COLOR }$
// Set alpha
float alphaOut = 1.0;
${ GENERATE_ALPHA }$
// Write output
outputF = vec4(litColor, alphaOut);
}
)"
};
// == Rules
const ShaderReplacementRule SPHERE_PROPAGATE_VALUE (
/* rule name */ "SPHERE_PROPAGATE_VALUE",
{ /* replacement sources */
{"VERT_DECLARATIONS", R"(
in float a_value;
out float a_valueToGeom;
)"},
{"VERT_ASSIGNMENTS", R"(
a_valueToGeom = a_value;
)"},
{"GEOM_DECLARATIONS", R"(
in float a_valueToGeom[];
out float a_valueToFrag;
)"},
{"GEOM_PER_EMIT", R"(
a_valueToFrag = a_valueToGeom[0];
)"},
{"FRAG_DECLARATIONS", R"(
in float a_valueToFrag;
)"},
{"GENERATE_SHADE_VALUE", R"(
float shadeValue = a_valueToFrag;
)"},
},
/* uniforms */ {},
/* attributes */ {
{"a_value", DataType::Float},
},
/* textures */ {}
);
const ShaderReplacementRule SPHERE_PROPAGATE_VALUE2 (
/* rule name */ "SPHERE_PROPAGATE_VALUE2",
{ /* replacement sources */
{"VERT_DECLARATIONS", R"(
in vec2 a_value2;
out vec2 a_value2ToGeom;
)"},
{"VERT_ASSIGNMENTS", R"(
a_value2ToGeom = a_value2;
)"},
{"GEOM_DECLARATIONS", R"(
in vec2 a_value2ToGeom[];
out vec2 a_value2ToFrag;
)"},
{"GEOM_PER_EMIT", R"(
a_value2ToFrag = a_value2ToGeom[0];
)"},
{"FRAG_DECLARATIONS", R"(
in vec2 a_value2ToFrag;
)"},
{"GENERATE_SHADE_VALUE", R"(
vec2 shadeValue2 = a_value2ToFrag;
)"},
},
/* uniforms */ {},
/* attributes */ {
{"a_value2", DataType::Vector2Float},
},
/* textures */ {}
);
const ShaderReplacementRule SPHERE_PROPAGATE_COLOR (
/* rule name */ "SPHERE_PROPAGATE_COLOR",
{ /* replacement sources */
{"VERT_DECLARATIONS", R"(
in vec3 a_color;
out vec3 a_colorToGeom;
)"},
{"VERT_ASSIGNMENTS", R"(
a_colorToGeom = a_color;
)"},
{"GEOM_DECLARATIONS", R"(
in vec3 a_colorToGeom[];
out vec3 a_colorToFrag;
)"},
{"GEOM_PER_EMIT", R"(
a_colorToFrag = a_colorToGeom[0];
)"},
{"FRAG_DECLARATIONS", R"(
in vec3 a_colorToFrag;
)"},
{"GENERATE_SHADE_VALUE", R"(
vec3 shadeColor = a_colorToFrag;
)"},
},
/* uniforms */ {},
/* attributes */ {
{"a_color", DataType::Vector3Float},
},
/* textures */ {}
);
const ShaderReplacementRule SPHERE_VARIABLE_SIZE (
/* rule name */ "SPHERE_VARIABLE_SIZE",
{ /* replacement sources */
{"VERT_DECLARATIONS", R"(
in float a_pointRadius;
out float a_pointRadiusToGeom;
)"},
{"VERT_ASSIGNMENTS", R"(
a_pointRadiusToGeom = a_pointRadius;
)"},
{"GEOM_DECLARATIONS", R"(
in float a_pointRadiusToGeom[];
out float a_pointRadiusToFrag;
)"},
{"GEOM_PER_EMIT", R"(
a_pointRadiusToFrag = a_pointRadiusToGeom[0];
)"},
{"FRAG_DECLARATIONS", R"(
in float a_pointRadiusToFrag;
)"},
{"SPHERE_SET_POINT_RADIUS_GEOM", R"(
pointRadius *= a_pointRadiusToGeom[0];
)"},
{"SPHERE_SET_POINT_RADIUS_FRAG", R"(
pointRadius *= a_pointRadiusToFrag;
)"},
},
/* uniforms */ {},
/* attributes */ {
{"a_pointRadius", DataType::Float},
},
/* textures */ {}
);
// clang-format on
} // namespace backend_openGL3_glfw
} // namespace render
} // namespace polyscope
| 27.723077 | 145 | 0.563596 | [
"geometry",
"render"
] |
a07c9c4ad9b443ba90a2af1838002eb4bf2bd570 | 830 | cpp | C++ | code/fft.cpp | pedroteosousa/caderno | 9d13449df8734dc979d1f66cd4c424b8a7d8cc48 | [
"MIT"
] | null | null | null | code/fft.cpp | pedroteosousa/caderno | 9d13449df8734dc979d1f66cd4c424b8a7d8cc48 | [
"MIT"
] | 4 | 2018-02-06T16:52:39.000Z | 2018-10-13T05:21:24.000Z | code/fft.cpp | pedroteosousa/caderno | 9d13449df8734dc979d1f66cd4c424b8a7d8cc48 | [
"MIT"
] | null | null | null | typedef complex<double> cpx;
const double pi = acos(-1.0);
// DFT if type = 1, IDFT if type = -1
// If you are multiplying, remember to let EACH vector with n >= sum of degrees of both polys
// n is required to be a power of 2
void FFT(vector<cpx> &v, vector<cpx> &ans, int n, int type, int p[]) { // p[n]
assert(!(n & (n - 1))); int i, sz, o; p[0] = 0;
for(i = 1; i < n; i++) p[i] = (p[i >> 1] >> 1) | ((i & 1)? (n >> 1) : 0);
for(i = 0; i < n; i++) ans[i] = v[p[i]];
for(sz = 1; sz < n; sz <<= 1) {
const cpx wn(cos(type * pi / sz), sin(type * pi / sz));
for(o = 0; o < n; o += (sz << 1)) {
cpx w = 1;
for(i = 0; i < sz; i++) {
const cpx u = ans[o + i], t = w * ans[o + sz + i];
ans[o + i] = u + t;
ans[o + i + sz] = u - t;
w *= wn;
}
}
}
if(type == -1) for(i = 0; i < n; i++) ans[i] /= n;
} | 36.086957 | 93 | 0.466265 | [
"vector"
] |
a07e8ec862f2fbcf05be6c9c5013a090100d276f | 1,839 | hpp | C++ | src/terark/io/DataInput_LittleEndian.hpp | rockeet/terark-zip | 3235373d04b7cf5d584259111b3a057c45cc1708 | [
"BSD-3-Clause"
] | 44 | 2020-12-21T05:14:38.000Z | 2022-03-15T11:27:32.000Z | src/terark/io/DataInput_LittleEndian.hpp | rockeet/terark-zip | 3235373d04b7cf5d584259111b3a057c45cc1708 | [
"BSD-3-Clause"
] | 2 | 2020-12-28T10:42:03.000Z | 2021-05-21T07:22:47.000Z | src/terark/io/DataInput_LittleEndian.hpp | rockeet/terark-zip | 3235373d04b7cf5d584259111b3a057c45cc1708 | [
"BSD-3-Clause"
] | 21 | 2020-12-22T09:40:16.000Z | 2021-12-07T18:16:00.000Z | public:
DATA_IO_GEN_LITTLE_ENDIAN_INT_INPUT(short)
DATA_IO_GEN_LITTLE_ENDIAN_INT_INPUT(unsigned short)
DATA_IO_GEN_LITTLE_ENDIAN_INT_INPUT(int)
DATA_IO_GEN_LITTLE_ENDIAN_INT_INPUT(unsigned int)
DATA_IO_GEN_LITTLE_ENDIAN_INT_INPUT(long)
DATA_IO_GEN_LITTLE_ENDIAN_INT_INPUT(unsigned long)
#if defined(BOOST_HAS_LONG_LONG)
DATA_IO_GEN_LITTLE_ENDIAN_INT_INPUT(long long)
DATA_IO_GEN_LITTLE_ENDIAN_INT_INPUT(unsigned long long)
#elif defined(BOOST_HAS_MS_INT64)
DATA_IO_GEN_LITTLE_ENDIAN_INT_INPUT(__int64)
DATA_IO_GEN_LITTLE_ENDIAN_INT_INPUT(unsigned __int64)
#endif
MyType& load(wchar_t* s, size_t n)
{
this->ensureRead(s, sizeof(wchar_t)*n);
#ifdef BOOST_ENDIAN_BIG_BYTE
byte_swap(s, n);
#endif
return *this;
}
#ifndef BOOST_NO_INTRINSIC_WCHAR_T
MyType& operator>>(wchar_t& x)
{
this->ensureRead(&x, sizeof(x));
#ifdef BOOST_ENDIAN_BIG_BYTE
x = byte_swap(x);
#endif
return *this;
}
#endif
template<class T> MyType& operator>>(T& x)
{
DataIO_load_elem(*this, x, DATA_IO_BSWAP_FOR_LITTLE(T)());
return *this;
}
template<class T, int Dim>
MyType& operator>>(T (&x)[Dim])
{
DataIO_load_array(*this, x, Dim, DATA_IO_BSWAP_FOR_LITTLE(T)());
return *this;
}
template<class T>
MyType& operator>>(valvec<T>& x)
{
DataIO_load_vector(*this, (T*)NULL, x, DATA_IO_BSWAP_FOR_LITTLE(T)());
return *this;
}
template<class T, class Alloc>
MyType& operator>>(std::vector<T, Alloc>& x)
{
DataIO_load_vector(*this, (T*)NULL, x, DATA_IO_BSWAP_FOR_LITTLE(T)());
return *this;
}
template<class T>
MyType& load_add(valvec<T>& x) {
DataIO_load_add_vector(*this, (T*)NULL, x, DATA_IO_BSWAP_FOR_LITTLE(T)());
return *this;
}
template<class T, class Alloc>
MyType& load_add(std::vector<T>& x) {
DataIO_load_add_vector(*this, (T*)NULL, x, DATA_IO_BSWAP_FOR_LITTLE(T)());
return *this;
}
| 24.197368 | 76 | 0.745514 | [
"vector"
] |
a08440f204804069ed5971e39b3534729176a822 | 65,579 | cpp | C++ | src/pbaas/pbaas.cpp | DavidLDawes/VerusCoin | 925fe06aac13471fd6dcdce39848d9a9b3f3e9ae | [
"Unlicense"
] | null | null | null | src/pbaas/pbaas.cpp | DavidLDawes/VerusCoin | 925fe06aac13471fd6dcdce39848d9a9b3f3e9ae | [
"Unlicense"
] | null | null | null | src/pbaas/pbaas.cpp | DavidLDawes/VerusCoin | 925fe06aac13471fd6dcdce39848d9a9b3f3e9ae | [
"Unlicense"
] | null | null | null | /********************************************************************
* (C) 2019 Michael Toutonghi
*
* Distributed under the MIT software license, see the accompanying
* file COPYING or http://www.opensource.org/licenses/mit-license.php.
*
* This provides support for PBaaS initialization, notarization, and cross-chain token
* transactions and enabling liquid or non-liquid tokens across the
* Verus ecosystem.
*
*/
#include "pbaas/crosschainrpc.h"
#include "pbaas/pbaas.h"
#include "pbaas/notarization.h"
#include "pbaas/identity.h"
#include "rpc/pbaasrpc.h"
#include "base58.h"
#include "timedata.h"
#include "main.h"
#include "transaction_builder.h"
using namespace std;
CConnectedChains ConnectedChains;
bool IsVerusActive()
{
return (strcmp(ASSETCHAINS_SYMBOL, "VRSC") == 0 || strcmp(ASSETCHAINS_SYMBOL, "VRSCTEST") == 0);
}
// this adds an opret to a mutable transaction and returns the voutnum if it could be added
int32_t AddOpRetOutput(CMutableTransaction &mtx, const CScript &opRetScript)
{
if (opRetScript.IsOpReturn() && opRetScript.size() <= MAX_OP_RETURN_RELAY)
{
CTxOut vOut = CTxOut();
vOut.scriptPubKey = opRetScript;
vOut.nValue = 0;
mtx.vout.push_back(vOut);
return mtx.vout.size() - 1;
}
else
{
return -1;
}
}
// returns a pointer to a base chain object, which can be cast to the
// object type indicated in its objType member
uint256 GetChainObjectHash(const CBaseChainObject &bo)
{
union {
const CChainObject<CBlockHeader> *pNewHeader;
const CChainObject<CTransaction> *pNewTx;
const CChainObject<CMerkleBranch> *pNewProof;
const CChainObject<CHeaderRef> *pNewHeaderRef;
const CChainObject<CPriorBlocksCommitment> *pPriors;
const CChainObject<CReserveTransfer> *pExport;
const CChainObject<CCrossChainProof> *pCrossChainProof;
const CBaseChainObject *retPtr;
};
retPtr = &bo;
switch(bo.objectType)
{
case CHAINOBJ_HEADER:
return pNewHeader->GetHash();
case CHAINOBJ_TRANSACTION:
return pNewTx->GetHash();
case CHAINOBJ_PROOF:
return pNewProof->GetHash();
case CHAINOBJ_HEADER_REF:
return pNewHeaderRef->GetHash();
case CHAINOBJ_PRIORBLOCKS:
return pPriors->GetHash();
case CHAINOBJ_RESERVETRANSFER:
return pExport->GetHash();
case CHAINOBJ_CROSSCHAINPROOF:
return pCrossChainProof->GetHash();
}
return uint256();
}
// used to export coins from one chain to another, if they are not native, they are represented on the other
// chain as tokens
bool ValidateCrossChainExport(struct CCcontract_info *cp, Eval* eval, const CTransaction &tx, uint32_t nIn, bool fulfilled)
{
return true;
}
bool IsCrossChainExportInput(const CScript &scriptSig)
{
return true;
}
// used to validate import of coins from one chain to another. if they are not native and are supported,
// they are represented o the chain as tokens
bool ValidateCrossChainImport(struct CCcontract_info *cp, Eval* eval, const CTransaction &tx, uint32_t nIn, bool fulfilled)
{
return true;
}
bool IsCrossChainImportInput(const CScript &scriptSig)
{
return true;
}
// used to validate a specific service reward based on the spending transaction
bool ValidateServiceReward(struct CCcontract_info *cp, Eval* eval, const CTransaction &tx, uint32_t nIn, bool fulfilled)
{
// for each type of service reward, we need to check and see if the spender is
// correctly formatted to be a valid spend of the service reward. for notarization
// we ensure that the notarization and its outputs are valid and that the spend
// applies to the correct billing period
return true;
}
bool IsServiceRewardInput(const CScript &scriptSig)
{
return true;
}
// used as a proxy token output for a reserve currency on its fractional reserve chain
bool ValidateReserveOutput(struct CCcontract_info *cp, Eval* eval, const CTransaction &tx, uint32_t nIn, bool fulfilled)
{
return true;
}
bool IsReserveOutputInput(const CScript &scriptSig)
{
return true;
}
bool ValidateReserveTransfer(struct CCcontract_info *cp, Eval* eval, const CTransaction &tx, uint32_t nIn, bool fulfilled)
{
return true;
}
bool IsReserveTransferInput(const CScript &scriptSig)
{
return true;
}
bool ValidateReserveDeposit(struct CCcontract_info *cp, Eval* eval, const CTransaction &tx, uint32_t nIn, bool fulfilled)
{
return true;
}
bool IsReserveDepositInput(const CScript &scriptSig)
{
return true;
}
bool ValidateCurrencyState(struct CCcontract_info *cp, Eval* eval, const CTransaction &tx, uint32_t nIn, bool fulfilled)
{
return true;
}
bool IsCurrencyStateInput(const CScript &scriptSig)
{
return true;
}
// used to convert a fractional reserve currency into its reserve and back
bool ValidateReserveExchange(struct CCcontract_info *cp, Eval* eval, const CTransaction &tx, uint32_t nIn, bool fulfilled)
{
return true;
}
bool IsReserveExchangeInput(const CScript &scriptSig)
{
return true;
}
/*
* Verifies that the input objects match the hashes and returns the transaction.
*
* If the opRetTx has the op ret, this calculates based on the actual transaction and
* validates the hashes. If the opRetTx does not have the opRet itself, this validates
* by ensuring that all objects are present on this chain, composing the opRet, and
* ensuring that the transaction then hashes to the correct txid.
*
*/
bool ValidateOpretProof(CScript &opRet, COpRetProof &orProof)
{
// enumerate through the objects and validate that they are objects of the expected type that hash
// to the value expected. return true if so
return true;
}
int8_t ObjTypeCode(const CBlockHeader &obj)
{
return CHAINOBJ_HEADER;
}
int8_t ObjTypeCode(const CMerkleBranch &obj)
{
return CHAINOBJ_PROOF;
}
int8_t ObjTypeCode(const CTransaction &obj)
{
return CHAINOBJ_TRANSACTION;
}
int8_t ObjTypeCode(const CHeaderRef &obj)
{
return CHAINOBJ_HEADER_REF;
}
int8_t ObjTypeCode(const CPriorBlocksCommitment &obj)
{
return CHAINOBJ_PRIORBLOCKS;
}
int8_t ObjTypeCode(const CReserveTransfer &obj)
{
return CHAINOBJ_RESERVETRANSFER;
}
int8_t ObjTypeCode(const CCrossChainProof &obj)
{
return CHAINOBJ_CROSSCHAINPROOF;
}
// this adds an opret to a mutable transaction that provides the necessary evidence of a signed, cheating stake transaction
CScript StoreOpRetArray(std::vector<CBaseChainObject *> &objPtrs)
{
CScript vData;
CDataStream s = CDataStream(SER_NETWORK, PROTOCOL_VERSION);
s << (int32_t)OPRETTYPE_OBJECTARR;
bool error = false;
for (auto pobj : objPtrs)
{
try
{
if (!DehydrateChainObject(s, pobj))
{
error = true;
break;
}
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
error = true;
break;
}
}
//std::vector<unsigned char> schars(s.begin(), s.begin() + 200);
//printf("stream vector chars: %s\n", HexBytes(&schars[0], schars.size()).c_str());
std::vector<unsigned char> vch(s.begin(), s.end());
return error ? CScript() : CScript() << OP_RETURN << vch;
}
void DeleteOpRetObjects(std::vector<CBaseChainObject *> &ora)
{
for (auto pobj : ora)
{
switch(pobj->objectType)
{
case CHAINOBJ_HEADER:
{
delete (CChainObject<CBlockHeader> *)pobj;
break;
}
case CHAINOBJ_TRANSACTION:
{
delete (CChainObject<CTransaction> *)pobj;
break;
}
case CHAINOBJ_PROOF:
{
delete (CChainObject<CMerkleBranch> *)pobj;
break;
}
case CHAINOBJ_HEADER_REF:
{
delete (CChainObject<CHeaderRef> *)pobj;
break;
}
case CHAINOBJ_PRIORBLOCKS:
{
delete (CChainObject<CPriorBlocksCommitment> *)pobj;
break;
}
case CHAINOBJ_RESERVETRANSFER:
{
delete (CChainObject<CReserveTransfer> *)pobj;
break;
}
case CHAINOBJ_CROSSCHAINPROOF:
{
delete (CChainObject<CCrossChainProof> *)pobj;
break;
}
default:
delete pobj;
}
}
ora.clear();
}
std::vector<CBaseChainObject *> RetrieveOpRetArray(const CScript &opRetScript)
{
std::vector<unsigned char> vch;
std::vector<CBaseChainObject *> vRet;
if (opRetScript.IsOpReturn() && GetOpReturnData(opRetScript, vch) && vch.size() > 0)
{
CDataStream s = CDataStream(vch, SER_NETWORK, PROTOCOL_VERSION);
int32_t opRetType;
try
{
s >> opRetType;
if (opRetType == OPRETTYPE_OBJECTARR)
{
CBaseChainObject *pobj;
while (!s.empty() && (pobj = RehydrateChainObject(s)))
{
vRet.push_back(pobj);
}
if (!s.empty())
{
printf("failed to load all objects in opret");
DeleteOpRetObjects(vRet);
vRet.clear();
}
}
}
catch(const std::exception& e)
{
std::cerr << e.what() << '\n';
DeleteOpRetObjects(vRet);
vRet.clear();
}
}
return vRet;
}
CNodeData::CNodeData(UniValue &obj)
{
networkAddress = uni_get_str(find_value(obj, "networkaddress"));
CBitcoinAddress ba(uni_get_str(find_value(obj, "paymentaddress")));
ba.GetKeyID(paymentAddress);
}
UniValue CNodeData::ToUniValue() const
{
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("networkaddress", networkAddress));
obj.push_back(Pair("paymentaddress", CBitcoinAddress(paymentAddress).ToString()));
return obj;
}
CPBaaSChainDefinition::CPBaaSChainDefinition(const UniValue &obj)
{
nVersion = PBAAS_VERSION;
name = std::string(uni_get_str(find_value(obj, "name")), 0, (KOMODO_ASSETCHAIN_MAXLEN - 1));
string invalidChars = "\\/:*?\"<>|";
for (int i = 0; i < name.size(); i++)
{
if (invalidChars.find(name[i]) != string::npos)
{
name[i] = '_';
}
}
CBitcoinAddress ba(uni_get_str(find_value(obj, "paymentaddress")));
ba.GetKeyID(address);
premine = uni_get_int64(find_value(obj, "premine"));
initialcontribution = uni_get_int64(find_value(obj, "initialcontribution"));
conversion = uni_get_int64(find_value(obj, "conversion"));
minpreconvert = uni_get_int64(find_value(obj, "minpreconvert"));
maxpreconvert = uni_get_int64(find_value(obj, "maxpreconvert"));
preconverted = uni_get_int64(find_value(obj, "preconverted"));
launchFee = uni_get_int64(find_value(obj, "launchfee"));
startBlock = uni_get_int(find_value(obj, "startblock"));
endBlock = uni_get_int(find_value(obj, "endblock"));
auto vEras = uni_getValues(find_value(obj, "eras"));
if (vEras.size() > ASSETCHAINS_MAX_ERAS)
{
vEras.resize(ASSETCHAINS_MAX_ERAS);
}
for (auto era : vEras)
{
rewards.push_back(uni_get_int64(find_value(era, "reward")));
rewardsDecay.push_back(uni_get_int64(find_value(era, "decay")));
halving.push_back(uni_get_int64(find_value(era, "halving")));
eraEnd.push_back(uni_get_int64(find_value(era, "eraend")));
eraOptions.push_back(uni_get_int64(find_value(era, "eraoptions")));
}
billingPeriod = uni_get_int(find_value(obj, "billingperiod"));
notarizationReward = uni_get_int64(find_value(obj, "notarizationreward"));
auto nodeVec = uni_getValues(find_value(obj, "nodes"));
for (auto node : nodeVec)
{
nodes.push_back(CNodeData(node));
}
}
CPBaaSChainDefinition::CPBaaSChainDefinition(const CTransaction &tx, bool validate)
{
bool definitionFound = false;
nVersion = PBAAS_VERSION_INVALID;
for (auto out : tx.vout)
{
COptCCParams p;
if (IsPayToCryptoCondition(out.scriptPubKey, p))
{
if (p.evalCode == EVAL_PBAASDEFINITION)
{
if (definitionFound)
{
nVersion = PBAAS_VERSION_INVALID;
}
else
{
FromVector(p.vData[0], *this);
definitionFound = true;
}
}
}
}
if (validate)
{
}
}
CServiceReward::CServiceReward(const CTransaction &tx, bool validate)
{
nVersion = PBAAS_VERSION_INVALID;
for (auto out : tx.vout)
{
COptCCParams p;
if (IsPayToCryptoCondition(out.scriptPubKey, p))
{
// always take the first for now
if (p.evalCode == EVAL_SERVICEREWARD)
{
FromVector(p.vData[0], *this);
break;
}
}
}
if (validate)
{
}
}
CCrossChainExport::CCrossChainExport(const CTransaction &tx)
{
for (auto out : tx.vout)
{
COptCCParams p;
if (IsPayToCryptoCondition(out.scriptPubKey, p))
{
// always take the first for now
if (p.evalCode == EVAL_CROSSCHAIN_EXPORT)
{
FromVector(p.vData[0], *this);
break;
}
}
}
}
uint160 CPBaaSChainDefinition::GetChainID(std::string name)
{
uint160 parent;
return CIdentity::GetID(name, parent);
}
uint160 CPBaaSChainDefinition::GetConditionID(int32_t condition) const
{
return CCrossChainRPCData::GetConditionID(name, condition);
}
UniValue CPBaaSChainDefinition::ToUniValue() const
{
UniValue obj(UniValue::VOBJ);
obj.push_back(Pair("version", (int64_t)nVersion));
obj.push_back(Pair("name", name));
obj.push_back(Pair("chainid", GetChainID().GetHex()));
obj.push_back(Pair("chainaddress", EncodeDestination(CTxDestination(CKeyID(GetChainID())))));
obj.push_back(Pair("paymentaddress", EncodeDestination(CTxDestination(address))));
obj.push_back(Pair("premine", (int64_t)premine));
obj.push_back(Pair("initialcontribution", (int64_t)initialcontribution));
obj.push_back(Pair("conversion", (int64_t)conversion));
obj.push_back(Pair("minpreconvert", (int64_t)minpreconvert));
obj.push_back(Pair("maxpreconvert", (int64_t)maxpreconvert));
obj.push_back(Pair("preconverted", (int64_t)preconverted));
obj.push_back(Pair("launchfee", (int64_t)launchFee));
obj.push_back(Pair("conversionpercent", ValueFromAmount(conversion * 100)));
obj.push_back(Pair("launchfeepercent", ValueFromAmount(launchFee * 100)));
obj.push_back(Pair("startblock", (int32_t)startBlock));
obj.push_back(Pair("endblock", (int32_t)endBlock));
UniValue eraArr(UniValue::VARR);
for (int i = 0; i < rewards.size(); i++)
{
UniValue era(UniValue::VOBJ);
era.push_back(Pair("reward", rewards.size() > i ? rewards[i] : (int64_t)0));
era.push_back(Pair("decay", rewardsDecay.size() > i ? rewardsDecay[i] : (int64_t)0));
era.push_back(Pair("halving", halving.size() > i ? (int32_t)halving[i] : (int32_t)0));
era.push_back(Pair("eraend", eraEnd.size() > i ? (int32_t)eraEnd[i] : (int32_t)0));
era.push_back(Pair("eraoptions", eraOptions.size() > i ? (int32_t)eraOptions[i] : (int32_t)0));
eraArr.push_back(era);
}
obj.push_back(Pair("eras", eraArr));
obj.push_back(Pair("billingperiod", billingPeriod));
obj.push_back(Pair("notarizationreward", notarizationReward));
UniValue nodeArr(UniValue::VARR);
for (auto node : nodes)
{
nodeArr.push_back(node.ToUniValue());
}
obj.push_back(Pair("nodes", nodeArr));
return obj;
}
int CPBaaSChainDefinition::GetDefinedPort() const
{
int port;
string host;
for (auto node : nodes)
{
SplitHostPort(node.networkAddress, port, host);
if (port)
{
return port;
}
}
return 0;
}
#define _ASSETCHAINS_TIMELOCKOFF 0xffffffffffffffff
extern uint64_t ASSETCHAINS_TIMELOCKGTE, ASSETCHAINS_TIMEUNLOCKFROM, ASSETCHAINS_TIMEUNLOCKTO;
extern int64_t ASSETCHAINS_SUPPLY, ASSETCHAINS_REWARD[3], ASSETCHAINS_DECAY[3], ASSETCHAINS_HALVING[3], ASSETCHAINS_ENDSUBSIDY[3], ASSETCHAINS_ERAOPTIONS[3];
extern int32_t PBAAS_STARTBLOCK, PBAAS_ENDBLOCK, ASSETCHAINS_LWMAPOS;
extern uint32_t ASSETCHAINS_ALGO, ASSETCHAINS_VERUSHASH, ASSETCHAINS_LASTERA;
extern std::string VERUS_CHAINNAME;
// adds the chain definition for this chain and nodes as well
// this also sets up the notarization chain, if there is one
bool SetThisChain(UniValue &chainDefinition)
{
ConnectedChains.ThisChain() = CPBaaSChainDefinition(chainDefinition);
if (!IsVerusActive())
{
CPBaaSChainDefinition ¬aryChainDef = ConnectedChains.notaryChain.chainDefinition;
// we set the notary chain to either Verus or VerusTest
notaryChainDef.nVersion = PBAAS_VERSION;
if (PBAAS_TESTMODE)
{
// setup Verus test parameters
notaryChainDef.name = "VRSCTEST";
notaryChainDef.premine = 5000000000000000;
notaryChainDef.rewards = std::vector<int64_t>({2400000000});
notaryChainDef.rewardsDecay = std::vector<int64_t>({0});
notaryChainDef.halving = std::vector<int32_t>({225680});
notaryChainDef.eraEnd = std::vector<int32_t>({0});
notaryChainDef.eraOptions = std::vector<int32_t>({notaryChainDef.OPTION_ID_REFERRALS});
}
else
{
// first setup Verus parameters
notaryChainDef.name = "VRSC";
notaryChainDef.premine = 0;
notaryChainDef.rewards = std::vector<int64_t>({0,38400000000,2400000000});
notaryChainDef.rewardsDecay = std::vector<int64_t>({100000000,0,0});
notaryChainDef.halving = std::vector<int32_t>({1,43200,1051920});
notaryChainDef.eraEnd = std::vector<int32_t>({10080,226080,0});
notaryChainDef.eraOptions = std::vector<int32_t>({notaryChainDef.OPTION_ID_REFERRALS,0,0});
}
}
if (ConnectedChains.ThisChain().IsValid())
{
memset(ASSETCHAINS_SYMBOL, 0, sizeof(ASSETCHAINS_SYMBOL));
strcpy(ASSETCHAINS_SYMBOL, ConnectedChains.ThisChain().name.c_str());
// set all command line parameters into mapArgs from chain definition
vector<string> nodeStrs;
for (auto node : ConnectedChains.ThisChain().nodes)
{
nodeStrs.push_back(node.networkAddress);
}
if (nodeStrs.size())
{
mapMultiArgs["-seednode"] = nodeStrs;
}
if (int port = ConnectedChains.ThisChain().GetDefinedPort())
{
mapArgs["-port"] = to_string(port);
}
ASSETCHAINS_SUPPLY = ConnectedChains.ThisChain().premine;
mapArgs["-ac_supply"] = to_string(ASSETCHAINS_SUPPLY);
ASSETCHAINS_ALGO = ASSETCHAINS_VERUSHASH;
ASSETCHAINS_LWMAPOS = 50;
ASSETCHAINS_TIMELOCKGTE = _ASSETCHAINS_TIMELOCKOFF;
ASSETCHAINS_TIMEUNLOCKFROM = 0;
ASSETCHAINS_TIMEUNLOCKTO = 0;
auto numEras = ConnectedChains.ThisChain().rewards.size();
ASSETCHAINS_LASTERA = numEras - 1;
mapArgs["-ac_eras"] = to_string(numEras);
mapArgs["-ac_end"] = "";
mapArgs["-ac_reward"] = "";
mapArgs["-ac_halving"] = "";
mapArgs["-ac_decay"] = "";
mapArgs["-ac_options"] = "";
for (int j = 0; j < ASSETCHAINS_MAX_ERAS; j++)
{
if (j > ASSETCHAINS_LASTERA)
{
ASSETCHAINS_REWARD[j] = ASSETCHAINS_REWARD[j-1];
ASSETCHAINS_DECAY[j] = ASSETCHAINS_DECAY[j-1];
ASSETCHAINS_HALVING[j] = ASSETCHAINS_HALVING[j-1];
ASSETCHAINS_ENDSUBSIDY[j] = 0;
ASSETCHAINS_ERAOPTIONS[j] = 0;
}
else
{
ASSETCHAINS_REWARD[j] = ConnectedChains.ThisChain().rewards[j];
ASSETCHAINS_DECAY[j] = ConnectedChains.ThisChain().rewardsDecay[j];
ASSETCHAINS_HALVING[j] = ConnectedChains.ThisChain().halving[j];
ASSETCHAINS_ENDSUBSIDY[j] = ConnectedChains.ThisChain().eraEnd[j];
ASSETCHAINS_ERAOPTIONS[j] = ConnectedChains.ThisChain().eraOptions[j];
if (j == 0)
{
mapArgs["-ac_reward"] = to_string(ASSETCHAINS_REWARD[j]);
mapArgs["-ac_decay"] = to_string(ASSETCHAINS_DECAY[j]);
mapArgs["-ac_halving"] = to_string(ASSETCHAINS_HALVING[j]);
mapArgs["-ac_end"] = to_string(ASSETCHAINS_ENDSUBSIDY[j]);
mapArgs["-ac_options"] = to_string(ASSETCHAINS_ERAOPTIONS[j]);
}
else
{
mapArgs["-ac_reward"] += "," + to_string(ASSETCHAINS_REWARD[j]);
mapArgs["-ac_decay"] += "," + to_string(ASSETCHAINS_DECAY[j]);
mapArgs["-ac_halving"] += "," + to_string(ASSETCHAINS_HALVING[j]);
mapArgs["-ac_end"] += "," + to_string(ASSETCHAINS_ENDSUBSIDY[j]);
mapArgs["-ac_options"] += "," + to_string(ASSETCHAINS_ERAOPTIONS[j]);
}
}
}
PBAAS_STARTBLOCK = ConnectedChains.ThisChain().startBlock;
mapArgs["-startblock"] = to_string(PBAAS_STARTBLOCK);
PBAAS_ENDBLOCK = ConnectedChains.ThisChain().endBlock;
mapArgs["-endblock"] = to_string(PBAAS_ENDBLOCK);
PBAAS_PRECONVERSION = ConnectedChains.ThisChain().conversion;
PBAAS_MINPRECONVERT = ConnectedChains.ThisChain().minpreconvert;
PBAAS_MAXPRECONVERT = ConnectedChains.ThisChain().maxpreconvert;
mapArgs["-ac_conversion"] = to_string(PBAAS_PRECONVERSION);
mapArgs["-ac_minpreconvert"] = to_string(PBAAS_MINPRECONVERT);
mapArgs["-ac_maxpreconvert"] = to_string(PBAAS_MAXPRECONVERT);
return true;
}
else
{
return false;
}
}
// ensures that the chain definition is valid and that there are no other definitions of the same name
// that have been confirmed.
bool ValidateChainDefinition(struct CCcontract_info *cp, Eval* eval, const CTransaction &tx, uint32_t nIn, bool fulfilled)
{
// the chain definition output can be spent when the chain is at the end of its life and only then
// TODO
return false;
}
// ensures that the chain definition is valid and that there are no other definitions of the same name
// that have been confirmed.
bool CheckChainDefinitionOutput(struct CCcontract_info *cp, Eval* eval, const CTransaction &tx, uint32_t nIn)
{
// checked before a chain definition output script is accepted as a valid transaction
// basics - we need a chain definition transaction to kick off a PBaaS chain. it must have:
// 1) valid chain definition output with parameters in proper ranges and no duplicate name
// 2) notarization output with conformant values
// 3) finalization output
// 3) notarization funding
//
// get the source transaction
uint256 blkHash;
CTransaction thisTx;
if (!GetTransaction(tx.vin[nIn].prevout.hash, thisTx, blkHash))
{
LogPrintf("failed to retrieve transaction %s\n", tx.vin[nIn].prevout.hash.GetHex().c_str());
return false;
}
CPBaaSChainDefinition chainDef(thisTx, true);
CPBaaSNotarization notarization(thisTx, true);
CNotarizationFinalization finalization(thisTx, true);
if (!chainDef.IsValid() || !notarization.IsValid() || finalization.IsValid())
{
LogPrintf("transaction specified, %s, must have valid chain definition, notarization, and finaization outputs\n", tx.vin[nIn].prevout.hash.GetHex().c_str());
return false;
}
CPBaaSChainDefinition prior;
// this ensures that there is no other definition of the same name already on the blockchain
if (!GetChainDefinition(chainDef.name, prior))
{
LogPrintf("PBaaS chain with the name %s already exists\n", chainDef.name.c_str());
return false;
}
return true;
}
CAmount CCrossChainExport::CalculateExportFee() const
{
if (numInputs > MAX_EXPORT_INPUTS)
{
return 0;
}
static const arith_uint256 satoshis(100000000);
int64_t ratio = 50000000 + ((25000000 / MAX_EXPORT_INPUTS) * (numInputs - 1));
return (((arith_uint256(totalFees) * arith_uint256(ratio))) / satoshis).GetLow64();
}
bool CConnectedChains::RemoveMergedBlock(uint160 chainID)
{
bool retval = false;
LOCK(cs_mergemining);
//printf("RemoveMergedBlock ID: %s\n", chainID.GetHex().c_str());
auto chainIt = mergeMinedChains.find(chainID);
if (chainIt != mergeMinedChains.end())
{
arith_uint256 target;
target.SetCompact(chainIt->second.block.nBits);
for (auto removeRange = mergeMinedTargets.equal_range(target); removeRange.first != removeRange.second; removeRange.first++)
{
// make sure we don't just match by target
if (removeRange.first->second->GetChainID() == chainID)
{
mergeMinedTargets.erase(removeRange.first);
break;
}
}
mergeMinedChains.erase(chainID);
dirty = retval = true;
// if we get to 0, give the thread a kick to stop waiting for mining
//if (!mergeMinedChains.size())
//{
// sem_submitthread.post();
//}
}
return retval;
}
// remove merge mined chains added and not updated since a specific time
void CConnectedChains::PruneOldChains(uint32_t pruneBefore)
{
vector<uint160> toRemove;
LOCK(cs_mergemining);
for (auto blkData : mergeMinedChains)
{
if (blkData.second.block.nTime < pruneBefore)
{
toRemove.push_back(blkData.first);
}
}
for (auto id : toRemove)
{
//printf("Pruning chainID: %s\n", id.GetHex().c_str());
RemoveMergedBlock(id);
}
}
// adds or updates merge mined blocks
// returns false if failed to add
bool CConnectedChains::AddMergedBlock(CPBaaSMergeMinedChainData &blkData)
{
// determine if we should replace one or add to the merge mine vector
{
LOCK(cs_mergemining);
arith_uint256 target;
uint160 cID = blkData.GetChainID();
auto it = mergeMinedChains.find(cID);
if (it != mergeMinedChains.end())
{
RemoveMergedBlock(cID); // remove it if already there
}
target.SetCompact(blkData.block.nBits);
//printf("AddMergedBlock name: %s, ID: %s\n", blkData.chainDefinition.name.c_str(), cID.GetHex().c_str());
mergeMinedTargets.insert(make_pair(target, &(mergeMinedChains.insert(make_pair(cID, blkData)).first->second)));
dirty = true;
}
return true;
}
bool CConnectedChains::GetChainInfo(uint160 chainID, CRPCChainData &rpcChainData)
{
{
LOCK(cs_mergemining);
auto chainIt = mergeMinedChains.find(chainID);
if (chainIt != mergeMinedChains.end())
{
rpcChainData = (CRPCChainData)chainIt->second;
return true;
}
return false;
}
}
// this returns a pointer to the data without copy and assumes the lock is held
CPBaaSMergeMinedChainData *CConnectedChains::GetChainInfo(uint160 chainID)
{
{
auto chainIt = mergeMinedChains.find(chainID);
if (chainIt != mergeMinedChains.end())
{
return &chainIt->second;
}
return NULL;
}
}
void CConnectedChains::QueueNewBlockHeader(CBlockHeader &bh)
{
//printf("QueueNewBlockHeader %s\n", bh.GetHash().GetHex().c_str());
{
LOCK(cs_mergemining);
qualifiedHeaders[UintToArith256(bh.GetHash())] = bh;
}
sem_submitthread.post();
}
// get the latest block header and submit one block at a time, returning after there are no more
// matching blocks to be found
vector<pair<string, UniValue>> CConnectedChains::SubmitQualifiedBlocks()
{
std::set<uint160> inHeader;
bool submissionFound;
CPBaaSMergeMinedChainData chainData;
vector<pair<string, UniValue>> results;
CBlockHeader bh;
arith_uint256 lastHash;
CPBaaSBlockHeader pbh;
do
{
submissionFound = false;
{
LOCK(cs_mergemining);
// attempt to submit with the lowest hash answers first to increase the likelihood of submitting
// common, merge mined headers for notarization, drop out on any submission
for (auto headerIt = qualifiedHeaders.begin(); !submissionFound && headerIt != qualifiedHeaders.end(); headerIt = qualifiedHeaders.begin())
{
// add the PBaaS chain ids from this header to a set for search
for (uint32_t i = 0; headerIt->second.GetPBaaSHeader(pbh, i); i++)
{
inHeader.insert(pbh.chainID);
}
uint160 chainID;
// now look through all targets that are equal to or above the hash of this header
for (auto chainIt = mergeMinedTargets.lower_bound(headerIt->first); !submissionFound && chainIt != mergeMinedTargets.end(); chainIt++)
{
chainID = chainIt->second->GetChainID();
if (inHeader.count(chainID))
{
// first, check that the winning header matches the block that is there
CPBaaSPreHeader preHeader(chainIt->second->block);
preHeader.SetBlockData(headerIt->second);
// check if the block header matches the block's specific data, only then can we create a submission from this block
if (headerIt->second.CheckNonCanonicalData(chainID))
{
// save block as is, remove the block from merged headers, replace header, and submit
chainData = *chainIt->second;
*(CBlockHeader *)&chainData.block = headerIt->second;
submissionFound = true;
}
//else // not an error condition. code is here for debugging
//{
// printf("Mismatch in non-canonical data for chain %s\n", chainIt->second->chainDefinition.name.c_str());
//}
}
//else // not an error condition. code is here for debugging
//{
// printf("Not found in header %s\n", chainIt->second->chainDefinition.name.c_str());
//}
}
// if this header matched no block, discard and move to the next, otherwise, we'll drop through
if (submissionFound)
{
// once it is going to be submitted, remove block from this chain until a new one is added again
RemoveMergedBlock(chainID);
break;
}
else
{
qualifiedHeaders.erase(headerIt);
}
}
}
if (submissionFound)
{
// submit one block and loop again. this approach allows multiple threads
// to collectively empty the submission queue, mitigating the impact of
// any one stalled daemon
UniValue submitParams(UniValue::VARR);
submitParams.push_back(EncodeHexBlk(chainData.block));
UniValue result, error;
try
{
result = RPCCall("submitblock", submitParams, chainData.rpcUserPass, chainData.rpcPort, chainData.rpcHost);
result = find_value(result, "result");
error = find_value(result, "error");
}
catch (exception e)
{
result = UniValue(e.what());
}
results.push_back(make_pair(chainData.chainDefinition.name, result));
if (result.isStr() || !error.isNull())
{
printf("Error submitting block to %s chain: %s\n", chainData.chainDefinition.name.c_str(), result.isStr() ? result.get_str().c_str() : error.get_str().c_str());
}
else
{
printf("Successfully submitted block to %s chain\n", chainData.chainDefinition.name.c_str());
}
}
} while (submissionFound);
return results;
}
// add all merge mined chain PBaaS headers into the blockheader and return the easiest nBits target in the header
uint32_t CConnectedChains::CombineBlocks(CBlockHeader &bh)
{
vector<uint160> inHeader;
vector<UniValue> toCombine;
arith_uint256 blkHash = UintToArith256(bh.GetHash());
arith_uint256 target(0);
CPBaaSBlockHeader pbh;
{
LOCK(cs_mergemining);
CPBaaSSolutionDescriptor descr = CVerusSolutionVector::solutionTools.GetDescriptor(bh.nSolution);
for (uint32_t i = 0; i < descr.numPBaaSHeaders; i++)
{
if (bh.GetPBaaSHeader(pbh, i))
{
inHeader.push_back(pbh.chainID);
}
}
// loop through the existing PBaaS chain ids in the header
// remove any that are not either this Chain ID or in our local collection and then add all that are present
for (uint32_t i = 0; i < inHeader.size(); i++)
{
auto it = mergeMinedChains.find(inHeader[i]);
if (inHeader[i] != ASSETCHAINS_CHAINID && (it == mergeMinedChains.end()))
{
bh.DeletePBaaSHeader(i);
}
}
for (auto chain : mergeMinedChains)
{
// get the native PBaaS header for each chain and put it into the
// header we are given
// it must have itself in as a PBaaS header
uint160 cid = chain.second.GetChainID();
if (chain.second.block.GetPBaaSHeader(pbh, cid) != -1)
{
if (!bh.AddUpdatePBaaSHeader(pbh))
{
LogPrintf("Failure to add PBaaS block header for %s chain\n", chain.second.chainDefinition.name.c_str());
break;
}
else
{
arith_uint256 t;
t.SetCompact(chain.second.block.nBits);
if (t > target)
{
target = t;
}
}
}
else
{
LogPrintf("Merge mined block for %s does not contain PBaaS information\n", chain.second.chainDefinition.name.c_str());
}
}
dirty = false;
}
return target.GetCompact();
}
bool CConnectedChains::IsVerusPBaaSAvailable()
{
return notaryChainVersion >= "0.5.9";
}
extern string PBAAS_HOST, PBAAS_USERPASS;
extern int32_t PBAAS_PORT;
bool CConnectedChains::CheckVerusPBaaSAvailable(UniValue &chainInfoUni, UniValue &chainDefUni)
{
if (chainInfoUni.isObject() && chainDefUni.isObject())
{
UniValue uniVer = find_value(chainInfoUni, "VRSCversion");
if (uniVer.isStr())
{
LOCK(cs_mergemining);
notaryChainVersion = uni_get_str(uniVer);
notaryChainHeight = uni_get_int(find_value(chainInfoUni, "blocks"));
CPBaaSChainDefinition chainDef(chainDefUni);
notaryChain = CRPCChainData(chainDef, PBAAS_HOST, PBAAS_PORT, PBAAS_USERPASS);
}
}
return IsVerusPBaaSAvailable();
}
bool CConnectedChains::CheckVerusPBaaSAvailable()
{
if (IsVerusActive())
{
notaryChainVersion = "";
}
else
{
// if this is a PBaaS chain, poll for presence of Verus / root chain and current Verus block and version number
// tolerate only 15 second timeout
UniValue chainInfo, chainDef;
try
{
UniValue params(UniValue::VARR);
chainInfo = find_value(RPCCallRoot("getinfo", params), "result");
if (!chainInfo.isNull())
{
params.push_back(VERUS_CHAINNAME);
chainDef = find_value(RPCCallRoot("getchaindefinition", params), "result");
if (!chainDef.isNull() && CheckVerusPBaaSAvailable(chainInfo, chainDef))
{
return true;
}
}
} catch (exception e)
{
}
}
notaryChainVersion = "";
return false;
}
CCoinbaseCurrencyState CConnectedChains::GetCurrencyState(int32_t height)
{
CCoinbaseCurrencyState currencyState;
CBlock block;
LOCK(cs_main);
bool isVerusActive = IsVerusActive();
if (!isVerusActive &&
CConstVerusSolutionVector::activationHeight.ActiveVersion(height) >= CActivationHeight::ACTIVATE_PBAAS &&
height != 0 &&
height <= chainActive.Height() &&
chainActive[height] &&
ReadBlockFromDisk(block, chainActive[height], Params().GetConsensus()) &&
(currencyState = CCoinbaseCurrencyState(block.vtx[0])).IsValid())
{
return currencyState;
}
else
{
bool isReserve = (thisChain.ChainOptions() & thisChain.OPTION_RESERVE);
CAmount preconvertedNative = currencyState.ReserveToNative(thisChain.preconverted, thisChain.conversion);
CCurrencyState cState(thisChain.conversion, preconvertedNative, preconvertedNative, 0, isReserve ? thisChain.preconverted : 0, isReserve ? CCurrencyState::VALID + CCurrencyState::ISRESERVE : CCurrencyState::VALID);
CAmount fees = 0;
if (!height && !isVerusActive)
{
fees = CReserveTransactionDescriptor::CalculateAdditionalConversionFee(thisChain.preconverted);
}
return CCoinbaseCurrencyState(cState, thisChain.preconverted, 0, CReserveOutput(CReserveOutput::VALID, 0), thisChain.conversion, fees, fees);
}
}
bool CConnectedChains::SetLatestMiningOutputs(const std::vector<pair<int, CScript>> &minerOutputs, CTxDestination &firstDestinationOut)
{
LOCK(cs_mergemining);
if (!minerOutputs.size() || !ExtractDestination(minerOutputs[0].second, firstDestinationOut))
{
return false;
}
latestMiningOutputs = minerOutputs;
latestDestination = firstDestinationOut;
return true;
}
void CConnectedChains::AggregateChainTransfers(const CTxDestination &feeOutput, uint32_t nHeight)
{
// all chains aggregate reserve transfer transactions, so aggregate and add all necessary export transactions to the mem pool
{
if (!nHeight)
{
return;
}
multimap<uint160, pair<CInputDescriptor, CReserveTransfer>> transferOutputs;
LOCK(cs_main);
// get all available transfer outputs to aggregate into export transactions
if (GetUnspentChainTransfers(transferOutputs))
{
if (!transferOutputs.size())
{
return;
}
std::vector<pair<CInputDescriptor, CReserveTransfer>> txInputs;
std::multimap<uint160, pair<int, CInputDescriptor>> exportOutputs;
uint160 bookEnd;
bookEnd.SetHex("ffffffffffffffffffffffffffffffffffffffff");
uint160 lastChain = bookEnd;
// add a bookend entry at the end of transfer outputs to ensure that we try to export all before it
transferOutputs.insert(make_pair(bookEnd, make_pair(CInputDescriptor(), CReserveTransfer())));
CPBaaSChainDefinition lastChainDef;
// merge all of the common chainID outputs into common export transactions if either MIN_BLOCKS blocks have passed since the last
// export of that type, or there are MIN_INPUTS or more outputs to aggregate
for (auto it = transferOutputs.begin(); it != transferOutputs.end(); it++)
{
// get chain target and see if it is the same
if (lastChain == bookEnd || it->first == lastChain)
{
txInputs.push_back(it->second);
}
else
{
// when we get here, we have a consecutive number of transfer outputs to consume in txInputs
// we need an unspent export output to export
if (GetUnspentChainExports(lastChain, exportOutputs) && exportOutputs.size())
{
auto lastExport = *exportOutputs.begin();
if (((nHeight - lastExport.second.first) >= CCrossChainExport::MIN_BLOCKS) || (txInputs.size() >= CCrossChainExport::MIN_INPUTS))
{
boost::optional<CTransaction> oneExport;
if (!GetChainDefinition(lastChain, lastChainDef))
{
printf("%s: chain definition for export chainID %s not found\n\n", __func__, lastChain.GetHex().c_str());
LogPrintf("%s: chain definition for export chainID %s not found\n\n", __func__, lastChain.GetHex().c_str());
continue;
}
// make one or more transactions that spends the last export and all possible cross chain transfers
while (txInputs.size())
{
TransactionBuilder tb(Params().GetConsensus(), nHeight);
int numInputs = (txInputs.size() < CCrossChainExport::MAX_EXPORT_INPUTS) ? txInputs.size() : CCrossChainExport::MAX_EXPORT_INPUTS;
int inputsLeft = txInputs.size() - numInputs;
if (inputsLeft > 0 && inputsLeft < CCrossChainExport::MIN_INPUTS)
{
inputsLeft += CCrossChainExport::MIN_INPUTS - inputsLeft;
numInputs -= CCrossChainExport::MIN_INPUTS - inputsLeft;
assert(numInputs > 0);
}
// each time through, we make one export transaction with the remainder or a subset of the
// reserve transfer inputs. inputs can be:
// 1. transfers of reserve for fractional reserve chains
// 2. pre-conversions for pre-launch participation in the premine
// 3. reserve market conversions to send between Verus and a fractional reserve chain and always output the native coin
//
// If we are on the Verus chain, all inputs will include native coins. On a PBaaS chain, inputs can either be native
// or reserve token inputs.
//
// On the Verus chain, total native amount, minus the fee, must be sent to the reserve address of the specific chain
// as reserve deposit with native coin equivalent. Pre-conversions and conversions will be realized on the PBaaS chain
// as part of the import process
//
// If we are on the PBaaS chain, conversions must happen before coins are sent this way back to the reserve chain.
// Verus reserve outputs can be directly aggregated and transferred, with fees paid through conversion and the
// remaining Verus reserve coin will be burned on the PBaaS chain as spending it is allowed, once notarized, on the
// Verus chain.
//
CAmount totalTxFees = 0;
CAmount totalAmount = 0;
CAmount exportOutVal = 0;
std::vector<CBaseChainObject *> chainObjects;
// first, we must add the export output from the current export thread to this chain
if (oneExport.has_value())
{
// spend the last export transaction output
CTransaction &tx = oneExport.get();
COptCCParams p;
int j;
for (j = 0; j < tx.vout.size(); j++)
{
if (::IsPayToCryptoCondition(tx.vout[j].scriptPubKey, p) && p.evalCode == EVAL_CROSSCHAIN_EXPORT)
{
break;
}
}
// had to be found and valid if we made the tx
assert(j < tx.vout.size() && p.IsValid());
tb.AddTransparentInput(COutPoint(tx.GetHash(), j), tx.vout[j].scriptPubKey, tx.vout[j].nValue);
exportOutVal = tx.vout[j].nValue;
}
else
{
// spend the recentExportIt output
tb.AddTransparentInput(lastExport.second.second.txIn.prevout, lastExport.second.second.scriptPubKey, lastExport.second.second.nValue);
exportOutVal = lastExport.second.second.nValue;
}
COptCCParams p;
int fails = 0;
for (int j = 0; j < numInputs; j++)
{
tb.AddTransparentInput(txInputs[j].first.txIn.prevout, txInputs[j].first.scriptPubKey, txInputs[j].first.nValue, txInputs[j].first.txIn.nSequence);
if (IsVerusActive() && txInputs[j].second.nValue + txInputs[j].second.nFees > txInputs[j].first.nValue)
{
// if this transfer is invalid and claims to carry more funds than it does, we consume it since it won't properly verify as a transfer, and
// it is too expensive to let it force evaluation repeatedly. this condition should not get by normal checks, but just in case, don't let it slow transfers
// we should formalize this into a chain contribution or amount adjustment.
printf("%s: transaction %s claims more value than it contains\n", __func__, txInputs[j].first.txIn.prevout.hash.GetHex().c_str());
LogPrintf("%s: transaction %s claims more value than it contains\n", __func__, txInputs[j].first.txIn.prevout.hash.GetHex().c_str());
fails++;
}
else
{
totalTxFees += txInputs[j].second.nFees;
totalAmount += txInputs[j].second.nValue;
chainObjects.push_back(new CChainObject<CReserveTransfer>(ObjTypeCode(txInputs[j].second), txInputs[j].second));
}
}
if (fails == numInputs)
{
// erase the inputs we've attempted to spend
txInputs.erase(txInputs.begin(), txInputs.begin() + numInputs);
continue;
}
CCrossChainExport ccx(lastChain, numInputs, totalAmount, totalTxFees);
CAmount exportFees = ccx.CalculateExportFee();
CReserveTransfer feeOut(CReserveTransfer::VALID + CReserveTransfer::SEND_BACK + CReserveTransfer::FEE_OUTPUT, exportFees, 0, GetDestinationID(feeOutput));
chainObjects.push_back(new CChainObject<CReserveTransfer>(ObjTypeCode(feeOut), feeOut));
// do a preliminary check
CReserveTransactionDescriptor rtxd;
std::vector<CTxOut> dummy;
if (!rtxd.AddReserveTransferImportOutputs(lastChainDef, chainObjects, dummy))
{
DeleteOpRetObjects(chainObjects);
printf("%s: failed to create valid exports\n", __func__);
LogPrintf("%s: failed to create valid exports\n", __func__);
// debugging output
printf("%s: failed to export outputs:\n", __func__);
for (auto oneout : dummy)
{
UniValue uniOut;
ScriptPubKeyToJSON(oneout.scriptPubKey, uniOut, false);
printf("%s\n", uniOut.write(true, 2).c_str());
}
}
else
{
// debugging output
printf("%s: exported outputs:\n", __func__);
for (auto oneout : dummy)
{
UniValue uniOut;
ScriptPubKeyToJSON(oneout.scriptPubKey, uniOut, false);
printf("%s\n", uniOut.write(true, 2).c_str());
}
CScript opRet = StoreOpRetArray(chainObjects);
DeleteOpRetObjects(chainObjects);
CCcontract_info CC;
CCcontract_info *cp;
cp = CCinit(&CC, EVAL_CROSSCHAIN_EXPORT);
CPubKey pk = CPubKey(ParseHex(CC.CChexstr));
// send native amount of zero to a cross chain export output of the specific chain
std::vector<CTxDestination> dests = std::vector<CTxDestination>({CKeyID(CCrossChainRPCData::GetConditionID(lastChain, EVAL_CROSSCHAIN_EXPORT))});
CTxOut exportOut = MakeCC1of1Vout(EVAL_CROSSCHAIN_EXPORT, exportOutVal, pk, dests, ccx);
tb.AddTransparentOutput(exportOut.scriptPubKey, exportOutVal);
// if we are on Verus chain, send all native funds to reserve deposit CC, which is equivalent to the reserve account
// if we are on a PBaaS chain, input is burned when sent back for release
if (IsVerusActive())
{
cp = CCinit(&CC, EVAL_RESERVE_DEPOSIT);
pk = CPubKey(ParseHex(CC.CChexstr));
// send the entire amount to a reserve transfer output of the specific chain
// we receive our fee on the other chain or when it comes back
dests = std::vector<CTxDestination>({CKeyID(CCrossChainRPCData::GetConditionID(lastChain, EVAL_RESERVE_DEPOSIT))});
CReserveOutput ro(CReserveOutput::VALID, totalAmount + totalTxFees);
CTxOut outToReserve = MakeCC1of1Vout(EVAL_RESERVE_DEPOSIT,
ro.nValue,
pk,
dests,
ro);
tb.AddTransparentOutput(outToReserve.scriptPubKey, ro.nValue);
}
tb.AddOpRet(opRet);
tb.SetFee(0);
TransactionBuilderResult buildResult(tb.Build());
if (!buildResult.IsError() && buildResult.IsTx())
{
// replace the last one only if we have a valid new one
CTransaction tx = buildResult.GetTxOrThrow();
LOCK2(cs_main, mempool.cs);
static int lastHeight = 0;
// remove conflicts, so that we get in
std::list<CTransaction> removed;
mempool.removeConflicts(tx, removed);
// add to mem pool, prioritize according to the fee we will get, and relay
printf("Created and signed export transaction %s\n", tx.GetHash().GetHex().c_str());
LogPrintf("Created and signed export transaction %s\n", tx.GetHash().GetHex().c_str());
if (myAddtomempool(tx))
{
uint256 hash = tx.GetHash();
mempool.PrioritiseTransaction(hash, hash.GetHex(), (double)(exportFees << 1), exportFees);
RelayTransaction(tx);
}
}
else
{
// we can't do any more useful work for this chain if we failed here
printf("Failed to create export transaction: %s\n", buildResult.GetError().c_str());
LogPrintf("Failed to create export transaction: %s\n", buildResult.GetError().c_str());
break;
}
}
// erase the inputs we've attempted to spend
txInputs.erase(txInputs.begin(), txInputs.begin() + numInputs);
}
}
}
}
lastChain = it->first;
}
}
}
}
// send new imports from this chain to the specified chain, which generally will be the notary chain
void CConnectedChains::SendNewImports(const uint160 &chainID,
const CPBaaSNotarization ¬arization,
const uint256 &lastExportTx,
const CTransaction &lastCrossImport,
const CTransaction &lastExport)
{
// currently only support sending imports to
}
void CConnectedChains::SubmissionThread()
{
try
{
arith_uint256 lastHash;
int64_t lastImportTime = 0;
uint32_t lastHeight = 0;
// wait for something to check on, then submit blocks that should be submitted
while (true)
{
boost::this_thread::interruption_point();
if (IsVerusActive())
{
// blocks get discarded after no refresh for 5 minutes by default, probably should be more often
//printf("SubmissionThread: pruning\n");
PruneOldChains(GetAdjustedTime() - 300);
bool submit = false;
{
LOCK(cs_mergemining);
if (mergeMinedChains.size() == 0 && qualifiedHeaders.size() != 0)
{
qualifiedHeaders.clear();
}
submit = qualifiedHeaders.size() != 0 && mergeMinedChains.size() != 0;
//printf("SubmissionThread: qualifiedHeaders.size(): %lu, mergeMinedChains.size(): %lu\n", qualifiedHeaders.size(), mergeMinedChains.size());
}
if (submit)
{
//printf("SubmissionThread: calling submit qualified blocks\n");
SubmitQualifiedBlocks();
}
else
{
//printf("SubmissionThread: waiting on sem\n");
sem_submitthread.wait();
}
}
else
{
// if this is a PBaaS chain, poll for presence of Verus / root chain and current Verus block and version number
if (CheckVerusPBaaSAvailable())
{
// check to see if we have recently earned a block with an earned notarization that qualifies for
// submitting an accepted notarization
if (earnedNotarizationHeight)
{
CBlock blk;
int32_t txIndex = -1, height;
{
LOCK(cs_mergemining);
if (earnedNotarizationHeight && earnedNotarizationHeight <= chainActive.Height() && earnedNotarizationBlock.GetHash() == chainActive[earnedNotarizationHeight]->GetBlockHash())
{
blk = earnedNotarizationBlock;
earnedNotarizationBlock = CBlock();
txIndex = earnedNotarizationIndex;
height = earnedNotarizationHeight;
earnedNotarizationHeight = 0;
}
}
if (txIndex != -1)
{
//printf("SubmissionThread: testing notarization\n");
CTransaction lastConfirmed;
uint256 txId = CreateAcceptedNotarization(blk, txIndex, height);
if (!txId.IsNull())
{
printf("Submitted notarization for acceptance: %s\n", txId.GetHex().c_str());
LogPrintf("Submitted notarization for acceptance: %s\n", txId.GetHex().c_str());
}
}
}
// every "n" seconds, look for imports to include in our blocks from the Verus chain
if ((GetAdjustedTime() - lastImportTime) >= 30 || lastHeight < (chainActive.LastTip() ? 0 : chainActive.LastTip()->GetHeight()))
{
lastImportTime = GetAdjustedTime();
lastHeight = (chainActive.LastTip() ? 0 : chainActive.LastTip()->GetHeight());
// see if our notary has a confirmed notarization for us
UniValue params(UniValue::VARR);
UniValue result;
params.push_back(thisChain.name);
try
{
result = find_value(RPCCallRoot("getlastimportin", params), "result");
} catch (exception e)
{
result = NullUniValue;
}
if (!result.isNull())
{
auto txUniStr = find_value(result, "lastimporttransaction");
auto txLastConfirmedStr = find_value(result, "lastconfirmednotarization");
auto txTemplateStr = find_value(result, "importtxtemplate");
CAmount totalImportAvailable = uni_get_int64(find_value(result, "totalimportavailable"));
CTransaction lastImportTx, lastConfirmedTx, templateTx;
if (txUniStr.isStr() && txTemplateStr.isStr() &&
DecodeHexTx(lastImportTx, txUniStr.get_str()) &&
DecodeHexTx(lastConfirmedTx, txLastConfirmedStr.get_str()) &&
DecodeHexTx(templateTx, txTemplateStr.get_str()))
{
std::vector<CTransaction> importTxes;
if (CreateLatestImports(notaryChain.chainDefinition, lastImportTx, templateTx, lastConfirmedTx, totalImportAvailable, importTxes))
{
for (auto importTx : importTxes)
{
UniValue txResult;
params.setArray();
params.push_back(EncodeHexTx(importTx));
try
{
txResult = find_value(RPCCallRoot("signrawtransaction", params), "result");
if (txResult.isObject() && !(txResult = find_value(txResult, "hex")).isNull() && txResult.isStr() && txResult.get_str().size())
{
params.setArray();
params.push_back(txResult);
txResult = find_value(RPCCallRoot("sendrawtransaction", params), "result");
}
else
{
txResult = NullUniValue;
}
} catch (exception e)
{
txResult = NullUniValue;
}
uint256 testId;
if (txResult.isStr())
{
testId.SetHex(txResult.get_str());
}
if (testId.IsNull())
{
break;
}
}
}
}
}
}
}
sleep(3);
}
boost::this_thread::interruption_point();
}
}
catch (const boost::thread_interrupted&)
{
LogPrintf("Verus merge mining thread terminated\n");
}
}
void CConnectedChains::SubmissionThreadStub()
{
ConnectedChains.SubmissionThread();
}
void CConnectedChains::QueueEarnedNotarization(CBlock &blk, int32_t txIndex, int32_t height)
{
// called after winning a block that contains an earned notarization
// the earned notarization and its height are queued for processing by the submission thread
// when a new notarization is added, older notarizations are removed, but all notarizations in the current height are
// kept
LOCK(cs_mergemining);
// we only care about the last
earnedNotarizationHeight = height;
earnedNotarizationBlock = blk;
earnedNotarizationIndex = txIndex;
}
bool IsChainDefinitionInput(const CScript &scriptSig)
{
uint32_t ecode;
return scriptSig.IsPayToCryptoCondition(&ecode) && ecode == EVAL_PBAASDEFINITION;
}
| 40.232515 | 222 | 0.547264 | [
"object",
"vector"
] |
a086288e493765c313d30c221cc647757fd0bf00 | 72,021 | cpp | C++ | openEAR-0.1.0/src/configManager.cpp | trimlab/Voice-Emotion-Detection | c7272dd2f70e2d4b8eee304e68578494d7ef624c | [
"MIT"
] | null | null | null | openEAR-0.1.0/src/configManager.cpp | trimlab/Voice-Emotion-Detection | c7272dd2f70e2d4b8eee304e68578494d7ef624c | [
"MIT"
] | null | null | null | openEAR-0.1.0/src/configManager.cpp | trimlab/Voice-Emotion-Detection | c7272dd2f70e2d4b8eee304e68578494d7ef624c | [
"MIT"
] | null | null | null | /*F******************************************************************************
*
* openSMILE - open Speech and Music Interpretation by Large-space Extraction
* the open-source Munich Audio Feature Extraction Toolkit
* Copyright (C) 2008-2009 Florian Eyben, Martin Woellmer, Bjoern Schuller
*
*
* Institute for Human-Machine Communication
* Technische Universitaet Muenchen (TUM)
* D-80333 Munich, Germany
*
*
* If you use openSMILE or any code from openSMILE in your research work,
* you are kindly asked to acknowledge the use of openSMILE in your publications.
* See the file CITING.txt for details.
*
* 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
*
******************************************************************************E*/
/*
central configuration manager for all components
provides standard interface for various plugable config reader classes (e.g. config file, commandline, database, etc.)
this configManager ONLY manages the configuration of specific parameters for components (or component instances),
it does NOT manage the components to be initialized and the component dependencies (i.e. initialisation of readers and writers of each component)
module names in this class refer to the names of the component instances.
i.e. if you create a component instance config be sure to use the same module (aka. component) names in the component parameter configuration file (this is the one read and managed by this module)
(however, there is one way to put the component initialisation config in this class:
you need to create a component "compInitializer" (or use the componentManager)
and then configure this component
)
*/
// TODO:::: implement setValue functions in analogy to getValue functions to override configuration values!
// also, add a flag to setValue, to only overwrite UNset options
#include <configManager.hpp>
#define MODULE "configManager"
// split n at first . into b (left) and s (right)
// return 1 if '.' was found in *n, 0 otherwise , *b is allocated and must be freed by calling code!
int instNameSplit(const char *n, char **b, const char **s)
{
if (n!=NULL) {
const char *x = strchr(n,'.');
if (x== NULL) {
if (b != NULL) *b = strdup(n);
if (s != NULL) *s = NULL;
return 0;
} else {
long blen = (long)(x-n);
if (b != NULL) {
*b = (char*)malloc(sizeof(char)*blen+1);
memcpy(*b,n,blen);
(*b)[blen]=0;
}
if (s != NULL) *s = x+1;
return 1;
}
}
return 0;
}
/** Config Instance ***************************/
//#define CFTP_VAR 1000 // experimental...? variable type, determined at loading of config file..
void ConfigValueNum::copyFrom(const ConfigValue *val)
{
if (val==NULL) return;
if (val->getType() != getType()) CONF_MANAGER_ERR("ConfigValue::copyFrom, cannot copy from incompatible type (%i)!",val->getType());
valueD = val->getDouble();
valueI = val->getInt();
set=val->isSet();
}
void ConfigValueStr::copyFrom(const ConfigValue *val)
{
if (val==NULL) return;
if (val->getType() != getType()) CONF_MANAGER_ERR("ConfigValue::copyFrom, cannot copy from incompatible type (%i)!",val->getType());
if (str != NULL) free(str);
if (val->getStr() != NULL) {
str = strdup(val->getStr());
set=val->isSet();
} else { set = 0; }
}
void ConfigValueChr::copyFrom(const ConfigValue *val)
{
if (val==NULL) return;
if (val->getType() != getType()) CONF_MANAGER_ERR("ConfigValue::copyFrom, cannot copy from incompatible type (%i)!",val->getType());
c = val->getChar();
set=val->isSet();
}
void ConfigValueObj::setValue(ConfigInstance * value, int n)
{
if ((obj != NULL)&&(freeObj)) delete obj;
obj = value; if (value!=NULL) set=1; else set = 0;
}
void ConfigValueObj::copyFrom(const ConfigValue *val)
{
if (val==NULL) return;
if (val->getType() != getType()) CONF_MANAGER_ERR("ConfigValue::copyFrom, cannot copy from incompatible type (%i)!",val->getType());
if ((obj != NULL)&&(freeObj)) delete obj;
obj = val->getObj(); freeObj=0;
if (obj != NULL) set=val->isSet(); else set = 0;
}
int ConfigValueObj::missingFrom(const ConfigValue *val)
{
if (val==NULL) return 0;
if (val->getType() != getType()) CONF_MANAGER_ERR("ConfigValue::copyFrom, cannot copy from incompatible type (%i)!",val->getType());
if (obj != NULL) {
return obj->missingFrom(val->getObj());
} else {
//obj = val->getObj(); freeObj=0; // TODO: nicer copy mechanism... e.g. copy constructor...?
CONF_MANAGER_ERR("ConfigValueObj::missingFrom: ConfigInstance copy not yet supported!");
}
}
int ConfigValueObj::updateWith(const ConfigValue *val)
{
if (val==NULL) return 0;
if (val->getType() != getType()) CONF_MANAGER_ERR("ConfigValue::copyFrom, cannot copy from incompatible type (%i)!",val->getType());
if (obj != NULL) {
return obj->updateWith(val->getObj());
} else {
//obj = val->getObj(); freeObj=0; // TODO: nicer copy mechanism... e.g. copy constructor...?
CONF_MANAGER_ERR("ConfigValueObj::updateWith: ConfigInstance copy not yet supported!");
}
}
ConfigValueObj::~ConfigValueObj()
{
if ((obj != NULL)&&(freeObj))
delete obj;
}
ConfigValueArr::ConfigValueArr(int initN) : N(0), el(NULL), maxN(-1)
{
if (initN < NEL_ALLOC_BLOCK) initN = NEL_ALLOC_BLOCK;
el = (ConfigValue **)calloc(1,sizeof(ConfigValue*)*initN);
aName = (char **)calloc(1,sizeof(char*)*initN);
if (el==NULL) OUT_OF_MEMORY;
if (aName==NULL) OUT_OF_MEMORY;
N=initN;
type=CFTP_ARR;
}
ConfigValueArr::~ConfigValueArr()
{
if (el != NULL) {
int i;
for (i=0; i<N; i++) {
if (el[i] != NULL) delete el[i];
}
free(el);
}
if (aName != NULL) {
int i;
for (i=0; i<N; i++) {
if (aName[i] != NULL) free(aName[i]);
}
free(aName);
}
}
void ConfigValueArr::setValue(ConfigValue *v, int n)
{
// TODO: checks... + realloc if n>=Nalloc
if (checkIdxWr(n)) {
if (el[n] != NULL) delete(el[n]);
el[n] = v;
set=1;
} else CONF_MANAGER_ERR("ConfigValueArr::setValue: invalid index %i (N=%i)",n,N);
}
int ConfigValueArr::checkIdx(int n) const
{
if (n >= 0) {
if (n<N) {
return 1;
}
}
return 0;
}
int ConfigValueArr::checkIdxWr(int n)
{
if (n >= 0) {
if (n<N) {
if (n>maxN) maxN=n;
return 1;
} else { // realloc:
int newSize = n;
if (newSize-N < NEL_ALLOC_BLOCK) newSize = N+NEL_ALLOC_BLOCK;
ConfigValue **_el = (ConfigValue**)crealloc( el, sizeof(ConfigValue*)*newSize, sizeof(ConfigValue*)*N );
char **_aName = (char**)crealloc( aName, sizeof(char*)*newSize, sizeof(char*)*N );
if (_el==NULL) OUT_OF_MEMORY;
if (_aName==NULL) OUT_OF_MEMORY;
N = newSize;
el = _el;
aName=_aName;
if (n>maxN) maxN=n;
return 1;
}
}
return 0;
}
int ConfigValueArr::findField(const char *_name, int noerr) const
{
int i;
if (_name == NULL) return -2; // bogus name...
if (aName == NULL) return -2; // not an associative array??
SMILE_DBG(5,"ConfigValueArr::findField: maxN = %i",maxN);
for (i=0; i<=maxN; i++) {
SMILE_DBG(5,"ConfigValueArr::findField: comp iter. %i",i);
if ((el[i] != NULL)&&(aName[i] != NULL)) {
SMILE_DBG(5,"ConfigValueArr::findField: compare '%s' <-> '%s'",aName[i],_name);
if (!strcmp(aName[i],_name)) { return i; }
}
}
if (!noerr) SMILE_ERR(5,"ConfigValueArr::findField: field '%s' not found in this associative array",_name);
return -1; // not found
}
int ConfigValueArr::findFieldWr(const char *_name)
{
int idx = findField(_name,1);
if (idx == -1) { // not found: assign it...
int i;
// search for first available index
for (i=0; i<N; i++) {
if ((el[i] == NULL)&&(aName[i] == NULL)) {
idx = i;
break;
}
}
if (idx == -1) { // no free elements... allocate next:
idx = N;
if (!checkIdxWr(N)) idx = -1; // no space, or some other error...!
}
if (idx >= 0) {
aName[idx] = strdup(_name);
}
}
return idx;
}
ConfigValue * ConfigValueArr::operator[](int n) const
{
SMILE_DBG(5,"operator [int] of ConfigValueArr called...");
if (checkIdx(n)) return el[n];
else return NULL;
}
ConfigValue * ConfigValueArr::operator[](const char *_name) const
{
SMILE_DBG(5,"operator [char *] of ConfigValueArr called...");
int n = findField(_name);
if (checkIdx(n)) return el[n];
else return NULL;
}
// TODO: resize array.....!!!
void ConfigValueArr::copyFrom(const ConfigValue *val)
{
int i;
if (val==NULL) return;
ConfigValueArr *a;
if (val->getType() >= CFTP_ARR) a = (ConfigValueArr *)val;
else CONF_MANAGER_ERR("ConfigValueArr::copyFrom called with non-array element as argument!");
int Nc;
Nc = a->getN();
if (Nc > N) Nc = N;
for (i=0; i<Nc; i++) {
if (el[i] != NULL)
el[i]->copyFrom(a->el[i]);
//TODO.... else : REAL copy of ConfigVal object... ??
}
}
int ConfigValueArr::missingFrom(const ConfigValue *val)
{
int i;
if (val==NULL) return 0;
ConfigValueArr *a;
if (val->getType() >= CFTP_ARR) a = (ConfigValueArr *)val;
else return 0;
int Nc;
Nc = a->getN();
if (Nc > N) Nc = N;
for (i=0; i<Nc; i++) {
if (el[i] != NULL)
el[i]->missingFrom(a->el[i]);
//TODO.... else : REAL copy of ConfigVal object... ??
}
return 0; // TODO...
}
int ConfigValueArr::updateWith(const ConfigValue *val)
{
int i;
if (val==NULL) return 0;
ConfigValueArr *a;
if (val->getType() >= CFTP_ARR) a = (ConfigValueArr *)val;
else return 0;
int Nc;
Nc = a->getN();
if (Nc > N) Nc = N;
for (i=0; i<Nc; i++) {
if (el[i] != NULL)
el[i]->updateWith(a->el[i]);
//TODO.... else : REAL copy of ConfigVal object... ??
}
return 0; // TODO...
}
void ConfigValueNumArr::setValue(double v, int n)
{
if (checkIdxWr(n)) {
if (el[n] == NULL) {
// allocate value..
el[n] = new ConfigValueNum(v); // WARNING: freeObj = 1 always!
if (el[n] == NULL) OUT_OF_MEMORY;
} else {
el[n]->setValue(v);
}
}
}
void ConfigValueNumArr::setValue(int v, int n)
{
if (checkIdxWr(n)) {
if (el[n] == NULL) {
// allocate value..
el[n] = new ConfigValueNum(v); // WARNING: freeObj = 1 always!
if (el[n] == NULL) OUT_OF_MEMORY;
} else {
el[n]->setValue(v);
}
}
}
void ConfigValueStrArr::setValue(const char *v, int n)
{
if (checkIdxWr(n)) {
if (el[n] == NULL) {
// alocate value..
el[n] = new ConfigValueStr(v); // WARNING: freeObj = 1 always!
if (el[n] == NULL) OUT_OF_MEMORY;
} else {
el[n]->setValue(v);
}
}
}
void ConfigValueChrArr::setValue(char v, int n) {
if (checkIdxWr(n)) {
if (el[n] == NULL) {
// alocate value..
el[n] = new ConfigValueChr(v); // WARNING: freeObj = 1 always!
if (el[n] == NULL) OUT_OF_MEMORY;
} else {
el[n]->setValue(v);
}
}
}
void ConfigValueObjArr::setValue(ConfigInstance *v, int n) {
if (checkIdxWr(n)) {
if (el[n] == NULL) {
// alocate value..
el[n] = new ConfigValueObj(v); // WARNING: freeObj = 1 always!
if (el[n] == NULL) OUT_OF_MEMORY;
} else {
el[n]->setValue(v);
}
}
}
/**************/
/**** Config Type ***************************************************************/
ConfigType::ConfigType(const char *_name, int _N) :
element(NULL),
I(0)
{
if (name != NULL) setName( _name );
if (_N > 0) {
N=_N;
element = (ConfigDescription *)calloc(1,sizeof(ConfigDescription)*_N);
} else {
CONF_MANAGER_ERR("Cannot create ConfigType object with number of elements _N < 0 (_N=%i)!",_N);
}
}
// type copy constructor
ConfigType::ConfigType( ConfigType const& copy, const char *_newname) :
N(copy.N),
I(copy.I),
element(NULL)
{
if (_newname != NULL) setName(_newname);
else { setName(copy.name); }
// copy configDescription:
if (copy.element != NULL) {
element = (ConfigDescription *)calloc(1,sizeof(ConfigDescription)*N);
memcpy( element, copy.element, sizeof(ConfigDescription)*N );
int i;
for (i=0; i<N; i++) {
element[i].description = NULL;
element[i].dfltStr = NULL;
element[i].freeType=0;
if (copy.element[i].description != NULL) {
element[i].description = strdup(copy.element[i].description);
}
if (copy.element[i].dfltStr != NULL) {
element[i].dfltStr = strdup(copy.element[i].dfltStr);
}
}
}
}
void ConfigType::setName(const char *_name)
{
if (_name == NULL) { SMILE_ERR(1,"cannot set name == NULL (setName)"); }
else {
size_t l = strlen(_name);
if (l>CONFIGTYPE_STRLEN) {
l=CONFIGTYPE_STRLEN;
}
#ifdef _MSC_VER // Visual Studio specific macro
strncpy_s( name, CONFIGTYPE_STRLEN, _name, MIN((l+1),CONFIGTYPE_STRLEN) );
#else
strncpy( name, _name, MIN((l+1),CONFIGTYPE_STRLEN) );
#endif
}
}
int ConfigType::findFieldH(const char *_name, int *n, const ConfigType **tp, int *aIdx, char **aStr) const
{
try {
if (_name != NULL) {
int h, idx;
char *base=NULL;
const ConfigType *cur=this;
const char*origname = _name;
int arrIdx = -1;
char *arrStr = NULL;
do {
if (cur==NULL) {
CONF_MANAGER_ERR("ConfigType::findFieldH: cannot dereference NULL subobject pointer while finding filed '%s' (rem:'%s')",origname,_name);
}
// split name
const char *rem=NULL;
h = instNameSplit(_name, &base, &rem);
if (base == NULL) { CONF_MANAGER_ERR("no base name returned by instNameSplit (name='%s')!\n",_name); }
arrIdx = -1;
if (arrStr != NULL) { free(arrStr); arrStr=NULL; }
idx = cur->findField(base,&arrIdx,&arrStr);
if (base!=NULL) { free(base); base=NULL; }
_name=rem;
if (h==1) {
if ((idx >= 0)&&(idx < N)) { // check for valid index
if ((cur->getType(idx) == CFTP_OBJ)||(cur->getType(idx) == CFTP_OBJ_ARR)) {
cur = cur->element[idx].subType;
}
else
CONF_MANAGER_ERR("ConfigType::findFieldH: subtype object referenced in '%s', however field %i is not of type OBJ or OBJ_ARR!",_name,idx);
} else {
// error field "base" not found...
CONF_MANAGER_ERR("ConfigType::findFieldH: referenced base field with name '%s' not found!",origname);
}
}
} while (h==1);
if (h==0) {
if ((idx >= 0)&&(idx < N)) { // check for valid index
if (n!=NULL) *n = idx;
if (tp!=NULL) *tp = cur;
if (aIdx!=NULL) *aIdx = arrIdx;
if (aStr!=NULL) *aStr = arrStr;
else if (arrStr != NULL) free(arrStr);
return 1;
} else
if (arrStr != NULL) { free(arrStr); }
// error field "base" not found...
CONF_MANAGER_ERR("ConfigType::findFieldH: referenced base field with name '%s' not found!",origname);
}
if (arrStr != NULL) { free(arrStr); }
}
} catch (ConfigException *) {}
return 0;
}
void ConfigType::printTypeHelp(char *basestr, int _subtype) const
{
if (basestr == NULL)
SMILE_PRINT("\n === ConfigType '%s' : ===",getName());
// TODO: print type description
if (element != NULL) {
int i;
const char *ArrS="";
for (i=0; i<I; i++) {
if (element[i].enabled) {
char *b=NULL;
if (basestr != NULL) b=myvprint("%s.",basestr);
else b=myvprint("");
if (element[i].type >= CFTP_ARR) { element[i].type -= CFTP_ARR+1; ArrS="[]"; }
else { ArrS=""; }
switch(element[i].type) {
case CFTP_OBJ:
if (element[i].subType != NULL)
SMILE_PRINT(" %s%s%s = <object of type '%s'>",b,element[i].name,ArrS,element[i].subType->getName());
break;
case CFTP_NUM:
SMILE_PRINT(" %s%s%s = <numeric> [dflt: %f]",b,element[i].name,ArrS,element[i].dfltDouble);
break;
case CFTP_STR:
SMILE_PRINT(" %s%s%s = <string> [dflt: '%s']",b,element[i].name,ArrS,element[i].dfltStr);
break;
case CFTP_CHR:
SMILE_PRINT(" %s%s%s = <char> [dflt: '%c']",b,element[i].name,ArrS,element[i].dfltChar);
break;
}
if (b!=NULL) free(b);
if (element[i].description != NULL) {
SMILE_PRINT(" %s",element[i].description);
}
if ((element[i].type == CFTP_OBJ)&&(_subtype)) {
if (element[i].subType != NULL)
if (basestr!=NULL)
element[i].subType->printTypeHelp(myvprint("%s.%s%s",basestr,element[i].name,ArrS));
else
element[i].subType->printTypeHelp(myvprint("%s%s",element[i].name,ArrS));
}
}
}
}
if (basestr != NULL) free(basestr);
else SMILE_PRINT(" ");
}
ConfigType::~ConfigType()
{
if (element != NULL) {
int i;
for (i=0; i<N; i++) {
if (element[i].description != NULL) {
free(element[i].description);
}
if (element[i].dfltStr != NULL) {
free(element[i].dfltStr);
}
// TODO: delete subType!?
if ((element[i].freeType)&&(element[i].subType!=NULL)) delete element[i].subType;
}
free(element);
}
}
// disable field by setting "enabled = 0", the field is still available normally, however, it will not be shown by printTypeHelp anymore!
int ConfigType::disableField(const char *_name)
{
int FF = findField(_name);
if (FF > -1) {
element[FF].enabled = 0;
return 1;
}
return 0;
}
int ConfigType::setField(const char *_name, const char *description, int type, int subtype, const ConfigType *subType, int freeType, int _N)
{
// check name for forbidden characters: . [ ] = : , ;
if (strchr(_name,'.') != NULL) CONF_MANAGER_ERR("ConfigType::setField: Forbidden charachter '.' in field name '%s'",_name);
if (strchr(_name,',') != NULL) CONF_MANAGER_ERR("ConfigType::setField: Forbidden charachter ',' in field name '%s'",_name);
if (strchr(_name,'[') != NULL) CONF_MANAGER_ERR("ConfigType::setField: Forbidden charachter '[' in field name '%s'",_name);
if (strchr(_name,']') != NULL) CONF_MANAGER_ERR("ConfigType::setField: Forbidden charachter ']' in field name '%s'",_name);
if (strchr(_name,':') != NULL) CONF_MANAGER_ERR("ConfigType::setField: Forbidden charachter ':' in field name '%s'",_name);
if (strchr(_name,';') != NULL) CONF_MANAGER_ERR("ConfigType::setField: Forbidden charachter ';' in field name '%s'",_name);
if (strchr(_name,'=') != NULL) CONF_MANAGER_ERR("ConfigType::setField: Forbidden charachter '=' in field name '%s'",_name);
// check for uniqueness of name:
int FF = findField(_name);
if (FF == -1) {
// check for free space:
if (I>=N) {
// DONE: dynamically increase the number of fields
//CONF_MANAGER_ERR("ConfigType::setField: cannot add more then N=%i fields! Specify a larger N when creating the object!",N);
#define N_NEW_ALLOC 20
ConfigDescription * tmp = (ConfigDescription *)realloc(element, sizeof(ConfigDescription)*(I+N_NEW_ALLOC));
if (tmp != NULL) {
ConfigDescription * tmp2 = tmp+N;
// initialise tmp2 with zero
bzero( tmp2, sizeof(ConfigDescription)*N_NEW_ALLOC);
N=I+N_NEW_ALLOC;
element = tmp;
} else { OUT_OF_MEMORY; }
}
element[I].enabled = 1;
element[I].type = type;
element[I].subtype = subtype;
element[I].subType = subType;
element[I].freeType = freeType;
#ifdef _MSC_VER // Visual Studio specific macro
strncpy_s( element[I].name, CONFIGTYPE_STRLEN, _name, CONFIGTYPE_STRLEN );
#else
strncpy( element[I].name, _name, CONFIGTYPE_STRLEN );
#endif
if (description != NULL) {
element[I].description = strdup(description);
} else { element[I].description = NULL; }
element[I].N = _N;
element[I].isMandatory = 0;
return I++;
} else {
element[FF].enabled = 1;
element[FF].type = type;
element[FF].subtype = subtype;
//element[FF].subType = subType; // TODO: subtype overwrite!
//element[FF].freeType = freeType; // TODO: free on overwrite!?
// strncpy( element[FF].name, _name, CONFIGTYPE_STRLEN ); // name may not be changed!
if (description != NULL) {
if (element[FF].description != NULL) free(element[FF].description);
element[FF].description = strdup(description);
}
element[FF].N = _N;
//element[FF].isMandatory = 0;
return FF;
// CONF_MANAGER_ERR("ConfigType::setField: '%s' is not a unique name, already used in type!");
}
return -1;
}
int ConfigType::setField(const char *_name, const char *description, int dflt, int arr)
{
int ret=0;
if (!arr) {
ret = setField(_name,description,CFTP_NUM,0,(const ConfigType*)NULL);
} else {
ret = setField(_name,description,CFTP_NUM_ARR,0,(const ConfigType*)NULL);
}
if (ret >= 0) element[ret].dfltDouble = (double)dflt;
return ret;
}
int ConfigType::setField(const char *_name, const char *description, double dflt, int arr)
{
int ret=0;
if (!arr) {
ret = setField(_name,description,CFTP_NUM,0,(const ConfigType*)NULL);
} else {
ret = setField(_name,description,CFTP_NUM_ARR,0,(const ConfigType*)NULL);
}
if (ret >= 0) element[ret].dfltDouble = dflt;
return ret;
}
int ConfigType::setField(const char *_name, const char *description, const char * dflt, int arr)
{
int ret=0;
if (!arr) {
ret = setField(_name,description,CFTP_STR,0,NULL);
} else {
ret = setField(_name,description,CFTP_STR_ARR,0,NULL);
}
if (ret >= 0) {
if (dflt != NULL) {
if (element[ret].dfltStr != NULL) free(element[ret].dfltStr);
element[ret].dfltStr = strdup(dflt);
} else
element[ret].dfltStr = NULL;
}
return ret;
}
int ConfigType::setField(const char *_name, const char *description, char dflt, int arr)
{
int ret=0;
if (!arr) {
ret = setField(_name,description,CFTP_CHR,0,NULL);
} else {
ret = setField(_name,description,CFTP_CHR_ARR,0,NULL);
}
if (ret >= 0) element[ret].dfltChar = dflt;
return ret;
}
int ConfigType::setField(const char *_name, const char *description, const ConfigType *dflt, int arr, int freeType)
{
int ret=-1;
if (dflt==NULL) return ret;
if (arr==NO_ARRAY) {
ret = setField(_name,description,CFTP_OBJ,0,dflt,freeType);
} else {
ret = setField(_name,description,CFTP_OBJ_ARR,0,dflt,freeType);
}
return ret;
}
const ConfigDescription * ConfigType::operator[] (int n)
{
if ((n<N)&&(n>=0))
return &(element[n]);
else CONF_MANAGER_ERR("ConfigType [%i] index out of bounds (0-%i)",n,N);
}
int ConfigType::findField(const char *_name, int *arrI, char **arrS) const
{
// search for [] array indices:
if (element == NULL) return -1;
if (name == NULL) {
SMILE_DBG(4,"ConfigType::findField: called with _name == NULL!");
return -1;
}
char *base = strdup(_name);
char * s = strchr(base,'[');
int isArr=0;
if (s!=NULL) { // [ was found
isArr=1;
char * e = strchr(base,']');
if (e==NULL) {
CONF_PARSER_ERR("ConfigType::findField: parse error: field name '%s', missing closing array index markers ] at end of name!",_name);
}
if (strlen(e) > 1) {
CONF_PARSER_ERR("ConfigType::findField: parse error: field name '%s', has array index markers [] not at end of name!",_name);
}
s[0] = 0;
if ((arrI != NULL)||(arrS != NULL)) {
e[0] = 0;
long Aidx;
char *idxStr = s+1;
// TODO: remove spaces from idxStr...
if (strlen(idxStr) <= 0) CONF_PARSER_ERR("ConfigType::findField: parse error: field name '%s', has empty array index markers []!",_name);
// scan array index...
char *eptr = NULL;
Aidx = strtol(idxStr,&eptr,0);
if ((eptr != NULL)&&(eptr[0]!=0)) { // not a pure number!
if (arrS != NULL) *arrS = strdup(idxStr);
if (arrI != NULL) *arrI = -1;
} else {
//sscanf( idxStr, "%i", &Aidx );
if (arrI != NULL) *arrI = Aidx;
if (arrS != NULL) *arrS = NULL;
}
}
} else if (arrI != NULL) { *arrI = -1; }
// now find "base":
int i;
for (i=0; i<N; i++) {
if (element[i].name != NULL) {
if (!strcmp(element[i].name,base)) {
free(base);
/*
if ((element[i].type >= CFTP_ARR)&&(!isArr)) {
SMILE_ERR(1,"missing array index [] for element '%s'",element[i].name);
return -1;
} TODO: move this somewhere else (in every function that uses findField(H)....!)*/
if ((element[i].type < CFTP_ARR)&&(isArr)) {
SMILE_ERR(1,"array index [] specified for non-array element '%s'",element[i].name);
return -1;
}
return i;
}
}
}
free(base);
return -1; // field not found
}
int ConfigType::getType(int n) const {
if ((n>=0)&&(n<N)&&(element!=NULL)) {
return element[n].type;
}
return -1;
}
const ConfigType * ConfigType::getTypeObj(int n) const {
if ((n>=0)&&(n<N)&&(element!=NULL)) {
return element[n].subType;
}
return NULL;
}
const char * ConfigType::getName(int n) const {
if ((n>=0)&&(n<N)&&(element!=NULL)) {
return element[n].name;
}
return NULL;
}
/**************************************************/
ConfigInstance::ConfigInstance(const char *_name, const ConfigType *_type, int _freeType) :
freeType(_freeType),
type(NULL)
{
int n;
if (name != NULL) {
#ifdef _MSC_VER // Visual Studio specific macro
strncpy_s(name,CONFIGTYPE_STRLEN,_name,CONFIGTYPE_STRLEN);
#else
strncpy(name,_name,CONFIGTYPE_STRLEN);
#endif
type=_type;
if (_type != NULL) {
n=_type->getN();
field=(ConfigValue **)calloc(1,sizeof(ConfigValue *)*n);
if (field == NULL) OUT_OF_MEMORY;
N=n;
int i;
for (i=0; i<n; i++) {
switch(_type->getType(i)) {
case CFTP_NUM : field[i] = new ConfigValueNum(_type->getDfltNum(i)); break;
case CFTP_STR : field[i] = new ConfigValueStr(_type->getDfltStr(i)); break;
case CFTP_CHR : field[i] = new ConfigValueChr(_type->getDfltChr(i)); break;
case CFTP_OBJ : field[i] = new ConfigValueObj(new ConfigInstance(_type->getName(i) ,_type->getDfltObj(i))); break;
case CFTP_ARR : field[i] = new ConfigValueArr(); break;
case CFTP_NUM_ARR : field[i] = new ConfigValueNumArr(); break;
case CFTP_STR_ARR : field[i] = new ConfigValueStrArr(); break;
case CFTP_CHR_ARR : field[i] = new ConfigValueChrArr(); break;
case CFTP_OBJ_ARR : field[i] = new ConfigValueObjArr(); break;
default: CONF_MANAGER_ERR("cannot create field of unknown type constant %i",_type->getType(i));
}
if (field[i] != NULL) field[i]->unset();
}
} else {
CONF_MANAGER_ERR("Canot create a ConfigInstance with _type==NULL !");
}
} else {
CONF_MANAGER_ERR("Canot create a ConfigInstance with _name==NULL !");
}
}
ConfigInstance::~ConfigInstance()
{
if ((freeType)&&(type!=NULL)) delete type;
if (field != NULL) {
int i;
for(i=0; i<N; i++) {
if (field[i] != NULL) delete field[i];
}
free(field);
}
}
/* sanity check the given instance, if it is of the same type, dimensions etc. */
int ConfigInstance::sanityCheck(ConfigInstance *_match) const
{
// do some sanity checks:
if (_match == NULL) {
// argument cannot be NULL...
//CONF_MANAGER_ERR("argument of sanityCheck(ConfigInstance *_match) is NULL!");
return 0;
}
if (_match->field == NULL) {
// no values in default
CONF_MANAGER_ERR("sanityCheck: field array in class passed as parameter is NULL!");
}
if (_match->N != N) { // number of values must match
SMILE_ERR(2,"cannot update missing values from an Instance with a different number of values");
return 0;
}
if (_match->type->getName() != type->getName()) { // type name must match ??
SMILE_ERR(3,"type mismatch during update missingFrom");
return 0;
}
return 1;
}
/* returns the number of values that were taken (updated) from _default */
// TODO: handle array types...
int ConfigInstance::missingFrom(ConfigInstance *_default)
{
int i,nup=0;
if (!sanityCheck(_default)) return 0;
for (i=0; i<N; i++) {
nup += field[i]->missingFrom(_default->getValue(i));
// (field[i]->getType() == CFTP_OBJ)||(field[i]->getType() >= CFTP_ARR) then hierarchically update...
//if ((!(field[i]->isSet()))||(field[i]->getType() == CFTP_OBJ)||(field[i]->getType() >= CFTP_ARR)) { // value not set, use _default...
// field[i]->copyFrom(_default->getValue(i));
// nup++;
//}
}
return nup;
}
/* returns number of values overwritten (=number of set values in _new) */
int ConfigInstance::updateWith(ConfigInstance *_new)
{
int i,nov=0;
if (!sanityCheck(_new)) return 0;
for (i=0; i<N; i++) {
field[i]->updateWith(_new->getValue(i));
// if (!(_new->field[i]->isSet())) { // value not set, use _default...
// field[i]->copyFrom(_new->getValue(i));
// nov++;
// }
}
return nov;
}
/*
find field (value) in instance by field name (hierarchical)
return 1 on success, 0 on error
optional: set *in to address of ConfigInstance containig the found value/field
and *n to index of field in that instance.
(only valid, if not NULL is returned)
*/
int ConfigInstance::findField(const char *_name, int *n, ConfigInstance **in, int *aIdx, char **aStr)
{
try {
if (_name != NULL) {
int h, idx;
char *base=NULL;
ConfigInstance *cur=this;
const char*origname = _name;
int arrIdx = -1;
char *arrStr = NULL;
do {
if (cur==NULL) {
CONF_MANAGER_ERR("ConfigInstance::findField: cannot dereference NULL subobject pointer while finding value for '%s' (rem:'%s')",origname,_name);
}
// split name
const char *rem;
h = instNameSplit(_name, &base, &rem);
arrIdx = -1;
if (arrStr != NULL) { free(arrStr); arrStr = NULL; }
idx = cur->type->findField(base,&arrIdx,&arrStr);
if (base!=NULL) { free(base); base=NULL; }
_name=rem;
if (h==1) {
if ((idx >= 0)&&(idx < N)) { // check for valid index
if ((cur->field[idx]->getType() == CFTP_OBJ)||(cur->field[idx]->getType() == CFTP_OBJ_ARR)) {
// TODO... check if field is initialized ???!!!!!
if (field[idx] == NULL) CONF_MANAGER_ERR("ConfigInstance::findField: attempting to access object field '%s', which has not been initialized (full name: '%s')!",base,origname);
cur = cur->field[idx]->getObj(arrIdx);
}
else
CONF_MANAGER_ERR("ConfigInstance::findField: subtype object referenced in '%s', however field %i is not of type OBJ or OBJ_ARR!",_name,idx);
} else {
// error field "base" not found...
CONF_MANAGER_ERR("ConfigInstance::findField: referenced base field with name '%s' not found!",origname);
}
}
} while (h==1);
if (h==0) {
if ((idx >= 0)&&(idx < N)) { // check for valid index
if (n!=NULL) *n = idx;
if (in!=NULL) *in = cur;
if (aIdx!=NULL) *aIdx = arrIdx;
if (aStr!=NULL) *aStr = arrStr;
return 1;
} else
if (arrStr != NULL) free(arrStr);
// error field "base" not found...
CONF_MANAGER_ERR("ConfigInstance::findField: referenced base field with name '%s' not found!",origname);
}
if (arrStr != NULL) free(arrStr);
}
} catch (ConfigException *) {}
return 0;
}
int ConfigInstance::getType(const char *_name)
{ /* recursively dereference, via findField */
int n,aIdx;
ConfigInstance *child=NULL;
int r = findField(_name, &n, &child, &aIdx, NULL);
if ((r)&&(child!=NULL)) {
return child->getType(n);
} else { return r; }
}
/* this function does not check n for valid range!!*/
/* the memory pointed to by val is freed, if the content is copied over exisiting content,
otherwise the memory is not freed and the pointer is copied. the memory pointed to by
val may NEVER be freed by the calling code, however it must be allocated by the calling code */
void ConfigInstance::setVal(int n, ConfigValue *val, int idx)
{
if (val == NULL) return;
if (field[n] == NULL) {
int ty = type->getType(n);
if (ty != val->getType()) CONF_MANAGER_ERR("ConfigInstance::setVal: Type mistmatch *val : %i != getType(%i) : %i",val->getType(),ty);
if ((ty >= CFTP_ARR)&&(idx>=0)) {
// a) array -> create array value for type
switch(ty) {
case CFTP_NUM_ARR: field[n] = new ConfigValueNumArr(idx+1); break;
case CFTP_STR_ARR: field[n] = new ConfigValueStrArr(idx+1); break;
case CFTP_CHR_ARR: field[n] = new ConfigValueChrArr(idx+1); break;
case CFTP_OBJ_ARR: field[n] = new ConfigValueObjArr(idx+1); break;
default: CONF_MANAGER_ERR("unknonwn array type %i for field idx=%i encountered in ConfigInstance::setVal!",ty,n);
}
if (field[n] == NULL) OUT_OF_MEMORY;
field[n]->setValue(val,idx); // this is bogus , TODO: copyFrom for array element!
} else {
// b) non-array, or full array passed as *val parameter (when idx==-1): copy val
field[n] = val;
}
} else { // copy values
if ((idx >= 0)&&(field[n]->getType() >= CFTP_ARR)) {
// a) array -> use copyFrom with array index...
ConfigValue *tmp = (*(ConfigValueArr*)(field[n]))[idx];
if ( tmp != NULL) {
tmp->copyFrom(val); delete val;
} else
field[n]->setValue(val,idx);
} else {
// b) non-array:
field[n]->copyFrom(val); // check type??
delete val;
}
}
}
const ConfigValue * ConfigInstance::getVal(int n, int idx) const {
if ((idx >= 0)&&(field[n]->getType() >= CFTP_ARR)) {
// a) array -> get element [idx]
return (*(ConfigValueArr*)(field[n]))[idx];
} else {
// b) non-array or full array element:
return field[n];
}
}
/* recursively dereference subobj pointers */
/* does not copy *val, it stores the pointer directly in the configInstance object */
void ConfigInstance::setValue(ConfigValue *val, int n, const char *_name, int arrIdx)
{
if (n >= 0) { // prefer N
if (n<N) {
setVal(n,val,arrIdx);
}
} else if (_name != NULL) {
SMILE_DBG(5,"called ConfigInstance::setValue (_name = '%s')",_name);
// split name
const char *rem=NULL;
char *base=NULL;
int h = instNameSplit(_name, &base, &rem);
arrIdx=-1;
char *arrStr=NULL;
int idx = type->findField(base,&arrIdx,&arrStr);
SMILE_DBG(5,"findField returned idx=%i and arrIdx=%i arrStr='%s' (h=%i)",idx,arrIdx,arrStr,h);
if (h==1) {
if ((idx >= 0)&&(idx < N)) { // check for valid index
if (field[idx] == NULL) CONF_MANAGER_ERR("ConfigInstance::getValue: attempting to access object field '%s', which has not been initialized!",base);
if ((field[idx]->getType() == CFTP_OBJ)||(field[idx]->getType() == CFTP_OBJ_ARR)) {
// TODO: if field[idx] not allocated... create a new Instance...!
if (field[idx] == NULL) { // ... should never happen....
SMILE_DBG(4,"ConfigInstance::setValue : creating new field (base = '%s') ... STRANGE!?",base);
field[idx] = new ConfigValueObj(new ConfigInstance(base, type->getTypeObj(idx) ));
}
if (arrStr != NULL) {
arrIdx = field[idx]->findFieldWr(arrStr);
free(arrStr);
}
SMILE_DBG(4,"ConfigInstance::setValue : arrIdx = %i, isset = %i",arrIdx, field[idx]->isSet(arrIdx));
if (!(field[idx]->isSet(arrIdx))) {
SMILE_DBG(4,"ConfigInstance::setValue : creating new array element (base = '%s') ai:%i",base,arrIdx);
field[idx]->setValue(new ConfigInstance(base, type->getTypeObj(idx) ),arrIdx);
}
ConfigInstance *cur = field[idx]->getObj(arrIdx);
if (cur!=NULL) cur->setValue(val,-1,rem);
else
CONF_MANAGER_ERR("setValue: cannot dereference NULL subobject pointer while setting value for '%s' (rem:'%s')",_name,rem);
}
else
CONF_MANAGER_ERR("subtype object referenced in '%s', however field %i is not of type OBJ or OBJ_ARR!",_name,idx);
} else CONF_MANAGER_ERR("setValue: hierarchical field referenced ('%s') does not exist! ",rem);
} else {
if (arrStr != NULL) {
arrIdx = field[idx]->findFieldWr(arrStr);
free(arrStr);
}
setValue(val,idx,NULL,arrIdx);
}
if (base!=NULL) { free(base); base=NULL; }
}
}
const ConfigValue * ConfigInstance::getValue(int n, const char *_name, int arrIdx) const
{
if (n >= 0) { // prefer N
if (n<N) {
return getVal(n,arrIdx);
}
} else if (_name != NULL) {
// split name
SMILE_DBG(5,"called ConfigInstance::getValue (_name = '%s')",_name);
const char *rem;
char *base=NULL;
int h = instNameSplit(_name, &base, &rem);
arrIdx = -1;
char *arrStr = NULL;
int idx = type->findField(base,&arrIdx,&arrStr);
SMILE_DBG(5,"findField returned idx=%i and arrIdx=%i arrStr='%s' (h=%i)",idx,arrIdx,arrStr,h);
if (base!=NULL) { free(base); base=NULL; }
if (h==1) {
if ((idx >= 0)&&(idx < N)) { // check for valid index
if (field[idx] == NULL) CONF_MANAGER_ERR("ConfigInstance::getValue: attempting to access object field '%s', which has not been initialized!",base);
if ((field[idx]->getType() == CFTP_OBJ)||(field[idx]->getType() == CFTP_OBJ_ARR)) {
// TODO:: check if field[idx] is initialized!!
if (arrStr != NULL) {
arrIdx = field[idx]->findField(arrStr);
free(arrStr);
}
ConfigInstance *cur = field[idx]->getObj(arrIdx);
if (cur!=NULL) return cur->getValue(-1,rem);
else
CONF_MANAGER_ERR("getValue: cannot dereference NULL subobject pointer while getting value for'%s' (rem:'%s')",name,rem);
} else CONF_MANAGER_ERR("getValue: hierarchical field referenced is not of type object! ('%s')",rem);
} else CONF_MANAGER_ERR("getValue: hierarchical field referenced ('%s') does not exist! ",rem);
} else {
if (idx < 0) SMILE_WRN(2,"ConfigInstance::getValue : non-existant field '%s' (%i)",_name,n);
if (arrStr != NULL) {
arrIdx = field[idx]->findField(arrStr);
free(arrStr);
}
return getValue(idx,NULL,arrIdx);
}
}
SMILE_WRN(2,"ConfigInstance::getValue : index %i out of bounds (0-%i)",n,N-1);
return NULL;
}
/*******************************************************************************/
/* generic backend reader interface, virtual class only, descendant must implement:
findInstancesByName
getInstance
openInput
*/
cConfigReader::cConfigReader(const char *_inputPath, int _inputId) :
inputPath(NULL),
inputId(_inputId),
cmdparser(NULL)
{
SMILE_MSG(4,"creating a new cConfigReader component",inputPath);
if (_inputPath != NULL) inputPath = strdup(_inputPath);
// derived class must call openInput()!?
}
void cConfigReader::destroyStrArray(char **arr, int n)
{
int i;
if (arr != NULL) {
for (i=0; i<n; i++) {
if (arr[n] != NULL) free(arr[n]);
}
free(arr);
}
}
char ** cConfigReader::findInstances(const ConfigType *_type, int *N)
{
if (_type != NULL) {
return findInstancesByTypeName(_type->getName(),N);
}
return NULL;
}
cConfigReader::~cConfigReader()
{
//closeInput(); must be called by derived class... ?
if (inputPath != NULL) free(inputPath);
}
/*******************************************************************************/
/* commandline config reader */
#if 0
class cCommandlineConfigReader : public cConfigReader {
protected:
char **argv;
int argc;
public:
cCommandlineConfigReader(const char **_argv, int _argc);
virtual int openInput() {} // nothing to open here...
virtual int closeInput() {}
virtual char ** findInstancesByTypeName(const char *_typename, int *N); /* returns names (and no.) of instances of type "typename" */
virtual ConfigInstance *getInstance(const char *_instname, const ConfigType *_type); /* get an instance with name _instname */
virtual ~cConfigReader() {}
};
cCommandlineConfigReader::cCommandlineConfigReader(const char **_argv, int _argc)
{
}
#endif
/*******************************************************************************/
/* ini-style file config reader */
/* file format:
[InstanceName:TypeName]
InstanceName.Field1.subfield=value
InstanceName.Field1.myarray[0]=value
InstanceName.Field1.myarray[1]=value
InstanceName.NextField = value
[NextInstanceName:TypeName]
*/
int cFileConfigReader::addInst(const char*_instname, const char*_typename)
{
if (nInst >= nInstAlloc) { // realloc
fileInstance *f = (fileInstance *)realloc( inst, sizeof(fileInstance) * (nInst+10));
if (f == NULL) OUT_OF_MEMORY;
inst = f;
nInstAlloc = nInst+10;
}
inst[nInst].name = strdup(_instname);
inst[nInst].type = strdup(_typename);
SMILE_DBG(3,"cFileConfigReader , added instance: '[%s:%s]'",inst[nInst].name,inst[nInst].type);
inst[nInst].N=0;
inst[nInst].Nalloc=0;
inst[nInst].lines = NULL;
inst[nInst].lineNr = NULL;
return nInst++;
}
int cFileConfigReader::addLine(int n, const char *line, int lineNr)
{
if ((n<0)||(n>=nInst)) return -1;
if (inst[n].N >= inst[n].Nalloc) { // realloc
char **l = (char **)realloc(inst[n].lines, sizeof(char*) * (inst[n].N+100) );
if (l==NULL) OUT_OF_MEMORY;
inst[n].lines = l;
inst[n].Nalloc = inst[n].N+100;
int *ln = (int *)realloc(inst[n].lineNr, sizeof(int) * (inst[n].N+100) );
if (ln==NULL) OUT_OF_MEMORY;
inst[n].lineNr = ln;
}
inst[n].lines[inst[n].N] = strdup(line);
inst[n].lineNr[inst[n].N] = lineNr;
return inst[n].N++;
}
/* each instance has a header: [instname:type] followed by the lines with values */
/* including other config files can be done via the command: \{path/and/file_to.include} */
int cFileConfigReader::openInput(const char*fname, int *idx0)
{
FILE *in=NULL;
// open file "_inputpath"
if (fname==NULL) {
SMILE_MSG(2,"reading config file '%s'",inputPath);
in = fopen( inputPath, "r" );
if (in == NULL) CONF_MANAGER_ERR("cFileConfigReader::openInput : cannot open input file '%s'!",inputPath);
} else {
SMILE_MSG(2,"reading config file '%s'",fname);
if (!strcmp(fname,inputPath)) CONF_MANAGER_ERR("loop in config file includes detected (the base file '%s' was included)!",inputPath);
in = fopen( fname, "r" );
if (in == NULL) CONF_MANAGER_ERR("cFileConfigReader::openInput : cannot open input file '%s'!",fname);
}
// read file, 1st pass to find Types & Names
char *line=NULL;
int nline=-1;
int idx = -1;
if (idx0!=NULL) idx=*idx0;
int lineNr = 0;
size_t n,read;
do {
read = getline(&line, &n, in);
char *origline = line;
if ((read != (size_t)-1)&&(origline!=NULL)) { ///XXXX
lineNr++;
// remove newline at end:
int len = (int)strlen(line)-1;
if (len>=0) { if (line[len] == '\n') { line[len] = 0; len--; } }
if (len>=0) { if (line[len] == '\r') { line[len] = 0; len--; } }
while (((line[0] == ' ')||(line[0] == '\t'))&&(len>=0)) { line[0] = 0; line++; len--; }
if (len >= 0) {
SMILE_DBG(5,"read line: '%s' read=%i, len=%i",line,read,len);
if (line[0]=='[') { // check for instance header
char *ty = strchr(line,':');
if (ty==NULL) { CONF_PARSER_ERR("(line %i) error parsing '%s':\n %s missing ':' separating instance name and type!",lineNr,inputPath,line); }
ty[0] = 0; ty++;
char *tmp = strchr(ty,':');
if (tmp!=NULL) { CONF_PARSER_ERR("(line %i) error parsing '%s':\n ':' cannot appear in config type name!",lineNr,inputPath,line); }
tmp = strchr(ty,']');
if (tmp==NULL) { CONF_PARSER_ERR("(line %i) error parsing '%s':\n %s missing ']' after instance type!",lineNr,inputPath,line); }
tmp[0] = 0;
char *ins = line+1;
idx = addInst(ins,ty);
//free(line); line = NULL;
} else if ((len>1)&&(line[0] == '\\')&&(line[1] == '{')&&(line[len]=='}')) { // include config file
line[len]=0;
const char*fn = line+2;
openInput(fn,&idx);
} else {
addLine(idx,line,lineNr);
}
}
}
if (origline != NULL) { free(origline); line = NULL; }
} while (read != (size_t)-1); // XXXX
fclose(in);
if (line != NULL) { free(line); line = NULL; }
SMILE_MSG(3,"successfully read config file '%s'",inputPath);
if (idx0!=NULL) *idx0=idx;
return 1;
}
cFileConfigReader::~cFileConfigReader()
{
int i;
if (inst != NULL) {
for (i=0; i<nInst; i++) {
if (inst[i].name != NULL) free(inst[i].name);
if (inst[i].type != NULL) free(inst[i].type);
if (inst[i].lineNr != NULL) free(inst[i].lineNr);
if (inst[i].lines != NULL) {
int j;
for (j=0; j<inst[i].N; j++) {
if (inst[i].lines[j] != NULL) free(inst[i].lines[j]);
}
free(inst[i].lines);
}
}
free(inst);
}
}
char ** cFileConfigReader::findInstancesByTypeName(const char *_typename, int *N) /* returns names (and no.) of instances of type "typename" */
{
int i;
char **insts=NULL;
int n=0;
if (_typename == NULL) return NULL;
if (N == NULL) return NULL;
SMILE_DBG(3,"cFileConfigReader::findInstancesByTypeName: typename=%s",_typename);
for (i=0; i<nInst; i++) {
if (!strcmp(inst[i].type,_typename)) n++;
}
*N = n;
insts = (char **) calloc(1,sizeof(char*)*n);
n=0;
for (i=0; i<nInst; i++) {
if (!strcmp(inst[i].type,_typename)) {
insts[n++] = strdup(inst[i].name);
SMILE_DBG(3,"found inst : '%s'",inst[i].name);
}
}
return insts;
}
/*
format of a config line:
name.name[nr].name.name{str}.name = val;val;val
comments: line begins with ; or # or //
name may not contain: [ ] . : = ; , \
val can be either numeric, string, or config instance reference: 0.00 blah \in[instname]
or commandline option reference: \cm[long(short){dflt}:description] (to add a new option)
or cmdline reference : \cm[long] (to reference an existing option)
or value of another field : $fieldname
val may not contain ; or $ or \ as first character
TODO later: add \; and \$ and \\ for quoting
TODO??? array by ; ..!
*/
/* parse lines of an instance...*/
ConfigInstance *cFileConfigReader::getInstance(const char *_instname, const ConfigType *_type, cConfigManager *cman) /* get an instance with name _instname */
{
ConfigInstance *ret = new ConfigInstance( _instname, _type, 0 );
if (ret == NULL) OUT_OF_MEMORY;
int i,idx;
// find instance index
SMILE_DBG(3,"cFileConfigReader::getInstance: instname=%s",_instname);
for (idx=0; idx<nInst; idx++) {
if (!strcmp(inst[idx].name,_instname)) break;
}
SMILE_DBG(2,"cFileConfigReader::getInstance: instname=%s -> idx=%i",_instname,idx);
if (idx >= nInst) CONF_PARSER_ERR("cFileConfigReader::getInstance: requested instance name '%s' not found in config file!",_instname);
//now go through instance and parse lines
for (i=0; i<inst[idx].N; i++) {
char *line = strdup(inst[idx].lines[i]);
int lineNr = inst[idx].lineNr[i];
char *origline = line; // we use this later in the call to free();
if (line==NULL) OUT_OF_MEMORY;
SMILE_DBG(5,"cFileConfigReader::getInstance: parsing line no. %i\n %s",lineNr,line);
// remove CR(+LF) at end
int l = (int)strlen(line)-1;
if (line[l] == '\n') { line[l] = 0; l--; }
if (line[l] == '\r') { line[l] = 0; l--; }
//remove spaces at end and beginning
while (((line[l] == ' ')||(line[l] == '\t'))&&(l>=0)) { line[l] = 0; l--; }
while (((line[0] == ' ')||(line[0] == '\t'))&&(l>=0)) { line[0] = 0; line++; l--; }
if (l<0) { if (origline != NULL) free(origline); continue; } // skip empty lines
// check for comment:
if ((line[0] == '#')||(line[0]==';')||((l>0)&&(line[0]=='/')&&(line[1]=='/')))
{ if (origline != NULL) free(origline); continue; } // skip commented-out lines
// TODO: search for \in[] -> link to instance
// return NULL and name of instance to link to
// split at FIRST =
char *field=line;
char *value;
value=strchr(line,'=');
if ( value == NULL ) CONF_PARSER_ERR("(line %i) cFileConfigReader::getInstance: missing '=' in line %i '%s' of instance '%s'",lineNr,i,line,inst[idx].name);
value[0]=0;
value++;
int arrT=0,arrN=-1; char *arrS=NULL;
// remove basename (instance name)
field = strchr(line,'.');
if (field == NULL) field = line;//CONF_PARSER_ERR("cFileConfigReader::getInstance: missing field name in line '%s'",line);
else {
field[0] = 0;
// check if first part of line really was _instname..
if (strcmp(line,_instname)) {
field[0] = '.';
field = line;
} else { field++; }
}
l=(int)strlen(field)-1;
// remove whitespaces at end of fieldname
while (((field[l] == ' ')||(field[l] == '\t'))&&(l>0)) { field[l] = 0; l--; }
// get field basename:
/*
char *fieldbn = NULL;
char *nex = strchr(field,'.');
if (nex != NULL) {
nex[0] = 0;
fieldbn = strdup(field);
nex[0] = '.';
} else {
fieldbn = strdup(field);
}
*/
// check for array basename AND array type of field
if (l>=0) {
SMILE_DBG(5," field=%s",field);
if (field[l] == ']') { // numeric or associative array
field[l] = 0;
char * v = strrchr(field,'[');
if (v == NULL) CONF_PARSER_ERR("(line %i) cFileConfigReader::getInstance: execess ] found at end of field name!",lineNr);
v++;
//TODO: associative array [] support
// int val=0;
char *eptr=NULL;
long rn = strtol(v,&eptr,0);
if (strlen(v) <= 0) CONF_PARSER_ERR("(line %i) cFileConfigReader::getInstance: nothing specified in [] as array index!",lineNr);
if ((eptr!=NULL)&&(eptr[0]!=0)) { // invalid characters -> no number!
arrT=2; arrS = strdup(v);
} else {
// int rn = sscanf(v,"%i",&val);
// if (rn!=1) CONF_PARSER_ERR("(line %i) cFileConfigReader::getInstance: no number specified in [] as array index!");
arrT=1; //arrN = val;
arrN=rn; // XXXX
}
field[l] = ']';
}
/*
else if (field[l] == '}') { // associative string array
field[l] = 0;
char * v = strrchr(field,'{');
if (v == NULL) CONF_PARSER_ERR("(line %i) cFileConfigReader::getInstance: execess } found at end of field name!");
v++;
int val;
int rn = strlen(v);
if (v<=0) CONF_PARSER_ERR("(line %i) cFileConfigReader::getInstance: no name specified in {} as array index!");
arrT=2; arrS = strdup(v);
field[l] = '}';
}
*/
} else {
CONF_PARSER_ERR("(line %i) cFileConfigReader::getInstance: invalid field name '%s'",lineNr,field);
}
// parse value (remove pre and post whitespaces)
l = (int)strlen(value);
//remove spaces at end and beginning
while (((value[l] == ' ')||(value[l] == '\t'))&&(l>0)) { value[l] = 0; l--; }
while (((value[0] == ' ')||(value[0] == '\t'))&&(l>0)) { value[0] = 0; value++; l--; }
if (l==0) CONF_PARSER_ERR("(line %i) cFileConfigReader::getInstance: empty value in line %i '%s' of instance '%s'",lineNr,i,line,inst[idx].name);
SMILE_DBG(5," value=%s",value);
// check for presence of unquoted ; => initialize array values of numeric index array, if array type matches )
char *a = strchr(value,';');
if ((a>value)&&(*(a-1)!='\\')&&(a != NULL)) { // this should enable quoting of ; via \ ... ???
arrT=10;arrN=-1;
}
if (arrS != NULL) free(arrS);
// if (arrT==10) {
// TODO: split values, convert each value, and save in array element
// SMILE_ERR(1,"(line %i) arrT==10 not yet implemented! (array elements split by ';')",lineNr);
// } else
{
/* optional: set *in to address of ConfigInstance containig the found value/field
and *n to index of field in that instance.
(only valid, if not NULL is returned)
*/
int n,aIdx;
const ConfigType *tp=NULL;
int h = _type->findFieldH(field, &n, &tp, &aIdx, NULL);
int ty;
if (tp != NULL) {
ty = tp->getType(n);
} else {
// TODO: Error!!!
SMILE_ERR(4,"type not found!");
ty=-1;
}
SMILE_DBG(4,"type = %i",ty);
if (ty>=CFTP_ARR) {
if (arrT == 0) //CONF_PARSER_ERR("(line %i) expected array index for array type",lineNr,line);
{
SMILE_WRN(3,"(line %i) array type field with only one element and no array index in [], assuming arrT=10 and N=1",lineNr);
arrT=10;
}
ty-=(CFTP_ARR+1);
}
int nFields = 1;
char **valuefield = NULL;
if (arrT==10) {
// count number of unquoted ';' separators
int i;
//while (value[0] == ';') { value++; l--; }
//while (value[l] == ';') { value[l]=0; l--; }
for (i=1; i<=l; i++) { if ((value[i] == ';')&&(value[i-1] != '\\')&&(i!=l)) nFields++; if (value[i] == 0) break; }
// split into field array..
valuefield = (char**)calloc(1,sizeof(char*)*nFields);
i=0;
do {
if (i>=nFields) break;
a = strchr(value,';');
if (a!=NULL) *a=0;
valuefield[i]=value;
int lll = (int)strlen(valuefield[i]);
// remove spaces at beginning and end
while ( (lll>=0)&& ((valuefield[i][0]==' ')||(valuefield[i][0]=='\t')) ) { valuefield[i]++; lll--; }
while ( (lll>=0)&& ((valuefield[i][lll-1]==' ')||(valuefield[i][lll-1]=='\t')) ) { valuefield[i][lll-1]=0; lll--; }
if (lll<=0) valuefield[i]=NULL;
if (a!=NULL) {
value=a+1;
}
i++;
} while (a!=NULL);
}
int idx;
for( idx=0; idx < nFields; idx++) {
if (arrT == 10) value = valuefield[idx] ; //...
// resolve commandline references RIGHT HERE:: :-)
char *tmpstr=NULL;
if (value == NULL) continue;
/* commandline option reference: \cm[long(short){dflt}:description] */
int vl=(int)strlen(value);
if (vl>=5) {
if ((value[0]=='\\')&&(value[1]=='c')&&(value[2]=='m')&&(value[3]=='[')&&(value[vl-1]==']')) { // \cm[*]
if (cmdparser != NULL) {
char *_long = value+4;
char *_short = strchr(value,'(');
char *_dflt = strchr(value,'{');
char *_descr = strchr(value,':');
if (_short!=NULL) {
*_short = 0;
_short++;
char *_tmp = strchr(_short,')');
if (_tmp == NULL) { CONF_MANAGER_ERR("line %i : missing ) in commandline reference '%s'",lineNr,value); }
else *_tmp = 0;
if (strlen(_short) > 1) { CONF_MANAGER_ERR("line %i : short option () in commandline reference '%s' is longer than one character!",lineNr,value); }
}
if (_dflt!=NULL) {
*_dflt = 0;
_dflt++;
char *_tmp = strchr(_dflt,'}');
if (_tmp == NULL) { CONF_MANAGER_ERR("line %i : missing } in commandline reference '%s'",lineNr,value); }
else *_tmp = 0;
if (strlen(_dflt) < 0) { CONF_MANAGER_ERR("line %i : dflt value {} in commandline reference '%s' is too short!",lineNr,value); }
}
if (_descr!=NULL) {
*_descr = 0;
_descr++;
char *_tmp = strchr(_descr,']');
if (_tmp == NULL) { CONF_MANAGER_ERR("line %i : missing ] at end of commandline reference '%s'",lineNr,value); }
else *_tmp = 0;
if (strlen(_descr) < 0) { CONF_MANAGER_ERR("line %i : description :..] in commandline reference '%s' is too short!",lineNr,value); }
}
char *_tmp = strchr(_long,']');
if (_tmp != NULL) { *_tmp = 0; }
char __s=0;
if (_short!=NULL) __s = *_short;
if ( (_dflt==NULL)&&(_descr==NULL) ) { // old option
// do nothing...
} else { // new option
if (ty==CFTP_NUM) {
char *ep=NULL;
double _dfltD = strtod(_dflt,&ep);
if ((_dfltD==0.0)&&(ep==_dflt)) { CONF_MANAGER_ERR("line %i : invalid numerical default value for commandline reference '%s'",lineNr,value); }
cmdparser->addDouble( _long, __s, _descr, _dfltD );
} else {
cmdparser->addStr( _long, __s, _descr, _dflt );
}
// if new option was added : rerun doParse
cmdparser->doParse(1); // ignore duplicates...
}
if (ty==CFTP_NUM) {
tmpstr = myvprint("%f",cmdparser->getDouble(_long));
} else {
tmpstr = strdup(cmdparser->getStr(_long));
}
value = tmpstr;
} else {
CONF_MANAGER_ERR("commandline reference specified in line %i, however no commandline parser is present!",lineNr);
}
}
}
int mtmp=0;
vl = (int)strlen(value);
for (mtmp=1; mtmp<vl; mtmp++) {
if (value[mtmp-1]=='\\') {
if ( (value[mtmp]==';')||(value[mtmp]=='\\') ) {
// remove value[a-1] and move all chars to left, vl--
int aa;
for (aa=mtmp-1; aa<vl; aa++) {
value[aa] = value[aa+1];
}
value[vl--] = 0;
}
}
}
// ---
ConfigValue *cv=NULL;
double f;
// convert value according to type...
switch (ty) {
//TODO: resolve variable references (i.e. $xxxx)
// introduce ConfigValueRef type... which will be replaced once all instances have been read
case CFTP_NUM:
//sscanf(value,"%f",&f);
char *eptr;
// cv = new ConfigValueRef(REF_NUM,name)
f = strtod(value,&eptr);
if ((f==0.0)&&(eptr == value)) { CONF_PARSER_ERR("(line %i) cFileConfigReader::getInstance: error parsing numeric value '%s'",lineNr,value); }
SMILE_DBG(5,"parsing numeric value: (field: '%s') val=%f (str: '%s')",field,f,value);
cv = new ConfigValueNum(f);
break;
case CFTP_STR:
// cv = new ConfigValueRef(REF_STR,name)
cv = new ConfigValueStr(value);
SMILE_DBG(5,"set string value : '%s'",cv->getStr());
break;
case CFTP_CHR:
// cv = new ConfigValueRef(REF_CHR,name)
if (strlen(value) > 1) SMILE_WRN(2,"(line %i) cFileConfigReader::getInstance: char field has length > 1 ('%s'='%s')",lineNr,field,value);
cv = new ConfigValueChr(value[0]);
SMILE_DBG(5,"set char value : '%c'",cv->getChar());
break;
case CFTP_OBJ:
// TODO!! resolve object references '\instancename'
// also use ConfigValueRef type here...
// cv = new ConfigValueRef(REF_INST,name)
// if (cman!=NULL) in = cman->getInstance(iname);
// cv = new ConfigValueObj( in , 0 );
/*
if (strlen(value) > 1) SMILE_WRN(2,"cFileConfigReader::getInstance: char field has length > 1 ('%s'='%s')",field,value);
cv = new ConfigValueChr(value[0]);
SMILE_DBG(5,"set char value : '%c'",cv->getChr());
break;
*/
default:
CONF_PARSER_ERR("(line %i) cFileConfigReader::getInstance: unknown field type (name '%s') (in ConfigType '%s') ty=%i",lineNr,field,_type->getName(),ty);
//CONF_PARSER_ERR("unknown type OR cannot convert value");
}
if (tmpstr!=NULL) free(tmpstr);
// TODO: variables, references, placeholders....
// use setValue() to set the value
if (arrT == 10) {
char *c = myvprint("%s[%i]",field,idx);
ret->setValue(cv, -1, c);
free(c);
} else {
ret->setValue(cv, -1, field);
}
} // END for nFields
// free valuefield:
if (valuefield != NULL) free(valuefield);
//const ConfigValue *v = ret->getValue(-1,field);
//SMILE_DBG(5,"str = '%s'",v->getStr());
}
free(origline);
}
return ret;
}
/******************************************************************************/
cConfigManager::cConfigManager(cCommandlineParser *_parser) :
nReaders(0),
nInst(0),
nTypes(0),
cmdparser(_parser)
{
defaults = (ConfigInstance **)calloc(1,sizeof(ConfigInstance *)*NEL_ALLOC_BLOCK);
if (defaults != NULL) nTypesAlloc = NEL_ALLOC_BLOCK;
else nTypesAlloc = 0;
inst = (ConfigInstance **)calloc(1,sizeof(ConfigInstance *)*NEL_ALLOC_BLOCK);
if (inst != NULL) nInstAlloc = NEL_ALLOC_BLOCK;
else nInstAlloc = 0;
reader = (cConfigReader **)calloc(1,sizeof(cConfigReader *)*NEL_ALLOC_BLOCK);
//readerPriority = (int *)calloc(1,sizeof(int)*NEL_ALLOC_BLOCK);
// if ((reader != NULL)&&(readerPriority!=NULL)) {
if (reader != NULL) {
nReadersAlloc = NEL_ALLOC_BLOCK;
} else {
if (reader != NULL) free(reader);
// if (readerPriority != NULL) free(readerPriority);
nReadersAlloc = 0;
}
}
/* order in which readers are added determines their priority,
readers added last, will overwrite values from readers added prior to them */
int cConfigManager::addReader(cConfigReader *_reader)
{
if (_reader == NULL) return -1;
if (nReaders >= nReadersAlloc) { // realloc if true
cConfigReader **tmp = (cConfigReader **)realloc(reader, sizeof(cConfigReader*) * (nReadersAlloc+NEL_ALLOC_BLOCK));
if (tmp != NULL) {
reader = tmp;
nReadersAlloc += NEL_ALLOC_BLOCK;
} else { OUT_OF_MEMORY; }
}
_reader->setCmdparser(cmdparser);
reader[nReaders] = _reader;
return nReaders++;
}
int cConfigManager::addInstance(ConfigInstance *_inst)
{
if (_inst == NULL) return -1;
if (nInst >= nInstAlloc) { // realloc if true
ConfigInstance **tmp = (ConfigInstance **)realloc(inst, sizeof(ConfigInstance*) * (nInstAlloc+NEL_ALLOC_BLOCK));
if (tmp != NULL) {
inst = tmp;
nInstAlloc += NEL_ALLOC_BLOCK;
} else { OUT_OF_MEMORY; }
}
inst[nInst] = _inst;
return nInst++;
}
int cConfigManager::deleteInstance(const char *_instname) /* deletes instance "_instname" */
{
int idx = findInstance(_instname);
if (idx >= 0) {
delete inst[idx];
int i;
for (i=idx; i<nInst-1; i++) {
inst[i] = inst[i+1];
}
inst[i] = NULL;
nInst--;
return 1;
} else {
SMILE_ERR(1,"cannot delete instance '%s' -> not found!",_instname);
}
return 0;
}
/* return value is index of instance or -1 if instance was not found */
int cConfigManager::findInstance(const char *_instname) const
{
int i;
if (_instname == NULL) {
SMILE_DBG(2,"findInstance called with _instname = NULL!!");
return -1;
}
for (i=0; i<nInst; i++) {
SMILE_DBG(5,"findInstance: comparing instname ('%s') with '%s' for inst %i",_instname,inst[i]->getName(),i);
if (!strcmp(inst[i]->getName(),_instname)) {
SMILE_DBG(5,"findInstance: match (%i)!",i);
return i;
}
}
return -1;
}
/* return value is index of instance or -1 if instance was not found */
int cConfigManager::findType(const char *_typename) const
{
int i;
if (_typename == NULL) return -1;
for (i=0; i<nTypes; i++) {
if (defaults[i]->getType() != NULL) {
if (!strcmp(defaults[i]->getTypeName(),_typename)) return i;
}
}
return -1;
}
const ConfigType * cConfigManager::getTypeObj(int n) const
{
if ((n>=0)&&(n<nTypes)) {
if (defaults[n] != NULL) return defaults[n]->getType();
}
return NULL;
}
const ConfigType *cConfigManager::getTypeObj(const char *_typename) const // hierarchical type resolving...
{
if (_typename != NULL) {
char *b=NULL;
const char *s=NULL;
const ConfigType *tp=NULL;
int h = instNameSplit(_typename, &b, &s);
if (b!=NULL) {
tp = getTypeObj(findType(b));
free(b); b=NULL;
}
if (tp !=NULL) {
while (h==1) {
h = instNameSplit(s, &b, &s);
if (b!=NULL) {
int t = tp->findField(b);
free(b); b=NULL;
tp = tp->getTypeObj(t);
if (tp==NULL) {
SMILE_WRN(4,"getType: cannot find configType for '%s' (at 's=%s')",_typename,s);
return NULL;
}
} else {
CONF_MANAGER_ERR("getType: empty base returned by instNameSplit! (for config type '%s')",_typename);
}
}
return tp;
} else {
SMILE_WRN(4,"getType: cannot find configType base of '%s'",_typename);
return NULL;
}
}
return NULL;
}
int cConfigManager::updateInstance(ConfigInstance *_inst)
{
if (_inst == NULL) return -1;
int update = 0;
int idx = findInstance(_inst->getName());
if (idx == -1) {
// new instance, check for default instance in *defaults
SMILE_DBG(3,"updateInstance: adding new instance '%s'",_inst->getName());
const ConfigType *tmpType = _inst->getType();
int tidx = findType(tmpType->getName());
if (tidx == -1) {
// error: unknown type! (can not be...)
CONF_MANAGER_ERR("updateInstance: trying to add instance (%s) of unknown type (%s) to configManager",_inst->getName(),tmpType->getName());
} else {
// copy and "update" default:
_inst->missingFrom(defaults[tidx]);
addInstance(_inst);
}
} else {
//update only
inst[idx]->updateWith(_inst);
update = 1;
}
return update;
}
/* register an instance specifying the type and the default values */
/* the instance MUST contain a type, the instance must be created with freeType=0
the instance will be freed by the configManager */
int cConfigManager::registerType(ConfigInstance *_type)
{
if (_type == NULL) return -1;
// check for unique name... TODO:
int existing = findType(_type->getName());
if (existing >= 0) {
SMILE_WRN(3,"ConfigType '%s' is already registered. Exiting cConfigManager::registerType",_type->getName());
return existing;
}
if (nTypes >= nTypesAlloc) { // realloc if true
ConfigInstance **tmp = (ConfigInstance **)realloc(defaults, sizeof(ConfigInstance*) * (nTypesAlloc+NEL_ALLOC_BLOCK));
if (tmp != NULL) {
defaults = tmp;
nTypesAlloc += NEL_ALLOC_BLOCK;
} else { OUT_OF_MEMORY; }
}
defaults[nTypes] = _type;
return nTypes++;
}
void cConfigManager::readConfig()
{ /* read the config, after readers and types have been registered */
// find instance names for all types in all readers
int i,r,t;
for (t=0; t<nTypes; t++) { // foreach config type
const ConfigType *typ = defaults[t]->getType();
for (r=0; r<nReaders; r++) { // foreach reader, in priority order
int _n;
char ** inames = reader[r]->findInstances(typ, &_n); // find instances
SMILE_DBG(4,"found %i instance(s) for type %s",_n,typ->getName());
if (inames != NULL) {
for (i=0; i<_n; i++) { // foreach instance of the current reader
SMILE_DBG(5,"reading configInstance %i ('%s') from reader %i",i,inames[i],r);
ConfigInstance *rd = reader[r]->getInstance(inames[i], typ);
/* #ifdef DEBUG
const ConfigValue *v=rd->getValue(-1,"age");
if (v!=NULL) {
SMILE_DBG(4,"readConfig: inst->getValue('age') = %i",v->getInt());
}
#endif*/
// TODO: if getInstance returned NULL , check for instance link... remember link
// now add the instance to the Manager
if (updateInstance(rd))
{ delete rd; }
free(inames[i]);
}
free(inames);
} else {
SMILE_DBG(4,"findInstances returned NULL pointer to instnames array!");
}
}
}
// TODO: now, for each instance: resolve wildcards, %cmdline_xx%, etc. (except for %instname% )
// TODO: scan for instance links
// ... and for variable links (... difficult...)
}
/* no hierarchical names are supported... */
ConfigInstance * cConfigManager::getInstance(const char *_instname)
{
const char * _subname;
char * _instbasename=NULL;
int h = instNameSplit(_instname, &_instbasename, &_subname);
int idx = findInstance(_instbasename);
if (_instbasename != NULL) free(_instbasename);
if (idx >= 0) {
if (h) { // search through the hierarchy
CONF_MANAGER_ERR("cConfigManager::getInstance: cannot get sub-instance, use getValue instead!");
} else {
return inst[idx];
}
}
return NULL;
}
const ConfigValue * cConfigManager::getValue(const char *_name) const
{
const char * _subname=NULL;
char * _instbasename=NULL;
SMILE_DBG(4,"cConfigManager::getValue: _name = '%s'",_name);
int h = instNameSplit(_name, &_instbasename, &_subname);
SMILE_DBG(4,"cConfigManager::getValue: instNameSplit returned %i",h);
int idx = findInstance(_instbasename);
if (_instbasename != NULL) free(_instbasename);
if (idx >= 0) {
if (h) { // search through the hierarchy
return inst[idx]->getValue(-1,_subname);
} else {
CONF_MANAGER_ERR("field name not given in name '%s'",_name);
}
} else CONF_MANAGER_ERR("base instance of field '%s' not found in configManager!",_name);
return NULL;
}
int cConfigManager::getArraySize(const char *_name) const
{
const ConfigValue *v = getValue(_name);
if (v!=NULL) {
if (v->getType() >= CFTP_ARR) {
return v->getSize();
} else {
CONF_MANAGER_ERR("cannot get size of array field '%s', this field is not an array (type=%i)",_name,v->getType());
}
}
return -1;
}
char ** cConfigManager::getArrayKeys(const char *_name, int *N) const
{
const ConfigValue *v = getValue(_name);
if (v!=NULL) {
if (v->getType() >= CFTP_ARR) {
if (N!=NULL) *N = v->getSize();
return v->getAAkeys();
} else {
CONF_MANAGER_ERR("cannot get names (and size) of array field '%s', this field is not an array (type=%i)",_name,v->getType());
}
}
if (N!=NULL) *N=0;
return NULL;
}
void cConfigManager::printTypeHelp(int _subtype, const char *selection)
{
int i;
const ConfigType * tp;
if (defaults == NULL) return;
for (i=0; i<nTypes; i++) {
tp = defaults[i]->getType();
if (tp != NULL) {
if (selection != NULL) {
//printf("N: %s Sel: %s Strl(sel): %i\n",tp->getName(), selection, strlen(selection));
if (!strncasecmp(tp->getName(), selection, strlen(selection)) ) {
tp->printTypeHelp(NULL,_subtype);
}
} else {
tp->printTypeHelp(NULL,_subtype);
}
}
}
}
cConfigManager::~cConfigManager()
{
int i;
//free instances
if (inst != NULL) {
for (i=0; i<nInst; i++) {
if (inst[i] != NULL) { delete inst[i]; }
}
free(inst);
}
nInstAlloc=0; nInst=0;
//free types
if (defaults != NULL) {
for (i=0; i<nTypes; i++) {
if (defaults[i] != NULL) { delete defaults[i]; }
}
free(defaults);
}
nTypesAlloc=0; nTypes=0;
//free readers
if (reader != NULL) {
for (i=0; i<nReaders; i++) {
if (reader[i] != NULL) { delete reader[i]; }
}
free(reader);
}
nReadersAlloc=0; nReaders=0;
}
| 33.327626 | 198 | 0.586634 | [
"object"
] |
a08b3fb13f50d15c50c48d8dbfcee211af631437 | 47,576 | cpp | C++ | jni/guacd/cairo/src/skia/cairo-skia-context.cpp | maqiangddb/AndroidVncServer | 3bd4414ff4a84cd7407493364078dc4d77d4e5ad | [
"MIT"
] | 2 | 2016-05-26T06:54:21.000Z | 2021-05-09T18:05:50.000Z | addons/cairo/src/skia/cairo-skia-context.cpp | alvatar/sphere-fusion | f0bd78be9bbd42955677f3b8d73ccce167f7e486 | [
"Zlib"
] | null | null | null | addons/cairo/src/skia/cairo-skia-context.cpp | alvatar/sphere-fusion | f0bd78be9bbd42955677f3b8d73ccce167f7e486 | [
"Zlib"
] | 1 | 2019-03-16T08:46:46.000Z | 2019-03-16T08:46:46.000Z | /* -*- Mode: c; c-basic-offset: 4; indent-tabs-mode: t; tab-width: 8; -*- */
/* cairo - a vector graphics library with display and print output
*
* Copyright © 2002 University of Southern California
* Copyright © 2005 Red Hat, Inc.
* Copyright © 2010 Intel Corporation
*
* This library is free software; you can redistribute it and/or
* modify it either under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation
* (the "LGPL") or, at your option, under the terms of the Mozilla
* Public License Version 1.1 (the "MPL"). If you do not alter this
* notice, a recipient may use your version of this file under either
* the MPL or the LGPL.
*
* You should have received a copy of the LGPL along with this library
* in the file COPYING-LGPL-2.1; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
* You should have received a copy of the MPL along with this library
* in the file COPYING-MPL-1.1
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (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.mozilla.org/MPL/
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY
* OF ANY KIND, either express or implied. See the LGPL or the MPL for
* the specific language governing rights and limitations.
*
* The Original Code is the cairo graphics library.
*
* The Initial Developer of the Original Code is University of Southern
* California.
*
* Contributor(s):
* Carl D. Worth <cworth@cworth.org>
* Chris Wilson <chris@chris-wilson.co.uk>
*/
#include "cairoint.h"
#include "cairo-private.h"
#include "cairo-error-private.h"
#include "cairo-arc-private.h"
#include "cairo-backend-private.h"
#include "cairo-default-context-private.h"
#include "cairo-freed-pool-private.h"
#include "cairo-gstate-private.h"
#include "cairo-image-surface-inline.h"
#include "cairo-path-private.h"
#include "cairo-pattern-private.h"
#include "cairo-skia-private.h"
#include "cairo-surface-backend-private.h"
#include <SkShader.h>
#include <SkColorShader.h>
#include <SkGradientShader.h>
#include <SkDashPathEffect.h>
#if !defined(INFINITY)
#define INFINITY HUGE_VAL
#endif
#if (CAIRO_FIXED_BITS == 32) && (CAIRO_FIXED_FRAC_BITS == 16) && defined(SK_SCALAR_IS_FIXED)
# define CAIRO_FIXED_TO_SK_SCALAR(x) (x)
#elif defined(SK_SCALAR_IS_FIXED)
/* This can be done better, but this will do for now */
# define CAIRO_FIXED_TO_SK_SCALAR(x) SkFloatToScalar(_cairo_fixed_to_double(x))
#else
# define CAIRO_FIXED_TO_SK_SCALAR(x) SkFloatToScalar(_cairo_fixed_to_double(x))
#endif
#define UNSUPPORTED
static freed_pool_t context_pool;
static void
_cairo_skia_context_destroy (void *abstract_cr)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cr->path->reset ();
cr->paint->reset ();
delete cr->canvas;
cairo_surface_destroy (&cr->target->image.base);
cairo_surface_destroy (&cr->original->image.base);
if (cr->source != NULL) {
if (cr->source_image != NULL) {
_cairo_surface_release_source_image (cr->source, cr->source_image, cr->source_extra);
cr->source_image = NULL;
}
cairo_surface_destroy (cr->source);
cr->source = NULL;
}
_cairo_fini (&cr->base);
_freed_pool_put (&context_pool, cr);
}
static cairo_surface_t *
_cairo_skia_context_get_original_target (void *abstract_cr)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
return &cr->original->image.base;
}
static cairo_surface_t *
_cairo_skia_context_get_current_target (void *abstract_cr)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
return &cr->target->image.base;
}
static cairo_status_t
_cairo_skia_context_save (void *abstract_cr)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cr->canvas->save ();
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_restore (void *abstract_cr)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cr->canvas->restore ();
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_push_group (void *abstract_cr, cairo_content_t content)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cairo_surface_t *group_surface;
cairo_status_t status;
int width, height;
//clip = _cairo_gstate_get_clip (cr->gstate);
width = cr->target->image.width;
height = cr->target->image.height;
group_surface = cr->target->image.base.backend->create_similar (&cr->target->image.base,
content, width, height);
#if 0
/* Set device offsets on the new surface so that logically it appears at
* the same location on the parent surface -- when we pop_group this,
* the source pattern will get fixed up for the appropriate target surface
* device offsets, so we want to set our own surface offsets from /that/,
* and not from the device origin. */
cairo_surface_set_device_offset (group_surface,
parent_surface->device_transform.x0 - extents.x,
parent_surface->device_transform.y0 - extents.y);
/* If we have a current path, we need to adjust it to compensate for
* the device offset just applied. */
_cairo_path_fixed_transform (cr->path,
&group_surface->device_transform);
#endif
status = _cairo_skia_context_save (cr);
if (unlikely (status)) {
cairo_surface_destroy (group_surface);
return status;
}
cairo_surface_destroy (&cr->target->image.base);
cr->target = (cairo_skia_surface_t *) group_surface;
return CAIRO_STATUS_SUCCESS;
}
static cairo_pattern_t *
_cairo_skia_context_pop_group (void *abstract_cr)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cairo_surface_t *group_surface;
cairo_pattern_t *group_pattern;
cairo_status_t status;
group_surface = cairo_surface_reference (&cr->target->image.base);
status = _cairo_skia_context_restore (cr);
if (unlikely (status)) {
group_pattern = _cairo_pattern_create_in_error (status);
goto done;
}
group_pattern = cairo_pattern_create_for_surface (group_surface);
status = group_pattern->status;
if (unlikely (status))
goto done;
#if 0
_cairo_gstate_get_matrix (cr->gstate, &group_matrix);
/* Transform by group_matrix centered around device_transform so that when
* we call _cairo_gstate_copy_transformed_pattern the result is a pattern
* with a matrix equivalent to the device_transform of group_surface. */
if (_cairo_surface_has_device_transform (group_surface)) {
cairo_pattern_set_matrix (group_pattern, &group_surface->device_transform);
_cairo_pattern_transform (group_pattern, &group_matrix);
_cairo_pattern_transform (group_pattern, &group_surface->device_transform_inverse);
} else {
cairo_pattern_set_matrix (group_pattern, &group_matrix);
}
/* If we have a current path, we need to adjust it to compensate for
* the device offset just removed. */
_cairo_path_fixed_transform (cr->path,
&group_surface->device_transform_inverse);
#endif
done:
cairo_surface_destroy (group_surface);
return group_pattern;
}
static inline cairo_surface_t *
surface_from_pattern (const cairo_pattern_t *pattern)
{
return (reinterpret_cast <const cairo_surface_pattern_t *> (pattern))->surface;
}
static inline bool
surface_to_sk_bitmap (cairo_surface_t *surface, SkBitmap& bitmap)
{
cairo_image_surface_t *img = (cairo_image_surface_t *) surface;
SkBitmap::Config config;
bool opaque;
if (unlikely (! format_to_sk_config (img->format, config, opaque)))
return false;
bitmap.reset ();
bitmap.setConfig (config, img->width, img->height, img->stride);
bitmap.setIsOpaque (opaque);
bitmap.setPixels (img->data);
return true;
}
static inline SkMatrix
matrix_to_sk (const cairo_matrix_t& mat)
{
SkMatrix skm;
skm.reset ();
skm.set (SkMatrix::kMScaleX, SkFloatToScalar (mat.xx));
skm.set (SkMatrix::kMSkewX, SkFloatToScalar (mat.xy));
skm.set (SkMatrix::kMTransX, SkFloatToScalar (mat.x0));
skm.set (SkMatrix::kMSkewY, SkFloatToScalar (mat.yx));
skm.set (SkMatrix::kMScaleY, SkFloatToScalar (mat.yy));
skm.set (SkMatrix::kMTransY, SkFloatToScalar (mat.y0));
/*
skm[6] = SkFloatToScalar (0.0);
skm[7] = SkFloatToScalar (0.0);
skm[8] = SkFloatToScalar (1.0); -- this isn't right, it wants a magic value in there that it'll set itself. It wants Sk_Fract1 (2.30), not Sk_Scalar1
*/
return skm;
}
static inline SkMatrix
matrix_inverse_to_sk (const cairo_matrix_t& mat)
{
cairo_matrix_t inv = mat;
cairo_status_t status = cairo_matrix_invert (&inv);
assert (status == CAIRO_STATUS_SUCCESS);
return matrix_to_sk (inv);
}
static SkShader::TileMode
extend_to_sk (cairo_extend_t extend)
{
static const SkShader::TileMode modeMap[] = {
SkShader::kClamp_TileMode, // NONE behaves like PAD, because noone wants NONE
SkShader::kRepeat_TileMode,
SkShader::kMirror_TileMode,
SkShader::kClamp_TileMode
};
return modeMap[extend];
}
static inline SkColor
color_to_sk (const cairo_color_t& c)
{
/* Need unpremultiplied 1-byte values */
return SkColorSetARGB ((U8CPU) (c.alpha * 255),
(U8CPU) (c.red * 255),
(U8CPU) (c.green * 255),
(U8CPU) (c.blue * 255));
}
static inline SkColor
color_stop_to_sk (const cairo_color_stop_t& c)
{
/* Need unpremultiplied 1-byte values */
return SkColorSetARGB ((U8CPU) (c.alpha * 255),
(U8CPU) (c.red * 255),
(U8CPU) (c.green * 255),
(U8CPU) (c.blue * 255));
}
static SkShader*
source_to_sk_shader (cairo_skia_context_t *cr,
const cairo_pattern_t *pattern)
{
SkShader *shader = NULL;
if (pattern->type == CAIRO_PATTERN_TYPE_SOLID) {
cairo_solid_pattern_t *solid = (cairo_solid_pattern_t *) pattern;
return new SkColorShader (color_to_sk (solid->color));
} else if (pattern->type == CAIRO_PATTERN_TYPE_SURFACE) {
cairo_surface_t *surface = surface_from_pattern (pattern);
cr->source = cairo_surface_reference (surface);
if (surface->type == CAIRO_SURFACE_TYPE_SKIA) {
cairo_skia_surface_t *esurf = (cairo_skia_surface_t *) surface;
shader = SkShader::CreateBitmapShader (*esurf->bitmap,
extend_to_sk (pattern->extend),
extend_to_sk (pattern->extend));
} else {
SkBitmap bitmap;
if (! _cairo_surface_is_image (surface)) {
cairo_status_t status;
status = _cairo_surface_acquire_source_image (surface,
&cr->source_image,
&cr->source_extra);
if (status)
return NULL;
surface = &cr->source_image->base;
}
if (unlikely (! surface_to_sk_bitmap (surface, bitmap)))
return NULL;
shader = SkShader::CreateBitmapShader (bitmap,
extend_to_sk (pattern->extend),
extend_to_sk (pattern->extend));
}
} else if (pattern->type == CAIRO_PATTERN_TYPE_LINEAR
/* || pattern->type == CAIRO_PATTERN_TYPE_RADIAL */)
{
cairo_gradient_pattern_t *gradient = (cairo_gradient_pattern_t *) pattern;
SkColor colors_stack[10];
SkScalar pos_stack[10];
SkColor *colors = colors_stack;
SkScalar *pos = pos_stack;
if (gradient->n_stops > 10) {
colors = new SkColor[gradient->n_stops];
pos = new SkScalar[gradient->n_stops];
}
for (unsigned int i = 0; i < gradient->n_stops; i++) {
pos[i] = CAIRO_FIXED_TO_SK_SCALAR (gradient->stops[i].offset);
colors[i] = color_stop_to_sk (gradient->stops[i].color);
}
if (pattern->type == CAIRO_PATTERN_TYPE_LINEAR) {
cairo_linear_pattern_t *linear = (cairo_linear_pattern_t *) gradient;
SkPoint points[2];
points[0].set (SkFloatToScalar (linear->pd1.x),
SkFloatToScalar (linear->pd1.y));
points[1].set (SkFloatToScalar (linear->pd2.x),
SkFloatToScalar (linear->pd2.y));
shader = SkGradientShader::CreateLinear (points, colors, pos, gradient->n_stops,
extend_to_sk (pattern->extend));
} else {
// XXX todo -- implement real radial shaders in Skia
}
if (gradient->n_stops > 10) {
delete [] colors;
delete [] pos;
}
}
if (shader && ! _cairo_matrix_is_identity (&pattern->matrix))
shader->setLocalMatrix (matrix_inverse_to_sk (pattern->matrix));
return shader;
}
static inline bool
pattern_filter_to_sk (const cairo_pattern_t *pattern)
{
switch (pattern->filter) {
case CAIRO_FILTER_GOOD:
case CAIRO_FILTER_BEST:
case CAIRO_FILTER_BILINEAR:
case CAIRO_FILTER_GAUSSIAN:
return true;
default:
case CAIRO_FILTER_FAST:
case CAIRO_FILTER_NEAREST:
return false;
}
}
static inline bool
pattern_to_sk_color (const cairo_pattern_t *pattern, SkColor& color)
{
if (pattern->type != CAIRO_PATTERN_TYPE_SOLID)
return false;
color = color_to_sk (((cairo_solid_pattern_t *) pattern)->color);
return true;
}
static cairo_status_t
_cairo_skia_context_set_source (void *abstract_cr,
cairo_pattern_t *source)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
SkColor color;
if (cr->source != NULL) {
if (cr->source_image != NULL) {
_cairo_surface_release_source_image (cr->source, cr->source_image, cr->source_extra);
cr->source_image = NULL;
}
cairo_surface_destroy (cr->source);
cr->source = NULL;
}
if (pattern_to_sk_color (source, color)) {
cr->paint->setColor (color);
} else {
SkShader *shader = source_to_sk_shader (cr, source);
if (shader == NULL) {
UNSUPPORTED;
return CAIRO_STATUS_SUCCESS;
}
cr->paint->setShader (shader);
shader->unref ();
cr->paint->setFilterBitmap (pattern_filter_to_sk (source));
}
/* XXX change notification */
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_set_source_rgba (void *abstract_cr, double red, double green, double blue, double alpha)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
/* Need unpremultiplied 1-byte values */
cr->paint->setARGB ((U8CPU) (alpha * 255),
(U8CPU) (red * 255),
(U8CPU) (green * 255),
(U8CPU) (blue * 255));
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_set_source_surface (void *abstract_cr,
cairo_surface_t *surface,
double x,
double y)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cairo_pattern_t *pattern;
cairo_matrix_t matrix;
cairo_status_t status;
if (surface->type == CAIRO_SURFACE_TYPE_SKIA) {
cairo_skia_surface_t *esurf = (cairo_skia_surface_t *) surface;
SkShader *shader;
shader = SkShader::CreateBitmapShader (*esurf->bitmap,
SkShader::kClamp_TileMode, /* XXX */
SkShader::kClamp_TileMode);
cr->paint->setShader (shader);
shader->unref ();
cr->paint->setFilterBitmap (true);
return CAIRO_STATUS_SUCCESS;
}
pattern = cairo_pattern_create_for_surface (surface);
if (unlikely (pattern->status))
return pattern->status;
cairo_matrix_init_translate (&matrix, -x, -y);
cairo_pattern_set_matrix (pattern, &matrix);
status = _cairo_skia_context_set_source (cr, pattern);
cairo_pattern_destroy (pattern);
return status;
}
static cairo_pattern_t *
_cairo_skia_context_get_source (void *abstract_cr)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
UNSUPPORTED;
return NULL;
}
static cairo_status_t
_cairo_skia_context_set_tolerance (void *abstract_cr,
double tolerance)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
/* XXX ignored */
return CAIRO_STATUS_SUCCESS;
}
static inline SkXfermode::Mode
operator_to_sk (cairo_operator_t op)
{
static const SkXfermode::Mode modeMap[] = {
SkXfermode::kClear_Mode,
SkXfermode::kSrc_Mode,
SkXfermode::kSrcOver_Mode,
SkXfermode::kSrcIn_Mode,
SkXfermode::kSrcOut_Mode,
SkXfermode::kSrcATop_Mode,
SkXfermode::kDst_Mode,
SkXfermode::kDstOver_Mode,
SkXfermode::kDstIn_Mode,
SkXfermode::kDstOut_Mode,
SkXfermode::kDstATop_Mode,
SkXfermode::kXor_Mode,
SkXfermode::kPlus_Mode, // XXX Add?
SkXfermode::kPlus_Mode, // XXX SATURATE
SkXfermode::kPlus_Mode,
SkXfermode::kMultiply_Mode,
SkXfermode::kScreen_Mode,
SkXfermode::kOverlay_Mode,
SkXfermode::kDarken_Mode,
SkXfermode::kLighten_Mode,
SkXfermode::kColorDodge_Mode,
SkXfermode::kColorBurn_Mode,
SkXfermode::kHardLight_Mode,
SkXfermode::kSoftLight_Mode,
SkXfermode::kDifference_Mode,
SkXfermode::kExclusion_Mode,
SkXfermode::kSrcOver_Mode, // XXX: CAIRO_OPERATOR_HSL_HUE
SkXfermode::kSrcOver_Mode, // XXX: CAIRO_OPERATOR_HSL_SATURATION,
SkXfermode::kSrcOver_Mode, // XXX: CAIRO_OPERATOR_HSL_COLOR,
SkXfermode::kSrcOver_Mode, // XXX: CAIRO_OPERATOR_HSL_LUMINOSITY
};
return modeMap[op];
}
static cairo_status_t
_cairo_skia_context_set_operator (void *abstract_cr, cairo_operator_t op)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cr->paint->setXfermodeMode (operator_to_sk (op));
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_set_opacity (void *abstract_cr, double opacity)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
/* XXX */
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_set_antialias (void *abstract_cr, cairo_antialias_t antialias)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cr->paint->setAntiAlias (antialias != CAIRO_ANTIALIAS_NONE);
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_set_fill_rule (void *abstract_cr,
cairo_fill_rule_t fill_rule)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cr->path->setFillType (fill_rule == CAIRO_FILL_RULE_WINDING ? SkPath::kWinding_FillType : SkPath::kEvenOdd_FillType);
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_set_line_width (void *abstract_cr,
double line_width)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cr->paint->setStrokeWidth (SkFloatToScalar (line_width));
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_set_line_cap (void *abstract_cr,
cairo_line_cap_t line_cap)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
static const SkPaint::Cap map[] = {
SkPaint::kButt_Cap,
SkPaint::kRound_Cap,
SkPaint::kSquare_Cap
};
cr->paint->setStrokeCap (map[line_cap]);
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_set_line_join (void *abstract_cr,
cairo_line_join_t line_join)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
static const SkPaint::Join map[] = {
SkPaint::kMiter_Join,
SkPaint::kRound_Join,
SkPaint::kBevel_Join
};
cr->paint->setStrokeJoin (map[line_join]);
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_set_dash (void *abstract_cr,
const double *dashes,
int num_dashes,
double offset)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
SkScalar intervals_static[20];
SkScalar *intervals = intervals_static;
if (num_dashes == 0) {
cr->paint->setPathEffect (NULL);
return CAIRO_STATUS_SUCCESS;
}
int loop = 0;
if ((num_dashes & 1) != 0) {
loop = 1;
num_dashes <<= 1;
}
if (num_dashes > 20)
intervals = new SkScalar[num_dashes];
int i = 0;
do {
for (int j = 0; i < num_dashes; j++)
intervals[i++] = SkFloatToScalar (dashes[j]);
} while (loop--);
SkDashPathEffect *dash = new SkDashPathEffect (intervals, num_dashes, SkFloatToScalar (offset));
cr->paint->setPathEffect (dash);
dash->unref ();
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_set_miter_limit (void *abstract_cr, double limit)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cr->paint->setStrokeMiter (SkFloatToScalar (limit));
return CAIRO_STATUS_SUCCESS;
}
static cairo_antialias_t
_cairo_skia_context_get_antialias (void *abstract_cr)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
return cr->paint->isAntiAlias () ? CAIRO_ANTIALIAS_DEFAULT : CAIRO_ANTIALIAS_NONE;
}
static void
_cairo_skia_context_get_dash (void *abstract_cr,
double *dashes,
int *num_dashes,
double *offset)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
*num_dashes = 0;
/* XXX */
}
static cairo_fill_rule_t
_cairo_skia_context_get_fill_rule (void *abstract_cr)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
SkPath::FillType ft;
ft = cr->path->getFillType ();
if (ft == SkPath::kWinding_FillType)
return CAIRO_FILL_RULE_WINDING;
if (ft == SkPath::kEvenOdd_FillType)
return CAIRO_FILL_RULE_EVEN_ODD;;
UNSUPPORTED;
return CAIRO_FILL_RULE_WINDING;
}
static double
_cairo_skia_context_get_line_width (void *abstract_cr)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
return /* ScalarToFloat */ cr->paint->getStrokeWidth ();
}
static cairo_line_cap_t
_cairo_skia_context_get_line_cap (void *abstract_cr)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
static const cairo_line_cap_t map[] = {
CAIRO_LINE_CAP_BUTT,
CAIRO_LINE_CAP_ROUND,
CAIRO_LINE_CAP_SQUARE
};
return map[cr->paint->getStrokeCap ()];
}
static cairo_line_join_t
_cairo_skia_context_get_line_join (void *abstract_cr)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
static const cairo_line_join_t map[] = {
CAIRO_LINE_JOIN_MITER,
CAIRO_LINE_JOIN_ROUND,
CAIRO_LINE_JOIN_BEVEL
};
return map[cr->paint->getStrokeJoin ()];
}
static double
_cairo_skia_context_get_miter_limit (void *abstract_cr)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
return /* SkScalarToFloat */ cr->paint->getStrokeMiter ();
}
static cairo_operator_t
_cairo_skia_context_get_operator (void *abstract_cr)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
UNSUPPORTED;
//cr->paint->getXfermode ();
return CAIRO_OPERATOR_OVER;
}
static double
_cairo_skia_context_get_opacity (void *abstract_cr)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
UNSUPPORTED;
return 1.;
}
static double
_cairo_skia_context_get_tolerance (void *abstract_cr)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
/* XXX */
return CAIRO_GSTATE_TOLERANCE_DEFAULT;
}
/* Current tranformation matrix */
static cairo_status_t
_cairo_skia_context_translate (void *abstract_cr,
double tx,
double ty)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cairo_matrix_translate (&cr->matrix, tx, ty);
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_scale (void *abstract_cr,
double sx,
double sy)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cairo_matrix_scale (&cr->matrix, sx, sy);
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_rotate (void *abstract_cr,
double theta)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cairo_matrix_rotate (&cr->matrix, theta);
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_transform (void *abstract_cr,
const cairo_matrix_t *matrix)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cairo_matrix_multiply (&cr->matrix, &cr->matrix, matrix);
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_set_matrix (void *abstract_cr,
const cairo_matrix_t *matrix)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cr->matrix = *matrix;
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_set_identity_matrix (void *abstract_cr)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cairo_matrix_init_identity (&cr->matrix);
return CAIRO_STATUS_SUCCESS;
}
static void
_cairo_skia_context_get_matrix (void *abstract_cr,
cairo_matrix_t *matrix)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
*matrix = cr->matrix;
}
static void
_cairo_skia_context_user_to_device (void *abstract_cr,
double *x,
double *y)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cairo_matrix_transform_point (&cr->matrix, x, y);
}
static void
_cairo_skia_context_user_to_device_distance (void *abstract_cr,
double *dx,
double *dy)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cairo_matrix_transform_distance (&cr->matrix, dx, dy);
}
static void
_cairo_skia_context_device_to_user (void *abstract_cr,
double *x,
double *y)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cairo_matrix_t inverse;
cairo_status_t status;
inverse = cr->matrix;
status = cairo_matrix_invert (&inverse);
assert (CAIRO_STATUS_SUCCESS == status);
cairo_matrix_transform_point (&inverse, x, y);
}
static void
_cairo_skia_context_device_to_user_distance (void *abstract_cr,
double *dx,
double *dy)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cairo_matrix_t inverse;
cairo_status_t status;
inverse = cr->matrix;
status = cairo_matrix_invert (&inverse);
assert (CAIRO_STATUS_SUCCESS == status);
cairo_matrix_transform_distance (&inverse, dx, dy);
}
/* Path constructor */
static cairo_status_t
_cairo_skia_context_new_path (void *abstract_cr)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cr->path->reset ();
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_new_sub_path (void *abstract_cr)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cr->path->rMoveTo (0, 0); /* XXX */
return CAIRO_STATUS_SUCCESS;
}
static void
user_to_device_point (cairo_skia_context_t *cr, double *x, double *y)
{
cairo_matrix_transform_point (&cr->matrix, x, y);
cairo_matrix_transform_point (&cr->target->image.base.device_transform, x, y);
}
static void
user_to_device_distance (cairo_skia_context_t *cr, double *dx, double *dy)
{
cairo_matrix_transform_distance (&cr->matrix, dx, dy);
cairo_matrix_transform_distance (&cr->target->image.base.device_transform, dx, dy);
}
static cairo_status_t
_cairo_skia_context_move_to (void *abstract_cr, double x, double y)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
user_to_device_point (cr, &x, &y);
cr->path->moveTo (SkFloatToScalar (x), SkFloatToScalar (y));
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_line_to (void *abstract_cr, double x, double y)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
user_to_device_point (cr, &x, &y);
cr->path->lineTo (SkFloatToScalar (x), SkFloatToScalar (y));
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_curve_to (void *abstract_cr,
double x1, double y1,
double x2, double y2,
double x3, double y3)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
user_to_device_point (cr, &x1, &y1);
user_to_device_point (cr, &x2, &y2);
user_to_device_point (cr, &x3, &y3);
cr->path->cubicTo (SkFloatToScalar (x1), SkFloatToScalar (y1),
SkFloatToScalar (x2), SkFloatToScalar (y2),
SkFloatToScalar (x3), SkFloatToScalar (y3));
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_arc_to (void *abstract_cr,
double x1, double y1,
double x2, double y2,
double radius)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
#if 0
user_to_device_point (cr, &x1, &y1);
user_to_device_point (cr, &x2, &y2);
user_to_device_distance (cr, &radius, &radius);
#endif
cr->path->arcTo (SkFloatToScalar (x1), SkFloatToScalar (y1),
SkFloatToScalar (x2), SkFloatToScalar (y2),
SkFloatToScalar (radius));
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_rel_move_to (void *abstract_cr, double dx, double dy)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
user_to_device_distance (cr, &dx, &dy);
cr->path->rMoveTo (SkFloatToScalar (dx), SkFloatToScalar (dy));
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_rel_line_to (void *abstract_cr, double dx, double dy)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
user_to_device_distance (cr, &dx, &dy);
cr->path->rLineTo (SkFloatToScalar (dx), SkFloatToScalar (dy));
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_rel_curve_to (void *abstract_cr,
double dx1, double dy1,
double dx2, double dy2,
double dx3, double dy3)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
user_to_device_distance (cr, &dx1, &dy1);
user_to_device_distance (cr, &dx2, &dy2);
user_to_device_distance (cr, &dx3, &dy3);
cr->path->rCubicTo (SkFloatToScalar (dx1), SkFloatToScalar (dy1),
SkFloatToScalar (dx2), SkFloatToScalar (dy2),
SkFloatToScalar (dx3), SkFloatToScalar (dy3));
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_rel_arc_to (void *abstract_cr,
double dx1, double dy1,
double dx2, double dy2,
double radius)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
#if 0
user_to_device_point (cr, &x1, &y1);
user_to_device_point (cr, &x2, &y2);
user_to_device_distance (cr, &radius, &radius);
#endif
cr->path->arcTo (SkFloatToScalar (dx1), SkFloatToScalar (dy1),
SkFloatToScalar (dx2), SkFloatToScalar (dy2),
SkFloatToScalar (radius));
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_close_path (void *abstract_cr)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cr->path->close ();
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_rectangle (void *abstract_cr,
double x, double y,
double width, double height)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
double x1, y1, x2, y2;
/* XXX assume no rotation! */
x1 = x, y1 = y;
user_to_device_point (cr, &x1, &y1);
x2 = x + width, y2 = y + height;
user_to_device_point (cr, &x2, &y2);
cr->path->addRect (SkFloatToScalar (x1), SkFloatToScalar (y1),
SkFloatToScalar (x2), SkFloatToScalar (y2));
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_arc (void *abstract_cr,
double xc, double yc, double radius,
double angle1, double angle2,
cairo_bool_t forward)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cairo_status_t status;
/* XXX cr->path->arc() */
/* Do nothing, successfully, if radius is <= 0 */
if (radius <= 0.0) {
status = _cairo_skia_context_line_to (cr, xc, yc);
if (unlikely (status))
return status;
status = _cairo_skia_context_line_to (cr, xc, yc);
if (unlikely (status))
return status;
return CAIRO_STATUS_SUCCESS;
}
status = _cairo_skia_context_line_to (cr,
xc + radius * cos (angle1),
yc + radius * sin (angle1));
if (unlikely (status))
return status;
if (forward)
_cairo_arc_path (&cr->base, xc, yc, radius, angle1, angle2);
else
_cairo_arc_path_negative (&cr->base, xc, yc, radius, angle1, angle2);
return CAIRO_STATUS_SUCCESS;
}
static void
_cairo_skia_context_path_extents (void *abstract_cr,
double *x1,
double *y1,
double *x2,
double *y2)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
SkRect rect;
rect = cr->path->getBounds ();
UNSUPPORTED;
/* XXX transform SkScalar rect to user */
}
static cairo_bool_t
_cairo_skia_context_has_current_point (void *abstract_cr)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
return TRUE;
}
static cairo_bool_t
_cairo_skia_context_get_current_point (void *abstract_cr,
double *x,
double *y)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
SkPoint pt;
cr->path->getLastPt (&pt);
//*x = SkScalarToFloat (pt.x);
//*y = SkScalarToFloat (pt.y);
//_cairo_gstate_backend_to_user (cr->gstate, x, y);
return TRUE;
}
static cairo_path_t *
_cairo_skia_context_copy_path (void *abstract_cr)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
/* XXX iterate */
UNSUPPORTED;
return NULL;
}
static cairo_path_t *
_cairo_skia_context_copy_path_flat (void *abstract_cr)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
/* XXX iterate and decompose */
UNSUPPORTED;
return NULL;
}
static cairo_status_t
_cairo_skia_context_append_path (void *abstract_cr,
const cairo_path_t *path)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
// return _cairo_path_append_to_context (path, cr);
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_stroke_to_path (void *abstract_cr)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cr->paint->setStyle (SkPaint::kStroke_Style);
cr->paint->getFillPath (*cr->path, cr->path);
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_paint (void *abstract_cr)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
#if 0
if (cr->source != NULL) {
SkBitmap bitmap;
SkMatrix bitmapMatrix;
if (cr->source->type == CAIRO_SURFACE_TYPE_SKIA) {
cairo_skia_surface_t *esurf = (cairo_skia_surface_t *) cr->source->type;
bitmap = *esurf->bitmap;
} else {
surface_to_sk_bitmap (&cr->source_image->base, bitmap);
}
// XXX pattern->matrix, pattern->filter, pattern->extend
cr->canvas->drawBitmapMatrix (bitmap, bitmapMatrix, cr->paint);
} else {
cr->canvas->drawPaint (*cr->paint);
}
#else
cr->canvas->drawPaint (*cr->paint);
#endif
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_paint_with_alpha (void *abstract_cr,
double alpha)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cairo_status_t status;
if (CAIRO_ALPHA_IS_OPAQUE (alpha))
return _cairo_skia_context_paint (cr);
cr->paint->setAlpha(SkScalarRound(255*alpha));
status = _cairo_skia_context_paint (cr);
cr->paint->setAlpha(255);
return status;
}
static cairo_status_t
_cairo_skia_context_mask (void *abstract_cr,
cairo_pattern_t *mask)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
/* XXX */
//UNSUPPORTED;
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_stroke_preserve (void *abstract_cr)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cr->paint->setStyle (SkPaint::kStroke_Style);
/* XXX pen transformation? */
//assert (_cairo_matrix_is_identity (&cr->matrix));
cr->canvas->drawPath (*cr->path, *cr->paint);
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_stroke (void *abstract_cr)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cairo_status_t status;
status = _cairo_skia_context_stroke_preserve (cr);
if (unlikely (status))
return status;
return _cairo_skia_context_new_path (cr);
}
static cairo_status_t
_cairo_skia_context_in_stroke (void *abstract_cr,
double x, double y,
cairo_bool_t *inside)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
UNSUPPORTED;
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_stroke_extents (void *abstract_cr,
double *x1, double *y1, double *x2, double *y2)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
UNSUPPORTED;
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_fill_preserve (void *abstract_cr)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cr->paint->setStyle (SkPaint::kFill_Style);
cr->canvas->drawPath (*cr->path, *cr->paint);
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_fill (void *abstract_cr)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cairo_status_t status;
status = _cairo_skia_context_fill_preserve (cr);
if (unlikely (status))
return status;
return _cairo_skia_context_new_path (cr);
}
static cairo_status_t
_cairo_skia_context_in_fill (void *abstract_cr,
double x, double y,
cairo_bool_t *inside)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
UNSUPPORTED;
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_fill_extents (void *abstract_cr,
double *x1, double *y1, double *x2, double *y2)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
UNSUPPORTED;
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_clip_preserve (void *abstract_cr)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cr->canvas->clipPath (*cr->path);
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_clip (void *abstract_cr)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
cairo_status_t status;
status = _cairo_skia_context_clip_preserve (cr);
if (unlikely (status))
return status;
return _cairo_skia_context_new_path (cr);
}
static cairo_status_t
_cairo_skia_context_in_clip (void *abstract_cr,
double x, double y,
cairo_bool_t *inside)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_reset_clip (void *abstract_cr)
{
cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
SkRegion rgn(SkIRect::MakeWH (cr->target->bitmap->width (),
cr->target->bitmap->height ()));
cr->canvas->setClipRegion(rgn);
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_clip_extents (void *abstract_cr,
double *x1, double *y1,
double *x2, double *y2)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
UNSUPPORTED;
return CAIRO_STATUS_SUCCESS;
}
static cairo_rectangle_list_t *
_cairo_skia_context_copy_clip_rectangle_list (void *abstract_cr)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
UNSUPPORTED;
return NULL;
}
static cairo_status_t
_cairo_skia_context_copy_page (void *abstract_cr)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
UNSUPPORTED;
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_show_page (void *abstract_cr)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
UNSUPPORTED;
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_set_font_face (void *abstract_cr,
cairo_font_face_t *font_face)
{
// cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
//return _cairo_gstate_set_font_face (cr->gstate, font_face);
return CAIRO_STATUS_SUCCESS;
}
static cairo_font_face_t *
_cairo_skia_context_get_font_face (void *abstract_cr)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
UNSUPPORTED;
return NULL;
}
static cairo_status_t
_cairo_skia_context_font_extents (void *abstract_cr,
cairo_font_extents_t *extents)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
UNSUPPORTED;
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_set_font_size (void *abstract_cr,
double size)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
UNSUPPORTED;
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_set_font_matrix (void *abstract_cr,
const cairo_matrix_t *matrix)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
UNSUPPORTED;
return CAIRO_STATUS_SUCCESS;
}
static void
_cairo_skia_context_get_font_matrix (void *abstract_cr,
cairo_matrix_t *matrix)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
UNSUPPORTED;
}
static cairo_status_t
_cairo_skia_context_set_font_options (void *abstract_cr,
const cairo_font_options_t *options)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
UNSUPPORTED;
return CAIRO_STATUS_SUCCESS;
}
static void
_cairo_skia_context_get_font_options (void *abstract_cr,
cairo_font_options_t *options)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
UNSUPPORTED;
}
static cairo_status_t
_cairo_skia_context_set_scaled_font (void *abstract_cr,
cairo_scaled_font_t *scaled_font)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
UNSUPPORTED;
return CAIRO_STATUS_SUCCESS;
}
static cairo_scaled_font_t *
_cairo_skia_context_get_scaled_font (void *abstract_cr)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
UNSUPPORTED;
return _cairo_scaled_font_create_in_error (CAIRO_STATUS_SURFACE_TYPE_MISMATCH);
}
static cairo_status_t
_cairo_skia_context_glyphs (void *abstract_cr,
const cairo_glyph_t *glyphs,
int num_glyphs,
cairo_glyph_text_info_t *info)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
/* XXX */
//UNSUPPORTED;
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_glyph_path (void *abstract_cr,
const cairo_glyph_t *glyphs,
int num_glyphs)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
UNSUPPORTED;
return CAIRO_STATUS_SUCCESS;
}
static cairo_status_t
_cairo_skia_context_glyph_extents (void *abstract_cr,
const cairo_glyph_t *glyphs,
int num_glyphs,
cairo_text_extents_t *extents)
{
//cairo_skia_context_t *cr = (cairo_skia_context_t *) abstract_cr;
UNSUPPORTED;
return CAIRO_STATUS_SUCCESS;
}
static const cairo_backend_t _cairo_skia_context_backend = {
CAIRO_TYPE_SKIA,
_cairo_skia_context_destroy,
_cairo_skia_context_get_original_target,
_cairo_skia_context_get_current_target,
_cairo_skia_context_save,
_cairo_skia_context_restore,
_cairo_skia_context_push_group,
_cairo_skia_context_pop_group,
_cairo_skia_context_set_source_rgba,
_cairo_skia_context_set_source_surface,
_cairo_skia_context_set_source,
_cairo_skia_context_get_source,
_cairo_skia_context_set_antialias,
_cairo_skia_context_set_dash,
_cairo_skia_context_set_fill_rule,
_cairo_skia_context_set_line_cap,
_cairo_skia_context_set_line_join,
_cairo_skia_context_set_line_width,
_cairo_skia_context_set_miter_limit,
_cairo_skia_context_set_opacity,
_cairo_skia_context_set_operator,
_cairo_skia_context_set_tolerance,
_cairo_skia_context_get_antialias,
_cairo_skia_context_get_dash,
_cairo_skia_context_get_fill_rule,
_cairo_skia_context_get_line_cap,
_cairo_skia_context_get_line_join,
_cairo_skia_context_get_line_width,
_cairo_skia_context_get_miter_limit,
_cairo_skia_context_get_opacity,
_cairo_skia_context_get_operator,
_cairo_skia_context_get_tolerance,
_cairo_skia_context_translate,
_cairo_skia_context_scale,
_cairo_skia_context_rotate,
_cairo_skia_context_transform,
_cairo_skia_context_set_matrix,
_cairo_skia_context_set_identity_matrix,
_cairo_skia_context_get_matrix,
_cairo_skia_context_user_to_device,
_cairo_skia_context_user_to_device_distance,
_cairo_skia_context_device_to_user,
_cairo_skia_context_device_to_user_distance,
_cairo_skia_context_new_path,
_cairo_skia_context_new_sub_path,
_cairo_skia_context_move_to,
_cairo_skia_context_rel_move_to,
_cairo_skia_context_line_to,
_cairo_skia_context_rel_line_to,
_cairo_skia_context_curve_to,
_cairo_skia_context_rel_curve_to,
_cairo_skia_context_arc_to,
_cairo_skia_context_rel_arc_to,
_cairo_skia_context_close_path,
_cairo_skia_context_arc,
_cairo_skia_context_rectangle,
_cairo_skia_context_path_extents,
_cairo_skia_context_has_current_point,
_cairo_skia_context_get_current_point,
_cairo_skia_context_copy_path,
_cairo_skia_context_copy_path_flat,
_cairo_skia_context_append_path,
_cairo_skia_stroke_to_path,
_cairo_skia_context_clip,
_cairo_skia_context_clip_preserve,
_cairo_skia_context_in_clip,
_cairo_skia_context_clip_extents,
_cairo_skia_context_reset_clip,
_cairo_skia_context_copy_clip_rectangle_list,
_cairo_skia_context_paint,
_cairo_skia_context_paint_with_alpha,
_cairo_skia_context_mask,
_cairo_skia_context_stroke,
_cairo_skia_context_stroke_preserve,
_cairo_skia_context_in_stroke,
_cairo_skia_context_stroke_extents,
_cairo_skia_context_fill,
_cairo_skia_context_fill_preserve,
_cairo_skia_context_in_fill,
_cairo_skia_context_fill_extents,
_cairo_skia_context_set_font_face,
_cairo_skia_context_get_font_face,
_cairo_skia_context_set_font_size,
_cairo_skia_context_set_font_matrix,
_cairo_skia_context_get_font_matrix,
_cairo_skia_context_set_font_options,
_cairo_skia_context_get_font_options,
_cairo_skia_context_set_scaled_font,
_cairo_skia_context_get_scaled_font,
_cairo_skia_context_font_extents,
_cairo_skia_context_glyphs,
_cairo_skia_context_glyph_path,
_cairo_skia_context_glyph_extents,
_cairo_skia_context_copy_page,
_cairo_skia_context_show_page,
};
cairo_t *
_cairo_skia_context_create (void *target)
{
cairo_skia_surface_t *surface = (cairo_skia_surface_t *) target;
cairo_skia_context_t *cr;
cr = (cairo_skia_context_t *) _freed_pool_get (&context_pool);
if (unlikely (cr == NULL)) {
cr = new cairo_skia_context_t;
if (unlikely (cr == NULL))
return _cairo_create_in_error (_cairo_error (CAIRO_STATUS_NO_MEMORY));
cr->path = new SkPath;
cr->paint = new SkPaint;
}
_cairo_init (&cr->base, &_cairo_skia_context_backend);
cr->source = NULL;
cr->source_image = NULL;
cr->paint->setStrokeWidth (SkFloatToScalar (2.0));
cr->target = (cairo_skia_surface_t *) cairo_surface_reference ((cairo_surface_t *) target);
cr->original = (cairo_skia_surface_t *) cairo_surface_reference ((cairo_surface_t *) target);
cr->canvas = new SkCanvas (*surface->bitmap);
cr->canvas->save ();
cairo_matrix_init_identity (&cr->matrix);
return &cr->base;
}
#if 0
void
_cairo_skia_context_set_SkPaint (cairo_t *cr, SkPaint paint)
{
*cr->paint = paint;
}
void
_cairo_skia_context_set_SkPath (cairo_t *cr, SkPath path)
{
*cr->path = path;
}
#endif
| 27.232971 | 154 | 0.731335 | [
"vector",
"transform",
"solid"
] |
a09395ea448e222b21a7208ed4d8548d70414529 | 22,111 | cpp | C++ | weex_core/Source/core/render/manager/render_manager.cpp | Blankdlh/incubator-weex | 8bcd48dff97046e444f5cd4dff34baad6a4b0850 | [
"Apache-2.0"
] | 1 | 2019-08-07T14:59:20.000Z | 2019-08-07T14:59:20.000Z | weex_core/Source/core/render/manager/render_manager.cpp | x-flower-rain/incubator-weex | 3bfb619122bbb87431b90790dd0d47a8db8ef193 | [
"Apache-2.0"
] | 12 | 2019-07-09T05:55:28.000Z | 2019-07-31T01:12:28.000Z | weex_core/Source/core/render/manager/render_manager.cpp | x-flower-rain/incubator-weex | 3bfb619122bbb87431b90790dd0d47a8db8ef193 | [
"Apache-2.0"
] | null | null | null | /**
* 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 "core/render/manager/render_manager.h"
#include <chrono>
#include <utility>
#include <vector>
#include "base/log_defines.h"
#include "base/time_utils.h"
#include "core/common/view_utils.h"
#include "core/css/constants_name.h"
#include "core/layout/measure_func_adapter.h"
#include "core/parser/dom_wson.h"
#include "core/render/node/render_object.h"
#include "core/render/page/render_page.h"
#include "core/render/page/render_page_custom.h"
#include "core/render/target/render_target.h"
#include "core/manager/weex_core_manager.h"
#include "wson/wson_parser.h"
namespace WeexCore {
RenderManager *RenderManager::g_pInstance = nullptr;
bool RenderManager::CreatePage(const std::string& page_id, const char *data) {
#if RENDER_LOG
wson_parser parser(data);
LOGD("[RenderManager] CreatePage >>>> pageId: %s, dom data: %s",
pageId.c_str(), parser.toStringUTF8().c_str());
#endif
std::string targetName = RenderTargetManager::getRenderTargetName(page_id);
if (!targetName.empty()) {
if (RenderTargetManager::sharedInstance()->getAvailableTargetNames().count(targetName) == 0) {
// cannot find the target, degress
targetName = "";
}
}
if (!targetName.empty()) {
RenderPageCustom* pageCustom = CreateCustomPage(page_id, targetName);
WsonGenerate(data, "", 0, [=](const std::string& ref,
const std::string& type,
const std::string& parentRef,
std::map<std::string, std::string>* styles,
std::map<std::string, std::string>* attrs,
std::set<std::string>* events,
int index) {
if (parentRef.empty()) {
pageCustom->CreateBody(ref, type, styles, attrs, events);
}
else {
pageCustom->AddRenderObject(ref, type, parentRef, index, styles, attrs, events);
}
});
return true;
}
else {
RenderPage *page = new RenderPage(page_id);
pages_.insert(std::pair<std::string, RenderPage *>(page_id, page));
initDeviceConfig(page, page_id);
int64_t start_time = getCurrentTime();
RenderObject *root = Wson2RenderObject(data, page_id, page->reserve_css_styles());
page->ParseJsonTime(getCurrentTime() - start_time);
return page->CreateRootRender(root);
}
}
bool RenderManager::CreatePage(const std::string& page_id, RenderObject *root) {
#if RENDER_LOG
wson_parser parser(data);
LOGD("[RenderManager] CreatePage >>>> pageId: %s, dom data: %s",
pageId.c_str(), parser.toStringUTF8().c_str());
#endif
RenderPage *page = new RenderPage(page_id);
this->pages_.insert(std::pair<std::string, RenderPage *>(page_id, page));
initDeviceConfig(page, page_id);
return page->CreateRootRender(root);
}
bool RenderManager::CreatePage(const std::string& page_id, std::function<RenderObject* (RenderPage*)> constructRoot) {
#if RENDER_LOG
LOGD("[RenderManager] CreatePage >>>> pageId: %s", pageId.c_str());
#endif
RenderPage *page = new RenderPage(page_id);
this->pages_.insert(std::pair<std::string, RenderPage *>(page_id, page));
initDeviceConfig(page, page_id);
int64_t start_time = getCurrentTime();
RenderObject *root = constructRoot(page);
page->ParseJsonTime(getCurrentTime() - start_time);
return page->CreateRootRender(root);
}
RenderPageCustom* RenderManager::CreateCustomPage(const std::string& page_id, const std::string& page_type) {
#if RENDER_LOG
LOGD("[RenderManager] CreateCustomPage >>>> pageId: %s, pageType: %s", pageId.c_str(), page_type.c_str());
#endif
RenderPageCustom::PageOptions options;
{
std::lock_guard<std::mutex> guard(page_args_mutex_);
auto findPageArgs = page_args_.find(page_id);
if (findPageArgs != page_args_.end()) {
options.args = findPageArgs->second;
}
}
options.view_scale = 1;
auto value = WeexCore::WXCoreEnvironment::getInstance()->GetOption("pixel_scale");
if (value != "") {
options.view_scale = strtof(value.c_str(), NULL);
}
auto findViewPort = options.args.find("viewportwidth");
if (findViewPort != options.args.end()) {
options.viewport_width = getFloat(findViewPort->second.c_str());
}
else {
options.viewport_width = kDefaultViewPortWidth;
}
auto findDeviceWidth = options.args.find("devicewidth");
if (findDeviceWidth != options.args.end()) {
options.device_width = getFloat(findDeviceWidth->second.c_str());
}
else {
/* For iOS DeviceWidth stored by WeexCore is in UIKit view system coordinate(iPhone6 is 375).
So we must provide heron with the pixel device width here. */
options.device_width = WXCoreEnvironment::getInstance()->DeviceWidth() * options.view_scale;
}
auto findDeviation = options.args.find("roundoffdeviation");
if (findDeviation != options.args.end()) {
options.is_round_off = getBool(findDeviation->second.c_str());
}
else {
options.is_round_off = kDefaultRoundOffDeviation;
}
RenderPageCustom* page = new RenderPageCustom(page_id, page_type, options);
this->pages_.insert(std::pair<std::string, RenderPageCustom *>(page_id, page));
return page;
}
bool RenderManager::AddRenderObject(const std::string &page_id,
const std::string &parent_ref, int index,
const char *data) {
RenderPageBase *page = GetPage(page_id);
if (page == nullptr) return false;
#if RENDER_LOG
wson_parser parser(data);
LOGD(
"[RenderManager] AddRenderObject >>>> pageId: %s, parentRef: %s, index: "
"%d, dom data: %s",
pageId.c_str(), parentRef.c_str(), index, parser.toStringUTF8().c_str());
#endif
int64_t start_time = getCurrentTime();
if (page->is_platform_page()) {
RenderObject *child = Wson2RenderObject(data, page_id, static_cast<RenderPage*>(page)->reserve_css_styles());
static_cast<RenderPage*>(page)->ParseJsonTime(getCurrentTime() - start_time);
if (child == nullptr) return false;
return static_cast<RenderPage*>(page)->AddRenderObject(parent_ref, index, child);
}
else {
WsonGenerate(data, parent_ref, index, [=] (const std::string& ref,
const std::string& type,
const std::string& parentRef,
std::map<std::string, std::string>* styles,
std::map<std::string, std::string>* attrs,
std::set<std::string>* events,
int index) {
page->AddRenderObject(ref, type, parentRef, index, styles, attrs, events);
});
return true;
}
}
bool RenderManager::AddRenderObject(const std::string &page_id, const std::string &parent_ref,
int index, RenderObject *root) {
RenderPageBase *page = GetPage(page_id);
if (page == nullptr) return false;
#if RENDER_LOG
wson_parser parser(data);
LOGD(
"[RenderManager] AddRenderObject >>>> pageId: %s, parentRef: %s, index: "
"%d, dom data: %s",
pageId.c_str(), parentRef.c_str(), index, parser.toStringUTF8().c_str());
#endif
if (root == nullptr) return false;
if (page->is_platform_page()) {
return static_cast<RenderPage*>(page)->AddRenderObject(parent_ref, index, root);
}
else {
return false;
}
}
bool RenderManager::AddRenderObject(const std::string &page_id,
const std::string &parent_ref, int index,
std::function<RenderObject* (RenderPage*)> constructRoot) {
RenderPageBase *page = GetPage(page_id);
if (page == nullptr) return false;
#if RENDER_LOG
wson_parser parser(data);
LOGD(
"[RenderManager] AddRenderObject >>>> pageId: %s, parentRef: %s, index: "
"%d, dom data: %s",
pageId.c_str(), parentRef.c_str(), index, parser.toStringUTF8().c_str());
#endif
RenderObject *root = constructRoot(static_cast<RenderPage*>(page));
if (root == nullptr) return false;
static_cast<RenderPage*>(page)->set_is_dirty(true);
return static_cast<RenderPage*>(page)->AddRenderObject(parent_ref, index, root);
}
bool RenderManager::RemoveRenderObject(const std::string &page_id,
const std::string &ref) {
RenderPageBase *page = this->GetPage(page_id);
if (page == nullptr) return false;
#if RENDER_LOG
LOGD("[RenderManager] RemoveRenderObject >>>> pageId: %s, ref: %s",
pageId.c_str(), ref.c_str());
#endif
return page->RemoveRenderObject(ref);
}
bool RenderManager::MoveRenderObject(const std::string &page_id,
const std::string &ref,
const std::string &parent_ref, int index) {
RenderPageBase *page = this->GetPage(page_id);
if (page == nullptr) return false;
#if RENDER_LOG
LOGD(
"[RenderManager] MoveRenderObject >>>> pageId: %s, ref: %s, parentRef: "
"%s, index: %d",
pageId.c_str(), ref.c_str(), parentRef.c_str(), index);
#endif
return page->MoveRenderObject(ref, parent_ref, index);
}
bool RenderManager::UpdateAttr(const std::string &page_id,
const std::string &ref, const char *data) {
RenderPageBase *page = this->GetPage(page_id);
if (page == nullptr) return false;
#if RENDER_LOG
wson_parser parser(data);
LOGD("[RenderManager] UpdateAttr >>>> pageId: %s, ref: %s, data: %s",
pageId.c_str(), ref.c_str(), parser.toStringUTF8().c_str());
#endif
int64_t start_time = getCurrentTime();
std::vector<std::pair<std::string, std::string>> *attrs = Wson2Pairs(data);
page->ParseJsonTime(getCurrentTime() - start_time);
return page->UpdateAttr(ref, attrs);
}
bool RenderManager::UpdateAttr(const std::string &page_id, const std::string &ref,
std::vector<std::pair<std::string, std::string>> *attrPair) {
RenderPageBase *page = this->GetPage(page_id);
if (page == nullptr) return false;
#if RENDER_LOG
wson_parser parser(data);
LOGD("[RenderManager] UpdateAttr >>>> pageId: %s, ref: %s, data: %s",
pageId.c_str(), ref.c_str(), parser.toStringUTF8().c_str());
#endif
return page->UpdateAttr(ref, attrPair);
}
bool RenderManager::UpdateStyle(const std::string &page_id,
const std::string &ref, const char *data) {
RenderPageBase *page = this->GetPage(page_id);
if (page == nullptr) return false;
#if RENDER_LOG
wson_parser parser(data);
LOGD("[RenderManager] UpdateStyle >>>> pageId: %s, ref: %s, data: %s",
pageId.c_str(), ref.c_str(), parser.toStringUTF8().c_str());
#endif
int64_t start_time = getCurrentTime();
std::vector<std::pair<std::string, std::string>> *styles = Wson2Pairs(data);
page->ParseJsonTime(getCurrentTime() - start_time);
return page->UpdateStyle(ref, styles);
}
bool RenderManager::UpdateStyle(const std::string &page_id, const std::string &ref,
std::vector<std::pair<std::string, std::string>> *stylePair) {
RenderPageBase *page = this->GetPage(page_id);
if (page == nullptr) return false;
#if RENDER_LOG
wson_parser parser(data);
LOGD("[RenderManager] UpdateStyle >>>> pageId: %s, ref: %s, data: %s",
pageId.c_str(), ref.c_str(), parser.toStringUTF8().c_str());
#endif
return page->UpdateStyle(ref, stylePair);
}
bool RenderManager::AddEvent(const std::string &page_id, const std::string &ref,
const std::string &event) {
RenderPageBase *page = this->GetPage(page_id);
if (page == nullptr) return false;
#if RENDER_LOG
LOGD("[RenderManager] AddEvent >>>> pageId: %s, ref: %s, event: %s",
pageId.c_str(), ref.c_str(), event.c_str());
#endif
return page->AddEvent(ref, event);
}
bool RenderManager::RemoveEvent(const std::string &page_id,
const std::string &ref,
const std::string &event) {
RenderPageBase *page = this->GetPage(page_id);
if (page == nullptr) return false;
#if RENDER_LOG
LOGD("[RenderManager] RemoveEvent >>>> pageId: %s, ref: %s, event: %s",
pageId.c_str(), ref.c_str(), event.c_str());
#endif
return page->RemoveEvent(ref, event);
}
bool RenderManager::CreateFinish(const std::string &page_id) {
RenderPageBase *page = GetPage(page_id);
if (page == nullptr) return false;
LOGE("RenderManager::CreateFinish %s", page_id.data());
#if RENDER_LOG
LOGD("[RenderManager] CreateFinish >>>> pageId: %s", pageId.c_str());
#endif
bool b = page->CreateFinish();
#if RENDER_LOG
auto end_time = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now());
LOGE("DATA_RENDER, Wx End %lld",end_time);
#endif
return b;
}
std::unique_ptr<ValueWithType> RenderManager::CallNativeModule(const char *page_id, const char *module, const char *method,
const char *arguments, int arguments_length,
const char *options, int options_length) {
if (strcmp(module, "meta") == 0) {
CallMetaModule(page_id, method, arguments);
}
RenderPageBase* page = GetPage(page_id);
if (page == nullptr){ //page not exist, call normal platform layer
return WeexCoreManager::Instance()->
getPlatformBridge()->
platform_side()->
CallNativeModule(page_id, module, method, arguments, arguments_length, options, options_length);
}
//redirect to page.
return page->CallNativeModule(module, method, arguments, arguments_length, options, options_length);
}
void RenderManager::CallNativeComponent(const char *page_id, const char *ref,
const char *method,
const char *arguments,
int arguments_length,
const char *options,
int options_length) {
RenderPageBase* page = GetPage(page_id);
if (page == nullptr) {
WeexCoreManager::Instance()
->getPlatformBridge()
->platform_side()
->CallNativeComponent(page_id, ref, method, arguments, arguments_length,
options, options_length);
return;
}
// redirect to page
page->CallNativeComponent(ref, method, arguments, arguments_length, options, options_length);
}
void RenderManager::CallMetaModule(const char *page_id, const char *method, const char *arguments) {
if (strcmp(method, "setViewport") == 0) {
wson_parser parser(arguments);
if (parser.isArray(parser.nextType())) {
int size = parser.nextArraySize();
for (int i = 0; i < size; i++) {
uint8_t value_type = parser.nextType();
if (parser.isMap(value_type)) {
int map_size = parser.nextMapSize();
for (int j = 0; j < map_size; j++) {
std::string key = parser.nextMapKeyUTF8();
std::string value = parser.nextStringUTF8(parser.nextType());
if (key == WIDTH) {
setPageArgument(page_id, "viewportwidth", value);
}
else if (key == ROUND_OFF_DEVIATION) {
setPageArgument(page_id, "roundoffdeviation", value);
}
else if (key == "deviceWidth") {
setPageArgument(page_id, "devicewidth", value);
}
else if (key == "deviceHeight") {
// unsupported now
}
else if (key == "reserveCssStyles") {
setPageArgument(page_id, "reserveCssStyles", value);
}
}
}
}
}
}
}
RenderPageBase *RenderManager::GetPage(const std::string &page_id) {
std::map<std::string, RenderPageBase *>::iterator iter =
this->pages_.find(page_id);
if (iter != this->pages_.end()) {
return iter->second;
} else {
return nullptr;
}
}
bool RenderManager::ClosePage(const std::string &page_id) {
auto pageArgs = removePageArguments(page_id);
RenderPageBase *page = GetPage(page_id);
if (page == nullptr) {
/* Page in WeexCore is created when js outputs createBody command.
But before createBody, custom render page like heron page may be created.
So we must tell heron manager to close the page
*/
auto findPageType = pageArgs.find("renderType");
if (findPageType != pageArgs.end()) {
auto target = RenderTargetManager::sharedInstance()->getRenderTarget(findPageType->second);
if (target) {
target->deletePage(page_id);
}
}
return false;
}
#if RENDER_LOG
LOGD("[RenderManager] ClosePage >>>> pageId: %s", pageId.c_str());
#endif
page->OnRenderPageClose();
this->pages_.erase(page_id);
delete page;
page = nullptr;
return true;
}
bool RenderManager::ReloadPageLayout(const std::string& page_id)
{
RenderPageBase *page = GetPage(page_id);
if (page == nullptr) return false;
return page->ReapplyStyles();
}
float RenderManager::viewport_width(const std::string &page_id) {
RenderPageBase *page = GetPage(page_id);
if (page == nullptr) return kDefaultViewPortWidth;
return page->GetViewportWidth();
}
void RenderManager::set_viewport_width(const std::string &page_id, float viewport_width) {
RenderPageBase *page = GetPage(page_id);
if (page == nullptr) {
// page is not created yet, we should store the view port value
setPageArgument(page_id, "viewportwidth", std::to_string(viewport_width));
return;
}
page->SetViewportWidth(viewport_width);
}
float RenderManager::DeviceWidth(const std::string &page_id) {
RenderPageBase *page = GetPage(page_id);
if(page == nullptr){
return WXCoreEnvironment::getInstance()->DeviceWidth();
}
return page->GetDeviceWidth();
}
void RenderManager::setDeviceWidth(const std::string &page_id, float device_width) {
RenderPageBase *page = GetPage(page_id);
if (page == nullptr) {
// page is not created yet, we should store the device width value
setPageArgument(page_id, "devicewidth", std::to_string(device_width));
return;
}
page->SetDeviceWidth(device_width);
}
bool RenderManager::round_off_deviation(const std::string &page_id) {
RenderPageBase *page = GetPage(page_id);
if (page == nullptr) return kDefaultRoundOffDeviation;
return page->GetRoundOffDeviation();
}
void RenderManager::set_round_off_deviation(const std::string &page_id, bool round_off_deviation) {
RenderPageBase *page = GetPage(page_id);
if (page == nullptr) {
setPageArgument(page_id, "roundoffdeviation", round_off_deviation ? "true" : "false");
return;
}
page->SetRoundOffDeviation(round_off_deviation);
}
void RenderManager::setPageArgument(const std::string& pageId, const std::string& key, const std::string& value) {
if (pageId.empty() || key.empty()) {
return;
}
std::lock_guard<std::mutex> guard(page_args_mutex_);
page_args_[pageId][key] = value;
}
std::string RenderManager::getPageArgument(const std::string& pageId, const std::string& key) {
std::lock_guard<std::mutex> guard(page_args_mutex_);
auto findPage = page_args_.find(pageId);
if (findPage != page_args_.end()) {
auto findKey = findPage->second.find(key);
if (findKey != findPage->second.end()) {
return findKey->second;
}
}
return "";
}
std::map<std::string, std::string> RenderManager::removePageArguments(const std::string& pageId) {
std::lock_guard<std::mutex> guard(page_args_mutex_);
std::map<std::string, std::string> result;
auto findPage = page_args_.find(pageId);
if (findPage != page_args_.end()) {
std::swap(result, findPage->second);
page_args_.erase(findPage);
}
return result;
}
void RenderManager::Batch(const std::string &page_id) {
RenderPageBase *page = this->GetPage(page_id);
if (page == nullptr) return;
if (!page->is_platform_page()) return;
static_cast<RenderPage*>(page)->Batch();
}
void RenderManager::initDeviceConfig(RenderPage *page, const std::string &page_id) {
if (page == nullptr) return;
auto viewPortWidth = getPageArgument(page_id, "viewportwidth");
if (!viewPortWidth.empty()) {
page->set_viewport_width(getFloat(viewPortWidth.c_str()));
}
auto deviceWidth = getPageArgument(page_id, "devicewidth");
if (!deviceWidth.empty()) {
page->set_device_width(getFloat(deviceWidth.c_str()));
}
auto roundOff = getPageArgument(page_id, "roundoffdeviation");
if (!roundOff.empty()) {
page->set_round_off_deviation(getBool(roundOff));
}
auto reserveCssStyles = getPageArgument(page_id, "reserveCssStyles");
if (!reserveCssStyles.empty()) {
page->set_reserve_css_styles(getBool(reserveCssStyles));
}
}
} // namespace WeexCore
| 34.93049 | 123 | 0.638144 | [
"render",
"vector"
] |
90b759e5df2711abd92563e56b3fdf226648ec9e | 9,358 | hpp | C++ | include/OVR/AmbienceEmitter.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/OVR/AmbienceEmitter.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | null | null | null | include/OVR/AmbienceEmitter.hpp | v0idp/virtuoso-codegen | 6f560f04822c67f092d438a3f484249072c1d21d | [
"Unlicense"
] | 1 | 2022-03-30T21:07:35.000Z | 2022-03-30T21:07:35.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.MonoBehaviour
#include "UnityEngine/MonoBehaviour.hpp"
// Including type: UnityEngine.Vector2
#include "UnityEngine/Vector2.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-array.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: OVR
namespace OVR {
// Forward declaring type: SoundFXRef
class SoundFXRef;
}
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Transform
class Transform;
// Forward declaring type: Collider
class Collider;
}
// Completed forward declares
// Type namespace: OVR
namespace OVR {
// Forward declaring type: AmbienceEmitter
class AmbienceEmitter;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::OVR::AmbienceEmitter);
DEFINE_IL2CPP_ARG_TYPE(::OVR::AmbienceEmitter*, "OVR", "AmbienceEmitter");
// Type namespace: OVR
namespace OVR {
// Size: 0x4C
#pragma pack(push, 1)
// Autogenerated type: OVR.AmbienceEmitter
// [TokenAttribute] Offset: FFFFFFFF
class AmbienceEmitter : public ::UnityEngine::MonoBehaviour {
public:
public:
// public OVR.SoundFXRef[] ambientSounds
// Size: 0x8
// Offset: 0x18
::ArrayW<::OVR::SoundFXRef*> ambientSounds;
// Field size check
static_assert(sizeof(::ArrayW<::OVR::SoundFXRef*>) == 0x8);
// public System.Boolean autoActivate
// Size: 0x1
// Offset: 0x20
bool autoActivate;
// Field size check
static_assert(sizeof(bool) == 0x1);
// [TooltipAttribute] Offset: 0x6EE0B4
// public System.Boolean autoRetrigger
// Size: 0x1
// Offset: 0x21
bool autoRetrigger;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: autoRetrigger and: randomRetriggerDelaySecs
char __padding2[0x2] = {};
// [MinMaxAttribute] Offset: 0x6EE0EC
// public UnityEngine.Vector2 randomRetriggerDelaySecs
// Size: 0x8
// Offset: 0x24
::UnityEngine::Vector2 randomRetriggerDelaySecs;
// Field size check
static_assert(sizeof(::UnityEngine::Vector2) == 0x8);
// Padding between fields: randomRetriggerDelaySecs and: playPositions
char __padding3[0x4] = {};
// [TooltipAttribute] Offset: 0x6EE110
// public UnityEngine.Transform[] playPositions
// Size: 0x8
// Offset: 0x30
::ArrayW<::UnityEngine::Transform*> playPositions;
// Field size check
static_assert(sizeof(::ArrayW<::UnityEngine::Transform*>) == 0x8);
// private System.Boolean activated
// Size: 0x1
// Offset: 0x38
bool activated;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: activated and: playingIdx
char __padding5[0x3] = {};
// private System.Int32 playingIdx
// Size: 0x4
// Offset: 0x3C
int playingIdx;
// Field size check
static_assert(sizeof(int) == 0x4);
// private System.Single nextPlayTime
// Size: 0x4
// Offset: 0x40
float nextPlayTime;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Single fadeTime
// Size: 0x4
// Offset: 0x44
float fadeTime;
// Field size check
static_assert(sizeof(float) == 0x4);
// private System.Int32 lastPosIdx
// Size: 0x4
// Offset: 0x48
int lastPosIdx;
// Field size check
static_assert(sizeof(int) == 0x4);
public:
// Deleting conversion operator: operator ::System::IntPtr
constexpr operator ::System::IntPtr() const noexcept = delete;
// Get instance field reference: public OVR.SoundFXRef[] ambientSounds
[[deprecated("Use field access instead!")]] ::ArrayW<::OVR::SoundFXRef*>& dyn_ambientSounds();
// Get instance field reference: public System.Boolean autoActivate
[[deprecated("Use field access instead!")]] bool& dyn_autoActivate();
// Get instance field reference: public System.Boolean autoRetrigger
[[deprecated("Use field access instead!")]] bool& dyn_autoRetrigger();
// Get instance field reference: public UnityEngine.Vector2 randomRetriggerDelaySecs
[[deprecated("Use field access instead!")]] ::UnityEngine::Vector2& dyn_randomRetriggerDelaySecs();
// Get instance field reference: public UnityEngine.Transform[] playPositions
[[deprecated("Use field access instead!")]] ::ArrayW<::UnityEngine::Transform*>& dyn_playPositions();
// Get instance field reference: private System.Boolean activated
[[deprecated("Use field access instead!")]] bool& dyn_activated();
// Get instance field reference: private System.Int32 playingIdx
[[deprecated("Use field access instead!")]] int& dyn_playingIdx();
// Get instance field reference: private System.Single nextPlayTime
[[deprecated("Use field access instead!")]] float& dyn_nextPlayTime();
// Get instance field reference: private System.Single fadeTime
[[deprecated("Use field access instead!")]] float& dyn_fadeTime();
// Get instance field reference: private System.Int32 lastPosIdx
[[deprecated("Use field access instead!")]] int& dyn_lastPosIdx();
// public System.Void .ctor()
// Offset: 0x189D954
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static AmbienceEmitter* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::OVR::AmbienceEmitter::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<AmbienceEmitter*, creationType>()));
}
// private System.Void Awake()
// Offset: 0x189D330
void Awake();
// private System.Void Update()
// Offset: 0x189D4D4
void Update();
// public System.Void OnTriggerEnter(UnityEngine.Collider col)
// Offset: 0x189D6AC
void OnTriggerEnter(::UnityEngine::Collider* col);
// public System.Void Play()
// Offset: 0x189D534
void Play();
// public System.Void EnableEmitter(System.Boolean enable)
// Offset: 0x189D7E8
void EnableEmitter(bool enable);
}; // OVR.AmbienceEmitter
#pragma pack(pop)
static check_size<sizeof(AmbienceEmitter), 72 + sizeof(int)> __OVR_AmbienceEmitterSizeCheck;
static_assert(sizeof(AmbienceEmitter) == 0x4C);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: OVR::AmbienceEmitter::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: OVR::AmbienceEmitter::Awake
// Il2CppName: Awake
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (OVR::AmbienceEmitter::*)()>(&OVR::AmbienceEmitter::Awake)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(OVR::AmbienceEmitter*), "Awake", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: OVR::AmbienceEmitter::Update
// Il2CppName: Update
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (OVR::AmbienceEmitter::*)()>(&OVR::AmbienceEmitter::Update)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(OVR::AmbienceEmitter*), "Update", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: OVR::AmbienceEmitter::OnTriggerEnter
// Il2CppName: OnTriggerEnter
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (OVR::AmbienceEmitter::*)(::UnityEngine::Collider*)>(&OVR::AmbienceEmitter::OnTriggerEnter)> {
static const MethodInfo* get() {
static auto* col = &::il2cpp_utils::GetClassFromName("UnityEngine", "Collider")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(OVR::AmbienceEmitter*), "OnTriggerEnter", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{col});
}
};
// Writing MetadataGetter for method: OVR::AmbienceEmitter::Play
// Il2CppName: Play
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (OVR::AmbienceEmitter::*)()>(&OVR::AmbienceEmitter::Play)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(OVR::AmbienceEmitter*), "Play", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: OVR::AmbienceEmitter::EnableEmitter
// Il2CppName: EnableEmitter
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (OVR::AmbienceEmitter::*)(bool)>(&OVR::AmbienceEmitter::EnableEmitter)> {
static const MethodInfo* get() {
static auto* enable = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(OVR::AmbienceEmitter*), "EnableEmitter", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{enable});
}
};
| 43.525581 | 168 | 0.710515 | [
"vector",
"transform"
] |
90bc4f4961bbf66236a9768cbdda387dcccca2ed | 19,218 | cc | C++ | src/stream.cc | kwiberg/frz | 8661247c70e89a671b2b412c8c4f4c3f329ef98d | [
"Apache-2.0"
] | null | null | null | src/stream.cc | kwiberg/frz | 8661247c70e89a671b2b412c8c4f4c3f329ef98d | [
"Apache-2.0"
] | 12 | 2021-02-24T22:48:56.000Z | 2021-03-21T12:33:05.000Z | src/stream.cc | kwiberg/frz | 8661247c70e89a671b2b412c8c4f4c3f329ef98d | [
"Apache-2.0"
] | null | null | null | /*
Copyright 2021 Karl Wiberg
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 "stream.hh"
#include <absl/base/thread_annotations.h>
#include <absl/synchronization/mutex.h>
#include <algorithm>
#include <deque>
#include <optional>
#include "assert.hh"
#include "worker.hh"
namespace frz {
namespace {
// A very simple Streamer that will sequentially get bytes from the source,
// feed them to the sink, and repeat until the stream ends.
class SingleThreadedStreamer final : public Streamer {
public:
SingleThreadedStreamer(CreateSingleThreadedStreamerArgs args)
: buffer_(std::make_unique<std::byte[]>(args.buffer_size)),
buffer_size_(args.buffer_size) {}
void Stream(StreamSource& source, StreamSink& sink,
std::function<void(int num_bytes)> progress) override {
const std::span<std::byte> buffer(buffer_.get(), buffer_size_);
while (true) {
const auto result = source.GetBytes(buffer);
if (auto* bc = std::get_if<StreamSource::BytesCopied>(&result)) {
sink.AddBytes(buffer.subspan(0, bc->num_bytes));
progress(bc->num_bytes);
} else if (std::get_if<StreamSource::End>(&result)) {
break;
} else {
FRZ_CHECK(false);
}
}
}
void ForkedStream(ForkedStreamArgs args) override {
const std::span<std::byte> buffer(buffer_.get(), buffer_size_);
while (true) {
const auto result = args.source.GetBytes(buffer);
if (auto* bc = std::get_if<StreamSource::BytesCopied>(&result)) {
args.primary_sink.AddBytes(buffer.subspan(0, bc->num_bytes));
args.primary_progress(bc->num_bytes);
args.secondary_sink.AddBytes(buffer.subspan(0, bc->num_bytes));
args.secondary_progress(bc->num_bytes);
} else if (std::get_if<StreamSource::End>(&result)) {
static_cast<void>(args.primary_done());
break;
} else {
FRZ_CHECK(false);
}
}
}
private:
const std::unique_ptr<std::byte[]> buffer_;
const std::size_t buffer_size_;
};
// Move-only object that owns a heap-allocated array of bytes (size fixed at
// construction time), and keeps track of (1) the number of valid bytes and (2)
// whether this buffer contains the last byte of the stream.
//
// After being moved from or default constructed, the object must be assigned a
// new value before it can be read or written.
class StreamBuffer final {
public:
// Default constructor. Creates the buffer in an invalid state, just as if
// it had been moved from.
StreamBuffer() : data_(nullptr), capacity_(0) { FRZ_ASSERT(!Valid()); }
explicit StreamBuffer(int size)
: data_(std::make_unique<std::byte[]>(size)), capacity_(size) {
FRZ_ASSERT(Valid());
}
StreamBuffer(StreamBuffer&&) = default;
StreamBuffer& operator=(StreamBuffer&&) = default;
StreamBuffer(const StreamBuffer&) = delete;
StreamBuffer& operator=(const StreamBuffer&) = delete;
// Return the span of valid bytes.
std::span<const std::byte> Read() const {
FRZ_ASSERT(Valid());
return std::span(data_.get(), status_.size);
}
// Is the last byte in this buffer also the last byte of the whole stream?
bool End() const {
FRZ_ASSERT(Valid());
return status_.end;
}
// Return a writable span for the whole buffer. Callers must call
// .FinishWrite() when they're done writing to it.
std::span<std::byte> Write() {
FRZ_ASSERT(Valid());
return std::span(data_.get(), capacity_);
}
// Inform the buffer of how many bytes were written to it, and whether the
// last byte written is the last byte of the whole stream.
struct WriteStatus {
int size;
bool end;
};
void FinishWrite(WriteStatus status) {
FRZ_ASSERT(Valid());
FRZ_ASSERT_LE(status.size, capacity_);
status_ = status;
FRZ_ASSERT(Valid());
}
private:
bool Valid() const { return data_ && status_.size <= capacity_; }
std::unique_ptr<std::byte[]> data_;
int capacity_;
WriteStatus status_ = {.size = 0, .end = false};
};
// A queue of StreamBuffers. Its methods may be called concurrently with each
// other, but no method may be called concurrently with itself.
class StreamBufferQueue final {
public:
// Create a new circular stream buffer that may grow to at most
// `max_buffers` buffers, each of size `bytes_per_buffer`.
StreamBufferQueue(int max_buffers, int bytes_per_buffer)
: bytes_per_buffer_(bytes_per_buffer),
buffer_allocation_budget_(max_buffers) {}
// Clear the queue without freeing any memory.
void Clear() {
absl::MutexLock ml_unused(&unused_mutex_);
absl::MutexLock ml_filled(&filled_mutex_);
for (StreamBuffer& buf : filled_) {
unused_.push_back(std::move(buf));
}
filled_.clear();
}
// Get an unused buffer and write to it. Will block if there are no free
// buffers, and we've reached the limit for how many we may allocate.
void Enqueue(std::function<void(StreamBuffer& buf)> write_fun) {
bool success = Enqueue(write_fun, /*may_block=*/true);
FRZ_ASSERT(success); // only nonblocking Enqueue() can fail
}
// Get an unused buffer and write to it. Will return false without running
// `write_fun` if there are no free buffers, and we've reached the limit
// for how many we may allocate. Return true on success.
bool NonblockingEnqueue(std::function<void(StreamBuffer& buf)> write_fun) {
return Enqueue(write_fun, /*may_block=*/false);
}
// Get the oldest full buffer and read from it. Will block until there is a
// full buffer available.
void Dequeue(std::function<void(const StreamBuffer& buf)> read_fun) {
StreamBuffer buf;
// Grab the "filled" mutex, blocking until the "filled" queue isn't
// empty, and then pop the frontost buffer off the queue.
{
auto not_blocked = [&] { return !filled_.empty(); };
absl::MutexLock ml(&filled_mutex_, absl::Condition(¬_blocked));
FRZ_ASSERT(!filled_.empty());
buf = std::move(filled_.back());
filled_.pop_back();
}
// Let the caller read from the buffer.
read_fun(buf);
// Push the newly unused buffer onto the "unused" stack.
{
absl::MutexLock ml(&unused_mutex_);
unused_.push_back(std::move(buf));
}
}
private:
// Get an unused buffer and write to it. Will block (if `may_block` is
// true) or abort without running `write_fun` (if `may_block` is false)
// if there are no free buffers, and we've reached the limit for how many
// we may allocate. Return true if all went well, false if we aborted.
bool Enqueue(std::function<void(StreamBuffer& buf)>& write_fun,
bool may_block) {
StreamBuffer buf;
if (buffer_allocation_budget_ >= 1) {
// Grab the "unused" mutex without blocking, and pop the topmost
// unused buffer off the stack. If the "unused" stack is empty,
// release the mutex and then allocate a new buffer.
bool allocate_new = false;
{
absl::MutexLock ml(&unused_mutex_);
if (unused_.empty()) {
--buffer_allocation_budget_;
allocate_new = true;
} else {
buf = std::move(unused_.back());
unused_.pop_back();
}
}
if (allocate_new) {
buf = StreamBuffer(bytes_per_buffer_);
}
} else {
// Grab the "unused" mutex, blocking until the "unused" stack isn't
// empty, and then pop the topmost unused buffer off the stack.
auto not_blocked = [&] { return !may_block || !unused_.empty(); };
absl::MutexLock ml(&unused_mutex_, absl::Condition(¬_blocked));
if (unused_.empty()) {
// No unused buffer was immediately available.
return false;
}
buf = std::move(unused_.back());
unused_.pop_back();
}
// Let the caller fill the buffer.
write_fun(buf);
// Add the newly filled buffer to the back of the "filled" queue.
{
absl::MutexLock ml(&filled_mutex_);
filled_.push_back(std::move(buf));
}
return true;
}
const int bytes_per_buffer_;
// How many more buffers may we allocate? Not protected by a mutex, because
// it's only touched by `.Enqueue()`.
int buffer_allocation_budget_;
// Unused buffers. A stack, because while we don't care about the data in
// these buffers, we prefer to reuse memory that is cache hot.
absl::Mutex unused_mutex_;
std::vector<StreamBuffer> unused_ ABSL_GUARDED_BY(unused_mutex_);
// Filled buffers. A queue, because we must stream data in FIFO order.
// TODO: For better performance, reimplement as a fixed-size circular
// buffer protected by two `std::counting_semaphore`.
absl::Mutex filled_mutex_;
std::deque<StreamBuffer> filled_ ABSL_GUARDED_BY(filled_mutex_);
};
// TODO: Replace with `std::latch` once we have standard library support for
// it.
class Latch final {
public:
void CountDown() {
absl::MutexLock ml(&mutex_);
FRZ_ASSERT(!unlocked_);
unlocked_ = true;
}
void Wait() {
auto not_blocked = [&] { return unlocked_; };
absl::MutexLock ml(&mutex_, absl::Condition(¬_blocked));
}
private:
absl::Mutex mutex_;
bool unlocked_ ABSL_GUARDED_BY(mutex_) = false;
};
// A Streamer that runs the source in a woker thread and the sink in the
// current thread; this allows them to execute in parallel.
class MultiThreadedStreamer final : public Streamer {
public:
MultiThreadedStreamer(CreateMultiThreadedStreamerArgs args)
: primary_queue_(args.num_buffers, args.bytes_per_buffer),
secondary_queue_(args.num_buffers_secondary, args.bytes_per_buffer) {}
void Stream(StreamSource& source, StreamSink& sink,
std::function<void(int num_bytes)> progress) override {
primary_queue_.Clear(); // in case an earlier operation was interrupted
auto source_work = [&] {
for (bool end = false; !end;) {
primary_queue_.Enqueue([&](StreamBuffer& buf) {
auto result = FillBufferFromStream(source, buf.Write());
buf.FinishWrite(
{.size = result.num_bytes, .end = result.end});
end = result.end;
});
}
};
auto sink_work = [&] {
for (bool end = false; !end;) {
primary_queue_.Dequeue([&](const StreamBuffer& buf) {
sink.AddBytes(buf.Read());
progress(buf.Read().size());
end = buf.End();
});
}
};
// We run the source on a worker thread and the sink on this thread.
// That way, we can simply return without additional synchronization
// once the sink work is done.
worker_[0].Do(source_work);
sink_work();
}
void ForkedStream(ForkedStreamArgs args) override {
// Clear queues in case an earlier operation was interrupted.
primary_queue_.Clear();
secondary_queue_.Clear();
// We call the caller's callbacks from different threads. To guarantee
// that calls are sequential, we protect the calls with a mutex.
absl::Mutex callback_mutex;
// If and when we discover that we don't care about finishing the
// secondary stream, we set this flag to true.
std::atomic<bool> cancel_secondary_sink = false;
// Latches that get flipped when the sinks have eaten all their bytes.
Latch primary_sink_finished;
Latch secondary_sink_finished;
auto source_work = [&] {
std::optional<std::int64_t> secondary_restart_position;
// Stream data from `source` to `primary_sink`, and also to
// `secondary_sink` as long as it can keep up.
for (bool end = false; !end;) {
const std::int64_t pos = args.source.GetPosition();
primary_queue_.Enqueue([&](StreamBuffer& buf1) {
auto result =
FillBufferFromStream(args.source, buf1.Write());
buf1.FinishWrite(
{.size = result.num_bytes, .end = result.end});
end = result.end;
if (!secondary_restart_position.has_value()) {
const bool success =
secondary_queue_.NonblockingEnqueue(
[&](StreamBuffer& buf2) {
FRZ_ASSERT_LE(buf1.Read().size(),
buf2.Write().size());
std::ranges::copy(buf1.Read(),
buf2.Write().data());
buf2.FinishWrite({.size = result.num_bytes,
.end = result.end});
FRZ_ASSERT_EQ(buf1.Read().size(),
buf2.Read().size());
});
if (!success) {
// We couldn't stream the data to `secondary_sink`
// without blocking. Remember the position we need
// to restart from in case we want to finish it
// later.
secondary_restart_position = pos;
}
}
});
}
// Wait for the primary sink to eat all the bytes we sent it, then
// tell the caller that the primary stream is done.
primary_sink_finished.Wait();
const SecondaryStreamDecision ssd = [&] {
absl::MutexLock ml(&callback_mutex);
return args.primary_done();
}();
if (ssd == SecondaryStreamDecision::kAbandon) {
// The caller doesn't want the secondary stream. Ask it to stop
// ASAP and not finish flushing its buffer.
cancel_secondary_sink.store(true, std::memory_order_relaxed);
if (secondary_restart_position.has_value()) {
// The secondary stream may be blocked reading its buffer.
// Feed it an artificial end marker.
secondary_queue_.Enqueue([&](StreamBuffer& buf) {
buf.FinishWrite({.size = 0, .end = true});
});
}
} else if (ssd == SecondaryStreamDecision::kFinish &&
secondary_restart_position.has_value()) {
// The callers wants the secondary stream, but we haven't
// finished feeding its buffer. Do that.
args.source.SetPosition(*secondary_restart_position);
for (bool end = false; !end;) {
secondary_queue_.Enqueue([&](StreamBuffer& buf) {
auto result =
FillBufferFromStream(args.source, buf.Write());
buf.FinishWrite(
{.size = result.num_bytes, .end = result.end});
end = result.end;
});
}
}
// Wait for the secondary sink to finish.
secondary_sink_finished.Wait();
};
auto primary_sink_work = [&] {
for (bool end = false; !end;) {
primary_queue_.Dequeue([&](const StreamBuffer& buf) {
args.primary_sink.AddBytes(buf.Read());
end = buf.End();
absl::MutexLock ml(&callback_mutex);
args.primary_progress(buf.Read().size());
});
}
primary_sink_finished.CountDown();
};
auto secondary_sink_work = [&] {
for (bool end = false; !end && !cancel_secondary_sink.load(
std::memory_order_relaxed);) {
secondary_queue_.Dequeue([&](const StreamBuffer& buf) {
args.secondary_sink.AddBytes(buf.Read());
end = buf.End();
absl::MutexLock ml(&callback_mutex);
args.secondary_progress(buf.Read().size());
});
}
secondary_sink_finished.CountDown();
};
// `source_work` waits for both sinks to finish, so running the sinks
// on worker threads and the source on the current thread ensures that
// all work is finished before we return.
worker_[0].Do(primary_sink_work);
worker_[1].Do(secondary_sink_work);
source_work();
}
private:
StreamBufferQueue primary_queue_;
StreamBufferQueue secondary_queue_;
Worker worker_[2];
};
} // namespace
FillBufferFromStreamResult FillBufferFromStream(StreamSource& source,
std::span<std::byte> buffer) {
int num_bytes = 0;
while (num_bytes < std::ssize(buffer)) {
const auto result = source.GetBytes(buffer.subspan(num_bytes));
if (auto* bw = std::get_if<StreamSource::BytesCopied>(&result)) {
num_bytes += bw->num_bytes;
} else if (std::get_if<StreamSource::End>(&result)) {
return {.num_bytes = num_bytes, .end = true};
} else {
FRZ_CHECK(false);
}
}
FRZ_ASSERT_EQ(num_bytes, buffer.size());
return {.num_bytes = num_bytes, .end = false};
}
std::unique_ptr<Streamer> CreateSingleThreadedStreamer(
CreateSingleThreadedStreamerArgs args) {
return std::make_unique<SingleThreadedStreamer>(args);
}
std::unique_ptr<Streamer> CreateMultiThreadedStreamer(
CreateMultiThreadedStreamerArgs args) {
return std::make_unique<MultiThreadedStreamer>(args);
}
} // namespace frz
| 39.14053 | 80 | 0.577844 | [
"object",
"vector"
] |
90c15a549812fea0b815da6757a94eb7a398b181 | 797 | cpp | C++ | game/actors/Rock.cpp | mbellman/polygarden | 265d7f2516b94df3c930da73bc385871f0d1f896 | [
"Unlicense"
] | null | null | null | game/actors/Rock.cpp | mbellman/polygarden | 265d7f2516b94df3c930da73bc385871f0d1f896 | [
"Unlicense"
] | 1 | 2020-10-08T04:04:17.000Z | 2020-10-08T04:04:17.000Z | game/actors/Rock.cpp | mbellman/polygarden | 265d7f2516b94df3c930da73bc385871f0d1f896 | [
"Unlicense"
] | null | null | null | #include <PolyEngine.h>
#include "actors/Rock.h"
#include "HeightMap.h"
void Rock::onRegistered() {
stage->add<ReferenceMesh>("rock", [&](ReferenceMesh* rock) {
Mesh* shadowLod = new Mesh();
shadowLod->from(ObjLoader("./assets/rock-1/model-lod.obj"));
rock->from(ObjLoader("./assets/rock-1/model.obj"));
rock->texture = Texture::use("./assets/rock-1/texture.png");
rock->normalMap = Texture::use("./assets/rock-1/normals.png");
rock->shadowLod = shadowLod;
});
}
void Rock::onInit() {
stage->add<Instance>([&](Instance* rock) {
rock->from(stage->get<Mesh>("rock"));
rock->setPosition(HeightMap::getRandomGroundPosition());
rock->setScale(RNG::random(15.0f, 30.0f));
rock->setOrientation(Vec3f(0.0f, RNG::random(0.0f, M_PI * 2.0f), 0.0f));
});
} | 30.653846 | 76 | 0.643664 | [
"mesh",
"model"
] |
90c1c22e8cde5c69b554202951a529beb605186f | 1,987 | hpp | C++ | wechat/models/wx_msg.hpp | ArkBriar/WxPenguin | ae1cf9719a185b3ecb546e4f0537c6afc77ddb45 | [
"MIT"
] | 1 | 2017-03-13T09:59:30.000Z | 2017-03-13T09:59:30.000Z | wechat/models/wx_msg.hpp | arkbriar/WxPenguin | ae1cf9719a185b3ecb546e4f0537c6afc77ddb45 | [
"MIT"
] | null | null | null | wechat/models/wx_msg.hpp | arkbriar/WxPenguin | ae1cf9719a185b3ecb546e4f0537c6afc77ddb45 | [
"MIT"
] | null | null | null | #pragma once
#ifndef WX_MSG_HPP_ZFY2D0BN
#define WX_MSG_HPP_ZFY2D0BN
#include <string>
#include "../json/json.hpp"
namespace WebWx {
namespace Model {
class WxMsg {
public:
class WxRecommendInfo {
public:
WxRecommendInfo();
WxRecommendInfo(const nlohmann::json&);
std::string UserName;
std::string NickName;
int QQNum;
std::string Province;
std::string City;
std::string Content;
std::string Signature;
std::string Alias;
int Scene;
int VerifyFlag;
int AttrStatus;
int Sex;
std::string Ticket;
int OpCode;
};
class WxAppInfo {
public:
WxAppInfo();
WxAppInfo(const nlohmann::json&);
std::string AppID;
int Type;
};
WxMsg();
WxMsg(const nlohmann::json&);
std::string MsgId;
std::string FromUserName;
std::string ToUserName;
int MsgType;
std::string Content;
int Status;
int ImgStatus;
int CreateTime;
int VoiceLength;
int PlayLength;
std::string FileName;
std::string FileSize;
std::string MediaId;
std::string Url;
int AppMsgType;
int StatusNotifyCode;
int StatusNotifyUserName;
WxRecommendInfo RecommendInfo;
int ForwardFlag;
WxAppInfo AppInfo;
int HasProductId;
std::string Ticket;
int ImgHeight;
int ImgWidth;
int SubMsgType;
std::uint64_t NewMsgId;
};
}
}
#endif /* end of include guard: WX_MSG_HPP_ZFY2D0BN */
| 24.530864 | 55 | 0.471565 | [
"model"
] |
90c7a999530dc1230016999095a3be917ec6c696 | 8,215 | cpp | C++ | src/platformer/game/platformer_animation.cpp | marstau/shinsango | d9468787ae8e18fa478f936770d88e9bf93c11c0 | [
"BSD-3-Clause"
] | 1 | 2021-06-16T15:25:47.000Z | 2021-06-16T15:25:47.000Z | src/platformer/game/platformer_animation.cpp | marstau/shinsango | d9468787ae8e18fa478f936770d88e9bf93c11c0 | [
"BSD-3-Clause"
] | null | null | null | src/platformer/game/platformer_animation.cpp | marstau/shinsango | d9468787ae8e18fa478f936770d88e9bf93c11c0 | [
"BSD-3-Clause"
] | null | null | null | #include "animation.h"
#include <sstream>
#include "util/token.h"
#include "util/graphics/bitmap.h"
#include "util/debug.h"
#include "util/funcs.h"
#include "util/file-system.h"
#include "util/exceptions/load_exception.h"
using namespace std;
using namespace Platformer;
Frame::Frame(const Token *the_token, imageMap &images):
bmp(0),
time(0),
horizontalFlip(false),
verticalFlip(false),
alpha(255){
if ( *the_token != "frame" ){
throw LoadException(__FILE__, __LINE__, "Not an frame");
}
const Token & tok = *the_token;
/* Frame
use image -1 to not draw anything, it can be used to get a blinking effect
use time -1 to draw infinitly or until animation is reset
(frame
(image NUM)
(alpha NUM)
(hflip 0|1)
(vflip 0|1)
(time NUM))
*/
TokenView view = tok.view();
while (view.hasMore()){
try{
const Token * token;
view >> token;
if (*token == "image"){
// get the number
int num;
token->view() >> num;
// now assign the bitmap
bmp = images[num];
} else if (*token == "alpha"){
// get alpha
token->view() >> alpha;
} else if (*token == "hflip"){
// horizontal flip
token->view() >> horizontalFlip;
} else if (*token == "vflip"){
// horizontal flip
token->view() >> verticalFlip;
} else if (*token == "time"){
// time to display
token->view() >> time;
} else {
Global::debug( 3 ) << "Unhandled menu attribute: "<<endl;
if (Global::getDebug() >= 3){
token->print(" ");
}
}
} catch ( const TokenException & ex ) {
throw LoadException(__FILE__, __LINE__, ex, "Animation parse error");
} catch ( const LoadException & ex ) {
throw ex;
}
}
}
Frame::Frame(Graphics::Bitmap * bmp):
bmp(bmp),
time(0),
horizontalFlip(false),
verticalFlip(false),
alpha(255){
}
Frame::~Frame(){
}
static void renderSprite(int x, int y, const Graphics::Bitmap & sprite, int alpha, bool horizontalFlip, bool verticalFlip, const Graphics::Bitmap & where){
if (alpha != 255){
Graphics::Bitmap::transBlender( 0, 0, 0, alpha );
if (horizontalFlip && !verticalFlip){
sprite.translucent().drawHFlip(x,y, where);
} else if (!horizontalFlip && verticalFlip){
sprite.translucent().drawVFlip(x,y, where);
} else if (horizontalFlip && verticalFlip){
sprite.translucent().drawHVFlip(x,y, where);
} else if (!horizontalFlip && !verticalFlip){
sprite.translucent().draw(x,y, where);
}
} else {
if (horizontalFlip && !verticalFlip){
sprite.drawHFlip(x,y, where);
} else if (!horizontalFlip && verticalFlip){
sprite.drawVFlip(x,y, where);
} else if (horizontalFlip && verticalFlip){
sprite.drawHVFlip(x,y, where);
} else if (!horizontalFlip && !verticalFlip){
sprite.draw(x,y, where);
}
}
}
void Frame::draw(int x, int y, const Graphics::Bitmap & work){
if (!bmp){
return;
}
renderSprite(x, y, *bmp, alpha, horizontalFlip, verticalFlip, work);
}
static int findPosition(int end, int offset){
while (true){
offset-=end;
if (offset < end){
return offset;
}
}
}
void Frame::drawRepeatable(int x, int y, const Graphics::Bitmap & work){
if (!bmp){
return;
}
const int w = work.getWidth();
const int h = work.getHeight();
Graphics::Bitmap temp(w,h);
int x2 = 0;
int y2 = 0;
if (( (x + w) > bmp->getWidth()) || ((y + h) > bmp->getHeight()) ){
// Original position
if (x < bmp->getWidth()){
bmp->Blit(x,y,w,h,0,0,temp);
}
// Beyond X + W
if (x+w > bmp->getWidth()){
bmp->Blit(findPosition(bmp->getWidth(),x),y,w,h,0,0,temp);
}
// Beyond Y + H
if (y+h > bmp->getHeight()){
bmp->Blit(x,findPosition(bmp->getHeight(),y),w,h,0,0,temp);
}
} else {
bmp->Blit(x,y,w,h,0,0,temp);
}
renderSprite(0, 0, temp, alpha, horizontalFlip, verticalFlip, work);
}
Animation::Animation(const Token *the_token):
ticks(0),
currentFrame(0),
loop(0){
images[-1] = 0;
std::string basedir = "";
if ( *the_token != "animation" ){
throw LoadException(__FILE__, __LINE__, "Not an animation");
}
/* Animation:
The images must be listed prior to listing any frames, basedir can be used to set the directory where the images are located
loop will begin at the subsequent frame listed after loop
(anim (id NUM)
(basedir LOCATION)
(image NUM FILE)
(frame "Read comments above in constructor")
(loop NUM)
*/
const Token & tok = *the_token;
TokenView view = tok.view();
while (view.hasMore()){
try{
const Token * token;
view >> token;
if (*token == "id"){
// get the name
token->view() >> id;
} else if (*token == "basedir"){
// set the base directory for loading images
token->view() >> basedir;
} else if (*token == "image"){
// add bitmaps by number to the map
int number;
std::string temp;
token->view() >> number >> temp;
Global::debug(1, "Platformer") << "Loading image for animation number: " << id << ". Image: " << temp << endl;
Graphics::Bitmap *bmp = new Graphics::Bitmap(Storage::instance().find(Filesystem::RelativePath(basedir + temp)).path());
if (bmp->getError()){
delete bmp;
} else {
images[number] = bmp;
}
} else if (*token == "frame"){
// new frame
Frame *frame = new Frame(token, images);
frames.push_back(frame);
} else if (*token == "loop"){
// start loop here
int l;
token->view() >> l;
if (l >= (int)frames.size()){
ostringstream out;
out << "Loop location is larger than the number of frames. Loop: " << loop << " Frames: " << frames.size();
throw LoadException(__FILE__, __LINE__, out.str());
}
loop = l;
} else {
Global::debug( 3 ) << "Unhandled Animation attribute: "<<endl;
if (Global::getDebug() >= 3){
token->print(" ");
}
}
} catch ( const TokenException & ex ) {
throw LoadException(__FILE__, __LINE__, ex, "Animation parse error");
} catch ( const LoadException & ex ) {
throw ex;
}
}
if (id.empty()){
throw LoadException(__FILE__, __LINE__, "The animation has no identification, give it a name.");
}
}
Animation::~Animation(){
for (std::vector<Frame *>::iterator i = frames.begin(); i != frames.end(); ++i){
if (*i){
delete *i;
}
}
for (imageMap::iterator i = images.begin(); i != images.end(); ++i){
if (i->second){
delete i->second;
}
}
}
void Animation::act(){
if( frames[currentFrame]->getTime() != -1 ){
ticks++;
if(ticks >= frames[currentFrame]->getTime()){
ticks = 0;
forwardFrame();
}
}
}
void Animation::draw(int x, int y, const Graphics::Bitmap & work){
frames[currentFrame]->draw(x, y,work);
}
void Animation::drawRepeatable(int x, int y, const Graphics::Bitmap & work){
frames[currentFrame]->drawRepeatable(x, y,work);
}
void Animation::forwardFrame(){
if (currentFrame < frames.size() -1){
currentFrame++;
} else {
currentFrame = loop;
}
}
void Animation::backFrame(){
if (currentFrame > loop){
currentFrame--;
} else {
currentFrame = frames.size() - 1;
}
}
const Graphics::Bitmap & Animation::getBitmap() const {
return frames[currentFrame]->getBitmap();
}
| 29.65704 | 155 | 0.53451 | [
"vector"
] |
90cf10e8c368226d87032630970065d4b32bbabb | 21,732 | hpp | C++ | Model/Pods/Realm/core/include/tightdb/group_shared.hpp | huhuanming/ModelExampleForiOS | 78d442807e42da4851b0717f8916a4ee9adcf821 | [
"MIT"
] | 1 | 2016-01-14T09:45:31.000Z | 2016-01-14T09:45:31.000Z | Model/Pods/Realm/include-ios/tightdb/group_shared.hpp | huhuanming/ModelExampleForiOS | 78d442807e42da4851b0717f8916a4ee9adcf821 | [
"MIT"
] | null | null | null | Model/Pods/Realm/include-ios/tightdb/group_shared.hpp | huhuanming/ModelExampleForiOS | 78d442807e42da4851b0717f8916a4ee9adcf821 | [
"MIT"
] | null | null | null | /*************************************************************************
*
* TIGHTDB CONFIDENTIAL
* __________________
*
* [2011] - [2012] TightDB Inc
* All Rights Reserved.
*
* NOTICE: All information contained herein is, and remains
* the property of TightDB Incorporated and its suppliers,
* if any. The intellectual and technical concepts contained
* herein are proprietary to TightDB Incorporated
* and its suppliers and may be covered by U.S. and Foreign Patents,
* patents in process, and are protected by trade secret or copyright law.
* Dissemination of this information or reproduction of this material
* is strictly forbidden unless prior written permission is obtained
* from TightDB Incorporated.
*
**************************************************************************/
#ifndef TIGHTDB_GROUP_SHARED_HPP
#define TIGHTDB_GROUP_SHARED_HPP
#include <limits>
#include <tightdb/util/features.h>
#include <tightdb/group.hpp>
//#include <tightdb/commit_log.hpp>
namespace tightdb {
namespace _impl {
class WriteLogCollector;
}
/// A SharedGroup facilitates transactions.
///
/// When multiple threads or processes need to access a database
/// concurrently, they must do so using transactions. By design,
/// TightDB does not allow for multiple threads (or processes) to
/// share a single instance of SharedGroup. Instead, each concurrently
/// executing thread or process must use a separate instance of
/// SharedGroup.
///
/// Each instance of SharedGroup manages a single transaction at a
/// time. That transaction can be either a read transaction, or a
/// write transaction.
///
/// Utility classes ReadTransaction and WriteTransaction are provided
/// to make it safe and easy to work with transactions in a scoped
/// manner (by means of the RAII idiom). However, transactions can
/// also be explicitly started (begin_read(), begin_write()) and
/// stopped (end_read(), commit(), rollback()).
///
/// If a transaction is active when the SharedGroup is destroyed, that
/// transaction is implicitely terminated, either by a call to
/// end_read() or rollback().
///
/// Two processes that want to share a database file must reside on
/// the same host.
///
///
/// Desired exception behavior (not yet fully implemented)
/// ------------------------------------------------------
///
/// - If any data access API function throws an unexpcted exception during a
/// read transaction, the shared group accessor is left in state "error
/// during read".
///
/// - If any data access API function throws an unexpcted exception during a
/// write transaction, the shared group accessor is left in state "error
/// during write".
///
/// - If GroupShared::begin_write() or GroupShared::begin_read() throws an
/// unexpcted exception, the shared group accessor is left in state "no
/// transaction in progress".
///
/// - GroupShared::end_read() and GroupShared::rollback() do not throw.
///
/// - If GroupShared::commit() throws an unexpcted exception, the shared group
/// accessor is left in state "error during write" and the transaction was
/// not comitted.
///
/// - If GroupShared::advance_read() or GroupShared::promote_to_write() throws
/// an unexpcted exception, the shared group accessor is left in state "error
/// during read".
///
/// - If GroupShared::commit_and_continue_as_read() or
/// GroupShared::rollback_and_continue_as_read() throws an unexpcted
/// exception, the shared group accessor is left in state "error during
/// write".
///
/// It has not yet been decided exactly what an "unexpected exception" is, but
/// `std::bad_alloc` is surely one example. On the other hand, an expected
/// exception is one that is mentioned in the function specific documentation,
/// and is used to abort an operation due to a special, but expected condition.
///
/// States
/// ------
///
/// - A newly created shared group accessor is in state "no transaction in
/// progress".
///
/// - In state "error during read", almost all TightDB API functions are
/// illegal on the connected group of accessors. The only valid operations
/// are destruction of the shared group, and GroupShared::end_read(). If
/// GroupShared::end_read() is called, the new state becomes "no transaction
/// in progress".
///
/// - In state "error during write", almost all TightDB API functions are
/// illegal on the connected group of accessors. The only valid operations
/// are destruction of the shared group, and GroupShared::rollback(). If
/// GroupShared::end_write() is called, the new state becomes "no transaction
/// in progress"
class SharedGroup {
public:
enum DurabilityLevel {
durability_Full,
durability_MemOnly
#ifndef _WIN32
// Async commits are not yet supported on windows
, durability_Async
#endif
};
/// Equivalent to calling open(const std::string&, bool,
/// DurabilityLevel) on a default constructed instance.
explicit SharedGroup(const std::string& file, bool no_create = false,
DurabilityLevel dlevel = durability_Full);
struct unattached_tag {};
/// Create a SharedGroup instance in its unattached state. It may
/// then be attached to a database file later by calling
/// open(). You may test whether this instance is currently in its
/// attached state by calling is_attached(). Calling any other
/// function (except the destructor) while in the unattached state
/// has undefined behavior.
SharedGroup(unattached_tag) TIGHTDB_NOEXCEPT;
~SharedGroup() TIGHTDB_NOEXCEPT;
/// Attach this SharedGroup instance to the specified database
/// file.
///
/// If the database file does not already exist, it will be
/// created (unless \a no_create is set to true.) When multiple
/// threads are involved, it is safe to let the first thread, that
/// gets to it, create the file.
///
/// While at least one instance of SharedGroup exists for a
/// specific database file, a "lock" file will be present too. The
/// lock file will be placed in the same directory as the database
/// file, and its name will be derived by appending ".lock" to the
/// name of the database file.
///
/// When multiple SharedGroup instances refer to the same file,
/// they must specify the same durability level, otherwise an
/// exception will be thrown.
///
/// Calling open() on a SharedGroup instance that is already in
/// the attached state has undefined behavior.
///
/// \param file Filesystem path to a TightDB database file.
///
/// \throw util::File::AccessError If the file could not be
/// opened. If the reason corresponds to one of the exception
/// types that are derived from util::File::AccessError, the
/// derived exception type is thrown. Note that InvalidDatabase is
/// among these derived exception types.
void open(const std::string& file, bool no_create = false,
DurabilityLevel dlevel = durability_Full,
bool is_backend = false);
#ifdef TIGHTDB_ENABLE_REPLICATION
/// Equivalent to calling open(Replication&) on a
/// default constructed instance.
explicit SharedGroup(Replication& repl,
DurabilityLevel dlevel = durability_Full);
/// Open this group in replication mode. The specified Replication
/// instance must remain in exixtence for as long as the
/// SharedGroup.
void open(Replication&, DurabilityLevel dlevel = durability_Full);
friend class Replication;
#endif
/// A SharedGroup may be created in the unattached state, and then
/// later attached to a file with a call to open(). Calling any
/// function other than open(), is_attached(), and ~SharedGroup()
/// on an unattached instance results in undefined behavior.
bool is_attached() const TIGHTDB_NOEXCEPT;
/// Reserve disk space now to avoid allocation errors at a later
/// point in time, and to minimize on-disk fragmentation. In some
/// cases, less fragmentation translates into improved
/// performance.
///
/// When supported by the system, a call to this function will
/// make the database file at least as big as the specified size,
/// and cause space on the target device to be allocated (note
/// that on many systems on-disk allocation is done lazily by
/// default). If the file is already bigger than the specified
/// size, the size will be unchanged, and on-disk allocation will
/// occur only for the initial section that corresponds to the
/// specified size. On systems that do not support preallocation,
/// this function has no effect. To know whether preallocation is
/// supported by TightDB on your platform, call
/// util::File::is_prealloc_supported().
///
/// It is an error to call this function on an unattached shared
/// group. Doing so will result in undefined behavior.
void reserve(std::size_t size_in_bytes);
// Has db been modified since last transaction?
bool has_changed();
// Transactions:
// Begin a new read transaction. Accessors obtained prior to this point
// are invalid (if they weren't already) and new accessors must be
// obtained from the group returned.
const Group& begin_read();
// End a read transaction. Accessors are detached.
void end_read() TIGHTDB_NOEXCEPT;
// Begin a new write transaction. Accessors obtained prior to this point
// are invalid (if they weren't already) and new accessors must be
// obtained from the group returned. It is illegal to call begin_write
// inside an active transaction.
Group& begin_write();
// End the current write transaction. All accessors are detached.
void commit();
// End the current write transaction. All accessors are detached.
void rollback() TIGHTDB_NOEXCEPT;
// Pinned transactions:
// Shared group can work with either pinned or unpinned read transactions.
// - With unpinned read transactions, each new read transaction will refer
// to the latest database state.
// - With pinned read transactions, each new read transaction will refer
// to the database state as it was, when pin_read_transactions() was called,
// ignoring further changes until shared group is either unpinned or
// pinned again to a new state.
// Default is to use unpinned read transactions.
//
// You can only pin read transactions. You must unpin before starting a
// write transaction.
//
// Note that a write transaction can proceed via one SharedGroup, while
// read transactions are pinned via another SharedGroup that is attached
// to the same database. It is important to understand that each such
// write transaction will allocate resources (memory and/or disk), which
// will not be freed until the pinning is ended. For this reason, one should
// be careful to avoid long lived pinnings on databases that also see many
// write transactions.
// Pin subsequent read transactions to the current state. It is illegal
// to use pin_read_transactions() while a transaction is in progress. Returns true,
// if transactions are pinned to a new version of the database, false
// if there are no changes.
bool pin_read_transactions();
// Unpin, i.e. allow subsequent read transactions to refer to whatever
// is the current state when they are initiated. It is illegal to use
// unpin_read_transactions() while a transaction is in progress.
void unpin_read_transactions();
#ifdef TIGHTDB_DEBUG
void test_ringbuf();
#endif
/// If a stale .lock file is present when a SharedGroup is opened,
/// an Exception of type PresumablyStaleLockFile will be thrown.
/// The name of the stale lock file will be given as argument to the
/// exception. Important: In a heavily loaded scenario a lock file
/// may be considered stale, merely because the system is unresponsive
/// for a long period of time. Depending on your knowledge of the
/// system and its load, you must choose to either retry the operation
/// or manually remove the stale lock file.
class PresumablyStaleLockFile : public std::runtime_error {
public:
PresumablyStaleLockFile(const std::string& msg): std::runtime_error(msg) {}
};
// If the database file is deleted while there are open shared groups,
// subsequent attempts to open shared groups will try to join an already
// active sharing scheme, but fail due to the missing database file.
// This causes the following exception to be thrown from Open or the constructor.
class LockFileButNoData : public std::runtime_error {
public:
LockFileButNoData(const std::string& msg) : std::runtime_error(msg) {}
};
private:
struct SharedInfo;
struct ReadLockInfo {
uint_fast64_t m_version;
uint_fast32_t m_reader_idx;
ref_type m_top_ref;
size_t m_file_size;
ReadLockInfo() : m_version(std::numeric_limits<std::size_t>::max()),
m_reader_idx(0), m_top_ref(0), m_file_size(0) {};
};
// Member variables
Group m_group;
ReadLockInfo m_readlock;
uint_fast32_t m_local_max_entry;
util::File m_file;
util::File::Map<SharedInfo> m_file_map; // Never remapped
util::File::Map<SharedInfo> m_reader_map;
std::string m_file_path;
enum TransactStage {
transact_Ready,
transact_Reading,
transact_Writing
};
TransactStage m_transact_stage;
bool m_transactions_are_pinned;
struct ReadCount;
// Ring buffer managment
bool ringbuf_is_empty() const TIGHTDB_NOEXCEPT;
std::size_t ringbuf_size() const TIGHTDB_NOEXCEPT;
std::size_t ringbuf_capacity() const TIGHTDB_NOEXCEPT;
bool ringbuf_is_first(std::size_t ndx) const TIGHTDB_NOEXCEPT;
void ringbuf_remove_first() TIGHTDB_NOEXCEPT;
std::size_t ringbuf_find(uint64_t version) const TIGHTDB_NOEXCEPT;
ReadCount& ringbuf_get(std::size_t ndx) TIGHTDB_NOEXCEPT;
ReadCount& ringbuf_get_first() TIGHTDB_NOEXCEPT;
ReadCount& ringbuf_get_last() TIGHTDB_NOEXCEPT;
void ringbuf_put(const ReadCount& v);
void ringbuf_expand();
// Grab the latest readlock and update readlock info. Compare latest against
// current (before updating) and determine if the version is the same as before.
// As a side effect update memory mapping to ensure that the ringbuffer entries
// referenced in the readlock info is accessible.
// The caller may provide an uninitialized readlock in which case same_as_before
// is given an undefined value.
void grab_latest_readlock(ReadLockInfo& readlock, bool& same_as_before);
// Release a specific readlock. The readlock info MUST have been obtained by a
// call to grab_latest_readlock().
void release_readlock(ReadLockInfo& readlock) TIGHTDB_NOEXCEPT;
void do_begin_write();
void do_commit();
// Must be called only by someone that has a lock on the write
// mutex.
uint_fast64_t get_current_version();
// make sure the given index is within the currently mapped area.
// if not, expand the mapped area. Returns true if the area is expanded.
bool grow_reader_mapping(uint_fast32_t index);
// Must be called only by someone that has a lock on the write
// mutex.
void low_level_commit(uint_fast64_t new_version);
void do_async_commits();
#ifdef TIGHTDB_ENABLE_REPLICATION
class TransactLogRegistry {
public:
/// Get all transaction logs between the specified versions. The number
/// of requested logs is exactly `to_version - from_version`. If this
/// number is greater than zero, the first requested log is the one that
/// brings the database from `from_version` to `from_version +
/// 1`. References to the requested logs are store in successive entries
/// of `logs_buffer`. The calee retains ownership of the memory
/// referenced by those entries.
virtual void get_commit_entries(uint_fast64_t from_version, uint_fast64_t to_version,
BinaryData* logs_buffer) TIGHTDB_NOEXCEPT = 0;
/// Declare no further interest in the transaction logs between the
/// specified versions.
virtual void release_commit_entries(uint_fast64_t to_version) TIGHTDB_NOEXCEPT = 0;
virtual ~TransactLogRegistry() {}
};
// Advance the current read transaction to include latest state.
// All accessors are retained and synchronized to the new state
// according to the (to be) defined operational transform.
void advance_read(TransactLogRegistry& write_logs);
// Promote the current read transaction to a write transaction.
// CAUTION: This also synchronizes with latest state of the database,
// including synchronization of all accessors.
// FIXME: A version of this which does NOT synchronize with latest
// state will be made available later, once we are able to merge commits.
void promote_to_write(TransactLogRegistry& write_logs);
// End the current write transaction and transition atomically into
// a read transaction, WITHOUT synchronizing to external changes
// to data. All accessors are retained and continue to reflect the
// state at commit.
void commit_and_continue_as_read();
// Abort the current write transaction, discarding all changes within it,
// and thus restoring state to when promote_to_write() was last called.
// Any accessors referring to the aborted state will be detached. Accessors
// which was detached during the write transaction (for whatever reason)
// are not restored but will remain detached.
void rollback_and_continue_as_read();
// called by WriteLogCollector to transfer the actual commit log for
// accessor retention/update as part of rollback.
void do_rollback_and_continue_as_read(const char* begin, const char* end);
#endif
friend class ReadTransaction;
friend class WriteTransaction;
friend class LangBindHelper;
friend class _impl::WriteLogCollector;
};
class ReadTransaction {
public:
ReadTransaction(SharedGroup& sg):
m_shared_group(sg)
{
m_shared_group.begin_read(); // Throws
}
~ReadTransaction() TIGHTDB_NOEXCEPT
{
m_shared_group.end_read();
}
bool has_table(StringData name) const TIGHTDB_NOEXCEPT
{
return get_group().has_table(name);
}
ConstTableRef get_table(std::size_t table_ndx) const
{
return get_group().get_table(table_ndx); // Throws
}
ConstTableRef get_table(StringData name) const
{
return get_group().get_table(name); // Throws
}
template<class T> BasicTableRef<const T> get_table(StringData name) const
{
return get_group().get_table<T>(name); // Throws
}
const Group& get_group() const TIGHTDB_NOEXCEPT
{
return m_shared_group.m_group;
}
private:
SharedGroup& m_shared_group;
};
class WriteTransaction {
public:
WriteTransaction(SharedGroup& sg):
m_shared_group(&sg)
{
m_shared_group->begin_write(); // Throws
}
~WriteTransaction() TIGHTDB_NOEXCEPT
{
if (m_shared_group)
m_shared_group->rollback();
}
TableRef get_table(std::size_t table_ndx) const
{
return get_group().get_table(table_ndx); // Throws
}
TableRef get_table(StringData name) const
{
return get_group().get_table(name); // Throws
}
TableRef add_table(StringData name, bool require_unique_name = true) const
{
return get_group().add_table(name, require_unique_name); // Throws
}
TableRef get_or_add_table(StringData name, bool* was_added = 0) const
{
return get_group().get_or_add_table(name, was_added); // Throws
}
template<class T> BasicTableRef<T> get_table(StringData name) const
{
return get_group().get_table<T>(name); // Throws
}
template<class T>
BasicTableRef<T> add_table(StringData name, bool require_unique_name = true) const
{
return get_group().add_table<T>(name, require_unique_name); // Throws
}
template<class T> BasicTableRef<T> get_or_add_table(StringData name, bool* was_added = 0) const
{
return get_group().get_or_add_table<T>(name, was_added); // Throws
}
Group& get_group() const TIGHTDB_NOEXCEPT
{
TIGHTDB_ASSERT(m_shared_group);
return m_shared_group->m_group;
}
void commit()
{
TIGHTDB_ASSERT(m_shared_group);
m_shared_group->commit();
m_shared_group = 0;
}
private:
SharedGroup* m_shared_group;
};
// Implementation:
inline SharedGroup::SharedGroup(const std::string& file, bool no_create, DurabilityLevel dlevel):
m_group(Group::shared_tag()),
m_transactions_are_pinned(false)
{
open(file, no_create, dlevel);
}
inline SharedGroup::SharedGroup(unattached_tag) TIGHTDB_NOEXCEPT:
m_group(Group::shared_tag()),
m_transactions_are_pinned(false)
{
}
inline bool SharedGroup::is_attached() const TIGHTDB_NOEXCEPT
{
return m_file_map.is_attached();
}
#ifdef TIGHTDB_ENABLE_REPLICATION
inline SharedGroup::SharedGroup(Replication& repl, DurabilityLevel dlevel):
m_group(Group::shared_tag()),
m_transactions_are_pinned(false)
{
open(repl, dlevel);
}
#endif
} // namespace tightdb
#endif // TIGHTDB_GROUP_SHARED_HPP
| 37.860627 | 99 | 0.695104 | [
"transform"
] |
90d15939b5a9e8736b1397a4d74db546b099c603 | 1,107 | cpp | C++ | lib/tolerator-rt/runtime.cpp | chintanaprabhu/LLVM-dynamic-analysis | dff9140b194a49c343bfa4062b52ee646e3fd409 | [
"MIT"
] | null | null | null | lib/tolerator-rt/runtime.cpp | chintanaprabhu/LLVM-dynamic-analysis | dff9140b194a49c343bfa4062b52ee646e3fd409 | [
"MIT"
] | null | null | null | lib/tolerator-rt/runtime.cpp | chintanaprabhu/LLVM-dynamic-analysis | dff9140b194a49c343bfa4062b52ee646e3fd409 | [
"MIT"
] | null | null | null |
#include <cstdint>
#include <cstdio>
#include <iostream>
#include <map>
#include <vector>
extern "C" {
// This macro allows us to prefix strings so that they are less likely to
// conflict with existing symbol names in the examined programs.
// e.g. TOLERATE(entry) yields ToLeRaToR_entry
#define TOLERATE(X) ToLeRaToR_##X
std::map<int64_t, int64_t> addressMap;
void
TOLERATE(helloworld)() {
printf("==============================\n"
"\tHello, World!\n"
"==============================\n");
}
void
TOLERATE(goodbyeworld)() {
printf("==============================\n"
"\tGoodbye, World!\n"
"==============================\n");
}
void TOLERATE(saveRange)(int64_t startAddress, int64_t elements) {
addressMap[startAddress] = elements;
}
bool TOLERATE(loadValidate)(int64_t address, int64_t size) {
auto it = addressMap.lower_bound(address);
int64_t base = (*it).first;
int64_t allocatedSize = (*it).second;
if(base <= address && address+size <= base+allocatedSize) {
return true;
}
printf("FOUND: Invalid read from memory\n");
exit(0);
}
}
| 23.0625 | 73 | 0.599819 | [
"vector"
] |
90d3ba6fe66c7d47044ff7bf2f587bf39c88151a | 2,069 | cc | C++ | SimG4Core/DD4hepGeometry/test/plugins/DD4hepTestG4Geometry.cc | skyriacoCMS/cmssw | 17507fb9bbd5f1db06dda9c95d52758ef2356994 | [
"Apache-2.0"
] | null | null | null | SimG4Core/DD4hepGeometry/test/plugins/DD4hepTestG4Geometry.cc | skyriacoCMS/cmssw | 17507fb9bbd5f1db06dda9c95d52758ef2356994 | [
"Apache-2.0"
] | null | null | null | SimG4Core/DD4hepGeometry/test/plugins/DD4hepTestG4Geometry.cc | skyriacoCMS/cmssw | 17507fb9bbd5f1db06dda9c95d52758ef2356994 | [
"Apache-2.0"
] | null | null | null | #include "FWCore/Framework/interface/one/EDAnalyzer.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include "FWCore/Framework/interface/ESTransientHandle.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "DetectorDescription/DDCMS/interface/DDDetector.h"
#include "DetectorDescription/DDCMS/interface/DDVectorRegistry.h"
#include "Geometry/Records/interface/DDVectorRegistryRcd.h"
#include "Geometry/Records/interface/GeometryFileRcd.h"
#include "DDG4/Geant4Converter.h"
#include "DD4hep/Detector.h"
#include <iostream>
#include <string>
using namespace std;
using namespace cms;
using namespace edm;
using namespace dd4hep;
class DD4hepTestG4Geometry : public one::EDAnalyzer<> {
public:
explicit DD4hepTestG4Geometry(const ParameterSet&);
void beginJob() override {}
void analyze(Event const& iEvent, EventSetup const&) override;
void endJob() override {}
private:
const ESInputTag m_tag;
const string m_detElementPath;
const string m_placedVolPath;
};
DD4hepTestG4Geometry::DD4hepTestG4Geometry(const ParameterSet& iConfig)
: m_tag(iConfig.getParameter<ESInputTag>("DDDetector"))
{}
void
DD4hepTestG4Geometry::analyze(const Event&, const EventSetup& iEventSetup)
{
LogVerbatim("Geometry") << "\nDD4hepTestG4Geometry::analyze: " << m_tag;
const DDVectorRegistryRcd& regRecord = iEventSetup.get<DDVectorRegistryRcd>();
ESTransientHandle<DDVectorRegistry> reg;
regRecord.get(m_tag.module(), reg);
const GeometryFileRcd& ddRecord = iEventSetup.get<GeometryFileRcd>();
ESTransientHandle<DDDetector> ddd;
ddRecord.get(m_tag.module(), ddd);
const dd4hep::Detector& detector = *ddd->description();
dd4hep::sim::Geant4Converter g4Geo = dd4hep::sim::Geant4Converter(detector);
g4Geo.debugMaterials = true;
g4Geo.debugElements = true;
g4Geo.debugShapes = true;
g4Geo.debugVolumes = true;
g4Geo.debugPlacements = true;
g4Geo.create(detector.world());
LogVerbatim("Geometry") << "Done.";
}
DEFINE_FWK_MODULE(DD4hepTestG4Geometry);
| 31.348485 | 80 | 0.777187 | [
"geometry"
] |
90d4a4ead42c14b93c4b76a7cf4826c250c5be78 | 876 | cpp | C++ | tests/Mock/FFTCheckerFilter.cpp | AudioTK/AudioTK | dba42eea68534501efe74692b74edf4792cca231 | [
"BSD-3-Clause"
] | 23 | 2021-02-04T10:47:46.000Z | 2022-03-25T03:45:00.000Z | tests/Mock/FFTCheckerFilter.cpp | AudioTK/AudioTK | dba42eea68534501efe74692b74edf4792cca231 | [
"BSD-3-Clause"
] | 2 | 2021-02-01T15:45:06.000Z | 2021-09-13T19:39:05.000Z | tests/Mock/FFTCheckerFilter.cpp | AudioTK/AudioTK | dba42eea68534501efe74692b74edf4792cca231 | [
"BSD-3-Clause"
] | 2 | 2021-04-12T03:28:12.000Z | 2021-12-17T00:47:11.000Z | /**
* \file FFTCheckerFilter.cpp
*/
#include <ATK/Core/TypedBaseFilter.h>
#include <ATK/Mock/FFTCheckerFilter.h>
#include <ATK/Mock/SimpleSinusGeneratorFilter.h>
#include <gtest/gtest.h>
constexpr gsl::index PROCESSSIZE = (1024 * 1024);
TEST(FFTCheckerFilter, sinus_test)
{
ATK::SimpleSinusGeneratorFilter<double> generator;
generator.set_output_sampling_rate(1024*64);
generator.set_amplitude(1);
generator.set_frequency(1000);
ATK::FFTCheckerFilter<double> checker;
checker.set_input_sampling_rate(1024*64);
std::vector<std::pair<int, double> > frequency_checks;
frequency_checks.push_back(std::make_pair(100, 0));
frequency_checks.push_back(std::make_pair(1000, 1));
frequency_checks.push_back(std::make_pair(10000, 0));
checker.set_checks(frequency_checks);
checker.set_input_port(0, &generator, 0);
checker.process(PROCESSSIZE);
}
| 26.545455 | 56 | 0.760274 | [
"vector"
] |
90d5d4bc6faecc749e6fb5675d78614627ca61a6 | 42,135 | cc | C++ | cryptohome/vault_keyset_unittest.cc | ascii33/platform2 | b78891020724e9ff26b11ca89c2a53f949e99748 | [
"BSD-3-Clause"
] | null | null | null | cryptohome/vault_keyset_unittest.cc | ascii33/platform2 | b78891020724e9ff26b11ca89c2a53f949e99748 | [
"BSD-3-Clause"
] | null | null | null | cryptohome/vault_keyset_unittest.cc | ascii33/platform2 | b78891020724e9ff26b11ca89c2a53f949e99748 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Unit tests for VaultKeyset.
#include "cryptohome/vault_keyset.h"
#include <memory>
#include <openssl/evp.h>
#include <optional>
#include <string.h> // For memcmp().
#include <utility>
#include <variant>
#include <vector>
#include <base/files/file_path.h>
#include <base/logging.h>
#include <base/strings/string_number_conversions.h>
#include <brillo/secure_blob.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <libhwsec-foundation/crypto/aes.h>
#include <libhwsec-foundation/crypto/hmac.h>
#include <libhwsec-foundation/crypto/secure_blob_util.h>
#include <libhwsec-foundation/error/testing_helper.h>
#include "cryptohome/auth_blocks/auth_block.h"
#include "cryptohome/auth_blocks/auth_block_state.h"
#include "cryptohome/auth_blocks/auth_block_utils.h"
#include "cryptohome/auth_blocks/libscrypt_compat_auth_block.h"
#include "cryptohome/auth_blocks/pin_weaver_auth_block.h"
#include "cryptohome/crypto.h"
#include "cryptohome/crypto_error.h"
#include "cryptohome/cryptohome_common.h"
#include "cryptohome/mock_cryptohome_keys_manager.h"
#include "cryptohome/mock_le_credential_manager.h"
#include "cryptohome/mock_platform.h"
#include "cryptohome/mock_tpm.h"
#include "cryptohome/storage/file_system_keyset.h"
namespace cryptohome {
using base::FilePath;
using brillo::SecureBlob;
using cryptohome::error::CryptohomeCryptoError;
using cryptohome::error::CryptohomeError;
using cryptohome::error::CryptohomeLECredError;
using cryptohome::error::ErrorAction;
using cryptohome::error::ErrorActionSet;
using hwsec_foundation::CreateSecureRandomBlob;
using hwsec_foundation::GetSecureRandom;
using hwsec_foundation::HmacSha256;
using hwsec_foundation::kAesBlockSize;
using hwsec_foundation::SecureBlobToHex;
using hwsec_foundation::error::testing::ReturnError;
using hwsec_foundation::status::OkStatus;
using ::testing::_;
using ::testing::DoAll;
using ::testing::NiceMock;
using ::testing::Return;
using ::testing::SaveArg;
using ::testing::SetArgPointee;
using ::testing::WithArg;
namespace {
constexpr char kHexHighEntropySecret[] =
"F3D9D5B126C36676689E18BB8517D95DF4F30947E71D4A840824425760B1D3FA";
constexpr char kHexResetSecret[] =
"B133D2450392335BA8D33AA95AD52488254070C66F5D79AEA1A46AC4A30760D4";
constexpr char kHexWrappedKeyset[] =
"B737B5D73E39BD390A4F361CE2FC166CF1E89EC6AEAA35D4B34456502C48B4F5EFA310077"
"324B393E13AF633DF3072FF2EC78BD2B80D919035DB97C30F1AD418737DA3F26A4D35DF6B"
"6A9743BD0DF3D37D8A68DE0932A9905452D05ECF92701B9805937F76EE01D10924268F057"
"EDD66087774BB86C2CB92B01BD3A3C41C10C52838BD3A3296474598418E5191DEE9E8D831"
"3C859C9EDB0D5F2BC1D7FC3C108A0D4ABB2D90E413086BCFFD0902AB68E2BF787817EB10C"
"25E2E43011CAB3FB8AA";
constexpr char kHexSalt[] = "D470B9B108902241";
constexpr char kHexVaultKey[] =
"665A58534E684F2B61516B6D42624B514E6749732B4348427450305453754158377232347"
"37A79466C6B383D";
constexpr char kHexFekIv[] = "EA80F14BF29C6D580D536E7F0CC47F3E";
constexpr char kHexChapsIv[] = "ED85D928940E5B02ED218F29225AA34F";
constexpr char kHexWrappedChapsKey[] =
"7D7D01EECC8DAE7906CAD56310954BBEB3CC81765210D29902AB92DDE074217771AD284F2"
"12C13897C6CBB30CEC4CD75";
constexpr int kLegacyIndex = 1;
constexpr char kLegacyLabel[] = "legacy-1";
constexpr char kTempLabel[] = "tempLabel";
constexpr char kFilePath[] = "foo";
constexpr char kPasswordKey[] = "key";
constexpr char kObfuscatedUsername[] = "foo@gmail.com";
constexpr char kFakePasswordKey[] = "blabla";
constexpr int kPasswordRounds = 5;
// Generated with this command:
// cryptohome --action=mount_ex --user=fakeuser1@example.com
// --key_label=PasswordLabel --create --password=FakePasswordForFakeUser1
constexpr char kHexLibScryptExampleSerializedVaultKeyset[] =
"0802120869528fca742022fd1ab402736372797074000e00000008000000"
"019602e181d3047f2560d889b199015da9a2786101a1d491dccc7a9bd516"
"2d4ef72cd09817ab78dd27355bd45f5dd2c66a89f9b4c7911d2a85126e2a"
"ee5df1a88dceaa1b4adb5b98fc0107f5bafd881fb8b552cef71067cdfa39"
"6d11c51e5467a8937c393687eb407de488015ec793fe87bf5cd6987ff50d"
"e13111ee4604b774b951adc18ccc3ae0132e842df56b38e8256238fa3205"
"8ae9425451c54f8527669ad67888b64deabdf974d701ff7c429942979edf"
"ae07b8cf6b82e6a11c764ab216814de8652706c6aedc66f3ec7da371fd92"
"912742879e8bae064970b453c9e94d5f3677b80103f958599f8ee9aa6e68"
"3d497e4cc464666b71ec25c67336713cfb79020ee36a0ef2ae8a210c0b97"
"9e0ec287d0b622f7706ea7ace69c856ecc37b2221e5fb34a13120d506173"
"73776f72644c6162656c42021000529001736372797074000e0000000800"
"000001b9eed4ad3694dc8fcec59a06c16e508829e99bf1a45dabb1298574"
"c873f885d9355b3294bd243e40382fda5651ae094ab270188068d42e3bd8"
"320bbb57a165a613d70998310e9c6c3ea1f6759603275d22968ca3bda165"
"dc5dbc77921411ae5ba426ea84fcb29e8ee7c758be9a2e1c544d2834bd2c"
"ea69f49b484e68fca167265aa001736372797074000e0000000800000001"
"6f632b3a3faab2347327f58e4146fc00b1dddea4e7971caf7b3a49b6c02e"
"8ad24fb05076c16b7d1065df6379ef34b54a97231edb7393a7446beec328"
"afc962c24e123dd9e81a451c4f0f670f20e51662171c319127f96fd2718d"
"d6e73b29f32b86ffcc3cf115243f810ddcdc9be1e2ba3aba5d30cf3457e8"
"02f9da1d6c5934af7651cd9cca3d53ab5c6cafc057f52e8b";
constexpr char kHexLibScryptExampleSalt[] = "69528fca742022fd";
constexpr char kHexLibScryptExamplePasskey[] =
"6335336231666336333130336466313430356266626235336630303133366264";
constexpr char kHexLibScryptExampleFek[] =
"1b70e790b9d48ae2d695bfba06ee8b47bece82c990569e191a79b9c1a256fa7140f1e69090"
"eb2c59d4370a9ff9bc623989c72b3617013a91c8ad52ab9c80d8a1";
constexpr char kHexLibScryptExampleFekSig[] = "7535f385362a8450";
constexpr char kHexLibScryptExampleFekSalt[] = "4e8f98e96de8d6ae";
constexpr char kHexLibScryptExampleFnek[] =
"0ccf1c6a7e319665f843f950de0b9f82ce72ddb2e8eb4727a7c7b4786fbf307dc861696f36"
"a17044bd4f69949269088fab95cea159354a4968252d510c1e93a1";
constexpr char kHexLibScryptExampleFnekSig[] = "71cb91c3ab4f2721";
constexpr char kHexLibScryptExampleFnekSalt[] = "65ee2c9d0fea7161";
std::string HexDecode(const std::string& hex) {
std::vector<uint8_t> output;
CHECK(base::HexStringToBytes(hex, &output));
return std::string(output.begin(), output.end());
}
} // namespace
class VaultKeysetTest : public ::testing::Test {
public:
VaultKeysetTest() : crypto_(&platform_) {}
VaultKeysetTest(const VaultKeysetTest&) = delete;
VaultKeysetTest& operator=(const VaultKeysetTest&) = delete;
virtual ~VaultKeysetTest() {}
static bool FindBlobInBlob(const brillo::SecureBlob& haystack,
const brillo::SecureBlob& needle) {
if (needle.size() > haystack.size()) {
return false;
}
for (unsigned int start = 0; start <= (haystack.size() - needle.size());
start++) {
if (memcmp(&haystack[start], needle.data(), needle.size()) == 0) {
return true;
}
}
return false;
}
protected:
MockPlatform platform_;
Crypto crypto_;
NiceMock<MockTpm> tpm_;
};
TEST_F(VaultKeysetTest, AllocateRandom) {
// Check that allocating a random VaultKeyset works
VaultKeyset vault_keyset;
vault_keyset.Initialize(&platform_, &crypto_);
vault_keyset.CreateFromFileSystemKeyset(FileSystemKeyset::CreateRandom());
EXPECT_EQ(CRYPTOHOME_DEFAULT_KEY_SIZE, vault_keyset.GetFek().size());
EXPECT_EQ(CRYPTOHOME_DEFAULT_KEY_SIGNATURE_SIZE,
vault_keyset.GetFekSig().size());
EXPECT_EQ(CRYPTOHOME_DEFAULT_KEY_SALT_SIZE, vault_keyset.GetFekSalt().size());
EXPECT_EQ(CRYPTOHOME_DEFAULT_KEY_SIZE, vault_keyset.GetFnek().size());
EXPECT_EQ(CRYPTOHOME_DEFAULT_KEY_SIGNATURE_SIZE,
vault_keyset.GetFnekSig().size());
EXPECT_EQ(CRYPTOHOME_DEFAULT_KEY_SALT_SIZE,
vault_keyset.GetFnekSalt().size());
EXPECT_EQ(CRYPTOHOME_CHAPS_KEY_LENGTH, vault_keyset.GetChapsKey().size());
}
TEST_F(VaultKeysetTest, SerializeTest) {
// Check that serialize works
VaultKeyset vault_keyset;
vault_keyset.Initialize(&platform_, &crypto_);
vault_keyset.CreateFromFileSystemKeyset(FileSystemKeyset::CreateRandom());
SecureBlob blob;
EXPECT_TRUE(vault_keyset.ToKeysBlob(&blob));
EXPECT_TRUE(VaultKeysetTest::FindBlobInBlob(blob, vault_keyset.GetFek()));
EXPECT_TRUE(VaultKeysetTest::FindBlobInBlob(blob, vault_keyset.GetFekSig()));
EXPECT_TRUE(VaultKeysetTest::FindBlobInBlob(blob, vault_keyset.GetFekSalt()));
EXPECT_TRUE(VaultKeysetTest::FindBlobInBlob(blob, vault_keyset.GetFnek()));
EXPECT_TRUE(VaultKeysetTest::FindBlobInBlob(blob, vault_keyset.GetFnekSig()));
EXPECT_TRUE(
VaultKeysetTest::FindBlobInBlob(blob, vault_keyset.GetFnekSalt()));
}
TEST_F(VaultKeysetTest, DeserializeTest) {
// Check that deserialize works
VaultKeyset vault_keyset;
vault_keyset.Initialize(&platform_, &crypto_);
vault_keyset.CreateFromFileSystemKeyset(FileSystemKeyset::CreateRandom());
SecureBlob blob;
EXPECT_TRUE(vault_keyset.ToKeysBlob(&blob));
VaultKeyset new_vault_keyset;
new_vault_keyset.FromKeysBlob(blob);
EXPECT_EQ(vault_keyset.GetFek().size(), new_vault_keyset.GetFek().size());
EXPECT_TRUE(VaultKeysetTest::FindBlobInBlob(vault_keyset.GetFek(),
new_vault_keyset.GetFek()));
EXPECT_EQ(vault_keyset.GetFekSig().size(),
new_vault_keyset.GetFekSig().size());
EXPECT_TRUE(VaultKeysetTest::FindBlobInBlob(vault_keyset.GetFekSig(),
new_vault_keyset.GetFekSig()));
EXPECT_EQ(vault_keyset.GetFekSalt().size(),
new_vault_keyset.GetFekSalt().size());
EXPECT_TRUE(VaultKeysetTest::FindBlobInBlob(vault_keyset.GetFekSalt(),
new_vault_keyset.GetFekSalt()));
EXPECT_EQ(vault_keyset.GetFnek().size(), new_vault_keyset.GetFnek().size());
EXPECT_TRUE(VaultKeysetTest::FindBlobInBlob(vault_keyset.GetFnek(),
new_vault_keyset.GetFnek()));
EXPECT_EQ(vault_keyset.GetFnekSig().size(),
new_vault_keyset.GetFnekSig().size());
EXPECT_TRUE(VaultKeysetTest::FindBlobInBlob(vault_keyset.GetFnekSig(),
new_vault_keyset.GetFnekSig()));
EXPECT_EQ(vault_keyset.GetFnekSalt().size(),
new_vault_keyset.GetFnekSalt().size());
EXPECT_TRUE(VaultKeysetTest::FindBlobInBlob(vault_keyset.GetFnekSalt(),
new_vault_keyset.GetFnekSalt()));
}
ACTION_P(CopyToSecureBlob, b) {
b->assign(arg0.begin(), arg0.end());
return true;
}
ACTION_P(CopyFromSecureBlob, b) {
arg0->assign(b->begin(), b->end());
return true;
}
TEST_F(VaultKeysetTest, LoadSaveTest) {
VaultKeyset keyset;
keyset.Initialize(&platform_, &crypto_);
keyset.CreateFromFileSystemKeyset(FileSystemKeyset::CreateRandom());
SecureBlob bytes;
static const int kFscryptPolicyVersion = 2;
keyset.SetFSCryptPolicyVersion(kFscryptPolicyVersion);
EXPECT_CALL(platform_, WriteFileAtomicDurable(FilePath(kFilePath), _, _))
.WillOnce(WithArg<1>(CopyToSecureBlob(&bytes)));
EXPECT_CALL(platform_, ReadFile(FilePath(kFilePath), _))
.WillOnce(WithArg<1>(CopyFromSecureBlob(&bytes)));
SecureBlob key(kPasswordKey);
std::string obfuscated_username(kObfuscatedUsername);
EXPECT_TRUE(keyset.Encrypt(key, obfuscated_username));
EXPECT_TRUE(keyset.Save(FilePath(kFilePath)));
VaultKeyset new_keyset;
new_keyset.Initialize(&platform_, &crypto_);
EXPECT_TRUE(new_keyset.Load(FilePath(kFilePath)));
EXPECT_TRUE(new_keyset.Decrypt(key, false /* locked_to_single_user */,
nullptr /* crypto_error */));
EXPECT_EQ(new_keyset.GetFSCryptPolicyVersion(), kFscryptPolicyVersion);
}
TEST_F(VaultKeysetTest, WriteError) {
VaultKeyset keyset;
keyset.Initialize(&platform_, &crypto_);
keyset.CreateFromFileSystemKeyset(FileSystemKeyset::CreateRandom());
SecureBlob bytes;
EXPECT_CALL(platform_, WriteFileAtomicDurable(FilePath(kFilePath), _, _))
.WillOnce(Return(false));
SecureBlob key(kPasswordKey);
std::string obfuscated_username(kObfuscatedUsername);
EXPECT_TRUE(keyset.Encrypt(key, obfuscated_username));
EXPECT_FALSE(keyset.Save(FilePath(kFilePath)));
}
TEST_F(VaultKeysetTest, AuthLockedDefault) {
VaultKeyset keyset;
keyset.Initialize(&platform_, &crypto_);
static const int kFscryptPolicyVersion = 2;
keyset.CreateFromFileSystemKeyset(FileSystemKeyset::CreateRandom());
keyset.SetFSCryptPolicyVersion(kFscryptPolicyVersion);
keyset.SetFlags(SerializedVaultKeyset::LE_CREDENTIAL);
SecureBlob key(kPasswordKey);
std::string obfuscated_username(kObfuscatedUsername);
EXPECT_TRUE(keyset.Encrypt(key, obfuscated_username));
EXPECT_FALSE(keyset.GetAuthLocked());
}
TEST_F(VaultKeysetTest, GetPcrBoundAuthBlockStateTest) {
VaultKeyset keyset;
keyset.Initialize(&platform_, &crypto_);
keyset.CreateFromFileSystemKeyset(FileSystemKeyset::CreateRandom());
keyset.SetFlags(SerializedVaultKeyset::TPM_WRAPPED |
SerializedVaultKeyset::SCRYPT_DERIVED |
SerializedVaultKeyset::PCR_BOUND);
keyset.SetTpmPublicKeyHash(brillo::SecureBlob("yadayada"));
keyset.SetTPMKey(brillo::SecureBlob("blabla"));
keyset.SetExtendedTPMKey(brillo::SecureBlob("foobaz"));
AuthBlockState auth_state;
EXPECT_TRUE(GetAuthBlockState(keyset, auth_state));
const TpmBoundToPcrAuthBlockState* tpm_state =
std::get_if<TpmBoundToPcrAuthBlockState>(&auth_state.state);
ASSERT_NE(tpm_state, nullptr);
ASSERT_TRUE(tpm_state->scrypt_derived.has_value());
EXPECT_TRUE(tpm_state->scrypt_derived.value());
EXPECT_TRUE(tpm_state->extended_tpm_key.has_value());
EXPECT_TRUE(tpm_state->tpm_key.has_value());
}
TEST_F(VaultKeysetTest, GetEccAuthBlockStateTest) {
VaultKeyset keyset;
keyset.Initialize(&platform_, &crypto_);
keyset.CreateFromFileSystemKeyset(FileSystemKeyset::CreateRandom());
keyset.SetFlags(SerializedVaultKeyset::TPM_WRAPPED |
SerializedVaultKeyset::SCRYPT_DERIVED |
SerializedVaultKeyset::ECC |
SerializedVaultKeyset::PCR_BOUND);
keyset.SetTpmPublicKeyHash(brillo::SecureBlob("yadayada"));
keyset.SetTPMKey(brillo::SecureBlob("blabla"));
keyset.SetExtendedTPMKey(brillo::SecureBlob("foobaz"));
keyset.password_rounds_ = 5;
keyset.vkk_iv_ = brillo::SecureBlob("wowowow");
keyset.auth_salt_ = brillo::SecureBlob("salt");
AuthBlockState auth_state;
EXPECT_TRUE(GetAuthBlockState(keyset, auth_state));
const TpmEccAuthBlockState* tpm_state =
std::get_if<TpmEccAuthBlockState>(&auth_state.state);
ASSERT_NE(tpm_state, nullptr);
EXPECT_TRUE(tpm_state->salt.has_value());
EXPECT_TRUE(tpm_state->sealed_hvkkm.has_value());
EXPECT_TRUE(tpm_state->extended_sealed_hvkkm.has_value());
EXPECT_TRUE(tpm_state->tpm_public_key_hash.has_value());
EXPECT_TRUE(tpm_state->vkk_iv.has_value());
EXPECT_EQ(tpm_state->auth_value_rounds.value(), 5);
}
TEST_F(VaultKeysetTest, GetNotPcrBoundAuthBlockState) {
VaultKeyset keyset;
keyset.Initialize(&platform_, &crypto_);
keyset.CreateFromFileSystemKeyset(FileSystemKeyset::CreateRandom());
keyset.SetFlags(SerializedVaultKeyset::TPM_WRAPPED);
keyset.SetTpmPublicKeyHash(brillo::SecureBlob("yadayada"));
keyset.SetTPMKey(brillo::SecureBlob("blabla"));
AuthBlockState auth_state;
EXPECT_TRUE(GetAuthBlockState(keyset, auth_state));
const TpmNotBoundToPcrAuthBlockState* tpm_state =
std::get_if<TpmNotBoundToPcrAuthBlockState>(&auth_state.state);
ASSERT_NE(tpm_state, nullptr);
ASSERT_TRUE(tpm_state->scrypt_derived.has_value());
EXPECT_FALSE(tpm_state->scrypt_derived.value());
EXPECT_TRUE(tpm_state->tpm_key.has_value());
}
TEST_F(VaultKeysetTest, GetPinWeaverAuthBlockState) {
VaultKeyset keyset;
keyset.Initialize(&platform_, &crypto_);
const uint64_t le_label = 012345;
keyset.CreateFromFileSystemKeyset(FileSystemKeyset::CreateRandom());
keyset.SetFlags(SerializedVaultKeyset::LE_CREDENTIAL);
keyset.SetLELabel(le_label);
AuthBlockState auth_state;
EXPECT_TRUE(GetAuthBlockState(keyset, auth_state));
const PinWeaverAuthBlockState* pin_auth_state =
std::get_if<PinWeaverAuthBlockState>(&auth_state.state);
ASSERT_NE(pin_auth_state, nullptr);
EXPECT_TRUE(pin_auth_state->le_label.has_value());
EXPECT_EQ(le_label, pin_auth_state->le_label.value());
}
TEST_F(VaultKeysetTest, GetChallengeCredentialAuthBlockState) {
VaultKeyset keyset;
keyset.Initialize(&platform_, &crypto_);
keyset.CreateFromFileSystemKeyset(FileSystemKeyset::CreateRandom());
keyset.SetFlags(SerializedVaultKeyset::SCRYPT_WRAPPED |
SerializedVaultKeyset::SIGNATURE_CHALLENGE_PROTECTED);
AuthBlockState auth_state;
EXPECT_TRUE(GetAuthBlockState(keyset, auth_state));
const ChallengeCredentialAuthBlockState* cc_state =
std::get_if<ChallengeCredentialAuthBlockState>(&auth_state.state);
EXPECT_NE(cc_state, nullptr);
}
TEST_F(VaultKeysetTest, GetLibscryptCompatAuthBlockState) {
VaultKeyset keyset;
keyset.Initialize(&platform_, &crypto_);
keyset.CreateFromFileSystemKeyset(FileSystemKeyset::CreateRandom());
keyset.SetFlags(SerializedVaultKeyset::SCRYPT_WRAPPED);
keyset.SetWrappedKeyset(brillo::SecureBlob("foo"));
keyset.SetWrappedChapsKey(brillo::SecureBlob("bar"));
keyset.SetWrappedResetSeed(brillo::SecureBlob("baz"));
AuthBlockState auth_state;
EXPECT_TRUE(GetAuthBlockState(keyset, auth_state));
const LibScryptCompatAuthBlockState* scrypt_state =
std::get_if<LibScryptCompatAuthBlockState>(&auth_state.state);
ASSERT_NE(scrypt_state, nullptr);
EXPECT_TRUE(scrypt_state->wrapped_keyset.has_value());
EXPECT_TRUE(scrypt_state->wrapped_chaps_key.has_value());
EXPECT_TRUE(scrypt_state->wrapped_reset_seed.has_value());
}
TEST_F(VaultKeysetTest, GetDoubleWrappedCompatAuthBlockStateFailure) {
VaultKeyset keyset;
keyset.Initialize(&platform_, &crypto_);
keyset.CreateFromFileSystemKeyset(FileSystemKeyset::CreateRandom());
keyset.SetFlags(SerializedVaultKeyset::SCRYPT_WRAPPED |
SerializedVaultKeyset::TPM_WRAPPED);
AuthBlockState auth_state;
// A required tpm_key is not set in keyset, failure in creating
// sub-state TpmNotBoundToPcrAuthBlockState.
EXPECT_FALSE(GetAuthBlockState(keyset, auth_state));
const DoubleWrappedCompatAuthBlockState* double_wrapped_state =
std::get_if<DoubleWrappedCompatAuthBlockState>(&auth_state.state);
EXPECT_EQ(double_wrapped_state, nullptr);
}
TEST_F(VaultKeysetTest, GetDoubleWrappedCompatAuthBlockState) {
VaultKeyset keyset;
keyset.Initialize(&platform_, &crypto_);
keyset.CreateFromFileSystemKeyset(FileSystemKeyset::CreateRandom());
keyset.SetFlags(SerializedVaultKeyset::SCRYPT_WRAPPED |
SerializedVaultKeyset::TPM_WRAPPED);
keyset.SetTPMKey(brillo::SecureBlob("blabla"));
AuthBlockState auth_state;
EXPECT_TRUE(GetAuthBlockState(keyset, auth_state));
const DoubleWrappedCompatAuthBlockState* double_wrapped_state =
std::get_if<DoubleWrappedCompatAuthBlockState>(&auth_state.state);
EXPECT_NE(double_wrapped_state, nullptr);
}
TEST_F(VaultKeysetTest, EncryptionTest) {
// Check that EncryptVaultKeyset returns something other than the bytes
// passed.
VaultKeyset vault_keyset;
vault_keyset.Initialize(&platform_, &crypto_);
vault_keyset.CreateFromFileSystemKeyset(FileSystemKeyset::CreateRandom());
SecureBlob key(20);
GetSecureRandom(key.data(), key.size());
AuthBlockState auth_block_state;
ASSERT_TRUE(vault_keyset.EncryptVaultKeyset(key, "", &auth_block_state));
}
TEST_F(VaultKeysetTest, DecryptionTest) {
// Check that DecryptVaultKeyset returns the original keyset.
VaultKeyset vault_keyset;
vault_keyset.Initialize(&platform_, &crypto_);
vault_keyset.CreateFromFileSystemKeyset(FileSystemKeyset::CreateRandom());
SecureBlob key(20);
GetSecureRandom(key.data(), key.size());
AuthBlockState auth_block_state;
ASSERT_TRUE(vault_keyset.EncryptVaultKeyset(key, "", &auth_block_state));
// TODO(kerrnel): This is a hack to bridge things until DecryptVaultKeyset is
// modified to take a key material and an auth block state.
vault_keyset.SetAuthBlockState(auth_block_state);
SecureBlob original_data;
ASSERT_TRUE(vault_keyset.ToKeysBlob(&original_data));
CryptoError crypto_error = CryptoError::CE_NONE;
ASSERT_TRUE(vault_keyset.DecryptVaultKeyset(
key, false /* locked_to_single_user */, &crypto_error));
SecureBlob new_data;
ASSERT_TRUE(vault_keyset.ToKeysBlob(&new_data));
EXPECT_EQ(new_data.size(), original_data.size());
ASSERT_TRUE(VaultKeysetTest::FindBlobInBlob(new_data, original_data));
}
TEST_F(VaultKeysetTest, GetLegacyLabelTest) {
VaultKeyset vault_keyset;
vault_keyset.Initialize(&platform_, &crypto_);
vault_keyset.SetLegacyIndex(kLegacyIndex);
ASSERT_EQ(vault_keyset.GetLabel(), kLegacyLabel);
}
TEST_F(VaultKeysetTest, GetLabelTest) {
VaultKeyset vault_keyset;
vault_keyset.Initialize(&platform_, &crypto_);
KeyData key_data;
key_data.set_label(kTempLabel);
vault_keyset.SetLegacyIndex(kLegacyIndex);
vault_keyset.SetKeyData(key_data);
ASSERT_EQ(vault_keyset.GetLabel(), kTempLabel);
}
TEST_F(VaultKeysetTest, GetEmptyLabelTest) {
VaultKeyset vault_keyset;
vault_keyset.Initialize(&platform_, &crypto_);
KeyData key_data;
// Setting empty label.
key_data.set_label("");
vault_keyset.SetLegacyIndex(kLegacyIndex);
vault_keyset.SetKeyData(key_data);
ASSERT_EQ(vault_keyset.GetLabel(), kLegacyLabel);
}
TEST_F(VaultKeysetTest, InitializeToAdd) {
// Check if InitializeToAdd correctly copies keys
// from parameter vault keyset to underlying data structure.
VaultKeyset vault_keyset;
vault_keyset.Initialize(&platform_, &crypto_);
vault_keyset.CreateFromFileSystemKeyset(FileSystemKeyset::CreateRandom());
const auto reset_iv = CreateSecureRandomBlob(kAesBlockSize);
static const int kFscryptPolicyVersion = 2;
vault_keyset.SetResetIV(reset_iv);
vault_keyset.SetFSCryptPolicyVersion(kFscryptPolicyVersion);
vault_keyset.SetLegacyIndex(kLegacyIndex);
VaultKeyset vault_keyset_copy;
vault_keyset_copy.InitializeToAdd(vault_keyset);
SecureBlob key(kPasswordKey);
std::string obfuscated_username(kObfuscatedUsername);
vault_keyset.Encrypt(key, obfuscated_username);
// Check that InitializeToAdd correctly copied vault_keyset fields
// i.e. fek/fnek keys, reset seed, reset IV, and FSCrypt policy version
// FEK
ASSERT_EQ(vault_keyset.GetFek(), vault_keyset_copy.GetFek());
ASSERT_EQ(vault_keyset.GetFekSig(), vault_keyset_copy.GetFekSig());
ASSERT_EQ(vault_keyset.GetFekSalt(), vault_keyset_copy.GetFekSalt());
// FNEK
ASSERT_EQ(vault_keyset.GetFnek(), vault_keyset_copy.GetFnek());
ASSERT_EQ(vault_keyset.GetFnekSig(), vault_keyset_copy.GetFnekSig());
ASSERT_EQ(vault_keyset.GetFnekSalt(), vault_keyset_copy.GetFnekSalt());
// Other metadata
ASSERT_EQ(vault_keyset.GetResetSeed(), vault_keyset_copy.GetResetSeed());
ASSERT_EQ(vault_keyset.GetResetIV(), vault_keyset_copy.GetResetIV());
ASSERT_EQ(vault_keyset.GetChapsKey(), vault_keyset_copy.GetChapsKey());
ASSERT_EQ(vault_keyset.GetFSCryptPolicyVersion(),
vault_keyset_copy.GetFSCryptPolicyVersion());
// Other fields are empty/not changed/uninitialized
// i.e. the wrapped_keyset_ shouldn't be copied
ASSERT_NE(vault_keyset.GetWrappedKeyset(),
vault_keyset_copy.GetWrappedKeyset());
// int32_t flags_
ASSERT_NE(vault_keyset_copy.GetFlags(), vault_keyset.GetFlags());
// int legacy_index_
ASSERT_NE(vault_keyset_copy.GetLegacyIndex(), vault_keyset.GetLegacyIndex());
}
TEST_F(VaultKeysetTest, DecryptFailNotLoaded) {
// Check to decrypt a VaultKeyset that hasn't been loaded yet.
VaultKeyset vault_keyset;
vault_keyset.Initialize(&platform_, &crypto_);
vault_keyset.CreateFromFileSystemKeyset(FileSystemKeyset::CreateRandom());
SecureBlob key(kPasswordKey);
std::string obfuscated_username(kObfuscatedUsername);
ASSERT_TRUE(vault_keyset.Encrypt(key, obfuscated_username));
CryptoError crypto_error = CryptoError::CE_NONE;
// locked_to_single_user determines whether to use the extended tmp_key,
// uses normal tpm_key when false with a TpmBoundToPcrAuthBlock
ASSERT_FALSE(vault_keyset.Decrypt(key, false /*locked_to_single_user*/,
&crypto_error));
ASSERT_EQ(crypto_error, CryptoError::CE_OTHER_CRYPTO);
}
TEST_F(VaultKeysetTest, DecryptTPMCommErr) {
// Test to have Decrypt() fail because of CE_TPM_COMM_ERROR.
// Setup
auto mock_loader = std::make_unique<MockCryptohomeKeyLoader>();
MockCryptohomeKeyLoader* mock_loader_ptr = mock_loader.get();
std::vector<
std::pair<CryptohomeKeyType, std::unique_ptr<CryptohomeKeyLoader>>>
mock_loaders;
mock_loaders.push_back(
std::make_pair(CryptohomeKeyType::kRSA, std::move(mock_loader)));
auto cryptohome_keys_manager =
std::make_unique<CryptohomeKeysManager>(std::move(mock_loaders));
crypto_.Init(&tpm_, cryptohome_keys_manager.get());
EXPECT_CALL(tpm_, IsEnabled()).WillRepeatedly(Return(true));
EXPECT_CALL(tpm_, IsOwned()).WillRepeatedly(Return(true));
SecureBlob bytes;
EXPECT_CALL(platform_, WriteFileAtomicDurable(FilePath(kFilePath), _, _))
.WillOnce(WithArg<1>(CopyToSecureBlob(&bytes)));
EXPECT_CALL(platform_, ReadFile(FilePath(kFilePath), _))
.WillOnce(WithArg<1>(CopyFromSecureBlob(&bytes)));
VaultKeyset vk;
vk.Initialize(&platform_, &crypto_);
vk.CreateFromFileSystemKeyset(FileSystemKeyset::CreateRandom());
vk.SetFlags(SerializedVaultKeyset::TPM_WRAPPED);
// Test
SecureBlob key(kPasswordKey);
std::string obfuscated_username(kObfuscatedUsername);
ASSERT_TRUE(vk.Encrypt(key, obfuscated_username));
ASSERT_TRUE(vk.Save(FilePath(kFilePath)));
VaultKeyset new_keyset;
new_keyset.Initialize(&platform_, &crypto_);
EXPECT_TRUE(new_keyset.Load(FilePath(kFilePath)));
EXPECT_CALL(*mock_loader_ptr, HasCryptohomeKey())
.WillRepeatedly(Return(false));
// DecryptVaultKeyset within Decrypt fails
// and passes error CryptoError::CE_TPM_COMM_ERROR
// Decrypt -> DecryptVaultKeyset -> Derive
// -> CheckTPMReadiness -> HasCryptohomeKey(fails and error propagates up)
CryptoError tmp_error;
ASSERT_FALSE(new_keyset.Decrypt(key, false, &tmp_error));
ASSERT_EQ(tmp_error, CryptoError::CE_TPM_COMM_ERROR);
}
TEST_F(VaultKeysetTest, LibScryptBackwardCompatibility) {
VaultKeyset vk;
vk.Initialize(&platform_, &crypto_);
SerializedVaultKeyset serialized;
serialized.ParseFromString(
HexDecode(kHexLibScryptExampleSerializedVaultKeyset));
vk.InitializeFromSerialized(serialized);
// TODO(b/198394243): We should remove this because it's not actually used.
EXPECT_EQ(SecureBlobToHex(vk.auth_salt_), kHexLibScryptExampleSalt);
AuthBlockState auth_state;
EXPECT_TRUE(GetAuthBlockState(vk, auth_state));
CryptoError crypto_error = CryptoError::CE_NONE;
EXPECT_TRUE(vk.DecryptVaultKeyset(
brillo::SecureBlob(HexDecode(kHexLibScryptExamplePasskey)), false,
&crypto_error));
EXPECT_EQ(CryptoError::CE_NONE, crypto_error);
EXPECT_EQ(SecureBlobToHex(vk.GetFek()), kHexLibScryptExampleFek);
EXPECT_EQ(SecureBlobToHex(vk.GetFekSig()), kHexLibScryptExampleFekSig);
EXPECT_EQ(SecureBlobToHex(vk.GetFekSalt()), kHexLibScryptExampleFekSalt);
EXPECT_EQ(SecureBlobToHex(vk.GetFnek()), kHexLibScryptExampleFnek);
EXPECT_EQ(SecureBlobToHex(vk.GetFnekSig()), kHexLibScryptExampleFnekSig);
EXPECT_EQ(SecureBlobToHex(vk.GetFnekSalt()), kHexLibScryptExampleFnekSalt);
}
TEST_F(VaultKeysetTest, GetTpmWritePasswordRounds) {
// Test to ensure that for GetTpmNotBoundtoPcrState
// correctly copies the password_rounds field from
// the VaultKeyset to the auth_state parameter.
VaultKeyset keyset;
SerializedVaultKeyset serialized_vk;
serialized_vk.set_flags(SerializedVaultKeyset::TPM_WRAPPED);
serialized_vk.set_password_rounds(kPasswordRounds);
keyset.InitializeFromSerialized(serialized_vk);
keyset.Initialize(&platform_, &crypto_);
keyset.SetTPMKey(brillo::SecureBlob(kFakePasswordKey));
AuthBlockState tpm_state;
EXPECT_TRUE(GetAuthBlockState(keyset, tpm_state));
auto test_state =
std::get_if<TpmNotBoundToPcrAuthBlockState>(&tpm_state.state);
// test_state is of type TpmNotBoundToPcrAuthBlockState
ASSERT_EQ(keyset.GetPasswordRounds(), test_state->password_rounds.value());
}
TEST_F(VaultKeysetTest, DecryptionTestWithKeyBlobs) {
// Check that Decrypt returns the original keyset.
// Setup
VaultKeyset vault_keyset;
vault_keyset.Initialize(&platform_, &crypto_);
vault_keyset.CreateFromFileSystemKeyset(FileSystemKeyset::CreateRandom());
SecureBlob bytes;
EXPECT_CALL(platform_, WriteFileAtomicDurable(FilePath(kFilePath), _, _))
.WillOnce(WithArg<1>(CopyToSecureBlob(&bytes)));
EXPECT_CALL(platform_, ReadFile(FilePath(kFilePath), _))
.WillOnce(WithArg<1>(CopyFromSecureBlob(&bytes)));
KeyBlobs key_blobs = {.vkk_key = brillo::SecureBlob(32, 'A'),
.vkk_iv = brillo::SecureBlob(16, 'B'),
.chaps_iv = brillo::SecureBlob(16, 'C')};
TpmBoundToPcrAuthBlockState pcr_state = {.salt = brillo::SecureBlob("salt")};
AuthBlockState auth_state = {.state = pcr_state};
ASSERT_TRUE(vault_keyset.EncryptEx(key_blobs, auth_state));
EXPECT_TRUE(vault_keyset.Save(FilePath(kFilePath)));
SecureBlob original_data;
ASSERT_TRUE(vault_keyset.ToKeysBlob(&original_data));
// Test
VaultKeyset new_keyset;
new_keyset.Initialize(&platform_, &crypto_);
EXPECT_TRUE(new_keyset.Load(FilePath(kFilePath)));
CryptoError crypto_error = CryptoError::CE_NONE;
ASSERT_TRUE(new_keyset.DecryptEx(key_blobs, &crypto_error));
ASSERT_EQ(crypto_error, CryptoError::CE_NONE);
// Verify
SecureBlob new_data;
ASSERT_TRUE(new_keyset.ToKeysBlob(&new_data));
EXPECT_EQ(new_data.size(), original_data.size());
ASSERT_TRUE(VaultKeysetTest::FindBlobInBlob(new_data, original_data));
}
TEST_F(VaultKeysetTest, DecryptWithAuthBlockFailNotLoaded) {
// Check to decrypt a VaultKeyset that hasn't been loaded yet.
VaultKeyset vault_keyset;
vault_keyset.Initialize(&platform_, &crypto_);
vault_keyset.CreateFromFileSystemKeyset(FileSystemKeyset::CreateRandom());
KeyBlobs key_blobs = {.vkk_key = brillo::SecureBlob(32, 'A'),
.vkk_iv = brillo::SecureBlob(16, 'B'),
.chaps_iv = brillo::SecureBlob(16, 'C')};
TpmBoundToPcrAuthBlockState pcr_state = {.salt = brillo::SecureBlob("salt")};
AuthBlockState auth_state = {.state = pcr_state};
EXPECT_TRUE(vault_keyset.EncryptEx(key_blobs, auth_state));
CryptoError crypto_error = CryptoError::CE_NONE;
// Load() needs to be called before decrypting the keyset.
ASSERT_FALSE(vault_keyset.DecryptEx(key_blobs, &crypto_error));
ASSERT_EQ(crypto_error, CryptoError::CE_OTHER_CRYPTO);
}
class LeCredentialsManagerTest : public ::testing::Test {
public:
LeCredentialsManagerTest() : crypto_(&platform_) {
EXPECT_CALL(cryptohome_keys_manager_, Init())
.WillOnce(Return()); // because HasCryptohomeKey returned false once.
EXPECT_CALL(tpm_, IsEnabled()).WillRepeatedly(Return(true));
EXPECT_CALL(tpm_, IsOwned()).WillRepeatedly(Return(true));
// Raw pointer as crypto_ expects unique_ptr, which we will wrap this
// allocation into.
le_cred_manager_ = new MockLECredentialManager();
EXPECT_CALL(*le_cred_manager_, CheckCredential(_, _, _, _))
.WillRepeatedly(DoAll(
SetArgPointee<2>(
brillo::SecureBlob(HexDecode(kHexHighEntropySecret))),
SetArgPointee<3>(brillo::SecureBlob(HexDecode(kHexResetSecret))),
ReturnError<CryptohomeLECredError>()));
crypto_.set_le_manager_for_testing(
std::unique_ptr<cryptohome::LECredentialManager>(le_cred_manager_));
crypto_.Init(&tpm_, &cryptohome_keys_manager_);
pin_vault_keyset_.Initialize(&platform_, &crypto_);
}
~LeCredentialsManagerTest() override = default;
// Not copyable or movable
LeCredentialsManagerTest(const LeCredentialsManagerTest&) = delete;
LeCredentialsManagerTest& operator=(const LeCredentialsManagerTest&) = delete;
LeCredentialsManagerTest(LeCredentialsManagerTest&&) = delete;
LeCredentialsManagerTest& operator=(LeCredentialsManagerTest&&) = delete;
protected:
MockPlatform platform_;
Crypto crypto_;
NiceMock<MockTpm> tpm_;
NiceMock<MockCryptohomeKeysManager> cryptohome_keys_manager_;
MockLECredentialManager* le_cred_manager_;
VaultKeyset pin_vault_keyset_;
const CryptohomeError::ErrorLocationPair kErrorLocationForTesting1 =
CryptohomeError::ErrorLocationPair(
static_cast<::cryptohome::error::CryptohomeError::ErrorLocation>(1),
std::string("Testing1"));
};
TEST_F(LeCredentialsManagerTest, Encrypt) {
EXPECT_CALL(*le_cred_manager_, InsertCredential(_, _, _, _, _, _))
.WillOnce(ReturnError<CryptohomeLECredError>());
pin_vault_keyset_.CreateFromFileSystemKeyset(
FileSystemKeyset::CreateRandom());
pin_vault_keyset_.SetLowEntropyCredential(true);
// This used to happen in VaultKeyset::EncryptVaultKeyset, but now happens in
// VaultKeyset::Encrypt and thus needs to be done manually here.
pin_vault_keyset_.reset_seed_ = CreateSecureRandomBlob(kAesBlockSize);
pin_vault_keyset_.reset_salt_ = CreateSecureRandomBlob(kAesBlockSize);
pin_vault_keyset_.reset_secret_ = HmacSha256(
pin_vault_keyset_.reset_salt_.value(), pin_vault_keyset_.reset_seed_);
AuthBlockState auth_block_state;
EXPECT_TRUE(pin_vault_keyset_.EncryptVaultKeyset(
brillo::SecureBlob(HexDecode(kHexVaultKey)), "unused",
&auth_block_state));
EXPECT_TRUE(
std::holds_alternative<PinWeaverAuthBlockState>(auth_block_state.state));
}
TEST_F(LeCredentialsManagerTest, EncryptFail) {
EXPECT_CALL(*le_cred_manager_, InsertCredential(_, _, _, _, _, _))
.WillOnce(ReturnError<CryptohomeLECredError>(
kErrorLocationForTesting1, ErrorActionSet({ErrorAction::kFatal}),
LE_CRED_ERROR_NO_FREE_LABEL));
pin_vault_keyset_.CreateFromFileSystemKeyset(
FileSystemKeyset::CreateRandom());
pin_vault_keyset_.SetLowEntropyCredential(true);
// This used to happen in VaultKeyset::EncryptVaultKeyset, but now happens in
// VaultKeyset::Encrypt and thus needs to be done manually here.
pin_vault_keyset_.reset_seed_ = CreateSecureRandomBlob(kAesBlockSize);
pin_vault_keyset_.reset_salt_ = CreateSecureRandomBlob(kAesBlockSize);
pin_vault_keyset_.reset_secret_ = HmacSha256(
pin_vault_keyset_.reset_salt_.value(), pin_vault_keyset_.reset_seed_);
AuthBlockState auth_block_state;
EXPECT_FALSE(pin_vault_keyset_.EncryptVaultKeyset(
brillo::SecureBlob(HexDecode(kHexVaultKey)), "unused",
&auth_block_state));
}
TEST_F(LeCredentialsManagerTest, Decrypt) {
VaultKeyset vk;
// vk needs its Crypto object set to be able to create the AuthBlock in the
// DecryptVaultKeyset() call.
vk.Initialize(&platform_, &crypto_);
SerializedVaultKeyset serialized;
serialized.set_flags(SerializedVaultKeyset::LE_CREDENTIAL);
serialized.set_le_fek_iv(HexDecode(kHexFekIv));
serialized.set_le_chaps_iv(HexDecode(kHexChapsIv));
serialized.set_wrapped_keyset(HexDecode(kHexWrappedKeyset));
serialized.set_wrapped_chaps_key(HexDecode(kHexWrappedChapsKey));
serialized.set_salt(HexDecode(kHexSalt));
serialized.set_le_label(0644);
vk.InitializeFromSerialized(serialized);
AuthBlockState auth_state;
EXPECT_TRUE(GetAuthBlockState(vk, auth_state));
CryptoError crypto_error = CryptoError::CE_NONE;
EXPECT_TRUE(vk.DecryptVaultKeyset(brillo::SecureBlob(HexDecode(kHexVaultKey)),
false, &crypto_error));
EXPECT_EQ(CryptoError::CE_NONE, crypto_error);
}
// crbug.com/1224150: auth_locked must be set to false when an LE credential is
// re-saved.
TEST_F(LeCredentialsManagerTest, EncryptTestReset) {
EXPECT_CALL(*le_cred_manager_, InsertCredential(_, _, _, _, _, _))
.WillOnce(ReturnError<CryptohomeLECredError>());
pin_vault_keyset_.CreateFromFileSystemKeyset(
FileSystemKeyset::CreateRandom());
pin_vault_keyset_.SetLowEntropyCredential(true);
// This used to happen in VaultKeyset::EncryptVaultKeyset, but now happens in
// VaultKeyset::Encrypt and thus needs to be done manually here.
pin_vault_keyset_.reset_seed_ = CreateSecureRandomBlob(kAesBlockSize);
pin_vault_keyset_.reset_salt_ = CreateSecureRandomBlob(kAesBlockSize);
pin_vault_keyset_.reset_secret_ = HmacSha256(
pin_vault_keyset_.reset_salt_.value(), pin_vault_keyset_.reset_seed_);
pin_vault_keyset_.auth_locked_ = true;
SecureBlob key(kPasswordKey);
std::string obfuscated_username(kObfuscatedUsername);
EXPECT_TRUE(pin_vault_keyset_.Encrypt(key, obfuscated_username));
EXPECT_TRUE(pin_vault_keyset_.HasKeyData());
EXPECT_FALSE(pin_vault_keyset_.auth_locked_);
const SerializedVaultKeyset& serialized = pin_vault_keyset_.ToSerialized();
EXPECT_FALSE(serialized.key_data().policy().auth_locked());
}
TEST_F(LeCredentialsManagerTest, DecryptTPMDefendLock) {
// Test to have LECredential fail Decrypt because CE_TPM_DEFEND_LOCK
// Setup
pin_vault_keyset_.CreateFromFileSystemKeyset(
FileSystemKeyset::CreateRandom());
pin_vault_keyset_.SetLowEntropyCredential(true);
SecureBlob bytes;
EXPECT_CALL(platform_, WriteFileAtomicDurable(FilePath(kFilePath), _, _))
.WillOnce(WithArg<1>(CopyToSecureBlob(&bytes)))
.WillOnce(WithArg<1>(CopyToSecureBlob(&bytes)));
EXPECT_CALL(platform_, ReadFile(FilePath(kFilePath), _))
.WillOnce(WithArg<1>(CopyFromSecureBlob(&bytes)));
SecureBlob key(kPasswordKey);
std::string obfuscated_username(kObfuscatedUsername);
ASSERT_TRUE(pin_vault_keyset_.Encrypt(key, obfuscated_username));
ASSERT_TRUE(pin_vault_keyset_.Save(FilePath(kFilePath)));
VaultKeyset new_keyset;
new_keyset.Initialize(&platform_, &crypto_);
EXPECT_TRUE(new_keyset.Load(FilePath(kFilePath)));
// Test
ASSERT_FALSE(new_keyset.GetAuthLocked());
// Have le_cred_manager inject a
// CryptoError::CE_TPM_DEFEND_LOCK error
EXPECT_CALL(*le_cred_manager_, CheckCredential(_, _, _, _))
.WillOnce(ReturnError<CryptohomeLECredError>(
kErrorLocationForTesting1, ErrorActionSet({ErrorAction::kFatal}),
LE_CRED_ERROR_TOO_MANY_ATTEMPTS));
CryptoError crypto_error;
ASSERT_FALSE(new_keyset.Decrypt(key, false, &crypto_error));
ASSERT_EQ(crypto_error, CryptoError::CE_TPM_DEFEND_LOCK);
ASSERT_TRUE(new_keyset.GetAuthLocked());
}
TEST_F(LeCredentialsManagerTest, EncryptWithKeyBlobs) {
EXPECT_CALL(*le_cred_manager_, InsertCredential(_, _, _, _, _, _))
.WillOnce(ReturnError<CryptohomeLECredError>());
pin_vault_keyset_.CreateFromFileSystemKeyset(
FileSystemKeyset::CreateRandom());
pin_vault_keyset_.SetLowEntropyCredential(true);
std::optional<brillo::SecureBlob> reset_secret =
pin_vault_keyset_.GetOrGenerateResetSecret();
EXPECT_TRUE(reset_secret.has_value());
auto auth_block = std::make_unique<PinWeaverAuthBlock>(
crypto_.le_manager(), crypto_.cryptohome_keys_manager());
AuthInput auth_input = {brillo::SecureBlob(HexDecode(kHexVaultKey)), false,
"unused", reset_secret.value()};
KeyBlobs key_blobs;
AuthBlockState auth_state;
CryptoStatus status = auth_block->Create(auth_input, &auth_state, &key_blobs);
ASSERT_TRUE(status.ok());
EXPECT_TRUE(
std::holds_alternative<PinWeaverAuthBlockState>(auth_state.state));
EXPECT_TRUE(pin_vault_keyset_.EncryptEx(key_blobs, auth_state));
}
TEST_F(LeCredentialsManagerTest, EncryptWithKeyBlobsFailWithBadAuthState) {
EXPECT_CALL(*le_cred_manager_, InsertCredential(_, _, _, _, _, _))
.WillOnce(ReturnError<CryptohomeLECredError>(
kErrorLocationForTesting1, ErrorActionSet({ErrorAction::kFatal}),
LE_CRED_ERROR_NO_FREE_LABEL));
pin_vault_keyset_.CreateFromFileSystemKeyset(
FileSystemKeyset::CreateRandom());
pin_vault_keyset_.SetLowEntropyCredential(true);
brillo::SecureBlob reset_secret =
pin_vault_keyset_.GetOrGenerateResetSecret().value();
auto auth_block = std::make_unique<PinWeaverAuthBlock>(
crypto_.le_manager(), crypto_.cryptohome_keys_manager());
AuthInput auth_input = {brillo::SecureBlob(44, 'A'), false, "unused",
reset_secret};
KeyBlobs key_blobs;
AuthBlockState auth_state;
CryptoStatus status = auth_block->Create(auth_input, &auth_state, &key_blobs);
ASSERT_FALSE(status.ok());
EXPECT_FALSE(
std::holds_alternative<PinWeaverAuthBlockState>(auth_state.state));
}
TEST_F(LeCredentialsManagerTest, DecryptWithKeyBlobs) {
VaultKeyset vk;
vk.Initialize(&platform_, &crypto_);
SerializedVaultKeyset serialized;
serialized.set_flags(SerializedVaultKeyset::LE_CREDENTIAL);
serialized.set_le_fek_iv(HexDecode(kHexFekIv));
serialized.set_le_chaps_iv(HexDecode(kHexChapsIv));
serialized.set_wrapped_keyset(HexDecode(kHexWrappedKeyset));
serialized.set_wrapped_chaps_key(HexDecode(kHexWrappedChapsKey));
serialized.set_salt(HexDecode(kHexSalt));
serialized.set_le_label(0644);
vk.InitializeFromSerialized(serialized);
auto auth_block = std::make_unique<PinWeaverAuthBlock>(
crypto_.le_manager(), crypto_.cryptohome_keys_manager());
AuthInput auth_input = {brillo::SecureBlob(HexDecode(kHexVaultKey)), false};
KeyBlobs key_blobs;
AuthBlockState auth_state;
EXPECT_TRUE(vk.GetPinWeaverState(&auth_state));
CryptoStatus status = auth_block->Derive(auth_input, auth_state, &key_blobs);
ASSERT_TRUE(status.ok());
CryptoError crypto_error = CryptoError::CE_NONE;
EXPECT_TRUE(vk.DecryptVaultKeysetEx(key_blobs, &crypto_error));
EXPECT_EQ(CryptoError::CE_NONE, crypto_error);
}
} // namespace cryptohome
| 39.158922 | 80 | 0.775507 | [
"object",
"vector"
] |
90dcc051b8f8676b59a38025ce724fe0d9ff16a7 | 1,013 | cpp | C++ | test.cpp | anttisalonen/libcommon | f16ecf275af944329a0d2285823a9c1f73c84e98 | [
"MIT"
] | null | null | null | test.cpp | anttisalonen/libcommon | f16ecf275af944329a0d2285823a9c1f73c84e98 | [
"MIT"
] | null | null | null | test.cpp | anttisalonen/libcommon | f16ecf275af944329a0d2285823a9c1f73c84e98 | [
"MIT"
] | 4 | 2016-08-03T08:43:15.000Z | 2021-08-23T14:20:43.000Z | #include <time.h>
#include <iostream>
#include <cstdlib>
int math_segment_segment_3d_distance(int argc, char** argv);
int geometry(int argc, char** argv);
int quadtree(int argc, char** argv);
int linequadtree(int argc, char** argv);
int math_quaternion(int argc, char** argv);
int main(int argc, char** argv)
{
int seed;
if(argc > 1)
seed = atoi(argv[1]);
else
seed = time(0);
std::cout << "Seed: " << seed << "\n";
srand(seed);
bool failed = false;
if(geometry(argc, argv)) {
std::cerr << "Geometry test failed.\n";
failed = true;
}
if(quadtree(argc, argv)) {
std::cerr << "Quadtree test failed.\n";
failed = true;
}
if(linequadtree(argc, argv)) {
std::cerr << "Quadtree test failed.\n";
failed = true;
}
if(math_segment_segment_3d_distance(argc, argv)) {
std::cerr << "Math segment-segment 3D distance test failed.\n";
failed = true;
}
if(math_quaternion(argc, argv)) {
std::cerr << "Math quaternion test failed.\n";
failed = true;
}
return failed ? 1 : 0;
}
| 19.480769 | 65 | 0.64462 | [
"geometry",
"3d"
] |
90e326162834fb033da5656aa1c4704fbaeba2b0 | 3,257 | cpp | C++ | DSVis/app/app.cpp | Dreamerryao/CPlusPlus-Project | 5861a277f13fb23c6a6c0548095014c25ae32b62 | [
"MIT"
] | 1 | 2020-07-25T14:49:10.000Z | 2020-07-25T14:49:10.000Z | DSVis/app/app.cpp | Dreamerryao/CPlusPlus-Project | 5861a277f13fb23c6a6c0548095014c25ae32b62 | [
"MIT"
] | null | null | null | DSVis/app/app.cpp | Dreamerryao/CPlusPlus-Project | 5861a277f13fb23c6a6c0548095014c25ae32b62 | [
"MIT"
] | null | null | null | #include <QApplication>
#include "app.h"
app::app()
{
}
app::~app()
{
}
void app::run(){
//model初始化
model = std::make_shared<ArrayModel>();
Tmodel = std::make_shared<TreeModel>();
//viewModel初始化,绑定model
viewmodel = std::make_shared<ArrayViewModel>();
viewmodel->setArrayModel(model);
Tviewmodel = std::make_shared<TreeViewModel>();
Tviewmodel->setTreeModel(Tmodel);
//debug重绘绑定指针问题
//对Mode1的展示界面进行命令的绑定,如array add command
_Mode1_displayP.set_ptrAAC(viewmodel->getArrayAddCommand());
_Mode1_displayP.set_ptrADC(viewmodel->getArrayDelCommand());
_Mode1_displayP.set_ptrSPC(viewmodel->getStackPopCommand());
_Mode1_displayP.set_ptrQDC(viewmodel->getQueueDeqCommand());
_Mode1_displayP.set_ptrTIC(Tviewmodel->getTreeInsCommand());
_Mode1_displayP.set_ptrTDC(Tviewmodel->getTreeDelCommand());
_Mode1_displayP.set_Array(viewmodel->getArray());
_Mode1_displayP.set_Tree(Tviewmodel->getTree());
_Model2_main.set_ptrAAC(viewmodel->getArrayAddCommand());
_Model2_main.set_ptrADC(viewmodel->getArrayDelCommand());
_Model2_main.set_ptrSPC(viewmodel->getStackPopCommand());
_Model2_main.set_ptrQDC(viewmodel->getQueueDeqCommand());
_Model2_main.set_ptrTIC(Tviewmodel->getTreeInsCommand());
_Model2_main.set_ptrTDC(Tviewmodel->getTreeDelCommand());
_Model2_main.set_ptrANC(viewmodel->getArrayNewCommand());
_Model2_main.set_ptrTNC(Tviewmodel->getTreeNewCommand());
_Model2_main.set_ptrARC(viewmodel->getArrayReplaceCommand());
_Model2_main.set_Array(viewmodel->getArray());
_Model2_main.set_Tree(Tviewmodel->getTree());
//ViewModel 添加notification
viewmodel->AddPropertyNotification(_Mode1_displayP.getOUS());
Tviewmodel->AddPropertyNotification(_Mode1_displayP.getOUS());
viewmodel->AddCommandNotification(_Model2_main.getM2CS());
viewmodel->AddPropertyNotification(_Model2_main.getM2US());
Tviewmodel->AddCommandNotification(_Model2_main.getM2CS());
Tviewmodel->AddPropertyNotification(_Model2_main.getM2US());
//界面跳转相关命令
_M1Command = std::make_shared<M1Command>(this);
_M2Command = std::make_shared<M2Command>(this);
_AboutCommand = std::make_shared<AboutCommand>(this);
_cancelCommand=std::make_shared<cancelCommand>(this);
_changeCommand=std::make_shared<changeCommand>(this);
//firstPage绑定 转到 Mode1,Mode2,About界面的命令
_firstPage.set_ptrM1Command(this->_M1Command);
_firstPage.set_ptrM2Command(this->_M2Command);
_firstPage.set_ptrAboutCommand(this->_AboutCommand);
//mode1_main绑定 转到Mode1_display界面的命令
_Model1_main.setChangeCommand(this->_changeCommand);
//返回FirstPage命令
_aboutPage.set_ptrCancel(this->_cancelCommand);
_Model1_main.setCancelCommand(this->_cancelCommand);
_Model2_main.setCancelCommand(this->_cancelCommand);
_Mode1_displayP.setCancelCommand(this->_cancelCommand);
//显示初始界面
_firstPage.show();
}
FirstPage* app::getFirstPage(){
return & _firstPage;
}
Model2_main * app::getModel2_main(){
return & _Model2_main;
}
model1_main * app::getModel1_main(){
return & _Model1_main;
}
about* app::getAbout(){
return & _aboutPage;
}
Mode1_display* app::getOp(){
return & _Mode1_displayP;
}
| 31.019048 | 66 | 0.747006 | [
"model"
] |
90e87db26b09fc8f0f7e542fb6cb1e16a7eb4f1a | 2,244 | cpp | C++ | test/test_txid.cpp | fujita-cg/cfd-core | 9f3bbf0dfdfbc33dd4fd00cb6d81665dc98bffe2 | [
"MIT"
] | null | null | null | test/test_txid.cpp | fujita-cg/cfd-core | 9f3bbf0dfdfbc33dd4fd00cb6d81665dc98bffe2 | [
"MIT"
] | 2 | 2019-11-11T06:29:38.000Z | 2020-07-18T08:02:16.000Z | test/test_txid.cpp | fujita-cg/cfd-core | 9f3bbf0dfdfbc33dd4fd00cb6d81665dc98bffe2 | [
"MIT"
] | 1 | 2019-11-08T13:13:42.000Z | 2019-11-08T13:13:42.000Z | #include "gtest/gtest.h"
#include <vector>
#include "cfdcore/cfdcore_common.h"
#include "cfdcore/cfdcore_transaction.h"
#include "cfdcore/cfdcore_exception.h"
// https://qiita.com/yohm/items/477bac065f4b772127c7
// The main function are using gtest's main().
// TEST(test_suite_name, test_name)
using cfd::core::Txid;
using cfd::core::ByteData256;
using cfd::core::CfdException;
TEST(Txid, TxidEmpty) {
Txid txid;
EXPECT_STREQ(txid.GetHex().c_str(), "");
EXPECT_EQ(txid.GetData().GetDataSize(), 0);
}
TEST(Txid, Txid256bit) {
ByteData256 byte_data = ByteData256(
"3412907856341290785634129078563412907856341290785634129078563412");
Txid txid = Txid(byte_data);
EXPECT_STREQ(
txid.GetHex().c_str(),
"1234567890123456789012345678901234567890123456789012345678901234");
EXPECT_EQ(txid.GetData().GetDataSize(), 32);
}
TEST(Txid, TxidFromHex) {
Txid txid = Txid(
"1234567890123456789012345678901234567890123456789012345678901234");
EXPECT_STREQ(
txid.GetHex().c_str(),
"1234567890123456789012345678901234567890123456789012345678901234");
EXPECT_EQ(txid.GetData().GetDataSize(), 32);
EXPECT_STREQ(
txid.GetData().GetHex().c_str(),
"3412907856341290785634129078563412907856341290785634129078563412");
}
TEST(Txid, TxidFromHexError) {
EXPECT_THROW(
Txid txid = Txid( "123456789012345678901234567890123456789012345678901234567890123412"),
CfdException);
}
TEST(Txid, TxidEqualsMatch) {
Txid txid1 = Txid(
"1234567890123456789012345678901234567890123456789012345678901234");
Txid txid2 = Txid(
"1234567890123456789012345678901234567890123456789012345678901234");
EXPECT_TRUE(txid1.Equals(txid2));
}
TEST(Txid, TxidEqualsUnMatch) {
Txid txid1 = Txid(
"1234567890123456789012345678901234567890123456789012345678901234");
Txid txid2 = Txid(
"0234567890123456789012345678901234567890123456789012345678901234");
EXPECT_FALSE(txid1.Equals(txid2));
}
TEST(Txid, TxidEqualsGetByte) {
std::vector<uint8_t> list1(32);
list1[2] = 8;
list1[4] = 64;
list1[6] = 32;
ByteData256 byte_data = ByteData256(list1);
Txid txid = Txid(byte_data);
bool is_equals = (txid.GetData().GetBytes() == list1);
EXPECT_TRUE(is_equals);
}
| 28.769231 | 94 | 0.745544 | [
"vector"
] |
90ef2bdbbe153d646c7e7c3abbb5548053514bbc | 1,895 | hpp | C++ | boost/log/utility/functional/fun_ref.hpp | HelloSunyi/boost_1_54_0 | 429fea793612f973d4b7a0e69c5af8156ae2b56e | [
"BSL-1.0"
] | 61 | 2015-12-05T19:34:20.000Z | 2021-06-25T09:07:09.000Z | boost/log/utility/functional/fun_ref.hpp | graehl/boost | 37cc4ca77896a86ad10e90dc03e1e825dc0d5492 | [
"BSL-1.0"
] | 38 | 2015-07-22T07:35:45.000Z | 2019-03-14T16:03:06.000Z | boost/log/utility/functional/fun_ref.hpp | graehl/boost | 37cc4ca77896a86ad10e90dc03e1e825dc0d5492 | [
"BSL-1.0"
] | 35 | 2015-12-17T00:09:14.000Z | 2021-01-27T10:47:11.000Z | /*
* Copyright Andrey Semashev 2007 - 2013.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*/
/*!
* \file fun_ref.hpp
* \author Andrey Semashev
* \date 30.03.2008
*
* This header contains function object reference adapter. The adapter stores a reference to external
* function object and forwards all calls to the referred function.
*/
#ifndef BOOST_LOG_UTILITY_FUNCTIONAL_FUN_REF_HPP_INCLUDED_
#define BOOST_LOG_UTILITY_FUNCTIONAL_FUN_REF_HPP_INCLUDED_
#include <boost/log/detail/config.hpp>
#include <boost/log/detail/header.hpp>
#ifdef BOOST_LOG_HAS_PRAGMA_ONCE
#pragma once
#endif
namespace boost {
BOOST_LOG_OPEN_NAMESPACE
//! Reference wrapper for function objects
template< typename FunT >
struct function_reference_wrapper
{
typedef typename FunT::result_type result_type;
explicit function_reference_wrapper(FunT& fun) : m_Fun(fun) {}
result_type operator() () const
{
return m_Fun();
}
#if !defined(BOOST_NO_CXX11_VARIADIC_TEMPLATES)
template< typename... ArgsT >
result_type operator() (ArgsT const&... args) const
{
return m_Fun(args...);
}
#else
template< typename T >
result_type operator() (T const& arg) const
{
return m_Fun(arg);
}
template< typename T1, typename T2 >
result_type operator() (T1 const& arg1, T2 const& arg2) const
{
return m_Fun(arg1, arg2);
}
#endif
private:
FunT& m_Fun;
};
template< typename FunT >
BOOST_LOG_FORCEINLINE function_reference_wrapper< FunT > fun_ref(FunT& fun)
{
return function_reference_wrapper< FunT >(fun);
}
BOOST_LOG_CLOSE_NAMESPACE // namespace log
} // namespace boost
#include <boost/log/detail/footer.hpp>
#endif // BOOST_LOG_UTILITY_FUNCTIONAL_FUN_REF_HPP_INCLUDED_
| 23.6875 | 101 | 0.716095 | [
"object"
] |
90ef5fe95ac63eff75a9e4dd65368357b1e26b8c | 1,223 | cpp | C++ | Test/Test.cpp | DrizztDoUrden/OpenCLMocker | f3382ce780483f2af9c44b112ee76a2d374f097c | [
"MIT"
] | null | null | null | Test/Test.cpp | DrizztDoUrden/OpenCLMocker | f3382ce780483f2af9c44b112ee76a2d374f097c | [
"MIT"
] | null | null | null | Test/Test.cpp | DrizztDoUrden/OpenCLMocker | f3382ce780483f2af9c44b112ee76a2d374f097c | [
"MIT"
] | null | null | null | #include <CL/cl.h>
#include <cassert>
#include <iostream>
#include <vector>
void Validate(cl_int status)
{
assert(status==CL_SUCCESS);
}
int main()
{
auto platformsNumber = cl_uint{};
Validate(clGetPlatformIDs(0, nullptr, &platformsNumber));
auto platforms = std::vector<cl_platform_id>{};
platforms.resize(platformsNumber);
Validate(clGetPlatformIDs(platformsNumber, platforms.data(), nullptr));
std::cout << "Platform count: " << platforms.size() << std::endl;
for (auto platform: platforms)
{
auto deviceNum = cl_uint{};
Validate(clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, 0, nullptr, &deviceNum));
auto devices = std::vector<cl_device_id>{};
devices.resize(deviceNum);
Validate(clGetDeviceIDs(platform, CL_DEVICE_TYPE_GPU, deviceNum, devices.data(), nullptr));
std::cout << "Device count: " << devices.size() << std::endl;
cl_int status = 0;
cl_context_properties cps[3] = {
CL_CONTEXT_PLATFORM, reinterpret_cast<cl_context_properties>(platform), 0 };
auto ctx = clCreateContextFromType(cps, CL_DEVICE_TYPE_GPU, nullptr, nullptr, &status);
Validate(status);
}
return 0;
}
| 29.119048 | 99 | 0.665576 | [
"vector"
] |
90f3726331caa3fece610a03554bed4afd8acfed | 1,231 | hpp | C++ | ql/experimental/preexperimental/tDistribution1d.hpp | universe1987/QuantLib | bbb0145aff285853755b9f6ed013f53a41163acb | [
"BSD-3-Clause"
] | 4 | 2016-03-28T15:05:23.000Z | 2020-02-17T23:05:57.000Z | ql/experimental/preexperimental/tDistribution1d.hpp | universe1987/QuantLib | bbb0145aff285853755b9f6ed013f53a41163acb | [
"BSD-3-Clause"
] | 1 | 2015-02-02T20:32:43.000Z | 2015-02-02T20:32:43.000Z | ql/experimental/preexperimental/tDistribution1d.hpp | pcaspers/quantlib | bbb0145aff285853755b9f6ed013f53a41163acb | [
"BSD-3-Clause"
] | 10 | 2015-01-26T14:50:24.000Z | 2015-10-23T07:41:30.000Z | /*! \file tDistribution1d.hpp
t distribution 1 dim, for nu=0.0 normal distribution
Peter Caspers */
#ifndef quantlib_tDistribution1d_hpp
#define quantlib_tDistribution1d_hpp
#include <ql/quantlib.hpp>
#include <gammaFunction.hpp>
#include <vector>
#include <math.h>
#include <stdio.h>
#define SMALL 1.0E-8 // for p<SMALL, p>1-SMALL inverse cumulative is cut here
using namespace std;
namespace QuantLib {
class TDistribution1d {
public:
TDistribution1d(double accuracy=1.0E-13) : accuracy_(accuracy) {} // accuracy for inverse cumulative
double density(const double nu, const double x);
double cumulative(const double nu, const double x);
double cumulativeInv(const double nu, const double p);
vector<double> sample(const double nu, const unsigned long n, const unsigned long seed);
private:
double accuracy_;
};
class T1dInvHelper {
public:
T1dInvHelper(TDistribution1d *t, const double nu, const double p) : t_(t), nu_(nu), p_(p) {
p_ = p;
if(p_<SMALL) p_=SMALL;
if(p_>1.0-SMALL) p_=1.0-SMALL;
}
double operator()(double x) const {
return t_->cumulative(nu_,x)-p_;
}
private:
TDistribution1d *t_;
double p_,nu_;
};
}
#endif
| 20.180328 | 103 | 0.69212 | [
"vector"
] |
90f5e893675206496935cad03621d187897fc94c | 659 | cpp | C++ | 07. Reverse Integer.cpp | corn1ng/LeetCode-Solution | e7b6f77dd407c9a5cc8be43dc9b0e5d9bc185b95 | [
"Apache-2.0"
] | 6 | 2017-11-18T02:16:35.000Z | 2017-12-17T06:30:40.000Z | 07. Reverse Integer.cpp | corn1ng/LeetCode-Solution | e7b6f77dd407c9a5cc8be43dc9b0e5d9bc185b95 | [
"Apache-2.0"
] | null | null | null | 07. Reverse Integer.cpp | corn1ng/LeetCode-Solution | e7b6f77dd407c9a5cc8be43dc9b0e5d9bc185b95 | [
"Apache-2.0"
] | null | null | null | // 主要要防止int 溢出的情况,所以 res ,p 都设为long long 来防止溢出.
class Solution {
public:
int reverse(int x) {
vector<int> a;
if(x==0 ) return 0;
int flag =1;
if(x<0)
{
x =-x;
flag =0;
}
while(x!=0)
{
int number = x%10;
a.push_back(number);
x =x/10;
}
long long res=0;
long long p=1;
for(int i=a.size()-1;i>=0;i--)
{
res =res+a[i]*p;
p=p*10;
}
if(flag==0)
{
res=-res;
}
return (res<INT_MIN || res>INT_MAX) ? 0 : res;
}
};
| 19.969697 | 54 | 0.365706 | [
"vector"
] |
90f6f5426d31fd647b488cd527db32548fa15ff7 | 45,414 | cpp | C++ | glvis.cpp | hudsabel/glvis | 8f769890f8260eaba7c320f6eabb96e0e61cda94 | [
"BSD-3-Clause"
] | null | null | null | glvis.cpp | hudsabel/glvis | 8f769890f8260eaba7c320f6eabb96e0e61cda94 | [
"BSD-3-Clause"
] | null | null | null | glvis.cpp | hudsabel/glvis | 8f769890f8260eaba7c320f6eabb96e0e61cda94 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-443271.
//
// This file is part of the GLVis visualization tool and library. For more
// information and source code availability see https://glvis.org.
//
// GLVis is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
// GLVis - an OpenGL visualization server based on the MFEM library
#include <limits>
#include <iostream>
#include <fstream>
#include <string>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <csignal>
#include <unistd.h>
#include "mfem.hpp"
#include "lib/palettes.hpp"
#include "lib/visual.hpp"
#include "lib/stream_reader.hpp"
using namespace std;
using namespace mfem;
const char *string_none = "(none)";
const char *string_default = "(default)";
// Global variables for command line arguments
const char *mesh_file = string_none;
const char *sol_file = string_none;
const char *vec_sol_file = string_none;
const char *gfunc_file = string_none;
const char *arg_keys = string_none;
int np = 0;
int pad_digits = 6;
int gf_component = -1;
bool keep_attr = false;
int window_x = 0; // not a command line option
int window_y = 0; // not a command line option
int window_w = 400;
int window_h = 350;
const char *window_title = string_default;
const char *c_plot_caption = string_none;
string plot_caption;
string extra_caption;
// Global variables
int input = 1;
StreamState stream_state;
VisualizationSceneScalarData *vs = NULL;
communication_thread *comm_thread = NULL;
GeometryRefiner GLVisGeometryRefiner;
const char *window_titles[] = { "GLVis [scalar data]",
"GLVis [vector data]", "GLVis [mesh]"
};
istream *script = NULL;
int scr_running = 0;
int scr_level = 0;
Vector *init_nodes = NULL;
double scr_min_val, scr_max_val;
Array<istream *> input_streams;
extern char **environ;
void PrintSampleUsage(ostream &out);
// read the mesh and the solution from a file
void ReadSerial(StreamState& state);
// choose grid function component and set the input flag
void SetGridFunction(StreamState& state);
// read the mesh and the solution from multiple files
void ReadParallel(StreamState& state);
int ReadParMeshAndGridFunction(int np, const char *mesh_prefix,
const char *sol_prefix, StreamState& state,
int keep_attr);
int ReadInputStreams(StreamState& state);
void CloseInputStreams(bool);
// Visualize the data in the global variables mesh, sol/grid_f, etc
// 0 - scalar data, 1 - vector data, 2 - mesh only, (-1) - unknown
bool GLVisInitVis(int field_type)
{
if (field_type < 0 || field_type > 2)
{
return false;
}
const char *win_title = (window_title == string_default) ?
window_titles[field_type] : window_title;
if (InitVisualization(win_title, window_x, window_y, window_w, window_h))
{
cerr << "Initializing the visualization failed." << endl;
return false;
}
if (input_streams.Size() > 0)
{
GetAppWindow()->setOnKeyDown(SDLK_SPACE, ThreadsPauseFunc);
glvis_command = new GLVisCommand(&vs, stream_state, &keep_attr);
comm_thread = new communication_thread(input_streams);
}
double mesh_range = -1.0;
if (field_type == 0 || field_type == 2)
{
if (stream_state.grid_f)
{
stream_state.grid_f->GetNodalValues(stream_state.sol);
}
if (stream_state.mesh->SpaceDimension() == 2)
{
VisualizationSceneSolution * vss;
if (stream_state.normals.Size() > 0)
{
vs = vss = new VisualizationSceneSolution(*stream_state.mesh, stream_state.sol,
&stream_state.normals);
}
else
{
vs = vss = new VisualizationSceneSolution(*stream_state.mesh, stream_state.sol);
}
if (stream_state.grid_f)
{
vss->SetGridFunction(*stream_state.grid_f);
}
if (field_type == 2)
{
vs->OrthogonalProjection = 1;
vs->SetLight(false);
vs->Zoom(1.8);
// Use the 'bone' palette when visualizing a 2D mesh only (otherwise
// the 'jet-like' palette is used in 2D, see vssolution.cpp).
vs->palette.SetIndex(4);
}
}
else if (stream_state.mesh->SpaceDimension() == 3)
{
VisualizationSceneSolution3d * vss;
vs = vss = new VisualizationSceneSolution3d(*stream_state.mesh,
stream_state.sol);
if (stream_state.grid_f)
{
vss->SetGridFunction(stream_state.grid_f.get());
}
if (field_type == 2)
{
if (stream_state.mesh->Dimension() == 3)
{
// Use the 'white' palette when visualizing a 3D volume mesh only
vss->palette.SetIndex(11);
vss->SetLightMatIdx(4);
}
else
{
// Use the 'bone' palette when visualizing a surface mesh only
vss->palette.SetIndex(4);
}
// Otherwise, the 'vivid' palette is used in 3D see vssolution3d.cpp
vss->ToggleDrawAxes();
vss->ToggleDrawMesh();
}
}
if (field_type == 2)
{
if (stream_state.grid_f)
{
mesh_range = stream_state.grid_f->Max() + 1.0;
}
else
{
mesh_range = stream_state.sol.Max() + 1.0;
}
}
}
else if (field_type == 1)
{
if (stream_state.mesh->SpaceDimension() == 2)
{
if (stream_state.grid_f)
{
vs = new VisualizationSceneVector(*stream_state.grid_f);
}
else
{
vs = new VisualizationSceneVector(*stream_state.mesh, stream_state.solu,
stream_state.solv);
}
}
else if (stream_state.mesh->SpaceDimension() == 3)
{
if (stream_state.grid_f)
{
stream_state.grid_f
= ProjectVectorFEGridFunction(std::move(stream_state.grid_f));
vs = new VisualizationSceneVector3d(*stream_state.grid_f);
}
else
{
vs = new VisualizationSceneVector3d(*stream_state.mesh, stream_state.solu,
stream_state.solv, stream_state.solw);
}
}
}
if (vs)
{
// increase the refinement factors if visualizing a GridFunction
if (stream_state.grid_f)
{
vs->AutoRefine();
vs->SetShading(2, true);
}
if (mesh_range > 0.0)
{
vs->SetValueRange(-mesh_range, mesh_range);
vs->SetAutoscale(0);
}
if (stream_state.mesh->SpaceDimension() == 2 && field_type == 2)
{
SetVisualizationScene(vs, 2, stream_state.keys.c_str());
}
else
{
SetVisualizationScene(vs, 3, stream_state.keys.c_str());
}
}
return true;
}
void GLVisStartVis()
{
RunVisualization(); // deletes vs
vs = NULL;
if (input_streams.Size() > 0)
{
glvis_command->Terminate();
delete comm_thread;
delete glvis_command;
glvis_command = NULL;
}
cout << "GLVis window closed." << endl;
}
int ScriptReadSolution(istream &scr, StreamState& state)
{
string mword,sword;
cout << "Script: solution: " << flush;
// read the mesh
scr >> ws >> mword; // mesh filename (can't contain spaces)
cout << "mesh: " << mword << "; " << flush;
named_ifgzstream imesh(mword.c_str());
if (!imesh)
{
cout << "Can not open mesh file: " << mword << endl;
return 1;
}
state.mesh.reset(new Mesh(imesh, 1, 0, state.fix_elem_orient));
// read the solution (GridFunction)
scr >> ws >> sword;
if (sword == mword) // mesh and solution in the same file
{
cout << "solution: " << mword << endl;
state.grid_f.reset(new GridFunction(state.mesh.get(), imesh));
}
else
{
cout << "solution: " << sword << endl;
ifgzstream isol(sword.c_str());
if (!isol)
{
cout << "Can not open solution file: " << sword << endl;
state.mesh.release();
return 2;
}
state.grid_f.reset(new GridFunction(state.mesh.get(), isol));
}
state.Extrude1DMeshAndSolution();
return 0;
}
int ScriptReadParSolution(istream &scr, StreamState& state)
{
int np, keep_attr, err;
string mesh_prefix, sol_prefix;
cout << "Script: psolution: " << flush;
// read number of processors
scr >> np;
cout << "# processors: " << np << "; " << flush;
// read the mesh prefix
scr >> ws >> mesh_prefix; // mesh prefix (can't contain spaces)
cout << "mesh prefix: " << mesh_prefix << "; " << flush;
scr >> ws >> keep_attr;
if (keep_attr)
{
cout << "(real attributes); " << flush;
}
else
{
cout << "(processor attributes); " << flush;
}
// read the solution prefix
scr >> ws >> sol_prefix;
cout << "solution prefix: " << sol_prefix << endl;
err = ReadParMeshAndGridFunction(np, mesh_prefix.c_str(),
sol_prefix.c_str(), state, keep_attr);
if (!err)
{
state.Extrude1DMeshAndSolution();
}
return err;
}
int ScriptReadDisplMesh(istream &scr, StreamState& state)
{
StreamState meshstate;
string word;
cout << "Script: mesh: " << flush;
scr >> ws >> word;
{
named_ifgzstream imesh(word.c_str());
if (!imesh)
{
cout << "Can not open mesh file: " << word << endl;
return 1;
}
cout << word << endl;
meshstate.mesh.reset(new Mesh(imesh, 1, 0, state.fix_elem_orient));
}
meshstate.Extrude1DMeshAndSolution();
Mesh* const m = meshstate.mesh.get();
if (init_nodes == NULL)
{
init_nodes = new Vector;
meshstate.mesh->GetNodes(*init_nodes);
state.mesh = NULL;
state.grid_f = NULL;
}
else
{
FiniteElementCollection *vfec = NULL;
FiniteElementSpace *vfes;
vfes = (FiniteElementSpace *)m->GetNodalFESpace();
if (vfes == NULL)
{
vfec = new LinearFECollection;
vfes = new FiniteElementSpace(m, vfec, m->SpaceDimension());
}
meshstate.grid_f.reset(new GridFunction(vfes));
GridFunction * const g = meshstate.grid_f.get();
if (vfec)
{
g->MakeOwner(vfec);
}
m->GetNodes(*g);
if (g->Size() == init_nodes->Size())
{
subtract(*init_nodes, *g, *g);
}
else
{
cout << "Script: incompatible meshes!" << endl;
*g = 0.0;
}
state.mesh = std::move(meshstate.mesh);
state.grid_f = std::move(meshstate.grid_f);
}
return 0;
}
void ExecuteScriptCommand()
{
if (!script)
{
cout << "No script stream defined! (Bug?)" << endl;
return;
}
istream &scr = *script;
string word;
int done_one_command = 0;
while (!done_one_command)
{
scr >> ws;
if (!scr.good())
{
cout << "End of script." << endl;
scr_level = 0;
return;
}
if (scr.peek() == '#')
{
getline(scr, word);
continue;
}
scr >> word;
if (word == "{")
{
scr_level++;
}
else if (word == "}")
{
scr_level--;
if (scr_level < 0)
{
scr_level = 0;
}
}
else if (word == "solution" || word == "mesh" || word == "psolution")
{
StreamState new_state;
if (word == "solution")
{
if (ScriptReadSolution(scr, new_state))
{
done_one_command = 1;
continue;
}
}
else if (word == "mesh")
{
if (ScriptReadDisplMesh(scr, new_state))
{
done_one_command = 1;
continue;
}
if (new_state.mesh == NULL)
{
cout << "Script: unexpected 'mesh' command!" << endl;
done_one_command = 1;
continue;
}
}
else if (word == "psolution")
{
if (ScriptReadParSolution(scr, new_state))
{
done_one_command = 1;
continue;
}
}
if (stream_state.SetNewMeshAndSolution(std::move(new_state), vs))
{
MyExpose();
}
else
{
cout << "Different type of mesh / solution." << endl;
}
}
else if (word == "screenshot")
{
scr >> ws >> word;
cout << "Script: screenshot: " << flush;
if (Screenshot(word.c_str(), true))
{
cout << "Screenshot(" << word << ") failed." << endl;
done_one_command = 1;
continue;
}
cout << "-> " << word << endl;
if (scr_min_val > vs->GetMinV())
{
scr_min_val = vs->GetMinV();
}
if (scr_max_val < vs->GetMaxV())
{
scr_max_val = vs->GetMaxV();
}
}
else if (word == "viewcenter")
{
scr >> vs->ViewCenterX >> vs->ViewCenterY;
cout << "Script: viewcenter: "
<< vs->ViewCenterX << ' ' << vs->ViewCenterY << endl;
MyExpose();
}
else if (word == "perspective")
{
scr >> ws >> word;
cout << "Script: perspective: " << word;
if (word == "off")
{
vs->OrthogonalProjection = 1;
}
else if (word == "on")
{
vs->OrthogonalProjection = 0;
}
else
{
cout << '?';
}
cout << endl;
MyExpose();
}
else if (word == "light")
{
scr >> ws >> word;
cout << "Script: light: " << word;
if (word == "off")
{
vs->SetLight(false);
}
else if (word == "on")
{
vs->SetLight(true);
}
else
{
cout << '?';
}
cout << endl;
MyExpose();
}
else if (word == "view")
{
double theta, phi;
scr >> theta >> phi;
cout << "Script: view: " << theta << ' ' << phi << endl;
vs->SetView(theta, phi);
MyExpose();
}
else if (word == "zoom")
{
double factor;
scr >> factor;
cout << "Script: zoom: " << factor << endl;
vs->Zoom(factor);
MyExpose();
}
else if (word == "shading")
{
scr >> ws >> word;
cout << "Script: shading: " << flush;
int s = -1;
if (word == "flat")
{
s = 0;
}
else if (word == "smooth")
{
s = 1;
}
else if (word == "cool")
{
s = 2;
}
if (s != -1)
{
vs->SetShading(s, false);
cout << word << endl;
MyExpose();
}
else
{
cout << word << " ?" << endl;
}
}
else if (word == "subdivisions")
{
int t, b;
scr >> t >> b;
cout << "Script: subdivisions: " << flush;
vs->SetRefineFactors(t, b);
cout << t << ' ' << b << endl;
MyExpose();
}
else if (word == "valuerange")
{
double min, max;
scr >> min >> max;
cout << "Script: valuerange: " << flush;
vs->SetValueRange(min, max);
cout << min << ' ' << max << endl;
MyExpose();
}
else if (word == "autoscale")
{
scr >> ws >> word;
cout << "Script: autoscale: " << word;
if (word == "off")
{
vs->SetAutoscale(0);
}
else if (word == "on")
{
vs->SetAutoscale(1);
}
else if (word == "value")
{
vs->SetAutoscale(2);
}
else if (word == "mesh")
{
vs->SetAutoscale(3);
}
else
{
cout << '?';
}
cout << endl;
}
else if (word == "window")
{
scr >> window_x >> window_y >> window_w >> window_h;
cout << "Script: window: " << window_x << ' ' << window_y
<< ' ' << window_w << ' ' << window_h << endl;
MoveResizeWindow(window_x, window_y, window_w, window_h);
MyExpose();
}
else if (word == "keys")
{
scr >> stream_state.keys;
cout << "Script: keys: '" << stream_state.keys << "'" << endl;
// SendKeySequence(keys.c_str());
CallKeySequence(stream_state.keys.c_str());
MyExpose();
}
else if (word == "palette")
{
int pal;
scr >> pal;
cout << "Script: palette: " << pal << endl;
vs->palette.SetIndex(pal-1);
MyExpose();
}
else if (word == "palette_repeat")
{
int rpt_times;
scr >> rpt_times;
cout << "Script: palette_repeat: " << rpt_times << endl;
vs->palette.SetRepeatTimes(rpt_times);
vs->palette.Init();
MyExpose();
}
else if (word == "toggle_attributes")
{
Array<int> attr_list;
cout << "Script: toggle_attributes:";
for (scr >> ws; scr.peek() != ';'; scr >> ws)
{
attr_list.Append(0);
scr >> attr_list.Last();
if (attr_list.Size() <= 256)
{
cout << ' ' << attr_list.Last();
}
else if (attr_list.Size() == 257)
{
cout << " ... " << flush;
}
}
scr.get(); // read the end symbol: ';'
cout << endl;
vs->ToggleAttributes(attr_list);
MyExpose();
}
else if (word == "rotmat")
{
cout << "Script: rotmat:";
for (int i = 0; i < 16; i++)
{
scr >> vs->rotmat[i/4][i%4];
cout << ' ' << vs->rotmat[i/4][i%4];
}
cout << endl;
MyExpose();
}
else if (word == "camera")
{
double cam[9];
cout << "Script: camera:";
for (int i = 0; i < 9; i++)
{
scr >> cam[i];
cout << ' ' << cam[i];
}
cout << endl;
vs->cam.Set(cam);
MyExpose();
}
else if (word == "scale")
{
double scale;
cout << "Script: scale:";
scr >> scale;
cout << ' ' << scale;
cout << endl;
vs->Scale(scale);
MyExpose();
}
else if (word == "translate")
{
double x, y, z;
cout << "Script: translate:";
scr >> x >> y >> z;
cout << ' ' << x << ' ' << y << ' ' << z;
cout << endl;
vs->Translate(x, y, z);
MyExpose();
}
else if (word == "plot_caption")
{
char delim;
scr >> ws >> delim;
getline(scr, plot_caption, delim);
vs->PrepareCaption(); // turn on or off the caption
MyExpose();
}
else
{
cout << "Unknown command in script: " << word << endl;
}
done_one_command = 1;
}
}
void ScriptControl();
void ScriptIdleFunc()
{
ExecuteScriptCommand();
if (scr_level == 0)
{
ScriptControl();
}
}
void ScriptControl()
{
if (scr_running)
{
scr_running = 0;
RemoveIdleFunc(ScriptIdleFunc);
}
else
{
scr_running = 1;
AddIdleFunc(ScriptIdleFunc);
}
}
void PlayScript(istream &scr)
{
string word;
scr_min_val = numeric_limits<double>::infinity();
scr_max_val = -scr_min_val;
// read initializing commands
while (1)
{
scr >> ws;
if (!scr.good())
{
cout << "Error in script" << endl;
return;
}
if (scr.peek() == '#')
{
getline(scr, word);
continue;
}
scr >> word;
if (word == "window")
{
scr >> window_x >> window_y >> window_w >> window_h;
}
else if (word == "solution")
{
if (ScriptReadSolution(scr, stream_state))
{
return;
}
// start the visualization
break;
}
else if (word == "psolution")
{
if (ScriptReadParSolution(scr, stream_state))
{
return;
}
// start the visualization
break;
}
else if (word == "mesh")
{
if (ScriptReadDisplMesh(scr, stream_state))
{
return;
}
if (stream_state.mesh)
{
break;
}
}
else
{
cout << "Unknown command in script: " << word << endl;
}
}
scr_level = scr_running = 0;
script = &scr;
stream_state.keys.clear();
if (GLVisInitVis((stream_state.grid_f->VectorDim() == 1) ? 0 : 1))
{
GetAppWindow()->setOnKeyDown(SDLK_SPACE, ScriptControl);
GLVisStartVis();
}
delete init_nodes; init_nodes = NULL;
cout << "Script: min_val = " << scr_min_val
<< ", max_val = " << scr_max_val << endl;
script = NULL;
}
int main (int argc, char *argv[])
{
// variables for command line arguments
bool multi_session = true; // not added as option
bool mac = false;
const char *stream_file = string_none;
const char *script_file = string_none;
const char *font_name = string_default;
int portnum = 19916;
bool secure = socketstream::secure_default;
int multisample = GetMultisample();
double line_width = 1.0;
double ms_line_width = gl3::LINE_WIDTH_AA;
int geom_ref_type = Quadrature1D::ClosedUniform;
bool legacy_gl_ctx = false;
OptionsParser args(argc, argv);
args.AddOption(&mesh_file, "-m", "--mesh",
"Mesh file to visualize.");
args.AddOption(&gfunc_file, "-g", "--grid-function",
"Solution (GridFunction) file to visualize.");
args.AddOption(&gf_component, "-gc", "--grid-function-component",
"Select a grid function component, [0-<num-comp>) or"
" -1 for all.");
args.AddOption(&sol_file, "-s", "--scalar-solution",
"Scalar solution (vertex values) file to visualize.");
args.AddOption(&vec_sol_file, "-v", "--vector-solution",
"Vector solution (vertex values) file to visualize.");
args.AddOption(&np, "-np", "--num-proc",
"Load mesh/solution from multiple processors.");
args.AddOption(&pad_digits, "-d", "--pad-digits",
"Number of digits used for processor ranks in file names.");
args.AddOption(&script_file, "-run", "--run-script",
"Run a GLVis script file.");
args.AddOption(&arg_keys, "-k", "--keys",
"Execute key shortcut commands in the GLVis window.");
args.AddOption(&stream_state.fix_elem_orient, "-fo", "--fix-orientations",
"-no-fo", "--dont-fix-orientations",
"Attempt to fix the orientations of inverted elements.");
args.AddOption(&keep_attr, "-a", "--real-attributes",
"-ap", "--processor-attributes",
"When opening a parallel mesh, use the real mesh attributes"
" or replace them with the processor rank.");
args.AddOption(&geom_ref_type, "-grt", "--geometry-refiner-type",
"Set of points to use when refining geometry:"
" 3 = uniform, 1 = Gauss-Lobatto, (see mfem::Quadrature1D).");
args.AddOption(&stream_state.save_coloring, "-sc", "--save-coloring",
"-no-sc", "--dont-save-coloring",
"Save the mesh coloring generated when opening only a mesh.");
args.AddOption(&portnum, "-p", "--listen-port",
"Specify the port number on which to accept connections.");
args.AddOption(&secure, "-sec", "--secure-sockets",
"-no-sec", "--standard-sockets",
"Enable or disable GnuTLS secure sockets.");
args.AddOption(&mac, "-mac", "--save-stream",
"-no-mac", "--dont-save-stream",
"In server mode, save incoming data to a file before"
" visualization.");
args.AddOption(&stream_file, "-saved", "--saved-stream",
"Load a GLVis stream saved to a file.");
args.AddOption(&window_w, "-ww", "--window-width",
"Set the window width.");
args.AddOption(&window_h, "-wh", "--window-height",
"Set the window height.");
args.AddOption(&window_title, "-wt", "--window-title",
"Set the window title.");
args.AddOption(&c_plot_caption, "-c", "--plot-caption",
"Set the plot caption (visible when colorbar is visible).");
args.AddOption(&font_name, "-fn", "--font",
"Set the font: [<font-name>[:style=<style>]][-<font-size>],"
" e.g. -fn \"Helvetica:style=Bold-16\".");
args.AddOption(&multisample, "-ms", "--multisample",
"Set the multisampling mode (toggled with the 'A' key).");
args.AddOption(&line_width, "-lw", "--line-width",
"Set the line width (multisampling off).");
args.AddOption(&ms_line_width, "-mslw", "--multisample-line-width",
"Set the line width (multisampling on).");
args.AddOption(&legacy_gl_ctx, "-oldgl", "--legacy-gl",
"-anygl", "--any-gl",
"Only try to create a legacy OpenGL (< 2.1) context.");
cout << endl
<< " _/_/_/ _/ _/ _/ _/" << endl
<< " _/ _/ _/ _/ _/_/_/" << endl
<< " _/ _/_/ _/ _/ _/ _/ _/_/" << endl
<< " _/ _/ _/ _/ _/ _/ _/_/" << endl
<< " _/_/_/ _/_/_/_/ _/ _/ _/_/_/" << endl
<< endl ;
args.Parse();
if (!args.Good())
{
if (!args.Help())
{
args.PrintError(cout);
cout << endl;
}
PrintSampleUsage(cout);
args.PrintHelp(cout);
return 1;
}
// set options
if (mesh_file != string_none)
{
input |= 2;
}
if (sol_file != string_none)
{
input |= 4;
}
if (vec_sol_file != string_none)
{
sol_file = vec_sol_file;
input |= 8;
}
if (gfunc_file != string_none)
{
sol_file = gfunc_file;
stream_state.is_gf = 255;
}
if (np > 0)
{
input |= 256;
}
if (arg_keys != string_none)
{
stream_state.keys = arg_keys;
}
if (font_name != string_default)
{
SetFont(font_name);
}
if (multisample != GetMultisample())
{
SetMultisample(multisample);
}
if (line_width != GetLineWidth())
{
SetLineWidth(line_width);
}
if (ms_line_width != GetLineWidthMS())
{
SetLineWidthMS(ms_line_width);
}
if (c_plot_caption != string_none)
{
plot_caption = c_plot_caption;
}
if (legacy_gl_ctx == true)
{
SetLegacyGLOnly(legacy_gl_ctx);
}
GLVisGeometryRefiner.SetType(geom_ref_type);
string data_type;
// check for saved stream file
if (stream_file != string_none)
{
ifstream ifs(stream_file);
if (!ifs)
{
cout << "Can not open stream file: " << stream_file << endl;
return 1;
}
ifs >> data_type >> ws;
int ft = stream_state.ReadStream(ifs, data_type);
input_streams.Append(&ifs);
if (GLVisInitVis(ft))
{
GLVisStartVis();
}
return 0;
}
// check for script file
if (script_file != string_none)
{
ifstream scr(script_file);
if (!scr)
{
cout << "Can not open script: " << script_file << endl;
return 1;
}
PlayScript(scr);
return 0;
}
// print help for wrong input
if (!(input == 1 || input == 3 || input == 7 || input == 11 || input == 259 ||
(stream_state.is_gf && (input == 3 || input == 259))))
{
cout << "Invalid combination of mesh/solution options!\n\n";
PrintSampleUsage(cout);
args.PrintHelp(cout);
return 1;
}
#ifndef MFEM_USE_GNUTLS
if (secure)
{
cout << "The secure option can only be used when MFEM is compiled with"
" GnuTLS support." << endl;
return 1;
}
#endif
int childPID, viscount = 0, nproc = 1, proc = 0;
// server mode, read the mesh and the solution from a socket
if (input == 1)
{
// get rid of zombies
if (multi_session)
{
signal(SIGCHLD, SIG_IGN);
}
#ifdef MFEM_USE_GNUTLS
GnuTLS_global_state *state = NULL;
GnuTLS_session_params *params = NULL;
if (secure)
{
state = new GnuTLS_global_state;
// state->set_log_level(1000);
string home_dir(getenv("HOME"));
string server_dir = home_dir + "/.config/glvis/server/";
#ifndef MFEM_USE_GNUTLS_X509
string pubkey = server_dir + "pubring.gpg";
string privkey = server_dir + "secring.gpg";
string trustedkeys = server_dir + "trusted-clients.gpg";
#else
string pubkey = server_dir + "cert.pem";
string privkey = server_dir + "key.pem";
string trustedkeys = server_dir + "trusted-clients.pem";
#endif
params = new GnuTLS_session_params(
*state, pubkey.c_str(), privkey.c_str(),
trustedkeys.c_str(), GNUTLS_SERVER);
if (!params->status.good())
{
cout << " public key = " << pubkey << '\n'
<< " private key = " << privkey << '\n'
<< " trusted keys = " << trustedkeys << endl;
cout << "Error setting GLVis server parameters.\n"
"Generate your GLVis keys with:"
" bash glvis-keygen.sh [\"Your Name\"] [\"Your Email\"]"
<< endl;
delete params; delete state;
return 3;
}
}
#endif
const int backlog = 128;
socketserver server(portnum, backlog);
if (server.good())
{
cout << "Waiting for data on port " << portnum << " ..." << endl;
}
else
{
cout << "Server already running on port " << portnum << ".\n" << endl;
#ifdef MFEM_USE_GNUTLS
delete params; delete state;
#endif
return 2;
}
socketstream *isock;
#ifndef MFEM_USE_GNUTLS
isock = new socketstream;
#else
isock = secure ? new socketstream(*params) : new socketstream(false);
#endif
while (1)
{
while (server.accept(*isock) < 0)
{
#ifdef GLVIS_DEBUG
cout << "GLVis: server.accept(...) failed." << endl;
#endif
}
*isock >> data_type >> ws;
if (mac)
{
viscount++;
}
int par_data = 0;
if (data_type == "parallel")
{
par_data = 1;
np = 0;
do
{
*isock >> nproc >> proc;
#ifdef GLVIS_DEBUG
cout << "new connection: parallel " << nproc << ' ' << proc
<< endl;
#endif
if (np == 0)
{
if (nproc <= 0)
{
cout << "Invalid number of processors: " << nproc << endl;
mfem_error();
}
input_streams.SetSize(nproc);
input_streams = NULL;
}
else
{
if (nproc != input_streams.Size())
{
cout << "Unexpected number of processors: " << nproc
<< ", expected: " << input_streams.Size() << endl;
mfem_error();
}
}
if (0 > proc || proc >= nproc)
{
cout << "Invalid processor rank: " << proc
<< ", number of processors: " << nproc << endl;
mfem_error();
}
if (input_streams[proc])
{
cout << "Second connection attempt from processor rank: "
<< proc << endl;
mfem_error();
}
input_streams[proc] = isock;
#ifndef MFEM_USE_GNUTLS
isock = new socketstream;
#else
isock = secure ? new socketstream(*params) :
new socketstream(false);
#endif
np++;
if (np == nproc)
{
break;
}
// read next available socket stream
while (server.accept(*isock) < 0)
{
#ifdef GLVIS_DEBUG
cout << "GLVis: server.accept(...) failed." << endl;
#endif
}
*isock >> data_type >> ws; // "parallel"
if (data_type != "parallel")
{
cout << "Expected keyword \"parallel\", got \"" << data_type
<< '"' << endl;
mfem_error();
}
}
while (1);
}
char tmp_file[50];
if (multi_session)
{
if (mac)
{
sprintf(tmp_file,"glvis-saved.%04d",viscount);
ofstream ofs(tmp_file);
if (!par_data)
{
ofs << data_type << '\n';
ofs << isock->rdbuf();
isock->close();
}
else
{
ReadInputStreams(stream_state);
CloseInputStreams(false);
ofs.precision(8);
ofs << "solution\n";
stream_state.mesh->Print(ofs);
stream_state.grid_f->Save(ofs);
}
ofs.close();
cout << "Data saved in " << tmp_file << endl;
}
childPID = fork();
}
else
{
childPID = 0;
}
switch (childPID)
{
case -1:
cout << "The process couldn't fork. Exit." << endl;
exit(1);
case 0: // This is the child process
server.close();
if (mac)
{
// exec ourself
const char *args[4] = { argv[0], "-saved", tmp_file, NULL };
execve(args[0], (char* const*)args, environ);
exit(0);
}
else
{
if (multi_session)
{
signal(SIGINT, SIG_IGN);
}
int ft;
if (!par_data)
{
ft = stream_state.ReadStream(*isock, data_type);
input_streams.Append(isock);
}
else
{
delete isock;
ft = ReadInputStreams(stream_state);
}
if (GLVisInitVis(ft))
{
GLVisStartVis();
}
CloseInputStreams(false);
exit(0);
}
default : // This is the parent process
if (!par_data)
{
isock->rdbuf()->socketbuf::close();
}
else
{
CloseInputStreams(true);
}
}
}
#ifdef MFEM_USE_GNUTLS
delete params; delete state;
#endif
}
else // input != 1, non-server mode
{
if (input & 256)
{
ReadParallel(stream_state);
}
else
{
ReadSerial(stream_state);
}
bool use_vector_soln = (input & 8);
bool use_soln = (input & 4);
int field_type;
if (use_vector_soln)
{
field_type = 1;
}
else
{
field_type = (use_soln) ? 0 : 2;
}
if (GLVisInitVis(field_type))
{
GLVisStartVis();
}
}
cout << "Thank you for using GLVis." << endl;
return 0;
}
void PrintSampleUsage(ostream &out)
{
out <<
"Start a GLVis server:\n"
" glvis\n"
"Visualize a mesh:\n"
" glvis -m <mesh_file>\n"
"Visualize mesh and solution (grid function):\n"
" glvis -m <mesh_file> -g <grid_function_file> [-gc <component>]\n"
"Visualize parallel mesh and solution (grid function):\n"
" glvis -np <#proc> -m <mesh_prefix> [-g <grid_function_prefix>]\n\n"
"All Options:\n";
}
void ReadSerial(StreamState& state)
{
// get the mesh from a file
named_ifgzstream meshin(mesh_file);
if (!meshin)
{
cerr << "Can not open mesh file " << mesh_file << ". Exit.\n";
exit(1);
}
state.mesh.reset(new Mesh(meshin, 1, 0, state.fix_elem_orient));
if (state.is_gf || (input & 4) || (input & 8))
{
// get the solution from file
bool freesolin = false;
ifgzstream *solin = NULL;
if (!strcmp(mesh_file,sol_file))
{
solin = &meshin;
}
else
{
solin = new ifgzstream(sol_file);
freesolin = true;
if (!(*solin))
{
cerr << "Can not open solution file " << sol_file << ". Exit.\n";
exit(1);
}
}
if (state.is_gf)
{
state.grid_f.reset(new GridFunction(state.mesh.get(), *solin));
SetGridFunction(state);
}
else if (input & 4)
{
// get rid of NetGen's info line
char buff[128];
solin->getline(buff,128);
state.sol.Load(*solin, state.mesh->GetNV());
}
else if (input & 8)
{
state.solu.Load(*solin, state.mesh->GetNV());
state.solv.Load(*solin, state.mesh->GetNV());
if (state.mesh->SpaceDimension() == 3)
{
state.solw.Load(*solin, state.mesh->GetNV());
}
}
if (freesolin)
{
delete solin;
}
}
else
{
state.SetMeshSolution();
}
state.Extrude1DMeshAndSolution();
}
void SetGridFunction(StreamState& state)
{
if (gf_component != -1)
{
if (gf_component < 0 || gf_component >= state.grid_f->VectorDim())
{
cerr << "Invalid component " << gf_component << '.' << endl;
exit(1);
}
FiniteElementSpace *ofes = state.grid_f->FESpace();
FiniteElementCollection *fec =
FiniteElementCollection::New(ofes->FEColl()->Name());
FiniteElementSpace *fes = new FiniteElementSpace(state.mesh.get(), fec);
GridFunction *new_gf = new GridFunction(fes);
new_gf->MakeOwner(fec);
for (int i = 0; i < new_gf->Size(); i++)
{
(*new_gf)(i) = (*state.grid_f)(ofes->DofToVDof(i, gf_component));
}
state.grid_f.reset(new_gf);
}
if (state.grid_f->VectorDim() == 1)
{
state.grid_f->GetNodalValues(state.sol);
input |= 4;
}
else
{
input |= 8;
}
}
void ReadParallel(StreamState& state)
{
int err;
if (state.is_gf)
{
err = ReadParMeshAndGridFunction(np, mesh_file, sol_file,
state, keep_attr);
if (!err)
{
SetGridFunction(state);
}
}
else
{
err = ReadParMeshAndGridFunction(np, mesh_file, NULL,
state, keep_attr);
if (!err)
{
state.SetMeshSolution();
}
}
if (err)
{
exit(1);
}
state.Extrude1DMeshAndSolution();
}
int ReadParMeshAndGridFunction(int np, const char *mesh_prefix,
const char *sol_prefix,
StreamState& state, int keep_attr)
{
state.mesh = NULL;
// are the solutions bundled together with the mesh files?
bool same_file = false;
if (sol_prefix)
{
same_file = !strcmp(sol_prefix, mesh_prefix);
state.grid_f = NULL;
}
Array<Mesh *> mesh_array(np);
Array<GridFunction *> gf_array(np);
mesh_array = NULL;
gf_array = NULL;
int err = 0;
for (int p = 0; p < np; p++)
{
ostringstream fname;
fname << mesh_prefix << '.' << setfill('0') << setw(pad_digits) << p;
named_ifgzstream meshfile(fname.str().c_str());
if (!meshfile)
{
cerr << "Could not open mesh file: " << fname.str() << '!' << endl;
err = 1;
break;
}
mesh_array[p] = new Mesh(meshfile, 1, 0, state.fix_elem_orient);
if (!keep_attr)
{
// set element and boundary attributes to be the processor number + 1
for (int i = 0; i < mesh_array[p]->GetNE(); i++)
{
mesh_array[p]->GetElement(i)->SetAttribute(p+1);
}
for (int i = 0; i < mesh_array[p]->GetNBE(); i++)
{
mesh_array[p]->GetBdrElement(i)->SetAttribute(p+1);
}
}
// read the solution
if (sol_prefix)
{
if (!same_file)
{
ostringstream fname;
fname << sol_prefix << '.' << setfill('0') << setw(pad_digits) << p;
ifgzstream solfile(fname.str().c_str());
if (!solfile)
{
cerr << "Could not open solution file "
<< fname.str() << '!' << endl;
err = 2;
break;
}
gf_array[p] = new GridFunction(mesh_array[p], solfile);
}
else // mesh and solution in the same file
{
gf_array[p] = new GridFunction(mesh_array[p], meshfile);
}
}
}
if (!err)
{
// create the combined mesh and gf
state.mesh.reset(new Mesh(mesh_array, np));
if (sol_prefix)
{
state.grid_f.reset(new GridFunction(state.mesh.get(), gf_array, np));
}
}
for (int p = 0; p < np; p++)
{
delete gf_array[np-1-p];
delete mesh_array[np-1-p];
}
return err;
}
int ReadInputStreams(StreamState& state)
{
int nproc = input_streams.Size();
Array<Mesh *> mesh_array(nproc);
Array<GridFunction *> gf_array(nproc);
string data_type;
int gf_count = 0;
int field_type = 0;
for (int p = 0; p < nproc; p++)
{
#ifdef GLVIS_DEBUG
cout << "connection[" << p << "]: reading initial data ... " << flush;
#endif
istream &isock = *input_streams[p];
// assuming the "parallel nproc p" part of the stream has been read
isock >> ws >> data_type >> ws; // "*_data" / "mesh" / "solution"
#ifdef GLVIS_DEBUG
cout << " type " << data_type << " ... " << flush;
#endif
mesh_array[p] = new Mesh(isock, 1, 0, state.fix_elem_orient);
if (!keep_attr)
{
// set element and boundary attributes to proc+1
for (int i = 0; i < mesh_array[p]->GetNE(); i++)
{
mesh_array[p]->GetElement(i)->SetAttribute(p+1);
}
for (int i = 0; i < mesh_array[p]->GetNBE(); i++)
{
mesh_array[p]->GetBdrElement(i)->SetAttribute(p+1);
}
}
gf_array[p] = NULL;
if (data_type != "mesh")
{
gf_array[p] = new GridFunction(mesh_array[p], isock);
gf_count++;
}
#ifdef GLVIS_DEBUG
cout << "done." << endl;
#endif
}
if (gf_count > 0 && gf_count != nproc)
{
mfem_error("Input streams contain a mixture of data types!");
}
state.mesh.reset(new Mesh(mesh_array, nproc));
if (gf_count == 0)
{
state.SetMeshSolution();
field_type = 2;
}
else
{
state.grid_f.reset(new GridFunction(state.mesh.get(), gf_array, nproc));
field_type = (state.grid_f->VectorDim() == 1) ? 0 : 1;
}
for (int p = 0; p < nproc; p++)
{
delete mesh_array[nproc-1-p];
delete gf_array[nproc-1-p];
}
state.Extrude1DMeshAndSolution();
return field_type;
}
void CloseInputStreams(bool parent)
{
for (int i = 0; i < input_streams.Size(); i++)
{
if (parent)
{
socketstream *sock = dynamic_cast<socketstream*>(input_streams[i]);
if (sock) { sock->rdbuf()->socketbuf::close(); }
}
delete input_streams[i];
}
input_streams.DeleteAll();
}
| 27.177738 | 92 | 0.492932 | [
"mesh",
"geometry",
"vector",
"3d"
] |
90fb5ab30d2e48e2e06ba30bd0348fb97cdb6e98 | 1,814 | cpp | C++ | UVa/UVA - 11997/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | UVa/UVA - 11997/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | UVa/UVA - 11997/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: 2019-10-18 23:13:20
* solution_verdict: Accepted language: C++
* run_time: 80 memory_used:
* problem: https://vjudge.net/problem/UVA-11997
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=750;
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int n;while(cin>>n)
{
vector<vector<int> >aa(n);int sum=0;
for(int i=0;i<n;i++)
{
aa[i].resize(n);
for(int j=0;j<n;j++)
cin>>aa[i][j];
sort(aa[i].begin(),aa[i].end());
sum+=aa[i][0];
}
priority_queue<int>pq;pq.push(sum);
for(int j=1;j<n;j++)pq.push(sum+aa[0][j]-aa[0][0]);
vector<int>tmp;//asymptotic
for(int i=1;i<n;i++)
{
tmp.clear();
while(pq.size())
{
tmp.push_back(pq.top());pq.pop();
}
for(auto x:tmp)pq.push(x);
reverse(tmp.begin(),tmp.end());
for(int j=1;j<n;j++)
{
for(int k=0;k<n;k++)
{
if(tmp[k]+aa[i][j]-aa[i][0]<pq.top())
{
pq.push(tmp[k]+aa[i][j]-aa[i][0]);
pq.pop();
}
else break;
}
}
}
tmp.clear();
while(pq.size())
{
tmp.push_back(pq.top());pq.pop();
}
for(auto x:tmp)pq.push(x);
reverse(tmp.begin(),tmp.end());
for(int i=0;i<tmp.size();i++)
{
if(i)cout<<" ";
cout<<tmp[i];
}
cout<<endl;
}
return 0;
} | 27.074627 | 111 | 0.384234 | [
"vector"
] |
90fc1c55388e29979f2a5d04c9eb4573006d7b23 | 5,308 | cpp | C++ | src/MainFrame.cpp | Drusy/qt-borderless | e46af84034bc6b8cf57d40283c84d5d5514102e2 | [
"MIT"
] | 5 | 2016-06-06T13:25:53.000Z | 2021-04-18T22:53:05.000Z | src/MainFrame.cpp | Drusy/qt-borderless | e46af84034bc6b8cf57d40283c84d5d5514102e2 | [
"MIT"
] | null | null | null | src/MainFrame.cpp | Drusy/qt-borderless | e46af84034bc6b8cf57d40283c84d5d5514102e2 | [
"MIT"
] | 2 | 2015-06-26T12:06:04.000Z | 2019-05-15T13:30:40.000Z | #include "MainFrame.h"
#include "TitleBar.h"
#include "HoverMoveFilter.h"
#include "WindowTitleFilter.h"
MainFrame::MainFrame()
{
mMousePressed = false;
setFrameShape(Panel);
// Make this a borderless window which can't
// be resized or moved via the window system
setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint | Qt::Dialog);
// Event tricks
setMouseTracking(true);
setAttribute(Qt::WA_Hover);
installEventFilter(new HoverMoveFilter(this));
// Get title changes
installEventFilter(new WindowTitleFilter(this));
// Title
mTitleBar = new TitleBar(this);
setWindowTitle("Borderless window");
mMainWindow = new QMainWindow(this);
mMainWindow->setWindowFlags(Qt::Widget);
// Creating action
QAction *action = new QAction(QIcon::fromTheme("document-open"), tr("&Open..."), this);
action->setShortcuts(QKeySequence::Open);
action->setStatusTip(tr("Do nothing ;)"));
// Creating toolbar
QToolBar *toolbar = new QToolBar(mMainWindow);
toolbar->addAction(action);
mMainWindow->addToolBar(toolbar);
// Creating menu
QMenu *menu = mMainWindow->menuBar()->addMenu(tr("&File"));
menu->addAction(action);
// Creating dock
QDockWidget *dockWidget = new QDockWidget(tr("Dock Widget"), this);
QPushButton *pushButton = new QPushButton(QIcon::fromTheme("edit-undo"),"Panic",dockWidget);
dockWidget->setWidget(pushButton);
mMainWindow->addDockWidget(Qt::RightDockWidgetArea, dockWidget);
QVBoxLayout *vbox = new QVBoxLayout(this);
vbox->addWidget(mTitleBar);
vbox->setMargin(0);
vbox->setSpacing(0);
QVBoxLayout *layout = new QVBoxLayout();
layout->addWidget(mMainWindow);
layout->setMargin(WINDOW_MARGIN);
layout->setSpacing(0);
vbox->addLayout(layout);
//HWND hwnd = (HWND)GetActiveWindow();
//SetWindowLongPtr(hwnd, GWL_STYLE, static_cast<LONG>(WS_VISIBLE |WS_POPUP | WS_CAPTION | WS_THICKFRAME | WS_MAXIMIZEBOX | WS_MINIMIZEBOX));
}
bool MainFrame::nativeEvent(const QByteArray &, void *message, long *result) {
MSG* msg = reinterpret_cast<MSG*>(message);
switch(msg->message) {
case WM_NCCALCSIZE:
*result = 0;
return true;
}
return false;
}
void MainFrame::mousePressEvent(QMouseEvent *e)
{
// mOldPos = e->pos();
mMousePressed = e->button() == Qt::LeftButton;
if (mMousePressed) {
if (left) {
mClickedPos.setX(e->pos().x());
}
if (right) {
mClickedPos.setX(width() - e->pos().x());
}
if (bottom) {
mClickedPos.setY(height() - e->pos().y());
}
}
setWindowTitle("Resizing");
}
void MainFrame::mouseReleaseEvent(QMouseEvent *e)
{
if (e->button() == Qt::LeftButton) {
mMousePressed = false;
}
setWindowTitle("Borderless window");
}
void MainFrame::mouseMove(QPoint newPos, QPoint oldPos)
{
if (mMousePressed) {
int dx = newPos.x() - oldPos.x();
int dy = newPos.y() - oldPos.y();
QRect g = geometry();
QSize minSize = minimumSize();
// We don't resize if the windows has the minimum size
if (left) {
// Fix a bug when you try to resize to less than minimum size and
// then the mouse goes right again.
if (dx < 0 && oldPos.x() > mClickedPos.x() ) {
dx += oldPos.x() - mClickedPos.x();
if (dx > 0) {
dx = 0;
}
} else if ( dx > 0 && g.width() - dx < minSize.width()) {
dx = g.width() - minSize.width();
}
g.setLeft(g.left() + dx);
}
if (right) {
// Fix a bug when you try to resize to less than minimum size and
// then the mouse goes right again.
if (dx > 0 && (width() - newPos.x() > mClickedPos.x())) {
dx -= width() - newPos.x() - mClickedPos.x();
if (dx < 0) {
dx = 0;
}
}
g.setRight(g.right() + dx);
}
if (bottom) {
// Fix a bug when you try to resize to less than minimum size and
// then the mouse goes down again.
if (dy > 0 && (height() - newPos.y() > mClickedPos.y())) {
dy -= height() - newPos.y() - mClickedPos.y();
if (dy < 0) {
dy = 0;
}
}
g.setBottom(g.bottom() + dy);
}
setGeometry(g);
} else {
QRect r = rect();
left = qAbs(newPos.x()- r.left()) <= WINDOW_MARGIN &&
newPos.y() > mTitleBar->height();
right = qAbs(newPos.x() - r.right()) <= WINDOW_MARGIN &&
newPos.y() > mTitleBar->height();
bottom = qAbs(newPos.y() - r.bottom()) <= WINDOW_MARGIN;
bool hor = left | right;
if (hor && bottom) {
if (left)
setCursor(Qt::SizeBDiagCursor);
else
setCursor(Qt::SizeFDiagCursor);
} else if (hor) {
setCursor(Qt::SizeHorCursor);
} else if (bottom) {
setCursor(Qt::SizeVerCursor);
} else {
setCursor(Qt::ArrowCursor);
}
}
}
| 30.331429 | 144 | 0.555765 | [
"geometry"
] |
2908b2b4804887104a6a86d42ae28d5e85f99860 | 2,500 | cpp | C++ | src/asn-one-objects/LdapSearchRequestAsnOneObject.cpp | gflix/LdapServer | 1865caeec95c0e984cfab70d54976197349457eb | [
"MIT"
] | 1 | 2020-10-04T21:00:42.000Z | 2020-10-04T21:00:42.000Z | src/asn-one-objects/LdapSearchRequestAsnOneObject.cpp | gflix/LdapServer | 1865caeec95c0e984cfab70d54976197349457eb | [
"MIT"
] | null | null | null | src/asn-one-objects/LdapSearchRequestAsnOneObject.cpp | gflix/LdapServer | 1865caeec95c0e984cfab70d54976197349457eb | [
"MIT"
] | null | null | null | /*
* LdapSearchRequestAsnOneObject.cpp
*
* Created on: 14.05.2017
* Author: felix
*/
#include <cassert>
#include <asn-one-objects/LdapSearchRequestAsnOneObject.h>
#include <common/Log.h>
namespace Flix {
LdapSearchRequestAsnOneObject::LdapSearchRequestAsnOneObject():
GenericAsnOneObject(AsnOneObjectType::LDAP_SEARCH_REQUEST)
{
}
LdapSearchRequestAsnOneObject::~LdapSearchRequestAsnOneObject()
{
}
bool LdapSearchRequestAsnOneObject::isValid(void) const
{
if (subObjects.size() < 8) {
return false;
}
// Do not check for subObjects[6] as this type depends on the filter
if (subObjects[0]->getType() != AsnOneObjectType::OCTET_STRING ||
subObjects[1]->getType() != AsnOneObjectType::ENUMERATED ||
subObjects[2]->getType() != AsnOneObjectType::ENUMERATED ||
subObjects[3]->getType() != AsnOneObjectType::INTEGER ||
subObjects[4]->getType() != AsnOneObjectType::INTEGER ||
subObjects[5]->getType() != AsnOneObjectType::BOOLEAN ||
subObjects[7]->getType() != AsnOneObjectType::SEQUENCE) {
return false;
}
return true;
}
LdapSearchRequestAsnOneObject* LdapSearchRequestAsnOneObject::decode(StreamBuffer buffer, AsnOneDecodeStatus& decodeStatus)
{
decodeStatus = AsnOneDecodeStatus::OK;
LdapSearchRequestAsnOneObject* asnOneObject = new LdapSearchRequestAsnOneObject();
if (!asnOneObject->decodeSequence(buffer, decodeStatus)) {
delete asnOneObject;
return nullptr;
}
if (!asnOneObject->isValid()) {
decodeStatus = AsnOneDecodeStatus::INVALID_COMPOUND;
delete asnOneObject;
return nullptr;
}
return asnOneObject;
}
LdapSearchRequestAsnOneObject* LdapSearchRequestAsnOneObject::castObject(GenericAsnOneObject* object)
{
return static_cast<LdapSearchRequestAsnOneObject*>(object);
}
StreamBuffer LdapSearchRequestAsnOneObject::serialize(void) const
{
// not supported
assert(false);
return {};
}
std::string LdapSearchRequestAsnOneObject::dump(void) const
{
std::string dumpedObject;
dumpedObject = "LdapSearchRequest{";
bool firstObject = true;
for (auto& subObject: subObjects) {
if (!subObject) {
continue;
}
if (firstObject) {
firstObject = false;
} else {
dumpedObject += ", ";
}
dumpedObject += subObject->dump();
}
dumpedObject += '}';
return dumpedObject;
}
} /* namespace Flix */
| 25.252525 | 123 | 0.6784 | [
"object"
] |
290e3e3345464ed569686228ed294be0aa7ae0c7 | 66,740 | cpp | C++ | src/PdnPinDumper/src/dr/FlexDR_maze.cpp | ax3ghazy/pdn | a53aaf9620654fc799227f2f48d61eceb0322b36 | [
"BSD-3-Clause"
] | null | null | null | src/PdnPinDumper/src/dr/FlexDR_maze.cpp | ax3ghazy/pdn | a53aaf9620654fc799227f2f48d61eceb0322b36 | [
"BSD-3-Clause"
] | null | null | null | src/PdnPinDumper/src/dr/FlexDR_maze.cpp | ax3ghazy/pdn | a53aaf9620654fc799227f2f48d61eceb0322b36 | [
"BSD-3-Clause"
] | null | null | null | /* Authors: Lutong Wang and Bangqi Xu */
/*
* Copyright (c) 2019, The Regents of the University of California
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University 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 REGENTS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "dr/FlexDR.h"
#include "drc/frDRC.h"
#include <chrono>
using namespace std;
using namespace fr;
inline frCoord FlexDRWorker::pt2boxDistSquare(const frPoint &pt, const frBox &box) {
frCoord dx = max(max(box.left() - pt.x(), pt.x() - box.right()), 0);
frCoord dy = max(max(box.bottom() - pt.y(), pt.y() - box.top()), 0);
return dx * dx + dy * dy;
}
inline frCoord FlexDRWorker::box2boxDistSquare(const frBox &box1, const frBox &box2, frCoord &dx, frCoord &dy) {
dx = max(max(box1.left(), box2.left()) - min(box1.right(), box2.right()), 0);
dy = max(max(box1.bottom(), box2.bottom()) - min(box1.top(), box2.top()), 0);
return dx * dx + dy * dy;
}
/*inline*/ void FlexDRWorker::modMinSpacingCostPlaner(drNet* net, const frBox &box, frMIdx z, bool isAddPathCost) {
auto lNum = gridGraph.getLayerNum(z);
// obj1 = curr obj
frCoord width1 = box.width();
frCoord length1 = box.length();
// obj2 = other obj
// layer default width
frCoord width2 = getDesign()->getTech()->getLayer(lNum)->getWidth();
frCoord halfwidth2 = width2 / 2;
// spacing value needed
frCoord bloatDist = 0;
auto con = getDesign()->getTech()->getLayer(lNum)->getMinSpacing();
if (con) {
if (con->typeId() == frConstraintTypeEnum::frcSpacingConstraint) {
bloatDist = static_cast<frSpacingConstraint*>(con)->getMinSpacing();
} else if (con->typeId() == frConstraintTypeEnum::frcSpacingTablePrlConstraint) {
bloatDist = static_cast<frSpacingTablePrlConstraint*>(con)->find(max(width1, width2), length1);
} else if (con->typeId() == frConstraintTypeEnum::frcSpacingTableTwConstraint) {
bloatDist = static_cast<frSpacingTableTwConstraint*>(con)->find(width1, width2, length1);
} else {
cout <<"Warning: min spacing rule not supporterd" <<endl;
return;
}
} else {
cout <<"Warning: no min spacing rule" <<endl;
return;
}
frCoord bloatDistSquare = bloatDist * bloatDist;
FlexMazeIdx mIdx1;
FlexMazeIdx mIdx2;
// assumes width always > 2
frBox bx(box.left() - bloatDist - halfwidth2 + 1, box.bottom() - bloatDist - halfwidth2 + 1,
box.right() + bloatDist + halfwidth2 - 1, box.top() + bloatDist + halfwidth2 - 1);
gridGraph.getIdxBox(mIdx1, mIdx2, bx);
//if (!isInitDR()) {
// cout <<" box " <<box <<" bloatDist " <<bloatDist <<" bx " <<bx <<endl;
// cout <<" midx1/2 (" <<mIdx1.x() <<", " <<mIdx1.y() <<") ("
// <<mIdx2.x() <<", " <<mIdx2.y() <<") (" <<endl;
//}
frPoint pt, pt1, pt2, pt3, pt4;
frCoord distSquare = 0;
int cnt = 0;
for (int i = mIdx1.x(); i <= mIdx2.x(); i++) {
for (int j = mIdx1.y(); j <= mIdx2.y(); j++) {
gridGraph.getPoint(pt, i, j);
pt1.set(pt.x() + halfwidth2, pt.y() - halfwidth2);
pt2.set(pt.x() + halfwidth2, pt.y() + halfwidth2);
pt3.set(pt.x() - halfwidth2, pt.y() - halfwidth2);
pt4.set(pt.x() - halfwidth2, pt.y() + halfwidth2);
distSquare = min(pt2boxDistSquare(pt1, box), pt2boxDistSquare(pt2, box));
distSquare = min(pt2boxDistSquare(pt3, box), distSquare);
distSquare = min(pt2boxDistSquare(pt4, box), distSquare);
if (distSquare < bloatDistSquare) {
if (isAddPathCost) {
gridGraph.addDRCCostPlanar(i, j, z); // safe access
} else {
gridGraph.subDRCCostPlanar(i, j, z); // safe access
}
if (TEST) {
cout <<" (" <<i <<", " <<j <<", " <<z <<") minSpc planer" <<endl;
}
cnt++;
//if (!isInitDR()) {
// cout <<" planer find viol mIdx (" <<i <<", " <<j <<") " <<pt <<endl;
//}
}
}
}
//cout <<"planer mod " <<cnt <<" edges" <<endl;
}
/*inline*/ void FlexDRWorker::modMinSpacingCost(drNet* net, const frBox &box, frMIdx z, bool isAddPathCost, bool isCurrPs) {
auto lNum = gridGraph.getLayerNum(z);
// obj1 = curr obj
frCoord width1 = box.width();
frCoord length1 = box.length();
// obj2 planar = other obj
// layer default width
frCoord width2planar = getDesign()->getTech()->getLayer(lNum)->getWidth();
frCoord halfwidth2planar = width2planar / 2;
// obj2 viaL = other obj
frViaDef* viaDefL = (lNum > getDesign()->getTech()->getBottomLayerNum()) ?
getDesign()->getTech()->getLayer(lNum-1)->getDefaultViaDef() :
nullptr;
frVia viaL(viaDefL);
frBox viaBoxL(0,0,0,0);
if (viaDefL) {
viaL.getLayer2BBox(viaBoxL);
}
frCoord width2viaL = viaBoxL.width();
frCoord length2viaL = viaBoxL.length();
// obj2 viaU = other obj
frViaDef* viaDefU = (lNum < getDesign()->getTech()->getTopLayerNum()) ?
getDesign()->getTech()->getLayer(lNum+1)->getDefaultViaDef() :
nullptr;
frVia viaU(viaDefU);
frBox viaBoxU(0,0,0,0);
if (viaDefU) {
viaU.getLayer1BBox(viaBoxU);
}
frCoord width2viaU = viaBoxU.width();
frCoord length2viaU = viaBoxU.length();
// spacing value needed
frCoord bloatDistPlanar = 0;
frCoord bloatDistViaL = 0;
frCoord bloatDistViaU = 0;
auto con = getDesign()->getTech()->getLayer(lNum)->getMinSpacing();
if (con) {
if (con->typeId() == frConstraintTypeEnum::frcSpacingConstraint) {
bloatDistPlanar = static_cast<frSpacingConstraint*>(con)->getMinSpacing();
bloatDistViaL = static_cast<frSpacingConstraint*>(con)->getMinSpacing();
bloatDistViaU = static_cast<frSpacingConstraint*>(con)->getMinSpacing();
} else if (con->typeId() == frConstraintTypeEnum::frcSpacingTablePrlConstraint) {
bloatDistPlanar = static_cast<frSpacingTablePrlConstraint*>(con)->find(max(width1, width2planar), length1);
bloatDistViaL = static_cast<frSpacingTablePrlConstraint*>(con)->find(max(width1, width2viaL), isCurrPs ? length2viaL : min(length1, length2viaL));
bloatDistViaU = static_cast<frSpacingTablePrlConstraint*>(con)->find(max(width1, width2viaU), isCurrPs ? length2viaU : min(length1, length2viaU));
} else if (con->typeId() == frConstraintTypeEnum::frcSpacingTableTwConstraint) {
bloatDistPlanar = static_cast<frSpacingTableTwConstraint*>(con)->find(width1, width2planar, length1);
bloatDistViaL = static_cast<frSpacingTableTwConstraint*>(con)->find(width1, width2viaL, isCurrPs ? length2viaL : min(length1, length2viaL));
bloatDistViaU = static_cast<frSpacingTableTwConstraint*>(con)->find(width1, width2viaU, isCurrPs ? length2viaU : min(length1, length2viaU));
} else {
cout <<"Warning: min spacing rule not supporterd" <<endl;
return;
}
} else {
cout <<"Warning: no min spacing rule" <<endl;
return;
}
// other obj eol spc to curr obj
// no need to bloat eolWithin because eolWithin always < minSpacing
frCoord bloatDistEolX = 0;
frCoord bloatDistEolY = 0;
for (auto con: getDesign()->getTech()->getLayer(lNum)->getEolSpacing()) {
auto eolSpace = con->getMinSpacing();
auto eolWidth = con->getEolWidth();
// eol up and down
if (viaDefL && viaBoxL.right() - viaBoxL.left() < eolWidth) {
bloatDistEolY = max(bloatDistEolY, eolSpace);
}
if (viaDefU && viaBoxU.right() - viaBoxU.left() < eolWidth) {
bloatDistEolY = max(bloatDistEolY, eolSpace);
}
// eol left and right
if (viaDefL && viaBoxL.top() - viaBoxL.bottom() < eolWidth) {
bloatDistEolX = max(bloatDistEolX, eolSpace);
}
if (viaDefU && viaBoxU.top() - viaBoxU.bottom() < eolWidth) {
bloatDistEolX = max(bloatDistEolX, eolSpace);
}
}
frCoord bloatDist = max(max(bloatDistPlanar, bloatDistViaL), bloatDistViaU);
//frCoord bloatDistSquare = bloatDist * bloatDist;
FlexMazeIdx mIdx1;
FlexMazeIdx mIdx2;
// assumes width always > 2
frBox bx(box.left() - max(bloatDist, bloatDistEolX) - max(max(halfwidth2planar, viaBoxL.right() ), viaBoxU.right() ) + 1,
box.bottom() - max(bloatDist, bloatDistEolY) - max(max(halfwidth2planar, viaBoxL.top() ), viaBoxU.top() ) + 1,
box.right() + max(bloatDist, bloatDistEolX) + max(max(halfwidth2planar, viaBoxL.left() ), viaBoxU.left() ) - 1,
box.top() + max(bloatDist, bloatDistEolY) + max(max(halfwidth2planar, viaBoxL.bottom()), viaBoxU.bottom()) - 1);
gridGraph.getIdxBox(mIdx1, mIdx2, bx);
//if (!isInitDR()) {
// cout <<" box " <<box <<" bloatDist " <<bloatDist <<" bx " <<bx <<endl;
// cout <<" midx1/2 (" <<mIdx1.x() <<", " <<mIdx1.y() <<") ("
// <<mIdx2.x() <<", " <<mIdx2.y() <<") (" <<endl;
//}
frPoint pt;
frBox tmpBx;
frCoord dx, dy, prl;
frTransform xform;
frCoord reqDist = 0;
frCoord distSquare = 0;
int cnt = 0;
for (int i = mIdx1.x(); i <= mIdx2.x(); i++) {
for (int j = mIdx1.y(); j <= mIdx2.y(); j++) {
gridGraph.getPoint(pt, i, j);
xform.set(pt);
// planar
tmpBx.set(pt.x() - halfwidth2planar, pt.y() - halfwidth2planar,
pt.x() + halfwidth2planar, pt.y() + halfwidth2planar);
distSquare = box2boxDistSquare(box, tmpBx, dx, dy);
prl = max(dx, dy);
if (con->typeId() == frConstraintTypeEnum::frcSpacingConstraint) {
reqDist = static_cast<frSpacingConstraint*>(con)->getMinSpacing();
} else if (con->typeId() == frConstraintTypeEnum::frcSpacingTablePrlConstraint) {
reqDist = static_cast<frSpacingTablePrlConstraint*>(con)->find(max(width1, width2planar), prl > 0 ? length1 : 0);
} else if (con->typeId() == frConstraintTypeEnum::frcSpacingTableTwConstraint) {
reqDist = static_cast<frSpacingTableTwConstraint*>(con)->find(width1, width2planar, prl > 0 ? length1 : 0);
}
if (distSquare < reqDist * reqDist) {
if (isAddPathCost) {
gridGraph.addDRCCostPlanar(i, j, z); // safe access
} else {
gridGraph.subDRCCostPlanar(i, j, z); // safe access
}
if (TEST) {
cout <<" (" <<i <<", " <<j <<", " <<z <<") minSpc planer" <<endl;
}
cnt++;
}
// viaL
if (viaDefL) {
tmpBx.set(viaBoxL);
tmpBx.transform(xform);
distSquare = box2boxDistSquare(box, tmpBx, dx, dy);
prl = max(dx, dy);
// curr is ps
if (isCurrPs) {
if (dx == 0 && dy > 0) {
prl = viaBoxL.right() - viaBoxL.left();
} else if (dx > 0 && dy == 0) {
prl = viaBoxL.top() - viaBoxL.bottom();
}
}
if (con->typeId() == frConstraintTypeEnum::frcSpacingConstraint) {
reqDist = static_cast<frSpacingConstraint*>(con)->getMinSpacing();
} else if (con->typeId() == frConstraintTypeEnum::frcSpacingTablePrlConstraint) {
reqDist = static_cast<frSpacingTablePrlConstraint*>(con)->find(max(width1, width2viaL), prl);
} else if (con->typeId() == frConstraintTypeEnum::frcSpacingTableTwConstraint) {
reqDist = static_cast<frSpacingTableTwConstraint*>(con)->find(width1, width2viaL, prl);
}
if (distSquare < reqDist * reqDist) {
if (isAddPathCost) {
gridGraph.addDRCCostVia(i, j, z - 1);
} else {
gridGraph.subDRCCostVia(i, j, z - 1);
}
if (TEST) {
cout <<" (" <<i <<", " <<j <<", " <<z - 1 <<") U minSpc via" <<endl;
}
} else {
modMinSpacingCostVia_eol(box, tmpBx, isAddPathCost, false, i, j, z);
}
//modMinSpacingCostVia_eol(box, tmpBx, isAddPathCost, false, i, j, z);
}
if (viaDefU) {
tmpBx.set(viaBoxU);
tmpBx.transform(xform);
distSquare = box2boxDistSquare(box, tmpBx, dx, dy);
prl = max(dx, dy);
// curr is ps
if (isCurrPs) {
if (dx == 0 && dy > 0) {
prl = viaBoxU.right() - viaBoxU.left();
} else if (dx > 0 && dy == 0) {
prl = viaBoxU.top() - viaBoxU.bottom();
}
}
if (con->typeId() == frConstraintTypeEnum::frcSpacingConstraint) {
reqDist = static_cast<frSpacingConstraint*>(con)->getMinSpacing();
} else if (con->typeId() == frConstraintTypeEnum::frcSpacingTablePrlConstraint) {
reqDist = static_cast<frSpacingTablePrlConstraint*>(con)->find(max(width1, width2viaU), prl);
} else if (con->typeId() == frConstraintTypeEnum::frcSpacingTableTwConstraint) {
reqDist = static_cast<frSpacingTableTwConstraint*>(con)->find(width1, width2viaU, prl);
}
if (distSquare < reqDist * reqDist) {
if (isAddPathCost) {
gridGraph.addDRCCostVia(i, j, z);
} else {
gridGraph.subDRCCostVia(i, j, z);
}
if (TEST) {
cout <<" (" <<i <<", " <<j <<", " <<z <<") U minSpc via" <<endl;
}
} else {
modMinSpacingCostVia_eol(box, tmpBx, isAddPathCost, true, i, j, z);
}
//modMinSpacingCostVia_eol(box, tmpBx, isAddPathCost, true, i, j, z);
}
}
}
//cout <<"planer mod " <<cnt <<" edges" <<endl;
}
/*inline*/ void FlexDRWorker::modMinSpacingCostVia_eol_helper(const frBox &box, const frBox &testBox, bool isAddPathCost, bool isUpperVia,
frMIdx i, frMIdx j, frMIdx z) {
if (testBox.overlaps(box, false)) {
if (isUpperVia) {
if (isAddPathCost) {
gridGraph.addDRCCostVia(i, j, z);
} else {
gridGraph.subDRCCostVia(i, j, z);
}
if (TEST) {
cout <<" (" <<i <<", " <<j <<", " <<z <<") U minSpc eol helper" <<endl;
}
} else {
if (isAddPathCost) {
gridGraph.addDRCCostVia(i, j, z - 1);
} else {
gridGraph.subDRCCostVia(i, j, z - 1);
}
if (TEST) {
cout <<" (" <<i <<", " <<j <<", " <<z - 1 <<") U minSpc eol helper" <<endl;
}
}
}
}
/*inline*/ void FlexDRWorker::modMinSpacingCostVia_eol(const frBox &box, const frBox &tmpBx, bool isAddPathCost, bool isUpperVia,
frMIdx i, frMIdx j, frMIdx z) {
auto lNum = gridGraph.getLayerNum(z);
frBox testBox;
if (getDesign()->getTech()->getLayer(lNum)->hasEolSpacing()) {
for (auto eolCon: getDesign()->getTech()->getLayer(lNum)->getEolSpacing()) {
auto eolSpace = eolCon->getMinSpacing();
auto eolWidth = eolCon->getEolWidth();
auto eolWithin = eolCon->getEolWithin();
// eol to up and down
if (tmpBx.right() - tmpBx.left() < eolWidth) {
testBox.set(tmpBx.left() - eolWithin, tmpBx.top(), tmpBx.right() + eolWithin, tmpBx.top() + eolSpace);
modMinSpacingCostVia_eol_helper(box, testBox, isAddPathCost, isUpperVia, i, j, z);
testBox.set(tmpBx.left() - eolWithin, tmpBx.bottom() - eolSpace, tmpBx.right() + eolWithin, tmpBx.bottom());
modMinSpacingCostVia_eol_helper(box, testBox, isAddPathCost, isUpperVia, i, j, z);
}
// eol to left and right
if (tmpBx.top() - tmpBx.bottom() < eolWidth) {
testBox.set(tmpBx.right(), tmpBx.bottom() - eolWithin, tmpBx.right() + eolSpace, tmpBx.top() + eolWithin);
modMinSpacingCostVia_eol_helper(box, testBox, isAddPathCost, isUpperVia, i, j, z);
testBox.set(tmpBx.left() - eolSpace, tmpBx.bottom() - eolWithin, tmpBx.left(), tmpBx.top() + eolWithin);
modMinSpacingCostVia_eol_helper(box, testBox, isAddPathCost, isUpperVia, i, j, z);
}
}
}
}
void FlexDRWorker::modMinSpacingCostVia(const frBox &box, frMIdx z, bool isAddPathCost, bool isUpperVia, bool isCurrPs) {
auto lNum = gridGraph.getLayerNum(z);
// obj1 = curr obj
frCoord width1 = box.width();
frCoord length1 = box.length();
// obj2 = other obj
// default via dimension
frViaDef* viaDef = nullptr;
if (isUpperVia) {
viaDef = (lNum < getDesign()->getTech()->getTopLayerNum()) ?
getDesign()->getTech()->getLayer(lNum+1)->getDefaultViaDef() :
nullptr;
} else {
viaDef = (lNum > getDesign()->getTech()->getBottomLayerNum()) ?
getDesign()->getTech()->getLayer(lNum-1)->getDefaultViaDef() :
nullptr;
}
if (viaDef == nullptr) {
return;
}
frVia via(viaDef);
frBox viaBox(0,0,0,0);
if (isUpperVia) {
via.getLayer1BBox(viaBox);
} else {
via.getLayer2BBox(viaBox);
}
frCoord width2 = viaBox.width();
frCoord length2 = viaBox.length();
// spacing value needed
frCoord bloatDist = 0;
auto con = getDesign()->getTech()->getLayer(lNum)->getMinSpacing();
if (con) {
if (con->typeId() == frConstraintTypeEnum::frcSpacingConstraint) {
bloatDist = static_cast<frSpacingConstraint*>(con)->getMinSpacing();
} else if (con->typeId() == frConstraintTypeEnum::frcSpacingTablePrlConstraint) {
bloatDist = static_cast<frSpacingTablePrlConstraint*>(con)->find(max(width1, width2), isCurrPs ? length2 : min(length1, length2));
} else if (con->typeId() == frConstraintTypeEnum::frcSpacingTableTwConstraint) {
bloatDist = static_cast<frSpacingTableTwConstraint*>(con)->find(width1, width2, isCurrPs ? length2 : min(length1, length2));
} else {
cout <<"Warning: min spacing rule not supporterd" <<endl;
return;
}
} else {
cout <<"Warning: no min spacing rule" <<endl;
return;
}
// other obj eol spc to curr obj
// no need to blaot eolWithin because eolWithin always < minSpacing
frCoord bloatDistEolX = 0;
frCoord bloatDistEolY = 0;
for (auto con: getDesign()->getTech()->getLayer(lNum)->getEolSpacing()) {
auto eolSpace = con->getMinSpacing();
auto eolWidth = con->getEolWidth();
// eol up and down
if (viaBox.right() - viaBox.left() < eolWidth) {
bloatDistEolY = max(bloatDistEolY, eolSpace);
}
// eol left and right
if (viaBox.top() - viaBox.bottom() < eolWidth) {
bloatDistEolX = max(bloatDistEolX, eolSpace);
}
}
//frCoord bloatDistSquare = bloatDist * bloatDist;
FlexMazeIdx mIdx1;
FlexMazeIdx mIdx2;
// assumes width always > 2
frBox bx(box.left() - max(bloatDist, bloatDistEolX) - (viaBox.right() - 0) + 1,
box.bottom() - max(bloatDist, bloatDistEolY) - (viaBox.top() - 0) + 1,
box.right() + max(bloatDist, bloatDistEolX) + (0 - viaBox.left()) - 1,
box.top() + max(bloatDist, bloatDistEolY) + (0 - viaBox.bottom()) - 1);
gridGraph.getIdxBox(mIdx1, mIdx2, bx);
frPoint pt;
frBox tmpBx;
frCoord distSquare = 0;
frCoord dx, dy, prl;
frTransform xform;
frCoord reqDist = 0;
frBox sViaBox;
for (int i = mIdx1.x(); i <= mIdx2.x(); i++) {
for (int j = mIdx1.y(); j <= mIdx2.y(); j++) {
gridGraph.getPoint(pt, i, j);
xform.set(pt);
//if (gridGraph.isSVia(i, j, isUpperVia ? z : z - 1)) {
//auto sViaDef= apSVia[FlexMazeIdx(i, j, isUpperVia ? z : z - 1)];
//frVia sVia(sViaDef);
//if (isUpperVia) {
// sVia.getLayer1BBox(sViaBox);
//} else {
// sVia.getLayer2BBox(sViaBox);
//}
//tmpBx.set(sViaBox);
//continue;
//}
tmpBx.set(viaBox);
tmpBx.transform(xform);
distSquare = box2boxDistSquare(box, tmpBx, dx, dy);
prl = max(dx, dy);
// curr is ps
if (isCurrPs) {
if (dx == 0 && dy > 0) {
prl = viaBox.right() - viaBox.left();
} else if (dx > 0 && dy == 0) {
prl = viaBox.top() - viaBox.bottom();
}
}
if (con->typeId() == frConstraintTypeEnum::frcSpacingConstraint) {
reqDist = static_cast<frSpacingConstraint*>(con)->getMinSpacing();
} else if (con->typeId() == frConstraintTypeEnum::frcSpacingTablePrlConstraint) {
reqDist = static_cast<frSpacingTablePrlConstraint*>(con)->find(max(width1, width2), prl);
} else if (con->typeId() == frConstraintTypeEnum::frcSpacingTableTwConstraint) {
reqDist = static_cast<frSpacingTableTwConstraint*>(con)->find(width1, width2, prl);
}
if (distSquare < reqDist * reqDist) {
if (isUpperVia) {
if (isAddPathCost) {
gridGraph.addDRCCostVia(i, j, z);
} else {
gridGraph.subDRCCostVia(i, j, z);
}
if (TEST) {
cout <<" (" <<i <<", " <<j <<", " <<z <<") U minSpc via" <<endl;
}
} else {
if (isAddPathCost) {
gridGraph.addDRCCostVia(i, j, z - 1);
} else {
gridGraph.subDRCCostVia(i, j, z - 1);
}
if (TEST) {
cout <<" (" <<i <<", " <<j <<", " <<z - 1 <<") U minSpc via" <<endl;
}
}
}
// eol, other obj to curr obj
modMinSpacingCostVia_eol(box, tmpBx, isAddPathCost, isUpperVia, i, j, z);
}
}
}
// type == 0: planer
// type == 1: down
// type == 2: up
/*inline*/ void FlexDRWorker::modEolSpacingCost_helper(const frBox &testbox, frMIdx z, bool isAddPathCost, int type) {
auto lNum = gridGraph.getLayerNum(z);
frBox bx;
if (type == 0) {
// layer default width
frCoord width2 = getDesign()->getTech()->getLayer(lNum)->getWidth();
frCoord halfwidth2 = width2 / 2;
// assumes width always > 2
bx.set(testbox.left() - halfwidth2 + 1, testbox.bottom() - halfwidth2 + 1,
testbox.right() + halfwidth2 - 1, testbox.top() + halfwidth2 - 1);
} else {
// default via dimension
frViaDef* viaDef = nullptr;
if (type == 1) {
viaDef = (lNum > getDesign()->getTech()->getBottomLayerNum()) ?
getDesign()->getTech()->getLayer(lNum-1)->getDefaultViaDef() :
nullptr;
} else if (type == 2) {
viaDef = (lNum < getDesign()->getTech()->getTopLayerNum()) ?
getDesign()->getTech()->getLayer(lNum+1)->getDefaultViaDef() :
nullptr;
}
if (viaDef == nullptr) {
return;
}
frVia via(viaDef);
frBox viaBox(0,0,0,0);
if (type == 2) { // upper via
via.getLayer1BBox(viaBox);
} else {
via.getLayer2BBox(viaBox);
}
// assumes via bbox always > 2
bx.set(testbox.left() - (viaBox.right() - 0) + 1, testbox.bottom() - (viaBox.top() - 0) + 1,
testbox.right() + (0 - viaBox.left()) - 1, testbox.top() + (0 - viaBox.bottom()) - 1);
}
FlexMazeIdx mIdx1;
FlexMazeIdx mIdx2;
gridGraph.getIdxBox(mIdx1, mIdx2, bx); // >= bx
for (int i = mIdx1.x(); i <= mIdx2.x(); i++) {
for (int j = mIdx1.y(); j <= mIdx2.y(); j++) {
if (type == 0) {
if (isAddPathCost) {
gridGraph.addDRCCostPlanar(i, j, z); // safe access
} else {
gridGraph.subDRCCostPlanar(i, j, z); // safe access
}
if (TEST) {
cout <<" (" <<i <<", " <<j <<", " <<z <<") N eolSpc" <<endl;
}
} else if (type == 1) {
//if (gridGraph.isSVia(i, j, z - 1)) {
// continue;
//}
if (isAddPathCost) {
gridGraph.addDRCCostVia(i, j, z - 1); // safe access
} else {
gridGraph.subDRCCostVia(i, j, z - 1); // safe access
}
if (TEST) {
cout <<" (" <<i <<", " <<j <<", " <<z - 1 <<") U eolSpc" <<endl;
}
} else if (type == 2) {
//if (gridGraph.isSVia(i, j, z)) {
// continue;
//}
if (isAddPathCost) {
gridGraph.addDRCCostVia(i, j, z); // safe access
} else {
gridGraph.subDRCCostVia(i, j, z); // safe access
}
if (TEST) {
cout <<" (" <<i <<", " <<j <<", " <<z <<") U eolSpc" <<endl;
}
}
}
}
}
/*inline*/ void FlexDRWorker::modEolSpacingCost(const frBox &box, frMIdx z, bool isAddPathCost) {
auto lNum = gridGraph.getLayerNum(z);
frBox testBox;
if (getDesign()->getTech()->getLayer(lNum)->hasEolSpacing()) {
for (auto con: getDesign()->getTech()->getLayer(lNum)->getEolSpacing()) {
auto eolSpace = con->getMinSpacing();
auto eolWidth = con->getEolWidth();
auto eolWithin = con->getEolWithin();
// curr obj to other obj eol
//if (!isInitDR()) {
// cout <<"eolSpace/within = " <<eolSpace <<" " <<eolWithin <<endl;
//}
// eol to up and down
if (box.right() - box.left() < eolWidth) {
testBox.set(box.left() - eolWithin, box.top(), box.right() + eolWithin, box.top() + eolSpace);
//if (!isInitDR()) {
// cout <<" topBox " <<testBox <<endl;
//}
modEolSpacingCost_helper(testBox, z, isAddPathCost, 0);
modEolSpacingCost_helper(testBox, z, isAddPathCost, 1);
modEolSpacingCost_helper(testBox, z, isAddPathCost, 2);
testBox.set(box.left() - eolWithin, box.bottom() - eolSpace, box.right() + eolWithin, box.bottom());
//if (!isInitDR()) {
// cout <<" bottomBox " <<testBox <<endl;
//}
modEolSpacingCost_helper(testBox, z, isAddPathCost, 0);
modEolSpacingCost_helper(testBox, z, isAddPathCost, 1);
modEolSpacingCost_helper(testBox, z, isAddPathCost, 2);
}
// eol to left and right
if (box.top() - box.bottom() < eolWidth) {
testBox.set(box.right(), box.bottom() - eolWithin, box.right() + eolSpace, box.top() + eolWithin);
//if (!isInitDR()) {
// cout <<" rightBox " <<testBox <<endl;
//}
modEolSpacingCost_helper(testBox, z, isAddPathCost, 0);
modEolSpacingCost_helper(testBox, z, isAddPathCost, 1);
modEolSpacingCost_helper(testBox, z, isAddPathCost, 2);
testBox.set(box.left() - eolSpace, box.bottom() - eolWithin, box.left(), box.top() + eolWithin);
//if (!isInitDR()) {
// cout <<" leftBox " <<testBox <<endl;
//}
modEolSpacingCost_helper(testBox, z, isAddPathCost, 0);
modEolSpacingCost_helper(testBox, z, isAddPathCost, 1);
modEolSpacingCost_helper(testBox, z, isAddPathCost, 2);
}
// other obj to curr obj eol
}
}
}
/*inline*/ void FlexDRWorker::modCutSpacingCost(const frBox &box, frMIdx z, bool isAddPathCost) {
auto lNum = gridGraph.getLayerNum(z) + 1;
if (!getDesign()->getTech()->getLayer(lNum)->hasCutSpacing()) {
return;
}
// obj1 = curr obj
// obj2 = other obj
// default via dimension
frViaDef* viaDef = getDesign()->getTech()->getLayer(lNum)->getDefaultViaDef();
frVia via(viaDef);
frBox viaBox(0,0,0,0);
via.getCutBBox(viaBox);
// spacing value needed
frCoord bloatDist = 0;
for (auto con: getDesign()->getTech()->getLayer(lNum)->getCutSpacing()) {
bloatDist = max(bloatDist, con->getCutSpacing());
}
//frCoord bloatDistSquare = bloatDist * bloatDist;
FlexMazeIdx mIdx1;
FlexMazeIdx mIdx2;
// assumes width always > 2
frBox bx(box.left() - bloatDist - (viaBox.right() - 0) + 1,
box.bottom() - bloatDist - (viaBox.top() - 0) + 1,
box.right() + bloatDist + (0 - viaBox.left()) - 1,
box.top() + bloatDist + (0 - viaBox.bottom()) - 1);
gridGraph.getIdxBox(mIdx1, mIdx2, bx);
frPoint pt;
frBox tmpBx;
frCoord distSquare = 0;
frCoord c2cSquare = 0;
frCoord dx, dy, prl;
frTransform xform;
//frCoord reqDist = 0;
frCoord reqDistSquare = 0;
frPoint boxCenter, tmpBxCenter;
boxCenter.set((box.left() + box.right()) / 2, (box.bottom() + box.top()) / 2);
frCoord currDistSquare = 0;
bool hasViol = false;
for (int i = mIdx1.x(); i <= mIdx2.x(); i++) {
for (int j = mIdx1.y(); j <= mIdx2.y(); j++) {
for (auto &uFig: via.getViaDef()->getCutFigs()) {
auto obj = static_cast<frRect*>(uFig.get());
gridGraph.getPoint(pt, i, j);
xform.set(pt);
obj->getBBox(tmpBx);
//tmpBx.set(viaBox);
tmpBx.transform(xform);
tmpBxCenter.set((tmpBx.left() + tmpBx.right()) / 2, (tmpBx.bottom() + tmpBx.top()) / 2);
distSquare = box2boxDistSquare(box, tmpBx, dx, dy);
c2cSquare = (boxCenter.x() - tmpBxCenter.x()) * (boxCenter.x() - tmpBxCenter.x()) +
(boxCenter.y() - tmpBxCenter.y()) * (boxCenter.y() - tmpBxCenter.y());
prl = max(dx, dy);
for (auto con: getDesign()->getTech()->getLayer(lNum)->getCutSpacing()) {
hasViol = false;
//reqDist = con->getCutSpacing();
reqDistSquare = con->getCutSpacing() * con->getCutSpacing();
currDistSquare = con->hasCenterToCenter() ? c2cSquare : distSquare;
if (con->hasSameNet()) {
continue;
}
if (con->isLayer()) {
;
} else if (con->isAdjacentCuts()) {
if (currDistSquare < reqDistSquare) {
hasViol = true;
// should disable hasViol and modify this part to new grid graph
}
} else if (con->isParallelOverlap()) {
if (prl > 0 && currDistSquare < reqDistSquare) {
hasViol = true;
}
} else if (con->isArea()) {
auto currArea = max(box.length() * box.width(), tmpBx.length() * tmpBx.width());
if (currArea >= con->getCutArea() && currDistSquare < reqDistSquare) {
hasViol = true;
}
} else {
if (currDistSquare < reqDistSquare) {
hasViol = true;
}
}
if (hasViol) {
if (isAddPathCost) {
gridGraph.addDRCCostVia(i, j, z);
} else {
gridGraph.subDRCCostVia(i, j, z);
}
if (TEST) {
cout <<" (" <<i <<", " <<j <<", " <<z <<") U cutSpc" <<endl;
}
break;
}
}
}
}
}
}
void FlexDRWorker::addPathCost(drConnFig *connFig) {
modPathCost(connFig, true);
}
void FlexDRWorker::subPathCost(drConnFig *connFig) {
modPathCost(connFig, false);
}
/*inline*/ void FlexDRWorker::modPathCost(drConnFig *connFig, bool isAddPathCost) {
if (connFig->typeId() == drcPathSeg) {
auto obj = static_cast<drPathSeg*>(connFig);
auto net = obj->getNet();
FlexMazeIdx bi, ei;
obj->getMazeIdx(bi, ei);
if (TEST) {
cout <<" ";
if (isAddPathCost) {
cout <<"add";
} else {
cout <<"sub";
}
cout <<"PsCost for " <<bi <<" -- " <<ei <<endl;
}
// new
frBox box;
obj->getBBox(box);
modMinSpacingCostPlaner(net, box, bi.z(), isAddPathCost);
modMinSpacingCostVia(box, bi.z(), isAddPathCost, true, true);
modMinSpacingCostVia(box, bi.z(), isAddPathCost, false, true);
//modMinSpacingCost(net, box, bi.z(), isAddPathCost, true);
modEolSpacingCost(box, bi.z(), isAddPathCost);
} else if (connFig->typeId() == drcPatchWire) {
auto obj = static_cast<drPatchWire*>(connFig);
auto net = obj->getNet();
frMIdx zIdx = gridGraph.getMazeZIdx(obj->getLayerNum());
// FlexMazeIdx bi, ei;
// obj->getMazeIdx(bi, ei);
// if (TEST) {
// cout <<" ";
// if (isAddPathCost) {
// cout <<"add";
// } else {
// cout <<"sub";
// }
// cout <<"PsCost for " <<bi <<" -- " <<ei <<endl;
// }
// new
frBox box;
obj->getBBox(box);
modMinSpacingCostPlaner(net, box, zIdx, isAddPathCost);
modMinSpacingCostVia(box, zIdx, isAddPathCost, true, true);
modMinSpacingCostVia(box, zIdx, isAddPathCost, false, true);
//modMinSpacingCost(net, box, bi.z(), isAddPathCost, true);
modEolSpacingCost(box, zIdx, isAddPathCost);
} else if (connFig->typeId() == drcVia) {
auto obj = static_cast<drVia*>(connFig);
auto net = obj->getNet();
FlexMazeIdx bi, ei;
obj->getMazeIdx(bi, ei);
if (TEST) {
cout <<" ";
if (isAddPathCost) {
cout <<"add";
} else {
cout <<"sub";
}
cout <<"ViaCost for " <<bi <<" -- " <<ei <<endl;
}
// new
frBox box;
obj->getLayer1BBox(box); // assumes enclosure for via is always rectangle
modMinSpacingCostPlaner(net, box, bi.z(), isAddPathCost);
modMinSpacingCostVia(box, bi.z(), isAddPathCost, true, false);
modMinSpacingCostVia(box, bi.z(), isAddPathCost, false, false);
//modMinSpacingCost(net, box, bi.z(), isAddPathCost, false);
modEolSpacingCost(box, bi.z(), isAddPathCost);
obj->getLayer2BBox(box); // assumes enclosure for via is always rectangle
modMinSpacingCostPlaner(net, box, ei.z(), isAddPathCost);
modMinSpacingCostVia(box, ei.z(), isAddPathCost, true, false);
modMinSpacingCostVia(box, ei.z(), isAddPathCost, false, false);
//modMinSpacingCost(net, box, ei.z(), isAddPathCost, false);
modEolSpacingCost(box, ei.z(), isAddPathCost);
//obj->getCutBBox(box);
frTransform xform;
frPoint pt;
obj->getOrigin(pt);
xform.set(pt);
for (auto &uFig: obj->getViaDef()->getCutFigs()) {
//if (uFig->typeId() == frcRect) {
auto rect = static_cast<frRect*>(uFig.get());
rect->getBBox(box);
box.transform(xform);
modCutSpacingCost(box, bi.z(), isAddPathCost);
//}
}
}
}
void FlexDRWorker::mazeIterInit_sortRerouteNets(vector<drNet*> &rerouteNets) {
// sort
sort(rerouteNets.begin(), rerouteNets.end(),
[](drNet* const &a, drNet* const &b) {
frBox boxA, boxB;
a->getPinBox(boxA);
b->getPinBox(boxB);
auto areaA = (boxA.right() - boxA.left()) * (boxA.top() - boxA.bottom());
auto areaB = (boxB.right() - boxB.left()) * (boxB.top() - boxB.bottom());
return (a->getNumPinsIn() == b->getNumPinsIn() ? (areaA == areaB ? a->getId() < b->getId() : areaA < areaB) :
a->getNumPinsIn() < b->getNumPinsIn());
});
}
void FlexDRWorker::mazeIterInit_initDR(vector<drNet*> &rerouteNets) {
for (auto &net: nets) {
rerouteNets.push_back(net.get());
}
mazeIterInit_sortRerouteNets(rerouteNets);
for (auto &net: rerouteNets) {
net->setModified(true);
net->setNumMarkers(0);
// add via access cost when net is not routed
if (RESERVE_VIA_ACCESS) {
initMazeCost_via_helper(net, true);
}
//net->clear();
}
}
// temporary settings to test search and repair
void FlexDRWorker::mazeIterInit_searchRepair(vector<drNet*> &rerouteNets) {
auto &workerRegionQuery = getWorkerRegionQuery();
int cnt = 0;
if (getRipupMode() == 0) {
for (auto &net: nets) {
if (net->isRipup()) {
rerouteNets.push_back(net.get());
}
}
} else if (getRipupMode() == 1) {
for (auto &net: nets) {
rerouteNets.push_back(net.get());
}
}
// change the drNet magical sorting bit here
// to do
//sort(rerouteNets.begin(), rerouteNets.end(),
// [](drNet* const &a, drNet* const &b) {return *a < *b;});
mazeIterInit_sortRerouteNets(rerouteNets);
for (auto &net: rerouteNets) {
net->setModified(true);
net->setNumMarkers(0);
for (auto &uConnFig: net->getRouteConnFigs()) {
subPathCost(uConnFig.get());
workerRegionQuery.remove(uConnFig.get()); // worker region query
cnt++;
}
// add via access cost when net is not routed
if (RESERVE_VIA_ACCESS) {
initMazeCost_via_helper(net, true);
}
net->clear();
}
//cout <<"sr sub " <<cnt <<" connfig costs" <<endl;
}
void FlexDRWorker::mazeIterInit(vector<drNet*> &rerouteNets) {
initMazeCost_marker();
if (isInitDR()) {
mazeIterInit_initDR(rerouteNets);
} else {
mazeIterInit_searchRepair(rerouteNets);
}
}
void FlexDRWorker::mazeNetInit(drNet* net) {
gridGraph.resetStatus();
// sub via access cost when net is about to route
if (RESERVE_VIA_ACCESS) {
initMazeCost_via_helper(net, false);
}
initMazeCost_ap_helper(net, false);
initMazeCost_boundary_helper(net, false);
}
void FlexDRWorker::mazeNetEnd(drNet* net) {
initMazeCost_ap_helper(net, true);
initMazeCost_boundary_helper(net, true);
}
void FlexDRWorker::route_drc() {
DRCWorker drcWorker(getDesign(), fixedObjs);
drcWorker.addDRNets(nets);
using namespace std::chrono;
high_resolution_clock::time_point t0 = high_resolution_clock::now();
drcWorker.init();
high_resolution_clock::time_point t1 = high_resolution_clock::now();
drcWorker.setup();
high_resolution_clock::time_point t2 = high_resolution_clock::now();
drcWorker.main();
setMarkers(drcWorker.getViolations());
high_resolution_clock::time_point t3 = high_resolution_clock::now();
//drcWorker.report();
duration<double> time_span0 = duration_cast<duration<double>>(t1 - t0);
duration<double> time_span1 = duration_cast<duration<double>>(t2 - t1);
duration<double> time_span2 = duration_cast<duration<double>>(t3 - t2);
if (VERBOSE > 1) {
stringstream ss;
ss <<"DRC (INIT/SETUP/MAIN) " <<time_span0.count() <<" "
<<time_span1.count() <<" "
<<time_span2.count() <<" "
<<endl;
ss <<"#viol = " <<markers.size() <<endl;
cout <<ss.str() <<flush;
}
}
void FlexDRWorker::route_postRouteViaSwap() {
auto &workerRegionQuery = getWorkerRegionQuery();
set<FlexMazeIdx> modifiedViaIdx;
frBox box;
vector<drConnFig*> results;
frPoint bp;
FlexMazeIdx bi, ei;
bool flag = false;
for (auto &marker: getMarkers()) {
results.clear();
marker.getBBox(box);
auto lNum = marker.getLayerNum();
workerRegionQuery.query(box, lNum, results);
for (auto &connFig: results) {
if (connFig->typeId() == drcVia) {
auto obj = static_cast<drVia*>(connFig);
obj->getMazeIdx(bi, ei);
auto it = apSVia.find(bi);
if (modifiedViaIdx.find(bi) == modifiedViaIdx.end() && it != apSVia.end()) {
auto ap = it->second;
if (ap->nextAccessViaDef()) {
auto newViaDef = ap->getAccessViaDef();
workerRegionQuery.remove(obj);
obj->setViaDef(newViaDef);
workerRegionQuery.add(obj);
modifiedViaIdx.insert(bi);
flag = true;
}
}
}
}
}
if (flag) {
route_drc();
}
}
void FlexDRWorker::route() {
//bool enableOutput = true;
bool enableOutput = false;
if (enableOutput) {
cout << "start Maze route #nets = " <<nets.size() <<endl;
}
if (isEnableDRC() && getRipupMode() == 0 && getInitNumMarkers() == 0) {
return;
}
if (DRCTEST) {
DRCWorker drcWorker(getDesign(), fixedObjs);
drcWorker.addDRNets(nets);
using namespace std::chrono;
high_resolution_clock::time_point t0 = high_resolution_clock::now();
drcWorker.init();
high_resolution_clock::time_point t1 = high_resolution_clock::now();
drcWorker.setup();
high_resolution_clock::time_point t2 = high_resolution_clock::now();
drcWorker.main();
high_resolution_clock::time_point t3 = high_resolution_clock::now();
drcWorker.report();
duration<double> time_span0 = duration_cast<duration<double>>(t1 - t0);
duration<double> time_span1 = duration_cast<duration<double>>(t2 - t1);
duration<double> time_span2 = duration_cast<duration<double>>(t3 - t2);
stringstream ss;
ss <<"time (INIT/SETUP/MAIN) " <<time_span0.count() <<" "
<<time_span1.count() <<" "
<<time_span2.count() <<" "
<<endl;
cout <<ss.str() <<flush;
} else {
for (int i = 0; i < mazeEndIter; ++i) {
vector<drNet*> rerouteNets;
mazeIterInit(rerouteNets);
minAreaVios.clear();
//if (i == 0) {
// workerDRCCost = DRCCOST;
// workerMarkerCost = MARKERCOST;
//} else {
// workerDRCCost *= 2;
// workerMarkerCost *= 2;
//}
for (auto net: rerouteNets) {
//for (auto &pin: net->getPins()) {
// for (auto &ap: )
mazeNetInit(net);
bool isRouted = routeNet(net);
if (isRouted == false) {
// TODO: output maze area
cout << "Fatal error: Maze Route cannot find path. Connectivity Changed.\n";
if (OUT_MAZE_FILE != string("")) {
gridGraph.print();
}
exit(1);
}
mazeNetEnd(net);
}
// drc worker here
if (isEnableDRC()) {
route_drc();
route_postRouteViaSwap();
}
// save to best drc
if (i == 0 || (isEnableDRC() && getMarkers().size() < getBestMarkers().size())) {
for (auto &net: nets) {
net->setBestRouteConnFigs();
}
setBestMarkers();
}
// quick drc
int violNum = getNumQuickMarkers();
if (VERBOSE > 1) {
cout <<"#quick viol = " <<getNumQuickMarkers() <<endl;
}
if (isEnableDRC() && getMarkers().empty()) {
break;
} else if (violNum == 0) {
break;
}
}
}
}
void FlexDRWorker::routeNet_prep(drNet* net, set<drPin*, frBlockObjectComp> &unConnPins,
map<FlexMazeIdx, set<drPin*, frBlockObjectComp> > &mazeIdx2unConnPins/*,
map<FlexMazeIdx, frViaDef*> &apSVia*/) {
for (auto &pin: net->getPins()) {
unConnPins.insert(pin.get());
for (auto &ap: pin->getAccessPatterns()) {
FlexMazeIdx mi;
ap->getMazeIdx(mi);
mazeIdx2unConnPins[mi].insert(pin.get());
gridGraph.setDst(mi);
}
}
}
void FlexDRWorker::routeNet_setSrc(set<drPin*, frBlockObjectComp> &unConnPins,
map<FlexMazeIdx, set<drPin*, frBlockObjectComp> > &mazeIdx2unConnPins,
vector<FlexMazeIdx> &connComps,
FlexMazeIdx &ccMazeIdx1, FlexMazeIdx &ccMazeIdx2) {
frMIdx xDim, yDim, zDim;
gridGraph.getDim(xDim, yDim, zDim);
ccMazeIdx1.set(xDim - 1, yDim - 1, zDim - 1);
ccMazeIdx2.set(0, 0, 0);
// first pin selection algorithm goes here
// choose the center pin
int totAPCnt = 0;
frCoord totX = 0;
frCoord totY = 0;
frCoord totZ = 0;
FlexMazeIdx mi;
frPoint bp;
for (auto &pin: unConnPins) {
for (auto &ap: pin->getAccessPatterns()) {
ap->getMazeIdx(mi);
ap->getPoint(bp);
totX += bp.x();
totY += bp.y();
totZ += gridGraph.getZHeight(mi.z());
totAPCnt++;
}
}
totX /= totAPCnt;
totY /= totAPCnt;
totZ /= totAPCnt;
frCoord currDist = std::numeric_limits<frCoord>::max();
drPin* currPin = nullptr;
for (auto &pin: unConnPins) {
for (auto &ap: pin->getAccessPatterns()) {
ap->getMazeIdx(mi);
ap->getPoint(bp);
frCoord dist = abs(totX - bp.x()) + abs(totY - bp.y()) + abs(totZ - gridGraph.getZHeight(mi.z()));
if (dist < currDist) {
currDist = dist;
currPin = pin;
}
}
}
unConnPins.erase(currPin);
//auto currPin = *(unConnPins.begin());
//unConnPins.erase(unConnPins.begin());
// first pin selection algorithm ends here
for (auto &ap: currPin->getAccessPatterns()) {
ap->getMazeIdx(mi);
connComps.push_back(mi);
ccMazeIdx1.set(min(ccMazeIdx1.x(), mi.x()),
min(ccMazeIdx1.y(), mi.y()),
min(ccMazeIdx1.z(), mi.z()));
ccMazeIdx2.set(max(ccMazeIdx2.x(), mi.x()),
max(ccMazeIdx2.y(), mi.y()),
max(ccMazeIdx2.z(), mi.z()));
auto it = mazeIdx2unConnPins.find(mi);
if (it == mazeIdx2unConnPins.end()) {
continue;
}
auto it2 = it->second.find(currPin);
if (it2 == it->second.end()) {
continue;
}
it->second.erase(it2);
gridGraph.setSrc(mi);
// remove dst label only when no other pins share the same loc
if (it->second.empty()) {
mazeIdx2unConnPins.erase(it);
gridGraph.resetDst(mi);
}
}
}
drPin* FlexDRWorker::routeNet_getNextDst(FlexMazeIdx &ccMazeIdx1, FlexMazeIdx &ccMazeIdx2,
map<FlexMazeIdx, set<drPin*, frBlockObjectComp> > &mazeIdx2unConnPins) {
frPoint pt;
frPoint ll, ur;
gridGraph.getPoint(ll, ccMazeIdx1.x(), ccMazeIdx1.y());
gridGraph.getPoint(ur, ccMazeIdx2.x(), ccMazeIdx2.y());
frCoord currDist = std::numeric_limits<frCoord>::max();
drPin* nextDst = nullptr;
for (auto &[mazeIdx, setS]: mazeIdx2unConnPins) {
gridGraph.getPoint(pt, mazeIdx.x(), mazeIdx.y());
frCoord dx = max(max(ll.x() - pt.x(), pt.x() - ur.x()), 0);
frCoord dy = max(max(ll.y() - pt.y(), pt.y() - ur.y()), 0);
frCoord dz = max(max(gridGraph.getZHeight(ccMazeIdx1.z()) - gridGraph.getZHeight(mazeIdx.z()),
gridGraph.getZHeight(mazeIdx.z()) - gridGraph.getZHeight(ccMazeIdx2.z())), 0);
if (dx + dy + dz < currDist) {
currDist = dx + dy + dz;
nextDst = *(setS.begin());
}
if (currDist == 0) {
break;
}
}
return nextDst;
}
void FlexDRWorker::mazePinInit() {
gridGraph.resetPrevNodeDir();
}
void FlexDRWorker::routeNet_postAstarUpdate(vector<FlexMazeIdx> &path, vector<FlexMazeIdx> &connComps,
set<drPin*, frBlockObjectComp> &unConnPins,
map<FlexMazeIdx, set<drPin*, frBlockObjectComp> > &mazeIdx2unConnPins,
bool isFirstConn) {
// first point is dst
set<FlexMazeIdx> localConnComps;
if (!path.empty()) {
auto mi = path[0];
vector<drPin*> tmpPins;
for (auto pin: mazeIdx2unConnPins[mi]) {
//unConnPins.erase(pin);
tmpPins.push_back(pin);
}
for (auto pin: tmpPins) {
unConnPins.erase(pin);
for (auto &ap: pin->getAccessPatterns()) {
FlexMazeIdx mi;
ap->getMazeIdx(mi);
auto it = mazeIdx2unConnPins.find(mi);
if (it == mazeIdx2unConnPins.end()) {
continue;
}
auto it2 = it->second.find(pin);
if (it2 == it->second.end()) {
continue;
}
it->second.erase(it2);
if (it->second.empty()) {
mazeIdx2unConnPins.erase(it);
gridGraph.resetDst(mi);
}
if (ALLOW_PIN_AS_FEEDTHROUGH) {
localConnComps.insert(mi);
gridGraph.setSrc(mi);
}
}
}
} else {
cout <<"Error: routeNet_postAstarUpdate path is empty" <<endl;
}
// must be before comment line ABC so that the used actual src is set in gridgraph
if (isFirstConn && (!ALLOW_PIN_AS_FEEDTHROUGH)) {
for (auto &mi: connComps) {
gridGraph.resetSrc(mi);
}
connComps.clear();
if ((int)path.size() == 1) {
connComps.push_back(path[0]);
gridGraph.setSrc(path[0]);
}
}
// line ABC
// must have >0 length
for (int i = 0; i < (int)path.size() - 1; ++i) {
auto start = path[i];
auto end = path[i + 1];
auto startX = start.x(), startY = start.y(), startZ = start.z();
auto endX = end.x(), endY = end.y(), endZ = end.z();
// horizontal wire
if (startX != endX && startY == endY && startZ == endZ) {
for (auto currX = std::min(startX, endX); currX <= std::max(startX, endX); ++currX) {
localConnComps.insert(FlexMazeIdx(currX, startY, startZ));
gridGraph.setSrc(currX, startY, startZ);
//gridGraph.resetDst(currX, startY, startZ);
}
// vertical wire
} else if (startX == endX && startY != endY && startZ == endZ) {
for (auto currY = std::min(startY, endY); currY <= std::max(startY, endY); ++currY) {
localConnComps.insert(FlexMazeIdx(startX, currY, startZ));
gridGraph.setSrc(startX, currY, startZ);
//gridGraph.resetDst(startX, currY, startZ);
}
// via
} else if (startX == endX && startY == endY && startZ != endZ) {
for (auto currZ = std::min(startZ, endZ); currZ <= std::max(startZ, endZ); ++currZ) {
localConnComps.insert(FlexMazeIdx(startX, startY, currZ));
gridGraph.setSrc(startX, startY, currZ);
//gridGraph.resetDst(startX, startY, currZ);
}
// zero length
} else if (startX == endX && startY == endY && startZ == endZ) {
//root.addPinGrid(startX, startY, startZ);
std::cout << "Warning: zero-length path in updateFlexPin\n";
} else {
std::cout << "Error: non-colinear path in updateFlexPin\n";
}
}
for (auto &mi: localConnComps) {
if (isFirstConn && !ALLOW_PIN_AS_FEEDTHROUGH) {
connComps.push_back(mi);
} else {
if (!(mi == *(path.cbegin()))) {
connComps.push_back(mi);
}
}
}
}
void FlexDRWorker::routeNet_postAstarWritePath(drNet* net, vector<FlexMazeIdx> &points/*,
const map<FlexMazeIdx, frViaDef*> &apSVia*/) {
//bool enableOutput = true;
bool enableOutput = false;
if (points.empty()) {
if (enableOutput) {
std::cout << "Warning: path is empty in writeMazePath\n";
}
return;
}
if (TEST && points.size()) {
cout <<"path";
for (auto &mIdx: points) {
cout <<" (" <<mIdx.x() <<", " <<mIdx.y() <<", " <<mIdx.z() <<")";
}
cout <<endl;
}
auto &workerRegionQuery = getWorkerRegionQuery();
for (int i = 0; i < (int)points.size() - 1; ++i) {
FlexMazeIdx start, end;
if (points[i + 1] < points[i]) {
start = points[i + 1];
end = points[i];
} else {
start = points[i];
end = points[i + 1];
}
auto startX = start.x(), startY = start.y(), startZ = start.z();
auto endX = end.x(), endY = end.y(), endZ = end.z();
// horizontal wire
if (startX != endX && startY == endY && startZ == endZ) {
frPoint startLoc, endLoc;
frLayerNum currLayerNum = gridGraph.getLayerNum(startZ);
gridGraph.getPoint(startLoc, startX, startY);
gridGraph.getPoint(endLoc, endX, endY);
auto currPathSeg = make_unique<drPathSeg>();
currPathSeg->setPoints(startLoc, endLoc);
currPathSeg->setLayerNum(currLayerNum);
currPathSeg->addToNet(net);
currPathSeg->setStyle(getTech()->getLayer(currLayerNum)->getDefaultSegStyle());
currPathSeg->setMazeIdx(start, end);
unique_ptr<drConnFig> tmp(std::move(currPathSeg));
workerRegionQuery.add(tmp.get());
net->addRoute(tmp);
// quick drc cnt
bool prevHasCost = false;
for (int i = startX; i < endX; i++) {
if (gridGraph.hasDRCCost(i, startY, startZ, frDirEnum::E)) {
if (!prevHasCost) {
net->addMarker();
prevHasCost = true;
}
if (TEST) {
cout <<" pass marker @(" <<i <<", " <<startY <<", " <<startZ <<") E" <<endl;
}
} else {
prevHasCost = false;
}
}
if (enableOutput) {
cout <<" write horz pathseg ("
<<startLoc.x() * 1.0 / getDesign()->getTopBlock()->getDBUPerUU() <<", "
<<startLoc.y() * 1.0 / getDesign()->getTopBlock()->getDBUPerUU() <<") ("
<<endLoc.x() * 1.0 / getDesign()->getTopBlock()->getDBUPerUU() <<", "
<<endLoc.y() * 1.0 / getDesign()->getTopBlock()->getDBUPerUU() <<") "
<<getTech()->getLayer(currLayerNum)->getName() <<endl;
}
// vertical wire
} else if (startX == endX && startY != endY && startZ == endZ) {
frPoint startLoc, endLoc;
frLayerNum currLayerNum = gridGraph.getLayerNum(startZ);
gridGraph.getPoint(startLoc, startX, startY);
gridGraph.getPoint(endLoc, endX, endY);
auto currPathSeg = make_unique<drPathSeg>();
currPathSeg->setPoints(startLoc, endLoc);
currPathSeg->setLayerNum(currLayerNum);
currPathSeg->addToNet(net);
currPathSeg->setStyle(getTech()->getLayer(currLayerNum)->getDefaultSegStyle());
currPathSeg->setMazeIdx(start, end);
unique_ptr<drConnFig> tmp(std::move(currPathSeg));
workerRegionQuery.add(tmp.get());
net->addRoute(tmp);
// quick drc cnt
bool prevHasCost = false;
for (int i = startY; i < endY; i++) {
if (gridGraph.hasDRCCost(startX, i, startZ, frDirEnum::E)) {
if (!prevHasCost) {
net->addMarker();
prevHasCost = true;
}
if (TEST) {
cout <<" pass marker @(" <<startX <<", " <<i <<", " <<startZ <<") N" <<endl;
}
} else {
prevHasCost = false;
}
}
if (enableOutput) {
cout <<" write vert pathseg ("
<<startLoc.x() * 1.0 / getDesign()->getTopBlock()->getDBUPerUU() <<", "
<<startLoc.y() * 1.0 / getDesign()->getTopBlock()->getDBUPerUU() <<") ("
<<endLoc.x() * 1.0 / getDesign()->getTopBlock()->getDBUPerUU() <<", "
<<endLoc.y() * 1.0 / getDesign()->getTopBlock()->getDBUPerUU() <<") "
<<getTech()->getLayer(currLayerNum)->getName() <<endl;
}
// via
} else if (startX == endX && startY == endY && startZ != endZ) {
for (auto currZ = startZ; currZ < endZ; ++currZ) {
frPoint loc;
frLayerNum startLayerNum = gridGraph.getLayerNum(currZ);
//frLayerNum endLayerNum = gridGraph.getLayerNum(currZ + 1);
gridGraph.getPoint(loc, startX, startY);
FlexMazeIdx mi(startX, startY, currZ);
auto cutLayerDefaultVia = getTech()->getLayer(startLayerNum + 1)->getDefaultViaDef();
if (gridGraph.isSVia(startX, startY, currZ)) {
cutLayerDefaultVia = apSVia.find(mi)->second->getAccessViaDef();
}
auto currVia = make_unique<drVia>(cutLayerDefaultVia);
currVia->setOrigin(loc);
currVia->setMazeIdx(FlexMazeIdx(startX, startY, currZ), FlexMazeIdx(startX, startY, currZ+1));
unique_ptr<drConnFig> tmp(std::move(currVia));
workerRegionQuery.add(tmp.get());
net->addRoute(tmp);
if (gridGraph.hasDRCCost(startX, startY, currZ, frDirEnum::U)) {
net->addMarker();
if (TEST) {
cout <<" pass marker @(" <<startX <<", " <<startY <<", " <<currZ <<") U" <<endl;
}
}
if (enableOutput) {
cout <<" write via ("
<<loc.x() * 1.0 / getDesign()->getTopBlock()->getDBUPerUU() <<", "
<<loc.y() * 1.0 / getDesign()->getTopBlock()->getDBUPerUU() <<") "
<<cutLayerDefaultVia->getName() <<endl;
}
}
// zero length
} else if (startX == endX && startY == endY && startZ == endZ) {
std::cout << "Warning: zero-length path in updateFlexPin\n";
} else {
std::cout << "Error: non-colinear path in updateFlexPin\n";
}
}
}
void FlexDRWorker::routeNet_postRouteAddPathCost(drNet* net) {
int cnt = 0;
for (auto &connFig: net->getRouteConnFigs()) {
addPathCost(connFig.get());
cnt++;
}
//cout <<"updated " <<cnt <<" connfig costs" <<endl;
}
bool FlexDRWorker::routeNet(drNet* net) {
if (net->getPins().size() <= 1) {
return true;
}
if (TEST) {
cout <<"route " <<net->getFrNet()->getName() <<endl;
}
set<drPin*, frBlockObjectComp> unConnPins;
map<FlexMazeIdx, set<drPin*, frBlockObjectComp> > mazeIdx2unConnPins;
//map<FlexMazeIdx, frViaDef*> apSVia;
routeNet_prep(net, unConnPins, mazeIdx2unConnPins/*, apSVia*/);
FlexMazeIdx ccMazeIdx1, ccMazeIdx2; // connComps ll, ur flexmazeidx
vector<FlexMazeIdx> connComps;
routeNet_setSrc(unConnPins, mazeIdx2unConnPins, connComps, ccMazeIdx1, ccMazeIdx2);
vector<FlexMazeIdx> path; // astar must return with >= 1 idx
bool isFirstConn = true;
while(!unConnPins.empty()) {
mazePinInit();
auto nextPin = routeNet_getNextDst(ccMazeIdx1, ccMazeIdx2, mazeIdx2unConnPins);
path.clear();
if (gridGraph.search(connComps, nextPin, path, ccMazeIdx1, ccMazeIdx2)) {
routeNet_postAstarUpdate(path, connComps, unConnPins, mazeIdx2unConnPins, isFirstConn);
routeNet_postAstarWritePath(net, path/*, apSVia*/);
routeNet_postAstarPatchMinAreaVio(net, path);
isFirstConn = false;
}
}
routeNet_postRouteAddPathCost(net);
return true;
}
void FlexDRWorker::routeNet_postAstarPatchMinAreaVio(drNet* net, const vector<FlexMazeIdx> &path) {
if (path.empty()) {
return;
}
// get path with separated (stacked vias)
vector<FlexMazeIdx> points;
for (int i = 0; i < (int)path.size() - 1; ++i) {
auto currIdx = path[i];
auto nextIdx = path[i+1];
if (currIdx.z() == nextIdx.z()) {
points.push_back(currIdx);
} else {
if (currIdx.z() < nextIdx.z()) {
for (auto z = currIdx.z(); z < nextIdx.z(); ++z) {
FlexMazeIdx tmpIdx(currIdx.x(), currIdx.y(), z);
points.push_back(tmpIdx);
}
} else {
for (auto z = currIdx.z(); z > nextIdx.z(); --z) {
FlexMazeIdx tmpIdx(currIdx.x(), currIdx.y(), z);
points.push_back(tmpIdx);
}
}
}
}
points.push_back(path.back());
auto layerNum = gridGraph.getLayerNum(points.front().z());
auto minAreaConstraint = getDesign()->getTech()->getLayer(layerNum)->getAreaConstraint();
frCoord currArea = (minAreaConstraint) ? minAreaConstraint->getMinArea() : 0;
frCoord startViaHalfEncArea = 0, endViaHalfEncArea = 0;
FlexMazeIdx prevIdx = points[0], currIdx;
for (int i = 1; i < (int)points.size(); ++i) {
currIdx = points[i];
// check minAreaViolation when change layer
if (currIdx.z() != prevIdx.z()) {
auto layerNum = gridGraph.getLayerNum(prevIdx.z());
auto minAreaConstraint = getDesign()->getTech()->getLayer(layerNum)->getAreaConstraint();
frCoord reqArea = (minAreaConstraint) ? minAreaConstraint->getMinArea() : 0;
// add next via enclosure
if (currIdx.z() < prevIdx.z()) {
currArea += gridGraph.getHalfViaEncArea(prevIdx.z() - 1, false);
endViaHalfEncArea = gridGraph.getHalfViaEncArea(prevIdx.z() - 1, false);
} else {
currArea += gridGraph.getHalfViaEncArea(prevIdx.z(), true);
endViaHalfEncArea = gridGraph.getHalfViaEncArea(prevIdx.z(), true);
}
// push to minArea violation
if (currArea < reqArea) {
FlexMazeIdx bp, ep;
frCoord gapArea = reqArea - (currArea - startViaHalfEncArea - endViaHalfEncArea) - std::min(startViaHalfEncArea, endViaHalfEncArea);
// bp = std::min(prevIdx, currIdx);
// ep = std::max(prevIdx, currIdx);
if (points[i-1].z() == points[i-2].z()) {
bp = std::min(points[i-1], points[i-2]);
ep = std::max(points[i-1], points[i-2]);
} else {
bp = points[i-1];
ep = points[i-1];
}
auto patchWidth = getDesign()->getTech()->getLayer(layerNum)->getWidth();
// FlexDRMinAreaVio minAreaVio(net, bp, ep, reqArea - (currArea - startViaHalfEncArea) - std::min(startViaHalfEncArea, endViaHalfEncArea));
// minAreaVios.push_back(minAreaVio);
routeNet_postAstarAddPatchMetal(net, bp, ep, gapArea, patchWidth);
}
// init for next path
if (currIdx.z() < prevIdx.z()) {
currArea = gridGraph.getHalfViaEncArea(prevIdx.z() - 1, true);
startViaHalfEncArea = gridGraph.getHalfViaEncArea(prevIdx.z() - 1, true);
} else {
currArea = gridGraph.getHalfViaEncArea(prevIdx.z(), false);
startViaHalfEncArea = gridGraph.getHalfViaEncArea(prevIdx.z(), false);
}
}
// add the wire area
else {
auto layerNum = gridGraph.getLayerNum(prevIdx.z());
auto pathWidth = getDesign()->getTech()->getLayer(layerNum)->getWidth();
frPoint bp, ep;
gridGraph.getPoint(bp, prevIdx.x(), prevIdx.y());
gridGraph.getPoint(ep, currIdx.x(), currIdx.y());
frCoord pathLength = abs(bp.x() - ep.x()) + abs(bp.y() - ep.y());
currArea += pathLength * pathWidth;
}
prevIdx = currIdx;
}
}
// void FlexDRWorker::routeNet_postRouteAddPatchMetalCost(drNet* net) {
// for (auto &patch: net->getRoutePatchConnFigs()) {
// addPathCost(patch.get());
// }
// }
void FlexDRWorker::routeNet_postAstarAddPatchMetal(drNet* net,
const FlexMazeIdx bpIdx,
const FlexMazeIdx epIdx,
const frCoord gapArea,
const frCoord patchWidth) {
bool isPatchHorz;
bool isLeftClean = true;
frLayerNum layerNum = gridGraph.getLayerNum(bpIdx.z());
frCoord patchLength = gapArea / patchWidth;
if (gapArea % patchWidth != 0) {
++patchLength;
}
frPoint origin;
auto &workerRegionQuery = getWorkerRegionQuery();
// stacked via
if (bpIdx.x() == epIdx.x() && bpIdx.y() == epIdx.y()) {
if (getDesign()->getTech()->getLayer(layerNum)->getDir() == frcHorzPrefRoutingDir) {
isPatchHorz = true;
} else {
isPatchHorz = false;
}
}
// vertical patch
else if (bpIdx.x() == epIdx.x()) {
isPatchHorz = false;
}
// horizontal patch
else {
isPatchHorz = true;
}
// try bottom / left option
if (isPatchHorz) {
gridGraph.getPoint(origin, bpIdx.x(), bpIdx.y());
frPoint patchEnd(origin.x() - patchLength, origin.y());
if (!getRouteBox().contains(patchEnd)) {
isLeftClean = false;
} else {
frPoint patchLL(origin.x() - patchLength, origin.y() - patchWidth / 2);
frPoint patchUR(origin.x(), origin.y() + patchWidth / 2);
FlexMazeIdx startIdx, endIdx;
gridGraph.getMazeIdx(startIdx, patchLL, layerNum);
gridGraph.getMazeIdx(endIdx, patchUR, layerNum);
for (auto xIdx = startIdx.x(); xIdx < endIdx.x(); ++xIdx) {
for (auto yIdx = startIdx.y(); yIdx < endIdx.y(); ++yIdx) {
if (gridGraph.hasDRCCost(xIdx, yIdx, bpIdx.z(), frDirEnum::E) ||
gridGraph.hasDRCCost(xIdx, yIdx, bpIdx.z(), frDirEnum::N)) {
isLeftClean = false;
break;
}
}
}
}
// add patch if clean
if (isLeftClean) {
frPoint patchLL(origin.x() - patchLength, origin.y() - patchWidth / 2);
frPoint patchUR(origin.x(), origin.y() + patchWidth / 2);
auto tmpPatch = make_unique<drPatchWire>();
tmpPatch->setLayerNum(layerNum);
tmpPatch->setOrigin(origin);
// tmpPatch->setBBox(frBox(patchLL, patchUR));
tmpPatch->setOffsetBox(frBox(-patchLength, -patchWidth / 2, 0, patchWidth / 2));
tmpPatch->addToNet(net);
unique_ptr<drConnFig> tmp(std::move(tmpPatch));
workerRegionQuery.add(tmp.get());
net->addRoute(tmp);
}
} else {
gridGraph.getPoint(origin, bpIdx.x(), bpIdx.y());
frPoint patchEnd(origin.x(), origin.y() - patchLength);
if (!getRouteBox().contains(patchEnd)) {
isLeftClean = false;
} else {
frPoint patchLL(origin.x() - patchWidth / 2, origin.y() - patchLength);
frPoint patchUR(origin.x() + patchWidth / 2, origin.y());
FlexMazeIdx startIdx, endIdx;
gridGraph.getMazeIdx(startIdx, patchLL, layerNum);
gridGraph.getMazeIdx(endIdx, patchUR, layerNum);
for (auto xIdx = startIdx.x(); xIdx < endIdx.x(); ++xIdx) {
for (auto yIdx = startIdx.y(); yIdx < endIdx.y(); ++yIdx) {
if (gridGraph.hasDRCCost(xIdx, yIdx, bpIdx.z(), frDirEnum::E) ||
gridGraph.hasDRCCost(xIdx, yIdx, bpIdx.z(), frDirEnum::N)) {
isLeftClean = false;
break;
}
}
}
}
// add patch if clean
if (isLeftClean) {
frPoint patchLL(origin.x() - patchWidth / 2, origin.y() - patchLength);
frPoint patchUR(origin.x() + patchWidth / 2, origin.y());
auto tmpPatch = make_unique<drPatchWire>();
tmpPatch->setLayerNum(layerNum);
tmpPatch->setOrigin(origin);
// tmpPatch->setBBox(frBox(patchLL, patchUR));
tmpPatch->setOffsetBox(frBox(-patchWidth / 2, -patchLength, patchWidth / 2, 0));
tmpPatch->addToNet(net);
unique_ptr<drConnFig> tmp(std::move(tmpPatch));
workerRegionQuery.add(tmp.get());
net->addRoute(tmp);
}
}
// use top / right option if bottom / left is not usable
if (!isLeftClean) {
gridGraph.getPoint(origin, epIdx.x(), epIdx.y());
if (isPatchHorz) {
frPoint patchLL(origin.x(), origin.y() - patchWidth / 2);
frPoint patchUR(origin.x() + patchLength, origin.y() + patchWidth / 2);
auto tmpPatch = make_unique<drPatchWire>();
tmpPatch->setLayerNum(layerNum);
tmpPatch->setOrigin(origin);
// tmpPatch->setBBox(frBox(patchLL, patchUR));
tmpPatch->setOffsetBox(frBox(0, -patchWidth / 2, patchLength, patchWidth / 2));
tmpPatch->addToNet(net);
unique_ptr<drConnFig> tmp(std::move(tmpPatch));
workerRegionQuery.add(tmp.get());
net->addRoute(tmp);
} else {
frPoint patchLL(origin.x() - patchWidth / 2, origin.y());
frPoint patchUR(origin.x() + patchWidth / 2, origin.y() + patchLength);
auto tmpPatch = make_unique<drPatchWire>();
tmpPatch->setLayerNum(layerNum);
tmpPatch->setOrigin(origin);
// tmpPatch->setBBox(frBox(patchLL, patchUR));
tmpPatch->setOffsetBox(frBox(-patchWidth / 2, 0, patchWidth / 2, patchLength));
tmpPatch->addToNet(net);
unique_ptr<drConnFig> tmp(std::move(tmpPatch));
workerRegionQuery.add(tmp.get());
net->addRoute(tmp);
}
}
}
| 37.942013 | 154 | 0.587084 | [
"vector",
"transform"
] |
2912dd1180ccf161e6ff9d609ff9409aff4b4cb3 | 486 | cpp | C++ | January Challenges/Day21-Find the Most Competitive Subsequence.cpp | kaushalk844/leetcode | c9497a1cf36e4d7f84161cf8d12e2cfc4a6b937d | [
"MIT"
] | null | null | null | January Challenges/Day21-Find the Most Competitive Subsequence.cpp | kaushalk844/leetcode | c9497a1cf36e4d7f84161cf8d12e2cfc4a6b937d | [
"MIT"
] | null | null | null | January Challenges/Day21-Find the Most Competitive Subsequence.cpp | kaushalk844/leetcode | c9497a1cf36e4d7f84161cf8d12e2cfc4a6b937d | [
"MIT"
] | null | null | null | class Solution {
public:
vector<int> mostCompetitive(vector<int>& nums, int k) {
vector<int> ans;
int rem = nums.size()-k;
for(auto a:nums){
while(ans.size() && rem && a<ans.back()){
ans.pop_back();
rem--;
}
ans.push_back(a);
}
while(rem){
ans.pop_back();
rem--;
}
return ans; //
}
};
| 19.44 | 59 | 0.37037 | [
"vector"
] |
291d0dd77fad4b7ffbf7410965e515ea108dd057 | 14,255 | hpp | C++ | external/jigsaw/src/marche.hpp | crohr88/jigsaw-matlab | 372b960d33ac135dc12574a34107848146d43c6e | [
"Unlicense"
] | null | null | null | external/jigsaw/src/marche.hpp | crohr88/jigsaw-matlab | 372b960d33ac135dc12574a34107848146d43c6e | [
"Unlicense"
] | null | null | null | external/jigsaw/src/marche.hpp | crohr88/jigsaw-matlab | 372b960d33ac135dc12574a34107848146d43c6e | [
"Unlicense"
] | null | null | null |
/*
--------------------------------------------------------
*
* ,o, ,o, /
* ` ` e88~88e d88~\ /~~~8e Y88b e /
* 888 888 88 88 C888 88b Y88b d8b /
* 888 888 "8b_d8" Y88b e88~-888 Y888/Y88b/
* 888 888 / 888D C88 888 Y8/ Y8/
* 88P 888 Cb \_88P "8b_-888 Y Y
* \_8" Y8""8D
*
--------------------------------------------------------
* MARCHE: "fast-marching" eikonal equation solver.
--------------------------------------------------------
*
* Last updated: 01 March, 2020
*
* Copyright 2013 -- 2020
* Darren Engwirda
* d.engwirda@gmail.com
* https://github.com/dengwirda
*
--------------------------------------------------------
*
* This program may be freely redistributed under the
* condition that the copyright notices (including this
* entire header) are not removed, and no compensation
* is received through use of the software. Private,
* research, and institutional use is free. You may
* distribute modified versions of this code UNDER THE
* CONDITION THAT THIS CODE AND ANY MODIFICATIONS MADE
* TO IT IN THE SAME FILE REMAIN UNDER COPYRIGHT OF THE
* ORIGINAL AUTHOR, BOTH SOURCE AND OBJECT CODE ARE
* MADE FREELY AVAILABLE WITHOUT CHARGE, AND CLEAR
* NOTICE IS GIVEN OF THE MODIFICATIONS. Distribution
* of this code as part of a commercial system is
* permissible ONLY BY DIRECT ARRANGEMENT WITH THE
* AUTHOR. (If you are not directly supplying this
* code to a customer, and you are instead telling them
* how they can obtain it for free, then you are not
* required to make any arrangement with me.)
*
* Disclaimer: Neither I nor: Columbia University, The
* Massachusetts Institute of Technology, The
* University of Sydney, nor the National Aeronautics
* and Space Administration warrant this code in any
* way whatsoever. This code is provided "as-is" to be
* used at your own risk.
*
--------------------------------------------------------
*/
namespace MARCHE {
std::string asciibanner =
" \n"
"#------------------------------------------------------------\n"
"#\n"
"# ,o, ,o, / \n"
"# ` ` e88~88e d88~\\ /~~~8e Y88b e / \n"
"# 888 888 88 88 C888 88b Y88b d8b / \n"
"# 888 888 \"8b_d8\" Y88b e88~-888 Y888/Y88b/ \n"
"# 888 888 / 888D C88 888 Y8/ Y8/ \n"
"# 88P 888 Cb \\_88P \"8b_-888 Y Y \n"
"# \\_8\" Y8\"\"8D \n"
"#\n"
"#------------------------------------------------------------\n"
"# MARCHE: \"fast-marching\" eikonal equation solver. \n"
"#------------------------------------------------------------\n"
" \n"
" " __JGSWVSTR "\n\n" ;
}
# ifdef __lib_jigsaw
# include "liblib/init_jig_t.hpp"
# include "liblib/init_msh_t.hpp"
# include "liblib/load_jig_t.hpp"
# include "liblib/load_msh_t.hpp"
# include "liblib/save_jig_t.hpp"
# include "liblib/save_msh_t.hpp"
__normal_call iptr_type marche ( // lib-jigsaw
jigsaw_jig_t *_jjig ,
jigsaw_msh_t *_fmsh
)
{
iptr_type _retv = +0;
__unreferenced(_fmsh) ;
hfun_data _ffun ; // FUNC data
jcfg_data _jcfg ;
# ifdef __use_timers
typename std ::chrono::
high_resolution_clock::
time_point _ttic ;
typename std ::chrono::
high_resolution_clock::
time_point _ttoc ;
typename std ::chrono::
high_resolution_clock _time;
__unreferenced(_time) ;
# endif//__use_timers
/*--------------------------------- init. geo. kernel */
mp_float::exactinit() ;
/*--------------------------------- setup *.JLOG data */
if (_jjig != nullptr )
{
_jcfg._verbosity = _jjig->_verbosity ;
}
jlog_null _jlog(_jcfg) ;
_jlog.push(MARCHE::
asciibanner) ;
/*--------------------------------- parse *.JCFG data */
if (_jjig != nullptr )
{
_jlog.push (
" Reading CFG. data...\n\n" ) ;
# ifdef __use_timers
_ttic = _time.now();
# endif//__use_timers
if ((_retv = copy_jcfg (
_jcfg,
_jlog,*_jjig)) != __no_error)
{
return _retv ;
}
if ((_retv = test_jcfg (
_jcfg, _jlog)) != __no_error)
{
return _retv ;
}
_jlog.push (
" CFG. data summary...\n\n" ) ;
if ((_retv = echo_jcfg (
_jcfg, _jlog)) != __no_error)
{
return _retv ;
}
# ifdef __use_timers
_ttoc = _time.now();
_jlog.push(dump_time(_ttic, _ttoc));
# endif//__use_timers
}
if (_fmsh != nullptr )
{
/*--------------------------------- parse *.HFUN data */
_jlog.push ( __jloglndv "\n" ) ;
_jlog.push (
" Reading FFUN data...\n\n" ) ;
# ifdef __use_timers
_ttic = _time.now();
# endif//__use_timers
if ((_retv = copy_hfun (
_jcfg, _jlog ,
_ffun,*_fmsh)) != __no_error)
{
return _retv ;
}
if ((_retv = test_hfun (
_jcfg,
_jlog, _ffun)) != __no_error)
{
return _retv ;
}
# ifdef __use_timers
_ttoc = _time.now();
_jlog.push(dump_time(_ttic, _ttoc));
# endif//__use_timers
}
if (_fmsh != nullptr )
{
/*--------------------------------- assemble size-fun */
_jlog.push ( __jloglndv "\n" ) ;
_jlog.push (
" Forming FFUN data...\n\n" ) ;
# ifdef __use_timers
_ttic = _time.now();
# endif//__use_timers
_ffun.init_hfun(_jcfg, true) ;
if (_jcfg._verbosity > 0 )
{
_jlog.push (
" FFUN data summary...\n\n" ) ;
if ((_retv = echo_hfun (
_jcfg,
_jlog, _ffun)) != __no_error)
{
return _retv ;
}
}
# ifdef __use_timers
_ttoc = _time.now();
_jlog.push(dump_time(_ttic, _ttoc));
# endif//__use_timers
}
if (_fmsh != nullptr )
{
/*--------------------------------- call h-jac solver */
_jlog.push ( __jloglndv "\n" ) ;
_jlog.push (
" Fast-march solver...\n\n" ) ;
# ifdef __use_timers
_ttic = _time.now();
# endif//__use_timers
_ffun.clip_hfun(_jcfg) ;
# ifdef __use_timers
_ttoc = _time.now();
_jlog.push(dump_time(_ttic, _ttoc));
# endif//__use_timers
}
if (_fmsh != nullptr )
{
/*--------------------------------- dump mesh to file */
_jlog.push ( __jloglndv "\n" ) ;
_jlog.push (
" Writing FFUN data...\n\n" ) ;
# ifdef __use_timers
_ttic = _time.now();
# endif//__use_timers
if ((_retv = save_hfun (
_jcfg, _jlog,
_ffun,*_fmsh)) != __no_error)
{
return _retv ;
}
# ifdef __use_timers
_ttoc = _time.now();
_jlog.push(dump_time(_ttic, _ttoc));
# endif//__use_timers
}
/*-------------------------- success, if we got here! */
return ( _retv ) ;
}
# else
# if defined(__cmd_marche)
__normal_call iptr_type main ( // cmd-marche
int _argc ,
char **_argv
)
{
hfun_data _ffun ; // FUNC data
# ifdef __use_timers
typename std ::chrono::
high_resolution_clock::
time_point _ttic ;
typename std ::chrono::
high_resolution_clock::
time_point _ttoc ;
typename std ::chrono::
high_resolution_clock _time;
__unreferenced(_time) ;
# endif//__use_timers
/*--------------------------------- init. geo. kernel */
mp_float::exactinit() ;
/*-------------------------- find *.JFCG file in args */
iptr_type _retv = -1 ;
jcfg_data _jcfg ;
for (; _argc-- != +0; )
{
std::string _ssrc(_argv[_argc]) ;
if (_ssrc.find("-h") == 0 ||
_ssrc.find(
"--help") == 0 )
{
_retv = -2 ;
std::cout <<
"run marche jigname.jig";
std::cout << std::endl ;
break ;
}
if (_ssrc.find("-v") == 0 ||
_ssrc.find(
"--version") == 0 ||
_ssrc.find(
"-whoami") == 0 )
{
_retv = -2 ;
std::cout << __JGSWVSTR ;
std::cout << std::endl ;
break ;
}
std::string _path , _name , _fext ;
file_part ( _ssrc ,
_path , _name , _fext ) ;
if (_fext.find("jig") == 0)
{
_retv = +0 ;
_jcfg._jcfg_file =_ssrc ;
_jcfg._file_path =_path ;
_jcfg._file_name =_name ;
break ;
}
}
if (_retv != +0) return ( _retv ) ;
/*--------------------------------- setup *.JLOG file */
jlog_text _jlog(_jcfg) ;
_jlog.push(MARCHE::
asciibanner) ;
if(!_jcfg._jcfg_file.empty())
{
/*--------------------------------- parse *.JCFG file */
_jlog.push (
" Reading CFG. file...\n\n" ) ;
# ifdef __use_timers
_ttic = _time.now();
# endif//__use_timers
if ((_retv = read_jcfg (
_jcfg, _jlog)) != __no_error)
{
return _retv ;
}
if ((_retv = test_jcfg (
_jcfg, _jlog)) != __no_error)
{
return _retv ;
}
_jlog.push (
" CFG. data summary...\n\n" ) ;
if ((_retv = echo_jcfg (
_jcfg, _jlog)) != __no_error)
{
return _retv ;
}
# ifdef __use_timers
_ttoc = _time.now();
_jlog.push(dump_time(_ttic, _ttoc));
# endif//__use_timers
}
if(!_jcfg._hfun_file.empty())
{
/*--------------------------------- parse *.HFUN file */
_jlog.push ( __jloglndv "\n" ) ;
_jlog.push (
" Reading FFUN file...\n\n" ) ;
# ifdef __use_timers
_ttic = _time.now();
# endif//__use_timers
if ((_retv = read_hfun (
_jcfg,
_jlog, _ffun)) != __no_error)
{
return _retv ;
}
if ((_retv = test_hfun (
_jcfg,
_jlog, _ffun)) != __no_error)
{
return _retv ;
}
# ifdef __use_timers
_ttoc = _time.now();
_jlog.push(dump_time(_ttic, _ttoc));
# endif//__use_timers
}
if(!_jcfg._hfun_file.empty())
{
/*--------------------------------- assemble size-fun */
_jlog.push ( __jloglndv "\n" ) ;
_jlog.push (
" Forming FFUN data...\n\n" ) ;
# ifdef __use_timers
_ttic = _time.now();
# endif//__use_timers
_ffun.init_hfun(_jcfg, true) ;
if (_jcfg._verbosity > 0 )
{
_jlog.push (
" FFUN data summary...\n\n" ) ;
if ((_retv = echo_hfun (
_jcfg,
_jlog, _ffun)) != __no_error)
{
return _retv ;
}
}
# ifdef __use_timers
_ttoc = _time.now();
_jlog.push(dump_time(_ttic, _ttoc));
# endif//__use_timers
}
if(!_jcfg._hfun_file.empty())
{
/*--------------------------------- call h-jac solver */
_jlog.push ( __jloglndv "\n" ) ;
_jlog.push (
" Fast-march solver...\n\n" ) ;
# ifdef __use_timers
_ttic = _time.now();
# endif//__use_timers
_ffun.clip_hfun(_jcfg) ;
# ifdef __use_timers
_ttoc = _time.now();
_jlog.push(dump_time(_ttic, _ttoc));
# endif//__use_timers
}
if(!_jcfg._hfun_file.empty())
{
/*--------------------------------- dump mesh to file */
_jlog.push ( __jloglndv "\n" ) ;
_jlog.push (
" Writing FFUN file...\n\n" ) ;
# ifdef __use_timers
_ttic = _time.now();
# endif//__use_timers
if ((_retv = save_hfun (
_jcfg,
_jlog, _ffun)) != __no_error)
{
return _retv ;
}
# ifdef __use_timers
_ttoc = _time.now();
_jlog.push(dump_time(_ttic, _ttoc));
# endif//__use_timers
}
/*-------------------------- success, if we got here! */
return ( _retv ) ;
}
# endif //__cmd_marche
# endif //__lib_jigsaw
| 27.679612 | 69 | 0.407085 | [
"mesh",
"object"
] |
291e8141bdd5f7d5aa62d81fad8494b2df82c690 | 15,824 | cpp | C++ | src/names/main.cpp | opensourcerulez/xaya | 0bd3b6658c29f04bc8a40dbc9cc35fbdb26ff3cf | [
"MIT"
] | null | null | null | src/names/main.cpp | opensourcerulez/xaya | 0bd3b6658c29f04bc8a40dbc9cc35fbdb26ff3cf | [
"MIT"
] | null | null | null | src/names/main.cpp | opensourcerulez/xaya | 0bd3b6658c29f04bc8a40dbc9cc35fbdb26ff3cf | [
"MIT"
] | null | null | null | // Copyright (c) 2014-2018 Daniel Kraft
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <names/main.h>
#include <chainparams.h>
#include <coins.h>
#include <consensus/validation.h>
#include <dbwrapper.h>
#include <hash.h>
#include <names/encoding.h>
#include <script/interpreter.h>
#include <script/names.h>
#include <script/script.h>
#include <txmempool.h>
#include <undo.h>
#include <util/system.h>
#include <util/strencodings.h>
#include <validation.h>
#include <univalue.h>
namespace
{
constexpr unsigned MAX_VALUE_LENGTH = 2048;
constexpr unsigned MAX_NAME_LENGTH = 256;
/* Ensure that the name length fits to the script element size limit to avoid
a situation as in Namecoin where names can become unspendable. */
static_assert (MAX_VALUE_LENGTH <= MAX_SCRIPT_ELEMENT_SIZE,
"Maximum value size is too large for script element size");
static_assert (MAX_NAME_LENGTH <= MAX_SCRIPT_ELEMENT_SIZE,
"Maximum name size is too large for script element size");
} // anonymous namespace
/* ************************************************************************** */
/* CNameTxUndo. */
void
CNameTxUndo::fromOldState (const valtype& nm, const CCoinsView& view)
{
name = nm;
isNew = !view.GetName (name, oldData);
}
void
CNameTxUndo::apply (CCoinsViewCache& view) const
{
if (isNew)
view.DeleteName (name);
else
view.SetName (name, oldData, true);
}
/* ************************************************************************** */
/* CNameMemPool. */
uint256
CNameMemPool::getTxForName (const valtype& name) const
{
NameTxMap::const_iterator mi;
mi = mapNameRegs.find (name);
if (mi != mapNameRegs.end ())
{
assert (mapNameUpdates.count (name) == 0);
return mi->second;
}
mi = mapNameUpdates.find (name);
if (mi != mapNameUpdates.end ())
{
assert (mapNameRegs.count (name) == 0);
return mi->second;
}
return uint256 ();
}
void
CNameMemPool::addUnchecked (const CTxMemPoolEntry& entry)
{
AssertLockHeld (pool.cs);
const uint256& txHash = entry.GetTx ().GetHash ();
if (entry.isNameRegistration ())
{
const valtype& name = entry.getName ();
assert (mapNameRegs.count (name) == 0);
mapNameRegs.insert (std::make_pair (name, txHash));
}
if (entry.isNameUpdate ())
{
const valtype& name = entry.getName ();
assert (mapNameUpdates.count (name) == 0);
mapNameUpdates.insert (std::make_pair (name, txHash));
}
}
void
CNameMemPool::remove (const CTxMemPoolEntry& entry)
{
AssertLockHeld (pool.cs);
if (entry.isNameRegistration ())
{
const NameTxMap::iterator mit = mapNameRegs.find (entry.getName ());
assert (mit != mapNameRegs.end ());
mapNameRegs.erase (mit);
}
if (entry.isNameUpdate ())
{
const NameTxMap::iterator mit = mapNameUpdates.find (entry.getName ());
assert (mit != mapNameUpdates.end ());
mapNameUpdates.erase (mit);
}
}
void
CNameMemPool::removeConflicts (const CTransaction& tx)
{
AssertLockHeld (pool.cs);
for (const auto& txout : tx.vout)
{
const CNameScript nameOp(txout.scriptPubKey);
if (nameOp.isNameOp () && nameOp.getNameOp () == OP_NAME_REGISTER)
{
const valtype& name = nameOp.getOpName ();
const NameTxMap::const_iterator mit = mapNameRegs.find (name);
if (mit != mapNameRegs.end ())
{
const CTxMemPool::txiter mit2 = pool.mapTx.find (mit->second);
assert (mit2 != pool.mapTx.end ());
pool.removeRecursive (mit2->GetTx (),
MemPoolRemovalReason::NAME_CONFLICT);
}
}
}
}
void
CNameMemPool::check (const CCoinsView& coins) const
{
AssertLockHeld (pool.cs);
std::set<valtype> nameRegs;
std::set<valtype> nameUpdates;
for (const auto& entry : pool.mapTx)
{
const uint256 txHash = entry.GetTx ().GetHash ();
if (entry.isNameRegistration ())
{
const valtype& name = entry.getName ();
const NameTxMap::const_iterator mit = mapNameRegs.find (name);
assert (mit != mapNameRegs.end ());
assert (mit->second == txHash);
assert (nameRegs.count (name) == 0);
nameRegs.insert (name);
/* There should be no existing name. */
CNameData data;
assert (!coins.GetName (name, data));
}
if (entry.isNameUpdate ())
{
const valtype& name = entry.getName ();
const NameTxMap::const_iterator mit = mapNameUpdates.find (name);
assert (mit != mapNameUpdates.end ());
assert (mit->second == txHash);
assert (nameUpdates.count (name) == 0);
nameUpdates.insert (name);
CNameData data;
if (!coins.GetName (name, data))
assert (false);
}
}
assert (nameRegs.size () == mapNameRegs.size ());
assert (nameUpdates.size () == mapNameUpdates.size ());
/* Check that nameRegs and nameUpdates are disjoint. They must be since
a name can only be in either category, depending on whether it exists
at the moment or not. */
for (const auto& name : nameRegs)
assert (nameUpdates.count (name) == 0);
for (const auto& name : nameUpdates)
assert (nameRegs.count (name) == 0);
}
bool
CNameMemPool::checkTx (const CTransaction& tx) const
{
AssertLockHeld (pool.cs);
/* In principle, multiple name_updates could be performed within the
mempool at once (building upon each other). This is disallowed, though,
since the current mempool implementation does not like it. (We keep
track of only a single update tx for each name.) */
for (const auto& txout : tx.vout)
{
const CNameScript nameOp(txout.scriptPubKey);
if (!nameOp.isNameOp ())
continue;
switch (nameOp.getNameOp ())
{
case OP_NAME_REGISTER:
{
const valtype& name = nameOp.getOpName ();
if (registersName (name))
return false;
break;
}
case OP_NAME_UPDATE:
{
const valtype& name = nameOp.getOpName ();
if (updatesName (name))
return false;
break;
}
default:
assert (false);
}
}
return true;
}
/* ************************************************************************** */
/* CNameConflictTracker. */
namespace
{
void
ConflictTrackerNotifyEntryRemoved (CNameConflictTracker* tracker,
CTransactionRef txRemoved,
MemPoolRemovalReason reason)
{
if (reason == MemPoolRemovalReason::NAME_CONFLICT)
tracker->AddConflictedEntry (txRemoved);
}
} // anonymous namespace
CNameConflictTracker::CNameConflictTracker (CTxMemPool &p)
: txNameConflicts(std::make_shared<std::vector<CTransactionRef>>()), pool(p)
{
pool.NotifyEntryRemoved.connect (
boost::bind (&ConflictTrackerNotifyEntryRemoved, this, _1, _2));
}
CNameConflictTracker::~CNameConflictTracker ()
{
pool.NotifyEntryRemoved.disconnect (
boost::bind (&ConflictTrackerNotifyEntryRemoved, this, _1, _2));
}
void
CNameConflictTracker::AddConflictedEntry (CTransactionRef txRemoved)
{
txNameConflicts->emplace_back (std::move (txRemoved));
}
/* ************************************************************************** */
bool
IsNameValid (const valtype& name, CValidationState& state)
{
if (name.size () > MAX_NAME_LENGTH)
return state.Invalid (false, REJECT_INVALID, "the name is too long");
/* All names must have a namespace. This means that they must start with
some lower-case letters and /. As a regexp, that is: [a-z]+\/.* */
bool foundNamespace = false;
for (size_t i = 0; i < name.size (); ++i)
{
if (name[i] == '/')
{
if (i == 0)
return state.Invalid (false, REJECT_INVALID,
"the empty namespace is not valid");
foundNamespace = true;
break;
}
if (name[i] < 'a' || name[i] > 'z')
return state.Invalid (false, REJECT_INVALID,
"the namespace must only consist of lower-case"
" letters");
}
if (!foundNamespace)
return state.Invalid (false, REJECT_INVALID, "the name has no namespace");
/* Non-printable ASCII characters are not allowed. This check works also for
UTF-8 encoded strings, as characters <0x80 are encoded as a single byte
and never occur as part of some other UTF-8 sequence. */
for (const unsigned char c : name)
if (c < 0x20)
return state.Invalid (false, REJECT_INVALID,
"non-printable ASCII characters are not allowed"
" in names");
/* Only valid UTF-8 strings can be names. */
if (!IsValidUtf8String (std::string (name.begin (), name.end ())))
return state.Invalid (false, REJECT_INVALID, "the name is not valid UTF-8");
return true;
}
bool
IsValueValid (const valtype& value, CValidationState& state)
{
if (value.size () > MAX_VALUE_LENGTH)
return state.Invalid (false, REJECT_INVALID, "the value is too long");
/* The value must parse with Univalue as JSON and be an object. */
UniValue jsonValue;
if (!jsonValue.read (std::string (value.begin (), value.end ())))
return state.Invalid (false, REJECT_INVALID, "the value is not valid JSON");
if (!jsonValue.isObject ())
return state.Invalid (false, REJECT_INVALID,
"the value must be a JSON object");
return true;
}
bool
CheckNameTransaction (const CTransaction& tx, unsigned nHeight,
const CCoinsView& view,
CValidationState& state)
{
const std::string strTxid = tx.GetHash ().GetHex ();
const char* txid = strTxid.c_str ();
/* As a first step, try to locate inputs and outputs of the transaction
that are name scripts. At most one input and output should be
a name operation. */
int nameIn = -1;
CNameScript nameOpIn;
Coin coinIn;
for (unsigned i = 0; i < tx.vin.size (); ++i)
{
const COutPoint& prevout = tx.vin[i].prevout;
Coin coin;
if (!view.GetCoin (prevout, coin))
return state.DoS (100, error ("%s: failed to fetch input coin for %s",
__func__, txid),
REJECT_INVALID, "bad-txns-inputs-missingorspent");
const CNameScript op(coin.out.scriptPubKey);
if (op.isNameOp ())
{
if (nameIn != -1)
return state.Invalid (error ("%s: multiple name inputs into"
" transaction %s", __func__, txid));
nameIn = i;
nameOpIn = op;
coinIn = coin;
}
}
int nameOut = -1;
CNameScript nameOpOut;
for (unsigned i = 0; i < tx.vout.size (); ++i)
{
const CNameScript op(tx.vout[i].scriptPubKey);
if (op.isNameOp ())
{
if (nameOut != -1)
return state.Invalid (error ("%s: multiple name outputs from"
" transaction %s", __func__, txid));
nameOut = i;
nameOpOut = op;
}
}
/* If there are no name outputs, then this transaction is not a name
operation. In this case, there should also be no name inputs, but
otherwise the validation is done. */
if (nameOut == -1)
{
if (nameIn != -1)
return state.Invalid (error ("%s: tx %s has name inputs but no outputs",
__func__, txid));
return true;
}
/* Reject "greedy names". */
const Consensus::Params& params = Params ().GetConsensus ();
if (tx.vout[nameOut].nValue < params.rules->MinNameCoinAmount(nHeight))
return state.Invalid (error ("%s: greedy name", __func__));
/* Now that we have ruled out NAME_NEW, check that we have a previous
name input that is being updated. */
assert (nameOpOut.isAnyUpdate ());
if (nameOpOut.getNameOp () == OP_NAME_REGISTER) {
if (nameIn != -1)
return state.Invalid (error ("%s: name registration with"
" name input", __func__));
}
else if (nameIn == -1)
return state.Invalid (error ("CheckNameTransaction: update without"
" previous name input"));
const valtype& name = nameOpOut.getOpName ();
if (!IsNameValid (name, state))
{
error ("%s: Name is invalid: %s", __func__, FormatStateMessage (state));
return false;
}
if (!IsValueValid (nameOpOut.getOpValue (), state))
{
error ("%s: Value is invalid: %s", __func__, FormatStateMessage (state));
return false;
}
/* Process NAME_UPDATE next. */
if (nameOpOut.getNameOp () == OP_NAME_UPDATE)
{
if (!nameOpIn.isAnyUpdate ())
return state.Invalid (error ("CheckNameTransaction: NAME_UPDATE with"
" prev input that is no update"));
if (name != nameOpIn.getOpName ())
return state.Invalid (error ("%s: NAME_UPDATE name mismatch to prev tx"
" found in %s", __func__, txid));
/* This is actually redundant, since updates need an existing name coin
to spend anyway. But it does not hurt to enforce this here, too. */
CNameData oldName;
if (!view.GetName (name, oldName))
return state.Invalid (error ("%s: NAME_UPDATE name does not exist",
__func__));
/* This is an internal consistency check. If everything is fine,
the input coins from the UTXO database should match the
name database. */
assert (static_cast<unsigned> (coinIn.nHeight) == oldName.getHeight ());
assert (tx.vin[nameIn].prevout == oldName.getUpdateOutpoint ());
return true;
}
/* Finally, NAME_REGISTER. */
CNameData oldName;
if (view.GetName (name, oldName))
return state.Invalid (error ("CheckNameTransaction: NAME_REGISTER"
" on an existing name"));
/* We don't have to specifically check that miners don't create blocks with
conflicting NAME_FIRSTUPDATE's, since the mining's CCoinsViewCache
takes care of this with the check above already. */
return true;
}
void
ApplyNameTransaction (const CTransaction& tx, unsigned nHeight,
CCoinsViewCache& view, CBlockUndo& undo)
{
assert (nHeight != MEMPOOL_HEIGHT);
/* Changes are encoded in the outputs. We don't have to do any checks,
so simply apply all these. */
for (unsigned i = 0; i < tx.vout.size (); ++i)
{
const CNameScript op(tx.vout[i].scriptPubKey);
if (op.isNameOp () && op.isAnyUpdate ())
{
const valtype& name = op.getOpName ();
LogPrint (BCLog::NAMES, "Updating name at height %d: %s\n",
nHeight, EncodeNameForMessage (name));
CNameTxUndo opUndo;
opUndo.fromOldState (name, view);
undo.vnameundo.push_back (opUndo);
CNameData data;
data.fromScript (nHeight, COutPoint (tx.GetHash (), i), op);
view.SetName (name, data, false);
}
}
}
void
CheckNameDB (bool disconnect)
{
const int option
= gArgs.GetArg ("-checknamedb", Params ().DefaultCheckNameDB ());
if (option == -1)
return;
assert (option >= 0);
if (option != 0)
{
if (disconnect || chainActive.Height () % option != 0)
return;
}
pcoinsTip->Flush ();
assert (pcoinsTip->ValidateNameDB ());
}
| 30.140952 | 80 | 0.594603 | [
"object",
"vector"
] |
29200b6c73a0a0094f1d6c33f50fdbcf1c752a9d | 7,519 | hpp | C++ | include/VROSC/NoteSwitchMaterialController.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | include/VROSC/NoteSwitchMaterialController.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | include/VROSC/NoteSwitchMaterialController.hpp | RedBrumbler/virtuoso-codegen | e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: VROSC.NoteBoardNoteVisualController
#include "VROSC/NoteBoardNoteVisualController.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Renderer
class Renderer;
// Forward declaring type: Material
class Material;
}
// Forward declaring namespace: VROSC
namespace VROSC {
// Forward declaring type: NoteBoardNote
class NoteBoardNote;
}
// Completed forward declares
// Type namespace: VROSC
namespace VROSC {
// Forward declaring type: NoteSwitchMaterialController
class NoteSwitchMaterialController;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::VROSC::NoteSwitchMaterialController);
DEFINE_IL2CPP_ARG_TYPE(::VROSC::NoteSwitchMaterialController*, "VROSC", "NoteSwitchMaterialController");
// Type namespace: VROSC
namespace VROSC {
// Size: 0x50
#pragma pack(push, 1)
// Autogenerated type: VROSC.NoteSwitchMaterialController
// [TokenAttribute] Offset: FFFFFFFF
class NoteSwitchMaterialController : public ::VROSC::NoteBoardNoteVisualController {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// private UnityEngine.Renderer _renderer
// Size: 0x8
// Offset: 0x20
::UnityEngine::Renderer* renderer;
// Field size check
static_assert(sizeof(::UnityEngine::Renderer*) == 0x8);
// private UnityEngine.Material _restingOctaveMaterial
// Size: 0x8
// Offset: 0x28
::UnityEngine::Material* restingOctaveMaterial;
// Field size check
static_assert(sizeof(::UnityEngine::Material*) == 0x8);
// private UnityEngine.Material _restingOddMaterial
// Size: 0x8
// Offset: 0x30
::UnityEngine::Material* restingOddMaterial;
// Field size check
static_assert(sizeof(::UnityEngine::Material*) == 0x8);
// private UnityEngine.Material _restingEvenMaterial
// Size: 0x8
// Offset: 0x38
::UnityEngine::Material* restingEvenMaterial;
// Field size check
static_assert(sizeof(::UnityEngine::Material*) == 0x8);
// private UnityEngine.Material _playingMaterial
// Size: 0x8
// Offset: 0x40
::UnityEngine::Material* playingMaterial;
// Field size check
static_assert(sizeof(::UnityEngine::Material*) == 0x8);
// private UnityEngine.Material _restingMaterial
// Size: 0x8
// Offset: 0x48
::UnityEngine::Material* restingMaterial;
// Field size check
static_assert(sizeof(::UnityEngine::Material*) == 0x8);
public:
// Get instance field reference: private UnityEngine.Renderer _renderer
::UnityEngine::Renderer*& dyn__renderer();
// Get instance field reference: private UnityEngine.Material _restingOctaveMaterial
::UnityEngine::Material*& dyn__restingOctaveMaterial();
// Get instance field reference: private UnityEngine.Material _restingOddMaterial
::UnityEngine::Material*& dyn__restingOddMaterial();
// Get instance field reference: private UnityEngine.Material _restingEvenMaterial
::UnityEngine::Material*& dyn__restingEvenMaterial();
// Get instance field reference: private UnityEngine.Material _playingMaterial
::UnityEngine::Material*& dyn__playingMaterial();
// Get instance field reference: private UnityEngine.Material _restingMaterial
::UnityEngine::Material*& dyn__restingMaterial();
// public System.Void .ctor()
// Offset: 0xA16384
// Implemented from: VROSC.NoteBoardNoteVisualController
// Base method: System.Void NoteBoardNoteVisualController::.ctor()
// Base method: System.Void MonoBehaviour::.ctor()
// Base method: System.Void Behaviour::.ctor()
// Base method: System.Void Component::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static NoteSwitchMaterialController* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::VROSC::NoteSwitchMaterialController::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<NoteSwitchMaterialController*, creationType>()));
}
// public override System.Void Setup(VROSC.NoteBoardNote noteField, System.Boolean octave, System.Boolean isOdd)
// Offset: 0xA16318
// Implemented from: VROSC.NoteBoardNoteVisualController
// Base method: System.Void NoteBoardNoteVisualController::Setup(VROSC.NoteBoardNote noteField, System.Boolean octave, System.Boolean isOdd)
void Setup(::VROSC::NoteBoardNote* noteField, bool octave, bool isOdd);
// public override System.Void SetPlaying(System.Boolean isPlaying)
// Offset: 0xA16350
// Implemented from: VROSC.NoteBoardNoteVisualController
// Base method: System.Void NoteBoardNoteVisualController::SetPlaying(System.Boolean isPlaying)
void SetPlaying(bool isPlaying);
}; // VROSC.NoteSwitchMaterialController
#pragma pack(pop)
static check_size<sizeof(NoteSwitchMaterialController), 72 + sizeof(::UnityEngine::Material*)> __VROSC_NoteSwitchMaterialControllerSizeCheck;
static_assert(sizeof(NoteSwitchMaterialController) == 0x50);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: VROSC::NoteSwitchMaterialController::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: VROSC::NoteSwitchMaterialController::Setup
// Il2CppName: Setup
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::NoteSwitchMaterialController::*)(::VROSC::NoteBoardNote*, bool, bool)>(&VROSC::NoteSwitchMaterialController::Setup)> {
static const MethodInfo* get() {
static auto* noteField = &::il2cpp_utils::GetClassFromName("VROSC", "NoteBoardNote")->byval_arg;
static auto* octave = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* isOdd = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::NoteSwitchMaterialController*), "Setup", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{noteField, octave, isOdd});
}
};
// Writing MetadataGetter for method: VROSC::NoteSwitchMaterialController::SetPlaying
// Il2CppName: SetPlaying
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::NoteSwitchMaterialController::*)(bool)>(&VROSC::NoteSwitchMaterialController::SetPlaying)> {
static const MethodInfo* get() {
static auto* isPlaying = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(VROSC::NoteSwitchMaterialController*), "SetPlaying", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{isPlaying});
}
};
| 47.89172 | 200 | 0.741987 | [
"object",
"vector"
] |
29223e2353fa9bee914f5327cab5db1be29b4777 | 914 | cpp | C++ | CSES/Sorting-and-Serching/1085.cpp | TISparta/competitive-programming-solutions | 31987d4e67bb874bf15653565c6418b5605a20a8 | [
"MIT"
] | 1 | 2018-01-30T13:21:30.000Z | 2018-01-30T13:21:30.000Z | CSES/Sorting-and-Serching/1085.cpp | TISparta/competitive-programming-solutions | 31987d4e67bb874bf15653565c6418b5605a20a8 | [
"MIT"
] | null | null | null | CSES/Sorting-and-Serching/1085.cpp | TISparta/competitive-programming-solutions | 31987d4e67bb874bf15653565c6418b5605a20a8 | [
"MIT"
] | 1 | 2018-08-29T13:26:50.000Z | 2018-08-29T13:26:50.000Z | // Binary Search
// 3
// 10-09-2020
#include <bits/stdc++.h>
#define all(A) begin(A), end(A)
#define rall(A) rbegin(A), rend(A)
#define sz(A) int(A.size())
#define pb push_back
#define mp make_pair
using namespace std;
typedef long long ll;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
typedef vector <int> vi;
typedef vector <ll> vll;
typedef vector <pii> vpii;
typedef vector <pll> vpll;
int main () {
ios::sync_with_stdio(false); cin.tie(0);
int n, k;
cin >> n >> k;
vi x(n);
for (int& xi: x) cin >> xi;
ll l = *max_element(all(x)), r = 1e15;
while (l != r) {
ll m = (l + r) >> 1;
ll need = 0;
for (int l = 0; l < n; l++) {
ll sum = x[l];
int r = l;
while (r + 1 < n and sum + x[r + 1] <= m) r += 1, sum += x[r];
need += 1;
l = r;
}
if (need <= k) r = m;
else l = m + 1;
}
cout << l << '\n';
return (0);
}
| 19.869565 | 68 | 0.515317 | [
"vector"
] |
292686660723b1f23d1fa25d67615dd669705c79 | 5,633 | cpp | C++ | src/new_expr/internal_functions.cpp | phantom9999/BaikalDB | 094a7fc457cb345d8e9834a052d7bc17e996999f | [
"Apache-2.0"
] | 1 | 2018-08-07T13:33:47.000Z | 2018-08-07T13:33:47.000Z | src/new_expr/internal_functions.cpp | MinHaoSun/BaikalDB | 191870058f1956d8b50258526aef92c24fc0262f | [
"Apache-2.0"
] | null | null | null | src/new_expr/internal_functions.cpp | MinHaoSun/BaikalDB | 191870058f1956d8b50258526aef92c24fc0262f | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2018 Baidu, Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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 "internal_functions.h"
#include "hll_common.h"
#include <algorithm>
#include <cctype>
namespace baikaldb {
static const int32_t DATE_FORMAT_LENGTH = 128;
ExprValue length(const std::vector<ExprValue>& input) {
if (input[0].is_null()) {
return ExprValue::Null();
}
ExprValue tmp(pb::UINT32);
tmp._u.uint32_val = input[0].get_string().size();
return tmp;
}
ExprValue lower(const std::vector<ExprValue>& input) {
if (input[0].is_null()) {
return ExprValue::Null();
}
ExprValue tmp(pb::STRING);
tmp.str_val = input[0].str_val;
std::transform(tmp.str_val.begin(), tmp.str_val.end(), tmp.str_val.begin(), ::tolower);
return tmp;
}
ExprValue upper(const std::vector<ExprValue>& input) {
if (input[0].is_null()) {
return ExprValue::Null();
}
ExprValue tmp(pb::STRING);
tmp.str_val = input[0].str_val;
std::transform(tmp.str_val.begin(), tmp.str_val.end(), tmp.str_val.begin(), ::toupper);
return tmp;
}
ExprValue concat(const std::vector<ExprValue>& input) {
ExprValue tmp(pb::STRING);
for (auto& s : input) {
if (s.is_null()) {
return ExprValue::Null();
}
tmp.str_val += s.get_string();
}
return tmp;
}
ExprValue substr(const std::vector<ExprValue>& input) {
for (auto& s : input) {
if (s.is_null()) {
return ExprValue::Null();
}
}
std::string str = input[0].get_string();
ExprValue tmp(pb::STRING);
int pos = input[1].get_numberic<int>();
if (pos < 0) {
pos = str.size() + pos;
} else {
--pos;
}
if (pos < 0 || pos >= (int)str.size()) {
return tmp;
}
int len = -1;
if (input.size() == 3) {
len = input[2].get_numberic<int>();
if (len <= 0) {
return tmp;
}
}
tmp.str_val = str;
if (len == -1) {
tmp.str_val = tmp.str_val.substr(pos);
} else {
tmp.str_val = tmp.str_val.substr(pos, len);
}
return tmp;
}
ExprValue left(const std::vector<ExprValue>& input) {
for (auto& s : input) {
if (s.is_null()) {
return ExprValue::Null();
}
}
ExprValue tmp(pb::STRING);
int len = input[1].get_numberic<int>();
if (len <= 0) {
return tmp;
}
tmp.str_val = input[0].str_val;
tmp.str_val = tmp.str_val.substr(0, len);
return tmp;
}
ExprValue right(const std::vector<ExprValue>& input) {
for (auto& s : input) {
if (s.is_null()) {
return ExprValue::Null();
}
}
ExprValue tmp(pb::STRING);
int len = input[1].get_numberic<int>();
if (len <= 0) {
return tmp;
}
int pos = input[0].str_val.size() - len;
if (pos < 0) {
pos = 0;
}
tmp.str_val = input[0].str_val;
tmp.str_val = tmp.str_val.substr(pos);
return tmp;
}
ExprValue unix_timestamp(const std::vector<ExprValue>& input) {
ExprValue tmp(pb::UINT32);
if (input.size() == 0) {
tmp._u.uint32_val = time(NULL);
} else {
if (input[0].is_null()) {
return ExprValue::Null();
}
tmp = input[0];
tmp.cast_to(pb::TIMESTAMP);
tmp.type = pb::UINT32;
}
return tmp;
}
ExprValue from_unixtime(const std::vector<ExprValue>& input) {
ExprValue tmp(pb::TIMESTAMP);
if (input[0].is_null()) {
return ExprValue::Null();
}
tmp._u.uint32_val = input[0].get_numberic<uint32_t>();
return tmp;
}
ExprValue now(const std::vector<ExprValue>& input) {
return ExprValue::Now();
}
ExprValue date_format(const std::vector<ExprValue>& input) {
for (auto& s : input) {
if (s.is_null()) {
return ExprValue::Null();
}
}
ExprValue tmp = input[0];
time_t t = tmp.cast_to(pb::TIMESTAMP)._u.uint32_val;
struct tm t_result;
localtime_r(&t, &t_result);
char s[DATE_FORMAT_LENGTH];
strftime(s, sizeof(s), input[1].str_val.c_str(), &t_result);
ExprValue format_result(pb::STRING);
format_result.str_val = s;
return format_result;
}
ExprValue hll_add(const std::vector<ExprValue>& input) {
if (input.size() < 2) {
return ExprValue::Null();
}
if (input[0].is_null()) {
return hll::hll_init();
}
if (input[1].is_null()) {
return input[0];
}
return hll::hll_add((ExprValue&)input[0], input[1].hash());
}
ExprValue hll_merge(const std::vector<ExprValue>& input) {
if (input.size() < 2) {
return ExprValue::Null();
}
if (input[0].is_null()) {
return input[1];
} else if (input[1].is_null()) {
return input[0];
}
return hll::hll_merge((ExprValue&)input[0], (ExprValue&)input[1]);
}
ExprValue hll_estimate(const std::vector<ExprValue>& input) {
if (input[0].is_null()) {
return ExprValue::Null();
}
ExprValue tmp(pb::INT64);
tmp._u.int64_val = hll::hll_estimate(input[0]);
return tmp;
}
}
/* vim: set ts=4 sw=4 sts=4 tw=100 */
| 26.952153 | 92 | 0.587964 | [
"vector",
"transform"
] |
292c65e4dc2402eea2d53a5ec30547598c2fa2af | 1,721 | hpp | C++ | RPG-Game/Game.hpp | mDevv/RPG-Game | e83857c2e71f2689053e6fd114ee85dae05ddcb1 | [
"MIT"
] | null | null | null | RPG-Game/Game.hpp | mDevv/RPG-Game | e83857c2e71f2689053e6fd114ee85dae05ddcb1 | [
"MIT"
] | 1 | 2017-06-14T17:34:50.000Z | 2017-06-14T17:34:50.000Z | RPG-Game/Game.hpp | mDevv/RPG-Game | e83857c2e71f2689053e6fd114ee85dae05ddcb1 | [
"MIT"
] | null | null | null | //
// Game.hpp
// RPG-Game
//
// Created by Michał Dziewulski on 10.05.2017.
// Copyright © 2017 Michał Dziewulski. All rights reserved.
//
#ifndef Game_hpp
#define Game_hpp
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
#include <memory>
#include <fstream>
#include "json.hpp"
#include "ResourcePath.hpp"
#include "Entity.hpp"
#include "ArcherEntity.hpp"
#include "WarriorEntity.hpp"
#include "KnightEntity.hpp"
#include "MageEntity.hpp"
#include "CavalierEntity.hpp"
namespace global
{
extern const float W_HEIGHT; // 800 map + 200 bar
extern const float W_WIDTH;
extern unsigned size;
extern const bool GREEN;
extern const bool ORANGE;
extern unsigned greenAmount;
extern unsigned orangeAmount;
extern int errorFlag;
}
class Game
{
public:
Game();
~Game();
void run();
void save();
void load(std::string fileName);
private:
void render(sf::RenderWindow &window);
void renderWinner(sf::RenderWindow &window, bool winner);
void renderErrorLoad(sf::RenderWindow &window);
void renderErrorSave(sf::RenderWindow &window);
void drawBackground(sf::RenderWindow &window);
void drawFields(sf::RenderWindow &window);
void drawMenu(sf::RenderWindow &window);
void drawMap(sf::RenderWindow &window);
sf::Texture backgroundTile;
sf::RectangleShape bar;
sf::Texture nextTurnButton;
sf::Texture saveButton;
sf::RectangleShape lineY;
sf::RectangleShape lineX;
sf::RectangleShape playerTurn;
sf::Texture army;
bool m_turn;
bool m_hasAttacked;
bool m_hasMoved;
Entity*** map;
Entity* selected;
int selectedPosX;
int selectedPosY;
};
#endif /* Game_hpp */
| 22.644737 | 61 | 0.689715 | [
"render"
] |
a0963106e9857b4d0929ffec82db5466bafbb64e | 1,562 | cpp | C++ | TG/bookcodes/ch5/la4287_kosaraju.cpp | Anyrainel/aoapc-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | 3 | 2017-08-15T06:00:01.000Z | 2018-12-10T09:05:53.000Z | TG/bookcodes/ch5/la4287_kosaraju.cpp | Anyrainel/aoapc-related-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | null | null | null | TG/bookcodes/ch5/la4287_kosaraju.cpp | Anyrainel/aoapc-related-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | 2 | 2017-09-16T18:46:27.000Z | 2018-05-22T05:42:03.000Z | // LA4287 Proving Equivalences:用Kosaraju算法算SCC
// Rujia Liu
#include<cstdio>
#include<algorithm>
#include<vector>
#include<cstring>
#include<stack>
using namespace std;
const int maxn = 20000 + 10;
vector<int> G[maxn], G2[maxn];
vector<int> S;
int vis[maxn], sccno[maxn], scc_cnt;
void dfs1(int u) {
if(vis[u]) return;
vis[u] = 1;
for(int i = 0; i < G[u].size(); i++) dfs1(G[u][i]);
S.push_back(u);
}
void dfs2(int u) {
if(sccno[u]) return;
sccno[u] = scc_cnt;
for(int i = 0; i < G2[u].size(); i++) dfs2(G2[u][i]);
}
void find_scc(int n) {
scc_cnt = 0;
S.clear();
memset(sccno, 0, sizeof(sccno));
memset(vis, 0, sizeof(vis));
for(int i = 0; i < n; i++) dfs1(i);
for(int i = n-1; i >= 0; i--)
if(!sccno[S[i]]) { scc_cnt++; dfs2(S[i]); }
}
int in0[maxn], out0[maxn];
int main() {
int T, n, m;
scanf("%d", &T);
while(T--) {
scanf("%d%d", &n, &m);
for(int i = 0; i < n; i++) { G[i].clear(); G2[i].clear(); }
for(int i = 0; i < m; i++) {
int u, v;
scanf("%d%d", &u, &v); u--; v--;
G[u].push_back(v); G2[v].push_back(u);
}
find_scc(n);
for(int i = 1; i <= scc_cnt; i++) in0[i] = out0[i] = 1;
for(int u = 0; u < n; u++)
for(int i = 0; i < G[u].size(); i++) {
int v = G[u][i];
if(sccno[u] != sccno[v]) in0[sccno[v]] = out0[sccno[u]] = 0;
}
int a = 0, b = 0;
for(int i = 1; i <= scc_cnt; i++) {
if(in0[i]) a++;
if(out0[i]) b++;
}
int ans = max(a, b);
if(scc_cnt == 1) ans = 0;
printf("%d\n", ans);
}
return 0;
}
| 21.694444 | 68 | 0.495519 | [
"vector"
] |
a096e99db8d0353ece4a2bdaf0f31cd6b6acd0e4 | 845 | cpp | C++ | aten/src/ATen/native/quantized/cpu/xnnpack_utils.cpp | dme65/pytorch | bc512253d5fe718a029324c45f175a81b088facd | [
"Intel"
] | null | null | null | aten/src/ATen/native/quantized/cpu/xnnpack_utils.cpp | dme65/pytorch | bc512253d5fe718a029324c45f175a81b088facd | [
"Intel"
] | null | null | null | aten/src/ATen/native/quantized/cpu/xnnpack_utils.cpp | dme65/pytorch | bc512253d5fe718a029324c45f175a81b088facd | [
"Intel"
] | null | null | null | #include <ATen/ATen.h>
#ifdef USE_XNNPACK
namespace at {
namespace native {
namespace xnnp_utils {
std::vector<size_t> get_mem_format_aware_shape(const at::Tensor& in) {
const auto mem_format = in.suggest_memory_format();
const auto& sizes = in.sizes();
std::vector<size_t> ret(sizes.begin(), sizes.end());
if (mem_format == c10::MemoryFormat::ChannelsLast) {
// NCHW -> NHWC
// 0123 -> 0231
ret[1] = sizes[2]; /* H */
ret[2] = sizes[3]; /* W */
ret[3] = sizes[1]; /* C */
} else if (mem_format == c10::MemoryFormat::ChannelsLast3d) {
// NCDHW -> NDHWC
// 01234 -> 02341
ret[1] = sizes[2]; /* D */
ret[2] = sizes[3]; /* H */
ret[3] = sizes[4]; /* W */
ret[4] = sizes[1]; /* C */
}
return ret;
}
} // namespace xnnp_utils
} // namespace native
} // namespace at
#endif // USE_XNNPACK
| 25.606061 | 70 | 0.590533 | [
"vector"
] |
a09855d13c4a380ef97aa1ec9c20dd56810df112 | 4,059 | cpp | C++ | src/imgui_toolbars.cpp | yak32/glw_imgui | 546b8658558629cd7f5a5f72470b2faad61e68df | [
"BSD-2-Clause"
] | 56 | 2016-09-22T03:34:21.000Z | 2022-02-08T23:47:31.000Z | src/imgui_toolbars.cpp | yak32/glw_imgui | 546b8658558629cd7f5a5f72470b2faad61e68df | [
"BSD-2-Clause"
] | null | null | null | src/imgui_toolbars.cpp | yak32/glw_imgui | 546b8658558629cd7f5a5f72470b2faad61e68df | [
"BSD-2-Clause"
] | 13 | 2017-05-25T08:19:09.000Z | 2020-06-15T10:08:07.000Z | // glw_imgui
// Copyright (C) 2016 Iakov Sumygin - BSD license
#include "imgui_toolbars.h"
#include "imgui_ui.h"
#include "imgui_rollout.h"
#include <math.h>
#include <cstdlib>
namespace imgui {
Toolbar* Toolbar::add_rollout(Rollout* r, float _div, bool _horz) {
div = _div;
horz = _horz;
if (div == 1.0f) {
rollout = r;
return this;
}
if (div > 0) {
left = new Toolbar(r);
right = new Toolbar(NULL);
return right;
}
right = new Toolbar(r);
left = new Toolbar(NULL);
return left;
}
void visit_rollout_node(std::vector<Rollout*>& rollouts, Toolbar* n, int x, int y, int w, int h) {
if (!n)
return;
if (n->rollout) {
// leaf node
n->rollout->x = x;
n->rollout->y = y;
n->rollout->w = w;
n->rollout->h = h;
for (int r_id : n->rollout->tabs) {
Rollout* r = rollouts[r_id];
r->x = x;
r->y = y;
r->w = w;
r->h = h;
}
}
n->w = w;
n->h = h;
int div = 0;
int dist = n->horz ? w : h;
if (n->div > 0)
div = n->div < 1.0f ? (int)(dist * n->div) : (int)(n->div);
else
div = n->div > -1.0f ? dist + (int)(dist * n->div) : dist + (int)(n->div);
int sep = 1;
if (n->horz) {
visit_rollout_node(rollouts, n->left, x, y, div, h);
visit_rollout_node(rollouts, n->right, x + div + sep, y, w - div - sep, h);
}
else {
visit_rollout_node(rollouts, n->left, x, y, w, div);
visit_rollout_node(rollouts, n->right, x, y + div + sep, w, h - div - sep);
}
}
div_drag find_div(int mx, int my, Toolbar* toolbar, int x, int y, int w, int h, int padding) {
div_drag res;
res.div = NULL;
if (!toolbar || mx < x || mx > x + w || my < y || my > y + h)
return res;
int div = 0;
int dist = toolbar->horz ? w : h;
if (toolbar->div > 0)
div = toolbar->div < 1.0f ? (int)(dist * toolbar->div) : (int)(toolbar->div);
else
div = toolbar->div > -1.0f ? dist + (int)(dist * toolbar->div) : dist + (int)(toolbar->div);
int sep = 1;
if (toolbar->horz) {
if ((!toolbar->left || !toolbar->left->rollout ||
toolbar->left->rollout->options & RESIZE_AREA) &&
(!toolbar->right || !toolbar->right->rollout ||
toolbar->right->rollout->options & RESIZE_AREA) &&
std::abs(mx - (x + div)) < padding * 2) {
return div_drag(&toolbar->div, toolbar->w);
}
res = find_div(mx, my, toolbar->left, x, y, div, h, padding);
if (res.div)
return res;
res = find_div(mx, my, toolbar->right, x + div + sep, y, w - div - sep, h, padding);
if (res.div)
return res;
}
else {
if ((!toolbar->left || !toolbar->left->rollout ||
toolbar->left->rollout->options & RESIZE_AREA) &&
(!toolbar->right || !toolbar->right->rollout ||
toolbar->right->rollout->options & RESIZE_AREA) &&
std::abs(my - (y + div)) < padding * 2) {
return div_drag(&toolbar->div, toolbar->h);
}
res = find_div(mx, my, toolbar->left, x, y, w, div, padding);
if (res.div)
return res;
res = find_div(mx, my, toolbar->right, x, y + div + sep, w, h - div - sep, padding);
if (res.div)
return res;
}
return res;
}
Toolbar* search_rollout_node(Toolbar* n, const Rollout* search, bool check_tabs) {
if (!n)
return NULL;
if (n->rollout == search)
return n;
if (check_tabs && n->rollout)
for (auto i : n->rollout->tabs)
if (i == search->id)
return n;
Toolbar* r = search_rollout_node(n->left, search, check_tabs);
if (r)
return r;
r = search_rollout_node(n->right, search, check_tabs);
if (r)
return r;
return NULL;
}
Toolbar* search_rollout_parent_node(Toolbar* n, const Rollout* search) {
if (!n)
return NULL;
if (n->left && n->left->rollout == search)
return n;
if (n->right && n->right->rollout == search)
return n;
Toolbar* r = search_rollout_parent_node(n->left, search);
if (r)
return r;
r = search_rollout_parent_node(n->right, search);
if (r)
return r;
return NULL;
}
void div_drag::shift(int shift) {
*div += (fabs(*div) >= 1.0f) ? (float)shift : (float)shift / size;
}
void clear_toolbars(Toolbar* n) {
if (!n)
return;
clear_toolbars(n->left);
clear_toolbars(n->right);
delete (n->left);
delete (n->right);
n->left = NULL;
n->right = NULL;
}
}
| 26.357143 | 98 | 0.600887 | [
"vector"
] |
a09b89cbd79bf1639e6b27fa984c6d7b8af4d097 | 4,259 | cpp | C++ | unittest/srdf.cpp | mkatliar/pinocchio | b755b9cf2567eab39de30a68b2a80fac802a4042 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | unittest/srdf.cpp | mkatliar/pinocchio | b755b9cf2567eab39de30a68b2a80fac802a4042 | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | unittest/srdf.cpp | mkatliar/pinocchio | b755b9cf2567eab39de30a68b2a80fac802a4042 | [
"BSD-2-Clause-FreeBSD"
] | 1 | 2020-02-25T13:34:37.000Z | 2020-02-25T13:34:37.000Z | //
// Copyright (c) 2016-2018 CNRS
//
#include <iostream>
#include "pinocchio/multibody/model.hpp"
#include "pinocchio/parsers/urdf.hpp"
#include "pinocchio/parsers/srdf.hpp"
#include <boost/test/unit_test.hpp>
using namespace pinocchio;
using namespace std;
BOOST_AUTO_TEST_SUITE ( BOOST_TEST_MODULE )
BOOST_AUTO_TEST_CASE(test_removeCollisionPairs)
{
using namespace pinocchio::urdf;
using namespace pinocchio::srdf;
const string model_filename = PINOCCHIO_SOURCE_DIR"/models/romeo/romeo_description/urdf/romeo_small.urdf";
const string model_dir = PINOCCHIO_SOURCE_DIR"/models/romeo";
const string srdf_filename = PINOCCHIO_SOURCE_DIR"/models/romeo/romeo_description/srdf/romeo.srdf";
Model model;
buildModel(model_filename, model);
GeometryModel geom_model;
vector<string> paths; paths.push_back(model_dir);
buildGeom(model,model_filename,COLLISION,geom_model,paths);
geom_model.addAllCollisionPairs();
const size_t num_init_col_pairs = geom_model.collisionPairs.size();
removeCollisionPairs(model,geom_model,srdf_filename,false);
const size_t num_col_pairs = geom_model.collisionPairs.size();
BOOST_CHECK(num_init_col_pairs > num_col_pairs);
}
BOOST_AUTO_TEST_CASE(readReferenceConfig)
{
using namespace pinocchio::urdf;
using namespace pinocchio::srdf;
const string model_filename = PINOCCHIO_SOURCE_DIR"/models/simple_humanoid.urdf";
const string srdf_filename = PINOCCHIO_SOURCE_DIR"/models/simple_humanoid.srdf";
Model model;
buildModel(model_filename, model);
loadReferenceConfigurations(model,srdf_filename,false);
Eigen::VectorXd q = model.referenceConfigurations["half_sitting"];
Eigen::VectorXd q2 = model.referenceConfigurations["half_sitting2"];
BOOST_CHECK(q.size() == model.nq);
BOOST_CHECK(!q.isZero());
BOOST_CHECK(q2.size() == model.nq);
BOOST_CHECK(!q2.isZero());
}
BOOST_AUTO_TEST_CASE(readReferenceConfig_stream)
{
const string urdf =
"<robot name='test'>"
"<link name='base_link'/>"
"<link name='child_link'/>"
"<joint type='revolute' name='joint'>"
" <parent link='base_link'/>"
" <child link='child_link'/>"
" <limit effort='30' velocity='1.0' />"
"</joint>"
"</robot>";
const string srdf =
"<robot name='test'>"
"<group_state name='reference' group='all'>"
" <joint name='joint' value='0.0' />"
"</group_state>"
"</robot>";
Model model;
pinocchio::urdf::buildModelFromXML(urdf, model);
std::istringstream iss (srdf);
pinocchio::srdf::loadReferenceConfigurationsFromXML(model,iss,false);
Eigen::VectorXd q = model.referenceConfigurations["reference"];
Eigen::VectorXd qexpected(1); qexpected << 0;
BOOST_CHECK(q.size() == model.nq);
BOOST_CHECK(q.isApprox(qexpected));
}
BOOST_AUTO_TEST_CASE(test_continuous_joint)
{
const string urdf =
"<robot name='test'>"
"<link name='base_link'/>"
"<link name='child_link'/>"
"<joint type='continuous' name='joint'>"
" <parent link='base_link'/>"
" <child link='child_link'/>"
" <limit effort='30' velocity='1.0' />"
"</joint>"
"</robot>";
const string srdf =
"<robot name='test'>"
"<group_state name='reference' group='all'>"
" <joint name='joint' value='0.0' />"
"</group_state>"
"</robot>";
Model model;
pinocchio::urdf::buildModelFromXML(urdf, model);
std::istringstream iss (srdf);
pinocchio::srdf::loadReferenceConfigurationsFromXML(model,iss,false);
Eigen::VectorXd q = model.referenceConfigurations["reference"];
Eigen::VectorXd qexpected(2); qexpected << 1,0;
BOOST_CHECK(q.size() == model.nq);
BOOST_CHECK(q.isApprox(qexpected));
}
BOOST_AUTO_TEST_CASE(readRotorParams)
{
using namespace pinocchio::urdf;
using namespace pinocchio::srdf;
const string model_filename = PINOCCHIO_SOURCE_DIR"/models/simple_humanoid.urdf";
const string srdf_filename = PINOCCHIO_SOURCE_DIR"/models/simple_humanoid.srdf";
Model model;
buildModel(model_filename, model);
loadRotorParameters(model,srdf_filename,false);
BOOST_CHECK(model.rotorInertia(model.joints[model.getJointId("WAIST_P")].idx_v())==1.0);
BOOST_CHECK(model.rotorGearRatio(model.joints[model.getJointId("WAIST_R")].idx_v())==1.0);
}
BOOST_AUTO_TEST_SUITE_END()
| 29.576389 | 108 | 0.722705 | [
"vector",
"model"
] |
a09cb7363694d6c6418c875eb12298133adaf4af | 10,090 | cpp | C++ | src/caffe/RFCN/psroi_align_layer.cpp | xyt2008/frcnn | 32a559e881cceeba09a90ff45ad4aae1dabf92a1 | [
"BSD-2-Clause"
] | 198 | 2018-01-07T13:44:29.000Z | 2022-03-21T12:06:16.000Z | src/caffe/RFCN/psroi_align_layer.cpp | xyt2008/frcnn | 32a559e881cceeba09a90ff45ad4aae1dabf92a1 | [
"BSD-2-Clause"
] | 18 | 2018-02-01T13:24:53.000Z | 2021-04-26T10:51:47.000Z | src/caffe/RFCN/psroi_align_layer.cpp | xyt2008/frcnn | 32a559e881cceeba09a90ff45ad4aae1dabf92a1 | [
"BSD-2-Clause"
] | 82 | 2018-01-06T14:21:43.000Z | 2022-02-16T09:39:58.000Z | // ------------------------------------------------------------------
// R-FCN
// Written by Jiangfan Deng
// Written by Afanti<afanti.deng@gmail.com>
// Modify by fyk to add CPU forward
// ------------------------------------------------------------------
#include <algorithm>
#include <cfloat>
#include <string>
#include <utility>
#include <vector>
#include "psroi_align_layer.hpp"
using std::max;
using std::min;
namespace caffe {
template <typename Dtype>
void PSROIAlignLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
PSROIAlignParameter psroi_align_param =
this->layer_param_.psroi_align_param();
spatial_scale_ = psroi_align_param.spatial_scale();
LOG(INFO) << "Spatial scale: " << spatial_scale_;
CHECK_GT(psroi_align_param.output_dim(), 0)
<< "output_dim must be > 0";
CHECK_GT(psroi_align_param.group_size(), 0)
<< "group_size must be > 0";
output_dim_ = psroi_align_param.output_dim();
group_size_ = psroi_align_param.group_size();
sample_num_ = psroi_align_param.sample_num();
pooled_height_ = group_size_;
pooled_width_ = group_size_;
}
template <typename Dtype>
void PSROIAlignLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
channels_ = bottom[0]->channels();
CHECK_EQ(channels_, output_dim_*group_size_*group_size_)
<< "input channel number does not match layer parameters";
height_ = bottom[0]->height();
width_ = bottom[0]->width();
top[0]->Reshape(bottom[1]->num(), output_dim_, pooled_height_, pooled_width_);
mapping_channel_.Reshape(bottom[1]->num(), output_dim_, pooled_height_, pooled_width_);
sample_pos_.Reshape(bottom[1]->num(), output_dim_, pooled_height_*pooled_width_*sample_num_*sample_num_, 2);
}
template <typename Dtype>
void bilinear_interpolate(const Dtype* bottom_data, const int height, const int width, Dtype h, Dtype w, Dtype & val) {
// deal with cases that inverse elements are out of feature map boundary
if (h < -0.5 || h > height - 0.5 || w < -0.5 || w > width - 0.5) return;
if (h <= 0) h = 0;
if (w <= 0) w = 0;
int h_high; // h_high 是比 h 大的最小整数
int w_high; // w_high 是比 w 大的最小整数
int h_low = (int) h; // h_low 是比 h 小的最大整数
int w_low = (int) w; // w_low 是比 w 小的最大整数
if (w_low >= width - 1) {
w_low = width - 1;
w_high = width-1;
w = (Dtype) w_low;
} else
w_high = w_low + 1;
if (h_low >= height - 1) {
h_high = height-1;
h_low = height - 1;
h = (Dtype) h_low;
} else
h_high = h_low + 1;
Dtype l_dh = h - h_low;
Dtype l_dw = w - w_low;
Dtype h_dh = 1 - l_dh, h_dw = 1 - l_dw;
// 进行双线性内插
Dtype u1 = bottom_data[h_low * width + w_low];
Dtype u2 = bottom_data[h_low * width + w_high];
Dtype u3 = bottom_data[h_high * width + w_low];
Dtype u4 = bottom_data[h_high * width + w_high];
Dtype w1 = h_dh * h_dw, w2 = h_dh * l_dw, w3 = l_dh * h_dw, w4 = l_dh * l_dw;
val = (w1 * u1 + w2 * u2 + w3 * u3 + w4 * u4);
}
template <typename Dtype>
void PSROIAlignForward(
const int num,
const Dtype* bottom_data,
const Dtype spatial_scale,
const int channels,
const int height, const int width,
const int pooled_height, const int pooled_width,
const Dtype* bottom_rois,
const int output_dim, // 输出通道数
const int group_size, // k*k*(c+1) 中的 k
Dtype* top_data,
int* mapping_channel,
Dtype* sample_pos_data,
const int sample_num) {
for (int n = 0; n < num; ++n) {
// [start, end) interval for spatial sampling
int roi_add = n*5;
int roi_batch_ind = bottom_rois[roi_add];
Dtype roi_start_w =
static_cast<Dtype>(bottom_rois[roi_add + 1]) * spatial_scale;
Dtype roi_start_h =
static_cast<Dtype>(bottom_rois[roi_add + 2]) * spatial_scale;
Dtype roi_end_w =
static_cast<Dtype>(bottom_rois[roi_add + 3] + 1.) * spatial_scale;
Dtype roi_end_h =
static_cast<Dtype>(bottom_rois[roi_add + 4] + 1.) * spatial_scale;
// Force too small ROIs to be 1x1
Dtype roi_width = max<Dtype>(roi_end_w - roi_start_w, 0.1); // avoid 0
Dtype roi_height = max<Dtype>(roi_end_h - roi_start_h, 0.1);
// Compute w and h at bottom
Dtype bin_size_h = roi_height / static_cast<Dtype>(pooled_height);
Dtype bin_size_w = roi_width / static_cast<Dtype>(pooled_width);
for (int ctop = 0; ctop < output_dim; ++ctop) {
for (int ph = 0; ph < pooled_height; ++ph) {
for (int pw = 0; pw < pooled_width; ++pw) {
int index = n*output_dim*pooled_height*pooled_width + ctop*pooled_height*pooled_width + ph*pooled_width + pw;
// 获得当前RoI的宽和高在池化前特征图上的起始和结束索引值, 浮点数
Dtype hstart = static_cast<Dtype>(ph) * bin_size_h;
Dtype wstart = static_cast<Dtype>(pw) * bin_size_w;
Dtype hend = static_cast<Dtype>(ph + 1) * bin_size_h;
Dtype wend = static_cast<Dtype>(pw + 1) * bin_size_w;
// Add roi offsets and clip to input boundaries
hstart = min(max(hstart + roi_start_h, Dtype(0)), Dtype(height-1));
hend = min(max(hend + roi_start_h, Dtype(0)), Dtype(height-1));
wstart = min(max(wstart + roi_start_w, Dtype(0)), Dtype(width-1));
wend = min(max(wend + roi_start_w, Dtype(0)), Dtype(width-1));
bool is_empty = (hend <= hstart) || (wend <= wstart);
int gw = pw;
int gh = ph;
int c = (ctop*group_size + gh)*group_size + gw; //
// 在池化前特征图上采样点之间的距离,浮点数 (在 h 和 w 两个方向上)
Dtype sample_h = bin_size_h / (sample_num + 1);
Dtype sample_w = bin_size_w / (sample_num + 1);
Dtype val = 0;
//bottom_data += (roi_batch_ind * channels + c) * height * width;
int bottom_data_offset = (roi_batch_ind * channels + c) * height * width;
Dtype out_sum = 0.0;
int p_counter = -1;
Dtype* sample_pos_diff = sample_pos_data + index * sample_num * sample_num * 2;
for (int i = 1; i <= sample_num; ++i) {
for (int j = 1; j <= sample_num; ++j) {
++p_counter;
Dtype cur_h = hstart + i * sample_h;
Dtype cur_w = wstart + j * sample_w;
if (cur_h >= hend || cur_w >= wend) continue;
bilinear_interpolate(bottom_data + bottom_data_offset, height, width, cur_h, cur_w, val);
out_sum += val;
sample_pos_diff[p_counter * 2 + 0] = cur_h;
sample_pos_diff[p_counter * 2 + 1] = cur_w;
// updated = true;
}
}
// Dtype bin_area = (hend - hstart) * (wend - wstart);
top_data[index] = is_empty ? 0. : out_sum / static_cast<Dtype>(sample_num * sample_num);
mapping_channel[index] = c;
}
}
}
}
}
template <typename Dtype>
void PSROIAlignLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
const Dtype* bottom_data = bottom[0]->cpu_data();
const Dtype* bottom_rois = bottom[1]->cpu_data();
Dtype* top_data = top[0]->mutable_cpu_data();
Dtype* sample_pos_data = sample_pos_.mutable_cpu_data();
int* mapping_channel_ptr = mapping_channel_.mutable_cpu_data();
int count = top[0]->count();
caffe_set(count, Dtype(0), top_data);
caffe_set(count, -1, mapping_channel_ptr);
// NOLINT_NEXT_LINE(whitespace/operators)
PSROIAlignForward(bottom[1]->num(), bottom_data, spatial_scale_,
channels_, height_, width_, pooled_height_,
pooled_width_, bottom_rois, output_dim_, group_size_,
top_data, mapping_channel_ptr, sample_pos_data, sample_num_);
}
template <typename Dtype>
void PSROIAlignLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) {
NOT_IMPLEMENTED;
}
#ifdef CPU_ONLY
STUB_GPU(PSROIAlignLayer);
#endif
INSTANTIATE_CLASS(PSROIAlignLayer);
REGISTER_LAYER_CLASS(PSROIAlign);
} // namespace caffe
| 46.712963 | 137 | 0.5 | [
"vector"
] |
a0a73b9d840d1163f7fd40e85c2dd2b250bd367c | 6,649 | cpp | C++ | tests/main.cpp | kevcadieux/irrlicht | 97472da9c22ae4a49dfcefb9da5156601fa6a82a | [
"IJG"
] | 440 | 2015-01-04T16:01:46.000Z | 2022-03-25T08:31:38.000Z | tests/main.cpp | kevcadieux/irrlicht | 97472da9c22ae4a49dfcefb9da5156601fa6a82a | [
"IJG"
] | 2 | 2021-02-14T19:28:53.000Z | 2021-02-14T20:41:58.000Z | tests/main.cpp | svn2github/irrlicht-trunk | 284c35911e87c0d4ae9ee2100b704af10cef57a5 | [
"IJG"
] | 189 | 2015-01-06T10:39:46.000Z | 2022-02-21T07:20:59.000Z | // Copyright (C) 2008-2012 Colin MacDonald and Christian Stehno
// No rights reserved: this software is in the public domain.
// This is the entry point for the Irrlicht test suite.
// This is an MSVC pragma to link against the Irrlicht library.
// Other builds must link against it in the project files.
#if defined(_MSC_VER)
#pragma comment(lib, "Irrlicht.lib")
#define _CRT_SECURE_NO_WARNINGS 1
#endif // _MSC_VER
#include "testUtils.h"
#include <stdio.h>
#include <time.h>
#include <vector>
struct STestDefinition
{
//! The test entry point function
bool(*testSignature)(void);
//! A descriptive name for the test
const char * testName;
};
//! This is the main entry point for the Irrlicht test suite.
/** \return The number of test that failed, i.e. 0 is success. */
int main(int argumentCount, char * arguments[])
{
if(argumentCount > 3)
{
logTestString("\nUsage: %s [testNumber] [testCount]\n");
return 9999;
}
#define TEST(x)\
{\
extern bool x(void);\
STestDefinition newTest;\
newTest.testSignature = x;\
newTest.testName = #x;\
tests.push_back(newTest);\
}
// Use an STL vector so that we don't rely on Irrlicht.
std::vector<STestDefinition> tests;
#if 0
// To interactively debug a test, move it (temporarily) in here and enable the define to only run this test
// Otherwise debugging is slightly tricky as each test runs in it's own process.
TEST(textureFeatures);
#else
TEST(disambiguateTextures); // Normally you should run this first, since it validates the working directory.
// Now the simple tests without device
TEST(testIrrArray);
TEST(testIrrMap);
TEST(testIrrList);
TEST(exports);
TEST(irrCoreEquals);
TEST(testIrrString);
TEST(testLine2d);
TEST(matrixOps);
TEST(testDimension2d);
TEST(testVector2d);
TEST(testVector3d);
TEST(testQuaternion);
TEST(testS3DVertex);
TEST(testaabbox3d);
TEST(color);
TEST(testTriangle3d);
TEST(vectorPositionDimension2d);
// file system checks (with null driver)
TEST(filesystem);
TEST(archiveReader);
TEST(testXML);
TEST(serializeAttributes);
// null driver
TEST(fast_atof);
TEST(loadTextures);
TEST(collisionResponseAnimator);
TEST(enumerateImageManipulators);
TEST(removeCustomAnimator);
TEST(sceneCollisionManager);
TEST(sceneNodeAnimator);
TEST(meshLoaders);
TEST(testTimer);
TEST(testCoreutil);
// software drivers only
TEST(softwareDevice);
TEST(b3dAnimation);
TEST(burningsVideo);
TEST(billboards);
TEST(createImage);
TEST(cursorSetVisible);
TEST(flyCircleAnimator);
TEST(guiDisabledMenu);
TEST(makeColorKeyTexture);
TEST(md2Animation);
TEST(meshTransform);
TEST(skinnedMesh);
TEST(testGeometryCreator);
TEST(writeImageToFile);
TEST(ioScene);
// all driver checks
TEST(videoDriver);
TEST(screenshot);
TEST(drawPixel);
TEST(drawRectOutline);
TEST(drawVertexPrimitive);
TEST(material);
TEST(renderTargetTexture);
TEST(textureFeatures);
TEST(textureRenderStates);
TEST(transparentMaterials);
TEST(userclipplane);
TEST(antiAliasing);
TEST(draw2DImage);
TEST(lights);
TEST(twodmaterial);
TEST(viewPort);
TEST(mrt);
TEST(projectionMatrix);
// large scenes/long rendering
// shadows are slow
// TEST(orthoCam);
// TEST(stencilShadow);
// q3 maps are slow
TEST(planeMatrix);
TEST(terrainSceneNode);
TEST(lightMaps);
TEST(triangleSelector);
TEST(line2DTest);
#endif
unsigned int numberOfTests = tests.size();
unsigned int testToRun = 0;
unsigned int fails = 0;
bool firstRun=true;
const bool spawn=false;
// args: [testNumber] [testCount]
if(argumentCount > 1)
{
if (!strcmp(arguments[1],"--list"))
{
for (unsigned int i=0; i<tests.size(); ++i)
{
logTestString("%3d: %s\n", i, tests[i].testName);
}
logTestString("\n");
return 0;
}
int tmp = atoi(arguments[1]);
firstRun = (tmp>=0);
testToRun=abs(tmp);
if (!firstRun)
testToRun -= 1;
if(argumentCount > 2)
{
numberOfTests = testToRun + abs(atoi(arguments[2]));
if (numberOfTests>=tests.size())
numberOfTests=tests.size();
}
}
if(testToRun >= numberOfTests)
{
logTestString("\nError: invalid test %d (maximum %d)\n",
testToRun, numberOfTests-testToRun);
return 9999;
}
const unsigned int testCount = numberOfTests-testToRun;
const bool logFileOpened = openTestLog(firstRun);
assert(logFileOpened);
if (firstRun)
{
if (numberOfTests)
{
for (unsigned int i=testToRun; i<numberOfTests; ++i)
{
logTestString("\nStarting test %d, '%s'\n",
i, tests[i].testName);
if (spawn)
{
closeTestLog();
char runNextTest[256];
(void)sprintf(runNextTest, "\"%s\" -%d 1", arguments[0], i+1);
// Spawn the next test in a new process.
if (system(runNextTest))
{
(void)openTestLog(false);
logTestString("\n******** Test failure ********\n"\
"Test %d '%s' failed\n"\
"******** Test failure ********\n",
i, tests[i].testName);
++fails;
}
else
(void)openTestLog(false);
}
else
{
if (!tests[i].testSignature())
{
logTestString("\n******** Test failure ********\n"\
"Test %d '%s' failed\n"\
"******** Test failure ********\n",
i, tests[i].testName);
++fails;
}
}
}
}
const int passed = testCount - fails;
logTestString("\nTests finished. %d test%s of %d passed.\n\n",
passed, 1 == passed ? "" : "s", testCount);
if(0 == fails && testCount==tests.size())
{
time_t rawtime;
struct tm * timeinfo;
(void)time(&rawtime);
timeinfo = gmtime(&rawtime);
(void)printf("\nTest suite pass at GMT %s\n", asctime(timeinfo));
FILE * testsLastPassedAtFile = fopen("tests-last-passed-at.txt", "w");
if(testsLastPassedAtFile)
{
(void)fprintf(testsLastPassedAtFile, "Tests finished. %d test%s of %d passed.\n",
passed, 1 == passed ? "" : "s", numberOfTests);
#ifdef _DEBUG
(void)fprintf(testsLastPassedAtFile, "Compiled as DEBUG\n");
#else
(void)fprintf(testsLastPassedAtFile, "Compiled as RELEASE\n");
#endif
(void)fprintf(testsLastPassedAtFile, "Test suite pass at GMT %s\n", asctime(timeinfo));
(void)fclose(testsLastPassedAtFile);
}
}
closeTestLog();
#ifdef _IRR_WINDOWS_
(void)system("tests.log");
#else
(void)system("$PAGER tests.log");
#endif
return fails;
}
else
{
const bool res = tests[testToRun].testSignature();
closeTestLog();
return res?0:1;
}
}
| 25.475096 | 110 | 0.650023 | [
"vector",
"3d"
] |
a0a9fae364d6860219dce2a031450125f43fe5d6 | 2,433 | hpp | C++ | doc/quickbook/oglplus/quickref/enums/capability_class.hpp | matus-chochlik/oglplus | 76dd964e590967ff13ddff8945e9dcf355e0c952 | [
"BSL-1.0"
] | 364 | 2015-01-01T09:38:23.000Z | 2022-03-22T05:32:00.000Z | doc/quickbook/oglplus/quickref/enums/capability_class.hpp | matus-chochlik/oglplus | 76dd964e590967ff13ddff8945e9dcf355e0c952 | [
"BSL-1.0"
] | 55 | 2015-01-06T16:42:55.000Z | 2020-07-09T04:21:41.000Z | doc/quickbook/oglplus/quickref/enums/capability_class.hpp | matus-chochlik/oglplus | 76dd964e590967ff13ddff8945e9dcf355e0c952 | [
"BSL-1.0"
] | 57 | 2015-01-07T18:35:49.000Z | 2022-03-22T05:32:04.000Z | // File doc/quickbook/oglplus/quickref/enums/capability_class.hpp
//
// Automatically generated file, DO NOT modify manually.
// Edit the source 'source/enums/oglplus/capability.txt'
// or the 'source/enums/make_enum.py' script instead.
//
// Copyright 2010-2019 Matus Chochlik.
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
//[oglplus_enums_capability_class
#if !__OGLPLUS_NO_ENUM_VALUE_CLASSES
namespace enums {
template <typename Base, template <__Capability> class Transform>
class __EnumToClass<Base, __Capability, Transform> /*<
Specialization of __EnumToClass for the __Capability enumeration.
>*/
: public Base {
public:
EnumToClass();
EnumToClass(Base&& base);
Transform<Capability::PrimitiveRestart> PrimitiveRestart;
Transform<Capability::DepthTest> DepthTest;
Transform<Capability::StencilTest> StencilTest;
Transform<Capability::ScissorTest> ScissorTest;
Transform<Capability::CullFace> CullFace;
Transform<Capability::RasterizerDiscard> RasterizerDiscard;
Transform<Capability::PolygonOffsetPoint> PolygonOffsetPoint;
Transform<Capability::PolygonOffsetLine> PolygonOffsetLine;
Transform<Capability::PolygonOffsetFill> PolygonOffsetFill;
Transform<Capability::Blend> Blend;
Transform<Capability::ColorLogicOp> ColorLogicOp;
Transform<Capability::Dither> Dither;
Transform<Capability::Multisample> Multisample;
Transform<Capability::SampleShading> SampleShading;
Transform<Capability::LineSmooth> LineSmooth;
Transform<Capability::PolygonSmooth> PolygonSmooth;
Transform<Capability::ProgramPointSize> ProgramPointSize;
Transform<Capability::TextureCubeMapSeamless> TextureCubeMapSeamless;
Transform<Capability::SampleAlphaToCoverage> SampleAlphaToCoverage;
Transform<Capability::SampleAlphaToOne> SampleAlphaToOne;
Transform<Capability::SampleCoverage> SampleCoverage;
Transform<Capability::SampleMask> SampleMask;
Transform<Capability::FramebufferSRGB> FramebufferSRGB;
Transform<Capability::DebugOutputSynchronous> DebugOutputSynchronous;
Transform<Capability::StreamRasterization> StreamRasterization;
Transform<Capability::BlendAdvancedCoherent> BlendAdvancedCoherent;
Transform<Capability::FragmentCoverageToColor> FragmentCoverageToColor;
};
} // namespace enums
#endif
//]
| 42.684211 | 75 | 0.792437 | [
"transform"
] |
a0a9ff146a9d12286b86ac7aa497c2137e0d2a72 | 9,085 | cpp | C++ | src/grt/src/MakeWireParasitics.cpp | ravi-varadarajan/OpenROAD | dc228c6a539157349d9391d893ed255b51dd4f64 | [
"BSD-3-Clause-Clear"
] | null | null | null | src/grt/src/MakeWireParasitics.cpp | ravi-varadarajan/OpenROAD | dc228c6a539157349d9391d893ed255b51dd4f64 | [
"BSD-3-Clause-Clear"
] | null | null | null | src/grt/src/MakeWireParasitics.cpp | ravi-varadarajan/OpenROAD | dc228c6a539157349d9391d893ed255b51dd4f64 | [
"BSD-3-Clause-Clear"
] | null | null | null | /////////////////////////////////////////////////////////////////////////////
//
// BSD 3-Clause License
//
// Copyright (c) 2019, The Regents of the University of California
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of the 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.
//
///////////////////////////////////////////////////////////////////////////////
#include "MakeWireParasitics.h"
#include "db_sta/dbNetwork.hh"
#include "db_sta/dbSta.hh"
#include "sta/ArcDelayCalc.hh"
#include "sta/Corner.hh"
#include "sta/Parasitics.hh"
#include "sta/ParasiticsClass.hh"
#include "sta/Sdc.hh"
#include "sta/StaState.hh"
#include "sta/Units.hh"
#include "utl/Logger.h"
namespace grt {
using utl::GRT;
using std::abs;
using std::min;
MakeWireParasitics::MakeWireParasitics(ord::OpenRoad* openroad,
GlobalRouter* grouter)
{
grouter_ = grouter;
logger_ = openroad->getLogger();
sta_ = openroad->getSta();
tech_ = openroad->getDb()->getTech();
parasitics_ = sta_->parasitics();
corner_ = sta_->cmdCorner();
min_max_ = sta::MinMax::max();
analysis_point_ = corner_->findParasiticAnalysisPt(min_max_);
network_ = openroad->getDbNetwork();
sta_net_ = nullptr;
parasitic_ = nullptr;
node_id_ = 0;
}
void MakeWireParasitics::estimateParasitcs(odb::dbNet* net,
std::vector<Pin>& pins,
std::vector<GSegment>& routes)
{
debugPrint(logger_, GRT, "est_rc", 1, "net {}", net->getConstName());
sta_net_ = network_->dbToSta(net);
node_id_ = 0;
node_map_.clear();
parasitic_
= parasitics_->makeParasiticNetwork(sta_net_, false, analysis_point_);
makePinRoutePts(pins);
makeRouteParasitics(net, routes);
makeParasiticsToGrid(pins);
reduceParasiticNetwork();
}
void MakeWireParasitics::makePinRoutePts(std::vector<Pin>& pins)
{
for (Pin& pin : pins) {
sta::Pin* sta_pin = staPin(pin);
sta::ParasiticNode* pin_node
= parasitics_->ensureParasiticNode(parasitic_, sta_pin);
RoutePt route_pt = routePt(pin);
node_map_[route_pt] = pin_node;
}
}
RoutePt MakeWireParasitics::routePt(Pin& pin)
{
const odb::Point& pt = pin.getPosition();
int layer = pin.getTopLayer();
return RoutePt(pt.getX(), pt.getY(), layer);
}
sta::Pin* MakeWireParasitics::staPin(Pin& pin)
{
if (pin.isPort())
return network_->dbToSta(pin.getBTerm());
else
return network_->dbToSta(pin.getITerm());
}
void MakeWireParasitics::makeRouteParasitics(odb::dbNet* net,
std::vector<GSegment>& routes)
{
for (GSegment& route : routes) {
sta::ParasiticNode* n1
= ensureParasiticNode(route.init_x, route.init_y, route.init_layer);
sta::ParasiticNode* n2
= ensureParasiticNode(route.final_x, route.final_y, route.final_layer);
int wire_length_dbu
= abs(route.init_x - route.final_x) + abs(route.init_y - route.final_y);
sta::Units* units = sta_->units();
float res = 0.0;
float cap = 0.0;
if (wire_length_dbu == 0) {
// via
int lower_layer = min(route.init_layer, route.final_layer);
odb::dbTechLayer* cut_layer
= tech_->findRoutingLayer(lower_layer)->getUpperLayer();
res = cut_layer->getResistance(); // assumes single cut
cap = 0.0;
debugPrint(logger_,
GRT,
"est_rc",
1,
"{} -> {} via r={}",
parasitics_->name(n1),
parasitics_->name(n2),
units->resistanceUnit()->asString(res));
} else if (route.init_layer == route.final_layer) {
layerRC(wire_length_dbu, route.init_layer, res, cap);
debugPrint(logger_,
GRT,
"est_rc",
1,
"{} -> {} {}u layer={} r={} c={}",
parasitics_->name(n1),
parasitics_->name(n2),
static_cast<int>(dbuToMeters(wire_length_dbu) * 1e+6),
route.init_layer,
units->resistanceUnit()->asString(res),
units->capacitanceUnit()->asString(cap));
} else
logger_->warn(GRT, 25, "non wire or via route found on net {}.",
net->getConstName());
parasitics_->incrCap(n1, cap / 2.0, analysis_point_);
parasitics_->makeResistor(nullptr, n1, n2, res, analysis_point_);
parasitics_->incrCap(n2, cap / 2.0, analysis_point_);
}
}
void MakeWireParasitics::makeParasiticsToGrid(std::vector<Pin>& pins)
{
for (Pin& pin : pins) {
RoutePt route_pt = routePt(pin);
sta::ParasiticNode* pin_node = node_map_[route_pt];
makeParasiticsToGrid(pin, pin_node);
}
}
// Make parasitics for the wire from the pin to the grid location of the pin.
void MakeWireParasitics::makeParasiticsToGrid(Pin& pin,
sta::ParasiticNode* pin_node)
{
const odb::Point& grid_pt = pin.getOnGridPosition();
int layer = pin.getTopLayer();
RoutePt route_pt(grid_pt.getX(), grid_pt.getY(), layer);
sta::ParasiticNode* grid_node = node_map_[route_pt];
if (grid_node) {
const odb::Point& pt = pin.getPosition();
int wire_length_dbu
= abs(pt.getX() - grid_pt.getX()) + abs(pt.getY() - grid_pt.getY());
float res, cap;
layerRC(wire_length_dbu, layer, res, cap);
parasitics_->incrCap(pin_node, cap / 2.0, analysis_point_);
parasitics_->makeResistor(
nullptr, pin_node, grid_node, res, analysis_point_);
parasitics_->incrCap(grid_node, cap / 2.0, analysis_point_);
} else {
logger_->warn(GRT, 26, "missing route to pin {}.", pin.getName());
}
}
void MakeWireParasitics::layerRC(int wire_length_dbu,
int layer_id,
// Return values.
float& res,
float& cap)
{
odb::dbTechLayer* layer = tech_->findRoutingLayer(layer_id);
float layer_width = grouter_->dbuToMicrons(layer->getWidth());
float res_ohm_per_micron = layer->getResistance() / layer_width;
float cap_pf_per_micron
= layer_width * layer->getCapacitance() + 2 * layer->getEdgeCapacitance();
float r_per_meter = 1E+6 * res_ohm_per_micron; // ohm/meter
float cap_per_meter = 1E+6 * 1E-12 * cap_pf_per_micron; // F/meter
float wire_length = dbuToMeters(wire_length_dbu);
res = r_per_meter * wire_length;
cap = cap_per_meter * wire_length;
}
double MakeWireParasitics::dbuToMeters(int dbu)
{
return (double) dbu / (tech_->getDbUnitsPerMicron() * 1E+6);
}
sta::ParasiticNode* MakeWireParasitics::ensureParasiticNode(int x,
int y,
int layer)
{
RoutePt pin_loc(x, y, layer);
sta::ParasiticNode* node = node_map_[pin_loc];
if (node == nullptr) {
node = parasitics_->ensureParasiticNode(parasitic_, sta_net_, node_id_++);
node_map_[pin_loc] = node;
}
return node;
}
void MakeWireParasitics::reduceParasiticNetwork()
{
sta::Sdc* sdc = sta_->sdc();
sta::OperatingConditions* op_cond = sdc->operatingConditions(min_max_);
sta::ReducedParasiticType reduce_to
= sta_->arcDelayCalc()->reducedParasiticType();
parasitics_->reduceTo(parasitic_,
sta_net_,
reduce_to,
op_cond,
corner_,
min_max_,
analysis_point_);
parasitics_->deleteParasiticNetwork(sta_net_, analysis_point_);
}
} // namespace grt
| 35.488281 | 80 | 0.627188 | [
"vector"
] |
a0aadee2d0fa9323e3318adee27f36f5f1e03290 | 5,299 | cpp | C++ | src/program/evolution-sequential.cpp | demiurge-project/ARGoS3-NEAT | bcd6d3073cc00c8d8958f09c748b9bef2559605e | [
"Apache-2.0"
] | 1 | 2020-01-14T10:59:19.000Z | 2020-01-14T10:59:19.000Z | src/program/evolution-sequential.cpp | demiurge-project/ARGoS3-NEAT | bcd6d3073cc00c8d8958f09c748b9bef2559605e | [
"Apache-2.0"
] | null | null | null | src/program/evolution-sequential.cpp | demiurge-project/ARGoS3-NEAT | bcd6d3073cc00c8d8958f09c748b9bef2559605e | [
"Apache-2.0"
] | 1 | 2020-08-14T08:27:45.000Z | 2020-08-14T08:27:45.000Z | // Standard C++ Library
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <math.h>
// NEAT
#include "../NEAT/experiments.h"
// ARGOS
#include <argos3/core/simulator/simulator.h>
#include <argos3/core/simulator/loop_functions.h>
#include <argos3/core/simulator/visualization/visualization.h>
// Controller
#include "../NEATController.h"
// Loop function
#include <argos3/demiurge/loop-functions/CoreLoopFunctions.h>
/**
* Function that launches the experiment and evaluates this last one.
* @note: To launch your own program: you can use, for example, system("") which is a combination of fork(), exec() and waitpid().
*/
void launchARGoSAndEvaluate(NEAT::Population& pop, unsigned int num_runs_per_gen) {
// The CSimulator class of ARGoS is a singleton.
static argos::CSimulator& cSimulator = argos::CSimulator::GetInstance();
// Get a reference to the loop functions (the evaluation is done by the loop fct)
static CoreLoopFunctions& cLoopFunctions = dynamic_cast<CoreLoopFunctions&>(cSimulator.GetLoopFunctions());
// Produce the different random seeds for the experiment
argos::CRandom::CreateCategory("neat", 1);
argos::CRandom::CRNG* pRNG = argos::CRandom::CreateRNG("neat");
std::vector<UInt32> vecRandomSeed;
for(size_t i=0; i<num_runs_per_gen; i++) {
vecRandomSeed.push_back( pRNG->Uniform(argos::CRange<UInt32>(0, UINT32_MAX)) );
}
int i=0;
for(std::vector<Organism*>::iterator itOrg = (pop.organisms).begin(); itOrg != (pop.organisms).end(); ++itOrg, ++i) {
std::cout << "\nOrganism[" << i << "]: " << std::endl;
// Set the neural network
CSpace::TMapPerType cEntities = cSimulator.GetSpace().GetEntitiesByType("controller");
for (CSpace::TMapPerType::iterator it = cEntities.begin(); it != cEntities.end(); ++it) {
CControllableEntity* pcEntity = any_cast<CControllableEntity*>(it->second);
try {
CEPuckNEATController& cController = dynamic_cast<CEPuckNEATController&>(pcEntity->GetController());
cController.SetNetwork(*((*itOrg)->net));
} catch (std::exception& ex) {
LOGERR << "Error while setting network: " << ex.what() << std::endl;
}
}
// Launch the experiment with the specified random seed, and get the score
double dPerformance = 0.0;
for(size_t j = 0; j < num_runs_per_gen; j++) {
std::cout << "Random seed: " << vecRandomSeed[j] << std::endl;
cSimulator.SetRandomSeed(vecRandomSeed[j]);
cSimulator.Reset();
cSimulator.Execute();
dPerformance += cLoopFunctions.GetObjectiveFunction();
}
// Compute the average performance
if(num_runs_per_gen > 0) {
dPerformance /= num_runs_per_gen;
}
// The evaluation of this network is stored in the fitness
(*itOrg)->fitness = dPerformance;
std::cout << "--> Average fitness = " << (*itOrg)->fitness << std::endl;
}
}
/**
* Function that launches the experiment and evaluates this last one.
* @note: To launch your own program: you can use, for example, system("") which is a combination of fork(), exec() and waitpid().
* TODO: set the random seed
*/
/*double launchARGoSAndEvaluate(NEAT::Network& net) {
// The CSimulator class of ARGoS is a singleton.
static argos::CSimulator& cSimulator = argos::CSimulator::GetInstance();
// Get a reference to the loop functions (the evaluation is done by the loop fct)
static CoreLoopFunctions& cLoopFunctions = dynamic_cast<CoreLoopFunctions&>(cSimulator.GetLoopFunctions());
// Launch the experiment with the correct network
cSimulator.Reset();
cLoopFunctions.ConfigureFromNetwork(net);
cSimulator.Execute();
// Return the evaluation of this network
return cLoopFunctions.getPerformance();
}*/
/**
* Main program.
*/
int main(int argc, char *argv[]) {
// Check the arguments
if (argc < 4) {
std::cerr << "Arg1: A configuration file (.argos or .xml) is required for ARGoS." << std::endl;
std::cerr << "Arg2: A NEAT parameters file (.ne file) is required to run the experiments." << std::endl;
std::cerr << "Arg3: A starter genome file is required for the creation of the initial population." << std::endl;
std::cerr << "Arg4 (optional): The seed (unsigned integer) used to initialize NEAT. If none is specified, then NEAT will initialize with the current time" << std::endl;
return -1;
}
// Checks the seed (if it exists)
int seed = 0;
if (argc >= 5) {
try {
seed = atoi(argv[4]);
}
catch (const std::invalid_argument& err) {
std::cerr << "Invalid argument: " << err.what() << std::endl;
std::cerr << "The seed will be left at 0!" << std::endl;
}
}
// Initialization of ARGoS
argos::CSimulator& cSimulator = argos::CSimulator::GetInstance();
cSimulator.SetExperimentFileName(argv[1]);
cSimulator.LoadExperiment();
// Launch NEAT with the specified experiment
launchNEAT(argv[2], argv[3], launchARGoSAndEvaluate, seed);
std::cout << "/* End of evolution... */" << std::endl;
std::cout << "/* Output files writen in gen/ folder */" << std::endl;
// Dispose of ARGoS stuff
cSimulator.Destroy();
return 0;
}
| 36.544828 | 174 | 0.661823 | [
"vector"
] |
a0b2702b4de76e56c39272c1d507468a4634904e | 5,723 | hpp | C++ | include/testmatch/helpers.hpp | LiamBlake/TestMatch-Backend | 58f48641857042aa52c383db6e3b6d994be91479 | [
"MIT"
] | 1 | 2021-03-28T09:46:39.000Z | 2021-03-28T09:46:39.000Z | include/testmatch/helpers.hpp | LiamBlake/TestMatch | aae0cb0863b76dc9a53d95dffe6788a49fa9ec0e | [
"MIT"
] | 16 | 2021-03-28T09:50:48.000Z | 2021-09-15T19:13:17.000Z | include/testmatch/helpers.hpp | LiamBlake/TestMatch | aae0cb0863b76dc9a53d95dffe6788a49fa9ec0e | [
"MIT"
] | null | null | null | // -*- lsst-c++ -*-
/* Utility.h
*
* Contains various helper functions used throughout the program. Includes
* functions for converting between strings and their encodings as integers, and
* vice-versa. These are used primarily in conversions from simulation backend
* to printed/displayed results (e.g. a scorecard or ball-by-ball description).
*
* Note that all the functions here are defined and implementated here (with the
* inline keyword). This is probably bad practice, but I wanted to avoid having
* an additional .cpp file since no class is declared here. If I need to declare
* a class here for whatever reason, I will probably move the implementations
* here to a .cpp, but for now, the header is all we need.
*
*/
#ifndef UTILITY_H
#define UTILITY_H
#include "enums.hpp"
#include <cmath>
#include <exception>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
// For the sake of formatting, allow integers and strings to be added
// std::string operator+() {};
/* Add new entry to end of array - reallocates memory dynamically.
Deletes the old array and returns a pointer to the new.
Arguments:
T* arr - pointer to array of type T
int old_length - length of array arr
T new_entry - item to add to end of array arr
This exists because overs can contain an arbitrary amount of balls
(due to extras), but I don't want to use vectors since I will be wasting
a lot of memory.
*/
template <class T>
inline T* arr_add_item(T* arr, int old_length, T new_entry) {
// Reallocate array
T* new_arr = new T[old_length + 1];
if (old_length > 0) {
for (int i = 0; i < old_length; i++) {
new_arr[i] = arr[i];
}
delete[] arr;
}
delete[] arr;
arr[old_length] = new_entry;
return arr;
}
inline std::vector<std::string> split_str(std::string str,
std::string delim = ",") {
/* TODO: implement with string* return type to save memory,
ideally using the arr_add_item template defined in
Utility.h. Attempts at this have been giving strange
results, where the while loop won't iterate unless
cout << len << endl is included at the start of the
loop.
*/
std::vector<std::string> token;
// Check for boundary cases
if (str.length() == 0) {
return token;
}
size_t curr, prev = 0;
curr = str.find(delim);
// Check delim is actually present in string
if (curr == std::string::npos) {
token.push_back(str);
return token;
}
while (curr != std::string::npos) {
token.push_back(str.substr(prev, curr - prev));
prev = curr + delim.length();
curr = str.find(delim, prev);
}
// Add remaining string
token.push_back(str.substr(prev, curr - prev));
return token;
}
inline std::string join_str(std::vector<std::string> str_comp,
std::string join) {
std::string output = "";
for (std::string x : str_comp) {
output += x + join;
}
// Remove last join added in above loop
return output.substr(0, output.size() - join.size());
}
template <typename T>
T sample_cdf(T* values, int length, double* dist) {
// Generate random number
double r = ((double)rand() / (RAND_MAX));
// Iterate through distribution until first entry > r
int i = 0;
while (++i < length && r > dist[i])
;
return values[i - 1];
}
// Converts ball count to overs and balls
inline std::pair<int, int> balls_to_ov(unsigned int balls) {
std::pair<int, int> output((int)balls / 6, balls % 6);
return output;
}
// Generates a realisation of a truncated exponential distribution
inline double rtexp(double mean, double min, double max) {
double Fmin = exp(min);
double Fmax = exp(max);
// Generate uniform random number
double r = ((double)rand() / (RAND_MAX));
// Inverse sampling
double p = r * (Fmax - Fmin) + Fmin;
return -mean * log(1 - p);
}
template <typename T>
inline void delete_linkedlist(T* first) {
T* next = first;
while (next != nullptr) {
T* tmp = next;
next = next->get_next();
delete tmp;
}
}
/**
* @brief Converts integer to ordinal string
* @param num Integer to be converted
* @return Converted string
*
* e.g. ordinal(1) returns "1st", ordinal(15) returns "15th"
*/
inline std::string ordinal(int num) {
std::string output = std::to_string(num);
char fin = output.back();
if (fin == '1') {
output += "st";
} else if (fin == '2') {
output += "nd";
} else if (fin == '3') {
output += "rd";
} else {
output += "th";
}
return output;
}
/**
* @brief Determine whether a given bowling type is "slow" (i.e. spin or medium
* pace)
* @param bowl_type The bowling type, encoding as the appropriate enum.
* @return A boolean indicating whether the bowling type is slow (true) or not
* (false).
*
* The passed bowling type is checked via a switch statement.
*/
bool is_slow_bowler(BowlType bowl_type);
/**
* @brief Performs Box-Cox transform given power parameter
*
* @param x value to transform
* @param lambda power parameter
* @return transformed value
*/
inline double boxcox(double x, double lambda) {
if (x < 0) {
// raise exception
throw std::invalid_argument(
"Value to transform must be greater than 0");
}
if (lambda == 0) {
return log(x);
} else {
return (pow(x, lambda) - 1) / lambda;
}
}
#endif // UTILITY_H
| 26.995283 | 80 | 0.615062 | [
"vector",
"transform"
] |
a0b2a342e57646e088e61cdabd85cfb96d9a55ef | 336 | cpp | C++ | foo.cpp | RCoeurjoly/CPP-Crash-Course | 17f98e5d0b6c6d62acaab96b8210d2050ce72c64 | [
"MIT"
] | null | null | null | foo.cpp | RCoeurjoly/CPP-Crash-Course | 17f98e5d0b6c6d62acaab96b8210d2050ce72c64 | [
"MIT"
] | null | null | null | foo.cpp | RCoeurjoly/CPP-Crash-Course | 17f98e5d0b6c6d62acaab96b8210d2050ce72c64 | [
"MIT"
] | null | null | null | #include <iostream>
#include <stdexcept>
#include <fstream>
#include <sstream>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
#include <stdio.h>
using namespace std;
float foo( float a=0, float b=1, float c=2 ){return a+b+c;}
int main() {
cout << foo(1) << endl << foo(1,2) << endl << foo(1,2,3) << endl;
}
| 19.764706 | 67 | 0.645833 | [
"vector"
] |
a0b713159b3c951339345a486bc84e205cb55332 | 3,248 | cpp | C++ | example/windows/main.cpp | drisme/fb_auth | 20355f7df9286c42b73a10a2ac2f94035bb5d219 | [
"MIT"
] | 3 | 2019-10-16T19:26:24.000Z | 2020-05-21T07:29:30.000Z | example/windows/main.cpp | Jeremywhiteley/fb_auth | c76a274f05996291aeed1838df2b8ed818a9f3bb | [
"MIT"
] | null | null | null | example/windows/main.cpp | Jeremywhiteley/fb_auth | c76a274f05996291aeed1838df2b8ed818a9f3bb | [
"MIT"
] | 1 | 2021-01-21T02:50:44.000Z | 2021-01-21T02:50:44.000Z | // Copyright 2018 Google LLC
//
// 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 <flutter/flutter_view_controller.h>
#include <windows.h>
#include <codecvt>
#include <iostream>
#include <string>
#include <vector>
#include "flutter/generated_plugin_registrant.h"
#include "win32_window.h"
#include "window_configuration.h"
namespace {
// Returns the path of the directory containing this executable, or an empty
// string if the directory cannot be found.
std::string GetExecutableDirectory() {
wchar_t buffer[MAX_PATH];
if (GetModuleFileName(nullptr, buffer, MAX_PATH) == 0) {
std::cerr << "Couldn't locate executable" << std::endl;
return "";
}
std::wstring_convert<std::codecvt_utf8<wchar_t>> wide_to_utf8;
std::string executable_path = wide_to_utf8.to_bytes(buffer);
size_t last_separator_position = executable_path.find_last_of('\\');
if (last_separator_position == std::string::npos) {
std::cerr << "Unabled to find parent directory of " << executable_path
<< std::endl;
return "";
}
return executable_path.substr(0, last_separator_position);
}
} // namespace
int APIENTRY wWinMain(HINSTANCE instance, HINSTANCE prev, wchar_t *command_line,
int show_command) {
// Attach to console when present (e.g., 'flutter run') or create a
// new console when running with a debugger.
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
::AllocConsole();
}
// Resources are located relative to the executable.
std::string base_directory = GetExecutableDirectory();
if (base_directory.empty()) {
base_directory = ".";
}
std::string data_directory = base_directory + "\\data";
std::string assets_path = data_directory + "\\flutter_assets";
std::string icu_data_path = data_directory + "\\icudtl.dat";
// Arguments for the Flutter Engine.
std::vector<std::string> arguments;
// Top-level window frame.
Win32Window::Point origin(kFlutterWindowOriginX, kFlutterWindowOriginY);
Win32Window::Size size(kFlutterWindowWidth, kFlutterWindowHeight);
flutter::FlutterViewController flutter_controller(
icu_data_path, size.width, size.height, assets_path, arguments);
RegisterPlugins(&flutter_controller);
// Create a top-level win32 window to host the Flutter view.
Win32Window window;
if (!window.CreateAndShow(kFlutterWindowTitle, origin, size)) {
return EXIT_FAILURE;
}
// Parent and resize Flutter view into top-level window.
window.SetChildContent(flutter_controller.GetNativeWindow());
// Run messageloop with a hook for flutter_view to do work.
window.RunMessageLoop(
[&flutter_controller]() { flutter_controller.ProcessMessages(); });
return EXIT_SUCCESS;
}
| 34.924731 | 80 | 0.730296 | [
"vector"
] |
a0bcd972a3087d85ec90d60325b27486cf4de9bd | 4,229 | cpp | C++ | adaptors/base/separate-update-render/update-thread.cpp | pwisbey/dali-adaptor | 21d5e77316e53285fa1e210a93b13cf9889e3b54 | [
"Apache-2.0"
] | null | null | null | adaptors/base/separate-update-render/update-thread.cpp | pwisbey/dali-adaptor | 21d5e77316e53285fa1e210a93b13cf9889e3b54 | [
"Apache-2.0"
] | null | null | null | adaptors/base/separate-update-render/update-thread.cpp | pwisbey/dali-adaptor | 21d5e77316e53285fa1e210a93b13cf9889e3b54 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2015 Samsung Electronics Co., Ltd.
*
* 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.
*
*/
// CLASS HEADER
#include "update-thread.h"
// EXTERNAL INCLUDES
#include <cstdio>
// INTERNAL INCLUDES
#include <dali/integration-api/debug.h>
#include <base/interfaces/adaptor-internal-services.h>
#include <base/separate-update-render/thread-synchronization.h>
#include <base/environment-options.h>
namespace Dali
{
namespace Internal
{
namespace Adaptor
{
namespace
{
#if defined(DEBUG_ENABLED)
Integration::Log::Filter* gUpdateLogFilter = Integration::Log::Filter::New(Debug::NoLogging, false, "LOG_UPDATE_THREAD");
#endif
} // unnamed namespace
UpdateThread::UpdateThread( ThreadSynchronization& sync,
AdaptorInternalServices& adaptorInterfaces,
const EnvironmentOptions& environmentOptions )
: mThreadSynchronization( sync ),
mCore( adaptorInterfaces.GetCore()),
mFpsTracker( environmentOptions ),
mUpdateStatusLogger( environmentOptions ),
mThread( NULL ),
mEnvironmentOptions( environmentOptions )
{
}
UpdateThread::~UpdateThread()
{
Stop();
}
void UpdateThread::Start()
{
DALI_LOG_INFO( gUpdateLogFilter, Debug::Verbose, "UpdateThread::Start()\n");
if ( !mThread )
{
// Create and run the update-thread
mThread = new pthread_t();
int error = pthread_create( mThread, NULL, InternalThreadEntryFunc, this );
DALI_ASSERT_ALWAYS( !error && "Return code from pthread_create() in UpdateThread" );
}
}
void UpdateThread::Stop()
{
DALI_LOG_INFO( gUpdateLogFilter, Debug::Verbose, "UpdateThread::Stop()\n");
if( mThread )
{
// wait for the thread to finish
pthread_join(*mThread, NULL);
delete mThread;
mThread = NULL;
}
}
bool UpdateThread::Run()
{
DALI_LOG_INFO( gUpdateLogFilter, Debug::Verbose, "UpdateThread::Run()\n");
// Install a function for logging
mEnvironmentOptions.InstallLogFunction();
Integration::UpdateStatus status;
bool runUpdate = true;
float lastFrameDelta( 0.0f );
unsigned int lastSyncTime( 0 );
unsigned int nextSyncTime( 0 );
// Update loop, we stay inside here while the update-thread is running
// We also get the last delta and the predict when this update will be rendered
while ( mThreadSynchronization.UpdateReady( status.NeedsNotification(), runUpdate, lastFrameDelta, lastSyncTime, nextSyncTime ) )
{
DALI_LOG_INFO( gUpdateLogFilter, Debug::Verbose, "UpdateThread::Run. 1 - UpdateReady(delta:%f, lastSync:%u, nextSync:%u)\n", lastFrameDelta, lastSyncTime, nextSyncTime);
DALI_LOG_INFO( gUpdateLogFilter, Debug::Verbose, "UpdateThread::Run. 2 - Core.Update()\n");
mThreadSynchronization.AddPerformanceMarker( PerformanceInterface::UPDATE_START );
mCore.Update( lastFrameDelta, lastSyncTime, nextSyncTime, status );
mThreadSynchronization.AddPerformanceMarker( PerformanceInterface::UPDATE_END );
mFpsTracker.Track( status.SecondsFromLastFrame() );
unsigned int keepUpdatingStatus = status.KeepUpdating();
// Optional logging of update/render status
mUpdateStatusLogger.Log( keepUpdatingStatus );
// 2 things can keep update running.
// - The status of the last update
// - The status of the last render
runUpdate = (Integration::KeepUpdating::NOT_REQUESTED != keepUpdatingStatus);
DALI_LOG_INFO( gUpdateLogFilter, Debug::Verbose, "UpdateThread::Run. 3 - runUpdate(%d)\n", runUpdate );
// Reset time variables
lastFrameDelta = 0.0f;
lastSyncTime = 0;
nextSyncTime = 0;
}
// Uninstall the logging function
mEnvironmentOptions.UnInstallLogFunction();
return true;
}
} // namespace Adaptor
} // namespace Internal
} // namespace Dali
| 29.368056 | 173 | 0.725467 | [
"render"
] |
a0bdbbd24c6874cad6947bfc6c3c3c9c17ae90ca | 4,134 | cc | C++ | src/sol/model/olm/cw.cc | awong100/SOL | 1c522a1b667d258f4c9482788c19b74cdf9e6d69 | [
"Apache-2.0"
] | 84 | 2016-08-27T13:13:41.000Z | 2021-04-28T14:24:57.000Z | src/sol/model/olm/cw.cc | awong100/SOL | 1c522a1b667d258f4c9482788c19b74cdf9e6d69 | [
"Apache-2.0"
] | 9 | 2017-01-23T01:12:20.000Z | 2020-08-29T07:46:28.000Z | src/sol/model/olm/cw.cc | awong100/SOL | 1c522a1b667d258f4c9482788c19b74cdf9e6d69 | [
"Apache-2.0"
] | 37 | 2016-09-05T06:27:39.000Z | 2021-04-15T02:17:29.000Z | /*********************************************************************************
* File Name : cw.cc
* Created By : yuewu
* Description : Confidence Weighted Online Learning
**********************************************************************************/
#include "sol/model/olm/cw.h"
#include <cmath>
using namespace std;
using namespace sol;
using namespace sol::math;
namespace sol {
namespace model {
CW::CW(int class_num)
: OnlineLinearModel(class_num),
hinge_base_(nullptr),
a_(1.f),
phi_(0.5244f) {
this->Sigmas_ = new math::Vector<real_t>[this->clf_num_];
for (int i = 0; i < this->clf_num_; ++i) {
this->Sigmas_[i].resize(this->dim_);
this->Sigmas_[i] = this->a_;
}
// loss
if (class_num == 2) {
this->SetParameter("loss", "hinge");
} else {
this->SetParameter("loss", "maxscore-hinge");
}
}
CW::~CW() { DeleteArray(this->Sigmas_); }
void CW::SetParameter(const std::string& name, const std::string& value) {
if (name == "a") {
this->a_ = stof(value);
for (int i = 0; i < this->clf_num_; ++i) {
this->Sigmas_[i] = this->a_;
}
} else if (name == "phi") {
this->phi_ = stof(value);
this->require_reinit_ = true;
} else if (name == "loss") {
OnlineLinearModel::SetParameter(name, value);
if ((this->loss_->type() & loss::Loss::Type::HINGE) == 0) {
throw invalid_argument("only hinge-based loss functions are allowed");
}
this->hinge_base_ = static_cast<loss::HingeBase*>(this->loss_);
} else if (name == "bias_eta") {
OnlineLinearModel::SetParameter(name, value);
this->require_reinit_ = true;
} else {
OnlineLinearModel::SetParameter(name, value);
}
}
void CW::BeginTrain() {
OnlineLinearModel::BeginTrain();
math::Vector<real_t>* sigmas = this->Sigmas_;
float* vt = &this->Vi_;
float bias_eta = this->bias_eta();
float phi = this->phi_;
this->hinge_base_->set_margin([sigmas, vt, bias_eta, phi](
const pario::DataPoint& dp, float* predict, label_t predict_label,
float* gradient, int cls_num) {
const auto& x = dp.data();
*vt = 0.f;
//(\delta \psi)(x,i) = -g(i) * x
for (int c = 0; c < cls_num; ++c) {
if (gradient[c] == 0) continue;
float gc2 = gradient[c] * gradient[c];
*vt += expr::dotmul(sigmas[c], L2(x)) * gc2;
if (bias_eta != 0) *vt += sigmas[c][0] * gc2;
}
return phi * *vt;
});
}
void CW::Update(const pario::DataPoint& dp, const float*, float loss) {
const auto& x = dp.data();
float Mi = phi_ * Vi_ - loss;
float tmp = (1 + 2 * phi_ * Mi);
float alpha_i =
(-(1 + 2 * phi_ * Mi) + sqrtf(tmp * tmp - 8 * phi_ * (Mi - phi_ * Vi_))) /
(4 * phi_ * Vi_);
this->eta_ = alpha_i;
tmp = 2 * alpha_i * phi_;
for (int c = 0; c < this->clf_num_; ++c) {
if (g(c) == 0) continue;
w(c) -= eta_ * g(c) * Sigmas_[c] * x;
// update bias
w(c)[0] -= bias_eta() * g(c) * Sigmas_[c][0];
// update sigma
Sigmas_[c] /= (1.f + tmp * Sigmas_[c] * L2(x));
Sigmas_[c][0] /= (1.f + tmp * Sigmas_[c][0]);
}
}
void CW::update_dim(index_t dim) {
if (dim > this->dim_) {
float a = this->a_;
for (int c = 0; c < this->clf_num_; ++c) {
math::Vector<real_t>& Sigma = this->Sigmas_[c];
Sigma.resize(dim);
Sigma.slice_op([a](real_t& val) { val = a; }, this->dim_);
}
OnlineLinearModel::update_dim(dim);
}
}
void CW::GetModelInfo(Json::Value& root) const {
OnlineLinearModel::GetModelInfo(root);
root["online"]["a"] = this->a_;
root["online"]["phi"] = this->phi_;
}
void CW::GetModelParam(std::ostream& os) const {
OnlineLinearModel::GetModelParam(os);
for (int c = 0; c < this->clf_num_; ++c) {
os << "Sigma[" << c << "]: " << this->Sigmas_[c] << "\n";
}
}
int CW::SetModelParam(std::istream& is) {
OnlineLinearModel::SetModelParam(is);
string line;
for (int c = 0; c < this->clf_num_; ++c) {
is >> line >> this->Sigmas_[c];
}
return Status_OK;
}
RegisterModel(CW, "cw", "confidence weighted online learning");
} // namespace model
} // namespace sol
| 27.932432 | 83 | 0.553943 | [
"vector",
"model"
] |
a0be2c2bed2784eb3f965956b6ea73765d51765b | 6,027 | cpp | C++ | tests-batch/eventdata/main.cpp | elainejiang8/MinVR | d3905b0a7b6b3e324e6ab3773ef29f651b8ad9d7 | [
"BSD-3-Clause"
] | 18 | 2016-08-04T16:09:52.000Z | 2022-01-17T15:43:37.000Z | tests-batch/eventdata/main.cpp | elainejiang8/MinVR | d3905b0a7b6b3e324e6ab3773ef29f651b8ad9d7 | [
"BSD-3-Clause"
] | 123 | 2015-01-08T17:32:39.000Z | 2021-12-22T00:55:00.000Z | tests-batch/eventdata/main.cpp | elainejiang8/MinVR | d3905b0a7b6b3e324e6ab3773ef29f651b8ad9d7 | [
"BSD-3-Clause"
] | 21 | 2016-11-04T18:36:29.000Z | 2022-03-01T19:44:11.000Z |
#include <iostream>
#include <data/VRDataIndex.h>
#include <event/VREvent.h>
#include <math/VRMath.h>
int main(int argc, char **argv) {
// fill a data index with an example for each of the VRCoreTypes
VRDataIndex e1Data;
// VRInt
e1Data.addData("MyInteger", 1);
// VRDouble
e1Data.addData("MyFloat", 2.2);
// VRString
e1Data.addData("MyString", "test string!");
// VRIntArray
VRIntArray ia;
ia.push_back(1);
ia.push_back(2);
ia.push_back(3);
e1Data.addData("MyIntArray", ia);
// VRDoubleArray
VRDoubleArray da;
da.push_back(1.23);
da.push_back(2.34);
da.push_back(3.45);
e1Data.addData("MyDoubleArray", da);
// VRStringArray
VRStringArray sa;
sa.push_back("one fish");
sa.push_back("two fish");
sa.push_back("red fish");
sa.push_back("blue fish");
e1Data.addData("MyStringArray", sa);
// create a new event with this data index
VREvent e1("ExampleEvent", e1Data);
std::cout << "Event 1:" << e1.toXML() << std::endl;
// create a second event with data from the first, testing the Event::to/fromXML methods
VREvent e2 = VREvent::fromXML(e1.toXML());
std::cout << "Event 2:" << e2.toXML() << std::endl;
if (e1.toXML() == e2.toXML()) {
std::cout << "Test of Event::toXML() and Event::fromXML() successful!" << std::endl;
}
else {
std::cout << "Error: e1.toXML() is not equal to e2.toXML() -- could be a problem with Event::toXML(), Event::fromXML(), or VRDataIndex" << std::endl;
}
// Test reading the data out into a new variable, using the long notation
VRDoubleArray myDA = e2.getDataIndex()->getDatumPtr("MyDoubleArray", "/")->getValueDoubleArray();
std::cout << e2.getDataIndex()->getTypeAsString("MyDoubleArray", "/") << std::endl;
for (VRDoubleArray::iterator it=myDA.begin(); it<myDA.end(); ++it) {
std::cout << *it << std::endl;
}
// Test reading the data out into a new variable, here VRAnyCoreType gets returned by getValue and is then cast into a VRDoubleArray
VRDoubleArray myDA2 = e2.getDataIndex()->getValue("MyDoubleArray");
for (VRDoubleArray::iterator it=myDA2.begin(); it<myDA2.end(); ++it) {
std::cout << *it << std::endl;
}
std::cout << std::endl;
// now test types from VRMath
VRDataIndex e3Data;
VRPoint3 p(1,2,3);
// At its heart, VRPoint3 is really just a 3 element array of doubles, so it's easy to
// convert the data to a VRDoubleArray, which is one of the VRCoreTypes accepted by VRDataIndex.
e3Data.addData("Position", p.toVRDoubleArray());
// Alternatively, since VRPoint3 inherets from VRDoubleArrayConvertable, we can call addData
// directly on p as a shorthand.
e3Data.addData("Position2", p);
VRVector3 v(1.2, 2.3, 3.4);
e3Data.addData("Heading", v);
VRMatrix4 m = VRMatrix4::translation(VRVector3(5.5, 6.6, 7.7)) * VRMatrix4::scale(VRVector3(2.0, 2.0, 2.0));
e3Data.addData("TransformMatrix", m);
// check to see that toXML and fromXML work as expected...
VREvent e3("EventWithMathTypes", e3Data);
std::cout << "Event 3: " << e3.toXML() << std::endl;
VREvent e4 = VREvent::fromXML(e3.toXML());
std::cout << "Event 4: " << e4.toXML() << std::endl;
// now test reading some data out of the dataIndex and getting it into the right VRMath type
// note: getValue returns VRAnyCoreType and then the VRPoint3(VRAnyCoreType) constructor is
// called, where VRAnyCoreType is interpreted as the core type VRDoubleArray and then the
// point is created.
VRPoint3 p2 = e4.getDataIndex()->getValue("Position");
std::cout << "Position = " << p2 << std::endl;
VRVector3 h = e4.getDataIndex()->getValue("Heading");
std::cout << "Heading = " << h << std::endl;
VRMatrix4 m2 = e4.getDataIndex()->getValue("TransformMatrix");
std::cout << "TransformMatrix = " << m2 << std::endl;
/*** OLD APPROACH - PRE VRDataIndex
// EVENTS FOR ARBITRARY TYPES:
// Using the templated constructor for VREvent, we can create an event with any arbitrary data object
// as long as that object implements the method: void serialize(ByteData &data);
VRVector3 v1(1,2,3);
std::cout << v1 << std::endl;
VREvent e1("event 1", v1);
// To get the data out, we can use the templated getData method:
VRVector3 v2(e1.getData());
std::cout << v2 << std::endl;
// Or, if the type implements a constructor that takes a ByteData argument, then we can get the data this way.
// Here, there is an implicit call to the constructor: Vec3(const ByteData &data);
VRVector3 v3 = e1.getData();
std::cout << v3 << std::endl;
// EVENTS FOR BUILTIN TYPES:
// Note: we could skip the asInt() or asFloat() syntax below if we overload the cast () operator in ByteData in order
// to automatically cast it to an int or float, but I think it might be better to avoid this. I can see bugs coming
// up from confusion over implicit casts to floats vs. doubles for example.
VREvent e2("event 2", 2);
int i = e2.getData().toInt();
std::cout << "i = " << i << std::endl;
VREvent e3("event 3", 123456789);
int j = e3.getData().toInt();
std::cout << "j = " << j << std::endl;
VREvent e4("event 4", (float)1.23456789);
float f = e4.getData().toFloat();
std::cout << "f = " << f << std::endl;
// Use a ByteStream to serialize a more complex datastructure through several write/serialize calls.
VRByteStream bs;
bs.writeInt(5);
bs.writeInt(3);
v3.serialize(bs);
bs.writeInt(1);
std::cout << bs.readInt() << " " << bs.readInt() << std::endl;
VRVector3 v4;
v4.deserialize(bs);
std::cout << v4 << std::endl;
std::cout << bs.readInt() << std::endl;
// Anythign that can be packed into ByteData can be used as a data type for events
VREvent e5("event 5", bs.toByteData());
VRByteStream bs2(e5.getData());
std::cout << bs2.readInt() << " " << bs2.readInt() << std::endl;
VRVector3 v5;
v5.deserialize(bs2);
std::cout << v5 << std::endl;
std::cout << bs2.readInt() << std::endl;
***/
}
| 30.439394 | 153 | 0.6519 | [
"object"
] |
a0be6dbd4d8ec363b821afd0ef5378729d5f86d7 | 19,920 | hpp | C++ | src/percept/mesh/gen/SweepMesher.hpp | jrood-nrel/percept | 363cdd0050443760d54162f140b2fb54ed9decf0 | [
"BSD-2-Clause"
] | 3 | 2017-08-08T21:06:02.000Z | 2020-01-08T13:23:36.000Z | src/percept/mesh/gen/SweepMesher.hpp | jrood-nrel/percept | 363cdd0050443760d54162f140b2fb54ed9decf0 | [
"BSD-2-Clause"
] | 2 | 2016-12-17T00:18:56.000Z | 2019-08-09T15:29:25.000Z | src/percept/mesh/gen/SweepMesher.hpp | jrood-nrel/percept | 363cdd0050443760d54162f140b2fb54ed9decf0 | [
"BSD-2-Clause"
] | 2 | 2017-11-30T07:02:41.000Z | 2019-08-05T17:07:04.000Z | // Copyright 2002 - 2008, 2010, 2011 National Technology Engineering
// Solutions of Sandia, LLC (NTESS). Under the terms of Contract
// DE-NA0003525 with NTESS, the U.S. Government retains certain rights
// in this software.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#ifndef percept_mesh_gen_SweepMesher_hpp
#define percept_mesh_gen_SweepMesher_hpp
#include <vector>
#include <iostream>
#include <percept/PerceptBoostArray.hpp>
#include <Shards_Array.hpp>
#include <Shards_ArrayVector.hpp>
#include <Shards_BasicTopologies.hpp>
#include <stk_util/parallel/Parallel.hpp>
#include <stk_mesh/base/Types.hpp>
#include <stk_mesh/base/MetaData.hpp>
#include <stk_mesh/base/BulkData.hpp>
#include <stk_mesh/base/Entity.hpp>
#include <stk_mesh/base/Field.hpp>
#include <stk_mesh/base/CoordinateSystems.hpp>
#include <stk_mesh/base/MetaData.hpp>
#include <stk_mesh/base/Stencils.hpp>
#include <stk_mesh/base/TopologyDimensions.hpp>
#include <percept/ShardsInterfaceTable.hpp>
#include <percept/util/GeneralFunction.hpp>
#include <percept/PerceptMesh.hpp>
SHARDS_ARRAY_DIM_TAG_SIMPLE_DECLARATION( Tag1 )
SHARDS_ARRAY_DIM_TAG_SIMPLE_DECLARATION( Tag2 )
SHARDS_ARRAY_DIM_TAG_SIMPLE_DECLARATION( Tag3 )
SHARDS_ARRAY_DIM_TAG_SIMPLE_DECLARATION( Tag4 )
namespace percept
{
using namespace interface_table;
using namespace util;
template<typename T> void push_back( std::vector<T>& dst, const std::vector<T>& src)
{
dst.insert(dst.end(), src.begin(), src.end());
}
typedef boost::array<double,3> Coord;
typedef GeneralFunction< Coord, Coord > VectorFieldGeneralFunction;
class Transform : public VectorFieldGeneralFunction
{
public:
Transform() {}
virtual ~Transform() {}
virtual Coord operator()(const Coord& x)
{
Coord y;
operator()(x, y);
return y;
}
using VectorFieldGeneralFunction::operator();
virtual void operator()(const Coord& x, Coord& y) =0;
};
class TransformDir : public Transform
{
Coord m_dir;
public:
TransformDir(Coord dir) : m_dir(dir) {}
using Transform::operator();
virtual Coord operator()(const Coord& x)
{
Coord y;
operator()(x, y);
return y;
}
virtual void operator()(const Coord& x, Coord& y)
{
y[0] = x[0] + m_dir[0];
y[1] = x[1] + m_dir[1];
y[2] = x[2] + m_dir[2];
}
};
// FIXME - use shards::Array
typedef std::vector< Coord > VectorOfCoord;
typedef std::vector<unsigned> VectorOfInt;
using namespace shards ;
//typedef ArrayVector<unsigned,NaturalOrder,Tag1,Tag2> ArrayInt2 ;
/** \class stk::utils::SweepMesher
* \brief A simple utility to product tensor product (line, quad, hex) meshes by sweeping
* as well as non-tensor product mesh by breaking into sub-elements (tri, tet, wedge, pyramid)
*
* \author Steve Kennon, Brian Carnes, Kevin Copps
*
* Usage: initialize with a simple pair of node, element arrays, such as
*
* double coords[][3] = {
* {0,0,0}, {1,0,0}, {2,2,0}, {0,3,0},
* {0,0,1}, {1,0,1}, {2,2,1}, {0,3,1}
* };
*
* unsigned quad4Elems[] = {
* 0,1,2,3,
* 4,5,6,7
* };
*
* SweepMesher tp;
* tp.initNodes(coords, 8);
* tp.initElems(elemType, // one of enum's defined below
* quad4Elems, 2);
*
* Then use sweep to create a hex mesh (this example breaks a quad to create two Tri's, then creates a mixed hex/wedge mesh)
*
* boost::array< double, 3> dir = {0,0,1};
* std::vector<Transform *> xforms(1, &TransformDir( dir ) );
*
* // break one of the quads into tris
* unsigned quadElemIndex = 1;
* tp2.breakElem<SweepMesher::ET_Quad4, SweepMesher::ET_Tri3>(quadElemIndex);
* std::cout << "after break\n";
* tp2.dump();
*
* // sweep to make a hex mesh
* boost::array< double, 3> dir1 = {0,0,2.345};
* xforms[0] = &TransformDir(dir1);
* tp2.sweep( SweepMesher::ET_Quad4, SweepMesher::ET_Hex8, xforms);
*
*
*/
class SweepMesher
{
//ATest m_atest;
const interface_table::elemInfoType *m_elemInfo;
public:
bool m_deleteAfterSweep;
bool m_deleteAfterBreak;
/// only a few sweep types allowed so far; later could add quadratic sweeping
SweepMesher(unsigned spatialDim=3) : m_spatial_dimension(spatialDim)
//: m_deleteAfterSweep(1), m_deleteAfterBreak(1), m_metaData(0), m_bulkData(0)
{
//m_dump = false;
//m_elemInfo = ShardsInterfaceTable::s_elemInfo;
initialize();
//m_atest.doIt();
}
~SweepMesher()
{
delete m_bulkData;
delete m_metaData;
}
void initialize()
{
m_deleteAfterSweep = 1;
m_deleteAfterBreak = 1;
m_metaData = 0;
m_bulkData = 0;
m_dump = false;
m_elemInfo = ShardsInterfaceTable::s_elemInfo;
}
// allow public access for simplicity - FIXME
VectorOfCoord m_node_coords; // node pool
VectorOfInt m_elems[NUM_ELEM_TYPES];
void CopyFromBasicMesh(SweepMesher& source)
{
m_node_coords = source.m_node_coords;
for (unsigned i = 0; i < NUM_ELEM_TYPES; i++)
m_elems[i] = source.m_elems[i];
}
stk::mesh::BulkData * get_bulk_data() { return m_bulkData;}
stk::mesh::MetaData * getMetaData() { return m_metaData; }
private:
bool m_dump;
unsigned m_spatial_dimension;
stk::mesh::MetaData * m_metaData;
stk::mesh::BulkData * m_bulkData;
std::vector<stk::mesh::Part *> m_parts;
stk::mesh::Part *m_block_hex;
stk::mesh::Part *m_block_wedge;
CoordinatesFieldType * m_coordinates_field;
// CoordinatesFieldType & m_centroid_field;
// ScalarFieldType & m_temperature_field;
// ScalarFieldType & m_volume_field;
public:
void initNodes(double coords[][3], unsigned numNodes)
{
//std::cout << "h1" << std::endl;
m_node_coords.clear();
//m_node_coords.assign(coords, coords+numNodes);
for (unsigned i = 0; i < numNodes; i++)
{
Coord x;
x[0] = coords[i][0];
x[1] = coords[i][1];
x[2] = coords[i][2];
m_node_coords.push_back(x);
}
}
void initNodes(Coord coords[], unsigned numNodes)
{
//std::cout << "h2" << std::endl;
m_node_coords.clear();
m_node_coords.assign(coords, coords+numNodes);
}
void initElems(unsigned elemType, unsigned indices[], unsigned numElem)
{
//std::cout << "h3" << std::endl;
m_elems[elemType].clear();
m_elems[elemType].assign(indices, indices+numElem*m_elemInfo[elemType].vertex_count);
}
private:
void transform(VectorOfCoord& oldNodes, VectorOfCoord& newNodes, Transform& xform)
{
// xform.do( on each node)
for(unsigned i = 0; i < oldNodes.size(); i++)
{
#if defined(NO_GEOM_SUPPORT)
xform.operator()(oldNodes[i], newNodes[i]);
#else
xform(oldNodes[i], newNodes[i]);
#endif
}
}
void cloneNodes(VectorOfCoord& oldNodes, VectorOfCoord& newNodes, Transform& xform)
{
//unsigned nnodes = oldNodes.size();
newNodes = oldNodes; // deep copy
transform(oldNodes, newNodes, xform);
}
void cloneElems(VectorOfCoord& oldNodes, VectorOfInt& oldElems, VectorOfInt& newElems)
{
unsigned nnodes = oldNodes.size();
newElems = oldElems;
for (unsigned i = 0; i < oldElems.size(); i++)
{
newElems[i] += nnodes;
}
}
void sweep(unsigned elemType, unsigned sweptElemType,
VectorOfCoord& oldNodes, VectorOfInt& oldElems, VectorOfCoord& newNodes, VectorOfInt& newElems, VectorOfInt& newSweptElems)
{
// for now we assume all elems are "vertex only", i.e. only linears, so we can just double the nodes and tack on the end
// special cases: line to quad: have to reverse the nodes
newSweptElems.clear();
// this would be a lot easier with a multi-d array - FIXME
unsigned nodes_per_elem = m_elemInfo[elemType].vertex_count;
unsigned numElems = oldElems.size()/nodes_per_elem;
//unsigned numSweptElems = numElems;
for (unsigned iel = 0; iel < numElems; iel++)
{
unsigned *newElemI = &newElems[iel*nodes_per_elem];
unsigned *oldElemI = &oldElems[iel*nodes_per_elem];
VectorOfInt newElem(newElemI, newElemI+nodes_per_elem);
VectorOfInt oldElem(oldElemI, oldElemI+nodes_per_elem);
if (elemType == shards_Line_2)
{
newElem = VectorOfInt(newElem.rbegin(), newElem.rend());
}
push_back(newSweptElems, oldElem);
push_back(newSweptElems, newElem);
}
}
public:
// for a single element type
void sweep(unsigned elemType, unsigned sweptElemType, std::vector<Transform *> xforms)
{
//void sweep(std::vector<unsigned> elemTypes, std::vector<unsigned> sweptElemTypes, std::vector<Transform *> xforms)
sweep(VectorOfInt(1, elemType), VectorOfInt(1, sweptElemType), xforms);
}
/// for a specified group of element types in the mesh at once
void sweep(VectorOfInt elemTypes, VectorOfInt sweptElemTypes, std::vector<Transform *> xforms)
{
unsigned nlevels = xforms.size();
//assert(2*m_elemInfo[elemType].vertex_count == m_elemInfo[sweptElemType].vertex_count);
// setup arrays
unsigned neleType = elemTypes.size();
std::vector<VectorOfInt> voldElems(neleType);
std::vector<VectorOfInt> vnewElems(neleType);
// a bit of overkill here, but leaving open the possibility of more complex heterogeneous meshes with e.g. linear and quadratics
for (unsigned ieleType = 0; ieleType < elemTypes.size(); ieleType++)
{
unsigned elemType = elemTypes[ieleType];
//unsigned sweptElemType = sweptElemTypes[ieleType];
voldElems[ieleType] = m_elems[elemType];
vnewElems[ieleType] = m_elems[elemType];
}
VectorOfCoord oldNodes = m_node_coords;
VectorOfCoord newNodes = oldNodes;
VectorOfInt newSweptElems;
for (unsigned ilev = 0; ilev < nlevels; ilev++)
{
//clone(oldNodes, oldElems, newNodes, newElems, *xforms[ilev]);
cloneNodes(oldNodes, newNodes, *xforms[ilev]);
for (unsigned ieleType = 0; ieleType < elemTypes.size(); ieleType++)
{
unsigned elemType = elemTypes[ieleType];
unsigned sweptElemType = sweptElemTypes[ieleType];
cloneElems(oldNodes, voldElems[ieleType], vnewElems[ieleType]);
sweep(elemType, sweptElemType, oldNodes, voldElems[ieleType], newNodes, vnewElems[ieleType], newSweptElems);
push_back(m_elems[sweptElemType], newSweptElems);
voldElems[ieleType] = vnewElems[ieleType];
}
oldNodes = newNodes;
push_back(m_node_coords, newNodes);
}
if (m_deleteAfterSweep)
{
for (unsigned ieleType = 0; ieleType < elemTypes.size(); ieleType++)
{
unsigned elemType = elemTypes[ieleType];
m_elems[elemType].clear();
}
}
};
/// for all element types in the mesh at once
void sweep( std::vector<Transform *> xforms)
{
VectorOfInt elemTypes;
VectorOfInt sweptElemTypes;
for (unsigned i = 0; i < NUM_ELEM_TYPES; i++)
{
if (m_elems[i].size() > 0)
{
elemTypes.push_back(m_elemInfo[i].elemEnumType);
sweptElemTypes.push_back(m_elemInfo[i].sweptElemType);
}
}
sweep(elemTypes, sweptElemTypes, xforms);
}
/// for all element types in the mesh at once - path following
void sweep(const double path[][3], unsigned npts)
{
VectorOfCoord vpath;
for (unsigned i = 0; i < npts; i++)
{
const Coord &pt = *reinterpret_cast<const Coord * >(path[i]);
vpath.push_back(pt);
}
sweep(vpath);
}
void sweep(const VectorOfCoord& path)
{
unsigned npoints = path.size();
std::vector<Transform *> xforms(npoints-1);
for (unsigned i = 0; i < npoints-1; i++)
{
boost::array< double, 3> dir;
dir[0] = path[i+1][0]-path[i][0];
dir[1] = path[i+1][1]-path[i][1];
dir[2] = path[i+1][2]-path[i][2];
xforms[i] = new TransformDir(dir);
}
sweep(xforms);
for (unsigned i = 0; i < npoints-1; i++)
{
delete xforms[i];
}
}
void sweep(const VectorOfCoord& path, const VectorOfCoord& dir);
/// apply a single transformation to all nodes' coordinates
void transform(Transform& xform)
{
for (unsigned i = 0; i < m_node_coords.size(); i++)
{
Coord y;
xform.operator()(m_node_coords[i], y);
m_node_coords[i] = y;
}
}
void squareMesh(unsigned nx, unsigned ny, double xlength, double ylength, double xorigin=0.0, double yorigin=0.0)
{
for (unsigned iy = 0; iy < ny; iy++)
{
double y = yorigin + ylength*((double)iy)/((double)(ny-1));
for (unsigned ix = 0; ix < nx; ix++)
{
double x = xorigin + xlength*((double)ix)/((double)(nx-1));
Coord pt = {{x, y, 0}};
m_node_coords.push_back(pt);
}
}
for (unsigned iye = 0; iye < ny-1; iye++)
{
for (unsigned ixe = 0; ixe < nx-1; ixe++)
{
unsigned nodexy = ixe + iye*nx;
unsigned nodexpy = ixe+1 + iye*nx;
unsigned nodexpyp = ixe+1 + (iye+1)*nx;
unsigned nodexyp = ixe + (iye+1)*nx;
m_elems[shards_Quadrilateral_4].push_back(nodexy);
m_elems[shards_Quadrilateral_4].push_back(nodexpy);
m_elems[shards_Quadrilateral_4].push_back(nodexpyp);
m_elems[shards_Quadrilateral_4].push_back(nodexyp);
}
}
}
void cubeMesh(unsigned nx, unsigned ny, unsigned nz, double xlength, double ylength, double zlength,
double xorigin=0.0, double yorigin=0.0, double zorigin=0.0)
{
for (unsigned iz = 0; iz < nz; iz++)
{
double z = zorigin + zlength*((double)iz)/((double)(nz-1));
for (unsigned iy = 0; iy < ny; iy++)
{
double y = yorigin + ylength*((double)iy)/((double)(ny-1));
for (unsigned ix = 0; ix < nx; ix++)
{
double x = xorigin + xlength*((double)ix)/((double)(nx-1));
Coord pt = {{x, y, z}};
m_node_coords.push_back(pt);
}
}
}
for (unsigned ize = 0; ize < nz-1; ize++)
{
for (unsigned iye = 0; iye < ny-1; iye++)
{
for (unsigned ixe = 0; ixe < nx-1; ixe++)
{
unsigned nodexy = ixe + iye*nx + ize*nx*ny;
unsigned nodexpy = ixe+1 + iye*nx + ize*nx*ny;
unsigned nodexpyp = ixe+1 + (iye+1)*nx + ize*nx*ny;
unsigned nodexyp = ixe + (iye+1)*nx + ize*nx*ny;
unsigned nodexyzp = ixe + iye*nx + (ize+1)*nx*ny;
unsigned nodexpyzp = ixe+1 + iye*nx + (ize+1)*nx*ny;
unsigned nodexpypzp = ixe+1 + (iye+1)*nx + (ize+1)*nx*ny;
unsigned nodexypzp = ixe + (iye+1)*nx + (ize+1)*nx*ny;
m_elems[shards_Hexahedron_8].push_back(nodexy);
m_elems[shards_Hexahedron_8].push_back(nodexpy);
m_elems[shards_Hexahedron_8].push_back(nodexpyp);
m_elems[shards_Hexahedron_8].push_back(nodexyp);
m_elems[shards_Hexahedron_8].push_back(nodexyzp);
m_elems[shards_Hexahedron_8].push_back(nodexpyzp);
m_elems[shards_Hexahedron_8].push_back(nodexpypzp);
m_elems[shards_Hexahedron_8].push_back(nodexypzp);
}
}
}
}
void debug(const char* str)
{
std::cout << " debug: " << str << std::endl;
std::cout.flush();
}
void debug(const char* str, const int i)
{
std::cout << " debug: " << str << " " << i << std::endl;
std::cout.flush();
}
template<unsigned fromType, unsigned toType> void breakElement(unsigned elemIndex);
template<unsigned fromType, unsigned toType> void breakAllElements()
{
//debug("breakAllElements");
unsigned numElems = m_elems[fromType].size()/m_elemInfo[fromType].vertex_count;
if (0) debug("numElems: ", numElems);
unsigned numElemsTo = m_elems[toType].size()/m_elemInfo[toType].vertex_count;
if (0) debug("numElemsTo: ", numElemsTo);
bool deleteAfterBreak = m_deleteAfterBreak;
m_deleteAfterBreak = false;
for (unsigned elemIndex = 0; elemIndex < numElems; elemIndex++)
{
breakElement<fromType, toType > ( elemIndex);
}
m_deleteAfterBreak = deleteAfterBreak;
if (m_deleteAfterBreak)
{
m_elems[fromType].clear();
}
}
void dumpSTK();
void dump(bool onOff) { m_dump= onOff; }
void dump()
{
if (!m_dump) return;
std::cout << "\ndump::\n";
for (unsigned i = 0; i < m_node_coords.size(); i++)
{
std::cout << "node: " << i << " = {" << m_node_coords[i][0] << " " << m_node_coords[i][1] << " " << m_node_coords[i][2] << "}" << std::endl;
}
for (unsigned i = 0; i < NUM_ELEM_TYPES; i++)
{
if (m_elems[i].size() > 0)
{
//std::cout << "h4 " << i << std::endl;
std::cout.flush();
unsigned nodes_per_elem = m_elemInfo[i].vertex_count;
unsigned numElems = m_elems[i].size()/nodes_per_elem;
std::cout << "elem[" << m_elemInfo[i].name << "]: num= " << numElems << std::endl;
unsigned counter=0;
for (unsigned iel = 0; iel < numElems; iel++)
{
std::cout << " { ";
for (unsigned j = 0; j < nodes_per_elem; j++)
{
std::cout << m_elems[i][counter++] << " ";
std::cout.flush();
}
std::cout << " }\n";
}
std::cout.flush();
}
}
}
/// create a std::mesh representation of this
void stkMeshCreate(stk::ParallelMachine& );
void stkMeshCreateMetaNoCommit(stk::ParallelMachine& );
void stkMeshCreateBulkAfterMetaCommit(stk::ParallelMachine& );
void writeSTKMesh(const char* filename);
};
}//namespace percept
#endif
| 33.591906 | 152 | 0.558333 | [
"mesh",
"vector",
"transform"
] |
a0c21de837e2b2859001a6909a7a0a5ab9c6921e | 6,597 | cc | C++ | third_party/openfst/src/lib/fst.cc | hellais/marionette | 12be546b5d166033e7ca3b2a6a3379122b71b8ce | [
"Apache-2.0"
] | 11 | 2016-03-04T16:29:06.000Z | 2021-10-02T03:27:55.000Z | third_party/openfst/src/lib/fst.cc | hellais/marionette | 12be546b5d166033e7ca3b2a6a3379122b71b8ce | [
"Apache-2.0"
] | 5 | 2015-04-08T16:52:03.000Z | 2015-08-22T18:14:50.000Z | third_party/openfst/src/lib/fst.cc | hellais/marionette | 12be546b5d166033e7ca3b2a6a3379122b71b8ce | [
"Apache-2.0"
] | 5 | 2015-08-20T16:39:58.000Z | 2021-10-19T18:48:27.000Z | // fst.cc
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Copyright 2005-2010 Google, Inc.
// Author: riley@google.com (Michael Riley)
//
// \file
// FST definitions.
#include <fst/fst.h>
// Include these so they are registered
#include <fst/compact-fst.h>
#include <fst/const-fst.h>
#include <fst/matcher-fst.h>
#include <fst/vector-fst.h>
#include <fst/edit-fst.h>
// FST flag definitions
DEFINE_bool(fst_verify_properties, false,
"Verify fst properties queried by TestProperties");
DEFINE_string(fst_weight_separator, ",",
"Character separator between printed composite weights; "
"must be a single character");
DEFINE_string(fst_weight_parentheses, "",
"Characters enclosing the first weight of a printed composite "
"weight (e.g. pair weight, tuple weight and derived classes) to "
"ensure proper I/O of nested composite weights; "
"must have size 0 (none) or 2 (open and close parenthesis)");
DEFINE_bool(fst_default_cache_gc, true, "Enable garbage collection of cache");
DEFINE_int64(fst_default_cache_gc_limit, 1<<20LL,
"Cache byte size that triggers garbage collection");
DEFINE_bool(fst_align, false, "Write FST data aligned where appropriate");
DEFINE_string(save_relabel_ipairs, "", "Save input relabel pairs to file");
DEFINE_string(save_relabel_opairs, "", "Save output relabel pairs to file");
DEFINE_string(fst_read_mode, "read",
"Default file reading mode for mappable files");
namespace fst {
// Register VectorFst, ConstFst and EditFst for common arcs types
REGISTER_FST(VectorFst, StdArc);
REGISTER_FST(VectorFst, LogArc);
REGISTER_FST(VectorFst, Log64Arc);
REGISTER_FST(ConstFst, StdArc);
REGISTER_FST(ConstFst, LogArc);
REGISTER_FST(ConstFst, Log64Arc);
REGISTER_FST(EditFst, StdArc);
REGISTER_FST(EditFst, LogArc);
REGISTER_FST(EditFst, Log64Arc);
// Register CompactFst for common arcs with the default (uint32) size type
static FstRegisterer<
CompactFst<StdArc, StringCompactor<StdArc> > >
CompactFst_StdArc_StringCompactor_registerer;
static FstRegisterer<
CompactFst<LogArc, StringCompactor<LogArc> > >
CompactFst_LogArc_StringCompactor_registerer;
static FstRegisterer<
CompactFst<StdArc, WeightedStringCompactor<StdArc> > >
CompactFst_StdArc_WeightedStringCompactor_registerer;
static FstRegisterer<
CompactFst<LogArc, WeightedStringCompactor<LogArc> > >
CompactFst_LogArc_WeightedStringCompactor_registerer;
static FstRegisterer<
CompactFst<StdArc, AcceptorCompactor<StdArc> > >
CompactFst_StdArc_AcceptorCompactor_registerer;
static FstRegisterer<
CompactFst<LogArc, AcceptorCompactor<LogArc> > >
CompactFst_LogArc_AcceptorCompactor_registerer;
static FstRegisterer<
CompactFst<StdArc, UnweightedCompactor<StdArc> > >
CompactFst_StdArc_UnweightedCompactor_registerer;
static FstRegisterer<
CompactFst<LogArc, UnweightedCompactor<LogArc> > >
CompactFst_LogArc_UnweightedCompactor_registerer;
static FstRegisterer<
CompactFst<StdArc, UnweightedAcceptorCompactor<StdArc> > >
CompactFst_StdArc_UnweightedAcceptorCompactor_registerer;
static FstRegisterer<
CompactFst<LogArc, UnweightedAcceptorCompactor<LogArc> > >
CompactFst_LogArc_UnweightedAcceptorCompactor_registerer;
// Fst type definitions for lookahead Fsts.
extern const char arc_lookahead_fst_type[] = "arc_lookahead";
extern const char ilabel_lookahead_fst_type[] = "ilabel_lookahead";
extern const char olabel_lookahead_fst_type[] = "olabel_lookahead";
// Identifies stream data as an FST (and its endianity)
static const int32 kFstMagicNumber = 2125659606;
// Check for Fst magic number in stream, to indicate
// caller function that the stream content is an Fst header;
bool IsFstHeader(istream &strm, const string &source) {
int64 pos = strm.tellg();
bool match = true;
int32 magic_number = 0;
ReadType(strm, &magic_number);
if (magic_number != kFstMagicNumber
) {
match = false;
}
strm.seekg(pos);
return match;
}
// Check Fst magic number and read in Fst header.
// If rewind = true, reposition stream to before call (if possible).
bool FstHeader::Read(istream &strm, const string &source, bool rewind) {
int64 pos = 0;
if (rewind) pos = strm.tellg();
int32 magic_number = 0;
ReadType(strm, &magic_number);
if (magic_number != kFstMagicNumber
) {
LOG(ERROR) << "FstHeader::Read: Bad FST header: " << source;
if (rewind) strm.seekg(pos);
return false;
}
ReadType(strm, &fsttype_);
ReadType(strm, &arctype_);
ReadType(strm, &version_);
ReadType(strm, &flags_);
ReadType(strm, &properties_);
ReadType(strm, &start_);
ReadType(strm, &numstates_);
ReadType(strm, &numarcs_);
if (!strm) {
LOG(ERROR) << "FstHeader::Read: read failed: " << source;
return false;
}
if (rewind) strm.seekg(pos);
return true;
}
// Write Fst magic number and Fst header.
bool FstHeader::Write(ostream &strm, const string &source) const {
WriteType(strm, kFstMagicNumber);
WriteType(strm, fsttype_);
WriteType(strm, arctype_);
WriteType(strm, version_);
WriteType(strm, flags_);
WriteType(strm, properties_);
WriteType(strm, start_);
WriteType(strm, numstates_);
WriteType(strm, numarcs_);
return true;
}
FstReadOptions::FstReadOptions(const string& src, const FstHeader *hdr,
const SymbolTable* isym, const SymbolTable* osym)
: source(src), header(hdr), isymbols(isym), osymbols(osym),
read_isymbols(true), read_osymbols(true) {
mode = ReadMode(FLAGS_fst_read_mode);
}
FstReadOptions::FstReadOptions(const string& src, const SymbolTable* isym,
const SymbolTable* osym)
: source(src), header(0), isymbols(isym), osymbols(osym),
read_isymbols(true), read_osymbols(true) {
mode = ReadMode(FLAGS_fst_read_mode);
}
FstReadOptions::FileReadMode FstReadOptions::ReadMode(const string &mode) {
if (mode == "read") {
return READ;
}
if (mode == "map") {
return MAP;
}
LOG(ERROR) << "Unknown file read mode " << mode;
return READ;
}
} // namespace fst
| 33.658163 | 80 | 0.736395 | [
"vector"
] |
a0c4dfb109b98ee3bb1e4d78832a1a47d73cf0fa | 11,178 | cc | C++ | gui/qfilesystemtreeview/QFileSystemTreeView.cc | amyznikov/SerStacker | 6657240210af0b35fff1c5adc1d6f9d51b469e80 | [
"CC0-1.0"
] | 1 | 2021-09-03T06:02:59.000Z | 2021-09-03T06:02:59.000Z | gui/qfilesystemtreeview/QFileSystemTreeView.cc | amyznikov/SerStacker | 6657240210af0b35fff1c5adc1d6f9d51b469e80 | [
"CC0-1.0"
] | 1 | 2021-09-03T03:43:54.000Z | 2021-09-10T01:30:46.000Z | gui/qfilesystemtreeview/QFileSystemTreeView.cc | amyznikov/SerStacker | 6657240210af0b35fff1c5adc1d6f9d51b469e80 | [
"CC0-1.0"
] | null | null | null | /*
* QFileSystemTreeView.cc
*
* Created on: Dec 17, 2016
* Author: amyznikov
*/
#include "QFileSystemTreeView.h"
#include <gui/widgets/QWaitCursor.h>
#define ICON_copy "copy"
#define ICON_delete "delete"
static QIcon getIcon(const QString & name)
{
return QIcon(QString(":/qfilesystemtreeview/icons/%1").arg(name));
}
///////////////////////////////////////////////////////////////////////////////
QFileSystemTreeView::QFileSystemTreeView(QWidget * parent /*= 0*/)
: Base(parent)
{
Q_INIT_RESOURCE(qfilesystemtreeview_resources);
QVBoxLayout * layout = new QVBoxLayout(this);
layout->addWidget(treeView = new QFileSystemCustomTreeView(this), 100);
treeView->setSelectionMode(QAbstractItemView::ExtendedSelection);
treeView->setContextMenuPolicy(Qt::CustomContextMenu);
refresh();
connect(treeView, &QFileSystemCustomTreeView::customContextMenuRequested,
this, &ThisClass::onCustomContextMenu);
connect(treeView, &QFileSystemCustomTreeView::pressed,
this, &ThisClass::onItemPressed);
}
void QFileSystemTreeView::refresh()
{
QString origPath;
QModelIndex index;
QDir::Filters origFilter = QDir::Drives | QDir::Dirs | QDir::NoDotAndDotDot;
if ( model ) {
origPath = model->fileInfo(treeView->currentIndex()).absoluteFilePath();
origFilter = model->filter();
treeView->setModel(NULL);
delete model;
}
treeView->setModel(model = new QFileSystemModel(this));
model->setReadOnly(false);
model->setRootPath("/");
model->setFilter(origFilter);
treeView->viewport()->setAcceptDrops(true);
treeView->setDragEnabled(true);
treeView->setDragDropMode(QAbstractItemView::DragDrop);
treeView->setDefaultDropAction(Qt::CopyAction);
treeView->setAcceptDrops(true);
treeView->setDropIndicatorShown(true);
treeView->setHeaderHidden(true);
for ( int i = 1; i < model->columnCount(); ++i ) {
treeView->setColumnHidden(i, true);
}
if ( (index = model->index(origPath)).isValid() ) {
treeView->setCurrentIndex(index);
treeView->expand(index);
treeView->scrollTo(index, QAbstractItemView::EnsureVisible);
}
connect(treeView->selectionModel(), &QItemSelectionModel::currentChanged, // (const QModelIndex &, const QModelIndex &)
this, &ThisClass::onCurrentDirectoryChanged, // (const QModelIndex &, const QModelIndex &))
Qt::DirectConnection);
}
void QFileSystemTreeView::hideColumn(int column)
{
return treeView->hideColumn(column);
}
void QFileSystemTreeView::showColumn(int column)
{
return treeView->showColumn(column);
}
void QFileSystemTreeView::setFilter(QDir::Filters filters)
{
model->setFilter(filters);
emit filterChanged();
//updateFilterIcon();
refresh();
}
QDir::Filters QFileSystemTreeView::filter() const
{
return model->filter();
}
QModelIndex QFileSystemTreeView::setRootPath(const QString &path)
{
return model->setRootPath(path);
}
QString QFileSystemTreeView::rootPath() const
{
return model->rootPath();
}
QDir QFileSystemTreeView::rootDirectory() const
{
return model->rootDirectory();
}
QString QFileSystemTreeView::absoluteFilePath(const QModelIndex &index)
{
return model->fileInfo(index).absoluteFilePath();
}
QString QFileSystemTreeView::currentAbsoluteFilePath(void)
{
return model->fileInfo(treeView->currentIndex()).absoluteFilePath();
}
bool QFileSystemTreeView::displayPath(const QString & path, bool showErrMsgIfNotExists)
{
QModelIndex index = model->index(path);
if ( !index.isValid() ) {
if ( showErrMsgIfNotExists ) {
QMessageBox::critical(this, "ERROR", QString("Requested path not exists.\n'%1'").arg(path));
}
return false;
}
treeView->scrollTo(index, QAbstractItemView::PositionAtCenter);
treeView->setCurrentIndex(index);
treeView->expand(index);
return true;
}
void QFileSystemTreeView::onCurrentDirectoryChanged(const QModelIndex & current, const QModelIndex & /*previous*/)
{
if ( model->fileInfo(current).isDir() ) {
emit currentDirectoryChanged(model->fileInfo(current).absoluteFilePath());
}
}
void QFileSystemTreeView::onItemPressed(const QModelIndex &index)
{
QFileInfo fileInfo = model->fileInfo(index);
if ( fileInfo.isDir() ) {
emit directoryItemPressed(fileInfo.absoluteFilePath());
}
}
void QFileSystemTreeView::onCustomContextMenu(const QPoint & pos)
{
QFileInfoList fileList;
do { // force put QModelIndexList into separate scope
QModelIndexList selectedIndexes = treeView->selectionModel()->selectedRows();
if ( !selectedIndexes.empty() ) {
for ( int i = 0, n = selectedIndexes.size(); i < n; ++i ) {
if ( selectedIndexes[i].isValid() ) {
fileList.append(model->fileInfo(selectedIndexes[i]));
}
}
}
else {
QModelIndex index = treeView->indexAt(pos);
if ( index.isValid() ) {
fileList.append(model->fileInfo(index));
}
}
} while ( 0 );
emit customContextMenuRequested(treeView->viewport()->mapToGlobal(pos), fileList);
}
void QFileSystemTreeView::fillContextMenu(QMenu & menu, const QFileInfoList & flist)
{
QAction * act;
if ( flist.size() > 0 && QApplication::clipboard() ) {
menu.addAction(act = new QAction(getIcon(ICON_copy),
tr("Copy full path"), this));
connect(act, &QAction::triggered, [flist] {
QString text = flist[0].absoluteFilePath();
for ( int i = 1, n = flist.size(); i < n; ++i ) {
text.append("\n");
text.append(flist[i].absoluteFilePath());
}
QApplication::clipboard()->setText(text);
});
}
if ( flist.size() > 0 ) {
menu.addAction(act = new QAction(tr("Move to...."), this));
connect(act, &QAction::triggered,
[this, flist] {
QString newName = QFileDialog::getExistingDirectory(this, "MOVE TO FOLDER",
flist[0].absoluteFilePath(), QFileDialog::DontUseNativeDialog | QFileDialog::ShowDirsOnly);
if ( !newName.isEmpty() ) {
for ( int i = 0, n = flist.size(); i < n; ++i ) {
const QString & oldName = flist[i].fileName();
const QString & oldPathName = flist[i].absoluteFilePath();
const QString newPathName = QString("%1/%2").arg(newName).arg(oldName);
QWaitCursor wait(this);
if ( rename(oldPathName.toStdString().c_str(), newPathName.toStdString().c_str()) != 0 ) {
int resp = QMessageBox::critical(this, "ERROR",
QString("rename() fails for '%1': %2").arg(oldPathName).arg(strerror(errno)),
QMessageBox::Ok, QMessageBox::Cancel);
if ( resp == QMessageBox::Cancel ) {
break;
}
}
}
}
});
}
if ( flist.size() == 1 ) {
QString abspath = flist[0].absoluteFilePath();
menu.addAction(act = new QAction(style()->standardIcon(QStyle::SP_FileDialogNewFolder),
tr("Create directory..."), this));
connect(act, &QAction::triggered,
[this, abspath] {
bool ok = false;
QString dirName = QInputDialog::getText(this, tr("Specify Folder name"),
tr("Folder name:"), QLineEdit::Normal, QString(),&ok);
if ( ok && !dirName.isEmpty() ) {
dirName = QString("%1/%2").arg(abspath).arg(dirName);
QWaitCursor wait(this);
if ( !QDir().mkpath(dirName) ) {
// if ( !create_path(dirName.toStdString()) != 0 ) {
QMessageBox::critical(this, "ERROR", QString("create_path() fails: %1").arg(strerror(errno)));
}
}});
}
if ( flist.size() > 0 ) {
menu.addAction(act = new QAction(getIcon(ICON_delete),
tr("Delete selected items ..."), this));
connect(act, &QAction::triggered,
[this, flist] {
int resp;
if ( flist.size() < 2 ) {
resp = QMessageBox::warning(this, "CONFIRMATION IS MANDATORY",
QString("ARE YOU SURE TO COMPLETELY RECURSIVELY DELETE THIS FOLDER ???"),
QMessageBox::Yes | QMessageBox::No);
}
else {
resp = QMessageBox::warning(this, "CONFIRMATION IS MANDATORY",
QString("ARE YOU SURE TO COMPLETELY RECURSIVELY DELETE %1 SELECTED FOLDERS ???").arg(flist.size()),
QMessageBox::Yes | QMessageBox::No);
}
if ( resp == QMessageBox::Yes ) {
QWaitCursor wait(this);
QStringList pathList;
for ( int i = 0, n = flist.size(); i < n; ++i ) {
pathList.append(flist[i].absoluteFilePath());
}
for ( int i = 0, n = pathList.size(); i < n; ++i ) {
const QString & absPath = pathList[i];
if ( absPath != "/" ) {
if ( !QDir(absPath).removeRecursively() ) {
resp = QMessageBox::critical(this, "ERROR",
QString("recursive_rmdir() fails: %1\n%2").arg(strerror(errno)).arg(absPath),
QMessageBox::Ok, QMessageBox::Cancel);
if ( resp == QMessageBox::Cancel ) {
break;
}
}
}
}
}
});
}
}
QFileSystemCustomTreeView::QFileSystemCustomTreeView(QWidget * parent)
: Base(parent)
{
}
void QFileSystemCustomTreeView::dropEvent(QDropEvent * e)
{
QFileSystemModel * m;
QModelIndex index;
Qt::DropActions possibleActsions;
if ( !(m = dynamic_cast<QFileSystemModel *>(model())) ) {
return Base::dropEvent(e);
}
if ( !((possibleActsions = e->possibleActions()) & Qt::ActionMask) ) {
return Base::dropEvent(e);
}
if ( !(index = indexAt(e->pos())).isValid() ) {
return Base::dropEvent(e);
}
if ( e->source() == this ) {
// QTreeView can handle only internal moves
e->setDropAction(Qt::MoveAction);
}
else {
QMenu menu(this);
QAction * copyAction = Q_NULLPTR;
QAction * moveAction = Q_NULLPTR;
QAction * linkAction = Q_NULLPTR;
QAction * act = Q_NULLPTR;
if ( possibleActsions & Qt::CopyAction ) {
menu.addAction(copyAction = new QAction("Copy here", this));
}
if ( possibleActsions & Qt::MoveAction ) {
menu.addAction(moveAction = new QAction("Move here", this));
}
if ( possibleActsions & Qt::LinkAction ) {
menu.addAction(linkAction = new QAction("Link here", this));
}
if ( !(act = menu.exec(viewport()->mapToGlobal(e->pos()))) ) {
e->setDropAction(Qt::IgnoreAction);
}
else if ( act == copyAction ) {
e->setDropAction(Qt::CopyAction);
}
else if ( act == moveAction ) {
e->setDropAction(Qt::MoveAction);
}
else if ( act == linkAction ) {
e->setDropAction(Qt::LinkAction);
}
else {
e->setDropAction(Qt::IgnoreAction);
}
}
if ( e->dropAction() != Qt::IgnoreAction ) {
if ( m->dropMimeData(e->mimeData(), e->dropAction(), -1, -1, index) ) {
e->accept();
}
else {
QMessageBox::critical(this, "ERROR",
"dropMimeData() fails\n\n"
"Check the permissions and make sure destination is not already exists");
}
}
}
| 29.033766 | 122 | 0.616747 | [
"model"
] |
a0c6799264c1d4f2cdd0dc3e9ef00cb02785f5ec | 2,949 | cpp | C++ | 3rdparty/FlyCube/src/Core/Pipeline/VKRayTracingPipeline.cpp | CU-Production/FlyCube-Demos | 2763720818499bc9244eb4b16e60e647a5c88827 | [
"MIT"
] | 8 | 2021-03-17T19:25:12.000Z | 2022-02-05T02:08:21.000Z | 3rdparty/FlyCube/src/Core/Pipeline/VKRayTracingPipeline.cpp | THISISAGOODNAME/SSSR | ea4b6350b2da3d5656c7aa8c87f9965144369d22 | [
"MIT"
] | null | null | null | 3rdparty/FlyCube/src/Core/Pipeline/VKRayTracingPipeline.cpp | THISISAGOODNAME/SSSR | ea4b6350b2da3d5656c7aa8c87f9965144369d22 | [
"MIT"
] | 2 | 2021-09-22T14:39:51.000Z | 2021-11-08T09:47:38.000Z | #include "Pipeline/VKRayTracingPipeline.h"
#include "Pipeline/VKGraphicsPipeline.h"
#include <Device/VKDevice.h>
#include <Adapter/VKAdapter.h>
#include <Program/VKProgram.h>
#include <BindingSetLayout/VKBindingSetLayout.h>
#include <Shader/Shader.h>
#include <map>
VKRayTracingPipeline::VKRayTracingPipeline(VKDevice& device, const RayTracingPipelineDesc& desc)
: VKPipeline(device, desc.program, desc.layout)
, m_desc(desc)
{
std::vector<vk::RayTracingShaderGroupCreateInfoKHR> groups(m_desc.groups.size());
auto get = [&](uint64_t id) -> uint32_t
{
auto it = m_shader_ids.find(id);
if (it == m_shader_ids.end())
{
return VK_SHADER_UNUSED_KHR;
}
return it->second;
};
for (size_t i = 0; i < m_desc.groups.size(); ++i)
{
decltype(auto) group = groups[i];
group.generalShader = VK_SHADER_UNUSED_KHR;
group.closestHitShader = VK_SHADER_UNUSED_KHR;
group.anyHitShader = VK_SHADER_UNUSED_KHR;
group.intersectionShader = VK_SHADER_UNUSED_KHR;
switch (m_desc.groups[i].type)
{
case RayTracingShaderGroupType::kGeneral:
group.type = vk::RayTracingShaderGroupTypeKHR::eGeneral;
group.generalShader = get(m_desc.groups[i].general);
break;
case RayTracingShaderGroupType::kTrianglesHitGroup:
group.type = vk::RayTracingShaderGroupTypeKHR::eTrianglesHitGroup;
group.closestHitShader = get(m_desc.groups[i].closest_hit);
group.anyHitShader = get(m_desc.groups[i].any_hit);
break;
case RayTracingShaderGroupType::kProceduralHitGroup:
group.type = vk::RayTracingShaderGroupTypeKHR::eProceduralHitGroup;
group.intersectionShader = get(m_desc.groups[i].intersection);
break;
}
}
vk::RayTracingPipelineCreateInfoKHR ray_pipeline_info{};
ray_pipeline_info.stageCount = static_cast<uint32_t>(m_shader_stage_create_info.size());
ray_pipeline_info.pStages = m_shader_stage_create_info.data();
ray_pipeline_info.groupCount = static_cast<uint32_t>(groups.size());
ray_pipeline_info.pGroups = groups.data();
ray_pipeline_info.maxPipelineRayRecursionDepth = 1;
ray_pipeline_info.layout = m_pipeline_layout;
m_pipeline = m_device.GetDevice().createRayTracingPipelineKHRUnique({}, {}, ray_pipeline_info);
}
PipelineType VKRayTracingPipeline::GetPipelineType() const
{
return PipelineType::kRayTracing;
}
std::vector<uint8_t> VKRayTracingPipeline::GetRayTracingShaderGroupHandles(uint32_t first_group, uint32_t group_count) const
{
std::vector<uint8_t> shader_handles_storage(group_count * m_device.GetShaderGroupHandleSize());
m_device.GetDevice().getRayTracingShaderGroupHandlesKHR(m_pipeline.get(), first_group, group_count, shader_handles_storage.size(), shader_handles_storage.data());
return shader_handles_storage;
}
| 39.851351 | 166 | 0.716853 | [
"vector"
] |
a0d32c608ac61e069e22d03e90a721843ed24d47 | 35,204 | cpp | C++ | tests/test_value.cpp | khoitd1997/toml11 | d685088c923c6eb4e4f62df28e4bfd9559c1aa52 | [
"MIT"
] | null | null | null | tests/test_value.cpp | khoitd1997/toml11 | d685088c923c6eb4e4f62df28e4bfd9559c1aa52 | [
"MIT"
] | null | null | null | tests/test_value.cpp | khoitd1997/toml11 | d685088c923c6eb4e4f62df28e4bfd9559c1aa52 | [
"MIT"
] | null | null | null | #define BOOST_TEST_MODULE "test_value"
#ifdef UNITTEST_FRAMEWORK_LIBRARY_EXIST
#include <boost/test/unit_test.hpp>
#else
#define BOOST_TEST_NO_LIB
#include <boost/test/included/unit_test.hpp>
#endif
#include <toml.hpp>
#include <map>
#include <list>
#if __cplusplus >= 201703L
#include <string_view>
#endif
BOOST_AUTO_TEST_CASE(test_value_boolean)
{
toml::value v1(true);
toml::value v2(false);
BOOST_TEST(v1.type() == toml::value_t::boolean);
BOOST_TEST(v2.type() == toml::value_t::boolean);
BOOST_TEST(v1.is(toml::value_t::boolean));
BOOST_TEST(v2.is(toml::value_t::boolean));
BOOST_TEST(v1.is<toml::boolean>());
BOOST_TEST(v2.is<toml::boolean>());
BOOST_TEST(v1.is_boolean());
BOOST_TEST(v2.is_boolean());
BOOST_TEST(v1.cast<toml::value_t::boolean>() == true);
BOOST_TEST(v2.cast<toml::value_t::boolean>() == false);
BOOST_TEST(v1.as_boolean() == true);
BOOST_TEST(v2.as_boolean() == false);
BOOST_TEST(v1.as_boolean(std::nothrow) == true);
BOOST_TEST(v2.as_boolean(std::nothrow) == false);
v1 = false;
v2 = true;
BOOST_TEST(v1.type() == toml::value_t::boolean);
BOOST_TEST(v2.type() == toml::value_t::boolean);
BOOST_TEST(v1.is(toml::value_t::boolean));
BOOST_TEST(v2.is(toml::value_t::boolean));
BOOST_TEST(v1.is<toml::boolean>());
BOOST_TEST(v2.is<toml::boolean>());
BOOST_TEST(v1.is_boolean());
BOOST_TEST(v2.is_boolean());
BOOST_TEST(v1.cast<toml::value_t::boolean>() == false);
BOOST_TEST(v2.cast<toml::value_t::boolean>() == true);
BOOST_TEST(v1.as_boolean() == false);
BOOST_TEST(v2.as_boolean() == true);
toml::value v3(v1);
toml::value v4(v2);
BOOST_TEST(v3 == v1);
BOOST_TEST(v4 == v2);
BOOST_TEST(v3.type() == toml::value_t::boolean);
BOOST_TEST(v4.type() == toml::value_t::boolean);
BOOST_TEST(v3.is(toml::value_t::boolean));
BOOST_TEST(v4.is(toml::value_t::boolean));
BOOST_TEST(v3.is<toml::boolean>());
BOOST_TEST(v4.is<toml::boolean>());
BOOST_TEST(v3.is_boolean());
BOOST_TEST(v4.is_boolean());
BOOST_TEST(v3.cast<toml::value_t::boolean>() == false);
BOOST_TEST(v4.cast<toml::value_t::boolean>() == true);
BOOST_TEST(v3.as_boolean() == false);
BOOST_TEST(v4.as_boolean() == true);
toml::value v5(std::move(v1));
toml::value v6(std::move(v2));
BOOST_TEST(v5.type() == toml::value_t::boolean);
BOOST_TEST(v6.type() == toml::value_t::boolean);
BOOST_TEST(v5.is(toml::value_t::boolean));
BOOST_TEST(v6.is(toml::value_t::boolean));
BOOST_TEST(v5.is<toml::boolean>());
BOOST_TEST(v6.is<toml::boolean>());
BOOST_TEST(v3.is_boolean());
BOOST_TEST(v4.is_boolean());
BOOST_TEST(v5.cast<toml::value_t::boolean>() == false);
BOOST_TEST(v6.cast<toml::value_t::boolean>() == true);
BOOST_TEST(v5.as_boolean() == false);
BOOST_TEST(v6.as_boolean() == true);
v1 = 42;
v2 = 3.14;
BOOST_TEST(v1.type() == toml::value_t::integer);
BOOST_TEST(v2.type() == toml::value_t::floating);
BOOST_TEST(v1.is(toml::value_t::integer));
BOOST_TEST(v2.is(toml::value_t::floating));
BOOST_TEST(v1.is<toml::integer>());
BOOST_TEST(v2.is<toml::floating>());
BOOST_TEST(v1.is_integer());
BOOST_TEST(v2.is_floating());
BOOST_TEST(v1.cast<toml::value_t::integer>() == 42);
BOOST_TEST(v2.cast<toml::value_t::floating>() == 3.14);
BOOST_TEST(v1.as_integer() == 42);
BOOST_TEST(v2.as_floating() == 3.14);
}
BOOST_AUTO_TEST_CASE(test_value_integer)
{
toml::value v1(-42);
toml::value v2(42u);
BOOST_TEST(v1.type() == toml::value_t::integer);
BOOST_TEST(v2.type() == toml::value_t::integer);
BOOST_TEST(v1.is(toml::value_t::integer));
BOOST_TEST(v2.is(toml::value_t::integer));
BOOST_TEST(v1.is<toml::integer>());
BOOST_TEST(v2.is<toml::integer>());
BOOST_TEST(v1.is_integer());
BOOST_TEST(v2.is_integer());
BOOST_TEST(v1.cast<toml::value_t::integer>() == -42);
BOOST_TEST(v2.cast<toml::value_t::integer>() == 42u);
BOOST_TEST(v1.as_integer() == -42);
BOOST_TEST(v2.as_integer() == 42u);
BOOST_TEST(v1.as_integer(std::nothrow) == -42);
BOOST_TEST(v2.as_integer(std::nothrow) == 42u);
v1 = 54;
v2 = -54;
BOOST_TEST(v1.type() == toml::value_t::integer);
BOOST_TEST(v2.type() == toml::value_t::integer);
BOOST_TEST(v1.is(toml::value_t::integer));
BOOST_TEST(v2.is(toml::value_t::integer));
BOOST_TEST(v1.is<toml::integer>());
BOOST_TEST(v2.is<toml::integer>());
BOOST_TEST(v1.is_integer());
BOOST_TEST(v2.is_integer());
BOOST_TEST(v1.cast<toml::value_t::integer>() == 54);
BOOST_TEST(v2.cast<toml::value_t::integer>() == -54);
BOOST_TEST(v1.as_integer() == 54);
BOOST_TEST(v2.as_integer() == -54);
toml::value v3(v1);
toml::value v4(v2);
BOOST_TEST(v3 == v1);
BOOST_TEST(v4 == v2);
BOOST_TEST(v3.type() == toml::value_t::integer);
BOOST_TEST(v4.type() == toml::value_t::integer);
BOOST_TEST(v3.is(toml::value_t::integer));
BOOST_TEST(v4.is(toml::value_t::integer));
BOOST_TEST(v3.is<toml::integer>());
BOOST_TEST(v4.is<toml::integer>());
BOOST_TEST(v3.is_integer());
BOOST_TEST(v4.is_integer());
BOOST_TEST(v3.cast<toml::value_t::integer>() == 54);
BOOST_TEST(v4.cast<toml::value_t::integer>() == -54);
BOOST_TEST(v3.as_integer() == 54);
BOOST_TEST(v4.as_integer() == -54);
toml::value v5(std::move(v1));
toml::value v6(std::move(v2));
BOOST_TEST(v5.type() == toml::value_t::integer);
BOOST_TEST(v6.type() == toml::value_t::integer);
BOOST_TEST(v5.is(toml::value_t::integer));
BOOST_TEST(v6.is(toml::value_t::integer));
BOOST_TEST(v5.is<toml::integer>());
BOOST_TEST(v6.is<toml::integer>());
BOOST_TEST(v5.is_integer());
BOOST_TEST(v6.is_integer());
BOOST_TEST(v5.cast<toml::value_t::integer>() == 54);
BOOST_TEST(v6.cast<toml::value_t::integer>() == -54);
BOOST_TEST(v5.as_integer() == 54);
BOOST_TEST(v6.as_integer() == -54);
v1 = true;
v2 = false;
BOOST_TEST(v1.type() == toml::value_t::boolean);
BOOST_TEST(v2.type() == toml::value_t::boolean);
BOOST_TEST(v1.is(toml::value_t::boolean));
BOOST_TEST(v2.is(toml::value_t::boolean));
BOOST_TEST(v1.is<toml::boolean>());
BOOST_TEST(v2.is<toml::boolean>());
BOOST_TEST(v1.is_boolean());
BOOST_TEST(v2.is_boolean());
BOOST_TEST(v1.cast<toml::value_t::boolean>() == true);
BOOST_TEST(v2.cast<toml::value_t::boolean>() == false);
BOOST_TEST(v1.as_boolean() == true);
BOOST_TEST(v2.as_boolean() == false);
}
BOOST_AUTO_TEST_CASE(test_value_float)
{
toml::value v1(3.14);
toml::value v2(3.14f);
BOOST_TEST(v1.type() == toml::value_t::floating);
BOOST_TEST(v2.type() == toml::value_t::floating);
BOOST_TEST(v1.is(toml::value_t::floating));
BOOST_TEST(v2.is(toml::value_t::floating));
BOOST_TEST(v1.is<toml::floating>());
BOOST_TEST(v2.is<toml::floating>());
BOOST_TEST(v1.is_floating());
BOOST_TEST(v2.is_floating());
BOOST_TEST(v1.cast<toml::value_t::floating>() == 3.14);
BOOST_TEST(v2.cast<toml::value_t::floating>() == 3.14,
boost::test_tools::tolerance(1e-2));
BOOST_TEST(v1.as_floating() == 3.14);
BOOST_TEST(v2.as_floating() == 3.14,
boost::test_tools::tolerance(1e-2));
BOOST_TEST(v1.as_floating(std::nothrow) == 3.14);
BOOST_TEST(v2.as_floating(std::nothrow) == 3.14,
boost::test_tools::tolerance(1e-2));
v1 = 2.718f;
v2 = 2.718;
BOOST_TEST(v1.type() == toml::value_t::floating);
BOOST_TEST(v2.type() == toml::value_t::floating);
BOOST_TEST(v1.is(toml::value_t::floating));
BOOST_TEST(v2.is(toml::value_t::floating));
BOOST_TEST(v1.is<toml::floating>());
BOOST_TEST(v2.is<toml::floating>());
BOOST_TEST(v1.is_floating());
BOOST_TEST(v2.is_floating());
BOOST_TEST(v1.cast<toml::value_t::floating>() == 2.718,
boost::test_tools::tolerance(1e-3));
BOOST_TEST(v2.cast<toml::value_t::floating>() == 2.718);
BOOST_TEST(v1.as_floating() == 2.718,
boost::test_tools::tolerance(1e-3));
BOOST_TEST(v2.as_floating() == 2.718);
toml::value v3(v1);
toml::value v4(v2);
BOOST_TEST(v3 == v1);
BOOST_TEST(v4 == v2);
BOOST_TEST(v3.type() == toml::value_t::floating);
BOOST_TEST(v4.type() == toml::value_t::floating);
BOOST_TEST(v3.is(toml::value_t::floating));
BOOST_TEST(v4.is(toml::value_t::floating));
BOOST_TEST(v3.is<toml::floating>());
BOOST_TEST(v4.is<toml::floating>());
BOOST_TEST(v3.is_floating());
BOOST_TEST(v4.is_floating());
BOOST_TEST(v3.cast<toml::value_t::floating>() == 2.718,
boost::test_tools::tolerance(1e-3));
BOOST_TEST(v4.cast<toml::value_t::floating>() == 2.718);
BOOST_TEST(v3.as_floating() == 2.718,
boost::test_tools::tolerance(1e-3));
BOOST_TEST(v4.as_floating() == 2.718);
toml::value v5(std::move(v1));
toml::value v6(std::move(v2));
BOOST_TEST(v5.type() == toml::value_t::floating);
BOOST_TEST(v6.type() == toml::value_t::floating);
BOOST_TEST(v5.is(toml::value_t::floating));
BOOST_TEST(v6.is(toml::value_t::floating));
BOOST_TEST(v5.is<toml::floating>());
BOOST_TEST(v6.is<toml::floating>());
BOOST_TEST(v5.is_floating());
BOOST_TEST(v6.is_floating());
BOOST_TEST(v5.cast<toml::value_t::floating>() == 2.718,
boost::test_tools::tolerance(1e-3));
BOOST_TEST(v6.cast<toml::value_t::floating>() == 2.718);
BOOST_TEST(v5.as_floating() == 2.718,
boost::test_tools::tolerance(1e-3));
BOOST_TEST(v6.as_floating() == 2.718);
v1 = true;
v2 = false;
BOOST_TEST(v1.type() == toml::value_t::boolean);
BOOST_TEST(v2.type() == toml::value_t::boolean);
BOOST_TEST(v1.is(toml::value_t::boolean));
BOOST_TEST(v2.is(toml::value_t::boolean));
BOOST_TEST(v1.is<toml::boolean>());
BOOST_TEST(v2.is<toml::boolean>());
BOOST_TEST(v1.is_boolean());
BOOST_TEST(v2.is_boolean());
BOOST_TEST(v1.cast<toml::value_t::boolean>() == true);
BOOST_TEST(v2.cast<toml::value_t::boolean>() == false);
BOOST_TEST(v1.as_boolean() == true);
BOOST_TEST(v2.as_boolean() == false);
}
BOOST_AUTO_TEST_CASE(test_value_string)
{
toml::value v1(std::string("foo"));
toml::value v2(std::string("foo"), toml::string_t::literal);
toml::value v3("foo");
BOOST_TEST(v1.type() == toml::value_t::string);
BOOST_TEST(v2.type() == toml::value_t::string);
BOOST_TEST(v3.type() == toml::value_t::string);
BOOST_TEST(v1.is(toml::value_t::string));
BOOST_TEST(v2.is(toml::value_t::string));
BOOST_TEST(v3.is(toml::value_t::string));
BOOST_TEST(v1.is<toml::string>());
BOOST_TEST(v2.is<toml::string>());
BOOST_TEST(v3.is<toml::string>());
BOOST_TEST(v1.is_string());
BOOST_TEST(v2.is_string());
BOOST_TEST(v3.is_string());
BOOST_TEST(v1.cast<toml::value_t::string>() == "foo");
BOOST_TEST(v2.cast<toml::value_t::string>() == "foo");
BOOST_TEST(v3.cast<toml::value_t::string>() == "foo");
BOOST_TEST(v1.as_string() == "foo");
BOOST_TEST(v2.as_string() == "foo");
BOOST_TEST(v3.as_string() == "foo");
BOOST_TEST(v1.as_string(std::nothrow) == "foo");
BOOST_TEST(v2.as_string(std::nothrow) == "foo");
BOOST_TEST(v3.as_string(std::nothrow) == "foo");
v1 = "bar";
v2 = "bar";
v3 = "bar";
BOOST_TEST(v1.type() == toml::value_t::string);
BOOST_TEST(v2.type() == toml::value_t::string);
BOOST_TEST(v3.type() == toml::value_t::string);
BOOST_TEST(v1.is(toml::value_t::string));
BOOST_TEST(v2.is(toml::value_t::string));
BOOST_TEST(v3.is(toml::value_t::string));
BOOST_TEST(v1.is_string());
BOOST_TEST(v2.is_string());
BOOST_TEST(v3.is_string());
BOOST_TEST(v1.cast<toml::value_t::string>() == "bar");
BOOST_TEST(v2.cast<toml::value_t::string>() == "bar");
BOOST_TEST(v3.cast<toml::value_t::string>() == "bar");
BOOST_TEST(v1.as_string() == "bar");
BOOST_TEST(v2.as_string() == "bar");
BOOST_TEST(v3.as_string() == "bar");
toml::value v4(v1);
toml::value v5(v2);
toml::value v6(v3);
BOOST_TEST(v4 == v1);
BOOST_TEST(v5 == v2);
BOOST_TEST(v6 == v3);
BOOST_TEST(v4.type() == toml::value_t::string);
BOOST_TEST(v5.type() == toml::value_t::string);
BOOST_TEST(v6.type() == toml::value_t::string);
BOOST_TEST(v4.is(toml::value_t::string));
BOOST_TEST(v5.is(toml::value_t::string));
BOOST_TEST(v6.is(toml::value_t::string));
BOOST_TEST(v4.is<toml::string>());
BOOST_TEST(v5.is<toml::string>());
BOOST_TEST(v6.is<toml::string>());
BOOST_TEST(v4.is_string());
BOOST_TEST(v5.is_string());
BOOST_TEST(v6.is_string());
BOOST_TEST(v4.cast<toml::value_t::string>() == "bar");
BOOST_TEST(v5.cast<toml::value_t::string>() == "bar");
BOOST_TEST(v6.cast<toml::value_t::string>() == "bar");
BOOST_TEST(v4.as_string() == "bar");
BOOST_TEST(v5.as_string() == "bar");
BOOST_TEST(v6.as_string() == "bar");
v4.cast<toml::value_t::string>().str.at(2) = 'z';
v5.cast<toml::value_t::string>().str.at(2) = 'z';
v6.cast<toml::value_t::string>().str.at(2) = 'z';
BOOST_TEST(v4.type() == toml::value_t::string);
BOOST_TEST(v5.type() == toml::value_t::string);
BOOST_TEST(v6.type() == toml::value_t::string);
BOOST_TEST(v4.is(toml::value_t::string));
BOOST_TEST(v5.is(toml::value_t::string));
BOOST_TEST(v6.is(toml::value_t::string));
BOOST_TEST(v4.is<toml::string>());
BOOST_TEST(v5.is<toml::string>());
BOOST_TEST(v6.is<toml::string>());
BOOST_TEST(v4.is_string());
BOOST_TEST(v5.is_string());
BOOST_TEST(v6.is_string());
BOOST_TEST(v4.as_string() == "baz");
BOOST_TEST(v5.as_string() == "baz");
BOOST_TEST(v6.as_string() == "baz");
v1 = true;
v2 = true;
v3 = true;
BOOST_TEST(v1.type() == toml::value_t::boolean);
BOOST_TEST(v2.type() == toml::value_t::boolean);
BOOST_TEST(v3.type() == toml::value_t::boolean);
BOOST_TEST(v1.is(toml::value_t::boolean));
BOOST_TEST(v2.is(toml::value_t::boolean));
BOOST_TEST(v3.is(toml::value_t::boolean));
BOOST_TEST(v1.is<toml::boolean>());
BOOST_TEST(v2.is<toml::boolean>());
BOOST_TEST(v3.is<toml::boolean>());
BOOST_TEST(v1.is_boolean());
BOOST_TEST(v2.is_boolean());
BOOST_TEST(v3.is_boolean());
BOOST_TEST(v1.cast<toml::value_t::boolean>() == true);
BOOST_TEST(v2.cast<toml::value_t::boolean>() == true);
BOOST_TEST(v3.cast<toml::value_t::boolean>() == true);
BOOST_TEST(v1.as_boolean() == true);
BOOST_TEST(v2.as_boolean() == true);
BOOST_TEST(v3.as_boolean() == true);
#if __cplusplus >= 201703L
std::string_view sv = "foo";
toml::value v7(sv);
toml::value v8(sv, toml::string_t::literal);
BOOST_TEST(v7.type() == toml::value_t::string);
BOOST_TEST(v8.type() == toml::value_t::string);
BOOST_TEST(v7.is(toml::value_t::string));
BOOST_TEST(v8.is(toml::value_t::string));
BOOST_TEST(v7.is<toml::string>());
BOOST_TEST(v8.is<toml::string>());
BOOST_TEST(v7.is_string());
BOOST_TEST(v8.is_string());
BOOST_TEST(v7.cast<toml::value_t::string>() == "foo");
BOOST_TEST(v8.cast<toml::value_t::string>() == "foo");
#endif
}
BOOST_AUTO_TEST_CASE(test_value_local_date)
{
toml::value v1(toml::local_date(2018, toml::month_t::Jan, 31));
BOOST_TEST(v1.type() == toml::value_t::local_date);
BOOST_TEST(v1.is(toml::value_t::local_date));
BOOST_TEST(v1.is<toml::local_date>());
BOOST_TEST(v1.is_local_date());
BOOST_TEST(v1.cast<toml::value_t::local_date>() ==
toml::local_date(2018, toml::month_t::Jan, 31));
BOOST_TEST(v1.as_local_date() ==
toml::local_date(2018, toml::month_t::Jan, 31));
BOOST_TEST(v1.as_local_date(std::nothrow) ==
toml::local_date(2018, toml::month_t::Jan, 31));
v1 = toml::local_date(2018, toml::month_t::Apr, 1);
BOOST_TEST(v1.type() == toml::value_t::local_date);
BOOST_TEST(v1.is(toml::value_t::local_date));
BOOST_TEST(v1.is<toml::local_date>());
BOOST_TEST(v1.is_local_date());
BOOST_TEST(v1.cast<toml::value_t::local_date>() ==
toml::local_date(2018, toml::month_t::Apr, 1));
BOOST_TEST(v1.as_local_date() ==
toml::local_date(2018, toml::month_t::Apr, 1));
toml::value v2(v1);
BOOST_TEST(v2 == v1);
BOOST_TEST(v2.type() == toml::value_t::local_date);
BOOST_TEST(v2.is(toml::value_t::local_date));
BOOST_TEST(v2.is<toml::local_date>());
BOOST_TEST(v2.is_local_date());
BOOST_TEST(v2.cast<toml::value_t::local_date>() ==
toml::local_date(2018, toml::month_t::Apr, 1));
BOOST_TEST(v2.as_local_date() ==
toml::local_date(2018, toml::month_t::Apr, 1));
v1 = true;
BOOST_TEST(v1.type() == toml::value_t::boolean);
BOOST_TEST(v1.is(toml::value_t::boolean));
BOOST_TEST(v1.is<toml::boolean>());
BOOST_TEST(v1.is_boolean());
BOOST_TEST(v1.cast<toml::value_t::boolean>() == true);
BOOST_TEST(v1.as_boolean() == true);
}
BOOST_AUTO_TEST_CASE(test_value_local_time)
{
toml::value v1(toml::local_time(12, 30, 45));
toml::value v2(std::chrono::hours(12) + std::chrono::minutes(30) +
std::chrono::seconds(45));
BOOST_TEST(v1.type() == toml::value_t::local_time);
BOOST_TEST(v2.type() == toml::value_t::local_time);
BOOST_TEST(v1.is(toml::value_t::local_time));
BOOST_TEST(v2.is(toml::value_t::local_time));
BOOST_TEST(v1.is<toml::local_time>());
BOOST_TEST(v2.is<toml::local_time>());
BOOST_TEST(v1.is_local_time());
BOOST_TEST(v2.is_local_time());
BOOST_TEST(v1.cast<toml::value_t::local_time>() ==
toml::local_time(12, 30, 45));
BOOST_TEST(v1.as_local_time() ==
toml::local_time(12, 30, 45));
BOOST_TEST(v2.cast<toml::value_t::local_time>() ==
toml::local_time(12, 30, 45));
BOOST_TEST(v2.as_local_time() ==
toml::local_time(12, 30, 45));
BOOST_TEST(v1.cast<toml::value_t::local_time>() ==
v2.cast<toml::value_t::local_time>());
BOOST_TEST(v1.as_local_time() ==
v2.as_local_time());
BOOST_TEST(v1.as_local_time(std::nothrow) ==
v2.as_local_time(std::nothrow));
v1 = toml::local_time(1, 30, 0, /*ms*/ 100, /*us*/ 0);
BOOST_TEST(v1.type() == toml::value_t::local_time);
BOOST_TEST(v1.is(toml::value_t::local_time));
BOOST_TEST(v1.is<toml::local_time>());
BOOST_TEST(v1.is_local_time());
BOOST_TEST(v1.cast<toml::value_t::local_time>() ==
toml::local_time(1, 30, 0, 100, 0));
BOOST_TEST(v1.as_local_time() ==
toml::local_time(1, 30, 0, 100, 0));
toml::value v3(v1);
BOOST_TEST(v3 == v1);
BOOST_TEST(v3.type() == toml::value_t::local_time);
BOOST_TEST(v3.is(toml::value_t::local_time));
BOOST_TEST(v3.is<toml::local_time>());
BOOST_TEST(v3.is_local_time());
BOOST_TEST(v3.cast<toml::value_t::local_time>() ==
toml::local_time(1, 30, 0, 100, 0));
BOOST_TEST(v3.as_local_time() ==
toml::local_time(1, 30, 0, 100, 0));
v1 = true;
BOOST_TEST(v1.type() == toml::value_t::boolean);
BOOST_TEST(v1.is(toml::value_t::boolean));
BOOST_TEST(v1.is<toml::boolean>());
BOOST_TEST(v1.is_boolean());
BOOST_TEST(v1.cast<toml::value_t::boolean>() == true);
BOOST_TEST(v1.as_boolean() == true);
}
BOOST_AUTO_TEST_CASE(test_value_local_datetime)
{
toml::value v1(toml::local_datetime(
toml::local_date(2018, toml::month_t::Jan, 31),
toml::local_time(12, 30, 45)
));
BOOST_TEST(v1.type() == toml::value_t::local_datetime);
BOOST_TEST(v1.is(toml::value_t::local_datetime));
BOOST_TEST(v1.is<toml::local_datetime>());
BOOST_TEST(v1.is_local_datetime());
BOOST_TEST(v1.cast<toml::value_t::local_datetime>() ==
toml::local_datetime(
toml::local_date(2018, toml::month_t::Jan, 31),
toml::local_time(12, 30, 45)));
BOOST_TEST(v1.as_local_datetime() ==
toml::local_datetime(
toml::local_date(2018, toml::month_t::Jan, 31),
toml::local_time(12, 30, 45)));
BOOST_TEST(v1.as_local_datetime(std::nothrow) ==
toml::local_datetime(
toml::local_date(2018, toml::month_t::Jan, 31),
toml::local_time(12, 30, 45)));
v1 = toml::local_datetime(
toml::local_date(2018, toml::month_t::Apr, 1),
toml::local_time(1, 15, 30));
BOOST_TEST(v1.type() == toml::value_t::local_datetime);
BOOST_TEST(v1.is(toml::value_t::local_datetime));
BOOST_TEST(v1.is<toml::local_datetime>());
BOOST_TEST(v1.is_local_datetime());
BOOST_TEST(v1.cast<toml::value_t::local_datetime>() ==
toml::local_datetime(
toml::local_date(2018, toml::month_t::Apr, 1),
toml::local_time(1, 15, 30)));
BOOST_TEST(v1.as_local_datetime() ==
toml::local_datetime(
toml::local_date(2018, toml::month_t::Apr, 1),
toml::local_time(1, 15, 30)));
toml::value v2(v1);
BOOST_TEST(v2 == v1);
BOOST_TEST(v2.type() == toml::value_t::local_datetime);
BOOST_TEST(v2.is(toml::value_t::local_datetime));
BOOST_TEST(v2.is<toml::local_datetime>());
BOOST_TEST(v2.is_local_datetime());
BOOST_TEST(v2.cast<toml::value_t::local_datetime>() ==
toml::local_datetime(
toml::local_date(2018, toml::month_t::Apr, 1),
toml::local_time(1, 15, 30)));
BOOST_TEST(v2.as_local_datetime() ==
toml::local_datetime(
toml::local_date(2018, toml::month_t::Apr, 1),
toml::local_time(1, 15, 30)));
v1 = true;
BOOST_TEST(v1.type() == toml::value_t::boolean);
BOOST_TEST(v1.is(toml::value_t::boolean));
BOOST_TEST(v1.is<toml::boolean>());
BOOST_TEST(v1.is_boolean());
BOOST_TEST(v1.cast<toml::value_t::boolean>() == true);
BOOST_TEST(v1.as_boolean() == true);
}
BOOST_AUTO_TEST_CASE(test_value_offset_datetime)
{
toml::value v1(toml::offset_datetime(
toml::local_date(2018, toml::month_t::Jan, 31),
toml::local_time(12, 30, 45),
toml::time_offset(9, 0)
));
BOOST_TEST(v1.type() == toml::value_t::offset_datetime);
BOOST_TEST(v1.is(toml::value_t::offset_datetime));
BOOST_TEST(v1.is<toml::offset_datetime>());
BOOST_TEST(v1.is_offset_datetime());
BOOST_TEST(v1.cast<toml::value_t::offset_datetime>() ==
toml::offset_datetime(
toml::local_date(2018, toml::month_t::Jan, 31),
toml::local_time(12, 30, 45),
toml::time_offset(9, 0)
));
BOOST_TEST(v1.as_offset_datetime() ==
toml::offset_datetime(
toml::local_date(2018, toml::month_t::Jan, 31),
toml::local_time(12, 30, 45),
toml::time_offset(9, 0)
));
BOOST_TEST(v1.as_offset_datetime(std::nothrow) ==
toml::offset_datetime(
toml::local_date(2018, toml::month_t::Jan, 31),
toml::local_time(12, 30, 45),
toml::time_offset(9, 0)
));
v1 = toml::offset_datetime(
toml::local_date(2018, toml::month_t::Apr, 1),
toml::local_time(1, 15, 30),
toml::time_offset(9, 0));
BOOST_TEST(v1.type() == toml::value_t::offset_datetime);
BOOST_TEST(v1.is(toml::value_t::offset_datetime));
BOOST_TEST(v1.is<toml::offset_datetime>());
BOOST_TEST(v1.is_offset_datetime());
BOOST_TEST(v1.cast<toml::value_t::offset_datetime>() ==
toml::offset_datetime(
toml::local_date(2018, toml::month_t::Apr, 1),
toml::local_time(1, 15, 30),
toml::time_offset(9, 0)));
BOOST_TEST(v1.as_offset_datetime() ==
toml::offset_datetime(
toml::local_date(2018, toml::month_t::Apr, 1),
toml::local_time(1, 15, 30),
toml::time_offset(9, 0)));
toml::value v2(v1);
BOOST_TEST(v2 == v1);
BOOST_TEST(v2.type() == toml::value_t::offset_datetime);
BOOST_TEST(v2.is(toml::value_t::offset_datetime));
BOOST_TEST(v2.is<toml::offset_datetime>());
BOOST_TEST(v2.is_offset_datetime());
BOOST_TEST(v2.cast<toml::value_t::offset_datetime>() ==
toml::offset_datetime(
toml::local_date(2018, toml::month_t::Apr, 1),
toml::local_time(1, 15, 30),
toml::time_offset(9, 0)));
BOOST_TEST(v2.as_offset_datetime() ==
toml::offset_datetime(
toml::local_date(2018, toml::month_t::Apr, 1),
toml::local_time(1, 15, 30),
toml::time_offset(9, 0)));
v1 = true;
BOOST_TEST(v1.type() == toml::value_t::boolean);
BOOST_TEST(v1.is(toml::value_t::boolean));
BOOST_TEST(v1.is<toml::boolean>());
BOOST_TEST(v1.is_boolean());
BOOST_TEST(v1.cast<toml::value_t::boolean>() == true);
BOOST_TEST(v1.as_boolean() == true);
}
BOOST_AUTO_TEST_CASE(test_value_array)
{
std::vector<int> v{1,2,3,4,5};
toml::value v1(v);
toml::value v2{6,7,8,9,0};
BOOST_TEST(v1.type() == toml::value_t::array);
BOOST_TEST(v1.is(toml::value_t::array));
BOOST_TEST(v1.is<toml::array>());
BOOST_TEST(v1.is_array());
BOOST_TEST(v2.type() == toml::value_t::array);
BOOST_TEST(v2.is(toml::value_t::array));
BOOST_TEST(v2.is<toml::array>());
BOOST_TEST(v2.is_array());
BOOST_TEST(v1.cast<toml::value_t::array>().at(0).cast<toml::value_t::integer>() == 1);
BOOST_TEST(v1.cast<toml::value_t::array>().at(1).cast<toml::value_t::integer>() == 2);
BOOST_TEST(v1.cast<toml::value_t::array>().at(2).cast<toml::value_t::integer>() == 3);
BOOST_TEST(v1.cast<toml::value_t::array>().at(3).cast<toml::value_t::integer>() == 4);
BOOST_TEST(v1.cast<toml::value_t::array>().at(4).cast<toml::value_t::integer>() == 5);
BOOST_TEST(v1.as_array().at(0).as_integer() == 1);
BOOST_TEST(v1.as_array().at(1).as_integer() == 2);
BOOST_TEST(v1.as_array().at(2).as_integer() == 3);
BOOST_TEST(v1.as_array().at(3).as_integer() == 4);
BOOST_TEST(v1.as_array().at(4).as_integer() == 5);
BOOST_TEST(v1.as_array(std::nothrow).at(0).as_integer() == 1);
BOOST_TEST(v1.as_array(std::nothrow).at(1).as_integer() == 2);
BOOST_TEST(v1.as_array(std::nothrow).at(2).as_integer() == 3);
BOOST_TEST(v1.as_array(std::nothrow).at(3).as_integer() == 4);
BOOST_TEST(v1.as_array(std::nothrow).at(4).as_integer() == 5);
BOOST_TEST(v2.cast<toml::value_t::array>().at(0).cast<toml::value_t::integer>() == 6);
BOOST_TEST(v2.cast<toml::value_t::array>().at(1).cast<toml::value_t::integer>() == 7);
BOOST_TEST(v2.cast<toml::value_t::array>().at(2).cast<toml::value_t::integer>() == 8);
BOOST_TEST(v2.cast<toml::value_t::array>().at(3).cast<toml::value_t::integer>() == 9);
BOOST_TEST(v2.cast<toml::value_t::array>().at(4).cast<toml::value_t::integer>() == 0);
v1 = {6,7,8,9,0};
v2 = v;
BOOST_TEST(v1.type() == toml::value_t::array);
BOOST_TEST(v1.is(toml::value_t::array));
BOOST_TEST(v1.is<toml::array>());
BOOST_TEST(v1.is_array());
BOOST_TEST(v2.type() == toml::value_t::array);
BOOST_TEST(v2.is(toml::value_t::array));
BOOST_TEST(v2.is<toml::array>());
BOOST_TEST(v2.is_array());
BOOST_TEST(v1.cast<toml::value_t::array>().at(0).cast<toml::value_t::integer>() == 6);
BOOST_TEST(v1.cast<toml::value_t::array>().at(1).cast<toml::value_t::integer>() == 7);
BOOST_TEST(v1.cast<toml::value_t::array>().at(2).cast<toml::value_t::integer>() == 8);
BOOST_TEST(v1.cast<toml::value_t::array>().at(3).cast<toml::value_t::integer>() == 9);
BOOST_TEST(v1.cast<toml::value_t::array>().at(4).cast<toml::value_t::integer>() == 0);
BOOST_TEST(v1.as_array().at(0).as_integer() == 6);
BOOST_TEST(v1.as_array().at(1).as_integer() == 7);
BOOST_TEST(v1.as_array().at(2).as_integer() == 8);
BOOST_TEST(v1.as_array().at(3).as_integer() == 9);
BOOST_TEST(v1.as_array().at(4).as_integer() == 0);
BOOST_TEST(v2.cast<toml::value_t::array>().at(0).cast<toml::value_t::integer>() == 1);
BOOST_TEST(v2.cast<toml::value_t::array>().at(1).cast<toml::value_t::integer>() == 2);
BOOST_TEST(v2.cast<toml::value_t::array>().at(2).cast<toml::value_t::integer>() == 3);
BOOST_TEST(v2.cast<toml::value_t::array>().at(3).cast<toml::value_t::integer>() == 4);
BOOST_TEST(v2.cast<toml::value_t::array>().at(4).cast<toml::value_t::integer>() == 5);
BOOST_TEST(v2.as_array().at(0).as_integer() == 1);
BOOST_TEST(v2.as_array().at(1).as_integer() == 2);
BOOST_TEST(v2.as_array().at(2).as_integer() == 3);
BOOST_TEST(v2.as_array().at(3).as_integer() == 4);
BOOST_TEST(v2.as_array().at(4).as_integer() == 5);
toml::value v3(v1);
BOOST_TEST(v3 == v1);
BOOST_TEST(v3.type() == toml::value_t::array);
BOOST_TEST(v3.is(toml::value_t::array));
BOOST_TEST(v3.is<toml::array>());
BOOST_TEST(v3.is_array());
BOOST_TEST(v3.cast<toml::value_t::array>().at(0).cast<toml::value_t::integer>() == 6);
BOOST_TEST(v3.cast<toml::value_t::array>().at(1).cast<toml::value_t::integer>() == 7);
BOOST_TEST(v3.cast<toml::value_t::array>().at(2).cast<toml::value_t::integer>() == 8);
BOOST_TEST(v3.cast<toml::value_t::array>().at(3).cast<toml::value_t::integer>() == 9);
BOOST_TEST(v3.cast<toml::value_t::array>().at(4).cast<toml::value_t::integer>() == 0);
BOOST_TEST(v3.as_array().at(0).as_integer() == 6);
BOOST_TEST(v3.as_array().at(1).as_integer() == 7);
BOOST_TEST(v3.as_array().at(2).as_integer() == 8);
BOOST_TEST(v3.as_array().at(3).as_integer() == 9);
BOOST_TEST(v3.as_array().at(4).as_integer() == 0);
v1 = true;
BOOST_TEST(v1.type() == toml::value_t::boolean);
BOOST_TEST(v1.is(toml::value_t::boolean));
BOOST_TEST(v1.is<toml::boolean>());
BOOST_TEST(v1.is_boolean());
BOOST_TEST(v1.cast<toml::value_t::boolean>() == true);
BOOST_TEST(v1.as_boolean() == true);
}
BOOST_AUTO_TEST_CASE(test_value_table)
{
toml::value v1{{"foo", 42}, {"bar", 3.14}, {"baz", "qux"}};
BOOST_TEST(v1.type() == toml::value_t::table);
BOOST_TEST(v1.is(toml::value_t::table));
BOOST_TEST(v1.is<toml::table>());
BOOST_TEST(v1.is_table());
BOOST_TEST(v1.cast<toml::value_t::table>().at("foo").cast<toml::value_t::integer>() == 42);
BOOST_TEST(v1.cast<toml::value_t::table>().at("bar").cast<toml::value_t::floating>() == 3.14);
BOOST_TEST(v1.cast<toml::value_t::table>().at("baz").cast<toml::value_t::string>().str == "qux");
BOOST_TEST(v1.as_table().at("foo").as_integer() == 42);
BOOST_TEST(v1.as_table().at("bar").as_floating() == 3.14);
BOOST_TEST(v1.as_table().at("baz").as_string().str == "qux");
BOOST_TEST(v1.as_table(std::nothrow).at("foo").as_integer() == 42);
BOOST_TEST(v1.as_table(std::nothrow).at("bar").as_floating() == 3.14);
BOOST_TEST(v1.as_table(std::nothrow).at("baz").as_string().str == "qux");
v1 = {{"foo", 2.71}, {"bar", 54}, {"baz", "quux"}};
BOOST_TEST(v1.type() == toml::value_t::table);
BOOST_TEST(v1.is(toml::value_t::table));
BOOST_TEST(v1.is<toml::table>());
BOOST_TEST(v1.is_table());
BOOST_TEST(v1.cast<toml::value_t::table>().at("foo").cast<toml::value_t::floating>() == 2.71);
BOOST_TEST(v1.cast<toml::value_t::table>().at("bar").cast<toml::value_t::integer>() == 54);
BOOST_TEST(v1.cast<toml::value_t::table>().at("baz").cast<toml::value_t::string>().str == "quux");
BOOST_TEST(v1.as_table().at("foo").as_floating() == 2.71);
BOOST_TEST(v1.as_table().at("bar").as_integer() == 54);
BOOST_TEST(v1.as_table().at("baz").as_string().str == "quux");
v1 = toml::table{{"foo", 2.71}, {"bar", 54}, {"baz", "quux"}};
BOOST_TEST(v1.type() == toml::value_t::table);
BOOST_TEST(v1.is(toml::value_t::table));
BOOST_TEST(v1.is<toml::table>());
BOOST_TEST(v1.is_table());
BOOST_TEST(v1.cast<toml::value_t::table>().at("foo").cast<toml::value_t::floating>() == 2.71);
BOOST_TEST(v1.cast<toml::value_t::table>().at("bar").cast<toml::value_t::integer>() == 54);
BOOST_TEST(v1.cast<toml::value_t::table>().at("baz").cast<toml::value_t::string>().str == "quux");
BOOST_TEST(v1.as_table().at("foo").as_floating() == 2.71);
BOOST_TEST(v1.as_table().at("bar").as_integer() == 54);
BOOST_TEST(v1.as_table().at("baz").as_string().str == "quux");
toml::value v3(v1);
BOOST_TEST(v3 == v1);
BOOST_TEST(v3.type() == toml::value_t::table);
BOOST_TEST(v3.is(toml::value_t::table));
BOOST_TEST(v3.is<toml::table>());
BOOST_TEST(v3.is_table());
BOOST_TEST(v3.cast<toml::value_t::table>().at("foo").cast<toml::value_t::floating>() == 2.71);
BOOST_TEST(v3.cast<toml::value_t::table>().at("bar").cast<toml::value_t::integer>() == 54);
BOOST_TEST(v3.cast<toml::value_t::table>().at("baz").cast<toml::value_t::string>().str == "quux");
BOOST_TEST(v3.as_table().at("foo").as_floating() == 2.71);
BOOST_TEST(v3.as_table().at("bar").as_integer() == 54);
BOOST_TEST(v3.as_table().at("baz").as_string().str == "quux");
v1 = true;
BOOST_TEST(v1.type() == toml::value_t::boolean);
BOOST_TEST(v1.is(toml::value_t::boolean));
BOOST_TEST(v1.is<toml::boolean>());
BOOST_TEST(v1.is_boolean());
BOOST_TEST(v1.cast<toml::value_t::boolean>() == true);
BOOST_TEST(v1.as_boolean() == true);
}
BOOST_AUTO_TEST_CASE(test_value_empty)
{
toml::value v1;
BOOST_TEST(v1.is_uninitialized());
BOOST_TEST(v1.is(toml::value_t::empty));
BOOST_CHECK_THROW(v1.as_boolean(), toml::type_error);
BOOST_CHECK_THROW(v1.as_integer(), toml::type_error);
BOOST_CHECK_THROW(v1.as_floating(), toml::type_error);
BOOST_CHECK_THROW(v1.as_string(), toml::type_error);
BOOST_CHECK_THROW(v1.as_offset_datetime(), toml::type_error);
BOOST_CHECK_THROW(v1.as_local_datetime(), toml::type_error);
BOOST_CHECK_THROW(v1.as_local_date(), toml::type_error);
BOOST_CHECK_THROW(v1.as_local_time(), toml::type_error);
BOOST_CHECK_THROW(v1.as_array(), toml::type_error);
BOOST_CHECK_THROW(v1.as_table(), toml::type_error);
}
| 38.770925 | 103 | 0.612402 | [
"vector"
] |
a0d3af47c1ad14412d489622886f7480a896e902 | 1,685 | cpp | C++ | src/Render.cpp | assalw/Allanite | 1709b9b523ed65dfa63e016abc4d27c55bcf874c | [
"BSD-2-Clause"
] | 2 | 2017-12-25T09:04:26.000Z | 2017-12-26T08:48:23.000Z | src/Render.cpp | assalw/Allanite | 1709b9b523ed65dfa63e016abc4d27c55bcf874c | [
"BSD-2-Clause"
] | null | null | null | src/Render.cpp | assalw/Allanite | 1709b9b523ed65dfa63e016abc4d27c55bcf874c | [
"BSD-2-Clause"
] | null | null | null | //
// Created by Wadie Assal on 25-12-17.
//
#include <GL/glew.h>
#include <string>
#include <stdexcept>
#include "../include/Render.h"
Render::Render() : windowOpened()
{}
void Render::createWindow(std::string name, int width, int height)
{
if (!windowOpened) {
SDL_LogInfo(SDL_LOG_CATEGORY_RENDER, "Creating Render window");
// OpenGL version 4
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
window = SDL_CreateWindow(name.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height,
SDL_WINDOW_OPENGL);
glContext = SDL_GL_CreateContext(window);
glewInit();
glViewport(0, 0, width, height);
// Print OpenGL version
SDL_LogInfo(SDL_LOG_CATEGORY_RENDER, "%s: %s", "OpenGL Version:", glGetString(GL_VERSION));
windowOpened = true;
}
else
{
SDL_LogInfo(SDL_LOG_CATEGORY_RENDER, "Can not open Render window in %s. Window already created.", name.c_str());
}
}
void Render::renderWindow()
{
if (windowOpened)
{
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(1.0, 1.0, 1.0, 1.0);
SDL_GL_SwapWindow(window);
}
else
{
throw std::runtime_error("Unable to render to window. Window not available.");
}
}
void Render::closeWindow()
{
if (windowOpened)
{
SDL_GL_DeleteContext(glContext);
SDL_DestroyWindow(window);
windowOpened = false;
}
}
Render::~Render()
{
closeWindow();
}
| 22.466667 | 120 | 0.642136 | [
"render"
] |
a0de365783dbafc3bbbabe54c15a267a19f7c458 | 6,199 | cpp | C++ | agent/chord_instr_agent.cpp | CSA-PLLab/STAND | 2e41f21b842ab43f23aecbf5527f6043ce837b29 | [
"BSD-3-Clause"
] | null | null | null | agent/chord_instr_agent.cpp | CSA-PLLab/STAND | 2e41f21b842ab43f23aecbf5527f6043ce837b29 | [
"BSD-3-Clause"
] | null | null | null | agent/chord_instr_agent.cpp | CSA-PLLab/STAND | 2e41f21b842ab43f23aecbf5527f6043ce837b29 | [
"BSD-3-Clause"
] | null | null | null | /*
* This agent expects at least one of the following arguments:
*
* 1. event_handler_class=<CLASS NAME>
* If this argument is present, then this agent takes the following actions:
* a) When the VMInit event is called by JVMTI, this agent calls the static
* synchronized method "void init(String)" in the class denoted by
* <CLASS NAME>; also, all agent options are passed via the string
* argument to that method.
* b) When the VMDeath event is called by JVMTI, this agent calls the static
* synchronized method "void done()" in the class denoted by <CLASS NAME>.
*
* 2. classes_file=<FILE NAME>
* If this argument is present, then this agent collects all loaded classes
* and writes their names, one per line, to the file denoted by <FILE NAME>.
*/
#include <jvmti.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
#include "iostream"
#include "fstream"
#include "set"
#include "map"
#include "vector"
#include "string"
static jvmtiEnv* jvmti_env;
#define MAX 20000
static bool list_loaded_classes = false;
static char classes_file[MAX];
static bool enable_event_handler = false;
static char event_handler_class[MAX];
static char* event_handler_args_str = NULL;
char* get_token(char *str, char *seps, char *buf, int max)
{
int len;
buf[0] = 0;
if (str == NULL || str[0] == 0)
return NULL;
str += strspn(str, seps);
if (str[0] == 0)
return NULL;
len = (int) strcspn(str, seps);
if (len >= max) {
cerr << "ERROR: get_token failed" << endl;
exit(1);
}
strncpy(buf, str, len);
buf[len] = 0;
return str + len;
}
static void call_event_handler_class_method(JNIEnv* jni_env,
const char* mName, const char* mSign, const char* args)
{
jclass c = jni_env->FindClass(event_handler_class);
if (c == NULL) {
cout << "ERROR: JNI: Cannot find class: " <<
event_handler_class << endl;
exit(1);
}
jmethodID m = jni_env->GetStaticMethodID(c, mName, mSign);
if (m == NULL) {
cout << "ERROR: JNI: Cannot get method " << mName << mSign <<
" from class: " << event_handler_class << endl;
exit(1);
}
if (args != NULL) {
jstring a = jni_env->NewStringUTF(args);
jni_env->CallStaticObjectMethod(c, m, a);
} else
jni_env->CallStaticObjectMethod(c, m);
}
static void JNICALL VMStart(jvmtiEnv *jvmti_env, JNIEnv* jni_env)
{
cout << "ENTER VMStart" << endl;
cout << "LEAVE VMStart" << endl;
}
static void JNICALL VMInit(jvmtiEnv *jvmti_env, JNIEnv* jni_env, jthread thread)
{
cout << "ENTER VMInit" << endl;
if (enable_event_handler) {
const char* mName = "init";
const char* mSign = "(Ljava/lang/String;)V";
call_event_handler_class_method(jni_env, mName, mSign, event_handler_args_str);
}
cout << "LEAVE VMInit" << endl;
}
static void JNICALL VMDeath(jvmtiEnv *jvmti_env, JNIEnv* jni_env)
{
cout << "ENTER VMDeath" << endl;
if (list_loaded_classes) {
jint class_count;
jclass* classes;
jvmtiError result;
result = jvmti_env->GetLoadedClasses(&class_count, &classes);
assert(result == JVMTI_ERROR_NONE);
fstream classes_out;
classes_out.open(classes_file, ios::out);
for (int i = 0; i < class_count; i++) {
jclass klass = classes[i];
char* class_name;
jvmti_env->GetClassSignature(klass, &class_name, NULL);
if (class_name[0] == '[')
continue;
classes_out << class_name << endl;
}
classes_out.close();
}
if (enable_event_handler) {
const char* mName = "done";
const char* mSign = "()V";
call_event_handler_class_method(jni_env, mName, mSign, NULL);
}
cout << "LEAVE VMDeath" << endl;
}
JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *jvm, char *options, void *reserved)
{
cout << "ENTER Agent_OnLoad" << endl;
if (options == NULL) {
cerr << "ERROR: Expected options to agent" << endl;
exit(1);
}
char* next = options;
while (1) {
char token[MAX];
next = get_token(next, (char*) ",=", token, sizeof(token));
if (next == NULL)
break;
if (strcmp(token, "event_handler_class") == 0) {
next = get_token(next, (char*) ",=", event_handler_class, MAX);
if (next == NULL) {
cerr << "ERROR: Bad option event_handler_class=<name>: "
<< options << endl;
exit(1);
}
enable_event_handler = true;
continue;
}
if (strcmp(token, "classes_file") == 0) {
next = get_token(next, (char*) ",=", classes_file, MAX);
if (next == NULL) {
cerr << "ERROR: Bad option classes_file=<name>: "
<< options << endl;
exit(1);
}
list_loaded_classes = true;
continue;
}
}
if (enable_event_handler) {
event_handler_args_str = strdup(options);
assert(event_handler_args_str != NULL);
}
jvmtiError retval;
jint result = jvm->GetEnv((void**) &jvmti_env, JVMTI_VERSION_1_0);
assert(result == JNI_OK);
retval = jvmti_env->SetEventNotificationMode(JVMTI_ENABLE,
JVMTI_EVENT_VM_START, NULL);
assert(retval == JVMTI_ERROR_NONE);
retval = jvmti_env->SetEventNotificationMode(JVMTI_ENABLE,
JVMTI_EVENT_VM_INIT, NULL);
assert(retval == JVMTI_ERROR_NONE);
retval = jvmti_env->SetEventNotificationMode(JVMTI_ENABLE,
JVMTI_EVENT_VM_DEATH, NULL);
assert(retval == JVMTI_ERROR_NONE);
jvmtiCapabilities capa;
memset(&capa, 0, sizeof(capa));
capa.can_tag_objects = 1;
retval = jvmti_env->AddCapabilities(&capa);
assert(retval == JVMTI_ERROR_NONE);
jvmtiEventCallbacks callbacks;
memset(&callbacks, 0, sizeof(callbacks));
callbacks.VMStart = &VMStart;
callbacks.VMInit = &VMInit;
callbacks.VMDeath = &VMDeath;
retval = jvmti_env->SetEventCallbacks(&callbacks, sizeof(callbacks));
assert(retval == JVMTI_ERROR_NONE);
cout << "LEAVE Agent_OnLoad" << endl;
return JNI_OK;
}
JNIEXPORT void JNICALL Agent_OnUnload(JavaVM *jvm)
{
cout << "ENTER Agent_OnUnload" << endl;
cout << "LEAVE Agent_OnUnload" << endl;
}
| 29.379147 | 82 | 0.63607 | [
"vector"
] |
a0df2f128a7067cfa90c981cc92926867cd3013a | 1,401 | hh | C++ | extern/polymesh/src/polymesh/attribute_base.hh | huzjkevin/portal_maze_zgl | efb32b1c3430f20638c1401095999ecb4d0af5aa | [
"MIT"
] | null | null | null | extern/polymesh/src/polymesh/attribute_base.hh | huzjkevin/portal_maze_zgl | efb32b1c3430f20638c1401095999ecb4d0af5aa | [
"MIT"
] | null | null | null | extern/polymesh/src/polymesh/attribute_base.hh | huzjkevin/portal_maze_zgl | efb32b1c3430f20638c1401095999ecb4d0af5aa | [
"MIT"
] | null | null | null | #pragma once
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <vector>
// Helper for mesh-based attribute bookkeeping
namespace polymesh
{
class Mesh;
template <class MeshT>
struct low_level_api_base;
template <class tag>
struct primitive_attribute_base
{
// members
protected:
Mesh const* mMesh;
private:
primitive_attribute_base* mNextAttribute = nullptr;
primitive_attribute_base* mPrevAttribute = nullptr;
protected:
primitive_attribute_base(Mesh const* mesh) : mMesh(mesh) {} // no registration, it's too early!
virtual void resize_from(int old_size) = 0;
virtual void clear_with_default() = 0;
virtual void apply_remapping(std::vector<int> const& map) = 0;
virtual void apply_transpositions(std::vector<std::pair<int, int>> const& ts) = 0;
virtual size_t byte_size() const = 0;
virtual size_t allocated_byte_size() const = 0;
// links and unlinks the attribute with the mesh
// CAUTION: does not change data in any way.
void register_attr();
void deregister_attr();
friend class Mesh;
template <class MeshT>
friend struct low_level_api_base;
public:
virtual ~primitive_attribute_base()
{
// CAUTION: this must always be called in case attributes get non-default ctors
deregister_attr();
}
Mesh const& mesh() const { return *mMesh; }
};
} // namespace polymesh
| 24.578947 | 99 | 0.709493 | [
"mesh",
"vector"
] |
a0e08eacf40a49ae98e30607a7dae1b6d61b7310 | 1,802 | hpp | C++ | programs/koinos-types/lang/koinos_codegen_cpp/rt/exceptions.hpp | joticajulian/koinos-types | 7d01248437d063deb780af03057737e4937f82d1 | [
"MIT"
] | null | null | null | programs/koinos-types/lang/koinos_codegen_cpp/rt/exceptions.hpp | joticajulian/koinos-types | 7d01248437d063deb780af03057737e4937f82d1 | [
"MIT"
] | null | null | null | programs/koinos-types/lang/koinos_codegen_cpp/rt/exceptions.hpp | joticajulian/koinos-types | 7d01248437d063deb780af03057737e4937f82d1 | [
"MIT"
] | null | null | null | #pragma once
#include <stdexcept>
#define KOINOS_PACK_MAX_ARRAY_ALLOC_SIZE (1024*1024*10)
#define KOINOS_PACK_MAX_RECURSION_DEPTH (20)
namespace koinos::pack {
#define KOINOS_PACK_DECLARE_EXCEPTION( exception ) \
struct exception final : std::runtime_error \
{ \
exception( const char* what_arg ) : \
std::runtime_error( what_arg ) {}; \
virtual ~exception() override {} \
}
/*
* Generic serialization error. Any uses should consider being replaced
* with a more specific/descriptire exception.
*/
KOINOS_PACK_DECLARE_EXCEPTION( parse_error );
/*
* Parsing input recursed too deep.
*/
KOINOS_PACK_DECLARE_EXCEPTION( depth_violation );
/*
* Parsing input would require allocation too much memory
*/
KOINOS_PACK_DECLARE_EXCEPTION( allocation_violation );
/*
* Unexpected end of stream while packing/unpacking binary.
*/
KOINOS_PACK_DECLARE_EXCEPTION( stream_error );
/*
* JSON parsing is out of bounds for the destination integer type.
*/
KOINOS_PACK_DECLARE_EXCEPTION( json_int_out_of_bounds );
/*
* There was a problem serializing to the JSON object. This is probably
* caused by programmer error.
*/
KOINOS_PACK_DECLARE_EXCEPTION( json_serialization_error );
/*
* Incoming JSON type does not match expected type.
*/
KOINOS_PACK_DECLARE_EXCEPTION( json_type_mismatch );
/*
* There was a problem decoding an encoded byte string
*/
KOINOS_PACK_DECLARE_EXCEPTION( json_decode_error );
KOINOS_PACK_DECLARE_EXCEPTION( bad_cast_exception );
/*
* Opqaue type is not unboxed
*/
KOINOS_PACK_DECLARE_EXCEPTION( opaque_not_unboxed );
/*
* Opaque type is locked
*/
KOINOS_PACK_DECLARE_EXCEPTION( opaque_locked );
} // koinos::pack
#undef KOINOS_PACK_DECLARE_EXCEPTION
| 23.710526 | 71 | 0.726415 | [
"object"
] |
a0e102465cfabf66636a081b02ee194e68b7013f | 1,049 | hpp | C++ | TGEngine/public/graphics/vulkan/VulkanShaderPipe.hpp | Troblecodings/TGEngine | 09c845f6ad68f99e51fdd7f9139e45475010f3d9 | [
"Apache-2.0"
] | 9 | 2018-03-22T16:01:54.000Z | 2022-01-12T02:27:10.000Z | TGEngine/public/graphics/vulkan/VulkanShaderPipe.hpp | Troblecodings/TGEngine | 09c845f6ad68f99e51fdd7f9139e45475010f3d9 | [
"Apache-2.0"
] | 20 | 2018-03-11T12:35:55.000Z | 2020-02-19T17:36:47.000Z | TGEngine/public/graphics/vulkan/VulkanShaderPipe.hpp | Troblecodings/TGEngine | 09c845f6ad68f99e51fdd7f9139e45475010f3d9 | [
"Apache-2.0"
] | 6 | 2019-02-26T13:59:55.000Z | 2021-07-15T14:11:10.000Z | #pragma once
#include <vulkan/vulkan.hpp>
#include <string>
#include <vector>
#include <array>
namespace tge::shader {
using namespace vk;
_CONSTEXPR20_CONTAINER std::string operator""_str(const char *chr,
std::size_t size) {
return std::string(chr, size);
}
const std::array shaderNames = {
std::vector({"assets/testvec4.vert"_str, "assets/test.frag"_str}),
std::vector({"assets/testUV.vert"_str, "assets/testTexture.frag"_str})};
struct VulkanShaderPipe {
std::vector<std::pair<std::vector<uint32_t>, ShaderStageFlagBits>> shader;
std::vector<PipelineShaderStageCreateInfo> pipelineShaderStage;
std::vector<VertexInputBindingDescription> vertexInputBindings;
std::vector<VertexInputAttributeDescription> vertexInputAttributes;
PipelineVertexInputStateCreateInfo inputStateCreateInfo;
PipelineRasterizationStateCreateInfo rasterization;
std::vector<DescriptorSetLayoutBinding> descriptorLayoutBindings;
size_t layoutID = UINT64_MAX;
};
} // namespace tge::graphics
| 31.787879 | 76 | 0.745472 | [
"vector"
] |
a0e1d3ba957e9268ea4d852f75d88113b72c4c58 | 13,916 | cxx | C++ | PathReconstruction/Widgets/qSlicerPathReconstructionTableWidget.cxx | tavaughan/SlicerPathReconstruction | 5504e03ade1892e7c0186495c21e64ebf93d3cce | [
"MIT"
] | 1 | 2019-04-18T15:00:05.000Z | 2019-04-18T15:00:05.000Z | PathReconstruction/Widgets/qSlicerPathReconstructionTableWidget.cxx | tavaughan/SlicerPathReconstruction | 5504e03ade1892e7c0186495c21e64ebf93d3cce | [
"MIT"
] | 11 | 2018-03-24T16:06:06.000Z | 2019-04-10T18:36:22.000Z | PathReconstruction/Widgets/qSlicerPathReconstructionTableWidget.cxx | tavaughan/SlicerPathReconstruction | 5504e03ade1892e7c0186495c21e64ebf93d3cce | [
"MIT"
] | 1 | 2018-04-02T14:00:33.000Z | 2018-04-02T14:00:33.000Z | /*==============================================================================
Copyright (c) Thomas Vaughan
Laboratory for Percutaneous Surgery (PerkLab)
Queen's University, Kingston, ON, Canada. All Rights Reserved.
See COPYRIGHT.txt
or http://www.slicer.org/copyright/copyright.txt for details.
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "qSlicerPathReconstructionTableWidget.h"
#include "vtkSlicerPathReconstructionLogic.h"
// QSlicer includes
#include "qSlicerApplication.h"
#include "qSlicerModuleManager.h"
#include "qSlicerAbstractCoreModule.h"
// MRML includes
#include <vtkMRMLScene.h>
#include <vtkMRMLModelNode.h>
#include "vtkMRMLPathReconstructionNode.h"
#include "vtkMRMLMarkupsToModelNode.h"
// Qt includes
#include <QDebug>
#include <QtGui>
#include <QtPlugin>
#include <QTableWidgetItem>
//-----------------------------------------------------------------------------
/// \ingroup Slicer_QtModules_PathReconstruction
class qSlicerPathReconstructionTableWidgetPrivate : public Ui_qSlicerPathReconstructionTableWidget
{
Q_DECLARE_PUBLIC( qSlicerPathReconstructionTableWidget );
protected:
qSlicerPathReconstructionTableWidget* const q_ptr;
public:
qSlicerPathReconstructionTableWidgetPrivate( qSlicerPathReconstructionTableWidget& object);
vtkWeakPointer< vtkMRMLPathReconstructionNode > PathReconstructionNode;
vtkWeakPointer< vtkSlicerPathReconstructionLogic > PathReconstructionLogic;
};
// --------------------------------------------------------------------------
qSlicerPathReconstructionTableWidgetPrivate::qSlicerPathReconstructionTableWidgetPrivate( qSlicerPathReconstructionTableWidget& object ) : q_ptr( &object )
{
}
//-----------------------------------------------------------------------------
qSlicerPathReconstructionTableWidget::qSlicerPathReconstructionTableWidget( QWidget* parentWidget ) : Superclass( parentWidget ) , d_ptr( new qSlicerPathReconstructionTableWidgetPrivate( *this ) )
{
this->setup();
}
//-----------------------------------------------------------------------------
qSlicerPathReconstructionTableWidget::~qSlicerPathReconstructionTableWidget()
{
this->setPathReconstructionNode( NULL );
}
//-----------------------------------------------------------------------------
void qSlicerPathReconstructionTableWidget::setup()
{
Q_D( qSlicerPathReconstructionTableWidget );
d->setupUi( this );
// This cannot be called by the constructor, because Slicer may not exist when the constructor is called
d->PathReconstructionLogic = NULL;
if (qSlicerApplication::application() != NULL && qSlicerApplication::application()->moduleManager() != NULL)
{
qSlicerAbstractCoreModule* pathReconstructionModule = qSlicerApplication::application()->moduleManager()->module( "PathReconstruction" );
if ( pathReconstructionModule != NULL )
{
d->PathReconstructionLogic = vtkSlicerPathReconstructionLogic::SafeDownCast( pathReconstructionModule->logic() );
vtkMRMLScene* scene = d->PathReconstructionLogic->GetMRMLScene();
this->setMRMLScene( scene );
}
}
if (d->PathReconstructionLogic == NULL)
{
qCritical() << Q_FUNC_INFO << ": path reconstruction module logic not found. Some functionality will not work.";
}
connect( d->PathReconstructionNodeComboBox, SIGNAL( currentNodeChanged( vtkMRMLNode* ) ), this, SLOT( updateGUIFromMRML() ) );
connect( d->FittingParametersComboBox, SIGNAL( nodeAddedByUser( vtkMRMLNode* ) ), this, SLOT( onFittingParametersAdded( vtkMRMLNode* ) ) );
connect( d->FittingParametersComboBox, SIGNAL( currentNodeChanged( vtkMRMLNode* ) ), this, SLOT( onFittingParametersChanged() ) );
connect( d->FittingColorPicker, SIGNAL( colorChanged( QColor ) ), this, SLOT( onFittingColorChanged( QColor ) ) );
connect( d->RefitPathsButton, SIGNAL( clicked() ), this, SLOT( onRefitPathsButtonClicked() ) );
}
//-----------------------------------------------------------------------------
vtkMRMLNode* qSlicerPathReconstructionTableWidget::currentNode() const
{
Q_D( const qSlicerPathReconstructionTableWidget );
return d->PathReconstructionNode;
}
//-----------------------------------------------------------------------------
QTableWidget* qSlicerPathReconstructionTableWidget::tableWidget() const
{
Q_D( const qSlicerPathReconstructionTableWidget );
return d->PathsTable;
}
//------------------------------------------------------------------------------
qMRMLNodeComboBox* qSlicerPathReconstructionTableWidget::pathReconstructionNodeComboBox() const
{
Q_D( const qSlicerPathReconstructionTableWidget );
return d->PathReconstructionNodeComboBox;
}
//------------------------------------------------------------------------------
void qSlicerPathReconstructionTableWidget::setMRMLScene(vtkMRMLScene* scene)
{
this->Superclass::setMRMLScene(scene);
this->updateGUIFromMRML();
}
//-----------------------------------------------------------------------------
void qSlicerPathReconstructionTableWidget::setPathReconstructionNode( vtkMRMLNode* currentNode )
{
Q_D( qSlicerPathReconstructionTableWidget );
vtkMRMLPathReconstructionNode* pathReconstructionNode = vtkMRMLPathReconstructionNode::SafeDownCast( currentNode );
if ( pathReconstructionNode == d->PathReconstructionNode )
{
return;
}
this->qvtkReconnect( d->PathReconstructionNode, pathReconstructionNode, vtkCommand::ModifiedEvent, this, SLOT( updateGUIFromMRML() ) );
this->qvtkReconnect( d->PathReconstructionNode, pathReconstructionNode, vtkMRMLPathReconstructionNode::InputDataModifiedEvent, this, SLOT( updateGUIFromMRML() ) );
// The table should scroll to the bottom when new paths are added
this->qvtkReconnect( d->PathReconstructionNode, pathReconstructionNode, vtkMRMLPathReconstructionNode::PathAddedEvent, d->PathsTable, SLOT( scrollToBottom() ) );
d->PathReconstructionNode = pathReconstructionNode;
this->updateGUIFromMRML();
}
//-----------------------------------------------------------------------------
void qSlicerPathReconstructionTableWidget::setPathReconstructionNodeComboBoxVisible( bool visible )
{
Q_D( qSlicerPathReconstructionTableWidget );
d->PathReconstructionNodeComboBox->setVisible( visible );
}
//-----------------------------------------------------------------------------
void qSlicerPathReconstructionTableWidget::setFittingParametersVisible( bool visible )
{
Q_D( qSlicerPathReconstructionTableWidget );
d->FittingParametersLabel->setVisible( visible );
d->FittingParametersComboBox->setVisible( visible );
d->RefitPathsButton->setVisible( visible );
}
//-----------------------------------------------------------------------------
void qSlicerPathReconstructionTableWidget::onFittingParametersAdded( vtkMRMLNode* newNode )
{
Q_D( qSlicerPathReconstructionTableWidget );
vtkMRMLPathReconstructionNode* pathReconstructionNode = vtkMRMLPathReconstructionNode::SafeDownCast( d->PathReconstructionNode );
if ( pathReconstructionNode == NULL )
{
qCritical() << Q_FUNC_INFO << ": invalid parameter node";
return;
}
vtkMRMLMarkupsToModelNode* markupsToModelNode = vtkMRMLMarkupsToModelNode::SafeDownCast( newNode );
if ( markupsToModelNode == NULL )
{
qCritical() << Q_FUNC_INFO << ": invalid MarkupsToModel node";
return;
}
pathReconstructionNode->ApplyDefaultSettingsToMarkupsToModelNode( markupsToModelNode );
}
//-----------------------------------------------------------------------------
void qSlicerPathReconstructionTableWidget::onFittingParametersChanged()
{
Q_D( qSlicerPathReconstructionTableWidget );
vtkMRMLPathReconstructionNode* pathReconstructionNode = vtkMRMLPathReconstructionNode::SafeDownCast( d->PathReconstructionNode );
if ( pathReconstructionNode == NULL )
{
qCritical() << Q_FUNC_INFO << ": invalid parameter node";
return;
}
const char* markupsToModelNodeID = NULL;
vtkMRMLMarkupsToModelNode* markupsToModelNode = vtkMRMLMarkupsToModelNode::SafeDownCast( d->FittingParametersComboBox->currentNode() );
if( markupsToModelNode != NULL )
{
markupsToModelNodeID = markupsToModelNode->GetID();
}
pathReconstructionNode->SetAndObserveMarkupsToModelNodeID( markupsToModelNodeID );
}
//-----------------------------------------------------------------------------
void qSlicerPathReconstructionTableWidget::onFittingColorChanged( QColor col )
{
Q_D( qSlicerPathReconstructionTableWidget );
vtkMRMLPathReconstructionNode* pathReconstructionNode = vtkMRMLPathReconstructionNode::SafeDownCast( d->PathReconstructionNode );
if ( pathReconstructionNode == NULL )
{
qCritical() << Q_FUNC_INFO << ": invalid parameter node";
return;
}
double red = (double)col.redF();
double green = (double)col.greenF();
double blue = (double)col.blueF();
pathReconstructionNode->SetPathColor( red, green, blue );
}
//-----------------------------------------------------------------------------
void qSlicerPathReconstructionTableWidget::onRefitPathsButtonClicked()
{
Q_D( qSlicerPathReconstructionTableWidget );
vtkMRMLPathReconstructionNode* pathReconstructionNode = vtkMRMLPathReconstructionNode::SafeDownCast( d->PathReconstructionNode );
if ( pathReconstructionNode == NULL )
{
qCritical() << Q_FUNC_INFO << ": invalid parameter node";
return;
}
if ( d->PathReconstructionLogic == NULL )
{
qWarning() << Q_FUNC_INFO << ": invalid module logic";
return;
}
d->PathReconstructionLogic->RefitAllPaths( pathReconstructionNode );
}
//-----------------------------------------------------------------------------
void qSlicerPathReconstructionTableWidget::updateGUIFromMRML()
{
Q_D(qSlicerPathReconstructionTableWidget);
if ( this->mrmlScene() == NULL )
{
qCritical() << Q_FUNC_INFO << ": Scene is invalid";
return;
}
vtkMRMLPathReconstructionNode* currentPathReconstructionNode = vtkMRMLPathReconstructionNode::SafeDownCast( d->PathReconstructionNode );
if ( currentPathReconstructionNode == NULL )
{
d->FittingParametersComboBox->setEnabled( false );
d->FittingColorPicker->setEnabled( false );
d->RefitPathsButton->setEnabled( false );
d->PathsTable->setRowCount( 0 );
return;
}
// Update the fitting parameters
bool wasBlockedFittingColor = d->FittingColorPicker->blockSignals( true );
d->FittingColorPicker->setEnabled( true );
QColor pathColor;
double pathRed = currentPathReconstructionNode->GetPathColorRed();
double pathGreen = currentPathReconstructionNode->GetPathColorGreen();
double pathBlue = currentPathReconstructionNode->GetPathColorBlue();
pathColor.setRgbF( pathRed, pathGreen, pathBlue );
d->FittingColorPicker->setColor( pathColor );
d->FittingColorPicker->blockSignals( wasBlockedFittingColor );
bool wasBlockedFittingParameters = d->FittingParametersComboBox->blockSignals( true );
d->FittingParametersComboBox->setEnabled( true );
vtkMRMLMarkupsToModelNode* fittingParametersNode = currentPathReconstructionNode->GetMarkupsToModelNode();
if ( fittingParametersNode != NULL )
{
d->FittingParametersComboBox->setCurrentNode( fittingParametersNode );
d->RefitPathsButton->setEnabled( true );
}
else
{
d->RefitPathsButton->setEnabled( false );
}
d->FittingParametersComboBox->blockSignals( wasBlockedFittingParameters );
// Update the fiducials table
bool wasBlockedTableWidget = d->PathsTable->blockSignals( true );
const int suffixColumn = 0;
const int pointsNameColumn = 1;
const int pathNameColumn = 2;
const int numberOfColumns = 3;
d->PathsTable->clear();
d->PathsTable->setColumnCount( numberOfColumns );
d->PathsTable->setHorizontalHeaderLabels( QStringList() << "ID" << "Markups" << "Model" );
#if (QT_VERSION < QT_VERSION_CHECK(5, 0, 0))
d->PathsTable->horizontalHeader()->setResizeMode( QHeaderView::Stretch );
#else
d->PathsTable->horizontalHeader()->setSectionResizeMode( QHeaderView::Stretch );
#endif
d->PathsTable->setContextMenuPolicy( Qt::CustomContextMenu );
d->PathsTable->setSelectionBehavior( QAbstractItemView::SelectRows ); // only select rows rather than cells
vtkSmartPointer< vtkIntArray > suffixes = vtkSmartPointer< vtkIntArray >::New();
currentPathReconstructionNode->GetSuffixes( suffixes );
int numberOfSuffixes = suffixes->GetNumberOfTuples();
d->PathsTable->setRowCount( numberOfSuffixes );
for ( int suffixIndex = 0; suffixIndex < numberOfSuffixes; suffixIndex++ )
{
int suffix = suffixes->GetTuple1( suffixIndex );
QTableWidgetItem* suffixItem = new QTableWidgetItem( QString::number( suffix ) );
d->PathsTable->setItem( suffixIndex, suffixColumn, suffixItem );
std::string pointsName;
vtkMRMLModelNode* pointsNode = currentPathReconstructionNode->GetPointsModelNodeBySuffix( suffix );
if ( pointsNode == NULL )
{
pointsName = "NULL";
}
else
{
pointsName = pointsNode->GetName();
}
QTableWidgetItem* pointsNameItem = new QTableWidgetItem( QString::fromStdString( pointsName ) );
d->PathsTable->setItem( suffixIndex, pointsNameColumn, pointsNameItem );
std::string pathName;
vtkMRMLModelNode* pathNode = currentPathReconstructionNode->GetPathModelNodeBySuffix( suffix );
if ( pathNode == NULL )
{
pathName = "NULL";
}
else
{
pathName = pathNode->GetName();
}
QTableWidgetItem* pathNameItem = new QTableWidgetItem( QString::fromStdString( pathName ) );
d->PathsTable->setItem( suffixIndex, pathNameColumn, pathNameItem );
}
d->PathsTable->blockSignals( wasBlockedTableWidget );
}
| 39.646724 | 196 | 0.685686 | [
"object",
"model"
] |
a0e5a0a3f51e9e83ecebe3b1f425ecfe2816d48b | 2,221 | cpp | C++ | cpp/33.search-in-rotated-sorted-array.cpp | vermouth1992/Leetcode | 0d7dda52b12f9e01d88fc279243742cd8b4bcfd1 | [
"MIT"
] | null | null | null | cpp/33.search-in-rotated-sorted-array.cpp | vermouth1992/Leetcode | 0d7dda52b12f9e01d88fc279243742cd8b4bcfd1 | [
"MIT"
] | null | null | null | cpp/33.search-in-rotated-sorted-array.cpp | vermouth1992/Leetcode | 0d7dda52b12f9e01d88fc279243742cd8b4bcfd1 | [
"MIT"
] | null | null | null | /*
* @lc app=leetcode id=33 lang=cpp
*
* [33] Search in Rotated Sorted Array
*
* https://leetcode.com/problems/search-in-rotated-sorted-array/description/
*
* algorithms
* Medium (33.15%)
* Total Accepted: 498.4K
* Total Submissions: 1.5M
* Testcase Example: '[4,5,6,7,0,1,2]\n0'
*
* Suppose an array sorted in ascending order is rotated at some pivot unknown
* to you beforehand.
*
* (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]).
*
* You are given a target value to search. If found in the array return its
* index, otherwise return -1.
*
* You may assume no duplicate exists in the array.
*
* Your algorithm's runtime complexity must be in the order of O(log n).
*
* Example 1:
*
*
* Input: nums = [4,5,6,7,0,1,2], target = 0
* Output: 4
*
*
* Example 2:
*
*
* Input: nums = [4,5,6,7,0,1,2], target = 3
* Output: -1
*
*/
#include "common.hpp"
class Solution {
private:
// from [start, end)
int searchHelper(vector<int>& nums, size_t start, size_t end, int target) {
if (end - start <= 1) {
if (nums[start] == target) return start;
else return -1;
}
int mid = (start + end) / 2;
// [start, mid)
if (start == mid - 1) {
if (nums[start] == target) return start;
return searchHelper(nums, mid, end, target);
} else if (mid == end - 1) {
if (nums[mid] == target) return mid;
else searchHelper(nums, start, mid, target);
}
if (nums[start] < nums[mid - 1]) {
if (target >= nums[start] && target <= nums[mid - 1]) {
return searchHelper(nums, start, mid, target);
} else {
return searchHelper(nums, mid, end, target);
}
} else {
if (target >= nums[mid] && target <= nums[end - 1]) {
return searchHelper(nums, mid, end, target);
} else {
return searchHelper(nums, start, mid, target);
}
}
}
public:
int search(vector<int>& nums, int target) {
if (nums.size() <= 0) return -1;
else return searchHelper(nums, 0, nums.size(), target);
}
};
| 26.440476 | 79 | 0.538046 | [
"vector"
] |
a0ee433b271f058cee044edac537fe243d45d502 | 3,455 | cpp | C++ | src/Kernel/src/Color.cpp | till213/SkyDolly | 75caa54fa9fcbaae04b6605c3c1a68e0cb9a0c16 | [
"MIT"
] | 21 | 2021-03-01T00:19:41.000Z | 2022-02-22T02:57:19.000Z | src/Kernel/src/Color.cpp | till213/SkyDolly | 75caa54fa9fcbaae04b6605c3c1a68e0cb9a0c16 | [
"MIT"
] | 11 | 2021-06-20T20:16:56.000Z | 2022-03-28T19:03:34.000Z | src/Kernel/src/Color.cpp | till213/SkyDolly | 75caa54fa9fcbaae04b6605c3c1a68e0cb9a0c16 | [
"MIT"
] | 3 | 2021-04-06T19:06:16.000Z | 2022-01-20T21:22:39.000Z | /**
* Sky Dolly - The Black Sheep for your Flight Recordings
*
* Copyright (c) Oliver Knoll
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this
* software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge,
* publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
* to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#include <vector>
#include <QColor>
#include "Color.h"
// PUBLIC
std::vector<QRgb> Color::createColorRamp(QColor startColor, QColor endColor, int nofTotalColors) noexcept
{
return createColorRamp(startColor.rgba(), endColor.rgba(), nofTotalColors);
}
std::vector<QRgb> Color::createColorRamp(QRgb startColor, QRgb endColor, int nofTotalColors) noexcept
{
std::vector<QRgb> colorRamp;
if (nofTotalColors > 2) {
const double startAlpha = qAlpha(startColor);
const double startRed = qRed(startColor);
const double startGreen = qGreen(startColor);
const double startBlue = qBlue(startColor);
const double endAlpha = qAlpha(endColor);
const double endRed = qRed(endColor);
const double endGreen = qGreen(endColor);
const double endBlue = qBlue(endColor);
// Distance values may be negative
const double nofIntervals = nofTotalColors - 1;
const double deltaAlpha = (endAlpha - startAlpha) / static_cast<double>(nofIntervals);
const double deltaRed = (endRed - startRed) / static_cast<double>(nofIntervals);
const double deltaGreen = (endGreen - startGreen) / static_cast<double>(nofIntervals);
const double deltaBlue = (endBlue - startBlue) / static_cast<double>(nofIntervals);
// First color
colorRamp.push_back(startColor);
// Color ramp
for (int i = 1; i < nofTotalColors - 1; ++i) {
const double newAlpha = startAlpha + static_cast<double>(i) * deltaAlpha;
const double newRed = startRed + static_cast<double>(i) * deltaRed;
const double newGreen = startGreen + static_cast<double>(i) * deltaGreen;
const double newBlue = startBlue + static_cast<double>(i) * deltaBlue;
const QRgb newRgb = qRound(newAlpha) << 24 | qRound(newRed) << 16 | qRound(newGreen) << 8 | qRound(newBlue);
colorRamp.push_back(newRgb);
}
// Last color
colorRamp.push_back(endColor);
} else if (nofTotalColors == 2) {
colorRamp.push_back(startColor);
colorRamp.push_back(endColor);
} else if (nofTotalColors == 1) {
colorRamp.push_back(startColor);
}
return colorRamp;
}
| 40.647059 | 120 | 0.692619 | [
"vector"
] |
a0f57570e2c7f9d4fed4199bed861a706826c755 | 31,361 | cpp | C++ | Audio/Announcer.cpp | IvarJonsson/Project-Unknown | 4675b41bbb5e90135c7bf3aded2c2e262b50f351 | [
"BSL-1.0"
] | null | null | null | Audio/Announcer.cpp | IvarJonsson/Project-Unknown | 4675b41bbb5e90135c7bf3aded2c2e262b50f351 | [
"BSL-1.0"
] | null | null | null | Audio/Announcer.cpp | IvarJonsson/Project-Unknown | 4675b41bbb5e90135c7bf3aded2c2e262b50f351 | [
"BSL-1.0"
] | null | null | null | // Copyright 2001-2016 Crytek GmbH / Crytek Group. All rights reserved.
/*************************************************************************
-------------------------------------------------------------------------
History:
- 21:07:2009 Created by Tim Furnish
*************************************************************************/
#include "StdAfx.h"
#include "Audio/Announcer.h"
#include "Audio/GameAudio.h"
#include "GameRules.h"
#include <CryString/StringUtils.h>
#include "Utility/DesignerWarning.h"
#include "Player.h"
#include <CrySystem/ILocalizationManager.h>
#include <CrySystem/ISystem.h>
#include "UI/UIManager.h"
#include "UI/HUD/HUDEventWrapper.h"
#include "UI/HUD/HUDUtils.h"
#include <GameXmlParamReader.h>
#include "GameRulesModules/IGameRulesRoundsModule.h"
#include "GameRulesModules/IGameRulesStateModule.h"
#define ANNOUNCER_FILENAME "Scripts/Sounds/cw2_Annoucements.xml"
#define ANNOUNCER_MAX_LOAD_WAIT_TIMEOUT 5.0f
#define CHECK_FOR_THIS_MANY_DUPLICATED_STRINGS_WHEN_READING_ANNOUNCER_XML 128
#define AnnouncerConditionList(f) \
f(kAnnouncerCondition_self) \
f(kAnnouncerCondition_teammate) \
f(kAnnouncerCondition_enemy) \
f(kAnnouncerCondition_any) \
AUTOENUM_BUILDFLAGS_WITHZERO(AnnouncerConditionList, kAnnouncerCondition_none);
static AUTOENUM_BUILDNAMEARRAY(s_conditionNames, AnnouncerConditionList);
CRY_TODO(26, 1, 2010, "kAnnouncerCondition_any isn't really any....");
CAnnouncer* CAnnouncer::s_announcer_instance = NULL;
//------------------------------------------------------------------------
CAnnouncer* CAnnouncer::GetInstance()
{
CRY_ASSERT(s_announcer_instance);
return s_announcer_instance;
}
#ifndef _RELEASE
//------------------------------------------------------------------------
struct SAnnouncerAutoComplete : public IConsoleArgumentAutoComplete
{
virtual int GetCount() const { return CAnnouncer::GetInstance()->GetCount(); };
virtual const char* GetValue( int nIndex ) const { return CAnnouncer::GetInstance()->GetName(nIndex); };
};
static SAnnouncerAutoComplete s_perkNameAutoComplete;
#endif
#ifndef _RELEASE
//------------------------------------------------------------------------
int CAnnouncer::GetCount() const
{
return m_annoucementList.size();
}
#endif
#ifndef _RELEASE
//------------------------------------------------------------------------
const char* CAnnouncer::GetName(int i) const
{
return m_annoucementList[i].m_pName;
}
#endif
#ifndef _RELEASE
//------------------------------------------------------------------------
const char* CAnnouncer::GetAudio(int i) const
{
return m_annoucementList[i].m_audio;
}
#endif
//------------------------------------------------------------------------
CAnnouncer::CAnnouncer(const EGameMode gamemode)
{
CRY_ASSERT(!s_announcer_instance);
s_announcer_instance = this;
#ifndef _RELEASE
IConsole * console = gEnv->pConsole;
if (console)
{
REGISTER_COMMAND("announce", CAnnouncer::CmdAnnounce, VF_NULL, "Trigger a local announcement");
REGISTER_COMMAND("announcerDump", CAnnouncer::CmdDump, VF_NULL, "Dump loaded announcements to console");
REGISTER_COMMAND("announcerDumpPlayed", CAnnouncer::CmdDumpPlayed, VF_NULL, "Dump loaded announcements that have played to console");
REGISTER_COMMAND("announcerDumpUnPlayed", CAnnouncer::CmdDumpUnPlayed, VF_NULL, "Dump loaded announcements that haven't played to console");
REGISTER_COMMAND("announcerClearPlayCount", CAnnouncer::CmdClearPlayCount, VF_NULL, "Clear the playcounts of all announcements");
REGISTER_COMMAND("announcerCheck", CAnnouncer::CmdCheckAnnouncements, VF_NULL, "Check all announcements in gamemode");
console->RegisterAutoComplete("announce", & s_perkNameAutoComplete);
}
#endif
m_lastPlayedTime = 0.0f;
m_canPlayFromTime = 0.0f;
m_repeatTime = 0.0f;
LoadAnnouncements(gamemode);
//m_soundsBeingListenedTo.reserve(10);
//m_mostRecentSoundId = INVALID_SOUNDID;
m_messageSignalID = g_pGame->GetGameAudio()->GetSignalID("Notify_announcer");
}
//------------------------------------------------------------------------
CAnnouncer::~CAnnouncer()
{
#ifndef _RELEASE
IConsole * console = gEnv->pConsole;
if (console)
{
console->RemoveCommand("announce");
console->RemoveCommand("announcerDump");
console->RemoveCommand("announcerDumpPlayed");
console->RemoveCommand("announcerDumpUnPlayed");
console->RemoveCommand("announcerClearPlayCount");
console->RemoveCommand("announcerCheck");
console->UnRegisterAutoComplete("announce");
}
#endif
CRY_ASSERT(s_announcer_instance == this);
s_announcer_instance = NULL;
/*ISoundSystem *pSoundSystem = gEnv->pSoundSystem;
for (TSoundIDList::const_iterator it=m_soundsBeingListenedTo.begin(); it!=m_soundsBeingListenedTo.end(); ++it)
{
tSoundID soundID = *it;
_smart_ptr<ISound> pSound = pSoundSystem->GetSound(soundID);
if (pSound)
{
CryLog("[ANNOUNCER] Found a dangling sound being listened to %x; removing. This used to cause crashes", soundID);
pSound->RemoveEventListener((ISoundEventListener*) this);
}
else
{
CRY_ASSERT_MESSAGE(0, string().Format("~CAnnouncer() has found a soundID we were listening to %x; which has failed to resolve into a valid ISound*", soundID).c_str());
CryLog("[ANNOUNCER] Found a dangling soundID being listened to %x but failed to resolve it. Doing nothing", soundID);
}
}*/
}
//------------------------------------------------------------------------
void CAnnouncer::LoadAnnouncements(const EGameMode gamemode)
{
const char* currentLanguage = gEnv->pSystem->GetLocalizationManager()->GetLanguage();
const char* currentGamemodeName = GetGamemodeName(gamemode);
m_annoucementList.clear();
m_singleAllocTextBlock.Reset();
const char* filename = ANNOUNCER_FILENAME;
CryComment("[ANNOUNCER] LoadAnnouncements('%s')", filename);
XmlNodeRef xmlNode = GetISystem()->LoadXmlFromFile( filename );
DesignerWarning (xmlNode, "Announcement definitions file '%s' could not be read!", filename);
if( xmlNode == NULL )
{
//This can legitimately fail to load at runtime, so return cleanly
return;
}
CGameXmlParamReader xmlReader(xmlNode);
const int childCount = xmlReader.GetUnfilteredChildCount();
CSingleAllocTextBlock::SReuseDuplicatedStrings duplicatedStringsWorkspace[CHECK_FOR_THIS_MANY_DUPLICATED_STRINGS_WHEN_READING_ANNOUNCER_XML];
m_singleAllocTextBlock.SetDuplicatedStringWorkspace(duplicatedStringsWorkspace, CHECK_FOR_THIS_MANY_DUPLICATED_STRINGS_WHEN_READING_ANNOUNCER_XML);
// Calculate how much memory we'll need to store all the strings...
for (int iChild = 0; iChild < childCount; ++iChild)
{
const XmlNodeRef childXML = xmlReader.GetFilteredChildAt(iChild);
IF_UNLIKELY( childXML == NULL )
{
continue;
}
const char * tagType = childXML->getTag();
const char * name = childXML->getAttr("Name");
bool isAnnouncement = (stricmp("Announcement", tagType) == 0);
DesignerWarning(isAnnouncement, "While reading '%s' found a '%s' tag when only expected to find 'Announcement' tags", filename, tagType);
DesignerWarning(name, "While reading '%s' found a '%s' tag with no name!", filename, tagType);
if (name && isAnnouncement)
{
CGameXmlParamReader childReader(childXML);
const int subChildCount = childReader.GetUnfilteredChildCount();
m_singleAllocTextBlock.IncreaseSizeNeeded(name);
for (int iSubChild = 0; iSubChild < subChildCount; ++iSubChild)
{
const XmlNodeRef optionXML = childReader.GetFilteredChildAt(iSubChild);
IF_UNLIKELY( optionXML == NULL)
{
continue;
}
if(0 == stricmp(optionXML->getTag(), "Gamemode"))
{
if(ShouldLoadNode(optionXML, currentGamemodeName, currentLanguage))
{
CGameXmlParamReader optionReader(optionXML);
const int gamemodeChildCount = optionReader.GetUnfilteredChildCount();
for (int iGamemodeChild = 0; iGamemodeChild < gamemodeChildCount; ++iGamemodeChild)
{
const XmlNodeRef gamemodeOptionXML = optionReader.GetFilteredChildAt(iGamemodeChild);
if (gamemodeOptionXML)
{
const char * gamemodeOptionName = gamemodeOptionXML->getTag();
if (0 == stricmp(gamemodeOptionName, "SoundOption"))
{
m_singleAllocTextBlock.IncreaseSizeNeeded(gamemodeOptionXML->getAttr("sound"));
}
}
}
}
}
else if (0 == stricmp(optionXML->getTag(), "SoundOption"))
{
m_singleAllocTextBlock.IncreaseSizeNeeded(optionXML->getAttr("sound"));
}
}
}
}
// Allocate memory for strings...
m_singleAllocTextBlock.Allocate();
// Now use allocated memory to store strings...
for (int iChild = 0; iChild < childCount; ++iChild)
{
const XmlNodeRef childXML = xmlReader.GetFilteredChildAt(iChild);
IF_UNLIKELY( childXML == NULL )
{
continue;
}
const char * tagType = childXML->getTag();
const char * name = childXML->getAttr("Name");
bool isAnnouncement = (stricmp("Announcement", tagType) == 0);
if (isAnnouncement && name)
{
const char * storedName = m_singleAllocTextBlock.StoreText(name);
const char * conStr = childXML->getAttr("condition");
EAnnounceConditions conditions = (conStr && conStr[0]) ? AutoEnum_GetBitfieldFromString(conStr, s_conditionNames, AnnouncerConditionList_numBits) : kAnnouncerCondition_any;
float noRepeatTime = 0.0f;
childXML->getAttr("norepeat", noRepeatTime);
SOnScreenMessageDef onScreenMessage;
CGameXmlParamReader childReader(childXML);
const int subChildCount = childReader.GetUnfilteredChildCount();
DesignerWarning(childCount > 0, "While reading '%s' found an announcement (name='%s' condition='%s') with no child tags!", filename, name, conStr);
int numAnnouncementsAdded = 0;
for (int iSubChild = 0; iSubChild < subChildCount; ++iSubChild)
{
const XmlNodeRef optionXML = childReader.GetFilteredChildAt(iSubChild);
IF_UNLIKELY( optionXML == NULL )
{
continue;
}
const char * optionName = optionXML->getTag();
if (0 == stricmp(optionName, "Gamemode"))
{
if(ShouldLoadNode(optionXML, currentGamemodeName, currentLanguage))
{
CGameXmlParamReader optionReader(optionXML);
const int gamemodeChildCount = optionReader.GetUnfilteredChildCount();
for (int iGamemodeChild = 0; iGamemodeChild < gamemodeChildCount; ++iGamemodeChild)
{
const XmlNodeRef gamemodeOptionXML = optionReader.GetFilteredChildAt(iGamemodeChild);
if (gamemodeOptionXML != NULL)
{
const char * gamemodeOptionName = gamemodeOptionXML->getTag();
bool loaded = LoadAnnouncementOption(gamemodeOptionName, gamemodeOptionXML, conditions, storedName, onScreenMessage, noRepeatTime, numAnnouncementsAdded);
DesignerWarning(loaded, "While reading '%s' found an unexpected tag '%s' inside an announcement (name='%s' condition='%s')", filename, optionName, name, conStr);
}
}
}
}
else
{
bool loaded = LoadAnnouncementOption(optionName, optionXML, conditions, storedName, onScreenMessage, noRepeatTime, numAnnouncementsAdded);
DesignerWarning(loaded, "While reading '%s' found an unexpected tag '%s' inside an announcement (name='%s' condition='%s')", filename, optionName, name, conStr);
}
}
if (numAnnouncementsAdded == 0 && !onScreenMessage.empty())
{
const char * sound = NULL;
AddAnnouncement(storedName, conditions, sound, onScreenMessage, 0.0f);
}
}
}
m_singleAllocTextBlock.Lock();
}
//------------------------------------------------------------------------
const char* CAnnouncer::GetGamemodeName(EGameMode mode)
{
switch (mode)
{
case eGM_AllOrNothing:
return "AON";
case eGM_Assault:
return "AS";
case eGM_BombTheBase:
return "BTB";
case eGM_CaptureTheFlag:
return "CTF";
case eGM_CrashSite:
return "CS";
case eGM_Extraction:
return "EXT";
case eGM_InstantAction:
return "IA";
case eGM_PowerStruggle:
return "PS";
case eGM_TeamInstantAction:
return "TIA";
case eGM_Gladiator:
return "GL";
default:
CRY_ASSERT_TRACE(false, ("Annoucner doesn't know what gamemode attribute to check for (%d needs adding to switch statement)", mode));
return "";
}
}
//------------------------------------------------------------------------
bool CAnnouncer::ShouldLoadNode(const XmlNodeRef gamemodeXML, const char* currentGamemodeName, const char* currentLanguage)
{
CRY_ASSERT(0 == stricmp(gamemodeXML->getTag(), "Gamemode"));
int shouldLoadSpecficLang = 0;
if(!gamemodeXML->getAttr(currentLanguage, shouldLoadSpecficLang))
{
if (!gamemodeXML->getAttr("languagedefault", shouldLoadSpecficLang))
{
shouldLoadSpecficLang = 1;
}
}
if(shouldLoadSpecficLang)
{
int shouldLoad = 0;
if(gamemodeXML->getAttr(currentGamemodeName, shouldLoad))
{
return (shouldLoad == 1);
}
if(gamemodeXML->getAttr("default", shouldLoad))
{
return (shouldLoad == 1);
}
}
return false;
}
//------------------------------------------------------------------------
bool CAnnouncer::LoadAnnouncementOption(const char* optionName, const XmlNodeRef optionXML, const EAnnounceConditions conditions, const char * storedName, SOnScreenMessageDef &onScreenMessage, const float noRepeat, int &numAnnouncementsAdded)
{
if (0 == stricmp(optionName, "DisplayMessage"))
{
onScreenMessage.Read(optionXML);
}
else if (0 == stricmp(optionName, "SoundOption"))
{
const char * sound = m_singleAllocTextBlock.StoreText(optionXML->getAttr("sound"));
AddAnnouncement(storedName, conditions, sound, onScreenMessage, noRepeat);
numAnnouncementsAdded++;
}
else
{
return false;
}
return true;
}
//------------------------------------------------------------------------
void CAnnouncer::AddAnnouncement(const char * pName, const EAnnounceConditions condition, const char * audio, const SOnScreenMessageDef & onScreenMessage, const float noRepeat)
{
SAnnouncementDef newAnnoucement;
newAnnoucement.m_announcementID = CAnnouncer::NameToID(pName);
newAnnoucement.m_pName = pName;
newAnnoucement.m_conditions = condition;
newAnnoucement.m_audio = audio;
//newAnnoucement.m_audioFlags = (audio && !strstr(audio, ":")) ? FLAG_SOUND_VOICE : FLAG_SOUND_EVENT;
newAnnoucement.m_onScreenMessage = onScreenMessage;
newAnnoucement.m_noRepeat = noRepeat;
m_annoucementList.push_back(newAnnoucement);
}
//------------------------------------------------------------------------
const SAnnouncementDef * CAnnouncer::FindAnnouncementWithConditions(const int announcementCRC, EAnnounceConditions conditions) const
{
const int annoucementSize = m_annoucementList.size();
std::vector<const SAnnouncementDef*> results;
for(int i = 0; i < annoucementSize; i++)
{
if(m_annoucementList[i].m_announcementID == announcementCRC)
{
if(m_annoucementList[i].m_conditions & conditions)
{
results.push_back(&m_annoucementList[i]);
}
}
}
if(!results.empty())
{
return results[cry_random((size_t)0, results.size() - 1)];
}
return NULL;
}
//------------------------------------------------------------------------
void CAnnouncer::Announce(const char* announcement, EAnnounceContext context)
{
AnnounceInternal(0, 0, announcement, kAnnouncerCondition_any, false, context);
}
//------------------------------------------------------------------------
void CAnnouncer::Announce(const EntityId entityID, EAnnouncementID announcementID, EAnnounceContext context)
{
EAnnounceConditions conditions = GetConditionsFromEntityId(entityID);
AnnounceInternal(entityID, 0, announcementID, conditions, false, context);
}
//------------------------------------------------------------------------
void CAnnouncer::Announce(const EntityId entityID, const char* announcement, EAnnounceContext context)
{
EAnnounceConditions conditions = GetConditionsFromEntityId(entityID);
AnnounceInternal(entityID, 0, announcement, conditions, false, context);
}
//------------------------------------------------------------------------
void CAnnouncer::AnnounceFromTeamId(const int teamId, EAnnouncementID announcementID, EAnnounceContext context)
{
EAnnounceConditions conditions = GetConditionsFromTeamId(teamId);
AnnounceInternal(0, 0, announcementID, conditions, false, context);
}
//------------------------------------------------------------------------
void CAnnouncer::AnnounceFromTeamId(const int teamId, const char* announcement, EAnnounceContext context)
{
EAnnounceConditions conditions = GetConditionsFromTeamId(teamId);
AnnounceInternal(0, 0, announcement, conditions, false, context);
}
//------------------------------------------------------------------------
void CAnnouncer::AnnounceAsTeam(const int teamId, EAnnouncementID announcementID, EAnnounceContext context)
{
AnnounceInternal(0, teamId, announcementID, kAnnouncerCondition_any, false, context);
}
//------------------------------------------------------------------------
void CAnnouncer::AnnounceAsTeam(const int teamId, const char* announcement, EAnnounceContext context)
{
AnnounceInternal(0, teamId, announcement, kAnnouncerCondition_any, false, context);
}
//------------------------------------------------------------------------
void CAnnouncer::ForceAnnounce(const char* announcement, EAnnounceContext context)
{
AnnounceInternal(0, 0, announcement, kAnnouncerCondition_any, true, context);
}
//------------------------------------------------------------------------
void CAnnouncer::ForceAnnounce(const EAnnouncementID announcementID, EAnnounceContext context)
{
AnnounceInternal(0, 0, announcementID, kAnnouncerCondition_any, true, context);
}
//------------------------------------------------------------------------
EAnnounceConditions CAnnouncer::GetConditionsFromTeamId(const int teamId) const
{
EAnnounceConditions conditions = kAnnouncerCondition_any;
CGameRules *pGameRules=g_pGame->GetGameRules();
CRY_ASSERT(pGameRules);
EntityId localActorEntityID = gEnv->pGameFramework->GetClientActorId();
int localTeam = pGameRules->GetTeam(localActorEntityID);
if (localTeam == 0 || localTeam != teamId)
{
conditions |= kAnnouncerCondition_enemy;
}
else
{
conditions |= kAnnouncerCondition_teammate;
}
return conditions;
}
//------------------------------------------------------------------------
EAnnounceConditions CAnnouncer::GetConditionsFromEntityId(const EntityId entityId) const
{
EAnnounceConditions conditions = kAnnouncerCondition_any;
CGameRules *pGameRules=g_pGame->GetGameRules();
CRY_ASSERT(pGameRules);
EntityId localActorEntityID = gEnv->pGameFramework->GetClientActorId();
if (localActorEntityID == entityId)
{
conditions |= kAnnouncerCondition_self;
}
else
{
int localTeam = pGameRules->GetTeam(localActorEntityID);
int entityTeam = pGameRules->GetTeam(entityId);
if (localTeam == 0 || localTeam != entityTeam)
{
conditions |= kAnnouncerCondition_enemy;
}
else
{
conditions |= kAnnouncerCondition_teammate;
}
}
return conditions;
}
//------------------------------------------------------------------------
bool CAnnouncer::AnnounceInternal(EntityId entityID, const int overrideTeamId, const char* announcement, const EAnnounceConditions conditions, const bool force, EAnnounceContext context)
{
EAnnouncementID announcementID = CAnnouncer::NameToID(announcement);
return AnnounceInternal(entityID, overrideTeamId, announcementID, conditions, force, context);
}
//------------------------------------------------------------------------
bool CAnnouncer::AnnounceInternal(EntityId entityID, const int overrideTeamId, const EAnnouncementID announcementID, const EAnnounceConditions conditions, const bool force, EAnnounceContext context)
{
bool doAudio = true;
bool okToAnnounce = false;
CGameRules *pGameRules = g_pGame->GetGameRules();
IGameRulesStateModule *pStateModule = pGameRules ? pGameRules->GetStateModule() : NULL;
if (pStateModule)
{
IGameRulesStateModule::EGR_GameState gameState = pStateModule->GetGameState();
switch(context)
{
case eAC_inGame:
if (gameState == IGameRulesStateModule::EGRS_InGame)
okToAnnounce = true;
break;
case eAC_postGame:
if (gameState == IGameRulesStateModule::EGRS_PostGame)
okToAnnounce = true;
break;
case eAC_always:
okToAnnounce=true;
break;
default:
CRY_ASSERT_MESSAGE(0, string().Format("AnnounceInternal() unhandled context=%d", context));
break;
}
if (!okToAnnounce)
{
#ifndef _RELEASE
const SAnnouncementDef * pAnnouncement = FindAnnouncementWithConditions(announcementID, conditions);
CryLog("[ANNOUNCER] CAnnouncer::AnnounceInternal() rejecting announcement=%d (%s); as our gamestate %d isn't valid for our context=%d", announcementID, pAnnouncement ? pAnnouncement->m_pName : "<ANNOUNCEMENT INVALID>", gameState, context);
#endif
return false;
}
}
else
{
CryLog("[ANNOUNCER] CAnnouncer::AnnounceInternal() has no stateModule to validate against");
}
const float currentTime = gEnv->pTimer->GetCurrTime();
if (!force && (m_canPlayFromTime > currentTime))
{
CryLog("[ANNOUNCER] CanPlay %.2f - currentTime %.2f", m_canPlayFromTime, currentTime);
doAudio = false;
}
const SAnnouncementDef * doAnnouncement = FindAnnouncementWithConditions(announcementID, conditions);
if (doAnnouncement)
{
bool allow = force || (AllowNoRepeat(doAnnouncement->m_noRepeat, currentTime) && AllowAnnouncement());
if (doAudio && doAnnouncement->m_audio && allow)
{
string audioFilename(doAnnouncement->m_audio);
ConvertToFinalSoundName(overrideTeamId, audioFilename);
/*_smart_ptr<ISound> const pSound = gEnv->pSoundSystem->CreateSound(audioFilename.c_str(), doAnnouncement->m_audioFlags);
if (pSound)
{
if (force && (m_mostRecentSoundId != INVALID_SOUNDID))
{
if (_smart_ptr<ISound> const pRecent=gEnv->pSoundSystem->GetSound(m_mostRecentSoundId))
{
if (pRecent->IsPlaying())
{
CryLog("[ANNOUNCER] attempting to FORCE play sound '%s' by stopping most recent sound '%s'", audioFilename.c_str(), pRecent->GetName());
pRecent->Stop();
}
}
}
pSound->SetSemantic(doAnnouncement->m_audioFlags & FLAG_SOUND_VOICE ? eSoundSemantic_OnlyVoice : eSoundSemantic_SoundSpot);
pSound->Play();
#ifndef _RELEASE
{
SAnnouncementDef *pNonConstAnnouncement = const_cast<SAnnouncementDef*>(doAnnouncement);
++pNonConstAnnouncement->m_playCount;
}
#endif
m_lastPlayedTime = gEnv->pTimer->GetCurrTime();
m_canPlayFromTime = m_lastPlayedTime + ANNOUNCER_MAX_LOAD_WAIT_TIMEOUT;
pSound->AddEventListener((ISoundEventListener*) this, "CAnnouncer");
const tSoundID sid = pSound->GetId();
m_soundsBeingListenedTo.push_back(sid);
m_mostRecentSoundId = sid;
}
else
{
CryLog("[ANNOUNCER] Unable to create sound '%s' - probably invalid sound in XML file or s_soundEnable is set to 0", audioFilename.c_str());
m_mostRecentSoundId = INVALID_SOUNDID;
}*/
}
if (!doAnnouncement->m_onScreenMessage.empty() && g_pGame->GetIGameFramework()->GetClientActor())
{
IEntity *pEntity = gEnv->pEntitySystem->GetEntity(entityID);
SHUDEventWrapper::GameStateNotify( doAnnouncement->m_onScreenMessage.GetDisplayText(), m_messageSignalID, pEntity ? pEntity->GetName() : "??" );
}
}
return doAnnouncement != NULL;
}
//------------------------------------------------------------------------
bool CAnnouncer::AllowAnnouncement() const
{
bool allow = true;
CGameRules* pGameRules = g_pGame->GetGameRules();
if(pGameRules)
{
IGameRulesRoundsModule* pRoundsModule=pGameRules->GetRoundsModule();
if (pRoundsModule)
{
allow = allow && pRoundsModule->IsInProgress();
}
}
allow = allow && !g_pGame->GetUI()->IsLoading();
return allow;
}
//------------------------------------------------------------------------
bool CAnnouncer::AllowNoRepeat(const float noRepeat, const float currentTime)
{
if(noRepeat > 0.0f)
{
if(m_repeatTime > currentTime)
{
CryLog("[ANNOUNCER] Repeat Time %.2f < currentTime %.2f", m_repeatTime, currentTime);
return false;
}
m_repeatTime = currentTime + noRepeat; //allowed to play - but keep a record of time
}
return true;
}
//static------------------------------------------------------------------------
EAnnouncementID CAnnouncer::NameToID(const char* announcement)
{
CryStackStringT<char, 32> lower(announcement);
lower.MakeLower();
return CCrc32::Compute(lower.c_str());
}
#ifndef _RELEASE
//------------------------------------------------------------------------
void CAnnouncer::CmdAnnounce(IConsoleCmdArgs* pCmdArgs)
{
// First argument is command itself
if (pCmdArgs->GetArgCount() > 1)
{
const char * arg = pCmdArgs->GetArg(1);
EAnnounceConditions conditions = (pCmdArgs->GetArgCount() > 2) ? atoi(pCmdArgs->GetArg(2)) : kAnnouncerCondition_self|kAnnouncerCondition_teammate|kAnnouncerCondition_enemy|kAnnouncerCondition_any;
int annoucements = (pCmdArgs->GetArgCount() > 3) ? atoi(pCmdArgs->GetArg(3)) : 1;
for(int i = 0; i < annoucements; i++)
{
bool done = GetInstance()->AnnounceInternal(0, 0, arg, conditions, true, eAC_always);
if (! done)
{
CryLog ("[ANNOUNCER] Failed to find an appropriate announcement (%s %u)", arg, conditions);
}
}
}
else
{
CryLog ("[ANNOUNCER] Wrong number of arguments to console command");
}
}
#endif
#ifndef _RELEASE
//------------------------------------------------------------------------
void CAnnouncer::CmdDump(IConsoleCmdArgs* pCmdArgs)
{
const CAnnouncer* pAnnouncer = GetInstance();
const int count = pAnnouncer->GetCount();
CryLog("----------------------------------------------------------------------");
CryLog("Dump all");
CryLog("----------------------------------------------------------------------");
for(int i = 0; i < count; i++)
{
CryLogAlways("Announcer: %s - %s (playCount=%d)", pAnnouncer->GetName(i), pAnnouncer->GetAudio(i), pAnnouncer->m_annoucementList[i].m_playCount);
}
CryLog("----------------------------------------------------------------------");
CryLog("Total: %d", count);
CryLog("----------------------------------------------------------------------");
}
#endif
#ifndef _RELEASE
//------------------------------------------------------------------------
void CAnnouncer::CmdDumpPlayed(IConsoleCmdArgs *pCmdArgs)
{
const CAnnouncer* pAnnouncer = GetInstance();
const int count = pAnnouncer->GetCount();
CryLog("----------------------------------------------------------------------");
CryLog("Dump Played");
CryLog("----------------------------------------------------------------------");
int numDumped=0;
for(int i = 0; i < count; i++)
{
if (pAnnouncer->m_annoucementList[i].m_playCount > 0)
{
CryLogAlways("Announcer: %s - %s (playCount=%d)", pAnnouncer->GetName(i), pAnnouncer->GetAudio(i), pAnnouncer->m_annoucementList[i].m_playCount);
numDumped++;
}
}
CryLog("----------------------------------------------------------------------");
CryLog("Total Played: %d", numDumped);
CryLog("----------------------------------------------------------------------");
}
#endif
#ifndef _RELEASE
//------------------------------------------------------------------------
void CAnnouncer::CmdDumpUnPlayed(IConsoleCmdArgs *pCmdArgs)
{
const CAnnouncer* pAnnouncer = GetInstance();
const int count = pAnnouncer->GetCount();
CryLog("----------------------------------------------------------------------");
CryLog("Dump UnPlayed");
CryLog("----------------------------------------------------------------------");
int numDumped=0;
for(int i = 0; i < count; i++)
{
if (pAnnouncer->m_annoucementList[i].m_playCount == 0)
{
CryLogAlways("%s - %s (playCount=%d)", pAnnouncer->GetName(i), pAnnouncer->GetAudio(i), pAnnouncer->m_annoucementList[i].m_playCount);
numDumped++;
}
}
CryLog("----------------------------------------------------------------------");
CryLog("Total UnPlayed: %d", numDumped);
CryLog("----------------------------------------------------------------------");
}
#endif
#ifndef _RELEASE
//------------------------------------------------------------------------
void CAnnouncer::CmdClearPlayCount(IConsoleCmdArgs *pCmdArgs)
{
CAnnouncer* pAnnouncer = GetInstance();
const int count = pAnnouncer->GetCount();
int numCleared=0;
for(int i = 0; i < count; i++)
{
if (pAnnouncer->m_annoucementList[i].m_playCount > 0)
{
numCleared++;
}
pAnnouncer->m_annoucementList[i].m_playCount = 0;
}
CryLog("----------------------------------------------------------------------");
CryLog("Cleared PlayCount on %d announcements", numCleared);
CryLog("----------------------------------------------------------------------");
}
#endif
#ifndef _RELEASE
//------------------------------------------------------------------------
void CAnnouncer::CmdCheckAnnouncements(IConsoleCmdArgs* pCmdArgs)
{
CAnnouncer* pAnnouncer = GetInstance();
const int annoucementSize = pAnnouncer->m_annoucementList.size();
for(int i = 0; i < annoucementSize; i++)
{
for(int j = 1; j <= 2; j++)
{
string audioFilename(pAnnouncer->m_annoucementList[i].m_audio);
pAnnouncer->ConvertToFinalSoundName(j, audioFilename);
/*ISound* pSound = gEnv->pSoundSystem->CreateSound(audioFilename, pAnnouncer->m_annoucementList[i].m_audioFlags);
if(!pSound)
{
CryLogAlways("[ANNOUNCER] Unable to create sound '%s'", audioFilename.c_str());
}*/
}
}
}
#endif
//------------------------------------------------------------------------
//void CAnnouncer::OnSoundEvent( ESoundCallbackEvent event, ISound *pSound )
//{
// if(event == SOUND_EVENT_ON_LOADED)
// {
// const int lengthMs = pSound->GetLengthMs();
// CRY_ASSERT(lengthMs != 0); //This should only be zero when the sound isn't loaded
// const float length = (float) lengthMs/1000.0f;
// m_canPlayFromTime = m_lastPlayedTime + length;
// pSound->RemoveEventListener((ISoundEventListener*) this);
// if (!stl::find_and_erase(m_soundsBeingListenedTo, pSound->GetId()))
// {
// CRY_ASSERT_MESSAGE(0, "CAnnouncer::OnSoundEvent() failed to find a sound in our own listeners vector. This should not happen");
// }
// }
// else if(event == SOUND_EVENT_ON_LOAD_FAILED)
// {
// m_canPlayFromTime = m_lastPlayedTime;
// pSound->RemoveEventListener((ISoundEventListener*) this);
// if (!stl::find_and_erase(m_soundsBeingListenedTo, pSound->GetId()))
// {
// CRY_ASSERT_MESSAGE(0, "CAnnouncer::OnSoundEvent() failed to find a sound in our own listeners vector. This should not happen");
// }
// }
//}
//------------------------------------------------------------------------
void CAnnouncer::ConvertToFinalSoundName(const int overrideTeamId, string& filename)
{
if(filename.find("[team]"))
{
const int teamIndex = GetTeam(overrideTeamId);
string temp = filename.replace("[team]", "%d");
filename.Format(temp.c_str(), teamIndex);
}
}
//------------------------------------------------------------------------
const int CAnnouncer::GetTeam(const int overrideTeamId)
{
int teamIndex = 1;
if(overrideTeamId != 0)
{
teamIndex = overrideTeamId;
}
else
{
//get team of local client
CGameRules* pGameRules = g_pGame->GetGameRules();
CRY_ASSERT(pGameRules);
EntityId localActorEntityID = gEnv->pGameFramework->GetClientActorId();
teamIndex = pGameRules->GetTeam(localActorEntityID);
}
teamIndex = CLAMP(teamIndex, 1, 2);
return teamIndex;
}
| 33.469584 | 242 | 0.643411 | [
"vector"
] |
9d028466350aadfcb550086d0aa3cf887822f104 | 10,785 | cpp | C++ | test/aes-brute-force.cpp | GiantDarth/aes256-brute-force | 8e2385f41d569b78f2cbe290262207a9d412d6dd | [
"Apache-2.0"
] | null | null | null | test/aes-brute-force.cpp | GiantDarth/aes256-brute-force | 8e2385f41d569b78f2cbe290262207a9d412d6dd | [
"Apache-2.0"
] | null | null | null | test/aes-brute-force.cpp | GiantDarth/aes256-brute-force | 8e2385f41d569b78f2cbe290262207a9d412d6dd | [
"Apache-2.0"
] | null | null | null | #include "aes_ni.h"
#include <chrono>
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <cstdint>
#include <thread>
#include <string>
#include <vector>
#include <assert.h>
int hexdigit_value(char c){
int nibble = -1;
if(('0'<=c) && (c<='9')) nibble = c-'0';
if(('a'<=c) && (c<='f')) nibble = c-'a' + 10;
if(('A'<=c) && (c<='F')) nibble = c-'A' + 10;
return nibble;
}
int is_hexdigit(char c){
return -1!=hexdigit_value(c);
}
size_t hexstr_to_bytes(uint8_t *dst, size_t dst_size, char *hexstr){
unsigned int len = strlen(hexstr);
if(dst_size>(len/2))
dst_size = (len/2);
memset(dst,0,dst_size);
for(unsigned int i=0;i<dst_size*2;i++){
unsigned int shift = 4 - 4*(i & 1);
unsigned int charIndex = i;//len-1-i;
char c = hexstr[charIndex];
uint8_t nibble = hexdigit_value(c);
dst[i/2] |= nibble << shift;
}
return dst_size;
}
void bytes_to_hexstr(char *dst,uint8_t *bytes, unsigned int nBytes){
unsigned int i;
for(i=0;i<nBytes;i++){
sprintf(dst+2*i,"%02X",bytes[i]);
}
}
size_t cleanup_hexstr(char *hexstr, size_t hexstr_size, char *str, size_t str_size){
size_t cnt=0;
int lastIs0=0;
for(unsigned int j = 0;j<str_size;j++){
char c = str[j];
if(is_hexdigit(c)){
if(cnt==hexstr_size-1){//need final char for null.
printf("Too many hex digits. hexstr=%s\n",hexstr);
hexstr[cnt]=0;
return -1;
}
hexstr[cnt++]=c;
} else if(lastIs0) {
if('x'==c) cnt--;
if('X'==c) cnt--;
}
lastIs0 = '0'==c;
}
hexstr[cnt]=0;
return cnt;
}
static void print_bytes_sep(const char *msg,const unsigned char *buf, unsigned int size, const char m2[], const char sep[]){
unsigned int i;
printf("%s",msg);
for(i=0;i<size-1;i++) printf("%02X%s",buf[i],sep);
if(i<size) printf("%02X",buf[i]);
printf("%s", m2);
}
static void print_128(const char m[], const uint8_t a[16], const char m2[]){
print_bytes_sep( m,a ,4,"_","");
print_bytes_sep("",a+4 ,4,"_","");
print_bytes_sep("",a+8 ,4,"_","");
print_bytes_sep("",a+12,4,m2 ,"");
}
static void println_128(const char m[], const uint8_t a[16]){print_128(m,a,"\n");}
size_t user_hexstr_to_bytes(uint8_t*out, size_t out_size, char *str, size_t str_size){
size_t hexstr_size = cleanup_hexstr(str,str_size,str,str_size);
size_t conv_size = (hexstr_size/2) < out_size ? hexstr_size/2 : out_size;
return hexstr_to_bytes(out,conv_size,str);
}
typedef struct u128 {
uint8_t bytes[16];
} aes128_key_t;
class aes_brute_force{
public:
static bool done;
static void reset(){
done=false;
}
static bool is_done(){
return done;
}
static void set_done(){
done=true;
}
static unsigned int mask_to_offsets(uint8_t key_mask[16], unsigned int offsets[16]){
unsigned int n_offsets = 0;
unsigned int nbits = 0;
for(unsigned int i=0;i<16;i++){
if(key_mask[i]){//byte granularity
offsets[n_offsets++] = i;
nbits+=8;
}
}
return n_offsets;
}
static void search( unsigned int offsets[16],
unsigned int n_offsets,
uint8_t key[16], //I/O
uint8_t plain[16],
uint8_t cipher[16],
uint64_t &loop_cnt, //output the number of iteration actually done
bool &found //output
){
uint8_t r[16];
unsigned int nbits = n_offsets*8;
uint64_t n_loops = 1;
n_loops = n_loops << nbits;
found=false;
for(loop_cnt=0;loop_cnt<n_loops;loop_cnt++){
uint64_t cnt=loop_cnt;
__m128i key_schedule[11];
for(unsigned int o=0;o<n_offsets;o++){
key[offsets[o]] = (uint8_t)cnt;
cnt = cnt >> 8;
}
aes128_load_key_enc_only(key,key_schedule);
aes128_enc(key_schedule,plain,r);
if(0==memcmp(r,cipher,16)){
found=true;
done=true;
return;
}
}
}
explicit aes_brute_force(uint8_t key_mask[16],uint8_t key[16],uint8_t plain[16],uint8_t cipher[16]){
aes128_key_t k;
memcpy(&k ,key ,16);
memcpy(this->plain ,plain ,16);
memcpy(this->cipher ,cipher ,16);
keys.push_back(k);
n_offsets = mask_to_offsets(key_mask, offsets);
nbits = n_offsets*8;
}
void compute() {
loop_cnt=0;
for(auto k=keys.begin();k!=keys.end();++k){
uint64_t cnt;
search(offsets, n_offsets, k->bytes, plain, cipher,cnt,found);
loop_cnt+=cnt;
if(found){
memcpy(correct_key,k->bytes,16);
return;
}
if(is_done()){ //used for multithread operations
return;
}
}
}
void operator()() {
compute();
}
void push(uint8_t key[16]){
aes128_key_t k;
memcpy(&k ,key ,16);
keys.push_back(k);
}
uint64_t loop_cnt;
bool found;
unsigned int offsets[16];
unsigned int n_offsets;
unsigned int nbits;
std::vector<aes128_key_t> keys;
uint8_t correct_key[16];
uint8_t plain[16];
uint8_t cipher[16];
};
bool aes_brute_force::done=false;
int main (int argc, char*argv[]){
uint8_t key_mask[16]={0};
uint8_t key_in[16] ={0};
uint8_t plain[16] ={0};
uint8_t cipher[16] ={0};
const char *key_mask_str = "FF0000FF_00FF0000_0000FF00_00000000";
const char *key_in_str = "007E1500_2800D2A6_ABF70088_09CF4F3C";
// 2B7E1516_28AED2A6_ABF71588_09CF4F3C
const char *plain_str = "3243F6A8_885A308D_313198A2_E0370734";
const char *cipher_str = "3925841D_02DC09FB_DC118597_196A0B32";
char buf[4][1024]={0};
memcpy(buf[0],key_mask_str,strlen(key_mask_str));
memcpy(buf[1],key_in_str ,strlen(key_in_str));
memcpy(buf[2],plain_str ,strlen(plain_str ));
memcpy(buf[3],cipher_str ,strlen(cipher_str));
char *demo_argv[] = {argv[0],buf[0],buf[1],buf[2],buf[3]};
if(0!=aes128_self_test()){
std::cerr << "ERROR: AES-NI self test failed" << std::endl;
exit(-1);
}
bool test_demo = false;
if( (argc<2) || ((argc>1) && (strlen(argv[1])<16)) ){
std::cerr << "AES128 encryption key brute force search" << std::endl;
std::cerr << "Usage: " << argv[0] << " <key_mask> <key_in> <plain> <cipher> [n_threads]" << std::endl;
std::cerr << std::endl;
std::cerr << "launching test/demo..." << std::endl << std::endl;
argc = 5;
argv=demo_argv;
for(int i=0;i<argc;i++){
std::cerr << argv[i] << " ";
}
std::cerr << std::endl << std::endl;
test_demo=true;
}
unsigned int len;
len=user_hexstr_to_bytes(key_mask,16,argv[1],strlen(argv[1])+1);assert(16==len);
len=user_hexstr_to_bytes(key_in ,16,argv[2],strlen(argv[2])+1);assert(16==len);
len=user_hexstr_to_bytes(plain ,16,argv[3],strlen(argv[3])+1);assert(16==len);
len=user_hexstr_to_bytes(cipher ,16,argv[4],strlen(argv[4])+1);assert(16==len);
unsigned int n_threads = std::thread::hardware_concurrency();
if(0==n_threads) n_threads=1;
if(argc>5){
n_threads= std::stoi(argv[5],0,0);
}
std::cout << "INFO: " << n_threads << " concurrent threads supported in hardware." << std::endl << std::endl;
std::cout << "Search parameters:" << std::endl;
std::cout <<"\tn_threads: " << n_threads << std::endl;
println_128("\tkey_mask: ",key_mask);
println_128("\tkey_in: ",key_in);
println_128("\tplain: ",plain);
println_128("\tcipher: ",cipher);
std::cout << std::endl;
unsigned int offsets[16];
unsigned int n_offsets = aes_brute_force::mask_to_offsets(key_mask, offsets);
uint8_t jobs_key_mask[16];
memcpy(jobs_key_mask,key_mask,16);
if(1==n_offsets){
n_threads = 1;
std::cout << "INFO: n_threads set to 1 because n_offsets=1"<< std::endl;
}
if(1!=n_threads) {
jobs_key_mask[offsets[0]] = 0;//fix this key byte at the job level.
}
println_128("\tjobs_key_mask:",jobs_key_mask);
std::vector<std::thread *> threads(n_threads);
std::vector<aes_brute_force *> jobs(n_threads);
aes_brute_force::reset();
int n_keys_per_thread = n_threads==1 ? 0 : (256+n_threads-1) / n_threads;
unsigned int jobs_cnt=0;
for(unsigned int thread_i=0;thread_i<n_threads;thread_i++){
key_in[offsets[0]]=jobs_cnt++;
jobs.at(thread_i) = new aes_brute_force(jobs_key_mask, key_in, plain, cipher);
for(int i=0;i<n_keys_per_thread-1;i++){
key_in[offsets[0]]=jobs_cnt++;
jobs.at(thread_i)->push(key_in);
}
}
std::cout << std::endl << "Launching " << n_offsets*8<< " bits search" << std::endl;
if(test_demo) std::cout << "This can take a couple of minutes on slow computers." << std::endl;
std::chrono::steady_clock::time_point t1 = std::chrono::steady_clock::now();
for(unsigned int thread_i=0;thread_i<n_threads;thread_i++){
threads.at(thread_i)=new std::thread(&aes_brute_force::compute, jobs.at(thread_i));
}
bool found = false;
uint64_t loop_cnt=0;
int winner=-1;
for(unsigned int thread_i=0;thread_i<n_threads;thread_i++){
threads.at(thread_i)->join();
if(jobs.at(thread_i)->found){
found=true;
winner = thread_i;
memcpy(key_in,jobs.at(thread_i)->correct_key,16);
}
loop_cnt+=jobs.at(thread_i)->loop_cnt;
}
std::chrono::steady_clock::time_point t2 = std::chrono::steady_clock::now();
std::cout << std::endl;
if(found){
std::cout << "Thread " << winner << " claims to have found the key" << std::endl;
println_128("\tkey found: ",key_in);
} else {
std::cout << "No matching key could be found" << std::endl;
}
std::cout << std::endl << "Performances:" << std::endl;
std::cout << "\t" << std::dec << loop_cnt << " AES128 operations done in ";
std::chrono::duration<double> time_span = std::chrono::duration_cast<std::chrono::duration<double>>(t2 - t1);
std::cout << time_span.count() << "s" << std::endl;
uint64_t ns = std::chrono::duration_cast<std::chrono::nanoseconds>(t2-t1).count();
unsigned int aes_op_duration_ns = ns / loop_cnt;
std::cout << "\t" << aes_op_duration_ns << "ns per AES128 operation" <<std::endl;
uint64_t key_per_sec = loop_cnt / time_span.count();
if(key_per_sec>1000000){
std::cout << "\t" << std::fixed << std::setprecision(2) << key_per_sec/1000000.0 << " million keys per second" << std::endl;
}else{
std::cout << "\t" << key_per_sec << " keys per second" << std::endl;
}
if(test_demo){
if(found){
const uint8_t expected_key[] = {0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c};
if(memcmp(expected_key,key_in,16)){
std::cout << "ERROR: key found is not the expected one! That worth a debug session!" << std::endl;
return -1;
} else {
std::cout << "INFO: found the expected key, test passed." << std::endl;
}
} else {
std::cout << "ERROR: key could not be found! That worth a debug session!" << std::endl;
return -1;
}
}
return 0;
}
| 31.627566 | 132 | 0.626889 | [
"vector"
] |
9d048dc1e0f8fc569cc24bfe175486875f1ba3a5 | 24,127 | cpp | C++ | src/cgi/map/cgi_Layers.cpp | marek-cel/mscsim-cc0 | 348f659eae61fd998df8bf2fa81090596548d06d | [
"CC0-1.0"
] | 4 | 2020-03-03T08:10:59.000Z | 2021-09-04T08:02:17.000Z | src/cgi/map/cgi_Layers.cpp | marek-cel/mscsim-cc0 | 348f659eae61fd998df8bf2fa81090596548d06d | [
"CC0-1.0"
] | null | null | null | src/cgi/map/cgi_Layers.cpp | marek-cel/mscsim-cc0 | 348f659eae61fd998df8bf2fa81090596548d06d | [
"CC0-1.0"
] | null | null | null | /****************************************************************************//*
* Copyright (C) 2021 Marek M. Cel
*
* Creative Commons Legal Code
*
* CC0 1.0 Universal
*
* CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE
* LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN
* ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS
* INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES
* REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS
* PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM
* THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED
* HEREUNDER.
*
* Statement of Purpose
*
* The laws of most jurisdictions throughout the world automatically confer
* exclusive Copyright and Related Rights (defined below) upon the creator
* and subsequent owner(s) (each and all, an "owner") of an original work of
* authorship and/or a database (each, a "Work").
*
* Certain owners wish to permanently relinquish those rights to a Work for
* the purpose of contributing to a commons of creative, cultural and
* scientific works ("Commons") that the public can reliably and without fear
* of later claims of infringement build upon, modify, incorporate in other
* works, reuse and redistribute as freely as possible in any form whatsoever
* and for any purposes, including without limitation commercial purposes.
* These owners may contribute to the Commons to promote the ideal of a free
* culture and the further production of creative, cultural and scientific
* works, or to gain reputation or greater distribution for their Work in
* part through the use and efforts of others.
*
* For these and/or other purposes and motivations, and without any
* expectation of additional consideration or compensation, the person
* associating CC0 with a Work (the "Affirmer"), to the extent that he or she
* is an owner of Copyright and Related Rights in the Work, voluntarily
* elects to apply CC0 to the Work and publicly distribute the Work under its
* terms, with knowledge of his or her Copyright and Related Rights in the
* Work and the meaning and intended legal effect of CC0 on those rights.
*
* 1. Copyright and Related Rights. A Work made available under CC0 may be
* protected by copyright and related or neighboring rights ("Copyright and
* Related Rights"). Copyright and Related Rights include, but are not
* limited to, the following:
*
* i. the right to reproduce, adapt, distribute, perform, display,
* communicate, and translate a Work;
* ii. moral rights retained by the original author(s) and/or performer(s);
* iii. publicity and privacy rights pertaining to a person's image or
* likeness depicted in a Work;
* iv. rights protecting against unfair competition in regards to a Work,
* subject to the limitations in paragraph 4(a), below;
* v. rights protecting the extraction, dissemination, use and reuse of data
* in a Work;
* vi. database rights (such as those arising under Directive 96/9/EC of the
* European Parliament and of the Council of 11 March 1996 on the legal
* protection of databases, and under any national implementation
* thereof, including any amended or successor version of such
* directive); and
* vii. other similar, equivalent or corresponding rights throughout the
* world based on applicable law or treaty, and any national
* implementations thereof.
*
* 2. Waiver. To the greatest extent permitted by, but not in contravention
* of, applicable law, Affirmer hereby overtly, fully, permanently,
* irrevocably and unconditionally waives, abandons, and surrenders all of
* Affirmer's Copyright and Related Rights and associated claims and causes
* of action, whether now known or unknown (including existing as well as
* future claims and causes of action), in the Work (i) in all territories
* worldwide, (ii) for the maximum duration provided by applicable law or
* treaty (including future time extensions), (iii) in any current or future
* medium and for any number of copies, and (iv) for any purpose whatsoever,
* including without limitation commercial, advertising or promotional
* purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each
* member of the public at large and to the detriment of Affirmer's heirs and
* successors, fully intending that such Waiver shall not be subject to
* revocation, rescission, cancellation, termination, or any other legal or
* equitable action to disrupt the quiet enjoyment of the Work by the public
* as contemplated by Affirmer's express Statement of Purpose.
*
* 3. Public License Fallback. Should any part of the Waiver for any reason
* be judged legally invalid or ineffective under applicable law, then the
* Waiver shall be preserved to the maximum extent permitted taking into
* account Affirmer's express Statement of Purpose. In addition, to the
* extent the Waiver is so judged Affirmer hereby grants to each affected
* person a royalty-free, non transferable, non sublicensable, non exclusive,
* irrevocable and unconditional license to exercise Affirmer's Copyright and
* Related Rights in the Work (i) in all territories worldwide, (ii) for the
* maximum duration provided by applicable law or treaty (including future
* time extensions), (iii) in any current or future medium and for any number
* of copies, and (iv) for any purpose whatsoever, including without
* limitation commercial, advertising or promotional purposes (the
* "License"). The License shall be deemed effective as of the date CC0 was
* applied by Affirmer to the Work. Should any part of the License for any
* reason be judged legally invalid or ineffective under applicable law, such
* partial invalidity or ineffectiveness shall not invalidate the remainder
* of the License, and in such case Affirmer hereby affirms that he or she
* will not (i) exercise any of his or her remaining Copyright and Related
* Rights in the Work or (ii) assert any associated claims and causes of
* action with respect to the Work, in either case contrary to Affirmer's
* express Statement of Purpose.
*
* 4. Limitations and Disclaimers.
*
* a. No trademark or patent rights held by Affirmer are waived, abandoned,
* surrendered, licensed or otherwise affected by this document.
* b. Affirmer offers the Work as-is and makes no representations or
* warranties of any kind concerning the Work, express, implied,
* statutory or otherwise, including without limitation warranties of
* title, merchantability, fitness for a particular purpose, non
* infringement, or the absence of latent or other defects, accuracy, or
* the present or absence of errors, whether or not discoverable, all to
* the greatest extent permissible under applicable law.
* c. Affirmer disclaims responsibility for clearing rights of other persons
* that may apply to the Work or any use thereof, including without
* limitation any person's Copyright and Related Rights in the Work.
* Further, Affirmer disclaims responsibility for obtaining any necessary
* consents, permissions or other rights required for any use of the
* Work.
* d. Affirmer understands and acknowledges that Creative Commons is not a
* party to this document and has no duty or obligation with respect to
* this CC0 or use of the Work.
******************************************************************************/
#include <cgi/map/cgi_Layers.h>
#include <osg/Geode>
#include <osg/Geometry>
#include <osg/LineWidth>
#include <osg/PositionAttitudeTransform>
#include <osg/Material>
#include <cgi/cgi_Geometry.h>
#include <cgi/cgi_GeoTIFF.h>
#include <cgi/cgi_Mercator.h>
#include <cgi/cgi_Models.h>
#include <cgi/cgi_Textures.h>
#include <cgi/map/cgi_Map.h>
#include <fdm/utils/fdm_String.h>
#include <fdm/xml/fdm_XmlDoc.h>
#include <sim/Log.h>
#include <sim/Path.h>
////////////////////////////////////////////////////////////////////////////////
using namespace cgi;
////////////////////////////////////////////////////////////////////////////////
Layers::Layers( const Module *parent ) :
Module( parent )
{
_switchInWaters = new osg::Switch();
_switchCrops = new osg::Switch();
_switchGrassland = new osg::Switch();
_switchWoodland = new osg::Switch();
_switchBuiltup = new osg::Switch();
_switchSatellite = new osg::Switch();
_switchAirports = new osg::Switch();
_switchRailroads = new osg::Switch();
_switchRoads = new osg::Switch();
_switchBorders = new osg::Switch();
_switchCoastline = new osg::Switch();
_oceans = new osg::PositionAttitudeTransform();
_landmass = new osg::PositionAttitudeTransform();
_coastline = new osg::PositionAttitudeTransform();
_crops = new osg::PositionAttitudeTransform();
_grassland = new osg::PositionAttitudeTransform();
_woodland = new osg::PositionAttitudeTransform();
_builtup = new osg::PositionAttitudeTransform();
_water_course = new osg::PositionAttitudeTransform();
_water_inland = new osg::PositionAttitudeTransform();
_satellite = new osg::PositionAttitudeTransform();
_airports = new osg::PositionAttitudeTransform();
_railroads = new osg::PositionAttitudeTransform();
_roads = new osg::PositionAttitudeTransform();
_borders = new osg::PositionAttitudeTransform();
_oceans ->setPosition( osg::Vec3d( 0.0, 0.0, Map::_zOceans ) );
_landmass ->setPosition( osg::Vec3d( 0.0, 0.0, Map::_zLandmass ) );
_crops ->setPosition( osg::Vec3d( 0.0, 0.0, Map::_zCrops ) );
_grassland ->setPosition( osg::Vec3d( 0.0, 0.0, Map::_zGrassland ) );
_woodland ->setPosition( osg::Vec3d( 0.0, 0.0, Map::_zWoodland ) );
_builtup ->setPosition( osg::Vec3d( 0.0, 0.0, Map::_zBuiltup ) );
_water_course ->setPosition( osg::Vec3d( 0.0, 0.0, Map::_zWaterCourse ) );
_water_inland ->setPosition( osg::Vec3d( 0.0, 0.0, Map::_zWaterInland ) );
_satellite ->setPosition( osg::Vec3d( 0.0, 0.0, Map::_zSatellite ) );
_airports ->setPosition( osg::Vec3d( 0.0, 0.0, Map::_zAirports ) );
_railroads ->setPosition( osg::Vec3d( 0.0, 0.0, Map::_zRailroads ) );
_roads ->setPosition( osg::Vec3d( 0.0, 0.0, Map::_zRoads ) );
_borders ->setPosition( osg::Vec3d( 0.0, 0.0, Map::_zBorders ) );
_coastline ->setPosition( osg::Vec3d( 0.0, 0.0, Map::_zCoastline ) );
_switchCrops ->addChild( _crops .get() );
_switchGrassland ->addChild( _grassland .get() );
_switchWoodland ->addChild( _woodland .get() );
_switchBuiltup ->addChild( _builtup .get() );
_switchInWaters ->addChild( _water_course .get() );
_switchInWaters ->addChild( _water_inland .get() );
_switchSatellite ->addChild( _satellite .get() );
_switchAirports ->addChild( _airports .get() );
_switchRailroads ->addChild( _railroads .get() );
_switchRoads ->addChild( _roads .get() );
_switchBorders ->addChild( _borders .get() );
_switchCoastline ->addChild( _coastline .get() );
_root->addChild( _oceans .get() );
_root->addChild( _landmass .get() );
_root->addChild( _switchCrops .get() );
_root->addChild( _switchGrassland .get() );
_root->addChild( _switchWoodland .get() );
_root->addChild( _switchBuiltup .get() );
_root->addChild( _switchInWaters .get() );
_root->addChild( _switchSatellite .get() );
_root->addChild( _switchAirports .get() );
_root->addChild( _switchRailroads .get() );
_root->addChild( _switchRoads .get() );
_root->addChild( _switchBorders .get() );
_root->addChild( _switchCoastline .get() );
initLayer( _oceans .get() , Map::_colorOceans );
initLayer( _landmass .get() , Map::_colorLandmass );
initLayer( _crops .get() , Map::_colorCrops );
initLayer( _grassland .get() , Map::_colorGrassland );
initLayer( _woodland .get() , Map::_colorWoodland );
initLayer( _builtup .get() , Map::_colorBuiltup );
initLayer( _water_course .get() , Map::_colorWaterCourse );
initLayer( _water_inland .get() , Map::_colorWaterInland );
initLayer( _airports .get() , Map::_colorAirports );
initLayer( _railroads .get() , Map::_colorRailroads );
initLayer( _roads .get() , Map::_colorRoads );
initLayer( _borders .get() , Map::_colorBorders );
//initLayer( _coastline .get() , Map::_colorCoastline );
initLayer( _coastline .get() , Map::_colorOceans ); // !!
createOcean();
readLayers();
}
////////////////////////////////////////////////////////////////////////////////
Layers::~Layers() {}
////////////////////////////////////////////////////////////////////////////////
void Layers::setVisibilityCrops( bool visible )
{
if ( visible )
_switchCrops->setAllChildrenOn();
else
_switchCrops->setAllChildrenOff();
}
////////////////////////////////////////////////////////////////////////////////
void Layers::setVisibilityGrassland( bool visible )
{
if ( visible )
_switchGrassland->setAllChildrenOn();
else
_switchGrassland->setAllChildrenOff();
}
////////////////////////////////////////////////////////////////////////////////
void Layers::setVisibilityWoodland( bool visible )
{
if ( visible )
_switchWoodland->setAllChildrenOn();
else
_switchWoodland->setAllChildrenOff();
}
////////////////////////////////////////////////////////////////////////////////
void Layers::setVisibilityBuiltup( bool visible )
{
if ( visible )
_switchBuiltup->setAllChildrenOn();
else
_switchBuiltup->setAllChildrenOff();
}
////////////////////////////////////////////////////////////////////////////////
void Layers::setVisibilityInWaters( bool visible )
{
if ( visible )
_switchInWaters->setAllChildrenOn();
else
_switchInWaters->setAllChildrenOff();
}
////////////////////////////////////////////////////////////////////////////////
void Layers::setVisibilitySatellite( bool visible )
{
if ( visible )
{
_switchSatellite->setAllChildrenOn();
_switchCoastline->setAllChildrenOn();
}
else
{
_switchSatellite->setAllChildrenOff();
_switchCoastline->setAllChildrenOff();
}
}
////////////////////////////////////////////////////////////////////////////////
void Layers::setVisibilityAirports( bool visible )
{
if ( visible )
_switchAirports->setAllChildrenOn();
else
_switchAirports->setAllChildrenOff();
}
////////////////////////////////////////////////////////////////////////////////
void Layers::setVisibilityRailroads( bool visible )
{
if ( visible )
_switchRailroads->setAllChildrenOn();
else
_switchRailroads->setAllChildrenOff();
}
////////////////////////////////////////////////////////////////////////////////
void Layers::setVisibilityRoads( bool visible )
{
if ( visible )
_switchRoads->setAllChildrenOn();
else
_switchRoads->setAllChildrenOff();
}
////////////////////////////////////////////////////////////////////////////////
void Layers::setVisibilityBorders( bool visible )
{
if ( visible )
_switchBorders->setAllChildrenOn();
else
_switchBorders->setAllChildrenOff();
}
////////////////////////////////////////////////////////////////////////////////
void Layers::createOcean()
{
osg::ref_ptr<osg::Geode> geode = new osg::Geode();
_oceans->addChild( geode.get() );
osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry();
geode->addDrawable( geometry.get() );
osg::ref_ptr<osg::Vec3Array> v = new osg::Vec3Array();
v->push_back( osg::Vec3( -Mercator::_max_x, -Mercator::_max_y, 0.0 ) );
v->push_back( osg::Vec3( Mercator::_max_x, -Mercator::_max_y, 0.0 ) );
v->push_back( osg::Vec3( Mercator::_max_x, Mercator::_max_y, 0.0 ) );
v->push_back( osg::Vec3( -Mercator::_max_x, Mercator::_max_y, 0.0 ) );
Geometry::createQuad( geometry.get(), v.get() );
}
////////////////////////////////////////////////////////////////////////////////
void Layers::initLayer( osg::Node* layer, osg::Vec3 color, float width )
{
osg::ref_ptr<osg::Material> material = new osg::Material();
material->setColorMode( osg::Material::AMBIENT_AND_DIFFUSE );
material->setAmbient( osg::Material::FRONT, osg::Vec4( color, 1.0f ) );
material->setDiffuse( osg::Material::FRONT, osg::Vec4( color, 1.0f ) );
layer->getOrCreateStateSet()->setAttribute( material.get(),
osg::StateAttribute::OVERRIDE | osg::StateAttribute::ON );
osg::ref_ptr<osg::LineWidth> lineWidth = new osg::LineWidth();
lineWidth->setWidth( width );
layer->getOrCreateStateSet()->setAttributeAndModes( lineWidth.get(),
osg::StateAttribute::ON );
}
////////////////////////////////////////////////////////////////////////////////
void Layers::readLayers()
{
fdm::XmlDoc doc( Path::get( "map/layers/layers.xml" ).c_str() );
if ( doc.isOpen() )
{
fdm::XmlNode rootNode = doc.getRootNode();
if ( rootNode.isValid() )
{
if ( 0 == fdm::String::icompare( rootNode.getName(), "layers" ) )
{
fdm::XmlNode landmassNode = rootNode.getFirstChildElement( "landmass" );
fdm::XmlNode coastlineNode = rootNode.getFirstChildElement( "coastline" );
fdm::XmlNode cropsNode = rootNode.getFirstChildElement( "crops" );
fdm::XmlNode grasslandNode = rootNode.getFirstChildElement( "grassland" );
fdm::XmlNode woodlandNode = rootNode.getFirstChildElement( "woodland" );
fdm::XmlNode builtupNode = rootNode.getFirstChildElement( "builtup" );
fdm::XmlNode railroadsNode = rootNode.getFirstChildElement( "railroads" );
fdm::XmlNode roadsNode = rootNode.getFirstChildElement( "roads" );
fdm::XmlNode airportsNode = rootNode.getFirstChildElement( "airports" );
fdm::XmlNode waterCourseNode = rootNode.getFirstChildElement( "water_course" );
fdm::XmlNode waterInlandNode = rootNode.getFirstChildElement( "water_inland" );
fdm::XmlNode bordersNode = rootNode.getFirstChildElement( "borders" );
if ( landmassNode .isValid() ) readLayer( landmassNode , _landmass .get() );
if ( coastlineNode .isValid() ) readLayer( coastlineNode , _coastline .get() );
if ( cropsNode .isValid() ) readLayer( cropsNode , _crops .get() );
if ( grasslandNode .isValid() ) readLayer( grasslandNode , _grassland .get() );
if ( woodlandNode .isValid() ) readLayer( woodlandNode , _woodland .get() );
if ( builtupNode .isValid() ) readLayer( builtupNode , _builtup .get() );
if ( railroadsNode .isValid() ) readLayer( railroadsNode , _railroads .get() );
if ( roadsNode .isValid() ) readLayer( roadsNode , _roads .get() );
if ( airportsNode .isValid() ) readLayer( airportsNode , _airports .get() );
if ( waterCourseNode .isValid() ) readLayer( waterCourseNode , _water_course .get() );
if ( waterInlandNode .isValid() ) readLayer( waterInlandNode , _water_inland .get() );
if ( bordersNode .isValid() ) readLayer( bordersNode , _borders .get() );
fdm::XmlNode satelliteNode = rootNode.getFirstChildElement( "satellite" );
if ( satelliteNode.isValid() ) readLayerSatellite( satelliteNode, _satellite.get() );
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
void Layers::readLayer( const fdm::XmlNode &node, osg::Group *parent )
{
fdm::XmlNode fileNode = node.getFirstChildElement( "file" );
while ( fileNode.isValid() )
{
fdm::XmlNode fileTextNode = fileNode.getFirstChild();
if ( fileTextNode.isValid() && fileTextNode.isText() )
{
std::string file = fileTextNode.getText();
osg::ref_ptr<osg::Node> layerNode = Models::get( file.c_str(), true );
if ( layerNode.valid() )
{
parent->addChild( layerNode.get() );
}
}
fileNode = fileNode.getNextSiblingElement( "file" );
}
}
////////////////////////////////////////////////////////////////////////////////
void Layers::readLayerSatellite( const fdm::XmlNode &node, osg::Group *parent )
{
fdm::XmlNode fileNode = node.getFirstChildElement( "file" );
while ( fileNode.isValid() )
{
fdm::XmlNode fileTextNode = fileNode.getFirstChild();
if ( fileTextNode.isValid() && fileTextNode.isText() )
{
readSatelliteImage( parent, fileTextNode.getText().c_str() );
}
fileNode = fileNode.getNextSiblingElement( "file" );
}
}
////////////////////////////////////////////////////////////////////////////////
void Layers::readSatelliteImage( osg::Group *parent, const char *file )
{
// images should be in World Mercator WGS-84 (EPSG:3395) projection
char proj4_merc[] = { "+proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs" };
GeoTIFF geoTiff( Path::get( file ).c_str() );
if ( geoTiff.isOpen() )
{
if ( geoTiff.compareSRS_PROJ4( proj4_merc ) )
{
double x_ul = geoTiff.getMapUpperLeftX();
double y_ul = geoTiff.getMapUpperLeftY();
double w = geoTiff.getMapW();
double h = geoTiff.getMapH();
osg::ref_ptr<osg::PositionAttitudeTransform> pat = new osg::PositionAttitudeTransform();
parent->addChild( pat.get() );
pat->setPosition( osg::Vec3d( x_ul, y_ul, 0.0 ) );
osg::ref_ptr<osg::Geode> geode = new osg::Geode();
pat->addChild( geode.get() );
osg::ref_ptr<osg::Geometry> geometry = new osg::Geometry();
geode->addDrawable( geometry.get() );
osg::ref_ptr<osg::Vec3Array> v = new osg::Vec3Array();
v->push_back( osg::Vec3( 0.0 , h , 0.0 ) );
v->push_back( osg::Vec3( w , h , 0.0 ) );
v->push_back( osg::Vec3( w , 0.0 , 0.0 ) );
v->push_back( osg::Vec3( 0.0 , 0.0 , 0.0 ) );
Geometry::createQuad( geometry.get(), v.get(), true );
osg::ref_ptr<osg::Texture2D> texture = Textures::get( file );
osg::ref_ptr<osg::StateSet> stateSet = geode->getOrCreateStateSet();
if ( texture.valid() )
{
stateSet->setMode( GL_BLEND, osg::StateAttribute::ON );
stateSet->setRenderingHint( osg::StateSet::TRANSPARENT_BIN );
stateSet->setTextureAttributeAndModes( 0, texture, osg::StateAttribute::ON );
}
// material
osg::ref_ptr<osg::Material> material = new osg::Material();
material->setColorMode( osg::Material::AMBIENT_AND_DIFFUSE );
material->setAmbient( osg::Material::FRONT, osg::Vec4( 1.0f, 1.0f, 1.0f, 1.0f ) );
material->setDiffuse( osg::Material::FRONT, osg::Vec4( 1.0f, 1.0f, 1.0f, 1.0f ) );
stateSet->setAttribute( material.get() );
}
else
{
Log::e() << "File: " << file << " projection is not EPSG:3395" << std::endl;
}
}
else
{
Log::e() << "Cannot open dataset: " << file << std::endl;
}
}
| 43.550542 | 102 | 0.607286 | [
"geometry"
] |
9d0818c794b0e62db9129f13b6fcc2ffe7224546 | 13,746 | cc | C++ | src/channel_state.cc | Fusoppark/DRAMsim3 | 9e9d12b10cc2fff0282ce851c873bb21f870048e | [
"MIT"
] | 1 | 2021-04-01T11:47:53.000Z | 2021-04-01T11:47:53.000Z | src/channel_state.cc | Fusoppark/DRAMsim3 | 9e9d12b10cc2fff0282ce851c873bb21f870048e | [
"MIT"
] | null | null | null | src/channel_state.cc | Fusoppark/DRAMsim3 | 9e9d12b10cc2fff0282ce851c873bb21f870048e | [
"MIT"
] | 1 | 2021-09-06T06:09:52.000Z | 2021-09-06T06:09:52.000Z | #include "channel_state.h"
namespace dramsim3 {
ChannelState::ChannelState(const Config& config, const Timing& timing)
: rank_idle_cycles(config.ranks, 0),
config_(config),
timing_(timing),
rank_is_sref_(config.ranks, false),
four_aw_(config_.ranks, std::vector<uint64_t>()),
thirty_two_aw_(config_.ranks, std::vector<uint64_t>()) {
bank_states_.reserve(config_.ranks);
for (auto i = 0; i < config_.ranks; i++) {
auto rank_states = std::vector<std::vector<BankState>>();
rank_states.reserve(config_.bankgroups);
for (auto j = 0; j < config_.bankgroups; j++) {
auto bg_states =
std::vector<BankState>(config_.banks_per_group, BankState());
rank_states.push_back(bg_states);
}
bank_states_.push_back(rank_states);
}
}
bool ChannelState::IsAllBankIdleInRank(int rank) const {
for (int j = 0; j < config_.bankgroups; j++) {
for (int k = 0; k < config_.banks_per_group; k++) {
if (bank_states_[rank][j][k].IsRowOpen()) {
return false;
}
}
}
return true;
}
bool ChannelState::IsRWPendingOnRef(const Command& cmd) const {
int rank = cmd.Rank();
int bankgroup = cmd.Bankgroup();
int bank = cmd.Bank();
return (IsRowOpen(rank, bankgroup, bank) &&
RowHitCount(rank, bankgroup, bank) == 0 &&
bank_states_[rank][bankgroup][bank].OpenRow() == cmd.Row());
}
void ChannelState::BankNeedRefresh(int rank, int bankgroup, int bank,
bool need) {
if (need) {
Address addr = Address(-1, rank, bankgroup, bank, -1, -1);
refresh_q_.emplace_back(CommandType::REFRESH_BANK, addr, -1);
} else {
for (auto it = refresh_q_.begin(); it != refresh_q_.end(); it++) {
if (it->Rank() == rank && it->Bankgroup() == bankgroup &&
it->Bank() == bank) {
refresh_q_.erase(it);
break;
}
}
}
return;
}
void ChannelState::RankNeedRefresh(int rank, bool need) {
if (need) {
Address addr = Address(-1, rank, -1, -1, -1, -1);
refresh_q_.emplace_back(CommandType::REFRESH, addr, -1);
} else {
for (auto it = refresh_q_.begin(); it != refresh_q_.end(); it++) {
if (it->Rank() == rank) {
refresh_q_.erase(it);
break;
}
}
}
return;
}
// Rowclone added
bool ChannelState::CanStartWait(const Command& cmd, uint64_t clk) const{
// only called when read copy ( cmd -> write copy )
auto dest = config_.AddressMapping(cmd.hex_addr.dest_addr);
return bank_states_[dest.rank][dest.bankgroup][dest.bank].CanStartWait(dest, clk);
}
Command ChannelState::GetReadyCommand(const Command& cmd, uint64_t clk) const {
Command ready_cmd = Command();
if (cmd.IsRankCMD()) {
int num_ready = 0;
for (auto j = 0; j < config_.bankgroups; j++) {
for (auto k = 0; k < config_.banks_per_group; k++) {
ready_cmd =
bank_states_[cmd.Rank()][j][k].GetReadyCommand(cmd, clk);
if (!ready_cmd.IsValid()) { // Not ready
continue;
}
if (ready_cmd.cmd_type != cmd.cmd_type) { // likely PRECHARGE
Address new_addr = Address(-1, cmd.Rank(), j, k, -1, -1);
ready_cmd.addr = new_addr;
return ready_cmd;
} else {
num_ready++;
}
}
}
// All bank ready
if (num_ready == config_.banks) {
return ready_cmd;
} else {
return Command();
}
} else {
//std::cout<<"channelstategetreadycommand"<<std::endl;
ready_cmd = bank_states_[cmd.Rank()][cmd.Bankgroup()][cmd.Bank()]
.GetReadyCommand(cmd, clk);
if (!ready_cmd.IsValid()) {
return Command();
}
if (ready_cmd.cmd_type == CommandType::ACTIVATE) {
if (!ActivationWindowOk(ready_cmd.Rank(), clk)) {
return Command();
}
}
return ready_cmd;
}
}
void ChannelState::UpdateState(const Command& cmd) {
if (cmd.IsRankCMD()) {
for (auto j = 0; j < config_.bankgroups; j++) {
for (auto k = 0; k < config_.banks_per_group; k++) {
bank_states_[cmd.Rank()][j][k].UpdateState(cmd);
}
}
if (cmd.IsRefresh()) {
RankNeedRefresh(cmd.Rank(), false);
} else if (cmd.cmd_type == CommandType::SREF_ENTER) {
rank_is_sref_[cmd.Rank()] = true;
} else if (cmd.cmd_type == CommandType::SREF_EXIT) {
rank_is_sref_[cmd.Rank()] = false;
}
} else {
bank_states_[cmd.Rank()][cmd.Bankgroup()][cmd.Bank()].UpdateState(cmd);
if (cmd.IsRefresh()) {
BankNeedRefresh(cmd.Rank(), cmd.Bankgroup(), cmd.Bank(), false);
} else if (cmd.IsReadCopy()){
// make dest bank WAIT WRITECOPY
//std::cout<<"making wait"<<std::endl;
if(!cmd.isFPM){
//std::cout<<"have to make wait"<<std::endl;
auto dest_address = config_.AddressMapping(cmd.hex_addr.dest_addr);
bank_states_[dest_address.rank][dest_address.bankgroup][dest_address.bank].StartWaitWriteCopy(cmd);
//std::cout<<dest_address.rank<<" start wait"<<std::endl;
}
// if not FPM? (same bank copy!?)
else{
auto dest_address = config_.AddressMapping(cmd.hex_addr.dest_addr);
bank_states_[dest_address.rank][dest_address.bankgroup][dest_address.bank].FPMWaitWritecopy(cmd);
}
}
}
return;
}
void ChannelState::UpdateTiming(const Command& cmd, uint64_t clk) {
CommandType copy_type;
switch (cmd.cmd_type) {
case CommandType::ACTIVATE:
UpdateActivationTimes(cmd.Rank(), clk);
case CommandType::READ:
case CommandType::READ_PRECHARGE:
case CommandType::WRITE:
case CommandType::WRITE_PRECHARGE:
case CommandType::PRECHARGE:
case CommandType::REFRESH_BANK:
// TODO - simulator speed? - Speciazlize which of the below
// functions to call depending on the command type Same Bank
UpdateSameBankTiming(
cmd.addr, timing_.same_bank[static_cast<int>(cmd.cmd_type)],
clk);
// Same Bankgroup other banks
UpdateOtherBanksSameBankgroupTiming(
cmd.addr,
timing_
.other_banks_same_bankgroup[static_cast<int>(cmd.cmd_type)],
clk);
// Other bankgroups
UpdateOtherBankgroupsSameRankTiming(
cmd.addr,
timing_
.other_bankgroups_same_rank[static_cast<int>(cmd.cmd_type)],
clk);
// Other ranks
UpdateOtherRanksTiming(
cmd.addr, timing_.other_ranks[static_cast<int>(cmd.cmd_type)],
clk);
break;
case CommandType::REFRESH:
case CommandType::SREF_ENTER:
case CommandType::SREF_EXIT:
UpdateSameRankTiming(
cmd.addr, timing_.same_rank[static_cast<int>(cmd.cmd_type)],
clk);
break;
case CommandType::READCOPY:
case CommandType::READCOPY_PRECHARGE:
case CommandType::WRITECOPY:
case CommandType::WRITECOPY_PRECHARGE:
if((cmd.cmd_type == CommandType::READCOPY) && (cmd.isFPM)){copy_type = CommandType::READCOPY_FPM;}
else if((cmd.cmd_type == CommandType::READCOPY) && (!cmd.isFPM)){copy_type = CommandType::READCOPY_PSM;}
else if((cmd.cmd_type == CommandType::READCOPY_PRECHARGE) && (cmd.isFPM)){copy_type = CommandType::READCOPY_FPM;}
else if((cmd.cmd_type == CommandType::READCOPY_PRECHARGE) && (!cmd.isFPM)){copy_type = CommandType::READCOPY_PSM_PRECHARGE;}
else if((cmd.cmd_type == CommandType::WRITECOPY) && (cmd.isFPM)){copy_type = CommandType::WRITECOPY_FPM;}
else if((cmd.cmd_type == CommandType::WRITECOPY) && (!cmd.isFPM)){copy_type = CommandType::WRITECOPY_PSM;}
else if((cmd.cmd_type == CommandType::WRITECOPY_PRECHARGE) && (cmd.isFPM)){copy_type = CommandType::WRITECOPY_FPM_PRECHARGE;}
else {copy_type = CommandType::WRITECOPY_PSM_PRECHARGE;}
// Same Bank
UpdateSameBankTiming(cmd.addr, timing_.same_bank[static_cast<int>(copy_type)],clk);
// Same Bankgroup other banks
UpdateOtherBanksSameBankgroupTiming(cmd.addr,timing_.other_banks_same_bankgroup[static_cast<int>(copy_type)],clk);
// Other bankgroups
UpdateOtherBankgroupsSameRankTiming(cmd.addr,timing_.other_bankgroups_same_rank[static_cast<int>(copy_type)],clk);
// Other ranks
UpdateOtherRanksTiming(cmd.addr, timing_.other_ranks[static_cast<int>(copy_type)],clk);
break;
default:
AbruptExit(__FILE__, __LINE__);
}
return;
}
void ChannelState::UpdateSameBankTiming(
const Address& addr,
const std::vector<std::pair<CommandType, int>>& cmd_timing_list,
uint64_t clk) {
for (auto cmd_timing : cmd_timing_list) {
bank_states_[addr.rank][addr.bankgroup][addr.bank].UpdateTiming(
cmd_timing.first, clk + cmd_timing.second);
}
return;
}
void ChannelState::UpdateOtherBanksSameBankgroupTiming(
const Address& addr,
const std::vector<std::pair<CommandType, int>>& cmd_timing_list,
uint64_t clk) {
for (auto k = 0; k < config_.banks_per_group; k++) {
if (k != addr.bank) {
for (auto cmd_timing : cmd_timing_list) {
bank_states_[addr.rank][addr.bankgroup][k].UpdateTiming(
cmd_timing.first, clk + cmd_timing.second);
}
}
}
return;
}
void ChannelState::UpdateOtherBankgroupsSameRankTiming(
const Address& addr,
const std::vector<std::pair<CommandType, int>>& cmd_timing_list,
uint64_t clk) {
for (auto j = 0; j < config_.bankgroups; j++) {
if (j != addr.bankgroup) {
for (auto k = 0; k < config_.banks_per_group; k++) {
for (auto cmd_timing : cmd_timing_list) {
bank_states_[addr.rank][j][k].UpdateTiming(
cmd_timing.first, clk + cmd_timing.second);
}
}
}
}
return;
}
void ChannelState::UpdateOtherRanksTiming(
const Address& addr,
const std::vector<std::pair<CommandType, int>>& cmd_timing_list,
uint64_t clk) {
for (auto i = 0; i < config_.ranks; i++) {
if (i != addr.rank) {
for (auto j = 0; j < config_.bankgroups; j++) {
for (auto k = 0; k < config_.banks_per_group; k++) {
for (auto cmd_timing : cmd_timing_list) {
bank_states_[i][j][k].UpdateTiming(
cmd_timing.first, clk + cmd_timing.second);
}
}
}
}
}
return;
}
void ChannelState::UpdateSameRankTiming(
const Address& addr,
const std::vector<std::pair<CommandType, int>>& cmd_timing_list,
uint64_t clk) {
for (auto j = 0; j < config_.bankgroups; j++) {
for (auto k = 0; k < config_.banks_per_group; k++) {
for (auto cmd_timing : cmd_timing_list) {
bank_states_[addr.rank][j][k].UpdateTiming(
cmd_timing.first, clk + cmd_timing.second);
}
}
}
return;
}
void ChannelState::UpdateTimingAndStates(const Command& cmd, uint64_t clk) {
UpdateState(cmd);
UpdateTiming(cmd, clk);
return;
}
bool ChannelState::ActivationWindowOk(int rank, uint64_t curr_time) const {
bool tfaw_ok = IsFAWReady(rank, curr_time);
if (config_.IsGDDR()) {
if (!tfaw_ok)
return false;
else
return Is32AWReady(rank, curr_time);
}
return tfaw_ok;
}
void ChannelState::UpdateActivationTimes(int rank, uint64_t curr_time) {
if (!four_aw_[rank].empty() && curr_time >= four_aw_[rank][0]) {
four_aw_[rank].erase(four_aw_[rank].begin());
}
four_aw_[rank].push_back(curr_time + config_.tFAW);
if (config_.IsGDDR()) {
if (!thirty_two_aw_[rank].empty() &&
curr_time >= thirty_two_aw_[rank][0]) {
thirty_two_aw_[rank].erase(thirty_two_aw_[rank].begin());
}
thirty_two_aw_[rank].push_back(curr_time + config_.t32AW);
}
return;
}
bool ChannelState::IsFAWReady(int rank, uint64_t curr_time) const {
if (!four_aw_[rank].empty()) {
if (curr_time < four_aw_[rank][0] && four_aw_[rank].size() >= 4) {
return false;
}
}
return true;
}
bool ChannelState::Is32AWReady(int rank, uint64_t curr_time) const {
if (!thirty_two_aw_[rank].empty()) {
if (curr_time < thirty_two_aw_[rank][0] &&
thirty_two_aw_[rank].size() >= 32) {
return false;
}
}
return true;
}
} // namespace dramsim3
| 37.972376 | 138 | 0.559508 | [
"vector"
] |
9d08fd836cdbee5fed51f491fb32d2284b694af1 | 888 | cpp | C++ | src/Burst.cpp | XianchaoZhang/hdr-plus | 7435e79bfebef1e5239f57bfa96961ee7e7c3587 | [
"MIT"
] | 1 | 2019-04-11T02:23:07.000Z | 2019-04-11T02:23:07.000Z | src/Burst.cpp | XianchaoZhang/hdr-plus | 7435e79bfebef1e5239f57bfa96961ee7e7c3587 | [
"MIT"
] | null | null | null | src/Burst.cpp | XianchaoZhang/hdr-plus | 7435e79bfebef1e5239f57bfa96961ee7e7c3587 | [
"MIT"
] | null | null | null | #include "Burst.h"
Halide::Runtime::Buffer<uint16_t> Burst::ToBuffer() const {
if (Raws.empty()) {
return Halide::Runtime::Buffer<uint16_t>();
}
Halide::Runtime::Buffer<uint16_t> result(GetWidth(), GetHeight(), Raws.size());
for (int i = 0; i < Raws.size(); ++i) {
auto resultSlice = result.sliced(2, i);
Raws[i]->CopyToBuffer(resultSlice);
}
return result;
}
void Burst::CopyToBuffer(Halide::Runtime::Buffer<uint16_t> &buffer) const {
buffer.copy_from(ToBuffer());
}
std::vector<AbstractInputSource::SPtr> Burst::LoadRaws(const std::string &dirPath, std::vector<std::string> &inputs) {
std::vector<AbstractInputSource::SPtr> result;
for (const auto& input : inputs) {
const std::string img_path = dirPath + "/" + input;
result.emplace_back(std::make_shared<RawSource>(img_path));
}
return result;
}
| 31.714286 | 118 | 0.647523 | [
"vector"
] |
9d0a846ecb0c2b07eb53dfb06a4b1dfdb74ce3f8 | 2,648 | cpp | C++ | fp/b5.cpp | nyirock/plasmid_2015 | 01d89632bcf432b735dbef11fd06d1a279e69370 | [
"MIT"
] | null | null | null | fp/b5.cpp | nyirock/plasmid_2015 | 01d89632bcf432b735dbef11fd06d1a279e69370 | [
"MIT"
] | null | null | null | fp/b5.cpp | nyirock/plasmid_2015 | 01d89632bcf432b735dbef11fd06d1a279e69370 | [
"MIT"
] | null | null | null | /*
* fp.cpp
*
* Created on: Jul 6, 2015
* Author: andriy
*/
#include<iostream>
#include<cstdlib>
#include<algorithm>// find(), search() count() functions
//#include <gmp.h>
//using std::count;
//using std::cout;
//using std::endl;
#include<map> //for key value relations
#include<vector>
#include<string>
using std::string;
#include <iterator>
#include <algorithm>
#include<cmath>//for pow() fucntion
#include"baseFive.h"
using namespace std;
int main(){
char testBaseFive[50];
//cout<<itoa(6, testBaseFive,5)<<endl;
const char * filename="input_DNA.txt";
char * buffer=readFile(filename);
string genome=string(buffer);
string text="ACTATAGCATGCATCGCCAGTGCATAGCATTGCCATGCTTAGCGGC";
string text1="ACTATAGCATGCATCGCCAGTGCATAT";//28 characters
string textNumber="231423412322412314121421432";//26 characters;
string textNumbr2="1111111111111111111111111111";//27 characters almost maximum number, one digit more than the others
string textNumbr3="444444444444444444444444444";//26 characters
int k=18;
vector <unsigned long> positions;
vector <string> patternsBaseFive;
for(int i=0;i<genome.length()-k+1;i++){
string dnaText=genome.substr(i,k);
string baseFive=dnaToBaseFive(dnaText);
unsigned long baseTen=fromBaseFiveToTen(baseFive);
//FrequentPatterns currentPattern(baseFive,baseTen);
positions.push_back(baseTen);
patternsBaseFive.push_back(baseFive);
}
// for(int i=0;i<positions.size();i++)
// cout<<i<<" "<<baseFiveToDNA(patternsBaseFive[i])<<" "<<patternsBaseFive[i]<<" "<<positions[i]<<endl;
// for(int i=0;i<positions.size();i++)
// if(positions[i]==7)
// cout<<"Position of \"AG\" is:"<<i<<endl;
// unsigned long * a=&positions[0];
// unsigned long *p;
// //vector<long unsigned> myints={10,20,30,7,5,15,20};
// p=find(a,a+46,positions[40]);
// cout<<"element 7 is: "<<*p<<"At the position: "<<(p-a)<<endl;
map <unsigned long, int> frequencyMap;
for(int i=0;i<positions.size();i++){
if(!frequencyMap.count(positions[i])>0){//value is unique
int myCount=std::count(positions.begin(),positions.end(),positions[i]);
frequencyMap[positions[i]]=myCount;
}
}
int totalKeys=0;
cout<<"Ten"<<" "<<"Five"<<" "<<"DNA"<<" "<<"Count"<<endl;
for(map<unsigned long, int>::const_iterator it=frequencyMap.begin();it!=frequencyMap.end();++it){
//totalKeys+=it->second;
//if(it->second>100){
cout<<it->first<<" "<<itoa(it->first,testBaseFive,5)<<" "<<baseFiveToDNA(itoa(it->first,testBaseFive,5))<<" "<<it->second<<endl;
//}
}
//cout<<"Total patterns: "<<totalKeys<<"Map Size: "<<frequencyMap.size()<<endl;
//cout<<"genome length: "<<genome.length()<<endl;
return 0;
}
| 28.170213 | 130 | 0.686556 | [
"vector"
] |
9d0b8d357db8a667097daf2e01f94760248768fd | 5,667 | cpp | C++ | SOLVER/src/models3D/Model3D.cpp | nicklinyi/AxiSEM-3D | cd11299605cd6b92eb867d4109d2e6a8f15e6b4d | [
"MIT"
] | 8 | 2020-06-05T01:13:20.000Z | 2022-02-24T05:11:50.000Z | SOLVER/src/models3D/Model3D.cpp | nicklinyi/AxiSEM-3D | cd11299605cd6b92eb867d4109d2e6a8f15e6b4d | [
"MIT"
] | 24 | 2020-10-21T19:03:38.000Z | 2021-11-17T21:32:02.000Z | SOLVER/src/models3D/Model3D.cpp | nicklinyi/AxiSEM-3D | cd11299605cd6b92eb867d4109d2e6a8f15e6b4d | [
"MIT"
] | 5 | 2020-06-21T11:54:22.000Z | 2021-06-23T01:02:39.000Z | //
// Model3D.cpp
// AxiSEM3D
//
// Created by Kuangdai Leng on 3/26/20.
// Copyright © 2020 Kuangdai Leng. All rights reserved.
//
// base class of all 3D models
#include "Model3D.hpp"
#include "Quad.hpp"
#include "vicinity.hpp"
// compute spz on element
eigen::DMatX3 Model3D::computeElemSPZ(const Quad &quad, bool undulated) {
// quad nr
const eigen::IRowN &pointNr = quad.getPointNr();
// GLL coordinates
const eigen::DMat2N &pointSZ = quad.getPointSZ();
// allocate
eigen::DMatX3 spz(pointNr.sum(), 3);
// structured to flattened
int row = 0;
for (int ipnt = 0; ipnt < spectral::nPEM; ipnt++) {
int nr = pointNr(ipnt);
// identical (s, z)
spz.block(row, 0, nr, 1).fill(pointSZ(0, ipnt));
spz.block(row, 2, nr, 1).fill(pointSZ(1, ipnt));
// linearly varying phi
spz.block(row, 1, nr, 1) =
eigen::DColX::LinSpaced(nr, 0, 2. * numerical::dPi / nr * (nr - 1));
row += nr;
}
// undulated geometry
if (!undulated) {
return spz;
}
// get undulation from quad
eigen::arN_DColX und = quad.getUndulation();
// structured to flattened
row = 0;
for (int ipnt = 0; ipnt < spectral::nPEM; ipnt++) {
int nr = pointNr(ipnt);
// extend to 3D
if (und[ipnt].rows() == 1) {
und[ipnt] = und[ipnt].replicate(nr, 1);
}
// change coords based on CS type
if (geodesy::isCartesian()) {
// add undulation to z in Cartesian
spz.block(row, 2, nr, 1) += und[ipnt];
} else {
// add undulation to r in spherical
double s = spz(row, 0);
double z = spz(row, 2);
double r = sqrt(s * s + z * z);
double theta = (r < numerical::dEpsilon) ? 0. : acos(z / r);
spz.block(row, 0, nr, 1) += und[ipnt] * sin(theta);
spz.block(row, 2, nr, 1) += und[ipnt] * cos(theta);
}
row += nr;
}
return spz;
}
// compute spz on edge
eigen::DMatX3 Model3D::computeEdgeSPZ(const Quad &quad, int edge) {
// edge points
const std::vector<int> &ipnts = vicinity::constants::gEdgeIPnt[edge];
// quad nr
const eigen::IRowN &pointNr = quad.getPointNr();
// GLL coordinates
const eigen::DMat2N &pointSZ = quad.getPointSZ();
// allocate
eigen::DMatX3 spz(pointNr(ipnts).sum(), 3);
// structured to flattened
int row = 0;
for (int ipnt: ipnts) {
int nr = pointNr(ipnt);
// identical (s, z)
spz.block(row, 0, nr, 1).fill(pointSZ(0, ipnt));
spz.block(row, 2, nr, 1).fill(pointSZ(1, ipnt));
// linearly varying phi
spz.block(row, 1, nr, 1) =
eigen::DColX::LinSpaced(nr, 0, 2. * numerical::dPi / nr * (nr - 1));
row += nr;
}
return spz;
}
#include "Volumetric3D.hpp"
#include "Geometric3D.hpp"
#include "OceanLoad3D.hpp"
#include "inparam.hpp"
#include "timer.hpp"
// build from inparam
void Model3D::
buildInparam(const ExodusMesh &exodusMesh, const LocalMesh &localMesh,
std::vector<std::shared_ptr<const Model3D>> &models3D,
bool rebuilding) {
// count
int modelCount = inparam::gInparamModel.get<int>("list_of_3D_models:[?]");
// loop over model list
int mindexActive = -1;
for (int mindex = 0; mindex < modelCount; mindex++) {
// model name and key in inparam
std::string keyInparam = "list_of_3D_models";
const std::string &modelName = inparam::gInparamModel.
get<std::string>(keyInparam + ":{" + bstring::toString(mindex) + "}");
keyInparam += ":[" + bstring::toString(mindex) + "]:" + modelName;
// start building
timer::gPreloopTimer.begin("Building 3D model: " + modelName);
// activated or not
if (!inparam::gInparamModel.get<bool>(keyInparam + ":activated")) {
timer::gPreloopTimer.message("Model is deactivated.");
timer::gPreloopTimer.ended("Building 3D model: " + modelName);
continue;
}
mindexActive++;
// do not rebuild if model is mpi-independent
if (rebuilding) {
if (!models3D[mindexActive]->isMPI_Dependent()) {
timer::gPreloopTimer.message("Model is MPI-independent, "
"no need to rebuild.");
timer::gPreloopTimer.ended("Building 3D model: " + modelName);
continue;
}
}
// try volumetric first
std::shared_ptr<const Model3D>
model = Volumetric3D::buildInparam(exodusMesh, localMesh,
modelName, keyInparam);
// try geometric
if (model == nullptr) {
model = Geometric3D::buildInparam(exodusMesh, localMesh,
modelName, keyInparam);
}
// try ocean load
if (model == nullptr) {
model = OceanLoad3D::buildInparam(exodusMesh, localMesh,
modelName, keyInparam);
}
// unknown model class
if (model == nullptr) {
throw std::runtime_error("Model3D::buildInparam || "
"Unknown 3D model: " + modelName);
}
// replace or push back
if (rebuilding) {
models3D[mindexActive].reset(model.get());
} else {
models3D.push_back(model);
}
timer::gPreloopTimer.ended("Building 3D model: " + modelName);
}
}
| 33.532544 | 78 | 0.541556 | [
"geometry",
"vector",
"model",
"3d"
] |
9d15723a9a6d53e108f84c4937e84f1f9fa06bdd | 13,231 | cc | C++ | src/cuda_api_profiler/globals.cc | UofT-EcoSystem/rlscope | cdd9bbdc2a3a832be24f20105b8c9fe28149cb63 | [
"Apache-2.0"
] | 35 | 2021-01-26T22:34:17.000Z | 2022-03-02T01:25:11.000Z | src/cuda_api_profiler/globals.cc | UofT-EcoSystem/rlscope | cdd9bbdc2a3a832be24f20105b8c9fe28149cb63 | [
"Apache-2.0"
] | 1 | 2022-03-15T01:40:03.000Z | 2022-03-15T01:40:03.000Z | src/cuda_api_profiler/globals.cc | UofT-EcoSystem/rlscope | cdd9bbdc2a3a832be24f20105b8c9fe28149cb63 | [
"Apache-2.0"
] | 1 | 2021-03-17T08:49:07.000Z | 2021-03-17T08:49:07.000Z | //
// Created by jagle on 8/19/2019.
//
#include <string>
#include <algorithm>
#include <cctype>
#include <iostream>
#include <fstream>
#include <memory>
#include <unistd.h>
#include <signal.h>
#include <regex>
#include "common/util.h"
#include <boost/process.hpp>
#include <boost/algorithm/string.hpp>
//#include <boost/algorithm/string/join.hpp>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
#include <spdlog/spdlog.h>
//#include <sys/types.h>
// Must be included in order operator<< to work with spd logging.
// https://github.com/gabime/spdlog#user-defined-types
#include "spdlog/fmt/ostr.h"
#include "cuda_api_profiler/cupti_logging.h"
#include "cuda_api_profiler/device_tracer.h"
#include "cuda_api_profiler/cuda_ld_preload.h"
#include "cuda_api_profiler/globals.h"
#include "cuda_api_profiler/get_env_var.h"
//#include "cuda_api_profiler/generic_logging.h"
//#include "cuda_api_profiler/debug_flags.h"
#include "common_util.h"
#define MAYBE_RETURN_ERROR(status) \
if (status.code() != MyStatus::OK().code()) { \
VLOG(INFO) << "rls-prof C++ API @ " << __func__ << " failed with " << status.ToString(); \
return; \
}
namespace bp = boost::process;
namespace rlscope {
Globals globals;
Globals::Globals() {
MyStatus status = MyStatus::OK();
spdlog::set_level(spdlog::level::debug); // Set global log level to debug
#ifdef WITH_CUDA_LD_PRELOAD
VLOG(1) << "dlopen(\"libcudart.so\")";
cuda_library = GetCudaLibrary();
VLOG(1) << "dlopen(\"libcudart.so\"): success!";
#endif
// std::ifstream cmdline_stream("/proc/self/cmdline");
// std::string cmdline((std::istreambuf_iterator<char>(cmdline_stream)),
// std::istreambuf_iterator<char>());
//
// VLOG(1) << "Initialize globals\n"
// << " CMD = " << cmdline;
// VLOG(1) << "SKIP creating device_tracer";
device_tracer = rlscope::CreateDeviceTracer();
auto RLSCOPE_TRACE_AT_START = getenv("RLSCOPE_TRACE_AT_START");
VLOG(1) << "RLSCOPE_TRACE_AT_START = " << RLSCOPE_TRACE_AT_START;
if (device_tracer && env_is_on("RLSCOPE_TRACE_AT_START", false, true)) {
VLOG(1) << "TraceAtStart";
this->TraceAtStart();
}
}
std::string Globals::IMLConfigPath() const {
auto rlscope_config_path = boost::filesystem::path(_directory) /
"process" / _process_name /
"phase" / _phase_name /
"rlscope_config.json";
return rlscope_config_path.string();
}
bool is_machine_util_file(const boost::filesystem::path& path) {
std::regex machine_util_regex(R"(^machine_util\..*.proto)");
std::smatch match;
return std::regex_search(path.filename().string(), match, machine_util_regex);
}
bool is_cuda_device_events_file(const boost::filesystem::path& path) {
std::regex machine_util_regex(R"(^cuda_device_events\..*.proto)");
std::smatch match;
return std::regex_search(path.filename().string(), match, machine_util_regex);
}
bool is_cuda_api_stats_file(const boost::filesystem::path& path) {
std::regex machine_util_regex(R"(^cuda_api_stats\..*.proto)");
std::smatch match;
return std::regex_search(path.filename().string(), match, machine_util_regex);
}
bool is_trace_file(const boost::filesystem::path& path) {
return is_machine_util_file(path) || is_cuda_device_events_file(path) || is_cuda_api_stats_file(path);
}
void Globals::DeleteOldTraceFiles() const {
boost::filesystem::path root_path(_directory);
// https://rosettacode.org/wiki/Walk_a_directory/Recursively#C.2B.2B
if (!boost::filesystem::is_directory(root_path)) {
return;
}
std::list<boost::filesystem::path> to_remove;
for (boost::filesystem::recursive_directory_iterator iter(root_path), end;
iter != end;
++iter)
{
auto path = iter->path();
if (is_trace_file(path)) {
to_remove.push_back(path);
// boost::filesystem::remove(path);
}
}
for (const auto& path : to_remove) {
LOG(INFO) << "RM trace-file @ " << path;
boost::filesystem::remove(path);
}
}
void Globals::DumpIMLConfig() const {
MyStatus status = MyStatus::OK();
auto cur_env = boost::this_process::environment();
json js;
std::map<std::string, std::string> env_dict;
for (const auto& pair : cur_env) {
env_dict[pair.get_name()] = pair.to_string();
// env_dict[pair.]
}
js["env"] = env_dict;
js["process_name"] = _process_name;
js["machine_name"] = _machine_name;
js["phase"] = _phase_name;
js["directory"] = _directory;
auto path = IMLConfigPath();
boost::filesystem::path bpath(path);
boost::filesystem::create_directories(bpath.parent_path());
status = WriteJson(path, js);
assert(status.code() == MyStatus::OK().code());
}
boost::process::environment Globals::PatchedEnviron() {
using namespace boost::process;
environment env = boost::this_process::environment();
if (env.find("LD_PRELOAD") == env.end()) {
return env;
}
std::string LD_PRELOAD = env["LD_PRELOAD"].to_string();
// auto LD_PRELOAD_cstr = getenv("LD_PRELOAD");
// if (LD_PRELOAD_cstr == nullptr) {
// return;
// }
// std::string LD_PRELOAD = LD_PRELOAD_cstr;
std::vector<std::string> paths;
boost::split(paths, LD_PRELOAD, [] (char c) {
return c == ':';
});
auto is_sample_lib = [] (const std::string& path) -> bool {
boost::filesystem::path bpath = path;
auto basename = bpath.filename().string();
return (basename == "librlscope.so");
};
std::vector<std::string> keep_paths;
keep_paths.reserve(paths.size());
for (const auto& path : paths) {
if (!is_sample_lib(path)) {
keep_paths.push_back(path);
}
}
auto new_LD_PRELOAD = boost::algorithm::join(keep_paths, ":");
// setenv("LD_PRELOAD", new_LD_PRELOAD.c_str(), 1);
env["LD_PRELOAD"] = new_LD_PRELOAD;
return env;
}
bool Globals::env_is_yes(const std::string& var) const {
return !env_is_no(var);
}
bool Globals::env_is_no(const std::string& var) const {
auto cur_env = boost::this_process::environment();
if (cur_env.find(var) != cur_env.end()) {
auto value = cur_env[var].to_string();
return (value == "") || (value == "no") || (value == "0") || (value == "false");
}
return true;
}
void Globals::StartUtilSampler() {
auto cur_env = boost::this_process::environment();
if (cur_env.find("RLSCOPE_UTIL_SAMPLER_PID") != cur_env.end()) {
// Utilization sampler is already running; don't start it again.
return;
}
bp::environment env = PatchedEnviron();
bp::ipstream pipe_stream;
auto util_sampler_exe = bp::search_path("rls-util-sampler");
if (util_sampler_exe == "") {
LOG(INFO) << "Couldn't find path to rls-util-sampler on $PATH; have you installed the rlscope python package and activated your environment?";
exit(EXIT_FAILURE);
}
auto pid = getpid();
auto pid_str = std::to_string(pid);
// child c("gcc --version", env, std_out > pipe_stream);
std::vector<std::string> cmd_list{
util_sampler_exe.string(),
"--rlscope-root-pid", pid_str,
"--rlscope-directory", _directory,
};
if (env_is_yes("RLSCOPE_DEBUG")) {
cmd_list.push_back("--rlscope-debug");
}
auto cmd_str = boost::algorithm::join(cmd_list, " ");
_util_sampler = bp::child(
cmd_list,
// util_sampler_exe,
// "--rlscope-root-pid", pid_str,
// "--rlscope-directory", _directory,
env);
LOG(INFO) << "Start GPU utilization sampler " << util_sampler_exe << " @ pid=" << pid;
LOG(INFO) << " $ " << cmd_str;
auto util_sampler_pid = _util_sampler.id();
int ret = setenv("RLSCOPE_UTIL_SAMPLER_PID", std::to_string(util_sampler_pid).c_str(), 1);
assert(ret == 0);
// std::string line;
//
// size_t i = 0;
// while (pipe_stream && std::getline(pipe_stream, line) && !line.empty()) {
// std::cerr << "LINE[" << i << "]: " << line << std::endl;
// i += 1;
// }
//
// c.wait();
}
void Globals::TraceAtStart() {
MyStatus status = MyStatus::OK();
// Should we trace sub-processes?
// The problem here is that we want to run a sub-process during library loading.
// But that means the sub-process will also load the library, and launch a sub-process... etc
// PatchEnviron();
auto RLSCOPE_DIRECTORY = getenv("RLSCOPE_DIRECTORY");
if (RLSCOPE_DIRECTORY == nullptr || strcmp("", RLSCOPE_DIRECTORY) == 0) {
LOG(INFO) << "ERROR: env variable RLSCOPE_DIRECTORY must be set to a directory for storing trace-files.";
exit(EXIT_FAILURE);
}
VLOG(1) << "Check: RLSCOPE_DIRECTORY";
auto RLSCOPE_PROCESS_NAME = getenv("RLSCOPE_PROCESS_NAME");
if (RLSCOPE_PROCESS_NAME == nullptr || strcmp("", RLSCOPE_PROCESS_NAME) == 0) {
LOG(INFO) << "ERROR: env variable RLSCOPE_PROCESS_NAME must be set to the process name.";
exit(EXIT_FAILURE);
}
LOG(INFO) << "Check: RLSCOPE_PROCESS_NAME";
auto RLSCOPE_PHASE_NAME = getenv("RLSCOPE_PHASE_NAME");
if (RLSCOPE_PHASE_NAME == nullptr || strcmp("", RLSCOPE_PHASE_NAME) == 0) {
LOG(INFO) << "ERROR: env variable RLSCOPE_PHASE_NAME must be set to the process name.";
exit(EXIT_FAILURE);
}
LOG(INFO) << "Check: RLSCOPE_PHASE_NAME";
char hostname[256];
int ret = gethostname(hostname, 256);
assert(ret == 0);
_directory = RLSCOPE_DIRECTORY;
_process_name = RLSCOPE_PROCESS_NAME;
_machine_name = hostname;
_phase_name = RLSCOPE_PHASE_NAME;
CheckAvailGpus();
DeleteOldTraceFiles();
// LOG(INFO) << "BLAH: hostname = " << hostname;
status = device_tracer->SetMetadata(
/*directory*/RLSCOPE_DIRECTORY,
/*process_name*/RLSCOPE_PROCESS_NAME,
/*machine_name*/hostname,
/*phase_name*/RLSCOPE_PHASE_NAME);
// MAYBE_RETURN_ERROR(status);
MAYBE_LOG_ERROR(LOG(INFO), __func__, status);
MAYBE_EXIT(status);
mkdir_p(_directory);
DumpIMLConfig();
StartUtilSampler();
LOG(INFO) << "Starting tracing at program start (export RLSCOPE_TRACE_AT_START=yes)";
status = device_tracer->Start();
// MAYBE_RETURN_ERROR(status);
MAYBE_LOG_ERROR(LOG(FATAL), __func__, status);
MAYBE_EXIT(status);
}
void Globals::CheckAvailGpus() const {
auto report_error_and_exit = [] () {
std::stringstream ss;
ss << "RL-Scope ERROR: you must set CUDA_VISIBLE_DEVICES to one of the available GPU's in the system; currently doesn't support multi-GPU use-cases; for example:\n";
ss << " $ export CUDA_VISIBLE_DEVICES=\"0\"";
LOG(INFO) << ss.str();
exit(EXIT_FAILURE);
};
auto cur_env = boost::this_process::environment();
if (cur_env.find("CUDA_VISIBLE_DEVICES") == cur_env.end()) {
report_error_and_exit();
}
auto CUDA_VISIBLE_DEVICES_str = cur_env["CUDA_VISIBLE_DEVICES"].to_string();
std::vector<std::string> device_id_strs;
boost::split(device_id_strs, CUDA_VISIBLE_DEVICES_str, [] (char c) {
return c == ',';
});
std::set<int> device_ids;
std::transform(device_id_strs.begin(), device_id_strs.end(), std::inserter(device_ids, device_ids.end()), [] (const std::string& device_id_str) {
return std::stoi(device_id_str);
});
if (device_ids.size() != 1) {
report_error_and_exit();
}
}
Globals::~Globals() {
// NOTE: some programs will close stdout/stderr BEFORE this gets called.
// This will cause log message to be LOST.
// HOWEVER, the destructor will still execute.
// You can confirm this behaviour by creating a file.
//
// https://stackoverflow.com/questions/23850624/ld-preload-does-not-work-as-expected
//
// std::ofstream myfile;
// myfile.open("globals.destructor.txt");
// myfile << "Writing this to a file.\n";
// myfile.close();
if (device_tracer && device_tracer->IsEnabled()) {
VLOG(FATAL) << "Looks like DeviceTracer was still running... "
<< "please call rlscope_api.disable_tracing() in python BEFORE exiting to avoid stranger behavior in C++ destructors during library unload.";
}
//#define MAYBE_RETURN_ERROR(status)
// if (status.code() != MyStatus::OK().code()) {
// DBG_LOG("rls-prof C++ API @ {} failed with {}", __func__, status.ToString());
// return;
// }
if (_util_sampler.valid() && _util_sampler.running()) {
LOG(INFO) << "Terminate GPU utilization sampler @ pid = " << _util_sampler.id();
// NOTE: this send SIGKILL to process which doesn't allow it to cleanup and dump trace-files...
// use SIGTERM instead.
// _util_sampler.terminate();
int ret = kill(_util_sampler.id(), SIGTERM);
if (ret != 0) {
int err = errno;
if (err == ESRCH) {
LOG(INFO) << "Failed to terminate GPU utilization sampler since its pid didn't exist: " << strerror(err);
} else {
LOG(INFO) << "Failed to terminate GPU utilization sampler (not sure why): " << strerror(err);
exit(EXIT_FAILURE);
}
}
_util_sampler.wait();
}
auto RLSCOPE_TRACE_AT_START = getenv("RLSCOPE_TRACE_AT_START");
// VLOG(1) << "RLSCOPE_TRACE_AT_START = " << RLSCOPE_TRACE_AT_START;
if (device_tracer && env_is_on("RLSCOPE_TRACE_AT_START", false, true)) {
MyStatus status;
status = device_tracer->Print();
MAYBE_RETURN_ERROR(status);
status = device_tracer->AsyncDump();
MAYBE_RETURN_ERROR(status);
status = device_tracer->AwaitDump();
MAYBE_RETURN_ERROR(status);
}
// Dump CUDA API call counts and total CUDA API time to a protobuf file.
// device_tracer->Collect();
}
}
| 32.58867 | 169 | 0.674325 | [
"vector",
"transform"
] |
1dd71475da85a11886a70a1081b47bd8eff1f163 | 10,180 | hpp | C++ | MTimeTool.hpp | yzyw0702/cppToolSet | 5a3d1015cce7a3c81bce8dc89bfc580ba226d834 | [
"MIT"
] | 1 | 2018-09-27T04:02:27.000Z | 2018-09-27T04:02:27.000Z | MTimeTool.hpp | yzyw0702/cpptoolset | 5a3d1015cce7a3c81bce8dc89bfc580ba226d834 | [
"MIT"
] | null | null | null | MTimeTool.hpp | yzyw0702/cpptoolset | 5a3d1015cce7a3c81bce8dc89bfc580ba226d834 | [
"MIT"
] | null | null | null | //===========================
//====> MDateTimeTool
//===========================
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <algorithm>
#include "MStringTool.hpp"
using namespace std;
#ifndef _MTIMETOOL_HPP_
#define _MTIMETOOL_HPP_
namespace tooltime {
class MDateTime {
public: // interfaces
/* constructor */
MDateTime(const string timestr) {
this->m_pTm = str2tm(timestr);
if (!this->isValidTm()) {
cout << "invalid date-time: " << timestr << endl;
this->m_pTm = NULL;
this->m_sTm = "";
}
this->m_sTm = timestr;
}
MDateTime(tm tmIn) {
this->m_pTm = new tm;
*this->m_pTm = tmIn;
char buff[64];
strftime(buff, sizeof(buff), "%Y-%m-%d-%H.%M.%S", this->m_pTm);
this->m_sTm = buff;
}
bool operator < (const MDateTime& other) {
return difftime(mktime(this->m_pTm), mktime(other.m_pTm)) < 0;
}
string getTmStr() {
return this->m_sTm;
}
MDateTime operator + (const double nSec) {
time_t curr = mktime(this->m_pTm);
curr += nSec;
MDateTime* newDt = new MDateTime(this->m_sTm);
newDt->m_pTm = localtime(&curr);
char buff[64];
strftime(buff, sizeof(buff), "%Y-%m-%d-%H.%M.%S", newDt->m_pTm);
newDt->m_sTm = buff;
return *newDt;
}
void operator += (const double nSec) {
time_t curr = mktime(this->m_pTm);
curr += nSec;
this->m_pTm = localtime(&curr);
char buff[64];
strftime(buff, sizeof(buff), "%Y-%m-%d-%H.%M.%S", this->m_pTm);
this->m_sTm = buff;
}
double operator - (const MDateTime& other) {
return difftime(mktime(this->m_pTm), mktime(other.m_pTm));
}
string getDate() { // format: 2018-10-07
return this->m_sTm.substr(0, 10);
}
double getClock() { // unit: sec
double sec = (double)this->m_pTm->tm_hour * 3600;
sec += (double)this->m_pTm->tm_min * 60;
sec += (double)this->m_pTm->tm_sec;
return sec;
}
private: // internal operations
bool isValidTm() {
int yr = this->m_pTm->tm_year + 1900;
if (yr < 1900) return false;
bool isLeapYr = false;
if ((yr % 100 != 0 && yr % 4 == 0) || (yr % 100 == 0 && yr % 400 == 0))
isLeapYr = true;
int m = this->m_pTm->tm_mon + 1;
if (m < 1 || m > 12)
return false;
int d = this->m_pTm->tm_mday;
if ((isLeapYr && m == 2 && d > 28) || (!isLeapYr && m == 2 && d > 27))
return false;
if ((m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12) && d > 31)
return false;
if ((m == 2 || m == 4 || m == 6 || m == 9 || m == 11) && d > 30)
return false;
int hr = this->m_pTm->tm_hour;
if (hr < 0 || hr > 23) return false;
int mi = this->m_pTm->tm_min;
if (mi < 0 || mi > 59) return false;
int se = this->m_pTm->tm_sec;
if (se < 0 || se > 59) return false;
return true;
}
tm* str2tm(const string tmFormated) {
// specific for format "%Y-%m-%d-%H.%M.%S"
vector<string> lTerms = toolstring::split(tmFormated, '-');
tm* t = new tm;
t->tm_year = atoi(lTerms[0].c_str()) - 1900;
t->tm_mon = atoi(lTerms[1].c_str()) - 1;
t->tm_mday = atoi(lTerms[2].c_str());
vector<string> lTm = toolstring::split(lTerms[3], '.');
t->tm_hour = atoi(lTm[0].c_str());
t->tm_min = atoi(lTm[1].c_str());
t->tm_sec = atoi(lTm[2].c_str());
return t;
}
private: // members
tm* m_pTm;
string m_sTm;
};
class MTmFile {
public:
MTmFile() {}
MTmFile(const string filename) {
init(filename);
}
void init(const string filename) {
this->m_fName = filename;
this->fname2tmrg();
}
vector<string> getFileTmRange() {
vector<string> lTm;
lTm.push_back(this->m_pTmStart->getTmStr());
lTm.push_back(this->m_pTmStop->getTmStr());
return lTm;
}
MDateTime getStartTm() {
return *this->m_pTmStart;
}
MDateTime getStopTm() {
return *this->m_pTmStop;
}
private:
void fname2tmrg() {
string prefix = toolstring::rstrip(this->m_fName, ".avi");
vector<string> lTerms = toolstring::split(prefix, '-');
this->m_chName = lTerms[0];
string sStart = lTerms[1] + "-" + lTerms[2] + "-" + lTerms[3] + "-" + lTerms[4];
string sStop = lTerms[1] + "-" + lTerms[2] + "-" + lTerms[3] + "-" + lTerms[5];
this->m_pTmStart = new MDateTime(sStart);
this->m_pTmStop = new MDateTime(sStop);
if (*this->m_pTmStop < *this->m_pTmStart) {
*this->m_pTmStop += 24 * 60 * 60;
}
}
public:
string m_fName;
string m_chName;
private:
MDateTime* m_pTmStart;
MDateTime* m_pTmStop;
};
/* find in-continuous point in a time series */
vector<int> getErrTmPt(vector<string>& lFTm, int thresh = 60) {
MTmFile curr, prev;
vector<int> lIdxErr;
for (int i = 0; i < (int)lFTm.size(); i++) {
curr.init(lFTm[i]);
if (i == 0) {
prev = curr;
continue;
}
double diff = curr.getStartTm() - prev.getStopTm();
if ((diff > 0 && diff > thresh) || (diff < 0 && -diff > thresh)) {
lIdxErr.push_back(i - 1);
}
prev = curr;
}
return lIdxErr; // no interrupt time point
}
/* # get circadian time based on given light schedule */
// ## <pZt>: MDateTime pointer, its str-format must be "2018-10-07-09.00.00"
// ## <hrCtOn>: CT time when light on, unit = hr
// ## <return>: CT time (hr), < 12 = day, > 12 = night
double getCtTime(MDateTime* pZt, double hrCtOn) {
double hrCt = pZt->getClock() / 3600 - hrCtOn;
return (hrCt < 0 ? (hrCt + 24) : hrCt);
}
MDateTime getCurrDateTm() {
time_t secCurr = time(NULL);
tm* pTmCurr = localtime(&secCurr);
return MDateTime(*pTmCurr);
}
bool cmpTmFile(const string& a, const string& b) {
MTmFile tmfA(a), tmfB(b);
MDateTime startA = tmfA.getStartTm();
MDateTime startB = tmfB.getStartTm();
return startA < startB;
}
void sortByDateTm(vector<string>& lFTm) {
std::sort(lFTm.begin(), lFTm.end(), cmpTmFile);
}
} // end of namespace tooltime
namespace debug_tooltime {
using namespace tooltime;
void debug_time() {
/* test class MDateTime */
cout << "## Test class MDateTime\n";
string s1 = "2017-12-29-09.00.00";
string s2 = "2018-01-01-09.00.00";
MDateTime dt1(s1);
MDateTime dt2(s2);
double diff = dt2 - dt1;
if (dt1 < dt2) {
cout << "\tTime " << dt1.getTmStr() << " is earlier than "
<< dt2.getTmStr() << endl;
}
cout << "\tDifference between " << dt1.getTmStr() << " and " << dt2.getTmStr() << " = " << diff / 60 << " min\n";
MDateTime dt3 = dt2 + diff;
cout << "\tAnd if we further add the same difference to " << dt2.getTmStr() << ",\n\tthen the result is " << dt3.getTmStr() << endl;
/* test class MTmFile */
cout << "\n## Test class MTmFile\n";
string fTm = "004-2018-09-26-22.00.00-00.00.00.avi";
MTmFile hTm(fTm);
cout << "\tFile " << hTm.m_fName << " time range is:\n";
toolstring::printStringList(hTm.getFileTmRange());
cout << "\tchannel-name = " << hTm.m_chName << endl;
/* test func getErrTmPt */
cout << "\n## Test func getErrTmPt\n";
string lStr[] = {
"004-2018-09-26-08.46.48-10.00.00.avi",
"004-2018-09-26-10.00.00-12.00.00.avi",
"004-2018-09-26-12.00.00-14.00.00.avi",
"004-2018-09-26-14.00.00-15.58.00.avi",
"004-2018-09-26-16.00.00-18.00.00.avi",
"004-2018-09-26-18.00.00-20.00.00.avi",
"004-2018-09-26-20.00.00-22.00.00.avi",
"004-2018-09-26-22.00.00-00.00.00.avi",
"004-2018-09-27-00.00.00-02.00.00.avi",
"004-2018-09-27-02.00.00-04.00.00.avi",
"004-2018-09-27-04.00.00-06.00.00.avi",
"004-2018-09-27-06.00.00-08.00.00.avi",
"004-2018-09-27-08.00.00-10.00.00.avi",
"004-2018-09-27-10.00.00-12.00.00.avi",
"004-2018-09-27-12.00.00-13.40.19.avi"
};
vector<string> lFTm(lStr, lStr + 15);
vector<int> lErrTmPt = getErrTmPt(lFTm, 60);
if (lErrTmPt.size() == 0) cout << "\tTime-file series are continous.\n";
else {
for (int i = 0; i < (int)lErrTmPt.size(); i++) {
cout << "\tDetect abnormal time point between "
<< lFTm[lErrTmPt[i]] << " and " << lFTm[lErrTmPt[i] + 1]
<< endl;
}
}
/* test func getClock, getDate, getCtTime */
cout << "\n## Test func getClock, getDate, getCtTime\n";
string sTmCt16 = "2017-12-29-01.00.00";
string sTmCt0 = "2017-12-29-09.00.00";
string sTmCt12hf = "2017-12-29-21.15.00";
MDateTime dtCt16(sTmCt16), dtCt0(sTmCt0), dtCt12hf(sTmCt12hf);
double hrCtOn = 9.0;
cout << "\tDate = " << dtCt16.getDate() << endl;
double hrCt16 = getCtTime(&dtCt16, hrCtOn);
double hrCt0 = getCtTime(&dtCt0, hrCtOn);
double hrCt12hf = getCtTime(&dtCt12hf, hrCtOn);
cout << "\tTime " << sTmCt16 << " = CT" << hrCt16 << endl
<< "\tTime " << sTmCt0 << " = CT" << hrCt0 << endl
<< "\tTime " << sTmCt12hf << " = CT" << hrCt12hf << endl;
/* test MDateTime(tm) and func getCurrDateTm */
cout << "\n## Test MDateTime(tm) and func getCurrDateTm\n";
MDateTime dtCurr = getCurrDateTm();
cout << "\tCurrent date-time: " << dtCurr.getTmStr().c_str() << endl;
/* test func cmpTmFile, sortByDateTm */
cout << "\n## Test func cmpTmFile, sortByDateTm\n";
string ulStr[] = {
"004-2018-09-26-14.00.00-16.00.00.avi",
"004-2018-09-26-16.00.00-18.00.00.avi",
"004-2018-09-27-00.00.00-02.00.00.avi",
"004-2018-09-27-06.00.00-08.00.00.avi",
"004-2018-09-27-08.00.00-10.00.00.avi",
"004-2018-09-26-08.46.48-10.00.00.avi",
"004-2018-09-26-10.00.00-12.00.00.avi",
"004-2018-09-26-12.00.00-14.00.00.avi",
"004-2018-09-27-02.00.00-04.00.00.avi",
"004-2018-09-27-04.00.00-06.00.00.avi",
"004-2018-09-26-18.00.00-20.00.00.avi",
"004-2018-09-26-20.00.00-22.00.00.avi",
"004-2018-09-26-22.00.00-00.00.00.avi",
"004-2018-09-27-10.00.00-12.00.00.avi",
"004-2018-09-27-12.00.00-13.40.19.avi"
};
vector<string> ulFTm;
for (int i=0; i < 15; i++)
ulFTm.push_back(ulStr[i]);
cout << "\t### before sorting:\n";
toolstring::printStringList(ulFTm);
sortByDateTm(ulFTm);
cout << "\n\t### after sorting:\n";
toolstring::printStringList(ulFTm);
}
}
#endif | 31.131498 | 135 | 0.574656 | [
"vector"
] |
1ddba0271ef2f10dcdd13d776389f4b52d3cff29 | 726 | cpp | C++ | Third Maximum Number.cpp | durgirajesh/Leetcode | 18b11cd90e8a5ce33f4029d5b7edf9502273bc76 | [
"MIT"
] | 2 | 2020-06-25T12:46:13.000Z | 2021-07-06T06:34:33.000Z | Third Maximum Number.cpp | durgirajesh/Leetcode | 18b11cd90e8a5ce33f4029d5b7edf9502273bc76 | [
"MIT"
] | null | null | null | Third Maximum Number.cpp | durgirajesh/Leetcode | 18b11cd90e8a5ce33f4029d5b7edf9502273bc76 | [
"MIT"
] | null | null | null | class Solution {
public:
int thirdMax(vector<int>& nums) {
int n=nums.size();
priority_queue<int> maxheap;
for(int i=0;i<n;i++){
maxheap.push(nums[i]);
}
vector<int> vec;
int prev=maxheap.top();
vec.push_back(prev);
maxheap.pop();
while(!maxheap.empty()){
if(maxheap.top()!=prev){
vec.push_back(maxheap.top());
}
prev=maxheap.top();
maxheap.pop();
}
if(vec.size() < 3){
return vec[0];
}
else{
return vec[2];
}
}
};
| 21.352941 | 46 | 0.37741 | [
"vector"
] |
1de2b5bc3542adbe66381a25fb7eb0e834cfc5bd | 15,856 | cpp | C++ | source/Vulkan/GraphicsPipelineManager.cpp | hadryansalles/Luz | a262b809cb7e2e9e6ca033afcab300cbafc689f4 | [
"MIT"
] | 43 | 2021-07-27T19:22:35.000Z | 2022-03-19T19:11:06.000Z | source/Vulkan/GraphicsPipelineManager.cpp | hadryansalles/Luz | a262b809cb7e2e9e6ca033afcab300cbafc689f4 | [
"MIT"
] | null | null | null | source/Vulkan/GraphicsPipelineManager.cpp | hadryansalles/Luz | a262b809cb7e2e9e6ca033afcab300cbafc689f4 | [
"MIT"
] | 3 | 2021-09-26T13:32:10.000Z | 2021-12-08T10:18:15.000Z | #include "Luzpch.hpp"
#include "GraphicsPipelineManager.hpp"
#include "PhysicalDevice.hpp"
#include "LogicalDevice.hpp"
#include "SwapChain.hpp"
#include "Instance.hpp"
#include "VulkanUtils.hpp"
void GraphicsPipelineManager::Create() {
auto device = LogicalDevice::GetVkDevice();
auto allocator = Instance::GetAllocator();
auto numFrames = SwapChain::GetNumFrames();
VkDescriptorPoolSize imguiPoolSizes[] = { {VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1000}, {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1000} };
VkDescriptorPoolCreateInfo imguiPoolInfo{};
imguiPoolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
imguiPoolInfo.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT;
imguiPoolInfo.maxSets = (uint32_t)(1024);
imguiPoolInfo.poolSizeCount = sizeof(imguiPoolSizes)/sizeof(VkDescriptorPoolSize);
imguiPoolInfo.pPoolSizes = imguiPoolSizes;
VkResult result = vkCreateDescriptorPool(device, &imguiPoolInfo, allocator, &imguiDescriptorPool);
DEBUG_VK(result, "Failed to create imgui descriptor pool!");
// create bindless resources
{
const u32 MAX_UNIFORMS = PhysicalDevice::GetProperties().limits.maxPerStageDescriptorUniformBuffers-10;
const u32 MAX_STORAGE = PhysicalDevice::GetProperties().limits.maxPerStageDescriptorStorageBuffers;
const u32 MAX_TEXTURES = PhysicalDevice::GetProperties().limits.maxPerStageDescriptorSampledImages-10;
// create descriptor set pool for bindless resources
std::vector<VkDescriptorPoolSize> bindlessPoolSizes = {
{VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, MAX_TEXTURES},
{VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, MAX_UNIFORMS},
{VK_DESCRIPTOR_TYPE_STORAGE_BUFFER, MAX_STORAGE},
{VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR, 1}
};
VkDescriptorPoolCreateInfo bindlessPoolInfo{};
bindlessPoolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
bindlessPoolInfo.flags = VK_DESCRIPTOR_POOL_CREATE_UPDATE_AFTER_BIND_BIT;
bindlessPoolInfo.maxSets = 1;
bindlessPoolInfo.poolSizeCount = bindlessPoolSizes.size();
bindlessPoolInfo.pPoolSizes = bindlessPoolSizes.data();
result = vkCreateDescriptorPool(device, &bindlessPoolInfo, allocator, &bindlessDescriptorPool);
DEBUG_VK(result, "Failed to create bindless descriptor pool!");
// create descriptor set layout for bindless resources
std::vector<VkDescriptorSetLayoutBinding> bindings;
std::vector<VkDescriptorBindingFlags> bindingFlags;
VkDescriptorSetLayoutBinding texturesBinding{};
texturesBinding.binding = TEXTURES_BINDING;
texturesBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
texturesBinding.descriptorCount = MAX_TEXTURES;
texturesBinding.stageFlags = VK_SHADER_STAGE_ALL;
bindings.push_back(texturesBinding);
bindingFlags.push_back({ VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT | VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT });
VkDescriptorSetLayoutBinding storageBuffersBinding{};
storageBuffersBinding.binding = STORAGE_BINDING;
storageBuffersBinding.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
storageBuffersBinding.descriptorCount = MAX_STORAGE;
storageBuffersBinding.stageFlags = VK_SHADER_STAGE_ALL;
bindings.push_back(storageBuffersBinding);
bindingFlags.push_back({ VK_DESCRIPTOR_BINDING_PARTIALLY_BOUND_BIT });
VkDescriptorSetLayoutBinding accelerationStructureBinding{};
accelerationStructureBinding.binding = ACCELERATION_STRUCTURE_BINDING;
accelerationStructureBinding.descriptorType = VK_DESCRIPTOR_TYPE_ACCELERATION_STRUCTURE_KHR;
accelerationStructureBinding.descriptorCount = 1;
accelerationStructureBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
bindings.push_back(accelerationStructureBinding);
bindingFlags.push_back({ VK_DESCRIPTOR_BINDING_UPDATE_AFTER_BIND_BIT });
VkDescriptorSetLayoutBindingFlagsCreateInfo setLayoutBindingFlags{};
setLayoutBindingFlags.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_BINDING_FLAGS_CREATE_INFO;
setLayoutBindingFlags.bindingCount = bindingFlags.size();
setLayoutBindingFlags.pBindingFlags = bindingFlags.data();
VkDescriptorSetLayoutCreateInfo descriptorLayoutInfo{};
descriptorLayoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
descriptorLayoutInfo.bindingCount = bindings.size();
descriptorLayoutInfo.pBindings = bindings.data();
descriptorLayoutInfo.flags = VK_DESCRIPTOR_SET_LAYOUT_CREATE_UPDATE_AFTER_BIND_POOL_BIT;
descriptorLayoutInfo.pNext = &setLayoutBindingFlags;
result = vkCreateDescriptorSetLayout(device, &descriptorLayoutInfo, allocator, &bindlessDescriptorLayout);
DEBUG_VK(result, "Failed to create bindless descriptor set layout!");
// create descriptor set for bindless resources
VkDescriptorSetAllocateInfo allocInfo{};
allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
allocInfo.descriptorPool = bindlessDescriptorPool;
allocInfo.descriptorSetCount = 1;
allocInfo.pSetLayouts = &bindlessDescriptorLayout;
result = vkAllocateDescriptorSets(device, &allocInfo, &bindlessDescriptorSet);
DEBUG_VK(result, "Failed to allocate bindless descriptor set!");
}
}
void GraphicsPipelineManager::Destroy() {
vkDestroyDescriptorPool(LogicalDevice::GetVkDevice(), imguiDescriptorPool, Instance::GetAllocator());
// bindless resources
{
vkDestroyDescriptorPool(LogicalDevice::GetVkDevice(), bindlessDescriptorPool, Instance::GetAllocator());
vkDestroyDescriptorSetLayout(LogicalDevice::GetVkDevice(), bindlessDescriptorLayout, Instance::GetAllocator());
bindlessDescriptorSet = VK_NULL_HANDLE;
bindlessDescriptorPool = VK_NULL_HANDLE;
bindlessDescriptorLayout = VK_NULL_HANDLE;
}
}
void GraphicsPipelineManager::CreatePipeline(const GraphicsPipelineDesc& desc, GraphicsPipelineResource& res) {
auto device = LogicalDevice::GetVkDevice();
auto allocator = Instance::GetAllocator();
std::vector<ShaderResource> shaderResources(desc.shaderStages.size());
std::vector<VkPipelineShaderStageCreateInfo> shaderStages(desc.shaderStages.size());
for (int i = 0; i < shaderResources.size(); i++) {
Shader::Create(desc.shaderStages[i], shaderResources[i]);
shaderStages[i] = shaderResources[i].stageCreateInfo;
}
VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vertexInputInfo.vertexBindingDescriptionCount = 1;
vertexInputInfo.vertexAttributeDescriptionCount = (uint32_t)(desc.attributesDesc.size());
// these points to an array of structs that describe how to load the vertex data
vertexInputInfo.pVertexBindingDescriptions = &desc.bindingDesc;
vertexInputInfo.pVertexAttributeDescriptions = desc.attributesDesc.data();
// define the type of input of our pipeline
VkPipelineInputAssemblyStateCreateInfo inputAssembly{};
inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
// with this parameter true we can break up lines and triangles in _STRIP topology modes
inputAssembly.primitiveRestartEnable = VK_FALSE;
VkViewport viewport{};
viewport.x = 0.0f;
viewport.y = 0.0f;
viewport.width = static_cast<float> (SwapChain::GetExtent().width);
viewport.height = static_cast<float> (SwapChain::GetExtent().height);
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
VkRect2D scissor{};
scissor.offset = { 0, 0 };
scissor.extent = SwapChain::GetExtent();
VkPipelineViewportStateCreateInfo viewportState{};
viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewportState.viewportCount = 1;
viewportState.pViewports = &viewport;
viewportState.scissorCount = 1;
viewportState.pScissors = &scissor;
std::vector<VkDescriptorSetLayout> layouts;
layouts.push_back(bindlessDescriptorLayout);
VkPushConstantRange pushConstant{};
pushConstant.offset = 0;
pushConstant.size = 128;
pushConstant.stageFlags = VK_SHADER_STAGE_ALL;
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = layouts.size();
pipelineLayoutInfo.pSetLayouts = layouts.data();
pipelineLayoutInfo.pushConstantRangeCount = 1;
pipelineLayoutInfo.pPushConstantRanges = &pushConstant;
auto vkRes = vkCreatePipelineLayout(device, &pipelineLayoutInfo, allocator, &res.layout);
DEBUG_VK(vkRes, "Failed to create pipeline layout!");
VkGraphicsPipelineCreateInfo pipelineInfo{};
pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipelineInfo.stageCount = 2;
pipelineInfo.pStages = shaderStages.data();
pipelineInfo.pVertexInputState = &vertexInputInfo;
pipelineInfo.pInputAssemblyState = &inputAssembly;
pipelineInfo.pViewportState = &viewportState;
pipelineInfo.pRasterizationState = &desc.rasterizer;
pipelineInfo.pMultisampleState = &desc.multisampling;
pipelineInfo.pDepthStencilState = &desc.depthStencil;
pipelineInfo.pColorBlendState = &desc.colorBlendState;
pipelineInfo.pDynamicState = nullptr;
pipelineInfo.layout = res.layout;
pipelineInfo.renderPass = SwapChain::GetRenderPass();
pipelineInfo.subpass = 0;
// if we were creating this pipeline by deriving it from another
// we should specify here
pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
pipelineInfo.basePipelineIndex = -1;
vkRes = vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineInfo, allocator, &res.pipeline);
DEBUG_VK(vkRes, "Failed to create graphics pipeline!");
for (int i = 0; i < shaderResources.size(); i++) {
Shader::Destroy(shaderResources[i]);
}
res.dirty = false;
}
void GraphicsPipelineManager::DestroyPipeline(GraphicsPipelineResource& res) {
vkDestroyPipeline(LogicalDevice::GetVkDevice(), res.pipeline, Instance::GetAllocator());
vkDestroyPipelineLayout(LogicalDevice::GetVkDevice(), res.layout, Instance::GetAllocator());
for (int i = 0; i < res.descriptorSetLayouts.size(); i++) {
vkDestroyDescriptorSetLayout(LogicalDevice::GetVkDevice(), res.descriptorSetLayouts[i], Instance::GetAllocator());
}
}
void GraphicsPipelineManager::OnImgui(GraphicsPipelineDesc& desc, GraphicsPipelineResource& res) {
ImGuiTreeNodeFlags nodeFlags = ImGuiTreeNodeFlags_DefaultOpen;
const float totalWidth = ImGui::GetContentRegionAvailWidth();
std::string name = desc.name + " Graphics Pipeline";
if (ImGui::CollapsingHeader(name.c_str())) {
// polygon mode
{
if (PhysicalDevice::GetFeatures().fillModeNonSolid) {
ImGui::Text("Polygon Mode");
ImGui::SameLine(totalWidth*3.0/5.0f);
ImGui::SetNextItemWidth(totalWidth*2.0/5.0f);
ImGui::PushID("polygonMode");
if (ImGui::BeginCombo("", LUZ_VkPolygonModeStr(desc.rasterizer.polygonMode))) {
for (auto mode : LUZ_VkPolygonModes()) {
bool selected = mode == desc.rasterizer.polygonMode;
if (ImGui::Selectable(LUZ_VkPolygonModeStr(mode), selected) && !selected) {
desc.rasterizer.polygonMode = mode;
res.dirty = true;
}
if (selected) {
ImGui::SetItemDefaultFocus();
}
}
ImGui::EndCombo();
}
ImGui::PopID();
}
}
// line width
{
if (PhysicalDevice::GetFeatures().wideLines) {
ImGui::Text("Line width");
ImGui::SameLine(totalWidth * 3.0 / 5.0f);
ImGui::SetNextItemWidth(totalWidth * 2.0 / 5.0f);
ImGui::PushID("lineWidth");
if (ImGui::DragFloat("", &desc.rasterizer.lineWidth, 0.01f, 0.01f, 10.0f)) {
res.dirty = true;
}
ImGui::PopID();
}
}
// cull mode
{
ImGui::Text("Cull Mode");
ImGui::SameLine(totalWidth*3.0/5.0f);
ImGui::SetNextItemWidth(totalWidth*2.0/5.0f);
ImGui::PushID("cullMode");
if (ImGui::BeginCombo("", LUZ_VkCullModeStr(desc.rasterizer.cullMode))) {
for (auto mode : LUZ_VkCullModes()) {
bool selected = mode == desc.rasterizer.cullMode;
if (ImGui::Selectable(LUZ_VkCullModeStr(mode), selected) && !selected) {
desc.rasterizer.cullMode = mode;
res.dirty = true;
}
if (selected) {
ImGui::SetItemDefaultFocus();
}
}
ImGui::EndCombo();
}
ImGui::PopID();
}
// sample shading
{
if (PhysicalDevice::GetFeatures().sampleRateShading) {
ImGui::Text("Sample Shading");
ImGui::SameLine(totalWidth*3.0f/5.0f);
ImGui::PushID("sampleShading");
if (ImGui::Checkbox("", (bool*)&desc.multisampling.sampleShadingEnable)) {
res.dirty = true;
}
ImGui::PopID();
if(desc.multisampling.sampleShadingEnable) {
ImGui::Text("Min Sample Shading");
ImGui::SameLine(totalWidth * 3.0f / 5.0f);
ImGui::SetNextItemWidth(totalWidth * 2.0f / 5.0f);
ImGui::PushID("minSampleShading");
if (ImGui::DragFloat("", &desc.multisampling.minSampleShading, 0.0001f, 0.0f, 1.0f)) {
res.dirty = true;
}
ImGui::PopID();
}
}
}
// depth clamp
{
if (PhysicalDevice::GetFeatures().depthClamp) {
ImGui::Text("Depth Clamp");
ImGui::SameLine(totalWidth * 3.0f / 5.0f);
ImGui::PushID("depthClamp");
if (ImGui::Checkbox("", (bool*)&desc.rasterizer.depthClampEnable)) {
res.dirty = true;
}
ImGui::PopID();
}
}
}
}
void GraphicsPipelineManager::WriteStorage(StorageBuffer& uniform, int index) {
int numFrames = SwapChain::GetNumFrames();
std::vector<VkDescriptorBufferInfo> bufferInfos(numFrames);
std::vector<VkWriteDescriptorSet> writes(numFrames);
for (int i = 0; i < numFrames; i++) {
bufferInfos[i].buffer = uniform.resource.buffer;
bufferInfos[i].offset = i*uniform.sectionSize;
bufferInfos[i].range = uniform.dataSize;
writes[i].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
writes[i].dstSet = bindlessDescriptorSet;
writes[i].dstBinding = GraphicsPipelineManager::STORAGE_BINDING;
writes[i].dstArrayElement = numFrames*index + i;
writes[i].descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
writes[i].descriptorCount = 1;
writes[i].pBufferInfo = &bufferInfos[i];
}
vkUpdateDescriptorSets(LogicalDevice::GetVkDevice(), numFrames, writes.data(), 0, nullptr);
} | 47.050445 | 144 | 0.682265 | [
"vector"
] |
1de925f77ea4b50c374f3f8f4ddc14ece4cd2cee | 2,530 | cpp | C++ | YelBelt/week 6/result/database.cpp | Bytan97/CpSpec | 31ec3c960c2f9446c3f3928ce08b24a872eb288b | [
"Unlicense"
] | null | null | null | YelBelt/week 6/result/database.cpp | Bytan97/CpSpec | 31ec3c960c2f9446c3f3928ce08b24a872eb288b | [
"Unlicense"
] | null | null | null | YelBelt/week 6/result/database.cpp | Bytan97/CpSpec | 31ec3c960c2f9446c3f3928ce08b24a872eb288b | [
"Unlicense"
] | null | null | null | #include "database.h"
void Database::Add(const Date &date, const std::string &event) {
if (!data_unique[date].count(event)) {
data[date].push_back(event);
}
data_unique[date].insert(event);
}
void Database::Print(std::ostream &os) const {
for (const auto &[key, value] : data) {
for (const auto &event : value) {
os << key << " " << event << std::endl;
}
}
}
std::string Database::Last(Date date) const {
if (data.empty()) {
throw std::invalid_argument("");
}
auto left = data.upper_bound(date);
if (left == data.begin()) {
throw std::invalid_argument("");
}
--left;
if (left->first > date) {
throw std::invalid_argument("");
}
std::ostringstream os;
os << left->first << " " << left->second.back();
return os.str();
}
int Database::RemoveIf(const std::function<bool(const Date &, const std::string &)> &predicate) {
int cnt = 0;
std::map<Date, std::vector<std::string>> updated_data;
std::map<Date, std::set<std::string>> updated_unique_data;
for (auto &events_date : data) {
auto date = events_date.first;
auto boundary = std::stable_partition(events_date.second.begin(),
events_date.second.end(),
[predicate, date](const auto &event) {
return !predicate(date, event);
});
if (boundary != events_date.second.begin()) {
updated_data[date] = std::vector<std::string>(events_date.second.begin(), boundary);
updated_unique_data[date] = std::set<std::string>(events_date.second.begin(), boundary);
cnt += static_cast<int>(events_date.second.size() - updated_data[date].size());
} else {
cnt += static_cast<int>(events_date.second.size());
}
}
data = updated_data;
data_unique = updated_unique_data;
return cnt;
}
std::vector<std::pair<Date, std::string>> Database::FindIf(const std::function<bool(const Date &,
const std::string &)> &predicate) const {
std::vector<std::pair<Date, std::string>> result;
for (const auto &[date, events] : data) {
for (const auto &event : events) {
if (predicate(date, event)) {
result.push_back({date, event});
}
}
}
return result;
}
std::ostream &operator<<(std::ostream &os, const std::pair<Date, std::string> &entry) {
os << entry.first << " " << entry.second;
return os;
}
| 32.435897 | 125 | 0.572727 | [
"vector"
] |
1de991b7bbf3d68e527abe675552da6e64724b38 | 3,288 | hpp | C++ | src/served/parameters.hpp | ColquhounAudio/served | 612fa1cc8a71555109b2614cb3e29609c1c16b77 | [
"MIT"
] | null | null | null | src/served/parameters.hpp | ColquhounAudio/served | 612fa1cc8a71555109b2614cb3e29609c1c16b77 | [
"MIT"
] | null | null | null | src/served/parameters.hpp | ColquhounAudio/served | 612fa1cc8a71555109b2614cb3e29609c1c16b77 | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2014 MediaSift Ltd.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef SERVED_PARAMS_HPP
#define SERVED_PARAMS_HPP
#include <unordered_map>
#include <string>
namespace served {
/*
* Represents a collection of named parameters passed via the request URI.
*
* This class represents named parameters defined by the user when registering
* method handlers in a multiplexer.
*
* When the multiplexer matches a method handler, the parsed parameters are
* stored in an instance of this object which is then passed to the handler via
* the request object.
*
* Parameters are stored in a hash map.
*/
class parameters
{
typedef std::unordered_map<std::string, std::string> parameter_list;
parameter_list _list;
public:
// ----- parameter setting -----
/*
* Accesses a parameter based on a key.
*
* The reference to the parameter is returned and can be modified through this operator. If the
* key does not yet exist then it is created.
*
* @param key the key of the parameter
*
* @return the parameter stored under the key
*/
std::string & operator[](std::string const& key);
/*
* Set a parameter.
*
* @param key the key to store the parameter under
* @param value the value of the parameter
*/
void set(std::string const& key, std::string const& value);
// ----- parameter accessors -----
/*
* Obtain the value of a parameter.
*
* @param key the key of the parameter
*
* @return the value of the parameter, or an empty string if the key is not matched.
*/
const std::string operator[](std::string const& key) const;
/*
* Obtain the value of a parameter.
*
* @param key the key of the parameter
*
* @return the value of the parameter, or an empty string if the key is not matched.
*/
const std::string get(std::string const& key) const;
// ----- iterators -----
parameter_list::iterator begin() { return _list.begin(); }
parameter_list::iterator end () { return _list.end (); }
parameter_list::const_iterator begin() const { return _list.begin(); }
parameter_list::const_iterator end () const { return _list.end (); }
const std::unordered_map<std::string, std::string> getList() const;
};
} // served
#endif // SERVED_PARAMS_HPP
| 30.728972 | 96 | 0.714112 | [
"object"
] |
1dea770431d42ac2e7871c749e5bab022e5263d8 | 13,525 | cpp | C++ | src/linking/entry_point.cpp | dan-blank/yogar-cbmc | 05b4f056b585b65828acf39546c866379dca6549 | [
"MIT"
] | 1 | 2020-10-20T14:33:25.000Z | 2020-10-20T14:33:25.000Z | src/linking/entry_point.cpp | dan-blank/yogar-cbmc | 05b4f056b585b65828acf39546c866379dca6549 | [
"MIT"
] | 1 | 2017-02-22T14:35:19.000Z | 2017-02-27T08:49:58.000Z | src/linking/entry_point.cpp | dan-blank/yogar-cbmc | 05b4f056b585b65828acf39546c866379dca6549 | [
"MIT"
] | 4 | 2019-01-19T03:32:21.000Z | 2021-12-20T14:25:19.000Z | /*******************************************************************\
Module:
Author: Daniel Kroening, kroening@kroening.com
\*******************************************************************/
#include <cassert>
#include <cstdlib>
#include <util/namespace.h>
#include <util/expr_util.h>
#include <util/std_expr.h>
#include <util/arith_tools.h>
#include <util/std_code.h>
#include <util/config.h>
#include <util/cprover_prefix.h>
#include <util/prefix.h>
#include <ansi-c/c_types.h>
#include "entry_point.h"
#include "zero_initializer.h"
/*******************************************************************\
Function: build_function_environment
Inputs:
Outputs:
Purpose:
\*******************************************************************/
exprt::operandst build_function_environment(
const code_typet::parameterst ¶meters)
{
exprt::operandst result;
result.resize(parameters.size());
for(unsigned i=0; i<parameters.size(); i++)
{
result[i]=side_effect_expr_nondett(parameters[i].type());
}
return result;
}
/*******************************************************************\
Function: static_lifetime_init
Inputs:
Outputs:
Purpose:
\*******************************************************************/
bool static_lifetime_init(
symbol_tablet &symbol_table,
const source_locationt &source_location,
message_handlert &message_handler)
{
namespacet ns(symbol_table);
symbol_tablet::symbolst::iterator s_it=
symbol_table.symbols.find("c::__CPROVER_initialize");
if(s_it==symbol_table.symbols.end()) return false;
symbolt &init_symbol=s_it->second;
init_symbol.value=code_blockt();
init_symbol.value.add_source_location()=source_location;
code_blockt &dest=to_code_block(to_code(init_symbol.value));
// do assignments based on "value"
Forall_symbols(it, symbol_table.symbols)
{
const irep_idt &identifier=it->first;
if(!it->second.is_static_lifetime) continue;
if(it->second.is_type) continue;
// special values
if(identifier==CPROVER_PREFIX "constant_infinity_uint" ||
identifier==CPROVER_PREFIX "memory" ||
identifier=="c::__func__" ||
identifier=="c::__FUNCTION__" ||
identifier=="c::__PRETTY_FUNCTION__" ||
identifier=="c::argc'" ||
identifier=="c::argv'" ||
identifier=="c::envp'" ||
identifier=="c::envp_size'")
continue;
// just for linking
if(has_prefix(id2string(identifier), CPROVER_PREFIX "architecture_"))
continue;
const typet &type=ns.follow(it->second.type);
// check type
if(type.id()==ID_code ||
type.id()==ID_empty)
continue;
// We won't try to initialize any symbols that have
// remained incomplete.
if(it->second.value.is_nil() &&
it->second.is_extern)
// Compilers would usually complain about these
// symbols being undefined.
continue;
if(type.id()==ID_array &&
to_array_type(type).size().is_nil())
{
// C standard 6.9.2, paragraph 5
// adjust the type to an array of size 1
it->second.type=type;
it->second.type.set(ID_size, gen_one(size_type()));
}
if(type.id()==ID_incomplete_struct ||
type.id()==ID_incomplete_union)
continue; // do not initialize
if(it->second.value.id()==ID_nondet)
continue; // do not initialize
exprt rhs;
if(it->second.value.is_nil())
{
try
{
namespacet ns(symbol_table);
rhs=zero_initializer(it->second.type, it->second.location, ns, message_handler);
assert(rhs.is_not_nil());
}
catch(...)
{
return true;
}
}
else
rhs=it->second.value;
symbol_exprt symbol(it->second.name, it->second.type);
code_assignt code(symbol, rhs);
code.add_source_location()=it->second.location;
dest.move_to_operands(code);
}
// call designated "initialization" functions
forall_symbols(it, symbol_table.symbols)
{
if(it->second.type.get_bool("initialization") &&
it->second.type.id()==ID_code)
{
code_function_callt function_call;
function_call.function()=it->second.symbol_expr();
function_call.add_source_location()=source_location;
dest.move_to_operands(function_call);
}
}
return false;
}
/*******************************************************************\
Function: entry_point
Inputs:
Outputs:
Purpose:
\*******************************************************************/
bool entry_point(
symbol_tablet &symbol_table,
const std::string &standard_main,
message_handlert &message_handler)
{
// check if main is already there
if(symbol_table.symbols.find(ID_main)!=symbol_table.symbols.end())
return false; // silently ignore
irep_idt main_symbol;
// find main symbol
if(config.main!="")
{
std::list<irep_idt> matches;
forall_symbol_base_map(it, symbol_table.symbol_base_map, config.main)
{
// look it up
symbol_tablet::symbolst::const_iterator s_it=symbol_table.symbols.find(it->second);
if(s_it==symbol_table.symbols.end()) continue;
if(s_it->second.type.id()==ID_code)
matches.push_back(it->second);
}
if(matches.empty())
{
messaget message(message_handler);
message.error("main symbol `"+config.main+"' not found");
return true; // give up
}
if(matches.size()>=2)
{
messaget message(message_handler);
message.error("main symbol `"+config.main+"' is ambiguous");
return true;
}
main_symbol=matches.front();
}
else
main_symbol=standard_main;
// look it up
symbol_tablet::symbolst::const_iterator s_it=symbol_table.symbols.find(main_symbol);
if(s_it==symbol_table.symbols.end())
{
messaget message(message_handler);
message.error("main symbol `"+id2string(main_symbol)+"' not in symbol table");
return true; // give up, no main
}
const symbolt &symbol=s_it->second;
// check if it has a body
if(symbol.value.is_nil())
{
messaget message(message_handler);
message.error("main symbol `"+id2string(main_symbol)+"' has no body");
return false; // give up
}
if(static_lifetime_init(symbol_table, symbol.location, message_handler))
return true;
code_blockt init_code;
// build call to initialization function
{
symbol_tablet::symbolst::iterator init_it=
symbol_table.symbols.find("c::__CPROVER_initialize");
if(init_it==symbol_table.symbols.end())
throw "failed to find __CPROVER_initialize symbol";
code_function_callt call_init;
call_init.lhs().make_nil();
call_init.add_source_location()=symbol.location;
call_init.function()=init_it->second.symbol_expr();
init_code.move_to_operands(call_init);
}
// build call to main function
code_function_callt call_main;
call_main.add_source_location()=symbol.location;
call_main.function()=symbol.symbol_expr();
call_main.function().add_source_location()=symbol.location;
const code_typet::parameterst ¶meters=
to_code_type(symbol.type).parameters();
if(symbol.name==standard_main)
{
if(parameters.size()==0)
{
// ok
}
else if(parameters.size()==2 || parameters.size()==3)
{
namespacet ns(symbol_table);
const symbolt &argc_symbol=ns.lookup("c::argc'");
const symbolt &argv_symbol=ns.lookup("c::argv'");
{
// assume argc is at least one
exprt one=from_integer(1, argc_symbol.type);
exprt ge(ID_ge, typet(ID_bool));
ge.copy_to_operands(argc_symbol.symbol_expr(), one);
codet assumption;
assumption.set_statement(ID_assume);
assumption.move_to_operands(ge);
init_code.move_to_operands(assumption);
}
{
// assume argc is at most MAX/8-1
mp_integer upper_bound=
power(2, config.ansi_c.int_width-4);
exprt bound_expr=from_integer(upper_bound, argc_symbol.type);
exprt le(ID_le, typet(ID_bool));
le.copy_to_operands(argc_symbol.symbol_expr(), bound_expr);
codet assumption;
assumption.set_statement(ID_assume);
assumption.move_to_operands(le);
init_code.move_to_operands(assumption);
}
if(parameters.size()==3)
{
const symbolt &envp_size_symbol=ns.lookup("c::envp_size'");
// assume envp_size is INTMAX-1
mp_integer max;
if(envp_size_symbol.type.id()==ID_signedbv)
{
max=to_signedbv_type(envp_size_symbol.type).largest();
}
else if(envp_size_symbol.type.id()==ID_unsignedbv)
{
max=to_unsignedbv_type(envp_size_symbol.type).largest();
}
else
assert(false);
exprt max_minus_one=from_integer(max-1, envp_size_symbol.type);
exprt le(ID_le, bool_typet());
le.copy_to_operands(envp_size_symbol.symbol_expr(), max_minus_one);
codet assumption;
assumption.set_statement(ID_assume);
assumption.move_to_operands(le);
init_code.move_to_operands(assumption);
}
{
/* zero_string doesn't work yet */
/*
exprt zero_string(ID_zero_string, array_typet());
zero_string.type().subtype()=char_type();
zero_string.type().set(ID_size, "infinity");
exprt index(ID_index, char_type());
index.copy_to_operands(zero_string, gen_zero(uint_type()));
exprt address_of("address_of", pointer_typet());
address_of.type().subtype()=char_type();
address_of.copy_to_operands(index);
if(argv_symbol.type.subtype()!=address_of.type())
address_of.make_typecast(argv_symbol.type.subtype());
// assign argv[*] to the address of a string-object
exprt array_of("array_of", argv_symbol.type);
array_of.copy_to_operands(address_of);
init_code.copy_to_operands(
code_assignt(argv_symbol.symbol_expr(), array_of));
*/
}
{
// assign argv[argc] to NULL
exprt null(ID_constant, argv_symbol.type.subtype());
null.set(ID_value, ID_NULL);
exprt index_expr(ID_index, argv_symbol.type.subtype());
index_expr.copy_to_operands(
argv_symbol.symbol_expr(),
argc_symbol.symbol_expr());
// disable bounds check on that one
index_expr.set("bounds_check", false);
init_code.copy_to_operands(code_assignt(index_expr, null));
}
if(parameters.size()==3)
{
const symbolt &envp_symbol=ns.lookup("c::envp'");
const symbolt &envp_size_symbol=ns.lookup("c::envp_size'");
// assume envp[envp_size] is NULL
exprt null(ID_constant, envp_symbol.type.subtype());
null.set(ID_value, ID_NULL);
exprt index_expr(ID_index, envp_symbol.type.subtype());
index_expr.copy_to_operands(
envp_symbol.symbol_expr(),
envp_size_symbol.symbol_expr());
// disable bounds check on that one
index_expr.set("bounds_check", false);
exprt is_null(ID_equal, typet(ID_bool));
is_null.copy_to_operands(index_expr, null);
codet assumption2;
assumption2.set_statement(ID_assume);
assumption2.move_to_operands(is_null);
init_code.move_to_operands(assumption2);
}
{
exprt::operandst &operands=call_main.arguments();
if(parameters.size()==3)
operands.resize(3);
else
operands.resize(2);
exprt &op0=operands[0];
exprt &op1=operands[1];
op0=argc_symbol.symbol_expr();
{
const exprt &arg1=parameters[1];
exprt index_expr(ID_index, arg1.type().subtype());
index_expr.copy_to_operands(argv_symbol.symbol_expr(), gen_zero(index_type()));
// disable bounds check on that one
index_expr.set("bounds_check", false);
op1=exprt(ID_address_of, arg1.type());
op1.move_to_operands(index_expr);
}
// do we need envp?
if(parameters.size()==3)
{
const symbolt &envp_symbol=ns.lookup("c::envp'");
exprt &op2=operands[2];
const exprt &arg2=parameters[2];
exprt index_expr(ID_index, arg2.type().subtype());
index_expr.copy_to_operands(
envp_symbol.symbol_expr(), gen_zero(index_type()));
op2=exprt(ID_address_of, arg2.type());
op2.move_to_operands(index_expr);
}
}
}
else
assert(false);
}
else
{
// produce nondet arguments
call_main.arguments()=build_function_environment(parameters);
}
init_code.move_to_operands(call_main);
// add "main"
symbolt new_symbol;
code_typet main_type;
main_type.return_type()=empty_typet();
new_symbol.name=ID_main;
new_symbol.type.swap(main_type);
new_symbol.value.swap(init_code);
if(symbol_table.move(new_symbol))
{
messaget message;
message.set_message_handler(message_handler);
message.error("failed to move main symbol");
return true;
}
return false;
}
| 26.624016 | 89 | 0.606802 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.