blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
9b6b0dbbe1bc91f30bc521b7e33b3659169cc98c
9cc082679768805040f9d7e239b25407adc92918
/MarXet/dialog/RscMarXetDefines.hpp
ec58c9cf62005822aae517ab2e384eff8a6b3c17
[]
no_license
3v5TCX/Exile.Tanoa
2a217c0b5d59915744459288b9ad1e877de9d055
1a239401c06ba3fc90d21598f7f59db8cfdc2e77
refs/heads/master
2023-01-08T07:22:53.008010
2020-11-11T10:30:43
2020-11-11T10:30:43
309,702,226
0
0
null
null
null
null
UTF-8
C++
false
false
21,063
hpp
/** * * Author: WolfkillArcadia * www.arcasindustries.com * © 2017 Arcas Industries * * This work is protected by Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (CC BY-NC-SA 4.0). * */ // Control types #define CT_STATIC 0 #define CT_BUTTON 1 #define CT_EDIT 2 #define CT_SLIDER 3 #define CT_COMBO 4 #define CT_LISTBOX 5 #define CT_TOOLBOX 6 #define CT_CHECKBOXES 7 #define CT_PROGRESS 8 #define CT_HTML 9 #define CT_STATIC_SKEW 10 #define CT_ACTIVETEXT 11 #define CT_TREE 12 #define CT_STRUCTURED_TEXT 13 #define CT_CONTEXT_MENU 14 #define CT_CONTROLS_GROUP 15 #define CT_SHORTCUTBUTTON 16 #define CT_XKEYDESC 40 #define CT_XBUTTON 41 #define CT_XLISTBOX 42 #define CT_XSLIDER 43 #define CT_XCOMBO 44 #define CT_ANIMATED_TEXTURE 45 #define CT_OBJECT 80 #define CT_OBJECT_ZOOM 81 #define CT_OBJECT_CONTAINER 82 #define CT_OBJECT_CONT_ANIM 83 #define CT_LINEBREAK 98 #define CT_USER 99 #define CT_MAP 100 #define CT_MAP_MAIN 101 #define CT_LISTNBOX 102 #define CT_CHECKBOX 77 // Static styles #define ST_POS 0x0F #define ST_HPOS 0x03 #define ST_VPOS 0x0C #define ST_LEFT 0x00 #define ST_RIGHT 0x01 #define ST_CENTER 0x02 #define ST_DOWN 0x04 #define ST_UP 0x08 #define ST_VCENTER 0x0C #define ST_TYPE 0xF0 #define ST_SINGLE 0x00 #define ST_MULTI 0x10 #define ST_TITLE_BAR 0x20 #define ST_PICTURE 0x30 #define ST_FRAME 0x40 #define ST_BACKGROUND 0x50 #define ST_GROUP_BOX 0x60 #define ST_GROUP_BOX2 0x70 #define ST_HUD_BACKGROUND 0x80 #define ST_TILE_PICTURE 0x90 #define ST_WITH_RECT 0xA0 #define ST_LINE 0xB0 #define ST_SHADOW 0x100 #define ST_NO_RECT 0x200 #define ST_KEEP_ASPECT_RATIO 0x800 #define ST_TITLE ST_TITLE_BAR + ST_CENTER // Slider styles #define SL_DIR 0x400 #define SL_VERT 0 #define SL_HORZ 0x400 #define SL_TEXTURES 0x10 // progress bar #define ST_VERTICAL 0x01 #define ST_HORIZONTAL 0 // Listbox styles #define LB_TEXTURES 0x10 #define LB_MULTI 0x20 // Tree styles #define TR_SHOWROOT 1 #define TR_AUTOCOLLAPSE 2 // MessageBox styles #define MB_BUTTON_OK 1 #define MB_BUTTON_CANCEL 2 #define MB_BUTTON_USER 4 /////////////////////////////////////////////////////////////////////////// /// Base Classes /////////////////////////////////////////////////////////////////////////// class RscMarXetText { deletable = 0; fade = 0; type = 0; idc = -1; colorBackground[] ={0,0,0,0}; colorText[] ={1,1,1,1}; text = ""; fixedWidth = 0; x = 0; y = 0; h = 0.037; w = 0.3; style = 0; shadow = 0; colorShadow[] ={0,0,0,0.5}; font = "OrbitronLight"; SizeEx = "(((((safezoneW / safezoneH) min 0.9) / 1.2) / 25) * 1)"; linespacing = 1; tooltipColorText[] ={1,1,1,1}; tooltipColorBox[] ={1,1,1,1}; tooltipColorShade[] ={0,0,0,0.65}; }; class RscMarXetStructuredText { deletable = 0; fade = 0; type = 13; idc = -1; style = 0; colorText[] ={1,1,1,1}; class Attributes { font = "PuristaMedium"; color = "#ffffff"; colorLink = "#D09B43"; align = "left"; shadow = 1; }; x = 0; y = 0; h = 0.035; w = 0.1; text = ""; size = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)"; shadow = 1; }; class RscMarXetPictureKeepAspect { colorBackground[] = {0,0,0,0}; colorText[] = {1,1,1,1}; deletable = 0; fade = 0; fixedWidth = 0; font = "TahomaB"; h = 0.15; idc = -1; linespacing = 0; shadow = 0; sizeEx = 0; style = "0x30 + 0x800"; text =""; tooltipColorBox[] = {1,1,1,1}; tooltipColorShade[] = {0,0,0,0.65}; tooltipColorText[] = {1,1,1,1}; type = 0; w = 0.2; x = 0; y = 0; }; class RscMarXetPicture { deletable = 0; fade = 0; type = 0; idc = -1; style = 48; colorBackground[] ={0,0,0,0}; colorText[] ={1,1,1,1}; font = "TahomaB"; sizeEx = 0; lineSpacing = 0; text = ""; fixedWidth = 0; shadow = 0; x = 0; y = 0; w = 0.2; h = 0.15; tooltipColorText[] ={1,1,1,1}; tooltipColorBox[] ={1,1,1,1}; tooltipColorShade[] ={0,0,0,0.65}; }; class RscMarXetEdit { deletable = 0; fade = 0; type = 2; x = 0; y = 0; h = 0.04; w = 0.2; colorBackground[] ={0,0,0,0}; colorText[] ={1,1,1,1}; colorDisabled[] ={1,1,1,0.5}; colorSelection[] = { "(profilenamespace getvariable ['GUI_BCG_RGB_R',0.77])", "(profilenamespace getvariable ['GUI_BCG_RGB_G',0.51])", "(profilenamespace getvariable ['GUI_BCG_RGB_B',0.08])", 1 }; autocomplete = ""; text = ""; size = 0.2; style = "0x00 + 0x40"; font = "OrbitronLight"; shadow = 2; sizeEx = "(((((safezoneW / safezoneH) min 1) / 1.2) / 25) * 1)"; canModify = 1; tooltipColorText[] = {1,1,1,1}; tooltipColorBox[] ={1,1,1,1}; tooltipColorShade[] ={0,0,0,0.65}; }; class RscMarXetCombo { deletable = 0; fade = 0; type = 4; colorSelect[] ={0,0,0,1}; colorText[] ={1,1,1,1}; colorBackground[] ={0,0,0,1}; colorScrollbar[] ={1,0,0,1}; colorDisabled[] ={1,1,1,0.25}; colorPicture[] ={1,1,1,1}; colorPictureSelected[] ={1,1,1,1}; colorPictureDisabled[] ={1,1,1,0.25}; colorPictureRight[] ={1,1,1,1}; colorPictureRightSelected[] ={1,1,1,1}; colorPictureRightDisabled[] ={1,1,1,0.25}; colorTextRight[] ={1,1,1,1}; colorSelectRight[] ={0,0,0,1}; colorSelect2Right[] ={0,0,0,1}; tooltipColorText[] ={1,1,1,1}; tooltipColorBox[] ={1,1,1,1}; tooltipColorShade[] ={0,0,0,0.65}; soundSelect[] = { "\A3\ui_f\data\sound\RscCombo\soundSelect", 0.1, 1 }; soundExpand[] = { "\A3\ui_f\data\sound\RscCombo\soundExpand", 0.1, 1 }; soundCollapse[] = { "\A3\ui_f\data\sound\RscCombo\soundCollapse", 0.1, 1 }; maxHistoryDelay = 1; class ComboScrollBar { color[] ={1,1,1,1}; }; style = "0x10 + 0x200"; font = "PuristaMedium"; sizeEx = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)"; shadow = 0; x = 0; y = 0; w = 0.12; h = 0.035; colorSelectBackground[] ={1,1,1,0.7}; arrowEmpty = ""; arrowFull = ""; wholeHeight = 0.45; colorActive[] ={1,0,0,1}; }; class RscMarXetListBox { deletable = 0; fade = 0; type = 5; rowHeight = 0; colorText[] ={1,1,1,1}; colorDisabled[] ={1,1,1,0.25}; colorScrollbar[] ={1,0,0,0}; colorSelect[] ={0,0.698,0.804,1}; colorSelect2[] ={0,0.698,0.804,1}; colorSelectBackground[] ={1,1,1,0.3}; colorSelectBackground2[] ={1,1,1,0.3}; colorBackground[] ={0,0,0,0.3}; soundSelect[] = { "\A3\ui_f\data\sound\RscListbox\soundSelect", 0.09, 1 }; autoScrollSpeed = -1; autoScrollDelay = 5; autoScrollRewind = 0; arrowEmpty = "#(argb,8,8,3)color(1,1,1,1)"; arrowFull = "#(argb,8,8,3)color(1,1,1,1)"; colorPicture[] ={0,0.698,0.804,1}; colorPictureSelected[] ={1,1,1,1}; colorPictureDisabled[] ={1,1,1,0.25}; colorPictureRight[] ={1,1,1,1}; colorPictureRightSelected[] ={1,1,1,1}; colorPictureRightDisabled[] ={1,1,1,0.25}; colorTextRight[] ={1,1,1,1}; colorSelectRight[] ={0,00,1}; colorSelect2Right[] ={0,0,0,1}; tooltipColorText[] ={1,1,1,1}; tooltipColorBox[] ={1,1,1,1}; tooltipColorShade[] ={0,0,0,0.65}; class ListScrollBar { color[] ={1,1,1,0.5}; autoScrollEnabled = 1; }; x = 0; y = 0; w = 0.3; h = 0.3; style = 16; font = "OrbitronLight"; sizeEx = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)"; shadow = 0; colorShadow[] ={0,0,0,0.5}; period = 1.2; maxHistoryDelay = 1; }; class RscExileMarXetItemListBox: RscMarXetListBox { sizeEx = "0.8 * ( ( ((safezoneW / safezoneH) min 1) / 1.2) / 25)"; sizeEx2 = "0.8 * ( ( ((safezoneW / safezoneH) min 1) / 1.2) / 25)"; rowHeight = "2 * ( ( ((safezoneW / safezoneH) min 1) / 1.2) / 25)"; canDrag = 0; itemSpacing = 0.001; period = 1.2; shadow = 0; maxHistoryDelay = 1; fade = 0; deletable = 0; type = 5; style = 16; colorSelect[] = {0, 0, 0, 1}; colorBackground[] = {0, 0, 0, 0.3}; colorDisabled[] = {1, 1, 1, 0.25}; colorPicture[] = {1, 1, 1, 1}; colorPictureDisabled[] = {1, 1, 1, 0.25}; colorPictureRight[] = {1, 1, 1, 1}; colorPictureRightDisabled[] = {1, 1, 1, 0.25}; colorPictureSelected[] = {1, 1, 1, 1}; colorScrollbar[] = {1, 0, 0, 0}; // yes, this is RED colorSelect2[] = {0, 0, 0, 1}; colorSelect2Right[] = {0, 0, 0, 1}; colorSelectBackground2[] = {1, 1, 1, 0.5}; colorSelectBackground[] = {0.95, 0.95, 0.95, 1}; colorSelectRight[] = {0, 0, 0, 1}; colorShadow[] = {0, 0, 0, 0.5}; colorText[] = {1, 1, 1, 1}; colorTextRight[] = {1, 1, 1, 1}; disabledCtrlColor[] = {1, 1, 1, 0.5}; itemBackground[] = {1, 1, 1, 0.1}; tooltipColorBox[] = {1, 1, 1, 1}; tooltipColorShade[] = {0, 0, 0, 0.65}; tooltipColorText[] = {1, 1, 1, 1}; soundSelect[] = { "\A3\ui_f\data\sound\RscListbox\soundSelect", 0.09, 1 }; class ListScrollBar { color[] ={1,1,1,0.5}; autoScrollEnabled = 1; }; font = "OrbitronLight"; }; class RscMarXetButton { deletable = 0; fade = 0; type = 1; text = ""; colorText[] ={1,1,1,1}; colorDisabled[] ={1,1,1,0.25}; colorBackground[] ={0,0,0,0.2}; colorBackgroundDisabled[] ={0,0,0,0.5}; colorBackgroundActive[] ={1,1,1,0.05}; colorFocused[] ={1,1,1,0}; colorShadow[] ={0,0,0,0}; colorBorder[] ={0,0,0,1}; soundEnter[] = { "\A3\ui_f\data\sound\RscButton\soundEnter", 0.09, 1 }; soundPush[] = { "\A3\ui_f\data\sound\RscButton\soundPush", 0.09, 1 }; soundClick[] = { "\A3\ui_f\data\sound\RscButton\soundClick", 0.09, 1 }; soundEscape[] = { "\A3\ui_f\data\sound\RscButton\soundEscape", 0.09, 1 }; style = 2; x = 0; y = 0; w = 0.095589; h = 0.039216; shadow = 2; font = "OrbitronLight"; sizeEx = "(((((safezoneW / safezoneH) min 1) / 1.2) / 25) * 1)"; offsetX = 0; offsetY = 0; offsetPressedX = 0; offsetPressedY = 0; borderSize = 0; }; class RscMarXetShortcutButton { deletable = 0; fade = 0; type = 16; x = 0.1; y = 0.1; class HitZone { left = 0; top = 0; right = 0; bottom = 0; }; class ShortcutPos { left = 0; top = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 20) - (((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)) / 2"; w = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1) * (3/4)"; h = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)"; }; class TextPos { left = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1) * (3/4)"; top = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 20) - (((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)) / 2"; right = 0.005; bottom = 0; }; shortcuts[] = { }; textureNoShortcut = "#(argb,8,8,3)color(0,0,0,0)"; color[] ={1,1,1,1}; colorFocused[] ={1,1,1,1}; color2[] ={0.95,0.95,0.95,1}; colorDisabled[] ={1,1,1,0.25}; colorBackground[] = { "(profilenamespace getvariable ['GUI_BCG_RGB_R',0.77])", "(profilenamespace getvariable ['GUI_BCG_RGB_G',0.51])", "(profilenamespace getvariable ['GUI_BCG_RGB_B',0.08])", 1 }; colorBackgroundFocused[] = { "(profilenamespace getvariable ['GUI_BCG_RGB_R',0.77])", "(profilenamespace getvariable ['GUI_BCG_RGB_G',0.51])", "(profilenamespace getvariable ['GUI_BCG_RGB_B',0.08])", 1 }; colorBackground2[] ={1,1,1,1}; soundEnter[] = { "\A3\ui_f\data\sound\RscButton\soundEnter", 0.09, 1 }; soundPush[] = { "\A3\ui_f\data\sound\RscButton\soundPush", 0.09, 1 }; soundClick[] = { "\A3\ui_f\data\sound\RscButton\soundClick", 0.09, 1 }; soundEscape[] = { "\A3\ui_f\data\sound\RscButton\soundEscape", 0.09, 1 }; class Attributes { font = "PuristaMedium"; color = "#E5E5E5"; align = "left"; shadow = "true"; }; idc = -1; style = 0; default = 0; shadow = 1; w = 0.183825; h = "((((safezoneW / safezoneH) min 1.2) / 1.2) / 20)"; textSecondary = ""; colorSecondary[] ={1,1,1,1}; colorFocusedSecondary[] ={1,1,1,1}; color2Secondary[] ={0.95,0.95,0.95,1}; colorDisabledSecondary[] ={1,1,1,0.25}; sizeExSecondary = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)"; fontSecondary = "PuristaMedium"; animTextureDefault = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\normal_ca.paa"; animTextureNormal = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\normal_ca.paa"; animTextureDisabled = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\normal_ca.paa"; animTextureOver = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\over_ca.paa"; animTextureFocused = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\focus_ca.paa"; animTexturePressed = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\down_ca.paa"; periodFocus = 1.2; periodOver = 0.8; period = 0.4; font = "PuristaMedium"; size = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)"; sizeEx = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)"; text = ""; action = ""; class AttributesImage { font = "PuristaMedium"; color = "#E5E5E5"; align = "left"; }; }; class RscMarXetShortcutButtonMain { idc = -1; style = 0; default = 0; w = 0.313726; h = 0.104575; color[] ={1,1,1,1}; colorDisabled[] ={1,1,1,0.25}; class HitZone { left = 0; top = 0; right = 0; bottom = 0; }; class ShortcutPos { left = 0.0145; top = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 20) - (((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1.2)) / 2"; w = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1.2) * (3/4)"; h = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1.2)"; }; class TextPos { left = "(((safezoneW / safezoneH) min 1.2) / 32) * 1.5"; top = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 20)*2 - (((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1.2)) / 2"; right = 0.005; bottom = 0; }; animTextureNormal = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButtonMain\normal_ca.paa"; animTextureDisabled = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButtonMain\disabled_ca.paa"; animTextureOver = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButtonMain\over_ca.paa"; animTextureFocused = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButtonMain\focus_ca.paa"; animTexturePressed = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButtonMain\down_ca.paa"; animTextureDefault = "\A3\ui_f\data\GUI\RscCommon\RscShortcutButtonMain\normal_ca.paa"; period = 0.5; font = "PuristaMedium"; size = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1.2)"; sizeEx = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1.2)"; text = ""; action = ""; class Attributes { font = "PuristaMedium"; color = "#E5E5E5"; align = "left"; shadow = "false"; }; class AttributesImage { font = "PuristaMedium"; color = "#E5E5E5"; align = "false"; }; }; class RscMarXetFrame { type = 0; idc = -1; style = 64; shadow = 2; colorBackground[] ={0,0,0,0}; colorText[] ={1,1,1,1}; font = "PuristaMedium"; sizeEx = 0.02; text = ""; x = 0; y = 0; w = 0.3; h = 0.3; }; class RscMarXetSlider { deletable = 0; fade = 0; type = 3; style = 1024; color[] ={1,1,1,0.8}; colorActive[] ={1,1,1,1}; shadow = 0; x = 0; y = 0; w = 0.3; h = 0.025; }; class MarXetIGUIBack { type = 0; idc = 124; style = 128; text = ""; colorText[] ={0,0,0,0}; font = "PuristaMedium"; sizeEx = 0; shadow = 0; x = 0.1; y = 0.1; w = 0.1; h = 0.1; colorbackground[] = { "(profilenamespace getvariable ['IGUI_BCG_RGB_R',0])", "(profilenamespace getvariable ['IGUI_BCG_RGB_G',1])", "(profilenamespace getvariable ['IGUI_BCG_RGB_B',1])", "(profilenamespace getvariable ['IGUI_BCG_RGB_A',0.8])" }; }; class RscMarXetCheckBox { idc = -1; type = 77; style = 0; checked = 0; x = "0.375 * safezoneW + safezoneX"; y = "0.36 * safezoneH + safezoneY"; w = "0.025 * safezoneW"; h = "0.04 * safezoneH"; color[] ={1,1,1,0.7}; colorFocused[] ={1,1,1,1}; colorHover[] ={1,1,1,1}; colorPressed[] ={1,1,1,1}; colorDisabled[] ={1,1,1,0.2}; colorBackground[] ={0,0,0,0}; colorBackgroundFocused[] ={0,0,0,0}; colorBackgroundHover[] ={0,0,0,0}; colorBackgroundPressed[] ={0,0,0,0}; colorBackgroundDisabled[] ={0,0,0,0}; textureChecked = "A3\Ui_f\data\GUI\RscCommon\RscCheckBox\CheckBox_checked_ca.paa"; textureUnchecked = "A3\Ui_f\data\GUI\RscCommon\RscCheckBox\CheckBox_unchecked_ca.paa"; textureFocusedChecked = "A3\Ui_f\data\GUI\RscCommon\RscCheckBox\CheckBox_checked_ca.paa"; textureFocusedUnchecked = "A3\Ui_f\data\GUI\RscCommon\RscCheckBox\CheckBox_unchecked_ca.paa"; textureHoverChecked = "A3\Ui_f\data\GUI\RscCommon\RscCheckBox\CheckBox_checked_ca.paa"; textureHoverUnchecked = "A3\Ui_f\data\GUI\RscCommon\RscCheckBox\CheckBox_unchecked_ca.paa"; texturePressedChecked = "A3\Ui_f\data\GUI\RscCommon\RscCheckBox\CheckBox_checked_ca.paa"; texturePressedUnchecked = "A3\Ui_f\data\GUI\RscCommon\RscCheckBox\CheckBox_unchecked_ca.paa"; textureDisabledChecked = "A3\Ui_f\data\GUI\RscCommon\RscCheckBox\CheckBox_checked_ca.paa"; textureDisabledUnchecked = "A3\Ui_f\data\GUI\RscCommon\RscCheckBox\CheckBox_unchecked_ca.paa"; tooltipColorText[] ={1,1,1,1}; tooltipColorBox[] ={1,1,1,1}; tooltipColorShade[] ={0,0,0,0.65}; soundEnter[] ={"",0.1,1}; soundPush[] ={"",0.1,1}; soundClick[] ={"",0.1,1}; soundEscape[] ={"",0.1,1}; }; class RscMarXetTextCheckBox { idc = -1; type = 7; style = 0; x = "0.375 * safezoneW + safezoneX"; y = "0.36 * safezoneH + safezoneY"; w = "0.025 * safezoneW"; h = "0.04 * safezoneH"; colorText[] ={1,0,0,1}; color[] ={0,0,0,0}; colorBackground[] ={0,0,0,0}; colorTextSelect[] ={0,0.8,0,1}; colorSelectedBg[] = { "(profilenamespace getvariable ['GUI_BCG_RGB_R',0.77])", "(profilenamespace getvariable ['GUI_BCG_RGB_G',0.51])", "(profilenamespace getvariable ['GUI_BCG_RGB_B',0.08])", 1 }; colorSelect[] ={0,0,0,1}; colorTextDisable[] ={0.4,0.4,0.4,1}; colorDisable[] ={0.4,0.4,0.4,1}; tooltipColorText[] ={1,1,1,1}; tooltipColorBox[] ={1,1,1,1}; tooltipColorShade[] ={0,0,0,0.65}; font = "PuristaMedium"; sizeEx = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 0.8)"; rows = 1; columns = 1; strings[] = { "UNCHECKED" }; checked_strings[] = { "CHECKED" }; }; class RscMarXetButtonMenu { idc = -1; type = 16; style = "0x02 + 0xC0"; default = 0; shadow = 0; x = 0; y = 0; w = 0.095589; h = 0.039216; animTextureNormal = "#(argb,8,8,3)color(1,1,1,1)"; animTextureDisabled = "#(argb,8,8,3)color(1,1,1,1)"; animTextureOver = "#(argb,8,8,3)color(1,1,1,1)"; animTextureFocused = "#(argb,8,8,3)color(1,1,1,1)"; animTexturePressed = "#(argb,8,8,3)color(1,1,1,1)"; animTextureDefault = "#(argb,8,8,3)color(1,1,1,1)"; colorBackground[] ={0,0,0,0.8}; colorBackgroundFocused[] ={1,1,1,1}; colorBackground2[] ={0.75,0.75,0.75,1}; color[] ={1,1,1,1}; colorFocused[] ={0,0,0,1}; color2[] ={0,0,0,1}; colorText[] ={1,1,1,1}; colorDisabled[] ={1,1,1,0.25}; textSecondary = ""; colorSecondary[] ={1,1,1,1}; colorFocusedSecondary[] ={0,0,0,1}; color2Secondary[] ={0,0,0,1}; colorDisabledSecondary[] ={1,1,1,0.25}; sizeExSecondary = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)"; fontSecondary = "PuristaLight"; period = 1.2; periodFocus = 1.2; periodOver = 1.2; size = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)"; sizeEx = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)"; tooltipColorText[] ={1,1,1,1}; tooltipColorBox[] ={1,1,1,1}; tooltipColorShade[] ={0,0,0,0.65}; class TextPos { left = "0.25 * (((safezoneW / safezoneH) min 1.2) / 40)"; top = "(((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) - (((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)) / 2"; right = 0.005; bottom = 0; }; class Attributes { font = "PuristaLight"; color = "#E5E5E5"; align = "left"; shadow = "false"; }; class ShortcutPos { left = "5.25 * (((safezoneW / safezoneH) min 1.2) / 40)"; top = 0; w = "1 * (((safezoneW / safezoneH) min 1.2) / 40)"; h = "1 * ((((safezoneW / safezoneH) min 1.2) / 1.2) / 25)"; }; soundEnter[] = { "\A3\ui_f\data\sound\RscButtonMenu\soundEnter", 0.09, 1 }; soundPush[] = { "\A3\ui_f\data\sound\RscButtonMenu\soundPush", 0.09, 1 }; soundClick[] = { "\A3\ui_f\data\sound\RscButtonMenu\soundClick", 0.09, 1 }; soundEscape[] = { "\A3\ui_f\data\sound\RscButtonMenu\soundEscape", 0.09, 1 }; }; class RscMarXetButtonMenuOK { idc = 1; shortcuts[] ={ "0x00050000 + 0", 28, 57, 156 }; default = 1; text = "OK"; soundPush[] = { "\A3\ui_f\data\sound\RscButtonMenuOK\soundPush", 0.09, 1 }; }; class RscMarXetButtonMenuCancel { idc = 2; shortcuts[] = { "0x00050000 + 1" }; text = "Cancel"; }; class RscMarXetControlsGroup { deletable = 0; fade = 0; class VScrollbar { color[] ={1,1,1,1}; width = 0.021; autoScrollEnabled = 1; }; class HScrollbar { color[] ={1,1,1,1}; height = 0.028; }; class Controls { }; type = 15; idc = -1; x = 0; y = 0; w = 1; h = 1; shadow = 0; style = 16; }; class RscMarXetProgress { type = 8; style = 0; colorFrame[] = {0,0,0,1}; colorBar[] = {0,0.698,0.804,1}; texture = "#(argb,8,8,3)color(1,1,1,1)"; w = 1; h = 0.03; };
[ "job@belonogov.com" ]
job@belonogov.com
f7df603e8223124eed44b6b2054c94bacb73129e
2d1f82fe5c4818ef1da82d911d0ed81a0b41ec85
/codeforces/R568/CF1185E.cpp
f7d18f19f0bc8119cb62b8bf1d8e4ba98e969536
[]
no_license
OrigenesZhang/-1s
d12bad12dee37d4bb168647d7b888e2e198e8e56
08a88e4bb84b67a44eead1b034a42f5338aad592
refs/heads/master
2020-12-31T00:43:17.972520
2020-12-23T14:56:38
2020-12-23T14:56:38
80,637,191
4
1
null
null
null
null
UTF-8
C++
false
false
2,340
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> pii; #define FOR(i, a, b) for (int (i) = (a); (i) <= (b); (i)++) #define ROF(i, a, b) for (int (i) = (a); (i) >= (b); (i)--) #define REP(i, n) FOR(i, 0, (n)-1) #define sqr(x) ((x) * (x)) #define all(x) (x).begin(), (x).end() #define reset(x, y) memset(x, y, sizeof(x)) #define uni(x) (x).erase(unique(all(x)), (x).end()) #define BUG(x) cerr << #x << " = " << (x) << endl #define pb push_back #define eb emplace_back #define mp make_pair #define _1 first #define _2 second #define chkmin(a, b) a = min(a, b) #define chkmax(a, b) a = max(a, b) const int maxn = 2123; int T, n, m; char mat[maxn][maxn], G[maxn][maxn]; vector<pii> tab[26], ans[26]; int main() { scanf("%d", &T); while (T--) { scanf("%d%d", &n, &m); FOR(i, 1, n) scanf("%s", mat[i] + 1); FOR(i, 1, n) FOR(j, 1, m) G[i][j] = '.'; REP(i, 26) { tab[i].clear(); ans[i].clear(); } int occ = -1; FOR(i, 1, n) FOR(j, 1, m) if (islower(mat[i][j])) { int idx = mat[i][j] - 'a'; chkmax(occ, idx); tab[idx].eb(i, j); } if (occ == -1) { puts("YES\n0"); continue; } auto fi = tab[occ].front(); bool good = true; ROF(idx, occ, 0) { sort(all(tab[idx])); if (tab[idx].empty()) ans[idx] = {fi, fi}; else if (tab[idx].size() == 1) { ans[idx] = {tab[idx][0], tab[idx][0]}; } else { if (tab[idx][0]._1 != tab[idx].back()._1 && tab[idx][0]._2 != tab[idx].back()._2) { good = false; break; } ans[idx] = {tab[idx][0], tab[idx].back()}; } } if (!good) { puts("NO"); continue; } REP(i, occ + 1) { int x1 = ans[i][0]._1, y1 = ans[i][0]._2, x2 = ans[i][1]._1, y2 = ans[i][1]._2; if (ans[i][0] == ans[i][1]) { G[x1][y1] = i + 'a'; continue; } if (x1 != x2) { FOR(j, x1, x2) G[j][y1] = i + 'a'; } else { FOR(j, y1, y2) G[x1][j] = i + 'a'; } } FOR(i, 1, n) FOR(j, 1, m) if (mat[i][j] != G[i][j]) { good = false; break; } puts(good ? "YES" : "NO"); if (good) { printf("%d\n", occ + 1); REP(i, occ + 1) printf("%d %d %d %d\n", ans[i][0]._1, ans[i][0]._2, ans[i][1]._1, ans[i][1]._2); } } }
[ "zhangbin199807@gmail.com" ]
zhangbin199807@gmail.com
00175e5728df124c3d869b2fa1e34ba872f51854
003d8fea3077ede86e4785411424a5acf622252f
/test/txpl/vm/scope_erase_test.cpp
bc4c98229c1994e0767e9357a3a7080daa342287
[ "BSL-1.0" ]
permissive
ptomulik/txpl
c43f961f160dcdee968fc214b5196b934a4ca514
109b5847abe0d46c598ada46f411f98ebe8dc4c8
refs/heads/master
2021-06-20T02:01:54.072229
2015-05-19T07:14:38
2015-05-19T07:14:38
31,542,106
0
0
null
null
null
null
UTF-8
C++
false
false
3,481
cpp
// Copyright (C) 2015, Pawel Tomulik <ptomulik@meil.pw.edu.pl> // // 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) #define BOOST_TEST_MODULE test_txpl_vm_scope_erase #include <txpl/test_config.hpp> #include <boost/test/unit_test.hpp> #ifndef TXPL_TEST_SKIP_VM_SCOPE_ERASE #include <txpl/vm/scope_erase.hpp> #include <txpl/vm/scope_find.hpp> #include <txpl/vm/scope_insert.hpp> #include <txpl/vm/value.hpp> #include <txpl/vm/basic_types.hpp> #include <boost/variant/get.hpp> #include <type_traits> struct error_handler { error_handler(std::string& msg) : msg(msg) { } void operator()(std::string const& msg) const { this->msg = msg; } std::string& msg; }; BOOST_AUTO_TEST_CASE(test__scope_erase) { using namespace txpl::vm; using boost::get; typedef basic_types<>::int_type int_type; std::string emsg; error_handler eh(emsg); { symbol<> sym; scope<> global; value<> v = int_type{10}; emsg = ""; BOOST_CHECK(scope_insert(global, "v0", v, eh)); BOOST_CHECK_EQUAL(emsg, ""); BOOST_CHECK(scope_erase(global, "v0", eh)); BOOST_CHECK_EQUAL(emsg, ""); BOOST_CHECK(!scope_find(global, "v0", sym, eh )); BOOST_CHECK_EQUAL(emsg, "v0 not found in global scope"); } { symbol<> sym; scope<> global; value<> v = int_type{10}; BOOST_CHECK(scope_insert(global, "ns1::v1", v, eh)); BOOST_CHECK(scope_insert(global, "ns1::ns2::v2", v, eh)); BOOST_CHECK(scope_insert(global, "ns1::ns2::ns3::v3", v, eh)); BOOST_CHECK(scope_find(global, "ns1::v1", sym, eh)); BOOST_CHECK(scope_find(global, "ns1::ns2", sym, eh)); BOOST_CHECK(scope_find(global, "ns1::ns2::v2", sym, eh)); BOOST_CHECK(scope_find(global, "ns1::ns2::ns3", sym, eh)); BOOST_CHECK(scope_find(global, "ns1::ns2::ns3::v3", sym, eh)); // Erase one element, and check what's left emsg = ""; BOOST_CHECK(scope_erase(global, "ns1::ns2::ns3::v3", eh)); BOOST_CHECK_EQUAL(emsg, ""); BOOST_CHECK(scope_find(global, "ns1::v1", sym, eh)); BOOST_CHECK(scope_find(global, "ns1::ns2", sym, eh)); BOOST_CHECK(scope_find(global, "ns1::ns2::v2", sym, eh)); BOOST_CHECK(scope_find(global, "ns1::ns2::ns3", sym, eh)); emsg = ""; BOOST_CHECK(!scope_find(global, "ns1::ns2::ns3::v3", sym, eh)); BOOST_CHECK_EQUAL(emsg, "v3 not found in ns1::ns2::ns3"); // Now it should return false emsg = ""; BOOST_CHECK(!scope_erase(global, "ns1::ns2::ns3::v3", eh)); BOOST_CHECK_EQUAL(emsg, "v3 not found in ns1::ns2::ns3"); // Erase another element, and check what's left emsg = ""; BOOST_CHECK(scope_erase(global, "ns1::ns2", eh)); BOOST_CHECK_EQUAL(emsg, ""); BOOST_CHECK(scope_find(global, "ns1", sym, eh)); BOOST_CHECK(scope_find(global, "ns1::v1", sym, eh)); emsg = ""; BOOST_CHECK(!scope_find(global, "ns1::ns2", sym, eh)); BOOST_CHECK_EQUAL(emsg, "ns2 not found in ns1"); emsg = ""; BOOST_CHECK(!scope_find(global, "ns1::ns2::v2", sym, eh)); BOOST_CHECK_EQUAL(emsg, "ns2 not found in ns1"); emsg = ""; BOOST_CHECK(!scope_find(global, "ns1::ns2::ns3", sym, eh)); BOOST_CHECK_EQUAL(emsg, "ns2 not found in ns1"); emsg = ""; BOOST_CHECK(!scope_find(global, "ns1::ns2::ns3::v3", sym, eh)); BOOST_CHECK_EQUAL(emsg, "ns2 not found in ns1"); } } #else BOOST_AUTO_TEST_CASE(dummy) { BOOST_CHECK(true); } #endif
[ "ptomulik@meil.pw.edu.pl" ]
ptomulik@meil.pw.edu.pl
a34ba1add309077bbf28c0c1a3714ea6580fdab6
a5a00baf0b6bad26f6c2052d8df83a994250e9fd
/mapreduce/ImageReduce.hpp
f6718903215b7ec370bc26ea32f84a717d13e721
[ "Apache-2.0" ]
permissive
i4s/ssodc
e673eafe3b97fa7ff0a1277058542dc7f8d6c8b5
24f7c383eaf8eb5e799f55c6a2da6fdd1b47ea99
refs/heads/master
2021-01-21T04:47:37.443561
2016-06-10T20:38:42
2016-06-10T20:43:31
53,934,357
0
2
null
null
null
null
UTF-8
C++
false
false
422
hpp
#pragma once #include <string> #include "ReduceInterface.hpp" namespace ssodc { namespace mapreduce { class ImageReduce : public ReduceInterface { public: ImageReduce(std::map<int, std::string>&); ~ImageReduce(); int Reducing(); std::string GetProcessedData(); private: std::string m_processedData; std::map<int, std::string> m_partPath; }; } /* namespace mapreduce */ } /* namespace ssodc */
[ "zhurko.e96@gmail.com" ]
zhurko.e96@gmail.com
89d7e4bca5dc35b3050abcd46598ccd455d59521
08afc231bdf071b1675ba19bced63e0cca404a0c
/src/keepass.h
87a232126f33b9fca7e70e78edbf4b24e6c5af37
[ "MIT" ]
permissive
novaexchange/ULM
aa3fbb3c0ae8c1b5fdf0c67dd7d7d98dfec37b5e
3e4bac481cd1f3c478b3dd2e112988c2ef14dd87
refs/heads/master
2021-01-23T13:16:36.995571
2017-06-03T10:01:59
2017-06-03T10:01:59
93,238,949
0
1
null
2017-09-02T22:09:31
2017-06-03T09:42:44
C++
UTF-8
C++
false
false
3,590
h
// Copyright (c) 2014-2017 The Ulm Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef _KEEPASS_H_ #define _KEEPASS_H_ #include "support/allocators/secure.h" #include <univalue.h> class CKeePassIntegrator; static const unsigned int DEFAULT_KEEPASS_HTTP_PORT = 19455; extern CKeePassIntegrator keePassInt; class CKeePassIntegrator { private: static const int KEEPASS_CRYPTO_KEY_SIZE = 32; static const int KEEPASS_CRYPTO_BLOCK_SIZE = 16; static const int KEEPASS_HTTP_CONNECT_TIMEOUT = 30; static const char* KEEPASS_HTTP_HOST; bool bIsActive; unsigned int nPort; SecureString sKeyBase64; SecureString sKey; SecureString sUrl; //SecureString sSubmitUrl; std::string strKeePassId; std::string strKeePassEntryName; class CKeePassRequest { UniValue requestObj; std::string strType; std::string strIV; SecureString sKey; void init(); public: void addStrParameter(std::string strName, std::string strValue); // Regular void addStrParameter(std::string strName, SecureString sValue); // Encrypt std::string getJson(); CKeePassRequest(SecureString sKey, std::string strType) { this->sKey = sKey; this->strType = strType; init(); }; }; class CKeePassEntry { SecureString sUuid; SecureString sName; SecureString sLogin; SecureString sPassword; public: CKeePassEntry(SecureString sUuid, SecureString sName, SecureString sLogin, SecureString sPassword) : sUuid(sUuid), sName(sName), sLogin(sLogin), sPassword(sPassword) { } SecureString getUuid() { return sUuid; } SecureString getName() { return sName; } SecureString getLogin() { return sLogin; } SecureString getPassword() { return sPassword; } }; class CKeePassResponse { bool bSuccess; std::string strType; std::string strIV; SecureString sKey; void parseResponse(std::string strResponse); public: UniValue responseObj; CKeePassResponse(SecureString sKey, std::string strResponse) { this->sKey = sKey; parseResponse(strResponse); } bool getSuccess() { return bSuccess; } SecureString getSecureStr(std::string strName); std::string getStr(std::string strName); std::vector<CKeePassEntry> getEntries(); SecureString decrypt(std::string strValue); // DecodeBase64 and decrypt arbitrary string value }; static SecureString generateRandomKey(size_t nSize); static std::string constructHTTPPost(const std::string& strMsg, const std::map<std::string,std::string>& mapRequestHeaders); void doHTTPPost(const std::string& strRequest, int& nStatus, std::string& strResponse); void rpcTestAssociation(bool bTriggerUnlock); std::vector<CKeePassEntry> rpcGetLogins(); void rpcSetLogin(const SecureString& sWalletPass, const SecureString& sEntryId); public: CKeePassIntegrator(); void init(); static SecureString generateKeePassKey(); void rpcAssociate(std::string& strId, SecureString& sKeyBase64); SecureString retrievePassphrase(); void updatePassphrase(const SecureString& sWalletPassphrase); }; #endif
[ "hiksecure@sfr.fr" ]
hiksecure@sfr.fr
8d8c84b5da4600dcc61892602fb390da4fd2c277
7f10acf84f452799362b982d89fb7cb76d41fdbc
/Plugins/AdvancedSessions/Intermediate/Build/Win64/UE4/Development/AdvancedSessions/Module.AdvancedSessions.cpp
110281cd1a59404310a4b3e0a7712c75eb6a55b4
[]
no_license
PojectPN/ShooterGame
97299b91c50a865a620180697a215902bb564661
c7a4d5eac8c75e2add1b619d04e0e21e979c8ed7
refs/heads/master
2021-07-18T12:26:01.227464
2017-10-25T13:15:20
2017-10-25T13:15:20
105,905,480
0
0
null
null
null
null
UTF-8
C++
false
false
3,530
cpp
// This file is automatically generated at compile-time to include some subset of the user-created cpp files. #include "C:\Users\paul-\Documents\Unreal Projects\FPSGame\NewShooter\ShooterGame\Plugins\AdvancedSessions\Source\AdvancedSessions\Private\AdvancedExternalUILibrary.cpp" #include "C:\Users\paul-\Documents\Unreal Projects\FPSGame\NewShooter\ShooterGame\Plugins\AdvancedSessions\Source\AdvancedSessions\Private\AdvancedFriendsGameInstance.cpp" #include "C:\Users\paul-\Documents\Unreal Projects\FPSGame\NewShooter\ShooterGame\Plugins\AdvancedSessions\Source\AdvancedSessions\Private\AdvancedFriendsInterface.cpp" #include "C:\Users\paul-\Documents\Unreal Projects\FPSGame\NewShooter\ShooterGame\Plugins\AdvancedSessions\Source\AdvancedSessions\Private\AdvancedFriendsLibrary.cpp" #include "C:\Users\paul-\Documents\Unreal Projects\FPSGame\NewShooter\ShooterGame\Plugins\AdvancedSessions\Source\AdvancedSessions\Private\AdvancedIdentityLibrary.cpp" #include "C:\Users\paul-\Documents\Unreal Projects\FPSGame\NewShooter\ShooterGame\Plugins\AdvancedSessions\Source\AdvancedSessions\Private\AdvancedSessions.cpp" #include "C:\Users\paul-\Documents\Unreal Projects\FPSGame\NewShooter\ShooterGame\Plugins\AdvancedSessions\Source\AdvancedSessions\Private\AdvancedSessionsLibrary.cpp" #include "C:\Users\paul-\Documents\Unreal Projects\FPSGame\NewShooter\ShooterGame\Plugins\AdvancedSessions\Source\AdvancedSessions\Private\AdvancedVoiceLibrary.cpp" #include "C:\Users\paul-\Documents\Unreal Projects\FPSGame\NewShooter\ShooterGame\Plugins\AdvancedSessions\Source\AdvancedSessions\Private\CancelFindSessionsCallbackProxy.cpp" #include "C:\Users\paul-\Documents\Unreal Projects\FPSGame\NewShooter\ShooterGame\Plugins\AdvancedSessions\Source\AdvancedSessions\Private\CreateSessionCallbackProxyAdvanced.cpp" #include "C:\Users\paul-\Documents\Unreal Projects\FPSGame\NewShooter\ShooterGame\Plugins\AdvancedSessions\Source\AdvancedSessions\Private\EndSessionCallbackProxy.cpp" #include "C:\Users\paul-\Documents\Unreal Projects\FPSGame\NewShooter\ShooterGame\Plugins\AdvancedSessions\Source\AdvancedSessions\Private\FindFriendSessionCallbackProxy.cpp" #include "C:\Users\paul-\Documents\Unreal Projects\FPSGame\NewShooter\ShooterGame\Plugins\AdvancedSessions\Source\AdvancedSessions\Private\FindSessionsCallbackProxyAdvanced.cpp" #include "C:\Users\paul-\Documents\Unreal Projects\FPSGame\NewShooter\ShooterGame\Plugins\AdvancedSessions\Source\AdvancedSessions\Private\GetFriendsCallbackProxy.cpp" #include "C:\Users\paul-\Documents\Unreal Projects\FPSGame\NewShooter\ShooterGame\Plugins\AdvancedSessions\Source\AdvancedSessions\Private\GetRecentPlayersCallbackProxy.cpp" #include "C:\Users\paul-\Documents\Unreal Projects\FPSGame\NewShooter\ShooterGame\Plugins\AdvancedSessions\Source\AdvancedSessions\Private\GetUserPrivilegeCallbackProxy.cpp" #include "C:\Users\paul-\Documents\Unreal Projects\FPSGame\NewShooter\ShooterGame\Plugins\AdvancedSessions\Source\AdvancedSessions\Private\LoginUserCallbackProxy.cpp" #include "C:\Users\paul-\Documents\Unreal Projects\FPSGame\NewShooter\ShooterGame\Plugins\AdvancedSessions\Source\AdvancedSessions\Private\LogoutUserCallbackProxy.cpp" #include "C:\Users\paul-\Documents\Unreal Projects\FPSGame\NewShooter\ShooterGame\Plugins\AdvancedSessions\Source\AdvancedSessions\Private\SendFriendInviteCallbackProxy.cpp" #include "C:\Users\paul-\Documents\Unreal Projects\FPSGame\NewShooter\ShooterGame\Plugins\AdvancedSessions\Source\AdvancedSessions\Private\UpdateSessionCallbackProxyAdvanced.cpp"
[ "BlaZZor04@users.noreply.github.com" ]
BlaZZor04@users.noreply.github.com
b68890393136969c6d7708d7c878c6d025ba8795
3cd73f433c73c2872815041998c32684543faf6f
/myPrograms/nameGreater.cpp
50512df887225296ca3c63dd7c1c0f8ba32bc9db
[]
no_license
kjp148/keananpaul-CSCI20-Fall2016
fe804421c84abbad5ea03d765dc97f408f4e4b12
72579c60f9e506162b447c39ce66a45bd7e83118
refs/heads/master
2020-09-22T06:53:36.819007
2016-12-13T07:34:41
2016-12-13T07:34:41
66,402,759
0
0
null
null
null
null
UTF-8
C++
false
false
245
cpp
#include <iostream> #include <fstream> #include <string> using namespace std; int main() { string myName = "Elizabeth"; string yourName = "Gabrielle"; if (myName > yourName) { cout << "My name is greater"; } else { cout << "You suck"; } }
[ "kpaul006@student.butte.edu" ]
kpaul006@student.butte.edu
de63d7f30721f6db2f8d3d8b08234e9e93b0106d
f3e813535f75fb461e2306f1ad18596ac233e758
/odb_api_bundle-0.17.6-Source/odb_api/src/odb_api/DataColumns.h
244c56e06ac2ff70d344d7858dadcc4d8b4beccb
[ "Apache-2.0" ]
permissive
vyesubabu/metview
47f9de3eb5f1bf418e513ed306aa2279635b79c7
74c2b9bc28673001fd02e00194e92c53a897fb62
refs/heads/master
2021-05-17T16:42:41.697859
2018-04-09T15:08:19
2018-04-09T15:08:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,646
h
/// @file DataColumns.h /// @author Tomas Kral #ifndef ODBLIB_DATACOLUMNS_H_ #define ODBLIB_DATACOLUMNS_H_ #include "odb_api/DataColumn.h" namespace odb { class MetaData; } namespace odb { /*! Represents a collection of table columns. * * The DataColumns class defines a schema of a DataTable. You can access * the DataColumns through the @ref DataTable::columns "columns()" * method of a DataTable class. * * @ingroup data */ class DataColumns : private std::vector<DataColumn> { public: using std::vector<DataColumn>::push_back; using std::vector<DataColumn>::size; using std::vector<DataColumn>::empty; using std::vector<DataColumn>::begin; using std::vector<DataColumn>::end; using std::vector<DataColumn>::clear; using std::vector<DataColumn>::operator[]; using std::vector<DataColumn>::operator=; /// Iterates through columns in the collection. typedef std::vector<DataColumn>::iterator iterator; /// Iterates through columns in the collection (const version). typedef std::vector<DataColumn>::const_iterator const_iterator; /// Creates a new empty collection of columns. DataColumns(); /// Creates and populates a new collection of columns. DataColumns(const odb::MetaData& metadata); /// Creates and populates a new collection of columns. DataColumns(const DataColumns& other); /// Destroys the collection. ~DataColumns(); /// Returns column of the given name. DataColumn& operator[](const std::string& name) { return (*this)[indexOf(name)]; } /// Returns column of the given name (const overload). const DataColumn& operator[](const std::string& name) const { return (*this)[indexOf(name)]; } /// Returns joined collection of the current and the @p other collection. DataColumns operator+(const DataColumns& other) const; /// Adds columns from the @p other collection to the current one. DataColumns& operator+=(const DataColumns& other); /// Compares two column collections. /// Returns @c true if the two column collections contains the same columns. bool operator==(const DataColumns& other) const; /// Returns index of the column given its name. size_t indexOf(const std::string& name) const; /// Adds a new column of the given name and type into the collection. void add(const std::string& name, const std::string& type); /// Assigns columns from ODB metadata. /// This method is provided for inter-operability with ODB library. DataColumns& operator=(const odb::MetaData& metadata); }; } // namespace odb #endif // ODBLIB_DATACOLUMNS_H_
[ "Xin.L.Zhang@noaa.gov" ]
Xin.L.Zhang@noaa.gov
a2ca3859b91ec82226f436fc613e68b6d7ad907f
778c8350f9a57c0ea52bf692ca3607e413967c69
/Advance Programing 1/Passenger.cpp
2607e2db0bf186e7ecd8ec704f66fd7a8ad80419
[]
no_license
amirlic/advance-program-1
5b69dbd808a79f43bb353001ba54b47cb5093f33
aa32069f3206bac56d0ea9e3787daa7f46ed1dc5
refs/heads/master
2021-05-06T16:19:47.427150
2017-12-09T18:35:06
2017-12-09T18:35:06
113,690,692
0
0
null
null
null
null
UTF-8
C++
false
false
407
cpp
//this class is used to indicate a cab's passenger #include "Passenger.h" Point Passenger::getSource() { return this->source; } Point Passenger::getDestination() { return this->destination; } int Passenger::giveStisfaction() { return 0; } Passenger::Passenger(Point s, Point d) { this->source = s; this->destination = d; } Passenger::Passenger() { } Passenger::~Passenger() { }
[ "noreply@github.com" ]
noreply@github.com
28e536d9649d197ce3044c47da6491759c82d451
9e02c151f257584592d7374b0045196a3fd2cf53
/AtCoder/practice/welcome.cpp
d8f66498a8c54b3dfe9fd95940783f22924829ea
[]
no_license
robertcal/cpp_competitive_programming
891c97f315714a6b1fc811f65f6be361eb642ef2
0bf5302f1fb2aa8f8ec352d83fa6281f73dec9b5
refs/heads/master
2021-12-13T18:12:31.930186
2021-09-29T00:24:09
2021-09-29T00:24:09
173,748,291
0
0
null
null
null
null
UTF-8
C++
false
false
186
cpp
#include <iostream> using namespace std; int main() { int a, b, c; string s; cin >> a >> b >> c; cin >> s; cout << a + b + c << " " << s << endl; return 0; }
[ "robertcal900@gmail.com" ]
robertcal900@gmail.com
976f619d2d5e4ed4f65de6e13e26d50f3e18a4bf
1bd1b87e3ca999550665982355ba3b14f2e5d9c0
/Solved Again/LeetCode/Top Interview Questions/Easy/Array/Plus One.cpp
8617c9dcacf9dc21dd4b5e22bb24463c495ee327
[]
no_license
HMarsafy/Problem-Solving
8dc65c51f07e0a3a2d7f9b5a7cf0f54b09408a71
c0cd3720e4bc86ef7b67e22cae901e7e32be5de9
refs/heads/main
2023-05-12T23:01:06.139822
2023-05-07T14:00:34
2023-05-07T14:00:34
215,096,954
0
0
null
null
null
null
UTF-8
C++
false
false
772
cpp
vector<int> plusOne(vector<int>& digits) { int last = digits.size() - 1 ; if(digits[last] != 9) { digits[last] ++ ; //return digits; } else { int count = 0 ; while(last >= 0 && (digits[last]) == 9 ) { count++; last--; } if(count == digits.size()) { vector<int> out((count+1),0); out[0] = 1 ; return out; } else { digits[last]++; while(count--) { digits[++last] = 0; } } } return digits; }
[ "noreply@github.com" ]
noreply@github.com
bf8bb46c7262bb12cf95a5863cd36e08cfc78251
76aab74b58991e2cf8076d6b4ed6f4deba1c57bd
/Atcoder/abc125c.cpp
fb1fc893a4ff512d24a4153790774af9ad12630c
[]
no_license
StudyingFather/my-code
9c109660c16b18f9974d37a2a1d809db4d6ce50a
8d02be445ac7affad58c2d71f3ef602f3d2801f6
refs/heads/master
2023-08-16T23:17:10.817659
2023-08-04T11:31:40
2023-08-04T11:31:40
149,898,152
6
2
null
null
null
null
UTF-8
C++
false
false
468
cpp
#include <cstdio> #include <algorithm> using namespace std; int a[100005],pre[100005],post[100005]; int gcd(int a,int b) { return b==0?a:gcd(b,a%b); } int main() { int n,ans=1; scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%d",&a[i]); pre[1]=a[1],post[n]=a[n]; for(int i=1;i<=n;i++) pre[i]=gcd(pre[i-1],a[i]); for(int i=n-1;i;i--) post[i]=gcd(post[i+1],a[i]); for(int i=1;i<=n;i++) ans=max(ans,gcd(pre[i-1],post[i+1])); printf("%d\n",ans); return 0; }
[ "594422141@qq.com" ]
594422141@qq.com
3edf58a56d0334d2c970fe6a7cdf39ed1404d438
30667f904bf553424e56364263e9923b5f42d74d
/PowerBook/Rect.cpp
6d5d0bd4083227bef6c385af33356716bea0da5d
[]
no_license
bb2002/CPPStudyProjects
037ae0a2b8a4f89a9725845989a1f00921b018cd
2569dbb9e4a1c2acfbe67fcce20304b5094f79a3
refs/heads/master
2020-04-29T06:05:51.377024
2019-03-15T23:54:07
2019-03-15T23:54:07
175,904,985
0
0
null
null
null
null
UHC
C++
false
false
463
cpp
#include "pch.h" #include<iostream> #include "Rect.h" using namespace std; Rect::Rect(const Point & ul, const Point & lr) { if (ul.GetX() > lr.GetX() || ul.GetY() > lr.GetY()) { cout << "Error. Out of range" << endl; } this->upLeft = ul; this->lowRight = lr; } void Rect::ShowRectInfo() const { cout << "좌 상당 : " << upLeft.GetX() << ", " << upLeft.GetY() << endl; cout << "우 하단 : " << lowRight.GetX() << ", " << lowRight.GetY() << endl; }
[ "5252bb@daum.net" ]
5252bb@daum.net
9ab6f2f7d38b8be6f567663281f88dc855541eea
51faca0ffd1c452a427e551cd8c528a4ac80fc75
/vg/fd/contest/3/F.cpp
88f22f9cd315d7763c5e9327fa067c880b0430b0
[]
no_license
xLLLxLLLx/xLLLx
37f4127a34374b27f14fe856d854c9a13a9b2e28
7ec2ddf39d903c0cdfd52268edd44b2ccbe7e73b
refs/heads/master
2020-04-18T16:19:24.099657
2019-11-03T05:11:41
2019-11-03T05:11:41
167,631,326
4
0
null
null
null
null
UTF-8
C++
false
false
1,205
cpp
#include<bits/stdc++.h> #define fr(i,x,y) for(int i=x;i<=y;++i) #define rf(i,x,y) for(int i=x;i>=y;--i) #define db double #define LL long long using namespace std; const int N=55; struct data{ LL a,b; }qx[N]; LL f[N][N]; int n; bool cmp(data xx,data yy){ if(xx.a!=yy.a) return xx.a>yy.a; else return xx.b<yy.b; } LL Min(LL &x,LL y){ x=min(x,y); } bool check(LL x){ int lt=1; memset(f,0x3f,sizeof f); f[0][0]=0; fr(i,1,n){ lt=i; while(lt+1<=n&&qx[i].a==qx[lt+1].a) lt++; fr(k,0,i-1) fr(t,0,min(lt-i+1,k)){ fr(j,i,i+t-1) Min(f[j][k-(j-i+1)],f[i-1][k]); LL sum=0; fr(j,i+t,lt){ sum+=qx[j].a-x*qx[j].b; int pos=k-t+(j-(i+t)+1); // if(j==5&&pos==1) cout<<"sum="<<sum<<endl; Min(f[j][pos],f[i-1][k]+sum); } } i=lt; } // fr(i,1,n) fr(j,0,i) printf("f[%d][%d]=%lf\n",i,j,f[i][j]); fr(i,0,n) if(f[n][i]<=0) return 1; return 0; } int main(){ scanf("%d",&n); fr(i,1,n) scanf("%lld",&qx[i].a),qx[i].a*=1000; fr(i,1,n) scanf("%lld",&qx[i].b),qx[i].b; sort(qx+1,qx+1+n,cmp); // fr(i,1,n) cout<<qx[i].a<<" "<<qx[i].b<<endl; LL l=0,r=1e13,ans=-1; while(l<=r){ db mid=(l+r)>>1; if(check(mid)) ans=mid,r=mid-1; else l=mid+1; } cout<<ans<<endl; return 0; }
[ "pysxlqp@163.com" ]
pysxlqp@163.com
081273aa992eeb50ebb39a9314fc9b7423b1299d
9d9c217d265515738bd2889cf7512d796169c243
/Problems/Codeforces/Gym/101353/C/main.cpp
632ef3686dbb34a8577b38012d583324668ab493
[]
no_license
Evalir/Algorithms
f4d70f6b5cb7a20b5304a8543dd9dd443d2e7d7d
c58507d9f79eb388dd98b8e22302598eb29876e0
refs/heads/master
2021-07-08T16:52:15.820629
2019-09-21T23:45:52
2019-09-21T23:45:52
99,495,180
0
0
null
2017-10-24T22:07:37
2017-08-06T15:20:17
Makefile
UTF-8
C++
false
false
2,160
cpp
#include <bits/stdc++.h> using namespace std; using Long = long long; using pii = pair<int,int>; const int MOD = 1000000001; bool isPrime[2000010]; vector<int> Primes; Long gcd (Long n1, Long n2) { return (n2 == 0) ? n1 : gcd (n2, n1 % n2); } void Sieve() { for(int i = 2; i <= 10000; i++) { if(!isPrime[i]) { Primes.push_back(i); for(int j = i + i; j <= 10000; j += i) { isPrime[j] = true; } } } } int ff(Long x, Long p) { int k = 0; while(x % p == 0) { x /= p; k++; } return k; } int main() { Sieve(); int n; scanf("%d", &n); if (n == 1) { Long x; scanf("%lld", &x); printf("%lld\n", (x % MOD)); } else if (n == 2) { Long x,y; scanf("%lld%lld", &x,&y); Long k = gcd(x,y); printf("%lld\n", (((x/k) % MOD) * ((y/k) % MOD)) % MOD); } else if (n == 3) { Long x, y, z; scanf("%lld%lld%lld", &x,&y,&z); Long gA = gcd(gcd(x,y),z); x /= gA, y /= gA, z /= gA; Long g1 = gcd(x,y); x /= g1, y /= g1; Long g2 = gcd(y,z); y /= g2, z /= g2; Long g3 = gcd(x,z); x /= g3, z /= g3; x %= MOD, y %= MOD, z %= MOD; printf("%lld\n", (x*y*z) % MOD); } else { vector<Long> V(n); for(auto &t : V) scanf("%lld", &t); Long ans = 1LL; for(int i = 0; Primes[i] < 1010 && i < Primes.size(); i++) { pii maxPowers = {0,0}; for(int j = 0; j < n; j++) { if (V[j] % Primes[i] == 0) { int k = ff(V[j],Primes[i]); V[j] /= pow(Primes[i],k); if (maxPowers.first <= k) { maxPowers.second = maxPowers.first; maxPowers.first = k; } } } Long mx = maxPowers.first-maxPowers.second; for(int j = 1; j <= (mx); j++) { ans *= Primes[i] % MOD; ans %= MOD; } } printf("%lld\n", ans); } return 0; }
[ "hi.evalir@gmail.com" ]
hi.evalir@gmail.com
2402842e179dda4b387f4e702d736297f7f50e43
948f4e13af6b3014582909cc6d762606f2a43365
/testcases/juliet_test_suite/testcases/CWE121_Stack_Based_Buffer_Overflow/s02/CWE121_Stack_Based_Buffer_Overflow__CWE193_char_alloca_memcpy_72b.cpp
fd1a66fa29630770b0b7a1bd71c3e23ecfcb9a38
[]
no_license
junxzm1990/ASAN--
0056a341b8537142e10373c8417f27d7825ad89b
ca96e46422407a55bed4aa551a6ad28ec1eeef4e
refs/heads/master
2022-08-02T15:38:56.286555
2022-06-16T22:19:54
2022-06-16T22:19:54
408,238,453
74
13
null
2022-06-16T22:19:55
2021-09-19T21:14:59
null
UTF-8
C++
false
false
1,933
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE121_Stack_Based_Buffer_Overflow__CWE193_char_alloca_memcpy_72b.cpp Label Definition File: CWE121_Stack_Based_Buffer_Overflow__CWE193.label.xml Template File: sources-sink-72b.tmpl.cpp */ /* * @description * CWE: 121 Stack Based Buffer Overflow * BadSource: Point data to a buffer that does not have space for a NULL terminator * GoodSource: Point data to a buffer that includes space for a NULL terminator * Sinks: memcpy * BadSink : Copy string to data using memcpy() * Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files * * */ #include "std_testcase.h" #include <vector> #ifndef _WIN32 #include <wchar.h> #endif /* MAINTENANCE NOTE: The length of this string should equal the 10 */ #define SRC_STRING "AAAAAAAAAA" using namespace std; namespace CWE121_Stack_Based_Buffer_Overflow__CWE193_char_alloca_memcpy_72 { #ifndef OMITBAD void badSink(vector<char *> dataVector) { /* copy data out of dataVector */ char * data = dataVector[2]; { char source[10+1] = SRC_STRING; /* Copy length + 1 to include NUL terminator from source */ /* POTENTIAL FLAW: data may not have enough space to hold source */ memcpy(data, source, (strlen(source) + 1) * sizeof(char)); printLine(data); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(vector<char *> dataVector) { char * data = dataVector[2]; { char source[10+1] = SRC_STRING; /* Copy length + 1 to include NUL terminator from source */ /* POTENTIAL FLAW: data may not have enough space to hold source */ memcpy(data, source, (strlen(source) + 1) * sizeof(char)); printLine(data); } } #endif /* OMITGOOD */ } /* close namespace */
[ "yzhang0701@gmail.com" ]
yzhang0701@gmail.com
6daf5953c5f14e38281ea9ea13b6fe3ce12a1322
41371839eaa16ada179d580f7b2c1878600b718e
/UVa/Volume I/00101.cpp
8cd7cc6cd347830c5267f5a699613eb84dfffd32
[]
no_license
marinvhs/SMAS
5481aecaaea859d123077417c9ee9f90e36cc721
2241dc612a653a885cf9c1565d3ca2010a6201b0
refs/heads/master
2021-01-22T16:31:03.431389
2009-10-01T02:33:01
2009-10-01T02:33:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,960
cpp
///////////////////////////////// // 00101 - The Blocks Problem ///////////////////////////////// #include<cstdio> #include<cstring> int nBlock; struct block{ int v,pile; struct block*abo; struct block*bel; }; void goBack(block *a){ if(a == NULL) return; goBack(a->abo); a->bel->abo = NULL; a->bel = NULL; a->pile = a->v; } void moveOnto(block *a, block *b){ if(a->bel!=NULL) a->bel->abo = NULL; goBack(a->abo); goBack(b->abo); b->abo = a; a->pile = b->pile; a->bel = b; } void moveOver(block *a, block *b){ if(a->bel!=NULL) a->bel->abo = NULL; while(b->abo!=NULL) b = b->abo; goBack(a->abo); b->abo = a; a->pile = b->pile; a->bel = b; } void pileOver(block *a, block *b){ if(a->bel!=NULL) a->bel->abo = NULL; while(b->abo!=NULL) b = b->abo; b->abo = a; a->bel = b; while(a!=NULL){ a->pile = b->pile; a = a->abo; } } void pileOnto(block *a, block *b){ if(a->bel!=NULL) a->bel->abo = NULL; goBack(b->abo); b->abo = a; a->bel = b; while(a!=NULL){ a->pile = b->pile; a = a->abo; } } void showeet(block **b){ block *aux; for(int i = 0; i < nBlock; i++){ printf("%d:",i); if(b[i]->bel == NULL){ aux = b[i]; while(aux != NULL){ printf(" %d",aux->v); aux = aux->abo; } } printf("\n"); } } int main(void){ char cmd[5], mode[5]; int b1,b2; scanf("%d\n",&nBlock); struct block*b[nBlock]; for(int i = 0; i < nBlock; i++){ b[i] = new block; b[i]->v = b[i]->pile = i; b[i]->abo = b[i]->bel = NULL; } while(true){ scanf("%s ",&cmd); if(strcmp(cmd,"quit")==0) break; scanf(" %d %s %d\n",&b1,&mode,&b2); if(b1 == b2 || b[b1]->pile == b[b2]->pile) continue; if(strcmp(cmd,"move")==0){ if(strcmp(mode,"onto")==0) moveOnto(b[b1],b[b2]); else moveOver(b[b1],b[b2]); } else if(strcmp(mode,"onto")==0) pileOnto(b[b1],b[b2]); else pileOver(b[b1],b[b2]); } showeet(b); return 0; }
[ "mistermarin@gmail.com" ]
mistermarin@gmail.com
c801d5fb9ce75755c5a6950b443b6de7c9997fe4
3d74f759ee48d383aa82eeff0a55864a93a001ba
/shell/platform/android/surface/snapshot_surface_producer.h
5ec8c68b2f457aa4a5bd4865fa0bad19acc1be7a
[ "BSD-3-Clause" ]
permissive
flutter/engine
78be5418a9b2f7730dda9ca9fcb25b7055f3da85
902ece7f89d7730cc69f35e098b223cbbf4e25f1
refs/heads/main
2023-09-04T06:12:34.462953
2023-09-04T05:33:32
2023-09-04T05:33:32
39,211,337
7,090
6,862
BSD-3-Clause
2023-09-14T21:58:17
2015-07-16T17:39:56
C++
UTF-8
C++
false
false
882
h
// Copyright 2013 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SHELL_PLATFORM_ANDROID_SURFACE_SNAPSHOT_SURFACE_PRODUCER_H_ #define SHELL_PLATFORM_ANDROID_SURFACE_SNAPSHOT_SURFACE_PRODUCER_H_ #include "flutter/flow/surface.h" #include "flutter/shell/common/snapshot_surface_producer.h" #include "flutter/shell/platform/android/surface/android_surface.h" namespace flutter { class AndroidSnapshotSurfaceProducer : public SnapshotSurfaceProducer { public: explicit AndroidSnapshotSurfaceProducer(AndroidSurface& android_surface); // |SnapshotSurfaceProducer| std::unique_ptr<Surface> CreateSnapshotSurface() override; private: AndroidSurface& android_surface_; }; } // namespace flutter #endif // SHELL_PLATFORM_ANDROID_SURFACE_SNAPSHOT_SURFACE_PRODUCER_H_
[ "noreply@github.com" ]
noreply@github.com
4fe8fe8598f7e40cc7f1ca7946ca35aa92aaaa87
452be58b4c62e6522724740cac332ed0fe446bb8
/src/cobalt/media/formats/mp2t/es_parser_adts.h
f52e1dc6e6eb4fae795ef2e51308563334237d93
[ "Apache-2.0" ]
permissive
blockspacer/cobalt-clone-cab7770533804d582eaa66c713a1582f361182d3
b6e802f4182adbf6a7451a5d48dc4e158b395107
0b72f93b07285f3af3c8452ae2ceaf5860ca7c72
refs/heads/master
2020-08-18T11:32:21.458963
2019-10-17T13:09:35
2019-10-17T13:09:35
215,783,613
1
1
null
null
null
null
UTF-8
C++
false
false
2,686
h
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef COBALT_MEDIA_FORMATS_MP2T_ES_PARSER_ADTS_H_ #define COBALT_MEDIA_FORMATS_MP2T_ES_PARSER_ADTS_H_ #include <list> #include <memory> #include <utility> #include "base/callback.h" #include "base/compiler_specific.h" #include "base/macros.h" #include "base/time/time.h" #include "media/base/audio_decoder_config.h" #include "media/base/media_export.h" #include "media/formats/mp2t/es_parser.h" #include "media/formats/mpeg/adts_stream_parser.h" #include "starboard/types.h" namespace cobalt { namespace media { class AudioTimestampHelper; class BitReader; class OffsetByteQueue; class StreamParserBuffer; } // namespace media namespace cobalt { namespace media { namespace mp2t { class MEDIA_EXPORT EsParserAdts : public EsParser { public: typedef base::Callback<void(const AudioDecoderConfig&)> NewAudioConfigCB; EsParserAdts(const NewAudioConfigCB& new_audio_config_cb, const EmitBufferCB& emit_buffer_cb, bool sbr_in_mimetype); ~EsParserAdts() override; // EsParser implementation. void Flush() override; private: struct AdtsFrame; // EsParser implementation. bool ParseFromEsQueue() override; void ResetInternal() override; // Synchronize the stream on an ADTS syncword (consuming bytes from // |es_queue_| if needed). // Returns true when a full ADTS frame has been found: in that case // |adts_frame| structure is filled up accordingly. // Returns false otherwise (no ADTS syncword found or partial ADTS frame). bool LookForAdtsFrame(AdtsFrame* adts_frame); // Skip an ADTS frame in the ES queue. void SkipAdtsFrame(const AdtsFrame& adts_frame); // Signal any audio configuration change (if any). // Return false if the current audio config is not // a supported ADTS audio config. bool UpdateAudioConfiguration(const uint8_t* adts_header, int size); // Callbacks: // - to signal a new audio configuration, // - to send ES buffers. NewAudioConfigCB new_audio_config_cb_; EmitBufferCB emit_buffer_cb_; // True when AAC SBR extension is signalled in the mimetype // (mp4a.40.5 in the codecs parameter). bool sbr_in_mimetype_; // Interpolated PTS for frames that don't have one. std::unique_ptr<AudioTimestampHelper> audio_timestamp_helper_; // Last audio config. AudioDecoderConfig last_audio_decoder_config_; ADTSStreamParser adts_parser_; DISALLOW_COPY_AND_ASSIGN(EsParserAdts); }; } // namespace mp2t } // namespace media } // namespace cobalt #endif // COBALT_MEDIA_FORMATS_MP2T_ES_PARSER_ADTS_H_
[ "trofimov_d_a@magnit.ru" ]
trofimov_d_a@magnit.ru
8c7f54216587be2d08f6ace0c24ee34fa1b7d3e0
53f155c92599ccaa92be24c259893911bf03aff8
/trunk/source/distanceaspect.h
6ad0ae820af83335723ba3c03e3ff85dfcf71732
[]
no_license
BackupTheBerlios/framework-svn
6813d63b9fab1eef7873d3e115be339c1f7a73a1
8bd8bedee4456d00fdb03b9a76cfe0b9e364ef73
refs/heads/master
2021-01-01T16:00:01.456584
2006-12-13T22:03:46
2006-12-13T22:03:46
40,671,138
0
0
null
null
null
null
UTF-8
C++
false
false
759
h
#include "geographyaspect.h" #include "socialcircleaspect.h" #include "educationlevelaspect.h" #ifndef DISTASP #define DISTASP class DistanceAspect : public AspectBase { public: void Evolve(); void InitializeAspect(); int GetInfoSize(); void virtual ShowValues(int agentId, std::vector <char *> &fields, varValue *values); float GeographicDistance(key agentId1, key agentId2); int EducationDistance(key agentId1, key agentId2); // float GeographicDistance(float x1, float y1, float x2, float y2); int CircleDistance(key agentId1, key agentId2); private: GeographyAspect *_geographyAspect; EducationLevelAspect *_educationLevelAspect; SocialCircleAspect *_socialCircleAspect; int _delta; }; #endif
[ "pablodegrande@8096f40a-0115-0410-8a2f-ff4c50103d81" ]
pablodegrande@8096f40a-0115-0410-8a2f-ff4c50103d81
f7890041b17bed961e582f0959c4947cb5107353
12172b93f4cd90dddd4b56777c0b6d414a2c2d7e
/rush00/Enemy.hpp
314e5dcf225916cae3406c956faefd73c5420f53
[]
no_license
dpaunovi/Piscine_CPP
bef7a7ef958a09d2d221186e0c7a04256a04948a
bc529a157fa6d0978481f4d6731eaa1b1eecc5d3
refs/heads/master
2020-03-19T08:16:57.688041
2019-01-20T22:28:02
2019-01-20T22:28:02
136,191,019
0
0
null
null
null
null
UTF-8
C++
false
false
1,316
hpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Enemy.hpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dpaunovi <dpaunovi@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/01/12 15:29:29 by dpaunovi #+# #+# */ /* Updated: 2019/01/13 13:47:37 by dpaunovi ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef ENEMY_HPP #define ENEMY_HPP #include "AGameEntity.hpp" #include <ctime> class Enemy : public AGameEntity{ public: Enemy(); Enemy(CVector vm, char c); Enemy(Enemy const &src); virtual ~Enemy(); Enemy &operator=(Enemy const &rhs); virtual void updateEntity(int input); void shoot(void); private: int _speed; int _moveSpeed; clock_t _lastAction; clock_t _lastMove; }; #endif
[ "dpaunovi@e2r10p7.42.fr" ]
dpaunovi@e2r10p7.42.fr
4b272f4118c9652c63088d45b94e428c419261a6
6bd7786b556f3f301bf51534b9457c4bf691bbfc
/src/window/window.hpp
f19c3e8db0a8f288754dfbfa77716b368fb7729a
[]
no_license
hirokazuy/icfp2009
deb7c6bbfb52ac1c14b710aed78c50b2f2b4ee14
c494dfffecee0c9483ec73fda80fa4cf0924c1bc
refs/heads/master
2020-05-15T12:20:50.521304
2009-06-29T13:42:49
2009-06-29T13:42:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,234
hpp
// -*- Mode: c++; Coding: utf-8; tab-width: 4; -*- #ifndef __WINDOW_HPP__ #define __WINDOW_HPP__ #include <SDL/SDL.h> #include <boost/utility.hpp> //------------------------------------------------------------------------------- // SDL_Window の定義 //------------------------------------------------------------------------------- class SDLWindow : public boost::noncopyable { public: struct SDLWindowInitOption { unsigned int width; unsigned int height; Uint32 depth; Uint32 flags; }; static const SDLWindowInitOption DEFAULT_INIT_OPT; public: SDLWindow(); virtual ~SDLWindow(); virtual bool init(const SDLWindowInitOption& opt = DEFAULT_INIT_OPT); bool caption(const std::string& wmName, const std::string& iconName); virtual void clear(); virtual void swapBuffers(); private: SDL_Surface *window_; SDLWindowInitOption opt_; }; //------------------------------------------------------------------------------- // OpenGL 対応版 Window //------------------------------------------------------------------------------- class GLSDLWindow : public SDLWindow { public: GLSDLWindow() {} virtual ~GLSDLWindow() {} bool init(const SDLWindowInitOption& opt); void clear(); }; #endif // __WINDOW_HPP__
[ "hien.ayatuki@gmail.com" ]
hien.ayatuki@gmail.com
483a36774366041cc3bb9344c31beaf88c022388
e27d9e460c374473e692f58013ca692934347ef1
/drafts/quickSpectrogram_2/libraries/liblsl/external/lslboost/multi_index/detail/ord_index_node.hpp
ab9f2718949ba46490f5a0c415448a18137c45ef
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
thoughtworksarts/Dual_Brains
84a0edf69d95299021daf4af9311aed5724a2e84
a7a6586b91a280950693b427d8269bd68bf8a7ab
refs/heads/master
2021-09-18T15:50:51.397078
2018-07-16T23:20:18
2018-07-16T23:20:18
119,759,649
3
0
null
2018-07-16T23:14:34
2018-02-01T00:09:16
HTML
UTF-8
C++
false
false
19,257
hpp
/* Copyright 2003-2008 Joaquin M Lopez Munoz. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.lslboost.org/LICENSE_1_0.txt) * * See http://www.lslboost.org/libs/multi_index for library home page. * * The internal implementation of red-black trees is based on that of SGI STL * stl_tree.h file: * * Copyright (c) 1996,1997 * Silicon Graphics Computer Systems, Inc. * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Silicon Graphics makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * * * Copyright (c) 1994 * Hewlett-Packard Company * * Permission to use, copy, modify, distribute and sell this software * and its documentation for any purpose is hereby granted without fee, * provided that the above copyright notice appear in all copies and * that both that copyright notice and this permission notice appear * in supporting documentation. Hewlett-Packard Company makes no * representations about the suitability of this software for any * purpose. It is provided "as is" without express or implied warranty. * */ #ifndef BOOST_MULTI_INDEX_DETAIL_ORD_INDEX_NODE_HPP #define BOOST_MULTI_INDEX_DETAIL_ORD_INDEX_NODE_HPP #if defined(_MSC_VER)&&(_MSC_VER>=1200) #pragma once #endif #include <lslboost/config.hpp> /* keep it first to prevent nasty warns in MSVC */ #include <cstddef> #include <lslboost/detail/allocator_utilities.hpp> #include <lslboost/multi_index/detail/prevent_eti.hpp> #if !defined(BOOST_MULTI_INDEX_DISABLE_COMPRESSED_ORDERED_INDEX_NODES) #include <lslboost/mpl/and.hpp> #include <lslboost/mpl/if.hpp> #include <lslboost/multi_index/detail/uintptr_type.hpp> #include <lslboost/type_traits/alignment_of.hpp> #include <lslboost/type_traits/is_same.hpp> #endif namespace lslboost{ namespace multi_index{ namespace detail{ /* definition of red-black nodes for ordered_index */ enum ordered_index_color{red=false,black=true}; enum ordered_index_side{to_left=false,to_right=true}; template<typename Allocator> struct ordered_index_node_impl; /* fwd decl. */ template<typename Allocator> struct ordered_index_node_std_base { typedef typename prevent_eti< Allocator, typename lslboost::detail::allocator::rebind_to< Allocator, ordered_index_node_impl<Allocator> >::type >::type::pointer pointer; typedef typename prevent_eti< Allocator, typename lslboost::detail::allocator::rebind_to< Allocator, ordered_index_node_impl<Allocator> >::type >::type::const_pointer const_pointer; typedef ordered_index_color& color_ref; typedef pointer& parent_ref; ordered_index_color& color(){return color_;} ordered_index_color color()const{return color_;} pointer& parent(){return parent_;} pointer parent()const{return parent_;} pointer& left(){return left_;} pointer left()const{return left_;} pointer& right(){return right_;} pointer right()const{return right_;} private: ordered_index_color color_; pointer parent_; pointer left_; pointer right_; }; #if !defined(BOOST_MULTI_INDEX_DISABLE_COMPRESSED_ORDERED_INDEX_NODES) /* If ordered_index_node_impl has even alignment, we can use the least * significant bit of one of the ordered_index_node_impl pointers to * store color information. This typically reduces the size of * ordered_index_node_impl by 25%. */ #if defined(BOOST_MSVC) /* This code casts pointers to an integer type that has been computed * to be large enough to hold the pointer, however the metaprogramming * logic is not always spotted by the VC++ code analyser that issues a * long list of warnings. */ #pragma warning(push) #pragma warning(disable:4312 4311) #endif template<typename Allocator> struct ordered_index_node_compressed_base { typedef ordered_index_node_impl<Allocator>* pointer; typedef const ordered_index_node_impl<Allocator>* const_pointer; struct color_ref { color_ref(uintptr_type* r_):r(r_){} operator ordered_index_color()const { return ordered_index_color(*r&uintptr_type(1)); } color_ref& operator=(ordered_index_color c) { *r&=~uintptr_type(1); *r|=uintptr_type(c); return *this; } color_ref& operator=(const color_ref& x) { return operator=(x.operator ordered_index_color()); } private: uintptr_type* r; }; struct parent_ref { parent_ref(uintptr_type* r_):r(r_){} operator pointer()const { return (pointer)(void*)(*r&~uintptr_type(1)); } parent_ref& operator=(pointer p) { *r=((uintptr_type)(void*)p)|(*r&uintptr_type(1)); return *this; } parent_ref& operator=(const parent_ref& x) { return operator=(x.operator pointer()); } pointer operator->()const { return operator pointer(); } private: uintptr_type* r; }; color_ref color(){return color_ref(&parentcolor_);} ordered_index_color color()const { return ordered_index_color(parentcolor_&std::size_t(1ul)); } parent_ref parent(){return parent_ref(&parentcolor_);} pointer parent()const { return (pointer)(void*)(parentcolor_&~uintptr_type(1)); } pointer& left(){return left_;} pointer left()const{return left_;} pointer& right(){return right_;} pointer right()const{return right_;} private: uintptr_type parentcolor_; pointer left_; pointer right_; }; #if defined(BOOST_MSVC) #pragma warning(pop) #endif #endif template<typename Allocator> struct ordered_index_node_impl_base: #if !defined(BOOST_MULTI_INDEX_DISABLE_COMPRESSED_ORDERED_INDEX_NODES) mpl::if_c< !(has_uintptr_type::value)|| (alignment_of<ordered_index_node_compressed_base<Allocator> >::value%2)|| !(is_same< typename prevent_eti< Allocator, typename lslboost::detail::allocator::rebind_to< Allocator, ordered_index_node_impl<Allocator> >::type >::type::pointer, ordered_index_node_impl<Allocator>*>::value), ordered_index_node_std_base<Allocator>, ordered_index_node_compressed_base<Allocator> >::type #else ordered_index_node_std_base<Allocator> #endif {}; template<typename Allocator> struct ordered_index_node_impl:ordered_index_node_impl_base<Allocator> { private: typedef ordered_index_node_impl_base<Allocator> super; public: typedef typename super::color_ref color_ref; typedef typename super::parent_ref parent_ref; typedef typename super::pointer pointer; typedef typename super::const_pointer const_pointer; /* interoperability with bidir_node_iterator */ static void increment(pointer& x) { if(x->right()!=pointer(0)){ x=x->right(); while(x->left()!=pointer(0))x=x->left(); } else{ pointer y=x->parent(); while(x==y->right()){ x=y; y=y->parent(); } if(x->right()!=y)x=y; } } static void decrement(pointer& x) { if(x->color()==red&&x->parent()->parent()==x){ x=x->right(); } else if(x->left()!=pointer(0)){ pointer y=x->left(); while(y->right()!=pointer(0))y=y->right(); x=y; }else{ pointer y=x->parent(); while(x==y->left()){ x=y; y=y->parent(); } x=y; } } /* algorithmic stuff */ static void rotate_left(pointer x,parent_ref root) { pointer y=x->right(); x->right()=y->left(); if(y->left()!=pointer(0))y->left()->parent()=x; y->parent()=x->parent(); if(x==root) root=y; else if(x==x->parent()->left())x->parent()->left()=y; else x->parent()->right()=y; y->left()=x; x->parent()=y; } static pointer minimum(pointer x) { while(x->left()!=pointer(0))x=x->left(); return x; } static pointer maximum(pointer x) { while(x->right()!=pointer(0))x=x->right(); return x; } static void rotate_right(pointer x,parent_ref root) { pointer y=x->left(); x->left()=y->right(); if(y->right()!=pointer(0))y->right()->parent()=x; y->parent()=x->parent(); if(x==root) root=y; else if(x==x->parent()->right())x->parent()->right()=y; else x->parent()->left()=y; y->right()=x; x->parent()=y; } static void rebalance(pointer x,parent_ref root) { x->color()=red; while(x!=root&&x->parent()->color()==red){ if(x->parent()==x->parent()->parent()->left()){ pointer y=x->parent()->parent()->right(); if(y!=pointer(0)&&y->color()==red){ x->parent()->color()=black; y->color()=black; x->parent()->parent()->color()=red; x=x->parent()->parent(); } else{ if(x==x->parent()->right()){ x=x->parent(); rotate_left(x,root); } x->parent()->color()=black; x->parent()->parent()->color()=red; rotate_right(x->parent()->parent(),root); } } else{ pointer y=x->parent()->parent()->left(); if(y!=pointer(0)&&y->color()==red){ x->parent()->color()=black; y->color()=black; x->parent()->parent()->color()=red; x=x->parent()->parent(); } else{ if(x==x->parent()->left()){ x=x->parent(); rotate_right(x,root); } x->parent()->color()=black; x->parent()->parent()->color()=red; rotate_left(x->parent()->parent(),root); } } } root->color()=black; } static void link( pointer x,ordered_index_side side,pointer position,pointer header) { if(side==to_left){ position->left()=x; /* also makes leftmost=x when parent==header */ if(position==header){ header->parent()=x; header->right()=x; } else if(position==header->left()){ header->left()=x; /* maintain leftmost pointing to min node */ } } else{ position->right()=x; if(position==header->right()){ header->right()=x; /* maintain rightmost pointing to max node */ } } x->parent()=position; x->left()=pointer(0); x->right()=pointer(0); ordered_index_node_impl::rebalance(x,header->parent()); } static pointer rebalance_for_erase( pointer z,parent_ref root,pointer& leftmost,pointer& rightmost) { pointer y=z; pointer x=pointer(0); pointer x_parent=pointer(0); if(y->left()==pointer(0)){ /* z has at most one non-null child. y==z. */ x=y->right(); /* x might be null */ } else{ if(y->right()==pointer(0)){ /* z has exactly one non-null child. y==z. */ x=y->left(); /* x is not null */ } else{ /* z has two non-null children. Set y to */ y=y->right(); /* z's successor. x might be null. */ while(y->left()!=pointer(0))y=y->left(); x=y->right(); } } if(y!=z){ z->left()->parent()=y; /* relink y in place of z. y is z's successor */ y->left()=z->left(); if(y!=z->right()){ x_parent=y->parent(); if(x!=pointer(0))x->parent()=y->parent(); y->parent()->left()=x; /* y must be a child of left */ y->right()=z->right(); z->right()->parent()=y; } else{ x_parent=y; } if(root==z) root=y; else if(z->parent()->left()==z)z->parent()->left()=y; else z->parent()->right()=y; y->parent()=z->parent(); ordered_index_color c=y->color(); y->color()=z->color(); z->color()=c; y=z; /* y now points to node to be actually deleted */ } else{ /* y==z */ x_parent=y->parent(); if(x!=pointer(0))x->parent()=y->parent(); if(root==z){ root=x; } else{ if(z->parent()->left()==z)z->parent()->left()=x; else z->parent()->right()=x; } if(leftmost==z){ if(z->right()==pointer(0)){ /* z->left() must be null also */ leftmost=z->parent(); } else{ leftmost=minimum(x); /* makes leftmost==header if z==root */ } } if(rightmost==z){ if(z->left()==pointer(0)){ /* z->right() must be null also */ rightmost=z->parent(); } else{ /* x==z->left() */ rightmost=maximum(x); /* makes rightmost==header if z==root */ } } } if(y->color()!=red){ while(x!=root&&(x==pointer(0)|| x->color()==black)){ if(x==x_parent->left()){ pointer w=x_parent->right(); if(w->color()==red){ w->color()=black; x_parent->color()=red; rotate_left(x_parent,root); w=x_parent->right(); } if((w->left()==pointer(0)||w->left()->color()==black) && (w->right()==pointer(0)||w->right()->color()==black)){ w->color()=red; x=x_parent; x_parent=x_parent->parent(); } else{ if(w->right()==pointer(0 ) || w->right()->color()==black){ if(w->left()!=pointer(0)) w->left()->color()=black; w->color()=red; rotate_right(w,root); w=x_parent->right(); } w->color()=x_parent->color(); x_parent->color()=black; if(w->right()!=pointer(0))w->right()->color()=black; rotate_left(x_parent,root); break; } } else{ /* same as above,with right <-> left */ pointer w=x_parent->left(); if(w->color()==red){ w->color()=black; x_parent->color()=red; rotate_right(x_parent,root); w=x_parent->left(); } if((w->right()==pointer(0)||w->right()->color()==black) && (w->left()==pointer(0)||w->left()->color()==black)){ w->color()=red; x=x_parent; x_parent=x_parent->parent(); } else{ if(w->left()==pointer(0)||w->left()->color()==black){ if(w->right()!=pointer(0))w->right()->color()=black; w->color()=red; rotate_left(w,root); w=x_parent->left(); } w->color()=x_parent->color(); x_parent->color()=black; if(w->left()!=pointer(0))w->left()->color()=black; rotate_right(x_parent,root); break; } } } if(x!=pointer(0))x->color()=black; } return y; } static void restore(pointer x,pointer position,pointer header) { if(position->left()==pointer(0)||position->left()==header){ link(x,to_left,position,header); } else{ decrement(position); link(x,to_right,position,header); } } #if defined(BOOST_MULTI_INDEX_ENABLE_INVARIANT_CHECKING) /* invariant stuff */ static std::size_t black_count(pointer node,pointer root) { if(node==pointer(0))return 0; std::size_t sum=0; for(;;){ if(node->color()==black)++sum; if(node==root)break; node=node->parent(); } return sum; } #endif }; template<typename Super> struct ordered_index_node_trampoline: prevent_eti< Super, ordered_index_node_impl< typename lslboost::detail::allocator::rebind_to< typename Super::allocator_type, char >::type > >::type { typedef typename prevent_eti< Super, ordered_index_node_impl< typename lslboost::detail::allocator::rebind_to< typename Super::allocator_type, char >::type > >::type impl_type; }; template<typename Super> struct ordered_index_node:Super,ordered_index_node_trampoline<Super> { private: typedef ordered_index_node_trampoline<Super> trampoline; public: typedef typename trampoline::impl_type impl_type; typedef typename trampoline::color_ref impl_color_ref; typedef typename trampoline::parent_ref impl_parent_ref; typedef typename trampoline::pointer impl_pointer; typedef typename trampoline::const_pointer const_impl_pointer; impl_color_ref color(){return trampoline::color();} ordered_index_color color()const{return trampoline::color();} impl_parent_ref parent(){return trampoline::parent();} impl_pointer parent()const{return trampoline::parent();} impl_pointer& left(){return trampoline::left();} impl_pointer left()const{return trampoline::left();} impl_pointer& right(){return trampoline::right();} impl_pointer right()const{return trampoline::right();} impl_pointer impl() { return static_cast<impl_pointer>( static_cast<impl_type*>(static_cast<trampoline*>(this))); } const_impl_pointer impl()const { return static_cast<const_impl_pointer>( static_cast<const impl_type*>(static_cast<const trampoline*>(this))); } static ordered_index_node* from_impl(impl_pointer x) { return static_cast<ordered_index_node*>( static_cast<trampoline*>(&*x)); } static const ordered_index_node* from_impl(const_impl_pointer x) { return static_cast<const ordered_index_node*>( static_cast<const trampoline*>(&*x)); } /* interoperability with bidir_node_iterator */ static void increment(ordered_index_node*& x) { impl_pointer xi=x->impl(); trampoline::increment(xi); x=from_impl(xi); } static void decrement(ordered_index_node*& x) { impl_pointer xi=x->impl(); trampoline::decrement(xi); x=from_impl(xi); } }; } /* namespace multi_index::detail */ } /* namespace multi_index */ } /* namespace lslboost */ #endif
[ "gabriel.ibagon@gmail.com" ]
gabriel.ibagon@gmail.com
07ee5d66735c2fb47c96e4ffe50d8459e3e785c0
7a46183d7c64190b5112e67b7780fd634b7b1387
/Heading/heranca multipla.h
b251f2bbd98d48f769ba8bd94fb90b22eab11ff6
[]
no_license
Yopenbey/C-
02048d7442263ca75b8a31da03c0a1274b99ecc9
106878f4651584399fa7e26806ff321a4621f597
refs/heads/master
2022-12-06T04:12:13.840341
2020-08-27T02:04:37
2020-08-27T02:04:37
273,419,806
0
0
null
null
null
null
UTF-8
C++
false
false
398
h
#ifndef HERANCA_MULTIPLA_H_INCLUDED #define HERANCA_MULTIPLA_H_INCLUDED class Base1{ public: void impBase1(); }; void Base1::impBase1(){ std::cout << "Imp classe Base1" << std::endl; } class Base2{ public: void impBase2(); }; void Base2::impBase2(){ std::cout << "Imp classe Base2" << std::endl; } class CFB:public Base1, public Base2{ }; #endif // HERANCA_MULTIPLA_H_INCLUDED
[ "noreply@github.com" ]
noreply@github.com
44f69718f220d1d29f0220bc71643bf614d98f97
cf968dfb3f50f8fd41f6e9b126fc91b6d06f8bd2
/src/bls/bls.h
75fe5fa3d3b865ced915f2e928f086648d4bc523
[ "MIT" ]
permissive
emnaSE/Xdata-test-master
515f998cbff6d88e66d2c8af2016965b9f1faac0
ac1eed013fcf3a6d50fb7a87b1b9eb50cac5ac46
refs/heads/master
2020-06-11T23:20:30.398357
2019-06-27T15:48:25
2019-06-27T15:48:25
194,119,124
0
0
null
null
null
null
UTF-8
C++
false
false
10,422
h
// Copyright (c) 2018 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef XDA_CRYPTO_BLS_H #define XDA_CRYPTO_BLS_H #include "hash.h" #include "serialize.h" #include "uint256.h" #include "utilstrencodings.h" #undef ERROR // chia BLS uses relic, which defines ERROR, which in turn causes win32/win64 builds to print many warnings #include <chiabls/bls.hpp> #include <chiabls/privatekey.hpp> #include <chiabls/publickey.hpp> #include <chiabls/signature.hpp> #undef DOUBLE #include <array> #include <mutex> #include <unistd.h> // reversed BLS12-381 #define BLS_CURVE_ID_SIZE 32 #define BLS_CURVE_SECKEY_SIZE 32 #define BLS_CURVE_PUBKEY_SIZE 48 #define BLS_CURVE_SIG_SIZE 96 class CBLSSignature; class CBLSPublicKey; template <typename ImplType, size_t _SerSize, typename C> class CBLSWrapper { friend class CBLSSecretKey; friend class CBLSPublicKey; friend class CBLSSignature; protected: ImplType impl; bool fValid{false}; mutable uint256 cachedHash; inline constexpr size_t GetSerSize() const { return SerSize; } virtual bool InternalSetBuf(const void* buf) = 0; virtual bool InternalGetBuf(void* buf) const = 0; public: static const size_t SerSize = _SerSize; CBLSWrapper() { struct NullHash { uint256 hash; NullHash() { char buf[_SerSize]; memset(buf, 0, _SerSize); CHashWriter ss(SER_GETHASH, 0); ss.write(buf, _SerSize); hash = ss.GetHash(); } }; static NullHash nullHash; cachedHash = nullHash.hash; } CBLSWrapper(const CBLSWrapper& ref) = default; CBLSWrapper& operator=(const CBLSWrapper& ref) = default; CBLSWrapper(CBLSWrapper&& ref) { std::swap(impl, ref.impl); std::swap(fValid, ref.fValid); std::swap(cachedHash, ref.cachedHash); } CBLSWrapper& operator=(CBLSWrapper&& ref) { std::swap(impl, ref.impl); std::swap(fValid, ref.fValid); std::swap(cachedHash, ref.cachedHash); return *this; } bool operator==(const C& r) const { return fValid == r.fValid && impl == r.impl; } bool operator!=(const C& r) const { return !((*this) == r); } bool IsValid() const { return fValid; } void SetBuf(const void* buf, size_t size) { if (size != SerSize) { Reset(); return; } if (std::all_of((const char*)buf, (const char*)buf + SerSize, [](char c) { return c == 0; })) { Reset(); } else { fValid = InternalSetBuf(buf); if (!fValid) { Reset(); } } UpdateHash(); } void Reset() { *((C*)this) = C(); } void GetBuf(void* buf, size_t size) const { assert(size == SerSize); if (!fValid) { memset(buf, 0, SerSize); } else { bool ok = InternalGetBuf(buf); assert(ok); } } template <typename T> void SetBuf(const T& buf) { SetBuf(buf.data(), buf.size()); } template <typename T> void GetBuf(T& buf) const { buf.resize(GetSerSize()); GetBuf(buf.data(), buf.size()); } const uint256& GetHash() const { return cachedHash; } void UpdateHash() const { cachedHash = ::SerializeHash(*this); } bool SetHexStr(const std::string& str) { if (!IsHex(str)) { Reset(); return false; } auto b = ParseHex(str); if (b.size() != SerSize) { Reset(); return false; } SetBuf(b); return IsValid(); } public: template <typename Stream> inline void Serialize(Stream& s) const { char buf[SerSize] = {0}; GetBuf(buf, SerSize); s.write((const char*)buf, SerSize); } template <typename Stream> inline void Unserialize(Stream& s, bool checkMalleable = true) { char buf[SerSize]; s.read((char*)buf, SerSize); SetBuf(buf, SerSize); if (checkMalleable && !CheckMalleable(buf, SerSize)) { throw std::ios_base::failure("malleable BLS object"); } } inline bool CheckMalleable(void* buf, size_t size) const { char buf2[SerSize]; GetBuf(buf2, SerSize); if (memcmp(buf, buf2, SerSize)) { // TODO not sure if this is actually possible with the BLS libs. I'm assuming here that somewhere deep inside // these libs masking might happen, so that 2 different binary representations could result in the same object // representation return false; } return true; } inline std::string ToString() const { std::vector<unsigned char> buf; GetBuf(buf); return HexStr(buf.begin(), buf.end()); } }; class CBLSId : public CBLSWrapper<uint256, BLS_CURVE_ID_SIZE, CBLSId> { public: using CBLSWrapper::operator=; using CBLSWrapper::operator==; using CBLSWrapper::operator!=; CBLSId() {} void SetInt(int x); void SetHash(const uint256& hash); static CBLSId FromInt(int64_t i); static CBLSId FromHash(const uint256& hash); protected: bool InternalSetBuf(const void* buf); bool InternalGetBuf(void* buf) const; }; class CBLSSecretKey : public CBLSWrapper<bls::PrivateKey, BLS_CURVE_SECKEY_SIZE, CBLSSecretKey> { public: using CBLSWrapper::operator=; using CBLSWrapper::operator==; using CBLSWrapper::operator!=; CBLSSecretKey() {} void AggregateInsecure(const CBLSSecretKey& o); static CBLSSecretKey AggregateInsecure(const std::vector<CBLSSecretKey>& sks); #ifndef BUILD_BITCOIN_INTERNAL void MakeNewKey(); #endif bool SecretKeyShare(const std::vector<CBLSSecretKey>& msk, const CBLSId& id); CBLSPublicKey GetPublicKey() const; CBLSSignature Sign(const uint256& hash) const; protected: bool InternalSetBuf(const void* buf); bool InternalGetBuf(void* buf) const; }; class CBLSPublicKey : public CBLSWrapper<bls::PublicKey, BLS_CURVE_PUBKEY_SIZE, CBLSPublicKey> { friend class CBLSSecretKey; friend class CBLSSignature; public: using CBLSWrapper::operator=; using CBLSWrapper::operator==; using CBLSWrapper::operator!=; CBLSPublicKey() {} void AggregateInsecure(const CBLSPublicKey& o); static CBLSPublicKey AggregateInsecure(const std::vector<CBLSPublicKey>& pks); bool PublicKeyShare(const std::vector<CBLSPublicKey>& mpk, const CBLSId& id); bool DHKeyExchange(const CBLSSecretKey& sk, const CBLSPublicKey& pk); protected: bool InternalSetBuf(const void* buf); bool InternalGetBuf(void* buf) const; }; class CBLSSignature : public CBLSWrapper<bls::InsecureSignature, BLS_CURVE_SIG_SIZE, CBLSSignature> { friend class CBLSSecretKey; public: using CBLSWrapper::operator==; using CBLSWrapper::operator!=; using CBLSWrapper::CBLSWrapper; CBLSSignature() {} CBLSSignature(const CBLSSignature&) = default; CBLSSignature& operator=(const CBLSSignature&) = default; void AggregateInsecure(const CBLSSignature& o); static CBLSSignature AggregateInsecure(const std::vector<CBLSSignature>& sigs); static CBLSSignature AggregateSecure(const std::vector<CBLSSignature>& sigs, const std::vector<CBLSPublicKey>& pks, const uint256& hash); void SubInsecure(const CBLSSignature& o); bool VerifyInsecure(const CBLSPublicKey& pubKey, const uint256& hash) const; bool VerifyInsecureAggregated(const std::vector<CBLSPublicKey>& pubKeys, const std::vector<uint256>& hashes) const; bool VerifySecureAggregated(const std::vector<CBLSPublicKey>& pks, const uint256& hash) const; bool Recover(const std::vector<CBLSSignature>& sigs, const std::vector<CBLSId>& ids); protected: bool InternalSetBuf(const void* buf); bool InternalGetBuf(void* buf) const; }; #ifndef BUILD_BITCOIN_INTERNAL class CBLSLazySignature { private: mutable std::mutex mutex; mutable char buf[BLS_CURVE_SIG_SIZE]; mutable bool bufValid{false}; mutable CBLSSignature sig; mutable bool sigInitialized{false}; public: CBLSLazySignature() { memset(buf, 0, sizeof(buf)); } CBLSLazySignature(const CBLSLazySignature& r) { *this = r; } CBLSLazySignature& operator=(const CBLSLazySignature& r) { std::unique_lock<std::mutex> l(r.mutex); bufValid = r.bufValid; if (r.bufValid) { memcpy(buf, r.buf, sizeof(buf)); } else { memset(buf, 0, sizeof(buf)); } sigInitialized = r.sigInitialized; if (r.sigInitialized) { sig = r.sig; } else { sig.Reset(); } return *this; } template<typename Stream> inline void Serialize(Stream& s) const { std::unique_lock<std::mutex> l(mutex); if (!sigInitialized && !bufValid) { throw std::ios_base::failure("sig and buf not initialized"); } if (!bufValid) { sig.GetBuf(buf, sizeof(buf)); bufValid = true; } s.write(buf, sizeof(buf)); } template<typename Stream> inline void Unserialize(Stream& s) { std::unique_lock<std::mutex> l(mutex); s.read(buf, sizeof(buf)); bufValid = true; sigInitialized = false; } void SetSig(const CBLSSignature& _sig); const CBLSSignature& GetSig() const; }; #endif typedef std::vector<CBLSId> BLSIdVector; typedef std::vector<CBLSPublicKey> BLSVerificationVector; typedef std::vector<CBLSPublicKey> BLSPublicKeyVector; typedef std::vector<CBLSSecretKey> BLSSecretKeyVector; typedef std::vector<CBLSSignature> BLSSignatureVector; typedef std::shared_ptr<BLSIdVector> BLSIdVectorPtr; typedef std::shared_ptr<BLSVerificationVector> BLSVerificationVectorPtr; typedef std::shared_ptr<BLSPublicKeyVector> BLSPublicKeyVectorPtr; typedef std::shared_ptr<BLSSecretKeyVector> BLSSecretKeyVectorPtr; typedef std::shared_ptr<BLSSignatureVector> BLSSignatureVectorPtr; bool BLSInit(); #endif // XDA_CRYPTO_BLS_H
[ "emna.sellamni@sqoin.us" ]
emna.sellamni@sqoin.us
c1a118cfc7c534a181fe5b624fee9e60067360a2
e862f48c627b8effec2a25b37c590ca4f2649fc0
/src/pwiz-4209/pwiz/utility/bindings/CLI/common/IterationListenerTest.cpp
bc76cbd9ee23bd4838e21aa2ca0e1f59b3f597e5
[ "Apache-2.0" ]
permissive
Bandeira/sps
ec82a77c315cf1aff9761c801d1dc63cb5c5e9f0
1809945c9e5a6836a753a434d2c8570941130021
refs/heads/master
2016-09-01T08:18:34.221603
2015-12-10T23:56:52
2015-12-10T23:56:52
47,741,477
0
0
null
null
null
null
UTF-8
C++
false
false
2,688
cpp
// // $Id: IterationListenerTest.cpp 4129 2012-11-20 00:05:37Z chambm $ // // // Original author: Darren Kessner <darren@proteowizard.org> // // Copyright 2008 Spielberg Family Center for Applied Proteomics // Cedars Sinai Medical Center, Los Angeles, California 90048 // // 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 "unit.hpp" #include <stdexcept> using namespace pwiz::CLI::util; using namespace pwiz::CLI::cv; using namespace pwiz::CLI::data; using System::String; using System::Collections::Generic::List; public ref struct IterationListenerTest : IterationListener { List<int>^ iterationIndexes; int iterationCount; String^ message; IterationListenerTest() { iterationIndexes = gcnew List<int>(); } virtual Status update(UpdateMessage^ updateMessage) override { iterationIndexes->Add(updateMessage->iterationIndex); iterationCount = updateMessage->iterationCount; message = updateMessage->message; return Status::Ok; } }; void test() { IterationListenerTest^ iterationListenerTest = gcnew IterationListenerTest(); IterationListenerRegistry^ ilr = gcnew IterationListenerRegistry(); ilr->addListener(iterationListenerTest, 10); for (size_t i=0; i < 100; ++i) ilr->broadcastUpdateMessage(gcnew IterationListener::UpdateMessage(i, 100, "iteration")); // 0 9 19 29 39 49 59 69 79 89 99 unit_assert(iterationListenerTest->iterationIndexes->Count == 11); unit_assert(iterationListenerTest->iterationIndexes[0] == 0); unit_assert(iterationListenerTest->iterationIndexes[10] == 99); unit_assert(iterationListenerTest->iterationCount == 100); unit_assert(iterationListenerTest->message == "iteration"); } int main(int argc, const char* argv[]) { TEST_PROLOG_EX(argc, argv, "_CLI") try { test(); } catch (exception& e) { TEST_FAILED("std::exception: " + string(e.what())) } catch (System::Exception^ e) { TEST_FAILED("System.Exception: " + ToStdString(e->Message)) } catch (...) { TEST_FAILED("Caught unknown exception.") } TEST_EPILOG }
[ "ming@localhost" ]
ming@localhost
cea069175175c2e9ee0884d3a51d9bd55b62f58b
f4cbb7aec6000c0b674b0c4fbcab398a7e759588
/main/ble_services.hpp
61981ee119af61f1792e789445d60a492e8d3b63
[]
no_license
LilDataMonster/loincloth
948d1a8b78a0bde7760ac3e2ae6d2a9a6cc2bad9
b12d48539c45c6568a9739498fe073700c792414
refs/heads/master
2023-03-15T03:37:59.267726
2021-03-25T03:22:39
2021-03-25T03:22:39
285,973,392
0
0
null
2020-12-21T02:05:29
2020-08-08T04:34:45
C++
UTF-8
C++
false
false
1,859
hpp
#ifndef BLE_SERVICE #define BLE_SERVICE #include <globals.hpp> #include <esp_gatts_api.h> #define ESP_APP_ID 0x55 #define PROFILE_NUM 1 #define PROFILE_APP_IDX 0 #define SVC_INST_ID 0 /* Service */ static const uint32_t GATTS_SERVICE_UUID_LDM = 0x4C444D00; static const uint16_t GATTS_CHAR_UUID_MAC = 0x4D01; static const uint16_t GATTS_CHAR_UUID_IPV4 = 0x4D02; #if CONFIG_DHT_SENSOR_ENABLED static const uint16_t GATTS_CHAR_UUID_DHT = 0x4D03; #endif #if CONFIG_BME680_SENSOR_ENABLED static const uint16_t GATTS_CHAR_UUID_BME680 = 0x4D04; #endif static const uint16_t primary_service_uuid = ESP_GATT_UUID_PRI_SERVICE; static const uint16_t character_declaration_uuid = ESP_GATT_UUID_CHAR_DECLARE; static const uint16_t character_client_config_uuid = ESP_GATT_UUID_CHAR_CLIENT_CONFIG; static const uint8_t char_prop_read = ESP_GATT_CHAR_PROP_BIT_READ; static const uint8_t char_prop_write = ESP_GATT_CHAR_PROP_BIT_WRITE; static const uint8_t char_prop_read_write_notify = ESP_GATT_CHAR_PROP_BIT_WRITE | ESP_GATT_CHAR_PROP_BIT_READ | ESP_GATT_CHAR_PROP_BIT_NOTIFY; void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param); esp_err_t bleUpdateIpv4(void); #if CONFIG_DHT_SENSOR_ENABLED esp_err_t bleUpdateDht(void); extern float dht_data[2]; #endif #if CONFIG_BME680_SENSOR_ENABLED esp_err_t bleUpdateBme680(void); extern float bme680_data[4]; #endif /* Attributes State Machine */ enum { LDM_IDX_SVC, LDM_MAC_CHAR, LDM_MAC_VAL, LDM_IPV4_CHAR, LDM_IPV4_VAL, #if CONFIG_DHT_SENSOR_ENABLED LDM_DHT_CHAR, LDM_DHT_VAL, #endif #if CONFIG_BME680_SENSOR_ENABLED LDM_BME680_CHAR, LDM_BME680_VAL, #endif LDM_IDX_NB }; #endif
[ "fand.kanade@gmail.com" ]
fand.kanade@gmail.com
a3f6649bba91090de444480135438864a7081281
0ca28e453efca89d30796f3e020a7ccb685839a4
/ch06-recursion/exercises/03-count-target.cpp
783799015ed4aade9c728d61c8b7f1d43fe2d15f
[]
no_license
abangfarhan/think-like-a-programmer
6e073526d7886a6df4180645964787e48be6721a
f58eb14d1d6172cf47435988339272760a724455
refs/heads/master
2021-09-02T15:39:09.148098
2018-01-03T12:42:11
2018-01-03T12:42:11
115,246,301
2
0
null
null
null
null
UTF-8
C++
false
false
722
cpp
#include <iostream> int countTargetIterative(int target, int arr[], int size) { int targetCounted = 0; for (int i = 0; i < size; i++) { if (arr[i] == target) targetCounted++; } return targetCounted; } int countTargetRecursion(int target, int arr[], int size) { if (size == 0) return 0; int targetCounted = countTargetRecursion(target, arr, size - 1); if (arr[size - 1] == target) targetCounted++; return targetCounted; } int main() { int size = 10; int arr[size] = {100, 2, 3, 100, 4, 6, 7, 100, 9, 10}; int target = 100; std::cout << countTargetIterative(target, arr, size) << std::endl; std::cout << countTargetRecursion(target, arr, size) << std::endl; }
[ "abangfarhan31@gmail.com" ]
abangfarhan31@gmail.com
fcc657e028c8d67a59bf73789501798bba7556c3
f8f60937ab22d13c94c3e23f302d1be25c47db73
/include/eggs/variant/detail/apply.hpp
574965cd4c8d1d1676626fca445911c367712e3d
[ "BSL-1.0" ]
permissive
pmed/variant
daf4025afd5090168116b1200d05abd2efed6b9d
83b86295d35f40866e20da5c1b2027c42ce90cfa
refs/heads/master
2020-12-02T15:07:08.365708
2015-07-09T00:11:26
2015-07-09T00:11:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,977
hpp
//! \file eggs/variant/detail/apply.hpp // Eggs.Variant // // Copyright Agustin K-ballo Berge, Fusion Fenix 2014-2015 // // 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) #ifndef EGGS_VARIANT_DETAIL_APPLY_HPP #define EGGS_VARIANT_DETAIL_APPLY_HPP #include <eggs/variant/detail/pack.hpp> #include <eggs/variant/detail/storage.hpp> #include <eggs/variant/detail/visitor.hpp> #include <eggs/variant/bad_variant_access.hpp> #include <cstddef> #include <type_traits> #include <utility> #include <eggs/variant/detail/config/prefix.hpp> namespace eggs { namespace variants { namespace detail { /////////////////////////////////////////////////////////////////////////// template <typename F, typename ...Args> EGGS_CXX11_CONSTEXPR auto _invoke(F&& f, Args&&... args) EGGS_CXX11_NOEXCEPT_IF(EGGS_CXX11_NOEXCEPT_EXPR( std::forward<F>(f)(std::forward<Args>(args)...))) -> decltype(std::forward<F>(f)(std::forward<Args>(args)...)) { return std::forward<F>(f)(std::forward<Args>(args)...); } #if EGGS_CXX11_HAS_SFINAE_FOR_EXPRESSIONS template <typename F, typename Arg0, typename ...Args> EGGS_CXX11_CONSTEXPR auto _invoke(F&& f, Arg0&& arg0, Args&&... args) EGGS_CXX11_NOEXCEPT_IF(EGGS_CXX11_NOEXCEPT_EXPR( (arg0.*f)(std::forward<Args>(args)...))) -> decltype((arg0.*f)(std::forward<Args>(args)...)) { return (arg0.*f)(std::forward<Args>(args)...); } template <typename F, typename Arg0, typename ...Args> EGGS_CXX11_CONSTEXPR auto _invoke(F&& f, Arg0&& arg0, Args&&... args) EGGS_CXX11_NOEXCEPT_IF(EGGS_CXX11_NOEXCEPT_EXPR( ((*arg0).*f)(std::forward<Args>(args)...))) -> decltype(((*arg0).*f)(std::forward<Args>(args)...)) { return ((*arg0).*f)(std::forward<Args>(args)...); } template <typename F, typename Arg0> EGGS_CXX11_CONSTEXPR auto _invoke(F&& f, Arg0&& arg0) EGGS_CXX11_NOEXCEPT -> decltype(arg0.*f) { return arg0.*f; } template <typename F, typename Arg0> EGGS_CXX11_CONSTEXPR auto _invoke(F&& f, Arg0&& arg0) EGGS_CXX11_NOEXCEPT -> decltype((*arg0).*f) { return (*arg0).*f; } #endif template <typename R> struct _invoke_guard { template <typename ...Ts> EGGS_CXX11_CONSTEXPR R operator()(Ts&&... vs) const EGGS_CXX11_NOEXCEPT_IF(EGGS_CXX11_NOEXCEPT_EXPR( _invoke(std::forward<Ts>(vs)...))) { return _invoke(std::forward<Ts>(vs)...); } }; template <> struct _invoke_guard<void> { template <typename ...Ts> EGGS_CXX14_CONSTEXPR void operator()(Ts&&... vs) const EGGS_CXX11_NOEXCEPT_IF(EGGS_CXX11_NOEXCEPT_EXPR( _invoke(std::forward<Ts>(vs)...))) { _invoke(std::forward<Ts>(vs)...); } }; /////////////////////////////////////////////////////////////////////////// template <typename T, typename Is = make_index_pack<T::size>> struct _make_apply_pack; template <typename T, std::size_t I, std::size_t ...Is> struct _make_apply_pack<T, pack_c<std::size_t, I, Is...>> { using type = pack<index<Is>...>; }; template <typename T> using _apply_pack = typename _make_apply_pack<T>::type; /////////////////////////////////////////////////////////////////////////// template <typename V, typename I> struct _apply_get { using type = decltype(std::declval<V>().get(I{})); type EGGS_CXX11_CONSTEXPR operator()(V& v) const { return v.get(I{}); } }; template <typename V, typename I> struct _apply_get<V&&, I> { using type = typename std::remove_reference< decltype(std::declval<V>().get(I{}))>::type; EGGS_CXX11_CONSTEXPR type operator()(V& v) const { return std::move(v.get(I{})); } }; /////////////////////////////////////////////////////////////////////////// template <typename R, typename F, typename Ms, typename Vs> struct _apply; template < typename R, typename F, typename ...Ms, typename V > struct _apply<R, F, pack<Ms...>, pack<V>> : visitor< _apply<R, F, pack<Ms...>, pack<V>> , R(F&&, Ms..., V&&) > { template <typename I> static EGGS_CXX11_CONSTEXPR R call(F&& f, Ms... ms, V&& v) { return _invoke_guard<R>{}( std::forward<F>(f), std::forward<Ms>(ms)... , _apply_get<V, I>{}(v)); } }; template < typename R, typename F, typename ...Ms , typename V0, typename V1, typename ...Vs > struct _apply<R, F, pack<Ms...>, pack<V0, V1, Vs...>> : visitor< _apply<R, F, pack<Ms...>, pack<V0, V1, Vs...>> , R(F&&, Ms..., V0&&, V1&&, Vs&&...) > { template <typename I> static EGGS_CXX11_CONSTEXPR R call(F&& f, Ms... ms, V0&& v0, V1&& v1, Vs&&... vs) { using T = typename _apply_get<V0, I>::type; return v0.which() != 0 ? _apply<R, F, pack<Ms..., T>, pack<V1, Vs...>>{}( _apply_pack<typename std::decay<V1>::type>{}, v1.which() - 1 , std::forward<F>(f) , std::forward<Ms>(ms)..., _apply_get<V0, I>{}(v0) , std::forward<V1>(v1), std::forward<Vs>(vs)... ) : throw_bad_variant_access<R>(); } }; template <typename R, typename F, typename V, typename ...Vs> EGGS_CXX11_CONSTEXPR R apply(F&& f, V&& v, Vs&&... vs) { return v.which() != 0 ? _apply<R, F, pack<>, pack<V&&, Vs&&...>>{}( _apply_pack<typename std::decay<V>::type>{}, v.which() - 1 , std::forward<F>(f) , std::forward<V>(v), std::forward<Vs>(vs)... ) : throw_bad_variant_access<R>(); } /////////////////////////////////////////////////////////////////////////// template <typename ...Ts> struct _always_void { using type = void; }; template <typename T, typename Enable = void> struct _weak_result {}; template <typename R, typename ...Args> struct _weak_result<R(*)(Args...)> { using type = R; }; template <typename R, typename ...Args> struct _weak_result<R(*)(Args..., ...)> { using type = R; }; template <typename C> struct _weak_result<C, typename _always_void<typename C::result_type>::type> { using type = typename C::result_type; }; template <typename T> using weak_result = typename _weak_result<T>::type; }}} #include <eggs/variant/detail/config/suffix.hpp> #endif /*EGGS_VARIANT_DETAIL_APPLY_HPP*/
[ "k@fusionfenix.com" ]
k@fusionfenix.com
6480846f1815bc1b40d6fa168a781054be031529
5497bd7824ae39b70b7723cfb897c0d8b0651233
/oop/black-jack/include/House.h
d5ffaaf1c3345b535b928e5bb7e9455ff442e0ad
[]
no_license
imaxer/gb_cpp
4dbbe5144196443cd57348118b6f05372f268cc0
edfe5182a4d3bd9b007d5efee6673a8b28025060
refs/heads/master
2023-06-12T14:46:45.638189
2021-06-28T14:25:11
2021-06-28T14:25:11
335,910,756
0
0
null
2021-07-08T14:35:30
2021-02-04T09:58:12
C++
UTF-8
C++
false
false
422
h
/* * Created by Maksim Paramonov on 05.04.2021. */ #ifndef CPP_HOUSE_H #define CPP_HOUSE_H #include <string> #include "GenericPlayer.h" class House : public GenericPlayer { public: House() : GenericPlayer("house") {}; House(const House &house) = default; House(House &&house) = default; ~House() override = default; bool isHitting() override; void flipFirstCard(); }; #endif //CPP_HOUSE_H
[ "imaxer.pm@gmail.com" ]
imaxer.pm@gmail.com
696bb54c84a867743c28418522fb508d28b04ecf
4d43c3b6a442a322f1045724040867209c396174
/examples/abc/abc.ino
8c977a3161045a96cf8d4ae64c8c3815278809a7
[ "MIT" ]
permissive
LZY1586/DFRobot_Capacitive_Fingerprint
8c13ba2b40247880197f24f46a763508db3db921
b332298372b227ded0ec2b46ec784a80d75ec9fa
refs/heads/master
2021-03-25T12:35:45.506791
2020-03-24T05:15:56
2020-03-24T05:15:56
247,618,787
0
0
null
null
null
null
UTF-8
C++
false
false
5,597
ino
/*! * @file fingerprintRegistration.ino * @brief 采集指纹并保存 * @n 本实验需要Leonardo主控和ID809指纹模块 * @n 实验现象:按下3秒内为指纹匹配 * @n 按下3-6秒为注册指纹 * @n 6秒以上为删除指纹 * @n 空闲5秒之后进入休眠 * @copyright Copyright (c) 2010 DFRobot Co.Ltd (http://www.dfrobot.com) * @licence The MIT License (MIT) * @author [Eddard](Eddard.liu@dfrobot.com) * @version V1.0 * @date 2020-03-19 * @get from https://www.dfrobot.com * @url https://github.com/DFRobot/DFRobot_SHT3x */ #include <DFRobot_ID809.h> #define COLLECT_NUMBER 3 //指纹采样次数,可设置1-3 #define WAKEUP 6 //唤醒引脚 DFRobot_ID809 finger; void setup(){ /*初始化打印串口*/ Serial.begin(9600); /*初始化Serial1*/ Serial1.begin(115200); /*将Serial1作为指纹模块的通讯串口*/ finger.begin(Serial1); /*等待Serial打开*/ while(!Serial); /*测试设备与主控是否能正常通讯*/ while(finger.testConnection()){ Serial.println("与设备通讯失败,请检查接线"); delay(1000); } } unsigned long time = 0; uint8_t wakeUpFlag = 1; //指纹模块唤醒标志位 void loop(){ if(digitalRead(WAKEUP)){ /*获取手指按下时间*/ time = millis(); /*采集指纹图像,超过5S没按下手指则采集超时*/ if(finger.fingerprintCollection(/*timeout = */5) == 0){ //采集成功 /*等待手指松开*/ while(finger.detectFinger()); /*获取手指松开时间*/ time = millis() - time; }else{ time = 0; } if(time == 0){ /*指纹采集失败*/ }else if(time > 0 && time <= 3000){ Serial.println("进入匹配指纹模式"); /*对比指纹*/ fingerprintMatching(); }else if(time > 3000 && time <=6000){ Serial.println("进入注册指纹模式"); /*注册指纹*/ fingerprintRegistration(); }else{ Serial.println("进入删除指纹模式"); /*删除该指纹*/ fingerprintDeletion(); } time = millis(); wakeUpFlag = 1; } if(wakeUpFlag == 1 && (millis()-time) > 5000){ wakeUpFlag = 0; /*指纹模块进入休眠*/ finger.enterStandbyState(); } } //匹配指纹 void fingerprintMatching(){ /*将采集到的指纹与指纹库中的所有指纹对比,成功返回指纹编号,失败返回0*/ uint8_t ret = finger.search(); if(ret){ /*设置指纹灯环模式、颜色和闪烁次数, 可设置参数如下: <LEDMode> eBreathing eFastBlink eKeepsOn eNormalClose eFadeIn eFadeOut eSlowBlink <LEDColor> eLEDGreen eLEDRed eLEDYellow eLEDBlue eLEDCyan eLEDMagenta eLEDWhite <闪烁次数> 0表示一直闪烁 */ finger.LEDCtrl(finger.eKeepsOn, finger.eLEDGreen, /*flashing number = */0); Serial.print("匹配成功,ID="); Serial.println(ret); }else{ /*设置指纹灯环为红色常亮*/ finger.LEDCtrl(finger.eKeepsOn, finger.eLEDRed, /*flashing number = */0); Serial.println("匹配失败"); } delay(1000); /*关闭指纹灯环*/ finger.LEDCtrl(finger.eNormalClose, finger.eLEDBlue, /*flashing number = */0); } //注册指纹 void fingerprintRegistration(){ uint8_t ID,i; /*对比指纹,作用:清除上次采集的指纹图像*/ finger.search(); /*获取一个未注册编号,用来保存指纹*/ ID = finger.getEmptyID(); Serial.print("ID="); Serial.println(ID); i = 0; //采样计数清零 /*指纹采样三次*/ while(i < COLLECT_NUMBER){ /*设置灯环为蓝色呼吸灯*/ finger.LEDCtrl(finger.eBreathing, finger.eLEDBlue, /*flashing number=*/0); Serial.print("正在进行第"); Serial.print(i+1); Serial.println("次指纹采样"); Serial.println("请按下手指"); /*采集指纹图像,超过5S没按下手指则采集超时*/ if(finger.fingerprintCollection(/*timeout = */5) == 0){ /*设置指纹灯环为黄色快闪3次*/ finger.LEDCtrl(finger.eFastBlink, finger.eLEDYellow, /*flashing number = */3); Serial.println("采集成功"); i++; //采样计数+1 }else{ //打印ret对应的错误码 Serial.println("采集失败"); } Serial.println("请松开手指"); /*等待手指松开*/ while(finger.detectFinger()); } /*将指纹信息保存到一个未注册的编号中*/ finger.storeFingerprint(ID); Serial.print("保存成功,ID="); Serial.println(ID); Serial.println("-----------------------------"); /*设置指纹灯环为绿色常亮*/ finger.LEDCtrl(finger.eKeepsOn, finger.eLEDGreen, /*flashing number = */0); delay(1000); /*关闭指纹灯环*/ finger.LEDCtrl(finger.eNormalClose, finger.eLEDBlue, /*flashing number = */0); } //删除指纹 void fingerprintDeletion(){ uint8_t ret; /*将采集到的指纹与指纹库中的所有指纹对比,成功返回指纹编号,失败返回0*/ ret = finger.search(); if(ret){ /*设置指纹灯环为绿色常亮*/ finger.LEDCtrl(finger.eKeepsOn, finger.eLEDGreen, /*flashing number = */0); finger.delFingerprint(ret); Serial.print("已删除指纹,ID="); Serial.println(ret); }else{ /*设置指纹灯环为红色常亮*/ finger.LEDCtrl(finger.eKeepsOn, finger.eLEDRed, /*flashing number = */0); Serial.println("匹配失败或该指纹未注册"); } delay(1000); /*关闭指纹灯环*/ finger.LEDCtrl(finger.eNormalClose, finger.eLEDBlue, /*flashing number = */0); }
[ "1586254416@qq.com" ]
1586254416@qq.com
5bfc3c67e5fda2f86d34410d399100f880666fc3
87bd17a50a4e888ca1bbe2a775175345137fa218
/src/GuiManager/GuiManager.cpp
ecd7b9dcff71f4014075df4ce22ddd88446acc7a
[ "Unlicense" ]
permissive
ZachStephens/cpp20Sandbox
6b65ca270a7bba5f2f9eecace9662d17e48f4465
0267c9984f4a70db26f1be315f6f74428a6658f0
refs/heads/develop
2023-03-31T21:22:20.087965
2021-03-28T19:45:17
2021-03-28T19:45:17
307,140,516
0
0
Unlicense
2021-03-28T19:45:17
2020-10-25T16:24:11
C++
UTF-8
C++
false
false
5,311
cpp
#include <imgui.h> #include <imgui-SFML.h> #include <SFML/Graphics/RenderWindow.hpp> #include <SFML/System/Clock.hpp> #include <SFML/Window/Event.hpp> #include <spdlog/spdlog.h> #include "GuiManager.hpp" #include "../ThreadCommunicator/ThreadCommunicator.hpp" #include "CoreLogicManager/Messages/LogicInputMessage.hpp" #include <iostream> #include <map> #include <algorithm> #include <functional> #include <memory> namespace gman { GuiManager::GuiManager(std::shared_ptr<ThreadCom::ThreadCommunicator<ThreadCom::commMsg>> threadComm, std::shared_ptr<ThreadCom::ThreadCommunicator<gman::guiManRequest>> guiManRequestComm) : RunnableManager(std::move(threadComm)), mGuiRequester(std::move(guiManRequestComm)) { const auto FRAME_RATE_LIMIT = 90; this->mWindow.setFramerateLimit(FRAME_RATE_LIMIT); ImGui::SFML::Init(this->mWindow); this->mWindow.setActive(false); sf::Image image; image.loadFromFile("/home/zach/Pictures/bison.jpeg"); mBackgroundTexture.loadFromImage(image); auto TextureSize = mBackgroundTexture.getSize();//Get size of texture. auto WindowSize = mWindow.getSize();//Get size of window. auto ScaleX = static_cast<float>(WindowSize.x) / static_cast<float>(TextureSize.x); auto ScaleY = static_cast<float>(WindowSize.y) / static_cast<float>(TextureSize.y);//Calculate scale. mBackground.setTexture(mBackgroundTexture); mBackground.setScale(ScaleX, ScaleY);//Set scale. mServiceId = mThreadComm->registerHandler(this->commMsgHandler); mGuiRequestHandlerId = mGuiRequester->registerHandler(this->guiRequestMsgHandler); } // void GuiManager::guiRequestMsgHandler(std::unique_ptr<guiManRequest> msg) // { // // mRequestQueue.push_back(std::move(msg)); // auto shapeToDraw = msg->mShape; // this->mWindow.draw(*shapeToDraw); // } // void GuiManager::processGuiManRequest(std::unique_ptr<std::vector<guiManRequest>> requestVec) // { // spdlog::set_level(spdlog::level::info); // spdlog::debug("processGuiManRequest start"); // if (requestVec) { // mRequestVecPending.swap(requestVec); // } else { // mRequestVecPending->clear(); // } // spdlog::debug("processGuiManRequest requestVec Moved"); // spdlog::set_level(spdlog::level::info); // } void GuiManager::update() { spdlog::set_level(spdlog::level::info); ImGui::SFML::Update(mWindow, mDeltaClock.restart()); // Requests of other entities to be drawn are handled as they appear spdlog::debug("Check if pending empty"); if (mRequestVecPending && !mRequestVecPending->empty()) { spdlog::debug("Attempt Swap"); mRequestVec.swap(mRequestVecPending); spdlog::debug("Move Completed"); } if (mRequestVec && !mRequestVec->empty()) { spdlog::debug("Attempt draw"); mWindow.clear(); mWindow.draw(mBackground); for (const auto &request : *mRequestVec) { auto shapeToDraw = request.mShape; mWindow.draw(*shapeToDraw); } spdlog::debug("Attempt clear"); mRequestVec->clear(); spdlog::debug("mRequestVec cleared"); } spdlog::set_level(spdlog::level::info); // while (!mRequestVec.empty()) { // processGuiManRequest(std::move(mRequestQueue.front())); // mRequestVec.pop_front(); // } auto concatted = std::string("Hello, world!, "); ImGui::Begin(concatted.c_str()); ImGui::Button("Look at this pretty button"); ImGui::End(); // mWindow.clear(); } void GuiManager::onKeyPressed(const sf::Keyboard::Key key) { if (key == sf::Keyboard::Escape) { mWindow.close(); } else { std::vector<uint8_t> bytesToPass; bytesToPass.push_back(1); const auto keyAsByte = static_cast<uint8_t>(key); spdlog::debug("keyAsByte: {}", keyAsByte); bytesToPass.push_back(keyAsByte); auto logicMsg = ThreadCom::commMsg(bytesToPass); spdlog::debug("Is pressed {}", key); mThreadComm->ship(2, logicMsg); } } void GuiManager::onKeyReleased(const sf::Keyboard::Key key) { if (key == sf::Keyboard::Escape) { mWindow.close(); } else { std::vector<uint8_t> bytesToPass; bytesToPass.push_back(0); const auto keyAsByte = static_cast<uint8_t>(key); spdlog::debug("keyAsByte: {}", keyAsByte); bytesToPass.push_back(keyAsByte); auto logicMsg = ThreadCom::commMsg(bytesToPass); spdlog::debug("Is released {}", key); mThreadComm->ship(2, logicMsg); } } void GuiManager::run() { //ImGui::SFML::Update(mWindow, mDeltaClock.restart()); // Running in new thread. Any other threads must set window to inactive mWindow.setActive(true); mWindow.setKeyRepeatEnabled(false); while (mWindow.isOpen()) { spdlog::set_level(spdlog::level::debug); sf::Event event{}; while (mWindow.pollEvent(event)) { ImGui::SFML::ProcessEvent(event); if (event.type == sf::Event::Closed) { mWindow.close(); } if (event.type == sf::Event::KeyPressed) { onKeyPressed(event.key.code);//NOLINT } if (event.type == sf::Event::KeyReleased) { onKeyReleased(event.key.code);//NOLINT } } // clear at regular intervals auto elapsed = mDeltaClock.getElapsedTime().asMilliseconds(); if (elapsed > 2) { update(); ImGui::SFML::Render(mWindow); mWindow.display(); } } ImGui::SFML::Shutdown(); mThreadComm->kill(); } }// namespace gman
[ "stephens2633@gmail.com" ]
stephens2633@gmail.com
bf31255f6f08a4b89826f90b7f9619873591835e
816480b413071d53e88b25ebca247395b911e695
/client/DLGQUESTIONEDIT.cpp
e3cd5393f490db35e06f13ea312271dd3d2cb8fb
[]
no_license
kabofang/ExamOnline
300ff7970b1ffb3dc87404a1297c263322c5957e
85ffe4bbf152c56047099800be58f5cd100566d7
refs/heads/master
2023-04-25T16:04:47.472366
2021-05-10T19:04:12
2021-05-10T19:04:12
365,757,882
0
0
null
null
null
null
GB18030
C++
false
false
2,599
cpp
// DLGQUESTIONEDIT.cpp : implementation file // #include "stdafx.h" #include "client.h" #include "DLGQUESTIONEDIT.h" #include "./netlib/message.h" #include "./xml/XmlNodeWrapper.h" // CDLGQUESTIONEDIT dialog IMPLEMENT_DYNAMIC(CDLGQUESTIONEDIT, CDialog) CDLGQUESTIONEDIT::CDLGQUESTIONEDIT(CWnd* pParent /*=NULL*/) : CDialog(CDLGQUESTIONEDIT::IDD, pParent) { } CDLGQUESTIONEDIT::~CDLGQUESTIONEDIT() { } void CDLGQUESTIONEDIT::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CDLGQUESTIONEDIT, CDialog) ON_BN_CLICKED(IDC_BUTTON1, OnBnClickedButton1) ON_BN_CLICKED(IDC_BUTTON3, OnBnClickedButton3) END_MESSAGE_MAP() // CDLGQUESTIONEDIT message handlers void CDLGQUESTIONEDIT::OnBnClickedButton1() { // TODO: Add your control notification handler code here SetDlgItemText(IDC_EDITBODY,""); SetDlgItemText(IDC_EDIT1,""); SetDlgItemText(IDC_EDIT2,""); SetDlgItemText(IDC_EDIT3,""); SetDlgItemText(IDC_EDIT4,""); } void CDLGQUESTIONEDIT::OnBnClickedButton3() { // TODO: Add your control notification handler code here CString strtext; GetDlgItemText(IDC_EDIT5,strtext); strtext.TrimLeft(); strtext.TrimRight(); if (strtext == "") { AfxMessageBox("答案不能为空!"); return; } CXmlDocumentWrapper xmlDoc;//存放XML包装类对象 xmlDoc.LoadXML("<QUESTIONINFO></QUESTIONINFO>"); CXmlNodeWrapper rootnode(xmlDoc.AsNode()); CXmlNodeWrapper node(rootnode.InsertNode(0,"BODY")); GetDlgItemText(IDC_EDITBODY,strtext); strtext.TrimLeft(); strtext.TrimRight(); node.SetText(strtext); CXmlNodeWrapper node_a(rootnode.InsertNode(1,"OPTIONA")); GetDlgItemText(IDC_EDIT1,strtext); strtext.TrimLeft(); strtext.TrimRight(); node_a.SetText(strtext); CXmlNodeWrapper node_b(rootnode.InsertNode(2,"OPTIONB")); GetDlgItemText(IDC_EDIT2,strtext); strtext.TrimLeft(); strtext.TrimRight(); node_b.SetText(strtext); CXmlNodeWrapper node_c(rootnode.InsertNode(3,"OPTIONC")); GetDlgItemText(IDC_EDIT3,strtext); strtext.TrimLeft(); strtext.TrimRight(); node_c.SetText(strtext); CXmlNodeWrapper node_d(rootnode.InsertNode(4,"OPTIOND")); GetDlgItemText(IDC_EDIT4,strtext); strtext.TrimLeft(); strtext.TrimRight(); node_d.SetText(strtext); CXmlNodeWrapper node_key(rootnode.InsertNode(5,"KEY")); GetDlgItemText(IDC_EDIT5,strtext); strtext.TrimLeft(); strtext.TrimRight(); node_key.SetText(strtext); if (DoMsgSend(MSG_MANAGE,MSG_QUESTION_SAVE,(char *)(LPCTSTR)xmlDoc.GetXML(),xmlDoc.GetXML().GetLength()+1) == false) AfxMessageBox("保存试题失败!"); else AfxMessageBox("保存试题成功!"); }
[ "447155821@qq.com" ]
447155821@qq.com
3e021d97311981fb5825d2f4ad46b60967f92d62
8dbfe09372d73aca4e192220661aa072cd6dfc9b
/NetworkChess/NetworkChess/include/chatClient.h
c86761b3ea9a18b6898a1f2429d1687295053711
[]
no_license
maximehelaine/NetworkChess
2bd17ab34eb8e94d7a3e961294fa62e20ec3674a
123f719cbe10dfbe5a05ab8b3c1e9c6cff46b9f8
refs/heads/master
2016-09-11T00:06:02.883720
2015-07-20T21:52:19
2015-07-20T21:52:19
37,647,169
0
0
null
null
null
null
UTF-8
C++
false
false
1,098
h
#ifndef _CHATCLIENT_H_ #define _CHATCLIENT_H_ #include <Winsock2.h> #include <string> #include <vector> #include <thread> #define MAX_BUFFER 255 class ChatClient { public: ChatClient(); ChatClient(const std::string& ip, unsigned short port); ChatClient(SOCKET sock, const std::string&); virtual ~ChatClient(); void connect(); void close(); bool send(const std::string& data); bool receive(std::string& buffer); SOCKET getSocket() const; std::string getIp() const; unsigned short getPort() const; const std::string& getName() const; std::string& getName(); bool isConnect() const; void setIp(const std::string&); void setPort(const unsigned short); void setName(const std::string&); void receiveLoop(); bool processCommandLine(const std::string&); protected: std::string m_name; SOCKET m_sock; std::string m_ip; unsigned short m_port; bool m_threadRunning; std::thread* m_thread; bool m_isConnect; void processClientSideMessage(const std::string&); }; #endif //_CHATCLIENT_H_
[ "mhelainedu91@live.fr" ]
mhelainedu91@live.fr
8815cd4825c89c297d9102fbfcd3edcd006a918a
04b1803adb6653ecb7cb827c4f4aa616afacf629
/third_party/android_crazy_linker/src/src/crazy_linker_thread_data.cpp
d685c429e3e9b8690a36b85abf7c13504e814be1
[ "BSD-3-Clause", "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
1,957
cpp
// Copyright 2014 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 "crazy_linker_thread_data.h" #include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <cstring> namespace { static pthread_key_t s_thread_key; static pthread_once_t s_once = PTHREAD_ONCE_INIT; static void ThreadDataDestroy(void* data) { free(data); } static void InitThreadKey() { pthread_key_create(&s_thread_key, ThreadDataDestroy); } } // namespace namespace crazy { void ThreadData::Init() { dlerror_ = dlerror_buffers_[0]; dlerror_[0] = '\0'; } void ThreadData::SwapErrorBuffers() { if (dlerror_ == dlerror_buffers_[0]) dlerror_ = dlerror_buffers_[1]; else dlerror_ = dlerror_buffers_[0]; dlerror_[0] = '\0'; } void ThreadData::SetErrorArgs(const char* fmt, va_list args) { if (fmt == NULL) { dlerror_[0] = '\0'; return; } vsnprintf(dlerror_, kBufferSize, fmt, args); } void ThreadData::AppendErrorArgs(const char* fmt, va_list args) { if (fmt == NULL) return; size_t len = strlen(dlerror_); vsnprintf(dlerror_ + len, kBufferSize - len, fmt, args); } ThreadData* GetThreadDataFast() { return reinterpret_cast<ThreadData*>(pthread_getspecific(s_thread_key)); } ThreadData* GetThreadData() { pthread_once(&s_once, InitThreadKey); ThreadData* data = GetThreadDataFast(); if (!data) { data = reinterpret_cast<ThreadData*>(calloc(sizeof(*data), 1)); data->Init(); pthread_setspecific(s_thread_key, data); } return data; } // Set the linker error string for the current thread. void SetLinkerErrorString(const char* str) { GetThreadData()->SetError(str); } // Set the formatted linker error for the current thread. void SetLinkerError(const char* fmt, ...) { va_list args; va_start(args, fmt); GetThreadData()->SetErrorArgs(fmt, args); va_end(args); } } // namespace crazy
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
931d020b5b5c5186b0b19b6f40cab3a756f3b6b7
c8dd74c797efce471b1092539daa8f0d7ac14204
/Bullet.cpp
140731074e185645632166b9abae2a85bcc9e099
[]
no_license
Haalk/MyProject3
3d7a97cf8254204f5e2240709e1735e7977275c9
618328c91ebfd58b3dd8b4685081e2382e65f107
refs/heads/master
2020-03-18T15:00:55.768318
2018-05-25T16:42:24
2018-05-25T16:42:24
134,881,682
0
0
null
null
null
null
UTF-8
C++
false
false
1,345
cpp
#include "Bullet.h" #include <iostream> #include <conio.h> Bullet::Bullet(const nDirection::edirection & dir, const COORD & coord) : b_dir(dir),b_Coord(coord),isKill(false) { } Bullet::~Bullet() { } bool Bullet::move(Field* field) { //if (field->isTank(b_Coord)) //GameOver(); SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), b_Coord); std::cout << " "; switch (b_dir) { case nDirection::edirection::LEFT: if (b_Coord.X > 1/*&& !field->isWall(b_Coord.X-1, b_Coord.Y)*/)b_Coord.X -= 1; else return false; break; case nDirection::edirection::RIGHT: if (b_Coord.X < SIZE_FIELD - 2 /*&& !field->isWall(b_Coord.X+1, b_Coord.Y)*/)b_Coord.X += 1; else return false; break; case nDirection::edirection::UP: if (b_Coord.Y > 1/* && !field->isWall(b_Coord.X, b_Coord.Y-1)*/)b_Coord.Y -= 1; else return false; break; case nDirection::edirection::DOWN: if (b_Coord.Y < SIZE_FIELD - 3 /*&& !field->isWall(b_Coord.X, b_Coord.Y+1)*/)b_Coord.Y += 1; else return false; break; default: break; } if (field->isTank(b_Coord)) GameOver(); SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), b_Coord); std::cout << "."; return true; } void Bullet::GameOver() { system("cls"); std::cout << "\n\n\t\t THANK YOU!!!"; _getch(); exit(0); }
[ "noreply@github.com" ]
noreply@github.com
eb9c441ec7c394ef14add15d8d04d04a4e9d4578
b2527ae73cc56f6aa7d0854acf6efb430b1bb68c
/Codeforces/Simple_problem.cpp
c50738b4dcf29a6a4107ea68721162d8d79e5b86
[]
no_license
TusharCSE35/Online-Programming
0538e478d67505ae9f77aaa51492308e6b0d2302
ea85e684b5032f4832fba6c21806bbed79fdc076
refs/heads/main
2023-06-02T08:52:32.174072
2021-06-15T19:58:25
2021-06-15T19:58:25
377,196,826
0
0
null
null
null
null
UTF-8
C++
false
false
3,980
cpp
/*********************************************************************************\ * _________ _ _ ________ _ _ __ ________ * * |___ ___|| | | || ______|| | | | / \ | ____ | * * | | | | | || |______ | |_____| | / /\ \ | |____| | * * | | | | | ||______ || _____ | / /__\ \ | __ __| * * | | | |____| | ______| || | | | / ______ \ | | \ \ * * |_| |________||________||_| |_| /_/ \_\ |_| \_\ * * * * Department of Computer Science & Engineering * * Student ID : 18CSE035 * * Bangabnadhu Sheikh Mujibur Rahman Science & Technology University,Gopalgonj. * * * \*********************************************************************************/ //Now Write to Code ___________________________ #include <bits/stdc++.h> using namespace std ; typedef long long ll; typedef long double ld; typedef unsigned long long ull; typedef pair<int,int> pii; typedef pair<ll,ll> pll; typedef vector<int> vi; typedef vector<ll> vll; typedef vector<vector<int>> vvi; inline int Int(){int x; cin >> x; return x;} inline ll Long(){ll x; cin >> x; return x;} inline float Float(){float x; cin >> x; return x;} inline double Double(){double x; cin >> x; return x;} inline void Yes(){cout << "Yes" << endl;} inline void No(){cout << "No" << endl;} inline void YES(){cout << "YES" << endl;} inline void NO(){cout << "NO" << endl;} const int N =(int)2e5 + 5; const int maxN =(int)1e6 + 6; const ll Mod =(ll)1e9 + 7; const int inf =(int)2e9; const ll Inf =(ll)1e18; #define fastio ios_base::sync_with_stdio(false),cin.tie(NULL) #define T int t,q; cin >> t; for(q=1;q<=t;q++) #define Forn(i,n) for(int i=0;i<n;i++) #define ForN(i,n) int i;for(i=n-1;n>=0;i--) #define forn(i,n) for(int i=1;i<=n;i++) #define forN(i,n) int i;for(i=n;n>=1;i--) #define fors(i,s) for(int i=0;i<s.size();i++) #define Sort(s) sort(s.begin(),s.end()) #define debug(x) cerr << #x << " = " << x << '\n' ; #define rep(i,b,e) for(__typeof(e) i=(b); i!=(e+1)-2*(b>e); i=i+1-2*(b>e)) #define gcd(a,b) __gcd(a , b) #define lcm(a,b) (a*(b/__gcd(a,b))) #define gt greater<int>() #define Int Int() #define Long Long() #define Float Float() #define Double Double() #define all(x) x.begin() , x.end() #define sz(x) (int)x.size() #define ff first #define ss second #define pb push_back #define eb emplace_back #define mp make_pair #define mem(a) memset(a,0,sizeof a) #define memn(a) memset(a,-1,sizeof a) #define biday return 0 #define nl endl #define sp(n) fixed<<setprecision(n) #define pi acos(-1) #define PI 3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342 int main() { int n,i,j,x=0; vll v; cin >> n; while(n) { if(n%10)v.pb(n%10); n/=10; } sort(v.begin(),v.end()); for(i=0; i<v.size(); i++)cout << v[i] << " "; cout << endl; for(i=0; i<v.size(); i++) { x=x*10+v[i]; } cout << x << endl; biday; } //...............BYE BYE................
[ "noreply@github.com" ]
noreply@github.com
158155f826f3a53557a5d4f605a83142d8d2f003
90c69083466ac513bbf9293d9bce463315895551
/src/LogisticRegression.cpp
65df904d4ea259441c1a45d37e09d1dcee95ec8d
[]
no_license
masedki/MHBinaryModelSelection
d300e0ebc2c3b1cada1cc3974a6ffcf96d36cffa
6d06094084ab2d6cb45ab220fee048fb7e4fb2db
refs/heads/master
2021-01-01T03:36:56.039640
2015-02-10T14:47:11
2015-02-10T14:47:11
26,183,232
0
0
null
null
null
null
UTF-8
C++
false
false
2,419
cpp
// // LogisticRegression.cpp // // // Created by sedki on 02/11/2014. // #include <RcppArmadillo.h> #include <RcppEigen.h> #include <Rcpp.h> using namespace std; using namespace Rcpp; using namespace arma; using namespace Eigen; #include "conversion.h" #include "LogisticRegression.h" LogisticRegression::LogisticRegression(NumericVector & yin, NumericMatrix & Xin, NumericVector & start) { convertVector<NumericVector,VectorXd>(yin, y); convertMatrix<NumericMatrix,MatrixXd>(Xin, X); this->n = X.rows(); this->p = X.cols(); convertVector<NumericVector,VectorXd>(start, beta); this->gradient.setZero(p); this->hessian.setZero(p, p); this->W.setZero(n,n); this->iter = 0; this->maxit = 5; this->tol = 1e-03; this->again = true; }; void LogisticRegression::ComputeGradient(){ VectorXd xb = X*beta; VectorXd pi = VectorXd::Zero(n); for(int i = 0; i < n; ++i) pi(i) = exp(xb(i))/(1+exp(xb(i))); VectorXd tmp = y - pi; gradient = X.transpose()*tmp; for(int i = 0; i < n; ++i) W(i,i) = pi(i)*(1 - pi(i)); }; void LogisticRegression::ComputeHessian() { hessian = (X.transpose()*W)*X; }; void LogisticRegression::NewtonRaphsonUpdate() { iter++; VectorXd oldbeta(beta); LLT<MatrixXd> llt; llt.compute(hessian); //beta += hessian.ldlt().solve(gradient); //A.ldlt().solve(b)) beta += llt.solve(gradient); if(((beta.array() - oldbeta.array()).array().abs().sum()/p < tol) || (iter > maxit)) again = false; }; // VectorXd LogisticRegression::ShowCoefficient() { return(beta); }; // // bool LogisticRegression::Continue() { return(again); } // long double LogisticRegression::twiceloglik() { VectorXd xb = X*beta; long double l = 2 * (y.array()*xb.array() - (VectorXd::Ones(n).array() + xb.array().exp()).array().log()).sum(); return(l); }; // // void LogisticRegression::Run() { while(Continue()==true) { ComputeGradient(); ComputeHessian(); NewtonRaphsonUpdate(); } }; // //[[Rcpp::export]] List RcppLogisticRegression(NumericVector & Y, NumericMatrix & X, NumericVector & beta) { LogisticRegression myReg(Y,X,beta); while(myReg.Continue()==true) { myReg.ComputeGradient(); myReg.ComputeHessian(); myReg.NewtonRaphsonUpdate(); } return List::create(Named("twiceloglik") = myReg.twiceloglik(), Named("coefficients") = myReg.ShowCoefficient()); };
[ "masedki@gmail.com" ]
masedki@gmail.com
dd3eb15d4ab9e801704b068a1aad0e7135bba046
1e69512209ce418956253f7b5ca5a64c169f363a
/user_interface.cpp
c50b286cd76b32f65a8257a9ae0542112628f6b4
[]
no_license
TejBirring8/LCDTest
cdf8da7b1bb707d07acaf2b2343f05cf9cfb36b0
918c338c5d8a142ab51743bb3d6b2d65c716e804
refs/heads/master
2023-03-21T01:12:59.577652
2021-03-04T23:47:38
2021-03-04T23:47:38
204,681,326
1
0
null
null
null
null
UTF-8
C++
false
false
1,258
cpp
#include <vector> #include <string> #include <iostream> #include <algorithm> #include "user_interface.h" using namespace std; string UserInterface::ask_multichoice_question( const string& question, vector<string>& possible_answers ) { cout << question << endl << endl; int count = 1; for(vector<string>::iterator it = possible_answers.begin(); it != possible_answers.end(); ++it) { string& str = *it; cout << "[" << count << "] " << *it << endl << endl; ++count; // convert to lowercase for comparison/validation sake transform(str.begin(), str.end(), str.begin(), ::tolower); } ask_again: cout << "Please enter your answer: " ; string ins = ""; cin >> ins; cout << endl; // repeat if inappropriate answer bool is_valid_answer = false; transform(ins.begin(), ins.end(), ins.begin(), ::tolower); for(vector<string>::iterator it = possible_answers.begin(); it != possible_answers.end(); ++it) { if ( ins.compare(*it) == 0 ) is_valid_answer = true; } if (!is_valid_answer) goto ask_again; // return valid possible answer entered by user return ins; }
[ "tejbirring8@gmail.com" ]
tejbirring8@gmail.com
dfe2e7625047f291e8c2ed1397645a1a8ec3762e
0d9c7b3fabae7322aa97cd022d5de30a350ae3f8
/src/charge.h
fe2b45fd5619d55fc7822fc3b696fed5cf0f3fad
[]
no_license
zixiaoqt/Bit-Park
9639b78bf131777ed500c1a7e93c18960fe6eb16
9b397feb171fb90c00c64af14af63e9bd7d5f889
refs/heads/master
2016-09-13T19:50:29.911646
2016-04-14T06:43:56
2016-04-14T06:43:56
56,211,792
3
1
null
null
null
null
UTF-8
C++
false
false
2,142
h
#ifndef _VIP_CHARGE_H__ #define _VIP_CHARGE_H__ #include <functional> #include "passvehicle.h" #include "database.h" #include "define.h" #include "transaction.h" namespace parkingserver { class Charge { public: Charge(const PassVehicle& enter_vehicle, const PassVehicle& exit_vehicle, const VIPVehicle& vip, Json::Value& json); virtual ~Charge() = default; virtual void CalCharge() = 0; void SetFreeTimeMode(int mode) { freetime_mode_ = mode; } void SetChargePattern(int pattern) { charge_pattern_ = pattern; } void SetTranscation(Transaction* transaction) { transaction_ = transaction; } ParkingType GetParkingType() const {return parking_type_;} protected: void BuildChargeJson(double charge, double require_charge); // 按照进场和出场实际计费 void ChargeByTimeDuration(time_t enter_time, time_t exit_time); void ChargeByAccessTime(); // 自动放行详单 void BuildAutoChargeBill(); // 免费时段账单 void FreeDurationBill(time_t begint_time, time_t end_time); // 自动放行的收费入库 void RecordAutoCharge(double charge, PayType pay_type, double remain_money); void ChargeAutoInsertDB(); // 计算具有时效性的VIP费用,依据车辆进场时间和出场时间与VIP有效时间的关系分为6种情况 // vip生效时间 vip失效时间 // o---------o // 1. o----o // 2. o------o // 3. o-------------------------------o // 4. o-----o // 5. o--------o // 6. o-------o void CalTimeBasedVIPCharge(); protected: const PassVehicle& enter_vehicle_; const PassVehicle& exit_vehicle_; VIPVehicle vip_; Json::Value& json_; Bill bill_; std::string charge_id_; int park_position_ = 0; ParkingType parking_type_ = TEMPORARY_VEHICLE_PARKING; double remain_money_ = 0; int freetime_mode_; int charge_pattern_; Transaction* transaction_; }; } #endif
[ "2967732156@qq.com" ]
2967732156@qq.com
79c015090598ba36d40ae35fc295fae76a495f6e
2ccc39b3699159e045e5e9b54cf7c73fcb3030da
/node_modules/macos-notification-state/lib/notificationstate.cc
d2edf7a0b218f7fe566ffafe9f8739eca8909270
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "LicenseRef-scancode-public-domain", "CC0-1.0" ]
permissive
bgamut/squwbsmastering
f451db6a5c14c1ca5a4f6d0bceaea13229f178d2
40c0a7e22240f5eed7d22d6011deedd2421f9685
refs/heads/master
2022-12-11T05:36:00.923749
2019-11-21T07:31:00
2019-11-21T07:31:00
157,075,959
0
0
CC0-1.0
2022-12-10T09:35:20
2018-11-11T12:11:17
HTML
UTF-8
C++
false
false
1,250
cc
#include <node.h> #include <v8.h> #ifdef TARGET_OS_MAC #include "notificationstate-query.h" #include "do-not-disturb.h" #endif using namespace v8; void _QueryUserSessionState(const v8::FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); int returnValue = -1; #ifdef TARGET_OS_MAC returnValue = queryUserSessionState(); #endif args.GetReturnValue().Set(Int32::New(isolate, returnValue)); } void _GetDoNotDisturb(const v8::FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); int returnValue = -1; #ifdef TARGET_OS_MAC bool dnd = getDoNotDisturb(); if (dnd) { returnValue = 1; } else { returnValue = 0; } #endif args.GetReturnValue().Set(Int32::New(isolate, returnValue)); } void Init(Handle<Object> exports) { Isolate* isolate = Isolate::GetCurrent(); exports->Set(String::NewFromUtf8(isolate, "getNotificationState"), FunctionTemplate::New(isolate, _QueryUserSessionState)->GetFunction()); exports->Set(String::NewFromUtf8(isolate, "getDoNotDisturb"), FunctionTemplate::New(isolate, _GetDoNotDisturb)->GetFunction()); } NODE_MODULE(notificationstate, Init)
[ "bgamut@gmail.com" ]
bgamut@gmail.com
8892a0b2c377360538232d40d3a28d7989240299
d9d118f4f1d626a750897babce33b3ce34f11575
/x451/TML_X0_FIDL/HMI/gen/dbus/consumes/v1/com/harman/pres/aaprescontrolsDBusProxy.cpp
f788513f0ccb26bafdd8fd8cdd229b5e7be5a384
[]
no_license
HNarayana-youCanDoIt/Testproject
39af23d3ee4c2a413670c3dcd68dbd41424bbe91
226795327f50102989dfc8e12174823dddc2aa68
refs/heads/master
2023-03-26T05:57:57.044706
2021-03-31T11:14:53
2021-03-31T11:14:53
353,326,120
0
0
null
null
null
null
UTF-8
C++
false
false
11,511
cpp
/* * This file was generated by the CommonAPI Generators. * Used org.genivi.commonapi.dbus 3.1.5. * Used org.franca.core 0.9.1.201412191134. * * generated by DCIF CodeGen Version: R2_v2.1.0 * generated on: Wed Oct 30 12:44:55 IST 2019 */ #include <v1/com/harman/pres/aaprescontrolsDBusProxy.hpp> namespace v1 { namespace com { namespace harman { namespace pres { std::shared_ptr<CommonAPI::DBus::DBusProxy> createaaprescontrolsDBusProxy( const CommonAPI::DBus::DBusAddress &_address, const std::shared_ptr<CommonAPI::DBus::DBusProxyConnection> &_connection) { return std::make_shared<aaprescontrolsDBusProxy>(_address, _connection); } INITIALIZER(registeraaprescontrolsDBusProxy) { CommonAPI::DBus::Factory::get()->registerProxyCreateMethod( aaprescontrols::getInterface(), &createaaprescontrolsDBusProxy); } aaprescontrolsDBusProxy::aaprescontrolsDBusProxy( const CommonAPI::DBus::DBusAddress &_address, const std::shared_ptr<CommonAPI::DBus::DBusProxyConnection> &_connection) : CommonAPI::DBus::DBusProxy(_address, _connection) , session_(*this, "onSessionAttributeChanged", "(sssbiib)", "getSessionAttribute", static_cast<::v1::com::harman::pres::pprestypes_::sSessionDetailsDeployment_t*>(nullptr)), deviceInfo_(*this, "onDeviceInfoAttributeChanged", "a(sssbi)", "getDeviceInfoAttribute", static_cast<CommonAPI::DBus::ArrayDeployment<::v1::com::harman::pres::pprestypes_::sDevDetailsDeployment_t>*>(nullptr)), batteryInfo_(*this, "onBatteryInfoAttributeChanged", "(iib)", "getBatteryInfoAttribute", static_cast<::v1::com::harman::pres::pprestypes_::sBatteryLevelInfoDeployment_t*>(nullptr)), playbackStatus_(*this, "onPlaybackStatusAttributeChanged", "(isubbb)", "getPlaybackStatusAttribute", static_cast<::v1::com::harman::pres::pprestypes_::sMediaPlaybackStatusUpdateDeployment_t*>(nullptr)), songNode_(*this, "onSongNodeAttributeChanged", "(sssssu)", "getSongNodeAttribute", static_cast<::v1::com::harman::pres::pprestypes_::sSongNodeUpdateDeployment_t*>(nullptr)), metadata_(*this, "onMetadataAttributeChanged", "(sssssui)", "getMetadataAttribute", static_cast<::v1::com::harman::pres::pprestypes_::sMetaDataUpdateDeployment_t*>(nullptr)), turnInfo_(*this, "onTurnInfoAttributeChanged", "(siisii)", "getTurnInfoAttribute", static_cast<::v1::com::harman::pres::pprestypes_::sNaviNextTurnInfoDeployment_t*>(nullptr)), turnDistInfo_(*this, "onTurnDistInfoAttributeChanged", "(iiii)", "getTurnDistInfoAttribute", static_cast<::v1::com::harman::pres::pprestypes_::sNaviNextTurnDistInfoDeployment_t*>(nullptr)), navFocusType_(*this, "onNavFocusTypeAttributeChanged", "i", "getNavFocusTypeAttribute", static_cast<CommonAPI::EmptyDeployment*>(nullptr)), navStatusType_(*this, "onNavStatusTypeAttributeChanged", "i", "getNavStatusTypeAttribute", static_cast<CommonAPI::EmptyDeployment*>(nullptr)) { } aaprescontrolsDBusProxy::SessionAttribute& aaprescontrolsDBusProxy::getSessionAttribute() { return session_; } aaprescontrolsDBusProxy::DeviceInfoAttribute& aaprescontrolsDBusProxy::getDeviceInfoAttribute() { return deviceInfo_; } aaprescontrolsDBusProxy::BatteryInfoAttribute& aaprescontrolsDBusProxy::getBatteryInfoAttribute() { return batteryInfo_; } aaprescontrolsDBusProxy::PlaybackStatusAttribute& aaprescontrolsDBusProxy::getPlaybackStatusAttribute() { return playbackStatus_; } aaprescontrolsDBusProxy::SongNodeAttribute& aaprescontrolsDBusProxy::getSongNodeAttribute() { return songNode_; } aaprescontrolsDBusProxy::MetadataAttribute& aaprescontrolsDBusProxy::getMetadataAttribute() { return metadata_; } aaprescontrolsDBusProxy::TurnInfoAttribute& aaprescontrolsDBusProxy::getTurnInfoAttribute() { return turnInfo_; } aaprescontrolsDBusProxy::TurnDistInfoAttribute& aaprescontrolsDBusProxy::getTurnDistInfoAttribute() { return turnDistInfo_; } aaprescontrolsDBusProxy::NavFocusTypeAttribute& aaprescontrolsDBusProxy::getNavFocusTypeAttribute() { return navFocusType_; } aaprescontrolsDBusProxy::NavStatusTypeAttribute& aaprescontrolsDBusProxy::getNavStatusTypeAttribute() { return navStatusType_; } /** * description: Message indicates that the AndroidAuto session is requested */ void aaprescontrolsDBusProxy::startProjection(const std::string &_appUrl, const ::v2::com::harman::pres::aaprestypes::sTransportInfo &_tranportInfo, const ::v2::com::harman::pres::aaprestypes::enTransportType &_type, CommonAPI::CallStatus &_internalCallStatus) { CommonAPI::Deployable<std::string, CommonAPI::DBus::StringDeployment> deploy_appUrl(_appUrl, static_cast<CommonAPI::DBus::StringDeployment*>(nullptr)); CommonAPI::Deployable<::v2::com::harman::pres::aaprestypes::sTransportInfo, ::v2::com::harman::pres::aaprestypes_::sTransportInfoDeployment_t> deploy_tranportInfo(_tranportInfo, static_cast<::v2::com::harman::pres::aaprestypes_::sTransportInfoDeployment_t*>(nullptr)); CommonAPI::Deployable<::v2::com::harman::pres::aaprestypes::enTransportType, CommonAPI::EmptyDeployment> deploy_type(_type, static_cast<CommonAPI::EmptyDeployment*>(nullptr)); CommonAPI::DBus::DBusProxyHelper< CommonAPI::DBus::DBusSerializableArguments< CommonAPI::Deployable<std::string, CommonAPI::DBus::StringDeployment >, CommonAPI::Deployable<::v2::com::harman::pres::aaprestypes::sTransportInfo, ::v2::com::harman::pres::aaprestypes_::sTransportInfoDeployment_t >, CommonAPI::Deployable<::v2::com::harman::pres::aaprestypes::enTransportType, CommonAPI::EmptyDeployment > >, CommonAPI::DBus::DBusSerializableArguments< > >::callMethod( *this, "startProjection", "s((iis)(ss))i", deploy_appUrl, deploy_tranportInfo, deploy_type, _internalCallStatus); } void aaprescontrolsDBusProxy::stopProjection(const std::string &_appUrl, CommonAPI::CallStatus &_internalCallStatus) { CommonAPI::Deployable<std::string, CommonAPI::DBus::StringDeployment> deploy_appUrl(_appUrl, static_cast<CommonAPI::DBus::StringDeployment*>(nullptr)); CommonAPI::DBus::DBusProxyHelper< CommonAPI::DBus::DBusSerializableArguments< CommonAPI::Deployable<std::string, CommonAPI::DBus::StringDeployment > >, CommonAPI::DBus::DBusSerializableArguments< > >::callMethod( *this, "stopProjection", "s", deploy_appUrl, _internalCallStatus); } /** * description: This request method allows client to request for the Projection screen * show : true - show false - hide , If false client can disregard layer and * appUrl appUrl : URL identifier of the desired application to launch Blank * String: native screen will be launched other apps: tbd */ void aaprescontrolsDBusProxy::requestProjection(const std::string &_appUrl, CommonAPI::CallStatus &_internalCallStatus) { CommonAPI::Deployable<std::string, CommonAPI::DBus::StringDeployment> deploy_appUrl(_appUrl, static_cast<CommonAPI::DBus::StringDeployment*>(nullptr)); CommonAPI::DBus::DBusProxyHelper< CommonAPI::DBus::DBusSerializableArguments< CommonAPI::Deployable<std::string, CommonAPI::DBus::StringDeployment > >, CommonAPI::DBus::DBusSerializableArguments< > >::callMethod( *this, "requestProjection", "s", deploy_appUrl, _internalCallStatus); } /** * description: Method to request for the screen hide switchReason : reason for switching out * of the android auto screen , refer enum values */ void aaprescontrolsDBusProxy::requestNative(const ::v2::com::harman::pres::aaprestypes::eScreenSwitchReason &_switchReason, CommonAPI::CallStatus &_internalCallStatus) { CommonAPI::Deployable<::v2::com::harman::pres::aaprestypes::eScreenSwitchReason, CommonAPI::EmptyDeployment> deploy_switchReason(_switchReason, static_cast<CommonAPI::EmptyDeployment*>(nullptr)); CommonAPI::DBus::DBusProxyHelper< CommonAPI::DBus::DBusSerializableArguments< CommonAPI::Deployable<::v2::com::harman::pres::aaprestypes::eScreenSwitchReason, CommonAPI::EmptyDeployment > >, CommonAPI::DBus::DBusSerializableArguments< > >::callMethod( *this, "requestNative", "i", deploy_switchReason, _internalCallStatus); } /** * description: WIFI_AA Method to request connection to a wireless android device */ void aaprescontrolsDBusProxy::connect(const std::string &_btAddr, CommonAPI::CallStatus &_internalCallStatus) { CommonAPI::Deployable<std::string, CommonAPI::DBus::StringDeployment> deploy_btAddr(_btAddr, static_cast<CommonAPI::DBus::StringDeployment*>(nullptr)); CommonAPI::DBus::DBusProxyHelper< CommonAPI::DBus::DBusSerializableArguments< CommonAPI::Deployable<std::string, CommonAPI::DBus::StringDeployment > >, CommonAPI::DBus::DBusSerializableArguments< > >::callMethod( *this, "connect", "s", deploy_btAddr, _internalCallStatus); } /** * description: WIFI_AA Method allows client to request for disconnection of current active * device */ void aaprescontrolsDBusProxy::disconnect(CommonAPI::CallStatus &_internalCallStatus) { CommonAPI::DBus::DBusProxyHelper< CommonAPI::DBus::DBusSerializableArguments< >, CommonAPI::DBus::DBusSerializableArguments< > >::callMethod( *this, "disconnect", "", _internalCallStatus); } /** * description: WIFI_AA Method allows client to request for the deletion of the device from * the wireless androidauto device list */ void aaprescontrolsDBusProxy::deleteDevice(const std::string &_btAddr, CommonAPI::CallStatus &_internalCallStatus) { CommonAPI::Deployable<std::string, CommonAPI::DBus::StringDeployment> deploy_btAddr(_btAddr, static_cast<CommonAPI::DBus::StringDeployment*>(nullptr)); CommonAPI::DBus::DBusProxyHelper< CommonAPI::DBus::DBusSerializableArguments< CommonAPI::Deployable<std::string, CommonAPI::DBus::StringDeployment > >, CommonAPI::DBus::DBusSerializableArguments< > >::callMethod( *this, "deleteDevice", "s", deploy_btAddr, _internalCallStatus); } /** * description: WIFI_AA This request method allows client to request for cancelling the * ongoing connect process. */ void aaprescontrolsDBusProxy::cancelConnect(CommonAPI::CallStatus &_internalCallStatus) { CommonAPI::DBus::DBusProxyHelper< CommonAPI::DBus::DBusSerializableArguments< >, CommonAPI::DBus::DBusSerializableArguments< > >::callMethod( *this, "cancelConnect", "", _internalCallStatus); } void aaprescontrolsDBusProxy::getOwnVersion(uint16_t& ownVersionMajor, uint16_t& ownVersionMinor) const { ownVersionMajor = 1; ownVersionMinor = 1; } } // namespace pres } // namespace harman } // namespace com } // namespace v1
[ "hemanthakumar.narayana@harman.com" ]
hemanthakumar.narayana@harman.com
fb303585183c58defe71fec1c5be280fc328932a
661cb6c861c76049a79250d2c881946badf6e038
/Source/Survival/Objects/ObjectReplicated.cpp
34013a6d494794fe7be34810de01a266dd69a222
[]
no_license
SergeyFi/Survival
28d1d6aec12d1b6caa2d33d532df1a6ce3e20447
be44c264a4472af0a96eef42e249427704e825ab
refs/heads/master
2022-12-25T23:05:13.121210
2020-10-02T17:46:53
2020-10-02T17:46:53
297,156,823
0
0
null
null
null
null
UTF-8
C++
false
false
117
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "ObjectReplicated.h"
[ "fearthunder@yandex.ru" ]
fearthunder@yandex.ru
be4ce2af4e1818eb77b0e330cabfe0a6919f0a68
72f2992a3659ff746ba5ce65362acbe85a918df9
/apps-src/apps/external/zxing/pdf417/PDFReader.h
6ec25ed1a45df6da9680f38e180d180418e0d9d2
[ "BSD-2-Clause" ]
permissive
chongtianfeiyu/Rose
4742f06ee9ecd55f9717ac6378084ccf8bb02a15
412175b57265ba2cda1e33dd2047a5a989246747
refs/heads/main
2023-05-23T14:03:08.095087
2021-06-19T13:23:58
2021-06-19T14:00:25
391,238,554
0
1
BSD-2-Clause
2021-07-31T02:39:25
2021-07-31T02:39:24
null
UTF-8
C++
false
false
1,005
h
#pragma once /* * Copyright 2016 Nu-book Inc. * Copyright 2016 ZXing authors * * 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 "Reader.h" #include <list> namespace ZXing { namespace Pdf417 { /** * This implementation can detect and decode PDF417 codes in an image. * * @author Guenther Grau */ class Reader : public ZXing::Reader { public: Result decode(const BinaryBitmap& image) const override; std::list<Result> decodeMultiple(const BinaryBitmap& image) const; }; } // Pdf417 } // ZXing
[ "service@leagor.com" ]
service@leagor.com
6b29f32d14f0e8d28a6e7333a8bcf0a42f8594b4
a0b0d3e00f838d780b2b231a7668e4a3a360be64
/day08/qt_day7_homework_charclient/main.cpp
95a8096d05be423ef16eed44d6b48d8704ccd235
[]
no_license
hewei-bit/QT-Learing
d5ba754b2f6dec4fb18e085766a6b1e2b394111f
d5c1c4cb8d15237b1c21eda4385bd661068b545e
refs/heads/master
2022-11-26T05:06:18.491108
2020-08-02T07:20:37
2020-08-02T07:20:37
275,719,032
0
0
null
null
null
null
UTF-8
C++
false
false
172
cpp
#include "charclient.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); CharClient w; w.show(); return a.exec(); }
[ "1003826976@qq.com" ]
1003826976@qq.com
bba118e4b9f83662bb7713328563ddda81e06c5d
d16985a72e39109c30b1e975007cc1cabe8a6ac8
/Common/Packets/CLAskCreateCode.cpp
40c563a3eff96c91e6f2c45bdabc5939919bd4a1
[]
no_license
uvbs/wx2Server
e878c3c5c27715a0a1044f6b3229960d36eff4b4
78a4b693ac018a4ae82e7919f6e29c97b92554ab
refs/heads/master
2021-01-18T00:06:34.770227
2013-12-13T09:18:54
2013-12-13T09:18:54
43,288,843
2
3
null
2015-09-28T08:24:45
2015-09-28T08:24:44
null
UTF-8
C++
false
false
824
cpp
#include "stdafx.h" #include "CLAskCreateCode.h" BOOL CLAskCreateCode::Read( SocketInputStream& iStream ) { __ENTER_FUNCTION iStream.Read( (CHAR*)(&m_AskType), sizeof(BYTE)); if(CREATECODE_SEND==m_AskType) { iStream.Read((CHAR*)(&m_Answer), sizeof(CreateCode)); } return TRUE ; __LEAVE_FUNCTION return FALSE ; } BOOL CLAskCreateCode::Write( SocketOutputStream& oStream )const { __ENTER_FUNCTION oStream.Write( (CHAR*)(&m_AskType), sizeof(BYTE)); if(CREATECODE_SEND==m_AskType) { oStream.Write((CHAR*)(&m_Answer), sizeof(CreateCode)); } return TRUE ; __LEAVE_FUNCTION return FALSE ; } UINT CLAskCreateCode::Execute( Player* pPlayer ) { __ENTER_FUNCTION return CLAskCreateCodeHandler::Execute( this, pPlayer ) ; __LEAVE_FUNCTION return FALSE ; }
[ "tangming032@outlook.com" ]
tangming032@outlook.com
0d1bcf827d63b84c739fa01562513f89d9de42f6
7f62f204ffde7fed9c1cb69e2bd44de9203f14c8
/DboClient/Tool/GUIEditor/GUIFileView.cpp
681c56c1f2b5056a6f7f9af6af4e0d8217de5b17
[]
no_license
4l3dx/DBOGLOBAL
9853c49f19882d3de10b5ca849ba53b44ab81a0c
c5828b24e99c649ae6a2953471ae57a653395ca2
refs/heads/master
2022-05-28T08:57:10.293378
2020-05-01T00:41:08
2020-05-01T00:41:08
259,094,679
3
3
null
2020-04-29T17:06:22
2020-04-26T17:43:08
null
UHC
C++
false
false
1,946
cpp
// GUIFileView.cpp : 구현 파일입니다. // #include "stdafx.h" #include "GUIEditor.h" #include "GUIFileView.h" #include ".\guifileview.h" CGUIFileView* g_pFileView = NULL; // CGUIFileView IMPLEMENT_DYNCREATE(CGUIFileView, CView) CGUIFileView::CGUIFileView() { } CGUIFileView::~CGUIFileView() { } BEGIN_MESSAGE_MAP(CGUIFileView, CView) ON_WM_SIZE() END_MESSAGE_MAP() // CGUIFileView 그리기입니다. void CGUIFileView::OnDraw(CDC* pDC) { CDocument* pDoc = GetDocument(); // TODO: 여기에 그리기 코드를 추가합니다. } // CGUIFileView 진단입니다. #ifdef _DEBUG void CGUIFileView::AssertValid() const { CView::AssertValid(); } void CGUIFileView::Dump(CDumpContext& dc) const { CView::Dump(dc); } #endif //_DEBUG // CGUIFileView 메시지 처리기입니다. BOOL CGUIFileView::Create(LPCTSTR lpszClassName, LPCTSTR lpszWindowName, DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID, CCreateContext* pContext) { // TODO: 여기에 특수화된 코드를 추가 및/또는 기본 클래스를 호출합니다. BOOL bRet; bRet = CWnd::Create(lpszClassName, lpszWindowName, dwStyle, rect, pParentWnd, nID, pContext); // this part creates the TreeCtrl and use the CLeftView // as his parent Window if ( m_DirTree.m_hWnd == NULL && bRet ) { bRet = m_DirTree.Create( WS_CHILD | TVS_LINESATROOT | TVS_HASBUTTONS | WS_VISIBLE | TVS_HASLINES, CRect(0, 0, 0, 0), this, ID_TREECTRL ); if ( bRet ) //m_DirTree.DisplayTree( "Z:\\DBO-X\\DboTest\\texture\\gui", TRUE ); m_DirTree.DisplayTree( NULL, TRUE ); } return bRet; //return CView::Create(lpszClassName, lpszWindowName, dwStyle, rect, pParentWnd, nID, pContext); } void CGUIFileView::OnSize(UINT nType, int cx, int cy) { CView::OnSize(nType, cx, cy); // TODO: 여기에 메시지 처리기 코드를 추가합니다. if ( m_DirTree.m_hWnd ) m_DirTree.SetWindowPos( NULL, 0, 0, cx, cy, SWP_NOZORDER | SWP_NOMOVE ); }
[ "64261665+dboguser@users.noreply.github.com" ]
64261665+dboguser@users.noreply.github.com
7284801cdc11390ab6b1b085d3891df035d67963
f7b2b9c4231dc482353d8f29ae7906052bfb6cdc
/Count Primes/main.cpp
4944cc73ce77708902dc1676db26bdb6e1a81cfd
[]
no_license
llluiop/cppleetcode
e18c25e5d83629792bfab48a5252eb6407a2a650
249e5731515065352d91efe689385636e8553894
refs/heads/master
2020-04-04T05:50:30.660708
2019-11-24T02:53:55
2019-11-24T02:53:55
46,335,048
0
0
null
null
null
null
UTF-8
C++
false
false
985
cpp
#include <iostream> #include <math.h> #include <vector> using namespace std; class Solution { public: //time limit exceeded // int countPrimes(int n) { // if (n <= 1) // { // return 0; // } // // int count = 0; // // for (int i = 2; i <= n; i++) // { // int j = 2; // bool isPrime = true; // while (j <= sqrt(i)) // { // if (i % j == 0) // { // isPrime = false; // break; // } // // ++j; // } // // if (isPrime) // { // ++count; // } // } // // return count; // } int countPrimes(int n) { vector<bool> b(n); for (int i = 2; i*i < n; i++) { if (!b[i]) { for (int j = i; j * i < n; j++) { b[i*j] = true; } } } int c = 0; for (int i = 2; i < n; i++) { if (!b[i]) { ++c; } } return c; } }; int main() { Solution s; cout << s.countPrimes(3); return getchar(); }
[ "290522165@163.com" ]
290522165@163.com
6ceb6ea5c073db227c691a66e5a563da73dac61d
eb6f8317c6c361e05df91ae16fd66ecf3a3a8b01
/cplusplus/数据结构/哈夫曼树/哈弗曼编码.cpp
5df5805f3cb43f9006ada2d0fb14011086e31bb8
[]
no_license
Joey-Liu/online-judge-old-version
b00a12ec2da0053c461e914433ccb6760f7e8c50
c452ecee203c20e2856faa8ef876ad855e6c8957
refs/heads/master
2020-03-16T00:53:56.668165
2018-10-28T02:54:28
2018-10-28T02:54:28
132,428,000
1
0
null
null
null
null
GB18030
C++
false
false
2,155
cpp
#include<iostream> #include<stdio.h> #include<stdlib.h> typedef struct { char ch; unsigned int weight; unsigned int parent,lchild,rchild; }HTNode,*HuffmanTree; typedef char** HuffmanCode; #define N 8 void HuffmanCoding(HuffmanTree &HT,HuffmanCode &HC,int *w,int n,char d[]); int main() { int w[N]={5,29,7,8,14,23,3,11}; char d[N+1]="abcdefgh"; int i,n=8; i=1; HuffmanTree HT=NULL; HuffmanCode HC; HuffmanCoding(HT,HC,w,n,d); for(i=1;i<=n;i++) printf("%c:%s\n",HT[i].ch,HC[i]); system("pause"); return 0; } void HuffmanCoding(HuffmanTree &HT,HuffmanCode &HC,int *w,int n,char d[]) //w存放n个字符的权值 { if(n<=1) { printf("不用编码\n"); system("pause"); exit(1); } int m,i,j; //一共n个叶子节点 HuffmanTree p=NULL; m=2*n-1; HT=(HuffmanTree)malloc((m+1)*sizeof(HTNode)); for(i=1; i<=n; i++) { HT[i].weight = w[i-1]; HT[i].ch=d[i-1]; HT[i].parent = 0; HT[i].lchild = HT[i].rchild = 0; } HT[i].lchild = HT[i].rchild = 0; for(;i<=m; ++i) { HT[i].parent = 0; } for(i=n+1;i<=m;i++) //开始建哈夫曼树 { int s1=0,s2; //存储权值最小的两个数 for(j=1;j<m;j++) { if(HT[j].parent==0&&0==s1) {s1=j;continue;} if(HT[j].parent==0) {s2=j;break;} } for(j=s2;j<i;j++) //注意j<i { if(HT[j].parent==0) { if(HT[j].weight<HT[s1].weight) { s2=s1; s1=j; } else if(HT[j].weight<HT[s2].weight) s2=j; } }//挑选出权值最小的两个节点 //printf("s1=%d,s2=%d\n",s1,s2); // HT[s1].parent=i; HT[s2].parent=i; HT[i].lchild=s1; HT[i].rchild=s2; HT[i].weight=HT[s1].weight+HT[s2].weight; //printf("i=%d,weight=%d\n",i,HT[i].weight); } HC=(char**)malloc((n+1)*sizeof(char*)); char* cd=(char*)malloc(n*sizeof(char)); cd[n-1]='\0'; int start,f,c; for(i=1;i<=n;i++) { start=n-1; for(c=i,f=HT[i].parent;f!=0;c=f,f=HT[f].parent) { if(HT[f].lchild==c) cd[--start]='0'; else cd[--start]='1'; } HC[i]=(char*)malloc((n-start)*sizeof(char)); strcpy(HC[i],&cd[start]); } free(cd); }
[ "joey_liucoder@163.com" ]
joey_liucoder@163.com
1d7dbfe400915f739d43b7c780d439c938f97841
d41e7e050095b111c05b7b3c7da3953e0686744a
/ソース/souce/dx11mathutil.h
d0c9c4975d394e0d63a69772a00bd36cc20f4cce
[]
no_license
mizu9972/ParticleEditter
e4fe4daf0c99de84538e97a41da8cb7daa53b655
73762beffc94f4c5693dfe60cda9a7c48a4e3aee
refs/heads/master
2020-09-24T10:35:05.855449
2020-02-17T11:41:54
2020-02-17T11:41:54
225,740,701
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,750
h
#pragma once #include <DirectXMath.h> using namespace DirectX; struct PLANE { float a, b, c, d; }; void DX11MakeWorldMatrix(XMFLOAT4X4& mat, XMFLOAT3& angle, XMFLOAT3& trans); void DX11Vec3MulMatrix(DirectX::XMFLOAT3& outvec, const DirectX::XMFLOAT3& invec, const DirectX::XMFLOAT4X4& mat); void DX11Vec3Cross(DirectX::XMFLOAT3& outvec, DirectX::XMFLOAT3& invec1, DirectX::XMFLOAT3& invec2); void DX11Vec3Dot(float& dot, const DirectX::XMFLOAT3& invec1, const DirectX::XMFLOAT3& invec2); void DX11Vec3Normalize(DirectX::XMFLOAT3& outvec, DirectX::XMFLOAT3& invec); void DX11MtxIdentity(DirectX::XMFLOAT4X4& mat); void DX11GetQtfromMatrix(const XMFLOAT4X4& mat, XMFLOAT4& qt); void DX11QtRotationAxis(XMFLOAT4& qt, XMFLOAT4& axis, float angle); void DX11QtMul(XMFLOAT4& outqt, const XMFLOAT4& qt1, const XMFLOAT4& qt2); void DX11MtxFromQt(XMFLOAT4X4& outmtx, const XMFLOAT4& qt); void DX11QtNormalize(XMFLOAT4& inqt, XMFLOAT4& outqt); void DX11Vec4Length(XMFLOAT4& vec, float& length); void DX11p2pLength(const XMFLOAT3& p1, const XMFLOAT3& p2, float& length); void DX11MtxTranslation(const XMFLOAT3& trans, XMFLOAT4X4& matrix); void DX11QtSlerp(const XMFLOAT4& fromqt, const XMFLOAT4& toqt, float t, XMFLOAT4& ansqt); void DX11QtIdentity(XMFLOAT4& qt); void DX11Vec3Length(XMFLOAT3& vec, float& length); void DX11MtxRotationAxis(const XMFLOAT3& axis, float angle, XMFLOAT4X4& outmtx); void DX11MtxMultiply(XMFLOAT4X4& ansmtx, const XMFLOAT4X4& p1mtx, const XMFLOAT4X4& p2mtx); bool IsInFrustum(const XMFLOAT3& pos, const XMFLOAT4X4& matrix); void IsInFrustum(const XMFLOAT3& pos, const XMFLOAT4X4& matrix, float ans[]); bool IsInFrustum(const XMFLOAT3& pos, const XMFLOAT4X4& matrix, float ans[], PLANE* plane); bool IsInFrustum( const XMFLOAT3& pos, // BS中心座標 float radius, // 半径 const XMFLOAT4X4& matrix, // ビュー変換行列*プロジェクション変換行列 float ans[], // 平面との距離 bool canseeflag[], // フラスタム平面とBSの関係 PLANE* plane); // 平面方程式; void GetPlanefromProjectionmatrix(PLANE* p, const XMFLOAT4X4& matrix); void GetPlanefromProjectionmatrixWithNormalize(PLANE* p, const XMFLOAT4X4& matrix); void DX11MtxInverse(XMFLOAT4X4& ansmtx, const XMFLOAT4X4& mtx); void DX11MtxTranspose(XMFLOAT4X4& outmtx, const XMFLOAT4X4& inmtx); void DX11MtxRotationX(float angle, XMFLOAT4X4& outmtx); void DX11MtxRotationY(float angle, XMFLOAT4X4& outmtx); void DX11MtxRotationZ(float angle, XMFLOAT4X4& outmtx); void DX11MtxScale(float sx, float sy, float sz, XMFLOAT4X4& outmtx); float haltonseq(unsigned int no, unsigned int base); void DX11MtxIdentity(DirectX::XMFLOAT4X4& mat); void DX11MtxTranslation(const XMFLOAT3& trans, XMFLOAT4X4& matrix);
[ "oisiimizu9972@icloud.com" ]
oisiimizu9972@icloud.com
80af448e1eb81879bd263d437be116528e90af39
3e5ae9b260b16fcc86bb0669c1bd4e56912b5433
/examples/ch02/Fig02_22.cpp
d11bf5a2c9158f16ffaa09af4df142b84d5eb334
[]
no_license
briancpark/deitel-cpp
e8612c7011c9d9d748290419ae2708d2f3f11543
90cdae5661718e65ab945bcf45fe6adff30c1e10
refs/heads/main
2023-06-14T14:07:05.497253
2021-07-05T01:46:04
2021-07-05T01:46:04
382,984,213
0
0
null
null
null
null
UTF-8
C++
false
false
2,980
cpp
// Fig. 2.22: fig02_22.cpp // Counting letter grades #include <iostream> using std::cout; using std::cin; using std::endl; int main() { int grade, // one grade aCount = 0, // number of A's bCount = 0, // number of B's cCount = 0, // number of C's dCount = 0, // number of D's fCount = 0; // number of F's cout << "Enter the letter grades." << endl << "Enter the EOF character to end input." << endl; while ( ( grade = cin.get() ) != EOF ) { switch ( grade ) { // switch nested in while case 'A': // grade was uppercase A case 'a': // or lowercase a ++aCount; break; // necessary to exit switch case 'B': // grade was uppercase B case 'b': // or lowercase b ++bCount; break; case 'C': // grade was uppercase C case 'c': // or lowercase c ++cCount; break; case 'D': // grade was uppercase D case 'd': // or lowercase d ++dCount; break; case 'F': // grade was uppercase F case 'f': // or lowercase f ++fCount; break; case '\n': // ignore newlines, case '\t': // tabs, case ' ': // and spaces in input break; default: // catch all other characters cout << "Incorrect letter grade entered." << " Enter a new grade." << endl; break; // optional } } cout << "\n\nTotals for each letter grade are:" << "\nA: " << aCount << "\nB: " << bCount << "\nC: " << cCount << "\nD: " << dCount << "\nF: " << fCount << endl; return 0; } /************************************************************************** * (C) Copyright 2000 by Deitel & Associates, Inc. and Prentice Hall. * * All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/
[ "briancpark@berkeley.edu" ]
briancpark@berkeley.edu
61f72a5ff9fdd7e8b14d740e4f133b6f9223b98c
c37e0042441ce9b7529589e8c315fcc256a7b23b
/bart-engine-2d/Engine/source/box2d/Collision/Shapes/b2PolygonShape.cpp
bc684918a1e83c1bba56948ef84b03530f7d8305
[]
no_license
Atill3/ProgAv2
5833b0971779ba130ce279e3cc23bb47a540763d
b5fbd2feb0db5d578dc5218bc84eefb7c693717b
refs/heads/master
2022-11-19T19:00:18.182365
2020-07-23T15:03:27
2020-07-23T15:03:27
281,983,156
0
0
null
null
null
null
UTF-8
C++
false
false
9,480
cpp
/* * Copyright (c) 2006-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #include <Collision/Shapes/b2PolygonShape.h> #include <new> b2Shape* b2PolygonShape::Clone(b2BlockAllocator* allocator) const { void* mem = allocator->Allocate(sizeof(b2PolygonShape)); b2PolygonShape* clone = new (mem) b2PolygonShape; *clone = *this; return clone; } void b2PolygonShape::SetAsBox(float32 hx, float32 hy) { m_vertexCount = 4; m_vertices[0].Set(-hx, -hy); m_vertices[1].Set(hx, -hy); m_vertices[2].Set(hx, hy); m_vertices[3].Set(-hx, hy); m_normals[0].Set(0.0f, -1.0f); m_normals[1].Set(1.0f, 0.0f); m_normals[2].Set(0.0f, 1.0f); m_normals[3].Set(-1.0f, 0.0f); m_centroid.SetZero(); } void b2PolygonShape::SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle) { m_vertexCount = 4; m_vertices[0].Set(-hx, -hy); m_vertices[1].Set(hx, -hy); m_vertices[2].Set(hx, hy); m_vertices[3].Set(-hx, hy); m_normals[0].Set(0.0f, -1.0f); m_normals[1].Set(1.0f, 0.0f); m_normals[2].Set(0.0f, 1.0f); m_normals[3].Set(-1.0f, 0.0f); m_centroid = center; b2Transform xf; xf.p = center; xf.q.Set(angle); // Transform vertices and normals. for (int32 i = 0; i < m_vertexCount; ++i) { m_vertices[i] = b2Mul(xf, m_vertices[i]); m_normals[i] = b2Mul(xf.q, m_normals[i]); } } int32 b2PolygonShape::GetChildCount() const { return 1; } static b2Vec2 ComputeCentroid(const b2Vec2* vs, int32 count) { b2Assert(count >= 3); b2Vec2 c; c.Set(0.0f, 0.0f); float32 area = 0.0f; // pRef is the reference point for forming triangles. // It's location doesn't change the result (except for rounding error). b2Vec2 pRef(0.0f, 0.0f); #if 0 // This code would put the reference point inside the polygon. for (int32 i = 0; i < count; ++i) { pRef += vs[i]; } pRef *= 1.0f / count; #endif const float32 inv3 = 1.0f / 3.0f; for (int32 i = 0; i < count; ++i) { // Triangle vertices. b2Vec2 p1 = pRef; b2Vec2 p2 = vs[i]; b2Vec2 p3 = i + 1 < count ? vs[i + 1] : vs[0]; b2Vec2 e1 = p2 - p1; b2Vec2 e2 = p3 - p1; float32 D = b2Cross(e1, e2); float32 triangleArea = 0.5f * D; area += triangleArea; // Area weighted centroid c += triangleArea * inv3 * (p1 + p2 + p3); } // Centroid b2Assert(area > b2_epsilon); c *= 1.0f / area; return c; } void b2PolygonShape::Set(const b2Vec2* vertices, int32 count) { b2Assert(3 <= count && count <= b2_maxPolygonVertices); m_vertexCount = count; // Copy vertices. for (int32 i = 0; i < m_vertexCount; ++i) { m_vertices[i] = vertices[i]; } // Compute normals. Ensure the edges have non-zero length. for (int32 i = 0; i < m_vertexCount; ++i) { int32 i1 = i; int32 i2 = i + 1 < m_vertexCount ? i + 1 : 0; b2Vec2 edge = m_vertices[i2] - m_vertices[i1]; b2Assert(edge.LengthSquared() > b2_epsilon * b2_epsilon); m_normals[i] = b2Cross(edge, 1.0f); m_normals[i].Normalize(); } #ifdef _DEBUG // Ensure the polygon is convex and the interior // is to the left of each edge. for (int32 i = 0; i < m_vertexCount; ++i) { int32 i1 = i; int32 i2 = i + 1 < m_vertexCount ? i + 1 : 0; b2Vec2 edge = m_vertices[i2] - m_vertices[i1]; for (int32 j = 0; j < m_vertexCount; ++j) { // Don't check vertices on the current edge. if (j == i1 || j == i2) { continue; } b2Vec2 r = m_vertices[j] - m_vertices[i1]; // If this crashes, your polygon is non-convex, has colinear edges, // or the winding order is wrong. float32 s = b2Cross(edge, r); b2Assert(s > 0.0f && "ERROR: Please ensure your polygon is convex and has a CCW winding order"); } } #endif // Compute the polygon centroid. m_centroid = ComputeCentroid(m_vertices, m_vertexCount); } bool b2PolygonShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const { b2Vec2 pLocal = b2MulT(xf.q, p - xf.p); for (int32 i = 0; i < m_vertexCount; ++i) { float32 dot = b2Dot(m_normals[i], pLocal - m_vertices[i]); if (dot > 0.0f) { return false; } } return true; } bool b2PolygonShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, const b2Transform& xf, int32 childIndex) const { B2_NOT_USED(childIndex); // Put the ray into the polygon's frame of reference. b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p); b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p); b2Vec2 d = p2 - p1; float32 lower = 0.0f, upper = input.maxFraction; int32 index = -1; for (int32 i = 0; i < m_vertexCount; ++i) { // p = p1 + a * d // dot(normal, p - v) = 0 // dot(normal, p1 - v) + a * dot(normal, d) = 0 float32 numerator = b2Dot(m_normals[i], m_vertices[i] - p1); float32 denominator = b2Dot(m_normals[i], d); if (denominator == 0.0f) { if (numerator < 0.0f) { return false; } } else { // Note: we want this predicate without division: // lower < numerator / denominator, where denominator < 0 // Since denominator < 0, we have to flip the inequality: // lower < numerator / denominator <==> denominator * lower > numerator. if (denominator < 0.0f && numerator < lower * denominator) { // Increase lower. // The segment enters this half-space. lower = numerator / denominator; index = i; } else if (denominator > 0.0f && numerator < upper * denominator) { // Decrease upper. // The segment exits this half-space. upper = numerator / denominator; } } // The use of epsilon here causes the assert on lower to trip // in some cases. Apparently the use of epsilon was to make edge // shapes work, but now those are handled separately. //if (upper < lower - b2_epsilon) if (upper < lower) { return false; } } b2Assert(0.0f <= lower && lower <= input.maxFraction); if (index >= 0) { output->fraction = lower; output->normal = b2Mul(xf.q, m_normals[index]); return true; } return false; } void b2PolygonShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const { B2_NOT_USED(childIndex); b2Vec2 lower = b2Mul(xf, m_vertices[0]); b2Vec2 upper = lower; for (int32 i = 1; i < m_vertexCount; ++i) { b2Vec2 v = b2Mul(xf, m_vertices[i]); lower = b2Min(lower, v); upper = b2Max(upper, v); } b2Vec2 r(m_radius, m_radius); aabb->lowerBound = lower - r; aabb->upperBound = upper + r; } void b2PolygonShape::ComputeMass(b2MassData* massData, float32 density) const { // Polygon mass, centroid, and inertia. // Let rho be the polygon density in mass per unit area. // Then: // mass = rho * int(dA) // centroid.x = (1/mass) * rho * int(x * dA) // centroid.y = (1/mass) * rho * int(y * dA) // I = rho * int((x*x + y*y) * dA) // // We can compute these integrals by summing all the integrals // for each triangle of the polygon. To evaluate the integral // for a single triangle, we make a change of variables to // the (u,v) coordinates of the triangle: // x = x0 + e1x * u + e2x * v // y = y0 + e1y * u + e2y * v // where 0 <= u && 0 <= v && u + v <= 1. // // We integrate u from [0,1-v] and then v from [0,1]. // We also need to use the Jacobian of the transformation: // D = cross(e1, e2) // // Simplification: triangle centroid = (1/3) * (p1 + p2 + p3) // // The rest of the derivation is handled by computer algebra. b2Assert(m_vertexCount >= 3); b2Vec2 center; center.Set(0.0f, 0.0f); float32 area = 0.0f; float32 I = 0.0f; // s is the reference point for forming triangles. // It's location doesn't change the result (except for rounding error). b2Vec2 s(0.0f, 0.0f); // This code would put the reference point inside the polygon. for (int32 i = 0; i < m_vertexCount; ++i) { s += m_vertices[i]; } s *= 1.0f / m_vertexCount; const float32 k_inv3 = 1.0f / 3.0f; for (int32 i = 0; i < m_vertexCount; ++i) { // Triangle vertices. b2Vec2 e1 = m_vertices[i] - s; b2Vec2 e2 = i + 1 < m_vertexCount ? m_vertices[i + 1] - s : m_vertices[0] - s; float32 D = b2Cross(e1, e2); float32 triangleArea = 0.5f * D; area += triangleArea; // Area weighted centroid center += triangleArea * k_inv3 * (e1 + e2); float32 ex1 = e1.x, ey1 = e1.y; float32 ex2 = e2.x, ey2 = e2.y; float32 intx2 = ex1 * ex1 + ex2 * ex1 + ex2 * ex2; float32 inty2 = ey1 * ey1 + ey2 * ey1 + ey2 * ey2; I += (0.25f * k_inv3 * D) * (intx2 + inty2); } // Total mass massData->mass = density * area; // Center of mass b2Assert(area > b2_epsilon); center *= 1.0f / area; massData->center = center + s; // Inertia tensor relative to the local origin (point s). massData->I = density * I; // Shift to center of mass then to original body origin. massData->I += massData->mass * (b2Dot(massData->center, massData->center) - b2Dot(center, center)); }
[ "richatill3@live.ca" ]
richatill3@live.ca
7320ce48e38a65d59d62379de19f76ebdb9b3091
ef754d39a2a592b29c956cb31dabab4f0e6720d2
/sociobots_driver/src/multi_minion.cpp
47c6a4c11c364fb150b06b336817957bdb430e69
[]
no_license
jeweljames/pandabot
9098bdf25a92c158b812f5e28fc86d2cadadaa06
701d42c9cfa28028592b01c3462c0479b84df274
refs/heads/master
2020-04-25T04:14:56.870774
2015-04-30T17:51:23
2015-04-30T17:51:23
33,355,204
0
0
null
null
null
null
UTF-8
C++
false
false
5,157
cpp
/********************************************************************** Author: Gonçalo Cabrita on 03/09/2012 *********************************************************************/ #include <ros/ros.h> #include <tf/transform_broadcaster.h> #include <nav_msgs/Odometry.h> // odom #include <geometry_msgs/Twist.h> // cmd_vel #include <ar_track_alvar/AlvarMarkers.h> #include "miniQ.h" // Robot data structure class Robot { public: Robot(int id) : robot(), odom_pub(), cmd_vel_sub(), prefix() { robot.setId(id); prefix = "/robot_"; prefix.append<int>(1, 48+id); ROS_WARN("Created robot %s",prefix.c_str()); }; Robot(const Robot& r) : robot(), odom_pub(), cmd_vel_sub(), prefix() { robot = r.robot; odom_pub = r.odom_pub; cmd_vel_sub = r.cmd_vel_sub; prefix = r.prefix; }; // Robot miniQ robot; ros::Publisher odom_pub; ros::Subscriber cmd_vel_sub; ros::Subscriber visual_odom_sub ; std::string prefix; }; // The group of miniQs!!! std::vector<Robot> miniqs; void cmdVelReceived(int index, const geometry_msgs::Twist::ConstPtr& cmd_vel) { miniqs[index].robot.setVelocities(cmd_vel->linear.x, cmd_vel->angular.z); } void visualOdomCallback(int index , const ar_track_alvar::AlvarMarkers::ConstPtr& marker_msg) { for (unsigned int i = 0; i < marker_msg->markers.size(); i ++) { //check if the marker detected is the calibration marker if (marker_msg->markers[i].id == index) { miniqs[index].robot.getPositionFromCamera(marker_msg->markers[i].pose.pose.position.x,marker_msg->markers[i].pose.pose.position.y, marker_msg->markers[i].pose.pose.position.z, marker_msg->markers[i].pose.pose.orientation) ; } } } int main(int argc, char** argv) { ros::init(argc, argv, "miniq_node"); ROS_INFO("miniQ for ROS - Multi robot version."); ros::NodeHandle n; ros::NodeHandle pn("~"); std::string port; pn.param<std::string>("port", port, "/dev/ttyUSB0"); int baudrate; pn.param("baudrate", baudrate, 9600); if(!miniQ::openPort((char*)port.c_str(), baudrate)) { ROS_FATAL("miniQ -- Failed to open serial port %s at %d baud!", port.c_str(), baudrate); } ROS_INFO("miniQ -- Successfully connected to the miniQ!"); std::vector<int> ids; // Lets load the list of robot ids... XmlRpc::XmlRpcValue list_of_ids; if( n.getParam("/list_of_ids", list_of_ids) ) { ROS_ASSERT(list_of_ids.getType() == XmlRpc::XmlRpcValue::TypeArray); for(int i=0 ; i<list_of_ids.size() ; ++i) { ROS_ASSERT(list_of_ids[i].getType() == XmlRpc::XmlRpcValue::TypeInt); ids.push_back(static_cast<int>(list_of_ids[i])); } } else // If a list of ids is not defined scan for robots... { ROS_FATAL("miniQ -- A list of IDs was not provided, scanning for robots..."); } if(ids.size() == 0) { ROS_FATAL("miniQ -- Could not find any miniQs!!!"); ROS_BREAK(); } ROS_INFO("miniQ -- Finished scanning for robots!"); for(int i=0 ; i<ids.size() ; ++i) { miniqs.push_back(Robot(ids[i])); std::string odom_topic = miniqs[i].prefix; odom_topic.append("/odom"); miniqs[i].odom_pub = n.advertise<nav_msgs::Odometry>(odom_topic, 50); std::string cmd_vel_topic = miniqs[i].prefix; cmd_vel_topic.append("/cmd_vel"); miniqs[i].cmd_vel_sub = n.subscribe<geometry_msgs::Twist>(cmd_vel_topic, 10, boost::bind(cmdVelReceived, i, _1) ); std::string visual_odom_topic = "/ar_pose_marker"; miniqs[i].visual_odom_sub = n.subscribe<ar_track_alvar::AlvarMarkers>(visual_odom_topic,10, boost::bind(visualOdomCallback, i, _1)); } tf::TransformBroadcaster odom_broadcaster; ros::Time current_time; std::string frame_id; ros::Rate r(2); while(n.ok()) { ros::spinOnce(); current_time = ros::Time::now(); for(int i=0 ; i<miniqs.size() ; i++) { double odom_x = miniqs[i].robot.getX(); double odom_y = miniqs[i].robot.getY(); double yaw_angle = tf::getYaw(miniqs[i].robot.getRotation()); //ROS_INFO("Publishing data... %lf %lf %lf", odom_x, odom_y, odom_yaw); // Since all odometry is 6DOF we'll need a quaternion created from yaw geometry_msgs::Quaternion odom_quaternion = tf::createQuaternionMsgFromYaw(yaw_angle); // First, we'll publish the transform over tf //jewel added a 1.55 z-offset to see the robot not at the camera frame but on the arena tf::Transform new_tf(tf::createQuaternionFromYaw(yaw_angle), tf::Vector3(odom_x, odom_y, 1.55)); ros::Time transform_expiration = current_time + ros::Duration(1/(MINIQ_RATE)*2.0); std::string odom_frame_id = "/camera1"; std::string base_frame_id = miniqs[i].prefix; base_frame_id.append("/footprint"); tf::StampedTransform odom_trans(new_tf, transform_expiration, odom_frame_id, base_frame_id); // Send the transform odom_broadcaster.sendTransform(odom_trans); // ros::Duration((1/MINIQ_RATE)/(double)(miniqs.size())-elapsed_time.toSec()*2.0).sleep(); } r.sleep(); } return 0; } // EOF
[ "mailjeweljames@gmail.com" ]
mailjeweljames@gmail.com
1301140c934d9ae69d50a3ee59090e609f44632e
229f25ccda6d721f31c6d4de27a7bb85dcc0f929
/solutions/uri/structures/1260 Hardwood Species/solution.cpp
7b00ce81f9741380bbd5b28ad8e54ad5ed6f630e
[]
no_license
camil0palacios/Competitive-programming
e743378a8791a66c90ffaae29b4fd4cfb58fff59
4211fa61e516cb986b3404d87409ad1a49f78132
refs/heads/master
2022-11-01T20:35:21.541132
2022-10-27T03:13:42
2022-10-27T03:13:42
155,419,333
0
0
null
null
null
null
UTF-8
C++
false
false
1,042
cpp
#include <bits/stdc++.h> #define endl '\n' #define ll long long #define fori(i,a,b) for(int i = a; i < b; i++) #define forr(i,a,b) for(int i = a; i >= b; i--) #define fore(i,a,b) for(int i = a; i <= b; i++) #define ft first #define sd second #define all(v) v.begin(), v.end() #define sz(v) (int) v.size() #define pb push_back #define eb emplace_back using namespace std; typedef pair<int,int> ii; typedef vector<int> vi; typedef vector<bool> vb; typedef vector<ii> vii; typedef vector<ll> vll; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout << fixed << setprecision(4); int t; cin >> t; bool ok = 0; cin.ignore(); string s; getline(cin, s); while(t--) { map<string, int> m; int tot = 0; while(getline(cin, s)) { if(s.empty()) break; m[s]++; tot++; } if(ok) cout << endl; for(auto & p : m) { cout << p.ft << ' ' << 100.0*p.sd/tot << endl; } ok = 1; } return 0; }
[ "camilopalacios772@gmail.com" ]
camilopalacios772@gmail.com
195250e2048839e9a7200ada07e155c4c2c5f029
43075233f5d92e7d4e8e373672336c54789bde4f
/include/gcore/base64.h
8febec3052a8abf755536120e8036c85dcbd856f
[ "MIT" ]
permissive
gatgui/gcore
c410e0e05155460c880dd0b78112f2c6fa71ebc7
69af52ac7bba1ea2568209753bc33423887ce765
refs/heads/master
2021-12-05T13:00:14.790274
2021-11-03T02:49:43
2021-11-03T02:50:17
349,980
0
3
null
null
null
null
UTF-8
C++
false
false
2,527
h
/* MIT License Copyright (c) 2013 Gaetan Guidet This file is part of gcore. 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 __gcore_base64_h_ #define __gcore_base64_h_ #include <gcore/config.h> #include <string> namespace gcore { class GCORE_API Base64 { public: static size_t EncodeLength(size_t inlen); static bool Encode(const void *in, size_t inlen, char *out, size_t outlen); static char* Encode(const void *in, size_t inlen, size_t &outlen); static bool Encode(const void *in, size_t inlen, std::string &out); static bool Encode(const std::string &in, char *out, size_t outlen); static char* Encode(const std::string &in, size_t &outlen); static bool Encode(const std::string &in, std::string &out); static std::string Encode(const void *data, size_t len); static std::string Encode(const std::string &in); // --- static size_t DecodeLength(const char *in, size_t len); static bool Decode(const char *in, size_t len, void *out, size_t outlen); static void* Decode(const char *in, size_t len, size_t &outlen); static bool Decode(const char *in, size_t len, std::string &out); static bool Decode(const std::string &in, void *out, size_t outlen); static void* Decode(const std::string &in, size_t &outlen); static bool Decode(const std::string &in, std::string &out); static std::string Decode(const char *in, size_t len); static std::string Decode(const std::string &in); }; } #endif
[ "gatgui@gmail.com" ]
gatgui@gmail.com
c5576c913272012b79717e82f271df47ede46813
753a70bc416e8dced2853f278b08ef60cdb3c768
/include/tensorflow/lite/toco/tflite/op_version_test.cc
0d34b1997356aada9a81a63088671bab40531405
[ "MIT" ]
permissive
finnickniu/tensorflow_object_detection_tflite
ef94158e5350613590641880cb3c1062f7dd0efb
a115d918f6894a69586174653172be0b5d1de952
refs/heads/master
2023-04-06T04:59:24.985923
2022-09-20T16:29:08
2022-09-20T16:29:08
230,891,552
60
19
MIT
2023-03-25T00:31:18
2019-12-30T09:58:41
C++
UTF-8
C++
false
false
6,378
cc
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/toco/tflite/op_version.h" #include <gmock/gmock.h> #include <gtest/gtest.h> #include "tensorflow/lite/toco/model.h" namespace toco { namespace tflite { namespace { TEST(OpVersionTest, MinimumVersionForSameOpVersions) { Model model; // Float convolutional kernel is introduced since '1.5.0'. std::unique_ptr<ConvOperator> conv(new ConvOperator()); const string conv_input = "conv_input"; const string conv_filter = "conv_filter"; const string conv_output = "conv_output"; conv->inputs.push_back(conv_input); conv->inputs.push_back(conv_filter); conv->outputs.push_back(conv_output); auto& array_map = model.GetMutableArrayMap(); array_map[conv_input] = std::unique_ptr<Array>(new Array); array_map[conv_input]->data_type = ArrayDataType::kFloat; array_map[conv_filter] = std::unique_ptr<Array>(new Array); array_map[conv_filter]->data_type = ArrayDataType::kFloat; array_map[conv_output] = std::unique_ptr<Array>(new Array); array_map[conv_output]->data_type = ArrayDataType::kFloat; model.operators.push_back(std::move(conv)); // Float softmax kernel is introduced since '1.5.0'. std::unique_ptr<SoftmaxOperator> softmax(new SoftmaxOperator()); const string softmax_input = "softmax_input"; const string softmax_output = "softmax_output"; softmax->inputs.push_back(softmax_input); softmax->outputs.push_back(softmax_output); array_map[softmax_input] = std::unique_ptr<Array>(new Array); array_map[softmax_input]->data_type = ArrayDataType::kFloat; array_map[softmax_output] = std::unique_ptr<Array>(new Array); model.operators.push_back(std::move(softmax)); EXPECT_EQ(GetMinimumRuntimeVersionForModel(model), "1.5.0"); } TEST(OpVersionTest, MinimumVersionForMultipleOpVersions) { Model model; // Dilated DepthWiseConvolution is introduced since '1.12.0'. std::unique_ptr<DepthwiseConvOperator> conv(new DepthwiseConvOperator()); const string conv_input = "conv_input"; const string conv_filter = "conv_filter"; const string conv_output = "conv_output"; conv->inputs.push_back(conv_input); conv->inputs.push_back(conv_filter); conv->outputs.push_back(conv_output); auto& array_map = model.GetMutableArrayMap(); array_map[conv_input] = std::unique_ptr<Array>(new Array); array_map[conv_filter] = std::unique_ptr<Array>(new Array); array_map[conv_output] = std::unique_ptr<Array>(new Array); conv->dilation_width_factor = 2; conv->dilation_height_factor = 2; model.operators.push_back(std::move(conv)); // FullyConnected op with kShuffled4x16Int8 weight format is introduced from // '1.10.0'. std::unique_ptr<FullyConnectedOperator> fc(new FullyConnectedOperator()); const string fc_input = "fc_input"; const string fc_weights = "fc_weights"; const string fc_bias = "fc_bias"; const string fc_output = "fc_output"; fc->inputs.push_back(fc_input); fc->inputs.push_back(fc_weights); fc->inputs.push_back(fc_bias); fc->outputs.push_back(fc_output); array_map[fc_input] = std::unique_ptr<Array>(new Array); array_map[fc_weights] = std::unique_ptr<Array>(new Array); array_map[fc_output] = std::unique_ptr<Array>(new Array); fc->weights_format = FullyConnectedWeightsFormat::kShuffled4x16Int8; model.operators.push_back(std::move(fc)); EXPECT_EQ(GetMinimumRuntimeVersionForModel(model), "1.12.0"); } TEST(OpVersionTest, MinimumVersionForEmptyOpVersions) { Model model; // my_custom_op_1 isn't associated with any runtime version. auto my_custom_op_1 = absl::make_unique<TensorFlowUnsupportedOperator>(); my_custom_op_1->tensorflow_op = "MyAwesomeCustomOp1"; model.operators.push_back(std::move(my_custom_op_1)); // my_custom_op_2 isn't associated with any runtime version. auto my_custom_op_2 = absl::make_unique<TensorFlowUnsupportedOperator>(); my_custom_op_2->tensorflow_op = "MyAwesomeCustomOp2"; model.operators.push_back(std::move(my_custom_op_2)); EXPECT_EQ(GetMinimumRuntimeVersionForModel(model), ""); } TEST(OpVersionTest, MinimumVersionForMixedOpVersions) { Model model; // my_custom_op isn't associated with any runtime version. auto my_custom_op = absl::make_unique<TensorFlowUnsupportedOperator>(); my_custom_op->tensorflow_op = "MyAwesomeCustomOp"; model.operators.push_back(std::move(my_custom_op)); // FullyConnected op with kShuffled4x16Int8 weight format is introduced from // '1.10.0'. std::unique_ptr<FullyConnectedOperator> fc(new FullyConnectedOperator()); const string fc_input = "fc_input"; const string fc_weights = "fc_weights"; const string fc_bias = "fc_bias"; const string fc_output = "fc_output"; fc->inputs.push_back(fc_input); fc->inputs.push_back(fc_weights); fc->inputs.push_back(fc_bias); fc->outputs.push_back(fc_output); auto& array_map = model.GetMutableArrayMap(); array_map[fc_input] = std::unique_ptr<Array>(new Array); array_map[fc_weights] = std::unique_ptr<Array>(new Array); array_map[fc_output] = std::unique_ptr<Array>(new Array); fc->weights_format = FullyConnectedWeightsFormat::kShuffled4x16Int8; model.operators.push_back(std::move(fc)); EXPECT_EQ(GetMinimumRuntimeVersionForModel(model), "1.10.0"); } TEST(OpVersionTest, CompareVersionString) { EXPECT_TRUE(CompareVersion("1.9", "1.13")); EXPECT_FALSE(CompareVersion("1.13", "1.13")); EXPECT_TRUE(CompareVersion("1.14", "1.14.1")); EXPECT_FALSE(CompareVersion("1.14.1", "1.14")); EXPECT_FALSE(CompareVersion("1.14.1", "1.9")); EXPECT_FALSE(CompareVersion("1.0.9", "1.0.8")); EXPECT_FALSE(CompareVersion("2.1.0", "1.2.0")); EXPECT_TRUE(CompareVersion("", "1.13")); EXPECT_FALSE(CompareVersion("", "")); } } // namespace } // namespace tflite } // namespace toco
[ "finn.niu@apptech.com.hk" ]
finn.niu@apptech.com.hk
f4913007072228b144168e1b0be8df1cad0bc01a
dd209db10f682a541288cb83ca64d5e2621e12e1
/4-cycle-simulator/simulator-ver2.cpp
2dc6cd19446c35afd2436c0d040271fb46b04e36
[]
no_license
RedlineResearch/etanalyzer-cpp
377c8fe74fadbb70499e02a1f93e13ea948bfa92
736d56b56e8195749db4bca8ebfa1b3afbe8ce7d
refs/heads/master
2021-03-27T18:21:55.578527
2019-07-30T07:53:40
2019-07-30T07:53:40
43,264,556
0
0
null
null
null
null
UTF-8
C++
false
false
79,519
cpp
#include <iostream> #include <fstream> #include <sstream> #include <cstdio> #include <map> #include <set> #include <vector> #include <deque> #include <string> #include <utility> // TODO #include <stxxl/map> using namespace std; #include "tokenizer.h" #include "classinfo.h" #include "execution.h" #include "heap.h" #include "summary.hpp" // #include "lastmap.h" #include "version.hpp" // // STXXL related constants // #define DATA_NODE_BLOCK_SIZE (4096) // #define DATA_LEAF_BLOCK_SIZE (4096) // ---------------------------------------------------------------------- // Types class Object; class CCNode; typedef std::map< string, std::vector< Summary * > > GroupSum_t; typedef std::map< string, Summary * > TypeTotalSum_t; typedef std::map< unsigned int, Summary * > SizeSum_t; // An Edge Source is an object and it's specific field. // Global edge sources have a NULL object pointer. typedef std::pair< Object *, FieldId_t > EdgeSrc_t; // ---------------------------------------------------------------------- // We then map Edge Sources to a vector/list of Object pointers. // For every edge source, we keep a list of all the objects (pointers) // it has ever pointed to. // This is the in-memory stl version typedef std::map< EdgeSrc_t, std::vector< Object * > > EdgeSummary_t; // We need a reverse map from object pointer to the edge sources that ever // pointed to that object. typedef std::map< Object *, std::vector< EdgeSrc_t > > Object2EdgeSrcMap_t; // Trying an on-disk version but the library I DLed doesn't work well with C++11 // TODO //! [comparator] // TODO struct CompareGreater_EdgeSummary // TODO { // TODO bool operator () (const EdgeSrc_t &a, const EdgeSrc_t &b) const { // TODO Object *first = std::get<0>(a); // TODO Object *second = std::get<0>(b); // TODO if (first != second) { // TODO return first > second; // TODO } else { // TODO FieldId_t field1 = std::get<1>(a); // TODO FieldId_t field2 = std::get<1>(b); // TODO return field1 > field2; // TODO } // TODO } // TODO static EdgeSrc_t max_value() { // TODO return std::make_pair( static_cast<Object *>(NULL), // TODO std::numeric_limits<unsigned int>::min() ); // TODO } // TODO }; // TODO //! [comparator] // TODO // This is the out-of-core (on-disk) version. // TODO typedef stxxl::map< EdgeSrc_t, std::vector< Object * >, // TODO CompareGreater_EdgeSummary, // TODO DATA_NODE_BLOCK_SIZE, DATA_LEAF_BLOCK_SIZE > // TODO stxxl_EdgeSummary_t; // TODO // TODO: This is just dummy code to test the STXXL compilation units. // TODO // Need to replace EdgeSummary_t with the stxxl::map. (Or maybe make it configurable) // TODO // TODO: Test // TODO typedef stxxl_EdgeSummary_t EdgeSummary_t; // TODO // TODO //! [comparator] // TODO struct CompareGreater // TODO { // TODO bool operator () (const int & a, const int & b) const { // TODO return a > b; // TODO } // TODO static int max_value() { // TODO return std::numeric_limits<int>::min(); // TODO } // TODO }; // TODO //! [comparator] // TODO // This is the out-of-core (on-disk) version. // TODO //! [comparator] // TODO typedef stxxl::map<int, char, CompareGreater, DATA_NODE_BLOCK_SIZE, DATA_LEAF_BLOCK_SIZE> stxxl_Object2EdgeSrcMap_t; // EdgeSummary_t and Object2EdgeSrcMap_t contain the raw data. We need some // summaries. // enum class ObjectRefType moved to heap.h - RLV enum class EdgeSrcType { STABLE = 1, // Like True Love. Only one target ever. // TODO: This is an original idea that maybe singly-owned objects // can be considered part of the stable group. SERIAL_STABLE = 2, // Kind of like a serial monogamist. // Can point to different objects but never shares the // target object UNSTABLE = 32, // Points to different objects and // shares objects with other references UNKNOWN = 1024 }; string edgesrctype2str( EdgeSrcType r) { if (r == EdgeSrcType::STABLE) { return "STABLE"; } else if (r == EdgeSrcType::SERIAL_STABLE) { return "SERIAL_STABLE"; } else if (r == EdgeSrcType::UNSTABLE) { return "UNSTABLE"; } else { return "UNKNOWN"; } } string edgesrctype2shortstr( EdgeSrcType r) { if (r == EdgeSrcType::STABLE) { return "S"; // STABLE } else if (r == EdgeSrcType::SERIAL_STABLE) { return "ST"; // SERIAL_STABLE } else if (r == EdgeSrcType::UNSTABLE) { return "U"; // UNSTABLE } else { return "X"; // UNKNOWN } } // Map a reference to its type typedef std::map< EdgeSrc_t, EdgeSrcType > EdgeSrc2Type_t; // Map an object to its type // TODO: Is this needed? typedef std::map< Object *, ObjectRefType > Object2Type_t; // ---------------------------------------------------------------------- // Globals // -- Key object map to set of objects KeySet_t keyset; // -- Object to key object map ObjectPtrMap_t whereis; // -- The heap HeapState Heap( whereis, keyset ); // -- Execution state #ifdef ENABLE_TYPE1 ExecMode cckind = ExecMode::Full; // Full calling context #else ExecMode cckind = ExecMode::StackOnly; // Stack-only context #endif // ENABLE_TYPE1 ExecState Exec(cckind); // -- Turn on debugging bool debug = false; // -- Remember the last event by thread ID // TODO: Types for object and thread IDs? // TODO LastMap last_map; // ---------------------------------------------------------------------- // Analysis deque< deque<Object*> > cycle_list; set<unsigned int> root_set; map<unsigned int, unsigned int> deathrc_map; map<unsigned int, bool> not_candidate_map; EdgeSummary_t edge_summary; Object2EdgeSrcMap_t obj2ref_map; // ---------------------------------------------------------------------- void sanity_check() { /* if (Now > obj->getDeathTime() && obj->getRefCount() != 0) { nonzero_ref++; printf(" Non-zero-ref-dead %X of type %s\n", obj->getId(), obj->getType().c_str()); } */ } bool member( Object* obj, const ObjectSet& theset ) { return theset.find(obj) != theset.end(); } unsigned int closure( ObjectSet& roots, ObjectSet& premarked, ObjectSet& result ) { unsigned int mark_work = 0; vector<Object*> worklist; // -- Initialize the worklist with only unmarked roots for ( ObjectSet::iterator i = roots.begin(); i != roots.end(); i++ ) { Object* root = *i; if ( !member(root, premarked) ) { worklist.push_back(root); } } // -- Do DFS until the worklist is empty while (worklist.size() > 0) { Object* obj = worklist.back(); worklist.pop_back(); result.insert(obj); mark_work++; const EdgeMap& fields = obj->getFields(); for ( EdgeMap::const_iterator p = fields.begin(); p != fields.end(); p++ ) { Edge* edge = p->second; Object* target = edge->getTarget(); if (target) { // if (target->isLive(Exec.NowUp())) { if ( !member(target, premarked) && !member(target, result) ) { worklist.push_back(target); } // } else { // cout << "WEIRD: Found a dead object " << target->info() << " from " << obj->info() << endl; // } } } } return mark_work; } unsigned int count_live( ObjectSet & objects, unsigned int at_time ) { int count = 0; // -- How many are actually live for ( ObjectSet::iterator p = objects.begin(); p != objects.end(); p++ ) { Object* obj = *p; if (obj->isLive(at_time)) { count++; } } return count; } void update_reference_summaries( Object *src, FieldId_t fieldId, Object *tgt ) { // edge_summary : EdgeSummary_t is a global // obj2ref_map : Object2EdgeSrcMap_t is a global EdgeSrc_t ref = std::make_pair( src, fieldId ); // The reference 'ref' points to the new target auto iter = edge_summary.find(ref); if (iter == edge_summary.end()) { // Not found. Create a new vector of Object pointers edge_summary[ref] = std::vector< Object * >(); } edge_summary[ref].push_back(tgt); // Do the reverse mapping ONLY if tgt is not NULL if (tgt) { auto rev = obj2ref_map.find(tgt); if (rev == obj2ref_map.end()) { obj2ref_map[tgt] = std::move(std::vector< EdgeSrc_t >()); } obj2ref_map[tgt].push_back(ref); } } // ---------------------------------------------------------------------- // Read and process trace events void apply_merlin( std::deque< Object * > &new_garbage ) { if (new_garbage.size() == 0) { // TODO Log an ERROR or a WARNING return; } // TODO: Use setDeathTime( new_dtime ); // Sort the new_garbage vector according to latest last_timestamp. std::sort( new_garbage.begin(), new_garbage.end(), []( Object *left, Object *right ) { return (left->getLastTimestamp() > right->getLastTimestamp()); } ); // Do a standard DFS. while (new_garbage.size() > 0) { // Start with the latest for the DFS. Object *cur = new_garbage[0]; new_garbage.pop_front(); std::deque< Object * > mystack; // stack for DFS std::set< Object * > labeled; // What Objects have been labeled mystack.push_front( cur ); while (mystack.size() > 0) { Object *otmp = mystack[0]; mystack.pop_front(); assert(otmp); // The current timestamp max unsigned int tstamp_max = otmp->getLastTimestamp(); otmp->setDeathTime( tstamp_max ); // Remove from new_garbage deque auto ngiter = std::find( new_garbage.begin(), new_garbage.end(), otmp ); if (ngiter != new_garbage.end()) { // still in the new_garbage deque new_garbage.erase(ngiter); } // Check if labeled already auto iter = labeled.find(otmp); if (iter == labeled.end()) { // Not found => not labeled labeled.insert(otmp); // Go through all the edges out of otmp // -- Visit all edges for ( auto ptr = otmp->getFields().begin(); ptr != otmp->getFields().end(); ptr++ ) { Edge *edge = ptr->second; if ( edge && ((edge->getEdgeState() == EdgeState::DEAD_BY_OBJECT_DEATH) || (edge->getEdgeState() == EdgeState::DEAD_BY_OBJECT_DEATH_NOT_SAVED)) ) { edge->setEndTime( tstamp_max ); Object *mytgt = edge->getTarget(); if (mytgt) { // Get timestamp unsigned int tstmp = mytgt->getLastTimestamp(); if (tstamp_max > tstmp) { mytgt->setLastTimestamp( tstamp_max ); mytgt->setDeathTime( tstamp_max ); } // This might be a bug. I probably shouldn't be setting the tstamp_max here. // But then again where should it be set? It seems that this is the right thing // to do here. // TODO else { // TODO tstamp_max = tstmp; // TODO } mystack.push_front( mytgt ); } } } } } } // Until the vector is empty } // ---------------------------------------------------------------------- // TODO: Document summarize_reference_stability void summarize_reference_stability( EdgeSrc2Type_t &stability, EdgeSummary_t &my_refsum, Object2EdgeSrcMap_t &my_obj2ref ) { // Check each object to see if it's stable...(see ObjectRefType) for ( auto it = my_obj2ref.begin(); it != my_obj2ref.end(); ++it ) { // my_obj2ref : Object2EdgeSrcMap_t is a reverse map of sorts. // For each object in the map, it maps to a vector of references // that point/refer to that object // This Object is the target Object *obj = it->first; // This is the vector of references std::vector< EdgeSrc_t > reflist = it->second; // Convert to a set in order to remove possible duplicates std::set< EdgeSrc_t > refset( reflist.begin(), reflist.end() ); if (!obj) { continue; } // obj is not NULL. // if ( (refset.size() <= 1) && (obj->wasLastUpdateNull() != true) ) { if (refset.size() <= 1) { obj->setRefTargetType( ObjectRefType::SINGLY_OWNED ); } else { obj->setRefTargetType( ObjectRefType::MULTI_OWNED ); } } // Check each edge source to see if its stable...(see EdgeSrcType) for ( auto it = my_refsum.begin(); it != my_refsum.end(); ++it ) { // my_refsum : EdgeSummary_t is a map from reference to a vector of // objects that the reference pointed to. A reference is a pair // of (Object pointer, fieldId). // Get the reference and deconstruct into parts. EdgeSrc_t ref = it->first; Object *obj = std::get<0>(ref); FieldId_t fieldId = std::get<1>(ref); // Get the vector/list of object pointers std::vector< Object * > objlist = it->second; // We need to make sure that all elements are not duplicates. std::set< Object * > objset( objlist.begin(), objlist.end() ); // Is NULL in there? auto findit = objset.find(NULL); bool nullflag = (findit != objset.end()); if (nullflag) { // If NULL is in the list, remove NULL. objset.erase(findit); } unsigned int size = objset.size(); if (size == 1) { // The reference only points to one object! // Convert object set back into a vector. std::vector< Object * > tmplist( objset.begin(), objset.end() ); assert( tmplist.size() == 1 ); Object *tgt = tmplist[0]; // Check for source and target death times // The checks for NULL are probably NOT necessary. assert(obj != NULL); VTime_t src_dtime = obj->getDeathTime(); assert(tgt != NULL); VTime_t tgt_dtime = tgt->getDeathTime(); if (tgt_dtime != src_dtime) { // UNSTABLE if target and source deathtimes are different // NOTE: This used to be UNSTABLE if target died before source. // We are using a more conservative definition of stability here. stability[ref] = EdgeSrcType::UNSTABLE; } else { stability[ref] = (tgt->wasLastUpdateNull() ? EdgeSrcType::UNSTABLE : EdgeSrcType::STABLE); } } else { // objlist is of length > 1 // This may still be stable if all objects in // the list are STABLE. Assume they're all stable unless // otherwise proven. stability[ref] = EdgeSrcType::SERIAL_STABLE; // aka serial monogamist for ( auto objit = objset.begin(); objit != objset.end(); ++objit ) { ObjectRefType objtype = (*objit)->getRefTargetType(); if (objtype == ObjectRefType::MULTI_OWNED) { stability[ref] = EdgeSrcType::UNSTABLE; break; } else if (objtype == ObjectRefType::UNKNOWN) { // Not sure if this is even possible. // TODO: Make this an assertion? // Let's assume that UNKNOWNs make it UNSTABLE. stability[ref] = EdgeSrcType::UNSTABLE; break; } // else continue } } } } // ---------------------------------------------------------------------- // TODO: Document sumSize unsigned int sumSize( std::set< Object * >& s ) { unsigned int total = 0; for ( auto it = s.begin(); it != s.end(); ++it ) { total += (*it)->getSize(); } return total; } // ---------------------------------------------------------------------- // TODO: Document update_summaries void update_summaries( Object *key, std::set< Object * >& tgtSet, GroupSum_t& pgs, TypeTotalSum_t& tts, SizeSum_t& ssum ) { string mytype = key->getType(); unsigned gsize = tgtSet.size(); // per group summary auto git = pgs.find(mytype); if (git == pgs.end()) { pgs[mytype] = std::move(std::vector< Summary * >()); } unsigned int total_size = sumSize( tgtSet ); Summary *s = new Summary( gsize, total_size, 1 ); // -- third parameter is number of groups which is simply 1 here. pgs[mytype].push_back(s); // type total summary auto titer = tts.find(mytype); if (titer == tts.end()) { Summary *t = new Summary( gsize, total_size, 1 ); tts[mytype] = t; } else { tts[mytype]->size += total_size; tts[mytype]->num_objects += tgtSet.size(); tts[mytype]->num_groups++; } // size summary auto sit = ssum.find(gsize); if (sit == ssum.end()) { Summary *u = new Summary( gsize, total_size, 1 ); ssum[gsize] = u; } else { ssum[gsize]->size += total_size; ssum[gsize]->num_groups++; // Doesn't make sense to make use of the num_objects field. } } // ---------------------------------------------------------------------- // TODO: Document update_summary_from_keyset void update_summary_from_keyset( KeySet_t &keyset, GroupSum_t &per_group_summary, TypeTotalSum_t &type_total_summary, SizeSum_t &size_summary ) { for ( auto it = keyset.begin(); it != keyset.end(); ++it ) { Object *key = it->first; std::set< Object * > *tgtSet = it->second; // TODO TODO 7 March 2016 - Put into CSV file. cout << "[ " << key->getType() << " ]: " << tgtSet->size() << endl; update_summaries( key, *tgtSet, per_group_summary, type_total_summary, size_summary ); } } // Forward declarations of output functions void output_size_summary( string &dgroups_filename, SizeSum_t &size_summary ); void output_type_summary( string &dgroups_by_type_filename, TypeTotalSum_t &type_total_summary ); void output_all_objects2( string &objectinfo_filename, HeapState &myheap, std::set<ObjectId_t> dag_keys, std::set<ObjectId_t> dag_all_set, std::set<ObjectId_t> all_keys, unsigned int final_time ); void output_reference_summary( string &reference_summary_filename, string &ref_reverse_summary_filename, string &stability_summary_filename, EdgeSummary_t &my_refsum, Object2EdgeSrcMap_t &my_obj2ref, EdgeSrc2Type_t &stability ); void output_cycles( KeySet_t &keyset, string &cycle_filename, std::set<int> &node_set ); unsigned int output_edges( HeapState &myheap, ofstream &edge_info_file ); // ---------------------------------------------------------------------- // Do cycles. TODO: What else? void do_cycles( string &dgroups_filename, string &dgroups_by_type_filename, string &objectinfo_filename, string &reference_summary_filename, string &ref_reverse_summary_filename, string &stability_summary_filename, string &cycle_filename, ofstream &edge_info_file, unsigned int final_time ) { // NOTE: keyset of type KeySet_t is a GLOBAL. // std::deque< pair<int,int> > edgelist; // per_group_summary: type -> vector of group summary GroupSum_t per_group_summary; // type_total_summary: summarize the stats per type TypeTotalSum_t type_total_summary; // size_summary: per group size summary. That is, for each group of size X, // add up the sizes. SizeSum_t size_summary; // Remember the key objects for non-cyclic death groups. set<ObjectId_t> dag_keys; deque<ObjectId_t> dag_all; // Reference stability summary EdgeSrc2Type_t stability_summary; // Lambdas for utility auto lfn = [](Object *ptr) -> unsigned int { return ((ptr) ? ptr->getId() : 0); }; auto ifNull = [](Object *ptr) -> bool { return (ptr == NULL); }; // NOTE: keyset is a GLOBAL. // If that bothers you, then pass it in as a parameter. It's all good. // KeySet_t is a map: // Object * -> pointer to set< Object * > for ( auto kiter = keyset.begin(); kiter != keyset.end(); kiter++ ) { auto optr = kiter->first; // Object pointer ObjectId_t objId = (optr ? optr->getId() : 0); // All keys in a KeySet_t will be key object Ids dag_keys.insert(objId); dag_all.push_back(objId); // TODO: set< Object * > *sptr = kiter->second; auto sptr = kiter->second; // pointer to set< Object * > if (!sptr) { // TODO: Null set pointer? Should DEBUG. TODO continue; } deque< Object * > deqtmp; // Not sure why this doesn't work: TODO COPY CODE // std::copy( sptr->begin(), sptr->end(), deqtmp.begin() ); // std::remove_if( deqtmp.begin(), deqtmp.end(), ifNull ); // END TODO COPY CODE for ( auto setit = sptr->begin(); setit != sptr->end(); setit++ ) { if (*setit) { deqtmp.push_back( *setit ); } } if (deqtmp.size() > 0) { // TODO Not sure why this transform isn't working like the for loop. // Not too important, but kind of curious as to how I'm not using // std::transform properly. // TODO // std::transform( deqtmp.cbegin(), // deqtmp.cend(), // dag_all.begin(), // lfn ); for ( auto dqit = deqtmp.begin(); dqit != deqtmp.end(); dqit++ ) { if (*dqit) { dag_all.push_back( (*dqit)->getId() ); } } } } // Copy all dag_all object Ids into dag_all_set to get rid of duplicates. set< ObjectId_t > dag_all_set( dag_all.cbegin(), dag_all.cend() ); // scan_queue2 determines all the death groups that are cyclic // The '2' is a historical version of the function that won't be // removed. // - not_candidate_map is GLOBAL: map from unsigned int to bool // TODO: Is unsigned int ObjectId_t? // - edgelist is GLOBAL: map from int to int // TODO: Are the ints also ObjectId_t? // TODO: Heap.scan_queue2( edgelist, // TODO: not_candidate_map ); // TODO TODO ^^^^^^^^^^^^^^^^^^^^ update_summary_from_keyset( keyset, per_group_summary, type_total_summary, size_summary ); // Save key object IDs for _all_ death groups. set<ObjectId_t> all_keys; for ( KeySet_t::iterator kiter = keyset.begin(); kiter != keyset.end(); kiter++ ) { Object *optr = kiter->first; ObjectId_t objId = (optr ? optr->getId() : 0); all_keys.insert(objId); // NOTE: We don't really need to add ALL objects here since // we can simply test against dag_all_set to see if it's a DAG // object. If not in dag_all_set, then it's a CYC object. } // Analyze the edge summaries summarize_reference_stability( stability_summary, edge_summary, obj2ref_map ); // ---------------------------------------------------------------------- // OUTPUT THE SUMMARIES // By size summary of death groups output_size_summary( dgroups_filename, size_summary ); // Type total summary output output_type_summary( dgroups_by_type_filename, type_total_summary ); // Output all objects info output_all_objects2( objectinfo_filename, Heap, dag_keys, dag_all_set, all_keys, final_time ); // TODO 2017-0220 output_context_summary( context_death_count_filename, // TODO 2017-0220 Exec ); output_reference_summary( reference_summary_filename, ref_reverse_summary_filename, stability_summary_filename, edge_summary, obj2ref_map, stability_summary ); // TODO: What next? // Output cycles set<int> node_set; output_cycles( keyset, cycle_filename, node_set ); // TODO: Moved the edge output to as needed instead of all at the end. // TODO // Output all edges unsigned int added_edges = output_edges( Heap, edge_info_file ); edge_info_file << "---------------[ EDGE INFO END ]------------------------------------------------" << endl; edge_info_file.close(); } // ---------------------------------------------------------------------- // Read and process trace events unsigned int read_trace_file( FILE *f, ofstream &eifile ) { // eifile is the edge_info_file Tokenizer tokenizer(f); unsigned int method_id; unsigned int object_id; unsigned int target_id; unsigned int field_id; unsigned int thread_id; unsigned int exception_id; Object *obj; Object *target; Method *method; unsigned int total_objects = 0; // Remember all the dead objects std::deque< Object * > new_garbage; Method *main_method = ClassInfo::get_main_method(); unsigned int main_id = main_method->getId(); unsigned int latest_death_time = 0; // DEBUG unsigned int debug_stack_edges = 0; // END DEBUG // -- Allocation time unsigned int AllocationTime = 0; while ( ! tokenizer.isDone()) { tokenizer.getLine(); if (tokenizer.isDone()) { break; } #ifndef DEBUG_SPECJBB if (Exec.NowUp() % 1050000 == 1) { // cout << " Method time: " << Exec.Now() << " Alloc time: " << AllocationTime << endl; cout << " Update time: " << Exec.NowUp() << " | Method time: TODO | Alloc time: " << AllocationTime << endl; } #endif // DEBUG_SPECJBB switch (tokenizer.getChar(0)) { case 'A': case 'I': case 'N': case 'P': case 'V': { // A/I/N/P/V <id> <size> <type> <site> [<els>] <threadid> // 0 1 2 3 4 5 5/6 unsigned int thrdid = (tokenizer.numTokens() == 6) ? tokenizer.getInt(6) : tokenizer.getInt(5); Thread* thread = Exec.getThread(thrdid); unsigned int els = (tokenizer.numTokens() == 6) ? tokenizer.getInt(5) : 0; AllocSite *as = ClassInfo::TheAllocSites[tokenizer.getInt(4)]; string njlib_sitename; if (thread) { MethodDeque javalib_context = thread->top_javalib_methods(); assert(javalib_context.size() > 0); Method *meth = javalib_context.back(); njlib_sitename = ( meth ? meth->getName() : "NONAME" ); // TODO: if (cckind == ExecMode::Full) { // TODO: // Get full stacktrace // TODO: DequeId_t strace = thread->stacktrace_using_id(); // TODO: } } else { assert(false); } // if (thread) ... else // DEBUG // if (!as) { // cerr << "DBG: objId[ " << tokenizer.getInt(1) << " ] has no alloc site." << endl; // } // END DEBUG obj = Heap.allocate( tokenizer.getInt(1), // id tokenizer.getInt(2), // size tokenizer.getChar(0), // kind of alloc tokenizer.getString(3), // type as, // AllocSite pointer njlib_sitename, // NonJava-library alloc sitename els, // length IF applicable thread, // thread Id Exec.NowUp() ); // Current time #ifdef _SIZE_DEBUG cout << "OS: " << sizeof(obj) << endl; #endif // _SIZE_DEBUG AllocationTime = Heap.getAllocTime(); Exec.SetAllocTime( AllocationTime ); if (as) { Exec.UpdateObj2AllocContext( obj, as->getMethod()->getName() ); } else { Exec.UpdateObj2AllocContext( obj, "NOSITE" ); } if (cckind == ExecMode::Full) { // Get full stacktrace DequeId_t strace = thread->stacktrace_using_id(); obj->setAllocContextList( strace ); } total_objects++; } break; case 'U': { // U <old-target> <object> <new-target> <field> <thread> // 0 1 2 3 4 5 // -- Look up objects and perform update unsigned int objId = tokenizer.getInt(2); unsigned int tgtId = tokenizer.getInt(3); unsigned int oldTgtId = tokenizer.getInt(1); unsigned int threadId = tokenizer.getInt(5); unsigned int field = tokenizer.getInt(4); Thread *thread = Exec.getThread(threadId); Method *topMethod = NULL; Method *topMethod_using_action = NULL; if (thread) { topMethod = thread->TopMethod(); MethodDeque tjmeth = thread->top_javalib_methods(); topMethod_using_action = tjmeth.back(); } Object *oldObj = Heap.getObject(oldTgtId); LastEvent lastevent = LastEvent::UPDATE_UNKNOWN; Exec.IncUpdateTime(); obj = Heap.getObject(objId); // NOTE that we don't need to check for non-NULL source object 'obj' // here. NULL means that it's a global/static reference. target = ((tgtId > 0) ? Heap.getObject(tgtId) : NULL); if (obj) { update_reference_summaries( obj, field, target ); } // TODO last_map.setLast( threadId, LastEvent::UPDATE, obj ); // Set lastEvent and heap/stack flags for new target if (target) { if ( obj && obj != target /* && !(obj->wasRoot()) * NOTE: This was the original code which in resulted * in LESS Died By STACK after HEAP. Making this change * to see if the results match the intuition of the code * being analyzed. - RLV 2017 Feb 16 * */ ) { target->setPointedAtByHeap(); } target->setLastTimestamp( Exec.NowUp() ); // TODO: target->setActualLastTimestamp( Exec.NowUp() ); // TODO: Maybe LastUpdateFromStatic isn't the most descriptive // So since target has an incoming edge, LastUpdateFromStatic // should be FALSE. target->unsetLastUpdateFromStatic(); } // Set lastEvent and heap/stack flags for old target if (oldObj) { // Set the last time stamp for Merlin Algorithm purposes oldObj->setLastTimestamp( Exec.NowUp() ); oldObj->setActualLastTimestamp( Exec.NowUp() ); // Keep track of other properties if (tgtId != 0) { oldObj->unsetLastUpdateNull(); } else { oldObj->setLastUpdateNull(); } if (target) { if (oldTgtId != tgtId) { lastevent = LastEvent::UPDATE_AWAY_TO_VALID; oldObj->setLastEvent( lastevent ); } } else { // There's no need to check for oldTgtId == tgtId here. lastevent = LastEvent::UPDATE_AWAY_TO_NULL; oldObj->setLastEvent( lastevent ); } if (field == 0) { oldObj->setLastUpdateFromStatic(); } else { oldObj->unsetLastUpdateFromStatic(); } // Last action site oldObj->setLastActionSite(topMethod_using_action); string last_action_name = topMethod_using_action->getName(); oldObj->set_nonJavaLib_last_action_context( last_action_name ); } if (oldTgtId == tgtId) { // It sometimes happens that the newtarget is the same as // the old target. So we won't create any more new edges. // DEBUG: cout << "UPDATE same new == old: " << target << endl; } else { if (obj) { Edge *new_edge = NULL; // Can't call updateField if obj is NULL if (target) { // Increment and decrement refcounts unsigned int field_id = tokenizer.getInt(4); new_edge = Heap.make_edge( obj, field_id, target, Exec.NowUp() ); #ifdef _SIZE_DEBUG cout << "ES: " << sizeof(new_edge) << endl; #endif // _SIZE_DEBUG } obj->updateField( new_edge, field_id, Exec.NowUp(), topMethod, // for death site info Reason::HEAP, // reason NULL, // death root 0 because may not be a root lastevent, // last event to determine cause EdgeState::DEAD_BY_UPDATE, // edge is dead because of update eifile ); // output edge info file // // NOTE: topMethod COULD be NULL here. // DEBUG ONLY IF NEEDED // Example: // if ( (objId == tgtId) && (objId == 166454) ) { // if ( (objId == 166454) ) { // tokenizer.debugCurrent(); // } } } } break; case 'D': { // D <object> <thread-id> // 0 1 2 unsigned int objId = tokenizer.getInt(1); obj = Heap.getObject(objId); if (obj) { unsigned int now_uptime = Exec.NowUp(); // Merlin algorithm portion. TODO: This is getting unwieldy. Think about // refactoring. // Keep track of the latest death time // TODO: Debug? Well it's a decent sanity check so we may leave it in. assert( latest_death_time <= now_uptime ); // Ok, so now we can see if the death time has if (now_uptime > latest_death_time) { // Do the Merlin algorithm apply_merlin( new_garbage ); // TODO: What are the parameters? // - new_garbage for sure // - anything else? // For now this simply updates the object death times } // Update latest death time latest_death_time = now_uptime; // The rest of the bookkeeping new_garbage.push_back(obj); unsigned int threadId = tokenizer.getInt(2); LastEvent lastevent = obj->getLastEvent(); // Set the died by flags if ( (lastevent == LastEvent::UPDATE_AWAY_TO_NULL) || (lastevent == LastEvent::UPDATE_AWAY_TO_VALID) || (lastevent == LastEvent::UPDATE_UNKNOWN) ) { if (obj->wasLastUpdateFromStatic()) { obj->setDiedByGlobalFlag(); } // Design decision: all died by globals are // also died by heap. obj->setDiedByHeapFlag(); } else if ( (lastevent == LastEvent::ROOT) || (lastevent == LastEvent::OBJECT_DEATH_AFTER_ROOT_DECRC) || (lastevent == LastEvent::OBJECT_DEATH_AFTER_UPDATE_DECRC) ) { obj->setDiedByStackFlag(); } //else { // cerr << "Unhandled event: " << lastevent2str(lastevent) << endl; // } Heap.makeDead( obj, now_uptime, eifile ); // Get the current method Method *topMethod = NULL; MethodDeque top_2_methods; MethodDeque javalib_context; // TODO: ContextPair cpair; CPairType cptype; Thread *thread; if (threadId > 0) { thread = Exec.getThread(threadId); // Update counters in ExecState for map of // Object * to simple context pair } else { // No thread info. Get from ExecState thread = Exec.get_last_thread(); } if (thread) { // TODO: cptype = thread->getContextPairType(); unsigned int count = 0; topMethod = thread->TopMethod(); top_2_methods = thread->top_N_methods(2); // TODO TODO HERE TODO // Exec.IncDeathContext( top_2_methods ); // TODO TODO HERE TODO javalib_context = thread->top_javalib_methods(); if (cckind == ExecMode::Full) { // Get full stacktrace DequeId_t strace = thread->stacktrace_using_id(); obj->setDeathContextList( strace ); } // Set the death site Exec.UpdateObj2DeathContext( obj, javalib_context ); #ifdef DEBUG_SPECJBB // if the object is of type [I // SPECJBB if (obj->getType() == "[I") { if (obj->getType() == "Lspec/benchmarks/_205_raytrace/Point;") { MethodDeque cstack = thread->full_method_stack(); cout << "---------------------------------------------------------------------" << endl; cout << "DEBUG: objectId[ " << obj->getId() << " ]:" << endl << " "; for ( auto iter = cstack.begin(); iter != cstack.end(); iter++ ) { cout << (*iter)->getName() << " <- "; } cout << endl; } // #endif // DEBUG_SPECJBB // Death reason setting Reason myreason; if (thread->isLocalVariable(obj)) { myreason = Reason::STACK; } else { myreason = Reason::HEAP; } // Recursively make the edges dead and assign the proper death cause for ( EdgeMap::iterator p = obj->getEdgeMapBegin(); p != obj->getEdgeMapEnd(); ++p ) { Edge* target_edge = p->second; if (target_edge) { unsigned int fieldId = target_edge->getSourceField(); obj->updateField( NULL, fieldId, Exec.NowUp(), topMethod, myreason, obj, lastevent, EdgeState::DEAD_BY_OBJECT_DEATH_NOT_SAVED, eifile ); // output edge info file // NOTE: STACK is used because the object that died, // died by STACK. } } } // if (thread) unsigned int rc = obj->getRefCount(); deathrc_map[objId] = rc; not_candidate_map[objId] = (rc == 0); } else { assert(false); } // if (obj) ... else } break; case 'M': { // M <methodid> <receiver> <threadid> // 0 1 2 3 // current_cc = current_cc->DemandCallee(method_id, object_id, thread_id); // TEMP TODO ignore method events method_id = tokenizer.getInt(1); method = ClassInfo::TheMethods[method_id]; thread_id = tokenizer.getInt(3); // Check to see if this is the main function if (method == main_method) { Exec.set_main_func_uptime( Exec.NowUp() ); Exec.set_main_func_alloctime( Exec.NowAlloc() ); } Exec.Call(method, thread_id); } break; case 'E': case 'X': { // E <methodid> <receiver> [<exceptionobj>] <threadid> // 0 1 2 3 3/4 method_id = tokenizer.getInt(1); method = ClassInfo::TheMethods[method_id]; thread_id = (tokenizer.numTokens() == 4) ? tokenizer.getInt(3) : tokenizer.getInt(4); Exec.Return(method, thread_id); } break; case 'T': // T <methodid> <receiver> <exceptionobj> // 0 1 2 3 break; case 'H': // H <methodid> <receiver> <exceptionobj> break; case 'R': // R <objid> <threadid> // 0 1 2 { unsigned int objId = tokenizer.getInt(1); Object *object = Heap.getObject(objId); unsigned int threadId = tokenizer.getInt(2); // cout << "objId: " << objId << " threadId: " << threadId << endl; if (object) { object->setRootFlag(Exec.NowUp()); object->setLastEvent( LastEvent::ROOT ); object->setLastTimestamp( Exec.NowUp() ); object->setActualLastTimestamp( Exec.NowUp() ); Thread *thread = Exec.getThread(threadId); Method *topMethod_using_action = NULL; if (thread) { MethodDeque tjmeth = thread->top_javalib_methods(); topMethod_using_action = tjmeth.back(); } if (thread) { thread->objectRoot(object); } if (topMethod_using_action) { // Last action site object->setLastActionSite(topMethod_using_action); string last_action_name = topMethod_using_action->getName(); object->set_nonJavaLib_last_action_context( last_action_name ); } else { // Last action site object->setLastActionSite(NULL); string last_action_name("VMCONTEXT"); object->set_nonJavaLib_last_action_context( last_action_name ); } } root_set.insert(objId); // TODO last_map.setLast( threadId, LastEvent::ROOT, object ); } break; default: // cout << "ERROR: Unknown entry " << tokenizer.curChar() << endl; break; } } cout << "DEBUG_STACK_EDGES: " << debug_stack_edges << endl; return total_objects; } // ---------------------------------------------------------------------- // Remove edges not in cyclic garbage void filter_edgelist( deque< pair<int,int> >& edgelist, deque< deque<int> >& cycle_list ) { set<int> nodes; deque< pair<int,int> > newlist; for ( auto it = cycle_list.begin(); it != cycle_list.end(); ++it ) { for ( auto tmp = it->begin(); tmp != it->end(); ++tmp ) { nodes.insert(*tmp); } } for ( auto it = edgelist.begin(); it != edgelist.end(); ++it ) { auto first_it = nodes.find(it->first); if (first_it == nodes.end()) { // First node not found, carry on. continue; } auto second_it = nodes.find(it->second); if (second_it != nodes.end()) { // Found both edge nodes in cycle set 'nodes' // Add the edge. newlist.push_back(*it); } } edgelist = newlist; } // --------------------------------------------------------------------------- // ------[ OUTPUT FUNCTIONS ]------------------------------------------------- // --------------------------------------------------------------------------- void output_size_summary( string &dgroups_filename, SizeSum_t &size_summary ) { ofstream dgroups_file(dgroups_filename); dgroups_file << "\"num_objects\",\"size_bytes\",\"num_groups\"" << endl; for ( auto it = size_summary.begin(); it != size_summary.end(); ++it ) { unsigned int gsize = it->first; Summary *s = it->second; dgroups_file << s->num_objects << "," << s->size << "," << s->num_groups << endl; } dgroups_file.close(); } void output_type_summary( string &dgroups_by_type_filename, TypeTotalSum_t &type_total_summary ) { ofstream dgroups_by_type_file(dgroups_by_type_filename); for ( TypeTotalSum_t::iterator it = type_total_summary.begin(); it != type_total_summary.end(); ++it ) { string myType = it->first; Summary *s = it->second; dgroups_by_type_file << myType << "," << s->size << "," << s->num_groups << "," << s->num_objects << endl; } dgroups_by_type_file.close(); } // All sorts of hacky debug function. Very brittle. void debug_type_algo( Object *object, string& dgroup_kind ) { KeyType ktype = object->getKeyType(); unsigned int objId = object->getId(); if (ktype == KeyType::UNKNOWN_KEYTYPE) { cout << "ERROR: objId[ " << objId << " ] : " << "Keytype not set but algo determines [ " << dgroup_kind << " ]" << endl; return; } if (dgroup_kind == "CYCLE") { if (ktype != KeyType::CYCLE) { goto fail; } } else if (dgroup_kind == "CYCKEY") { if (ktype != KeyType::CYCLEKEY) { goto fail; } } else if (dgroup_kind == "DAG") { if (ktype != KeyType::DAG) { goto fail; } } else if (dgroup_kind == "DAGKEY") { if (ktype != KeyType::DAGKEY) { goto fail; } } else { cout << "ERROR: objId[ " << objId << " ] : " << "Unknown key type: " << dgroup_kind << endl; } return; fail: cout << "ERROR: objId[ " << objId << " ] : " << "Keytype [ " << keytype2str(ktype) << " ]" << " doesn't match [ " << dgroup_kind << " ]" << endl; return; } void output_all_objects2( string &objectinfo_filename, HeapState &myheap, std::set<ObjectId_t> dag_keys, std::set<ObjectId_t> dag_all_set, std::set<ObjectId_t> all_keys, unsigned int final_time ) { ofstream object_info_file(objectinfo_filename); object_info_file << "---------------[ OBJECT INFO ]--------------------------------------------------" << endl; const vector<string> header( { "objId", "createTime", "deathTime", "size", "type", "diedBy", "lastUpdate", "subCause", "clumpKind", "deathContext1", "deathContext2", "firstNonJavaLibMethod", "deatchContext_height", "allocContext2", "allocContextType", "createTime_alloc", "deathTime_alloc", "allocSiteName", "stability", "last_actual_timestamp", "nonJavaLibAllocSiteName" } ); for ( ObjectMap::iterator it = myheap.begin(); it != myheap.end(); ++it ) { Object *object = it->second; ObjectId_t objId = object->getId(); KeyType ktype = object->getKeyType(); string dgroup_kind; if (ktype == KeyType::CYCLE) { dgroup_kind = "CYC"; } else if (ktype == KeyType::CYCLEKEY) { dgroup_kind = "CYCKEY"; } else if (ktype == KeyType::DAG) { dgroup_kind = "DAG"; } else if (ktype == KeyType::DAGKEY) { dgroup_kind = "DAGKEY"; } else { dgroup_kind = "CYC"; } string dtype; if (object->getDiedByStackFlag()) { dtype = "S"; // by stack } else if (object->getDiedByHeapFlag()) { if (object->wasLastUpdateFromStatic()) { dtype = "G"; // by static global } else { dtype = "H"; // by heap } } else { dtype = "E"; // program end } // TODO: Commented out the CONTEXT PAIR functionality that I'm not using. // TODO // Get the context pair and type for the allocation event // TODO ContextPair allocCpair = object->getAllocContextPair(); // TODO Method *alloc_meth_ptr1 = std::get<0>(allocCpair); // TODO Method *alloc_meth_ptr2 = std::get<1>(allocCpair); // TODO string alloc_method1 = (alloc_meth_ptr1 ? alloc_meth_ptr1->getName() : "NONAME"); // TODO string alloc_method2 = (alloc_meth_ptr2 ? alloc_meth_ptr2->getName() : "NONAME"); // TODO // Get the context pair and type for the death event // TODO ContextPair deathCpair = object->getDeathContextPair(); // TODO Method *death_meth_ptr1 = std::get<0>(deathCpair); // TODO Method *death_meth_ptr2 = std::get<1>(deathCpair); // TODO string death_method1 = (death_meth_ptr1 ? death_meth_ptr1->getName() : "NONAME"); // TODO string death_method2 = (death_meth_ptr2 ? death_meth_ptr2->getName() : "NONAME"); // END TODO: CONTEXT PAIR funcionality string death_method_l1 = object->getDeathContextSiteName(1); string death_method_l2 = object->getDeathContextSiteName(2); string death_method_nonjavalib = object->get_nonJavaLib_death_context(); string last_action_method_nonjavalib = object->get_nonJavaLib_last_action_context(); string allocsite_name = object->getAllocSiteName(); string nonjlib_allocsite_name = object->getNonJavaLibAllocSiteName(); ObjectRefType objstability = object->getRefTargetType(); // S -> Stable // U -> Unstable // X -> Unknown string stability = ( (objstability == ObjectRefType::SINGLY_OWNED) ? "S" : (objstability == ObjectRefType::MULTI_OWNED ? "M" : "X") ); unsigned int dtime = object->getDeathTime(); object_info_file << objId << "," << object->getCreateTime() << "," << (dtime > 0 ? dtime : final_time) << "," << object->getSize() << "," << object->getType() << "," << dtype << "," << (object->wasLastUpdateNull() ? "NULL" : "VAL") << "," << (object->getDiedByStackFlag() ? (object->wasPointedAtByHeap() ? "SHEAP" : "SONLY") : "H") << "," << dgroup_kind //-------------------------------------------------------------------------------- << "," << death_method_l1 // Fisrt level context for death //-------------------------------------------------------------------------------- << "," << death_method_l2 // Second level context for death //-------------------------------------------------------------------------------- << "," << last_action_method_nonjavalib // first nonJavaLib method //-------------------------------------------------------------------------------- << "," << "TODO" // Full death context height // TODO << "," << alloc_method1 // Part 1 of simple context pair - alloc site //-------------------------------------------------------------------------------- << "," << "X" // padding - used to be alloc_method2 // TODO << "," << alloc_method2 // part 2 of simple context pair - alloc site //-------------------------------------------------------------------------------- << "," << "X" // padding - used to be allocContextType // TODO << "," << (object->getAllocContextType() == CPairType::CP_Call ? "C" : "R") // C is call. R is return. //-------------------------------------------------------------------------------- << "," << object->getCreateTimeAlloc() << "," << object->getDeathTimeAlloc() << "," << allocsite_name << "," << stability // S, U, or X << "," << object->getActualLastTimestamp() << "," << nonjlib_allocsite_name << endl; // TODO: The following can be made into a lookup table: // method names // allocsite names // type names // May only be necessary for performance reasons (ie, simulator eats up too much RAM // on the larger benchmarks/programs.) } object_info_file << "---------------[ OBJECT INFO END ]----------------------------------------------" << endl; object_info_file.close(); } void output_cycles( KeySet_t &keyset, string &cycle_filename, std::set<int> &node_set ) { ofstream cycle_file(cycle_filename); cycle_file << "---------------[ CYCLES ]-------------------------------------------------------" << endl; for ( KeySet_t::iterator it = keyset.begin(); it != keyset.end(); ++it ) { Object *obj = it->first; set< Object * > *sptr = it->second; unsigned int keyObjId = obj->getId(); cycle_file << keyObjId; for ( set<Object *>::iterator tmp = sptr->begin(); tmp != sptr->end(); ++tmp ) { unsigned int tmpId = (*tmp)->getId(); if (tmpId != keyObjId) { cycle_file << "," << tmpId; } node_set.insert((*tmp)->getId()); } cycle_file << endl; } cycle_file << "---------------[ CYCLES END ]---------------------------------------------------" << endl; cycle_file.close(); } unsigned int output_edges( HeapState &myheap, ofstream &edge_info_file ) { unsigned int total_done; // Iterate through for ( auto it = myheap.begin_edgestate_map(); it != myheap.end_edgestate_map(); ++it ) { std::pair< Edge *, VTime_t > key = it->first; EdgeState estate = it->second; Edge *edge = std::get<0>(key); VTime_t ctime = std::get<1>(key); assert(edge); Object *src = edge->getSource(); assert(src); VTime_t endtime = src->getDeathTime(); if ( (estate == EdgeState::DEAD_BY_OBJECT_DEATH) || (estate == EdgeState::DEAD_BY_UPDATE) || (estate == EdgeState::DEAD_BY_PROGRAM_END) ) { // If the estate is any of these 3, then we've already // saved this edge. Log a WARNING. cerr << "WARNING: edge(" << edge->getSource()->getId() << ", " << edge->getTarget()->getId() << ")[time: " << edge->getCreateTime() << "] -> Estate[" << static_cast<int>(estate) << "]" << endl; } else { if (estate == EdgeState::DEAD_BY_OBJECT_DEATH_NOT_SAVED) { estate = EdgeState::DEAD_BY_OBJECT_DEATH; } else if (estate == EdgeState::DEAD_BY_PROGRAM_END_NOT_SAVED) { estate = EdgeState::DEAD_BY_PROGRAM_END; } else if ((estate == EdgeState::NONE) or (estate == EdgeState::LIVE)) { cerr << "ERROR: edge(" << edge->getSource()->getId() << ", " << edge->getTarget()->getId() << ")[time: " << edge->getCreateTime() << "] -> Estate[" << static_cast<int>(estate) << "]" << endl; cerr << "Quitting." << endl; exit(100); } output_edge( edge, endtime, estate, edge_info_file ); total_done++; } } return total_done; } #if 0 // Commented out code. unsigned int output_edges_OLD( HeapState &myheap, string &edgeinfo_filename ) { unsigned int total_edges = 0; ofstream edge_info_file(edgeinfo_filename); edge_info_file << "---------------[ EDGE INFO ]----------------------------------------------------" << endl; // srcId, tgtId, allocTime, deathTime for ( EdgeSet::iterator it = myheap.begin_edges(); it != myheap.end_edges(); ++it ) { Edge *eptr = *it; Object *source = eptr->getSource(); Object *target = eptr->getTarget(); assert(source); assert(target); unsigned int srcId = source->getId(); unsigned int tgtId = target->getId(); EdgeState estate = eptr->getEdgeState(); unsigned int endtime = ( (estate == EdgeState::DEAD_BY_OBJECT_DEATH) ? source->getDeathTime() : eptr->getEndTime() ); // TODO: This code was meant to filter out edges not belonging to cycles. // But since we're also interested in the non-cycle nodes now, this is // probably dead code and won't be used again. TODO // set<int>::iterator srcit = node_set.find(srcId); // set<int>::iterator tgtit = node_set.find(tgtId); // if ( (srcit != node_set.end()) || (srcit != node_set.end()) ) { // TODO: Header? edge_info_file << srcId << "," << tgtId << "," << eptr->getCreateTime() << "," << endtime << "," << eptr->getSourceField() << "," << static_cast<int>(estate) << endl; // } total_edges++; } edge_info_file << "---------------[ EDGE INFO END ]------------------------------------------------" << endl; edge_info_file.close(); return total_edges; } #endif // if 0 // ---------------------------------------------------------------------- // Output the map of death context site -> count of obects dying void output_context_summary( string &context_death_count_filename, ExecState &exstate ) { ofstream cdeathfile(context_death_count_filename); cdeathfile << "\"method1\",\"method2\",\"total_count\",\"death_count\"" << endl; for ( auto it = exstate.begin_execPairCountMap(); it != exstate.end_execPairCountMap(); ++it ) { ContextPair cpair = it->first; unsigned int total = it->second; unsigned int dcount; auto iter = exstate.m_deathPairCountMap.find(cpair); dcount = ( (iter == exstate.m_deathPairCountMap.end()) ? 0 : exstate.m_deathPairCountMap[cpair] ); Method *first = std::get<0>(cpair); Method *second = std::get<1>(cpair); string meth1_name = (first ? first->getName() : "NONAME"); string meth2_name = (second ? second->getName() : "NONAME"); cdeathfile << meth1_name << "," << meth2_name << "," << total << endl; } cdeathfile.close(); } // ---------------------------------------------------------------------- // Output the map of simple context pair -> count of obects dying // OLD CODE: Currently unused as we're not doing context pairs anymore // TODO: void XXX_output_context_summary( string &context_death_count_filename, // TODO: ExecState &exstate ) // TODO: { // TODO: ofstream context_death_count_file(context_death_count_filename); // TODO: for ( auto it = exstate.begin_deathCountMap(); // TODO: it != exstate.end_deathCountMap(); // TODO: ++it ) { // TODO: ContextPair cpair = it->first; // TODO: Method *first = std::get<0>(cpair); // TODO: Method *second = std::get<1>(cpair); // TODO: unsigned int total = it->second; // TODO: unsigned int meth1_id = (first ? first->getId() : 0); // TODO: unsigned int meth2_id = (second ? second->getId() : 0); // TODO: string meth1_name = (first ? first->getName() : "NONAME"); // TODO: string meth2_name = (second ? second->getName() : "NONAME"); // TODO: char cptype = exstate.get_cptype_name(cpair); // TODO: context_death_count_file << meth1_name << "," // TODO: << meth2_name << "," // TODO: << cptype << "," // TODO: << total << endl; // TODO: } // TODO: context_death_count_file.close(); // TODO: } void output_reference_summary( string &reference_summary_filename, string &ref_reverse_summary_filename, string &stability_summary_filename, EdgeSummary_t &my_refsum, Object2EdgeSrcMap_t &my_obj2ref, EdgeSrc2Type_t &stability ) { ofstream edge_summary_file(reference_summary_filename); ofstream reverse_summary_file(ref_reverse_summary_filename); ofstream stability_summary_file(stability_summary_filename); // // Summarizes the objects pointed at by the reference (object Id + field Id) // This is the REF-SUMMARY output file. In garbology, the ReferenceReader // is responsible for reading it. for ( auto it = my_refsum.begin(); it != my_refsum.end(); ++it ) { // Key is an edge source (which we used to call 'ref') EdgeSrc_t ref = it->first; Object *obj = std::get<0>(ref); FieldId_t fieldId = std::get<1>(ref); // Value is a vector of Object pointers std::vector< Object * > objlist = it->second; ObjectId_t objId = (obj ? obj->getId() : 0); edge_summary_file << objId << "," // 1 - object Id << fieldId << ","; // 2 - field Id unsigned int actual_size = 0; for ( auto vecit = objlist.begin(); vecit != objlist.end(); ++vecit ) { if (*vecit) { ++actual_size; } } edge_summary_file << actual_size; // 3 - number of objects pointed at if (actual_size > 0) { for ( auto vecit = objlist.begin(); vecit != objlist.end(); ++vecit ) { if (*vecit) { edge_summary_file << "," << (*vecit)->getId(); // 4+ - objects pointed at } } } edge_summary_file << endl; } // // Summarizes the reverse, which is for each object (using its Id), give // the references that point to it. // This is the REF-REVERSE-SUMMARY output file. In garbology, the ReverseRefReader // is responsible for reading it. for ( auto it = my_obj2ref.begin(); it != my_obj2ref.end(); ++it ) { Object *obj = it->first; std::vector< EdgeSrc_t > reflist = it->second; if (!obj) { continue; } // obj is not NULL. ObjectId_t objId = obj->getId(); reverse_summary_file << objId << "," // 1 - object Id << reflist.size(); // 2 - number of references in lifetime for ( auto vecit = reflist.begin(); vecit != reflist.end(); ++vecit ) { Object *srcObj = std::get<0>(*vecit); FieldId_t fieldId = std::get<1>(*vecit); ObjectId_t srcId = (srcObj ? srcObj->getId() : 0); reverse_summary_file << ",(" << srcId << "," << fieldId << ")"; // 3+ - list of incoming references } reverse_summary_file << endl; } // // Summarize the stability attributes of features. // output file is *-STABILITY-SUMMARY.csv for ( auto it = stability.begin(); it != stability.end(); ++it ) { EdgeSrc_t ref = it->first; EdgeSrcType reftype = it->second; Object *obj = std::get<0>(ref); FieldId_t fieldId = std::get<1>(ref); ObjectId_t objId = (obj ? obj->getId() : 0); stability_summary_file << objId << "," // 1 - object Id << fieldId << "," // 2 - field Id << edgesrctype2shortstr(reftype) // 3 - reference stability type << endl; } // Close the files. edge_summary_file.close(); reverse_summary_file.close(); stability_summary_file.close(); } // ---------------------------------------------------------------------- int main(int argc, char* argv[]) { if (argc != 6) { cout << "Usage: " << argv[0] << " <namesfile> <output base name> <OBJDEBUG/NOOBJDEBUG> <main.class> <main.function>" << endl; cout << " git version: " << build_git_sha << endl; cout << " build date : " << build_git_time << endl; cout << " CC kind : " << Exec.get_kind() << endl; exit(1); } cout << "# git version: " << build_git_sha << endl; cout << "# build date : " << build_git_time << endl; cout << "---------------[ START ]-----------------------------------------------------------" << endl; //------------------------------------------------------------------ // FILENAME related data string basename(argv[2]); string cycle_filename( basename + "-CYCLES.csv" ); string objectinfo_filename( basename + "-OBJECTINFO.txt" ); string edgeinfo_filename( basename + "-EDGEINFO.txt" ); string typeinfo_filename( basename + "-TYPEINFO.txt" ); string summary_filename( basename + "-SUMMARY.csv" ); string dsite_filename( basename + "-DSITES.csv" ); string dgroups_filename( basename + "-DGROUPS.csv" ); string dgroups_by_type_filename( basename + "-DGROUPS-BY-TYPE.csv" ); string context_death_count_filename( basename + "-CONTEXT-DCOUNT.csv" ); string reference_summary_filename( basename + "-REF-SUMMARY.csv" ); string ref_reverse_summary_filename( basename + "-REF-REVERSE-SUMMARY.csv" ); string stability_summary_filename( basename + "-STABILITY-SUMMARY.csv" ); string call_context_filename( basename + "-CALL-CONTEXT.csv" ); ofstream call_context_file(call_context_filename); Exec.set_output( &call_context_file ); string nodemap_filename( basename + "-NODEMAP.csv" ); ofstream nodemap_file(nodemap_filename); Exec.set_nodefile( &nodemap_file ); // END FILENAME data //------------------------------------------------------------------ // Main class/function parameters string main_class(argv[4]); string main_function(argv[5]); cout << "Main class: " << main_class << endl; cout << "Main function: " << main_function << endl; // TODO: cycle command line option. Remove this option // string cycle_switch(argv[3]); // bool cycle_flag = ((cycle_switch == "NOCYCLE") ? false : true); string obj_debug_switch(argv[3]); bool obj_debug_flag = ((obj_debug_switch == "OBJDEBUG") ? true : false); if (obj_debug_flag) { cout << "Enable OBJECT DEBUG." << endl; Heap.enableObjectDebug(); // default is no debug } cout << "Read names file..." << endl; ClassInfo::read_names_file( argv[1], main_class, main_function ); cout << "Start trace..." << endl; FILE* f = fdopen(0, "r"); ofstream edge_info_file(edgeinfo_filename); edge_info_file << "---------------[ EDGE INFO ]----------------------------------------------------" << endl; unsigned int total_objects = read_trace_file(f, edge_info_file); unsigned int final_time = Exec.NowUp() + 1; unsigned int final_time_alloc = Heap.getAllocTime(); cout << "Done at update time: " << Exec.NowUp() << endl; cout << "Total objects: " << total_objects << endl; cout << "Heap.size: " << Heap.size() << endl; // assert( total_objects == Heap.size() ); Heap.end_of_program( final_time, edge_info_file ); // TODO: Call cycle detection function // NOTE: Should do_cycles return anything? TODO do_cycles( dgroups_filename, dgroups_by_type_filename, objectinfo_filename, reference_summary_filename, ref_reverse_summary_filename, stability_summary_filename, cycle_filename, edge_info_file, final_time ); ofstream summary_file(summary_filename); summary_file << "---------------[ SUMMARY INFO ]----------------------------------------------------" << endl; summary_file << "number_of_objects," << Heap.size() << endl << "number_of_edges," << Heap.numberEdges() << endl << "died_by_stack," << Heap.getTotalDiedByStack2() << endl << "died_by_heap," << Heap.getTotalDiedByHeap2() << endl << "died_by_global," << Heap.getTotalDiedByGlobal() << endl << "died_at_end," << Heap.getTotalDiedAtEnd() << endl << "last_update_null," << Heap.getTotalLastUpdateNull() << endl << "last_update_null_heap," << Heap.getTotalLastUpdateNullHeap() << endl << "last_update_null_stack," << Heap.getTotalLastUpdateNullStack() << endl << "last_update_null_size," << Heap.getSizeLastUpdateNull() << endl << "last_update_null_heap_size," << Heap.getSizeLastUpdateNullHeap() << endl << "last_update_null_stack_size," << Heap.getSizeLastUpdateNullStack() << endl << "died_by_stack_only," << Heap.getDiedByStackOnly() << endl << "died_by_stack_after_heap," << Heap.getDiedByStackAfterHeap() << endl << "died_by_stack_only_size," << Heap.getSizeDiedByStackOnly() << endl << "died_by_stack_after_heap_size," << Heap.getSizeDiedByStackAfterHeap() << endl << "no_death_sites," << Heap.getNumberNoDeathSites() << endl << "size_died_by_stack," << Heap.getSizeDiedByStack() << endl << "size_died_by_heap," << Heap.getSizeDiedByHeap() << endl << "size_died_at_end," << Heap.getSizeDiedAtEnd() << endl << "vm_RC_zero," << Heap.getVMObjectsRefCountZero() << endl << "vm_RC_positive," << Heap.getVMObjectsRefCountPositive() << endl << "max_live_size," << Heap.maxLiveSize() << endl << "main_func_uptime," << Exec.get_main_func_uptime() << endl << "main_func_alloctime," << Exec.get_main_func_alloctime() << endl << "final_time," << final_time << endl << "final_time_alloc," << final_time_alloc << endl; summary_file << "---------------[ SUMMARY INFO END ]------------------------------------------------" << endl; summary_file.close(); //--------------------------------------------------------------------- ofstream dsite_file(dsite_filename); dsite_file << "---------------[ DEATH SITES INFO ]------------------------------------------------" << endl; for ( DeathSitesMap::iterator it = Heap.begin_dsites(); it != Heap.end_dsites(); ++it ) { Method *meth = it->first; set<string> *types = it->second; if (meth && types) { dsite_file << meth->getName() << "," << types->size(); for ( set<string>::iterator sit = types->begin(); sit != types->end(); ++sit ) { dsite_file << "," << *sit; } dsite_file << endl; } } dsite_file << "---------------[ DEATH SITES INFO END ]--------------------------------------------" << endl; dsite_file.close(); dsite_file << "---------------[ DONE ]------------------------------------------------------------" << endl; cout << "---------------[ DONE ]------------------------------------------------------------" << endl; cout << "# git version: " << build_git_sha << endl; cout << "# build date : " << build_git_time << endl; }
[ "raoul@littletechtips.com" ]
raoul@littletechtips.com
2148ea8635f2a9c712219933c03dd1051ea58ed3
a66f5aab4de1367d42562f456c15fcadf304428b
/src/entityComponentSystem/EntityComponentManager.cpp
4b95d0d93ee2ca4b7a285bc623a525f2d15adce4
[ "MIT", "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
piandpower/galavant
56d4451cde5758a0a9b4c80be55ea560bf89b6d4
dbb1d1e9ef90eb2ab682838ac533d7b4545b40f9
refs/heads/master
2021-01-13T07:37:57.481620
2016-10-01T20:08:43
2016-10-01T20:08:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,127
cpp
#include "EntityComponentManager.hpp" Entity EntityComponentManager::NextNewEntity = 1; EntityComponentManager::EntityComponentManager() { } EntityComponentManager::~EntityComponentManager() { DestroyAllEntities(); } // Sets the ComponentManager for a ComponentType. Returns false if there is already a manager // for that type (it will not be set) bool EntityComponentManager::AddComponentManagerOfType(ComponentType type, ComponentManager *manager) { if (manager) { // Make sure there isn't already a ComponentManager for the type EntityComponentManager::ComponentManagerMapIterator findIt = ComponentManagers.find(type); if (findIt == ComponentManagers.end()) ComponentManagers[type] = manager; } return false; } bool EntityComponentManager::AddComponentManager(ComponentManager *manager) { return AddComponentManagerOfType(manager->GetType(), manager); } // Returns the ComponentManager assigned to the provided type, or nullptr if there isn't one // assigned. If your ComponentManager needs another, it is preferable to get its dependencies // directly (i.e. passed in during a initialize() function) ComponentManager *EntityComponentManager::GetComponentManagerForType(ComponentType type) { EntityComponentManager::ComponentManagerMapIterator findIt = ComponentManagers.find(type); if (findIt == ComponentManagers.end()) return nullptr; return findIt->second; } void EntityComponentManager::GetNewEntities(EntityList &list, int count) { for (int i = 0; i < count; i++) { list.push_back(NextNewEntity); ActiveEntities.push_back(NextNewEntity); NextNewEntity++; } } // Mark an Entity for destruction. It is not destroyed immediately; rather, it is destroyed when // DestroyEntitiesPendingDestruction() is called. void EntityComponentManager::MarkDestroyEntities(EntityList &entities) { EntitiesPendingDestruction.insert(EntitiesPendingDestruction.end(), entities.begin(), entities.end()); } void EntityComponentManager::UnsubscribeEntitiesFromAllManagers(EntityList &entitiesToUnsubscribe) { // Unsubscribe all of the entities from all ComponentManagers // Some component managers will not actually have the Entity being destroyed subscribed, but // that's fine for (EntityComponentManager::ComponentManagerMapIterator it = ComponentManagers.begin(); it != ComponentManagers.end(); ++it) { ComponentManager *currentComponentManager = it->second; if (currentComponentManager) currentComponentManager->UnsubscribeEntities(entitiesToUnsubscribe); } } // Destroy all entities which have been marked for destruction. Because an entity is just an ID // and a collection of components, this function must notify all ComponentManagers that the // Entity should be unsubscribed from their services. void EntityComponentManager::DestroyEntitiesPendingDestruction(void) { if (!EntitiesPendingDestruction.empty()) { // Ensure there are no duplicates in EntitiesPendingDestruction EntityListSortAndRemoveDuplicates(EntitiesPendingDestruction); UnsubscribeEntitiesFromAllManagers(EntitiesPendingDestruction); // Remove all destroyed entities from the ActiveEntities list EntityListRemoveNonUniqueEntitiesInSuspect(EntitiesPendingDestruction, ActiveEntities); EntitiesPendingDestruction.clear(); } } // Destroys all entities that were created by this EntityComponentManager (i.e. all entities in // the ActiveEntities list) void EntityComponentManager::DestroyAllEntities(void) { // Mark all active entities as pending destruction. I do this because if I just destroyed // ActiveEntities, then EntitiesPendingDestruction could have entities which have already been // destroyed and entities which weren't active (i.e. not created by this manager) but marked for // destruction. By effectively combining the two in MarkDestroyEntities(), we ensure all // entities are going to be destroyed MarkDestroyEntities(ActiveEntities); DestroyEntitiesPendingDestruction(); ActiveEntities.clear(); // this should be empty anyways EntitiesPendingDestruction.clear(); }
[ "macoymadson@gmail.com" ]
macoymadson@gmail.com
551d0d0c6a9a29bc34d083677bed8563e979f244
0d3907be308b4340d2d3e6cb3c8deaf72378f92c
/lec04/drawSquare.cpp
d1af594f62a2a1d470df318242acf447d8d5a177
[]
no_license
ucsb-cs16-s20-nichols/code-from-class
360041ad51e31b429ddc91aed36247d3b82edc1e
640c38267175c50326a1053a468553ff8055af97
refs/heads/master
2021-04-12T19:35:10.525625
2020-06-11T19:15:18
2020-06-11T19:15:18
249,104,417
1
4
null
null
null
null
UTF-8
C++
false
false
928
cpp
#include <iostream> #include <cstdlib> #include <string> using namespace std; // declare drawSquare string drawSquare(int n); int main(int argc, char *argv[]) { // get the width from the user int n; cout << "Enter the width of the square\n"; cin >> n; // call the drawSquare function to help output the square cout << drawSquare(n) << endl; return 0; } // define drawSquare string drawSquare(int n) { string result = ""; // keep adding up character into this string // draw an n * n square of '*' characters // this outer loops makes sure to print n lines of (n stars) for (int i = 0; i < n; i++) { // iterate n times the outer loop // this inner loop worries about printing a single line of n stars for (int j = 0; j < n; j++) { // iterate n times the inner loop result = result + "* "; } result += '\n'; } return result; }
[ "lawtonnichols@gmail.com" ]
lawtonnichols@gmail.com
858e34f084243bc22bf1e71f734ea06fd846c52e
7ae73c0b3e781fbee094ffd366137b1929ea4919
/src/automation.cpp
82cc06b3077d5032ea73f25805b19258e5b83e9e
[]
no_license
IllinoisAUV/Automation
b7e23ce4761fedc20d0ecd958b09e69197e64c05
d508b819e05d48ba679c2983842944a31d810659
refs/heads/master
2021-01-09T06:23:25.900294
2017-08-15T16:30:24
2017-08-15T16:30:24
80,970,549
0
0
null
null
null
null
UTF-8
C++
false
false
6,577
cpp
/* * File: automation_ws/src/automation.cpp * Author: Shubhankar Agarwal <shubhankar0109@@gmail.com> * Date: February 2017 * Description: Automation the control of the bluerov. */ #include "automation.h" #include <errno.h> #include <fcntl.h> #include <math.h> #include <mavros_msgs/CommandBool.h> #include <mavros_msgs/OverrideRCIn.h> #include <mavros_msgs/SetMode.h> #include <mavros_msgs/StreamRate.h> #include <ros/console.h> #include <ros/ros.h> #include <sensor_msgs/FluidPressure.h> #include <sensor_msgs/Imu.h> #include <stdio.h> #include <tf2/transform_datatypes.h> #include <unistd.h> #include <functional> using mavros_msgs::OverrideRCIn; using mavros_msgs::StreamRate; using sensor_msgs::Imu; using sensor_msgs::FluidPressure; using mavros_msgs::SetMode; #define CONSTRAIN(num, min, max) (num < min ? min : (num > max ? max : num)) bool Automation::armed_; Automation::Automation() { imu_sub_ = nh.subscribe("/mavros/imu/data", 1, &Automation::imuCallback, this); rc_override_pub_ = nh.advertise<OverrideRCIn>("/mavros/rc/override", 1); angular_setpoint_sub_ = nh.subscribe("/vehicle/angular/setpoint", 1, &Automation::angularSetpointCallback, this); linear_setpoint_sub_ = nh.subscribe( "/vehicle/linear/setpoint", 1, &Automation::linearSetpointCallback, this); arming_sub_ = nh.subscribe("/vehicle/arming", 1, &Automation::armingCallback, this); kill_sub_ = nh.subscribe("/kill_switch", 1, &Automation::killCallback, this); arming_client_ = nh.serviceClient<mavros_msgs::CommandBool>("/mavros/cmd/arming"); mode_client_ = nh.serviceClient<mavros_msgs::SetMode>("mavros/set_mode"); rate_client_ = nh.serviceClient<StreamRate>("/mavros/set_stream_rate"); mode_ = MODE_DEPTH_HOLD; new_mode_ = true; camera_tilt_ = 1500; } void Automation::killCallback(const std_msgs::Bool::ConstPtr &kill) { if (kill->data) { // Causes a race on debounce? DisarmPixhawk(); } } void Automation::setMode(Mode mode) { mode_ = mode; SetMode mode_cmd; mode_cmd.request.base_mode = 0; switch (mode) { case MODE_STABILIZE: mode_cmd.request.custom_mode = "STABILIZE"; break; case MODE_MANUAL: mode_cmd.request.custom_mode = "MANUAL"; break; case MODE_DEPTH_HOLD: mode_cmd.request.custom_mode = "ALT_HOLD"; break; } if (mode_client_.call(mode_cmd) && mode_cmd.response.success) { ROS_INFO("Mode changed"); } else { ROS_INFO("Failed to change mode"); return; } } void Automation::ArmPixhawk() { ROS_INFO("Arming PixHawk"); ros::NodeHandle n; ros::ServiceClient client = n.serviceClient<mavros_msgs::CommandBool>("/mavros/cmd/arming"); mavros_msgs::CommandBool srv; srv.request.value = true; if (!client.call(srv)) { ROS_INFO("Failed to arm"); return; } armed_ = true; } void Automation::DisarmPixhawk() { ROS_INFO("Disarming PixHawk"); ros::NodeHandle n; ros::ServiceClient client = n.serviceClient<mavros_msgs::CommandBool>("/mavros/cmd/arming"); mavros_msgs::CommandBool srv; srv.request.value = false; if (!client.call(srv)) { ROS_INFO("Failed to disarm"); return; } armed_ = false; } void Automation::SetIMURate(int hz) { ROS_INFO("Setting the IMU Rate to %d Hz", hz); ros::NodeHandle n; ros::ServiceClient client = n.serviceClient<StreamRate>("/mavros/set_stream_rate"); StreamRate srv; srv.request.stream_id = 0; // StreamRate::STREAM_ALL; srv.request.message_rate = hz; srv.request.on_off = 0; if (!client.call(srv)) { ROS_ERROR("Failed to call set_stream_rate service"); } } void Automation::setRPY(double roll, double pitch, double yaw) { // Map angle to [-pi, pi] roll_set_ = roll - (round(roll / M_PI) * M_PI); pitch_set_ = pitch - (round(pitch / M_PI) * M_PI); } void Automation::imuCallback(const sensor_msgs::Imu::ConstPtr &msg) { #if 0 tf::Quaternion q(msg->orientation.x, msg->orientation.y, msg->orientation.z, msg->orientation.w); tf::Matrix3x3 m(q); m.getRPY(roll_, pitch_, yaw_); /* ROS_INFO("Got rpy: %f %f %f", roll_, pitch_, yaw_); */ roll_dot_ = msg->angular_velocity.x; pitch_dot_ = msg->angular_velocity.y; yaw_dot_ = msg->angular_velocity.z; #endif } void Automation::armingCallback(const std_msgs::Bool::ConstPtr &msg) { ROS_INFO("Received arm command: %s", msg->data ? "true" : "false"); if (msg->data) { Automation::ArmPixhawk(); } else { Automation::DisarmPixhawk(); } } void Automation::angularSetpointCallback( const geometry_msgs::Vector3::ConstPtr &msg) { ROS_INFO("Received angular setpoint: %f %f %f", msg->x, msg->y, msg->z); roll_set_ = CONSTRAIN(msg->x, -M_PI, M_PI); pitch_set_ = CONSTRAIN(msg->y, -M_PI, M_PI); yaw_dot_ = CONSTRAIN(msg->z, -1.0, 1.0); } void Automation::linearSetpointCallback( const geometry_msgs::Vector3::ConstPtr &msg) { ROS_INFO("Received linear setpoint: %f %f %f", msg->x, msg->y, msg->z); xdot_ = CONSTRAIN(msg->x, -1.0, 1.0); ydot_ = CONSTRAIN(msg->y, -1.0, 1.0); zdot_ = CONSTRAIN(msg->z, -1.0, 1.0); } void Automation::spin(float hz) { ros::Rate rate(hz); while (ros::ok()) { ros::spinOnce(); OverrideRCIn msg; msg.channels[1] = angleToPpm(roll_set_); msg.channels[0] = angleToPpm(pitch_set_); msg.channels[3] = speedToPpm(yaw_dot_); msg.channels[5] = speedToPpm(xdot_); msg.channels[6] = speedToPpm(ydot_); msg.channels[2] = speedToPpm(zdot_); msg.channels[4] = mode_; msg.channels[7] = camera_tilt_; rc_override_pub_.publish(msg); rate.sleep(); } } void Automation::setSpeed(double x, double y, double z) { xdot_ = x; ydot_ = y; zdot_ = z; } uint16_t Automation::angleToPpm(double angle) { // Map [-pi, pi] -> [1000, 2000] uint16_t ppm = (angle - (-M_PI)) / (M_PI - (-M_PI)) * (1000) + 1000; return ppm; } uint16_t Automation::speedToPpm(double speed) { if (speed > 1.0 || speed < -1.0) { ROS_ERROR("Invalid speed requested: %f", speed); return 1500; } return 1500 + speed * 500.0; } void Automation::spinOnce() { if(new_mode_) { setMode(mode_); new_mode_ = false; } OverrideRCIn msg; msg.channels[1] = angleToPpm(roll_set_); msg.channels[0] = angleToPpm(pitch_set_); msg.channels[3] = speedToPpm(yaw_dot_); msg.channels[5] = speedToPpm(xdot_); msg.channels[6] = speedToPpm(ydot_); msg.channels[2] = speedToPpm(zdot_); msg.channels[4] = 1500; msg.channels[7] = camera_tilt_; rc_override_pub_.publish(msg); }
[ "abrandemuehl@gmail.com" ]
abrandemuehl@gmail.com
c3d9b3c5da4438b204992102beda9db9c024a98a
222c0d1fbbb9320fa5198712a02c4a8e52ef5fda
/clasa a XI a/informatica/2017.03.21/pb10/main.cpp
0bd412f6b245d5a98686200d16a647b975643a12
[]
no_license
ruxandramatei/liceu
f2952a25174e90ad21db413cd6da259006b91d73
07a92ceca34b530a6432783f94a65f67d54b9a2a
refs/heads/master
2020-12-25T22:31:50.287125
2017-07-09T17:02:19
2017-07-09T17:02:19
68,613,285
3
0
null
null
null
null
UTF-8
C++
false
false
906
cpp
#include <iostream> #include <fstream> using namespace std; ifstream in("pb.in"); ofstream out("pb.out"); int a[101][101], b[101][101], n, m; void citire(){ in>>n>>m; for(int i=1;i<=m;i++){ int x, y; in>>x>>y; a[x][y]=a[y][x]=1; } } void bf(int x){ int c[101],d[101],p,u,temp; temp=x; for(int i=1;i<=n;i++){ d[i]=-1; } p=u=1; d[x]=0; c[1]=x; while(p<=u){ x=c[p++]; for(int i=1;i<=n;i++) if(a[x][i]==1 && d[i]==-1){ d[i]=d[x]+1; c[++u]=i; } } for(int i=1;i<=n;i++) b[i][temp]=d[i]; } int main() { citire(); for(int i=1;i<=n;i++) bf(i); for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++) if(b[i][j]==-1) out<<"0 "; else out<<"1 "; out<<'\n'; } return 0; }
[ "ruxandramatei0@gmail.com" ]
ruxandramatei0@gmail.com
768add765cc6156084b3ac1eba892cb7a723f033
615250894ed0927703142f4271a99ba42ae500c5
/KT-817GroundControlStation/main.cpp
5ff60a560f4384fba1a0b99a6dbe31c3bcbff5e8
[]
no_license
AliEmreKeskin/savasan-iha
2ef06375c9a5301ea4c8db972d52013c18e6bffc
9056040bd62d56909ac03b461d9332a28cb9024e
refs/heads/master
2022-11-05T11:51:29.871834
2019-06-25T13:01:03
2019-06-25T13:01:03
192,405,507
4
1
null
2022-11-01T06:11:38
2019-06-17T19:22:13
C++
UTF-8
C++
false
false
429
cpp
#include "mainview.h" #include <QApplication> #include <QtGui> #include "mywidget.h" #include <QDesktopWidget> int main(int argc, char *argv[]) { QApplication a(argc, argv); MainView w; QRect screenGeometry = QApplication::desktop()->screenGeometry(); int x = (screenGeometry.width()-w.width()) / 2; int y = (screenGeometry.height()-w.height()) / 2; w.move(x, y); w.show(); return a.exec(); }
[ "aliemrekeskin@outlook.com" ]
aliemrekeskin@outlook.com
6ecb826f11c94ecb8ded8acf25f398161a36a686
67a0abd89ff033d00c1ea73baebf6820da3c2dc3
/UI.cpp
184de0541abe76cbc4155b9f4376542afc9a29be
[]
no_license
CodeSausage/Snake_by_Cpp
4143a5385ad32aeec5f14c0848b32670faf02509
e076061a5ccd5f6c0ffe39836c4c63443c291e68
refs/heads/master
2022-07-17T07:27:51.616234
2020-05-17T07:56:21
2020-05-17T07:56:21
264,605,965
0
0
null
null
null
null
GB18030
C++
false
false
847
cpp
#include "UI.h" #include "贪吃蛇.h" UI::UI(int x = 1, int y = 0) { _level = x; _score = y; } void UI::Draw() { RECT scoreRect = { 10, 10, 140, 50 }; RECT scoreRect2 = { 20, 10, 150, 50 }; //string score = "分数"; drawtext(_T("分数: "), &scoreRect, DT_CENTER); TCHAR s[5]; swprintf_s(s, _T("%d"), _score); outtextxy(30, 10, s); //drawtext('c', &scoreRect, DT_CENTER); RECT levelRect = { 10, 240, 140, 290 }; RECT levelRect2 = { 20, 240, 150, 290 }; drawtext(_T("难度"), &levelRect, DT_CENTER); TCHAR s2[5]; swprintf_s(s2, _T("%d"), _level); outtextxy(30, 240, s2); //drawtext(_level, &levelRect2, DT_CENTER); } void UI::Compute_Score() { _score++; } void UI::SetLevel(int x) { _level = x; } int UI::GetLevel() { return _level; } int UI::GetScore() { return _score; }
[ "noreply@github.com" ]
noreply@github.com
74849f510f5c8c4cfd28c689d9e5e95435768a19
4a19825243ab58f036bc63769b77fc5e35ddd1f7
/BANKING_HW5/Account.h
a010207af9c07d800b217573319d15242af2308a
[]
no_license
swescott17/BANKING_HW5
6b5de023bc300d2b62a4402d6e558cdbddbb906e
d13449f27542aeced5dced2f85b08290712bb5e9
refs/heads/master
2021-01-21T17:17:09.084241
2017-03-17T22:15:58
2017-03-17T22:15:58
85,127,442
0
0
null
null
null
null
UTF-8
C++
false
false
5,747
h
#ifndef ACCOUNT_H_ #define ACCOUNT_H_ #include <string> #include <vector> #include <sstream> #include "Customer.h" #include "Transaction.h" using namespace std; /** The Bank has Accounts and an Account belongs to a Customer. Additionally, there are specialized types of accounts: Checking_Account and Savings_Account. Checking_Account and Savings_Account have specialized ways of adding interest, and describing itself. @author: Ed Walker */ class Account { protected: Customer* customer; // The customer who owns this account double balance; // The available balance in this account int account_number; // A unique number identifying this account std::vector<Transaction *> transactions; // The record of transactions that have occured with this account /** Describe fees associated with the customer who owns this account. The fee will depend on the specific type of customer. @return string showing checking and overdraft fees */ std::string get_fees() { int overdraft, charge; // Polymorphism: calls the correct virtual methods from the specific customer type // FIXME: Get the overdraft and check charge information from this accounts customer std::stringstream ss; ss << "Check Charge: " << charge << " Overdraft Fee: " << overdraft; return ss.str(); } protected: /** Add interest based on a specified interest rate to account @param interest The interest rate */ void add_interest(double interest) { double amt = balance*interest; balance = balance + amt; std::string fees = get_fees(); Transaction *tran = NULL; // FIXME: Create a Transaction object and assign it to the transaction vector. transactions.push_back(tran); } public: /** Constructor requires a customer to create an account Balance always starts with 0 when account is created. */ Account() {} Account(Customer *cust, int id) : customer(cust), account_number(id), balance(0) {} /** Generic accesser and setter methods for properties customer, balance, and account_number */ Customer *get_customer() { return customer; } void set_customer(Customer *cust) { customer = cust; } int get_account() { return account_number; } void set_balance(double new_balance) { balance = new_balance; } void set_account(int account_number) { this->account_number = account_number; } double get_balance() { return balance; } /** Generic method describing the account information. Remember that you will need to indicate if an account is Savings or Checking in an overridden version of to_string() in the derived classes. @return string describing generic information about the account */ virtual std::string to_string() { std::stringstream ss; // for composing the string that describes this account // FIXME: Add information about the customer who owns this account. ss << " Balance: " << balance << std::endl; ss << " Account ID: " << account_number << std::endl; return ss.str(); } /** Deposits amount into account @param amt The deposit amount */ virtual void deposit(double amt) { balance += amt; std::string fees = get_fees(); Transaction *tran = NULL; // FIXME: Create a Transaction object and assign it to transaction vector. transactions.push_back(tran); } /** Withdraws amount from account @param amt The withdrawal amount */ virtual void withdraw(double amt) { balance -= amt; std::string fees = get_fees(); Transaction *tran = NULL; // FIXME: Create a Transaction object and assign it to tran. transactions.push_back(tran); } // We want the Savings_Account and Checking_Account to implement this. virtual void add_interest() = 0; }; class Savings_Account : public Account { private: Customer* customer; // The customer who owns this account double balance; // The available balance in this account int account_number; // A unique number identifying this account public: Savings_Account() {} Savings_Account(Customer *cust, int id) { customer = cust; account_number = id; } void add_interest() //interest added to customer's current interest { double interest; Customer * customer1 = this->get_customer(); interest = customer1->get_sInterest(); /*if (typeid(Adult) == typeid(*customer1)) { Adult* m = static_cast<Adult*>(customer1); interest = m.get_sInterest(); } if (typeid(Senior) == typeid(*customer)) { Senior* newm = static_cast<Senior*>(customer); interest = newm.get_sInterest(); } if (typeid(Student) == typeid(*customer)) { Student* newm = static_cast<Student*>(customer); interest = newm.get_sInterest(); } else { interest = 0.01; }*/ balance = balance + (balance*interest); } }; class Checking_Account : public Account { private: Customer* customer; // The customer who owns this account double balance; // The available balance in this account int account_number; // A unique number identifying this account public: Checking_Account() {} Checking_Account(Customer *cust, int id) { customer = cust; account_number = id; } void add_interest() { double interest; Customer * customer1 = this->get_customer(); interest = customer1->get_cInterest(); /*if (typeid(Adult) == typeid(*customer1)) { Adult* m = static_cast<Adult*>(customer1); interest = m.get_cInterest(); } if (typeid(Senior) == typeid(*customer)) { Senior* newm = static_cast<Senior*>(customer); interest = newm.get_cInterest(); } if (typeid(Student) == typeid(*customer)) { Student* newm = static_cast<Student*>(customer); interest = newm.get_cInterest(); } else { interest = 0.01; }*/ balance = balance + (balance*interest); } }; //adf #endif
[ "swescott17@my.whitworth.edu" ]
swescott17@my.whitworth.edu
a94b5a35ad7e0824469da30425f327dac362ac3f
4afa80f87a5b4e2e9911c368b34e7230fe4e3d03
/FloorTile.cc
ecbd7b03a54d39a53be06c473a19cc7208460a86
[]
no_license
JackyT0n/Dungeon-Crawler
66e0dffd10c2b8f28fcc116190004c5e26a65eb8
1440aee4f2a4b7609fb1d75098ed9fb0c818b928
refs/heads/master
2020-06-26T04:32:49.734177
2019-07-29T22:02:58
2019-07-29T22:02:58
199,531,912
0
0
null
null
null
null
UTF-8
C++
false
false
1,290
cc
#include "FloorTile.h" using namespace std; #include <iostream> #include "DHoard.h" FloorTile::FloorTile(int xPos, int yPos): Cell(xPos, yPos){ walkable = true; } FloorTile::~FloorTile(){ delete charOnTile; delete itemOnTile; } void FloorTile:: setDisplay(char newDisplay){ display = newDisplay; } SubscriptionType FloorTile::subType() const{return SubscriptionType::All;} void FloorTile::notify(Subject &whoNotified){ if (charOnTile && charOnTile->getDisplay() != 'D'){ //calls the beStruckBy of the PC whoNotified.getInfo().charOnTile->beStruckBy(*charOnTile); } else if(itemOnTile){ string type = itemOnTile->getName(); ActionDisplay::setPotion(type,false); if (itemOnTile->getName() == "hoard"){ DHoard * theHoard = reinterpret_cast<DHoard *>(itemOnTile); whoNotified.getInfo().charOnTile->beStruckBy(*theHoard->getDrag()); } } } Info FloorTile::getInfo() const { char the_display; if (charOnTile){ the_display = charOnTile->getDisplay(); } else if (itemOnTile){ the_display = itemOnTile->getDisplay(); } else{ the_display = display; } Info cellInfo = {xPos, yPos, the_display, addedToChamber, charOnTile, itemOnTile}; return cellInfo; } void FloorTile::flipAddedToChamber(){ addedToChamber = true; }
[ "noreply@github.com" ]
noreply@github.com
c1fb2e4cdc736e781705ea0540c6c6dcf1cd6944
35d27f8663fcdebccb13fabab06812af96acdc4b
/codeforces/101853/h/h.cpp
8ee100c64dad98d5ab3285835c11544818868942
[]
no_license
noooaah/solved_problem
666490ca49e0001e3919ad7f29180d59caa0a16b
fbcebe223f063623f45415548f9f265e385ddac0
refs/heads/master
2023-03-17T18:27:05.712309
2019-09-05T13:10:01
2019-09-05T13:10:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
229
cpp
#include<bits/stdc++.h> using namespace std; main() { int t; scanf("%d" , &t); while(t --) { int n; scanf("%d" , &n); n = sqrt(n/6); printf("%d\n" , n); } }
[ "evoiz963@gmail.com" ]
evoiz963@gmail.com
d044ba543f82310083fc11a077441ec7ea3979bc
007d63d4cb49676fd678840a3e1244ad63bdb121
/released_plugins_more/visiocyte_plugins/resample_swc/resampling.h
b696356b96581a314610a260342530ad52372d37
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
satya-arjunan/visiocyte
1a09cc886b92ca10c80b21d43220b33c6009e079
891404d83d844ae94ee8f1cea1bb14deba588c4f
refs/heads/master
2020-04-23T02:07:33.357029
2019-04-08T06:40:03
2019-04-08T06:40:03
170,835,824
0
0
null
null
null
null
UTF-8
C++
false
false
4,370
h
//resample neuronTree subject to a step length //2012-02-29 by Yinan Wan //2012-03-05 Yinan Wan: interpolate radius #ifndef __RESAMPLING_H__ #define __RESAMPLING_H__ #include "basic_surf_objs.h" #include <vector> using namespace std; #define DISTP(a,b) sqrt(((a)->x-(b)->x)*((a)->x-(b)->x)+((a)->y-(b)->y)*((a)->y-(b)->y)+((a)->z-(b)->z)*((a)->z-(b)->z)) struct Point; struct Point { double x,y,z,r; VISIOCYTELONG type; Point* p; VISIOCYTELONG childNum; VISIOCYTELONG level,seg_id; QList<float> fea_val; }; typedef vector<Point*> Segment; typedef vector<Point*> Tree; void resample_path(Segment * seg, double step) { char c; Segment seg_r; double path_length = 0; Point* start = seg->at(0); Point* seg_par = seg->back()->p; VISIOCYTELONG iter_old = 0; seg_r.push_back(start); while (iter_old < seg->size() && start && start->p) { path_length += DISTP(start,start->p); if (path_length<=seg_r.size()*step) { start = start->p; iter_old++; } else//a new point should be created { path_length -= DISTP(start,start->p); Point* pt = new Point; double rate = (seg_r.size()*step-path_length)/(DISTP(start,start->p)); pt->x = start->x + rate*(start->p->x-start->x); pt->y = start->y + rate*(start->p->y-start->y); pt->z = start->z + rate*(start->p->z-start->z); pt->r = start->r*(1-rate) + start->p->r*rate;//intepolate the radius pt->p = start->p; if (rate<0.5) { pt->type = start->type; pt->seg_id = start->seg_id; pt->level = start->level; pt->fea_val = start->fea_val; } else { pt->type = start->p->type; pt->seg_id = start->p->seg_id; pt->level = start->p->level; pt->fea_val = start->p->fea_val; } seg_r.back()->p = pt; seg_r.push_back(pt); path_length += DISTP(start,pt); start = pt; } } seg_r.back()->p = seg_par; for (VISIOCYTELONG i=0;i<seg->size();i++) if (!seg->at(i)) {delete seg->at(i); seg->at(i) = NULL;} *seg = seg_r; }; NeuronTree resample(NeuronTree input, double step) { NeuronTree result; VISIOCYTELONG siz = input.listNeuron.size(); Tree tree; for (VISIOCYTELONG i=0;i<siz;i++) { NeuronSWC s = input.listNeuron[i]; Point* pt = new Point; pt->x = s.x; pt->y = s.y; pt->z = s.z; pt->r = s.r; pt ->type = s.type; pt->seg_id = s.seg_id; pt->level = s.level; pt->fea_val = s.fea_val; pt->p = NULL; pt->childNum = 0; tree.push_back(pt); } for (VISIOCYTELONG i=0;i<siz;i++) { if (input.listNeuron[i].pn<0) continue; VISIOCYTELONG pid = input.hashNeuron.value(input.listNeuron[i].pn); tree[i]->p = tree[pid]; tree[pid]->childNum++; } // printf("tree constructed.\n"); vector<Segment*> seg_list; for (VISIOCYTELONG i=0;i<siz;i++) { if (tree[i]->childNum!=1)//tip or branch point { Segment* seg = new Segment; Point* cur = tree[i]; do { seg->push_back(cur); cur = cur->p; } while(cur && cur->childNum==1); seg_list.push_back(seg); } } // printf("segment list constructed.\n"); for (VISIOCYTELONG i=0;i<seg_list.size();i++) { resample_path(seg_list[i], step); } // printf("resample done.\n"); tree.clear(); map<Point*, VISIOCYTELONG> index_map; for (VISIOCYTELONG i=0;i<seg_list.size();i++) for (VISIOCYTELONG j=0;j<seg_list[i]->size();j++) { tree.push_back(seg_list[i]->at(j)); index_map.insert(pair<Point*, VISIOCYTELONG>(seg_list[i]->at(j), tree.size()-1)); } for (VISIOCYTELONG i=0;i<tree.size();i++) { NeuronSWC S; Point* p = tree[i]; S.n = i+1; if (p->p==NULL) S.pn = -1; else S.pn = index_map[p->p]+1; if (p->p==p) printf("There is loop in the tree!\n"); S.x = p->x; S.y = p->y; S.z = p->z; S.r = p->r; S.type = p->type; S.seg_id = p->seg_id; S.level = p->level; S.fea_val = p->fea_val; result.listNeuron.push_back(S); } for (VISIOCYTELONG i=0;i<tree.size();i++) { if (tree[i]) {delete tree[i]; tree[i]=NULL;} } for (VISIOCYTELONG j=0;j<seg_list.size();j++) if (seg_list[j]) {delete seg_list[j]; seg_list[j] = NULL;} for (VISIOCYTELONG i=0;i<result.listNeuron.size();i++) result.hashNeuron.insert(result.listNeuron[i].n, i); return result; } #endif
[ "satya.arjunan@gmail.com" ]
satya.arjunan@gmail.com
531d549b88083f9c554b8ca1191174b8d1bf2849
056fcc67222afe34d96fd9cadb35469f6d305907
/driveronly_mp_rom/frameworks/av/libvideoeditor/lvpp/PreviewPlayer.cpp
5e741075739e32570fcef440243e961d1c6f6129
[ "LicenseRef-scancode-unicode", "Apache-2.0" ]
permissive
datagutt/12055
a9e98f2972a76d92b7d07eee690cd1300b780efe
593741d834fff91ad3587c762caea5f00b69ba69
refs/heads/master
2020-07-21T13:04:55.731555
2013-10-10T06:12:43
2013-10-10T06:12:43
14,116,459
1
1
null
null
null
null
UTF-8
C++
false
false
62,319
cpp
/* * Copyright (C) 2011 The Android 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. */ // #define LOG_NDEBUG 0 #define LOG_TAG "PreviewPlayer" #include <utils/Log.h> #include <binder/IPCThreadState.h> #include <binder/IServiceManager.h> #include <media/IMediaPlayerService.h> #include <media/stagefright/DataSource.h> #include <media/stagefright/MediaBuffer.h> #include <media/stagefright/MediaDefs.h> #include <media/stagefright/MediaExtractor.h> #include <media/stagefright/MediaSource.h> #include <media/stagefright/MetaData.h> #include <media/stagefright/OMXCodec.h> #include <media/stagefright/foundation/ADebug.h> #include <gui/Surface.h> #include <gui/ISurfaceTexture.h> #include <gui/SurfaceTextureClient.h> #include "VideoEditorPreviewController.h" #include "DummyAudioSource.h" #include "DummyVideoSource.h" #include "VideoEditorSRC.h" #include "PreviewPlayer.h" namespace android { void addBatteryData(uint32_t params) { sp<IBinder> binder = defaultServiceManager()->getService(String16("media.player")); sp<IMediaPlayerService> service = interface_cast<IMediaPlayerService>(binder); CHECK(service.get() != NULL); service->addBatteryData(params); } struct PreviewPlayerEvent : public TimedEventQueue::Event { PreviewPlayerEvent( PreviewPlayer *player, void (PreviewPlayer::*method)()) : mPlayer(player), mMethod(method) { } protected: virtual ~PreviewPlayerEvent() {} virtual void fire(TimedEventQueue *queue, int64_t /* now_us */) { (mPlayer->*mMethod)(); } private: PreviewPlayer *mPlayer; void (PreviewPlayer::*mMethod)(); PreviewPlayerEvent(const PreviewPlayerEvent &); PreviewPlayerEvent &operator=(const PreviewPlayerEvent &); }; PreviewPlayer::PreviewPlayer(NativeWindowRenderer* renderer) : mQueueStarted(false), mTimeSource(NULL), mVideoRendererIsPreview(false), mAudioPlayer(NULL), mDisplayWidth(0), mDisplayHeight(0), mFlags(0), mExtractorFlags(0), mVideoBuffer(NULL), mLastVideoTimeUs(-1), mNativeWindowRenderer(renderer), mCurrFramingEffectIndex(0), mFrameRGBBuffer(NULL), mFrameYUVBuffer(NULL) { CHECK_EQ(mClient.connect(), (status_t)OK); DataSource::RegisterDefaultSniffers(); mVideoRenderer = NULL; mEffectsSettings = NULL; mAudioPlayer = NULL; mAudioMixStoryBoardTS = 0; mCurrentMediaBeginCutTime = 0; mCurrentMediaVolumeValue = 0; mNumberEffects = 0; mDecodedVideoTs = 0; mDecVideoTsStoryBoard = 0; mCurrentVideoEffect = VIDEO_EFFECT_NONE; mProgressCbInterval = 0; mNumberDecVideoFrames = 0; mOverlayUpdateEventPosted = false; #ifndef ANDROID_DEFAULT_CODE mIsFirstFrame = true; #endif mIsChangeSourceRequired = true; mVideoEvent = new PreviewPlayerEvent(this, &PreviewPlayer::onVideoEvent); mVideoEventPending = false; mVideoLagEvent = new PreviewPlayerEvent(this, &PreviewPlayer::onVideoLagUpdate); mVideoEventPending = false; mCheckAudioStatusEvent = new PreviewPlayerEvent( this, &PreviewPlayer::onCheckAudioStatus); mAudioStatusEventPending = false; mStreamDoneEvent = new PreviewPlayerEvent( this, &PreviewPlayer::onStreamDone); mStreamDoneEventPending = false; mProgressCbEvent = new PreviewPlayerEvent(this, &PreviewPlayer::onProgressCbEvent); mOverlayUpdateEvent = new PreviewPlayerEvent(this, &PreviewPlayer::onUpdateOverlayEvent); mProgressCbEventPending = false; mOverlayUpdateEventPending = false; mRenderingMode = (M4xVSS_MediaRendering)MEDIA_RENDERING_INVALID; mIsFiftiesEffectStarted = false; reset(); } PreviewPlayer::~PreviewPlayer() { if (mQueueStarted) { mQueue.stop(); } reset(); if (mVideoRenderer) { mNativeWindowRenderer->destroyRenderInput(mVideoRenderer); } Mutex::Autolock lock(mLock); clear_l(); mClient.disconnect(); } void PreviewPlayer::cancelPlayerEvents_l(bool updateProgressCb) { mQueue.cancelEvent(mVideoEvent->eventID()); mVideoEventPending = false; mQueue.cancelEvent(mStreamDoneEvent->eventID()); mStreamDoneEventPending = false; mQueue.cancelEvent(mCheckAudioStatusEvent->eventID()); mAudioStatusEventPending = false; mQueue.cancelEvent(mVideoLagEvent->eventID()); mVideoLagEventPending = false; if (updateProgressCb) { mQueue.cancelEvent(mProgressCbEvent->eventID()); mProgressCbEventPending = false; } } status_t PreviewPlayer::setDataSource(const char *path) { Mutex::Autolock autoLock(mLock); return setDataSource_l(path); } status_t PreviewPlayer::setDataSource_l(const char *path) { reset_l(); mUri = path; // The actual work will be done during preparation in the call to // ::finishSetDataSource_l to avoid blocking the calling thread in // setDataSource for any significant time. return OK; } status_t PreviewPlayer::setDataSource_l(const sp<MediaExtractor> &extractor) { bool haveAudio = false; bool haveVideo = false; for (size_t i = 0; i < extractor->countTracks(); ++i) { sp<MetaData> meta = extractor->getTrackMetaData(i); const char *mime; CHECK(meta->findCString(kKeyMIMEType, &mime)); if (!haveVideo && !strncasecmp(mime, "video/", 6)) { setVideoSource(extractor->getTrack(i)); haveVideo = true; } else if (!haveAudio && !strncasecmp(mime, "audio/", 6)) { setAudioSource(extractor->getTrack(i)); haveAudio = true; if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_VORBIS)) { // Only do this for vorbis audio, none of the other audio // formats even support this ringtone specific hack and // retrieving the metadata on some extractors may turn out // to be very expensive. sp<MetaData> fileMeta = extractor->getMetaData(); int32_t loop; if (fileMeta != NULL && fileMeta->findInt32(kKeyAutoLoop, &loop) && loop != 0) { mFlags |= AUTO_LOOPING; } } } if (haveAudio && haveVideo) { break; } } /* Add the support for Dummy audio*/ if( !haveAudio ){ mAudioTrack = DummyAudioSource::Create(32000, 2, 20000, ((mPlayEndTimeMsec)*1000LL)); if(mAudioTrack != NULL) { haveAudio = true; } } if (!haveAudio && !haveVideo) { return UNKNOWN_ERROR; } mExtractorFlags = extractor->flags(); return OK; } status_t PreviewPlayer::setDataSource_l_jpg() { ALOGV("setDataSource_l_jpg"); M4OSA_ERR err = M4NO_ERROR; mAudioSource = DummyAudioSource::Create(32000, 2, 20000, ((mPlayEndTimeMsec)*1000LL)); if(mAudioSource != NULL) { setAudioSource(mAudioSource); } status_t error = mAudioSource->start(); if (error != OK) { ALOGE("Error starting dummy audio source"); mAudioSource.clear(); return err; } mDurationUs = (mPlayEndTimeMsec - mPlayBeginTimeMsec)*1000LL; mVideoSource = DummyVideoSource::Create(mVideoWidth, mVideoHeight, #ifndef ANDROID_DEFAULT_CODE mPlayEndTimeMsec*1000LL, mUri); #else mDurationUs, mUri); #endif updateSizeToRender(mVideoSource->getFormat()); setVideoSource(mVideoSource); status_t err1 = mVideoSource->start(); if (err1 != OK) { mVideoSource.clear(); #ifndef ANDROID_DEFAULT_CODE return err1; #else return err; #endif } mIsVideoSourceJpg = true; return OK; } void PreviewPlayer::reset_l() { if (mFlags & PREPARING) { mFlags |= PREPARE_CANCELLED; } while (mFlags & PREPARING) { mPreparedCondition.wait(mLock); } cancelPlayerEvents_l(); mAudioTrack.clear(); mVideoTrack.clear(); // Shutdown audio first, so that the respone to the reset request // appears to happen instantaneously as far as the user is concerned // If we did this later, audio would continue playing while we // shutdown the video-related resources and the player appear to // not be as responsive to a reset request. if (mAudioPlayer == NULL && mAudioSource != NULL) { // If we had an audio player, it would have effectively // taken possession of the audio source and stopped it when // _it_ is stopped. Otherwise this is still our responsibility. mAudioSource->stop(); } mAudioSource.clear(); mTimeSource = NULL; //Single audio player instance used //So donot delete it here //It is deleted from PreviewController class //delete mAudioPlayer; mAudioPlayer = NULL; if (mVideoBuffer) { mVideoBuffer->release(); mVideoBuffer = NULL; } if (mVideoSource != NULL) { mVideoSource->stop(); // The following hack is necessary to ensure that the OMX // component is completely released by the time we may try // to instantiate it again. wp<MediaSource> tmp = mVideoSource; mVideoSource.clear(); while (tmp.promote() != NULL) { usleep(1000); } IPCThreadState::self()->flushCommands(); } mDurationUs = -1; mFlags = 0; mExtractorFlags = 0; mVideoWidth = mVideoHeight = -1; mTimeSourceDeltaUs = 0; mVideoTimeUs = 0; mSeeking = NO_SEEK; mSeekNotificationSent = false; mSeekTimeUs = 0; mUri.setTo(""); mCurrentVideoEffect = VIDEO_EFFECT_NONE; mIsVideoSourceJpg = false; mFrameRGBBuffer = NULL; if(mFrameYUVBuffer != NULL) { free(mFrameYUVBuffer); mFrameYUVBuffer = NULL; } } status_t PreviewPlayer::play() { ALOGV("play"); Mutex::Autolock autoLock(mLock); mFlags &= ~CACHE_UNDERRUN; mFlags &= ~INFORMED_AV_EOS; return play_l(); } status_t PreviewPlayer::startAudioPlayer_l() { ALOGV("startAudioPlayer_l"); CHECK(!(mFlags & AUDIO_RUNNING)); if (mAudioSource == NULL || mAudioPlayer == NULL) { return OK; } if (!(mFlags & AUDIOPLAYER_STARTED)) { mFlags |= AUDIOPLAYER_STARTED; // We've already started the MediaSource in order to enable // the prefetcher to read its data. status_t err = mAudioPlayer->start( true /* sourceAlreadyStarted */); if (err != OK) { notifyListener_l(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, err); return err; } } else { mAudioPlayer->resume(); } mFlags |= AUDIO_RUNNING; mWatchForAudioEOS = true; return OK; } status_t PreviewPlayer::setAudioPlayer(VideoEditorAudioPlayer *audioPlayer) { ALOGV("setAudioPlayer"); Mutex::Autolock autoLock(mLock); CHECK(!(mFlags & PLAYING)); mAudioPlayer = audioPlayer; ALOGV("SetAudioPlayer"); mIsChangeSourceRequired = true; // check if the new and old source are dummy sp<MediaSource> anAudioSource = mAudioPlayer->getSource(); if (anAudioSource == NULL) { // Audio player does not have any source set. ALOGV("setAudioPlayer: Audio player does not have any source set"); return OK; } // If new video source is not dummy, then always change source // Else audio player continues using old audio source and there are // frame drops to maintain AV sync sp<MetaData> meta; if (mVideoSource != NULL) { meta = mVideoSource->getFormat(); const char *pVidSrcType; if (meta->findCString(kKeyDecoderComponent, &pVidSrcType)) { if (strcmp(pVidSrcType, "DummyVideoSource") != 0) { ALOGV(" Video clip with silent audio; need to change source"); return OK; } } } const char *pSrcType1; const char *pSrcType2; meta = anAudioSource->getFormat(); if (meta->findCString(kKeyDecoderComponent, &pSrcType1)) { if (strcmp(pSrcType1, "DummyAudioSource") == 0) { meta = mAudioSource->getFormat(); if (meta->findCString(kKeyDecoderComponent, &pSrcType2)) { if (strcmp(pSrcType2, "DummyAudioSource") == 0) { mIsChangeSourceRequired = false; // Just set the new play duration for the existing source MediaSource *pMediaSrc = anAudioSource.get(); DummyAudioSource *pDummyAudioSource = (DummyAudioSource*)pMediaSrc; #ifndef ANDROID_DEFAULT_CODE int64_t dumyaudioduration = pDummyAudioSource->getDuration(); #endif //Increment the duration of audio source pDummyAudioSource->setDuration( (int64_t)((mPlayEndTimeMsec)*1000LL)); // Stop the new audio source // since we continue using old source ALOGV("setAudioPlayer: stop new audio source"); mAudioSource->stop(); #ifndef ANDROID_DEFAULT_CODE status_t finalStatus; if(mAudioPlayer->reachedEOS(&finalStatus)) { ALOGD("Front DummySoure eos,so seek to (%lld) again ",dumyaudioduration); mAudioPlayer->seekTo(dumyaudioduration); mAudioPlayer->resume(); } #endif } } } } return OK; } void PreviewPlayer::onStreamDone() { ALOGV("onStreamDone"); // Posted whenever any stream finishes playing. Mutex::Autolock autoLock(mLock); if (!mStreamDoneEventPending) { return; } mStreamDoneEventPending = false; if (mStreamDoneStatus != ERROR_END_OF_STREAM) { ALOGV("MEDIA_ERROR %d", mStreamDoneStatus); notifyListener_l( MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, mStreamDoneStatus); pause_l(true /* at eos */); mFlags |= AT_EOS; return; } const bool allDone = (mVideoSource == NULL || (mFlags & VIDEO_AT_EOS)) && (mAudioSource == NULL || (mFlags & AUDIO_AT_EOS)); if (!allDone) { return; } if (mFlags & (LOOPING | AUTO_LOOPING)) { seekTo_l(0); if (mVideoSource != NULL) { postVideoEvent_l(); } } else { ALOGV("MEDIA_PLAYBACK_COMPLETE"); //pause before sending event pause_l(true /* at eos */); //This lock is used to syncronize onStreamDone() in PreviewPlayer and //stopPreview() in PreviewController Mutex::Autolock autoLock(mLockControl); /* Make sure PreviewPlayer only notifies MEDIA_PLAYBACK_COMPLETE once for each clip! * It happens twice in following scenario. * To make the clips in preview storyboard are played and switched smoothly, * PreviewController uses two PreviewPlayer instances and one AudioPlayer. * The two PreviewPlayer use the same AudioPlayer to play the audio, * and change the audio source of the AudioPlayer. * If the audio source of current playing clip and next clip are dummy * audio source(image or video without audio), it will not change the audio source * to avoid the "audio glitch", and keep using the current audio source. * When the video of current clip reached the EOS, PreviewPlayer will set EOS flag * for video and audio, and it will notify MEDIA_PLAYBACK_COMPLETE. * But the audio(dummy audio source) is still playing(for next clip), * and when it reached the EOS, and video reached EOS, * PreviewPlayer will notify MEDIA_PLAYBACK_COMPLETE again. */ if (!(mFlags & INFORMED_AV_EOS)) { notifyListener_l(MEDIA_PLAYBACK_COMPLETE); mFlags |= INFORMED_AV_EOS; } mFlags |= AT_EOS; ALOGV("onStreamDone end"); return; } } status_t PreviewPlayer::play_l() { ALOGV("play_l"); mFlags &= ~SEEK_PREVIEW; if (mFlags & PLAYING) { return OK; } mStartNextPlayer = false; if (!(mFlags & PREPARED)) { status_t err = prepare_l(); if (err != OK) { return err; } } mFlags |= PLAYING; mFlags |= FIRST_FRAME; bool deferredAudioSeek = false; if (mAudioSource != NULL) { if (mAudioPlayer == NULL) { if (mAudioSink != NULL) { mAudioPlayer = new VideoEditorAudioPlayer(mAudioSink, this); mAudioPlayer->setSource(mAudioSource); mAudioPlayer->setAudioMixSettings( mPreviewPlayerAudioMixSettings); mAudioPlayer->setAudioMixPCMFileHandle( mAudioMixPCMFileHandle); mAudioPlayer->setAudioMixStoryBoardSkimTimeStamp( mAudioMixStoryBoardTS, mCurrentMediaBeginCutTime, mCurrentMediaVolumeValue); mFlags |= AUDIOPLAYER_STARTED; // We've already started the MediaSource in order to enable // the prefetcher to read its data. status_t err = mAudioPlayer->start( true /* sourceAlreadyStarted */); if (err != OK) { //delete mAudioPlayer; mAudioPlayer = NULL; mFlags &= ~(PLAYING | FIRST_FRAME); return err; } mTimeSource = mAudioPlayer; mFlags |= AUDIO_RUNNING; deferredAudioSeek = true; mWatchForAudioSeekComplete = false; mWatchForAudioEOS = true; } } else { bool isAudioPlayerStarted = mAudioPlayer->isStarted(); #ifndef ANDROID_DEFAULT_CODE // Demon, always set this as new observer to avoid wrong audio status callback mAudioPlayer->setObserver(this); #endif if (mIsChangeSourceRequired == true) { ALOGV("play_l: Change audio source required"); if (isAudioPlayerStarted == true) { mAudioPlayer->pause(); } mAudioPlayer->setSource(mAudioSource); mAudioPlayer->setObserver(this); mAudioPlayer->setAudioMixSettings( mPreviewPlayerAudioMixSettings); mAudioPlayer->setAudioMixStoryBoardSkimTimeStamp( mAudioMixStoryBoardTS, mCurrentMediaBeginCutTime, mCurrentMediaVolumeValue); if (isAudioPlayerStarted == true) { mAudioPlayer->resume(); } else { status_t err = OK; err = mAudioPlayer->start(true); if (err != OK) { mAudioPlayer = NULL; mAudioPlayer = NULL; mFlags &= ~(PLAYING | FIRST_FRAME); return err; } } } else { ALOGV("play_l: No Source change required"); mAudioPlayer->setAudioMixStoryBoardSkimTimeStamp( mAudioMixStoryBoardTS, mCurrentMediaBeginCutTime, mCurrentMediaVolumeValue); mAudioPlayer->resume(); } mFlags |= AUDIOPLAYER_STARTED; mFlags |= AUDIO_RUNNING; mTimeSource = mAudioPlayer; deferredAudioSeek = true; mWatchForAudioSeekComplete = false; mWatchForAudioEOS = true; } } if (mTimeSource == NULL && mAudioPlayer == NULL) { mTimeSource = &mSystemTimeSource; } // Set the seek option for Image source files and read. // This resets the timestamping for image play if (mIsVideoSourceJpg) { MediaSource::ReadOptions options; MediaBuffer *aLocalBuffer; options.setSeekTo(mSeekTimeUs); mVideoSource->read(&aLocalBuffer, &options); aLocalBuffer->release(); } if (mVideoSource != NULL) { // Kick off video playback postVideoEvent_l(); } if (deferredAudioSeek) { // If there was a seek request while we were paused // and we're just starting up again, honor the request now. seekAudioIfNecessary_l(); } if (mFlags & AT_EOS) { // Legacy behaviour, if a stream finishes playing and then // is started again, we play from the start... seekTo_l(0); } return OK; } status_t PreviewPlayer::initRenderer_l() { if (mSurface != NULL) { if(mVideoRenderer == NULL) { mVideoRenderer = mNativeWindowRenderer->createRenderInput(); #ifdef ANDROID_DEFAULT_CODE if (mVideoSource != NULL) { updateSizeToRender(mVideoSource->getFormat()); } #endif #ifndef ANDROID_DEFAULT_CODE if (mVideoRenderer == NULL) return UNKNOWN_ERROR; #endif } #ifndef ANDROID_DEFAULT_CODE if (mVideoRenderer != NULL && mVideoSource != NULL) { updateSizeToRender(mVideoSource->getFormat()); } #endif } return OK; } status_t PreviewPlayer::seekTo(int64_t timeUs) { Mutex::Autolock autoLock(mLock); if ((mExtractorFlags & MediaExtractor::CAN_SEEK) || (mIsVideoSourceJpg)) { return seekTo_l(timeUs); } return OK; } status_t PreviewPlayer::getVideoDimensions( int32_t *width, int32_t *height) const { Mutex::Autolock autoLock(mLock); if (mVideoWidth < 0 || mVideoHeight < 0) { return UNKNOWN_ERROR; } *width = mVideoWidth; *height = mVideoHeight; return OK; } status_t PreviewPlayer::initAudioDecoder_l() { sp<MetaData> meta = mAudioTrack->getFormat(); const char *mime; CHECK(meta->findCString(kKeyMIMEType, &mime)); if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_RAW)) { mAudioSource = mAudioTrack; } else { sp<MediaSource> aRawSource; aRawSource = OMXCodec::Create( mClient.interface(), mAudioTrack->getFormat(), false, // createEncoder mAudioTrack); if(aRawSource != NULL) { mAudioSource = new VideoEditorSRC(aRawSource); } } if (mAudioSource != NULL) { int64_t durationUs; if (mAudioTrack->getFormat()->findInt64(kKeyDuration, &durationUs)) { setDuration_l(durationUs); } status_t err = mAudioSource->start(); if (err != OK) { mAudioSource.clear(); return err; } } else if (!strcasecmp(mime, MEDIA_MIMETYPE_AUDIO_QCELP)) { // For legacy reasons we're simply going to ignore the absence // of an audio decoder for QCELP instead of aborting playback // altogether. return OK; } return mAudioSource != NULL ? OK : UNKNOWN_ERROR; } status_t PreviewPlayer::initVideoDecoder_l(uint32_t flags) { initRenderer_l(); if (mVideoRenderer == NULL) { ALOGE("Cannot create renderer"); return UNKNOWN_ERROR; } mVideoSource = OMXCodec::Create( mClient.interface(), mVideoTrack->getFormat(), false, mVideoTrack, NULL, flags, mVideoRenderer->getTargetWindow()); if (mVideoSource != NULL) { int64_t durationUs; if (mVideoTrack->getFormat()->findInt64(kKeyDuration, &durationUs)) { setDuration_l(durationUs); } updateSizeToRender(mVideoTrack->getFormat()); status_t err = mVideoSource->start(); if (err != OK) { mVideoSource.clear(); return err; } } return mVideoSource != NULL ? OK : UNKNOWN_ERROR; } void PreviewPlayer::onVideoEvent() { uint32_t i=0; M4OSA_ERR err1 = M4NO_ERROR; int64_t imageFrameTimeUs = 0; #ifndef ANDROID_DEFAULT_CODE // Avoid of onVideoEvent occpuy mLock all the time. // It would cause that pause() can not get the mLock, and even result in ANR usleep(0); #endif Mutex::Autolock autoLock(mLock); if (!mVideoEventPending) { // The event has been cancelled in reset_l() but had already // been scheduled for execution at that time. return; } mVideoEventPending = false; if (mFlags & SEEK_PREVIEW) { mFlags &= ~SEEK_PREVIEW; return; } TimeSource *ts_st = &mSystemTimeSource; int64_t timeStartUs = ts_st->getRealTimeUs(); if (mSeeking != NO_SEEK) { if(mAudioSource != NULL) { // We're going to seek the video source first, followed by // the audio source. // In order to avoid jumps in the DataSource offset caused by // the audio codec prefetching data from the old locations // while the video codec is already reading data from the new // locations, we'll "pause" the audio source, causing it to // stop reading input data until a subsequent seek. if (mAudioPlayer != NULL && (mFlags & AUDIO_RUNNING)) { mAudioPlayer->pause(); mFlags &= ~AUDIO_RUNNING; } mAudioSource->pause(); } } if (!mVideoBuffer) { MediaSource::ReadOptions options; if (mSeeking != NO_SEEK) { ALOGV("LV PLAYER seeking to %lld us (%.2f secs)", mSeekTimeUs, mSeekTimeUs / 1E6); options.setSeekTo( mSeekTimeUs, MediaSource::ReadOptions::SEEK_CLOSEST); } for (;;) { status_t err = mVideoSource->read(&mVideoBuffer, &options); options.clearSeekTo(); if (err != OK) { CHECK(!mVideoBuffer); if (err == INFO_FORMAT_CHANGED) { ALOGV("LV PLAYER VideoSource signalled format change"); notifyVideoSize_l(); if (mVideoRenderer != NULL) { mVideoRendererIsPreview = false; err = initRenderer_l(); if (err != OK) { postStreamDoneEvent_l(err); } } updateSizeToRender(mVideoSource->getFormat()); continue; } // So video playback is complete, but we may still have // a seek request pending that needs to be applied to the audio track if (mSeeking != NO_SEEK) { ALOGV("video stream ended while seeking!"); } finishSeekIfNecessary(-1); ALOGV("PreviewPlayer: onVideoEvent EOS reached."); mFlags |= VIDEO_AT_EOS; mFlags |= AUDIO_AT_EOS; mOverlayUpdateEventPosted = false; postStreamDoneEvent_l(err); // Set the last decoded timestamp to duration mDecodedVideoTs = (mPlayEndTimeMsec*1000LL); return; } if (mVideoBuffer->range_length() == 0) { // Some decoders, notably the PV AVC software decoder // return spurious empty buffers that we just want to ignore. mVideoBuffer->release(); mVideoBuffer = NULL; continue; } int64_t videoTimeUs; CHECK(mVideoBuffer->meta_data()->findInt64(kKeyTime, &videoTimeUs)); if (mSeeking != NO_SEEK) { if (videoTimeUs < mSeekTimeUs) { // buffers are before seek time // ignore them mVideoBuffer->release(); mVideoBuffer = NULL; continue; } } else { if((videoTimeUs/1000) < mPlayBeginTimeMsec) { // Frames are before begin cut time // Donot render mVideoBuffer->release(); mVideoBuffer = NULL; continue; } } break; } } mNumberDecVideoFrames++; int64_t timeUs; CHECK(mVideoBuffer->meta_data()->findInt64(kKeyTime, &timeUs)); setPosition_l(timeUs); if (!mStartNextPlayer) { int64_t playbackTimeRemaining = (mPlayEndTimeMsec * 1000LL) - timeUs; if (playbackTimeRemaining <= 1500000) { //When less than 1.5 sec of playback left // send notification to start next player mStartNextPlayer = true; notifyListener_l(0xAAAAAAAA); } } SeekType wasSeeking = mSeeking; finishSeekIfNecessary(timeUs); if (mAudioPlayer != NULL && !(mFlags & (AUDIO_RUNNING))) { status_t err = startAudioPlayer_l(); if (err != OK) { ALOGE("Starting the audio player failed w/ err %d", err); return; } } TimeSource *ts = (mFlags & AUDIO_AT_EOS) ? &mSystemTimeSource : mTimeSource; if(ts == NULL) { mVideoBuffer->release(); mVideoBuffer = NULL; return; } if(!mIsVideoSourceJpg) { if (mFlags & FIRST_FRAME) { mFlags &= ~FIRST_FRAME; mTimeSourceDeltaUs = ts->getRealTimeUs() - timeUs; } int64_t realTimeUs, mediaTimeUs; if (!(mFlags & AUDIO_AT_EOS) && mAudioPlayer != NULL && mAudioPlayer->getMediaTimeMapping(&realTimeUs, &mediaTimeUs)) { mTimeSourceDeltaUs = realTimeUs - mediaTimeUs; } int64_t nowUs = ts->getRealTimeUs() - mTimeSourceDeltaUs; int64_t latenessUs = nowUs - timeUs; if (wasSeeking != NO_SEEK) { // Let's display the first frame after seeking right away. latenessUs = 0; } ALOGV("Audio time stamp = %lld and video time stamp = %lld", ts->getRealTimeUs(),timeUs); if (latenessUs > 40000) { // We're more than 40ms late. ALOGV("LV PLAYER we're late by %lld us (%.2f secs)", latenessUs, latenessUs / 1E6); mVideoBuffer->release(); mVideoBuffer = NULL; postVideoEvent_l(0); return; } if (latenessUs < -25000) { // We're more than 25ms early. ALOGV("We're more than 25ms early, lateness %lld", latenessUs); postVideoEvent_l(25000); return; } } if (mVideoRendererIsPreview || mVideoRenderer == NULL) { mVideoRendererIsPreview = false; status_t err = initRenderer_l(); if (err != OK) { postStreamDoneEvent_l(err); } } // If timestamp exceeds endCutTime of clip, donot render if((timeUs/1000) > mPlayEndTimeMsec) { mVideoBuffer->release(); mVideoBuffer = NULL; mFlags |= VIDEO_AT_EOS; mFlags |= AUDIO_AT_EOS; ALOGV("PreviewPlayer: onVideoEvent timeUs > mPlayEndTime; send EOS.."); mOverlayUpdateEventPosted = false; // Set the last decoded timestamp to duration mDecodedVideoTs = (mPlayEndTimeMsec*1000LL); postStreamDoneEvent_l(ERROR_END_OF_STREAM); return; } // Capture the frame timestamp to be rendered mDecodedVideoTs = timeUs; // Post processing to apply video effects for(i=0;i<mNumberEffects;i++) { // First check if effect starttime matches the clip being previewed if((mEffectsSettings[i].uiStartTime < (mDecVideoTsStoryBoard/1000)) || (mEffectsSettings[i].uiStartTime >= ((mDecVideoTsStoryBoard/1000) + mPlayEndTimeMsec - mPlayBeginTimeMsec))) { // This effect doesn't belong to this clip, check next one continue; } // Check if effect applies to this particular frame timestamp if((mEffectsSettings[i].uiStartTime <= (((timeUs+mDecVideoTsStoryBoard)/1000)-mPlayBeginTimeMsec)) && ((mEffectsSettings[i].uiStartTime+mEffectsSettings[i].uiDuration) >= (((timeUs+mDecVideoTsStoryBoard)/1000)-mPlayBeginTimeMsec)) && (mEffectsSettings[i].uiDuration != 0)) { setVideoPostProcessingNode( mEffectsSettings[i].VideoEffectType, TRUE); } else { setVideoPostProcessingNode( mEffectsSettings[i].VideoEffectType, FALSE); } } //Provide the overlay Update indication when there is an overlay effect if (mCurrentVideoEffect & VIDEO_EFFECT_FRAMING) { mCurrentVideoEffect &= ~VIDEO_EFFECT_FRAMING; //never apply framing here. if (!mOverlayUpdateEventPosted) { // Find the effect in effectSettings array M4OSA_UInt32 index; for (index = 0; index < mNumberEffects; index++) { M4OSA_UInt32 timeMs = mDecodedVideoTs/1000; M4OSA_UInt32 timeOffset = mDecVideoTsStoryBoard/1000; if(mEffectsSettings[index].VideoEffectType == (M4VSS3GPP_VideoEffectType)M4xVSS_kVideoEffectType_Framing) { if (((mEffectsSettings[index].uiStartTime + 1) <= timeMs + timeOffset - mPlayBeginTimeMsec) && ((mEffectsSettings[index].uiStartTime - 1 + mEffectsSettings[index].uiDuration) >= timeMs + timeOffset - mPlayBeginTimeMsec)) { break; } } } if (index < mNumberEffects) { mCurrFramingEffectIndex = index; mOverlayUpdateEventPosted = true; postOverlayUpdateEvent_l(); ALOGV("Framing index = %ld", mCurrFramingEffectIndex); } else { ALOGV("No framing effects found"); } } #ifndef ANDROID_DEFAULT_CODE } else if (mOverlayUpdateEventPosted || mIsFirstFrame) { #else } else if (mOverlayUpdateEventPosted) { #endif //Post the event when the overlay is no more valid ALOGV("Overlay is Done"); mOverlayUpdateEventPosted = false; postOverlayUpdateEvent_l(); } #ifndef ANDROID_DEFAULT_CODE mIsFirstFrame = false; #endif if (mVideoRenderer != NULL) { mVideoRenderer->render(mVideoBuffer, mCurrentVideoEffect, mRenderingMode, mIsVideoSourceJpg); } mVideoBuffer->release(); mVideoBuffer = NULL; // Post progress callback based on callback interval set if(mNumberDecVideoFrames >= mProgressCbInterval) { postProgressCallbackEvent_l(); mNumberDecVideoFrames = 0; // reset counter } // if reached EndCutTime of clip, post EOS event if((timeUs/1000) >= mPlayEndTimeMsec) { ALOGV("PreviewPlayer: onVideoEvent EOS."); mFlags |= VIDEO_AT_EOS; mFlags |= AUDIO_AT_EOS; mOverlayUpdateEventPosted = false; // Set the last decoded timestamp to duration mDecodedVideoTs = (mPlayEndTimeMsec*1000LL); postStreamDoneEvent_l(ERROR_END_OF_STREAM); } else { if ((wasSeeking != NO_SEEK) && (mFlags & SEEK_PREVIEW)) { mFlags &= ~SEEK_PREVIEW; return; } if(!mIsVideoSourceJpg) { postVideoEvent_l(0); } else { postVideoEvent_l(33000); } } } status_t PreviewPlayer::prepare() { ALOGV("prepare"); Mutex::Autolock autoLock(mLock); return prepare_l(); } status_t PreviewPlayer::prepare_l() { ALOGV("prepare_l"); if (mFlags & PREPARED) { return OK; } if (mFlags & PREPARING) { return UNKNOWN_ERROR; } mIsAsyncPrepare = false; status_t err = prepareAsync_l(); if (err != OK) { return err; } while (mFlags & PREPARING) { mPreparedCondition.wait(mLock); } return mPrepareResult; } status_t PreviewPlayer::prepareAsync() { ALOGV("prepareAsync"); Mutex::Autolock autoLock(mLock); return prepareAsync_l(); } status_t PreviewPlayer::prepareAsync_l() { ALOGV("prepareAsync_l"); if (mFlags & PREPARING) { return UNKNOWN_ERROR; // async prepare already pending } if (!mQueueStarted) { mQueue.start(); mQueueStarted = true; } mFlags |= PREPARING; mAsyncPrepareEvent = new PreviewPlayerEvent( this, &PreviewPlayer::onPrepareAsyncEvent); mQueue.postEvent(mAsyncPrepareEvent); return OK; } status_t PreviewPlayer::finishSetDataSource_l() { sp<DataSource> dataSource; sp<MediaExtractor> extractor; dataSource = DataSource::CreateFromURI(mUri.string(), NULL); if (dataSource == NULL) { return UNKNOWN_ERROR; } //If file type is .rgb, then no need to check for Extractor int uriLen = strlen(mUri); int startOffset = uriLen - 4; if(!strncasecmp(mUri+startOffset, ".rgb", 4)) { extractor = NULL; } else { extractor = MediaExtractor::Create(dataSource, MEDIA_MIMETYPE_CONTAINER_MPEG4); } if (extractor == NULL) { ALOGV("finishSetDataSource_l: failed to create extractor"); return setDataSource_l_jpg(); } return setDataSource_l(extractor); } void PreviewPlayer::onPrepareAsyncEvent() { Mutex::Autolock autoLock(mLock); ALOGV("onPrepareAsyncEvent"); if (mFlags & PREPARE_CANCELLED) { ALOGV("prepare was cancelled before doing anything"); abortPrepare(UNKNOWN_ERROR); return; } if (mUri.size() > 0) { status_t err = finishSetDataSource_l(); if (err != OK) { abortPrepare(err); return; } } if (mVideoTrack != NULL && mVideoSource == NULL) { status_t err = initVideoDecoder_l(OMXCodec::kHardwareCodecsOnly); if (err != OK) { abortPrepare(err); return; } } if (mAudioTrack != NULL && mAudioSource == NULL) { status_t err = initAudioDecoder_l(); if (err != OK) { abortPrepare(err); return; } } finishAsyncPrepare_l(); } void PreviewPlayer::finishAsyncPrepare_l() { ALOGV("finishAsyncPrepare_l"); if (mIsAsyncPrepare) { if (mVideoSource == NULL) { notifyListener_l(MEDIA_SET_VIDEO_SIZE, 0, 0); } else { notifyVideoSize_l(); } notifyListener_l(MEDIA_PREPARED); } mPrepareResult = OK; mFlags &= ~(PREPARING|PREPARE_CANCELLED); mFlags |= PREPARED; mAsyncPrepareEvent = NULL; mPreparedCondition.broadcast(); } void PreviewPlayer::acquireLock() { ALOGV("acquireLock"); mLockControl.lock(); } void PreviewPlayer::releaseLock() { ALOGV("releaseLock"); mLockControl.unlock(); } status_t PreviewPlayer::loadEffectsSettings( M4VSS3GPP_EffectSettings* pEffectSettings, int nEffects) { ALOGV("loadEffectsSettings"); mNumberEffects = nEffects; mEffectsSettings = pEffectSettings; return OK; } status_t PreviewPlayer::loadAudioMixSettings( M4xVSS_AudioMixingSettings* pAudioMixSettings) { ALOGV("loadAudioMixSettings"); mPreviewPlayerAudioMixSettings = pAudioMixSettings; return OK; } status_t PreviewPlayer::setAudioMixPCMFileHandle( M4OSA_Context pAudioMixPCMFileHandle) { ALOGV("setAudioMixPCMFileHandle"); mAudioMixPCMFileHandle = pAudioMixPCMFileHandle; return OK; } status_t PreviewPlayer::setAudioMixStoryBoardParam( M4OSA_UInt32 audioMixStoryBoardTS, M4OSA_UInt32 currentMediaBeginCutTime, M4OSA_UInt32 primaryTrackVolValue ) { ALOGV("setAudioMixStoryBoardParam"); mAudioMixStoryBoardTS = audioMixStoryBoardTS; mCurrentMediaBeginCutTime = currentMediaBeginCutTime; mCurrentMediaVolumeValue = primaryTrackVolValue; return OK; } status_t PreviewPlayer::setPlaybackBeginTime(uint32_t msec) { mPlayBeginTimeMsec = msec; return OK; } status_t PreviewPlayer::setPlaybackEndTime(uint32_t msec) { mPlayEndTimeMsec = msec; return OK; } status_t PreviewPlayer::setStoryboardStartTime(uint32_t msec) { mStoryboardStartTimeMsec = msec; mDecVideoTsStoryBoard = mStoryboardStartTimeMsec * 1000LL; return OK; } status_t PreviewPlayer::setProgressCallbackInterval(uint32_t cbInterval) { mProgressCbInterval = cbInterval; return OK; } status_t PreviewPlayer::setMediaRenderingMode( M4xVSS_MediaRendering mode, M4VIDEOEDITING_VideoFrameSize outputVideoSize) { mRenderingMode = mode; /* get the video width and height by resolution */ return getVideoSizeByResolution( outputVideoSize, &mOutputVideoWidth, &mOutputVideoHeight); } status_t PreviewPlayer::resetJniCallbackTimeStamp() { mDecVideoTsStoryBoard = mStoryboardStartTimeMsec * 1000LL; return OK; } void PreviewPlayer::postProgressCallbackEvent_l() { if (mProgressCbEventPending) { return; } mProgressCbEventPending = true; mQueue.postEvent(mProgressCbEvent); } void PreviewPlayer::onProgressCbEvent() { Mutex::Autolock autoLock(mLock); if (!mProgressCbEventPending) { return; } mProgressCbEventPending = false; // If playback starts from previous I-frame, // then send frame storyboard duration if ((mDecodedVideoTs/1000) < mPlayBeginTimeMsec) { notifyListener_l(MEDIA_INFO, 0, mDecVideoTsStoryBoard/1000); } else { notifyListener_l(MEDIA_INFO, 0, (((mDecodedVideoTs+mDecVideoTsStoryBoard)/1000)-mPlayBeginTimeMsec)); } } void PreviewPlayer::postOverlayUpdateEvent_l() { if (mOverlayUpdateEventPending) { return; } mOverlayUpdateEventPending = true; mQueue.postEvent(mOverlayUpdateEvent); } void PreviewPlayer::onUpdateOverlayEvent() { Mutex::Autolock autoLock(mLock); if (!mOverlayUpdateEventPending) { return; } mOverlayUpdateEventPending = false; int updateState = mOverlayUpdateEventPosted? 1: 0; notifyListener_l(0xBBBBBBBB, updateState, mCurrFramingEffectIndex); } void PreviewPlayer::setVideoPostProcessingNode( M4VSS3GPP_VideoEffectType type, M4OSA_Bool enable) { uint32_t effect = VIDEO_EFFECT_NONE; //Map M4VSS3GPP_VideoEffectType to local enum switch(type) { case M4VSS3GPP_kVideoEffectType_FadeFromBlack: effect = VIDEO_EFFECT_FADEFROMBLACK; break; case M4VSS3GPP_kVideoEffectType_FadeToBlack: effect = VIDEO_EFFECT_FADETOBLACK; break; case M4xVSS_kVideoEffectType_BlackAndWhite: effect = VIDEO_EFFECT_BLACKANDWHITE; break; case M4xVSS_kVideoEffectType_Pink: effect = VIDEO_EFFECT_PINK; break; case M4xVSS_kVideoEffectType_Green: effect = VIDEO_EFFECT_GREEN; break; case M4xVSS_kVideoEffectType_Sepia: effect = VIDEO_EFFECT_SEPIA; break; case M4xVSS_kVideoEffectType_Negative: effect = VIDEO_EFFECT_NEGATIVE; break; case M4xVSS_kVideoEffectType_Framing: effect = VIDEO_EFFECT_FRAMING; break; case M4xVSS_kVideoEffectType_Fifties: effect = VIDEO_EFFECT_FIFTIES; break; case M4xVSS_kVideoEffectType_ColorRGB16: effect = VIDEO_EFFECT_COLOR_RGB16; break; case M4xVSS_kVideoEffectType_Gradient: effect = VIDEO_EFFECT_GRADIENT; break; default: effect = VIDEO_EFFECT_NONE; break; } if (enable == M4OSA_TRUE) { //If already set, then no need to set again if (!(mCurrentVideoEffect & effect)) { mCurrentVideoEffect |= effect; if (effect == VIDEO_EFFECT_FIFTIES) { mIsFiftiesEffectStarted = true; } } } else { //Reset only if already set if (mCurrentVideoEffect & effect) { mCurrentVideoEffect &= ~effect; } } } status_t PreviewPlayer::setImageClipProperties(uint32_t width,uint32_t height) { mVideoWidth = width; mVideoHeight = height; return OK; } status_t PreviewPlayer::readFirstVideoFrame() { ALOGV("readFirstVideoFrame"); if (!mVideoBuffer) { MediaSource::ReadOptions options; if (mSeeking != NO_SEEK) { ALOGV("seeking to %lld us (%.2f secs)", mSeekTimeUs, mSeekTimeUs / 1E6); options.setSeekTo( mSeekTimeUs, MediaSource::ReadOptions::SEEK_CLOSEST); } for (;;) { status_t err = mVideoSource->read(&mVideoBuffer, &options); options.clearSeekTo(); if (err != OK) { CHECK(!mVideoBuffer); if (err == INFO_FORMAT_CHANGED) { ALOGV("VideoSource signalled format change"); notifyVideoSize_l(); if (mVideoRenderer != NULL) { mVideoRendererIsPreview = false; err = initRenderer_l(); if (err != OK) { postStreamDoneEvent_l(err); } } updateSizeToRender(mVideoSource->getFormat()); continue; } ALOGV("EOS reached."); mFlags |= VIDEO_AT_EOS; mFlags |= AUDIO_AT_EOS; postStreamDoneEvent_l(err); #ifndef ANDROID_DEFAULT_CODE return err; #else return OK; #endif } if (mVideoBuffer->range_length() == 0) { // Some decoders, notably the PV AVC software decoder // return spurious empty buffers that we just want to ignore. mVideoBuffer->release(); mVideoBuffer = NULL; continue; } int64_t videoTimeUs; CHECK(mVideoBuffer->meta_data()->findInt64(kKeyTime, &videoTimeUs)); if (mSeeking != NO_SEEK) { if (videoTimeUs < mSeekTimeUs) { // buffers are before seek time // ignore them mVideoBuffer->release(); mVideoBuffer = NULL; continue; } } else { if ((videoTimeUs/1000) < mPlayBeginTimeMsec) { // buffers are before begin cut time // ignore them mVideoBuffer->release(); mVideoBuffer = NULL; continue; } } break; } } int64_t timeUs; CHECK(mVideoBuffer->meta_data()->findInt64(kKeyTime, &timeUs)); setPosition_l(timeUs); mDecodedVideoTs = timeUs; #ifndef ANDROID_DEFAULT_CODE mIsFirstFrame = true; #endif return OK; } status_t PreviewPlayer::getLastRenderedTimeMs(uint32_t *lastRenderedTimeMs) { *lastRenderedTimeMs = (((mDecodedVideoTs+mDecVideoTsStoryBoard)/1000)-mPlayBeginTimeMsec); return OK; } void PreviewPlayer::updateSizeToRender(sp<MetaData> meta) { if (mVideoRenderer) { mVideoRenderer->updateVideoSize(meta); } } void PreviewPlayer::setListener(const wp<MediaPlayerBase> &listener) { Mutex::Autolock autoLock(mLock); mListener = listener; } status_t PreviewPlayer::setDataSource(const sp<IStreamSource> &source) { return INVALID_OPERATION; } void PreviewPlayer::reset() { Mutex::Autolock autoLock(mLock); reset_l(); } void PreviewPlayer::clear_l() { mDisplayWidth = 0; mDisplayHeight = 0; if (mFlags & PLAYING) { updateBatteryUsage_l(); } if (mFlags & PREPARING) { mFlags |= PREPARE_CANCELLED; if (mFlags & PREPARING_CONNECTED) { // We are basically done preparing, we're just buffering // enough data to start playback, we can safely interrupt that. finishAsyncPrepare_l(); } } while (mFlags & PREPARING) { mPreparedCondition.wait(mLock); } cancelPlayerEvents_l(true); mAudioTrack.clear(); mVideoTrack.clear(); // Shutdown audio first, so that the respone to the reset request // appears to happen instantaneously as far as the user is concerned // If we did this later, audio would continue playing while we // shutdown the video-related resources and the player appear to // not be as responsive to a reset request. if (mAudioPlayer == NULL && mAudioSource != NULL) { // If we had an audio player, it would have effectively // taken possession of the audio source and stopped it when // _it_ is stopped. Otherwise this is still our responsibility. mAudioSource->stop(); } mAudioSource.clear(); mTimeSource = NULL; delete mAudioPlayer; mAudioPlayer = NULL; if (mVideoSource != NULL) { shutdownVideoDecoder_l(); } mDurationUs = -1; mFlags = 0; mExtractorFlags = 0; mTimeSourceDeltaUs = 0; mVideoTimeUs = 0; mSeeking = NO_SEEK; mSeekNotificationSent = false; mSeekTimeUs = 0; mUri.setTo(""); mBitrate = -1; mLastVideoTimeUs = -1; } void PreviewPlayer::notifyListener_l(int msg, int ext1, int ext2) { if (mListener != NULL) { sp<MediaPlayerBase> listener = mListener.promote(); if (listener != NULL) { listener->sendEvent(msg, ext1, ext2); } } } void PreviewPlayer::onVideoLagUpdate() { Mutex::Autolock autoLock(mLock); if (!mVideoLagEventPending) { return; } mVideoLagEventPending = false; int64_t audioTimeUs = mAudioPlayer->getMediaTimeUs(); int64_t videoLateByUs = audioTimeUs - mVideoTimeUs; if (!(mFlags & VIDEO_AT_EOS) && videoLateByUs > 300000ll) { ALOGV("video late by %lld ms.", videoLateByUs / 1000ll); notifyListener_l( MEDIA_INFO, MEDIA_INFO_VIDEO_TRACK_LAGGING, videoLateByUs / 1000ll); } postVideoLagEvent_l(); } void PreviewPlayer::notifyVideoSize_l() { sp<MetaData> meta = mVideoSource->getFormat(); int32_t vWidth, vHeight; int32_t cropLeft, cropTop, cropRight, cropBottom; CHECK(meta->findInt32(kKeyWidth, &vWidth)); CHECK(meta->findInt32(kKeyHeight, &vHeight)); mGivenWidth = vWidth; mGivenHeight = vHeight; if (!meta->findRect( kKeyCropRect, &cropLeft, &cropTop, &cropRight, &cropBottom)) { cropLeft = cropTop = 0; cropRight = vWidth - 1; cropBottom = vHeight - 1; ALOGD("got dimensions only %d x %d", vWidth, vHeight); } else { ALOGD("got crop rect %d, %d, %d, %d", cropLeft, cropTop, cropRight, cropBottom); } mCropRect.left = cropLeft; mCropRect.right = cropRight; mCropRect.top = cropTop; mCropRect.bottom = cropBottom; int32_t displayWidth; if (meta->findInt32(kKeyDisplayWidth, &displayWidth)) { ALOGV("Display width changed (%d=>%d)", mDisplayWidth, displayWidth); mDisplayWidth = displayWidth; } int32_t displayHeight; if (meta->findInt32(kKeyDisplayHeight, &displayHeight)) { ALOGV("Display height changed (%d=>%d)", mDisplayHeight, displayHeight); mDisplayHeight = displayHeight; } int32_t usableWidth = cropRight - cropLeft + 1; int32_t usableHeight = cropBottom - cropTop + 1; if (mDisplayWidth != 0) { usableWidth = mDisplayWidth; } if (mDisplayHeight != 0) { usableHeight = mDisplayHeight; } int32_t rotationDegrees; if (!mVideoTrack->getFormat()->findInt32( kKeyRotation, &rotationDegrees)) { rotationDegrees = 0; } if (rotationDegrees == 90 || rotationDegrees == 270) { notifyListener_l( MEDIA_SET_VIDEO_SIZE, usableHeight, usableWidth); } else { notifyListener_l( MEDIA_SET_VIDEO_SIZE, usableWidth, usableHeight); } } status_t PreviewPlayer::pause() { Mutex::Autolock autoLock(mLock); mFlags &= ~CACHE_UNDERRUN; return pause_l(); } status_t PreviewPlayer::pause_l(bool at_eos) { if (!(mFlags & PLAYING)) { return OK; } cancelPlayerEvents_l(); if (mAudioPlayer != NULL && (mFlags & AUDIO_RUNNING)) { if (at_eos) { // If we played the audio stream to completion we // want to make sure that all samples remaining in the audio // track's queue are played out. mAudioPlayer->pause(true /* playPendingSamples */); } else { mAudioPlayer->pause(); } mFlags &= ~AUDIO_RUNNING; } mFlags &= ~PLAYING; updateBatteryUsage_l(); return OK; } bool PreviewPlayer::isPlaying() const { return (mFlags & PLAYING) || (mFlags & CACHE_UNDERRUN); } void PreviewPlayer::setSurface(const sp<Surface> &surface) { Mutex::Autolock autoLock(mLock); mSurface = surface; setNativeWindow_l(surface); } void PreviewPlayer::setSurfaceTexture(const sp<ISurfaceTexture> &surfaceTexture) { Mutex::Autolock autoLock(mLock); mSurface.clear(); if (surfaceTexture != NULL) { setNativeWindow_l(new SurfaceTextureClient(surfaceTexture)); } } void PreviewPlayer::shutdownVideoDecoder_l() { if (mVideoBuffer) { mVideoBuffer->release(); mVideoBuffer = NULL; } mVideoSource->stop(); // The following hack is necessary to ensure that the OMX // component is completely released by the time we may try // to instantiate it again. wp<MediaSource> tmp = mVideoSource; mVideoSource.clear(); while (tmp.promote() != NULL) { usleep(1000); } IPCThreadState::self()->flushCommands(); } void PreviewPlayer::setNativeWindow_l(const sp<ANativeWindow> &native) { mNativeWindow = native; if (mVideoSource == NULL) { return; } ALOGI("attempting to reconfigure to use new surface"); bool wasPlaying = (mFlags & PLAYING) != 0; pause_l(); shutdownVideoDecoder_l(); CHECK_EQ(initVideoDecoder_l(), (status_t)OK); if (mLastVideoTimeUs >= 0) { mSeeking = SEEK; mSeekNotificationSent = true; mSeekTimeUs = mLastVideoTimeUs; mFlags &= ~(AT_EOS | AUDIO_AT_EOS | VIDEO_AT_EOS); } if (wasPlaying) { play_l(); } } void PreviewPlayer::setAudioSink( const sp<MediaPlayerBase::AudioSink> &audioSink) { Mutex::Autolock autoLock(mLock); mAudioSink = audioSink; } status_t PreviewPlayer::setLooping(bool shouldLoop) { Mutex::Autolock autoLock(mLock); mFlags = mFlags & ~LOOPING; if (shouldLoop) { mFlags |= LOOPING; } return OK; } void PreviewPlayer::setDuration_l(int64_t durationUs) { if (mDurationUs < 0 || durationUs > mDurationUs) { mDurationUs = durationUs; } } status_t PreviewPlayer::getDuration(int64_t *durationUs) { Mutex::Autolock autoLock(mLock); if (mDurationUs < 0) { return UNKNOWN_ERROR; } *durationUs = mDurationUs; return OK; } status_t PreviewPlayer::getPosition(int64_t *positionUs) { Mutex::Autolock autoLock(mLock); if (mSeeking != NO_SEEK) { *positionUs = mSeekTimeUs; } else if (mVideoSource != NULL && (mAudioPlayer == NULL || !(mFlags & VIDEO_AT_EOS))) { *positionUs = mVideoTimeUs; } else if (mAudioPlayer != NULL) { *positionUs = mAudioPlayer->getMediaTimeUs(); } else { *positionUs = 0; } return OK; } void PreviewPlayer::setPosition_l(int64_t timeUs) { mVideoTimeUs = timeUs; } status_t PreviewPlayer::seekTo_l(int64_t timeUs) { ALOGV("seekTo_l"); if (mFlags & CACHE_UNDERRUN) { mFlags &= ~CACHE_UNDERRUN; play_l(); } if ((mFlags & PLAYING) && mVideoSource != NULL && (mFlags & VIDEO_AT_EOS)) { // Video playback completed before, there's no pending // video event right now. In order for this new seek // to be honored, we need to post one. postVideoEvent_l(); } mSeeking = SEEK; mSeekNotificationSent = false; mSeekTimeUs = timeUs; mFlags &= ~(AT_EOS | AUDIO_AT_EOS | VIDEO_AT_EOS); seekAudioIfNecessary_l(); if (!(mFlags & PLAYING)) { ALOGV("seeking while paused, sending SEEK_COMPLETE notification" " immediately."); notifyListener_l(MEDIA_SEEK_COMPLETE); mSeekNotificationSent = true; if ((mFlags & PREPARED) && mVideoSource != NULL) { mFlags |= SEEK_PREVIEW; postVideoEvent_l(); } } return OK; } void PreviewPlayer::seekAudioIfNecessary_l() { if (mSeeking != NO_SEEK && mVideoSource == NULL && mAudioPlayer != NULL) { mAudioPlayer->seekTo(mSeekTimeUs); mWatchForAudioSeekComplete = true; mWatchForAudioEOS = true; } } void PreviewPlayer::setAudioSource(const sp<MediaSource>& source) { CHECK(source != NULL); mAudioTrack = source; } void PreviewPlayer::setVideoSource(const sp<MediaSource>& source) { CHECK(source != NULL); mVideoTrack = source; } void PreviewPlayer::finishSeekIfNecessary(int64_t videoTimeUs) { if (mSeeking == SEEK_VIDEO_ONLY) { mSeeking = NO_SEEK; return; } if (mSeeking == NO_SEEK || (mFlags & SEEK_PREVIEW)) { return; } if (mAudioPlayer != NULL) { ALOGV("seeking audio to %lld us (%.2f secs).", videoTimeUs, videoTimeUs / 1E6); // If we don't have a video time, seek audio to the originally // requested seek time instead. mAudioPlayer->seekTo(videoTimeUs < 0 ? mSeekTimeUs : videoTimeUs); mWatchForAudioSeekComplete = true; mWatchForAudioEOS = true; } else if (!mSeekNotificationSent) { // If we're playing video only, report seek complete now, // otherwise audio player will notify us later. notifyListener_l(MEDIA_SEEK_COMPLETE); mSeekNotificationSent = true; } mFlags |= FIRST_FRAME; mSeeking = NO_SEEK; } void PreviewPlayer::onCheckAudioStatus() { Mutex::Autolock autoLock(mLock); if (!mAudioStatusEventPending) { // Event was dispatched and while we were blocking on the mutex, // has already been cancelled. return; } mAudioStatusEventPending = false; #ifndef ANDROID_DEFAULT_CODE if(mAudioPlayer == NULL) { ALOGE("onCheckAudioStatus mAudioPlayer == NULL!"); return; } #endif if (mWatchForAudioSeekComplete && !mAudioPlayer->isSeeking()) { mWatchForAudioSeekComplete = false; if (!mSeekNotificationSent) { notifyListener_l(MEDIA_SEEK_COMPLETE); mSeekNotificationSent = true; } mSeeking = NO_SEEK; } status_t finalStatus; if (mWatchForAudioEOS && mAudioPlayer->reachedEOS(&finalStatus)) { mWatchForAudioEOS = false; mFlags |= AUDIO_AT_EOS; mFlags |= FIRST_FRAME; postStreamDoneEvent_l(finalStatus); } } void PreviewPlayer::postVideoEvent_l(int64_t delayUs) { if (mVideoEventPending) { return; } mVideoEventPending = true; mQueue.postEventWithDelay(mVideoEvent, delayUs < 0 ? 10000 : delayUs); } void PreviewPlayer::postStreamDoneEvent_l(status_t status) { if (mStreamDoneEventPending) { return; } mStreamDoneEventPending = true; mStreamDoneStatus = status; mQueue.postEvent(mStreamDoneEvent); } void PreviewPlayer::postVideoLagEvent_l() { if (mVideoLagEventPending) { return; } mVideoLagEventPending = true; mQueue.postEventWithDelay(mVideoLagEvent, 1000000ll); } void PreviewPlayer::postCheckAudioStatusEvent_l(int64_t delayUs) { if (mAudioStatusEventPending) { return; } mAudioStatusEventPending = true; mQueue.postEventWithDelay(mCheckAudioStatusEvent, delayUs); } void PreviewPlayer::abortPrepare(status_t err) { CHECK(err != OK); if (mIsAsyncPrepare) { notifyListener_l(MEDIA_ERROR, MEDIA_ERROR_UNKNOWN, err); } mPrepareResult = err; mFlags &= ~(PREPARING|PREPARE_CANCELLED|PREPARING_CONNECTED); mAsyncPrepareEvent = NULL; mPreparedCondition.broadcast(); } uint32_t PreviewPlayer::getSourceSeekFlags() const { Mutex::Autolock lock(mLock); return mExtractorFlags; } void PreviewPlayer::postAudioEOS(int64_t delayUs) { Mutex::Autolock autoLock(mLock); postCheckAudioStatusEvent_l(delayUs); } void PreviewPlayer::postAudioSeekComplete() { Mutex::Autolock autoLock(mLock); postCheckAudioStatusEvent_l(0 /* delayUs */); } void PreviewPlayer::updateBatteryUsage_l() { uint32_t params = IMediaPlayerService::kBatteryDataTrackDecoder; if ((mAudioSource != NULL) && (mAudioSource != mAudioTrack)) { params |= IMediaPlayerService::kBatteryDataTrackAudio; } if (mVideoSource != NULL) { params |= IMediaPlayerService::kBatteryDataTrackVideo; } addBatteryData(params); } } // namespace android
[ "zhangws@gmail.com" ]
zhangws@gmail.com
457ae2fa00c50881f988fb982a5e0a8047cc111c
11736eccc6bceb598930954d7c41255bc09e4df4
/Morse/Morse.h
0f4f95e4f20b71089dcf9e3e3e6d7dd8fe1deb1c
[]
no_license
azraelite/Morse
1812601ef1c31b983da6a63e62289f9f24a00ff0
6dc458a8d258db8ae77162bf1349271bef632ce3
refs/heads/master
2021-03-30T21:23:07.103548
2018-03-12T17:18:59
2018-03-12T17:18:59
124,922,808
0
0
null
null
null
null
UTF-8
C++
false
false
628
h
#ifndef Morse_h #define Morse_h #if ARDUINO>=100 #include "Arduino.h" #else #include "WProgram.h" #endif class Morse { public : Morse(); void moe(); void moi(); void mos(); void moh(); void mo5(); void test(); void setupMorse(uint8_t pin, long time); private : uint8_t _pin; long _time_unit; long _dot; long _dash; long _igap; long _sgap; long _mgap; unsigned long _time_now; void signal_m(); void signal_o(); void signal_e(); void signal_i(); void signal_s(); void signal_h(); void signal_5(); void signal_short_gap(); }; #endif
[ "noreply@github.com" ]
noreply@github.com
01da3fd41848b908a50d4a315db8b11dfff5ae00
acf7796906e59d64f285a88574406e1b9d4cd453
/624-B/624-B-50344018.cpp
aebc578fa0ddec37524c4779f7628df9d449172e
[]
no_license
samnoon1971/Codeforces
13fd99aa13a1d57792c7a0b9042c9f1fc3a14deb
a31444c717944d2c81f75af7a3e6650fb41ccf1d
refs/heads/main
2023-03-07T18:46:31.705957
2021-02-18T19:52:34
2021-02-18T19:52:34
340,160,077
1
0
null
null
null
null
UTF-8
C++
false
false
480
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { ll n, x; vector <ll> v; cin >> n; for(ll i=0; i<n; i++) { cin >> x; v.push_back(x); } sort(v.rbegin(), v.rend()); ll sum=*v.begin(), cnt=*v.begin(); for(vector <ll> :: iterator it=v.begin()+1; it!=v.end(); it++) { cnt=min(cnt-1, *it); if(!cnt) break; sum+=cnt; } cout << sum << endl; return 0; }
[ "samnoonabrar@gmail.com" ]
samnoonabrar@gmail.com
f05427155f971d3280370ff398b8336891cb9313
634120df190b6262fccf699ac02538360fd9012d
/Develop/mdk/Mint3.2/Source/MSheet.cpp
a363797b8edc6b9a814ab231f6de8e678b25707d
[]
no_license
ktj007/Raiderz_Public
c906830cca5c644be384e68da205ee8abeb31369
a71421614ef5711740d154c961cbb3ba2a03f266
refs/heads/master
2021-06-08T03:37:10.065320
2016-11-28T07:50:57
2016-11-28T07:50:57
74,959,309
6
4
null
2016-11-28T09:53:49
2016-11-28T09:53:49
null
UTF-8
C++
false
false
641
cpp
#include "stdafx.h" #include "MSheet.h" #include "Mint.h" namespace mint3 { // MSheet MSheet::MSheet( const char* szName, MWidget* pParent, MListener* pListener) : MWidget( szName, pParent, pListener) { m_Rect = MRECT( 0, 0, MGetMint()->GetStandardWidth(), MGetMint()->GetStandardHeight()); m_bDragAndDrop = false; SetAnchor( MAnchorStyle( true, true, true, true)); } // IsLayered bool MSheet::IsLayered() const { if ( m_pParent == NULL) return false; if ( m_pParent->IsLayered()) return true; return false; } // OnEvent bool MSheet::OnEvent( MEvent* pEvent, MListener* pListener) { return false; } } // namespace mint3
[ "espause0703@gmail.com" ]
espause0703@gmail.com
cb490dcdd3e86419bbdf2b3ca3d7a82cf7afd9d3
f01cf0c5aba8a588fefe8a08f0e357b3a023b6dd
/Exercise4/MeshViewer.hh
4182b9f303c7bb3c5649b5f96940ece5d3c0d057
[]
no_license
Immocat/CS621hw
569c6c10e0d8c9f6e674dbe6c87d097c9bd478ca
8e92ead1a01000cd6bc8ec778e946dd39e133f8f
refs/heads/master
2021-05-10T11:01:49.651645
2018-04-04T16:52:08
2018-04-04T16:52:08
118,399,726
7
1
null
null
null
null
UTF-8
C++
false
false
2,880
hh
//============================================================================= // // Code framework for the lecture // // "Surface Representation and Geometric Modeling" // // Mark Pauly, Mario Botsch, Balint Miklos, and Hao Li // // Copyright (C) 2007 by Computer Graphics Laboratory, ETH Zurich // // //----------------------------------------------------------------------------- // // License // // 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., 51 Franklin Street, Fifth Floor, // Boston, MA 02110-1301, USA. // //============================================================================= //============================================================================= // // CLASS MeshViewerWidget // //============================================================================= #ifndef MESH_VIEWER_WIDGET_HH #define MESH_VIEWER_WIDGET_HH //== INCLUDES ================================================================= #include "GlutExaminer.hh" #include <OpenMesh/Core/Mesh/TriMesh_ArrayKernelT.hh> //== CLASS DEFINITION ========================================================= class MeshViewer : public GlutExaminer { public: /// default constructor MeshViewer(const char* _title, int _width, int _height); /// open mesh virtual bool open_mesh(const char* _filename); /// update buffer with face indices void update_face_indices(); /// draw the scene virtual void draw(const std::string& _draw_mode); protected: typedef OpenMesh::TriMesh_ArrayKernelT<> Mesh; protected: Mesh mesh_; std::vector<unsigned int> indices_; }; //============================================================================= #endif // MESH_VIEWER_WIDGET_HH defined //=============================================================================
[ "immocat@hotmail.com" ]
immocat@hotmail.com
ce466105dc368b8aabfcf973632033e813e29934
54b8fc0f09512c46296fe1a7143c345290bec76a
/CreekWater/code/mywidgets/buttongroup/buttongroup.h
e7bd4719f0daa6002d68c126ec86e65549d9b00d
[]
no_license
flyghost/creekwater
367a2ec02d80a4a53a5104bba1bf74e646d8a046
08fadf016bbdabb4b22e0176df39581a627058c9
refs/heads/master
2022-11-12T06:08:23.326839
2022-08-17T17:02:59
2022-08-17T17:02:59
206,063,878
11
9
null
null
null
null
UTF-8
C++
false
false
5,090
h
#ifndef BUTTONGROUP_H #define BUTTONGROUP_H #include <QWidget> class QBoxLayout; class QAbstractButton; class QButtonGroup; class QPropertyAnimation; #ifdef quc #if (QT_VERSION < QT_VERSION_CHECK(5,7,0)) #include <QtDesigner/QDesignerExportWidget> #else #include <QtUiPlugin/QDesignerExportWidget> #endif class QDESIGNER_WIDGET_EXPORT ButtonGroup : public QWidget #else class ButtonGroup : public QWidget #endif { Q_OBJECT Q_ENUMS(LinePosition) Q_PROPERTY(int interval READ getInterval WRITE setInterval) Q_PROPERTY(int lineLen READ getLineLen WRITE setLineLen) Q_PROPERTY(int index READ getIndex WRITE setIndex) Q_PROPERTY(QString texts READ getTexts WRITE setTexts) Q_PROPERTY(LinePosition linePosition READ getLinePosition WRITE setLinePosition) Q_PROPERTY(QColor lineColor READ getLineColor WRITE setLineColor) Q_PROPERTY(QColor btnNormalColor READ getBtnNormalColor WRITE setBtnNormalColor) Q_PROPERTY(QColor btnHoverColor READ getBtnHoverColor WRITE setBtnHoverColor) Q_PROPERTY(QColor btnDarkColor READ getBtnDarkColor WRITE setBtnDarkColor) Q_PROPERTY(QColor textNormalColor READ getTextNormalColor WRITE setTextNormalColor) Q_PROPERTY(QColor textHoverColor READ getTextHoverColor WRITE setTextHoverColor) Q_PROPERTY(QColor textDarkColor READ getTextDarkColor WRITE setTextDarkColor) Q_PROPERTY(QColor baseColor READ getBaseColor WRITE setBaseColor) public: enum LinePosition { LinePosition_Left = 0, //左边 LinePosition_Right = 1, //右边 LinePosition_Top = 2, //上边 LinePosition_Bottom = 3 //下边 }; explicit ButtonGroup(QWidget *parent = 0); ~ButtonGroup(); protected: void resizeEvent(QResizeEvent *); void showEvent(QShowEvent *); void paintEvent(QPaintEvent *); private: int interval; //线条移动的速度 int lineLen; //线条的长度 int index; //当前索引 QString texts; //按钮文本集合 LinePosition linePosition; //线条方向 QColor lineColor; //线条的颜色 QColor btnNormalColor; //按钮正常颜色 QColor btnHoverColor; //按钮经过颜色 QColor btnDarkColor; //按钮加深选中颜色 QColor textNormalColor; //文字正常颜色 QColor textHoverColor; //文字经过颜色 QColor textDarkColor; //文字加深选中颜色 QColor baseColor; //基准颜色 int previousIndex; //上一个按钮索引 int offset; //偏移量 QSize btnSize; //按钮的尺寸 QBoxLayout *layout; //布局 QButtonGroup *btnGroup; //按钮组 QList<QAbstractButton *> btns; //按钮集合 QPropertyAnimation *animation; //属性动画 private slots: void onButtonClicked(int index); void onValueChanged(const QVariant &value); public: int getInterval() const; int getLineLen() const; int getIndex() const; QString getTexts() const; LinePosition getLinePosition() const; QColor getLineColor() const; QColor getBtnNormalColor() const; QColor getBtnHoverColor() const; QColor getBtnDarkColor() const; QColor getTextNormalColor() const; QColor getTextHoverColor() const; QColor getTextDarkColor() const; QColor getBaseColor() const; QSize sizeHint() const; QSize minimumSizeHint() const; public Q_SLOTS: //设置线条移动的速度 void setInterval(int interval); //设置线条的尺寸 void setLineLen(int lineLen); //设置当前索引,选中按钮 void setIndex(int index); //设置按钮文本集合 void setTexts(const QString &texts); //设置线条方向 void setLinePosition(const LinePosition &linePosition); //设置线条颜色 void setLineColor(const QColor &lineColor); //设置按钮正常颜色 void setBtnNormalColor(const QColor &btnNormalColor); //设置按钮悬停颜色 void setBtnHoverColor(const QColor &btnHoverColor); //设置鼠标选中颜色 void setBtnDarkColor(const QColor &btnDarkColor); //设置文字正常颜色 void setTextNormalColor(const QColor &textNormalColor); //设置文字悬停颜色 void setTextHoverColor(const QColor &textHoverColor); //设置文字选中颜色 void setTextDarkColor(const QColor &textDarkColor); //设置基准颜色 void setBaseColor(const QColor &baseColor, bool normal = false); //初始化按下按钮 void init(); //添加按钮 void addButton(QAbstractButton *btn, int id); //结束添加 void addFinsh(); //设置按钮样式 void setBtnStyle(); Q_SIGNALS: void buttonClicked(int index); void buttonClicked(QAbstractButton *btn); }; #endif // BUTTONGROUP_H
[ "zhaoyang_wu@foxmail.com" ]
zhaoyang_wu@foxmail.com
e082495b1f3bd4ed966ebad1909b45b96e723cf3
56924001e3334f5ecdf28fe5080e91f5aa1ebd6a
/RealmSwiftDemo/Pods/Realm/include/core/realm/util/string_buffer.hpp
c6e0824f4a904284561171584f923c54ad082840
[ "Apache-2.0", "LicenseRef-scancode-commercial-license", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-generic-export-compliance" ]
permissive
iMazy/DemoBySwift
2c51e541e31065387d74aed02d0e6b899d2c93e9
173ceb71512c13d7b4bef520a4574be70e0b8a2a
refs/heads/master
2022-12-04T15:44:28.846787
2022-11-22T08:53:52
2022-11-22T08:53:52
89,046,336
10
2
Apache-2.0
2017-12-05T02:30:13
2017-04-22T05:18:44
Swift
UTF-8
C++
false
false
4,886
hpp
/************************************************************************* * * Copyright 2016 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **************************************************************************/ #ifndef REALM_UTIL_STRING_BUFFER_HPP #define REALM_UTIL_STRING_BUFFER_HPP #include <cstddef> #include <cstring> #include <string> #include <realm/util/features.h> #include <realm/util/buffer.hpp> namespace realm { namespace util { // FIXME: Check whether this class provides anything that a C++03 // std::string does not already provide. In particular, can a C++03 // std::string be used as a contiguous mutable buffer? class StringBuffer { public: StringBuffer() noexcept; ~StringBuffer() noexcept { } std::string str() const; /// Returns the current size of the string in this buffer. This /// size does not include the terminating zero. size_t size() const noexcept; /// Gives read and write access to the bytes of this buffer. The /// caller may read and write from *c_str() up to, but not /// including, *(c_str()+size()). char* data() noexcept; /// Gives read access to the bytes of this buffer. The caller may /// read from *c_str() up to, but not including, /// *(c_str()+size()). const char* data() const noexcept; /// Guarantees that the returned string is zero terminated, that /// is, *(c_str()+size()) is zero. The caller may read from /// *c_str() up to and including *(c_str()+size()). const char* c_str() const noexcept; void append(const std::string&); void append(const char* append_data, size_t append_size); /// Append a zero-terminated string to this buffer. void append_c_str(const char* c_string); /// The specified size is understood as not including the /// terminating zero. If the specified size is less than the /// current size, then the string is truncated accordingly. If the /// specified size is greater than the current size, then the /// extra characters will have undefined values, however, there /// will be a terminating zero at *(c_str()+size()), and the /// original terminating zero will also be left in place such that /// from the point of view of c_str(), the size of the string is /// unchanged. void resize(size_t new_size); /// The specified minimum capacity is understood as not including /// the terminating zero. This operation does not change the size /// of the string in the buffer as returned by size(). If the /// specified capacity is less than the current capacity, this /// operation has no effect. void reserve(size_t min_capacity); /// Set size to zero. The capacity remains unchanged. void clear() noexcept; private: util::Buffer<char> m_buffer; size_t m_size; // Excluding the terminating zero void reallocate(size_t min_capacity); }; // Implementation: inline StringBuffer::StringBuffer() noexcept : m_size(0) { } inline std::string StringBuffer::str() const { return std::string(m_buffer.data(), m_size); } inline size_t StringBuffer::size() const noexcept { return m_size; } inline char* StringBuffer::data() noexcept { return m_buffer.data(); } inline const char* StringBuffer::data() const noexcept { return m_buffer.data(); } inline const char* StringBuffer::c_str() const noexcept { static const char zero = 0; const char* d = data(); return d ? d : &zero; } inline void StringBuffer::append(const std::string& s) { return append(s.data(), s.size()); } inline void StringBuffer::append_c_str(const char* c_string) { append(c_string, std::strlen(c_string)); } inline void StringBuffer::reserve(size_t min_capacity) { size_t capacity = m_buffer.size(); if (capacity == 0 || capacity - 1 < min_capacity) reallocate(min_capacity); } inline void StringBuffer::resize(size_t new_size) { reserve(new_size); // Note that even reserve(0) will attempt to allocate a // buffer, so we can safely write the truncating zero at this // time. m_size = new_size; m_buffer[new_size] = 0; } inline void StringBuffer::clear() noexcept { if (m_buffer.size() == 0) return; m_size = 0; m_buffer[0] = 0; } } // namespace util } // namespace realm #endif // REALM_UTIL_STRING_BUFFER_HPP
[ "mazongyong@163.com" ]
mazongyong@163.com
9069a72d86de90a7cfd411cafa402e1752044b9d
f6cecd4e3ca6f66ba36505173d959db53745036f
/ios/versioned-react-native/ABI44_0_0/ReactNative/ReactCommon/react/renderer/components/textinput/iostextinput/ABI44_0_0TextInputEventEmitter.cpp
2637200890a9497023346a56476095a54b68e139
[ "BSD-3-Clause", "MIT", "Apache-2.0" ]
permissive
Simek/expo
6d3844eb75206c72c35b91c8f1752328aee99749
6f3c4a42304030fc2d2fbd213b07c1aac6785206
refs/heads/main
2023-02-05T11:30:58.908890
2022-07-19T10:03:07
2022-07-19T10:03:07
222,480,219
1
0
MIT
2022-08-18T08:43:17
2019-11-18T15:23:00
Objective-C
UTF-8
C++
false
false
3,630
cpp
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "ABI44_0_0TextInputEventEmitter.h" namespace ABI44_0_0facebook { namespace ABI44_0_0React { static jsi::Value textInputMetricsPayload( jsi::Runtime &runtime, TextInputMetrics const &textInputMetrics) { auto payload = jsi::Object(runtime); payload.setProperty( runtime, "text", jsi::String::createFromUtf8(runtime, textInputMetrics.text)); payload.setProperty(runtime, "eventCount", textInputMetrics.eventCount); { auto selection = jsi::Object(runtime); selection.setProperty( runtime, "start", textInputMetrics.selectionRange.location); selection.setProperty( runtime, "end", textInputMetrics.selectionRange.location + textInputMetrics.selectionRange.length); payload.setProperty(runtime, "selection", selection); } return payload; }; static jsi::Value keyPressMetricsPayload( jsi::Runtime &runtime, KeyPressMetrics const &keyPressMetrics) { auto payload = jsi::Object(runtime); payload.setProperty(runtime, "eventCount", keyPressMetrics.eventCount); std::string key; if (keyPressMetrics.text.empty()) { key = "Backspace"; } else { if (keyPressMetrics.text.front() == '\n') { key = "Enter"; } else if (keyPressMetrics.text.front() == '\t') { key = "Tab"; } else { key = keyPressMetrics.text.front(); } } payload.setProperty( runtime, "key", jsi::String::createFromUtf8(runtime, key)); return payload; }; void TextInputEventEmitter::onFocus( TextInputMetrics const &textInputMetrics) const { dispatchTextInputEvent("focus", textInputMetrics); } void TextInputEventEmitter::onBlur( TextInputMetrics const &textInputMetrics) const { dispatchTextInputEvent("blur", textInputMetrics); } void TextInputEventEmitter::onChange( TextInputMetrics const &textInputMetrics) const { dispatchTextInputEvent("change", textInputMetrics); } void TextInputEventEmitter::onChangeText( TextInputMetrics const &textInputMetrics) const { dispatchTextInputEvent("changeText", textInputMetrics); } void TextInputEventEmitter::onContentSizeChange( TextInputMetrics const &textInputMetrics) const { dispatchTextInputEvent("contentSizeChange", textInputMetrics); } void TextInputEventEmitter::onSelectionChange( TextInputMetrics const &textInputMetrics) const { dispatchTextInputEvent("selectionChange", textInputMetrics); } void TextInputEventEmitter::onEndEditing( TextInputMetrics const &textInputMetrics) const { dispatchTextInputEvent("endEditing", textInputMetrics); } void TextInputEventEmitter::onSubmitEditing( TextInputMetrics const &textInputMetrics) const { dispatchTextInputEvent("submitEditing", textInputMetrics); } void TextInputEventEmitter::onKeyPress( KeyPressMetrics const &keyPressMetrics) const { dispatchEvent( "keyPress", [keyPressMetrics](jsi::Runtime &runtime) { return keyPressMetricsPayload(runtime, keyPressMetrics); }, EventPriority::AsynchronousBatched); } void TextInputEventEmitter::dispatchTextInputEvent( std::string const &name, TextInputMetrics const &textInputMetrics, EventPriority priority) const { dispatchEvent( name, [textInputMetrics](jsi::Runtime &runtime) { return textInputMetricsPayload(runtime, textInputMetrics); }, priority); } } // namespace ABI44_0_0React } // namespace ABI44_0_0facebook
[ "noreply@github.com" ]
noreply@github.com
79b7cf77e12be03a63e87a022f88f24583739550
5f919f448d074caa4cb932fab8f829f8b480b873
/src/rpc/net.cpp
65efd6de2b1022a591f53a540db99fee9bad46f6
[ "MIT" ]
permissive
swatchie-1/hilux
9849440fe25548d0f97f0cb5d88f4deff1140204
8d8e9f93144829b65868d051fcc08f7e28610daa
refs/heads/master
2021-07-19T20:46:43.779686
2020-03-03T21:16:29
2020-03-03T21:16:29
141,552,658
7
10
MIT
2020-04-22T21:53:24
2018-07-19T09:02:00
C++
UTF-8
C++
false
false
26,445
cpp
// Copyright (c) 2009-2015 The Bitcoin Core developers // Copyright (c) 2014-2017 The Dash Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "rpc/server.h" #include "chainparams.h" #include "clientversion.h" #include "validation.h" #include "net.h" #include "net_processing.h" #include "netbase.h" #include "protocol.h" #include "sync.h" #include "timedata.h" #include "ui_interface.h" #include "util.h" #include "utilstrencodings.h" #include "version.h" #include <boost/foreach.hpp> #include <univalue.h> using namespace std; UniValue getconnectioncount(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getconnectioncount\n" "\nReturns the number of connections to other nodes.\n" "\nResult:\n" "n (numeric) The connection count\n" "\nExamples:\n" + HelpExampleCli("getconnectioncount", "") + HelpExampleRpc("getconnectioncount", "") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); return (int)g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL); } UniValue ping(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "ping\n" "\nRequests that a ping be sent to all other nodes, to measure ping time.\n" "Results provided in getpeerinfo, pingtime and pingwait fields are decimal seconds.\n" "Ping command is handled in queue with all other commands, so it measures processing backlog, not just network ping.\n" "\nExamples:\n" + HelpExampleCli("ping", "") + HelpExampleRpc("ping", "") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); // Request that each node send a ping during next message processing pass g_connman->ForEachNode([](CNode* pnode) { pnode->fPingQueued = true; }); return NullUniValue; } UniValue getpeerinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getpeerinfo\n" "\nReturns data about each connected network node as a json array of objects.\n" "\nResult:\n" "[\n" " {\n" " \"id\": n, (numeric) Peer index\n" " \"addr\":\"host:port\", (string) The ip address and port of the peer\n" " \"addrlocal\":\"ip:port\", (string) local address\n" " \"services\":\"xxxxxxxxxxxxxxxx\", (string) The services offered\n" " \"relaytxes\":true|false, (boolean) Whether peer has asked us to relay transactions to it\n" " \"lastsend\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last send\n" " \"lastrecv\": ttt, (numeric) The time in seconds since epoch (Jan 1 1970 GMT) of the last receive\n" " \"bytessent\": n, (numeric) The total bytes sent\n" " \"bytesrecv\": n, (numeric) The total bytes received\n" " \"conntime\": ttt, (numeric) The connection time in seconds since epoch (Jan 1 1970 GMT)\n" " \"timeoffset\": ttt, (numeric) The time offset in seconds\n" " \"pingtime\": n, (numeric) ping time (if available)\n" " \"minping\": n, (numeric) minimum observed ping time (if any at all)\n" " \"pingwait\": n, (numeric) ping wait (if non-zero)\n" " \"version\": v, (numeric) The peer version, such as 7001\n" " \"subver\": \"/Hilux Core:x.x.x/\", (string) The string version\n" " \"inbound\": true|false, (boolean) Inbound (true) or Outbound (false)\n" " \"startingheight\": n, (numeric) The starting height (block) of the peer\n" " \"banscore\": n, (numeric) The ban score\n" " \"synced_headers\": n, (numeric) The last header we have in common with this peer\n" " \"synced_blocks\": n, (numeric) The last block we have in common with this peer\n" " \"inflight\": [\n" " n, (numeric) The heights of blocks we're currently asking from this peer\n" " ...\n" " ]\n" " \"bytessent_per_msg\": {\n" " \"addr\": n, (numeric) The total bytes sent aggregated by message type\n" " ...\n" " }\n" " \"bytesrecv_per_msg\": {\n" " \"addr\": n, (numeric) The total bytes received aggregated by message type\n" " ...\n" " }\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getpeerinfo", "") + HelpExampleRpc("getpeerinfo", "") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); vector<CNodeStats> vstats; g_connman->GetNodeStats(vstats); UniValue ret(UniValue::VARR); BOOST_FOREACH(const CNodeStats& stats, vstats) { UniValue obj(UniValue::VOBJ); CNodeStateStats statestats; bool fStateStats = GetNodeStateStats(stats.nodeid, statestats); obj.push_back(Pair("id", stats.nodeid)); obj.push_back(Pair("addr", stats.addrName)); if (!(stats.addrLocal.empty())) obj.push_back(Pair("addrlocal", stats.addrLocal)); obj.push_back(Pair("services", strprintf("%016x", stats.nServices))); obj.push_back(Pair("relaytxes", stats.fRelayTxes)); obj.push_back(Pair("lastsend", stats.nLastSend)); obj.push_back(Pair("lastrecv", stats.nLastRecv)); obj.push_back(Pair("bytessent", stats.nSendBytes)); obj.push_back(Pair("bytesrecv", stats.nRecvBytes)); obj.push_back(Pair("conntime", stats.nTimeConnected)); obj.push_back(Pair("timeoffset", stats.nTimeOffset)); if (stats.dPingTime > 0.0) obj.push_back(Pair("pingtime", stats.dPingTime)); if (stats.dMinPing < std::numeric_limits<int64_t>::max()/1e6) obj.push_back(Pair("minping", stats.dMinPing)); if (stats.dPingWait > 0.0) obj.push_back(Pair("pingwait", stats.dPingWait)); obj.push_back(Pair("version", stats.nVersion)); // Use the sanitized form of subver here, to avoid tricksy remote peers from // corrupting or modifiying the JSON output by putting special characters in // their ver message. obj.push_back(Pair("subver", stats.cleanSubVer)); obj.push_back(Pair("inbound", stats.fInbound)); obj.push_back(Pair("startingheight", stats.nStartingHeight)); if (fStateStats) { obj.push_back(Pair("banscore", statestats.nMisbehavior)); obj.push_back(Pair("synced_headers", statestats.nSyncHeight)); obj.push_back(Pair("synced_blocks", statestats.nCommonHeight)); UniValue heights(UniValue::VARR); BOOST_FOREACH(int height, statestats.vHeightInFlight) { heights.push_back(height); } obj.push_back(Pair("inflight", heights)); } obj.push_back(Pair("whitelisted", stats.fWhitelisted)); UniValue sendPerMsgCmd(UniValue::VOBJ); BOOST_FOREACH(const mapMsgCmdSize::value_type &i, stats.mapSendBytesPerMsgCmd) { if (i.second > 0) sendPerMsgCmd.push_back(Pair(i.first, i.second)); } obj.push_back(Pair("bytessent_per_msg", sendPerMsgCmd)); UniValue recvPerMsgCmd(UniValue::VOBJ); BOOST_FOREACH(const mapMsgCmdSize::value_type &i, stats.mapRecvBytesPerMsgCmd) { if (i.second > 0) recvPerMsgCmd.push_back(Pair(i.first, i.second)); } obj.push_back(Pair("bytesrecv_per_msg", recvPerMsgCmd)); ret.push_back(obj); } return ret; } UniValue addnode(const UniValue& params, bool fHelp) { string strCommand; if (params.size() == 2) strCommand = params[1].get_str(); if (fHelp || params.size() != 2 || (strCommand != "onetry" && strCommand != "add" && strCommand != "remove")) throw runtime_error( "addnode \"node\" \"add|remove|onetry\"\n" "\nAttempts add or remove a node from the addnode list.\n" "Or try a connection to a node once.\n" "\nArguments:\n" "1. \"node\" (string, required) The node (see getpeerinfo for nodes)\n" "2. \"command\" (string, required) 'add' to add a node to the list, 'remove' to remove a node from the list, 'onetry' to try a connection to the node once\n" "\nExamples:\n" + HelpExampleCli("addnode", "\"192.168.0.6:9999\" \"onetry\"") + HelpExampleRpc("addnode", "\"192.168.0.6:9999\", \"onetry\"") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); string strNode = params[0].get_str(); if (strCommand == "onetry") { CAddress addr; g_connman->OpenNetworkConnection(addr, NULL, strNode.c_str()); return NullUniValue; } if (strCommand == "add") { if(!g_connman->AddNode(strNode)) throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: Node already added"); } else if(strCommand == "remove") { if(!g_connman->RemoveAddedNode(strNode)) throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node has not been added."); } return NullUniValue; } UniValue disconnectnode(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "disconnectnode \"node\" \n" "\nImmediately disconnects from the specified node.\n" "\nArguments:\n" "1. \"node\" (string, required) The node (see getpeerinfo for nodes)\n" "\nExamples:\n" + HelpExampleCli("disconnectnode", "\"192.168.0.6:9999\"") + HelpExampleRpc("disconnectnode", "\"192.168.0.6:9999\"") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); bool ret = g_connman->DisconnectNode(params[0].get_str()); if (!ret) throw JSONRPCError(RPC_CLIENT_NODE_NOT_CONNECTED, "Node not found in connected nodes"); return NullUniValue; } UniValue getaddednodeinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "getaddednodeinfo dummy ( \"node\" )\n" "\nReturns information about the given added node, or all added nodes\n" "(note that onetry addnodes are not listed here)\n" "\nArguments:\n" "1. dummy (boolean, required) Kept for historical purposes but ignored\n" "2. \"node\" (string, optional) If provided, return information about this specific node, otherwise all nodes are returned.\n" "\nResult:\n" "[\n" " {\n" " \"addednode\" : \"192.168.0.201\", (string) The node ip address or name (as provided to addnode)\n" " \"connected\" : true|false, (boolean) If connected\n" " \"addresses\" : [ (list of objects) Only when connected = true\n" " {\n" " \"address\" : \"192.168.0.201:9999\", (string) The hilux server IP and port we're connected to\n" " \"connected\" : \"outbound\" (string) connection, inbound or outbound\n" " }\n" " ]\n" " }\n" " ,...\n" "]\n" "\nExamples:\n" + HelpExampleCli("getaddednodeinfo", "true") + HelpExampleCli("getaddednodeinfo", "true \"192.168.0.201\"") + HelpExampleRpc("getaddednodeinfo", "true, \"192.168.0.201\"") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); std::vector<AddedNodeInfo> vInfo = g_connman->GetAddedNodeInfo(); if (params.size() == 2) { bool found = false; for (const AddedNodeInfo& info : vInfo) { if (info.strAddedNode == params[1].get_str()) { vInfo.assign(1, info); found = true; break; } } if (!found) { throw JSONRPCError(RPC_CLIENT_NODE_NOT_ADDED, "Error: Node has not been added."); } } UniValue ret(UniValue::VARR); for (const AddedNodeInfo& info : vInfo) { UniValue obj(UniValue::VOBJ); obj.push_back(Pair("addednode", info.strAddedNode)); obj.push_back(Pair("connected", info.fConnected)); UniValue addresses(UniValue::VARR); if (info.fConnected) { UniValue address(UniValue::VOBJ); address.push_back(Pair("address", info.resolvedAddress.ToString())); address.push_back(Pair("connected", info.fInbound ? "inbound" : "outbound")); addresses.push_back(address); } obj.push_back(Pair("addresses", addresses)); ret.push_back(obj); } return ret; } UniValue getnettotals(const UniValue& params, bool fHelp) { if (fHelp || params.size() > 0) throw runtime_error( "getnettotals\n" "\nReturns information about network traffic, including bytes in, bytes out,\n" "and current time.\n" "\nResult:\n" "{\n" " \"totalbytesrecv\": n, (numeric) Total bytes received\n" " \"totalbytessent\": n, (numeric) Total bytes sent\n" " \"timemillis\": t, (numeric) Total cpu time\n" " \"uploadtarget\":\n" " {\n" " \"timeframe\": n, (numeric) Length of the measuring timeframe in seconds\n" " \"target\": n, (numeric) Target in bytes\n" " \"target_reached\": true|false, (boolean) True if target is reached\n" " \"serve_historical_blocks\": true|false, (boolean) True if serving historical blocks\n" " \"bytes_left_in_cycle\": t, (numeric) Bytes left in current time cycle\n" " \"time_left_in_cycle\": t (numeric) Seconds left in current time cycle\n" " }\n" "}\n" "\nExamples:\n" + HelpExampleCli("getnettotals", "") + HelpExampleRpc("getnettotals", "") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); UniValue obj(UniValue::VOBJ); obj.push_back(Pair("totalbytesrecv", g_connman->GetTotalBytesRecv())); obj.push_back(Pair("totalbytessent", g_connman->GetTotalBytesSent())); obj.push_back(Pair("timemillis", GetTimeMillis())); UniValue outboundLimit(UniValue::VOBJ); outboundLimit.push_back(Pair("timeframe", g_connman->GetMaxOutboundTimeframe())); outboundLimit.push_back(Pair("target", g_connman->GetMaxOutboundTarget())); outboundLimit.push_back(Pair("target_reached", g_connman->OutboundTargetReached(false))); outboundLimit.push_back(Pair("serve_historical_blocks", !g_connman->OutboundTargetReached(true))); outboundLimit.push_back(Pair("bytes_left_in_cycle", g_connman->GetOutboundTargetBytesLeft())); outboundLimit.push_back(Pair("time_left_in_cycle", g_connman->GetMaxOutboundTimeLeftInCycle())); obj.push_back(Pair("uploadtarget", outboundLimit)); return obj; } static UniValue GetNetworksInfo() { UniValue networks(UniValue::VARR); for(int n=0; n<NET_MAX; ++n) { enum Network network = static_cast<enum Network>(n); if(network == NET_UNROUTABLE) continue; proxyType proxy; UniValue obj(UniValue::VOBJ); GetProxy(network, proxy); obj.push_back(Pair("name", GetNetworkName(network))); obj.push_back(Pair("limited", IsLimited(network))); obj.push_back(Pair("reachable", IsReachable(network))); obj.push_back(Pair("proxy", proxy.IsValid() ? proxy.proxy.ToStringIPPort() : string())); obj.push_back(Pair("proxy_randomize_credentials", proxy.randomize_credentials)); networks.push_back(obj); } return networks; } UniValue getnetworkinfo(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getnetworkinfo\n" "Returns an object containing various state info regarding P2P networking.\n" "\nResult:\n" "{\n" " \"version\": xxxxx, (numeric) the server version\n" " \"subversion\": \"/Hilux Core:x.x.x/\", (string) the server subversion string\n" " \"protocolversion\": xxxxx, (numeric) the protocol version\n" " \"localservices\": \"xxxxxxxxxxxxxxxx\", (string) the services we offer to the network\n" " \"localrelay\": true|false, (bool) true if transaction relay is requested from peers\n" " \"timeoffset\": xxxxx, (numeric) the time offset\n" " \"connections\": xxxxx, (numeric) the number of connections\n" " \"networkactive\": true|false, (bool) whether p2p networking is enabled\n" " \"networks\": [ (array) information per network\n" " {\n" " \"name\": \"xxx\", (string) network (ipv4, ipv6 or onion)\n" " \"limited\": true|false, (boolean) is the network limited using -onlynet?\n" " \"reachable\": true|false, (boolean) is the network reachable?\n" " \"proxy\": \"host:port\" (string) the proxy that is used for this network, or empty if none\n" " }\n" " ,...\n" " ],\n" " \"relayfee\": x.xxxxxxxx, (numeric) minimum relay fee for non-free transactions in " + CURRENCY_UNIT + "/kB\n" " \"localaddresses\": [ (array) list of local addresses\n" " {\n" " \"address\": \"xxxx\", (string) network address\n" " \"port\": xxx, (numeric) network port\n" " \"score\": xxx (numeric) relative score\n" " }\n" " ,...\n" " ]\n" " \"warnings\": \"...\" (string) any network warnings (such as alert messages) \n" "}\n" "\nExamples:\n" + HelpExampleCli("getnetworkinfo", "") + HelpExampleRpc("getnetworkinfo", "") ); LOCK(cs_main); UniValue obj(UniValue::VOBJ); obj.push_back(Pair("version", CLIENT_VERSION)); obj.push_back(Pair("subversion", strSubVersion)); obj.push_back(Pair("protocolversion",PROTOCOL_VERSION)); if(g_connman) obj.push_back(Pair("localservices", strprintf("%016x", g_connman->GetLocalServices()))); obj.push_back(Pair("localrelay", fRelayTxes)); obj.push_back(Pair("timeoffset", GetTimeOffset())); if (g_connman) { obj.push_back(Pair("networkactive", g_connman->GetNetworkActive())); obj.push_back(Pair("connections", (int)g_connman->GetNodeCount(CConnman::CONNECTIONS_ALL))); } obj.push_back(Pair("networks", GetNetworksInfo())); obj.push_back(Pair("relayfee", ValueFromAmount(::minRelayTxFee.GetFeePerK()))); UniValue localAddresses(UniValue::VARR); { LOCK(cs_mapLocalHost); BOOST_FOREACH(const PAIRTYPE(CNetAddr, LocalServiceInfo) &item, mapLocalHost) { UniValue rec(UniValue::VOBJ); rec.push_back(Pair("address", item.first.ToString())); rec.push_back(Pair("port", item.second.nPort)); rec.push_back(Pair("score", item.second.nScore)); localAddresses.push_back(rec); } } obj.push_back(Pair("localaddresses", localAddresses)); obj.push_back(Pair("warnings", GetWarnings("statusbar"))); return obj; } UniValue setban(const UniValue& params, bool fHelp) { string strCommand; if (params.size() >= 2) strCommand = params[1].get_str(); if (fHelp || params.size() < 2 || (strCommand != "add" && strCommand != "remove")) throw runtime_error( "setban \"ip(/netmask)\" \"add|remove\" (bantime) (absolute)\n" "\nAttempts add or remove a IP/Subnet from the banned list.\n" "\nArguments:\n" "1. \"ip(/netmask)\" (string, required) The IP/Subnet (see getpeerinfo for nodes ip) with a optional netmask (default is /32 = single ip)\n" "2. \"command\" (string, required) 'add' to add a IP/Subnet to the list, 'remove' to remove a IP/Subnet from the list\n" "3. \"bantime\" (numeric, optional) time in seconds how long (or until when if [absolute] is set) the ip is banned (0 or empty means using the default time of 24h which can also be overwritten by the -bantime startup argument)\n" "4. \"absolute\" (boolean, optional) If set, the bantime must be a absolute timestamp in seconds since epoch (Jan 1 1970 GMT)\n" "\nExamples:\n" + HelpExampleCli("setban", "\"192.168.0.6\" \"add\" 86400") + HelpExampleCli("setban", "\"192.168.0.0/24\" \"add\"") + HelpExampleRpc("setban", "\"192.168.0.6\", \"add\" 86400") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); CSubNet subNet; CNetAddr netAddr; bool isSubnet = false; if (params[0].get_str().find("/") != string::npos) isSubnet = true; if (!isSubnet) { CNetAddr resolved; LookupHost(params[0].get_str().c_str(), resolved, false); netAddr = resolved; } else LookupSubNet(params[0].get_str().c_str(), subNet); if (! (isSubnet ? subNet.IsValid() : netAddr.IsValid()) ) throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: Invalid IP/Subnet"); if (strCommand == "add") { if (isSubnet ? g_connman->IsBanned(subNet) : g_connman->IsBanned(netAddr)) throw JSONRPCError(RPC_CLIENT_NODE_ALREADY_ADDED, "Error: IP/Subnet already banned"); int64_t banTime = 0; //use standard bantime if not specified if (params.size() >= 3 && !params[2].isNull()) banTime = params[2].get_int64(); bool absolute = false; if (params.size() == 4 && params[3].isTrue()) absolute = true; isSubnet ? g_connman->Ban(subNet, BanReasonManuallyAdded, banTime, absolute) : g_connman->Ban(netAddr, BanReasonManuallyAdded, banTime, absolute); } else if(strCommand == "remove") { if (!( isSubnet ? g_connman->Unban(subNet) : g_connman->Unban(netAddr) )) throw JSONRPCError(RPC_MISC_ERROR, "Error: Unban failed"); } return NullUniValue; } UniValue listbanned(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "listbanned\n" "\nList all banned IPs/Subnets.\n" "\nExamples:\n" + HelpExampleCli("listbanned", "") + HelpExampleRpc("listbanned", "") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); banmap_t banMap; g_connman->GetBanned(banMap); UniValue bannedAddresses(UniValue::VARR); for (banmap_t::iterator it = banMap.begin(); it != banMap.end(); it++) { CBanEntry banEntry = (*it).second; UniValue rec(UniValue::VOBJ); rec.push_back(Pair("address", (*it).first.ToString())); rec.push_back(Pair("banned_until", banEntry.nBanUntil)); rec.push_back(Pair("ban_created", banEntry.nCreateTime)); rec.push_back(Pair("ban_reason", banEntry.banReasonToString())); bannedAddresses.push_back(rec); } return bannedAddresses; } UniValue clearbanned(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "clearbanned\n" "\nClear all banned IPs.\n" "\nExamples:\n" + HelpExampleCli("clearbanned", "") + HelpExampleRpc("clearbanned", "") ); if(!g_connman) throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); g_connman->ClearBanned(); return NullUniValue; } UniValue setnetworkactive(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) { throw runtime_error( "setnetworkactive true|false\n" "Disable/enable all p2p network activity." ); } if (!g_connman) { throw JSONRPCError(RPC_CLIENT_P2P_DISABLED, "Error: Peer-to-peer functionality missing or disabled"); } g_connman->SetNetworkActive(params[0].get_bool()); return g_connman->GetNetworkActive(); }
[ "tzehming@gmail.com" ]
tzehming@gmail.com
97c88fce1b73e9942fe403c256b194dfb8e35640
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_20293.cpp
588841538e1988b0f196d50b1bfc6b82aaf13012
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
110
cpp
(cb) { QUEUE_FS_TP_JOB(loop, req); return 0; } else { fs__link(req); return req->result; }
[ "993273596@qq.com" ]
993273596@qq.com
01fc42a93580fa5dc2aac02199894d210d579947
fa59cf02bff45a1fe2c3bc0e6fd82a8b92e70c74
/SymAna/Register.cpp
f432170685546bf57d24fd117e8d2aa74d6f3d68
[]
no_license
liumuqing/symDep
90bc3d9bdcad8056f1f5397eb8f0f5fb42fbbe88
d1ea722f3ebc30de987f5c9f6da6dd1a03b1964d
refs/heads/master
2021-01-13T01:59:03.590374
2014-07-03T07:02:47
2014-07-03T07:02:47
21,450,104
1
0
null
null
null
null
GB18030
C++
false
false
2,435
cpp
#include "Common.h" #include "Register.h" const unsigned int REG4_LEN = 8; Register REG4[REG4_LEN] = { eax, ebx, ecx, edx, esp, ebp, esi, edi }; const unsigned int REG2_LEN = 8; Register REG2[REG2_LEN] = { ax, bx, cx, dx, sp, bp, si, di }; const unsigned int REG1_LEN = 8; Register REG1[REG1_LEN] = { al, bl, cl, dl, ah, bh, ch, dh }; const unsigned int REG_ALL_LEN = REG4_LEN + REG2_LEN + REG1_LEN; Register REG_ALL[REG_ALL_LEN] = { eax, ebx, ecx, edx, esp, ebp, esi, edi, ax, bx, cx, dx, sp, bp, si, di, al, bl, cl, dl, ah, bh, ch, dh, }; const unsigned int REG_TOTAL_BYTE = 8 * 4; unsigned int registerLength(Register reg) { switch (char(reg) & 0xf0) { case 0x00: return 4; case 0x10: return 2; case 0x20: case 0x30: return 1; default: printf("%d", reg); throw Error("registerLength Error"); } } unsigned int registerOffset(Register reg)//将32位寄存器依次排列,返回某一寄存器的偏移量,比如说ax就返回0, ah就返回1, ebx返回4, 必须从0开始,紧密排列 { switch (reg & 0xf0) { case 0x00: case 0x10: case 0x20: return (reg & 0x0f) * 4; case 0x30: return (reg & 0x0f) * 4 + 1; default: throw Error("registerOffset Error"); } } Register stringToRegister(const char * str, unsigned int length) { if (length == 0) length = strlen(str); switch (length) { case 2: switch (str[1]) { case 'x': switch (str[0]){ case 'a': return ax; case 'b': return bx; case 'c': return cx; case 'd': return dx; }break; case 'h': switch (str[0]){ case 'a': return ah; case 'b': return bh; case 'c': return ch; case 'd': return dh; }break; case 'l': switch (str[0]){ case 'a': return al; case 'b': return bl; case 'c': return cl; case 'd': return dl; }break; case 'p': switch (str[0]){ case 'b': return bp; case 's': return sp; }break; case 'i': switch (str[0]){ case 'd': return di; case 's': return si; }break; } break; case 3: if (str[0] != 'e') break; switch (str[2]) { case 'x': switch (str[1]){ case 'a':return eax; case 'b':return ebx; case 'c':return ecx; case 'd':return edx; }break; case 'p': switch (str[1]){ case 'b':return ebp; case 's':return esp; }break; case 'i': switch (str[1]){ case 'd':return edi; case 's':return esi; }break; } break; } throw Error("stringToRegister: not string match a register"); }
[ "523416700@qq.com" ]
523416700@qq.com
85f7075fd2d19ee1be095dedb5d0de519dfe8521
f00687b9f8671496f417672aaf8ddffc2fa8060a
/uva/10048 - Audiophobia.cpp
d3cc7c2d47225cc738058f948cd95069ea2133b2
[]
no_license
kazi-nayeem/Programming-Problems-Solutions
29c338085f1025b2545ff66bdb0476ec4d7773c2
7ee29a4e06e9841388389be5566db34fbdda8f7c
refs/heads/master
2023-02-05T15:06:50.355903
2020-12-30T10:19:54
2020-12-30T10:19:54
279,388,214
2
2
null
null
null
null
UTF-8
C++
false
false
1,632
cpp
#include<cstdio> #include<iostream> #include<vector> #include<algorithm> using namespace std; #define MX 105 struct edge{ int u, v, w; bool operator < (const edge &p) const { return w<p.w; } }; vector<edge> vc; int parent[MX]; int mst(const int a, const int b); int findpar(const int n); int main() { edge tem; int test = 0, c, s, q; while(scanf("%d %d %d", &c, &s, &q) == 3) { if(c == 0 && s == 0 && q == 0) break; if(test) putchar('\n'); vc.clear(); for(int i = 0; i < s; i++) { scanf("%d %d %d", &tem.u, &tem.v, &tem.w); vc.push_back(tem); } sort(vc.begin(), vc.end()); int a, b; printf("Case #%d\n", ++test); for(int i = 0; i < q; i++) { scanf("%d %d", &a, &b); int di = mst(a, b); if(di == -1) printf("no path\n"); else printf("%d\n", di); } } return 0; } int mst(const int a, const int b) { for(int i = 0; i < MX; i++) parent[i] = i; int u, v, st, en; int sz = vc.size(); for(int i = 0; i < sz; i++) { u = findpar(vc[i].u); v = findpar(vc[i].v); if(u != v) { parent[u] = v; st =findpar(a); en = findpar(b); if(st == en) return vc[i].w; } } return -1; } int findpar(const int n) { if(parent[n] == n) return n; return parent[n] = findpar(parent[n]); }
[ "masum.nayeem@gmail.com" ]
masum.nayeem@gmail.com
92e33baf9a8be8b562eac8b6d63d84b923a285d8
da1aa824deb8d7d7416151601e662629765780f0
/Seg3D/src/Core/Matlab/matlabfile.h
9b63248ca3983455dca1529fa7ab8b6ffe6d7088
[ "MIT" ]
permissive
viscenter/educe
69b5402782a4455af6d4009cb69f0d9a47042095
2dca76e7def3e0620896f155af64f6ba84163d77
refs/heads/master
2021-01-02T22:44:36.560170
2009-06-12T15:16:15
2009-06-12T15:16:15
5,413,435
1
0
null
null
null
null
UTF-8
C++
false
false
4,851
h
/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2004 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. */ // NOTE: This MatlabIO file is used in different projects as well. Please, do not // make it depend on other scirun code. This way it is easier to maintain matlabIO // code among different projects. Thank you. /* * FILE: matlabfile.h * AUTH: Jeroen G Stinstra * DATE: 16 MAY 2005 */ /* * CLASS DESCRIPTION * This class is an interface to a matfile and handles the importing and exporting * matlabarray objects. The latter represent the full complexity of a matlab array. * * MEMORY MODEL * The class maintains its own copies of the data. Each vector, string and other * data unit is copied. * Large quantities of data are shipped in and out as matlabarray objects. These * objects are handles to complex structures in memory and maintain their own data integrity. * When copying a matfiledata object only pointers are copied, however all information * for freeing the object is stored inside and no memory losses should occur. * * ERROR HANDLING * All errors are reported as exceptions described in the matfilebase class. * Errors of external c library functions are caught and forwarded as exceptions. * * COPYING/ASSIGNMENT * Do not copy the object, this will lead to errors (NEED TO FIX THIS) * * RESOURCE ALLOCATION * Files are closed by calling close() or by destroying the object * */ #ifndef JGS_MATLABIO_MATLABFILE_H #define JGS_MATLABIO_MATLABFILE_H 1 #include "matfilebase.h" #include "matfile.h" #include "matfiledata.h" #include "matlabarray.h" #include <vector> #include <string> #include <iostream> #include "share.h" namespace MatlabIO { class SCISHARE matlabfile : public matfile { private: // matrixaddress is a vector of offsets // where the different matrices are stored // matrixname is a vector of the same length // storing the name of these matrices // NOTE: These fields are only available for // read access std::vector<int> matrixaddress_; std::vector<std::string> matrixname_; private: void importmatlabarray(matlabarray& ma,int mode); void exportmatlabarray(matlabarray& ma); mitype converttype(mxtype type); mxtype convertclass(mlclass mclass,mitype type); public: // constructors matlabfile(); matlabfile(std::string filename,std::string accessmode); virtual ~matlabfile(); // open and close a file (not needed at this point) // access mode is "r" or "w", a combination is not supported yet void open(std::string filename,std::string accessmode); void close(); // functions for scanning through the contents of a matlab file // getnummatlabarrays() gets the number of arrays stored in the file // and getmatlabarrayinfo() loads the matrix header but not the data // inside, it does read the headers of sub matrices, getmatlabarrayshortinfo() // on the other hand only reads the header of the top level matlabarray // (no submatrices are read) int getnummatlabarrays(); matlabarray getmatlabarrayshortinfo(int matrixindex); matlabarray getmatlabarrayshortinfo(std::string name); matlabarray getmatlabarrayinfo(int matrixindex); matlabarray getmatlabarrayinfo(std::string name); // function reading matrices matlabarray getmatlabarray(int matrixindex); matlabarray getmatlabarray(std::string name); // function writing the matrices // A matrix name needs to be added. This the name of the object // as it appears in matlab void putmatlabarray(matlabarray& ma,std::string matrixname); }; } // end namespace MatlabIO #endif
[ "ryan.baumann@gmail.com" ]
ryan.baumann@gmail.com
766f1de8ee4b150597538943c883b8af252bb963
78c559b1c3c0366cec77bb043305fb4b0fd1d639
/src/scenes/CameraScene.h
bd22e310d5657823ad3fa6853d66466ef5d637ff
[ "MIT" ]
permissive
kyle-piddington/SharkProject
1039e780d42d0fd27ce4332d8f02a6462393a567
d34d27cd7a7fbd385dd9edccd69b2d2257be70f2
refs/heads/master
2020-05-30T08:39:26.792611
2015-11-18T16:58:39
2015-11-18T16:58:39
44,460,255
0
0
null
null
null
null
UTF-8
C++
false
false
460
h
#ifndef __CAMERA_SCENE__ #define __CAMERA_SCENE__ #include "Camera.h" #include "EmptyScene.h" #include "Keyboard.h" #include "Mouse.h" #include "TabletopCamera.h" class CameraScene:public EmptyScene { public: CameraScene(Context * ctx); virtual ~CameraScene(); virtual void update(); TabletopCamera camera; float Cam_Speed = 1.0/10.0; float Cam_Rot_Speed = M_PI; private: void handleCameraInput(); float pitch; float yaw; }; #endif
[ "kpiddy@gmail.com" ]
kpiddy@gmail.com
38eed7e323f232429680cbb7900c0017e1092395
920b66d220bdcd6c65a0e80a1c3cb9a7e042685a
/cruise/navigation_tutorials/simple_navigation_goals_tutorial/src/get_center_position (复件).cpp
4b5ac3913ea8a937405f672ac87d5f0f2bea457a
[]
no_license
NKU-ZiXuan/Graduation_Project
34795b1f9202380a2feac347ac290425bf05e763
d2bf757084f274677e953ea20c8f9fd5b824698d
refs/heads/master
2022-07-27T08:00:27.497738
2020-05-23T04:02:13
2020-05-23T04:02:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,446
cpp
#include <ros/ros.h> #include <geometry_msgs/Point.h> #include <mavros_msgs/UavState.h> #include <ref_generation/ReferenceTarget.h> #include <uav_state/UavStatePull.h> #include<cmath> #include<stdio.h> static int val=1; float target_xx=0, target_yy=0, target_zz=0, target_cc=0; ros::Publisher target_pub_; ros::Publisher turtlebot1_target_pub_; ros::Publisher turtlebot2_target_pub_; ros::Publisher turtlebot3_target_pub_; ros::Publisher turtlebot4_target_pub_; ros::Subscriber get_center_point_sub; ros::ServiceClient pull_state_client_; mavros_msgs::UavState m_uavstate_; //center_point_sub_ = it_.subscribe("/camera/image_color", 10, &ImageProc::imgCallback,this); void get_uavstate() { uav_state::UavStatePull srv; if(pull_state_client_.call(srv)) { m_uavstate_ = srv.response.uavstate; } } void get_center_point_cb( const geometry_msgs::Point::ConstPtr& center) { float cam_x, cam_y, cam_z=0, center_x, center_y; double cam_c; float target_x, target_y, target_z, target_c; get_uavstate(); center_x = center->x;//continue when data come center_y = center->y; while (val<=100) { cam_x = center_x*(m_uavstate_.z_pos-0.35)/480; cam_y = center_y*(m_uavstate_.z_pos-0.35)/480; //cam_z = 0; printf("Object center offset is (%f,%f) \n",cam_x,cam_y); /* cam_x = abs(2*center_x*atan(2/3)*(m_uavstate_.z_pos-0.35)/640); cam_y = abs(2*center_y*atan(1/2)*(m_uavstate_.z_pos-0.35)/480);/ */ target_x = m_uavstate_.x_pos + cam_x; target_y = m_uavstate_.y_pos + cam_y; //target_z = m_uavstate_.z_pos + cam_z; cam_c = atan2(cam_y, cam_x) ; // radian for camera angle target_c = m_uavstate_.c_pos + cam_c; target_xx += target_x; target_yy += target_y; //target_zz += target_z; target_cc += target_c; //printf("target_zz is %f \n",target_zz); ++val; break; } if (val==101) { // transform target position in local ENU frame ref_generation::ReferenceTarget target; geometry_msgs::Point turtlebot_target; target.x = target_xx/100; target.y = target_yy/100; turtlebot_target.x = target_xx/100; turtlebot_target.y = target_yy/100; //target.z = target_zz/100; target.z = m_uavstate_.z_pos + cam_z; target.c = target_cc/100; //printf("target.z is %f \n",target.z); // publish to off_mission target_pub_.publish(target); float target_a,target_b,target_c,target_d,min; // target_a = sqrt((target.x-m1)*(target.x-m1) + (target.y-n1)*(target.y-n1)); target_b = sqrt((target.x-m2)*(target.x-m2) + (target.y-n2)*(target.y-n2)); target_c = sqrt((target.x-m3)*(target.x-m3) + (target.y-n3)*(target.y-n3)); target_d = sqrt((target.x-m4)*(target.x-m4) + (target.y-n4)*(target.y-n4)); min=target_a; if(min>target_b)min=target_b; if(min>target_c)min=target_c; if(min>target_d)min=target_d; if(min==target_a) { turtlebot1_target_pub_.publish(turtlebot_target); } if(min==target_b) { turtlebot2_target_pub_.publish(turtlebot_target); } if(min==target_c) { turtlebot3_target_pub_.publish(turtlebot_target); } if(min==target_d) { turtlebot4_target_pub_.publish(turtlebot_target); } } // transform target position in local ENU frame // ref_generation::ReferenceTarget target; // target.x = m_uavstate_.x_pos + cam_x; // target.y = m_uavstate_.y_pos + cam_y; // target.z = m_uavstate_.z_pos + cam_z; // double cam_c = atan2(cam_y, cam_x) ; // radian for camera angle // target.c = m_uavstate_.c_pos + cam_c; } int main(int argc, char **argv) { ros::init(argc, argv, "get_center_position"); ros::NodeHandle nh_; get_center_point_sub = nh_.subscribe<geometry_msgs::Point>("center_point", 1000, &get_center_point_cb); target_pub_ = nh_.advertise<ref_generation::ReferenceTarget>("online_target", 100); turtlebot1_target_pub_ = nh_.advertise<geometry_msgs::Point>("nearest_turtlebot1", 100); turtlebot2_target_pub_ = nh_.advertise<geometry_msgs::Point>("nearest_turtlebot2", 100); turtlebot3_target_pub_ = nh_.advertise<geometry_msgs::Point>("nearest_turtlebot3", 100); turtlebot4_target_pub_ = nh_.advertise<geometry_msgs::Point>("nearest_turtlebot4", 100); pull_state_client_ = nh_.serviceClient<uav_state::UavStatePull>("update_uavstate"); ros::spin(); return 0; }
[ "gjxslwz@gmail.com" ]
gjxslwz@gmail.com
9514b1b8860715e2851fe02bae58305856a2a670
477c8309420eb102b8073ce067d8df0afc5a79b1
/Plugins/SQToolkit/pqSQVolumeSource.h
2c2cb418ea07694d51ea5fa372dc38a326f0fdbf
[ "LicenseRef-scancode-paraview-1.2" ]
permissive
aashish24/paraview-climate-3.11.1
e0058124e9492b7adfcb70fa2a8c96419297fbe6
c8ea429f56c10059dfa4450238b8f5bac3208d3a
refs/heads/uvcdat-master
2021-07-03T11:16:20.129505
2013-05-10T13:14:30
2013-05-10T13:14:30
4,238,077
1
0
NOASSERTION
2020-10-12T21:28:23
2012-05-06T02:32:44
C++
UTF-8
C++
false
false
2,417
h
/* ____ _ __ ____ __ ____ / __/___(_) / ___ ____/ __ \__ _____ ___ / /_ / _/__ ____ _\ \/ __/ / _ \/ -_) __/ /_/ / // / -_|_-</ __/ _/ // _ \/ __/ /___/\__/_/_.__/\__/_/ \___\_\_,_/\__/___/\__/ /___/_//_/\__(_) Copyright 2008 SciberQuest Inc. */ #ifndef __pqSQVolumeSource_h #define __pqSQVolumeSource_h #include "pqNamedObjectPanel.h" //#include "pqComponentsExport.h" //#include <vtkstd/vector> #include "ui_pqSQVolumeSourceForm.h" using Ui::pqSQVolumeSourceForm; // Define the following to enable debug io // #define pqSQVolumeSourceDEBUG class pqProxy; class vtkEventQtSlotConnect; class QWidget; class pqSQVolumeSource : public pqNamedObjectPanel { Q_OBJECT public: pqSQVolumeSource(pqProxy* proxy, QWidget* p=NULL); ~pqSQVolumeSource(); // Description: // Set/Get values to/from the UI. void GetOrigin(double *o); void SetOrigin(double *o); void GetPoint1(double *p1); void SetPoint1(double *p1); void GetPoint2(double *p2); void SetPoint2(double *p2); void GetPoint3(double *p3); void SetPoint3(double *p3); void GetResolution(int *res); void SetResolution(int *res); void GetSpacing(double *dx); void SetSpacing(double *dx); // Description: // dispatch context menu events. void contextMenuEvent(QContextMenuEvent *event); protected slots: // Description: // Transfer configuration to and from the clip board. void CopyConfiguration(); void PasteConfiguration(); // Description: // read/write configuration from disk. void loadConfiguration(); void saveConfiguration(); // Description: // check if cooridnates produce a good volume. int ValidateCoordinates(); // Description: // calculate plane's dimensions for display. Retun 0 in case // an error occured. void DimensionsModified(); // Description: // update and display computed values, and enforce aspect ratio lock. void SpacingModified(); void ResolutionModified(); // Description: // Update the UI with values from the server. void PullServerConfig(); void PushServerConfig(); // Description: // This is where we have to communicate our state to the server. virtual void accept(); // Description: // Pull config from proxy virtual void reset(); private: double Dims[3]; double Dx[3]; int Nx[3]; private: pqSQVolumeSourceForm *Form; vtkEventQtSlotConnect *VTKConnect; }; #endif
[ "aashish.chaudhary@kitware.com" ]
aashish.chaudhary@kitware.com
bec41d091cc1e1b6d83debbe4d476a649ba1004a
521504174d832b66a70692e51c80ed1c65004c2d
/nvpr_examples/skia/src/gpu/gl/debug/GrFBBindableObj.cpp
ea27f4e2a01a319a81e1b5fd95d8f1a58ec12804
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause" ]
permissive
csevenr/NVprSDK
5d3909b74d890fd0c43ddcdb82e1472fade44598
509b75299ccc5a974ce3a98e60b47ea520b0126b
refs/heads/master
2020-09-08T14:20:35.134543
2016-07-07T17:57:33
2016-07-07T17:57:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
182
cpp
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrFBBindableObj.h"
[ "markkilgard@gmail.com" ]
markkilgard@gmail.com
2abc659fdba86e61314a02401bb7502993cb4914
7045bb4f95ada6e1669a3cd9520681b7e548c319
/Meijer/Platform-Core-Patch/Remote Console Manager/src/remote-console-manager/actions/RemoteDataCommand.h
a81dc752ca2a7e3a132a90860b059f9ac347b042
[]
no_license
co185057/MeijerTESTSVN
0ffe207db43c8e881fdbad66c1c058e25fe451f5
3a3df97b2decc1a04e6efe7c8ab74eff5409f39f
refs/heads/master
2023-05-30T00:19:36.524059
2021-06-10T08:41:31
2021-06-10T08:41:31
375,576,064
0
0
null
null
null
null
UTF-8
C++
false
false
2,298
h
#pragma once // $Header: /Integration_Customer/Meijer/CURRENT_DEV/Platform-Core-Patch/remote console manager/src/remote-console-manager/actions/RemoteDataCommand.h 3 10/21/08 4:09p Sm133076 $ /* * @(#)RemoteDataCommand.h $Revision: 3 $ $Date: 10/21/08 4:09p $ * * Copyright 2005 by NCR Corporation, * * All rights reserved. * * This software is the confidential and proprietary information * of NCR Corporation. ("Confidential Information"). You * shall not disclose such Confidential Information and shall use * it only in accordance with the terms of the license agreement * you entered into with NCR. */ /* * $Log: /Integration_Customer/Meijer/CURRENT_DEV/Platform-Core-Patch/remote console manager/src/remote-console-manager/actions/RemoteDataCommand.h $ * * 3 10/21/08 4:09p Sm133076 * Patch G Migration * * 7 10/20/06 9:50a Tn185011 * Roll back to 244 * * 4 4/12/05 2:54p Dm185016 * Changes for AllLaneStatusSummary * * 2 2/28/05 4:40p Dm185016 * lint * * 1 2/14/05 7:03p Dm185016 * Release Exclusive Access Event support */ #include "rcmapi.h" #include "SMConstants.h" #include "Createable.h" #include "KeyValueHandler.h" #include "RCMActionBase.h" #include "Pool.h" #include "Message.h" using namespace STATE_MACHINE_NAMESPACE; namespace fastlane { class RCMANAGER_API CRemoteDataCommand : virtual public CRCMActionBase , public CCreateable<CRemoteDataCommand, IAction> // , public CPool<CRemoteDataCommand> { public: CRemoteDataCommand(); virtual ~CRemoteDataCommand(); virtual HRESULT Execute(bool *, IMessage &); protected: HRESULT ParseOperands(); virtual HRESULT ParseAuxData(const _TCHAR *pszRemoteData); virtual const _TCHAR * GetOperation(); // This section contains the handlers for the various K,V pairs private: DECLARE_KV_HANDLER_CLASS_BEGIN(RDCParms) DECLARE_KV_CSTRING(AuxData) DECLARE_KV_CSTRING(Operation) DECLARE_KV_CSTRING(LookupTableName) DECLARE_KV_HANDLER_CLASS_END private: // hide copy and assignment CRemoteDataCommand(const CRemoteDataCommand&); CRemoteDataCommand& operator = (const CRemoteDataCommand &); RDCParms m_parms; }; }
[ "co185057@ncr.com" ]
co185057@ncr.com
f645a657e8478c230b84fe24d7cae17d287e6cb0
86a70b4a86a9751ea19c248c047c22546b743cc5
/src/algo/blast/blastinput/blastn_args.cpp
15212180f13be2e016ca377512e810bd5e9c98d9
[]
no_license
mkuhn/blast-matrix
05b9b8a274b5d8eaa220ec89df6741ffbc8c62d6
915ba9ac3a81549c53b314a059188c937993efd8
refs/heads/master
2020-12-22T10:51:47.040589
2012-10-24T09:14:24
2012-10-24T09:14:24
236,756,103
1
0
null
null
null
null
UTF-8
C++
false
false
4,522
cpp
/* $Id: blastn_args.cpp 170780 2009-09-16 18:25:06Z camacho $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Christiam Camacho * */ /** @file blastn_args.cpp * Implementation of the BLASTN command line arguments */ #ifndef SKIP_DOXYGEN_PROCESSING static char const rcsid[] = "$Id: blastn_args.cpp 170780 2009-09-16 18:25:06Z camacho $"; #endif #include <ncbi_pch.hpp> #include <algo/blast/blastinput/blastn_args.hpp> #include <algo/blast/api/disc_nucl_options.hpp> #include <algo/blast/api/blast_exception.hpp> #include <algo/blast/blastinput/blast_input_aux.hpp> #include <algo/blast/api/version.hpp> BEGIN_NCBI_SCOPE BEGIN_SCOPE(blast) USING_SCOPE(objects); CBlastnAppArgs::CBlastnAppArgs() { CRef<IBlastCmdLineArgs> arg; static const string kProgram("blastn"); arg.Reset(new CProgramDescriptionArgs(kProgram, "Nucleotide-Nucleotide BLAST")); const bool kQueryIsProtein = false; m_Args.push_back(arg); m_ClientId = kProgram + " " + CBlastVersion().Print(); static const string kDefaultTask = "megablast"; SetTask(kDefaultTask); set<string> tasks (CBlastOptionsFactory::GetTasks(CBlastOptionsFactory::eNuclNucl)); arg.Reset(new CTaskCmdLineArgs(tasks, kDefaultTask)); m_Args.push_back(arg); m_BlastDbArgs.Reset(new CBlastDatabaseArgs); m_BlastDbArgs->SetDatabaseMaskingSupport(true); arg.Reset(m_BlastDbArgs); m_Args.push_back(arg); m_StdCmdLineArgs.Reset(new CStdCmdLineArgs); arg.Reset(m_StdCmdLineArgs); m_Args.push_back(arg); arg.Reset(new CGenericSearchArgs(kQueryIsProtein, false, true)); m_Args.push_back(arg); arg.Reset(new CNuclArgs); m_Args.push_back(arg); arg.Reset(new CDiscontiguousMegablastArgs); m_Args.push_back(arg); arg.Reset(new CFilteringArgs(kQueryIsProtein)); m_Args.push_back(arg); arg.Reset(new CGappedArgs); m_Args.push_back(arg); m_HspFilteringArgs.Reset(new CHspFilteringArgs); arg.Reset(m_HspFilteringArgs); m_Args.push_back(arg); arg.Reset(new CWindowSizeArg); m_Args.push_back(arg); arg.Reset(new COffDiagonalRangeArg); m_Args.push_back(arg); arg.Reset(new CMbIndexArgs); m_Args.push_back(arg); m_QueryOptsArgs.Reset(new CQueryOptionsArgs(kQueryIsProtein)); arg.Reset(m_QueryOptsArgs); m_Args.push_back(arg); m_FormattingArgs.Reset(new CFormattingArgs); arg.Reset(m_FormattingArgs); m_Args.push_back(arg); m_MTArgs.Reset(new CMTArgs); arg.Reset(m_MTArgs); m_Args.push_back(arg); m_RemoteArgs.Reset(new CRemoteArgs); arg.Reset(m_RemoteArgs); m_Args.push_back(arg); m_DebugArgs.Reset(new CDebugArgs); arg.Reset(m_DebugArgs); m_Args.push_back(arg); } CRef<CBlastOptionsHandle> CBlastnAppArgs::x_CreateOptionsHandle(CBlastOptions::EAPILocality locality, const CArgs& args) { CRef<CBlastOptionsHandle> retval; SetTask(args[kTask].AsString()); retval.Reset(CBlastOptionsFactory::CreateTask(GetTask(), locality)); _ASSERT(retval.NotEmpty()); return retval; } int CBlastnAppArgs::GetQueryBatchSize() const { return blast::GetQueryBatchSize(ProgramNameToEnum(GetTask()), m_IsUngapped); } END_SCOPE(blast) END_NCBI_SCOPE
[ "mkuhn@localhost" ]
mkuhn@localhost
e17ced9925f33babcd9549336af9dc87fdf8c20c
30b7ffd17845db982883a91ce8d04551281658c4
/BAPS/Mo/A.cpp
55ff2a925789fac3754ea659db1dded404aa51d8
[]
no_license
shas9/codehub
95418765b602b52edb0d48a473ad7e7a798f76e5
bda856bf6ca0f3a1d59980895cfab82f690c75a2
refs/heads/master
2023-06-21T01:09:34.275708
2021-07-26T14:54:03
2021-07-26T14:54:03
389,404,954
0
0
null
null
null
null
UTF-8
C++
false
false
2,246
cpp
#include <bits/stdc++.h>` #define slld(longvalue) scanf("%lld", &longvalue) #define plld(longvalue) printf("%lld\n", longvalue) #define slf(longvalue) scanf("%lf", &longvalue) #define plf(longvalue) printf("%lf\n", longvalue) #define sc(letter) scanf("%c", &letter) #define pc(letter) printf("%c", letter) #define ss(name) scanf("%s", name) #define ps(name) printf("%s", name) #define pnew printf("\n") #define ll long long #define printcase(indexing,ans) printf("Case %lld: %lld\n", indexing, ans) #define pb(x) push_back(x) #define bug printf("BUG\n") #define mxlld LLONG_MAX #define mnlld -LLONG_MAX #define mxd 2e8 #define mnd -2e8 #define pi 3.14159265359 #define mod 1000000009 #define maxn 200005 using namespace std; struct node { ll l, r, id; }; node que[maxn]; ll arr[maxn]; ll freq[maxn * 6]; ll cnt[maxn]; const int ssq = 450; bool comp(node a, node b) { ll x = a.l / ssq; ll y = b.l / ssq; if(x == y) { return a.r < b.r; } else { return a.l < b.l; } } ll ans; void add(ll x) { ll c = freq[x]; ans += x * (c + c + 1); freq[x]++; } void rem(ll x) { ll c = freq[x]; ans -= x * (c + c - 1); freq[x]--; } int main() { ll i, j, k, l, m, n, o; ll testcase; ll input, flag, tag, q; // freopen("in.txt", "r", stdin); slld(n); slld(q); for(i = 1; i <= n; i++) slld(arr[i]); for(i = 0; i < q; i++) { slld(j); slld(k); que[i].l = j; que[i].r = k; que[i].id = i + 1; } sort(que, que + q,comp); ll r = 0; l = 1; ans = 0; for(i = 0; i < q; i++) { //cout << que[i].l << " : " << que[i].r << endl; while(l > que[i].l) add(arr[--l]); while(r < que[i].r) add(arr[++r]); while(l < que[i].l) rem(arr[l++]); while(r > que[i].r) rem(arr[r--]); //cout << ans << endl; cnt[que[i].id] = ans; //cout << que[i].id << " " << ans << endl; } //sort(que.begin(),que.end(),comp2); for(i = 1; i <= q; i++) { plld(cnt[i]); } }
[ "shahwathasnaine@gmail.com" ]
shahwathasnaine@gmail.com
3e5ebec6633e2921b75e6fee7f277578d447cbbd
ce4f6ee8dbf2487593a341abf4755c662ef3c983
/src/game_defs.cpp
f21f111faf1f27764c22fcb590d5fb7218c589fb
[]
no_license
tksuoran/PowerBattle
38fa2f89cd9c624348ff38b408fe4a0d72610ca8
7c8de49a261e15554309623b3ef1d060c9bbda69
refs/heads/master
2022-10-29T18:59:06.197509
2018-09-15T15:43:52
2020-06-22T08:52:12
274,083,775
1
0
null
null
null
null
UTF-8
C++
false
false
16,190
cpp
#include <nlohmann/json.hpp> #include "game.hpp" #include "file_util.hpp" #include "globals.hpp" using json = nlohmann::json; #if 0 struct OriginalTerrainType { std::string name; uint8_t Color {0U}; uint8_t MAllow {0U}; uint8_t MCost {0U}; uint8_t Threat {0U}; uint8_t ADamage {0U}; uint8_t DBonus {0U}; uint8_t CSize {0U}; uint8_t Strength{0U}; uint8_t Mult {0U}; uint8_t VChg {0U}; uint8_t HNum {0U}; }; void Game::load_terrain_defs() { std::vector<unsigned char> def_data = read_file("data/definitions/terrain_types.def"); constexpr size_t hex_types = 55U; constexpr size_t load_string_length = 12U; size_t pos = 0U; std::vector<OriginalTerrainType> original_terrain_types; // +1 because original data has one too many records for (size_t i = 0U; i < hex_types + 1U; ++i) { OriginalTerrainType type; type.Color = def_data[pos++]; type.MAllow = def_data[pos++]; type.MCost = def_data[pos++]; type.Threat = def_data[pos++]; type.ADamage = def_data[pos++]; type.DBonus = def_data[pos++]; type.CSize = def_data[pos++]; type.Strength = def_data[pos++]; type.Mult = def_data[pos++]; type.VChg = def_data[pos++]; type.HNum = def_data[pos++]; original_terrain_types.push_back(type); // printf("\nTerrain %d:\n", i); // printf("Color = %u\n", type.Color); // printf("MAllow = %u\n", type.MAllow); // printf("MCost = %u\n", type.MCost); // printf("Threat = %u\n", type.Threat); // printf("ADamage = %u\n", type.ADamage); // printf("DBonus = %u\n", type.DBonus); // printf("CSize = %u\n", type.CSize); // printf("Strength = %u\n", type.Strength); // printf("Mult = %u\n", type.Mult); // printf("VChg = %u\n", type.VChg); // printf("HNum = %u\n", type.HNum); } // +1 because original data has one too many records for (size_t i = 0U; i < hex_types + 1U; ++i) { std::string value = get_string(def_data, pos, load_string_length); // remove trailing spaces value.erase(std::find_if(value.rbegin(), value.rend(), std::bind1st(std::not_equal_to<char>(), ' ')).base(), value.end()); pos += load_string_length; // printf("Terrain %d Name = %s\n", i, name.c_str()); if (i < original_terrain_types.size()) { original_terrain_types[i].name = value; } } constexpr size_t def_count = 11U; for (size_t i = 0U; i < def_count; ++i) { std::string name = get_string(def_data, pos, load_string_length); pos += load_string_length; // printf("Field %d Name = %s\n", i, name.c_str()); } json j; auto j_terrain_types = json::array(); for (auto &ot : original_terrain_types) { json t; t["Name" ] = ot.name; t["Color" ] = ot.Color; t["MAllow" ] = ot.MAllow; t["MCost" ] = ot.MCost; t["Threat" ] = ot.Threat; t["ADamage" ] = ot.ADamage; t["DBonus" ] = ot.DBonus; t["CSize" ] = ot.CSize; t["Strength"] = ot.Strength; t["Mult" ] = ot.Mult; t["VChg" ] = ot.VChg; t["HNum" ] = ot.HNum; j_terrain_types.push_back(t); } j["terrain_types"] = j_terrain_types; std::string json_string = j.dump(); write_file("data/definitions/terrain_types.json", json_string); } #else void Game::load_terrain_defs() { std::string def_data = read_file_string("data/definitions/terrain_types.json"); auto j = json::parse(def_data); auto terrain_types = j["terrain_types"]; m_terrain_types.resize(terrain_types.size()); size_t index = 0U; for (auto t : terrain_types) { m_terrain_types[index].name = t["Name"]; } //constexpr size_t hex_types = 55U; } #endif #if 0 struct OriginalUnitType { std::string name; uint8_t MType {0U}; // Movement Type Bits uint8_t Moves[2]{0U, 0U}; // Movement Points per Turn uint8_t TDef {0U}; // Threat Defence uint8_t Fuel {0U}; // Fuel Tank Size uint8_t Refuel {0U}; // Refuel Points per Turn uint8_t CType {0U}; // Cargo Type Bits uint8_t Cargo {0U}; // Cargo Space uint8_t Loading {0U}; // Loadings/Unloadings per Turn uint8_t Tech {0U}; // Required Techlevel for Production uint8_t PTime {0U}; // Production Time uint8_t Cost {0U}; // Reserved uint8_t Hits {0U}; // Maximum HitPoints uint8_t Repair {0U}; // Repair Points per Turn uint8_t Levels {0U}; // Reserved uint8_t BType {0U}; // Battle Type # uint8_t Attack [4]{0U, 0U, 0U, 0U}; // Attack Points against BattleTypes uint8_t Defence[4]{0U, 0U, 0U, 0U}; // Defence - " - uint8_t LgtGndMod; // Light Ground Modifier uint8_t Range[2]{0U, 0U}; // Artillery Attack Range uint8_t RAttack {0U}; // Ranged Attack Modifier uint8_t Ammo {0U}; // Ammunitation Storage uint8_t Shots {0U}; // Artillery Attacks per Turn uint8_t LAtt {0U}; // Attack LevelModifier uint8_t LDef {0U}; // Defence LevelModifier uint8_t CAttack {0U}; // City Attack Modifier uint8_t Vision[2]{0U, 0U}; // Vision Range uint8_t VFrom [2]{0U, 0U}; // Visible From -Range uint8_t LUI {0U}; // Leveled Unit Icon # uint8_t fff {0U}; // Reserved uint8_t ggg {0U}; // Reserved uint8_t hhh {0U}; // Reserved uint8_t Sfx {0U}; // Sound Effect # uint8_t Frequ {0U}; // Sound Effect Frequency uint8_t Specials{0U}; // Special Abilities uint8_t Undefd {0U}; // Reserved uint8_t L {0U}; // Reserved }; void Game::load_unit_defs() { std::vector<unsigned char> def_data = read_file("data/definitions/unit_types.def"); constexpr size_t types = 42U; constexpr size_t load_string_length = 12U; size_t pos = 0U; std::vector<OriginalUnitType> original_unit_types; for (size_t i = 0U; i < types + 1U; ++i) { OriginalUnitType type; type.MType = def_data[pos++]; // Movement Type Bits type.Moves[0] = def_data[pos++]; // Movement Points per Turn type.Moves[1] = def_data[pos++]; // Movement Points per Turn type.TDef = def_data[pos++]; // Threat Defence type.Fuel = def_data[pos++]; // Fuel Tank Size type.Refuel = def_data[pos++]; // Refuel Points per Turn type.CType = def_data[pos++]; // Cargo Type Bits type.Cargo = def_data[pos++]; // Cargo Space type.Loading = def_data[pos++]; // Loadings/Unloadings per Turn type.Tech = def_data[pos++]; // Required Techlevel for Production type.PTime = def_data[pos++]; // Production Time type.Cost = def_data[pos++]; // Reserved type.Hits = def_data[pos++]; // Maximum HitPoints type.Repair = def_data[pos++]; // Repair Points per Turn type.Levels = def_data[pos++]; // Reserved type.BType = def_data[pos++]; // Battle Type # type.Attack[0] = def_data[pos++]; // Attack Points against BattleTypes type.Attack[1] = def_data[pos++]; // Attack Points against BattleTypes type.Attack[2] = def_data[pos++]; // Attack Points against BattleTypes type.Attack[3] = def_data[pos++]; // Attack Points against BattleTypes type.Defence[0] = def_data[pos++]; // Defence - " - type.Defence[1] = def_data[pos++]; // Defence - " - type.Defence[2] = def_data[pos++]; // Defence - " - type.Defence[3] = def_data[pos++]; // Defence - " - type.LgtGndMod = def_data[pos++]; // Light Ground Modifier type.Range[0] = def_data[pos++]; // Artillery Attack Range type.Range[1] = def_data[pos++]; // Artillery Attack Range type.RAttack = def_data[pos++]; // Ranged Attack Modifier type.Ammo = def_data[pos++]; // Ammunitation Storage type.Shots = def_data[pos++]; // Artillery Attacks per Turn type.LAtt = def_data[pos++]; // Attack LevelModifier type.LDef = def_data[pos++]; // Defence LevelModifier type.CAttack = def_data[pos++]; // City Attack Modifier type.Vision[0] = def_data[pos++]; // Vision Range type.Vision[1] = def_data[pos++]; // Vision Range type.VFrom[0] = def_data[pos++]; // Visible From -Range type.VFrom[1] = def_data[pos++]; // Visible From -Range type.LUI = def_data[pos++]; // Leveled Unit Icon # type.fff = def_data[pos++]; // Reserved type.ggg = def_data[pos++]; // Reserved type.hhh = def_data[pos++]; // Reserved type.Sfx = def_data[pos++]; // Sound Effect # type.Frequ = def_data[pos++]; // Sound Effect Frequency type.Specials = def_data[pos++]; // Special Abilities type.Undefd = def_data[pos++]; // Reserved type.L = def_data[pos++]; // Reserved original_unit_types.push_back(type); // printf("\nUnit type %d:\n", i); // printf("MType = %u\n", type.MType); // printf("Moves[0] = %u\n", type.Moves[0]); // printf("Moves[1] = %u\n", type.Moves[1]); // printf("TDef = %u\n", type.TDef); // printf("Fuel = %u\n", type.Fuel); // printf("Refuel = %u\n", type.Refuel); // printf("CType = %u\n", type.CType); // printf("Cargo = %u\n", type.Cargo); // printf("Loading = %u\n", type.Loading); // printf("Tech = %u\n", type.Tech); // printf("PTime = %u\n", type.PTime); // printf("Cost = %u\n", type.Cost); // printf("Hits = %u\n", type.Hits); // printf("Repair = %u\n", type.Repair); // printf("Levels = %u\n", type.Levels); // printf("BType = %u\n", type.BType); // printf("Attack[0] = %u\n", type.Attack[0]); // printf("Attack[1] = %u\n", type.Attack[1]); // printf("Attack[2] = %u\n", type.Attack[2]); // printf("Attack[3] = %u\n", type.Attack[3]); // printf("Defence[0] = %u\n", type.Defence[0]); // printf("Defence[1] = %u\n", type.Defence[1]); // printf("Defence[2] = %u\n", type.Defence[2]); // printf("Defence[3] = %u\n", type.Defence[3]); // printf("LgtGndMod = %u\n", type.LgtGndMod); // printf("Range[0] = %u\n", type.Range[0]); // printf("Range[1] = %u\n", type.Range[1]); // printf("RAttack = %u\n", type.RAttack); // printf("Ammo = %u\n", type.Ammo); // printf("Shots = %u\n", type.Shots); // printf("LAtt = %u\n", type.LAtt); // printf("LDef = %u\n", type.LDef); // printf("CAttack = %u\n", type.CAttack); // printf("Vision[0] = %u\n", type.Vision[0]); // printf("Vision[1] = %u\n", type.Vision[1]); // printf("VFrom[0] = %u\n", type.VFrom[0]); // printf("VFrom[1] = %u\n", type.VFrom[1]); // printf("LUI = %u\n", type.LUI); // printf("fff = %u\n", type.fff); // printf("ggg = %u\n", type.ggg); // printf("hhh = %u\n", type.hhh); // printf("Sfx = %u\n", type.Sfx); // printf("Frequ = %u\n", type.Frequ); // printf("Specials = %u\n", type.Specials); // printf("Undefd = %u\n", type.Undefd); // printf("L = %u\n", type.L); } for (size_t i = 0U; i < types + 1U; ++i) { std::string name = get_string(def_data, pos, load_string_length); pos += load_string_length; // printf("Unit %d Name = %s\n", i, name.c_str()); if (i < original_unit_types.size()) { original_unit_types[i].name = name; } } constexpr size_t def_count = 36U; for (size_t i = 0U; i < def_count; ++i) { std::string name = get_string(def_data, pos, load_string_length); pos += load_string_length; // printf("Field %d Name = %s\n", i, name.c_str()); } json j; auto j_unit_types = json::array(); for (auto &ot : original_unit_types) { json t; t["Name" ] = ot.name ; // Movement Type Bits t["MType" ] = ot.MType ; // Movement Type Bits t["Moves" ] = ot.Moves ; // Movement Points per Turn t["TDef" ] = ot.TDef ; // Threat Defence t["Fuel" ] = ot.Fuel ; // Fuel Tank Size t["Refuel" ] = ot.Refuel ; // Refuel Points per Turn t["CType" ] = ot.CType ; // Cargo Type Bits t["Cargo" ] = ot.Cargo ; // Cargo Space t["Loading" ] = ot.Loading ; // Loadings/Unloadings per Turn t["Tech" ] = ot.Tech ; // Required Techlevel for Production t["PTime" ] = ot.PTime ; // Production Time t["Cost" ] = ot.Cost ; // Reserved t["Hits" ] = ot.Hits ; // Maximum HitPoints t["Repair" ] = ot.Repair ; // Repair Points per Turn t["Levels" ] = ot.Levels ; // Reserved t["BType" ] = ot.BType ; // Battle Type # t["Attack" ] = ot.Attack ; // Attack Points against BattleTypes t["Defence" ] = ot.Defence ; // Defence - " - t["LgtGndMod" ] = ot.LgtGndMod ; // Light Ground Modifier t["Range" ] = ot.Range ; // Artillery Attack Range t["RAttack" ] = ot.RAttack ; // Ranged Attack Modifier t["Ammo" ] = ot.Ammo ; // Ammunitation Storage t["Shots" ] = ot.Shots ; // Artillery Attacks per Turn t["LAtt" ] = ot.LAtt ; // Attack LevelModifier t["LDef" ] = ot.LDef ; // Defence LevelModifier t["CAttack" ] = ot.CAttack ; // City Attack Modifier t["Vision" ] = ot.Vision ; // Vision Range t["VFrom" ] = ot.VFrom ; // Visible From -Range t["LUI" ] = ot.LUI ; // Leveled Unit Icon # t["fff" ] = ot.fff ; // Reserved t["ggg" ] = ot.ggg ; // Reserved t["hhh" ] = ot.hhh ; // Reserved t["Sfx" ] = ot.Sfx ; // Sound Effect # t["Frequ" ] = ot.Frequ ; // Sound Effect Frequency t["Specials" ] = ot.Specials ; // Special Abilities t["Undefd" ] = ot.Undefd ; // Reserved t["L" ] = ot.L ; // Reserved j_unit_types.push_back(t); } j["unit_types"] = j_unit_types; std::string json_string = j.dump(); write_file("data/definitions/unit_types.json", json_string); } #else void Game::load_unit_defs() { std::string def_data = read_file_string("data/definitions/unit_types.json"); auto j = json::parse(def_data); auto unit_types = j["unit_types"]; m_unit_types.resize(unit_types.size()); size_t index = 0U; for (auto t : unit_types) { auto &u = m_unit_types[index]; u.move_type_bits = t["MType"]; u.moves[0] = t["Moves"][0]; u.moves[1] = t["Moves"][1]; u.fuel = t["Fuel"]; u.refuel_per_turn = t["Refuel"]; u.cargo_type = t["CType"]; u.load_count_per_turn = t["Loading"]; u.production_time = t["PTime"]; u.hit_points = t["Hits"]; u.repair_per_turn = t["Repair"]; u.levels = t["Levels"]; // reserved u.battle_type = t["BType"]; u.attack[0] = t["Attack"][0]; u.attack[1] = t["Attack"][1]; u.attack[2] = t["Attack"][2]; u.attack[3] = t["Attack"][3]; u.defence[0] = t["Defence"][0]; u.defence[1] = t["Defence"][1]; u.defence[2] = t["Defence"][2]; u.defence[3] = t["Defence"][3]; u.name = t["Name"]; } } #endif
[ "tksuoran@gmail.com" ]
tksuoran@gmail.com
b5a6d5d594e602beef78219f7716790a1c1c7322
42d981b9ac42ad12577865115228b3744aad6e6b
/bachelors/year2/semestre1/HomeTasks/3/3.cpp
b7c819c9d3fbaaf113da45026968c1d6eea9dd10
[]
no_license
Witalia008/university_courses
bcd7683ac3abbfb8f5474c0d114ed01cbc15eab6
8bdfb3b5f8ce44680dde530e4eabc28141013bd0
refs/heads/main
2023-04-11T11:16:59.444067
2021-04-01T01:31:02
2021-04-01T01:31:02
350,045,497
0
0
null
null
null
null
UTF-8
C++
false
false
1,692
cpp
#include <stdio.h> #include <cstdlib> #include <iostream> #include <iomanip> #include <string> using namespace std; string find_ribs(string bents) { string res; //each bent doubles number of edges, 2^n edges in the end and 2^n-1 ribs res.resize((1 << bents.size()) - 1, ' '); int pos = 0; for (int i = bents.size() - 1; i >= 0; --i) { char cur = bents[i] == 'F' ? 'K' : 'O'; //will go with step 2, 4, 8, ... for i = n - 1, n - 2, ... for (int j = pos; j < res.size(); j += (1 << (bents.size() - i))) { res[j] = cur; cur = cur == 'K' ? 'O' : 'K'; } //move initial position (0, 1, 3, 7, ...) pos += (1 << (bents.size() - i - 1)); } return res; } string find_bents(string ribs) { string res = ""; while ((1 << res.size()) < ribs.size()) res += ' '; int pos = 0; //restore each bent from last to first for (int i = res.size() - 1; i >= 0; --i) { res[i] = ribs[pos] == 'K' ? 'F' : 'B'; char cur = ribs[pos]; //go with steps 2, 4, 8 for i = n-1, n-2, ... for (int j = pos; j < ribs.size(); j += (1 << (res.size() - i))) { //should be eaqual to pattern (as in previous function) if (ribs[j] != cur) return "Impossible"; cur = cur == 'K' ? 'O' : 'K'; } //move init position (will be 0, 1, 3, ...) pos += (1 << (res.size() - i - 1)); } return res; } int main () { freopen("output.txt", "w", stdout); cout << find_ribs("FBF") << endl; cout << find_bents("KOOKKKO") << endl; return 0; }
[ "kojvitalij@gmail.com" ]
kojvitalij@gmail.com
430443005a135b7f9d3b609d7eaac9894e1216ad
39fe085377f3c7327e82d92dcb38083d039d8447
/core/sqf/inc/fs/adds/fsbuiltins.h
12d5fb45e3509f71b630a54afa632543d89afcf3
[ "Apache-2.0" ]
permissive
naveenmahadevuni/incubator-trafodion
0da8d4c7d13a47d3247f260b4e67618c0fae1539
ed24b19436530b2c214e4bf73280bc8e3f419669
refs/heads/master
2021-01-22T04:40:52.402291
2015-07-16T00:02:50
2015-07-16T00:02:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,743
h
// @@@ START COPYRIGHT @@@ // // (C) Copyright 1997-2014 Hewlett-Packard Development Company, L.P. // // 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. // // @@@ END COPYRIGHT @@@ //********************************************************************* //********************************************************************* #ifndef _FS_BUILTINS #define _FS_BUILTINS // // This header defines some builtins for which we currently have no prototypes and // which are required to compile // Symbols used for "oversized" value arguments // #ifndef _INC_TDM_CEXTDECS_H typedef int fat_16; typedef __int64 fat_32; // Values used to indicate omitted arguments // #ifdef OLD_OMIT_VALUES short const OMITSHORT = -292; unsigned short const OMITUNSIGNEDSHORT = 0xFEDC; int const OMITINT = -19136512; unsigned int const OMITUNSIGNEDINT = 0xFEDC0000; long const OMITLONG = -19136512; unsigned long const OMITUNSIGNEDLONG = 0xFEDC0000; __int64 const OMIT__INT64 = -82190693199511552; /*FEDC000000000000*/ #else short const OMITSHORT = -291; unsigned short const OMITUNSIGNEDSHORT = 0xFEDD; int const OMITINT = -19070975; fat_16 const OMITFAT_16 = -19070975; unsigned int const OMITUNSIGNEDINT = 0xFEDD0001; long const OMITLONG = -19070975; fat_32 const OMITFAT_32 = 0xfedd000000000001LL; unsigned long const OMITUNSIGNEDLONG = 0xFEDD0001; __int64 const OMIT__INT64 = 0xfedd000000000001LL; #endif // OLD_OMIT_VALUES // // We don't want the Rosetta versions of _arg_present and _optional // #ifdef _arg_present #undef _arg_present #endif #ifdef _optional #undef _optional #endif #define _optional(a,b) (a ? (b) : OMIT ) // Type names for argument substitution classes. NOTE: Be sure to include // a specialized instance of _arg_present for each of these. // #define arg_16 OptionalArgument<short> #define arg_32 OptionalArgument<int> #define arg_64 OptionalArgument<__int64> // Class ArgumentOmitted serves two pruposes: // 1) When the argument is an instance of ArgumentOmitted template class, causes the // "omitted" constructor to be invoked during the call...and the != overload operator // to be invokes by the _arg_present function. // 2) When the argument is a pre-define or user defined type, generates the specified value // to indicate that the argument is omitted during the call or when tested // by the _arg_present function. // class ArgumentOmitted { public: operator short() {return OMITSHORT;} operator short*() {return NULL;} operator int() {return OMITINT;} operator int*() {return NULL;} operator long() {return OMITLONG;} #ifndef NA_64BIT // dg64 - since __int64 is same as long, not necessary operator __int64() {return OMIT__INT64;} #endif operator __int64*() {return NULL;} // gps11-11 #ifdef NA_64BIT //operator _int_64*() {return NULL;} #endif #ifndef NA_64BIT // dg64 - since __int64 is same as long, not necessary operator long*() {return NULL;} #endif operator char*() {return NULL;} operator unsigned short() {return OMITUNSIGNEDSHORT;} operator unsigned short*() {return NULL;} operator unsigned int() {return OMITUNSIGNEDINT;} operator unsigned int*() {return NULL;} operator unsigned long() {return OMITUNSIGNEDLONG;} operator unsigned long*() {return NULL;} operator unsigned char*() {return NULL;} operator void*() {return NULL;} operator void**() {return NULL;} }; #ifndef _USERDEFINEDARGOMITTED_ // gps11-12 static ArgumentOmitted OMIT; #endif #endif //Single instantiation of ArgumentOmitted class // Template class OptionalArgument generates the optional argument classes to use // in the argument list in place of the corresponding pre-defined or user-defined "original" // types when there is not a suitable argument value to indicate omission. // template <class T> class OptionalArgument { inline int _arg_present(OptionalArgument<T>); public: OptionalArgument(T arg) : argument(arg), present(1) {} // Arg present constructor OptionalArgument(ArgumentOmitted) : argument(0), present(0) {} // Arg omitted constructor T operator=(T arg) {argument = arg; return argument;} // Assignment from original type operator T() {return argument;} // Conversion to original type private: T argument; int present; }; #ifdef ARG_PRESENT_OMIT // Instances used for pre-defined and user-defined types // Note: template function was removed to eliminate the unnecessary instances of // of pointers to user-defined classes and structures. These can be resolved // by implicit casts. // #define ORIGINAL_ARG_PRESENT(T,V) \ inline int _arg_present(T arg) { \ return (arg != V); \ } ORIGINAL_ARG_PRESENT(short, OMITSHORT) ORIGINAL_ARG_PRESENT(short*, NULL) ORIGINAL_ARG_PRESENT(int, OMITINT) ORIGINAL_ARG_PRESENT(int*, NULL) ORIGINAL_ARG_PRESENT(long, OMITLONG) ORIGINAL_ARG_PRESENT(long*, NULL) ORIGINAL_ARG_PRESENT(char*, NULL) ORIGINAL_ARG_PRESENT(unsigned short, OMITUNSIGNEDSHORT) ORIGINAL_ARG_PRESENT(unsigned short*, NULL) ORIGINAL_ARG_PRESENT(unsigned int, OMITUNSIGNEDINT) ORIGINAL_ARG_PRESENT(unsigned int*, NULL) ORIGINAL_ARG_PRESENT(unsigned long, OMITUNSIGNEDLONG) ORIGINAL_ARG_PRESENT(unsigned long*, NULL) ORIGINAL_ARG_PRESENT(unsigned char*, NULL) ORIGINAL_ARG_PRESENT(void*, NULL) ORIGINAL_ARG_PRESENT(void**, NULL) #endif // ARG_PRESENT_OMIT #ifdef ARG_PRESENT_REPLACEMENT //Instances used for OptionalArgument replacement classes // #define REPLACEMENT_ARG_PRESENT(T) \ inline int _arg_present(OptionalArgument<T> arg) { \ return arg.present; \ } REPLACEMENT_ARG_PRESENT(short) REPLACEMENT_ARG_PRESENT(int) REPLACEMENT_ARG_PRESENT(__int64) #endif // ARG_PRESENT_REPLACEMENT short _fixedtoascii ( fixed_0 qvalue, void *buffer, unsigned short maxdigits); short _asciitofixed ( void *buffer, unsigned short maxdigits, unsigned short *remainingdigits, fixed_0 qvaluein, fixed_0 *qvalueout, short *overflow); #endif
[ "steve.varnau@hp.com" ]
steve.varnau@hp.com
a02fb8ab38c4a377f5e8cda5fb1c4874d1868b45
786d1707ef4b4d9471b3307244d1baf82d49484b
/fluids/fluid_system.cpp
88c56894e4c23b9f4b8f89672c6e3f9dda1d8001
[]
no_license
ruchirgarg05/PorousSimulation
4e4902bddb83e282eb8509ca0e25eea2288018a3
5d3a56ae06df6778d1461e5a3a7a87a33662034e
refs/heads/master
2023-06-07T20:35:59.255880
2021-06-21T14:43:24
2021-06-21T14:43:24
null
0
0
null
null
null
null
GB18030
C++
false
false
96,649
cpp
#include <assert.h> #include <stdio.h> #include <conio.h> #include "gl_helper.h" #include <gl/glut.h> #include "camera3d.h" #include "common_defs.h" #include "mtime.h" #include "fluid_system.h" #include "fluid_system_host.cuh" #include <io.h> #include <direct.h> #include <iostream> #include <fstream> #include <iomanip> //计时 #include <Mmsystem.h> #pragma comment(lib, "Winmm.lib") double scaleP,scaleP3,scaledis; //double a[18],b[6]; Vector3DF volumes[10],softBoundary[2],emit[2]; Vector3DF cont,mb1,mb2; Vector4DF massRatio,densityRatio,viscRatio; Vector4DF permeabilityRatio; Vector4DF pressRatio; Vector4DF colorValue; //float cont[3]; int loadwhich; int example; float panr,omega; //case 3 float relax; float emitSpeed,emitangle,emitcircle,emitposx,emitposy,emitposz,emitfreq; //case 5 int upframe; // you know, the density will change in case 2 with upframe reached float change_den=2; float last_den=2; float test=1.0; void FluidSystem::TransferToCUDA () { CopyToCUDA ( (float*) mPos, (float*) mVel, (float*) mVelEval, (float*) mForce, mPressure, mDensity, mClusterCell, mGridNext, (char*) mClr); CopyMfToCUDA ( m_alpha, m_alpha_pre, m_pressure_modify, (float*) m_vel_phrel, m_restMass, m_restDensity, m_visc, (float*)m_velxcor, (float*)m_alphagrad); CopyToCUDA_Uproject((int*) MF_type); CopyToCUDA_elastic(elasticID, porosity_particle, (float*)signDistance); #ifdef NEW_BOUND CopyBoundToCUDA(mIsBound); #endif } void FluidSystem::TransferFromCUDA () { CopyFromCUDA ( (float*) mPos, (float*) mVel, (float*) mVelEval, (float*) mForce, mPressure, mDensity, mClusterCell, mGridNext, (char*) mClr, 1); CopyMfFromCUDA ( m_alpha, m_alpha_pre, m_pressure_modify, (float*) m_vel_phrel, m_restMass, m_restDensity, m_visc, (float*)m_velxcor, (float*)m_alphagrad, 1); CopyFromCUDA_Uproject(MF_type,m_beta); #ifdef NEW_BOUND CopyBoundFromCUDA(mIsBound); #endif } void FluidSystem::TransferFromCUDAForLoad () { CopyFromCUDA ( (float*) mPos, (float*) mVel, (float*) mVelEval, (float*) mForce, mPressure, mDensity, mClusterCell, mGridNext, (char*) mClr, 2); CopyMfFromCUDA ( m_alpha, m_alpha_pre, m_pressure_modify, (float*) m_vel_phrel, m_restMass, m_restDensity, m_visc, (float*)m_velxcor, (float*)m_alphagrad, 2); #ifdef NEW_BOUND CopyBoundFromCUDA(mIsBound); #endif CopyFromCUDA_Uproject(MF_type, m_beta); } //------------------------------ Initialization FluidSystem::FluidSystem () { mNumPoints = 0; mMaxPoints = 0; mPackBuf = 0x0; mPackGrid = 0x0; mFP = 0x0; mPos = 0x0; mClr = 0x0; mIsBound = 0x0; mVel = 0x0; mVelEval = 0x0; mAge = 0x0; mPressure = 0x0; mDensity = 0x0; mForce = 0x0; mClusterCell = 0x0; mGridNext = 0x0; mNbrNdx = 0x0; mNbrCnt = 0x0; mSelected = -1; m_Grid = 0x0; m_GridCnt = 0x0; m_Frame = 0; m_NeighborTable = 0x0; m_NeighborDist = 0x0; elasticID = 0x0; m_Param [ PMODE ] = RUN_MULTI_CUDA_FULL; m_Param [ PEXAMPLE ] = 1; m_Param [ PGRID_DENSITY ] = 2.0; m_Param [ PNUM ] = 8192; //65536 * 128; //m_Param[PNUM] = 12000; m_Toggle [ PDEBUG ] = false; m_Toggle [ PUSE_GRID ] = false; m_Toggle [ PPROFILE ] = false; m_Toggle [ PCAPTURE ] = false; m_Toggle [ HIDEBOUND] = true; m_Toggle [HIDEFLUID] = false; m_Toggle [HIDESOLID] = false; m_Toggle [HIDERIGID] = false; memset(m_Yan,0,sizeof(m_Yan)); if ( !xml.Load ( "scene.xml" ) ) { error.PrintF ( "fluid", "ERROR: Problem loading scene.xml. Check formatting.\n" ); error.Exit (); } //From YanXiao nOutFrame = 0; } void FluidSystem::Setup ( bool bStart ) { //TestPrefixSum ( 16*1024*1024 ); m_Frame = 0; m_Time = 0; ClearNeighborTable (); mNumPoints = 0; SetupDefaultParams (); //MfTestSetupExample(); setupSPHexample(); //epsilonfile = fopen("OutputData\\epsilonFile.txt","w+"); printf("max-allowed particle number is %d\n", m_maxAllowedPoints); printf("particle num:%d\n", NumPoints()); printf("elastic num:%d\n", numElasticPoints); printf("spacing is %f, smooth radius is %f, simscale is %f\n", m_Param[PSPACING], m_Param[PSMOOTHRADIUS]/ m_Param[PSIMSCALE], m_Param[PSIMSCALE]); SetupGridAllocate ( m_Vec[PVOLMIN], m_Vec[PVOLMAX], m_Param[PSIMSCALE], m_Param[PGRIDSIZE], 1.0 ); // Setup grid FluidClearCUDA (); Sleep ( 500 ); FluidSetupRotationCUDA (panr, omega, loadwhich, capillaryForceRatio); float CudaMem = 0; CudaMem += ElasticSetupCUDA(numElasticPoints, miu, lambda, porosity, m_Permeability, maxNeighborNum, pressureRatio, SurfaceTensionRatio); PorousParamCUDA(bulkModulus_porous, bulkModulus_grains, bulkModulus_solid, bulkModulus_fluid, poroDeformStrength, capillary,Relax2); CudaMem += FluidSetupCUDA ( NumPoints(), m_GridSrch, *(int3*)& m_GridRes, *(float3*)& m_GridSize, *(float3*)& m_GridDelta, *(float3*)& m_GridMin, *(float3*)& m_GridMax, m_GridTotal, (int) m_Vec[PEMIT_RATE].x ); std::cout << "CUDA memory cost : " << CudaMem << std::endl; Sleep ( 500 ); Vector3DF grav = m_Vec[PPLANE_GRAV_DIR]; printf("%f %f\n",m_Param[PBSTIFF],m_Param[PEXTSTIFF]); FluidParamCUDA ( m_Param[PSIMSCALE], m_Param[PSMOOTHRADIUS], m_Param[PRADIUS], m_Param[PMASS], m_Param[PRESTDENSITY], *(float3*)& m_Vec[PBOUNDMIN], *(float3*)& m_Vec[PBOUNDMAX], m_Param[PEXTSTIFF], m_Param[PINTSTIFF],m_Param[PBSTIFF], m_Param[PVISC], m_Param[PEXTDAMP], m_Param[PFORCE_MIN], m_Param[PFORCE_MAX], m_Param[PFORCE_FREQ], m_Param[PGROUND_SLOPE], grav.x, grav.y, grav.z, m_Param[PACCEL_LIMIT], m_Param[PVEL_LIMIT] ); ParamUpdateCUDA(m_Toggle[HIDEBOUND], m_Toggle[HIDEFLUID], m_Toggle[HIDESOLID],m_Toggle[HIDERIGID], restColorValue); //FluidParamCUDA ( m_Param[PSIMSCALE], m_Param[PSMOOTHRADIUS], m_Param[PRADIUS], m_Param[PMASS], m_Param[PRESTDENSITY], *(float3*)& m_Vec[PBOUNDMIN], *(float3*)& m_Vec[PBOUNDMAX], m_Param[PBSTIFF], m_Param[PINTSTIFF], m_Param[PVISC], m_Param[PEXTDAMP], m_Param[PFORCE_MIN], m_Param[PFORCE_MAX], m_Param[PFORCE_FREQ], m_Param[PGROUND_SLOPE], grav.x, grav.y, grav.z, m_Param[PACCEL_LIMIT], m_Param[PVEL_LIMIT] ); FluidParamCUDA_projectu(vfactor, fpfactor, spfactor,bdamp); FluidMfParamCUDA (m_fluidDensity,m_fluidVisc,m_fluidPMass,m_fluidDiffusion,m_Param[FLUID_CATNUM], m_DT, *(float3*)& cont,*(float3*)& mb1,*(float3*)& mb2, relax, example); //cout << "fluid catnum is " << m_Param[FLUID_CATNUM] << endl; TransferToCUDA (); // Initial transfer //Sorting InitialSortCUDA( 0x0, 0x0, 0x0 ); SortGridCUDA( 0x0 ); CountingSortFullCUDA_( 0x0 ); //Initialize:compute density of solid,store it into mf_restdensity[i] initSPH(m_restDensity, MF_type); OnfirstRun(); } void FluidSystem::RunSimulateMultiCUDAFull() { mint::Time start; start.SetSystemTime(ACC_NSEC); //printf("start time is %f\n", start.) //printf("RunSimulateMultiCUDAFull\n"); LARGE_INTEGER t1, t2, tc; if (m_Frame == 1) m_CostTime = 0; QueryPerformanceFrequency(&tc); InitialSortCUDA(0x0, 0x0, 0x0); record(PTIME_INSERT, "Insert CUDA", start); start.SetSystemTime(ACC_NSEC); SortGridCUDA(0x0); CountingSortFullCUDA_(0x0); record(PTIME_SORT, "Full Sort CUDA", start); start.SetSystemTime(ACC_NSEC); QueryPerformanceCounter(&t1); MfPredictAdvection(m_Time); record(PTIME_SORT, "Predict Advection CUDA", start); start.SetSystemTime(ACC_NSEC); PressureSolve(0, NumPoints()); if (numElasticPoints > 0) ComputeElasticForceCUDA(); ComputePorousForceCUDA(); MfComputeAlphaAdvanceCUDA(); //case 1 record(PTIMEALPHA, "Alpha Advance CUDA", start); start.SetSystemTime(ACC_NSEC); LeapFrogIntegration(m_Time); record(PTIME_ADVANCE, "Advance CUDA", start); QueryPerformanceCounter(&t2); m_CostTime += (t2.QuadPart - t1.QuadPart)*1.0 / tc.QuadPart; if (m_Frame == 1000) { cout << "ave time :" << m_CostTime / m_Frame << endl; } TransferFromCUDA(); // return for rendering } void FluidSystem::OnfirstRun() { printf("on first run\n"); mint::Time start; start.SetSystemTime(ACC_NSEC); InitialSortCUDA(0x0, 0x0, 0x0); record(PTIME_INSERT, "Insert CUDA", start); start.SetSystemTime(ACC_NSEC); SortGridCUDA(0x0); CountingSortFullCUDA_(0x0); record(PTIME_SORT, "Full Sort CUDA", start); start.SetSystemTime(ACC_NSEC); MfComputePressureCUDA(); //case 3,5 record(PTIME_PRESS, "Compute Pressure CUDA", start); start.SetSystemTime(ACC_NSEC); ComputeCorrectLCUDA(); record(PTIME_PRESS, "Compute CorrectL CUDA", start); start.SetSystemTime(ACC_NSEC); TransferFromCUDA(); // return for rendering } void FluidSystem::Record() { mFileNum = getLastRecording() + 1; mFileName = getFilename(mFileNum); //if (mFP != 0x0) fclose(mFP); char name[100]; strcpy(name, mFileName.c_str()); ofstream out(name); //mFP = fopen(name, "wb"); //if (mFP == 0x0) { // printf("ERROR: Cannot write file %s\n", mFileName.c_str()); // exit(-1); //} //mLastPoints = 0; //mFileSize = 0; Vector3DF* ppos = mPos; Vector3DF* pvel = mVel; float* pdens = mDensity; DWORD* pclr = mClr; int* bound = mIsBound; char* dat = mPackBuf; int* type = MF_type; int channels; int dsize; out << NumPointsNoBound << endl; //out << NumPointsNoBound<<" "<<softBoundary[0].x << " " << softBoundary[0].z // << " " << softBoundary[0].y << " " << softBoundary[1].x // << " " << softBoundary[1].z << " " << softBoundary[1].y <<endl; //fwrite ( &mNumPoints, sizeof(int), 1, mFP ); //cout << "output file: " << mFP << endl; // How many channels to write? //fwrite ( &channels, sizeof(int), 1, mFP ) ; // Write data //if ( channels == 2 ) { // dsize = sizeof(Vector3DF)+sizeof(DWORD); for (int n = 0; n < mNumPoints; n++) { if (*type == 1) { ppos++; pclr++; type++; continue; } /*if ((*ppos).y < 0) continue;*/ //*(Vector3DF*) dat = *ppos++; dat += sizeof(Vector3DF); //out << n << " " << ((Vector3DF*)dat)->x //*(DWORD*) dat = *pclr++; dat += sizeof(DWORD); out << ppos->x << " " << ppos->z << " " << ppos->y << " "; if (_example == 1) { if (*type == 0) { out << m_alpha[n*MAX_FLUIDNUM + 1] << " " << m_alpha[n*MAX_FLUIDNUM + 2] << " " << m_alpha[n*MAX_FLUIDNUM + 3] << " " << m_alpha[n*MAX_FLUIDNUM + 1] + m_alpha[n*MAX_FLUIDNUM + 2] + m_alpha[n*MAX_FLUIDNUM + 3] << " "; } else { float beta[MAX_FLUIDNUM]; for (int k = 1; k < MAX_FLUIDNUM; ++k) beta[k] = m_beta[n*MAX_FLUIDNUM*MAX_SOLIDNUM + k * MAX_SOLIDNUM + *type - 2]; out << 1 / (1 + sqrt(beta[2] + beta[3])) << " " << 1 / (1 + sqrt(beta[1] + beta[3])) << " " << sqrt(beta[3]) / (1 + sqrt(beta[3])) <<" "<< 1 << " "; } } else { if (*type == 0) { out << 1 << " " << 1 << " " << 1 << " " << 0.6*m_alpha[n*MAX_FLUIDNUM + 1] + m_alpha[n*MAX_FLUIDNUM + 2] + m_alpha[n*MAX_FLUIDNUM + 3] << " "; } else { float beta[MAX_FLUIDNUM]; for (int k = 1; k < MAX_FLUIDNUM; ++k) beta[k] = m_beta[n*MAX_FLUIDNUM*MAX_SOLIDNUM + k * MAX_SOLIDNUM + *type - 2]; if (*type == 5) out << 1 / (1 + sqrt(beta[2] + beta[3])) << " " << 1 / (1 + sqrt(beta[1] + beta[3])) << " " << sqrt(beta[3]) / (1 + sqrt(beta[3])) << " " << 1 << " "; else out << 0 << " " << 1 << " " << 0 << " " << 1 << " "; } } out << *type << endl; ppos++; pclr++; type++; } out.close(); mFileSize += float(dsize * mNumPoints) / 1048576.0; mLastPoints = mNumPoints; //fflush ( mFP ); } char dsttmp[100]; void FluidSystem::outputFile() { FILE* fp; sprintf(dsttmp, "OutputData\\data_%04d.txt", nOutFrame); if (_access(dsttmp, 0) == -1) _mkdir(dsttmp); fp = fopen(dsttmp,"w"); fprintf(fp,"%d\n",NumPoints()); Vector3DF* ppos = mPos; for (int i = 0;i<NumPoints();i++,ppos++){ //fprintf(fp,"%f %f %f\n",ppos->x,ppos->y,ppos->z); fprintf(fp,"%f %f %f",mPos[i].x,mPos[i].y,mPos[i].z); for (int j = 0;j<MAX_FLUIDNUM;j++) fprintf(fp," %f",*(m_alpha+i*MAX_FLUIDNUM + j)); fprintf(fp," %f",m_restMass[i]); fprintf(fp," %f",m_restDensity[i]); fprintf(fp," %d\n",MF_type[i]); } fclose(fp); nOutFrame++; } void FluidSystem::storeModel(char* filename) { FILE* fp; sprintf(dsttmp, filename, nOutFrame); fp = fopen(dsttmp, "w"); fprintf(fp, "%d\n", numElasticPoints); Vector3DF* ppos = mPos; for (int i = 0; i<NumPoints(); i++, ppos++) { if(MF_type[i]==1) fprintf(fp, "%f %f %f\n", mPos[i].x, mPos[i].y, mPos[i].z); } fclose(fp); } void FluidSystem::LoadParticles(char* filename, Vector3DF off) { fstream f; f.open(filename, ios::in); int num; f >> num; float x, y, z; int n = numElasticPoints; int p; for (int i = 0; i<num; i++) { f >> x >> y >> z; p = AddParticle(); if (p != -1) { *(elasticID + p) = n; (mPos + p)->Set(x+off.x, y+off.y, z+off.z); *(m_alpha + p*MAX_FLUIDNUM) = 1.0f; *(m_alpha_pre + p*MAX_FLUIDNUM) = 1.0f; *(m_restMass + p) = m_fluidPMass[0]; *(m_restDensity + p) = m_fluidDensity[0]; *(m_visc + p) = m_fluidVisc[0]; *(mIsBound + p) = false; *(MF_type + p) = 1; //1 means deformable *(porosity_particle + n) = porosity; n++; } } numElasticPoints = n; f.close(); } int countNeighborNum(float radius, Vector3DF pos, Vector3DF* mpos, int num) { Vector3DF d; float distance; int count = 0; for (int p = 0; p < num; ++p) { d = pos - mpos[p]; distance = d.x*d.x+d.y*d.y+d.z*d.z; if (distance < radius) count++; } return count; } void FluidSystem::solveModel() { int n = numElasticPoints; int count; float radius = m_Param[PSMOOTHRADIUS] * m_Param[PSMOOTHRADIUS]/(m_Param[PSIMSCALE]* m_Param[PSIMSCALE]); for(int p=0;p<n;++p) { count = countNeighborNum(radius, mPos[p], mPos, n); if (count < 8) { MF_type[p] = 0; numElasticPoints--; } } } extern bool bPause; void FluidSystem::Run (int width, int height) { // Clear sim timers m_Param[ PTIME_INSERT ] = 0.0; m_Param[ PTIME_SORT ] = 0.0; m_Param[ PTIME_COUNT ] = 0.0; m_Param[ PTIME_PRESS ] = 0.0; m_Param[ PTIME_FORCE ] = 0.0; m_Param[ PTIME_ADVANCE ] = 0.0; ParamUpdateCUDA(m_Toggle[HIDEBOUND], m_Toggle[HIDEFLUID], m_Toggle[HIDESOLID],m_Toggle[HIDERIGID], restColorValue); mint::Time start; start.SetSystemTime(ACC_NSEC); RunSimulateMultiCUDAFull(); //DWORD end = timeGetTime(); //printf("simulate time %d\n", end - start); if ( GetYan(START_OUTPUT) && m_Frame % (int)(0.005 / m_DT) == 0 && RecordNum <= 400) { //StartRecord(); start.SetSystemTime ( ACC_NSEC ); CaptureVideo(width, height); Record (); RecordNum++; record ( PTIME_RECORD, "Record", start ); } //if((_example == 2 && m_Frame == 10000)) // saveParticle("save_stat.txt"); if ( m_Toggle[PCAPTURE] && m_Frame %(int)(0.005/m_DT)==0){//controlled by '`' CaptureVideo ( width, height ); /*if( m_Frame /(int)(0.005/m_DT)== 200){ //bPause = true; liftup(1); } if( m_Frame /(int)(0.005/m_DT)== 215){ //bPause = true; liftup(0); } if( m_Frame /(int)(0.005/m_DT)== 300){ bPause = true; }*/ } int k=10000; if(m_Frame == k) liftup(1); if(m_Frame == k+1400) liftup(0); //if(m_Frame == k+1050*2+750) // liftup(2); if(m_Frame == 27000) bPause = !bPause; //if ( GetYan(START_OUTPUT)==1 && m_Frame %(int)(0.005/m_DT)==0 ){ //controlled by 'b' // outputFile(); //} m_Time += m_DT; m_Frame++; //outputepsilon(epsilonfile); //if(example == 2 && m_Frame == upframe) // SetYan(CHANGE_DEN,1); } void FluidSystem::Exit () { //fclose(epsilonfile); free ( mPos ); free ( mClr ); free (mIsBound); free ( mVel ); free ( mVelEval ); free ( mAge ); free ( mPressure ); free ( mDensity ); free ( mForce ); free ( mClusterCell ); free ( mGridCell ); free ( mGridNext ); free ( mNbrNdx ); free ( mNbrCnt ); //multi fluid free (m_alpha); free (m_alpha_pre); free (m_pressure_modify); free (m_vel_phrel); free (m_restMass); free (m_restDensity); free (m_visc); free (m_velxcor); free (m_alphagrad); free (MF_type); //free (MF_tensor); free (elasticID); free(signDistance); FluidClearCUDA(); cudaExit (0,0); } // Allocate particle memory void FluidSystem::AllocateParticles ( int cnt ) { int nump = 0; // number to copy from previous data Vector3DF* srcPos = mPos; mPos = (Vector3DF*) malloc ( EMIT_BUF_RATIO*cnt*sizeof(Vector3DF) ); if ( srcPos != 0x0 ) { memcpy ( mPos, srcPos, nump *sizeof(Vector3DF)); free ( srcPos ); } DWORD* srcClr = mClr; mClr = (DWORD*) malloc ( EMIT_BUF_RATIO*cnt*sizeof(DWORD) ); if ( srcClr != 0x0 ) { memcpy ( mClr, srcClr, nump *sizeof(DWORD)); free ( srcClr ); } int* srcIsBound = mIsBound; mIsBound = (int*) malloc ( cnt*sizeof(int) ); if ( srcIsBound != 0x0 ) { memcpy ( mIsBound, srcIsBound, nump *sizeof(int)); free ( srcIsBound ); } Vector3DF* srcVel = mVel; mVel = (Vector3DF*) malloc ( EMIT_BUF_RATIO*cnt*sizeof(Vector3DF) ); if ( srcVel != 0x0 ) { memcpy ( mVel, srcVel, nump *sizeof(Vector3DF)); free ( srcVel ); } Vector3DF* srcVelEval = mVelEval; mVelEval = (Vector3DF*) malloc ( EMIT_BUF_RATIO*cnt*sizeof(Vector3DF) ); if ( srcVelEval != 0x0 ) { memcpy ( mVelEval, srcVelEval, nump *sizeof(Vector3DF)); free ( srcVelEval ); } unsigned short* srcAge = mAge; mAge = (unsigned short*) malloc ( EMIT_BUF_RATIO*cnt*sizeof(unsigned short) ); if ( srcAge != 0x0 ) { memcpy ( mAge, srcAge, nump *sizeof(unsigned short)); free ( srcAge ); } float* srcPress = mPressure; mPressure = (float*) malloc ( EMIT_BUF_RATIO*cnt*sizeof(float) ); if ( srcPress != 0x0 ) { memcpy ( mPressure, srcPress, nump *sizeof(float)); free ( srcPress ); } float* srcDensity = mDensity; mDensity = (float*) malloc ( EMIT_BUF_RATIO*cnt*sizeof(float) ); if ( srcDensity != 0x0 ) { memcpy ( mDensity, srcDensity, nump *sizeof(float)); free ( srcDensity ); } Vector3DF* srcForce = mForce; mForce = (Vector3DF*) malloc ( EMIT_BUF_RATIO*cnt*sizeof(Vector3DF) ); if ( srcForce != 0x0 ) { memcpy ( mForce, srcForce, nump *sizeof(Vector3DF)); free ( srcForce ); } uint* srcCell = mClusterCell; mClusterCell = (uint*) malloc ( EMIT_BUF_RATIO*cnt*sizeof(uint) ); if ( srcCell != 0x0 ) { memcpy ( mClusterCell, srcCell, nump *sizeof(uint)); free ( srcCell ); } uint* srcGCell = mGridCell; mGridCell = (uint*) malloc ( EMIT_BUF_RATIO*cnt*sizeof(uint) ); if ( srcGCell != 0x0 ) { memcpy ( mGridCell, srcGCell, nump *sizeof(uint)); free ( srcGCell ); } uint* srcNext = mGridNext; mGridNext = (uint*) malloc ( EMIT_BUF_RATIO*cnt*sizeof(uint) ); if ( srcNext != 0x0 ) { memcpy ( mGridNext, srcNext, nump *sizeof(uint)); free ( srcNext ); } uint* srcNbrNdx = mNbrNdx; mNbrNdx = (uint*) malloc ( EMIT_BUF_RATIO*cnt*sizeof(uint) ); if ( srcNbrNdx != 0x0 ) { memcpy ( mNbrNdx, srcNbrNdx, nump *sizeof(uint)); free ( srcNbrNdx ); } uint* srcNbrCnt = mNbrCnt; mNbrCnt = (uint*) malloc ( EMIT_BUF_RATIO*cnt*sizeof(uint) ); if ( srcNbrCnt != 0x0 ) { memcpy ( mNbrCnt, srcNbrCnt, nump *sizeof(uint)); free ( srcNbrCnt ); } m_Param[PSTAT_PMEM] = 68 * 2 * cnt; //multi fluid float* src_alpha = m_alpha; m_alpha = (float*) malloc ( EMIT_BUF_RATIO*cnt*MAX_FLUIDNUM*sizeof(float)); if (src_alpha != 0x0) { memcpy (m_alpha, src_alpha, nump * MAX_FLUIDNUM * sizeof(float)); free(src_alpha);} float* src_beta = m_beta; m_beta = (float*)malloc(EMIT_BUF_RATIO*cnt*MAX_FLUIDNUM * sizeof(float)*MAX_SOLIDNUM); if (src_beta != 0x0) { memcpy(m_beta, src_beta, nump * MAX_FLUIDNUM * sizeof(float)*MAX_SOLIDNUM); free(src_beta); } float* src_alpha_pre = m_alpha_pre; m_alpha_pre = (float*) malloc ( EMIT_BUF_RATIO*cnt*MAX_FLUIDNUM*sizeof(float)); if (src_alpha_pre != 0x0) { memcpy (m_alpha_pre, src_alpha_pre, nump * MAX_FLUIDNUM * sizeof(float)); free(src_alpha_pre);} float* src_pressure_modify = m_pressure_modify; m_pressure_modify = (float*) malloc ( EMIT_BUF_RATIO*cnt*sizeof(float)); if (src_pressure_modify != 0x0) { memcpy (m_pressure_modify, src_pressure_modify, nump * sizeof(float)); free(src_pressure_modify);} Vector3DF* src_vel_phrel = m_vel_phrel; m_vel_phrel = (Vector3DF*) malloc ( EMIT_BUF_RATIO*cnt*MAX_FLUIDNUM*sizeof(Vector3DF)); if (src_vel_phrel != 0x0) { memcpy (m_vel_phrel, src_vel_phrel, nump * MAX_FLUIDNUM * sizeof(Vector3DF)); free(src_vel_phrel);} float* src_restMass = m_restMass; m_restMass = (float*) malloc ( EMIT_BUF_RATIO*cnt*sizeof(float) ); if ( src_restMass != 0x0 ) { memcpy ( m_restMass, src_restMass, nump *sizeof(float)); free ( src_restMass ); } float* src_restDensity = m_restDensity; m_restDensity = (float*) malloc ( EMIT_BUF_RATIO*cnt*sizeof(float) ); if ( src_restDensity != 0x0 ) { memcpy ( m_restDensity, src_restDensity, nump *sizeof(float)); free ( src_restDensity ); } float* src_visc = m_visc; m_visc = (float*) malloc ( EMIT_BUF_RATIO*cnt*sizeof(float) ); if ( src_visc != 0x0 ) { memcpy ( m_visc, src_visc, nump *sizeof(float)); free ( src_visc ); } Vector3DF* src_velxcor = m_velxcor; m_velxcor = (Vector3DF*) malloc ( EMIT_BUF_RATIO*cnt*sizeof(Vector3DF) ); if ( src_velxcor != 0x0 ) { memcpy ( m_velxcor, src_velxcor, nump *sizeof(Vector3DF)); free ( src_velxcor ); } Vector3DF* src_alphagrad = m_alphagrad; m_alphagrad = (Vector3DF*) malloc ( EMIT_BUF_RATIO*cnt*MAX_FLUIDNUM*sizeof(Vector3DF)); if (src_alphagrad != 0x0) { memcpy (m_alphagrad, src_alphagrad, nump * MAX_FLUIDNUM * sizeof(Vector3DF)); free(src_alphagrad);} //elastic information uint* src_elasticID = elasticID; elasticID = (uint*)malloc(EMIT_BUF_RATIO*cnt * sizeof(uint)); if (src_elasticID != 0x0) { memcpy(elasticID, src_elasticID, nump * sizeof(uint)); free(src_elasticID); } float* src_porosity = porosity_particle; porosity_particle = (float*)malloc(EMIT_BUF_RATIO*cnt * sizeof(float)); if (src_porosity != 0x0) { memcpy(porosity_particle, src_porosity, nump * sizeof(float)); free(src_porosity); } Vector3DF* src_signDistance = signDistance; signDistance = (Vector3DF*)malloc(EMIT_BUF_RATIO* cnt * sizeof(Vector3DF)); if (src_signDistance != 0x0) { memcpy(signDistance, src_signDistance, cnt * sizeof(Vector3DF)); free(src_signDistance); } //Project U int* src_mftype = MF_type; MF_type = (int*) malloc(EMIT_BUF_RATIO*cnt*sizeof(int)); if(src_mftype != 0x0) {memcpy( MF_type, src_mftype, nump*sizeof(int)); free(src_mftype);} //End Project U m_Param[PSTAT_PMEM] = EMIT_BUF_RATIO * (92 + 36*MAX_FLUIDNUM)* 2 * cnt; mMaxPoints = cnt; } float unitMatrix[9] = {1,0,0, 0,1,0, 0,0,1}; int FluidSystem::AddParticle () { if ( mNumPoints >= mMaxPoints ) return -1; int n = mNumPoints; (mPos + n)->Set ( 0,0,0 ); (mVel + n)->Set ( 0,0,0 ); (mVelEval + n)->Set ( 0,0,0 ); (mForce + n)->Set ( 0,0,0 ); *(mPressure + n) = 0; *(mDensity + n) = 0; *(mGridNext + n) = -1; *(mClusterCell + n) = -1; //#ifdef NEW_BOUND *(mIsBound+n) = 0; //#endif //multi fluid memset(m_alpha + n*MAX_FLUIDNUM,0,MAX_FLUIDNUM*sizeof(float)); memset(m_alpha_pre + n*MAX_FLUIDNUM,0,MAX_FLUIDNUM*sizeof(float)); memset(m_pressure_modify + n,0,sizeof(float)); memset(m_vel_phrel+n*MAX_FLUIDNUM,0,MAX_FLUIDNUM*sizeof(Vector3DF)); memset(m_alphagrad+n*MAX_FLUIDNUM,0,MAX_FLUIDNUM*sizeof(Vector3DF)); *(m_restMass + n) = 0; *(m_restDensity + n) = 0; *(m_visc + n) = 0; (m_velxcor + n)->Set(0,0,0); mNumPoints++; return n; } void FluidSystem::record ( int param, std::string name, mint::Time& start ) { mint::Time stop; stop.SetSystemTime ( ACC_NSEC ); stop = stop - start; m_Param [ param ] = stop.GetMSec(); if ( m_Toggle[PPROFILE] ) printf ("%s: %s\n", name.c_str(), stop.GetReadableTime().c_str() ); } void FluidSystem::AllocatePackBuf () { if ( mPackBuf != 0x0 ) free ( mPackBuf ); mPackBuf = (char*) malloc ( sizeof(Fluid) * mMaxPoints ); } void FluidSystem::ClearNeighborTable () { if ( m_NeighborTable != 0x0 ) free (m_NeighborTable); if ( m_NeighborDist != 0x0) free (m_NeighborDist ); m_NeighborTable = 0x0; m_NeighborDist = 0x0; m_NeighborNum = 0; m_NeighborMax = 0; } // Ideal grid cell size (gs) = 2 * smoothing radius = 0.02*2 = 0.04 // Ideal domain size = k*gs/d = k*0.02*2/0.005 = k*8 = {8, 16, 24, 32, 40, 48, ..} // (k = number of cells, gs = cell size, d = simulation scale) void FluidSystem::SetupGridAllocate ( Vector3DF min, Vector3DF max, float sim_scale, float cell_size, float border ) { float world_cellsize = cell_size / sim_scale; m_GridMin = min; m_GridMax = max; m_GridSize = m_GridMax; m_GridSize -= m_GridMin; m_GridRes.x = ceil ( m_GridSize.x / world_cellsize ); // Determine grid resolution m_GridRes.y = ceil ( m_GridSize.y / world_cellsize ); m_GridRes.z = ceil ( m_GridSize.z / world_cellsize ); m_GridSize.x = m_GridRes.x * cell_size / sim_scale; // Adjust grid size to multiple of cell size m_GridSize.y = m_GridRes.y * cell_size / sim_scale; m_GridSize.z = m_GridRes.z * cell_size / sim_scale; m_GridDelta = m_GridRes; // delta = translate from world space to cell # m_GridDelta /= m_GridSize; m_GridTotal = (int)(m_GridRes.x * m_GridRes.y * m_GridRes.z); // Allocate grid if ( m_Grid == 0x0 ) free (m_Grid); if ( m_GridCnt == 0x0 ) free (m_GridCnt); m_Grid = (uint*) malloc ( sizeof(uint*) * m_GridTotal ); m_GridCnt = (uint*) malloc ( sizeof(uint*) * m_GridTotal ); memset ( m_Grid, GRID_UCHAR, m_GridTotal*sizeof(uint) ); memset ( m_GridCnt, GRID_UCHAR, m_GridTotal*sizeof(uint) ); m_Param[PSTAT_GMEM] = 12 * m_GridTotal; // Grid memory used // Number of cells to search: // n = (2r / w) +1, where n = 1D cell search count, r = search radius, w = world cell width // m_GridSrch = floor(2*(m_Param[PSMOOTHRADIUS]/sim_scale) / world_cellsize+0.001) + 1; if ( m_GridSrch < 2 ) m_GridSrch = 2; m_GridAdjCnt = m_GridSrch * m_GridSrch * m_GridSrch ; // 3D search count = n^3, e.g. 2x2x2=8, 3x3x3=27, 4x4x4=64 if ( m_GridSrch > 6 ) { printf ( "ERROR: Neighbor search is n > 6. \n " ); exit(-1); } int cell = 0; for (int y=0; y < m_GridSrch; y++ ) for (int z=0; z < m_GridSrch; z++ ) for (int x=0; x < m_GridSrch; x++ ) m_GridAdj[cell++] = ( y*m_GridRes.z + z )*m_GridRes.x + x ; // -1 compensates for ndx 0=empty printf ( "Adjacency table (CPU) \n"); for (int n=0; n < m_GridAdjCnt; n++ ) { printf ( " ADJ: %d, %d\n", n, m_GridAdj[n] ); } if ( mPackGrid != 0x0 ) free ( mPackGrid ); mPackGrid = (int*) malloc ( sizeof(int) * m_GridTotal ); } int FluidSystem::getGridCell ( int p, Vector3DI& gc ) { return getGridCell ( *(mPos+p), gc ); } int FluidSystem::getGridCell ( Vector3DF& pos, Vector3DI& gc ) { gc.x = (int)( (pos.x - m_GridMin.x) * m_GridDelta.x); // Cell in which particle is located gc.y = (int)( (pos.y - m_GridMin.y) * m_GridDelta.y); gc.z = (int)( (pos.z - m_GridMin.z) * m_GridDelta.z); return (int)( (gc.y*m_GridRes.z + gc.z)*m_GridRes.x + gc.x); } Vector3DI FluidSystem::getCell ( int c ) { Vector3DI gc; int xz = m_GridRes.x*m_GridRes.z; gc.y = c / xz; c -= gc.y*xz; gc.z = c / m_GridRes.x; c -= gc.z*m_GridRes.x; gc.x = c; return gc; } void FluidSystem::SetupRender () { glEnable ( GL_TEXTURE_2D ); glGenTextures ( 1, (GLuint*) mTex ); glBindTexture ( GL_TEXTURE_2D, mTex[0] ); glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP); glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP); glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST ); glTexParameterf (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST ); glPixelStorei( GL_UNPACK_ALIGNMENT, 4); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGB32F_ARB, 8, 8, 0, GL_RGB, GL_FLOAT, 0); glGenBuffersARB ( 3, (GLuint*) mVBO ); // Construct a sphere in a VBO int udiv = 6; int vdiv = 6; float du = 180.0 / udiv; float dv = 360.0 / vdiv; float x,y,z, x1,y1,z1; float r = 1.0; Vector3DF* buf = (Vector3DF*) malloc ( sizeof(Vector3DF) * (udiv+2)*(vdiv+2)*2 ); Vector3DF* dat = buf; mSpherePnts = 0; for ( float tilt=-90; tilt <= 90.0; tilt += du) { for ( float ang=0; ang <= 360; ang += dv) { x = sin ( ang*DEGtoRAD) * cos ( tilt*DEGtoRAD ); y = cos ( ang*DEGtoRAD) * cos ( tilt*DEGtoRAD ); z = sin ( tilt*DEGtoRAD ) ; x1 = sin ( ang*DEGtoRAD) * cos ( (tilt+du)*DEGtoRAD ) ; y1 = cos ( ang*DEGtoRAD) * cos ( (tilt+du)*DEGtoRAD ) ; z1 = sin ( (tilt+du)*DEGtoRAD ); dat->x = x*r; dat->y = y*r; dat->z = z*r; dat++; dat->x = x1*r; dat->y = y1*r; dat->z = z1*r; dat++; mSpherePnts += 2; } } glBindBufferARB ( GL_ARRAY_BUFFER_ARB, mVBO[2] ); glBufferDataARB ( GL_ARRAY_BUFFER_ARB, mSpherePnts*sizeof(Vector3DF), buf, GL_STATIC_DRAW_ARB); glVertexPointer ( 3, GL_FLOAT, 0, 0x0 ); free ( buf ); mImg.read ( "ball32.bmp", "ball32a.bmp" ); // Enable Instacing shader //cgGLEnableProfile( vert_profile ); //cgGLBindProgram ( cgVP ); //cgGLEnableProfile( frag_profile ); //cgGLBindProgram ( cgFP ); } void FluidSystem::DrawGrid () { Vector3DF gd (1, 1, 1); Vector3DF gc; gd /= m_GridDelta; glBegin ( GL_LINES ); for (int z=0; z <= m_GridRes.z; z++ ) { for (int y=0; y <= m_GridRes.y; y++ ) { gc.Set ( 1, y, z); gc /= m_GridDelta; gc += m_GridMin; glVertex3f ( m_GridMin.x, gc.y, gc.z ); glVertex3f ( m_GridMax.x, gc.y, gc.z ); } } for (int z=0; z <= m_GridRes.z; z++ ) { for (int x=0; x <= m_GridRes.x; x++ ) { gc.Set ( x, 1, z); gc /= m_GridDelta; gc += m_GridMin; glVertex3f ( gc.x, m_GridMin.y, gc.z ); glVertex3f ( gc.x, m_GridMax.y, gc.z ); } } for (int y=0; y <= m_GridRes.y; y++ ) { for (int x=0; x <= m_GridRes.x; x++ ) { gc.Set ( x, y, 1); gc /= m_GridDelta; gc += m_GridMin; glVertex3f ( gc.x, gc.y, m_GridMin.z ); glVertex3f ( gc.x, gc.y, m_GridMax.z ); } } glEnd (); } void FluidSystem::DrawText () { char msg[100]; Vector3DF* ppos = mPos; DWORD* pclr = mClr; Vector3DF clr; for (int n = 0; n < NumPoints(); n++) { sprintf ( msg, "%d", n ); glColor4f ( (RED(*pclr)+1.0)*0.5, (GRN(*pclr)+1.0)*0.5, (BLUE(*pclr)+1.0)*0.5, ALPH(*pclr) ); drawText3D ( ppos->x, ppos->y, ppos->z, msg ); ppos++; pclr++; } } void FluidSystem::Draw ( Camera3D& cam, float rad ) { char* dat; Vector3DF* ppos; float* pdens; DWORD* pclr; glDisable ( GL_LIGHTING ); switch ( (int) m_Param[PDRAWGRID] ) { case 0: break; case 1: glColor4f ( 0.7, 0.7, 0.7, 0.05 ); DrawGrid (); break; }; if ( m_Param[PDRAWTEXT] == 1.0 ) { DrawText (); }; // Draw Modes // DRAW_POINTS 0 // DRAW_SPRITES 1 switch ( (int) m_Param[PDRAWMODE] ) { case 0: //multi fluid bound if(GetYan(SHOW_BOUND) == 0)//controlled by '7', capture screen '`' BTW { for (int i = 0;i<NumPoints();i++) if (mIsBound[i]!=0) mPos[i].x=mPos[i].y=mPos[i].z=-1000; } glPointSize ( 6 ); glEnable ( GL_POINT_SIZE ); glEnable( GL_BLEND ); glBindBufferARB ( GL_ARRAY_BUFFER_ARB, mVBO[0] ); glBufferDataARB ( GL_ARRAY_BUFFER_ARB, NumPoints()*sizeof(Vector3DF), mPos, GL_DYNAMIC_DRAW_ARB); glVertexPointer ( 3, GL_FLOAT, 0, 0x0 ); glBindBufferARB ( GL_ARRAY_BUFFER_ARB, mVBO[1] ); glBufferDataARB ( GL_ARRAY_BUFFER_ARB, NumPoints()*sizeof(uint), mClr, GL_DYNAMIC_DRAW_ARB); glColorPointer ( 4, GL_UNSIGNED_BYTE, 0, 0x0 ); glEnableClientState ( GL_VERTEX_ARRAY ); glEnableClientState ( GL_COLOR_ARRAY ); glNormal3f ( 0, 0.001, 1 ); glColor3f ( 1, 1, 1 ); //glLoadMatrixf ( view_mat ); glDrawArrays ( GL_POINTS, 0, NumPoints() ); glDisableClientState ( GL_VERTEX_ARRAY ); glDisableClientState ( GL_COLOR_ARRAY ); break; case 1: //actually used switch(GetYan(SHOW_BOUND)){ //controlled by 7 case 1: for (int i = 0;i<NumPoints();i++) if (mIsBound[i]==1 || MF_type[i]==1) mPos[i].x=mPos[i].y=mPos[i].z=-1000; break; case 2: for (int i = 0;i<NumPoints();i++) if (mIsBound[i]==1 || MF_type[i]==0) mPos[i].x=mPos[i].y=mPos[i].z=-1000; break; } /*if(example==3) for (int i = 0;i<NumPoints();i++) if (mPos[i].y>23||mPos[i].y<0) mPos[i].y=mPos[i].z=mPos[i].x = -1000;*/ /*if (GetYan(SAVE_STAT) == 1) saveParticle("save_stat.txt"); int outP = 0; for (int i = 0;i<NumPoints();i++) if (mIsBound[i]==0 && (mPos[i].x<-100 ||mPos[i].y<-100||mPos[i].z<-100)) outP++;*/ glEnable ( GL_LIGHTING ); glEnable(GL_BLEND); glEnable(GL_ALPHA_TEST); glAlphaFunc( GL_GREATER, 0.5 ); glEnable ( GL_COLOR_MATERIAL ); glColorMaterial ( GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE ); // Point sprite size glPointSize ( 48 ); glEnable ( GL_POINT_SIZE ); glEnable(GL_POINT_SPRITE_ARB); { float quadratic[] = { 0.0f, 0.3f, 0.00f }; glEnable ( GL_POINT_DISTANCE_ATTENUATION ); glPointParameterfvARB( GL_POINT_DISTANCE_ATTENUATION, quadratic ); } //float maxSize = 64.0f; //if(example==3){ // glGetFloatv( GL_POINT_SIZE_MAX_ARB, &maxSize ); // glPointSize( maxSize ); // glPointParameterfARB( GL_POINT_SIZE_MAX_ARB, maxSize ); //} glPointParameterfARB( GL_POINT_SIZE_MIN_ARB, 1.0f ); // Texture and blending mode glEnable ( GL_TEXTURE_2D ); glBindTexture ( GL_TEXTURE_2D, mImg.getID() ); glTexEnvi (GL_POINT_SPRITE, GL_COORD_REPLACE, GL_TRUE); glTexEnvf (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_BLEND ); glBlendFunc ( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ; // Point buffers glBindBufferARB ( GL_ARRAY_BUFFER_ARB, mVBO[0] ); glBufferDataARB ( GL_ARRAY_BUFFER_ARB, NumPoints()*sizeof(Vector3DF), mPos, GL_DYNAMIC_DRAW_ARB); glVertexPointer ( 3, GL_FLOAT, 0, 0x0 ); glBindBufferARB ( GL_ARRAY_BUFFER_ARB, mVBO[1] ); glBufferDataARB ( GL_ARRAY_BUFFER_ARB, NumPoints()*sizeof(uint), mClr, GL_DYNAMIC_DRAW_ARB); glColorPointer ( 4, GL_UNSIGNED_BYTE, 0, 0x0 ); glEnableClientState ( GL_VERTEX_ARRAY ); glEnableClientState ( GL_COLOR_ARRAY ); // Render - Point Sprites glNormal3f ( 0, 1, 0.001 ); glColor3f ( 1, 1, 1 ); glDrawArrays ( GL_POINTS, 0, NumPoints() ); // Restore state glDisableClientState ( GL_VERTEX_ARRAY ); glDisableClientState ( GL_COLOR_ARRAY ); glDisable (GL_POINT_SPRITE_ARB); glDisable ( GL_ALPHA_TEST ); glDisable ( GL_TEXTURE_2D ); glDepthMask( GL_TRUE ); break; case 2: if(GetYan(SHOW_BOUND) == 0) { for (int i = 0;i<NumPoints();i++) if (mIsBound[i]!=0) mPos[i].x=mPos[i].y=mPos[i].z=-1000; } // Notes: // # particles, time(Render), time(Total), time(Sim), Render Overhead (%) // 250000, 12, 110, 98, 10% - Point sprites // 250000, 36, 146, 110, 24% - Direct rendering (drawSphere) // 250000, 140, 252, 110, 55% - Batch instancing glEnable ( GL_LIGHTING ); ppos = mPos; pclr = mClr; pdens = mDensity; for (int n = 0; n < NumPoints(); n++) if (mIsBound[n]==0) { glPushMatrix (); glTranslatef ( ppos->x, ppos->y, ppos->z ); glScalef ( rad, rad, rad ); glColor4f ( RED(*pclr), GRN(*pclr), BLUE(*pclr), ALPH(*pclr) ); drawSphere (); glPopMatrix (); ppos++; pclr++; } // --- HARDWARE INSTANCING /* cgGLEnableProfile( vert_profile ); // Sphere VBO glBindBufferARB ( GL_ARRAY_BUFFER_ARB, mVBO[2] ); glVertexPointer ( 3, GL_FLOAT, 0, 0x0 ); glEnableClientState ( GL_VERTEX_ARRAY ); glColor4f( 1,1,1,1 ); CGparameter uParam = cgGetNamedParameter( cgVP, "modelViewProj" ); glLoadMatrixf ( view_mat ); cgGLSetStateMatrixParameter( uParam, CG_GL_MODELVIEW_PROJECTION_MATRIX, CG_GL_MATRIX_IDENTITY ); uParam = cgGetNamedParameter( cgVP, "transformList" ); int batches = NumPoints() / 768; int noff = 0; for (int n=0; n < batches; n++ ) { cgGLSetParameterArray3f ( uParam, 0, 768, (float*) (mPos + noff) ); glDrawArraysInstancedARB ( GL_TRIANGLE_STRIP, 0, mSpherePnts, 768 ); noff += 768; } cgGLDisableProfile( vert_profile ); glDisableClientState ( GL_VERTEX_ARRAY ); glDisableClientState ( GL_COLOR_ARRAY ); */ //--- Texture buffer technique /* uParam = cgGetNamedParameter( cgVP, "transformList"); cgGLSetTextureParameter ( uParam, mTex[0] ); cgGLEnableTextureParameter ( uParam ); uParam = cgGetNamedParameter( cgVP, "primCnt"); cgGLSetParameter1f ( uParam, NumPoints() ); glBindTexture ( GL_TEXTURE_2D, mTex[0] ); glTexImage2D ( GL_TEXTURE_2D, 0, GL_RGB32F_ARB, 2048, int(NumPoints()/2048)+1, 0, GL_RGB, GL_FLOAT, mPos ); glBindTexture ( GL_TEXTURE_2D, 0x0 ); glFinish ();*/ break; }; //-------------------------------------- DEBUGGING // draw neighbors of particle i /*int i = 320; int j, jndx = (mNbrList + i )->first; for (int nbr=0; nbr < (mNbrList+i)->num; nbr++ ) { j = *(m_NeighborTable+jndx); ppos = (mPos + j ); glPushMatrix (); glTranslatef ( ppos->x, ppos->y, ppos->z ); glScalef ( 0.25, 0.25, 0.25 ); glColor4f ( 0, 1, 0, 1); // green drawSphere (); glPopMatrix (); jndx++; } // draw particles in grid cells of i Vector3DF jpos; Grid_FindCells ( i ); for (int cell=0; cell < 8; cell++) { j = m_Grid [ *(mClusterCell+i) + m_GridAdj[cell] ]; while ( j != -1 ) { if ( i==j ) { j = *(mGridNext+j); continue; } jpos = *(mPos + j); glPushMatrix (); glTranslatef ( jpos.x, jpos.y, jpos.z ); glScalef ( 0.22, 0.22, 0.22 ); glColor4f ( 1, 1, 0, 1); // yellow drawSphere (); glPopMatrix (); j = *(mGridNext+j); } } // draw grid cells of particle i float poff = m_Param[PSMOOTHRADIUS] / m_Param[PSIMSCALE]; int gx = (int)( (-poff + ppos->x - m_GridMin.x) * m_GridDelta.x); // Determine grid cell int gy = (int)( (-poff + ppos->y - m_GridMin.y) * m_GridDelta.y); int gz = (int)( (-poff + ppos->z - m_GridMin.z) * m_GridDelta.z); Vector3DF gd (1, 1, 1); Vector3DF gc; gd /= m_GridDelta; */ // Error particles (debugging) /*for (int n=0; n < NumPoints(); n++) { if ( ALPH(*(mClr+n))==0.9 ) DrawParticle ( n, 12, 14, Vector3DF(1,0,0) ); } // Draw selected particle DrawNeighbors ( mSelected ); DrawParticle ( mSelected, 8, 12, Vector3DF(1,1,1) ); DrawCircle ( *(mPos+mSelected), m_Param[PSMOOTHRADIUS]/m_Param[PSIMSCALE], Vector3DF(1,1,0), cam ); Vector3DI gc; int gs = getGridCell ( mSelected, gc ); // Grid cell of selected glDisable ( GL_DEPTH_TEST ); glColor3f ( 0.8, 0.8, 0.9 ); gs = *(mClusterCell + mSelected); // Cluster cell for (int n=0; n < m_GridAdjCnt; n++ ) { // Cluster group gc = getCell ( gs + m_GridAdj[n] ); DrawCell ( gc.x, gc.y, gc.z ); } glColor3f ( 1.0, 1.0, 1.0 ); DrawCell ( gc.x, gc.y, gc.z ); glEnable ( GL_DEPTH_TEST );*/ } std::string FluidSystem::getFilename ( int n ) { char name[100]; sprintf ( name, "OutputData%d\\particles%04d.dat", _example, n ); return name; } void FluidSystem::StartRecord () { mFileNum = getLastRecording () + 1; mFileName = getFilename ( mFileNum ); if ( mFP != 0x0 ) fclose ( mFP ); char name[100]; strcpy ( name, mFileName.c_str() ); mFP = fopen ( name, "wb" ); if ( mFP == 0x0 ) { printf ( "ERROR: Cannot write file %s\n", mFileName.c_str() ); exit ( -1 ); } mLastPoints = 0; mFileSize = 0; } int FluidSystem::getLastRecording () { FILE* fp; int num = 0; fp = fopen ( getFilename(num).c_str(), "rb" ); while ( fp != 0x0 ) { // skip existing recordings fclose ( fp ); num++; fp = fopen ( getFilename(num).c_str(), "rb" ); } return num-1; } std::string FluidSystem::getModeStr () { char buf[100]; switch ( (int) m_Param[PMODE] ) { case RUN_SEARCH: sprintf ( buf, "SEARCH ONLY (CPU)" ); break; case RUN_VALIDATE: sprintf ( buf, "VALIDATE GPU to CPU"); break; case RUN_CPU_SLOW: sprintf ( buf, "SIMULATE CPU Slow"); break; case RUN_CPU_GRID: sprintf ( buf, "SIMULATE CPU Grid"); break; case RUN_CUDA_RADIX: sprintf ( buf, "SIMULATE CUDA Radix Sort"); break; case RUN_CUDA_INDEX: sprintf ( buf, "SIMULATE CUDA Index Sort" ); break; case RUN_CUDA_FULL: sprintf ( buf, "SIMULATE CUDA Full Sort" ); break; case RUN_CUDA_CLUSTER: sprintf ( buf, "SIMULATE CUDA Clustering" ); break; case RUN_PLAYBACK: sprintf ( buf, "PLAYBACK (%s)", mFileName.c_str() ); break; }; //sprintf ( buf, "RECORDING (%s, %.4f MB)", mFileName.c_str(), mFileSize ); break; return buf; }; int FluidSystem::SelectParticle ( int x, int y, int wx, int wy, Camera3D& cam ) { Vector4DF pnt; Vector3DF* ppos = mPos; for (int n = 0; n < NumPoints(); n++ ) { pnt = cam.project ( *ppos ); pnt.x = (pnt.x+1.0)*0.5 * wx; pnt.y = (pnt.y+1.0)*0.5 * wy; if ( x > pnt.x-8 && x < pnt.x+8 && y > pnt.y-8 && y < pnt.y+8 ) { mSelected = n; return n; } ppos++; } mSelected = -1; return -1; } void FluidSystem::DrawParticleInfo ( int p ) { char disp[256]; glColor4f ( 1.0, 1.0, 1.0, 1.0 ); sprintf ( disp, "Particle: %d", p ); drawText ( 10, 20, disp ); Vector3DI gc; int gs = getGridCell ( p, gc ); sprintf ( disp, "Grid Cell: <%d, %d, %d> id: %d", gc.x, gc.y, gc.z, gs ); drawText ( 10, 40, disp ); int cc = *(mClusterCell + p); gc = getCell ( cc ); sprintf ( disp, "Cluster Cell: <%d, %d, %d> id: %d", gc.x, gc.y, gc.z, cc ); drawText ( 10, 50, disp ); sprintf ( disp, "Neighbors: " ); int cnt = *(mNbrCnt + p); int ndx = *(mNbrNdx + p); for ( int n=0; n < cnt; n++ ) { sprintf ( disp, "%s%d, ", disp, m_NeighborTable[ ndx ] ); ndx++; } drawText ( 10, 70, disp ); if ( cc != -1 ) { sprintf ( disp, "Cluster Group: "); drawText ( 10, 90, disp); int cadj; int stotal = 0; for (int n=0; n < m_GridAdjCnt; n++ ) { // Cluster group cadj = cc+m_GridAdj[n]; gc = getCell ( cadj ); sprintf ( disp, "<%d, %d, %d> id: %d, cnt: %d ", gc.x, gc.y, gc.z, cc+m_GridAdj[n], m_GridCnt[ cadj ] ); drawText ( 20, 100+n*10, disp ); stotal += m_GridCnt[cadj]; } sprintf ( disp, "Search Overhead: %f (%d of %d), %.2f%% occupancy", float(stotal)/ cnt, cnt, stotal, float(cnt)*100.0/stotal ); drawText ( 10, 380, disp ); } } void FluidSystem::SetupKernels () { m_Param [ PDIST ] = pow ( m_Param[PMASS] / m_Param[PRESTDENSITY], 1/3.0 ); m_R2 = m_Param [PSMOOTHRADIUS] * m_Param[PSMOOTHRADIUS]; m_Poly6Kern = 315.0f / (64.0f * 3.141592 * pow( m_Param[PSMOOTHRADIUS], 9) ); // Wpoly6 kernel (denominator part) - 2003 Muller, p.4 m_SpikyKern = -45.0f / (3.141592 * pow( m_Param[PSMOOTHRADIUS], 6) ); // Laplacian of viscocity (denominator): PI h^6 m_LapKern = 45.0f / (3.141592 * pow( m_Param[PSMOOTHRADIUS], 6) ); CubicSplineKern1 = 1 / (4 * 3.141592*pow(m_Param[PSMOOTHRADIUS], 3)); CubicSplineKern2 = 1 / (3.141592*pow(m_Param[PSMOOTHRADIUS], 3)); gradCubicSplineKern1 = -3 / (4 * 3.141592*pow(m_Param[PSMOOTHRADIUS], 4)); gradCubicSplineKern2 = 1 / (3.141592*pow(m_Param[PSMOOTHRADIUS], 4)); } void FluidSystem::SetupDefaultParams () { // Range = +/- 10.0 * 0.006 (r) = 0.12 m (= 120 mm = 4.7 inch) // Container Volume (Vc) = 0.001728 m^3 // Rest Density (D) = 1000.0 kg / m^3 // Particle Mass (Pm) = 0.00020543 kg (mass = vol * density) // Number of Particles (N) = 4000.0 // Water Mass (M) = 0.821 kg (= 821 grams) // Water Volume (V) = 0.000821 m^3 (= 3.4 cups, .21 gals) // Smoothing Radius (R) = 0.02 m (= 20 mm = ~3/4 inch) // Particle Radius (Pr) = 0.00366 m (= 4 mm = ~1/8 inch) // Particle Volume (Pv) = 2.054e-7 m^3 (= .268 milliliters) // Rest Distance (Pd) = 0.0059 m // // Given: D, Pm, N // Pv = Pm / D 0.00020543 kg / 1000 kg/m^3 = 2.054e-7 m^3 // Pv = 4/3*pi*Pr^3 cuberoot( 2.054e-7 m^3 * 3/(4pi) ) = 0.00366 m // M = Pm * N 0.00020543 kg * 4000.0 = 0.821 kg // V = M / D 0.821 kg / 1000 kg/m^3 = 0.000821 m^3 // V = Pv * N 2.054e-7 m^3 * 4000 = 0.000821 m^3 // Pd = cuberoot(Pm/D) cuberoot(0.00020543/1000) = 0.0059 m // // Ideal grid cell size (gs) = 2 * smoothing radius = 0.02*2 = 0.04 // Ideal domain size = k*gs/d = k*0.02*2/0.005 = k*8 = {8, 16, 24, 32, 40, 48, ..} // (k = number of cells, gs = cell size, d = simulation scale) // "The viscosity coefficient is the dynamic viscosity, visc > 0 (units Pa.s), // and to include a reasonable damping contribution, it should be chosen // to be approximately a factor larger than any physical correct viscosity // coefficient that can be looked up in the literature. However, care should // be taken not to exaggerate the viscosity coefficient for fluid materials. // If the contribution of the viscosity force density is too large, the net effect // of the viscosity term will introduce energy into the system, rather than // draining the system from energy as intended." // Actual visocity of water = 0.001 Pa.s // viscosity of water at 20 deg C. m_Time = 0; // Start at T=0 m_DT = 0.003; m_Param [ PSIMSCALE ] = 0.005;//m_Param [ PSIMSCALE ] = 0.005; // unit size m_Param [ PVISC ] = 0.35; // pascal-second (Pa.s) = 1 kg m^-1 s^-1 (see wikipedia page on viscosity) m_Param [ PRESTDENSITY ] = 600.0; // kg / m^3 m_Param [ PSPACING ] = 0.0; // spacing will be computed automatically from density in most examples (set to 0 for autocompute) m_Param [ PMASS ] = 0.00020543; // kg m_Param [ PRADIUS ] = 0.02; // m m_Param [ PDIST ] = 0.0059; // m //m_Param [ PSMOOTHRADIUS ] = 0.005;// m_Param [ PSMOOTHRADIUS ] = 0.01/scaleP3;// // m m_Param [ PINTSTIFF ] = 1.5; m_Param [ PEXTSTIFF ] = 50000.0; m_Param [ PEXTDAMP ] = 100.0; m_Param [ PACCEL_LIMIT ] = 150.0; // m / s^2 m_Param [ PVEL_LIMIT ] = 3.0; // m / s m_Param [ PMAX_FRAC ] = 1.0; m_Param [ PPOINT_GRAV_AMT ] = 0.0; m_Param [ PGROUND_SLOPE ] = 0.0; m_Param [ PFORCE_MIN ] = 0.0; m_Param [ PFORCE_MAX ] = 0.0; m_Param [ PFORCE_FREQ ] = 8.0; m_Toggle [ PWRAP_X ] = false; m_Toggle [ PWALL_BARRIER ] = false; m_Toggle [ PLEVY_BARRIER ] = false; m_Toggle [ PDRAIN_BARRIER ] = false; m_Param [ PSTAT_NBRMAX ] = 0 ; m_Param [ PSTAT_SRCHMAX ] = 0 ; m_Vec [ PPOINT_GRAV_POS ].Set ( 0, 50, 0 ); m_Vec [ PPLANE_GRAV_DIR ].Set ( 0, -9.8, 0 ); m_Vec [ PEMIT_POS ].Set ( 0, 0, 0 ); m_Vec [ PEMIT_RATE ].Set ( 0, 0, 0 ); m_Vec [ PEMIT_ANG ].Set ( 0, 90, 1.0 ); m_Vec [ PEMIT_DANG ].Set ( 0, 0, 0 ); // Default sim config m_Toggle [ PRUN ] = true; // Run integrator m_Param [PGRIDSIZE] = m_Param[PSMOOTHRADIUS] * 2; m_Param [PDRAWMODE] = 1; // Sprite drawing m_Param [PDRAWGRID] = 0; // No grid m_Param [PDRAWTEXT] = 0; // No text // Load settings from XML (overwrite the above defaults) ParseXML ( "Fluid", 0, false ); //Multifluid: component number in use m_Param [ FLUID_CATNUM ] = MAX_FLUIDNUM; for(int i=0;i<MAX_FLUIDNUM;i++) { m_fluidPMass[i]=0.00004279792; m_fluidDensity[i]=1000; m_fluidVisc[i]=0.35; } m_fluidDiffusion=0.0; } void FluidSystem::ParseXML_Bound (std::string name, int boundnum) { #ifdef NEW_BOUND xml.setBase ( name, boundnum ); xml.assignValueD ( &m_Param[PBMASS], "Mass" ); xml.assignValueD ( &m_Param[PBSTIFF], "BoundStiff" ); xml.assignValueD ( &m_Param[PBVISC], "Viscosity" ); xml.assignValueD ( &m_Param[PBRESTDENSITY], "RestDensity" ); #endif } void FluidSystem::ParseXML ( std::string name, int id, bool bStart ) { xml.setBase ( name, id ); xml.assignValueD ( &m_DT, "DT" ); xml.assignValueStr ( mSceneName, "Name" ); if (bStart) xml.assignValueD ( &m_Param[PNUM], "Num" ); xml.assignValueD ( &m_Param[PGRID_DENSITY], "GridDensity" ); xml.assignValueD ( &m_Param[PSIMSCALE], "SimScale" ); xml.assignValueD ( &m_Param[PVISC], "Viscosity" ); xml.assignValueD ( &m_Param[PRESTDENSITY], "RestDensity" ); xml.assignValueD ( &m_Param[PSPACING], "Spacing" ); xml.assignValueD ( &m_Param[PMASS], "Mass" ); xml.assignValueD ( &m_Param[PRADIUS], "Radius" ); xml.assignValueD ( &m_Param[PDIST], "SearchDist" ); xml.assignValueD ( &m_Param[PINTSTIFF], "IntStiff" ); xml.assignValueD ( &m_Param[PEXTSTIFF], "BoundStiff" ); xml.assignValueD ( &m_Param[PEXTDAMP], "BoundDamp" ); xml.assignValueD ( &m_Param[PACCEL_LIMIT], "AccelLimit" ); xml.assignValueD ( &m_Param[PVEL_LIMIT], "VelLimit" ); xml.assignValueD ( &m_Param[PPOINT_GRAV_AMT], "PointGravAmt" ); xml.assignValueD ( &m_Param[PGROUND_SLOPE], "GroundSlope" ); xml.assignValueD ( &m_Param[PFORCE_MIN], "WaveForceMin" ); xml.assignValueD ( &m_Param[PFORCE_MAX], "WaveForceMax" ); xml.assignValueD ( &m_Param[PFORCE_FREQ], "WaveForceFreq" ); xml.assignValueD ( &m_Param[PDRAWMODE], "DrawMode" ); xml.assignValueD ( &m_Param[PDRAWGRID], "DrawGrid" ); xml.assignValueD ( &m_Param[PDRAWTEXT], "DrawText" ); xml.assignValueD ( &m_Param[PSMOOTHRADIUS], "SmoothRadius" ); xml.assignValueV3 ( &m_Vec[PVOLMIN], "VolMin" ); xml.assignValueV3 ( &m_Vec[PVOLMAX], "VolMax" ); xml.assignValueV3 ( &m_Vec[PINITMIN], "InitMin" ); xml.assignValueV3 ( &m_Vec[PINITMAX], "InitMax" ); xml.assignValueV3 ( &m_Vec[PPOINT_GRAV_POS], "PointGravPos" ); xml.assignValueV3 ( &m_Vec[PPLANE_GRAV_DIR], "PlaneGravDir" ); } void FluidSystem::ParseMFXML ( std::string name, int id, bool bStart ) { xml.setBase ( name, id ); xml.assignValueD ( &m_DT, "DT" ); xml.assignValueStr ( mSceneName, "Name" ); if (bStart) xml.assignValueD ( &m_Param[PNUM], "Num" ); xml.assignValueD ( &m_Param[PGRID_DENSITY], "GridDensity" ); xml.assignValueD ( &m_Param[PSIMSCALE], "SimScale" ); xml.assignValueD ( &m_Param[PVISC], "Viscosity" ); xml.assignValueD ( &m_Param[PRESTDENSITY], "RestDensity" ); xml.assignValueD ( &m_Param[PSPACING], "Spacing" ); xml.assignValueD ( &m_Param[PMASS], "Mass" ); xml.assignValueD ( &m_Param[PRADIUS], "Radius" ); xml.assignValueD ( &m_Param[PDIST], "SearchDist" ); xml.assignValueD ( &m_Param[PINTSTIFF], "IntStiff" ); xml.assignValueD ( &m_Param[PEXTSTIFF], "BoundStiff" ); xml.assignValueD ( &m_Param[PEXTDAMP], "BoundDamp" ); xml.assignValueD ( &m_Param[PACCEL_LIMIT], "AccelLimit" ); xml.assignValueD ( &m_Param[PVEL_LIMIT], "VelLimit" ); xml.assignValueD ( &m_Param[PPOINT_GRAV_AMT], "PointGravAmt" ); xml.assignValueD ( &m_Param[PGROUND_SLOPE], "GroundSlope" ); xml.assignValueD ( &m_Param[PFORCE_MIN], "WaveForceMin" ); xml.assignValueD ( &m_Param[PFORCE_MAX], "WaveForceMax" ); xml.assignValueD ( &m_Param[PFORCE_FREQ], "WaveForceFreq" ); xml.assignValueD ( &m_Param[PDRAWMODE], "DrawMode" ); xml.assignValueD ( &m_Param[PDRAWGRID], "DrawGrid" ); xml.assignValueD ( &m_Param[PDRAWTEXT], "DrawText" ); xml.assignValueD ( &m_Param[PSMOOTHRADIUS], "SmoothRadius" ); xml.assignValueV3 ( &m_Vec[PVOLMIN], "VolMin" ); xml.assignValueV3 ( &m_Vec[PVOLMAX], "VolMax" ); xml.assignValueV3 ( &m_Vec[PINITMIN], "InitMin" ); xml.assignValueV3 ( &m_Vec[PINITMAX], "InitMax" ); xml.assignValueV3 ( &m_Vec[PPOINT_GRAV_POS], "PointGravPos" ); xml.assignValueV3 ( &m_Vec[PPLANE_GRAV_DIR], "PlaneGravDir" ); xml.assignValueV3 ( &m_Vec[PBOUNDMIN], "sb3"); xml.assignValueV3 ( &m_Vec[PBOUNDMAX], "sb6"); xml.assignValueV3( &volumes[0], "VolMin0"); xml.assignValueV3( &volumes[1], "VolMax0"); xml.assignValueV3( &volumes[2], "VolMin1"); xml.assignValueV3( &volumes[3], "VolMax1"); xml.assignValueV3( &volumes[4], "VolMin2"); xml.assignValueV3( &volumes[5], "VolMax2"); xml.assignValueV3(&volumes[6], "VolMin3"); xml.assignValueV3(&volumes[7], "VolMax3"); xml.assignValueV3(&volumes[8], "VolMin4"); xml.assignValueV3(&volumes[9], "VolMax4"); xml.assignValueV3(&softBoundary[0], "BoundMin"); xml.assignValueV3(&softBoundary[1], "BoundMax"); xml.assignValueD(&scaleP, "ScaleP"); xml.assignValueD(&scaledis,"ScaleDis"); xml.assignValueD(&m_Param[FLUID_CATNUM],"FluidCount"); xml.assignValueD(&vfactor,"BoundViscFactor"); xml.assignValueD(&fpfactor, "fluidPressureFactor"); xml.assignValueD(&spfactor, "solidPressureFactor"); xml.assignValueD(&bdamp, "BoundXZdamp"); xml.assignValueV3(&mb1,"mb3"); xml.assignValueV3(&mb2,"mb6"); xml.assignValueV4(&massRatio,"MassRatio"); xml.assignValueV4(&densityRatio,"DensityRatio"); xml.assignValueV4(&viscRatio,"ViscRatio"); loadwhich = xml.getValueI("LoadWhich"); upframe = xml.getValueI("Upframe"); xml.assignValueV3(&cont, "Cont"); xml.assignValueF(&relax, "Relax"); xml.assignValueF(&poroDeformStrength, "poroDeformStrength"); xml.assignValueF(&capillary, "capillary"); xml.assignValueF(&Relax2, "Relax2"); xml.assignValueF(&SurfaceTensionRatio, "SurfaceTension"); xml.assignValueV4(&colorValue, "ColorValue"); xml.assignValueV3(&emit[0],"emit3"); xml.assignValueV3(&emit[1],"emit6"); xml.assignValueF(&capillaryForceRatio, "capillaryForceRatio"); panr = xml.getValueF("Panr"); omega = xml.getValueF("Omega"); //solid maxNeighborNum = xml.getValueI("maxNeighborNum"); miu = xml.getValueF("miu"); lambda = xml.getValueF("lambda"); porosity = xml.getValueF("porosity"); m_Param[PERMEABILITY] = xml.getValueF("permeability"); //cout << "permeability:" << setprecision(15)<<m_Param[PERMEABILITY]; for (int k = 0; k < MAX_FLUIDNUM; ++k) { xml.assignValueV4(&permeabilityRatio, string("permeabilityRatio") + to_string(k + 1)); m_Permeability[k*MAX_SOLIDNUM + 0] = permeabilityRatio.x*m_Param[PERMEABILITY]; m_Permeability[k*MAX_SOLIDNUM + 1] = permeabilityRatio.y*m_Param[PERMEABILITY]; m_Permeability[k*MAX_SOLIDNUM + 2] = permeabilityRatio.z*m_Param[PERMEABILITY]; m_Permeability[k*MAX_SOLIDNUM + 3] = permeabilityRatio.w*m_Param[PERMEABILITY]; cout << string("permeabilityRatio") + to_string(k) << m_Permeability[k*MAX_SOLIDNUM + 0] << " " << m_Permeability[k*MAX_SOLIDNUM + 1] << " " << m_Permeability[k*MAX_SOLIDNUM + 2] << " " << m_Permeability[k*MAX_SOLIDNUM + 3] << endl; } for (int k = 0; k < MAX_FLUIDNUM; ++k) { xml.assignValueV4(&pressRatio, string("pressureRatio") + to_string(k + 1)); pressureRatio[k*MAX_SOLIDNUM + 0] = pressRatio.x; pressureRatio[k*MAX_SOLIDNUM + 1] = pressRatio.y; pressureRatio[k*MAX_SOLIDNUM + 2] = pressRatio.z; pressureRatio[k*MAX_SOLIDNUM + 3] = pressRatio.w; cout << string("pressureRatio") + to_string(k)<< pressureRatio[k*MAX_SOLIDNUM + 0] << " " << pressureRatio[k*MAX_SOLIDNUM + 1] << " " << pressureRatio[k*MAX_SOLIDNUM + 2] << " " << pressureRatio[k*MAX_SOLIDNUM + 3] << endl; } Vector4DF v; xml.assignValueV4(&v, "bulkModulus"); bulkModulus_porous = v.x; bulkModulus_grains = v.y; bulkModulus_solid = v.z; bulkModulus_fluid = v.w; emitSpeed = mb2.z; emitangle = emit[0].x; emitcircle = emit[0].y; emitposx = emit[0].z; emitposy = emit[1].x; emitposz = emit[1].y; emitfreq = emit[1].z; printf("Emit param: %f %f %f %f %f %f %f\n",emitSpeed,emitangle,emitcircle,emitposx,emitposy,emitposz,emitfreq); } void FluidSystem::SetupSpacing () { m_Param [ PSIMSIZE ] = m_Param [ PSIMSCALE ] * (m_Vec[PVOLMAX].z - m_Vec[PVOLMIN].z); if ( m_Param[PSPACING] == 0 ) { // Determine spacing from density m_Param [PDIST] = pow ( m_Param[PMASS] / m_Param[PRESTDENSITY], 1/3.0 ); m_Param [PSPACING] = m_Param [ PDIST ]*scaledis / m_Param[ PSIMSCALE ]; } else { // Determine density from spacing m_Param [PDIST] = m_Param[PSPACING] * m_Param[PSIMSCALE] / 0.87; m_Param [PRESTDENSITY] = m_Param[PMASS] / pow ( m_Param[PDIST], 3.0 ); } printf ( "Add Particles. Density: %f, Spacing: %f, PDist: %f\n", m_Param[PRESTDENSITY], m_Param [ PSPACING ], m_Param[ PDIST ] ); // Particle Boundaries //m_Vec[PBOUNDMIN].Set(softBoundary[0].x,softBoundary[0].y,softBoundary[0].z); //m_Vec[PBOUNDMAX].Set(softBoundary[1].x,softBoundary[1].y,softBoundary[1].z); } void FluidSystem::CaptureVideo (int width, int height) { Image img ( width, height, 3, 8 ); // allocates pixel memory FILE *fScreenshot; char fileName[64]; sprintf( fileName, "ScreenOutput\\screen_%04d.bmp", m_Frame ); fScreenshot = fopen( fileName, "wb"); // record frame buffer directly to image pixels glReadPixels( 0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, img.getPixelData() ); img.writeBMP ( fScreenshot ); // write bmp format fflush ( fScreenshot ); // close file fclose ( fScreenshot ); //convert to BGR format /*unsigned char temp; int i = 0; while (i < nSize) { temp = pixels[i]; //grab blue pixels[i] = pixels[i+2];//assign red to blue pixels[i+2] = temp; //assign blue to red i += 3; //skip to next blue byte }*/ // TGA format /*unsigned char TGAheader[12]={0,0,2,0,0,0,0,0,0,0,0,0}; unsigned char header[6] = {m_WindowWidth%256,m_WindowWidth/256, m_WindowHeight%256,m_WindowHeight/256,24,0}; fwrite(TGAheader, sizeof(unsigned char), 12, fScreenshot); fwrite(header, sizeof(unsigned char), 6, fScreenshot); fwrite(pixels, sizeof(GLubyte), nSize, fScreenshot); fclose(fScreenshot);*/ return; } int FluidSystem::SetupMfAddVolume ( Vector3DF min, Vector3DF max, float spacing, Vector3DF offs, int cat ) { Vector3DF pos; int n = 0, p; float dx, dy, dz, x, y, z; int cntx, cnty, cntz; cntx = ceil( (max.x-min.x-offs.x) / spacing ); cntz = ceil( (max.z-min.z-offs.z) / spacing ); cnty = ceil((max.y - min.y - offs.y) / spacing); //printf("cntx is %d, cntz is %d, cnty is %d, total is %d\n", cntx, cntz, cnty, cntx*cntz*cnty); int cnt = cntx * cntz; int xp, yp, zp, c2; float odd; if(cat >= m_Param [ FLUID_CATNUM ])return 0; dx = max.x-min.x; dy = max.y-min.y; dz = max.z-min.z; c2 = cnt/2; for (float y = min.y+offs.y; y <= max.y; y += spacing ) { for (int xz=0; xz < cnt; xz++ ) { x = min.x+offs.x + (xz % int(cntx))*spacing; z = min.z+offs.z + (xz / int(cntx))*spacing; /*if ( xy < c2 ) { zp = xy / int(dx); x = min.x+offs + (xz % int(cntx/2) )*spacing*2 + (zp % 2)*spacing; z = min.z+offs + zp * spacing; } else { zp = (xy-c2) / int(dx); x = min.x+offs + ( (xz-c2) % int(cntx/2) )*spacing*2 + (zp % 2)*spacing; z = min.z+offs + (cntz-1-zp) * spacing; }*/ p = AddParticle (); if ( p != -1 ) { n++; (mPos+p)->Set ( x,y,z); // *(mClr+p) = COLORA( (x-min.x)/dx, (y-min.y)/dy, (z-min.z)/dz, 1); *(mClr+p) = COLORA( 0.25, +0.25 + (y-min.y)*.75/dy, 0.25 + (z-min.z)*.75/dz, 1); // (x-min.x)/dx *(m_alpha+p*MAX_FLUIDNUM+cat) = 1.0f;*(m_alpha_pre+p*MAX_FLUIDNUM+cat) = 1.0f; *(m_restMass+p) = m_fluidPMass[cat]; *(m_restDensity+p) = m_fluidDensity[cat]; *(m_visc+p) = m_fluidVisc[cat]; //*(m_alpha + p*MAX_FLUIDNUM + 1) = 1; //*(m_alpha_pre + p*MAX_FLUIDNUM + 1) = 0.5f; //*(m_alpha + p*MAX_FLUIDNUM + 1) = 0.5f; // *(m_alpha_pre + p*MAX_FLUIDNUM + 1) = 0.5f; //*(m_alpha + p*MAX_FLUIDNUM + 2) = 0.5f; // *(m_alpha_pre + p*MAX_FLUIDNUM + 2) = 0.5f; *(MF_type+p) = 0; //which means liquid (project-u) } } } printf("%d fluid has %d particles\n",cat,n); return n; } int FluidSystem::SetupMfAddBlendVolume(Vector3DF min, Vector3DF max, float spacing, Vector3DF offs) { Vector3DF pos; int n = 0, p; float dx, dy, dz, x, y, z; int cntx, cnty, cntz; cntx = ceil((max.x - min.x - offs.x) / spacing); cntz = ceil((max.z - min.z - offs.z) / spacing); cnty = ceil((max.y - min.y - offs.y) / spacing); //printf("cntx is %d, cntz is %d, cnty is %d, total is %d\n", cntx, cntz, cnty, cntx*cntz*cnty); int cnt = cntx * cntz; int xp, yp, zp, c2; float odd; dx = max.x - min.x; dy = max.y - min.y; dz = max.z - min.z; c2 = cnt / 2; for (float y = min.y + offs.y; y <= max.y; y += spacing) { for (int xz = 0; xz < cnt; xz++) { x = min.x + offs.x + (xz % int(cntx))*spacing; z = min.z + offs.z + (xz / int(cntx))*spacing; p = AddParticle(); if (p != -1) { n++; (mPos + p)->Set(x, y, z); *(mClr + p) = COLORA(0.25, +0.25 + (y - min.y)*.75 / dy, 0.25 + (z - min.z)*.75 / dz, 1); // (x-min.x)/dx *(m_alpha + p*MAX_FLUIDNUM + 1) = 0.34f; *(m_alpha_pre + p*MAX_FLUIDNUM + 1) = 0.34f; *(m_alpha + p*MAX_FLUIDNUM + 2) = 0.33f; *(m_alpha_pre + p*MAX_FLUIDNUM + 2) = 0.33f; *(m_alpha + p*MAX_FLUIDNUM + 3) = 0.33f; *(m_alpha_pre + p*MAX_FLUIDNUM + 3) = 0.33f; //*(m_alpha + p*MAX_FLUIDNUM + 4) = 0.25f; *(m_alpha_pre + p*MAX_FLUIDNUM + 4) = 0.25f; *(m_restMass + p) = 0; *(m_restDensity + p) = 0; *(m_visc + p) = 0; for (int k = 1; k < MAX_FLUIDNUM; ++k) { *(m_restMass + p) += 1.0 / (MAX_FLUIDNUM-1) * m_fluidPMass[k]; *(m_restDensity + p) += 1.0 / (MAX_FLUIDNUM-1) * m_fluidDensity[k]; *(m_visc + p) += 1.0 / (MAX_FLUIDNUM-1) * m_fluidVisc[k]; } *(MF_type + p) = 0; //which means liquid (project-u) } } } //printf("%d fluid has %d particles\n", cat, n); return n; } int FluidSystem::SetupMfAddGridSolid(Vector3DF min, Vector3DF max, float spacing, Vector3DF offs, int type) { Vector3DF pos; int n = 0, p; float dx, dy, dz, x, y, z; int cntx, cnty, cntz; cntx = ceil((max.x - min.x - offs.x) / spacing); cntz = ceil((max.z - min.z - offs.z) / spacing); int holeSize1 = 4, holeSize2 = 4;//10*spacing as size int cnt = cntx * cntz; int xp, yp, zp, c2; float odd; dx = max.x - min.x; dy = max.y - min.y; dz = max.z - min.z; float distance1; c2 = cnt / 2; float xcenter = max.x - dx / 2; float ycenter = max.y - dy / 2; float zcenter = max.z - dz / 2; int xindex, zindex; float omega = 0.0; float rx, ry; //float radius = 81 * spacing*spacing; float radius = pow(min(dx, dz) / 6, 2); float2 center = make_float2(min.x + dx / 2, min.z + dz / 2); center.x += (type - 4)*dx / 4; center.y += (type - 4)*dz / 4; for (float y = min.y + offs.y; y <= max.y; y += spacing) { for (int xz = 0; xz < cnt; xz++) { x = min.x + offs.x + (xz % int(cntx))*spacing; z = min.z + offs.z + (xz / int(cntx))*spacing; //xindex = ceil((x - min.x - offs.x) / spacing); //zindex = ceil((z - min.z - offs.z) / spacing); xindex = xz%cntx; zindex = xz / cntx; //round //if (pow(x - center.x, 2) + pow(z - center.y, 2) < radius) // continue; if (!((xindex +type) % holeSize1 == 0 || (zindex +type) % holeSize2 == 0)) { distance1 = min(x - min.x, z - min.z); distance1 = min(max.x - x, distance1); distance1 = min(max.z - z, distance1); if (distance1 > 2*spacing) continue; } //if (pow(x - xcenter, 2) + pow(z - zcenter, 2) < radius) // continue; p = AddParticle(); if (p != -1) { n++; (mPos + p)->Set(x, y, z); *(mClr + p) = COLORA(1, 0, 1, 1); // (x-min.x)/dx //*(m_alpha + p*MAX_FLUIDNUM + type) = 1.0f; *(m_alpha_pre + p*MAX_FLUIDNUM + type) = 1.0f; *(m_restMass + p) = m_fluidPMass[0]; *(m_restDensity + p) = m_fluidDensity[0]; *(m_visc + p) = m_fluidVisc[0]; *(MF_type + p) = type; *(mIsBound + p) = 1; rx = x - xcenter; ry = y - ycenter; } } } printf("%d fluid has %d particles\n", 0, n); return n; } int FluidSystem::SetupMfAddSolidSolid(Vector3DF min, Vector3DF max, float spacing, Vector3DF offs, int type) { Vector3DF pos; int n = 0, p; float dx, dy, dz, x, y, z; int cntx, cnty, cntz; cntx = ceil((max.x - min.x - offs.x) / spacing); cntz = ceil((max.z - min.z - offs.z) / spacing); int holeSize = 3;//10*spacing as size int cnt = cntx * cntz; int xp, yp, zp, c2; float odd; dx = max.x - min.x; dy = max.y - min.y; dz = max.z - min.z; c2 = cnt / 2; float xcenter = max.x - dx / 2; float ycenter = max.y - dy / 2; int xindex, zindex; float omega = 0.0; float rx, ry; float radius2 = pow(min(dx, dz) / 2, 2); float2 center = make_float2(min.x + dx / 2, min.z + dz / 2); for (float y = min.y + offs.y; y <= max.y; y += spacing) { for (int xz = 0; xz < cnt; xz++) { x = min.x + offs.x + (xz % int(cntx))*spacing; z = min.z + offs.z + (xz / int(cntx))*spacing; //xindex = ceil((x - min.x - offs.x) / spacing); //zindex = ceil((z - min.z - offs.z) / spacing); //xindex = xz%cntx; //zindex = xz / cntx; //if (!(xindex % holeSize == 0 || zindex % holeSize == 0)) // continue; p = AddParticle(); if (p != -1) { n++; (mPos + p)->Set(x, y, z); *(mClr + p) = COLORA(1, 0, 1, 1); // (x-min.x)/dx //*(m_alpha + p*MAX_FLUIDNUM + type) = 1.0f; *(m_alpha_pre + p*MAX_FLUIDNUM + type) = 1.0f; *(m_restMass + p) = m_fluidPMass[0]; *(m_restDensity + p) = m_fluidDensity[0]; *(m_visc + p) = m_fluidVisc[0]; *(MF_type + p) = 3; *(mIsBound + p) = 1; //rx = x - xcenter; //ry = y - ycenter; } } } printf("Solid solid has %d particles\n", n); return n; } int FluidSystem::SetupBoundary(Vector3DF min, Vector3DF max, float spacing, Vector3DF offs, int cat) { Vector3DF pos; int n = 0, p; float dx, dy, dz, x, y, z; int cntx, cnty, cntz; cntx = ceil((max.x - min.x - offs.x) / spacing); cntz = ceil((max.z - min.z - offs.z) / spacing); int cnt = cntx * cntz; int xp, yp, zp, c2; float odd; if (cat >= m_Param[FLUID_CATNUM])return n; dx = max.x - min.x; dy = max.y - min.y; dz = max.z - min.z; c2 = cnt / 2; float distance1,distance2,distance3; for (float y = min.y + offs.y; y <= max.y; y += spacing) { for (int xz = 0; xz < cnt; xz++) { x = min.x + offs.x + (xz % int(cntx))*spacing; z = min.z + offs.z + (xz / int(cntx))*spacing; distance1 = min(x - min.x, z - min.z); distance2 = min(max.x-x, y - min.y); distance3 = min(max.z - z, distance1); distance3 = min(distance3, distance2); //distance1 = max.y - y; //distance3 = min(distance3, distance1); if (distance3 > 1.8*spacing) continue; /*if ( xy < c2 ) { zp = xy / int(dx); x = min.x+offs + (xz % int(cntx/2) )*spacing*2 + (zp % 2)*spacing; z = min.z+offs + zp * spacing; } else { zp = (xy-c2) / int(dx); x = min.x+offs + ( (xz-c2) % int(cntx/2) )*spacing*2 + (zp % 2)*spacing; z = min.z+offs + (cntz-1-zp) * spacing; }*/ p = AddParticle(); if (p != -1) { //if (y > 50) // cout << "y is " << y << endl; n++; (mPos + p)->Set(x, y, z); //*(mClr + p) = COLORA(0.25, +0.25 + (y - min.y)*.75 / dy, 0.25 + (z - min.z)*.75 / dz, 1); // (x-min.x)/dx *(mIsBound + p) = 1; *(m_restMass + p) = m_Param[PBMASS]; *(m_restDensity + p) = m_Param[PBRESTDENSITY]; *(m_visc + p) = m_Param[PBVISC]; *(MF_type + p) = 1; } } } return n; } int FluidSystem::SetupMfAddCylinder(Vector3DF min, Vector3DF max, float spacing, Vector3DF offs, int type) { Vector3DF pos; int n = 0, p; float dx, dy, dz, x, y, z; int cntx, cnty, cntz; cntx = ceil((max.x - min.x - offs.x) / spacing); cntz = ceil((max.z - min.z - offs.z) / spacing); int cnt = cntx * cntz; int xp, yp, zp, c2; float odd; dx = max.x - min.x; dy = max.y - min.y; dz = max.z - min.z; c2 = cnt / 2; float xcenter = max.x - dx / 2; float ycenter = max.y - dy / 2; float omega = 0.0; float rx, ry; float radius2 = pow(min(dx, dz) / 2,2); float2 center = make_float2(min.x + dx / 2, min.z + dz / 2); for (float y = min.y + offs.y; y <= max.y; y += spacing) { for (int xz = 0; xz < cnt; xz++) { x = min.x + offs.x + (xz % int(cntx))*spacing; z = min.z + offs.z + (xz / int(cntx))*spacing; if (pow(x - center.x, 2) + pow(z - center.y, 2) > radius2) continue; p = AddParticle(); if (p != -1) { *(elasticID + p) = n; n++; (mPos + p)->Set(x, y, z); *(mClr + p) = COLORA(1,0,1,1); // (x-min.x)/dx *(m_alpha + p*MAX_FLUIDNUM + type) = 1.0f; *(m_alpha_pre + p*MAX_FLUIDNUM + type) = 1.0f; *(m_restMass + p) = m_fluidPMass[0]; *(m_restDensity + p) = m_fluidDensity[0]; *(m_visc + p) = m_fluidVisc[0]; *(MF_type + p) = 1; //1 means deformable rx = x - xcenter; ry = y - ycenter; //mVel[p].Set( ry*omega, -rx*omega, 0); //mVelEval[p].Set( ry*omega, -rx*omega,0); //mVel[p].Set( -0.4, 0, 0); //mVelEval[p].Set( -0.4, 0,0); /* if(mPos[p].y>15){ (mVel + p)->Set ( 0,-0.4,0.4 ); (mVelEval + p)->Set ( 0,-0.4,0.4 ); } else{ (mVel + p)-> Set ( 0,-0.4,0 ); (mVelEval + p)->Set ( 0,-0.4,0 ); }*/ } } } printf("%d fluid has %d particles\n", 0, n); return n; } void FluidSystem::liftup(int mode){ floatup_cuda(mode); printf("Frame: %d liftmode: %d\n", m_Frame, mode); } void FluidSystem::saveParticle(std::string name) { TransferFromCUDAForLoad(); FILE* fp; int n = 0; for (int i = 0;i<NumPoints();i++) if (mIsBound[i] == 0 && mPos[i].x>-500) n++; fp = fopen(name.c_str(),"w"); fprintf(fp,"%d\n",n); Vector3DF* ppos = mPos; for (int i = 0;i<NumPoints();i++,ppos++) if (mIsBound[i] == 0 && mPos[i].x>-500) { fprintf(fp,"%f %f %f\n",ppos->x,ppos->y,ppos->z); //for (int j = 0;j<MAX_FLUIDNUM;j++) //{ // fprintf(fp," %f",*(m_alpha+i*MAX_FLUIDNUM + j)); // fprintf(fp," %f",*(m_alpha_pre+i*MAX_FLUIDNUM + j)); //} //fprintf(fp," %f",m_restMass[i]); //fprintf(fp," %f",m_restDensity[i]); //fprintf(fp," %f",m_visc[i]); //fprintf(fp," %f %f %f",mVel[i].x, mVel[i].y, mVel[i].z); //fprintf(fp," %f %f %f",mVelEval[i].x, mVelEval[i].y, mVelEval[i].z); //fprintf(fp," %d",MF_type[i]); } fclose(fp); SetYan(SAVE_STAT,0); } int FluidSystem::loadParticle(std::string name) { int n,p; float f1,f2,f3; FILE* fp; fp = fopen(name.c_str(),"r"); fscanf(fp,"%d",&n); Vector3DF* ppos = mPos; for (int i = 0;i<n;i++) { p = AddParticle(); // the index of the added particle if (p!=-1) { fscanf(fp,"%f %f %f",&f1,&f2,&f3); (mPos +p)->Set(f1,f2,f3); *(m_alpha + p*MAX_FLUIDNUM + 3) = 1.0f; *(m_alpha_pre + p*MAX_FLUIDNUM + 3) = 1.0f; *(m_restMass + p) = m_fluidPMass[3]; *(m_restDensity + p) = m_fluidDensity[3]; *(m_visc + p) = m_fluidVisc[3]; *(MF_type+p) = 0; //for (int j = 0;j<MAX_FLUIDNUM;j++) //{ // fscanf(fp,"%f",(m_alpha+p*MAX_FLUIDNUM + j)); // fscanf(fp,"%f",(m_alpha_pre+p*MAX_FLUIDNUM + j)); //} //fscanf(fp,"%f",m_restMass+p); //fscanf(fp,"%f",m_restDensity+p); //fscanf(fp,"%f",m_visc+p); //fscanf(fp," %f %f %f",&mVel[i].x, &mVel[i].y, &mVel[i].z); //fscanf(fp," %f %f %f",&mVelEval[i].x, &mVelEval[i].y, &mVelEval[i].z); //mVel[i].x = mVel[i].y = mVel[i].z = 0; //mVelEval[i].x = mVelEval[i].y = mVelEval[i].z = 0; //fscanf(fp,"%d",&MF_type[i]); //*(mClr+p) = COLORA( 1,1,1,1); } } fclose(fp); //saveParticle("fluids_exa2.dat"); return n; } int FluidSystem::SetupAddMonster(BI2Reader bi2reader, int type, int cat) { //printf("%f %f %f %f\n", m_Param[PBMASS], m_Param[PBRESTDENSITY], m_Param[PBVISC], m_Param[PBSTIFF]); float x, y, z, n = 0; for (int i = 0; i<bi2reader.info.nbound; i++) { x = bi2reader.info.Pos[i].x / m_Param[PSIMSCALE]; y = bi2reader.info.Pos[i].y / m_Param[PSIMSCALE]; z = bi2reader.info.Pos[i].z / m_Param[PSIMSCALE]; if (x < m_Vec[PVOLMIN].x || x>m_Vec[PVOLMAX].x || y<m_Vec[PVOLMIN].y || y> m_Vec[PVOLMAX].y || z<m_Vec[PVOLMIN].z || z>m_Vec[PVOLMAX].z) continue; int p = AddParticle(); if (p != -1) { (mPos + p)->Set(bi2reader.info.Pos[i].x / m_Param[PSIMSCALE]-25, bi2reader.info.Pos[i].y / m_Param[PSIMSCALE]-25, bi2reader.info.Pos[i].z / m_Param[PSIMSCALE]+25); *(mClr + p) = COLORA(1, 1, 1, 0); *(mIsBound + p) = false; *(m_restMass + p) = m_Param[PBMASS]; *(m_restDensity + p) = m_fluidDensity[cat]; *(m_visc + p) = m_fluidVisc[cat]; *(MF_type + p) = type;//which means rigid (project-u) *(m_alpha + p*MAX_FLUIDNUM + cat) = 1.0f; *(m_alpha_pre + p*MAX_FLUIDNUM + cat) = 1.0f; n++; } } return n; } #ifdef NEW_BOUND void FluidSystem::SetupAddBound(BI2Reader bi2reader,int boundtype) { printf("%f %f %f %f\n",m_Param[PBMASS],m_Param[PBRESTDENSITY],m_Param[PBVISC],m_Param[PBSTIFF]); float x,y,z; for (int i = 0;i<bi2reader.info.nbound;i++) { x = bi2reader.info.Pos[i].x/m_Param[PSIMSCALE]; y = bi2reader.info.Pos[i].y/m_Param[PSIMSCALE]; z = bi2reader.info.Pos[i].z/m_Param[PSIMSCALE]; if( x < m_Vec[PVOLMIN].x || x>m_Vec[PVOLMAX].x || y<m_Vec[PVOLMIN].y || y> m_Vec[PVOLMAX].y || z<m_Vec[PVOLMIN].z || z>m_Vec[PVOLMAX].z) continue; int p = AddParticle(); if (p!=-1) { (mPos+p)->Set (bi2reader.info.Pos[i].x/m_Param[PSIMSCALE],bi2reader.info.Pos[i].y/m_Param[PSIMSCALE],bi2reader.info.Pos[i].z/m_Param[PSIMSCALE]); *(mClr+p) = COLORA(1,1,1,0); *(mIsBound+p) = boundtype; *(m_restMass+p) = m_Param[PBMASS]; *(m_restDensity+p) = m_Param[PBRESTDENSITY]; *(m_visc+p) = m_Param[PBVISC]; *(MF_type+p) = 2;//which means rigid (project-u) } } } #endif //void FluidSystem::MfTestSetupExample () //{ // example= _example; // m_Param[PEXAMPLE] = example; // printf("here we have example %d\n",example); // ParseXML_Bound("BoundInfo",example); // // //load boundary and special models // // BI2Reader* bi2readers[10]; //ten pointers to build bi2reader dynamically, in use now // char biname[200]; // switch(example){ //#ifdef NEW_BOUND // case 1: // sprintf(biname,".\\extra_particles\\Boundary1.bi2"); // bi2readers[0] = new BI2Reader(biname); // bi2readers[0]->GetInfo(false); // bi2readers[0]->PrintInfo(); // break; // case 12: // sprintf(biname,".\\extra_particles\\Boundary12.bi2"); // bi2readers[0] = new BI2Reader(biname); // bi2readers[0]->GetInfo(false); // bi2readers[0]->PrintInfo(); // break; //#endif // case 2: // sprintf(biname,".\\extra_particles\\monster2.bi2"); // bi2readers[0] = new BI2Reader(biname); // bi2readers[0]->GetInfo(false); // bi2readers[0]->PrintInfo(); // break; // } // double particleVisc = m_Param[PVISC]; // // //parse the xml and adjust some parameters according to scaleP // ParseMFXML ( "MultiScene", example, true ); // // // //adjust the parametres according to the scale parameter // scaleP3 = pow(scaleP,1.0/3.0); // m_Param[PMASS]/=scaleP; //#ifdef NEW_BOUND // m_Param[PBMASS]/=scaleP; //#endif // m_Param[PSMOOTHRADIUS]/=scaleP3; // m_Param[PRADIUS]/=scaleP3; // m_Param [PNUM]*=scaleP; // // //Add the number of boundary or monster to PNUM // switch(example){ //#ifdef NEW_BOUND // case 1: // m_Param[PNUM] += bi2readers[0]->info.nbound; //boundary particles // break; // case 12: // m_Param[PNUM] += bi2readers[0]->info.nbound; //boundary particles // break; // case 2: // m_Param[PNUM] += bi2readers[0]->info.nbound;//monster // break; // } //#endif // m_Param [PGRIDSIZE] = 2*m_Param[PSMOOTHRADIUS] / m_Param[PGRID_DENSITY]; // // m_fluidPMass[0] = m_Param[PMASS]*massRatio.x; // m_fluidPMass[1] = m_Param[PMASS]*massRatio.y; // m_fluidPMass[2] = m_Param[PMASS]*massRatio.z; // m_fluidDensity[0] = 600.0*densityRatio.x; // m_fluidDensity[1] = 600.0*densityRatio.y; // m_fluidDensity[2] = 600.0*densityRatio.z; // m_fluidVisc[0] = particleVisc*viscRatio.x; // m_fluidVisc[1] = particleVisc*viscRatio.y; // m_fluidVisc[2] = particleVisc*viscRatio.z; // if(m_Param[FLUID_CATNUM]>3){ // m_fluidPMass[3] = m_Param[PMASS]*massRatio.w; // m_fluidDensity[3] = 600.0*densityRatio.w; // m_fluidVisc[3] = particleVisc*viscRatio.w; // } // // //Allocate buffer and setup the kernels and spacing // AllocateParticles ( m_Param[PNUM] ); // AllocatePackBuf (); // SetupKernels (); // SetupSpacing (); // // //Add fluid particles // if (loadwhich == 0) // { // switch(example){ // case 1: // m_Vec [ PINITMIN ].Set (volumes[0].x,volumes[0].y,volumes[0].z); // m_Vec [ PINITMAX ].Set (volumes[1].x,volumes[1].y,volumes[1].z); // SetupMfAddVolume ( m_Vec[PINITMIN], m_Vec[PINITMAX], m_Param[PSPACING], Vector3DF(0,0.1,0),0); // // m_Vec [ PINITMIN ].Set (volumes[2].x,volumes[2].y,volumes[2].z); // m_Vec [ PINITMAX ].Set (volumes[3].x,volumes[3].y,volumes[3].z); // SetupMfAddVolume ( m_Vec[PINITMIN], m_Vec[PINITMAX], m_Param[PSPACING], Vector3DF(0,0.1,0),1); // // m_Vec [ PINITMIN ].Set (volumes[4].x,volumes[4].y,volumes[4].z); // m_Vec [ PINITMAX ].Set (volumes[5].x,volumes[5].y,volumes[5].z); // SetupMfAddVolume ( m_Vec[PINITMIN], m_Vec[PINITMAX], m_Param[PSPACING], Vector3DF(0,0.1,0),2); // break; // case 11: // m_Vec [ PINITMIN ].Set (volumes[0].x,volumes[0].y,volumes[0].z); // m_Vec [ PINITMAX ].Set (volumes[1].x,volumes[1].y,volumes[1].z); // SetupMfAddVolume ( m_Vec[PINITMIN], m_Vec[PINITMAX], m_Param[PSPACING], Vector3DF(0,0.1,0),0); // // m_Vec [ PINITMIN ].Set (volumes[2].x,volumes[2].y,volumes[2].z); // m_Vec [ PINITMAX ].Set (volumes[3].x,volumes[3].y,volumes[3].z); // SetupMfAddVolume ( m_Vec[PINITMIN], m_Vec[PINITMAX], m_Param[PSPACING], Vector3DF(0,0.1,0),1); // // m_Vec [ PINITMIN ].Set (volumes[4].x,volumes[4].y,volumes[4].z); // m_Vec [ PINITMAX ].Set (volumes[5].x,volumes[5].y,volumes[5].z); // SetupMfAddVolume ( m_Vec[PINITMIN], m_Vec[PINITMAX], m_Param[PSPACING], Vector3DF(0,0.1,0),2); // break; // case 12: // m_Vec [ PINITMIN ].Set (volumes[0].x,volumes[0].y,volumes[0].z); // m_Vec [ PINITMAX ].Set (volumes[1].x,volumes[1].y,volumes[1].z); // SetupMfAddVolume ( m_Vec[PINITMIN], m_Vec[PINITMAX], m_Param[PSPACING], Vector3DF(0,0.1,0),0); // // m_Vec [ PINITMIN ].Set (volumes[2].x,volumes[2].y,volumes[2].z); // m_Vec [ PINITMAX ].Set (volumes[3].x,volumes[3].y,volumes[3].z); // SetupMfAddVolume ( m_Vec[PINITMIN], m_Vec[PINITMAX], m_Param[PSPACING], Vector3DF(0,0.1,0),1); // // m_Vec [ PINITMIN ].Set (volumes[4].x,volumes[4].y,volumes[4].z); // m_Vec [ PINITMAX ].Set (volumes[5].x,volumes[5].y,volumes[5].z); // SetupMfAddVolume ( m_Vec[PINITMIN], m_Vec[PINITMAX], m_Param[PSPACING], Vector3DF(0,0.1,0),2); // break; // } // } // else{ //load from file // switch(example){ // case 2: // mMaxPoints = loadParticle(".\\save\\save_stat2.txt"); // break; // case 3: // mMaxPoints = loadParticle(".\\save\\save_stat3.txt"); // break; // case 5: // mMaxPoints = loadParticle(".\\save\\save_stat5.txt"); // //mMaxPoints += 32767*scaleP; // break; // } // } // // //Add particles of boundary or extra models // // switch(example){ //#ifdef NEW_BOUND // case 1: // //mMaxPoints += bi2readers[0]->info.nbound; // //SetupAddBound(*bi2readers[0],1); // break; // case 12: // //mMaxPoints += bi2readers[0]->info.nbound; // SetupAddBound(*bi2readers[0],1); // break; //#endif // case 2: // //mMaxPoints += bi2readers[0]->info.np; // SetupAddShape(*bi2readers[0],1); // break; // } // m_maxAllowedPoints = mNumPoints * EMIT_BUF_RATIO; // // //set emit parametres // if(example==5){ // m_maxAllowedPoints += 32767*scaleP; // m_Vec[PEMIT_RATE] = Vector3DF(5,256,25); // m_Vec[PEMIT_SPREAD] = Vector3DF(0,0,0); // m_Vec[PEMIT_ANG] = Vector3DF(0,135,2); // m_Vec[PEMIT_POS] = Vector3DF(0,60,0); // } // else{ // //Emit Params // m_Vec[PEMIT_RATE] = Vector3DF(1.1,9,0); // m_Vec[PEMIT_SPREAD] = Vector3DF(0,0,0); // m_Vec[PEMIT_ANG] = Vector3DF(0,180,1); // m_Vec[PEMIT_POS] = Vector3DF(0,60,30); // } //} void FluidSystem::SetupAddShape(BI2Reader bi2reader,int cat) { printf("%f %f %f %f\n",m_Param[PBMASS],m_Param[PBRESTDENSITY],m_Param[PBVISC],m_Param[PBSTIFF]); for (int i = 0;i<bi2reader.info.np;i++) { int p = AddParticle(); if (p!=-1) { // printf("%f %f %f\n",bi2reader.info.Pos[i].x/m_Param[PSIMSCALE],bi2reader.info.Pos[i].y/m_Param[PSIMSCALE],bi2reader.info.Pos[i].z/m_Param[PSIMSCALE]); (mPos+p)->Set (bi2reader.info.Pos[i].x/m_Param[PSIMSCALE],bi2reader.info.Pos[i].y/m_Param[PSIMSCALE],bi2reader.info.Pos[i].z/m_Param[PSIMSCALE]); *(mClr+p) = COLORA(1,1,1,1); *(m_alpha+p*MAX_FLUIDNUM+cat) = 1.0f;*(m_alpha_pre+p*MAX_FLUIDNUM+cat) = 1.0f; *(m_restMass+p) = m_fluidPMass[cat]; *(m_restDensity+p) = m_fluidDensity[cat]; *(m_visc+p) = m_fluidVisc[cat]; *(mIsBound+p) = 2; *(MF_type+p) = 1; //which means deformable (project-u) } } } void FluidSystem::EmitMfParticles (int cat) { mMaxPoints = mNumPoints; int currentPoints = mMaxPoints; if ( m_Vec[PEMIT_RATE].x > 0 && (m_Frame) % (int) m_Vec[PEMIT_RATE].x == 0 ) { float ss = m_Param [ PDIST ] / m_Param[ PSIMSCALE ]; // simulation scale (not Schutzstaffel) AddMfEmit ( ss, cat ); } EmitUpdateCUDA(currentPoints,mMaxPoints); } void FluidSystem::AddMfEmit ( float spacing, int cat ) { int p; Vector3DF dir; Vector3DF pos; float ang_rand, tilt_rand; //float rnd = m_Vec[PEMIT_RATE].y * 0.15; int x = (int) sqrt(m_Vec[PEMIT_RATE].y); int offset = m_Vec[PEMIT_RATE].y/x; for ( int n = 0; n < m_Vec[PEMIT_RATE].y; n++ ) { float zOffset = -spacing * (float)(offset) * 0.5 + spacing * (n/x); float xOffset = -spacing * (float)(offset) * 0.5 + spacing * (n%x); if(zOffset*zOffset+xOffset*xOffset>m_Vec[PEMIT_RATE].z) continue; ang_rand = (float(rand()*2.0/RAND_MAX) - 1.0) * m_Vec[PEMIT_SPREAD].x; tilt_rand = (float(rand()*2.0/RAND_MAX) - 1.0) * m_Vec[PEMIT_SPREAD].y; dir.z = cos ( ( m_Vec[PEMIT_ANG].x + ang_rand) * DEGtoRAD ) * sin( ( m_Vec[PEMIT_ANG].y + tilt_rand) * DEGtoRAD ) * m_Vec[PEMIT_ANG].z; dir.x = sin ( ( m_Vec[PEMIT_ANG].x + ang_rand) * DEGtoRAD ) * sin( ( m_Vec[PEMIT_ANG].y + tilt_rand) * DEGtoRAD ) * m_Vec[PEMIT_ANG].z; dir.y = cos ( ( m_Vec[PEMIT_ANG].y + tilt_rand) * DEGtoRAD ) * m_Vec[PEMIT_ANG].z; //original position //pos = m_Vec[PEMIT_POS]; //pos.z += spacing * (n/x); //pos.x += spacing * (n%x); pos = Vector3DF(xOffset,0,zOffset); ////rotate \theta around a=(-sin \phi, cos \phi, 0), axis order z->x->y Vector3DF rotateAxis = Vector3DF(cos(m_Vec[PEMIT_ANG].x*DEGtoRAD),0.0,-sin(m_Vec[PEMIT_ANG].x*DEGtoRAD)); Vector3DF finalpos; float A1[3][3],A2[3][3],M[3][3]; A1[0][0]=rotateAxis.x*rotateAxis.x;A1[0][1]=A1[1][0]=rotateAxis.x*rotateAxis.y;A1[0][2]=A1[2][0]=rotateAxis.x*rotateAxis.z; A1[1][1]=rotateAxis.y*rotateAxis.y;A1[1][2]=A1[2][1]=rotateAxis.y*rotateAxis.z;A1[2][2]=rotateAxis.z*rotateAxis.z; A2[0][0]=A2[1][1]=A2[2][2]=0.0;A2[0][1]=rotateAxis.z;A2[1][0]=-rotateAxis.z; A2[0][2]=-rotateAxis.y;A2[2][0]=rotateAxis.y;A2[1][2]=rotateAxis.x;A2[2][1]=-rotateAxis.x; float costheta=cos(m_Vec[PEMIT_ANG].y*DEGtoRAD); float sintheta=sin(m_Vec[PEMIT_ANG].y*DEGtoRAD); M[0][0]=A1[0][0]+(1-A1[0][0])*costheta+A2[0][0]*sintheta; M[0][1]=A1[0][1]+(0-A1[0][1])*costheta+A2[0][1]*sintheta; M[0][2]=A1[0][2]+(0-A1[0][2])*costheta+A2[0][2]*sintheta; M[1][0]=A1[1][0]+(0-A1[1][0])*costheta+A2[1][0]*sintheta; M[1][1]=A1[1][1]+(1-A1[1][1])*costheta+A2[1][1]*sintheta; M[1][2]=A1[1][2]+(0-A1[1][2])*costheta+A2[1][2]*sintheta; M[2][0]=A1[2][0]+(0-A1[2][0])*costheta+A2[2][0]*sintheta; M[2][1]=A1[2][1]+(0-A1[2][1])*costheta+A2[2][1]*sintheta; M[2][2]=A1[2][2]+(1-A1[2][2])*costheta+A2[2][2]*sintheta; finalpos.x=pos.x*M[0][0]+pos.y*M[1][0]+pos.z*M[2][0]; finalpos.y=pos.x*M[0][1]+pos.y*M[1][1]+pos.z*M[2][1]; finalpos.z=pos.x*M[0][2]+pos.y*M[1][2]+pos.z*M[2][2]; pos=finalpos+m_Vec[PEMIT_POS]; //// if(mMaxPoints<m_maxAllowedPoints) { mMaxPoints++; p = AddParticle (); *(mPos+p) = pos; *(mVel+p) = dir; *(mVelEval+p) = dir; *(mAge+p) = 0; *(mClr+p) = COLORA ( m_Time/10.0, m_Time/5.0, m_Time /4.0, 1 ); *(m_alpha+p*MAX_FLUIDNUM+cat) = 1.0f;*(m_alpha_pre+p*MAX_FLUIDNUM+cat) = 1.0f; *(m_restMass+p) = m_fluidPMass[cat]; *(m_restDensity+p) = m_fluidDensity[cat]; *(m_visc+p) = m_fluidVisc[cat]; *(mIsBound+p) = 0; *(MF_type+p) = 0; //which means liquid } } } void FluidSystem::EmitUpdateCUDA (int startnum, int endnum) { int numpoints = endnum - startnum; #ifdef NEW_BOUND CopyEmitToCUDA ( (float*) mPos, (float*) mVel, (float*) mVelEval, (float*) mForce, mPressure, mDensity, mClusterCell, mGridNext, (char*) mClr, startnum, numpoints , mIsBound); #else CopyEmitToCUDA ( (float*) mPos, (float*) mVel, (float*) mVelEval, (float*) mForce, mPressure, mDensity, mClusterCell, mGridNext, (char*) mClr, startnum, numpoints ); #endif CopyEmitMfToCUDA ( m_alpha, m_alpha_pre, m_pressure_modify, (float*) m_vel_phrel, m_restMass, m_restDensity, m_visc, (float*)m_velxcor, (float*)m_alphagrad, startnum, numpoints); UpdatePNumCUDA(endnum); cudaThreadSynchronize (); } int findNearestV(PIC* bunny, float x, float y, float z) { float minD = 100000000; float distance; int index = -1; for (int i = 0; i < bunny->V.size(); ++i) { distance = pow(x - bunny->V[i].X, 2) + pow(y - bunny->V[i].Y, 2) + pow(z - bunny->V[i].Z, 2); if (distance <minD) { index = i; minD = distance; } } return index; } int FluidSystem::SetupModel(PIC* bunny, float spacing, int type, Vector3DF displacement) { Vector3DF pos; int n = 0, p; float x, y, z; int cntx, cnty, cntz; int index; cntx = ceil((bunny->maxPos.X - bunny->minPos.X) / spacing); cntz = ceil((bunny->maxPos.Z - bunny->minPos.Z) / spacing); int cnt = cntx * cntz; int xp, yp, zp, c2; float odd; c2 = cnt / 2; for (float y = bunny->minPos.Y; y <= bunny->maxPos.Y; y += spacing) { for (int xz = 0; xz < cnt; xz++) { x = bunny->minPos.X + (xz % int(cntx))*spacing; z = bunny->minPos.Z + (xz / int(cntx))*spacing; index = findNearestV(bunny, x, y, z); /*printf("pos is (%f,%f,%f), nearest point is (%f,%f,%f), index is %d\n", x, y, z, bunny->V[index].X, bunny->V[index].Y, bunny->V[index].Z, index);*/ if (bunny->VN[index].NX*(bunny->V[index].X - x) + bunny->VN[index].NY*(bunny->V[index].Y - y) + bunny->VN[index].NZ*(bunny->V[index].Z - z) < 0) continue; p = AddParticle(); if (p != -1) { //dist = sqrt(pow(zcenter - z, 2) + pow(xcenter - x, 2) + pow(ycenter - y, 2)); *(elasticID + p) = n; (mPos + p)->Set(x+displacement.x, y+ displacement.y, z+ displacement.z); *(m_alpha + p*MAX_FLUIDNUM + type) = 1.0f; *(m_alpha_pre + p*MAX_FLUIDNUM + type) = 1.0f; *(m_restMass + p) = m_fluidPMass[0]; *(m_restDensity + p) = m_fluidDensity[0]; *(m_visc + p) = m_fluidVisc[0]; *(mIsBound + p) = false; *(MF_type + p) = 1; //1 means deformable *(porosity_particle + n) = porosity; n++; } } } return n; } int FluidSystem::SetupMfAddDeformVolume ( Vector3DF min, Vector3DF max, float spacing, Vector3DF offs, int type ) { Vector3DF pos; int n = 0, p; float dx, dy, dz, x, y, z; int cntx, cnty, cntz; cntx = ceil( (max.x-min.x-offs.x) / spacing ); cntz = ceil( (max.z-min.z-offs.z) / spacing ); int cnt = cntx * cntz; int xp, yp, zp, c2; float odd; dx = max.x-min.x; dy = max.y-min.y; dz = max.z-min.z; c2 = cnt/2; float radius = min(dz/2, min(dx/2, dy/2)); radius = radius * radius; float xcenter = max.x - dx/2; float ycenter = max.y - dy/2; float zcenter = max.z - dz / 2; float omega = 0.0; float rx,ry; float d[6]; Vector3DF dist; for (float y = min.y+offs.y; y <= max.y; y += spacing ) { for (int xz=0; xz < cnt; xz++ ) { x = min.x+offs.x + (xz % int(cntx))*spacing; z = min.z+offs.z + (xz / int(cntx))*spacing; if (pow(x - xcenter, 2) + pow(y - ycenter, 2) + pow(z - zcenter, 2) > radius) continue; p = AddParticle (); if ( p != -1 ) { //dist = sqrt(pow(zcenter - z, 2) + pow(xcenter - x, 2) + pow(ycenter - y, 2)); *(elasticID + p) = n; d[0] = x - min.x; d[1] = y - min.y; d[2] = z - min.z; d[3] = max.x - x; d[4] = max.y - y; d[5] = max.z - z; if (d[0] < d[3])dist.x = -d[0]; else dist.x = d[3]; if (d[1] < d[4])dist.y = -d[1]; else dist.y = d[4]; if (d[2] < d[5])dist.z = -d[2]; else dist.z = d[5]; //假设现在只有一个固体 (signDistance + n)->Set(dist.x,dist.y,dist.z); (mPos+p)->Set ( x,y,z); *(mClr+p) = COLORA( 0.25, +0.25 + (y-min.y)*.75/dy, 0.25 + (z-min.z)*.75/dz, 1); // (x-min.x)/dx *(m_alpha+p*MAX_FLUIDNUM+type) = 1.0f;*(m_alpha_pre+p*MAX_FLUIDNUM+type) = 1.0f; *(m_restMass+p) = m_fluidPMass[0]; *(m_restDensity+p) = m_fluidDensity[0]; *(m_visc+p) = m_fluidVisc[0]; *(mIsBound + p) = false; // *(MF_type + p) = 3;//3 means ghost elastic particles //else *(MF_type+p) = 2; //1 means deformable //omega = porosity * radius / (0.01*radius + dist); //if (omega > 0.95) // omega = 0.95; *(porosity_particle + n) = porosity; /**(misGhost + n) = 0; if (x == min.x + offs.x || y == min.y + offs.y || z == min.z + offs.z) *(misGhost + n) = 1; if (x + spacing >= max.x || y + spacing >= max.y || z + spacing >= max.z) *(misGhost + n) = 1;*/ rx = x - xcenter; ry = y - ycenter; n++; } } } printf("%d elastic solid has %d particles\n",0,n); return n; } int FluidSystem::SetupMfAddSphere(Vector3DF min, Vector3DF max, float spacing, Vector3DF offs, int type) { Vector3DF pos; int n = 0, p; int id = numElasticPoints; float dx, dy, dz, x, y, z; int cntx, cnty, cntz; cntx = ceil((max.x - min.x - offs.x) / spacing); cntz = ceil((max.z - min.z - offs.z) / spacing); int cnt = cntx * cntz; int xp, yp, zp, c2; float odd; dx = max.x - min.x; dy = max.y - min.y; dz = max.z - min.z; c2 = cnt / 2; float xcenter = max.x - dx / 2; float ycenter = max.y - dy / 2; float zcenter = max.z - dz / 2; float omega = 0.0; float rx, ry; float radius = min(dx, dz); radius = min(radius, dy); radius /= 2; float radius2 = pow(radius, 2); float3 center = make_float3(min.x + dx / 2, min.y + dy / 2, min.z + dz / 2); for (float y = min.y + offs.y; y <= max.y; y += spacing) { for (int xz = 0; xz < cnt; xz++) { x = min.x + offs.x + (xz % int(cntx))*spacing; z = min.z + offs.z + (xz / int(cntx))*spacing; if (pow(x - center.x, 2) + pow(z - center.z, 2) + pow(y - center.y, 2) > radius2) continue; p = AddParticle(); if (p != -1) { *(elasticID + p) = id++; n++; (mPos + p)->Set(x, y, z); *(mClr + p) = COLORA(1, 0, 1, 1); // (x-min.x)/dx *(m_alpha + p*MAX_FLUIDNUM + 0) = 1.0f; *(m_alpha_pre + p*MAX_FLUIDNUM + 0) = 1.0f; *(m_restMass + p) = m_fluidPMass[0]; *(m_restDensity + p) = m_fluidDensity[0]; *(m_visc + p) = m_fluidVisc[0]; *(MF_type + p) = type; //1 means deformable *(mIsBound + p) = 0; rx = x - xcenter; ry = y - ycenter; //mVel[p].Set( ry*omega, -rx*omega, 0); //mVelEval[p].Set( ry*omega, -rx*omega,0); //mVel[p].Set( -0.4, 0, 0); //mVelEval[p].Set( -0.4, 0,0); /* if(mPos[p].y>15){ (mVel + p)->Set ( 0,-0.4,0.4 ); (mVelEval + p)->Set ( 0,-0.4,0.4 ); } else{ (mVel + p)-> Set ( 0,-0.4,0 ); (mVelEval + p)->Set ( 0,-0.4,0 ); }*/ } } } printf("%d fluid has %d particles\n", 0, n); return n; } int FluidSystem::SetupMfAddMagicWand(Vector3DF min, Vector3DF max, float spacing, Vector3DF offs) { Vector3DF pos; int n = 0, p; float dx, dy, dz, x, y, z; int cntx, cnty, cntz; cntx = ceil((max.x - min.x - offs.x) / spacing); cntz = ceil((max.z - min.z - offs.z) / spacing); int cnt = cntx * cntz; int xp, yp, zp, c2; float odd; dx = max.x - min.x; dy = max.y - min.y; dz = max.z - min.z; c2 = cnt / 2; float xcenter = min.x + dx / 4; float ycenter = min.y + dy / 4; float zcenter = min.z + dz / 4; float zcenter2 = max.z - dz / 2; float ycenter2 = max.y - dy / 2; float omega = 0.0; float rx, ry; float radius = min(dy / 2, dz / 2); //radius of cylinder float rc; //radius = min(radius, dy/2); //radius /= 2; rc = radius / 3; float radius2 = pow(radius, 2), rc2 = pow(rc, 2); float3 center = make_float3(min.x + radius, min.y + dy / 2, min.z + dz / 2); float3 center3 = make_float3(max.x - radius, max.y - dy / 2, max.z - dz / 2); int isSphere = true; for (float y = min.y + offs.y; y <= max.y; y += spacing) { for (int xz = 0; xz < cnt; xz++) { x = min.x + offs.x + (xz % int(cntx))*spacing; z = min.z + offs.z + (xz / int(cntx))*spacing; isSphere = true; if (x < min.x + 2 * radius) { if (pow(x-center.x,2) + pow(z - center.z, 2) + pow(y - center.y, 2) > radius2) { if (x > min.x + radius) { if (pow(z - zcenter2, 2) + pow(y - ycenter2, 2) > rc2) continue; else isSphere = false; } else continue; } } else { if (pow(z - zcenter2, 2) + pow(y - ycenter2, 2) > rc2 && pow(x-center3.x,2)+pow(y-center3.y,2)+pow(z-center3.z,2)>radius2) continue; else isSphere = false; } p = AddParticle(); if (p != -1) { *(elasticID + p) = n; n++; (mPos + p)->Set(x, y, z); *(mClr + p) = COLORA(1, 0, 1, 1); // (x-min.x)/dx *(m_alpha + p*MAX_FLUIDNUM + 0) = 1.0f; *(m_alpha_pre + p*MAX_FLUIDNUM + 0) = 1.0f; *(m_restMass + p) = m_fluidPMass[0]; *(m_restDensity + p) = m_fluidDensity[0]; *(m_visc + p) = m_fluidVisc[0]; if (isSphere) *(MF_type + p) = 5; //1 means deformable else *(MF_type + p) = 4; rx = x - xcenter; ry = y - ycenter; } } } printf("%d fluid has %d particles\n", 0, n); return n; } void FluidSystem:: setupSPHexample() { ParseXML_Bound("BoundInfo",1); example = _example; BI2Reader* bi2readers[10]; //ten pointers to build bi2reader dynamically, in use now char biname[200]; //parse the xml and adjust some parameters according to scaleP ParseMFXML ( "MultiScene", example, true ); double particleVisc = m_Param[PVISC]; //adjust the parametres according to the scale parameter scaleP3 = pow(scaleP,1.0/3.0); m_Param[PNUM] = 80000; m_Param[PMASS]/=scaleP; m_Param[PBMASS]/=scaleP; m_Param[PSMOOTHRADIUS]/=scaleP3; m_Param[PRADIUS]/=scaleP3; printf("scale P is %f, pnum is %d\n", scaleP, m_Param[PNUM]); m_Param [PNUM]*=scaleP; m_Param [PGRIDSIZE] = 2*m_Param[PSMOOTHRADIUS] / m_Param[PGRID_DENSITY]; m_fluidPMass[0] = m_Param[PMASS] * massRatio.x; m_fluidPMass[1] = m_Param[PMASS] * massRatio.y; m_fluidPMass[2] = m_Param[PMASS] * massRatio.z; m_fluidPMass[3] = m_Param[PMASS] * massRatio.w; m_fluidDensity[0] = 600.0*densityRatio.x; m_fluidDensity[1] = 600.0*densityRatio.y; m_fluidDensity[2] = 600.0*densityRatio.z; m_fluidDensity[3] = 600.0*densityRatio.w; m_fluidVisc[0] = particleVisc*viscRatio.x; m_fluidVisc[1] = particleVisc*viscRatio.y; m_fluidVisc[2] = particleVisc*viscRatio.z; m_fluidVisc[3] = particleVisc*viscRatio.w; restColorValue[0] = colorValue.x; restColorValue[1] = colorValue.y; restColorValue[2] = colorValue.z; AllocateParticles ( m_Param[PNUM] ); AllocatePackBuf (); SetupKernels (); SetupSpacing (); numElasticPoints = 0; int solidNum = 0, liquidNum = 0, boundaryNum = 0; int pNum = 0; switch (_example) { case 1: m_Vec[PINITMIN].Set(volumes[0].x, volumes[0].y, volumes[0].z); m_Vec[PINITMAX].Set(volumes[1].x, volumes[1].y, volumes[1].z); solidNum += SetupMfAddGridSolid(m_Vec[PINITMIN], m_Vec[PINITMAX], m_Param[PSPACING], Vector3DF(0, 0, 0), 5); m_Vec[PINITMIN].Set(volumes[2].x, volumes[2].y, volumes[2].z); m_Vec[PINITMAX].Set(volumes[3].x, volumes[3].y, volumes[3].z); solidNum += SetupMfAddGridSolid(m_Vec[PINITMIN], m_Vec[PINITMAX], m_Param[PSPACING], Vector3DF(0, 0, 0), 4); m_Vec[PINITMIN].Set(volumes[4].x, volumes[4].y, volumes[4].z); m_Vec[PINITMAX].Set(volumes[5].x, volumes[5].y, volumes[5].z); solidNum += SetupMfAddGridSolid(m_Vec[PINITMIN], m_Vec[PINITMAX], m_Param[PSPACING], Vector3DF(0, 0, 0), 3); //ball m_Vec[PINITMIN].Set(volumes[6].x, volumes[6].y, volumes[6].z); m_Vec[PINITMAX].Set(volumes[7].x, volumes[7].y, volumes[7].z); //numElasticPoints = SetupMfAddDeformVolume(m_Vec[PINITMIN], m_Vec[PINITMAX], m_Param[PSPACING], Vector3DF(0, 0, 0), 0); NumPointsNoBound = numElasticPoints = 0; //fluid m_Vec[PINITMIN].Set(volumes[8].x, volumes[8].y, volumes[8].z); m_Vec[PINITMAX].Set(volumes[9].x, volumes[9].y, volumes[9].z); NumPointsNoBound += SetupMfAddBlendVolume(m_Vec[PINITMIN], m_Vec[PINITMAX], m_Param[PSPACING], Vector3DF(0, 0.1, 0)); liquidNum = NumPointsNoBound; break; case 2: numElasticPoints = 0; m_Vec[PINITMIN].Set(volumes[0].x, volumes[0].y, volumes[0].z); m_Vec[PINITMAX].Set(volumes[1].x, volumes[1].y, volumes[1].z); numElasticPoints = SetupMfAddMagicWand(m_Vec[PINITMIN], m_Vec[PINITMAX], m_Param[PSPACING], Vector3DF(0, 0, 0)); solidNum = numElasticPoints; //m_Vec[PINITMIN].Set(volumes[2].x, volumes[2].y, volumes[2].z); //m_Vec[PINITMAX].Set(volumes[3].x, volumes[3].y, volumes[3].z); //numElasticPoints += SetupMfAddMagicWand(m_Vec[PINITMIN], m_Vec[PINITMAX], m_Param[PSPACING], Vector3DF(0, 0, 0), 4); m_Vec[PINITMIN].Set(volumes[4].x, volumes[4].y, volumes[4].z); m_Vec[PINITMAX].Set(volumes[5].x, volumes[5].y, volumes[5].z); NumPointsNoBound = loadParticle("extra_particles\\fluids_ex2.dat"); //NumPointsNoBound = SetupMfAddVolume(m_Vec[PINITMIN], m_Vec[PINITMAX], m_Param[PSPACING], Vector3DF(0, 0, 0), 3); liquidNum = NumPointsNoBound; NumPointsNoBound += numElasticPoints; break; case 3: NumPointsNoBound = numElasticPoints = 0; //fluid m_Vec[PINITMIN].Set(volumes[8].x, volumes[8].y, volumes[8].z); m_Vec[PINITMAX].Set(volumes[9].x, volumes[9].y, volumes[9].z); NumPointsNoBound += SetupMfAddBlendVolume(m_Vec[PINITMIN], m_Vec[PINITMAX], m_Param[PSPACING], Vector3DF(0, 0.1, 0)); liquidNum = NumPointsNoBound; break; } pNum += NumPointsNoBound; cout << "without boundary, particle num is " << pNum << endl; //solveModel(); //storeModel("bunny.txt"); //SetupMfAddDeformVolume m_Vec [ PINITMIN ].Set (softBoundary[0].x, softBoundary[0].y, softBoundary[0].z); m_Vec [ PINITMAX ].Set (softBoundary[1].x, softBoundary[1].y, softBoundary[1].z); boundaryNum = SetupBoundary(m_Vec[PINITMIN], m_Vec[PINITMAX], m_Param[PSPACING], Vector3DF(0, 0, 0), 1); printf("liquid num is %d, solid num is %d, boundary num is %d\n", liquidNum, solidNum, boundaryNum); m_maxAllowedPoints = mNumPoints * EMIT_BUF_RATIO; }
[ "xuben@mail.nankai.edu.cn" ]
xuben@mail.nankai.edu.cn
3749b1274bee91cec74cb1ba024f7af8030348bd
5b41e312db8aeb5532ba59498c93e2ec1dccd4ff
/SMC_Frame/CActivityManager.cpp
264d07ca4d32364367426b5ac520abfd246a1b64
[]
no_license
frankilfrancis/KPO_HMI_vs17
10d96c6cb4aebffb83254e6ca38fe6d1033eba79
de49aa55eccd8a7abc165f6057088a28426a1ceb
refs/heads/master
2020-04-15T16:40:14.366351
2019-11-14T15:33:25
2019-11-14T15:33:25
164,845,188
0
1
null
null
null
null
UTF-8
C++
false
false
8,557
cpp
// Copyright (C) 2004 SMS Demag AG #include "CDateTime.h" #include "CActivityManager.h" CActivityManager::CActivityManager(seqActivityStatus& seqData) : m_SeqActivityStatus(seqData) { } CActivityManager::CActivityManager() { } CActivityManager::~CActivityManager() { } bool CActivityManager::initActivity(const std::string& Type, const std::string& Name) { bool RetValue = true; if ( !isActivityStatus(Type,Name)) { // insert activity to m_SeqActivityStatus addActivityStatus(Type,Name,true,0); // set active but not yet started } else { for ( long i = 0 ; i < CIntfData::getLength(m_SeqActivityStatus) ; ++i ) { sActivityStatus ActivityStatus; CIntfData::getAt(ActivityStatus,m_SeqActivityStatus,i); if ( std::string(ActivityStatus.ActivityType) == Type ) { if ( std::string(ActivityStatus.ActivityName) == Name ) { ActivityStatus.ActivityStatus = true; // set active // update m_SeqActivityStatus CIntfData::setAt(m_SeqActivityStatus,ActivityStatus,i); } } } } return RetValue; } bool CActivityManager::startCurrentActivity(const std::string& Type) { std::string Name = getCurrentActivityName(Type); return startActivity(Type, Name); } bool CActivityManager::startActivity(const std::string& Type, const std::string& Name) { bool RetValue = true; if ( !isActivityStatus(Type,Name)) { // insert activity to m_SeqActivityStatus addActivityStatus(Type,Name,true,1); } else { for ( long i = 0 ; i < CIntfData::getLength(m_SeqActivityStatus) ; ++i ) { sActivityStatus ActivityStatus; CIntfData::getAt(ActivityStatus,m_SeqActivityStatus,i); if ( std::string(ActivityStatus.ActivityType) == Type ) { if ( std::string(ActivityStatus.ActivityName) == Name ) { // increase ActivityNo for each start ! ActivityStatus.ActivityNo = ActivityStatus.ActivityNo + 1; ActivityStatus.ActivityStatus = true; // update m_SeqActivityStatus CIntfData::setAt(m_SeqActivityStatus,ActivityStatus,i); } } } } return RetValue; } bool CActivityManager::endActivity(const std::string& Type, const std::string& Name) { bool RetValue = true; if ( !isActivityStatus(Type,Name)) { // insert activity to m_SeqActivityStatus addActivityStatus(Type,Name,false,1); } else { for ( long i = 0 ; i < CIntfData::getLength(m_SeqActivityStatus) ; ++i ) { sActivityStatus ActivityStatus; CIntfData::getAt(ActivityStatus,m_SeqActivityStatus,i); if ( std::string(ActivityStatus.ActivityType) == Type ) { if ( std::string(ActivityStatus.ActivityName) == Name ) { ActivityStatus.ActivityStatus = false; // update m_SeqActivityStatus CIntfData::setAt(m_SeqActivityStatus,ActivityStatus,i); } } } } return RetValue; } bool CActivityManager::addActivityStatus(const std::string& Type, const std::string& Name, bool Status, long No) { sActivityStatus ActivityStatus; ActivityStatus.ActivityType = Type.c_str(); ActivityStatus.ActivityName = Name.c_str(); ActivityStatus.ActivityStatus = Status; ActivityStatus.ActivityNo = No; CIntfData::insert(m_SeqActivityStatus,ActivityStatus); return true; } bool CActivityManager::presetActivityStatus(const std::string& Type, const std::string& Name, bool Status) { bool RetValue = false; for ( long i = 0 ; i < CIntfData::getLength(m_SeqActivityStatus) ; ++i ) { sActivityStatus ActivityStatus; CIntfData::getAt(ActivityStatus,m_SeqActivityStatus,i); if ( std::string(ActivityStatus.ActivityType) == Type ) { if ( std::string(ActivityStatus.ActivityName) == Name ) { ActivityStatus.ActivityStatus = Status; // update m_SeqActivityStatus CIntfData::setAt(m_SeqActivityStatus,ActivityStatus,i); RetValue = true; } } } return RetValue; } bool CActivityManager::presetActivityStatus(bool Status) { bool RetValue = false; for ( long i = 0 ; i < CIntfData::getLength(m_SeqActivityStatus) ; ++i ) { sActivityStatus ActivityStatus; CIntfData::getAt(ActivityStatus,m_SeqActivityStatus,i); ActivityStatus.ActivityStatus = Status; // update m_SeqActivityStatus CIntfData::setAt(m_SeqActivityStatus,ActivityStatus,i); RetValue = true; } return RetValue; } bool CActivityManager::endCurrentActivity(const std::string& Type) { std::string Name = getCurrentActivityName(Type); return endActivity(Type, Name); } bool CActivityManager::getActivityStatus(const std::string& Type, const std::string& Name) { bool RetValue = false; for ( long i = 0 ; i < CIntfData::getLength(m_SeqActivityStatus) ; ++i ) { sActivityStatus ActivityStatus; CIntfData::getAt(ActivityStatus,m_SeqActivityStatus,i); if ( std::string(ActivityStatus.ActivityType) == Type ) { if ( std::string(ActivityStatus.ActivityName) == Name ) { RetValue = ActivityStatus.ActivityStatus; break; } } } return RetValue; } std::string CActivityManager::getCurrentActivityName(const std::string& Type) { std::string ActivityName; for ( long i = 0 ; i < CIntfData::getLength(m_SeqActivityStatus) ; ++i ) { sActivityStatus ActivityStatus; CIntfData::getAt(ActivityStatus,m_SeqActivityStatus,i); if ( std::string(ActivityStatus.ActivityType) == Type ) { if ( ActivityStatus.ActivityStatus == true ) { ActivityName = ActivityStatus.ActivityName; break; } } } return ActivityName; } long CActivityManager::getCurrentActivityNo(const std::string& Type) { long ActivityNo = DEF::Inv_Long; for ( long i = 0 ; i < CIntfData::getLength(m_SeqActivityStatus) ; ++i ) { sActivityStatus ActivityStatus; CIntfData::getAt(ActivityStatus,m_SeqActivityStatus,i); if ( std::string(ActivityStatus.ActivityType) == Type ) { if ( ActivityStatus.ActivityStatus == true ) { ActivityNo = ActivityStatus.ActivityNo; break; } } } return ActivityNo; } seqActivityStatus& CActivityManager::getSequence() { return m_SeqActivityStatus; } bool CActivityManager::fillSequence(seqActivityStatus& seqData) { m_SeqActivityStatus = seqData; return true; } std::vector<std::string> CActivityManager::getActivityNames(const std::string& Type) { std::vector<std::string> ActivityNames; for ( long i = 0 ; i < CIntfData::getLength(m_SeqActivityStatus) ; ++i ) { sActivityStatus ActivityStatus; CIntfData::getAt(ActivityStatus,m_SeqActivityStatus,i); if ( std::string(ActivityStatus.ActivityType) == Type ) { ActivityNames.push_back(std::string(ActivityStatus.ActivityName)); } } return ActivityNames; } bool CActivityManager::isActivityStatus(const std::string& Type, const std::string& Name, bool Status) { bool RetValue = false; for ( long i = 0 ; i < CIntfData::getLength(m_SeqActivityStatus) ; ++i ) { sActivityStatus ActivityStatus; CIntfData::getAt(ActivityStatus,m_SeqActivityStatus,i); if ( std::string(ActivityStatus.ActivityType) == Type ) { if ( std::string(ActivityStatus.ActivityName) == Name ) { if ( ActivityStatus.ActivityStatus == Status ) { RetValue = true; } } } } return RetValue; } bool CActivityManager::isActivityStatus(const std::string& Type, const std::string& Name) { bool RetValue = false; for ( long i = 0 ; i < CIntfData::getLength(m_SeqActivityStatus) ; ++i ) { sActivityStatus ActivityStatus; CIntfData::getAt(ActivityStatus,m_SeqActivityStatus,i); if ( std::string(ActivityStatus.ActivityType) == Type ) { if ( std::string(ActivityStatus.ActivityName) == Name ) { RetValue = true; } } } return RetValue; } long CActivityManager::getActivityNo(const std::string& Type, const std::string& Name) { long ActivityNo = DEF::Inv_Long; for ( long i = 0 ; i < CIntfData::getLength(m_SeqActivityStatus) ; ++i ) { sActivityStatus ActivityStatus; CIntfData::getAt(ActivityStatus,m_SeqActivityStatus,i); if ( std::string(ActivityStatus.ActivityType) == Type ) { if ( std::string(ActivityStatus.ActivityName) == Name ) { ActivityNo = ActivityStatus.ActivityNo; break; } } } return ActivityNo; }
[ "52784069+FrankilPacha@users.noreply.github.com" ]
52784069+FrankilPacha@users.noreply.github.com
896398d96ba595a15b4ec508bf5ede387492f5e4
6a69d57c782e0b1b993e876ad4ca2927a5f2e863
/vendor/samsung/common/packages/apps/SBrowser/src/ash/touch/touch_hud_debug.cc
4d362c49eb98d7aebabbfc2930ed1b7b0297bd69
[ "BSD-3-Clause" ]
permissive
duki994/G900H-Platform-XXU1BOA7
c8411ef51f5f01defa96b3381f15ea741aa5bce2
4f9307e6ef21893c9a791c96a500dfad36e3b202
refs/heads/master
2020-05-16T20:57:07.585212
2015-05-11T11:03:16
2015-05-11T11:03:16
35,418,464
2
1
null
null
null
null
UTF-8
C++
false
false
14,277
cc
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/touch/touch_hud_debug.h" #include "ash/display/display_manager.h" #include "ash/root_window_controller.h" #include "ash/shell.h" #include "base/json/json_string_value_serializer.h" #include "base/strings/string_number_conversions.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "third_party/skia/include/core/SkPath.h" #include "ui/aura/root_window.h" #include "ui/events/event.h" #include "ui/gfx/animation/animation_delegate.h" #include "ui/gfx/canvas.h" #include "ui/gfx/display.h" #include "ui/gfx/size.h" #include "ui/gfx/transform.h" #include "ui/views/controls/label.h" #include "ui/views/layout/box_layout.h" #include "ui/views/widget/widget.h" #if defined(USE_X11) #include <X11/extensions/XInput2.h> #include <X11/Xlib.h> #include "ui/events/x/device_data_manager.h" #endif namespace ash { namespace internal { const int kPointRadius = 20; const SkColor kColors[] = { SK_ColorYELLOW, SK_ColorGREEN, SK_ColorRED, SK_ColorBLUE, SK_ColorGRAY, SK_ColorMAGENTA, SK_ColorCYAN, SK_ColorWHITE, SK_ColorBLACK, SkColorSetRGB(0xFF, 0x8C, 0x00), SkColorSetRGB(0x8B, 0x45, 0x13), SkColorSetRGB(0xFF, 0xDE, 0xAD), }; const int kAlpha = 0x60; const int kMaxPaths = arraysize(kColors); const int kReducedScale = 10; const char* GetTouchEventLabel(ui::EventType type) { switch (type) { case ui::ET_UNKNOWN: return " "; case ui::ET_TOUCH_PRESSED: return "P"; case ui::ET_TOUCH_MOVED: return "M"; case ui::ET_TOUCH_RELEASED: return "R"; case ui::ET_TOUCH_CANCELLED: return "C"; default: break; } return "?"; } int GetTrackingId(const ui::TouchEvent& event) { if (!event.HasNativeEvent()) return 0; #if defined(USE_XI2_MT) ui::DeviceDataManager* manager = ui::DeviceDataManager::GetInstance(); double tracking_id; if (manager->GetEventData(*event.native_event(), ui::DeviceDataManager::DT_TOUCH_TRACKING_ID, &tracking_id)) { return static_cast<int>(tracking_id); } #endif return 0; } int GetSourceDeviceId(const ui::TouchEvent& event) { if (!event.HasNativeEvent()) return 0; #if defined(USE_X11) XEvent* xev = event.native_event(); return static_cast<XIDeviceEvent*>(xev->xcookie.data)->sourceid; #endif return 0; } // A TouchPointLog represents a single touch-event of a touch point. struct TouchPointLog { public: explicit TouchPointLog(const ui::TouchEvent& touch) : id(touch.touch_id()), type(touch.type()), location(touch.root_location()), timestamp(touch.time_stamp().InMillisecondsF()), radius_x(touch.radius_x()), radius_y(touch.radius_y()), pressure(touch.force()), tracking_id(GetTrackingId(touch)), source_device(GetSourceDeviceId(touch)) { } // Populates a dictionary value with all the information about the touch // point. scoped_ptr<base::DictionaryValue> GetAsDictionary() const { scoped_ptr<base::DictionaryValue> value(new base::DictionaryValue()); value->SetInteger("id", id); value->SetString("type", std::string(GetTouchEventLabel(type))); value->SetString("location", location.ToString()); value->SetDouble("timestamp", timestamp); value->SetDouble("radius_x", radius_x); value->SetDouble("radius_y", radius_y); value->SetDouble("pressure", pressure); value->SetInteger("tracking_id", tracking_id); value->SetInteger("source_device", source_device); return value.Pass(); } int id; ui::EventType type; gfx::Point location; double timestamp; float radius_x; float radius_y; float pressure; int tracking_id; int source_device; }; // A TouchTrace keeps track of all the touch events of a single touch point // (starting from a touch-press and ending at a touch-release or touch-cancel). class TouchTrace { public: typedef std::vector<TouchPointLog>::iterator iterator; typedef std::vector<TouchPointLog>::const_iterator const_iterator; typedef std::vector<TouchPointLog>::reverse_iterator reverse_iterator; typedef std::vector<TouchPointLog>::const_reverse_iterator const_reverse_iterator; TouchTrace() { } void AddTouchPoint(const ui::TouchEvent& touch) { log_.push_back(TouchPointLog(touch)); } const std::vector<TouchPointLog>& log() const { return log_; } bool active() const { return !log_.empty() && log_.back().type != ui::ET_TOUCH_RELEASED && log_.back().type != ui::ET_TOUCH_CANCELLED; } // Returns a list containing data from all events for the touch point. scoped_ptr<base::ListValue> GetAsList() const { scoped_ptr<base::ListValue> list(new base::ListValue()); for (const_iterator i = log_.begin(); i != log_.end(); ++i) list->Append((*i).GetAsDictionary().release()); return list.Pass(); } void Reset() { log_.clear(); } private: std::vector<TouchPointLog> log_; DISALLOW_COPY_AND_ASSIGN(TouchTrace); }; // A TouchLog keeps track of all touch events of all touch points. class TouchLog { public: TouchLog() : next_trace_index_(0) { } void AddTouchPoint(const ui::TouchEvent& touch) { if (touch.type() == ui::ET_TOUCH_PRESSED) StartTrace(touch); AddToTrace(touch); } void Reset() { next_trace_index_ = 0; for (int i = 0; i < kMaxPaths; ++i) traces_[i].Reset(); } scoped_ptr<base::ListValue> GetAsList() const { scoped_ptr<base::ListValue> list(new base::ListValue()); for (int i = 0; i < kMaxPaths; ++i) { if (!traces_[i].log().empty()) list->Append(traces_[i].GetAsList().release()); } return list.Pass(); } int GetTraceIndex(int touch_id) const { return touch_id_to_trace_index_.at(touch_id); } const TouchTrace* traces() const { return traces_; } private: void StartTrace(const ui::TouchEvent& touch) { // Find the first inactive spot; otherwise, overwrite the one // |next_trace_index_| is pointing to. int old_trace_index = next_trace_index_; do { if (!traces_[next_trace_index_].active()) break; next_trace_index_ = (next_trace_index_ + 1) % kMaxPaths; } while (next_trace_index_ != old_trace_index); int touch_id = touch.touch_id(); traces_[next_trace_index_].Reset(); touch_id_to_trace_index_[touch_id] = next_trace_index_; next_trace_index_ = (next_trace_index_ + 1) % kMaxPaths; } void AddToTrace(const ui::TouchEvent& touch) { int touch_id = touch.touch_id(); int trace_index = touch_id_to_trace_index_[touch_id]; traces_[trace_index].AddTouchPoint(touch); } TouchTrace traces_[kMaxPaths]; int next_trace_index_; std::map<int, int> touch_id_to_trace_index_; DISALLOW_COPY_AND_ASSIGN(TouchLog); }; // TouchHudCanvas draws touch traces in |FULLSCREEN| and |REDUCED_SCALE| modes. class TouchHudCanvas : public views::View { public: explicit TouchHudCanvas(const TouchLog& touch_log) : touch_log_(touch_log), scale_(1) { SetPaintToLayer(true); SetFillsBoundsOpaquely(false); paint_.setStyle(SkPaint::kFill_Style); } virtual ~TouchHudCanvas() {} void SetScale(int scale) { if (scale_ == scale) return; scale_ = scale; gfx::Transform transform; transform.Scale(1. / scale_, 1. / scale_); layer()->SetTransform(transform); } int scale() const { return scale_; } void TouchPointAdded(int touch_id) { int trace_index = touch_log_.GetTraceIndex(touch_id); const TouchTrace& trace = touch_log_.traces()[trace_index]; const TouchPointLog& point = trace.log().back(); if (point.type == ui::ET_TOUCH_PRESSED) StartedTrace(trace_index); if (point.type != ui::ET_TOUCH_CANCELLED) AddedPointToTrace(trace_index); } void Clear() { for (int i = 0; i < kMaxPaths; ++i) paths_[i].reset(); SchedulePaint(); } private: void StartedTrace(int trace_index) { paths_[trace_index].reset(); colors_[trace_index] = SkColorSetA(kColors[trace_index], kAlpha); } void AddedPointToTrace(int trace_index) { const TouchTrace& trace = touch_log_.traces()[trace_index]; const TouchPointLog& point = trace.log().back(); const gfx::Point& location = point.location; SkScalar x = SkIntToScalar(location.x()); SkScalar y = SkIntToScalar(location.y()); SkPoint last; if (!paths_[trace_index].getLastPt(&last) || x != last.x() || y != last.y()) { paths_[trace_index].addCircle(x, y, SkIntToScalar(kPointRadius)); SchedulePaint(); } } // Overridden from views::View. virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE { for (int i = 0; i < kMaxPaths; ++i) { if (paths_[i].countPoints() == 0) continue; paint_.setColor(colors_[i]); canvas->DrawPath(paths_[i], paint_); } } SkPaint paint_; const TouchLog& touch_log_; SkPath paths_[kMaxPaths]; SkColor colors_[kMaxPaths]; int scale_; DISALLOW_COPY_AND_ASSIGN(TouchHudCanvas); }; TouchHudDebug::TouchHudDebug(aura::Window* initial_root) : TouchObserverHUD(initial_root), mode_(FULLSCREEN), touch_log_(new TouchLog()), canvas_(NULL), label_container_(NULL) { const gfx::Display& display = Shell::GetInstance()->display_manager()->GetDisplayForId(display_id()); views::View* content = widget()->GetContentsView(); canvas_ = new TouchHudCanvas(*touch_log_); content->AddChildView(canvas_); const gfx::Size& display_size = display.size(); canvas_->SetSize(display_size); label_container_ = new views::View; label_container_->SetLayoutManager(new views::BoxLayout( views::BoxLayout::kVertical, 0, 0, 0)); for (int i = 0; i < kMaxTouchPoints; ++i) { touch_labels_[i] = new views::Label; touch_labels_[i]->SetBackgroundColor(SkColorSetARGB(0, 255, 255, 255)); touch_labels_[i]->SetShadowColors(SK_ColorWHITE, SK_ColorWHITE); touch_labels_[i]->SetShadowOffset(1, 1); label_container_->AddChildView(touch_labels_[i]); } label_container_->SetX(0); label_container_->SetY(display_size.height() / kReducedScale); label_container_->SetSize(label_container_->GetPreferredSize()); label_container_->SetVisible(false); content->AddChildView(label_container_); } TouchHudDebug::~TouchHudDebug() { } // static scoped_ptr<base::DictionaryValue> TouchHudDebug::GetAllAsDictionary() { scoped_ptr<base::DictionaryValue> value(new base::DictionaryValue()); aura::Window::Windows roots = Shell::GetInstance()->GetAllRootWindows(); for (aura::Window::Windows::iterator iter = roots.begin(); iter != roots.end(); ++iter) { internal::RootWindowController* controller = GetRootWindowController(*iter); internal::TouchHudDebug* hud = controller->touch_hud_debug(); if (hud) { scoped_ptr<base::ListValue> list = hud->GetLogAsList(); if (!list->empty()) value->Set(base::Int64ToString(hud->display_id()), list.release()); } } return value.Pass(); } void TouchHudDebug::ChangeToNextMode() { switch (mode_) { case FULLSCREEN: SetMode(REDUCED_SCALE); break; case REDUCED_SCALE: SetMode(INVISIBLE); break; case INVISIBLE: SetMode(FULLSCREEN); break; } } scoped_ptr<base::ListValue> TouchHudDebug::GetLogAsList() const { return touch_log_->GetAsList(); } void TouchHudDebug::Clear() { if (widget()->IsVisible()) { canvas_->Clear(); for (int i = 0; i < kMaxTouchPoints; ++i) touch_labels_[i]->SetText(base::string16()); label_container_->SetSize(label_container_->GetPreferredSize()); } } void TouchHudDebug::SetMode(Mode mode) { if (mode_ == mode) return; mode_ = mode; switch (mode) { case FULLSCREEN: label_container_->SetVisible(false); canvas_->SetVisible(true); canvas_->SetScale(1); canvas_->SchedulePaint(); widget()->Show(); break; case REDUCED_SCALE: label_container_->SetVisible(true); canvas_->SetVisible(true); canvas_->SetScale(kReducedScale); canvas_->SchedulePaint(); widget()->Show(); break; case INVISIBLE: widget()->Hide(); break; } } void TouchHudDebug::UpdateTouchPointLabel(int index) { int trace_index = touch_log_->GetTraceIndex(index); const TouchTrace& trace = touch_log_->traces()[trace_index]; TouchTrace::const_reverse_iterator point = trace.log().rbegin(); ui::EventType touch_status = point->type; float touch_radius = std::max(point->radius_x, point->radius_y); while (point != trace.log().rend() && point->type == ui::ET_TOUCH_CANCELLED) point++; DCHECK(point != trace.log().rend()); gfx::Point touch_position = point->location; std::string string = base::StringPrintf("%2d: %s %s (%.4f)", index, GetTouchEventLabel(touch_status), touch_position.ToString().c_str(), touch_radius); touch_labels_[index]->SetText(base::UTF8ToUTF16(string)); } void TouchHudDebug::OnTouchEvent(ui::TouchEvent* event) { if (event->touch_id() >= kMaxTouchPoints) return; touch_log_->AddTouchPoint(*event); canvas_->TouchPointAdded(event->touch_id()); UpdateTouchPointLabel(event->touch_id()); label_container_->SetSize(label_container_->GetPreferredSize()); } void TouchHudDebug::OnDisplayBoundsChanged(const gfx::Display& display) { TouchObserverHUD::OnDisplayBoundsChanged(display); if (display.id() != display_id()) return; const gfx::Size& size = display.size(); canvas_->SetSize(size); label_container_->SetY(size.height() / kReducedScale); } void TouchHudDebug::SetHudForRootWindowController( RootWindowController* controller) { controller->set_touch_hud_debug(this); } void TouchHudDebug::UnsetHudForRootWindowController( RootWindowController* controller) { controller->set_touch_hud_debug(NULL); } } // namespace internal } // namespace ash
[ "duki994@gmail.com" ]
duki994@gmail.com
b02ca36150e7bf4285f2167752aa9dd8ee6f687e
069bac97b6c90de189a73e6381b32b7a3a44e034
/lab_dict/anagram_dict.cpp
6dd6dd7d1741d80e4ff995b7c0a1978226f161bd
[]
no_license
Mukhil04/Data-Structures
d0a9f32e1d05ab37a44998ee66a9dbb33a0f17d8
4388c1eb148b9dac8ce1e24a9c56484644671be8
refs/heads/main
2023-08-04T23:28:21.892763
2021-09-27T05:59:33
2021-09-27T05:59:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,162
cpp
/** * @file anagram_dict.cpp * Implementation of the AnagramDict class. * * @author Matt Joras * @date Winter 2013 */ #include "anagram_dict.h" #include <algorithm> /* I wonder why this is included... */ #include <fstream> #include <iostream> using std::string; using std::vector; using std::ifstream; /** * Constructs an AnagramDict from a filename with newline-separated * words. * @param filename The name of the word list file. */ AnagramDict::AnagramDict(const string& filename) { /* Your code goes here! */ ifstream wordsFile(filename); string word; std::map<string, int> values; if (wordsFile.is_open()) { while (getline(wordsFile, word)) { int value = 1; for (char c : word){ value*= (int(c) - 96); } string str = word; values.insert(std::pair<string,int>(str, value)); } while(values.size() != 1 && values.size() != 0){ int flag = 0; for (auto itr = values.begin(); itr != values.end(); ++itr){ if (!(itr != values.begin())){ continue; } if (values.begin()->second == itr->second){ if (!(dict.find(values.begin()->first) != dict.end())){ dict.insert(std::pair<string,std::vector<std::string>>(values.begin()->first, {itr ->first})); dict.insert(std::pair<string,std::vector<std::string>>(itr->first, {values.begin()->first})); flag = 1; values.erase(itr->first); values.erase(values.begin()->first); break; } } } if (flag == 0){ dict.insert(std::pair<string,std::vector<std::string>>(values.begin()->first, {})); values.erase(values.begin()->first); } } if (values.size()!=0){ dict.insert(std::pair<string,std::vector<std::string>>(values.begin()->first, {})); } } } /** * Constructs an AnagramDict from a vector of words. * @param words The vector of strings to be used as source words. */ AnagramDict::AnagramDict(const vector<string>& words) { std::map<string, int> values; for (size_t i = 0; i < words.size(); i++){ int value = 1; for (char c : words[i]){ value*= (int(c) - 96); } string str = words[i]; values.insert(std::pair<string,int>(str, value)); } while(values.size() != 1 && values.size() != 0){ int flag = 0; for (auto itr = values.begin(); itr != values.end(); ++itr){ if (!(itr != values.begin())){ continue; } if (values.begin()->second == itr->second){ if (!(dict.find(values.begin()->first) != dict.end())){ dict.insert(std::pair<string,std::vector<std::string>>(values.begin()->first, {itr ->first})); dict.insert(std::pair<string,std::vector<std::string>>(itr->first, {values.begin()->first})); flag = 1; values.erase(itr->first); values.erase(values.begin()->first); break; } } } if (flag == 0){ dict.insert(std::pair<string,std::vector<std::string>>(values.begin()->first, {})); values.erase(values.begin()->first); } } if (values.size()!=0){ dict.insert(std::pair<string,std::vector<std::string>>(values.begin()->first, {})); } } /** * @param word The word to find anagrams of. * @return A vector of strings of anagrams of the given word. Empty * vector returned if no anagrams are found or the word is not in the * word list. */ vector<string> AnagramDict::get_anagrams(const string& word) const { /* Your code goes here! */ vector <string> result; if (dict.find(word) != dict.end()){ result.push_back(dict.find(word)->second[0]); if (dict.find(dict.find(word)->second[0]) != dict.end()){ result.push_back(dict.find(dict.find(word)->second[0])->second[0]); } return result; } else{ return vector<string>(); } } /** * @return A vector of vectors of strings. Each inner vector contains * the "anagram siblings", i.e. words that are anagrams of one another. * NOTE: It is impossible to have one of these vectors have less than * two elements, i.e. words with no anagrams are ommitted. */ vector<vector<string>> AnagramDict::get_all_anagrams() const { /* Your code goes here! */ vector<vector<string>> vect; vector <string> median; for (auto itr = dict.begin(); itr != dict.end(); ++itr){ if (dict.find(itr->first) != dict.end() && !dict.find(itr->first)->second.empty()){ median = get_anagrams(itr->first); if (median.empty()){ continue; } else{ vect.push_back(median); } } } return vect; }
[ "noreply@github.com" ]
noreply@github.com
0505455536424805c61d5b5f67dc79e5682561b8
1fe0ccfb7c0323562bd5092a80b82675d8d85eef
/boat-ws/devel/include/driver_base/ConfigValue.h
95d52dedb0fa2f9b40f184e321c1c20ff9a9e0ee
[]
no_license
lineCode/AV-Invisible-Boat
9bf64048463af045e404f773be9c8a5ddaf7d58a
0b1515d7b746127286ab07b5338984bf9763b38e
refs/heads/master
2021-01-09T19:56:38.682529
2018-04-09T18:26:35
2018-04-09T18:26:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,286
h
// Generated by gencpp from file driver_base/ConfigValue.msg // DO NOT EDIT! #ifndef DRIVER_BASE_MESSAGE_CONFIGVALUE_H #define DRIVER_BASE_MESSAGE_CONFIGVALUE_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace driver_base { template <class ContainerAllocator> struct ConfigValue_ { typedef ConfigValue_<ContainerAllocator> Type; ConfigValue_() : name() , value(0.0) { } ConfigValue_(const ContainerAllocator& _alloc) : name(_alloc) , value(0.0) { (void)_alloc; } typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _name_type; _name_type name; typedef double _value_type; _value_type value; typedef boost::shared_ptr< ::driver_base::ConfigValue_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::driver_base::ConfigValue_<ContainerAllocator> const> ConstPtr; }; // struct ConfigValue_ typedef ::driver_base::ConfigValue_<std::allocator<void> > ConfigValue; typedef boost::shared_ptr< ::driver_base::ConfigValue > ConfigValuePtr; typedef boost::shared_ptr< ::driver_base::ConfigValue const> ConfigValueConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::driver_base::ConfigValue_<ContainerAllocator> & v) { ros::message_operations::Printer< ::driver_base::ConfigValue_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace driver_base namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False} // {'driver_base': ['/home/racecar/AV-Invisible-Boat/boat-ws/src/driver_common/driver_base/msg'], 'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::driver_base::ConfigValue_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::driver_base::ConfigValue_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::driver_base::ConfigValue_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::driver_base::ConfigValue_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::driver_base::ConfigValue_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::driver_base::ConfigValue_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::driver_base::ConfigValue_<ContainerAllocator> > { static const char* value() { return "d8512f27253c0f65f928a67c329cd658"; } static const char* value(const ::driver_base::ConfigValue_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0xd8512f27253c0f65ULL; static const uint64_t static_value2 = 0xf928a67c329cd658ULL; }; template<class ContainerAllocator> struct DataType< ::driver_base::ConfigValue_<ContainerAllocator> > { static const char* value() { return "driver_base/ConfigValue"; } static const char* value(const ::driver_base::ConfigValue_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::driver_base::ConfigValue_<ContainerAllocator> > { static const char* value() { return "string name\n\ float64 value\n\ "; } static const char* value(const ::driver_base::ConfigValue_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::driver_base::ConfigValue_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.name); stream.next(m.value); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct ConfigValue_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::driver_base::ConfigValue_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::driver_base::ConfigValue_<ContainerAllocator>& v) { s << indent << "name: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.name); s << indent << "value: "; Printer<double>::stream(s, indent + " ", v.value); } }; } // namespace message_operations } // namespace ros #endif // DRIVER_BASE_MESSAGE_CONFIGVALUE_H
[ "brettg0396@gmail.com" ]
brettg0396@gmail.com
eb0bc3588592ec103d03aec2038246eba402d00d
30dd9ff200f97b525b069577471d23387b23970b
/src/planning/scenario_planning/lane_driving/behavior_planning/turn_signal_decider/src/turn_signal_decider_core.cpp
5a1e5cce0179d7a165f8ac6bbd2f67c1d0432760
[]
permissive
ColleyLi/AutowareArchitectureProposal
cd544ef913e3c49852d385883c3e3ee5b518b1b8
80ac2a8823d342e5a1e34703dbde27e8e9b5cd98
refs/heads/master
2022-04-18T01:41:53.649137
2020-04-21T12:18:58
2020-04-21T12:18:58
257,659,506
2
0
Apache-2.0
2020-04-21T17:03:50
2020-04-21T17:03:49
null
UTF-8
C++
false
false
7,779
cpp
/* * Copyright 2020 Tier IV, 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 <turn_signal_decider/turn_signal_decider.h> using autoware_planning_msgs::PathWithLaneId; using autoware_vehicle_msgs::TurnSignal; namespace { double getDistance3d(const geometry_msgs::Point & p1, const geometry_msgs::Point & p2) { return std::sqrt(std::pow(p1.x - p2.x, 2) + std::pow(p1.y - p2.y, 2) + std::pow(p1.z - p2.z, 2)); } } // namespace namespace turn_signal_decider { TurnSignalDecider::TurnSignalDecider() : pnh_("~") { // setup data manager constexpr double vehicle_pose_update_period = 0.1; vehicle_pose_timer_ = pnh_.createTimer( ros::Duration(vehicle_pose_update_period), &DataManager::onVehiclePoseUpdate, &data_); path_subscriber_ = pnh_.subscribe("input/path_with_lane_id", 1, &DataManager::onPathWithLaneId, &data_); map_subscriber_ = pnh_.subscribe("input/vector_map", 1, &DataManager::onLaneletMap, &data_); // get ROS parameters pnh_.param<double>("lane_change_search_distance", parameters_.lane_change_search_distance, 30); pnh_.param<double>("intersection_search_distance", parameters_.intersection_search_distance, 30); // set publishers turn_signal_publisher_ = pnh_.advertise<TurnSignal>("output/turn_signal_cmd", 1, false); constexpr double timer_period = 0.1; turn_signal_timer_ = pnh_.createTimer(ros::Duration(timer_period), &TurnSignalDecider::onTurnSignalTimer, this); } void TurnSignalDecider::onTurnSignalTimer(const ros::TimerEvent & event) { // wait for mandatory topics if (!data_.isDataReady()) { return; } // setup const auto path = data_.getPath(); FrenetCoordinate3d vehicle_pose_frenet; if (!convertToFrenetCoordinate3d( path, data_.getVehiclePoseStamped().pose.position, &vehicle_pose_frenet)) { ROS_ERROR_THROTTLE(5, "failed to convert vehicle pose into frenet coordinate"); return; } // set turn signals according to closest manuevers TurnSignal turn_signal, lane_change_signal, intersection_signal; double distance_to_lane_change, distance_to_intersection; double min_distance = std::numeric_limits<double>::max(); if (isChangingLane(path, vehicle_pose_frenet, &lane_change_signal, &distance_to_lane_change)) { if (min_distance > distance_to_lane_change) { min_distance = distance_to_lane_change; turn_signal = lane_change_signal; } } if (isTurning(path, vehicle_pose_frenet, &intersection_signal, &distance_to_intersection)) { if (min_distance > distance_to_intersection) { min_distance = distance_to_lane_change; turn_signal = intersection_signal; } } turn_signal.header.stamp = ros::Time::now(); turn_signal.header.frame_id = "base_link"; turn_signal_publisher_.publish(turn_signal); } lanelet::routing::RelationType TurnSignalDecider::getRelation( const lanelet::ConstLanelet & prev_lane, const lanelet::ConstLanelet & next_lane) const { const auto routing_graph_ptr = data_.getRoutingGraphPtr(); if (prev_lane == next_lane) { return lanelet::routing::RelationType::None; } const auto & relation = routing_graph_ptr->routingRelation(prev_lane, next_lane); if (relation) { return relation.get(); } // check if lane change extends across muliple lanes const auto shortest_path = routing_graph_ptr->shortestPath(prev_lane, next_lane); if (shortest_path) { auto prev_llt = shortest_path->front(); for (const auto & llt : shortest_path.get()) { if (prev_llt == llt) { continue; } const auto & relation = routing_graph_ptr->routingRelation(prev_llt, llt); if (!relation) { continue; } if ( relation.get() == lanelet::routing::RelationType::Left || relation.get() == lanelet::routing::RelationType::Right) { return relation.get(); } prev_llt = llt; } } return lanelet::routing::RelationType::None; } bool TurnSignalDecider::isChangingLane( const PathWithLaneId & path, const FrenetCoordinate3d & vehicle_pose_frenet, TurnSignal * signal_state_ptr, double * distance_ptr) const { if (signal_state_ptr == nullptr || distance_ptr == nullptr) { ROS_ERROR("Given argument is nullptr."); return false; } if (path.points.empty()) { return false; } double accumulated_distance = 0; auto prev_point = path.points.front(); auto prev_lane_id = path.points.front().lane_ids.front(); for (const auto & path_point : path.points) { accumulated_distance += getDistance3d(prev_point.point.pose.position, path_point.point.pose.position); prev_point = path_point; const double distance_from_vehicle = accumulated_distance - vehicle_pose_frenet.length; if (distance_from_vehicle < 0) { continue; } for (const auto & lane_id : path_point.lane_ids) { if (lane_id == prev_lane_id) { continue; } const auto & prev_lane = data_.getLaneFromId(prev_lane_id); const auto & lane = data_.getLaneFromId(lane_id); prev_lane_id = lane_id; // check lane change relation const auto relation = getRelation(prev_lane, lane); if (relation == lanelet::routing::RelationType::Left) { signal_state_ptr->data = TurnSignal::LEFT; *distance_ptr = distance_from_vehicle; return true; } if (relation == lanelet::routing::RelationType::Right) { signal_state_ptr->data = TurnSignal::RIGHT; *distance_ptr = distance_from_vehicle; return true; } } if (distance_from_vehicle > parameters_.lane_change_search_distance) { return false; } } return false; } bool TurnSignalDecider::isTurning( const PathWithLaneId & path, const FrenetCoordinate3d & vehicle_pose_frenet, TurnSignal * signal_state_ptr, double * distance_ptr) const { if (signal_state_ptr == nullptr || distance_ptr == nullptr) { ROS_ERROR("Given argument is nullptr."); return false; } if (path.points.empty()) { return false; } double accumulated_distance = 0; auto prev_point = path.points.front(); auto prev_lane_id = lanelet::InvalId; for (const auto & path_point : path.points) { accumulated_distance += getDistance3d(prev_point.point.pose.position, path_point.point.pose.position); prev_point = path_point; const double distance_from_vehicle = accumulated_distance - vehicle_pose_frenet.length; if (distance_from_vehicle < 0) { continue; } for (const auto & lane_id : path_point.lane_ids) { if (lane_id == prev_lane_id) { continue; } prev_lane_id = lane_id; const auto & lane = data_.getLaneFromId(lane_id); if (lane.attributeOr("turn_direction", std::string("none")) == "left") { signal_state_ptr->data = TurnSignal::LEFT; *distance_ptr = distance_from_vehicle; return true; } if (lane.attributeOr("turn_direction", std::string("none")) == "right") { signal_state_ptr->data = TurnSignal::RIGHT; *distance_ptr = distance_from_vehicle; return true; } } if (distance_from_vehicle > parameters_.intersection_search_distance) { return false; } } return false; } } // namespace turn_signal_decider
[ "yukky.saito@gmail.com" ]
yukky.saito@gmail.com
b10b180f5729c8b15e9021fc033afd24d2c4d5e9
33303d4a07598139320c796f07c614d5e901e6ef
/cpp/daal/src/algorithms/logitboost/inner/logitboost_training_result_v1.h
708526ca281704371c5c23e44fe6d28ff0dbfcc0
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0", "Intel", "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "MIT", "Zlib" ]
permissive
bysheva/oneDAL
7eb33dbb5aa3393c032f4e68cc1cb93fc50c0c3f
84cb27c9afde49320670006b4ff0791ee90d73d1
refs/heads/master
2023-05-05T21:18:45.345237
2021-03-01T08:00:08
2021-03-01T08:00:08
284,727,302
0
2
Apache-2.0
2021-05-29T00:02:24
2020-08-03T14:49:26
C++
UTF-8
C++
false
false
2,144
h
/* file: logitboost_training_result_v1.h */ /******************************************************************************* * Copyright 2014-2021 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /* //++ // Implementation of the interface for LogitBoost model-based training //-- */ #ifndef __LOGITBOOST_TRAINING_RESULT_V1_H__ #define __LOGITBOOST_TRAINING_RESULT_V1_H__ #include "algorithms/boosting/logitboost_training_types.h" namespace daal { namespace algorithms { namespace logitboost { namespace training { namespace interface1 { /** * Allocates memory to store final results of the LogitBoost training algorithm * \param[in] input %Input of the LogitBoost training algorithm * \param[in] parameter Parameters of the algorithm * \param[in] method LogitBoost computation method */ template <typename algorithmFPType> DAAL_EXPORT services::Status Result::allocate(const daal::algorithms::Input * input, const daal::algorithms::Parameter * parameter, const int method) { const classifier::training::interface1::Input * algInput = static_cast<const classifier::training::interface1::Input *>(input); services::Status s; logitboost::interface1::ModelPtr model = logitboost::interface1::Model::create(algInput->getNumberOfFeatures(), static_cast<const logitboost::interface1::Parameter *>(parameter), &s); set(classifier::training::model, model); return s; } } // namespace interface1 } // namespace training } // namespace logitboost } // namespace algorithms } // namespace daal #endif
[ "noreply@github.com" ]
noreply@github.com
c97036454a7e0777793f4e2d4a1f27fd74a1ba1c
06680d8792da2ff5c778a4175579575e526bca05
/Перегрузка функций2/Перегрузка функций2.cpp
68c6bca34f8ca1ad612e86e42d45e5d0cce9a5cc
[]
no_license
Rudaya99/1-
32812c7eca8259c86340a5e2bcfd597a839f6dbc
7dcdae3e00d76f2e690036b515965b4f39a69284
refs/heads/master
2022-12-23T07:35:11.885218
2020-10-03T08:14:41
2020-10-03T08:14:41
300,829,230
0
0
null
null
null
null
UTF-8
C++
false
false
2,302
cpp
// Перегрузка функций2.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы. // #include <iostream> #include<cstdlib> using namespace std; void show_message(void) { setlocale(LC_ALL, "Russian"); cout << "Стандартное сообщение: " << "Учимся программировать на C++" << endl; } void show_message(const char* message) { cout << message << endl; } void show_message(const char* first,const char* second) { cout << first << endl; cout << second << endl; } void main(void) { show_message(); show_message("Учимся программировать на языке C++!"); show_message("B C++ нет предрассудков!", "Перегрузка - это круто!"); } //std::cout << "Привет мир!\n"; // Запуск программы: CTRL+F5 или меню "Отладка" > "Запуск без отладки" // Отладка программы: F5 или меню "Отладка" > "Запустить отладку" // Советы по началу работы // 1. В окне обозревателя решений можно добавлять файлы и управлять ими. // 2. В окне Team Explorer можно подключиться к системе управления версиями. // 3. В окне "Выходные данные" можно просматривать выходные данные сборки и другие сообщения. // 4. В окне "Список ошибок" можно просматривать ошибки. // 5. Последовательно выберите пункты меню "Проект" > "Добавить новый элемент", чтобы создать файлы кода, или "Проект" > "Добавить существующий элемент", чтобы добавить в проект существующие файлы кода. // 6. Чтобы снова открыть этот проект позже, выберите пункты меню "Файл" > "Открыть" > "Проект" и выберите SLN-файл.
[ "67676443+Rudaya99@users.noreply.github.com" ]
67676443+Rudaya99@users.noreply.github.com
4695a6da789b9445d3c72903d1d5c611b975c6c6
ec24aa6034750a671f2c9474ee0a9a8e6ca20049
/src/filters/channels/Mono2Stereo_fx1.cpp
4499a72aef243cbc9a11a045484a9b8958b3952e
[]
no_license
blegal/signal_plot
fd99d81e59982e1cf4952d797936461f6bf73fbf
6868fe92fef0cdeea787c8f87e5e36d5cff1823d
refs/heads/master
2016-09-05T10:43:54.848124
2015-03-26T14:07:27
2015-03-26T14:07:27
32,930,990
2
0
null
null
null
null
UTF-8
C++
false
false
948
cpp
#include "Mono2Stereo_fx1.h" Mono2Stereo_fx1::Mono2Stereo_fx1() : Filter("Mono2Stereo fx1") { } Mono2Stereo_fx1::~Mono2Stereo_fx1() { } void Mono2Stereo_fx1::process(RawSound* _in, RawSound* _out){ startTimer(); // ON ADAPATE LA SORTIE A LA TRANSFORMATION A REALISER _out->transform( 2, 2 * _in->length(), _in->sample_rate() ); // ON VERIFIE QUE LE SIGNAL D'ENTREE EST BIEN MONO... if( _in->channels() == 2 ) { short* in = _in->data(); short* out = _out->data(); int n = _in->length(); for (int i = 0; i < n; i++) { out[i] = in[i]; } return; } short* in = _in->data(); short* out = _out->data(); int n = _in->length(); for (int i = 0; i < n; i++) { out[2*i ] = in[i]; out[2*i+1] = in[i]; } stopTimer(); }
[ "bertrand.legal@ims-bordeaux.fr" ]
bertrand.legal@ims-bordeaux.fr
5869e979c3436009bc417786f7c71e9cd08e2bb2
f562bb3ffee04acca08432966fe889114cb38d70
/dev/src/cpp/packages/serial/main.cpp
1a15639eac01d87257eb6bbd1b7af6897e24373c
[]
no_license
aaronhd/SCAVE2
ec98f521e0ff16ec3c0eb3a6a1ee9c1fc8118c73
3d47c47c5317a935a0c5bc457a906faa5e64e4a9
refs/heads/master
2020-04-23T06:40:07.610357
2018-07-06T22:51:08
2018-07-06T22:51:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
231
cpp
#include "serial.h" int main(int argc, char** argv) { std::cout << "Testing serial" << std::endl; serial* ports[2]; ports[0] = new writer; ports[1] = new reader; delete ports[0]; delete ports[1]; pthread_exit(NULL); }
[ "ucfnsl@gmail.com" ]
ucfnsl@gmail.com