blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
5
146
content_id
stringlengths
40
40
detected_licenses
listlengths
0
7
license_type
stringclasses
2 values
repo_name
stringlengths
6
79
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
4 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.07k
426M
star_events_count
int64
0
27
fork_events_count
int64
0
12
gha_license_id
stringclasses
3 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
6 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
1 class
length_bytes
int64
20
6.28M
extension
stringclasses
20 values
content
stringlengths
20
6.28M
authors
listlengths
1
16
author_lines
listlengths
1
16
7aa93c57b62e9ccc1042bee0f0b72471dc42dad8
300650d1cde847eeb72a38e001fc4ff31d64802f
/source/libwiigui/gui.h
83a3159cc44d1349c9f2b41b1943c1cf9840f8ba
[]
no_license
TheProjecter/wii-cheat-manager-gx
5b86e2b2972c6fc48db43668c2506654610ca0f3
89932a3a4192e2a6b52daf7ada73ebefee72fd37
refs/heads/master
2021-01-10T15:13:04.074418
2010-05-19T00:55:59
2010-05-19T00:55:59
43,165,415
0
0
null
null
null
null
UTF-8
C++
false
false
32,476
h
/*!\mainpage libwiigui Documentation * * \section Introduction * libwiigui is a GUI library for the Wii, created to help structure the * design of a complicated GUI interface, and to enable an author to create * a sophisticated, feature-rich GUI. It was originally conceived and written * after I started to design a GUI for Snes9x GX, and found libwiisprite and * GRRLIB inadequate for the purpose. It uses GX for drawing, and makes use * of PNGU for displaying images and FreeTypeGX for text. It was designed to * be flexible and is easy to modify - don't be afraid to change the way it * works or expand it to suit your GUI's purposes! If you do, and you think * your changes might benefit others, please share them so they might be * added to the project! * * \section Quickstart * Start from the supplied template example. For more advanced uses, see the * source code for Snes9x GX, FCE Ultra GX, and Visual Boy Advance GX. * \section Contact * If you have any suggestions for the library or documentation, or want to * contribute, please visit the libwiigui website: * http://code.google.com/p/libwiigui/ * \section Credits * This library was wholly designed and written by Tantric. Thanks to the * authors of PNGU and FreeTypeGX, of which this library makes use. Thanks * also to the authors of GRRLIB and libwiisprite for laying the foundations. * */ #ifndef LIBWIIGUI_H #define LIBWIIGUI_H #include <gccore.h> #include <malloc.h> #include <stdlib.h> #include <string.h> #include <vector> #include <exception> #include <wchar.h> #include <math.h> #include <asndlib.h> #include <wiiuse/wpad.h> #include "pngu.h" #include "FreeTypeGX.h" #include "video.h" #include "filelist.h" #include "input.h" #include "oggplayer.h" extern FreeTypeGX *fontSystem[]; #define SCROLL_INITIAL_DELAY 20 #define SCROLL_LOOP_DELAY 3 #define FILE_PAGESIZE 8 #define PAGESIZE 8 #define MAX_OPTIONS 30 #define MAX_KEYBOARD_DISPLAY 32 typedef void (*UpdateCallback)(void * e); enum { ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTRE, ALIGN_TOP, ALIGN_BOTTOM, ALIGN_MIDDLE }; enum { STATE_DEFAULT, STATE_SELECTED, STATE_CLICKED, STATE_HELD, STATE_DISABLED }; enum { SOUND_PCM, SOUND_OGG }; enum { IMAGE_TEXTURE, IMAGE_COLOR, IMAGE_DATA }; enum { TRIGGER_SIMPLE, TRIGGER_HELD, TRIGGER_BUTTON_ONLY, TRIGGER_BUTTON_ONLY_IN_FOCUS }; enum { SCROLL_NONE, SCROLL_HORIZONTAL }; typedef struct _paddata { u16 btns_d; u16 btns_u; u16 btns_h; s8 stickX; s8 stickY; s8 substickX; s8 substickY; u8 triggerL; u8 triggerR; } PADData; #define EFFECT_SLIDE_TOP 1 #define EFFECT_SLIDE_BOTTOM 2 #define EFFECT_SLIDE_RIGHT 4 #define EFFECT_SLIDE_LEFT 8 #define EFFECT_SLIDE_IN 16 #define EFFECT_SLIDE_OUT 32 #define EFFECT_FADE 64 #define EFFECT_SCALE 128 #define EFFECT_COLOR_TRANSITION 256 //!Sound conversion and playback. A wrapper for other sound libraries - ASND, libmad, ltremor, etc class GuiSound { public: //!Constructor //!\param s Pointer to the sound data //!\param l Length of sound data //!\param t Sound format type (SOUND_PCM or SOUND_OGG) GuiSound(const u8 * s, s32 l, int t); //!Destructor ~GuiSound(); //!Start sound playback void Play(); //!Stop sound playback void Stop(); //!Pause sound playback void Pause(); //!Resume sound playback void Resume(); //!Checks if the sound is currently playing //!\return true if sound is playing, false otherwise bool IsPlaying(); //!Set sound volume //!\param v Sound volume (0-100) void SetVolume(int v); //!Set the sound to loop playback (only applies to OGG) //!\param l Loop (true to loop) void SetLoop(bool l); protected: const u8 * sound; //!< Pointer to the sound data int type; //!< Sound format type (SOUND_PCM or SOUND_OGG) s32 length; //!< Length of sound data s32 voice; //!< Currently assigned ASND voice channel s32 volume; //!< Sound volume (0-100) bool loop; //!< Loop sound playback }; //!Menu input trigger management. Determine if action is neccessary based on input data by comparing controller input data to a specific trigger element. class GuiTrigger { public: //!Constructor GuiTrigger(); //!Destructor ~GuiTrigger(); //!Sets a simple trigger. Requires: element is selected, and trigger button is pressed //!\param ch Controller channel number //!\param wiibtns Wii controller trigger button(s) - classic controller buttons are considered separately //!\param gcbtns GameCube controller trigger button(s) void SetSimpleTrigger(s32 ch, u32 wiibtns, u16 gcbtns); //!Sets a held trigger. Requires: element is selected, and trigger button is pressed //!\param ch Controller channel number //!\param wiibtns Wii controller trigger button(s) - classic controller buttons are considered separately //!\param gcbtns GameCube controller trigger button(s) void SetHeldTrigger(s32 ch, u32 wiibtns, u16 gcbtns); //!Sets a button-only trigger. Requires: Trigger button is pressed //!\param ch Controller channel number //!\param wiibtns Wii controller trigger button(s) - classic controller buttons are considered separately //!\param gcbtns GameCube controller trigger button(s) void SetButtonOnlyTrigger(s32 ch, u32 wiibtns, u16 gcbtns); //!Sets a button-only trigger. Requires: trigger button is pressed and parent window of element is in focus //!\param ch Controller channel number //!\param wiibtns Wii controller trigger button(s) - classic controller buttons are considered separately //!\param gcbtns GameCube controller trigger button(s) void SetButtonOnlyInFocusTrigger(s32 ch, u32 wiibtns, u16 gcbtns); //!Get X/Y value from Wii Joystick (classic, nunchuk) input //!\param right Controller stick (left = 0, right = 1) //!\param axis Controller stick axis (x-axis = 0, y-axis = 1) //!\return Stick value s8 WPAD_Stick(u8 right, int axis); //!Move menu selection left (via pad/joystick). Allows scroll delay and button overriding //!\return true if selection should be moved left, false otherwise bool Left(); //!Move menu selection right (via pad/joystick). Allows scroll delay and button overriding //!\return true if selection should be moved right, false otherwise bool Right(); //!Move menu selection up (via pad/joystick). Allows scroll delay and button overriding //!\return true if selection should be moved up, false otherwise bool Up(); //!Move menu selection down (via pad/joystick). Allows scroll delay and button overriding //!\return true if selection should be moved down, false otherwise bool Down(); u8 type; //!< trigger type (TRIGGER_SIMPLE, TRIGGER_HELD, TRIGGER_BUTTON_ONLY, TRIGGER_BUTTON_ONLY_IN_FOCUS) s32 chan; //!< Trigger controller channel (0-3, -1 for all) WPADData * wpad; //!< Wii controller trigger WPADData wpaddata; //!< Wii controller trigger data PADData pad; //!< GameCube controller trigger data }; extern GuiTrigger userInput[4]; //!Primary GUI class. Most other classes inherit from this class. class GuiElement { public: //!Constructor GuiElement(); //!Destructor ~GuiElement(); //!Set the element's parent //!\param e Pointer to parent element void SetParent(GuiElement * e); //!Gets the element's parent //!\return Pointer to parent element GuiElement * GetParent(); //!Gets the current leftmost coordinate of the element //!Considers horizontal alignment, x offset, width, and parent element's GetLeft() / GetWidth() values //!\return left coordinate int GetLeft(); //!Gets the current topmost coordinate of the element //!Considers vertical alignment, y offset, height, and parent element's GetTop() / GetHeight() values //!\return top coordinate int GetTop(); //!Sets the minimum y offset of the element //!\param y Y offset void SetMinY(int y); //!Gets the minimum y offset of the element //!\return Minimum Y offset int GetMinY(); //!Sets the maximum y offset of the element //!\param y Y offset void SetMaxY(int y); //!Gets the maximum y offset of the element //!\return Maximum Y offset int GetMaxY(); //!Sets the minimum x offset of the element //!\param x X offset void SetMinX(int x); //!Gets the minimum x offset of the element //!\return Minimum X offset int GetMinX(); //!Sets the maximum x offset of the element //!\param x X offset void SetMaxX(int x); //!Gets the maximum x offset of the element //!\return Maximum X offset int GetMaxX(); //!Gets the current width of the element. Does not currently consider the scale //!\return width int GetWidth(); //!Gets the height of the element. Does not currently consider the scale //!\return height int GetHeight(); //!Sets the size (width/height) of the element //!\param w Width of element //!\param h Height of element void SetSize(int w, int h); //!Checks whether or not the element is visible //!\return true if visible, false otherwise bool IsVisible(); //!Checks whether or not the element is selectable //!\return true if selectable, false otherwise bool IsSelectable(); //!Checks whether or not the element is clickable //!\return true if clickable, false otherwise bool IsClickable(); //!Checks whether or not the element is holdable //!\return true if holdable, false otherwise bool IsHoldable(); //!Sets whether or not the element is selectable //!\param s Selectable void SetSelectable(bool s); //!Sets whether or not the element is clickable //!\param c Clickable void SetClickable(bool c); //!Sets whether or not the element is holdable //!\param h Holdable void SetHoldable(bool h); //!Gets the element's current state //!\return state int GetState(); //!Gets the controller channel that last changed the element's state //!\return Channel number (0-3, -1 = no channel) int GetStateChan(); //!Sets the element's alpha value //!\param a alpha value void SetAlpha(int a); //!Gets the element's alpha value //!Considers alpha, alphaDyn, and the parent element's GetAlpha() value //!\return alpha int GetAlpha(); //!Sets the element's scale //!\param s scale (1 is 100%) void SetScale(float s); //!Gets the element's current scale //!Considers scale, scaleDyn, and the parent element's GetScale() value float GetScale(); //!Set a new GuiTrigger for the element //!\param t Pointer to GuiTrigger void SetTrigger(GuiTrigger * t); //!\overload //!\param i Index of trigger array to set //!\param t Pointer to GuiTrigger void SetTrigger(u8 i, GuiTrigger * t); //!Checks whether rumble was requested by the element //!\return true is rumble was requested, false otherwise bool Rumble(); //!Sets whether or not the element is requesting a rumble event //!\param r true if requesting rumble, false if not void SetRumble(bool r); //!Set an effect for the element //!\param e Effect to enable //!\param a Amount of the effect (usage varies on effect) //!\param t Target amount of the effect (usage varies on effect) void SetEffect(int e, int a, int t=0); //!Sets an effect to be enabled on wiimote cursor over //!\param e Effect to enable //!\param a Amount of the effect (usage varies on effect) //!\param t Target amount of the effect (usage varies on effect) void SetEffectOnOver(int e, int a, int t=0); //!Shortcut to SetEffectOnOver(EFFECT_SCALE, 4, 110) void SetEffectGrow(); //!Gets the current element effects //!\return element effects int GetEffect(); //!Checks whether the specified coordinates are within the element's boundaries //!\param x X coordinate //!\param y Y coordinate //!\return true if contained within, false otherwise bool IsInside(int x, int y); //!Sets the element's position //!\param x X coordinate //!\param y Y coordinate void SetPosition(int x, int y); //!Updates the element's effects (dynamic values) //!Called by Draw(), used for animation purposes void UpdateEffects(); //!Sets a function to called after after Update() //!Callback function can be used to response to changes in the state of the element, and/or update the element's attributes void SetUpdateCallback(UpdateCallback u); //!Checks whether the element is in focus //!\return true if element is in focus, false otherwise int IsFocused(); //!Sets the element's visibility //!\param v Visibility (true = visible) virtual void SetVisible(bool v); //!Sets the element's focus //!\param f Focus (true = in focus) virtual void SetFocus(int f); //!Sets the element's state //!\param s State (STATE_DEFAULT, STATE_SELECTED, STATE_CLICKED, STATE_DISABLED) //!\param c Controller channel (0-3, -1 = none) virtual void SetState(int s, int c = -1); //!Resets the element's state to STATE_DEFAULT virtual void ResetState(); //!Gets whether or not the element is in STATE_SELECTED //!\return true if selected, false otherwise virtual int GetSelected(); //!Sets the element's alignment respective to its parent element //!\param hor Horizontal alignment (ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTRE) //!\param vert Vertical alignment (ALIGN_TOP, ALIGN_BOTTOM, ALIGN_MIDDLE) virtual void SetAlignment(int hor, int vert); //!Called constantly to allow the element to respond to the current input data //!\param t Pointer to a GuiTrigger, containing the current input data from PAD/WPAD virtual void Update(GuiTrigger * t); //!Called constantly to redraw the element virtual void Draw(); protected: bool visible; //!< Visibility of the element. If false, Draw() is skipped int focus; //!< Element focus (-1 = focus disabled, 0 = not focused, 1 = focused) int width; //!< Element width int height; //!< Element height int xoffset; //!< Element X offset int yoffset; //!< Element Y offset int ymin; //!< Element's min Y offset allowed int ymax; //!< Element's max Y offset allowed int xmin; //!< Element's min X offset allowed int xmax; //!< Element's max X offset allowed int xoffsetDyn; //!< Element X offset, dynamic (added to xoffset value for animation effects) int yoffsetDyn; //!< Element Y offset, dynamic (added to yoffset value for animation effects) int alpha; //!< Element alpha value (0-255) f32 scale; //!< Element scale (1 = 100%) int alphaDyn; //!< Element alpha, dynamic (multiplied by alpha value for blending/fading effects) f32 scaleDyn; //!< Element scale, dynamic (multiplied by alpha value for blending/fading effects) bool rumble; //!< Wiimote rumble (on/off) - set to on when this element requests a rumble event int effects; //!< Currently enabled effect(s). 0 when no effects are enabled int effectAmount; //!< Effect amount. Used by different effects for different purposes int effectTarget; //!< Effect target amount. Used by different effects for different purposes int effectsOver; //!< Effects to enable when wiimote cursor is over this element. Copied to effects variable on over event int effectAmountOver; //!< EffectAmount to set when wiimote cursor is over this element int effectTargetOver; //!< EffectTarget to set when wiimote cursor is over this element int alignmentHor; //!< Horizontal element alignment, respective to parent element (LEFT, RIGHT, CENTRE) int alignmentVert; //!< Horizontal element alignment, respective to parent element (TOP, BOTTOM, MIDDLE) int state; //!< Element state (DEFAULT, SELECTED, CLICKED, DISABLED) int stateChan; //!< Which controller channel is responsible for the last change in state bool selectable; //!< Whether or not this element selectable (can change to SELECTED state) bool clickable; //!< Whether or not this element is clickable (can change to CLICKED state) bool holdable; //!< Whether or not this element is holdable (can change to HELD state) GuiTrigger * trigger[2]; //!< GuiTriggers (input actions) that this element responds to GuiElement * parentElement; //!< Parent element UpdateCallback updateCB; //!< Callback function to call when this element is updated }; //!Allows GuiElements to be grouped together into a "window" class GuiWindow : public GuiElement { public: //!Constructor GuiWindow(); //!\overload //!\param w Width of window //!\param h Height of window GuiWindow(int w, int h); //!Destructor ~GuiWindow(); //!Appends a GuiElement to the GuiWindow //!\param e The GuiElement to append. If it is already in the GuiWindow, it is removed first void Append(GuiElement* e); //!Inserts a GuiElement into the GuiWindow at the specified index //!\param e The GuiElement to insert. If it is already in the GuiWindow, it is removed first //!\param i Index in which to insert the element void Insert(GuiElement* e, u32 i); //!Removes the specified GuiElement from the GuiWindow //!\param e GuiElement to be removed void Remove(GuiElement* e); //!Removes all GuiElements void RemoveAll(); //!Returns the GuiElement at the specified index //!\param index The index of the element //!\return A pointer to the element at the index, NULL on error (eg: out of bounds) GuiElement* GetGuiElementAt(u32 index) const; //!Returns the size of the list of elements //!\return The size of the current element list u32 GetSize(); //!Sets the visibility of the window //!\param v visibility (true = visible) void SetVisible(bool v); //!Resets the window's state to STATE_DEFAULT void ResetState(); //!Sets the window's state //!\param s State void SetState(int s); //!Gets the index of the GuiElement inside the window that is currently selected //!\return index of selected GuiElement int GetSelected(); //!Sets the window focus //!\param f Focus void SetFocus(int f); //!Change the focus to the specified element //!This is intended for the primary GuiWindow only //!\param e GuiElement that should have focus void ChangeFocus(GuiElement * e); //!Changes window focus to the next focusable window or element //!If no element is in focus, changes focus to the first available element //!If B or 1 button is pressed, changes focus to the next available element //!This is intended for the primary GuiWindow only //!\param t Pointer to a GuiTrigger, containing the current input data from PAD/WPAD void ToggleFocus(GuiTrigger * t); //!Moves the selected element to the element to the left or right //!\param d Direction to move (-1 = left, 1 = right) void MoveSelectionHor(int d); //!Moves the selected element to the element above or below //!\param d Direction to move (-1 = up, 1 = down) void MoveSelectionVert(int d); //!Draws all the elements in this GuiWindow void Draw(); //!Updates the window and all elements contains within //!Allows the GuiWindow and all elements to respond to the input data specified //!\param t Pointer to a GuiTrigger, containing the current input data from PAD/WPAD void Update(GuiTrigger * t); protected: std::vector<GuiElement*> _elements; //!< Contains all elements within the GuiWindow }; //!Converts image data into GX-useable RGBA8. Currently designed for use only with PNG files class GuiImageData { public: //!Constructor //!Converts the image data to RGBA8 - expects PNG format //!\param i Image data GuiImageData(const u8 * i); //!Destructor ~GuiImageData(); //!Gets a pointer to the image data //!\return pointer to image data u8 * GetImage(); //!Gets the image width //!\return image width int GetWidth(); //!Gets the image height //!\return image height int GetHeight(); protected: u8 * data; //!< Image data int height; //!< Height of image int width; //!< Width of image }; //!Display, manage, and manipulate images in the GUI class GuiImage : public GuiElement { public: //!Constructor GuiImage(); //!\overload //!\param img Pointer to GuiImageData element GuiImage(GuiImageData * img); //!\overload //!Sets up a new image from the image data specified //!\param img //!\param w Image width //!\param h Image height GuiImage(u8 * img, int w, int h); //!\overload //!Creates an image filled with the specified color //!\param w Image width //!\param h Image height //!\param c Image color GuiImage(int w, int h, GXColor c); //!Destructor ~GuiImage(); //!Sets the image rotation angle for drawing //!\param a Angle (in degrees) void SetAngle(float a); //!Sets the number of times to draw the image horizontally //!\param t Number of times to draw the image void SetTile(int t); //!Constantly called to draw the image void Draw(); //!Gets the image data //!\return pointer to image data u8 * GetImage(); //!Sets up a new image using the GuiImageData object specified //!\param img Pointer to GuiImageData object void SetImage(GuiImageData * img); //!\overload //!\param img Pointer to image data //!\param w Width //!\param h Height void SetImage(u8 * img, int w, int h); //!Gets the pixel color at the specified coordinates of the image //!\param x X coordinate //!\param y Y coordinate GXColor GetPixel(int x, int y); //!Sets the pixel color at the specified coordinates of the image //!\param x X coordinate //!\param y Y coordinate //!\param color Pixel color void SetPixel(int x, int y, GXColor color); //!Directly modifies the image data to create a color-striped effect //!Alters the RGB values by the specified amount //!\param s Amount to increment/decrement the RGB values in the image void ColorStripe(int s); //!Directly modifies the image data to change the image to grayscale void Grayscale(); //!Sets a stripe effect on the image, overlaying alpha blended rectangles //!Does not alter the image data //!\param s Alpha amount to draw over the image void SetStripe(int s); protected: int imgType; //!< Type of image data (IMAGE_TEXTURE, IMAGE_COLOR, IMAGE_DATA) u8 * image; //!< Poiner to image data. May be shared with GuiImageData data f32 imageangle; //!< Angle to draw the image int tile; //!< Number of times to draw (tile) the image horizontally int stripe; //!< Alpha value (0-255) to apply a stripe effect to the texture }; //!Display, manage, and manipulate text in the GUI class GuiText : public GuiElement { public: //!Constructor //!\param t Text //!\param s Font size //!\param c Font color GuiText(const char * t, int s, GXColor c); //!\overload //!Assumes SetPresets() has been called to setup preferred text attributes //!\param t Text GuiText(const char * t); //!Destructor ~GuiText(); //!Sets the text of the GuiText element //!\param t Text void SetText(const char * t); //!Sets up preset values to be used by GuiText(t) //!Useful when printing multiple text elements, all with the same attributes set //!\param sz Font size //!\param c Font color //!\param w Maximum width of texture image (for text wrapping) //!\param s Font size //!\param h Text alignment (horizontal) //!\param v Text alignment (vertical) void SetPresets(int sz, GXColor c, int w, u16 s, int h, int v); //!Sets the font size //!\param s Font size void SetFontSize(int s); //!Sets the maximum width of the drawn texture image //!\param w Maximum width void SetMaxWidth(int w); //!Enables/disables text scrolling //!\param s Scrolling on/off void SetScroll(int s); //!Enables/disables text wrapping //!\param w Wrapping on/off //!\param width Maximum width (0 to disable) void SetWrap(bool w, int width = 0); //!Sets the font color //!\param c Font color void SetColor(GXColor c); //!Sets the FreeTypeGX style attributes //!\param s Style attributes void SetStyle(u16 s); //!Sets the text alignment //!\param hor Horizontal alignment (ALIGN_LEFT, ALIGN_RIGHT, ALIGN_CENTRE) //!\param vert Vertical alignment (ALIGN_TOP, ALIGN_BOTTOM, ALIGN_MIDDLE) void SetAlignment(int hor, int vert); //!Constantly called to draw the text void Draw(); protected: char * origText; //!< Original text data wchar_t* text; //!< Unicode text value int size; //!< Font size int maxWidth; //!< Maximum width of the generated text object (for text wrapping) bool wrap; //!< Wrapping toggle wchar_t* textDyn; //!< Wrapped text value int textScroll; //!< Scrolling toggle int textScrollPos; //!< Current starting index of text string for scrolling int textScrollInitialDelay; //!< Delay to wait before starting to scroll int textScrollDelay; //!< Scrolling speed u16 style; //!< FreeTypeGX style attributes GXColor color; //!< Font color }; //!Display, manage, and manipulate buttons in the GUI. Buttons can have images, icons, text, and sound set (all of which are optional) class GuiButton : public GuiElement { public: //!Constructor //!\param w Width //!\param h Height GuiButton(int w, int h); //!Destructor ~GuiButton(); //!Sets the button's image //!\param i Pointer to GuiImage object void SetImage(GuiImage* i); //!Sets the button's image on over //!\param i Pointer to GuiImage object void SetImageOver(GuiImage* i); //!Sets the button's image on hold //!\param i Pointer to GuiImage object void SetImageHold(GuiImage* i); //!Sets the button's image on click //!\param i Pointer to GuiImage object void SetImageClick(GuiImage* i); //!Sets the button's icon //!\param i Pointer to GuiImage object void SetIcon(GuiImage* i); //!Sets the button's icon on over //!\param i Pointer to GuiImage object void SetIconOver(GuiImage* i); //!Sets the button's icon on hold //!\param i Pointer to GuiImage object void SetIconHold(GuiImage* i); //!Sets the button's icon on click //!\param i Pointer to GuiImage object void SetIconClick(GuiImage* i); //!Sets the button's label //!\param t Pointer to GuiText object //!\param n Index of label to set (optional, default is 0) void SetLabel(GuiText* t, int n = 0); //!Sets the button's label on over (eg: different colored text) //!\param t Pointer to GuiText object //!\param n Index of label to set (optional, default is 0) void SetLabelOver(GuiText* t, int n = 0); //!Sets the button's label on hold //!\param t Pointer to GuiText object //!\param n Index of label to set (optional, default is 0) void SetLabelHold(GuiText* t, int n = 0); //!Sets the button's label on click //!\param t Pointer to GuiText object //!\param n Index of label to set (optional, default is 0) void SetLabelClick(GuiText* t, int n = 0); //!Sets the sound to play on over //!\param s Pointer to GuiSound object void SetSoundOver(GuiSound * s); //!Sets the sound to play on hold //!\param s Pointer to GuiSound object void SetSoundHold(GuiSound * s); //!Sets the sound to play on click //!\param s Pointer to GuiSound object void SetSoundClick(GuiSound * s); //!Constantly called to draw the GuiButton void Draw(); //!Constantly called to allow the GuiButton to respond to updated input data //!\param t Pointer to a GuiTrigger, containing the current input data from PAD/WPAD void Update(GuiTrigger * t); protected: GuiImage * image; //!< Button image (default) GuiImage * imageOver; //!< Button image for STATE_SELECTED GuiImage * imageHold; //!< Button image for STATE_HELD GuiImage * imageClick; //!< Button image for STATE_CLICKED GuiImage * icon; //!< Button icon (drawn after button image) GuiImage * iconOver; //!< Button icon for STATE_SELECTED GuiImage * iconHold; //!< Button icon for STATE_HELD GuiImage * iconClick; //!< Button icon for STATE_CLICKED GuiText * label[3]; //!< Label(s) to display (default) GuiText * labelOver[3]; //!< Label(s) to display for STATE_SELECTED GuiText * labelHold[3]; //!< Label(s) to display for STATE_HELD GuiText * labelClick[3]; //!< Label(s) to display for STATE_CLICKED GuiSound * soundOver; //!< Sound to play for STATE_SELECTED GuiSound * soundHold; //!< Sound to play for STATE_HELD GuiSound * soundClick; //!< Sound to play for STATE_CLICKED }; typedef struct _keytype { char ch, chShift; } Key; //!On-screen keyboard class GuiKeyboard : public GuiWindow { public: GuiKeyboard(char * t, u32 m); ~GuiKeyboard(); void Update(GuiTrigger * t); char kbtextstr[256]; protected: u32 kbtextmaxlen; Key keys[4][11]; int shift; int caps; GuiText * kbText; GuiImage * keyTextboxImg; GuiText * keyCapsText; GuiImage * keyCapsImg; GuiImage * keyCapsOverImg; GuiButton * keyCaps; GuiText * keyShiftText; GuiImage * keyShiftImg; GuiImage * keyShiftOverImg; GuiButton * keyShift; GuiText * keyBackText; GuiImage * keyBackImg; GuiImage * keyBackOverImg; GuiButton * keyBack; GuiImage * keySpaceImg; GuiImage * keySpaceOverImg; GuiButton * keySpace; GuiButton * keyBtn[4][11]; GuiImage * keyImg[4][11]; GuiImage * keyImgOver[4][11]; GuiText * keyTxt[4][11]; GuiImageData * keyTextbox; GuiImageData * key; GuiImageData * keyOver; GuiImageData * keyMedium; GuiImageData * keyMediumOver; GuiImageData * keyLarge; GuiImageData * keyLargeOver; GuiSound * keySoundOver; GuiSound * keySoundClick; GuiTrigger * trigA; }; typedef struct _optionlist { int length; char name[MAX_OPTIONS][50]; char value[MAX_OPTIONS][50]; } OptionList; //!Display a list of menu options class GuiOptionBrowser : public GuiElement { public: GuiOptionBrowser(int w, int h, OptionList * l); ~GuiOptionBrowser(); void SetCol2Position(int x); int FindMenuItem(int c, int d); int GetClickedOption(); void ResetState(); void SetFocus(int f); void Draw(); void TriggerUpdate(); void Update(GuiTrigger * t); GuiText * optionVal[PAGESIZE]; protected: int selectedItem; int listOffset; bool listChanged; OptionList * options; int optionIndex[PAGESIZE]; GuiButton * optionBtn[PAGESIZE]; GuiText * optionTxt[PAGESIZE]; GuiImage * optionBg[PAGESIZE]; GuiButton * arrowUpBtn; GuiButton * arrowDownBtn; GuiImage * bgOptionsImg; GuiImage * scrollbarImg; GuiImage * arrowDownImg; GuiImage * arrowDownOverImg; GuiImage * arrowUpImg; GuiImage * arrowUpOverImg; GuiImageData * bgOptions; GuiImageData * bgOptionsEntry; GuiImageData * scrollbar; GuiImageData * arrowDown; GuiImageData * arrowDownOver; GuiImageData * arrowUp; GuiImageData * arrowUpOver; GuiSound * btnSoundOver; GuiSound * btnSoundClick; GuiTrigger * trigA; }; //!Display a list of files class GuiFileBrowser : public GuiElement { public: GuiFileBrowser(int w, int h); ~GuiFileBrowser(); void ResetState(); void SetFocus(int f); void Draw(); void TriggerUpdate(); void Update(GuiTrigger * t); GuiButton * fileList[FILE_PAGESIZE]; protected: int selectedItem; int numEntries; bool listChanged; GuiText * fileListText[FILE_PAGESIZE]; GuiImage * fileListBg[FILE_PAGESIZE]; GuiImage * fileListFolder[FILE_PAGESIZE]; GuiButton * arrowUpBtn; GuiButton * arrowDownBtn; GuiButton * scrollbarBoxBtn; GuiImage * bgFileSelectionImg; GuiImage * scrollbarImg; GuiImage * arrowDownImg; GuiImage * arrowDownOverImg; GuiImage * arrowUpImg; GuiImage * arrowUpOverImg; GuiImage * scrollbarBoxImg; GuiImage * scrollbarBoxOverImg; GuiImageData * bgFileSelection; GuiImageData * bgFileSelectionEntry; GuiImageData * fileFolder; GuiImageData * scrollbar; GuiImageData * arrowDown; GuiImageData * arrowDownOver; GuiImageData * arrowUp; GuiImageData * arrowUpOver; GuiImageData * scrollbarBox; GuiImageData * scrollbarBoxOver; GuiSound * btnSoundOver; GuiSound * btnSoundClick; GuiTrigger * trigA; GuiTrigger * trigHeldA; }; #endif
[ "rhydonj@cd65cd96-570e-b3a8-811c-2f05879e1164" ]
[ [ [ 1, 894 ] ] ]
65f96a58883a2f7a4b5dc002207b5aedd55314db
2ca3ad74c1b5416b2748353d23710eed63539bb0
/Src/Lokapala/Raptor/StatusReportDTO.cpp
a6d4c6d5ba6055d6060271d051c03de4ad4bc1a0
[]
no_license
sjp38/lokapala
5ced19e534bd7067aeace0b38ee80b87dfc7faed
dfa51d28845815cfccd39941c802faaec9233a6e
refs/heads/master
2021-01-15T16:10:23.884841
2009-06-03T14:56:50
2009-06-03T14:56:50
32,124,140
0
0
null
null
null
null
UTF-8
C++
false
false
702
cpp
/**@file StatusReportDTO.cpp * @brief CStatusReportDTO 클래스의 멤버함수를 구현한다. * @author siva */ #include "stdafx.h" #include "StatusReportDTO.h" /**@brief 생성자. 랩터에선 이걸 쓰진 않는다. */ CStatusReportDTO::CStatusReportDTO(CString a_hostAddress, State a_state, CString a_date, CString a_comment) { m_hostAddress = a_hostAddress; m_state = a_state; m_date = a_date; m_comment = a_comment; } /**@brief 생성자. 랩터에선 이걸 쓰게 된다. */ CStatusReportDTO::CStatusReportDTO(State a_state, CString a_date, CString a_comment) { m_hostAddress = _T(""); m_state = a_state; m_date = a_date; m_comment = a_comment; }
[ "nilakantha38@b9e76448-5c52-0410-ae0e-a5aea8c5d16c" ]
[ [ [ 1, 25 ] ] ]
f06a7b9929b0373c21fdb15cd823f54e57c79579
58ef4939342d5253f6fcb372c56513055d589eb8
/SimulateMessage/Client/source/Tools/src/QueryDlgUtil.cpp
000b21a3e027b27d9ceb885f22bf2484528fb1eb
[]
no_license
flaithbheartaigh/lemonplayer
2d77869e4cf787acb0aef51341dc784b3cf626ba
ea22bc8679d4431460f714cd3476a32927c7080e
refs/heads/master
2021-01-10T11:29:49.953139
2011-04-25T03:15:18
2011-04-25T03:15:18
50,263,327
0
0
null
null
null
null
GB18030
C++
false
false
5,256
cpp
#include <StringLoader.h> #include <AknQueryDialog.h> #include <AknGlobalNote.h> #include <aknnotewrappers.h> #include <aknmessagequerydialog.h> #include "SHPlatform.h" /********** * * RESOURCE DIALOG r_confirmation_query { flags = EGeneralQueryFlags; buttons = R_AVKON_SOFTKEYS_YES_NO; items = { DLG_LINE { type = EAknCtQuery; id = EGeneralQuery; control = AVKON_CONFIRMATION_QUERY { layout = EConfirmationQueryLayout; label = STRING_r_contacts_con_label_text; }; } }; } RESOURCE DIALOG r_dialog_input { flags = EGeneralQueryFlags; buttons = R_AVKON_SOFTKEYS_OK_CANCEL; items = { DLG_LINE { type = EAknCtQuery; id = EGeneralQuery; control = AVKON_DATA_QUERY { layout = EDataLayout; label = qtn_dialog_url; control = EDWIN { maxlength = 40; }; }; } }; } RESOURCE DIALOG r_about_query_dialog { flags = EGeneralQueryFlags | EEikDialogFlagNoBorder | EEikDialogFlagNoShadow; buttons = R_AVKON_SOFTKEYS_OK_EMPTY; items= { DLG_LINE { type = EAknCtPopupHeadingPane; id = EAknMessageQueryHeaderId; itemflags = EEikDlgItemNonFocusing; control = AVKON_HEADING { }; }, DLG_LINE { type = EAknCtMessageQuery; id = EAknMessageQueryContentId; control = AVKON_MESSAGE_QUERY { }; } }; } * */ TBool ShowConfirmationQueryL( const TInt& aTextResourceId ) { HBufC* prompt = StringLoader::LoadLC( aTextResourceId ); CAknQueryDialog* dlg = CAknQueryDialog::NewL(); dlg->SetPromptL( *prompt ); TInt retCode( dlg->ExecuteLD( R_CONFIRMATION_QUERY ) ); CleanupStack::PopAndDestroy(); //prompt return retCode; } TBool ShowConfirmationQueryL( const TDesC& aText ) { CAknQueryDialog* dlg = CAknQueryDialog::NewL(); dlg->SetPromptL( aText ); TInt retCode( dlg->ExecuteLD( R_CONFIRMATION_QUERY ) ); return retCode; } TInt StartWaitingDlg(const TInt& aTextResourceId) { HBufC* prompt = StringLoader::LoadLC( aTextResourceId ); CAknGlobalNote* globalNote = CAknGlobalNote::NewL(); CleanupStack::PushL( globalNote ); TInt noteId = globalNote->ShowNoteL( EAknGlobalWaitNote, prompt->Des() ); CleanupStack::PopAndDestroy(2); return noteId; } void EndWaitingDlg(const TInt& aDlgId) { CAknGlobalNote * note = CAknGlobalNote::NewL(); CleanupStack::PushL( note ); note->CancelNoteL( aDlgId ); CleanupStack::PopAndDestroy(); } void ShowInfomationDlgL(const TInt& aTextResourceId) { HBufC* prompt = StringLoader::LoadLC( aTextResourceId ); CAknInformationNote* iInfoNote = new (ELeave) CAknInformationNote; iInfoNote->ExecuteLD(prompt->Des()); CleanupStack::PopAndDestroy(); } void ShowInfomationDlgL(const TDesC& aDes) { CAknInformationNote* iInfoNote = new (ELeave) CAknInformationNote; iInfoNote->ExecuteLD(aDes); } TBool ShowInputDlgL(const TInt& aTextResourceId,TDes& aText) { HBufC* prompt = StringLoader::LoadLC( aTextResourceId ); CAknTextQueryDialog* dlg = CAknTextQueryDialog::NewL( aText ); dlg->SetPromptL(prompt->Des()); dlg->SetMaxLength(KMaxName); TInt retCode( dlg->ExecuteLD( R_DIALOG_INPUT )); CleanupStack::PopAndDestroy(); //prompt return retCode; } TBool ShowModalInfoDlgL(const TInt& aTextHeaderId,const TDesC& aDes) { HBufC* prompt = StringLoader::LoadLC( aTextHeaderId ); CEikonEnv::Static()->InfoWinL(prompt->Des(),aDes); //任意使用 CleanupStack::PopAndDestroy(); //prompt return ETrue; } TBool ShowModalInfoDlgL(const TInt& aTextHeaderId,const TInt& aTextResourceId) { HBufC* header = StringLoader::LoadLC( aTextHeaderId ); HBufC* prompt = StringLoader::LoadLC( aTextResourceId ); CEikonEnv::Static()->InfoWinL(header->Des(), prompt->Des()); //任意使用 CleanupStack::PopAndDestroy(2); //prompt return ETrue; } TBool ShowModalAboutDlgL(const TInt& aTextHeaderId,const TInt& aTextResourceId) { CAknMessageQueryDialog* dlg = new (ELeave) CAknMessageQueryDialog(); dlg->PrepareLC(R_ABOUT_QUERY_DIALOG); HBufC* title = StringLoader::LoadLC(aTextHeaderId); dlg->QueryHeading()->SetTextL(*title); CleanupStack::PopAndDestroy(); //title HBufC* msg = StringLoader::LoadLC(aTextResourceId); dlg->SetMessageTextL(*msg); CleanupStack::PopAndDestroy(); //msg dlg->RunLD(); return ETrue; } TBool ShowModalAboutDlgL(const TInt& aTextHeaderId,const TDesC& aDes) { CAknMessageQueryDialog* dlg = new (ELeave) CAknMessageQueryDialog(); dlg->PrepareLC(R_ABOUT_QUERY_DIALOG); HBufC* title = StringLoader::LoadLC(aTextHeaderId); dlg->QueryHeading()->SetTextL(*title); CleanupStack::PopAndDestroy(); //title dlg->SetMessageTextL(aDes); dlg->RunLD(); return ETrue; }
[ "zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494" ]
[ [ [ 1, 209 ] ] ]
2b67e808109a74461dd1863d2fba080d4dc57f6d
f25e9e8fd224f81cefd6d900f6ce64ce77abb0ae
/Exercises/LinearAlgebraUnitTest/LinearAlgebraUnityTest/LinearAlgebraUnityTest.cpp
b9462fb5c63446c9434071ae418eeccfeaca6054
[]
no_license
giacomof/gameengines2010itu
8407be66d1aff07866d3574a03804f2f5bcdfab1
bc664529a429394fe5743d5a76a3d3bf5395546b
refs/heads/master
2016-09-06T05:02:13.209432
2010-12-12T22:18:19
2010-12-12T22:18:19
35,165,366
0
0
null
null
null
null
UTF-8
C++
false
false
14,629
cpp
// LinearAlgebraUnityTest.cpp : Defines the entry point for the console application. // #include "linearAlgebraDLL.h" #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> #include <boost/test/floating_point_comparison.hpp> #define PI = 3.141592 using namespace linearAlgebraDLL; using namespace boost::unit_test; // Test case for methods of the Vector class BOOST_AUTO_TEST_CASE( vector_methods ) { // Istantiation of various vectors for the tests Vector nX = Vector(1.0f, 0.0f, 0.0f); Vector nY = Vector(0.0f, 1.0f, 0.0f); Vector nZ = Vector(0.0f, 0.0f, 1.0f); Vector temp = Vector(3.0f, 1.0f, 2.0f); Vector zero = Vector(0.0f, 0.0f, 0.0f); Vector one = Vector(1.0f, 1.0f, 1.0f); Vector two = Vector(2.0f, 2.0f, 2.0f); // Test for the vector getMagnitude() method BOOST_CHECK(nX.getMagnitude() == 1.0f); BOOST_CHECK_CLOSE( two.getMagnitude(), 3.4641f, 0.1 ); // Test for the vector getQuadraticMagnitude() method BOOST_CHECK(one.getQuadraticMagnitude() == 3.0f); BOOST_CHECK(two.getQuadraticMagnitude() == 12.0f); // Test for the vector normalize() method BOOST_CHECK(nX.normalize() == nX); temp = temp.normalize(); BOOST_CHECK_CLOSE( temp.get(0), 0.802f, 0.1 ); BOOST_CHECK_CLOSE( temp.get(1), 0.267f, 0.1 ); BOOST_CHECK_CLOSE( temp.get(2), 0.534f, 0.1 ); // Test for the vector get() method BOOST_CHECK(nX.get(0) == 1.0f); BOOST_CHECK(nZ.get(2) == 1.0f); BOOST_CHECK(nY.get(0) != 1.0f); // Test for the vector set() method zero.set(0, 2.0f); zero.set(1, 2.0f); zero.set(2, 2.0f); BOOST_CHECK(zero.get(0) == 2.0f); BOOST_CHECK(zero.get(1) == 2.0f); BOOST_CHECK(zero.get(2) == 2.0f); } // Test case for operators overload for Vector class BOOST_AUTO_TEST_CASE( vector_operators_overloads ) { // Istantiation of normalized vectors coincident with axes Vector nX = Vector(1.0f, 0.0f, 0.0f); Vector nY = Vector(0.0f, 1.0f, 0.0f); Vector nZ = Vector(0.0f, 0.0f, 1.0f); //Istantiation of various vectors for the tests Vector one = Vector(1.0f, 1.0f, 1.0f); // Test for the vector comparison operation BOOST_CHECK(nX == nX); BOOST_CHECK(one == one); // Test for the vectors sum BOOST_CHECK(nX + nY == Vector(1.0f, 1.0f, 0.0f)); BOOST_CHECK(nX + nZ == Vector(1.0f, 0.0f, 1.0f)); BOOST_CHECK(nX + nY + nZ == Vector(1.0f, 1.0f, 1.0f)); // Test for the vectors subtraction BOOST_CHECK(one - nY == Vector(1.0f, 0.0f, 1.0f)); BOOST_CHECK(one - nZ - nX == Vector(0.0f, 1.0f, 0.0f)); BOOST_CHECK(nX - nY - nZ == Vector(1.0f, -1.0f, -1.0f)); // Test for the product between vectors and scalars BOOST_CHECK(nX * 3.0f == Vector(3.0f, 0.0f, 0.0f)); BOOST_CHECK(one * -5.0f == Vector(-5.0f, -5.0f, -5.0f)); // Test for the vector scalar product BOOST_CHECK(nX * nY == 0); BOOST_CHECK(nX * nX == 1); // Test for the vector cross product BOOST_CHECK(nX % nY == nZ); BOOST_CHECK(one % nY == Vector(-1.0f, 0.0f, 1.0f)); // Test for the vector [] operator BOOST_CHECK(nX[0] == 1.0f); BOOST_CHECK(nZ[2] == 1.0f); BOOST_CHECK(nY[0] != 1.0f); } // Test case for operators overload for Point class BOOST_AUTO_TEST_CASE( point_operators_overload ) { // Istantiation of various points for the tests Point p1 = Point(1.0f, 1.0f, 1.0f); Point p2 = Point(2.0f, 2.0f, 2.0f); Point p123 = Point(1.0f, 2.0f, 3.0f); Point p234 = Point(2.0f, 3.0f, 4.0f); //Istantiation of various vectors for the tests Vector zero = Vector(0.0f, 0.0f, 0.0f); Vector one = Vector(1.0f, 1.0f, 1.0f); Vector test1 = Vector(0.0f, 1.0f, 2.0f); // Test for the points subtraction BOOST_CHECK(p123 - p1 == test1); BOOST_CHECK(p1 - p1 == zero); // Test for the points and vectors sum BOOST_CHECK(p1 + one == p2); BOOST_CHECK(p123 + one == p234); } // Test case for methods of Quaternion class BOOST_AUTO_TEST_CASE( quaternion_methods ) { // Istantiation of various quaternions for the tests Quaternion q1 = Quaternion(Vector(1.0f, 0.0f, 0.0f), 60.0f); Quaternion q2 = Quaternion(Vector(0.0f, 0.0f, 1.0f), 45.0f); Quaternion q3 = Quaternion(Vector(1.0f, 0.0f, 1.0f), 90.0f); // Test for the quaternion getMagnitude() method BOOST_CHECK(q1.getMagnitude() == 1); // Test for the quaternion normalize() method Quaternion qTest = Quaternion(); qTest.setX(12); qTest.setY(8); qTest.setZ(1); qTest.setW(459.0f); BOOST_CHECK(qTest.getMagnitude() > 1); BOOST_CHECK(qTest.normalize().getMagnitude() == 1); // Test for the quaternion getVector() method Vector test1 = q1.getVector(); BOOST_CHECK_CLOSE( test1.get(0), 0.4999f, 0.1 ); BOOST_CHECK_CLOSE( test1.get(1), 0.0f, 0.1 ); BOOST_CHECK_CLOSE( test1.get(2), 0.0f, 0.1 ); Vector test2 = q3.getVector(); BOOST_CHECK_CLOSE( test2.get(0), 0.4999f, 0.1 ); BOOST_CHECK_CLOSE( test2.get(1), 0.0f, 0.1 ); BOOST_CHECK_CLOSE( test2.get(2), 0.4999f, 0.1 ); // Test for the quaternion getW() method BOOST_CHECK_CLOSE( q1.getW(), 0.8660f, 0.1 ); BOOST_CHECK_CLOSE( q3.getW(), 0.7071f, 0.1 ); // Test for the quaternion getAxisAngle() method Vector * vectorTestPtr; vectorTestPtr = &Vector(); float testF = 0; q1.getAxisAngle(vectorTestPtr, &testF); BOOST_CHECK(*vectorTestPtr == Vector(1.0f, 0.0f, 0.0f)); BOOST_CHECK_CLOSE( testF, 60.0f, 0.1 ); // Test for the quaternion setW() method q3.setW(12.0f); BOOST_CHECK(q3.getW() == 12.0f); } // Test case for operators overload for Quaternion class BOOST_AUTO_TEST_CASE( quaternion_operators_overload ) { // Istantiation of various quaternions for the tests Quaternion q1 = Quaternion(Vector(1.0f, 0.0f, 0.0f), 60.0f); Quaternion q2 = Quaternion(Vector(0.0f, 0.0f, 1.0f), 45.0f); Quaternion q3 = Quaternion(Vector(1.0f, 0.0f, 1.0f), 90.0f); //Istantiation of various vectors for the tests Vector zero = Vector(0.0f, 0.0f, 0.0f); Vector one = Vector(1.0f, 1.0f, 1.0f); // Test case for the quaternions comparison operation BOOST_CHECK(q1 == q1); BOOST_CHECK(q2 == q2); // Test case for the quaternions sum operation Quaternion test1 = q1 + q2; BOOST_CHECK_CLOSE( test1.getVector().get(0), 0.4999f, 0.1 ); BOOST_CHECK_CLOSE( test1.getVector().get(1), 0.0f, 0.1 ); BOOST_CHECK_CLOSE( test1.getVector().get(2), 0.3826f, 0.1 ); BOOST_CHECK_CLOSE( test1.getW(), 1.7899f, 0.1 ); Quaternion test2 = q2 + q3; BOOST_CHECK_CLOSE( test2.getVector().get(0), 0.4999f, 0.1 ); BOOST_CHECK_CLOSE( test2.getVector().get(1), 0.0f, 0.1 ); BOOST_CHECK_CLOSE( test2.getVector().get(2), 0.8826f, 0.1 ); BOOST_CHECK_CLOSE( test2.getW(), 1.6309f, 0.1 ); // Test case for the quaternions multiplication operation Quaternion test3 = q1 * q2; BOOST_CHECK_CLOSE( test3.getVector().get(0), 0.4619f, 0.1 ); BOOST_CHECK_CLOSE( test3.getVector().get(1), -0.1913f, 0.1 ); BOOST_CHECK_CLOSE( test3.getVector().get(2), 0.3314f, 0.1 ); BOOST_CHECK_CLOSE( test3.getW(), 0.8001f, 0.1 ); Quaternion test4 = q2 * q3; BOOST_CHECK_CLOSE( test4.getVector().get(0), 0.4619f, 0.1 ); BOOST_CHECK_CLOSE( test4.getVector().get(1), 0.1913f, 0.1 ); BOOST_CHECK_CLOSE( test4.getVector().get(2), 0.7325f, 0.1 ); BOOST_CHECK_CLOSE( test4.getW(), 0.4619f, 0.1 ); // Test case for the quaternions and vectors multiplication Vector result = q3 * one; BOOST_CHECK_CLOSE(result.getX(), 0.5f, 0.1); BOOST_CHECK_CLOSE(result.getY(), 0.0f, 0.1); BOOST_CHECK_CLOSE(result.getZ(), 0.5f, 0.1); } // Test case for methods and operators of the Matrix class BOOST_AUTO_TEST_CASE( matrix_methods ) { // Istantiation of various matrices for the tests Matrix m1 = Matrix( 0.0f, 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f, 10.0f, 11.0f, 0.0f, 0.0f, 0.0f, 1.0f); Matrix m1t = Matrix( 0.0f, 4.0f, 8.0f, 0.0f, 1.0f, 5.0f, 9.0f, 0.0f, 2.0f, 6.0f, 10.0f, 0.0f, 3.0f, 7.0f, 11.0f, 1.0f); Matrix m2 = Matrix( 0.0f, 2.0f, 4.0f, 6.0f, 8.0f, 10.0f, 12.0f, 14.0f, 16.0f, 18.0f, 20.0f, 22.0f, 0.0f, 0.0f, 0.0f, 2.0f); Matrix manualIdentity = Matrix( 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); Matrix mTranslation345 = Matrix( 1.0f, 0.0f, 0.0f, 3.0f, 0.0f, 1.0f, 0.0f, 4.0f, 0.0f, 0.0f, 1.0f, 5.0f, 0.0f, 0.0f, 0.0f, 1.0f); Matrix mScaling678 = Matrix( 6.0f, 0.0f, 0.0f, 0.0f, 0.0f, 7.0f, 0.0f, 0.0f, 0.0f, 0.0f, 8.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); Matrix mUniformScaling9 = Matrix( 9.0f, 0.0f, 0.0f, 0.0f, 0.0f, 9.0f, 0.0f, 0.0f, 0.0f, 0.0f, 9.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); Matrix mXRotationM90 = Matrix( 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); Matrix mYRotation45 = Matrix( 0.707107f, 0.0f, 0.707106f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, -0.707106f, 0.0f, 0.707106f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); Matrix mZRotation30 = Matrix( 0.866026f, -0.5f, 0.0f, 0.0f, 0.5f, 0.866026f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); Matrix mAxisRotation = Matrix( 1.0f, -0.866025f, 0.499999f, 0.0f, 0.866025f, 0.500001f, -0.866025f, 0.0f, 0.0f, 0.866025f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); Matrix mQuaternionRotation = Matrix( 0.75f, -0.612372f, 0.25f, 0.0f, 0.612372f, 0.500001f, -0.612372f, 0.0f, 0.25f, 0.612372f, 0.75f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); Matrix mShearingMatrix = Matrix( 1.0f, 1.0f, 2.0f, 0.0f, 3.0f, 1.0f, 4.0f, 0.0f, 5.0f, 6.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); // Istantiation of various points and vectors for the tests Vector vTwo = Vector(2.0f, 2.0f, 2.0f); Point pTwo = Point(2.0f, 2.0f, 2.0f); // Used to compare floating point values double epsilon; // Test for the compare operator between matrices BOOST_CHECK(m1 == m1); BOOST_CHECK(manualIdentity == manualIdentity); // Test for the generateIdentityMatrix() method BOOST_CHECK(manualIdentity == Matrix::generateIdentityMatrix()); // Test for the generateTranslationMatrix() method BOOST_CHECK(mTranslation345 == Matrix::generateTranslationMatrix(3.0f, 4.0f, 5.0f)); // Test for the generateScalingMatrix() method BOOST_CHECK(mScaling678 == Matrix::generateScalingMatrix(6.0f, 7.0f, 8.0f)); // Test for the generateUniformScalingMatrix() method BOOST_CHECK(mUniformScaling9 == Matrix::generateUniformScalingMatrix(9.0f)); // Test for the generateXRotationMatrix() method Matrix generatedMXRotationM90 = Matrix::generateXRotationMatrix(-90.0); for(unsigned short r = 0; r < 4; r++) { for(unsigned short c = 0; c < 4; c++) { epsilon = generatedMXRotationM90.get(r, c) - mXRotationM90.get(r, c); BOOST_CHECK_SMALL( epsilon, 0.00001 ); } } // Test for the generateYRotationMatrix() method Matrix generatedMYRotation45 = Matrix::generateYRotationMatrix(45.0); for(unsigned short r = 0; r < 4; r++) { for(unsigned short c = 0; c < 4; c++) { epsilon = generatedMYRotation45.get(r, c) - mYRotation45.get(r, c); BOOST_CHECK_SMALL( epsilon, 0.00001 ); } } // Test for the generateZRotationMatrix() method Matrix generatedMZRotation30 = Matrix::generateZRotationMatrix(30.0); for(unsigned short r = 0; r < 4; r++) { for(unsigned short c = 0; c < 4; c++) { epsilon = generatedMZRotation30.get(r, c) - mZRotation30.get(r, c); BOOST_CHECK_SMALL( epsilon, 0.00001 ); } } // Test for the generateAxesRotationMatrix() method Matrix generatedAxisRotation = Matrix::generateAxisRotationMatrix(Vector(1.0f, 0.0f, 1.0f), 60.0f); for(unsigned short r = 0; r < 4; r++) { for(unsigned short c = 0; c < 4; c++) { epsilon = generatedAxisRotation.get(r, c) - mAxisRotation.get(r, c); BOOST_CHECK_SMALL( epsilon, 0.00001 ); } } // Test for the generateQuaternionRotationMatrix() method Matrix generatedQuaternionRotation = Matrix::generateQuaternionRotationMatrix(Quaternion(Vector(1.0f, 0.0f, 1.0f), 60.0f)); for(unsigned short r = 0; r < 4; r++) { for(unsigned short c = 0; c < 4; c++) { epsilon = generatedQuaternionRotation.get(r, c) - mQuaternionRotation.get(r, c); BOOST_CHECK_SMALL( epsilon, 0.00001 ); } } // Test for the generateShearingMatrix() method Matrix generatedShearingMatrix = Matrix::generateShearingMatrix(1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f); for(unsigned short r = 0; r < 4; r++) { for(unsigned short c = 0; c < 4; c++) { epsilon = generatedShearingMatrix.get(r, c) - mShearingMatrix.get(r, c); BOOST_CHECK_SMALL( epsilon, 0.00001 ); } } // Test for the function for returning the quaternion from a matrix Quaternion quaternionCheck = Quaternion(Vector(1.0f, 0.0f, 1.0f), 60.0f); Quaternion quateternionResult = Matrix::getQuaternion(generatedQuaternionRotation); BOOST_CHECK_CLOSE( quateternionResult.getX(),quaternionCheck.getX(), 0.1 ); BOOST_CHECK_CLOSE( quateternionResult.getY(),quaternionCheck.getY(), 0.1 ); BOOST_CHECK_CLOSE( quateternionResult.getZ(),quaternionCheck.getZ(), 0.1 ); BOOST_CHECK_CLOSE( quateternionResult.getW(),quaternionCheck.getW(), 0.1 ); // Test for the Matrix * Matrix operator BOOST_CHECK( m1 * manualIdentity == m1); // Test for the Matrix * scalar operator BOOST_CHECK( m1 * 2.0f == m2); // Test for the Matrix * vector/point operator BOOST_CHECK( mTranslation345 * vTwo == vTwo); BOOST_CHECK( mUniformScaling9 * vTwo == Vector(18.0f, 18.0f, 18.0f)); BOOST_CHECK( mTranslation345 * pTwo == Point(5.0f, 6.0f, 7.0f)); // Test for the getTranspose() method BOOST_CHECK( m1.getTranspose() == m1t); // Test for the getInverse() method BOOST_CHECK(Matrix::generateIdentityMatrix().getInverse() == manualIdentity); Matrix inverseTest = mAxisRotation * mAxisRotation.getInverse(); for(unsigned short r = 0; r < 4; r++) { for(unsigned short c = 0; c < 4; c++) { epsilon = manualIdentity.get(r, c) - inverseTest.get(r, c); BOOST_CHECK_SMALL( epsilon, 0.00001 ); } } // Test for the getInverse() method BOOST_CHECK(m1.getDeterminant() == 0); // Test for the getRowAsVector() method BOOST_CHECK(m1t.getRowAsVector(1) == Vector(1.0f, 5.0f, 9.0f)); // Test for the getColumnAsVector() method BOOST_CHECK(m2.getColumnAsVector(0) == Vector(0.0f, 8.0f, 16.0f)); }
[ "[email protected]@1a5f623d-5e27-cfcb-749e-01bf3eb0ad9d" ]
[ [ [ 1, 433 ] ] ]
e04d558c9eabaa6a33fb5c9fc16e89a6c186537e
b8fe0ddfa6869de08ba9cd434e3cf11e57d59085
/NxOgre/rendersystems/ogre/OGRE3DRenderSystem.h
858a35555b6458c88004b4913aa0aad1c519bf85
[]
no_license
juanjmostazo/ouan-tests
c89933891ed4f6ad48f48d03df1f22ba0f3ff392
eaa73fb482b264d555071f3726510ed73bef22ea
refs/heads/master
2021-01-10T20:18:35.918470
2010-06-20T15:45:00
2010-06-20T15:45:00
38,101,212
0
0
null
null
null
null
UTF-8
C++
false
false
7,477
h
/** File: OGRE3DRenderSystem.h Created on: 25-Nov-08 Author: Robin Southern "betajaen" Copyright (c) 2008-2009 Robin Southern 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 OGRE3D_RENDERSYSTEM_H #define OGRE3D_RENDERSYSTEM_H #include "OGRE3DCommon.h" #include "NxOgre.h" #include "NxOgreArray.h" #include "Ogre.h" class OGRE3DExportClass OGRE3DRenderSystem : public NxOgre::PointerClass<_OGRE3DRenderSystem>, public NxOgre::TimeListener { public: /** \brief OGRE3DRenderSystem constructor. \param Scene* Scene to work with \param SceneManager SceneManager, or 0 to use the first available. */ OGRE3DRenderSystem(NxOgre::Scene*, Ogre::SceneManager* = ::Ogre::Root::getSingletonPtr()->getSceneManagerIterator().getNext()); /** \brief */ ~OGRE3DRenderSystem(void); /** \brief Get the scene. */ NxOgre::Scene* getScene(void); /** \brief Create a Body. */ OGRE3DBody* createBody(NxOgre::Shape*, NxOgre::Vec3 position, const Ogre::String& meshName, const NxOgre::RigidBodyDescription& = NxOgre::RigidBodyDescription()); /** \brief Create a Body. */ OGRE3DBody* createBody(NxOgre::Shapes, NxOgre::Vec3 position, const Ogre::String& meshName, const NxOgre::RigidBodyDescription& = NxOgre::RigidBodyDescription()); /** \brief Create a Body. \note SceneNode will be now be "owned" by the Body, and will release it and the contents when destroyed. */ OGRE3DBody* createBody(NxOgre::Shape*, NxOgre::Vec3 position, Ogre::SceneNode*, const NxOgre::RigidBodyDescription& = NxOgre::RigidBodyDescription()); /** \brief Create a Body, with a scenenode. \note SceneNode will be now be "owned" by the Body, and will release it and the contents when destroyed. -- OUAN HACK - NOT NOW */ OGRE3DBody* createBody(NxOgre::Shapes, NxOgre::Vec3 position, Ogre::SceneNode*, const NxOgre::RigidBodyDescription& = NxOgre::RigidBodyDescription()); /** \brief Destroy a Body. */ void destroyBody(OGRE3DBody*); /** \brief Create and manage a Renderable. */ OGRE3DRenderable* createRenderable(NxOgre::Enums::RenderableType, const Ogre::String& materialName = "BaseWhiteNoLighting"); /** \brief Destroy a Renderable. */ void destroyRenderable(OGRE3DRenderable*); /** \brief Create and manage a point Renderable. */ OGRE3DPointRenderable* createPointRenderable(const Ogre::String& ogre_mesh_name); /** \brief Create and manage a point Renderable. */ OGRE3DPointRenderable* createPointRenderable(Ogre::MovableObject*); /** \brief Create and manage a point Renderable. * OUAN HACK */ OGRE3DPointRenderable* createPointRenderable(Ogre::SceneNode*); /** \brief Destroy a Renderable. */ void destroyPointRenderable(OGRE3DPointRenderable*); /** \brief Create a KinematicBody, a KinematicActor as a Body. */ OGRE3DKinematicBody* createKinematicBody(NxOgre::Shape*, NxOgre::Vec3 position, const Ogre::String& meshName, const NxOgre::RigidBodyDescription& = NxOgre::RigidBodyDescription()); /** OUAN HACK */ OGRE3DKinematicBody* createKinematicBody(NxOgre::Shape*, NxOgre::Vec3 position, Ogre::SceneNode* node, const NxOgre::RigidBodyDescription& = NxOgre::RigidBodyDescription()); /** \brief Destroy a KinematicBody. */ void destroyKinematicBody(OGRE3DKinematicBody*); /** \brief Helper function for Debug Visualisation. */ void setVisualisationMode(NxOgre::Enums::VisualDebugger); /** \brief Is the Visual Debuggger active? */ bool hasDebugVisualisation(void) const; /** \internal Do not call. */ bool advance(float user_deltaTime, const NxOgre::Enums::Priority&); /** \brief */ Ogre::SceneManager* getSceneManager(); /** \brief Create an unique name */ Ogre::String getUniqueName(const Ogre::String& prefix) const; /** \brief Helper function to create a cloth using the OGRE3DRenderable */ NxOgre::Cloth* createCloth(const NxOgre::ClothDescription&, const Ogre::String& material = "BaseWhiteNoLighting"); /** \brief Helper function to destroya cloth with a OGRE3DRenderable */ void destroyCloth(NxOgre::Cloth*); /** \brief Helper function to create a soft body using the OGRE3DRenderable */ NxOgre::SoftBody* createSoftBody(const NxOgre::SoftBodyDescription&, const Ogre::String& material = "BaseWhiteNoLighting"); /** \brief Helper function to destroya soft body with a OGRE3DRenderable */ void destroySoftBody(NxOgre::SoftBody*); protected: NxOgre::Scene* mScene; Ogre::SceneManager* mSceneManager; NxOgre::Array<OGRE3DBody*> mBodies; NxOgre::Array<OGRE3DKinematicBody*> mKinematicBodies; NxOgre::Array<OGRE3DRenderable*> mRenderables; NxOgre::Array<OGRE3DPointRenderable*> mPointRenderables; OGRE3DRenderable* mVisualDebuggerRenderable; Ogre::SceneNode* mVisualDebuggerNode; bool mVisualDebuggerShown; static unsigned int mUniqueIdentifier; }; #endif
[ "ithiliel@6899d1ce-2719-11df-8847-f3d5e5ef3dde", "juanj.mostazo@6899d1ce-2719-11df-8847-f3d5e5ef3dde" ]
[ [ [ 1, 71 ], [ 73, 107 ], [ 111, 177 ] ], [ [ 72, 72 ], [ 108, 110 ] ] ]
8b9d1be5bdb1517006dfa2dadf08d13a55112064
2f72d621e6ec03b9ea243a96e8dd947a952da087
/lol4edit/gui/GenericSelectDialog.cpp
dce0380d44c9eb3f498bb5a6540556b70df0046d
[]
no_license
gspu/lol4fg
752358c3c3431026ed025e8cb8777e4807eed7a0
12a08f3ef1126ce679ea05293fe35525065ab253
refs/heads/master
2023-04-30T05:32:03.826238
2011-07-23T23:35:14
2011-07-23T23:35:14
364,193,504
0
0
null
null
null
null
UTF-8
C++
false
false
2,782
cpp
#include "GenericSelectDialog.h" #include "h/SelectDialog.h" #include <QtGui/QListWidget> GenericSelectDialog::GenericSelectDialog(QWidget *parent, Qt::WindowFlags f): QDialog(parent,f) { ui = new Ui::SelectDialog(); ui->setupUi(this); //this->setAttribute(Qt::WA_DeleteOnClose); } void GenericSelectDialog::accept() { QList<QListWidgetItem*> selection = ui->listWidget->selectedItems(); if(selection.empty()) return; QListWidgetItem* item = selection.first(); acceptSelection(item); //close(); QDialog::accept(); } //void GenericSelectDialog::setupUi() //{ // dialog = new QDialog();//this; // if (dialog->objectName().isEmpty()) // dialog->setObjectName(QString::fromUtf8("Dialog")); // dialog->resize(303, 314); // verticalLayout = new QVBoxLayout(dialog); // verticalLayout->setObjectName(QString::fromUtf8("verticalLayout")); // listWidget = new QListWidget(dialog); // listWidget->setObjectName(QString::fromUtf8("listWidget")); // //listWidget->set // verticalLayout->addWidget(listWidget); // horizontalLayout = new QHBoxLayout(); // horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout")); // horizontalSpacer = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum); // horizontalLayout->addItem(horizontalSpacer); // cancelButton = new QPushButton(dialog); // cancelButton->setObjectName(QString::fromUtf8("cancelButton")); // horizontalLayout->addWidget(cancelButton); // okayButton = new QPushButton(dialog); // okayButton->setObjectName(QString::fromUtf8("okayButton")); // horizontalLayout->addWidget(okayButton); // verticalLayout->addLayout(horizontalLayout); // retranslateUi(); // QMetaObject::connectSlotsByName(this); // connectSignals(); // fillList(); // this->setWidget(dialog); //} // setupUi //void GenericSelectDialog::retranslateUi() //{ // this->setWindowTitle(QApplication::translate("Dialog", "Dialog", 0, QApplication::UnicodeUTF8)); // cancelButton->setText(QApplication::translate("Dialog", "Cancel", 0, QApplication::UnicodeUTF8)); // okayButton->setText(QApplication::translate("Dialog", "OK", 0, QApplication::UnicodeUTF8)); // Q_UNUSED(this); //} // retranslateUi void GenericSelectDialog::connectSignals() { /*connect(cancelButton, SIGNAL(clicked()), this, SLOT(hide())); connect(okayButton, SIGNAL(clicked()), this, SLOT(okButtonClick()));*/ connect(ui->listWidget,SIGNAL(itemDoubleClicked(QListWidgetItem*)),this,SLOT(acceptSelection(QListWidgetItem*))); } /*void GenericSelectDialog::okButtonClick() { QList<QListWidgetItem*> selection = listWidget->selectedItems(); QListWidgetItem* item = selection.first(); acceptSelection(item); }*/
[ "praecipitator@bd7a9385-7eed-4fd6-88b1-0096df50a1ac" ]
[ [ [ 1, 87 ] ] ]
022c70ca635d360027624d9517f789f9ec74e0bc
028d79ad6dd6bb4114891b8f4840ef9f0e9d4a32
/src/vidhrdw/balsente.cpp
4b7767dab9a42cba30d4f81194aab8ed8b285d1e
[]
no_license
neonichu/iMame4All-for-iPad
72f56710d2ed7458594838a5152e50c72c2fb67f
4eb3d4ed2e5ccb5c606fcbcefcb7c5a662ace611
refs/heads/master
2020-04-21T07:26:37.595653
2011-11-26T12:21:56
2011-11-26T12:21:56
2,855,022
4
0
null
null
null
null
UTF-8
C++
false
false
11,042
cpp
/*************************************************************************** vidhrdw/balsente.c Functions to emulate the video hardware of the machine. ****************************************************************************/ #include "driver.h" #include "vidhrdw/generic.h" #ifndef INCLUDE_DRAW_CORE /************************************* * * External globals * *************************************/ extern UINT8 balsente_shooter; extern UINT8 balsente_shooter_x; extern UINT8 balsente_shooter_y; /************************************* * * Statics * *************************************/ static UINT8 *local_videoram; static UINT8 *scanline_dirty; static UINT8 *scanline_palette; static UINT8 last_scanline_palette; static UINT8 screen_refresh_counter; static UINT8 palettebank_vis; /************************************* * * Prototypes * *************************************/ void balsente_vh_stop(void); static void update_screen_8(struct osd_bitmap *bitmap, int full_refresh); static void update_screen_16(struct osd_bitmap *bitmap, int full_refresh); /************************************* * * Video system start * *************************************/ int balsente_vh_start(void) { /* reset the system */ palettebank_vis = 0; /* allocate a local copy of video RAM */ local_videoram = (UINT8*)malloc(256 * 256); if (!local_videoram) { balsente_vh_stop(); return 1; } /* allocate a scanline dirty array */ scanline_dirty = (UINT8*)malloc(256); if (!scanline_dirty) { balsente_vh_stop(); return 1; } /* allocate a scanline palette array */ scanline_palette = (UINT8*)malloc(256); if (!scanline_palette) { balsente_vh_stop(); return 1; } /* mark everything dirty to start */ memset(scanline_dirty, 1, 256); /* reset the scanline palette */ memset(scanline_palette, 0, 256); last_scanline_palette = 0; return 0; } /************************************* * * Video system shutdown * *************************************/ void balsente_vh_stop(void) { /* free the local video RAM array */ if (local_videoram) free(local_videoram); local_videoram = NULL; /* free the scanline dirty array */ if (scanline_dirty) free(scanline_dirty); scanline_dirty = NULL; /* free the scanline dirty array */ if (scanline_palette) free(scanline_palette); scanline_palette = NULL; } /************************************* * * Video RAM write * *************************************/ WRITE_HANDLER( balsente_videoram_w ) { videoram[offset] = data; /* expand the two pixel values into two bytes */ local_videoram[offset * 2 + 0] = data >> 4; local_videoram[offset * 2 + 1] = data & 15; /* mark the scanline dirty */ scanline_dirty[offset / 128] = 1; } /************************************* * * Palette banking * *************************************/ static void update_palette(void) { int scanline = cpu_getscanline(), i; if (scanline > 255) scanline = 0; /* special case: the scanline is the same as last time, but a screen refresh has occurred */ if (scanline == last_scanline_palette && screen_refresh_counter) { for (i = 0; i < 256; i++) { /* mark the scanline dirty if it was a different palette */ if (scanline_palette[i] != palettebank_vis) scanline_dirty[i] = 1; scanline_palette[i] = palettebank_vis; } } /* fill in the scanlines up till now */ else { for (i = last_scanline_palette; i != scanline; i = (i + 1) & 255) { /* mark the scanline dirty if it was a different palette */ if (scanline_palette[i] != palettebank_vis) scanline_dirty[i] = 1; scanline_palette[i] = palettebank_vis; } /* remember where we left off */ last_scanline_palette = scanline; } /* reset the screen refresh counter */ screen_refresh_counter = 0; } WRITE_HANDLER( balsente_palette_select_w ) { /* only update if changed */ if (palettebank_vis != (data & 3)) { /* update the scanline palette */ update_palette(); palettebank_vis = data & 3; } //logerror("balsente_palette_select_w(%d) scanline=%d\n", data & 3, cpu_getscanline()); } /************************************* * * Palette RAM write * *************************************/ WRITE_HANDLER( balsente_paletteram_w ) { int r, g, b; paletteram[offset] = data & 0x0f; r = paletteram[(offset & ~3) + 0]; g = paletteram[(offset & ~3) + 1]; b = paletteram[(offset & ~3) + 2]; palette_change_color(offset / 4, (r << 4) | r, (g << 4) | g, (b << 4) | b); } /************************************* * * Main screen refresh * *************************************/ void balsente_vh_screenrefresh(struct osd_bitmap *bitmap, int full_refresh) { UINT8 palette_used[4]; int x, y, i; /* update the remaining scanlines */ screen_refresh_counter++; update_palette(); /* determine which palette banks were used */ palette_used[0] = palette_used[1] = palette_used[2] = palette_used[3] = 0; for (i = 0; i < 240; i++) palette_used[scanline_palette[i]] = 1; /* make sure color 1024 is white for our crosshair */ palette_change_color(1024, 0xff, 0xff, 0xff); /* set the used status of all the palette entries */ for (x = 0; x < 4; x++) if (palette_used[x]) memset(&palette_used_colors[x * 256], PALETTE_COLOR_USED, 256); else memset(&palette_used_colors[x * 256], PALETTE_COLOR_UNUSED, 256); palette_used_colors[1024] = balsente_shooter ? PALETTE_COLOR_USED : PALETTE_COLOR_UNUSED; /* recompute the palette, and mark all scanlines dirty if we need to redraw */ if (palette_recalc()) memset(scanline_dirty, 1, 256); /* do the core redraw */ if (bitmap->depth == 8) update_screen_8(bitmap, full_refresh); else update_screen_16(bitmap, full_refresh); /* draw a crosshair */ if (balsente_shooter) { int beamx = balsente_shooter_x; int beamy = balsente_shooter_y - 12; int xoffs = beamx - 3; int yoffs = beamy - 3; for (y = -3; y <= 3; y++, yoffs++, xoffs++) { if (yoffs >= 0 && yoffs < 240 && beamx >= 0 && beamx < 256) { plot_pixel(bitmap, beamx, yoffs, Machine->pens[1024]); scanline_dirty[yoffs] = 1; } if (xoffs >= 0 && xoffs < 256 && beamy >= 0 && beamy < 240) plot_pixel(bitmap, xoffs, beamy, Machine->pens[1024]); } } } /************************************* * * Depth-specific refresh * *************************************/ #define ADJUST_FOR_ORIENTATION(orientation, bitmap, dst, x, y, xadv) \ if (orientation) \ { \ int dy = bitmap->line[1] - bitmap->line[0]; \ int tx = x, ty = y, temp; \ if (orientation & ORIENTATION_SWAP_XY) \ { \ temp = tx; tx = ty; ty = temp; \ xadv = dy / (bitmap->depth / 8); \ } \ if (orientation & ORIENTATION_FLIP_X) \ { \ tx = bitmap->width - 1 - tx; \ if (!(orientation & ORIENTATION_SWAP_XY)) xadv = -xadv; \ } \ if (orientation & ORIENTATION_FLIP_Y) \ { \ ty = bitmap->height - 1 - ty; \ if ((orientation & ORIENTATION_SWAP_XY)) xadv = -xadv; \ } \ /* can't lookup line because it may be negative! */ \ dst = (TYPE *)(bitmap->line[0] + dy * ty) + tx; \ } #define INCLUDE_DRAW_CORE #define DRAW_FUNC update_screen_8 #define TYPE UINT8 #include "balsente.cpp" #undef TYPE #undef DRAW_FUNC #define DRAW_FUNC update_screen_16 #define TYPE UINT16 #include "balsente.cpp" #undef TYPE #undef DRAW_FUNC #else /************************************* * * Core refresh routine * *************************************/ void DRAW_FUNC(struct osd_bitmap *bitmap, int full_refresh) { int orientation = Machine->orientation; int x, y, i; /* draw any dirty scanlines from the VRAM directly */ for (y = 0; y < 240; y++) { UINT16 *pens = &Machine->pens[scanline_palette[y] * 256]; if (scanline_dirty[y] || full_refresh) { UINT8 *src = &local_videoram[y * 256]; TYPE *dst = (TYPE *)bitmap->line[y]; int xadv = 1; /* adjust in case we're oddly oriented */ ADJUST_FOR_ORIENTATION(orientation, bitmap, dst, 0, y, xadv); /* redraw the scanline */ for (x = 0; x < 256; x++, dst += xadv) *dst = pens[*src++]; scanline_dirty[y] = 0; } } /* draw the sprite images */ for (i = 0; i < 40; i++) { UINT8 *sprite = spriteram + ((0xe0 + i * 4) & 0xff); UINT8 *src; int flags = sprite[0]; int image = sprite[1] | ((flags & 3) << 8); int ypos = sprite[2] + 17; int xpos = sprite[3]; /* get a pointer to the source image */ src = &memory_region(REGION_GFX1)[64 * image]; if (flags & 0x80) src += 4 * 15; /* loop over y */ for (y = 0; y < 16; y++, ypos = (ypos + 1) & 255) { if (ypos >= 16 && ypos < 240) { UINT16 *pens = &Machine->pens[scanline_palette[y] * 256]; UINT8 *old = &local_videoram[ypos * 256 + xpos]; TYPE *dst = &((TYPE *)bitmap->line[ypos])[xpos]; int currx = xpos, xadv = 1; /* adjust in case we're oddly oriented */ ADJUST_FOR_ORIENTATION(orientation, bitmap, dst, xpos, ypos, xadv); /* mark this scanline dirty */ scanline_dirty[ypos] = 1; /* standard case */ if (!(flags & 0x40)) { /* loop over x */ for (x = 0; x < 4; x++, dst += xadv * 2, old += 2) { int ipixel = *src++; int left = ipixel & 0xf0; int right = (ipixel << 4) & 0xf0; int pen; /* left pixel */ if (left && currx >= 0 && currx < 256) { /* combine with the background */ pen = left | old[0]; dst[0] = pens[pen]; } currx++; /* right pixel */ if (right && currx >= 0 && currx < 256) { /* combine with the background */ pen = right | old[1]; dst[xadv] = pens[pen]; } currx++; } } /* hflip case */ else { src += 4; /* loop over x */ for (x = 0; x < 4; x++, dst += xadv * 2, old += 2) { int ipixel = *--src; int left = (ipixel << 4) & 0xf0; int right = ipixel & 0xf0; int pen; /* left pixel */ if (left && currx >= 0 && currx < 256) { /* combine with the background */ pen = left | old[0]; dst[0] = pens[pen]; } currx++; /* right pixel */ if (right && currx >= 0 && currx < 256) { /* combine with the background */ pen = right | old[1]; dst[xadv] = pens[pen]; } currx++; } src += 4; } } else src += 4; if (flags & 0x80) src -= 2 * 4; } } } #endif
[ [ [ 1, 470 ] ] ]
04451cc1412e146062a82703874fe410092c0ee4
4b116281b895732989336f45dc65e95deb69917b
/Code Base/GSP410-Project2/Unit.h
3151ae612e2e4f76261797db2b50e72f7da1b9d1
[]
no_license
Pavani565/gsp410-spaceshooter
1f192ca16b41e8afdcc25645f950508a6f9a92c6
c299b03d285e676874f72aa062d76b186918b146
refs/heads/master
2021-01-10T00:59:18.499288
2011-12-12T16:59:51
2011-12-12T16:59:51
33,170,205
0
0
null
null
null
null
UTF-8
C++
false
false
1,353
h
#pragma once #include <d3dx9.h> #include "Structures.h" #include "Renderable.h" class CUnit : public virtual CRenderable { protected: // General Unit Variables // RECT m_Rect; D3DXVECTOR3 m_Coordinates; D3DXVECTOR3 m_Center; D3DCOLOR m_Color; float m_Scale; float m_Angle; RowCol m_MySector; //IDirect3DTexture9* m_UnitTexture; int m_TextureType; D3DXIMAGE_INFO m_TextureInfo; public: // General Unit Set Functions // void setX(float newX); void setY(float newY); void setSector(int row, int col); void setSector(RowCol); void setScale(float scale); void setAngle(float angle); //void setTexturePointer(IDirect3DTexture9* TextureAddress); void setTextureType(int TextureType); void setTextureInfo(D3DXIMAGE_INFO TextureInformation); void resetRect(void); // General Unit Get Functions // float getX(void); float getY(void); int getRow(void); int getCol(void); RowCol getSector(void); //IDirect3DTexture9* getTexturePointer(void); D3DXIMAGE_INFO getTextureInfo(void); // Derived Virtual Functions Defined // int GetTextureType(void); RECT GetRect(void); D3DXVECTOR3 GetCenter(void); D3DCOLOR GetColor(void); float GetScale(void); float GetRotation(void); D3DXVECTOR3 GetPosition(void); // Constructor & Destructor // CUnit(void); ~CUnit(void); };
[ "[email protected]@7eab73fc-b600-5548-9ef9-911d97763ba7" ]
[ [ [ 1, 56 ] ] ]
203ac51a0bcb5c526e37b27038664d1ee5936207
2acd91cf2dfe87f4c78fba230de2c2ffc90350ea
/ salad-bar-in-space-game/edge/bouncibility/include/Level.h
3fe0714251742bfbd0941c0c317091bf6e58e8bd
[]
no_license
Joshvanburen/salad-bar-in-space-game
5f410a06be475edee1ab85950c667e6a6f970763
b23a35c832258f4fc1a921a45ab4238c734ef1f0
refs/heads/master
2016-09-01T18:46:29.672326
2008-05-07T18:40:30
2008-05-07T18:40:30
32,195,299
0
0
null
null
null
null
UTF-8
C++
false
false
3,645
h
#pragma once #include "Common.h" #include "irrlicht.h" namespace irr{ namespace newton{ class IMaterial; class IBody; } } namespace Sound{ class Audio; } typedef std::list<WorldEntity*> EntityVector; //!The Level class holds everything within a specific level. It loads in all the world entities and updates them. Each level has its own xml file. class Level { //Private methods and variables private: //!Vector to hold all world entities EntityVector m_WorldEntities; EntityVector m_EntitiesToAdd; EntityVector m_EntitiesToRemove; //!Iterator for the world entities EntityVector::iterator m_WorldEntityItr; //!Level name std::string m_LevelName; //!Filename of xml definition for this level. std::string m_XmlFile; //!Level file name std::string m_LevelFile; //!name of music file std::string m_MusicName; int m_MusicIndex; //!Handle to the sound object for music. std::vector<Sound::Audio*> m_MusicList; Sound::Audio* m_Music; //!Level timer; int m_Time; //!Current status of level int m_Status; irr::scene::ICameraSceneNode* m_Camera; irr::core::dimension2di m_LevelDimensions; int m_MinX, m_MinY, m_MaxX, m_MaxY; int m_StartingX; int m_StartingY; irr::scene::IMeshSceneNode* m_SceneNode; irr::scene::IMesh* m_Mesh; irr::newton::IBody* m_Physics_Body; irr::newton::IMaterial* m_Material; friend std::ostream& operator << (std::ostream& os, const Level& level); //Public methods and variables public: static const int WAITING_REPEAT; static const int RUNNING; static const int WAITING_START; static const int FINISHED; static const int STOPPED; explicit Level(); ~Level(); //! Load the level from the given xml definition. Loads in all entities from the EntityManager and stores them in the entityvector. /*! Level xml definition format <Level attributes, name, music, time, startingx, starting y, mapfilename> <WorldEntities> <Entity name, xlocation, ylocation, startState/> ... </WorldEntities> </Level> */ bool load(const std::string& LevelDefinition); irr::scene::ICameraSceneNode* getCamera(){ return m_Camera; } void removeEntity(WorldEntity* entity); void addEntity(WorldEntity* entity); //!Releases all resources used. Does not need to delete the entities it has, EntityManager does this. void shutdown(); //!Updates the level and all children void update(); //!Gets the level name const std::string& getName(); //!Gets the music file name const std::string& getMusicName(); //!Gets the current level time int getCurrentTime(); //!Sets the current level time void setCurrentTime(int ctime); //!return the status of the current level. Used to determine whether to go to now or display restart menu, etc. int status(); //!Allows someone else to set the status of this level to FINISHED, WAITING_REPEAT, or any other possible statuses. This would be accessed by the UserInterface or possibly a finished marker worldentity. void setStatus(int newStatus); //!Returns the dimensions specified in the XML as the bounds of the level. Might be used by camera and input system. irr::core::dimension2di getDimensions(){ return m_LevelDimensions; } float getMinX(){ return (float)m_MinX; } float getMinY(){ return (float)m_MinY; } float getMaxX(){ return (float)m_MaxX; } float getMaxY(){ return (float)m_MaxY; } };
[ "[email protected]@1a2710a4-8244-0410-8b66-391840787a9e", "pipilu.qin@1a2710a4-8244-0410-8b66-391840787a9e" ]
[ [ [ 1, 22 ], [ 24, 87 ], [ 90, 123 ] ], [ [ 23, 23 ], [ 88, 89 ] ] ]
15388824cacd708f14e2f0d0661a3e124f127ab7
d609fb08e21c8583e5ad1453df04a70573fdd531
/trunk/DiskMonitor/DiskMonitor.cpp
004c6344458e4d15df9c350dbf3b3cbd8230acc9
[]
no_license
svn2github/openxp
d68b991301eaddb7582b8a5efd30bc40e87f2ac3
56db08136bcf6be6c4f199f4ac2a0850cd9c7327
refs/heads/master
2021-01-19T10:29:42.455818
2011-09-17T10:27:15
2011-09-17T10:27:15
21,675,919
0
1
null
null
null
null
GB18030
C++
false
false
1,107
cpp
#include "stdafx.h" #include "DiskMonitor.h" #include "DiskMonitorDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif BEGIN_MESSAGE_MAP(CDiskMonitorApp, CWinApp) ON_COMMAND(ID_HELP, &CWinApp::OnHelp) END_MESSAGE_MAP() CDiskMonitorApp::CDiskMonitorApp() { } CDiskMonitorApp theApp; BOOL CDiskMonitorApp::InitInstance() { INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinApp::InitInstance(); AfxEnableControlContainer(); skinppLoadSkin("spring.ssk");//给界面换皮肤 SetRegistryKey(_T("系统目录变化监视")); #ifndef _DEBUG HANDLE m_hMutex = CreateMutex(NULL,TRUE, m_pszAppName); if(GetLastError() == ERROR_ALREADY_EXISTS) { MessageBox(NULL,_T("监视程序已启动,暂不能同时开启多个!"),_T("系统提示"),MB_OK); return FALSE; } #endif CDiskMonitorDlg dlg; m_pMainWnd = &dlg; dlg.DoModal(); return FALSE; } int CDiskMonitorApp::ExitInstance() { skinppExitSkin(); return CWinApp::ExitInstance(); }
[ "[email protected]@f92b348d-55a1-4afa-8193-148a6675784b" ]
[ [ [ 1, 53 ] ] ]
13bcf93ceea3b8ece655b2b2212b9a49e71b7fbb
4fdc157f7d6c5af784c3492909d848a0371e5877
/autre/SFML1/display.h
20fa40c0ef8b06f8a809b5c9a55ad513d7ed377b
[]
no_license
moumen19/robotiquecartemere
d969e50aedc53844bb7c512ff15e6812b8b469de
8333bb0b5c1b1396e1e99a870af2f60c9db149b0
refs/heads/master
2020-12-24T17:17:14.273869
2011-02-11T15:44:38
2011-02-11T15:44:38
34,446,411
0
0
null
null
null
null
UTF-8
C++
false
false
953
h
#ifndef DISPLAY_H #define DISPLAY_H #include <SFML/Graphics.hpp> #include <SFML/Window.hpp> #include <SFML/System.hpp> #define windowSizeW 800 #define windowSizeH 600 #define Id_BAU 0x90 #define Id_US_min 0x30 #define Id_US_max 0x4F #define Id_IR_min 0x50 #define Id_IR_max 0x6F #define Id_Vide_min 0x70 #define Id_Vide_max 0x8F class display { public: display(); ~display(); void Close(); void setSensorDistance(int idSensor, float dist); void changeDistanceBAU(int dist); // pour le BAU, toute valeur différente de 0 est considérée comme positive ! (sécurité) void changeDistanceUS(int id, float dist); void changeDistanceIR(int id, float dist); void changeDistanceVide(int id, float dist); private: void initializeDistanceValues(); std::map<int, float> _currentDistance; sf::RenderWindow * _window; }; #endif // DISPLAY_H
[ "julien.delbergue@308fe9b9-b635-520e-12eb-2ef3f824b1b6" ]
[ [ [ 1, 43 ] ] ]
74f9391f508f5b9677757b9aaf9f7aedf72ecabd
71ffdff29137de6bda23f02c9e22a45fe94e7910
/KillaCoptuz3000/src/Objects/CWeapon.h
bd32b0db508e610e15f6b594f6af3c3a6c2fd29a
[]
no_license
anhoppe/killakoptuz3000
f2b6ecca308c1d6ebee9f43a1632a2051f321272
fbf2e77d16c11abdadf45a88e1c747fa86517c59
refs/heads/master
2021-01-02T22:19:10.695739
2009-03-15T21:22:31
2009-03-15T21:22:31
35,839,301
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,880
h
// *************************************************************** // CWeapon version: 1.0 · date: 05/05/2007 // ------------------------------------------------------------- // // ------------------------------------------------------------- // Copyright (C) 2007 - All Rights Reserved // *************************************************************** // // *************************************************************** #ifndef CWEAPON_H #define CWEAPON_H #include "KillaCoptuz3000/src/Objects/CSprite.h" #include "tinyxml/tinyxml.h" #include <list> class CShot; class CLevel; class CWeapon : public CSprite { public: CWeapon(); ~CWeapon(); virtual VeObjectType getType() { return e_weapon; }; virtual bool load(TiXmlNode* t_nodePtr); virtual void update(CLevel* t_levelPtr); /** Fire one standard shot */ void fire(); // Controls m_angle for being in the allowed interval void controlAngle(); /** Get tracking angle to tracked object*/ float trackAngle(float t_trgX, float t_trgY); float m_minAngle; float m_maxAngle; unsigned int m_maxShots; unsigned int m_framesPerShot; unsigned int m_framesSinceShot; float m_shotRadius; CShot* m_shotPtr; #if(PRODUCT == LE3000) // in the level editor the weapon holds the information about the shots float m_shotX; float m_shotY; float m_shotWidth; float m_shotHeight; int m_shotCycleInterval; float m_shotVelocity; int m_shotHitPoints; #endif /** Auto tracking of weapon on / off*/ bool m_isTracking; FSOUND_SAMPLE* m_soundPtr; }; #endif
[ "anhoppe@9386d06f-8230-0410-af72-8d16ca8b68df", "fabianheinemann@9386d06f-8230-0410-af72-8d16ca8b68df" ]
[ [ [ 1, 63 ], [ 67, 71 ] ], [ [ 64, 66 ] ] ]
c981ac5a35f1c5014bd2154e78dd170e5162fc3e
37c11de5fa036e89b5cd742f1ea688290038e322
/Location.h
575050747b66416d1edac2b05c03ad27c466be3a
[ "Apache-2.0" ]
permissive
patches11/aichallenge_ant
3c7eef9603782ae45ecfcdf92573c8b0d974c03d
6909b38cc2e9287990ef6ec279b1cccce375af91
refs/heads/master
2020-04-01T18:43:50.469456
2011-11-11T19:17:10
2011-11-11T19:17:10
29,498,473
0
0
null
null
null
null
UTF-8
C++
false
false
809
h
#ifndef LOCATION_H_ #define LOCATION_H_ #include <iostream> #include <stdio.h> /* struct for representing locations in the grid. */ struct Location { int row, col; Location() { row = col = 0; }; Location(int r, int c) { row = r; col = c; }; friend bool operator< (Location first, Location second) { if (first.row < second.row) return true; if (first.row > second.row) return false; if (first.col < second.col) return true; return false; } friend bool operator== (Location first, Location second) { if (first.row == second.row && first.col == second.col) return true; return false; } }; std::ostream& operator<<(std::ostream &os, const Location &loc); #endif //LOCATION_H_
[ [ [ 1, 48 ] ] ]
99748b99d960d55c78ca4d4ef02cb72f92de80da
5dc78c30093221b4d2ce0e522d96b0f676f0c59a
/src/modules/audio/openal/Source.h
e609ae2a85c0a6e3347388852bd644be4e46fc1b
[ "Zlib" ]
permissive
JackDanger/love
f03219b6cca452530bf590ca22825170c2b2eae1
596c98c88bde046f01d6898fda8b46013804aad6
refs/heads/master
2021-01-13T02:32:12.708770
2009-07-22T17:21:13
2009-07-22T17:21:13
142,595
1
0
null
null
null
null
UTF-8
C++
false
false
1,797
h
/** * Copyright (c) 2006-2009 LOVE Development Team * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. **/ #ifndef LOVE_AUDIO_OPENAL_SOURCE_H #define LOVE_AUDIO_OPENAL_SOURCE_H // LOVE #include <common/Object.h> #include <audio/Source.h> #include "Pool.h" // OpenAL #include <AL/alc.h> #include <AL/al.h> namespace love { namespace audio { namespace openal { class Audio; class Source : public love::audio::Source { private: Pool * pool; ALuint source; float pitch; float volume; public: Source(Pool * pool); Source(Pool * pool, Audible * audible); virtual ~Source(); void play(); void stop(); void pause(); void resume(); void rewind(); bool isFinished() const; void update(); void setPitch(float pitch); float getPitch() const; void setVolume(float volume); float getVolume() const; }; // Source } // openal } // audio } // love #endif // LOVE_AUDIO_OPENAL_SOURCE_H
[ "prerude@3494dbca-881a-0410-bd34-8ecbaf855390" ]
[ [ [ 1, 76 ] ] ]
0057e8982beec903a51c0703d27777b27d2748de
5fb9b06a4bf002fc851502717a020362b7d9d042
/developertools/GumpEditor-0.32/diagram/DiagramEditor/Tokenizer.h
36166b9ee77cd734758e817886f05835afbb57de
[]
no_license
bravesoftdz/iris-svn
8f30b28773cf55ecf8951b982370854536d78870
c03438fcf59d9c788f6cb66b6cb9cf7235fbcbd4
refs/heads/master
2021-12-05T18:32:54.525624
2006-08-21T13:10:54
2006-08-21T13:10:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,252
h
/* ========================================================================== CTokeniz Author : Johan Rosengren, Abstrakt Mekanik AB Date : 2004-03-31 Purpose : CTokenizer is a very simple class to tokenize a string into a string array. Description : The string is chopped up and put into an internal CStringArray. With GetAt, different types of data can be read from the different elements. Usage : ========================================================================*/ #ifndef _TOKENIZER_H_ #define _TOKENIZER_H_ #include <tchar.h> //////////////////////////////////////////////////////////////////////////// // CTokenizer is a class to tokenize a string // class CTokenizer { public: CTokenizer(CString strInput, const CString& strDelimiter = _T( "," ) ) { Init(strInput, strDelimiter); } void Init(const CString& strInput, const CString& strDelimiter = _T( "," ) ) { CString copy( strInput ); m_stra.RemoveAll(); int nFound = copy.Find( strDelimiter ); while(nFound != -1) { CString strLeft; strLeft = copy.Left( nFound ); copy = copy.Right( copy.GetLength() - ( nFound + 1 ) ); m_stra.Add( strLeft ); nFound = copy.Find( strDelimiter ); } m_stra.Add( copy ); } int GetSize() const { return m_stra.GetSize(); } void GetAt( int nIndex, CString& str ) const { if( nIndex < m_stra.GetSize() ) str = m_stra.GetAt( nIndex ); else str = _T( "" ); } void GetAt( int nIndex, int& var ) const { if( nIndex < m_stra.GetSize() ) var = _ttoi( m_stra.GetAt( nIndex ) ); else var = 0; } void GetAt( int nIndex, WORD& var ) const { if( nIndex < m_stra.GetSize() ) var = ( WORD ) _ttoi( m_stra.GetAt( nIndex ) ); else var = 0; } void GetAt( int nIndex, double& var ) const { char *stop; if( nIndex < m_stra.GetSize() ) var = _tcstod( m_stra.GetAt( nIndex ), &stop ); else var = 0.0; } void GetAt( int nIndex, DWORD& var ) const { if( nIndex < m_stra.GetSize() ) var = ( DWORD ) _ttoi( m_stra.GetAt( nIndex ) ); else var = 0; } private: CStringArray m_stra; }; #endif // _TOKENIZER_H_
[ "sience@a725d9c3-d2eb-0310-b856-fa980ef11a19" ]
[ [ [ 1, 106 ] ] ]
c9dee69b512d0f2b85dcfd669408a4952f52609e
5c5e77abfc71e6459f89fcbd710a8f258f4a03cf
/声音采集/playsound/Mixer.cpp
e652b0e9e7e1ce8b003ffe0509a3aae86b39b420
[]
no_license
goo2git/smalltools
cf65f2210f060e893d27acace2b8b001a2d7cf23
5976b7013bf920f452dfc4a59e5f7b9c2952b9e0
refs/heads/master
2021-01-22T06:37:10.658791
2011-04-06T07:07:21
2011-04-06T07:07:21
35,361,712
0
0
null
null
null
null
GB18030
C++
false
false
13,661
cpp
// Mixer.cpp: implementation of the CMixer class. // //#include "stdwx.h" #include "Mixer.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CMixer::CMixer() { m_VolRange = 100; } CMixer::~CMixer() { } CMixer::CMixer(const int VolRange) { m_VolRange = VolRange; } //----------------------------设定音量--------------------------------------- bool CMixer::GetVolumeControl( HMIXER hmixer ,long componentType,long ctrlType,MIXERCONTROL* mxc ) { MIXERLINECONTROLS mxlc; MIXERLINE mxl; bool exist = false; mxl.cbStruct = sizeof(mxl); mxl.dwComponentType = componentType; if (componentType == MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE) {//获取录音麦克风设备 mxl.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_WAVEIN; //得到录制总线中的连接数 mixerGetLineInfo((HMIXEROBJ)hmixer, &mxl, MIXER_OBJECTF_HMIXER | MIXER_GETLINEINFOF_COMPONENTTYPE); //将连接数保存 DWORD dwConnections = mxl.cConnections; // 准备获取麦克风设备的ID DWORD dwLineID = 0; for(DWORD i = 0; i < dwConnections; ++i) { //枚举每一个设备,当Source的ID等于当前的迭代记数 mxl.dwSource = i; //根据SourceID获得连接的信息 MMRESULT mr = mixerGetLineInfo((HMIXEROBJ)hmixer, &mxl, MIXER_OBJECTF_HMIXER | MIXER_GETLINEINFOF_SOURCE); //判断函数执行错误 if(mr != 0) { break; } //如果当前设备类型是麦克风,则跳出循环。 if(mxl.dwComponentType == MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE) { exist = true; break; } } } else if(!mixerGetLineInfo((HMIXEROBJ)hmixer, &mxl, MIXER_GETLINEINFOF_COMPONENTTYPE)) { exist = true; } if (exist) { mxlc.cbStruct = sizeof(mxlc); mxlc.dwLineID = mxl.dwLineID; mxlc.dwControlType = ctrlType; mxlc.cControls = 1; mxlc.cbmxctrl = sizeof(MIXERCONTROL); mxlc.pamxctrl = mxc; if(mixerGetLineControls((HMIXEROBJ)hmixer,&mxlc,MIXER_GETLINECONTROLSF_ONEBYTYPE)) return 0; else return 1; } return 0; } //--------------------------------------------------------------------------- long CMixer::GetMuteValue(HMIXER hmixer ,MIXERCONTROL *mxc) { MIXERCONTROLDETAILS mxcd; MIXERCONTROLDETAILS_BOOLEAN mxcdMute; mxcd.hwndOwner = 0; mxcd.cbStruct = sizeof(mxcd); mxcd.dwControlID = mxc->dwControlID; mxcd.cbDetails = sizeof(mxcdMute); mxcd.paDetails = &mxcdMute; mxcd.cChannels = 1; mxcd.cMultipleItems = 0; if (mixerGetControlDetails((HMIXEROBJ)hmixer, &mxcd,MIXER_OBJECTF_HMIXER|MIXER_GETCONTROLDETAILSF_VALUE)) { return -1; } return mxcdMute.fValue; } //--------------------------------------------------------------------------- unsigned CMixer::GetVolumeValue(HMIXER hmixer ,MIXERCONTROL *mxc) { MIXERCONTROLDETAILS mxcd; MIXERCONTROLDETAILS_UNSIGNED vol; vol.dwValue=0; mxcd.hwndOwner = 0; mxcd.cbStruct = sizeof(mxcd); mxcd.dwControlID = mxc->dwControlID; mxcd.cbDetails = sizeof(vol); mxcd.paDetails = &vol; mxcd.cChannels = 1; if(mixerGetControlDetails((HMIXEROBJ)hmixer, &mxcd, MIXER_OBJECTF_HMIXER|MIXER_GETCONTROLDETAILSF_VALUE)) { return -1; } return vol.dwValue; } //--------------------------------------------------------------------------- bool CMixer::SetMuteValue(HMIXER hmixer ,MIXERCONTROL *mxc, bool mute) { MIXERCONTROLDETAILS mxcd; MIXERCONTROLDETAILS_BOOLEAN mxcdMute; mxcdMute.fValue=mute; mxcd.hwndOwner = 0; mxcd.dwControlID = mxc->dwControlID; mxcd.cbStruct = sizeof(mxcd); mxcd.cbDetails = sizeof(mxcdMute); mxcd.paDetails = &mxcdMute; mxcd.cChannels = 1; mxcd.cMultipleItems = 0; if (mixerSetControlDetails((HMIXEROBJ)hmixer, &mxcd, MIXER_OBJECTF_HMIXER|MIXER_SETCONTROLDETAILSF_VALUE)) { return 0; } return 1; } //--------------------------------------------------------------------------- bool CMixer::SetVolumeValue(HMIXER hmixer ,MIXERCONTROL *mxc, long volume) { MIXERCONTROLDETAILS mxcd; MIXERCONTROLDETAILS_UNSIGNED vol; vol.dwValue = volume; mxcd.hwndOwner = 0; mxcd.dwControlID = mxc->dwControlID; mxcd.cbStruct = sizeof(mxcd); mxcd.cbDetails = sizeof(vol); mxcd.paDetails = &vol; mxcd.cChannels = 1; if(mixerSetControlDetails((HMIXEROBJ)hmixer, &mxcd, MIXER_OBJECTF_HMIXER|MIXER_SETCONTROLDETAILSF_VALUE)) { return 0; } return 1; } //--------------------------------------------------------------------------- unsigned /*WINAPI */CMixer::GetVolume(MixerDeice dev)//得到设备的音量dev=0主音量,1WAVE ,2MIDI ,3 LINE IN { long device; unsigned rt=0; MIXERCONTROL volCtrl; HMIXER hmixer; switch (dev) { case WAVEOUT: device=MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT; break; case SYNTHESIZER: device=MIXERLINE_COMPONENTTYPE_SRC_SYNTHESIZER; break; case MICROPHONE: // device=MIXERLINE_COMPONENTTYPE_SRC_COMPACTDISC; break; // cd 音量 device=MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE; break; //麦克风音量 // device=MIXERLINE_COMPONENTTYPE_SRC_LINE; break; //PC 扬声器音量 //device=MIXERLINE_COMPONENTTYPE_SRC_COMPACTDISC; break; default: device=MIXERLINE_COMPONENTTYPE_DST_SPEAKERS; } if(mixerOpen(&hmixer, 0, 0, 0, 0)) return 0; if(!GetVolumeControl(hmixer,device,MIXERCONTROL_CONTROLTYPE_VOLUME,&volCtrl)) { mixerClose(hmixer); return 0; } rt = GetVolumeValue(hmixer,&volCtrl)*m_VolRange /volCtrl.Bounds.lMaximum; mixerClose(hmixer); return rt; } //--------------------------------------------------------------------------- bool /*WINAPI*/ CMixer::SetVolume(MixerDeice dev,long vol)//设置设备的音量 { // dev =0,1,2 分别表示主音量,波形,MIDI ,LINE IN // vol=0-m_VolRange 表示音量的大小 , 设置与返回音量的值用的是百分比,即音量从0 - m_VolRange ,而不是设备的绝对值 // retrun false 表示设置音量的大小的操作不成功 // retrun true 表示设置音量的大小的操作成功 long device; bool rc=false; MIXERCONTROL volCtrl; HMIXER hmixer; switch (dev) { case WAVEOUT: device=MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT; break; case SYNTHESIZER: device=MIXERLINE_COMPONENTTYPE_SRC_SYNTHESIZER; break; case MICROPHONE: // device=MIXERLINE_COMPONENTTYPE_SRC_COMPACTDISC; break; // cd 音量 device=MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE; break; //麦克风音量 // device=MIXERLINE_COMPONENTTYPE_SRC_LINE; break; //PC 扬声器音量 //device=MIXERLINE_COMPONENTTYPE_SRC_COMPACTDISC; break; default: device=MIXERLINE_COMPONENTTYPE_DST_SPEAKERS; } if(mixerOpen(&hmixer, 0, 0, 0, 0)) return 0; if(GetVolumeControl(hmixer,device,MIXERCONTROL_CONTROLTYPE_VOLUME,&volCtrl)) { vol=vol*volCtrl.Bounds.lMaximum/m_VolRange ; if(SetVolumeValue(hmixer,&volCtrl,vol)) { rc=true; } } mixerClose(hmixer); return rc; } //--------------------------------------------------------------------------- bool /*WINAPI*/ CMixer::SetMute(MixerDeice dev,/*long*/bool vol)//设置设备静音 { // dev =0,1,2 分别表示主音量,波形,MIDI ,LINE IN // vol=0,1 分别表示取消静音,设置静音 // retrun false 表示取消或设置静音操作不成功 // retrun true 表示取消或设置静音操作成功 long device; bool rc=false; MIXERCONTROL volCtrl; HMIXER hmixer; switch (dev) { case WAVEOUT: device=MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT; break; case SYNTHESIZER: device=MIXERLINE_COMPONENTTYPE_SRC_SYNTHESIZER; break; case MICROPHONE: // device=MIXERLINE_COMPONENTTYPE_SRC_COMPACTDISC; break; // cd 音量 device=MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE; break; //麦克风音量 // device=MIXERLINE_COMPONENTTYPE_SRC_LINE; break; //PC 扬声器音量 //device=MIXERLINE_COMPONENTTYPE_SRC_COMPACTDISC; break; default: device=MIXERLINE_COMPONENTTYPE_DST_SPEAKERS; } if(mixerOpen(&hmixer, 0, 0, 0, 0)) return 0; if(GetVolumeControl(hmixer,device,MIXERCONTROL_CONTROLTYPE_MUTE,&volCtrl)) { if(SetMuteValue(hmixer,&volCtrl,(bool)vol)) { rc=true; } } mixerClose(hmixer); return rc; } //--------------------------------------------------------------------------- bool /*WINAPI */CMixer::GetMute(MixerDeice dev)//检查设备是否静音 { //dev =0,1,2 分别表示主音量,波形,MIDI ,LINE IN // retrun false 表示没有静音 // retrun true 表示静音 long device; bool rc=false; MIXERCONTROL volCtrl; HMIXER hmixer; switch (dev) { case WAVEOUT: device=MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT; break; case SYNTHESIZER: device=MIXERLINE_COMPONENTTYPE_SRC_SYNTHESIZER; break; case MICROPHONE: // device=MIXERLINE_COMPONENTTYPE_SRC_COMPACTDISC; break; // cd 音量 //device=MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE; break; //麦克风音量 // device=MIXERLINE_COMPONENTTYPE_SRC_LINE; break; //PC 扬声器音量 //device=MIXERLINE_COMPONENTTYPE_SRC_COMPACTDISC; break; device=MIXERLINE_COMPONENTTYPE_DST_WAVEIN; break; default: device=MIXERLINE_COMPONENTTYPE_DST_SPEAKERS; } if(mixerOpen(&hmixer, 0, 0, 0, 0)) return 0; if(GetVolumeControl(hmixer,device,MIXERCONTROL_CONTROLTYPE_MUTE,&volCtrl)) { rc=GetMuteValue(hmixer,&volCtrl); } mixerClose(hmixer); return rc; } //如果第一个参数是true,那么就是设置,否则就是获得 bool CMixer::SetGetDevVolume(bool bIsSet,DWORD & dwVolume) { MMRESULT rc; // 多媒体函数返回结果变量 HMIXER hMixer; // 混合器设备句柄 MIXERLINE mxl; // 音频线路标准状态信息结构体 MIXERLINECONTROLS mxlc; // 音频线路控制器集合信息结构体 MIXERCONTROL mxc; // 单个音频线路控制器信息结构体 // 打开混合器设备 rc = mixerOpen(&hMixer, // 返回的设备句柄 0, // 单声卡的设备ID为零 0, // 不使用回调机制 0, // 回调函数参数 0); // MIXER_OBJECTF_MIXER宏的值,表示任选有效设备ID // 打开混合器设备无错的话,则 if (MMSYSERR_NOERROR == rc) { // MIXERLINE 结构体变量清零 ZeroMemory(&mxl, sizeof(MIXERLINE)); mxl.cbStruct = sizeof(MIXERLINE); // 微软用此办法判断版本 // 指出需要获取的通道,声卡的音频输出用MIXERLINE_COMPONENTTYPE_DST_SPEAKERS mxl.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_SPEAKERS; // 取得混合器设备的指定线路信息 rc = mixerGetLineInfo((HMIXEROBJ)hMixer, &mxl, // 取得MIXERLINE::dwComponentType指定类型的第一个音频线路信息 MIXER_GETLINEINFOF_COMPONENTTYPE); // 取得混合器设备的指定线路信息成功的话,则 if (MMSYSERR_NOERROR == rc) { // MIXERCONTROL 结构体变量清零 ZeroMemory(&mxc, sizeof(MIXERCONTROL)); mxc.cbStruct = sizeof(mxc); // 微软用此办法判断版本 // MIXERLINECONTROLS 结构体变量清零 ZeroMemory(&mxlc, sizeof(MIXERLINECONTROLS)); mxlc.cbStruct = sizeof(mxlc); // 微软用此办法判断版本 mxlc.dwLineID = mxl.dwLineID; // 上面取得的声卡音频输出线路标识 // 控制类型为控制音量 mxlc.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME; mxlc.cControls = 1; // 使用 MIXERCONTROL 结构体变量个数 mxlc.pamxctrl = &mxc; // MIXERCONTROL 结构体变量指针 mxlc.cbmxctrl = sizeof(mxc); // MIXERCONTROL 结构体变量字节大小 // 取得控制器信息 rc = mixerGetLineControls((HMIXEROBJ)hMixer, &mxlc, MIXER_GETLINECONTROLSF_ONEBYTYPE); // 取得控制器信息成功的话,则 if (MMSYSERR_NOERROR == rc) { // 获取控制器中的值的音量范围:mxc.Bounds.lMinimum到mxc.Bounds.lMaximum. MIXERCONTROLDETAILS mxcd; // 控制器的状态信息 MIXERCONTROLDETAILS_SIGNED volStruct; // 音量结构体变量(就一个成员量) // MIXERCONTROLDETAILS 结构体变量清零 ZeroMemory(&mxcd, sizeof(mxcd)); mxcd.cbStruct = sizeof(mxcd); // 微软用此办法判断版本 mxcd.dwControlID = mxc.dwControlID; // 上面取得的控制器标识 mxcd.paDetails = &volStruct; // 音量结构体变量指针 mxcd.cbDetails = sizeof(volStruct); // 音量结构体变量字节大小 mxcd.cChannels = 1; // 取得或设置全部通道 // 设置音量 if (bIsSet) { volStruct.lValue = dwVolume; // 想要设置的值 rc = mixerSetControlDetails((HMIXEROBJ)hMixer, &mxcd, MIXER_SETCONTROLDETAILSF_VALUE); if (MMSYSERR_NOERROR == rc) { return true; } else { return false; } } // 获得音量值 else { rc = mixerGetControlDetails((HMIXEROBJ)hMixer, &mxcd, MIXER_GETCONTROLDETAILSF_VALUE); if (MMSYSERR_NOERROR == rc) { dwVolume=volStruct.lValue; } else { return false; } } } else { return false; } } else { return false; } } else { return false; } return true; }
[ "[email protected]@11e4cd5c-f3ce-5a92-1cba-4cc5eaddca49" ]
[ [ [ 1, 440 ] ] ]
e641006dd5e1a7a9df9f646627b6a6105a28416a
09e322e0db32ccd7c0a8aaa357fb8763c43bf1bf
/PComImpl/thread_ptr.h
c0eb2ac162441634a86cbf25c647cc6e1110f484
[]
no_license
chrisforbes/profiler
165ba38c01fcb10174973430f0ebbbbff84dc6f6
02111db2d065f385bdac7767a340e5c1f4ae974e
refs/heads/master
2020-05-20T01:56:53.481186
2009-10-02T10:30:27
2009-10-02T10:30:27
324,424
5
1
null
null
null
null
UTF-8
C++
false
false
309
h
#pragma once template< typename T > class ThreadPtr { DWORD id; public: ThreadPtr() : id( TlsAlloc() ) { } T * get() const { return (T *)TlsGetValue( id ); } void set( T const * x ) { TlsSetValue( id, (void *) x ); } virtual ~ThreadPtr() { TlsFree( id ); } };
[ "(no author)@993157c7-ee19-0410-b2c4-bb4e9862e678" ]
[ [ [ 1, 26 ] ] ]
33da496e6457afd6d3ae4acce45c4e70cf6fbbef
ed6f03c2780226a28113ba535d3e438ee5d70266
/src/eljconfigbase.cpp
671ecd4034a09941c20fd6ce15c28b9ba5a810ba
[]
no_license
snmsts/wxc
f06c0306d0ff55f0634e5a372b3a71f56325c647
19663c56e4ae2c79ccf647d687a9a1d42ca8cb61
refs/heads/master
2021-01-01T05:41:20.607789
2009-04-08T09:12:08
2009-04-08T09:12:08
170,876
4
1
null
null
null
null
UTF-8
C++
false
false
5,596
cpp
#include "wrapper.h" extern "C" { EWXWEXPORT(wxConfigBase*,wxConfigBase_Create)() { return wxConfigBase::Create(); } EWXWEXPORT(void,wxConfigBase_Delete)(wxConfigBase* self) { delete self; } EWXWEXPORT(void,wxConfigBase_SetPath)(wxConfigBase* self,wxString* strPath) { self->SetPath(*strPath); } EWXWEXPORT(wxString*,wxConfigBase_GetPath)(wxConfigBase* self) { return new wxString(self->GetPath()); } EWXWEXPORT(wxString*,wxConfigBase_GetFirstGroup)(wxConfigBase* self,long* lIndex) { wxString* tmp; tmp = new wxString(wxT("")); if (self->GetFirstGroup(*tmp,*lIndex)) { *lIndex = -1; } return tmp; } EWXWEXPORT(wxString*,wxConfigBase_GetNextGroup)(wxConfigBase* self,long* lIndex) { wxString* tmp; tmp = new wxString(wxT("")); if (self->GetNextGroup(*tmp,*lIndex)) { *lIndex = -1; } return tmp; } EWXWEXPORT(wxString*,wxConfigBase_GetFirstEntry)(wxConfigBase* self,long* lIndex) { wxString* tmp; tmp = new wxString(wxT("")); if (self->GetFirstEntry(*tmp,*lIndex)) { *lIndex = -1; } return tmp; } EWXWEXPORT(wxString*,wxConfigBase_GetNextEntry)(wxConfigBase* self,long* lIndex) { wxString* tmp; tmp = new wxString(wxT("")); if (self->GetNextEntry(*tmp,*lIndex)) { *lIndex = -1; } return tmp; } EWXWEXPORT(size_t,wxConfigBase_GetNumberOfEntries)(wxConfigBase* self,bool bRecursive) { return self->GetNumberOfEntries(bRecursive); } EWXWEXPORT(size_t,wxConfigBase_GetNumberOfGroups)(wxConfigBase* self,bool bRecursive) { return self->GetNumberOfGroups(bRecursive); } EWXWEXPORT(bool,wxConfigBase_HasGroup)(wxConfigBase* self,wxString* strName) { return self->HasGroup(*strName); } EWXWEXPORT(bool,wxConfigBase_HasEntry)(wxConfigBase* self,wxString* strName) { return self->HasEntry(*strName); } EWXWEXPORT(bool,wxConfigBase_Exists)(wxConfigBase* self,wxString* strName) { return self->Exists(*strName); } EWXWEXPORT(int,wxConfigBase_GetEntryType)(wxConfigBase* self,wxString* name) { return (int)self->GetEntryType(*name); } EWXWEXPORT(wxString*,wxConfigBase_ReadString)(wxConfigBase* self,wxString* key,wxString* defVal) { wxString tmp; tmp = self->Read(*key,*defVal); return new wxString(tmp); } EWXWEXPORT(int,wxConfigBase_ReadInteger)(wxConfigBase* self,wxString* key,int defVal) { return self->Read(*key, defVal); } EWXWEXPORT(double,wxConfigBase_ReadDouble)(wxConfigBase* self,wxString* key,double defVal) { double val; if (self->Read(*key, &val, defVal)) return val; return 0.0; } EWXWEXPORT(bool,wxConfigBase_ReadBool)(wxConfigBase* self,wxString* key,bool defVal) { bool val; if (self->Read(*key, &val, defVal)) return val; return false; } EWXWEXPORT(bool,wxConfigBase_WriteString)(wxConfigBase* self,wxString* key,wxString* value) { return self->Write(*key,*value); } EWXWEXPORT(bool,wxConfigBase_Writelong)(wxConfigBase* self,wxString* key,long value) { return self->Write(*key, value); } EWXWEXPORT(bool,wxConfigBase_WriteDouble)(wxConfigBase* self,wxString* key,double value) { return self->Write(*key, value); } EWXWEXPORT(bool,wxConfigBase_WriteBool)(wxConfigBase* self,wxString* key,bool value) { return self->Write(*key, value); } EWXWEXPORT(bool,wxConfigBase_Flush)(wxConfigBase* self,bool bCurrentOnly) { return self->Flush(bCurrentOnly); } EWXWEXPORT(bool,wxConfigBase_RenameEntry)(wxConfigBase* self,wxString* oldName,wxString* newName) { return self->RenameEntry(*oldName,*newName); } EWXWEXPORT(bool,wxConfigBase_RenameGroup)(wxConfigBase* self,wxString* oldName,wxString* newName) { return self->RenameGroup(*oldName,*newName); } EWXWEXPORT(bool,wxConfigBase_DeleteEntry)(wxConfigBase* self,wxString* key,bool bDeleteGroupIfEmpty) { return self->DeleteEntry(*key, bDeleteGroupIfEmpty); } EWXWEXPORT(bool,wxConfigBase_DeleteGroup)(wxConfigBase* self,wxString* key) { return self->DeleteGroup(*key); } EWXWEXPORT(bool,wxConfigBase_DeleteAll)(wxConfigBase* self) { return self->DeleteAll(); } EWXWEXPORT(bool,wxConfigBase_IsExpandingEnvVars)(wxConfigBase* self) { return self->IsExpandingEnvVars(); } EWXWEXPORT(void,wxConfigBase_SetExpandEnvVars)(wxConfigBase* self,bool bDoIt) { self->SetExpandEnvVars(bDoIt); } EWXWEXPORT(void,wxConfigBase_SetRecordDefaults)(wxConfigBase* self,bool bDoIt) { self->SetRecordDefaults(bDoIt); } EWXWEXPORT(bool,wxConfigBase_IsRecordingDefaults)(wxConfigBase* self) { return self->IsRecordingDefaults(); } EWXWEXPORT(wxString*,wxConfigBase_ExpandEnvVars)(wxConfigBase* self,wxString* str) { return new wxString(self->ExpandEnvVars(*str)); } EWXWEXPORT(wxString*,wxConfigBase_GetAppName)(wxConfigBase* self) { return new wxString(self->GetAppName()); } EWXWEXPORT(wxString*,wxConfigBase_GetVendorName)(wxConfigBase* self) { return new wxString(self->GetVendorName()); } EWXWEXPORT(void,wxConfigBase_SetAppName)(wxConfigBase* self,wxString* appName) { self->SetAppName(*appName); } EWXWEXPORT(void,wxConfigBase_SetVendorName)(wxConfigBase* self,wxString* vendorName) { self->SetVendorName(*vendorName); } EWXWEXPORT(void,wxConfigBase_SetStyle)(wxConfigBase* self,int style) { self->SetStyle((long)style); } EWXWEXPORT(long,wxConfigBase_GetStyle)(wxConfigBase* self) { return self->GetStyle(); } }
[ [ [ 1, 230 ] ] ]
9f73dff0387d01029371cf6eeb930fc51ae68052
6477cf9ac119fe17d2c410ff3d8da60656179e3b
/Projects/openredalert/src/ui/logger.cpp
1d82a67989d536d5d8d4795ce6d9c3eefe6b5eec
[]
no_license
crutchwalkfactory/motocakerteam
1cce9f850d2c84faebfc87d0adbfdd23472d9f08
0747624a575fb41db53506379692973e5998f8fe
refs/heads/master
2021-01-10T12:41:59.321840
2010-12-13T18:19:27
2010-12-13T18:19:27
46,494,539
0
0
null
null
null
null
UTF-8
C++
false
false
4,546
cpp
// Logger.cpp // 1.2 // This file is part of OpenRedAlert. // // OpenRedAlert 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, version 2 of the License. // // OpenRedAlert 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 OpenRedAlert. If not, see <http://www.gnu.org/licenses/>. #include <cstdarg> // for use fct like 'printf' #include <cstdio> #include <cstdlib> #include "include/Logger.h" #include "video/MessagePool.h" #include "vfs/vfs.h" #include "vfs/VFile.h" namespace pc { extern MessagePool * msg; } Logger::Logger(const char *logname, int threshold) { logfile = VFSUtils::VFS_Open(logname, "w"); #if !defined _WIN32 if( logfile == NULL ) { printf("Unable to open logfile \"%s\" for writing, using stdout instead\n", logname); } #endif indentsteps = 0; indentString[0] = '\0'; rendergamemsg = false; this->threshold = threshold; } /** * Close the logfile at exit */ Logger::~Logger(){ VFSUtils::VFS_Close(logfile); } void Logger::indent(){ if( indentsteps > 60 ) { indentsteps = 62; } else { indentString[indentsteps] = ' '; indentString[indentsteps+1] = ' '; indentsteps+=2; } indentString[indentsteps] = '\0'; } void Logger::unindent(){ if( indentsteps < 3 ) { indentsteps = 0; } else { indentsteps -= 2; } indentString[indentsteps] = '\0'; } void Logger::error(const char *txt, ...) { va_list ap, aq; va_start(ap, txt); va_start(aq, txt); if (logfile != NULL) { logfile->vfs_printf("%sERROR: ", indentString); logfile->vfs_vprintf(txt, aq); logfile->flush(); } #if !defined _WIN32 printf("%sERROR: ", indentString); vprintf(txt, ap); fflush(stdout); #endif va_end(aq); va_end(ap); } void Logger::debug(const char *txt, ...) { va_list ap, aq; va_start(ap, txt); va_start(aq, txt); if (logfile != NULL) { logfile->vfs_printf("%sDEBUG: ", indentString); logfile->vfs_vprintf(txt, aq); logfile->flush(); } #if !defined _WIN32 printf("%sDEBUG: ", indentString); vprintf(txt, ap); fflush(stdout); #endif va_end(aq); va_end(ap); } void Logger::warning(const char *txt, ...) { va_list ap, aq; va_start(ap, txt); va_start(aq, txt); if (logfile != NULL) { logfile->vfs_printf("%sWARNING: ", indentString); logfile->vfs_vprintf(txt, aq); logfile->flush(); } #if !defined _WIN32 if (threshold > 0) { printf("%sWARNING: ", indentString); vprintf(txt,ap); fflush(stdout); } #endif va_end(aq); va_end(ap); } void Logger::note(const char *txt, ...) { va_list ap, aq; va_start(ap, txt); va_start(aq, txt); if (logfile != NULL) { logfile->vfs_printf("%s", indentString); logfile->vfs_vprintf(txt, aq); logfile->flush(); } #if !defined _WIN32 if (threshold > 1) { printf("%s", indentString); vprintf(txt,ap); fflush(stdout); } #endif va_end(aq); va_end(ap); } void Logger::gameMsg(const char *txt, ...) { va_list ap; va_start(ap, txt); if (logfile != NULL) { logfile->vfs_printf("%sGame: ", indentString); logfile->vfs_vprintf(txt, ap); logfile->vfs_printf("\n"); logfile->flush(); } va_end(ap); if(rendergamemsg && (pc::msg != NULL)) { char msgstring[64]; va_start(ap, txt); #ifdef _MSC_VER //_vsnprintf(msgstring, 64, txt, ap); #else //vsnprintf(msgstring, 64, txt, ap); #endif va_end(ap); pc::msg->postMessage(msgstring); } else { #if !defined _WIN32 va_start(ap, txt); printf("%s",indentString); vprintf(txt,ap); va_end(ap); printf("\n"); fflush(stdout); #endif } } void Logger::renderGameMsg(bool r) { rendergamemsg = r; }
[ [ [ 1, 190 ] ] ]
0f85d97e76c8afa5d4a03659fb64d3cac2455232
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Depend/Foundation/Mathematics/Wm4Segment3.h
938ee02743fbe1ba97e8b85733ed2a82dc27e370
[]
no_license
daleaddink/flagship3d
4835c223fe1b6429c12e325770c14679c42ae3c6
6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a
refs/heads/master
2021-01-15T16:29:12.196094
2009-11-01T10:18:11
2009-11-01T10:18:11
37,734,654
1
0
null
null
null
null
UTF-8
C++
false
false
1,540
h
// Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // The Wild Magic Version 4 Foundation Library source code is supplied // under the terms of the license agreement // http://www.geometrictools.com/License/Wm4FoundationLicense.pdf // and may not be copied or disclosed except in accordance with the terms // of that agreement. #ifndef WM4SEGMENT3_H #define WM4SEGMENT3_H #include "Wm4FoundationLIB.h" #include "Wm4Vector3.h" namespace Wm4 { template <class Real> class Segment3 { public: // The segment is represented as P+t*D, where P is the segment origin, // D is a unit-length direction vector and |t| <= e. The value e is // referred to as the extent of the segment. The end points of the // segment are P-e*D and P+e*D. The user must ensure that the direction // vector is unit-length. The representation for a segment is analogous // to that for an oriented bounding box. P is the center, D is the // axis direction, and e is the extent. // construction Segment3 (); // uninitialized Segment3 (const Vector3<Real>& rkOrigin, const Vector3<Real>& rkDirection, Real fExtent); // end points Vector3<Real> GetPosEnd () const; // P+e*D Vector3<Real> GetNegEnd () const; // P-e*D Vector3<Real> Origin, Direction; Real Extent; }; #include "Wm4Segment3.inl" typedef Segment3<float> Segment3f; typedef Segment3<double> Segment3d; } #endif
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 52 ] ] ]
039bf48c6db51da3dfb3671960768e6192051861
55c675d13726d1ce015f0193654593e3b6b0f269
/WizardHolesPage.cpp
3f455b3b4930abb10e68cc2f67b8ccc6fd0d6a31
[]
no_license
fourier/Geometry2d
c4e0e9eaa16375f675fddecaab01f75b9b99dbf0
2f84511e06ae012d6c9052796e70015d5f81acc6
refs/heads/master
2020-12-24T14:10:07.238982
2009-05-26T06:57:15
2009-05-26T06:57:15
12,709,941
1
0
null
null
null
null
UTF-8
C++
false
false
1,174
cpp
// WizardHolesPage.cpp : implementation file // #include "stdafx.h" #include "Geometry2d.h" #include "WizardHolesPage.h" #include ".\wizardgeometrysheet.h" #include ".\Geometry2dView.h" #include ".\wizardholespage.h" // CWizardHolesPage dialog IMPLEMENT_DYNAMIC(CWizardHolesPage, CExtResizablePropertyPage) CWizardHolesPage::CWizardHolesPage() : CExtResizablePropertyPage(CWizardHolesPage::IDD) { } CWizardHolesPage::~CWizardHolesPage() { } void CWizardHolesPage::DoDataExchange(CDataExchange* pDX) { CExtResizablePropertyPage::DoDataExchange(pDX); } BEGIN_MESSAGE_MAP(CWizardHolesPage, CExtResizablePropertyPage) END_MESSAGE_MAP() // CWizardHolesPage message handlers BOOL CWizardHolesPage::OnSetActive() { CWizardGeometrySheet* pSheet = static_cast<CWizardGeometrySheet*>(GetParent()); pSheet->SetWizardButtons(PSWIZB_NEXT | PSWIZB_BACK ); // pSheet->GetView()->SetMode(CGeometry2dView::EHoles); return CExtResizablePropertyPage ::OnSetActive(); } BOOL CWizardHolesPage::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT* pResult) { return CExtResizablePropertyPage::OnNotify(wParam,lParam,pResult); }
[ [ [ 1, 50 ] ] ]
421be5236fa87bd3e2011acdfce7f8bd5e7e67dd
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/zombie/nnavmesh/src/ncnavnode/ncnavnode_main.cc
afa69e39fd5e7d4998e97c407dbfe363397a931f
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,851
cc
//------------------------------------------------------------------------------ // ncnavnode.cc // (C) 2005 Conjurer Services, S.A. //------------------------------------------------------------------------------ #include "precompiled/pchnnavmesh.h" #include "ncnavnode/ncnavnode.h" //------------------------------------------------------------------------------ nNebulaComponentObjectAbstract(ncNavNode,nComponentObject); //------------------------------------------------------------------------------ NSCRIPT_INITCMDS_BEGIN(ncNavNode) NSCRIPT_INITCMDS_END() //------------------------------------------------------------------------------ /** Default constructor */ ncNavNode::ncNavNode() : externalLinksNumber( 0 ) { // Empty } //------------------------------------------------------------------------------ /** Destructor */ ncNavNode::~ncNavNode() { if ( nEntityObjectServer::Instance()->CanBeUnremoved( this->GetEntityObject()->GetId() ) ) { this->ClearLocalLinks( REMOVE_SELF_FROM_TARGET ); this->ClearExternalLinks( REMOVE_SELF_FROM_TARGET ); } } //------------------------------------------------------------------------------ /** Add a local link */ void ncNavNode::AddLocalLink( ncNavNode* node ) { n_assert( node ); if ( node ) { nEntityObjectId entityId( node->GetEntityObject()->GetId() ); if ( this->links.FindIndex( entityId ) == -1 ) { this->links.Append( entityId ); } } } //------------------------------------------------------------------------------ /** Add an external link */ void ncNavNode::AddExternalLink( ncNavNode* node ) { n_assert( node ); if ( node ) { nEntityObjectId entityId( node->GetEntityObject()->GetId() ); if ( this->links.FindIndex( entityId ) == -1 ) { this->links.Insert( 0, entityId ); ++this->externalLinksNumber; } } } //------------------------------------------------------------------------------ /** Remove a local link by target node id */ void ncNavNode::RemoveLocalLink( nEntityObjectId entityId, RemoveMode removeMode ) { for ( int i( this->externalLinksNumber ); i < this->links.Size(); ++i ) { if ( this->links[i] == entityId ) { if ( removeMode == REMOVE_SELF_FROM_TARGET ) { // Remove the link that the target node has to this node nEntityObject* targetNode( nEntityObjectServer::Instance()->GetEntityObject( entityId ) ); if ( targetNode ) { targetNode->GetComponentSafe<ncNavNode>()->RemoveLocalLink( this->GetEntityObject()->GetId(), DO_NOT_REMOVE_SELF_FROM_TARGET ); } } this->links.Erase( i ); break; } } } //------------------------------------------------------------------------------ /** Remove an external link by target node id */ void ncNavNode::RemoveExternalLink( nEntityObjectId entityId, RemoveMode removeMode ) { for ( int i(0); i < this->externalLinksNumber; ++i ) { if ( this->links[i] == entityId ) { if ( removeMode == REMOVE_SELF_FROM_TARGET ) { // Remove the link that the target node has to this node nEntityObject* targetNode( nEntityObjectServer::Instance()->GetEntityObject( entityId ) ); if ( targetNode ) { targetNode->GetComponentSafe<ncNavNode>()->RemoveExternalLink( this->GetEntityObject()->GetId(), DO_NOT_REMOVE_SELF_FROM_TARGET ); } } this->links.Erase( i ); --this->externalLinksNumber; break; } } } //------------------------------------------------------------------------------ /** Remove all local links */ void ncNavNode::ClearLocalLinks( RemoveMode removeMode ) { while ( this->links.Size() > this->externalLinksNumber ) { if ( removeMode == REMOVE_SELF_FROM_TARGET ) { // Remove the link that the target node has to this node nEntityObject* targetNode( nEntityObjectServer::Instance()->GetEntityObject( this->links.Back() ) ); if ( targetNode ) { targetNode->GetComponentSafe<ncNavNode>()->RemoveLocalLink( this->GetEntityObject()->GetId(), DO_NOT_REMOVE_SELF_FROM_TARGET ); } } // Remove the link this->links.Erase( this->links.Size() - 1 ); } } //------------------------------------------------------------------------------ /** Remove all external links */ void ncNavNode::ClearExternalLinks( RemoveMode removeMode ) { for ( ; this->externalLinksNumber > 0; --this->externalLinksNumber ) { if ( removeMode == REMOVE_SELF_FROM_TARGET ) { // Remove the link that the target node has to this node nEntityObject* targetNode( nEntityObjectServer::Instance()->GetEntityObject( this->links[0] ) ); if ( targetNode ) { targetNode->GetComponentSafe<ncNavNode>()->RemoveExternalLink( this->GetEntityObject()->GetId(), DO_NOT_REMOVE_SELF_FROM_TARGET ); } } // Remove the link this->links.Erase( 0 ); } } //------------------------------------------------------------------------------ /** UpdateLinks */ void ncNavNode::UpdateLinks() { for ( int i=0; i<this->links.Size(); i++ ) { ncNavNode* node = this->GetLink(i); if ( node ) { node->RemoveLink (this); } } this->links.Reset(); this->externalLinksNumber = 0; } //------------------------------------------------------------------------------ /** RemoveLink */ void ncNavNode::RemoveLink (ncNavNode* node) { // @todo Fix this function, current implementation isn't safe for ( int i=0; i<this->links.Size(); ) { ncNavNode* link = this->GetLink(i); if ( link ) { int index = this->links.FindIndex( node->GetEntityObject()->GetId() ); if ( index != -1 ) { if ( index < this->externalLinksNumber ) { // External links are prepended --this->externalLinksNumber; } this->links.Erase (index); } else { i++; } } else { ++i; } } } //------------------------------------------------------------------------------ /** Get the number of local links */ int ncNavNode::GetLocalLinksNumber() const { return this->links.Size() - this->externalLinksNumber; } //------------------------------------------------------------------------------ /** Get the target node a local link by index */ ncNavNode* ncNavNode::GetLocalLink( int index ) const { // Local links are appended return this->GetLink( this->externalLinksNumber + index ); } //------------------------------------------------------------------------------ /** Get an approximated size in bytes of this node (actually, only the component) */ int ncNavNode::GetByteSize() const { // Static data int size( sizeof(this) ); // Links size += this->links.Size() * sizeof( nEntityObjectId ); return size; }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 277 ] ] ]
be0fe1cba5c057ecaf941223814c8d5c8e5aa43f
5c32ff848169b05f0627f24db99a4a77a3d62ac7
/BioStreamDB/DbValve.h
3c25abf4546169d1a27b2eb28324d973efe75c64
[]
no_license
namin/micado
2ad5c269d93ac4a56ef1c346636587c6d49c14e0
04a675cfaf071b5cd9e4c005f0cd629fcbca3e95
refs/heads/master
2016-09-05T21:03:11.545033
2009-01-19T00:38:03
2009-01-19T00:38:03
40,253,425
1
0
null
null
null
null
UTF-8
C++
false
false
6,625
h
// (C) Copyright 2002-2005 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // //----------------------------------------------------------------------------- //----- DbValve.h : Declaration of the DbValve //----------------------------------------------------------------------------- #pragma once #ifdef BIOSTREAMDB_MODULE #define DLLIMPEXP __declspec(dllexport) #else //----- Note: we don't use __declspec(dllimport) here, because of the //----- "local vtable" problem with msvc. If you use __declspec(dllimport), //----- then, when a client dll does a new on the class, the object's //----- vtable pointer points to a vtable allocated in that client //----- dll. If the client dll then passes the object to another dll, //----- and the client dll is then unloaded, the vtable becomes invalid //----- and any virtual calls on the object will access invalid memory. //----- //----- By not using __declspec(dllimport), we guarantee that the //----- vtable is allocated in the server dll during the ctor and the //----- client dll does not overwrite the vtable pointer after calling //----- the ctor. And, since we expect the server dll to remain in //----- memory indefinitely, there is no problem with vtables unexpectedly //----- going away. #define DLLIMPEXP #endif //----------------------------------------------------------------------------- #include "dbpl.h" //----------------------------------------------------------------------------- class DLLIMPEXP DbValve : public AcDbPolyline { public: ACRX_DECLARE_MEMBERS(DbValve) ; protected: static Adesk::UInt32 kCurrentVersionNumber ; public: DbValve () ; virtual ~DbValve () ; //----- BioStream protocols virtual Acad::ErrorStatus setCenter(const AcGePoint2d& center); virtual Acad::ErrorStatus getCenter(AcGePoint2d& center) const; virtual Acad::ErrorStatus setIndex(const Adesk::Int16& index); virtual Acad::ErrorStatus getIndex(Adesk::Int16& index) const; //----- AcDbObject protocols //- Dwg Filing protocol virtual Acad::ErrorStatus dwgOutFields (AcDbDwgFiler *pFiler) const ; virtual Acad::ErrorStatus dwgInFields (AcDbDwgFiler *pFiler) ; //- Dxf Filing protocol virtual Acad::ErrorStatus dxfOutFields (AcDbDxfFiler *pFiler) const ; virtual Acad::ErrorStatus dxfInFields (AcDbDxfFiler *pFiler) ; //----- AcDbEntity protocols //- Graphics protocol virtual Adesk::Boolean worldDraw (AcGiWorldDraw *mode) ; //----- AcDbCurve protocols //- Curve property tests. virtual Adesk::Boolean isClosed () const ; virtual Adesk::Boolean isPeriodic () const ; //- Get planar and start/end geometric properties. virtual Acad::ErrorStatus getStartParam (double &param) const ; virtual Acad::ErrorStatus getEndParam (double &param) const ; virtual Acad::ErrorStatus getStartPoint (AcGePoint3d &point) const ; virtual Acad::ErrorStatus getEndPoint (AcGePoint3d &point) const ; //- Conversions to/from parametric/world/distance. virtual Acad::ErrorStatus getPointAtParam (double param, AcGePoint3d &point) const ; virtual Acad::ErrorStatus getParamAtPoint (const AcGePoint3d &point, double &param) const ; virtual Acad::ErrorStatus getDistAtParam (double param, double &dist) const ; virtual Acad::ErrorStatus getParamAtDist (double dist, double &param) const ; virtual Acad::ErrorStatus getDistAtPoint (const AcGePoint3d &point , double &dist) const ; virtual Acad::ErrorStatus getPointAtDist (double dist, AcGePoint3d &point) const ; //- Derivative information. virtual Acad::ErrorStatus getFirstDeriv (double param, AcGeVector3d &firstDeriv) const ; virtual Acad::ErrorStatus getFirstDeriv (const AcGePoint3d &point, AcGeVector3d &firstDeriv) const ; virtual Acad::ErrorStatus getSecondDeriv (double param, AcGeVector3d &secDeriv) const ; virtual Acad::ErrorStatus getSecondDeriv (const AcGePoint3d &point, AcGeVector3d &secDeriv) const ; //- Closest point on curve. virtual Acad::ErrorStatus getClosestPointTo (const AcGePoint3d &givenPnt, AcGePoint3d &pointOnCurve, Adesk::Boolean extend =Adesk::kFalse) const ; virtual Acad::ErrorStatus getClosestPointTo (const AcGePoint3d &givenPnt, const AcGeVector3d &direction, AcGePoint3d &pointOnCurve, Adesk::Boolean extend =Adesk::kFalse) const ; //- Get a projected copy of the curve. virtual Acad::ErrorStatus getOrthoProjectedCurve (const AcGePlane &plane, AcDbCurve *&projCrv) const ; virtual Acad::ErrorStatus getProjectedCurve (const AcGePlane &plane, const AcGeVector3d &projDir, AcDbCurve *&projCrv) const ; //- Get offset, spline and split copies of the curve. virtual Acad::ErrorStatus getOffsetCurves (double offsetDist, AcDbVoidPtrArray &offsetCurves) const ; virtual Acad::ErrorStatus getOffsetCurvesGivenPlaneNormal (const AcGeVector3d &normal, double offsetDist, AcDbVoidPtrArray &offsetCurves) const ; virtual Acad::ErrorStatus getSpline (AcDbSpline *&spline) const ; virtual Acad::ErrorStatus getSplitCurves (const AcGeDoubleArray &params, AcDbVoidPtrArray &curveSegments) const ; virtual Acad::ErrorStatus getSplitCurves (const AcGePoint3dArray &points, AcDbVoidPtrArray &curveSegments) const ; //- Extend the curve. virtual Acad::ErrorStatus extend (double newParam) ; virtual Acad::ErrorStatus extend (Adesk::Boolean extendStart, const AcGePoint3d &toPoint) ; //- Area calculation. virtual Acad::ErrorStatus getArea (double &area) const ; private: AcGePoint2d m_center; Adesk::Int16 m_index; // ----------------------------------------------------------------------------- virtual Acad::ErrorStatus transformBy(const AcGeMatrix3d & xform); } ; #ifdef BIOSTREAMDB_MODULE ACDB_REGISTER_OBJECT_ENTRY_AUTO(DbValve) #endif
[ "Nada AMIN@b571c760-3347-0410-a02b-4f11275fb890" ]
[ [ [ 1, 130 ] ] ]
7c5277bcc7f5239c04dcedb8d6043abdf4674c4b
e02f627da312e04ec538a34e6bcf6ef7ea87698d
/Vert.h
67ba11dd934dfd10c9ea65c6605d18818d1bb84e
[]
no_license
placidz/projetlods
053108510c49585f168dd469bd4b59caefb89a70
f47372beabbd1854ad0f21562653c95d3e19d9e1
refs/heads/master
2016-09-05T22:27:02.744917
2011-02-21T18:13:59
2011-02-21T18:13:59
32,144,842
0
0
null
null
null
null
UTF-8
C++
false
false
396
h
#ifndef VERT_H #define VERT_H #include <list> #include <Vec2.h> #include <Vec3.h> #include <Edge.h> typedef struct Vert * ptrVert; class Edge; class Vert { public: int id; Vec3d pos; Vec3d normal; Vec3d color; Vec2d tex; std::list<Edge*> edges; Vert(); Vert(int _id); Vert(Vert* _v); ~Vert(); }; #endif // VERT_H
[ "[email protected]@c2703def-0b70-d52f-7536-8dfe1f43c09c", "[email protected]@c2703def-0b70-d52f-7536-8dfe1f43c09c" ]
[ [ [ 1, 27 ], [ 29, 29 ], [ 31, 33 ] ], [ [ 28, 28 ], [ 30, 30 ] ] ]
03e1d0980e5c598bc951dc4dbb5e2e8cbf4ccfc0
6630a81baef8700f48314901e2d39141334a10b7
/1.4/Testing/Cxx/swWxGuiTesting/CapturedEvents/swCRSliderUpdateEvent.h
df503e7a4eb0b261057c08b84d131e97af811e63
[]
no_license
jralls/wxGuiTesting
a1c0bed0b0f5f541cc600a3821def561386e461e
6b6e59e42cfe5b1ac9bca02fbc996148053c5699
refs/heads/master
2021-01-10T19:50:36.388929
2009-03-24T20:22:11
2009-03-26T18:51:24
623,722
1
0
null
null
null
null
ISO-8859-1
C++
false
false
2,760
h
/////////////////////////////////////////////////////////////////////////////// // Name: swWxGuiTesting/CaptureEvents/swCRSliderUpdateEvent.h // Author: Reinhold Füreder // Created: 2004 // Copyright: (c) 2005 Reinhold Füreder // Licence: wxWindows licence /////////////////////////////////////////////////////////////////////////////// #ifndef SWCRSLIDERUPDATEEVENT_H #define SWCRSLIDERUPDATEEVENT_H #ifdef __GNUG__ #pragma interface "swCRSliderUpdateEvent.h" #endif #include "Common.h" #include "swCRCapturedEvent.h" namespace swTst { /*! \class CRSliderUpdateEvent \brief Handle slider update events. Understandably, moving the slider creates several events -- intermediate positions are taken into account as well; cf. text control text update events. Moreover, a range of different events are created: - wxEVT_COMMAND_SLIDER_UPDATED, wxEVT_SCROLL_THUMBTRACK continuously; - wxEVT_SCROLL_THUMBRELEASE and wxEVT_SCROLL_ENDSCROLL (only MS Windows) at the end. TODO: Maybe sometimes it is desirable to create intermediate events, so capturing wxEVT_SCROLL_THUMBRELEASE should be used in general, and for in special cases (where intermediate events are of interest) this behaviour should be switched to on??? */ class CRSliderUpdateEvent : public CRCapturedEvent { public: /*! \fn CRSliderUpdateEvent (wxEvent *event) \brief Constructor \param event event to handle */ CRSliderUpdateEvent (wxEvent *event); /*! \fn virtual ~CRSliderUpdateEvent () \brief Destructor */ virtual ~CRSliderUpdateEvent (); /*! \fn virtual bool IsPending () const \brief Return true because slider update events are assembled into one. \return true */ virtual bool IsPending () const; /*! \fn virtual void Process (CRCapturedEvent **pendingEvt) \brief Process event, only called after checking for handling ability. \param pendingEvt current pending event with respect to code emitting (or NULL if none is pending) */ virtual void Process (CRCapturedEvent **pendingEvt); /*! \fn virtual void EmitCpp () \brief Emit event simulation specific C++ code. */ virtual void EmitCpp (); protected: private: wxString m_containerName; wxString m_sliderName; int m_sliderValue; bool m_isXRC; private: // No copy and assignment constructor: CRSliderUpdateEvent (const CRSliderUpdateEvent &rhs); CRSliderUpdateEvent & operator= (const CRSliderUpdateEvent &rhs); }; } // End namespace swTst #endif // SWCRSLIDERUPDATEEVENT_H
[ "john@64288482-8357-404e-ad65-de92a562ee98" ]
[ [ [ 1, 94 ] ] ]
c513152b6a9c8518f8cc8e30a11a62a9058afb30
48c6de8cb63cf11147049ce07b2bd7e020d0d12b
/opencollada/include/COLLADAFramework/include/COLLADAFWObject.h
887aecc4b01a5a7fbaf32c1ff180a73d299de057
[]
no_license
ngbinh/libBlenderWindows
73effaa1aab8d9d1745908f5528ded88eca21ce3
23fbaaaad973603509b23f789a903959f6ebb560
refs/heads/master
2020-06-08T00:41:55.437544
2011-03-25T05:13:25
2011-03-25T05:13:25
1,516,625
1
1
null
null
null
null
UTF-8
C++
false
false
2,429
h
/* Copyright (c) 2008-2009 NetAllied Systems GmbH This file is part of COLLADAFramework. Licensed under the MIT Open Source License, for details please see LICENSE file or the website http://www.opensource.org/licenses/mit-license.php */ #ifndef __COLLADAFW_OBJECT_H__ #define __COLLADAFW_OBJECT_H__ #include "COLLADAFWPrerequisites.h" #include "COLLADAFWUniqueId.h" namespace COLLADAFW { /** Base class of all classes that can be referenced in the model.*/ class Object { public: virtual ~Object(){}; /** Returns the class id of the object.*/ virtual ClassId getClassId() const =0; /** Returns the unique id of the object.*/ virtual const UniqueId& getUniqueId() const = 0; }; /** Base class of all classes that can be referenced in the model.*/ template<ClassId classId> class ObjectTemplate : public Object { private: /** The unique id of the object.*/ UniqueId mUniqueId; public: ObjectTemplate(ObjectId objectId, FileId fileId) : mUniqueId(classId, objectId, fileId) {} ObjectTemplate(const UniqueId& uniqueId) : mUniqueId(uniqueId) {} virtual ~ObjectTemplate() {} /** Returns the unique id of the object.*/ const UniqueId& getUniqueId() const { return mUniqueId; } /** Returns the class id of the object.*/ static ClassId ID() { return classId; } /** Returns the class id of the object.*/ ClassId getClassId() const { return ID(); } /** Returns the object id of the object.*/ ObjectId getObjectId() const { return mUniqueId.getObjectId(); } /** Returns the file id of the object.*/ FileId getFileId() const { return mUniqueId.getFileId(); } protected: /** Sets the unique id of the object.*/ void setUniqueId ( const UniqueId& uniqueId ) { COLLADABU_ASSERT( uniqueId.getClassId() == classId ); mUniqueId = uniqueId; } }; template<class ObjectType> ObjectType* objectSafeCast(Object* object) { if ( !object) return 0; if ( object->getClassId() == ObjectType::ID() ) return (ObjectType*)object; else return 0; } template<class ObjectType> const ObjectType* objectSafeCast(const Object* object) { if ( !object) return 0; if ( object->getClassId() == ObjectType::ID() ) return (ObjectType*)object; else return 0; } } // namespace COLLADAFW #endif // __COLLADAFW_OBJECT_H__
[ [ [ 1, 107 ] ] ]
7e6263f245ced5b484b25083cf7aff1f7d9210e9
a9cf0c2a8904e42a206c3575b244f8b0850dd7af
/Member.h
b8cdc6ba482237989c063732f78f81c5d5a66910
[]
no_license
jayrulez/ourlib
3a38751ccb6a38785d4df6f508daeff35ccfd09f
e4727d638f2d69ea29114dc82b9687ea1fd17a2d
refs/heads/master
2020-04-22T15:42:00.891099
2010-01-06T20:00:17
2010-01-06T20:00:17
40,554,487
0
0
null
null
null
null
UTF-8
C++
false
false
973
h
/* @Group: BSC2D @Group Members: <ul> <li>Robert Campbell: 0701334</li> <li>Audley Gordon: 0802218</li> <li>Dale McFarlane: 0801042</li> <li>Dyonne Duberry: 0802189</li> <li>Xavier Lowe: 0802488</li> </ul> @ */ #ifndef _MEMBER_H #define _MEMBER_H #include "gui\console\console.h" #include "gui\console\frame.h" #include <string> using namespace std; class Member { private: string id; string firstName; string lastName; string address; string contactNumber; console consoleObj; frame frameObj; public: Member(); ~Member(); Member(string,string,string,string,string); void setId(string); int getNewId(); void setFirstName(string); void setLastName(string); void setAddress(string); void setContactNumber(string); string getId() const; string getFirstName() const; string getLastName() const; string getAddress() const; string getContactNumber() const; void showMember(int,int); }; #endif
[ [ [ 1, 49 ] ] ]
5062909842dc42aa709c86faddca1db86b4a1349
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/graph/test/graph_concepts.cpp
969c2a52124fea8a34c86d2d1ba7f8dc5a09f440
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference", "Artistic-2.0", "LicenseRef-scancode-public-domain" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
UTF-8
C++
false
false
1,572
cpp
//======================================================================= // Copyright 1997, 1998, 1999, 2000 University of Notre Dame. // Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek // // 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) //======================================================================= #include <boost/graph/graph_concepts.hpp> #include <boost/graph/graph_archetypes.hpp> int main(int,char*[]) { using namespace boost; // Check graph concepts againt their archetypes typedef default_constructible_archetype< sgi_assignable_archetype< equality_comparable_archetype<> > > Vertex; typedef incidence_graph_archetype<Vertex, directed_tag, allow_parallel_edge_tag> Graph1; function_requires< IncidenceGraphConcept<Graph1> >(); typedef adjacency_graph_archetype<Vertex, directed_tag, allow_parallel_edge_tag> Graph2; function_requires< AdjacencyGraphConcept<Graph2> >(); typedef vertex_list_graph_archetype<Vertex, directed_tag, allow_parallel_edge_tag> Graph3; function_requires< VertexListGraphConcept<Graph3> >(); function_requires< ColorValueConcept<color_value_archetype> >(); typedef incidence_graph_archetype<Vertex, directed_tag, allow_parallel_edge_tag> G; typedef property_graph_archetype<G, vertex_color_t, color_value_archetype> Graph4; function_requires< PropertyGraphConcept<Graph4, Vertex, vertex_color_t> >(); return 0; }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 40 ] ] ]
8e4903a15c1a427eb8cb9bd996f567c459cd5362
91b964984762870246a2a71cb32187eb9e85d74e
/SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/multi_index/test/test_comparison.cpp
d7a8cc78a082c3377304cbcdadf51b706b6f069d
[ "BSL-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
willrebuild/flyffsf
e5911fb412221e00a20a6867fd00c55afca593c7
d38cc11790480d617b38bb5fc50729d676aef80d
refs/heads/master
2021-01-19T20:27:35.200154
2011-02-10T12:34:43
2011-02-10T12:34:43
32,710,780
3
0
null
null
null
null
ISO-8859-1
C++
false
false
3,431
cpp
/* Boost.MultiIndex test for comparison functions. * * Copyright 2003-2006 Joaquín M López Muñoz. * 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) * * See http://www.boost.org/libs/multi_index for library home page. */ #include "test_comparison.hpp" #include <boost/config.hpp> /* keep it first to prevent nasty warns in MSVC */ #include "pre_multi_index.hpp" #include "employee.hpp" #include <boost/test/test_tools.hpp> using namespace boost::multi_index; template<typename Value> struct lookup_list{ typedef multi_index_container< Value, indexed_by< sequenced<>, ordered_non_unique<identity<Value> > > > type; }; template<typename Value> struct lookup_vector{ typedef multi_index_container< Value, indexed_by< random_access<>, ordered_non_unique<identity<Value> > > > type; }; void test_comparison() { employee_set es; employee_set_by_age& i2=get<2>(es); employee_set_as_inserted& i3=get<3>(es); employee_set_randomly& i5=get<5>(es); es.insert(employee(0,"Joe",31,1123)); es.insert(employee(1,"Robert",27,5601)); es.insert(employee(2,"John",40,7889)); es.insert(employee(3,"Albert",20,9012)); es.insert(employee(4,"John",57,1002)); employee_set es2; employee_set_by_age& i22=get<age>(es2); employee_set_as_inserted& i32=get<3>(es2); employee_set_randomly& i52=get<5>(es2); es2.insert(employee(0,"Joe",31,1123)); es2.insert(employee(1,"Robert",27,5601)); es2.insert(employee(2,"John",40,7889)); es2.insert(employee(3,"Albert",20,9012)); BOOST_CHECK(es==es&&es<=es&&es>=es&& i22==i22&&i22<=i22&&i22>=i22&& i32==i32&&i32<=i32&&i32>=i32&& i52==i52&&i52<=i52&&i52>=i52); BOOST_CHECK(es!=es2&&es2<es&&es>es2&&!(es<=es2)&&!(es2>=es)); BOOST_CHECK(i2!=i22&&i22<i2&&i2>i22&&!(i2<=i22)&&!(i22>=i2)); BOOST_CHECK(i3!=i32&&i32<i3&&i3>i32&&!(i3<=i32)&&!(i32>=i3)); BOOST_CHECK(i5!=i52&&i52<i5&&i5>i52&&!(i5<=i52)&&!(i52>=i5)); lookup_list<int>::type l1; lookup_list<char>::type l2; lookup_vector<char>::type l3; lookup_list<long>::type l4; lookup_vector<long>::type l5; l1.push_back(3); l1.push_back(4); l1.push_back(5); l1.push_back(1); l1.push_back(2); l2.push_back(char(3)); l2.push_back(char(4)); l2.push_back(char(5)); l2.push_back(char(1)); l2.push_back(char(2)); l3.push_back(char(3)); l3.push_back(char(4)); l3.push_back(char(5)); l3.push_back(char(1)); l3.push_back(char(2)); l4.push_back(long(3)); l4.push_back(long(4)); l4.push_back(long(5)); l4.push_back(long(1)); l5.push_back(long(3)); l5.push_back(long(4)); l5.push_back(long(5)); l5.push_back(long(1)); BOOST_CHECK(l1==l2&&l1<=l2&&l1>=l2); BOOST_CHECK( get<1>(l1)==get<1>(l2)&&get<1>(l1)<=get<1>(l2)&&get<1>(l1)>=get<1>(l2)); BOOST_CHECK( get<1>(l1)==get<1>(l3)&&get<1>(l1)<=get<1>(l3)&&get<1>(l1)>=get<1>(l3)); BOOST_CHECK(l1!=l4&&l4<l1&&l1>l4); BOOST_CHECK( get<1>(l1)!=get<1>(l4)&&get<1>(l1)<get<1>(l4)&&get<1>(l4)>get<1>(l1)); BOOST_CHECK(l3!=l5&&l5<l3&&l3>l5); BOOST_CHECK( get<1>(l3)!=get<1>(l5)&&get<1>(l3)<get<1>(l5)&&get<1>(l5)>get<1>(l3)); }
[ "[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278" ]
[ [ [ 1, 117 ] ] ]
5934fc45a8f84b772ee11c96b9be55e9cc49faf7
9ad9345e116ead00be7b3bd147a0f43144a2e402
/Integration_WAH_&_Extraction/SMDataExtraction/FlexVCBridgeStaticLib/ASResponse.h
9abd71de7b0eb325c2bb754c6861d52e00266530
[]
no_license
asankaf/scalable-data-mining-framework
e46999670a2317ee8d7814a4bd21f62d8f9f5c8f
811fddd97f52a203fdacd14c5753c3923d3a6498
refs/heads/master
2020-04-02T08:14:39.589079
2010-07-18T16:44:56
2010-07-18T16:44:56
33,870,353
0
0
null
null
null
null
UTF-8
C++
false
false
1,248
h
/* * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is the Flex C++ Bridge. * * The Initial Developer of the Original Code is * Anirudh Sasikumar (http://anirudhs.chaosnet.org/). * Portions created by the Initial Developer are Copyright (C) 2008 * the Initial Developer. All Rights Reserved. * * Contributor(s): * */ #pragma once #include <string> /* Encapsulates an XML response from flash. This has an int id as well * that points to which flash object the request is from. Flash * objects to id mapping is persisted in the CFlashIDManager class */ class CASResponse { public: CASResponse(void); ~CASResponse(void); std::string m_sResponse; int m_iFlashID; unsigned int m_uiID; bool m_bResponded; };
[ "jaadds@c7f6ba40-6498-11de-987a-95e5a5a5d5f1" ]
[ [ [ 1, 44 ] ] ]
bbf02361ebe56279302d90191a8f12b383217e25
5c3ae0d061432533efe7b777c8205cf00db72be6
/ spacerenegade/src/ou_thread.cpp
a169d8ccfdd8509484defdc2e0722243e1913e50
[]
no_license
jamoozy/spacerenegade
6da0abbcdc86a9edb3a1a9c4e7224d5a1121423c
4240a4b6418cb7b03d22a42de65e800277cfc889
refs/heads/master
2016-09-06T17:24:11.028035
2007-08-12T07:19:14
2007-08-12T07:19:14
41,124,730
0
0
null
null
null
null
UTF-8
C++
false
false
7,343
cpp
/** ou_thread.cpp * implements the Thread class * Author: Vijay Mathew Pandyalakal * Date: 13-OCT-2003 **/ /* Copyright 2000 - 2005 Vijay Mathew Pandyalakal. All rights reserved. * * This software may be used or modified for any purpose, personal or * commercial. Open Source redistributions are permitted. * * Redistributions qualify as "Open Source" under one of the following terms: * * Redistributions are made at no charge beyond the reasonable cost of * materials and delivery. * * Redistributions are accompanied by a copy of the Source Code or by an * irrevocable offer to provide a copy of the Source Code for up to three * years at the cost of materials and delivery. Such redistributions * must allow further use, modification, and redistribution of the Source * Code under substantially the same terms as this license. * * Redistributions of source code must retain the copyright notices as they * appear in each source code file, these license terms, and the * disclaimer/limitation of liability set forth as paragraph 6 below. * * Redistributions in binary form must reproduce this Copyright Notice, * these license terms, and the disclaimer/limitation of liability set * forth as paragraph 6 below, in the documentation and/or other materials * provided with the distribution. * * The Software is provided on an "AS IS" basis. No warranty is * provided that the Software is free of defects, or fit for a * particular purpose. * * Limitation of Liability. The Author shall not be liable * for any damages suffered by the Licensee or any third party resulting * from use of the Software. */ #ifdef WIN32 #include <string> using namespace std; #include <windows.h> #include "ou_thread.h" using namespace openutils; const int Thread::P_ABOVE_NORMAL = THREAD_PRIORITY_ABOVE_NORMAL; const int Thread::P_BELOW_NORMAL = THREAD_PRIORITY_BELOW_NORMAL; const int Thread::P_HIGHEST = THREAD_PRIORITY_HIGHEST; const int Thread::P_IDLE = THREAD_PRIORITY_IDLE; const int Thread::P_LOWEST = THREAD_PRIORITY_LOWEST; const int Thread::P_NORMAL = THREAD_PRIORITY_NORMAL; const int Thread::P_CRITICAL = THREAD_PRIORITY_TIME_CRITICAL; // The Thread class implementation // Thread() Thread::Thread() { m_hThread = NULL; m_strName = "null"; } /** Thread(const char* nm) * overloaded constructor * creates a Thread object identified by "nm" **/ Thread::Thread(const char* nm) { m_hThread = NULL; m_strName = nm; } Thread::~Thread() { if(m_hThread != NULL) { stop(); } } /** setName(const char* nm) * sets the Thread object's name to "nm" **/ void Thread::setName(const char* nm) { m_strName = nm; } /** getName() * return the Thread object's name as a string **/ string Thread::getName() const { return m_strName; } /** run() * called by the thread callback _ou_thread_proc() * to be overridden by child classes of Thread **/ void Thread::run() { // Base run } /** sleep(long ms) * holds back the thread's execution for * "ms" milliseconds **/ void Thread::sleep(long ms) { Sleep(ms); } /** start() * creates a low-level thread object and calls the * run() function **/ void Thread::start() { DWORD tid = 0; m_hThread = (unsigned long*)CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)_ou_thread_proc,(Thread*)this,0,&tid); if(m_hThread == NULL) { throw ThreadException("Failed to create thread"); }else { setPriority(Thread::P_NORMAL); } } /** stop() * stops the running thread and frees the thread handle **/ void Thread::stop() { if(m_hThread == NULL) return; WaitForSingleObject(m_hThread,INFINITE); CloseHandle(m_hThread); m_hThread = NULL; } /** setPriority(int tp) * sets the priority of the thread to "tp" * "tp" must be a valid priority defined in the * Thread class **/ void Thread::setPriority(int tp) { if(m_hThread == NULL) { throw ThreadException("Thread object is null"); }else { if(SetThreadPriority(m_hThread,tp) == 0) { throw ThreadException("Failed to set priority"); } } } /** suspend() * suspends the thread **/ void Thread::suspend() { if(m_hThread == NULL) { throw ThreadException("Thread object is null"); }else { if(SuspendThread(m_hThread) < 0) { throw ThreadException("Failed to suspend thread"); } } } /** resume() * resumes a suspended thread **/ void Thread::resume() { if(m_hThread == NULL) { throw ThreadException("Thread object is null"); }else { if(ResumeThread(m_hThread) < 0) { throw ThreadException("Failed to resume thread"); } } } /** wait(const char* m,long ms) * makes the thread suspend execution until the * mutex represented by "m" is released by another thread. * "ms" specifies a time-out for the wait operation. * "ms" defaults to 5000 milli-seconds **/ bool Thread::wait(const char* m,long ms) { HANDLE h = OpenMutex(MUTEX_ALL_ACCESS,FALSE,m); if(h == NULL) { throw ThreadException("Mutex not found"); } DWORD d = WaitForSingleObject(h,ms); switch(d) { case WAIT_ABANDONED: throw ThreadException("Mutex not signaled"); break; case WAIT_OBJECT_0: return true; case WAIT_TIMEOUT: throw ThreadException("Wait timed out"); break; } return false; } /** release(const char* m) * releases the mutex "m" and makes it * available for other threads **/ void Thread::release(const char* m) { HANDLE h = OpenMutex(MUTEX_ALL_ACCESS,FALSE,m); if(h == NULL) { throw ThreadException("Invalid mutex handle"); } if(ReleaseMutex(h) == 0) { throw ThreadException("Failed to release mutex"); } } // The Mutex class implementation /** Mutex() * default constructor **/ Mutex::Mutex() { m_hMutex = NULL; m_strName = ""; } /** Mutex(const char* nm) * overloaded constructor * creates a Mutex object identified by "nm" **/ Mutex::Mutex(const char* nm) { m_strName = nm; m_hMutex = (unsigned long*)CreateMutex(NULL,FALSE,nm); if(m_hMutex == NULL) { throw ThreadException("Failed to create mutex"); } } /** create(const char* nm) * frees the current mutex handle. * creates a Mutex object identified by "nm" **/ void Mutex::create(const char* nm) { if(m_hMutex != NULL) { CloseHandle(m_hMutex); m_hMutex = NULL; } m_strName = nm; m_hMutex = (unsigned long*)CreateMutex(NULL,FALSE,nm); if(m_hMutex == NULL) { throw ThreadException("Failed to create mutex"); } } /** getMutexHandle() * returns the handle of the low-level mutex object **/ unsigned long* Mutex::getMutexHandle() { return m_hMutex; } /** getName() * returns the name of the mutex **/ string Mutex::getName() { return m_strName; } void Mutex::release() { if(m_hMutex != NULL) { CloseHandle(m_hMutex); } } Mutex::~Mutex() { /*if(m_hMutex != NULL) { CloseHandle(m_hMutex); }*/ } // ThreadException ThreadException::ThreadException(const char* m) { msg = m; } string ThreadException::getMessage() const { return msg; } // global thread caallback unsigned int _ou_thread_proc(void* param) { Thread* tp = (Thread*)param; tp->run(); return 0; } #endif
[ "pmacalpi@d98d4265-742f-0410-abd1-c3b8cf015911", "jamoozy@d98d4265-742f-0410-abd1-c3b8cf015911" ]
[ [ [ 1, 40 ], [ 43, 58 ], [ 60, 60 ], [ 63, 216 ], [ 219, 294 ] ], [ [ 41, 42 ], [ 59, 59 ], [ 61, 62 ], [ 217, 218 ], [ 295, 298 ] ] ]
7193a45034ea2f0e0a126736795136c0418e3a25
0522251afd28910c4a93a7e8b996228c9a3cf9ef
/src/newwizard.h
c231dc93763c39cde332efc4a6e1014f33586693
[]
no_license
dcj/cvstat
b84a6d4818c25ea5d075b2985ae85ceaa61c88f1
b2156cc656031c32b17a974c552ca28367e5031d
refs/heads/master
2021-01-13T01:31:06.918852
2009-11-23T06:52:44
2009-11-23T06:52:44
32,278,345
0
0
null
null
null
null
UTF-8
C++
false
false
465
h
#ifndef NEWWIZARD_H #define NEWWIZARD_H #include <QDialog> #include "ui_newwizard.h" class NewWizard : public QDialog { Q_OBJECT public: NewWizard(QWidget *parent = 0); ~NewWizard(); QString getCVSRoot() const; void setCVSRootList(const QStringList & cvsroots ); bool isCVSDirectory(const QString & path) const; protected slots: void onBrowseClicked(bool checked); private: Ui::NewWizardClass ui; }; #endif // NEWWIZARD_H
[ "lijia.c@20ff9102-832f-11de-b3c3-01234016dac8" ]
[ [ [ 1, 27 ] ] ]
77a95d59a8d2ea83484a749501927968b4523e54
94c1c7459eb5b2826e81ad2750019939f334afc8
/source/FoxDriver.cpp
5e4ddaf1283d5c46e61c6d5607f92ba387fb09c2
[]
no_license
wgwang/yinhustock
1c57275b4bca093e344a430eeef59386e7439d15
382ed2c324a0a657ddef269ebfcd84634bd03c3a
refs/heads/master
2021-01-15T17:07:15.833611
2010-11-27T07:06:40
2010-11-27T07:06:40
37,531,026
1
3
null
null
null
null
GB18030
C++
false
false
14,618
cpp
#include "stdafx.h" #include "FoxDriver.h" #include "StkReceiver.h" #include "StkDatabase.h" CFoxDriver::CFoxDriver() { m_hMapping = NULL; m_pMapping = NULL; m_bHub = FALSE; } CFoxDriver::~CFoxDriver() { CloseFoxMemoryShare(); } BOOL CFoxDriver::CreateFoxMemoryShare(DWORD dwPid) { if (m_pMapping) { UnmapViewOfFile(m_pMapping); } if (m_hMapping) { CloseHandle(m_hMapping); } DWORD dwProcessId = GetCurrentProcessId(); if (dwPid != -1) { dwProcessId = dwPid; } char szShareName[64]; sprintf(szShareName, _T("PatiosoftShareMem%d"), dwProcessId); m_hMapping = CreateFileMapping((HANDLE)0xFFFFFFFF, NULL, PAGE_READWRITE, 0, 1000, szShareName); if (m_hMapping == NULL) { return FALSE; } m_pMapping = MapViewOfFile(m_hMapping, FILE_MAP_ALL_ACCESS, 0, 0, 0); if (m_pMapping == NULL) { return FALSE; } return TRUE; } void CFoxDriver::CloseFoxMemoryShare() { if (m_pMapping) { UnmapViewOfFile(m_pMapping); m_pMapping = NULL; } if (m_hMapping) { CloseHandle(m_hMapping); m_hMapping = NULL; } } BOOL CFoxDriver::CopyProcessInfo(HWND hWnd, BOOL bReceive, BOOL bHub) { if (m_pMapping == NULL) { return FALSE; } if (bReceive) { FOX_SHAREINFO foxSi; memset(&foxSi, 0, sizeof(foxSi)); foxSi.stime = time(&foxSi.stime); foxSi.dwFoxPid = GetCurrentProcessId(); foxSi.hReceiverWnd = hWnd; memcpy(m_pMapping, (void*)&foxSi, sizeof(foxSi)); } else { FOX_SHAREINFO* pSi = (FOX_SHAREINFO*)m_pMapping; pSi->dtime = time(&pSi->dtime); pSi->dwDriverPid = ::GetCurrentProcessId(); pSi->hDrvierWnd = hWnd; memcpy(&m_foxInfo, m_pMapping, sizeof(FOX_SHAREINFO)); if (!bHub) { COPYDATASTRUCT* pData = new COPYDATASTRUCT; int data = 1; pData->cbData = sizeof(int); pData->lpData = &data; pData->dwData = 1; SendMessage(pSi->hReceiverWnd, WM_COPYDATA, (WPARAM)1, (LPARAM)pData); } } return TRUE; } void CFoxDriver::RequestTick(WORD wMarket, LPTSTR szCode) { char nBuffer[360]; memset(nBuffer, 0, sizeof(nBuffer)); FOX_DATA* pData = (FOX_DATA*)nBuffer; pData->m_dwFlag = 0x00CA; pData->m_dwType = 1; int nData = 0x0100; memcpy(nBuffer + 0x0C, &nData, sizeof(nData)); nData = 0x0010CD35; memcpy(nBuffer + 0x10, &nData, sizeof(nData)); nData = 0x00000001; memcpy(nBuffer + 0x18, &nData, sizeof(nData)); nData = 0x00000001; memset(nBuffer + 0x1C, 0xFF, 0x18); memcpy(nBuffer + 0x34, &nData, sizeof(nData)); memcpy(nBuffer + 0x38, &wMarket, sizeof(WORD)); strcpy(nBuffer + 0x3A, szCode); //nData = 0x02DD8848; //memcpy(nBuffer + 0x0164, &nData, sizeof(nData)); COPYDATASTRUCT cds; memset(&cds, 0, sizeof(cds)); cds.dwData = 0; cds.cbData = sizeof(nBuffer); cds.lpData = nBuffer; CFile file; if (file.Open(_T("D:\\StockData\\Fox_Request_Tick"), CFile::modeCreate | CFile::modeWrite)) { file.Write(nBuffer, sizeof(nBuffer)); file.Close(); } if (IsWindow(m_foxInfo.hDrvierWnd)) { SendMessage(m_foxInfo.hDrvierWnd, WM_COPYDATA, 0, (LPARAM)&cds); } } void CFoxDriver::RequestKline(WORD wMarket, LPTSTR szCode, int nType) { char nBuffer[56]; memset(nBuffer, 0, sizeof(nBuffer)); FOX_DATA* pData = (FOX_DATA*)nBuffer; pData->m_dwFlag = 0x00CA; DWORD dwType; if (nType == 1) { dwType = 0x0A; // 1 分钟 } else if (nType == 2) { dwType = 0x03; // 5 分钟 } else if (nType == 5) { dwType = 0x04; // 日线 } else { return; } pData->m_dwType = dwType; int nData = 0x0200; memcpy(nBuffer + 0x0C, &nData, sizeof(nData)); memcpy(nBuffer + 0x10, &wMarket, sizeof(WORD)); strcpy(nBuffer + 0x12, szCode); COPYDATASTRUCT cds; memset(&cds, 0, sizeof(cds)); cds.dwData = 0; cds.cbData = sizeof(nBuffer); cds.lpData = nBuffer; CFile file; if (file.Open(_T("D:\\StockData\\Fox_Request_Kline"), CFile::modeCreate | CFile::modeWrite)) { file.Write(nBuffer, sizeof(nBuffer)); file.Close(); } if (IsWindow(m_foxInfo.hDrvierWnd)) { SendMessage(m_foxInfo.hDrvierWnd, WM_COPYDATA, 0, (LPARAM)&cds); } } void CFoxDriver::Start(HWND hWnd, BOOL bReceive, DWORD dwPid, BOOL bHub) { if (CreateFoxMemoryShare(dwPid)) { CopyProcessInfo(hWnd, bReceive, bHub); h1 = hWnd; if (bReceive && !bHub) { Sleep(1000); CString str; str.Format(_T("%d"), ::GetCurrentProcessId()); ShellExecute(NULL, NULL, _T("System\\ftstkdrv.exe"), str, NULL, SW_SHOWNORMAL); } else if (bHub) { HWND hWnd = TSKReceiver()->CreateReceiverWnd(); CreateFoxMemoryShare(); CopyProcessInfo(hWnd); h2 = hWnd; Sleep(1000); CString str; str.Format(_T("%d"), ::GetCurrentProcessId()); ShellExecute(NULL, NULL, _T("D:\\证券股票\\千钧茶舍专用\\System\\ftstkdrv.exe"), str, NULL, SW_SHOWNORMAL); } if (!IsWindow(m_foxInfo.hReceiverWnd)) { bHub = FALSE; bReceive = TRUE; } m_bHub = bHub; } } void CFoxDriver::Stop() { if (m_pMapping == NULL) return; HWND hwnd = ((FOX_SHAREINFO*)m_pMapping)->hDrvierWnd; int nData = 3; COPYDATASTRUCT data; data.cbData = 4; data.dwData = 0; data.lpData = &nData; if (::IsWindow(hwnd)) { ::SendMessage(hwnd, WM_COPYDATA, 0, (LPARAM)&data); } } void CFoxDriver::RequestData(WORD wMarket, LPTSTR szCode, int nType) { if (!::IsWindow(m_foxInfo.hDrvierWnd)) return; switch (nType) { case 0: RequestTick(wMarket, szCode); break; case 1: case 2: case 5: RequestTick(wMarket, szCode); RequestKline(wMarket, szCode, nType); break; default: break; } } void CFoxDriver::ProcessData(HWND hWnd, WPARAM wParam, LPARAM lParam) { COPYDATASTRUCT* pData = (COPYDATASTRUCT*)lParam; FOX_DATA* pFoxHeader = (FOX_DATA*)pData->lpData; int nCount = pFoxHeader->m_nCount; BYTE* pBuffBase = (BYTE*)pData->lpData + FOX_DATAOFFSET; CFile fileLog; static UINT nNum = 0; time_t t; char filename[256]; sprintf(filename, "D:\\StockData\\FoxData\\%d - %04d - %04x - %04x - %d", time(&t), nNum++, pFoxHeader->m_dwFlag, pFoxHeader->m_dwType, pData->cbData); BOOL bPacketLog = TRUE; // 接收程序已经启动 if (pFoxHeader->m_dwFlag == 1 && !m_bHub) { CFile file; int lenght; BYTE* pBuffer = NULL; COPYDATASTRUCT data; data.dwData = 0; // 保存接收程序信息 FOX_SHAREINFO* pInfo = (FOX_SHAREINFO*)m_pMapping; m_foxInfo.dtime = pInfo->dtime; m_foxInfo.dwDriverPid = pInfo->dwDriverPid; m_foxInfo.hDrvierWnd = pInfo->hDrvierWnd; HWND hwnd = m_foxInfo.hDrvierWnd; // FOX_DATA* pFoxHeader; lenght = 184; pBuffer = new BYTE[lenght]; memset(pBuffer, 0, lenght); pFoxHeader = (FOX_DATA*)pBuffer; pFoxHeader->m_dwFlag = 0x65; pFoxHeader->m_dwType = 0x80; pFoxHeader->m_nCount = 2; CString strName; strName.LoadString(IDR_MAINFRAME); strcpy((char*)pBuffer + 0x5C, strName.GetBuffer(0)); data.cbData = lenght; data.lpData = pBuffer; if (::IsWindow(hwnd)) { ::SendMessage(hwnd, WM_COPYDATA, 0, (LPARAM)&data); } delete pBuffer; //*/ //file.Open(_T("D:\\StockData\\fox - 1289045593 - 0065 - 00b4 - 184.dat"), CFile::modeRead); //lenght = file.GetLength(); //pBuffer = new BYTE[lenght]; //file.Read(pBuffer, lenght); //file.Close(); //data.cbData = lenght; //data.lpData = pBuffer; //if (::IsWindow(hwnd)) //{ // ::SendMessage(hwnd, WM_COPYDATA, 0, (LPARAM)&data); //} //delete pBuffer; //file.Open(_T("D:\\StockData\\fox - 1289045599 - 0066 - 023f - 579.dat"), CFile::modeRead); //lenght = file.GetLength(); //pBuffer = new BYTE[lenght]; //file.Read(pBuffer, lenght); //file.Close(); //data.cbData = lenght; //data.lpData = pBuffer; //if (::IsWindow(hwnd)) //{ // ::SendMessage(hwnd, WM_COPYDATA, 0, (LPARAM)&data); //} //delete pBuffer; //file.Open(_T("D:\\StockData\\fox - 1289045603 - 0067 - 0210 - 532.dat"), CFile::modeRead); //lenght = file.GetLength(); //pBuffer = new BYTE[lenght]; //file.Read(pBuffer, lenght); //file.Close(); //data.cbData = lenght; //data.lpData = pBuffer; //if (::IsWindow(hwnd)) //{ // ::SendMessage(hwnd, WM_COPYDATA, 0, (LPARAM)&data); //} //delete pBuffer; int nData = 2; data.cbData = 4; data.lpData = &nData; if (::IsWindow(hwnd)) { ::SendMessage(hwnd, WM_COPYDATA, 0, (LPARAM)&data); } bPacketLog = FALSE; } else if (pFoxHeader->m_dwFlag == 2 && !m_bHub) { CFile file; int len; char* buffer; COPYDATASTRUCT data; data.dwData = 0; HWND hwnd = ((FOX_SHAREINFO*)m_pMapping)->hReceiverWnd; //file.Open("D:\\StockData\\foxdata - 1 - 1288194121 - 56.dat", CFile::modeRead); //len = file.GetLength(); //buffer = new char[len]; //file.Read(buffer, len); //file.Close(); //data.cbData = file.GetLength(); //data.lpData = buffer; //if (::IsWindow(hwnd)) //{ // ::SendMessage(hwnd, WM_COPYDATA, 0, (LPARAM)&data); //} //delete buffer; //file.Open("D:\\StockData\\foxdata - 1 - 1288194123 - 569506.dat", CFile::modeRead); //len = file.GetLength(); //buffer = new char[len]; //file.Read(buffer, len); //file.Close(); //data.cbData = file.GetLength(); //data.lpData = buffer; //if (::IsWindow(hwnd)) //{ // ::SendMessage(hwnd, WM_COPYDATA, 0, (LPARAM)&data); //} //delete buffer; //file.Open("D:\\StockData\\foxdata - 1 - 1288194244 - 288.dat", CFile::modeRead); //len = file.GetLength(); //buffer = new char[len]; //file.Read(buffer, len); //file.Close(); //data.cbData = file.GetLength(); //data.lpData = buffer; //if (::IsWindow(hwnd)) //{ // ::SendMessage(hwnd, WM_COPYDATA, 0, (LPARAM)&data); //} //delete buffer; bPacketLog = FALSE; } else if (pFoxHeader->m_dwFlag == FOX_CMD_ACCOUNT) { bPacketLog = TRUE; } else if (pFoxHeader->m_dwFlag == FOX_CMD_FILE && pFoxHeader->m_dwType == FOX_CMD_CODELIST) // 代码表 { FOX_CODELIST* pList = (FOX_CODELIST*)pBuffBase; bPacketLog = FALSE; TRACE3(_T("CodeList: %d %s %d\r\n"), pList->m_wMarket, pList->m_szLabel, nCount); CString str; str.Format(_T("%s.1"), filename); ofstream ofs(str.GetBuffer(0), ios::out | ios::binary); for (int i = 0; i < nCount; i++) { str.Format("%s %d\r\n", (char*)&pList[i].m_wMarket, pList[i].time); ofs.write(str.GetBuffer(0), str.GetLength()); } ofs.close(); } else if (pFoxHeader->m_dwFlag == FOX_CMD_REPORT && pFoxHeader->m_dwType == RCV_REPORT) { RCV_REPORT_STRUCTEx* pReport = (RCV_REPORT_STRUCTEx*)pBuffBase; TSKDatabase()->ProcessReport(pReport, nCount); bPacketLog = FALSE; TRACE3(_T("Report: %d %s %d\r\n"), pReport->m_wMarket, pReport->m_szLabel, nCount); } else if (pFoxHeader->m_dwFlag == FOX_CMD_FILE && pFoxHeader->m_dwType == FILE_HISTORY_EX) { RCV_HISTORY_STRUCTEx* pHistory = (RCV_HISTORY_STRUCTEx*)pBuffBase; TSKDatabase()->ProcessHistory(pHistory, nCount); bPacketLog = FALSE; TRACE3(_T("History: %d %s %d\r\n"), pHistory->m_head.m_wMarket, pHistory->m_head.m_szLabel, nCount); } else if (pFoxHeader->m_dwFlag == FOX_CMD_FILE && pFoxHeader->m_dwType == FILE_POWER_EX) { RCV_POWER_STRUCTEx* pPower = (RCV_POWER_STRUCTEx*)pBuffBase; TSKDatabase()->ProcessPower(pPower, nCount); bPacketLog = FALSE; TRACE3(_T("Power: %d %s %d\r\n"), pPower->m_head.m_wMarket, pPower->m_head.m_szLabel, nCount); } else if (pFoxHeader->m_dwFlag == FOX_CMD_FILE && pFoxHeader->m_dwType == 83) { FOX_TICK* pTick = (FOX_TICK*)pBuffBase; TSKDatabase()->ProcessTick(pTick, nCount); bPacketLog = FALSE; TRACE3(_T("Tick: %d %s %d\r\n"), pTick->m_head.m_wMarket, pTick->m_head.m_szLabel, nCount); //CString str; //str.Format(_T("%s.1"), filename); //ofstream ofs(str.GetBuffer(0), ios::out | ios::binary); //for (int i = 0; i < nCount; i++) //{ // if (pTick[i].m_head.m_dwHeadTag == 0xFFFFFFFF) // { // ofs.write(pTick->m_head.m_szLabel, strlen(pTick->m_head.m_szLabel)); // ofs.write("\r\n", 2); // continue; // } // tm* t; // t = localtime(&pTick[i].m_time); // char strtime[64]; // strftime(strtime, 64, "%Y-%m-%d %H:%M:%S", t); // str.Format("%s\t%.2f\t%.2f\t%.2f\t%.2f\t%.2f\r\n", strtime, pTick[i].m_fNewPrice, pTick[i].m_fVolume, pTick[i].m_fVolume, pTick[i].byte[0], pTick[i].byte[1]); // ofs.write(str.GetBuffer(0), str.GetLength()); //} //ofs.close(); } else if (pFoxHeader->m_dwFlag == FOX_CMD_FILE && pFoxHeader->m_dwType == FOX_CMD_FINANCE) { bPacketLog = FALSE; //TRACE3(_T("Power: %d %s %d\r\n"), pPower->m_head.m_wMarket, pPower->m_head.m_szLabel, nCount); //typedef struct //{ // time_t time; // float f[56]; //} ccc; //ccc* c = (ccc*)pBuffBase; //CString str; //str.Format(_T("%s.1"), filename); //ofstream ofs(str.GetBuffer(0), ios::out | ios::binary); //for (int j = 0; j < nCount; j++) //{ // if (c->time == 0xFFFFFFFF) // { // ofs.write(((char*)c)+6, 10); // c++; // continue; // } // ofs.write("\r\n", 5); // for (int i = 0; i < 56; i++) // { // char mmm[200]; // sprintf(mmm, "%f\r\n", c->f[i]); // ofs.write((char*)mmm, strlen(mmm)); // } // ofs.write("---\r\n", 5); // c++; //} //ofs.close(); } else { bPacketLog = TRUE; TRACE3(_T("unkow: %04x %04x %d\r\n"), pFoxHeader->m_dwFlag, pFoxHeader->m_dwType, pFoxHeader->m_nCount); } if (m_bHub) { FOX_SHAREINFO* pInfo = (FOX_SHAREINFO*)m_pMapping; // 接收程序启动 if (pFoxHeader->m_dwFlag == 1) { // 保存接收程序信息 m_foxInfo.dtime = pInfo->dtime; m_foxInfo.dwDriverPid = pInfo->dwDriverPid; m_foxInfo.hDrvierWnd = pInfo->hDrvierWnd; } // 接收程序发来信息,转发到股票软件 if (hWnd == h2) { if (::IsWindow(m_foxInfo.hReceiverWnd)) { ::SendMessage(m_foxInfo.hReceiverWnd, WM_COPYDATA, 0, lParam); } } // 股票软件发来信息,转发到接收程序 if (hWnd == h1) { if (::IsWindow(m_foxInfo.hDrvierWnd)) { ::SendMessage(m_foxInfo.hDrvierWnd, WM_COPYDATA, 0, lParam); } } } if (bPacketLog) { CString str; str.Format(_T("%s.0"), filename); fileLog.Open(str, CFile::modeCreate | CFile::modeReadWrite); fileLog.Write(pData->lpData, pData->cbData); fileLog.Close(); } }
[ [ [ 1, 627 ] ] ]
b7b1cdb48cb482a91dec3cf93b467d78d5eeb6f1
021e8c48a44a56571c07dd9830d8bf86d68507cb
/build/vtk/vtkArrayInterpolate.h
4e1d7236b2440d0bc83555d650dafb59dae11824
[ "BSD-3-Clause" ]
permissive
Electrofire/QdevelopVset
c67ae1b30b0115d5c2045e3ca82199394081b733
f88344d0d89beeec46f5dc72c20c0fdd9ef4c0b5
refs/heads/master
2021-01-18T10:44:01.451029
2011-05-01T23:52:15
2011-05-01T23:52:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,228
h
/*========================================================================= Program: Visualization Toolkit Module: vtkArrayInterpolate.h ------------------------------------------------------------------------- Copyright 2008 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. ------------------------------------------------------------------------- Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #ifndef __vtkArrayInterpolate_h #define __vtkArrayInterpolate_h #include "vtkTypedArray.h" class vtkArrayExtents; class vtkArraySlices; class vtkArrayWeights; // .SECTION Thanks // Developed by Timothy M. Shead ([email protected]) at Sandia National Laboratories. // Description: // Computes the weighted sum of a collection of slices from a source // array, and stores the results in a slice of a target array. Note that // the number of source slices and weights must match, and the extents of // each source slice must match the extents of the target slice. // // Note: The implementation assumes that operator*(T, double) is defined, // and that there is an implicit conversion from its result back to T. // // If you need to interpolate arrays of T other than double, you will // likely want to create your own specialization of this function. // // The implementation should produce correct results for dense and sparse // arrays, but may perform poorly on sparse. template<typename T> void vtkInterpolate( vtkTypedArray<T>* source_array, const vtkArraySlices& source_slices, const vtkArrayWeights& source_weights, const vtkArrayExtents& target_slice, vtkTypedArray<T>* target_array); #include "vtkArrayInterpolate.txx" #endif
[ "ganondorf@ganondorf-VirtualBox.(none)" ]
[ [ [ 1, 60 ] ] ]
324bbb1c50195e85ee4dc397221492d32847e6e9
6253ab92ce2e85b4db9393aa630bde24655bd9b4
/Local Map 2/LocalMap.h
d0f7aa6873dd3924b6f8b163b296936a2f30fafd
[]
no_license
Aand1/cornell-urban-challenge
94fd4df18fd4b6cc6e12d30ed8eed280826d4aed
779daae8703fe68e7c6256932883de32a309a119
refs/heads/master
2021-01-18T11:57:48.267384
2008-10-01T06:43:18
2008-10-01T06:43:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,006
h
#ifndef LOCALMAP_H #define LOCALMAP_H #include "LocalMapConstants.h" #include "LocalMapFunctions.h" #include "LooseCluster.h" #include "MetaMeasurement.h" #include "Particle.h" #include "RadialExistenceGrid.h" #include "RandomNumberCache.h" #include "RandomNumberGenerator.h" #include "Sensor.h" #include "VehicleOdometry.h" #include "..\Common\localMapInterface\localMapInterface.h" #include "OccupancyGrid/OccupancyGridInterface.h" #include <FLOAT.H> #include <MATH.H> #include <STDIO.H> #include <STRING.H> //types of associations (max likelihood, create new target, random, ignore all) #define LM_MAXLIKELIHOOD 1 #define LM_NEWTARGET 2 #define LM_RANDOM 3 #define LM_IGNORE 4 //indicators for birth and clutter associations #define LM_BIRTH -1 #define LM_CLUTTER -99 //maximum number of clusters #define LM_MAXCLUSTERS 500 //the unclusterable cluster tag #define LM_UNCLUSTERED -1 //lengths of character arrays for printing #define LM_LINESIZE 1024 #define LM_FIELDSIZE 128 class LocalMap { private: //the current LocalMap timestamp double mLocalMapTime; //whether the LocalMap has been initialized bool mIsInitialized; //what type of association to perform in this target int mAssociationType; //LOOSE (UNUSED OBSTACLE POINTS) //number of loose (unused) ibeo clusters int mNumLooseIbeoClusters; //the loose ibeo clusters (stored as an array of clusters) LooseCluster mLooseIbeoClusters[LM_MAXCLUSTERS]; //the unclusterable cluster LooseCluster mLooseUnclusterableIbeoPoints; //number of loose (unused) left side SICK clusters int mNumLooseDriverSideSickClusters; //number of loose (unused) right side SICK clusters int mNumLoosePassengerSideSickClusters; //number of loose (unused) clustered SICK clusters //the loose left side SICK clusters (stored as an array of clusters) LooseCluster mLooseDriverSideSickClusters[LM_MAXCLUSTERS]; //the loose right side SICK clusters (stored as an array of clusters) LooseCluster mLoosePassengerSideSickClusters[LM_MAXCLUSTERS]; int mNumLooseClusteredSickClusters; //number of loose (unused) back horizontal SICK clusters LooseCluster mLooseClusteredSickClusters[LM_MAXCLUSTERS]; //the unclusterable cluster LooseCluster mLooseUnclusterableClusteredSickPoints; //the number of particles in the LocalMap int mNumParticles; //the array of particles in the LocalMap Particle* mParticles; //the current most likely particle Particle* mMostLikelyParticle; //the LocalMap random number generator RandomNumberGenerator* mLMGenerator; //the cache of uniform random numbers RandomNumberCache mUniformCache; //TRANSMIT OBJECTS //the timestamp of the forward predicted data for transmit double mTransmitTime; //the particle to transmit Particle* mTransmitParticle; //number of unused obstacle points to transmit int mTransmitNumLoosePoints; //the cluster IDs for the unused obstacle points int* mTransmitLooseIDs; //the heights of each loose point (0 = low obstacle, 1 = high obstacle) int* mTransmitLoosePointHeights; //the loose obstacle points, as {x, y} pairs double* mTransmitLoosePoints; double BirthLikelihood(MetaMeasurement* iMeasurement, Particle* iParticle, Sensor* iSensor, VehicleOdometry* iVehicleOdometry); double ClutterLikelihood(MetaMeasurement* iMeasurement, Particle* iParticle, Sensor* iSensor, VehicleOdometry* iVehicleOdometry); void DeleteLooseIbeoClusters(); void DeleteLooseDriverSideSickClusters(); void DeleteLoosePassengerSideSickClusters(); void DeleteLooseClusteredSickClusters(); double RandUniform() {return mUniformCache.RandomNumber();} void ReplaceUniform() {mUniformCache.ReplaceRandomNumber(mLMGenerator->RandUniform()); return;} void Update(double iMeasurementTime, MetaMeasurement* iMeasurement, Sensor* iSensor, VehicleOdometry* iVehicleOdometry); public: LocalMap(int iNumParticles, RandomNumberGenerator* iRandomNumberGenerator, int iAssociationType = LM_RANDOM); ~LocalMap(); bool IsInitialized() {return mIsInitialized;} double LocalMapTime() {return mLocalMapTime;} Particle* MostLikelyParticle() {return mMostLikelyParticle;} void GenerateTargetsMessage(LocalMapTargetsMsg* oTargetsMessage); void GenerateLooseClustersMessage(LocalMapLooseClustersMsg* oLooseClustersMessage); void Initialize(double iInitialTime); void MaintainTargets(); void Predict(double iPredictTime, VehicleOdometry* iVehicleOdometry); bool PredictForTransmit(double iPredictTime, VehicleOdometry* iVehicleOdometry); void PrintLoosePoints(FILE* iLoosePointsFile); void PrintTargets(FILE* iTargetFile); void Resample(); void UpdateWithClusteredIbeo(double iMeasurementTime, int iNumIbeoPoints, double* iClusteredIbeoBuff, Sensor* iSensor, VehicleOdometry* iVehicleOdometry); void UpdateExistenceWithClusteredIbeo(double iMeasurementTime, int iNumIbeoPoints, double* iClusteredIbeoBuff, Sensor* iClusterSensor, Sensor* iIbeoSensor, VehicleOdometry* iVehicleOdometry); void UpdateExistenceWithVelodyneGrid(double iMeasurementTime, OccupancyGridInterface* iVelodyneGrid, Sensor* iSensor, VehicleOdometry* iVehicleOdometry); void UpdateWithMobileyeObstacles(double iMeasurementTime, int iNumObstacles, double* iMobileyeBuff, Sensor* iSensor, VehicleOdometry* iVehicleOdometry); void UpdateWithRadar(double iMeasurementTime, int iNumObstacles, double* iRadarBuff, Sensor* iSensor, VehicleOdometry* iVehicleOdometry); void UpdateWithSideSick(double iMeasurementTime, int iNumDataRows, double* iSickBuff, bool iIsDriverSide, Sensor* iSensor, VehicleOdometry* iVehicleOdometry); void UpdateWithClusteredSick(double iMeasurementTime, int iNumSickPoints, double* iClusteredSickBuff, Sensor* iSensor, VehicleOdometry* iVehicleOdometry); void UpdateExistenceWithClusteredSick(double iMeasurementTime, int iNumSickPoints, double* iClusteredSickBuff, Sensor* iSensor, VehicleOdometry* iVehicleOdometry); }; #endif //LOCALMAP_H
[ "anathan@5031bdca-8e6f-11dd-8a4e-8714b3728bc5" ]
[ [ [ 1, 141 ] ] ]
d2bac89b9aea5cb2c7134f85c691020269ed0813
cfa667b1f83649600e78ea53363ee71dfb684d81
/code/tests/testhttpviewer/testhttpviewerapplication.cc
97db79b73e89af2d0f00199345255f3b95e3ac53
[]
no_license
zhouxh1023/nebuladevice3
c5f98a9e2c02828d04fb0e1033f4fce4119e1b9f
3a888a7c6e6d1a2c91b7ebd28646054e4c9fc241
refs/heads/master
2021-01-23T08:56:15.823698
2011-08-26T02:22:25
2011-08-26T02:22:25
32,018,644
0
1
null
null
null
null
UTF-8
C++
false
false
10,087
cc
//------------------------------------------------------------------------------ // testhttpviewerapplication.cc // (C) 2009 Radon Labs GmbH //------------------------------------------------------------------------------ #include "stdneb.h" #include "tests/testhttpviewer/testhttpviewerapplication.h" #include "debugrender/debugrender.h" #include "debugrender/debugshaperenderer.h" #include "math/quaternion.h" #include "input/keyboard.h" #include "input/gamepad.h" namespace Tools { using namespace CoreGraphics; using namespace Graphics; using namespace Math; using namespace Util; using namespace Resources; using namespace Timing; using namespace Debug; using namespace Input; //------------------------------------------------------------------------------ /** */ TestHttpViewerApplication::TestHttpViewerApplication() : avgFPS(0.0f), benchmarkmode(false), renderDebug(false) { // empty } //------------------------------------------------------------------------------ /** */ TestHttpViewerApplication::~TestHttpViewerApplication() { if (this->IsOpen()) { this->Close(); } } //------------------------------------------------------------------------------ /** */ bool TestHttpViewerApplication::Open() { n_assert(!this->IsOpen()); if (ViewerApplication::Open()) { // setup lights matrix44 lightTransform = matrix44::rotationx(n_deg2rad(-45.0f)); this->globalLight = GlobalLightEntity::Create(); this->globalLight->SetTransform(lightTransform); this->globalLight->SetColor(float4(0.3, 0.3f, 0.3f, 1.0f)); this->globalLight->SetBackLightColor(float4(0.0f, 0.0f, 0.5f, 1.0f)); this->globalLight->SetAmbientLightColor(float4(0.1f, 0.1f, 0.1f, 1.0f)); this->globalLight->SetCastShadows(false); this->stage->AttachEntity(this->globalLight.cast<GraphicsEntity>()); // create a few point lights /* IndexT lightIndex; const SizeT numLights = 4; for (lightIndex = 0; lightIndex < numLights; lightIndex++) { float x = n_rand() * 40.0f - 20.0f; float y = 3; float z = n_rand() * 40.0f - 20.0f; float r = n_rand() * 2.0f; float g = n_rand() * 2.0f; float b = n_rand() * 2.0f; matrix44 pointLightTransform = matrix44::multiply(matrix44::scaling(10.0f, 10.0f, 10.0f), matrix44::translation(x, y, z)); Ptr<PointLightEntity> pointLight = PointLightEntity::Create(); pointLight->SetTransform(pointLightTransform); pointLight->SetColor(float4(r, g, b, 1.0f)); pointLight->SetCastShadows(false); this->localLights.Append(pointLight); this->lightTransforms.Append(pointLightTransform); this->stage->AttachEntity(pointLight.cast<GraphicsEntity>()); } */ // setup models this->ground = ModelEntity::Create(); this->ground->SetResourceId(ResourceId("mdl:examples/dummyground.n3")); this->ground->SetTransform(matrix44::translation(0.0f, 0.0f, 0.0f)); this->stage->AttachEntity(ground.cast<GraphicsEntity>()); IndexT j; bool createStatic = true; for (j = -1; j < 2; ++j) { IndexT i; for (i = -1; i < 2; ++i) { Ptr<ModelEntity> model = ModelEntity::Create(); model->SetTransform(matrix44::translation(7.0f * i, 0.0, 7.0f * j - 5)); if (createStatic) { model->SetResourceId(ResourceId("mdl:examples/tiger.n3")); this->stage->AttachEntity(model.cast<GraphicsEntity>()); } else { model->SetResourceId(ResourceId("mdl:characters/mensch_m.n3")); this->stage->AttachEntity(model.cast<GraphicsEntity>()); // apply skin Ptr<Graphics::ApplySkinList> skinList = Graphics::ApplySkinList::Create(); skinList->SetSkinList(StringAtom("mann_nackt")); model->SendMsg(skinList.cast<GraphicsEntityMessage>()); // play animation Ptr<Graphics::AnimPlayClip> playClip = Graphics::AnimPlayClip::Create(); playClip->SetClipName("gehen_01"); playClip->SetTrackIndex(0); playClip->SetLoopCount(0.0f); model->SendMsg(playClip.cast<GraphicsEntityMessage>()); } this->models.Append(model); createStatic = !createStatic; } } // wait for resources to be loaded // GraphicsInterface::Instance()->WaitForPendingResources(); return true; } return false; } //------------------------------------------------------------------------------ /** */ void TestHttpViewerApplication::Close() { this->stage->RemoveEntity(this->globalLight.cast<GraphicsEntity>()); this->stage->RemoveEntity(this->ground.cast<GraphicsEntity>()); this->globalLight = 0; this->ground = 0; IndexT i; for (i = 0; i < this->localLights.Size(); i++) { this->stage->RemoveEntity(this->localLights[i].cast<GraphicsEntity>()); } this->localLights.Clear(); for (i = 0; i < this->models.Size(); i++) { this->stage->RemoveEntity(this->models[i].cast<GraphicsEntity>()); } this->models.Clear(); ViewerApplication::Close(); } //------------------------------------------------------------------------------ /** */ void TestHttpViewerApplication::OnConfigureDisplay() { ViewerApplication::OnConfigureDisplay(); this->display->Settings().DisplayMode() = CoreGraphics::DisplayMode(640, 480, CoreGraphics::PixelFormat::X8R8G8B8); this->display->Settings().SetVerticalSyncEnabled(true); } //------------------------------------------------------------------------------ /** */ void TestHttpViewerApplication::OnProcessInput() { const Ptr<Keyboard>& kbd = InputServer::Instance()->GetDefaultKeyboard(); // enable/disable debug view if (kbd->KeyDown(Key::F4)) { // turn on debug rendering Ptr<Debug::RenderDebugView> renderDebugMsg = Debug::RenderDebugView::Create(); renderDebugMsg->SetThreadId(Threading::Thread::GetMyThreadId()); renderDebugMsg->SetEnableDebugRendering(!this->renderDebug); Graphics::GraphicsInterface::Instance()->SendBatched(renderDebugMsg.cast<Messaging::Message>()); this->renderDebug = !this->renderDebug; } else if (kbd->KeyDown(Key::F3)) { this->benchmarkmode = !this->benchmarkmode; // reset to start pos this->mayaCameraUtil.Reset(); } if (this->benchmarkmode) { // auto rotate this->mayaCameraUtil.SetOrbiting(Math::float2(0.02,0)); this->mayaCameraUtil.SetOrbitButton(true); this->mayaCameraUtil.Update(); this->camera->SetTransform(this->mayaCameraUtil.GetCameraTransform()); } else { ViewerApplication::OnProcessInput(); } } //------------------------------------------------------------------------------ /** */ void TestHttpViewerApplication::OnUpdateFrame() { // test text rendering Timing::Time frameTime = (float)this->GetFrameTime(); Util::String fpsTxt; fpsTxt.Format("Game FPS: %.2f", 1/frameTime); _debug_text(fpsTxt, Math::float2(0.0,0.0), Math::float4(1,1,1,1)); _debug_text("Toggle Benchmark with F3!", Math::float2(0.0,0.025), Math::float4(1,1,1,1)); if (this->benchmarkmode) { // benchmark with avg frames for every 100 frames if (this->frameTimes.Size() > 0 || frameTime < 0.08) { this->frameTimes.Append(frameTime); } if (this->frameTimes.Size() > 0 && this->frameTimes.Size() % 50 == 0) { this->avgFPS = 0; IndexT i; for (i = 0; i < this->frameTimes.Size(); ++i) { this->avgFPS += this->frameTimes[i]; } this->avgFPS /= this->frameTimes.Size(); } if (this->avgFPS > 0) { fpsTxt.Format("Benchmarking: Avg Game FPS: %.2f", 1/this->avgFPS); } else { fpsTxt = "Benchmarking: Wait for measuring average framerate"; } _debug_text(fpsTxt, Math::float2(0.0,0.05f), Math::float4(1,1,1,1)); } float time = (float) this->GetTime(); IndexT i; for (i = 0; i < this->localLights.Size(); i++) { matrix44 m = this->lightTransforms[i]; float4 t(5 * n_sin(0.1f * i * time), 0.0f, 5 * n_sin(0.05f * i * time), 0.0f); m.translate(t); this->localLights[i]->SetTransform(m); } // render a few debug shapes /*IndexT x; for (x = 0; x < 10; x++) { IndexT y; for (y = 0; y < 10; y++) { quaternion rot = quaternion::rotationyawpitchroll(0.0f, curTime, 0.0f); matrix44 m = matrix44::affinetransformation(1.0f, vector::nullvec(), rot, point(x * 2.0f, 1.0f, y * 2.0f)); DebugShapeRenderer::Instance()->DrawBox(m, float4(1.0f, 0.0f, 0.0f, 0.5f)); } }*/ ViewerApplication::OnUpdateFrame(); } } // namespace Tools
[ [ [ 1, 283 ] ] ]
f3a84628e7e858ee57b0b1c711ab9985f0610255
a699a508742a0fd3c07901ab690cdeba2544a5d1
/RailwayDetection/RWDSClient/Schedule.cpp
e0836592e6bae34d95b172567117b9f378dd0057
[]
no_license
xiaomailong/railway-detection
2bf92126bceaa9aebd193b570ca6cd5556faef5b
62e998f5de86ee2b6282ea71b592bc55ee25fe14
refs/heads/master
2021-01-17T06:04:48.782266
2011-09-27T15:13:55
2011-09-27T15:13:55
42,157,845
0
1
null
2015-09-09T05:24:10
2015-09-09T05:24:09
null
GB18030
C++
false
false
14,251
cpp
// Schedule.cpp : 实现文件 // #include "stdafx.h" #include "RWDSClient.h" #include "Schedule.h" #include "afxdialogex.h" #include "DataService.h" #include "CmdDefine.h" // CSchedule 对话框 IMPLEMENT_DYNAMIC(CSchedule, CDialogEx) CSchedule::CSchedule(CWnd* pParent) : CDialogEx(CSchedule::IDD, pParent) { m_CRWDSClientView = static_cast<CRWDSClientView*>(pParent); m_StaffChanged = FALSE; //m_TimeChanged = FALSE; } CSchedule::~CSchedule() { } void CSchedule::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_SCHEDULELIST, m_ListCtrl); DDX_Control(pDX, IDC_LISTARRIVETTIME, m_ListArriveTime); DDX_Control(pDX, IDC_COMBO_STARTDAY, m_ComboStartDay); DDX_Control(pDX, IDC_LIST_SELECTEDSTAFF, m_ListStaffSelected); DDX_Control(pDX, IDC_LIST_UNSELECTSTAFF, m_ListStaffUnselected); } BEGIN_MESSAGE_MAP(CSchedule, CDialogEx) ON_NOTIFY(LVN_ITEMCHANGED, IDC_SCHEDULELIST, &CSchedule::OnLvnItemchangedSchedulelist) ON_NOTIFY(LVN_ITEMCHANGED, IDC_LISTARRIVETTIME, &CSchedule::OnLvnItemchangedListarrivettime) ON_BN_CLICKED(IDC_BTN_MODIFYTIME, &CSchedule::OnBnClickedBtnModifytime) ON_BN_CLICKED(IDC_BTN_MODIFYCALENDER, &CSchedule::OnBnClickedBtnModifycalender) //ON_BN_CLICKED(IDC_BTN_CLEANSTAFF, &CSchedule::OnBnClickedBtnCleanstaff) ON_BN_CLICKED(IDC_BTN_ADDLISTSTAFF, &CSchedule::OnBnClickedBtnAddliststaff) ON_BN_CLICKED(IDC_BTN_REMOVELISTSTAFF, &CSchedule::OnBnClickedBtnRemoveliststaff) ON_BN_CLICKED(IDC_BTN_CANCEL, &CSchedule::OnBnClickedBtnCancel) ON_BN_CLICKED(IDC_BTN_SAVE, &CSchedule::OnBnClickedBtnSave) END_MESSAGE_MAP() // CSchedule 消息处理程序 BOOL CSchedule::OnInitDialog() { CDialogEx::OnInitDialog(); // TODO: 在此添加额外的初始化 m_ListCtrl.SetExtendedStyle(LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES); m_ListArriveTime.SetExtendedStyle(LVS_EX_FULLROWSELECT|LVS_EX_GRIDLINES); CRect clientRect; m_ListCtrl.GetClientRect(&clientRect); while(m_ListCtrl.DeleteColumn(0)); m_ListCtrl.InsertColumn(0, _T("编号"), LVCFMT_LEFT, clientRect.Width()/4); m_ListCtrl.InsertColumn(1, _T("线路名"), LVCFMT_LEFT, clientRect.Width()/4); m_ListCtrl.InsertColumn(2, _T("开始时间"), LVCFMT_LEFT, clientRect.Width()/4); m_ListCtrl.InsertColumn(3, _T("结束时间"), LVCFMT_LEFT, clientRect.Width()/4); m_ListArriveTime.GetClientRect(&clientRect); while(m_ListArriveTime.DeleteColumn(0)); m_ListArriveTime.InsertColumn(0, _T("公里处"), LVCFMT_LEFT, clientRect.Width()*3/5); m_ListArriveTime.InsertColumn(1, _T("到达时间"), LVCFMT_LEFT, clientRect.Width()*2/5); CString id; CString schName; CString lineName; CString dev; CString wk; CString beTime; CString endTime; LineInfo* line = NULL; int count = m_CRWDSClientView->m_CurrentOrg->iLine.size(); for (int i=0; i<count; i++) { line = m_CRWDSClientView->m_CurrentOrg->iLine[i]; id.Format(_T("%d"), line->iLineID); lineName = line->iLineName; if(line->iLineKmTime.size()>0) { CTime tb(line->iLineKmTime[0]); CTime te(line->iLineKmTime[line->iLineKmTime.size()-1]); beTime.Format(_T("%02d:%02d"), tb.GetHour(), tb.GetMinute()); endTime.Format(_T("%02d:%02d"), te.GetHour(), te.GetMinute()); } else { beTime = _T(""); endTime = _T(""); } m_ListCtrl.InsertItem(i, id); m_ListCtrl.SetItemText(i, 1, lineName); m_ListCtrl.SetItemText(i, 2, beTime); m_ListCtrl.SetItemText(i, 3, endTime); } //初始化日程信息 m_ComboStartDay.ResetContent(); for (int i=0; i<strStartNoCount; i++) { m_ComboStartDay.AddString(strStartNo[i]); } CTime startTime(m_CRWDSClientView->m_CurrentOrg->iCalendar->iStartDay); int i = startTime.GetMonth(); int ii = startTime.GetDay(); ((CDateTimeCtrl*)GetDlgItem(IDC_DATETIMEPICKER_STARTDAY))->SetTime(&startTime); AddStaffToListBox(); GetDlgItem(IDC_EDIT_SCHEDULEREMARK)->SetWindowText(m_CRWDSClientView->m_CurrentOrg->iCalendar->iScheduleRemark); return TRUE; // return TRUE unless you set the focus to a control // 异常: OCX 属性页应返回 FALSE } void CSchedule::AddStaffToListBox() {//加载排班员工至listbox StaffInfo* staffSeleted; StaffInfo* staffUnseleted; for (size_t i=0; i<m_CRWDSClientView->m_CurrentOrg->iCalendar->iScheduleStaff.size(); i++) { staffSeleted = m_CRWDSClientView->m_CurrentOrg->iCalendar->iScheduleStaff[i]; m_StaffSeleted.push_back(staffSeleted); m_ListStaffSelected.AddString(staffSeleted->iName); } BOOL addStaff = TRUE; for (size_t i=0; i<m_CRWDSClientView->m_CurrentOrg->iStaff.size(); i++) { addStaff = TRUE; staffUnseleted = m_CRWDSClientView->m_CurrentOrg->iStaff[i]; for (size_t j=0; j<m_CRWDSClientView->m_CurrentOrg->iCalendar->iScheduleStaff.size(); j++) {//添加已选员工 staffSeleted = m_CRWDSClientView->m_CurrentOrg->iCalendar->iScheduleStaff[j]; if (staffSeleted == staffUnseleted) {//该员工已选择该线路 addStaff = FALSE; break; } } if (addStaff) { m_StaffUnseleted.push_back(staffUnseleted); m_ListStaffUnselected.AddString(staffUnseleted->iName); } } } void CSchedule::OnLvnItemchangedSchedulelist(NMHDR *pNMHDR, LRESULT *pResult) { LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR); // TODO: 在此添加控件通知处理程序代码 POSITION pos; pos = m_ListCtrl.GetFirstSelectedItemPosition(); int select = m_ListCtrl.GetNextSelectedItem(pos); if (select<0) { return; } LineInfo* line = m_CRWDSClientView->m_CurrentOrg->iLine[select]; CString km; CString at; m_ListArriveTime.DeleteAllItems(); for (size_t i=0; i<line->iLineKmLonLat.size(); i++) { ENCODERAILWAYFULLNAME(km, line->iLineKmLonLat[i]->iRailLine->iRailName, line->iLineKmLonLat[i]->iKM, line->iLineKmLonLat[i]->iDirect); if (i < line->iLineKmTime.size()) { CTime t1(line->iLineKmTime[i]); at.Format(_T("%02d:%02d"), t1.GetHour(), t1.GetMinute()); } else { at = _T("00:00"); } m_ListArriveTime.InsertItem(i, km); m_ListArriveTime.SetItemText(i, 1, at); } m_SelectedLine = line; //处理日程表 CTime startTime(m_CRWDSClientView->m_CurrentOrg->iCalendar->iStartDay); ((CDateTimeCtrl*)GetDlgItem(IDC_DATETIMEPICKER_STARTDAY))->SetTime(&startTime); CString str; str.Format(_T("%d"), m_CRWDSClientView->m_CurrentOrg->iCalendar->iPeriods); GetDlgItem(IDC_EDIT_PERIODS)->SetWindowText(str); //按周期显示天数 m_ComboStartDay.ResetContent(); for (int i=0; i<strStartNoCount; i++) { m_ComboStartDay.AddString(strStartNo[i]); } int curSel = static_cast<int>(line->iStartNo); if (line->iStartNo >= m_ComboStartDay.GetCount()) { curSel = -1; } m_ComboStartDay.SetCurSel(curSel); *pResult = 0; } void CSchedule::OnLvnItemchangedListarrivettime(NMHDR *pNMHDR, LRESULT *pResult) { LPNMLISTVIEW pNMLV = reinterpret_cast<LPNMLISTVIEW>(pNMHDR); // TODO: 在此添加控件通知处理程序代码 POSITION pos; pos = m_ListArriveTime.GetFirstSelectedItemPosition(); int select = m_ListArriveTime.GetNextSelectedItem(pos); if (select<0) { return; } CTime t1(m_SelectedLine->iLineKmTime[select]); CString str; str.Format(_T("%02d"), t1.GetHour()); GetDlgItem(IDC_EDIT_HOUR)->SetWindowText(str); str.Format(_T("%02d"), t1.GetMinute()); GetDlgItem(IDC_EDIT_MINUTE)->SetWindowText(str); *pResult = 0; } void CSchedule::OnBnClickedBtnModifytime() { // TODO: 在此添加控件通知处理程序代码 POSITION pos; pos = m_ListArriveTime.GetFirstSelectedItemPosition(); int select = m_ListArriveTime.GetNextSelectedItem(pos); if (select<0) { return; } //CTime t1(m_SelectedSchedule->iULineKmTime[select]); CString strHour; CString strMin; struct tm schTime; localtime_s(&schTime, &m_SelectedLine->iLineKmTime[select]); GetDlgItem(IDC_EDIT_HOUR)->GetWindowText(strHour); schTime.tm_hour = _ttoi(strHour); GetDlgItem(IDC_EDIT_MINUTE)->GetWindowText(strMin); schTime.tm_min = _ttoi(strMin); m_SelectedLine->iLineKmTime[select] = mktime(&schTime); AfxMessageBox(_T("修改成功")); CString str; str.Format(_T("%02d:%02d"), schTime.tm_hour, schTime.tm_min); m_ListArriveTime.SetItemText(select, 1, str); POSITION posCtrl; posCtrl = m_ListCtrl.GetFirstSelectedItemPosition(); int ctrlIndex = m_ListCtrl.GetNextSelectedItem(posCtrl); if (ctrlIndex < 0) { return; } if (select == 0) { m_ListCtrl.SetItemText(ctrlIndex, 2, str); } else if (select == m_ListArriveTime.GetItemCount()-1) { m_ListCtrl.SetItemText(ctrlIndex, 3, str); } //保存修改过到达时间 BOOL pushback = TRUE; for (size_t i=0; i<m_ModifyLineArrvieTime.size(); i++) { if (m_SelectedLine == m_ModifyLineArrvieTime[i]) {//该线路已经修改过 pushback = FALSE; break; } } if (pushback) { m_ModifyLineArrvieTime.push_back(m_SelectedLine); //m_ModifyArrvieTime = TRUE; } //m_TimeChanged = TRUE; } void CSchedule::OnBnClickedBtnModifycalender() { // TODO: 在此添加控件通知处理程序代码 CTime startTime; CString str; GetDlgItem(IDC_EDIT_PERIODS)->GetWindowText(str); int periods = _ttoi(str); if (periods<1) { AfxMessageBox(_T("排班周期必须要大于或者等于1")); return; } if (m_ComboStartDay.GetCurSel() < 0) { AfxMessageBox(_T("请选择开始日期")); return; } //排班开始时间 CalendarSchedule schedule; schedule.iPeriods = _ttoi(str); ((CDateTimeCtrl*)GetDlgItem(IDC_DATETIMEPICKER_STARTDAY))->GetTime(startTime); schedule.iStartDay = startTime.GetTime(); //m_ComboStartDay.ResetContent(); //for (int i=0; i<m_CRWDSClientView->m_CurrentOrg->iCalendar->iPeriods && i<StrStartNoCount; i++) //{ // m_ComboStartDay.AddString(StrStartNo[i]); //} //if (m_SelectedLine->iStartNo >= m_ComboStartDay.GetCount()) //{ // m_SelectedLine->iStartNo = KUndefine; //} //m_ComboStartDay.SetCurSel(m_SelectedLine->iStartNo); GetDlgItem(IDC_EDIT_SCHEDULEREMARK)->GetWindowText(schedule.iScheduleRemark); if (schedule.iPeriods != m_CRWDSClientView->m_CurrentOrg->iCalendar->iPeriods || schedule.iStartDay != m_CRWDSClientView->m_CurrentOrg->iCalendar->iStartDay || schedule.iScheduleRemark != m_CRWDSClientView->m_CurrentOrg->iCalendar->iScheduleRemark) {//传排班表 m_CRWDSClientView->m_CurrentOrg->iCalendar->iPeriods = schedule.iPeriods; m_CRWDSClientView->m_CurrentOrg->iCalendar->iStartDay = schedule.iStartDay; m_CRWDSClientView->m_CurrentOrg->iCalendar->iScheduleRemark = schedule.iScheduleRemark; SetCalendarSchedule(m_CRWDSClientView->m_CurrentOrg->iOrgID, m_CRWDSClientView->m_CurrentOrg->iCalendar); m_StaffChanged = FALSE;//数据已经上传,无需再次上次人员信息 } if (m_StaffChanged) { SetCalendarSchedule(m_CRWDSClientView->m_CurrentOrg->iOrgID, m_CRWDSClientView->m_CurrentOrg->iCalendar); m_StaffChanged = FALSE; } LineStartNo preNo = m_SelectedLine->iStartNo; LineStartNo startNo = static_cast<LineStartNo>(m_ComboStartDay.GetCurSel()); if (preNo != startNo) {//修改线路的开始时间 m_SelectedLine->iStartNo = startNo; SetOrgLine(m_CRWDSClientView->m_CurrentOrg->iOrgID, CMD_LINE_MODIFY, m_SelectedLine); } for( size_t i=0; i<m_ModifyLineArrvieTime.size(); i++) {//保存线路的时间 SetOrgLine(m_CRWDSClientView->m_CurrentOrg->iOrgID, CMD_LINE_MODIFY, m_ModifyLineArrvieTime[i]); } m_ModifyLineArrvieTime.clear(); AfxMessageBox(_T("修改成功")); } void CSchedule::OnBnClickedBtnAddliststaff() { // TODO: 在此添加控件通知处理程序代码 int curStaffIndex = m_ListStaffUnselected.GetCurSel(); if (curStaffIndex<0) { return; } StaffInfo* curStaff = m_StaffUnseleted[curStaffIndex]; //把员工添加到当前选择的路线 //m_SelectedLine->iArrangeStaff.push_back(curStaff); m_CRWDSClientView->m_CurrentOrg->iCalendar->iScheduleStaff.push_back(curStaff); //更改状态 m_ListStaffUnselected.DeleteString(curStaffIndex); m_ListStaffSelected.AddString(curStaff->iName); m_StaffUnseleted.erase(m_StaffUnseleted.begin()+curStaffIndex); m_StaffSeleted.push_back(curStaff); m_StaffChanged = TRUE; //curStaff->iArrangeLine.push_back(m_SelectedLine); } void CSchedule::OnBnClickedBtnRemoveliststaff() { // TODO: 在此添加控件通知处理程序代码 int curStaffIndex = m_ListStaffSelected.GetCurSel(); if (curStaffIndex<0) { return; } StaffInfo* curStaff = m_StaffSeleted[curStaffIndex]; //把员工移除排班表 m_CRWDSClientView->m_CurrentOrg->iCalendar->iScheduleStaff.erase( m_CRWDSClientView->m_CurrentOrg->iCalendar->iScheduleStaff.begin()+curStaffIndex); //更改状态 m_ListStaffSelected.DeleteString(curStaffIndex); m_ListStaffUnselected.AddString(curStaff->iName); m_StaffSeleted.erase(m_StaffSeleted.begin()+curStaffIndex); m_StaffUnseleted.push_back(curStaff); m_StaffChanged = TRUE; //for (size_t i=0; i<curStaff->iArrangeLine.size(); i++) //{ // if (m_SelectedLine == curStaff->iArrangeLine[i]) // { // curStaff->iArrangeLine.erase(curStaff->iArrangeLine.begin()+i); // break; // } //} } void CSchedule::OnBnClickedBtnCancel() { // TODO: 在此添加控件通知处理程序代码 OnCancel(); } void CSchedule::OnBnClickedBtnSave() { // TODO: 在此添加控件通知处理程序代码 for( size_t i=0; i<m_ModifyLineArrvieTime.size(); i++) { SetOrgLine(m_CRWDSClientView->m_CurrentOrg->iOrgID, CMD_LINE_MODIFY, m_ModifyLineArrvieTime[i]); } m_ModifyLineArrvieTime.clear(); }
[ "[email protected]@4d6b9eea-9d24-033f-dd66-d003eccfd9d3", "[email protected]@4d6b9eea-9d24-033f-dd66-d003eccfd9d3" ]
[ [ [ 1, 8 ], [ 10, 46 ], [ 49, 123 ], [ 125, 280 ], [ 287, 287 ], [ 297, 297 ], [ 299, 422 ] ], [ [ 9, 9 ], [ 47, 48 ], [ 124, 124 ], [ 281, 286 ], [ 288, 296 ], [ 298, 298 ], [ 423, 440 ] ] ]
991f29ccd9586527de52ca11db00cf359611048c
2f77d5232a073a28266f5a5aa614160acba05ce6
/01.DevelopLibrary/03.Code/UI/SmsPassInputWnd.h
698a18058f4bc2b29b826e5dee3a22bcb57858b9
[]
no_license
radtek/mobilelzz
87f2d0b53f7fd414e62c8b2d960e87ae359c81b4
402276f7c225dd0b0fae825013b29d0244114e7d
refs/heads/master
2020-12-24T21:21:30.860184
2011-03-26T02:19:47
2011-03-26T02:19:47
58,142,323
0
0
null
null
null
null
UTF-8
C++
false
false
741
h
#ifndef __SMSPASSINPUTWND_h__ #define __SMSPASSINPUTWND_h__ #include "UiEditControl.h" #include "NewSmsWnd.h" #include "EasySmsUiCtrl.h" #include "EasySmsWndBase.h" class CSmsPassInputWnd : public CEasySmsWndBase { MZ_DECLARE_DYNAMIC( CSmsPassInputWnd ); public: CSmsPassInputWnd(void); virtual ~CSmsPassInputWnd(void); public: virtual BOOL OnInitDialog(); virtual void OnMzCommand( WPARAM wParam, LPARAM lParam ); BOOL SubInitialize(); private: protected: private: UiSingleLineEdit m_PassInput; UiSingleLineEdit m_PassInput_Again; UiPicture m_Picture; int m_modeIndex; CEasySmsUiCtrl m_clCEasySmsUiCtrl; }; #endif
[ [ [ 1, 48 ] ] ]
945562eab8b336d578e3529a2f4ffe6fd5c08664
160e08f968425ae7b8e83f7381c617906b4e9f18
/TimeServices.Engine.AtiStreams/Core/CalModule.cpp
0144ce807d52cdf0629e5c222b24d708f443e417
[]
no_license
m3skine/timeservices
0f6a938a25a49a0cad884e2ae9fb1fff4a8a08fe
1efca945a2121cd7f45c05387503ea8ef66541e6
refs/heads/master
2020-04-10T20:06:24.326180
2010-04-21T01:12:44
2010-04-21T01:12:44
33,272,683
0
0
null
null
null
null
UTF-8
C++
false
false
1,880
cpp
#include "calcl.h" #include "CalContext.h" #include "CalModule.h" #include <stdio.h> #include <string> namespace TimeServices { namespace Engine { namespace Core { static void __logger(const CALchar *text) { fprintf(stderr, text); } bool CalModule::Initialize(const CALchar* ilKernel, bool disassemble) { CALimage image = NULL; CALboolean success = CAL_FALSE; // Get device specific information CALdeviceattribs attribs; if (!_context->GetAttributes(attribs)) return false; // Compile IL kernel into object CALobject obj; if (calclCompile(&obj, CAL_LANGUAGE_IL, ilKernel, attribs.target) != CAL_RESULT_OK) { fprintf(stderr, "There was an error compiling the program.\n"); fprintf(stderr, "Error string is %s\n", calclGetErrorString()); return false; } // Link object into an image if (calclLink(&image, &obj, 1) != CAL_RESULT_OK) { fprintf(stderr, "There was an error linking the program.\n"); fprintf(stderr, "Error string is %s\n", calclGetErrorString()); return false; } if (calclFreeObject(obj) != CAL_RESULT_OK) { fprintf(stderr, "There was an error freeing the compiler object.\n"); fprintf(stderr, "Error string: %s\n", calclGetErrorString()); return false; } if (disassemble == true) calclDisassembleImage(image, __logger); // Load module into the context if (calModuleLoad(&_module, _context->GetApiContext(), image) != CAL_RESULT_OK) { fprintf(stderr, "There was an error loading the program module.\n"); fprintf(stderr, "Error string is %s\n", calGetErrorString()); return false; } if (calclFreeImage(image) != CAL_RESULT_OK) { fprintf(stderr, "There was an error freeing the program image.\n"); fprintf(stderr, "Error string is %s\n", calGetErrorString()); return false; } return true; } }}}
[ "Moreys@localhost" ]
[ [ [ 1, 62 ] ] ]
cc6e373a211e3ff9d78ec5f4283693a705b7c6cc
9267674a05b4561b921413a711e9dbd6193b936a
/include/players/beardface.h
38769c5e4e2ba1ae48bc72b3c7d5b9612aebd434
[]
no_license
scognito/puppetfigher
249564d09eab07f75444dde60fb0f10f6deba2c0
ddf34730304e66dbe8de2d5cd12a5e61f7aded36
refs/heads/master
2021-01-16T23:06:38.792594
2009-09-25T19:56:03
2009-09-25T19:56:03
32,251,497
0
0
null
null
null
null
UTF-8
C++
false
false
266
h
#ifndef _Beardface_H_ #define _Beardface_H_ #include "player.h" class Beardface : public Player { public: Beardface(float x, float y, b2World* w); ~Beardface(); private: void InitArmor(); void InitWeapon(); }; #endif //_Beardface_H_
[ "justin.hawkins@6d35b48c-a465-11de-bea2-1db044c32224" ]
[ [ [ 1, 17 ] ] ]
594bc44bb89d1f131e04ed55736203aacc24f4a4
9b781f66110d82c4918feffeeee3740d6b9dcc73
/Motion Graphs/Edge.cpp
173cfa9a4a93d131aead7cc238ec6efb2b21a49f
[]
no_license
vanish87/Motion-Graphs
3c41cbb4ae838e2dce1172a56dfa00b8fe8f12cf
6eab48f3625747d838f2f8221705a1dba154d8ca
refs/heads/master
2021-01-23T05:34:56.297154
2011-06-10T09:53:15
2011-06-10T09:53:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
576
cpp
#include "stdafx.h" #include "Edge.h" /* * Contructors and Destructors */ Edge::Edge(){ this->dest = NULL; } Edge::Edge(gNode *d, std::string label){ this->dest = d; this->label = label; } /*Edge::Edge(gNode *d, Ninja *n,bool transition, Motion *m1, Motion *m2, int init1, int init2, int end1, int end2){ this->dest = d; this->ninja = n; this->transition = transition; this->m1 = m1; this->m2 = m2; this->init1 = init1; this->init2 = init2; this->end1 = end1; this->end2 = end2; }*/ Edge::~Edge(){ } /* * Methods */
[ "onumis@6a9b4378-2129-4827-95b0-0a0a1e71ef92", "mariojgpinto@6a9b4378-2129-4827-95b0-0a0a1e71ef92" ]
[ [ [ 1, 1 ] ], [ [ 2, 36 ] ] ]
cf5379bf74b3539c39a81e7d7d7a606516002361
11ba7667109ae553162c7329bcd2f4902d841a66
/AugmentedTowerDefense/src/OgreApp.cpp
5941eae24b2767ed95b9e16ba9cb510004dca3f8
[]
no_license
abmantis/AugmentedTowerDefense
3cd8761034a98667a34650f6a476beb59aa7e818
00008495f538e0d982c0eae3025d02ae21e3dee2
refs/heads/master
2021-01-01T18:37:10.678181
2011-02-09T23:09:51
2011-02-09T23:09:51
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,010
cpp
#include "StdAfx.h" #include "OgreApp.h" #include "AppLogic.h" #include "OgreAppFrameListener.h" OgreApp *Ogre::Singleton<class OgreApp>::ms_Singleton = 0; OgreApp::OgreApp() { mInitialisationBegun = false; mInitialisationComplete = false; // Ogre mRoot = 0; mFrameListener = 0; mWindow = 0; // framework mAppLogic = 0; // OIS mInputMgr = 0; mKeyboard = 0; mMouse = 0; } OgreApp::~OgreApp() { shutdown(); } //////////////////////////////////////////////// bool OgreApp::init(void) { try { assert(!mInitialisationBegun); mInitialisationBegun = true; if(!mAppLogic) return false; if(!mAppLogic->preInit(mCommandLineArgs)) return false; mRoot = new Ogre::Root("plugins.cfg", "ogre.cfg", "Ogre.log"); if(!mRoot->restoreConfig() && !mRoot->showConfigDialog()) return false; mWindow = mRoot->initialise(true); createInputDevices(false); setupResources(); mFrameListener = new OgreAppFrameListener(this); mRoot->addFrameListener(mFrameListener); if(!mAppLogic->init()) return false; mInitialisationComplete = true; } catch (Ogre::Exception& e) { MessageBox(NULL, e.getFullDescription().c_str(), "An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL); return false; } return true; } void OgreApp::run(void) { if(init()) mRoot->startRendering(); shutdown(); } bool OgreApp::preUpdate( Ogre::Real deltaTime ) { return mAppLogic->preUpdate(deltaTime); } bool OgreApp::update(Ogre::Real deltaTime) { updateInputDevices(); return mAppLogic->update(deltaTime); } void OgreApp::shutdown(void) { if(!mInitialisationBegun) return; if(mInitialisationComplete) mAppLogic->shutdown(); destroyInputDevices(); delete mFrameListener; mFrameListener = 0; delete mRoot; mRoot = 0; if(mAppLogic) mAppLogic->postShutdown(); mInitialisationComplete = false; mInitialisationBegun = false; } //////////////////////////////////////////////// void OgreApp::setAppLogic(AppLogic *appLogic) { if(mAppLogic == appLogic) return; if(mAppLogic) { mAppLogic->setParentApp(0); } mAppLogic = appLogic; if(appLogic) { appLogic->setParentApp(this); } } void OgreApp::setCommandLine(const Ogre::String &commandLine) { Ogre::String configFile; mCommandLine = commandLine; if(!commandLine.empty()) { // splits command line in a vector without spliting text between quotes Ogre::StringVector quoteSplit = Ogre::StringUtil::split(commandLine, "\""); // if the first char was a quote, split() ignored it. if(commandLine[0] == '\"') quoteSplit.insert(quoteSplit.begin(), " "); // insert a space in the list to reflect the presence of the first quote // insert a space instead of an empty string because the next split() will ingore the space but not the empty string // split(" ")->{} / split("")->{""} for(unsigned int i = 0; i < quoteSplit.size(); i++) { if(i&1) // odd elements : between quotes { mCommandLineArgs.push_back(quoteSplit[i]); } else // even elements : outside quotes { Ogre::StringVector spaceSplit = Ogre::StringUtil::split(quoteSplit[i]); mCommandLineArgs.insert(mCommandLineArgs.end(), spaceSplit.begin(), spaceSplit.end()); } } } } //////////////////////////////////////////////// void OgreApp::notifyWindowMetrics(Ogre::RenderWindow* rw, int left, int top, int width, int height) { if(mMouse) { const OIS::MouseState &ms = mMouse->getMouseState(); ms.height = height; // mutable fields ms.width = width; } } void OgreApp::notifyWindowClosed(Ogre::RenderWindow* rw) { destroyInputDevices(); } //////////////////////////////////////////////// /// Method which will define the source of resources (other than current folder) void OgreApp::setupResources(void) { // Load resource paths from config file Ogre::ConfigFile cf; cf.load("resources.cfg"); // Go through all sections & settings in the file Ogre::ConfigFile::SectionIterator seci = cf.getSectionIterator(); Ogre::String secName, typeName, archName; while (seci.hasMoreElements()) { secName = seci.peekNextKey(); Ogre::ConfigFile::SettingsMultiMap *settings = seci.getNext(); Ogre::ConfigFile::SettingsMultiMap::const_iterator i; for (i = settings->begin(); i != settings->end(); ++i) { typeName = i->first; archName = i->second; Ogre::ResourceGroupManager::getSingleton().addResourceLocation( archName, typeName, secName); } } Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups(); } //////////////////////////////////////////////// void OgreApp::createInputDevices(bool exclusive) { OIS::ParamList pl; size_t winHandle = 0; mWindow->getCustomAttribute("WINDOW", &winHandle); pl.insert(std::make_pair("WINDOW", Ogre::StringConverter::toString(winHandle))); if(!exclusive) { pl.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_FOREGROUND" ))); pl.insert(std::make_pair(std::string("w32_mouse"), std::string("DISCL_NONEXCLUSIVE"))); pl.insert(std::make_pair(std::string("w32_keyboard"), std::string("DISCL_FOREGROUND"))); pl.insert(std::make_pair(std::string("w32_keyboard"), std::string("DISCL_NONEXCLUSIVE"))); } mInputMgr = OIS::InputManager::createInputSystem(pl); mKeyboard = static_cast<OIS::Keyboard*>(mInputMgr->createInputObject(OIS::OISKeyboard, true)); mMouse = static_cast<OIS::Mouse*>(mInputMgr->createInputObject(OIS::OISMouse, true)); } void OgreApp::updateInputDevices(void) { if(mInputMgr) { mKeyboard->capture(); mMouse->capture(); } } void OgreApp::destroyInputDevices(void) { if(mInputMgr) { mInputMgr->destroyInputObject(mKeyboard); mKeyboard = 0; mInputMgr->destroyInputObject(mMouse); mMouse = 0; OIS::InputManager::destroyInputSystem(mInputMgr); mInputMgr = 0; } }
[ [ [ 1, 254 ] ] ]
9207332d967075c898fa43b53340aa30ec2231e5
4be39d7d266a00f543cf89bcf5af111344783205
/include/slave_ptr.hpp
430b26edd97c324f05e4ab307a7e6b144fb661a6
[]
no_license
nkzxw/lastigen-haustiere
6316bb56b9c065a52d7c7edb26131633423b162a
bdf6219725176ae811c1063dd2b79c2d51b4bb6a
refs/heads/master
2021-01-10T05:42:05.591510
2011-02-03T14:59:11
2011-02-03T14:59:11
47,530,529
1
0
null
null
null
null
ISO-8859-1
C++
false
false
3,083
hpp
//TODO: nombre: Dependent Pointers #ifndef SLAVE_HPP_INCLUDED #define SLAVE_HPP_INCLUDED #include <boost/shared_ptr.hpp> //#include <boost/interprocess/detail/atomic.hpp> #include <boost/noncopyable.hpp> namespace boost { template<class T> class slave_ptr; namespace detail { template<class T> struct slave_ptr_traits { typedef T & reference; }; template<> struct slave_ptr_traits<void> { typedef void reference; }; #if !defined(BOOST_NO_CV_VOID_SPECIALIZATIONS) template<> struct slave_ptr_traits<void const> { typedef void reference; }; template<> struct slave_ptr_traits<void volatile> { typedef void reference; }; template<> struct slave_ptr_traits<void const volatile> { typedef void reference; }; #endif } // namespace detail template <typename T> class master_ptr; // // slave_ptr // // // template <typename T> class slave_ptr { private: // Borland 5.5.1 specific workaround typedef slave_ptr<T> this_type; public: typedef T element_type; typedef T value_type; typedef T * pointer; typedef typename boost::detail::slave_ptr_traits<T>::reference reference; //TODO: move semantics slave_ptr() : master_(0) {} explicit slave_ptr(master_ptr<T>* master) : master_(master) {} slave_ptr(const slave_ptr<T>& other) : master_(other.master_) { } // //slave_ptr<T>& operator=( slave_ptr<T> const & r ) // never throws // slave_ptr<T>& operator=( const slave_ptr<T>& r ) // never throws // { // this_type(r).swap(*this); //return *this; // } typename pointer operator->() const { //return master_->ptr_.get(); return master_->get(); } reference operator* () const // never throws { //BOOST_ASSERT(px != 0); return *master_->ptr_.get(); } master_ptr<T>* master_; }; // No debería ser copiable, ya que si se copia, // Es un shared_ptr con habilidad de hacer un atomic_swap template <typename T> class master_ptr : boost::noncopyable //: shared_ptr<T> { private: // Borland 5.5.1 specific workaround typedef master_ptr<T> this_type; public: typedef T element_type; typedef T value_type; typedef T * pointer; typedef typename boost::detail::slave_ptr_traits<T>::reference reference; friend class boost::slave_ptr<T>; master_ptr() //: ptr_(0) { } master_ptr(T* ptr) : ptr_(ptr) { } slave_ptr<T> getSlave() { return slave_ptr<T>(this); } //TODO: ver si se puede hacer otro método que sea const. T* get() { return ptr_.get(); } T* get() const { return ptr_.get(); } typename pointer operator->() const { return ptr_.get(); } void reset(T* ptr) { ptr_.reset(ptr); } bool atomic_exchange(master_ptr<T> * newPtr) { return atomic_compare_exchange( &ptr_, &ptr_, newPtr->ptr_ ); } private: boost::shared_ptr<T> ptr_; }; } // namespace boost #endif //SLAVE_HPP_INCLUDED
[ "fpelliccioni@c29dda52-a065-11de-a33f-1de61d9b9616" ]
[ [ [ 1, 182 ] ] ]
7a1668f2daac143cca7bc1f198366024ab481ac7
b3f6e84f764d13d5bd49fadb00171f7cd191e2b8
/src/SourceOutput.cpp
8bf2cda2598a93f1d026bd8cc336325d00e8832c
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
youngj/cranea
f55a93d2c7b97479a2f9c7f63ac72f1dd419e9f6
5411a9374a7dc29dd33e4445ef9277ed2b72c835
refs/heads/master
2020-05-18T15:13:03.623874
2008-04-23T08:50:20
2008-04-23T08:50:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,679
cpp
#include "SourceOutput.h" #include "SourceBase.h" #include <iostream> #include <fstream> #include <string> using namespace std; SourceOutput::SourceOutput(const string &filename) : out_(filename.c_str(), ios::binary | ios::out | ios::trunc), encryptedStart_(0) { } void SourceOutput::writePlaintext(const std::string &str) { if (str.find('\0') != string::npos) { throw "Embedded NUL character in string"; } if (!str.empty()) { out_.write(str.c_str(), str.length()); } } void SourceOutput::startEncryptedBlock() { char buf[KEY_SIZE + (1 + NUM_GLOBAL_MAPS) * sizeof(off_t)]; out_.put('\0'); encryptedStart_ = out_.tellp(); out_.write(buf, sizeof(buf)); } void SourceOutput::setInitialLocation(SourceLocation *loc) { initialLoc_ = loc; } bool SourceOutput::isRecorded(SourceBase *object) { return offsetMap_.find(object->gid()) != offsetMap_.end(); } void SourceOutput::recordObject(SourceBase *object) { int gid = object->gid(); offsetMap_[gid] = out_.tellp(); if (object->isTopLevel()) { gidMaps_[object->type()][object->keyhash()] = gid; } } ostream &SourceOutput::stream() { return out_; } void SourceOutput::finalize() { // writes the offsetMap and stores its offset at the beginning of the file off_t mapOffset = out_.tellp(); writeVal<size_t>(offsetMap_.size()); for (map<int, off_t>::const_iterator it = offsetMap_.begin(); it != offsetMap_.end(); ++it) { writeVal<int>(it->first); writeVal<off_t>(it->second); } writeValAndReturn<off_t>(mapOffset, encryptedStart_); // writes the gidMaps and stores their offset at the beginning of the file for (int i = 0; i < NUM_GLOBAL_MAPS; i++) { mapOffset = out_.tellp(); map<byte *, int> &gidMap = gidMaps_[i]; writeVal<size_t>(gidMap.size()); for (map<byte *, int>::const_iterator it = gidMap.begin(); it != gidMap.end(); ++it) { byte *objectKeyHash = it->first; out_.write((char *)objectKeyHash, KEYHASH_SIZE); writeVal<int>(it->second); } writeValAndReturn<off_t>(mapOffset, encryptedStart_ + (i+1) * sizeof(off_t)); } if (initialLoc_) { out_.seekp(encryptedStart_ + (1 + NUM_GLOBAL_MAPS) * sizeof(off_t)); out_.write((char *)initialLoc_->key(), KEY_SIZE); } } off_t SourceOutput::pos() { return out_.tellp(); } void SourceOutput::close() { out_.close(); }
[ "adunar@1d512d32-bd3c-0410-8fef-f7bcb4ce661b" ]
[ [ [ 1, 113 ] ] ]
79317c026709b34d45faf9030c39a1e102a4c2e6
bf7d05c055c5686e4ded30f9705a28a396520d48
/MGA/MgaRegistrar.cpp
7545333bc788f70f3f42c699cc1513c0d562bd31
[]
no_license
ghemingway/mgalib
f32438d5abdbeb5739c298e401a0513f91c8d6d0
c8cf8507a7fe73efe1da19abcdb77b52e75e2de0
refs/heads/master
2020-12-24T15:40:33.538434
2011-02-04T16:38:09
2011-02-04T16:38:09
32,185,568
0
1
null
null
null
null
WINDOWS-1252
C++
false
false
87,070
cpp
/*** Included Header Files ***/ #include "MgaRegistrar.h" // --------------------------- MgaRegistrar --------------------------- // MgaRegistrar::MgaRegistrar() : _paradigms(), _components() { // Set values to defaults this->_iconPath = "./"; this->_showMultipleView = true; this->_eventLoggingEnabled = true; this->_autosaveEnabled = true; this->_autosaveFrequency = 60; this->_autosaveUseDirectory = true; this->_autosaveDirectory = "."; this->_externalEditorEnabled = false; this->_externalEditor = ""; this->_useAutoRouting = true; this->_labelAvoidance = true; this->_scriptEngine = ""; this->_zoomLevel = ""; this->_mouseOverNotify = true; this->_realNumberFormatString = ""; this->_timeStamping = false; this->_useNavigation = true; this->_undoQueueSize = ""; this->_edgeSmoothMode = 1; this->_fontSmoothMode = 1; } const Result_t MgaRegistrar::QueryParadigm(const std::string &name, const std::string &uuidStr, std::string &connection) const throw() { // Look through all paradigms for the name std::list<ParadigmStruct>::const_iterator paradigmIter = this->_paradigms.begin(); while (paradigmIter != this->_paradigms.end()) { // Have we found the paradigm if (paradigmIter->name == name) { // Get the Uuid and connection string std::string guidStr = paradigmIter->currentVersion->first; connection = paradigmIter->currentVersion->second; // All is good return S_OK; } // Move on to the next paradigm ++paradigmIter; } // We don't know that paradigm return E_NOTFOUND; } const Result_t MgaRegistrar::UuidFromVersion(const std::string &name, const std::string &version, std::string &uuidStr) const throw() { // Look through all paradigms for the name std::list<ParadigmStruct>::const_iterator paradigmIter = this->_paradigms.begin(); while (paradigmIter != this->_paradigms.end()) { // Have we found the paradigm if (paradigmIter->name == name) { // Try to find the version std::map<std::string,std::string>::const_iterator versionIter = paradigmIter->versions.find(version); if (versionIter == paradigmIter->versions.end()) return E_NOTFOUND; // Get the Uuid and connection string // std::string guidStr = paradigmIter->currentVersion->first; // connection = paradigmIter->currentVersion->second; // All is good return S_OK; } // Move on to the next paradigm ++paradigmIter; } // We don't know that paradigm return E_NOTFOUND; } const Result_t MgaRegistrar::AssociatedComponents(const std::string &paradigm, const ComponentType_t &type, std::vector<std::string> &programIDs) throw() { programIDs = std::vector<std::string>(); return S_OK; } // --------------------------- XMLRegistrar --------------------------- // bool XMLRegistrar::Write(MgaRegistrar* registry) { return true; } XMLRegistrar::XMLRegistrar(const std::string &filename) : ::MgaRegistrar(), _filename(filename) { // Initialize Xerces infrastructure XMLPlatformUtils::Initialize(); // Get XML tags ready this->_TAG_MGARegistry = XMLString::transcode("MGARegistry"); this->_TAG_Components = XMLString::transcode("Components"); this->_TAG_GUI = XMLString::transcode("GUI"); this->_TAG_Paradigms = XMLString::transcode("Paradigms"); this->_TAG_Paradigm = XMLString::transcode("Paradigm"); this->_TAG_Version = XMLString::transcode("Version"); this->_ATTR_RegVersion = XMLString::transcode("regversion"); this->_ATTR_IconPath = XMLString::transcode("iconpath"); this->_ATTR_JavaClassPath = XMLString::transcode("javaclasspath"); this->_ATTR_JavaMemory = XMLString::transcode("javamemory"); this->_ATTR_Name = XMLString::transcode("name"); this->_ATTR_CurrentVersion = XMLString::transcode("currentversion"); this->_ATTR_Uuid = XMLString::transcode("uuid"); this->_ATTR_Connection = XMLString::transcode("connection"); // Configure DOM parser. this->_configFileParser = new XercesDOMParser(); ASSERT( this->_configFileParser != NULL ); this->_configFileParser->setValidationScheme(XercesDOMParser::Val_Never); this->_configFileParser->setDoNamespaces(false); this->_configFileParser->setDoSchema(false); this->_configFileParser->setLoadExternalDTD(false); } const Result_t XMLRegistrar::Parse(void) { // Try parsing the file try { this->_configFileParser->parse( this->_filename.c_str() ); // no need to free this pointer - owned by the parent parser object xercesc::DOMDocument* xmlDoc = this->_configFileParser->getDocument(); // Get the top-level element: NAme is "root". No attributes for "root" DOMElement* elementRoot = xmlDoc->getDocumentElement(); if( !elementRoot ) return E_XMLPARSER; // throw(std::runtime_error( "empty XML document" )); // Get the registry version ID const XMLCh* xmlch = elementRoot->getAttribute(this->_ATTR_RegVersion); char* tmpChar = XMLString::transcode(xmlch); std::string regVersion = tmpChar; XMLString::release(&tmpChar); // Get the icon path xmlch = elementRoot->getAttribute(this->_ATTR_IconPath); tmpChar = XMLString::transcode(xmlch); std::string iconPath = tmpChar; if (iconPath != "") this->_iconPath = iconPath; XMLString::release(&tmpChar); // Get the java class path // XMLString::release(&this->_ATTR_JavaClassPath); // Get the java memory size // XMLString::release(&this->_ATTR_JavaMemory); // Look one level nested within "MGARegistry" DOMNodeList* children = elementRoot->getChildNodes(); const XMLSize_t nodeCount = children->getLength(); // For all nodes, children of "root" in the XML tree. for(XMLSize_t i = 0; i < nodeCount; ++i) { DOMNode* currentNode = children->item(i); if( currentNode->getNodeType() && // true is not NULL currentNode->getNodeType() == DOMNode::ELEMENT_NODE ) // is element { // Found node which is an Element. Re-cast node as element DOMElement* currentElement = dynamic_cast< xercesc::DOMElement* >( currentNode ); if( XMLString::equals(currentElement->getTagName(), this->_TAG_Paradigms)) { Result_t result = this->ParseParadigms(currentElement); // Look for possible errors if (result != S_OK) return result; } } else if( currentNode->getNodeType() && // true is not NULL currentNode->getNodeType() == DOMNode::ELEMENT_NODE ) // is element { // Found node which is an Element. Re-cast node as element DOMElement* currentElement = dynamic_cast< xercesc::DOMElement* >( currentNode ); if( XMLString::equals(currentElement->getTagName(), this->_TAG_Components)) { Result_t result = this->ParseComponents(currentElement); // Look for possible errors if (result != S_OK) return result; } } else if( currentNode->getNodeType() && // true is not NULL currentNode->getNodeType() == DOMNode::ELEMENT_NODE ) // is element { // Found node which is an Element. Re-cast node as element DOMElement* currentElement = dynamic_cast< xercesc::DOMElement* >( currentNode ); if( XMLString::equals(currentElement->getTagName(), this->_TAG_GUI)) { Result_t result = this->ParseGUI(currentElement); // Look for possible errors if (result != S_OK) return result; } } } } catch( xercesc::XMLException& e ) { char* message = xercesc::XMLString::transcode( e.getMessage() ); std::cout << "Error parsing file: " << message << std::endl; XMLString::release( &message ); return E_INVALID_USAGE; } // All must be OK return S_OK; } const Result_t XMLRegistrar::ParseComponents(DOMElement* element) { std::cout << "Parsing Components.\n"; return S_OK; } const Result_t XMLRegistrar::ParseGUI(DOMElement* element) { std::cout << "Parsing GUI.\n"; return S_OK; } const Result_t XMLRegistrar::ParseParadigms(DOMElement* element) { // Try parsing paradigms try { // Look one level nested within "Paradigms" DOMNodeList* children = element->getChildNodes(); const XMLSize_t nodeCount = children->getLength(); // For all nodes, children of "Paradigms" in the XML tree. for(XMLSize_t i = 0; i < nodeCount; ++i) { DOMNode* currentNode = children->item(i); if( currentNode->getNodeType() && // true is not NULL currentNode->getNodeType() == DOMNode::ELEMENT_NODE ) // is element { // Found node which is an Element. Re-cast node as element DOMElement* currentElement = dynamic_cast< xercesc::DOMElement* >( currentNode ); if( XMLString::equals(currentElement->getTagName(), this->_TAG_Paradigm)) { Result_t result = this->ParseParadigm(currentElement); if (result != S_OK) return result; } } } } catch( xercesc::XMLException& e ) { char* message = xercesc::XMLString::transcode( e.getMessage() ); std::cout << "Error parsing Paradigms: " << message << std::endl; XMLString::release( &message ); return E_INVALID_USAGE; } // All must be OK return S_OK; } const Result_t XMLRegistrar::ParseParadigm(DOMElement* element) { // Try parsing the paradigm ParadigmStruct newParadigm; std::string currentVersion; try { // Get the paradigm name const XMLCh* xmlch = element->getAttribute(this->_ATTR_Name); char* tmpChar = XMLString::transcode(xmlch); std::string name = tmpChar; XMLString::release(&tmpChar); // Get the current version xmlch = element->getAttribute(this->_ATTR_CurrentVersion); tmpChar = XMLString::transcode(xmlch); currentVersion = tmpChar; XMLString::release(&tmpChar); // Make sure we have some valid info if (currentVersion == "" || name == "") return S_OK; newParadigm.name = name; // Get all version and connection info for the paradigm DOMNodeList* children = element->getChildNodes(); const XMLSize_t nodeCount = children->getLength(); // For all nodes, children of "Paradigms" in the XML tree. for(XMLSize_t i = 0; i < nodeCount; ++i) { DOMNode* currentNode = children->item(i); if( currentNode->getNodeType() && // true is not NULL currentNode->getNodeType() == DOMNode::ELEMENT_NODE ) // is element { // Found node which is an Element. Re-cast node as element DOMElement* currentElement = dynamic_cast< xercesc::DOMElement* >( currentNode ); if( XMLString::equals(currentElement->getTagName(), this->_TAG_Version)) { // Get the version GUID xmlch = currentElement->getAttribute(this->_ATTR_Uuid); tmpChar = XMLString::transcode(xmlch); std::string guid = tmpChar; XMLString::release(&tmpChar); // Get the version Connection string xmlch = currentElement->getAttribute(this->_ATTR_Connection); tmpChar = XMLString::transcode(xmlch); std::string connection = tmpChar; XMLString::release(&tmpChar); // Check for errors if (guid == "" || connection == "") return S_OK; newParadigm.versions.insert( std::make_pair(guid, connection) ); } } } } catch( xercesc::XMLException& e ) { char* message = xercesc::XMLString::transcode( e.getMessage() ); std::cout << "Error parsing Paradigm: " << message << std::endl; XMLString::release( &message ); return E_INVALID_USAGE; } // Try to resolve current version if (newParadigm.versions.find(currentVersion) != newParadigm.versions.end()) { // Add this paradigm to the registry list this->_paradigms.push_back(newParadigm); // Make sure currentVersion is set now that we have the paradigm in the list ParadigmStruct &refStruct = this->_paradigms.back(); refStruct.currentVersion = refStruct.versions.find(currentVersion); } // All must be OK return S_OK; } const Result_t XMLRegistrar::OpenRegistry(const std::string &filename, MgaRegistrar* &registrar) throw() { // Try to open the file struct stat fileStatus; int retVal = stat(filename.c_str(), &fileStatus); if (retVal == -1) { // Set registrar to NULL and return error registrar = NULL; retVal = errno; if( retVal == ENOENT ) return E_INVALID_FILENAME; // throw ( std::runtime_error("Path file_name does not exist, or path is an empty string.") ); else if( retVal == ENOTDIR ) return E_INVALID_FILENAME; // throw ( std::runtime_error("A component of the path is not a directory.")); else if( retVal == ELOOP ) return E_INVALID_FILENAME; // throw ( std::runtime_error("Too many symbolic links encountered while traversing the path.")); else if( retVal == EACCES ) return E_INVALID_FILENAME; // throw ( std::runtime_error("Permission denied.")); else if( retVal == ENAMETOOLONG ) return E_INVALID_FILENAME; // throw ( std::runtime_error("File can not be read\n")); } XMLRegistrar *xmlRegistrar = NULL; try { xmlRegistrar = new XMLRegistrar(filename); } catch( XMLException& e ) { char* message = XMLString::transcode( e.getMessage() ); std::cout << "XML toolkit initialization error: " << message << std::endl; XMLString::release( &message ); // We are done here, clean up and go home delete xmlRegistrar; registrar = NULL; return E_XMLPARSER; } // Parse the file Result_t result = xmlRegistrar->Parse(); if (result != S_OK) { // Clean up and return the error delete xmlRegistrar; registrar = NULL; return result; } // All is good registrar = xmlRegistrar; return S_OK; } XMLRegistrar::~XMLRegistrar() { // We are done...clean up delete this->_configFileParser; // if(m_OptionA) XMLString::release( &m_OptionA ); // if(m_OptionB) XMLString::release( &m_OptionB ); try { XMLString::release(&this->_TAG_MGARegistry); XMLString::release(&this->_TAG_Components); XMLString::release(&this->_TAG_GUI); XMLString::release(&this->_TAG_Paradigms); XMLString::release(&this->_TAG_Paradigm); XMLString::release(&this->_TAG_Version); XMLString::release(&this->_ATTR_RegVersion); XMLString::release(&this->_ATTR_IconPath); XMLString::release(&this->_ATTR_JavaClassPath); XMLString::release(&this->_ATTR_JavaMemory); XMLString::release(&this->_ATTR_Name); XMLString::release(&this->_ATTR_CurrentVersion); XMLString::release(&this->_ATTR_Uuid); XMLString::release(&this->_ATTR_Connection); } catch( ... ) { std::cout << "Unknown exception encountered in XMLRegistrar::~XMLRegistrar" << std::endl; } // Terminate Xerces try { XMLPlatformUtils::Terminate(); // Terminate after release of memory } catch( xercesc::XMLException& e ) { char* message = xercesc::XMLString::transcode( e.getMessage() ); std::cout << "XML ttolkit teardown error: " << message << std::endl; XMLString::release( &message ); } } /* STDMETHODIMP CMgaRegistrar::get_IconPath(regaccessmode_enum mode, BSTR *path) { CHECK_OUT(path); COMTRY { LONG res; CString str; if(mode & RM_USER) { CRegKey mga; res = mga.Open(HKEY_CURRENT_USER, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "IconPath"); str.TrimRight(" ;,\t"); if(!str.IsEmpty()) REVOKE_SYS2(mode); } } if(mode & (RM_SYSDOREAD)) { CRegKey mga; res = mga.Open(HKEY_LOCAL_MACHINE, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { CString str2 = QueryValue(mga, "IconPath"); str2.TrimLeft(" ;,\t"); if(!str.IsEmpty() && !str2.IsEmpty()) str += ";"; str += str2; } } CopyTo(str, path); } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::put_IconPath(regaccessmode_enum mode, BSTR path) { COMTRY { CString str; CopyTo(path, str); if(mode & RM_USER) { CRegKey mga; ERRTHROW( mga.Create(HKEY_CURRENT_USER, rootreg) ); ERRTHROW( mga.SetStringValue( "IconPath", str )); } if(mode & (RM_SYS | RM_TEST)) { CRegKey mga; ERRTHROW( mga.Create(HKEY_LOCAL_MACHINE, rootreg) ); if(mode & RM_SYS) ERRTHROW( mga.SetStringValue( "IconPath", str)); } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::get_ShowMultipleView(regaccessmode_enum mode, VARIANT_BOOL *enabled) { COMTRY { LONG res; CString str; if(mode & RM_USER) { CRegKey mga; res = mga.Open(HKEY_CURRENT_USER, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "ShowMultipleView"); if(!str.IsEmpty()) { REVOKE_SYS2(mode); } } } if(mode & (RM_SYSDOREAD)) { CRegKey mga; res = mga.Open(HKEY_LOCAL_MACHINE, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "ShowMultipleView"); } } *enabled = (str == "1") ? VARIANT_TRUE : VARIANT_FALSE; // Default value: false } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::put_ShowMultipleView(regaccessmode_enum mode, VARIANT_BOOL enabled) { COMTRY { CString str = (enabled == VARIANT_FALSE) ? "0" : "1"; if(mode & RM_USER) { CRegKey mga; ERRTHROW( mga.Create(HKEY_CURRENT_USER, rootreg) ); ERRTHROW( mga.SetStringValue( "ShowMultipleView", str)); } if(mode & (RM_SYS | RM_TEST)) { CRegKey mga; ERRTHROW( mga.Create(HKEY_LOCAL_MACHINE, rootreg) ); if(mode & RM_SYS) ERRTHROW( mga.SetStringValue( "ShowMultipleView", str)); } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::get_EventLoggingEnabled(regaccessmode_enum mode, VARIANT_BOOL *enabled) { COMTRY { LONG res; CString str; if(mode & RM_USER) { CRegKey mga; res = mga.Open(HKEY_CURRENT_USER, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "EventLoggingEnabled"); if(!str.IsEmpty()) { REVOKE_SYS2(mode); } } } if(mode & (RM_SYSDOREAD)) { CRegKey mga; res = mga.Open(HKEY_LOCAL_MACHINE, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "EventLoggingEnabled"); } } *enabled = (str == "1") ? VARIANT_TRUE : VARIANT_FALSE; // Default value: false } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::put_EventLoggingEnabled(regaccessmode_enum mode, VARIANT_BOOL enabled) { COMTRY { CString str = (enabled == VARIANT_FALSE) ? "0" : "1"; if(mode & RM_USER) { CRegKey mga; ERRTHROW( mga.Create(HKEY_CURRENT_USER, rootreg) ); ERRTHROW( mga.SetStringValue( "EventLoggingEnabled", str)); } if(mode & (RM_SYS | RM_TEST)) { CRegKey mga; ERRTHROW( mga.Create(HKEY_LOCAL_MACHINE, rootreg) ); if(mode & RM_SYS) ERRTHROW( mga.SetStringValue( "EventLoggingEnabled", str)); } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::get_AutosaveEnabled(regaccessmode_enum mode, VARIANT_BOOL *enabled) { COMTRY { LONG res; CString str; if(mode & RM_USER) { CRegKey mga; res = mga.Open(HKEY_CURRENT_USER, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "AutosaveEnabled"); if(!str.IsEmpty()) { REVOKE_SYS2(mode); } } } if(mode & (RM_SYSDOREAD)) { CRegKey mga; res = mga.Open(HKEY_LOCAL_MACHINE, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "AutosaveEnabled"); } } *enabled = (str == "1") ? VARIANT_TRUE : VARIANT_FALSE; // Default value: false } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::put_AutosaveEnabled(regaccessmode_enum mode, VARIANT_BOOL enabled) { COMTRY { CString str = (enabled == VARIANT_FALSE) ? "0" : "1"; if(mode & RM_USER) { CRegKey mga; ERRTHROW( mga.Create(HKEY_CURRENT_USER, rootreg) ); ERRTHROW( mga.SetStringValue( "AutosaveEnabled", str)); } if(mode & (RM_SYS | RM_TEST)) { CRegKey mga; ERRTHROW( mga.Create(HKEY_LOCAL_MACHINE, rootreg) ); if(mode & RM_SYS) ERRTHROW( mga.SetStringValue( "AutosaveEnabled", str)); } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::get_AutosaveFreq(regaccessmode_enum mode, long *secs) { COMTRY { LONG res; CString str; if(mode & RM_USER) { CRegKey mga; res = mga.Open(HKEY_CURRENT_USER, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "AutosaveFreq"); if(!str.IsEmpty()) { REVOKE_SYS2(mode); } } } if(mode & (RM_SYSDOREAD)) { CRegKey mga; res = mga.Open(HKEY_LOCAL_MACHINE, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "AutosaveFreq"); } } if (_stscanf((LPCTSTR)str, "%ld", secs) != 1) { *secs = 60; // Default value: 1 minute } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::put_AutosaveFreq(regaccessmode_enum mode, long secs) { COMTRY { CString str; str.Format("%ld", secs); if(mode & RM_USER) { CRegKey mga; ERRTHROW( mga.Create(HKEY_CURRENT_USER, rootreg) ); ERRTHROW( mga.SetStringValue( "AutosaveFreq", str)); } if(mode & (RM_SYS | RM_TEST)) { CRegKey mga; ERRTHROW( mga.Create(HKEY_LOCAL_MACHINE, rootreg) ); if(mode & RM_SYS) ERRTHROW( mga.SetStringValue( "AutosaveFreq", str)); } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::get_AutosaveUseDir(regaccessmode_enum mode, VARIANT_BOOL *enabled) { COMTRY { LONG res; CString str; if(mode & RM_USER) { CRegKey mga; res = mga.Open(HKEY_CURRENT_USER, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "AutosaveUseDir"); if(!str.IsEmpty()) { REVOKE_SYS2(mode); } } } if(mode & (RM_SYSDOREAD)) { CRegKey mga; res = mga.Open(HKEY_LOCAL_MACHINE, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "AutosaveUseDir"); } } *enabled = (str == "1") ? VARIANT_TRUE : VARIANT_FALSE; // Default value: false } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::put_AutosaveUseDir(regaccessmode_enum mode, VARIANT_BOOL enabled) { COMTRY { CString str = (enabled == VARIANT_FALSE) ? "0" : "1"; if(mode & RM_USER) { CRegKey mga; ERRTHROW( mga.Create(HKEY_CURRENT_USER, rootreg) ); ERRTHROW( mga.SetStringValue( "AutosaveUseDir", str)); } if(mode & (RM_SYS | RM_TEST)) { CRegKey mga; ERRTHROW( mga.Create(HKEY_LOCAL_MACHINE, rootreg) ); if(mode & RM_SYS) ERRTHROW( mga.SetStringValue( "AutosaveUseDir", str)); } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::get_AutosaveDir(regaccessmode_enum mode, BSTR *dir) { CHECK_OUT(dir); COMTRY { LONG res; CString str; if(mode & RM_USER) { CRegKey mga; res = mga.Open(HKEY_CURRENT_USER, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "AutosaveDir"); } } if(mode & (RM_SYSDOREAD)) { CRegKey mga; res = mga.Open(HKEY_LOCAL_MACHINE, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "AutosaveDir"); } } CopyTo(str, dir); } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::put_AutosaveDir(regaccessmode_enum mode, BSTR dir) { COMTRY { CString str; CopyTo(dir, str); if(mode & RM_USER) { CRegKey mga; ERRTHROW( mga.Create(HKEY_CURRENT_USER, rootreg) ); ERRTHROW( mga.SetStringValue( "AutosaveDir", str)); } if(mode & (RM_SYS | RM_TEST)) { CRegKey mga; ERRTHROW( mga.Create(HKEY_LOCAL_MACHINE, rootreg) ); if(mode & RM_SYS) ERRTHROW( mga.SetStringValue( "AutosaveDir", str)); } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::get_ExternalEditorEnabled(regaccessmode_enum mode, VARIANT_BOOL *enabled) { COMTRY { LONG res; CString str; if(mode & RM_USER) { CRegKey mga; res = mga.Open(HKEY_CURRENT_USER, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "ExternalEditorEnabled"); if(!str.IsEmpty()) { REVOKE_SYS2(mode); } } } if(mode & (RM_SYSDOREAD)) { CRegKey mga; res = mga.Open(HKEY_LOCAL_MACHINE, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "ExternalEditorEnabled"); } } *enabled = (str == "1") ? VARIANT_TRUE : VARIANT_FALSE; // Default value: false } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::put_ExternalEditorEnabled(regaccessmode_enum mode, VARIANT_BOOL enabled) { COMTRY { CString str = (enabled == VARIANT_FALSE) ? "0" : "1"; if(mode & RM_USER) { CRegKey mga; ERRTHROW( mga.Create(HKEY_CURRENT_USER, rootreg) ); ERRTHROW( mga.SetStringValue( "ExternalEditorEnabled", str)); } if(mode & (RM_SYS | RM_TEST)) { CRegKey mga; ERRTHROW( mga.Create(HKEY_LOCAL_MACHINE, rootreg) ); if(mode & RM_SYS) ERRTHROW( mga.SetStringValue( "ExternalEditorEnabled", str)); } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::get_ExternalEditor(regaccessmode_enum mode, BSTR *path) { CHECK_OUT(path); COMTRY { LONG res; CString str; if(mode & RM_USER) { CRegKey mga; res = mga.Open(HKEY_CURRENT_USER, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "ExternalEditor"); } } if(mode & (RM_SYSDOREAD)) { CRegKey mga; res = mga.Open(HKEY_LOCAL_MACHINE, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "ExternalEditor"); } } CopyTo(str, path); } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::put_ExternalEditor(regaccessmode_enum mode, BSTR path) { COMTRY { CString str; CopyTo(path, str); if(mode & RM_USER) { CRegKey mga; ERRTHROW( mga.Create(HKEY_CURRENT_USER, rootreg) ); ERRTHROW( mga.SetStringValue( "ExternalEditor", str)); } if(mode & (RM_SYS | RM_TEST)) { CRegKey mga; ERRTHROW( mga.Create(HKEY_LOCAL_MACHINE, rootreg) ); if(mode & RM_SYS) ERRTHROW( mga.SetStringValue( "ExternalEditor", str)); } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::get_UseAutoRouting(regaccessmode_enum mode, VARIANT_BOOL *enabled) { COMTRY { LONG res; CString str; if(mode & RM_USER) { CRegKey mga; res = mga.Open(HKEY_CURRENT_USER, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "UseAutoRouting"); if(!str.IsEmpty()) { REVOKE_SYS2(mode); } } } if(mode & (RM_SYSDOREAD)) { CRegKey mga; res = mga.Open(HKEY_LOCAL_MACHINE, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "UseAutoRouting"); } } *enabled = (str == "0") ? VARIANT_FALSE : VARIANT_TRUE; // Default value: true } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::put_UseAutoRouting(regaccessmode_enum mode, VARIANT_BOOL enabled) { COMTRY { CString str = (enabled == VARIANT_FALSE) ? "0" : "1"; if(mode & RM_USER) { CRegKey mga; ERRTHROW( mga.Create(HKEY_CURRENT_USER, rootreg) ); ERRTHROW( mga.SetStringValue( "UseAutoRouting", str)); } if(mode & (RM_SYS | RM_TEST)) { CRegKey mga; ERRTHROW( mga.Create(HKEY_LOCAL_MACHINE, rootreg) ); if(mode & RM_SYS) ERRTHROW( mga.SetStringValue( "UseAutoRouting", str)); } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::get_LabelAvoidance(regaccessmode_enum mode, VARIANT_BOOL *enabled) { COMTRY { LONG res; CString str; if(mode & RM_USER) { CRegKey mga; res = mga.Open(HKEY_CURRENT_USER, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "LabelAvoidance"); if(!str.IsEmpty()) { REVOKE_SYS2(mode); } } } if(mode & (RM_SYSDOREAD)) { CRegKey mga; res = mga.Open(HKEY_LOCAL_MACHINE, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "LabelAvoidance"); } } *enabled = (str == "1") ? VARIANT_TRUE : VARIANT_FALSE; // Default value: false } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::put_LabelAvoidance(regaccessmode_enum mode, VARIANT_BOOL enabled) { COMTRY { CString str = (enabled == VARIANT_FALSE) ? "0" : "1"; if(mode & RM_USER) { CRegKey mga; ERRTHROW( mga.Create(HKEY_CURRENT_USER, rootreg) ); ERRTHROW( mga.SetStringValue( "LabelAvoidance", str)); } if(mode & (RM_SYS | RM_TEST)) { CRegKey mga; ERRTHROW( mga.Create(HKEY_LOCAL_MACHINE, rootreg) ); if(mode & RM_SYS) ERRTHROW( mga.SetStringValue( "LabelAvoidance", str)); } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::get_ScriptEngine(regaccessmode_enum mode, BSTR *path) { CHECK_OUT(path); COMTRY { LONG res; CString str; if(mode & RM_USER) { CRegKey mga; res = mga.Open(HKEY_CURRENT_USER, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "ScriptEngine"); str.TrimRight(" ;,\t"); if(!str.IsEmpty()) REVOKE_SYS2(mode); } } if(mode & (RM_SYSDOREAD)) { CRegKey mga; res = mga.Open(HKEY_LOCAL_MACHINE, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { CString str2 = QueryValue(mga, "ScriptEngine"); str2.TrimLeft(" ;,\t"); if(!str.IsEmpty() && !str2.IsEmpty()) str += ";"; str += str2; } } CopyTo(str, path); } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::put_ScriptEngine(regaccessmode_enum mode, BSTR path) { COMTRY { CString str; CopyTo(path, str); if(mode & RM_USER) { CRegKey mga; ERRTHROW( mga.Create(HKEY_CURRENT_USER, rootreg) ); ERRTHROW( mga.SetStringValue("ScriptEngine", str) );//z7 } if(mode & (RM_SYS | RM_TEST)) { CRegKey mga; ERRTHROW( mga.Create(HKEY_LOCAL_MACHINE, rootreg) ); if(mode & RM_SYS) ERRTHROW( mga.SetStringValue("ScriptEngine", str) );//z7 } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::GetDefZoomLevel(regaccessmode_enum p_mode, BSTR *p_zlev) { CHECK_OUT(p_zlev); COMTRY { LONG res; CString str; if(p_mode & RM_USER) { CRegKey mga; res = mga.Open(HKEY_CURRENT_USER, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "DefaultZoomLevel"); if(!str.IsEmpty()) REVOKE_SYS2(p_mode); } } if(p_mode & (RM_SYSDOREAD)) { CRegKey mga; res = mga.Open(HKEY_LOCAL_MACHINE, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "DefaultZoomLevel"); } } CopyTo(str, p_zlev); } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::SetDefZoomLevel(regaccessmode_enum p_mode, BSTR p_zlev) { COMTRY { CString str; CopyTo(p_zlev, str); if(p_mode & RM_USER) { CRegKey mga; ERRTHROW( mga.Create(HKEY_CURRENT_USER, rootreg) ); ERRTHROW( mga.SetStringValue( "DefaultZoomLevel", str)); } if(p_mode & (RM_SYS | RM_TEST)) { CRegKey mga; ERRTHROW( mga.Create(HKEY_LOCAL_MACHINE, rootreg) ); if(p_mode & RM_SYS) ERRTHROW( mga.SetStringValue( "DefaultZoomLevel", str)); } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::GetMouseOverNotify(regaccessmode_enum mode, VARIANT_BOOL *enabled) { COMTRY { LONG res; CString str; if(mode & RM_USER) { CRegKey mga; res = mga.Open(HKEY_CURRENT_USER, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "MouseOverNotify"); if(!str.IsEmpty()) { REVOKE_SYS2(mode); } } } if(mode & (RM_SYSDOREAD)) { CRegKey mga; res = mga.Open(HKEY_LOCAL_MACHINE, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "MouseOverNotify"); } } *enabled = (str == "1") ? VARIANT_TRUE : VARIANT_FALSE; // Default value: false } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::SetMouseOverNotify(regaccessmode_enum mode, VARIANT_BOOL enabled) { COMTRY { CString str = (enabled == VARIANT_FALSE) ? "0" : "1"; if(mode & RM_USER) { CRegKey mga; ERRTHROW( mga.Create(HKEY_CURRENT_USER, rootreg) ); ERRTHROW( mga.SetStringValue( "MouseOverNotify", str)); } if(mode & (RM_SYS | RM_TEST)) { CRegKey mga; ERRTHROW( mga.Create(HKEY_LOCAL_MACHINE, rootreg) ); if(mode & RM_SYS) ERRTHROW( mga.SetStringValue( "MouseOverNotify", str)); } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::GetRealNmbFmtStr(regaccessmode_enum p_mode, BSTR *p_fmtStr) { CHECK_OUT(p_fmtStr); COMTRY { LONG res; CString str; if(p_mode & RM_USER) { CRegKey mga; res = mga.Open(HKEY_CURRENT_USER, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "RealNmbFmtStr"); if(!str.IsEmpty()) REVOKE_SYS2(p_mode); } } if(p_mode & (RM_SYSDOREAD)) { CRegKey mga; res = mga.Open(HKEY_LOCAL_MACHINE, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "RealNmbFmtStr"); } } CopyTo(str, p_fmtStr); } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::SetRealNmbFmtStr(regaccessmode_enum p_mode, BSTR p_fmtStr) { COMTRY { CString str; CopyTo(p_fmtStr, str); if(p_mode & RM_USER) { CRegKey mga; ERRTHROW( mga.Create(HKEY_CURRENT_USER, rootreg) ); ERRTHROW( mga.SetStringValue( "RealNmbFmtStr", str)); } if(p_mode & (RM_SYS | RM_TEST)) { CRegKey mga; ERRTHROW( mga.Create(HKEY_LOCAL_MACHINE, rootreg) ); if(p_mode & RM_SYS) ERRTHROW( mga.SetStringValue( "RealNmbFmtStr", str)); } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::GetTimeStamping(regaccessmode_enum p_mode, VARIANT_BOOL *p_enabled) { COMTRY { LONG res; CString str; if(p_mode & RM_USER) { CRegKey mga; res = mga.Open(HKEY_CURRENT_USER, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "TimeStamping"); if(!str.IsEmpty()) { REVOKE_SYS2(p_mode); } } } if(p_mode & (RM_SYSDOREAD)) { CRegKey mga; res = mga.Open(HKEY_LOCAL_MACHINE, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "TimeStamping"); } } *p_enabled = (str == "1") ? VARIANT_TRUE : VARIANT_FALSE; // Default value: false } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::SetTimeStamping(regaccessmode_enum p_mode, VARIANT_BOOL p_enabled) { COMTRY { CString str = (p_enabled == VARIANT_FALSE) ? "0" : "1"; if(p_mode & RM_USER) { CRegKey mga; ERRTHROW( mga.Create(HKEY_CURRENT_USER, rootreg) ); ERRTHROW( mga.SetStringValue( "TimeStamping", str)); } if(p_mode & (RM_SYS | RM_TEST)) { CRegKey mga; ERRTHROW( mga.Create(HKEY_LOCAL_MACHINE, rootreg) ); if(p_mode & RM_SYS) ERRTHROW( mga.SetStringValue( "TimeStamping", str)); } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::GetNavigation(regaccessmode_enum p_mode, VARIANT_BOOL *p_enabled) { COMTRY { LONG res; CString str; if(p_mode & RM_USER) { CRegKey mga; res = mga.Open(HKEY_CURRENT_USER, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "Navigation"); if(!str.IsEmpty()) { REVOKE_SYS2(p_mode); } } } if(p_mode & (RM_SYSDOREAD)) { CRegKey mga; res = mga.Open(HKEY_LOCAL_MACHINE, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "Navigation"); } } *p_enabled = (str == "0") ? VARIANT_FALSE : VARIANT_TRUE; // Default value: true } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::SetNavigation(regaccessmode_enum p_mode, VARIANT_BOOL p_enabled) { COMTRY { CString str = (p_enabled == VARIANT_FALSE) ? "0" : "1"; if(p_mode & RM_USER) { CRegKey mga; ERRTHROW( mga.Create(HKEY_CURRENT_USER, rootreg) ); ERRTHROW( mga.SetStringValue( "Navigation", str)); } if(p_mode & (RM_SYS | RM_TEST)) { CRegKey mga; ERRTHROW( mga.Create(HKEY_LOCAL_MACHINE, rootreg) ); if(p_mode & RM_SYS) ERRTHROW( mga.SetStringValue( "Navigation", str)); } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::GetUndoQueueSize(regaccessmode_enum p_mode, BSTR *p_qusz) { CHECK_OUT(p_qusz); COMTRY { LONG res; CString str; if(p_mode & RM_USER) { CRegKey mga; res = mga.Open(HKEY_CURRENT_USER, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "UndoQueueSize"); if(!str.IsEmpty()) REVOKE_SYS2(p_mode); } } if(p_mode & (RM_SYSDOREAD)) { CRegKey mga; res = mga.Open(HKEY_LOCAL_MACHINE, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "UndoQueueSize"); } } CopyTo(str, p_qusz); } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::SetUndoQueueSize(regaccessmode_enum p_mode, BSTR p_qusz) { COMTRY { CString str; CopyTo(p_qusz, str); if(p_mode & RM_USER) { CRegKey mga; ERRTHROW( mga.Create(HKEY_CURRENT_USER, rootreg) ); ERRTHROW( mga.SetStringValue( "UndoQueueSize", str)); } if(p_mode & (RM_SYS | RM_TEST)) { CRegKey mga; ERRTHROW( mga.Create(HKEY_LOCAL_MACHINE, rootreg) ); if(p_mode & RM_SYS) ERRTHROW( mga.SetStringValue( "UndoQueueSize", str)); } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::get_EdgeSmoothMode(regaccessmode_enum mode, edgesmoothmode_enum* smoothMode) { COMTRY { LONG res; CString str; if(mode & RM_USER) { CRegKey mga; res = mga.Open(HKEY_CURRENT_USER, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "EdgeSmoothMode"); if(!str.IsEmpty()) { REVOKE_SYS2(mode); } } } if(mode & (RM_SYSDOREAD)) { CRegKey mga; res = mga.Open(HKEY_LOCAL_MACHINE, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "EdgeSmoothMode"); } } *smoothMode = (edgesmoothmode_enum)(str.IsEmpty() ? 2 : strtol(str, NULL, 10)); } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::put_EdgeSmoothMode(regaccessmode_enum mode, edgesmoothmode_enum smoothMode) { COMTRY { CString str; str.Format("%d", smoothMode); if(mode & RM_USER) { CRegKey mga; ERRTHROW( mga.Create(HKEY_CURRENT_USER, rootreg) ); ERRTHROW( mga.SetStringValue( "EdgeSmoothMode", str)); } if(mode & (RM_SYS | RM_TEST)) { CRegKey mga; ERRTHROW( mga.Create(HKEY_LOCAL_MACHINE, rootreg) ); if(mode & RM_SYS) ERRTHROW( mga.SetStringValue( "EdgeSmoothMode", str)); } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::get_FontSmoothMode(regaccessmode_enum mode, fontsmoothmode_enum* smoothMode) { COMTRY { LONG res; CString str; if(mode & RM_USER) { CRegKey mga; res = mga.Open(HKEY_CURRENT_USER, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "FontSmoothMode"); if(!str.IsEmpty()) { REVOKE_SYS2(mode); } } } if(mode & (RM_SYSDOREAD)) { CRegKey mga; res = mga.Open(HKEY_LOCAL_MACHINE, rootreg, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { str = QueryValue(mga, "FontSmoothMode"); } } *smoothMode = (fontsmoothmode_enum)(str.IsEmpty() ? 4 : strtol(str, NULL, 10)); } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::put_FontSmoothMode(regaccessmode_enum mode, fontsmoothmode_enum smoothMode) { COMTRY { CString str; str.Format("%d", smoothMode); if(mode & RM_USER) { CRegKey mga; ERRTHROW( mga.Create(HKEY_CURRENT_USER, rootreg) ); ERRTHROW( mga.SetStringValue( "FontSmoothMode", str)); } if(mode & (RM_SYS | RM_TEST)) { CRegKey mga; ERRTHROW( mga.Create(HKEY_LOCAL_MACHINE, rootreg) ); if(mode & RM_SYS) ERRTHROW( mga.SetStringValue( "FontSmoothMode", str)); } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::get_Paradigms(regaccessmode_enum mode, VARIANT *names) { CHECK_OUT(names); COMTRY { CStringArray ret; if(mode & RM_USER) { CRegKey pars; LONG res = pars.Open(HKEY_CURRENT_USER, rootreg+"\\Paradigms", KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { for(int index = 0;; ++index) { TCHAR name[1024]; LONG err = RegEnumKey(pars, index, name, 1024); if( err == ERROR_NO_MORE_ITEMS ) break; ERRTHROW( err ); REVOKE_SYS2(mode); ret.Add(name); } } } int retlen = ret.GetSize(); if(mode & RM_SYSDOREAD) { CRegKey pars; LONG res = pars.Open(HKEY_LOCAL_MACHINE, rootreg+"\\Paradigms", KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { for(int index = 0;; ++index) { TCHAR name[1024]; LONG err = RegEnumKey(pars, index, name, 1024); if( err == ERROR_NO_MORE_ITEMS ) break; ERRTHROW( err ); int j; for(j = 0; j < retlen; j++) { // Make sure, name is not present already, if yes, system copy is ignored if(!ret[j].CompareNoCase(name)) break; } if(j != retlen) continue; ret.Add(name); } } } CopyTo(ret, names); } COMCATCH(;) } HRESULT GetMtaInfo(BSTR conn, BSTR *parname, BSTR *version, VARIANT *guid) { COMTRY { CComObjPtr<IMgaMetaProject> paradigm; COMTHROW( paradigm.CoCreateInstance(OLESTR("MGA.MgaMetaProject")) ); ASSERT( paradigm != NULL ); COMTHROW( paradigm->Open(conn) ); COMTHROW( paradigm->get_Name(parname) ); COMTHROW( paradigm->get_Version(version) ); COMTHROW( paradigm->get_GUID(guid) ); COMTHROW( paradigm->Close() ); } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::RegisterParadigmFromData(BSTR connstr, BSTR *newname, regaccessmode_enum mode) { CHECK_IN(connstr); if(newname) CHECK_OUT(newname); COMTRY { CString conn = connstr; CString connrecent; // we have to parse it if( conn.Left(4) == "XML=" ) { CString file = conn.Mid(4); conn = "MGA="; conn += file; if( conn.Right(4).CompareNoCase(".xml") == 0 || conn.Right(4).CompareNoCase(".xmp") == 0 ) { conn.Delete(conn.GetLength() - 4, 4); } conn += ".mta"; #define FILEPART(x) (((LPCTSTR)x)+4) DWORD info = GetFileAttributes(FILEPART(conn)); if(info != 0xFFFFFFFF ) { // save old version of paradigm under another name if(info & FILE_ATTRIBUTE_DIRECTORY) COMTHROW(E_FILEOPEN); try { CComBstrObj name; // Format: name-<GUID> CComVariant prevguid; CComBstrObj prevversion; COMTHROW(GetMtaInfo(PutInBstr(conn), PutOut(name), PutOut(prevversion), PutOut(prevguid))); CComBstrObj conn1; if(QueryParadigm(name, PutOut(conn1), &prevguid, REGACCESS_PRIORITY) == S_OK && conn1 == CComBSTR(conn)) { // if it was correctly registered under the previous nonextended name GUID gg; CopyTo(prevguid,gg); CComBstrObj guidstr; CopyTo(gg, guidstr); connrecent = conn.Left(conn.GetLength()-4)+"-"+CString(PutInCString(guidstr))+".mta"; bool sysmove = false, usermove = false; conn1.Empty(); if(QueryParadigm(name, PutOut(conn1), &prevguid, REGACCESS_SYSTEM) == S_OK && conn1 == CComBSTR(conn)) { // if it was correctly registered in system if(RegisterParadigm(name, PutInBstr(connrecent), prevversion, prevguid, REGACCESS_TEST) != S_OK) { AfxMessageBox("Cannot register this paradigm file\n" "an existing '.mta' file with the same name\n" "is registered in the system registry\n" "which you are not permitted to change.\n" "You need to change the name or location\n" "of the new paradigm file"); return E_INVALID_USAGE; } sysmove = true;; } conn1.Empty(); if(QueryParadigm(name, PutOut(conn1), &prevguid, REGACCESS_USER) == S_OK && conn1 == CComBSTR(conn)) { // if it was correctly registered in user usermove = true;; } if(!MoveFileEx(FILEPART(conn), FILEPART(connrecent), MOVEFILE_REPLACE_EXISTING)) { COMTHROW(E_FILEOPEN); } if(sysmove) { COMTHROW( RegisterParadigm( name, PutInBstr(connrecent), prevversion, prevguid, REGACCESS_SYSTEM) ); } if(usermove) { COMTHROW( RegisterParadigm( name, PutInBstr(connrecent), prevversion, prevguid, REGACCESS_USER) ); } } } catch(hresult_exception(&e)) { AfxMessageBox(CString("Failure saving previous version of paradigm\n") + e.what() + (e.hr == E_BINFILE?" [Binary paradigm file (.mta) incompatibility]\nPossible reason: GME version 6 changed the binary format of paradigms.":"") + "\nOld version will be overwritten"); connrecent.Empty(); } } CComObjPtr<IMgaMetaParser> parser; COMTHROW( parser.CoCreateInstance(OLESTR("MGA.MgaMetaParser")) ); ASSERT( parser != NULL ); COMTHROW( parser->Parse(PutInBstr(file), PutInBstr(conn)) ); } CComBstrObj name; CComVariant guid; CComBstrObj version; COMTHROW(GetMtaInfo(PutInBstr(conn), PutOut(name), PutOut(version), PutOut(guid))); if(!connrecent.IsEmpty()) { CComBstrObj namer; CComVariant guidr; CComBstrObj versionr; COMTHROW(GetMtaInfo(PutInBstr(connrecent), PutOut(namer), PutOut(versionr), PutOut(guidr))); // We should change existing registration only here, if the new GUID != the old } COMTHROW(RegisterParadigm( name, PutInBstr(conn), PutInBstr(version), guid, mode) ); if(newname) MoveTo(name, newname); } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::RegisterParadigm(BSTR name, BSTR connstr, BSTR version, VARIANT guid, regaccessmode_enum mode) { COLE2CT version2(version); CString cver(version2); if( guid.vt != (VT_UI1 | VT_ARRAY) || GetArrayLength(guid) != sizeof(GUID) ) COMRETURN(E_INVALIDARG); COMTRY { GUID guid2; CopyTo(guid, guid2); CComBstrObj guid3; CopyTo(guid2, guid3); if(mode & RM_USER) { CRegKey mga; ERRTHROW(mga.Create(HKEY_CURRENT_USER, rootreg) ); CRegKey pars; ERRTHROW( pars.Create(mga, "Paradigms") ); CRegKey par; ERRTHROW( par.Create(pars, PutInCString(name)) ); ERRTHROW( par.SetStringValue( "CurrentVersion", PutInCString(guid3))); if (!cver.IsEmpty()) { ERRTHROW( par.SetStringValue( cver, PutInCString(guid3))); } CRegKey parg; ERRTHROW( parg.Create(par, PutInCString(guid3)) ); ERRTHROW( parg.SetStringValue( "ConnStr", PutInCString(connstr))); } if(mode & (RM_SYS | RM_TEST)) { CRegKey mga; ERRTHROW(mga.Create(HKEY_LOCAL_MACHINE, rootreg) ); CRegKey pars; ERRTHROW( pars.Create(mga, "Paradigms") ); CRegKey par; if(mode & RM_SYS) { ERRTHROW( par.Create(pars, PutInCString(name)) ); CString gg = QueryValue(par, "GUID"); CString gc = QueryValue(par, "ConnStr"); par.DeleteValue("GUID"); par.DeleteValue("ConnStr"); if(!gc.IsEmpty() && !gg.IsEmpty()) { CRegKey parg2; ERRTHROW( parg2.Create(par, gg) ); ERRTHROW( parg2.SetStringValue( "ConnStr", gc) ); } ERRTHROW( par.SetStringValue( "CurrentVersion", PutInCString(guid3))); if (!cver.IsEmpty()) { ERRTHROW( par.SetStringValue( cver, PutInCString(guid3))); } CRegKey parg; ERRTHROW( parg.Create(par, PutInCString(guid3)) ); ERRTHROW( parg.SetStringValue( "ConnStr", PutInCString(connstr))); } else { LONG res = par.Open(pars, PutInCString(name)); if(res != ERROR_SUCCESS && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); } } Associate(CComBSTR(L"Mga.AddOn.ConstraintManager"), name, mode); // no error checking } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::QueryParadigmAllGUIDs(BSTR parname, VARIANT *guidstrs, regaccessmode_enum mode) { CHECK_OUT(guidstrs); COLE2CT parname2(parname); CString pname(parname2); COMTRY { CStringArray ret; if(mode & RM_USER) { CRegKey par; LONG res = par.Open(HKEY_CURRENT_USER, rootreg+"\\Paradigms\\" + pname, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { for(int index = 0;; ++index) { TCHAR name[1024]; LONG err = RegEnumKey(par, index, name, 1024); if( err == ERROR_NO_MORE_ITEMS ) break; ERRTHROW( err ); REVOKE_SYS2(mode); ret.Add(name); } } } int retlen = ret.GetSize(); if(mode & RM_SYSDOREAD) { CRegKey par; LONG res = par.Open(HKEY_LOCAL_MACHINE, rootreg+"\\Paradigms\\" + pname, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { CString cur = QueryValue(par, "CurrentVersion"); if(!cur.IsEmpty()) { // New style: Connection strings are stored under GUID subkeys for(int index = 0;; ++index) { TCHAR name[1024]; LONG err = RegEnumKey(par, index, name, 1024); if( err == ERROR_NO_MORE_ITEMS ) break; ERRTHROW( err ); int j; for(j = 0; j < retlen; j++) { // Make sure, name is not present already, if yes system copy is ignored if(!ret[j].CompareNoCase(name)) break; } if(j != retlen) continue; ret.Add(name); } } else { CString name = QueryValue(par, "GUID"); int j; for(j = 0; j < retlen; j++) { // Make sure, name is not present already, if yes system copy is ignored if(!ret[j].CompareNoCase(name)) break; } if(j == retlen) ret.Add(name); } } } CopyTo(ret, guidstrs); } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::QueryParadigm(BSTR parname, BSTR *connstr, VARIANT *guid, regaccessmode_enum mode) { CHECK_OUT(connstr); // CHECK_OUT(guid); COMTRY { CString pname = PutInCString(parname); CRegKey subk; CString guidact; CComBstrObj inguidstr; if(guid->vt != VT_EMPTY) { GUID g; CopyTo(*guid, g); CopyTo(g, inguidstr); // if(inguidstr == L"{00000000-0000-0000-0000-000000000000}") inguidstr = NULL; } LONG res; if(mode & RM_USER) { CRegKey par; res = par.Open(HKEY_CURRENT_USER, rootreg + "\\Paradigms\\" + pname, KEY_READ); if(res == ERROR_SUCCESS) { // REVOKE_SYS2(mode); // paradigm found, ignore system settings if(inguidstr == NULL) { guidact = QueryValue(par, "CurrentVersion"); if(guidact.IsEmpty()) res = ERROR_FILE_NOT_FOUND; } else guidact = inguidstr; } if(res == ERROR_SUCCESS) res = subk.Open(par, guidact, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) mode = REGACCESS_USER; } if(mode & RM_SYSDOREAD) { CRegKey par; res = par.Open(HKEY_LOCAL_MACHINE, rootreg + "\\Paradigms\\" + pname, KEY_READ); if(res == ERROR_SUCCESS) { CString cur = QueryValue(par, "CurrentVersion"); if(cur.IsEmpty()) { guidact = QueryValue(par, "GUID"); if(inguidstr != NULL && inguidstr != CComBSTR(guidact)) COMTHROW(E_NOTFOUND); subk.Attach(par.Detach()); } else { if(inguidstr == NULL) guidact = cur; else guidact = inguidstr; res = subk.Open(par, guidact, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); } } } if(subk == NULL) return(E_NOTFOUND); // !!!!!!! CopyTo(QueryValue(subk, "ConnStr"), connstr); if(inguidstr == NULL) { GUID g; CopyTo(CComBSTR(guidact),g); CopyTo(g, guid); } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::get_ParadigmGUIDString(regaccessmode_enum mode, BSTR parname, BSTR *guidstr) { CHECK_OUT(guidstr); COMTRY { CComBSTR connstr; CComVariant guid; COMTHROW(QueryParadigm(parname, &connstr, &guid, mode)); GUID g; CopyTo(guid, g); CopyTo(g, guidstr); } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::VersionFromGUID(BSTR name, VARIANT guid, BSTR *ver, regaccessmode_enum mode) { CHECK_OUT(ver); bool found = false; COMTRY { GUID gg; CopyTo(guid,gg); CComBstrObj guidbstr; CopyTo(gg, guidbstr); LONG res; if(mode & RM_USER) { CRegKey par; res = par.Open(HKEY_CURRENT_USER, rootreg + "\\Paradigms\\"+name, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { mode = REGACCESS_USER; for(int index = 0;; ++index) { TCHAR name[512]; DWORD namesize = sizeof(name); BYTE value[512]; DWORD valuesize = sizeof(value); DWORD valtype; LONG err = RegEnumValue(par, index, name, &namesize, NULL, &valtype, value, &valuesize); if( err == ERROR_NO_MORE_ITEMS ) break; ERRTHROW( err ); if (valtype == REG_SZ) { CString cver(value); if (cver.Compare(PutInCString(guidbstr)) == 0) { CString namestr(name); if (namestr.CompareNoCase("CurrentVersion") != 0) { found = true; CopyTo(namestr, ver); } } } } } } if(mode & (RM_SYSDOREAD)) { CRegKey par; res = par.Open(HKEY_LOCAL_MACHINE, rootreg + "\\Paradigms\\"+name, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { for(int index = 0;; ++index) { TCHAR name[512]; DWORD namesize = sizeof(name); BYTE value[512]; DWORD valuesize = sizeof(value); DWORD valtype; LONG err = RegEnumValue(par, index, name, &namesize, NULL, &valtype, value, &valuesize); if( err == ERROR_NO_MORE_ITEMS ) break; ERRTHROW( err ); if (valtype == REG_SZ) { CString cver(value); if (cver.Compare(PutInCString(guidbstr)) == 0) { CString namestr(name); if (namestr.CompareNoCase("CurrentVersion") != 0) { found = true; CopyTo(namestr, ver); } } } } } } if(!found) return(E_NOTFOUND); } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::UnregisterParadigmGUID(BSTR name, VARIANT v, regaccessmode_enum mode) { // it cannot be unregistered if it is the current version COMTRY { GUID gg; CopyTo(v,gg); CComBstrObj guidbstr; CopyTo(gg, guidbstr); if(mode & RM_USER) { CRegKey par; ERRTHROW( par.Open(HKEY_CURRENT_USER, rootreg + "\\Paradigms\\"+name) ); CString cur = QueryValue(par, "CurrentVersion"); if(cur.Compare(PutInCString(guidbstr)) == 0) { COMTHROW(E_INVALID_USAGE); } for(int index = 0;; ++index) { TCHAR name[512]; DWORD namesize = sizeof(name); BYTE value[512]; DWORD valuesize = sizeof(value); DWORD valtype; LONG err = RegEnumValue(par, index, name, &namesize, NULL, &valtype, value, &valuesize); if( err == ERROR_NO_MORE_ITEMS ) break; ERRTHROW( err ); if (valtype == REG_SZ) { CString cver(value); if (cver.Compare(PutInCString(guidbstr)) == 0) { RegDeleteValue(par, name); } } } ERRTHROW( par.RecurseDeleteKey(PutInCString(guidbstr)) ); } if(mode & (RM_SYS | RM_TEST)) { CRegKey par; ERRTHROW( par.Open(HKEY_LOCAL_MACHINE, rootreg + "\\Paradigms\\"+name) ); CString cur = QueryValue(par, "CurrentVersion"); if(cur.Compare(PutInCString(guidbstr)) == 0) { COMTHROW(E_INVALID_USAGE); } if(mode & RM_SYS) { ERRTHROW( par.RecurseDeleteKey(PutInCString(guidbstr)) ); for(int index = 0;; ++index) { TCHAR name[512]; DWORD namesize = sizeof(name); BYTE value[512]; DWORD valuesize = sizeof(value); DWORD valtype; LONG err = RegEnumValue(par, index, name, &namesize, NULL, &valtype, value, &valuesize); if( err == ERROR_NO_MORE_ITEMS ) break; ERRTHROW( err ); if (valtype == REG_SZ) { CString cver(value); if (cver.Compare(PutInCString(guidbstr)) == 0) { RegDeleteValue(par, name); } } } } if(mode & RM_TEST) ERRTHROW( par.Open(par, PutInCString(guidbstr)) ); } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::UnregisterParadigm(BSTR name, regaccessmode_enum mode) { COMTRY { if(mode & RM_USER) { CRegKey pars; LONG res = pars.Open(HKEY_CURRENT_USER, rootreg + "\\Paradigms"); if(!res) res = pars.RecurseDeleteKey(PutInCString(name)); if(res == ERROR_FILE_NOT_FOUND) res = ERROR_SUCCESS; ERRTHROW(res); } if(mode & (RM_SYS | RM_TEST)) { CRegKey pars; LONG res = pars.Open(HKEY_LOCAL_MACHINE, rootreg + "\\Paradigms"); if(!res) { if(mode & RM_SYS) res = pars.RecurseDeleteKey(PutInCString(name)); if(mode & RM_TEST) res = pars.Open(pars, PutInCString(name)); } if(res == ERROR_FILE_NOT_FOUND) res = ERROR_SUCCESS; ERRTHROW(res); } } COMCATCH(;) } // It also adds broken registry entries (e.g. the ones where the type is missing) STDMETHODIMP CMgaRegistrar::get_Components(regaccessmode_enum mode, VARIANT *progids) { CHECK_OUT(progids); COMTRY { CStringArray ret; if(mode & RM_USER) { CRegKey comps; LONG res = comps.Open(HKEY_CURRENT_USER, rootreg+"\\Components", KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { for(int index = 0;; ++index) { TCHAR name[1024]; LONG err = RegEnumKey(comps, index, name, 1024); if( err == ERROR_NO_MORE_ITEMS ) break; ERRTHROW( err ); CRegKey comp; err = comp.Open(comps, name, KEY_READ); DWORD type2; if(err == ERROR_SUCCESS) err = comp.QueryDWORDValue( "Type", type2); if(err == ERROR_SUCCESS && (type2 & COMPONENTTYPE_SYSREGREF) != 0) { LONG res = comp.Open(HKEY_LOCAL_MACHINE, rootreg+"\\Components\\"+name, KEY_READ); if(res != ERROR_SUCCESS) { // delete dangling sysregref key comps.RecurseDeleteKey(name); } continue; } REVOKE_SYS2(mode); ret.Add(name); } } } int retlen = ret.GetSize(); if(mode & RM_SYSDOREAD) { CRegKey comps; LONG res = comps.Open(HKEY_LOCAL_MACHINE, rootreg+"\\Components", KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { for(int index = 0;; ++index) { TCHAR name[1024]; LONG err = RegEnumKey(comps, index, name, 1024); if( err == ERROR_NO_MORE_ITEMS ) break; ERRTHROW( err ); int j; for(j = 0; j < retlen; j++) { // Make sure, name is not present already, if yes system copy is ignored if(!ret[j].CompareNoCase(name)) break; } if(j != retlen) continue; CRegKey comp; err = comp.Open(comps, name, KEY_READ); DWORD type2; if(err == ERROR_SUCCESS) err = comp.QueryDWORDValue( "Type", type2); if(err == ERROR_SUCCESS && !(type2 & COMPONENTTYPE_ALL)) break; // none of the component types ret.Add(name); } } } CopyTo(ret, progids); } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::RegisterComponent(BSTR progid, componenttype_enum type, BSTR desc, regaccessmode_enum mode) { COMTRY { CComBstrObj paradigms(OLESTR("*")); if(!(type & COMPONENTTYPE_PARADIGM_INDEPENDENT)) { paradigms.Empty(); CComPtr<IMgaComponent> comp; CreateMgaComponent(comp, progid); if(!comp) COMTHROW(E_MGA_COMPONENT_ERROR); COMTHROW(comp->get_Paradigm(PutOut(paradigms))); } if(mode & RM_USER) { CRegKey mga; ERRTHROW( mga.Create(HKEY_CURRENT_USER, rootreg) ); CRegKey comps; ERRTHROW( comps.Create(mga, "Components") ); CRegKey comp; ERRTHROW( comp.Create(comps, PutInCString(progid)) ); ERRTHROW( comp.SetDWORDValue( "Type", (DWORD)type)); ERRTHROW( comp.SetStringValue( "Description", PutInCString(desc))); if(paradigms.Length()) { ERRTHROW( comp.SetStringValue( "Paradigm", PutInCString(paradigms))); } } if(mode & (RM_SYS | RM_TEST)) { CRegKey mga; ERRTHROW( mga.Create(HKEY_LOCAL_MACHINE, rootreg) ); CRegKey comps; ERRTHROW( comps.Create(mga, "Components") ); if(mode & RM_SYS) { CRegKey comp; ERRTHROW( comp.Create(comps, PutInCString(progid)) ); ERRTHROW( comp.SetDWORDValue( "Type", (DWORD)type)); ERRTHROW( comp.SetStringValue( "Description", PutInCString(desc))); if(paradigms.Length()) { ERRTHROW( comp.SetStringValue( "Paradigm", PutInCString(paradigms))); } } else { CRegKey comp; LONG res = comp.Open(comps, PutInCString(progid)); if(res != ERROR_SUCCESS && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); } } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::QueryComponent(BSTR progid, componenttype_enum *type, BSTR *desc, regaccessmode_enum mode) { CHECK_OUT(type); if(desc) CHECK_OUT(desc); CString progidstr = PutInCString(progid); COMTRY { if(mode & RM_USER) { CRegKey comp; LONG res = comp.Open(HKEY_CURRENT_USER, rootreg+"\\Components\\"+progidstr, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { DWORD type2; ERRTHROW( comp.QueryDWORDValue( "Type", type2) ); if((type2 & COMPONENTTYPE_ALL)) { *type = (componenttype_enum)type2; if(desc) CopyTo(QueryValue(comp, "Description"), desc); return S_OK; } } } if(mode & RM_SYSDOREAD) { CRegKey comp; LONG res = comp.Open(HKEY_LOCAL_MACHINE, rootreg+"\\Components\\"+progidstr, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { DWORD type2; ERRTHROW( comp.QueryDWORDValue( "Type", type2) ); if((type2 & COMPONENTTYPE_ALL)) { *type = (componenttype_enum)type2; if(desc) CopyTo(QueryValue(comp, "Description"), desc); return S_OK; } } } COMTHROW(E_NOTFOUND); } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::UnregisterComponent(BSTR progid, regaccessmode_enum mode) { COMTRY { // if(mode & RM_USER) { if(mode & (RM_USER | RM_SYS) ){ CRegKey comps; LONG res = comps.Open(HKEY_CURRENT_USER, rootreg + "\\Components"); DWORD type2 = 0; if(!res) { CRegKey comp; res = comp.Open(comps, PutInCString(progid), KEY_READ); if(!res) comp.QueryDWORDValue( "Type", type2); } if((mode & RM_USER) || (type2 & COMPONENTTYPE_SYSREGREF) != 0 ) { if(!res) res = comps.RecurseDeleteKey(PutInCString(progid)); if(res == ERROR_FILE_NOT_FOUND) res = ERROR_SUCCESS; ERRTHROW(res); } } if(mode & (RM_SYS | RM_TEST)) { CRegKey comps; LONG res = comps.Open(HKEY_LOCAL_MACHINE, rootreg + "\\Components"); if(!res) { if(mode & RM_SYS) res = comps.RecurseDeleteKey(PutInCString(progid)); if(mode & RM_TEST) res = comps.Open(comps, PutInCString(progid)); } if(res == ERROR_FILE_NOT_FOUND) res = ERROR_SUCCESS; ERRTHROW(res); } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::put_ComponentExtraInfo(regaccessmode_enum mode, BSTR progid, BSTR name, BSTR newVal) { CString progidstr = PutInCString(progid); COMTRY { if(mode & RM_USER) { CRegKey comp; LONG res = comp.Open(HKEY_CURRENT_USER, rootreg+"\\Components\\"+progidstr); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { DWORD type2; ERRTHROW( comp.QueryDWORDValue( "Type", type2)); if((type2 & COMPONENTTYPE_ALL)) { if(!newVal) { ERRTHROW( comp.DeleteValue(PutInCString(name)) ); } else { ERRTHROW( comp.SetStringValue( PutInCString(name), PutInCString(newVal))); } } } } if(mode & (RM_SYS | RM_TEST)) { CRegKey comp; LONG res = comp.Open(HKEY_LOCAL_MACHINE, rootreg+"\\Components\\"+progidstr); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { DWORD type2; ERRTHROW( comp.QueryDWORDValue( "Type", type2)); if((mode & RM_SYS) && (type2 & COMPONENTTYPE_ALL)) { if(!newVal) { ERRTHROW( comp.DeleteValue(PutInCString(name)) ); } else { ERRTHROW( comp.SetStringValue( PutInCString(name), PutInCString(newVal))); } } } } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::get_ComponentExtraInfo(regaccessmode_enum mode, BSTR progid, BSTR name, BSTR* pVal) { CHECK_OUT(pVal); CString progidstr = PutInCString(progid); COMTRY { if(mode & RM_USER) { CRegKey comp; LONG res = comp.Open(HKEY_CURRENT_USER, rootreg+"\\Components\\"+progidstr, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { DWORD type2; ERRTHROW( comp.QueryDWORDValue( "Type", type2)); if((type2 & COMPONENTTYPE_ALL)) { CopyTo(QueryValue(comp, PutInCString(name)), pVal); return S_OK; } } } if(mode & RM_SYSDOREAD) { CRegKey comp; LONG res = comp.Open(HKEY_LOCAL_MACHINE, rootreg+"\\Components\\"+progidstr, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { DWORD type2; ERRTHROW( comp.QueryDWORDValue( "Type", type2)); if((type2 & COMPONENTTYPE_ALL)) { CopyTo(QueryValue(comp, PutInCString(name)), pVal); return S_OK; } } } return E_NOTFOUND; } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::get_LocalDllPath(BSTR progid, BSTR* pVal) { CHECK_OUT(pVal); COMTRY { CString m_strProgId = PutInCString(progid); CRegKey comp; CString m_strClassId; for(int i = 0; i < 10; i++) { LONG res = comp.Open(HKEY_CLASSES_ROOT, m_strProgId + "\\CLSID", KEY_READ); if(res == ERROR_SUCCESS) { m_strClassId = QueryValue(comp,"" ); break; } else { res = comp.Open(HKEY_CLASSES_ROOT, m_strProgId + "\\CurVer", KEY_READ); if(res != ERROR_SUCCESS) COMTHROW(E_NOTFOUND); m_strProgId = QueryValue(comp, "" ); comp.Close(); } } if(m_strClassId.IsEmpty()) COMTHROW(E_NOTFOUND); LONG res = comp.Open(HKEY_CLASSES_ROOT, "CLSID\\" + m_strClassId + "\\InprocServer32", KEY_READ); CString m_strPath; if(res == ERROR_SUCCESS) { m_strPath = QueryValue(comp, "" ); if (m_strPath == "mscoree.dll") { char data[MAX_PATH]; ULONG num_bytes = sizeof(data) / sizeof(data[0]); if (comp.QueryValue("CodeBase", 0, data, &num_bytes) == ERROR_SUCCESS) { m_strPath = data; m_strPath = m_strPath.Right(m_strPath.GetLength() - 8); m_strPath.Replace('/', '\\'); } else { if (comp.QueryValue("Assembly", 0, data, &num_bytes) == ERROR_SUCCESS) { m_strPath = "GAC: "; m_strPath += data; } } } } CopyTo(m_strPath, pVal); } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::get_AssociatedComponents(BSTR paradigm, componenttype_enum type, regaccessmode_enum mode, VARIANT *progids) { CHECK_OUT(progids); type = (componenttype_enum)(type & COMPONENTTYPE_ALL); COMTRY { CString paradigm2; CopyTo(paradigm, paradigm2); regaccessmode_enum mode1 = mode; if(mode1 & RM_USER) { CRegKey par; LONG res = par.Open(HKEY_CURRENT_USER, rootreg + "\\Paradigms\\" + paradigm2, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) mode1 = REGACCESS_USER; //if paradigm is user-defined, associations must be user too } if(mode1 & RM_SYSDOREAD) { CRegKey par; LONG res = par.Open(HKEY_LOCAL_MACHINE, rootreg + "\\Paradigms\\" + paradigm2, KEY_READ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res != ERROR_SUCCESS) COMTHROW(E_NOTFOUND); } CStringArray ret; TCHAR name[1024]; CRegKey syscomps; syscomps.Open(HKEY_LOCAL_MACHINE, rootreg + "\\Components", KEY_READ ); if(mode & RM_USER) { CRegKey comps; LONG res = comps.Open(HKEY_CURRENT_USER, rootreg + "\\Components", KEY_READ ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { for(int index = 0;; ++index) { LONG err = RegEnumKey(comps, index, name, sizeof(name)); if( err == ERROR_NO_MORE_ITEMS ) break; // ERRTHROW( err ); if(err != ERROR_SUCCESS) continue; CRegKey comp; if( comp.Open(comps, name, KEY_READ) != ERROR_SUCCESS) continue; DWORD comptype; if( comp.QueryDWORDValue( "Type", comptype) != ERROR_SUCCESS) continue; if( comptype & COMPONENTTYPE_SYSREGREF) { LONG res = ERROR_FILE_NOT_FOUND; if(syscomps) { CRegKey syscomp; res = syscomp.Open(syscomps, name, KEY_READ); if(!res) res = syscomp.QueryDWORDValue( "Type", comptype); } if(res != ERROR_SUCCESS) { // delete dangling SYSREGREF-s ERRTHROW(comp.Close()); ERRTHROW(comps.DeleteSubKey(name)); } } if( ((componenttype_enum)comptype & type) == 0 ) continue; if( 1) { //((componenttype_enum)comptype & COMPONENTTYPE_PARADIGM_INDEPENDENT) == 0 ) { CRegKey assocs; if( assocs.Open(comp, "Associated", KEY_READ) != ERROR_SUCCESS) continue; DWORD count; if( assocs.QueryValue(paradigm2, NULL, NULL, &count) != ERROR_SUCCESS ) continue; } ret.Add(name); } } } int retlen; if(retlen = ret.GetSize()) REVOKE_SYS2(mode); if(mode & RM_SYSDOREAD) { CRegKey comps; LONG res = comps.Open(HKEY_LOCAL_MACHINE, rootreg + "\\Components", KEY_READ ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { for(int index = 0;; ++index) { LONG err = RegEnumKey(comps, index, name, sizeof(name)); if( err == ERROR_NO_MORE_ITEMS ) break; // ERRTHROW( err ); if(err != ERROR_SUCCESS) continue; CRegKey comp; if( comp.Open(comps, name, KEY_READ) != ERROR_SUCCESS) continue; DWORD comptype; if( comp.QueryDWORDValue( "Type", comptype) != ERROR_SUCCESS) continue; if( ((componenttype_enum)comptype & type) == 0 ) continue; if(1) {// ((componenttype_enum)comptype & COMPONENTTYPE_PARADIGM_INDEPENDENT) == 0 ) { CRegKey assocs; if( assocs.Open(comp, "Associated", KEY_READ) != ERROR_SUCCESS) continue; DWORD count; if( assocs.QueryValue( paradigm2, NULL, NULL, &count) != ERROR_SUCCESS ) continue; } int j; for(j = 0; j < retlen; j++) { // Make sure, name is not present already, if yes system copy is ignored if(!ret[j].CompareNoCase(name)) break; } if(j != retlen) continue; ret.Add(name); } } } CopyTo(ret, progids); } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::get_AssociatedParadigms(BSTR progid, regaccessmode_enum mode, VARIANT *paradigms) { CHECK_OUT(paradigms); COMTRY { CStringArray ret; TCHAR name[1024]; CString progidstr = PutInCString(progid); int mode1 = mode; bool somethingfound = false; CRegKey comp; if(mode & RM_USER) { LONG res = comp.Open(HKEY_CURRENT_USER, rootreg + "\\Components\\" + progidstr, KEY_READ ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { DWORD comptype; ERRTHROW( comp.QueryDWORDValue( "Type", comptype) ); if(comptype & COMPONENTTYPE_SYSREGREF) { ATLASSERT(comptype == COMPONENTTYPE_SYSREGREF); } else { somethingfound = true; REVOKE_SYS2(mode); if( ((componenttype_enum)comptype & COMPONENTTYPE_PARADIGM_INDEPENDENT) != 0 ) { COMTHROW( get_Paradigms(mode, paradigms)); return S_OK; } CRegKey assocs; ERRTHROW( assocs.Open(comp, "Associated", KEY_READ) ); for(int index = 0;; ++index) { DWORD namesize = sizeof(name); LONG err = RegEnumValue(assocs, index, name, &namesize, NULL, NULL, NULL, NULL); if( err == ERROR_NO_MORE_ITEMS ) break; ERRTHROW( err ); CComBSTR cs; CComVariant guid; if(QueryParadigm(CComBSTR(name), &cs, &guid, REGACCESS_PRIORITY) != S_OK) continue; ret.Add(name); } } } } int retlen = ret.GetSize(); if(retlen) REVOKE_SYS2(mode); if(mode & RM_SYSDOREAD) { LONG res = comp.Open(HKEY_LOCAL_MACHINE, rootreg + "\\Components\\" + progidstr, KEY_READ ); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); if(res == ERROR_SUCCESS) { somethingfound = true; DWORD comptype; ERRTHROW( comp.QueryDWORDValue( "Type", comptype) ); if( ((componenttype_enum)comptype & COMPONENTTYPE_PARADIGM_INDEPENDENT) != 0 ) { VariantClear(paradigms); COMTHROW( get_Paradigms(mode, paradigms)); return S_OK; } CRegKey assocs; ERRTHROW( assocs.Open(comp, "Associated", KEY_READ) ); for(int index = 0;; ++index) { DWORD namesize = sizeof(name); LONG err = RegEnumValue(assocs, index, name, &namesize, NULL, NULL, NULL, NULL); if( err == ERROR_NO_MORE_ITEMS ) break; ERRTHROW( err ); CComBSTR cs; CComVariant guid; if(QueryParadigm(CComBSTR(name), &cs, &guid, REGACCESS_SYSTEM) != S_OK) continue; int j; for(j = 0; j < retlen; j++) { // Make sure, name is not present already, if yes system copy is ignored if(!ret[j].CompareNoCase(name)) break; } if(j != retlen) continue; ret.Add(name); } } } if(!somethingfound) COMTHROW(E_NOTFOUND); CopyTo(ret, paradigms); } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::Associate(BSTR progid, BSTR paradigm, regaccessmode_enum mode) { COLE2CT progid2(progid); CString pname(progid2); COMTRY { bool somethingdone = false; if(mode & RM_USER) { CRegKey comp; LONG res = comp.Open(HKEY_CURRENT_USER, rootreg + "\\Components\\" + pname); CRegKey assocs; if(res == ERROR_FILE_NOT_FOUND) { // try to create a shadow registry CRegKey comp1, mga; res = comp1.Open(HKEY_LOCAL_MACHINE, rootreg + "\\Components\\" + pname, KEY_READ); if(!res) res = mga.Create(HKEY_CURRENT_USER, rootreg); CRegKey comps; if(!res) res = ( comps.Create(mga, "Components") ); if(!res) res = ( comp.Create(comps, pname) ); if(!res) res = ( comp.SetDWORDValue( "Type", (DWORD)COMPONENTTYPE_SYSREGREF)); } if(!res) res = assocs.Create(comp, "Associated"); if(!res) assocs.SetStringValue( PutInCString(paradigm), ""); if(!res) somethingdone = true; if(res == ERROR_FILE_NOT_FOUND) res = ERROR_SUCCESS; ERRTHROW(res); } if(mode & (RM_SYS | RM_TEST)) { CRegKey comp; LONG res = comp.Open(HKEY_LOCAL_MACHINE, rootreg + "\\Components\\" + pname); if(mode & RM_SYS) { CRegKey assocs; if(!res) res = assocs.Create(comp, "Associated"); if(!res) res = assocs.SetStringValue( PutInCString(paradigm), ""); } else { CRegKey assocs; LONG res = assocs.Open(comp, "Associated"); if(res != ERROR_SUCCESS && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); } if(!res) somethingdone = true; } if(!somethingdone) COMTHROW(E_NOTFOUND); } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::Disassociate(BSTR progid, BSTR paradigm, regaccessmode_enum mode) { COLE2CT progid2(progid); CString pname(progid2); COMTRY { if(mode & RM_USER) { CRegKey comp; LONG res = comp.Open(HKEY_CURRENT_USER, rootreg + "\\Components\\" + pname); CRegKey assocs; if(!res) res = assocs.Open(comp, "Associated"); if(!res) res = assocs.DeleteValue(PutInCString(paradigm)); if(res == ERROR_FILE_NOT_FOUND) res = ERROR_SUCCESS; ERRTHROW(res); } if(mode & (RM_SYS | RM_TEST)) { CRegKey comp; LONG res = comp.Open(HKEY_LOCAL_MACHINE, rootreg + "\\Components\\" + pname); CRegKey assocs; if(!res) res = assocs.Open(comp, "Associated"); if(mode & RM_SYS) { if(!res) res = assocs.DeleteValue(PutInCString(paradigm)); } if(res == ERROR_FILE_NOT_FOUND) res = ERROR_SUCCESS; ERRTHROW(res); } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::IsAssociated(BSTR progid, BSTR paradigm, VARIANT_BOOL *is_ass, VARIANT_BOOL *can_ass, regaccessmode_enum mode){ CHECK_IN(progid); CHECK_OUT(paradigm); CString progidstr = PutInCString(progid); CString parc = PutInCString(paradigm); COMTRY { LONG res; DWORD dummy; componenttype_enum type; COMTHROW(QueryComponent(progid, &type, NULL, REGACCESS_PRIORITY)); if(is_ass) *is_ass = VARIANT_FALSE; if(can_ass) *can_ass = VARIANT_FALSE; if(mode & RM_USER) { CRegKey comp, acomp; res = comp.Open(HKEY_CURRENT_USER, rootreg+"\\Components\\"+progidstr, KEY_READ); if(res == ERROR_SUCCESS) { mode = REGACCESS_USER; res = acomp.Open(comp,"Associated", KEY_READ); if(res == ERROR_SUCCESS) res = acomp.QueryValue( parc, NULL, NULL, &dummy); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); } } if(mode & RM_SYSDOREAD) { CRegKey comp, acomp; res = comp.Open(HKEY_LOCAL_MACHINE, rootreg+"\\Components\\"+progidstr, KEY_READ); if(res == ERROR_SUCCESS) res = acomp.Open(comp,"Associated", KEY_READ); if(res == ERROR_SUCCESS) res = acomp.QueryValue( parc, NULL, NULL, &dummy); if(res != ERROR_SUCCESS && res != ERROR_ACCESS_DENIED && res != ERROR_FILE_NOT_FOUND) ERRTHROW(res); } if(is_ass) *is_ass = (res == ERROR_SUCCESS) ? VARIANT_TRUE : VARIANT_FALSE; VARIANT_BOOL can = VARIANT_FALSE; CComBSTR pars; get_ComponentExtraInfo(mode,progid,CComBSTR("Paradigm"), &pars); if(!pars && !(type & COMPONENTTYPE_SCRIPT)) { CComPtr<IMgaComponent> comp; CreateMgaComponent(comp, progid); if(!comp) COMTHROW(E_NOTFOUND); COMTHROW(comp->get_Paradigm(&pars)); put_ComponentExtraInfo(REGACCESS_BOTH, progid, CComBSTR("Paradigm"), pars); // just try } if(!pars) { can = type & COMPONENTTYPE_PARADIGM_INDEPENDENT ? VARIANT_TRUE : VARIANT_FALSE; } else if(!wcscmp(pars, L"*")) { can = VARIANT_TRUE; } else { can = VARIANT_FALSE; const OLECHAR *p = wcstok(pars, L" \n\t"); while(p) { if(!_wcsicmp(p, paradigm)) { can = VARIANT_TRUE; break; } p = wcstok(NULL, L" \n\t"); } } if(can_ass) *can_ass = can; } COMCATCH(;) } // --- Actions typedef HRESULT (STDAPICALLTYPE *CTLREGPROC)(); STDMETHODIMP CMgaRegistrar::RegisterComponentLibrary(BSTR path, regaccessmode_enum mode) { COMTRY { HMODULE hModule = LoadLibrary(CString(path)); if( hModule == 0 ) HR_THROW(E_FAIL); CTLREGPROC DLLRegisterServer = (CTLREGPROC)::GetProcAddress(hModule,"DllRegisterServer" ); if( DLLRegisterServer == NULL ) { FreeLibrary(hModule); //CLR dll: using namespace MgaDotNetServices; CComPtr<_Registrar> reg; COMTHROW(reg.CoCreateInstance(L"MGA.DotNetRegistrar")); try { reg->Register(_bstr_t(path)); } catch (_com_error& e) { SetErrorInfo(e.Error(), e.Description()); return e.Error(); } return S_OK; } else { //c++ dll: COMTHROW( DLLRegisterServer() ); FreeLibrary(hModule); } CComObjPtr<ITypeLib> typelib; COMTHROW( LoadTypeLibEx(path, REGKIND_REGISTER, PutOut(typelib)) ); UINT index = typelib->GetTypeInfoCount(); while( index-- > 0 ) { CComObjPtr<ITypeInfo> typeinfo; COMTHROW( typelib->GetTypeInfo(index, PutOut(typeinfo)) ); TYPEATTR *typeattr = NULL; COMTHROW( typeinfo->GetTypeAttr(&typeattr) ); ASSERT( typeattr != NULL ); try { if( typeattr->typekind == TKIND_COCLASS ) { CComPtr<IMgaComponent> component; // if( SUCCEEDED(typeinfo->CreateInstance(NULL, // __uuidof(IMgaComponent), (void**)PutOut(component))) ) if (SUCCEEDED(CreateMgaComponent(component, typeattr->guid))) { CComBstrObj desc; COMTHROW( component->get_ComponentName(PutOut(desc)) ); componenttype_enum type; COMTHROW( component->get_ComponentType(&type) ); LPOLESTR olestr; COMTHROW( ProgIDFromCLSID(typeattr->guid, &olestr) ); CComBstrObj progid(olestr); { LPOLESTR pp = olestr + wcslen(olestr) - 2; if(wcslen(olestr) > 2 && pp[0] == '.' && isdigit(pp[1]) ) { pp[0] = 0; CLSID tempGUID; HRESULT hr = CLSIDFromProgID(olestr, &tempGUID); if(hr == S_OK && tempGUID == typeattr->guid) { progid = olestr; } } } COMTHROW( RegisterComponent(progid, type, desc, mode) ); CoTaskMemFree(olestr); CString paradigms; COMTHROW( component->get_Paradigm(PutOut(paradigms)) ); paradigms += ' '; paradigms.TrimLeft(" \n\t"); while( !paradigms.IsEmpty() ) { int i = paradigms.FindOneOf(" \n\t"); ASSERT( i > 0 ); if(paradigms.Left(i).Compare("*")) { COMTHROW( Associate(progid, PutInBstr(paradigms.Left(i)), mode) ); } paradigms = paradigms.Mid(i); paradigms.TrimLeft(" \n\t"); } } } typeinfo->ReleaseTypeAttr(typeattr); } catch(hresult_exception &) { typeinfo->ReleaseTypeAttr(typeattr); throw; } } } COMCATCH(;) } STDMETHODIMP CMgaRegistrar::UnregisterComponentLibrary(BSTR path, regaccessmode_enum mode) { COMTRY { CComObjPtr<ITypeLib> typelib; COMTHROW( LoadTypeLibEx(path, REGKIND_NONE, PutOut(typelib)) ); UINT index = typelib->GetTypeInfoCount(); while( index) //WAS: while( --index >= 0 ) // was an infinite loop with UINT { --index; CComObjPtr<ITypeInfo> typeinfo; COMTHROW( typelib->GetTypeInfo(index, PutOut(typeinfo)) );// index parameter with the range of 0 to GetTypeInfoCount() –1. TYPEATTR *typeattr = NULL; COMTHROW( typeinfo->GetTypeAttr(&typeattr) ); ASSERT( typeattr != NULL ); try { if( typeattr->typekind == TKIND_COCLASS ) { LPOLESTR olestr; if( SUCCEEDED(ProgIDFromCLSID(typeattr->guid, &olestr)) ) { CComBstrObj progid(olestr); COMTHROW( UnregisterComponent(progid, mode) ); } } typeinfo->ReleaseTypeAttr(typeattr); } catch(hresult_exception &) { typeinfo->ReleaseTypeAttr(typeattr); throw; } } // TODO: unregister the type library } COMCATCH(;) } */
[ "graham.hemingway@8932de9b-a0df-7518-fb39-9aee4a96b462", "kevin.m.smyth@8932de9b-a0df-7518-fb39-9aee4a96b462" ]
[ [ [ 1, 137 ], [ 139, 374 ], [ 376, 2909 ] ], [ [ 138, 138 ], [ 375, 375 ] ] ]
7cf96617b01ccdd8bb88e694e038c2b8812567ac
b7c505dcef43c0675fd89d428e45f3c2850b124f
/Src/SimulatorQt/Util/qt/Win32/include/Qt/qatomic_x86_64.h
243ffa86e97029f7113a21ee9192e02fc6cd700e
[ "BSD-2-Clause" ]
permissive
pranet/bhuman2009fork
14e473bd6e5d30af9f1745311d689723bfc5cfdb
82c1bd4485ae24043aa720a3aa7cb3e605b1a329
refs/heads/master
2021-01-15T17:55:37.058289
2010-02-28T13:52:56
2010-02-28T13:52:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,353
h
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QATOMIC_X86_64_H #define QATOMIC_X86_64_H QT_BEGIN_HEADER QT_BEGIN_NAMESPACE #define Q_ATOMIC_INT_REFERENCE_COUNTING_IS_ALWAYS_NATIVE #define Q_ATOMIC_INT_REFERENCE_COUNTING_IS_WAIT_FREE inline bool QBasicAtomicInt::isReferenceCountingNative() { return true; } inline bool QBasicAtomicInt::isReferenceCountingWaitFree() { return true; } #define Q_ATOMIC_INT_TEST_AND_SET_IS_ALWAYS_NATIVE #define Q_ATOMIC_INT_TEST_AND_SET_IS_WAIT_FREE inline bool QBasicAtomicInt::isTestAndSetNative() { return true; } inline bool QBasicAtomicInt::isTestAndSetWaitFree() { return true; } #define Q_ATOMIC_INT_FETCH_AND_STORE_IS_ALWAYS_NATIVE #define Q_ATOMIC_INT_FETCH_AND_STORE_IS_WAIT_FREE inline bool QBasicAtomicInt::isFetchAndStoreNative() { return true; } inline bool QBasicAtomicInt::isFetchAndStoreWaitFree() { return true; } #define Q_ATOMIC_INT_FETCH_AND_ADD_IS_ALWAYS_NATIVE #define Q_ATOMIC_INT_FETCH_AND_ADD_IS_WAIT_FREE inline bool QBasicAtomicInt::isFetchAndAddNative() { return true; } inline bool QBasicAtomicInt::isFetchAndAddWaitFree() { return true; } #define Q_ATOMIC_POINTER_TEST_AND_SET_IS_ALWAYS_NATIVE #define Q_ATOMIC_POINTER_TEST_AND_SET_IS_WAIT_FREE template <typename T> Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::isTestAndSetNative() { return true; } template <typename T> Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::isTestAndSetWaitFree() { return true; } #define Q_ATOMIC_POINTER_FETCH_AND_STORE_IS_ALWAYS_NATIVE #define Q_ATOMIC_POINTER_FETCH_AND_STORE_IS_WAIT_FREE template <typename T> Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::isFetchAndStoreNative() { return true; } template <typename T> Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::isFetchAndStoreWaitFree() { return true; } #define Q_ATOMIC_POINTER_FETCH_AND_ADD_IS_ALWAYS_NATIVE #define Q_ATOMIC_POINTER_FETCH_AND_ADD_IS_WAIT_FREE template <typename T> Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::isFetchAndAddNative() { return true; } template <typename T> Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::isFetchAndAddWaitFree() { return true; } #if defined(Q_CC_GNU) || defined(Q_CC_INTEL) inline bool QBasicAtomicInt::ref() { unsigned char ret; asm volatile("lock\n" "incl %0\n" "setne %1" : "=m" (_q_value), "=qm" (ret) : "m" (_q_value) : "memory"); return ret != 0; } inline bool QBasicAtomicInt::deref() { unsigned char ret; asm volatile("lock\n" "decl %0\n" "setne %1" : "=m" (_q_value), "=qm" (ret) : "m" (_q_value) : "memory"); return ret != 0; } inline bool QBasicAtomicInt::testAndSetOrdered(int expectedValue, int newValue) { unsigned char ret; asm volatile("lock\n" "cmpxchgl %3,%2\n" "sete %1\n" : "=a" (newValue), "=qm" (ret), "+m" (_q_value) : "r" (newValue), "0" (expectedValue) : "memory"); return ret != 0; } inline int QBasicAtomicInt::fetchAndStoreOrdered(int newValue) { asm volatile("xchgl %0,%1" : "=r" (newValue), "+m" (_q_value) : "0" (newValue) : "memory"); return newValue; } inline int QBasicAtomicInt::fetchAndAddOrdered(int valueToAdd) { asm volatile("lock\n" "xaddl %0,%1" : "=r" (valueToAdd), "+m" (_q_value) : "0" (valueToAdd) : "memory"); return valueToAdd; } template <typename T> Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::testAndSetOrdered(T *expectedValue, T *newValue) { unsigned char ret; asm volatile("lock\n" "cmpxchgq %3,%2\n" "sete %1\n" : "=a" (newValue), "=qm" (ret), "+m" (_q_value) : "r" (newValue), "0" (expectedValue) : "memory"); return ret != 0; } template <typename T> Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndStoreOrdered(T *newValue) { asm volatile("xchgq %0,%1" : "=r" (newValue), "+m" (_q_value) : "0" (newValue) : "memory"); return newValue; } template <typename T> Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndAddOrdered(qptrdiff valueToAdd) { asm volatile("lock\n" "xaddq %0,%1" : "=r" (valueToAdd), "+m" (_q_value) : "0" (valueToAdd * sizeof(T)) : "memory"); return reinterpret_cast<T *>(valueToAdd); } #else // !Q_CC_INTEL && !Q_CC_GNU extern "C" { Q_CORE_EXPORT int q_atomic_test_and_set_int(volatile int *ptr, int expected, int newval); Q_CORE_EXPORT int q_atomic_test_and_set_ptr(volatile void *ptr, void *expected, void *newval); Q_CORE_EXPORT int q_atomic_increment(volatile int *ptr); Q_CORE_EXPORT int q_atomic_decrement(volatile int *ptr); Q_CORE_EXPORT int q_atomic_set_int(volatile int *ptr, int newval); Q_CORE_EXPORT void *q_atomic_set_ptr(volatile void *ptr, void *newval); Q_CORE_EXPORT int q_atomic_fetch_and_add_int(volatile int *ptr, int value); Q_CORE_EXPORT void *q_atomic_fetch_and_add_ptr(volatile void *ptr, qptrdiff value); } // extern "C" inline bool QBasicAtomicInt::ref() { return q_atomic_increment(&_q_value) != 0; } inline bool QBasicAtomicInt::deref() { return q_atomic_decrement(&_q_value) != 0; } inline bool QBasicAtomicInt::testAndSetOrdered(int expected, int newval) { return q_atomic_test_and_set_int(&_q_value, expected, newval) != 0; } inline int QBasicAtomicInt::fetchAndStoreOrdered(int newval) { return q_atomic_set_int(&_q_value, newval); } inline int QBasicAtomicInt::fetchAndAddOrdered(int aValue) { return q_atomic_fetch_and_add_int(&_q_value, aValue); } template <typename T> Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::testAndSetOrdered(T *expectedValue, T *newValue) { return q_atomic_test_and_set_ptr(&_q_value, expectedValue, newValue); } template <typename T> Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndStoreOrdered(T *newValue) { return reinterpret_cast<T *>(q_atomic_set_ptr(&_q_value, newValue)); } template <typename T> Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndAddOrdered(qptrdiff valueToAdd) { return reinterpret_cast<T *>(q_atomic_fetch_and_add_ptr(&_q_value, valueToAdd * sizeof(T))); } #endif // Q_CC_GNU || Q_CC_INTEL inline bool QBasicAtomicInt::testAndSetRelaxed(int expectedValue, int newValue) { return testAndSetOrdered(expectedValue, newValue); } inline bool QBasicAtomicInt::testAndSetAcquire(int expectedValue, int newValue) { return testAndSetOrdered(expectedValue, newValue); } inline bool QBasicAtomicInt::testAndSetRelease(int expectedValue, int newValue) { return testAndSetOrdered(expectedValue, newValue); } inline int QBasicAtomicInt::fetchAndStoreRelaxed(int newValue) { return fetchAndStoreOrdered(newValue); } inline int QBasicAtomicInt::fetchAndStoreAcquire(int newValue) { return fetchAndStoreOrdered(newValue); } inline int QBasicAtomicInt::fetchAndStoreRelease(int newValue) { return fetchAndStoreOrdered(newValue); } inline int QBasicAtomicInt::fetchAndAddRelaxed(int valueToAdd) { return fetchAndAddOrdered(valueToAdd); } inline int QBasicAtomicInt::fetchAndAddAcquire(int valueToAdd) { return fetchAndAddOrdered(valueToAdd); } inline int QBasicAtomicInt::fetchAndAddRelease(int valueToAdd) { return fetchAndAddOrdered(valueToAdd); } template <typename T> Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::testAndSetRelaxed(T *expectedValue, T *newValue) { return testAndSetOrdered(expectedValue, newValue); } template <typename T> Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::testAndSetAcquire(T *expectedValue, T *newValue) { return testAndSetOrdered(expectedValue, newValue); } template <typename T> Q_INLINE_TEMPLATE bool QBasicAtomicPointer<T>::testAndSetRelease(T *expectedValue, T *newValue) { return testAndSetOrdered(expectedValue, newValue); } template <typename T> Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndStoreRelaxed(T *newValue) { return fetchAndStoreOrdered(newValue); } template <typename T> Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndStoreAcquire(T *newValue) { return fetchAndStoreOrdered(newValue); } template <typename T> Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndStoreRelease(T *newValue) { return fetchAndStoreOrdered(newValue); } template <typename T> Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndAddRelaxed(qptrdiff valueToAdd) { return fetchAndAddOrdered(valueToAdd); } template <typename T> Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndAddAcquire(qptrdiff valueToAdd) { return fetchAndAddOrdered(valueToAdd); } template <typename T> Q_INLINE_TEMPLATE T *QBasicAtomicPointer<T>::fetchAndAddRelease(qptrdiff valueToAdd) { return fetchAndAddOrdered(valueToAdd); } QT_END_NAMESPACE QT_END_HEADER #endif // QATOMIC_X86_64_H
[ "alon@rogue.(none)" ]
[ [ [ 1, 363 ] ] ]
a09821dcbbbe0d3442bc338f61f8410c0c0ee6b8
0f8559dad8e89d112362f9770a4551149d4e738f
/Wall_Destruction/Havok/Source/Animation/Animation/Rig/hkaSkeleton.inl
318c5a328326898bc9ed79d576af7f34737d0523
[]
no_license
TheProjecter/olafurabertaymsc
9360ad4c988d921e55b8cef9b8dcf1959e92d814
456d4d87699342c5459534a7992f04669e75d2e1
refs/heads/master
2021-01-10T15:15:49.289873
2010-09-20T12:58:48
2010-09-20T12:58:48
45,933,002
0
0
null
null
null
null
UTF-8
C++
false
false
2,299
inl
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ HK_FORCE_INLINE hkaSkeleton::LocalFrameOnBone::LocalFrameOnBone() { } HK_FORCE_INLINE hkaSkeleton::LocalFrameOnBone::LocalFrameOnBone( hkFinishLoadedObjectFlag f ) : m_localFrame(f) { } HK_FORCE_INLINE hkaSkeleton::hkaSkeleton() { } HK_FORCE_INLINE hkaSkeleton::hkaSkeleton( const hkaSkeleton& skel ) : hkReferencedObject(skel) { m_name = skel.m_name; m_parentIndices = skel.m_parentIndices; m_bones = skel.m_bones; m_referencePose = skel.m_referencePose; m_floatSlots = skel.m_floatSlots; m_localFrames = skel.m_localFrames; } HK_FORCE_INLINE hkaSkeleton::hkaSkeleton(hkFinishLoadedObjectFlag f) : hkReferencedObject(f), m_name(f), m_parentIndices(f), m_bones(f), m_referencePose(f), m_floatSlots(f), m_localFrames(f) { } HK_FORCE_INLINE hkLocalFrame* hkaSkeleton::getLocalFrameForBone( int boneIndex ) const { for( int i = 0; i < m_localFrames.getSize(); i++ ) { if ( m_localFrames[i].m_boneIndex == boneIndex ) { return m_localFrames[i].m_localFrame; } else if ( m_localFrames[i].m_boneIndex > boneIndex ) { break; } } return HK_NULL; } /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20091222) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
[ [ [ 1, 71 ] ] ]
4f25a09d353751fc8ed492cc0d52fcc511bc060e
6188f1aaaf5508e046cde6da16b56feb3d5914bc
/branches/CamFighter 1.0/Graphics/OGL/Extensions/ARB_fragment_shader.cpp
4ea9b45a11c7a96bc88638db09ff9bb4fda2083e
[]
no_license
dogtwelve/fighter3d
7bb099f0dc396e8224c573743ee28c54cdd3d5a2
c073194989bc1589e4aa665714c5511f001e6400
refs/heads/master
2021-04-30T15:58:11.300681
2011-06-27T18:51:30
2011-06-27T18:51:30
33,675,635
1
0
null
null
null
null
UTF-8
C++
false
false
142
cpp
#include "ARB_fragment_shader.h" bool GL_init_ARB_fragment_shader(void) { return GLExtensions::Exists("GL_ARB_fragment_shader"); }
[ "dmaciej1@f75eed02-8a0f-11dd-b20b-83d96e936561" ]
[ [ [ 1, 6 ] ] ]
4869ee1becec273b7750bba1615f239b43caef91
ffe0a7d058b07d8f806d610fc242d1027314da23
/V3e/dev/IRCCmd.h
91fb8a103b33985b8cad4c89ee1488a5ce4f1873
[]
no_license
Cybie/mangchat
27bdcd886894f8fdf2c8956444450422ea853211
2303d126245a2b4778d80dda124df8eff614e80e
refs/heads/master
2016-09-11T13:03:57.386786
2009-12-13T22:09:37
2009-12-13T22:09:37
32,145,077
0
0
null
null
null
null
UTF-8
C++
false
false
423
h
#ifndef _MC_IRC_CMD_H #define _MC_IRC_CMD_H #include "IRCMsg.h" class IRCCmd { public: IRCCmd(void){}; IRCCmd(IRCMsg *_msg){ msg = _msg; }; ~IRCCmd(void); public: void OnDefault(); void OnPrivMsg(); void OnNotice(); void OnConnect(); void OnJoin(); void OnPart(); void OnNick(); void OnKick(); void OnMode(); void OnQuit(); private: IRCMsg *msg; }; #endif
[ "cybraxcyberspace@dfcbb000-c142-0410-b1aa-f54c88fa44bd" ]
[ [ [ 1, 29 ] ] ]
73134d18a84ad2f8b8d89ab193912f84ecab2c97
61bcb936a14064e2a819269d25b5c09b92dad45f
/Reference/EDK_project/code/GUI/HIO/MainFrm.cpp
8fe67a12bb7e814e0b482aaccfadd5fc87707028
[]
no_license
lanxinwoaini/robotic-vision-631
47fe73588a5b51296b9ac7fbacd4a553e4fd8e34
fdb160a8498ec668a32116c655368d068110aba7
refs/heads/master
2021-01-10T08:06:58.829618
2011-04-20T15:19:06
2011-04-20T15:19:06
47,861,917
1
0
null
null
null
null
UTF-8
C++
false
false
5,205
cpp
// MainFrm.cpp : implementation of the CMainFrame class // #include "stdafx.h" #include "HIO.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CMainFrame IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd) BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd) ON_WM_CREATE() ON_COMMAND(ID_HELIOS_START, &CMainFrame::OnHeliosStart) ON_COMMAND(ID_HELIOS_STOP, &CMainFrame::OnHeliosStop) ON_WM_CLOSE() END_MESSAGE_MAP() static UINT indicators[] = { ID_SEPARATOR, // status line indicator ID_INDICATOR_CAPS, ID_INDICATOR_NUM, ID_INDICATOR_SCRL, }; // CMainFrame construction/destruction CMainFrame::CMainFrame() {} CMainFrame::~CMainFrame() {} int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CFrameWnd::OnCreate(lpCreateStruct) == -1) return -1; if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP | CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) || !m_wndToolBar.LoadToolBar(IDR_MAINFRAME)) { TRACE0("Failed to create toolbar\n"); return -1; // fail to create } if (!m_wndStatusBar.Create(this) || !m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT))) { TRACE0("Failed to create status bar\n"); return -1; // fail to create } // TODO: Delete these three lines if you don't want the toolbar to be dockable m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY); EnableDocking(CBRS_ALIGN_ANY); DockControlBar(&m_wndToolBar); return 0; } BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { if( !CFrameWnd::PreCreateWindow(cs) ) return FALSE; // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return TRUE; } // CMainFrame diagnostics #ifdef _DEBUG void CMainFrame::AssertValid() const { CFrameWnd::AssertValid(); } void CMainFrame::Dump(CDumpContext& dc) const { CFrameWnd::Dump(dc); } #endif //_DEBUG // CMainFrame message handlers void CMainFrame::OnHeliosStart() { HStart(); } void CMainFrame::OnHeliosStop() { HStop(); } void CMainFrame::OnClose() { // TODO: Preserve the position and size of my window WINDOWPLACEMENT wp; // before it is destroyed, save the position of the window wp.length = sizeof wp; if ( GetWindowPlacement(&wp) ) { if ( IsIconic() ) // never restore to Iconic state wp.showCmd = SW_SHOW ; if ((wp.flags & WPF_RESTORETOMAXIMIZED) != 0) // if maximized and maybe iconic restore maximized state wp.showCmd = SW_SHOWMAXIMIZED ; // and write it to the .INI file WriteWindowPlacement(&wp); } CFrameWnd::OnClose(); } void CMainFrame::ActivateFrame(int nCmdShow) { // nCmdShow is the normal show mode this frame should be in // translate default nCmdShow (-1) if (nCmdShow == -1) { if (!IsWindowVisible()) nCmdShow = SW_SHOWNORMAL; else if (IsIconic()) nCmdShow = SW_RESTORE; } // bring to top before showing BringToTop(nCmdShow); if (nCmdShow != -1) { // show the window as specified WINDOWPLACEMENT wp; if ( !ReadWindowPlacement(&wp) ) { ShowWindow(nCmdShow); } else { if ( nCmdShow != SW_SHOWNORMAL ) wp.showCmd = nCmdShow; SetWindowPlacement(&wp); // ShowWindow(wp.showCmd); } // and finally, bring to top after showing BringToTop(nCmdShow); } return ; } static char szSection[] = "Settings"; static char szWindowPos[] = "WindowPos"; static char szFormat[] = "%u,%u,%d,%d,%d,%d,%d,%d,%d,%d"; BOOL CMainFrame::ReadWindowPlacement(WINDOWPLACEMENT *pwp) { CString strBuffer; int nRead ; strBuffer = AfxGetApp()->GetProfileString(szSection, szWindowPos); if ( strBuffer.IsEmpty() ) return FALSE; nRead = sscanf_s(strBuffer, szFormat, &pwp->flags, &pwp->showCmd, &pwp->ptMinPosition.x, &pwp->ptMinPosition.y, &pwp->ptMaxPosition.x, &pwp->ptMaxPosition.y, &pwp->rcNormalPosition.left, &pwp->rcNormalPosition.top, &pwp->rcNormalPosition.right, &pwp->rcNormalPosition.bottom); if ( nRead != 10 ) return FALSE; pwp->length = sizeof(WINDOWPLACEMENT); return TRUE; } // Write a window placement to settings section of app's ini file. void CMainFrame::WriteWindowPlacement(WINDOWPLACEMENT *pwp) { char szBuffer[sizeof("-32767")*8 + sizeof("65535")*2]; int max = 1; CString s; sprintf_s(szBuffer, sizeof("-32767")*8 + sizeof("65535")*2, szFormat, pwp->flags, pwp->showCmd, pwp->ptMinPosition.x, pwp->ptMinPosition.y, pwp->ptMaxPosition.x, pwp->ptMaxPosition.y, pwp->rcNormalPosition.left, pwp->rcNormalPosition.top, pwp->rcNormalPosition.right, pwp->rcNormalPosition.bottom); AfxGetApp()->WriteProfileString(szSection, szWindowPos, szBuffer); }
[ [ [ 1, 221 ] ] ]
c62e3b03b405e042e8d5e7bd634851aa83babd58
4360326fcaad7f6d8349b676dc5f00cdf29f7144
/src/simulator/base_packet.h
e73d750e42fc8edf760e79eaa4f835017822d834
[]
no_license
raxter/WSN_SWEB_sim
04cfddaaaed05fed17822dcabb27dd2196744de8
545e7d1727d913d8b6b90990bda7023fbdd6370f
refs/heads/master
2020-04-05T23:44:14.001375
2009-05-25T02:10:36
2009-05-25T02:10:36
199,714
2
1
null
null
null
null
UTF-8
C++
false
false
889
h
#ifndef __WSN_SIMULATOR_BASE_PACKET_H__ #define __WSN_SIMULATOR_BASE_PACKET_H__ #include "nodes/base_node.h" namespace WSN { namespace Simulator { namespace PacketTypes { enum Type {NoType, Init, GrpInit, EnergyReq, EnergySend, DataReq, DataSend, HeadReAlloc}; const int numberOfTypes = 8; } /* TODO make const */ class BasePacket { public: protected: BasePacket (int signalDistance, PacketTypes::Type type, const Node::BaseNode& node, int dstId = -1, int dstGrpId = -1); public: virtual ~BasePacket (); public: const double signalDistance; /* packet data */ const int srcId; const int dstId; const int dstGrpId; const PacketTypes::Type type; int getSizeInBytes() const; protected: int size; // in bytes }; } /* end of namespace Simulator */ } /* end of namespace WSN */ #endif // __WSN_SIMULATOR_PACKET_H__
[ "richard@richard-laptop-old.(none)", "[email protected]" ]
[ [ [ 1, 31 ], [ 33, 50 ] ], [ [ 32, 32 ] ] ]
3de4805b12bcc61484f6f9b3b6f61873f5003485
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/zombie/nscene/src/nscene/nstreamgeometrynode_main.cc
71d744a515ccc760cdf4c9bfd203a6daf407913b
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,528
cc
#include "precompiled/pchnscene.h" //------------------------------------------------------------------------------ // nstreamgeometrynode_main.cc // (C) 2004 Conjurer Services, S.A. //------------------------------------------------------------------------------ #include "nscene/nstreamgeometrynode.h" #include "nscene/nbatchmeshloader.h" #include "kernel/nlogclass.h" nNebulaScriptClass(nStreamGeometryNode, "ngeometrynode"); //------------------------------------------------------------------------------ /** */ nStreamGeometryNode::nStreamGeometryNode() { this->SetWorldCoord(true); } //------------------------------------------------------------------------------ /** */ nStreamGeometryNode::~nStreamGeometryNode() { // empty } //------------------------------------------------------------------------------ /** */ void nStreamGeometryNode::BeginShapes(int num) { this->streamSlots.SetFixedSize(num); } //------------------------------------------------------------------------------ /** */ void nStreamGeometryNode::SetShapeAt(int index, const char *relPath) { this->streamSlots[index].refShapeNode = relPath; } //------------------------------------------------------------------------------ /** */ const char * nStreamGeometryNode::GetShapeAt(int index) { return this->streamSlots[index].refShapeNode.getname(); } //------------------------------------------------------------------------------ /** */ void nStreamGeometryNode::EndShapes() { // TODO- sum the number of slots resulting from all shapes * frequency } //------------------------------------------------------------------------------ /** */ int nStreamGeometryNode::GetNumShapes() { return this->streamSlots.Size(); } //------------------------------------------------------------------------------ /** */ void nStreamGeometryNode::SetUvPosAt(int index, int layer, const vector2& pos) { n_assert(layer < nGfxServer2::MaxTextureStages); this->streamSlots[index].textureTransform[layer].settranslation(pos); this->streamSlots[index].useTextureTransform[layer] = true; } //------------------------------------------------------------------------------ /** */ void nStreamGeometryNode::SetUvScaleAt(int index, int layer, const vector2& scale) { n_assert(layer < nGfxServer2::MaxTextureStages); this->streamSlots[index].textureTransform[layer].setscale(scale); this->streamSlots[index].useTextureTransform[layer] = true; } //------------------------------------------------------------------------------ /** */ void nStreamGeometryNode::SetFrequencyAt(int index, int frequency) { this->streamSlots[index].frequency = frequency; } //------------------------------------------------------------------------------ /** */ int nStreamGeometryNode::GetFrequencyAt(int index) { return this->streamSlots[index].frequency; } //------------------------------------------------------------------------------ /** */ bool nStreamGeometryNode::LoadResources() { //try to reuse the nStaticBatchNode resource loading implementation: //input: the meshes to batch, vertex components, number of copies of each //texture transform(s) for each slot, insert instance index as Indices[0] if (!this->refMesh.isvalid() && this->streamSlots.Size() > 0) { // get a new or shared mesh nMesh2* mesh = nGfxServer2::Instance()->NewMesh(this->GetFullName().Get()); n_assert(mesh); if (!mesh->IsLoaded()) { mesh->SetFilename(this->GetFullName().Get()); mesh->SetUsage(nMesh2::NeedsVertexShader|nMesh2::WriteOnce); mesh->SetResourceLoader(nBatchMeshLoader::Instance()->GetFullName().Get()); if (!mesh->Load()) { NLOG(resource, (0, "nStreamGeometryNode: Error loading batch: '%s'\n", this->GetFullName().Get())); mesh->Release(); return false; } } this->refMesh = mesh; } // initialize the slot map int numSlots = 0; for (int index = 0; index < this->streamSlots.Size(); ++index) { this->streamSlots[index].firstSlot = numSlots; numSlots += this->streamSlots[index].frequency; } this->instanceSlots.SetFixedSize(numSlots); this->positionPalette.SetFixedSize(numSlots); this->rotationPalette.SetFixedSize(numSlots); return nGeometryNode::LoadResources(); } //------------------------------------------------------------------------------ /** */ void nStreamGeometryNode::UnloadResources() { if (this->refMesh.isvalid()) { this->refMesh->Release(); this->refMesh.invalidate(); } return nGeometryNode::UnloadResources(); } //------------------------------------------------------------------------------ /** */ void nStreamGeometryNode::EntityCreated(nEntityObject* entityObject) { return nGeometryNode::EntityCreated(entityObject); } //------------------------------------------------------------------------------ /** */ void nStreamGeometryNode::EntityDestroyed(nEntityObject* entityObject) { return nGeometryNode::EntityDestroyed(entityObject); } //------------------------------------------------------------------------------ /** this should never be called- streamed geometry is always rendered through it primitive geometry node. */ void nStreamGeometryNode::Attach(nSceneGraph* sceneGraph, nEntityObject* entityObject) { //n_assert_always(); nGeometryNode::Attach(sceneGraph, entityObject); } //------------------------------------------------------------------------------ /** */ bool nStreamGeometryNode::Apply(nSceneGraph* /*sceneGraph*/) { //apply per-stream surface parameters //if nGeometryNode::Apply(sceneGraph); //TODO- set the geometry stream or whatever if (!this->refMesh.isvalid()) { return false; } nGfxServer2* gfxServer = nGfxServer2::Instance(); n_assert(this->refMesh->IsValid()); // set mesh, vertex and index range gfxServer->SetMesh(this->refMesh, this->refMesh); gfxServer->SetVertexRange(0, this->refMesh->GetNumVertices()); gfxServer->SetIndexRange(0, this->refMesh->GetNumIndices()); return false;//HACK to prevent subclass doing anything else } //------------------------------------------------------------------------------ /** */ bool nStreamGeometryNode::Render(nSceneGraph* sceneGraph, nEntityObject* /*entityObject*/) { if (!this->refMesh.isvalid()) { return false; } //knowing the node in behalf of which I'm being called now is easy, because //it is the one in the scene graph nGeometryNode* curGeometry = (nGeometryNode*) sceneGraph->GetCurrentNode(); n_assert(curGeometry->GetStreamId() == this->geometryId); if (curGeometry->GetStreamIndex() != -1) { //TODO- check that there are that many slots n_assert(curGeometry->GetStreamIndex() < this->streamSlots.Size()); this->instanceIndices.Append(sceneGraph->GetCurrentIndex()); //actual rendering is deferred until ::Flush() //where all instance information will have been collected //don't call this, per-instance parameters are not rendered: //nGeometryNode::Render(sceneGraph, entityObject); return false;//HACK to prevent subclass doing anything else } return false; } //------------------------------------------------------------------------------ /** */ bool nStreamGeometryNode::Flush(nSceneGraph* sceneGraph) { //return nGeometryNode::Flush(sceneGraph); if (this->instanceIndices.Size() > 0) { nGfxServer2* gfxServer = nGfxServer2::Instance(); nShader2* curShader = gfxServer->GetShader(); //TEMP- ensure that the shader is an instanced shader indeed if (!curShader->IsParameterUsed(nShaderState::InstPositionPalette) || !curShader->IsParameterUsed(nShaderState::InstRotationPalette)) { this->instanceIndices.Reset(); return false; } int curIndex = sceneGraph->GetCurrentIndex(); gfxServer->SetTransform(nGfxServer2::Model, matrix44()); // render as many times as needed while there are slots left to draw while (this->instanceIndices.Size() > 0) { if (this->RenderStreamSlots(sceneGraph, curShader)) { gfxServer->DrawIndexedNS(nGfxServer2::TriangleList);//this->GetPrimitiveType() } } sceneGraph->SetCurrentIndex(curIndex); return false;//HACK! to prevent subclass doing anything else } return false; } //------------------------------------------------------------------------------ /** This method fills the instance stream with shader parameters and removes instances from the array, until all possible slots are used. It is called until there are no instances left to draw. */ bool nStreamGeometryNode::RenderStreamSlots(nSceneGraph* sceneGraph, nShader2* curShader) { vector4 nullVec; this->instanceSlots.Fill(0, this->instanceSlots.Size(), -1); this->positionPalette.Fill(0, this->positionPalette.Size(), nullVec); this->rotationPalette.Fill(0, this->rotationPalette.Size(), nullVec); //1- fill the map of slots, -1 if slot not used for (int index = 0; index < this->instanceIndices.Size(); /*empty*/) { sceneGraph->SetCurrentIndex(this->instanceIndices[index]); nGeometryNode* curGeometry = (nGeometryNode*) sceneGraph->GetCurrentNode(); int streamIndex = curGeometry->GetStreamIndex(); n_assert(streamIndex != -1); //check if there are empty slots for this stream index const StreamSlot& streamSlot = this->streamSlots[streamIndex]; int slotIndex = streamSlot.firstSlot; int maxSlotIndex = streamSlot.firstSlot + streamSlot.frequency; while (this->instanceSlots.At(slotIndex) != -1 && slotIndex < maxSlotIndex) { ++slotIndex; } if (slotIndex < maxSlotIndex) { ncTransform* transform = (ncTransform*) sceneGraph->GetCurrentEntity()->GetComponent<ncTransform>(); // instance position + scale vector4 instPosScale(transform->GetPosition()); instPosScale.w = transform->GetScale().x; this->positionPalette.Set(slotIndex, instPosScale); // instance rotation vector4 instEuler(transform->GetEuler()); this->rotationPalette.Set(slotIndex, instEuler); this->instanceSlots.Set(slotIndex, this->instanceIndices[index]); this->instanceIndices.Erase(index); } else { ++index; } } //2- flush collected instance parameters into shader slots curShader->SetVector4Array(nShaderState::InstPositionPalette, this->positionPalette.Begin(), this->positionPalette.Size()); curShader->SetVector4Array(nShaderState::InstRotationPalette, this->rotationPalette.Begin(), this->rotationPalette.Size()); //TODO- return false to prevent drawing if no slot was filled return true; }
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 360 ] ] ]
3a5540a018d543a995bbbb858a132513f5ddcb47
4758b780dad736c20ec46e3e901ecdf5a0921c04
/vm/int/SourceCode/SIO_TCP.cpp
499e4461de218a08186e7be95314716c51372003
[]
no_license
arbv/kronos
8f165515e77851d98b0e60b04d4b64d5bc40f3ea
4974f865161b78161011cb92223bef45930261d9
refs/heads/master
2023-08-19T18:56:36.980449
2008-08-23T19:44:08
2008-08-23T19:44:08
97,011,574
1
1
null
2017-07-12T13:31:54
2017-07-12T13:31:54
null
UTF-8
C++
false
false
4,077
cpp
#include "preCompiled.h" #include <winsock2.h> #include "SIO_TCP.h" #include "cO_tcp.h" /////////////////////////////////////////////////////////////////////////////// // SioTcp. SioTcp::SioTcp(int addr, int ipt) : i(0), o(0) { o = new cO_tcp; i = new cI(addr, ipt, o); if (o == null || i == null) delete this; } SioTcp::~SioTcp() { if (i != null) { delete i; i = null; } if (o != null) { delete o; o = null; } } int SioTcp::addr() { return i->addr(); } int SioTcp::ipt() { return i->ipt(); } int SioTcp::inpIpt() { return i->inpIpt(); } int SioTcp::outIpt() { return i->outIpt(); } int SioTcp::inp(int addr) { return i->inp(addr); } void SioTcp::out(int addr, int data) { i->out(addr, data); } int SioTcp::busyRead() { return o->busyRead(); } void SioTcp::write(char *ptr, int bytes) { o->write(ptr, bytes); } void SioTcp::writeChar(char ch) { o->writeChar(ch); } // Ugly, need to do something about it:- int SioTcp::connect(dword so) { return ((cO_tcp*)o)->connect(so); } int SioTcp::connected() { return ((cO_tcp*)o)->connected(); } /////////////////////////////////////////////////////////////////////////////// // SioTcps - server side SioTcps::SioTcps(word p) : port(p), N(0) { } SioTcps::~SioTcps() { TerminateThread((HANDLE)thread, 0); } int SioTcps::addClient(SioTcp *p) { if (N >= max_tcp) return 0; rgtcp[N++] = p; return N; } void SioTcps::serve(dword so) { SioTcp *tcp = find(); if (tcp == NULL) { char *msg = "Active connection limit has been reached.\r\n" "Please try again later.\r\n" "Thank you, Kronos Group.\r\n"; send(so, msg, strlen(msg), 0); Sleep(2000); closesocket(so); } else { tcp->connect(so); } } dword SioTcps::Worker(void) { SOCKET so = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (so == INVALID_SOCKET) { dword dw = WSAGetLastError(); trace("socket: %d [%08X]\n", dw, dw); return dw; } SOCKADDR_IN sin; sin.sin_family = AF_INET; sin.sin_port = htons(port); sin.sin_addr.S_un.S_addr = 0; if (bind(so, (SOCKADDR *)&sin, sizeof(sin)) != 0) { dword dw = WSAGetLastError(); trace("bind: %d [%08X]\n", dw, dw); return dw; } if (listen(so, SOMAXCONN) != 0) { dword dw = WSAGetLastError(); trace("listen: %d [%08X]\n", dw, dw); return dw; } do { trace("Kronos server is accepting connections...\n"); SOCKADDR_IN sinClient; int sinLen = sizeof(sinClient); dword soClient = accept(so, (SOCKADDR *)&sinClient, &sinLen); if (soClient != INVALID_SOCKET) { trace("Connection from %d.%d.%d.%d\n", sinClient.sin_addr.S_un.S_un_b.s_b1, sinClient.sin_addr.S_un.S_un_b.s_b2, sinClient.sin_addr.S_un.S_un_b.s_b3, sinClient.sin_addr.S_un.S_un_b.s_b4); serve(soClient); } } while (sin.sin_addr.S_un.S_addr == 0); // John - you never get here. // May be you need shutdown() same as in IGD480 trace("Kronos server exiting...\n"); closesocket(so); return 0; } dword WINAPI ServerThread(void *param) { SioTcps *pst = (SioTcps *)param; return pst->Worker(); } int SioTcps::start() { WSADATA data; word nVersion = MAKEWORD(2,1); if (WSAStartup(nVersion, &data) != 0) { dword dw = WSAGetLastError(); trace("WSAStartup: %d [%08X]\n", dw, dw); return false; } dword id = 0; thread = (dword)CreateThread(NULL, 4096, ServerThread, (void *)this, 0, &id); return thread != NULL; } SioTcp *SioTcps::find() { for (int i = 0; i < N; ++i) { if (!rgtcp[i]->connected()) return rgtcp[i]; } return NULL; }
[ "leo.kuznetsov@4e16752f-1752-0410-94d0-8bc3fbd73b2e" ]
[ [ [ 1, 180 ] ] ]
5ce6b1733359bf170784065242e184475ba911a1
3daaefb69e57941b3dee2a616f62121a3939455a
/mgllib/src/2d/MglBitmapText.cpp
1668e1e793bc814215799b1780f7f6dfbf630914
[]
no_license
myun2ext/open-mgl-legacy
21ccadab8b1569af8fc7e58cf494aaaceee32f1e
8faf07bad37a742f7174b454700066d53a384eae
refs/heads/master
2016-09-06T11:41:14.108963
2009-12-28T12:06:58
2009-12-28T12:06:58
null
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
4,426
cpp
////////////////////////////////////////////////////////// // // MglBitmapText // - ビットマップテキスト表示クラス // ////////////////////////////////////////////////////////// #include "stdafx.h" #include "MglBitmapText.h" // コンストラクタ CMglBitmapText::CMglBitmapText() { m_myudg = NULL; m_nOneCharWidth = 0; m_nOneCharHeight = 0; initFlg = FALSE; } // デストラクタ CMglBitmapText::~CMglBitmapText() { } // 初期化 void CMglBitmapText::Init( CMglGraphicManager *in_myudg, const char* szBitmapFile, int nOneCharWidth, int nOneCharHeight, const char* szStringSequence ) { m_myudg = in_myudg; sfcBitmapFont.Init( m_myudg ); //sfcBitmapFont.CreateFromFile( szBitmapFile, FALSE ); sfcBitmapFont.Create( szBitmapFile, FALSE ); m_stringSequence = szStringSequence; m_nOneCharWidth = nOneCharWidth; m_nOneCharHeight = nOneCharHeight; initFlg = TRUE; } // 絵画 void CMglBitmapText::Draw( const char* szDrawString, float x, float y, D3DCOLOR color ) { InitCheck(); DrawEx( szDrawString, 1.0f, 1.0f, 0, 0, 0, x, y, color ); } // 絵画 void CMglBitmapText::Draw( int nDrawNum, float x, float y, D3DCOLOR color ) { char szDrawString[32]; sprintf( szDrawString, "%d", nDrawNum ); Draw( szDrawString, x, y, color ); } // 絵画Ex void CMglBitmapText::DrawEx( int nDrawNum, float fScaleX, float fScaleY, float fRotationCenterX, float fRotationCenterY, float fAngle, float x, float y, D3DCOLOR color, DWORD dwAlphaOption ) { char szDrawString[32]; sprintf( szDrawString, "%d", nDrawNum ); DrawEx( szDrawString, fScaleX, fScaleY, fRotationCenterX, fRotationCenterY, fAngle, x, y, color ); } // 絵画Ex void CMglBitmapText::DrawEx( const char* szDrawString, float fScaleX, float fScaleY, float fRotationCenterX, float fRotationCenterY, float fAngle, float x, float y, D3DCOLOR color, DWORD dwAlphaOption ) { //DrawEx2( szDrawString, m_nOneCharWidth * fScaleX, m_nOneCharHeight * fScaleX, // fScaleX, fScaleY, fRotationCenterX, fRotationCenterY, fAngle, x, y, color ); DrawEx2( szDrawString, 0, 0, fScaleX, fScaleY, fRotationCenterX, fRotationCenterY, fAngle, x, y, color ); } // 絵画Ex2 void CMglBitmapText::DrawEx2( int nDrawNum, int nCharSpace, int nLineSpace, float fScaleX, float fScaleY, float fRotationCenterX, float fRotationCenterY, float fAngle, float x, float y, D3DCOLOR color, DWORD dwAlphaOption ) { char szDrawString[32]; sprintf( szDrawString, "%d", nDrawNum ); DrawEx2( szDrawString, nCharSpace, nLineSpace, fScaleX, fScaleY, fRotationCenterX, fRotationCenterY, fAngle, x, y, color ); } // 絵画Ex2 void CMglBitmapText::DrawEx2( const char* szDrawString, int nCharSpace, int nLineSpace, float fScaleX, float fScaleY, float fRotationCenterX, float fRotationCenterY, float fAngle, float x, float y, D3DCOLOR color, DWORD dwAlphaOption ) { InitCheck(); int nDrawPosX = x; int nDrawPosY = y; int nWidthEx = m_nOneCharWidth * fScaleX + nCharSpace; // 一文字一文字の間隔 int nHeightEx = m_nOneCharHeight * fScaleY + nLineSpace; // 一文字一文字の間隔 // 絵画する文字列を一つ一つ見ていくループ for( const char* pDrawChar=szDrawString; *pDrawChar != '\0'; pDrawChar++ ) { // 改行だったら if ( *pDrawChar == '\n' ) { nDrawPosY += nHeightEx; nDrawPosX = x; continue; } int nBitmapLineNo = 0; int nBitmapXCount = 0; // ビットマップの文字列を一つ一つ見ていくループ for( const char* pBitmapChar=m_stringSequence.c_str(); *pBitmapChar != '\0'; pBitmapChar++ ) { // 改行だったら一行進める if ( *pBitmapChar == '\n' ) { nBitmapLineNo++; nBitmapXCount = 0; continue; } // 一致したら絵画 if ( *pBitmapChar == *pDrawChar ) { RECT rect; int nBitmapX = nBitmapXCount * m_nOneCharWidth; int nBitmapY = nBitmapLineNo * m_nOneCharHeight; _Rect2( nBitmapX, nBitmapY, m_nOneCharWidth, m_nOneCharHeight, &rect ); // 絵画 //sfcBitmapFont.DrawEx( fScaleX, fScaleY, fRotationCenterX, fRotationCenterY, fAngle, nDrawPosX, nDrawPosY, &rect, color ); sfcBitmapFont.Draw( nDrawPosX, nDrawPosY, &rect, color, fScaleX, fScaleY, fRotationCenterX, fRotationCenterY, fAngle ); break; } nBitmapXCount++; } nDrawPosX += nWidthEx; } }
[ "myun2@6d62ff88-fa28-0410-b5a4-834eb811a934" ]
[ [ [ 1, 142 ] ] ]
c5c70b0540fdc29f35c0101af0c68021a36836f5
0454def9ffc8db9884871a7bccbd7baa4322343b
/src/plugins/freecovers/QUFreeCoversSource.h
455726b2ac0e1b09afb47521088c7a7ea6d50f2a
[]
no_license
escaped/uman
e0187d1d78e2bb07dade7ef6ef041b6ed424a2d3
bedc1c6c4fc464be4669f03abc9bac93e7e442b0
refs/heads/master
2016-09-05T19:26:36.679240
2010-07-26T07:55:31
2010-07-26T07:55:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,160
h
#ifndef QUFREECOVERSSOURCE_H #define QUFREECOVERSSOURCE_H #include "QUMultilingualImageSource.h" class QUFreeCoversSource: public QUMultilingualImageSource { Q_OBJECT public: QUFreeCoversSource(QObject *parent = 0); virtual ImageType type() const { return CoverImage; } virtual QString name() const { return "FreeCovers"; } virtual QString version() const { return "1.0.0"; } virtual QString author() const { return "Marcel Taeumel"; } virtual QString description() const { return tr("The cd covers archive. No uncompressed covers."); } virtual QStringList songDataFields() const { return QStringList() << "First" << "Second" << "Third"; } virtual QStringList customDataFields() const { return QStringList(); } virtual QString help(const QString &field) const { return QString(); } virtual QStringList hosts() const; protected: virtual QString registryKey() const { return "freecovers"; } virtual QString defaultValue(const QString &key) const; virtual QMap<QString, QString> translationLocations() const; virtual QURemoteImageCollector* imageCollector(QUSongInterface*); }; #endif // QUFREECOVERSSOURCE_H
[ [ [ 1, 31 ] ] ]
d9aa72380eee8f90794b29bf1a1f480865ae150e
0b66a94448cb545504692eafa3a32f435cdf92fa
/tags/0.5/cbear.berlios.de/windows/registry/data.hpp
5ebbcd5776d20f4ef75516ab3fa135e3eb63e83d
[ "MIT" ]
permissive
BackupTheBerlios/cbear-svn
e6629dfa5175776fbc41510e2f46ff4ff4280f08
0109296039b505d71dc215a0b256f73b1a60b3af
refs/heads/master
2021-03-12T22:51:43.491728
2007-09-28T01:13:48
2007-09-28T01:13:48
40,608,034
0
0
null
null
null
null
UTF-8
C++
false
false
6,366
hpp
/* The MIT License Copyright (c) 2005 C Bear (http://cbear.berlios.de) 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 CBEAR_BERLIOS_DE_WINDOWS_REGISTRY_DATA_HPP_INCLUDED #define CBEAR_BERLIOS_DE_WINDOWS_REGISTRY_DATA_HPP_INCLUDED #pragma warning(push) #pragma warning(disable: 4512) #pragma warning(disable: 4100) // behavior change: an object of POD type constructed with an initializer of the // form () will be default-initialized #pragma warning(disable: 4345) // unreachable code #pragma warning(disable: 4702) #include <boost/variant.hpp> #pragma warning(pop) #include <cbear.berlios.de/policy/main.hpp> #include <cbear.berlios.de/windows/base.hpp> namespace cbear_berlios_de { namespace windows { namespace registry { namespace detail { class data_none {}; template<class Char> class data_variant { public: typedef boost::variant< data_none, dword_t, ulonglong_t, base::basic_string<Char> > type; }; } class data_id_type: public policy::wrap<data_id_type, dword_t> { typedef policy::wrap<data_id_type, dword_t> wrap_type; public: enum enumeration_type { // Binary data in any form. binary = REG_BINARY, // A 32-bit number. dword = REG_DWORD, // A 32-bit number in little-endian format. dword_little_endian = REG_DWORD_LITTLE_ENDIAN, // A 32-bit number in big-endian format. dword_big_endian = REG_DWORD_BIG_ENDIAN, // Null-terminated string that contains unexpanded references to // environment variables (for example, "%PATH%"). To expand the // environment variable references, use the ExpandEnvironmentStrings // function. expand_sz = REG_EXPAND_SZ, // Reserved for system use. link = REG_LINK, // Array of null-terminated strings, terminated by two null characters. multi_sz = REG_MULTI_SZ, // No defined value type. none = REG_NONE, // A 64-bit number. qword = REG_QWORD, // A 64-bit number in little-endian format. qword_little_endian = REG_QWORD_LITTLE_ENDIAN, // Null-terminated string. It will be a Unicode or ANSI string, depending on // whether you use the Unicode or ANSI functions. sz = REG_SZ, }; data_id_type() {} data_id_type(enumeration_type X): wrap_type(X) {} }; // Data. template<class Char> class data: public detail::data_variant<Char>::type { public: // Character. typedef Char char_type; // Base type. typedef typename detail::data_variant<char_type>::type base_type; // None type. typedef detail::data_none none_type; // Id type. typedef data_id_type id_type; class properties_type { public: typedef const byte_t *pointer_type; typedef dword_t size_type; id_type id; pointer_type begin; size_type size; properties_type(id_type id, pointer_type begin, size_type size): id(id), begin(begin), size(size) { } }; template<class Type> class traits; template<class Type, id_type::enumeration_type TypeId> class traits_helper { public: static const id_type::enumeration_type id = TypeId; static properties_type properties(const Type &X) { return properties_type( id, reinterpret_cast<properties_type::pointer_type>(&X), sizeof(Type)); } }; template<> class traits<none_type>: public traits_helper<none_type, id_type::none> { public: static properties_type properties(const none_type &) { return properties_type(id, 0, 0); } }; template<> class traits<dword_t>: public traits_helper<dword_t, id_type::dword> {}; template<> class traits<ulonglong_t>: public traits_helper<ulonglong_t, id_type::qword> { }; typedef base::basic_string<char_type> string_type; template<> class traits<string_type>: public traits_helper<string_type, id_type::sz> { public: static properties_type properties(const string_type &X) { typedef typename properties_type::size_type size_type; return properties_type( id, reinterpret_cast<properties_type::pointer_type>(X.c_str()), size_type((X.size() + 1) * sizeof(Char))); } }; template<std::size_t Size> class traits<char_type[Size]>: public traits_helper<char_type[Size], id_type::sz> { public: static properties_type properties(const char_type(&X)[Size]) { return properties_type( id, reinterpret_cast<properties_pointer::data_type>(X), Size * sizeof(char_type)); } }; template<> class traits<data> { private: class properties_visitor: public boost::static_visitor<properties_type> { public: template<class T> properties_type operator()(const T &X) const { return traits<T>::properties(X); } }; public: static properties_type properties(const data &X) { return boost::apply_visitor(properties_visitor(), X); } }; template<class T> static properties_type properties(const T &X) { return traits<T>::properties(X); } data &operator=(const data &X) { base_type::operator=(static_cast<const base_type &>(X)); return *this; } data() {} data(const data &X): base_type(static_cast<const base_type &>(X)) {} template<class T> data(const T &X): base_type(X) {} template<std::size_t Size> data(const char_type (&X)[Size]): base_type(string_type(X, Size - 1)) {} }; } } } #endif
[ "sergey_shandar@e6e9985e-9100-0410-869a-e199dc1b6838" ]
[ [ [ 1, 245 ] ] ]
fd4536d050c5e72a29b37bfbcd354f553dfa972e
c0a577ec612a721b324bb615c08882852b433949
/englishplayer/MP3Parser/puller.cpp
0c6c77b21f5d09001d6aaec8a41af601aec9c2b1
[]
no_license
guojerry/cppxml
ca87ca2e3e62cbe2a132d376ca784f148561a4cc
a4f8b7439e37b6f1f421445694c5a735f8beda71
refs/heads/master
2021-01-10T10:57:40.195940
2010-04-21T13:25:29
2010-04-21T13:25:29
52,403,012
0
0
null
null
null
null
UTF-8
C++
false
false
9,056
cpp
// a modification of //------------------------------------------------------------------------------ // File: PullPin.cpp // // Desc: DirectShow base classes - implements CPullPin class that pulls data // from IAsyncReader. // // Copyright (c) 1992-2001 Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ #include <streams.h> #include "parser.h" #include "puller.h" CPuller::CPuller(CParserFilter * parent) : m_pReader(NULL), m_pAlloc(NULL), m_State(TM_Exit), m_parent(parent) { } CPuller::~CPuller() { Disconnect(); } // returns S_OK if successfully connected to an IAsyncReader interface // from this object // Optional allocator should be proposed as a preferred allocator if // necessary HRESULT CPuller::Connect(IUnknown* pUnk, IMemAllocator* pAlloc, BOOL bSync) { CAutoLock lock(&m_AccessLock); if(m_pReader) { return VFW_E_ALREADY_CONNECTED; } HRESULT hr = pUnk->QueryInterface(IID_IAsyncReader, (void**)&m_pReader); if(FAILED(hr)) { return(hr); } hr = DecideAllocator(pAlloc, NULL); if(FAILED(hr)) { Disconnect(); return hr; } return S_OK; } // disconnect any connection made in Connect HRESULT CPuller::Disconnect() { CAutoLock lock(&m_AccessLock); StopThread(); if(m_pReader) { m_pReader->Release(); m_pReader = NULL; } if(m_pAlloc) { m_pAlloc->Release(); m_pAlloc = NULL; } return S_OK; } // agree an allocator using RequestAllocator - optional // props param specifies your requirements (non-zero fields). // returns an error code if fail to match requirements. // optional IMemAllocator interface is offered as a preferred allocator // but no error occurs if it can't be met. HRESULT CPuller::DecideAllocator( IMemAllocator * pAlloc, ALLOCATOR_PROPERTIES * pProps) { ALLOCATOR_PROPERTIES *pRequest; ALLOCATOR_PROPERTIES Request; if (pProps == NULL) { HRESULT hr = m_parent->DecideBufferSize(pAlloc, &Request); if FAILED(hr) return hr; pRequest = &Request; } else { pRequest = pProps; } HRESULT hr = m_pReader->RequestAllocator(pAlloc, pRequest, &m_pAlloc); return hr; } // start pulling data HRESULT CPuller::Active(void) { ASSERT(!ThreadExists()); return StartThread(); } // stop pulling data HRESULT CPuller::Inactive(void) { StopThread(); return S_OK; } int CPuller::StartSeek() { CAutoLock lock(&m_AccessLock); ThreadMsg AtStart = m_State; if(AtStart == TM_Start) { BeginFlush(); PauseThread(); EndFlush(); } return AtStart; } HRESULT CPuller::FinishSeek(int AtStart) { CAutoLock lock(&m_AccessLock); HRESULT hr = S_OK; if(AtStart == TM_Start) { hr = StartThread(); } return hr; } HRESULT CPuller::StartThread() { CAutoLock lock(&m_AccessLock); if(!m_pAlloc || !m_pReader) { return E_UNEXPECTED; } HRESULT hr; if(!ThreadExists()) { // commit allocator hr = m_pAlloc->Commit(); if(FAILED(hr)) { return hr; } // start thread if(!Create()) { return E_FAIL; } } m_State = TM_Start; hr = (HRESULT) CallWorker(m_State); return hr; } HRESULT CPuller::PauseThread() { CAutoLock lock(&m_AccessLock); if(!ThreadExists()) { return E_UNEXPECTED; } // need to flush to ensure the thread is not blocked // in WaitForNext HRESULT hr = m_pReader->BeginFlush(); if(FAILED(hr)) { return hr; } m_State = TM_Pause; hr = CallWorker(TM_Pause); m_pReader->EndFlush(); return hr; } HRESULT CPuller::StopThread() { CAutoLock lock(&m_AccessLock); if(!ThreadExists()) { return S_FALSE; } // need to flush to ensure the thread is not blocked // in WaitForNext HRESULT hr = m_pReader->BeginFlush(); if(FAILED(hr)) { return hr; } m_State = TM_Exit; hr = CallWorker(TM_Exit); m_pReader->EndFlush(); // wait for thread to completely exit Close(); // decommit allocator if(m_pAlloc) { m_pAlloc->Decommit(); } return S_OK; } DWORD CPuller::ThreadProc(void) { while(1) { DWORD cmd = GetRequest(); switch(cmd) { case TM_Exit: Reply(S_OK); return 0; case TM_Pause: // we are paused already Reply(S_OK); break; case TM_Start: Reply(S_OK); Process(); break; } // at this point, there should be no outstanding requests on the // upstream filter. // We should force begin/endflush to ensure that this is true. // !!!Note that we may currently be inside a BeginFlush/EndFlush pair // on another thread, but the premature EndFlush will do no harm now // that we are idle. m_pReader->BeginFlush(); CleanupCancelled(); m_pReader->EndFlush(); } } void CPuller::Process() { BOOL bDiscontinuity = TRUE; DWORD dwRequest; bool bContinue(true); while (bContinue) { // Break out without calling EndOfStream if we're asked to // do something different if(CheckRequest(&dwRequest)) { return; } IMediaSample* pSample; HRESULT hr = m_pAlloc->GetBuffer(&pSample, NULL, NULL, 0); if(FAILED(hr)) { OnError(hr); return; } if(bDiscontinuity) { pSample->SetDiscontinuity(TRUE); bDiscontinuity = FALSE; } hr = m_parent->FillSample(m_pReader, pSample); if(FAILED(hr)) { pSample->Release(); OnError(hr); return; } if (hr == S_FALSE) bContinue = false; hr = Receive(pSample); pSample->Release(); if(hr != S_OK) { if(FAILED(hr)) { OnError(hr); } return; } } EndOfStream(); } // after a flush, cancelled i/o will be waiting for collection // and release void CPuller::CleanupCancelled(void) { while(1) { IMediaSample * pSample; DWORD_PTR dwUnused; HRESULT hr = m_pReader->WaitForNext(0, // no wait &pSample, &dwUnused); if(pSample) { pSample->Release(); } else { // no more samples return; } } } // ================================================================= // Implements the CPuller class // ================================================================= HRESULT CPuller::Receive(IMediaSample *pIn) { return m_parent->Receive(pIn); } HRESULT CPuller::EndOfStream() { //Use this method to call IPin::EndOfStream on each downstream input pin that receives data from this object. //If your filter's output pin(s) derive from CBaseOutputPin, call the CBaseOutputPin::DeliverEndOfStream method. return m_parent->EndOfStream(); } HRESULT CPuller::BeginFlush() { // The CPuller::Seek method calls this method. Implement this method to call the IPin::BeginFlush method on // each downstream input pin that receives data from this object. If your filter's output pin(s) derive from // CBaseOutputPin, call the CBaseOutputPin::DeliverBeginFlush method. // This design enables the filter to seek the stream simply by calling Seek on the CPuller object. return m_parent->BeginFlush(); } HRESULT CPuller::EndFlush() { // The CPuller::Seek method calls this method. Implement this method to call the IPin::EndFlush method on // each downstream input pin that receives data from this object. If your filter's output pin(s) derive from // CBaseOutputPin, call the CBaseOutputPin::DeliverEndFlush method. // This design enables the filter to seek the stream simply by calling Seek on the CPuller object. return m_parent->EndFlush(); } void CPuller::OnError(HRESULT hr) { // The object calls this method whenever an error occurs that halts the data-pulling thread. The filter can use // this method to recover from streaming errors gracefully. In most cases, the error is returned from the upstream // filter, so the upstream filter is responsible for reporting it to the Filter Graph Manager. If the error occurs // inside the CPuller::Receive method, your filter should send an EC_ERRORABORT event. (See IMediaEventSink::Notify.) // TO DO return; }
[ "oeichenwei@0e9f5f58-6d57-11de-950b-9fccee66d0d9" ]
[ [ [ 1, 372 ] ] ]
8dafeef5a69337d9d054ebcc87c0f5cf2747f088
8f5d0d23e857e58ad88494806bc60c5c6e13f33d
/Models/cKeyFrame.cpp
53850845c17bd63ed94f80d851af4ce3ef128e20
[]
no_license
markglenn/projectlife
edb14754118ec7b0f7d83bd4c92b2e13070dca4f
a6fd3502f2c2713a8a1a919659c775db5309f366
refs/heads/master
2021-01-01T15:31:30.087632
2011-01-30T16:03:41
2011-01-30T16:03:41
1,704,290
1
1
null
null
null
null
UTF-8
C++
false
false
97
cpp
#include "ckeyframe.h" cKeyFrame::cKeyFrame(void) { } cKeyFrame::~cKeyFrame(void) { }
[ [ [ 1, 9 ] ] ]
2da7c389c4611340bd2769e20510d34a4fb338b4
33f59b1ba6b12c2dd3080b24830331c37bba9fe2
/Depend/Foundation/ImageAnalysis/Wm4ExtractSurfaceCubes.cpp
997b302227edf76c721e6b76ef81e2a72ac0fccc
[]
no_license
daleaddink/flagship3d
4835c223fe1b6429c12e325770c14679c42ae3c6
6cce5b1ff7e7a2d5d0df7aa0594a70d795c7979a
refs/heads/master
2021-01-15T16:29:12.196094
2009-11-01T10:18:11
2009-11-01T10:18:11
37,734,654
1
0
null
null
null
null
UTF-8
C++
false
false
30,729
cpp
// Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // The Wild Magic Version 4 Foundation Library source code is supplied // under the terms of the license agreement // http://www.geometrictools.com/License/Wm4FoundationLicense.pdf // and may not be copied or disclosed except in accordance with the terms // of that agreement. #include "Wm4FoundationPCH.h" #include "Wm4ExtractSurfaceCubes.h" using namespace Wm4; typedef std::map<Vector3f,int> VMap; typedef VMap::iterator VMapIterator; typedef std::map<TriangleKey,int> TMap; typedef TMap::iterator TMapIterator; //---------------------------------------------------------------------------- ExtractSurfaceCubes::ExtractSurfaceCubes(int iXBound, int iYBound, int iZBound, int* aiData) { assert(iXBound > 0 && iYBound > 0 && iZBound > 0 && aiData); m_iXBound = iXBound; m_iYBound = iYBound; m_iZBound = iZBound; m_iXYBound = iXBound*iYBound; m_aiData = aiData; } //---------------------------------------------------------------------------- void ExtractSurfaceCubes::ExtractContour (float fLevel, std::vector<Vector3f>& rkVA, std::vector<TriangleKey>& rkTA) { rkVA.clear(); rkTA.clear(); for (int iZ = 0; iZ < m_iZBound-1; iZ++) { for (int iY = 0; iY < m_iYBound-1; iY++) { for (int iX = 0; iX < m_iXBound-1; iX++) { // get vertices on edges of box (if any) VETable kTable; int iType = GetVertices(fLevel,iX,iY,iZ,kTable); if (iType != 0) { // get edges on faces of box GetXMinEdges(iX,iY,iZ,iType,kTable); GetXMaxEdges(iX,iY,iZ,iType,kTable); GetYMinEdges(iX,iY,iZ,iType,kTable); GetYMaxEdges(iX,iY,iZ,iType,kTable); GetZMinEdges(iX,iY,iZ,iType,kTable); GetZMaxEdges(iX,iY,iZ,iType,kTable); // ear-clip the wireframe mesh kTable.RemoveTriangles(rkVA,rkTA); } } } } } //---------------------------------------------------------------------------- void ExtractSurfaceCubes::MakeUnique (std::vector<Vector3f>& rkVA, std::vector<TriangleKey>& rkTA) { int iVQuantity = (int)rkVA.size(); int iTQuantity = (int)rkTA.size(); if (iVQuantity == 0 || iTQuantity == 0) { return; } // use a hash table to generate unique storage VMap kVMap; VMapIterator pkVIter; for (int iV = 0, iNextVertex = 0; iV < iVQuantity; iV++) { // keep only unique vertices std::pair<VMapIterator,bool> kResult = kVMap.insert( std::make_pair(rkVA[iV],iNextVertex)); if (kResult.second == true) { iNextVertex++; } } // use a hash table to generate unique storage TMap kTMap; TMapIterator pkTIter; for (int iT = 0, iNextTriangle = 0; iT < iTQuantity; iT++) { // replace old vertex indices by new ones TriangleKey& rkTri = rkTA[iT]; pkVIter = kVMap.find(rkVA[rkTri.V[0]]); assert( pkVIter != kVMap.end() ); rkTri.V[0] = pkVIter->second; pkVIter = kVMap.find(rkVA[rkTri.V[1]]); assert( pkVIter != kVMap.end() ); rkTri.V[1] = pkVIter->second; pkVIter = kVMap.find(rkVA[rkTri.V[2]]); assert( pkVIter != kVMap.end() ); rkTri.V[2] = pkVIter->second; // keep only unique triangles std::pair<TMapIterator,bool> kResult = kTMap.insert( std::make_pair(rkTri,iNextTriangle)); if (kResult.second == true) { iNextTriangle++; } } // pack the vertices rkVA.resize(kVMap.size()); for (pkVIter = kVMap.begin(); pkVIter != kVMap.end(); pkVIter++) { rkVA[pkVIter->second] = pkVIter->first; } // pack the triangles rkTA.resize(kTMap.size()); for (pkTIter = kTMap.begin(); pkTIter != kTMap.end(); pkTIter++) { rkTA[pkTIter->second] = pkTIter->first; } } //---------------------------------------------------------------------------- void ExtractSurfaceCubes::OrientTriangles (std::vector<Vector3f>& rkVA, std::vector<TriangleKey>& rkTA, bool bSameDir) { for (int i = 0; i < (int)rkTA.size(); i++) { TriangleKey& rkTri = rkTA[i]; // get triangle vertices Vector3f kV0 = rkVA[rkTri.V[0]]; Vector3f kV1 = rkVA[rkTri.V[1]]; Vector3f kV2 = rkVA[rkTri.V[2]]; // construct triangle normal based on current orientation Vector3f kEdge1 = kV1 - kV0; Vector3f kEdge2 = kV2 - kV0; Vector3f kNormal = kEdge1.Cross(kEdge2); // get the image gradient at the vertices Vector3f kGrad0 = GetGradient(kV0); Vector3f kGrad1 = GetGradient(kV1); Vector3f kGrad2 = GetGradient(kV2); // compute the average gradient Vector3f kGradAvr = (kGrad0 + kGrad1 + kGrad2)/3.0f; // compute the dot product of normal and average gradient float fDot = kGradAvr.Dot(kNormal); // choose triangle orientation based on gradient direction int iSave; if (bSameDir) { if (fDot < 0.0f) { // wrong orientation, reorder it iSave = rkTri.V[1]; rkTri.V[1] = rkTri.V[2]; rkTri.V[2] = iSave; } } else { if (fDot > 0.0f) { // wrong orientation, reorder it iSave = rkTri.V[1]; rkTri.V[1] = rkTri.V[2]; rkTri.V[2] = iSave; } } } } //---------------------------------------------------------------------------- void ExtractSurfaceCubes::ComputeNormals (const std::vector<Vector3f>& rkVA, const std::vector<TriangleKey>& rkTA, std::vector<Vector3f>& rkNA) { // maintain a running sum of triangle normals at each vertex int iVQuantity = (int)rkVA.size(); int iTQuantity = (int)rkTA.size(); rkNA.resize(iVQuantity); int i; for (i = 0; i < iVQuantity; i++) { rkNA[i] = Vector3f::ZERO; } for (i = 0; i < iTQuantity; i++) { const TriangleKey& rkT = rkTA[i]; Vector3f kV0 = rkVA[rkT.V[0]]; Vector3f kV1 = rkVA[rkT.V[1]]; Vector3f kV2 = rkVA[rkT.V[2]]; // construct triangle normal Vector3f kEdge1 = kV1 - kV0; Vector3f kEdge2 = kV2 - kV0; Vector3f kNormal = kEdge1.Cross(kEdge2); // maintain the sum of normals at each vertex rkNA[rkT.V[0]] += kNormal; rkNA[rkT.V[1]] += kNormal; rkNA[rkT.V[2]] += kNormal; } // The normal vector storage was used to accumulate the sum of // triangle normals. Now these vectors must be rescaled to be // unit length. for (i = 0; i < iVQuantity; i++) { rkNA[i].Normalize(); } } //---------------------------------------------------------------------------- int ExtractSurfaceCubes::GetVertices (float fLevel, int iX, int iY, int iZ, VETable& rkTable) { int iType = 0; // get image values at corners of voxel int i000 = iX + m_iXBound*(iY + m_iYBound*iZ); int i100 = i000 + 1; int i010 = i000 + m_iXBound; int i110 = i010 + 1; int i001 = i000 + m_iXYBound; int i101 = i001 + 1; int i011 = i001 + m_iXBound; int i111 = i011 + 1; float fF000 = (float)m_aiData[i000]; float fF100 = (float)m_aiData[i100]; float fF010 = (float)m_aiData[i010]; float fF110 = (float)m_aiData[i110]; float fF001 = (float)m_aiData[i001]; float fF101 = (float)m_aiData[i101]; float fF011 = (float)m_aiData[i011]; float fF111 = (float)m_aiData[i111]; float fX0 = (float)iX, fY0 = (float)iY, fZ0 = (float)iZ; float fX1 = fX0+1.0f, fY1 = fY0+1.0f, fZ1 = fZ0+1.0f; // xmin-ymin edge float fDiff0 = fLevel - fF000; float fDiff1 = fLevel - fF001; if (fDiff0*fDiff1 < 0.0f) { iType |= EB_XMIN_YMIN; rkTable.Insert(EI_XMIN_YMIN, Vector3f(fX0,fY0,fZ0+fDiff0/(fF001-fF000))); } // xmin-ymax edge fDiff0 = fLevel - fF010; fDiff1 = fLevel - fF011; if (fDiff0*fDiff1 < 0.0f) { iType |= EB_XMIN_YMAX; rkTable.Insert(EI_XMIN_YMAX, Vector3f(fX0,fY1,fZ0+fDiff0/(fF011-fF010))); } // xmax-ymin edge fDiff0 = fLevel - fF100; fDiff1 = fLevel - fF101; if (fDiff0*fDiff1 < 0.0f) { iType |= EB_XMAX_YMIN; rkTable.Insert(EI_XMAX_YMIN, Vector3f(fX1,fY0,fZ0+fDiff0/(fF101-fF100))); } // xmax-ymax edge fDiff0 = fLevel - fF110; fDiff1 = fLevel - fF111; if (fDiff0*fDiff1 < 0.0f) { iType |= EB_XMAX_YMAX; rkTable.Insert(EI_XMAX_YMAX, Vector3f(fX1,fY1,fZ0+fDiff0/(fF111-fF110))); } // xmin-zmin edge fDiff0 = fLevel - fF000; fDiff1 = fLevel - fF010; if (fDiff0*fDiff1 < 0.0f) { iType |= EB_XMIN_ZMIN; rkTable.Insert(EI_XMIN_ZMIN, Vector3f(fX0,fY0+fDiff0/(fF010-fF000),fZ0)); } // xmin-zmax edge fDiff0 = fLevel - fF001; fDiff1 = fLevel - fF011; if (fDiff0*fDiff1 < 0.0f) { iType |= EB_XMIN_ZMAX; rkTable.Insert(EI_XMIN_ZMAX, Vector3f(fX0,fY0+fDiff0/(fF011-fF001),fZ1)); } // xmax-zmin edge fDiff0 = fLevel - fF100; fDiff1 = fLevel - fF110; if (fDiff0*fDiff1 < 0.0f) { iType |= EB_XMAX_ZMIN; rkTable.Insert(EI_XMAX_ZMIN, Vector3f(fX1,fY0+fDiff0/(fF110-fF100),fZ0)); } // xmax-zmax edge fDiff0 = fLevel - fF101; fDiff1 = fLevel - fF111; if (fDiff0*fDiff1 < 0.0f) { iType |= EB_XMAX_ZMAX; rkTable.Insert(EI_XMAX_ZMAX, Vector3f(fX1,fY0+fDiff0/(fF111-fF101),fZ1)); } // ymin-zmin edge fDiff0 = fLevel - fF000; fDiff1 = fLevel - fF100; if (fDiff0*fDiff1 < 0.0f) { iType |= EB_YMIN_ZMIN; rkTable.Insert(EI_YMIN_ZMIN, Vector3f(fX0+fDiff0/(fF100-fF000),fY0,fZ0)); } // ymin-zmax edge fDiff0 = fLevel - fF001; fDiff1 = fLevel - fF101; if (fDiff0*fDiff1 < 0.0f) { iType |= EB_YMIN_ZMAX; rkTable.Insert(EI_YMIN_ZMAX, Vector3f(fX0+fDiff0/(fF101-fF001),fY0,fZ1)); } // ymax-zmin edge fDiff0 = fLevel - fF010; fDiff1 = fLevel - fF110; if (fDiff0*fDiff1 < 0.0f) { iType |= EB_YMAX_ZMIN; rkTable.Insert(EI_YMAX_ZMIN, Vector3f(fX0+fDiff0/(fF110-fF010),fY1,fZ0)); } // ymax-zmax edge fDiff0 = fLevel - fF011; fDiff1 = fLevel - fF111; if (fDiff0*fDiff1 < 0.0f) { iType |= EB_YMAX_ZMAX; rkTable.Insert(EI_YMAX_ZMAX, Vector3f(fX0+fDiff0/(fF111-fF011),fY1,fZ1)); } return iType; } //---------------------------------------------------------------------------- void ExtractSurfaceCubes::GetXMinEdges (int iX, int iY, int iZ, int iType, VETable& rkTable) { int iFaceType = 0; if (iType & EB_XMIN_YMIN) { iFaceType |= 0x01; } if (iType & EB_XMIN_YMAX) { iFaceType |= 0x02; } if (iType & EB_XMIN_ZMIN) { iFaceType |= 0x04; } if (iType & EB_XMIN_ZMAX) { iFaceType |= 0x08; } switch (iFaceType) { case 0: return; case 3: rkTable.Insert(EI_XMIN_YMIN,EI_XMIN_YMAX); break; case 5: rkTable.Insert(EI_XMIN_YMIN,EI_XMIN_ZMIN); break; case 6: rkTable.Insert(EI_XMIN_YMAX,EI_XMIN_ZMIN); break; case 9: rkTable.Insert(EI_XMIN_YMIN,EI_XMIN_ZMAX); break; case 10: rkTable.Insert(EI_XMIN_YMAX,EI_XMIN_ZMAX); break; case 12: rkTable.Insert(EI_XMIN_ZMIN,EI_XMIN_ZMAX); break; case 15: { // four vertices, one per edge, need to disambiguate int i = iX + m_iXBound*(iY + m_iYBound*iZ); int iF00 = m_aiData[i]; // F(x,y,z) i += m_iXBound; int iF10 = m_aiData[i]; // F(x,y+1,z) i += m_iXYBound; int iF11 = m_aiData[i]; // F(x,y+1,z+1) i -= m_iXBound; int iF01 = m_aiData[i]; // F(x,y,z+1) int iDet = iF00*iF11 - iF01*iF10; if (iDet > 0) { // disjoint hyperbolic segments, pair <P0,P2>, <P1,P3> rkTable.Insert(EI_XMIN_YMIN,EI_XMIN_ZMIN); rkTable.Insert(EI_XMIN_YMAX,EI_XMIN_ZMAX); } else if (iDet < 0) { // disjoint hyperbolic segments, pair <P0,P3>, <P1,P2> rkTable.Insert(EI_XMIN_YMIN,EI_XMIN_ZMAX); rkTable.Insert(EI_XMIN_YMAX,EI_XMIN_ZMIN); } else { // plus-sign configuration, add branch point to tessellation rkTable.Insert(FI_XMIN,Vector3f(rkTable.GetX(EI_XMIN_ZMIN), rkTable.GetY(EI_XMIN_ZMIN),rkTable.GetZ(EI_XMIN_YMIN))); // add edges sharing the branch point rkTable.Insert(EI_XMIN_YMIN,FI_XMIN); rkTable.Insert(EI_XMIN_YMAX,FI_XMIN); rkTable.Insert(EI_XMIN_ZMIN,FI_XMIN); rkTable.Insert(EI_XMIN_ZMAX,FI_XMIN); } break; } default: assert(false); } } //---------------------------------------------------------------------------- void ExtractSurfaceCubes::GetXMaxEdges (int iX, int iY, int iZ, int iType, VETable& rkTable) { int iFaceType = 0; if (iType & EB_XMAX_YMIN) { iFaceType |= 0x01; } if (iType & EB_XMAX_YMAX) { iFaceType |= 0x02; } if (iType & EB_XMAX_ZMIN) { iFaceType |= 0x04; } if (iType & EB_XMAX_ZMAX) { iFaceType |= 0x08; } switch (iFaceType) { case 0: return; case 3: rkTable.Insert(EI_XMAX_YMIN,EI_XMAX_YMAX); break; case 5: rkTable.Insert(EI_XMAX_YMIN,EI_XMAX_ZMIN); break; case 6: rkTable.Insert(EI_XMAX_YMAX,EI_XMAX_ZMIN); break; case 9: rkTable.Insert(EI_XMAX_YMIN,EI_XMAX_ZMAX); break; case 10: rkTable.Insert(EI_XMAX_YMAX,EI_XMAX_ZMAX); break; case 12: rkTable.Insert(EI_XMAX_ZMIN,EI_XMAX_ZMAX); break; case 15: { // four vertices, one per edge, need to disambiguate int i = (iX+1) + m_iXBound*(iY + m_iYBound*iZ); int iF00 = m_aiData[i]; // F(x,y,z) i += m_iXBound; int iF10 = m_aiData[i]; // F(x,y+1,z) i += m_iXYBound; int iF11 = m_aiData[i]; // F(x,y+1,z+1) i -= m_iXBound; int iF01 = m_aiData[i]; // F(x,y,z+1) int iDet = iF00*iF11 - iF01*iF10; if (iDet > 0) { // disjoint hyperbolic segments, pair <P0,P2>, <P1,P3> rkTable.Insert(EI_XMAX_YMIN,EI_XMAX_ZMIN); rkTable.Insert(EI_XMAX_YMAX,EI_XMAX_ZMAX); } else if (iDet < 0) { // disjoint hyperbolic segments, pair <P0,P3>, <P1,P2> rkTable.Insert(EI_XMAX_YMIN,EI_XMAX_ZMAX); rkTable.Insert(EI_XMAX_YMAX,EI_XMAX_ZMIN); } else { // plus-sign configuration, add branch point to tessellation rkTable.Insert(FI_XMAX,Vector3f(rkTable.GetX(EI_XMAX_ZMIN), rkTable.GetY(EI_XMAX_ZMIN),rkTable.GetZ(EI_XMAX_YMIN))); // add edges sharing the branch point rkTable.Insert(EI_XMAX_YMIN,FI_XMAX); rkTable.Insert(EI_XMAX_YMAX,FI_XMAX); rkTable.Insert(EI_XMAX_ZMIN,FI_XMAX); rkTable.Insert(EI_XMAX_ZMAX,FI_XMAX); } break; } default: assert(false); } } //---------------------------------------------------------------------------- void ExtractSurfaceCubes::GetYMinEdges (int iX, int iY, int iZ, int iType, VETable& rkTable) { int iFaceType = 0; if (iType & EB_XMIN_YMIN) { iFaceType |= 0x01; } if (iType & EB_XMAX_YMIN) { iFaceType |= 0x02; } if (iType & EB_YMIN_ZMIN) { iFaceType |= 0x04; } if (iType & EB_YMIN_ZMAX) { iFaceType |= 0x08; } switch (iFaceType) { case 0: return; case 3: rkTable.Insert(EI_XMIN_YMIN,EI_XMAX_YMIN); break; case 5: rkTable.Insert(EI_XMIN_YMIN,EI_YMIN_ZMIN); break; case 6: rkTable.Insert(EI_XMAX_YMIN,EI_YMIN_ZMIN); break; case 9: rkTable.Insert(EI_XMIN_YMIN,EI_YMIN_ZMAX); break; case 10: rkTable.Insert(EI_XMAX_YMIN,EI_YMIN_ZMAX); break; case 12: rkTable.Insert(EI_YMIN_ZMIN,EI_YMIN_ZMAX); break; case 15: { // four vertices, one per edge, need to disambiguate int i = iX + m_iXBound*(iY + m_iYBound*iZ); int iF00 = m_aiData[i]; // F(x,y,z) i++; int iF10 = m_aiData[i]; // F(x+1,y,z) i += m_iXYBound; int iF11 = m_aiData[i]; // F(x+1,y,z+1) i--; int iF01 = m_aiData[i]; // F(x,y,z+1) int iDet = iF00*iF11 - iF01*iF10; if (iDet > 0) { // disjoint hyperbolic segments, pair <P0,P2>, <P1,P3> rkTable.Insert(EI_XMIN_YMIN,EI_YMIN_ZMIN); rkTable.Insert(EI_XMAX_YMIN,EI_YMIN_ZMAX); } else if (iDet < 0) { // disjoint hyperbolic segments, pair <P0,P3>, <P1,P2> rkTable.Insert(EI_XMIN_YMIN,EI_YMIN_ZMAX); rkTable.Insert(EI_XMAX_YMIN,EI_YMIN_ZMIN); } else { // plus-sign configuration, add branch point to tessellation rkTable.Insert(FI_YMIN,Vector3f(rkTable.GetX(EI_YMIN_ZMIN), rkTable.GetY(EI_XMIN_YMIN),rkTable.GetZ(EI_XMIN_YMIN))); // add edges sharing the branch point rkTable.Insert(EI_XMIN_YMIN,FI_YMIN); rkTable.Insert(EI_XMAX_YMIN,FI_YMIN); rkTable.Insert(EI_YMIN_ZMIN,FI_YMIN); rkTable.Insert(EI_YMIN_ZMAX,FI_YMIN); } break; } default: assert(false); } } //---------------------------------------------------------------------------- void ExtractSurfaceCubes::GetYMaxEdges (int iX, int iY, int iZ, int iType, VETable& rkTable) { int iFaceType = 0; if (iType & EB_XMIN_YMAX) { iFaceType |= 0x01; } if (iType & EB_XMAX_YMAX) { iFaceType |= 0x02; } if (iType & EB_YMAX_ZMIN) { iFaceType |= 0x04; } if (iType & EB_YMAX_ZMAX) { iFaceType |= 0x08; } switch (iFaceType) { case 0: return; case 3: rkTable.Insert(EI_XMIN_YMAX,EI_XMAX_YMAX); break; case 5: rkTable.Insert(EI_XMIN_YMAX,EI_YMAX_ZMIN); break; case 6: rkTable.Insert(EI_XMAX_YMAX,EI_YMAX_ZMIN); break; case 9: rkTable.Insert(EI_XMIN_YMAX,EI_YMAX_ZMAX); break; case 10: rkTable.Insert(EI_XMAX_YMAX,EI_YMAX_ZMAX); break; case 12: rkTable.Insert(EI_YMAX_ZMIN,EI_YMAX_ZMAX); break; case 15: { // four vertices, one per edge, need to disambiguate int i = iX + m_iXBound*((iY+1) + m_iYBound*iZ); int iF00 = m_aiData[i]; // F(x,y,z) i++; int iF10 = m_aiData[i]; // F(x+1,y,z) i += m_iXYBound; int iF11 = m_aiData[i]; // F(x+1,y,z+1) i--; int iF01 = m_aiData[i]; // F(x,y,z+1) int iDet = iF00*iF11 - iF01*iF10; if (iDet > 0) { // disjoint hyperbolic segments, pair <P0,P2>, <P1,P3> rkTable.Insert(EI_XMIN_YMAX,EI_YMAX_ZMIN); rkTable.Insert(EI_XMAX_YMAX,EI_YMAX_ZMAX); } else if (iDet < 0) { // disjoint hyperbolic segments, pair <P0,P3>, <P1,P2> rkTable.Insert(EI_XMIN_YMAX,EI_YMAX_ZMAX); rkTable.Insert(EI_XMAX_YMAX,EI_YMAX_ZMIN); } else { // plus-sign configuration, add branch point to tessellation rkTable.Insert(FI_YMAX,Vector3f(rkTable.GetX(EI_YMAX_ZMIN), rkTable.GetY(EI_XMIN_YMAX),rkTable.GetZ(EI_XMIN_YMAX))); // add edges sharing the branch point rkTable.Insert(EI_XMIN_YMAX,FI_YMAX); rkTable.Insert(EI_XMAX_YMAX,FI_YMAX); rkTable.Insert(EI_YMAX_ZMIN,FI_YMAX); rkTable.Insert(EI_YMAX_ZMAX,FI_YMAX); } break; } default: assert(false); } } //---------------------------------------------------------------------------- void ExtractSurfaceCubes::GetZMinEdges (int iX, int iY, int iZ, int iType, VETable& rkTable) { int iFaceType = 0; if (iType & EB_XMIN_ZMIN) { iFaceType |= 0x01; } if (iType & EB_XMAX_ZMIN) { iFaceType |= 0x02; } if (iType & EB_YMIN_ZMIN) { iFaceType |= 0x04; } if (iType & EB_YMAX_ZMIN) { iFaceType |= 0x08; } switch (iFaceType) { case 0: return; case 3: rkTable.Insert(EI_XMIN_ZMIN,EI_XMAX_ZMIN); break; case 5: rkTable.Insert(EI_XMIN_ZMIN,EI_YMIN_ZMIN); break; case 6: rkTable.Insert(EI_XMAX_ZMIN,EI_YMIN_ZMIN); break; case 9: rkTable.Insert(EI_XMIN_ZMIN,EI_YMAX_ZMIN); break; case 10: rkTable.Insert(EI_XMAX_ZMIN,EI_YMAX_ZMIN); break; case 12: rkTable.Insert(EI_YMIN_ZMIN,EI_YMAX_ZMIN); break; case 15: { // four vertices, one per edge, need to disambiguate int i = iX + m_iXBound*(iY + m_iYBound*iZ); int iF00 = m_aiData[i]; // F(x,y,z) i++; int iF10 = m_aiData[i]; // F(x+1,y,z) i += m_iXBound; int iF11 = m_aiData[i]; // F(x+1,y+1,z) i--; int iF01 = m_aiData[i]; // F(x,y+1,z) int iDet = iF00*iF11 - iF01*iF10; if (iDet > 0) { // disjoint hyperbolic segments, pair <P0,P2>, <P1,P3> rkTable.Insert(EI_XMIN_ZMIN,EI_YMIN_ZMIN); rkTable.Insert(EI_XMAX_ZMIN,EI_YMAX_ZMIN); } else if (iDet < 0) { // disjoint hyperbolic segments, pair <P0,P3>, <P1,P2> rkTable.Insert(EI_XMIN_ZMIN,EI_YMAX_ZMIN); rkTable.Insert(EI_XMAX_ZMIN,EI_YMIN_ZMIN); } else { // plus-sign configuration, add branch point to tessellation rkTable.Insert(FI_ZMIN,Vector3f(rkTable.GetX(EI_YMIN_ZMIN), rkTable.GetY(EI_XMIN_ZMIN),rkTable.GetZ(EI_XMIN_ZMIN))); // add edges sharing the branch point rkTable.Insert(EI_XMIN_ZMIN,FI_ZMIN); rkTable.Insert(EI_XMAX_ZMIN,FI_ZMIN); rkTable.Insert(EI_YMIN_ZMIN,FI_ZMIN); rkTable.Insert(EI_YMAX_ZMIN,FI_ZMIN); } break; } default: assert(false); } } //---------------------------------------------------------------------------- void ExtractSurfaceCubes::GetZMaxEdges (int iX, int iY, int iZ, int iType, VETable& rkTable) { int iFaceType = 0; if (iType & EB_XMIN_ZMAX) { iFaceType |= 0x01; } if (iType & EB_XMAX_ZMAX) { iFaceType |= 0x02; } if (iType & EB_YMIN_ZMAX) { iFaceType |= 0x04; } if (iType & EB_YMAX_ZMAX) { iFaceType |= 0x08; } switch (iFaceType) { case 0: return; case 3: rkTable.Insert(EI_XMIN_ZMAX,EI_XMAX_ZMAX); break; case 5: rkTable.Insert(EI_XMIN_ZMAX,EI_YMIN_ZMAX); break; case 6: rkTable.Insert(EI_XMAX_ZMAX,EI_YMIN_ZMAX); break; case 9: rkTable.Insert(EI_XMIN_ZMAX,EI_YMAX_ZMAX); break; case 10: rkTable.Insert(EI_XMAX_ZMAX,EI_YMAX_ZMAX); break; case 12: rkTable.Insert(EI_YMIN_ZMAX,EI_YMAX_ZMAX); break; case 15: { // four vertices, one per edge, need to disambiguate int i = iX + m_iXBound*(iY + m_iYBound*(iZ+1)); int iF00 = m_aiData[i]; // F(x,y,z) i++; int iF10 = m_aiData[i]; // F(x+1,y,z) i += m_iXBound; int iF11 = m_aiData[i]; // F(x+1,y+1,z) i--; int iF01 = m_aiData[i]; // F(x,y+1,z) int iDet = iF00*iF11 - iF01*iF10; if (iDet > 0) { // disjoint hyperbolic segments, pair <P0,P2>, <P1,P3> rkTable.Insert(EI_XMIN_ZMAX,EI_YMIN_ZMAX); rkTable.Insert(EI_XMAX_ZMAX,EI_YMAX_ZMAX); } else if (iDet < 0) { // disjoint hyperbolic segments, pair <P0,P3>, <P1,P2> rkTable.Insert(EI_XMIN_ZMAX,EI_YMAX_ZMAX); rkTable.Insert(EI_XMAX_ZMAX,EI_YMIN_ZMAX); } else { // plus-sign configuration, add branch point to tessellation rkTable.Insert(FI_ZMAX,Vector3f(rkTable.GetX(EI_YMIN_ZMAX), rkTable.GetY(EI_XMIN_ZMAX),rkTable.GetZ(EI_XMIN_ZMAX))); // add edges sharing the branch point rkTable.Insert(EI_XMIN_ZMAX,FI_ZMAX); rkTable.Insert(EI_XMAX_ZMAX,FI_ZMAX); rkTable.Insert(EI_YMIN_ZMAX,FI_ZMAX); rkTable.Insert(EI_YMAX_ZMAX,FI_ZMAX); } break; } default: assert(false); } } //---------------------------------------------------------------------------- Vector3f ExtractSurfaceCubes::GetGradient (Vector3f kP) { int iX = (int)kP.X(); if (iX < 0 || iX >= m_iXBound-1) { return Vector3f::ZERO; } int iY = (int)kP.Y(); if (iY < 0 || iY >= m_iYBound-1) { return Vector3f::ZERO; } int iZ = (int)kP.Z(); if (iZ < 0 || iZ >= m_iZBound-1) { return Vector3f::ZERO; } // get image values at corners of voxel int i000 = iX + m_iXBound*(iY + m_iYBound*iZ); int i100 = i000 + 1; int i010 = i000 + m_iXBound; int i110 = i010 + 1; int i001 = i000 + m_iXYBound; int i101 = i001 + 1; int i011 = i001 + m_iXBound; int i111 = i011 + 1; float fF000 = (float)m_aiData[i000]; float fF100 = (float)m_aiData[i100]; float fF010 = (float)m_aiData[i010]; float fF110 = (float)m_aiData[i110]; float fF001 = (float)m_aiData[i001]; float fF101 = (float)m_aiData[i101]; float fF011 = (float)m_aiData[i011]; float fF111 = (float)m_aiData[i111]; kP.X() -= iX; kP.Y() -= iY; kP.Z() -= iZ; float fOmX = 1.0f - kP.X(); float fOmY = 1.0f - kP.Y(); float fOmZ = 1.0f - kP.Z(); Vector3f kGrad; float fTmp0 = fOmY*(fF100-fF000) + kP.Y()*(fF110-fF010); float fTmp1 = fOmY*(fF101-fF001) + kP.Y()*(fF111-fF011); kGrad.X() = fOmZ*fTmp0 + kP.Z()*fTmp1; fTmp0 = fOmX*(fF010-fF000) + kP.X()*(fF110-fF100); fTmp1 = fOmX*(fF011-fF001) + kP.X()*(fF111-fF101); kGrad.Y() = fOmZ*fTmp0 + kP.Z()*fTmp1; fTmp0 = fOmX*(fF001-fF000) + kP.X()*(fF101-fF100); fTmp1 = fOmX*(fF011-fF010) + kP.X()*(fF111-fF110); kGrad.Z() = fOmY*fTmp0 + kP.Y()*fTmp1; return kGrad; } //---------------------------------------------------------------------------- ExtractSurfaceCubes::VETable::VETable () { } //---------------------------------------------------------------------------- void ExtractSurfaceCubes::VETable::Insert (int i, const Vector3f& rkP) { assert(0 <= i && i < 18); Vertex& rkV = m_akVertex[i]; rkV.P = rkP; rkV.Valid = true; } //---------------------------------------------------------------------------- void ExtractSurfaceCubes::VETable::Insert (int i0, int i1) { assert(0 <= i0 && i0 < 18 && 0 <= i1 && i1 < 18); Vertex& rkV0 = m_akVertex[i0]; Vertex& rkV1 = m_akVertex[i1]; assert(rkV0.AdjQuantity < 4 && rkV1.AdjQuantity < 4); rkV0.Adj[rkV0.AdjQuantity++] = i1; rkV1.Adj[rkV1.AdjQuantity++] = i0; } //---------------------------------------------------------------------------- void ExtractSurfaceCubes::VETable::RemoveVertex (int i) { assert(0 <= i && i < 18); Vertex& rkV0 = m_akVertex[i]; assert(rkV0.AdjQuantity == 2); int iA0 = rkV0.Adj[0], iA1 = rkV0.Adj[1]; Vertex& rkVA0 = m_akVertex[iA0]; Vertex& rkVA1 = m_akVertex[iA1]; int j; for (j = 0; j < rkVA0.AdjQuantity; j++) { if (rkVA0.Adj[j] == i) { rkVA0.Adj[j] = iA1; break; } } assert(j != rkVA0.AdjQuantity); for (j = 0; j < rkVA1.AdjQuantity; j++) { if (rkVA1.Adj[j] == i) { rkVA1.Adj[j] = iA0; break; } } assert(j != rkVA1.AdjQuantity); rkV0.Valid = false; if (rkVA0.AdjQuantity == 2) { if (rkVA0.Adj[0] == rkVA0.Adj[1]) { rkVA0.Valid = false; } } if (rkVA1.AdjQuantity == 2) { if (rkVA1.Adj[0] == rkVA1.Adj[1]) { rkVA1.Valid = false; } } } //---------------------------------------------------------------------------- bool ExtractSurfaceCubes::VETable::Remove (TriangleKey& rkTri) { for (int i = 0; i < 18; i++) { Vertex& rkV = m_akVertex[i]; if (rkV.Valid && rkV.AdjQuantity == 2) { rkTri.V[0] = i; rkTri.V[1] = rkV.Adj[0]; rkTri.V[2] = rkV.Adj[1]; RemoveVertex(i); return true; } } return false; } //---------------------------------------------------------------------------- void ExtractSurfaceCubes::VETable::RemoveTriangles ( std::vector<Vector3f>& rkVA, std::vector<TriangleKey>& rkTA) { // ear-clip the wireframe to get the triangles TriangleKey kTri; while (Remove(kTri)) { int iV0 = (int)rkVA.size(), iV1 = iV0+1, iV2 = iV1+1; rkTA.push_back(TriangleKey(iV0,iV1,iV2)); rkVA.push_back(m_akVertex[kTri.V[0]].P); rkVA.push_back(m_akVertex[kTri.V[1]].P); rkVA.push_back(m_akVertex[kTri.V[2]].P); } } //----------------------------------------------------------------------------
[ "yf.flagship@e79fdf7c-a9d8-11de-b950-3d5b5f4ea0aa" ]
[ [ [ 1, 978 ] ] ]
98c1996ea1a59018b10714f28fc5ae36e1875872
a46400e00852a50d520994e2784834ca1662ca41
/CPPNinjaMonkey/src/lib/net/NetworkPacketMarshaller.h
8cc993f5e32579b405c064874e932ba8f5ea0f42
[]
no_license
j0rg3n/shadow-ninja-monkey
ccddd252da672d13c9a251c687d83be98c4c59c8
aac16245be849e109f5e584bf97a4e6443860aba
refs/heads/master
2021-01-10T10:28:39.371674
2011-02-06T21:12:56
2011-02-06T21:12:56
45,484,036
0
0
null
null
null
null
UTF-8
C++
false
false
649
h
#pragma once #ifndef NETWORKPACKETMARSHALLER_H_INCLUDED #define NETWORKPACKETMARSHALLER_H_INCLUDED #include <vector> #include "boost/function.hpp" #include "net/NetworkPacket.h" #include "Socket.h" // ----------------------------------------------------------------------------- class NetworkPacketMarshaller { public: NetworkPacketMarshaller(Socket& socket, boost::function<void (std::vector<NetworkPacket>)> packetsReceived); ~NetworkPacketMarshaller(); void Receive(); void Send(std::vector<NetworkPacket> packets); private: class Impl; Impl* m_pImpl; }; #endif // NETWORKPACKETMARSHALLER_H_INCLUDED
[ [ [ 1, 31 ] ] ]
ea8f99dc7d108e1e092db5c626f74d949fe53193
3bfc30f7a07ce0f6eabcd526e39ba1030d84c1f3
/BlobbyWarriors/Source/BlobbyWarriors/Model/Entity/Graphic.h
8dc778bad8ded678da8a3999c415db4eeed16185
[]
no_license
visusnet/Blobby-Warriors
b0b70a0b4769b60d96424b55ad7c47b256e60061
adec63056786e4e8dfcb1ed7f7fe8b09ce05399d
refs/heads/master
2021-01-19T14:09:32.522480
2011-11-29T21:53:25
2011-11-29T21:53:25
2,850,563
0
0
null
null
null
null
UTF-8
C++
false
false
565
h
#ifndef GRAPHIC_H #define GRAPHIC_H class Graphic; #include "AbstractEntity.h" #include "../../Debug.h" class Graphic : public AbstractEntity { public: void draw(); void setX(float x); float getX(); void setY(float y); float getY(); void setAngle(float angle); float getAngle(); void setWidth(float width); float getWidth(); void setHeight(float height); float getHeight(); void setDepth(float depth); float getDepth(); private: float x; float y; float angle; float width; float height; float depth; }; #endif
[ [ [ 1, 34 ] ] ]
d08d8d4532fb672dd00938ae9f507d8c67a62701
fb135677f176035a63927d5e307986d27205a6ab
/bitwise-engine/Graphics/Color.cpp
837a674c3edf0e3993471d31a32d7ad8c89ad0f6
[]
no_license
jaylindquist/bitwise-engine
eb7c6991a18db22430a8c38c45cfb5c3de3ed936
c8be0cb946fff4523b6a42dbe014f6a204afdedb
refs/heads/master
2016-09-06T06:45:51.390789
2008-11-19T23:24:52
2008-11-19T23:24:52
35,298,714
0
0
null
null
null
null
UTF-8
C++
false
false
1,237
cpp
#include "Color.h" using namespace BitwiseEngine::Math; using namespace BitwiseEngine::Graphics; Color Color::WHITE = Color(RealHelper::ONE, RealHelper::ONE, RealHelper::ONE, RealHelper::ONE); Color Color::BLACK = Color(RealHelper::ZERO, RealHelper::ZERO, RealHelper::ZERO, RealHelper::ONE); Color Color::RED = Color(RealHelper::ONE, RealHelper::ZERO, RealHelper::ZERO, RealHelper::ONE); Color Color::GREEN = Color(RealHelper::ZERO, RealHelper::ONE, RealHelper::ZERO, RealHelper::ONE); Color Color::BLUE = Color(RealHelper::ZERO, RealHelper::ZERO, RealHelper::ONE, RealHelper::ONE); Color Color::CYAN = Color(RealHelper::ZERO, RealHelper::ONE, RealHelper::ONE, RealHelper::ONE); Color Color::MAGENTA = Color(RealHelper::ONE, RealHelper::ZERO, RealHelper::ONE, RealHelper::ONE); Color Color::YELLOW = Color(RealHelper::ONE, RealHelper::ONE, RealHelper::ZERO, RealHelper::ONE); Color::Color() { r = RealHelper::ONE; g = RealHelper::ONE; b = RealHelper::ONE; a = RealHelper::ONE; } Color::Color(Real red, Real green, Real blue) { r = red; g = green; b = blue; a = RealHelper::ONE; } Color::Color(Real red, Real green, Real blue, Real alpha) { r = red; g = green; b = blue; a = alpha; }
[ "yasunobu13@194bc0c5-1251-0410-adcc-b97d8ca696f6" ]
[ [ [ 1, 38 ] ] ]
d8ada4fb5c7a8bc9c6ce36dcd1d1e7b073b9ac1e
2f77d5232a073a28266f5a5aa614160acba05ce6
/01.DevelopLibrary/03.Code/Core/SmsService/SmsService.h
e2352f7d4b230a2c775fe13d8c7be86c207fd400
[]
no_license
radtek/mobilelzz
87f2d0b53f7fd414e62c8b2d960e87ae359c81b4
402276f7c225dd0b0fae825013b29d0244114e7d
refs/heads/master
2020-12-24T21:21:30.860184
2011-03-26T02:19:47
2011-03-26T02:19:47
58,142,323
0
0
null
null
null
null
UTF-8
C++
false
false
3,836
h
#ifndef __SmsService_h__ #define __SmsService_h__ enum Search_DateKind{ Search_DateKind_Before, Search_DateKind_After, Search_DateKind_Between }; class CSmsService : public CBasicService { public: CSmsService(); ~CSmsService(); virtual APP_Result Initialize(); protected: virtual APP_Result MakeParam(wchar_t* pwcsRequestXML); virtual APP_Result ExcuteParam(wchar_t* pwcsRequestXML, wchar_t** ppwcsResultXML); virtual APP_Result MakeResult(wchar_t** ppwcsResultXML); private: APP_Result ExcuteForSearch(CRequestXmlOperator& clXmlOpe, CXmlStream& clResultXml); APP_Result ExcuteForDelete(CRequestXmlOperator& clXmlOpe, CXmlStream& clResultXml); APP_Result ExcuteForAdd(CRequestXmlOperator& clXmlOpe, CXmlStream& clResultXml); APP_Result ExcuteForEdit(CRequestXmlOperator& clXmlOpe, CXmlStream& clResultXml); APP_Result ExcuteForDetail(CRequestXmlOperator& clXmlOpe, CXmlStream& clResultXml); APP_Result ExcuteForList(CRequestXmlOperator& clXmlOpe, CXmlStream& clResultXml); APP_Result AddProtectDatta(CRequestXmlOperator& clReqXmlOpe, CXmlStream& clResultXml); APP_Result EditProtectDatta(CRequestXmlOperator& clReqXmlOpe, CXmlStream& clResultXml); APP_Result DeleteProtectDatta(CRequestXmlOperator& clReqXmlOpe, CXmlStream& clResultXml); APP_Result DecideQuery(OperationCondition* pConditions, long lConditionCount, CSQL_query** ppQueryNeeded, BOOL& bIsPermitDecode); APP_Result MakeSmsList(CRequestXmlOperator& clXmlOpe, CSQL_query* pQHandle, CXmlStream& clResultXml, BOOL bIsPermitDecode); APP_Result MakeSmsListRecs( CSQL_query* pQHandle, CXmlNode* pNodeList, BOOL bIsPermitDecode, BOOL bIsList, long& lListCount, long& lEncodeCount ); APP_Result CheckCode(long lPID, BOOL& bNeedDecode, wchar_t* pwcsDBCode, long lCodeSize); APP_Result ConvertDisplayCode2DBCode(wchar_t* pwcsCode, wchar_t* pwcsDBCode, long lDBCodeCount ); APP_Result ConvertDBCode2DisplayCode(wchar_t* pDBCode, wchar_t* pwcsCode, long lCodeCount); APP_Result EncodeSmsContentByContactor(long lPID); APP_Result CheckInputCode(long lPID, wchar_t* pwcsInputCode); APP_Result UpdateCode(long lPID, wchar_t* pwcsInputCode); APP_Result DeleteCode(long lPID); APP_Result UpdateSmsInfo(CRequestXmlOperator& clReqXmlOpe, CXmlStream& clResultXml); APP_Result UpdateSmsRecInfo(long lSID, CSQL_query* pQHandle, wchar_t* pwcsValue); APP_Result GetPIDByAddress(wchar_t* pwcsAddress, long& lPID); APP_Result CreateTable(wchar_t* pSqlCommand); APP_Result DecideSearchCommond(CDynamicArray<OperationCondition>&spConditions, Search_DateKind& enDateKind,CSQL_SmartQuery& pQHandle); APP_Result InitSearchParam(Search_DateKind& enDateKind,CSQL_SmartQuery& pQHandle); APP_Result SetSearchParamByConditions(CDynamicArray<OperationCondition>&spConditions, Search_DateKind& enDateKind,CSQL_SmartQuery& pQHandle); APP_Result UpdateSmsGroupInfo(long lPID); APP_Result CheckIsPermitDecodeContent(long lPID, wchar_t* pDisplayCode, BOOL &bIsPermitDecode); private: CSQL_SmartQuery m_pQUnReadSms; long m_lID_QUnReadSms; CSQL_SmartQuery m_pQSmsList; long m_lID_QSmsList; CSQL_SmartQuery m_pQSmsListByContactor; long m_lID_QSmsListByContactor; CSQL_SmartQuery m_pQUpdateReadStatus; long m_lID_QSmsReadStatus; CSQL_SmartQuery m_pQUpdateLockStatus; long m_lID_QUpdateLockStatus; CSQL_SmartQuery m_pQCheckCode; long m_lID_QCheckCode; CSQL_SmartQuery m_pQInsertCode; long m_lID_QInsertCode; CSQL_SmartQuery m_pQUpdateSmsContent; long m_lID_QUpdateSmsContent; CSQL_SmartQuery m_pQGetNameByPID; CSQL_SmartQuery m_pQGetDetailBySID; CSQL_session* m_pclSqlDBSession; CSQL_session* m_pclSqlContactsDBSession; }; #endif __SmsService_h__
[ "lidan8908589@8983de3c-2b35-11df-be6c-f52728ce0ce6" ]
[ [ [ 1, 102 ] ] ]
55cc00c35335bef8e4f2ec83eaee26cd0f7fedfa
11c7904170760e079f064347e62570ec3e1549fd
/PrecompiledBoostOrbiter.cpp
33233a532f8374d5bd217210b85331631c655932
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
rstarkov/BoostOrbiter
17f68b289f513cf056dc4324ac9c927f271dd849
f9e481f23831edcf9ea799b56fe6768465316703
refs/heads/master
2020-11-29T20:44:32.725856
2011-03-27T21:27:36
2011-03-27T21:27:36
96,652,896
0
0
null
null
null
null
UTF-8
C++
false
false
400
cpp
//---------------------------------------------------------------------------- // This file is part of the BoostOrbiter project, and is subject to the terms // and conditions defined in file 'license.txt'. Full list of contributors is // available in file 'contributors.txt'. //---------------------------------------------------------------------------- #include "PrecompiledBoostOrbiter.h"
[ [ [ 1, 7 ] ] ]
6bcc9fa06bd73a8ef0f66629e394adbb6f1ff396
5ff30d64df43c7438bbbcfda528b09bb8fec9e6b
/kgraphics/renderer/Effect.cpp
d2e85343dac47372ce7ea69cf3b999a2541fe722
[]
no_license
lvtx/gamekernel
c80cdb4655f6d4930a7d035a5448b469ac9ae924
a84d9c268590a294a298a4c825d2dfe35e6eca21
refs/heads/master
2016-09-06T18:11:42.702216
2011-09-27T07:22:08
2011-09-27T07:22:08
38,255,025
3
1
null
null
null
null
UTF-8
C++
false
false
1,357
cpp
#include "stdafx.h" #include <kgraphics/renderer/Effect.h> using namespace gfx; Effect::Effect( ID3DXEffect* effect ) : m_effect( effect ) { K_ASSERT( m_effect != 0 ); } Effect::~Effect() { if ( m_effect != 0 ) { m_effect->Release(); m_effect = 0; } } bool Effect::SetMatrix( const std::string& name, D3DXMATRIX* matrix ) { return SUCCEEDED( m_effect->SetMatrix( name.c_str(), matrix ) ); } bool Effect::SetTexture( const std::string& name, Texture* tex ) { return SUCCEEDED( m_effect->SetTexture( name.c_str(), tex->GetTex() ) ); } bool Effect::SetValue( const std::string& name, void* v, uint size ) { K_ASSERT( v != 0 ); K_ASSERT( size > 0 ); return SUCCEEDED( m_effect->SetValue( name.c_str(), v, size ) ); } bool Effect::SetTechnique( const std::string& tech ) { return SUCCEEDED( m_effect->SetTechnique( tech.c_str() ) ); } bool Effect::Begin( uint& passes ) { return SUCCEEDED( m_effect->Begin(&passes, 0) ); } bool Effect::BeginPass( uint pass ) { return SUCCEEDED( m_effect->BeginPass( pass ) ); } bool Effect::EndPass() { return SUCCEEDED( m_effect->EndPass() ); } bool Effect::End() { return SUCCEEDED( m_effect->End() ); } void Effect::OnLost() { // TODO: resource handling } void Effect::OnRestored() { // TODO: resoruce handling }
[ "darkface@localhost" ]
[ [ [ 1, 74 ] ] ]
e896f6457efb98e222be76d1b89801cf30caf78f
7b379862f58f587d9327db829ae4c6493b745bb1
/JuceLibraryCode/modules/juce_core/streams/juce_OutputStream.cpp
b532e8be1631e15fafa1960114e9acfe2d25095e
[]
no_license
owenvallis/Nomestate
75e844e8ab68933d481640c12019f0d734c62065
7fe7c06c2893421a3c77b5180e5f27ab61dd0ffd
refs/heads/master
2021-01-19T07:35:14.301832
2011-12-28T07:42:50
2011-12-28T07:42:50
2,950,072
2
0
null
null
null
null
UTF-8
C++
false
false
8,474
cpp
/* ============================================================================== This file is part of the JUCE library - "Jules' Utility Class Extensions" Copyright 2004-11 by Raw Material Software Ltd. ------------------------------------------------------------------------------ JUCE can be redistributed and/or modified under the terms of the GNU General Public License (Version 2), as published by the Free Software Foundation. A copy of the license is included in the JUCE distribution, or can be found online at www.gnu.org/licenses. JUCE 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. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.rawmaterialsoftware.com/juce for more information. ============================================================================== */ BEGIN_JUCE_NAMESPACE //============================================================================== #if JUCE_DEBUG struct DanglingStreamChecker { DanglingStreamChecker() {} ~DanglingStreamChecker() { /* It's always a bad idea to leak any object, but if you're leaking output streams, then there's a good chance that you're failing to flush a file to disk properly, which could result in corrupted data and other similar nastiness.. */ jassert (activeStreams.size() == 0); } Array<void*, CriticalSection> activeStreams; }; static DanglingStreamChecker danglingStreamChecker; #endif //============================================================================== OutputStream::OutputStream() : newLineString (NewLine::getDefault()) { #if JUCE_DEBUG danglingStreamChecker.activeStreams.add (this); #endif } OutputStream::~OutputStream() { #if JUCE_DEBUG danglingStreamChecker.activeStreams.removeValue (this); #endif } //============================================================================== void OutputStream::writeBool (const bool b) { writeByte (b ? (char) 1 : (char) 0); } void OutputStream::writeByte (char byte) { write (&byte, 1); } void OutputStream::writeRepeatedByte (uint8 byte, int numTimesToRepeat) { while (--numTimesToRepeat >= 0) writeByte ((char) byte); } void OutputStream::writeShort (short value) { const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value); write (&v, 2); } void OutputStream::writeShortBigEndian (short value) { const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value); write (&v, 2); } void OutputStream::writeInt (int value) { const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value); write (&v, 4); } void OutputStream::writeIntBigEndian (int value) { const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value); write (&v, 4); } void OutputStream::writeCompressedInt (int value) { unsigned int un = (value < 0) ? (unsigned int) -value : (unsigned int) value; uint8 data[5]; int num = 0; while (un > 0) { data[++num] = (uint8) un; un >>= 8; } data[0] = (uint8) num; if (value < 0) data[0] |= 0x80; write (data, num + 1); } void OutputStream::writeInt64 (int64 value) { const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value); write (&v, 8); } void OutputStream::writeInt64BigEndian (int64 value) { const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value); write (&v, 8); } void OutputStream::writeFloat (float value) { union { int asInt; float asFloat; } n; n.asFloat = value; writeInt (n.asInt); } void OutputStream::writeFloatBigEndian (float value) { union { int asInt; float asFloat; } n; n.asFloat = value; writeIntBigEndian (n.asInt); } void OutputStream::writeDouble (double value) { union { int64 asInt; double asDouble; } n; n.asDouble = value; writeInt64 (n.asInt); } void OutputStream::writeDoubleBigEndian (double value) { union { int64 asInt; double asDouble; } n; n.asDouble = value; writeInt64BigEndian (n.asInt); } void OutputStream::writeString (const String& text) { // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind // if lots of large, persistent strings were to be written to streams). const int numBytes = text.getNumBytesAsUTF8() + 1; HeapBlock<char> temp ((size_t) numBytes); text.copyToUTF8 (temp, numBytes); write (temp, numBytes); } void OutputStream::writeText (const String& text, const bool asUTF16, const bool writeUTF16ByteOrderMark) { if (asUTF16) { if (writeUTF16ByteOrderMark) write ("\x0ff\x0fe", 2); String::CharPointerType src (text.getCharPointer()); bool lastCharWasReturn = false; for (;;) { const juce_wchar c = src.getAndAdvance(); if (c == 0) break; if (c == '\n' && ! lastCharWasReturn) writeShort ((short) '\r'); lastCharWasReturn = (c == L'\r'); writeShort ((short) c); } } else { const char* src = text.toUTF8(); const char* t = src; for (;;) { if (*t == '\n') { if (t > src) write (src, (int) (t - src)); write ("\r\n", 2); src = t + 1; } else if (*t == '\r') { if (t[1] == '\n') ++t; } else if (*t == 0) { if (t > src) write (src, (int) (t - src)); break; } ++t; } } } int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite) { if (numBytesToWrite < 0) numBytesToWrite = std::numeric_limits<int64>::max(); int numWritten = 0; while (numBytesToWrite > 0 && ! source.isExhausted()) { char buffer [8192]; const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer))); if (num <= 0) break; write (buffer, num); numBytesToWrite -= num; numWritten += num; } return numWritten; } //============================================================================== void OutputStream::setNewLineString (const String& newLineString_) { newLineString = newLineString_; } //============================================================================== OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number) { return stream << String (number); } OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number) { return stream << String (number); } OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character) { stream.writeByte (character); return stream; } OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text) { stream.write (text, (int) strlen (text)); return stream; } OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data) { stream.write (data.getData(), (int) data.getSize()); return stream; } OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead) { FileInputStream in (fileToRead); return stream << in; } OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, InputStream& streamToRead) { stream.writeFromInputStream (streamToRead, -1); return stream; } OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const NewLine&) { return stream << stream.getNewLineString(); } END_JUCE_NAMESPACE
[ "ow3nskip" ]
[ [ [ 1, 317 ] ] ]
be0afceeadff8fe14ccb0cdd857def596344d04b
5ac13fa1746046451f1989b5b8734f40d6445322
/minimangalore/Nebula2/code/tutorials/mtutorial06/message/damagevalues.cc
4967fd5bd9b4384a619adfd2192aa46f45eacb21
[]
no_license
moltenguy1/minimangalore
9f2edf7901e7392490cc22486a7cf13c1790008d
4d849672a6f25d8e441245d374b6bde4b59cbd48
refs/heads/master
2020-04-23T08:57:16.492734
2009-08-01T09:13:33
2009-08-01T09:13:33
35,933,330
0
0
null
null
null
null
UTF-8
C++
false
false
400
cc
//------------------------------------------------------------------------------ // //------------------------------------------------------------------------------ #include "mtutorial06/message/damagevalues.h" namespace Message { ImplementRtti(Message::DamageValues, Message::Msg); ImplementFactory(Message::DamageValues); ImplementMsgId(Message::DamageValues); } // namespace Message
[ "[email protected]@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c" ]
[ [ [ 1, 11 ] ] ]
4f858203d7178033e2d6197f45662b2060126c7a
fcdddf0f27e52ece3f594c14fd47d1123f4ac863
/TeCom/src/Tdk/Source Files/TdkCoordTransformer.cpp
49c4195aedf8d3b81c91ba2912b61a854c1f3897
[]
no_license
radtek/terra-printer
32a2568b1e92cb5a0495c651d7048db6b2bbc8e5
959241e52562128d196ccb806b51fda17d7342ae
refs/heads/master
2020-06-11T01:49:15.043478
2011-12-12T13:31:19
2011-12-12T13:31:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,115
cpp
/** * Tecgraf - GIS development team * * Tdk Framework * * @(#) TdkCoordTransformer.cpp **/ /* ** --------------------------------------------------------------- ** Includes: */ #include "TdkCoordTransformer.h" /* ** --------------------------------------------------------------- ** Definitions: */ /* ** --------------------------------------------------------------- ** Methods Implementation: */ TdkCoordTransformer::TdkCoordTransformer(const TdkTransformationType& transformationType) : sX_(1.0), sY_(1.0), s_(0.), tX_(0.), tY_(0.), llxW_(0.), llyW_(0.), urxW_(0.), uryW_(0.), widthW_(0.), heightW_(0.), llxV_(0.), llyV_(0.), urxV_(0.), uryV_(0.), widthV_(0.), heightV_(0.), transformationType_(transformationType) {} void TdkCoordTransformer::setWindow(const double& llx, const double& lly, const double& urx, const double& ury) { llxW_ = llx; llyW_ = lly; urxW_ = urx; uryW_ = ury; updateTransformation(); } void TdkCoordTransformer::setWindow(const TeBox& box) { setWindow(box.x1_, box.y1_, box.x2_, box.y2_); } void TdkCoordTransformer::getWindow(double& llx, double& lly, double& urx, double& ury) { llx = llxW_; lly = llyW_; urx = urxW_; ury = uryW_; } void TdkCoordTransformer::setViewport(const double& llx, const double& lly, const double& urx, const double& ury) { llxV_ = llx; llyV_ = lly; urxV_ = urx; uryV_ = ury; updateTransformation(); } void TdkCoordTransformer::setViewport(const TeBox& box) { setViewport(box.x1_, box.y1_, box.x2_, box.y2_); } void TdkCoordTransformer::getViewport(double& llx, double& lly, double& urx, double& ury) { llx = llxV_; lly = llyV_; urx = urxV_; ury = uryV_; } void TdkCoordTransformer::window2Viewport(const double& wx, const double& wy, double& vx, double& vy) { vx = sX_ * wx + tX_; vy = sY_ * wy + tY_; } void TdkCoordTransformer::window2Viewport(const TeCoord2D& wc, TeCoord2D& vc) { vc.x_ = sX_ * wc.x_ + tX_; vc.y_ = sY_ * wc.y_ + tY_; } void TdkCoordTransformer::window2Viewport(const TdkPrimitiveCoord& wc, TdkPrimitiveCoord& vc) { vc.x_ = sX_ * wc.x_ + tX_; vc.y_ = sY_ * wc.y_ + tY_; } void TdkCoordTransformer::window2Viewport(const TeBox& wbox, TeBox& vbox) { window2Viewport(wbox.x1_, wbox.y1_, vbox.x1_, vbox.y1_); window2Viewport(wbox.x2_, wbox.y2_, vbox.x2_, vbox.y2_); } void TdkCoordTransformer::window2Viewport(const double& w, double& v, const bool& xdirection) { if (xdirection) v = sX_ * w; else v = sY_ * w; } void TdkCoordTransformer::window2Viewport(const TeLine2D& lineIn, TeLine2D& lineOut) { lineOut.clear(); unsigned int lineInSize = lineIn.size(); lineOut.reserve(lineInSize); TeCoord2D c(0.0, 0.0); for (unsigned int i = 0; i < lineInSize; ++i) { window2Viewport(lineIn[i].x_, lineIn[i].y_, c.x_, c.y_); lineOut.add(c); } } void TdkCoordTransformer::window2Viewport(const TePolygon& polyIn, TePolygon& polyOut) { polyOut.clear(); unsigned int polyInSize = polyIn.size(); polyOut.reserve(polyInSize); for (unsigned int i = 0; i < polyInSize; ++i) { TeLine2D lout; window2Viewport(polyIn[i], lout); TeLinearRing r(lout); polyOut.add(r); } } void TdkCoordTransformer::window2Viewport(TdkPrimitiveCoord* inputCoords, TdkPrimitiveCoord* outputCoords, const int& numCoords) { for (int i = 0; i < numCoords; ++i) window2Viewport(inputCoords[i], outputCoords[i]); } void TdkCoordTransformer::viewport2Window(const double& vx, const double& vy, double& wx, double& wy) { wx = ((vx - tX_) / sX_); wy = ((vy - tY_) / sY_); } void TdkCoordTransformer::viewport2Window(const TdkPrimitiveCoord& vc, TdkPrimitiveCoord& wc) { wc.x_ = ((vc.x_ - tX_) / sX_); wc.y_ = ((vc.y_ - tY_) / sY_); } void TdkCoordTransformer::viewport2Window(const double& v, double& w, const bool& xdirection) { if (xdirection) w = v / sX_; else w = v / sY_; } void TdkCoordTransformer::viewport2Window(const TeLine2D& lineIn, TeLine2D& lineOut) { lineOut.clear(); unsigned int lineInSize = lineIn.size(); lineOut.reserve(lineInSize); TeCoord2D c(0.0, 0.0); for (unsigned int i = 0; i < lineInSize; ++i) { viewport2Window(lineIn[i].x_, lineIn[i].y_, c.x_, c.y_); lineOut.add(c); } } void TdkCoordTransformer::viewport2Window(const TePolygon& polyIn, TePolygon& polyOut) { polyOut.clear(); unsigned int polyInSize = polyIn.size(); polyOut.reserve(polyInSize); for (unsigned int i = 0; i < polyInSize; ++i) { TeLine2D lout; viewport2Window(polyIn[i], lout); TeLinearRing r(lout); polyOut.add(r); } } void TdkCoordTransformer::viewport2Window(TdkPrimitiveCoord* inputCoords, TdkPrimitiveCoord* outputCoords, const int& numCoords) { for (int i = 0; i < numCoords; ++i) viewport2Window(inputCoords[i], outputCoords[i]); } const TdkCoordTransformer::TdkTransformationType& TdkCoordTransformer::getTransformationType() const { return transformationType_; } void TdkCoordTransformer::setTransformationType(const TdkTransformationType& transformationType) { transformationType_ = transformationType; updateTransformation(); } TeBox TdkCoordTransformer::adjustWindowBox(const TeBox &boxW, const TeBox &boxV) { TeBox boxOut; boxOut=boxW; adjustWindowBox(boxOut.x1_, boxOut.y1_, boxOut.x2_, boxOut.y2_, boxV.x1(),boxV.y1(), boxV.x2(), boxV.y2(), TdkCoordTransformer::TdkDiscrete, true); return boxOut; } void TdkCoordTransformer::adjustWindowBox(double& llxW, double& llyW, double& urxW, double& uryW, const double& llxV, const double& llyV, const double& urxV, const double& uryV, const TdkTransformationType& transformationType, const bool& centralized) { double worldDX = urxW - llxW; double worldDY = uryW - llyW; double vpDX = urxV - llxV; double vpDY = uryV - llyV; if (transformationType == TdkDiscrete) { vpDX += 1.0; vpDY += 1.0; } double fx = vpDX / worldDX; double fy = vpDY / worldDY; // a funcao de transformacao escolhera para a proporcao do eixo que provoca a maior degradacao // da imagem: ou seja, a que a relacao (cumprimento_imagem / cumprimento_mundo) for menor if (fx > fy) { // o eixo x e redimensionado (aumentado o seu cumprimento) double dxw = vpDX / fy; if (centralized) { double dyw = vpDY / fy; double xc = (urxW + llxW) / 2.0; double yc = (uryW + llyW) / 2.0; llxW = xc - (dxw / 2.0); urxW = xc + (dxw / 2.0); llyW = yc - (dyw / 2.0); uryW = yc + (dyw / 2.0); } else { urxW = llxW + dxw; } } else { double dyw = vpDY / fx; if (centralized) { double dxw = vpDX / fx; double xc = (urxW + llxW) / 2.0; double yc = (uryW + llyW) / 2.0; llxW = xc - (dxw / 2.0); urxW = xc + (dxw / 2.0); llyW = yc - (dyw / 2.0); uryW = yc + (dyw / 2.0); } else { uryW = llyW + dyw; } } } void TdkCoordTransformer::updateTransformation() { widthW_ = urxW_ - llxW_; heightW_ = uryW_ - llyW_; widthV_ = urxV_ - llxV_; heightV_ = uryV_ - llyV_; if (transformationType_ == TdkDiscrete) { widthV_ += 1.0; heightV_ += 1.0; } if (widthW_ != 0.0) sX_ = widthV_ / widthW_; if (heightW_ != 0.0) sY_ = heightV_ / heightW_; tX_ = llxV_ - llxW_ * sX_; tY_ = llyV_ - llyW_ * sY_; s_ = sqrt(sX_ * sX_ + sY_ * sY_); } /* ** --------------------------------------------------------------- ** End: */
[ "[email protected]@58180da6-ba8b-8960-36a5-00cc02a3ddec" ]
[ [ [ 1, 363 ] ] ]
84179a705fe8723c3259d3d7a0f797169f488ff3
ad80c85f09a98b1bfc47191c0e99f3d4559b10d4
/code/inc/util/nnode.h
e8f47a30e0bebd190fa916fa9d1115b5c6528ff7
[]
no_license
DSPNerd/m-nebula
76a4578f5504f6902e054ddd365b42672024de6d
52a32902773c10cf1c6bc3dabefd2fd1587d83b3
refs/heads/master
2021-12-07T18:23:07.272880
2009-07-07T09:47:09
2009-07-07T09:47:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,554
h
#ifndef N_NODE_H #define N_NODE_H //------------------------------------------------------------------------------ /** Implement a node in a doubly linked list. (C) 2002 RadonLabs GmbH */ #ifndef N_TYPES_H #include "kernel/ntypes.h" #endif #ifndef N_DEBUG_H #include "kernel/ndebug.h" #endif //------------------------------------------------------------------------------ class nNode { public: /// the default constructor nNode(); /// constructor providing user data pointer nNode(void *ptr); /// the destructor ~nNode(); /// get the next node in the list nNode *GetSucc() const; /// get the previous node in the list nNode *GetPred() const; /// insert this node before 'succ' node into list void InsertBefore(nNode *succ); /// insert this node after 'pred' node into list void InsertAfter(nNode *pred); /// remove node from list void Remove(); /// set user data pointer void SetPtr(void *p); /// get user data pointer void *GetPtr() const; /// check if node is currently linked into a list bool IsLinked() const; private: friend class nList; nNode *succ; nNode *pred; void *ptr; }; //----------------------------------------------------------------------------- /**. */ inline nNode::nNode(void) : succ(0), pred(0), ptr(0) { // empty } //----------------------------------------------------------------------------- /**. */ inline nNode::nNode(void *_ptr) : succ(0), pred(0), ptr(_ptr) { // empty } //----------------------------------------------------------------------------- /**. The destructor will throw an assertion if the node is still linked into a list! */ inline nNode::~nNode(void) { n_assert(!this->succ); } //----------------------------------------------------------------------------- /**. Get the node after this node in the list, return 0 if there is no next node. @return the next node or 0 */ inline nNode* nNode::GetSucc(void) const { n_assert(this->succ); if (this->succ->succ) return this->succ; else return 0; } //----------------------------------------------------------------------------- /**. Get the node before this node in the list, return 0 if there is no previous node. @return the previous node or 0 */ inline nNode* nNode::GetPred(void) const { n_assert(this->pred); if (this->pred->pred) return this->pred; else return NULL; } //----------------------------------------------------------------------------- /**. @param node in front of which this node should be inserted */ inline void nNode::InsertBefore(nNode *succ) { n_assert(succ->pred); n_assert(!this->succ); nNode *pred = succ->pred; this->pred = pred; this->succ = succ; pred->succ = this; succ->pred = this; } //----------------------------------------------------------------------------- /**. @param the node after which this node should be inserted */ inline void nNode::InsertAfter(nNode *pred) { n_assert(pred->succ); n_assert(!this->succ); nNode *succ = pred->succ; this->pred = pred; this->succ = succ; pred->succ = this; succ->pred = this; } //----------------------------------------------------------------------------- /**. */ inline void nNode::Remove(void) { n_assert(this->succ); nNode *succ = this->succ; nNode *pred = this->pred; succ->pred = pred; pred->succ = succ; this->succ = NULL; this->pred = NULL; } //----------------------------------------------------------------------------- /**. @param the new user data pointer */ inline void nNode::SetPtr(void *p) { this->ptr = p; } //----------------------------------------------------------------------------- /**. @return the user data pointer */ inline void* nNode::GetPtr() const { return this->ptr; } //----------------------------------------------------------------------------- /**. @return true if node is currently linked into a list */ inline bool nNode::IsLinked(void) const { if (this->succ) { return true; } else { return false; } }; //-------------------------------------------------------------------- #endif
[ "plushe@411252de-2431-11de-b186-ef1da62b6547" ]
[ [ [ 1, 214 ] ] ]
a04ce6dbe81defc4df66a281788b8f1cad8ae62f
138a353006eb1376668037fcdfbafc05450aa413
/source/ogre/OgreNewt/boost/mpl/aux_/nested_type_wknd.hpp
b169b8668b9e6cbfe02821880036eb599eb90650
[]
no_license
sonicma7/choreopower
107ed0a5f2eb5fa9e47378702469b77554e44746
1480a8f9512531665695b46dcfdde3f689888053
refs/heads/master
2020-05-16T20:53:11.590126
2009-11-18T03:10:12
2009-11-18T03:10:12
32,246,184
0
0
null
null
null
null
UTF-8
C++
false
false
1,436
hpp
#ifndef BOOST_MPL_AUX_NESTED_TYPE_WKND_HPP_INCLUDED #define BOOST_MPL_AUX_NESTED_TYPE_WKND_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2000-2004 // // 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) // // See http://www.boost.org/libs/mpl for documentation. // $Source: /cvsroot/ogre/ogreaddons/ogrenewt/OgreNewt_Main/inc/boost/mpl/aux_/nested_type_wknd.hpp,v $ // $Date: 2006/04/17 23:47:07 $ // $Revision: 1.1 $ #include <boost/mpl/aux_/config/gcc.hpp> #include <boost/mpl/aux_/config/workaround.hpp> #if BOOST_WORKAROUND(BOOST_MPL_CFG_GCC, BOOST_TESTED_AT(0x0302)) \ || BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x561)) \ || BOOST_WORKAROUND(__SUNPRO_CC, BOOST_TESTED_AT(0x530)) \ || BOOST_WORKAROUND(__DMC__, BOOST_TESTED_AT(0x840)) namespace boost { namespace mpl { namespace aux { template< typename T > struct nested_type_wknd : T::type { }; }}} #if BOOST_WORKAROUND(__DMC__, BOOST_TESTED_AT(0x840)) # define BOOST_MPL_AUX_NESTED_TYPE_WKND(T) \ aux::nested_type_wknd<T> \ /**/ #else # define BOOST_MPL_AUX_NESTED_TYPE_WKND(T) \ ::boost::mpl::aux::nested_type_wknd<T> \ /**/ #endif #else // !BOOST_MPL_CFG_GCC et al. # define BOOST_MPL_AUX_NESTED_TYPE_WKND(T) T::type #endif #endif // BOOST_MPL_AUX_NESTED_TYPE_WKND_HPP_INCLUDED
[ "Sonicma7@0822fb10-d3c0-11de-a505-35228575a32e" ]
[ [ [ 1, 48 ] ] ]
02d6b69453c40a05b31a8dd92248cfa1955c51c4
0e540b75e36fe6602a5c612defe5ab2b948c21eb
/src/params.cpp
5c5b76fb6bde4db3113652163a4da4f068347d04
[ "MIT-0" ]
permissive
ramiro/pyodbc
999b5c33a3c56397fb331ce47755dead153e324f
2c2c09d92b1f6ccb80689c6cc6fee7fa35a3716c
refs/heads/master
2020-12-25T10:49:21.719424
2008-12-21T13:24:01
2008-12-21T13:24:01
94,824
1
0
null
null
null
null
UTF-8
C++
false
false
26,588
cpp
#include "pyodbc.h" #include "pyodbcmodule.h" #include "params.h" #include "cursor.h" #include "connection.h" #include "buffer.h" #include "wrapper.h" #include "errors.h" #include "dbspecific.h" struct ParamDesc { SQLSMALLINT sql_type; SQLULEN column_size; SQLSMALLINT decimal_digits; }; inline Connection* GetConnection(Cursor* cursor) { return (Connection*)cursor->cnxn; } static bool CacheParamDesc(Cursor* cur); static int GetParamBufferSize(PyObject* param, Py_ssize_t iParam); static bool BindParam(Cursor* cur, int iParam, const ParamDesc* pDesc, PyObject* param, byte** ppbParam); void FreeParameterData(Cursor* cur) { // Unbinds the parameters and frees the parameter buffer. if (cur->paramdata) { Py_BEGIN_ALLOW_THREADS SQLFreeStmt(cur->hstmt, SQL_RESET_PARAMS); Py_END_ALLOW_THREADS free(cur->paramdata); cur->paramdata = 0; } } void FreeParameterInfo(Cursor* cur) { // Internal function to free just the cached parameter information. This is not used by the general cursor code // since this information is also freed in the less granular free_results function that clears everything. Py_XDECREF(cur->pPreparedSQL); free(cur->paramdescs); cur->pPreparedSQL = 0; cur->paramdescs = 0; cur->paramcount = 0; } struct ObjectArrayHolder { Py_ssize_t count; PyObject** objs; ObjectArrayHolder(Py_ssize_t count, PyObject** objs) { this->count = count; this->objs = objs; } ~ObjectArrayHolder() { for (Py_ssize_t i = 0; i < count; i++) Py_XDECREF(objs[i]); free(objs); } }; bool PrepareAndBind(Cursor* cur, PyObject* pSql, PyObject* original_params, bool skip_first) { // // Normalize the parameter variables. // // Since we may replace parameters (we replace objects with Py_True/Py_False when writing to a bit/bool column), // allocate an array and use it instead of the original sequence. Since we don't change ownership we don't bother // with incref. (That is, PySequence_GetItem will INCREF and ~ObjectArrayHolder will DECREF.) int params_offset = skip_first ? 1 : 0; Py_ssize_t cParams = original_params == 0 ? 0 : PySequence_Length(original_params) - params_offset; PyObject** params = (PyObject**)malloc(sizeof(PyObject*) * cParams); if (!params) { PyErr_NoMemory(); return 0; } for (Py_ssize_t i = 0; i < cParams; i++) params[i] = PySequence_GetItem(original_params, i + params_offset); ObjectArrayHolder holder(cParams, params); // // Prepare the SQL if necessary. // if (pSql == cur->pPreparedSQL) { // We've already prepared this SQL, so we don't need to do so again. We've also cached the parameter // information in cur->paramdescs. if (cParams != cur->paramcount) { RaiseErrorV(0, ProgrammingError, "The SQL contains %d parameter markers, but %d parameters were supplied", cur->paramcount, cParams); return false; } } else { FreeParameterInfo(cur); SQLRETURN ret; if (PyString_Check(pSql)) { Py_BEGIN_ALLOW_THREADS ret = SQLPrepare(cur->hstmt, (SQLCHAR*)PyString_AS_STRING(pSql), SQL_NTS); Py_END_ALLOW_THREADS } else { Py_BEGIN_ALLOW_THREADS ret = SQLPrepareW(cur->hstmt, (SQLWCHAR*)PyUnicode_AsUnicode(pSql), SQL_NTS); Py_END_ALLOW_THREADS } if (cur->cnxn->hdbc == SQL_NULL_HANDLE) { // The connection was closed by another thread in the ALLOW_THREADS block above. RaiseErrorV(0, ProgrammingError, "The cursor's connection was closed."); return false; } if (!SQL_SUCCEEDED(ret)) { RaiseErrorFromHandle("SQLPrepare", GetConnection(cur)->hdbc, cur->hstmt); return false; } if (!CacheParamDesc(cur)) return false; cur->pPreparedSQL = pSql; Py_INCREF(cur->pPreparedSQL); } // // Convert parameters if necessary // // If we were able to get the parameter descriptions (the target columns), we'll convert objects being written to // bit/bool columns. Drivers that don't give us the target descriptions will require users to pass in booleans or // ints, but we hope drivers will add support. if (cur->paramdescs) { for (Py_ssize_t i = 0; i < cParams; i++) { if (cur->paramdescs[i].sql_type == SQL_BIT && !PyBool_Check(params[i])) params[i] = PyObject_IsTrue(params[i]) ? Py_True : Py_False; } } // Calculate the amount of memory we need for param_buffer. We can't allow it to reallocate on the fly since // we will bind directly into its memory. (We only use a vector so its destructor will free the memory.) // We'll set aside one SQLLEN for each column to be used as the StrLen_or_IndPtr. int cb = 0; for (Py_ssize_t i = 0; i < cParams; i++) { int cbT = GetParamBufferSize(params[i], i + 1) + sizeof(SQLLEN); // +1 to map to ODBC one-based index if (cbT < 0) return 0; cb += cbT; } cur->paramdata = reinterpret_cast<byte*>(malloc(cb)); if (cur->paramdata == 0) { PyErr_NoMemory(); return false; } // Bind each parameter. If possible, items will be bound directly into the Python object. Otherwise, // param_buffer will be used and ibNext will be updated. byte* pbParam = cur->paramdata; for (Py_ssize_t i = 0; i < cParams; i++) { ParamDesc* pDesc = (cur->paramdescs != 0) ? &cur->paramdescs[i] : 0; if (!BindParam(cur, i + 1, pDesc, params[i], &pbParam)) { free(cur->paramdata); cur->paramdata = 0; return false; } } return true; } static bool CacheParamDesc(Cursor* cur) { // Called after a SQL statement is prepared to cache the number of parameters and some information about each. // // If successful, true is returned. Otherwise, the appropriate exception will be registered with the Python system and // false is returned. cur->paramcount = 0; cur->paramdescs = 0; SQLSMALLINT cT; SQLRETURN ret; Py_BEGIN_ALLOW_THREADS ret = SQLNumParams(cur->hstmt, &cT); Py_END_ALLOW_THREADS if (!SQL_SUCCEEDED(ret)) { RaiseErrorFromHandle("SQLNumParams", GetConnection(cur)->hdbc, cur->hstmt); return false; } cur->paramcount = (int)cT; if (!GetConnection(cur)->supports_describeparam) { // The driver can't describe the parameters to us, so we'll do without. They are helpful, but are only really // required when binding a None (NULL) since we don't know the required data type. return true; } ParamDesc* pT = reinterpret_cast<ParamDesc*>(malloc(sizeof(ParamDesc) * cT)); if (pT == 0) { PyErr_NoMemory(); return false; } for (SQLSMALLINT i = 0; i < cT; i++) { SQLSMALLINT Nullable; Py_BEGIN_ALLOW_THREADS ret = SQLDescribeParam(cur->hstmt, static_cast<SQLUSMALLINT>(i + 1), &pT[i].sql_type, &pT[i].column_size, &pT[i].decimal_digits, &Nullable); Py_END_ALLOW_THREADS if (!SQL_SUCCEEDED(ret)) { // This used to trigger an error, but SQLDescribeParam just isn't as supported or robust as I had hoped. // There are a couple of old bugs that cause "Invalid Descriptor index" that are supposed to be fixed, but // one also mentions that SQLDescribeParam is not supported for subquery parameters (!). // // Once I find a way to bind None (NULL) consistently, I'll remove SQLDescribeParam completely. pT[i].sql_type = SQL_VARCHAR; pT[i].column_size = 1; pT[i].decimal_digits = 0; } } cur->paramdescs = pT; return true; } static int GetParamBufferSize(PyObject* param, Py_ssize_t iParam) { // Returns the size in bytes needed to hold the parameter in a format for binding, used to allocate the parameter // buffer. (The value is not passed to ODBC. Values passed to ODBC are in BindParam.) // // If we can bind directly into the Python object (e.g., using PyString_AsString), zero is returned since no extra // memory is required. If the data will be provided at execution time (e.g. SQL_DATA_AT_EXEC), zero is returned // since the parameter value is not stored at all. If the data type is not recognized, -1 is returned. if (param == Py_None) return 0; if (PyString_Check(param) || PyUnicode_Check(param)) return 0; if (param == Py_True || param == Py_False) return 1; if (PyInt_Check(param)) return sizeof(long int); if (PyLong_Check(param)) return sizeof(INT64); if (PyFloat_Check(param)) return sizeof(double); if (PyDecimal_Check(param)) { // There isn't an efficient way of getting the precision, but it's there and it's obvious. Object digits = PyObject_GetAttrString(param, "_int"); if (digits) return PySequence_Length(digits) + 3; // sign, decimal, null // _int doesn't exist any more? return 42; } if (PyBuffer_Check(param)) { // If the buffer has a single segment, we can bind directly to it, so we need 0 bytes. Otherwise, we'll use // SQL_DATA_AT_EXEC, so we still need 0 bytes. return 0; } if (PyDateTime_Check(param)) return sizeof(TIMESTAMP_STRUCT); if (PyDate_Check(param)) return sizeof(DATE_STRUCT); if (PyTime_Check(param)) return sizeof(TIME_STRUCT); RaiseErrorV("HY105", ProgrammingError, "Invalid parameter type. param-index=%zd param-type=%s", iParam, param->ob_type->tp_name); return -1; } #ifdef TRACE_ALL #define _MAKESTR(n) case n: return #n static const char* SqlTypeName(SQLSMALLINT n) { switch (n) { _MAKESTR(SQL_UNKNOWN_TYPE); _MAKESTR(SQL_CHAR); _MAKESTR(SQL_NUMERIC); _MAKESTR(SQL_DECIMAL); _MAKESTR(SQL_INTEGER); _MAKESTR(SQL_SMALLINT); _MAKESTR(SQL_FLOAT); _MAKESTR(SQL_REAL); _MAKESTR(SQL_DOUBLE); _MAKESTR(SQL_DATETIME); _MAKESTR(SQL_VARCHAR); _MAKESTR(SQL_TYPE_DATE); _MAKESTR(SQL_TYPE_TIME); _MAKESTR(SQL_TYPE_TIMESTAMP); _MAKESTR(SQL_SS_TIME2); } return "unknown"; } static const char* CTypeName(SQLSMALLINT n) { switch (n) { _MAKESTR(SQL_C_CHAR); _MAKESTR(SQL_C_LONG); _MAKESTR(SQL_C_SHORT); _MAKESTR(SQL_C_FLOAT); _MAKESTR(SQL_C_DOUBLE); _MAKESTR(SQL_C_NUMERIC); _MAKESTR(SQL_C_DEFAULT); _MAKESTR(SQL_C_DATE); _MAKESTR(SQL_C_TIME); _MAKESTR(SQL_C_TIMESTAMP); _MAKESTR(SQL_C_TYPE_DATE); _MAKESTR(SQL_C_TYPE_TIME); _MAKESTR(SQL_C_TYPE_TIMESTAMP); _MAKESTR(SQL_C_INTERVAL_YEAR); _MAKESTR(SQL_C_INTERVAL_MONTH); _MAKESTR(SQL_C_INTERVAL_DAY); _MAKESTR(SQL_C_INTERVAL_HOUR); _MAKESTR(SQL_C_INTERVAL_MINUTE); _MAKESTR(SQL_C_INTERVAL_SECOND); _MAKESTR(SQL_C_INTERVAL_YEAR_TO_MONTH); _MAKESTR(SQL_C_INTERVAL_DAY_TO_HOUR); _MAKESTR(SQL_C_INTERVAL_DAY_TO_MINUTE); _MAKESTR(SQL_C_INTERVAL_DAY_TO_SECOND); _MAKESTR(SQL_C_INTERVAL_HOUR_TO_MINUTE); _MAKESTR(SQL_C_INTERVAL_HOUR_TO_SECOND); _MAKESTR(SQL_C_INTERVAL_MINUTE_TO_SECOND); _MAKESTR(SQL_C_BINARY); _MAKESTR(SQL_C_BIT); _MAKESTR(SQL_C_SBIGINT); _MAKESTR(SQL_C_UBIGINT); _MAKESTR(SQL_C_TINYINT); _MAKESTR(SQL_C_SLONG); _MAKESTR(SQL_C_SSHORT); _MAKESTR(SQL_C_STINYINT); _MAKESTR(SQL_C_ULONG); _MAKESTR(SQL_C_USHORT); _MAKESTR(SQL_C_UTINYINT); _MAKESTR(SQL_C_GUID); } return "unknown"; } #endif static bool BindParam(Cursor* cur, int iParam, const ParamDesc* pDesc, PyObject* param, byte** ppbParam) { // Called to bind a single parameter. // // iParam // The one-based index of the parameter being bound. // // param // The parameter to bind. // // ppbParam // On entry, *ppbParam points to the memory available for binding the current parameter. It should be // incremented by the amount of memory used. // // Each parameter saves room for a length-indicator. If the Python object is not in a format that we can bind to // directly, the memory immediately after the length indicator is used to copy the parameter data in a usable // format. // // The memory used is determined by the type of PyObject. The total required is calculated, a buffer is // allocated, and passed repeatedly to this function. It is essential that the amount pre-calculated (from // GetParamBufferSize) match the amount used by this function. Any changes to either function must be // coordinated. (It might be wise to build a table. I would do a lot more with assertions, but building a debug // version of Python is a real pain. It would be great if the Python for Windows team provided a pre-built // version.) // When binding, ODBC requires 2 values: the column size and the buffer size. The column size is related to the // destination (the SQL type of the column being written to) and the buffer size refers to the source (the size of // the C data being written). If you send the wrong column size, data may be truncated. For example, if you send // sizeof(TIMESTAMP_STRUCT) as the column size when writing a timestamp, it will be rounded to the nearest minute // because that is the precision that would fit into a string of that size. // Every parameter reserves space for a length-indicator. Either set *pcbData to the actual input data length or // set pcbData to zero (not *pcbData) if you have a fixed-length parameter and don't need it. SQLLEN* pcbValue = reinterpret_cast<SQLLEN*>(*ppbParam); *ppbParam += sizeof(SQLLEN); // (I've made the parameter a pointer-to-a-pointer (ergo, the "pp") so that it is obvious at the call-site that we // are modifying it (&p). Here we save a pointer into the buffer which we can compare to pbValue later to see if // we bound into the buffer (pbValue == pbParam) or bound directly into `param` (pbValue != pbParam). // // (This const means that the data the pointer points to is not const, you can change *pbParam, but the actual // pointer itself is. We will be comparing the address to pbValue, not the contents.) byte* const pbParam = *ppbParam; SQLSMALLINT fCType = 0; SQLSMALLINT fSqlType = 0; SQLULEN cbColDef = 0; SQLSMALLINT decimalDigits = 0; SQLPOINTER pbValue = 0; // Set to the data to bind, either into `param` or set to pbParam. SQLLEN cbValueMax = 0; if (pDesc != 0 && pDesc->sql_type == SQL_BIT) { // We know the target type is a Boolean, so we'll use Python semantics and ask the object if it is 'true'. // (When using a database that won't give us the target types (pDesc == 0), users will have to pass a boolean // or an int. I don't like having different behavior, but we hope all ODBC drivers are improving and will // support the feature.) // // However, unlike Python, a database also supports NULL, so if the value is None, we'll keep it and write a // NULL to the database. if (param != Py_None) param = PyObject_IsTrue(param) ? Py_True : Py_False; // I'm not going to addref these since we aren't going to decref them either. Since they are global/singletons // we know they'll be around for the duration of this function. } if (param == Py_None) { fSqlType = pDesc ? pDesc->sql_type : SQL_VARCHAR; fCType = SQL_C_DEFAULT; *pcbValue = SQL_NULL_DATA; cbColDef = 1; } else if (PyString_Check(param)) { char* pch = PyString_AS_STRING(param); int len = PyString_GET_SIZE(param); if (len <= MAX_VARCHAR_BUFFER) { fSqlType = SQL_VARCHAR; fCType = SQL_C_CHAR; pbValue = pch; cbColDef = max(len, 1); cbValueMax = len + 1; *pcbValue = (SQLLEN)len; } else { fSqlType = SQL_LONGVARCHAR; fCType = SQL_C_CHAR; pbValue = param; cbColDef = max(len, 1); cbValueMax = sizeof(PyObject*); *pcbValue = SQL_LEN_DATA_AT_EXEC((SQLLEN)len); } } else if (PyUnicode_Check(param)) { Py_UNICODE* pch = PyUnicode_AsUnicode(param); int len = PyUnicode_GET_SIZE(param); if (len <= MAX_VARCHAR_BUFFER) { fSqlType = SQL_WVARCHAR; fCType = SQL_C_WCHAR; pbValue = pch; cbColDef = max(len, 1); cbValueMax = (len + 1) * Py_UNICODE_SIZE; *pcbValue = (SQLLEN)(len * Py_UNICODE_SIZE); } else { fSqlType = SQL_WLONGVARCHAR; fCType = SQL_C_WCHAR; pbValue = param; cbColDef = max(len, 1) * sizeof(SQLWCHAR); cbValueMax = sizeof(PyObject*); *pcbValue = SQL_LEN_DATA_AT_EXEC((SQLLEN)(len * Py_UNICODE_SIZE)); } } else if (param == Py_True || param == Py_False) { *pbParam = (unsigned char)(param == Py_True ? 1 : 0); fSqlType = SQL_BIT; fCType = SQL_C_BIT; pbValue = pbParam; cbValueMax = 1; pcbValue = 0; } else if (PyDateTime_Check(param)) { TIMESTAMP_STRUCT* value = (TIMESTAMP_STRUCT*)pbParam; value->year = (SQLSMALLINT) PyDateTime_GET_YEAR(param); value->month = (SQLUSMALLINT)PyDateTime_GET_MONTH(param); value->day = (SQLUSMALLINT)PyDateTime_GET_DAY(param); value->hour = (SQLUSMALLINT)PyDateTime_DATE_GET_HOUR(param); value->minute = (SQLUSMALLINT)PyDateTime_DATE_GET_MINUTE(param); value->second = (SQLUSMALLINT)PyDateTime_DATE_GET_SECOND(param); // SQL Server chokes if the fraction has more data than the database supports. We expect other databases to be // the same, so we reduce the value to what the database supports. // http://support.microsoft.com/kb/263872 int precision = ((Connection*)cur->cnxn)->datetime_precision - 20; // (20 includes a separating period) if (precision <= 0) { value->fraction = 0; } else { value->fraction = (SQLUINTEGER)(PyDateTime_DATE_GET_MICROSECOND(param) * 1000); // 1000 == micro -> nano // (How many leading digits do we want to keep? With SQL Server 2005, this should be 3: 123000000) int keep = (int)pow(10.0, 9-min(9, precision)); value->fraction = value->fraction / keep * keep; decimalDigits = (SQLSMALLINT)precision; } fSqlType = SQL_TIMESTAMP; fCType = SQL_C_TIMESTAMP; pbValue = pbParam; cbColDef = ((Connection*)cur->cnxn)->datetime_precision; cbValueMax = sizeof(TIMESTAMP_STRUCT); pcbValue = 0; } else if (PyDate_Check(param)) { DATE_STRUCT* value = (DATE_STRUCT*)pbParam; value->year = (SQLSMALLINT) PyDateTime_GET_YEAR(param); value->month = (SQLUSMALLINT)PyDateTime_GET_MONTH(param); value->day = (SQLUSMALLINT)PyDateTime_GET_DAY(param); fSqlType = SQL_TYPE_DATE; fCType = SQL_C_TYPE_DATE; pbValue = pbParam; cbColDef = 10; // The size of date represented as a string (yyyy-mm-dd) cbValueMax = sizeof(DATE_STRUCT); pcbValue = 0; } else if (PyTime_Check(param)) { TIME_STRUCT* value = (TIME_STRUCT*)pbParam; value->hour = (SQLUSMALLINT)PyDateTime_TIME_GET_HOUR(param); value->minute = (SQLUSMALLINT)PyDateTime_TIME_GET_MINUTE(param); value->second = (SQLUSMALLINT)PyDateTime_TIME_GET_SECOND(param); fSqlType = SQL_TYPE_TIME; fCType = SQL_C_TIME; pbValue = pbParam; cbColDef = 8; cbValueMax = sizeof(TIME_STRUCT); pcbValue = 0; } else if (PyInt_Check(param)) { long* value = (long*)pbParam; *value = PyInt_AsLong(param); fSqlType = SQL_INTEGER; fCType = SQL_C_LONG; pbValue = pbParam; cbValueMax = sizeof(long); pcbValue = 0; } else if (PyLong_Check(param)) { INT64* value = (INT64*)pbParam; *value = PyLong_AsLongLong(param); fSqlType = SQL_BIGINT; fCType = SQL_C_SBIGINT; pbValue = pbParam; cbValueMax = sizeof(INT64); pcbValue = 0; } else if (PyFloat_Check(param)) { double* value = (double*)pbParam; *value = PyFloat_AsDouble(param); fSqlType = SQL_DOUBLE; fCType = SQL_C_DOUBLE; pbValue = pbParam; cbValueMax = sizeof(double); pcbValue = 0; } else if (PyDecimal_Check(param)) { // Using the ODBC binary format would eliminate issues of whether to use '.' vs ',', but I've had unending // problems attemting to bind the decimal using the binary struct. In particular, the scale is never honored // properly. It appears that drivers have lots of bugs. For now, we'll copy the value into a string, manually // change '.' to the database's decimal value. (At this point, it appears that the decimal class *always* uses // '.', regardless of the user's locale.) // GetParamBufferSize reserved room for the string length, which may include a sign and decimal. Object str = PyObject_CallMethod(param, "__str__", 0); if (!str) return false; char* pch = PyString_AS_STRING(str.Get()); int len = PyString_GET_SIZE(str.Get()); *pcbValue = (SQLLEN)len; // Note: SQL_DECIMAL here works for SQL Server but is not handled by MS Access. SQL_NUMERIC seems to work for // both, probably because I am providing exactly NUMERIC(p,s) anyway. fSqlType = SQL_NUMERIC; fCType = SQL_C_CHAR; pbValue = pbParam; cbColDef = len; memcpy(pbValue, pch, len + 1); cbValueMax = len + 1; char* pchDecimal = strchr((char*)pbValue, '.'); if (pchDecimal) { decimalDigits = (SQLSMALLINT)(len - (pchDecimal - (char*)pbValue) - 1); if (chDecimal != '.') *pchDecimal = chDecimal; // (pointing into our own copy in pbValue) } } else if (PyBuffer_Check(param)) { const char* pb; int cb = PyBuffer_GetMemory(param, &pb); if (cb != -1 && cb <= MAX_VARBINARY_BUFFER) { // There is one segment, so we can bind directly into the buffer object. fCType = SQL_C_BINARY; fSqlType = SQL_VARBINARY; pbValue = (SQLPOINTER)pb; cbValueMax = cb; cbColDef = max(cb, 1); *pcbValue = cb; } else { // There are multiple segments, so we'll provide the data at execution time. Pass the PyObject pointer as // the parameter value which will be pased back to us when the data is needed. (If we release threads, we // need to up the refcount!) fCType = SQL_C_BINARY; fSqlType = SQL_LONGVARBINARY; pbValue = param; cbColDef = PyBuffer_Size(param); cbValueMax = sizeof(PyObject*); // How big is pbValue; ODBC copies it and gives it back in SQLParamData *pcbValue = SQL_LEN_DATA_AT_EXEC(PyBuffer_Size(param)); } } else { RaiseErrorV("HY097", NotSupportedError, "Python type %s not supported. param=%d", param->ob_type->tp_name, iParam); return false; } #ifdef TRACE_ALL printf("BIND: param=%d fCType=%d (%s) fSqlType=%d (%s) cbColDef=%d DecimalDigits=%d cbValueMax=%d *pcb=%d\n", iParam, fCType, CTypeName(fCType), fSqlType, SqlTypeName(fSqlType), cbColDef, decimalDigits, cbValueMax, pcbValue ? *pcbValue : 0); #endif SQLRETURN ret = -1; Py_BEGIN_ALLOW_THREADS ret = SQLBindParameter(cur->hstmt, (SQLUSMALLINT)iParam, SQL_PARAM_INPUT, fCType, fSqlType, cbColDef, decimalDigits, pbValue, cbValueMax, pcbValue); Py_END_ALLOW_THREADS; if (GetConnection(cur)->hdbc == SQL_NULL_HANDLE) { // The connection was closed by another thread in the ALLOW_THREADS block above. RaiseErrorV(0, ProgrammingError, "The cursor's connection was closed."); return false; } if (!SQL_SUCCEEDED(ret)) { RaiseErrorFromHandle("SQLBindParameter", GetConnection(cur)->hdbc, cur->hstmt); return false; } if (pbValue == pbParam) { // We are using the passed in buffer to bind; skip past the amount of buffer we used. *ppbParam += cbValueMax; } return true; }
[ [ [ 1, 750 ] ] ]
04b67f956ae04de3a18c8508673901835ecfa4c8
a51ac532423cf58c35682415c81aee8e8ae706ce
/CameraAPI/DummyDriver.cpp
30d1bb56ec0ef78b7edd1149cc6c645cecd6f049
[]
no_license
anderslindmark/PickNPlace
b9a89fb2a6df839b2b010b35a0c873af436a1ab9
00ca4f6ce2ecfeddfea7db5cb7ae8e9d0023a5e1
refs/heads/master
2020-12-24T16:59:20.515351
2008-05-25T01:32:31
2008-05-25T01:32:31
34,914,321
1
0
null
null
null
null
UTF-8
C++
false
false
1,103
cpp
#include "DummyDriver.h" #include "DummyCamera.h" #include "log.h" #include <sstream> namespace camera { DummyDriver::DummyDriver() { LOG_TRACE("DummyDriver::DummyDriver()"); m_width = 256; m_height = 256; } DummyDriver::~DummyDriver() { LOG_TRACE("DummyDriver::~DummyDriver()"); } void DummyDriver::updateCameraIdentifiers() { LOG_TRACE("DummyDriver::updateCameraIdentifiers()"); } int DummyDriver::getCameraIdentifierCount() { LOG_TRACE("DummyDriver::getCameraIdentifierCount()"); return 3; } std::string DummyDriver::getCameraIdentifier(int index) { LOG_TRACE("DummyDriver::getCameraIdentifier()"); std::stringstream ss; ss << "camera" << index; return ss.str(); } Camera *DummyDriver::createCamera(const std::string &identifier) { LOG_TRACE("DummyDriver::createCamera()"); LOG_DEBUG("DummyDriver::createCamera(): Creating camera " << identifier); return new DummyCamera(m_width, m_height); } void DummyDriver::setImageSize(int width, int height) { m_width = width; m_height = height; } } // namespace camera
[ "kers@f672c3ff-8b41-4f22-a4ab-2adcb4f732c7", "js@f672c3ff-8b41-4f22-a4ab-2adcb4f732c7" ]
[ [ [ 1, 5 ], [ 8, 42 ], [ 44, 48 ], [ 51, 55 ] ], [ [ 6, 7 ], [ 43, 43 ], [ 49, 50 ] ] ]
19d723cf10771f75da794c1aa1908df69c5dbcc2
b84a38aad619acf34c22ed6e6caa0f7b00ebfa0a
/Code/TootleFilesys/TFileSimpleVector.cpp
bd60dda8fc221880916fa6c50a2ee7de960dc1a3
[]
no_license
SoylentGraham/Tootle
4ae4e8352f3e778e3743e9167e9b59664d83b9cb
17002da0936a7af1f9b8d1699d6f3e41bab05137
refs/heads/master
2021-01-24T22:44:04.484538
2010-11-03T22:53:17
2010-11-03T22:53:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
26,251
cpp
#include "TFileSimpleVector.h" #include <TootleAsset/TMesh.h> #include <TootleMaths/TTessellate.h> #include "TLFile.h" TLFileSys::TFileSimpleVector::TFileSimpleVector(TRefRef FileRef,TRefRef FileTypeRef) : TFileXml ( FileRef, FileTypeRef ), m_SvgPointScale ( 1.f ), m_SvgLayerZIncrement ( 0.5f ), m_VertexColoursEnabled ( TRUE ), m_ProjectUVsEnabled ( FALSE ) { } //-------------------------------------------------------- // import the XML and convert from SVG to mesh //-------------------------------------------------------- SyncBool TLFileSys::TFileSimpleVector::ExportAsset(TPtr<TLAsset::TAsset>& pAsset,TRefRef ExportAssetType) { if ( pAsset ) { TLDebug_Break("Async export not supported yet. asset should be NULL"); return SyncFalse; } // import xml SyncBool ImportResult = TFileXml::Import(); if ( ImportResult != SyncTrue ) return ImportResult; // get the root svg tag (all items are under this and contains scene info) TPtr<TXmlTag> pSvgTag = m_XmlData.GetChild("svg"); // malformed SVG maybe if ( !pSvgTag ) return SyncFalse; s32 i; // delete branches we dont care about for ( i=pSvgTag->GetChildren().GetLastIndex(); i>=0; i-- ) { TXmlTag& Tag = *pSvgTag->GetChildren().ElementAt(i); // keep these kinds of tags if ( Tag.GetTagType() == TLXml::TagType_OpenClose || Tag.GetTagType() == TLXml::TagType_SelfClose ) { continue; } // delete this tag pSvgTag->GetChildren().RemoveAt(i); } // no data if ( pSvgTag->GetChildren().GetSize() == 0 ) return SyncFalse; // create mesh asset TPtr<TLAsset::TMesh> pNewMesh = new TLAsset::TMesh( GetFileRef() ); // init scale m_SvgPointScale = 1.f; // check for options const TString* pVertexColoursProperty = pSvgTag->GetProperty("TootleVertexColours"); if ( pVertexColoursProperty ) m_VertexColoursEnabled = !pVertexColoursProperty->IsEqual("false",FALSE); const TString* pProjectUVsProperty = pSvgTag->GetProperty("TootleProjectUVs"); if ( pProjectUVsProperty ) m_ProjectUVsEnabled = !pProjectUVsProperty->IsEqual("false",FALSE); // old style defualt scalar was [document width] = [1 unit] float DimensionScalar = 1.f; // find dimensions float Width = 100.f; const TString* pWidthString = pSvgTag->GetProperty("width"); if ( pWidthString ) pWidthString->GetFloat(Width); // new scale format - if set then the width is relative to a ortho screen width (ie. 100 wide) instead of 1 unit wide // gr: now uses document width, so 100 width assumes orhto camera of 100 const TString* pOrthoScaleProperty = pSvgTag->GetProperty("TootleOrthoScale"); if ( pOrthoScaleProperty ) if ( !pOrthoScaleProperty->IsEqual("false",FALSE) ) DimensionScalar = Width; // set scale m_SvgPointScale = Width <= 0.f ? 1.f : DimensionScalar / Width; // init offset m_SvgPointMove.Set( 0.f, 0.f, 0.f ); // parse xml to mesh (and it's children) if ( !ImportMesh( pNewMesh, *pSvgTag ) ) return SyncFalse; // set projection UVs if ( m_ProjectUVsEnabled ) pNewMesh->CalcProjectionUVs(); // assign resulting asset pAsset = pNewMesh; pNewMesh->CalcBounds(); return SyncTrue; } //-------------------------------------------------------- // generate mesh data from this SVG tag //-------------------------------------------------------- Bool TLFileSys::TFileSimpleVector::ImportMesh(TPtr<TLAsset::TMesh>& pMesh,TXmlTag& Tag) { // deal with child tags for ( u32 c=0; c<Tag.GetChildren().GetSize(); c++ ) { TXmlTag& ChildTag = *Tag.GetChildren().ElementAt(c); if ( ChildTag.GetTagName() == "polygon" ) { if ( !ImportPolygonTag( pMesh, ChildTag ) ) return FALSE; } else if ( ChildTag.GetTagName() == "path" ) { if ( !ImportPathTag( pMesh, ChildTag ) ) return FALSE; } else if ( ChildTag.GetTagName() == "rect" ) { if ( !ImportRectTag( pMesh, ChildTag ) ) return FALSE; } // unknown type, make a new child out of it if ( !ChildTag.GetChildren().GetSize() ) continue; float OldZ = m_SvgPointMove.z; // every time we go deeper down the tree increment the z m_SvgPointMove.z += m_SvgLayerZIncrement; if ( !ImportMesh( pMesh, ChildTag ) ) return FALSE; // verify mesh if ( !pMesh->Debug_Verify() ) return false; // restore z //m_SvgPointMove.z = OldZ; } return TRUE; } //-------------------------------------------------------- // convert Polygon tag to mesh info and add to mesh //-------------------------------------------------------- Bool TLFileSys::TFileSimpleVector::ImportPolygonTag(TPtr<TLAsset::TMesh>& pMesh,TXmlTag& Tag) { const TString* pString = Tag.GetProperty("points"); if ( !pString ) { if ( TLDebug_Break("Expected points property of svg for <polygon>") ) return FALSE; return TRUE; } // empty string.. empty polygon u32 StringLength = pString->GetLength(); if ( StringLength == 0 ) return TRUE; // THeapArray<TTempString> NumberPairs; if ( !pString->Split(' ', NumberPairs ) ) { TLDebug_Break("No numbers?"); return FALSE; } // split pairs into point numbers, then into vertex positions THeapArray<float3> OutlinePoints; for ( u32 i=0; i<NumberPairs.GetSize(); i++ ) { THeapArray<TTempString> PointStrings; if ( !NumberPairs[i].Split( ',', PointStrings ) ) { if ( TLDebug_Break( TString("Error splitting pair of numbers: %s", NumberPairs[i].GetData() ) ) ) return FALSE; continue; } // turn first string into a number float2 Point; if ( !PointStrings[0].GetFloat( Point.x ) ) { if ( TLDebug_Break("Invalid number found in number pair") ) return FALSE; continue; } if ( !PointStrings[1].GetFloat( Point.y ) ) { if ( TLDebug_Break("Invalid number found in number pair") ) return FALSE; continue; } float3 VertexPos = CoordinateToVertexPos( Point ); OutlinePoints.Add( VertexPos ); } // empty, but not invalid, nothing to create if ( OutlinePoints.GetSize() == 0 ) return TRUE; // turn into datum instead of geometry TRef DatumRef,DatumShapeType; Bool IsJustDatum=TRUE; if ( IsTagDatum( Tag, DatumRef, DatumShapeType, IsJustDatum ) ) { pMesh->CreateDatum( OutlinePoints, DatumRef, DatumShapeType ); // just a datum, don't create geometry if ( IsJustDatum ) return TRUE; } // turn into a polygon in the mesh TLMaths::TTessellator* pTessellator = TLMaths::Platform::CreateTessellator( pMesh ); if ( !pTessellator ) return FALSE; TPtr<TLMaths::TContour> pContour = new TLMaths::TContour( OutlinePoints, NULL ); pTessellator->AddContour(pContour); if ( !pTessellator->GenerateTessellations( TLMaths::TLTessellator::WindingMode_Odd ) ) return FALSE; return TRUE; } //-------------------------------------------------------- // convert Polygon tag to mesh info and add to mesh // http://www.w3.org/TR/SVG/paths.html#PathElement //-------------------------------------------------------- Bool TLFileSys::TFileSimpleVector::ImportPathTag(TPtr<TLAsset::TMesh>& pMesh,TXmlTag& Tag) { const TString* pString = Tag.GetProperty("d"); if ( !pString ) { if ( TLDebug_Break("Expected d property of svg for <path>") ) return FALSE; return TRUE; } const TString& String = *pString; // empty string.. empty polygon u32 StringLength = String.GetLength(); if ( StringLength == 0 ) return TRUE; TPtrArray<TLMaths::TContour> Contours; THeapArray<TLMaths::TContourCurve> PathCurves; THeapArray<float3> PathPoints; TChar LastCommand = 0x0; float2 CurrentPosition; // parse commands in string u32 CharIndex = 0; while ( CharIndex<String.GetLength() ) { // read next command TChar NewCommand; if ( TLString::ReadNextLetter( String, CharIndex, NewCommand ) ) { Bool FindNewCommand = FALSE; // process command switch ( NewCommand ) { case 'z': // finish contour case 'Z': // finish contour { // finish current contour if ( PathPoints.GetSize() ) { TPtr<TLMaths::TContour> pNewContour = new TLMaths::TContour( PathPoints, &PathCurves ); Contours.Add( pNewContour ); PathPoints.Empty(); PathCurves.Empty(); } LastCommand = NewCommand; // gr: maybe get rid of this and expect an M next? FindNewCommand = TRUE; break; } case 'm': case 'M': // new contour { // finish current contour if ( PathPoints.GetSize() ) { TPtr<TLMaths::TContour> pNewContour = new TLMaths::TContour( PathPoints, &PathCurves ); Contours.Add( pNewContour ); PathPoints.Empty(); PathCurves.Empty(); } // start new contour by fetching the initial pos float2 InitialPos; if ( !TLString::ReadNextFloat( String, CharIndex, InitialPos ) ) return FALSE; PathPoints.Add( CoordinateToVertexPos( InitialPos ) ); PathCurves.Add( TLMaths::ContourCurve_On ); CurrentPosition = InitialPos; LastCommand = NewCommand; FindNewCommand = TRUE; } break; case 'l': case 'L': // line to here case 'c': case 'C': // line to here { // set command and let code continue to do simple process LastCommand = NewCommand; } break; case 'a': // arc (relative) case 'A': // arc (absolute) { // set command and let code continue to do simple process LastCommand = NewCommand; } break; case 'S': // shorthand curve case 'Q': // quadratic bezier curve case 'T': // shorthand quadratic bezier curve { TLDebug_Print( TString("Unhandled <path> command: %c", NewCommand ) ); // no error with structure, we just cant import this path return TRUE; } break; default: TLDebug_Break( TString("Unknown <path> command: %c", NewCommand ) ); // no error with structure, we just cant import this path return TRUE; continue; } // if we want to just go onto the next command then skip over continue-processing below if ( FindNewCommand ) continue; } // no command, continue last command // line if ( LastCommand == 'L' || LastCommand == 'l' || LastCommand == 'H' || LastCommand == 'V' ) { float2 NewPos = CurrentPosition; if ( LastCommand == 'L' || LastCommand == 'l') { // read new pos if ( !TLString::ReadNextFloat( String, CharIndex, NewPos ) ) return FALSE; if ( TLString::IsCharLowercase( LastCommand ) ) NewPos += CurrentPosition; } else if ( LastCommand == 'H' ) { // read new x float NewX; if ( !TLString::ReadNextFloat( String, CharIndex, NewX ) ) return FALSE; if ( TLString::IsCharLowercase( LastCommand ) ) NewPos.x += NewX; else NewPos.x = NewX; } else if ( LastCommand == 'V' ) { // read new x float NewY; if ( !TLString::ReadNextFloat( String, CharIndex, NewY ) ) return FALSE; if ( TLString::IsCharLowercase( LastCommand ) ) NewPos.y += NewY; else NewPos.y = NewY; } // continue line PathPoints.Add( CoordinateToVertexPos( NewPos ) ); PathCurves.Add( TLMaths::ContourCurve_On ); CurrentPosition = NewPos; } else if(( LastCommand == 'C' ) || ( LastCommand == 'c' )) { // cubic curve - // read control point A (before) float2 CubicControlPointA; if ( !TLString::ReadNextFloat( String, CharIndex, CubicControlPointA ) ) return FALSE; // read control point B (after) float2 CubicControlPointB; if ( !TLString::ReadNextFloat( String, CharIndex, CubicControlPointB ) ) return FALSE; // read end point (on) float2 CubicPointPosition; if ( !TLString::ReadNextFloat( String, CharIndex, CubicPointPosition ) ) return FALSE; // first cubic point is last point in points if ( !PathPoints.GetSize() ) { TLDebug_Break("Expected a previous point to start the cubic curve from... maybe need to add the pos from M?"); continue; } float2 NewPosition, NewCubicControlPointA, NewCubicControlPointB; if ( TLString::IsCharLowercase( LastCommand ) ) { // Relative points NewPosition = CurrentPosition + CubicPointPosition; NewCubicControlPointA = CurrentPosition + CubicControlPointA; NewCubicControlPointB = CurrentPosition + CubicControlPointB; } else { // Absolute point NewPosition = CubicPointPosition; NewCubicControlPointA = CubicControlPointA; NewCubicControlPointB = CubicControlPointB; } // add these in the right order (as per tesselator) PathPoints.Add( CoordinateToVertexPos( NewCubicControlPointA ) ); PathCurves.Add( TLMaths::ContourCurve_Cubic ); PathPoints.Add( CoordinateToVertexPos( NewCubicControlPointB ) ); PathCurves.Add( TLMaths::ContourCurve_Cubic ); PathPoints.Add( CoordinateToVertexPos( NewPosition ) ); PathCurves.Add( TLMaths::ContourCurve_On ); CurrentPosition = NewPosition; } else if(( LastCommand == 'A' ) || ( LastCommand == 'a' )) { // arc - // Read radii (rx,ry) float2 Radii; if ( !TLString::ReadNextFloat( String, CharIndex, Radii ) ) return FALSE; // read x-axis rotation float XAxisRot; if ( !TLString::ReadNextFloat( String, CharIndex, XAxisRot ) ) return FALSE; // read sweep flag and arc flag float2 flags; if ( !TLString::ReadNextFloat( String, CharIndex, flags ) ) return FALSE; // read end point (on) float2 ArcEndPosition; if ( !TLString::ReadNextFloat( String, CharIndex, ArcEndPosition ) ) return FALSE; // first cubic point is last point in points if ( !PathPoints.GetSize() ) { TLDebug_Break("Expected a previous point to start the cubic curve from... maybe need to add the pos from M?"); continue; } float2 NewPosition; if ( TLString::IsCharLowercase( LastCommand ) ) { // Relative points NewPosition = CurrentPosition + ArcEndPosition; } else { // Absolute point NewPosition = ArcEndPosition; } // add these in the right order (as per tesselator) //PathPoints.Add( Radii); //PathCurves.Add( TLMaths::ContourCurve_Arc ); PathPoints.Add( CoordinateToVertexPos( NewPosition ) ); PathCurves.Add( TLMaths::ContourCurve_On ); CurrentPosition = NewPosition; } else if ( LastCommand == 'Z' || LastCommand == 'z' ) { CharIndex++; continue; } else { TLDebug_Break("Unhandled last command "); return FALSE; } } // finish current contour if wasn't ended by a command if ( PathPoints.GetSize() ) { TPtr<TLMaths::TContour> pNewContour = new TLMaths::TContour( PathPoints, &PathCurves ); Contours.Add( pNewContour ); PathPoints.Empty(); PathCurves.Empty(); } if ( !Contours.GetSize() ) return FALSE; // turn into datum instead of geometry TRef DatumRef,DatumShapeType; Bool IsJustDatum = TRUE; if ( IsTagDatum( Tag, DatumRef, DatumShapeType, IsJustDatum ) ) { if ( Contours.GetSize() == 1 ) { pMesh->CreateDatum( Contours[0]->GetPoints(), DatumRef, DatumShapeType ); } else { // put all contour points into one array of points THeapArray<float3> ContourPoints; for ( u32 c=0; c<Contours.GetSize(); c++ ) ContourPoints.Add( Contours[c]->GetPoints() ); pMesh->CreateDatum( ContourPoints, DatumRef, DatumShapeType ); } // skip creating geometry if datum is marked as just a datum if ( IsJustDatum ) return TRUE; } // create geometry // get style Style TagStyle( Tag.GetProperty("style") ); // if a filled vector then create tesselations from the outline if ( TagStyle.m_HasFill ) { // tesselate those bad boys! TLMaths::TTessellator* pTessellator = TLMaths::Platform::CreateTessellator( pMesh ); if ( pTessellator ) { u32 ContourCount = Contours.GetSize(); if ( ContourCount > 1 ) ContourCount = 1; for ( u32 c=0; c<ContourCount; c++ ) { pTessellator->AddContour( Contours[c] ); } pTessellator->SetVertexColour( m_VertexColoursEnabled ? &TagStyle.m_FillColour : NULL ); pTessellator->GenerateTessellations( TLMaths::TLTessellator::WindingMode_Odd ); } } if ( TagStyle.m_HasStroke ) { CreateMeshLines( *pMesh, Contours, TagStyle ); } return TRUE; } //-------------------------------------------------------- // convert rect tag into a polygon //-------------------------------------------------------- Bool TLFileSys::TFileSimpleVector::ImportRectTag(TPtr<TLAsset::TMesh>& pMesh,TXmlTag& Tag) { // get rect strings const TString* pLeftString = Tag.GetProperty("x"); const TString* pTopString = Tag.GetProperty("y"); const TString* pWidthString = Tag.GetProperty("width"); const TString* pHeighthString = Tag.GetProperty("height"); if ( !pWidthString || !pHeighthString || !pLeftString || !pTopString ) { if ( TLDebug_Break("Expected x/y/w/h properties of svg for <rect>") ) return FALSE; return TRUE; } // get style Style TagStyle( Tag.GetProperty("style") ); // create rect float4 Rect; Bool AnyError = FALSE; AnyError |= !pLeftString->GetFloat( Rect.Left() ); AnyError |= !pTopString->GetFloat( Rect.Top() ); AnyError |= !pWidthString->GetFloat( Rect.Width() ); AnyError |= !pHeighthString->GetFloat( Rect.Height() ); if ( AnyError ) { if ( TLDebug_Break("Failed to parse x/y/w/h string for dimensions of svg <rect>") ) return FALSE; return TRUE; } float2 PointTopLeft( Rect.Left(), Rect.Top() ); float2 PointTopRight( Rect.Right(), Rect.Top() ); float2 PointBottomLeft( Rect.Left(), Rect.Bottom() ); float2 PointBottomRight( Rect.Right(), Rect.Bottom() ); // vertex outline TFixedArray<float3,4> Vertexes; Vertexes.Add( CoordinateToVertexPos( PointTopLeft ) ); Vertexes.Add( CoordinateToVertexPos( PointTopRight ) ); Vertexes.Add( CoordinateToVertexPos( PointBottomRight ) ); Vertexes.Add( CoordinateToVertexPos( PointBottomLeft ) ); // turn into datum instead of geometry TRef DatumRef,DatumShapeType; Bool IsJustDatum = TRUE; if ( IsTagDatum( Tag, DatumRef, DatumShapeType, IsJustDatum ) ) { pMesh->CreateDatum( Vertexes, DatumRef, DatumShapeType ); // skip creating geometry if just a datum if ( IsJustDatum ) return TRUE; } if ( TagStyle.m_HasFill || TagStyle.m_HasStroke ) // create polygons { // create quad if ( TagStyle.m_HasFill ) { pMesh->GenerateQuad( Vertexes, m_VertexColoursEnabled ? &TagStyle.m_FillColour : NULL ); } // create line strip if ( TagStyle.m_HasStroke ) { TLAsset::TMesh::Linestrip* pNewLinestrip = pMesh->GetLinestrips().AddNew(); TLAsset::TMesh::Tristrip& NewLinestrip = *pNewLinestrip; NewLinestrip.Add( pMesh->AddVertex( Vertexes[0], m_VertexColoursEnabled ? &TagStyle.m_StrokeColour : NULL ) ); NewLinestrip.Add( pMesh->AddVertex( Vertexes[1], m_VertexColoursEnabled ? &TagStyle.m_StrokeColour : NULL ) ); NewLinestrip.Add( pMesh->AddVertex( Vertexes[2], m_VertexColoursEnabled ? &TagStyle.m_StrokeColour : NULL ) ); NewLinestrip.Add( pMesh->AddVertex( Vertexes[3], m_VertexColoursEnabled ? &TagStyle.m_StrokeColour : NULL ) ); } } return TRUE; } //-------------------------------------------------------- // move & scale coordinate and convert to float3 //-------------------------------------------------------- float3 TLFileSys::TFileSimpleVector::CoordinateToVertexPos(const float2& Coordinate) { float3 NewPos( Coordinate.x, Coordinate.y, 0.f ); NewPos += m_SvgPointMove; NewPos *= m_SvgPointScale; return NewPos; } //-------------------------------------------------------- // create line strips on mesh from a list of contours //-------------------------------------------------------- void TLFileSys::TFileSimpleVector::CreateMeshLines(TLAsset::TMesh& Mesh,TPtrArray<TLMaths::TContour>& Contours,Style& LineStyle) { for ( u32 c=0; c<Contours.GetSize(); c++ ) { CreateMeshLineStrip( Mesh, *Contours[c], LineStyle ); } } //-------------------------------------------------------- // create line strip on mesh from a contour //-------------------------------------------------------- void TLFileSys::TFileSimpleVector::CreateMeshLineStrip(TLAsset::TMesh& Mesh,TLMaths::TContour& Contour,Style& LineStyle) { const TArray<float3>& ContourPoints = Contour.GetPoints(); TLAsset::TMesh::Linestrip* pNewLine = Mesh.GetLinestrips().AddNew(); if ( !pNewLine ) return; s32 FirstVertex = -1; for ( u32 p=0; p<=ContourPoints.GetSize(); p++ ) { s32 VertexIndex = -1; // need to add the first vert to the last line to keep a loop if we split it up if ( p >= ContourPoints.GetSize() ) { // still the original line if ( p < TLAsset::g_MaxLineStripSize ) break; VertexIndex = FirstVertex; } else { VertexIndex = Mesh.AddVertex( ContourPoints[p], m_VertexColoursEnabled ? &LineStyle.m_StrokeColour : NULL ); } pNewLine->Add( VertexIndex ); if ( FirstVertex == -1 ) FirstVertex = VertexIndex; // gr: need to cut up the line if ( p < ContourPoints.GetSize() && pNewLine->GetSize() >= TLAsset::g_MaxLineStripSize ) { // make new line pNewLine = Mesh.GetLinestrips().AddNew(); if ( !pNewLine ) break; // start line at current vert so it doesnt break the line pNewLine->Add( VertexIndex ); } } } //-------------------------------------------------------- // check if tag marked as a datum //-------------------------------------------------------- Bool TLFileSys::TFileSimpleVector::IsTagDatum(TXmlTag& Tag,TRef& DatumRef,TRef& ShapeType,Bool& IsJustDatum) { // get the "id" property const TString* pIDString = Tag.GetProperty("id"); if ( !pIDString ) return FALSE; // check if string marked as a datum return TLString::IsDatumString( *pIDString, DatumRef, ShapeType, IsJustDatum ); } TLFileSys::TFileSimpleVector::Style::Style(const TString* pStyleString) : m_HasFill ( TRUE ), // by default we fill the polygon m_FillColour ( 1.f, 1.f, 1.f, 1.f ), m_HasStroke ( FALSE ), m_StrokeColour ( 1.f, 1.f, 1.f, 1.f ), m_StrokeWidth ( 0.f ) { // parse string Parse( pStyleString ); } //-------------------------------------------------------- // parse string and get style elements //-------------------------------------------------------- Bool TLFileSys::TFileSimpleVector::Style::Parse(const TString& StyleString) { // empty string if ( StyleString.GetLength() == 0 ) return FALSE; // example: // style="fill:#192bed;fill-opacity:0.44767445;stroke:none;stroke-width:2.26799989000000000;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1" // split string at semi colons THeapArray<TTempString> PropertyStrings; StyleString.Split( ';', PropertyStrings ); // make up properties TKeyArray<TTempString,TString> Properties; for ( u32 p=0; p<PropertyStrings.GetSize(); p++ ) { // split property TFixedArray<TTempString,2> PropertyParts; PropertyStrings[p].Split(':', PropertyParts); Properties.Add( PropertyParts[0], PropertyParts[1] ); } // get specific properties // get fill colour TString* pFillColour = Properties.Find("fill"); if ( pFillColour ) { m_HasFill = SetColourFromString( m_FillColour, *pFillColour ); } // get fill alpha TString* pFillAlpha = Properties.Find("fill-opacity"); if ( pFillAlpha ) { pFillAlpha->GetFloat( m_FillColour.GetAlphaf() ); } // see if it has a stroke or not TString* pStrokeColour = Properties.Find("stroke"); if ( pStrokeColour ) { m_HasStroke = SetColourFromString( m_StrokeColour, *pStrokeColour ); } // get stroke line size TString* pStrokeWidth = Properties.Find("stroke-width"); if ( pStrokeWidth ) { pStrokeWidth->GetFloat( m_StrokeWidth ); } // get stroke alpha TString* pStrokeAlpha = Properties.Find("stroke-opacity"); if ( pStrokeAlpha ) { pStrokeAlpha->GetFloat( m_StrokeColour.GetAlphaf() ); } return TRUE; } //-------------------------------------------------------- // extracts a colour from a string. returns FALSE if no colour or failed to parse //-------------------------------------------------------- Bool TLFileSys::TFileSimpleVector::Style::SetColourFromString(TColour& Colour,const TString& ColourString) { u32 Length = ColourString.GetLength(); // if string is empty, no colour if ( Length < 1 ) return FALSE; // colour is "none" so no colour if ( ColourString == "none" ) return FALSE; // todo: get string colours, "red", "blue", etc // is a hex colour? if ( ColourString[0] == '#' ) { // specific length expected if ( Length != 6 + 1 ) { TLDebug_Break("String not long enough to be a hex colour e.g. #ffffff"); return FALSE; } // split into individual strings for each hex part of the colour TTempString RedString; RedString.Append( ColourString, 1, 2 ); TTempString GreenString; GreenString.Append( ColourString, 3, 2 ); TTempString BlueString; BlueString.Append( ColourString, 5, 2 ); u32 r,g,b; Bool AnyError = FALSE; AnyError |= !RedString.GetHexInteger( r ); AnyError |= !GreenString.GetHexInteger( g ); AnyError |= !BlueString.GetHexInteger( b ); if ( AnyError || r>255 || g>255 || b>255 ) { TLDebug_Break("Failed to parse red, green or blue" ); return FALSE; } // set colour Colour.Set( r, g, b, Colour.GetAlpha8() ); return TRUE; } else { // not a hex colour... dunno how to parse this - please write all examples here in the comments :) TLDebug_Break("Don't know how to parse colour string in style"); return FALSE; } }
[ [ [ 1, 7 ], [ 10, 11 ], [ 16, 23 ], [ 25, 46 ], [ 48, 48 ], [ 50, 51 ], [ 54, 69 ], [ 71, 71 ], [ 99, 103 ], [ 105, 106 ], [ 111, 112 ], [ 114, 121 ], [ 123, 124 ], [ 126, 126 ], [ 129, 129 ], [ 131, 132 ], [ 134, 134 ], [ 136, 137 ], [ 139, 139 ], [ 141, 144 ], [ 146, 147 ], [ 150, 152 ], [ 154, 154 ], [ 161, 172 ], [ 174, 174 ], [ 176, 189 ], [ 191, 197 ], [ 199, 201 ], [ 203, 229 ], [ 257, 264 ], [ 266, 266 ], [ 268, 275 ], [ 277, 283 ], [ 287, 290 ], [ 292, 293 ], [ 296, 331 ], [ 333, 392 ], [ 394, 402 ], [ 404, 413 ], [ 415, 431 ], [ 433, 436 ], [ 438, 441 ], [ 443, 535 ], [ 541, 560 ], [ 565, 565 ], [ 571, 571 ], [ 574, 574 ], [ 601, 601 ], [ 603, 603 ], [ 607, 607 ], [ 609, 609 ], [ 613, 613 ], [ 615, 621 ], [ 623, 624 ], [ 629, 638 ], [ 640, 661 ], [ 668, 668 ], [ 673, 673 ], [ 684, 685 ], [ 687, 691 ], [ 693, 693 ], [ 698, 722 ], [ 724, 726 ], [ 728, 734 ], [ 736, 736 ], [ 738, 738 ], [ 740, 759 ], [ 761, 771 ], [ 773, 782 ], [ 796, 815 ], [ 817, 822 ], [ 824, 830 ], [ 832, 849 ], [ 851, 870 ], [ 872, 883 ], [ 885, 934 ] ], [ [ 8, 9 ], [ 12, 15 ], [ 24, 24 ], [ 47, 47 ], [ 49, 49 ], [ 52, 53 ], [ 70, 70 ], [ 72, 98 ], [ 104, 104 ], [ 107, 110 ], [ 113, 113 ], [ 122, 122 ], [ 125, 125 ], [ 127, 128 ], [ 130, 130 ], [ 133, 133 ], [ 135, 135 ], [ 138, 138 ], [ 140, 140 ], [ 145, 145 ], [ 148, 149 ], [ 153, 153 ], [ 155, 160 ], [ 173, 173 ], [ 175, 175 ], [ 190, 190 ], [ 198, 198 ], [ 202, 202 ], [ 230, 256 ], [ 265, 265 ], [ 267, 267 ], [ 276, 276 ], [ 284, 286 ], [ 291, 291 ], [ 294, 295 ], [ 332, 332 ], [ 393, 393 ], [ 403, 403 ], [ 414, 414 ], [ 432, 432 ], [ 437, 437 ], [ 442, 442 ], [ 536, 540 ], [ 561, 564 ], [ 566, 570 ], [ 572, 573 ], [ 575, 600 ], [ 602, 602 ], [ 604, 606 ], [ 608, 608 ], [ 610, 612 ], [ 614, 614 ], [ 622, 622 ], [ 625, 628 ], [ 639, 639 ], [ 662, 667 ], [ 669, 672 ], [ 674, 683 ], [ 686, 686 ], [ 692, 692 ], [ 694, 697 ], [ 723, 723 ], [ 727, 727 ], [ 735, 735 ], [ 737, 737 ], [ 739, 739 ], [ 760, 760 ], [ 772, 772 ], [ 783, 795 ], [ 816, 816 ], [ 823, 823 ], [ 831, 831 ], [ 850, 850 ], [ 871, 871 ], [ 884, 884 ] ] ]
b7ba0644d1778167c308921c6b815c7362cabb16
eb59f8abb82f425dfc067c7bdfaaf914756c5384
/CategoryEditDialog.h
231f321e016d6c74f54a89a1fc23456a47e44ae2
[]
no_license
congchenutd/congchenmoney
321cfafb28a0ae9190c65baab9b2de49b88f409c
4d57d3a3111600f7cf763fd37cb84ef6c3253736
refs/heads/master
2021-01-22T02:08:34.493176
2011-04-03T04:53:42
2011-04-03T04:53:42
32,358,806
0
0
null
null
null
null
UTF-8
C++
false
false
751
h
#ifndef CATEGORYDIALOG_H #define CATEGORYDIALOG_H #include <vector> #include "ui_CategoryEditDialog.h" class CategoryEditDialog : public QDialog { Q_OBJECT public: CategoryEditDialog(const QString& table, QWidget *parent = 0); QString getName () const; QColor getColor () const; int getParent() const; QString getUser() const; void setName (const QString& name); void setColor (const QColor& color); void setParent(int parent); void setUser (const QString& user); public slots: void slotChooseParent(int index); private: void initColorComboBox(); void initColors(); private: Ui::CategoryEditDialogClass ui; QString categoryTableName; }; #endif // CATEGORYDIALOG_H
[ "congchenutd@0e65ccb0-1e74-186d-738f-84c7691c4446" ]
[ [ [ 1, 35 ] ] ]
0074420b31250c8d3d8a1447cfee38f2000b63a8
3187b0dd0d7a7b83b33c62357efa0092b3943110
/src/dlib/gui_widgets/base_widgets.h
6f0f5184842c43b91488ef1930a5de544a5759ad
[ "BSL-1.0" ]
permissive
exi/gravisim
8a4dad954f68960d42f1d7da14ff1ca7a20e92f2
361e70e40f58c9f5e2c2f574c9e7446751629807
refs/heads/master
2021-01-19T17:45:04.106839
2010-10-22T09:11:24
2010-10-22T09:11:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
90,504
h
// Copyright (C) 2005 Davis E. King ([email protected]) // License: Boost Software License See LICENSE.txt for the full license. #ifndef DLIB_BASE_WIDGETs_ #define DLIB_BASE_WIDGETs_ #include "base_widgets_abstract.h" #include "drawable.h" #include "../gui_core.h" #include "../algs.h" #include "../member_function_pointer.h" #include "../timer.h" #include "../map.h" #include "../array2d.h" #include "../pixel.h" #include "../image_transforms.h" #include "../array.h" #include "../smart_pointers.h" #include <cctype> namespace dlib { // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // class dragable // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- class dragable : public drawable { /*! INITIAL VALUE - drag == false CONVENTION - if (the user is holding the left button down over this object) then - drag == true - x == the x position of the mouse relative to the upper left corner of this object. - y == the y position of the mouse relative to the upper left corner of this object. - else - drag == false !*/ public: dragable( drawable_window& w, unsigned long events = 0 ) : drawable(w,events | MOUSE_MOVE | MOUSE_CLICK), drag(false) {} virtual ~dragable( ) = 0; rectangle dragable_area ( ) const { auto_mutex M(m); return area; } void set_dragable_area ( const rectangle& area_ ) { auto_mutex M(m); area = area_; } protected: virtual void on_drag ( ){} void on_mouse_move ( unsigned long state, long x, long y ); void on_mouse_down ( unsigned long btn, unsigned long , long x, long y, bool ); private: rectangle area; bool drag; long x, y; // restricted functions dragable(dragable&); // copy constructor dragable& operator=(dragable&); // assignment operator }; // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // class mouse_over_event // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- class mouse_over_event : public drawable { /*! INITIAL VALUE - is_mouse_over_ == false CONVENTION - is_mouse_over_ == is_mouse_over() !*/ public: mouse_over_event( drawable_window& w, unsigned long events = 0 ) : drawable(w,events | MOUSE_MOVE), is_mouse_over_(false) {} virtual ~mouse_over_event( ) = 0; int next_free_user_event_number() const { return drawable::next_free_user_event_number()+1; } protected: bool is_mouse_over ( ) const; virtual void on_mouse_over ( ){} virtual void on_mouse_not_over ( ){} void on_mouse_leave ( ); void on_mouse_move ( unsigned long state, long x, long y ); void on_user_event ( int num ); private: mutable bool is_mouse_over_; // restricted functions mouse_over_event(mouse_over_event&); // copy constructor mouse_over_event& operator=(mouse_over_event&); // assignment operator }; // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // class button_action // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- class button_action : public mouse_over_event { /*! INITIAL VALUE - is_depressed_ == false - seen_click == false CONVENTION - is_depressed_ == is_depressed() - if (the user has clicked the button but hasn't yet released the left mouse button) then - seen_click == true - else - seen_click == false !*/ public: button_action( drawable_window& w, unsigned long events = 0 ) : mouse_over_event(w,events | MOUSE_MOVE | MOUSE_CLICK), is_depressed_(false), seen_click(false) {} virtual ~button_action( ) = 0; int next_free_user_event_number() const { return mouse_over_event::next_free_user_event_number()+1; } protected: bool is_depressed ( ) const; virtual void on_button_down ( ){} virtual void on_button_up ( bool mouse_over ){} void on_mouse_not_over ( ); void on_mouse_down ( unsigned long btn, unsigned long , long x, long y, bool ); void on_mouse_move ( unsigned long state, long x, long y ); void on_mouse_up ( unsigned long btn, unsigned long, long x, long y ); private: mutable bool is_depressed_; bool seen_click; void on_user_event ( int num ); // restricted functions button_action(button_action&); // copy constructor button_action& operator=(button_action&); // assignment operator }; // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // class arrow_button // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- class arrow_button : public button_action { /*! INITIAL VALUE dir == whatever is given to the constructor CONVENTION - dir == direction() !*/ public: enum arrow_direction { UP, DOWN, LEFT, RIGHT }; arrow_button( drawable_window& w, arrow_direction dir_ ) : button_action(w), dir(dir_) { enable_events(); } virtual ~arrow_button( ){ disable_events(); parent.invalidate_rectangle(rect); } arrow_direction direction ( ) const { auto_mutex M(m); return dir; } void set_direction ( arrow_direction new_direction ) { auto_mutex M(m); dir = new_direction; parent.invalidate_rectangle(rect); } void set_size ( unsigned long width, unsigned long height ); bool is_depressed ( ) const { auto_mutex M(m); return button_action::is_depressed(); } template < typename T > void set_button_down_handler ( T& object, void (T::*event_handler)() ) { auto_mutex M(m); button_down_handler.set(object,event_handler); } template < typename T > void set_button_up_handler ( T& object, void (T::*event_handler)(bool mouse_over) ) { auto_mutex M(m); button_up_handler.set(object,event_handler); } protected: void draw ( const canvas& c ) const; void on_button_down ( ) { if (button_down_handler.is_set()) button_down_handler(); } void on_button_up ( bool mouse_over ) { if (button_up_handler.is_set()) button_up_handler(mouse_over); } private: arrow_direction dir; member_function_pointer<>::kernel_1a button_down_handler; member_function_pointer<bool>::kernel_1a button_up_handler; // restricted functions arrow_button(arrow_button&); // copy constructor arrow_button& operator=(arrow_button&); // assignment operator }; // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // class scroll_bar // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- class scroll_bar : public drawable { /*! INITIAL VALUE - ori == a value given by the constructor - width_ == 16 - pos == 0 - max_pos == 0 - js == 10 CONVENTION - ori == orientation() - b1 == the button that is near the 0 end of the scroll bar - b2 == the button that is near the max_pos() end of the scroll bar - max_pos == max_slider_pos() - pos == slider_pos() - js == jump_size() !*/ public: enum bar_orientation { HORIZONTAL, VERTICAL }; scroll_bar( drawable_window& w, bar_orientation orientation_ ); virtual ~scroll_bar( ); bar_orientation orientation ( ) const; void set_orientation ( bar_orientation new_orientation ); void set_length ( unsigned long length ); long max_slider_pos ( ) const; void set_max_slider_pos ( long mpos ); void set_slider_pos ( long pos ); long slider_pos ( ) const; template < typename T > void set_scroll_handler ( T& object, void (T::*eh)() ) { scroll_handler.set(object,eh); } void set_pos ( long x, long y ); void enable ( ) { if (!hidden) show_slider(); if (max_pos != 0) { b1.enable(); b2.enable(); } drawable::enable(); } void disable ( ) { hide_slider(); b1.disable(); b2.disable(); drawable::disable(); } void hide ( ) { hide_slider(); top_filler.hide(); bottom_filler.hide(); b1.hide(); b2.hide(); drawable::hide(); } void show ( ) { b1.show(); b2.show(); drawable::show(); top_filler.show(); if (enabled) show_slider(); } void set_z_order ( long order ) { slider.set_z_order(order); top_filler.set_z_order(order); bottom_filler.set_z_order(order); b1.set_z_order(order); b2.set_z_order(order); drawable::set_z_order(order); } void set_jump_size ( long js ); long jump_size ( ) const; private: void hide_slider ( ); /*! ensures - hides the slider and makes any other changes needed so that the scroll_bar still looks right. !*/ void show_slider ( ); /*! ensures - shows the slider and makes any other changes needed so that the scroll_bar still looks right. !*/ void on_slider_drag ( ); /*! requires - is called whenever the user drags the slider !*/ void draw ( const canvas& c ) const; void b1_down ( ); void b1_up ( bool mouse_over ); void b2_down ( ); void b2_up ( bool mouse_over ); void top_filler_down ( ); void top_filler_up ( bool mouse_over ); void bottom_filler_down ( ); void bottom_filler_up ( bool mouse_over ); void on_user_event ( int i ) { switch (i) { case 0: b1_down(); break; case 1: b2_down(); break; case 2: top_filler_down(); break; case 3: bottom_filler_down(); break; case 4: // if the position we are supposed to switch the slider too isn't // already set if (delayed_pos != pos) { set_slider_pos(delayed_pos); if (scroll_handler.is_set()) scroll_handler(); } break; default: break; } } void delayed_set_slider_pos ( unsigned long dpos ) { delayed_pos = dpos; parent.trigger_user_event(this,4); } void b1_down_t ( ) { parent.trigger_user_event(this,0); } void b2_down_t ( ) { parent.trigger_user_event(this,1); } void top_filler_down_t ( ) { parent.trigger_user_event(this,2); } void bottom_filler_down_t ( ) { parent.trigger_user_event(this,3); } class filler : public button_action { friend class scroll_bar; public: filler ( drawable_window& w, scroll_bar& object, void (scroll_bar::*down)(), void (scroll_bar::*up)(bool) ): button_action(w) { bup.set(object,up); bdown.set(object,down); enable_events(); } ~filler ( ) { disable_events(); } void set_size ( unsigned long width, unsigned long height ) { rectangle old(rect); const unsigned long x = rect.left(); const unsigned long y = rect.top(); rect.set_right(x+width-1); rect.set_bottom(y+height-1); parent.invalidate_rectangle(rect+old); } private: void draw ( const canvas& c ) const { if (is_depressed()) draw_checkered(c, rect,rgb_pixel(0,0,0),rgb_pixel(43,47,55)); else draw_checkered(c, rect,rgb_pixel(255,255,255),rgb_pixel(212,208,200)); } void on_button_down ( ) { bdown(); } void on_button_up ( bool mouse_over ) { bup(mouse_over); } member_function_pointer<>::kernel_1a bdown; member_function_pointer<bool>::kernel_1a bup; }; class slider_class : public dragable { friend class scroll_bar; public: slider_class ( drawable_window& w, scroll_bar& object, void (scroll_bar::*handler)() ) : dragable(w) { mfp.set(object,handler); enable_events(); } ~slider_class ( ) { disable_events(); } void set_size ( unsigned long width, unsigned long height ) { rectangle old(rect); const unsigned long x = rect.left(); const unsigned long y = rect.top(); rect.set_right(x+width-1); rect.set_bottom(y+height-1); parent.invalidate_rectangle(rect+old); } private: void on_drag ( ) { mfp(); } void draw ( const canvas& c ) const { fill_rect(c, rect, rgb_pixel(212,208,200)); draw_button_up(c, rect); } member_function_pointer<>::kernel_1a mfp; }; void adjust_fillers ( ); /*! ensures - top_filler and bottom_filler appear in their correct positions relative to the current positions of the slider and the b1 and b2 buttons !*/ unsigned long get_slider_size ( ) const; /*! ensures - returns the length in pixels the slider should have based on the current state of this scroll bar !*/ const unsigned long width_; arrow_button b1, b2; slider_class slider; bar_orientation ori; filler top_filler, bottom_filler; member_function_pointer<>::kernel_1a scroll_handler; long pos; long max_pos; long js; timer<scroll_bar>::kernel_2a b1_timer; timer<scroll_bar>::kernel_2a b2_timer; timer<scroll_bar>::kernel_2a top_filler_timer; timer<scroll_bar>::kernel_2a bottom_filler_timer; long delayed_pos; // restricted functions scroll_bar(scroll_bar&); // copy constructor scroll_bar& operator=(scroll_bar&); // assignment operator }; // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // class widget_group // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- class widget_group : public drawable { /*! INITIAL VALUE widgets.size() == 0 CONVENTION Widgets contains all the drawable objects and their relative positions that are in *this. !*/ struct relpos { unsigned long x; unsigned long y; }; public: widget_group( drawable_window& w ) : drawable(w) { rect = rectangle(0,0,-1,-1); enable_events();} virtual ~widget_group( ){ disable_events(); } void empty ( ); void add ( drawable& widget, unsigned long x, unsigned long y ); bool is_member ( const drawable& widget ) const; void remove ( const drawable& widget ); unsigned long size ( ) const; void set_pos ( long x, long y ); void set_z_order ( long order ); void show ( ); void hide ( ); void enable ( ); void disable ( ); void fit_to_contents ( ); protected: // this object doesn't draw anything but also isn't abstract void draw ( const canvas& c ) const {} private: map<drawable*,relpos>::kernel_1a_c widgets; // restricted functions widget_group(widget_group&); // copy constructor widget_group& operator=(widget_group&); // assignment operator }; // ---------------------------------------------------------------------------------------- class image_widget : public dragable { /*! INITIAL VALUE - img.size() == 0 CONVENTION - img == the image this object displays !*/ public: image_widget( drawable_window& w ): dragable(w) { enable_events(); } ~image_widget( ) { disable_events(); parent.invalidate_rectangle(rect); } template < typename image_type > void set_image ( const image_type& new_img ) { auto_mutex M(m); assign_image(img,new_img); rectangle old(rect); rect.set_right(rect.left()+img.nc()-1); rect.set_bottom(rect.top()+img.nr()-1); parent.invalidate_rectangle(rect+old); } private: void draw ( const canvas& c ) const { rectangle area = rect.intersect(c); if (area.is_empty()) return; draw_image(c, point(rect.left(),rect.top()), img); } array2d<rgb_alpha_pixel>::kernel_1a img; // restricted functions image_widget(image_widget&); // copy constructor image_widget& operator=(image_widget&); // assignment operator }; // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // class tooltip // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- class tooltip : public mouse_over_event { /*! INITIAL VALUE - stuff.get() == 0 - events_are_enabled() == false CONVENTION - if (events_are_enabled() == true) then - stuff.get() != 0 !*/ public: tooltip( drawable_window& w ) : mouse_over_event(w,MOUSE_CLICK) {} ~tooltip( ){ disable_events();} void set_size ( long width, long height ) { auto_mutex M(m); rect = resize_rect(rect,width,height); } void set_text ( const std::string& str ) { auto_mutex M(m); if (!stuff) { stuff.reset(new data(*this)); enable_events(); } stuff->win.set_text(str); } const std::string text ( ) const { auto_mutex M(m); std::string temp; if (stuff) { temp = stuff->win.text; } return temp.c_str(); } void hide ( ) { mouse_over_event::hide(); if (stuff) { stuff->tt_timer.stop(); stuff->win.hide(); } } void disable ( ) { mouse_over_event::disable(); if (stuff) { stuff->tt_timer.stop(); stuff->win.hide(); } } protected: void on_mouse_over() { stuff->x = lastx; stuff->y = lasty; stuff->tt_timer.start(); } void on_mouse_not_over () { stuff->tt_timer.stop(); stuff->win.hide(); } void on_mouse_down ( unsigned long btn, unsigned long state, long x, long y, bool is_double_click ) { mouse_over_event::on_mouse_down(btn,state,x,y,is_double_click); stuff->tt_timer.stop(); stuff->win.hide(); } void draw ( const canvas& ) const{} private: class tooltip_window : public base_window { public: tooltip_window (const font* f) : base_window(false,true), pad(3), mfont(f) { } std::string text; rectangle rect_all; rectangle rect_text; const unsigned long pad; const font* mfont; void set_text ( const std::string& str ) { text = str.c_str(); unsigned long width, height; mfont->compute_size(text,width,height); set_size(width+pad*2, height+pad*2); rect_all.set_left(0); rect_all.set_top(0); rect_all.set_right(width+pad*2-1); rect_all.set_bottom(height+pad*2-1); rect_text = move_rect(rectangle(width,height),pad,pad); } void paint(const canvas& c) { c.fill(255,255,150); draw_rectangle(c, rect_all); mfont->draw_string(c,rect_text,text); } }; void show_tooltip ( ) { auto_mutex M(m); long x, y; // if the mouse has moved since we started the timer then // keep waiting until the user stops moving it if (lastx != stuff->x || lasty != stuff->y) { stuff->x = lastx; stuff->y = lasty; return; } unsigned long display_width, display_height; // stop the timer stuff->tt_timer.stop(); parent.get_pos(x,y); x += lastx+15; y += lasty+15; // make sure the tooltip isn't going to be off the screen parent.get_display_size(display_width, display_height); rectangle wrect(move_rect(stuff->win.rect_all,x,y)); rectangle srect(display_width, display_height); if (srect.contains(wrect) == false) { rectangle temp(srect.intersect(wrect)); x -= wrect.width()-temp.width(); y -= wrect.height()-temp.height(); } stuff->win.set_pos(x,y); stuff->win.show(); } // put all this stuff in data so we can arrange to only // construct it when someone is actually using the tooltip widget // rather than just instantiating it. struct data { data( tooltip& self ) : x(-1), y(-1), win(self.mfont), tt_timer(self,&tooltip::show_tooltip) { tt_timer.set_delay_time(400); } long x, y; tooltip_window win; timer<tooltip>::kernel_2a tt_timer; }; friend struct data; scoped_ptr<data> stuff; // restricted functions tooltip(tooltip&); // copy constructor tooltip& operator=(tooltip&); // assignment operator }; // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- // class popup_menu // ---------------------------------------------------------------------------------------- // ---------------------------------------------------------------------------------------- class menu_item { public: virtual ~menu_item() {} virtual rectangle get_left_size ( ) const { return rectangle(); } virtual rectangle get_middle_size ( ) const = 0; virtual rectangle get_right_size ( ) const { return rectangle(); } virtual unichar get_hot_key ( ) const { return 0; } virtual void draw_background ( const canvas& c, const rectangle& rect, const bool enabled, const bool is_selected ) const {} virtual void draw_left ( const canvas& c, const rectangle& rect, const bool enabled, const bool is_selected ) const {} virtual void draw_middle ( const canvas& c, const rectangle& rect, const bool enabled, const bool is_selected ) const = 0; virtual void draw_right ( const canvas& c, const rectangle& rect, const bool enabled, const bool is_selected ) const {} virtual void on_click ( ) const {} virtual bool has_click_event ( ) const { return false; } }; // ---------------------------------------------------------------------------------------- class menu_item_submenu : public menu_item { public: menu_item_submenu ( const std::string& str, unichar hk = 0 ) : text(str), f(default_font::get_font()), hotkey(hk) { if (hk != 0) { std::string::size_type pos = str.find_first_of(hk); if (pos != std::string::npos) { // now compute the location of the underline bar rectangle r1 = f->compute_cursor_rect( rectangle(100000,100000), str, pos); rectangle r2 = f->compute_cursor_rect( rectangle(100000,100000), str, pos+1); underline_p1.x() = r1.left()+1; underline_p2.x() = r2.left()-1; underline_p1.y() = r1.bottom()-f->height()+f->ascender()+2; underline_p2.y() = r2.bottom()-f->height()+f->ascender()+2; } } } virtual unichar get_hot_key ( ) const { return hotkey; } virtual rectangle get_middle_size ( ) const { unsigned long width, height; f->compute_size(text,width,height); return rectangle(width+30,height); } virtual rectangle get_right_size ( ) const { return rectangle(15, 5); } virtual void draw_background ( const canvas& c, const rectangle& rect, const bool enabled, const bool is_selected ) const { if (c.intersect(rect).is_empty()) return; if (enabled && is_selected) { fill_rect_with_vertical_gradient(c, rect,rgb_alpha_pixel(0,200,0,100), rgb_alpha_pixel(0,0,0,100)); draw_rectangle(c, rect,rgb_alpha_pixel(0,0,0,100)); } } virtual void draw_right ( const canvas& c, const rectangle& rect, const bool enabled, const bool is_selected ) const { if (c.intersect(rect).is_empty()) return; unsigned char color = 0; if (enabled == false) color = 128; long x, y; x = rect.right() - 7; y = rect.top() + rect.height()/2; for ( unsigned long i = 0; i < 5; ++i) draw_line (c, point(x - i, y + i), point(x - i, y - i), color); } virtual void draw_middle ( const canvas& c, const rectangle& rect, const bool enabled, const bool is_selected ) const { if (c.intersect(rect).is_empty()) return; if (enabled) { f->draw_string(c,rect,text); } else { f->draw_string(c,rect,text,128); } if (underline_p1 != underline_p2) { point base(rect.left(),rect.top()); draw_line(c, base+underline_p1, base+underline_p2); } } private: std::string text; const font* f; member_function_pointer<>::kernel_1a action; unichar hotkey; point underline_p1; point underline_p2; }; // ---------------------------------------------------------------------------------------- class menu_item_text : public menu_item { public: template <typename T> menu_item_text ( const std::string& str, T& object, void (T::*event_handler_)(), unichar hk = 0 ) : text(str), f(default_font::get_font()), hotkey(hk) { action.set(object,event_handler_); if (hk != 0) { std::string::size_type pos = str.find_first_of(hk); if (pos != std::string::npos) { // now compute the location of the underline bar rectangle r1 = f->compute_cursor_rect( rectangle(100000,100000), str, pos); rectangle r2 = f->compute_cursor_rect( rectangle(100000,100000), str, pos+1); underline_p1.x() = r1.left()+1; underline_p2.x() = r2.left()-1; underline_p1.y() = r1.bottom()-f->height()+f->ascender()+2; underline_p2.y() = r2.bottom()-f->height()+f->ascender()+2; } } } virtual unichar get_hot_key ( ) const { return hotkey; } virtual rectangle get_middle_size ( ) const { unsigned long width, height; f->compute_size(text,width,height); return rectangle(width,height); } virtual void draw_background ( const canvas& c, const rectangle& rect, const bool enabled, const bool is_selected ) const { if (c.intersect(rect).is_empty()) return; if (enabled && is_selected) { fill_rect_with_vertical_gradient(c, rect,rgb_alpha_pixel(0,200,0,100), rgb_alpha_pixel(0,0,0,100)); draw_rectangle(c, rect,rgb_alpha_pixel(0,0,0,100)); } } virtual void draw_middle ( const canvas& c, const rectangle& rect, const bool enabled, const bool is_selected ) const { if (c.intersect(rect).is_empty()) return; if (enabled) { f->draw_string(c,rect,text); } else { f->draw_string(c,rect,text,128); } if (underline_p1 != underline_p2) { point base(rect.left(),rect.top()); draw_line(c, base+underline_p1, base+underline_p2); } } virtual void on_click ( ) const { action(); } virtual bool has_click_event ( ) const { return true; } private: std::string text; const font* f; member_function_pointer<>::kernel_1a action; unichar hotkey; point underline_p1; point underline_p2; }; // ---------------------------------------------------------------------------------------- class menu_item_separator : public menu_item { public: virtual rectangle get_middle_size ( ) const { return rectangle(10,4); } virtual void draw_background ( const canvas& c, const rectangle& rect, const bool enabled, const bool is_selected ) const { if (c.intersect(rect).is_empty()) return; point p1(rect.left(),rect.top()+rect.height()/2-1); point p2(rect.right(),rect.top()+rect.height()/2-1); point p3(rect.left(),rect.top()+rect.height()/2); point p4(rect.right(),rect.top()+rect.height()/2); draw_line(c, p1,p2,128); draw_line(c, p3,p4,255); } virtual void draw_middle ( const canvas& c, const rectangle& rect, const bool enabled, const bool is_selected ) const { } }; // ---------------------------------------------------------------------------------------- class popup_menu : public base_window { /*! INITIAL VALUE - pad == 2 - item_pad == 3 - cur_rect == rectangle(pad,pad,pad-1,pad-1) - left_width == 0 - middle_width == 0 - selected_item == 0 - submenu_open == false - items.size() == 0 - item_enabled.size() == 0 - left_rects.size() == 0 - middle_rects.size() == 0 - right_rects.size() == 0 - line_rects.size() == 0 - submenus.size() == 0 - hide_handlers.size() == 0 CONVENTION - pad = 2 - item_pad = 3 - all of the following arrays have the same size: - items.size() - item_enabled.size() - left_rects.size() - middle_rects.size() - right_rects.size() - line_rects.size() - submenus.size() - win_rect == a rectangle that is the exact size of this window and with its upper left corner at (0,0) - cur_rect == the rect inside which all the menu items are drawn - if (a menu_item is supposed to be selected) then - selected_item == the index in menus of the menu_item - else - selected_item == submenus.size() - if (there is a selected submenu and it is currently open) then - submenu_open == true - else - submenu_open == false - for all valid i: - items[i] == a pointer to the ith menu_item - item_enabled[i] == true if the ith menu_item is enabled, false otherwise - left_rects[i] == the left rectangle for the ith menu item - middle_rects[i] == the middle rectangle for the ith menu item - right_rects[i] == the right rectangle for the ith menu item - line_rects[i] == the rectangle for the entire line on which the ith menu item appears. - if (submenus[i] != 0) then - the ith menu item has a submenu and it is pointed to by submenus[i] - hide_handlers == an array of all the on_hide events registered for this popup_menu !*/ public: popup_menu ( ) : base_window(false,true), pad(2), item_pad(3), cur_rect(pad,pad,pad-1,pad-1), left_width(0), middle_width(0), selected_item(0), submenu_open(false) { } template < typename menu_item_type > unsigned long add_menu_item ( const menu_item_type& new_item ) { auto_mutex M(wm); bool t = true; scoped_ptr<menu_item> item(new menu_item_type(new_item)); items.push_back(item); item_enabled.push_back(t); // figure out how big the window should be now and what not rectangle left = new_item.get_left_size(); rectangle middle = new_item.get_middle_size(); rectangle right = new_item.get_right_size(); bool recalc_rect_positions = false; const rectangle all = left+middle+right; // make sure left_width contains the max of all the left rectangles if (left.width() > left_width) { left_width = left.width(); recalc_rect_positions = true; } // make sure middle_width contains the max of all the middle rectangles if (middle.width() > middle_width) { middle_width = middle.width(); recalc_rect_positions = true; } // make the current rectangle wider if necessary if (cur_rect.width() < left_width + middle_width + right.width() + 2*item_pad) { cur_rect = resize_rect_width(cur_rect, left_width + middle_width + right.width() + 2*item_pad); recalc_rect_positions = true; } const long y = cur_rect.bottom()+1 + item_pad; const long x = cur_rect.left() + item_pad; // make the current rectangle taller to account for this new menu item cur_rect.set_bottom(cur_rect.bottom()+all.height() + 2*item_pad); // adjust all the saved rectangles since the width of the window changed // or left_width changed if (recalc_rect_positions) { long y = cur_rect.top() + item_pad; for (unsigned long i = 0; i < left_rects.size(); ++i) { middle_rects[i] = move_rect(middle_rects[i], x+left_width, y); right_rects[i] = move_rect(right_rects[i], x+cur_rect.width()-right_rects[i].width()-item_pad, y); line_rects[i] = resize_rect_width(line_rects[i], cur_rect.width()); y += line_rects[i].height(); } } // save the rectangles for later use. Also position them at the // right spots left = move_rect(left,x,y); middle = move_rect(middle,x+left_width,y); right = move_rect(right,x+cur_rect.width()-right.width()-item_pad,y); rectangle line(move_rect(rectangle(cur_rect.width(),all.height()+2*item_pad), x-item_pad, y-item_pad)); // make sure the left, middle, and right rectangles are centered in the // line. if (left.height() < all.height()) left = translate_rect(left,0, (all.height()-left.height())/2); if (middle.height() < all.height()) middle = translate_rect(middle,0, (all.height()-middle.height())/2); if (right.height() < all.height()) right = translate_rect(right,0, (all.height()-right.height())/2); left_rects.push_back(left); middle_rects.push_back(middle); right_rects.push_back(right); line_rects.push_back(line); popup_menu* junk = 0; submenus.push_back(junk); win_rect.set_right(cur_rect.right()+pad); win_rect.set_bottom(cur_rect.bottom()+pad); set_size(win_rect.width(),win_rect.height()); // make it so that nothing is selected selected_item = submenus.size(); return items.size()-1; } template < typename menu_item_type > unsigned long add_submenu ( const menu_item_type& new_item, popup_menu& submenu ) { auto_mutex M(wm); submenus[add_menu_item(new_item)] = &submenu; submenu.set_on_hide_handler(*this,&popup_menu::on_submenu_hide); return items.size()-1; } void enable_menu_item ( unsigned long idx ) { DLIB_ASSERT ( idx < size() , "\tvoid popup_menu::enable_menu_item()" << "\n\tidx: " << idx << "\n\tsize(): " << size() ); auto_mutex M(wm); item_enabled[idx] = true; invalidate_rectangle(cur_rect); } void disable_menu_item ( unsigned long idx ) { DLIB_ASSERT ( idx < size() , "\tvoid popup_menu::enable_menu_item()" << "\n\tidx: " << idx << "\n\tsize(): " << size() ); auto_mutex M(wm); item_enabled[idx] = false; invalidate_rectangle(cur_rect); } unsigned long size ( ) const { auto_mutex M(wm); return items.size(); } void clear ( ) { auto_mutex M(wm); hide(); cur_rect = rectangle(pad,pad,pad-1,pad-1); win_rect = rectangle(); left_width = 0; middle_width = 0; items.clear(); item_enabled.clear(); left_rects.clear(); middle_rects.clear(); right_rects.clear(); line_rects.clear(); submenus.clear(); selected_item = 0; submenu_open = false; } void show ( ) { auto_mutex M(wm); selected_item = submenus.size(); base_window::show(); } void hide ( ) { auto_mutex M(wm); // hide ourselves close_submenu(); selected_item = submenus.size(); base_window::hide(); } template <typename T> void set_on_hide_handler ( T& object, void (T::*event_handler)() ) { auto_mutex M(wm); member_function_pointer<>::kernel_1a temp; temp.set(object,event_handler); // if this handler isn't already registered then add it bool found_handler = false; for (unsigned long i = 0; i < hide_handlers.size(); ++i) { if (hide_handlers[i] == temp) { found_handler = true; break; } } if (found_handler == false) { hide_handlers.push_back(temp); } } void select_first_item ( ) { auto_mutex M(wm); close_submenu(); selected_item = items.size(); for (unsigned long i = 0; i < items.size(); ++i) { if ((items[i]->has_click_event() || submenus[i]) && item_enabled[i]) { selected_item = i; break; } } invalidate_rectangle(cur_rect); } bool forwarded_on_keydown ( unsigned long key, bool is_printable, unsigned long state ) { auto_mutex M(wm); // do nothing if this popup menu is empty if (items.size() == 0) return false; // check if the selected item is a submenu if (selected_item != submenus.size() && submenus[selected_item] != 0 && submenu_open) { // send the key to the submenu and return if that menu used the key if (submenus[selected_item]->forwarded_on_keydown(key,is_printable,state) == true) return true; } if (key == KEY_UP) { for (unsigned long i = 0; i < items.size(); ++i) { selected_item = (selected_item + items.size() - 1)%items.size(); // only stop looking if this one is enabled and has a click event or is a submenu if (item_enabled[selected_item] && (items[selected_item]->has_click_event() || submenus[selected_item]) ) break; } invalidate_rectangle(cur_rect); return true; } else if (key == KEY_DOWN) { for (unsigned long i = 0; i < items.size(); ++i) { selected_item = (selected_item + 1)%items.size(); // only stop looking if this one is enabled and has a click event or is a submenu if (item_enabled[selected_item] && (items[selected_item]->has_click_event() || submenus[selected_item])) break; } invalidate_rectangle(cur_rect); return true; } else if (key == KEY_RIGHT && submenu_open == false && display_selected_submenu()) { submenus[selected_item]->select_first_item(); return true; } else if (key == KEY_LEFT && selected_item != submenus.size() && submenus[selected_item] != 0 && submenu_open) { close_submenu(); return true; } else if (key == '\n') { if (selected_item != submenus.size() && (items[selected_item]->has_click_event() || submenus[selected_item])) { const long idx = selected_item; // only hide this popup window if this isn't a submenu if (submenus[idx] == 0) { hide(); hide_handlers.reset(); while (hide_handlers.move_next()) hide_handlers.element()(); } else { display_selected_submenu(); submenus[idx]->select_first_item(); } items[idx]->on_click(); return true; } } else if (is_printable) { // check if there is a hotkey for this key for (unsigned long i = 0; i < items.size(); ++i) { if (std::tolower(key) == std::tolower(items[i]->get_hot_key()) && (items[i]->has_click_event() || submenus[i]) ) { // only hide this popup window if this isn't a submenu if (submenus[i] == 0) { hide(); hide_handlers.reset(); while (hide_handlers.move_next()) hide_handlers.element()(); } else { if (selected_item != items.size()) invalidate_rectangle(line_rects[selected_item]); selected_item = i; display_selected_submenu(); invalidate_rectangle(line_rects[i]); submenus[i]->select_first_item(); } items[i]->on_click(); } } // always say we use a printable key for hotkeys return true; } return false; } private: void on_submenu_hide ( ) { hide(); hide_handlers.reset(); while (hide_handlers.move_next()) hide_handlers.element()(); } void on_window_resized( ) { invalidate_rectangle(win_rect); } void on_mouse_up ( unsigned long btn, unsigned long, long x, long y ) { if (cur_rect.contains(x,y) && btn == LEFT) { // figure out which item this was on for (unsigned long i = 0; i < items.size(); ++i) { if (line_rects[i].contains(x,y) && item_enabled[i] && items[i]->has_click_event()) { // only hide this popup window if this isn't a submenu if (submenus[i] == 0) { hide(); hide_handlers.reset(); while (hide_handlers.move_next()) hide_handlers.element()(); } items[i]->on_click(); break; } } } } void on_mouse_move ( unsigned long state, long x, long y ) { if (cur_rect.contains(x,y)) { // check if the mouse is still in the same rect it was in last time rectangle last_rect; if (selected_item != submenus.size()) { last_rect = line_rects[selected_item]; } // if the mouse isn't in the same rectangle any more if (last_rect.contains(x,y) == false) { if (selected_item != submenus.size()) { invalidate_rectangle(last_rect); close_submenu(); selected_item = submenus.size(); } // figure out if we should redraw any menu items for (unsigned long i = 0; i < items.size(); ++i) { if (items[i]->has_click_event() || submenus[i]) { if (line_rects[i].contains(x,y)) { selected_item = i; break; } } } // if we found a rectangle that contains the mouse then // tell it to redraw itself if (selected_item != submenus.size()) { display_selected_submenu(); invalidate_rectangle(line_rects[selected_item]); } } } } void close_submenu ( ) { if (selected_item != submenus.size() && submenus[selected_item] && submenu_open) { submenus[selected_item]->hide(); submenu_open = false; } } bool display_selected_submenu ( ) /*! ensures - if (submenus[selected_item] isn't null) then - displays the selected submenu - returns true - else - returns false !*/ { // show the submenu if one exists if (selected_item != submenus.size() && submenus[selected_item]) { long wx, wy; get_pos(wx,wy); wx += line_rects[selected_item].right(); wy += line_rects[selected_item].top(); submenus[selected_item]->set_pos(wx+1,wy-2); submenus[selected_item]->show(); submenu_open = true; return true; } return false; } void on_mouse_leave ( ) { if (selected_item != submenus.size()) { // only unhighlight a menu item if it isn't a submenu item if (submenus[selected_item] == 0) { invalidate_rectangle(line_rects[selected_item]); selected_item = submenus.size(); } } } void paint ( const canvas& c ) { c.fill(200,200,200); draw_rectangle(c, win_rect); for (unsigned long i = 0; i < items.size(); ++i) { bool is_selected = false; if (selected_item != submenus.size() && i == selected_item && item_enabled[i]) is_selected = true; items[i]->draw_background(c,line_rects[i], item_enabled[i], is_selected); items[i]->draw_left(c,left_rects[i], item_enabled[i], is_selected); items[i]->draw_middle(c,middle_rects[i], item_enabled[i], is_selected); items[i]->draw_right(c,right_rects[i], item_enabled[i], is_selected); } } const long pad; const long item_pad; rectangle cur_rect; rectangle win_rect; unsigned long left_width; unsigned long middle_width; array<scoped_ptr<menu_item> >::expand_1d_c items; array<bool>::expand_1d_c item_enabled; array<rectangle>::expand_1d_c left_rects; array<rectangle>::expand_1d_c middle_rects; array<rectangle>::expand_1d_c right_rects; array<rectangle>::expand_1d_c line_rects; array<popup_menu*>::expand_1d_c submenus; unsigned long selected_item; bool submenu_open; array<member_function_pointer<>::kernel_1a>::expand_1d_c hide_handlers; // restricted functions popup_menu(popup_menu&); // copy constructor popup_menu& operator=(popup_menu&); // assignment operator }; // ---------------------------------------------------------------------------------------- class zoomable_region : public drawable { /*! INITIAL VALUE - min_scale == 0.15 - max_scale == 1.0 - zoom_increment_ == 0.02 - scale == 1.0 - mouse_drag_screen == false CONVENTION - zoom_increment() == zoom_increment_ - min_zoom_scale() == min_scale - max_zoom_scale() == max_scale - zoom_scale() == scale - if (the user is currently dragging the graph around via the mouse) then - mouse_drag_screen == true - else - mouse_drag_screen == false - max_graph_point() == lr_point - display_rect() == display_rect_ - gui_to_graph_space(point(display_rect.left(),display_rect.top())) == gr_orig !*/ public: zoomable_region ( drawable_window& w, unsigned long events = 0 ) : drawable(w,MOUSE_CLICK | MOUSE_WHEEL | MOUSE_MOVE | events), min_scale(0.15), max_scale(1.0), zoom_increment_(0.02), vsb(w, scroll_bar::VERTICAL), hsb(w, scroll_bar::HORIZONTAL) { scale = 1; mouse_drag_screen = false; hsb.set_scroll_handler(*this,&zoomable_region::on_h_scroll); vsb.set_scroll_handler(*this,&zoomable_region::on_v_scroll); } inline ~zoomable_region ( )= 0; void set_pos ( long x, long y ) { auto_mutex M(m); drawable::set_pos(x,y); vsb.set_pos(rect.right()-2-vsb.width(),rect.top()+2); hsb.set_pos(rect.left()+2,rect.bottom()-2-hsb.height()); display_rect_ = rectangle(rect.left()+2,rect.top()+2,rect.right()-2-vsb.width(),rect.bottom()-2-hsb.height()); } void set_zoom_increment ( double zi ) { auto_mutex M(m); zoom_increment_ = zi; } double zoom_increment ( ) const { auto_mutex M(m); return zoom_increment_; } void set_max_zoom_scale ( double ms ) { auto_mutex M(m); max_scale = ms; if (scale > ms) { scale = max_scale; lr_point = gui_to_graph_space(point(display_rect_.right(),display_rect_.bottom())); redraw_graph(); } } void set_min_zoom_scale ( double ms ) { auto_mutex M(m); min_scale = ms; if (scale < ms) { scale = min_scale; lr_point = gui_to_graph_space(point(display_rect_.right(),display_rect_.bottom())); redraw_graph(); } } double min_zoom_scale ( ) const { auto_mutex M(m); return min_scale; } double max_zoom_scale ( ) const { auto_mutex M(m); return max_scale; } void set_size ( long width, long height ) { auto_mutex M(m); rectangle old(rect); rect = resize_rect(rect,width,height); vsb.set_pos(rect.right()-1-vsb.width(), rect.top()+2); hsb.set_pos(rect.left()+2, rect.bottom()-1-hsb.height()); display_rect_ = rectangle(rect.left()+2,rect.top()+2,rect.right()-2-vsb.width(),rect.bottom()-2-hsb.height()); vsb.set_length(display_rect_.height()); hsb.set_length(display_rect_.width()); parent.invalidate_rectangle(rect+old); const double old_scale = scale; scale = min_scale; lr_point = gui_to_graph_space(point(display_rect_.right(),display_rect_.bottom())); scale = old_scale; // call adjust_origin() so that the scroll bars get their max slider positions // setup right const point rect_corner(display_rect_.left(), display_rect_.top()); const vector<double> rect_corner_graph(gui_to_graph_space(rect_corner)); adjust_origin(rect_corner, rect_corner_graph); } void show ( ) { auto_mutex M(m); drawable::show(); hsb.show(); vsb.show(); } void hide ( ) { auto_mutex M(m); drawable::hide(); hsb.hide(); vsb.hide(); } void enable ( ) { auto_mutex M(m); drawable::enable(); hsb.enable(); vsb.enable(); } void disable ( ) { auto_mutex M(m); drawable::disable(); hsb.disable(); vsb.disable(); } void set_z_order ( long order ) { auto_mutex M(m); drawable::set_z_order(order); hsb.set_z_order(order); vsb.set_z_order(order); } protected: point graph_to_gui_space ( const vector<double>& p ) const { const point rect_corner(display_rect_.left(), display_rect_.top()); const dlib::vector<double> v(p); return (v - gr_orig)*scale + rect_corner; } vector<double> gui_to_graph_space ( const point& p ) const { const point rect_corner(display_rect_.left(), display_rect_.top()); const dlib::vector<double> v(p - rect_corner); return v/scale + gr_orig; } point max_graph_point ( ) const { return lr_point; } rectangle display_rect ( ) const { return display_rect_; } double zoom_scale ( ) const { return scale; } void set_zoom_scale ( double new_scale ) { if (min_scale <= new_scale && new_scale <= max_scale) { // find the point in the center of the graph area point center((display_rect_.left()+display_rect_.right())/2, (display_rect_.top()+display_rect_.bottom())/2); point graph_p(gui_to_graph_space(center)); scale = new_scale; adjust_origin(center, graph_p); redraw_graph(); } } void center_display_at_graph_point ( const vector<double>& p ) { // find the point in the center of the graph area point center((display_rect_.left()+display_rect_.right())/2, (display_rect_.top()+display_rect_.bottom())/2); adjust_origin(center, p); redraw_graph(); } // ----------- event handlers --------------- void on_wheel_down ( ) { // zoom out if (enabled && !hidden && scale > min_scale && display_rect_.contains(lastx,lasty)) { point gui_p(lastx,lasty); point graph_p(gui_to_graph_space(gui_p)); scale -= zoom_increment_; if (scale < min_scale) scale = min_scale; redraw_graph(); adjust_origin(gui_p, graph_p); } } void on_wheel_up ( ) { // zoom in if (enabled && !hidden && scale < max_scale && display_rect_.contains(lastx,lasty)) { point gui_p(lastx,lasty); point graph_p(gui_to_graph_space(gui_p)); scale += zoom_increment_; if (scale > max_scale) scale = max_scale; redraw_graph(); adjust_origin(gui_p, graph_p); } } void on_mouse_move ( unsigned long state, long x, long y ) { if (enabled && !hidden && mouse_drag_screen) { adjust_origin(point(x,y), drag_screen_point); redraw_graph(); } // check if the mouse isn't being dragged anymore if ((state & base_window::LEFT) == 0) { mouse_drag_screen = false; } } void on_mouse_up ( unsigned long btn, unsigned long state, long x, long y ) { mouse_drag_screen = false; } void on_mouse_down ( unsigned long btn, unsigned long state, long x, long y, bool is_double_click ) { if (enabled && !hidden && display_rect_.contains(x,y) && btn == base_window::LEFT) { mouse_drag_screen = true; drag_screen_point = gui_to_graph_space(point(x,y)); } } void draw ( const canvas& c ) const { draw_sunken_rectangle(c,rect); } private: void on_h_scroll ( ) { gr_orig.x() = hsb.slider_pos(); redraw_graph(); } void on_v_scroll ( ) { gr_orig.y() = vsb.slider_pos(); redraw_graph(); } void redraw_graph ( ) { parent.invalidate_rectangle(display_rect_); } void adjust_origin ( const point& gui_p, const vector<double>& graph_p ) /*! ensures - adjusts gr_orig so that we are as close to the following as possible: - graph_to_gui_space(graph_p) == gui_p - gui_to_graph_space(gui_p) == graph_p !*/ { const point rect_corner(display_rect_.left(), display_rect_.top()); const dlib::vector<double> v(gui_p - rect_corner); gr_orig = graph_p - v/scale; // make sure the origin isn't outside the point (0,0) if (gr_orig.x() < 0) gr_orig.x() = 0; if (gr_orig.y() < 0) gr_orig.y() = 0; // make sure the lower right corner of the display_rect_ doesn't map to a point beyond lr_point point lr_rect_corner(display_rect_.right(), display_rect_.bottom()); point p = graph_to_gui_space(lr_point); vector<double> lr_rect_corner_graph_space(gui_to_graph_space(lr_rect_corner)); vector<double> delta(lr_point - lr_rect_corner_graph_space); if (lr_rect_corner.x() > p.x()) { gr_orig.x() += delta.x(); } if (lr_rect_corner.y() > p.y()) { gr_orig.y() += delta.y(); } const vector<double> ul_rect_corner_graph_space(gui_to_graph_space(rect_corner)); lr_rect_corner_graph_space = gui_to_graph_space(lr_rect_corner); // now adjust the scroll bars hsb.set_max_slider_pos((unsigned long)std::max(lr_point.x()-(lr_rect_corner_graph_space.x()-ul_rect_corner_graph_space.x()),0.0)); vsb.set_max_slider_pos((unsigned long)std::max(lr_point.y()-(lr_rect_corner_graph_space.y()-ul_rect_corner_graph_space.y()),0.0)); // adjust slider position now. hsb.set_slider_pos(static_cast<long>(ul_rect_corner_graph_space.x())); vsb.set_slider_pos(static_cast<long>(ul_rect_corner_graph_space.y())); } vector<double> gr_orig; // point in graph space such that it's gui space point is the upper left of display_rect_ vector<double> lr_point; // point in graph space such that it is at the lower right corner of the screen at max zoom mutable std::ostringstream sout; double scale; // 0 < scale <= 1 double min_scale; double max_scale; double zoom_increment_; rectangle display_rect_; bool mouse_drag_screen; // true if the user is dragging the white background area point drag_screen_point; // the starting point the mouse was at in graph space for the background area drag scroll_bar vsb; scroll_bar hsb; // restricted functions zoomable_region(zoomable_region&); // copy constructor zoomable_region& operator=(zoomable_region&); // assignment operator }; zoomable_region::~zoomable_region() {} // ---------------------------------------------------------------------------------------- class scrollable_region : public drawable { /*! INITIAL VALUE - border_size == 2 - hscroll_bar_inc == 1 - vscroll_bar_inc == 1 CONVENTION - border_size == 2 - horizontal_scroll_increment() == hscroll_bar_inc - vertical_scroll_increment() == vscroll_bar_inc - vertical_scroll_pos() == vsb.slider_pos() - horizontal_scroll_pos() == hsb.slider_pos() - total_rect() == total_rect_ - display_rect() == display_rect_ !*/ public: scrollable_region ( drawable_window& w, unsigned long events = 0 ) : drawable(w, MOUSE_WHEEL|events), hsb(w,scroll_bar::HORIZONTAL), vsb(w,scroll_bar::VERTICAL), border_size(2), hscroll_bar_inc(1), vscroll_bar_inc(1) { hsb.set_scroll_handler(*this,&scrollable_region::on_h_scroll); vsb.set_scroll_handler(*this,&scrollable_region::on_v_scroll); } virtual inline ~scrollable_region ( ) = 0; void show ( ) { auto_mutex M(m); drawable::show(); if (need_h_scroll()) hsb.show(); if (need_v_scroll()) vsb.show(); } void hide ( ) { auto_mutex M(m); drawable::hide(); hsb.hide(); vsb.hide(); } void enable ( ) { auto_mutex M(m); drawable::enable(); hsb.enable(); vsb.enable(); } void disable ( ) { auto_mutex M(m); drawable::disable(); hsb.disable(); vsb.disable(); } void set_z_order ( long order ) { auto_mutex M(m); drawable::set_z_order(order); hsb.set_z_order(order); vsb.set_z_order(order); } void set_size ( unsigned long width, unsigned long height ) { auto_mutex M(m); rectangle old(rect); rect = resize_rect(rect,width,height); vsb.set_pos(rect.right()-border_size-vsb.width()+1, rect.top()+border_size); hsb.set_pos(rect.left()+border_size, rect.bottom()-border_size-hsb.height()+1); // adjust the display_rect_ if (need_h_scroll() && need_v_scroll()) { // both scroll bars aren't hidden if (!hidden) { vsb.show(); hsb.show(); } display_rect_ = rectangle( rect.left()+border_size, rect.top()+border_size, rect.right()-border_size-vsb.width(), rect.bottom()-border_size-hsb.height()); // figure out how many scroll bar positions there should be unsigned long hdelta = total_rect_.width()-display_rect_.width(); unsigned long vdelta = total_rect_.height()-display_rect_.height(); hdelta = (hdelta+hscroll_bar_inc-1)/hscroll_bar_inc; vdelta = (vdelta+vscroll_bar_inc-1)/vscroll_bar_inc; hsb.set_max_slider_pos(hdelta); vsb.set_max_slider_pos(vdelta); vsb.set_jump_size((display_rect_.height()+vscroll_bar_inc-1)/vscroll_bar_inc/2+1); hsb.set_jump_size((display_rect_.width()+hscroll_bar_inc-1)/hscroll_bar_inc/2+1); } else if (need_h_scroll()) { // only hsb is hidden if (!hidden) { hsb.show(); vsb.hide(); } display_rect_ = rectangle( rect.left()+border_size, rect.top()+border_size, rect.right()-border_size, rect.bottom()-border_size-hsb.height()); // figure out how many scroll bar positions there should be unsigned long hdelta = total_rect_.width()-display_rect_.width(); hdelta = (hdelta+hscroll_bar_inc-1)/hscroll_bar_inc; hsb.set_max_slider_pos(hdelta); vsb.set_max_slider_pos(0); hsb.set_jump_size((display_rect_.width()+hscroll_bar_inc-1)/hscroll_bar_inc/2+1); } else if (need_v_scroll()) { // only vsb is hidden if (!hidden) { hsb.hide(); vsb.show(); } display_rect_ = rectangle( rect.left()+border_size, rect.top()+border_size, rect.right()-border_size-vsb.width(), rect.bottom()-border_size); unsigned long vdelta = total_rect_.height()-display_rect_.height(); vdelta = (vdelta+vscroll_bar_inc-1)/vscroll_bar_inc; hsb.set_max_slider_pos(0); vsb.set_max_slider_pos(vdelta); vsb.set_jump_size((display_rect_.height()+vscroll_bar_inc-1)/vscroll_bar_inc/2+1); } else { // both are hidden if (!hidden) { hsb.hide(); vsb.hide(); } display_rect_ = rectangle( rect.left()+border_size, rect.top()+border_size, rect.right()-border_size, rect.bottom()-border_size); hsb.set_max_slider_pos(0); vsb.set_max_slider_pos(0); } vsb.set_length(display_rect_.height()); hsb.set_length(display_rect_.width()); // adjust the total_rect_ position by trigging the scroll events on_h_scroll(); on_v_scroll(); parent.invalidate_rectangle(rect+old); } unsigned long horizontal_scroll_increment ( ) const { auto_mutex M(m); return hscroll_bar_inc; } unsigned long vertical_scroll_increment ( ) const { auto_mutex M(m); return vscroll_bar_inc; } void set_horizontal_scroll_increment ( unsigned long inc ) { auto_mutex M(m); hscroll_bar_inc = inc; // call set_size to reset the scroll bars set_size(rect.width(),rect.height()); } void set_vertical_scroll_increment ( unsigned long inc ) { auto_mutex M(m); vscroll_bar_inc = inc; // call set_size to reset the scroll bars set_size(rect.width(),rect.height()); } long horizontal_scroll_pos ( ) const { auto_mutex M(m); return hsb.slider_pos(); } long vertical_scroll_pos ( ) const { auto_mutex M(m); return vsb.slider_pos(); } void set_horizontal_scroll_pos ( long pos ) { auto_mutex M(m); hsb.set_slider_pos(pos); on_h_scroll(); } void set_vertical_scroll_pos ( long pos ) { auto_mutex M(m); vsb.set_slider_pos(pos); on_v_scroll(); } void set_pos ( long x, long y ) { auto_mutex M(m); drawable::set_pos(x,y); vsb.set_pos(rect.right()-border_size-vsb.width()+1, rect.top()+border_size); hsb.set_pos(rect.left()+border_size, rect.bottom()-border_size-hsb.height()+1); const long delta_x = total_rect_.left() - display_rect_.left(); const long delta_y = total_rect_.top() - display_rect_.top(); display_rect_ = move_rect(display_rect_, rect.left()+border_size, rect.top()+border_size); total_rect_ = move_rect(total_rect_, display_rect_.left()+delta_x, display_rect_.top()+delta_y); } protected: const rectangle& display_rect ( ) const { return display_rect_; } void set_total_rect_size ( unsigned long width, unsigned long height ) { total_rect_ = move_rect(rectangle(width,height), display_rect_.left()-static_cast<long>(hsb.slider_pos()), display_rect_.top()-static_cast<long>(vsb.slider_pos())); // call this just to reconfigure the scroll bars set_size(rect.width(),rect.height()); } const rectangle& total_rect ( ) const { return total_rect_; } void scroll_to_rect ( const rectangle& r ) { const rectangle old(total_rect_); // adjust the horizontal scroll bar so that r fits as best as possible if (r.left() < display_rect_.left()) { long distance = (r.left()-total_rect_.left())/hscroll_bar_inc; hsb.set_slider_pos(distance); } else if (r.right() > display_rect_.right()) { long distance = (r.right()-total_rect_.left()-display_rect_.width()+hscroll_bar_inc)/hscroll_bar_inc; hsb.set_slider_pos(distance); } // adjust the vertical scroll bar so that r fits as best as possible if (r.top() < display_rect_.top()) { long distance = (r.top()-total_rect_.top())/hscroll_bar_inc; vsb.set_slider_pos(distance); } else if (r.bottom() > display_rect_.bottom()) { long distance = (r.bottom()-total_rect_.top()-display_rect_.height()+hscroll_bar_inc)/hscroll_bar_inc; vsb.set_slider_pos(distance); } // adjust total_rect_ so that it matches where the scroll bars are now total_rect_ = move_rect(total_rect_, display_rect_.left()-hscroll_bar_inc*hsb.slider_pos(), display_rect_.top()-vscroll_bar_inc*vsb.slider_pos()); // only redraw if we actually changed something if (total_rect_ != old) { parent.invalidate_rectangle(display_rect_); } } void on_wheel_down ( ) { if (rect.contains(lastx,lasty) && enabled && !hidden) { if (need_v_scroll()) { unsigned long pos = vsb.slider_pos(); vsb.set_slider_pos(pos+1); on_v_scroll(); } else if (need_h_scroll()) { unsigned long pos = hsb.slider_pos(); hsb.set_slider_pos(pos+1); on_h_scroll(); } } } void on_wheel_up ( ) { if (rect.contains(lastx,lasty) && enabled && !hidden) { if (need_v_scroll()) { unsigned long pos = vsb.slider_pos(); vsb.set_slider_pos(pos-1); on_v_scroll(); } else if (need_h_scroll()) { unsigned long pos = hsb.slider_pos(); hsb.set_slider_pos(pos-1); on_h_scroll(); } } } void draw ( const canvas& c ) const { rectangle area = c.intersect(rect); if (area.is_empty() == true) return; draw_sunken_rectangle(c,rect); } private: bool need_h_scroll ( ) const { if (total_rect_.width() > rect.width()-border_size*2) { return true; } else { // check if we would need a vertical scroll bar and if adding one would make us need // a horizontal one if (total_rect_.height() > rect.height()-border_size*2 && total_rect_.width() > rect.width()-border_size*2-vsb.width()) return true; else return false; } } bool need_v_scroll ( ) const { if (total_rect_.height() > rect.height()-border_size*2) { return true; } else { // check if we would need a horizontal scroll bar and if adding one would make us need // a vertical_scroll_pos one if (total_rect_.width() > rect.width()-border_size*2 && total_rect_.height() > rect.height()-border_size*2-hsb.height()) return true; else return false; } } void on_h_scroll ( ) { total_rect_ = move_rect(total_rect_, display_rect_.left()-hscroll_bar_inc*hsb.slider_pos(), total_rect_.top()); parent.invalidate_rectangle(display_rect_); } void on_v_scroll ( ) { total_rect_ = move_rect(total_rect_, total_rect_.left(), display_rect_.top()-vscroll_bar_inc*vsb.slider_pos()); parent.invalidate_rectangle(display_rect_); } rectangle total_rect_; rectangle display_rect_; scroll_bar hsb; scroll_bar vsb; const unsigned long border_size; unsigned long hscroll_bar_inc; unsigned long vscroll_bar_inc; }; scrollable_region::~scrollable_region(){} // ---------------------------------------------------------------------------------------- } #ifdef NO_MAKEFILE #include "base_widgets.cpp" #endif #endif // DLIB_BASE_WIDGETs_
[ [ [ 1, 3023 ] ] ]
1a1dd7b92a30e37498ad3592fa48882276086bb6
935acce0c94ff0ea19955681eca4d0f60fc27f61
/src/itkMinErrorThresholdImageFilter.h
a5d24e5aadb6f7a8e230ceae7eb1bede56dbf9f6
[]
no_license
midas-journal/midas-journal-308
36a80484dc0914da0fec67b30980ec27bba34a79
fdddc9805324ae02eab0d20b748e154ef0077dd6
refs/heads/master
2020-04-23T18:08:13.242705
2011-08-22T13:23:38
2011-08-22T13:23:38
2,248,617
3
0
null
null
null
null
UTF-8
C++
false
false
5,502
h
/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: $RCSfile: itkMinErrorThresholdImageFilter.h,v $ Language: C++ Date: $Date: 2008/10/21 13:59:37 $ Version: $Revision: 1 $ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #ifndef __itkMinErrorThresholdImageFilter_h #define __itkMinErrorThresholdImageFilter_h #include "itkImageToImageFilter.h" #include "itkFixedArray.h" namespace itk { /** \class MinErrorThresholdImageFilter * \brief Threshold an image using the MinError Threshold * * This filter creates a binary thresholded image that separates an * image into foreground and background components. The filter * computes the threshold using the MinErrorThresholdImageCalculator. * * \sa MinErrorThresholdImageCalculator * \sa BinaryThresholdImageFilter * \ingroup IntensityImageFilters Multithreaded * \author Yousef Al-Kofahi, Rensselear Polytechnic Institute (RPI), Troy, NY USA */ template<class TInputImage, class TOutputImage> class ITK_EXPORT MinErrorThresholdImageFilter : public ImageToImageFilter<TInputImage, TOutputImage> { public: /** Standard Self typedef */ typedef MinErrorThresholdImageFilter Self; typedef ImageToImageFilter<TInputImage,TOutputImage> Superclass; typedef SmartPointer<Self> Pointer; typedef SmartPointer<const Self> ConstPointer; /** Method for creation through the object factory. */ itkNewMacro(Self); /** Runtime information support. */ itkTypeMacro(MinErrorThresholdImageFilter, ImageToImageFilter); /** Image pixel value typedef. */ typedef typename TInputImage::PixelType InputPixelType; typedef typename TOutputImage::PixelType OutputPixelType; /** Image related typedefs. */ typedef typename TInputImage::Pointer InputImagePointer; typedef typename TOutputImage::Pointer OutputImagePointer; typedef typename TInputImage::SizeType InputSizeType; typedef typename TInputImage::IndexType InputIndexType; typedef typename TInputImage::RegionType InputImageRegionType; typedef typename TOutputImage::SizeType OutputSizeType; typedef typename TOutputImage::IndexType OutputIndexType; typedef typename TOutputImage::RegionType OutputImageRegionType; /** Image related typedefs. */ itkStaticConstMacro(InputImageDimension, unsigned int, TInputImage::ImageDimension ) ; itkStaticConstMacro(OutputImageDimension, unsigned int, TOutputImage::ImageDimension ) ; /** Set the "outside" pixel value. The default value * NumericTraits<OutputPixelType>::Zero. */ itkSetMacro(OutsideValue,OutputPixelType); /** Get the "outside" pixel value. */ itkGetMacro(OutsideValue,OutputPixelType); /** Set the "inside" pixel value. The default value * NumericTraits<OutputPixelType>::max() */ itkSetMacro(InsideValue,OutputPixelType); /** Get the "inside" pixel value. */ itkGetMacro(InsideValue,OutputPixelType); /** Set/Get the number of histogram bins. Defaults is 128. */ itkSetClampMacro( NumberOfHistogramBins, unsigned long, 1, NumericTraits<unsigned long>::max() ); itkGetMacro( NumberOfHistogramBins, unsigned long ); /** Get the computed threshold. */ itkGetMacro(Threshold,InputPixelType); /** Get the estimated mixture parameters. */ itkGetMacro(AlphaLeft,double); itkGetMacro(AlphaRight,double); itkGetMacro(PriorLeft,double); itkGetMacro(PriorRight,double); itkGetMacro(StdLeft,double); itkGetMacro(StdRight,double) /** Set the type of the mixture (1=mix of Gaussians, 2=mix of Poissons). */ itkSetMacro(MixtureType, unsigned int); #ifdef ITK_USE_CONCEPT_CHECKING /** Begin concept checking */ itkConceptMacro(OutputEqualityComparableCheck, (Concept::EqualityComparable<OutputPixelType>)); itkConceptMacro(InputOStreamWritableCheck, (Concept::OStreamWritable<InputPixelType>)); itkConceptMacro(OutputOStreamWritableCheck, (Concept::OStreamWritable<OutputPixelType>)); /** End concept checking */ #endif protected: MinErrorThresholdImageFilter(); ~MinErrorThresholdImageFilter(){}; void PrintSelf(std::ostream& os, Indent indent) const; void GenerateInputRequestedRegion(); void GenerateData (); private: MinErrorThresholdImageFilter(const Self&); //purposely not implemented void operator=(const Self&); //purposely not implemented /** some needed variables */ InputPixelType m_Threshold; OutputPixelType m_InsideValue; OutputPixelType m_OutsideValue; unsigned long m_NumberOfHistogramBins; double m_AlphaLeft; double m_AlphaRight; double m_PriorLeft; double m_PriorRight; double m_StdLeft; double m_StdRight; unsigned int m_MixtureType; } ; // end of class } // end namespace itk #ifndef ITK_MANUAL_INSTANTIATION #include "itkMinErrorThresholdImageFilter.txx" #endif #endif
[ [ [ 1, 152 ] ] ]
8d25dce18a95032ca212b3a92a6f648bf793ffad
55196303f36aa20da255031a8f115b6af83e7d11
/private/tests/test_MFC/MainFrm.cpp
1ec4b517bd29b7627b60efda7f3b05c1dd7dd55a
[]
no_license
Heartbroken/bikini
3f5447647d39587ffe15a7ae5badab3300d2a2ff
fe74f51a3a5d281c671d303632ff38be84d23dd7
refs/heads/master
2021-01-10T19:48:40.851837
2010-05-25T19:58:52
2010-05-25T19:58:52
37,190,932
0
0
null
null
null
null
UTF-8
C++
false
false
2,170
cpp
// MainFrm.cpp : implementation of the CMainFrame class // #include "stdafx.h" #include "test_MFC.h" #include "MainFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CMainFrame IMPLEMENT_DYNAMIC(CMainFrame, CMDIFrameWnd) BEGIN_MESSAGE_MAP(CMainFrame, CMDIFrameWnd) ON_WM_CREATE() END_MESSAGE_MAP() static UINT indicators[] = { ID_SEPARATOR, // status line indicator ID_INDICATOR_CAPS, ID_INDICATOR_NUM, ID_INDICATOR_SCRL, }; // CMainFrame construction/destruction CMainFrame::CMainFrame() { // TODO: add member initialization code here } CMainFrame::~CMainFrame() { } int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CMDIFrameWnd::OnCreate(lpCreateStruct) == -1) return -1; if (!m_wndToolBar.CreateEx(this) || !m_wndToolBar.LoadToolBar(IDR_MAINFRAME)) { TRACE0("Failed to create toolbar\n"); return -1; // fail to create } if (!m_wndDlgBar.Create(this, IDR_MAINFRAME, CBRS_ALIGN_TOP, AFX_IDW_DIALOGBAR)) { TRACE0("Failed to create dialogbar\n"); return -1; // fail to create } if (!m_wndReBar.Create(this) || !m_wndReBar.AddBar(&m_wndToolBar) || !m_wndReBar.AddBar(&m_wndDlgBar)) { TRACE0("Failed to create rebar\n"); return -1; // fail to create } if (!m_wndStatusBar.Create(this) || !m_wndStatusBar.SetIndicators(indicators, sizeof(indicators)/sizeof(UINT))) { TRACE0("Failed to create status bar\n"); return -1; // fail to create } // TODO: Remove this if you don't want tool tips m_wndToolBar.SetBarStyle(m_wndToolBar.GetBarStyle() | CBRS_TOOLTIPS | CBRS_FLYBY); return 0; } BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs) { if( !CMDIFrameWnd::PreCreateWindow(cs) ) return FALSE; // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs return TRUE; } // CMainFrame diagnostics #ifdef _DEBUG void CMainFrame::AssertValid() const { CMDIFrameWnd::AssertValid(); } void CMainFrame::Dump(CDumpContext& dc) const { CMDIFrameWnd::Dump(dc); } #endif //_DEBUG // CMainFrame message handlers
[ [ [ 1, 114 ] ] ]
9e0957ab54ce8cde0fe1d9ba287835eb13152851
27d5670a7739a866c3ad97a71c0fc9334f6875f2
/CPP/Targets/MapLib/Shared/include/XorFileHandler.h
349df2ee64d015624260011576ba381bdcd61478
[ "BSD-3-Clause" ]
permissive
ravustaja/Wayfinder-S60-Navigator
ef506c418b8c2e6498ece6dcae67e583fb8a4a95
14d1b729b2cea52f726874687e78f17492949585
refs/heads/master
2021-01-16T20:53:37.630909
2010-06-28T09:51:10
2010-06-28T09:51:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,131
h
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef XORFILEHANDLER_H #define XORFILEHANDLER_H #include "config.h" #include "XorHelper.h" #include "FileHandler.h" /** * FileHandler that can handle files that are partly xor "encrypted". */ class XorFileHandler : public FileHandler, public FileHandlerListener { public: /** * Constructs a XorFilehandler by passing another filehandler to it. * The supplied filehandler will not be deleted by the * XorFileHandler's constructor. */ XorFileHandler( FileHandler* fh ) : FileHandler( fh->getFileName() ), m_fh( fh ), m_xorHelper( NULL, 0, 0 ), m_pos( 0 ) {} /** * Set the xor helper. */ void setXorHelper( const XorHelper& xorHelper ) { m_xorHelper = xorHelper; } /** * Destroys the file handler and closes the file. */ virtual ~XorFileHandler() {} /** * Returns the original file handler. */ FileHandler* getOriginalFileHandler() const { return m_fh; } /** * Clears the file to zero length. */ void clearFile() { m_fh->clearFile(); } /** * Returns 0 if everything has been ok so far. */ int status() const { return m_fh->status(); } /** * Reads maxLength bytes from the file. * Calls the listener when done. If listener is NULL the * call will by synchronous and the number of bytes written * will be returned. */ int read( uint8* bytes, int maxLength, FileHandlerListener* listener ) { m_lastReadBuffer = bytes; m_listener = listener; return m_fh->read( bytes, maxLength, this ); } /** * Sets the read and write positions of the stream to the sent-in value. * -1 should set the position to end of file. */ void setPos( int pos ) { m_pos = pos; m_fh->setPos( pos ); } /** * Sets the size of the file. * @param size The new size in bytes. */ void setSize( int size ) { m_fh->setSize( size ); } /** * Returns the read/write position in the stream. */ int tell() { return m_pos; } /** * Writes bytes to the file of the FileHandler. * Calls the listener when it is done. * If listener is NULL the * call will by synchronous and the number of bytes written * will be returned. */ int write( const uint8* bytes, int length, FileHandlerListener* listener ) { xorBuffer( const_cast<uint8*> (bytes), m_pos, length ); m_listener = listener; return m_fh->write( bytes, length, this ); } /** * Returns the modification date of the file. * Currently it is enough if the date is less for * old files and more for new files. */ uint32 getModificationDate() const { return m_fh->getModificationDate(); } /** * Returns the amount of available space on the drive * where the file is located. */ uint32 getAvailableSpace() const { return m_fh->getAvailableSpace(); } /** * Cancels outstanding reads/writes. */ void cancel() { m_fh->cancel(); } /** * Returns the size of the file. */ int getFileSize() { return m_fh->getFileSize(); } /** * Called when the read is done. * @param nbrRead The number of bytes read. Negative value for failure. */ void readDone( int nbrRead ) { xorBuffer( m_lastReadBuffer, m_pos, nbrRead ); m_pos += nbrRead; m_listener->readDone( nbrRead ); } /** * Called when the write is done. * @param nbrWritten The number of bytes written. Negative for failure. */ void writeDone( int nbrWritten ) { m_pos += nbrWritten; m_listener->writeDone( nbrWritten ); } private: /** * Xor the supplied buffer. * @param buf The buffer to xor. * @param pos The position of the buffer in the file. * @param length The length of the buffer. */ void xorBuffer( uint8* buf, int pos, int length ) { m_xorHelper.xorBuffer( buf, pos, length ); } /// The filehandler. FileHandler* m_fh; /// The XorHelper. XorHelper m_xorHelper; /// The position of the file. int m_pos; /// The last readbuffer. uint8* m_lastReadBuffer; /// The listener. FileHandlerListener* m_listener; }; #endif
[ [ [ 1, 185 ] ] ]
8b816ffe59ba6249c04c7f5176c16efeebc2ef98
478570cde911b8e8e39046de62d3b5966b850384
/apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libc/testsyssim/inc/tsyssimserver.h
3806b12e4947d3293ae3007f495034bf7a118d2b
[]
no_license
SymbianSource/oss.FCL.sftools.ana.compatanamdw
a6a8abf9ef7ad71021d43b7f2b2076b504d4445e
1169475bbf82ebb763de36686d144336fcf9d93b
refs/heads/master
2020-12-24T12:29:44.646072
2010-11-11T14:03:20
2010-11-11T14:03:20
72,994,432
0
0
null
null
null
null
UTF-8
C++
false
false
1,021
h
/* * Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of "Eclipse Public License v1.0" * which accompanies this distribution, and is available * at the URL "http://www.eclipse.org/legal/epl-v10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ /* * ============================================================================== * Name : tsyssimserver.h * Part of : testsyssim * * Description : ?Description * Version: 0.5 * */ #ifndef __TSYSSIMSERVER_H__ #define __TSYSSIMSERVER_H__ #include <f32file.h> #include <test/TestExecuteServerBase.h> class CSyssimTestServer : public CTestServer { public: static CSyssimTestServer* NewL(); virtual CTestStep* CreateTestStep(const TDesC& aStepName); RFs& Fs() {return iFs;} private: RFs iFs; }; #endif //
[ "none@none" ]
[ [ [ 1, 47 ] ] ]
a00493526a4b051b4bda6a4cb2f9921ac92fa9f2
38fa90e0adaf61d02802e77962075f6913a3cdfa
/include/AoTK/math/vector3.hpp
82e83169ff0d651c14db1cdce598b850a130dbd5
[]
no_license
r-englund/AoTK
49097b39906c5f9cad1c79f3e22f867cbfe806e3
7a52b0788c25710b00fa5e582ef2fcbc4c839a8f
refs/heads/master
2021-01-17T11:54:34.889565
2011-09-01T20:19:38
2011-09-01T20:19:38
1,339,861
0
0
null
null
null
null
UTF-8
C++
false
false
5,161
hpp
#ifndef _AOTK_VECTOR3_HPP_ #define _AOTK_VECTOR3_HPP_ namespace AoTK{ namespace Math{ template<typename T> Vector3<T>::Vector3(T _x,T _y, T _z):x(_x),y(_y),z(_z){} template<typename T> Vector3<T>::Vector3():x(0),y(0),z(0){} template<typename T> template<typename T2> Vector3<T>::Vector3(const Vector3<T2> &V):x(V.x),y(V.y),z(V.z){} template<typename T> template<typename T2> T Vector3<T>::dot(const Vector3<T2> &V)const{ return x*V.x+y*V.y+z*V.z; } template<typename T> template<typename T2> Vector3<T> Vector3<T>::cross(const Vector3<T2> &V)const{ Vector3<T> _v; _v.x = y*V.z-z*V.y; _v.y = 0-x*V.z+z*V.x; _v.z = x*V.y-y*V.x; return _v; } #include <assert.h> template<typename T> inline void Vector3<T>::normalize(){ float l = sqrt(x*x+y*y+z*z); if(floatCMP(l,0)||floatCMP(l,1)) return; x /= l; y /= l; z /= l; } template<typename T> inline T Vector3<T>::getLength()const{ return sqrt(x*x+y*y+z*z); } template<typename T> template<typename T2> inline Vector3<T> Vector3<T>::operator+(const Vector3<T2> &V)const{ Vector3<T> _v(V); _v.x += x; _v.y += y; _v.z += z; return _v; } template<typename T> template<typename T2> inline Vector3<T> Vector3<T>::operator-(const Vector3<T2> &V)const{ Vector3<T> _v(V); _v.x -= x; _v.y -= y; _v.z -= z; return _v; } template<typename T> template<typename T2> inline Vector3<T> Vector3<T>::operator+(T2 t)const{ Vector3<T> _v(*this); _v.x += t; _v.y += t; _v.z += t; return _v; } template<typename T> template<typename T2> inline Vector3<T> Vector3<T>::operator-(T2 t)const{ Vector3<T> _v(*this); _v.x -= t; _v.y -= t; _v.z -= t; return _v; } template<typename T> template<typename T2> inline Vector3<T> Vector3<T>::operator*(T2 t)const{ Vector3<T> _v(*this); _v.x *= t; _v.y *= t; _v.z *= t; return _v; } template<typename T> template<typename T2> inline Vector3<T> Vector3<T>::operator/(T2 t)const{ Vector3<T> _v(*this); _v.x /= t; _v.y /= t; _v.z /= t; return _v; } template<typename T> template<typename T2> inline Vector3<T>& Vector3<T>::operator+=(const Vector3<T2> &V){ x+=V.x; y+=V.y; z+=V.z; return *this; } template<typename T> template<typename T2> inline Vector3<T>& Vector3<T>::operator-=(const Vector3<T2> &V){ x-=V.x; y-=V.y; z-=V.z; return *this; } template<typename T> template<typename T2> inline Vector3<T>& Vector3<T>::operator+=(T2 t){ x+=t; y+=t; z+=t; return *this; } template<typename T> template<typename T2> inline Vector3<T>& Vector3<T>::operator-=(T2 t){ x-=t; y-=t; z-=t; return *this; } template<typename T> template<typename T2> inline Vector3<T>& Vector3<T>::operator*=(T2 t){ x*=t; y*=t; z*=t; return *this; } template<typename T> template<typename T2> inline Vector3<T>& Vector3<T>::operator/=(T2 t){ x/=t; y/=t; z/=t; return *this; } template<typename T> template<typename T2> inline bool Vector3<T>::operator==(const Vector3<T2> &V)const{return x==V.x && y ==V.y && z ==V.z;} template<typename T> template<typename T2> inline bool Vector3<T>::operator!=(const Vector3<T2> &V)const{return x!=V.x || y !=V.y || z !=V.z;} template<typename T> template<typename T2> inline bool Vector3<T>::operator>(const Vector3<T2> &m)const{ return getLength() > m.getLength(); } template<typename T> template<typename T2> inline bool Vector3<T>::operator<(const Vector3<T2> &m)const{ return getLength() < m.getLength(); } template<typename T> template<typename T2> inline bool Vector3<T>::operator<=(const Vector3<T2> &m)const{ return getLength() <= m.getLength(); } template<typename T> template<typename T2> inline bool Vector3<T>::operator>=(const Vector3<T2> &m)const{ return getLength() >= m.getLength(); } //template<typename T> //std::ostream &operator<<(std::ostream &os,const Vector3<T> &V){ // os <<"["<< V.x << " " << V.y << " " << V.z << "]"; // return os; //} // //template<> //std::ostream &operator<<(std::ostream &os,const Vector3<int8_t> &V){ // os <<"["<< (int)V.x << " " << (int)V.y << " " << (int)V.z << "]"; // return os; //} // //template<> //std::ostream &operator<<(std::ostream &os,const Vector3<uint8_t> &V){ // os <<"["<< (int)V.x << " " << (int)V.y << " " << (int)V.z << "]"; // return os; //} // //template<typename T,typename T2> Vector3<T> operator*(T2 t,const Vector3<T> &v){ // Vector3<T> V(v); // V*=t; // return V; //} //template<typename T,typename T2> Vector3<T> operator+(T2 t,const Vector3<T> &v){ // Vector3<T> V(v); // V+=t; // return V; //} //template<typename T,typename T2> Vector3<T> operator-(T2 t,const Vector3<T> &v){ // Vector3<T> V(v); // V-=t; // return V; //} //template<typename T,typename T2> Vector3<T> operator/(T2 t,const Vector3<T> &v){ // Vector3<T> V(v); // V/=t; // return V; //} }; }; #endif
[ [ [ 1, 198 ] ] ]
5e1e0d77402257b04b7081b6e9bc80125e06e73f
353bd39ba7ae46ed521936753176ed17ea8546b5
/src/layer0_base/callback/src/dummy.cpp
0320b38559a3ba48276c2841f1b2aebd9c0772f5
[]
no_license
d0n3val/axe-engine
1a13e8eee0da667ac40ac4d92b6a084ab8a910e8
320b08df3a1a5254b776c81775b28fa7004861dc
refs/heads/master
2021-01-01T19:46:39.641648
2007-12-10T18:26:22
2007-12-10T18:26:22
32,251,179
1
0
null
null
null
null
UTF-8
C++
false
false
173
cpp
/** * @file * Dummy file to generate some code * @date 10 Jun 2004 */ #include "axe_callback.h" /* $Id: dummy.cpp,v 1.1 2004/07/27 22:42:48 doneval Exp $ */
[ "d0n3val@2cff7946-3f3c-0410-b79f-f9b517ddbf54" ]
[ [ [ 1, 9 ] ] ]
d8302f431cb36c82d7298e259ccb85397dcf0ad8
38926bfe477f933a307f51376dd3c356e7893ffc
/Source/CryEngine/CryCommon/Cry_Color.h
d79e80c203cc25fed24aa0d3b0d9d5bd88e6e027
[]
no_license
richmondx/dead6
b0e9dd94a0ebb297c0c6e9c4f24c6482ef4d5161
955f76f35d94ed5f991871407f3d3ad83f06a530
refs/heads/master
2021-12-05T14:32:01.782047
2008-01-01T13:13:39
2008-01-01T13:13:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
22,170
h
////////////////////////////////////////////////////////////////////// // // Crytek (C) 2001 // // File: CryColor4.h // Description: 4D Color template. // // History: // - August 12, 2001: Created by Alberto Demichelis // ////////////////////////////////////////////////////////////////////// #ifndef CRYTEK_CRYCOLOR_H #define CRYTEK_CRYCOLOR_H _inline float FClamp( float X, float Min, float Max ) { return X<Min ? Min : X<Max ? X : Max; } template <class T> struct Color_tpl; typedef Color_tpl<uint8> ColorB; // [ 0, 255] typedef Color_tpl<float> ColorF; // [0.0, 1.0] ////////////////////////////////////////////////////////////////////////////////////////////// // RGBA Color structure. ////////////////////////////////////////////////////////////////////////////////////////////// template <class T> struct Color_tpl { T r,g,b,a; inline Color_tpl() {}; Color_tpl(T _x, T _y, T _z, T _w); Color_tpl(T _x, T _y, T _z); /* inline Color_tpl(const Color_tpl<T> & v) { r = v.r; g = v.g; b = v.b; a = v.a; }*/ // works together with pack_abgr8888 Color_tpl(const unsigned int abgr ); Color_tpl(const f32 c ); Color_tpl(const ColorF& c); Color_tpl(const Vec3& c, float fAlpha); void Clamp(float Min = 0, float Max = 1.0f) { r = ::FClamp(r, Min, Max); g = ::FClamp(g, Min, Max); b = ::FClamp(b, Min, Max); a = ::FClamp(a, Min, Max); } void ScaleCol (float f) { r *= f; g *= f; b *= f; } float Luminance() const { return r*0.33f + g*0.59f + b*0.11f; } float NormalizeCol (ColorF& out) { float max; max = r; if (g > max) max = g; if (b > max) max = b; if (max == 0) return 0; out = *this / max; return max; } Color_tpl(const Vec3 & vVec) { r = (T)vVec.x; g = (T)vVec.y; b = (T)vVec.z; a = (T)1.f; } inline Color_tpl& operator = (const Vec3 &v) { r=(T)v.x; g=(T)v.y; b=(T)v.z; a=(T)1.0f; return *this; } inline T &operator [] (int index) { assert(index>=0 && index<=3); return ((T*)this)[index]; } inline T operator [] (int index) const { assert(index>=0 && index<=3); return ((T*)this)[index]; } void Set(float fR,float fG,float fB,float fA=1.0f) { r=static_cast<T>(fR);g=static_cast<T>(fG);b=static_cast<T>(fB);a=static_cast<T>(fA); } inline void set(T _x, T _y = 0, T _z = 0, T _w = 0) { r = _x; g = _y; b = _z; a = _w; } inline void set(T _x, T _y = 0, T _z = 0) { r = _x; g = _y; b = _z; a = 1; } inline Color_tpl operator + () const { return *this; } inline Color_tpl operator - () const { return Color_tpl<T>(-r, -g, -b, -a); } inline Color_tpl & operator += (const Color_tpl & v) { r += v.r; g += v.g; b += v.b; a += v.a; return *this; } inline Color_tpl & operator -= (const Color_tpl & v) { r -= v.r; g -= v.g; b -= v.b; a -= v.a; return *this; } inline Color_tpl & operator *= (const Color_tpl & v) { r *= v.r; g *= v.g; b *= v.b; a *= v.a; return *this; } inline Color_tpl & operator /= (const Color_tpl & v) { r /= v.r; g /= v.g; b /= v.b; a /= v.a; return *this; } inline Color_tpl & operator *= (T s) { r *= s; g *= s; b *= s; a *= s; return *this; } inline Color_tpl & operator /= (T s) { s = 1.0f / s; r *= s; g *= s; b *= s; a *= s; return *this; } inline Color_tpl operator + (const Color_tpl & v) const { return Color_tpl(r + v.r, g + v.g, b + v.b, a + v.a); } inline Color_tpl operator - (const Color_tpl & v) const { return Color_tpl(r - v.r, g - v.g, b - v.b, a - v.a); } inline Color_tpl operator * (const Color_tpl & v) const { return Color_tpl(r * v.r, g * v.g, b * v.b, a * v.a); } inline Color_tpl operator / (const Color_tpl & v) const { return Color_tpl(r / v.r, g / v.g, b / v.b, a / v.a); } inline Color_tpl operator * (T s) const { return Color_tpl(r * s, g * s, b * s, a * s); } inline Color_tpl operator / (T s) const { s = 1.0f / s; return Color_tpl(r * s, g * s, b * s, a * s); } inline bool operator == (const Color_tpl & v) const { return (r == v.r) && (g == v.g) && (b == v.b) && (a == v.a); } inline bool operator != (const Color_tpl & v) const { return (r != v.r) || (g != v.g) || (b != v.b) || (a != v.a); } inline unsigned char pack_rgb332() const; inline unsigned short pack_argb4444() const; inline unsigned short pack_rgb555() const; inline unsigned short pack_rgb565() const; inline unsigned int pack_rgb888() const; inline unsigned int pack_abgr8888() const; inline unsigned int pack_argb8888() const; inline Vec4 toVec4() { return Vec4(r,g,b,a); } inline void clamp(T bottom = 0.0f, T top = 1.0f); inline void maximum(const Color_tpl<T> &ca, const Color_tpl<T> &cb); inline void minimum(const Color_tpl<T> &ca, const Color_tpl<T> &cb); inline void abs(); inline void adjust_contrast(T c); inline void adjust_saturation(T s); inline void lerpFloat(const Color_tpl<T> &ca, const Color_tpl<T> &cb, float s); inline void negative(const Color_tpl<T> &c); inline void grey(const Color_tpl<T> &c); // helper function - maybe we can improve the integration static inline uint32 ComputeAvgCol_Fast( const uint32 dwCol0, const uint32 dwCol1 ) { uint32 dwHalfCol0 = (dwCol0/2) & 0x7f7f7f7f; // each component /2 uint32 dwHalfCol1 = (dwCol1/2) & 0x7f7f7f7f; // each component /2 return dwHalfCol0+dwHalfCol1; } // mCIE: adjusted to compensate problems of DXT compression (extra bit in green channel causes green/purple artefacts) // explained in CryEngine2 wiki: ColorSpaces Color_tpl<T> RGB2mCIE() const { float RGBSum = r+g+b; // 30.0f/31.0f to allow to express 1/3 (for grey colors) float fInv = (30.0f/31.0f) / (RGBSum+0.003f); // +0.001/0.003 to get 1/3 in the case of very dark colors float RNorm = (r+0.001f)*fInv; // float BNorm = (b+0.001f)*fInv; float GNorm = (g+0.001f)*fInv; float Scale = RGBSum/(3.0f); if(RNorm<0)RNorm=0; if(RNorm>1)RNorm=1; // if(BNorm<0)BNorm=0; if(BNorm>1)BNorm=1; if(GNorm<0)GNorm=0; if(GNorm>1)GNorm=1; // return Color_tpl<T>(RNorm,Scale,BNorm); return Color_tpl<T>(RNorm,GNorm,Scale); } // mCIE: adjusted to compensate problems of DXT compression (extra bit in green channel causes green/purple artefacts) // explained in CryEngine2 wiki: ColorSpaces Color_tpl<T> mCIE2RGB() const { // float fScale=g; float fScale=b; Color_tpl<T> ret = *this; // ret.g = 30.0f/31.0f-r-b; // ret.g = 30.0f/31.0f*0.997f-r-b; // improved grey scale ret.b = 30.0f/31.0f*0.997f-r-g; // improved grey scale ret *= 3.0f*31.0f/30.0f*fScale; ret.Clamp(); return ret; } AUTO_STRUCT_INFO }; ////////////////////////////////////////////////////////////////////////////////////////////// // template specialization /////////////////////////////////////////////// template<> inline Color_tpl<f32>::Color_tpl(f32 _x, f32 _y, f32 _z, f32 _w) { r = _x; g = _y; b = _z; a = _w; } template<> inline Color_tpl<f32>::Color_tpl(f32 _x, f32 _y, f32 _z) { r = _x; g = _y; b = _z; a = 1.f; } template<> inline Color_tpl<uint8>::Color_tpl(uint8 _x, uint8 _y, uint8 _z, uint8 _w) { r = _x; g = _y; b = _z; a = _w; } template<> inline Color_tpl<uint8>::Color_tpl(uint8 _x, uint8 _y, uint8 _z) { r = _x; g = _y; b = _z; a = 255; } //----------------------------------------------------------------------------- template<> inline Color_tpl<f32>::Color_tpl(const unsigned int abgr) { r = (abgr & 0xff) / 255.0f; g = ((abgr>>8) & 0xff) / 255.0f; b = ((abgr>>16) & 0xff) / 255.0f; a = ((abgr>>24) & 0xff) / 255.0f; } template<> inline Color_tpl<uint8>::Color_tpl(const unsigned int c) { *(unsigned int*)(&r)=c; } //use this with RGBA8 macro! //----------------------------------------------------------------------------- template<> inline Color_tpl<f32>::Color_tpl(const float c) { r=c; g=c; b=c; a=c; } template<> inline Color_tpl<uint8>::Color_tpl(const float c) { r = (uint8)(c*255); g = (uint8)(c*255); b = (uint8)(c*255); a = (uint8)(c*255); } //----------------------------------------------------------------------------- template<> inline Color_tpl<f32>::Color_tpl(const ColorF& c) { r=c.r; g=c.g; b=c.b; a=c.a; } template<> inline Color_tpl<uint8>::Color_tpl(const ColorF& c) { r = (uint8)(c.r*255); g = (uint8)(c.g*255); b = (uint8)(c.b*255); a = (uint8)(c.a*255); } template<> inline Color_tpl<f32>::Color_tpl(const Vec3& c, float fAlpha) { r=c.x; g=c.y; b=c.z; a=fAlpha; } template<> inline Color_tpl<uint8>::Color_tpl(const Vec3& c, float fAlpha) { r = (uint8)(c.x*255); g = (uint8)(c.y*255); b = (uint8)(c.z*255); a = (uint8)(fAlpha*255); } ////////////////////////////////////////////////////////////////////////////////////////////// // functions implementation /////////////////////////////////////////////// /////////////////////////////////////////////// /*template <class T> inline Color_tpl<T>::Color_tpl(const T *p_elts) { r = p_elts[0]; g = p_elts[1]; b = p_elts[2]; a = p_elts[3]; }*/ /////////////////////////////////////////////// /////////////////////////////////////////////// template <class T> inline Color_tpl<T> operator * (T s, const Color_tpl<T> & v) { return Color_tpl<T>(v.r * s, v.g * s, v.b * s, v.a * s); } /////////////////////////////////////////////// template <class T> inline unsigned char Color_tpl<T>::pack_rgb332() const { unsigned char cr; unsigned char cg; unsigned char cb; if(sizeof(r) == 1) // char and unsigned char { cr = r; cg = g; cb = b; } else if(sizeof(r) == 2) // short and unsigned short { cr = (unsigned short)(r)>>8; cg = (unsigned short)(g)>>8; cb = (unsigned short)(b)>>8; } else // float or double { cr = (unsigned char)(r * 255.0f); cg = (unsigned char)(g * 255.0f); cb = (unsigned char)(b * 255.0f); } return ((cr >> 5) << 5) | ((cg >> 5) << 2) | (cb >> 5); } /////////////////////////////////////////////// template <class T> inline unsigned short Color_tpl<T>::pack_argb4444() const { unsigned char cr; unsigned char cg; unsigned char cb; unsigned char ca; if(sizeof(r) == 1) // char and unsigned char { cr = r; cg = g; cb = b; ca = a; } else if(sizeof(r) == 2) // short and unsigned short { cr = (unsigned short)(r)>>8; cg = (unsigned short)(g)>>8; cb = (unsigned short)(b)>>8; ca = (unsigned short)(a)>>8; } else // float or double { cr = (unsigned char)(r * 255.0f); cg = (unsigned char)(g * 255.0f); cb = (unsigned char)(b * 255.0f); ca = (unsigned char)(a * 255.0f); } return ((ca >> 4) << 12) | ((cr >> 4) << 8) | ((cg >> 4) << 4) | (cb >> 4); } /////////////////////////////////////////////// template <class T> inline unsigned short Color_tpl<T>::pack_rgb555() const { unsigned char cr; unsigned char cg; unsigned char cb; if(sizeof(r) == 1) // char and unsigned char { cr = r; cg = g; cb = b; } else if(sizeof(r) == 2) // short and unsigned short { cr = (unsigned short)(r)>>8; cg = (unsigned short)(g)>>8; cb = (unsigned short)(b)>>8; } else // float or double { cr = (unsigned char)(r * 255.0f); cg = (unsigned char)(g * 255.0f); cb = (unsigned char)(b * 255.0f); } return ((cr >> 3) << 10) | ((cg >> 3) << 5) | (cb >> 3); } /////////////////////////////////////////////// template <class T> inline unsigned short Color_tpl<T>::pack_rgb565() const { unsigned short cr; unsigned short cg; unsigned short cb; if(sizeof(r) == 1) // char and unsigned char { cr = (unsigned short)r; cg = (unsigned short)g; cb = (unsigned short)b; } else if(sizeof(r) == 2) // short and unsigned short { cr = (unsigned short)(r)>>8; cg = (unsigned short)(g)>>8; cb = (unsigned short)(b)>>8; } else // float or double { cr = (unsigned short)(r * 255.0f); cg = (unsigned short)(g * 255.0f); cb = (unsigned short)(b * 255.0f); } return ((cr >> 3) << 11) | ((cg >> 2) << 5) | (cb >> 3); } /////////////////////////////////////////////// template <class T> inline unsigned int Color_tpl<T>::pack_rgb888() const { unsigned char cr; unsigned char cg; unsigned char cb; if(sizeof(r) == 1) // char and unsigned char { cr = (unsigned char)r; cg = (unsigned char)g; cb = (unsigned char)b; } else if(sizeof(r) == 2) // short and unsigned short { cr = (unsigned short)(r)>>8; cg = (unsigned short)(g)>>8; cb = (unsigned short)(b)>>8; } else // float or double { cr = (unsigned char)(r * 255.0f); cg = (unsigned char)(g * 255.0f); cb = (unsigned char)(b * 255.0f); } return (cr << 16) | (cg << 8) | cb; } /////////////////////////////////////////////// template <class T> inline unsigned int Color_tpl<T>::pack_abgr8888() const { unsigned char cr; unsigned char cg; unsigned char cb; unsigned char ca; if(sizeof(r) == 1) // char and unsigned char { cr = (unsigned char)r; cg = (unsigned char)g; cb = (unsigned char)b; ca = (unsigned char)a; } else if(sizeof(r) == 2) // short and unsigned short { cr = (unsigned short)(r)>>8; cg = (unsigned short)(g)>>8; cb = (unsigned short)(b)>>8; ca = (unsigned short)(a)>>8; } else // float or double { cr = (unsigned char)(r * 255.0f); cg = (unsigned char)(g * 255.0f); cb = (unsigned char)(b * 255.0f); ca = (unsigned char)(a * 255.0f); } return (ca << 24) | (cb << 16) | (cg << 8) | cr; } /////////////////////////////////////////////// template <class T> inline unsigned int Color_tpl<T>::pack_argb8888() const { unsigned char cr; unsigned char cg; unsigned char cb; unsigned char ca; if(sizeof(r) == 1) // char and unsigned char { cr = (unsigned char)r; cg = (unsigned char)g; cb = (unsigned char)b; ca = (unsigned char)a; } else if(sizeof(r) == 2) // short and unsigned short { cr = (unsigned short)(r)>>8; cg = (unsigned short)(g)>>8; cb = (unsigned short)(b)>>8; ca = (unsigned short)(a)>>8; } else // float or double { cr = (unsigned char)(r * 255.0f); cg = (unsigned char)(g * 255.0f); cb = (unsigned char)(b * 255.0f); ca = (unsigned char)(a * 255.0f); } return (ca << 24) | (cr << 16) | (cg << 8) | cb; } /////////////////////////////////////////////// template <class T> inline void Color_tpl<T>::clamp(T bottom, T top) { if(r < bottom) r = bottom; else if(r > top) r = top; if(g < bottom) g = bottom; else if(g > top) g = top; if(b < bottom) b = bottom; else if(b > top) b = top; if(a < bottom) a = bottom; else if(a > top) a = top; } /////////////////////////////////////////////// template <class T> void Color_tpl<T>::maximum(const Color_tpl<T> &ca, const Color_tpl<T> &cb) { r = (ca.r > cb.r) ? ca.r : cb.r; g = (ca.g > cb.g) ? ca.g : cb.g; b = (ca.b > cb.b) ? ca.b : cb.b; a = (ca.a > cb.a) ? ca.a : cb.a; } /////////////////////////////////////////////// template <class T> void Color_tpl<T>::minimum(const Color_tpl<T> &ca, const Color_tpl<T> &cb) { r = (ca.r < cb.r) ? ca.r : cb.r; g = (ca.g < cb.g) ? ca.g : cb.g; b = (ca.b < cb.b) ? ca.b : cb.b; a = (ca.a < cb.a) ? ca.a : cb.a; } /////////////////////////////////////////////// template <class T> void Color_tpl<T>::abs() { r = (r < 0) ? -r : r; g = (g < 0) ? -g : g; b = (b < 0) ? -b : b; a = (a < 0) ? -a : a; } /////////////////////////////////////////////// template <class T> void Color_tpl<T>::adjust_contrast(T c) { r = 0.5f + c * (r - 0.5f); g = 0.5f + c * (g - 0.5f); b = 0.5f + c * (b - 0.5f); a = 0.5f + c * (a - 0.5f); } /////////////////////////////////////////////// template <class T> void Color_tpl<T>::adjust_saturation(T s) { // Approximate values for each component's contribution to luminance. // Based upon the NTSC standard described in ITU-R Recommendation BT.709. T grey = r * 0.2125f + g * 0.7154f + b * 0.0721f; r = grey + s * (r - grey); g = grey + s * (g - grey); b = grey + s * (b - grey); a = grey + s * (a - grey); } /////////////////////////////////////////////// template <class T> void Color_tpl<T>::lerpFloat(const Color_tpl<T> &ca, const Color_tpl<T> &cb, float s) { r = (T)(ca.r + s * (cb.r - ca.r)); g = (T)(ca.g + s * (cb.g - ca.g)); b = (T)(ca.b + s * (cb.b - ca.b)); a = (T)(ca.a + s * (cb.a - ca.a)); } /////////////////////////////////////////////// template <class T> void Color_tpl<T>::negative(const Color_tpl<T> &c) { r = T(1.0f) - r; g = T(1.0f) - g; b = T(1.0f) - b; a = T(1.0f) - a; } /////////////////////////////////////////////// template <class T> void Color_tpl<T>::grey(const Color_tpl<T> &c) { T m = (r + g + b) / T(3); r = m; g = m; b = m; a = a; } ////////////////////////////////////////////////////////////////////////////////////////////// //#define RGBA8(r,g,b,a) (ColorB((uint8)(r),(uint8)(g),(uint8)(b),(uint8)(a))) #if defined(NEED_ENDIAN_SWAP) #define RGBA8(a,b,g,r) ((uint32)(((uint8)(r)|((uint16)((uint8)(g))<<8))|(((uint32)(uint8)(b))<<16)) | (((uint32)(uint8)(a))<<24) ) #else #define RGBA8(r,g,b,a) ((uint32)(((uint8)(r)|((uint16)((uint8)(g))<<8))|(((uint32)(uint8)(b))<<16)) | (((uint32)(uint8)(a))<<24) ) #endif #define Col_Black ColorF (0.0f, 0.0f, 0.0f) #define Col_White ColorF (1.0f, 1.0f, 1.0f) #define Col_Aquamarine ColorF (0.439216f, 0.858824f, 0.576471f) #define Col_Blue ColorF (0.0f, 0.0f, 1.0f) #define Col_BlueViolet ColorF (0.623529f, 0.372549f, 0.623529f) #define Col_Brown ColorF (0.647059f, 0.164706f, 0.164706f) #define Col_CadetBlue ColorF (0.372549f, 0.623529f, 0.623529f) #define Col_Coral ColorF (1.0f, 0.498039f, 0.0f) #define Col_CornflowerBlue ColorF (0.258824f, 0.258824f, 0.435294f) #define Col_Cyan ColorF (0.0f, 1.0f, 1.0f) #define Col_DarkGray ColorF (0.5f, 0.5f, 0.5f) #define Col_DarkGreen ColorF (0.184314f, 0.309804f, 0.184314f) #define Col_DarkOliveGreen ColorF (0.309804f, 0.309804f, 0.184314f) #define Col_DarkOrchild ColorF (0.6f, 0.196078f, 0.8f) #define Col_DarkSlateBlue ColorF (0.419608f, 0.137255f, 0.556863f) #define Col_DarkSlateGray ColorF (0.184314f, 0.309804f, 0.309804f) #define Col_DarkSlateGrey ColorF (0.184314f, 0.309804f, 0.309804f) #define Col_DarkTurquoise ColorF (0.439216f, 0.576471f, 0.858824f) #define Col_DarkWood ColorF (0.05f, 0.01f, 0.005f) #define Col_DimGray ColorF (0.329412f, 0.329412f, 0.329412f) #define Col_DimGrey ColorF (0.329412f, 0.329412f, 0.329412f) #define Col_FireBrick ColorF (0.9f, 0.4f, 0.3f) #define Col_ForestGreen ColorF (0.137255f, 0.556863f, 0.137255f) #define Col_Gold ColorF (0.8f, 0.498039f, 0.196078f) #define Col_Goldenrod ColorF (0.858824f, 0.858824f, 0.439216f) #define Col_Gray ColorF (0.752941f, 0.752941f, 0.752941f) #define Col_Green ColorF (0.0f, 1.0f, 0.0f) #define Col_GreenYellow ColorF (0.576471f, 0.858824f, 0.439216f) #define Col_Grey ColorF (0.752941f, 0.752941f, 0.752941f) #define Col_IndianRed ColorF (0.309804f, 0.184314f, 0.184314f) #define Col_Khaki ColorF (0.623529f, 0.623529f, 0.372549f) #define Col_LightBlue ColorF (0.74902f, 0.847059f, 0.847059f) #define Col_LightGray ColorF (0.658824f, 0.658824f, 0.658824f) #define Col_LightGrey ColorF (0.658824f, 0.658824f, 0.658824f) #define Col_LightSteelBlue ColorF (0.560784f, 0.560784f, 0.737255f) #define Col_LightWood ColorF (0.6f, 0.24f, 0.1f) #define Col_LimeGreen ColorF (0.196078f, 0.8f, 0.196078f) #define Col_Magenta ColorF (1.0f, 0.0f, 1.0f) #define Col_Maroon ColorF (0.556863f, 0.137255f, 0.419608f) #define Col_MedianWood ColorF (0.3f, 0.12f, 0.03f) #define Col_MediumAquamarine ColorF (0.196078f, 0.8f, 0.6f) #define Col_MediumBlue ColorF (0.196078f, 0.196078f, 0.8f) #define Col_MediumForestGreen ColorF (0.419608f, 0.556863f, 0.137255f) #define Col_MediumGoldenrod ColorF (0.917647f, 0.917647f, 0.678431f) #define Col_MediumOrchid ColorF (0.576471f, 0.439216f, 0.858824f) #define Col_MediumSeaGreen ColorF (0.258824f, 0.435294f, 0.258824f) #define Col_MediumSlateBlue ColorF (0.498039f, 0.0f, 1.0f) #define Col_MediumSpringGreen ColorF (0.498039f, 1.0f, 0.0f) #define Col_MediumTurquoise ColorF (0.439216f, 0.858824f, 0.858824f) #define Col_MediumVioletRed ColorF (0.858824f, 0.439216f, 0.576471f) #define Col_MidnightBlue ColorF (0.184314f, 0.184314f, 0.309804f) #define Col_Navy ColorF (0.137255f, 0.137255f, 0.556863f) #define Col_NavyBlue ColorF (0.137255f, 0.137255f, 0.556863f) #define Col_Orange ColorF (0.8f, 0.196078f, 0.196078f) #define Col_OrangeRed ColorF (0.0f, 0.0f, 0.498039f) #define Col_Orchid ColorF (0.858824f, 0.439216f, 0.858824f) #define Col_PaleGreen ColorF (0.560784f, 0.737255f, 0.560784f) #define Col_Pink ColorF (0.737255f, 0.560784f, 0.560784f) #define Col_Plum ColorF (0.917647f, 0.678431f, 0.917647f) #define Col_Red ColorF (1.0f, 0.0f, 0.0f) #define Col_Salmon ColorF (0.435294f, 0.258824f, 0.258824f) #define Col_SeaGreen ColorF (0.137255f, 0.556863f, 0.419608f) #define Col_Sienna ColorF (0.556863f, 0.419608f, 0.137255f) #define Col_SkyBlue ColorF (0.196078f, 0.6f, 0.8f) #define Col_SlateBlue ColorF (0.0f, 0.498039f, 1.0f) #define Col_SpringGreen ColorF (0.0f, 1.0f, 0.498039f) #define Col_SteelBlue ColorF (0.137255f, 0.419608f, 0.556863f) #define Col_Tan ColorF (0.858824f, 0.576471f, 0.439216f) #define Col_Thistle ColorF (0.847059f, 0.74902f, 0.847059f) #define Col_Turquoise ColorF (0.678431f, 0.917647f, 0.917647f) #define Col_Violet ColorF (0.309804f, 0.184314f, 0.309804f) #define Col_VioletRed ColorF (0.8f, 0.196078f, 0.6f) #define Col_Wheat ColorF (0.847059f, 0.847059f, 0.74902f) #define Col_Yellow ColorF (1.0f, 1.0f, 0.0f) #define Col_YellowGreen ColorF (0.6f, 0.8f, 0.196078f) #endif // CRYTEK_CRYCOLOR_H
[ "[email protected]", "kkirst@c5e09591-5635-0410-80e3-0b71df3ecc31" ]
[ [ [ 1, 224 ], [ 227, 229 ], [ 232, 232 ], [ 235, 240 ], [ 243, 243 ], [ 245, 245 ], [ 250, 668 ], [ 674, 753 ] ], [ [ 225, 226 ], [ 230, 231 ], [ 233, 234 ], [ 241, 242 ], [ 244, 244 ], [ 246, 249 ], [ 669, 673 ] ] ]
815e53ea1d3a9f0a7c7ab0caf0dfa42a5931e553
061348a6be0e0e602d4a5b3e0af28e9eee2d257f
/Source/Base/Event/Producers/OSGEventProducerType.inl
b4b70e749cdbeb8b20cd238e9f70280be2a4c203
[]
no_license
passthefist/OpenSGToolbox
4a76b8e6b87245685619bdc3a0fa737e61a57291
d836853d6e0647628a7dd7bb7a729726750c6d28
refs/heads/master
2023-06-09T22:44:20.711657
2010-07-26T00:43:13
2010-07-26T00:43:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,254
inl
/*---------------------------------------------------------------------------*\ * OpenSG * * * * * * Copyright (C) 2000-2002,2002 by the OpenSG Forum * * * * www.opensg.org * * * * contact: [email protected], [email protected], [email protected] * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * License * * * * This library is free software; you can redistribute it and/or modify it * * under the terms of the GNU Library General Public License as published * * by the Free Software Foundation, version 2. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. * * * \*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*\ * Changes * * * * * * * * * * * * * \*---------------------------------------------------------------------------*/ #ifndef _OSGEVENTPRODUCERTYPE_INL_ #define _OSGEVENTPRODUCERTYPE_INL_ #include "OSGConfig.h" #include "OSGBaseDef.h" #include "OSGMethodDescription.h" OSG_BEGIN_NAMESPACE /*-------------------------------------------------------------------------*/ /* Get */ inline UInt16 EventProducerType::getGroupId (void) const { return _uiGroupId; } inline EventProducerType *EventProducerType::getParent(void) const { return _pParent; } inline MethodDescription *EventProducerType::getMethodDescription(UInt32 uiMethodId) { MethodDescription *foundDesc = NULL; MethodDescription *testDesc; DescVecIt it; for ( it=_vDescVec.begin() ; it < _vDescVec.end(); it++ ) { testDesc = *it; if(testDesc != NULL) { if(testDesc->getMethodId() == uiMethodId) { foundDesc = testDesc; } } } return foundDesc; } inline const MethodDescription *EventProducerType::getMethodDescription( UInt32 uiMethodId) const { MethodDescription *foundDesc = NULL; MethodDescription *testDesc; DescVecConstIt it; for ( it=_vDescVec.begin() ; it < _vDescVec.end(); it++ ) { testDesc = *it; if(testDesc != NULL) { if(testDesc->getMethodId() == uiMethodId) { foundDesc = testDesc; } } } return foundDesc; } inline MethodDescription *EventProducerType::findMethodDescription( const std::string &szMethodName) { DescMapIt descIt = _mDescMap.find(szMethodName); return (descIt == _mDescMap.end()) ? NULL : (*descIt).second; } inline const MethodDescription *EventProducerType::findMethodDescription( const std::string &szMethodName) const { DescMapConstIt descIt = _mDescMap.find(szMethodName); return (descIt == _mDescMap.end()) ? NULL : (*descIt).second; } inline UInt32 EventProducerType::getNumMethodDescs(void) const { return _vDescVec.size(); } /*-------------------------------------------------------------------------*/ /* Is */ inline bool EventProducerType::isInitialized(void) const { return _bInitialized; } inline bool EventProducerType::isDerivedFrom(const TypeBase &other) const { return Inherited::isDerivedFrom(other); } inline bool EventProducerType::isDerivedFrom(const EventProducerType &other) const { if(_uiTypeId == other._uiTypeId) { return true; } else { EventProducerType *pCurrType = _pParent; while(pCurrType != NULL) { if(other._uiTypeId == pCurrType->_uiTypeId) { return true; } pCurrType = pCurrType->_pParent; } } return false; } inline bool MethodDescriptionPLT::operator()(const MethodDescription *pElemDesc1, const MethodDescription *pElemDesc2) const { return pElemDesc1->getMethodId() < pElemDesc2->getMethodId(); } OSG_END_NAMESPACE #endif /* _OSGEVENTPRODUCERTYPE_INL_ */
[ [ [ 1, 41 ], [ 44, 105 ], [ 107, 107 ], [ 109, 114 ], [ 116, 116 ], [ 118, 176 ] ], [ [ 42, 43 ], [ 106, 106 ], [ 108, 108 ], [ 115, 115 ], [ 117, 117 ] ] ]
32be790eb8048a0ebd656f12429122b67e2cde37
709cd826da3ae55945fd7036ecf872ee7cdbd82a
/Term/Bowling/tags/Submittion2/LethalBowling/Collision.cpp
d9fbeec36d6f99e9b310307ff142a31e1cf5480d
[]
no_license
argapratama/kucgbowling
20dbaefe1596358156691e81ccceb9151b15efb0
65e40b6f33c5511bddf0fa350c1eefc647ace48a
refs/heads/master
2018-01-08T15:27:44.784437
2011-06-19T15:23:39
2011-06-19T15:23:39
36,738,655
0
0
null
null
null
null
UTF-8
C++
false
false
304
cpp
#include "Collision.h" namespace Virgin { //#define COLLISIONTOLERANCE 0.1f //#define PENETRATIONTOLERANCE 0.05f //#define CONTACTTOLERANCE 0.1f float Collision::CollisionTolerance = 0.1f; float Collision::PenetrationTolerance = 0.05f; float Collision::ContactTolerance = 0.1f; }
[ [ [ 1, 14 ] ] ]
ad8b0ecba370fdc1e09f4ca5e9bb68fd50888822
ed2f2f743085b3f9cc3ca820dbff620b783fc577
/testMalloc/stdafx.cpp
aa0b4e8123969d0563975bb1f74008ff6425dbe5
[]
no_license
littlewingsoft/test-sqlite-blob
ae7b745fe8bcc5aac57480e9132807545c31efc1
796359fcd34fee39eff999bc179bf3194ac6f847
refs/heads/master
2019-01-19T17:50:40.792433
2011-08-22T12:03:10
2011-08-22T12:03:10
32,302,166
0
0
null
null
null
null
UHC
C++
false
false
336
cpp
// stdafx.cpp : 표준 포함 파일만 들어 있는 소스 파일입니다. // testMalloc.pch는 미리 컴파일된 헤더가 됩니다. // stdafx.obj에는 미리 컴파일된 형식 정보가 포함됩니다. #include "stdafx.h" // TODO: 필요한 추가 헤더는 // 이 파일이 아닌 STDAFX.H에서 참조합니다.
[ "jungmoona@e98d6a08-3d45-9aa4-e100-60898896f941" ]
[ [ [ 1, 8 ] ] ]
9c57f5e445c5b7c8e3bba207fa02d6cd8e99f251
27c6eed99799f8398fe4c30df2088f30ae317aff
/rtt-tool/qdoc3/codeparser.cpp
0b2b639886c3c39d1453ef35bb79d679b7325809
[]
no_license
lit-uriy/ysoft
ae67cd174861e610f7e1519236e94ffb4d350249
6c3f077ff00c8332b162b4e82229879475fc8f97
refs/heads/master
2021-01-10T08:16:45.115964
2009-07-16T00:27:01
2009-07-16T00:27:01
51,699,806
0
0
null
null
null
null
UTF-8
C++
false
false
8,258
cpp
/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information ([email protected]) ** ** This file is part of the tools applications of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at [email protected]. ** $QT_END_LICENSE$ ** ****************************************************************************/ /* codeparser.cpp */ #include <QtCore> #include "codeparser.h" #include "node.h" #include "tree.h" QT_BEGIN_NAMESPACE #define COMMAND_COMPAT Doc::alias(QLatin1String("compat")) #define COMMAND_DEPRECATED Doc::alias(QLatin1String("deprecated")) // ### don't document #define COMMAND_INGROUP Doc::alias(QLatin1String("ingroup")) #define COMMAND_INMODULE Doc::alias(QLatin1String("inmodule")) // ### don't document #define COMMAND_INTERNAL Doc::alias(QLatin1String("internal")) #define COMMAND_MAINCLASS Doc::alias(QLatin1String("mainclass")) #define COMMAND_NONREENTRANT Doc::alias(QLatin1String("nonreentrant")) #define COMMAND_OBSOLETE Doc::alias(QLatin1String("obsolete")) #define COMMAND_PRELIMINARY Doc::alias(QLatin1String("preliminary")) #define COMMAND_INPUBLICGROUP Doc::alias(QLatin1String("inpublicgroup")) #define COMMAND_REENTRANT Doc::alias(QLatin1String("reentrant")) #define COMMAND_SINCE Doc::alias(QLatin1String("since")) #define COMMAND_SUBTITLE Doc::alias(QLatin1String("subtitle")) #define COMMAND_THREADSAFE Doc::alias(QLatin1String("threadsafe")) #define COMMAND_TITLE Doc::alias(QLatin1String("title")) QList<CodeParser *> CodeParser::parsers; CodeParser::CodeParser() { parsers.prepend( this ); } CodeParser::~CodeParser() { parsers.removeAll( this ); } void CodeParser::initializeParser(const Config & /* config */) { } void CodeParser::terminateParser() { } QString CodeParser::headerFileNameFilter() { return sourceFileNameFilter(); } void CodeParser::parseHeaderFile( const Location& location, const QString& filePath, Tree *tree ) { parseSourceFile( location, filePath, tree ); } void CodeParser::doneParsingHeaderFiles( Tree *tree ) { doneParsingSourceFiles( tree ); } void CodeParser::initialize( const Config& config ) { QList<CodeParser *>::ConstIterator p = parsers.begin(); while ( p != parsers.end() ) { (*p)->initializeParser( config ); ++p; } } void CodeParser::terminate() { QList<CodeParser *>::ConstIterator p = parsers.begin(); while ( p != parsers.end() ) { (*p)->terminateParser(); ++p; } } CodeParser *CodeParser::parserForLanguage( const QString& language ) { QList<CodeParser *>::ConstIterator p = parsers.begin(); while ( p != parsers.end() ) { if ( (*p)->language() == language ) return *p; ++p; } return 0; } /*! Returns the set of strings representing the common metacommands. */ QSet<QString> CodeParser::commonMetaCommands() { return QSet<QString>() << COMMAND_COMPAT << COMMAND_DEPRECATED << COMMAND_INGROUP << COMMAND_INMODULE << COMMAND_INTERNAL << COMMAND_MAINCLASS << COMMAND_NONREENTRANT << COMMAND_OBSOLETE << COMMAND_PRELIMINARY << COMMAND_INPUBLICGROUP << COMMAND_REENTRANT << COMMAND_SINCE << COMMAND_SUBTITLE << COMMAND_THREADSAFE << COMMAND_TITLE; } void CodeParser::processCommonMetaCommand(const Location &location, const QString &command, const QString &arg, Node *node, Tree *tree) { if (command == COMMAND_COMPAT) { node->setStatus(Node::Compat); } else if ( command == COMMAND_DEPRECATED ) { node->setStatus( Node::Deprecated ); } else if ( command == COMMAND_INGROUP ) { tree->addToGroup(node, arg); } else if ( command == COMMAND_INPUBLICGROUP ) { tree->addToPublicGroup(node, arg); } else if ( command == COMMAND_INMODULE ) { node->setModuleName(arg); } else if (command == COMMAND_MAINCLASS) { node->setStatus(Node::Main); } else if ( command == COMMAND_OBSOLETE ) { if (node->status() != Node::Compat) node->setStatus( Node::Obsolete ); } else if ( command == COMMAND_NONREENTRANT ) { node->setThreadSafeness(Node::NonReentrant); } else if ( command == COMMAND_PRELIMINARY ) { node->setStatus( Node::Preliminary ); } else if (command == COMMAND_INTERNAL) { node->setAccess( Node::Private ); node->setStatus( Node::Internal ); } else if (command == COMMAND_REENTRANT) { node->setThreadSafeness(Node::Reentrant); } else if (command == COMMAND_SINCE) { node->setSince(arg); } else if (command == COMMAND_SUBTITLE) { if (node->type() == Node::Fake) { FakeNode *fake = static_cast<FakeNode *>(node); fake->setSubTitle(arg); } else location.warning(tr("Ignored '\\%1'").arg(COMMAND_SUBTITLE)); } else if (command == COMMAND_THREADSAFE) { node->setThreadSafeness(Node::ThreadSafe); } else if (command == COMMAND_TITLE) { if (node->type() == Node::Fake) { FakeNode *fake = static_cast<FakeNode *>(node); fake->setTitle(arg); /* qdoc -> doxygen. I think this must be done here, because there can be multiple "\externalpage" and "\title" metacommands in a single qdoc comment, which means, among other things, that the "\title" commands are not inserted into the metacommand map used by the Doc class. I'm sure there4 is a better way to do this in the DoxWriter class using the information in the FakeNode, but I don't have time to figure it out right now. */ if (DoxWriter::isDoxPass(1)) DoxWriter::insertTitle(fake,arg); } else location.warning(tr("Ignored '\\%1'").arg(COMMAND_TITLE)); } } QT_END_NAMESPACE
[ "lit-uriy@d7ba3245-3e7b-42d0-9cd4-356c8b94b330" ]
[ [ [ 1, 220 ] ] ]
6ac35753805001b3c23cdc97044e2fbcddc310a3
2c428e38d9b50e8484fc56f62e3c9f3c083b39fa
/COMP 201/Project2/mapfile.cc
1a98aeb776fef373af38604bf0378f4e53e01e0a
[]
no_license
daveharris/uni-work
9b0a75ad13e6cf5bf6dad586945bb00e2b9ab737
669a96db775c809106c02e9e2973761a884b618f
refs/heads/master
2016-09-06T19:51:25.773023
2011-02-03T02:10:02
2011-02-03T02:10:02
1,252,689
1
0
null
null
null
null
UTF-8
C++
false
false
5,483
cc
#include <iostream> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <stdio.h> #include "mapfile.h" #include "book.h" #include "bucket.h" using namespace std; Mapfile::Mapfile(int numBuckets) { this->numBuckets = numBuckets; for(int i=0; i<numBuckets; i++) { Bucket bucket; write(fd, &bucket, sizeof(bucket)); } } int Mapfile::openFile(char *filename) { int openretval = open(filename, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); fd = openretval; return (openretval >= 0); } int Mapfile::closeFile() { int closeretval = close(fd); return (closeretval >= 0); } int Mapfile::insert(Book& book) { Bucket bucket; Bucket bucketNext; ssize_t numbytes; int insertretval; off_t seekval; ssize_t readretval; int hash = hashFunction(book.getId(), numBuckets); //cout << "hash: " << hash << endl; seekval = lseek(fd, hash*512, SEEK_SET); if (seekval < 0) cout << "get initial seek bad!\n" << endl; readretval = read(fd, &bucket, sizeof(bucket)); insertretval = bucket.insert(book); if(insertretval == 1) { seekval = lseek(fd, hash*512, SEEK_SET); numbytes = write(fd, &bucket, sizeof(bucket)); return 1; } if(insertretval == -3) { //Book is already in bucket, say so and return cout << "Book "<< book.getId() << " is already in the map!! Book not added" << endl; return -1; } //Not in current bucket, so seek to the next one int i = 1; ssize_t readval; int insertval; int findval; while(i < numBuckets) { readval = read(fd, &bucketNext, sizeof(bucketNext)); findval = bucketNext.find(book.getId()); if(findval == -1) { insertval = bucketNext.insert(book); if(insertval != -2) { //write to the file seekval = lseek(fd, (i*512)+(hash*512), SEEK_SET); numbytes = write(fd, &bucketNext, sizeof(bucketNext)); if (!numbytes >= 0) { cout << "Write failed.\n"; return 0; } return 1; } } i++; } } int Mapfile::retrieve(Book* book, char* bookId) { Bucket bucket; Bucket bucketNext; int findretval; ssize_t readretval; off_t seekretval; int hash = hashFunction(bookId, numBuckets); seekretval = lseek(fd, hash*512, SEEK_SET); if (seekretval < 0) cout << "Retrieve initial seek bad!\n" << endl; readretval = read(fd, &bucket, sizeof(bucket)); if (readretval != sizeof(bucket)) { cout << "First read not successful" << endl; return -1; } findretval = bucket.find(bookId); if(findretval != -1) { //Book is in current bucket book = &(bucket.returnBook(findretval)); } else { //Not in current bucket, so seek to the next one int i = 1; ssize_t readval; int findval; while(i < numBuckets) { readval = read(fd, &bucketNext, sizeof(bucket)); if (readretval != sizeof(bucket)) { cout << "Sucessive read not successful" << endl; return -1; } findval = bucketNext.find(bookId); if(findval != -1) { //In this bucket, so return book at findval book = &(bucketNext.returnBook(findval)); } i++; } } } int Mapfile::remove(char* bookId){ Bucket bucket; Bucket bucketNext; ssize_t numbytes; int removeretval; off_t seekval; ssize_t readretval; int hash = hashFunction(bookId, numBuckets); //cout << "hash: " << hash << endl; seekval = lseek(fd, hash*512, SEEK_SET); if (seekval < 0) cout << "get initial seek bad!\n" << endl; readretval = read(fd, &bucket, sizeof(bucket)); removeretval = bucket.remove(bookId); if(removeretval == 1) { seekval = lseek(fd, hash*512, SEEK_SET); numbytes = write(fd, &bucket, sizeof(bucket)); return 1; } //Not in current bucket, so seek to the next one int i = 1; ssize_t readval; int removeval; int findval; while(i < numBuckets) { readval = read(fd, &bucketNext, sizeof(bucket)); findval = bucketNext.find(bookId); if(findval != -1) { removeval = bucketNext.remove(bookId); if(removeval != -1) { //write to the file seekval = lseek(fd, (i*512)+(hash*512), SEEK_SET); numbytes = write(fd, &bucketNext, sizeof(bucketNext)); if (!numbytes >= 0) { cout << "Write failed.\n"; return 0; } } } i++; } } void Mapfile::print() { Bucket bucket; int hash; int num; ssize_t readretval; off_t seekval; for(int i=0; i<numBuckets; i++) { seekval = lseek(fd, i*512, SEEK_SET); readretval = read(fd, &bucket, sizeof(bucket)); cout << "Bucket " << i << endl; for(int i=0; i<7; i++) { if(readretval == 512) { cout << "Position: " << i << " Id: "<< bucket.getId(i) << endl; } else { cout << "Position: " << i << " Id: "<< endl; } } } } /* seekval = lseek(fd, 0, SEEK_SET); if (seekval < 0) cout <<"Panic: seek fail in list!" << endl; num = 0; while (1) { readretval = read(fd, &a, sizeof(b)); if (readretval != sizeof(b)) break; hash = b.getId(); cout << "Account ID: " << id << "\n"; num++; } cout << "Number of accounts: " << num << "\n\n"; } */ int Mapfile::hashFunction(char key[7], int maxAddress) { int sum = 0; for(int i = 0; i < 7; i+=2) sum = (sum + 100 * key[i] + key[i+1]) % 19937; return (sum % maxAddress); }
[ [ [ 1, 258 ] ] ]
2b749032d67eb5664a7cfe4037b5026bd0097c7e
fd3f2268460656e395652b11ae1a5b358bfe0a59
/srchybrid/emule.h
f961ee96387e5c53df3cd26fddc25f135cb50e6c
[]
no_license
mikezhoubill/emule-gifc
e1cc6ff8b1bb63197bcfc7e67c57cfce0538ff60
46979cf32a313ad6d58603b275ec0b2150562166
refs/heads/master
2021-01-10T20:37:07.581465
2011-08-13T13:58:37
2011-08-13T13:58:37
32,465,033
4
2
null
null
null
null
UTF-8
C++
false
false
14,285
h
//this file is part of eMule //Copyright (C)2002-2008 Merkur ( strEmail.Format("%s@%s", "devteam", "emule-project.net") / http://www.emule-project.net ) // //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., 675 Mass Ave, Cambridge, MA 02139, USA. #pragma once #ifndef __AFXWIN_H__ #error include 'stdafx.h' before including this file for PCH #endif #include "resource.h" //Xman #include "ReadWriteLock.h" // SLUGFILLER: SafeHash #include "Version.h" // netfinity: Mod version // ==> UPnP support [MoNKi] - leuk_he /* #ifdef DUAL_UPNP //zz_fly :: dual upnp #include "UPnP_acat.h" //ACAT UPnP #endif //zz_fly :: dual upnp */ #include "UPnP_IGDControlPoint.h" //[MoNKi: -UPnPNAT Support-] // <== UPnP support [MoNKi] - leuk_he #include ".\MiniMule\SystemInfo.h" // CPU/MEM usage [$ick$/Stulle] - Max #include ".\MiniMule\TBHMM.h" // TBH: minimule - Max #define DEFAULT_NICK _T("ScarAngel @ http://scarangel.sourceforge.net") #define DEFAULT_TCP_PORT_OLD 4662 #define DEFAULT_UDP_PORT_OLD (DEFAULT_TCP_PORT_OLD+10) #define PORTTESTURL _T("http://porttest.emule-project.net/connectiontest.php?tcpport=%i&udpport=%i&lang=%i") class CSearchList; class CUploadQueue; class CListenSocket; class CDownloadQueue; class CScheduler; class UploadBandwidthThrottler; //Xman /* class LastCommonRouteFinder; */ //Xman end class CemuleDlg; class CClientList; class CKnownFileList; class CServerConnect; class CServerList; class CSharedFileList; class CClientCreditsList; class CFriendList; class CClientUDPSocket; class CIPFilter; class CWebServer; class CMMServer; class CAbstractFile; class CUpDownClient; class CPeerCacheFinder; class CFirewallOpener; // ==> UPnP support [MoNKi] - leuk_he /* class CUPnPImplWrapper; */ // <== UPnP support [MoNKi] - leuk_he //Xman class CBandWidthControl; // Maella -Accurate measure of bandwidth: eDonkey data + control, network adapter- struct SLogItem; class CIP2Country; //EastShare - added by AndCycle, IP to Country class CDLP; //Xman DLP class CSplashScreenEx; //Xman new slpash-screen arrangement class CSystemInfo; // CPU/MEM usage [$ick$/Stulle] - Max enum AppState{ APP_STATE_RUNNING = 0, APP_STATE_SHUTTINGDOWN, APP_STATE_DONE }; class CemuleApp : public CWinApp { friend class CTBHMM; // TBH: minimule - Max public: CemuleApp(LPCTSTR lpszAppName = NULL); // ZZ:UploadSpeedSense --> UploadBandwidthThrottler* uploadBandwidthThrottler; //Xman /* LastCommonRouteFinder* lastCommonRouteFinder; */ //Xman end // ZZ:UploadSpeedSense <-- CemuleDlg* emuledlg; CClientList* clientlist; CKnownFileList* knownfiles; CServerConnect* serverconnect; CServerList* serverlist; CSharedFileList* sharedfiles; CSearchList* searchlist; CListenSocket* listensocket; CUploadQueue* uploadqueue; CDownloadQueue* downloadqueue; CClientCreditsList* clientcredits; CFriendList* friendlist; CClientUDPSocket* clientudp; CIPFilter* ipfilter; CWebServer* webserver; CScheduler* scheduler; CMMServer* mmserver; CPeerCacheFinder* m_pPeerCache; CFirewallOpener* m_pFirewallOpener; // ==> UPnP support [MoNKi] - leuk_he /* CUPnPImplWrapper* m_pUPnPFinder; */ // <== UPnP support [MoNKi] - leuk_he //Xman // - Maella -Accurate measure of bandwidth: eDonkey data + control, network adapter- CBandWidthControl* pBandWidthControl; // Maella end CSplashScreenEx* m_pSplashWnd; //Xman new slpash-screen arrangement //Xman dynamic IP-Filters bool ipdlgisopen; CIP2Country* ip2country; //EastShare - added by AndCycle, IP to Country CDLP* dlp; //Xman end // ==> TBH: minimule - Max/ leuk_he CTBHMM* minimule; // <== TBH: minimule - Max/ leuk_he CSystemInfo* sysinfo; // CPU/MEM usage [$ick$/Stulle] - Max HANDLE m_hMutexOneInstance; int m_iDfltImageListColorFlags; CFont m_fontHyperText; CFont m_fontDefaultBold; CFont m_fontSymbol; CFont m_fontLog; CFont m_fontChatEdit; CBrush m_brushBackwardDiagonal; static const UINT m_nVersionMjr; static const UINT m_nVersionMin; static const UINT m_nVersionUpd; static const UINT m_nVersionBld; DWORD m_dwProductVersionMS; DWORD m_dwProductVersionLS; CString m_strCurVersionLong; CString m_strCurVersionLongDbg; UINT m_uCurVersionShort; UINT m_uCurVersionCheck; ULONGLONG m_ullComCtrlVer; //MORPH /* AppState m_app_state; // defines application state for shutdown */ volatile AppState m_app_state; // defines application state for shutdown //MORPH END CMutex hashing_mut; //Xman CReadWriteLock m_threadlock; // SLUGFILLER: SafeHash - This will ensure eMule goes last CString* pstrPendingLink; COPYDATASTRUCT sendstruct; // Implementierung virtual BOOL InitInstance(); virtual int ExitInstance(); virtual BOOL IsIdleMessage(MSG *pMsg); // ed2k link functions //Xman [MoNKi: -Check already downloaded files-] /* void AddEd2kLinksToDownload(CString strLinks, int cat); */ // ==> Smart Category Control (SCC) [khaos/SiRoB/Stulle] - Stulle /* void AddEd2kLinksToDownload(CString strLinks, int cat, bool askIfAlreadyDownloaded = false); */ void AddEd2kLinksToDownload(CString strLinks, int cat, bool fromclipboard=false, bool askIfAlreadyDownloaded = false); // <== Smart Category Control (SCC) [khaos/SiRoB/Stulle] - Stulle //Xman end //Xman new slpash-screen arrangement void ShowSplash(bool start=false); void UpdateSplash(LPCTSTR Text); void DestroySplash(); bool IsSplash() { return (m_pSplashWnd != NULL); } bool spashscreenfinished; uint32 m_dwSplashTime; //Xman end void SearchClipboard(); void IgnoreClipboardLinks(CString strLinks) {m_strLastClipboardContents = strLinks;} // ==> Smart Category Control (SCC) [khaos/SiRoB/Stulle] - Stulle /* void PasteClipboard(int cat = 0); */ void PasteClipboard(int cat = -1); // <== Smart Category Control (SCC) [khaos/SiRoB/Stulle] - Stulle bool IsEd2kFileLinkInClipboard(); bool IsEd2kServerLinkInClipboard(); bool IsEd2kLinkInClipboard(LPCSTR pszLinkType, int iLinkTypeLen); LPCTSTR GetProfileFile() { return m_pszProfileName; } CString CreateKadSourceLink(const CAbstractFile* f); // clipboard (text) bool CopyTextToClipboard(CString strText); CString CopyTextFromClipboard(); void OnlineSig(); void UpdateReceivedBytes(uint32 bytesToAdd); void UpdateSentBytes(uint32 bytesToAdd, bool sentToFriend = false); int GetFileTypeSystemImageIdx(LPCTSTR pszFilePath, int iLength = -1, bool bNormalsSize = false); HIMAGELIST GetSystemImageList() { return m_hSystemImageList; } HIMAGELIST GetBigSystemImageList() { return m_hBigSystemImageList; } CSize GetSmallSytemIconSize() { return m_sizSmallSystemIcon; } CSize GetBigSytemIconSize() { return m_sizBigSystemIcon; } void CreateBackwardDiagonalBrush(); void CreateAllFonts(); const CString &GetDefaultFontFaceName(); bool IsPortchangeAllowed(); bool IsConnected(bool bIgnoreEd2k = false, bool bIgnoreKad = false); bool IsFirewalled(); bool CanDoCallback( CUpDownClient *client ); uint32 GetID(); uint32 GetPublicIP(bool bIgnoreKadIP = false) const; // return current (valid) public IP or 0 if unknown void SetPublicIP(const uint32 dwIP); void ResetStandByIdleTimer(); // because nearly all icons we are loading are 16x16, the default size is specified as 16 and not as 32 nor LR_DEFAULTSIZE HICON LoadIcon(LPCTSTR lpszResourceName, int cx = 16, int cy = 16, UINT uFlags = LR_DEFAULTCOLOR) const; HICON LoadIcon(UINT nIDResource) const; HBITMAP LoadImage(LPCTSTR lpszResourceName, LPCTSTR pszResourceType) const; HBITMAP LoadImage(UINT nIDResource, LPCTSTR pszResourceType) const; bool LoadSkinColor(LPCTSTR pszKey, COLORREF& crColor) const; bool LoadSkinColorAlt(LPCTSTR pszKey, LPCTSTR pszAlternateKey, COLORREF& crColor) const; CString GetSkinFileItem(LPCTSTR lpszResourceName, LPCTSTR pszResourceType) const; void ApplySkin(LPCTSTR pszSkinProfile); void EnableRTLWindowsLayout(); void DisableRTLWindowsLayout(); void UpdateDesktopColorDepth(); void UpdateLargeIconSize(); bool IsXPThemeActive() const; bool IsVistaThemeActive() const; bool GetLangHelpFilePath(CString& strResult); void SetHelpFilePath(LPCTSTR pszHelpFilePath); void ShowHelp(UINT uTopic, UINT uCmd = HELP_CONTEXT); bool ShowWebHelp(UINT uTopic); // Elandal:ThreadSafeLogging --> // thread safe log calls void QueueDebugLogLine(bool bAddToStatusBar, LPCTSTR line,...); void QueueDebugLogLineEx(UINT uFlags, LPCTSTR line,...); void HandleDebugLogQueue(); void ClearDebugLogQueue(bool bDebugPendingMsgs = false); void QueueLogLine(bool bAddToStatusBar, LPCTSTR line,...); void QueueLogLineEx(UINT uFlags, LPCTSTR line,...); void HandleLogQueue(); void ClearLogQueue(bool bDebugPendingMsgs = false); // Elandal:ThreadSafeLogging <-- bool DidWeAutoStart() { return m_bAutoStart; } WSADATA m_wsaData; //eWombat [WINSOCK2] protected: bool ProcessCommandline(); void SetTimeOnTransfer(); static BOOL CALLBACK SearchEmuleWindow(HWND hWnd, LPARAM lParam); DECLARE_MESSAGE_MAP() afx_msg void OnHelp(); HIMAGELIST m_hSystemImageList; CMapStringToPtr m_aExtToSysImgIdx; CSize m_sizSmallSystemIcon; HIMAGELIST m_hBigSystemImageList; CMapStringToPtr m_aBigExtToSysImgIdx; CSize m_sizBigSystemIcon; CString m_strDefaultFontFaceName; bool m_bGuardClipboardPrompt; CString m_strLastClipboardContents; // Elandal:ThreadSafeLogging --> // thread safe log calls CCriticalSection m_queueLock; CTypedPtrList<CPtrList, SLogItem*> m_QueueDebugLog; CTypedPtrList<CPtrList, SLogItem*> m_QueueLog; // Elandal:ThreadSafeLogging <-- uint32 m_dwPublicIP; bool m_bAutoStart; private: UINT m_wTimerRes; //Xman -Reask sources after IP change- v4 public: bool m_bneedpublicIP; uint32 last_ip_change; uint32 last_valid_serverid; uint32 last_valid_ip; uint32 recheck_ip; uint32 last_traffic_reception; uint8 internetmaybedown; //Xman end // ==> UPnP support [MoNKi] - leuk_he /* #ifdef DUAL_UPNP //zz_fly :: dual upnp //ACAT UPnP public: MyUPnP* m_pUPnPNat; BOOL AddUPnPNatPort(MyUPnP::UPNPNAT_MAPPING *mapping, bool tryRandom = false); BOOL RemoveUPnPNatPort(MyUPnP::UPNPNAT_MAPPING *mapping); #endif //zz_fly :: dual upnp */ CUPnP_IGDControlPoint *m_UPnP_IGDControlPoint; // <== UPnP support [MoNKi] - leuk_he //Xman queued disc-access for read/flushing-threads /* zz_fly :: drop, use Morph's synchronization method instead. note: this feature can reduce the diskio. but it is hard to synchronize the threads. when synchronization failed, emule will crash. i can not let this feature work properly in .50 codebase. so, my only choice is drop this feature. void AddNewDiscAccessThread(CWinThread* threadtoadd); void ResumeNextDiscAccessThread(); void ForeAllDiscAccessThreadsToFinish(); private: CTypedPtrList<CPtrList, CWinThread*> threadqueue; CCriticalSection threadqueuelock; volatile uint16 m_uRunningNonBlockedDiscAccessThreads; */ //Xman end // MORPH START - Added by Commander, Friendlinks [emulEspaa] - added by zz_fly public: bool IsEd2kFriendLinkInClipboard(); // MORPH END - Added by Commander, Friendlinks [emulEspaa] // ==> ModID [itsonlyme/SiRoB] - Stulle public: static const UINT m_nMVersionMjr; static const UINT m_nMVersionMin; static const UINT m_nMVersionBld; static const TCHAR m_szMVersionLong[]; static const TCHAR m_szMVersion[]; CString m_strModVersion; CString m_strModLongVersion; CString m_strModVersionPure; uint8 m_uModLength; // <== ModID [itsonlyme/SiRoB] - Stulle // ==> Design Settings [eWombat/Stulle] - Stulle void CreateExtraFonts(CFont *font); void DestroyExtraFonts(); CFont *GetFontByStyle(DWORD nStyle,bool bNarrow); protected: CFont m_ExtraFonts[15]; // <== Design Settings [eWombat/Stulle] - Stulle // ==> Automatic shared files updater [MoNKi] - Stulle private: static CEvent* m_directoryWatcherCloseEvent; static CEvent* m_directoryWatcherReloadEvent; static CCriticalSection m_directoryWatcherCS; static UINT CheckDirectoryForChangesThread(LPVOID pParam); public: void ResetDirectoryWatcher(); void EndDirectoryWatcher(); void DirectoryWatcherExternalReload(); // <== Automatic shared files updater [MoNKi] - Stulle void RebindUPnP(); // UPnP support [MoNKi] - leuk_he // ==> Run eMule as NT Service [leuk_he/Stulle] - Stulle #define SVC_NO_OPT 0 #define SVC_BASIC_OPT 2 #define SVC_GUI_OPT 4 #define SVC_LIST_OPT 6 #define SVC_FULL_OPT 10 bool IsRunningAsService(int OptimizeLevel = SVC_BASIC_OPT ); // <== Run eMule as NT Service [leuk_he/Stulle] - Stulle }; extern CemuleApp theApp; ////////////////////////////////////////////////////////////////////////////// // CTempIconLoader class CTempIconLoader { public: // because nearly all icons we are loading are 16x16, the default size is specified as 16 and not as 32 nor LR_DEFAULTSIZE CTempIconLoader(LPCTSTR pszResourceID, int cx = 16, int cy = 16, UINT uFlags = LR_DEFAULTCOLOR); CTempIconLoader(UINT uResourceID, int cx = 16, int cy = 16, UINT uFlags = LR_DEFAULTCOLOR); ~CTempIconLoader(); operator HICON() const{ return this == NULL ? NULL : m_hIcon; } protected: HICON m_hIcon; };
[ "Mike.Ken.S@dd569cc8-ff36-11de-bbca-1111db1fd05b", "[email protected]@dd569cc8-ff36-11de-bbca-1111db1fd05b" ]
[ [ [ 1, 26 ], [ 32, 196 ], [ 199, 199 ], [ 203, 244 ], [ 246, 334 ], [ 344, 347 ], [ 353, 358 ], [ 361, 404 ], [ 410, 433 ] ], [ [ 27, 31 ], [ 197, 198 ], [ 200, 202 ], [ 245, 245 ], [ 335, 343 ], [ 348, 352 ], [ 359, 360 ], [ 405, 409 ] ] ]
033c84536456633cf84481a6faa778207a478e6f
ea12fed4c32e9c7992956419eb3e2bace91f063a
/zombie/code/nebula2/src/anim2/nanimstatearray.cc
291244b5322f5fc9241008edae2fb524da4e6ee5
[]
no_license
ugozapad/TheZombieEngine
832492930df28c28cd349673f79f3609b1fe7190
8e8c3e6225c2ed93e07287356def9fbdeacf3d6a
refs/heads/master
2020-04-30T11:35:36.258363
2011-02-24T14:18:43
2011-02-24T14:18:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,062
cc
#include "precompiled/pchnnebula.h" //------------------------------------------------------------------------------ // nanimstatearray.cc // (C) 2005 Conjurer Services, S.A. //------------------------------------------------------------------------------ #include "anim2/nanimstatearray.h" //------------------------------------------------------------------------------ #ifndef __ZOMBIE_EXPORTER__ static int __cdecl n_AnimStateArraySort(const void * a, const void * b) { if (a && b) { const nAnimState * animA = static_cast<const nAnimState*>(a); const nAnimState * animB = static_cast<const nAnimState*>(b); return (strcmp(animA->GetAnimFile(), animB->GetAnimFile())); } return 0; } #endif //------------------------------------------------------------------------------ /** */ void nAnimStateArray::End() { #ifndef __ZOMBIE_EXPORTER__ this->stateArray.QSort(n_AnimStateArraySort); #endif } //------------------------------------------------------------------------------
[ "magarcias@c1fa4281-9647-0410-8f2c-f027dd5e0a91" ]
[ [ [ 1, 36 ] ] ]
d2ffd0570f88c3c6e0d4f1d96ff53b9b2bd1361b
b6c9433cefda8cfe76c8cb6550bf92dde38e68a8
/epoc32/include/test/rfilelogger.h
a65cd112e6c96c044268beb78aa896b6a0a2d6e2
[]
no_license
fedor4ever/public-headers
667f8b9d0dc70aa3d52d553fd4cbd5b0a532835f
3666a83565a8de1b070f5ac0b22cc0cbd59117a4
refs/heads/master
2021-01-01T05:51:44.592006
2010-03-31T11:33:34
2010-03-31T11:33:34
33,378,397
0
0
null
null
null
null
UTF-8
C++
false
false
4,305
h
/* * Copyright (c) 2005-2009 Nokia Corporation and/or its subsidiary(-ies). * All rights reserved. * This component and the accompanying materials are made available * under the terms of the License "Symbian Foundation License v1.0" to Symbian Foundation members and "Symbian Foundation End User License Agreement v1.0" to non-members * which accompanies this distribution, and is available * at the URL "http://www.symbianfoundation.org/legal/licencesv10.html". * * Initial Contributors: * Nokia Corporation - initial contribution. * * Contributors: * * Description: * */ /** @file RFileLogger.h */ #if !(defined __ET_RFILELOGGER_H__) #define __ET_RFILELOGGER_H__ #include <e32base.h> const TInt KMaxSizOfTag=128; const TInt KMaxSizOfString = 256; const TInt KMaxFilename = 50; // *** Maintaince warning: the constant designed // used on both server side and client side. Any change shoud be // checked on both side _LIT(KMessageFormat," - %d - %S - %d - "); _LIT(KSeperation," - "); _LIT8(KSeperation8," - "); _LIT(KTagSeperation,"LogFieldsRequiredBeingAddedToAboveLogMessage"); _LIT(KTagSeperationEnd,"\t\t\t\t\t\t"); // make them invisible _LIT(KTagSeperation8,"LogFieldsRequiredBeingAddedToAboveLogMessage"); _LIT(KTagSeperationEnd8,"\t\t\t\t\t\t"); // make them invisible // *** End of Maintaince warning //#if !(defined __FILELOGGER_UREL) _LIT(KFileLogrerServerName,"RFileLoggerServer"); const TInt KMaxLoggerFilePath = 256; const TInt KMaxLoggerLineLength = 512; const TInt KRFileLoggerMajorVersion = 1; const TInt KRFileLoggerMinorVersion = 1; const TInt KRFileLoggerBuildVersion = 1; struct TExtraLogField { TBuf<KMaxSizOfTag> iLogFieldName; TBuf<KMaxSizOfString> iLogFieldValue; }; /** * RFileLoggerBody - class to provide internal data for the client side * * This class contains all data members which would otherwise be in the * RFileLogger class. They are instead in this file since that because * CreateSession is a protected member of RSessionBase, so we must derive *from it and provide a means to call this via pass-through inline functions. */ class RFileLoggerBody : public RSessionBase { public: inline TInt DoCreateSession(const TDesC& aServer,const TVersion& aVersion,TInt aAsyncMessageSlots); inline TInt DoSendReceive(TInt aFunction,const TIpcArgs& aArgs) const; inline TInt DoSendReceive(TInt aFunction) const; }; inline TInt RFileLoggerBody::DoCreateSession(const TDesC& aServer,const TVersion& aVersion,TInt aAsyncMessageSlots) { return CreateSession(aServer,aVersion,aAsyncMessageSlots); } inline TInt RFileLoggerBody::DoSendReceive(TInt aFunction,const TIpcArgs& aArgs) const { return SendReceive(aFunction,aArgs); } inline TInt RFileLoggerBody::DoSendReceive(TInt aFunction) const { return SendReceive(aFunction); } class RFileFlogger /** @internalComponent @test */ { public: enum TLogMode{ELogModeAppend,ELogModeOverWrite}; // Logging level enum TLogSeverity{ESevrErr = 1,ESevrHigh, ESevrWarn, ESevrMedium, ESevrInfo, ESevrLow, ESevrTEFUnit, ESevrAll}; enum TLogCommand{ECreateLog,EWriteLog}; enum TLogType{EXml,ETxt}; IMPORT_C RFileFlogger(); IMPORT_C ~RFileFlogger(); IMPORT_C TInt Connect(); IMPORT_C TInt CreateLog(const TDesC& aLogFilePath,TLogMode aMode); IMPORT_C void Log(const TText8* aFile, TInt aLine, TLogSeverity aSeverity, TRefByValue<const TDesC> aFmt,...); IMPORT_C void Log(const TText8* aFile, TInt aLine, TLogSeverity aSeverity, TInt arraylength, TExtraLogField* aLogFields, TRefByValue<const TDesC> aFmt,...); IMPORT_C void SetLogLevel(TLogSeverity aloglevel); IMPORT_C void Close(); IMPORT_C void Log(const TText8* aFile, TInt aLine, TLogSeverity aSeverity,TRefByValue<const TDesC> aFmt, VA_LIST aList); IMPORT_C void Log(const TText8* aFile, TInt aLine, TLogSeverity aSeverity, TInt arraylength, TExtraLogField* aLogFields, TRefByValue<const TDesC> aFmt, VA_LIST aList); private: void GetCPPModuleName(TDes& aModuleName, const TText8* aCPPFileName); void WriteL(const TDesC& aLogBuffer); void WriteL(TDes8& aLogBuffer); void AddTime(TDes8& aTime); RFileLoggerBody* ilogbody; TLogSeverity iloglevel; TBool iLogfileTag; }; #endif
[ [ [ 1, 136 ] ] ]
045f1f1312840265184d2adc3e53c63755f2d213
563e71cceb33a518f53326838a595c0f23d9b8f3
/v2/POC/POC/Node.h
253fbb48ca8544bb5cab6b71556fc92f4f67beb3
[]
no_license
fabio-miranda/procedural
3d937037d63dd16cd6d9e68fe17efde0688b5a0a
e2f4b9d34baa1315e258613fb0ea66d1235a63f0
refs/heads/master
2021-05-28T18:13:57.833985
2009-10-07T21:09:13
2009-10-07T21:09:13
39,636,279
1
1
null
null
null
null
UTF-8
C++
false
false
311
h
#ifndef NODE_H #define NODE_H #include <list> using namespace::std; #include "Vector3.h" class Node{ public: list<Node*> m_children; list<Node*>::iterator m_iterator; Vector3<float> m_position; public: Node(); virtual void Render(); virtual void AddNode(Node*); }; #endif
[ "fabiom@01b71de8-32d4-11de-96ab-f16d9912eac9" ]
[ [ [ 1, 25 ] ] ]
bf0910514d1ca1c4eea19d329ee7c37bd51586ff
0f40e36dc65b58cc3c04022cf215c77ae31965a8
/src/apps/sumo/sumo_node_movement.h
1c4e69daf60383a7bc32bd4af30778b4e2837055
[ "MIT", "BSD-3-Clause" ]
permissive
venkatarajasekhar/shawn-1
08e6cd4cf9f39a8962c1514aa17b294565e849f8
d36c90dd88f8460e89731c873bb71fb97da85e82
refs/heads/master
2020-06-26T18:19:01.247491
2010-10-26T17:40:48
2010-10-26T17:40:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,786
h
/************************************************************************ ** Source $HeadURL: https://www.ldv.ei.tum.de/repos/vertrauenstuds/shawn-apps/trunk/sumo/sumo_node_movement.h $ ** Version $Revision: 416 $ ** Id $Id: sumo_node_movement.h 416 2010-09-01 22:12:09Z wbam $ ************************************************************************ ** This file is part of the network simulator Shawn. ** ** Copyright (C) 2010 Josef Schlittenlacher ** ** Copyright (C) 2010 Technische Unversitaet Muenchen (www.tum.de) ** ** All rights reserved. ** ** Shawn is free software; you can redistribute it and/or modify it ** ** under the terms of the BSD License. Refer to the shawn-licence.txt ** ** file in the root of the Shawn source tree for further details. ** ************************************************************************/ #ifndef __SHAWN_APPS_SUMO_SUMO_NODE_MOVEMENT_CREATOR_H #define __SHAWN_APPS_SUMO_SUMO_NODE_MOVEMENT_CREATOR_H #include "_apps_enable_cmake.h" #ifdef ENABLE_SUMO #include "sumo_net.h" #include "sys/node_movements/playback/movement_info.h" #include "sys/node_movements/playback/node_movement_creator.h" #include "sys/processors/processor_factory.h" #include "sys/vec.h" #include <vector> #include <map> #include <string> #include <fstream> namespace shawn { class SimulationController; /** Moves nodes based on a SUMO dump file. * * Usage in the Shawn configuration file: * * node_movement mode=sumo net_file=<NET> dump_file=<DUMP> processors=<PROCESSOR> * * mode=sumo: Activates this class * net_file: The SUMO net file on which the SUMO dump file is based * dump_file: The SUMO dump file containing the node movements * processors: A list of processors that should be added to every created node * * You can test the class with the following Shawn configuration file: * * prepare_world edge_model=simple comm_model=disk_graph range=100 * node_movement mode=sumo net_file=eichstaett.net.xml dump_file=eichstaett-5T.dmp.xml processors=simple_app * simulation max_iterations=43200 * * This class reads the SUMO dump file block by block. One block contains all * movements within one time step. The movements are compared with those of the * previous time step to find new and deleted nodes. Such nodes are created * or deleted from the simulation. The block by block reading schema has the * advantage that only a small part of the SUMO dump file is kept in memory. * As a consequence, even large SUMO dump files (several gigabytes) can easily * be processed. */ class SumoNodeMovementCreator : public NodeMovementCreator { public: /** * Constructor */ SumoNodeMovementCreator( SimulationController& sc ); /** * Destructor */ virtual ~SumoNodeMovementCreator(); /** * Inherited from NodeMovementCreator. It returns the next node movement to be executed. * It is called whenever the movement controller needs a new command. The movement controller needs a new command as * long as next_movment does not return a NULL movement or a movement to be executed at a later point of time. Therefore, * next_movementreturns movements for each node at each round. When each node has been moved a MovementInfo for a NULL * node to be executed next round is returned. * The function also calls private functions to delete and add nodes. */ virtual MovementInfo * next_movement(); /* * Reset the input file */ virtual void reset(); private: /** * SUMO net that is associated with this dump file. It is used * for coordinate transformations. */ SumoNet net_; /** * Path to the SUMO dump file */ std::string dump_file_; /** * Input stream for SUMO dump file */ std::ifstream ifs_dump_file_; /** * Pointer to the simulation controller, initialized in constructor */ SimulationController* sc_; /** * Last round that has been parsed */ int last_parsed_round_; /** * Handle for processor factories to create processors specified in configuration file */ std::vector<ProcessorFactoryHandle> processor_factories_; /** * Map that holds all current positions of all nodes */ std::map<std::string, Vec> * map_current_positions_; /** * Map that holds all positions of all nodes at last round * This variable helps to detect whether a node has to be deleted, added or to define the parameters of the movement */ std::map<std::string, Vec> * map_last_positions_; /** * If next_movement is executed for the first time at a Shawn round, this vetor is filled with all movements that * have to be executed this round. * All further calls of next_movement then just pick the next remaining movement until all movements are done */ std::vector<MovementInfo*> remaining_movements_; /** * next_movement stores the round it is executed to this variable. So it can look by comparison with the world's *simulation_round() if it is executed for the first time at this round */ int last_round_; /** * Help function to define private functions that are called when a new round starts (when next_movement() is executed * for the first time at a round) */ void next_round(); /** * Read data needed for current round from dumpfile. * Store this data to the map of current positions * Called by next_round() */ void round_data_from_dumpfile(); /** * Generate movement data for current round out of current and last positions * Store all movements to remaing movements vector */ void generate_movements(); /** * Add new nodes to simulation. * If a node appears in current positions map and does not in last positions map, it is added. */ void add_new_nodes(); /** * Remove nodes from simulation. * If a node appears in last positions map and does not in current positions map, it is deleted. */ void delete_nodes(); /** * Shawn stops simulation after 5 rounds with no active node. To prevent this, a dummy node is placed at the origin (0|0). * The dummy node has all processors that are defined in the configuration file! If the dummy node disturbs you, place * it somewhere else. It can be found by its label "Dummy node". */ void create_dummy_node(); }; } #endif /* ENABLE_SUMO */ #endif /* __SHAWN_APPS_SUMO_SUMO_NODE_MOVEMENT_CREATOR_H */
[ [ [ 1, 197 ] ] ]
de8a7c790f22e6b8f652d5b5c6397d43b933211b
394a684577c234bf93373c7f7b92cddab1ba39b3
/src/gui.h
7b06de127aa2c2e844485d215ea3f8aef40484d2
[]
no_license
aramande/GameEngine
b1792e57c32607c8c020b7dc95e3177e5b4e60d7
044687c8924d30808a71deeec5af51f43722a583
refs/heads/master
2020-05-16T22:53:26.664558
2011-08-25T16:08:42
2011-08-25T16:08:42
1,292,389
1
0
null
null
null
null
UTF-8
C++
false
false
1,234
h
#ifndef GUI_H #define GUI_H #include "component.h" #include <map> #include <string> namespace engine{ class Gui { private: std::map<std::string, Component*> comps; static int index; std::string toStr(int number); public: Gui(); virtual ~Gui(); /** * Adds a component to the gui with a randomly generated name. * * @param component The component to be added * * @see Component::getName() */ void addComp(Component* component); /** * Adds a component to the game with an easy to access name. * * @param name The name given to the component, has to be unique. * @param component The component to be added * * @throws badarg If name already exists. * * @see Component::getName() * */ void setComp(std::string name, Component* component); /** * Removes a component by name from the gui, does not delete the pointer. * * @param name The name of the component to be removed */ void removeComp(std::string name); /** * Retrieve a component by name from the gui. * * @param name The name of the component to be removed */ Component* getComp(std::string name); }; } #endif
[ [ [ 1, 57 ] ] ]
05a2794809890ca4f670e65df34c83ad16ce2a30
f7275659680b07fbb9fb1647f0f26cc029565939
/alarmList.cpp
096073eb4b069daf475232c2533aea04b76334e4
[]
no_license
rexzhang/wxalarm
f564fcf019c8e9c9c1a0d75b4c1dae24113ad1c5
435d244e0382c10f38d1675c0699a7d7acc4bc7a
refs/heads/master
2016-09-06T10:37:59.614623
2008-08-31T14:38:43
2008-08-31T14:38:43
32,366,981
0
0
null
null
null
null
GB18030
C++
false
false
3,049
cpp
#include "alarmList.h" //#include "ticpp/tinyxml.h" #include "ticpp/ticpp.h" alarmList::alarmList() { //ctor } alarmList::~alarmList() { //dtor } bool alarmList::SaveList() { TiXmlDocument xmlConfig; TiXmlDeclaration *pXMLDeclaration = new TiXmlDeclaration( "1.0", "UTF-8", "" );//定义XML文件格式 TiXmlElement * pXMLAppName = new TiXmlElement( "wxAlarm" ); TiXmlElement * pXMLFileVersion = new TiXmlElement( "FileVersion" );//定义自定义的文件格式版本 pXMLFileVersion->SetAttribute("major", 1); pXMLFileVersion->SetAttribute("minor", 0); TiXmlElement * pXMLAlarmList = new TiXmlElement( "alarmList" ); TiXmlElement * pXMLAlarmItem = new TiXmlElement( "alarmItem" ); { time_t rawtime; rawtime=time(NULL);//获取当前时间 //char buffer [80]; //vsprintf(buffer, "%il", (long)rawtime); wxString wxbuffer; wxbuffer.Printf(wxT("%il"),rawtime);//time_t(long)转换为long的文本格式 //TiXmlText * text = new TiXmlText( "World" ); //TiXmlText * text = new TiXmlText( wxbuffer.char_str() );//wxString格式转换为c_char文本格式,并存储到XML节点 pXMLAlarmItem->SetAttribute("description", "xml测试项"); pXMLAlarmItem->SetAttribute("alarmTime", wxbuffer.char_str());//wxString格式转换为c_char文本格式,并存储到XML节点 bool repeatTest = true; pXMLAlarmItem->SetAttribute("repeat", repeatTest); pXMLAlarmItem->SetAttribute("repeatRange", wxbuffer.char_str()); pXMLAlarmItem->SetAttribute("memo", "备注测试内容"); } //连接生成完整的XML配置文件树 xmlConfig.LinkEndChild( pXMLDeclaration ); xmlConfig.LinkEndChild( pXMLAppName ); pXMLAppName->LinkEndChild( pXMLFileVersion ); pXMLAppName->LinkEndChild( pXMLAlarmList ); pXMLAlarmList->LinkEndChild( pXMLAlarmItem ); //保存XML配置文件 xmlConfig.SaveFile( "wxAlarm.xml" ); ////////////////////// return true; } bool alarmList::ReloadList() { ticpp::Document xmlConfig; xmlConfig.LoadFile("wxAlarm.xml", TIXML_ENCODING_UTF8);//吧XML载入内存 ticpp::Element * pWxAlarmElem = xmlConfig.FirstChildElement("wxAlarm");//定位<wxAlarm>块 ticpp::Element * pAlarmListElem = pWxAlarmElem->FirstChildElement("alarmList");//定位<alarmList>块 /* //ticpp::Element * pAlarmItemElem = pAlarmListElem->FirstChildElement("alarmItem");//定位<alarmList>块 std::string attr; pAlarmItemElem->GetAttribute( "description", &attr ); wxMessageBox(wxT("alarmItem")); */ ticpp::Iterator< ticpp::Element > child; for ( child = child.begin( pAlarmListElem ); child != child.end(); child++ )//循环遍历<alarmList>的子块 { std::string attr; child->GetAttribute( "description", &attr );//获取description值 wxMessageBox(wxT("alarmItem")); } return true; }
[ "rex.zhang@cce68e7b-343c-0410-bfd2-9b215a1710d6" ]
[ [ [ 1, 89 ] ] ]
16f241649306dc0b548cee42a7a556eb54a8c559
c0a577ec612a721b324bb615c08882852b433949
/antlr/src/StepByStep/PNodeFactory.hpp
c4784e0357e246c1328fa1d027c9269573aad9de
[]
no_license
guojerry/cppxml
ca87ca2e3e62cbe2a132d376ca784f148561a4cc
a4f8b7439e37b6f1f421445694c5a735f8beda71
refs/heads/master
2021-01-10T10:57:40.195940
2010-04-21T13:25:29
2010-04-21T13:25:29
52,403,012
0
0
null
null
null
null
UTF-8
C++
false
false
720
hpp
#ifndef PNode_Factory_hpp__ #define PNode_Factory_hpp__ #include "antlr/ASTFactory.hpp" #include "PNode.hpp" ANTLR_USING_NAMESPACE(std) ANTLR_USING_NAMESPACE(antlr) class _PNodeFactory : public ASTFactory { public: typedef RefAST (*factory_type)(); // remark reference to Pnode... _PNodeFactory() : nodeFactory(&PNode::factory) { } // add your own functionality... // // RefPNode _PNodeFactory::create(RefPNode tr) { if (!tr) return nullAST; RefPNode t = _PNodeFactory::nodeFactory(); t->initialize(tr); return t; } RefPNode _PNodeFactory::dup(RefPNode t) { return _PNodeFactory::create(t); } private: factory_type nodeFactory; }; #endif
[ "oeichenwei@0e9f5f58-6d57-11de-950b-9fccee66d0d9" ]
[ [ [ 1, 43 ] ] ]
bc3f2c8ae7a0abd35d1e1677c313821088546c4d
629e4fdc23cb90c0144457e994d1cbb7c6ab8a93
/lib/log/logexception.cpp
6ee87dca3fc1d6b1b6eab09bc7f4716adfff3671
[]
no_license
akin666/ice
4ed846b83bcdbd341b286cd36d1ef5b8dc3c0bf2
7cfd26a246f13675e3057ff226c17d95a958d465
refs/heads/master
2022-11-06T23:51:57.273730
2011-12-06T22:32:53
2011-12-06T22:32:53
276,095,011
0
0
null
null
null
null
UTF-8
C++
false
false
277
cpp
/* * logexception.cpp * * Created on: 6.11.2011 * Author: akin */ #include "logexception" namespace ice { LogException::LogException( std::string str ) : Exception( str ) { } LogException::~LogException() throw() { } } /* namespace ice */
[ "akin@localhost" ]
[ [ [ 1, 22 ] ] ]
3ce92cd5329f9a828918a679c0bf83b120a3e1a4
28e80ec171dfe5c73c93a98045a8d370d059f8c2
/src/fixtureManager.h
db4af679c7e1bbbf014313f186f7b9115b0471f9
[]
no_license
GunioRobot/movieToeSign
db83909fdf8c750944be52a35ba1fdc9445f11a9
7dfc105f940445dc84f7f0c5015e046669b7f665
refs/heads/master
2020-12-24T14:09:54.648624
2011-12-13T16:38:35
2011-12-13T16:38:35
2,996,486
0
0
null
null
null
null
UTF-8
C++
false
false
397
h
#pragma once #include "ofMain.h" #include "RGBfixture.h" class fixtureManager { public: fixtureManager(); virtual ~fixtureManager(); vector<RGBfixture> RGBfixtures; int gridRes; void setFromVideo(ofVideoPlayer & video); void setGrid(ofVideoPlayer & video); private: bool bGridChange; unsigned char* pixels; };
[ [ [ 1, 22 ] ] ]
3d3358f5e994659536917b723d92a92433f2db91
636990a23a0f702e3c82fa3fc422f7304b0d7b9e
/ocx/AnvizOcx/AnvizOcx/DoorGroups.h
744ef8cf028d97d73afd2c5a170c8482fa52feb1
[]
no_license
ak869/armcontroller
09599d2c145e6457aa8c55c8018514578d897de9
da68e180cacce06479158e7b31374e7ec81c3ebf
refs/heads/master
2021-01-13T01:17:25.501840
2009-02-09T18:03:20
2009-02-09T18:03:20
40,271,726
0
1
null
null
null
null
UTF-8
C++
false
false
1,771
h
// DoorGroups.h : Declaration of the CDoorGroups #pragma once #include "resource.h" // main symbols #include "AnvizOcx_i.h" #include ".\Protocoltest\Controller.h" #if defined(_WIN32_WCE) && !defined(_CE_DCOM) && !defined(_CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA) #error "Single-threaded COM objects are not properly supported on Windows CE platform, such as the Windows Mobile platforms that do not include full DCOM support. Define _CE_ALLOW_SINGLE_THREADED_OBJECTS_IN_MTA to force ATL to support creating single-thread COM object's and allow use of it's single-threaded COM object implementations. The threading model in your rgs file was set to 'Free' as that is the only threading model supported in non DCOM Windows CE platforms." #endif // CDoorGroups class ATL_NO_VTABLE CDoorGroups : public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<CDoorGroups, &CLSID_DoorGroups>, public IDispatchImpl<IDoorGroups, &IID_IDoorGroups, &LIBID_AnvizOcxLib, /*wMajor =*/ 1, /*wMinor =*/ 0> { private: CComVariant* m_VarVect; CController* m_parent; LONG m_nSize; public: CDoorGroups() { m_nSize = 0; m_VarVect = NULL; m_parent = NULL; } virtual ~CDoorGroups(); DECLARE_REGISTRY_RESOURCEID(IDR_DOORGROUPS) BEGIN_COM_MAP(CDoorGroups) COM_INTERFACE_ENTRY(IDoorGroups) COM_INTERFACE_ENTRY(IDispatch) END_COM_MAP() DECLARE_PROTECT_FINAL_CONSTRUCT() HRESULT FinalConstruct() { return S_OK; } void FinalRelease() { } public: STDMETHOD(get__NewEnum)(IUnknown** pVal); STDMETHOD(get_Item)(LONG Index, IDoorGroup** pVal); STDMETHOD(get_Count)(LONG* pVal); void Init(CController * pParent); }; OBJECT_ENTRY_AUTO(__uuidof(DoorGroups), CDoorGroups)
[ "leon.b.dong@41cf9b94-d0c3-11dd-86c2-0f8696b7b6f9" ]
[ [ [ 1, 69 ] ] ]
4ba2dd1203f79f5d07ce6ff76181be17d3016841
38d9a3374e52b67ca01ed8bbf11cd0b878cce2a5
/branches/tbeta/CCV-fid/apps/TUIOMultiplexer/src/testApp.cpp
335adbc0283cd19981b14747d10f353668b3f161
[]
no_license
hugodu/ccv-tbeta
8869736cbdf29685a62d046f4820e7a26dcd05a7
246c84989eea0b5c759944466db7c591beb3c2e4
refs/heads/master
2021-04-01T10:39:18.368714
2011-03-09T23:05:24
2011-03-09T23:05:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,422
cpp
#include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ ofSetFrameRate(60); ofSetWindowTitle(" TUIO Multiplexer "); hProcess = GetCurrentProcess();// process Handle for MemoryCheck //return; //removes the 'x' button on windows which causes a crash due to a GLUT bug #ifdef TARGET_WIN32 //Get rid of 'x' button HWND hwndConsole = FindWindowA(NULL, " TUIO Multiplexer "); HMENU hMnu = ::GetSystemMenu(hwndConsole, FALSE); RemoveMenu(hMnu, SC_CLOSE, MF_BYCOMMAND); #endif //problem with the initialization of the tuioClient: constructor get called at initialization.no way to set the port afterward // so we have to load the XML.config first for the data. //printToFile=false; loadXMLSettings("data/config.xml"); //cout<<"PRINTTOFILE:"<<printToFile<<endl; if(printToFile) { /***************************************************************************************************** * LOGGING ******************************************************************************************************/ /* alright first we need to get time and date so our logs can be ordered */ time ( &rawtime ); timeinfo = localtime ( &rawtime ); strftime (fileName,80,"../logs/log_%B_%d_%y_%H_%M_%S.txt",timeinfo); /* FILE *stream ; sprintf(fileName, ofToDataPath(fileName).c_str()); if((stream = freopen(fileName, "w", stdout)) == NULL){} */ sprintf(fileName, ofToDataPath(fileName).c_str()); filestr.open (fileName,ios::out | ios::app ); cout.rdbuf(filestr.rdbuf()); //filestr.close(); /******************************************************************************************************/ } tuioMultiplexer = new ofxTuioMultiplexer(tuioServerHost, tuioServerPort, tuioClientPort, tuioFlashPort, netinterfaceID, tuio_application_name); ofAddListener(tuioMultiplexer->objectAdded,this,&testApp::objectAdded); ofAddListener(tuioMultiplexer->objectRemoved,this,&testApp::objectRemoved); ofAddListener(tuioMultiplexer->objectUpdated,this,&testApp::objectUpdated); ofAddListener(tuioMultiplexer->cursorAdded,this,&testApp::tuioAdded); ofAddListener(tuioMultiplexer->cursorRemoved,this,&testApp::tuioRemoved); ofAddListener(tuioMultiplexer->cursorUpdated,this,&testApp::tuioUpdated); //the XML is already loaded so we give a pointer to it tuioMultiplexer->setXML(&XML); tuioMultiplexer->initXMLSettings(); tuioMultiplexer->initImage(); visible = !visible;//we toggle this back in the next method call toggleVisibility(); ofSetWindowPosition(position.x , position.y); tuioMultiplexer->init_UDP_calibrate_connection(); tuioMultiplexer->init_UDP_alive_connection(); tuioMultiplexer->connect(); fullScreen = (ofGetWindowMode() == OF_FULLSCREEN) ? true : false ; setScreenData(); } void testApp::setScreenData(){ if(fullScreen){ cout << "OF_FULLSCREEN:" << endl; tuioMultiplexer->offset.set((ofGetWidth()/2)-(tuioMultiplexer->main_screen_scaled.width /2),(ofGetHeight()/2)-(tuioMultiplexer->main_screen_scaled.height /2)); }else{ cout << "OF_WINDOW:" << endl; tuioMultiplexer->offset.set(0.0f,0.0f); } } void testApp::toggleVisibility(){ visible = !visible; if(visible){ ofSetWindowShape(tuioMultiplexer->main_screen_scaled.width , tuioMultiplexer->main_screen_scaled.height);//reshape the window to the size from the XML.config }else { ofSetWindowShape(110 , 1); } } //-------------------------------------------------------------- void testApp::update(){ //tuio.getMessage(); if(tuioMultiplexer == NULL)return; tuioMultiplexer->update();//trigger the TuioServer checkForMemoryLeak(); } //-------------------------------------------------------------- void testApp::draw(){ if(tuioMultiplexer == NULL)return; ofBackground(0,0,0); glPushMatrix(); glTranslatef(tuioMultiplexer->offset.x,tuioMultiplexer->offset.y, 0.0); //tuioMultiplexer->blobImage.draw(0,0); if(visible){ //tuioMultiplexer->drawCursors(); tuioMultiplexer->drawSourceScreens(); tuioMultiplexer->drawObjects(); glBlendFunc(GL_SRC_ALPHA,GL_ONE); tuioMultiplexer->blobImageBw.draw(0,0);// Here we see the Blobs as visual feedback so we didn't have to call tuioMultiplexer->drawCursors() explicit } //tuioMultiplexer->drawDebugInfo(); glPopMatrix(); } //-------------------------------------------------------------- void testApp::keyPressed (int key){ cout << "KeY:"<< key << keyMapper.isShiftDown()<< endl; int delta = keyMapper.isShiftDown() ? 10 : 1 ; switch(key){ case ' ': ofToggleFullscreen(); break; case 356: //LEFT ofSetWindowPosition(ofGetWindowPositionX()-delta , ofGetWindowPositionY()); break; case 357: //UP ofSetWindowPosition(ofGetWindowPositionX() , ofGetWindowPositionY()-delta); break; case 358: //RIGHT ofSetWindowPosition(ofGetWindowPositionX()+delta , ofGetWindowPositionY()); break; case 359: //DOWN ofSetWindowPosition(ofGetWindowPositionX() , ofGetWindowPositionY()+delta); break; case 'h': toggleVisibility(); break; case 'q': break; } } //-------------------------------------------------------------- void testApp::keyReleased(int key){ cout << "keyReleased:" << key << ":"<< (char)key<<endl; int w ; switch(key){ case ' ': // we need to catch this on Key up as on Keydown we get not the right WindowMode after the ofToggleFullscreen() call fullScreen = (ofGetWindowMode() == OF_FULLSCREEN) ? true : false ; if(fullScreen){ cout << "OF_FULLSCREEN:" << endl; }else{ cout << "OF_WINDOW:" << endl; //ofSetWindowShape(100 , 50); ofSetWindowShape(tuioMultiplexer->main_screen_scaled.width , tuioMultiplexer->main_screen_scaled.height); } setScreenData(); break; case 'x': cout << "x:" << key << endl; break; } } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(){ } void testApp::objectAdded(TuioObject & tuioObject){ cout << " new object: " + ofToString(tuioObject.getSymbolID())+ " X: "+ofToString(tuioObject.getX())+ " Y: "+ofToString(tuioObject.getY())+ " angle: "+ofToString(tuioObject.getAngleDegrees()) << endl; } void testApp::objectRemoved(TuioObject & tuioObject){ cout << " object removed: " + ofToString(tuioObject.getSymbolID())+ " X: "+ofToString(tuioObject.getX())+ " Y: "+ofToString(tuioObject.getY())+ " angle: "+ofToString(tuioObject.getAngleDegrees()) << endl; } void testApp::objectUpdated(TuioObject & tuioObject){ cout << " object updated: " + ofToString(tuioObject.getSymbolID())+ " X: "+ofToString(tuioObject.getX())+ " Y: "+ofToString(tuioObject.getY())+ " angle: "+ofToString(tuioObject.getAngleDegrees()) << endl; } void testApp::tuioAdded(TuioCursor & tuioCursor){ /* cout << " new cursor: " + ofToString(tuioCursor.getCursorID())+ " X: "+ofToString(tuioCursor.getX())+ " Y: "+ofToString(tuioCursor.getY()) << endl; */ ofxVec3f vec; tuioMultiplexer->localToGlobal(&vec,&tuioCursor,tuioMultiplexer->tuioCourser_source_map[&tuioCursor]); cout << "global Pos:" << " X: "<< vec.x << " Y: "<< vec.y << endl; //cout << "getTuioCursors(0)" << (int) tuio.client->getTuioCursors(0).size() << endl; //cout << "getTuioCursors(1)" << (int) tuio.client->getTuioCursors(1).size() << endl; } void testApp::tuioRemoved(TuioCursor & tuioCursor){ /* cout << " cursor removed: " + ofToString(tuioCursor.getCursorID())+ " X: "+ofToString(tuioCursor.getX())+ " Y: "+ofToString(tuioCursor.getY()) << endl; */ } void testApp::tuioUpdated(TuioCursor & tuioCursor){ /* cout << " cursor updated: " + ofToString(tuioCursor.getCursorID())+ " X: "+ofToString(tuioCursor.getX())+ " Y: "+ofToString(tuioCursor.getY()) << endl; */ } void testApp::loadXMLSettings(string path) { string message; if( XML.loadFile(path) ){ message = "testapp.xml loaded!"; }else{ message = "unable to load mySettings.xml check data/ folder"; } std::cout << "<<<<" << message<<":"<<path << std::endl; XML.pushTag("CONFIG" , 0); printToFile = XML.getValue("printToFile",0, 0); XML.pushTag("tuioServer" , 0); tuioServerHost = XML.getValue("host","127.0.0.1", 0); tuioServerPort =XML.getValue("port",3334, 0); tuioFlashPort=XML.getValue("flashport_out",3000, 0); tuio_application_name=XML.getValue("tuio_source_application","TUIOSOURCEFILTER", 0); cout << "tuioServerHost:" << tuioServerHost << endl; cout << "tuioServerPort:" << tuioServerPort << endl; XML.popTag(); netinterfaceID = XML.getValue("network_interface_nr",1, 0); XML.pushTag("tuioClient" , 0); tuioClientPort = XML.getValue("port",3333, 0); cout << "tuioClientPort:" << tuioClientPort << endl; XML.popTag(); visible = XML.getValue("visible",1,0); //int getAttribute(const string& tag, const string& attribute, int defaultValue, int which = 0); position.x = XML.getAttribute("position","x",0,0); position.y = XML.getAttribute("position","y",0,0); maxMemoryAllocation = XML.getValue("maxMemoryAllocation",50,0)*1024;//in MB XML.popTag(); } void testApp::checkForMemoryLeak(){ //info about memory usage of the current Process: http://msdn.microsoft.com/en-us/library/ms682050%28VS.85%29.aspx // or http://www.openframeworks.cc/forum/viewtopic.php?f=9&t=372&hilit=memory+usage //Linke Settings: additional dependencies : Psapi.Lib //and don't forget : psapi.dll to distribute (to find in Windows/system32/) /* The working set is the amount of memory physically mapped to the process context at a given time. Memory in the paged pool is system memory that can be transferred to the paging file on disk (paged) when it is not being used. Memory in the nonpaged pool is system memory that cannot be paged to disk as long as the corresponding objects are allocated. The pagefile usage represents how much memory is set aside for the process in the system paging file. When memory usage is too high, the virtual memory manager pages selected memory to disk. When a thread needs a page that is not in memory, the memory manager reloads it from the paging file. */ /* PROCESS_MEMORY_COUNTERS pmc; HANDLE hProcess; hProcess = GetCurrentProcess(); */ if ( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) ) { /* cout<< "\tPageFaultCount: "<< pmc.PageFaultCount << endl; cout<< "\tPeakWorkingSetSize: "<< pmc.PeakWorkingSetSize << endl; cout<< "\tWorkingSetSize: "<< pmc.WorkingSetSize << endl; cout<< "\tQuotaPeakPagedPoolUsage: "<< pmc.QuotaPeakPagedPoolUsage <<endl; cout<< "\tQuotaPagedPoolUsage: "<< pmc.QuotaPagedPoolUsage << endl; cout<< "\tQuotaPeakNonPagedPoolUsage: "<< pmc.QuotaPeakNonPagedPoolUsage << endl; cout<< "\tQuotaNonPagedPoolUsage: "<< pmc.QuotaNonPagedPoolUsage<< endl; cout<< "\tPagefileUsage: "<< pmc.PagefileUsage<< endl; cout<< "\tPeakPagefileUsage: "<< pmc.PeakPagefileUsage<< endl; */ } //cout << GetProcessMemoryInfo(GetCurrentProcess(),&pmc,sizeof(pmc) )<< endl; if(pmc.WorkingSetSize/1024 > maxMemoryAllocation){ CloseHandle( hProcess ); delete tuioMultiplexer;//clean up the connection, otherwise the follow Process will have no UDP connection! //Sleep(2000); //system("start CalibrationGUI.exe");//With a short console Popup :-( _execl("TUIO Multiplexer.exe","_execl",NULL);//Terminates the running process and starts a new Instance //_spawnl(_P_OVERLAY,"CalibrationGUI.exe","_spawnl",NULL); // same as _execl //OF_EXIT_APP(0); } }
[ "schlupek@463ed9da-a5aa-4e33-a7e2-2d3b412cff85" ]
[ [ [ 1, 399 ] ] ]
0096f366031e53b7f89475e34008b7a4ab3d7da5
34a68e61a469b94063bc98465557072897a9aa88
/libraries/gameswf/gameswf_processor.cpp
30c4ce4fa95e8e89328cd705da59c2d9e9de5d95
[]
no_license
CneoC/shinzui
f83bfc9cbd9a05480d5323a21339d83e4d403dd9
5a2b79b430b207500766849bd58538e6a4aff2f8
refs/heads/master
2020-05-03T11:00:52.671613
2010-01-25T00:05:55
2010-01-25T00:05:55
377,430
1
0
null
null
null
null
UTF-8
C++
false
false
7,491
cpp
// gameswf_processor.cpp -- Thatcher Ulrich <[email protected]> 2003 // This source code has been donated to the Public Domain. Do // whatever you want with it. // A SWF preprocessor for the gameswf library. Loads a set of SWF // files and generates precomputed data such as font bitmaps and shape // tesselation meshes. The precomputed data can be appended to the // original SWF files, so that gameswf can more rapidly load those SWF // files later. #include "base/tu_file.h" #include "base/container.h" #include "render/2d/swf/gameswf.h" #include "render/2d/swf/gameswf_impl.h" static bool s_verbose = false; static void message_log(const char* message) // Process a log message. { if (s_verbose) { fputs(message, stdout); //flush(stdout); // needed on osx for some reason } } static void log_callback(bool error, const char* message) // Error callback for handling gameswf messages. { if (error) { // Log, and also print to stderr. message_log(message); fputs(message, stderr); } else { message_log(message); } } static tu_file* file_opener(const char* url) // Callback function. This opens files for the gameswf library. { return new tu_file(url, "rb"); } static void print_usage() { printf( "gameswf_processor -- a SWF preprocessor for gameswf.\n" "\n" "This program has been donated to the Public Domain.\n" "See http://tulrich.com/geekstuff/gameswf.html for more info.\n" "\n" "usage: gameswf_processor [options] [swf files to process...]\n" "\n" "Preprocesses the given SWF movie files. Optionally write preprocessed shape\n" "and font data to cache files, so the associated SWF files can be loaded\n" "faster by gameswf.\n" "\n" "options:\n" "\n" " -h Print this info.\n" " -w Write a .gsc file with preprocessed info, for each input file.\n" " -v Be verbose; i.e. print log messages to stdout\n" " -vp Be verbose about movie parsing\n" " -va Be verbose about ActionScript\n" ); } struct movie_data { gameswf::movie_definition* m_movie; tu_string m_filename; }; static gameswf::movie_definition* play_movie(gameswf::player* player, const char* filename); static int write_cache_file(const movie_data& md); static bool s_do_output = false; static bool s_stop_on_errors = true; int main(int argc, char *argv[]) { assert(tu_types_validate()); array<const char*> infiles; for (int arg = 1; arg < argc; arg++) { if (argv[arg][0] == '-') { // Looks like an option. if (argv[arg][1] == 'h') { // Help. print_usage(); exit(1); } else if (argv[arg][1] == 'w') { // Write cache files. s_do_output = true; } else if (argv[arg][1] == 'v') { // Be verbose; i.e. print log messages to stdout. s_verbose = true; if (argv[arg][2] == 'a') { // Enable spew re: action. gameswf::set_verbose_action(true); } else if (argv[arg][2] == 'p') { // Enable parse spew. gameswf::set_verbose_parse(true); } // ... } } else { infiles.push_back(argv[arg]); } } if (infiles.size() == 0) { printf("no input files\n"); print_usage(); exit(1); } gameswf::gc_ptr<gameswf::player> player = new gameswf::player(); gameswf::register_file_opener_callback(file_opener); gameswf::register_log_callback(log_callback); gameswf::set_use_cache_files(false); // don't load old cache files! array<movie_data> data; // Play through all the movies. for (int i = 0, n = infiles.size(); i < n; i++) { gameswf::movie_definition* m = play_movie(player.get_ptr(), infiles[i]); if (m == NULL) { if (s_stop_on_errors) { // Fail. fprintf(stderr, "error playing through movie '%s', quitting\n", infiles[i]); exit(1); } } movie_data md; md.m_movie = m; md.m_filename = infiles[i]; data.push_back(md); } // Now append processed data. if (s_do_output) { for (int i = 0, n = data.size(); i < n; i++) { int error = write_cache_file(data[i]); if (error) { if (s_stop_on_errors) { // Fail. fprintf(stderr, "error processing movie '%s', quitting\n", data[i].m_filename.c_str()); exit(1); } } } } return 0; } gameswf::movie_definition* play_movie(gameswf::player* player, const char* filename) // Load the named movie, make an instance, and play it, virtually. // I.e. run through and render all the frames, even though we are not // actually doing any output (our output handlers are disabled). // // What this does is warm up all the cached data in the movie, so that // if we save that data for later, we won't have to tesselate shapes // or build font textures again. // // Return the movie definition. { gameswf::movie_definition* md = player->create_movie(filename); if (md == NULL) { fprintf(stderr, "error: can't play movie '%s'\n", filename); exit(1); } gameswf::root* m = md->create_instance(); if (m == NULL) { fprintf(stderr, "error: can't create instance of movie '%s'\n", filename); exit(1); } int kick_count = 0; // Run through the movie. player->set_root(m); for (;;) { // @@ do we also have to run through all sprite frames // as well? // // @@ also, ActionScript can rescale things // dynamically -- we can't really do much about that I // guess? // // @@ Maybe we should allow the user to specify some // safety margin on scaled shapes. int last_frame = m->get_current_frame(); m->advance(0.010f); m->display(); if (m->get_current_frame() == md->get_frame_count() - 1) { // Done. break; } if (m->get_play_state() == gameswf::character::STOP) { // Kick the movie. printf("kicking movie, kick ct = %d\n", kick_count); m->goto_frame(last_frame + 1); m->set_play_state(gameswf::character::PLAY); kick_count++; if (kick_count > 10) { printf("movie is stalled; giving up on playing it through.\n"); break; } } else if (m->get_current_frame() < last_frame) { // Hm, apparently we looped back. Skip ahead... printf("loop back; jumping to frame %d\n", last_frame); m->goto_frame(last_frame + 1); } else { kick_count = 0; } } return md; } int write_cache_file(const movie_data& md) // Write a cache file for the given movie. { // Open cache file. tu_string cache_filename(md.m_filename); cache_filename += ".gsc"; tu_file out(cache_filename.c_str(), "wb"); // "gsc" == "gameswf cache" if (out.get_error() == TU_FILE_NO_ERROR) { // Write out the data. gameswf::cache_options opt; md.m_movie->output_cached_data(&out, opt); if (out.get_error() == TU_FILE_NO_ERROR) { printf( "wrote '%s'\n", cache_filename.c_str()); } else { fprintf(stderr, "error: write failure to '%s'\n", cache_filename.c_str()); } } else { fprintf(stderr, "error: can't open '%s' for cache file output\n", cache_filename.c_str()); return 1; } // // xxx temp debug code: dump cached data to stdout // tu_file tu_stdout(stdout, false); // tu_stdout.copy_from(&cached_data); return 0; } // Local Variables: // mode: C++ // c-basic-offset: 8 // tab-width: 8 // indent-tabs-mode: t // End:
[ [ [ 1, 320 ] ] ]