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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
db965701710fc2d5a07ab737f8ae171dd80a497a | e41ff1b15d54fc77dd0b86abc83bcbefa0ff6c07 | /crystal/CSExceptions.cpp | fd94dc026c1977e765a3492c2c6453d7a37b3a45 | []
| no_license | zerotri/WynterStorm_old | 8dd9c6e3932b5883bce6f4fa6709159e8ca46ed8 | dd289ed3419a7eaff8e824d7f818b31b03075f21 | refs/heads/master | 2020-12-24T13:44:58.837251 | 2010-03-22T10:21:56 | 2010-03-22T10:21:56 | 570,788 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 657 | cpp | //#include <Crystal.h>
/*CrystalException::CrystalException(int lineNumber, const char* fileName)
: m_lineNumber(lineNumber), m_fileName(std::string(filename))
{
}
CrystalException::CrystalException(int lineNumber, const char* fileName, const char* error)
: m_lineNumber(lineNumber), m_fileName(std::string(filename)), m_error(std::string(error))
{
}
CrystalException::CrystalException(int lineNumber, std::string fileName)
: m_lineNumber(lineNumber), m_fileName(filename)
{
}
CrystalException::CrystalException(int lineNumber, std::string fileName, std::string error)
: m_lineNumber(lineNumber), m_fileName(filename), m_error(error)
{
}*/ | [
"[email protected]"
]
| [
[
[
1,
18
]
]
]
|
b1b7abc9aa9b367b993862b32c7fd6cb1c136b5c | c95a83e1a741b8c0eb810dd018d91060e5872dd8 | /Game/ClientFxDLL/polyfanfx.h | 275c2bb1de6db9ede408ec375d71cf2ebb6bcc07 | []
| no_license | rickyharis39/nolf2 | ba0b56e2abb076e60d97fc7a2a8ee7be4394266c | 0da0603dc961e73ac734ff365bfbfb8abb9b9b04 | refs/heads/master | 2021-01-01T17:21:00.678517 | 2011-07-23T12:11:19 | 2011-07-23T12:11:19 | 38,495,312 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,243 | h | //------------------------------------------------------------------
//
// MODULE : POLYFANFX.H
//
// PURPOSE : Defines class CPolyFanFX
//
// CREATED : On 11/23/98 At 6:21:38 PM
//
//------------------------------------------------------------------
#ifndef __POLYFANFX__H_
#define __POLYFANFX__H_
// Includes....
#include "basefx.h"
class CPolyFanProps : public CBaseFXProps
{
public:
CPolyFanProps();
//this will take a list of properties and convert it to internal values
virtual bool ParseProperties(FX_PROP* pProps, uint32 nNumProps);
char m_sPolyFanName[128];
uint32 m_nAlongNormal;
bool m_bParentRotate;
float m_fYaw;
LTVector m_vRot;
};
class CPolyFanFX : public CBaseFX
{
public :
// Constuctor
CPolyFanFX();
// Destructor
~CPolyFanFX();
// Member Functions
bool Init(ILTClient *pClientDE, FX_BASEDATA *pBaseData, const CBaseFXProps *pProps);
bool Update(float tmCur);
void Term();
// Accessors
protected :
const CPolyFanProps* GetProps() { return (const CPolyFanProps*)m_pProps; }
// Member Variables
};
#endif | [
"[email protected]"
]
| [
[
[
1,
64
]
]
]
|
fade408f1d56e7c7fb6e1c9c077510803ca257d8 | 222bc22cb0330b694d2c3b0f4b866d726fd29c72 | /src/nv38box/RaytracerRForce/KernelShader.cpp | 8b91acaa15b95c91aa87b5851e2152b3151569e9 | [
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference"
]
| permissive | darwin/inferno | 02acd3d05ca4c092aa4006b028a843ac04b551b1 | e87017763abae0cfe09d47987f5f6ac37c4f073d | refs/heads/master | 2021-03-12T22:15:47.889580 | 2009-04-17T13:29:39 | 2009-04-17T13:29:39 | 178,477 | 2 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 3,693 | cpp | // NV38Box (http://inferno.hildebrand.cz)
// Copyright (c) 2004 Antonin Hildebrand
// licensed under zlib/libpng license (see license.txt)
// released in Shader Triathlon – Summer 2004 ("Contest")
/*! \addtogroup RForce
@{
\ingroup Raytracers
*/
/*! \file KernelShader.cpp
\brief Implementation of KernelShader class.
*/
#include "base.h"
#include "KernelShader.h"
KernelShader::KernelShader()
{
m_iMode = KERNEL_SHADER_MODE_BASIC_PV_FLAT;
}
bool KernelShader::Prepare()
{
ReserveSlots(KERNEL_SHADER_MODE_COUNT);
if (!LoadVertexProgram (KERNEL_SHADER_MODE_COMPOSITION_SHADEDSECONDARY, SHADER_DIR "/" "kernel_shader1_vp.cg.shd")) return false;
if (!LoadFragmentProgram(KERNEL_SHADER_MODE_COMPOSITION_SHADEDSECONDARY, SHADER_DIR "/" "kernel_shader1_fp.cg.shd")) return false;
if (!LoadVertexProgram (KERNEL_SHADER_MODE_COMPOSITION_COLOREDSECONDARY, SHADER_DIR "/" "kernel_shader2_vp.cg.shd")) return false;
if (!LoadFragmentProgram(KERNEL_SHADER_MODE_COMPOSITION_COLOREDSECONDARY, SHADER_DIR "/" "kernel_shader2_fp.cg.shd")) return false;
if (!LoadVertexProgram (KERNEL_SHADER_MODE_BOUNDINGBOXES, SHADER_DIR "/" "kernel_shader3_vp.cg.shd")) return false;
if (!LoadFragmentProgram(KERNEL_SHADER_MODE_BOUNDINGBOXES, SHADER_DIR "/" "kernel_shader3_fp.cg.shd")) return false;
if (!LoadVertexProgram (KERNEL_SHADER_MODE_BASIC_FIXED_FLAT, SHADER_DIR "/" "kernel_shader4_vp.cg.shd")) return false;
if (!LoadFragmentProgram(KERNEL_SHADER_MODE_BASIC_FIXED_FLAT, SHADER_DIR "/" "kernel_shader4_fp.cg.shd")) return false;
if (!LoadVertexProgram (KERNEL_SHADER_MODE_BASIC_FIXED_TEXTURING, SHADER_DIR "/" "kernel_shader5_vp.cg.shd")) return false;
if (!LoadFragmentProgram(KERNEL_SHADER_MODE_BASIC_FIXED_TEXTURING, SHADER_DIR "/" "kernel_shader5_fp.cg.shd")) return false;
if (!LoadVertexProgram (KERNEL_SHADER_MODE_BASIC_PV_FLAT, SHADER_DIR "/" "kernel_shader6_vp.cg.shd")) return false;
if (!LoadFragmentProgram(KERNEL_SHADER_MODE_BASIC_PV_FLAT, SHADER_DIR "/" "kernel_shader6_fp.cg.shd")) return false;
if (!LoadVertexProgram (KERNEL_SHADER_MODE_BASIC_PV_TEXTURING, SHADER_DIR "/" "kernel_shader7_vp.cg.shd")) return false;
if (!LoadFragmentProgram(KERNEL_SHADER_MODE_BASIC_PV_TEXTURING, SHADER_DIR "/" "kernel_shader7_fp.cg.shd")) return false;
if (!LoadVertexProgram (KERNEL_SHADER_MODE_BASIC_PP_FLAT, SHADER_DIR "/" "kernel_shader8_vp.cg.shd")) return false;
if (!LoadFragmentProgram(KERNEL_SHADER_MODE_BASIC_PP_FLAT, SHADER_DIR "/" "kernel_shader8_fp.cg.shd")) return false;
if (!LoadVertexProgram (KERNEL_SHADER_MODE_BASIC_PP_TEXTURING, SHADER_DIR "/" "kernel_shader9_vp.cg.shd")) return false;
if (!LoadFragmentProgram(KERNEL_SHADER_MODE_BASIC_PP_TEXTURING, SHADER_DIR "/" "kernel_shader9_fp.cg.shd")) return false;
if (!LoadVertexProgram (KERNEL_SHADER_MODE_COMPOSITION_TEXTUREDSECONDARY, SHADER_DIR "/" "kernel_shader10_vp.cg.shd")) return false;
if (!LoadFragmentProgram(KERNEL_SHADER_MODE_COMPOSITION_TEXTUREDSECONDARY, SHADER_DIR "/" "kernel_shader10_fp.cg.shd")) return false;
return true;
}
void KernelShader::Activate()
{
CgManager* pCgManager = GetCgManager();
if (!pCgManager) return;
if (m_iMode!=KERNEL_SHADER_MODE_BASIC_FIXED_FLAT && m_iMode!=KERNEL_SHADER_MODE_BASIC_FIXED_TEXTURING)
{
// in fixed mode, use fixed-function vertex processing
cgGLEnableProfile(pCgManager->GetVertexProfile());
cgGLBindProgram(m_hVP[m_iMode]);
}
cgGLEnableProfile(pCgManager->GetFragmentProfile());
cgGLBindProgram(m_hFP[m_iMode]);
}
//! @} //doxygen group
| [
"[email protected]"
]
| [
[
[
1,
67
]
]
]
|
0c036e81901155b340bf349e6cc657f8edbe0c28 | 1775576281b8c24b5ce36b8685bc2c6919b35770 | /tags/release_1.0/tex_browser.cpp | 7bec94fb946686e1f46d88b3475c53ba8e5c3fba | []
| no_license | BackupTheBerlios/gtkslade-svn | 933a1268545eaa62087f387c057548e03497b412 | 03890e3ba1735efbcccaf7ea7609d393670699c1 | refs/heads/master | 2016-09-06T18:35:25.336234 | 2006-01-01T11:05:50 | 2006-01-01T11:05:50 | 40,615,146 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,090 | cpp |
#include "main.h"
#include "textures.h"
#include "tex_box.h"
#include "thing_type.h"
#include "draw.h"
#include <gdk/gdkkeysyms.h>
bool browse_sprites = false;
string selected_tex = "";
string tex_search = "";
int rows = 0;
vector<string> tex_names;
vector<string> browsesprites;
GtkWidget *browse_vscroll;
GtkWidget *browser_dialog;
CVAR(Int, browser_columns, 6, CVAR_SAVE)
extern GtkWidget *editor_window;
extern vector<Texture*> textures;
extern vector<Texture*> flats;
extern vector<Texture*> sprites;
extern GdkGLConfig *glconfig;
extern GdkGLContext *glcontext;
extern rgba_t col_selbox;
extern rgba_t col_selbox_line;
extern bool mix_tex;
void scroll_to_selected_texture(GtkWidget* w)
{
int width = (w->allocation.width / browser_columns);
int top = gtk_range_get_value(GTK_RANGE(browse_vscroll));
int bottom = top + w->allocation.height;
int a = 0;
for (int y = 0; y < rows; y++)
{
for (int x = 0; x < browser_columns; x++)
{
if (browse_sprites)
{
if (browsesprites[a] == selected_tex)
{
if (y * width < top)
gtk_range_set_value(GTK_RANGE(browse_vscroll), y * width);
if ((y+1) * width > bottom)
gtk_range_set_value(GTK_RANGE(browse_vscroll), ((y+1) * width) - w->allocation.height);
return;
}
}
else
{
if (tex_names[a] == selected_tex)
{
if (y * width < top)
gtk_range_set_value(GTK_RANGE(browse_vscroll), y * width);
if ((y+1) * width > bottom)
gtk_range_set_value(GTK_RANGE(browse_vscroll), ((y+1) * width) - w->allocation.height);
return;
}
}
a++;
if (a >= tex_names.size())
return;
}
}
}
gboolean browser_configure_event(GtkWidget *widget, GdkEventConfigure *event, gpointer data)
{
GdkGLContext *context = gtk_widget_get_gl_context(widget);
GdkGLDrawable *gldrawable = gtk_widget_get_gl_drawable(widget);
if (!gdk_gl_drawable_gl_begin(gldrawable, context))
return false;
glViewport(0, 0, widget->allocation.width, widget->allocation.height);
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
glClearDepth(1.0);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable(GL_CULL_FACE);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0.0f, widget->allocation.width, widget->allocation.height, 0.0f, -1.0f, 1.0f);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gdk_gl_drawable_gl_end(gldrawable);
rows = (tex_names.size() / browser_columns) + 1;
int width = widget->allocation.width / browser_columns;
int rows_page = widget->allocation.height / width;
gtk_range_set_range(GTK_RANGE(browse_vscroll), 0.0, (rows * width) - widget->allocation.height);
scroll_to_selected_texture(widget);
return true;
}
gboolean browser_expose_event(GtkWidget *w, GdkEventExpose *event, gpointer data)
{
int width = w->allocation.width / browser_columns;
rows = (tex_names.size() / browser_columns) + 1;
int top = gtk_range_get_value(GTK_RANGE(browse_vscroll));
// Set sizes for row and page steps (for the scrollbar)
int rows_page = w->allocation.height / width;
gtk_range_set_increments(GTK_RANGE(browse_vscroll), width, rows_page * width);
GdkGLContext *context = gtk_widget_get_gl_context(w);
GdkGLDrawable *gldrawable = gtk_widget_get_gl_drawable(w);
if (!gdk_gl_drawable_gl_begin(gldrawable, context))
return false;
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
int sel_index = -1;
int a = 0;
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < browser_columns; col++)
{
if (a >= tex_names.size())
continue;
rect_t rect(col * width, (row * width) - top, width, width, 0);
glLineWidth(2.0f);
if (selected_tex == tex_names[a])
{
draw_rect(rect, rgba_t(0, 180, 255, 150, 0), true);
draw_rect(rect, rgba_t(100, 220, 255, 255, 0), false);
sel_index = a;
}
glLineWidth(1.0f);
rect.resize(-8, -8);
if (((row + 1) * width) > top && (row * width) < (top + w->allocation.height))
{
if (!browse_sprites)
{
if (tex_names[a] != "-")
draw_texture_scale(rect, tex_names[a], 0);
draw_text(rect.x1() + (width/2) - 8, rect.y2() - 4, rgba_t(255, 255, 255, 255, 0), 1, tex_names[a].c_str());
}
else
draw_texture_scale(rect, browsesprites[a], 3);
}
a++;
}
}
if (browse_sprites && sel_index != -1)
draw_text(0, 0, rgba_t(255, 255, 255, 255, 0), 0, tex_names[sel_index].c_str());
if (gdk_gl_drawable_is_double_buffered(gldrawable))
gdk_gl_drawable_swap_buffers(gldrawable);
else
glFlush();
gdk_gl_drawable_gl_end(gldrawable);
return false;
}
gboolean browse_vscroll_change(GtkRange *range, GtkScrollType scroll, gdouble value, gpointer data)
{
GtkWidget *draw_area = (GtkWidget*)data;
gdk_window_invalidate_rect(draw_area->window, &draw_area->allocation, false);
return false;
}
gboolean browser_scroll_event(GtkWidget *widget, GdkEventScroll *event, gpointer user_data)
{
int width = (widget->allocation.width / browser_columns) / 2;
int top = gtk_range_get_value(GTK_RANGE(browse_vscroll));
if (event->direction == GDK_SCROLL_UP)
gtk_range_set_value(GTK_RANGE(browse_vscroll), top - width);
else if (event->direction = GDK_SCROLL_DOWN)
gtk_range_set_value(GTK_RANGE(browse_vscroll), top + width);
gdk_window_invalidate_rect(widget->window, &widget->allocation, false);
return false;
}
static gboolean browser_click_event(GtkWidget *widget, GdkEventButton *event)
{
int width = widget->allocation.width / browser_columns;
if (event->button == 1)
{
if (event->type == GDK_2BUTTON_PRESS)
gtk_dialog_response(GTK_DIALOG(browser_dialog), GTK_RESPONSE_ACCEPT);
else
{
int row = (gtk_range_get_value(GTK_RANGE(browse_vscroll)) + event->y) / width;
int col = event->x / width;
int index = (row * browser_columns) + col;
if (index < tex_names.size())
selected_tex = tex_names[index];
gdk_window_invalidate_rect(widget->window, &widget->allocation, false);
}
}
return false;
}
gboolean browser_key_event(GtkWidget *widget, GdkEventKey *event)
{
char key = gdk_keyval_name(event->keyval)[0];
int index = 0;
for (int a = 0; a < tex_names.size(); a++)
{
if (tex_names[a] == selected_tex)
index = a;
}
if (event->keyval == GDK_Return)
gtk_dialog_response(GTK_DIALOG(browser_dialog), GTK_RESPONSE_ACCEPT);
if (event->keyval == GDK_Up && index - browser_columns >= 0)
index -= browser_columns;
if (event->keyval == GDK_Left && index > 0)
index--;
if (event->keyval == GDK_Right && index < tex_names.size() - 1)
index++;
if (event->keyval == GDK_Down && index < tex_names.size() - browser_columns)
index += browser_columns;
selected_tex = tex_names[index];
scroll_to_selected_texture(widget);
gdk_window_invalidate_rect(widget->window, &widget->allocation, false);
return true;
}
void browser_search_entry_changed(GtkWidget *w, gpointer data)
{
string search = g_strup((gchar*)gtk_entry_get_text(GTK_ENTRY(w)));
for (int a = 0; a < tex_names.size(); a++)
{
if (tex_names[a].size() < search.size())
continue;
bool match = true;
for (int c = 0; c < search.size(); c++)
{
if (tex_names[a][c] != search[c])
match = false;
}
if (match)
{
selected_tex = tex_names[a];
scroll_to_selected_texture(GTK_WIDGET(data));
gdk_window_invalidate_rect(GTK_WIDGET(data)->window, >K_WIDGET(data)->allocation, false);
return;
}
}
}
GtkWidget* setup_texture_browser()
{
GtkWidget *hbox = gtk_hbox_new(false, 0);
GtkWidget *draw_area = gtk_drawing_area_new();
GTK_WIDGET_SET_FLAGS(draw_area, GTK_CAN_FOCUS);
gtk_widget_set_gl_capability(draw_area, glconfig, glcontext, TRUE, GDK_GL_RGBA_TYPE);
gtk_widget_set_events(draw_area, GDK_EXPOSURE_MASK|GDK_LEAVE_NOTIFY_MASK|GDK_BUTTON_PRESS_MASK);
g_signal_connect(G_OBJECT(draw_area), "expose-event", G_CALLBACK(browser_expose_event), NULL);
g_signal_connect(G_OBJECT(draw_area), "configure-event", G_CALLBACK(browser_configure_event), NULL);
g_signal_connect(G_OBJECT(draw_area), "button_press_event", G_CALLBACK(browser_click_event), NULL);
g_signal_connect(G_OBJECT(draw_area), "scroll-event", G_CALLBACK(browser_scroll_event), NULL);
g_signal_connect(G_OBJECT(draw_area), "key_press_event", G_CALLBACK(browser_key_event), NULL);
gtk_box_pack_start(GTK_BOX(hbox), draw_area, true, true, 0);
browse_vscroll = gtk_vscrollbar_new(NULL);
gtk_range_set_range(GTK_RANGE(browse_vscroll), 0.0, 1.0);
g_signal_connect(G_OBJECT(browse_vscroll), "change-value", G_CALLBACK(browse_vscroll_change), draw_area);
gtk_box_pack_start(GTK_BOX(hbox), browse_vscroll, false, false, 0);
GtkWidget *vbox = gtk_vbox_new(false, 0);
gtk_container_set_border_width(GTK_CONTAINER(vbox), 4);
gtk_box_pack_start(GTK_BOX(hbox), vbox, false, false, 0);
// 'search' entry
GtkWidget *entry = gtk_entry_new();
gtk_widget_set_size_request(entry, 64, -1);
g_signal_connect(G_OBJECT(entry), "changed", G_CALLBACK(browser_search_entry_changed), draw_area);
gtk_box_pack_start(GTK_BOX(vbox), gtk_label_new("Search:"), false, false, 0);
gtk_box_pack_start(GTK_BOX(vbox), entry, false, false, 0);
gtk_widget_grab_focus(draw_area);
return hbox;
}
string open_texture_browser(bool tex, bool flat, bool sprite, string init_tex, bool fullscreen)
{
tex_names.clear();
browsesprites.clear();
selected_tex = init_tex;
browse_sprites = sprite;
if (!sprite)
{
tex_names.push_back("-");
if (tex || mix_tex)
{
for (int a = 0; a < textures.size(); a++)
tex_names.push_back(textures[a]->name);
}
if (flat || mix_tex)
{
for (int a = 0; a < flats.size(); a++)
tex_names.push_back(flats[a]->name);
}
// Sort alphabetically for now
sort(tex_names.begin(), tex_names.end());
}
else
{
get_ttype_names(&tex_names);
for (int a = 0; a < tex_names.size(); a++)
browsesprites.push_back(get_thing_type_from_name(tex_names[a])->spritename);
}
browser_dialog = gtk_dialog_new_with_buttons("Textures",
GTK_WINDOW(editor_window),
GTK_DIALOG_MODAL,
GTK_STOCK_OK,
GTK_RESPONSE_ACCEPT,
GTK_STOCK_CANCEL,
GTK_RESPONSE_REJECT,
NULL);
gtk_container_add(GTK_CONTAINER(GTK_DIALOG(browser_dialog)->vbox), setup_texture_browser());
gtk_window_set_position(GTK_WINDOW(browser_dialog), GTK_WIN_POS_CENTER_ON_PARENT);
gtk_window_set_default_size(GTK_WINDOW(browser_dialog), 640, 480);
gtk_widget_show_all(browser_dialog);
if (fullscreen)
gtk_window_fullscreen(GTK_WINDOW(browser_dialog));
string ret = init_tex;
int response = gtk_dialog_run(GTK_DIALOG(browser_dialog));
if (response == GTK_RESPONSE_ACCEPT)
ret = selected_tex;
gtk_widget_destroy(browser_dialog);
gtk_window_present(GTK_WINDOW(editor_window));
return ret;
}
| [
"veilofsorrow@0f6d0948-3201-0410-bbe6-95a89488c5be"
]
| [
[
[
1,
385
]
]
]
|
3cb1150269c2d525e8e6f762e9ca51eb806dbc0c | f78d9c67f1785c436050d3c1ca40bf4253501717 | /Render.cpp | 456c95f64e275de91277d9d4815f0ecb8d50beb8 | []
| no_license | elcerdo/pixelcity | 0cdafbd013994475cd1db5919807f4e537d58b4c | aafecd6bd344ec79298d8aaf0c08426934fc2049 | refs/heads/master | 2021-01-10T22:06:18.964202 | 2009-05-13T19:15:40 | 2009-05-13T19:15:40 | 194,478 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 22,349 | cpp | /*-----------------------------------------------------------------------------
Render.cpp
2009 Shamus Young
-------------------------------------------------------------------------------
This is the core of the gl rendering functions. This contains the main
rendering function RenderUpdate (), which initiates the various
other renders in the other modules.
-----------------------------------------------------------------------------*/
#define RENDER_DISTANCE 1280
#define MAX_TEXT 256
#define YOUFAIL(message) {WinPopup (message);return;}
#define HELP_SIZE sizeof(help)
#define COLOR_CYCLE_TIME 10000 //milliseconds
#define COLOR_CYCLE (COLOR_CYCLE_TIME / 4)
#define FONT_COUNT (sizeof (fonts) / sizeof (struct glFont))
#define FONT_SIZE (LOGO_PIXELS - LOGO_PIXELS / 8)
#define BLOOM_SCALING 0.07f
#include <cstdio>
#include <ctime>
#include <cstring>
#include <cstdarg>
#include <cmath>
#include <GL/gl.h>
#include <GL/glu.h>
#include "Linux.h"
#include "glTypes.h"
#include "Entity.h"
#include "Car.h"
#include "Camera.h"
#include "Ini.h"
#include "Light.h"
#include "Macro.h"
#include "Math.h"
#include "Render.h"
#include "Sky.h"
#include "Texture.h"
#include "World.h"
#include "Win.h"
static char help[] =
"ESC - Exit!\n"
"F1 - Show this help screen\n"
"R - Rebuild city\n"
"L - Toggle 'letterbox' mode\n"
"F - Show Framecounter\n"
"W - Toggle Wireframe\n"
"E - Change full-scene effects\n"
"T - Toggle Textures\n"
"G - Toggle Fog\n"
;
struct glFont
{
char* name;
unsigned base_char;
} fonts[] =
{
"Courier New", 0,
"Arial", 0,
"Times New Roman", 0,
"Arial Black", 0,
"Impact", 0,
"Agency FB", 0,
"Book Antiqua", 0,
};
#if SCREENSAVER
enum
{
EFFECT_NONE,
EFFECT_BLOOM,
EFFECT_BLOOM_RADIAL,
EFFECT_COLOR_CYCLE,
EFFECT_GLASS_CITY,
EFFECT_COUNT,
EFFECT_DEBUG,
EFFECT_DEBUG_OVERBLOOM,
};
#else
enum
{
EFFECT_NONE,
EFFECT_BLOOM,
EFFECT_COUNT,
EFFECT_DEBUG_OVERBLOOM,
EFFECT_DEBUG,
EFFECT_BLOOM_RADIAL,
EFFECT_COLOR_CYCLE,
EFFECT_GLASS_CITY,
};
#endif
static float render_aspect;
static float fog_distance;
static int render_width;
static int render_height;
static bool letterbox;
static int letterbox_offset;
static int effect;
static unsigned next_fps;
static unsigned current_fps;
static unsigned frames;
static bool show_wireframe;
static bool flat;
static bool show_fps;
static bool show_fog;
static bool show_help;
/*-----------------------------------------------------------------------------
Draw a clock-ish progress.. widget... thing. It's cute.
-----------------------------------------------------------------------------*/
static void do_progress (float center_x, float center_y, float radius, float opacity, float progress)
{
int i;
int end_angle;
float inner, outer;
float angle;
float s, c;
float gap;
//Outer Ring
gap = radius * 0.05f;
outer = radius;
inner = radius - gap * 2;
glColor4f (1,1,1, opacity);
glBegin (GL_QUAD_STRIP);
for (i = 0; i <= 360; i+= 15) {
angle = (float)i * DEGREES_TO_RADIANS;
s = sinf (angle);
c = -cosf (angle);
glVertex2f (center_x + s * outer, center_y + c * outer);
glVertex2f (center_x + s * inner, center_y + c * inner);
}
glEnd ();
//Progress indicator
glColor4f (1,1,1, opacity);
end_angle = (int)(360 * progress);
outer = radius - gap * 3;
glBegin (GL_TRIANGLE_FAN);
glVertex2f (center_x, center_y);
for (i = 0; i <= end_angle; i+= 3) {
angle = (float)i * DEGREES_TO_RADIANS;
s = sinf (angle);
c = -cosf (angle);
glVertex2f (center_x + s * outer, center_y + c * outer);
}
glEnd ();
//Tic lines
glLineWidth (2.0f);
outer = radius - gap * 1;
inner = radius - gap * 2;
glColor4f (0,0,0, opacity);
glBegin (GL_LINES);
for (i = 0; i <= 360; i+= 15) {
angle = (float)i * DEGREES_TO_RADIANS;
s = sinf (angle);
c = -cosf (angle);
glVertex2f (center_x + s * outer, center_y + c * outer);
glVertex2f (center_x + s * inner, center_y + c * inner);
}
glEnd ();
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
static void do_effects (int type)
{
float hue1, hue2, hue3, hue4;
GLrgba color;
float fade;
int radius;
int x, y;
int i;
int bloom_radius;
int bloom_step;
fade = WorldFade ();
bloom_radius = 15;
bloom_step = bloom_radius / 3;
if (!TextureReady () && fade == 0.0f)
return;
//Now change projection modes so we can render full-screen effects
glDisable(GL_DEPTH_TEST);
glMatrixMode (GL_PROJECTION);
glPushMatrix ();
glLoadIdentity ();
glOrtho (0, render_width, render_height, 0, 0.1f, 2048);
glMatrixMode (GL_MODELVIEW);
glPushMatrix ();
glLoadIdentity();
glTranslatef(0, 0, -1.0f);
glDisable (GL_CULL_FACE);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
//Render full-screen effects
glBlendFunc (GL_ONE, GL_ONE);
glEnable (GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, TextureId (TEXTURE_BLOOM));
switch (type) {
case EFFECT_DEBUG:
glBindTexture(GL_TEXTURE_2D, TextureId (TEXTURE_LOGOS));
glDisable (GL_BLEND);
glBegin (GL_QUADS);
glColor3f (1, 1, 1);
glTexCoord2f (0, 0); glVertex2i (0, render_height / 4);
glTexCoord2f (0, 1); glVertex2i (0, 0);
glTexCoord2f (1, 1); glVertex2i (render_width / 4, 0);
glTexCoord2f (1, 0); glVertex2i (render_width / 4, render_height / 4);
glTexCoord2f (0, 0); glVertex2i (0, 512);
glTexCoord2f (0, 1); glVertex2i (0, 0);
glTexCoord2f (1, 1); glVertex2i (512, 0);
glTexCoord2f (1, 0); glVertex2i (512, 512);
glEnd ();
break;
case EFFECT_BLOOM_RADIAL:
//Psychedelic bloom
glEnable (GL_BLEND);
glBegin (GL_QUADS);
color = WorldBloomColor () * BLOOM_SCALING * 2;
glColor3fv (&color.red);
for (i = 0; i <= 100; i+=10) {
glTexCoord2f (0, 0); glVertex2i (-i, i + render_height);
glTexCoord2f (0, 1); glVertex2i (-i, -i);
glTexCoord2f (1, 1); glVertex2i (i + render_width, -i);
glTexCoord2f (1, 0); glVertex2i (i + render_width, i + render_height);
}
glEnd ();
break;
case EFFECT_COLOR_CYCLE:
//Oooh. Pretty colors. Tint the scene according to screenspace.
hue1 = (float)(GetTickCount () % COLOR_CYCLE_TIME) / COLOR_CYCLE_TIME;
hue2 = (float)((GetTickCount () + COLOR_CYCLE) % COLOR_CYCLE_TIME) / COLOR_CYCLE_TIME;
hue3 = (float)((GetTickCount () + COLOR_CYCLE * 2) % COLOR_CYCLE_TIME) / COLOR_CYCLE_TIME;
hue4 = (float)((GetTickCount () + COLOR_CYCLE * 3) % COLOR_CYCLE_TIME) / COLOR_CYCLE_TIME;
glBindTexture(GL_TEXTURE_2D, 0);
glEnable (GL_BLEND);
glBlendFunc (GL_ONE, GL_ONE);
glBlendFunc (GL_DST_COLOR, GL_SRC_COLOR);
glBegin (GL_QUADS);
color = glRgbaFromHsl (hue1, 1.0f, 0.6f);
glColor3fv (&color.red);
glTexCoord2f (0, 0); glVertex2i (0, render_height);
color = glRgbaFromHsl (hue2, 1.0f, 0.6f);
glColor3fv (&color.red);
glTexCoord2f (0, 1); glVertex2i (0, 0);
color = glRgbaFromHsl (hue3, 1.0f, 0.6f);
glColor3fv (&color.red);
glTexCoord2f (1, 1); glVertex2i (render_width, 0);
color = glRgbaFromHsl (hue4, 1.0f, 0.6f);
glColor3fv (&color.red);
glTexCoord2f (1, 0); glVertex2i (render_width, render_height);
glEnd ();
break;
case EFFECT_BLOOM:
//Simple bloom effect
glBegin (GL_QUADS);
color = WorldBloomColor () * BLOOM_SCALING;
glColor3fv (&color.red);
for (x = -bloom_radius; x <= bloom_radius; x += bloom_step) {
for (y = -bloom_radius; y <= bloom_radius; y += bloom_step) {
if (abs (x) == abs (y) && x)
continue;
glTexCoord2f (0, 0); glVertex2i (x, y + render_height);
glTexCoord2f (0, 1); glVertex2i (x, y);
glTexCoord2f (1, 1); glVertex2i (x + render_width, y);
glTexCoord2f (1, 0); glVertex2i (x + render_width, y + render_height);
}
}
glEnd ();
break;
case EFFECT_DEBUG_OVERBLOOM:
//This will punish that uppity GPU. Good for testing low frame rate behavior.
glBegin (GL_QUADS);
color = WorldBloomColor () * 0.01f;
glColor3fv (&color.red);
for (x = -50; x <= 50; x+=5) {
for (y = -50; y <= 50; y+=5) {
glTexCoord2f (0, 0); glVertex2i (x, y + render_height);
glTexCoord2f (0, 1); glVertex2i (x, y);
glTexCoord2f (1, 1); glVertex2i (x + render_width, y);
glTexCoord2f (1, 0); glVertex2i (x + render_width, y + render_height);
}
}
glEnd ();
break;
}
//Do the fade to / from darkness used to hide scene transitions
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable (GL_BLEND);
glDisable (GL_TEXTURE_2D);
glColor4f (0, 0, 0, fade);
glBegin (GL_QUADS);
glVertex2i (0, 0);
glVertex2i (0, render_height);
glVertex2i (render_width, render_height);
glVertex2i (render_width, 0);
glEnd ();
if (TextureReady () && !EntityReady () && fade != 0.0f) {
radius = render_width / 16;
do_progress ((float)render_width / 2, (float)render_height / 2, (float)radius, fade, EntityProgress ());
RenderPrint (render_width / 2 - LOGO_PIXELS, render_height / 2 + LOGO_PIXELS, 0, glRgba (0.5f), "%1.2f%%", EntityProgress () * 100.0f);
RenderPrint (1, "%s v%d.%d.%03d", APP_TITLE, VERSION_MAJOR, VERSION_MINOR, VERSION_REVISION);
}
glPopMatrix ();
glMatrixMode (GL_PROJECTION);
glPopMatrix ();
glMatrixMode (GL_MODELVIEW);
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
int RenderMaxTextureSize ()
{
int mts;
glGetIntegerv(GL_MAX_TEXTURE_SIZE, &mts);
mts = MIN (mts, render_width);
return MIN (mts, render_height);
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void RenderPrint (int x, int y, int font, GLrgba color, const char *fmt, ...)
{
char text[MAX_TEXT];
va_list ap;
text[0] = 0;
if (fmt == NULL)
return;
va_start(ap, fmt);
vsprintf(text, fmt, ap);
va_end(ap);
glPushAttrib(GL_LIST_BIT);
glListBase(fonts[font % FONT_COUNT].base_char - 32);
glColor3fv (&color.red);
glRasterPos2i (x, y);
glCallLists(strlen(text), GL_UNSIGNED_BYTE, text);
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void RenderPrint (int line, const char *fmt, ...)
{
char text[MAX_TEXT];
va_list ap;
text[0] = 0;
if (fmt == NULL)
return;
va_start (ap, fmt);
vsprintf (text, fmt, ap);
va_end (ap);
glDepthMask (false);
glMatrixMode (GL_PROJECTION);
glPushMatrix ();
glLoadIdentity ();
glOrtho (0, render_width, render_height, 0, 0.1f, 2048);
glDisable(GL_DEPTH_TEST);
glMatrixMode (GL_MODELVIEW);
glPushMatrix ();
glLoadIdentity();
glTranslatef(0, 0, -1.0f);
glEnable (GL_BLEND);
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glDisable (GL_DEPTH_TEST);
RenderPrint (0, line * FONT_SIZE - 2, 0, glRgba (0.0f), text);
RenderPrint (4, line * FONT_SIZE + 2, 0, glRgba (0.0f), text);
RenderPrint (2, line * FONT_SIZE, 0, glRgba (1.0f), text);
glPopAttrib();
glPopMatrix ();
glMatrixMode (GL_PROJECTION);
glPopMatrix ();
glMatrixMode (GL_MODELVIEW);
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void static do_help (void)
{
char* text;
int line;
char parse[HELP_SIZE];
int x;
strcpy (parse, help);
line = 0;
text = strtok (parse, "\n");
x = 10;
while (text) {
RenderPrint (line + 1, text);
text = strtok (NULL, "\n");
line++;
}
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void RenderResize (void)
{
float fovy;
render_width = WinWidth ();
render_height = WinHeight ();
if (letterbox) {
letterbox_offset = render_height / 6;
render_height = render_height - letterbox_offset * 2;
} else
letterbox_offset = 0;
//render_aspect = (float)render_height / (float)render_width;
glViewport (0, letterbox_offset, render_width, render_height);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
render_aspect = (float)render_width / (float)render_height;
fovy = 60.0f;
if (render_aspect > 1.0f)
fovy /= render_aspect;
gluPerspective (fovy, render_aspect, 0.1f, RENDER_DISTANCE);
glMatrixMode (GL_MODELVIEW);
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void RenderTerm (void)
{
//if (!hRC)
// return;
//wglDeleteContext (hRC);
//hRC = NULL;
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void RenderInit (void)
{
//HWND hWnd;
// unsigned PixelFormat;
//HFONT font;
// HFONT oldfont;
//hWnd = WinHwnd ();
//if (!(hDC = GetDC (hWnd)))
// YOUFAIL ("Can't Create A GL Device Context.") ;
// if (!(PixelFormat = ChoosePixelFormat(hDC,&pfd)))
// YOUFAIL ("Can't Find A Suitable PixelFormat.") ;
//if(!SetPixelFormat(hDC,PixelFormat,&pfd))
// YOUFAIL ("Can't Set The PixelFormat.");
// if (!(hRC = wglCreateContext (hDC)))
// YOUFAIL ("Can't Create A GL Rendering Context.");
//if(!wglMakeCurrent(hDC,hRC))
// YOUFAIL ("Can't Activate The GL Rendering Context.");
////Load the fonts for printing debug info to the window.
//for (int i = 0; i < FONT_COUNT; i++) {
// fonts[i].base_char = glGenLists(96);
// font = CreateFont (FONT_SIZE, 0, 0, 0,
// FW_BOLD, FALSE, FALSE, FALSE, DEFAULT_CHARSET, OUT_TT_PRECIS,
// CLIP_DEFAULT_PRECIS, ANTIALIASED_QUALITY, FF_DONTCARE|DEFAULT_PITCH,
// fonts[i].name);
// oldfont = (HFONT)SelectObject(hDC, font);
// wglUseFontBitmaps(hDC, 32, 96, fonts[i].base_char);
// SelectObject(hDC, oldfont);
// DeleteObject(font);
//}
////If the program is running for the first time, set the defaults.
//if (!IniInt ("SetDefaults")) {
// IniIntSet ("SetDefaults", 1);
// IniIntSet ("Effect", EFFECT_BLOOM);
// IniIntSet ("ShowFog", 1);
//}
////load in our settings
//letterbox = IniInt ("Letterbox") != 0;
//show_wireframe = IniInt ("Wireframe") != 0;
//show_fps = IniInt ("ShowFPS") != 0;
//show_fog = IniInt ("ShowFog") != 0;
//effect = IniInt ("Effect");
//flat = IniInt ("Flat") != 0;
//fog_distance = WORLD_HALF;
////clear the viewport so the user isn't looking at trash while the program starts
//glViewport (0, 0, WinWidth (), WinHeight ());
//glClearColor (0.0f, 0.0f, 0.0f, 1.0f);
//glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//SwapBuffers (hDC);
//RenderResize ();
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void RenderFPSToggle ()
{
show_fps = !show_fps;
IniIntSet ("ShowFPS", show_fps ? 1 : 0);
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
bool RenderFog ()
{
return show_fog;
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void RenderFogToggle ()
{
show_fog = !show_fog;
IniIntSet ("ShowFog", show_fog ? 1 : 0);
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void RenderLetterboxToggle ()
{
letterbox = !letterbox;
IniIntSet ("Letterbox", letterbox ? 1 : 0);
RenderResize ();
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void RenderWireframeToggle ()
{
show_wireframe = !show_wireframe;
IniIntSet ("Wireframe", show_wireframe ? 1 : 0);
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
bool RenderWireframe ()
{
return show_wireframe;
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void RenderEffectCycle ()
{
effect = (effect + 1) % EFFECT_COUNT;
IniIntSet ("Effect", effect);
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
bool RenderBloom ()
{
return effect == EFFECT_BLOOM || effect == EFFECT_BLOOM_RADIAL
|| effect == EFFECT_DEBUG_OVERBLOOM || effect == EFFECT_COLOR_CYCLE;
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
bool RenderFlat ()
{
return flat;
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void RenderFlatToggle ()
{
flat = !flat;
IniIntSet ("Flat", flat ? 1 : 0);
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void RenderHelpToggle ()
{
show_help = !show_help;
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
float RenderFogDistance ()
{
return fog_distance;
}
/*-----------------------------------------------------------------------------
-----------------------------------------------------------------------------*/
void RenderUpdate (void)
{
GLvector pos;
GLvector angle;
GLrgba color;
glViewport (0, 0, WinWidth (), WinHeight ());
glClearColor (0.0f, 0.0f, 0.0f, 1.0f);
if (letterbox)
glViewport (0, letterbox_offset, render_width, render_height);
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (TextureReady () && !EntityReady ()) {
do_effects (-1);
SwapBuffers();
return;
}
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glShadeModel(GL_SMOOTH);
glFogi (GL_FOG_MODE, GL_LINEAR);
if (show_fog) {
glEnable (GL_FOG);
glFogf (GL_FOG_START, fog_distance - 100);
glFogf (GL_FOG_END, fog_distance);
color = glRgba (0.0f);
glFogfv (GL_FOG_COLOR, &color.red);
} else
glDisable (GL_FOG);
glDepthFunc(GL_LEQUAL);
glEnable(GL_DEPTH_TEST);
glEnable (GL_CULL_FACE);
glCullFace (GL_BACK);
glEnable (GL_BLEND);
glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glMatrixMode (GL_TEXTURE);
glLoadIdentity();
glMatrixMode (GL_MODELVIEW);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
glLoadIdentity();
glLineWidth (1.0f);
pos = CameraPosition ();
angle = CameraAngle ();
glRotatef (angle.x, 1.0f, 0.0f, 0.0f);
glRotatef (angle.y, 0.0f, 1.0f, 0.0f);
glRotatef (angle.z, 0.0f, 0.0f, 1.0f);
glTranslatef (-pos.x, -pos.y, -pos.z);
glEnable (GL_TEXTURE_2D);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
//Render all the stuff in the whole entire world.
SkyRender ();
WorldRender ();
if (effect == EFFECT_GLASS_CITY) {
glDisable (GL_CULL_FACE);
glEnable (GL_BLEND);
glBlendFunc (GL_ONE, GL_ONE);
glDepthFunc (false);
glDisable(GL_DEPTH_TEST);
glMatrixMode (GL_TEXTURE);
glTranslatef ((pos.x + pos.z) / SEGMENTS_PER_TEXTURE, 0, 0);
glMatrixMode (GL_MODELVIEW);
} else {
glEnable (GL_CULL_FACE);
glDisable (GL_BLEND);
}
EntityRender ();
LightRender ();
CarRender ();
if (show_wireframe) {
glDisable (GL_TEXTURE_2D);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
EntityRender ();
}
do_effects (effect);
//Framerate tracker
if (GetTickCount () > next_fps) {
current_fps = frames;
frames = 0;
next_fps = GetTickCount () + 1000;
}
if (show_fps && !show_help) {
RenderPrint (1, "FPS=%d", current_fps);
RenderPrint (2, "Entities=%d", EntityCount () + LightCount () + CarCount ());
RenderPrint (3, "Lights=%d", LightCount ());
RenderPrint (4, "Polys=%d", EntityPolyCount () + LightCount () + CarCount ());
RenderPrint (5, "Building=%1.2f", EntityProgress () * 100);
}
//Show the help overlay
if (show_help)
do_help ();
glDepthMask (true);
frames++;
SwapBuffers();
}
| [
"youngshamus@c6164f88-37c5-11de-9d05-31133e6853b1",
"[email protected]"
]
| [
[
[
1,
24
],
[
47,
469
],
[
474,
483
],
[
532,
695
],
[
697,
772
],
[
774,
775
]
],
[
[
25,
46
],
[
470,
473
],
[
484,
531
],
[
696,
696
],
[
773,
773
]
]
]
|
3c74df4ec9214b276ed6cbc2346a129dd87980a4 | e02fa80eef98834bf8a042a09d7cb7fe6bf768ba | /MyGUIEngine/include/MyGUI_Message.h | 72917c6b0b63e4c6ae3040bbe0ed9a65a69b3cde | []
| no_license | MyGUI/mygui-historical | fcd3edede9f6cb694c544b402149abb68c538673 | 4886073fd4813de80c22eded0b2033a5ba7f425f | refs/heads/master | 2021-01-23T16:40:19.477150 | 2008-03-06T22:19:12 | 2008-03-06T22:19:12 | 22,805,225 | 2 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 5,712 | h | /*!
@file
@author Albert Semenov
@date 01/2008
@module
*/
#ifndef __MYGUI_MESSAGE_H__
#define __MYGUI_MESSAGE_H__
#include "MyGUI_Prerequest.h"
#include "MyGUI_Window.h"
namespace MyGUI
{
class _MyGUIExport Message : public Window
{
// для вызова закрытого конструктора
friend class factory::MessageFactory;
public:
enum ViewValueInfo
{
None = FLAG_NONE,
Ok = FLAG(0),
Yes = FLAG(1),
No = FLAG(2),
Abort = FLAG(3),
Retry = FLAG(4),
Ignore = FLAG(5),
Cancel = FLAG(6),
Try = FLAG(7),
Continue = FLAG(8),
Button1 = FLAG(9),
Button2 = FLAG(10),
Button3 = FLAG(11),
Button4 = FLAG(12),
Button5 = FLAG(13),
Button6 = FLAG(14),
Button7 = FLAG(15),
OkCancel = Ok | Cancel,
YesNo = Yes | No,
YesNoCancel = Yes | No | Cancel,
RetryCancel = Retry | Cancel,
AbortRetryIgnore = Abort | Retry | Ignore,
CancelTryContinue = Cancel | Try | Continue,
IconDefault = FLAG(16),
IconInfo = FLAG(16),
IconQuest = FLAG(17),
IconError = FLAG(18),
IconWarning = FLAG(19),
Icon1 = FLAG(16),
Icon2 = FLAG(17),
Icon3 = FLAG(18),
Icon4 = FLAG(19),
Icon5 = FLAG(20),
Icon6 = FLAG(21),
Icon7 = FLAG(22),
Icon8 = FLAG(23),
};
typedef size_t ViewInfo;
typedef delegates::CDelegate2<WidgetPtr, ViewInfo> EventInfo_WidgetMessage;
typedef delegates::IDelegate2<WidgetPtr, ViewInfo> EventMessageEnd;
protected:
Message(const IntCoord& _coord, char _align, const WidgetSkinInfoPtr _info, CroppedRectanglePtr _parent, const Ogre::String & _name);
void updateSize();
void notifyButtonClick(MyGUI::WidgetPtr _sender);
void clearButton();
void _onKeyButtonPressed(int _key, Char _char);
void _destroyMessage(ViewInfo _result);
public:
// тип данного виджета
inline static const Ogre::String & _getType() {static Ogre::String type("Message"); return type;}
virtual const Ogre::String & getWidgetType() { return _getType(); }
/** setMessage text*/
void setMessage(const Ogre::DisplayString & _message);
/** Create button with specific name*/
Message::ViewInfo addButtonName(const Ogre::DisplayString & _name);
/** Create button using ViewValueInfo*/
void setButton(ViewInfo _info);
/** set smooth Window showing*/
void setSmoothShow(bool _smooth);
/** get name of default layer*/
inline const std::string & getDefaultLayer() {return mDefaultLayer;}
void setMessageImage(size_t _image);
void setWindowFade(bool _fade);
/** static method for creating message with one command
@param
_modal if true all other GUI elements will be blocked untill message is closed
@param
_delegate event called on message close. void method(MyGUI::WidgetPtr _sender, MyGUI::Message::ViewInfo _button);
@param
_info any combination of flags from ViewValueInfo
@param
_button1 ... _button7 specific buttons names
*/
static MyGUI::MessagePtr _createMessage(const Ogre::DisplayString & _caption, const Ogre::DisplayString & _message,
const std::string & _skin, const std::string & _layer, bool _modal, EventMessageEnd * _delegate, ViewInfo _info,
const std::string & _button1 = "", const std::string & _button2 = "", const std::string & _button3 = "", const std::string & _button4 = "",
const std::string & _button5 = "", const std::string & _button6 = "", const std::string & _button7 = "");
/** see Message::_createMessage*/
inline static MyGUI::MessagePtr createMessage(const Ogre::DisplayString & _caption, const Ogre::DisplayString & _message, bool _modal, ViewInfo _info)
{
return _createMessage(_caption, _message, "", "", _modal, null, _info);
}
/** see Message::_createMessage*/
inline static MyGUI::MessagePtr createMessage(const Ogre::DisplayString & _caption, const Ogre::DisplayString & _message, bool _modal, EventMessageEnd * _delegate, ViewInfo _info)
{
return _createMessage(_caption, _message, "", "", _modal, _delegate, _info);
}
/** see Message::_createMessage*/
inline static MyGUI::MessagePtr createMessage(const Ogre::DisplayString & _caption, const Ogre::DisplayString & _message, bool _modal,
const std::string & _button1, const std::string & _button2 = "", const std::string & _button3 = "")
{
return _createMessage(_caption, _message, "", "", _modal, null, None, _button1, _button2, _button3);
}
/** see Message::_createMessage*/
inline static MyGUI::MessagePtr createMessage(const Ogre::DisplayString & _caption, const Ogre::DisplayString & _message, bool _modal,
EventMessageEnd * _delegate, const std::string & _button1, const std::string & _button2 = "", const std::string & _button3 = "")
{
return _createMessage(_caption, _message, "", "", _modal, _delegate, None, _button1, _button2, _button3);
}
public:
/* событие : надата кнопка на окне сообщений*/
/* прототип делегата : void method(MyGUI::WidgetPtr _sender, MyGUI::Message::ViewInfo _button);*/
EventInfo_WidgetMessage eventMessageBoxEnd;
private:
IntSize mOffsetText;
WidgetPtr mWidgetText;
std::string mButtonSkin, mButtonType;
IntSize mButtonSize, mButtonOffset;
VectorWidgetPtr mVectorButton;
ViewInfo mInfoOk, mInfoCancel;
size_t mButton1Index;
bool mSmoothShow;
std::string mDefaultLayer, mDefaultCaption;
std::string mFadeSkin, mFadeLayer;
WidgetPtr mWidgetFade;
StaticImagePtr mIcon;
}; // class _MyGUIExport Message : public Window
} // namespace MyGUI
#endif // __MYGUI_MESSAGE_H__
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
84
],
[
86,
87
],
[
89,
90
],
[
92,
93
],
[
96,
96
],
[
98,
101
],
[
112,
116
],
[
118,
122
],
[
124,
128
],
[
130,
135
],
[
137,
144
],
[
146,
157
],
[
159,
168
]
],
[
[
85,
85
],
[
88,
88
],
[
91,
91
],
[
94,
95
],
[
97,
97
],
[
102,
111
],
[
117,
117
],
[
123,
123
],
[
129,
129
],
[
136,
136
],
[
145,
145
],
[
158,
158
]
]
]
|
348f19541b7cc3cc02c550c28d3a057f9975d612 | 59166d9d1eea9b034ac331d9c5590362ab942a8f | /XMLTree2Geom/osg/nodes/osgNodeFronds.h | 798a56ea19e0596f55fa3c06ecaf7decced7383e | []
| no_license | seafengl/osgtraining | 5915f7b3a3c78334b9029ee58e6c1cb54de5c220 | fbfb29e5ae8cab6fa13900e417b6cba3a8c559df | refs/heads/master | 2020-04-09T07:32:31.981473 | 2010-09-03T15:10:30 | 2010-09-03T15:10:30 | 40,032,354 | 0 | 3 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 647 | h | #ifndef _OSG_NODE_FRONDS_H_
#define _OSG_NODE_FRONDS_H_
#include <osg/Referenced>
#include <osg/ref_ptr>
#include <osg/Geode>
class osgNodeFronds
{
public:
osgNodeFronds();
~osgNodeFronds();
//сохранить ветки по LOD'ам
void LODSave();
private:
//инициировать корневой узел данными
osg::ref_ptr< osg::Geode > InitFrondsGeode( int iLOD );
//настроить альфа канал
void SetupAlfaFunc( osg::ref_ptr< osg::Geode > geode , int iLOD );
//добавить текстуру
void AddTexture( osg::StateSet* state );
};
#endif //_OSG_NODE_FRONDS_H_ | [
"asmzx79@3290fc28-3049-11de-8daa-cfecb5f7ff5b"
]
| [
[
[
1,
28
]
]
]
|
26c37aa5f932378740a2e81b85a6d4a2645eeeec | 7383a6f68018334aca3b7b3ca931e917ae86141f | /klu/klulib/stdafx.cpp | 3eb62568010eefab3cc8c4ae160e19fe4003704e | []
| no_license | gotomypc/klucv2 | b1449cc6da998207a042d13621f3c261774bbb0f | 0340889c97318e7816ec9f007dfcc510e3a06cf9 | refs/heads/master | 2016-09-05T09:22:40.043359 | 2010-03-23T21:27:49 | 2010-03-23T21:27:49 | 35,355,430 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 383 | cpp | /**
* Copyright (C) 2010, Konrad Kleine and Jens Lukowski, all rights reserved.
*/
// stdafx.cpp : source file that includes just the standard includes
// klulib.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"[email protected]@842311ce-0f2e-11df-ac28-27e10010dbf6"
]
| [
[
[
1,
12
]
]
]
|
452b0a1627d6bf1a5dab82d1c24e571a11e3a6d0 | 0bab4267636e3b06cb0e73fe9d31b0edd76260c2 | /freewar-alpha/src/before_starting_game.cpp | 6a8660ac2be3c1372431eeae72859f61d1035c30 | []
| no_license | BackupTheBerlios/freewar-svn | 15fafedeed3ea1d374500d3430ff16b412b2f223 | aa1a28f19610dbce12be463d5ccd98f712631bc3 | refs/heads/master | 2021-01-10T19:54:11.599797 | 2006-12-10T21:45:11 | 2006-12-10T21:45:11 | 40,725,388 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,038 | cpp | //
// before_starting_game.cpp for freewar in /u/ept2/huot_j
//
// Made by jonathan huot
// Login <[email protected]>
//
// Started on Fri May 7 13:37:58 2004 jonathan huot
// Last update Sun Jul 11 18:08:36 2004
//
#include "freewar.h"
int init_server_connection(t_trame *req);
int server_connections(t_game_param *gp);
int before_starting_game(t_game_param *game_param)//t_engine *e, t_game_param *game_param)
{
t_trame *req;
int who_serve;
int send;
int update_param;
// //considere que le jeu cree une partie tout seul:
// printf("before start\n");
// fflush(fd_log);
return (HOME);
req = (t_trame*)xmalloc(sizeof(*req));
for (who_serve = NONE, send = 0, update_param = 0;
42; send = 0, update_param = 0)
/* < va gerer les requetes que va envoyer le jeu pour la creation
de partie jusque a le lancemant de la partie; et les requetes des
autres moteur.*/
{
printf("ESSAI\n");fflush(stdout);
fflush(fd_log);
if (check_select(10000))
{
printf("DEDAN\n");fflush(stdout);
if (exec_msg(&cnt->clients[0], req))
{
if (is_valid_trame(req, TAG_JOIN))
{
join_game(req);
// send_hash5_to_server(); // une
//if (!ok) // seule
// upgrade_BDD; // fois
// get_game_param_from_server(req, game_param);
who_serve = REMOTE;
// send_to_all_player_new_game_status(game_param);
// ^ envoi au client local les parametre de la partie
}
else if (is_valid_trame(req, TAG_CREATE))
{
// init_game_param(game_param, req, (t_pos*)&pos);
who_serve = HOME;
// send_to_all_player_new_game_status(game_param);
}
// else if (who_serve && is_valid_trame(req, TAG_LAUNCH_GAME))
// return (who_serve);
else if (who_serve == HOME)
//rentre ici quand le jeu est server.
{
/* GERAGE DES CONNECTIONS */
// server_connections(game_param, (t_pos*)&pos);
if (is_valid_trame(req, TAG_LAUNCH_GAME))
{
t_tmp *list;
for (list = cnt->newclient; list; list = list->next)
stock_msg(&list->c, TAG_LAUNCH_GAME, 0, NULL);
// move_clients_to_players(e, game_param);
return (who_serve);
}
/* GERAGE DE LA REQUETE */
// if (update_game_param(req, game_param, pos) ||
// va gerer les changements de param
// ot_chose()) || //finctions qui va gerer les autres requetes
// send_to_all_player_new_game_status(game_param))
// return (put_error("trame gerage failed"));
if (is_valid_trame(req, TAG_LEAVE))
who_serve = NONE;
}
else if (who_serve == REMOTE)
{
// verifier que l'on soit tjrs connecter au server
if (cnt->server.sock)
who_serve = NONE;
// if (cnt->last_recv->sock == cnt->server.sock &&
// is_valid_trame(req, TAG_GAME_STATUS))
// {
// if (copy_game_param(req, game_param))
// return (put_error("update_game_param failed"));
// }
// else if (cnt->last_recv->sock == cnt->clients[0].sock &&
// is_valid_trame(req, TAG_GP_PLAYERS))
// {
// if (send_to_all_player_new_game_status(game_param))
// return (put_error("send_to_all_player_new_game_status failed"));
// }
if (is_valid_trame(req, TAG_LEAVE))
who_serve = NONE;
}
}
else
{
t_tmp *list;
printf("DANS LE ELSE\n");fflush(stdout);
for (list = cnt->newclient; list; list = list->next)
{
if (exec_msg(&list->c, req))
{
if (is_valid_trame(req, TAG_JOIN))
{
fprintf(fd_log, "un joueur est la\n");
list->state = STATE_PLAYER;
return (HOME);
}
else
fprintf(fd_log, "un nouveau client me parle :%d.. alors qu'il devrait attendre"
"sagement\n", req->tag);
}
}
fprintf(fd_log, "les autres joueurs parlent\n");
// d'autres requetes ? (READY...)
}
}
}
return (ERROR);
}
| [
"doomsday@b2c3ed95-53e8-0310-b220-efb193137011"
]
| [
[
[
1,
130
]
]
]
|
59c05adc329f5c8516507d4b5a034c93c00e53e2 | 619941b532c6d2987c0f4e92b73549c6c945c7e5 | /Include/Nuclex/Audio/Sound.h | 1183907956ab150d69c2b6b63f8c0dfb94844ea2 | []
| no_license | dzw/stellarengine | 2b70ddefc2827be4f44ec6082201c955788a8a16 | 2a0a7db2e43c7c3519e79afa56db247f9708bc26 | refs/heads/master | 2016-09-01T21:12:36.888921 | 2008-12-12T12:40:37 | 2008-12-12T12:40:37 | 36,939,169 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,085 | h | // //
// # # ### # # -= Nuclex Library =- //
// ## # # # ## ## Sound.h - Active sound //
// ### # # ### //
// # ### # ### Controls a sound while it is playing //
// # ## # # ## ## //
// # # ### # # R1 (C)2002-2004 Markus Ewald -> License.txt //
// //
#ifndef NUCLEX_AUDIO_SOUND_H
#define NUCLEX_AUDIO_SOUND_H
#include "Nuclex/Nuclex.h"
#include "Nuclex/Math/Point3.h"
namespace Nuclex { namespace Audio {
// //
// Nuclex::Audio::Sound //
// //
/// Active sound
/** Controls a sound that is playing in 3D space with location und velocity.
*/
class Sound {
public:
enum SampleFormat {
SF_NONE = 0, ///< None or unknown
SF_11025_8, ///< 11025 Hz 8 Bit
SF_22050_8, ///< 22050 Hz 8 Bit
SF_44100_8, ///< 44100 Hz 8 Bit
SF_11025_16, ///< 11025 Hz 16 Bit
SF_22050_16, ///< 22050 Hz 16 Bit
SF_44100_16 ///< 44100 Hz 16 Bit
};
/// Get *bytes* per second from sample format
NUCLEX_API inline static size_t bpsFromFormat(SampleFormat eFormat);
/// Destructor
NUCLEX_API virtual ~Sound() {}
//
// ISound implementation
//
public:
/// Retrieve the sound's current position
/** Returns the sound's position
@return The sound's current position
*/
NUCLEX_API virtual const Point3<real> &getPosition() const = 0;
/// Sets the sound's position
/** Moves the sound source to the specified position
@param Position New sound source position
*/
NUCLEX_API virtual void setPosition(const Point3<real> &Position) = 0;
/// Retrieve the sound's current velocity
/** Returns the sound's velocity
@return The sound's current velocity
*/
NUCLEX_API virtual const Vector3<real> &getVelocity() const = 0;
/// Sets the sound's velocity
/** Moves the sound source to the specified velocity
@param Velocity New sound source velocity
*/
NUCLEX_API virtual void setVelocity(const Vector3<real> &Velocity) = 0;
};
// ############################################################################################# //
// # Nuclex::Audio::Sound::bpsFromFormat() # //
// ############################################################################################# //
/** Retrieves the number of *bytes* per second of the specified format
@param eFormat Format of which to retrieve the bps
@return The number of *bytes* per second in the specified format
*/
inline size_t Sound::bpsFromFormat(SampleFormat eFormat) {
switch(eFormat) {
case Sound::SF_11025_8: return 11025;
case Sound::SF_22050_8: return 22050;
case Sound::SF_44100_8: return 44100;
case Sound::SF_11025_16: return 11025 * 2;
case Sound::SF_22050_16: return 22050 * 2;
case Sound::SF_44100_16: return 44100 * 2;
default: return 0;
}
}
}} // namespace Nuclex::Audio
#endif // NUCLEX_AUDIO_SOUND_H
| [
"ctuoMail@5f320639-c338-0410-82ad-c55551ec1e38"
]
| [
[
[
1,
93
]
]
]
|
a25cd607f92b4789beb7173ffad385a4660813c6 | 46f6d6003ed790e6b4a735ef9baf087d45d2d29b | /Previewer/Source/Application/PreviewerView.cpp | f6c4a02b22807a3ccdbad72eb80ec7f324b5c444 | []
| no_license | larrson/metashader | ff8cb7b6912057f601113a437e2310ebb8fcf760 | fb56ad3ee7df1b84a7ffd4a037cbf9a22e891e48 | refs/heads/master | 2021-01-19T18:53:11.362265 | 2011-07-12T11:09:56 | 2011-07-12T11:09:56 | 35,814,208 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 3,211 | cpp | /**
@file PreviewerView.cpp
@brief プレビューア用Viewクラス
*/
// Includes ----------------------------------------------------------------------------------
#include "stdafx.h"
#include "CameraController.h"
#include "Graphics/Model.h"
#include "PreviewerView.h"
namespace opk
{
// Global Variable Definitions ---------------------------------------------------------------
namespace
{
const char* c_pszModelFilePath = "..\\..\\data\\model\\Sphere.x";
}
// Function Definitions ----------------------------------------------------------------------
//------------------------------------------------------------------------------------------
CPreviewerView::CPreviewerView()
{
m_pModel = new CModel();
m_pMouseHandler = new CCameraController();
}
//------------------------------------------------------------------------------------------
CPreviewerView::~CPreviewerView()
{
SAFE_DELETE( m_pModel );
SAFE_DELETE( m_pMouseHandler );
}
//------------------------------------------------------------------------------------------
LRESULT CPreviewerView::MsgProc( HWND i_hWnd, int i_nMsg, WPARAM i_wParam, LPARAM i_lParam )
{
// マウスハンドラへ処理を移譲
return m_pMouseHandler->OnMsgProc( i_hWnd, i_nMsg, i_wParam, i_lParam );
}
//------------------------------------------------------------------------------------------
void CPreviewerView::Update( float i_fElapsedTime )
{
}
//------------------------------------------------------------------------------------------
void CPreviewerView::Render()
{
CGraphicDevice* pDevice = CApp::GetInstance()->GetGraphicDevice(); MY_ASSERT( pDevice );
// カメラ設定
CCameraController *pCameraController = dynamic_cast<CCameraController*>( m_pMouseHandler );
pDevice->SetCameraInfo( pCameraController->GetCameraInfo() );
// ライト設定
// 0 Fill
D3DXVECTOR3 vLightDir0( 1, -1, -1); D3DXVec3Normalize( &vLightDir0, &vLightDir0);
pDevice->SetDirLightDir( 0, vLightDir0.x, vLightDir0.y, vLightDir0.z );
pDevice->SetDirLightColor( 0, 1.0f, 1.0f, 1.0f );
// 1 Back
D3DXVECTOR3 vLightDir1( 0, 0, -1); D3DXVec3Normalize( &vLightDir1, &vLightDir1);
pDevice->SetDirLightDir( 1, vLightDir1.x, vLightDir1.y, vLightDir1.z );
pDevice->SetDirLightColor( 1, 0.0f, 0.0f, 0.0f );
// 2 Key
D3DXVECTOR3 vLightDir2( -1, -1, 0); D3DXVec3Normalize( &vLightDir2, &vLightDir2);
pDevice->SetDirLightDir( 2, vLightDir2.x, vLightDir2.y, vLightDir2.z );
pDevice->SetDirLightColor( 2, 0.0f, 0.0f, 0.0f );
// モデルをレンダリング
m_pModel->Render();
}
//------------------------------------------------------------------------------------------
void CPreviewerView::Attach()
{
}
//------------------------------------------------------------------------------------------
void CPreviewerView::Restore()
{
// モデル初期化
std::string strModelFilePath = std::string(CApp::GetInstance()->GetApplicationDirectory());
strModelFilePath.append(c_pszModelFilePath);
m_pModel->LoadFromFile( strModelFilePath );
}
} // end of namespace opk
| [
"[email protected]@a50acfb0-bd1f-d52a-3783-6e72a8704c9b"
]
| [
[
[
1,
90
]
]
]
|
e061a6a7aa6adb4a3abd8d01b2a2fe7971b3ab2c | 6d680e20e4a703f0aa0d4bb5e50568143241f2d5 | /src/MobiHealth/Action.h | 69b8d52883631a215b7094058e7a777031ce74ec | []
| no_license | sirnicolaz/MobiHealt | f7771e53a4a80dcea3d159eca729e9bd227e8660 | bbfd61209fb683d5f75f00bbf81b24933922baac | refs/heads/master | 2021-01-20T12:21:17.215536 | 2010-04-21T14:21:16 | 2010-04-21T14:21:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,444 | h | #ifndef ACTION_H
#define ACTION_H
#include <QtGui/QWidget>
#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
#include <QStackedLayout>
#include <QHBoxLayout>
#include "ui_Action.h"
#include "GenericStep.h"
#include "DescriptorHandler.h"
#include <vector>
using namespace std;
class ActionMenu;
class ButtonLabel;
class ChangePatientFooter;
class QLabel;
class Action : public QWidget
{
Q_OBJECT
public:
Action(DescriptorHandler * actionDescriptor_in, QWidget *parent = 0);
~Action();
DescriptorHandler* getActionDescriptor();
bool isLastStep();
private:
Ui::ActionClass ui;
/* identifier */
QString ID;
//QWidget *parent;
DescriptorHandler *actionDescriptor;
/* user interface widgets */
ButtonLabel *nextButton;
ButtonLabel *backButton;
QVBoxLayout *mainLayout;
QHBoxLayout *buttonsLayout;
QStackedLayout *stepsLayout;
QLabel *loadingImage;
/* action1 steps (will be an array) */
vector<GenericStep*> steps;
/* reference to the footer object */
ChangePatientFooter *footer;
void setBackgroundImage();
void saveStep(GenericStep *);
public slots:
/* action1 wizard slots */
void nextStep();
void preStep();
void finishButtonSlot();
protected:
virtual GenericStep * createStep(int stepNumber);
};
#endif // ACTION_H
| [
"[email protected]"
]
| [
[
[
1,
71
]
]
]
|
97aa4f09c951093ac6cd19a23e2ec9d246fb6858 | b22c254d7670522ec2caa61c998f8741b1da9388 | /dependencies/OpenSceneGraph/include/osgIntrospection/Reflection | 50ccc03c1b0459841c0acc9e5923c60c47b3e2e3 | []
| no_license | ldaehler/lbanet | 341ddc4b62ef2df0a167caff46c2075fdfc85f5c | ecb54fc6fd691f1be3bae03681e355a225f92418 | refs/heads/master | 2021-01-23T13:17:19.963262 | 2011-03-22T21:49:52 | 2011-03-22T21:49:52 | 39,529,945 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,728 | /* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
//osgIntrospection - Copyright (C) 2005 Marco Jez
#ifndef OSGINTROSPECTION_REFLECTION_
#define OSGINTROSPECTION_REFLECTION_
#include <osgIntrospection/Export>
#include <osgIntrospection/ExtendedTypeInfo>
#include <typeinfo>
#include <map>
#include <vector>
#include <list>
/// This macro emulates the behavior of the standard typeid operator,
/// returning the Type object associated to the type of the given
/// expression.
#define typeof(type) osgIntrospection::Reflection::getType(extended_typeid< type >())
#define typeofvalue(val) osgIntrospection::Reflection::getType(osgIntrospection::ExtendedTypeInfo(typeid(val), false, false))
namespace osgIntrospection
{
class Type;
struct Converter;
typedef std::list<const Converter* > ConverterList;
/// A map of types, indexed by their associated ExtendedTypeInfo
/// structure.
typedef std::map<ExtendedTypeInfo, Type*> TypeMap;
enum CastType
{
STATIC_CAST,
DYNAMIC_CAST,
REINTERPRET_CAST,
COMPOSITE_CAST
};
/// This class provides basic reflection services such as registration
/// of new types and queries on the global type map.
class OSGINTROSPECTION_EXPORT Reflection
{
public:
/// Returns the Type object associated to the given
/// ExtendedTypeInfo structure. If the type hasn't been created
/// yet it is automatically created and added to the global type
/// map. Please note that such type will have the status of
/// "declared", you still need to give details about it through
/// a Reflector class before you can query it.
static const Type& getType(const ExtendedTypeInfo &ti);
/// Finds a Type object given its qualified name, which must
/// be identical to the qualified name returned by that Type's
/// getQualifiedName() method. If the type hasn't been created
/// yet, an exception is thrown.
static const Type& getType(const std::string& qname);
/// Returns the global map of types.
static const TypeMap& getTypes();
/// Return the Type object associated to the C++ type 'void'.
/// This is a shortcut for typeof(void), which may be slow if
/// the type map is large.
static const Type& type_void();
static const Converter* getConverter(const Type& source, const Type& dest);
static bool getConversionPath(const Type& source, const Type& dest, ConverterList& conv);
// This function should be called (at least on windows platforms using Visual Studio 7.1 or 8 as compiler) to unregister
// all the known types before exiting your program: otherwise, you will get a lot of false positive memory leaks in debug builds.
// It might also be used to dynamically reload the description of the known types (?)
static void uninitialize();
private:
template<typename C> friend class Reflector;
template<typename C> friend struct TypeNameAliasProxy;
friend struct ConverterProxy;
struct StaticData
{
TypeMap typemap;
const Type* type_void;
typedef std::map<const Type* , const Converter* > ConverterMap;
typedef std::map<const Type* , ConverterMap> ConverterMapMap;
ConverterMapMap convmap;
~StaticData();
};
static StaticData& getOrCreateStaticData();
static Type* registerType(const ExtendedTypeInfo &ti);
static Type* getOrRegisterType(const ExtendedTypeInfo &ti, bool replace_if_defined = false);
static void registerConverter(const Type& source, const Type& dest, const Converter* cvt);
private:
static bool accum_conv_path(const Type& source, const Type& dest, ConverterList& conv, std::vector<const Type* > &chain, CastType castType);
static StaticData* _static_data;
};
}
#endif
| [
"vdelage@3806491c-8dad-11de-9a8c-6d5b7d1e4d13"
]
| [
[
[
1,
116
]
]
]
|
|
8865a1b8978429681dfd19075d58dcac3068f381 | 9891c65690bfc3d774285ccfbd4733c2ad249d5a | /ok/ok/AssemblyInfo.cpp | c1bc319f26a6b93fdf9ec51ce3a928c29001ceb4 | []
| no_license | saki21/saki21 | 55569cdebd012b861f7b0ca9843caf1a404df0cc | f50ef1b9c5ac305f4edce6a4502ecc6afd104a34 | refs/heads/master | 2021-01-19T07:53:59.989872 | 2010-10-09T15:22:16 | 2010-10-09T15:22:16 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,444 | cpp | #include "stdafx.h"
using namespace System;
using namespace System::Reflection;
using namespace System::Runtime::CompilerServices;
using namespace System::Runtime::InteropServices;
using namespace System::Security::Permissions;
//
// アセンブリに関する一般情報は以下の属性セットをとおして制御されます。
// アセンブリに関連付けられている情報を変更するには、
// これらの属性値を変更してください。
//
[assembly:AssemblyTitleAttribute("ok")];
[assembly:AssemblyDescriptionAttribute("")];
[assembly:AssemblyConfigurationAttribute("")];
[assembly:AssemblyCompanyAttribute("saki21")];
[assembly:AssemblyProductAttribute("ok")];
[assembly:AssemblyCopyrightAttribute("Copyright (c) saki21 2010")];
[assembly:AssemblyTrademarkAttribute("")];
[assembly:AssemblyCultureAttribute("")];
//
// アセンブリのバージョン情報は、以下の 4 つの値で構成されています:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// すべての値を指定するか、下のように '*' を使ってリビジョンおよびビルド番号を
// 既定値にすることができます:
[assembly:AssemblyVersionAttribute("1.0.*")];
[assembly:ComVisible(false)];
[assembly:CLSCompliantAttribute(true)];
[assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)];
| [
"[email protected]"
]
| [
[
[
1,
40
]
]
]
|
f3d3e16e75508a4cf2c73687d77499cde9268b46 | da9e4cd28021ecc9e17e48ac3ded33b798aae59c | /APPS/Startup/Startup.cpp | 0201807721c2bf08a646d8daa78c2a7377f24496 | []
| no_license | hibive/sjmt6410pm090728 | d45242e74b94f954cf0960a4392f07178088e560 | 45ceea6c3a5a28172f7cd0b439d40c494355015c | refs/heads/master | 2021-01-10T10:02:35.925367 | 2011-01-27T04:22:44 | 2011-01-27T04:22:44 | 43,739,703 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 12,644 | cpp | //
// EBook2Startup.cpp
//
#include <windows.h>
#include "s1d13521.h"
#include "iphlpapi.h"
#include "etc.h"
#include <usbfnioctl.h>
#include <devload.h>
#define OMNIBOOK_REG_KEY _T("Software\\Omnibook")
#define APP_STARTUP_REG_STRING _T("AppStartup")
#define APP_STARTUP_REG_DEFAULT _T("\\eBook Store\\eBook_MainApp.exe")
#define APP_UPDATE_REG_STRING _T("AppUpdate")
#define APP_UPDATE_REG_DEFAULT _T("\\Storage Card\\eBook_UpdateApp.exe")
#define APP_SIPSYMBOL_REG_STRING _T("AppSipSymbol")
#define APP_SIPSYMBOL_REG_DEFAULT _T("\\Windows\\Omnibook_SipSymbol.exe")
#define WIFI_CARDNAME_TCHAR _T("SDIO86861")
#define WIFI_CARDNAME_CHAR "SDIO86861"
#define WIFI_CARDNAME_LEN 9
#define USB_FUN_DEV_NAME _T("UFN1:")
#define ARRAY_COUNT(x) (sizeof(x) / sizeof(x[0]))
LPCTSTR g_szUsbClassName[] = {
_T("Serial_Class"),
_T("Mass_Storage_Class"),
};
static int ufnGetCurrentClientName(void)
{
HANDLE hUSBFn = INVALID_HANDLE_VALUE;
hUSBFn = CreateFile(USB_FUN_DEV_NAME, DEVACCESS_BUSNAMESPACE, 0, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (INVALID_HANDLE_VALUE != hUSBFn)
{
UFN_CLIENT_INFO ufnInfo = {0,};
DWORD dwBytes;
DeviceIoControl(hUSBFn, IOCTL_UFN_GET_CURRENT_CLIENT, NULL, 0, &ufnInfo, sizeof(ufnInfo), &dwBytes, NULL);
RETAILMSG(0, (_T("IOCTL_UFN_GET_CURRENT_CLIENT\r\n")));
RETAILMSG(0, (_T(" ClientName = %s\r\n"), ufnInfo.szName));
RETAILMSG(0, (_T(" Description = %s\r\n"), ufnInfo.szDescription));
CloseHandle(hUSBFn);
for (int nMode=0; nMode<ARRAY_COUNT(g_szUsbClassName); nMode++)
{
if (g_szUsbClassName[nMode][0] == ufnInfo.szName[0])
return nMode;
}
}
return -1;
}
static BOOL ufnChangeCurrentClient(int nMode)
{
HANDLE hUSBFn = INVALID_HANDLE_VALUE;
UFN_CLIENT_INFO ufnInfo = {0,};
DWORD dwBytes;
if (ARRAY_COUNT(g_szUsbClassName) <= nMode)
return FALSE;
hUSBFn = CreateFile(USB_FUN_DEV_NAME, DEVACCESS_BUSNAMESPACE, 0, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (INVALID_HANDLE_VALUE != hUSBFn)
{
_stprintf_s(ufnInfo.szName, UFN_CLIENT_NAME_MAX_CHARS, _T("%s"), g_szUsbClassName[nMode]);
DeviceIoControl(hUSBFn, IOCTL_UFN_CHANGE_CURRENT_CLIENT, ufnInfo.szName, sizeof(ufnInfo.szName), NULL, 0, &dwBytes, NULL);
RETAILMSG(0, (_T("IOCTL_UFN_CHANGE_CURRENT_CLIENT\r\n")));
RETAILMSG(0, (_T(" ClientName = %s\r\n"), ufnInfo.szName));
CloseHandle(hUSBFn);
return TRUE;
}
return FALSE;
}
static BOOL RegOpenCreateStr(LPCTSTR lpSubKey, LPCTSTR lpName, LPTSTR lpData, DWORD dwCnt, BOOL bCreate)
{
HKEY hKey;
DWORD dwValue, dwType = REG_MULTI_SZ;
BOOL bRet = TRUE;
if (ERROR_SUCCESS != RegCreateKeyEx(HKEY_LOCAL_MACHINE,
lpSubKey,
0,
NULL,
0, // REG_OPTION_NON_VOLATILE
0,
0,
&hKey,
&dwValue))
{
return FALSE;
}
if (FALSE == bCreate && REG_CREATED_NEW_KEY == dwValue)
{
bRet = FALSE;
}
else if (REG_OPENED_EXISTING_KEY == dwValue)
{
if (ERROR_SUCCESS == RegQueryValueEx(hKey, lpName, 0, &dwType, (BYTE *)lpData, &dwCnt))
RETAILMSG(0, (_T("%s\r\n"), lpData));
else
bRet = FALSE;
}
else
{
bRet = FALSE;
}
RegCloseKey(hKey);
return bRet;
}
static BOOL RegOpenCreateDword(LPCTSTR lpSubKey, LPCTSTR lpName, LPDWORD lpData, BOOL bCreate)
{
HKEY hKey;
DWORD dwValue, dwType = REG_DWORD, dwCnt = sizeof(DWORD);
BOOL bRet = TRUE;
if (ERROR_SUCCESS != RegCreateKeyEx(HKEY_LOCAL_MACHINE,
lpSubKey,
0,
NULL,
0, // REG_OPTION_NON_VOLATILE
0,
0,
&hKey,
&dwValue))
{
return FALSE;
}
if (FALSE == bCreate && REG_CREATED_NEW_KEY == dwValue)
{
bRet = FALSE;
}
else if (REG_OPENED_EXISTING_KEY == dwValue)
{
if (ERROR_SUCCESS == RegQueryValueEx(hKey, lpName, 0, &dwType, (BYTE *)lpData, &dwCnt))
RETAILMSG(0, (_T("%d\r\n"), *lpData));
else
bRet = FALSE;
}
else
{
bRet = FALSE;
}
RegCloseKey(hKey);
return bRet;
}
static BOOL IsProgram(LPCWSTR lpszImageName)
{
HANDLE hFile = INVALID_HANDLE_VALUE;
BOOL bResult = TRUE;
hFile = CreateFileW(lpszImageName,
GENERIC_READ,
NULL, NULL,
OPEN_EXISTING,
NULL,
NULL);
if (hFile == INVALID_HANDLE_VALUE)
bResult = FALSE;
CloseHandle(hFile);
return bResult;
}
static BOOL RunProgram(LPCWSTR lpszImageName, LPCWSTR lpszCmdLine, DWORD dwWait)
{
PROCESS_INFORMATION pi = {0,};
BOOL bResult = FALSE;
bResult = CreateProcessW(lpszImageName,
lpszCmdLine,// Command line.
NULL, // Process handle not inheritable.
NULL, // Thread handle not inheritable.
FALSE, // Set handle inheritance to FALSE.
0, // No creation flags.
NULL, // Use parent's environment block.
NULL, // Use parent's starting directory.
NULL, // Pointer to STARTUPINFO structure.
&pi); // Pointer to PROCESS_INFORMATION structure.
if (bResult)
{
if (dwWait)
WaitForSingleObject(pi.hThread, dwWait);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
}
return bResult;
}
static BOOL CheckWifiMacAddress(HANDLE hEtc)
{
BOOL bRet = FALSE;
BYTE abInfo[512]={0,};
int nRetry = 0;
PIP_ADAPTER_INFO pAdapterInfo = NULL;
bRet = DeviceIoControl(hEtc, IOCTL_GET_BOARD_INFO, NULL, 100, abInfo, sizeof(abInfo), NULL, NULL);
if (FALSE == bRet)
{
RETAILMSG(1, (_T("ERROR : DeviceIoControl(IOCTL_GET_BOARD_INFO)\r\n")));
goto goto_Cleanup;
}
if (0 == memcmp(abInfo, "SJMT", 4) && 0 == memcmp(&abInfo[30], "MAC ", 4))
{
UINT8 szUUID[16]={0,};
memcpy(szUUID, abInfo, 16);
bRet = DeviceIoControl(hEtc, IOCTL_SET_BOARD_UUID, szUUID, sizeof(szUUID), NULL, 0, NULL, NULL);
goto goto_Cleanup;
}
goto_Retry:
DeviceIoControl(hEtc, IOCTL_SET_POWER_WLAN, NULL, TRUE, NULL, 0, NULL, NULL);
{
ULONG ulSizeAdapterInfo = 0;
DWORD dwReturnvalueGetAdapterInfo, i;
PIP_ADAPTER_INFO pOriginalPtr;
TCHAR szAdapterName[MAX_ADAPTER_NAME_LENGTH + 4 + 1];
for (i=0; i<20; i++)
{
dwReturnvalueGetAdapterInfo = GetAdaptersInfo(pAdapterInfo, &ulSizeAdapterInfo);
if (ERROR_NO_DATA == dwReturnvalueGetAdapterInfo)
{
RETAILMSG(0, (_T("Loop : ERROR_NO_DATA == dwReturnvalueGetAdapterInfo %d\r\n"), i));
Sleep(100);
}
else if (ERROR_BUFFER_OVERFLOW == dwReturnvalueGetAdapterInfo)
{
RETAILMSG(0, (_T("ERROR : ERROR_BUFFER_OVERFLOW == dwReturnvalueGetAdapterInfo %d, %d\r\n"), i, ulSizeAdapterInfo));
if (!(pAdapterInfo = (PIP_ADAPTER_INFO)malloc(ulSizeAdapterInfo)))
{
RETAILMSG(1, (_T("ERROR : Insufficient Memory\r\n")));
goto goto_Cleanup;
}
}
else if (ERROR_SUCCESS == dwReturnvalueGetAdapterInfo)
{
RETAILMSG(1, (_T("ERROR_SUCCESS == dwReturnvalueGetAdapterInfo %d, %d\r\n"), i, ulSizeAdapterInfo));
break;
}
else
{
RETAILMSG(1, (_T("ERROR : GetAdaptersInfo failed (error %ld)\r\n"), dwReturnvalueGetAdapterInfo));
goto goto_Cleanup;
}
}
if (NULL == pAdapterInfo)
{
nRetry++;
if (3 < nRetry)
{
RETAILMSG(1, (_T("ERROR : GetAdaptersInfo failed (error ERROR_NO_DATA)\r\n")));
goto goto_Cleanup;
}
DeviceIoControl(hEtc, IOCTL_SET_POWER_WLAN, NULL, FALSE, NULL, 0, NULL, NULL);
Sleep(100);
RETAILMSG(1, (_T("ERROR : GetAdaptersInfo failed (goto_Retry %d)\r\n"), nRetry));
goto goto_Retry;
}
pOriginalPtr = pAdapterInfo;
while (NULL != pAdapterInfo)
{
i = MultiByteToWideChar(CP_ACP, 0, pAdapterInfo->AdapterName, strlen(pAdapterInfo->AdapterName)+1,
szAdapterName, MAX_ADAPTER_NAME_LENGTH + 4 + 1);
szAdapterName[i] = NULL;
RETAILMSG(1, (_T("\t Adapter Name ...... : %s\r\n"), szAdapterName));
if (0 == strncmp(pAdapterInfo->AdapterName, WIFI_CARDNAME_CHAR, WIFI_CARDNAME_LEN))
{
UINT8 szUUID[16] = {'S','J','M','T',};
char *pTmp = (char *)&szUUID[4];
RETAILMSG(1, (_T("\t Address............ : ")));
for (i=0; i<pAdapterInfo->AddressLength; i++)
{
pTmp += sprintf(pTmp, "%02x", pAdapterInfo->Address[i]);
RETAILMSG(1, (_T("%02x"), pAdapterInfo->Address[i]));
}
RETAILMSG(1, (_T("\r\n")));
DeviceIoControl(hEtc, IOCTL_SET_BOARD_UUID, szUUID, sizeof(szUUID), NULL, 0, NULL, NULL);
memcpy(abInfo, szUUID, 16);
szUUID[0] = 'M'; szUUID[1] = 'A'; szUUID[2] = 'C'; szUUID[3] = ' ';
memcpy(&abInfo[30], szUUID, 16);
bRet = DeviceIoControl(hEtc, IOCTL_SET_BOARD_INFO, abInfo, sizeof(abInfo), NULL, 100, NULL, NULL);
if (FALSE == bRet)
{
RETAILMSG(1, (_T("ERROR : DeviceIoControl(IOCTL_SET_BOARD_INFO)\r\n")));
goto goto_Cleanup;
}
break;
}
pAdapterInfo = pAdapterInfo->Next;
RETAILMSG(1, (_T("\r\n")));
}
pAdapterInfo = NULL;
if (pOriginalPtr)
free(pOriginalPtr);
}
bRet = TRUE;
goto_Cleanup:
if (pAdapterInfo)
free(pAdapterInfo);
return bRet;
}
static void DirtyRectUpdate(HDC hDC)
{
ExtEscape(hDC, DRVESC_SET_DIRTYRECT, TRUE, NULL, 0, NULL);
{
DISPUPDATE du;
du.bWriteImage = TRUE;
du.pRect = NULL;
du.duState = DSPUPD_FULL;
du.bBorder = FALSE;
du.wfMode = WAVEFORM_GC;
ExtEscape(hDC, DRVESC_DISP_UPDATE, sizeof(du), (LPCSTR)&du, 0, NULL);
}
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
HANDLE hEtc = INVALID_HANDLE_VALUE;
BOOL bIsMassStorage = FALSE;
TCHAR szProgram[MAX_PATH] = {0,};
BOOL bDispUpdate = FALSE;
hEtc = CreateFile(ETC_DRIVER_NAME,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL, OPEN_EXISTING, 0, 0);
if (INVALID_HANDLE_VALUE != hEtc)
CheckWifiMacAddress(hEtc);
bIsMassStorage = (1 == ufnGetCurrentClientName()) ? TRUE : FALSE;
if (bIsMassStorage)
{
ufnChangeCurrentClient(0); // Serial_Class
Sleep(1000);
ufnChangeCurrentClient(1); // Mass_Storage_Class
}
sndPlaySound(_T("\\Windows\\Startup.wav"), SND_FILENAME | SND_ASYNC);
if (FALSE == RegOpenCreateStr(OMNIBOOK_REG_KEY, APP_STARTUP_REG_STRING, szProgram, MAX_PATH, FALSE))
{
RETAILMSG(1, (_T("RegOpenCreateStr(%s), Default(%s)\r\n"),
APP_STARTUP_REG_STRING, APP_STARTUP_REG_DEFAULT));
_tcscpy(szProgram, APP_STARTUP_REG_DEFAULT);
}
if (IsProgram(szProgram))
{
if (RunProgram(szProgram, NULL, 0))
{
RETAILMSG(1, (_T("RunProgram(%s)\r\n"), szProgram));
bDispUpdate = TRUE;
}
else
{
RETAILMSG(1, (_T("ERROR : RunProgram(%s)\r\n"), szProgram));
}
}
if (FALSE == bDispUpdate)
{
HDC hDC = GetDC(HWND_DESKTOP);
DirtyRectUpdate(hDC);
InvalidateRect(HWND_DESKTOP, NULL, TRUE);
ReleaseDC(HWND_DESKTOP, hDC);
if (FALSE == RegOpenCreateStr(OMNIBOOK_REG_KEY, APP_UPDATE_REG_STRING, szProgram, MAX_PATH, FALSE))
{
RETAILMSG(1, (_T("RegOpenCreateStr(%s), Default(%s)\r\n"),
APP_UPDATE_REG_STRING, APP_UPDATE_REG_DEFAULT));
_tcscpy(szProgram, APP_UPDATE_REG_DEFAULT);
}
if (IsProgram(szProgram))
{
if (RunProgram(szProgram, NULL, 0))
RETAILMSG(1, (_T("RunProgram(%s)\r\n"), szProgram));
else
RETAILMSG(1, (_T("ERROR : RunProgram(%s)\r\n"), szProgram));
}
else
{
RETAILMSG(1, (_T("ERROR : Not Found - %s\r\n"), szProgram));
}
}
if (FALSE == RegOpenCreateStr(OMNIBOOK_REG_KEY, APP_SIPSYMBOL_REG_STRING, szProgram, MAX_PATH, FALSE))
{
RETAILMSG(1, (_T("RegOpenCreateStr(%s), Default(%s)\r\n"),
APP_SIPSYMBOL_REG_STRING, APP_SIPSYMBOL_REG_DEFAULT));
_tcscpy(szProgram, APP_SIPSYMBOL_REG_DEFAULT);
}
if (IsProgram(szProgram))
{
RunProgram(szProgram, NULL, 0);
RETAILMSG(1, (_T("RunProgram : %s\r\n"), szProgram));
}
else
{
RETAILMSG(1, (_T("ERROR : Not Found - %s\r\n"), szProgram));
}
HDC hDC = GetDC(HWND_DESKTOP);
BOOL bDirtyRect = (BOOL)ExtEscape(hDC, DRVESC_GET_DIRTYRECT, 0, NULL, 0, NULL);
for (int i=0; (FALSE==bDirtyRect && i<5); i++)
{
Sleep(1000);
bDirtyRect = (BOOL)ExtEscape(hDC, DRVESC_GET_DIRTYRECT, 0, NULL, 0, NULL);
if (bIsMassStorage)
bDirtyRect = DeviceIoControl(hEtc, IOCTL_IS_ATTACH_UFN, NULL, 0, NULL, 0, NULL, NULL);
}
if (FALSE == bDirtyRect)
DirtyRectUpdate(hDC);
ReleaseDC(HWND_DESKTOP, hDC);
HANDLE hEvent = OpenEvent(EVENT_ALL_ACCESS, FALSE, _T("PowerManager/ReloadActivityTimeouts"));
if (hEvent)
{
SetEvent(hEvent);
CloseHandle(hEvent);
RETAILMSG(0, (_T("SetEvent(PowerManager/ReloadActivityTimeouts)\r\n")));
}
if (INVALID_HANDLE_VALUE != hEtc)
{
DeviceIoControl(hEtc, IOCTL_SET_POWER_WLAN, NULL, FALSE, NULL, 0, NULL, NULL);
CloseHandle(hEtc);
}
return 0;
}
| [
"jhlee74@a3c55b0e-9d05-11de-8bf8-05dd22f30006"
]
| [
[
[
1,
466
]
]
]
|
36b4b6fab37dfab29ffcb0a18f9108b46788f15c | ef23e388061a637f82b815d32f7af8cb60c5bb1f | /src/mame/includes/pcktgal.h | b347549910eaa9c0475970d561799cbe0fd2240e | []
| no_license | marcellodash/psmame | 76fd877a210d50d34f23e50d338e65a17deff066 | 09f52313bd3b06311b910ed67a0e7c70c2dd2535 | refs/heads/master | 2021-05-29T23:57:23.333706 | 2011-06-23T20:11:22 | 2011-06-23T20:11:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 416 | h | class pcktgal_state : public driver_device
{
public:
pcktgal_state(running_machine &machine, const driver_device_config_base &config)
: driver_device(machine, config) { }
int m_msm5205next;
int m_toggle;
UINT8 *m_spriteram;
size_t m_spriteram_size;
};
/*----------- defined in video/pcktgal.c -----------*/
PALETTE_INIT( pcktgal );
SCREEN_UPDATE( pcktgal );
SCREEN_UPDATE( pcktgalb );
| [
"Mike@localhost"
]
| [
[
[
1,
19
]
]
]
|
2c73f2e131957e3c46d61e6ada4c6bb885aeaa45 | b03f367d0c655c7776c8474c5e21a44d0890ea3d | /ship_sim_old/source/sci_ui.h | c69a651700e911c8d59ff6d0550ae579fae13920 | []
| no_license | Jacobi20/nano-vis | 0f94c77c5a03a5d1185f654528c69e5841571cb9 | 9c713a5f20c5b8c676e0a0847c8131e2a996d784 | refs/heads/master | 2021-01-20T11:31:23.350419 | 2011-08-09T13:22:57 | 2011-08-09T13:22:57 | 37,013,226 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,430 | h | /*
The MIT License
Copyright (c) 2010 IFMO/GameDev Studio
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.
*/
#pragma once
/*-----------------------------------------------------------------------------
Nano vis :
-----------------------------------------------------------------------------*/
class EUIDraw : public IUIDrawCB {
public:
EUIDraw ( D3D
} | [
"demiurghg@6d03c5d0-0fef-11df-8179-3f26cfb4ba5f"
]
| [
[
[
1,
34
]
]
]
|
08e7fc5ddaa423a67b16e2c6ba6ff6e68206895e | 2f72d621e6ec03b9ea243a96e8dd947a952da087 | /lol4/include/GameApplication.h | d03bd27ce005bc51ae39e380d52ff029634c8248 | []
| 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 | ISO-8859-1 | C++ | false | false | 11,251 | h | #ifndef __praGameApp
#define __praGameApp
//#include "KeyListener.h"
//mem probs without this next one
//#include <OgreNoMemoryMacros.h>
//#include <CEGUI/CEGUIImageset.h>
//#include <CEGUI/CEGUISystem.h>
//#include <CEGUI/CEGUILogger.h>
//#include <CEGUI/CEGUISchemeManager.h>
//#include <CEGUI/CEGUIWindowManager.h>
//#include <CEGUI/CEGUIWindow.h>
//#include "OgreCEGUIRenderer.h"
//#include "OgreCEGUIResourceProvider.h"
//#include <CEGUI/elements/CEGUIPushButton.h>
//#include <CEGUI/elements/CEGUIStaticText.h>
//#include <CEGUI/elements/CEGUIListboxTextItem.h>
////regular mem handler
//#include <OgreMemoryMacros.h>
#include "StandardApplication.h"
#include "Inventory.h"
#include "ZipSaveFile.h"
////#include "OgreAL.h"
//extern global_class *global;
using namespace Ogre;
class GameApplication: public StandardApplication
{
friend class CFrameListener;
public:
enum MenuMode
{
GUI_DISABLE,
GUI_INGAME,
GUI_MAINMENU,
GUI_OPTIONS,
GUI_SAVEGAME
};
//ContCallback *cc_static_char;
Real sensibility_x;
Real sensibility_y;
Real sensibility_x_keyboard;
Real sensibility_y_keyboard;
MenuMode menuMode;
/*
NOW, AGAIN:
*/
/// Standard constructor
GameApplication(String cmdline = "");
/// Standard destructor
~GameApplication();
/// Start the example
//void go(void);
//void showtextpanel();
//void settext(String txt, bool add=true);
//void initGUI();
void setMenu(MenuMode mId,bool changePausedState = true);
// bool handleQuit(const CEGUI::EventArgs& e);
// void log(Ogre::String txt);//kleine Hilfsfunktion
void setDebugText(String str,bool add=false);
void showScreenText(String str);
inline void hideScreenText()
{
showScreenText("");
}
void setHoldingItem(Inventory::invDataItem item);
void setHoldingSpell(gamedata_spell* spell);
void setHoldingContainer(gamedata_container* cont,Inventory *inv=NULL);
gamedata_char getGameCharData(String Id);
gamedata_char *getGameCharDataPtr(String Id);
/*void updateAllLevels(Real time);*/
void showInfoText(String txt, Real rel_x,Real rel_y);
void showInfoText(String txt,Ogre::MovableObject *mObj);
void updateInfoText(Real rel_x, Real rel_y);
void hideInfoText();
//lädt das level direkt. wenn reload auf true steht, wird das level neu geladen, auch wenn
//der player gerade drin ist. ausserdem wird der player nicht aus dem alten level geklont, sondern
//neu erstellt
//wenn placeplayer auf false gesetzt wird, reload als true angenommen, und das Level geladen,
//ohne den player zu setzen
void loadLevel(Ogre::String filename, Ogre::String entrance = "",bool reload = false,bool placePlayer = true);
//level zum Laden nach Abschluss des Frames vormerken
void setLoadLevel(Ogre::String filename, Ogre::String entrance = "");
//zum altes level löschen oder per setLoadLevel festgelegtes LVL laden
void frameEnded(Real time);
CEGUI::OgreCEGUIRenderer *getCEGUIRenderer();
void toggleInventory();
void toggleSpellbook();
void showOtherInventory(Inventory *inv,GameObject *owner);
void hideOtherInventory();
void setCursorMode(bool enable);
void gameOver();
Inventory::invDataItem curHolding;
gamedata_spell *curHoldingSpell;
gamedata_container* curHoldingContainer;
Inventory *curHoldingInventory;
Inventory *curOpenInventory;
GameObject *curOpenInvOwner;
Ogre::String screenshotBase;
Ogre::String defaultMusic;
Ogre::String defaultCombatMusic;
void setDisplayedWeapon(gamedata_item* item);
void setDisplayedSpell(gamedata_spell* spell);
SimpleSound::Source *music;
SimpleSound::Source *ambient1;
SimpleSound::Source *ambient2;
SimpleSound::Source *playersfx;
inline bool getZeroTime()
{
return zeroTime;
}
inline bool getPaused()
{
return paused;
}
inline bool getCursorMode()
{
return cursorMode;
}
void setPaused (bool set);
//einfach nur damit ich nen pointer auf das aktuelle musik-soundobjekt habe
void setMusic(SimpleSound::Buffer *buff, bool loop = false);
void playPlayerSFX(SimpleSound::Buffer *buff);
void setAmbient1(SimpleSound::Buffer *buff);
void setAmbient2(SimpleSound::Buffer *buff,bool loop = false);
void updateStatBars(Real hp, Real mp, int maxHP, int maxMP);
void updateCompass();
bool hasEnemy(GameObject *has)
{
for(ObjectList::iterator itr=enemyList.begin();itr!=enemyList.end();itr++)
{
if(*itr == has)
{
return true;
}
}
return false;
}
void addEnemy(GameObject *add)
{
if(hasEnemy(add))
return;
enemyList.push_back(add);
setBattleMusic(true);
}
void removeEnemy(GameObject *remove)
{
for(ObjectList::iterator itr=enemyList.begin();itr!=enemyList.end();itr++)
{
if(*itr == remove)
{
enemyList.erase(itr);
break;
}
}
if(enemyList.empty())
setBattleMusic(false);
}
private:
//Sounds
SimpleSound::Buffer *clickSnd;
//Sounds ENDE
Real screenTextTime; //zeit, um den bildschirmtext unten links auszublenden
bool screenTextShown;
gamedata_item* curDisplayedWeapon;
gamedata_spell* curDisplayedSpell;
bool inventoryOpen;
bool spellbookOpen;
bool otherInvOpen;
bool configLoaded;
Real otherInvSquaredDist;
CEGUI::OgreCEGUIRenderer* mGUIRenderer;
CEGUI::System *mGUISystem;
CEGUI::Window *mIngameGui, *mMainMenuGui, *mOptionsGui, *mSavegameGui;
CEGUI::Window *playerInventoryWnd, *playerEquipWnd, *playerSpellbookWnd, *otherInventoryWnd;
CEGUI::Window *holdingItemWnd;
// CEGUI::StaticText* infoText;
CEGUI::Window *infoText;
CEGUI::Window* hpBar;
CEGUI::Window* manaBar;
CEGUI::Window* hpBar_container;
CEGUI::Window* manaBar_container;
CEGUI::UDim hpBarWidth;
CEGUI::UDim manaBarWidth;
SceneManager *noLevelMgr; //für das mainmenu am anfang
Camera *noLevelCam; //gehört zu dem sceneMgr
std::vector<String> paramList;
bool showConfigDialog;
Ogre::String newRenderer,
curSelectedRenderer;
//für setLoadLevel
Ogre::String sllLevel;
Ogre::String sllEntrance;
bool sll;
bool unpauseNextFrame;
Real waitingUntilUnpause;//anscheinend muss ich im releasemodus min. 0.85 sekunden warten, bevor ich das level updaten kann
//nach dem unpausen, damit es nicht mit zu viel zeit geupdated wird
bool zeroTime;
bool DebugDoOnce;
Ogre::String startingLevel;
Ogre::String startingEntrance;
//ob cursormodus standard ist
bool useMouseLooking;
void setHoldingDisplay(Ogre::String imgName,Ogre::String subtext = "");
void updateDisplayedStats();
void setBattleMusic(bool set);
ZipSaveFile *tempSaveGame;
/*void saveGameBegin(String name);
void saveGameAddFile(void *buf,size_t size,Ogre::String fileName);
void saveGameAddFile(Ogre::String fileContents,Ogre::String fileName);
void saveGameAddFileFromDisk(Ogre::String fileNameSrc,Ogre::String fileNameDest);
void saveGameFinish();
*/
protected:
typedef std::list<GameObject*> ObjectList;
ObjectList enemyList;
CEGUI::Window *compassWnd;
//TextureUnitState *compassTexState;
SceneManager *compSceneMgr;
SceneNode *compNeedleNode;
Camera *compassCam;
bool battleMusic;
bool paused;
bool shutDown;
bool cursorMode;
void loadConfig();
void saveConfig();
CEGUI::ImagesetManager *imgr;
CEGUI::WindowManager *wmgr;
//das zeichnet die items neu
void updatePlayerInventory(Inventory *inv = NULL);
void updateOtherInventory(Inventory *inv = NULL);
void updateSpellbook(Spellbook *sb = NULL);
//das erzeugt die felder neu
void updatePlayerInventoryWindow();
void updateOtherInventoryWindow();
void updateSpellbookWindow();
unsigned int playerInventorySize;
unsigned int spellbookSize;
unsigned int otherInventorySize;
void updateInventoryField(unsigned int x, unsigned int y,Inventory::invDataItem it);
void updateOtherInvField(unsigned int x, unsigned int y,Inventory::invDataItem it);
void updateSpellbookField(unsigned int x, unsigned int y,gamedata_spell* spell);
void setSpellBorder(CEGUI::Window *field);
//the framelisteners will differ
CFrameListener *mFrameListener;
/*
EventProcessor *mEventProcessor;
RenderWindow* mWindow;
OgreNewt::World* mWorld;
bool lvlLoaded;*/
//global_class *global; //pointer to the global stuff container
// These internal methods package up the stages in the startup process
/** Sets up the application - returns false if the user chooses to abandon configuration. */
bool setup(void);
/** Configures the application - returns false if the user chooses to abandon configuration. */
bool configure(void);
void createDefaultSceneMgr(void);
//void createCamera(void);
//void createMaterials(void);
void createFrameListener(void);
/*void createScene(void);*/
//void destroyScene(void); // Optional to override this
//void createViewports(void);
/// Method which will define the source of resources (other than current folder)
//void setupResources(void);
/// Optional override method where you can create resource listeners (e.g. for loading screens)
void createResourceListener(void);
/// Optional override method where you can perform resource group loading
/// Must at least do ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
//void loadResources(void);
//void loadGameData(void);
/*void createPlayer(void);*/
//String *getCommonValues(TiXmlElement *Node);
//void lvlFromXml();
//void loadLvl(String filename);
void createGUI();
void initSound();
void updateVideoWindow();
void updateOptionsWindow();
void updateAudioWindow();
void createCompass();
void acceptSettings();
//erzeugt einen string mit einer XML-Datei als inhalt, wo spielstandspezifische
//Daten drin stehen
Ogre::String getSavegameSettings();
void saveOgreConfig();
//setzt das aktuelle Spiel zurück, zB um ein neues Spiel zu starten
void resetApp();
bool handleQuit(const CEGUI::EventArgs& e);
bool startGameClick(const CEGUI::EventArgs& e);
bool resumeClick(const CEGUI::EventArgs& e);
bool optionsClick(const CEGUI::EventArgs& e);
bool saveLoadClick(const CEGUI::EventArgs& e);
bool savegameLoadClick(const CEGUI::EventArgs& e);
bool savegameSaveClick(const CEGUI::EventArgs& e);
bool savegameDeleteClick(const CEGUI::EventArgs& e);
bool savegameListClick(const CEGUI::EventArgs& e);
bool savegameListDblClick(const CEGUI::EventArgs& e);
void updateSaveLoadWnd();
bool hideSaveLoadWnd(const CEGUI::EventArgs& e);
bool optionsCancelClick(const CEGUI::EventArgs& e);
bool optionsOKClick(const CEGUI::EventArgs& e);
bool optionsAcceptClick(const CEGUI::EventArgs& e);
bool optionsRendererChanged(const CEGUI::EventArgs& e);
bool playerInventoryClick(const CEGUI::EventArgs& e);
//bool otherInventoryClick(const CEGUI::EventArgs& e);
bool playerSpellbookClick(const CEGUI::EventArgs& e);
bool equipmentClick(const CEGUI::EventArgs& e);
//bool spellEquipClick(const CEGUI::EventArgs& e);
bool bagEquipClick(const CEGUI::EventArgs& e);
};
//}
#endif | [
"praecipitator@bd7a9385-7eed-4fd6-88b1-0096df50a1ac"
]
| [
[
[
1,
399
]
]
]
|
cfd239fdd9a46f440189340d5bfcc402c9c6f409 | 3949d20551a203cf29801d888844d83d297d8118 | /Sources/LudoAI/SkyDome.cpp | 99c3b816c7ce93c6998e76ec38a86cf87bd8c751 | []
| no_license | Cuihuo/sorgamedev | 2197cf5f19a6e8b3b7bba51d46ebc1f8c1f5731e | fa6eb43a586b0e175ac291e8cd583343c0f7a337 | refs/heads/master | 2021-01-10T17:38:50.996616 | 2008-11-28T17:13:19 | 2008-11-28T17:13:19 | 49,120,070 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,920 | cpp | ///////////////////////////////
// Filename: SkyDome.cpp
///////////////////////////////
#include "LudoCore/LudoGlobal.h"
#include "SkyDome.h"
#include "LudoCore/LudoVector.h"
#include "LudoCore/LudoStringManager.h"
#include <math.h>
using std::vector;
static const float DTOR = LUDO_PI / 180.0f;
static const float RADIUS = 2000.0f;
SkyDome::SkyDome(std::wstring baseName) : GameObject(baseName)
{
}
SkyDome::~SkyDome()
{
LUDO_SAFE_RELEASE(m_SkyTexture);
}
// Virtual
void SkyDome::Init()
{
//Prepare texture and vertices
D3DXIMAGE_INFO textureInfo;
D3DXCreateTextureFromFileEx( LudoRenderer::GetInstance()->GetDevice(), LudoStringManager::GetInstance()->GetString(SKY_TEXTURE).c_str(), D3DX_DEFAULT, D3DX_DEFAULT, D3DX_DEFAULT, 0,
D3DFMT_A8R8G8B8, D3DPOOL_MANAGED, D3DX_DEFAULT, D3DX_DEFAULT, 0, &textureInfo, NULL, (IDirect3DTexture9**)&m_SkyTexture );
int n = 0;
for (int i = 0; i <= 90 - DELTA_PHI; i += DELTA_PHI)
{
float iDTor = i*DTOR;
float iDPhiDTor = (i+DELTA_PHI)*DTOR;
for (int j = 0; j <= 360 - DELTA_THETA; j += DELTA_THETA)
{
float jDTor = DTOR * j;
float jDThetaDTor = DTOR*(j+DELTA_THETA);
m_SkyVertices[n].x = RADIUS * sinf(iDTor) * cosf(jDTor);
m_SkyVertices[n].y = RADIUS * cosf(iDTor) + GROUND_POS;
m_SkyVertices[n].z = RADIUS * sinf(iDTor) * sinf(jDTor);
n++;
m_SkyVertices[n].x = RADIUS * sinf(iDPhiDTor) * cosf(jDTor);
m_SkyVertices[n].y = RADIUS * cosf(iDPhiDTor) + GROUND_POS;
m_SkyVertices[n].z = RADIUS * sinf(iDPhiDTor) * sinf(jDTor);
n++;
m_SkyVertices[n].x = RADIUS * sinf(iDTor) * cosf(jDThetaDTor);
m_SkyVertices[n].y = RADIUS * cosf(iDTor) + GROUND_POS;
m_SkyVertices[n].z = RADIUS * sinf(iDTor) * sinf(jDThetaDTor);
n++;
if (i > -90 && i < 90)
{
m_SkyVertices[n].x = RADIUS * sinf(iDPhiDTor) * cosf(jDThetaDTor);
m_SkyVertices[n].y = RADIUS * cosf(iDPhiDTor) + GROUND_POS;
m_SkyVertices[n].z = RADIUS * sinf(iDPhiDTor) * sinf(jDThetaDTor);
n++;
}
}
}
// loop through the vertices
for (int i=0;i<SKY_NUM_VERTICES;i++)
{
LudoVector vertexNormal = LudoVector(-m_SkyVertices[i].x,-m_SkyVertices[i].y,-m_SkyVertices[i].z);
vertexNormal.Normalize();
m_SkyVertices[i].nx = vertexNormal.GetX();
m_SkyVertices[i].ny = vertexNormal.GetY();
m_SkyVertices[i].nz = vertexNormal.GetZ();
m_SkyVertices[i].u = asinf(m_SkyVertices[i].nx)/LUDO_PI + 0.5f;
m_SkyVertices[i].v = asinf(m_SkyVertices[i].ny)/LUDO_PI + 0.5f;
m_SkyIndices[i] = i;
}
for (int i = 0; i < SKY_NUM_VERTICES - 2; i++)
{
if (m_SkyVertices[i].u - m_SkyVertices[i+1].u > 0.9f)
{
m_SkyVertices[i+1].u += 1.0f;
}
if (m_SkyVertices[i+1].u - m_SkyVertices[i].u > 0.9f)
{
m_SkyVertices[i].u += 1.0f;
}
if (m_SkyVertices[i].u - m_SkyVertices[i+2].u > 0.9f)
{
m_SkyVertices[i+2].u += 1.0f;
}
if (m_SkyVertices[i+2].u - m_SkyVertices[i].u > 0.9f)
{
m_SkyVertices[i].u += 1.0f;
}
if (m_SkyVertices[i+1].u - m_SkyVertices[i+2].u > 0.9f)
{
m_SkyVertices[i+2].u += 1.0f;
}
if (m_SkyVertices[i+2].u -m_SkyVertices[i+1].u > 0.9f)
{
m_SkyVertices[i+1].u += 1.0f;
}
if (m_SkyVertices[i].v - m_SkyVertices[i+1].v > 0.8f)
{
m_SkyVertices[i+1].v += 1.0f;
}
if (m_SkyVertices[i+1].v - m_SkyVertices[i].v > 0.8f)
{
m_SkyVertices[i].v += 1.0f;
}
if (m_SkyVertices[i].v - m_SkyVertices[i+2].v > 0.8f)
{
m_SkyVertices[i+2].v += 1.0f;
}
if (m_SkyVertices[i+2].v - m_SkyVertices[i].v > 0.8f)
{
m_SkyVertices[i].v += 1.0f;
}
if (m_SkyVertices[i+1].v - m_SkyVertices[i+2].v > 0.8f)
{
m_SkyVertices[i+2].v += 1.0f;
}
if (m_SkyVertices[i+2].v - m_SkyVertices[i+1].v > 0.8f)
{
m_SkyVertices[i+1].v += 1.0f;
}
}
GameObject::Init();
}
// Virtual
void SkyDome::Render()
{
// Render the skydome
// LudoRenderer::GetInstance()->DrawVertices(*m_SkyVertices,SKY_NUM_VERTICES, m_SkyIndices, SKY_NUM_VERTICES, m_SkyTexture);
LudoRenderer::GetInstance()->DrawVertices(*m_SkyVertices,SKY_NUM_VERTICES, NULL, 0, m_SkyTexture);
GameObject::Render();
}
// Virtual
void SkyDome::Update()
{
GameObject::Update();
}
| [
"sikhan.ariel.lee@a3e5f5c2-bd6c-11dd-94c0-21daf384169b"
]
| [
[
[
1,
150
]
]
]
|
737e34c896911f81de7703eaf014e59c002a7f20 | 709cd826da3ae55945fd7036ecf872ee7cdbd82a | /Term/WildMagic2/Source/Approximation/WmlApprEllipsoidFit3.cpp | 1d3c86c0263f496f4854725cad18660ac951d1aa | []
| 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 | 6,816 | cpp | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
#include "WmlApprEllipsoidFit3.h"
#include "WmlContBox3.h"
#include "WmlDistVec3Eld3.h"
#include "WmlMinimizeN.h"
using namespace Wml;
//----------------------------------------------------------------------------
template <class Real>
EllipsoidFit3<Real>::EllipsoidFit3 (int iQuantity,
const Vector3<Real>* akPoint, Vector3<Real>& rkU, Matrix3<Real>& rkR,
Real afD[3], Real& rfError)
{
// Energy function is E : R^9 -> R where
// V = (V0,V1,V2,V3,V4,V5,V6,V7,V8)
// = (D[0],D[1],D[2],U.X(),U,y,U.Z(),A0,A1,A2).
// For really scattered data, you might need a search function
m_iQuantity = iQuantity;
m_akPoint = akPoint;
m_akTemp = new Vector3<Real>[iQuantity];
MinimizeN<Real> kMinimizer(9,Energy,8,8,32,this);
InitialGuess(iQuantity,akPoint,rkU,rkR,afD);
Real afAngle[3];
MatrixToAngles(rkR,afAngle);
Real afExtent[3] =
{
afD[0]*Math<Real>::FAbs(rkR[0][0]) +
afD[1]*Math<Real>::FAbs(rkR[0][1]) +
afD[2]*Math<Real>::FAbs(rkR[0][2]),
afD[0]*Math<Real>::FAbs(rkR[1][0]) +
afD[1]*Math<Real>::FAbs(rkR[1][1]) +
afD[2]*Math<Real>::FAbs(rkR[1][2]),
afD[0]*Math<Real>::FAbs(rkR[2][0]) +
afD[1]*Math<Real>::FAbs(rkR[2][1]) +
afD[2]*Math<Real>::FAbs(rkR[2][2])
};
Real afV0[9] =
{
((Real)0.5)*afD[0],
((Real)0.5)*afD[1],
((Real)0.5)*afD[2],
rkU.X() - afExtent[0],
rkU.Y() - afExtent[1],
rkU.Z() - afExtent[2],
-Math<Real>::PI,
(Real)0.0,
(Real)0.0
};
Real afV1[9] =
{
((Real)2.0)*afD[0],
((Real)2.0)*afD[1],
((Real)2.0)*afD[2],
rkU.X() + afExtent[0],
rkU.Y() + afExtent[1],
rkU.Z() + afExtent[2],
Math<Real>::PI,
Math<Real>::PI,
Math<Real>::PI
};
Real afVInitial[9] =
{
afD[0],
afD[1],
afD[2],
rkU.X(),
rkU.Y(),
rkU.Z(),
afAngle[0],
afAngle[1],
afAngle[2]
};
Real afVMin[9];
kMinimizer.GetMinimum(afV0,afV1,afVInitial,afVMin,rfError);
afD[0] = afVMin[0];
afD[1] = afVMin[1];
afD[2] = afVMin[2];
rkU.X() = afVMin[3];
rkU.Y() = afVMin[4];
rkU.Z() = afVMin[5];
AnglesToMatrix(&afVMin[6],rkR);
delete[] m_akTemp;
}
//----------------------------------------------------------------------------
template <class Real>
void EllipsoidFit3<Real>::InitialGuess (int iQuantity,
const Vector3<Real>* akPoint, Vector3<Real>& rkU, Matrix3<Real>& rkR,
Real afD[3])
{
Box3<Real> kBox = ContOrientedBox(iQuantity,akPoint);
rkU = kBox.Center();
rkR[0][0] = kBox.Axis(0).X();
rkR[0][1] = kBox.Axis(0).Y();
rkR[0][2] = kBox.Axis(0).Z();
rkR[1][0] = kBox.Axis(1).X();
rkR[1][1] = kBox.Axis(1).Y();
rkR[1][2] = kBox.Axis(1).Z();
rkR[2][0] = kBox.Axis(2).X();
rkR[2][1] = kBox.Axis(2).Y();
rkR[2][2] = kBox.Axis(2).Z();
afD[0] = kBox.Extent(0);
afD[1] = kBox.Extent(1);
afD[2] = kBox.Extent(2);
}
//----------------------------------------------------------------------------
template <class Real>
Real EllipsoidFit3<Real>::Energy (const Real* afV, void* pvData)
{
EllipsoidFit3& rkSelf = *(EllipsoidFit3*)pvData;
// build rotation matrix
Matrix3<Real> kRot;
AnglesToMatrix(&afV[6],kRot);
// Uniformly scale the extents to keep reasonable floating point values
// in the distance calculations.
Real fMax = afV[0];
if ( afV[1] > fMax )
fMax = afV[1];
if ( afV[2] > fMax )
fMax = afV[2];
Real fInvMax = ((Real)1.0)/fMax;
EllipsoidStandard3<Real> kEllipsoid;
kEllipsoid.Extent(0) = fInvMax*afV[0];
kEllipsoid.Extent(1) = fInvMax*afV[1];
kEllipsoid.Extent(2) = fInvMax*afV[2];
Vector3<Real> kClosest;
// transform the points to the coordinate system of U and R
Real fEnergy = (Real)0.0;
for (int i = 0; i < rkSelf.m_iQuantity; i++)
{
Vector3<Real> kDiff(
rkSelf.m_akPoint[i].X() - afV[3],
rkSelf.m_akPoint[i].Y() - afV[4],
rkSelf.m_akPoint[i].Z() - afV[5]);
rkSelf.m_akTemp[i] = fInvMax*(kDiff*kRot);
Real fDist = Distance(kEllipsoid,rkSelf.m_akTemp[i],kClosest);
fEnergy += fMax*fDist;
}
return fEnergy;
}
//----------------------------------------------------------------------------
template <class Real>
void EllipsoidFit3<Real>::MatrixToAngles (const Matrix3<Real>& rkR,
Real* afAngle)
{
// rotation axis = (cos(a0)sin(a1),sin(a0)sin(a1),cos(a1))
// a0 in [-pi,pi], a1 in [0,pi], a2 in [0,pi]
Vector3<Real> kAxis;
rkR.ToAxisAngle(kAxis,afAngle[2]);
if ( -(Real)1.0 < kAxis.Z() )
{
if ( kAxis.Z() < (Real)1.0 )
{
afAngle[0] = Math<Real>::ATan2(kAxis.Y(),kAxis.X());
afAngle[1] = Math<Real>::ACos(kAxis.Z());
}
else
{
afAngle[0] = (Real)0.0;
afAngle[1] = (Real)0.0;
}
}
else
{
afAngle[0] = (Real)0.0;
afAngle[1] = Math<Real>::PI;
}
}
//----------------------------------------------------------------------------
template <class Real>
void EllipsoidFit3<Real>::AnglesToMatrix (const Real* afAngle,
Matrix3<Real>& rkR)
{
// rotation axis = (cos(a0)sin(a1),sin(a0)sin(a1),cos(a1))
// a0 in [-pi,pi], a1 in [0,pi], a2 in [0,pi]
Real fCos0 = Math<Real>::Cos(afAngle[0]);
Real fSin0 = Math<Real>::Sin(afAngle[0]);
Real fCos1 = Math<Real>::Cos(afAngle[1]);
Real fSin1 = Math<Real>::Sin(afAngle[1]);
Vector3<Real> kAxis(fCos0*fSin1,fSin0*fSin1,fCos1);
rkR.FromAxisAngle(kAxis,afAngle[2]);
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// explicit instantiation
//----------------------------------------------------------------------------
namespace Wml
{
template WML_ITEM class EllipsoidFit3<float>;
template WML_ITEM class EllipsoidFit3<double>;
}
//----------------------------------------------------------------------------
| [
"[email protected]"
]
| [
[
[
1,
224
]
]
]
|
9996a658fb77b17866722b1208405c80fd6da78d | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Dependencies/Xerces/include/xercesc/sax2/SAX2XMLFilter.hpp | fa0cdf98b07e04329410cd7e87546fc9a5c78e3e | []
| no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,430 | hpp | /*
* Copyright 1999-2001,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: SAX2XMLFilter.hpp 191054 2005-06-17 02:56:35Z jberry $
*/
#ifndef SAX2XMLFilter_HPP
#define SAX2XMLFilter_HPP
#include <xercesc/sax2/SAX2XMLReader.hpp>
XERCES_CPP_NAMESPACE_BEGIN
class SAX2_EXPORT SAX2XMLFilter : public SAX2XMLReader
{
public:
// -----------------------------------------------------------------------
// Constructors and Destructor
// -----------------------------------------------------------------------
/** @name Constructors and Destructor */
//@{
/** The default constructor */
SAX2XMLFilter()
{
}
/** The destructor */
virtual ~SAX2XMLFilter()
{
}
//@}
//-----------------------------------------------------------------------
// The XMLFilter interface
//-----------------------------------------------------------------------
/** @name Implementation of SAX 2.0 XMLFilter interface's. */
//@{
/**
* This method returns the parent XMLReader object.
*
* @return A pointer to the parent XMLReader object.
*/
virtual SAX2XMLReader* getParent() const = 0 ;
/**
* Sets the parent XMLReader object; parse requests will be forwarded to this
* object, and callback notifications coming from it will be postprocessed
*
* @param parent The new XMLReader parent.
* @see SAX2XMLReader#SAX2XMLReader
*/
virtual void setParent(SAX2XMLReader* parent) = 0;
//@}
private :
/* The copy constructor, you cannot call this directly */
SAX2XMLFilter(const SAX2XMLFilter&);
/* The assignment operator, you cannot call this directly */
SAX2XMLFilter& operator=(const SAX2XMLFilter&);
};
XERCES_CPP_NAMESPACE_END
#endif
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
]
| [
[
[
1,
81
]
]
]
|
6200beb58da66f943ed1eecde36f515f77caa0e3 | 022d2957a29fe5054263a406bbdd85289cf17ee0 | /GontrolPC/GontrolPC/GontrolPCDlg.cpp | cba985737d356b964ed4fab69d2a41f1ee6a24ea | []
| no_license | amanuelg3/remote-control-with-android | aa6705da5c76311515ef6c4c972b7e64745be76d | 5e51aff7d1727608c615a0027c746592ebc4ba92 | refs/heads/master | 2016-09-03T01:07:29.047261 | 2011-06-11T16:25:32 | 2011-06-11T16:25:32 | 35,783,127 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,424 | cpp |
// GontrolPCDlg.cpp : implementation file
//
#include "stdafx.h"
#include "GontrolPC.h"
#include "GontrolPCDlg.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
#define TIMERID_HIDEWINDOW 1
// CAboutDlg dialog used for App About
class CAboutDlg : public CDialog
{
public:
CAboutDlg();
// Dialog Data
enum { IDD = IDD_ABOUTBOX };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
// Implementation
protected:
DECLARE_MESSAGE_MAP()
};
CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
}
void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
END_MESSAGE_MAP()
// CGontrolPCDlg dialog
CGontrolPCDlg::CGontrolPCDlg(CWnd* pParent /*=NULL*/)
: CDialog(CGontrolPCDlg::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
m_BeaconPort = DEFAULT_BEACONPORT;
m_RecvPort = DEFAULT_RECVPORT;
m_pLangRes = CLangRes::GetInstance();
m_fStart = false;
m_fHide = true;
m_ThreadAddr = sNotifyStatusThread;
}
void CGontrolPCDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CGontrolPCDlg, CDialog)
ON_WM_SYSCOMMAND()
ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
//}}AFX_MSG_MAP
ON_WM_DESTROY()
// ON_WM_NCPAINT()
ON_MESSAGE(WM_NOTIFYICON,&CGontrolPCDlg::OnNotifyIcon)
ON_COMMAND(ID_NOTIFYICON_EXIT, &CGontrolPCDlg::OnNotifyiconExit)
ON_COMMAND(ID_NOTIFYICON_START, &CGontrolPCDlg::OnNotifyiconStart)
ON_UPDATE_COMMAND_UI(ID_NOTIFYICON_START, &CGontrolPCDlg::OnUpdateNotifyiconStart)
ON_COMMAND(ID_NOTIFYICON_STOP, &CGontrolPCDlg::OnNotifyiconStop)
ON_UPDATE_COMMAND_UI(ID_NOTIFYICON_STOP, &CGontrolPCDlg::OnUpdateNotifyiconStop)
ON_WM_TIMER()
ON_COMMAND(ID_NOTIFYICON_SETTING, &CGontrolPCDlg::OnNotifyiconSetting)
END_MESSAGE_MAP()
// CGontrolPCDlg message handlers
BOOL CGontrolPCDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// Add "About..." menu item to system menu.
// IDM_ABOUTBOX must be in the system command range.
ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
ASSERT(IDM_ABOUTBOX < 0xF000);
CMenu* pSysMenu = GetSystemMenu(FALSE);
if (pSysMenu != NULL)
{
BOOL bNameValid;
CString strAboutMenu;
bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
ASSERT(bNameValid);
if (!strAboutMenu.IsEmpty())
{
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
}
}
// Set the icon for this dialog. The framework does this automatically
// when the application's main window is not a dialog
SetIcon(m_hIcon, TRUE); // Set big icon
SetIcon(m_hIcon, FALSE); // Set small icon
ModifyStyleEx(WS_EX_APPWINDOW, WS_EX_TOOLWINDOW);
ZeroMemory(&m_nticond,sizeof(NOTIFYICONDATA));
m_nticond.cbSize = sizeof(NOTIFYICONDATA);
m_nticond.hWnd = this->GetSafeHwnd();
m_nticond.uID = 1;
m_nticond.uVersion = NOTIFYICON_VERSION;
m_nticond.uFlags = NIF_ICON|NIF_MESSAGE|NIF_TIP;
m_nticond.uCallbackMessage = WM_NOTIFYICON;
m_nticond.hIcon = LoadIcon(AfxGetApp()->m_hInstance,MAKEINTRESOURCE(IDR_MAINSTOP));
_tcscpy_s(m_nticond.szInfoTitle,_countof(m_nticond.szInfoTitle),_T("Gontrol"));
m_nticond.szInfoTitle[_countof(m_nticond.szInfoTitle) - 1] = NULL;
_tcscpy_s(m_nticond.szTip,_countof(m_nticond.szTip),_T("Gontrol"));
m_nticond.szTip[_countof(m_nticond.szTip) - 1] = NULL;
Shell_NotifyIcon(NIM_ADD,&m_nticond);
Shell_NotifyIcon(NIM_SETVERSION,&m_nticond);
m_cfmgr = CreateConfigMgr(INISTORE);
CString szUserProfilePath;
szUserProfilePath.GetEnvironmentVariable(_T("APPDATA"));
m_cfmgr->SetTag(szUserProfilePath +_T("\\Gontrol\\Gontrol"));
int result = m_cfmgr->Open(true);
if (result)
{
CString szConfigFailMsg;
szConfigFailMsg.LoadString(IDS_CONFIGFILEFAIL);
ShowNotifyBalloon(szConfigFailMsg);
} // end of ' if(m_cfmgr->Open(true))
else
{
m_SettingDlg.LoadConfig(m_cfmgr);
}
m_pEmInput = new CEmInput();
m_pEmInput->SetBeaconPort(m_BeaconPort);
m_pEmInput->SetRecvFramePort(m_RecvPort);
m_pEmInput->SetInputFilter(&m_SettingDlg);
m_pEmInput->SetMsgQueue(&m_qConnMsg);
OnNotifyiconStart();
this->GetWindowPlacement(&m_wndpl);
this->MoveWindow(0,0,0,0);
Start();
return TRUE; // return TRUE unless you set the focus to a control
}
void CGontrolPCDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
if ((nID & 0xFFF0) == IDM_ABOUTBOX)
{
CAboutDlg dlgAbout;
dlgAbout.DoModal();
}
else
{
CDialog::OnSysCommand(nID, lParam);
}
}
// If you add a minimize button to your dialog, you will need the code below
// to draw the icon. For MFC applications using the document/view model,
// this is automatically done for you by the framework.
void CGontrolPCDlg::OnPaint()
{
if (IsIconic())
{
CPaintDC dc(this); // device context for painting
SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);
// Center icon in client rectangle
int cxIcon = GetSystemMetrics(SM_CXICON);
int cyIcon = GetSystemMetrics(SM_CYICON);
CRect rect;
GetClientRect(&rect);
int x = (rect.Width() - cxIcon + 1) / 2;
int y = (rect.Height() - cyIcon + 1) / 2;
// Draw the icon
dc.DrawIcon(x, y, m_hIcon);
}
else
{
CDialog::OnPaint();
}
}
// The system calls this function to obtain the cursor to display while the user drags
// the minimized window.
HCURSOR CGontrolPCDlg::OnQueryDragIcon()
{
return static_cast<HCURSOR>(m_hIcon);
}
void CGontrolPCDlg::OnDestroy()
{
this->RaiseExit();
delete m_pEmInput;
Stop();
Shell_NotifyIcon(NIM_DELETE,&m_nticond);
m_cfmgr->Close();
m_cfmgr->Release();
CDialog::OnDestroy();
}
void CGontrolPCDlg::OnNcPaint()
{
if (m_fHide)
{
ShowWindow(SW_HIDE);
}
// TODO: Add your message handler code here
// Do not call CDialog::OnNcPaint() for painting messages
}
LRESULT CGontrolPCDlg::OnNotifyIcon(WPARAM wParam,LPARAM lParam)
{
CMenu NTIconMenu;
switch(lParam)
{
case WM_LBUTTONDBLCLK:
OnNotifyiconSetting();
break;
case WM_RBUTTONDOWN:
this->SetForegroundWindow();
NTIconMenu.Attach(LoadMenu(CLangRes::GetInstance()->GetResourceDll(),MAKEINTRESOURCE(IDR_NTICON_MENU)));
//NTIconMenu.LoadMenu(IDR_NTICON_MENU);
//NTIconMenu.DestroyMenu();
//NTIconMenu.LoadMenu(IDR_NTICON_MENU);
POINT MousePoint;
GetCursorPos(&MousePoint);
NTIconMenu.GetSubMenu(0)->SetDefaultItem(ID_NOTIFYICON_SETTING);
if (m_fStart)
{
NTIconMenu.GetSubMenu(0)->EnableMenuItem(ID_NOTIFYICON_START,TRUE);
NTIconMenu.GetSubMenu(0)->EnableMenuItem(ID_NOTIFYICON_STOP,FALSE);
}
else
{
NTIconMenu.GetSubMenu(0)->EnableMenuItem(ID_NOTIFYICON_START,FALSE);
NTIconMenu.GetSubMenu(0)->EnableMenuItem(ID_NOTIFYICON_STOP,TRUE);
}
NTIconMenu.GetSubMenu(0)->TrackPopupMenu(TPM_RIGHTBUTTON ,MousePoint.x,MousePoint.y,this);
this->PostMessage(WM_NULL,0,0);
break;
//case WM_LBUTTONDOWN:
// this->SetWindowPlacement(&m_wndpl);
// break;
}
return 0;
}
void CGontrolPCDlg::OnNotifyiconExit()
{
OnCancel();
}
void CGontrolPCDlg::OnNotifyiconStart()
{
if (m_pEmInput->Start())
{
CString szStartErrorMsg;
szStartErrorMsg.LoadString(m_pLangRes->GetResourceDll(),IDS_STARTERRORMSG);
ShowNotifyBalloon(szStartErrorMsg,20000);
}
else
{
CString szStartErrorMsg;
szStartErrorMsg.LoadString(m_pLangRes->GetResourceDll(),IDS_WAITCONNECT);
SetNotifyIcon(LoadIcon(AfxGetApp()->m_hInstance,MAKEINTRESOURCE(IDR_MAINFRAME)));
ShowNotifyBalloon(szStartErrorMsg,20000);
m_fStart = true;
}
}
void CGontrolPCDlg::OnUpdateNotifyiconStart(CCmdUI *pCmdUI)
{
pCmdUI->Enable(!m_fStart);
}
void CGontrolPCDlg::OnNotifyiconStop()
{
m_pEmInput->Stop();
SetNotifyIcon(LoadIcon(AfxGetApp()->m_hInstance,MAKEINTRESOURCE(IDR_MAINSTOP)));
m_fStart = false;
}
void CGontrolPCDlg::OnUpdateNotifyiconStop(CCmdUI *pCmdUI)
{
pCmdUI->Enable(m_fStart);
}
void CGontrolPCDlg::OnTimer(UINT_PTR nIDEvent)
{
if (nIDEvent == TIMERID_HIDEWINDOW)
{
ShowWindow(SW_HIDE);
KillTimer(TIMERID_HIDEWINDOW);
}
CDialog::OnTimer(nIDEvent);
}
void CGontrolPCDlg::SetNotifyIcon(HICON hIcon)
{
m_nticond.uFlags &= ~NIF_INFO;
m_nticond.uTimeout = 0;
m_nticond.szInfo[0] = NULL;
m_nticond.hIcon = hIcon;
Shell_NotifyIcon(NIM_MODIFY,&m_nticond);
}
void CGontrolPCDlg::SetNotifyTip(const TCHAR * szTip)
{
m_nticond.uFlags &= ~NIF_INFO;
m_nticond.uTimeout = 0;
m_nticond.szInfo[0] = NULL;
_tcscpy_s(m_nticond.szTip,_countof(m_nticond.szTip),szTip);
m_nticond.szTip[_countof(m_nticond.szTip) - 1] = NULL;
Shell_NotifyIcon(NIM_MODIFY,&m_nticond);
}
void CGontrolPCDlg::ShowNotifyBalloon(const TCHAR * szInfo, UINT timeout)
{
m_nticond.uFlags |= NIF_INFO;
m_nticond.uTimeout = timeout;
_tcscpy_s(m_nticond.szInfo,_countof(m_nticond.szInfo),szInfo);
m_nticond.szInfo[_countof(m_nticond.szInfo) - 1] = NULL;
Shell_NotifyIcon(NIM_MODIFY,&m_nticond);
}
//bool CGontrolPCDlg::OSVersion6()
//{
// OSVERSIONINFOEX osvi;
// ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
// osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
// GetVersionEx ((OSVERSIONINFO *) &osvi);
// if (osvi.dwMajorVersion >= 6)
// {
// return true;
// }
// return false;
//}
//
//BOOL CGontrolPCDlg::TryElvtPriv(const TCHAR * szMessage)
//{
// if (!OSVersion6())
// {
// return TRUE+2;
// }
// CString szElvtPrivAsk;
// szElvtPrivAsk.LoadString(IDS_ELVTPRIVASK);
// if (MessageBox(szElvtPrivAsk,szMessage,MB_YESNO|MB_ICONQUESTION) == IDYES)
// {
// int (*pfnNeedElevatePriv)();
// int (*pfnCreateElevatePrivProcess)();
// BOOL rtVal = FALSE;
// HMODULE hModule = LoadLibrary(_T("ElvtPriv.dll"));
// if (hModule)
// {
// pfnNeedElevatePriv =
// (int (*)())GetProcAddress(hModule,"NeedElevatePriv");
// pfnCreateElevatePrivProcess =
// (int (*)())GetProcAddress(hModule,"CreateElevatePrivProcess");
// if (pfnNeedElevatePriv && pfnNeedElevatePriv()
// && pfnCreateElevatePrivProcess )
// {
// int ElvtResult = pfnCreateElevatePrivProcess();
// switch (ElvtResult)
// {
// case 0:
// rtVal = TRUE;
// break;
// case -1:
// rtVal = TRUE+1;
// break;
// default:
// rtVal = FALSE;
// }
// }
// FreeLibrary(hModule);
// } //end of 'if (hModule)
// return rtVal;
// }
// else
// {
// return TRUE+1;
// }
//}
void CGontrolPCDlg::OnNotifyiconSetting()
{
if (!m_SettingDlg.IsShown())
{
m_SettingDlg.DoModal();
}
else
{
m_SettingDlg.SetFocus();
}
}
int CGontrolPCDlg::Start()
{
return IMyThread::Start();
}
unsigned int __stdcall CGontrolPCDlg::sNotifyStatusThread(void * p)
{
CGontrolPCDlg * pThis = dynamic_cast<CGontrolPCDlg *>(reinterpret_cast<IMyThread *>(p));
if (!pThis)
{
#ifdef _DEBUG
::OutputDebugString(_T("RecvFrame: Thread this Pointer Error"));
#endif
return -1;
}
while (!pThis->m_fExit)
{
try
{
ConnMsg msg = pThis->m_qConnMsg.Take(THREADWAIT);
CString NotifyMessage;
NotifyMessage.LoadString(pThis->m_pLangRes->GetResourceDll(),msg.StringID);
NotifyMessage += _T("\n");
NotifyMessage += msg.szData;
pThis->ShowNotifyBalloon(NotifyMessage);
}
catch (TimeoutException &)
{}
}
return 0;
} | [
"wzmvictor@5d9a875e-b1a7-14b0-4603-314cddc6b85c"
]
| [
[
[
1,
452
]
]
]
|
36b8ee99d8e3d03cc4d9a90f7d485cd2fc23fef9 | 203f8465075e098f69912a6bbfa3498c36ce2a60 | /stacks/motion_planning/sbpl/src/planners/ARAStar/araplanner.cpp | 67c86107cb125561c319fd5d561461cfb65590b8 | []
| no_license | robcn/personalrobots-pkg | a4899ff2db9aef00a99274d70cb60644124713c9 | 4dcf3ca1142d3c3cb85f6d42f7afa33c59e2240a | refs/heads/master | 2021-06-20T16:28:29.549716 | 2009-09-04T23:56:10 | 2009-09-04T23:56:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 33,369 | cpp | /*
* Copyright (c) 2008, Maxim Likhachev
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University of Pennsylvania nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <iostream>
using namespace std;
#include "../../sbpl/headers.h"
//-----------------------------------------------------------------------------------------------------
ARAPlanner::ARAPlanner(DiscreteSpaceInformation* environment, bool bSearchForward)
{
bforwardsearch = bSearchForward;
environment_ = environment;
bsearchuntilfirstsolution = false;
finitial_eps = ARA_DEFAULT_INITIAL_EPS;
searchexpands = 0;
MaxMemoryCounter = 0;
fDeb = fopen("debug.txt", "w");
printf("debug on\n");
pSearchStateSpace_ = new ARASearchStateSpace_t;
//create the ARA planner
if(CreateSearchStateSpace(pSearchStateSpace_) != 1)
{
printf("ERROR: failed to create statespace\n");
return;
}
//set the start and goal states
if(InitializeSearchStateSpace(pSearchStateSpace_) != 1)
{
printf("ERROR: failed to create statespace\n");
return;
}
}
ARAPlanner::~ARAPlanner()
{
if(pSearchStateSpace_ != NULL){
//delete the statespace
DeleteSearchStateSpace(pSearchStateSpace_);
delete pSearchStateSpace_;
}
fclose(fDeb);
}
void ARAPlanner::Initialize_searchinfo(CMDPSTATE* state, ARASearchStateSpace_t* pSearchStateSpace)
{
ARAState* searchstateinfo = (ARAState*)state->PlannerSpecificData;
searchstateinfo->MDPstate = state;
InitializeSearchStateInfo(searchstateinfo, pSearchStateSpace);
}
CMDPSTATE* ARAPlanner::CreateState(int stateID, ARASearchStateSpace_t* pSearchStateSpace)
{
CMDPSTATE* state = NULL;
#if DEBUG
if(environment_->StateID2IndexMapping[stateID][ARAMDP_STATEID2IND] != -1)
{
printf("ERROR in CreateState: state already created\n");
exit(1);
}
#endif
//adds to the tail a state
state = pSearchStateSpace->searchMDP.AddState(stateID);
//remember the index of the state
environment_->StateID2IndexMapping[stateID][ARAMDP_STATEID2IND] = pSearchStateSpace->searchMDP.StateArray.size()-1;
#if DEBUG
if(state != pSearchStateSpace->searchMDP.StateArray[environment_->StateID2IndexMapping[stateID][ARAMDP_STATEID2IND]])
{
printf("ERROR in CreateState: invalid state index\n");
exit(1);
}
#endif
//create search specific info
state->PlannerSpecificData = (ARAState*)malloc(sizeof(ARAState));
Initialize_searchinfo(state, pSearchStateSpace);
MaxMemoryCounter += sizeof(ARAState);
return state;
}
CMDPSTATE* ARAPlanner::GetState(int stateID, ARASearchStateSpace_t* pSearchStateSpace)
{
if(stateID >= (int)environment_->StateID2IndexMapping.size())
{
printf("ERROR int GetState: stateID %d is invalid\n", stateID);
exit(1);
}
if(environment_->StateID2IndexMapping[stateID][ARAMDP_STATEID2IND] == -1)
return CreateState(stateID, pSearchStateSpace);
else
return pSearchStateSpace->searchMDP.StateArray[environment_->StateID2IndexMapping[stateID][ARAMDP_STATEID2IND]];
}
//-----------------------------------------------------------------------------------------------------
int ARAPlanner::ComputeHeuristic(CMDPSTATE* MDPstate, ARASearchStateSpace_t* pSearchStateSpace)
{
//compute heuristic for search
if(bforwardsearch)
{
#if MEM_CHECK == 1
//int WasEn = DisableMemCheck();
#endif
//forward search: heur = distance from state to searchgoal which is Goal ARAState
int retv = environment_->GetFromToHeuristic(MDPstate->StateID, pSearchStateSpace->searchgoalstate->StateID);
#if MEM_CHECK == 1
//if (WasEn)
// EnableMemCheck();
#endif
return retv;
}
else
{
//backward search: heur = distance from searchgoal to state
return environment_->GetStartHeuristic(MDPstate->StateID);
}
}
//initialization of a state
void ARAPlanner::InitializeSearchStateInfo(ARAState* state, ARASearchStateSpace_t* pSearchStateSpace)
{
state->g = INFINITECOST;
state->v = INFINITECOST;
state->iterationclosed = 0;
state->callnumberaccessed = pSearchStateSpace->callnumber;
state->bestnextstate = NULL;
state->costtobestnextstate = INFINITECOST;
state->heapindex = 0;
state->listelem[ARA_INCONS_LIST_ID] = 0;
state->numofexpands = 0;
state->bestpredstate = NULL;
//compute heuristics
#if USE_HEUR
if(pSearchStateSpace->searchgoalstate != NULL)
state->h = ComputeHeuristic(state->MDPstate, pSearchStateSpace);
else
state->h = 0;
#else
state->h = 0;
#endif
}
//re-initialization of a state
void ARAPlanner::ReInitializeSearchStateInfo(ARAState* state, ARASearchStateSpace_t* pSearchStateSpace)
{
state->g = INFINITECOST;
state->v = INFINITECOST;
state->iterationclosed = 0;
state->callnumberaccessed = pSearchStateSpace->callnumber;
state->bestnextstate = NULL;
state->costtobestnextstate = INFINITECOST;
state->heapindex = 0;
state->listelem[ARA_INCONS_LIST_ID] = 0;
state->numofexpands = 0;
state->bestpredstate = NULL;
//compute heuristics
#if USE_HEUR
if(pSearchStateSpace->searchgoalstate != NULL)
{
state->h = ComputeHeuristic(state->MDPstate, pSearchStateSpace);
}
else
state->h = 0;
#else
state->h = 0;
#endif
}
void ARAPlanner::DeleteSearchStateData(ARAState* state)
{
//no memory was allocated
MaxMemoryCounter = 0;
return;
}
//used for backward search
void ARAPlanner::UpdatePreds(ARAState* state, ARASearchStateSpace_t* pSearchStateSpace)
{
vector<int> PredIDV;
vector<int> CostV;
CKey key;
ARAState *predstate;
environment_->GetPreds(state->MDPstate->StateID, &PredIDV, &CostV);
//iterate through predecessors of s
for(int pind = 0; pind < (int)PredIDV.size(); pind++)
{
CMDPSTATE* PredMDPState = GetState(PredIDV[pind], pSearchStateSpace);
predstate = (ARAState*)(PredMDPState->PlannerSpecificData);
if(predstate->callnumberaccessed != pSearchStateSpace->callnumber)
ReInitializeSearchStateInfo(predstate, pSearchStateSpace);
//see if we can improve the value of predstate
if(predstate->g > state->v + CostV[pind])
{
predstate->g = state->v + CostV[pind];
predstate->bestnextstate = state->MDPstate;
predstate->costtobestnextstate = CostV[pind];
//re-insert into heap if not closed yet
if(predstate->iterationclosed != pSearchStateSpace->searchiteration)
{
key.key[0] = predstate->g + (int)(pSearchStateSpace->eps*predstate->h);
//key.key[1] = predstate->h;
if(predstate->heapindex != 0)
pSearchStateSpace->heap->updateheap(predstate,key);
else
pSearchStateSpace->heap->insertheap(predstate,key);
}
//take care of incons list
else if(predstate->listelem[ARA_INCONS_LIST_ID] == NULL)
{
pSearchStateSpace->inconslist->insert(predstate, ARA_INCONS_LIST_ID);
}
}
} //for predecessors
}
//used for forward search
void ARAPlanner::UpdateSuccs(ARAState* state, ARASearchStateSpace_t* pSearchStateSpace)
{
vector<int> SuccIDV;
vector<int> CostV;
CKey key;
ARAState *succstate;
environment_->GetSuccs(state->MDPstate->StateID, &SuccIDV, &CostV);
//iterate through predecessors of s
for(int sind = 0; sind < (int)SuccIDV.size(); sind++)
{
CMDPSTATE* SuccMDPState = GetState(SuccIDV[sind], pSearchStateSpace);
int cost = CostV[sind];
succstate = (ARAState*)(SuccMDPState->PlannerSpecificData);
if(succstate->callnumberaccessed != pSearchStateSpace->callnumber)
ReInitializeSearchStateInfo(succstate, pSearchStateSpace);
//see if we can improve the value of succstate
//taking into account the cost of action
if(succstate->g > state->v + cost)
{
succstate->g = state->v + cost;
succstate->bestpredstate = state->MDPstate;
//re-insert into heap if not closed yet
if(succstate->iterationclosed != pSearchStateSpace->searchiteration)
{
key.key[0] = succstate->g + (int)(pSearchStateSpace->eps*succstate->h);
//key.key[1] = succstate->h;
if(succstate->heapindex != 0)
pSearchStateSpace->heap->updateheap(succstate,key);
else
pSearchStateSpace->heap->insertheap(succstate,key);
}
//take care of incons list
else if(succstate->listelem[ARA_INCONS_LIST_ID] == NULL)
{
pSearchStateSpace->inconslist->insert(succstate, ARA_INCONS_LIST_ID);
}
} //check for cost improvement
} //for actions
}
//TODO-debugmax - add obsthresh and other thresholds to other environments in 3dkin
int ARAPlanner::GetGVal(int StateID, ARASearchStateSpace_t* pSearchStateSpace)
{
CMDPSTATE* cmdp_state = GetState(StateID, pSearchStateSpace);
ARAState* state = (ARAState*)cmdp_state->PlannerSpecificData;
return state->g;
}
//returns 1 if the solution is found, 0 if the solution does not exist and 2 if it ran out of time
int ARAPlanner::ImprovePath(ARASearchStateSpace_t* pSearchStateSpace, double MaxNumofSecs)
{
int expands;
ARAState *state, *searchgoalstate;
CKey key, minkey;
CKey goalkey;
expands = 0;
if(pSearchStateSpace->searchgoalstate == NULL)
{
printf("ERROR searching: no goal state is set\n");
exit(1);
}
//goal state
searchgoalstate = (ARAState*)(pSearchStateSpace->searchgoalstate->PlannerSpecificData);
if(searchgoalstate->callnumberaccessed != pSearchStateSpace->callnumber)
ReInitializeSearchStateInfo(searchgoalstate, pSearchStateSpace);
//set goal key
goalkey.key[0] = searchgoalstate->g;
//goalkey.key[1] = searchgoalstate->h;
//expand states until done
minkey = pSearchStateSpace->heap->getminkeyheap();
CKey oldkey = minkey;
while(!pSearchStateSpace->heap->emptyheap() && minkey.key[0] < INFINITECOST && goalkey > minkey &&
(clock()-TimeStarted) < MaxNumofSecs*(double)CLOCKS_PER_SEC)
{
//get the state
state = (ARAState*)pSearchStateSpace->heap->deleteminheap();
#if DEBUG
//fprintf(fDeb, "expanding state(%d): h=%d g=%u key=%u v=%u iterc=%d callnuma=%d expands=%d (g(goal)=%u)\n",
// state->MDPstate->StateID, state->h, state->g, state->g+(int)(pSearchStateSpace->eps*state->h), state->v,
// state->iterationclosed, state->callnumberaccessed, state->numofexpands, searchgoalstate->g);
fprintf(fDeb, "expanding: ");
PrintSearchState(state, fDeb);
if(state->listelem[ARA_INCONS_LIST_ID] != NULL)
{
fprintf(fDeb, "ERROR: expanding a state from inconslist\n");
printf("ERROR: expanding a state from inconslist\n");
exit(1);
}
fflush(fDeb);
#endif
#if DEBUG
if(minkey.key[0] < oldkey.key[0] && fabs(this->finitial_eps - 1.0) < ERR_EPS)
{
//printf("WARN in search: the sequence of keys decreases\n");
//exit(1);
}
oldkey = minkey;
#endif
if(state->v == state->g)
{
printf("ERROR: consistent state is being expanded\n");
#if DEBUG
fprintf(fDeb, "ERROR: consistent state is being expanded\n");
exit(1);
#endif
}
//recompute state value
state->v = state->g;
state->iterationclosed = pSearchStateSpace->searchiteration;
//new expand
expands++;
state->numofexpands++;
if(bforwardsearch == false)
UpdatePreds(state, pSearchStateSpace);
else
UpdateSuccs(state, pSearchStateSpace);
//recompute minkey
minkey = pSearchStateSpace->heap->getminkeyheap();
//recompute goalkey if necessary
if(goalkey.key[0] != (int)searchgoalstate->g)
{
//printf("re-computing goal key\n");
//recompute the goal key (heuristics should be zero)
goalkey.key[0] = searchgoalstate->g;
//goalkey.key[1] = searchgoalstate->h;
}
if(expands%100000 == 0 && expands > 0)
{
printf("expands so far=%u\n", expands);
}
}
int retv = 1;
if(searchgoalstate->g == INFINITECOST && pSearchStateSpace->heap->emptyheap())
{
printf("solution does not exist: search exited because heap is empty\n");
retv = 0;
}
else if(!pSearchStateSpace->heap->emptyheap() && goalkey > minkey)
{
printf("search exited because it ran out of time\n");
retv = 2;
}
else if(searchgoalstate->g == INFINITECOST && !pSearchStateSpace->heap->emptyheap())
{
printf("solution does not exist: search exited because all candidates for expansion have infinite heuristics\n");
retv = 0;
}
else
{
printf("search exited with a solution for eps=%.3f\n", pSearchStateSpace->eps);
retv = 1;
}
//fprintf(fDeb, "expanded=%d\n", expands);
searchexpands += expands;
return retv;
}
void ARAPlanner::BuildNewOPENList(ARASearchStateSpace_t* pSearchStateSpace)
{
ARAState *state;
CKey key;
CHeap* pheap = pSearchStateSpace->heap;
CList* pinconslist = pSearchStateSpace->inconslist;
//move incons into open
while(pinconslist->firstelement != NULL)
{
state = (ARAState*)pinconslist->firstelement->liststate;
//compute f-value
key.key[0] = state->g + (int)(pSearchStateSpace->eps*state->h);
//key.key[1] = state->h;
//insert into OPEN
pheap->insertheap(state, key);
//remove from INCONS
pinconslist->remove(state, ARA_INCONS_LIST_ID);
}
}
void ARAPlanner::Reevaluatefvals(ARASearchStateSpace_t* pSearchStateSpace)
{
CKey key;
int i;
CHeap* pheap = pSearchStateSpace->heap;
//recompute priorities for states in OPEN and reorder it
for (i = 1; i <= pheap->currentsize; ++i)
{
ARAState* state = (ARAState*)pheap->heap[i].heapstate;
pheap->heap[i].key.key[0] = state->g +
(int)(pSearchStateSpace->eps*state->h);
//pheap->heap[i].key.key[1] = state->h;
}
pheap->makeheap();
pSearchStateSpace->bReevaluatefvals = false;
}
//creates (allocates memory) search state space
//does not initialize search statespace
int ARAPlanner::CreateSearchStateSpace(ARASearchStateSpace_t* pSearchStateSpace)
{
//create a heap
pSearchStateSpace->heap = new CHeap;
pSearchStateSpace->inconslist = new CList;
MaxMemoryCounter += sizeof(CHeap);
MaxMemoryCounter += sizeof(CList);
pSearchStateSpace->searchgoalstate = NULL;
pSearchStateSpace->searchstartstate = NULL;
searchexpands = 0;
pSearchStateSpace->bReinitializeSearchStateSpace = false;
return 1;
}
//deallocates memory used by SearchStateSpace
void ARAPlanner::DeleteSearchStateSpace(ARASearchStateSpace_t* pSearchStateSpace)
{
if(pSearchStateSpace->heap != NULL)
{
pSearchStateSpace->heap->makeemptyheap();
delete pSearchStateSpace->heap;
pSearchStateSpace->heap = NULL;
}
if(pSearchStateSpace->inconslist != NULL)
{
pSearchStateSpace->inconslist->makeemptylist(ARA_INCONS_LIST_ID);
delete pSearchStateSpace->inconslist;
pSearchStateSpace->inconslist = NULL;
}
//delete the states themselves
int iend = (int)pSearchStateSpace->searchMDP.StateArray.size();
for(int i=0; i < iend; i++)
{
CMDPSTATE* state = pSearchStateSpace->searchMDP.StateArray[i];
if(state != NULL && state->PlannerSpecificData != NULL){
DeleteSearchStateData((ARAState*)state->PlannerSpecificData);
free((ARAState*)state->PlannerSpecificData);
state->PlannerSpecificData = NULL;
}
}
pSearchStateSpace->searchMDP.Delete();
}
//reset properly search state space
//needs to be done before deleting states
int ARAPlanner::ResetSearchStateSpace(ARASearchStateSpace_t* pSearchStateSpace)
{
pSearchStateSpace->heap->makeemptyheap();
pSearchStateSpace->inconslist->makeemptylist(ARA_INCONS_LIST_ID);
return 1;
}
//initialization before each search
void ARAPlanner::ReInitializeSearchStateSpace(ARASearchStateSpace_t* pSearchStateSpace)
{
CKey key;
//increase callnumber
pSearchStateSpace->callnumber++;
//reset iteration
pSearchStateSpace->searchiteration = 0;
pSearchStateSpace->bNewSearchIteration = true;
#if DEBUG
fprintf(fDeb, "reinitializing search state-space (new call number=%d search iter=%d)\n",
pSearchStateSpace->callnumber,pSearchStateSpace->searchiteration );
#endif
pSearchStateSpace->heap->makeemptyheap();
pSearchStateSpace->inconslist->makeemptylist(ARA_INCONS_LIST_ID);
//reset
pSearchStateSpace->eps = this->finitial_eps;
pSearchStateSpace->eps_satisfied = INFINITECOST;
//initialize start state
ARAState* startstateinfo = (ARAState*)(pSearchStateSpace->searchstartstate->PlannerSpecificData);
if(startstateinfo->callnumberaccessed != pSearchStateSpace->callnumber)
ReInitializeSearchStateInfo(startstateinfo, pSearchStateSpace);
startstateinfo->g = 0;
//insert start state into the heap
key.key[0] = (long int)(pSearchStateSpace->eps*startstateinfo->h);
//key.key[1] = startstateinfo->h;
pSearchStateSpace->heap->insertheap(startstateinfo, key);
pSearchStateSpace->bReinitializeSearchStateSpace = false;
pSearchStateSpace->bReevaluatefvals = false;
}
//very first initialization
int ARAPlanner::InitializeSearchStateSpace(ARASearchStateSpace_t* pSearchStateSpace)
{
if(pSearchStateSpace->heap->currentsize != 0 ||
pSearchStateSpace->inconslist->currentsize != 0)
{
printf("ERROR in InitializeSearchStateSpace: heap or list is not empty\n");
exit(1);
}
pSearchStateSpace->eps = this->finitial_eps;
pSearchStateSpace->eps_satisfied = INFINITECOST;
pSearchStateSpace->searchiteration = 0;
pSearchStateSpace->bNewSearchIteration = true;
pSearchStateSpace->callnumber = 0;
pSearchStateSpace->bReevaluatefvals = false;
//create and set the search start state
pSearchStateSpace->searchgoalstate = NULL;
//pSearchStateSpace->searchstartstate = GetState(SearchStartStateID, pSearchStateSpace);
pSearchStateSpace->searchstartstate = NULL;
pSearchStateSpace->bReinitializeSearchStateSpace = true;
return 1;
}
int ARAPlanner::SetSearchGoalState(int SearchGoalStateID, ARASearchStateSpace_t* pSearchStateSpace)
{
if(pSearchStateSpace->searchgoalstate == NULL ||
pSearchStateSpace->searchgoalstate->StateID != SearchGoalStateID)
{
pSearchStateSpace->searchgoalstate = GetState(SearchGoalStateID, pSearchStateSpace);
//should be new search iteration
pSearchStateSpace->eps_satisfied = INFINITECOST;
pSearchStateSpace->bNewSearchIteration = true;
pSearchStateSpace_->eps = this->finitial_eps;
//recompute heuristic for the heap if heuristics is used
#if USE_HEUR
for(int i = 0; i < (int)pSearchStateSpace->searchMDP.StateArray.size(); i++)
{
CMDPSTATE* MDPstate = pSearchStateSpace->searchMDP.StateArray[i];
ARAState* state = (ARAState*)MDPstate->PlannerSpecificData;
state->h = ComputeHeuristic(MDPstate, pSearchStateSpace);
}
pSearchStateSpace->bReevaluatefvals = true;
#endif
}
return 1;
}
int ARAPlanner::SetSearchStartState(int SearchStartStateID, ARASearchStateSpace_t* pSearchStateSpace)
{
CMDPSTATE* MDPstate = GetState(SearchStartStateID, pSearchStateSpace);
if(MDPstate != pSearchStateSpace->searchstartstate)
{
pSearchStateSpace->searchstartstate = MDPstate;
pSearchStateSpace->bReinitializeSearchStateSpace = true;
}
return 1;
}
int ARAPlanner::ReconstructPath(ARASearchStateSpace_t* pSearchStateSpace)
{
if(bforwardsearch) //nothing to do, if search is backward
{
CMDPSTATE* MDPstate = pSearchStateSpace->searchgoalstate;
CMDPSTATE* PredMDPstate;
ARAState *predstateinfo, *stateinfo;
#if DEBUG
fprintf(fDeb, "reconstructing a path:\n");
#endif
while(MDPstate != pSearchStateSpace->searchstartstate)
{
stateinfo = (ARAState*)MDPstate->PlannerSpecificData;
#if DEBUG
PrintSearchState(stateinfo, fDeb);
#endif
if(stateinfo->g == INFINITECOST)
{
//printf("ERROR in ReconstructPath: g of the state on the path is INFINITE\n");
//exit(1);
return -1;
}
if(stateinfo->bestpredstate == NULL)
{
printf("ERROR in ReconstructPath: bestpred is NULL\n");
exit(1);
}
//get the parent state
PredMDPstate = stateinfo->bestpredstate;
predstateinfo = (ARAState*)PredMDPstate->PlannerSpecificData;
//set its best next info
predstateinfo->bestnextstate = MDPstate;
//check the decrease of g-values along the path
if(predstateinfo->v >= stateinfo->g)
{
printf("ERROR in ReconstructPath: g-values are non-decreasing\n");
PrintSearchState(predstateinfo, fDeb);
exit(1);
}
//transition back
MDPstate = PredMDPstate;
}
}
return 1;
}
void ARAPlanner::PrintSearchPath(ARASearchStateSpace_t* pSearchStateSpace, FILE* fOut)
{
ARAState* searchstateinfo;
CMDPSTATE* state;
int goalID;
int PathCost;
if(bforwardsearch)
{
state = pSearchStateSpace->searchstartstate;
goalID = pSearchStateSpace->searchgoalstate->StateID;
}
else
{
state = pSearchStateSpace->searchgoalstate;
goalID = pSearchStateSpace->searchstartstate->StateID;
}
if(fOut == NULL)
fOut = stdout;
PathCost = ((ARAState*)pSearchStateSpace->searchgoalstate->PlannerSpecificData)->g;
fprintf(fOut, "Printing a path from state %d to the goal state %d\n",
state->StateID, pSearchStateSpace->searchgoalstate->StateID);
fprintf(fOut, "Path cost = %d:\n", PathCost);
environment_->PrintState(state->StateID, false, fOut);
int costFromStart = 0;
while(state->StateID != goalID)
{
fprintf(fOut, "state %d ", state->StateID);
if(state->PlannerSpecificData == NULL)
{
fprintf(fOut, "path does not exist since search data does not exist\n");
break;
}
searchstateinfo = (ARAState*)state->PlannerSpecificData;
if(searchstateinfo->bestnextstate == NULL)
{
fprintf(fOut, "path does not exist since bestnextstate == NULL\n");
break;
}
if(searchstateinfo->g == INFINITECOST)
{
fprintf(fOut, "path does not exist since bestnextstate == NULL\n");
break;
}
int costToGoal = PathCost - costFromStart;
int transcost = searchstateinfo->g - ((ARAState*)(searchstateinfo->bestnextstate->PlannerSpecificData))->v;
if(bforwardsearch)
transcost = -transcost;
costFromStart += transcost;
fprintf(fOut, "g=%d-->state %d, h = %d ctg = %d ", searchstateinfo->g,
searchstateinfo->bestnextstate->StateID, searchstateinfo->h, costToGoal);
state = searchstateinfo->bestnextstate;
environment_->PrintState(state->StateID, false, fOut);
}
}
void ARAPlanner::PrintSearchState(ARAState* state, FILE* fOut)
{
fprintf(fOut, "state %d: h=%d g=%u v=%u iterc=%d callnuma=%d expands=%d heapind=%d inconslist=%d\n",
state->MDPstate->StateID, state->h, state->g, state->v,
state->iterationclosed, state->callnumberaccessed, state->numofexpands, state->heapindex, state->listelem[ARA_INCONS_LIST_ID]?1:0);
environment_->PrintState(state->MDPstate->StateID, true, fOut);
}
int ARAPlanner::getHeurValue(ARASearchStateSpace_t* pSearchStateSpace, int StateID)
{
CMDPSTATE* MDPstate = GetState(StateID, pSearchStateSpace);
ARAState* searchstateinfo = (ARAState*)MDPstate->PlannerSpecificData;
return searchstateinfo->h;
}
vector<int> ARAPlanner::GetSearchPath(ARASearchStateSpace_t* pSearchStateSpace, int& solcost)
{
vector<int> SuccIDV;
vector<int> CostV;
vector<int> wholePathIds;
ARAState* searchstateinfo;
CMDPSTATE* state = NULL;
CMDPSTATE* goalstate = NULL;
CMDPSTATE* startstate=NULL;
if(bforwardsearch)
{
startstate = pSearchStateSpace->searchstartstate;
goalstate = pSearchStateSpace->searchgoalstate;
//reconstruct the path by setting bestnextstate pointers appropriately
ReconstructPath(pSearchStateSpace);
}
else
{
startstate = pSearchStateSpace->searchgoalstate;
goalstate = pSearchStateSpace->searchstartstate;
}
state = startstate;
wholePathIds.push_back(state->StateID);
solcost = 0;
FILE* fOut = stdout;
while(state->StateID != goalstate->StateID)
{
if(state->PlannerSpecificData == NULL)
{
fprintf(fOut, "path does not exist since search data does not exist\n");
break;
}
searchstateinfo = (ARAState*)state->PlannerSpecificData;
if(searchstateinfo->bestnextstate == NULL)
{
fprintf(fOut, "path does not exist since bestnextstate == NULL\n");
break;
}
if(searchstateinfo->g == INFINITECOST)
{
fprintf(fOut, "path does not exist since bestnextstate == NULL\n");
break;
}
environment_->GetSuccs(state->StateID, &SuccIDV, &CostV);
int actioncost = INFINITECOST;
for(int i = 0; i < (int)SuccIDV.size(); i++)
{
if(SuccIDV.at(i) == searchstateinfo->bestnextstate->StateID)
actioncost = CostV.at(i);
}
if(actioncost == INFINITECOST)
printf("WARNING: actioncost = %d\n", actioncost);
solcost += actioncost;
//fprintf(fDeb, "actioncost=%d between states %d and %d\n",
// actioncost, state->StateID, searchstateinfo->bestnextstate->StateID);
//environment_->PrintState(state->StateID, false, fDeb);
//environment_->PrintState(searchstateinfo->bestnextstate->StateID, false, fDeb);
#if DEBUG
ARAState* nextstateinfo = (ARAState*)(searchstateinfo->bestnextstate->PlannerSpecificData);
if(actioncost != abs((int)(searchstateinfo->g - nextstateinfo->g)) && pSearchStateSpace->eps_satisfied <= 1.001)
{
fprintf(fDeb, "ERROR: actioncost=%d is not matching the difference in g-values of %d\n",
actioncost, abs((int)(searchstateinfo->g - nextstateinfo->g)));
printf("ERROR: actioncost=%d is not matching the difference in g-values of %d\n",
actioncost,abs((int)(searchstateinfo->g - nextstateinfo->g)));
PrintSearchState(searchstateinfo, fDeb);
PrintSearchState(nextstateinfo, fDeb);
}
#endif
state = searchstateinfo->bestnextstate;
wholePathIds.push_back(state->StateID);
}
return wholePathIds;
}
bool ARAPlanner::Search(ARASearchStateSpace_t* pSearchStateSpace, vector<int>& pathIds, int & PathCost, bool bFirstSolution, bool bOptimalSolution, double MaxNumofSecs)
{
CKey key;
TimeStarted = clock();
searchexpands = 0;
#if DEBUG
fprintf(fDeb, "new search call (call number=%d)\n", pSearchStateSpace->callnumber);
#endif
if(pSearchStateSpace->bReinitializeSearchStateSpace == true){
//re-initialize state space
ReInitializeSearchStateSpace(pSearchStateSpace);
}
if(bOptimalSolution)
{
pSearchStateSpace->eps = 1;
MaxNumofSecs = INFINITECOST;
}
else if(bFirstSolution)
{
MaxNumofSecs = INFINITECOST;
}
//the main loop of ARA*
int prevexpands = 0;
clock_t loop_time;
while(pSearchStateSpace->eps_satisfied > ARA_FINAL_EPS &&
(clock()- TimeStarted) < MaxNumofSecs*(double)CLOCKS_PER_SEC)
{
loop_time = clock();
//decrease eps for all subsequent iterations
if(fabs(pSearchStateSpace->eps_satisfied - pSearchStateSpace->eps) < ERR_EPS && !bFirstSolution)
{
pSearchStateSpace->eps = pSearchStateSpace->eps - ARA_DECREASE_EPS;
if(pSearchStateSpace->eps < ARA_FINAL_EPS)
pSearchStateSpace->eps = ARA_FINAL_EPS;
//the priorities need to be updated
pSearchStateSpace->bReevaluatefvals = true;
//it will be a new search
pSearchStateSpace->bNewSearchIteration = true;
//build a new open list by merging it with incons one
BuildNewOPENList(pSearchStateSpace);
}
if(pSearchStateSpace->bNewSearchIteration)
{
pSearchStateSpace->searchiteration++;
pSearchStateSpace->bNewSearchIteration = false;
}
//re-compute f-values if necessary and reorder the heap
if(pSearchStateSpace->bReevaluatefvals)
Reevaluatefvals(pSearchStateSpace);
//improve or compute path
if(ImprovePath(pSearchStateSpace, MaxNumofSecs) == 1){
pSearchStateSpace->eps_satisfied = pSearchStateSpace->eps;
}
//print the solution cost and eps bound
printf("eps=%f expands=%d g(searchgoal)=%d time=%.3f\n", pSearchStateSpace->eps_satisfied, searchexpands - prevexpands,
((ARAState*)pSearchStateSpace->searchgoalstate->PlannerSpecificData)->g,double(clock()-loop_time)/CLOCKS_PER_SEC);
#if DEBUG
fprintf(fDeb, "eps=%f expands=%d g(searchgoal)=%d time=%.3f\n", pSearchStateSpace->eps_satisfied, searchexpands - prevexpands,
((ARAState*)pSearchStateSpace->searchgoalstate->PlannerSpecificData)->g,double(clock()-loop_time)/CLOCKS_PER_SEC);
PrintSearchState((ARAState*)pSearchStateSpace->searchgoalstate->PlannerSpecificData, fDeb);
#endif
prevexpands = searchexpands;
//if just the first solution then we are done
if(bFirstSolution)
break;
//no solution exists
if(((ARAState*)pSearchStateSpace->searchgoalstate->PlannerSpecificData)->g == INFINITECOST)
break;
}
#if DEBUG
fflush(fDeb);
#endif
PathCost = ((ARAState*)pSearchStateSpace->searchgoalstate->PlannerSpecificData)->g;
MaxMemoryCounter += environment_->StateID2IndexMapping.size()*sizeof(int);
printf("MaxMemoryCounter = %d\n", MaxMemoryCounter);
int solcost = INFINITECOST;
bool ret = false;
if(PathCost == INFINITECOST)
{
printf("could not find a solution\n");
ret = false;
}
else
{
printf("solution is found\n");
pathIds = GetSearchPath(pSearchStateSpace, solcost);
ret = true;
}
printf("total expands this call = %d, planning time = %.3f secs, solution cost=%d\n",
searchexpands, (clock()-TimeStarted)/((double)CLOCKS_PER_SEC), solcost);
//fprintf(fStat, "%d %d\n", searchexpands, solcost);
return ret;
}
//-----------------------------Interface function-----------------------------------------------------
//returns 1 if found a solution, and 0 otherwise
int ARAPlanner::replan(double allocated_time_secs, vector<int>* solution_stateIDs_V)
{
int solcost;
return replan(allocated_time_secs, solution_stateIDs_V, &solcost);
}
//returns 1 if found a solution, and 0 otherwise
int ARAPlanner::replan(double allocated_time_secs, vector<int>* solution_stateIDs_V, int* psolcost)
{
vector<int> pathIds;
bool bFound = false;
int PathCost;
bool bFirstSolution = this->bsearchuntilfirstsolution;
bool bOptimalSolution = false;
*psolcost = 0;
printf("planner: replan called (bFirstSol=%d, bOptSol=%d)\n", bFirstSolution, bOptimalSolution);
//plan
if((bFound = Search(pSearchStateSpace_, pathIds, PathCost, bFirstSolution, bOptimalSolution, allocated_time_secs)) == false)
{
printf("failed to find a solution\n");
}
//copy the solution
*solution_stateIDs_V = pathIds;
*psolcost = PathCost;
return (int)bFound;
}
int ARAPlanner::set_goal(int goal_stateID)
{
printf("planner: setting goal to %d\n", goal_stateID);
environment_->PrintState(goal_stateID, true, stdout);
if(bforwardsearch)
{
if(SetSearchGoalState(goal_stateID, pSearchStateSpace_) != 1)
{
printf("ERROR: failed to set search goal state\n");
return 0;
}
}
else
{
if(SetSearchStartState(goal_stateID, pSearchStateSpace_) != 1)
{
printf("ERROR: failed to set search start state\n");
return 0;
}
}
return 1;
}
int ARAPlanner::set_start(int start_stateID)
{
printf("planner: setting start to %d\n", start_stateID);
environment_->PrintState(start_stateID, true, stdout);
if(bforwardsearch)
{
if(SetSearchStartState(start_stateID, pSearchStateSpace_) != 1)
{
printf("ERROR: failed to set search start state\n");
return 0;
}
}
else
{
if(SetSearchGoalState(start_stateID, pSearchStateSpace_) != 1)
{
printf("ERROR: failed to set search goal state\n");
return 0;
}
}
return 1;
}
void ARAPlanner::costs_changed(StateChangeQuery const & stateChange)
{
pSearchStateSpace_->bReinitializeSearchStateSpace = true;
}
void ARAPlanner::costs_changed()
{
pSearchStateSpace_->bReinitializeSearchStateSpace = true;
}
int ARAPlanner::force_planning_from_scratch()
{
printf("planner: forceplanfromscratch set\n");
pSearchStateSpace_->bReinitializeSearchStateSpace = true;
return 1;
}
int ARAPlanner::set_search_mode(bool bSearchUntilFirstSolution)
{
printf("planner: search mode set to %d\n", bSearchUntilFirstSolution);
bsearchuntilfirstsolution = bSearchUntilFirstSolution;
return 1;
}
void ARAPlanner::print_searchpath(FILE* fOut)
{
PrintSearchPath(pSearchStateSpace_, fOut);
}
//---------------------------------------------------------------------------------------------------------
| [
"maximl@f5854215-dd47-0410-b2c4-cdd35faa7885",
"eitanme@f5854215-dd47-0410-b2c4-cdd35faa7885",
"bcohen1@f5854215-dd47-0410-b2c4-cdd35faa7885",
"gerkey@f5854215-dd47-0410-b2c4-cdd35faa7885",
"bhaskarama@f5854215-dd47-0410-b2c4-cdd35faa7885",
"mcgann@f5854215-dd47-0410-b2c4-cdd35faa7885",
"poftwaresatent@f5854215-dd47-0410-b2c4-cdd35faa7885"
]
| [
[
[
1,
39
],
[
42,
44
],
[
46,
72
],
[
74,
75
],
[
79,
132
],
[
134,
153
],
[
157,
170
],
[
174,
174
],
[
176,
299
],
[
301,
398
],
[
400,
400
],
[
407,
422
],
[
426,
437
],
[
439,
581
],
[
587,
658
],
[
660,
726
],
[
741,
744
],
[
748,
772
],
[
774,
778
],
[
780,
857
],
[
869,
914
],
[
916,
919
],
[
921,
922
],
[
924,
932
],
[
934,
949
],
[
951,
960
],
[
962,
967
],
[
969,
1002
],
[
1004,
1016
],
[
1020,
1024
],
[
1036,
1041
],
[
1044,
1045
],
[
1048,
1066
],
[
1069,
1092
],
[
1094,
1101
],
[
1105,
1106
],
[
1111,
1121
],
[
1123,
1123
],
[
1125,
1130
],
[
1134,
1140
],
[
1142,
1147
],
[
1150,
1167
],
[
1170,
1175
],
[
1177,
1191
],
[
1193,
1200
],
[
1208,
1219
],
[
1222,
1223
],
[
1229,
1238
]
],
[
[
40,
41
],
[
73,
73
],
[
76,
77
],
[
154,
156
],
[
171,
173
],
[
300,
300
],
[
438,
438
],
[
582,
586
],
[
727,
740
],
[
745,
747
],
[
773,
773
],
[
779,
779
],
[
868,
868
],
[
915,
915
],
[
920,
920
],
[
923,
923
],
[
933,
933
],
[
950,
950
],
[
961,
961
],
[
968,
968
],
[
1067,
1068
],
[
1141,
1141
],
[
1148,
1149
],
[
1168,
1169
],
[
1176,
1176
]
],
[
[
45,
45
],
[
175,
175
],
[
399,
399
],
[
401,
406
],
[
423,
425
],
[
659,
659
],
[
858,
867
],
[
1003,
1003
],
[
1017,
1019
],
[
1025,
1035
],
[
1042,
1043
],
[
1046,
1047
],
[
1102,
1104
],
[
1107,
1110
],
[
1122,
1122
],
[
1124,
1124
],
[
1131,
1133
],
[
1201,
1207
],
[
1220,
1221
],
[
1224,
1228
]
],
[
[
78,
78
]
],
[
[
133,
133
]
],
[
[
1093,
1093
]
],
[
[
1192,
1192
]
]
]
|
d1ddb550d8fd96379cf8eee249e2f9c31dcc027d | ade08cd4a76f2c4b9b5fdbb9b9edfbc7996b1bbc | /computer_graphics/lab5/Src/Application/material.h | 546b1bd69fc9745fb50424fc4b56fb00279eb805 | []
| no_license | smi13/semester07 | 6789be72d74d8d502f0a0d919dca07ad5cbaed0d | 4d1079a446269646e1a0e3fe12e8c5e74c9bb409 | refs/heads/master | 2021-01-25T09:53:45.424234 | 2011-01-07T16:08:11 | 2011-01-07T16:08:11 | 859,509 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 317 | h | #ifndef _material_h
#define _material_h
#include <d3dx9.h>
namespace cg_labs
{
struct Material
{
Material();
Material( D3DXCOLOR amb, D3DXCOLOR spec, D3DXCOLOR dif );
operator D3DMATERIAL9();
D3DXCOLOR Ambient, Specular, Diffuse;
};
}
#endif /* _material_h */ | [
"[email protected]"
]
| [
[
[
1,
20
]
]
]
|
b7445ad602c4242ad6dfca24a78ed679d9fae2d7 | 2ff4099407bd04ffc49489f22bd62996ad0d0edd | /Project/Code/inc/FrameBufferObject.h | 4c9703d3efd6cdd7ec53dfd560b221640c34d0c4 | []
| no_license | willemfrishert/imagebasedrendering | 13687840a8e5b37a38cc91c3c5b8135f9c1881f2 | 1cb9ed13b820b791a0aa2c80564dc33fefdc47a2 | refs/heads/master | 2016-09-10T15:23:42.506289 | 2007-06-04T11:52:13 | 2007-06-04T11:52:13 | 32,184,690 | 0 | 1 | null | null | null | null | ISO-8859-13 | C++ | false | false | 757 | h | #pragma once
/**
* @usage: Create object; bind and attach texture
*
* @file FrameBufferObject.h
* @author Joćo Pedro Jorge
*/
struct FBOTextureAttachment
{
GLuint id;
GLenum attachment;
GLenum target;
GLint mipmapLevel;
};
class FrameBufferObject
{
public:
FrameBufferObject(void);
~FrameBufferObject(void);
void attachTexture(GLuint texture, GLenum attachment, GLenum textarget, GLint mipmapLevel);
void attachTextureAttachment(const FBOTextureAttachment& attachment);
void attachDepthBuffer(GLuint depthBufferId);
void attachDepthRenderBuffer(GLuint aWidth, GLuint aHeight);
void bind();
static void unbind();
// methods
private:
void errcheck() const;
// attributes
private:
GLuint m_FrameBufferId;
}; | [
"wfrishert@15324175-3028-0410-9899-2d1205849c9d",
"jpjorge@15324175-3028-0410-9899-2d1205849c9d"
]
| [
[
[
1,
2
],
[
9,
17
],
[
25,
25
],
[
27,
27
]
],
[
[
3,
8
],
[
18,
24
],
[
26,
26
],
[
28,
40
]
]
]
|
d2fa8ad5789c934c06a0cd9cc7a97bdb1a3c0389 | 39040af0ff84935d083209731dd7343f93fa2874 | /demo/gdiplus/dlg_gdiplus/dlg_gdiplus.cpp | fde623a58361f4086d782473e98f46564ad081b9 | [
"Apache-2.0"
]
| permissive | alanzw/ulib-win | 02f8b7bcd8220b6a057fd3b33e733500294f9b56 | b67f644ed11c849e3c93b909f90d443df7be4e4c | refs/heads/master | 2020-04-06T05:26:54.849486 | 2011-07-23T05:47:17 | 2011-07-23T05:47:17 | 34,505,292 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,829 | cpp | //#define UNICODE
#include "resource.h"
#include <windows.h>
#include <tchar.h>
#ifdef __GNUC__
#include <gdiplus/gdiPlus.h>
#else
#include <gdiPlus.h>
#endif
#include "udialogx.h"
#include "udlgapp.h"
#include "ugdiplus.h"
using huys::UDialogBox;
using namespace Gdiplus;
class MyDialog : public UDialogBox
{
enum {
ID_UHEADER = 11
};
public:
MyDialog(HINSTANCE hInst, UINT nID)
: UDialogBox(hInst, nID){}
virtual void onDraw(HDC hdc)
{
Graphics graphics(hdc);
Pen pen(Color(255, 0, 0, 255));
graphics.DrawLine(&pen, 0, 0, 200, 100);
SolidBrush solidBrush(Color(255, 255, 0, 0));
graphics.FillEllipse(&solidBrush, 0, 0, 100, 60);
SolidBrush brush(Color(255, 0, 0, 255));
FontFamily fontFamily(L"Times New Roman");
Font font(&fontFamily, 24, FontStyleRegular, UnitPixel);
PointF pointF(10.0f, 20.0f);
graphics.DrawString(L"Hello World!", -1, &font, pointF, &brush);
GraphicsPath path;
Pen penJoin(Color(255, 0, 0, 255), 8);
path.StartFigure();
path.AddLine(Point(50, 200), Point(100, 200));
path.AddLine(Point(100, 200), Point(100, 250));
penJoin.SetLineJoin(LineJoinBevel);
graphics.DrawPath(&penJoin, &path);
pen.SetStartCap(LineCapArrowAnchor);
pen.SetEndCap(LineCapRoundAnchor);
graphics.DrawLine(&pen, 20, 175, 300, 175);
Pen blackPen(Color(255, 0, 0, 0), 2);
//
PointF pt1(210.0f, 10.0f);
PointF pt2(210.0f, 100.0f);
PointF pt3(250.0f, 50.0f);
PointF pt4(210.0f, 10.0f);
PointF points[4] = {pt1, pt2, pt3, pt4};
graphics.DrawLines(&blackPen, points, 4);
}
private:
UGDIPlusHelper _gh;
};
UDLGAPP_T(MyDialog, IDD_TEST);
| [
"fox000002@48c0247c-a797-11de-8c46-7bd654735883"
]
| [
[
[
1,
79
]
]
]
|
bad28fc9b05de8e1e7b7f1df069109f098346af1 | df238aa31eb8c74e2c208188109813272472beec | /Source/PluginBaseArea/StdAfx.cpp | e718131416f12500c356c83d28825f4d765a1238 | []
| no_license | myme5261314/plugin-system | d3166f36972c73f74768faae00ac9b6e0d58d862 | be490acba46c7f0d561adc373acd840201c0570c | refs/heads/master | 2020-03-29T20:00:01.155206 | 2011-06-27T15:23:30 | 2011-06-27T15:23:30 | 39,724,191 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 216 | cpp | // stdafx.cpp : source file that includes just the standard includes
// PluginBaseArea.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
| [
"myme5261314@ec588229-7da7-b333-41f6-0e1ebc3afda5"
]
| [
[
[
1,
8
]
]
]
|
12bd1c6f9b123928705e8921a7db77b55ab92749 | 7a310d01d1a4361fd06b40a74a2afc8ddc23b4d3 | /src_plugin/NemuBarForDonutP2_src/NemuBarForDonutP.cpp | ee49e8a4b8e7bcc19439dd9080b4aca0cdb44c47 | []
| no_license | plus7/DonutG | b6fec6111d25b60f9a9ae5798e0ab21bb2fa28f6 | 2d204c36f366d6162eaf02f4b2e1b8bc7b403f6b | refs/heads/master | 2020-06-01T15:30:31.747022 | 2010-08-21T18:51:01 | 2010-08-21T18:51:01 | 767,753 | 1 | 2 | null | null | null | null | SHIFT_JIS | C++ | false | false | 2,021 | cpp | // NemuBarForDonutP.cpp : DLL エクスポートのインプリメンテーション
// メモ: Proxy/Stub 情報
// 別々の proxy/stub DLL をビルドするためには、プロジェクトのディレクトリで
// nmake -f NemuBarForDonutPps.mak を実行してください。
#include "stdafx.h"
#include "resource.h"
#include "NemuBarForDonutP.h"
#include "NemuChecker.h"
#include "PluginInfo.h"
CComModule _Module;
CNemuToolBar g_NemuBar;
IUpdateChecker* CNemuToolBar::m_pChecker = NULL;
bool CNemuToolBar::m_bUpdate = false;
BEGIN_OBJECT_MAP(ObjectMap)
END_OBJECT_MAP()
/////////////////////////////////////////////////////////////////////////////
// DLL エントリ ポイント
extern "C"
BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID /*lpReserved*/)
{
if (dwReason == DLL_PROCESS_ATTACH)
{
_Module.Init(ObjectMap, hInstance);
DisableThreadLibraryCalls(hInstance);
}
else if (dwReason == DLL_PROCESS_DETACH)
_Module.Term();
CNemuToolBar::UninitNemuBar();
return TRUE; // ok
}
HWND WINAPI CreateToolBar(HWND hWndParent, UINT nID)
{
CNemuToolBar::InitNemuBar();
return g_NemuBar.Create(hWndParent, nID);
}
void WINAPI ShowToolBarMenu(UINT nID)
{
g_NemuBar.ShowMenu( nID );
}
void WINAPI PluginSetting()
{
//設定画面表示
g_NemuBar.ShowSettingDlg();
}
void WINAPI GetPluginInfo(PLUGININFO* pstPluginInfo)
{
memset( pstPluginInfo, 0, sizeof(PLUGININFO) );
pstPluginInfo->type = PLT_TOOLBAR;
strcpy( pstPluginInfo->name, "NemuBarForDonutP" );
strcpy( pstPluginInfo->version, "2.0.0" );
strcpy( pstPluginInfo->versionDate, "2004.05.15" );
strcpy( pstPluginInfo->authorName, "えがみん" );
strcpy( pstPluginInfo->authorUrl, "http://homepage2.nifty.com/egamin/donutnemu.html#DonutP" );
strcpy( pstPluginInfo->authorEmail, "---" );
strcpy( pstPluginInfo->comment, "NemuBarは右記より入手 http://www.aa.alpha-net.ne.jp/bosuke/" );
}
| [
"[email protected]"
]
| [
[
[
1,
69
]
]
]
|
c2df2656352b913e72248919f670790d0b5312df | 0da7fec56f63012180d848b1e72bada9f6984ef3 | /PocketDjVu_root/PocketDjvu/CNofyIcon.h | 66b830ff22bf323beca1faa92b50548d5ace140c | []
| no_license | UIKit0/pocketdjvu | a34fb2b8ac724d25fab7a0298942db1755098b25 | 4c0c761e6a3d3628440fb4fb0a9c54e5594807d9 | refs/heads/master | 2021-01-20T12:01:16.947853 | 2010-05-03T12:29:44 | 2010-05-03T12:29:44 | 32,293,688 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,078 | h | #pragma once
class CNofyIcon
{
public:
CNofyIcon() : m_bInstalled(), m_ni()
{
}
void Setup( HWND hwnd, UINT msgID, int iconID )
{
m_ni.cbSize = sizeof m_ni;
m_ni.hIcon = ::LoadIcon( ::GetModuleHandle(0), MAKEINTRESOURCE( iconID ) );
m_ni.hWnd = hwnd;
// m_ni.szTip = L"PocketDjVu";
m_ni.uCallbackMessage = msgID;
m_ni.uFlags = NIF_ICON|NIF_MESSAGE;//|NIF_TIP;
m_ni.uID = 12 + msgID;
}
bool Install()
{
if ( !m_ni.hIcon )
return false;
m_bInstalled = !!Shell_NotifyIcon( NIM_ADD, &m_ni );
return m_bInstalled;
}
bool Deinstall()
{
if ( !m_bInstalled )
return false;
bool res = !!Shell_NotifyIcon( NIM_DELETE, &m_ni );
if ( res )
m_bInstalled = true;
return res;
}
bool IsInstalled()
{
return m_bInstalled;
}
virtual ~CNofyIcon()
{
if ( m_bInstalled )
Deinstall();
}
private:
bool m_bInstalled;
NOTIFYICONDATA m_ni;
}; | [
"Igor.Solovyov@84cd470b-3125-0410-acc3-039690e87181"
]
| [
[
[
1,
55
]
]
]
|
fd33f86794cd4c972f2e937605a2eef3bf9a8938 | 9a48be80edc7692df4918c0222a1640545384dbb | /Libraries/Boost1.40/libs/intrusive/test/unordered_set_test.cpp | a13d9e1b1739a98e19f25a63ba217e3a2254ee08 | [
"BSL-1.0"
]
| permissive | fcrick/RepSnapper | 05e4fb1157f634acad575fffa2029f7f655b7940 | a5809843f37b7162f19765e852b968648b33b694 | refs/heads/master | 2021-01-17T21:42:29.537504 | 2010-06-07T05:38:05 | 2010-06-07T05:38:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,238 | cpp | /////////////////////////////////////////////////////////////////////////////
//
// (C) Copyright Olaf Krzikalla 2004-2006.
// (C) Copyright Ion Gaztanaga 2006-2008.
//
// 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/intrusive for documentation.
//
/////////////////////////////////////////////////////////////////////////////
#include <boost/intrusive/detail/config_begin.hpp>
#include <boost/intrusive/unordered_set.hpp>
#include <boost/intrusive/detail/pointer_to_other.hpp>
#include "itestvalue.hpp"
#include "smart_ptr.hpp"
#include "common_functors.hpp"
#include <vector>
#include <set>
#include <boost/detail/lightweight_test.hpp>
#include "test_macros.hpp"
#include "test_container.hpp"
using namespace boost::intrusive;
struct my_tag;
template<class VoidPointer>
struct hooks
{
typedef unordered_set_base_hook<void_pointer<VoidPointer> > base_hook_type;
typedef unordered_set_base_hook
< link_mode<auto_unlink>
, void_pointer<VoidPointer>
, tag<my_tag>
, store_hash<true>
> auto_base_hook_type;
typedef unordered_set_member_hook
< void_pointer<VoidPointer>
, optimize_multikey<true>
> member_hook_type;
typedef unordered_set_member_hook
< link_mode<auto_unlink>, void_pointer<VoidPointer>
, store_hash<true>
, optimize_multikey<true>
> auto_member_hook_type;
};
static const std::size_t BucketSize = 8;
template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental>
struct test_unordered_set
{
typedef typename ValueTraits::value_type value_type;
static void test_all(std::vector<value_type>& values);
static void test_sort(std::vector<value_type>& values);
static void test_insert(std::vector<value_type>& values);
static void test_swap(std::vector<value_type>& values);
static void test_rehash(std::vector<value_type>& values, detail::true_);
static void test_rehash(std::vector<value_type>& values, detail::false_);
static void test_find(std::vector<value_type>& values);
static void test_impl();
static void test_clone(std::vector<value_type>& values);
};
template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental>
void test_unordered_set<ValueTraits, CacheBegin, CompareHash, Incremental>::
test_all(std::vector<typename ValueTraits::value_type>& values)
{
typedef typename ValueTraits::value_type value_type;
typedef unordered_set
<value_type
, value_traits<ValueTraits>
, constant_time_size<value_type::constant_time_size>
, cache_begin<CacheBegin>
, compare_hash<CompareHash>
, incremental<Incremental>
> unordered_set_type;
typedef typename unordered_set_type::bucket_traits bucket_traits;
{
typename unordered_set_type::bucket_type buckets [BucketSize];
unordered_set_type testset(bucket_traits(buckets, BucketSize));
testset.insert(values.begin(), values.end());
test::test_container(testset);
testset.clear();
testset.insert(values.begin(), values.end());
test::test_common_unordered_and_associative_container(testset, values);
testset.clear();
testset.insert(values.begin(), values.end());
test::test_unordered_associative_container(testset, values);
testset.clear();
testset.insert(values.begin(), values.end());
test::test_unique_container(testset, values);
}
test_sort(values);
test_insert(values);
test_swap(values);
test_rehash(values, detail::bool_<Incremental>());
test_find(values);
test_impl();
test_clone(values);
}
//test case due to an error in tree implementation:
template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental>
void test_unordered_set<ValueTraits, CacheBegin, CompareHash, Incremental>::test_impl()
{
typedef typename ValueTraits::value_type value_type;
typedef unordered_set
<value_type
, value_traits<ValueTraits>
, constant_time_size<value_type::constant_time_size>
, cache_begin<CacheBegin>
, compare_hash<CompareHash>
, incremental<Incremental>
> unordered_set_type;
typedef typename unordered_set_type::bucket_traits bucket_traits;
std::vector<value_type> values (5);
for (int i = 0; i < 5; ++i)
values[i].value_ = i;
typename unordered_set_type::bucket_type buckets [BucketSize];
unordered_set_type testset(bucket_traits(buckets, BucketSize));
for (int i = 0; i < 5; ++i)
testset.insert (values[i]);
testset.erase (testset.iterator_to (values[0]));
testset.erase (testset.iterator_to (values[1]));
testset.insert (values[1]);
testset.erase (testset.iterator_to (values[2]));
testset.erase (testset.iterator_to (values[3]));
}
//test: constructor, iterator, clear, reverse_iterator, front, back, size:
template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental>
void test_unordered_set<ValueTraits, CacheBegin, CompareHash, Incremental>::
test_sort(std::vector<typename ValueTraits::value_type>& values)
{
typedef typename ValueTraits::value_type value_type;
typedef unordered_set
<value_type
, value_traits<ValueTraits>
, constant_time_size<value_type::constant_time_size>
, cache_begin<CacheBegin>
, compare_hash<CompareHash>
, incremental<Incremental>
> unordered_set_type;
typedef typename unordered_set_type::bucket_traits bucket_traits;
typename unordered_set_type::bucket_type buckets [BucketSize];
unordered_set_type testset1(values.begin(), values.end(), bucket_traits(buckets, BucketSize));
BOOST_TEST (5 == std::distance(testset1.begin(), testset1.end()));
if(Incremental){
{ int init_values [] = { 4, 5, 1, 2, 3 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); }
}
else{
{ int init_values [] = { 1, 2, 3, 4, 5 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); }
}
testset1.clear();
BOOST_TEST (testset1.empty());
}
//test: insert, const_iterator, const_reverse_iterator, erase, iterator_to:
template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental>
void test_unordered_set<ValueTraits, CacheBegin, CompareHash, Incremental>::
test_insert(std::vector<typename ValueTraits::value_type>& values)
{
typedef typename ValueTraits::value_type value_type;
typedef unordered_set
<value_type
, value_traits<ValueTraits>
, constant_time_size<value_type::constant_time_size>
, cache_begin<CacheBegin>
, compare_hash<CompareHash>
, incremental<Incremental>
> unordered_set_type;
typedef typename unordered_set_type::bucket_traits bucket_traits;
typename unordered_set_type::bucket_type buckets [BucketSize];
unordered_set_type testset(bucket_traits(buckets, BucketSize));
testset.insert(&values[0] + 2, &values[0] + 5);
const unordered_set_type& const_testset = testset;
if(Incremental)
{
{ int init_values [] = { 4, 5, 1 };
TEST_INTRUSIVE_SEQUENCE( init_values, const_testset.begin() ); }
typename unordered_set_type::iterator i = testset.begin();
BOOST_TEST (i->value_ == 4);
i = testset.insert(values[0]).first;
BOOST_TEST (&*i == &values[0]);
i = testset.iterator_to (values[2]);
BOOST_TEST (&*i == &values[2]);
testset.erase (i);
{ int init_values [] = { 5, 1, 3 };
TEST_INTRUSIVE_SEQUENCE( init_values, const_testset.begin() ); }
}
else{
{ int init_values [] = { 1, 4, 5 };
TEST_INTRUSIVE_SEQUENCE( init_values, const_testset.begin() ); }
typename unordered_set_type::iterator i = testset.begin();
BOOST_TEST (i->value_ == 1);
i = testset.insert(values[0]).first;
BOOST_TEST (&*i == &values[0]);
i = testset.iterator_to (values[2]);
BOOST_TEST (&*i == &values[2]);
testset.erase (i);
{ int init_values [] = { 1, 3, 5 };
TEST_INTRUSIVE_SEQUENCE( init_values, const_testset.begin() ); }
}
}
//test: insert (seq-version), swap, erase (seq-version), size:
template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental>
void test_unordered_set<ValueTraits, CacheBegin, CompareHash, Incremental>::
test_swap(std::vector<typename ValueTraits::value_type>& values)
{
typedef typename ValueTraits::value_type value_type;
typedef unordered_set
<value_type
, value_traits<ValueTraits>
, constant_time_size<value_type::constant_time_size>
, cache_begin<CacheBegin>
, compare_hash<CompareHash>
, incremental<Incremental>
> unordered_set_type;
typedef typename unordered_set_type::bucket_traits bucket_traits;
typename unordered_set_type::bucket_type buckets1 [BucketSize];
typename unordered_set_type::bucket_type buckets2 [BucketSize];
unordered_set_type testset1(&values[0], &values[0] + 2, bucket_traits(buckets1, BucketSize));
unordered_set_type testset2(bucket_traits(buckets2, BucketSize));
testset2.insert (&values[0] + 2, &values[0] + 6);
testset1.swap (testset2);
if(Incremental){
{ int init_values [] = { 4, 5, 1, 2 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); }
{ int init_values [] = { 2, 3 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset2.begin() ); }
testset1.erase (testset1.iterator_to(values[4]), testset1.end());
BOOST_TEST (testset1.size() == 1);
BOOST_TEST (&*testset1.begin() == &values[2]);
}
else{
{ int init_values [] = { 1, 2, 4, 5 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); }
{ int init_values [] = { 2, 3 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset2.begin() ); }
testset1.erase (testset1.iterator_to(values[5]), testset1.end());
BOOST_TEST (testset1.size() == 1);
BOOST_TEST (&*testset1.begin() == &values[3]);
}
}
//test: rehash:
template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental>
void test_unordered_set<ValueTraits, CacheBegin, CompareHash, Incremental>::
test_rehash(std::vector<typename ValueTraits::value_type>& values, detail::true_)
{
typedef typename ValueTraits::value_type value_type;
typedef unordered_set
<value_type
, value_traits<ValueTraits>
, constant_time_size<value_type::constant_time_size>
, cache_begin<CacheBegin>
, compare_hash<CompareHash>
, incremental<Incremental>
> unordered_set_type;
typedef typename unordered_set_type::bucket_traits bucket_traits;
//Build a uset
typename unordered_set_type::bucket_type buckets1 [BucketSize];
typename unordered_set_type::bucket_type buckets2 [BucketSize*2];
unordered_set_type testset1(&values[0], &values[0] + 6, bucket_traits(buckets1, BucketSize));
//Test current state
BOOST_TEST(testset1.split_count() == BucketSize/2);
{ int init_values [] = { 4, 5, 1, 2, 3 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); }
//Incremental rehash step
BOOST_TEST (testset1.incremental_rehash() == true);
BOOST_TEST(testset1.split_count() == (BucketSize/2+1));
{ int init_values [] = { 5, 1, 2, 3, 4 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); }
//Rest of incremental rehashes should lead to the same sequence
for(std::size_t split_bucket = testset1.split_count(); split_bucket != BucketSize; ++split_bucket){
BOOST_TEST (testset1.incremental_rehash() == true);
BOOST_TEST(testset1.split_count() == (split_bucket+1));
{ int init_values [] = { 1, 2, 3, 4, 5 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); }
}
//This incremental rehash should fail because we've reached the end of the bucket array
BOOST_TEST(testset1.incremental_rehash() == false);
BOOST_TEST(testset1.split_count() == BucketSize);
{ int init_values [] = { 1, 2, 3, 4, 5 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); }
//
//Try incremental hashing specifying a new bucket traits pointing to the same array
//
//This incremental rehash should fail because the new size is not twice the original
BOOST_TEST(testset1.incremental_rehash(bucket_traits(buckets1, BucketSize)) == false);
BOOST_TEST(testset1.split_count() == BucketSize);
{ int init_values [] = { 1, 2, 3, 4, 5 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); }
//This incremental rehash should success because the new size is twice the original
//and split_count is the same as the old bucket count
BOOST_TEST(testset1.incremental_rehash(bucket_traits(buckets1, BucketSize*2)) == true);
BOOST_TEST(testset1.split_count() == BucketSize);
{ int init_values [] = { 1, 2, 3, 4, 5 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); }
//This incremental rehash should also success because the new size is half the original
//and split_count is the same as the new bucket count
BOOST_TEST(testset1.incremental_rehash(bucket_traits(buckets1, BucketSize)) == true);
BOOST_TEST(testset1.split_count() == BucketSize);
{ int init_values [] = { 1, 2, 3, 4, 5 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); }
//
//Try incremental hashing specifying a new bucket traits pointing to the same array
//
//This incremental rehash should fail because the new size is not twice the original
BOOST_TEST(testset1.incremental_rehash(bucket_traits(buckets2, BucketSize)) == false);
BOOST_TEST(testset1.split_count() == BucketSize);
{ int init_values [] = { 1, 2, 3, 4, 5 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); }
//This incremental rehash should success because the new size is twice the original
//and split_count is the same as the old bucket count
BOOST_TEST(testset1.incremental_rehash(bucket_traits(buckets2, BucketSize*2)) == true);
BOOST_TEST(testset1.split_count() == BucketSize);
{ int init_values [] = { 1, 2, 3, 4, 5 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); }
//This incremental rehash should also success because the new size is half the original
//and split_count is the same as the new bucket count
BOOST_TEST(testset1.incremental_rehash(bucket_traits(buckets1, BucketSize)) == true);
BOOST_TEST(testset1.split_count() == BucketSize);
{ int init_values [] = { 1, 2, 3, 4, 5 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); }
//Full shrink rehash
testset1.rehash(bucket_traits(buckets1, 4));
BOOST_TEST (testset1.size() == values.size()-1);
BOOST_TEST (testset1.incremental_rehash() == false);
{ int init_values [] = { 4, 5, 1, 2, 3 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); }
//Full shrink rehash again
testset1.rehash(bucket_traits(buckets1, 2));
BOOST_TEST (testset1.size() == values.size()-1);
BOOST_TEST (testset1.incremental_rehash() == false);
{ int init_values [] = { 2, 4, 3, 5, 1 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); }
//Full growing rehash
testset1.rehash(bucket_traits(buckets1, BucketSize));
BOOST_TEST (testset1.size() == values.size()-1);
BOOST_TEST (testset1.incremental_rehash() == false);
{ int init_values [] = { 1, 2, 3, 4, 5 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); }
//Incremental rehash shrinking
//First incremental rehashes should lead to the same sequence
for(std::size_t split_bucket = testset1.split_count(); split_bucket > 6; --split_bucket){
BOOST_TEST (testset1.incremental_rehash(false) == true);
BOOST_TEST(testset1.split_count() == (split_bucket-1));
{ int init_values [] = { 1, 2, 3, 4, 5 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); }
}
//Incremental rehash step
BOOST_TEST (testset1.incremental_rehash(false) == true);
BOOST_TEST(testset1.split_count() == (BucketSize/2+1));
{ int init_values [] = { 5, 1, 2, 3, 4 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); }
//Incremental rehash step 2
BOOST_TEST (testset1.incremental_rehash(false) == true);
BOOST_TEST(testset1.split_count() == (BucketSize/2));
{ int init_values [] = { 4, 5, 1, 2, 3 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); }
//This incremental rehash should fail because we've reached the half of the bucket array
BOOST_TEST(testset1.incremental_rehash(false) == false);
BOOST_TEST(testset1.split_count() == BucketSize/2);
{ int init_values [] = { 4, 5, 1, 2, 3 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); }
}
//test: rehash:
template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental>
void test_unordered_set<ValueTraits, CacheBegin, CompareHash, Incremental>::
test_rehash(std::vector<typename ValueTraits::value_type>& values, detail::false_)
{
typedef typename ValueTraits::value_type value_type;
typedef unordered_set
<value_type
, value_traits<ValueTraits>
, constant_time_size<value_type::constant_time_size>
, cache_begin<CacheBegin>
, compare_hash<CompareHash>
, incremental<Incremental>
> unordered_set_type;
typedef typename unordered_set_type::bucket_traits bucket_traits;
typename unordered_set_type::bucket_type buckets1 [BucketSize];
typename unordered_set_type::bucket_type buckets2 [2];
typename unordered_set_type::bucket_type buckets3 [BucketSize*2];
unordered_set_type testset1(&values[0], &values[0] + 6, bucket_traits(buckets1, BucketSize));
BOOST_TEST (testset1.size() == values.size()-1);
{ int init_values [] = { 1, 2, 3, 4, 5 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); }
testset1.rehash(bucket_traits(buckets2, 2));
BOOST_TEST (testset1.size() == values.size()-1);
{ int init_values [] = { 4, 2, 5, 3, 1 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); }
testset1.rehash(bucket_traits(buckets3, BucketSize*2));
BOOST_TEST (testset1.size() == values.size()-1);
{ int init_values [] = { 1, 2, 3, 4, 5 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); }
//Now rehash reducing the buckets
testset1.rehash(bucket_traits(buckets3, 2));
BOOST_TEST (testset1.size() == values.size()-1);
{ int init_values [] = { 4, 2, 5, 3, 1 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); }
//Now rehash increasing the buckets
testset1.rehash(bucket_traits(buckets3, BucketSize*2));
BOOST_TEST (testset1.size() == values.size()-1);
{ int init_values [] = { 1, 2, 3, 4, 5 };
TEST_INTRUSIVE_SEQUENCE( init_values, testset1.begin() ); }
}
//test: find, equal_range (lower_bound, upper_bound):
template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental>
void test_unordered_set<ValueTraits, CacheBegin, CompareHash, Incremental>::
test_find(std::vector<typename ValueTraits::value_type>& values)
{
typedef typename ValueTraits::value_type value_type;
typedef unordered_set
<value_type
, value_traits<ValueTraits>
, constant_time_size<value_type::constant_time_size>
, cache_begin<CacheBegin>
, compare_hash<CompareHash>
, incremental<Incremental>
> unordered_set_type;
typedef typename unordered_set_type::bucket_traits bucket_traits;
typename unordered_set_type::bucket_type buckets [BucketSize];
unordered_set_type testset (values.begin(), values.end(), bucket_traits(buckets, BucketSize));
typedef typename unordered_set_type::iterator iterator;
value_type cmp_val;
cmp_val.value_ = 2;
iterator i = testset.find (cmp_val);
BOOST_TEST (i->value_ == 2);
BOOST_TEST ((++i)->value_ != 2);
std::pair<iterator,iterator> range = testset.equal_range (cmp_val);
BOOST_TEST (range.first->value_ == 2);
BOOST_TEST (range.second->value_ == 3);
BOOST_TEST (std::distance (range.first, range.second) == 1);
cmp_val.value_ = 7;
BOOST_TEST (testset.find (cmp_val) == testset.end());
}
template<class ValueTraits, bool CacheBegin, bool CompareHash, bool Incremental>
void test_unordered_set<ValueTraits, CacheBegin, CompareHash, Incremental>
::test_clone(std::vector<typename ValueTraits::value_type>& values)
{
typedef typename ValueTraits::value_type value_type;
typedef unordered_set
<value_type
, value_traits<ValueTraits>
, constant_time_size<value_type::constant_time_size>
, cache_begin<CacheBegin>
, compare_hash<CompareHash>
, incremental<Incremental>
> unordered_set_type;
typedef typename unordered_set_type::bucket_traits bucket_traits;
{
//Test with equal bucket arrays
typename unordered_set_type::bucket_type buckets1 [BucketSize];
typename unordered_set_type::bucket_type buckets2 [BucketSize];
unordered_set_type testset1 (values.begin(), values.end(), bucket_traits(buckets1, BucketSize));
unordered_set_type testset2 (bucket_traits(buckets2, BucketSize));
testset2.clone_from(testset1, test::new_cloner<value_type>(), test::delete_disposer<value_type>());
//Ordering is not guarantee in the cloning so insert data in a set and test
std::set<typename ValueTraits::value_type>
src(testset1.begin(), testset1.end());
std::set<typename ValueTraits::value_type>
dst(testset2.begin(), testset2.end());
BOOST_TEST (src.size() == dst.size() && std::equal(src.begin(), src.end(), dst.begin()));
testset2.clear_and_dispose(test::delete_disposer<value_type>());
BOOST_TEST (testset2.empty());
}
{
//Test with bigger source bucket arrays
typename unordered_set_type::bucket_type buckets1 [BucketSize*2];
typename unordered_set_type::bucket_type buckets2 [BucketSize];
unordered_set_type testset1 (values.begin(), values.end(), bucket_traits(buckets1, BucketSize*2));
unordered_set_type testset2 (bucket_traits(buckets2, BucketSize));
testset2.clone_from(testset1, test::new_cloner<value_type>(), test::delete_disposer<value_type>());
//Ordering is not guaranteed in the cloning so insert data in a set and test
std::set<typename ValueTraits::value_type>
src(testset1.begin(), testset1.end());
std::set<typename ValueTraits::value_type>
dst(testset2.begin(), testset2.end());
BOOST_TEST (src.size() == dst.size() && std::equal(src.begin(), src.end(), dst.begin()));
testset2.clear_and_dispose(test::delete_disposer<value_type>());
BOOST_TEST (testset2.empty());
}
{
//Test with smaller source bucket arrays
typename unordered_set_type::bucket_type buckets1 [BucketSize];
typename unordered_set_type::bucket_type buckets2 [BucketSize*2];
unordered_set_type testset1 (values.begin(), values.end(), bucket_traits(buckets1, BucketSize));
unordered_set_type testset2 (bucket_traits(buckets2, BucketSize*2));
testset2.clone_from(testset1, test::new_cloner<value_type>(), test::delete_disposer<value_type>());
//Ordering is not guarantee in the cloning so insert data in a set and test
std::set<typename ValueTraits::value_type>
src(testset1.begin(), testset1.end());
std::set<typename ValueTraits::value_type>
dst(testset2.begin(), testset2.end());
BOOST_TEST (src.size() == dst.size() && std::equal(src.begin(), src.end(), dst.begin()));
testset2.clear_and_dispose(test::delete_disposer<value_type>());
BOOST_TEST (testset2.empty());
}
}
template<class VoidPointer, bool constant_time_size, bool incremental>
class test_main_template
{
public:
int operator()()
{
typedef testvalue<hooks<VoidPointer> , constant_time_size> value_type;
static const int random_init[6] = { 3, 2, 4, 1, 5, 2 };
std::vector<testvalue<hooks<VoidPointer> , constant_time_size> > data (6);
for (int i = 0; i < 6; ++i)
data[i].value_ = random_init[i];
test_unordered_set < typename detail::get_base_value_traits
< value_type
, typename hooks<VoidPointer>::base_hook_type
>::type
, true
, false
, incremental
>::test_all(data);
test_unordered_set < typename detail::get_member_value_traits
< value_type
, member_hook< value_type
, typename hooks<VoidPointer>::member_hook_type
, &value_type::node_
>
>::type
, false
, false
, incremental
>::test_all(data);
return 0;
}
};
template<class VoidPointer, bool incremental>
class test_main_template<VoidPointer, false, incremental>
{
public:
int operator()()
{
typedef testvalue<hooks<VoidPointer> , false> value_type;
static const int random_init[6] = { 3, 2, 4, 1, 5, 2 };
std::vector<testvalue<hooks<VoidPointer> , false> > data (6);
for (int i = 0; i < 6; ++i)
data[i].value_ = random_init[i];
test_unordered_set < typename detail::get_base_value_traits
< value_type
, typename hooks<VoidPointer>::base_hook_type
>::type
, true
, false
, incremental
>::test_all(data);
test_unordered_set < typename detail::get_member_value_traits
< value_type
, member_hook< value_type
, typename hooks<VoidPointer>::member_hook_type
, &value_type::node_
>
>::type
, false
, false
, incremental
>::test_all(data);
test_unordered_set < typename detail::get_base_value_traits
< value_type
, typename hooks<VoidPointer>::auto_base_hook_type
>::type
, false
, true
, incremental
>::test_all(data);
test_unordered_set < typename detail::get_member_value_traits
< value_type
, member_hook< value_type
, typename hooks<VoidPointer>::auto_member_hook_type
, &value_type::auto_node_
>
>::type
, false
, true
, incremental
>::test_all(data);
return 0;
}
};
int main( int, char* [] )
{
test_main_template<void*, false, true>()();
test_main_template<smart_ptr<void>, false, true>()();
test_main_template<void*, true, true>()();
test_main_template<smart_ptr<void>, true, true>()();
test_main_template<void*, false, false>()();
test_main_template<smart_ptr<void>, false, false>()();
test_main_template<void*, true, true>()();
test_main_template<smart_ptr<void>, true, false>()();
return boost::report_errors();
}
#include <boost/intrusive/detail/config_end.hpp>
| [
"metrix@Blended.(none)"
]
| [
[
[
1,
658
]
]
]
|
d6b56fab5b945f6b3ad149eb8b17f22a23f6793a | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/mw/websrv/web_service_connection_api/connection/src/testproperty.cpp | 221a14781d9e7f00c2c24d2f2f29b069aa87e0de | []
| 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,379 | cpp | /*
* 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:
*
*/
// INCLUDE FILES
#include "testproperty.h"
#include <SenIdentityProvider.h>
#include <e32base.h>
CTestProperty* CTestProperty::NewL()
{
CTestProperty* pTest = new (ELeave) CTestProperty();
return pTest;
}
CTestProperty* CTestProperty::NewLC()
{
CTestProperty* pTest = new (ELeave) CTestProperty();
CleanupStack::PushL(pTest);
return pTest;
}
CTestProperty::CTestProperty()
{
}
TPtrC8 CTestProperty::Name()
{
return _L8("");
}
TPtrC8 CTestProperty::Type()
{
return _L8("");
}
TPtrC8 CTestProperty::Value()
{
return _L8("");
}
TInt CTestProperty::IntValue(TInt& aValue)
{
return KErrNone;
}
TInt CTestProperty::BoolValue(TBool& aValue)
{
return KErrNone;
}
TInt CTestProperty::ValueTokensL(const TDesC8& aDelimiter,
RPointerArray<TPtrC8>& aTokens)
{
return KErrNone;
}
| [
"none@none"
]
| [
[
[
1,
67
]
]
]
|
054fbde6b927c150681b705ffde830a82c01ce1d | a36d7a42310a8351aa0d427fe38b4c6eece305ea | /core_billiard/Camera.h | c387f8fa3a7e7365fe722882caab57e272510f63 | []
| no_license | newpolaris/mybilliard01 | ca92888373c97606033c16c84a423de54146386a | dc3b21c63b5bfc762d6b1741b550021b347432e8 | refs/heads/master | 2020-04-21T06:08:04.412207 | 2009-09-21T15:18:27 | 2009-09-21T15:18:27 | 39,947,400 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 423 | h | #pragma once
namespace my_render {
MY_INTERFACE Camera : EXTENDS_INTERFACE( Base ) {
virtual bool isPerspective() PURE;
virtual bool isOrthographic() PURE;
virtual CameraPerspective * getPerspectiveCamera() PURE;
virtual CameraOrthographic * getOrthographicCamera() PURE;
virtual void getProjectionMatrix44( float * returnMatrix44, bool bRightHand, bool bRowMajor ) PURE;
};
}
| [
"wrice127@af801a76-7f76-11de-8b9f-9be6f49bd635"
]
| [
[
[
1,
18
]
]
]
|
ba6d0ab4d5e031a61f43ae415a694e9072f7e15e | 4b0f51aeecddecf3f57a29ffa7a184ae48f1dc61 | /CleanProject/MyGUI/include/MyGUI_ChildSkinInfo.h | af444d5dd1c710169316c57c0991c3f849e59864 | []
| no_license | bahao247/apeengine2 | 56560dbf6d262364fbc0f9f96ba4231e5e4ed301 | f2617b2a42bdf2907c6d56e334c0d027fb62062d | refs/heads/master | 2021-01-10T14:04:02.319337 | 2009-08-26T08:23:33 | 2009-08-26T08:23:33 | 45,979,392 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,998 | h | /*!
@file
@author Albert Semenov
@date 12/2007
@module
*//*
This file is part of MyGUI.
MyGUI is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MyGUI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with MyGUI. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __MYGUI_CHILD_SKIN_INFO_H__
#define __MYGUI_CHILD_SKIN_INFO_H__
#include "MyGUI_Prerequest.h"
#include "MyGUI_Common.h"
namespace MyGUI
{
struct MYGUI_EXPORT ChildSkinInfo
{
ChildSkinInfo() : style(WidgetStyle::Child), align(Align::Default) { }
ChildSkinInfo(const std::string& _type, const WidgetStyle& _style, const std::string& _skin, const IntCoord& _coord, const Align& _align, const std::string& _layer, const std::string& _name) :
type(_type),
skin(_skin),
name(_name),
layer(_layer),
style(_style),
coord(_coord),
align(_align)
{
// set Child style by default
if (style == WidgetStyle::MAX) style = WidgetStyle::Child;
}
void addParam(const std::string& _key, const std::string& _value)
{
params[_key] = _value;
}
std::string findValue(const std::string& _key) const
{
MapString::const_iterator iter = params.find(_key);
if (iter != params.end()) return iter->second;
return "";
}
std::string type, skin, name, layer;
WidgetStyle style;
IntCoord coord;
Align align;
MapString params;
};
typedef std::vector<ChildSkinInfo> VectorChildSkinInfo;
} // namespace MyGUI
#endif // __MYGUI_CHILD_SKIN_INFO_H__
| [
"pablosn@06488772-1f9a-11de-8b5c-13accb87f508"
]
| [
[
[
1,
72
]
]
]
|
01f3d709e50f64cca235d0ab838419076e55450b | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SampleFoundation/TerrainLod/TerrainLod.cpp | 47d68512694f1fcd6cbc537d3904e94cd43eac77 | []
| no_license | pizibing/swingengine | d8d9208c00ec2944817e1aab51287a3c38103bea | e7109d7b3e28c4421c173712eaf872771550669e | refs/heads/master | 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,165 | cpp | // Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or (at
// your option) any later version. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
#include "TerrainLod.h"
SE_WINDOW_APPLICATION(TerrainLod);
SE_REGISTER_INITIALIZE(TerrainLod);
//----------------------------------------------------------------------------
TerrainLod::TerrainLod()
:
SEWindowApplication3("TerrainLod", 0, 0, 640, 480,
SEColorRGBA(0.5f, 0.5f, 0.5f, 1.0f)),
m_FogColor(SEColorRGB(0.5686f, 0.7255f, 0.8353f)),
m_fUVBias(0.0f),
m_fFogDensity(0.0005f),
m_fVerticalDistance(10.0f)
{
SESystem::SE_InsertDirectory("../../Data/Terrain/Height32");
SESystem::SE_InsertDirectory("../../Data/Terrain/Image32/");
SESystem::SE_InsertDirectory("../../Data/Terrain");
m_bLod = true;
}
//----------------------------------------------------------------------------
bool TerrainLod::OnInitialize()
{
if( !SEWindowApplication3::OnInitialize() )
{
return false;
}
m_spCamera->SetFrustum(-0.55f, 0.55f, -0.4125f, 0.4125f, 1.0f, 5000.0f);
SEVector3f tempCLoc(2048.0f, m_fVerticalDistance+50, 2048.0f);
SEVector3f tempCDir(1.0f, 0.0f, 1.0f);
SEVector3f tempCUp(0.0f, 1.0f, .0f);
SEVector3f tempCRight = tempCUp.Cross(tempCDir);
m_spCamera->SetFrame(tempCLoc, tempCRight, tempCUp, tempCDir);
CreateScene();
if( m_spRoamTerrain )
{
m_spRoamTerrain->Simplify(m_Culler);
}
// initial update of objects
m_spScene->UpdateGS();
m_spScene->UpdateRS();
// initial culling of scene
m_Culler.SetCamera(m_spCamera);
m_Culler.ComputeUnculledSet(m_spScene);
InitializeCameraMotion(0.5f, 0.01f);
InitializeObjectMotion(m_spScene);
return true;
}
//----------------------------------------------------------------------------
void TerrainLod::OnTerminate()
{
m_spScene = 0;
m_spRoamTerrain = 0;
m_spWireframe = 0;
SEWindowApplication3::OnTerminate();
}
//----------------------------------------------------------------------------
void TerrainLod::OnIdle()
{
//m_spRoamTerrain->Simplify(m_Culler);
MeasureTime();
if( MoveCamera() )
{
m_Culler.ComputeUnculledSet(m_spScene);
}
if( MoveObject() )
{
m_spScene->UpdateGS();
m_Culler.ComputeUnculledSet(m_spScene);
}
m_pRenderer->ClearBuffers();
if( m_pRenderer->BeginScene() )
{
m_pRenderer->DrawScene(m_Culler.GetVisibleSet());
DrawFrameRate(8, 20, SEColorRGBA::SE_RGBA_WHITE);
m_pRenderer->EndScene();
}
m_pRenderer->DisplayBackBuffer();
UpdateFrameCount();
}
//----------------------------------------------------------------------------
bool TerrainLod::OnKeyDown(unsigned char ucKey, int iX, int iY)
{
if( SEWindowApplication3::OnKeyDown(ucKey, iX, iY) )
{
return true;
}
switch( ucKey )
{
case 'w':
case 'W':
m_spWireframe->Enabled = !m_spWireframe->Enabled;
#if defined(SE_USING_DX10)
// DX10 render state objects must be re-created based on our new states.
m_spScene->UpdateRS();
#endif
return true;
case 's':
case 'S':
TestStreaming(m_spScene, 128, 128, 640, 480, "TerrainLod.seof");
return true;
case 'l':
if( m_spRoamTerrain )
{
m_bLod = !m_bLod;
m_spRoamTerrain->SetLod(m_bLod);
}
return true;
}
return false;
}
//----------------------------------------------------------------------------
void TerrainLod::CreateScene()
{
m_spScene = SE_NEW SENode;
m_spWireframe = SE_NEW SEWireframeState;
m_spScene->AttachGlobalState(m_spWireframe);
// Create ROAM terrain.
SEAttributes tempAttr;
tempAttr.SetPositionChannels(3);
tempAttr.SetNormalChannels(3);
tempAttr.SetTCoordChannels(0, 2); // terrain base texture
tempAttr.SetTCoordChannels(1, 2); // detail texture
SEColorRGBA tempBorderColor(m_FogColor[0], m_FogColor[1], m_FogColor[2],
1.0f);
m_spRoamTerrain = SE_NEW SERoamTerrain("height", "image", tempAttr,
m_spCamera, m_fUVBias, &tempBorderColor);
m_spScene->AttachChild(m_spRoamTerrain);
int iRows = m_spRoamTerrain->GetRowCount();
int iCols = m_spRoamTerrain->GetColCount();
for( int iRow = 0; iRow < iRows; iRow++ )
{
for( int iCol = 0; iCol < iCols; iCol++ )
{
SERoamTerrainPage* pPage = m_spRoamTerrain->GetPage(iRow, iCol);
// The default texturing uses a single base texture. Change this
// to use a base texture modulated by a detail texture and the
// result blended with fog.
SEMultitextureEffect* pEffect = DynamicCast<SEMultitextureEffect>(
pPage->GetEffect(0));
std::string tempBaseName = pEffect->GetImageName(0);
pPage->DetachEffect(pEffect);
SETerrainEffect* pTEffect = SE_NEW SETerrainEffect(
tempBaseName.c_str(), "Detail", m_FogColor, m_fFogDensity);
pPage->AttachEffect(pTEffect);
}
}
}
//----------------------------------------------------------------------------
| [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
]
| [
[
[
1,
189
]
]
]
|
9ae8487ececfe7b9a2e4609ffd92515be5bada82 | b73f27ba54ad98fa4314a79f2afbaee638cf13f0 | /libproject/Setting/AutoClean.cpp | ce43bd8a9e745e469770cfbdc38cf8c1100fa653 | []
| no_license | weimingtom/httpcontentparser | 4d5ed678f2b38812e05328b01bc6b0c161690991 | 54554f163b16a7c56e8350a148b1bd29461300a0 | refs/heads/master | 2021-01-09T21:58:30.326476 | 2009-09-23T08:05:31 | 2009-09-23T08:05:31 | 48,733,304 | 3 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,176 | cpp | #include "StdAfx.h"
#include ".\autoclean.h"
#include ".\settingitem.h"
#include <stdio.h>
#include <sys/timeb.h>
#include <time.h>
#include <assert.h>
#include <utility/timeutility.h>
//===========================================
// construtor and deconstructor
AutoClean::AutoClean(void) {
last_time_ = NULL;
defaultSetting();
}
AutoClean::~AutoClean(void) {
if (last_time_ != NULL) {
delete last_time_;
}
}
bool AutoClean::shouldExec() {
assert (NULL != last_time_);
// 如果不可用
if (isEnabled() == false) {
return false;
}
CTime t = CTime::GetCurrentTime();
CTimeSpan timespan = t - *last_time_;
if (timespan.GetTotalHours() / 24 >= getTimespan()) {
return true;
} else {
return false;
}
}
// 设置时间间隔的范围
void AutoClean::setTimespan(const int days) {
assert (getRangeMax() > getRangeMin());
setModified(true);
if (days < getRangeMin())
timespan_days_ = getRangeMin();
else if (days > getRangeMax())
timespan_days_ = getRangeMax();
else
timespan_days_ = days;
}
// 设置时间范围
void AutoClean::setScale(const int min, const int max) {
assert ( max > min);
max_ = max;
min_ = min;
}
// 充值时间
void AutoClean::reset() {
assert (NULL != last_time_);
*last_time_ = CTime::GetCurrentTime();
}
void AutoClean::setLastTime(LPCTSTR lpstr) {
if (NULL != last_time_) {
delete last_time_;
}
struct tm t = timeutility::tmfromstring(lpstr);
last_time_ = new CTime(t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec);
}
// 获取上一次的清理时间
std::string AutoClean::getLastTime() {
assert (NULL != last_time_);
TCHAR str[MAX_PATH];
_sntprintf(str, MAX_PATH, "%04d-%02d-%02d %02d:%02d:%02d",
last_time_->GetYear(), last_time_->GetMonth(), last_time_->GetDay(),
last_time_->GetHour(), last_time_->GetMinute(), last_time_->GetSecond());
return std::string(str);
}
//===========================================
// 默认设置
void AutoClean::defaultSetting() {
max_ = 30 ;
min_ = 1 ;
timespan_days_ = min_ * 3;
enable(true);
last_time_ = new CTime();
reset();
}
| [
"[email protected]"
]
| [
[
[
1,
96
]
]
]
|
0f7ec5321310adcdc3840e6fb3ace06428bc2363 | 94c1c7459eb5b2826e81ad2750019939f334afc8 | /source/managedata.h | fc7893b1ae425e6c9545fad588994b07eb52b334 | []
| 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 | UTF-8 | C++ | false | false | 1,186 | h | #if !defined(AFX_MANAGEDATA_H__A891F112_7F6B_455D_842F_60496EEEB9E4__INCLUDED_)
#define AFX_MANAGEDATA_H__A891F112_7F6B_455D_842F_60496EEEB9E4__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CSuperviseData : public CPropertySheet
{
DECLARE_DYNAMIC(CSuperviseData)
public:
CSuperviseData(UINT nIDCaption, CWnd* pParentWnd = NULL, UINT iSelectPage = 0);
CSuperviseData(LPCTSTR pszCaption, CWnd* pParentWnd = NULL, UINT iSelectPage = 0);
public:
CButtonST m_ok;
CButtonST m_cancel;
public:
//{{AFX_VIRTUAL(CSuperviseData)
public:
virtual BOOL OnInitDialog();
protected:
virtual void DoDataExchange(CDataExchange* pDX);
//}}AFX_VIRTUAL
public:
virtual ~CSuperviseData();
protected:
//{{AFX_MSG(CSuperviseData)
afx_msg BOOL OnHelpInfo(HELPINFO* pHelpInfo);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_MANAGEDATA_H__A891F112_7F6B_455D_842F_60496EEEB9E4__INCLUDED_)
| [
"[email protected]"
]
| [
[
[
1,
49
]
]
]
|
af42080f31c7e9f278c276d06eb9ffed61d3e26e | 36bf908bb8423598bda91bd63c4bcbc02db67a9d | /Include/CAsyncSock.h | 479b024f9988f54b9acaf1cb88c66ace83deeeaf | []
| no_license | code4bones/crawlpaper | edbae18a8b099814a1eed5453607a2d66142b496 | f218be1947a9791b2438b438362bc66c0a505f99 | refs/heads/master | 2021-01-10T13:11:23.176481 | 2011-04-14T11:04:17 | 2011-04-14T11:04:17 | 44,686,513 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,077 | h | /*
CAsyncSock.h
Classe per interfaccia Winsock (modalita' asincrona).
Luca Piergentili, 04/09/98
[email protected]
*/
#ifndef _CASYNCSOCK_H
#define _CASYNCSOCK_H 1
#include "window.h"
#include "CSock.h"
#include "CAsyncSockMessages.h"
class CSockWnd;
class CAsyncSock;
/*
CSockWnd
Classe interna per CAsyncSock, non utilizzare direttamente.
Crea la finestra a cui vengono indirizzati i messaggi delle WSAAsync...().
Ognuna delle funzioni Async...() di CAsyncSock chiama la corrispondente di CSockWnd.
Le Async...() di CSockWnd chiamano le WSAAsync...() impostando come callback le proprie
On...().
Le On...() di CSockWnd formattano i dati ricevuti e chiamano le callback di CAsyncSock
che a loro volta si occupano di inviare il messaggio relativo con i dati all'applicazione
principale:
App CAsyncSock CSockWnd
x() -> a() -> a()
|
wsa...(wnd handle,msg)
|
on_x() <- a_callback() <- on_a()
*/
class CSockWnd : public CWnd
{
// per poter accedere ai membri privati/protetti di CSock/CAsyncSock
friend class CAsyncSock;
public:
CSockWnd(CAsyncSock* pAsyncSock = NULL,CWnd* pParent = NULL);
virtual ~CSockWnd(void);
private:
/*
AsyncGetHostByName()
hostname -> ip
*/
int AsyncGetHostByName(LPCSTR,LPSTR,UINT);
HANDLE m_hAsyncGetHostByName;
LPSTR m_lpszAsyncGetHostByName;
UINT m_nAsyncGetHostByName;
char m_szIPAddr[IP_ADDRESS_SIZE];
/*
AsyncGetHostByAddr()
ip -> hostname
*/
int AsyncGetHostByAddr(LPCSTR,LPSTR,UINT);
HANDLE m_hAsyncGetHostByAddr;
LPSTR m_lpszAsyncGetHostByAddr;
UINT m_nAsyncGetHostByAddr;
char m_szHostName[HOSTNAME_SIZE];
/*
AsyncGetServByName()
servicename -> port
*/
int AsyncGetServByName(LPCSTR,LPCSTR,LPSTR,UINT);
HANDLE m_hAsyncGetServByName;
LPSTR m_lpszAsyncGetServByName;
UINT m_nAsyncGetServByName;
UINT m_nPort;
/*
AsyncGetServByPort()
port -> servicename
*/
int AsyncGetServByPort(UINT,LPCSTR,LPSTR,UINT);
HANDLE m_hAsyncGetServByPort;
LPSTR m_lpszAsyncGetServByPort;
UINT m_nAsyncGetServByPort;
char m_szService[32];
// ptr a CAsyncSock per chiamare le callback relative
CAsyncSock* m_pAsyncSock;
protected:
// callback per WSAAsyncSelect() per gli eventi asincroni del socket
LONG OnAsyncSelect(UINT,LONG); // WM_ASYNCSELECT
// callback per le WSAAsyncGetXByY(), ricevono i dati non formattati
LONG OnAsyncGetHostByName(UINT,LONG); // WM_ASYNCGETHOSTBYNAME
LONG OnAsyncGetHostByAddr(UINT,LONG); // WM_ASYNCGETHOSTBYADDR
LONG OnAsyncGetServByName(UINT,LONG); // WM_ASYNCGETSERVBYNAME
LONG OnAsyncGetServByPort(UINT,LONG); // WM_ASYNCGETSERVBYPORT
DECLARE_MESSAGE_MAP()
};
/*
CAsyncSock
*/
class CAsyncSock : public CSock
{
// per poter accedere ai membri privati/protetti di CSockWnd
friend class CSockWnd;
public:
CAsyncSock(CWnd* = NULL);
~CAsyncSock(void);
// interfaccia
inline int AsyncClose (void) {return(CAsyncSock::Close());} // chiude il socket asincrono
BOOL AsyncConnect (LPCSTR,UINT); // collega all'host/porta
BOOL AsyncGetHostByName (LPCSTR); // ricava l'ip a partire dal nome
BOOL AsyncGetHostByAddr (LPCSTR); // ricava il nome a partire dall'ip
BOOL AsyncGetServByName (LPCSTR,LPCSTR = "tcp"); // ricava il # porta corrispondente al servizio
BOOL AsyncGetServByPort (UINT,LPCSTR = "tcp"); // ricava il servizio corrispondente al # porta
// ridefinisce le virtual di CSock per la gestione degli eventi asincroni
virtual SOCKET Create (void);
virtual int Close (LPSTR = NULL,int = 0);
CSockWnd* m_pSockWnd; // ptr alla finestra interna per chiamare le funzioni relative
protected:
// callback per CSockWnd::OnAsyncSelect() per gli eventi asincroni del socket
LONG AsyncConnectCallBack (UINT,LONG);
LONG AsyncWriteCallBack (UINT,LONG);
LONG AsyncReadCallBack (UINT,LONG);
LONG AsyncCloseCallBack (UINT,LONG);
// callback per le CSockWnd::AsyncGetXByY(), ricevono i dati formattati
LONG AsyncGetHostByNameCallBack (UINT,LONG);
LONG AsyncGetHostByAddrCallBack (UINT,LONG);
LONG AsyncGetServByNameCallBack (UINT,LONG);
LONG AsyncGetServByPortCallBack (UINT,LONG);
// On...() per le classi derivate:
// l'applicazione che istanzia la classe CAsyncSock riceve i messaggi
// le classi derivate da CAsyncSock accedono ai dati non attraverso i messaggi ma ridefinendo
// le seguenti funzioni
virtual BOOL OnAsyncGetHostByName (LPCSTR) {return(TRUE);}
virtual BOOL OnAsyncGetHostByAddr (LPCSTR) {return(TRUE);}
virtual BOOL OnAsyncGetServByName (UINT) {return(TRUE);}
virtual BOOL OnAsyncGetServByPort (LPCSTR) {return(TRUE);}
private:
char m_szAsyncGetHostByName[MAXGETHOSTSTRUCT]; // buffer utilizzati dalle AsyncGetXByY()
char m_szAsyncGetHostByAddr[MAXGETHOSTSTRUCT];
char m_szAsyncGetServByName[MAXGETHOSTSTRUCT];
char m_szAsyncGetServByPort[MAXGETHOSTSTRUCT];
};
#endif // _CASYNCSOCK_H
| [
"[email protected]"
]
| [
[
[
1,
161
]
]
]
|
c8b14fa2795d585844a88790ddc01d2f8c9837fa | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SEApplications/SE_DX9_Application/SEDX9Application/SEWindowApplication3.h | d5bcfac4e4141a3fb1507942a4f61d0a3a736c92 | []
| no_license | pizibing/swingengine | d8d9208c00ec2944817e1aab51287a3c38103bea | e7109d7b3e28c4421c173712eaf872771550669e | refs/heads/master | 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,880 | h | // Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or (at
// your option) any later version. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
#ifndef Swing_WindowAppliCation3_H
#define Swing_WindowAppliCation3_H
#include "SEWindowApplication.h"
namespace Swing
{
//----------------------------------------------------------------------------
// 说明:
// 作者:Sun Che
// 时间:20080809
//----------------------------------------------------------------------------
class SEWindowApplication3 : public SEWindowApplication
{
public:
SEWindowApplication3(const char* acWindowTitle, int iXPosition,
int iYPosition, int iWidth, int iHeight,
const SEColorRGBA& rBackgroundColor);
virtual ~SEWindowApplication3(void);
// 事件回调函数
virtual bool OnInitialize(void);
virtual void OnTerminate(void);
virtual void OnDisplay(void);
virtual bool OnKeyDown(unsigned char ucKey, int iX, int iY);
virtual bool OnSpecialKeyDown(int iKey, int iX, int iY);
virtual bool OnSpecialKeyUp(int iKey, int iX, int iY);
virtual bool OnMouseClick(int iButton, int iState, int iX, int iY,
unsigned int uiModifiers);
virtual bool OnMotion(int iButton, int iX, int iY,
unsigned int uiModifiers);
protected:
// 摄像机运动
void InitializeCameraMotion(float fTrnSpeed, float fRotSpeed,
float fTrnSpeedFactor = 2.0f, float fRotSpeedFactor = 2.0f);
virtual bool MoveCamera(void);
virtual void MoveForward(void);
virtual void MoveBackward(void);
virtual void MoveUp(void);
virtual void MoveDown(void);
virtual void TurnLeft(void);
virtual void TurnRight(void);
virtual void LookUp(void);
virtual void LookDown(void);
SECameraPtr m_spCamera;
SEVector3f m_aWorldAxis[3];
float m_fTrnSpeed, m_fTrnSpeedFactor;
float m_fRotSpeed, m_fRotSpeedFactor;
bool m_bUArrowPressed;
bool m_bDArrowPressed;
bool m_bLArrowPressed;
bool m_bRArrowPressed;
bool m_bPgUpPressed;
bool m_bPgDnPressed;
bool m_bHomePressed;
bool m_bEndPressed;
bool m_bCameraMoveable;
// listener运动
SEListenerPtr m_spListener;
// 对象运动
void InitializeObjectMotion(SESpatial* pMotionObject);
bool MoveObject(void);
void RotateTrackBall(float fX0, float fY0, float fX1, float fY1);
SESpatialPtr m_spMotionObject;
int m_iDoRoll, m_iDoYaw, m_iDoPitch;
float m_fXTrack0, m_fYTrack0, m_fXTrack1, m_fYTrack1;
SEMatrix3f m_SaveRotate;
bool m_bUseTrackBall, m_bTrackBallDown;
// 性能测试
void ResetTime(void);
void MeasureTime(void);
void UpdateFrameCount(void);
void DrawFrameRate(int iX, int iY, const SEColorRGBA& rColor);
double m_dLastTime, m_dAccumulatedTime, m_dFrameRate;
int m_iFrameCount, m_iAccumulatedFrameCount, m_iTimer, m_iMaxTimer;
// 辅助显示世界体系坐标轴
void DrawWorldAxis(void);
SENodePtr m_spWorldAxis;
float m_fLengthOfAxis;
};
}
#endif
| [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
]
| [
[
[
1,
111
]
]
]
|
dfcf3e3b7165dfe671dff38b3920a19e4bfae663 | ec4c161b2baf919424d8d21cd0780cf8065e3f69 | /Velo/Source/Embedded Controller/arduino/cDigital.cpp | 4b297ae76fd3e718d9bdfef125db35efb38a5b65 | []
| no_license | jhays200/EV-Tracking | b215d2a915987fe7113a05599bda53f254248cfa | 06674e6f0f04fc2d0be1b1d37124a9a8e0144467 | refs/heads/master | 2016-09-05T18:41:21.650852 | 2011-06-04T01:50:25 | 2011-06-04T01:50:25 | 1,673,213 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 352 | cpp | ///////////////////////////////////////////////////////////
// cDigital.cpp
// Implementation of the Class cDigital
// Created on: 05-May-2010 3:28:14 AM
// Original author: shawn.mcginnis
///////////////////////////////////////////////////////////
#include "cDigital.h"
cDigital::cDigital(){
}
cDigital::~cDigital(){
} | [
"[email protected]"
]
| [
[
[
1,
18
]
]
]
|
5b9e90630bddd60843dcda419fe4a1b3ba2b14cd | 21da454a8f032d6ad63ca9460656c1e04440310e | /test/utest/StringTest.h | b929b8dbad2b75828048b5856cec210ad616d3d4 | []
| no_license | merezhang/wcpp | d9879ffb103513a6b58560102ec565b9dc5855dd | e22eb48ea2dd9eda5cd437960dd95074774b70b0 | refs/heads/master | 2021-01-10T06:29:42.908096 | 2009-08-31T09:20:31 | 2009-08-31T09:20:31 | 46,339,619 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 394 | h | #pragma once
#include "testcase.h"
class StringTest : public TestCase
{
public:
static const ws_char * const s_class_name;
public:
StringTest(void);
~StringTest(void);
WS_METHOD( ws_result , doTest )(void);
static void New(iTestCase ** ret);
void test_wsString(void);
void test_wsLong_ToString(void);
void test_wscUUID_ToString(void);
};
| [
"xukun0217@98f29a9a-77f1-11de-91f8-ab615253d9e8"
]
| [
[
[
1,
27
]
]
]
|
de7ded795b3f8a5addb6a53282cdb49bd8295205 | 854ee643a4e4d0b7a202fce237ee76b6930315ec | /arcemu_svn/src/sun/src/InstanceScripts/Instance_Mauradon.cpp | 84fad512ac878b0c11f737773f42d67e962b5069 | []
| no_license | miklasiak/projekt | df37fa82cf2d4a91c2073f41609bec8b2f23cf66 | 064402da950555bf88609e98b7256d4dc0af248a | refs/heads/master | 2021-01-01T19:29:49.778109 | 2008-11-10T17:14:14 | 2008-11-10T17:14:14 | 34,016,391 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,456 | cpp | /*
* Moon++ Scripts for Ascent MMORPG Server
* Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2007-2008 Moon++ Team <http://www.moonplusplus.info/>
*
* 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 3 of the License, or
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "StdAfx.h"
#include "Setup.h"
/************************************************************************/
/* Mauradon.cpp Script */
/************************************************************************/
class CelebrasTheCursed : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(CelebrasTheCursed);
SP_AI_Spell spells[3];
bool m_spellcheck[3];
CelebrasTheCursed(Creature* pCreature) : CreatureAIScript(pCreature)
{
nrspells = 3;
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
spells[0].info = dbcSpell.LookupEntry(21667);
spells[0].cooldown = 10;
spells[0].targettype = TARGET_ATTACKING;
spells[0].instant = true;
spells[0].perctrigger = (float)RandomFloat(20.0f);
spells[0].attackstoptimer = 3000;
m_spellcheck[0] = true;
spells[1].info = dbcSpell.LookupEntry(21331);
spells[1].cooldown = 10;
spells[1].targettype = TARGET_ATTACKING;
spells[1].instant = true;
spells[1].perctrigger = (float)RandomFloat(20.0f);
spells[1].attackstoptimer = 3000;
m_spellcheck[1] = true;
spells[2].info = dbcSpell.LookupEntry(21793);
spells[2].cooldown = 10;
spells[2].targettype = TARGET_ATTACKING;
spells[2].instant = true;
spells[2].perctrigger = (float)RandomFloat(20.0f);
spells[2].attackstoptimer = 3000;
m_spellcheck[2] = true;
}
void OnCombatStart(Unit* mTarget)
{
CastTime();
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
}
void CastTime()
{
for(int i=0;i<nrspells;i++)
spells[i].casttime = spells[i].cooldown;
}
void OnTargetDied(Unit* mTarget)
{
}
void OnCombatStop(Unit *mTarget)
{
CastTime();
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnDied(Unit * mKiller)
{
CastTime();
RemoveAIUpdateEvent();
}
void AIUpdate()
{
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
spells[i].casttime--;
if (m_spellcheck[i])
{
spells[i].casttime = spells[i].cooldown;
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant); break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
if (spells[i].speech != "")
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str());
_unit->PlaySoundToSet(spells[i].soundid);
}
m_spellcheck[i] = false;
return;
}
if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime)
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
protected:
int nrspells;
};
class LordVyletongue : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(LordVyletongue);
SP_AI_Spell spells[2];
bool m_spellcheck[2];
LordVyletongue(Creature* pCreature) : CreatureAIScript(pCreature)
{
nrspells = 2;
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
spells[0].info = dbcSpell.LookupEntry(21080);
spells[0].cooldown = 10;
spells[0].targettype = TARGET_ATTACKING;
spells[0].instant = true;
spells[0].perctrigger = (float)RandomFloat(20.0f);
spells[0].attackstoptimer = 3000;
m_spellcheck[0] = true;
spells[1].info = dbcSpell.LookupEntry(8817);
spells[1].cooldown = 10;
spells[1].targettype = TARGET_ATTACKING;
spells[1].instant = true;
spells[1].perctrigger = (float)RandomFloat(20.0f);
spells[1].attackstoptimer = 3000;
m_spellcheck[1] = true;
}
void OnCombatStart(Unit* mTarget)
{
CastTime();
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
}
void CastTime()
{
for(int i=0;i<nrspells;i++)
spells[i].casttime = spells[i].cooldown;
}
void OnTargetDied(Unit* mTarget)
{
}
void OnCombatStop(Unit *mTarget)
{
CastTime();
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnDied(Unit * mKiller)
{
CastTime();
RemoveAIUpdateEvent();
}
void AIUpdate()
{
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
spells[i].casttime--;
if (m_spellcheck[i])
{
spells[i].casttime = spells[i].cooldown;
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant); break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
if (spells[i].speech != "")
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str());
_unit->PlaySoundToSet(spells[i].soundid);
}
m_spellcheck[i] = false;
return;
}
if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime)
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
protected:
int nrspells;
};
class MeshlokTheHarvester : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(MeshlokTheHarvester);
SP_AI_Spell spells[2];
bool m_spellcheck[2];
MeshlokTheHarvester(Creature* pCreature) : CreatureAIScript(pCreature)
{
nrspells = 2;
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
spells[0].info = dbcSpell.LookupEntry(24375);
spells[0].cooldown = 10;
spells[0].targettype = TARGET_ATTACKING;
spells[0].instant = true;
spells[0].perctrigger = (float)RandomFloat(20.0f);
spells[0].attackstoptimer = 3000;
m_spellcheck[0] = true;
spells[1].info = dbcSpell.LookupEntry(15580);
spells[1].cooldown = 10;
spells[1].targettype = TARGET_ATTACKING;
spells[1].instant = true;
spells[1].perctrigger = (float)RandomFloat(20.0f);
spells[1].attackstoptimer = 3000;
m_spellcheck[1] = true;
}
void OnCombatStart(Unit* mTarget)
{
CastTime();
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
}
void CastTime()
{
for(int i=0;i<nrspells;i++)
spells[i].casttime = spells[i].cooldown;
}
void OnTargetDied(Unit* mTarget)
{
}
void OnCombatStop(Unit *mTarget)
{
CastTime();
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnDied(Unit * mKiller)
{
CastTime();
RemoveAIUpdateEvent();
}
void AIUpdate()
{
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
spells[i].casttime--;
if (m_spellcheck[i])
{
spells[i].casttime = spells[i].cooldown;
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant); break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
if (spells[i].speech != "")
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str());
_unit->PlaySoundToSet(spells[i].soundid);
}
m_spellcheck[i] = false;
return;
}
if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime)
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
protected:
int nrspells;
};
class PrincessTheradras : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(PrincessTheradras);
SP_AI_Spell spells[4];
bool m_spellcheck[4];
PrincessTheradras(Creature* pCreature) : CreatureAIScript(pCreature)
{
nrspells = 4;
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
spells[0].info = dbcSpell.LookupEntry(21909);
spells[0].cooldown = 10;
spells[0].targettype = TARGET_ATTACKING;
spells[0].instant = true;
spells[0].perctrigger = (float)RandomFloat(20.0f);
spells[0].attackstoptimer = 3000;
m_spellcheck[0] = true;
spells[1].info = dbcSpell.LookupEntry(21832);
spells[1].cooldown = 10;
spells[1].targettype = TARGET_ATTACKING;
spells[1].instant = true;
spells[1].perctrigger = (float)RandomFloat(20.0f);
spells[1].attackstoptimer = 3000;
m_spellcheck[1] = true;
spells[2].info = dbcSpell.LookupEntry(19128);
spells[2].cooldown = 10;
spells[2].targettype = TARGET_ATTACKING;
spells[2].instant = true;
spells[2].perctrigger = (float)RandomFloat(20.0f);
spells[2].attackstoptimer = 3000;
m_spellcheck[2] = true;
spells[3].info = dbcSpell.LookupEntry(21869);
spells[3].cooldown = 10;
spells[3].targettype = TARGET_ATTACKING;
spells[3].instant = true;
spells[3].perctrigger = (float)RandomFloat(20.0f);
spells[3].attackstoptimer = 3000;
m_spellcheck[3] = true;
}
void OnCombatStart(Unit* mTarget)
{
CastTime();
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
}
void CastTime()
{
for(int i=0;i<nrspells;i++)
spells[i].casttime = spells[i].cooldown;
}
void OnTargetDied(Unit* mTarget)
{
}
void OnCombatStop(Unit *mTarget)
{
CastTime();
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnDied(Unit * mKiller)
{
CastTime();
RemoveAIUpdateEvent();
}
void AIUpdate()
{
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
spells[i].casttime--;
if (m_spellcheck[i])
{
spells[i].casttime = spells[i].cooldown;
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant); break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
if (spells[i].speech != "")
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str());
_unit->PlaySoundToSet(spells[i].soundid);
}
m_spellcheck[i] = false;
return;
}
if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime)
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
protected:
int nrspells;
};
class Razorlash : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(Razorlash);
SP_AI_Spell spells[3];
bool m_spellcheck[3];
Razorlash(Creature* pCreature) : CreatureAIScript(pCreature)
{
nrspells = 3;
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
spells[0].info = dbcSpell.LookupEntry(21911);
spells[0].cooldown = 10;
spells[0].targettype = TARGET_ATTACKING;
spells[0].instant = true;
spells[0].perctrigger = (float)RandomFloat(20.0f);
spells[0].attackstoptimer = 3000;
m_spellcheck[0] = true;
spells[1].info = dbcSpell.LookupEntry(15584);
spells[1].cooldown = 10;
spells[1].targettype = TARGET_ATTACKING;
spells[1].instant = true;
spells[1].perctrigger = (float)RandomFloat(20.0f);
spells[1].attackstoptimer = 3000;
m_spellcheck[1] = true;
spells[2].info = dbcSpell.LookupEntry(21749);
spells[2].cooldown = 10;
spells[2].targettype = TARGET_ATTACKING;
spells[2].instant = true;
spells[2].perctrigger = (float)RandomFloat(20.0f);
spells[2].attackstoptimer = 3000;
m_spellcheck[2] = true;
}
void OnCombatStart(Unit* mTarget)
{
CastTime();
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
}
void CastTime()
{
for(int i=0;i<nrspells;i++)
spells[i].casttime = spells[i].cooldown;
}
void OnTargetDied(Unit* mTarget)
{
}
void OnCombatStop(Unit *mTarget)
{
CastTime();
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnDied(Unit * mKiller)
{
CastTime();
RemoveAIUpdateEvent();
}
void AIUpdate()
{
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
spells[i].casttime--;
if (m_spellcheck[i])
{
spells[i].casttime = spells[i].cooldown;
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant); break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
if (spells[i].speech != "")
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str());
_unit->PlaySoundToSet(spells[i].soundid);
}
m_spellcheck[i] = false;
return;
}
if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime)
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
protected:
int nrspells;
};
class TinkererGizlock : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(TinkererGizlock);
SP_AI_Spell spells[2];
bool m_spellcheck[2];
TinkererGizlock(Creature* pCreature) : CreatureAIScript(pCreature)
{
nrspells = 2;
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
spells[0].info = dbcSpell.LookupEntry(21833);
spells[0].cooldown = 10;
spells[0].targettype = TARGET_ATTACKING;
spells[0].instant = true;
spells[0].perctrigger = (float)RandomFloat(20.0f);
spells[0].attackstoptimer = 3000;
m_spellcheck[0] = true;
spells[1].info = dbcSpell.LookupEntry(22334);
spells[1].cooldown = 10;
spells[1].targettype = TARGET_ATTACKING;
spells[1].instant = true;
spells[1].perctrigger = (float)RandomFloat(20.0f);
spells[1].attackstoptimer = 3000;
m_spellcheck[1] = true;
}
void OnCombatStart(Unit* mTarget)
{
CastTime();
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
}
void CastTime()
{
for(int i=0;i<nrspells;i++)
spells[i].casttime = spells[i].cooldown;
}
void OnTargetDied(Unit* mTarget)
{
}
void OnCombatStop(Unit *mTarget)
{
CastTime();
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnDied(Unit * mKiller)
{
CastTime();
RemoveAIUpdateEvent();
}
void AIUpdate()
{
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
spells[i].casttime--;
if (m_spellcheck[i])
{
spells[i].casttime = spells[i].cooldown;
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant); break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
if (spells[i].speech != "")
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str());
_unit->PlaySoundToSet(spells[i].soundid);
}
m_spellcheck[i] = false;
return;
}
if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime)
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
protected:
int nrspells;
};
class Noxxion : public CreatureAIScript
{
public:
ADD_CREATURE_FACTORY_FUNCTION(Noxxion);
SP_AI_Spell spells[2];
bool m_spellcheck[2];
Noxxion(Creature* pCreature) : CreatureAIScript(pCreature)
{
nrspells = 2;
for(int i=0;i<nrspells;i++)
{
m_spellcheck[i] = false;
}
spells[0].info = dbcSpell.LookupEntry(21687);
spells[0].cooldown = 10;
spells[0].targettype = TARGET_ATTACKING;
spells[0].instant = true;
spells[0].perctrigger = (float)RandomFloat(20.0f);
spells[0].attackstoptimer = 3000;
m_spellcheck[0] = true;
spells[1].info = dbcSpell.LookupEntry(21547);
spells[1].cooldown = 10;
spells[1].targettype = TARGET_ATTACKING;
spells[1].instant = true;
spells[1].perctrigger = (float)RandomFloat(20.0f);
spells[1].attackstoptimer = 3000;
m_spellcheck[1] = true;
}
void OnCombatStart(Unit* mTarget)
{
CastTime();
RegisterAIUpdateEvent(_unit->GetUInt32Value(UNIT_FIELD_BASEATTACKTIME));
}
void CastTime()
{
for(int i=0;i<nrspells;i++)
spells[i].casttime = spells[i].cooldown;
}
void OnTargetDied(Unit* mTarget)
{
}
void OnCombatStop(Unit *mTarget)
{
CastTime();
_unit->GetAIInterface()->setCurrentAgent(AGENT_NULL);
_unit->GetAIInterface()->SetAIState(STATE_IDLE);
RemoveAIUpdateEvent();
}
void OnDied(Unit * mKiller)
{
CastTime();
RemoveAIUpdateEvent();
}
void AIUpdate()
{
float val = (float)RandomFloat(100.0f);
SpellCast(val);
}
void SpellCast(float val)
{
if(_unit->GetCurrentSpell() == NULL && _unit->GetAIInterface()->GetNextTarget())
{
float comulativeperc = 0;
Unit *target = NULL;
for(int i=0;i<nrspells;i++)
{
spells[i].casttime--;
if (m_spellcheck[i])
{
spells[i].casttime = spells[i].cooldown;
target = _unit->GetAIInterface()->GetNextTarget();
switch(spells[i].targettype)
{
case TARGET_SELF:
case TARGET_VARIOUS:
_unit->CastSpell(_unit, spells[i].info, spells[i].instant); break;
case TARGET_ATTACKING:
_unit->CastSpell(target, spells[i].info, spells[i].instant); break;
case TARGET_DESTINATION:
_unit->CastSpellAoF(target->GetPositionX(),target->GetPositionY(),target->GetPositionZ(), spells[i].info, spells[i].instant); break;
}
if (spells[i].speech != "")
{
_unit->SendChatMessage(CHAT_MSG_MONSTER_YELL, LANG_UNIVERSAL, spells[i].speech.c_str());
_unit->PlaySoundToSet(spells[i].soundid);
}
m_spellcheck[i] = false;
return;
}
if ((val > comulativeperc && val <= (comulativeperc + spells[i].perctrigger)) || !spells[i].casttime)
{
_unit->setAttackTimer(spells[i].attackstoptimer, false);
m_spellcheck[i] = true;
}
comulativeperc += spells[i].perctrigger;
}
}
}
protected:
int nrspells;
};
void SetupMaraudon(ScriptMgr * mgr)
{
mgr->register_creature_script(12225, &CelebrasTheCursed::Create);
mgr->register_creature_script(12236, &LordVyletongue::Create);
mgr->register_creature_script(12237, &MeshlokTheHarvester::Create);
mgr->register_creature_script(12201, &PrincessTheradras::Create);
mgr->register_creature_script(12258, &Razorlash::Create);
mgr->register_creature_script(13601, &TinkererGizlock::Create);
mgr->register_creature_script(13282, &Noxxion::Create);
} | [
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef"
]
| [
[
[
1,
918
]
]
]
|
2d86fb4f66470502179d5683716fc45868b168f4 | fd792229322e4042f6e88a01144665cebdb1c339 | /vc/dependencies/raknet/include/RakNet/RakMemoryOverride.h | e7f4198f2c4ffe1eb2ecf2b1282226b3b0ecfe79 | []
| no_license | weimingtom/mmomm | 228d70d9d68834fa2470d2cd0719b9cd60f8dbcd | cab04fcad551f7f68f99fa0b6bb14cec3b962023 | refs/heads/master | 2021-01-10T02:14:31.896834 | 2010-03-15T16:15:43 | 2010-03-15T16:15:43 | 44,764,408 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,096 | h | /// \file
/// \brief If _USE_RAK_MEMORY_OVERRIDE is defined, memory allocations go through rakMalloc, rakRealloc, and rakFree
///
/// This file is part of RakNet Copyright 2003 Jenkins Software LLC
///
/// Usage of RakNet is subject to the appropriate license agreement.
#ifndef __RAK_MEMORY_H
#define __RAK_MEMORY_H
#include "Export.h"
#include "RakNetDefines.h"
#include <new>
#if defined(_PS3) || defined(__PS3__) || defined(SN_TARGET_PS3)
#endif
#include "RakAlloca.h"
#if _USE_RAK_MEMORY_OVERRIDE==1
#if defined(new)
#pragma push_macro("new")
#undef new
#define RMO_NEW_UNDEF
#endif
#endif
// These pointers are statically and globally defined in RakMemoryOverride.cpp
// Change them to point to your own allocators if you want.
// Use the functions for a DLL, or just reassign the variable if using source
extern RAK_DLL_EXPORT void * (*rakMalloc) (size_t size);
extern RAK_DLL_EXPORT void * (*rakRealloc) (void *p, size_t size);
extern RAK_DLL_EXPORT void (*rakFree) (void *p);
extern RAK_DLL_EXPORT void * (*rakMalloc_Ex) (size_t size, const char *file, unsigned int line);
extern RAK_DLL_EXPORT void * (*rakRealloc_Ex) (void *p, size_t size, const char *file, unsigned int line);
extern RAK_DLL_EXPORT void (*rakFree_Ex) (void *p, const char *file, unsigned int line);
extern RAK_DLL_EXPORT void (*notifyOutOfMemory) (const char *file, const long line);
extern RAK_DLL_EXPORT void * (*dlMallocMMap) (size_t size);
extern RAK_DLL_EXPORT void * (*dlMallocDirectMMap) (size_t size);
extern RAK_DLL_EXPORT int (*dlMallocMUnmap) (void* ptr, size_t size);
// Change to a user defined allocation function
void RAK_DLL_EXPORT SetMalloc( void* (*userFunction)(size_t size) );
void RAK_DLL_EXPORT SetRealloc( void* (*userFunction)(void *p, size_t size) );
void RAK_DLL_EXPORT SetFree( void (*userFunction)(void *p) );
void RAK_DLL_EXPORT SetMalloc_Ex( void* (*userFunction)(size_t size, const char *file, unsigned int line) );
void RAK_DLL_EXPORT SetRealloc_Ex( void* (*userFunction)(void *p, size_t size, const char *file, unsigned int line) );
void RAK_DLL_EXPORT SetFree_Ex( void (*userFunction)(void *p, const char *file, unsigned int line) );
// Change to a user defined out of memory function
void RAK_DLL_EXPORT SetNotifyOutOfMemory( void (*userFunction)(const char *file, const long line) );
void RAK_DLL_EXPORT SetDLMallocMMap( void* (*userFunction)(size_t size) );
void RAK_DLL_EXPORT SetDLMallocDirectMMap( void* (*userFunction)(size_t size) );
void RAK_DLL_EXPORT SetDLMallocMUnmap( int (*userFunction)(void* ptr, size_t size) );
extern RAK_DLL_EXPORT void * (*GetMalloc()) (size_t size);
extern RAK_DLL_EXPORT void * (*GetRealloc()) (void *p, size_t size);
extern RAK_DLL_EXPORT void (*GetFree()) (void *p);
extern RAK_DLL_EXPORT void * (*GetMalloc_Ex()) (size_t size, const char *file, unsigned int line);
extern RAK_DLL_EXPORT void * (*GetRealloc_Ex()) (void *p, size_t size, const char *file, unsigned int line);
extern RAK_DLL_EXPORT void (*GetFree_Ex()) (void *p, const char *file, unsigned int line);
extern RAK_DLL_EXPORT void *(*GetDLMallocMMap())(size_t size);
extern RAK_DLL_EXPORT void *(*GetDLMallocDirectMMap())(size_t size);
extern RAK_DLL_EXPORT int (*GetDLMallocMUnmap())(void* ptr, size_t size);
namespace RakNet
{
template <class Type>
RAK_DLL_EXPORT Type* OP_NEW(const char *file, unsigned int line)
{
#if _USE_RAK_MEMORY_OVERRIDE==1
char *buffer = (char *) (GetMalloc_Ex())(sizeof(Type), file, line);
Type *t = new (buffer) Type;
return t;
#else
(void) file;
(void) line;
return new Type;
#endif
}
template <class Type, class P1>
RAK_DLL_EXPORT Type* OP_NEW_1(const char *file, unsigned int line, const P1 &p1)
{
#if _USE_RAK_MEMORY_OVERRIDE==1
char *buffer = (char *) (GetMalloc_Ex())(sizeof(Type), file, line);
Type *t = new (buffer) Type(p1);
return t;
#else
(void) file;
(void) line;
return new Type(p1);
#endif
}
template <class Type, class P1, class P2>
RAK_DLL_EXPORT Type* OP_NEW_2(const char *file, unsigned int line, const P1 &p1, const P2 &p2)
{
#if _USE_RAK_MEMORY_OVERRIDE==1
char *buffer = (char *) (GetMalloc_Ex())(sizeof(Type), file, line);
Type *t = new (buffer) Type(p1, p2);
return t;
#else
(void) file;
(void) line;
return new Type(p1, p2);
#endif
}
template <class Type, class P1, class P2, class P3>
RAK_DLL_EXPORT Type* OP_NEW_3(const char *file, unsigned int line, const P1 &p1, const P2 &p2, const P3 &p3)
{
#if _USE_RAK_MEMORY_OVERRIDE==1
char *buffer = (char *) (GetMalloc_Ex())(sizeof(Type), file, line);
Type *t = new (buffer) Type(p1, p2, p3);
return t;
#else
(void) file;
(void) line;
return new Type(p1, p2, p3);
#endif
}
template <class Type, class P1, class P2, class P3, class P4>
RAK_DLL_EXPORT Type* OP_NEW_4(const char *file, unsigned int line, const P1 &p1, const P2 &p2, const P3 &p3, const P4 &p4)
{
#if _USE_RAK_MEMORY_OVERRIDE==1
char *buffer = (char *) (GetMalloc_Ex())(sizeof(Type), file, line);
Type *t = new (buffer) Type(p1, p2, p3, p4);
return t;
#else
(void) file;
(void) line;
return new Type(p1, p2, p3, p4);
#endif
}
template <class Type>
RAK_DLL_EXPORT Type* OP_NEW_ARRAY(const int count, const char *file, unsigned int line)
{
if (count==0)
return 0;
#if _USE_RAK_MEMORY_OVERRIDE==1
Type *t;
char *buffer = (char *) (GetMalloc_Ex())(sizeof(int)+sizeof(Type)*count, file, line);
((int*)buffer)[0]=count;
for (int i=0; i<count; i++)
{
t = new(buffer+sizeof(int)+i*sizeof(Type)) Type;
}
return (Type *) (buffer+sizeof(int));
#else
(void) file;
(void) line;
return new Type[count];
#endif
}
template <class Type>
RAK_DLL_EXPORT void OP_DELETE(Type *buff, const char *file, unsigned int line)
{
#if _USE_RAK_MEMORY_OVERRIDE==1
if (buff==0) return;
buff->~Type();
(GetFree_Ex())((char*)buff, file, line );
#else
(void) file;
(void) line;
delete buff;
#endif
}
template <class Type>
RAK_DLL_EXPORT void OP_DELETE_ARRAY(Type *buff, const char *file, unsigned int line)
{
#if _USE_RAK_MEMORY_OVERRIDE==1
if (buff==0)
return;
int count = ((int*)((char*)buff-sizeof(int)))[0];
Type *t;
for (int i=0; i<count; i++)
{
t = buff+i;
t->~Type();
}
(GetFree_Ex())((char*)buff-sizeof(int), file, line );
#else
(void) file;
(void) line;
delete [] buff;
#endif
}
void RAK_DLL_EXPORT * _RakMalloc (size_t size);
void RAK_DLL_EXPORT * _RakRealloc (void *p, size_t size);
void RAK_DLL_EXPORT _RakFree (void *p);
void RAK_DLL_EXPORT * _RakMalloc_Ex (size_t size, const char *file, unsigned int line);
void RAK_DLL_EXPORT * _RakRealloc_Ex (void *p, size_t size, const char *file, unsigned int line);
void RAK_DLL_EXPORT _RakFree_Ex (void *p, const char *file, unsigned int line);
void RAK_DLL_EXPORT * _DLMallocMMap (size_t size);
void RAK_DLL_EXPORT * _DLMallocDirectMMap (size_t size);
int RAK_DLL_EXPORT _DLMallocMUnmap (void *p, size_t size);
}
// Call to make RakNet allocate a large block of memory, and do all subsequent allocations in that memory block
// Initial and reallocations will be done through whatever function is pointed to by yourMMapFunction, and yourDirectMMapFunction (default is malloc)
// Allocations will be freed through whatever function is pointed to by yourMUnmapFunction (default free)
void UseRaknetFixedHeap(size_t initialCapacity,
void * (*yourMMapFunction) (size_t size) = RakNet::_DLMallocMMap,
void * (*yourDirectMMapFunction) (size_t size) = RakNet::_DLMallocDirectMMap,
int (*yourMUnmapFunction) (void *p, size_t size) = RakNet::_DLMallocMUnmap);
// Free memory allocated from UseRaknetFixedHeap
void FreeRakNetFixedHeap(void);
#if _USE_RAK_MEMORY_OVERRIDE==1
#if defined(RMO_NEW_UNDEF)
#pragma pop_macro("new")
#undef RMO_NEW_UNDEF
#endif
#endif
#endif
| [
"[email protected]"
]
| [
[
[
1,
233
]
]
]
|
1686063694964e860c066f4086777692c1c4305a | 6712f8313dd77ae820aaf400a5836a36af003075 | /rtsCTS.cpp | c42da4a1ac94e5aa3ce87cbe209e0fa7e1d25d41 | []
| no_license | AdamTT1/bdScript | d83c7c63c2c992e516dca118cfeb34af65955c14 | 5483f239935ec02ad082666021077cbc74d1790c | refs/heads/master | 2021-12-02T22:57:35.846198 | 2010-08-08T22:32:02 | 2010-08-08T22:32:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,448 | cpp | /*
* rtsCTS.cpp
*
* This program will test the ability to get the state of the
* CTS pin, toggle the RTS pin, and spew data over a serial port.
*
*/
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <termios.h>
#include <sys/ioctl.h>
#include <signal.h>
#include <sys/poll.h>
#include <ctype.h>
#include "baudRate.h"
static bool volatile doExit = false ;
static void ctrlcHandler( int signo )
{
printf( "<ctrl-c>\r\n" );
doExit = true ;
}
static void toggleRTS( int fdSerial )
{
int line ;
if( 0 == ioctl(fdSerial, TIOCMGET, &line) )
{
line ^= TIOCM_RTS ;
if( 0 == ioctl(fdSerial, TIOCMSET, &line) )
{
printf( "toggled\r\n" );
}
else
perror( "TIOCMGET" );
}
else
perror( "TIOCMGET" );
}
static void setRaw( int fd, struct termios &oldState )
{
tcgetattr(fd,&oldState);
/* set raw mode for keyboard input */
struct termios newState = oldState;
newState.c_cc[VMIN] = 1;
unsigned baudConst ;
baudRateToConst( 115200, baudConst );
cfsetispeed(&newState, baudConst);
cfsetospeed(&newState, baudConst);
//
// Note that this doesn't appear to work!
// Reads always seem to be terminated at 16 chars!
//
newState.c_cc[VTIME] = 0; // 1/10th's of a second, see http://www.opengroup.org/onlinepubs/007908799/xbd/termios.html
newState.c_cflag &= ~(PARENB|CSTOPB|CSIZE|CRTSCTS); // Mask character size to 8 bits, no parity, Disable hardware flow control
newState.c_cflag |= (CLOCAL | CREAD |CS8); // Select 8 data bits
newState.c_lflag &= ~(ICANON | ECHO ); // set raw mode for input
newState.c_iflag &= ~(IXON | IXOFF | IXANY|INLCR|ICRNL|IUCLC); //no software flow control
newState.c_oflag &= ~OPOST; //raw output
tcsetattr( fd, TCSANOW, &newState );
}
static void showStatus( int fd )
{
int line ;
if( 0 == ioctl(fd, TIOCMGET, &line) )
{
printf( "line status 0x%04x: ", line );
if( line & TIOCM_CTS )
printf( "CTS " );
else
printf( "~CTS " );
if( line & TIOCM_RTS )
printf( "RTS " );
else
printf( "~RTS " );
printf( "\r\n" );
}
else
perror( "TIOCMGET" );
}
static void waitModemChange( int fd )
{
printf( "wait modem status..." ); fflush(stdout);
int line = TIOCM_RNG | TIOCM_DSR | TIOCM_CTS | TIOCM_CD ;
int result = ioctl(fd, TIOCMIWAIT, &line);
printf( "\r\n" );
if( 0 == result ){
printf( "changed\r\n" );
showStatus(fd);
}
else
perror( "TIOCMWAIT" );
}
static char const spewOutput[] = {
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890\r\n"
};
int main( int argc, char const * const argv[] )
{
if( 1 < argc )
{
char const *const deviceName = argv[1];
int const fdSerial = open( deviceName, O_RDWR );
if( 0 <= fdSerial )
{
fcntl( fdSerial, F_SETFD, FD_CLOEXEC );
fcntl( fdSerial, F_SETFL, O_NONBLOCK );
printf( "device %s opened\n", deviceName );
struct termios oldSerialState;
setRaw( fdSerial, oldSerialState);
struct termios oldStdinState;
setRaw( fileno(stdin), oldStdinState );
showStatus(fdSerial);
toggleRTS(fdSerial);
signal( SIGINT, ctrlcHandler );
pollfd fds[2];
fds[0].fd = fdSerial ;
fds[0].events = POLLIN | POLLERR ;
fds[1].fd = fileno(stdin);
fds[1].events = POLLIN | POLLERR ;
while( !doExit )
{
int const numReady = ::poll( fds, 2, 1000 );
if( 0 < numReady )
{
for( unsigned i = 0 ; i < 2 ; i++ )
{
if( fds[i].revents & POLLIN )
{
char inBuf[80];
int numRead = read( fds[i].fd, inBuf, sizeof(inBuf) );
for( int j = 0 ; j < numRead ; j++ )
{
char const c = inBuf[j];
switch( tolower(c) )
{
case 'x' :
case '\x03' : doExit = 1 ; break ;
case 'r' : toggleRTS(fdSerial); break ;
case 's' : showStatus(fdSerial); break ;
case 'w' : waitModemChange(fdSerial); break ;
case '!' : {
for( int line = 0 ; line < 10 ; line++ )
write( fdSerial, spewOutput, sizeof(spewOutput)-1 );
};
default:
printf( "%d: %c\r\n", fds[i].fd, inBuf[j] );
}
}
}
}
}
}
tcsetattr( fdSerial, TCSANOW, &oldSerialState );
tcsetattr( fileno(stdin), TCSANOW, &oldStdinState );
close( fdSerial );
}
else
perror( deviceName );
}
else
fprintf( stderr, "Usage: rtsCTS /dev/ttyS0\n" );
return 0 ;
}
| [
"ericn"
]
| [
[
[
1,
186
]
]
]
|
e6ad6b12a3f8ac5005765bf4867fd3034d518b22 | 91b964984762870246a2a71cb32187eb9e85d74e | /SRC/OFFI SRC!/boost_1_34_1/boost_1_34_1/libs/wave/samples/list_includes/list_includes.hpp | a52259f623654eb90b656c034975e30535cfc38c | [
"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 | UTF-8 | C++ | false | false | 1,718 | hpp | /*=============================================================================
Boost.Wave: A Standard compliant C++ preprocessor library
Sample: List include dependencies of a given source file
Configuration data
http://www.boost.org/
Copyright (c) 2001-2007 Hartmut Kaiser. 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)
=============================================================================*/
#if !defined(LIST_INCLUDES_HPP_843DB412_3AA8_4BCF_8081_AA4A5FDE0BE7_INCLUDED)
#define LIST_INCLUDES_HPP_843DB412_3AA8_4BCF_8081_AA4A5FDE0BE7_INCLUDED
///////////////////////////////////////////////////////////////////////////////
// include often used files from the stdlib
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <set>
///////////////////////////////////////////////////////////////////////////////
// include boost config
#include <boost/config.hpp> // global configuration information
///////////////////////////////////////////////////////////////////////////////
// build version
#include "list_includes_version.hpp"
///////////////////////////////////////////////////////////////////////////////
// configure this app here (global configuration constants)
#include "list_includes_config.hpp"
///////////////////////////////////////////////////////////////////////////////
// include required boost libraries
#include <boost/assert.hpp>
#include <boost/pool/pool_alloc.hpp>
#endif // !defined(LIST_INCLUDES_HPP_843DB412_3AA8_4BCF_8081_AA4A5FDE0BE7_INCLUDED)
| [
"[email protected]@e2c90bd7-ee55-cca0-76d2-bbf4e3699278"
]
| [
[
[
1,
42
]
]
]
|
ea81b87cbd5723c9fb5f237be7c45a09b2989ba9 | 27d5670a7739a866c3ad97a71c0fc9334f6875f2 | /CPP/Targets/MapLib/Unix/src/UnixMFDBufRequester.cpp | 3ff2639ead0638240e4af2449b5ba2fd255bbbb5 | [
"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 | 5,385 | cpp | /*
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.
*/
#include "UnixMFDBufRequester.h"
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
UnixFileHandler::UnixFileHandler( const char* fileName, bool createFile ) :
FileHandler( fileName ),
m_file( NULL )
{
if ( createFile ) {
// Create the directory which should contain the file
char* tmpName = new char[ strlen( fileName ) + 1 ];
strcpy( tmpName, getFileName() );
char* lastSlashPos = strrchr( tmpName, '/' );
*lastSlashPos = '\0';
char cmdStr[1024];
sprintf(cmdStr, "mkdir -p %s", tmpName);
FILE* filen = popen(cmdStr, "r");
if ( filen ) {
byte buf;
fread( &buf, 1, 1, filen);
pclose(filen);
}
delete [] tmpName;
// Create the file
m_file = fopen( fileName, "a+b");
fclose(m_file);
}
// Open file for writing and reading.
m_file = fopen( fileName, "r+b");
m_working = 0;
}
int
UnixFileHandler::status() const
{
if ( m_file == NULL ) {
return -1;
} else {
return 0;
}
}
UnixFileHandler::~UnixFileHandler()
{
if ( m_file ) {
fclose(m_file);
}
}
void
UnixFileHandler::clearFile()
{
fclose( m_file );
mc2dbg << "[UFH]: Removing file " << getFileName() << endl;
// Clears the file.
remove( getFileName() );
// Create a new file.
m_file = fopen( getFileName(), "a+b");
fclose(m_file);
// Open file for writing and reading.
m_file = fopen( getFileName(), "r+b");
}
int
UnixFileHandler::read( uint8* bytes,
int maxLength,
FileHandlerListener* listener )
{
MC2_ASSERT( m_working == 0 );
m_working++;
clearerr(m_file);
fseek( m_file, 0L, SEEK_CUR );
mc2dbg << "[UFH]: read: filepos = " << tell() << endl;
mc2dbg << "[UFH]: read("
<< getFileName() << ","
<< maxLength
<< "," << listener << ");" << endl;
int res = fread( bytes, maxLength, 1, m_file );
mc2dbg << "[UFH]: res = " << res << endl;
if ( res == 1 ) {
res = maxLength;
}
m_working--;
if ( listener ) {
listener->readDone( res );
return 0;
} else {
return res;
}
}
int
UnixFileHandler::write( const uint8* bytes,
int length,
FileHandlerListener* listener )
{
MC2_ASSERT( m_working == 0);
clearerr(m_file);
fseek( m_file, 0L, SEEK_CUR );
mc2dbg << "[UFH]: write: filepos = " << tell() << endl;
m_working++;
int res = fwrite( bytes, length, 1, m_file );
if ( res == 1 ) {
res = length;
}
fflush( m_file );
m_working--;
if ( listener ) {
listener->writeDone( res );
return 0;
} else {
return res;
}
}
void
UnixFileHandler::setPos( int pos )
{
if ( pos >= 0 ) {
fseek( m_file, pos, SEEK_SET);
} else {
fseek( m_file, 0, SEEK_END );
}
}
void
UnixFileHandler::setSize( int size )
{
// Get the fd for the file
int fd = fileno( m_file );
MC2_ASSERT( fd >= 0 );
// Flush the file
int fl = fflush( m_file );
MC2_ASSERT( fl >= 0 );
// Then truncate it.
int tr = ftruncate( fd, size );
MC2_ASSERT( tr >= 0 );
}
int
UnixFileHandler::tell()
{
return ftell(m_file);
}
uint32
UnixFileHandler::getModificationDate() const
{
struct stat myStat;
int res = stat( getFileName(), &myStat );
if ( res == 0 ) {
return uint32(myStat.st_mtime);
} else {
return MAX_UINT32;
}
}
uint32
UnixFileHandler::getAvailableSpace() const
{
return uint32(MAX_UINT32) >> 4;
}
| [
"[email protected]"
]
| [
[
[
1,
192
]
]
]
|
be0c6fdc12399bb819343c7be22c5c137d0c3bc6 | 95e726b45797eeb844964d93cc19d3ca0a5b017d | /source/URL_List.h | 9becfc33b7e22224379e062bc5353798d0c19600 | []
| no_license | iGlitch/brawlplusupdatifier | 805f780891d562a6dfb78d2ac8bc3f2f1e4baa6e | 6a966fbb4701070b228951ed083f6478d18f9dbf | refs/heads/master | 2021-01-10T10:13:14.228136 | 2009-10-30T11:28:36 | 2009-10-30T11:28:36 | 48,336,539 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 926 | h | /****************************************************************************
* URL List Class
* for USB Loader GX
* by dimok
***************************************************************************/
#ifndef ___URLLIST_H_
#define ___URLLIST_H_
#include "networkops.h"
#include "http.h"
typedef struct {
char *URL;
bool direct;
} Link_Info;
class URL_List {
public:
//!Constructor
//!\param url from where to get the list of links
URL_List(const char *url);
//!Destructor
~URL_List();
//! Get the a filepath of the list
//!\param list index
char * GetURL(int index);
//! Is it a direct URL or just a file or path under the main url
bool IsDirectURL(int index);
//! Get the number of links counted
int GetURLCount();
//! Sort list
void SortList();
protected:
int urlcount;
Link_Info *Links;
};
#endif
| [
"giantpune@a4a47d44-c171-11de-ad03-79fce359684b"
]
| [
[
[
1,
38
]
]
]
|
62b601cc8b55c25e6b1329736a7107c36f49342c | 854ee643a4e4d0b7a202fce237ee76b6930315ec | /arcemu_svn/src/arcemu-realmserver/ClientManager.h | 42f88c3f0787e7ebec4c6c214ca20b2d884616fe | []
| no_license | miklasiak/projekt | df37fa82cf2d4a91c2073f41609bec8b2f23cf66 | 064402da950555bf88609e98b7256d4dc0af248a | refs/heads/master | 2021-01-01T19:29:49.778109 | 2008-11-10T17:14:14 | 2008-11-10T17:14:14 | 34,016,391 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,845 | h | /*
* ArcEmu MMORPG Server
* Copyright (C) 2008 <http://www.ArcEmu.org/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#define MAX_SESSIONS 3000
class ClientMgr : public Singleton<ClientMgr>
{
public:
typedef HM_NAMESPACE::hash_map<uint32, RPlayerInfo*> ClientMap;
protected:
ClientMap m_clients;
uint32 m_maxSessionId;
Session * m_sessions[MAX_SESSIONS];
public:
ClientMgr();
~ClientMgr();
/* create rplayerinfo struct */
RPlayerInfo * CreateRPlayer(uint32 guid);
/* destroy rplayerinfo struct */
void DestroyRPlayerInfo(uint32 guid);
/* get rplayer */
ASCENT_INLINE RPlayerInfo * GetRPlayer(uint32 guid)
{
ClientMap::iterator itr = m_clients.find(guid);
return (itr != m_clients.end()) ? itr->second : 0;
}
/* send "mini" client data to all servers */
void SendPackedClientInfo(WServer * server);
/* get session by id */
ASCENT_INLINE Session * GetSession(uint32 Id) { return (Id < MAX_SESSIONS) ? m_sessions[Id] : 0; }
/* create a new session, returns null if the player is already logged in */
Session * CreateSession(uint32 AccountId);
/* updates sessions */
void Update();
};
#define sClientMgr ClientMgr::getSingleton()
| [
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef",
"[email protected]@3074cc92-8d2b-11dd-8ab4-67102e0efeef"
]
| [
[
[
1,
1
],
[
4,
63
]
],
[
[
2,
3
]
]
]
|
4e7cabcb7a1a7a5776a9b6b4820def0715cca28a | af260b99d9f045ac4202745a3c7a65ac74a5e53c | /branches/engine/2.4/src/Score.cpp | 700dc5241e7abb2ca8ef27c000c29e8a542d4869 | []
| no_license | BackupTheBerlios/snap-svn | 560813feabcf5d01f25bc960d474f7e218373da0 | a99b5c64384cc229e8628b22f3cf6a63a70ed46f | refs/heads/master | 2021-01-22T09:43:37.862180 | 2008-02-17T15:50:06 | 2008-02-17T15:50:06 | 40,819,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,848 | cpp | #include "Score.h"
#include "ScoreFunction.h"
#include <assert.h>
#include "ExtraMath.h"
//
// class for computing hyper-geometric pvalues
class HyperGeometric {
//
// copied from legacy SeedSearcher MyMath.h
public:
/**
*param : log(X) , log(Y).
*return: log(X+Y)
* Note: by default if one of the given is 0 just returns the other ,as it assumes this is the start of cumulative
* procedure summing prob.
* if one wants to treat 0 as log(1) than ignoreZero should be set to false.
*/
inline static
double addLog(double logX , double logY , bool ignoreZero = true)
{
if (ignoreZero) {
if (! logX) return logY;
if (! logY) return logX;
}
if (logX == -HUGE_VAL) return logY;
if (logY == -HUGE_VAL) return logX;
double m = (logX > logY) ? logX : logY;
return (m+log(exp(logX-m)+exp(logY-m)) );
}
inline static
double gammaln(int n) {
// simple implementation (for naturals only)
// log(gamma(n))=log((n-1)!)=log(1)+..+log(n-1)
// verified against matlab's gammaln.m
/* static map<int,double> lgammaVal; */
static const int MAX_GAMMA = 8000;
static double lgammaVal [MAX_GAMMA];
static double first4[4] = {0,0,0,0};
static double first4Val[4];
static int index = 0;
static bool init = false;
if (!init) {
for (int i=0;i<MAX_GAMMA;i++)
lgammaVal[i] = 0;
init = true;
}
//try the x,k cache:
assert(n>0);
if ( n < MAX_GAMMA) {
if(! lgammaVal[n])
lgammaVal[n] = lgamma(n);
return lgammaVal[n];
}
// check the n,m cache:
for (int i=0;i<4;i++) {
if (first4[i] == n)
return first4Val[i];
}
if (index < 4) {
first4[index] = n;
first4Val[index] = lgamma(n);
index++;
return first4Val[index-1];
}
return lgamma(n);// no cach helped here...
/* if (lgammaVal.find(n) == lgammaVal.end()) */
/* lgammaVal[n] = lgamma(n); */
/* double sum = 0.0; //log(1)=0 */
/* for (int i=2; i<=n-1; i++) */
/* sum += log(i); */
/* return(sum); */
}
inline static
double loghygepdf(int x, int m, int k, int n) {
//taking the pdf def - substituting gamma for factorial,
//and computing logs to raise exp to result at end
// verified against matlab's hygepdf.m
assert (0<=x && x<=n && n<=m && x<=k && k<=m && k-x<=m-n);
// can be extended in x so that all other values receive 0
double kx, mn, mknx; // we group folowing matlab, for no apparent reason
kx = gammaln(k+1) - gammaln(x+1) - gammaln(k-x+1);
mn = gammaln(m+1) - gammaln(n+1) - gammaln(m-n+1);
mknx = gammaln(m-k+1) - gammaln(n-x+1) - gammaln(m-n-k+x+1);
return (kx+mknx-mn);
}
inline static
double logTailhyge(int x, int m, int k, int n) {
// we compute the straight forward pdf sum over the smaller
// range between computing the cdf or its complementary
// verified against matlab's hygecdf.m
assert (0<=x && x<=n && n<=m && x<=k && k<=m && k-x<=m-n);
// can be extended: non int x => compute for floor(x)
// x<0 => cdf = 0
// x>min(k,n) => cdf = 1
double sum = -HUGE_VAL;
int xmax = (k<n ? k : n); // can't get more hits than that
for (int i=x; i<=xmax; i++) // its complementary
sum = addLog(sum,loghygepdf(i,m,k,n),false);
return(sum);
}
};
using namespace Scores;
Scores::HyperGeometricPvalue::HyperGeometricPvalue (const TFPN& tfpn)
: _tfpn (tfpn)
{
int x, k, N, M;
convert (_tfpn, x, k, N, M);
static const double LN_2 = ::log (static_cast <double> (2));
_log2Score = HyperGeometric::logTailhyge(x, M, k, N) / LN_2;
}
void
Scores::HyperGeometricPvalue::
convert (const TFPN& tfpn, int& x, int& k, int& N,int& M)
{
x = tfpn._TP;
k = tfpn._TP + tfpn._FP;
N = tfpn._TP + tfpn._FN;
M = tfpn._TP + tfpn._FP + tfpn._TN + tfpn._FN;
debug_mustbe (0<=x);
debug_mustbe (x<=k);
debug_mustbe (x<=N);
debug_mustbe (N<=M);
debug_mustbe (k<=M);
debug_mustbe (k-x<=M-N);
}
Scores::BonfCorrectedPvalue::
BonfCorrectedPvalue (boost::shared_ptr <Score> score, int repeatedTrials)
: _pscore (score), _repeatedTrials (repeatedTrials)
{
_log2Score = _pscore->log2Score() + log2 (_repeatedTrials);
}
Scores::FDRCorrectedPValue::
FDRCorrectedPValue ( boost::shared_ptr <Score> score,
int repeatedTrials,
int k,
const FDRCorrectedPValue* previousScore
)
: _pscore (score), _repeatedTrials (repeatedTrials)
{
_log2Score = _pscore->log2Score() + log2 (_repeatedTrials) - log2 (_k);
//
// the k-th best Pvalue must be better than the (k+1)th Pvalue
// even after the correction
if (previousScore != NULL)
_log2Score = tmin (_log2Score, previousScore->log2Score());
}
boost::shared_ptr <Scores::Function>
Scores::makeFunction (
CountType countType,
PositionWeightType scorePartial,
boost::shared_ptr <SequenceDB>& db,
boost::shared_ptr <SeqWeightFunction>& wf,
boost::shared_ptr <Factory>& factory,
int seedLength
)
{
switch (scorePartial) {
case _position_weight_discrete_:
switch (countType) {
case _count_gene_:
return boost::shared_ptr <Scores::Function> (
new DiscriminativeFunction <
detail::PositionWeighter <_position_weight_discrete_>,
detail::PositionCounter <_count_gene_>
> (db, wf, factory, seedLength)
);
case _count_total_:
return Function_ptr (
new DiscriminativeFunction <
detail::PositionWeighter <_position_weight_discrete_>,
detail::PositionCounter <_count_total_>
> (db, wf, factory, seedLength)
);
};
break;
case _position_weight_real_:
switch (countType) {
case _count_gene_:
return Function_ptr (
new DiscriminativeFunction <
detail::PositionWeighter <_position_weight_real_>,
detail::PositionCounter <_count_gene_>
> (db, wf, factory, seedLength)
);
case _count_total_:
return Function_ptr (
new DiscriminativeFunction <
detail::PositionWeighter <_position_weight_real_>,
detail::PositionCounter <_count_total_>
> (db, wf, factory, seedLength)
);
};
break;
case _position_weight_hotspots_:
switch (countType) {
case _count_gene_:
return Function_ptr (
new DiscriminativeFunction <
detail::PositionWeighter <_position_weight_hotspots_>,
detail::PositionCounter <_count_gene_>
> (db, wf, factory, seedLength)
);
case _count_total_:
return Function_ptr (
new DiscriminativeFunction <
detail::PositionWeighter <_position_weight_hotspots_>,
detail::PositionCounter <_count_total_>
> (db, wf, factory, seedLength)
);
};
break;
};
mustfail ();
return boost::shared_ptr <Scores::Function> ();
}
//
// compare to another score
// returns -1 if MY score is better (lower)
// returns 1 if the OTHER score is better (lower)
// returns 0 if the scores are equal
int Scores::Score::compare (const Score& other) const
{
double myscore = log2Score ();
double oscore = other.log2Score ();
Score* mynext = next ().get ();
Score* onext = other.next ().get ();
while ((myscore == oscore) && ((mynext != NULL) || (onext != NULL))) {
if (mynext != NULL) {
myscore = mynext->log2Score ();
mynext = mynext->next ().get ();
}
if (onext != NULL) {
oscore = onext->log2Score ();
onext = onext->next ().get ();
}
}
if (myscore < oscore) return -1;
else if (myscore > oscore) return 1;
else return 0;
}
//
// TODO: should this be implemented in hash table?
typedef std::map <Scores::TFPN, boost::shared_ptr <Scores::HyperGeometricPvalue> > HGScoreMap;
struct Scores::HyperGeometricPvalueFactory::Cache : public HGScoreMap {
} _hgcache;
Scores::HyperGeometricPvalueFactory::HyperGeometricPvalueFactory ()
{
}
Scores::HyperGeometricPvalueFactory::~HyperGeometricPvalueFactory ()
{
}
Scores::Score_ptr Scores::HyperGeometricPvalueFactory::create (const TFPN& tfpn) const
{
TFPN converted (0, 0, 0, 0);
HyperGeometricPvalue::convert (tfpn, converted._TP, converted._TN, converted._FP, converted._FN);
Cache::iterator it = _hgcache.lower_bound (tfpn);
if (it == _hgcache.end () || it->first != tfpn) {
it = _hgcache.insert (
it,
std::make_pair (
converted,
boost::shared_ptr <HyperGeometricPvalue> (
new HyperGeometricPvalue (tfpn)
)
)
);
debug_mustbe (it == _hgcache.find (converted));
debug_only (tfpn == it->second->parameters (converted));
}
return it->second;
}
typedef std::map <Scores::TFPN, boost::shared_ptr <Scores::ExplossScore> > ExplossScoreMap;
struct Scores::ExplossScoreFactory::Cache : public ExplossScoreMap {
} _explosscache;
boost::shared_ptr <Score> Scores::ExplossScoreFactory::create (const TFPN& tfpn ) const
{
Cache::iterator it = _explosscache.lower_bound (tfpn);
if (it == _explosscache.end () || it->first != tfpn) {
it = _explosscache.insert (
it,
std::make_pair (
tfpn,
boost::shared_ptr <ExplossScore> (
new ExplossScore (_weights, tfpn)
)
)
);
debug_only (
TFPN test (0, 0, 0, 0);
debug_mustbe (it == _explosscache.find (tfpn));
debug_mustbe (tfpn == (it->second->parameters (test)));
);
}
return it->second;
}
| [
"aviadr1@1f8b7f26-7806-0410-ba70-a23862d07478"
]
| [
[
[
1,
350
]
]
]
|
c736b95ed386b9376b677d02c475345fc5680138 | 09e322e0db32ccd7c0a8aaa357fb8763c43bf1bf | /PComImpl/profiler_base.h | 84e8c7928bf6d019798b3b3ebd3d473d50810f70 | []
| 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 | 7,517 | h | #pragma once
class ProfilerBase : public ICorProfilerCallback2
{
protected:
ICorProfilerInfo2 * profiler;
DWORD eventMask;
FILE * f;
public:
ProfilerBase( DWORD eventMask, std::string const& foo) : eventMask( eventMask )
{
f = fopen( foo.c_str(), "w" );
}
void Log( char const * s )
{
fprintf(f, "%s\n", s );
fflush(f);
}
void LogEx( char const * s, ... )
{
va_list l;
va_start( l, s );
vfprintf( f, s, l );
va_end( l );
}
STDMETHOD_(ULONG,AddRef)() { return S_OK; }
STDMETHOD_(ULONG,Release)() { return S_OK; }
STDMETHOD(QueryInterface)( IID const & riid, void ** ppInterface )
{
Log("Query Interface");
if (riid == IID_IUnknown || riid == IID_ICorProfilerCallback || riid == IID_ICorProfilerCallback2)
{
*ppInterface = (void*)this;
return S_OK;
}
Log("Asploded");
return E_NOINTERFACE;
}
STDMETHOD(Initialize)( IUnknown * pCorProfilerInfoUnk )
{
HRESULT hr = pCorProfilerInfoUnk->QueryInterface( IID_ICorProfilerInfo2, (void **)&profiler );
if (FAILED(hr))
return E_INVALIDARG;
profiler->SetEventMask( eventMask );
return S_OK;
}
STDMETHOD(Shutdown)() { return S_OK; }
STDMETHOD(AppDomainCreationStarted)(UINT appDomainId) { return E_NOTIMPL; }
STDMETHOD(AppDomainCreationFinished)(UINT appDomainId, HRESULT hrStatus ) { return E_NOTIMPL; }
STDMETHOD(AppDomainShutdownStarted)(UINT appDomainId) { return E_NOTIMPL; }
STDMETHOD(AppDomainShutdownFinished)(UINT appDomainId, HRESULT hrStatus ) { return E_NOTIMPL; }
STDMETHOD(AssemblyLoadStarted)(UINT assemblyId) { return E_NOTIMPL; }
STDMETHOD(AssemblyLoadFinished)(UINT assemblyId, HRESULT hrStatus) { return E_NOTIMPL; }
STDMETHOD(AssemblyUnloadStarted)(UINT assemblyId) { return E_NOTIMPL; }
STDMETHOD(AssemblyUnloadFinished)(UINT assemblyId, HRESULT hrStatus) { return E_NOTIMPL; }
STDMETHOD(ModuleLoadStarted)(UINT moduleId) { return E_NOTIMPL; }
STDMETHOD(ModuleLoadFinished)(UINT moduleId, HRESULT hrStatus) { return E_NOTIMPL; }
STDMETHOD(ModuleUnloadStarted)(UINT moduleId) { return E_NOTIMPL; }
STDMETHOD(ModuleUnloadFinished)(UINT moduleId, HRESULT hrStatus) { return E_NOTIMPL; }
STDMETHOD(ModuleAttachedToAssembly)(UINT moduleId, UINT assemblyId) { return E_NOTIMPL; }
STDMETHOD(ClassLoadStarted)(UINT classId) { return E_NOTIMPL; }
STDMETHOD(ClassLoadFinished)(UINT classId, HRESULT hrStatus) { return E_NOTIMPL; }
STDMETHOD(ClassUnloadStarted)(UINT classId) { return E_NOTIMPL; }
STDMETHOD(ClassUnloadFinished)(UINT classId, HRESULT hrStatus) { return E_NOTIMPL; }
STDMETHOD(FunctionUnloadStarted)(UINT functionId) { return E_NOTIMPL; }
STDMETHOD(JITCompilationStarted)(UINT functionId, BOOL fIsSafeToBlock) { return E_NOTIMPL; }
STDMETHOD(JITCompilationFinished)(UINT functionId, HRESULT hrStatus, BOOL fIsSafeToBlock) { return E_NOTIMPL; }
STDMETHOD(JITCachedFunctionSearchStarted)(UINT functionId, BOOL * pbUseCachedFunction ) { return E_NOTIMPL; }
STDMETHOD(JITCachedFunctionSearchFinished)(UINT functionId, COR_PRF_JIT_CACHE result ) { return E_NOTIMPL; }
STDMETHOD(JITFunctionPitched)(UINT functionId) { return E_NOTIMPL; }
STDMETHOD(JITInlining)(UINT callerId, UINT calleeId, BOOL * pfShouldInline) { return E_NOTIMPL; }
STDMETHOD(ThreadCreated)(UINT threadId) { return E_NOTIMPL; }
STDMETHOD(ThreadDestroyed)(UINT threadId) { return E_NOTIMPL; }
STDMETHOD(ThreadAssignedToOSThread)(UINT managed, DWORD os) { return E_NOTIMPL; }
STDMETHOD(RemotingClientInvocationStarted)() { return E_NOTIMPL; }
STDMETHOD(RemotingClientInvocationFinished)() { return E_NOTIMPL; }
STDMETHOD(RemotingClientSendingMessage)( GUID * pCookie, BOOL fIsAsync ) { return E_NOTIMPL; }
STDMETHOD(RemotingClientReceivingReply)( GUID * pCookie, BOOL fIsAsync ) { return E_NOTIMPL; }
STDMETHOD(RemotingServerInvocationStarted)() { return E_NOTIMPL; }
STDMETHOD(RemotingServerInvocationReturned)() { return E_NOTIMPL; }
STDMETHOD(RemotingServerReceivingMessage)( GUID * pCookie, BOOL fIsAsync ) { return E_NOTIMPL; }
STDMETHOD(RemotingServerSendingReply)( GUID * pCookie, BOOL fIsAsync ) { return E_NOTIMPL; }
STDMETHOD(UnmanagedToManagedTransition)(UINT functionId, COR_PRF_TRANSITION_REASON reason ) { return E_NOTIMPL; }
STDMETHOD(ManagedToUnmanagedTransition)(UINT functionId, COR_PRF_TRANSITION_REASON reason ) { return E_NOTIMPL; }
STDMETHOD(RuntimeSuspendStarted)( COR_PRF_SUSPEND_REASON reason ) { return E_NOTIMPL; }
STDMETHOD(RuntimeSuspendFinished)() { return E_NOTIMPL; }
STDMETHOD(RuntimeSuspendAborted)() { return E_NOTIMPL; }
STDMETHOD(RuntimeResumeStarted)() { return E_NOTIMPL; }
STDMETHOD(RuntimeResumeFinished)() { return E_NOTIMPL; }
STDMETHOD(RuntimeThreadSuspended)( UINT threadId ) { return E_NOTIMPL; }
STDMETHOD(RuntimeThreadResumed)( UINT threadId ) { return E_NOTIMPL; }
STDMETHOD(MovedReferences)( ULONG count, UINT oldIdRange[], UINT newIdRange[], ULONG idRangeLength[] ) { return E_NOTIMPL; }
STDMETHOD(ObjectAllocated)(UINT objectId, UINT classId) { return E_NOTIMPL; }
STDMETHOD(ObjectsAllocatedByClass)(ULONG classes, UINT classIds[], ULONG objectCounts[]) { return E_NOTIMPL; }
STDMETHOD(ObjectReferences)(UINT objectId, UINT classId, ULONG numRefs, UINT refIds[] ) { return E_NOTIMPL; }
STDMETHOD(RootReferences)(ULONG numRootRefs, UINT refs[] ) { return E_NOTIMPL; }
STDMETHOD(ExceptionThrown)(UINT objectId) { return E_NOTIMPL; }
STDMETHOD(ExceptionSearchFunctionEnter)(UINT functionId) { return E_NOTIMPL; }
STDMETHOD(ExceptionSearchFunctionLeave)() { return E_NOTIMPL; }
STDMETHOD(ExceptionSearchFilterEnter)(UINT functionId) { return E_NOTIMPL; }
STDMETHOD(ExceptionSearchFilterLeave)() { return E_NOTIMPL; }
STDMETHOD(ExceptionSearchCatcherFound)(UINT functionId) { return E_NOTIMPL; }
STDMETHOD(ExceptionOSHandlerEnter)(UINT_PTR) { return E_NOTIMPL; }
STDMETHOD(ExceptionOSHandlerLeave)(UINT_PTR) { return E_NOTIMPL; }
STDMETHOD(ExceptionUnwindFunctionEnter)(UINT functionId) { return E_NOTIMPL; }
STDMETHOD(ExceptionUnwindFunctionLeave)() { return E_NOTIMPL; }
STDMETHOD(ExceptionUnwindFinallyEnter)(UINT functionId) { return E_NOTIMPL; }
STDMETHOD(ExceptionUnwindFinallyLeave)() { return E_NOTIMPL; }
STDMETHOD(ExceptionCatcherEnter)(UINT functionId, UINT objectId) { return E_NOTIMPL; }
STDMETHOD(ExceptionCatcherLeave)() { return E_NOTIMPL; }
STDMETHOD(COMClassicVTableCreated)( UINT classId, GUID const & iid, void * vt, ULONG slots ) { return E_NOTIMPL; }
STDMETHOD(COMClassicVTableDestroyed)( UINT classId, GUID const & iid, void * vt ) { return E_NOTIMPL; }
STDMETHOD(ExceptionCLRCatcherFound)() { return E_NOTIMPL; }
STDMETHOD(ExceptionCLRCatcherExecute)() { return E_NOTIMPL; }
STDMETHOD(ThreadNameChanged)(UINT threadId, ULONG cchName, WCHAR name[]) { return E_NOTIMPL; }
STDMETHOD(GarbageCollectionStarted)(int gen, BOOL gens[], COR_PRF_GC_REASON reason) { return E_NOTIMPL; }
STDMETHOD(SurvivingReferences)(ULONG, UINT o[], ULONG l[]) { return E_NOTIMPL; }
STDMETHOD(GarbageCollectionFinished)() { return E_NOTIMPL; }
STDMETHOD(FinalizeableObjectQueued)(DWORD finalizerFlags, UINT object) { return E_NOTIMPL; }
STDMETHOD(RootReferences2)(ULONG, UINT ids[], COR_PRF_GC_ROOT_KIND rootkinds[],
COR_PRF_GC_ROOT_FLAGS flags[], UINT_PTR rootids[] ) { return E_NOTIMPL; }
STDMETHOD(HandleCreated)(UINT h, UINT obj) { return E_NOTIMPL; }
STDMETHOD(HandleDestroyed)(UINT h) { return E_NOTIMPL; }
};
| [
"chrisf@993157c7-ee19-0410-b2c4-bb4e9862e678",
"beedee@993157c7-ee19-0410-b2c4-bb4e9862e678",
"(no author)@993157c7-ee19-0410-b2c4-bb4e9862e678"
]
| [
[
[
1,
7
],
[
9,
10
],
[
21,
21
],
[
30,
32
],
[
35,
40
],
[
42,
154
]
],
[
[
8,
8
],
[
11,
20
],
[
33,
34
],
[
41,
41
]
],
[
[
22,
29
]
]
]
|
c68610d31ec432dbfc4e76e0e26947e0107db1b5 | ad59241b534bd17660dfbff28cdf8145f53aac92 | /CLIENT Avant refonte GUI/world.h | e34e4b15ada8fec2324088593cc4ebecf45ece92 | []
| no_license | CromFr/CromTPS | dc0e5c42d8c37b6169e014975d9f0ca8c9d3ad1f | 145ff39c2ab319e1d53e065ca8e92f137131cb38 | refs/heads/master | 2021-01-19T22:14:01.984408 | 2011-09-21T22:09:10 | 2011-09-21T22:09:10 | 2,282,991 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 504 | h | #ifndef WORLD_H_INCLUDED
#define WORLD_H_INCLUDED
int LoadMap(std::string sMapName);
bool GetIsBlockingVision(int nType);
bool GetIsBlockingWalk(int nType);
bool GetIsCollisionBallWithWorld(struct worldpospx pBall, float fRadius);
bool GetIsCollisionPointWithBall(struct worldpospx pPosPoint, struct worldpospx pPosBall, float fRadius);
bool GetIsCollisionPJWithWorld(struct worldpospx pPosPX);
bool GetIsCoordScreenPxInWorld(sf::Vector2<float>::Vector2<float> vPos);
#endif // WORLD_H_INCLUDED
| [
"[email protected]"
]
| [
[
[
1,
14
]
]
]
|
487fb1d22537b5b4611a7fe3bee20160cee1d230 | acf0e8a6d8589532d5585b28ec61b44b722bf213 | /new_gp_daemon/config_data_req_proc.h | b9fbbd58949a05144aca8cc927bd6bc80525761a | []
| no_license | mchouza/ngpd | 0f0e987a95db874b3cde4146364bf1d69cf677cb | 5cca5726910bfc97844689f1f40c94b27e0fb9f9 | refs/heads/master | 2016-09-06T02:09:32.007855 | 2008-04-06T14:17:55 | 2008-04-06T14:17:55 | 35,064,755 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 2,390 | h | //
// Copyright (c) 2008, Mariano M. Chouza
// 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.
//
// * The names of the contributors may not be used to endorse or promote
// products derived from this software without specific prior written
// permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
//=============================================================================
// config_data_req_proc.h
//-----------------------------------------------------------------------------
// Creado por Mariano M. Chouza | Empezado el 27 de marzo de 2008
//=============================================================================
#ifndef CONFIG_DATA_REQ_PROC_H
#define CONFIG_DATA_REQ_PROC_H
#include "req_processor.h"
namespace WebInterface
{
/// Maneja el acceso a los datos de configuración
class ConfigDataReqProc : public ReqProcessor
{
public:
/// Toma el ProcReq y actúa sobre el dato de configuración
/// correspondiente
virtual void process(const Poco::Net::HTTPServerRequest& procReq,
Poco::Net::HTTPServerResponse& resp);
};
}
#endif
| [
"mchouza@b858013c-4649-0410-a850-dde43e08a396"
]
| [
[
[
1,
56
]
]
]
|
2832a757a4b6ca0380c65284117dc24b58b4e6b4 | 12ea67a9bd20cbeed3ed839e036187e3d5437504 | /winxgui/Swc/swc/COutLook.h | 798bd791675cb5a45718bda94c3d741c6c7a9327 | []
| no_license | cnsuhao/winxgui | e0025edec44b9c93e13a6c2884692da3773f9103 | 348bb48994f56bf55e96e040d561ec25642d0e46 | refs/heads/master | 2021-05-28T21:33:54.407837 | 2008-09-13T19:43:38 | 2008-09-13T19:43:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,989 | h | /*
*
*
* Copyright 2007 Francisco Campos. All rights reserved.
* BEYONDATA PROPRIETARY. Use is subject to license terms. </F>
*
* \|||/
* |o_o|
* ----o00o-------o00o---
**/
#if !defined(AFX_BOUTLOOK_H_INCLUDED_)
#define AFX_BOUTLOOK_H_INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
//#define WM_OUTBAR_NOTIFY WM_USER+1
//#define NM_OB_ITEMCLICK WM_OUTBAR_NOTIFY+1
//esta clase da la flexibilidad de adicionar componentes
//diferentes a botones.
class COutLook;
class CItems
{
public:
CItems(COutLook* m_pParent,HICON m_hIcon,UINT Cmd,LPCSTR m_Message,LPCSTR m_ToolTip=_T(""), BOOL bTypeOutLook=TRUE);
public:
CToolButton m_bt;
int m_btipo; //es un boton o un derivado de Cwnd
LPSTR m_szMessage; //el mensaje bajo el boton
};
class COutLook : public CWin
{
friend class CItems;
public:
//***************************************
COutLook();
virtual ~COutLook();
//***************************************
public:
virtual BOOL Create(DWORD dwStyle, CRect& rect, CWin* pParentWnd, UINT nID) ;
virtual BOOL PreTranslateMessage(MSG* pMsg);
public:
void AddItem(UINT Cmd,LPCSTR m_szCaption,int nIndex,LPCSTR m_ToolTip=_T(""));
void SetImageList(UINT nBitmapID, int cx, int nGrow, COLORREF crMask);
virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam);
void RecalLayout();
void SetTypeLook(BOOL bNormal=TRUE)
{
m_TypeOutLook=bNormal;
}
protected:
//**************************************************
CImageCtrl m_imageList;
CArray m_ArrayButtons;
CSize m_sizeImage;
int m_ActualButtonPres;
int m_ultimoBotonResal;
int m_NumBottoms;
COLORREF m_cbkg;
int m_mouseMove;
int m_Avance; //avance del scroll
CRect m_rectArrowUp;
CRect m_rectArrowDown;
BOOL m_iDrawFrameUp;
BOOL m_iDrawFrameDown;
UINT mnID;
BOOL m_bPressU;
BOOL m_bPressD;
HDC hdc;
BOOL m_bIsXp;
BOOL m_TypeOutLook; // TRUE Outlook normal o FALSE
//**************************************************
BOOL OnPaint(HDC hDC);
BOOL OnLButtonDown(UINT nFlags, CPoint pt);
BOOL OnLButtonUp(UINT nFlags, CPoint pt);
BOOL OnSize(UINT nType, int cx, int cy);
BOOL OnSysColorChange();
void OnTimer(UINT nIDEvent);
BOOL OnEraseBkgnd(HDC hDC );
int OnDestroy();
protected:
BEGIN_MSG_MAP()
ON_WM_PAINT(OnPaint)
ON_WM_LBUTTONDOWN(OnLButtonDown)
ON_WM_LBUTTONUP(OnLButtonUp)
ON_WM_SIZE(OnSize)
ON_WM_SYSCOLORCHANGE(OnSysColorChange)
ON_WM_TIMER(OnTimer)
ON_WM_ERASEBKGND(OnEraseBkgnd)
ON_WM_DESTROY(OnDestroy)
END_MSG_MAP(CWin)
};
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_BOUTLOOK_H_INCLUDED_)
| [
"xushiweizh@86f14454-5125-0410-a45d-e989635d7e98"
]
| [
[
[
1,
124
]
]
]
|
d63c4d5f10d60fe6caf08e3787f1ac206f435503 | 13e9c77b28d1ce6de5fe4d08ef3e07559677582b | /softimage/AlembicPolyMsh.h | 32c43f67cbab7a91deafa02b6327678938168efe | [
"LicenseRef-scancode-unknown-license-reference",
"RSA-MD"
]
| permissive | oyaGG/helgemathee-alembic-softimage | c26145e00553bb999a2b7af220a065a1de2cfe41 | fb8c5f09f35ea899a272f9cab0dd2f887317c043 | refs/heads/master | 2021-01-14T10:21:11.877674 | 2011-09-08T09:52:22 | 2011-09-08T09:52:22 | 46,812,103 | 0 | 1 | null | 2015-11-24T18:58:38 | 2015-11-24T18:58:38 | null | UTF-8 | C++ | false | false | 518 | h | #ifndef _ALEMBIC_POLYMSH_H_
#define _ALEMBIC_POLYMSH_H_
#include "AlembicObject.h"
class AlembicPolyMesh: public AlembicObject
{
private:
Alembic::AbcGeom::OXformSchema mXformSchema;
Alembic::AbcGeom::OPolyMeshSchema mMeshSchema;
Alembic::AbcGeom::XformSample mXformSample;
Alembic::AbcGeom::OPolyMeshSchema::Sample mMeshSample;
int mNumSamples;
public:
AlembicPolyMesh(const XSI::CRef & in_Ref, AlembicWriteJob * in_Job);
virtual XSI::CStatus Save(double time);
};
#endif | [
"[email protected]"
]
| [
[
[
1,
21
]
]
]
|
87554b1f68e9567e45ac24e24909792fb3836318 | dc4b6ab7b120262779e29d8b2d96109517f35551 | /resources/Resources.h | a118cfcfb30dfbd950fa3a90241a845b3fd06a80 | []
| no_license | cnsuhao/wtlhelper9 | 92daef29b61f95f44a10e3277d8835c2dd620616 | 681df3a014fc71597e9380b0a60bd3cd23e22efe | refs/heads/master | 2021-07-17T19:59:07.143192 | 2009-05-18T14:24:48 | 2009-05-18T14:24:48 | 108,361,858 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,650 | h | ////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2004 Sergey Solozhentsev
// Author: Sergey Solozhentsev e-mail: [email protected]
// Product: WTL Helper
// File: Resources.h
// Created: 16.11.2004 8:55
//
// Using this software in commercial applications requires an author
// permission. The permission will be granted to everyone excluding the cases
// when someone simply tries to resell the code.
// This file may be redistributed by any means PROVIDING it is not sold for
// profit without the authors written consent, and providing that this notice
// and the authors name is included.
// This file is provided "as is" with no expressed or implied warranty. The
// author accepts no liability if it causes any damage to you or your computer
// whatsoever.
//
////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "../TextFile.h"
#include "ResDialog.h"
#include "ResMenu.h"
#include "ResToolbar.h"
#include "ResAccelerators.h"
struct ResString
{
CString m_ID;
CString m_String;
};
struct ResBinary
{
CString m_ID;
CString m_FileName;
};
class CResources
{
bool LoadString(CTextFile& file);
public:
CAtlArray<CResDialog> m_Dialogs;
CAtlArray<CResMenu> m_Menus;
CAtlArray<CResToolbar> m_Toolbars;
CAtlArray<CResAccelerators> m_Accels;
CAtlArray<ResString> m_Strings;
CAtlArray<ResBinary> m_Icons;
CAtlArray<ResBinary> m_Bitmaps;
CAtlArray<ResBinary> m_Cursors;
CResources(void);
~CResources(void);
bool Load(LPCTSTR filename, bool bAppend = false);
};
| [
"free2000fly@eea8f18a-16fd-41b0-b60a-c1204a6b73d1"
]
| [
[
[
1,
59
]
]
]
|
8d4c0a6c49e0f2c7e484e8a1f037dcf1679ac735 | 478570cde911b8e8e39046de62d3b5966b850384 | /apicompatanamdw/bcdrivers/os/ossrv/stdlibs/apps/libc/testglob/src/tglob.cpp | a278bda010d5fbad0531bf45e1d52cc3db5b459e | []
| 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 | 2,704 | cpp | /*
* Copyright (c) 2006 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:
*
*/
#include "tglob.h"
CTestglob::~CTestglob()
{
iRfs.RmDir(KDIRPATH1);
iRfs.RmDir(KDIRPATH2);
iRfs.RmDir(KBASEDIR);
iRfs.Close();
}
CTestglob::CTestglob(const TDesC& aStepName)
{
// MANDATORY Call to base class method to set up the human readable name for logging.
iRfs.Connect();
iRfs.MkDirAll(KDIRPATH1);
iRfs.MkDirAll(KDIRPATH2);
SetTestStepName(aStepName);
}
TVerdict CTestglob::doTestStepPreambleL()
{
__UHEAP_MARK;
SetTestStepResult(EPass);
return TestStepResult();
}
TVerdict CTestglob::doTestStepPostambleL()
{
__UHEAP_MARKEND;
return TestStepResult();
}
TVerdict CTestglob::doTestStepL()
{
int err;
//glob steps
if(TestStepName() == Kglobappend)
{
INFO_PRINTF1(_L("Kglobappend():"));
err = globappend();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == Kglobbrace)
{
INFO_PRINTF1(_L("Kglobbrace():"));
err = globbrace();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == Kglobdooffs)
{
INFO_PRINTF1(_L("Kglobdooffs():"));
err = globdooffs();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == Kglobmark)
{
INFO_PRINTF1(_L("Kglobmark():"));
err = globmark();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == Kglobnocheck)
{
INFO_PRINTF1(_L("Kglobnocheck():"));
err = globnocheck();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == Kglobnosort)
{
INFO_PRINTF1(_L("Kglobnosort():"));
err = globnosort();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else if(TestStepName() == Kglobtilde)
{
INFO_PRINTF1(_L("Kglobtilde():"));
err = globtilde();
SetTestStepResult(err ? static_cast<TVerdict>(err) : EPass);
}
else
{
SetTestStepResult(EPass);
}
return TestStepResult();
}
| [
"none@none"
]
| [
[
[
1,
117
]
]
]
|
edf183c05eec3a816b3ea9ae33c5f1f5e18e166c | 77aa13a51685597585abf89b5ad30f9ef4011bde | /src/hearthstone-shared/Collision/vmap/BaseModel.cpp | d8d13b0ee85955e5a8dff433291bd13c14c38b17 | []
| no_license | Zic/Xeon-MMORPG-Emulator | 2f195d04bfd0988a9165a52b7a3756c04b3f146c | 4473a22e6dd4ec3c9b867d60915841731869a050 | refs/heads/master | 2021-01-01T16:19:35.213330 | 2009-05-13T18:12:36 | 2009-05-14T03:10:17 | 200,849 | 8 | 10 | null | null | null | null | UTF-8 | C++ | false | false | 2,126 | cpp | /*
* Copyright (C) 2005,2006,2007 MaNGOS <http://www.mangosproject.org/>
* Copyright (C) 2007-2008 Ascent Team <http://www.ascentemu.com/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "BaseModel.h"
namespace VMAP
{
//==========================================================
void BaseModel::getMember(Array<TriangleBox>& pMembers)
{
for(unsigned int i=0; i<iNTriangles; i++)
{
pMembers.append(iTriangles[i]);
}
}
//==========================================================
BaseModel::BaseModel(unsigned int pNNodes, unsigned int pNTriangles)
{
init(pNNodes, pNTriangles);
};
//==========================================================
void BaseModel::init(unsigned int pNNodes, unsigned int pNTriangles)
{
iNNodes = pNNodes;
iNTriangles = pNTriangles;
iTriangles = NULL;
iTreeNodes = NULL;
if(iNNodes >0) iTreeNodes = new TreeNode[iNNodes];
if(iNTriangles >0) iTriangles = new TriangleBox[iNTriangles];
}
//==========================================================
void BaseModel::free()
{
if(getTriangles() != 0) delete [] getTriangles(); setNTriangles(0);
if(getTreeNodes() != 0) delete [] getTreeNodes(); setNNodes(0);
}
} // VMAP
| [
"valroft@a6a5f009-272a-4b40-a74d-5f9816a51f88"
]
| [
[
[
1,
60
]
]
]
|
4e687e2092522758a490033800cb00d4acd39a66 | e03ee4538dce040fe16fc7bb48d495735ac324f4 | /Stable/Behaviours/RoleFactory.cpp | 707beb3dfe1eecc7293a48089cf2aaecfb21ce50 | []
| no_license | vdelgadov/itcvideogame | dca6bcb084c5dde25ecf29ab1555dbe8b0a9a441 | 5eac60e901b29bff4d844f34cd52f97f4d1407b5 | refs/heads/master | 2020-05-16T23:43:48.956373 | 2009-12-01T02:09:08 | 2009-12-01T02:09:08 | 42,265,496 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,019 | cpp | #pragma once
#include "Actor_States.cpp"
InfluenceMap* AIController::s_InfluenceMap;
#include "Brute.cpp"
#include "Artillery.cpp"
#include "Skirk.cpp"
#include "../AIController/AIController.h"
class RoleFactory{
public:
enum state_t {ATTACK, ENGAGE};
static AState<Actor>* CreateRoleState(AIController::role_t r, state_t s ){
switch(r){
case AIController::BRUTE:
return CreateBruteState(s);
case AIController::ARTILLERY:
return CreateArtState(s);
case AIController::SKIRKMISHER:
return CreateSkirkState(s);
}
}
static AState<Actor>* CreateBruteState(state_t s){
if(s == ATTACK)
return new BruteAttack();
return new BruteEngaging();
}
static AState<Actor>* CreateArtState(state_t s){
if(s == ATTACK)
return new ArtAttack();
return new ArtEngaging();
}
static AState<Actor>* CreateSkirkState(state_t s){
if(s == ATTACK)
return new SkirkAttack();
return new SkirkEngaging();
}
}; | [
"leamsi.setroc@972b8bf6-92a2-11de-b72a-e7346c8bff7a",
"mrjackinc@972b8bf6-92a2-11de-b72a-e7346c8bff7a"
]
| [
[
[
1,
5
],
[
7,
7
],
[
17,
20
],
[
22,
22
],
[
24,
24
],
[
31,
31
],
[
39,
39
],
[
47,
47
],
[
55,
55
]
],
[
[
6,
6
],
[
8,
16
],
[
21,
21
],
[
23,
23
],
[
25,
30
],
[
32,
38
],
[
40,
46
],
[
48,
54
]
]
]
|
04ed9ab63cd4070a382252bd0015441b68a9de6a | 3821b0e33b166008aa89c49c9cb8b6f19836f589 | /PyVariable.h | de4832e26170e1913286960a31791e7a6d932ea7 | []
| no_license | bengioe/PyVariable | 792c37768d8da7f623aac99fa9c41d7a414b8594 | 5ca46969f8a52d02c672682beaf274e0532940df | refs/heads/master | 2016-09-06T13:42:17.366992 | 2011-07-20T21:31:00 | 2011-07-20T21:31:00 | 2,012,756 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,624 | h | #ifndef PYVAR_H
#define PYVAR_H
#include <Python.h>
#include <string>
#include <list>
class PyVariable;
#include "PyException.h"
class PyVariable
{
private:
PyObject* m_obj;
unsigned int m_flag;
// list of stuff used by our functions that should be freed someday
// since they could not be immediatly freed when returned
std::list<void*> m_tofree;
public:
PyVariable();
PyVariable(PyObject* obj,bool isBorrowedRef=false);
PyVariable(const PyVariable& o);
// build from C++ types
PyVariable(const char* s);
PyVariable(std::string s);
PyVariable(int i);
PyVariable(long i);
PyVariable(double d);
PyVariable(PyObject* (*fpFunc)(PyObject*,PyObject*));
PyVariable(void (*fpFunc)(PyVariable));
PyVariable(PyVariable (*fpFunc)(PyVariable));
~PyVariable();
/// PyVariable specific methods
// Once object is manipulated,
// we can send it back to Python:
PyObject* get();
// Check wether m_obj is null
bool isEmpty();
// Check wether obj is None
bool isNone();
// For dict's, set a key to a value
PyVariable setitem(PyVariable key,PyVariable value);
// Get attribute (one can also use o[attr] if type(o)!=dict)
PyVariable getattr(std::string attr);
/// "Common" methods
//str(o)
const char* c_str(); // C char*
operator const char*() {return this->c_str();}
std::string str(); // C++ string
operator std::string() {return this->str();}
//o.append
PyVariable append(PyVariable e, int nrepeat=1);
//C/C++ values
int c_int();
operator int () {return this->c_int();}
// math!
PyVariable operator+(PyVariable other);
PyVariable operator-(PyVariable other);
PyVariable operator/(PyVariable other);
PyVariable operator*(PyVariable other);
// affectation
void operator=(PyVariable other);
void operator=(long other);
void operator=(const char* other);
//o[k]
// note that if the object is a dictionnary, and k is not a key
// of o, an exception is raised. To affect (o[k] = v), use o.dict.set(k,v)
PyVariable operator[](int index);
PyVariable operator[](PyVariable index);
// the following is either o[k] if o is a dict
// or o.k if o is not a dict
PyVariable operator[](std::string);
PyVariable operator[](const char*);
//o()
PyVariable operator()();
//o(arg1,[arg2,[arg3]])
PyVariable operator()(PyVariable arg1,PyVariable arg2=Py_None, PyVariable arg3=Py_None);
//Creation static methods
static PyVariable dict();
static PyVariable list();
static PyVariable new_int();
static PyVariable new_str();
static PyVariable new_tuple();
//static class methods
static PyVariable import(std::string module_name);
static PyVariable reload(PyVariable module);
// "exec" runs PyRun_String, so you can use it as both an
// "eval" method and an "exec" method to print various stuff
static PyVariable exec(std::string str);
static PyVariable exec(const char* str, const char* args, ...);
};
/*
class _pyvar_dict_bit{
public:
_pyvar_dict_bit(){
d = PyDict_New();
}
_pyvar_dict_bit push(PyVariable k,PyVariable v){
PyDict_SetItem(d,k.get(),v.get());
return *this;
}
PyObject* pop(){
return d;
}
private:
PyObject* d;
};
PyVariable PyVariable::operator=(_pyvar_dict_bit db);
static _pyvar_dict_bit PyVariable::dict();
*/
#endif
| [
"[email protected]",
"[email protected]"
]
| [
[
[
1,
4
],
[
6,
13
],
[
17,
19
],
[
21,
26
],
[
29,
131
]
],
[
[
5,
5
],
[
14,
16
],
[
20,
20
],
[
27,
28
]
]
]
|
66e1d60f852424fcd853bbcd15dd25380b5291da | 3d7fc34309dae695a17e693741a07cbf7ee26d6a | /aluminizerFPGA/experiments.cpp | e20f64076881690c695e307d1fd2803716353441 | [
"LicenseRef-scancode-public-domain"
]
| permissive | nist-ionstorage/ionizer | f42706207c4fb962061796dbbc1afbff19026e09 | 70b52abfdee19e3fb7acdf6b4709deea29d25b15 | refs/heads/master | 2021-01-16T21:45:36.502297 | 2010-05-14T01:05:09 | 2010-05-14T01:05:09 | 20,006,050 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,101 | cpp | #include <vector>
#include <algorithm>
#include "experiments.h"
#include "host_interface.h"
#include "Numerics.h"
#include "motors.h"
#include "exp_recover.h"
using namespace std;
experiment::experiment(list_t* exp_list, const std::string& name) :
info_interface(exp_list, name),
auto_recover("Auto recover", ¶ms, "value=0"),
debug_level("Debug level", ¶ms, "value=0"),
num_exp("Experiments", ¶ms, "value=100 min=0 max=200"),
Padding(TTL_START_EXP, "Mg Padding", ¶ms, "t=20"),
rcSignal(channels, COOLING_ION_NAME + std::string(" signal (s)")),
rcTiming(channels, "Timing err."),
rcDDSerrors(channels, "DDS err."),
exp_flags(0)
{
Padding.setFlag(RP_FLAG_CAN_HIDE);
}
void experiment::init_exp_sequence(const GbE_msg& msg_in, GbE_msg& msg_out)
{
this->msg_in = &msg_in;
this->msg_out = &msg_out;
g_debug_level = debug_level;
iMsg = 0;
this->exp_flags = msg_in.extractU(1);
pmt.init(&msg_out, getNumChannels(), false);
init();
reshuffle();
//make sure ion is bright
if (auto_recover && eRecover)
eRecover->recover_ion();
prep_ions();
}
bool experiment::debug_exp(unsigned i)
{
return (i == 0) && (exp_flags & EXP_FLAG_DEBUG);
}
void experiment::put_results(GbE_msg& msg_out)
{
for (size_t i = 0; i < channels.size(); i++)
msg_out.insertU(i + 1, static_cast<unsigned>(1000 * (channels[i]->result + 1000000)));
}
void experiment::init_exp(unsigned i)
{
bDebugPulses = debug_exp(i);
if (bDebugPulses)
{
sprintf(host->buffDebug, "Start pulse sequence for experiment: %s\n", name.c_str());
host->sendDebugMsg(host->buffDebug);
}
}
void experiment::run(const GbE_msg& msg_in, GbE_msg& msg_out)
{
init_exp_sequence(msg_in, msg_out);
rcDDSerrors.result = 0;
for (unsigned i = 0; i < num_exp; i++)
{
init_exp(i);
//start timing check. disables interrupts
pmt.begin_timing_check(Padding.t, Padding.ttl);
//run the experiment
run_exp(i);
//stop timing check. enables interrupts
pmt.end_timing_check();
//get PMT results & check timing
unsigned N = getNumDetect();
for (unsigned j = 0; j < N; j++)
pmt.get_new_data();
if (bDebugPulses)
{
sprintf(host->buffDebug, "Finish pulse sequence for experiment: %s\n\n\n", name.c_str());
host->sendDebugMsg(host->buffDebug, true);
}
bDebugPulses = false;
//count DDS errors
// rcDDSerrors.result += (1 - PULSE_CONTROLLER_check_all_dds(pulser));
}
post_exp_calc_results();
finish_exp_sequence(msg_out);
post_exp_sequence(rcSignal.result);
}
void experiment::finish_exp_sequence(GbE_msg& msg_out)
{
pmt.print_timing_failures();
rcSignal.result = pmt.get_average();
rcTiming.result = pmt.num_failures();
put_results(msg_out);
}
void exp_detect::run_exp(int)
{
Precool.ddsOff();
DopplerCool.pulse();
Detect.detection_pulse();
Precool.pulseStayOn();
}
void exp_detect::detectBkg()
{
//background detection
unsigned ftwOn_old = Detect.ftwOn;
Detect.ftwOn = Detect.ftwOff;
Detect.detection_pulse();
Detect.ftwOn = ftwOn_old;
}
void exp_detectN::run_exp(int)
{
Precool.ddsOff();
DopplerCool.pulse();
unsigned N = getNumDetect();
for (unsigned i = 0; i < N; i++)
Detect.detection_pulse();
Precool.pulseStayOn();
}
void exp_load_Mg::run(const GbE_msg& msg_in, GbE_msg& msg_out)
{
init_exp_sequence(msg_in, msg_out);
int deltaN = 0;
//stretch detection time
unsigned tOld = Detect.t;
Detect.t = static_cast<unsigned>(Detect.t * detection_stretch);
for (unsigned i = 0; i < num_exp; i++)
{
init_exp(i);
//provide some padding so that the processor gets a head start in
//filling the timing buffer
Padding.pulse();
//run the experiment
run_exp(i);
//get PMT results & check timing
int n1 = pmt.get_new_data();
Precool.ddsOff();
DopplerCool.pulse();
detectBkg();
Precool.pulseStayOn();
int n2 = pmt.get_new_data(1, false);
deltaN += (n1 - n2);
if (bDebugPulses)
{
sprintf(host->buffDebug, "Finish pulse sequence for experiment: %s\n\n\n", name.c_str());
host->sendDebugMsg(host->buffDebug, true);
}
bDebugPulses = false;
}
//unstretch
Detect.t = tOld;
rcMgCounts.result = ((double)deltaN) / ((double)num_exp);
finish_exp_sequence(msg_out);
}
void exp_scanDDS::updateParams()
{
info_interface::updateParams();
pulse_dds.dds = dds_num;
}
void exp_scanDDS::run_exp(int)
{
pulse_dds.pulseStayOn();
}
void exp_repump::run_exp(int)
{
Precool.ddsOff();
DopplerCool.pulse();
Carrier.pulse();
PrecoolR.pulse();
Repump.pulse();
Detect.detection_pulse();
Precool.pulseStayOn();
}
void exp_heat::init()
{
exp_detect::init();
Heat.ttl = HeatTTL;
}
void exp_heat::run_exp(int)
{
Precool.ddsOff();
DopplerCool.pulse();
// new
Heat.pulse();
if (!disableCarrier)
Carrier90.stretched_pulse((unsigned)(CarrierStretch * 1000));
// old
/* Heat.stretched_pulse((unsigned)(CarrierStretch*1000));
if(!disableCarrier)
Carrier90.pulse();
*/
Detect.detection_pulse();
Precool.pulseStayOn();
}
void exp_load_Al::run(const GbE_msg& msg_in, GbE_msg& msg_out)
{
init_exp_sequence(msg_in, msg_out);
int deltaN1 = 0;
int deltaN2 = 0;
int deltaN3 = 0;
//stretch detection time
unsigned tOld = Detect.t;
Detect.t = static_cast<unsigned>(Detect.t * detection_stretch);
for (unsigned i = 0; i < num_exp; i++)
{
init_exp(i);
//provide some padding so that the processor gets a head start in
//filling the timing buffer
Padding.pulse();
run_exp_Bkg(i);
int n0 = pmt.get_new_data(1);
run_exp_MgCounts(i);
int n1 = pmt.get_new_data(1, false);
run_exp_MgCountsNoRF(i);
int n2 = pmt.get_new_data(1, false);
run_exp_MgCountsRF(i);
int n3 = pmt.get_new_data(1, false);
deltaN1 += (n1 - n0);
deltaN2 += (n2 - n0);
deltaN3 += (n3 - n0);
if (bDebugPulses)
{
sprintf(host->buffDebug, "Finish pulse sequence for experiment: %s\n\n\n", name.c_str());
host->sendDebugMsg(host->buffDebug, true);
}
bDebugPulses = false;
}
Detect.t = tOld;
rcMgCounts.result = ((double)deltaN1) / ((double)num_exp);
rcMgCountsNoRF.result = ((double)deltaN2) / ((double)num_exp);
rcMgCountsRF.result = ((double)deltaN3) / ((double)num_exp);
finish_exp_sequence(msg_out);
}
void exp_load_Al::run_exp_Bkg(int)
{
Precool.ddsOff();
DopplerCool.pulse();
detectBkg();
Precool.pulseStayOn();
}
void exp_load_Al::run_exp_MgCounts(int)
{
Precool.ddsOff();
DopplerCool.pulse();
Detect.detection_pulse();
Precool.pulseStayOn();
}
void exp_load_Al::run_exp_MgCountsNoRF(int)
{
Precool.ddsOff();
DopplerCool.pulse();
Carrier90.pulse();
Detect.detection_pulse();
Precool.pulseStayOn();
}
void exp_load_Al::run_exp_MgCountsRF(int)
{
Precool.ddsOff();
DopplerCool.pulse();
Heat.pulse();
Carrier90.pulse();
Detect.detection_pulse();
Precool.pulseStayOn();
}
| [
"trosen@814e38a0-0077-4020-8740-4f49b76d3b44"
]
| [
[
[
1,
347
]
]
]
|
d1299b155ade8ef1b1f46d8813946265f18a6d1e | 028fdbf6e634601077cf5a93d8494ef8453c4bcd | /Shared/SelfExtractor.cpp | a7c4f10f21bb14d2ae8f244a30a0733fcfd6e294 | []
| no_license | csyfek/sdl-sparks.extractor | c2c0ac55d54f3b489bc04f394aba0bab20578623 | 575aa57f829fad8173260c6b4bf00f34688c3883 | refs/heads/master | 2020-04-19T05:33:14.234652 | 2009-10-29T17:04:09 | 2009-10-29T17:04:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,497 | cpp | /*************************************************************************************
*
* File: SelfExtracter.cpp
* Version: 1.0
*
* Author: James Spibey
* Date: 04/08/1999
* E-mail: [email protected]
*
* Implementation of the CSelfExtracter class
*
* You are free to use, distribute or modify this code
* as long as this header is not removed or modified.
*
*
*************************************************************************************/
#include "stdafx.h"
#include "SelfExtractor.h"
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
/*******************************************************************************
*
* Function: CSelfExtractor::CSelfExtractor
*
* Description:
* Default Constructor
*
* Parameters:
* None
*
* Return:
* None
*******************************************************************************/
CSelfExtractor::CSelfExtractor()
{
m_nFiles = 0;
m_nTOCSize = 0;
}
/*******************************************************************************
*
* Function: CSelfExtractor::~CSelfExtractor
*
* Description:
* Destructor
*
* Parameters:
* None
*
* Return:
* None
*******************************************************************************/
CSelfExtractor::~CSelfExtractor()
{
}
/*******************************************************************************
*
* Function: CSelfExtractor::Create
*
* Description:
* Creates the Self-extracting executable
*
* Parameters:
* CString ExtractorPath: Path to the Extractor Executable
* CString Filename: Filename of the Self Extracting Archive to create
* funcPtr pFn: Pointer to a user defined callback function
* void* UserData: User defined data to pass to the callback function
*
* Return:
* int: Error Code
* NOTHING_TO_DO - No files have been selected to be archived
* COPY_FAILED - Failed to copy the extractor
* OUTPUT_FILE_ERROR - Failed to open the copied file for appending
* INPUT_FILE_ERROR - Failed to open an input file
*******************************************************************************/
int CSelfExtractor::Create(CString ExtractorPath, CString Filename, funcPtr pFn /* = NULL */, void* userData /*=NULL*/)
{
//Make sure we have some files to add
if(m_nFiles < 1)
return NOTHING_TO_DO;
//Copy the extractor to the new archive
CShellFileOp shOp;
shOp.SetFlags(FOF_FILESONLY | FOF_NOCONFIRMATION | FOF_SILENT);
shOp.AddFile(SH_SRC_FILE, ExtractorPath);
shOp.AddFile(SH_DEST_FILE, Filename);
if(shOp.CopyFiles() != 0)
return COPY_FAILED;
//Open the archive
CFile file;
if(!file.Open(Filename, CFile::modeWrite))
return OUTPUT_FILE_ERROR;
else
{
//Start at the end of the archive
file.SeekToEnd();
CreateArchive(&file, pFn, userData);
//Close the archive
file.Close();
}
return SUCCESS;
}
/*******************************************************************************
*
* Function: CSelfExtractor::Create
*
* Description:
* Creates the Self-extracting executable from an extractor in resources.
* Simply import the exe into your resources, making sure you specify the type
* as "SFX_EXE". Then just past the resource ID as the first parameter
*
* Parameters:
* UINT resource: Resource ID (eg IDR_SFX_EXE)
* CString Filename: Filename of the Self Extracting Archive to create
* funcPtr pFn: Pointer to a user defined callback function
* void* UserData: User defined data to pass to the callback function
*
* Return:
* int: Error Code
* NOTHING_TO_DO - No files have been selected to be archived
* COPY_FAILED - Failed to copy the extractor
* OUTPUT_FILE_ERROR - Failed to open the copied file for appending
* INPUT_FILE_ERROR - Failed to open an input file
*******************************************************************************/
int CSelfExtractor::Create(UINT resource, CString Filename, funcPtr pFn /* = NULL */, void* userData /*=NULL*/)
{
//Make sure we have some files to add
if(m_nFiles < 1)
return NOTHING_TO_DO;
//Load the extractor from resources
HRSRC hrSrc = FindResource(AfxGetResourceHandle(), MAKEINTRESOURCE(resource), "SFX_EXE");
if(hrSrc == NULL)
return RESOURCE_ERROR;
HGLOBAL hGlobal = LoadResource(AfxGetResourceHandle(), hrSrc);
if(hGlobal == NULL)
return RESOURCE_ERROR;
LPVOID lpExe = LockResource(hGlobal);
if(lpExe == NULL)
return RESOURCE_ERROR;
//Create the new archive from the extractor in the resources
CFile file;
if(!file.Open(Filename, CFile::modeCreate | CFile::modeWrite))
return OUTPUT_FILE_ERROR;
else
{
//Write the extractor exe
file.Write(lpExe, (UINT)SizeofResource(AfxGetResourceHandle(), hrSrc));
//Do the rest
CreateArchive(&file, pFn, userData);
//Close the archive
file.Close();
}
return SUCCESS;
}
int CSelfExtractor::CreateArchive(CFile* pFile, funcPtr pFn, void* userData)
{
DWORD dwRead = 0; //Total Data read from input file
DWORD dw = 0; //Last amount read from input file
char buffer[1000]; //Buffer for data
CFile data; //Input file
try
{
//Copy all the inout files into the archive
for(int i = 0; i < m_nFiles; i++)
{
//Open the input file
if(data.Open(m_InfoArray[i].GetPathname(), CFile::modeRead))
{
dwRead = 0;
m_InfoArray[i].SetOffset(pFile->GetPosition());
//Read data in and write it out until the end of file
while(static_cast<int>(dwRead) < m_InfoArray[i].GetFileSize())
{
dw = data.Read(buffer, 1000);
pFile->Write(buffer, dw);
dwRead += dw;
}
//Close this input file
data.Close();
//Call the user defined CallBack
if(pFn != NULL)
pFn(static_cast<void*>(&m_InfoArray[i]), userData);
}
else
return INPUT_FILE_ERROR;
}
//Now Write the TOC
for(int j = 0; j < m_nFiles; j++)
{
//Write the File Size
int Offset = m_InfoArray[j].GetFileOffset();
pFile->Write(&Offset, sizeof(int));
//Write the File Size
int len = m_InfoArray[j].GetFileSize();
pFile->Write(&len, sizeof(int));
//Write the filename
len = m_InfoArray[j].GetFilename().GetLength();
strncpy(buffer, m_InfoArray[j].GetFilename(), len);
pFile->Write(buffer, len);
//Write the length of the filename
pFile->Write(&len, sizeof(int));
}
//Write the total number of files
pFile->Write((void*)&m_nFiles, sizeof(int));
//Write the SIG
strcpy(buffer, SIGNATURE);
pFile->Write(buffer, strlen(SIGNATURE));
}
catch(CFileException* e)
{
//Got sick of seeing 'unreferenced local variable'
e->m_cause;
return OUTPUT_FILE_ERROR;
}
}
/*******************************************************************************
*
* Function: CSelfExtractor::ExtractAll
*
* Description:
* Extract the current archive to the specified directory
*
* Parameters:
* CString Dir: Destination Directory
* funcPtr pFn: Pointer to a user defined callback function
* void* UserData: User defined data to pass to the callback function
*
* Return:
* int: Error Code
* INPUT_FILE_ERROR - Failed to open the input file
* OUTPUT_FILE_ERROR - Failed to create an output file
*******************************************************************************/
int CSelfExtractor::ExtractAll(CString Dir, funcPtr pFn /*= NULL*/, void * userData /*= NULL*/)
{
//Make sure the directory name has a trailing backslash
EnsureTrailingBackSlash(Dir);
CFile Thisfile; //Archive (Usually itself)
//Read the Table of Contents
int res = ReadTOC(GetThisFileName());
if(res != SUCCESS)
return res;
//Open the archive
if(!Thisfile.Open(GetThisFileName(), CFile::modeRead))
return INPUT_FILE_ERROR;
else
{
//Get the files out in reverse order so we can work out the offsets
//Subtract 1 from the filecount as we are zero-based
for(int i = (m_nFiles - 1); i >= 0 ; i--)
{
ExtractOne(&Thisfile, i, Dir);
//Do the callback
if(pFn != NULL)
pFn(static_cast<void*>(&m_InfoArray[i]), userData);
}
//Close the archive
Thisfile.Close();
}
return SUCCESS;
}
/*******************************************************************************
*
* Function: CSelfExtractor::Extract
*
* Description:
* Extract a single file from the current archive to the specified directory
*
* Parameters:
* int index: index in array of file
* CString Dir: Destination Directory
*
* Return:
* int: Error Code
* INPUT_FILE_ERROR - Failed to open the input file
* OUTPUT_FILE_ERROR - Failed to create an output file
*******************************************************************************/
int CSelfExtractor::Extract(int index, CString Dir)
{
//Make sure the directory name has a trailing backslash
EnsureTrailingBackSlash(Dir);
CFile Thisfile; //Archive (Usually itself)
//Read the Table of Contents
int res = ReadTOC(GetThisFileName());
if(res != SUCCESS)
return res;
//Open the archive
if(!Thisfile.Open(GetThisFileName(), CFile::modeRead))
return INPUT_FILE_ERROR;
else
{
ExtractOne(&Thisfile, index, Dir);
//Close the archive
Thisfile.Close();
}
return SUCCESS;
}
/*******************************************************************************
*
* Function: CSelfExtractor::ExtractOne
*
* Description:
* Actual Data Extraction. Seeks to required offset in archive
* and writes new file
*
* Parameters:
* CFile* file: Pointer to the archive
* int index: Index of file in array
* CString Dir: Destination Dir
*
* Return:
* int: Error Code
*******************************************************************************/
int CSelfExtractor::ExtractOne(CFile* file, int index, CString Dir)
{
char buffer[1000]; //Buffer to read and write with
CFile NewFile; //Extracted File
//Get the file size (in bytes)
int FileSize = m_InfoArray[index].GetFileSize();
//Create the new file
if(!NewFile.Open(Dir + m_InfoArray[index].GetFilename() , CFile::modeCreate | CFile::modeWrite))
return OUTPUT_FILE_ERROR;
//Seek to the correct Offset
file->Seek(m_InfoArray[index].GetFileOffset(), CFile::begin);
//Loop the data out from the archive
DWORD dwWritten = 0;
DWORD dwRead = 0;
int AmountToRead = 0;
while(TRUE)
{
//Read out 1000 bytes at a time or the remainder if
//there is less than 1000 left. Exit if there is none left
AmountToRead = FileSize - dwWritten;
if(AmountToRead > 1000)
AmountToRead = 1000;
else if(AmountToRead == 0)
break;
dwRead = file->Read(buffer, AmountToRead);
NewFile.Write(buffer, dwRead);
dwWritten += dwRead;
}
//Close the output file
NewFile.Close();
return SUCCESS;
}
/*******************************************************************************
*
* Function: CSelfExtractor::ReadTOC
*
* Description:
* Read the archive's Table of Contents
*
* Parameters:
* CString Filename: Filename of the archive (full path)
*
* Return:
* int: Error Code
*******************************************************************************/
int CSelfExtractor::ReadTOC(CString Filename)
{
CFile Thisfile; //Archive file
char buffer[1000]; //Buffer to read and write with
//Clear the CSEFileInfo class array
Reset();
//Open the archive
if(!Thisfile.Open(Filename, CFile::modeRead))
return NO_SOURCE;
else
{
//Read in the signature
Thisfile.Seek(- static_cast<int>(strlen(SIGNATURE)), CFile::end);
Thisfile.Read(buffer, strlen(SIGNATURE));
//Check that it matches
if(strncmp(buffer, SIGNATURE, strlen(SIGNATURE)) != 0)
return INVALID_SIG;
else
{
//Read Number of files
int LastOffset = strlen(SIGNATURE) + static_cast<int>(sizeof(int));
Thisfile.Seek(-LastOffset, CFile::end);
Thisfile.Read(&m_nFiles, sizeof(int));
//If there are no files in the archive, there is nothing to extract
if(m_nFiles == 0)
return NOTHING_TO_DO;
//Read the TOC in. The array is filled in reverse to ensure that it
//corresponds to the data segment
for(int i = (m_nFiles - 1); i >= 0 ; i--)
{
int nSize = 0;
int nOffset = 0;
int len = 0;
LastOffset += sizeof(int);
//Get Length of Pathname
Thisfile.Seek(-LastOffset, CFile::end);
Thisfile.Read(&len, sizeof(int));
LastOffset += len;
//Get Path Name
Thisfile.Seek(-LastOffset, CFile::end);
Thisfile.Read(buffer, len);
LastOffset += sizeof(int);
//Get File Size
Thisfile.Seek(-LastOffset, CFile::end);
Thisfile.Read(&nSize, sizeof(int));
LastOffset += sizeof(int);
//Get File Offset
Thisfile.Seek(-LastOffset, CFile::end);
Thisfile.Read(&nOffset, sizeof(int));
//Set the data in the array
m_InfoArray[i].SetSize(nSize);
CString Temp(buffer);
m_InfoArray[i].SetFilename(Temp.Left(len));
m_InfoArray[i].SetOffset(nOffset);
}
//Record the total size of the TOC for use
//when extracting the data segment
m_nTOCSize = LastOffset;
}
}
//Close the archive
Thisfile.Close();
return SUCCESS;
}
/*******************************************************************************
*
* Function: CSelfExtractor::AddFile
*
* Description:
* Add a file to the archive
*
* Parameters:
* CString File: Input File path
*
* Return:
* BOOL: Success or Failure
*******************************************************************************/
BOOL CSelfExtractor::AddFile(CString File)
{
if(m_nFiles == MAX_FILES)
return FALSE;
if(m_InfoArray[m_nFiles].SetData(File))
{
m_nFiles++;
return TRUE;
}
return FALSE;
}
/*******************************************************************************
*
* Function: CSelfExtractor::Reset
*
* Description:
* Reset the CSEFileInfo Array
*
* Parameters:
* None
*
* Return:
* None
*******************************************************************************/
void CSelfExtractor::Reset()
{
for(int i = 0; i < MAX_FILES; i++)
m_InfoArray[i].Reset();
m_nFiles = 0;
m_nTOCSize = 0;
}
/*******************************************************************************
*
* Function: CSelfExtractor::EnsureTrailingBackSlash
*
* Description:
* Ensure that the string has a trailing backslash
*
* Parameters:
* CString &string: Pathname
*
* Return:
* CString: Pathname
*******************************************************************************/
CString CSelfExtractor::EnsureTrailingBackSlash(CString &string)
{
int len = string.GetLength();
if(string[len - 1] != '\\')
string += "\\";
return string;
}
/*******************************************************************************
*
* Function: CSelfExtractor::GetThisFileName
*
* Description:
* Get this executable's file path
*
* Parameters:
* None
*
* Return:
* CString: Full Path for this executable
*******************************************************************************/
CString CSelfExtractor::GetThisFileName()
{
char FullName[MAX_PATH+1];
GetModuleFileName(NULL,FullName,MAX_PATH);
return CString(FullName);
}
| [
"lonicerae(at)gmail.com@localhost"
]
| [
[
[
1,
573
]
]
]
|
59ee86e69d193462f701a7ca2864c53d09edc901 | cd0987589d3815de1dea8529a7705caac479e7e9 | /webkit/WebKit2/WebProcess/WebPage/win/WebPageWin.cpp | e40a11600de5df4240bdae160d1d6c259fb13615 | []
| no_license | azrul2202/WebKit-Smartphone | 0aab1ff641d74f15c0623f00c56806dbc9b59fc1 | 023d6fe819445369134dee793b69de36748e71d7 | refs/heads/master | 2021-01-15T09:24:31.288774 | 2011-07-11T11:12:44 | 2011-07-11T11:12:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,006 | cpp | /*
* Copyright (C) 2010 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "WebPage.h"
#include "FontSmoothingLevel.h"
#include "WebEvent.h"
#include "WebPreferencesStore.h"
#include <WebCore/FocusController.h>
#include <WebCore/FontRenderingMode.h>
#include <WebCore/Frame.h>
#include <WebCore/KeyboardEvent.h>
#include <WebCore/Page.h>
#include <WebCore/PlatformKeyboardEvent.h>
#include <WebCore/Settings.h>
#if PLATFORM(CG)
#include <WebKitSystemInterface/WebKitSystemInterface.h>
#endif
#include <WinUser.h>
using namespace WebCore;
namespace WebKit {
void WebPage::platformInitialize()
{
m_page->settings()->setFontRenderingMode(AlternateRenderingMode);
}
void WebPage::platformPreferencesDidChange(const WebPreferencesStore& store)
{
#if PLATFORM(CG)
FontSmoothingLevel adjustedLevel = static_cast<FontSmoothingLevel>(store.fontSmoothingLevel);
if (adjustedLevel == FontSmoothingLevelWindows)
adjustedLevel = FontSmoothingLevelMedium;
wkSetFontSmoothingLevel(adjustedLevel);
#endif
m_page->settings()->setFontRenderingMode(store.fontSmoothingLevel == FontSmoothingLevelWindows ? AlternateRenderingMode : NormalRenderingMode);
}
static const unsigned CtrlKey = 1 << 0;
static const unsigned AltKey = 1 << 1;
static const unsigned ShiftKey = 1 << 2;
struct KeyDownEntry {
unsigned virtualKey;
unsigned modifiers;
const char* name;
};
struct KeyPressEntry {
unsigned charCode;
unsigned modifiers;
const char* name;
};
static const KeyDownEntry keyDownEntries[] = {
{ VK_LEFT, 0, "MoveLeft" },
{ VK_LEFT, ShiftKey, "MoveLeftAndModifySelection" },
{ VK_LEFT, CtrlKey, "MoveWordLeft" },
{ VK_LEFT, CtrlKey | ShiftKey, "MoveWordLeftAndModifySelection" },
{ VK_RIGHT, 0, "MoveRight" },
{ VK_RIGHT, ShiftKey, "MoveRightAndModifySelection" },
{ VK_RIGHT, CtrlKey, "MoveWordRight" },
{ VK_RIGHT, CtrlKey | ShiftKey, "MoveWordRightAndModifySelection" },
{ VK_UP, 0, "MoveUp" },
{ VK_UP, ShiftKey, "MoveUpAndModifySelection" },
{ VK_PRIOR, ShiftKey, "MovePageUpAndModifySelection" },
{ VK_DOWN, 0, "MoveDown" },
{ VK_DOWN, ShiftKey, "MoveDownAndModifySelection" },
{ VK_NEXT, ShiftKey, "MovePageDownAndModifySelection" },
{ VK_PRIOR, 0, "MovePageUp" },
{ VK_NEXT, 0, "MovePageDown" },
{ VK_HOME, 0, "MoveToBeginningOfLine" },
{ VK_HOME, ShiftKey, "MoveToBeginningOfLineAndModifySelection" },
{ VK_HOME, CtrlKey, "MoveToBeginningOfDocument" },
{ VK_HOME, CtrlKey | ShiftKey, "MoveToBeginningOfDocumentAndModifySelection" },
{ VK_END, 0, "MoveToEndOfLine" },
{ VK_END, ShiftKey, "MoveToEndOfLineAndModifySelection" },
{ VK_END, CtrlKey, "MoveToEndOfDocument" },
{ VK_END, CtrlKey | ShiftKey, "MoveToEndOfDocumentAndModifySelection" },
{ VK_BACK, 0, "DeleteBackward" },
{ VK_BACK, ShiftKey, "DeleteBackward" },
{ VK_DELETE, 0, "DeleteForward" },
{ VK_BACK, CtrlKey, "DeleteWordBackward" },
{ VK_DELETE, CtrlKey, "DeleteWordForward" },
{ 'B', CtrlKey, "ToggleBold" },
{ 'I', CtrlKey, "ToggleItalic" },
{ VK_ESCAPE, 0, "Cancel" },
{ VK_OEM_PERIOD, CtrlKey, "Cancel" },
{ VK_TAB, 0, "InsertTab" },
{ VK_TAB, ShiftKey, "InsertBacktab" },
{ VK_RETURN, 0, "InsertNewline" },
{ VK_RETURN, CtrlKey, "InsertNewline" },
{ VK_RETURN, AltKey, "InsertNewline" },
{ VK_RETURN, ShiftKey, "InsertNewline" },
{ VK_RETURN, AltKey | ShiftKey, "InsertNewline" },
// It's not quite clear whether clipboard shortcuts and Undo/Redo should be handled
// in the application or in WebKit. We chose WebKit.
{ 'C', CtrlKey, "Copy" },
{ 'V', CtrlKey, "Paste" },
{ 'X', CtrlKey, "Cut" },
{ 'A', CtrlKey, "SelectAll" },
{ VK_INSERT, CtrlKey, "Copy" },
{ VK_DELETE, ShiftKey, "Cut" },
{ VK_INSERT, ShiftKey, "Paste" },
{ 'Z', CtrlKey, "Undo" },
{ 'Z', CtrlKey | ShiftKey, "Redo" },
};
static const KeyPressEntry keyPressEntries[] = {
{ '\t', 0, "InsertTab" },
{ '\t', ShiftKey, "InsertBacktab" },
{ '\r', 0, "InsertNewline" },
{ '\r', CtrlKey, "InsertNewline" },
{ '\r', AltKey, "InsertNewline" },
{ '\r', ShiftKey, "InsertNewline" },
{ '\r', AltKey | ShiftKey, "InsertNewline" },
};
const char* WebPage::interpretKeyEvent(const KeyboardEvent* evt)
{
ASSERT(evt->type() == eventNames().keydownEvent || evt->type() == eventNames().keypressEvent);
static HashMap<int, const char*>* keyDownCommandsMap = 0;
static HashMap<int, const char*>* keyPressCommandsMap = 0;
if (!keyDownCommandsMap) {
keyDownCommandsMap = new HashMap<int, const char*>;
keyPressCommandsMap = new HashMap<int, const char*>;
for (unsigned i = 0; i < _countof(keyDownEntries); i++)
keyDownCommandsMap->set(keyDownEntries[i].modifiers << 16 | keyDownEntries[i].virtualKey, keyDownEntries[i].name);
for (unsigned i = 0; i < _countof(keyPressEntries); i++)
keyPressCommandsMap->set(keyPressEntries[i].modifiers << 16 | keyPressEntries[i].charCode, keyPressEntries[i].name);
}
unsigned modifiers = 0;
if (evt->shiftKey())
modifiers |= ShiftKey;
if (evt->altKey())
modifiers |= AltKey;
if (evt->ctrlKey())
modifiers |= CtrlKey;
if (evt->type() == eventNames().keydownEvent) {
int mapKey = modifiers << 16 | evt->keyCode();
return mapKey ? keyDownCommandsMap->get(mapKey) : 0;
}
int mapKey = modifiers << 16 | evt->charCode();
return mapKey ? keyPressCommandsMap->get(mapKey) : 0;
}
static inline void scroll(Page* page, ScrollDirection direction, ScrollGranularity granularity)
{
page->focusController()->focusedOrMainFrame()->eventHandler()->scrollRecursively(direction, granularity);
}
bool WebPage::performDefaultBehaviorForKeyEvent(const WebKeyboardEvent& keyboardEvent)
{
if (keyboardEvent.type() != WebEvent::KeyDown && keyboardEvent.type() != WebEvent::RawKeyDown)
return false;
switch (keyboardEvent.windowsVirtualKeyCode()) {
case VK_BACK:
if (keyboardEvent.shiftKey())
m_page->goForward();
else
m_page->goBack();
break;
case VK_SPACE:
if (keyboardEvent.shiftKey())
scroll(m_page.get(), ScrollUp, ScrollByPage);
else
scroll(m_page.get(), ScrollDown, ScrollByPage);
break;
case VK_LEFT:
scroll(m_page.get(), ScrollLeft, ScrollByLine);
break;
case VK_RIGHT:
scroll(m_page.get(), ScrollRight, ScrollByLine);
break;
case VK_UP:
scroll(m_page.get(), ScrollUp, ScrollByLine);
break;
case VK_DOWN:
scroll(m_page.get(), ScrollDown, ScrollByLine);
break;
case VK_HOME:
scroll(m_page.get(), ScrollUp, ScrollByDocument);
break;
case VK_END:
scroll(m_page.get(), ScrollDown, ScrollByDocument);
break;
case VK_PRIOR:
scroll(m_page.get(), ScrollUp, ScrollByPage);
break;
case VK_NEXT:
scroll(m_page.get(), ScrollDown, ScrollByPage);
break;
default:
return false;
}
return true;
}
} // namespace WebKit
| [
"[email protected]"
]
| [
[
[
1,
238
]
]
]
|
36ae6733eff1424e15c02972aa23b4e2df13b916 | 83ed25c6e6b33b2fabd4f81bf91d5fae9e18519c | /code/BlenderLoader.h | 5289a3a57a57461bbf8398f1077d5059ee75ed41 | [
"BSD-3-Clause"
]
| permissive | spring/assimp | fb53b91228843f7677fe8ec18b61d7b5886a6fd3 | db29c9a20d0dfa9f98c8fd473824bba5a895ae9e | refs/heads/master | 2021-01-17T23:19:56.511185 | 2011-11-08T12:15:18 | 2011-11-08T12:15:18 | 2,017,841 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,688 | h | /*
Open Asset Import Library (ASSIMP)
----------------------------------------------------------------------
Copyright (c) 2006-2010, ASSIMP Development Team
All rights reserved.
Redistribution and use of this software 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 ASSIMP team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the ASSIMP Development Team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
/** @file BlenderLoader.h
* @brief Declaration of the Blender 3D (*.blend) importer class.
*/
#ifndef INCLUDED_AI_BLEND_LOADER_H
#define INCLUDED_AI_BLEND_LOADER_H
#include "BaseImporter.h"
#include "LogAux.h"
namespace Assimp {
// TinyFormatter.h
namespace Formatter {
template <typename T,typename TR, typename A> class basic_formatter;
typedef class basic_formatter< char, std::char_traits<char>, std::allocator<char> > format;
}
// BlenderDNA.h
namespace Blender {
class FileDatabase;
struct ElemBase;
}
// BlenderScene.h
namespace Blender {
struct Scene;
struct Object;
struct Mesh;
struct Camera;
struct Lamp;
struct MTex;
struct Image;
struct Material;
}
// BlenderIntermediate.h
namespace Blender {
struct ConversionData;
template <template <typename,typename> class TCLASS, typename T> struct TempArray;
}
// BlenderModifier.h
namespace Blender {
class BlenderModifierShowcase;
class BlenderModifier;
}
enum aiLoaderFlags
{
aiLoaderFlags_SupportAsciiFlavour = 0x1,
aiLoaderFlags_SupportBinaryFlavour = 0x2,
aiLoaderFlags_SupportCompressedFlavour = 0x4,
aiLoaderFlags_LimitedSupport = 0x8,
aiLoaderFlags_Experimental = 0x10,
aiLoaderFlags_Testing = 0x20,
aiLoaderFlags_Production = 0x40,
};
struct aiLoaderDesc
{
const char* mName;
const char* mAuthor;
const char* mMaintainer;
const char* mComments;
unsigned int mFlags;
unsigned int mMinMajor;
unsigned int mMinMinor;
unsigned int mMaxMajor;
unsigned int mMaxMinor;
};
// -------------------------------------------------------------------------------------------
/** Load blenders official binary format. The actual file structure (the `DNA` how they
* call it is outsourced to BlenderDNA.cpp/BlenderDNA.h. This class only performs the
* conversion from intermediate format to aiScene. */
// -------------------------------------------------------------------------------------------
class BlenderImporter : public BaseImporter, public LogFunctions<BlenderImporter>
{
public:
BlenderImporter();
~BlenderImporter();
public:
// --------------------
bool CanRead( const std::string& pFile,
IOSystem* pIOHandler,
bool checkSig
) const;
protected:
// --------------------
const aiLoaderDesc& GetInfo () const;
// --------------------
void GetExtensionList(std::set<std::string>& app);
// --------------------
void SetupProperties(const Importer* pImp);
// --------------------
void InternReadFile( const std::string& pFile,
aiScene* pScene,
IOSystem* pIOHandler
);
// --------------------
void ParseBlendFile(Blender::FileDatabase& out,
boost::shared_ptr<IOStream> stream
);
// --------------------
void ExtractScene(Blender::Scene& out,
const Blender::FileDatabase& file
);
// --------------------
void ConvertBlendFile(aiScene* out,
const Blender::Scene& in,
const Blender::FileDatabase& file
);
private:
// --------------------
aiNode* ConvertNode(const Blender::Scene& in,
const Blender::Object* obj,
Blender::ConversionData& conv_info
);
// --------------------
void ConvertMesh(const Blender::Scene& in,
const Blender::Object* obj,
const Blender::Mesh* mesh,
Blender::ConversionData& conv_data,
Blender::TempArray<std::vector,aiMesh>& temp
);
// --------------------
aiLight* ConvertLight(const Blender::Scene& in,
const Blender::Object* obj,
const Blender::Lamp* mesh,
Blender::ConversionData& conv_data
);
// --------------------
aiCamera* ConvertCamera(const Blender::Scene& in,
const Blender::Object* obj,
const Blender::Camera* mesh,
Blender::ConversionData& conv_data
);
// --------------------
void BuildMaterials(
Blender::ConversionData& conv_data
) ;
// --------------------
void ResolveTexture(
aiMaterial* out,
const Blender::Material* mat,
const Blender::MTex* tex,
Blender::ConversionData& conv_data
);
// --------------------
void ResolveImage(
aiMaterial* out,
const Blender::Material* mat,
const Blender::MTex* tex,
const Blender::Image* img,
Blender::ConversionData& conv_data
);
void AddSentinelTexture(
aiMaterial* out,
const Blender::Material* mat,
const Blender::MTex* tex,
Blender::ConversionData& conv_data
);
private: // static stuff, mostly logging and error reporting.
// --------------------
static void CheckActualType(const Blender::ElemBase* dt,
const char* check
);
// --------------------
static void NotSupportedObjectType(const Blender::Object* obj,
const char* type
);
private:
Blender::BlenderModifierShowcase* modifier_cache;
}; // !class BlenderImporter
} // end of namespace Assimp
#endif // AI_UNREALIMPORTER_H_INC
| [
"aramis_acg@67173fc5-114c-0410-ac8e-9d2fd5bffc1f"
]
| [
[
[
1,
248
]
]
]
|
1d5359bc0bb0310cb1a3034798c9e677051b27ea | a09f709362521d701c08b2cdc6433c956f8815c9 | /tests/compile_outputastree/liba/treea/treeb/deepfile.cpp | 94f28b6d15a29a1c72abe3a20250df9fa13524cc | []
| no_license | alenl/jamplus | 0eab8a5f8cd895804354b0cac844a0849549c3f6 | 5393a9b2f2467667b33fca542826498ce8ff2971 | refs/heads/master | 2021-01-18T10:29:38.604732 | 2008-11-20T20:48:04 | 2008-11-20T21:30:27 | 77,247 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 45 | cpp | int Add(int x, int y)
{
return x + y;
}
| [
"[email protected]"
]
| [
[
[
1,
4
]
]
]
|
7f7f6ff78fbd1877faa83d59cd802d2ab0bb60e6 | 28b097d96e87de603d75faf24e56394ac16d239f | /logger/myIDDraw2.cpp | 9ae23e012367d40281579fa83e2ed93088d25661 | []
| no_license | RazorbladeByte/ddhack | ecfe5845c24110daf5a89d6937612f5243bc9883 | b564e26ad89e112426a0c08e12040eef130bf826 | refs/heads/master | 2016-09-11T02:41:34.702359 | 2011-08-17T13:58:14 | 2011-08-17T13:58:14 | 2,220,900 | 9 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 5,520 | cpp | #include "StdAfx.h"
#include <varargs.h>
myIDDraw2::myIDDraw2(LPDIRECTDRAW2 pOriginal)
{
logf(this, "myIDDraw2 Constructor");
m_pIDDraw = pOriginal;
}
myIDDraw2::~myIDDraw2(void)
{
logf(this, "myIDDraw2 Destructor");
}
HRESULT __stdcall myIDDraw2::QueryInterface (REFIID a, LPVOID FAR * b)
{
char *iid = "?";
if (a == IID_IDirectDraw) iid = "IID_IDirectDraw";
if (a == IID_IDirectDraw2) iid = "IID_IDirectDraw2";
if (a == IID_IDirectDraw4) iid = "IID_IDirectDraw4";
if (a == IID_IDirectDraw7) iid = "IID_IDirectDraw7";
logf(this, "myIDDraw2::QueryInterface(%s,%08x)",iid,b);
*b = NULL;
// call this to increase AddRef at original object
// and to check if such an interface is there
HRESULT hRes = m_pIDDraw->QueryInterface(a, b);
if (hRes == NOERROR) // if OK, send our "fake" address
{
if (a == IID_IDirectDraw2)
*b = this;
}
return hRes;
}
ULONG __stdcall myIDDraw2::AddRef(void)
{
logf(this, "myIDDraw2::AddRef");
return(m_pIDDraw->AddRef());
}
ULONG __stdcall myIDDraw2::Release(void)
{
logf(this, "myIDDraw2::Release");
// call original routine
ULONG count = m_pIDDraw->Release();
logf(this, "Object Release.");
// in case no further Ref is there, the Original Object has deleted itself
// so do we here
if (count == 0)
{
m_pIDDraw = NULL;
delete(this);
}
return(count);
}
HRESULT __stdcall myIDDraw2::Compact(void)
{
logf(this, "myIDDraw2::Compact");
return(m_pIDDraw->Compact());
}
HRESULT __stdcall myIDDraw2::CreateClipper(DWORD a, LPDIRECTDRAWCLIPPER FAR* b, IUnknown FAR* c)
{
logf(this, "myIDDraw2::CreateClipper");
return(m_pIDDraw->CreateClipper(a, b, c));
}
HRESULT __stdcall myIDDraw2::CreatePalette(DWORD a, LPPALETTEENTRY b, LPDIRECTDRAWPALETTE FAR* c, IUnknown FAR* d)
{
HRESULT r = m_pIDDraw->CreatePalette(a, b, c, d);
*c = new myIDDrawPalette(*c);
logf(this, "myIDDraw2::CreatePalette(%d,%08x,%08x,%08x) return %d",a,b,c,d,r);
return r;
}
HRESULT __stdcall myIDDraw2::CreateSurface(LPDDSURFACEDESC a, LPDIRECTDRAWSURFACE FAR* b, IUnknown FAR* c)
{
HRESULT r = m_pIDDraw->CreateSurface(a, b, c);
logf(this, "myIDDraw2::CreateSurface([%d,0x%x,%d,%d,%d,%d,%d], %08x, %08x) return %d", a->dwSize, a->dwFlags, a->dwWidth, a->dwHeight, a->lPitch, a->dwBackBufferCount, a->ddsCaps, b, c, r);
*b = new myIDDrawSurface1(*b);
return r;
}
HRESULT __stdcall myIDDraw2::DuplicateSurface(LPDIRECTDRAWSURFACE a, LPDIRECTDRAWSURFACE FAR* b)
{
logf(this, "myIDDraw2::DuplicateSurface");
return(m_pIDDraw->DuplicateSurface(a, b));
}
HRESULT __stdcall myIDDraw2::EnumDisplayModes(DWORD a, LPDDSURFACEDESC b, LPVOID c, LPDDENUMMODESCALLBACK d)
{
logf(this, "myIDDraw2::EnumDisplayModes");
return(m_pIDDraw->EnumDisplayModes(a, b, c, d));
}
HRESULT __stdcall myIDDraw2::EnumSurfaces(DWORD a, LPDDSURFACEDESC b, LPVOID c, LPDDENUMSURFACESCALLBACK d)
{
logf(this, "myIDDraw2::EnumSurfaces");
return(m_pIDDraw->EnumSurfaces(a, b, c, d));
}
HRESULT __stdcall myIDDraw2::FlipToGDISurface(void)
{
logf(this, "myIDDraw2::FlipToGDISurface");
return(m_pIDDraw->FlipToGDISurface());
}
HRESULT __stdcall myIDDraw2::GetCaps(LPDDCAPS a, LPDDCAPS b)
{
logf(this, "myIDDraw2::GetCaps");
return(m_pIDDraw->GetCaps(a, b));
}
HRESULT __stdcall myIDDraw2::GetDisplayMode(LPDDSURFACEDESC a)
{
logf(this, "myIDDraw2::GetDisplayMode");
return(m_pIDDraw->GetDisplayMode(a));
}
HRESULT __stdcall myIDDraw2::GetFourCCCodes(LPDWORD a, LPDWORD b)
{
logf(this, "myIDDraw2::GetFourCCCodes");
return(m_pIDDraw->GetFourCCCodes(a, b));
}
HRESULT __stdcall myIDDraw2::GetGDISurface(LPDIRECTDRAWSURFACE FAR * a)
{
logf(this, "myIDDraw2::GetGDISurface");
return(m_pIDDraw->GetGDISurface(a));
}
HRESULT __stdcall myIDDraw2::GetMonitorFrequency(LPDWORD a)
{
logf(this, "myIDDraw2::GetMonitorFrequency");
return(m_pIDDraw->GetMonitorFrequency(a));
}
HRESULT __stdcall myIDDraw2::GetScanLine(LPDWORD a)
{
logf(this, "myIDDraw2::GetScanLine");
return(m_pIDDraw->GetScanLine(a));
}
HRESULT __stdcall myIDDraw2::GetVerticalBlankStatus(LPBOOL a)
{
logf(this, "myIDDraw2::GetVerticalBlankStatus");
return(m_pIDDraw->GetVerticalBlankStatus(a));
}
HRESULT __stdcall myIDDraw2::Initialize(GUID FAR* a)
{
logf(this, "myIDDraw2::Initialize");
return(m_pIDDraw->Initialize(a));
}
HRESULT __stdcall myIDDraw2::RestoreDisplayMode(void)
{
logf(this, "myIDDraw2::RestoreDisplayMode");
return(m_pIDDraw->RestoreDisplayMode());
}
HRESULT __stdcall myIDDraw2::SetCooperativeLevel(HWND a, DWORD b)
{
HRESULT h = m_pIDDraw->SetCooperativeLevel(a, b);
logf(this, "myIDDraw2::SetCooperativeLevel(%08x, %d) return %d", a, b, h);
return(h);
}
HRESULT __stdcall myIDDraw2::SetDisplayMode(DWORD a, DWORD b, DWORD c, DWORD d, DWORD e)
{
HRESULT h = m_pIDDraw->SetDisplayMode(a, b, c, d, e);
logf(this, "myIDDraw2::SetDisplayMode(%d, %d, %d, %d, %d) return %d",a,b,c,d,e,h);
return(h);
}
HRESULT __stdcall myIDDraw2::WaitForVerticalBlank(DWORD a, HANDLE b)
{
logf(this, "myIDDraw2::WaitForVerticalBlank(%d,%d)",a,b);
return(m_pIDDraw->WaitForVerticalBlank(a, b));
}
HRESULT __stdcall myIDDraw2::GetAvailableVidMem(LPDDSCAPS a, LPDWORD b, LPDWORD c)
{
logf(this, "myIDDraw2::GetAvailableVidMem");
return(m_pIDDraw->GetAvailableVidMem(a, b, c));
}
| [
"[email protected]@ca3b60c3-ba86-2864-2f26-32acf34adade"
]
| [
[
[
1,
235
]
]
]
|
9eae284bfbe98e132861e28b09b2c89f644983e8 | 2112057af069a78e75adfd244a3f5b224fbab321 | /branches/refactor/src_root/include/ireon_rs/root_app.h | deec88c76d8c82632ffdbdd83c0aa118618c7765 | []
| no_license | blockspacer/ireon | 120bde79e39fb107c961697985a1fe4cb309bd81 | a89fa30b369a0b21661c992da2c4ec1087aac312 | refs/heads/master | 2023-04-15T00:22:02.905112 | 2010-01-07T20:31:07 | 2010-01-07T20:31:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,792 | h | /**
* @file root_app.h
* Contains application class for root server
*/
/* Copyright (C) 2005 ireon.org developers council
* $Id: root_app.h 433 2005-12-20 20:19:15Z zak $
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#ifndef _ROOT_APP_H
#define _ROOT_APP_H
#include "common/xmlconfig.h"
#include "common/generic_app.h"
class CRootIServer;
class CRootEServer;
class CConfig;
class CRootApp : private CGenericApp
{
public:
CRootApp();
~CRootApp();
///Initialize application
void init();
///Run application
void go();
///Get instance
static CRootApp* instance() {return m_singleton;}
///Find cluster in list
bool findCluster(const String& s);
CRootIServer* iserver() {return m_iserver;}
CRootEServer* eserver() {return m_eserver;}
void shutdown();
private:
static CRootApp* m_singleton;
///Cluster adresses
StringVector m_clusters;
CRootIServer* m_iserver;
CRootEServer* m_eserver;
// some utility functions
bool checkRequiredConfigOptions();
bool initInternalServer();
bool initExternalServer();
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
71
]
]
]
|
d74810800cd5ee2ac280ce53c4f91e1d05c9d1c4 | cdf231431217413f50c2f1193e56271a09e856ac | /计算机图形学/ParticleSystem/ParticlePattern/trackball.cpp | b31663b58077c9e7a2e8930057ed9895f6bec6c5 | []
| no_license | zinking/wz-graduate-project | 98ae89870f0d1557b12a449794480ead34f5fc46 | de60b4fd04c861a6cd03884d16fa50540e7c52a4 | refs/heads/master | 2016-09-05T21:40:50.946079 | 2009-07-24T11:39:32 | 2009-07-24T11:39:32 | 32,133,474 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 2,515 | cpp |
#include "trackball.h"
static quat curr, last;
Quaternion quaternion;
#define Radius R
CTrackBall::CTrackBall()
{
R = 0.8;
ROOT_2_INV = 0.70710678118654752440;
simulate_trackball( &curr, 0.0, 0.0, 0.0, 0.0 );
}
CTrackBall::~CTrackBall() {}
float CTrackBall::project_to_sphere( float x, float y )
{
float z;
float d_sqr, d;
d_sqr = SQR( x ) + SQR( y );
d = sqrt( d_sqr );
if( d < Radius )
{
z = sqrt( 2.0 * SQR( Radius ) - d_sqr );
}
else
{
z = SQR( Radius ) / d;
}
return z;
}
void CTrackBall::simulate_trackball( quat *q, float p1x, float p1y, float p2x, float p2y )
{
if( p1x == p2x && p1y == p2y )
{
quaternion.quat_identity( q );
}
else
{
quat p1, p2, a, d;
float p1z, p2z;
float s, t;
p1z = project_to_sphere( p1x, p1y );
quaternion.quat_assign( &p1, 0.0, p1x, p1y, p1z );
p2z = project_to_sphere( p2x, p2y );
quaternion.quat_assign( &p2, 0.0, p2x, p2y, p2z );
quaternion.quat_mul( &a, &p1, &p2 );
a.w = 0.0;
s = quaternion.quat_norm(&a);
quaternion.quat_div_real(&a, &a, s);
quaternion.quat_sub(&d, &p1, &p2);
t = quaternion.quat_norm(&d) / (2.0 * Radius * ROOT_2_INV);
if (t > 1.0) t = 1.0;
quaternion.quat_assign(q, cos(asin(t)), a.x * t, a.y * t, a.z * t);
}
}
void CTrackBall::create_rotation_matrix(float m[4][4])
{
const quat *q = &curr;//ËÄÔªÊý-¡·Ðýת¾ØÕó
m[0][0] = 1.0 - 2.0 * (q->y * q->y + q->z * q->z);
m[0][1] = 2.0 * (q->x * q->y - q->z * q->w);
m[0][2] = 2.0 * (q->z * q->x + q->w * q->y);
m[0][3] = 0.0;
m[1][0] = 2.0 * (q->x * q->y + q->z * q->w);
m[1][1] = 1.0 - 2.0 * (q->z * q->z + q->x * q->x);
m[1][2] = 2.0 * (q->y * q->z - q->w * q->x);
m[1][3] = 0.0;
m[2][0] = 2.0 * (q->z * q->x - q->w * q->y);
m[2][1] = 2.0 * (q->y * q->z + q->x * q->w);
m[2][2] = 1.0 - 2.0 * (q->y * q->y + q->x * q->x);
m[2][3] = 0.0;
m[3][0] = 0.0;
m[3][1] = 0.0;
m[3][2] = 0.0;
m[3][3] = 1.0;
}
void CTrackBall::motioni_to_trackball( int begin_x, int begin_y, int x, int y, int height, int width, int *count )
{
quat t;
simulate_trackball(&last, (2.0 * begin_x - width) / width,
(height - 2.0 * begin_y) / height,
(2.0 * x - width) / width,
(height - 2.0 * y) / height);
quaternion.quat_mul(&t, &last, &curr);
curr = t;
if (++count[0] % 97 == 0)
{
float n = quaternion.quat_norm(&curr);
quaternion.quat_div_real(&curr, &curr, n);
}
} | [
"zinking3@927cf1a0-783d-11de-8a01-315fa775be5f"
]
| [
[
[
1,
106
]
]
]
|
1e11495d8a082416e3a7769deb42a9689344ac78 | 5ac13fa1746046451f1989b5b8734f40d6445322 | /minimangalore/Nebula2/code/contrib/nbsptool/src/nbsptool/libs/jpeg/jerror.cc | 94409acba121ece9f9be1d3cb8267ed57d0e2385 | []
| 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 | 7,345 | cc | /*
* jerror.c
*
* Copyright (C) 1991-1994, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains simple error-reporting and trace-message routines.
* These are suitable for Unix-like systems and others where writing to
* stderr is the right thing to do. Many applications will want to replace
* some or all of these routines.
*
* These routines are used by both the compression and decompression code.
*/
/* this is not a core library module, so it doesn't define JPEG_INTERNALS */
#include "nbsptool/libs/jpeg/jinclude.h"
#include "nbsptool/libs/jpeg/jpeglib.h"
#include "nbsptool/libs/jpeg/jversion.h"
#include "nbsptool/libs/jpeg/jerror.h"
#ifndef EXIT_FAILURE /* define exit() codes if not provided */
#define EXIT_FAILURE 1
#endif
/*
* Create the message string table.
* We do this from the master message list in jerror.h by re-reading
* jerror.h with a suitable definition for macro JMESSAGE.
* The message table is made an external symbol just in case any applications
* want to refer to it directly.
*/
#ifdef NEED_SHORT_EXTERNAL_NAMES
#define jpeg_std_message_table jMsgTable
#endif
#define JMESSAGE(code,string) string ,
const char * const jpeg_std_message_table[] = {
#include "nbsptool/libs/jpeg/jerror.h"
NULL
};
// Rad additions, longjmp out of the LoadJPGBuff
GLOBAL jmp_buf rad_loadfailed;
GLOBAL char rad_errormsg[JMSG_LENGTH_MAX];
/*
* Error exit handler: must not return to caller.
*
* Applications may override this if they want to get control back after
* an error. Typically one would longjmp somewhere instead of exiting.
* The setjmp buffer can be made a private field within an expanded error
* handler object. Note that the info needed to generate an error message
* is stored in the error object, so you can generate the message now or
* later, at your convenience.
* You should make sure that the JPEG object is cleaned up (with jpeg_abort
* or jpeg_destroy) at some point.
*/
METHODDEF void
error_exit (j_common_ptr cinfo)
{
// char buffer[JMSG_LENGTH_MAX];
/* Create the message */
(*cinfo->err->format_message) (cinfo,rad_errormsg);
/* Let the memory manager delete any temp files before we die */
jpeg_destroy(cinfo);
longjmp( rad_loadfailed, -1 );
}
/*
* Actual output of an error or trace message.
* Applications may override this method to send JPEG messages somewhere
* other than stderr.
*/
METHODDEF void
output_message (j_common_ptr cinfo)
{
char buffer[JMSG_LENGTH_MAX];
/* Create the message */
(*cinfo->err->format_message) (cinfo, buffer);
/* Send it to stderr, adding a newline */
printf("%s\n", buffer);
}
/*
* Decide whether to emit a trace or warning message.
* msg_level is one of:
* -1: recoverable corrupt-data warning, may want to abort.
* 0: important advisory messages (always display to user).
* 1: first level of tracing detail.
* 2,3,...: successively more detailed tracing messages.
* An application might override this method if it wanted to abort on warnings
* or change the policy about which messages to display.
*/
METHODDEF void
emit_message (j_common_ptr cinfo, int msg_level)
{
struct jpeg_error_mgr * err = cinfo->err;
if (msg_level < 0) {
/* It's a warning message. Since corrupt files may generate many warnings,
* the policy implemented here is to show only the first warning,
* unless trace_level >= 3.
*/
if (err->num_warnings == 0 || err->trace_level >= 3)
(*err->output_message) (cinfo);
/* Always count warnings in num_warnings. */
err->num_warnings++;
} else {
/* It's a trace message. Show it if trace_level >= msg_level. */
if (err->trace_level >= msg_level)
(*err->output_message) (cinfo);
}
}
/*
* Format a message string for the most recent JPEG error or message.
* The message is stored into buffer, which should be at least JMSG_LENGTH_MAX
* characters. Note that no '\n' character is added to the string.
* Few applications should need to override this method.
*/
METHODDEF void
format_message (j_common_ptr cinfo, char * buffer)
{
struct jpeg_error_mgr * err = cinfo->err;
int msg_code = err->msg_code;
const char * msgtext = NULL;
const char * msgptr;
char ch;
boolean isstring;
/* Look up message string in proper table */
if (msg_code > 0 && msg_code <= err->last_jpeg_message) {
msgtext = err->jpeg_message_table[msg_code];
} else if (err->addon_message_table != NULL &&
msg_code >= err->first_addon_message &&
msg_code <= err->last_addon_message) {
msgtext = err->addon_message_table[msg_code - err->first_addon_message];
}
/* Defend against bogus message number */
if (msgtext == NULL) {
err->msg_parm.i[0] = msg_code;
msgtext = err->jpeg_message_table[0];
}
/* Check for string parameter, as indicated by %s in the message text */
isstring = FALSE;
msgptr = msgtext;
while ((ch = *msgptr++) != '\0') {
if (ch == '%') {
if (*msgptr == 's') isstring = TRUE;
break;
}
}
/* Format the message into the passed buffer */
if (isstring)
sprintf(buffer, msgtext, err->msg_parm.s);
else
sprintf(buffer, msgtext,
err->msg_parm.i[0], err->msg_parm.i[1],
err->msg_parm.i[2], err->msg_parm.i[3],
err->msg_parm.i[4], err->msg_parm.i[5],
err->msg_parm.i[6], err->msg_parm.i[7]);
}
/*
* Reset error state variables at start of a new image.
* This is called during compression startup to reset trace/error
* processing to default state, without losing any application-specific
* method pointers. An application might possibly want to override
* this method if it has additional error processing state.
*/
METHODDEF void
reset_error_mgr (j_common_ptr cinfo)
{
cinfo->err->num_warnings = 0;
/* trace_level is not reset since it is an application-supplied parameter */
cinfo->err->msg_code = 0; /* may be useful as a flag for "no error" */
}
/*
* Fill in the standard error-handling methods in a jpeg_error_mgr object.
* Typical call is:
* struct jpeg_compress_struct cinfo;
* struct jpeg_error_mgr err;
*
* cinfo.err = jpeg_std_error(&err);
* after which the application may override some of the methods.
*/
GLOBAL struct jpeg_error_mgr *
jpeg_std_error (struct jpeg_error_mgr * err)
{
err->error_exit = error_exit;
err->emit_message = emit_message;
err->output_message = output_message;
err->format_message = format_message;
err->reset_error_mgr = reset_error_mgr;
err->trace_level = 0; /* default = no tracing */
err->num_warnings = 0; /* no warnings emitted yet */
err->msg_code = 0; /* may be useful as a flag for "no error" */
/* Initialize message table pointers */
err->jpeg_message_table = jpeg_std_message_table;
err->last_jpeg_message = (int) JMSG_LASTMSGCODE - 1;
err->addon_message_table = NULL;
err->first_addon_message = 0; /* for safety */
err->last_addon_message = 0;
return err;
}
| [
"BawooiT@d1c0eb94-fc07-11dd-a7be-4b3ef3b0700c"
]
| [
[
[
1,
233
]
]
]
|
f1ce1945e346b24d80b55107b61281fcf8649a36 | 485c5413e1a4769516c549ed7f5cd4e835751187 | /Source/ImacDemo/scenes/SciFiScene.h | f6cbc3711d6535e2dc73e0a13bec0c67f81c0c9a | []
| no_license | FranckLetellier/rvstereogram | 44d0a78c47288ec0d9fc88efac5c34088af88d41 | c494b87ee8ebb00cf806214bc547ecbec9ad0ca0 | refs/heads/master | 2021-05-29T12:00:15.042441 | 2010-03-25T13:06:10 | 2010-03-25T13:06:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,480 | h | /*************************************
*
* ImacDemo Project
*
* Created : 18/12/09
* Authors : Franck Letellier
* Baptiste Malaga
* Fabien Kapala
* Helena Duchaussoy
*
**************************************/
#ifndef __SCIFISCENE_H__
#define __SCIFISCENE_H__
/**
* @name SciFiScene.h
* @brief don't know yet :)
* @author baptiste malaga
* @date 21/12/09
*/
#include <time.h>
#include "abstractScene.h"
#include <GL/glew.h>
#include <GL/glut.h>
#include <GL/glu.h>
//Forward declaration
class FBO;
class SciFiScene: public AbstractScene
{
public:
SciFiScene(const std::string& sName, AbstractCamera* pCam);
virtual ~SciFiScene();
// Initialise a Scene
virtual bool init();
//Pre display (for FBO/lights and such...)
virtual void preRender();
virtual void render();
virtual void update();
virtual bool isFinished();
virtual void handleKeyUp(unsigned char c, int x, int y);
virtual void handleKeyDown(unsigned char c, int x, int y);
virtual void reset();
private:
GLfloat* m_fLightPosition;
GLfloat* m_fLightDistance;
GLfloat* m_fLightDirection;
GLfloat* m_fLightZeros;
float fAngle;
float depLightPSpeedX;
float depLightPSpeedY;
float depLightPAttX;
float depLightPAttY;
int depLightPSignX;
int depLightPSignY;
void renderEnvironment(bool m_bGlow);
float m_fMixValue;
int m_iMixSign;
};
#endif //__SCIFISCENE_H__
| [
"[email protected]"
]
| [
[
[
1,
77
]
]
]
|
66d6ff23b12677d5618337ef26bf1cfe5082fca8 | 41371839eaa16ada179d580f7b2c1878600b718e | /UVa/Volume C/10015.cpp | 4aafb0cb8a6d92c79d8bc0c1aad3e98bc2b4ba94 | []
| no_license | marinvhs/SMAS | 5481aecaaea859d123077417c9ee9f90e36cc721 | 2241dc612a653a885cf9c1565d3ca2010a6201b0 | refs/heads/master | 2021-01-22T16:31:03.431389 | 2009-10-01T02:33:01 | 2009-10-01T02:33:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 943 | cpp | /////////////////////////////////
// 10015 - Joseph's Cousin
/////////////////////////////////
#include<cstdio>
#include<vector>
#define MAX 32767
using namespace std;
bool sieve[32767];
unsigned short primes[3502];
unsigned short survivor[3502];
unsigned int current,k,i,j,n,idx,size;
void joseph(void){
vector<unsigned int> v;
vector<unsigned int>::iterator it;
for(i = 0; i < n; i++) v.push_back(i+1);
for(k = 0,i = 0; i < n-1; i++){
if(primes[i] > n-i) idx = primes[i]%(n-i);
else idx = primes[i];
size = v.size();
k = (k-1+idx)%size;
v.erase(v.begin()+k);
}
survivor[n] = *v.begin();
}
int main(void){
for(primes[0] = 2,i = 4; i < MAX; i+=2) sieve[i] = 1;
for(idx = 1,i = 3; i < MAX && idx < 3502; i+=2)
if(!sieve[i])
for(primes[idx++] = i,j = i*i; j < MAX; j+=i) sieve[j] = 1;
while(scanf("%d",&n) && n){
if(!survivor[n]) joseph();
printf("%d\n",survivor[n]);
}
return 0;
} | [
"[email protected]"
]
| [
[
[
1,
35
]
]
]
|
36b700e8e537d7f9ccca6cef693ae77f23dd1385 | c7d6926107b8fbd3d5e3cd80b895bebad53175e2 | /src/archiver.h | e5630e5a368daa388987068d097ca72ef67e53b7 | []
| no_license | walkline/Kani | 117c743dc9850a443904bd7e47dd7f7813f20a36 | 79704e2920d64e1d485b0b248ea00344adaf6351 | refs/heads/master | 2020-05-29T19:03:14.137221 | 2011-06-09T18:07:47 | 2011-06-09T18:07:47 | 1,838,943 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,837 | h | #ifndef ARCHIVER_H
#define ARCHIVER_H
#include "lz77.h"
#include <QStringList>
#include <QObject>
#include <QTextBrowser>
#include <QThread>
#include <QFile>
#define READ_LINES 100
#define FILES_LIMIT 200
/*TODO:
* 1. реализировать многофайловое архивирование. Переписать.
*/
/* Использует отдельный поток.
* Использование:
Archiver::Compress(filename, where); // Archiver::Decompress(filename, where);
Archiver::run();
*
*/
class Archiver : public QThread
{
Q_OBJECT
private:
QStringList files;
QStringList dirs;
quint32 *fileSize;
//for decompress
int fCount;
int dCount;
//get info from the file
void Decmpress();
bool startDeC;
bool startCom;
quint32 *linesC;
quint32 *readTimes;
bool isArchive;
QFile write;
QFile read;
QDataStream readS;
void WriteInfo();
void ReadInfo();
//Decompress
QString where;
public:
Archiver();
void AddFiles(QStringList f);
void DelFile(int index);
void AddFile(QString name, bool _isArchive = false);
void AddDirs(QStringList d){ dirs += d; }
void AddDir(QString name);
void Decompress(QString _where = "/");
//TODO: добавить параметр количество считуемых строк.
void Compress(QString _where = "/");
void clear();
bool isLoadArchive(){ return isArchive; }
bool isActive();
QStringList getFiles();
quint32* getFilesSize();
//unused
qint32 linesCount;
protected:
//QThread
void run();
signals:
void DStarted(bool);
void DEnd(bool);
void CStarted(bool);
void CEnd(bool);
};
#endif // ARCHIVER_H
| [
"walkline@walkline-UPC.(none)"
]
| [
[
[
1,
86
]
]
]
|
cc8ee986a6b6c45bf3cff076bc9da6b0b02074a9 | 61fb1bf48c8eeeda8ecb2c40fcec1d3277ba6935 | /patoBase/file.h | ceb1a9e726f9f5a6eab103a4829caf6a769434dd | []
| no_license | matherthal/pato-scm | 172497f3e5c6d71a2cbbd2db132282fb36ba4871 | ba573dad95afa0c0440f1ae7d5b52a2736459b10 | refs/heads/master | 2020-05-20T08:48:12.286498 | 2011-11-25T11:05:23 | 2011-11-25T11:05:23 | 33,139,075 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 353 | h | #ifndef FILE_H
#define FILE_H
#include <QFile>
#include "ifile.h"
class File : public IFile
{
public:
File();
public:
File(const QString &name);
~File();
bool copy(const QString &newName);
bool exists() const;
QString fileName() const;
bool remove();
private:
QFile file;
};
#endif // FILE_H
| [
"rafael@Micro-Mariana"
]
| [
[
[
1,
24
]
]
]
|
cf1de36ad48f6efcbda26c99bf957ce08bac2858 | 028d6009f3beceba80316daa84b628496a210f8d | /uidesigner/com.nokia.sdt.series60.componentlibrary/templates/tutorials/YahooImageSearch/inc/WebClientEngine.h | fbed2411872e516a086a63b12f44e3638154be73 | []
| no_license | JamesLinus/oss.FCL.sftools.dev.ide.carbidecpp | fa50cafa69d3e317abf0db0f4e3e557150fd88b3 | 4420f338bc4e522c563f8899d81201857236a66a | refs/heads/master | 2020-12-30T16:45:28.474973 | 2010-10-20T16:19:31 | 2010-10-20T16:19:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,706 | h | /*
==============================================================================
Name : WebClientEngine.h
Description:
Copyright (c) 2006 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 "Eclipse Public License v1.0"
which accompanies this distribution, and is available
at the URL "http://www.eclipse.org/legal/epl-v10.html".
Contributors:
Nokia Corporation - initial contribution.
Based on the CWebClientEngine class in the S60 SDK WebClient
example application.
==============================================================================
*/
#ifndef WEBCLIENTENGINE_H
#define WEBCLIENTENGINE_H
// INCLUDES
#include <coecntrl.h>
#include <http.h>
#include <http/mhttpauthenticationcallback.h>
#include <es_sock.h>
// CONSTANTS
const TInt KMaxHeaderNameLength = 32;
const TInt KMaxHeaderValueLength = 128;
const TInt KMaxAuthTypeLength = 128;
const TInt KMaxDateTimeStringLength = 40;
const TInt KMaxStatusTextLength = 32;
const TInt KMaxUserNameLength = 128;
const TInt KMaxPasswordLength = 128;
// Used user agent for requests
_LIT8( KUserAgent, "WebClient 1.0" );
// This client accepts all content types.
// (change to e.g. "text/plain" for plain text only)
_LIT8( KAccept, "*/*" );
// Format for output of data/time values
_LIT( KDateFormat,"%D%M%Y%/0%1%/1%2%/2%3%/3 %:0%H%:1%T%:2%S.%C%:3" );
// Some texts for header output
_LIT( KColon, ": " );
_LIT( Krealm, "Realm: " );
class CWebClientEngine;
// CLASS DECLARATION
/**
* MWebClientObserver
* CWebClientEngine passes events and responses body data with this interface.
* An instance of this class must be provided for construction of CWebClientEngine.
*/
class MWebClientObserver
{
public:
/**
* ClientOpenSessionFailedL( CWebClientEngine& anEngine )
* An error occurred opening the HTTP session. The calling code
* will leave after this method returns.
* @param anError: the error code
* Most common error; no access point configured, and session creation
* leaves with KErrNotFound.
*/
virtual void ClientOpenSessionFailedL( CWebClientEngine& anEngine, TInt anError ) = 0;
/**
* ClientConnectingL()
* Called to notify that a connection was initiated
*/
virtual void ClientConnectingL( CWebClientEngine& anEngine ) = 0;
/**
* ClientHeaderReceivedL()
* Called when HTTP header is received.
* @param aHeaderData: Header field name and value
*/
virtual void ClientHeaderReceivedL( CWebClientEngine& anEngine, const TDesC& aHeaderData ) = 0;
/**
* ClientBodyReceivedL()
* Called when a part of the HTTP body is received.
* @param aBodyData: Part of the body data received. (e.g. part of
* the received HTML page)
*/
virtual void ClientBodyReceivedL( CWebClientEngine& anEngine, const TDesC8& aBodyData ) = 0;
/**
* ClientConnectionCanceledL()
* Called to notify that a connection attempt has been canceled
*/
virtual void ClientConnectionCanceledL( CWebClientEngine& anEngine ) = 0;
/**
* ClientResponseCompleteL
* Called to notify that a transaction's response is complete.
* See TTransactionEvent::EResponseComplete
*/
virtual void ClientResponseCompleteL( CWebClientEngine& anEngine ) = 0;
/**
* ClientTransactionSucceeded()
* Called to notify that a transaction completed successfully
* See TTransactionEvent::ESucceeded
*/
virtual void ClientTransactionSucceededL( CWebClientEngine& anEngine ) = 0;
/**
* ClientTransactionFailed()
* Catch-all for failure.
* See TTransactionEvent::EFailed
*/
virtual void ClientTransactionFailedL( CWebClientEngine& anEngine ) = 0;
/**
* ClientUnknownEventL()
* Called to notify that an unknown HTTP event has
* been received.
* @param aStatus: the iStatus field of the event
* See THTTPEvent::iStatus
*/
virtual void ClientUnknownEventL( CWebClientEngine& anEngine , TInt aStatus ) = 0;
/**
* ClientRunErrorL()
* Called when a error occurs in the handling of a transaction event.
* @param anError: the error code
*/
virtual void ClientRunErrorL( CWebClientEngine& anEngine , TInt anError) = 0;
/**
* ClientGetCredentialsL()
* Called when authentication has been requested by the server.
* Return EFalse for no authentication or e.g. the user cancels
* an input dialog. Otherwise return the user name and password
* as out parameters along with an ETrue result.
* @param aUri: the current URI
* @param aRealm: the realm associated with the request
* @param aUserName: the returned user name
* @param aPassword: the returned password
*/
virtual TBool ClientGetCredentialsL( CWebClientEngine& anEngine, const TUriC8& aUri,
const TDesC8& aRealm,
TDes& aUsername,
TDes& aPassword ) = 0;
};
/**
* CWebClientEngine
* Provides simple interface to HTTP Client API.
*/
class CWebClientEngine : public CBase,
public MHTTPTransactionCallback,
public MHTTPAuthenticationCallback
{
public:
/**
* NewL()
* Create a CWebClientEngine object.
* @param iObserver:
* @return A pointer to the created instance of CWebClientEngine
*/
static CWebClientEngine* NewL( MWebClientObserver& aObserver );
/**
* NewLC()
* Create a CWebClientEngine object.
* @param iObserver:
* @return A pointer to the created instance of CWebClientEngine
*/
static CWebClientEngine* NewLC( MWebClientObserver& aObserver );
/**
* ~CWebClientEngine()
* Destroy the object
*/
~CWebClientEngine();
/**
* Opens the HTTP session. Automatically called when a session is initiated,
* or can be called separately.
*/
void OpenSessionL();
/**
* IssueHTTPGetL()
* Starts a new HTTP GET transaction.
* @param aUri: URI to get. (e.g. http://host.org")
*/
void IssueHTTPGetL( const TDesC8& aUri );
/**
* CancelTransactionL()
* Closes currently running transaction and frees resources related to it.
*/
void CancelTransactionL();
/**
* IsRunning()
* Checks if the transaction is running.
* @return ETrue, if transaction is currently running.
*/
inline TBool IsRunning() { return iRunning; };
private:
/**
* ConstructL()
* Perform the second phase construction of a CWebClientEngine object.
*/
void ConstructL();
/**
* CWebClientEngine()
* Perform the first phase of two phase construction.
* @param iObserver:
*/
CWebClientEngine( MWebClientObserver& iObserver );
/**
* SetHeaderL()
* Sets header value of an HTTP request.
* @param aHeaders: Headers of the HTTP request
* @param aHdrField: Enumerated HTTP header field, e.g. HTTP::EUserAgent
* @param aHdrValue: New value for header field
*/
void SetHeaderL( RHTTPHeaders aHeaders, TInt aHdrField,
const TDesC8& aHdrValue );
/**
* DumpRespHeadersL()
* Called when HTTP header is received.
* Displays HTTP header field names and values
* @param aTransaction: The transaction that is processed.
*/
void DumpRespHeadersL( RHTTPTransaction& aTransantion );
/**
* HandleRunErrorL()
* Called from MHFRunError() when *leave* occurs in handling of transaction event.
* @param aError: The leave code that occured.
*/
void HandleRunErrorL( TInt aError );
/**
* From MHTTPSessionEventCallback
*/
private:
/**
* MHFRunL()
* Called by framework to notify about transaction events.
* @param aTransaction: Transaction, where the event occured.
* @param aEvent: Occured event.
*/
void MHFRunL( RHTTPTransaction aTransaction, const THTTPEvent& aEvent );
/**
* MHFRunError()
* Called by framework when *leave* occurs in handling of transaction event.
* @param aError: The leave code that occured.
* @param aTransaction: The transaction that was being processed when leave occured.
* @param aEvent: The event that was being processed when leave occured.
* @return KErrNone, if the error was handled. Otherwise the value of aError, or
* some other error value. Returning error value causes causes
* HTTP-CORE 6 panic.
*/
TInt MHFRunError( TInt aError,
RHTTPTransaction aTransaction,
const THTTPEvent& aEvent );
/**
* From MHTTPAuthenticationCallback (needed for HTTP authentication)
*/
private:
/**
* GetCredentialsL()
* Called by framework when username and password for requested URI is
* needed.
* @param aURI: The URI being requested (e.g. "http://host.org")
* @param aRealm: The realm being requested (e.g. "[email protected]")
* @param aAuthenticationType: Authentication type. (e.g. "Basic")
* @param aUsername: Given user name.
* @param aPassword: Given password.
* @return A pointer to the created document
*/
TBool GetCredentialsL( const TUriC8& aUri,
RString aRealm,
RStringF aAuthenticationType,
RString& aUsername,
RString& aPassword );
private: // Data
RHTTPSession iSession;
RHTTPTransaction iTransaction;
RSocketServ iSocketServ;
RConnection iConnection;
MWebClientObserver& iObserver; // Used for passing body data and
// events to UI.
TBool iSessionOpened; // ETrue, if session successfully opened
TBool iRunning; // ETrue, if transaction running
};
#endif // WEBCLIENTENGINE_H
| [
"[email protected]"
]
| [
[
[
1,
312
]
]
]
|
4f1f7fd48c1bb92c47003cbc0c47bef56ba5e118 | ce262ae496ab3eeebfcbb337da86d34eb689c07b | /SETools/SEMax8Exporter/SEMax8Exporter/SEMax8TextureTree.h | 66126887629438f8e34bdd63ed6524e6788cd211 | []
| no_license | pizibing/swingengine | d8d9208c00ec2944817e1aab51287a3c38103bea | e7109d7b3e28c4421c173712eaf872771550669e | refs/heads/master | 2021-01-16T18:29:10.689858 | 2011-06-23T04:27:46 | 2011-06-23T04:27:46 | 33,969,301 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,682 | h | // Swing Engine Version 1 Source Code
// Most of techniques in the engine are mainly based on David Eberly's
// Wild Magic 4 open-source code.The author of Swing Engine learned a lot
// from Eberly's experience of architecture and algorithm.
// Several sub-systems are totally new,and others are re-implimented or
// re-organized based on Wild Magic 4's sub-systems.
// Copyright (c) 2007-2010. All Rights Reserved
//
// Eberly's permission:
// Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or (at
// your option) any later version. The license is available for reading at
// the location:
// http://www.gnu.org/copyleft/lgpl.html
#ifndef Swing_Max8TextureTree_H
#define Swing_Max8TextureTree_H
#include "SETexture.h"
#include <vector>
//----------------------------------------------------------------------------
// 名称:Max8TextureTree类
// 说明:
// 作者:Sun Che
// 时间:20080815
//----------------------------------------------------------------------------
class Max8TextureTree
{
public:
Max8TextureTree(void);
void SetTexture(Swing::SETexturePtr spSETexture);
Swing::SETexturePtr GetTexture(void);
void SetChildCount(int iCount);
int GetChildCount(void) const;
Max8TextureTree& GetChild(int i);
private:
Swing::SETexturePtr m_spSETexture;
std::vector<Max8TextureTree> m_Children;
};
#endif
| [
"[email protected]@876e9856-8d94-11de-b760-4d83c623b0ac"
]
| [
[
[
1,
52
]
]
]
|
f90f4009094058ddd2733a0b1f7a48e05c47882d | fd3f2268460656e395652b11ae1a5b358bfe0a59 | /srchybrid/SharedFilesCtrl.cpp | 8958973f1f534e9337ffef3a6f347d570c905a4e | []
| 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 | 132,572 | cpp | //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.
#include "stdafx.h"
#include "emule.h"
#include "emuledlg.h"
#include "SharedFilesCtrl.h"
#include "OtherFunctions.h"
#include "FileInfoDialog.h"
#include "MetaDataDlg.h"
#include "ED2kLinkDlg.h"
#include "ArchivePreviewDlg.h"
#include "CommentDialog.h"
#include "HighColorTab.hpp"
#include "ListViewWalkerPropertySheet.h"
#include "UserMsgs.h"
#include "ResizableLib/ResizableSheet.h"
#include "KnownFile.h"
#include "MapKey.h"
#include "SharedFileList.h"
#include "MemDC.h"
#include "PartFile.h"
#include "MenuCmds.h"
#include "IrcWnd.h"
#include "SharedFilesWnd.h"
#include "Opcodes.h"
#include "InputBox.h"
#include "WebServices.h"
#include "TransferDlg.h"
#include "ClientList.h"
#include "UpDownClient.h"
#include "Collection.h"
#include "CollectionCreateDialog.h"
#include "CollectionViewDialog.h"
#include "SearchParams.h"
#include "SearchDlg.h"
#include "SearchResultsWnd.h"
#include "ToolTipCtrlX.h"
#include "kademlia/kademlia/kademlia.h"
#include "kademlia/kademlia/UDPFirewallTester.h"
#include "MediaInfo.h"
#include "Log.h"
#include "KnownFileList.h"
#include "VisualStylesXP.h"
#include "MassRename.h" //Xman Mass Rename (Morph)
#include "Log.h" //Xman Mass Rename (Morph)
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
bool NeedArchiveInfoPage(const CSimpleArray<CObject*>* paItems);
void UpdateFileDetailsPages(CListViewPropertySheet *pSheet,
CResizablePage *pArchiveInfo, CResizablePage *pMediaInfo);
//////////////////////////////////////////////////////////////////////////////
// CSharedFileDetailsSheet
class CSharedFileDetailsSheet : public CListViewWalkerPropertySheet
{
DECLARE_DYNAMIC(CSharedFileDetailsSheet)
public:
CSharedFileDetailsSheet(CTypedPtrList<CPtrList, CShareableFile*>& aFiles, UINT uPshInvokePage = 0, CListCtrlItemWalk* pListCtrl = NULL);
virtual ~CSharedFileDetailsSheet();
protected:
CFileInfoDialog m_wndMediaInfo;
CMetaDataDlg m_wndMetaData;
CED2kLinkDlg m_wndFileLink;
CCommentDialog m_wndFileComments;
CArchivePreviewDlg m_wndArchiveInfo;
UINT m_uPshInvokePage;
static LPCTSTR m_pPshStartPage;
void UpdateTitle();
virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam);
virtual BOOL OnInitDialog();
DECLARE_MESSAGE_MAP()
afx_msg void OnDestroy();
afx_msg LRESULT OnDataChanged(WPARAM, LPARAM);
};
LPCTSTR CSharedFileDetailsSheet::m_pPshStartPage;
IMPLEMENT_DYNAMIC(CSharedFileDetailsSheet, CListViewWalkerPropertySheet)
BEGIN_MESSAGE_MAP(CSharedFileDetailsSheet, CListViewWalkerPropertySheet)
ON_WM_DESTROY()
ON_MESSAGE(UM_DATA_CHANGED, OnDataChanged)
END_MESSAGE_MAP()
CSharedFileDetailsSheet::CSharedFileDetailsSheet(CTypedPtrList<CPtrList, CShareableFile*>& aFiles, UINT uPshInvokePage, CListCtrlItemWalk* pListCtrl)
: CListViewWalkerPropertySheet(pListCtrl)
{
m_uPshInvokePage = uPshInvokePage;
POSITION pos = aFiles.GetHeadPosition();
while (pos)
m_aItems.Add(aFiles.GetNext(pos));
m_psh.dwFlags &= ~PSH_HASHELP;
m_wndFileComments.m_psp.dwFlags &= ~PSP_HASHELP;
m_wndFileComments.m_psp.dwFlags |= PSP_USEICONID;
m_wndFileComments.m_psp.pszIcon = _T("FileComments");
m_wndFileComments.SetFiles(&m_aItems);
AddPage(&m_wndFileComments);
m_wndArchiveInfo.m_psp.dwFlags &= ~PSP_HASHELP;
m_wndArchiveInfo.m_psp.dwFlags |= PSP_USEICONID;
m_wndArchiveInfo.m_psp.pszIcon = _T("ARCHIVE_PREVIEW");
m_wndArchiveInfo.SetFiles(&m_aItems);
m_wndMediaInfo.m_psp.dwFlags &= ~PSP_HASHELP;
m_wndMediaInfo.m_psp.dwFlags |= PSP_USEICONID;
m_wndMediaInfo.m_psp.pszIcon = _T("MEDIAINFO");
m_wndMediaInfo.SetFiles(&m_aItems);
if (NeedArchiveInfoPage(&m_aItems))
AddPage(&m_wndArchiveInfo);
else
AddPage(&m_wndMediaInfo);
m_wndMetaData.m_psp.dwFlags &= ~PSP_HASHELP;
m_wndMetaData.m_psp.dwFlags |= PSP_USEICONID;
m_wndMetaData.m_psp.pszIcon = _T("METADATA");
if (m_aItems.GetSize() == 1 && thePrefs.IsExtControlsEnabled()) {
m_wndMetaData.SetFiles(&m_aItems);
AddPage(&m_wndMetaData);
}
m_wndFileLink.m_psp.dwFlags &= ~PSP_HASHELP;
m_wndFileLink.m_psp.dwFlags |= PSP_USEICONID;
m_wndFileLink.m_psp.pszIcon = _T("ED2KLINK");
m_wndFileLink.SetFiles(&m_aItems);
AddPage(&m_wndFileLink);
LPCTSTR pPshStartPage = m_pPshStartPage;
if (m_uPshInvokePage != 0)
pPshStartPage = MAKEINTRESOURCE(m_uPshInvokePage);
for (int i = 0; i < m_pages.GetSize(); i++)
{
CPropertyPage* pPage = GetPage(i);
if (pPage->m_psp.pszTemplate == pPshStartPage)
{
m_psh.nStartPage = i;
break;
}
}
}
CSharedFileDetailsSheet::~CSharedFileDetailsSheet()
{
}
void CSharedFileDetailsSheet::OnDestroy()
{
if (m_uPshInvokePage == 0)
m_pPshStartPage = GetPage(GetActiveIndex())->m_psp.pszTemplate;
CListViewWalkerPropertySheet::OnDestroy();
}
BOOL CSharedFileDetailsSheet::OnInitDialog()
{
EnableStackedTabs(FALSE);
BOOL bResult = CListViewWalkerPropertySheet::OnInitDialog();
HighColorTab::UpdateImageList(*this);
InitWindowStyles(this);
EnableSaveRestore(_T("SharedFileDetailsSheet")); // call this after(!) OnInitDialog
UpdateTitle();
return bResult;
}
LRESULT CSharedFileDetailsSheet::OnDataChanged(WPARAM, LPARAM)
{
UpdateTitle();
UpdateFileDetailsPages(this, &m_wndArchiveInfo, &m_wndMediaInfo);
return 1;
}
void CSharedFileDetailsSheet::UpdateTitle()
{
if (m_aItems.GetSize() == 1)
SetWindowText(GetResString(IDS_DETAILS) + _T(": ") + STATIC_DOWNCAST(CAbstractFile, m_aItems[0])->GetFileName());
else
SetWindowText(GetResString(IDS_DETAILS));
}
BOOL CSharedFileDetailsSheet::OnCommand(WPARAM wParam, LPARAM lParam)
{
if (wParam == ID_APPLY_NOW)
{
CSharedFilesCtrl* pSharedFilesCtrl = DYNAMIC_DOWNCAST(CSharedFilesCtrl, m_pListCtrl->GetListCtrl());
if (pSharedFilesCtrl)
{
for (int i = 0; i < m_aItems.GetSize(); i++) {
// so, and why does this not(!) work while the sheet is open ??
pSharedFilesCtrl->UpdateFile(DYNAMIC_DOWNCAST(CKnownFile, m_aItems[i]));
}
}
}
return CListViewWalkerPropertySheet::OnCommand(wParam, lParam);
}
//////////////////////////////////////////////////////////////////////////////
// CSharedFilesCtrl
IMPLEMENT_DYNAMIC(CSharedFilesCtrl, CMuleListCtrl)
BEGIN_MESSAGE_MAP(CSharedFilesCtrl, CMuleListCtrl)
ON_NOTIFY_REFLECT(LVN_COLUMNCLICK, OnLvnColumnClick)
ON_NOTIFY_REFLECT(LVN_GETDISPINFO, OnLvnGetDispInfo)
ON_NOTIFY_REFLECT(LVN_GETINFOTIP, OnLvnGetInfoTip)
ON_NOTIFY_REFLECT(NM_DBLCLK, OnNmDblClk)
ON_NOTIFY_REFLECT_EX(NM_CLICK, OnNMClick)
ON_WM_CONTEXTMENU()
ON_WM_KEYDOWN()
ON_WM_SYSCOLORCHANGE()
ON_WM_MOUSEMOVE()
END_MESSAGE_MAP()
CSharedFilesCtrl::CSharedFilesCtrl()
: CListCtrlItemWalk(this)
{
memset(&m_aSortBySecondValue, 0, sizeof(m_aSortBySecondValue));
nAICHHashing = 0;
m_pDirectoryFilter = NULL;
SetGeneralPurposeFind(true);
// ==> Run eMule as NT Service [leuk_he/Stulle] - Stulle
/*
m_pToolTip = new CToolTipCtrlX;
*/
// workaround running MFC as service
if (!theApp.IsRunningAsService())
m_pToolTip = new CToolTipCtrlX;
else
m_pToolTip = NULL;
// <== Run eMule as NT Service [leuk_he/Stulle] - Stulle
SetSkinKey(L"SharedFilesLv");
m_pHighlightedItem = NULL;
}
CSharedFilesCtrl::~CSharedFilesCtrl()
{
while (!liTempShareableFilesInDir.IsEmpty()) // delete shareble files
delete liTempShareableFilesInDir.RemoveHead();
// ==> Run eMule as NT Service [leuk_he/Stulle] - Stulle
// workaround running MFC as service
if (!theApp.IsRunningAsService())
// <== Run eMule as NT Service [leuk_he/Stulle] - Stulle
delete m_pToolTip;
// ==> PowerShare [ZZ/MorphXT] - Stulle
if (m_PowershareMenu) VERIFY( m_PowershareMenu.DestroyMenu() );
if (m_PowerShareLimitMenu) VERIFY( m_PowerShareLimitMenu.DestroyMenu() );
// <== PowerShare [ZZ/MorphXT] - Stulle
// ==> Limit PS by amount of data uploaded [Stulle] - Stulle
if (m_PsAmountLimitMenu) VERIFY( m_PsAmountLimitMenu.DestroyMenu() );
// <== Limit PS by amount of data uploaded [Stulle] - Stulle
// ==> HideOS & SOTN [Slugfiller/ MorphXT] - Stulle
if (m_HideOSMenu) VERIFY( m_HideOSMenu.DestroyMenu() );
if (m_SelectiveChunkMenu) VERIFY( m_SelectiveChunkMenu.DestroyMenu() );
if (m_ShareOnlyTheNeedMenu) VERIFY( m_ShareOnlyTheNeedMenu.DestroyMenu() );
// <== HideOS & SOTN [Slugfiller/ MorphXT] - Stulle
// ==> mem leak fix [fafner] - Stulle
if (m_PrioMenu) VERIFY( m_PrioMenu.DestroyMenu() );
if (m_CollectionsMenu) VERIFY( m_CollectionsMenu.DestroyMenu() );
if (m_SharedFilesMenu) VERIFY( m_SharedFilesMenu.DestroyMenu() );
// <== mem leak fix [fafner] - Stulle
}
void CSharedFilesCtrl::Init()
{
SetPrefsKey(_T("SharedFilesCtrl"));
SetExtendedStyle(LVS_EX_FULLROWSELECT | LVS_EX_INFOTIP);
ASSERT( (GetStyle() & LVS_SINGLESEL) == 0 );
InsertColumn(0, GetResString(IDS_DL_FILENAME), LVCFMT_LEFT, DFLT_FILENAME_COL_WIDTH);
InsertColumn(1, GetResString(IDS_DL_SIZE), LVCFMT_RIGHT, DFLT_SIZE_COL_WIDTH);
InsertColumn(2, GetResString(IDS_TYPE), LVCFMT_LEFT, DFLT_FILETYPE_COL_WIDTH);
InsertColumn(3, GetResString(IDS_PRIORITY), LVCFMT_LEFT, DFLT_PRIORITY_COL_WIDTH);
InsertColumn(4, GetResString(IDS_FILEID), LVCFMT_LEFT, DFLT_HASH_COL_WIDTH, -1, true);
InsertColumn(5, GetResString(IDS_SF_REQUESTS), LVCFMT_RIGHT, 100);
InsertColumn(6, GetResString(IDS_SF_ACCEPTS), LVCFMT_RIGHT, 100, -1, true);
InsertColumn(7, GetResString(IDS_SF_TRANSFERRED), LVCFMT_RIGHT, 120);
InsertColumn(8, GetResString(IDS_SHARED_STATUS), LVCFMT_LEFT, DFLT_PARTSTATUS_COL_WIDTH);
InsertColumn(9, GetResString(IDS_FOLDER), LVCFMT_LEFT, DFLT_FOLDER_COL_WIDTH, -1, true);
InsertColumn(10,GetResString(IDS_COMPLSOURCES), LVCFMT_RIGHT, 60);
InsertColumn(11,GetResString(IDS_SHAREDTITLE), LVCFMT_LEFT, 100);
InsertColumn(12,GetResString(IDS_ARTIST), LVCFMT_LEFT, DFLT_ARTIST_COL_WIDTH, -1, true);
InsertColumn(13,GetResString(IDS_ALBUM), LVCFMT_LEFT, DFLT_ALBUM_COL_WIDTH, -1, true);
InsertColumn(14,GetResString(IDS_TITLE), LVCFMT_LEFT, DFLT_TITLE_COL_WIDTH, -1, true);
InsertColumn(15,GetResString(IDS_LENGTH), LVCFMT_RIGHT, DFLT_LENGTH_COL_WIDTH, -1, true);
InsertColumn(16,GetResString(IDS_BITRATE), LVCFMT_RIGHT, DFLT_BITRATE_COL_WIDTH, -1, true);
InsertColumn(17,GetResString(IDS_CODEC), LVCFMT_LEFT, DFLT_CODEC_COL_WIDTH, -1, true);
InsertColumn(18,GetResString(IDS_ONQUEUE), LVCFMT_LEFT, 50); //Xman see OnUploadqueue
InsertColumn(19,GetResString(IDS_SHAREFACTOR), LVCFMT_LEFT, 100); //Xman advanced upload-priority
// ==> Spread bars [Slugfiller/MorphXT] - Stulle
InsertColumn(20,GetResString(IDS_SF_UPLOADED_PARTS),LVCFMT_LEFT,170,13);
InsertColumn(21,GetResString(IDS_SF_TURN_PART),LVCFMT_LEFT,100,14);
InsertColumn(22,GetResString(IDS_SF_TURN_SIMPLE),LVCFMT_LEFT,100,15);
InsertColumn(23,GetResString(IDS_SF_FULLUPLOAD),LVCFMT_LEFT,100,16);
// <== Spread bars [Slugfiller/MorphXT] - Stulle
InsertColumn(24,GetResString(IDS_RARE_RATIO),LVCFMT_LEFT,100,17); // push rare file - Stulle
// ==> HideOS & SOTN [Slugfiller/ MorphXT] - Stulle
InsertColumn(25,GetResString(IDS_HIDEOS),LVCFMT_LEFT,100,18);
InsertColumn(26,GetResString(IDS_SHAREONLYTHENEED),LVCFMT_LEFT,100,19);
// <== HideOS & SOTN [Slugfiller/ MorphXT] - Stulle
InsertColumn(27,GetResString(IDS_POWERSHARE_COLUMN_LABEL),LVCFMT_LEFT,70,20); // PowerShare [ZZ/MorphXT] - Stulle
SetAllIcons();
CreateMenues();
LoadSettings();
m_aSortBySecondValue[0] = true; // Requests: Sort by 2nd value by default
m_aSortBySecondValue[1] = true; // Accepted Requests: Sort by 2nd value by default
m_aSortBySecondValue[2] = true; // Transferred Data: Sort by 2nd value by default
m_aSortBySecondValue[3] = false; // Shared ED2K|Kad: Sort by 1st value by default
if (GetSortItem() >= 5 && GetSortItem() <= 7)
m_aSortBySecondValue[GetSortItem() - 5] = GetSortSecondValue();
else if (GetSortItem() == 11)
m_aSortBySecondValue[3] = GetSortSecondValue();
SetSortArrow();
// ==> PowerShare [ZZ/MorphXT] - Stulle
/*
SortItems(SortProc, GetSortItem() + (GetSortAscending() ? 0 : 20) + (GetSortSecondValue() ? 100 : 0));
*/
SortItems(SortProc, GetSortItem() + (GetSortAscending() ? 0 : 30) + (GetSortSecondValue() ? 100 : 0));
// <== PowerShare [ZZ/MorphXT] - Stulle
// ==> Run eMule as NT Service [leuk_he/Stulle] - Stulle
// workaround running MFC as service
if (!theApp.IsRunningAsService())
{
// <== Run eMule as NT Service [leuk_he/Stulle] - Stulle
CToolTipCtrl* tooltip = GetToolTips();
if (tooltip){
m_pToolTip->SetFileIconToolTip(true);
m_pToolTip->SubclassWindow(*tooltip);
tooltip->ModifyStyle(0, TTS_NOPREFIX);
tooltip->SetDelayTime(TTDT_AUTOPOP, 20000);
tooltip->SetDelayTime(TTDT_INITIAL, thePrefs.GetToolTipDelay()*1000);
}
} // Run eMule as NT Service [leuk_he/Stulle] - Stulle
m_ShareDropTarget.SetParent(this);
VERIFY( m_ShareDropTarget.Register(this) );
}
void CSharedFilesCtrl::OnSysColorChange()
{
CMuleListCtrl::OnSysColorChange();
SetAllIcons();
CreateMenues();
}
void CSharedFilesCtrl::SetAllIcons()
{
ApplyImageList(NULL);
m_ImageList.DeleteImageList();
m_ImageList.Create(16, 16, theApp.m_iDfltImageListColorFlags | ILC_MASK, 0, 1);
m_ImageList.Add(CTempIconLoader(_T("EMPTY")));
m_ImageList.Add(CTempIconLoader(_T("FileSharedServer")));
m_ImageList.Add(CTempIconLoader(_T("FileSharedKad")));
m_ImageList.Add(CTempIconLoader(_T("Rating_NotRated")));
m_ImageList.Add(CTempIconLoader(_T("Rating_Fake")));
m_ImageList.Add(CTempIconLoader(_T("Rating_Poor")));
m_ImageList.Add(CTempIconLoader(_T("Rating_Fair")));
m_ImageList.Add(CTempIconLoader(_T("Rating_Good")));
m_ImageList.Add(CTempIconLoader(_T("Rating_Excellent")));
m_ImageList.Add(CTempIconLoader(_T("Collection_Search"))); // rating for comments are searched on kad
m_ImageList.SetOverlayImage(m_ImageList.Add(CTempIconLoader(_T("FileCommentsOvl"))), 1);
// Apply the image list also to the listview control, even if we use our own 'DrawItem'.
// This is needed to give the listview control a chance to initialize the row height.
ASSERT( (GetStyle() & LVS_SHAREIMAGELISTS) != 0 );
VERIFY( ApplyImageList(m_ImageList) == NULL );
}
void CSharedFilesCtrl::Localize()
{
CHeaderCtrl* pHeaderCtrl = GetHeaderCtrl();
HDITEM hdi;
hdi.mask = HDI_TEXT;
CString strRes;
strRes = GetResString(IDS_DL_FILENAME);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(0, &hdi);
strRes = GetResString(IDS_DL_SIZE);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(1, &hdi);
strRes = GetResString(IDS_TYPE);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(2, &hdi);
strRes = GetResString(IDS_PRIORITY);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(3, &hdi);
strRes = GetResString(IDS_FILEID);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(4, &hdi);
strRes = GetResString(IDS_SF_REQUESTS);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(5, &hdi);
strRes = GetResString(IDS_SF_ACCEPTS);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(6, &hdi);
strRes = GetResString(IDS_SF_TRANSFERRED);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(7, &hdi);
strRes = GetResString(IDS_SHARED_STATUS);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(8, &hdi);
strRes = GetResString(IDS_FOLDER);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(9, &hdi);
strRes = GetResString(IDS_COMPLSOURCES);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(10, &hdi);
strRes = GetResString(IDS_SHAREDTITLE);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(11, &hdi);
strRes = GetResString(IDS_ARTIST);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(12, &hdi);
strRes = GetResString(IDS_ALBUM);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(13, &hdi);
strRes = GetResString(IDS_TITLE);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(14, &hdi);
strRes = GetResString(IDS_LENGTH);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(15, &hdi);
strRes = GetResString(IDS_BITRATE);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(16, &hdi);
strRes = GetResString(IDS_CODEC);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(17, &hdi);
//Xman see OnUploadqueue
strRes = GetResString(IDS_ONQUEUE);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(18, &hdi);
//Xman end
//Xman advanced upload-priority
strRes = GetResString(IDS_SHAREFACTOR);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(19, &hdi);
//Xman end
// ==> Spread bars [Slugfiller/MorphXT] - Stulle
strRes = GetResString(IDS_SF_UPLOADED_PARTS);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(20, &hdi);
strRes = GetResString(IDS_SF_TURN_PART);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(21, &hdi);
strRes = GetResString(IDS_SF_TURN_SIMPLE);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(22, &hdi);
strRes = GetResString(IDS_SF_FULLUPLOAD);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(23, &hdi);
// <== Spread bars [Slugfiller/MorphXT] - Stulle
// ==> push rare file - Stulle
strRes = GetResString(IDS_RARE_RATIO);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(24, &hdi);
// <== push rare file - Stulle
// ==> HideOS & SOTN [Slugfiller/ MorphXT] - Stulle
strRes = GetResString(IDS_HIDEOS);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(25, &hdi);
strRes = GetResString(IDS_SHAREONLYTHENEED);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(26, &hdi);
// <== HideOS & SOTN [Slugfiller/ MorphXT] - Stulle
// ==> PowerShare [ZZ/MorphXT] - Stulle
strRes = GetResString(IDS_POWERSHARE_COLUMN_LABEL);
hdi.pszText = const_cast<LPTSTR>((LPCTSTR)strRes);
pHeaderCtrl->SetItem(27, &hdi);
// <== PowerShare [ZZ/MorphXT] - Stulle
// ==> Design Settings [eWombat/Stulle] - Stulle
COLORREF crTempColor = thePrefs.GetStyleBackColor(background_styles, style_b_sharedlist);
if(crTempColor == CLR_DEFAULT)
crTempColor = thePrefs.GetStyleBackColor(background_styles, style_b_default);
if(crTempColor != CLR_DEFAULT)
SetBkColor(crTempColor);
else
SetBkColor(COLORREF(RGB(255,255,255)));
// <== Design Settings [eWombat/Stulle] - Stulle
CreateMenues();
int iItems = GetItemCount();
for (int i = 0; i < iItems; i++)
Update(i);
ShowFilesCount();
}
void CSharedFilesCtrl::AddFile(const CShareableFile* file)
{
// ==> Run eMule as NT Service [leuk_he/Stulle] - Stulle
if (theApp.IsRunningAsService(SVC_LIST_OPT))
return;
// <== Run eMule as NT Service [leuk_he/Stulle] - Stulle
if (!theApp.emuledlg->IsRunning())
return;
// check filter conditions if we should show this file right now
if (m_pDirectoryFilter != NULL){
ASSERT( file->IsKindOf(RUNTIME_CLASS(CKnownFile)) || m_pDirectoryFilter->m_eItemType == SDI_UNSHAREDDIRECTORY );
switch(m_pDirectoryFilter->m_eItemType){
case SDI_ALL:
// No filter
break;
case SDI_FILESYSTEMPARENT:
return;
case SDI_UNSHAREDDIRECTORY:
// Items from the whole filesystem tree
if (file->IsPartFile())
return;
case SDI_NO:
// some shared directory
case SDI_CATINCOMING:
// Categories with special incoming dirs
if (CompareDirectories(file->GetSharedDirectory(), m_pDirectoryFilter->m_strFullPath) != 0)
return;
break;
case SDI_TEMP:
// only tempfiles
if (!file->IsPartFile())
return;
else if (m_pDirectoryFilter->m_nCatFilter != -1 && (UINT)m_pDirectoryFilter->m_nCatFilter != ((CPartFile*)file)->GetCategory())
return;
break;
case SDI_DIRECTORY:
// any userselected shared dir but not incoming or temp
if (file->IsPartFile())
return;
if (CompareDirectories(file->GetSharedDirectory(), thePrefs.GetMuleDirectory(EMULE_INCOMINGDIR)) == 0)
return;
break;
case SDI_INCOMING:
// Main incoming directory
if (CompareDirectories(file->GetSharedDirectory(), thePrefs.GetMuleDirectory(EMULE_INCOMINGDIR)) != 0)
return;
// Hmm should we show all incoming files dirs or only those from the main incoming dir here?
// hard choice, will only show the main for now
break;
// Avi3k: SharedView Ed2kType
case SDI_ED2KFILETYPE:
{
if (m_pDirectoryFilter->m_nCatFilter == -1 || m_pDirectoryFilter->m_nCatFilter != GetED2KFileTypeID(file->GetFileName()))
return;
break;
}
// end Avi3k: SharedView Ed2kType
}
}
if (IsFilteredItem(file))
return;
if (FindFile(file) != -1)
{
// in the filesystem view the shared status might have changed so we need to update the item to redraw the checkbox
if (m_pDirectoryFilter != NULL && m_pDirectoryFilter->m_eItemType == SDI_UNSHAREDDIRECTORY)
UpdateFile(file);
return;
}
// if we are in the filesystem view, this might be a CKnownFile which has to replace a CShareableFile
// (in case we start sharing this file), so make sure to replace the old one instead of adding a new
if (m_pDirectoryFilter != NULL && m_pDirectoryFilter->m_eItemType == SDI_UNSHAREDDIRECTORY && file->IsKindOf(RUNTIME_CLASS(CKnownFile)))
{
for (POSITION pos = liTempShareableFilesInDir.GetHeadPosition(); pos != NULL; )
{
CShareableFile* pFile = liTempShareableFilesInDir.GetNext(pos);
if (pFile->GetFilePath().CompareNoCase(file->GetFilePath()) == 0)
{
int iOldFile = FindFile(pFile);
if (iOldFile != (-1))
{
SetItemData(iOldFile, (LPARAM)file);
Update(iOldFile);
ShowFilesCount();
return;
}
}
}
}
int iItem = InsertItem(LVIF_TEXT | LVIF_PARAM, GetItemCount(), LPSTR_TEXTCALLBACK, 0, 0, 0, (LPARAM)file);
if (iItem >= 0)
Update(iItem);
ShowFilesCount(); //Xman Code Improvement for ShowFilesCount
}
void CSharedFilesCtrl::RemoveFile(const CShareableFile* file, bool bDeletedFromDisk)
{
int iItem = FindFile(file);
if (iItem != -1)
{
if (!bDeletedFromDisk && m_pDirectoryFilter != NULL && m_pDirectoryFilter->m_eItemType == SDI_UNSHAREDDIRECTORY)
{
// in the file system view we usally dont need to remove a file, if it becomes unshared it will
// still be visible as its still in the file system and the knownfile object doesn't gets deleted neither
// so to avoid having to reload the whole list we just update it instead of removing and refinding
UpdateFile(file);
ShowFilesCount();
}
else
{
DeleteItem(iItem);
ShowFilesCount();
}
}
}
//Xman advanced upload-priority
/*
void CSharedFilesCtrl::UpdateFile(const CShareableFile* file, bool bUpdateFileSummary)
*/
void CSharedFilesCtrl::UpdateFile(const CShareableFile* file, bool bUpdateFileSummary, bool force)
//Xman end
{
// ==> Run eMule as NT Service [leuk_he/Stulle] - Stulle
if (theApp.IsRunningAsService(SVC_LIST_OPT))
return;
// <== Run eMule as NT Service [leuk_he/Stulle] - Stulle
if (!file || !theApp.emuledlg->IsRunning())
return;
//MORPH START - SiRoB, Don't Refresh item if not needed
if( theApp.emuledlg->activewnd != theApp.emuledlg->sharedfileswnd && !force) //Xman advanced upload-priority
return;
//MORPH END - SiRoB, Don't Refresh item if not needed
int iItem = FindFile(file);
if (iItem != -1)
{
Update(iItem);
//Xman [MoNKi: -Downloaded History-]
/*
if (bUpdateFileSummary && GetItemState(iItem, LVIS_SELECTED))
*/
if (bUpdateFileSummary && GetItemState(iItem, LVIS_SELECTED) && IsWindowVisible())
//Xman end
theApp.emuledlg->sharedfileswnd->ShowSelectedFilesDetails();
}
}
int CSharedFilesCtrl::FindFile(const CShareableFile* pFile)
{
LVFINDINFO find;
find.flags = LVFI_PARAM;
find.lParam = (LPARAM)pFile;
return FindItem(&find);
}
void CSharedFilesCtrl::ReloadFileList()
{
//Xman [MoNKi: -Downloaded History-]
if(theApp.emuledlg->sharedfileswnd->historylistctrl.IsWindowVisible())
{
theApp.emuledlg->sharedfileswnd->historylistctrl.Reload();
return;
}
//Xman end
DeleteAllItems();
theApp.emuledlg->sharedfileswnd->ShowSelectedFilesDetails();
CCKey bufKey;
CKnownFile* cur_file;
for (POSITION pos = theApp.sharedfiles->m_Files_map.GetStartPosition(); pos != 0; ){
theApp.sharedfiles->m_Files_map.GetNextAssoc(pos, bufKey, cur_file);
AddFile(cur_file);
}
if (m_pDirectoryFilter != NULL && m_pDirectoryFilter->m_eItemType == SDI_UNSHAREDDIRECTORY && !m_pDirectoryFilter->m_strFullPath.IsEmpty()){
AddShareableFiles(m_pDirectoryFilter->m_strFullPath);
}
else {
while (!liTempShareableFilesInDir.IsEmpty()) // cleanup temp filelist
delete liTempShareableFilesInDir.RemoveHead();
}
ShowFilesCount();
}
void CSharedFilesCtrl::ShowFilesCount()
{
//Xman [MoNKi: -Downloaded History-]
/*
CString str;
if (theApp.sharedfiles->GetHashingCount() + nAICHHashing)
str.Format(_T(" (%i, %s %i)"), theApp.sharedfiles->GetCount(), GetResString(IDS_HASHING), theApp.sharedfiles->GetHashingCount() + nAICHHashing);
else
str.Format(_T(" (%i)"), theApp.sharedfiles->GetCount());
theApp.emuledlg->sharedfileswnd->GetDlgItem(IDC_TRAFFIC_TEXT)->SetWindowText(GetResString(IDS_SF_FILES) + str);
*/
//if(theApp.emuledlg->sharedfileswnd->sharedfilesctrl.IsWindowVisible())
if(!theApp.emuledlg->sharedfileswnd->historylistctrl.IsWindowVisible()) //Xman Code Improvement for ShowFilesCount
{
CString str;
if (theApp.sharedfiles->GetHashingCount() + nAICHHashing)
str.Format(_T(" (%i, %s %i)"), theApp.sharedfiles->GetCount(), GetResString(IDS_HASHING), theApp.sharedfiles->GetHashingCount() + nAICHHashing);
else
str.Format(_T(" (%i)"), theApp.sharedfiles->GetCount());
theApp.emuledlg->sharedfileswnd->GetDlgItem(IDC_TRAFFIC_TEXT)->SetWindowText(GetResString(IDS_SF_FILES) + str);
}
//Xman End
}
void CSharedFilesCtrl::DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct)
{
if (!theApp.emuledlg->IsRunning())
return;
if (!lpDrawItemStruct->itemData)
return;
// ==> Visual Studio 2010 Compatibility [Stulle/Avi-3k/ied] - Stulle
/*
CMemDC dc(CDC::FromHandle(lpDrawItemStruct->hDC), &lpDrawItemStruct->rcItem);
*/
CMemoryDC dc(CDC::FromHandle(lpDrawItemStruct->hDC), &lpDrawItemStruct->rcItem);
// <== Visual Studio 2010 Compatibility [Stulle/Avi-3k/ied] - Stulle
//zz_fly :: we init it ourself :: from DolphinX :: start
/*
BOOL bCtrlFocused;
InitItemMemDC(dc, lpDrawItemStruct, bCtrlFocused);
*/
//zz_fly :: end
// ==> Design Settings [eWombat/Stulle] - Stulle
BOOL bCtrlFocused;
InitItemMemDC(dc, lpDrawItemStruct, bCtrlFocused, false, style_b_sharedlist);
// <== Design Settings [eWombat/Stulle] - Stulle
CRect cur_rec(lpDrawItemStruct->rcItem);
CRect rcClient;
GetClientRect(&rcClient);
/*const*/ CShareableFile* file = (CShareableFile*)lpDrawItemStruct->itemData;
CKnownFile* pKnownFile = NULL;
if (file->IsKindOf(RUNTIME_CLASS(CKnownFile)))
pKnownFile = (CKnownFile*)file;
// ==> Design Settings [eWombat/Stulle] - Stulle
/*
//zz_fly :: we init it ourself :: from DolphinX :: start
BOOL bCtrlFocused = ((GetFocus() == this) || (GetStyle() & LVS_SHOWSELALWAYS));
dc.FillBackground((lpDrawItemStruct->itemState & ODS_SELECTED)?
((bCtrlFocused)?
m_crHighlight
:
m_crNoHighlight)
:
//Xman PowerRelease
((pKnownFile && pKnownFile->GetUpPriority()==PR_POWER)?
RGB(255,210,210)
:
//Xman end
m_crWindow));
dc.SetTextColor((lpDrawItemStruct->itemState & ODS_SELECTED) ? m_crHighlightText : m_crWindowText);
dc.SetFont(GetFont());
//zz_fly :: end
*/
// <== Design Settings [eWombat/Stulle] - Stulle
CHeaderCtrl *pHeaderCtrl = GetHeaderCtrl();
int iCount = pHeaderCtrl->GetItemCount();
cur_rec.right = cur_rec.left - sm_iLabelOffset;
cur_rec.left += sm_iIconOffset;
int iIconDrawWidth = theApp.GetSmallSytemIconSize().cx;
for (int iCurrent = 0; iCurrent < iCount; iCurrent++)
{
int iColumn = pHeaderCtrl->OrderToIndex(iCurrent);
if (!IsColumnHidden(iColumn))
{
UINT uDrawTextAlignment;
int iColumnWidth = GetColumnWidth(iColumn, uDrawTextAlignment);
cur_rec.right += iColumnWidth;
if (cur_rec.left < cur_rec.right && HaveIntersection(rcClient, cur_rec))
{
TCHAR szItem[1024];
GetItemDisplayText(file, iColumn, szItem, _countof(szItem));
switch (iColumn)
{
case 0: {
int iCheckboxDrawWidth = 0;
if (CheckBoxesEnabled())
{
int iState = (file == m_pHighlightedItem) ? CBS_UNCHECKEDHOT : CBS_UNCHECKEDNORMAL;
int iNoStyleState = (file == m_pHighlightedItem) ? DFCS_PUSHED : 0;
// no interacting with shell linked files or default shared directories
if ((file->IsShellLinked() && theApp.sharedfiles->ShouldBeShared(file->GetSharedDirectory(), file->GetFilePath(), false))
|| (theApp.sharedfiles->ShouldBeShared(file->GetSharedDirectory(), file->GetFilePath(), true)))
{
iState = CBS_CHECKEDDISABLED;
iNoStyleState = DFCS_CHECKED | DFCS_INACTIVE;
}
else if (theApp.sharedfiles->ShouldBeShared(file->GetSharedDirectory(), file->GetFilePath(), false))
{
iState = (file == m_pHighlightedItem) ? CBS_CHECKEDHOT : CBS_CHECKEDNORMAL;
iNoStyleState = (file == m_pHighlightedItem) ? (DFCS_PUSHED | DFCS_CHECKED) : DFCS_CHECKED;
}
// SLUGFILLER: SafeHash remove - removed installation dir unsharing
/*
else if (!thePrefs.IsShareableDirectory(file->GetPath()))
{
iState = CBS_DISABLED;
iNoStyleState = DFCS_INACTIVE;
}
*/
// SLUGFILLER: SafeHash remove - removed installation dir unsharing
HTHEME hTheme = (g_xpStyle.IsThemeActive() && g_xpStyle.IsAppThemed()) ? g_xpStyle.OpenThemeData(NULL, L"BUTTON") : NULL;
CRect recCheckBox = cur_rec;
recCheckBox.right = recCheckBox.left + 16;
recCheckBox.top += (cur_rec.Height() > 16) ? ((cur_rec.Height() - 16) / 2) : 0;
recCheckBox.bottom = recCheckBox.top + 16;
if (hTheme != NULL)
g_xpStyle.DrawThemeBackground(hTheme, dc.GetSafeHdc(), BP_CHECKBOX, iState, &recCheckBox, NULL);
else
dc.DrawFrameControl(&recCheckBox, DFC_BUTTON, DFCS_BUTTONCHECK | iNoStyleState | DFCS_FLAT);
cur_rec.left += 2 + 16;
iCheckboxDrawWidth += 2 + 16;
}
int iIconPosY = (cur_rec.Height() > theApp.GetSmallSytemIconSize().cy) ? ((cur_rec.Height() - theApp.GetSmallSytemIconSize().cy) / 2) : 0;
int iImage = theApp.GetFileTypeSystemImageIdx(file->GetFileName());
if (theApp.GetSystemImageList() != NULL)
::ImageList_Draw(theApp.GetSystemImageList(), iImage, dc.GetSafeHdc(), cur_rec.left, cur_rec.top + iIconPosY, ILD_TRANSPARENT);
if (!file->GetFileComment().IsEmpty() || file->GetFileRating())
m_ImageList.Draw(dc, 0, CPoint(cur_rec.left, cur_rec.top + iIconPosY), ILD_NORMAL | INDEXTOOVERLAYMASK(1));
cur_rec.left += iIconDrawWidth;
if (thePrefs.ShowRatingIndicator() && (file->HasComment() || file->HasRating() || file->IsKadCommentSearchRunning()))
{
m_ImageList.Draw(dc, file->UserRating(true) + 3, CPoint(cur_rec.left + 2, cur_rec.top + iIconPosY), ILD_NORMAL);
cur_rec.left += 2 + 16;
iIconDrawWidth += 2 + 16;
}
cur_rec.left += sm_iLabelOffset;
dc.DrawText(szItem, -1, &cur_rec, MLC_DT_TEXT | uDrawTextAlignment);
cur_rec.left -= iIconDrawWidth + iCheckboxDrawWidth;
cur_rec.right -= sm_iSubItemInset;
break;
}
case 8:
if (pKnownFile != NULL && pKnownFile->GetPartCount()) {
cur_rec.bottom--;
cur_rec.top++;
COLORREF crOldBackColor = dc->GetBkColor(); //Xman Code Improvement: FillSolidRect
pKnownFile->DrawShareStatusBar(dc, &cur_rec, false, thePrefs.UseFlatBar());
dc.SetBkColor(crOldBackColor); //Xman Code Improvement: FillSolidRect
cur_rec.bottom++;
cur_rec.top--;
}
break;
case 11:
if (pKnownFile == NULL)
break;
if (pKnownFile->GetPublishedED2K())
m_ImageList.Draw(dc, 1, cur_rec.TopLeft(), ILD_NORMAL);
if (IsSharedInKad(pKnownFile))
{
cur_rec.left += 16;
m_ImageList.Draw(dc, IsSharedInKad(pKnownFile) ? 2 : 0, cur_rec.TopLeft(), ILD_NORMAL);
cur_rec.left -= 16;
}
break;
// ==> Spread bars [Slugfiller/MorphXT] - Stulle
case 20:
if(pKnownFile == NULL)
break;
cur_rec.bottom--;
cur_rec.top++;
pKnownFile->statistic.DrawSpreadBar(dc,&cur_rec,thePrefs.UseFlatBar());
cur_rec.bottom++;
cur_rec.top--;
break;
// <== Spread bars [Slugfiller/MorphXT] - Stulle
default:
dc.DrawText(szItem, -1, &cur_rec, MLC_DT_TEXT | uDrawTextAlignment);
break;
}
}
cur_rec.left += iColumnWidth;
}
}
DrawFocusRect(dc, lpDrawItemStruct->rcItem, lpDrawItemStruct->itemState & ODS_FOCUS, bCtrlFocused, lpDrawItemStruct->itemState & ODS_SELECTED);
}
void CSharedFilesCtrl::GetItemDisplayText(const CShareableFile* file, int iSubItem, LPTSTR pszText, int cchTextMax) const
{
if (pszText == NULL || cchTextMax <= 0) {
ASSERT(0);
return;
}
pszText[0] = _T('\0');
switch (iSubItem)
{
case 0:
_tcsncpy(pszText, file->GetFileName(), cchTextMax);
break;
case 1:
_tcsncpy(pszText, CastItoXBytes(file->GetFileSize(), false, false), cchTextMax);
break;
case 2:
_tcsncpy(pszText, file->GetFileTypeDisplayStr(), cchTextMax);
break;
case 9:
_tcsncpy(pszText, file->GetPath(), cchTextMax);
pszText[cchTextMax - 1] = _T('\0');
PathRemoveBackslash(pszText);
break;
}
if (file->IsKindOf(RUNTIME_CLASS(CKnownFile))){
CKnownFile* pKnownFile = (CKnownFile*)file;
switch (iSubItem)
{
case 3:
// ==> PowerShare [ZZ/MorphXT] - Stulle
if(pKnownFile->GetPowerShared())
_sntprintf(pszText, cchTextMax, _T("%s %s"), GetResString(IDS_POWERSHARE_PREFIX), pKnownFile->GetUpPriorityDisplayString());
else
// <== PowerShare [ZZ/MorphXT] - Stulle
_tcsncpy(pszText, pKnownFile->GetUpPriorityDisplayString(), cchTextMax);
break;
case 4:
_tcsncpy(pszText, md4str(pKnownFile->GetFileHash()), cchTextMax);
break;
case 5:
_sntprintf(pszText, cchTextMax, _T("%u (%u)"), pKnownFile->statistic.GetRequests(), pKnownFile->statistic.GetAllTimeRequests());
break;
case 6:
_sntprintf(pszText, cchTextMax, _T("%u (%u)"), pKnownFile->statistic.GetAccepts(), pKnownFile->statistic.GetAllTimeAccepts());
break;
case 7:
_sntprintf(pszText, cchTextMax, _T("%s (%s)"), CastItoXBytes(pKnownFile->statistic.GetTransferred(), false, false), CastItoXBytes(pKnownFile->statistic.GetAllTimeTransferred(), false, false));
break;
case 8:
_sntprintf(pszText, cchTextMax, _T("%s: %u"), GetResString(IDS_SHARED_STATUS), pKnownFile->GetPartCount());
break;
case 10:
//Xman show virtual sources (morph) + virtualUploadsources
/*
if (pKnownFile->m_nCompleteSourcesCountLo == pKnownFile->m_nCompleteSourcesCountHi)
_sntprintf(pszText, cchTextMax, _T("%u"), pKnownFile->m_nCompleteSourcesCountLo);
else if (pKnownFile->m_nCompleteSourcesCountLo == 0)
_sntprintf(pszText, cchTextMax, _T("< %u"), pKnownFile->m_nCompleteSourcesCountHi);
else
_sntprintf(pszText, cchTextMax, _T("%u - %u"), pKnownFile->m_nCompleteSourcesCountLo, pKnownFile->m_nCompleteSourcesCountHi);
*/
if(pKnownFile->IsPartFile()==false || thePrefs.UseAdvancedAutoPtio()==false)
{
if (pKnownFile->m_nCompleteSourcesCountLo == pKnownFile->m_nCompleteSourcesCountHi)
_sntprintf(pszText, cchTextMax, _T("%u (%u)"), pKnownFile->m_nCompleteSourcesCountLo, pKnownFile->m_nVirtualCompleteSourcesCount);
else if (pKnownFile->m_nCompleteSourcesCountLo == 0)
_sntprintf(pszText, cchTextMax, _T("< %u (%u)"), pKnownFile->m_nCompleteSourcesCountHi, pKnownFile->m_nVirtualCompleteSourcesCount);
else
_sntprintf(pszText, cchTextMax, _T("%u - %u (%u)"), pKnownFile->m_nCompleteSourcesCountLo, pKnownFile->m_nCompleteSourcesCountHi, pKnownFile->m_nVirtualCompleteSourcesCount);
}
else
{
//Xman advanced upload-priority
if (pKnownFile->m_nCompleteSourcesCountLo == pKnownFile->m_nCompleteSourcesCountHi)
_sntprintf(pszText, cchTextMax, _T("%u (%u/%u)"), pKnownFile->m_nCompleteSourcesCountLo, pKnownFile->m_nVirtualCompleteSourcesCount, pKnownFile->m_nVirtualUploadSources);
else if (pKnownFile->m_nCompleteSourcesCountLo == 0)
_sntprintf(pszText, cchTextMax, _T("< %u (%u/%u)"), pKnownFile->m_nCompleteSourcesCountHi, pKnownFile->m_nVirtualCompleteSourcesCount, pKnownFile->m_nVirtualUploadSources);
else
_sntprintf(pszText, cchTextMax, _T("%u - %u (%u/%u)"), pKnownFile->m_nCompleteSourcesCountLo, pKnownFile->m_nCompleteSourcesCountHi, pKnownFile->m_nVirtualCompleteSourcesCount, pKnownFile->m_nVirtualUploadSources);
//Xman end
}
//Xman end
break;
case 11:
_sntprintf(pszText, cchTextMax, _T("%s|%s"), GetResString(pKnownFile->GetPublishedED2K() ? IDS_YES : IDS_NO), GetResString(IsSharedInKad(pKnownFile) ? IDS_YES : IDS_NO));
break;
case 12:
_tcsncpy(pszText, pKnownFile->GetStrTagValue(FT_MEDIA_ARTIST), cchTextMax);
break;
case 13:
_tcsncpy(pszText, pKnownFile->GetStrTagValue(FT_MEDIA_ALBUM), cchTextMax);
break;
case 14:
_tcsncpy(pszText, pKnownFile->GetStrTagValue(FT_MEDIA_TITLE), cchTextMax);
break;
case 15:{
uint32 nMediaLength = pKnownFile->GetIntTagValue(FT_MEDIA_LENGTH);
if (nMediaLength){
CString buffer;
SecToTimeLength(nMediaLength, buffer);
_tcsncpy(pszText, buffer, cchTextMax);
}
break;
}
case 16:{
uint32 nBitrate = pKnownFile->GetIntTagValue(FT_MEDIA_BITRATE);
if (nBitrate)
_sntprintf(pszText, cchTextMax, _T("%u %s"), nBitrate, GetResString(IDS_KBITSSEC));
break;
}
case 17:
_tcsncpy(pszText, GetCodecDisplayName(pKnownFile->GetStrTagValue(FT_MEDIA_CODEC)), cchTextMax);
break;
//Xman see OnUploadqueue
case 18:
_sntprintf(pszText, cchTextMax, _T("%u"),pKnownFile->GetOnUploadqueue());
break;
//Xman end
//Xman advanced upload-priority
case 19:
{
if(thePrefs.UseAdvancedAutoPtio())
_sntprintf(pszText, cchTextMax, _T("%.0f%% / %.0f%%"), pKnownFile->CalculateUploadPriorityPercent(), pKnownFile->statistic.GetAllTimeTransferred()/(float)pKnownFile->GetFileSize()*100);
else
_sntprintf(pszText, cchTextMax, _T("%.0f%%"), pKnownFile->statistic.GetAllTimeTransferred()/(float)pKnownFile->GetFileSize()*100);
break;
}
//Xman end
// ==> Spread bars [Slugfiller/MorphXT] - Stulle
case 20:
_tcsncpy(pszText, _T("Spreadhars"), cchTextMax);
break;
case 21:
_sntprintf(pszText, cchTextMax, _T("%.2f"),pKnownFile->statistic.GetSpreadSortValue());
break;
case 22:
if (pKnownFile->GetFileSize()>(uint64)0)
_sntprintf(pszText, cchTextMax, _T("%.2f"),((double)pKnownFile->statistic.GetAllTimeTransferred())/((double)pKnownFile->GetFileSize()));
else
_sntprintf(pszText, cchTextMax, _T("%.2f"),0.0f);
break;
case 23:
_sntprintf(pszText, cchTextMax, _T("%.2f"),pKnownFile->statistic.GetFullSpreadCount());
break;
// <== Spread bars [Slugfiller/MorphXT] - Stulle
// ==> push rare file - Stulle
case 24:
_sntprintf(pszText, cchTextMax, _T("%.1f"),pKnownFile->GetFileRatio());
break;
// <== push rare file - Stulle
// ==> HideOS & SOTN [Slugfiller/ MorphXT] - Stulle
case 25:
{
CString buffer;
UINT hideOSInWork = pKnownFile->HideOSInWork();
buffer = _T("[") + GetResString((hideOSInWork>0)?IDS_POWERSHARE_ON_LABEL:IDS_POWERSHARE_OFF_LABEL) + _T("] ");
if(pKnownFile->GetHideOS()<0)
buffer.Append(_T(" ") + ((CString)GetResString(IDS_DEFAULT)).Left(1) + _T(". "));
hideOSInWork = (pKnownFile->GetHideOS()>=0)?pKnownFile->GetHideOS():thePrefs.GetHideOvershares();
if (hideOSInWork>0)
buffer.AppendFormat(_T("%i"), hideOSInWork);
else
buffer.AppendFormat(_T("%s"), GetResString(IDS_DISABLED));
if (pKnownFile->GetSelectiveChunk()>=0){
if (pKnownFile->GetSelectiveChunk())
buffer.Append(_T(" + S"));
}else
if (thePrefs.IsSelectiveShareEnabled())
buffer.Append(_T(" + ") + ((CString)GetResString(IDS_DEFAULT)).Left(1) + _T(". S"));
_tcsncpy(pszText, buffer, cchTextMax);
break;
}
case 26:
if(pKnownFile->GetShareOnlyTheNeed()>=0) {
if (pKnownFile->GetShareOnlyTheNeed())
_sntprintf(pszText, cchTextMax, _T("%i"), pKnownFile->GetShareOnlyTheNeed());
else
_tcsncpy(pszText, GetResString(IDS_DISABLED), cchTextMax);
} else
_sntprintf(pszText, cchTextMax, _T("%s. %s"), ((CString)GetResString(IDS_DEFAULT)).Left(1), GetResString((thePrefs.GetShareOnlyTheNeed()>0)?IDS_ENABLED:IDS_DISABLED));
break;
// <== HideOS & SOTN [Slugfiller/ MorphXT] - Stulle
// ==> PowerShare [ZZ/MorphXT] - Stulle
case 27:
{
CString buffer;
int powersharemode;
bool powershared = pKnownFile->GetPowerShared();
buffer = _T("[") + GetResString((powershared)?IDS_POWERSHARE_ON_LABEL:IDS_POWERSHARE_OFF_LABEL) + _T("] ");
if (pKnownFile->GetPowerSharedMode()>=0)
powersharemode = pKnownFile->GetPowerSharedMode();
else {
powersharemode = thePrefs.GetPowerShareMode();
buffer.Append(_T(" ") + ((CString)GetResString(IDS_DEFAULT)).Left(1) + _T(". "));
} //
if(powersharemode == 2)
buffer.Append(GetResString(IDS_POWERSHARE_AUTO_LABEL));
else if (powersharemode == 1)
buffer.Append(GetResString(IDS_POWERSHARE_ACTIVATED_LABEL));
else if (powersharemode == 3) {
buffer.Append(GetResString(IDS_POWERSHARE_LIMITED));
if (pKnownFile->GetPowerShareLimit()<0)
buffer.AppendFormat(_T(" %s. %i"), ((CString)GetResString(IDS_DEFAULT)).Left(1), thePrefs.GetPowerShareLimit());
else
buffer.AppendFormat(_T(" %i"), pKnownFile->GetPowerShareLimit());
// ==> Limit PS by amount of data uploaded - Stulle
if (pKnownFile->GetPsAmountLimit()<0)
buffer.AppendFormat(_T(" %s. %i%%"), ((CString)GetResString(IDS_DEFAULT)).Left(1), thePrefs.GetPsAmountLimit());
else
buffer.AppendFormat(_T(" %i%%"), pKnownFile->GetPsAmountLimit());
// <== Limit PS by amount of data uploaded - Stulle
}
else
buffer.Append(GetResString(IDS_POWERSHARE_DISABLED_LABEL));
buffer.Append(_T(" ("));
if (pKnownFile->GetPowerShareAuto())
buffer.Append(GetResString(IDS_POWERSHARE_ADVISED_LABEL));
else if (pKnownFile->GetPowerShareLimited() && (powersharemode == 3))
buffer.Append(GetResString(IDS_POWERSHARE_LIMITED));
else if (pKnownFile->GetPowerShareAuthorized())
buffer.Append(GetResString(IDS_POWERSHARE_AUTHORIZED_LABEL));
else
buffer.Append(GetResString(IDS_POWERSHARE_DENIED_LABEL));
buffer.Append(_T(")"));
_tcsncpy(pszText, buffer, cchTextMax);
}
break;
// <== PowerShare [ZZ/MorphXT] - Stulle
}
}
pszText[cchTextMax - 1] = _T('\0');
}
void CSharedFilesCtrl::OnContextMenu(CWnd* /*pWnd*/, CPoint point)
{
// get merged settings
bool bFirstItem = true;
bool bContainsShareableFiles = false;
bool bContainsOnlyShareableFile = true;
bool bContainsUnshareableFile = false;
int iSelectedItems = GetSelectedCount();
int iCompleteFileSelected = -1;
UINT uPrioMenuItem = 0;
// ==> HideOS & SOTN [Slugfiller/ MorphXT] - Stulle
int iHideOS = -1;
UINT uHideOSMenuItem = 0;
UINT uSelectiveChunkMenuItem = 0;
UINT uShareOnlyTheNeedMenuItem = 0;
CString buffer;
// <== HideOS & SOTN [Slugfiller/ MorphXT] - Stulle
// ==> PowerShare [ZZ/MorphXT] - Stulle
int iPowerShareLimit = -1;
UINT uPowershareMenuItem = 0;
UINT uPowerShareLimitMenuItem = 0;
// <== PowerShare [ZZ/MorphXT] - Stulle
// ==> Limit PS by amount of data uploaded [Stulle] - Stulle
int iPsAmountLimit = -1;
UINT uPsAmountLimitMenuItem = 0;
// <== Limit PS by amount of data uploaded [Stulle] - Stulle
const CShareableFile* pSingleSelFile = NULL;
POSITION pos = GetFirstSelectedItemPosition();
while (pos)
{
const CShareableFile* pFile = (CShareableFile*)GetItemData(GetNextSelectedItem(pos));
if (bFirstItem)
pSingleSelFile = pFile;
else
pSingleSelFile = NULL;
int iCurCompleteFile = pFile->IsPartFile() ? 0 : 1;
if (bFirstItem)
iCompleteFileSelected = iCurCompleteFile;
else if (iCompleteFileSelected != iCurCompleteFile)
iCompleteFileSelected = -1;
bContainsUnshareableFile = !pFile->IsShellLinked() && !pFile->IsPartFile() && (bContainsUnshareableFile || (theApp.sharedfiles->ShouldBeShared(pFile->GetSharedDirectory(), pFile->GetFilePath(), false)
&& !theApp.sharedfiles->ShouldBeShared(pFile->GetSharedDirectory(), pFile->GetFilePath(), true)));
if (pFile->IsKindOf(RUNTIME_CLASS(CKnownFile)))
{
bContainsOnlyShareableFile = false;
UINT uCurPrioMenuItem = 0;
if (((CKnownFile*)pFile)->IsAutoUpPriority())
uCurPrioMenuItem = MP_PRIOAUTO;
else if (((CKnownFile*)pFile)->GetUpPriority() == PR_VERYLOW)
uCurPrioMenuItem = MP_PRIOVERYLOW;
else if (((CKnownFile*)pFile)->GetUpPriority() == PR_LOW)
uCurPrioMenuItem = MP_PRIOLOW;
else if (((CKnownFile*)pFile)->GetUpPriority() == PR_NORMAL)
uCurPrioMenuItem = MP_PRIONORMAL;
else if (((CKnownFile*)pFile)->GetUpPriority() == PR_HIGH)
uCurPrioMenuItem = MP_PRIOHIGH;
else if (((CKnownFile*)pFile)->GetUpPriority() == PR_VERYHIGH)
uCurPrioMenuItem = MP_PRIOVERYHIGH;
//Xman PowerRelease
else if (((CKnownFile*)pFile)->GetUpPriority() == PR_POWER)
uCurPrioMenuItem = MP_PRIOPOWER;
//Xman end
else
ASSERT(0);
if (bFirstItem)
uPrioMenuItem = uCurPrioMenuItem;
else if (uPrioMenuItem != uCurPrioMenuItem)
uPrioMenuItem = 0;
// ==> HideOS & SOTN [Slugfiller/ MorphXT] - Stulle
UINT uCurHideOSMenuItem = 0;
int iCurHideOS = ((CKnownFile*)pFile)->GetHideOS();
if (iCurHideOS == -1)
uCurHideOSMenuItem = MP_HIDEOS_DEFAULT;
else
uCurHideOSMenuItem = MP_HIDEOS_SET;
if (bFirstItem)
{
uHideOSMenuItem = uCurHideOSMenuItem;
iHideOS = iCurHideOS;
}
else if (uHideOSMenuItem != uCurHideOSMenuItem || iHideOS != iCurHideOS)
{
uHideOSMenuItem = 0;
iHideOS = -1;
}
UINT uCurSelectiveChunkMenuItem = 0;
if (((CKnownFile*)pFile)->GetSelectiveChunk() == -1)
uCurSelectiveChunkMenuItem = MP_SELECTIVE_CHUNK;
else
uCurSelectiveChunkMenuItem = MP_SELECTIVE_CHUNK+1 + ((CKnownFile*)pFile)->GetSelectiveChunk();
if (bFirstItem)
uSelectiveChunkMenuItem = uCurSelectiveChunkMenuItem;
else if (uSelectiveChunkMenuItem != uCurSelectiveChunkMenuItem)
uSelectiveChunkMenuItem = 0;
UINT uCurShareOnlyTheNeedMenuItem = 0;
if (((CKnownFile*)pFile)->GetShareOnlyTheNeed() == -1)
uCurShareOnlyTheNeedMenuItem = MP_SHAREONLYTHENEED;
else
uCurShareOnlyTheNeedMenuItem = MP_SHAREONLYTHENEED+1 + ((CKnownFile*)pFile)->GetShareOnlyTheNeed();
if (bFirstItem)
uShareOnlyTheNeedMenuItem = uCurShareOnlyTheNeedMenuItem ;
else if (uShareOnlyTheNeedMenuItem != uCurShareOnlyTheNeedMenuItem)
uShareOnlyTheNeedMenuItem = 0;
// <== HideOS & SOTN [Slugfiller/ MorphXT] - Stulle
// ==> PowerShare [ZZ/MorphXT] - Stulle
UINT uCurPowershareMenuItem = 0;
if (((CKnownFile*)pFile)->GetPowerSharedMode()==-1)
uCurPowershareMenuItem = MP_POWERSHARE_DEFAULT;
else
uCurPowershareMenuItem = MP_POWERSHARE_DEFAULT+1 + ((CKnownFile*)pFile)->GetPowerSharedMode();
if (bFirstItem)
uPowershareMenuItem = uCurPowershareMenuItem;
else if (uPowershareMenuItem != uCurPowershareMenuItem)
uPowershareMenuItem = 0;
UINT uCurPowerShareLimitMenuItem = 0;
int iCurPowerShareLimit = ((CKnownFile*)pFile)->GetPowerShareLimit();
if (iCurPowerShareLimit==-1)
uCurPowerShareLimitMenuItem = MP_POWERSHARE_LIMIT;
else
uCurPowerShareLimitMenuItem = MP_POWERSHARE_LIMIT_SET;
if (bFirstItem)
{
uPowerShareLimitMenuItem = uCurPowerShareLimitMenuItem;
iPowerShareLimit = iCurPowerShareLimit;
}
else if (uPowerShareLimitMenuItem != uCurPowerShareLimitMenuItem || iPowerShareLimit != iCurPowerShareLimit)
{
uPowerShareLimitMenuItem = 0;
iPowerShareLimit = -1;
}
// <== PowerShare [ZZ/MorphXT] - Stulle
// ==> Limit PS by amount of data uploaded [Stulle] - Stulle
UINT uCurPsAmountLimitMenuItem = 0;
int iCurPsAmountLimit = ((CKnownFile*)pFile)->GetPsAmountLimit();
if (iCurPsAmountLimit==-1)
uCurPsAmountLimitMenuItem = MP_PS_AMOUNT_LIMIT;
else
uCurPsAmountLimitMenuItem = MP_PS_AMOUNT_LIMIT_SET;
if (bFirstItem)
{
uPsAmountLimitMenuItem = uCurPsAmountLimitMenuItem;
iPsAmountLimit = iCurPsAmountLimit;
}
else if (uPsAmountLimitMenuItem != uCurPsAmountLimitMenuItem || iPsAmountLimit != iCurPsAmountLimit)
{
uPsAmountLimitMenuItem = 0;
iPsAmountLimit = -1;
}
// <== Limit PS by amount of data uploaded [Stulle] - Stulle
}
else
bContainsShareableFiles = true;
bFirstItem = false;
}
m_SharedFilesMenu.EnableMenuItem((UINT_PTR)m_PrioMenu.m_hMenu, (!bContainsShareableFiles && iSelectedItems > 0) ? MF_ENABLED : MF_GRAYED);
//Xman PowerRelease
/*
m_PrioMenu.CheckMenuRadioItem(MP_PRIOVERYLOW, MP_PRIOAUTO, uPrioMenuItem, 0);
*/
m_PrioMenu.CheckMenuRadioItem(MP_PRIOVERYLOW, MP_PRIOPOWER, uPrioMenuItem, 0);
//Xman end
bool bSingleCompleteFileSelected = (iSelectedItems == 1 && (iCompleteFileSelected == 1 || bContainsOnlyShareableFile));
m_SharedFilesMenu.EnableMenuItem(MP_OPEN, bSingleCompleteFileSelected ? MF_ENABLED : MF_GRAYED);
UINT uInsertedMenuItem = 0;
static const TCHAR _szSkinPkgSuffix1[] = _T(".") EMULSKIN_BASEEXT _T(".zip");
static const TCHAR _szSkinPkgSuffix2[] = _T(".") EMULSKIN_BASEEXT _T(".rar");
if (bSingleCompleteFileSelected
&& pSingleSelFile
&& ( pSingleSelFile->GetFilePath().Right(ARRSIZE(_szSkinPkgSuffix1)-1).CompareNoCase(_szSkinPkgSuffix1) == 0
|| pSingleSelFile->GetFilePath().Right(ARRSIZE(_szSkinPkgSuffix2)-1).CompareNoCase(_szSkinPkgSuffix2) == 0))
{
MENUITEMINFO mii = {0};
mii.cbSize = sizeof mii;
mii.fMask = MIIM_TYPE | MIIM_STATE | MIIM_ID;
mii.fType = MFT_STRING;
mii.fState = MFS_ENABLED;
mii.wID = MP_INSTALL_SKIN;
CString strBuff(GetResString(IDS_INSTALL_SKIN));
mii.dwTypeData = const_cast<LPTSTR>((LPCTSTR)strBuff);
if (::InsertMenuItem(m_SharedFilesMenu, MP_OPENFOLDER, FALSE, &mii))
uInsertedMenuItem = mii.wID;
}
//Xman PowerRelease
m_SharedFilesMenu.EnableMenuItem(MP_PRIOPOWER, (!bContainsShareableFiles && iCompleteFileSelected > 0) ? MF_ENABLED : MF_GRAYED);
//Xman end
m_SharedFilesMenu.EnableMenuItem(MP_OPENFOLDER, bSingleCompleteFileSelected ? MF_ENABLED : MF_GRAYED);
m_SharedFilesMenu.EnableMenuItem(MP_RENAME, (!bContainsShareableFiles && bSingleCompleteFileSelected) ? MF_ENABLED : MF_GRAYED);
m_SharedFilesMenu.EnableMenuItem(MP_REMOVE, iCompleteFileSelected > 0 ? MF_ENABLED : MF_GRAYED);
m_SharedFilesMenu.EnableMenuItem(MP_UNSHAREFILE, bContainsUnshareableFile ? MF_ENABLED : MF_GRAYED);
m_SharedFilesMenu.SetDefaultItem(bSingleCompleteFileSelected ? MP_OPEN : -1);
m_SharedFilesMenu.EnableMenuItem(MP_CMT, (!bContainsShareableFiles && iSelectedItems > 0) ? MF_ENABLED : MF_GRAYED);
m_SharedFilesMenu.EnableMenuItem(MP_DETAIL, iSelectedItems > 0 ? MF_ENABLED : MF_GRAYED);
m_SharedFilesMenu.EnableMenuItem(thePrefs.GetShowCopyEd2kLinkCmd() ? MP_GETED2KLINK : MP_SHOWED2KLINK, (!bContainsOnlyShareableFile && iSelectedItems > 0) ? MF_ENABLED : MF_GRAYED);
// ==> HideOS & SOTN [Slugfiller/ MorphXT] - Stulle
m_SharedFilesMenu.EnableMenuItem((UINT_PTR)m_HideOSMenu.m_hMenu, (iSelectedItems > 0 && iCompleteFileSelected > 0) ? MF_ENABLED : MF_GRAYED);
m_SharedFilesMenu.EnableMenuItem((UINT_PTR)m_SelectiveChunkMenu.m_hMenu, iSelectedItems > 0 ? MF_ENABLED : MF_GRAYED);
if (thePrefs.GetHideOvershares()==0)
buffer.Format(_T(" (%s)"),GetResString(IDS_DISABLED));
else
buffer.Format(_T(" (%u)"),thePrefs.GetHideOvershares());
// ==> XP Style Menu [Xanatos] - Stulle
/*
m_HideOSMenu.ModifyMenu(MP_HIDEOS_DEFAULT, MF_STRING,MP_HIDEOS_DEFAULT, GetResString(IDS_DEFAULT) + buffer);
*/
m_HideOSMenu.RemoveMenu(MP_HIDEOS_DEFAULT,MF_BYCOMMAND);
m_HideOSMenu.InsertMenu(1,MF_STRING|MF_BYPOSITION,MP_HIDEOS_DEFAULT,GetResString(IDS_DEFAULT) + buffer);
// <== XP Style Menu [Xanatos] - Stulle
if (iHideOS==-1)
buffer = GetResString(IDS_EDIT);
else if (iHideOS==0)
buffer = GetResString(IDS_DISABLED);
else
buffer.Format(_T("%i"), iHideOS);
// ==> XP Style Menu [Xanatos] - Stulle
/*
m_HideOSMenu.ModifyMenu(MP_HIDEOS_SET, MF_STRING,MP_HIDEOS_SET, buffer);
*/
m_HideOSMenu.RemoveMenu(MP_HIDEOS_SET,MF_BYCOMMAND);
m_HideOSMenu.InsertMenu(2,MF_STRING|MF_BYPOSITION,MP_HIDEOS_SET,buffer);
// <== XP Style Menu [Xanatos] - Stulle
m_HideOSMenu.CheckMenuRadioItem(MP_HIDEOS_DEFAULT, MP_HIDEOS_SET, uHideOSMenuItem, 0);
buffer.Format(_T(" (%s)"),thePrefs.IsSelectiveShareEnabled()?GetResString(IDS_ENABLED):GetResString(IDS_DISABLED));
// ==> XP Style Menu [Xanatos] - Stulle
/*
m_SelectiveChunkMenu.ModifyMenu(MP_SELECTIVE_CHUNK, MF_STRING, MP_SELECTIVE_CHUNK, GetResString(IDS_DEFAULT) + buffer);
*/
m_SelectiveChunkMenu.RemoveMenu(MP_SELECTIVE_CHUNK,MF_BYCOMMAND);
m_SelectiveChunkMenu.InsertMenu(1,MF_STRING|MF_BYPOSITION,MP_SELECTIVE_CHUNK,GetResString(IDS_DEFAULT) + buffer);
// <== XP Style Menu [Xanatos] - Stulle
m_SelectiveChunkMenu.CheckMenuRadioItem(MP_SELECTIVE_CHUNK, MP_SELECTIVE_CHUNK_1, uSelectiveChunkMenuItem, 0);
m_SharedFilesMenu.EnableMenuItem((UINT_PTR)m_ShareOnlyTheNeedMenu.m_hMenu, (iSelectedItems > 0 && iCompleteFileSelected > 0) ? MF_ENABLED : MF_GRAYED);
buffer.Format(_T(" (%s)"),thePrefs.GetShareOnlyTheNeed()?GetResString(IDS_ENABLED):GetResString(IDS_DISABLED));
// ==> XP Style Menu [Xanatos] - Stulle
/*
m_ShareOnlyTheNeedMenu.ModifyMenu(MP_SHAREONLYTHENEED, MF_STRING, MP_SHAREONLYTHENEED, GetResString(IDS_DEFAULT) + buffer);
*/
m_ShareOnlyTheNeedMenu.RemoveMenu(MP_SHAREONLYTHENEED,MF_BYCOMMAND);
m_ShareOnlyTheNeedMenu.InsertMenu(1,MF_STRING|MF_BYPOSITION,MP_SHAREONLYTHENEED,GetResString(IDS_DEFAULT) + buffer);
// <== XP Style Menu [Xanatos] - Stulle
m_ShareOnlyTheNeedMenu.CheckMenuRadioItem(MP_SHAREONLYTHENEED, MP_SHAREONLYTHENEED_1, uShareOnlyTheNeedMenuItem, 0);
// <== HideOS & SOTN [Slugfiller/ MorphXT] - Stulle
m_SharedFilesMenu.EnableMenuItem(MP_SPREADBAR_RESET, iSelectedItems > 0 ? MF_ENABLED : MF_GRAYED); // Spread bars [Slugfiller/MorphXT] - Stulle
// ==> PowerShare [ZZ/MorphXT] - Stulle
m_SharedFilesMenu.EnableMenuItem((UINT_PTR)m_PowershareMenu.m_hMenu, (iSelectedItems > 0 && iCompleteFileSelected > 0) ? MF_ENABLED : MF_GRAYED);
switch (thePrefs.GetPowerShareMode()){
case 0:
buffer.Format(_T(" (%s)"),GetResString(IDS_POWERSHARE_DISABLED));
break;
case 1:
buffer.Format(_T(" (%s)"),GetResString(IDS_POWERSHARE_ACTIVATED));
break;
case 2:
buffer.Format(_T(" (%s)"),GetResString(IDS_POWERSHARE_AUTO));
break;
case 3:
buffer.Format(_T(" (%s)"),GetResString(IDS_POWERSHARE_LIMITED));
break;
default:
buffer = _T(" (?)");
break;
}
// ==> XP Style Menu [Xanatos] - Stulle
/*
m_PowershareMenu.ModifyMenu(MP_POWERSHARE_DEFAULT, MF_STRING,MP_POWERSHARE_DEFAULT, GetResString(IDS_DEFAULT) + buffer);
*/
m_PowershareMenu.RemoveMenu(MP_POWERSHARE_DEFAULT,MF_BYCOMMAND);
m_PowershareMenu.InsertMenu(1,MF_STRING|MF_BYPOSITION,MP_POWERSHARE_DEFAULT,GetResString(IDS_DEFAULT) + buffer);
// <== XP Style Menu [Xanatos] - Stulle
m_PowershareMenu.CheckMenuRadioItem(MP_POWERSHARE_DEFAULT, MP_POWERSHARE_LIMITED, uPowershareMenuItem, 0);
m_PowershareMenu.EnableMenuItem((UINT_PTR)m_PowerShareLimitMenu.m_hMenu, iSelectedItems > 0 ? MF_ENABLED : MF_GRAYED);
if (thePrefs.GetPowerShareLimit()==0)
buffer.Format(_T(" (%s)"),GetResString(IDS_DISABLED));
else
buffer.Format(_T(" (%u)"),thePrefs.GetPowerShareLimit());
// ==> XP Style Menu [Xanatos] - Stulle
/*
m_PowerShareLimitMenu.ModifyMenu(MP_POWERSHARE_LIMIT, MF_STRING,MP_POWERSHARE_LIMIT, GetResString(IDS_DEFAULT) + buffer);
*/
m_PowerShareLimitMenu.RemoveMenu(MP_POWERSHARE_LIMIT,MF_BYCOMMAND);
m_PowerShareLimitMenu.InsertMenu(1,MF_STRING|MF_BYPOSITION,MP_POWERSHARE_LIMIT,GetResString(IDS_DEFAULT) + buffer);
// <== XP Style Menu [Xanatos] - Stulle
if (iPowerShareLimit==-1)
buffer = GetResString(IDS_EDIT);
else if (iPowerShareLimit==0)
buffer = GetResString(IDS_DISABLED);
else
buffer.Format(_T("%i"),iPowerShareLimit);
// ==> XP Style Menu [Xanatos] - Stulle
/*
m_PowerShareLimitMenu.ModifyMenu(MP_POWERSHARE_LIMIT_SET, MF_STRING,MP_POWERSHARE_LIMIT_SET, buffer);
*/
m_PowerShareLimitMenu.RemoveMenu(MP_POWERSHARE_LIMIT_SET,MF_BYCOMMAND);
m_PowerShareLimitMenu.InsertMenu(2,MF_STRING|MF_BYPOSITION,MP_POWERSHARE_LIMIT_SET,buffer);
// <== XP Style Menu [Xanatos] - Stulle
m_PowerShareLimitMenu.CheckMenuRadioItem(MP_POWERSHARE_LIMIT, MP_POWERSHARE_LIMIT_SET, uPowerShareLimitMenuItem, 0);
// <== PowerShare [ZZ/MorphXT] - Stulle
// ==> Limit PS by amount of data uploaded [Stulle] - Stulle
m_PowershareMenu.EnableMenuItem((UINT_PTR)m_PsAmountLimitMenu.m_hMenu, iSelectedItems > 0 ? MF_ENABLED : MF_GRAYED);
if (iPsAmountLimit==0)
buffer.Format(_T(" (%s)"),GetResString(IDS_DISABLED));
else
buffer.Format(_T(" (%i%%)"),thePrefs.GetPsAmountLimit());
// ==> XP Style Menu [Xanatos] - Stulle
/*
m_PsAmountLimitMenu.ModifyMenu(MP_PS_AMOUNT_LIMIT, MF_STRING,MP_PS_AMOUNT_LIMIT, GetResString(IDS_DEFAULT) + buffer);
*/
m_PsAmountLimitMenu.RemoveMenu(MP_PS_AMOUNT_LIMIT,MF_BYCOMMAND);
m_PsAmountLimitMenu.InsertMenu(1,MF_STRING|MF_BYPOSITION,MP_PS_AMOUNT_LIMIT,GetResString(IDS_DEFAULT) + buffer);
// <== XP Style Menu [Xanatos] - Stulle
if (iPsAmountLimit==-1)
buffer = GetResString(IDS_EDIT);
else if (iPsAmountLimit==0)
buffer = GetResString(IDS_DISABLED);
else
buffer.Format(_T("%i%%"),iPsAmountLimit);
// ==> XP Style Menu [Xanatos] - Stulle
/*
m_PsAmountLimitMenu.ModifyMenu(MP_PS_AMOUNT_LIMIT_SET, MF_STRING,MP_PS_AMOUNT_LIMIT_SET, buffer);
*/
m_PsAmountLimitMenu.RemoveMenu(MP_PS_AMOUNT_LIMIT_SET,MF_BYCOMMAND);
m_PsAmountLimitMenu.InsertMenu(2,MF_STRING|MF_BYPOSITION,MP_PS_AMOUNT_LIMIT_SET,buffer);
// <== XP Style Menu [Xanatos] - Stulle
m_PsAmountLimitMenu.CheckMenuRadioItem(MP_PS_AMOUNT_LIMIT, MP_PS_AMOUNT_LIMIT_SET, uPsAmountLimitMenuItem, 0);
// <== Limit PS by amount of data uploaded [Stulle] - Stulle
// ==> Copy feedback feature [MorphXT] - Stulle
/*
// Xman: IcEcRacKer Copy UL-feedback
m_SharedFilesMenu.EnableMenuItem(MP_ULFEEDBACK, (!bContainsShareableFiles && iSelectedItems > 0) ? MF_ENABLED : MF_GRAYED);
//Xman end
*/
m_SharedFilesMenu.EnableMenuItem(MP_COPYFEEDBACK, (!bContainsShareableFiles && iSelectedItems > 0) ? MF_ENABLED : MF_GRAYED);
m_SharedFilesMenu.EnableMenuItem(MP_COPYFEEDBACK_US, (!bContainsShareableFiles && iSelectedItems > 0) ? MF_ENABLED : MF_GRAYED);
// <== Copy feedback feature [MorphXT] - Stulle
m_SharedFilesMenu.EnableMenuItem(MP_FIND, GetItemCount() > 0 ? MF_ENABLED : MF_GRAYED);
//Xman Mass Rename (Morph)
m_SharedFilesMenu.EnableMenuItem(MP_MASSRENAME, (!bContainsShareableFiles && iSelectedItems > 0) ? MF_ENABLED : MF_GRAYED);
//Xman end
m_CollectionsMenu.EnableMenuItem(MP_MODIFYCOLLECTION, (!bContainsShareableFiles && pSingleSelFile != NULL && ((CKnownFile*)pSingleSelFile)->m_pCollection != NULL ) ? MF_ENABLED : MF_GRAYED);
m_CollectionsMenu.EnableMenuItem(MP_VIEWCOLLECTION, (!bContainsShareableFiles && pSingleSelFile != NULL && ((CKnownFile*)pSingleSelFile)->m_pCollection != NULL ) ? MF_ENABLED : MF_GRAYED);
m_CollectionsMenu.EnableMenuItem(MP_SEARCHAUTHOR, (!bContainsShareableFiles && pSingleSelFile != NULL && ((CKnownFile*)pSingleSelFile)->m_pCollection != NULL
&& !((CKnownFile*)pSingleSelFile)->m_pCollection->GetAuthorKeyHashString().IsEmpty()) ? MF_ENABLED : MF_GRAYED);
#if defined(_DEBUG)
if (thePrefs.IsExtControlsEnabled()){
//JOHNTODO: Not for release as we need kad lowID users in the network to see how well this work work. Also, we do not support these links yet.
if (iSelectedItems > 0 && theApp.IsConnected() && theApp.IsFirewalled() && theApp.clientlist->GetBuddy())
m_SharedFilesMenu.EnableMenuItem(MP_GETKADSOURCELINK, MF_ENABLED);
else
m_SharedFilesMenu.EnableMenuItem(MP_GETKADSOURCELINK, MF_GRAYED);
}
#endif
m_SharedFilesMenu.EnableMenuItem(Irc_SetSendLink, (!bContainsOnlyShareableFile && iSelectedItems == 1 && theApp.emuledlg->ircwnd->IsConnected()) ? MF_ENABLED : MF_GRAYED);
CTitleMenu WebMenu;
WebMenu.CreateMenu();
// ==> XP Style Menu [Xanatos] - Stulle
/*
WebMenu.AddMenuTitle(NULL, true);
*/
WebMenu.AddMenuTitle(GetResString(IDS_WEBSERVICES), true, false);
// <== XP Style Menu [Xanatos] - Stulle
int iWebMenuEntries = theWebServices.GetFileMenuEntries(&WebMenu);
UINT flag2 = (iWebMenuEntries == 0 || iSelectedItems != 1) ? MF_GRAYED : MF_STRING;
m_SharedFilesMenu.AppendMenu(flag2 | MF_POPUP, (UINT_PTR)WebMenu.m_hMenu, GetResString(IDS_WEBSERVICES), _T("WEB"));
GetPopupMenuPos(*this, point);
m_SharedFilesMenu.TrackPopupMenu(TPM_LEFTALIGN |TPM_RIGHTBUTTON,point.x,point.y,this);
m_SharedFilesMenu.RemoveMenu(m_SharedFilesMenu.GetMenuItemCount()-1,MF_BYPOSITION);
VERIFY( WebMenu.DestroyMenu() );
if (uInsertedMenuItem)
VERIFY( m_SharedFilesMenu.RemoveMenu(uInsertedMenuItem, MF_BYCOMMAND) );
}
BOOL CSharedFilesCtrl::OnCommand(WPARAM wParam, LPARAM /*lParam*/)
{
wParam = LOWORD(wParam);
CTypedPtrList<CPtrList, CShareableFile*> selectedList;
POSITION pos = GetFirstSelectedItemPosition();
while (pos != NULL){
int index = GetNextSelectedItem(pos);
if (index >= 0)
selectedList.AddTail((CShareableFile*)GetItemData(index));
}
if ( wParam == MP_CREATECOLLECTION
|| wParam == MP_FIND
|| selectedList.GetCount() > 0)
{
CShareableFile* file = NULL;
if (selectedList.GetCount() == 1)
file = selectedList.GetHead();
CKnownFile* pKnownFile = NULL;
if (file != NULL && file->IsKindOf(RUNTIME_CLASS(CKnownFile)))
pKnownFile = (CKnownFile*)file;
switch (wParam){
case Irc_SetSendLink:
if (pKnownFile != NULL)
theApp.emuledlg->ircwnd->SetSendFileString(pKnownFile->GetED2kLink());
break;
case MP_GETED2KLINK:{
CString str;
POSITION pos = selectedList.GetHeadPosition();
while (pos != NULL)
{
CShareableFile* file = selectedList.GetNext(pos);
if (file != NULL && file->IsKindOf(RUNTIME_CLASS(CKnownFile))){
if (!str.IsEmpty())
str += _T("\r\n");
str += ((CKnownFile*)file)->GetED2kLink();
}
}
theApp.CopyTextToClipboard(str);
break;
}
#if defined(_DEBUG)
//JOHNTODO: Not for release as we need kad lowID users in the network to see how well this work work. Also, we do not support these links yet.
case MP_GETKADSOURCELINK:{
CString str;
POSITION pos = selectedList.GetHeadPosition();
while (pos != NULL)
{
CShareableFile* file = selectedList.GetNext(pos);
if (file->IsKindOf(RUNTIME_CLASS(CKnownFile))){
if (!str.IsEmpty())
str += _T("\r\n");
str += theApp.CreateKadSourceLink((CKnownFile*)file);
}
}
theApp.CopyTextToClipboard(str);
break;
}
#endif
// file operations
case MP_OPEN:
case IDA_ENTER:
if (file && !file->IsPartFile())
OpenFile(file);
break;
case MP_INSTALL_SKIN:
if (file && !file->IsPartFile())
InstallSkin(file->GetFilePath());
break;
case MP_OPENFOLDER:
if (file && !file->IsPartFile())
ShellExecute(NULL, _T("open"), _T("explorer"), _T("/select,\"") + file->GetFilePath() + _T("\""), NULL, SW_SHOW);
break;
case MP_RENAME:
case MPG_F2:
if (pKnownFile && !pKnownFile->IsPartFile()){
InputBox inputbox;
CString title = GetResString(IDS_RENAME);
title.Remove(_T('&'));
inputbox.SetLabels(title, GetResString(IDS_DL_FILENAME), pKnownFile->GetFileName());
inputbox.SetEditFilenameMode();
inputbox.DoModal();
CString newname = inputbox.GetInput();
if (!inputbox.WasCancelled() && newname.GetLength()>0)
{
// at least prevent users from specifying something like "..\dir\file"
static const TCHAR _szInvFileNameChars[] = _T("\\/:*?\"<>|");
if (newname.FindOneOf(_szInvFileNameChars) != -1){
AfxMessageBox(GetErrorMessage(ERROR_BAD_PATHNAME));
break;
}
CString newpath;
PathCombine(newpath.GetBuffer(MAX_PATH), file->GetPath(), newname);
newpath.ReleaseBuffer();
if (_trename(pKnownFile->GetFilePath(), newpath) != 0){
CString strError;
strError.Format(GetResString(IDS_ERR_RENAMESF), file->GetFilePath(), newpath, _tcserror(errno));
AfxMessageBox(strError);
break;
}
if (pKnownFile->IsKindOf(RUNTIME_CLASS(CPartFile)))
{
pKnownFile->SetFileName(newname);
STATIC_DOWNCAST(CPartFile, pKnownFile)->SetFullName(newpath);
}
else
{
theApp.sharedfiles->RemoveKeywords(pKnownFile);
pKnownFile->SetFileName(newname);
theApp.sharedfiles->AddKeywords(pKnownFile);
}
pKnownFile->SetFilePath(newpath);
UpdateFile(pKnownFile);
}
}
else
MessageBeep(MB_OK);
break;
case MP_REMOVE:
case MPG_DELETE:
{
if (IDNO == AfxMessageBox(GetResString(IDS_CONFIRM_FILEDELETE),MB_ICONWARNING | MB_ICONQUESTION | MB_DEFBUTTON2 | MB_YESNO))
return TRUE;
SetRedraw(FALSE);
bool bRemovedItems = false;
while (!selectedList.IsEmpty())
{
CShareableFile* myfile = selectedList.RemoveHead();
if (!myfile || myfile->IsPartFile())
continue;
bool delsucc = ShellDeleteFile(myfile->GetFilePath());
if (delsucc){
if (myfile->IsKindOf(RUNTIME_CLASS(CKnownFile)))
theApp.sharedfiles->RemoveFile((CKnownFile*)myfile, true);
else
RemoveFile(myfile, true);
bRemovedItems = true;
if (myfile->IsKindOf(RUNTIME_CLASS(CPartFile)))
theApp.emuledlg->transferwnd->GetDownloadList()->ClearCompleted(static_cast<CPartFile*>(myfile));
}
else{
CString strError;
strError.Format( GetResString(IDS_ERR_DELFILE) + _T("\r\n\r\n%s"), myfile->GetFilePath(), GetErrorMessage(GetLastError()));
AfxMessageBox(strError);
}
}
SetRedraw(TRUE);
if (bRemovedItems) {
AutoSelectItem();
// Depending on <no-idea> this does not always cause a
// LVN_ITEMACTIVATE message sent. So, explicitly redraw
// the item.
theApp.emuledlg->sharedfileswnd->ShowSelectedFilesDetails();
theApp.emuledlg->sharedfileswnd->OnSingleFileShareStatusChanged(); // might have been a single shared file
}
break;
}
case MP_UNSHAREFILE:
{
SetRedraw(FALSE);
bool bUnsharedItems = false;
while (!selectedList.IsEmpty())
{
CShareableFile* myfile = selectedList.RemoveHead();
if (!myfile || myfile->IsPartFile() || !theApp.sharedfiles->ShouldBeShared(myfile->GetPath(), myfile->GetFilePath(), false)
|| theApp.sharedfiles->ShouldBeShared(myfile->GetPath(), myfile->GetFilePath(), true))
{
continue;
}
bUnsharedItems |= theApp.sharedfiles->ExcludeFile(myfile->GetFilePath());
ASSERT( bUnsharedItems );
}
SetRedraw(TRUE);
if (bUnsharedItems) {
theApp.emuledlg->sharedfileswnd->ShowSelectedFilesDetails();
theApp.emuledlg->sharedfileswnd->OnSingleFileShareStatusChanged();
if (GetFirstSelectedItemPosition() == NULL)
AutoSelectItem();
}
break;
}
case MP_CMT:
ShowFileDialog(selectedList, IDD_COMMENT);
break;
case MPG_ALTENTER:
case MP_DETAIL:
ShowFileDialog(selectedList);
break;
case MP_FIND:
OnFindStart();
break;
case MP_CREATECOLLECTION:
{
CCollection* pCollection = new CCollection();
POSITION pos = selectedList.GetHeadPosition();
while (pos != NULL)
{
CShareableFile* pFile = selectedList.GetNext(pos);
if (pFile->IsKindOf(RUNTIME_CLASS(CKnownFile)))
pCollection->AddFileToCollection(pFile, true);
}
CCollectionCreateDialog dialog;
dialog.SetCollection(pCollection,true);
dialog.DoModal();
//We delete this collection object because when the newly created
//collection file is added to the sharedfile list, it is read and verified
//and which creates the colleciton object that is attached to that file..
delete pCollection;
break;
}
case MP_SEARCHAUTHOR:
if (pKnownFile && pKnownFile->m_pCollection)
{
SSearchParams* pParams = new SSearchParams;
pParams->strExpression = pKnownFile->m_pCollection->GetCollectionAuthorKeyString();
pParams->eType = SearchTypeKademlia;
pParams->strFileType = ED2KFTSTR_EMULECOLLECTION;
pParams->strSpecialTitle = pKnownFile->m_pCollection->m_sCollectionAuthorName;
if (pParams->strSpecialTitle.GetLength() > 50){
pParams->strSpecialTitle = pParams->strSpecialTitle.Left(50) + _T("...");
}
theApp.emuledlg->searchwnd->m_pwndResults->StartSearch(pParams);
}
break;
case MP_VIEWCOLLECTION:
if (pKnownFile && pKnownFile->m_pCollection)
{
CCollectionViewDialog dialog;
dialog.SetCollection(pKnownFile->m_pCollection);
dialog.DoModal();
}
break;
case MP_MODIFYCOLLECTION:
if (pKnownFile && pKnownFile->m_pCollection)
{
CCollectionCreateDialog dialog;
CCollection* pCollection = new CCollection(pKnownFile->m_pCollection);
dialog.SetCollection(pCollection,false);
dialog.DoModal();
delete pCollection;
}
break;
case MP_SHOWED2KLINK:
ShowFileDialog(selectedList, IDD_ED2KLINK);
break;
case MP_PRIOVERYLOW:
case MP_PRIOLOW:
case MP_PRIONORMAL:
case MP_PRIOHIGH:
case MP_PRIOVERYHIGH:
case MP_PRIOPOWER: //Xman PowerRelease
case MP_PRIOAUTO:
{
SetRedraw(FALSE); //Xman Code Improvement
POSITION pos = selectedList.GetHeadPosition();
while (pos != NULL)
{
if (!selectedList.GetAt(pos)->IsKindOf(RUNTIME_CLASS(CKnownFile)))
{
selectedList.GetNext(pos); //zz_fly :: bug fix :: DolphinX
continue;
}
CKnownFile* file = (CKnownFile*)selectedList.GetNext(pos);
switch (wParam) {
case MP_PRIOVERYLOW:
file->SetAutoUpPriority(false);
file->SetUpPriority(PR_VERYLOW);
UpdateFile(file);
break;
case MP_PRIOLOW:
file->SetAutoUpPriority(false);
file->SetUpPriority(PR_LOW);
UpdateFile(file);
break;
case MP_PRIONORMAL:
file->SetAutoUpPriority(false);
file->SetUpPriority(PR_NORMAL);
UpdateFile(file);
break;
case MP_PRIOHIGH:
file->SetAutoUpPriority(false);
file->SetUpPriority(PR_HIGH);
UpdateFile(file);
break;
case MP_PRIOVERYHIGH:
file->SetAutoUpPriority(false);
file->SetUpPriority(PR_VERYHIGH);
UpdateFile(file);
break;
//Xman PowerRelease
case MP_PRIOPOWER:
if(file->IsPartFile()) //only to be sure
break;
file->SetAutoUpPriority(false);
file->SetUpPriority(PR_POWER);
UpdateFile(file);
break;
//Xman end
case MP_PRIOAUTO:
file->SetAutoUpPriority(true);
//Xman advanced upload-priority
if (thePrefs.UseAdvancedAutoPtio())
#ifdef _BETA
file->CalculateAndSetUploadPriority2();
#else
file->CalculateAndSetUploadPriority();
#endif
else
//Xman end
file->UpdateAutoUpPriority();
UpdateFile(file);
break;
}
}
SetRedraw(TRUE); //Xman Code Improvement
break;
}
// ==> HideOS & SOTN [Slugfiller/ MorphXT] - Stulle
case MP_HIDEOS_DEFAULT:
case MP_HIDEOS_SET:
{
POSITION pos = selectedList.GetHeadPosition();
int newHideOS = -1;
if (wParam==MP_HIDEOS_SET)
{
InputBox inputbox;
CString title=GetResString(IDS_HIDEOS);
CString currHideOS;
if (pKnownFile)
currHideOS.Format(_T("%i"), (pKnownFile->GetHideOS()>=0)?pKnownFile->GetHideOS():thePrefs.GetHideOvershares());
else
currHideOS = _T("0");
inputbox.SetLabels(GetResString(IDS_HIDEOS), GetResString(IDS_HIDEOVERSHARES), currHideOS);
inputbox.SetNumber(true);
int result = inputbox.DoModal();
if (result == IDCANCEL || (newHideOS = inputbox.GetInputInt()) < 0)
break;
}
SetRedraw(FALSE);
while (pos != NULL)
{
CShareableFile* file = selectedList.GetNext(pos);
if (!file->IsKindOf(RUNTIME_CLASS(CKnownFile)))
continue;
if (newHideOS == ((CKnownFile*)file)->GetHideOS())
continue;
((CKnownFile*)file)->SetHideOS(newHideOS);
UpdateFile(file);
}
SetRedraw(TRUE);
break;
}
// <== HideOS & SOTN [Slugfiller/ MorphXT] - Stulle
// ==> PowerShare [ZZ/MorphXT] - Stulle
case MP_POWERSHARE_ON:
case MP_POWERSHARE_OFF:
case MP_POWERSHARE_DEFAULT:
case MP_POWERSHARE_AUTO:
case MP_POWERSHARE_LIMITED:
{
SetRedraw(FALSE);
POSITION pos = selectedList.GetHeadPosition();
while (pos != NULL)
{
CShareableFile* file = selectedList.GetNext(pos);
if (!file->IsKindOf(RUNTIME_CLASS(CKnownFile)))
continue;
switch (wParam) {
case MP_POWERSHARE_DEFAULT:
((CKnownFile*)file)->SetPowerShared(-1);
break;
case MP_POWERSHARE_ON:
((CKnownFile*)file)->SetPowerShared(1);
break;
case MP_POWERSHARE_OFF:
((CKnownFile*)file)->SetPowerShared(0);
break;
case MP_POWERSHARE_AUTO:
((CKnownFile*)file)->SetPowerShared(2);
break;
case MP_POWERSHARE_LIMITED:
((CKnownFile*)file)->SetPowerShared(3);
break;
}
UpdateFile(file);
}
SetRedraw(TRUE);
break;
}
case MP_POWERSHARE_LIMIT:
case MP_POWERSHARE_LIMIT_SET:
{
POSITION pos = selectedList.GetHeadPosition();
int newPowerShareLimit = -1;
if (wParam==MP_POWERSHARE_LIMIT_SET)
{
InputBox inputbox;
CString title=GetResString(IDS_POWERSHARE);
CString currPowerShareLimit;
if (pKnownFile)
currPowerShareLimit.Format(_T("%i"), (pKnownFile->GetPowerShareLimit()>=0)?pKnownFile->GetPowerShareLimit():thePrefs.GetPowerShareLimit());
else
currPowerShareLimit = _T("0");
inputbox.SetLabels(GetResString(IDS_POWERSHARE), GetResString(IDS_POWERSHARE_LIMIT), currPowerShareLimit);
inputbox.SetNumber(true);
int result = inputbox.DoModal();
if (result == IDCANCEL || (newPowerShareLimit = inputbox.GetInputInt()) < 0)
break;
}
SetRedraw(FALSE);
while (pos != NULL)
{
CShareableFile* file = selectedList.GetNext(pos);
if (newPowerShareLimit == ((CKnownFile*)file)->GetPowerShareLimit())
break;
((CKnownFile*)file)->SetPowerShareLimit(newPowerShareLimit);
if (((CKnownFile*)file)->IsPartFile())
((CPartFile*)file)->UpdatePartsInfo();
else
((CKnownFile*)file)->UpdatePartsInfo();
UpdateFile(file);
}
SetRedraw(TRUE);
break;
}
// <== PowerShare [ZZ/MorphXT] - Stulle
// ==> Limit PS by amount of data uploaded [Stulle] - Stulle
case MP_PS_AMOUNT_LIMIT:
case MP_PS_AMOUNT_LIMIT_SET:
{
POSITION pos = selectedList.GetHeadPosition();
int newPsAmountLimit = -1;
if (wParam==MP_PS_AMOUNT_LIMIT_SET)
{
InputBox inputbox;
CString title=GetResString(IDS_POWERSHARE);
CString currPsAmountLimit;
if (pKnownFile)
currPsAmountLimit.Format(_T("%i"), ((pKnownFile->GetPsAmountLimit()>=0.0f)?pKnownFile->GetPsAmountLimit():thePrefs.GetPsAmountLimit()));
else
currPsAmountLimit = _T("0");
inputbox.SetLabels(GetResString(IDS_POWERSHARE), GetResString(IDS_PS_AMOUNT_LIMIT_LABEL), currPsAmountLimit);
inputbox.SetNumber(true);
int result = inputbox.DoModal();
if (result == IDCANCEL || (newPsAmountLimit = inputbox.GetInputInt()) < 0)
break;
if (newPsAmountLimit > MAX_PS_AMOUNT_LIMIT)
{
AfxMessageBox(GetResString(IDS_PS_AMOUNT_LIMIT_WRONG),MB_OK | MB_ICONINFORMATION,0);
break;
}
}
SetRedraw(FALSE);
while (pos != NULL)
{
CShareableFile* file = selectedList.GetNext(pos);
if (newPsAmountLimit == ((CKnownFile*)file)->GetPsAmountLimit())
break;
((CKnownFile*)file)->SetPsAmountLimit(newPsAmountLimit);
if (((CKnownFile*)file)->IsPartFile())
((CPartFile*)file)->UpdatePartsInfo();
else
((CKnownFile*)file)->UpdatePartsInfo();
UpdateFile(file);
}
SetRedraw(TRUE);
break;
}
// <== Limit PS by amount of data uploaded [Stulle] - Stulle
// ==> Spread bars [Slugfiller/MorphXT] - Stulle
case MP_SPREADBAR_RESET:
{
SetRedraw(FALSE);
POSITION pos = selectedList.GetHeadPosition();
while (pos != NULL)
{
CShareableFile* file = selectedList.GetNext(pos);
((CKnownFile*)file)->statistic.ResetSpreadBar();
}
SetRedraw(TRUE);
break;
}
// <== Spread bars [Slugfiller/MorphXT] - Stulle
// ==> Copy feedback feature [MorphXT] - Stulle
/*
// Xman: idea: IcEcRacKer Copy UL-feedback
case MP_ULFEEDBACK:
{
CString feed;
bool morefiles = selectedList.GetCount() > 1;
uint64 sumTransferred=0;
uint64 sumAllTimeTransferred=0;
if(!selectedList.IsEmpty())
{
feed.AppendFormat(_T("%s: %s \r\n"), GetResString(IDS_SF_STATISTICS),thePrefs.GetUserNick());
feed.AppendFormat(_T("Mod: %s%s[%s] \r\n"),_T("eMule"), theApp.m_strCurVersionLong, MOD_VERSION);
}
while (!selectedList.IsEmpty())
{
CShareableFile* file = selectedList.RemoveHead();
if (!file->IsKindOf(RUNTIME_CLASS(CKnownFile)))
continue;
sumTransferred += ((CKnownFile*)file)->statistic.GetTransferred();
sumAllTimeTransferred += ((CKnownFile*)file)->statistic.GetAllTimeTransferred();
feed.AppendFormat(_T("%s: %s \r\n"),GetResString(IDS_DL_FILENAME),((CKnownFile*)file)->GetFileName());
feed.AppendFormat(_T("%s: %s \r\n"),GetResString(IDS_TYPE),((CKnownFile*)file)->GetFileType());
feed.AppendFormat(_T("%s: %s\r\n"),GetResString(IDS_DL_SIZE), CastItoXBytes(((CKnownFile*)file)->GetFileSize(), false, false));
CPartFile* pfile = (CPartFile*)file;
if(pfile && pfile->IsPartFile())
feed.AppendFormat(_T("%s %.1f%%\r\n"), GetResString(IDS_FD_COMPSIZE), pfile->GetPercentCompleted());
else
feed.AppendFormat(_T("%s 100%%\r\n"), GetResString(IDS_FD_COMPSIZE));
feed.AppendFormat(_T("%s: %s (%s) \r\n"),GetResString(IDS_SF_TRANSFERRED), CastItoXBytes(((CKnownFile*)file)->statistic.GetTransferred(), false, false), CastItoXBytes(((CKnownFile*)file)->statistic.GetAllTimeTransferred(), false, false));
feed.AppendFormat(_T("%s: %u (%u)\r\n"),GetResString(IDS_COMPLSOURCES),((CKnownFile*)file)->m_nCompleteSourcesCountLo, ((CKnownFile*)file)->m_nVirtualCompleteSourcesCount);
feed.AppendFormat(_T("%s: %u \r\n"),GetResString(IDS_ONQUEUE),(((CKnownFile*)file)->GetOnUploadqueue())); //Xman see OnUploadqueue
feed.AppendFormat(_T("%s: %u (%u) \r\n\r\n"),GetResString(IDS_SF_ACCEPTS),((CKnownFile*)file)->statistic.GetAccepts(),(((CKnownFile*)file)->statistic.GetAllTimeAccepts()));
}
if(morefiles)
feed.AppendFormat(_T("sum: %s: %s (%s) \r\n\r\n"),GetResString(IDS_SF_TRANSFERRED), CastItoXBytes(sumTransferred, false, false), CastItoXBytes(sumAllTimeTransferred, false, false));
theApp.CopyTextToClipboard(feed);
break;
}
//Xman end
*/
case MP_COPYFEEDBACK:
case MP_COPYFEEDBACK_US:
{
CString feed;
uint64 uTransferredSum = 0;
uint64 uTransferredAllSum = 0;
int iCount = 0;
POSITION pos = selectedList.GetHeadPosition();
if(wParam == MP_COPYFEEDBACK_US)
{
// ==> Feedback personalization [Stulle] - Stulle
/*
feed.AppendFormat(_T("Feedback from %s on [%s]\r\n"),thePrefs.GetUserNick(),theApp.m_strModLongVersion);
*/
CString tmp;
tmp.Format(_T("Feedback from %s on [%s]"),GetColoredText(thePrefs.GetUserNick(),style_f_names),GetColoredText(theApp.m_strModLongVersion,style_f_names));
feed.Append(GetColoredText(tmp,style_f_label));
feed.Append(_T("\r\n"));
// <== Feedback personalization [Stulle] - Stulle
}
else
{
// ==> Feedback personalization [Stulle] - Stulle
/*
feed.AppendFormat(GetResString(IDS_FEEDBACK_FROM),thePrefs.GetUserNick(), theApp.m_strModLongVersion);
feed.Append(_T("\r\n"));
*/
CString tmp;
tmp.Format(GetResString(IDS_FEEDBACK_FROM),GetColoredText(thePrefs.GetUserNick(),style_f_names),GetColoredText(theApp.m_strModLongVersion,style_f_names));
feed.Append(GetColoredText(tmp,style_f_label));
feed.Append(_T("\r\n"));
// <== Feedback personalization [Stulle] - Stulle
}
while (pos != NULL)
{
CShareableFile* file = selectedList.GetNext(pos);
if (!file->IsKindOf(RUNTIME_CLASS(CKnownFile)))
continue;
feed.Append(((CKnownFile*)file)->GetFeedback(wParam == MP_COPYFEEDBACK_US));
if(pos != NULL) // Feedback personalization [Stulle] - Stulle
feed.Append(_T("\r\n"));
uTransferredSum += ((CKnownFile*)file)->statistic.GetTransferred();
uTransferredAllSum += ((CKnownFile*)file)->statistic.GetAllTimeTransferred();
iCount++;
}
if(iCount>1)
{
feed.Append(_T("\r\n"));
if(wParam == MP_COPYFEEDBACK_US)
{
// ==> Feedback personalization [Stulle] - Stulle
/*
feed.AppendFormat(_T("Transferred (all files): %s (%s)\r\n"),CastItoXBytes(uTransferredSum,false,false,3,true),CastItoXBytes(uTransferredAllSum,false,false,3,true));
*/
feed.AppendFormat(_T("Transferred (all files): %s (%s)"),GetColoredText(CastItoXBytes(uTransferredSum,false,false,3,true),style_f_transferred),GetColoredText(CastItoXBytes(uTransferredAllSum,false,false,3,true),style_f_transferred));
// <== Feedback personalization [Stulle] - Stulle
}
else
{
// ==> Feedback personalization [Stulle] - Stulle
/*
feed.AppendFormat(_T("%s: %s (%s)\r\n"),GetResString(IDS_FEEDBACK_ALL_TRANSFERRED),CastItoXBytes(uTransferredSum,false,false,3),CastItoXBytes(uTransferredAllSum,false,false,3));
*/
feed.AppendFormat(_T("%s: %s (%s)"),GetResString(IDS_FEEDBACK_ALL_TRANSFERRED),GetColoredText(CastItoXBytes(uTransferredSum,false,false,3,true),style_f_transferred),GetColoredText(CastItoXBytes(uTransferredAllSum,false,false,3,true),style_f_transferred));
// <== Feedback personalization [Stulle] - Stulle
}
}
feed.Append(GetColoredText(_T(""),-style_f_label)); // Feedback personalization [Stulle] - Stulle
feed.Append(_T("\r\n"));
//Todo: copy all the comments too
theApp.CopyTextToClipboard(feed);
break;
}
// <== Copy feedback feature [MorphXT] - Stulle
//Xman Mass Rename (Morph)
case MP_MASSRENAME:
{
CMassRenameDialog MRDialog;
// Add the files to the dialog
POSITION pos = selectedList.GetHeadPosition();
while (pos != NULL) {
CShareableFile* file = selectedList.GetNext(pos);
if (!file->IsKindOf(RUNTIME_CLASS(CKnownFile)))
continue;
MRDialog.m_FileList.AddTail((CKnownFile*)file);
}
int result = MRDialog.DoModal ();
if (result == IDOK) {
// The user has successfully entered new filenames. Now we have
// to rename all the files...
POSITION pos = selectedList.GetHeadPosition();
int i=0;
while (pos != NULL) {
CString newname = MRDialog.m_NewFilenames.at (i);
CString newpath = MRDialog.m_NewFilePaths.at (i);
CShareableFile* file = selectedList.GetNext(pos);
if (!file->IsKindOf(RUNTIME_CLASS(CKnownFile)))
continue;
// .part files could be renamed by simply changing the filename
// in the CKnownFile object.
if ((!((CKnownFile*)file)->IsPartFile()) && (_trename(((CKnownFile*)file)->GetFilePath(), newpath) != 0)){
// Use the "Format"-Syntax of AddLogLine here instead of
// CString.Format+AddLogLine, because if "%"-characters are
// in the string they would be misinterpreted as control sequences!
AddLogLine(false,_T("Failed to rename '%s' to '%s', Error: %hs"), file->GetFilePath(), newpath, _tcserror(errno));
} else {
//CString strres; // obsolete
if (!((CKnownFile*)file)->IsPartFile()) {
// Use the "Format"-Syntax of AddLogLine here instead of
// CString.Format+AddLogLine, because if "%"-characters are
// in the string they would be misinterpreted as control sequences!
AddLogLine(false,_T("Successfully renamed '%s' to '%s'"), ((CKnownFile*)file)->GetFilePath(), newpath);
((CKnownFile*)file)->SetFileName(newname);
if (file->IsKindOf(RUNTIME_CLASS(CPartFile)))
((CPartFile*) file)->SetFullName(newpath);
} else {
// Use the "Format"-Syntax of AddLogLine here instead of
// CString.Format+AddLogLine, because if "%"-characters are
// in the string they would be misinterpreted as control sequences!
AddLogLine(false,_T("Successfully renamed .part file '%s' to '%s'"), ((CKnownFile*)file)->GetFileName(), newname);
((CPartFile*) file)->SetFollowTheMajority(false); // Follow The Majority [AndCycle/Stulle] - Stulle
((CKnownFile*)file)->SetFileName(newname, true);
((CPartFile*) file)->UpdateDisplayedInfo();
((CPartFile*) file)->SavePartFile();
}
((CKnownFile*)file)->SetFilePath(newpath);
UpdateFile(file);
}
// Next item (pos is iterated when retriving the current file)
i++;
}
}
break;
}
//Xman end
default:
if (file && wParam>=MP_WEBURL && wParam<=MP_WEBURL+256){
theWebServices.RunURL(file, wParam);
}
// ==> HideOS & SOTN [Slugfiller/ MorphXT] - Stulle
else
{
POSITION pos = selectedList.GetHeadPosition();
while (pos != NULL)
{
CShareableFile* file = selectedList.GetNext(pos);
if (!file->IsKindOf(RUNTIME_CLASS(CKnownFile)))
continue;
if (wParam>=MP_SELECTIVE_CHUNK && wParam<=MP_SELECTIVE_CHUNK_1){
((CKnownFile*)file)->SetSelectiveChunk(wParam==MP_SELECTIVE_CHUNK?-1:wParam-MP_SELECTIVE_CHUNK_0);
UpdateFile(file);
}else if (wParam>=MP_SHAREONLYTHENEED && wParam<=MP_SHAREONLYTHENEED_1){
((CKnownFile*)file)->SetShareOnlyTheNeed(wParam==MP_SHAREONLYTHENEED?-1:wParam-MP_SHAREONLYTHENEED_0);
UpdateFile(file);
}
}
}
// <== HideOS & SOTN [Slugfiller/ MorphXT] - Stulle
break;
}
}
return TRUE;
}
void CSharedFilesCtrl::OnLvnColumnClick(NMHDR *pNMHDR, LRESULT *pResult)
{
NMLISTVIEW *pNMListView = (NMLISTVIEW *)pNMHDR;
bool sortAscending;
if (GetSortItem() != pNMListView->iSubItem)
{
switch (pNMListView->iSubItem)
{
case 3: // Priority
case 10: // Complete Sources
case 11: // Shared
sortAscending = false;
break;
case 5: // Requests
case 6: // Accepted Requests
case 7: // Transferred Data
// Keep the current 'm_aSortBySecondValue' for that column, but reset to 'descending'
sortAscending = false;
break;
default:
sortAscending = true;
break;
}
}
else
sortAscending = !GetSortAscending();
// Ornis 4-way-sorting
int adder = 0;
if (pNMListView->iSubItem >= 5 && pNMListView->iSubItem <= 7) // 5=IDS_SF_REQUESTS, 6=IDS_SF_ACCEPTS, 7=IDS_SF_TRANSFERRED
{
ASSERT( pNMListView->iSubItem - 5 < _countof(m_aSortBySecondValue) );
if (GetSortItem() == pNMListView->iSubItem && !sortAscending) // check for 'descending' because the initial sort order is also 'descending'
m_aSortBySecondValue[pNMListView->iSubItem - 5] = !m_aSortBySecondValue[pNMListView->iSubItem - 5];
adder = m_aSortBySecondValue[pNMListView->iSubItem - 5] ? 100 : 0;
}
else if (pNMListView->iSubItem == 11) // 11=IDS_SHAREDTITLE
{
ASSERT( 3 < _countof(m_aSortBySecondValue) );
if (GetSortItem() == pNMListView->iSubItem && !sortAscending) // check for 'descending' because the initial sort order is also 'descending'
m_aSortBySecondValue[3] = !m_aSortBySecondValue[3];
adder = m_aSortBySecondValue[3] ? 100 : 0;
}
// Sort table
if (adder == 0)
SetSortArrow(pNMListView->iSubItem, sortAscending);
else
SetSortArrow(pNMListView->iSubItem, sortAscending ? arrowDoubleUp : arrowDoubleDown);
// ==> PowerShare [ZZ/MorphXT] - Stulle
/*
UpdateSortHistory(pNMListView->iSubItem + (sortAscending ? 0 : 20) + adder, 20);
SortItems(SortProc, pNMListView->iSubItem + (sortAscending ? 0 : 20) + adder);
*/
UpdateSortHistory(pNMListView->iSubItem + (sortAscending ? 0 : 30) + adder, 30);
SortItems(SortProc, pNMListView->iSubItem + (sortAscending ? 0 : 30) + adder);
// <== PowerShare [ZZ/MorphXT] - Stulle
*pResult = 0;
}
int CSharedFilesCtrl::SortProc(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort)
{
const CShareableFile* item1 = (CShareableFile*)lParam1;
const CShareableFile* item2 = (CShareableFile*)lParam2;
bool bSortAscending;
int iColumn;
// ==> PowerShare [ZZ/MorphXT] - Stulle
/*
if (lParamSort >= 100) {
bSortAscending = lParamSort < 120;
iColumn = bSortAscending ? lParamSort : lParamSort - 20;
}
else {
bSortAscending = lParamSort < 20;
iColumn = bSortAscending ? lParamSort : lParamSort - 20;
}
*/
if (lParamSort >= 100) {
bSortAscending = lParamSort < 130;
iColumn = bSortAscending ? lParamSort : lParamSort - 30;
}
else {
bSortAscending = lParamSort < 30;
iColumn = bSortAscending ? lParamSort : lParamSort - 30;
}
// all indexes shifted by 10!!!
// <== PowerShare [ZZ/MorphXT] - Stulle
int iResult = 0;
bool bExtColumn = false;
switch (iColumn)
{
case 0: //filename
iResult = CompareLocaleStringNoCase(item1->GetFileName(), item2->GetFileName());
break;
case 1: //filesize
iResult = CompareUnsigned64(item1->GetFileSize(), item2->GetFileSize());
break;
case 2: //filetype
iResult = item1->GetFileTypeDisplayStr().Compare(item2->GetFileTypeDisplayStr());
// if the type is equal, subsort by extension
if (iResult == 0)
{
LPCTSTR pszExt1 = PathFindExtension(item1->GetFileName());
LPCTSTR pszExt2 = PathFindExtension(item2->GetFileName());
if ((pszExt1 == NULL) ^ (pszExt2 == NULL))
iResult = pszExt1 == NULL ? 1 : (-1);
else
iResult = pszExt1 != NULL ? _tcsicmp(pszExt1, pszExt2) : 0;
}
break;
case 9: //folder
iResult = CompareLocaleStringNoCase(item1->GetPath(), item2->GetPath());
break;
default:
bExtColumn = true;
}
if (bExtColumn)
{
if (item1->IsKindOf(RUNTIME_CLASS(CKnownFile)) && !item2->IsKindOf(RUNTIME_CLASS(CKnownFile)))
iResult = (-1);
else if (!item1->IsKindOf(RUNTIME_CLASS(CKnownFile)) && item2->IsKindOf(RUNTIME_CLASS(CKnownFile)))
iResult = 1;
else if (item1->IsKindOf(RUNTIME_CLASS(CKnownFile)) && item2->IsKindOf(RUNTIME_CLASS(CKnownFile)))
{
CKnownFile* kitem1 = (CKnownFile*)item1;
CKnownFile* kitem2 = (CKnownFile*)item2;
switch (iColumn)
{
case 3:{//prio
// ==> PowerShare [ZZ/MorphXT] - Stulle
/*
uint8 p1 = kitem1->GetUpPriority() + 1;
if (p1 == 5)
p1 = 0;
uint8 p2 = kitem2->GetUpPriority() + 1;
if (p2 == 5)
p2 = 0;
iResult = p1 - p2;
*/
if (!kitem1->GetPowerShared() && kitem2->GetPowerShared())
iResult=-1;
else if (kitem1->GetPowerShared() && !kitem2->GetPowerShared())
iResult=1;
else
if(kitem1->GetUpPriority() == PR_VERYLOW && kitem2->GetUpPriority() != PR_VERYLOW)
iResult=-1;
else if (kitem1->GetUpPriority() != PR_VERYLOW && kitem2->GetUpPriority() == PR_VERYLOW)
iResult=1;
else
iResult=kitem1->GetUpPriority()-kitem2->GetUpPriority();
// <== PowerShare [ZZ/MorphXT] - Stulle
break;
}
case 4: //fileID
iResult = memcmp(kitem1->GetFileHash(), kitem2->GetFileHash(), 16);
break;
case 5: //requests
iResult = CompareUnsigned(kitem1->statistic.GetRequests(), kitem2->statistic.GetRequests());
break;
case 6: //acc requests
iResult = CompareUnsigned(kitem1->statistic.GetAccepts(), kitem2->statistic.GetAccepts());
break;
case 7: //all transferred
iResult = CompareUnsigned64(kitem1->statistic.GetTransferred(), kitem2->statistic.GetTransferred());
break;
case 10: //complete sources
iResult = CompareUnsigned(kitem1->m_nCompleteSourcesCount, kitem2->m_nCompleteSourcesCount);
break;
case 11: //ed2k shared
iResult = kitem1->GetPublishedED2K() - kitem2->GetPublishedED2K();
break;
case 12:
iResult = CompareOptLocaleStringNoCaseUndefinedAtBottom(kitem1->GetStrTagValue(FT_MEDIA_ARTIST), kitem2->GetStrTagValue(FT_MEDIA_ARTIST), bSortAscending);
break;
case 13:
iResult = CompareOptLocaleStringNoCaseUndefinedAtBottom(kitem1->GetStrTagValue(FT_MEDIA_ALBUM), kitem2->GetStrTagValue(FT_MEDIA_ALBUM), bSortAscending);
break;
case 14:
iResult = CompareOptLocaleStringNoCaseUndefinedAtBottom(kitem1->GetStrTagValue(FT_MEDIA_TITLE), kitem2->GetStrTagValue(FT_MEDIA_TITLE), bSortAscending);
break;
case 15:
iResult = CompareUnsignedUndefinedAtBottom(kitem1->GetIntTagValue(FT_MEDIA_LENGTH), kitem2->GetIntTagValue(FT_MEDIA_LENGTH), bSortAscending);
break;
case 16:
iResult = CompareUnsignedUndefinedAtBottom(kitem1->GetIntTagValue(FT_MEDIA_BITRATE), kitem2->GetIntTagValue(FT_MEDIA_BITRATE), bSortAscending);
break;
case 17:
iResult = CompareOptLocaleStringNoCaseUndefinedAtBottom(GetCodecDisplayName(kitem1->GetStrTagValue(FT_MEDIA_CODEC)), GetCodecDisplayName(kitem2->GetStrTagValue(FT_MEDIA_CODEC)), bSortAscending);
break;
//Xman see OnUploadqueue
case 18:
iResult= kitem1->GetOnUploadqueue() -kitem2->GetOnUploadqueue();
break;
//Xman end
//Xman advanced upload-priority
//sort by the second value-> faster
case 19:
{
float it1value= kitem1->statistic.GetAllTimeTransferred()/(float)kitem1->GetFileSize()*1000; //sort one number after ,
float it2value= kitem2->statistic.GetAllTimeTransferred()/(float)kitem2->GetFileSize()*1000;
iResult=(int)(it1value-it2value);
break;
}
//Xman end
// ==> Spread bars [Slugfiller/MorphXT] - Stulle
case 20: //spread asc
case 21:
iResult=CompareFloat(kitem1->statistic.GetSpreadSortValue(),kitem2->statistic.GetSpreadSortValue());
break;
case 22: // VQB: Simple UL asc
{
float x1 = ((float)kitem1->statistic.GetAllTimeTransferred())/((float)kitem1->GetFileSize());
float x2 = ((float)kitem2->statistic.GetAllTimeTransferred())/((float)kitem2->GetFileSize());
iResult=CompareFloat(x1,x2);
break;
}
case 23: // SF: Full Upload Count asc
iResult=CompareFloat(kitem1->statistic.GetFullSpreadCount(),kitem2->statistic.GetFullSpreadCount());
break;
// <== Spread bars [Slugfiller/MorphXT] - Stulle
// ==> push rare file - Stulle
case 24:
iResult=CompareFloat(kitem1->GetFileRatio(),kitem2->GetFileRatio());
break;
// <== push rare file - Stulle
// ==> HideOS & SOTN [Slugfiller/ MorphXT] - Stulle
case 25:
if (kitem1->GetHideOS() == kitem2->GetHideOS())
iResult=kitem1->GetSelectiveChunk() - kitem2->GetSelectiveChunk();
else
iResult=kitem1->GetHideOS() - kitem2->GetHideOS();
break;
case 26:
iResult=kitem1->GetShareOnlyTheNeed() - kitem2->GetShareOnlyTheNeed();
break;
// <== HideOS & SOTN [Slugfiller/ MorphXT] - Stulle
// ==> PowerShare [ZZ/MorphXT] - Stulle
case 27:
if (!kitem1->GetPowerShared() && kitem2->GetPowerShared())
iResult=-1;
else if (kitem1->GetPowerShared() && !kitem2->GetPowerShared())
iResult=1;
else
if (kitem1->GetPowerSharedMode() != kitem2->GetPowerSharedMode())
iResult=kitem1->GetPowerSharedMode() - kitem2->GetPowerSharedMode();
else
if (!kitem1->GetPowerShareAuthorized() && kitem2->GetPowerShareAuthorized())
iResult=-1;
else if (kitem1->GetPowerShareAuthorized() && !kitem2->GetPowerShareAuthorized())
iResult=1;
else
if (!kitem1->GetPowerShareAuto() && kitem2->GetPowerShareAuto())
iResult=-1;
else if (kitem1->GetPowerShareAuto() && !kitem2->GetPowerShareAuto())
iResult=1;
else
if (!kitem1->GetPowerShareLimited() && kitem2->GetPowerShareLimited())
iResult=-1;
else if (kitem1->GetPowerShareLimited() && !kitem2->GetPowerShareLimited())
iResult=1;
else
iResult=0;
break;
// <== PowerShare [ZZ/MorphXT] - Stulle
case 105: //all requests
iResult = CompareUnsigned(kitem1->statistic.GetAllTimeRequests(), kitem2->statistic.GetAllTimeRequests());
break;
case 106: //all acc requests
iResult = CompareUnsigned(kitem1->statistic.GetAllTimeAccepts(), kitem2->statistic.GetAllTimeAccepts());
break;
case 107: //all transferred
iResult = CompareUnsigned64(kitem1->statistic.GetAllTimeTransferred(), kitem2->statistic.GetAllTimeTransferred());
break;
case 111:{ //kad shared
uint32 tNow = time(NULL);
int i1 = (tNow < kitem1->GetLastPublishTimeKadSrc()) ? 1 : 0;
int i2 = (tNow < kitem2->GetLastPublishTimeKadSrc()) ? 1 : 0;
iResult = i1 - i2;
break;
}
}
}
}
if (!bSortAscending)
iResult = -iResult;
// SLUGFILLER: multiSort remove - handled in parent class
/*
//call secondary sortorder, if this one results in equal
int dwNextSort;
if (iResult == 0 && (dwNextSort = theApp.emuledlg->sharedfileswnd->sharedfilesctrl.GetNextSortOrder(lParamSort)) != -1)
iResult = SortProc(lParam1, lParam2, dwNextSort);
*/
// SLUGFILLER End
return iResult;
}
void CSharedFilesCtrl::OpenFile(const CShareableFile* file)
{
if(file->IsKindOf(RUNTIME_CLASS(CKnownFile)) && ((CKnownFile*)file)->m_pCollection)
{
CCollectionViewDialog dialog;
dialog.SetCollection(((CKnownFile*)file)->m_pCollection);
dialog.DoModal();
}
else
ShellOpenFile(file->GetFilePath(), NULL);
}
void CSharedFilesCtrl::OnNmDblClk(NMHDR* /*pNMHDR*/, LRESULT* pResult)
{
int iSel = GetNextItem(-1, LVIS_SELECTED | LVIS_FOCUSED);
if (iSel != -1)
{
CShareableFile* file = (CShareableFile*)GetItemData(iSel);
if (file)
{
if (GetKeyState(VK_MENU) & 0x8000)
{
CTypedPtrList<CPtrList, CShareableFile*> aFiles;
aFiles.AddHead(file);
ShowFileDialog(aFiles);
}
else if (!file->IsPartFile())
OpenFile(file);
}
}
*pResult = 0;
}
void CSharedFilesCtrl::CreateMenues()
{
// ==> PowerShare [ZZ/MorphXT] - Stulle
if (m_PowershareMenu) VERIFY( m_PowershareMenu.DestroyMenu() );
if (m_PowerShareLimitMenu) VERIFY( m_PowerShareLimitMenu.DestroyMenu() );
// <== PowerShare [ZZ/MorphXT] - Stulle
// ==> Limit PS by amount of data uploaded [Stulle] - Stulle
if (m_PsAmountLimitMenu) VERIFY( m_PsAmountLimitMenu.DestroyMenu() );
// <== Limit PS by amount of data uploaded [Stulle] - Stulle
// ==> HideOS & SOTN [Slugfiller/ MorphXT] - Stulle
if (m_HideOSMenu) VERIFY( m_HideOSMenu.DestroyMenu() );
if (m_SelectiveChunkMenu) VERIFY( m_SelectiveChunkMenu.DestroyMenu() );
if (m_ShareOnlyTheNeedMenu) VERIFY( m_ShareOnlyTheNeedMenu.DestroyMenu() );
// <== HideOS & SOTN [Slugfiller/ MorphXT] - Stulle
if (m_PrioMenu) VERIFY( m_PrioMenu.DestroyMenu() );
if (m_CollectionsMenu) VERIFY( m_CollectionsMenu.DestroyMenu() );
if (m_SharedFilesMenu) VERIFY( m_SharedFilesMenu.DestroyMenu() );
// ==> PowerShare [ZZ/MorphXT] - Stulle
m_PowershareMenu.CreateMenu();
m_PowershareMenu.AddMenuTitle(GetResString(IDS_POWERSHARE), true, false); // XP Style Menu [Xanatos] - Stulle
m_PowershareMenu.AppendMenu(MF_STRING,MP_POWERSHARE_DEFAULT,GetResString(IDS_DEFAULT));
m_PowershareMenu.AppendMenu(MF_STRING,MP_POWERSHARE_OFF,GetResString(IDS_POWERSHARE_DISABLED));
m_PowershareMenu.AppendMenu(MF_STRING,MP_POWERSHARE_ON,GetResString(IDS_POWERSHARE_ACTIVATED));
m_PowershareMenu.AppendMenu(MF_STRING,MP_POWERSHARE_AUTO,GetResString(IDS_POWERSHARE_AUTO));
m_PowershareMenu.AppendMenu(MF_STRING,MP_POWERSHARE_LIMITED,GetResString(IDS_POWERSHARE_LIMITED));
m_PowerShareLimitMenu.CreateMenu();
m_PowerShareLimitMenu.AddMenuTitle(GetResString(IDS_POWERSHARE_LIMITED), true, false); // XP Style Menu [Xanatos] - Stulle
m_PowerShareLimitMenu.AppendMenu(MF_STRING,MP_POWERSHARE_LIMIT, GetResString(IDS_DEFAULT));
m_PowerShareLimitMenu.AppendMenu(MF_STRING,MP_POWERSHARE_LIMIT_SET, GetResString(IDS_DISABLED));
// <== PowerShare [ZZ/MorphXT] - Stulle
// ==> Limit PS by amount of data uploaded [Stulle] - Stulle
m_PsAmountLimitMenu.CreateMenu();
m_PsAmountLimitMenu.AddMenuTitle(GetResString(IDS_PS_LIMITED_AMNT), true, false); // XP Style Menu [Xanatos] - Stulle
m_PsAmountLimitMenu.AppendMenu(MF_STRING,MP_PS_AMOUNT_LIMIT, GetResString(IDS_DEFAULT));
m_PsAmountLimitMenu.AppendMenu(MF_STRING,MP_PS_AMOUNT_LIMIT_SET, GetResString(IDS_DISABLED));
// <== Limit PS by amount of data uploaded [Stulle] - Stulle
// ==> HideOS & SOTN [Slugfiller/ MorphXT] - Stulle
m_HideOSMenu.CreateMenu();
m_HideOSMenu.AddMenuTitle(GetResString(IDS_HIDEOS), true, false); // XP Style Menu [Xanatos] - Stulle
m_HideOSMenu.AppendMenu(MF_STRING,MP_HIDEOS_DEFAULT, GetResString(IDS_DEFAULT));
m_HideOSMenu.AppendMenu(MF_STRING,MP_HIDEOS_SET, GetResString(IDS_DISABLED));
m_SelectiveChunkMenu.CreateMenu();
m_SelectiveChunkMenu.AddMenuTitle(GetResString(IDS_SELECTIVESHARE), true, false); // XP Style Menu [Xanatos] - Stulle
m_SelectiveChunkMenu.AppendMenu(MF_STRING,MP_SELECTIVE_CHUNK, GetResString(IDS_DEFAULT));
m_SelectiveChunkMenu.AppendMenu(MF_STRING,MP_SELECTIVE_CHUNK_0, GetResString(IDS_DISABLED));
m_SelectiveChunkMenu.AppendMenu(MF_STRING,MP_SELECTIVE_CHUNK_1, GetResString(IDS_ENABLED));
m_ShareOnlyTheNeedMenu.CreateMenu();
m_ShareOnlyTheNeedMenu.AddMenuTitle(GetResString(IDS_SHAREONLYTHENEED), true, false); // XP Style Menu [Xanatos] - Stulle
m_ShareOnlyTheNeedMenu.AppendMenu(MF_STRING,MP_SHAREONLYTHENEED, GetResString(IDS_DEFAULT));
m_ShareOnlyTheNeedMenu.AppendMenu(MF_STRING,MP_SHAREONLYTHENEED_0, GetResString(IDS_DISABLED));
m_ShareOnlyTheNeedMenu.AppendMenu(MF_STRING,MP_SHAREONLYTHENEED_1, GetResString(IDS_ENABLED));
// <== HideOS & SOTN [Slugfiller/ MorphXT] - Stulle
m_PrioMenu.CreateMenu();
m_PrioMenu.AddMenuTitle(GetResString(IDS_PRIORITY), true, false); // XP Style Menu [Xanatos] - Stulle
m_PrioMenu.AppendMenu(MF_STRING,MP_PRIOVERYLOW,GetResString(IDS_PRIOVERYLOW));
m_PrioMenu.AppendMenu(MF_STRING,MP_PRIOLOW,GetResString(IDS_PRIOLOW));
m_PrioMenu.AppendMenu(MF_STRING,MP_PRIONORMAL,GetResString(IDS_PRIONORMAL));
m_PrioMenu.AppendMenu(MF_STRING,MP_PRIOHIGH, GetResString(IDS_PRIOHIGH));
m_PrioMenu.AppendMenu(MF_STRING,MP_PRIOVERYHIGH, GetResString(IDS_PRIORELEASE));
m_PrioMenu.AppendMenu(MF_STRING,MP_PRIOPOWER, GetResString(IDS_POWERRELEASE)); //Xman PowerRelease
m_PrioMenu.AppendMenu(MF_STRING,MP_PRIOAUTO, GetResString(IDS_PRIOAUTO));//UAP
m_CollectionsMenu.CreateMenu();
// ==> XP Style Menu [Xanatos] - Stulle
/*
m_CollectionsMenu.AddMenuTitle(NULL, true);
*/
m_CollectionsMenu.AddMenuTitle(GetResString(IDS_SEARCH_EMULECOLLECTION), true, false);
// <== XP Style Menu [Xanatos] - Stulle
m_CollectionsMenu.AppendMenu(MF_STRING,MP_CREATECOLLECTION, GetResString(IDS_CREATECOLLECTION), _T("COLLECTION_ADD"));
m_CollectionsMenu.AppendMenu(MF_STRING,MP_MODIFYCOLLECTION, GetResString(IDS_MODIFYCOLLECTION), _T("COLLECTION_EDIT"));
m_CollectionsMenu.AppendMenu(MF_STRING,MP_VIEWCOLLECTION, GetResString(IDS_VIEWCOLLECTION), _T("COLLECTION_VIEW"));
m_CollectionsMenu.AppendMenu(MF_STRING,MP_SEARCHAUTHOR, GetResString(IDS_SEARCHAUTHORCOLLECTION), _T("COLLECTION_SEARCH"));
m_SharedFilesMenu.CreatePopupMenu();
m_SharedFilesMenu.AddMenuTitle(GetResString(IDS_SHAREDFILES), true);
m_SharedFilesMenu.AppendMenu(MF_STRING,MP_OPEN, GetResString(IDS_OPENFILE), _T("OPENFILE"));
m_SharedFilesMenu.AppendMenu(MF_STRING,MP_OPENFOLDER, GetResString(IDS_OPENFOLDER), _T("OPENFOLDER"));
m_SharedFilesMenu.AppendMenu(MF_STRING,MP_RENAME, GetResString(IDS_RENAME) + _T("..."), _T("FILERENAME"));
m_SharedFilesMenu.AppendMenu(MF_STRING,MP_REMOVE, GetResString(IDS_DELETE), _T("DELETE"));
m_SharedFilesMenu.AppendMenu(MF_STRING,MP_UNSHAREFILE, GetResString(IDS_UNSHARE), _T("KADBOOTSTRAP")); // TODO: better icon
if (thePrefs.IsExtControlsEnabled())
m_SharedFilesMenu.AppendMenu(MF_STRING,Irc_SetSendLink,GetResString(IDS_IRC_ADDLINKTOIRC), _T("IRCCLIPBOARD"));
m_SharedFilesMenu.AppendMenu(MF_STRING|MF_SEPARATOR);
m_SharedFilesMenu.AppendMenu(MF_STRING|MF_POPUP,(UINT_PTR)m_PrioMenu.m_hMenu, GetResString(IDS_PRIORITY) + _T(" (") + GetResString(IDS_PW_CON_UPLBL) + _T(")"), _T("FILEPRIORITY"));
m_SharedFilesMenu.AppendMenu(MF_STRING|MF_SEPARATOR);
m_SharedFilesMenu.AppendMenu(MF_STRING|MF_POPUP,(UINT_PTR)m_CollectionsMenu.m_hMenu, GetResString(IDS_META_COLLECTION), _T("AABCollectionFileType"));
m_SharedFilesMenu.AppendMenu(MF_STRING|MF_SEPARATOR);
m_SharedFilesMenu.AppendMenu(MF_STRING,MP_DETAIL, GetResString(IDS_SHOWDETAILS), _T("FILEINFO"));
m_SharedFilesMenu.AppendMenu(MF_STRING,MP_CMT, GetResString(IDS_CMT_ADD), _T("FILECOMMENTS"));
if (thePrefs.GetShowCopyEd2kLinkCmd())
m_SharedFilesMenu.AppendMenu(MF_STRING,MP_GETED2KLINK, GetResString(IDS_DL_LINK1), _T("ED2KLINK") );
else
m_SharedFilesMenu.AppendMenu(MF_STRING,MP_SHOWED2KLINK, GetResString(IDS_DL_SHOWED2KLINK), _T("ED2KLINK") );
m_SharedFilesMenu.AppendMenu(MF_STRING,MP_FIND, GetResString(IDS_FIND), _T("Search"));
m_SharedFilesMenu.AppendMenu(MF_STRING|MF_SEPARATOR);
m_SharedFilesMenu.AppendHeading(GetResString(IDS_RELEASER));
// ==> PowerShare [ZZ/MorphXT] - Stulle
m_SharedFilesMenu.AppendMenu(MF_STRING|MF_POPUP,(UINT_PTR)m_PowershareMenu.m_hMenu, GetResString(IDS_POWERSHARE), _T("FILEPOWERSHARE"));
m_PowershareMenu.AppendMenu(MF_STRING|MF_SEPARATOR);
m_PowershareMenu.AppendMenu(MF_STRING|MF_POPUP,(UINT_PTR)m_PowerShareLimitMenu.m_hMenu, GetResString(IDS_POWERSHARE_LIMIT));
// <== PowerShare [ZZ/MorphXT] - Stulle
// ==> Limit PS by amount of data uploaded [Stulle] - Stulle
m_PowershareMenu.AppendMenu(MF_STRING|MF_POPUP,(UINT_PTR)m_PsAmountLimitMenu.m_hMenu, GetResString(IDS_PS_AMOUNT_LIMIT));
// <== Limit PS by amount of data uploaded [Stulle] - Stulle
// ==> HideOS & SOTN [Slugfiller/ MorphXT] - Stulle
m_SharedFilesMenu.AppendMenu(MF_STRING|MF_POPUP,(UINT_PTR)m_HideOSMenu.m_hMenu, GetResString(IDS_HIDEOS), _T("FILEHIDEOS"));
m_HideOSMenu.AppendMenu(MF_STRING|MF_SEPARATOR);
m_HideOSMenu.AppendMenu(MF_STRING|MF_POPUP,(UINT_PTR)m_SelectiveChunkMenu.m_hMenu, GetResString(IDS_SELECTIVESHARE));
m_SharedFilesMenu.AppendMenu(MF_STRING|MF_POPUP,(UINT_PTR)m_ShareOnlyTheNeedMenu.m_hMenu, GetResString(IDS_SHAREONLYTHENEED), _T("FILESHAREONLYTHENEED"));
// <== HideOS & SOTN [Slugfiller/ MorphXT] - Stulle
m_SharedFilesMenu.AppendMenu(MF_STRING,MP_SPREADBAR_RESET, GetResString(IDS_SPREAD_RESET), _T("RESETSPREADBAR")); // Spread bars [Slugfiller/MorphXT] - Stulle
// ==> Copy feedback feature [MorphXT] - Stulle
/*
// Xman: IcEcRacKer Copy UL-feedback
m_SharedFilesMenu.AppendMenu(MF_STRING,MP_ULFEEDBACK, _T("Copy UL-Feedback"), _T("FILECOMMENTS"));
m_SharedFilesMenu.AppendMenu(MF_STRING|MF_SEPARATOR);
//Xman end
*/
m_SharedFilesMenu.AppendMenu(MF_STRING,MP_COPYFEEDBACK, GetResString(IDS_COPYFEEDBACK), _T("COPY"));
m_SharedFilesMenu.AppendMenu(MF_STRING,MP_COPYFEEDBACK_US, GetResString(IDS_COPYFEEDBACK_US), _T("COPY"));
m_SharedFilesMenu.AppendMenu(MF_SEPARATOR);
// <== Copy feedback feature [MorphXT] - Stulle
//Xman Mass Rename (Morph)
if (thePrefs.IsExtControlsEnabled())
{
m_SharedFilesMenu.AppendMenu(MF_STRING,MP_MASSRENAME,GetResString(IDS_MR), _T("FILEMASSRENAME"));
m_SharedFilesMenu.AppendMenu(MF_STRING|MF_SEPARATOR);
}
//Xman end
#if defined(_DEBUG)
if (thePrefs.IsExtControlsEnabled()){
//JOHNTODO: Not for release as we need kad lowID users in the network to see how well this work work. Also, we do not support these links yet.
m_SharedFilesMenu.AppendMenu(MF_STRING,MP_GETKADSOURCELINK, _T("Copy eD2K Links To Clipboard (Kad)"));
m_SharedFilesMenu.AppendMenu(MF_STRING|MF_SEPARATOR);
}
#endif
}
void CSharedFilesCtrl::ShowComments(CShareableFile* file)
{
if (file)
{
CTypedPtrList<CPtrList, CShareableFile*> aFiles;
aFiles.AddHead(file);
ShowFileDialog(aFiles, IDD_COMMENT);
}
}
void CSharedFilesCtrl::OnLvnGetDispInfo(NMHDR *pNMHDR, LRESULT *pResult)
{
if (theApp.emuledlg->IsRunning()) {
// Although we have an owner drawn listview control we store the text for the primary item in the listview, to be
// capable of quick searching those items via the keyboard. Because our listview items may change their contents,
// we do this via a text callback function. The listview control will send us the LVN_DISPINFO notification if
// it needs to know the contents of the primary item.
//
// But, the listview control sends this notification all the time, even if we do not search for an item. At least
// this notification is only sent for the visible items and not for all items in the list. Though, because this
// function is invoked *very* often, do *NOT* put any time consuming code in here.
//
// Vista: That callback is used to get the strings for the label tips for the sub(!) items.
//
NMLVDISPINFO *pDispInfo = reinterpret_cast<NMLVDISPINFO*>(pNMHDR);
if (pDispInfo->item.mask & LVIF_TEXT) {
const CShareableFile* pFile = reinterpret_cast<CShareableFile*>(pDispInfo->item.lParam);
if (pFile != NULL)
GetItemDisplayText(pFile, pDispInfo->item.iSubItem, pDispInfo->item.pszText, pDispInfo->item.cchTextMax);
}
}
*pResult = 0;
}
void CSharedFilesCtrl::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags)
{
if (nChar == 'C' && (GetKeyState(VK_CONTROL) & 0x8000))
{
// Ctrl+C: Copy listview items to clipboard
SendMessage(WM_COMMAND, MP_GETED2KLINK);
return;
}
else if (nChar == VK_F5)
ReloadFileList();
else if (nChar == VK_SPACE && CheckBoxesEnabled())
{
// Toggle Checkboxes
// selection and item position might change during processing (shouldn't though, but lets make sure), so first get all pointers instead using the selection pos directly
SetRedraw(FALSE);
CTypedPtrList<CPtrList, CShareableFile*> selectedList;
POSITION pos = GetFirstSelectedItemPosition();
while (pos != NULL){
int index = GetNextSelectedItem(pos);
if (index >= 0)
selectedList.AddTail((CShareableFile*)GetItemData(index));
}
while (!selectedList.IsEmpty())
{
CheckBoxClicked(FindFile(selectedList.RemoveHead()));
}
SetRedraw(TRUE);
}
CMuleListCtrl::OnKeyDown(nChar, nRepCnt, nFlags);
}
void CSharedFilesCtrl::ShowFileDialog(CTypedPtrList<CPtrList, CShareableFile*>& aFiles, UINT uPshInvokePage)
{
if (aFiles.GetSize() > 0)
{
CSharedFileDetailsSheet dialog(aFiles, uPshInvokePage, this);
dialog.DoModal();
}
}
void CSharedFilesCtrl::SetDirectoryFilter(CDirectoryItem* pNewFilter, bool bRefresh){
if (m_pDirectoryFilter == pNewFilter)
return;
m_pDirectoryFilter = pNewFilter;
if (bRefresh)
ReloadFileList();
}
void CSharedFilesCtrl::OnLvnGetInfoTip(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMLVGETINFOTIP pGetInfoTip = reinterpret_cast<LPNMLVGETINFOTIP>(pNMHDR);
if (pGetInfoTip->iSubItem == 0)
{
LVHITTESTINFO hti = {0};
::GetCursorPos(&hti.pt);
ScreenToClient(&hti.pt);
if (SubItemHitTest(&hti) == -1 || hti.iItem != pGetInfoTip->iItem || hti.iSubItem != 0){
// don' show the default label tip for the main item, if the mouse is not over the main item
if ((pGetInfoTip->dwFlags & LVGIT_UNFOLDED) == 0 && pGetInfoTip->cchTextMax > 0 && pGetInfoTip->pszText[0] != _T('\0'))
pGetInfoTip->pszText[0] = _T('\0');
return;
}
const CShareableFile* pFile = (CShareableFile*)GetItemData(pGetInfoTip->iItem);
if (pFile && pGetInfoTip->pszText && pGetInfoTip->cchTextMax > 0)
{
CString strInfo = pFile->GetInfoSummary();
strInfo += TOOLTIP_AUTOFORMAT_SUFFIX_CH;
_tcsncpy(pGetInfoTip->pszText, strInfo, pGetInfoTip->cchTextMax);
pGetInfoTip->pszText[pGetInfoTip->cchTextMax-1] = _T('\0');
}
}
*pResult = 0;
}
bool CSharedFilesCtrl::IsFilteredItem(const CShareableFile* pFile) const
{
const CStringArray& rastrFilter = theApp.emuledlg->sharedfileswnd->m_astrFilter;
if (rastrFilter.GetSize() == 0)
return false;
// filtering is done by text only for all colums to keep it consistent and simple for the user even if that
// doesn't allows complex filters
TCHAR szFilterTarget[256];
GetItemDisplayText(pFile, theApp.emuledlg->sharedfileswnd->GetFilterColumn(),
szFilterTarget, _countof(szFilterTarget));
bool bItemFiltered = false;
for (int i = 0; i < rastrFilter.GetSize(); i++)
{
const CString& rstrExpr = rastrFilter.GetAt(i);
bool bAnd = true;
LPCTSTR pszText = (LPCTSTR)rstrExpr;
if (pszText[0] == _T('-')) {
pszText += 1;
bAnd = false;
}
bool bFound = (stristr(szFilterTarget, pszText) != NULL);
if ((bAnd && !bFound) || (!bAnd && bFound)) {
bItemFiltered = true;
break;
}
}
return bItemFiltered;
}
void CSharedFilesCtrl::SetToolTipsDelay(DWORD dwDelay)
{
CToolTipCtrl* tooltip = GetToolTips();
if (tooltip)
tooltip->SetDelayTime(TTDT_INITIAL, dwDelay);
}
bool CSharedFilesCtrl::IsSharedInKad(const CKnownFile *file) const
{
bool bSharedInKad;
if ((uint32)time(NULL) < file->GetLastPublishTimeKadSrc()) {
if (theApp.IsFirewalled() && theApp.IsConnected()) {
if ((theApp.clientlist->GetBuddy() && (file->GetLastPublishBuddy() == theApp.clientlist->GetBuddy()->GetIP()))
|| (Kademlia::CKademlia::IsRunning() && !Kademlia::CUDPFirewallTester::IsFirewalledUDP(true) && Kademlia::CUDPFirewallTester::IsVerified()))
{
bSharedInKad = true;
}
else
bSharedInKad = false;
}
else
bSharedInKad = true;
}
else
bSharedInKad = false;
return bSharedInKad;
}
void CSharedFilesCtrl::AddShareableFiles(CString strFromDir)
{
while (!liTempShareableFilesInDir.IsEmpty()) // cleanup old filelist
delete liTempShareableFilesInDir.RemoveHead();
CString strSearchPath(strFromDir);
PathAddBackslash(strSearchPath.GetBuffer(strFromDir.GetLength() + 1));
strSearchPath.ReleaseBuffer();
strSearchPath += _T("*");
CFileFind ff;
bool end = !ff.FindFile(strSearchPath, 0);
if (end) {
DWORD dwError = GetLastError();
if (dwError != ERROR_FILE_NOT_FOUND)
DebugLogError(_T("Failed to find files for SharedFilesListCtrl in %s, %s"), strFromDir, GetErrorMessage(dwError));
return;
}
SetRedraw(FALSE);
while (!end)
{
end = !ff.FindNextFile();
if (ff.IsDirectory() || ff.IsDots() || ff.IsSystem() || ff.IsTemporary() || ff.GetLength()==0 || ff.GetLength()>MAX_EMULE_FILE_SIZE)
continue;
CString strFoundFileName(ff.GetFileName());
CString strFoundFilePath(ff.GetFilePath());
CString strFoundDirectory(strFoundFilePath.Left(ff.GetFilePath().ReverseFind('\\') + 1));
ULONGLONG ullFoundFileSize = ff.GetLength();
CTime tFoundFileTime;
try{
ff.GetLastWriteTime(tFoundFileTime);
}
catch(CException* ex){
ex->Delete();
}
// ignore real(!) LNK files
TCHAR szExt[_MAX_EXT];
_tsplitpath(strFoundFileName, NULL, NULL, NULL, szExt);
if (_tcsicmp(szExt, _T(".lnk")) == 0){
SHFILEINFO info;
if (SHGetFileInfo(strFoundFilePath, 0, &info, sizeof(info), SHGFI_ATTRIBUTES) && (info.dwAttributes & SFGAO_LINK)){
continue;
}
}
// ignore real(!) thumbs.db files -- seems that lot of ppl have 'thumbs.db' files without the 'System' file attribute
if (strFoundFileName.CompareNoCase(_T("thumbs.db")) == 0)
{
// if that's a valid 'Storage' file, we declare it as a "thumbs.db" file.
CComPtr<IStorage> pStorage;
if (StgOpenStorage(strFoundFilePath, NULL, STGM_READ | STGM_SHARE_DENY_WRITE, NULL, 0, &pStorage) == S_OK)
{
CComPtr<IEnumSTATSTG> pEnumSTATSTG;
if (SUCCEEDED(pStorage->EnumElements(0, NULL, 0, &pEnumSTATSTG)))
{
STATSTG statstg = {0};
if (pEnumSTATSTG->Next(1, &statstg, 0) == S_OK)
{
CoTaskMemFree(statstg.pwcsName);
statstg.pwcsName = NULL;
continue;
}
}
}
}
// ==> Make code VS 2005 and VS 2008 ready [MorphXT] - Stulle
/*
uint32 fdate = (UINT)tFoundFileTime.GetTime();
*/
time_t fdate = (time_t)tFoundFileTime.GetTime();
// <== Make code VS 2005 and VS 2008 ready [MorphXT] - Stulle
if (fdate == 0)
fdate = (UINT)-1;
if (fdate == -1){
if (thePrefs.GetVerbose())
AddDebugLogLine(false, _T("Failed to get file date of \"%s\""), strFoundFilePath);
}
else
AdjustNTFSDaylightFileTime(fdate, strFoundFilePath);
CKnownFile* toadd = theApp.knownfiles->FindKnownFile(strFoundFileName, fdate, ullFoundFileSize);
if (toadd != NULL && theApp.sharedfiles->GetFileByID(toadd->GetFileHash()) != NULL) // check for shared
{
// this file is already shared and should be on the list, nothing to do
}
else if (toadd != NULL) // for known
{
toadd->SetFilePath(strFoundFilePath);
toadd->SetPath(strFoundDirectory);
AddFile(toadd); // known, could be on the list already
}
else // not known or shared, create
{
CShareableFile* pNewTempFile = new CShareableFile();
pNewTempFile->SetFilePath(strFoundFilePath);
pNewTempFile->SetFileName(strFoundFileName);
pNewTempFile->SetPath(strFoundDirectory);
pNewTempFile->SetFileSize(ullFoundFileSize);
uchar aucMD4[16];
md4clr(aucMD4);
pNewTempFile->SetFileHash(aucMD4);
liTempShareableFilesInDir.AddTail(pNewTempFile);
AddFile(pNewTempFile);
}
}
SetRedraw(TRUE);
ff.Close();
}
BOOL CSharedFilesCtrl::OnNMClick(NMHDR *pNMHDR, LRESULT *pResult)
{
if (CheckBoxesEnabled()) // do we have checkboxes?
{
NMLISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
int iItem = HitTest(pNMListView->ptAction);
if (iItem != -1){
// determine if the checkbox was clicked
CRect recItem;
if(GetItemRect(iItem, recItem, LVIR_BOUNDS))
{
CPoint pointHit = pNMListView->ptAction;
ASSERT( recItem.PtInRect(pointHit) );
recItem.left += sm_iIconOffset;
recItem.right = recItem.left + 16;
recItem.top += (recItem.Height() > 16) ? ((recItem.Height() - 16) / 2) : 0;
recItem.bottom = recItem.top + 16;
if (recItem.PtInRect(pointHit)){
// user clicked on the checkbox
CheckBoxClicked(iItem);
}
}
}
}
*pResult = 0;
return FALSE; // pass on to parent window
}
void CSharedFilesCtrl::CheckBoxClicked(int iItem)
{
if (iItem == (-1))
{
ASSERT( false );
return;
}
// check which state the checkbox (should) currently have
const CShareableFile* pFile = (CShareableFile*)GetItemData(iItem);
if (pFile->IsShellLinked())
return; // no interacting with shelllinked files
if (theApp.sharedfiles->ShouldBeShared(pFile->GetPath(), pFile->GetFilePath(), false)){
// this is currently shared so unshare it
if (theApp.sharedfiles->ShouldBeShared(pFile->GetPath(), pFile->GetFilePath(), true))
return; // not allowed to unshare this file
VERIFY( theApp.sharedfiles->ExcludeFile(pFile->GetFilePath()) );
// update GUI stuff
ShowFilesCount();
theApp.emuledlg->sharedfileswnd->ShowSelectedFilesDetails();
theApp.emuledlg->sharedfileswnd->OnSingleFileShareStatusChanged();
// no need to update the list itself, will be handled in the RemoveFile function
}
else
{
// SLUGFILLER: SafeHash remove - removed installation dir unsharing
/*
if (!thePrefs.IsShareableDirectory(pFile->GetPath()))
return; // not allowed to share
*/
// SLUGFILLER: SafeHash remove - removed installation dir unsharing
VERIFY( theApp.sharedfiles->AddSingleSharedFile(pFile->GetFilePath()) );
ShowFilesCount();
theApp.emuledlg->sharedfileswnd->ShowSelectedFilesDetails();
theApp.emuledlg->sharedfileswnd->OnSingleFileShareStatusChanged();
UpdateFile(pFile);
}
}
bool CSharedFilesCtrl::CheckBoxesEnabled() const
{
return m_pDirectoryFilter != NULL && m_pDirectoryFilter->m_eItemType == SDI_UNSHAREDDIRECTORY;
}
void CSharedFilesCtrl::OnMouseMove(UINT nFlags, CPoint point)
{
// highlighting Checkboxes
if (CheckBoxesEnabled())
{
// are we currently on any checkbox?
int iItem = HitTest(point);
if (iItem != (-1))
{
CRect recItem;
if(GetItemRect(iItem, recItem, LVIR_BOUNDS))
{
ASSERT( recItem.PtInRect(point) );
recItem.left += sm_iIconOffset;
recItem.right = recItem.left + 16;
recItem.top += (recItem.Height() > 16) ? ((recItem.Height() - 16) / 2) : 0;
recItem.bottom = recItem.top + 16;
if (recItem.PtInRect(point)){
// is this checkbox already hot?
if (m_pHighlightedItem != (CShareableFile*)GetItemData(iItem))
{
// update old highlighted item
CShareableFile* pOldItem = m_pHighlightedItem;
m_pHighlightedItem = (CShareableFile*)GetItemData(iItem);
UpdateFile(pOldItem, false);
// highlight current item
InvalidateRect(recItem);
}
CMuleListCtrl::OnMouseMove(nFlags, point);
return;
}
}
}
// no checkbox should be hot
if (m_pHighlightedItem != NULL)
{
CShareableFile* pOldItem = m_pHighlightedItem;
m_pHighlightedItem = NULL;
UpdateFile(pOldItem, false);
}
}
CMuleListCtrl::OnMouseMove(nFlags, point);
}
CSharedFilesCtrl::CShareDropTarget::CShareDropTarget()
{
m_piDropHelper = NULL;
m_pParent = NULL;
m_bUseDnDHelper = SUCCEEDED(CoCreateInstance(CLSID_DragDropHelper, NULL, CLSCTX_INPROC_SERVER, IID_IDropTargetHelper, (void**) &m_piDropHelper));
}
CSharedFilesCtrl::CShareDropTarget::~CShareDropTarget()
{
if (m_piDropHelper != NULL)
m_piDropHelper->Release();
}
DROPEFFECT CSharedFilesCtrl::CShareDropTarget::OnDragEnter(CWnd* pWnd, COleDataObject* pDataObject, DWORD /*dwKeyState*/, CPoint point)
{
DROPEFFECT dwEffect = DROPEFFECT_NONE;
if (pDataObject->IsDataAvailable(CF_HDROP))
dwEffect = DROPEFFECT_COPY;
if (m_bUseDnDHelper)
{
IDataObject* piDataObj = pDataObject->GetIDataObject(FALSE);
m_piDropHelper->DragEnter (pWnd->GetSafeHwnd(), piDataObj, &point, dwEffect);
}
return dwEffect;
}
DROPEFFECT CSharedFilesCtrl::CShareDropTarget::OnDragOver(CWnd* /*pWnd*/, COleDataObject* pDataObject, DWORD /*dwKeyState*/, CPoint point)
{
DROPEFFECT dwEffect = DROPEFFECT_NONE;
if (pDataObject->IsDataAvailable(CF_HDROP))
dwEffect = DROPEFFECT_COPY;
if (m_bUseDnDHelper)
{
m_piDropHelper->DragOver(&point, dwEffect);
}
return dwEffect;
}
BOOL CSharedFilesCtrl::CShareDropTarget::OnDrop(CWnd* /*pWnd*/, COleDataObject* pDataObject, DROPEFFECT dropEffect, CPoint point)
{
HGLOBAL hGlobal = pDataObject->GetGlobalData(CF_HDROP);
if (hGlobal != NULL)
{
HDROP hDrop = (HDROP)GlobalLock(hGlobal);
if (hDrop != NULL)
{
CString strFilePath;
CFileFind ff;
CStringList liToAddFiles; // all files too add
CStringList liToAddDirs; // all directories to add
bool bFromSingleDirectory = true; // are all files from within the same directory
CString strSingleDirectory = _T(""); // which would be this one
UINT nFileCount = DragQueryFile(hDrop, (UINT)(-1), NULL, 0);
for (UINT nFile = 0; nFile < nFileCount; nFile++ )
{
if (DragQueryFile(hDrop, nFile, strFilePath.GetBuffer(MAX_PATH), MAX_PATH) > 0 )
{
strFilePath.ReleaseBuffer();
if (ff.FindFile(strFilePath, 0))
{
ff.FindNextFile();
// just a quick pre check, complete check is done later in the share function itself
if (ff.IsDots() || ff.IsSystem() || ff.IsTemporary()
|| (!ff.IsDirectory() && (ff.GetLength()==0 || ff.GetLength()>MAX_EMULE_FILE_SIZE))
// SLUGFILLER: SafeHash remove - removed installation dir unsharing
/*
|| (ff.IsDirectory() && !thePrefs.IsShareableDirectory(ff.GetFilePath() + _T('\\')))
*/
// SLUGFILLER: SafeHash remove - removed installation dir unsharing
|| (ff.IsDirectory() && theApp.sharedfiles->ShouldBeShared(ff.GetFilePath()+ _T('\\'), _T(""), false))
|| (!ff.IsDirectory() && theApp.sharedfiles->ShouldBeShared(ff.GetFilePath(), ff.GetFilePath().Left(ff.GetFilePath().ReverseFind('\\') + 1), false)) )
{
DebugLog(_T("Drag&Drop'ed shared File ignored (%s)"), ff.GetFilePath());
ff.Close();
continue;
}
if (ff.IsDirectory())
{
DEBUG_ONLY( DebugLog(_T("Drag'n'Drop'ed directory: %s"), ff.GetFilePath()+ _T('\\')) );
liToAddDirs.AddTail(ff.GetFilePath() + _T('\\'));
}
else
{
DEBUG_ONLY( DebugLog(_T("Drag'n'Drop'ed file: %s"), ff.GetFilePath()) );
liToAddFiles.AddTail(ff.GetFilePath());
if (bFromSingleDirectory)
{
if (strSingleDirectory.IsEmpty())
strSingleDirectory = ff.GetFilePath().Left(ff.GetFilePath().ReverseFind('\\') + 1);
else if (strSingleDirectory.CompareNoCase(ff.GetFilePath().Left(ff.GetFilePath().ReverseFind('\\') + 1)) != NULL)
bFromSingleDirectory = false;
}
}
}
else
{
DebugLogError(_T("Drag&Drop'ed shared File not found (%s)"), strFilePath);
}
ff.Close();
}
else
{
ASSERT( false );
strFilePath.ReleaseBuffer();
}
}
if (!liToAddFiles.IsEmpty() || !liToAddDirs.IsEmpty())
{
// add the directories first as they could
// make single file adds invalid if they are contained in one of those dirs already
for (POSITION pos = liToAddDirs.GetHeadPosition(); pos != NULL; )
VERIFY( theApp.sharedfiles->AddSingleSharedDirectory(liToAddDirs.GetNext(pos)) ); // should always succeed
bool bHaveFiles = false;
// ==> Automatic shared files updater [MoNKi] - Stulle
/*
while (!liToAddFiles.IsEmpty())
bHaveFiles |= theApp.sharedfiles->AddSingleSharedFile(liToAddFiles.RemoveHead()); // could fail, due to the dirs added above
*/
int iDoAsfuReset = 0;
while (!liToAddFiles.IsEmpty())
bHaveFiles |= theApp.sharedfiles->AddSingleSharedFile(liToAddFiles.RemoveHead(),false,iDoAsfuReset); // could fail, due to the dirs added above
// <== Automatic shared files updater [MoNKi] - Stulle
// GUI updates
if (!liToAddDirs.IsEmpty())
theApp.emuledlg->sharedfileswnd->m_ctlSharedDirTree.Reload(true);
if (bHaveFiles)
theApp.emuledlg->sharedfileswnd->OnSingleFileShareStatusChanged();
m_pParent->ShowFilesCount();
if (bHaveFiles && liToAddDirs.IsEmpty() && bFromSingleDirectory)
{
// if we added only files from the same directory, show and select this in the filesystem tree
ASSERT( !strSingleDirectory.IsEmpty() );
VERIFY( theApp.emuledlg->sharedfileswnd->m_ctlSharedDirTree.ShowFileSystemDirectory(strSingleDirectory) );
}
else if (!liToAddDirs.IsEmpty() && !bHaveFiles)
{
// only directories added, if only one select the specific shared dir, otherwise the Shared Directories section
if (liToAddDirs.GetCount() == 1)
theApp.emuledlg->sharedfileswnd->m_ctlSharedDirTree.ShowSharedDirectory(liToAddDirs.GetHead());
else
theApp.emuledlg->sharedfileswnd->m_ctlSharedDirTree.ShowSharedDirectory(_T(""));
}
else
{
// otherwise select the All Shared Files category
theApp.emuledlg->sharedfileswnd->m_ctlSharedDirTree.ShowAllSharedFiles();
}
// ==> Automatic shared files updater [MoNKi] - Stulle
if(iDoAsfuReset == 1 || !liToAddDirs.IsEmpty()) // a dropped file caused reset or we added a dir
{
if(thePrefs.GetDirectoryWatcher() && (iDoAsfuReset == 0 || thePrefs.GetSingleSharedDirWatcher()))
theApp.ResetDirectoryWatcher();
}
// <== Automatic shared files updater [MoNKi] - Stulle
}
GlobalUnlock(hGlobal);
}
GlobalFree(hGlobal);
}
if (m_bUseDnDHelper)
{
IDataObject* piDataObj = pDataObject->GetIDataObject(FALSE);
m_piDropHelper->Drop(piDataObj, &point, dropEffect);
}
return TRUE;
}
void CSharedFilesCtrl::CShareDropTarget::OnDragLeave(CWnd* /*pWnd*/)
{
if (m_bUseDnDHelper)
m_piDropHelper->DragLeave();
} | [
"Mike.Ken.S@dd569cc8-ff36-11de-bbca-1111db1fd05b",
"[email protected]@dd569cc8-ff36-11de-bbca-1111db1fd05b"
]
| [
[
[
1,
41
],
[
43,
67
],
[
69,
543
],
[
546,
700
],
[
702,
714
],
[
722,
722
],
[
724,
761
],
[
763,
771
],
[
774,
774
],
[
779,
779
],
[
781,
782
],
[
787,
790
],
[
792,
796
],
[
819,
863
],
[
866,
1492
],
[
1494,
1625
],
[
1627,
1633
],
[
1635,
1636
],
[
1638,
1743
],
[
1745,
1757
],
[
1759,
1780
],
[
1782,
1864
],
[
1867,
1867
],
[
1869,
1894
],
[
1896,
1952
],
[
1954,
2255
],
[
2258,
2413
],
[
2415,
2420
],
[
2422,
2422
],
[
2424,
2634
],
[
2636,
3157
],
[
3159,
3171
],
[
3173,
3411
]
],
[
[
42,
42
],
[
68,
68
],
[
544,
545
],
[
701,
701
],
[
715,
721
],
[
723,
723
],
[
762,
762
],
[
772,
773
],
[
775,
778
],
[
780,
780
],
[
783,
786
],
[
791,
791
],
[
797,
818
],
[
864,
865
],
[
1493,
1493
],
[
1626,
1626
],
[
1634,
1634
],
[
1637,
1637
],
[
1744,
1744
],
[
1758,
1758
],
[
1781,
1781
],
[
1865,
1866
],
[
1868,
1868
],
[
1895,
1895
],
[
1953,
1953
],
[
2256,
2257
],
[
2414,
2414
],
[
2421,
2421
],
[
2423,
2423
],
[
2635,
2635
],
[
3158,
3158
],
[
3172,
3172
]
]
]
|
9db008b53fcf4eb93cc3c320b791e952a0d3dd6c | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Dependencies/Xerces/include/xercesc/validators/datatype/DateTimeDatatypeValidator.cpp | 298dc6e8603ba220fdc19f5bcf11b4d8f0631c0c | []
| no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,262 | cpp | /*
* Copyright 2001,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: DateTimeDatatypeValidator.cpp 191694 2005-06-21 17:53:28Z cargilld $
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/validators/datatype/DateTimeDatatypeValidator.hpp>
#include <xercesc/util/OutOfMemoryException.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Constructors and Destructor
// ---------------------------------------------------------------------------
DateTimeDatatypeValidator::DateTimeDatatypeValidator(MemoryManager* const manager)
:DateTimeValidator(0, 0, 0, DatatypeValidator::DateTime, manager)
{
setOrdered(XSSimpleTypeDefinition::ORDERED_PARTIAL);
}
DateTimeDatatypeValidator::DateTimeDatatypeValidator(
DatatypeValidator* const baseValidator
, RefHashTableOf<KVStringPair>* const facets
, RefArrayVectorOf<XMLCh>* const enums
, const int finalSet
, MemoryManager* const manager)
:DateTimeValidator(baseValidator, facets, finalSet, DatatypeValidator::DateTime, manager)
{
init(enums, manager);
}
DateTimeDatatypeValidator::~DateTimeDatatypeValidator()
{}
DatatypeValidator* DateTimeDatatypeValidator::newInstance
(
RefHashTableOf<KVStringPair>* const facets
, RefArrayVectorOf<XMLCh>* const enums
, const int finalSet
, MemoryManager* const manager
)
{
return (DatatypeValidator*) new (manager) DateTimeDatatypeValidator(this, facets, enums, finalSet, manager);
}
//
// caller need to release the date created here
//
XMLDateTime* DateTimeDatatypeValidator::parse(const XMLCh* const content, MemoryManager* const manager)
{
XMLDateTime *pRetDate = new (manager) XMLDateTime(content, manager);
Janitor<XMLDateTime> jan(pRetDate);
try
{
pRetDate->parseDateTime();
}
catch(const OutOfMemoryException&)
{
jan.release();
throw;
}
return jan.release();
}
void DateTimeDatatypeValidator::parse(XMLDateTime* const pDate)
{
pDate->parseDateTime();
}
const XMLCh* DateTimeDatatypeValidator::getCanonicalRepresentation(const XMLCh* const rawData
, MemoryManager* const memMgr
, bool toValidate) const
{
MemoryManager* toUse = memMgr? memMgr : fMemoryManager;
if (toValidate)
{
DateTimeDatatypeValidator* temp = (DateTimeDatatypeValidator*) this;
try
{
temp->checkContent(rawData, 0, false, toUse);
}
catch (...)
{
return 0;
}
}
try
{
XMLDateTime aDateTime(rawData, toUse);
aDateTime.parseDateTime();
return aDateTime.getDateTimeCanonicalRepresentation(toUse);
}
catch (...)
{
return 0;
}
}
/***
* Support for Serialization/De-serialization
***/
IMPL_XSERIALIZABLE_TOCREATE(DateTimeDatatypeValidator)
void DateTimeDatatypeValidator::serialize(XSerializeEngine& serEng)
{
DateTimeValidator::serialize(serEng);
}
XERCES_CPP_NAMESPACE_END
/**
* End of file DateTimeDatatypeValidator::cpp
*/
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
]
| [
[
[
1,
139
]
]
]
|
368f0c55f7cb47b59fc955123e8514c3db128770 | 619941b532c6d2987c0f4e92b73549c6c945c7e5 | /Stellar_/code/Foundation/Utility/blob.cc | 80e66bfa5b26c1a7ecfcc631c495ad4b9c7b8380 | []
| no_license | dzw/stellarengine | 2b70ddefc2827be4f44ec6082201c955788a8a16 | 2a0a7db2e43c7c3519e79afa56db247f9708bc26 | refs/heads/master | 2016-09-01T21:12:36.888921 | 2008-12-12T12:40:37 | 2008-12-12T12:40:37 | 36,939,169 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 348 | cc | //------------------------------------------------------------------------------
// blob.cc
// (C) 2006 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "utility/blob.h"
namespace Util
{
Memory::Heap* Blob::DataHeap = 0;
Memory::Heap* Blob::ObjectHeap = 0;
} | [
"ctuomail@5f320639-c338-0410-82ad-c55551ec1e38"
]
| [
[
[
1,
12
]
]
]
|
a08d32c50f16b2cfaff21b1d78cba2975f800946 | 3965e5c3231c720938cc10202d2baf5443352ffd | /optimization/numerical_base/od_min_finder.cpp | 1496d31153014b8bf2797cf726ed83cd3cd51dda | []
| no_license | smi13/semester06 | 4224f691677cea6769d7d06acbb8cacbe60f37d8 | 10cd78eb98ca26b46d133b805be5bef06a8ee136 | refs/heads/master | 2021-03-12T21:33:59.363142 | 2010-08-25T22:52:55 | 2010-08-25T22:52:55 | 862,620 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,441 | cpp | #include <cstring>
#include <cstdio>
#include <cmath>
#include "function.h"
#include "od_min_finder.h"
OdMinFinder::OdMinFinder( SimpleFunc &func , double a, double b ) : _funcCounter(0), _iterCounter(0),
_eps(-1), _a(a), _b(b), _func(func)
{
}
double OdMinFinder::find( double &x, METHOD m, int iter_number )
{
if (_eps < 0)
throw "No way, bitch!";
if (m == DICHOTOMY)
return _findDichotomy(x, iter_number);
if (m == GOLDEN_RATIO)
return _findGoldenRatio(x, iter_number);
throw "No way, bitch!";
}
int OdMinFinder::getIterCounter()
{
return _iterCounter;
}
int OdMinFinder::getFuncCounter()
{
return _funcCounter;
}
void OdMinFinder::_iterDichotomy( double &a, double &b )
{
double x1, x2, delta = _eps / 3;
x1 = (a + b) * 0.5 - delta;
x2 = (a + b) * 0.5 + delta;
double fx1 = _func(x1), fx2 = _func(x2);
_funcCounter += 2;
if (fx1 > fx2)
a = x1;
else
b = x2;
_iterCounter++;
}
double OdMinFinder::_findDichotomy( double &x, int iter_number )
{
double a = _a, b = _b;
if (iter_number == -1)
{
do
{
double tmp = (_b - _a);
if (fabs(tmp) < 2 * _eps)
break;
_iterDichotomy(_a, _b);
} while (true);
}
else
{
while (iter_number-- > 0)
{
_iterDichotomy(_a, _b);
}
}
x = (_a + _b) * 0.5;
return _func(x);
}
double OdMinFinder::_iterGoldenRatio( double &a, double &b )
{
int ret;
static double u1, u2, y1, y2, tmp1, tmp2;
if (_iterCounter == 0)
{
u1 = a + (3 - sqrt(5.0)) * 0.5 * (b - a);
u2 = a + (sqrt(5.0) - 1) * 0.5 * (b - a);
y1 = _func(u1);
_funcCounter++;
y2 = _func(u2);
_funcCounter++;
}
if (y1 > y2)
{
ret = 1;
a = u1;
u1 = u2;
y1 = y2;
tmp1 = a + (3 - sqrt(5.0)) * 0.5 * (b - a);
tmp2 = a + (sqrt(5.0) - 1) * 0.5 * (b - a);
if (fabs(tmp1 - u1) > fabs(tmp2 - u1))
u2 = tmp1;
else
u2 = tmp2;
y2 = _func(u2);
_funcCounter++;
}
else
{
ret = 2;
b = u2;
u2 = u1;
y2 = y1;
tmp1 = a + (3 - sqrt(5.0)) * 0.5 * (b - a);
tmp2 = a + (sqrt(5.0) - 1) * 0.5 * (b - a);
if (fabs(tmp1 - u2) > fabs(tmp2 - u2))
u1 = tmp1;
else
u1 = tmp2;
y1 = _func(u1);
_funcCounter++;
}
_iterCounter++;
if (ret == 1)
return u1;
else
return u2;
}
double OdMinFinder::_findGoldenRatio( double &x, int iter_number )
{
double a = _a, b = _b;
if (iter_number == -1)
{
do
{
double tmp = _b - _a;
if (fabs(tmp) < 2 * _eps)
break;
x = _iterGoldenRatio(_a, _b);
} while (true);
}
else
{
while (iter_number-- > 0)
{
x = _iterGoldenRatio(a, b);
}
}
return _func(x);
}
void OdMinFinder::getBorders( double &a, double &b )
{
a = _a;
b = _b;
}
void OdMinFinder::setEps( double eps )
{
this->_eps = eps;
}
void OdMinFinder::resetCounters()
{
_funcCounter = 0;
_iterCounter = 0;
}
void OdMinFinder::setBorders( double &a, double &b )
{
_a = a;
_b = b;
}
| [
"[email protected]"
]
| [
[
[
1,
198
]
]
]
|
d018bc6752a27b3a96c73ced4fc8f7825f0709b9 | 3eb83d1b36fb5ada2c7bcd35607f1ead259e283f | /DS/Projects/LevelEditor/CLevelDataMap.cpp | 0991f901ef90b8eeb94d137da5814fcd93ab6964 | []
| no_license | mickvangelderen/uwars | 2235b8883649843ed9dc2dca34260649132aa306 | 2cc4f6380f5046afa533b6a898b5513c1ab43af6 | refs/heads/master | 2021-01-01T18:18:44.665224 | 2010-03-23T15:43:17 | 2010-03-23T15:43:17 | 32,515,782 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,096 | cpp | #include "CLevelDataMap.h"
#include <iostream>
#include <stdio.h>
#include <string>
#include <vector>
#include "Types.h"
#include "Team.h"
#include "CLevelDataCell.h"
#include "StrLib.h"
CLevelDataMap::CLevelDataMap()
: m_name(""), m_description(""), m_level(0),
m_width(0), m_height(0), m_cells(){
}
CLevelDataMap::~CLevelDataMap(){
Destroy();
}
void CLevelDataMap::Set(string & name, string & description, u8 level, u32 width, u32 height, vector<CLevelDataCell> & cells){
Destroy();
this->m_name = name;
this->m_description = description;
this->m_level = level;
this->m_width = width;
this->m_height = height;
this->m_cells = cells;
}
void CLevelDataMap::Reset(){
Destroy();
m_width = 0;
m_height = 0;
}
void CLevelDataMap::Destroy(){
m_name.clear();
m_description.clear();
m_cells.clear();
}
void CLevelDataMap::Write(){
if(m_name.empty()) m_name = "Unnamed";
if(m_description.empty()) m_description = "No description specified";
string levelName = m_name + ".lvl";
FILE * f = fopen(levelName.c_str(), "wb");
u16 nCells = m_cells.size();
if(f){
WriteString(m_name, f);
WriteString(m_description, f);
fwrite(&m_level, sizeof(m_level), 1, f);
fwrite(&m_width, sizeof(m_width), 1, f);
fwrite(&m_height, sizeof(m_height), 1, f);
fwrite(&nCells, sizeof(nCells), 1, f);
for(u8 i=0; i<nCells; i++){
m_cells[i].Write(f);
}
}
fclose(f);
}
void CLevelDataMap::Read(string & mapname){
Destroy();
string levelName = mapname + ".lvl";
FILE * f = fopen(levelName.c_str(), "rb");
if(f){
m_name = ReadString(f);
m_description = ReadString(f);
fread(&m_level, sizeof(m_level), 1, f);
fread(&m_width, sizeof(m_width), 1, f);
fread(&m_height, sizeof(m_height), 1, f);
u16 numberOfCells = 0;
fread(&numberOfCells, sizeof(numberOfCells), 1, f);
if(numberOfCells > 0){
CLevelDataCell temp;
for(u8 i=0; i<numberOfCells; i++){
temp.Read(f);
m_cells.push_back(temp);
}
}
}
else{
std::cout<<"Couln't find/open file for reading\n";
}
} | [
"mickfreeze@097d8bfe-0ac2-11df-beaf-bb271b2086c6"
]
| [
[
[
1,
89
]
]
]
|
d321b68e933e25471d2c61ee3f321a8a0ec539fd | 28476e6f67b37670a87bfaed30fbeabaa5f773a2 | /src/AutumnGen/src/Configuration.cpp | 1c9abb1a5adf07e6de23ebd701547d056dc29b1a | []
| no_license | rdmenezes/autumnframework | d1aeb657cd470b67616dfcf0aacdb173ac1e96e1 | d082d8dc12cc00edae5f132b7f5f6e0b6406fe1d | refs/heads/master | 2021-01-20T13:48:52.187425 | 2008-07-17T18:25:19 | 2008-07-17T18:25:19 | 32,969,073 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,478 | cpp | /*
* Copyright 2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <map>
#include "Configuration.h"
using namespace std;
string Configuration::ClassWrapperSuffix = "_Wrapper";
string Configuration::FileWrapperSuffix = "_Wrapper";
string Configuration::HeadFileSuffix = ".h";
string Configuration::ImplFileSuffix = ".cpp";
string Configuration::OutPath = "";
void Configuration::setConfigs(map<string, string>& cons)
{
map<string, string>::iterator it = cons.begin();
while( it != cons.end() ){
if( it->first.compare("-out") == 0 )
Configuration::OutPath = it->second;
else if( it->first.compare("-hsuf") == 0 )
Configuration::HeadFileSuffix = it->second;
else if( it->first.compare("-isuf") == 0 )
Configuration::ImplFileSuffix = it->second;
else if( it->first.compare("-wsuf") == 0 )
Configuration::FileWrapperSuffix = it->second;
it++;
}
}
| [
"sharplog@c16174ff-a625-0410-88e5-87db5789ed7d"
]
| [
[
[
1,
44
]
]
]
|
bc0a2abf06470a3d21ec05cdfda2ac061af97f4a | 1c9f99b2b2e3835038aba7ec0abc3a228e24a558 | /Projects/elastix/elastix_sources_v4/src/Components/Optimizers/CMAEvolutionStrategy/elxCMAEvolutionStrategy.h | b972273ead824510a7b63247a8b446ec6d7dd5ef | []
| no_license | mijc/Diploma | 95fa1b04801ba9afb6493b24b53383d0fbd00b33 | bae131ed74f1b344b219c0ffe0fffcd90306aeb8 | refs/heads/master | 2021-01-18T13:57:42.223466 | 2011-02-15T14:19:49 | 2011-02-15T14:19:49 | 1,369,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,032 | h | /*======================================================================
This file is part of the elastix software.
Copyright (c) University Medical Center Utrecht. All rights reserved.
See src/CopyrightElastix.txt or http://elastix.isi.uu.nl/legal.php 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 __elxCMAEvolutionStrategy_h
#define __elxCMAEvolutionStrategy_h
#include "itkCMAEvolutionStrategyOptimizer.h"
#include "elxIncludes.h"
namespace elastix
{
using namespace itk;
/**
* \class CMAEvolutionStrategy
* \brief An optimizer based on the itk::CMAEvolutionStrategyOptimizer.
*
* A Covariance-Matrix-Adaptation-Evolution-Strategy optimizer.
*
* This optimizer support the NewSamplesEveryIteration option. It requests
* new samples for the computation of each search direction (not during
* the offspring generation). The theory doesn't say anything about such a
* situation, so, think twice before using the NewSamplesEveryIteration option.
*
* The parameters used in this class are:
* \parameter Optimizer: Select this optimizer as follows:\n
* <tt>(Optimizer "CMAEvolutionStrategy")</tt>
* \parameter MaximumNumberOfIterations: The maximum number of iterations in each resolution. \n
* example: <tt>(MaximumNumberOfIterations 100 100 50)</tt> \n
* Default value: 500.\n
* \parameter StepLength: Set the length of the initial step ( = Sigma0 = InitialSigma).\n
* example: <tt>(StepLength 2.0 1.0 0.5)</tt> \n
* Recommended value: 1/3 of the expected parameter range.\n
* Default value: 1.0.\n
* \parameter ValueTolerance: Stopping criterion. See the documentation of the
* itk::CMAEvolutionStrategyOptimizer for more information.\n
* example: <tt>(ValueTolerance 0.001 0.0001 0.000001)</tt> \n
* Default value: 0.00001. Can be specified for each resolution.\n
* \parameter PositionToleranceMin: Stopping criterion. See the documentation of the
* itk::CMAEvolutionStrategyOptimizer for more information.\n
* example: <tt>(PositionToleranceMin 0.001 0.0001 0.000001)</tt> \n
* Default value: 1e-8. Can be specified for each resolution.\n
* \parameter PositionToleranceMax: Stopping criterion. See the documentation of the
* itk::CMAEvolutionStrategyOptimizer for more information.\n
* example: <tt>(PositionToleranceMax 0.001 0.0001 0.000001)</tt> \n
* Default value: 1e8. Can be specified for each resolution.\n
* \parameter PopulationSize: the number of parameter vectors evaluated in each iteration.\n
* If you set it to 0, a default value is calculated by the optimizer, which is reported
* back to the elastix.log file.\n
* example: <tt>(PopulationSize 0 20 20)</tt> \n
* Default: 0 (so, automatically determined). Can be specified for each resolution.\n
* \parameter NumberOfParents: the number of parameter vectors selected for recombination.\n
* If you set it to 0, a default value is calculated
* by the optimizer, which is reported back to the elastix.log file.\n
* example: <tt>(NumberOfParents 0 10 10)</tt> \n
* Default: 0 (so, automatically determined). Can be specified for each resolution. \n
* This value must be less than or equal to the PopulationSize.\n
* \parameter MaximumDeviation: the step length is limited to this value. See the documentation of the
* itk::CMAEvolutionStrategyOptimizer for more information.\n
* example: <tt>(MaximumDeviation 10.0 10.0 5.0)</tt> \n
* Default: 10.0 * positionToleranceMax = practically infinity. Can be specified for each resolution.\n
* \parameter MinimumDeviation: the step length is ensured to be greater than this value.\n
* See the documentation of the itk::CMAEvolutionStrategyOptimizer for more information.\n
* example: <tt>(MinimumDeviation 0.01 0.01 0.0001)</tt> \n
* Default: 0.0. Can be specified for each resolution.\n
* \parameter UseDecayingSigma: use a predefined decaying function to control the steplength sigma.\n
* example: <tt>(UseDecayingSigma "false" "true" "false")</tt> \n
* Default/recommended: "false". Can be specified for each resolution.\n
* If you set it to true the SP_A and SP_alpha parameters apply.\n
* \parameter SP_A: If UseDecayingSigma is set to "true", the steplength \f$sigma(k)\f$ at each
* iteration \f$k\f$ is defined by: \n
* \f$sigma(k+1) = sigma(k) (SP\_A + k)^{SP\_alpha} / (SP\_A + k + 1)^{SP\_alpha}\f$. \n
* where sigma(0) is set by the parameter "StepLength". \n
* example: <tt>(SP_A 50.0 50.0 100.0)</tt> \n
* The default value is 50.0. SP_A can be defined for each resolution. \n
* \parameter SP_alpha: If UseDecayingSigma is set to "true", the steplength \f$sigma(k)\f$ at each
* iteration \f$k\f$ is defined by: \n
* \f$sigma(k+1) = sigma(k) (SP\_A + k)^{SP\_alpha} / (SP\_A + k + 1)^{SP\_alpha}\f$. \n
* where sigma(0) is set by the parameter "StepLength".\n
* example: <tt>(SP_alpha 0.602 0.602 0.602)</tt> \n
* The default value is 0.602. SP_alpha can be defined for each resolution. \n
* \parameter UseCovarianceMatrixAdaptation: a boolean that determines whether to use the
* covariance matrix adaptation scheme.\n
* example: <tt>(UseCovarianceMatrixAdaptation "false" "true" "true")</tt> \n
* Default: "true". This parameter may be altered by the optimizer. The actual value used is \n
* reported back in the elastix.log file. This parameter can be specified for each resolution. \n
* \parameter RecombinationWeightsPreset: the name of a preset for the recombination weights.\n
* See the documentation of the itk::CMAEvolutionStrategyOptimizer for more information.\n
* example: <tt>(UseCovarianceMatrixAdaptation "equal" "linear" "superlinear")</tt> \n
* Default/recommended: "superlinear". Choose one of {"equal", "linear", "superlinear"}.
* This parameter can be specified for each resolution. \n
* \parameter UpdateBDPeriod: the number of iterations after which the eigendecomposition of the
* covariance matrix is updated. If 0, the optimizer estimates a value. The actual value used is
* reported back in the elastix.log file. This parameter can be specified for each resolution. \n
* example: <tt>(UpdateBDPeriod 0 0 50)</tt> \n
* Default: 0 (so, automatically determined).
*
* \ingroup Optimizers
*/
template <class TElastix>
class CMAEvolutionStrategy :
public
itk::CMAEvolutionStrategyOptimizer,
public
OptimizerBase<TElastix>
{
public:
/** Standard ITK.*/
typedef CMAEvolutionStrategy Self;
typedef CMAEvolutionStrategyOptimizer Superclass1;
typedef OptimizerBase<TElastix> Superclass2;
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
/** Method for creation through the object factory. */
itkNewMacro( Self );
/** Run-time type information (and related methods). */
itkTypeMacro( CMAEvolutionStrategy, CMAEvolutionStrategyOptimizer );
/** Name of this class.
* Use this name in the parameter file to select this specific optimizer. \n
* example: <tt>(Optimizer "CMAEvolutionStrategy")</tt>\n
*/
elxClassNameMacro( "CMAEvolutionStrategy" );
/** Typedef's inherited from Superclass1.*/
typedef Superclass1::CostFunctionType CostFunctionType;
typedef Superclass1::CostFunctionPointer CostFunctionPointer;
typedef Superclass1::StopConditionType StopConditionType;
typedef Superclass1::ParametersType ParametersType;
typedef Superclass1::DerivativeType DerivativeType;
typedef Superclass1::ScalesType ScalesType;
/** Typedef's inherited from Elastix.*/
typedef typename Superclass2::ElastixType ElastixType;
typedef typename Superclass2::ElastixPointer ElastixPointer;
typedef typename Superclass2::ConfigurationType ConfigurationType;
typedef typename Superclass2::ConfigurationPointer ConfigurationPointer;
typedef typename Superclass2::RegistrationType RegistrationType;
typedef typename Superclass2::RegistrationPointer RegistrationPointer;
typedef typename Superclass2::ITKBaseType ITKBaseType;
/** Check if any scales are set, and set the UseScales flag on or off;
* after that call the superclass' implementation */
virtual void StartOptimization(void);
/** Methods to set parameters and print output at different stages
* in the registration process.*/
virtual void BeforeRegistration(void);
virtual void BeforeEachResolution(void);
virtual void AfterEachResolution(void);
virtual void AfterEachIteration(void);
virtual void AfterRegistration(void);
protected:
CMAEvolutionStrategy(){};
virtual ~CMAEvolutionStrategy() {};
/** Call the superclass' implementation and print the value of some variables */
virtual void InitializeProgressVariables(void);
private:
CMAEvolutionStrategy( const Self& ); // purposely not implemented
void operator=( const Self& ); // purposely not implemented
}; // end class CMAEvolutionStrategy
} // end namespace elastix
#ifndef ITK_MANUAL_INSTANTIATION
#include "elxCMAEvolutionStrategy.hxx"
#endif
#endif // end #ifndef __elxCMAEvolutionStrategy_h
| [
"[email protected]"
]
| [
[
[
1,
196
]
]
]
|
aa0591e4e686b04c38cc166d374eeac05fc126d8 | 1b2eb18a7d77e160bf992f952767198fe00fe10e | /trunk/096/pkg/packetHooks/PartySystem/include/packetInfo.inc | c21c18024e55cb5028260a35dd2066f7fe29cc92 | []
| no_license | BackupTheBerlios/poldistro-svn | 96fd832f9a7479bdc4d00501af45a14a3c571c0f | 251f022debb3e4d4ff3c9c43f3bf1029f15e47b1 | refs/heads/master | 2020-05-18T14:11:44.348758 | 2006-05-20T16:06:44 | 2006-05-20T16:06:44 | 40,800,663 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 315 | inc | // None of these need to be changed unless the UO client is reprogrammed to use different packet structure...
// So these will never need to be changed.
const MSGTYPE_PARTY := 0xBF;
const SUBCMD_PARTY := 6;
const OFFSET_PARTY_MSGLEN := 1;
const OFFSET_PARTY_SUBCMD := 3;
const OFFSET_PARTY_SUBSUBCMD := 5; | [
"austin@9d346cd0-66fc-0310-bdc5-e57197e5a75e"
]
| [
[
[
1,
9
]
]
]
|
d44ac9de7cbcbfb06fcbedb93eabe0ece2973c83 | 27bf1951e08b36c01374014a6da855a706680f7b | /USACO-Solution/src/1.2.5.cpp | 5bf03c082d7c8d27716a499a9e25c769b5d7745f | []
| no_license | zinking/algorithm-exercise | 4c520fd3ff6c14804d32e4ea427e5f7809cc7315 | c58902709e9f12146d3d1f66610306e5ff19cfff | refs/heads/master | 2016-09-05T22:27:19.791962 | 2009-07-24T04:45:18 | 2009-07-24T04:45:18 | 32,133,027 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,277 | cpp | /*
ID: zinking1
PROG: palsquare
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#define MAXLEN 40
ofstream fout ("palsquare.out");
ifstream fin ("palsquare.in");
bool toRadix( int base, int src, int result[MAXLEN], bool testPalindromes = true ){
int len = 0;
do{
result[len] = src % base;
len ++;
}while( src /= base );
result[len] = -1;
for( int i=0, j= len-1; i < j; i++, j-- ){
int temp = result[i];
result[i] = result[j];
result[j] = temp;
}
if( testPalindromes ){
for( int i=0, j= len-1; i < j; i++, j-- ){
if( result[i] != result[j] ) return false;
}
return true;
}
return false;
}
void output_number( int result[MAXLEN] ){
for( int i=0; result[i] != -1; i++ ){
if ( result[i] < 10 ) fout << result[i];
else{
fout << static_cast<char>( 'A' + result[i] - 10 );
}
}
}
int main() {
int base = 0;
fin >> base;
int converted[MAXLEN];
int converted_src[10];
for( int N=1; N <= 300; N++ ){
if( toRadix( base, N*N, converted) ){
toRadix( base, N, converted_src , false );
output_number( converted_src );
fout << " ";
output_number( converted );
fout << endl;
}
}
return 0;
}
| [
"zinking3@e423e194-685c-11de-ba0c-230037762ff9"
]
| [
[
[
1,
71
]
]
]
|
a9919df95c251f8aa89ef072f9ded556367e2ac9 | a6a3df5a00bf2389f723e6cb8bd69fc3c0618301 | /FxMainWin.cpp | 1c1fa2f57899ba3d5155a5974a55d969e6a85e3f | []
| no_license | libfetion/libfetion-gui-wince | 4de482e3451faf0bba885b14b57fc01b2bb980cd | b69456b10d888ff3b7421b401887a69333c72c12 | refs/heads/master | 2020-04-16T08:02:28.921130 | 2011-03-14T14:55:39 | 2011-03-14T14:55:39 | 32,465,759 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 52,358 | cpp | /***************************************************************************
* Copyright (C) 2008 by DDD *
* [email protected] *
* *
***************************************************************************/
// FxMainWin.cpp : 实现文件
#include "stdafx.h"
#include "WMLF.h"
#include "FxMainWin.h"
#include "LoginDlg.h"
#include "FxBuddy.h"
#include "FindBuddyDlg.h"
#include "Notify.h"
#include "BuddyInfoDlg.h"
#include "About.h"
#include "IniWR.h"
#include "FxDatabase.h"
#include "MyselfInfoDlg.h"
#include "FontSetting.h"
#include "AuthCodeDlg.h"
#ifdef M8
#include "M8Misc.h"
#endif
extern CFxDatabase * g_pFxDB;
#define TIMER_NEWMSG 15
#define TIMER_RELOGIN 20
#define TIMER_UPDATE_ACCOUNTINFO 25
#define TIMER_ADD_ITEM_TO_TREE 30
void Sys_EventListener (int message, WPARAM wParam, LPARAM lParam, void* args)
{
if(!args)
return;
FxMainWin * mainWind = (FxMainWin *) args;
if (message == FX_NEW_MESSAGE)
::SendMessage(mainWind->m_hWnd, message + WM_USER, wParam, lParam);
else
::PostMessage(mainWind->m_hWnd, message + WM_USER, wParam, lParam);
}
BOOL FxMainWin::handleFx_Sys_Event(int message, WPARAM wParam, LPARAM lParam)
{
if (message < WM_USER)
return FALSE;
switch(message - WM_USER)
{
case FX_CURRENT_VERSION:
//emit signal_Current_Version((int)wParam);
return TRUE;
case FX_ADDACCOUNT_APP:
handle_AddAccountApp((char*)(lParam), (char*)wParam);
return TRUE;
case FX_MOVE_GROUP_OK:
handle_MoveGroupOk((long)lParam, (int)wParam);
return TRUE;
case FX_NEW_MESSAGE:
addNewMessage(long(lParam));
return TRUE;
case FX_NEW_QUN_MESSAGE:
addNewQunMessage(long(lParam));
return TRUE;
case FX_SET_STATE_OK:
//emit signal_set_state((int)wParam);
m_strNickNameShow = m_strNickName + GetUserStateString();
this->UpdateData(FALSE);
return TRUE;
case FX_STATUS_ONLINE:
//如果触发事件的不是当前用户,则提示用户上线
if(m_lAccountID != lParam)
NotifyUser(2, (long)lParam, L"");
case FX_SET_BUDDY_INFO_OK:
case FX_STATUS_OFFLINE:
case FX_STATUS_BUSY:
case FX_STATUS_AWAY:
case FX_STATUS_MEETING:
case FX_STATUS_PHONE:
case FX_STATUS_DINNER:
case FX_STATUS_EXTENDED_AWAY:
case FX_STATUS_NUM_PRIMITIVES:
case FX_ACCOUNT_UPDATA_OK:
case FX_REMOVE_BLACKLIST_OK:
case FX_ADD_BLACKLIST_OK:
case FX_STATUS_SMSEXTENED:
this->m_BuddyOpt->updateAccountInfo(lParam);
if(m_BuddyInfoDlg && (m_BuddyInfoDlg->m_lAccountID == lParam))
{
m_BuddyInfoDlg->updateAccountInfo();
}
m_pFxMsgDlgView->updateAccountInfo(lParam);
return TRUE;
case FX_SET_REFUSE_SMS_DAY_OK:
//emit signal_UpdateSmsDay((wParam));
return TRUE;
case FX_SYS_ERR_NETWORK:
hand_SystemNetErr( wParam);
return TRUE;
case FX_SYS_DEREGISTERED:
MessageBox(_T("您已经在其它地方登录,程序将退出!"), _T("LibFetion"), MB_ICONSTOP);
::exit(0); //fixed: no release the res of this app...
return TRUE;
case FX_DIA_SEND_OK:
case FX_DIA_SEND_FAIL:
case FX_DIA_SEND_TIMEOUT:
case FX_SMS_OK:
case FX_SMS_FAIL:
case FX_SMS_FAIL_LIMIT:
case FX_SMS_TIMEOUT:
case FX_QUN_SEND_OK:
case FX_QUN_SEND_FAIL:
case FX_QUN_SEND_TIMEOUT:
case FX_QUN_SMS_OK:
case FX_QUN_SMS_FAIL:
case FX_QUN_SMS_FAIL_LIMIT:
case FX_QUN_SMS_TIMEOUT:
hand_MsgSend_Event( message - WM_USER, wParam, (long)lParam);
return TRUE;
case FX_ADD_BUDDY_OK:
fx_update_account_info_by_id((long)lParam);
//this->m_BuddyOpt->addAccountToGroup( fx_get_account_by_id((long)lParam) );
//update_account_info();
return TRUE;
case FX_RENAME_GROUP_OK:
//emit signal_reName_group( message, wParam, (qlonglong)lParam);
return TRUE;
//case FX_SET_BUDDY_INFO_OK:
//这个消息被放到上面与更新状态等消息一并处理
//emit signal_reName_buddy( message, wParam, (qlonglong)lParam);
return TRUE;
case FX_ADD_GROUP_OK:
//emit signal_add_group( message, wParam, (qlonglong)lParam);
return TRUE;
case FX_DEL_GROUP_OK:
//emit signal_del_group( message, wParam, (qlonglong)lParam);
return TRUE;
case FX_DEL_BUDDY_OK:
this->m_BuddyOpt->delAccount_direct((long)lParam);
return TRUE;
case FX_ADD_GROUP_FAIL:
case FX_DEL_GROUP_FAIL:
case FX_SET_BUDDY_INFO_FAIL:
case FX_RENAME_GROUP_FAIL: //ignored this message
if(wParam)
free((char*)(int)wParam);
return TRUE;
case FX_SET_NICKNAME_OK:
{
const Fetion_Personal * pInfo = fx_data_get_PersonalInfo();
m_strNickName = ConvertUtf8ToUtf16(pInfo->nickname);
m_strNickNameShow = m_strNickName + GetUserStateString();
this->UpdateData(FALSE);
}
return TRUE;
case FX_SET_IMPRESA_OK:
{
const Fetion_Personal * pInfo = fx_data_get_PersonalInfo();
m_strSign = ConvertUtf8ToUtf16(pInfo->impresa);
this->UpdateData(FALSE);
}
return TRUE;
#if 0 //follow message is ignored
case FX_MOVE_GROUP_FAIL:
case FX_REMOVE_BLACKLIST_FAIL:
case FX_ADD_BLACKLIST_FAIL:
case FX_REMOVE_BLACKLIST_TIMEOUT:
case FX_ADD_BLACKLIST_TIMEOUT:
case FX_RENAME_GROUP_TIMEOUT:
case FX_SET_BUDDY_INFO_TIMEOUT:
case FX_SET_REFUSE_SMS_DAY_FAIL:
#endif
//for relogin message. note: not for login
case FX_LOGIN_URI_ERROR:
case FX_LOGIN_FAIL:
case FX_LOGIN_NETWORK_ERROR:
case FX_LOGIN_UNKOWN_ERROR :
case FX_LOGIN_UNKOWN_USR:
case FX_LOGIN_GP_FAIL:
relogin_fetion();
break;
case FX_LOGIN_OK :
KillTimer(TIMER_RELOGIN);
relogin_ok();
break;
//for relogin message. note: not for login
case FX_LOGIN_NEED_AUTH_CODE:
m_verfy = fx_get_auth_code((char *)wParam);
if(m_verfy && m_verfy->pic)
{
CAuthCodeDlg dlg;
dlg.m_verfy = m_verfy;
INT_PTR nResponse = dlg.DoModal();
UpdateWindow();
if(IDOK == nResponse)
{
fx_set_auth_code(ConvertUtf16ToUtf8(dlg.m_strInputAuthCode).GetBuffer(), m_verfy);
}
else
{
fx_set_auth_code(NULL, m_verfy);
}
}
break;
default:
break;
}
return FALSE;
}
// FxMainWin 对话框
IMPLEMENT_DYNAMIC(FxMainWin, CDialog)
FxMainWin::FxMainWin(CWnd* pParent /*=NULL*/)
: CDialog(FxMainWin::IDD, pParent)
, loginDlg(NULL)
, m_BuddyOpt(NULL)
, m_BuddyInfoDlg(NULL)
, m_isLoginOK(FALSE)
, m_strNickName(_T(""))
, m_strNickNameShow(_T(""))
, m_strSign(_T(""))
, m_strStartupPath(_T(""))
, m_lAccountID(0)
, m_strMobileNo(_T(""))
, m_pFxMsgDlgView(NULL)
, m_pTreeFont(NULL)
, m_nTreeFontSize(9)
//, m_pFxDB(NULL)
, m_strAccountID(_T(""))
, m_verfy(NULL)
{
}
FxMainWin::~FxMainWin()
{
if(NULL != m_pFxMsgDlgView)
{
delete m_pFxMsgDlgView;
m_pFxMsgDlgView = NULL;
}
if(NULL != g_pFxDB)
{
delete g_pFxDB;
g_pFxDB = NULL;
}
if(NULL != m_pTreeFont)
{
delete m_pTreeFont;
m_pTreeFont = NULL;
}
if(NULL != loginDlg)
{
delete loginDlg;
loginDlg = NULL;
}
}
void FxMainWin::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_TREE_BUDDY, view);
DDX_Text(pDX, IDC_INFO_NAME, m_strNickNameShow);
DDX_Text(pDX, IDC_INFO_SIGN, m_strSign);
}
BEGIN_MESSAGE_MAP(FxMainWin, CDialog)
ON_WM_SIZE()
ON_WM_RBUTTONUP()
ON_WM_LBUTTONUP()
ON_WM_LBUTTONDBLCLK()
ON_WM_LBUTTONDOWN()
ON_WM_CLOSE()
ON_WM_TIMER()
//ON_COMMAND(IDM_MAIN_SENDMSG, &FxMainWin::OnSendMsg)
//ON_STN_CLICKED(IDC_BTN_ADD, &FxMainWin::OnStnClickedBtnAdd)
ON_COMMAND(IDM_MAIN_SET_VIBR, &FxMainWin::OnMainSetVibr)
ON_COMMAND(IDM_MAIN_SET_SILENCE, &FxMainWin::OnMainSetSilence)
ON_UPDATE_COMMAND_UI(IDM_MAIN_SET_SILENCE, &FxMainWin::OnUpdateMainSetSilence)
ON_UPDATE_COMMAND_UI(IDM_MAIN_SET_VIBR, &FxMainWin::OnUpdateMainSetVibr)
ON_COMMAND(IDM_MAIN_SET_ONLINE,&FxMainWin::OnMainSetOnline)
ON_UPDATE_COMMAND_UI(IDM_MAIN_SET_ONLINE,&FxMainWin::OnUpdateMainSetOnline)
ON_COMMAND(IDM_MAIN_SET_SHIELDQUNMESSAGE,&FxMainWin::OnMainShieldQunMessage)
ON_UPDATE_COMMAND_UI(IDM_MAIN_SET_SHIELDQUNMESSAGE,&FxMainWin::OnUpdateShieldQunMessage)
ON_COMMAND(IDM_BD_VIEWINFO, &FxMainWin::OnBdViewinfo)
ON_WM_INITMENUPOPUP()
// ON_COMMAND(IDM_MAIN_ADDBUDDY, &FxMainWin::OnMainAddbuddy)
ON_COMMAND(IDM_ABOUT, &FxMainWin::OnAbout)
ON_COMMAND(IDM_BD_DELETE, &FxMainWin::OnBdDelete)
ON_COMMAND(IDM_BD_ADDBLACKLIST, &FxMainWin::OnBdAddblacklist)
ON_COMMAND(IDM_BD_RMBLACKLIST, &FxMainWin::OnBdRmblacklist)
ON_COMMAND(IDM_MAIN_SET_NOSOUND, &FxMainWin::OnMainSetNosound)
ON_COMMAND(IDM_MAIN_SHOWNEWMSG, &FxMainWin::OnMainShownewmsg)
ON_COMMAND(IDM_BD_SENDMSG, &FxMainWin::OnBdSendmsg)
ON_COMMAND(IDM_BD_READDBUDDY, &FxMainWin::OnBdReAddbuddy)
ON_COMMAND(IDM_MAIN_ADDBUDDY, &FxMainWin::OnMainAddbuddy)
ON_COMMAND(IDM_MAIN_CLEAN, &FxMainWin::OnMainClean)
ON_COMMAND(IDM_SEND_MYSELF, &FxMainWin::OnSendMyself)
ON_COMMAND(IDM_UPDATE_ALL_ACCOUNTINFO, &FxMainWin::OnUpdateAllAccountinfo)
ON_COMMAND(IDM_MAIN_SET_LONGSMS, &FxMainWin::OnMainSetLongsms)
ON_COMMAND(IDM_MYSELF_INFO, &FxMainWin::OnMyselfInfo)
ON_COMMAND(IDM_MAIN_FONT_SETTING, &FxMainWin::OnMainFontSetting)
ON_WM_ACTIVATE()
END_MESSAGE_MAP()
#ifdef WIN32_PLATFORM_WFSP
WNDPROC prevProc; //取得原窗口过程函数指针
CTreeCtrl *g_cTree; //CTreeCtrl指针,用于获取Dlg中的控件
LRESULT CALLBACK MyTreeProc(
HWND hwnd, // handle to window
UINT uMsg, // message identifier
WPARAM wParam, // first message parameter
LPARAM lParam // second message parameter
)
{
if(WM_GETDLGCODE == uMsg)
{
return DLGC_WANTMESSAGE;
}
else if(WM_KEYDOWN == uMsg)
{
switch(wParam) //确认键按下
{
case '5':
//case VK_RETURN:
{
//展开选中节点
HTREEITEM hItem = g_cTree->GetSelectedItem();
if ((hItem != NULL) && g_cTree->ItemHasChildren(hItem))
{
g_cTree->Expand(hItem, TVE_TOGGLE);
/*
if ((g_cTree->GetItemState(hItem, TVIS_EXPANDED) & TVIS_EXPANDED) == FALSE) //未展开
{
g_cTree->Expand(hItem, TVE_EXPAND);
g_cTree->EnsureVisible(hItem);
}
else //展开
{
g_cTree->Expand(hItem, TVE_COLLAPSE);
}
*/
}
break;
}
case '0':
ShowWindow(::GetParent(hwnd), SW_MINIMIZE );
break;
case '1':
g_cTree->SelectItem(g_cTree->GetFirstVisibleItem());
break;
case '2':
{
HTREEITEM hItem = g_cTree->GetNextItem(g_cTree->GetSelectedItem(),TVGN_PREVIOUSVISIBLE);
if(hItem)
{
g_cTree->SelectItem(hItem);
}
break;
}
case '4':
keybd_event(VK_LEFT, 0, KEYEVENTF_EXTENDEDKEY, 0);
keybd_event(VK_LEFT, 0, KEYEVENTF_KEYUP, 0);
break;
case '6':
keybd_event(VK_RIGHT, 0, KEYEVENTF_EXTENDEDKEY, 0);
keybd_event(VK_RIGHT, 0, KEYEVENTF_KEYUP, 0);
break;
case '7':
{
HTREEITEM hItem = g_cTree->GetNextVisibleItem(g_cTree->GetSelectedItem());
if(hItem)
{
while(1)
{
if(NULL == g_cTree->GetNextVisibleItem(hItem))
break;
hItem = g_cTree->GetNextVisibleItem(hItem);
}
g_cTree->SelectItem(hItem);
}
break;
}
case '8':
{
HTREEITEM hItem = g_cTree->GetNextItem(g_cTree->GetSelectedItem(),TVGN_NEXTVISIBLE);
if(hItem)
{
g_cTree->SelectItem(hItem);
}
break;
}
case '3':
break;
case '9':
keybd_event(0x5b, 0, KEYEVENTF_EXTENDEDKEY, 0);
keybd_event(0x5b, 0, KEYEVENTF_KEYUP, 0);
break;
case VK_TBACK:
break;
}
}
return prevProc(hwnd,uMsg,wParam,lParam);
}
#endif // WIN32_PLATFORM_WFSP
// FxMainWin 消息处理程序
BOOL FxMainWin::OnInitDialog()
{
do_login();
CDialog::OnInitDialog();
::SHDoneButton(this->m_hWnd,SHDB_HIDE);
m_pFxMsgDlgView = new CFxMsgDlgView(this);
m_pFxMsgDlgView->Create(IDD_WMLF_MSG_VIEW, this);
m_pFxMsgDlgView->ModifyStyleEx(0, WS_EX_CONTROLPARENT);
#ifdef WIN32_PLATFORM_WFSP
g_cTree = &view;
prevProc=(WNDPROC)SetWindowLong(view.m_hWnd,GWL_WNDPROC,(LONG)MyTreeProc);
#endif // WIN32_PLATFORM_WFSP
//#ifdef WIN32_PLATFORM_WFSP
#ifndef M8
if (!m_dlgCommandBar.Create(this) ||
!m_dlgCommandBar.InsertMenuBar(IDR_MAIN_MENU))
{
TRACE0("未能创建 CommandBar\n");
return FALSE; // 未能创建
}
#else
AddMenuBarForM8(this->GetSafeHwnd(), IDR_MAIN_MENU);
FullScreen(this->GetSafeHwnd());
#endif
//#endif // WIN32_PLATFORM_WFSP
UpdateData(FALSE);
g_pFxDB = new CFxDatabase;
if(!g_pFxDB->Init(m_strStartupPath + _T("\\Users\\") + m_strAccountID + _T("\\") + m_strAccountID + _T(".db")))
//if(!g_pFxDB->Init(_T("\\") + m_mobile_no + _T(".db")))
{
MessageBox(_T("打开数据库文件失败"), _T("LibFetion"), MB_ICONSTOP);
//::exit(0);
}
m_BuddyOpt = new BuddyOpt(&view);
// TODO: 在此添加额外的初始化代码
SetTimer(TIMER_ADD_ITEM_TO_TREE, 1, NULL);
//设置好友列表的字体大小
SetTreeBuddyFontSize(m_nTreeFontSize);
return TRUE; // return TRUE unless you set the focus to a control
}
void FxMainWin::do_login()
{
GetStartupPath();
loginDlg = new CLoginDlg;
loginDlg->m_strStartupPath = m_strStartupPath;
ZeroMemory(&m_ConnInfo, sizeof(m_ConnInfo));
m_ConnInfo.cbSize = sizeof(m_ConnInfo);
m_ConnInfo.dwParams = CONNMGR_PARAM_GUIDDESTNET;
m_ConnInfo.dwPriority = CONNMGR_PRIORITY_USERINTERACTIVE;
loginDlg->m_pConnInfo = &m_ConnInfo;
loginDlg->DoModal();
//if login false, will exit the application
if (loginDlg->m_LoginFlag != TRUE)
{
m_isLoginOK = FALSE;
//AfxMessageBox(_T("will quit"));
fx_terminate();
::exit(0);
} else {
m_isLoginOK = TRUE;
}
#if DEBUG_GUI
m_lAccountID = 0;
m_strNickName = _T("测试");
m_strSign = _T("落花不是无情物");
#else
const Fetion_Personal * pInfo = fx_data_get_PersonalInfo();
m_strNickName = ConvertUtf8ToUtf16(pInfo->nickname);
m_strNickNameShow = m_strNickName + GetUserStateString();
m_strSign = ConvertUtf8ToUtf16(pInfo->impresa);
m_strAccountID = ConvertUtf8ToUtf16(fx_get_usr_uid());
m_strMobileNo = ConvertUtf8ToUtf16(fx_get_usr_mobilenum());
m_lAccountID = strtol(fx_get_usr_uid(), NULL,10);
{
//读取设置信息
//新消息提醒
m_bSound = GetSettingFromIni(_T("Sound"), 1);
//震动提醒
m_bVibrate = GetSettingFromIni(_T("Vibrate"));
//上线提醒
m_bOnline = GetSettingFromIni(_T("Online"));
//无提醒
m_bSilence = GetSettingFromIni(_T("Silence"));
//屏蔽群消息
m_bShieldQunMessage = GetSettingFromIni(_T("ShieldQunMessage"));
//使用长短信
m_bLongSMS = GetSettingFromIni(_T("LongSMS"));
fx_set_longsms(m_bLongSMS);
//好友列表字体大小
m_nTreeFontSize = GetSettingFromIni(_T("TreeFontSize"), 9);
}
#endif
}
#if defined(_DEVICE_RESOLUTION_AWARE) //&& !defined(WIN32_PLATFORM_WFSP)
void FxMainWin::OnSize(UINT /*nType*/, int /*cx*/, int /*cy*/)
{
DRA::DisplayMode dp = DRA::GetDisplayMode();
//DRA::RelayoutDialog(
// AfxGetInstanceHandle(),
// this->m_hWnd,
// dp != DRA::Portrait ?
// MAKEINTRESOURCE(IDD_WMLF_MAIN_WIDE) :
// MAKEINTRESOURCE(IDD_WMLF_MAIN));
//if(dp == DRA::Portrait)
{
int xgrpInfo, ygrpInfo, wgrpInfo, hgrpInfo;
int xIDC_HEAD_PIC, yIDC_HEAD_PIC, wIDC_HEAD_PIC, hIDC_HEAD_PIC;
int xIDC_INFO_NAME, yIDC_INFO_NAME, wIDC_INFO_NAME, hIDC_INFO_NAME;
int xIDC_INFO_SIGN, yIDC_INFO_SIGN, wIDC_INFO_SIGN, hIDC_INFO_SIGN;
int xtvBuddy, ytvBuddy, wtvBuddy, htvBuddy;
RECT rcCtl;
::GetClientRect(this->m_hWnd, &rcCtl);
xgrpInfo = rcCtl.left;
ygrpInfo = rcCtl.top;
wgrpInfo = rcCtl.right - rcCtl.left;
hgrpInfo = DRA::SCALEY(40);
#ifdef M8
ygrpInfo += 24;
#endif
xIDC_HEAD_PIC = xgrpInfo + DRA::SCALEX(4);
yIDC_HEAD_PIC = ygrpInfo + DRA::SCALEY(4);
wIDC_HEAD_PIC = DRA::SCALEX(32);
hIDC_HEAD_PIC = DRA::SCALEY(32);
xIDC_INFO_NAME = xIDC_HEAD_PIC + DRA::SCALEX(36);
yIDC_INFO_NAME = yIDC_HEAD_PIC;
wIDC_INFO_NAME = wgrpInfo - xIDC_INFO_NAME - DRA::SCALEY(4);
hIDC_INFO_NAME = DRA::SCALEY(16);
xIDC_INFO_SIGN = xIDC_INFO_NAME;
yIDC_INFO_SIGN = yIDC_INFO_NAME + hIDC_INFO_NAME + DRA::SCALEY(2);
wIDC_INFO_SIGN = wIDC_INFO_NAME;
hIDC_INFO_SIGN = DRA::SCALEY(16);
xtvBuddy = rcCtl.left;
ytvBuddy = rcCtl.top + hgrpInfo + DRA::SCALEY(2);
wtvBuddy = wgrpInfo;
htvBuddy = rcCtl.bottom - ytvBuddy;
//HWND hwndctl = ::GetDlgItem(this->m_hWnd, IDC_GRP_INFO);
//::MoveWindow(hwndctl, xgrpInfo, ygrpInfo, wgrpInfo, hgrpInfo, false);
HWND hwndctl = ::GetDlgItem(this->m_hWnd, IDC_HEAD_PIC);
::MoveWindow(hwndctl, xIDC_HEAD_PIC, yIDC_HEAD_PIC, wIDC_HEAD_PIC, hIDC_HEAD_PIC, false);
hwndctl = ::GetDlgItem(this->m_hWnd, IDC_INFO_NAME);
::MoveWindow(hwndctl, xIDC_INFO_NAME, yIDC_INFO_NAME, wIDC_INFO_NAME, hIDC_INFO_NAME, false);
hwndctl = ::GetDlgItem(this->m_hWnd, IDC_INFO_SIGN);
::MoveWindow(hwndctl, xIDC_INFO_SIGN, yIDC_INFO_SIGN, wIDC_INFO_SIGN, hIDC_INFO_SIGN, false);
hwndctl = ::GetDlgItem(this->m_hWnd, IDC_TREE_BUDDY);
::MoveWindow(hwndctl, xtvBuddy, ytvBuddy, wtvBuddy, htvBuddy, false);
}
}
#endif
void FxMainWin::OnClose()
{
ShowWindow(SW_HIDE);
if (m_BuddyOpt)
delete m_BuddyOpt;
m_BuddyOpt = NULL;
CNotify::RemoveNotification();
CDialog::OnClose();
}
//::GetCaretPos(&point);
BOOL FxMainWin::PreTranslateMessage(MSG* pMsg)
{
/*
将大部分原先在这里处理的消息移到DefWndProc中处理,以解决显示出菜单时无法收到消息的问题
*/
if (pMsg->hwnd == view.m_hWnd)
{
if (pMsg->message == WM_KEYDOWN)
{
switch(pMsg->wParam)
{
case VK_RETURN:
{
HTREEITEM hItem = view.GetSelectedItem();
if(NULL != hItem)
{
if(!view.ItemHasChildren(hItem))
{
return showMsgDlg(view.GetSelectedItem());
}
else
{
#ifndef WIN32_PLATFORM_WFSP
return view.Expand(hItem,TVE_TOGGLE);
#endif
}
}
break;
}
default:
break;
}
}
else
if (pMsg->message == WM_LBUTTONDOWN)
{
SHRGINFO shrg;
shrg.cbSize = sizeof(shrg);
shrg.hwndClient = pMsg->hwnd;
shrg.ptDown.x = LOWORD(pMsg->lParam);
shrg.ptDown.y = HIWORD(pMsg->lParam);
shrg.dwFlags = SHRG_RETURNCMD;
CPoint point;
point.x = shrg.ptDown.x;
point.y = shrg.ptDown.y;
if(::SHRecognizeGesture(&shrg) == GN_CONTEXTMENU)//长按键消息
{
if (showBuddyMenu(point)) return TRUE;
}
else
{
if(view.HitTest(point) == view.GetSelectedItem())
return showMsgDlg(point);
}
}
}
return CDialog::PreTranslateMessage(pMsg);
}
BOOL FxMainWin::SetUserOnlineState(int iState)
{
CString strDesc;
switch(iState)
{
case FX_STATUS_ONLINE:
strDesc = "在线";
break;
case FX_STATUS_OFFLINE:
strDesc = "隐身";
break;
case FX_STATUS_AWAY:
strDesc = "离开";
break;
case FX_STATUS_BUSY:
strDesc = "忙碌";
break;
default:
strDesc = "未设置";
break;
}
#ifdef UNICODE
char *pBuf;
HANDLE hClip=GlobalAlloc(GMEM_MOVEABLE,strDesc.GetLength()+1);
pBuf=(char*)GlobalLock(hClip);
strcpy(pBuf,(const char*)(strDesc.GetBuffer()));
GlobalUnlock(hClip);
#endif
fx_set_user_state(iState, pBuf, Sys_EventListener, this);
GlobalFree(hClip);
return TRUE;
}
BOOL FxMainWin::showBuddyMenu(CPoint point)
{
UINT uFlags;
HTREEITEM hItem = view.HitTest(point, &uFlags);
if ((hItem != NULL) && (TVHT_ONITEM & uFlags))
return showBuddyMenu(hItem);
return FALSE;
}
BOOL FxMainWin::showBuddyMenu(HTREEITEM hItem)
{
if(hItem != view.GetSelectedItem())
return FALSE;
RECT r;
CMenu menu;
UINT nIDRes;
view.GetItemRect(hItem, &r, TRUE);
CPoint point(r.left, r.top);
#if !DEBUG_GUI
if (view.GetParentItem(hItem))
nIDRes = IDR_MENU_BUDDY;
else
return FALSE; // no impl the grup menu//nIDRes = IDR_MENU_GROUP;
#endif
if (!menu.LoadMenu(nIDRes))
return FALSE;
CMenu *pPopupMenu = menu.GetSubMenu(0);
if(!m_BuddyOpt->isQunItem(view.GetParentItem(hItem)))
{
Account_Info *ac_info =(Account_Info*)view.GetItemData(hItem);
if(ac_info)
{
/* add a checking for the account state */
const Fetion_Account *account = fx_get_account_by_id(ac_info->accountID);
if(account)
{
int status = fx_get_online_status_by_account(account);
//check the account could chat or not.
if(!fx_is_auth_chat_by_account(account))
{
pPopupMenu->RemoveMenu(IDM_BD_SENDMSG, MF_BYCOMMAND);
}
if( (FX_STATUS_WAITING_AUTH != status) &&
(FX_STATUS_REFUSE != status))
{
pPopupMenu->RemoveMenu(IDM_BD_READDBUDDY, MF_BYCOMMAND);
}
if(fx_is_InBlacklist_by_account(account))
{
pPopupMenu->RemoveMenu(IDM_BD_ADDBLACKLIST, MF_BYCOMMAND);
}
else
{
pPopupMenu->RemoveMenu(IDM_BD_RMBLACKLIST, MF_BYCOMMAND);
}
}
}
ac_info = NULL;
}
else
{
pPopupMenu->RemoveMenu(IDM_BD_READDBUDDY, MF_BYCOMMAND);
}
view.ClientToScreen(&point);
pPopupMenu->TrackPopupMenu(TPM_LEFTALIGN,point.x,point.y + (r.bottom - r.top),this);
return TRUE;
}
BOOL FxMainWin::showMsgDlg()
{
HTREEITEM hItem = view.GetSelectedItem();
if ((hItem != NULL) && !view.ItemHasChildren(hItem))
{
return showMsgDlg(hItem);
} else {
return FALSE;
}
}
BOOL FxMainWin::showMsgDlg(CPoint point)
{
UINT uFlags;
HTREEITEM hItem = view.HitTest(point, &uFlags);
if ((hItem != NULL) && (TVHT_ONITEM & uFlags))
return showMsgDlg(hItem);
return FALSE;
}
BOOL FxMainWin::showMsgDlg(HTREEITEM hItem)
{
/***********************************************************
* 因为现在不一定是选择后打开聊天对话框,所以屏蔽这一句检查代码
* hiizsk 2009.07.14
if(hItem != view.GetSelectedItem())
return FALSE;
***********************************************************/
RECT r;
view.GetItemRect(hItem, &r, FALSE);
#if DEBUG_GUI
#else
if (!view.GetParentItem(hItem))
return FALSE;
if(!m_BuddyOpt->isQunItem(view.GetParentItem(hItem)))
{
Account_Info *ac_info =(Account_Info*)view.GetItemData(hItem);
if (!ac_info)
return FALSE;
/* add a checking for the account state */
const Fetion_Account *account = fx_get_account_by_id(ac_info->accountID);
if (!account)
return FALSE;
//check the account could chat or not.
if (!fx_is_auth_chat_by_account(account))
{
int status = fx_get_online_status_by_account(account);
switch (status)
{
case FX_STATUS_BLACK:
MessageBox(_T("不能和被您加入黑名单的好友聊天。"), _T("LibFetion"), MB_ICONINFORMATION);
return FALSE;
case FX_STATUS_WAITING_AUTH:
MessageBox(_T("对方不是您的好友,等待对方认证。"), _T("LibFetion"), MB_ICONINFORMATION);
return FALSE;
case FX_STATUS_REFUSE:
MessageBox(_T("对方拒绝添加您为好友。"), _T("LibFetion"), MB_ICONINFORMATION);
return FALSE;
case FX_STATUS_CLOSE_FETION_SERIVCE:
MessageBox(_T("对方已关闭飞信服务。"), _T("LibFetion"), MB_ICONINFORMATION);
return FALSE;
case FX_STATUS_MOBILE_OUT_OF_SERIVCE:
MessageBox(_T("对方已停机。"), _T("LibFetion"), MB_ICONINFORMATION);
return FALSE;
}
}
RemoveFilker(hItem);
showMsgDlg(ac_info->accountID);
}
else
{
Qun_Info *qun_info =(Qun_Info*)view.GetItemData(hItem);
if (!qun_info)
return FALSE;
RemoveFilker(hItem);
showMsgDlg(qun_info->qunID);
}
#endif
return TRUE;
}
BOOL FxMainWin::showMsgDlg(long lAccountID)
{
m_pFxMsgDlgView->LoginOK(m_isLoginOK);
m_pFxMsgDlgView->ShowWindow(SW_SHOW);
m_pFxMsgDlgView->m_isShow= TRUE;
m_pFxMsgDlgView->ShowChat(m_pFxMsgDlgView->ChatWith(lAccountID));
return TRUE;
}
bool FxMainWin::hand_SystemNetErr(int errcode)
{
fx_disable_emit_receive_msg();
this->m_isLoginOK = FALSE;
m_pFxMsgDlgView->LoginOK(m_isLoginOK);
GetDlgItem(IDC_NET_STATE)->ShowWindow(SW_SHOW);
relogin_fetion();
this->UpdateWindow();
return true;
}
void FxMainWin::relogin_ok()
{
this->m_isLoginOK = TRUE;
m_pFxMsgDlgView->LoginOK(m_isLoginOK);
//set the fetion system msg call back function
fx_set_system_msg_cb (Sys_EventListener, this);
fx_enable_emit_receive_msg();
GetDlgItem(IDC_NET_STATE)->ShowWindow(SW_HIDE);
m_strNickNameShow = m_strNickName + GetUserStateString();
this->UpdateData(FALSE);
}
void FxMainWin::relogin_fetion()
{
m_strNickNameShow = m_strNickName + GetUserStateString();
this->UpdateData(FALSE);
KillTimer(TIMER_RELOGIN);
HANDLE* hConnect = new HANDLE();
if(NULL != hConnect)
{
DWORD dwStatus = 0;
ConnMgrEstablishConnectionSync(&m_ConnInfo, hConnect, 25000, &dwStatus);
if(dwStatus==CONNMGR_STATUS_CONNECTED)
{
//网络连接成功
}
delete hConnect;
}
SetTimer(TIMER_RELOGIN, 1000*35, NULL);
//fx_relogin(Relogin_EventListener, this);
fx_relogin(Sys_EventListener, this, NULL, NULL);
}
void FxMainWin::update_account_info()
{
Account_Info * ac_info = m_BuddyOpt->fetchNoUpdateAccount();
if (ac_info)
{
fx_update_account_info_by_id(ac_info->accountID);
m_BuddyOpt->setHaveUpdateAccount(ac_info);
} else {
KillTimer(TIMER_UPDATE_ACCOUNTINFO);
}
}
void FxMainWin::OnTimer(UINT_PTR nIDEvent)
{
switch(nIDEvent)
{
case TIMER_NEWMSG: //1/1秒刷新一次
filker_newmsg();
break;
case TIMER_RELOGIN:
relogin_fetion();
break;
case TIMER_ADD_ITEM_TO_TREE:
KillTimer(TIMER_ADD_ITEM_TO_TREE);
m_BuddyOpt->addItemToTree();
//set the fetion system msg call back function
fx_set_system_msg_cb (Sys_EventListener, this);
fx_enable_emit_receive_msg();
//SetTimer(TIMER_UPDATE_ACCOUNTINFO, 1000*3, NULL);
break;
case TIMER_UPDATE_ACCOUNTINFO:
update_account_info();
break;
}
CDialog::OnTimer(nIDEvent);
}
void FxMainWin::filker_newmsg()
{
static bool state = false;
int counts = filker.GetCount();
for(int i = 0; i < counts; i++)
{
POSITION pos = filker.FindIndex(i);
if (!pos)
continue;
HTREEITEM hItem = filker.GetAt(pos);
if (state)
{
view.SetItemImage(hItem, I_FLICK, I_FLICK);
view.SetItemImage(view.GetParentItem(hItem), I_FLICK, I_FLICK);
}
else
{
if(!m_BuddyOpt->isQunItem(view.GetParentItem(hItem)))
{
m_BuddyOpt->setOnlineState(hItem);
}
else
{
view.SetItemImage(hItem, I_QUN, I_QUN);
}
view.SetItemImage(view.GetParentItem(hItem), I_QUN, I_QUN);
}
}
state = !state;
}
#define MSG_OK 1
#define MSG_FAIL 2
#define MSG_TIMEOUT 3
#define MSG_FAIL_LIMIT 4
void FxMainWin::hand_MsgSend_Event(int message, int fx_msg, long who)
{
switch(message)
{
case FX_SMS_OK:
case FX_DIA_SEND_OK:
case FX_QUN_SEND_OK:
case FX_QUN_SMS_OK:
handle_sendmsg( MSG_OK, fx_msg, who);
if(!fx_msg)
return;
fx_destroy_msg((Fetion_MSG *)fx_msg);
break;
case FX_SMS_FAIL:
case FX_DIA_SEND_FAIL:
case FX_QUN_SEND_FAIL:
case FX_QUN_SMS_FAIL:
handle_sendmsg( MSG_FAIL, fx_msg, who);
if(!fx_msg)
return;
fx_destroy_msg((Fetion_MSG *)fx_msg);
break;
case FX_SMS_TIMEOUT:
case FX_DIA_SEND_TIMEOUT:
case FX_QUN_SEND_TIMEOUT:
case FX_QUN_SMS_TIMEOUT:
handle_sendmsg( MSG_TIMEOUT, fx_msg, who);
//time out should not to destroy msg, beacuse the system will resend by itself..
break;
case FX_SMS_FAIL_LIMIT:
case FX_QUN_SMS_FAIL_LIMIT:
handle_sendmsg( MSG_FAIL_LIMIT , fx_msg, who);
fx_destroy_msg((Fetion_MSG *)fx_msg);
break;
}
}
void FxMainWin::handle_sendmsg(int msgflag, int fx_msg, long account_id)
{
if(!fx_msg)
return;
POSITION pos = NULL;
int i = 0;
Fetion_MSG *fxMsg = (Fetion_MSG *) fx_msg;
char *msg = fx_msg_no_format(fxMsg->message);
CString newmsg;
CString head;
switch(msgflag)
{
case MSG_OK:
pos = timeOutMsgVector.Find(fx_msg);
if (pos)
{
timeOutMsgVector.RemoveAt(pos);
//newmsg = "<b style=\"color:rgb(170,0,255);\">" +tr("auto resend ok:") + "</b>" + newmsg.fromUtf8(msg);
head = CString(_T("自动重发OK"));
}
break;
case MSG_FAIL:
pos = timeOutMsgVector.Find(fx_msg);
if (pos)
{
timeOutMsgVector.RemoveAt(pos);
}
//newmsg = "<b style=\"color:red;\">"+tr("send fail:") +"</b>"+ newmsg.fromUtf8(msg);
head = CString(_T("发送失败"));
break;
case MSG_FAIL_LIMIT:
pos = timeOutMsgVector.Find(fx_msg);
if (pos)
{
timeOutMsgVector.RemoveAt(pos);
}
//newmsg = "<b style=\"color:red;\">"+tr("send sms fail by limit:") +"</b>"+ newmsg.fromUtf8(msg);
head = CString(_T("发送数目限制"));
break;
case MSG_TIMEOUT:
timeOutMsgVector.InsertAfter(timeOutMsgVector.GetTailPosition(), fx_msg);
//newmsg = "<b style=\"color:rgb(170,0,255);\">" +tr("send timeout:") +"</b>" + newmsg.fromUtf8(msg)+"<br><b style=\"color:rgb(170,0,255);\">" +tr("will auto resend")+"</b>";
head = CString(_T("发送超时"));
break;
}
if(!head.IsEmpty())
{
MSGLOGDB MsgLog;
MsgLog.lID = account_id;
MsgLog.strSender = head;
MsgLog.MsgTime = GetCurrentTime();
MsgLog.strMsg = ConvertUtf8ToUtf16(msg);
g_pFxDB->AddMsgLog(&MsgLog);
newmsg = FormatMsgLog(&MsgLog);
addNewMessage(account_id, newmsg);
}
if(msg)
{
free(msg);
msg = NULL;
}
}
void FxMainWin::addNewMessage(long account_id, CString newmsg /* ="" */)
{
const Fetion_Account * account = fx_get_account_by_id (account_id);
if (!account)
return;
// 提醒用户
char * showname = fx_get_account_show_name(account, FALSE);
NotifyUser(1, account_id, ConvertUtf8ToUtf16(showname));
if(showname)
free(showname);
HTREEITEM accountItem = m_BuddyOpt->findAccountItemFromAllGroup(account);
m_BuddyOpt->setOnlineState(accountItem);
if(FALSE == m_pFxMsgDlgView->addNewMsg(account_id, newmsg))
{
return;
}
if (accountItem)
{
if (filker.GetCount() == 0)
SetTimer(TIMER_NEWMSG, 500,NULL);
// 更正一个好友多条消息时要打开多次对话框才会停止闪烁的BUG
if(filker.Find(accountItem) == NULL)
filker.InsertAfter(filker.GetTailPosition(), accountItem);
}
}
void FxMainWin::addNewQunMessage(long qun_id,CString newmsg )
{
const Fetion_Qun * qun = fx_get_qun_by_id(qun_id);
if (!qun)
return;
// 提醒用户
char * showname = fx_get_qun_show_name((Fetion_Qun*)qun);
NotifyUser(3, qun_id, ConvertUtf8ToUtf16(showname));
if(showname)
free(showname);
HTREEITEM accountItem = m_BuddyOpt->findQunItem(qun);
//对象不匹配,注释掉防止出错
//m_BuddyOpt->setOnlineState(accountItem);
if(FALSE == m_pFxMsgDlgView->addNewMsg(qun_id, newmsg))
{
return;
}
if (accountItem)
{
if (filker.GetCount() == 0)
SetTimer(TIMER_NEWMSG, 500,NULL);
// 更正一个好友多条消息时要打开多次对话框才会停止闪烁的BUG
if(filker.Find(accountItem) == NULL)
filker.InsertAfter(filker.GetTailPosition(), accountItem);
}
}
void FxMainWin::OnStnClickedBtnAdd()
{
CFindBuddyDlg* dlg = new CFindBuddyDlg();
dlg->m_strUserName = m_strNickName;
dlg->DoModal();
delete dlg;
}
void FxMainWin::OnBdReAddbuddy()
{
HTREEITEM hItem = view.GetSelectedItem();
if((NULL == hItem) || (NULL == view.GetParentItem(hItem)))
{
return;
}
Account_Info *ac_info =(Account_Info*)view.GetItemData(hItem);
if (ac_info)
{
const Fetion_Account * account = fx_get_account_by_id(ac_info->accountID);
if(NULL == account)
{
return;
}
CFindBuddyDlg* dlg = new CFindBuddyDlg();
CString strAccountID;
CString strMobileNo;
if(fx_is_pc_user_by_id(ac_info->accountID))
{
//飞信用户
strAccountID.Format(_T("%d"), ac_info->accountID);
if (account->personal)
{
strMobileNo = ConvertUtf8ToUtf16(account->personal->mobile_no);
}
else
{
strMobileNo = _T("");
}
}
else
{
//手机用户
strAccountID = _T("");
//获取显示正确的号码,如果是手机用户,则返回手机号码,其它返回飞信号
char* original = fx_get_original_ID(ac_info->accountID);
strMobileNo = ConvertUtf8ToUtf16(original);
free(original);
}
if(strMobileNo.IsEmpty())
{
dlg->m_bAddByMobileNo = FALSE;
dlg->m_strBuddyID = strAccountID;
}
else
{
dlg->m_bAddByMobileNo = TRUE;
dlg->m_strBuddyID = strMobileNo;
}
dlg->m_strUserName = m_strNickName;
Group_Info *group_info = (Group_Info *)view.GetItemData(view.GetParentItem(hItem));
if (group_info)
{
dlg->m_iGroupID = group_info->groupID;
}
dlg->DoModal();
delete dlg;
}
}
void FxMainWin::OnSendMsg()
{
this->showMsgDlg();
}
// 消息提示
// EventType: 1-新消息 2-用户上线 3-群消息提醒
void FxMainWin::NotifyUser(int EventType, long lAccountID, CString szBuddyName)
{
if(m_bSilence)
return;
LPCWSTR strSoundPath;
UINT Styles = 0;
int iPeriod = 0;
BOOL bVibrate = false;
CString wavfile;
switch(EventType)
{
case 1:
{
iPeriod = 1000; //毫秒
bVibrate = this->m_bVibrate;
wavfile = m_strStartupPath + CString(_T("\\message.wav"));
if(!(::GetFileAttributes(wavfile) == 0xFFFFFFFF))
{
Styles=SND_FILENAME;
strSoundPath=(LPCTSTR)wavfile;
}
else
{
strSoundPath = MAKEINTRESOURCE(IDR_MSGSOUND);
Styles = SND_RESOURCE;
}
break;
}
case 2:
{
if(!m_bOnline)
return ;
wavfile =m_strStartupPath + CString(_T("\\online.wav"));
if(!(::GetFileAttributes(wavfile) == 0xFFFFFFFF))
{
Styles=SND_FILENAME;
strSoundPath=(LPCTSTR)wavfile;
}
else
{
strSoundPath = MAKEINTRESOURCE(IDR_ONLINESOUND);
Styles = SND_RESOURCE;
}
CNotify::Nodify(this->m_hWnd, strSoundPath, 0, this->m_bSound,FALSE, Styles);//只声音提示,不震动
return ;
}
case 3:
{
if(m_bShieldQunMessage)
return;
wavfile=m_strStartupPath+CString(_T("\\qun.wav"));
if(!(::GetFileAttributes(wavfile) == 0xFFFFFFFF))
{
Styles=SND_FILENAME;
strSoundPath=(LPCTSTR)wavfile;
}
else
{
strSoundPath = MAKEINTRESOURCE(IDR_MSGSOUND);
Styles = SND_RESOURCE;
}
}
}
#ifdef WIN32_PLATFORM_PSPC
SetSystemPowerState(NULL, POWER_STATE_ON, 0);
if(this->IsTopParentActive())
{
CNotify::Nodify(this->m_hWnd, strSoundPath, iPeriod, this->m_bSound, this->m_bVibrate, Styles);
}
else
{
CString strMsg = L"<font color=\"#0000FF\"><b>为了保护个人隐私,这里不会直接显示消息,请自行点击查看。</b></font>";
// fixme: 这里要如何才能取得最后一条消息又不会导致消息被移除?
// 下面这个代码是有问题的.取出消息后,再打开对话框将看不到新消息
/*
Fetion_MSG * fxMsg = NULL;
//得到最后一条消息
fxMsg = fx_get_msg(lAccountID);
if(fxMsg == NULL)
return;
char * msg_contain = fx_msg_no_format(fxMsg->message);
strMsg = ConvertUtf8ToUtf16(msg_contain) + CString(_T("\r\n"));
if (msg_contain)
free(msg_contain);
fxMsg = NULL;
fxMsgPrev = NULL;
*/
CNotify::CreateAndAddNotification(this->GetSafeHwnd(), szBuddyName, strMsg);
}
#else
CNotify::Nodify(this->m_hWnd, strSoundPath, iPeriod, this->m_bSound, this->m_bVibrate, Styles);
#endif
}
void FxMainWin::OnMainSetVibr()
{
m_bVibrate = !m_bVibrate;
SetSettingToIni(_T("Vibrate"), m_bVibrate);
}
void FxMainWin::OnMainSetSilence()
{
m_bSilence = !m_bSilence;
SetSettingToIni(_T("Silence"), m_bSilence);
}
void FxMainWin::OnUpdateMainSetSilence(CCmdUI *pCmdUI)
{
pCmdUI->SetCheck(m_bSilence);
}
void FxMainWin::OnUpdateMainSetVibr(CCmdUI *pCmdUI)
{
pCmdUI->SetCheck(m_bVibrate);
}
void FxMainWin::OnMainSetOnline()
{
m_bOnline=!m_bOnline;
SetSettingToIni(_T("Online"), m_bOnline);
}
void FxMainWin::OnUpdateMainSetOnline(CCmdUI *pCmdUI)
{
pCmdUI->SetCheck(m_bOnline);
}
void FxMainWin::OnMainShieldQunMessage()
{
m_bShieldQunMessage = !m_bShieldQunMessage;
SetSettingToIni(_T("ShieldQunMessage"), m_bShieldQunMessage);
}
void FxMainWin::OnMainSetLongsms()
{
m_bLongSMS = !m_bLongSMS;
SetSettingToIni(_T("LongSMS"), m_bLongSMS);
fx_set_longsms(m_bLongSMS);
}
void FxMainWin::OnUpdateShieldQunMessage(CCmdUI *pCmdUI)
{
pCmdUI->SetCheck(m_bShieldQunMessage);
}
// 获取启动路径
CString FxMainWin::GetStartupPath(void)
{
if(m_strStartupPath == _T(""))
{
TCHAR cPath[MAX_PATH];
CString filePath;
GetModuleFileName( NULL, cPath, MAX_PATH );
filePath = cPath;
filePath = filePath.Left(filePath.ReverseFind('\\'));
m_strStartupPath = filePath;
}
return m_strStartupPath;
}
void FxMainWin::OnBdViewinfo()
{
HTREEITEM hItem = view.GetSelectedItem();
if ((hItem != NULL) && !view.ItemHasChildren(hItem))
{
if(!m_BuddyOpt->isQunItem(view.GetParentItem(hItem)))
{
showBuddyInfo(hItem);
}
else
{
}
}
}
BOOL FxMainWin::showBuddyInfo(HTREEITEM hItem)
{
#if !DEBUG_GUI
if(hItem != view.GetSelectedItem())
return FALSE;
if (!view.GetParentItem(hItem))
return FALSE;
Account_Info *ac_info =(Account_Info*)view.GetItemData(hItem);
if (!ac_info)
return FALSE;
m_BuddyInfoDlg = new CBuddyInfoDlg(ac_info->accountID);
#else
CBuddyInfoDlg* dlg = new CBuddyInfoDlg(123456);
#endif
m_BuddyInfoDlg->DoModal();
delete m_BuddyInfoDlg;
m_BuddyInfoDlg = NULL;
return TRUE;
}
void FxMainWin::OnInitMenuPopup(CMenu* pPopupMenu, UINT nIndex, BOOL bSysMenu)
{
CDialog::OnInitMenuPopup(pPopupMenu, nIndex, bSysMenu);
pPopupMenu->CheckMenuItem(IDM_MAIN_SET_SILENCE, m_bSilence ? MF_CHECKED : MF_UNCHECKED);
pPopupMenu->CheckMenuItem(IDM_MAIN_SET_NOSOUND, m_bSound ? MF_CHECKED : MF_UNCHECKED);
pPopupMenu->CheckMenuItem(IDM_MAIN_SET_VIBR, m_bVibrate ? MF_CHECKED : MF_UNCHECKED);
pPopupMenu->CheckMenuItem(IDM_MAIN_SET_ONLINE, m_bOnline ? MF_CHECKED : MF_UNCHECKED);
pPopupMenu->CheckMenuItem(IDM_MAIN_SET_SHIELDQUNMESSAGE, m_bShieldQunMessage ? MF_CHECKED : MF_UNCHECKED);
pPopupMenu->CheckMenuItem(IDM_MAIN_SET_LONGSMS, m_bLongSMS ? MF_CHECKED : MF_UNCHECKED);
pPopupMenu->CheckMenuItem(IDM_MAIN_STATE_ONLINE, MF_UNCHECKED);
pPopupMenu->CheckMenuItem(IDM_MAIN_STATE_HIDE, MF_UNCHECKED);
pPopupMenu->CheckMenuItem(IDM_MAIN_STATE_BUSY, MF_UNCHECKED);
pPopupMenu->CheckMenuItem(IDM_MAIN_STATE_AWAY, MF_UNCHECKED);
int iState = fx_get_user_state();
switch(iState)
{
case 0:
case FX_STATUS_ONLINE:
pPopupMenu->CheckMenuItem(IDM_MAIN_STATE_ONLINE, MF_CHECKED);
break;
case FX_STATUS_OFFLINE:
pPopupMenu->CheckMenuItem(IDM_MAIN_STATE_HIDE, MF_CHECKED);
break;
case FX_STATUS_BUSY:
pPopupMenu->CheckMenuItem(IDM_MAIN_STATE_BUSY, MF_CHECKED);
break;
case FX_STATUS_AWAY:
pPopupMenu->CheckMenuItem(IDM_MAIN_STATE_AWAY, MF_CHECKED);
break;
}
pPopupMenu->EnableMenuItem(IDM_BD_READDBUDDY, MF_GRAYED);
pPopupMenu->EnableMenuItem(IDM_BD_VIEWINFO, MF_GRAYED);
pPopupMenu->EnableMenuItem(IDM_BD_DELETE, MF_GRAYED);
pPopupMenu->EnableMenuItem(IDM_BD_ADDBLACKLIST, MF_GRAYED);
pPopupMenu->EnableMenuItem(IDM_BD_RMBLACKLIST, MF_GRAYED);
HTREEITEM hItem = view.GetSelectedItem();
if((NULL != hItem) && (NULL != view.GetParentItem(hItem)))
{
if(!m_BuddyOpt->isQunItem(view.GetParentItem(hItem)))
{
Account_Info *ac_info =(Account_Info*)view.GetItemData(hItem);
if(ac_info)
{
/* add a checking for the account state */
const Fetion_Account *account = fx_get_account_by_id(ac_info->accountID);
if(account)
{
int status = fx_get_online_status_by_account(account);
if( (FX_STATUS_WAITING_AUTH == status) ||
(FX_STATUS_REFUSE == status))
{
pPopupMenu->EnableMenuItem(IDM_BD_READDBUDDY, MF_ENABLED);
}
if(fx_is_InBlacklist_by_account(account))
{
pPopupMenu->EnableMenuItem(IDM_BD_RMBLACKLIST, MF_ENABLED);
}
else
{
pPopupMenu->EnableMenuItem(IDM_BD_ADDBLACKLIST, MF_ENABLED);
}
account = NULL;
}
ac_info = NULL;
}
pPopupMenu->EnableMenuItem(IDM_BD_VIEWINFO, MF_ENABLED);
pPopupMenu->EnableMenuItem(IDM_BD_DELETE, MF_ENABLED);
}
}
if(m_strMobileNo.IsEmpty())
{
pPopupMenu->EnableMenuItem(IDM_SEND_MYSELF, MF_GRAYED);
}
}
// 处理移动组成功的消息
void FxMainWin::handle_MoveGroupOk(long account_id, int group_id)
{
this->m_BuddyOpt->delAccount_direct(account_id);
this->m_BuddyOpt->addAccountToGroup(fx_get_account_by_id (account_id));
}
void FxMainWin::OnAbout()
{
CAbout dlg;
dlg.DoModal();
}
void FxMainWin::OnBdDelete()
{
HTREEITEM hItem = view.GetSelectedItem();
if ((hItem != NULL) && !view.ItemHasChildren(hItem))
{
if(m_BuddyOpt->isQunItem(view.GetParentItem(hItem)))
{
//群
return;
}
Account_Info *ac_info =(Account_Info*)view.GetItemData(hItem);
if (!ac_info)
return;
CString strMessage;
const Fetion_Account * fetion_account = fx_get_account_by_id(ac_info->accountID);
char * showname = fx_get_account_show_name(fetion_account, FALSE);
strMessage.Format(_T("是否确定要删除 %s?删除后对方仍能发送消息给你,如果不希望收到对方的消息请将其加入黑名单。"), ConvertUtf8ToUtf16(showname));
if(showname)
{
free(showname);
showname = NULL;
}
if(AfxMessageBox(strMessage, MB_YESNO) == IDNO)
return;
fx_delete_buddy_by_id(ac_info->accountID, NULL, NULL);
}
}
void FxMainWin::OnBdAddblacklist()
{
HTREEITEM hItem = view.GetSelectedItem();
if ((hItem != NULL) && !view.ItemHasChildren(hItem))
{
if(m_BuddyOpt->isQunItem(view.GetParentItem(hItem)))
{
//群
return;
}
Account_Info *ac_info =(Account_Info*)view.GetItemData(hItem);
if (!ac_info)
return;
CString strMessage;
strMessage.Format(_T("是否确定要将 %s 加入黑名单?对方将无法发送消息给你。"), ac_info->accountName);
if(AfxMessageBox(strMessage, MB_YESNO) == IDNO)
return;
fx_addto_blacklist_by_id(ac_info->accountID, NULL, NULL);
}
}
void FxMainWin::OnBdRmblacklist()
{
HTREEITEM hItem = view.GetSelectedItem();
if ((hItem != NULL) && !view.ItemHasChildren(hItem))
{
Account_Info *ac_info =(Account_Info*)view.GetItemData(hItem);
if (!ac_info)
return;
fx_removefrom_blacklist_by_id(ac_info->accountID, NULL, NULL);
}
}
void FxMainWin::OnMainSetNosound()
{
m_bSound = !m_bSound;
SetSettingToIni(_T("Sound"), m_bSound);
}
/***********************************************************************************
* 增加在左软键的提取新消息按钮,替代了原先很少用到的发送消息.发送消息更适合用确认键
* hiizsk 2009.07.14
************************************************************************************/
void FxMainWin::OnMainShownewmsg()
{
if(filker.GetCount() != 0)
{
HTREEITEM hItem = filker.GetHead();
showMsgDlg(hItem);
}
}
void FxMainWin::OnBdSendmsg()
{
showMsgDlg();
}
void FxMainWin::OnMainAddbuddy()
{
OnStnClickedBtnAdd();
}
LRESULT FxMainWin::DefWindowProc(UINT message, WPARAM wParam, LPARAM lParam)
{
if (message == WM_COMMAND)
{
switch (LOWORD(wParam))
{
case IDM_MAIN_STATE_ONLINE:
SetUserOnlineState(FX_STATUS_ONLINE);
break;
case IDM_MAIN_STATE_HIDE:
SetUserOnlineState(FX_STATUS_OFFLINE);
break;
case IDM_MAIN_STATE_BUSY:
SetUserOnlineState(FX_STATUS_BUSY);
break;
case IDM_MAIN_STATE_AWAY:
SetUserOnlineState(FX_STATUS_AWAY);
break;
case IDM_MAIN_MINIMAL:
ShowWindow( SW_MINIMIZE );
break;
case IDM_MAIN_LOGOFF:
::exit(0);
break;
case IDM_MAIN_SHOWNEWMSG2:
OnMainShownewmsg2();
break;
case IDM_MAIN_DIMISS:
OnMainDimiss();
break;
default:
break;
}
}
if (handleFx_Sys_Event(message, wParam, lParam))
return TRUE;
return CDialog::DefWindowProc(message, wParam, lParam);
}
// 通过桌面提醒进来的时候,需要移除提醒图标
void FxMainWin::OnMainShownewmsg2(void)
{
this->SetForegroundWindow();
OnMainShownewmsg();
//OnActivate那处理了,此处代码无须保留
//CNotify::RemoveNotification();
}
// 通过桌面提醒进来的时候,需要移除提醒图标
void FxMainWin::OnMainDimiss(void)
{
//虽然OnActivate那处理了,但此处代码要保留
CNotify::RemoveNotification();
}
void FxMainWin::OnMainClean()
{
// TODO: 在此添加命令处理程序代码
CIniWR hIni;
hIni.WritePrivateProfileString(m_strAccountID, _T("PassWord"), _T(""), m_strStartupPath + _T("\\Users\\") + m_strAccountID + _T("\\") + m_strAccountID + _T(".ini"));
}
void FxMainWin::OnOK()
{
// TODO: 在此添加专用代码和/或调用基类
//解决按回车键导致程序退出的问题
//CDialog::OnOK();
}
void FxMainWin::OnCancel()
{
// TODO: 在此添加专用代码和/或调用基类
//解决SP手机按CANCEL键后自动退出问题,并改成最小化
ShowWindow(SW_MINIMIZE);
#ifdef WIN32_PLATFORM_PSPC
//解决PPC上点X强制关闭程序的工具软件无法彻底关闭本程序的问题
CDialog::OnCancel();
#endif
}
CString FxMainWin::GetUserStateString(void)
{
CString strUserState = _T("");;
int iState = fx_get_user_state();
switch(iState)
{
case 0:
case FX_STATUS_ONLINE:
strUserState = _T(" (在线)");
break;
case FX_STATUS_OFFLINE:
strUserState = _T(" (隐身)");
break;
case FX_STATUS_BUSY:
strUserState = _T(" (忙碌)");
break;
case FX_STATUS_AWAY:
strUserState = _T(" (离开)");
break;
default:
break;
}
if(FALSE == this->m_isLoginOK)
{
strUserState = _T(" (脱机)");
}
return strUserState;
}
UINT FxMainWin::GetSettingFromIni(LPCTSTR lpKeyName, int nDefault)
{
CIniWR hIni;
return hIni.GetPrivateProfileInt(_T("OPTION"), lpKeyName, nDefault, m_strStartupPath + _T("\\Users\\") + m_strAccountID + _T("\\") + m_strAccountID + _T(".ini"));
}
BOOL FxMainWin::SetSettingToIni(LPCTSTR lpKeyName, UINT uValue)
{
CIniWR hIni;
return hIni.WritePrivateProfileInt(_T("OPTION"), lpKeyName, uValue, m_strStartupPath + _T("\\Users\\") + m_strAccountID + _T("\\") + m_strAccountID + _T(".ini"));
}
void FxMainWin::handle_AddAccountApp(char* uri, char* showname)
{
CString strMessage;
strMessage.Format(_T("%s 想添加你为好友,是否同意?"), ConvertUtf8ToUtf16(showname));
int iReturn = AfxMessageBox(strMessage, MB_YESNOCANCEL | MB_ICONQUESTION | MB_APPLMODAL);
if(IDYES == iReturn)
{
fx_handleContactRequest(uri, 1, 0, showname);
}
if(IDNO == iReturn)
{
fx_handleContactRequest(uri, 0, 0, showname);
}
}
void FxMainWin::RecoveryMenuBar()
{
ShowWindow(TRUE);
m_dlgCommandBar.InsertMenuBar(IDR_MAIN_MENU);
}
void FxMainWin::OnSendMyself()
{
// TODO: 在此添加命令处理程序代码
m_pFxMsgDlgView->LoginOK(m_isLoginOK);
m_pFxMsgDlgView->ShowWindow(SW_SHOW);
m_pFxMsgDlgView->m_isShow= TRUE;
m_pFxMsgDlgView->ShowChat(m_pFxMsgDlgView->ChatWith(strtol(fx_get_usr_uid(), NULL,10), TRUE));
}
void FxMainWin::RemoveFilker(long lAccountID)
{
const Fetion_Account * account = fx_get_account_by_id (lAccountID);
if(NULL == account)
{
return;
}
HTREEITEM hItem = m_BuddyOpt->findAccountItemFromAllGroup(account);
RemoveFilker(hItem);
}
void FxMainWin::RemoveFilker(HTREEITEM hItem)
{
if(NULL == hItem)
{
return;
}
POSITION pos = filker.Find(hItem);
if(pos)
{
filker.RemoveAt(pos);
}
if(!m_BuddyOpt->isQunItem(view.GetParentItem(hItem)))
{
m_BuddyOpt->setOnlineState(hItem);
}
else
{
view.SetItemImage(hItem, I_QUN, I_QUN);
}
view.SetItemImage(view.GetParentItem(hItem), I_QUN, I_QUN);
if (filker.GetCount() == 0)
{
KillTimer(TIMER_NEWMSG);
}
}
void FxMainWin::OnUpdateAllAccountinfo()
{
// TODO: 在此添加命令处理程序代码
CString strMessage;
strMessage.Format(_T("当好友较多时,刷新列表将会产生较大网络数据流量,且时间较长。如果只想更新单个好友资料,您可以选择单个好友的“查看资料”。是否确定要刷新列表?"));
if(MessageBox(strMessage, _T("LibFetion"), MB_OKCANCEL | MB_ICONQUESTION) == IDCANCEL)
{
return;
}
m_BuddyOpt->WantUpdateAllAccountInfo();
SetTimer(TIMER_UPDATE_ACCOUNTINFO, 1000*3, NULL);
}
void FxMainWin::OnMyselfInfo()
{
CMyselfInfoDlg Dlg;
Dlg.DoModal();
}
void FxMainWin::SetTreeBuddyFontSize(int nSize)
{
if(NULL != m_pTreeFont)
{
delete m_pTreeFont;
m_pTreeFont = NULL;
}
m_pTreeFont = new CFont;
m_pTreeFont->CreatePointFont(nSize*10, _T("MS Shell Dlg"));
view.SetFont(m_pTreeFont);
}
void FxMainWin::OnMainFontSetting()
{
CFontSetting Dlg;
Dlg.m_nTreeFontSize = m_nTreeFontSize;
INT_PTR nResponse = Dlg.DoModal();
if((IDOK == nResponse) &&(Dlg.m_nTreeFontSize >= 1) && (Dlg.m_nTreeFontSize <= 100))
{
m_nTreeFontSize = Dlg.m_nTreeFontSize;
SetTreeBuddyFontSize(m_nTreeFontSize);
SetSettingToIni(_T("TreeFontSize"), m_nTreeFontSize);
}
}
void FxMainWin::OnActivate(UINT nState, CWnd* pWndOther, BOOL bMinimized)
{
CDialog::OnActivate(nState, pWndOther, bMinimized);
if(WA_ACTIVE == nState)
{
CNotify::RemoveNotification();
}
}
| [
"shikun.z@8f3339bc-7e71-11dd-a943-c76e4c82ec5c",
"gladyeti@8f3339bc-7e71-11dd-a943-c76e4c82ec5c",
"libfetion@8f3339bc-7e71-11dd-a943-c76e4c82ec5c",
"daviyang35@8f3339bc-7e71-11dd-a943-c76e4c82ec5c",
"[email protected]@8f3339bc-7e71-11dd-a943-c76e4c82ec5c"
]
| [
[
[
1,
16
],
[
22,
26
],
[
29,
31
],
[
33,
38
],
[
43,
64
],
[
66,
68
],
[
71,
91
],
[
97,
107
],
[
109,
129
],
[
133,
148
],
[
150,
160
],
[
175,
202
],
[
222,
235
],
[
237,
238
],
[
240,
242
],
[
250,
254
],
[
275,
280
],
[
282,
293
],
[
296,
299
],
[
304,
313
],
[
315,
315
],
[
323,
435
],
[
440,
444
],
[
446,
458
],
[
471,
471
],
[
477,
481
],
[
483,
483
],
[
492,
510
],
[
512,
512
],
[
516,
516
],
[
535,
573
],
[
575,
578
],
[
580,
582
],
[
584,
741
],
[
784,
824
],
[
830,
830
],
[
869,
869
],
[
874,
879
],
[
884,
884
],
[
886,
889
],
[
891,
891
],
[
893,
901
],
[
903,
905
],
[
907,
908
],
[
911,
914
],
[
918,
918
],
[
931,
932
],
[
934,
949
],
[
951,
951
],
[
953,
957
],
[
968,
987
],
[
1002,
1063
],
[
1065,
1072
],
[
1075,
1079
],
[
1081,
1081
],
[
1083,
1083
],
[
1085,
1089
],
[
1091,
1091
],
[
1093,
1093
],
[
1095,
1098
],
[
1100,
1101
],
[
1113,
1114
],
[
1116,
1116
],
[
1119,
1127
],
[
1132,
1132
],
[
1134,
1134
],
[
1136,
1136
],
[
1138,
1144
],
[
1146,
1151
],
[
1186,
1189
],
[
1191,
1193
],
[
1261,
1267
],
[
1270,
1272
],
[
1274,
1276
],
[
1278,
1280
],
[
1300,
1300
],
[
1339,
1341
],
[
1343,
1343
],
[
1347,
1348
],
[
1350,
1371
],
[
1373,
1378
],
[
1380,
1384
],
[
1386,
1397
],
[
1426,
1445
],
[
1453,
1467
],
[
1469,
1471
],
[
1475,
1481
],
[
1483,
1483
],
[
1488,
1508
],
[
1555,
1573
],
[
1579,
1584
],
[
1593,
1604
],
[
1610,
1638
],
[
1641,
1709
],
[
1714,
1718
],
[
1720,
1721
],
[
1789,
1796
],
[
1799,
1801
]
],
[
[
17,
21
],
[
27,
28
],
[
32,
32
],
[
69,
70
],
[
92,
96
],
[
108,
108
],
[
130,
132
],
[
149,
149
],
[
161,
174
],
[
203,
221
],
[
236,
236
],
[
239,
239
],
[
243,
249
],
[
255,
274
],
[
281,
281
],
[
294,
295
],
[
317,
322
],
[
436,
439
],
[
445,
445
],
[
459,
464
],
[
466,
470
],
[
472,
476
],
[
482,
482
],
[
484,
491
],
[
511,
511
],
[
513,
515
],
[
517,
526
],
[
528,
534
],
[
574,
574
],
[
579,
579
],
[
583,
583
],
[
746,
746
],
[
748,
751
],
[
753,
773
],
[
825,
829
],
[
831,
868
],
[
870,
873
],
[
880,
883
],
[
885,
885
],
[
890,
890
],
[
892,
892
],
[
902,
902
],
[
909,
910
],
[
915,
917
],
[
919,
930
],
[
933,
933
],
[
950,
950
],
[
952,
952
],
[
958,
963
],
[
965,
967
],
[
988,
1001
],
[
1064,
1064
],
[
1073,
1074
],
[
1080,
1080
],
[
1082,
1082
],
[
1084,
1084
],
[
1090,
1090
],
[
1092,
1092
],
[
1094,
1094
],
[
1099,
1099
],
[
1102,
1112
],
[
1115,
1115
],
[
1117,
1118
],
[
1128,
1131
],
[
1133,
1133
],
[
1135,
1135
],
[
1137,
1137
],
[
1145,
1145
],
[
1166,
1166
],
[
1170,
1171
],
[
1190,
1190
],
[
1269,
1269
],
[
1342,
1342
],
[
1344,
1344
],
[
1346,
1346
],
[
1349,
1349
],
[
1379,
1379
],
[
1385,
1385
],
[
1401,
1401
],
[
1411,
1419
],
[
1446,
1452
],
[
1468,
1468
],
[
1472,
1474
],
[
1484,
1487
],
[
1522,
1522
],
[
1524,
1527
],
[
1529,
1543
],
[
1545,
1545
],
[
1551,
1554
],
[
1574,
1578
],
[
1585,
1592
],
[
1605,
1609
],
[
1640,
1640
],
[
1710,
1713
],
[
1719,
1719
],
[
1722,
1722
],
[
1726,
1727
],
[
1729,
1788
],
[
1797,
1798
],
[
1802,
1915
]
],
[
[
39,
42
],
[
465,
465
],
[
906,
906
],
[
964,
964
]
],
[
[
65,
65
],
[
300,
303
],
[
316,
316
],
[
527,
527
],
[
1152,
1165
],
[
1167,
1169
],
[
1172,
1185
],
[
1268,
1268
],
[
1273,
1273
],
[
1277,
1277
],
[
1281,
1299
],
[
1301,
1338
],
[
1345,
1345
],
[
1372,
1372
],
[
1398,
1400
],
[
1402,
1410
],
[
1420,
1425
],
[
1482,
1482
],
[
1639,
1639
],
[
1723,
1725
],
[
1728,
1728
]
],
[
[
314,
314
],
[
742,
745
],
[
747,
747
],
[
752,
752
],
[
774,
783
],
[
1194,
1260
],
[
1509,
1521
],
[
1523,
1523
],
[
1528,
1528
],
[
1544,
1544
],
[
1546,
1550
]
]
]
|
0f6d27f309db4f5d0625c54983d024c8d8d040de | 0033659a033b4afac9b93c0ac80b8918a5ff9779 | /game/client/c_playerresource.cpp | 9dcad9f89cf33f21be07eb36fee5bc24dbc3dec3 | []
| no_license | jonnyboy0719/situation-outbreak-two | d03151dc7a12a97094fffadacf4a8f7ee6ec7729 | 50037e27e738ff78115faea84e235f865c61a68f | refs/heads/master | 2021-01-10T09:59:39.214171 | 2011-01-11T01:15:33 | 2011-01-11T01:15:33 | 53,858,955 | 1 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 8,951 | cpp | //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose: Entity that propagates general data needed by clients for every player.
//
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include "c_playerresource.h"
#include "c_team.h"
#include "gamestringpool.h"
#ifdef HL2MP
/////
// SO2 - James
// Additional zombie team
//#include "hl2mp_gamerules.h"
#include "so_gamerules.h"
/////
#endif
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
const float PLAYER_RESOURCE_THINK_INTERVAL = 0.2f;
#define PLAYER_UNCONNECTED_NAME "unconnected"
IMPLEMENT_CLIENTCLASS_DT_NOBASE(C_PlayerResource, DT_PlayerResource, CPlayerResource)
RecvPropArray3( RECVINFO_ARRAY(m_iPing), RecvPropInt( RECVINFO(m_iPing[0]))),
RecvPropArray3( RECVINFO_ARRAY(m_iScore), RecvPropInt( RECVINFO(m_iScore[0]))),
RecvPropArray3( RECVINFO_ARRAY(m_iDeaths), RecvPropInt( RECVINFO(m_iDeaths[0]))),
RecvPropArray3( RECVINFO_ARRAY(m_bConnected), RecvPropInt( RECVINFO(m_bConnected[0]))),
RecvPropArray3( RECVINFO_ARRAY(m_iTeam), RecvPropInt( RECVINFO(m_iTeam[0]))),
RecvPropArray3( RECVINFO_ARRAY(m_bAlive), RecvPropInt( RECVINFO(m_bAlive[0]))),
RecvPropArray3( RECVINFO_ARRAY(m_iHealth), RecvPropInt( RECVINFO(m_iHealth[0]))),
END_RECV_TABLE()
BEGIN_PREDICTION_DATA( C_PlayerResource )
DEFINE_PRED_ARRAY( m_szName, FIELD_STRING, MAX_PLAYERS+1, FTYPEDESC_PRIVATE ),
DEFINE_PRED_ARRAY( m_iPing, FIELD_INTEGER, MAX_PLAYERS+1, FTYPEDESC_PRIVATE ),
DEFINE_PRED_ARRAY( m_iScore, FIELD_INTEGER, MAX_PLAYERS+1, FTYPEDESC_PRIVATE ),
DEFINE_PRED_ARRAY( m_iDeaths, FIELD_INTEGER, MAX_PLAYERS+1, FTYPEDESC_PRIVATE ),
DEFINE_PRED_ARRAY( m_bConnected, FIELD_BOOLEAN, MAX_PLAYERS+1, FTYPEDESC_PRIVATE ),
DEFINE_PRED_ARRAY( m_iTeam, FIELD_INTEGER, MAX_PLAYERS+1, FTYPEDESC_PRIVATE ),
DEFINE_PRED_ARRAY( m_bAlive, FIELD_BOOLEAN, MAX_PLAYERS+1, FTYPEDESC_PRIVATE ),
DEFINE_PRED_ARRAY( m_iHealth, FIELD_INTEGER, MAX_PLAYERS+1, FTYPEDESC_PRIVATE ),
END_PREDICTION_DATA()
C_PlayerResource *g_PR;
IGameResources * GameResources( void ) { return g_PR; }
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
C_PlayerResource::C_PlayerResource()
{
memset( m_iPing, 0, sizeof( m_iPing ) );
// memset( m_iPacketloss, 0, sizeof( m_iPacketloss ) );
memset( m_iScore, 0, sizeof( m_iScore ) );
memset( m_iDeaths, 0, sizeof( m_iDeaths ) );
memset( m_bConnected, 0, sizeof( m_bConnected ) );
memset( m_iTeam, 0, sizeof( m_iTeam ) );
memset( m_bAlive, 0, sizeof( m_bAlive ) );
memset( m_iHealth, 0, sizeof( m_iHealth ) );
for ( int i=0; i<MAX_TEAMS; i++ )
{
m_Colors[i] = COLOR_GREY;
}
#ifdef HL2MP
m_Colors[TEAM_COMBINE] = COLOR_BLUE;
m_Colors[TEAM_REBELS] = COLOR_RED;
/////
// SO2 - James
// Change color of players' name, etc
//m_Colors[TEAM_UNASSIGNED] = COLOR_YELLOW;
m_Colors[TEAM_UNASSIGNED] = COLOR_GREY;
/////
/////
// SO2 - James
// Additional zombie team
m_Colors[TEAM_ZOMBIES] = COLOR_RED;
/////
#endif
g_PR = this;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
C_PlayerResource::~C_PlayerResource()
{
g_PR = NULL;
}
void C_PlayerResource::OnDataChanged(DataUpdateType_t updateType)
{
BaseClass::OnDataChanged( updateType );
if ( updateType == DATA_UPDATE_CREATED )
{
SetNextClientThink( gpGlobals->curtime + PLAYER_RESOURCE_THINK_INTERVAL );
}
}
void C_PlayerResource::UpdatePlayerName( int slot )
{
if ( slot < 1 || slot > MAX_PLAYERS )
{
Error( "UpdatePlayerName with bogus slot %d\n", slot );
return;
}
player_info_t sPlayerInfo;
if ( IsConnected( slot ) && engine->GetPlayerInfo( slot, &sPlayerInfo ) )
{
m_szName[slot] = AllocPooledString( sPlayerInfo.name );
}
else
{
m_szName[slot] = AllocPooledString( PLAYER_UNCONNECTED_NAME );
}
}
void C_PlayerResource::ClientThink()
{
BaseClass::ClientThink();
for ( int i = 1; i <= gpGlobals->maxClients; ++i )
{
UpdatePlayerName( i );
}
SetNextClientThink( gpGlobals->curtime + PLAYER_RESOURCE_THINK_INTERVAL );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
const char *C_PlayerResource::GetPlayerName( int iIndex )
{
if ( iIndex < 1 || iIndex > MAX_PLAYERS )
{
Assert( false );
return "ERRORNAME";
}
if ( !IsConnected( iIndex ) )
return PLAYER_UNCONNECTED_NAME;
// X360TBD: Network - figure out why the name isn't set
if ( !m_szName[ iIndex ] || !Q_stricmp( m_szName[ iIndex ], PLAYER_UNCONNECTED_NAME ) )
{
// If you get a full "reset" uncompressed update from server, then you can have NULLNAME show up in the scoreboard
UpdatePlayerName( iIndex );
}
// This gets updated in ClientThink, so it could be up to 1 second out of date, oh well.
return m_szName[iIndex];
}
bool C_PlayerResource::IsAlive(int iIndex )
{
return m_bAlive[iIndex];
}
int C_PlayerResource::GetTeam(int iIndex )
{
if ( iIndex < 1 || iIndex > MAX_PLAYERS )
{
Assert( false );
return 0;
}
else
{
return m_iTeam[iIndex];
}
}
const char * C_PlayerResource::GetTeamName(int index)
{
C_Team *team = GetGlobalTeam( index );
if ( !team )
return "Unknown";
return team->Get_Name();
}
int C_PlayerResource::GetTeamScore(int index)
{
C_Team *team = GetGlobalTeam( index );
if ( !team )
return 0;
return team->Get_Score();
}
int C_PlayerResource::GetFrags(int index )
{
return 666;
}
bool C_PlayerResource::IsLocalPlayer(int index)
{
C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer();
if ( !pPlayer )
return false;
return ( index == pPlayer->entindex() );
}
bool C_PlayerResource::IsHLTV(int index)
{
if ( !IsConnected( index ) )
return false;
player_info_t sPlayerInfo;
if ( engine->GetPlayerInfo( index, &sPlayerInfo ) )
{
return sPlayerInfo.ishltv;
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool C_PlayerResource::IsFakePlayer( int iIndex )
{
if ( !IsConnected( iIndex ) )
return false;
// Yuck, make sure it's up to date
player_info_t sPlayerInfo;
if ( engine->GetPlayerInfo( iIndex, &sPlayerInfo ) )
{
return sPlayerInfo.fakeplayer;
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int C_PlayerResource::GetPing( int iIndex )
{
if ( !IsConnected( iIndex ) )
return 0;
return m_iPing[iIndex];
}
//-----------------------------------------------------------------------------
// Purpose:
/*-----------------------------------------------------------------------------
int C_PlayerResource::GetPacketloss( int iIndex )
{
if ( !IsConnected( iIndex ) )
return 0;
return m_iPacketloss[iIndex];
}*/
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int C_PlayerResource::GetPlayerScore( int iIndex )
{
if ( !IsConnected( iIndex ) )
return 0;
return m_iScore[iIndex];
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int C_PlayerResource::GetDeaths( int iIndex )
{
if ( !IsConnected( iIndex ) )
return 0;
return m_iDeaths[iIndex];
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int C_PlayerResource::GetHealth( int iIndex )
{
if ( !IsConnected( iIndex ) )
return 0;
return m_iHealth[iIndex];
}
const Color &C_PlayerResource::GetTeamColor(int index )
{
if ( index < 0 || index >= MAX_TEAMS )
{
Assert( false );
static Color blah;
return blah;
}
else
{
return m_Colors[index];
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool C_PlayerResource::IsConnected( int iIndex )
{
if ( iIndex < 1 || iIndex > MAX_PLAYERS )
return false;
else
return m_bConnected[iIndex];
}
| [
"MadKowa@ec9d42d2-91e1-33f0-ec5d-f2a905d45d61"
]
| [
[
[
1,
342
]
]
]
|
f6ed9ddbea51f5d5c724785f79ccec7a46ac68d8 | 99d3989754840d95b316a36759097646916a15ea | /trunk/2011_09_07_to_baoxin_gpd/ground_plane_detection/VLinesBasedREstimator.cpp | 6ec692ad7975c7cb0ded320cd44b579562fbc464 | []
| no_license | svn2github/ferryzhouprojects | 5d75b3421a9cb8065a2de424c6c45d194aeee09c | 482ef1e6070c75f7b2c230617afe8a8df6936f30 | refs/heads/master | 2021-01-02T09:20:01.983370 | 2011-10-20T11:39:38 | 2011-10-20T11:39:38 | 11,786,263 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 40 | cpp | #include ".\vlinesbasedrestimator.h"
| [
"ferryzhou@b6adba56-547e-11de-b413-c5e99dc0a8e2"
]
| [
[
[
1,
2
]
]
]
|
e36a5d85552fd0ba2886e7620515cc1c4185d652 | e4bad8b090b8f2fd1ea44b681e3ac41981f50220 | /trunk/Abeetles/Abeetles/RunLife.h | ef7afd3dce1ffab99e3b8678d88b5c6336f8df72 | []
| no_license | BackupTheBerlios/abeetles-svn | 92d1ce228b8627116ae3104b4698fc5873466aff | 803f916bab7148290f55542c20af29367ef2d125 | refs/heads/master | 2021-01-22T12:02:24.457339 | 2007-08-15T11:18:14 | 2007-08-15T11:18:14 | 40,670,857 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 201 | h | #pragma once
#include "Environment.h";
class CRunLife
{
public:
CRunLife(void);
~CRunLife(void);
static int run(void);
static bool DialogWithUser(CEnvironment * Env, int* jumpTime);
};
| [
"ibart@60a5a0de-1a2f-0410-942a-f28f22aea592"
]
| [
[
[
1,
11
]
]
]
|
ff3ca6c5e8966adf3a07e9cef0bd2f4c4ba8ccd6 | 709cd826da3ae55945fd7036ecf872ee7cdbd82a | /Term/WildMagic2/Renderers/OpenGL/WmlOpenGLPlanarReflection.cpp | c2c41f6cf101b985fbfd85742991b476d2172eb9 | []
| 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 | 9,478 | cpp | // Magic Software, Inc.
// http://www.magic-software.com
// http://www.wild-magic.com
// Copyright (c) 2003. All Rights Reserved
//
// The Wild Magic Library (WML) source code is supplied under the terms of
// the license agreement http://www.magic-software.com/License/WildMagic.pdf
// and may not be copied or disclosed except in accordance with the terms of
// that agreement.
#include "WmlOpenGLRenderer.h"
#include "WmlPlanarReflection.h"
using namespace Wml;
//----------------------------------------------------------------------------
void ComputeReflectionMatrix (GLfloat aafReflMatrix[4][4],
GLdouble adPlaneEq[4])
{
aafReflMatrix[0][0] = (GLfloat)(1.0 - 2.0*adPlaneEq[0]*adPlaneEq[0]);
aafReflMatrix[1][0] = (GLfloat)( - 2.0*adPlaneEq[0]*adPlaneEq[1]);
aafReflMatrix[2][0] = (GLfloat)( - 2.0*adPlaneEq[0]*adPlaneEq[2]);
aafReflMatrix[3][0] = (GLfloat)( - 2.0*adPlaneEq[3]*adPlaneEq[0]);
aafReflMatrix[0][1] = (GLfloat)( - 2.0*adPlaneEq[1]*adPlaneEq[0]);
aafReflMatrix[1][1] = (GLfloat)(1.0 - 2.0*adPlaneEq[1]*adPlaneEq[1]);
aafReflMatrix[2][1] = (GLfloat)( - 2.0*adPlaneEq[1]*adPlaneEq[2]);
aafReflMatrix[3][1] = (GLfloat)( - 2.0*adPlaneEq[3]*adPlaneEq[1]);
aafReflMatrix[0][2] = (GLfloat)( - 2.0*adPlaneEq[2]*adPlaneEq[0]);
aafReflMatrix[1][2] = (GLfloat)( - 2.0*adPlaneEq[2]*adPlaneEq[1]);
aafReflMatrix[2][2] = (GLfloat)(1.0 - 2.0*adPlaneEq[2]*adPlaneEq[2]);
aafReflMatrix[3][2] = (GLfloat)( - 2.0*adPlaneEq[3]*adPlaneEq[2]);
aafReflMatrix[0][3] = 0.0f;
aafReflMatrix[1][3] = 0.0f;
aafReflMatrix[2][3] = 0.0f;
aafReflMatrix[3][3] = 1.0f;
}
//----------------------------------------------------------------------------
void OpenGLRenderer::Draw (const PlanarReflection& rkPReflection)
{
TriMeshPtr spkPlane = rkPReflection.GetPlane();
NodePtr spkCaster = rkPReflection.GetCaster();
if ( !m_bCapPlanarReflection )
{
// The effect is not supported. Draw normally without the mirror.
// The OnDraw calls are necessary to handle culling and camera plane
// state.
spkPlane->OnDraw(*this);
spkCaster->OnDraw(*this);
return;
}
if ( m_bDrawingReflected )
{
// Some other object is currently doing a planar reflection. Do not
// allow the recursion and just draw normally.
Renderer::Draw(spkCaster);
SetState(spkPlane->GetRenderStateArray());
Draw(*spkPlane);
return;
}
// TO DO: Support for multiple mirrors could be added here by iterating
// over the section delimited by START PER-MIRROR and END PER-MIRROR.
// None of the OpenGL code needs to change, just the mirror-plane data.
// START PER-MIRROR
// enable depth buffering
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glDepthMask(GL_TRUE);
// Step 1 setup and render.
// Render the mirror into the stencil plane (but no color). All visible
// mirror pixels will have the stencil value of the mirror.
// Make sure that no pixels are written to the depth buffer or color
// buffer, but use depth buffer testing so that the stencil will not
// be written where the plane is behind something already in the
// depth buffer.
glEnable(GL_STENCIL_TEST);
glStencilFunc(GL_ALWAYS,rkPReflection.GetStencilValue(),~0);
glStencilOp(GL_KEEP,GL_KEEP,GL_REPLACE);
glStencilMask(~0);
glColorMask(GL_FALSE,GL_FALSE,GL_FALSE,GL_FALSE);
glDepthMask(GL_FALSE);
Draw(*spkPlane);
// Step 2 setup and render.
// Render the mirror plane again by only processing pixels where
// the stencil buffer contains the reference value. This time
// there is no changes to the stencil buffer and the depth buffer value
// is reset to the far view clipping plane (this is done by setting the
// range of depth values in the viewport volume to be [1,1]. Since the
// mirror plane cannot also be semi-transparent, then there we do not
// care what is behind the mirror plane in the depth buffer. We need
// to move the depth buffer values back where the mirror plane will
// be rendered so that when the reflected caster is rendered
// it can be depth buffered correctly (note that the rendering
// of the reflected caster will cause depth value to be written
// which will appear to be behind the mirror plane). Enable writes
// to the color buffer. Later when we want to render the reflecting
// plane and have it blend with the background (which should contain
// the reflected caster), we want to use the same blending function
// so that the pixels where the reflected caster was not rendered
// will contain the reflecting plane and in that case, the blending
// result will have the reflecting plane appear to be opaque when
// in reality it was blended with blending coefficients adding to one.
SetState(spkPlane->GetRenderStateArray());
glDepthRange(1.0,1.0);
glDepthFunc(GL_ALWAYS);
glStencilFunc(GL_EQUAL,rkPReflection.GetStencilValue(),~0);
glStencilOp(GL_KEEP,GL_KEEP,GL_KEEP);
glStencilMask(~0);
glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE);
glDepthMask(GL_TRUE);
Draw(*spkPlane);
// Step 2 cleanup.
// Restore the depth range and depth testing function.
glDepthFunc(GL_LESS);
glDepthRange(0.0,1.0);
// Step 3 setup.
// We are about to render the reflected caster. For that, we
// will need to compute the reflection viewing matrix.
Vector3f kCurrNormal = spkPlane->WorldRotate()*
rkPReflection.GetPlaneNormal();
Vector3f kCurrPoint = spkPlane->WorldTranslate()+spkPlane->WorldScale()*
(spkPlane->WorldRotate()*rkPReflection.GetPointOnPlane());
GLdouble adPlaneEq[4] = { -kCurrNormal.X(), -kCurrNormal.Y(),
-kCurrNormal.Z(), kCurrNormal.Dot(kCurrPoint) };
adPlaneEq[0] = -adPlaneEq[0];
adPlaneEq[1] = -adPlaneEq[1];
adPlaneEq[2] = -adPlaneEq[2];
adPlaneEq[3] = -adPlaneEq[3];
GLfloat aafReflectionMatrix[4][4];
ComputeReflectionMatrix(aafReflectionMatrix,adPlaneEq);
// Save the modelview transform before replacing it with
// the viewing transform which will handle the reflection.
glPushMatrix();
glMultMatrixf(&aafReflectionMatrix[0][0]);
// Setup a clip plane so that only objects above the mirror plane
// get reflected.
glClipPlane(GL_CLIP_PLANE0,adPlaneEq);
glEnable(GL_CLIP_PLANE0);
// Reverse the cull direction. Allow for models that are not necessarily
// set up with front or back face culling.
m_bReverseCullState = true;
// We do not support mirrors reflecting mirrors. They just appear as the
// base color in a reflection.
m_bDrawingReflected = true;
// Step 3 render.
// Render the reflected caster. Only render where the stencil buffer
// contains the reference value. Enable depth testing. This time
// allow writes to the color buffer.
glStencilFunc(GL_EQUAL,rkPReflection.GetStencilValue(),~0);
glStencilOp(GL_KEEP,GL_KEEP,GL_KEEP);
glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE);
Renderer::Draw(spkCaster);
// Step 3 cleanup.
// Restore state.
m_bDrawingReflected = false;
m_bReverseCullState = false;
glDisable(GL_CLIP_PLANE0);
glPopMatrix();
// Step 4 setup.
// We are about to render the reflecting plane again. Reset to
// the render state for the reflecting plane. We want to blend
// the reflecting plane with what is already in the color buffer
// where the reflecting plane will be rendered, particularly
// either the image of the reflected caster or the reflecting
// plane. All we want to change about the rendering of the
// reflecting plane at this stage is to force the alpha channel
// to always be the reflectance value for the reflecting plane.
// Render the reflecting plane wherever the stencil buffer is set
// to the reference value. This time clear the stencil buffer
// reference value where it is set. Perform the normal depth
// buffer testing and writes. Allow the color buffer to be
// written to, but this time blend the relecting plane with
// the values in the color buffer based on the reflectance value.
// Note that where the stencil buffer is set, the color buffer
// has either color values from the reflecting plane or the
// reflected caster. Blending will use src=1-alpha (reflecting plane)
// and dest=alpha background (reflecting plane or reflected caster).
SetState(spkPlane->GetRenderStateArray());
glEnable(GL_BLEND);
glBlendColorEXT(0.0f,0.0f,0.0f,rkPReflection.GetReflectance());
glBlendFunc(GL_ONE_MINUS_CONSTANT_ALPHA_EXT,GL_CONSTANT_ALPHA_EXT);
glStencilFunc(GL_EQUAL,rkPReflection.GetStencilValue(),~0);
glStencilOp(GL_KEEP,GL_KEEP,GL_INVERT);
glColorMask(GL_TRUE,GL_TRUE,GL_TRUE,GL_TRUE);
Draw(*spkPlane);
// Step 4 cleanup.
glDisable(GL_BLEND);
glDisable(GL_STENCIL_TEST);
// END PER-MIRROR
// render the objects as usual
Renderer::Draw(spkCaster);
}
//----------------------------------------------------------------------------
| [
"[email protected]"
]
| [
[
[
1,
221
]
]
]
|
214a0c7645c2a568a07d65c23f51a34d5a79d31e | 3920e5fc5cbc2512701a3d2f52e072fd50debb83 | /Source/Common/itkManagedImage.cxx | 46be521cd9a8c20f9a71e0a9fff0f5f5c355de32 | [
"MIT"
]
| permissive | amirsalah/manageditk | 4063a37d7370dcbcd08bfe9d24d22015d226ceaf | 1ca3a8ea7db221a3b6a578d3c75e3ed941ef8761 | refs/heads/master | 2016-08-12T05:38:03.377086 | 2010-08-02T08:17:32 | 2010-08-02T08:17:32 | 52,595,294 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,658 | cxx | /*=============================================================================
NOTE: THIS FILE IS A HANDMADE WRAPPER FOR THE ManagedITK PROJECT.
Project: ManagedITK
Program: Insight Segmentation & Registration Toolkit
Module: itkManagedImage.cxx
Language: C++/CLI
Author: Dan Mueller
Date: $Date: 2008-06-21 09:20:09 +0200 (Sat, 21 Jun 2008) $
Revision: $Revision: 18 $
Portions of this code are covered under the ITK and VTK copyright.
See http://www.itk.org/HTML/Copyright.htm for details.
See http://www.vtk.org/copyright.php for details.
Copyright (c) 2007-2008 Daniel Mueller
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.
=============================================================================*/
#pragma once
#pragma warning( disable : 4635 ) // Disable warnings about XML doc comments
#pragma warning( disable : 4996 ) // Disable warnings about deprecated methods
#ifndef __itkManagedImage_cxx
#define __itkManagedImage_cxx
// Include some useful ManagedITK files
#include "itkManagedImageBase.cxx"
#include "itkManagedInvalidWrappedTypeException.cxx"
// Use some managed namespaces
#using <mscorlib.dll>
#using <System.dll>
using namespace System;
using namespace System::IO;
using namespace System::Reflection;
using namespace System::Diagnostics;
namespace itk
{
///<summary>
///This class is a managed wrapper for itk::Image. A specific image type
///(eg. unsigned char, float, etc.) can be instantiated using the
///New(pixeltype, dim) method.
///</summary>
///<remarks>
///Images are defined by a pixel type (modeling the dependent variables),
///and a dimension (number of independent variables).
///An image is modeled as an array, defined by a start index and a size.
///The underlying array can be accessed via the Buffer property.
///
///There are three sets of meta-data describing an image. These are "Region"
///objects that define a portion of an image via a starting index for the image
///array and a size. The ivar LargestPossibleRegion defines the size and
///starting index of the image dataset. The entire image dataset, however,
///need not be resident in memory. The region of the image that is resident in
///memory is defined by the "BufferedRegion". The Buffer is a contiguous block
///of memory. The third set of meta-data defines a region of interest, called
///the "RequestedRegion". The RequestedRegion is used by the pipeline
///execution model to define what a filter is requested to produce.
///</remarks>
public ref class itkImage : itkImageBase
{
private:
itkImageBase^ m_Instance;
protected:
///<summary>Protected constructor.</summary>
itkImage ( ) : itkImageBase( )
{ }
public:
///<summary>Dispose of the managed object.</summary>
~itkImage ( )
{
if (!this->IsDisposed)
{
this->m_IsDisposed = true;
delete m_Instance;
}
}
///<summary>Finalize the managed object.</summary>
!itkImage ( )
{
if (!this->IsDisposed && this->DisposeNativeObjectOnFinalize)
delete this;
}
///<summary>Get/set a string describing the data object (typically an abosolute file name).</summary>
property String^ Name
{
virtual String^ get() override { return this->m_Instance->Name; }
virtual void set( String^ name ) override { this->m_Instance->Name = name; }
}
///<summary>Get the size of the image (from the LargestPossibleRegion).</summary>
///<remarks>This method was added in ManagedITK for simplicity.</remarks>
property itkSize^ Size
{
virtual itkSize^ get() override { return this->m_Instance->Size; }
}
///<summary>Get/set the spacing between pixels of the image.</summary>
property itkSpacing^ Spacing
{
virtual itkSpacing^ get() override { return this->m_Instance->Spacing; }
virtual void set( itkSpacing^ spacing ) override { this->m_Instance->Spacing = spacing; }
}
///<summary>Get/set the origin of the image in physical space.</summary>
property itkPoint^ Origin
{
virtual itkPoint^ get() override { return this->m_Instance->Origin; }
virtual void set( itkPoint^ origin ) override { this->m_Instance->Origin = origin; }
}
///<summary>
///Get/set the region object that defines the size and starting index
///for the largest possible region this image could represent.
///</summary>
property itkImageRegion^ LargestPossibleRegion
{
virtual itkImageRegion^ get() override { return this->m_Instance->LargestPossibleRegion; }
virtual void set ( itkImageRegion^ region ) override { this->m_Instance->LargestPossibleRegion = region; }
}
///<summary>
///Get/set the region object that defines the size and starting index
///for the region of the image requested (i.e., the region of the
///image to be operated on by a filter). Setting the RequestedRegion
///does not cause the object to be modified.
///</summary>
property itkImageRegion^ RequestedRegion
{
virtual itkImageRegion^ get() override { return this->m_Instance->RequestedRegion; }
virtual void set ( itkImageRegion^ region ) override { this->m_Instance->RequestedRegion = region; }
}
///<summary>
///Get/set the region object that defines the size and starting index
///of the region of the image currently loaded in memory.
///</summary>
property itkImageRegion^ BufferedRegion
{
virtual itkImageRegion^ get() override { return this->m_Instance->BufferedRegion; }
virtual void set ( itkImageRegion^ region ) override { this->m_Instance->BufferedRegion = region; }
}
///<summary>Get the pointer to the underlying image data array.</summary>
property IntPtr Buffer
{
virtual IntPtr get() override { return this->m_Instance->Buffer; }
}
///<summary>Get the direction cosines of the image. The direction cosines are vectors that point from one pixel to the next.</summary>
property itkMatrix^ Direction
{
virtual itkMatrix^ get() override { return this->m_Instance->Direction; }
virtual void set ( itkMatrix^ direction ) override { this->m_Instance->Direction = direction; }
}
///<summary>
///Gets/sets if the underlying native object should be disposed when the managed object is finalized.
///The default is true.
///</summary>
property bool DisposeNativeObjectOnFinalize
{
virtual bool get() override
{
if ( this->m_Instance == nullptr ) return true;
else return this->m_Instance->DisposeNativeObjectOnFinalize;
}
virtual void set( bool value ) override
{
if ( this->m_Instance != nullptr )
this->m_Instance->DisposeNativeObjectOnFinalize = value;
}
}
///<summary>Get the last modified time.</summary>
property unsigned long MTime
{
virtual unsigned long get() override { return this->m_Instance->MTime; }
}
///<summary>Get a string representing the type instance of this INativePointer.</summary>
///<example>"IUC2", "IF3", "IVF22".</example>
property String^ MangledTypeString
{
virtual String^ get() override
{
INativePointer^ instanceSmartPtr = safe_cast<INativePointer^>(m_Instance);
return instanceSmartPtr->MangledTypeString;
}
}
///<summary>
///Get/set the pointer to the native ITK object associated with
///this wrapper instance.
///</summary>
///<returns>The pointer to the native ITK object.</returns>
property virtual IntPtr NativePointer
{
virtual IntPtr get() override
{
INativePointer^ instanceSmartPtr = safe_cast<INativePointer^>(m_Instance);
return instanceSmartPtr->NativePointer;
}
virtual void set ( IntPtr value) override
{
INativePointer^ instanceSmartPtr = safe_cast<INativePointer^>(m_Instance);
instanceSmartPtr->NativePointer = value;
}
}
///<summary>Create an instance of an underlying native itk::Image.</summary>
///<param name="pixelType">The pixel type the underlying native itk::Image is templated over.</param>
///<param name="dim">The number of dimensions the underlying native itk::Image is templated over.</param>
static itkImage^ New ( itkPixelType^ pixelType, unsigned int dim )
{
if (pixelType == nullptr)
throw gcnew itkInvalidWrappedTypeException("The given pixel type is null. A valid pixel type must be specified to create an instance of a wrapped itk::Image.");
itkImage^ newImage = gcnew itkImage();
newImage->m_PixelType = pixelType;
newImage->m_Dimension = dim;
newImage->CreateInstance();
return newImage;
}
///<summary>Create an instance of the same underlying native itk::Image type as the given image.</summary>
///<param name="image">The type of the underlying native itk::Image to create.</param>
static itkImage^ New ( itkImageBase^ image )
{
if (image == nullptr)
throw gcnew itkInvalidWrappedTypeException("The given image is null. A valid image must be specified to create an instance of a wrapped itk::Image.");
itkImage^ newImage = gcnew itkImage();
newImage->m_PixelType = image->PixelType;
newImage->m_Dimension = image->Dimension;
newImage->CreateInstance();
return newImage;
}
///<summary>Create an instance of an underlying native itk::Image.</summary>
///<param name="mangledPixelType">A string representing the pixel type the underlying native itk::Image is templated over.</param>
///<param name="dim">The number of dimensions the underlying native itk::Image is templated over.</param>
static itkImage^ New ( String^ mangledPixelType, unsigned int dim )
{
if (mangledPixelType == nullptr || mangledPixelType->Length == 0)
throw gcnew itkInvalidWrappedTypeException("The given pixel type string is empty. A non-empty, valid pixel type string must be specified to create an instance of a wrapped itk::Image.");
itkImage^ newImage = gcnew itkImage();
newImage->m_PixelType = itkPixelType::CreateFromMangledType(mangledPixelType);
newImage->m_Dimension = dim;
newImage->CreateInstance();
return newImage;
}
///<summary>Create an instance of an underlying native itk::Image.</summary>
///<param name="mangledType">A string representing the pixel type and dimension the underlying native itk::Image is templated over. Eg. "UC2", "F3", etc.</param>
static itkImage^ New ( String^ mangledType )
{
if (mangledType == nullptr || mangledType->Length == 0)
throw gcnew itkInvalidWrappedTypeException("The given image type string is empty. A non-empty, valid image type string must be specified to create an instance of a wrapped itk::Image.");
itkImage^ newImage = gcnew itkImage();
newImage->m_PixelType = itkPixelType::CreateFromMangledType(mangledType);
newImage->m_Dimension = UInt32::Parse(mangledType->Substring(mangledType->Length-1, 1));
newImage->CreateInstance();
return newImage;
}
///<summary>Return itk::LightObject::Print( ostream ) as a string.</summary>
virtual String^ ToString ( ) override
{
return m_Instance->ToString( );
}
///<summary>
///Remove all observers watching this object.
///</summary>
///<remarks>
///By default, observers are created for all events. Calling this
///method removes all native observers, and therefore prevents
///the firing of managed events. Call AddAnyEventObserver() to
///reset the default observers which enable the managed events.
///</remarks>
virtual void RemoveAllObservers ( ) override
{
this->m_Instance->RemoveAllObservers();
}
///<summary>
///Adds a native observer watching for any event.
///</summary>
///<remarks>
///By default, observers are created for all events. Calling this
///method adds a single native observer for any event. This
///observer invokes the managed events. Therefore, calling this
///method more than once, or calling it without first calling
///RemoveAllObservers(), may cause the managed events to be
///invoked more than once.
///</remarks>
virtual void AddAnyEventObserver ( ) override
{
this->m_Instance->AddAnyEventObserver( );
this->PassEventsFromTypeToWrapper( );
}
///<summary>Read the image from the given file.</summary>
///<param name="filename">The relative or absolute file path and name.</param>
virtual void Read ( System::String^ filename ) override
{
this->m_Instance->Read(filename);
}
///<summary>Read an image series from the given filenames.</summary>
///<param name="filenames">An array of absolute file paths.</param>
///<remarks>This method was added in ManagedITK for simplicity.</remarks>
virtual void ReadSeries ( array<System::String^>^ filenames ) override
{
this->m_Instance->ReadSeries(filenames);
}
///<summary>Read an image series from the files matching the given pattern.</summary>
///<param name="path">An absolute path to search for the files comprising the series.</param>
///<param name="pattern">A pattern with wildcard character '*'.</param>
///<example>path="C:/temp/", pattern="test_*.png".</example>
///<remarks>This method was added in ManagedITK for simplicity.</remarks>
virtual void ReadSeries ( System::String^ path, System::String^ pattern ) override
{
this->m_Instance->ReadSeries(path, pattern);
}
///<summary>
///Read an image from the given DICOM directory using GDCM.
///This method uses the first found series identifier.
///</summary>
///<param name="directory">The directory containing the DICOM series.</param>
///<remarks>This method was added in ManagedITK for simplicity.</remarks>
virtual void ReadDicomDirectory( System::String^ directory ) override
{
this->m_Instance->ReadDicomDirectory(directory);
}
///<summary>Read an image from the given DICOM directory using GDCM.</summary>
///<param name="directory">The directory containing the DICOM series.</param>
///<param name="seriesid">The identifier of the series to read.</param>
///<remarks>This method was added in ManagedITK for simplicity.</remarks>
virtual void ReadDicomDirectory( System::String^ directory, System::String^ seriesid ) override
{
this->m_Instance->ReadDicomDirectory(directory, seriesid);
}
///<summary>Read an image from the given DICOM directory using GDCM.</summary>
///<param name="directory">The directory containing the DICOM series.</param>
///<param name="seriesid">The identifier of the series to read.</param>
///<param name="restrictions">Specifies additional DICOM information to distinguish unique volumes within the directory. Eg. "0008|0021" distinguishes series based on date.</param>
///<remarks>This method was added in ManagedITK for simplicity.</remarks>
virtual void ReadDicomDirectory( System::String^ directory,
System::String^ seriesid,
... array<System::String^>^ restrictions) override
{
this->m_Instance->ReadDicomDirectory(directory, seriesid, restrictions);
}
///<summary>Write the image to the given file.</summary>
///<param name="filename">The relative or absolute file path and name.</param>
///<remarks>This method was added in ManagedITK for simplicity.</remarks>
virtual void Write ( System::String^ filename ) override
{
this->m_Instance->Write(filename);
}
///<summary>Write an image series to the files matching the given format.</summary>
///<param name="filenameFormat">The absolute path and filename format for the images. Eg. C:/temp/test_{0}.png.</param>
///<param name="seriesFormat">A format string for the series numbers. Eg. "000".</param>
///<example>filenameFormat="C:/temp/test_{0}.png" and seriesFormat="000".</example>
///<remarks>This method was added in ManagedITK for simplicity.</remarks>
virtual void WriteSeries ( System::String^ filenameFormat, System::String^ seriesFormat ) override
{
this->m_Instance->WriteSeries(filenameFormat, seriesFormat);
}
///<summary>
///Allocates the memory for an empty image.
///This is the method to use to create an image from scratch (ie. not from IO).
///The regions MUST have been set: call SetRegions() before calling this method.
///The buffer is NOT initialised: call FillBuffer() after calling this method.
///</summary>
///<remarks>This method finalises the creation of the underlying native itk::Image.</remarks>
virtual void Allocate ( ) override
{
this->m_Instance->Allocate();
}
///<summary>
///Convenience method to set the LargestPossibleRegion, BufferedRegion and RequestedRegion.
///</summary>
///<param name="regions">The image region specifying the largest, requested, and buffered size.</param>
///<remarks>
///This method does not allocate the image, use Allocate for that purpose.
///</remarks>
virtual void SetRegions ( itkImageRegion^ regions ) override
{
this->m_Instance->SetRegions(regions);
}
///<summary>
///Fills the image data with the given value.
///The image regions must be set before calling this method and
///the image must have been allocated.
///</summary>
///<param name="value">The pixel value to fill the image.</param>
virtual void FillBuffer ( itkPixel^ value ) override
{
this->m_Instance->FillBuffer(value);
}
///<summary>Returns the pixel value at the given discrete location.</summary>
///<param name="index">The discrete location in image space.</param>
///<returns>The pixel value at the given discrete location.</returns>
virtual itkPixel^ GetPixel ( itkIndex^ index ) override
{
return m_Instance->GetPixel(index);
}
///<summary>Set the pixel value at the given discrete location.</summary>
///<param name="index">The discrete location in image space.</param>
///<param name="value">The new value to set.</param>
virtual void SetPixel ( itkIndex^ index, itkPixel^ value ) override
{
this->m_Instance->SetPixel(index, value);
}
///<summary>Separate this image from the pipeline.</summary>
///<remarks>
///This method disconnects the image from the upstream pipeline.
///Hence an Update() from downstream will not propagate back past this image.
///To completely isolate this image from the pipeline, the application must
///remove this image from any filters which it is connected as the input.
///</remarks>
virtual void DisconnectPipeline ( ) override
{
this->m_Instance->DisconnectPipeline();
}
///<summary>Convert a physical point to a continuous index.</summary>
///<param name="point">The geometric location in physical space.</param>
///<param name="cindex">The resultant continuous location in image space.</param>
///<returns>true if the resulting index is within the image, false otherwise.</returns>
virtual bool TransformPhysicalPointToContinuousIndex( itkPoint^ point, [System::Runtime::InteropServices::Out] itkContinuousIndex^% cindex ) override
{
return this->m_Instance->TransformPhysicalPointToContinuousIndex(point, cindex);
}
///<summary>Convert a physical point to a discrete index.</summary>
///<param name="point">The geometric location in physical space.</param>
///<param name="index">The resultant discrete location in image space.</param>
///<returns>true if the resulting index is within the image, false otherwise.</returns>
virtual bool TransformPhysicalPointToIndex( itkPoint^ point, [System::Runtime::InteropServices::Out] itkIndex^% index ) override
{
return this->m_Instance->TransformPhysicalPointToIndex(point, index);
}
///<summary>Convert a continuous index to a physical point.</summary>
///<param name="cindex">The continuous location in image space.</param>
///<param name="point">The resultant geometric location in physical space.</param>
virtual void TransformContinuousIndexToPhysicalPoint( itkContinuousIndex^ cindex, [System::Runtime::InteropServices::Out] itkPoint^% point ) override
{
this->m_Instance->TransformContinuousIndexToPhysicalPoint(cindex, point);
}
///<summary>Convert a discrete index to a physical point.</summary>
///<param name="index">The discrete location in image space.</param>
///<param name="point">The resultant geometric location in physical space.</param>
virtual void TransformIndexToPhysicalPoint( itkIndex^ index, [System::Runtime::InteropServices::Out] itkPoint^% point ) override
{
this->m_Instance->TransformIndexToPhysicalPoint(index, point);
}
private:
///<summary>Creates the correct type instance of the underlying native itk::Image.</summary>
void CreateInstance ( )
{
this->m_IsDisposed = false;
String^ nameInstanceType = "itk.itkImage_" + this->PixelType->MangledTypeString + this->Dimension;
try
{
System::Type^ typeInstance = System::Reflection::Assembly::GetExecutingAssembly()->GetType(nameInstanceType);
if (typeInstance == nullptr)
throw gcnew NullReferenceException("The type '" + nameInstanceType + "' could not be found in " + System::Reflection::Assembly::GetExecutingAssembly()->GetName() );
System::Object^ objInstance = typeInstance->InvokeMember("New", System::Reflection::BindingFlags::InvokeMethod, System::Type::DefaultBinder, nullptr, nullptr);
if (objInstance == nullptr)
throw gcnew NullReferenceException("Could not invoke the New() method for '" + nameInstanceType + "'.");
this->m_Instance = safe_cast<itkImageBase^>(objInstance);
this->PassEventsFromTypeToWrapper( );
}
catch (Exception^ ex)
{
throw gcnew itkInvalidWrappedTypeException("Could not create an instance of '" + nameInstanceType + "'. The given type may not be supported or may be invalid.", ex);
}
}
///<summary>Pass managed events from the type instance to this wrapper instance.</summary>
void PassEventsFromTypeToWrapper()
{
this->m_Instance->Started += gcnew itkEventHandler(this, &itkImage::Instance_StartedHandler);
this->m_Instance->Ended += gcnew itkEventHandler(this, &itkImage::Instance_EndedHandler);
this->m_Instance->Aborted += gcnew itkEventHandler(this, &itkImage::Instance_AbortedHandler);
this->m_Instance->Iteration += gcnew itkEventHandler(this, &itkImage::Instance_IterationHandler);
this->m_Instance->Modified += gcnew itkEventHandler(this, &itkImage::Instance_ModifiedHandler);
}
///<summary>Handle the Started event.</summary>
void Instance_StartedHandler(itkObject^ sender, itkEventArgs^ e)
{
this->InvokeStartedEvent(e);
}
///<summary>Handle the Ended event.</summary>
void Instance_EndedHandler(itkObject^ sender, itkEventArgs^ e)
{
this->InvokeEndedEvent(e);
}
///<summary>Handle the Aborted event.</summary>
void Instance_AbortedHandler(itkObject^ sender, itkEventArgs^ e)
{
this->InvokeAbortedEvent(e);
}
///<summary>Handle the Iteration event.</summary>
void Instance_IterationHandler(itkObject^ sender, itkEventArgs^ e)
{
this->InvokeIterationEvent(e);
}
///<summary>Handle the Modified event.</summary>
void Instance_ModifiedHandler(itkObject^ sender, itkEventArgs^ e)
{
this->InvokeModifiedEvent(e);
}
}; // end ref class
} // end namespace itk
#endif | [
"dan.muel@a4e08166-d753-0410-af4e-431cb8890a25"
]
| [
[
[
1,
573
]
]
]
|
4df0d830c752f2aa5fcfc9a867e3871a97c28a40 | 0f8559dad8e89d112362f9770a4551149d4e738f | /Wall_Destruction/Havok/Source/Physics/Utilities/VisualDebugger/Viewer/Dynamics/hkpConstraintViewer.h | 54f655829b7a5aa03650b4727600473f7d7f0280 | []
| 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,783 | h | /*
*
* 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.
*
*/
#ifndef HK_UTILITIES2_CONSTRAINT_VIEWER_H
#define HK_UTILITIES2_CONSTRAINT_VIEWER_H
#include <Physics/Utilities/VisualDebugger/Viewer/Dynamics/hkpWorldViewerBase.h>
#include <Physics/Dynamics/World/Listener/hkpWorldPostSimulationListener.h>
#include <Physics/Dynamics/Constraint/hkpConstraintListener.h>
class hkDebugDisplayHandler;
class hkpWorld;
class hkpRigidBody;
/// Shows constraint limits and frames.
class hkpConstraintViewer : public hkpWorldViewerBase,
protected hkpWorldPostSimulationListener
{
public:
HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_TOOLS);
/// Creates a hkpConstraintViewer.
static hkProcess* HK_CALL create(const hkArray<hkProcessContext*>& contexts);
/// Registers the hkpConstraintViewer with the hkViewerFactory.
static void HK_CALL registerViewer();
/// Gets the tag associated with this viewer type
virtual int getProcessTag() { return m_tag; }
static inline const char* HK_CALL getName() { return "Constraints"; }
protected:
hkpConstraintViewer(const hkArray<hkProcessContext*>& contexts);
virtual ~hkpConstraintViewer();
virtual void postSimulationCallback( hkpWorld* world );
virtual void worldAddedCallback( hkpWorld* world);
virtual void worldRemovedCallback( hkpWorld* world);
void draw(hkpConstraintInstance* constraint, const hkpEntity* masterEntity, hkDebugDisplayHandler* displayHandler);
protected:
static int m_tag;
hkArray<hkpConstraintInstance*> m_constraints;
public:
static hkReal m_scale;
};
#endif // HK_UTILITIES2_CONSTRAINT_VIEWER_H
/*
* 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.
*
*/
| [
"[email protected]"
]
| [
[
[
1,
79
]
]
]
|
5eb2c9ca4cbffbf2008b038534840ab76b048482 | eae3fc654f3a8063c819ee2844bba6b5cafba06f | /rgb.cpp | 5436890c878e0a617bf95394eef120a200ab8e5b | []
| no_license | DanielSkalski/majographix | f7c037448142465e1bd9483caf208c8bae371728 | 7ca30edd0b7eb138b342cb13cd39a84ed2a2280f | refs/heads/master | 2021-01-10T17:58:11.874374 | 2010-03-10T14:06:00 | 2010-03-10T14:06:00 | 36,719,665 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 961 | cpp | #include "rgb.h"
Rgb::Rgb(double r, double g, double b)
{
this->rv = r;
this->gv = g;
this->bv = b;
}
Rgb::Rgb(QColor c)
{
int r,g,b;
c.getRgb(&r,&g,&b);
this->rv = r;
this->gv = g;
this->bv = b;
}
Rgb::Rgb(const Rgb& r1)
{
rv = r1.r();
gv = r1.g();
bv = r1.b();
}
Rgb& Rgb::operator+(Rgb r1)
{
this->rv += r1.r();
this->gv += r1.g();
this->bv += r1.b();
rabs();
return *this;
}
Rgb& Rgb::operator-(Rgb r1)
{
this->rv -= r1.r();
this->gv -= r1.g();
this->bv -= r1.b();
rabs();
return *this;
}
Rgb& Rgb::operator=(Rgb r1)
{
this->rv = r1.r();
this->gv = r1.g();
this->bv = r1.b();
return *this;
}
Rgb& Rgb::operator/(double d)
{
rv /= d;
gv /= d;
bv /= d;
return *this;
}
Rgb& Rgb::operator*(double d)
{
rv *= d;
gv *= d;
bv *= d;
return *this;
}
| [
"[email protected]"
]
| [
[
[
1,
69
]
]
]
|
bfc50097b26c061fc7f38f9839bec7fba058db8f | 2f5bdba53c64b445a834c330bd13739ec714e273 | /simple-sdl-engine/src/Engine.cpp | 02278ecf0fa37ba316fc731f9751b22362db9f94 | []
| no_license | drphrozen/simple-sdl-engine | 1b17f2ce1e7db240ca7137cc2aba5cf696ce51ad | e2642b0fb08708b9b079376b45b6ea41271b04b2 | refs/heads/master | 2020-06-29T06:38:31.424982 | 2010-03-23T21:35:01 | 2010-03-23T21:35:01 | 32,145,883 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,422 | cpp | /*
* Engine.cpp
*
* Created on: 23/03/2010
* Author: drphrozen
*/
#include "Engine.h"
#include "GameException.h"
#include <SDL/SDL.h>
#include <iostream>
using std::endl;
#include <sstream>
using std::ostringstream;
Engine* Engine::engine = 0;
TickFunctionPtr Engine::tickPtr = 0;
Engine::Engine(int width, int height)
: done(true) {
/* Initialize SDL */
if (SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO) < 0) {
ostringstream stream;
stream << "Couldn't initialize SDL: " << SDL_GetError() << endl;
throw GameException(stream.str());
}
/* Set video mode */
screen = SDL_SetVideoMode(width, height, 0, SDL_SWSURFACE | SDL_ANYFORMAT);
if (!screen) {
ostringstream stream;
stream << "Couldn't set " << width << "x" << height << " video mode: %s" << SDL_GetError() << endl;
throw GameException(stream.str());
}
Sprite::screen = screen;
// TODO: move
background = SDL_MapRGB(screen->format, 0x99, 0xD9, 0xEA);
engine = this;
tickPtr = &Engine::tick;
}
Uint32 Engine::tick_wrapper(Uint32 interval) {
return (Engine::engine->*tickPtr)(interval);
}
void Engine::start(int fps) {
done = false;
SDL_SetTimer((int)(1000.0f/fps), &Engine::tick_wrapper);
SDL_Event event;
while (!done) {
while (SDL_PollEvent(&event)) {
HandleEvent(event);
}
}
}
void Engine::stop() {
done = true;
}
Engine::~Engine() {
}
| [
"drphrozen@9ebed219-65ff-6541-0e02-73910df5e799"
]
| [
[
[
1,
69
]
]
]
|
14e370e13fa4f84939eae5f82b075f56d0f636c2 | 2d212a074917aad8c57ed585e6ce8e2073aa06c6 | /cgworkshop/src/GUI/GUI.h | 266a77cf5c4927f091f1208a76f3232ba33e611e | []
| no_license | morsela/cgworkshop | b31c9ec39419edcedfaed81468c923436528e538 | cdf9ef2a9b2d9c389279fe0e38fb9c8bc1d86d89 | refs/heads/master | 2021-07-29T01:37:24.739450 | 2007-09-09T13:44:54 | 2007-09-09T13:44:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,017 | h | #ifndef _H_GUI_H_
#define _H_GUI_H_
#include <cv.h>
#include <GL/glut.h>
#include "TypeDefs.h"
#include "Loader.h"
#include "ControlPanel.h"
#include "ButtonPanel.h"
enum ESegmentationMethod
{
ONE_COL_SEGMENTATION,
AE_COL_SEGMENTATION,
AVG_COL_SEGMENTATION
};
class CGUI
{
public:
static void ThreadRunSegmentation( void *p );
public:
CGUI();
virtual ~CGUI() {}
bool Setup(char * pszImagePath, char * pScribbleFile = NULL);
static CGUI * GetInstance() { static CGUI inst; return &inst; }
void LoadTextures();
public:
int GetWindowWidth() const { return m_nWindowWidth; }
int GetWindowHeight() const { return m_nWindowHeight; }
void SetWindowSize(int x, int y) { m_nWindowWidth = x; m_nWindowHeight = y; }
int GetImageWidth() const { return m_nImageWidth; }
int GetImageHeight() const { return m_nImageHeight; }
void SetImageSize(int x, int y) { m_nImageWidth = x; m_nImageHeight = y; }
const IplImage * const GetImage() { return m_pImg; }
public:
void MouseMove(int x, int y);
void MouseAction(int button, int state, int x, int y);
void KeysAction(unsigned char key, int x, int y );
void Reshape(int x , int y);
void Render();
protected:
void RunSegmentation();
void AddScribblePoints(int x, int y);
friend class CControlPanel;
protected:
bool m_fRunning;
CButtonPanel m_buttonPanel;
CControlPanel m_ctrlPanel;
IplImage * m_pImg;
int m_nWindowWidth;
int m_nWindowHeight;
int m_nImageWidth;
int m_nImageHeight;
// the bounding box for the opengl orthogonal projection
float m_orthoBBox[4];
float m_orthoBBox2[4];
unsigned int m_textures[1];
// The vectors in object space coordinates (for rendering)
ScribbleVector m_scribbles;
bool m_fScribbling;
CLoader m_loader;
int m_nCurScribble;
int m_nScribblesNum;
ESegmentationMethod m_nSegMethod;
};
#endif //_H_GUI_H_
| [
"morsela@60b542fb-872c-0410-bfbb-43802cb78f6e"
]
| [
[
[
1,
112
]
]
]
|
f0594635d61a7d434dff5bf558fbd528cfa60387 | a699a508742a0fd3c07901ab690cdeba2544a5d1 | /RailwayDetection/KellService/KellService/IOCP/BaseThread.cpp | 9278ed698830c3d92a7ca7882213d6753f005165 | []
| 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 | 2,544 | cpp | #include "StdAfx.h"
#include <process.h>
#include "BaseThread.h"
CBaseThread::CBaseThread(void)
{
m_hThread = NULL;
m_bIsTerminate = false;
}
CBaseThread::~CBaseThread(void)
{
SafeTerminate();
}
bool CBaseThread::BeginThread(bool bIsRun)
{
if(NULL == m_hThread)
{
if(bIsRun)
m_hThread = (HANDLE)_beginthreadex(NULL, 0, &CBaseThread::Execute, (PVOID)this, 0, NULL);
else
m_hThread = (HANDLE)_beginthreadex(NULL, 0, &CBaseThread::Execute, (PVOID)this, CREATE_SUSPENDED, NULL);
if(m_hThread)
{
DoWriteLogInfo(LOG_DEBUG, _T("CBaseThread::CreateThreadInstance(), 创建子线程成功"));
return true;
}
WriteLogInfo(LOG_INFO, _T("CBaseThread::CreateThreadInstance(), 创建子线程出错,错误代码:%d"), errno);
}
return false;
}
bool CBaseThread::ForceTerminate()
{
if(m_hThread)
{
BOOL bErrorCode = FALSE;
bErrorCode = ::TerminateThread(m_hThread, -1);
if(bErrorCode)
{
CloseHandle(m_hThread);
m_hThread = NULL;
m_bIsTerminate = true;
return true;
}
int nErrorCode = GetLastError();
CloseHandle(m_hThread);
m_hThread = NULL;
m_bIsTerminate = true;
WriteLogInfo(LOG_INFO, _T("CBaseThread::ForceTerminate(), 强制关闭线程出错,错误代码:%d"), nErrorCode);
return false;
}
return true;
}
DWORD CBaseThread::ResumeThread()
{
if(m_hThread)
{
int nErrorCode = 0;
nErrorCode = ::ResumeThread(m_hThread);
if(-1 != nErrorCode)
{
return nErrorCode;
}
nErrorCode = GetLastError();
WriteLogInfo(LOG_INFO, _T("CBaseThread::ResumeThread(), 启动挂起的线程出错,错误代码:%d"), nErrorCode);
}
return -1;
}
DWORD CBaseThread::SuspendThread()
{
if(m_hThread)
{
int nErrorCode = 0;
nErrorCode = ::SuspendThread(m_hThread);
if(-1 != nErrorCode)
{
return nErrorCode;
}
nErrorCode = GetLastError();
WriteLogInfo(LOG_INFO, _T("CBaseThread::SuspendThread(), 挂起正在运行的线程出错,错误代码:%d"), nErrorCode);
}
return -1;
}
void CBaseThread::SafeTerminate()
{
if(m_hThread)
{
m_bIsTerminate = true;
WaitForSingleObject(m_hThread, 2000);
m_hThread = NULL;
}
}
unsigned int WINAPI CBaseThread::Execute(PVOID pArguments)
{
CBaseThread * pThread = (CBaseThread*)pArguments;
if(pThread)
{
unsigned int nExitCode = 0;
nExitCode = pThread->ExecuteThread();
CloseHandle(pThread->m_hThread);
pThread->m_hThread = NULL;
return nExitCode;
}
return 0;
}
| [
"[email protected]@4d6b9eea-9d24-033f-dd66-d003eccfd9d3"
]
| [
[
[
1,
126
]
]
]
|
a3dadafbd15e025a1c070accafa75506ec76642f | d1e629aeb72407daccf96515380b8f6044d3b38b | /Arduino/libraries/GPS/GPS.h | 514ae05b6a5cf4a891950baa576c15dd4896e0bf | []
| no_license | blanchg/balloon | 8eb97e1af67c8cd84a955b2f14de995b4add6153 | d69ac6220fc4bfbe6453f152e632d75097a71d68 | refs/heads/master | 2016-09-05T19:32:10.693398 | 2011-10-25T19:39:49 | 2011-10-25T19:39:49 | 2,574,623 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 789 | h |
#ifndef gps_h
#define gps_h
#include <SoftwareSerial.h>
#include <TinyGPS.h>
const short GPS_MSG_NONE = 0;
const short GPS_MSG_NMEA = 1;
const short GPS_MSG_BIN = 2;
class GPS : public SoftwareSerial
{
public:
long lat; // 100,000ths of a degree
long lon; // 100,000ths of a degree
long alt; // cm
unsigned long date;
unsigned long time;
unsigned long fix_age;
unsigned long course; // 100ths of a degree
unsigned long speed; // 100ths of a knot * 1.852 to get kph
TinyGPS data;
GPS(int rxPin, int txPin);
~GPS();
void begin(int speed);
void end();
bool capture();
void fixSpeed(int newSpeed);
void messageMode(short mode);
void nmeaStrings();
void powerMode(bool powerSave);
void changeSpeed(int currentSpeed, int newSpeed);
};
#endif
| [
"[email protected]"
]
| [
[
[
1,
39
]
]
]
|
a5bbef7d08afb856b08e0398329d1bfbbb6c2434 | 6188f1aaaf5508e046cde6da16b56feb3d5914bc | /CamFighter/AppFramework/OGL/GLWindowL.cpp | cdb8ed87e015febcf10a5e432a9a9d4dee9f9a96 | []
| 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 | 5,384 | cpp | #ifndef WIN32
#include "GLWindow.h"
#include <cstdio>
#include <cstring>
#include <cassert>
/* attributes for a single buffered visual in RGBA format with at least
* * 4 bits per color and a 16 bit depth buffer */
static int attrListSgl[] = {GLX_RGBA,
GLX_RED_SIZE, 8,
GLX_GREEN_SIZE, 8,
GLX_BLUE_SIZE, 8,
GLX_DEPTH_SIZE, 24,
GLX_STENCIL_SIZE, 8,
None};
/* attributes for a double buffered visual in RGBA format with at least
* * 4 bits per color and a 16 bit depth buffer */
static int attrListDbl[] = { GLX_RGBA, GLX_DOUBLEBUFFER,
GLX_RED_SIZE, 8,
GLX_GREEN_SIZE, 8,
GLX_BLUE_SIZE, 8,
GLX_DEPTH_SIZE, 24,
GLX_STENCIL_SIZE, 8,
None };
bool GLWindow::Create()
{
assert ( !IsDestroyed() );
assert ( IsDisposed() );
XVisualInfo *vi;
Colormap cmap;
int dpyWidth, dpyHeight;
int i;
int glxMajorVersion, glxMinorVersion;
int vidModeMajorVersion, vidModeMinorVersion;
XF86VidModeModeInfo **modes;
int modeNum;
int bestMode;
Atom wmDelete;
Window winDummy;
unsigned int borderDummy;
/* set best mode to current */
bestMode = 0;
/* get a connection */
hDC = XOpenDisplay(0);
screen = DefaultScreen(hDC);
XF86VidModeQueryVersion(hDC, &vidModeMajorVersion, &vidModeMinorVersion);
printf("XF86VidModeExtension-Version %d.%d\n", vidModeMajorVersion,
vidModeMinorVersion);
XF86VidModeGetAllModeLines(hDC, screen, &modeNum, &modes);
/* save desktop-resolution before switching modes */
deskMode = *modes[0];
/* look for mode with requested resolution */
for (i = 0; i < modeNum; i++)
if ((modes[i]->hdisplay == Width) && (modes[i]->vdisplay == Height))
bestMode = i;
/* get an appropriate visual */
vi = glXChooseVisual(hDC, screen, attrListDbl);
if (vi == NULL)
{
vi = glXChooseVisual(hDC, screen, attrListSgl);
printf("Only Singlebuffered Visual!\n");
}
else
printf("Got Doublebuffered Visual!\n");
glXQueryVersion(hDC, &glxMajorVersion, &glxMinorVersion);
printf("glX-Version %d.%d\n", glxMajorVersion, glxMinorVersion);
/* create a GLX context */
glctx = glXCreateContext(hDC, vi, 0, GL_TRUE);
/* create a color map */
cmap = XCreateColormap(hDC, RootWindow(hDC, vi->screen),
vi->visual, AllocNone);
attr.colormap = cmap;
attr.border_pixel = 0;
if (FL_fullscreen)
{
XF86VidModeSwitchToMode(hDC, screen, modes[bestMode]);
XF86VidModeSetViewPort(hDC, screen, 0, 0);
dpyWidth = modes[bestMode]->hdisplay;
dpyHeight = modes[bestMode]->vdisplay;
printf("Resolution %dx%d\n", dpyWidth, dpyHeight);
XFree(modes);
/* create a fullscreen window */
attr.override_redirect = True;
attr.event_mask = ExposureMask | KeyPressMask | ButtonPressMask |
FocusChangeMask | EnterWindowMask | StructureNotifyMask;
win = XCreateWindow(hDC, RootWindow(hDC, vi->screen),
0, 0, dpyWidth, dpyHeight, 0, vi->depth, InputOutput, vi->visual,
CWBorderPixel | CWColormap | CWEventMask | CWOverrideRedirect,
&attr);
XWarpPointer(hDC, None, win, 0, 0, 0, 0, 0, 0);
XMapRaised(hDC, win);
XGrabKeyboard(hDC, win, True, GrabModeAsync,
GrabModeAsync, CurrentTime);
XGrabPointer(hDC, win, True, ButtonPressMask,
GrabModeAsync, GrabModeAsync, win, None, CurrentTime);
}
else
{
/* create a window in window mode*/
attr.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask |
PointerMotionMask | FocusChangeMask | StructureNotifyMask;
win = XCreateWindow(hDC, RootWindow(hDC, vi->screen),
0, 0, Width, Height, 0, vi->depth, InputOutput, vi->visual,
CWBorderPixel | CWColormap | CWEventMask, &attr);
/* only set window title and handle wm_delete_events if in windowed mode */
wmDelete = XInternAtom(hDC, "WM_DELETE_WINDOW", True);
XSetWMProtocols(hDC, win, &wmDelete, 1);
XSetStandardProperties(hDC, win, Title,
Title, None, NULL, 0, NULL);
XMapRaised(hDC, win);
}
/* connect the glx-context to the window */
glXMakeCurrent(hDC, win, glctx);
XGetGeometry(hDC, win, &winDummy, &x, &y,
&Width, &Height, &borderDummy, &depth);
printf("Depth %d\n", depth);
if (glXIsDirect(hDC, glctx))
printf("Congrats, you have Direct Rendering!\n");
else
printf("Sorry, no Direct Rendering possible!\n");
GLenum err = glewInit();
if (GLEW_OK != err)
{
/* Problem: glewInit failed, something is seriously wrong. */
printf("GLEW error: %s", glewGetErrorString(err));
}
OnCreate();
this->Resize(Width, Height);
return true;
}
void GLWindow::Dispose()
{
if (glctx)
{
if (!glXMakeCurrent(hDC, None, NULL))
printf("Could not release drawing context.\n");
glXDestroyContext(hDC, glctx);
}
/* switch back to original desktop resolution if we were in fs */
if (FL_fullscreen)
{
XF86VidModeSwitchToMode(hDC, screen, &deskMode);
XF86VidModeSetViewPort(hDC, screen, 0, 0);
}
if (hDC) XCloseDisplay(hDC);
glctx = NULL;
hDC = NULL;
}
#endif
| [
"dmaciej1@f75eed02-8a0f-11dd-b20b-83d96e936561",
"darekmac@f75eed02-8a0f-11dd-b20b-83d96e936561"
]
| [
[
[
1,
128
],
[
136,
162
]
],
[
[
129,
135
]
]
]
|
d913f1740772c302c6f30fc65cbb57efc74b87b7 | c2d3b2484afb98a6447dfacfe733b98e8778e0a9 | /src/3D/SETexture.cpp | c1b2ae68ee18b1df1e8988a68945fc64c0c8d5a2 | []
| no_license | soniccat/3dEngine | cfb73af5c9b25d61dd77e882a31f4a62fbd3f036 | abf1d49a1756fb0217862f829b1ec7877a59eaf4 | refs/heads/master | 2020-05-15T07:07:22.751350 | 2010-03-27T13:05:38 | 2010-03-27T13:05:38 | 469,267 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,566 | cpp | #include "SETexture.h"
#include "SESceneLoader.h"
#include "SETools.h"
#include "SEImageLoader.h"
SETexture::SETexture(void)
{
id = -1;
}
SETexture::~SETexture(void)
{
if( id != -1 )
glDeleteTextures(1, &id);
}
void SETexture::Init( const SEImagePtr image )
{
SEAssert( id == -1, "recreate now not support");
mImage = image;
glGenTextures( 1, &id );
glBindTexture(GL_TEXTURE_2D, id );
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D( GL_TEXTURE_2D,
0,
image->pixelFormat(),
image->width(),
image->height(),
0,
image->pixelFormat(),
image->pixelDataType(),
image->data().get() );
}
void SETexture::Use()
{
glBindTexture(GL_TEXTURE_2D, id );
}
void SETexture::ParseData( SESceneLoader* loader )
{
switch( loader->validValueCount() )
{
case 1:
if( streq( loader->dataType(), "end") )
{
loader->PopDelegate();
}
break;
case 2:
if( streq( loader->dataType(), "path") )
{
SEImageLoader imageLoader;
SEPath path = loader->currentPath()->ParentPath();
path.AppendName( loader->value1() );
SEImagePtr image = imageLoader.Load( path.cString() );
Init( image );
}
break;
}
} | [
"[email protected]",
"ALEX@.(none)"
]
| [
[
[
1,
70
]
],
[
[
71,
71
]
]
]
|
008c5476a158eb357a9adcebf7a52023cd5024d4 | 58ef4939342d5253f6fcb372c56513055d589eb8 | /LemonTangram2/source/TangImage/src/TangImageManager.cpp | cf2eb943a7cb5a81ebbf3718cff61bf52a35782d | []
| 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 | UTF-8 | C++ | false | false | 11,128 | cpp | /*
============================================================================
Name : TangImageManager.cpp
Author : zengcity
Version : 1.0
Copyright : Your copyright notice
Description : CTangImageManager implementation
============================================================================
*/
#include <stdlib.h>
#include <eikenv.h>
#include <BAUTILS.H>
#include "TangImageManager.h"
#include <LemonTangram.mbg>
#include <LemonTangram.rsg>
#include "ImageElement.h"
#include "MacroUtil.h"
#include "TangImageDataReader.h"
#include "TangImageDataWriter.h"
#include "ImageRotator.h"
#include "TangElementUtil.h"
#include "Utils.h"
#include "TangImageSave.h"
#include "QueryDlgUtil.h"
#include "TangFileDefine.h"
#include "Configuration.h"
#include "ConfigDefine.h"
#include "TangErrDefine.h"
#include "LemonTangramAppUi.h"
#include "AlphaBackground.h"
#include "Slideshow.h"
#include "TangImageData.h"
CTangImageManager::CTangImageManager() :
iSelectedState(ESelectedStateChoose),
iDataArray(NULL),iScreenSave(NULL),
iElements(NULL),iAcceleration(0),
iScrollX(0),iScrollY(0)
{
// No implementation required
}
CTangImageManager::~CTangImageManager()
{
SAFE_DELETE(iRender);
SAFE_DELETE(iScreenSave);
SAFE_DELETE(iDataArray);
SAFE_DELETE(iImageData);
}
CTangImageManager* CTangImageManager::NewLC()
{
CTangImageManager* self = new (ELeave)CTangImageManager();
CleanupStack::PushL(self);
self->ConstructL();
return self;
}
CTangImageManager* CTangImageManager::NewL()
{
CTangImageManager* self=CTangImageManager::NewLC();
CleanupStack::Pop(); // self;
return self;
}
void CTangImageManager::ConstructL()
{
iImageData = CTangImageData::NewL();
iElements = iImageData->GetElements();
}
void CTangImageManager::InitOpenGL(CCoeControl* aParentControl, RWindow* aParentWindow)
{
iRender = CSlideshow::NewL(aParentControl,aParentWindow);
iRender->SetRedererState();
iRender->SetImageData(iImageData);
}
void CTangImageManager::LoadImageDataFileL(const TDesC& aFileName)
{
if (!iDataArray)
iDataArray = CTangImageDataReader::NewL(iElements);
iDataArray->LoadImageDataFileL(aFileName);
}
void CTangImageManager::Draw(CBitmapContext& /*aGc*/) const
{
if (iRender)
{
if ( iRender->GetState() != CSlideshow::ELoadingTextures )
iRender->Render();
}
}
TKeyResponse CTangImageManager::OfferKeyEventL(const TKeyEvent& aKeyEvent,
TEventCode aType)
{
if (iSelectedState == ESelectedStateChoose)
{
return KeyChoose(aKeyEvent, aType);
}
else
if (iSelectedState == ESelectedStateMove)
{
return KeyMove(aKeyEvent, aType);
}
return EKeyWasNotConsumed;
}
TKeyResponse CTangImageManager::KeyChoose(const TKeyEvent& aKeyEvent,
TEventCode aType)
{
TInt index;
TInt iSelectedIndex = iImageData->GetSelected();
switch (aType)
{
case EEventKeyUp:
switch (aKeyEvent.iScanCode)
{
case '2'://up
case EStdKeyUpArrow://
index = TangElementUtil::FindNearestVert(iElements,
iSelectedIndex,EMoveNorth);
// if (index != iSelectedIndex)
if (1)
{
iImageData->SetSelected(index);
}
return EKeyWasConsumed;
break;
case '8'://down
case EStdKeyDownArrow://ok
index = TangElementUtil::FindNearestVert(iElements,
iSelectedIndex,EMoveSouth);
// if (index != iSelectedIndex)
if (1)
{
iImageData->SetSelected(index);
}
return EKeyWasConsumed;
break;
case '4'://left
case EStdKeyLeftArrow://ok
index = TangElementUtil::FindNearestHori(iElements,
iSelectedIndex,EMoveWest);
// if (index != iSelectedIndex)
if (1)
{
iImageData->SetSelected(index);
}
return EKeyWasConsumed;
break;
case '6'://right
case EStdKeyRightArrow://ok
index = TangElementUtil::FindNearestHori(iElements,
iSelectedIndex,EMoveEast);
// if (index != iSelectedIndex)
if (1)
{
iImageData->SetSelected(index);
}
return EKeyWasConsumed;
break;
case '5':
case EStdKeyDevice3:
iSelectedState = ESelectedStateMove;
return EKeyWasConsumed;
break;
}
break;
case EEventKey:
return KeyScroll(aKeyEvent);
break;
}
return EKeyWasNotConsumed;
}
TKeyResponse CTangImageManager::KeyMove(const TKeyEvent& aKeyEvent,
TEventCode aType)
{
TInt x,y;
TInt iSelectedIndex = iImageData->GetSelected();
x = iElements[iSelectedIndex]->GetPositionX();
y = iElements[iSelectedIndex]->GetPositionY();
switch (aType)
{
case EEventKey:
switch (aKeyEvent.iCode)
{
case '2'://up
case EKeyUpArrow://
y += OffsetAccel();
iElements[iSelectedIndex]->SetPointion(x,y);
return EKeyWasConsumed;
break;
case '8'://down
case EKeyDownArrow://ok
y -= OffsetAccel();
iElements[iSelectedIndex]->SetPointion(x,y);
return EKeyWasConsumed;
break;
case '4'://left
case EKeyLeftArrow://ok
x -= OffsetAccel();
iElements[iSelectedIndex]->SetPointion(x,y);
return EKeyWasConsumed;
break;
case '6'://right
case EKeyRightArrow://ok
x += OffsetAccel();
iElements[iSelectedIndex]->SetPointion(x,y);
return EKeyWasConsumed;
break;
case '*':
Rotate(iSelectedIndex,OffsetDegreeAccel());
return EKeyWasConsumed;
break;
case '#':
Rotate(iSelectedIndex,-OffsetDegreeAccel());
return EKeyWasConsumed;
break;
default:
return KeyScroll(aKeyEvent);
break;
}
break;
case EEventKeyUp:
switch (aKeyEvent.iScanCode)
{
case '2'://up
case EStdKeyUpArrow://
case '8'://down
case EStdKeyDownArrow://ok
case '4'://left
case EStdKeyLeftArrow://ok
case '6'://right
case EStdKeyRightArrow://ok
ResetAccel();
return EKeyWasConsumed;
break;
case EStdKeyNkpAsterisk:
case EStdKeyHash:
ResetDegreeAccel();
return EKeyWasConsumed;
break;
case '0':
Flip(iSelectedIndex);
return EKeyWasConsumed;
break;
case '5':
case EStdKeyDevice3:
iSelectedState = ESelectedStateChoose;
return EKeyWasConsumed;
break;
}
break;
}
return EKeyWasNotConsumed;
}
TKeyResponse CTangImageManager::KeyScroll(const TKeyEvent& aKeyEvent)
{
switch (aKeyEvent.iScanCode)
{
case '3':
//if (iScrollX > 0)
iScrollX -= TANGRAM_SCROLL_MOVE;
return EKeyWasConsumed;
break;
case '1':
iScrollX += TANGRAM_SCROLL_MOVE;
return EKeyWasConsumed;
break;
case '9':
//if (iScrollY > 0)
iScrollY -= TANGRAM_SCROLL_MOVE;
return EKeyWasConsumed;
break;
case '7':
iScrollY += TANGRAM_SCROLL_MOVE;
return EKeyWasConsumed;
break;
}
return EKeyWasNotConsumed;
}
TInt CTangImageManager::OffsetAccel(/*EImageElementState aDirection*/)
{
if (iAcceleration < TANGRAM_ELEMENT_MAX_ACCELERATION) {
iAcceleration++;
}
return TANGRAM_ELEMENT_MOVE + iAcceleration;
}
void CTangImageManager::ResetAccel()
{
iAcceleration = 0;
}
TInt CTangImageManager::OffsetDegreeAccel(/*EImageElementState aDirection*/)
{
if (iDegreeAcceleration < TANGRAM_ELEMENT_MAX_ROTATOE_ACCELERATION) {
iDegreeAcceleration += TANGRAM_ELEMENT_OFFSET_ROTATOE_ACCELERATION;
}
return iDegreeAcceleration;
}
void CTangImageManager::ResetDegreeAccel()
{
iDegreeAcceleration = 0;
}
void CTangImageManager::Rotate(TInt aIndex, TInt aDegree)
{
CImageElement* element = iElements[aIndex];
int degree = element->GetDegree();
degree += aDegree;
TBool flip = element->GetFlip();
element->SetDegree(degree);
if (flip) {
degree = -degree;
}
}
void CTangImageManager::Flip(TInt aIndex)
{
CImageElement* element = iElements[aIndex];
int degree = element->GetDegree();
TBool flip = element->GetFlip();
flip = !flip;
element->SetFlip(flip);
}
void CTangImageManager::SaveProcessL()
{
if (ShowConfirmationQueryL(R_TEXT_DLG_CONFIRM_SAVE_PROGRESS))
{
TInt wait = StartWaitingDlg(R_TEXT_DLG_SAVE_PROGRESS);
CTangImageDataWriter* writer = CTangImageDataWriter::NewLC(iElements);
TFileName file;
GetAppPath(file);
file.Append(KSaveProcessFile);
writer->SaveDataToFile(file);
CleanupStack::PopAndDestroy(writer);
EndWaitingDlg(wait);
ShowInfomationDlgL(R_TEXT_DLG_SAVE_PROGRESS_SUCCESS);
}
}
void CTangImageManager::ResetProcessL()
{
if (ShowConfirmationQueryL(R_TEXT_DLG_CONFIRM_RESET_PROGRESS))
{
TInt wait = StartWaitingDlg(R_TEXT_DLG_RESET_PROGRESS);
TFileName path;
GetAppPath(path);
path.Append(KFileTangram);
LoadImageDataFileL(path);
EndWaitingDlg(wait);
}
}
void CTangImageManager::OpenProcessL()
{
if (ShowConfirmationQueryL(R_TEXT_DLG_CONFIRM_OPEN_PROGRESS))
{
TInt wait = StartWaitingDlg(R_TEXT_DLG_OPEN_PROGRESS);
TFileName file;
GetAppPath(file);
file.Append(KSaveProcessFile);
LoadImageDataFileL(file);
EndWaitingDlg(wait);
}
}
void CTangImageManager::SaveScreenL()
{
TBuf<KMaxName> name;
name.Copy(KSaveScreenDefault);
if (ShowInputDlgL(R_TEXT_DLG_SAVE_SCREEN_INPUT_NAME,name))
{
TFileName setup;
GetAppPath(setup);
setup.Append(KSetupSaveFile);
CConfiguration* config = CConfiguration::NewL(setup);
TFileName file;
config->Get(KCfgSaveFolder,file);
delete config;
file.Append(name);
file.Append(KSaveScreenFormat);
if (!BaflUtils::FileExists(CCoeEnv::Static()->FsSession(),file) ||
ShowConfirmationQueryL(R_TEXT_DLG_OVERWRITE_FILE))
{
iWaitDlgId = StartWaitingDlg(R_TEXT_DLG_SAVE_SCREEN);
SAFE_DELETE(iScreenSave);
iScreenSave = CTangImageSave::NewL(file,this);
Draw(iScreenSave->CreateBufferBitmapL());
iScreenSave->StartSave();
}
}
}
void CTangImageManager::SaveScreenL(CFbsBitmap *aBitmap)
{
TBuf<KMaxName> name;
name.Copy(KSaveScreenDefault);
if (ShowInputDlgL(R_TEXT_DLG_SAVE_SCREEN_INPUT_NAME,name))
{
TFileName setup;
GetAppPath(setup);
setup.Append(KSetupSaveFile);
CConfiguration* config = CConfiguration::NewL(setup);
TFileName file;
config->Get(KCfgSaveFolder,file);
delete config;
file.Append(name);
file.Append(KSaveScreenFormat);
if (!BaflUtils::FileExists(CCoeEnv::Static()->FsSession(),file) ||
ShowConfirmationQueryL(R_TEXT_DLG_OVERWRITE_FILE))
{
iWaitDlgId = StartWaitingDlg(R_TEXT_DLG_SAVE_SCREEN);
SAFE_DELETE(iScreenSave);
iScreenSave = CTangImageSave::NewL(file,this);
iScreenSave->StartSave(aBitmap);
}
}
}
void CTangImageManager::SaveComplete()
{
EndWaitingDlg(iWaitDlgId);
ShowInfomationDlgL(R_TEXT_DLG_SAVE_SCREEN_SUCCESS);
}
TInt CTangImageManager::GetConvertDown()
{
return iRender->GetState() == CSlideshow::ERunning;
}
| [
"zengcity@415e30b0-1e86-11de-9c9a-2d325a3e6494"
]
| [
[
[
1,
459
]
]
]
|
a37a6f55c50397c475ea539b71a7cff61ec40fc5 | 208475bcab65438eed5d8380f26eacd25eb58f70 | /QianExe/yx_DrvRecRpt.cpp | d7fd1bb5b6959d93931353a0d351d3aa07b18b5f | []
| no_license | awzhang/MyWork | 83b3f0b9df5ff37330c0e976310d75593f806ec4 | 075ad5d0726c793a0c08f9158080a144e0bb5ea5 | refs/heads/master | 2021-01-18T07:57:03.219372 | 2011-07-05T02:41:55 | 2011-07-05T02:46:30 | 15,523,223 | 1 | 2 | null | null | null | null | GB18030 | C++ | false | false | 48,376 | cpp | #include "yx_QianStdAfx.h"
#include "yx_DrvRecRpt.h"
#if USE_DRVRECRPT == 1 || USE_DRVRECRPT == 2 || USE_DRVRECRPT == 3 || USE_DRVRECRPT == 4 || USE_DRVRECRPT == 11
#undef MSG_HEAD
#define MSG_HEAD ("QianExe-DrvRec ")
const UINT DRVRECWIN_REUPLOAD_INTERVAL = 30000; // 行驶记录窗口重传间隔,ms
const DWORD DRVWINSNDMAXPERIOD_FSTCHKGPRS = DRVRECWIN_REUPLOAD_INTERVAL * 3 + 8000; // 行驶记录上传多久之后若没有应答,则要第一次检查GPRS网络,ms
const DWORD DRVWINSNDMAXPERIOD_CHKGPRS = 300000; // 行驶记录上传多久之后若没有应答,第一次检查GPRS网络后仍没有应答,要求底层检查GPRS的间隔,ms
const DWORD CHKDRV_INTERVAL = 1000; // 行驶记录检测间隔,1000ms,勿改动
const DWORD AVGSPEEDSAVE_INTERVAL = 60000; // 多久生成一个平均速度,ms
#if USE_DRVRECRPT == 1 || USE_DRVRECRPT == 11
const BYTE DRVRECFRAME_DATATYPE = 0x45;
#endif
#if USE_DRVRECRPT == 2
const BYTE DRVRECFRAME_DATATYPE = 0x46;
#endif
#if USE_DRVRECRPT == 3
const BYTE DRVRECFRAME_DATATYPE = 0x47;
#endif
#if USE_DRVRECRPT == 4
const BYTE DRVRECFRAME_DATATYPE = 0x48;
#endif
#pragma pack(4)
struct tagAvgSpeed
{
float m_fAvgSpeed; // 米/秒
char m_szDate[3]; // 年月日 (仅用于内存,文件中不存在此项)
char m_szTime[2]; // 时分
};
#pragma pack()
void *G_ThreadDrvRecSample(void *arg)
{
g_objDrvRecRpt.P_ThreadDrvRecSample();
}
void G_TmReRptDrvRecWin(void *arg, int len)
{
g_objDrvRecRpt.P_TmReRptDrvRecWin();
}
void G_TmStopUploadDrvrec(void *arg, int len)
{
g_objDrvRecRpt.P_TmStopUploadDrvrec();
}
CDrvRecRpt::CDrvRecRpt()
{
pthread_mutex_init( &m_MutexDrvRec, NULL );
m_objWaitSndDrvRecMng.InitCfg( QUEUE_WAITSNDDRVREC_SIZE, QUEUE_WAITSNDDRVREC_PERIOD );
memset( &m_objDrvRecSampleCfg, 0, sizeof(m_objDrvRecSampleCfg) );
m_dwDrvCurWinFstSndTime = GetTickCount();
m_bDrvCurWinChkGprs = false;
m_bytCurSndDrvRecFrameNum = 0;
m_bCurSndNeedAns = false;
memset( m_aryCurSndDrvRecFrameInfo, 0, sizeof(m_aryCurSndDrvRecFrameInfo) );
}
CDrvRecRpt::~CDrvRecRpt()
{
pthread_mutex_destroy( &m_MutexDrvRec );
}
int CDrvRecRpt::Init()
{
int iRet = 0;
Release();
// 先启动行驶记录数据采样线程
m_bStopDrvSample = false;
m_bEndDrvSample = false;
m_bForceRptDrv = false;
if( pthread_create(&m_pthreadDrvSample, NULL, G_ThreadDrvRecSample, NULL) != 0 )
{
iRet = ERR_THREAD;
goto INIT_END;
}
// 再开启特定的行驶记录采样
_BeginDrvRecSample( (BOOL)(g_objQianIO.GetDeviceSta() & DEVSTA_ACCVALID) ); // 该函数要在CVeSta对象_Init之后调用
INIT_END:
return iRet;
}
int CDrvRecRpt::Release()
{
m_bEndDrvSample = true;
m_bStopDrvSample = true;
}
void CDrvRecRpt::P_ThreadDrvRecSample()
{
char buf[SOCK_MAXSIZE];
DWORD dwBufLen = 0;
tagDrvSampleDatas objSampleDatas; // 保存的行驶数据集,满发送周期后生成一条行驶记录,然后重新采样行驶数据
tagDrvRecSampleCfg objCurSampleCfg, objNewSampleCfg; // 行驶数据采样的当前配置和新配置
#if USE_DRVRECRPT == 2
tagSampleData_3746 objOneSampleData; // 保存一次采样的行驶数据
tagSampleData_3746* arySampleData = objSampleDatas.m_uniSampleDatas.m_arySampleData_3746;
#endif
#if USE_DRVRECRPT == 3
tagSampleData_3747 objOneSampleData; // 保存一次采样的行驶数据
tagSampleData_3747* arySampleData = objSampleDatas.m_uniSampleDatas.m_arySampleData_3747;
#endif
#if USE_DRVRECRPT == 11
tagSampleData_3745_KJ2 objOneSampleData; // 保存一次采样的行驶数据
tagSampleData_3745_KJ2* arySampleData = objSampleDatas.m_uniSampleDatas.m_arySampleData_3745_KJ2;
#endif
tagGPSData gps(0);
double dLstLon = 0; // 上次循环时记录的经纬度
double dLstLat = 0;
double dDrvDis = 0; // 上次循环->本次循环所行驶的里程
double dCurSavSpdDis = 0; // 本次若需要计算1分钟平均速度时的1分钟内累加里程
double dMeterPerCycle = 0; // 每里程脉冲多少米 (标定值换算得到)
double dAvgSpeed = 0; // 本次循环时生成的平均速度,米/秒
DWORD dwWait = CHKDRV_INTERVAL; // 线程等待时间,必须为该常量值
DWORD dwCur = GetTickCount(); // 不要更改
DWORD dwLstSavSpdTm = dwCur; // 上次保存1分钟平均速度的时刻
DWORD dwLstSavRecTm = dwCur; // 上次采样行驶数据的时刻
DWORD dwDeltTm = 1; // 尽可能防止除0异常
DWORD dwPacketNum = 0; // 推入1条行驶记录到发送队列后得到的队列内记录总数
DWORD dwLstMeterCycle = 0; // 上次循环时读取的里程脉冲总数
DWORD dwCurMeterCycle = 0; // 当前循环时读取的里程脉冲总数
DWORD dwCyclePerSec = 0; // 当前循环时读取的每秒脉冲数
DWORD dwIoSta = 0;
BOOL blResult = FALSE;
WORD wCyclePerKm = 0; // 每公里脉冲数 (标定值)
BYTE bytAvgSpeed = 0; // 本次循环时生成的平均速度,海里/小时
BYTE bytLoopCt = 0; // 必须=0
BYTE bytSta = 0; // 0,初始态; 1,采样态; 2,采样暂停态(第1次检测到); 3,采样暂停态
bool bMeterDone = false;
bool bSpdDone = false;
// 添加行驶数据时的容量限制常量
const DWORD AVGSPD_MAXCOUNT = sizeof(objSampleDatas.m_aryAvgSpeed) / sizeof(objSampleDatas.m_aryAvgSpeed[0]);
const DWORD SAMPLEDATA_MAXCOUNT = sizeof(objSampleDatas.m_uniSampleDatas.m_arySampleData_3746)
/ sizeof(objSampleDatas.m_uniSampleDatas.m_arySampleData_3746[0]);
// 线程循环前的初始化 (重要)
dLstLon = dLstLat = 0;
bytLoopCt = 0;
bytSta = 0;
memset( &objSampleDatas, 0, sizeof(objSampleDatas) );
{
// 读取复位前的最后有效经纬度
double dLichen = 0;
long lLon = 0, lLat = 0;
g_objCarSta.GetLstValidLonlatAndLichen( lLon, lLat, dLichen );
dLstLon = lLon / LONLAT_DO_TO_L;
dLstLat = lLat / LONLAT_DO_TO_L;
#if USE_DRVRECRPT == 2 || USE_DRVRECRPT == 3 || USE_DRVRECRPT == 4
objSampleDatas.m_dDrvDis = dLichen;
#endif
}
// 线程循环处理
while( !m_bEndDrvSample )
{
usleep(dwWait*1000); // 固定的循环间隔
// (1)每次循环前的初始化
dwCur = GetTickCount();
dwDeltTm = 1000; // 初始化尽可能防止除0异常
bytAvgSpeed = 0;
memset( &objOneSampleData, 0, sizeof(objOneSampleData) );
memset( &gps, 0, sizeof(gps) );
GetCurGps( &gps, sizeof(gps), GPS_REAL ); // 获取GPS实时数据
// (重要) 若ACC无效,强制设为无效GPS,使得后面不参与里程统计,不更新为下次循环时使用的“上次有效位置”
if( !(g_objQianIO.GetDeviceSta() & DEVSTA_ACCVALID) )
gps.valid = 'V';
else
{
// 第一次获取到有效GPS时,要与Flash中记录的最后有效位置进行比较,偏移10km以上,则Flash中的记录不使用.
static bool sta_bFstJugLstValid = true;
if( sta_bFstJugLstValid && 'A' == gps.valid )
{
if( G_CalGeoDis2(dLstLon, dLstLat, gps.longitude, gps.latitude) > 10000 )
{
dLstLon = dLstLat = 0;
}
sta_bFstJugLstValid = false;
}
}
if( 0 == bytSta ) // 若是初始状态
{
// 清除旧的行驶记录数据,但是保留累积行驶里程 (重要)
double dDis = objSampleDatas.m_dDrvDis;
memset( &objSampleDatas, 0, sizeof(objSampleDatas) );
objSampleDatas.m_dDrvDis = dDis;
dwLstSavSpdTm = dwLstSavRecTm = dwCur; // 重新初始化各处理时刻
_GetDrvRecSampleCfg( objNewSampleCfg ); // 更新一次采样配置
objCurSampleCfg = objNewSampleCfg; // 当前配置使用最新的配置
}
if( 0 == bytLoopCt % 20 ) // 否则,每20秒
{
#ifdef DIS_SPD_USEIO
// 更新一次标定值 (初始时也在此更新)
GetImpCfg( &wCyclePerKm, sizeof(wCyclePerKm),
offsetof(tagImportantCfg, m_uni1QBiaodingCfg.m_obj1QBiaodingCfg.m_wCyclePerKm), sizeof(wCyclePerKm) );
if( wCyclePerKm > 50 )
{
dMeterPerCycle = 1000.0 / wCyclePerKm; // 注意保证wCyclePerKm大于0,以防止除0异常
}
else
{
dMeterPerCycle = 0;
}
#endif
// 若是采样态,则更新一次采样配置
if( 1 == bytSta ) _GetDrvRecSampleCfg( objNewSampleCfg );
}
// (2)更新当前状态
if( !m_bStopDrvSample ) // 若不需要中止采样
{
switch( bytSta )
{
case 0:
case 1:
bytSta = 1; // 采样态
break;
case 2: // 第一次暂停态
case 3: // 完全暂停态
default:
bytSta = 0; // 初始态
}
}
else
{
m_bStopDrvSample = false;
// 判断是否第一次暂停
switch( bytSta )
{
case 2:
case 3:
bytSta = 3;
break;
default:
bytSta = 2;
}
}
// (3)计算自上次循环到现在的里程
dDrvDis = 0;
#ifdef DIS_SPD_USEIO
bMeterDone = false;
// 先使用里程脉冲
blResult = g_objQianIO.IN_QueryMeterCycle( dwCurMeterCycle );
if( blResult )
{
if( dMeterPerCycle > 0.01 ) // 若标定值有效
{
dDrvDis = (dwCurMeterCycle - dwLstMeterCycle) * dMeterPerCycle;
bMeterDone = true;
}
dwLstMeterCycle = dwCurMeterCycle;
}
#endif
// 从里程脉冲获取失败,再考虑GPS
if( !bMeterDone && 'A' == gps.valid && dLstLon > 0.0001 && dLstLat > 0.0001 )
// 若上次经纬度有效,且本次GPS有效(此时ACC有效,因为前面的代码在ACC无效时把GPS也置为无效了)
{
dDrvDis = G_CalGeoDis2( dLstLon, dLstLat, gps.longitude, gps.latitude );
}
// 现在更新上次位置 (dLstLon、dLstLat在本次循环的后面不用了)
if( 'A' == gps.valid )
// 当前GPS有效,且ACC有效时
{
dLstLon = gps.longitude;
dLstLat = gps.latitude;
static DWORD sta_dwCt = 0;
if( 0 == ++ sta_dwCt % 600 ) // ACC有效和GPS有效状态下,每10分钟,保存一次最后有效位置,以最大可能确保里程累加准确
{
g_objCarSta.SavLstValidLonlatAndLichen(
long(gps.longitude * LONLAT_DO_TO_L),
long(gps.latitude * LONLAT_DO_TO_L),
objSampleDatas.m_dDrvDis );
// 让主线程做文件的写入工作
QIANMSG msg;
msg.m_lMsgType = MSG_SAVRECSTA;
if( msgsnd(g_MsgID, (void*)&msg, MSG_MAXLEN, 0) == -1 )
perror("send MSG_SAVRECSTA faile:");
else
PRTMSG(MSG_DBG, "send MSG_SAVRECSTA\n");
}
}
// (4)累加行驶里程
objSampleDatas.m_dDrvDis += dDrvDis;
// (5)判断是否要采样
if( 1 == bytSta || 2 == bytSta ) // 若是采样态或是第一次暂停采样态
{
// (5_1)判断是否达到采样周期,达到则要生成1条行驶数据
dwDeltTm = dwCur - dwLstSavRecTm;
if( objCurSampleCfg.m_wSampleCycle > 0 // 若需要采样
&&
dwDeltTm >= objCurSampleCfg.m_wSampleCycle * DWORD(1000) ) // 且达到采样周期
{
if( dwDeltTm < 1 ) dwDeltTm = 1; // 防止除0错误
// 生成1条行驶数据
objOneSampleData.m_bytYear = BYTE(gps.nYear % 1000);
objOneSampleData.m_bytMon = BYTE(gps.nMonth);
objOneSampleData.m_bytDay = BYTE(gps.nDay);
objOneSampleData.m_bytHour = BYTE(gps.nHour);
objOneSampleData.m_bytMin = BYTE(gps.nMinute);
objOneSampleData.m_bytSec = BYTE(gps.nSecond);
{
WORD wCurDriverNo = g_objCarSta.GetDriverNo();
objOneSampleData.m_szDriverNo[0] = BYTE(wCurDriverNo / 0x100 );
objOneSampleData.m_szDriverNo[1] = BYTE(wCurDriverNo % 0x100 );
}
#ifdef DIS_SPD_USEIO
bSpdDone = false;
// 先通过里程脉冲
if( dMeterPerCycle > 0.01 ) // 若标定值有效
{
if( g_objQianIO.IN_QueryIOSpeed(dwCyclePerSec) )
{
objOneSampleData.m_bytSpeed = BYTE(dwCyclePerSec * dMeterPerCycle * MIMIAO_TO_HAIHOUR);
bSpdDone = true;
}
}
// 失败再使用GPS
if( !bSpdDone )
{
objOneSampleData.m_bytSpeed = BYTE(gps.speed * MIMIAO_TO_HAIHOUR);
}
#else
objOneSampleData.m_bytSpeed = BYTE(gps.speed * MIMIAO_TO_HAIHOUR);
#endif
objOneSampleData.m_bytDir = BYTE(gps.direction / 3) + 1;
g_objQianIO.IN_QueryIOSta( dwIoSta );
objOneSampleData.m_bytIO = ~BYTE(dwIoSta % 0x100);
#if USE_DRVRECRPT == 1 || USE_DRVRECRPT == 2 || USE_DRVRECRPT == 4
if( g_objCarSta.GetVeSta() & VESTA_HEAVY )
objOneSampleData.m_bytIO |= 0x08;
else
objOneSampleData.m_bytIO &= 0xf7;
#endif
// 获取状态信息
{
// 协议定义:
// 状态字:H7 H6 H5 H4 H3 H2 H1 H0
// L7 L6 L5 L4 L3 L2 L1 L0
// H0:GPRS在线情况 0不在线 1在线
// H1:发生碰撞 0 无碰撞 1 碰撞
// H2:发生侧翻 0无侧翻 1 侧翻
// H3:欠压状态 0 无欠压 1欠压
// H4:主电断电状态 0 主电未断电 1主电断电
// H5:抢劫报警状态 0无抢劫报警 1发生抢劫报警
// H6:非法启动状态 0 无非法启动 1 发生非法启动
// H7:保留
//
// L1、L0经纬度坐标:
// 0 东经北纬 1 东经南纬 2 西经北纬 3 西经南纬
// L3、L2 GPS模块定位状态:
// 0:未定位 1:2D定位 2:3D定位 3 保留
// L5、L4 GPS模块工作状态:
// 0:正常 1:省电 2:通讯异常 3 保留
// L6、L7 保留
// 其他位保留待定,设置为0。
DWORD dwAlertSta = g_objMonAlert.GetAlertSta();
DWORD dwDevSta = g_objQianIO.GetDeviceSta();
BYTE bytH = 0, bytL = 0;
if( g_objSock.IsOnline() ) bytH |= 0x01; // 网络在线情况
if( dwAlertSta & ALERT_TYPE_BUMP ) bytH |= 0x02; // 碰撞报警
if( dwAlertSta & ALERT_TYPE_OVERTURN ) bytH |= 0x04; // 侧翻报警
if( dwAlertSta & ALERT_TYPE_POWBROWNOUT ) bytH |= 0x08; // 欠压状态
if( dwAlertSta & ALERT_TYPE_POWOFF ) bytH |= 0x10; // 断电状态
if( dwAlertSta & ALERT_TYPE_FOOT ) bytH |= 0x20; // 抢劫报警
if( dwAlertSta & ALERT_TYPE_DRIVE ) bytH |= 0x40; // 非法启动报警
bytL |= 0; // 暂时都强制使用"东经北纬"
if( '3' == gps.m_cFixType ) bytL |= 0x08; // 定位类型
else if( '2' == gps.m_cFixType ) bytL |= 0x04;
else bytL |= 0;
if( dwDevSta & DEVSTA_GPSON ) bytL |= 0; // GPS模块状态
else bytL |= 0x10;
objOneSampleData.m_bytSta1 = bytH;
objOneSampleData.m_bytSta2 = bytL;
}
G_Lonlat_DTo4Char( gps.longitude, objOneSampleData.m_szLon);
G_Lonlat_DTo4Char( gps.latitude, objOneSampleData.m_szLat);
#if USE_DRVRECRPT == 2 || USE_DRVRECRPT == 3
// 协议定义
// bit7~Bit0: 0表示无效,1表示有效
// Bit0: 碰撞检测位
// Bit1:侧翻检测位
// Bit2:欠压检测位
// Bit3:断电检测位
// Bit4:抢劫按钮检测位
// (不保险,放弃) objOneSampleData.m_bytAlertIO = BYTE( ~(dwIoSta >> 9) & 0x1f ); // 根据驱动返回值定义和协议定义,可这样快速处理
objOneSampleData.m_bytAlertIO = 0;
if( !(dwIoSta & 0x200) ) objOneSampleData.m_bytAlertIO |= 0x01; //碰撞IO
if( !(dwIoSta & 0x400) ) objOneSampleData.m_bytAlertIO |= 0x02; //侧翻IO
if( !(dwIoSta & 0x800) ) objOneSampleData.m_bytAlertIO |= 0x04; //欠压IO
if( dwIoSta & 0x1000 ) objOneSampleData.m_bytAlertIO |= 0x08; //断电IO
if( dwIoSta & 0x2000 ) objOneSampleData.m_bytAlertIO |= 0x10; //抢劫IO
objOneSampleData.m_bytHeightCount = 0; // 暂时不考虑载重传感器
memset( objOneSampleData.m_aryHeightIO, 0, sizeof(objOneSampleData.m_aryHeightIO) ); // 传感器数据暂清0
#endif
#if USE_DRVRECRPT == 11
objOneSampleData.m_bytPDop = BYTE(gps.m_bytPDop);
objOneSampleData.m_bytHDop = BYTE(gps.m_bytHDop);
objOneSampleData.m_bytVDop = BYTE(gps.m_bytVDop);
#endif
// 保存行驶数据
if( objSampleDatas.m_bytSampleDataCount < SAMPLEDATA_MAXCOUNT ) // 保险起见
{
arySampleData[ objSampleDatas.m_bytSampleDataCount ++ ]
= objOneSampleData;
}
dwLstSavRecTm = dwCur; // 更新上次采样行驶数据的时刻
}
// (5_2)累加平均速度计算周期内的里程,并判断是否要生成平均速度
dCurSavSpdDis += dDrvDis;
dwDeltTm = dwCur - dwLstSavSpdTm;
if( dwDeltTm >= AVGSPEEDSAVE_INTERVAL ) // 若距离上次计算平均速度的时间达到了计算周期
{
if( dwDeltTm < 1 ) dwDeltTm = 1; // 防止除0错误
// 生成1分钟平均速度并保存
dAvgSpeed = dCurSavSpdDis / (dwDeltTm / 1000.0);
bytAvgSpeed = BYTE(dAvgSpeed * MIMIAO_TO_HAIHOUR);
//if( objSampleDatas.m_bytAvgSpeedCount < AVGSPD_MAXCOUNT ) // 保险起见
{
objSampleDatas.m_aryAvgSpeed[ objSampleDatas.m_bytAvgSpeedCount ++ ] = bytAvgSpeed;
}
dCurSavSpdDis = 0; // 清零平均速度累加里程
dwLstSavSpdTm = dwCur; // 更新上次平均速度生成时刻
}
}
// (6)判断是否要生成一条行驶记录帧
if( objCurSampleCfg.m_bytSndCycle > 0 ) // 若要发送
{
// 判断是否要强制组帧并发送
bool bForceMakeWin =
2 == bytSta // 第1次暂停采样态
||
m_bForceRptDrv // 或 外部请求立刻生成
||
(objNewSampleCfg.m_wSampleCycle != objCurSampleCfg.m_wSampleCycle
|| objNewSampleCfg.m_bytSndCycle != objCurSampleCfg.m_bytSndCycle
|| objNewSampleCfg.m_bytSndWinSize != objCurSampleCfg.m_bytSndWinSize); // 或 配置要发生更改
if( m_bForceRptDrv == true ) m_bForceRptDrv = false;
if( objSampleDatas.m_bytSampleDataCount >= objCurSampleCfg.m_bytSndCycle // 若到达发送周期
|| bForceMakeWin ) // 或是需要强行组帧并发送
{
#if USE_DRVRECRPT == 3 || USE_DRVRECRPT == 11
#if USE_DRVRECRPT == 3
const double OIL_MVESPD = 1.852 * 2 / 3.6; // 米/秒
#endif
#if USE_DRVRECRPT == 11
const double OIL_MVESPD = 15 / 3.6; // 米/秒
#endif
// 获取当前相关状态
static bool sta_bAccValid = true;
bool bGpsValid = gps.valid == 'A' ? true : false;
bool bAccValid = g_objQianIO.GetDeviceSta() & DEVSTA_ACCVALID ? true : false;
#if USE_OIL == 1
// 确定油耗状态
#if USE_DRVRECRPT == 3
// 千里眼协议: 油耗值的状态 1 D7~D0,表示油耗采样时的状态 (以下各种状态只有一位有效)
// D0:0正常行驶,1车辆点火
// D1:0表示正常,1 GPS定位且速度大于2海里/小时
// D2:0表示定位,1不定位
// D3:0表示正常,1 GPS定位且速度小于2海里/小时
// D4:0表示正常,1停车(ACC无效)或ACC有效仪表盘却没有上电
// D5:0表示正常,1油耗盒没接
// D6:0表示正常,1油耗值不在设置范围内(即值无效)
// 部分信号不能采集,不处理
if( !bAccValid ) objSampleDatas.m_bytOilSta = 0x10;
else if( !bGpsValid ) objSampleDatas.m_bytOilSta = 0x04;
else
{
if( gps.speed >= OIL_MVESPD ) objSampleDatas.m_bytOilSta = 0x02;
else objSampleDatas.m_bytOilSta = 0x08;
}
#endif
#if USE_DRVRECRPT == 11
// 2客协议
// D7~D0,表示油耗采样时的状态
// 0x01: 点火 (事件触发)
// 0x02: 已通电,已定位,速度>15
// 0x04: 已通电,未定位
// 0x08: 已通电,已定位,速度>15
// 0x10: 数据无效的,未通电
if( !bAccValid ) objSampleDatas.m_bytOilSta = 0x10;
else if( bAccValid && !sta_bAccValid ) objSampleDatas.m_bytOilSta = 0x01;
else if( bAccValid && !bGpsValid ) objSampleDatas.m_bytOilSta = 0x04;
else if( bAccValid && bGpsValid && gps.speed >= OIL_MVESPD ) objSampleDatas.m_bytOilSta = 0x02;
else if( bAccValid && bGpsValid && gps.speed < OIL_MVESPD ) objSampleDatas.m_bytOilSta = 0x08;
#endif
#endif
// 获取油耗值
BOOL blGetOilSucc = FALSE; // 初始化为获取失败
// if( bAccValid )
// {
#if USE_OIL == 1
blGetOilSucc = g_objQianIO.IN_QueryOil( objSampleDatas.m_bytOilAD, objSampleDatas.m_bytPowAD );
#endif
#if USE_OIL == 2
blGetOilSucc = g_objOil.GetOilPowAndSta( &objSampleDatas.m_bytOilAD,
&objSampleDatas.m_bytPowAD, &objSampleDatas.m_bytOilSta );
#endif
// }
if( blGetOilSucc )
{
#if USE_OIL == 1
// 保存最新状态
g_objCarSta.SavOil( objSampleDatas.m_bytOilAD, objSampleDatas.m_bytPowAD, objSampleDatas.m_bytOilSta );
#endif
}
else
{
// 提取状态中保存的上次有效油耗数据
g_objCarSta.GetOil( &objSampleDatas.m_bytOilAD, &objSampleDatas.m_bytPowAD, &objSampleDatas.m_bytOilSta );
}
// 根据油耗配置作调整
{
tag1QBiaoding objBd;
if( !GetImpCfg( &objBd, sizeof(objBd), offsetof(tagImportantCfg, m_uni1QBiaodingCfg.m_obj1QBiaodingCfg), sizeof(objBd) ) )
{
if( objBd.m_bReverse )
{
objSampleDatas.m_bytOilAD = 255 - objSampleDatas.m_bytOilAD; // xun,要反转也仅仅反转油耗AD
}
if( objBd.m_bFiltrate && (objSampleDatas.m_bytOilAD > objBd.m_bytHiVal || objSampleDatas.m_bytOilAD < objBd.m_bytLoVal) )
{
objSampleDatas.m_bytOilSta = 0x40; // 范围无效
}
}
}
// 更新ACC状态记录
sta_bAccValid = bAccValid;
#endif
// 当前行驶数据组成1个行驶记录帧,推入发送队列
if( !_MakeOneDrvrecFrame(objSampleDatas, objCurSampleCfg.m_wSampleCycle, buf, sizeof(buf), dwBufLen) )
// 若组帧成功
{
m_objWaitSndDrvRecMng.PushData(LV8, dwBufLen, buf, dwPacketNum);
PRTMSG(MSG_DBG, "m_objWaitSndDrvRecMng push one frame\n");
}
else // 若不成功
{ // 不作处理 (将丢弃该帧,因为若是内存不足,再缓存没有意义;否则,可能是空数据,也不需要缓存)
}
// 无论是否组帧成功都要通知处理,可能上次组帧后到现在还没有采样过,也是正常
QIANMSG msg;
msg.m_lMsgType = MSG_DRVECDTOSND;
msg.m_uszMsgBuf[0] = (char)(bForceMakeWin ? 1 : 0);
if( msgsnd(g_MsgID, (void*)&msg, MSG_MAXLEN, 0) == -1 )
perror("send MSG_DRVECDTOSND faile:");
else
PRTMSG(MSG_DBG, "send MSG_DRVECDTOSND\n");
double dLeaveDis = 0;
#if USE_DRVRECRPT == 2 || USE_DRVRECRPT == 3
// 保留总里程
dLeaveDis = objSampleDatas.m_dDrvDis;
#endif
#if USE_DRVRECRPT == 1 || USE_DRVRECRPT == 11
// 保留组帧时因为精度原因而"丢失"的里程
dLeaveDis = objSampleDatas.m_dDrvDis - WORD(objSampleDatas.m_dDrvDis);
#endif
// 清除当前采样记录集
memset( &objSampleDatas, 0, sizeof(objSampleDatas) );
// 恢复总里程,或补充组帧时丢失的里程
objSampleDatas.m_dDrvDis = dLeaveDis;
// 生成行驶记录帧后,要更新当前的采样配置 (因为采样配置发生变化时会先把旧的行驶数据生成行驶记录帧)
objCurSampleCfg = objNewSampleCfg;
}
}
// 当前配置使用最新的配置,如果有更新的话
objCurSampleCfg = objNewSampleCfg;
// 修正等待时间 (为了尽可能的确保定时准确)
{
DWORD dwDelt = GetTickCount() - dwCur;
if( dwDelt + 200 < CHKDRV_INTERVAL ) // 至少预留200ms
dwWait = CHKDRV_INTERVAL - dwDelt;
else
dwWait = CHKDRV_INTERVAL;
}
// 递增循环次数
++ bytLoopCt;
}
// 线程退出前,将最后的有效经纬度和总里程保存到状态模块中
g_objCarSta.SavLstValidLonlatAndLichen(
long(dLstLon * LONLAT_DO_TO_L),
long(dLstLat * LONLAT_DO_TO_L),
objSampleDatas.m_dDrvDis );
}
void CDrvRecRpt::P_TmReRptDrvRecWin()
{
_SndDrvrecWin( true );
}
void CDrvRecRpt::P_TmStopUploadDrvrec()
{
_KillTimer(&g_objTimerMng, DRVREC_STOPUPLOAD_TIMER );
_StopDrvRecSample();
}
void CDrvRecRpt::DrvRecToSnd( bool v_bNeedSndWin )
{
#if DRVREC_SNDTYPE == 1
///////// { 方式1: 积满一个窗口才发送
// 若还有未发送完的窗口,则退出发送流程 (此时已由定时器控制重传)
if( !_IsCurSndDrvRecWinEmpty() ) return;
// 以下是没有正在发送的窗口的处理,此时重传定时器应该已经关闭
// 读取配置
tagDrvRecSampleCfg objDrvRecSampleCfg;
_GetDrvRecSampleCfg( objDrvRecSampleCfg );
// 到达发送窗口判断
bool bNeedSndWin = false;
if( v_bNeedSndWin ) bNeedSndWin = true; // 若强制作为一个窗口发送
else if( m_objWaitSndDrvRecMng.GetPacketCount() >= objDrvRecSampleCfg.m_bytSndWinSize ) bNeedSndWin = true;
// 若到达发送窗口
if( bNeedSndWin )
{
// 生成一个新窗口数据
_FillCurSndDrvRecWin();
// 发送一个窗口的数据
_SndDrvrecWin( false );
}
///////// } 方式1: 积满一个窗口才发送
#endif
#if DRVREC_SNDTYPE == 2
///////// { 方式2: 每帧发送,满一个窗口等待应答
static tagDrvRecSampleCfg sta_objDrvRecSampleCfg;
static BYTE sta_bytWinId = 0;
if( m_bytCurSndDrvRecFrameNum < 1 ) // 若此时既没有未传完的旧窗口,也没有发送过新的帧
{
// 刷新配置
_GetDrvRecSampleCfg( sta_objDrvRecSampleCfg );
m_bCurSndNeedAns = sta_objDrvRecSampleCfg.m_bytSndWinSize > 0;
// 保险操作
_KillTimer(&g_objTimerMng, DRVRECWIN_REUPLOAD_TIMER );
}
else if( m_bCurSndNeedAns && m_bytCurSndDrvRecFrameNum >= sta_objDrvRecSampleCfg.m_bytSndWinSize )
// 若当前窗口要可靠传输且正在等待应答
{
return;
}
char buf[ SOCK_MAXSIZE ];
int iBufLen = 0;
char* pSndBuf = NULL;
DWORD dwLen = 0;
DWORD dwPushTm = 0;
int iResult = 0;
BYTE bytLvl = 0;
BYTE bytFillNum = 0;
while( m_bytCurSndDrvRecFrameNum < sta_objDrvRecSampleCfg.m_bytSndWinSize // 若还未发满1个窗口
|| 0 == sta_objDrvRecSampleCfg.m_bytSndWinSize ) // 或不需要可靠传输
{
// 提取一帧数据
if( m_objWaitSndDrvRecMng.PopData( bytLvl, sizeof(buf), dwLen, buf, dwPushTm ) )
{
PRTMSG(MSG_DBG, "m_objWaitSndDrvRecMng pop no data\n");
break;
}
if( dwLen < 1 )
continue;
pSndBuf = new char[dwLen];
if( !pSndBuf ) break;
memcpy( pSndBuf, buf, dwLen );
// 将剩余信息填充完毕,若是可靠传输要缓存,并且若是最后一帧还要打开重传定时器
if( m_bCurSndNeedAns ) // 若需要可靠传输
{
pSndBuf[0] |= 0x42; // 可靠传输
pSndBuf[0] |= sta_bytWinId ? 0x08 : 0; // 窗口标志ID
if( m_bytCurSndDrvRecFrameNum + 1 >= sta_objDrvRecSampleCfg.m_bytSndWinSize ) // 若是本窗口最后1帧
{
pSndBuf[0] |= 0x01; // 最后: 末帧要应答
sta_bytWinId = ~sta_bytWinId; // 更换窗口标志
// 打开重传定时器
_SetTimer(&g_objTimerMng, DRVRECWIN_REUPLOAD_TIMER, DRVRECWIN_REUPLOAD_INTERVAL, G_TmReRptDrvRecWin);
m_dwDrvCurWinFstSndTime = GetTickCount();
m_bDrvCurWinChkGprs = false;
}
pSndBuf[1] = sta_objDrvRecSampleCfg.m_bytSndWinSize; // 窗口大小
pSndBuf[2] = m_bytCurSndDrvRecFrameNum; // 帧序号
// 可靠传输时要缓存已发送帧
if( m_bytCurSndDrvRecFrameNum < sizeof(m_aryCurSndDrvRecFrameInfo) / sizeof(m_aryCurSndDrvRecFrameInfo[0]) )
{
m_aryCurSndDrvRecFrameInfo[m_bytCurSndDrvRecFrameNum][0] = dwLen;
m_aryCurSndDrvRecFrameInfo[m_bytCurSndDrvRecFrameNum][1] = DWORD(pSndBuf);
++ m_bytCurSndDrvRecFrameNum;
}
}
else
{
pSndBuf[0] |= 0x40;
pSndBuf[1] = 0;
pSndBuf[2] = 0;
}
// 立即发送该帧
iResult = g_objSms.MakeSmsFrame( pSndBuf, int(dwLen), 0x37, DRVRECFRAME_DATATYPE,
buf, sizeof(buf), iBufLen, CVT_8TO7 );
if( !iResult )
{
iResult = g_objSock.SOCKSNDSMSDATA( buf, iBufLen, LV8 );
}
}
///////// } 方式2: 每帧发送,满一个窗口等待应答
#endif
}
void CDrvRecRpt::RecStaSav()
{
g_objCarSta.SavDrvRecSta( false );
}
void CDrvRecRpt::_BeginDrvRecSample( BOOL v_blAccOn )
{
// 获取最新配置
tag2QDriveRecCfg objDrvRecCfg;
objDrvRecCfg.Init();
GetSecCfg( &objDrvRecCfg, sizeof(objDrvRecCfg),
offsetof(tagSecondCfg, m_uni2QDriveRecCfg.m_obj2QDriveRecCfg), sizeof(objDrvRecCfg) );
// (1)修改内存中的采样发送配置
tagDrvRecSampleCfg objDrvSampleCfg;
WORD wSndPeriod = 1; // (分钟)
if( v_blAccOn )
{
objDrvSampleCfg.m_wSampleCycle = objDrvRecCfg.m_wOnSampCycle;
objDrvSampleCfg.m_bytSndCycle = objDrvRecCfg.m_bytOnSndCycle;
wSndPeriod = objDrvRecCfg.m_wOnPeriod;
}
else
{
objDrvSampleCfg.m_wSampleCycle = objDrvRecCfg.m_wOffSampCycle;
objDrvSampleCfg.m_bytSndCycle = objDrvRecCfg.m_bytOffSndCycle;
wSndPeriod = objDrvRecCfg.m_wOffPeriod;
}
objDrvSampleCfg.m_bytSndWinSize = objDrvRecCfg.m_bytSndWinSize;
_SetDrvRecSampleCfg( objDrvSampleCfg );
m_bForceRptDrv = true; // 强制生成3745行驶记录帧并上传
// (2)判断是否要进行采样
bool bNeedSample = false;
if( v_blAccOn && (objDrvRecCfg.m_wOnSampCycle > 0 && objDrvRecCfg.m_bytOnSndCycle > 0) )
{
bNeedSample = true;
}
else if( !v_blAccOn && (objDrvRecCfg.m_wOffSampCycle > 0 && objDrvRecCfg.m_bytOffSndCycle > 0) )
{
bNeedSample = true;
}
else
{
bNeedSample = false;
}
if( bNeedSample )
{
m_bStopDrvSample = false;
_KillTimer(&g_objTimerMng, DRVREC_STOPUPLOAD_TIMER );
if( 0xffff != wSndPeriod )
_SetTimer(&g_objTimerMng, DRVREC_STOPUPLOAD_TIMER, DWORD(wSndPeriod) * 60000, G_TmStopUploadDrvrec);
}
else
{
m_bStopDrvSample = true;
}
}
void CDrvRecRpt::_StopDrvRecSample()
{
m_bStopDrvSample = true;
}
void CDrvRecRpt::_GetDrvRecSampleCfg( tagDrvRecSampleCfg &v_objDrvRecSampleCfg )
{
pthread_mutex_lock( &m_MutexDrvRec );
v_objDrvRecSampleCfg = m_objDrvRecSampleCfg;
pthread_mutex_unlock( &m_MutexDrvRec );
}
void CDrvRecRpt::_SetDrvRecSampleCfg( const tagDrvRecSampleCfg &v_objDrvRecSampleCfg )
{
pthread_mutex_lock( &m_MutexDrvRec );
m_objDrvRecSampleCfg = v_objDrvRecSampleCfg;
pthread_mutex_unlock( &m_MutexDrvRec );
}
#if DRVREC_SNDTYPE == 1
bool CDrvRecRpt::_IsCurSndDrvRecWinEmpty()
{
return m_bytCurSndDrvRecFrameNum < 1;
}
// 填充一个窗口的数据,窗口大小根据设置,但是以实际能从队列中读到的为准,并且不超过发送窗口缓冲区的范围
// 如果不是可靠传输,则填充的是一组发送数据,在不超过发送缓冲区的范围内,尽可能多的读取
void CDrvRecRpt::_FillCurSndDrvRecWin()
{
// 保险操作,清除发送状态,实际上进入该函数前发送窗口应该是空的或者该窗口是已发送完毕的
_ClearCurSndDrvRecWin();
// 读取配置,更新当前发送状态
tagDrvRecSampleCfg objDrvSampleCfg;
_GetDrvRecSampleCfg( objDrvSampleCfg );
m_bCurSndNeedAns = objDrvSampleCfg.m_bytSndWinSize > 0 ? true : false;
// 确定本次要处理的帧数(可靠传输时就是一个窗口)
BYTE bytFillNum = 0;
if( m_bCurSndNeedAns )
{
bytFillNum = objDrvSampleCfg.m_bytSndWinSize;
if( bytFillNum > sizeof(m_aryCurSndDrvRecFrameInfo) / sizeof(m_aryCurSndDrvRecFrameInfo[0]) )
bytFillNum = sizeof(m_aryCurSndDrvRecFrameInfo) / sizeof(m_aryCurSndDrvRecFrameInfo[0]); // 保险操作
}
else bytFillNum = 32;
// 队列中的数据填充至当前发送窗口缓冲区
char buf[ SOCK_MAXSIZE ];
BYTE bytLvl = 0;
DWORD dwLen = 0;
DWORD dwPushTm = 0;
char* pTemp = NULL;
for( BYTE byt = 0; byt < bytFillNum; byt ++ )
{
if( m_objWaitSndDrvRecMng.PopData( bytLvl, sizeof(buf), dwLen, buf, dwPushTm ) ) break;
if( dwLen < 1 ) continue;
if( byt < sizeof(m_aryCurSndDrvRecFrameInfo) / sizeof(m_aryCurSndDrvRecFrameInfo[0]) )
{
pTemp = new char[dwLen];
if( !pTemp ) break;
memcpy( pTemp, buf, dwLen );
m_aryCurSndDrvRecFrameInfo[byt][0] = dwLen;
m_aryCurSndDrvRecFrameInfo[byt][1] = DWORD(pTemp);
}
}
// 当前发送的总帧数等于实际填充的帧数
m_bytCurSndDrvRecFrameNum = byt;
}
#endif
void CDrvRecRpt::_ClearCurSndDrvRecWin()
{
for( DWORD dw = 0; dw < sizeof(m_aryCurSndDrvRecFrameInfo) / sizeof(m_aryCurSndDrvRecFrameInfo[0]); dw ++ )
{
delete[] (char*) (m_aryCurSndDrvRecFrameInfo[dw][1]);
}
memset( m_aryCurSndDrvRecFrameInfo, 0, sizeof(m_aryCurSndDrvRecFrameInfo) );
m_bytCurSndDrvRecFrameNum = 0;
m_bCurSndNeedAns = false;
}
int CDrvRecRpt::_MakeOneDrvrecFrame( const tagDrvSampleDatas &v_objDrvSampleDatas, const WORD v_wSampleCycle,
char *const v_szBuf, const size_t v_sizBuf, DWORD &v_dwLen )
{
DWORD dw = 0;
DWORD dwTemp = 0;
WORD wTemp = 0;
BYTE byt = 0;
BYTE bytOilSta = 0;
// 预清除
memset( v_szBuf, 0, v_sizBuf );
v_dwLen = 0;
// 判断是否存在行驶数据
if( v_objDrvSampleDatas.m_bytSampleDataCount < 1 )
{
PRTMSG(MSG_ERR, "no SampleData\n");
return ERR_PAR;
}
// 缓存空间检查
if( v_sizBuf < 1000 ) // 下限为一个估计上的极大值
{
return ERR_SPACELACK;
}
// 生成一帧 (处理油耗标记,然后从里程开始赋值,前面的其他值在发送时赋值)
// 里程
#if USE_DRVRECRPT == 2 || USE_DRVRECRPT == 3 || USE_DRVRECRPT == 4
dwTemp = htonl( DWORD(v_objDrvSampleDatas.m_dDrvDis) );
memcpy( v_szBuf + 3, &dwTemp, 4); // 总里程
dw = 7;
#endif
#if USE_DRVRECRPT == 1 || USE_DRVRECRPT == 11
wTemp = htons( WORD(v_objDrvSampleDatas.m_dDrvDis) );
memcpy( v_szBuf + 3, &wTemp, 2); // 里程
dw = 5;
#endif
// 油耗
#if USE_DRVRECRPT == 3 || USE_DRVRECRPT == 11
bytOilSta = v_objDrvSampleDatas.m_bytOilSta;
#if USE_DRVRECRPT == 11
v_szBuf[ 0 ] |= char( 0x80 ); // 油耗标志位置1
#endif
v_szBuf[ dw ++ ] = char( v_objDrvSampleDatas.m_bytOilAD );
v_szBuf[ dw ++ ] = char( v_objDrvSampleDatas.m_bytPowAD );
v_szBuf[ dw ++ ] = char( bytOilSta );
#endif
// 采样间隔
wTemp = htons( v_wSampleCycle );
memcpy( v_szBuf + dw, &wTemp, 2 );
dw += 2;
// 行驶数据个数
v_szBuf[ dw ++ ] = char( v_objDrvSampleDatas.m_bytSampleDataCount );
// 行驶数据
for( byt = 0; byt < v_objDrvSampleDatas.m_bytSampleDataCount; byt ++ )
{
#if USE_DRVRECRPT == 2
// 基础大小
dwTemp = sizeof(tagSampleData_3746);
// 去除多余的载重字段
if( v_objDrvSampleDatas.m_uniSampleDatas.m_arySampleData_3746[byt].m_bytHeightCount
>
sizeof(v_objDrvSampleDatas.m_uniSampleDatas.m_arySampleData_3746[byt].m_aryHeightIO)
/
sizeof(v_objDrvSampleDatas.m_uniSampleDatas.m_arySampleData_3746[byt].m_aryHeightIO[0]) )
{ // 保险起见
memset( (char*)&v_objDrvSampleDatas.m_uniSampleDatas.m_arySampleData_3746[byt].m_bytHeightCount, 1,
sizeof(v_objDrvSampleDatas.m_uniSampleDatas.m_arySampleData_3746[byt].m_bytHeightCount) );
}
dwTemp -= sizeof(v_objDrvSampleDatas.m_uniSampleDatas.m_arySampleData_3746[byt].m_aryHeightIO)
-
v_objDrvSampleDatas.m_uniSampleDatas.m_arySampleData_3746[byt].m_bytHeightCount
* sizeof(v_objDrvSampleDatas.m_uniSampleDatas.m_arySampleData_3746[byt].m_aryHeightIO[0]);
// 存入发送缓存
if( byt > 0 )
{
dwTemp -= offsetof(tagSampleData_3746, m_szDriverNo); // 非第一点,去除日期时间
memcpy( v_szBuf + dw, v_objDrvSampleDatas.m_uniSampleDatas.m_arySampleData_3746[byt].m_szDriverNo, dwTemp );
dw += dwTemp;
}
else
{
// 第一个点含日期时间
memcpy( v_szBuf + dw, v_objDrvSampleDatas.m_uniSampleDatas.m_arySampleData_3746 + byt, dwTemp );
dw += dwTemp;
}
#endif
#if USE_DRVRECRPT == 3
// 基础大小
dwTemp = sizeof(tagSampleData_3747);
// 去除多余的载重字段
if( v_objDrvSampleDatas.m_uniSampleDatas.m_arySampleData_3747[byt].m_bytHeightCount
>
sizeof(v_objDrvSampleDatas.m_uniSampleDatas.m_arySampleData_3747[byt].m_aryHeightIO)
/
sizeof(v_objDrvSampleDatas.m_uniSampleDatas.m_arySampleData_3747[byt].m_aryHeightIO[0]) )
{ // 保险起见
memset( (char*)&v_objDrvSampleDatas.m_uniSampleDatas.m_arySampleData_3747[byt].m_bytHeightCount, 1,
sizeof(v_objDrvSampleDatas.m_uniSampleDatas.m_arySampleData_3747[byt].m_bytHeightCount) );
}
dwTemp -= sizeof(v_objDrvSampleDatas.m_uniSampleDatas.m_arySampleData_3747[byt].m_aryHeightIO)
-
v_objDrvSampleDatas.m_uniSampleDatas.m_arySampleData_3747[byt].m_bytHeightCount
* sizeof(v_objDrvSampleDatas.m_uniSampleDatas.m_arySampleData_3747[byt].m_aryHeightIO[0]);
// 存入发送缓存
if( byt > 0 )
{
dwTemp -= offsetof(tagSampleData_3747, m_szDriverNo); // 非第一点,去除日期时间
memcpy( v_szBuf + dw, v_objDrvSampleDatas.m_uniSampleDatas.m_arySampleData_3746[byt].m_szDriverNo, dwTemp );
dw += dwTemp;
}
else
{
// 第一个点含日期时间
memcpy( v_szBuf + dw, v_objDrvSampleDatas.m_uniSampleDatas.m_arySampleData_3746 + byt, dwTemp );
dw += dwTemp;
}
#endif
#if USE_DRVRECRPT == 11
// 基础大小
dwTemp = sizeof(tagSampleData_3745_KJ2);
// 存入发送缓存
if( byt > 0 )
{
dwTemp -= offsetof(tagSampleData_3745_KJ2, m_szDriverNo); // 非第一点,去除日期时间
memcpy( v_szBuf + dw, v_objDrvSampleDatas.m_uniSampleDatas.m_arySampleData_3745_KJ2[byt].m_szDriverNo,
dwTemp );
dw += dwTemp;
}
else
{
// 第一个点含日期时间
memcpy( v_szBuf + dw, v_objDrvSampleDatas.m_uniSampleDatas.m_arySampleData_3745_KJ2 + byt, dwTemp );
dw += dwTemp;
}
#endif
}
v_szBuf[ dw ++ ] = char( v_objDrvSampleDatas.m_bytAvgSpeedCount ); // 平均速度个数
// 平均速度
for( byt = 0; byt < v_objDrvSampleDatas.m_bytAvgSpeedCount; byt ++ )
{
memcpy( v_szBuf + dw, v_objDrvSampleDatas.m_aryAvgSpeed, sizeof(v_objDrvSampleDatas.m_aryAvgSpeed[0]) );
dw += sizeof(v_objDrvSampleDatas.m_aryAvgSpeed[0]);
}
v_dwLen = dw;
return 0;
}
void CDrvRecRpt::_SndDrvrecWin(bool v_bReSnd)
{
static BYTE sta_bytWinId = 0;
int iResult = 0;
char buf[ SOCK_MAXSIZE ];
int iBufLen = 0;
DWORD dwLen = 0;
char* pSndBuf = NULL;
BYTE byt = 0;
if( !v_bReSnd ) // 如果不是重传(即是上传一个新窗口,包括收到3705应答后重新上传部分帧)
{
for( byt = 0; byt < m_bytCurSndDrvRecFrameNum; byt ++ )
{
// 提取一帧
dwLen = m_aryCurSndDrvRecFrameInfo[byt][0];
pSndBuf = (char*)(m_aryCurSndDrvRecFrameInfo[byt][1]);
if( dwLen < 1 || !pSndBuf )
{
PRTMSG(MSG_ERR, "Snd 3745 Win, find a empty frame\n" );
continue;
}
// 发送前将剩余信息填充完毕 (在这里填充,是因为这时窗口内的帧数确定)
if( m_bCurSndNeedAns ) // 若需要可靠传输
{
pSndBuf[0] |= 0x42; // 先: 可靠传输
pSndBuf[0] |= sta_bytWinId ? 0x08 : 0; // 再: 窗口标志ID
if( byt + 1 == m_bytCurSndDrvRecFrameNum ) // 若是窗口最后1帧
{
pSndBuf[0] |= 0x01; // 最后: 末帧要应答
sta_bytWinId = ~sta_bytWinId; // 更换窗口标志
}
pSndBuf[1] = m_bytCurSndDrvRecFrameNum; // 窗口大小
pSndBuf[2] = byt; // 帧序号
}
else
{
pSndBuf[0] |= 0x40;
pSndBuf[1] = 0;
pSndBuf[2] = 0;
}
// 发送该帧
iResult = g_objSms.MakeSmsFrame( pSndBuf, int(dwLen), 0x37, DRVRECFRAME_DATATYPE, buf, sizeof(buf), iBufLen, CVT_8TO7 );
if( !iResult )
{
iResult = g_objSock.SOCKSNDSMSDATA( buf, iBufLen, LV8 );
}
}
// 若需要可靠传输,且至少发送了一帧
if( m_bCurSndNeedAns && byt > 0 )
{
// 打开重传定时器
_KillTimer(&g_objTimerMng, DRVRECWIN_REUPLOAD_TIMER );
_SetTimer(&g_objTimerMng, DRVRECWIN_REUPLOAD_TIMER, DRVRECWIN_REUPLOAD_INTERVAL, G_TmReRptDrvRecWin);
m_dwDrvCurWinFstSndTime = GetTickCount();
m_bDrvCurWinChkGprs = false;
}
else
{
// 发送完毕就清除当前发送的记录数组
_ClearCurSndDrvRecWin();
// 关闭重传定时器,保险起见
_KillTimer(&g_objTimerMng, DRVRECWIN_REUPLOAD_TIMER );
}
}
else // 否则,即是重传
{
if( m_bCurSndNeedAns && m_bytCurSndDrvRecFrameNum > 0 ) // 若需要可靠传输,且当前窗口有缓存帧
{
if( m_bytCurSndDrvRecFrameNum < sizeof(m_aryCurSndDrvRecFrameInfo) / sizeof(m_aryCurSndDrvRecFrameInfo[0])
&& m_bytCurSndDrvRecFrameNum > 0 ) // 保险起见
{
dwLen = m_aryCurSndDrvRecFrameInfo[m_bytCurSndDrvRecFrameNum - 1][0];
pSndBuf = (char*)(m_aryCurSndDrvRecFrameInfo[m_bytCurSndDrvRecFrameNum - 1][1]);
if( dwLen < 1 || !pSndBuf )
{
PRTMSG(MSG_ERR, "Resnd last 3745 of a win, but a empty frame\n" );
return;
}
// 发送该窗口最后1帧
iResult = g_objSms.MakeSmsFrame( pSndBuf, int(dwLen), 0x37, DRVRECFRAME_DATATYPE, buf, sizeof(buf), iBufLen, CVT_8TO7 );
if( !iResult )
{
iResult = g_objSock.SOCKSNDSMSDATA( buf, iBufLen, LV8 );
}
}
// 判断是否要底层检查网络
DWORD dwCur = GetTickCount();
if( !m_bDrvCurWinChkGprs && dwCur - m_dwDrvCurWinFstSndTime >= DRVWINSNDMAXPERIOD_FSTCHKGPRS ) // 若该窗口第一次检查
{
g_objSock.LetComuChkGPRS();
m_dwDrvCurWinFstSndTime = GetTickCount();
m_bDrvCurWinChkGprs = true;
}
else if( m_bDrvCurWinChkGprs && dwCur - m_dwDrvCurWinFstSndTime >= DRVWINSNDMAXPERIOD_CHKGPRS ) // 若该窗口非第一次检查
{
g_objSock.LetComuChkGPRS();
m_dwDrvCurWinFstSndTime = GetTickCount();
}
}
else
{
// 关闭重传定时器,保险起见
_KillTimer(&g_objTimerMng, DRVRECWIN_REUPLOAD_TIMER );
}
}
}
void CDrvRecRpt::DealAccChg( BOOL v_blAccOn )
{
if( !v_blAccOn )
{
char buf[100];
buf[0] = 0x01;
buf[1] = 0x00;
strcat( buf, "ACC断开" );
DataPush(buf, strlen(buf), DEV_QIAN, DEV_DVR, LV2);
}
_BeginDrvRecSample( v_blAccOn );
}
// 设置行驶记录参数
// 千里眼协议(内部模拟协议): 窗口大小(1)+【发送时长(2)+采样周期(2)+发送周期(1)】(ACC ON)+【发送时长(2)+采样周期(2)+发送周期(1)】(ACC OFF)
// KJ2协议: 窗口大小(1)+【采样周期(2)+发送周期(1)】(ACC ON)+【采样周期(2)+发送周期(1)】(ACC OFF)
int CDrvRecRpt::Deal103e(char* v_szSrcHandtel, char *v_szData, DWORD v_dwDataLen )
{
tag2QDriveRecCfg objDrvRecCfg, objDrvRecCfgBkp;
tag103e req;
int iRet = 0;
int iBufLen = 0;
char buf[ SOCK_MAXSIZE ];
BYTE bytResType;
// 参数检查
if( sizeof(tag103e) != v_dwDataLen )
{
iRet = ERR_DATA_INVALID;
goto DEAL103e_FAILED;
}
// 获取原始参数
iRet = GetSecCfg( &objDrvRecCfg, sizeof(objDrvRecCfg),
offsetof(tagSecondCfg, m_uni2QDriveRecCfg.m_obj2QDriveRecCfg), sizeof(objDrvRecCfg) );
if( iRet && ERR_IO != iRet ) goto DEAL103e_FAILED;
else iRet = 0; // 忽略其他错误
objDrvRecCfgBkp = objDrvRecCfg; // 先备份
// 解帧,更新设置
memcpy( &req, v_szData, sizeof(req) );
if( 0x7f == req.m_bytSndWinSize ) req.m_bytSndWinSize = 0;
if( 0x7f == req.m_bytOnSampCycleMin ) req.m_bytOnSampCycleMin = 0;
if( 0x7f == req.m_bytOnSampCycleSec ) req.m_bytOnSampCycleSec = 0;
if( 0x7f == req.m_bytOnSndCycle ) req.m_bytOnSndCycle = 0;
if( 0x7f == req.m_bytOffSampCycleMin ) req.m_bytOffSampCycleMin = 0;
if( 0x7f == req.m_bytOffSampCycleSec ) req.m_bytOffSampCycleSec = 0;
if( 0x7f == req.m_bytOffSndCycle ) req.m_bytOffSndCycle = 0;
objDrvRecCfg.m_bytSndWinSize = req.m_bytSndWinSize;
objDrvRecCfg.m_bytOnSndCycle = req.m_bytOnSndCycle;
objDrvRecCfg.m_bytOffSndCycle = req.m_bytOffSndCycle;
objDrvRecCfg.m_wOnSampCycle = req.m_bytOnSampCycleMin * 60 + req.m_bytOnSampCycleSec;
objDrvRecCfg.m_wOffSampCycle = req.m_bytOffSampCycleMin * 60 + req.m_bytOffSampCycleSec;
#if USE_DRVRECRPT == 1 || USE_DRVRECRPT == 2 || USE_DRVRECRPT == 3 || USE_DRVRECRPT == 4
if( 0x7f == req.m_bytOnSndHour ) req.m_bytOnSndHour = 0;
if( 0x7f == req.m_bytOnSndMin ) req.m_bytOnSndMin = 0;
if( 0x7f == req.m_bytOffSndHour ) req.m_bytOffSndHour = 0;
if( 0x7f == req.m_bytOffSndMin ) req.m_bytOffSndMin = 0;
objDrvRecCfg.m_wOnPeriod = WORD(req.m_bytOnSndHour) * 60 + req.m_bytOnSndMin;
objDrvRecCfg.m_wOffPeriod = WORD(req.m_bytOffSndHour) * 60 + req.m_bytOffSndMin;
if( 0 == objDrvRecCfg.m_wOnPeriod ) objDrvRecCfg.m_wOnPeriod = 0xffff; // 表示永久上报
if( 0 == objDrvRecCfg.m_wOffPeriod ) objDrvRecCfg.m_wOffPeriod = 0xffff;
#endif
#if USE_DRVRECRPT == 11
objDrvRecCfg.m_wOffPeriod = objDrvRecCfg.m_wOnPeriod = 0xffff; // 表示永久上报
#endif
if( objDrvRecCfg.m_bytSndWinSize > 32
|| objDrvRecCfg.m_bytSndWinSize > sizeof(m_aryCurSndDrvRecFrameInfo) / sizeof(m_aryCurSndDrvRecFrameInfo[0]) )
// 若发送窗口超过协议定义或缓存的最大范围
{
iRet = ERR_DATA_INVALID;
goto DEAL103e_FAILED;
}
// 组帧
bytResType = 0x01;
iRet = g_objSms.MakeSmsFrame( (char*)&bytResType, 1, 0x10, 0x7e, buf, sizeof(buf), iBufLen);
if( !iRet )
{
// 保存新设置
iRet = SetSecCfg( &objDrvRecCfg, offsetof(tagSecondCfg, m_uni2QDriveRecCfg.m_obj2QDriveRecCfg), sizeof(objDrvRecCfg) );
if( iRet ) goto DEAL103e_FAILED;
// 发送应答
iRet = g_objSock.SOCKSNDSMSDATA( buf, iBufLen, LV12, 0 );
if( !iRet )
{
// 使用新的设置处理行驶记录
_BeginDrvRecSample( (BOOL)(g_objQianIO.GetDeviceSta() & DEVSTA_ACCVALID) );
}
else
{
// 恢复原设置
SetSecCfg( &objDrvRecCfgBkp, offsetof(tagSecondCfg, m_uni2QDriveRecCfg.m_obj2QDriveRecCfg), sizeof(objDrvRecCfgBkp) );
goto DEAL103e_FAILED;
}
}
else goto DEAL103e_FAILED;
return 0;
DEAL103e_FAILED:
bytResType = 0x7f;
int iRet2 = g_objSms.MakeSmsFrame( (char*)&bytResType, 1, 0x10, 0x7e, buf, sizeof(buf), iBufLen);
if( !iRet2 ) g_objSock.SOCKSNDSMSDATA( buf, iBufLen, LV12, 0 );
return iRet;
}
// 行驶数据上传应答: 应答类型(1)+帧序号掩码(4)
int CDrvRecRpt::Deal3705(char* v_szSrcHandtel, char *v_szData, DWORD v_dwDataLen )
{
BYTE byt = 0;
if( v_dwDataLen < 1 ) return ERR_PAR;
if( 1 == v_szData[0] ) // 若是成功应答
{
// 先清除旧窗口数据
_ClearCurSndDrvRecWin();
// 再继续上传
DrvRecToSnd(0);
return 0;
}
else if( 0 == v_szData[0] ) // 若是需要重传应答
{
if( v_dwDataLen < 5 ) return ERR_PAR;
// 获取重传帧序号掩码
DWORD dwRcvCode = 0;
memcpy( &dwRcvCode, v_szData + 1, sizeof(dwRcvCode) );
dwRcvCode = ntohl( dwRcvCode );
// 寻找需要的最后一帧编号
DWORD dwSymb = 1;
BYTE bytLstFrameNo = 0xff;
for( byt = 0; byt < sizeof(m_aryCurSndDrvRecFrameInfo) / sizeof(m_aryCurSndDrvRecFrameInfo[0])
&& byt < m_bytCurSndDrvRecFrameNum; byt ++ )
{
if( dwSymb & dwRcvCode ) // 若该序号的帧未成功接收
bytLstFrameNo = byt;
dwSymb = dwSymb << 1;
}
if( bytLstFrameNo >= m_bytCurSndDrvRecFrameNum ) return ERR_PAR;
// 重传处理
char buf[ SOCK_MAXSIZE ];
int iBufLen = 0;
int iResult = 0;
DWORD dwLen = 0;
char* pSndBuf = NULL;
char cTemp = 0;
dwSymb = 1;
for( byt = 0; byt < sizeof(m_aryCurSndDrvRecFrameInfo) / sizeof(m_aryCurSndDrvRecFrameInfo[0])
&& byt < m_bytCurSndDrvRecFrameNum; byt ++ )
{
if( dwSymb & dwRcvCode ) // 若该序号的帧未成功接收
{
dwLen = m_aryCurSndDrvRecFrameInfo[byt][0];
pSndBuf = (char*)(m_aryCurSndDrvRecFrameInfo[byt][1]);
if( dwLen < 1 || !pSndBuf )
{
PRTMSG(MSG_ERR, "Deal3705,resend 3745 frame,find an empty frame\n" );
continue;
}
// 如果是最后一帧,发送前第一个字节的应答标志位修改为要应答
if( bytLstFrameNo == byt )
{
cTemp = pSndBuf[0];
pSndBuf[0] |= 1;
}
iResult = g_objSms.MakeSmsFrame( pSndBuf, int(dwLen), 0x37, DRVRECFRAME_DATATYPE,
buf, sizeof(buf), iBufLen, CVT_8TO7 );
if( !iResult ) iResult = g_objSock.SOCKSNDSMSDATA( buf, iBufLen, LV8 );
// 如果是最后一帧,发送完后第一个字节要恢复为原值
if( bytLstFrameNo == byt )
{
pSndBuf[0] = cTemp;
}
}
dwSymb = dwSymb << 1;
}
return iResult;
}
else
return ERR_PAR;
}
#endif //#if USE_DRVRECRPT == 1 || USE_DRVRECRPT == 2 || USE_DRVRECRPT == 3 || USE_DRVRECRPT == 4 || USE_DRVRECRPT == 11
| [
"[email protected]"
]
| [
[
[
1,
1435
]
]
]
|
69f04cbda17bd29448e930777bd9d7b0f3be0b97 | ef23e388061a637f82b815d32f7af8cb60c5bb1f | /src/mame/includes/gsword.h | 44a70ba2dde2fb211b27164a14486110b37f0733 | []
| no_license | marcellodash/psmame | 76fd877a210d50d34f23e50d338e65a17deff066 | 09f52313bd3b06311b910ed67a0e7c70c2dd2535 | refs/heads/master | 2021-05-29T23:57:23.333706 | 2011-06-23T20:11:22 | 2011-06-23T20:11:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 831 | h | class gsword_state : public driver_device
{
public:
gsword_state(running_machine &machine, const driver_device_config_base &config)
: driver_device(machine, config) { }
UINT8 *m_videoram;
int m_coins;
int m_fake8910_0;
int m_fake8910_1;
int m_nmi_enable;
UINT8 *m_cpu2_ram;
int m_protect_hack;
size_t m_spritexy_size;
UINT8 *m_spritexy_ram;
UINT8 *m_spritetile_ram;
UINT8 *m_spriteattrib_ram;
int m_charbank;
int m_charpalbank;
int m_flipscreen;
tilemap_t *m_bg_tilemap;
};
/*----------- defined in video/gsword.c -----------*/
WRITE8_HANDLER( gsword_charbank_w );
WRITE8_HANDLER( gsword_videoctrl_w );
WRITE8_HANDLER( gsword_videoram_w );
WRITE8_HANDLER( gsword_scroll_w );
PALETTE_INIT( josvolly );
PALETTE_INIT( gsword );
VIDEO_START( gsword );
SCREEN_UPDATE( gsword );
| [
"Mike@localhost"
]
| [
[
[
1,
35
]
]
]
|
6748682f5684e98f1396a52f85a0d567d7415f66 | 63c17f092bf95bc9daaf92ee05f6a823623f2f9b | /src/PlugInSDK/Template.cpp | c0ff4a499c5c360017e1fd7c2c868c18ce49fd38 | []
| no_license | sodiumda250/bkhdpnl | ba9d36b9b77d23c6cac004ce3c4818d19564eed4 | 52e628f3bc70f38bea4c6287778c3a3d765f37bf | refs/heads/master | 2020-03-31T11:59:52.220401 | 2009-10-20T05:50:43 | 2009-10-20T05:50:43 | 3,039,672 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,794 | cpp | ////////////////////////////////////////////////////////////////////////////////////
// Template file for plugin.
//
// You can modify and redistribute this file without any permission.
//
// Note:
// Create a sub folder under "PlugInSDK" folder. e.g. "PlugInSDK\MyProject\" and
// place your project files there.
#include <windows.h>
#include "../BeckyAPI.h"
#include "../BkCommon.h"
CBeckyAPI bka; // You can have only one instance in a project.
HINSTANCE g_hInstance = NULL;
char szIni[_MAX_PATH+2]; // Ini file to save your plugin settings.
/////////////////////////////////////////////////////////////////////////////
// DLL entry point
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
g_hInstance = (HINSTANCE)hModule;
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
{
if (!bka.InitAPI()) {
return FALSE;
}
GetModuleFileName((HINSTANCE)hModule, szIni, _MAX_PATH);
LPSTR lpExt = strrchr(szIni, '.');
if (lpExt) {
strcpy(lpExt, ".ini");
} else {
// just in case
strcat(szIni, ".ini");
}
}
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////////////////////
// Callbacks from Becky!
#ifdef __cplusplus
extern "C"{
#endif
////////////////////////////////////////////////////////////////////////
// Called when the program is started and the main window is created.
int WINAPI BKC_OnStart()
{
/*
Since BKC_OnStart is called after Becky!'s main window is
created, at least BKC_OnMenuInit with BKC_MENU_MAIN is called
before BKC_OnStart. So, do not assume BKC_OnStart is called
prior to any other callback.
*/
// Always return 0.
return 0;
}
////////////////////////////////////////////////////////////////////////
// Called when the main window is closing.
int WINAPI BKC_OnExit()
{
// Return -1 if you don't want to quit.
return 0;
}
////////////////////////////////////////////////////////////////////////
// Called when menu is intialized.
int WINAPI BKC_OnMenuInit(HWND hWnd, HMENU hMenu, int nType)
{
switch (nType) {
case BKC_MENU_MAIN:
{
/* Sample of adding menu items
HMENU hSubMenu = GetSubMenu(hMenu, 4);
// Define CmdProc as "void WINAPI CmdProc(HWND, LPARAM)"
UINT nID = bka.RegisterCommand("Information about this Command", nType,CmdProc);
AppendMenu(hSubMenu, MF_STRING, nID, "&Menu item");
*/
/* If needed, you can register the command UI update callback.
// Define CmdUIProc as "UINT WINAPI CmdUIProc(HWND, LPARAM)"
bka.RegisterUICallback(nID, CmdUIProc);
*/
}
break;
case BKC_MENU_LISTVIEW:
break;
case BKC_MENU_TREEVIEW:
break;
case BKC_MENU_MSGVIEW:
break;
case BKC_MENU_MSGEDIT:
break;
case BKC_MENU_TASKTRAY:
break;
case BKC_MENU_COMPOSE:
break;
case BKC_MENU_COMPEDIT:
break;
case BKC_MENU_COMPREF:
break;
default:
break;
}
// Always return 0.
return 0;
}
////////////////////////////////////////////////////////////////////////
// Called when a folder is opened.
int WINAPI BKC_OnOpenFolder(LPCTSTR lpFolderID)
{
// Always return 0.
return 0;
}
////////////////////////////////////////////////////////////////////////
// Called when a mail is selected.
int WINAPI BKC_OnOpenMail(LPCTSTR lpMailID)
{
// Always return 0.
return 0;
}
////////////////////////////////////////////////////////////////////////
// Called every minute.
int WINAPI BKC_OnEveryMinute()
{
// Always return 0.
return 0;
}
////////////////////////////////////////////////////////////////////////
// Called when a compose windows is opened.
int WINAPI BKC_OnOpenCompose(HWND hWnd, int nMode/* See COMPOSE_MODE_* in BeckyApi.h */)
{
// Always return 0.
return 0;
}
////////////////////////////////////////////////////////////////////////
// Called when the composing message is saved.
int WINAPI BKC_OnOutgoing(HWND hWnd, int nMode/* 0:SaveToOutbox, 1:SaveToDraft, 2:SaveToReminder*/)
{
// Return -1 if you do not want to send it yet.
return 0;
}
////////////////////////////////////////////////////////////////////////
// Called when a key is pressed.
int WINAPI BKC_OnKeyDispatch(HWND hWnd, int nKey/* virtual key code */, int nShift/* Shift state. 0x40=Shift, 0x20=Ctrl, 0x60=Shift+Ctrl, 0xfe=Alt*/)
{
// Return TRUE if you want to suppress subsequent command associated to this key.
return 0;
}
////////////////////////////////////////////////////////////////////////
// Called when a message is retrieved and saved to a folder
int WINAPI BKC_OnRetrieve(LPCTSTR lpMessage/* Message source*/, LPCTSTR lpMailID/* Mail ID*/)
{
// Always return 0.
return 0;
}
////////////////////////////////////////////////////////////////////////
// Called when a message is spooled
int WINAPI BKC_OnSend(LPCTSTR lpMessage/* Message source */)
{
// Return BKC_ONSEND_PROCESSED, if you have processed this message
// and don't need Becky! to send it.
// Becky! will move this message to Sent box when the sending
// operation is done.
// CAUTION: You are responsible for the destination of this
// message if you return BKC_ONSEND_PROCESSED.
// Return BKC_ONSEND_ERROR, if you want to cancel the sending operation.
// You are responsible for displaying an error message.
// Return 0 to proceed the sending operation.
return 0;
}
////////////////////////////////////////////////////////////////////////
// Called when all messages are retrieved
int WINAPI BKC_OnFinishRetrieve(int nNumber/* Number of messages*/)
{
// Always return 0.
return 0;
}
////////////////////////////////////////////////////////////////////////
// Called when plug-in setup is needed.
int WINAPI BKC_OnPlugInSetup(HWND hWnd)
{
// Return nonzero if you have processed.
// return 1;
return 0;
}
////////////////////////////////////////////////////////////////////////
// Called when plug-in information is being retrieved.
typedef struct tagBKPLUGININFO
{
char szPlugInName[80]; // Name of the plug-in
char szVendor[80]; // Name of the vendor
char szVersion[80]; // Version string
char szDescription[256]; // Short description about this plugin
} BKPLUGININFO, *LPBKPLUGININFO;
int WINAPI BKC_OnPlugInInfo(LPBKPLUGININFO lpPlugInInfo)
{
/* You MUST specify at least szPlugInName and szVendor.
otherwise Becky! will silently ignore your plug-in.
strcpy(lpPlugInInfo->szPlugInName, "Becky! PGP plug-in");
strcpy(lpPlugInInfo->szVendor, "RimArts, Inc.");
strcpy(lpPlugInInfo->szVersion, "1.0");
strcpy(lpPlugInInfo->szDescription, "Enables Becky! to use PGP.");
*/
// Always return 0.
return 0;
}
////////////////////////////////////////////////////////////////////////
// Called when drag and drop operation occurs.
int WINAPI BKC_OnDragDrop(LPCSTR lpTgt, LPCSTR lpSrc, int nCount, int dropEffect)
{
/*
lpTgt: A folder ID of the target folder.
You can assume it is a root mailbox, if the string
contains only one '\' character.
lpSrc: Either a folder ID or mail IDs. Multiple mail IDs are
separated by '\n' (0x0a).
You can assume it is a folder ID, if the string
doesn't contain '?' character.
nCount: Number of items to be dropped.
It can be more than one, if you drop mail items.
dropEffect: Type of drag and drop operation
1: Copy
2: Move
4: Link (Used for filtering setup in Becky!)
*/
// If you want to cancel the default drag and drop action,
// return -1;
// Do not assume the default action (copy, move, etc.) is always
// processed, because other plug-ins might cancel the operation.
return 0;
}
////////////////////////////////////////////////////////////////////////
// Called when a message was retrieved and about to be filtered.
int WINAPI BKC_OnBeforeFilter(LPCSTR lpMessage, int* lpnAction, char** lppParam)
{
/*
lpMessage: A complete message source, which ends with
"<CRLF>.<CRLF>".
lpnAction: [out] Returns the filtering action to be applied.
#define ACTION_NOTHING -1 // Do nothing
#define ACTION_MOVEFOLDER 0 // Move to a folder
#define ACTION_COLORLABEL 1 // Set the color label
#define ACTION_SETFLAG 2 // Set the flag
#define ACTION_SOUND 3 // Make a sound
#define ACTION_RUNEXE 4 // Run executable file
#define ACTION_REPLY 5 // Reply to the message
#define ACTION_FORWARD 6 // Forward the message
#define ACTION_LEAVESERVER 7 // Leave/delete on the server.
#define ACTION_ADDHEADER 8 // Add "X-" header to the top of the message. (Plug-in only feature)
lppParam: [out] Returns the pointer to the filtering parameter string.
ACTION_MOVEFOLDER: Folder name.
e.g. XXXXXXXX.mb\FolderName\
or \FolderName\ (begin with '\') to use
the mailbox the message belongs.
ACTION_COLORLABEL: Color code(BGR) in hexadecimal. e.g. 0088FF
ACTION_SETFLAG: "F" to set flag. "R" to set read.
ACTION_SOUND: Name of the sound file.
ACTION_RUNEXE: Command line to execute. %1 will be replaced with the path to the file that contains the entire message.
ACTION_REPLY: Path to the template file without extension.
e.g. #Reply\MyReply
ACTION_FORWARD: Path to the template file without extension. + "*" + Address to forward.
e.g. #Forward\MyForward*mail@address
*mail@address (no template)
ACTION_LEAVESERVER: The string consists of one or two decimals. The second decimal is optional.
Two decimals must be separated with a space.
First decimal 1: Delete the message from the server.
0: Leave the message on the server.
Second decimal 1: Do not store the message to the folder.
0: Store the message to the folder. (default action)
e.g. 0 (Leave the message on the server.)
1 1 (Delete the message on the server and do not save. (Means KILL))
ACTION_ADDHEADER "X-Header:data" that will be added at the top of the incoming message.
You can specify multiple headers by separating CRLF, but each header must
begin with "X-". e.g. "X-Plugindata1: test\r\nX-Plugindata2: test2";
*/
/* Return values
BKC_FILTER_DEFAULT Do nothing and apply default filtering rules.
BKC_FILTER_PASS Apply default filtering rules after applying the rule it returns.
BKC_FILTER_DONE Do not apply default rules.
BKC_FILTER_NEXT Request Becky! to call this callback again so that another rules can be added.
*/
return BKC_FILTER_DEFAULT;
}
#ifdef __cplusplus
}
#endif
| [
"woods@e212b10a-3bbd-de11-b494-001ec944baf4"
]
| [
[
[
1,
325
]
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.